Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
230 changes: 140 additions & 90 deletions darknode.js

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions docs/NEXUS-COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ File tools are confined to the project folder; secrets are blocked from being wr
- `/next` — queue a prompt after the current turn (Ctrl+X / Ctrl+S runs it now; clear / rm <n> to manage)
- `/btw` — side question — answered from context, never saved to history
- `/find` — search the whole conversation, tool output included: /find <text> (n/N step through matches, q closes)
- `/pager` — read the newest tool output in full: /pager [n] | answer (j/k, space, g/G, / search, q)
- `/pager` — read the last reply in full, or a tool output: /pager [n] (j/k, space, g/G, / search, q)
- `/compat` — which features this model supports (nothing is hidden) (opens in the side panel)
- `/mode` — capability preset: /mode power|cost|speed|reset (model-compatible only)
- `/god-prompt` — arm max-quality mode for your NEXT message only (gold border, auto-reverts)
Expand Down Expand Up @@ -308,7 +308,7 @@ File tools are confined to the project folder; secrets are blocked from being wr
### Scroll, select & copy

- `Mouse wheel` — scroll the transcript
- `Up / Down (empty input)` — scroll line by line
- `Up / Down (empty input)` — recall earlier prompts (the wheel scrolls)
- `PgUp / PgDn` — scroll a page
- `Home` — jump to the oldest
- `End` — jump to the latest
Expand Down Expand Up @@ -341,7 +341,7 @@ the cloud. Launch it with `darknode nexus --tui`. Type / inside for the command

Free local setup:
curl -fsSL https://ollama.com/install.sh | sh
ollama pull gpt-oss:20b # fast local agent (~14GB); pull gpt-oss:120b for max power (~63GB)
ollama pull qwen2.5-coder # fast local agent (~14GB); pull gpt-oss:120b for max power (~63GB)
```

### Engines & models (`/docs engines`)
Expand Down
3 changes: 2 additions & 1 deletion lib/cli/command-help.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const HELP = {
"/connect": { u: "", ex: ["/connect"], see: ["/engine", "/model", "/api"] },
"/alias": { u: "<name> = <text|/command> | rm <name>", a: [["name = …", "what it expands to — plain text or another /command"], ["rm <name>", "delete an alias (bare /alias lists them)"]], ex: ["/alias ship = /commit", "/alias rv = review this diff for security", "/alias rm ship"] },
"/retry": { u: "", ex: ["/retry"] },
"/settings": { u: "[<key> on|off | budget <usd>|off]", a: [["<key>", "a row under Limits in /settings, or recap"], ["budget <usd>|off", "session spend cap"]], ex: ["/settings", "/settings lean on", "/settings budget 5"], see: ["/budget"] },
"/budget": { u: "<usd>|off", a: [["<usd>", "stop warning past this session spend"], ["off", "remove the cap"]], ex: ["/budget 5", "/budget off"], see: ["/cost", "/savings"] },
"/report": { u: "[json|save|since <date>]", a: [["json", "machine-readable output"], ["save", "write it to a file"], ["since <date>", "only usage on/after YYYY-MM-DD"]], ex: ["/report", "/report json", "/report since 2026-10-01"], see: ["/cost", "/compliance"] },
"/compliance": { u: "[verify <bundle.json>]", a: [["verify <file>", "check a bundle's signature + hash chain"]], ex: ["/compliance", "/compliance verify audit.json"], see: ["/audit", "/report"] },
Expand Down Expand Up @@ -93,7 +94,7 @@ const HELP = {
"/autoupdate": { u: "on|check|off", ex: ["/autoupdate on", "/autoupdate off"] },
"/next": { u: "<prompt> | clear | rm <n>", ex: ["/next run the tests", "/next clear"], see: ["/loop"] },
"/find": { u: "<text>", a: [["n/N", "step through matches"], ["q", "close"]], ex: ["/find TODO", "/find race condition"], see: ["/pager", "/index"] },
"/pager": { u: "[n]", a: [["n", "which recent tool output; omit for the newest"]], ex: ["/pager", "/pager 2"], see: ["/find", "/expand"] },
"/pager": { u: "[n | answer]", a: [["n", "the n-th newest tool output (1 = newest)"], ["answer", "the last reply (also what bare /pager opens)"]], ex: ["/pager", "/pager 1", "/pager 2"], see: ["/find", "/expand"] },
"/mode": { u: "power|cost|speed|reset", ex: ["/mode power", "/mode reset"], see: ["/effort", "/model"] },
"/autocompact": { u: "auto|off|<amount>", ex: ["/autocompact auto", "/autocompact off", "/autocompact 80%"], see: ["/compact", "/recap"] },
"/recap": { u: "[on|off]", a: [["(no arg)", "recap now"], ["on|off", "toggle the after-task recap"]], ex: ["/recap", "/recap off"] },
Expand Down
13 changes: 11 additions & 2 deletions lib/cli/md-render.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
//
// C supplies the painters, so colour stays the caller's decision (NO_COLOR, themes):
// { inline(line), gray, dim, mag, green, yellow, cyan, red, bold, italic, underline }
// `inline` paints one prose row (headings, bold, inline code, bullets).
// `inline` paints one source line (headings, bold, inline code, list markers) before it is
// wrapped, so bold that crosses a row boundary is painted on both rows.
//
// Handles: fenced code (language-aware highlighting, gutter, label), ```diff,
// pipe tables (aligned; stacked records when too wide), block quotes, rules and
Expand All @@ -16,6 +17,7 @@ const { ansiWrap, strWidth, sanitizeTerm } = require("./tui-format");
const { trimUrl } = require("./links");

const id = (s) => s;
const LIST_RE = /^\s*(?:[-*+]|\d{1,3}[.)])\s+(?=\S)/; // "- x", "* x", "1. x", "2) x" (indent kept)
const stripSgr = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, "");

// ---- syntax highlighting ----------------------------------------------------
Expand Down Expand Up @@ -172,7 +174,14 @@ function renderMd(text, width, C) {
width = Math.max(10, width | 0);
const src = String(text == null ? "" : text).replace(/\r\n?/g, "\n").split("\n");
const out = [];
const prose = (l) => { for (const w of ansiWrap(italicize(linkify(l, C), C), width)) out.push(C.inline(w)); };
// Paint first, then wrap (ansiWrap carries the colour onto the next row). A list item's
// marker is painted alone and its wrapped rows hang under the text, not under the marker.
const prose = (l) => {
const lm = LIST_RE.exec(l);
if (!lm) { for (const w of ansiWrap(C.inline(italicize(linkify(l, C), C)), width)) out.push(w); return; }
const mark = C.inline(lm[0]), hang = strWidth(mark);
ansiWrap(C.inline(italicize(linkify(l.slice(lm[0].length), C), C)), Math.max(4, width - hang)).forEach((w, k) => out.push((k ? " ".repeat(hang) : mark) + w));
};
let fence = null; // { mark, lang, st, diff }
for (let i = 0; i < src.length; i++) {
const line = src[i];
Expand Down
26 changes: 25 additions & 1 deletion lib/cli/tui-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,31 @@ function toolResultView(name, input, content, opts) {
if (N === "WebSearch") return { lines: [{ k: "text", text: "Did 1 search" + (o.secs ? " in " + o.secs : "") }], more: 0 };
if (N === "Task") { const v = o.expanded ? clipOut(all.filter((l) => l.trim()), "out") : { lines: [], more: 0 }; v.lines.unshift({ k: "text", text: "Done" }); return v; }
if (obj && obj.ok === true && Object.keys(obj).length === 1) return { lines: [{ k: "text", text: "Done" }], more: 0 };
if (obj && obj.skipped === true) return { lines: [{ k: "text", text: "Dismissed without an answer" }], more: 0 }; // ask_user: the note inside is for the model
return clipOut(all.filter((l) => l.trim()), "out");
}

module.exports = { asText, sanitizeTerm, charWidth, strWidth, cutIdx, toolResultView, ccName, stripAnsi, visLen, fitWidth, ansiWrap, padRight, shortenPath, bootHeader, welcomeCard, idleHome, logoMark, MARK_ORBIT, orbitGlyph, activityLabel, footerLine, helpLines, modelLabel, effortLabel, explainEngineError };
// Wrap a two-column help screen (` command description`) to `width`: a row
// that doesn't fit wraps its description under the description column (a
// hanging indent), so nothing hard-wraps mid-word into column 0. A row with no
// second column wraps under its own indent + 2. ANSI-aware; rows that fit are
// returned untouched.
function wrapHelp(text, width) {
width = Math.max(30, width | 0);
const rawAt = (line, col) => { let v = 0, i = 0; while (i < line.length && v < col) { const m = /^\x1b\[[0-9;]*m/.exec(line.slice(i)); if (m) { i += m[0].length; continue; } const ch = String.fromCodePoint(line.codePointAt(i)); v += charWidth(ch); i += ch.length; } while (i < line.length) { const m = /^\x1b\[[0-9;]*m/.exec(line.slice(i)); if (!m) break; i += m[0].length; } return i; };
return String(text).split("\n").map((line) => {
const vis = stripAnsi(line);
if (strWidth(vis) <= width) return line;
const m = /^(\s*\S.*?\S)(\s{2,})(?=\S)/.exec(vis);
let col = m ? strWidth(m[1]) + m[2].length : -1;
if (col < 0 || col > width - 16) col = -1;
const ind = col >= 0 ? col : Math.min(vis.match(/^\s*/)[0].length + 2, Math.floor(width / 2));
const head = col >= 0 ? line.slice(0, rawAt(line, col)) : "";
const body = col >= 0 ? line.slice(rawAt(line, col)) : line.slice(rawAt(line, vis.match(/^\s*/)[0].length));
const lead = col >= 0 ? head : " ".repeat(vis.match(/^\s*/)[0].length);
const rows = ansiWrap(body, width - ind);
return rows.map((r, k) => (k ? " ".repeat(ind) : lead) + r).join("\n");
}).join("\n");
}

module.exports = { wrapHelp, asText, sanitizeTerm, charWidth, strWidth, cutIdx, toolResultView, ccName, stripAnsi, visLen, fitWidth, ansiWrap, padRight, shortenPath, bootHeader, welcomeCard, idleHome, logoMark, MARK_ORBIT, orbitGlyph, activityLabel, footerLine, helpLines, modelLabel, effortLabel, explainEngineError };
2 changes: 1 addition & 1 deletion lib/governance/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ function policyCheck(policy, action) {
function auditLog(cwd, entry) {
try {
const fs = require("fs"), path = require("path"), crypto = require("crypto");
fs.mkdirSync(path.join(cwd, ".nexus"), { recursive: true });
require("../nexus/nexus-dir").ensureNexusDir(cwd);
const file = path.join(cwd, ".nexus", "audit.jsonl");
let prevHash = "0".repeat(64), seq = 0;
try { const lines = fs.readFileSync(file, "utf8").trim().split("\n").filter(Boolean); if (lines.length) { const last = JSON.parse(lines[lines.length - 1]); prevHash = last.hash || prevHash; seq = (last.seq || 0) + 1; } } catch (_) {}
Expand Down
3 changes: 1 addition & 2 deletions lib/governance/usage.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ const TOK = (n) => { n = n || 0; return n >= 1e6 ? (n / 1e6).toFixed(2) + "M" :
// appendUsage(cwd, record) — append one JSON line. Best-effort; never throws.
function appendUsage(cwd, rec) {
try {
const dir = path.join(cwd, ".nexus");
fs.mkdirSync(dir, { recursive: true });
const dir = require("../nexus/nexus-dir").ensureNexusDir(cwd);
fs.appendFileSync(path.join(dir, "usage.jsonl"), JSON.stringify(rec) + "\n");
return true;
} catch (_) { return false; }
Expand Down
2 changes: 1 addition & 1 deletion lib/nexus/bisect.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ function persistCheckpoint(cwd, ck, deps) {
if (!ck || !ck.tree || !Array.isArray(ck.paths) || !ck.paths.length) return false; // only bisectable (path-scoped) checkpoints
try {
const dir = path.join(cwd, ".nexus");
fs.mkdirSync(dir, { recursive: true });
if (deps.fs) fs.mkdirSync(dir, { recursive: true }); else require("./nexus-dir").ensureNexusDir(cwd);
const file = path.join(dir, "checkpoints.jsonl");
const rec = { tree: ck.tree, label: String(ck.label || ""), ts: ck.ts || Date.now(), paths: ck.paths };
fs.appendFileSync(file, JSON.stringify(rec) + "\n");
Expand Down
2 changes: 1 addition & 1 deletion lib/nexus/code-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function loadIndex(cwd) {
function buildAndSave(cwd) {
const list = collectFiles(cwd);
const index = Object.assign(bm25.buildIndex(list), { files: list.length, capped: !!list.capped, ts: Date.now() });
try { fs.mkdirSync(path.join(cwd, ".nexus"), { recursive: true }); fs.writeFileSync(indexPath(cwd), JSON.stringify(index)); } catch (_) {}
try { require("./nexus-dir").ensureNexusDir(cwd); fs.writeFileSync(indexPath(cwd), JSON.stringify(index)); } catch (_) {}
return index;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/nexus/costsave.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function cacheGet(cwd, key, ttlMs) {
try { const f = path.join(cacheDir(cwd), key + ".json"); const st = fs.statSync(f); if (ttlMs && Date.now() - st.mtimeMs > ttlMs) return null; return JSON.parse(fs.readFileSync(f, "utf8")); } catch (_) { return null; }
}
function cachePut(cwd, key, rec) {
try { const d = cacheDir(cwd); fs.mkdirSync(d, { recursive: true }); fs.writeFileSync(path.join(d, key + ".json"), JSON.stringify(rec)); return true; } catch (_) { return false; }
try { const d = require("./nexus-dir").ensureNexusDir(cwd, "cache"); fs.writeFileSync(path.join(d, key + ".json"), JSON.stringify(rec)); return true; } catch (_) { return false; }
}
function cacheClear(cwd) { try { fs.rmSync(cacheDir(cwd), { recursive: true, force: true }); return true; } catch (_) { return false; } }
function cacheStats(cwd) {
Expand Down
2 changes: 1 addition & 1 deletion lib/nexus/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ V.terminal=function(){var rs=D.terminal.filter(match);
return bar()+(rs.length?'<div class="term">'+rs.map(function(r){return'<div class="cmd"><span class="pr">$</span> '+esc(r.command)+'<span class="by">'+(r.by==="you"?"you, with !":"agent")+(r.status&&r.status!=="done"?" · "+r.status:"")+(r.end&&r.start?" · "+dur(r.end-r.start):"")+'</span></div>'+(showOut?'<div class="out">'+esc(r.output||(r.status==="running"?"(running)":"(no output)"))+'</div>':"")}).join("")+'</div>':'<div class="empty">'+(q?"Nothing matches.":"No shell commands yet.")+'</div>')};
V.files=function(){var f=D.files,rows=f.files.filter(function(x){return!q||x.path.toLowerCase().indexOf(q)>=0});var diffs="";
if(selFile){D.conversation.forEach(function(m){(m.items||[]).forEach(function(i){if(i.type==="tool"&&i.file===selFile&&i.diff)diffs+='<div class="sub">'+esc(i.label)+' · '+clock(i.start)+'</div>'+diffHTML(i.diff)})})}
return'<div class="tools"><input type="search" id="q" placeholder="Filter files" value="'+esc(q)+'"><span>'+f.files.length+' files touched · click one to see its changes</span></div>'
return'<div class="tools"><input type="search" id="q" placeholder="Filter files" value="'+esc(q)+'"><span>'+f.files.length+' file'+(f.files.length===1?'':'s')+' touched · click one to see its changes</span></div>'
+'<div class="grid2"><div class="card"><h3>Files</h3>'+(rows.length?'<table><thead><tr><th>Path</th><th class="num">Reads</th><th class="num">Edits</th><th class="num">Last</th></tr></thead><tbody>'+rows.map(function(x){return'<tr class="pick'+(x.path===selFile?" sel":"")+'" data-f="'+esc(x.path)+'"><td class="mono">'+esc(x.path)+'</td><td class="num">'+x.read+'</td><td class="num">'+x.edit+'</td><td class="num">'+clock(x.last)+'</td></tr>'}).join("")+'</tbody></table>':'<div class="b empty">No files read or changed yet.</div>')+'</div>'
+'<div><div class="card"><h3>'+(selFile?esc(selFile):"Changes")+'</h3><div class="b">'+(selFile?(diffs||'<div class="empty">Read only: no edits to this file.</div>'):'<div class="empty">Pick a file.</div>')+'</div></div>'
+'<div class="card"><h3>Searches</h3><div class="b">'+(f.searches.length?f.searches.slice().reverse().map(function(s){return'<div class="ev"><span class="lb">'+esc(s.label)+'</span><span class="st '+s.status+'">'+s.status+'</span></div>'}).join(""):'<div class="empty">None.</div>')+'</div></div>'
Expand Down
29 changes: 28 additions & 1 deletion lib/nexus/local-loop.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
// compactTail(msgs, keep) -> the last `keep` messages after the system message,
// starting at a user message when there is one, else
// at the model's own step: never an orphaned tool result
// wantsToolWork(text) -> true when the request clearly asks for work on the
// project (a file/path, or a verb aimed at code, files,
// the repo or the shell) and doesn't rule tools out
// forbidsTools(text) -> the user said not to use tools
// sameText(a, b) -> b already says a (whitespace/case-insensitive), so a
// final step's `thought` needn't be shown above it

// A plain .slice() of the JSON cut the tail off silently: read_file caps a file at
// 10,000 chars, but JSON escaping (\n, \", \\) can push the observation past the
Expand Down Expand Up @@ -40,4 +46,25 @@ function compactTail(msgs, keep) {
return i < 0 ? [] : tail.slice(i);
}

module.exports = { capObservation, compactTail };
// The "look before you answer" reminder for a local model that answers a project question
// from memory. A plain question ("explain closures", "write a haiku", "what is 2+2") must
// never be pushed into tool calls: the model then invents one (a pointless grep, or an
// edit) just to satisfy the reminder. So it fires only for clear project work.
const NO_TOOLS = /\b(?:no|without(?:\s+using)?|don'?t\s+(?:use|call|run)|do\s+not\s+(?:use|call|run)|never\s+(?:use|call)|avoid(?:\s+using)?)\s+(?:any\s+)?tools?\b|\bno\s+tool\s+(?:calls?|use)\b/i;
function forbidsTools(text) { return NO_TOOLS.test(String(text || "")); }
const FILE_REF = /(?:^|[\s"'`(@])(?:\.{0,2}\/)?[\w.-]+\/[\w./-]+|\b[\w-]+\.(?:m?js|cjs|tsx?|jsx|py|go|rs|rb|java|kt|c|h|cc|cpp|hpp|cs|php|sh|bash|json|ya?ml|toml|ini|cfg|conf|md|txt|html?|css|scss|sql|lock|env|xml|gradle|dockerfile)\b|\b(?:Makefile|Dockerfile|README)\b/i;
const FS_WORK = /\b(?:run|execute|install|build|compile|test|lint|commit|grep|search|find|list|read|open|show|edit|modify|change|fix|refactor|rename|delete|remove|create|write|add|save|update|implement|debug|scan|check|look\s+at|inspect)\b[^.?!\n]*\b(?:files?|folders?|director(?:y|ies)|dirs?|repo(?:sitory)?|project|codebase|workspace|branch(?:es)?|commits?)\b/i;
const CODE_WORK = /\b(?:run|execute|install|build|compile|test|lint|edit|modify|change|fix|refactor|rename|delete|remove|update|debug|scan|check|look\s+at|inspect)\b[^.?!\n]*\b(?:code|functions?|class(?:es)?|modules?|scripts?|tests?|commands?|shell|packages?|dependenc(?:y|ies))\b/i;
const HERE = /\b(?:in|from|of|at|inside)\s+(?:this|the|my|our)\s+(?:repo(?:sitory)?|project|codebase|folder|directory|code|workspace)\b|\b(?:files?|folders?)\s+here\b/i;
function wantsToolWork(text) {
const t = String(text || "");
if (!t.trim() || forbidsTools(t)) return false;
return FILE_REF.test(t) || FS_WORK.test(t) || CODE_WORK.test(t) || HERE.test(t);
}
const NO_TOOLS_REPLY = "Not run: the user asked you not to use tools for this. Answer directly with action \"final\".";
const NUDGE = "You answered without looking at the project. This request is about the files here: use a tool first (read_file, list_dir, search or run_command), then give your final answer.";

const _norm = (x) => String(x == null ? "" : x).replace(/\s+/g, " ").trim().toLowerCase();
function sameText(a, b) { const x = _norm(a), y = _norm(b); return !!x && !!y && y.includes(x); }

module.exports = { capObservation, compactTail, wantsToolWork, forbidsTools, sameText, NUDGE, NO_TOOLS_REPLY };
Loading
Loading