From 6e71d6b792a530952394f2fc4ae619907460233c Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 13:36:53 -0700 Subject: [PATCH 01/16] nexus: keep the live token counter monotonic (real count never yanks it backwards) --- darknode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/darknode.js b/darknode.js index bb53c4f..a437216 100755 --- a/darknode.js +++ b/darknode.js @@ -3897,7 +3897,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { onThinking: (t) => { let last = block.items[block.items.length - 1]; if (!last || last.type !== "thinking") { last = { type: "thinking", full: "" }; block.items.push(last); } last.full += t; bumpLive(t); renderSoon(); }, onText: (t) => { textItem().full += t; bumpLive(t); renderSoon(); }, onDelta: (t) => { bumpLive(t); renderSoon(); }, // mid-message delta: advance the live token estimate only (the whole text/thinking still lands via onText/onThinking) - onLiveTokens: (n) => { estOut = n; sess.liveOut = confOut + estOut; renderSoon(); }, // real running output tokens for the in-flight message — overrides the char estimate + onLiveTokens: (n) => { estOut = Math.max(estOut, n); sess.liveOut = confOut + estOut; renderSoon(); }, // real running output tokens for the in-flight message — overrides the char estimate (never let it yank the counter backwards if the estimate ran ahead) onTool: (tu) => { const _item = { type: "tool", id: tu.id, name: tu.name, input: tu.input, label: toolLabel(tu.name, tu.input), detail: JSON.stringify(tu.input).slice(0, 400), status: "run", start: Date.now() }; if (["Write", "Edit", "MultiEdit"].includes(tu.name)) _item.diff = editDiff(tu.name, tu.input); From d34be843ab15b08551095380aa42ee09cf244225 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 14:06:05 -0700 Subject: [PATCH 02/16] nexus: fix composer corruption from batched/split control input MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two input-handling bugs that surfaced as 'the caret jumps right and backspace does nothing' (notably right after /restart, when the terminal batches keystrokes buffered during the cold start): - A held/batched Backspace arrives as one read ("\x7f\x7f…"). The keymap matches a single byte, and the printable guard let DEL (0x7f) through a naive 'seq >= " "' compare, so the run was INSERTED as stray chars instead of deleting. Replay a batched run of control bytes one at a time, and harden the composer's printable guard to never insert a control byte. - A terminal report/arrow split across reads (lone ESC in one chunk, its body in the next) leaked the body into the composer as text. Reassemble a split escape sequence by briefly holding a lone trailing ESC. Verified via pty harness (backspace, Alt+Backspace, batched arrows, split reports) and 4 new composer unit tests. 1670 tests pass. --- darknode.js | 25 ++++++++++++++++++++++++- lib/cli/composer.js | 6 +++++- test/composer.test.js | 16 ++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/darknode.js b/darknode.js index a437216..6780bbf 100755 --- a/darknode.js +++ b/darknode.js @@ -2578,6 +2578,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const ident = resolveOperator({ cwd }); // operator/team for chargeback attribution + audit provenance const oMsgs = nexusMd ? [{ role: "system", content: "Nexus coding assistant.\n" + nexusMd }] : [{ role: "system", content: "Nexus coding assistant." }]; let input = "", curPos = 0, busy = false, cont = false, busyStart = 0, busyWord = "", tick = null, activeBlock = null; // activeBlock: the nexus block currently streaming (the typewriter targets it even if an async note moved the transcript tail) + let _escHold = false, _escTimer = null, _escFlushing = false; // reassemble an escape/report sequence a terminal split across stdin reads (ESC alone, body next) // Carried across a compaction of the claude engine. Claude's context lives // server-side and is resumed with --continue; to actually shrink it we must // DROP --continue (cont=false) and re-seed the next prompt with a summary, @@ -3744,7 +3745,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (sess.ctxUsed > compactAt()) doCompact(true); }; const onResize = () => { lastLines = null; if (!loading) render(); }; // geometry changed — force a full repaint - const cleanup = () => { if (cleaned) return; cleaned = true; tuiActive = false; if (tick) { clearInterval(tick); tick = null; } if (_rsT) { clearTimeout(_rsT); _rsT = null; } if (_drainT) { clearTimeout(_drainT); _drainT = null; } if (compact.cur) { try { compact.cur.ctl.kill(); } catch (_) {} } if (ctl && ctl.kill) try { ctl.kill(); } catch (_) {} try { bgJobs.killAll(); } catch (_) {} try { if (dashServer) dashServer.close(); } catch (_) {} for (const s of mcpServers) { try { s.cp && s.cp.kill(); } catch (_) {} } try { process.stdin.setRawMode(false); } catch (_) {} process.stdin.pause(); process.stdin.removeAllListeners("data"); out.removeListener("resize", onResize); process.removeListener("exit", cleanup); process.removeListener("SIGINT", onSigint); process.removeListener("SIGTERM", onSigterm); process.removeListener("uncaughtException", onFatal); process.removeListener("unhandledRejection", onRejection); try { term.teardown(); } catch (_) {} }; + const cleanup = () => { if (cleaned) return; cleaned = true; tuiActive = false; if (tick) { clearInterval(tick); tick = null; } if (_rsT) { clearTimeout(_rsT); _rsT = null; } if (_drainT) { clearTimeout(_drainT); _drainT = null; } if (_escTimer) { clearTimeout(_escTimer); _escTimer = null; } if (compact.cur) { try { compact.cur.ctl.kill(); } catch (_) {} } if (ctl && ctl.kill) try { ctl.kill(); } catch (_) {} try { bgJobs.killAll(); } catch (_) {} try { if (dashServer) dashServer.close(); } catch (_) {} for (const s of mcpServers) { try { s.cp && s.cp.kill(); } catch (_) {} } try { process.stdin.setRawMode(false); } catch (_) {} process.stdin.pause(); process.stdin.removeAllListeners("data"); out.removeListener("resize", onResize); process.removeListener("exit", cleanup); process.removeListener("SIGINT", onSigint); process.removeListener("SIGTERM", onSigterm); process.removeListener("uncaughtException", onFatal); process.removeListener("unhandledRejection", onRejection); try { term.teardown(); } catch (_) {} }; tuiActive = true; const onFatal = (e) => { const sig = e === "SIGINT" || e === "SIGTERM"; try { term.teardown(); } catch (_) {} try { cleanup(); } catch (_) {} if (e && e instanceof Error) { try { process.stderr.write("\nNexus exited on error: " + e.message + "\n"); } catch (_) {} } try { resolve(); } catch (_) {} if (sig) process.exit(0); }; const onSigint = () => onFatal("SIGINT"), onSigterm = () => onFatal("SIGTERM"); @@ -5610,6 +5611,21 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (loading) { finishBoot(); return; } // any key skips the intro if (pasteNotice) pasteNotice = ""; // a paste preflight notice lasts until the next key let s = String(d); + // Reassemble an escape sequence a terminal split across reads. A report or + // arrow can arrive as a lone ESC in one chunk and its body ("[12;40R", "[I", + // "OP", "[A"…) in the next; the body starts with '[' or 'O', NOT ESC, so the + // printable guard below would insert it into the composer as stray text — + // parking the caret past the end and making backspace look dead (it's + // deleting the junk first). Hold a lone trailing ESC one beat and glue the + // next chunk onto it; if nothing follows, deliver it as a real Esc. + if (_escHold) { + _escHold = false; if (_escTimer) { clearTimeout(_escTimer); _escTimer = null; } + if (s.charCodeAt(0) !== 27) s = "\x1b" + s; // ESC + body → whole sequence + else { try { _escFlushing = true; process.stdin.emit("data", "\x1b"); } finally { _escFlushing = false; } } // held ESC was standalone; deliver it, then process this new chunk + } else if (s === "\x1b" && !_escFlushing) { + _escHold = true; _escTimer = setTimeout(() => { _escHold = false; _escTimer = null; try { _escFlushing = true; process.stdin.emit("data", "\x1b"); } finally { _escFlushing = false; } }, 40); + return; + } // A wheel notch in alt-screen scroll mode (?1007) arrives as a burst of arrow // keys in ONE chunk, often in SS3 form (ESC O A). Replay a burst key by key // and fold SS3 arrows to CSI so every handler below sees a single "\x1b[A". @@ -5627,6 +5643,13 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // every handler below matches a single exact sequence. const _seqs = s.match(/\x1b(?:\[[0-9;]*[A-Za-z~]|O[A-Z])/g); if (_seqs && _seqs.length > 1 && _seqs.join("") === s && !/\[<|\[200~|\[201~/.test(s)) { for (const k of _seqs) process.stdin.emit("data", k); return; } + // A run of single-byte control keys can batch into one read too — notably a + // held Backspace (0x7f) or keystrokes buffered during a slow restart, which + // arrive as "\x7f\x7f…". Each handler matches ONE exact byte, and the + // printable guard treats DEL (0x7f) as text, so a batched run would get + // inserted as stray chars instead of editing — the caret jumps right and + // nothing deletes. Replay such a run one byte at a time. + if (s.length > 1 && /^[\x00-\x08\x0b\x0c\x0e-\x1a\x1c-\x1f\x7f]+$/.test(s)) { for (const ch of s) process.stdin.emit("data", ch); return; } // (exclude \t \n \r so real newlines/paste still flow through, and ESC so Alt+key combos like Alt+Backspace stay intact) // Application-cursor mode (DECCKM, often left on by another program) sends // arrows/Home/End as SS3 (ESC O x): fold all of them to the CSI form. if (/^\x1bO[ABCDHF]$/.test(s)) s = "\x1b[" + s[2]; diff --git a/lib/cli/composer.js b/lib/cli/composer.js index ba5e6fd..d7b3992 100644 --- a/lib/cli/composer.js +++ b/lib/cli/composer.js @@ -582,7 +582,11 @@ function feed(model, seq, env, now) { } // ---- printable ---- - if (seq.length && seq >= " " && seq.charCodeAt(0) !== 27) { + // Guard against control bytes masquerading as text: `seq >= " "` is a string + // compare that passes DEL (0x7f) and other C0/C1 controls, so an unhandled + // backspace/report byte would otherwise be INSERTED into the buffer. Require a + // real printable leading char (space or above, and not DEL). + if (seq.length && seq.charCodeAt(0) >= 0x20 && seq.charCodeAt(0) !== 0x7f) { if (seq === "?" && !model.text.length) return { type: "help" }; // '?' on empty = keys help model.insert(seq); return { type: "render" }; } diff --git a/test/composer.test.js b/test/composer.test.js index d7feeea..df64ec8 100644 --- a/test/composer.test.js +++ b/test/composer.test.js @@ -126,6 +126,22 @@ group("undo (Ctrl+_)"); ok("undo reverts the last edit", m.text === "ab"); } +group("control bytes are never inserted as text"); +{ + const m = new C.ComposerModel({ text: "abc" }); m.cursor = m.text.length; + C.feed(m, "\x7f", {}); // single DEL = backspace (keymap), deletes rather than inserting + eq("single DEL (0x7f) backspaces, not inserts", m.text, "ab"); + // A batched control run (e.g. held Backspace "\x7f\x7f" that reached feed whole) + // must be dropped, not inserted — DEL slips past a naive `seq >= " "` compare. + const m2 = new C.ComposerModel({ text: "abc" }); m2.cursor = m2.text.length; + eq("batched DEL run is dropped, not inserted", C.feed(m2, "\x7f\x7f", {}).type, "none"); + eq(" …buffer is left untouched", m2.text, "abc"); + // Ordinary printable (incl. non-ASCII) still inserts. + const m3 = new C.ComposerModel(); + C.feed(m3, "é", {}); + eq("non-ASCII char still inserts", m3.text, "é"); +} + group("word jumps"); { const m = new C.ComposerModel({ text: "foo bar baz" }); m.cursor = m.text.length; From 7e9de7ff84bfb4e6df500fb1b4104c83ad4cf7ec Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 14:18:54 -0700 Subject: [PATCH 03/16] nexus: add multi-select + free-text ask popups, and a yes/no confirm for /clear The ask card (Claude-Code 'pick one' prompt) now has three modes: - pick-one ask_user{question,options:[...]} -> {selected,index} (existing) - pick-many ask_user{question,options:[...],multi:true} -> {selected,indices} (checkboxes, Space toggles) - free-text ask_user{question,input:true} -> {answer} (type an answer) renderAsk/askKey stay pure and snapshot-testable; the host carries the extra picked/text state and resolves the matching shape. /clear now confirms through a yes/no select card instead of the 'type /clear again' pattern, so the popup is reachable on every engine (not just when the local model raises ask_user). 20 new ask unit tests + a pty end-to-end check of the /clear flow; 1690 pass. --- darknode.js | 42 ++++++++++++++++++++++++++-------- lib/cli/ask.js | 62 ++++++++++++++++++++++++++++++++++++++++++-------- test/run.js | 32 ++++++++++++++++++++++++++ 3 files changed, 117 insertions(+), 19 deletions(-) diff --git a/darknode.js b/darknode.js index 6780bbf..636ad05 100755 --- a/darknode.js +++ b/darknode.js @@ -3606,8 +3606,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // ---- model-driven question: pause the agent loop, show the Claude-style // multiple-choice card, and resolve with the user's pick (or {cancelled} // if they skip with Esc). The key loop drives pendingAsk via Ask.askKey. ---- - const askUser = (question, options) => new Promise((resolve) => { - pendingAsk = { question: String(question || ""), options: options || [], sel: 0, resolve }; + const askUser = (question, options, extra) => new Promise((resolve) => { + pendingAsk = Object.assign({ question: String(question || ""), options: options || [], sel: 0, picked: [], text: "", resolve }, extra || {}); scroll = 0; render(); }); // ---- animation loop: typewriter reveal + spinners + elapsed ---- @@ -3963,7 +3963,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { } else { // ollama — LOCAL agent with full device access (read/write/edit/list/run_command) const mcps = mcpToolList(); const extra = (mcps.length ? " MCP tools: " + mcps.map((m) => m.full + " — " + oneline(m.desc, 40)).join("; ") + "." : "") + " spawn_agents{tasks:[\"...\",\"...\"]} runs several INDEPENDENT sub-tasks in parallel via sub-agents and returns all their results — use it to split big work."; - if (oMsgs.length === 1) oMsgs[0].content = "Nexus agent (cwd " + cwd + "). One action/step. Tools: read_file{path} write_file{path,content} edit_file{path,find,replace} multi_edit{path,edits:[{find,replace}]} apply_patch{patch} list_dir{path?} run_command{command} run_background{command} check_background{id?} stop_background{id} search{pattern,path?} find{glob,path?} http_fetch{url,method?} web_search{query} view_image{path} todo_write{todos} sysinfo{} list_processes{filter?} make_dir{path} move{from,to} copy{from,to} delete{path} repo_map{} find_symbol{name} find_references{name,path?,context?} module_graph{path?} outline{path} verify{kind?} git_tool{op,path?,ref?} lint_format{check?,path?} notebook_edit{path,op,index?,source?} remember{text} discover{query} batch{ops:[{op,path?,pattern?,glob?}]} invariants{} attest{claims?} bisect{test?} explain_break{output?} shrink{test?} ask_user{question,options:[\"A\",\"B\"]}." + extra + " repo_map{} returns a ranked file+symbol map to get oriented fast; find_symbol{name} jumps to where a function/class is defined; find_references{name} is the reverse — every USAGE/caller of a symbol across the repo, grouped by file with line numbers (def/import/usage tagged), for impact analysis before you rename, change a signature, or delete something. module_graph{path?} is the file-level view: what imports a file and what it imports (its blast radius), or a project summary of the most-imported files + entry points when path is omitted. outline{path} lists one file's functions/classes/types in order with line numbers to get oriented fast. batch{ops} runs several READ-ONLY lookups (op:read/search/glob/list) in ONE call and returns them all together — prefer it over firing many separate read_file/search/find calls when investigating, to save round-trips and tokens. multi_edit makes several edits to one file atomically; apply_patch applies a unified diff (anchors on context, so line numbers can drift). edit_file/multi_edit tolerate whitespace differences. verify{kind?} auto-detects and runs the project's own tests/build — call it after editing to check your work before you finish. invariants{} lints your pending diff against the repo's declared rules in .nexus/invariants.json (stray debug lines, new TODOs, new dependencies, forbidden-path edits) — call it before finishing so a reviewer-trustable gate catches mistakes tests don't. attest{claims?} reads the tamper-evident audit log and reports exactly what this run touched (files written, commands run, whether the network was used) and can prove declared claims like {\"noNetwork\":true,\"onlyPaths\":[\"src/**\"],\"noDelete\":true}. bisect{test?} binary-searches your per-turn checkpoints, restoring and testing each, to pinpoint the exact turn that broke the tests (then restores the working tree) — use it when a run ends with the tests failing and you don't know which change caused it. explain_break{output?} is the instant version: give it the failing test output and it blames the turn whose changes most likely caused it (no re-running) — a fast first guess before bisect proves it. shrink{test?} delta-debugs your OWN edits down to the minimal subset of changed files that still breaks the test, reverting the rest to baseline — use it to find the real blast radius when a run touched many files. ask_user{question,options} pauses and asks the user a MULTIPLE-CHOICE question (2-9 short options) and returns their pick — use it ONLY when a real decision is genuinely the user's to make (ambiguous requirement, a destructive/irreversible choice, which of several approaches); never for things you can decide or look up yourself, and never more than needed. git_tool{op} runs READ-ONLY structured git (op: status/log/diff/show/blame/branch) and returns a parsed object — use run_command for commits/pushes. lint_format auto-detects the project formatter and fixes code style in place (prettier/eslint/ruff/black/gofmt); pass check:true to only report. notebook_edit reads and edits Jupyter .ipynb cells structurally (op: read/edit/insert/delete) instead of hand-splicing the JSON. JSON: {\"thought\",\"action\":\"tool\",\"tool\",\"args\"} or {\"thought\",\"action\":\"final\",\"final\"}. Greetings→final." + (tightEdits ? " " + TIGHT_DIR : "") + (minimizeCalls ? " Minimize calls; chain commands." : "") + (lean ? " Terse." : "") + (styleDir(style) ? " " + styleDir(style) : "") + (hack ? " " + HACK_DIR : "") + (nexusMd ? "\nPROJECT:\n" + nexusMd.slice(0, 1000) : ""); + if (oMsgs.length === 1) oMsgs[0].content = "Nexus agent (cwd " + cwd + "). One action/step. Tools: read_file{path} write_file{path,content} edit_file{path,find,replace} multi_edit{path,edits:[{find,replace}]} apply_patch{patch} list_dir{path?} run_command{command} run_background{command} check_background{id?} stop_background{id} search{pattern,path?} find{glob,path?} http_fetch{url,method?} web_search{query} view_image{path} todo_write{todos} sysinfo{} list_processes{filter?} make_dir{path} move{from,to} copy{from,to} delete{path} repo_map{} find_symbol{name} find_references{name,path?,context?} module_graph{path?} outline{path} verify{kind?} git_tool{op,path?,ref?} lint_format{check?,path?} notebook_edit{path,op,index?,source?} remember{text} discover{query} batch{ops:[{op,path?,pattern?,glob?}]} invariants{} attest{claims?} bisect{test?} explain_break{output?} shrink{test?} ask_user{question,options:[\"A\",\"B\"]}." + extra + " repo_map{} returns a ranked file+symbol map to get oriented fast; find_symbol{name} jumps to where a function/class is defined; find_references{name} is the reverse — every USAGE/caller of a symbol across the repo, grouped by file with line numbers (def/import/usage tagged), for impact analysis before you rename, change a signature, or delete something. module_graph{path?} is the file-level view: what imports a file and what it imports (its blast radius), or a project summary of the most-imported files + entry points when path is omitted. outline{path} lists one file's functions/classes/types in order with line numbers to get oriented fast. batch{ops} runs several READ-ONLY lookups (op:read/search/glob/list) in ONE call and returns them all together — prefer it over firing many separate read_file/search/find calls when investigating, to save round-trips and tokens. multi_edit makes several edits to one file atomically; apply_patch applies a unified diff (anchors on context, so line numbers can drift). edit_file/multi_edit tolerate whitespace differences. verify{kind?} auto-detects and runs the project's own tests/build — call it after editing to check your work before you finish. invariants{} lints your pending diff against the repo's declared rules in .nexus/invariants.json (stray debug lines, new TODOs, new dependencies, forbidden-path edits) — call it before finishing so a reviewer-trustable gate catches mistakes tests don't. attest{claims?} reads the tamper-evident audit log and reports exactly what this run touched (files written, commands run, whether the network was used) and can prove declared claims like {\"noNetwork\":true,\"onlyPaths\":[\"src/**\"],\"noDelete\":true}. bisect{test?} binary-searches your per-turn checkpoints, restoring and testing each, to pinpoint the exact turn that broke the tests (then restores the working tree) — use it when a run ends with the tests failing and you don't know which change caused it. explain_break{output?} is the instant version: give it the failing test output and it blames the turn whose changes most likely caused it (no re-running) — a fast first guess before bisect proves it. shrink{test?} delta-debugs your OWN edits down to the minimal subset of changed files that still breaks the test, reverting the rest to baseline — use it to find the real blast radius when a run touched many files. ask_user{question,options} pauses and asks the user a question — use it ONLY when a real decision is genuinely the user's to make (ambiguous requirement, a destructive/irreversible choice, which of several approaches); never for things you can decide or look up yourself, and never more than needed. Three forms: pick-one ask_user{question,options:[\"A\",\"B\"]} returns {selected,index}; pick-many ask_user{question,options:[...],multi:true} (the user toggles several, Space to check) returns {selected:[...],indices:[...]}; free-text ask_user{question,input:true} (no options; the user types an answer) returns {answer}. git_tool{op} runs READ-ONLY structured git (op: status/log/diff/show/blame/branch) and returns a parsed object — use run_command for commits/pushes. lint_format auto-detects the project formatter and fixes code style in place (prettier/eslint/ruff/black/gofmt); pass check:true to only report. notebook_edit reads and edits Jupyter .ipynb cells structurally (op: read/edit/insert/delete) instead of hand-splicing the JSON. JSON: {\"thought\",\"action\":\"tool\",\"tool\",\"args\"} or {\"thought\",\"action\":\"final\",\"final\"}. Greetings→final." + (tightEdits ? " " + TIGHT_DIR : "") + (minimizeCalls ? " Minimize calls; chain commands." : "") + (lean ? " Terse." : "") + (styleDir(style) ? " " + styleDir(style) : "") + (hack ? " " + HACK_DIR : "") + (nexusMd ? "\nPROJECT:\n" + nexusMd.slice(0, 1000) : ""); if (localReplay.length) { for (const m of localReplay) oMsgs.push(m); localReplay = []; } // restored session → the local model remembers it if (imgAttach.length && apiConfigured()) oMsgs.push({ role: "user", content: [{ type: "text", text: promptText }].concat(imgAttach.map((im) => ({ type: "image_url", image_url: { url: "data:" + im.mime + ";base64," + im.b64 } }))) }); // OpenAI-compatible vision else if (imgAttach.length) oMsgs.push({ role: "user", content: promptText, images: imgAttach.map((im) => im.b64) }); // Ollama vision (llava / llama3.2-vision / …) @@ -4073,14 +4073,32 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // rendered exactly like the Claude-Code "pick one" prompt. The // chosen label (or a skip) is fed back as the tool observation. const q = a.question || a.prompt || a.q || a.text || ""; + const wantInput = a.input === true || a.freeform === true || a.free_text === true || a.text_input === true; + const multi = a.multi === true || a.multiple === true || a.multi_select === true; let opts = a.options || a.choices || a.answers || a.items || []; if (typeof opts === "string") opts = opts.split(/\s*\|\s*|\n/).map((x) => x.trim()).filter(Boolean); const norm = Ask.normOptions(opts); - if (!q || !norm.length) result = { error: "ask_user needs a non-empty question and an options array (2-9 choices), e.g. ask_user{question,options:[\"A\",\"B\"]}" }; + const skipNote = { skipped: true, note: "the user dismissed the question without answering — decide yourself or ask differently" }; + if (!q) result = { error: "ask_user needs a non-empty question" }; + else if (wantInput) { + // free-text: the user types an answer (no options needed). + card.label = "AskUser(" + oneline(q, 30) + ")"; render(); + const ans = await askUser(q, [], { input: true, placeholder: a.placeholder || a.hint }); + if (ans.cancelled) { result = skipNote; transcript.push({ role: "system", text: "Nexus asked: " + oneline(q, 48) + " — skipped" }); } + else { const answer = String(ans.value || ""); result = { answer }; transcript.push({ role: "system", text: "you answered: " + oneline(answer || "(empty)", 40) + " (" + oneline(q, 36) + ")" }); } + } + else if (!norm.length) result = { error: "ask_user needs an options array (2-9 choices), or input:true for a free-text answer — e.g. ask_user{question,options:[\"A\",\"B\"]}, ask_user{question,options:[...],multi:true}, or ask_user{question,input:true}" }; + else if (multi) { + // multi-select: the user toggles any number of choices (space), confirms with Enter. + card.label = "AskUser(" + oneline(q, 30) + ")"; render(); + const ans = await askUser(q, norm, { multi: true, picked: [] }); + if (ans.cancelled) { result = skipNote; transcript.push({ role: "system", text: "Nexus asked: " + oneline(q, 48) + " — skipped" }); } + else { const labels = (ans.values || []).map((v) => v && v.label != null ? v.label : String(v)); result = { selected: labels, indices: ans.indices || [] }; transcript.push({ role: "system", text: "you chose: " + oneline(labels.join(", ") || "(none)", 42) + " (" + oneline(q, 32) + ")" }); } + } else { card.label = "AskUser(" + oneline(q, 30) + ")"; render(); const ans = await askUser(q, norm); - if (ans.cancelled) { result = { skipped: true, note: "the user dismissed the question without choosing — decide yourself or ask differently" }; transcript.push({ role: "system", text: "Nexus asked: " + oneline(q, 48) + " — skipped" }); } + if (ans.cancelled) { result = skipNote; transcript.push({ role: "system", text: "Nexus asked: " + oneline(q, 48) + " — skipped" }); } else { const label = ans.value && ans.value.label != null ? ans.value.label : String(ans.value); result = { selected: label, index: ans.index }; transcript.push({ role: "system", text: "you chose: " + oneline(label, 36) + " (" + oneline(q, 40) + ")" }); } } } @@ -4634,8 +4652,12 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { else if (cmd === "/rewind") { if (!checkpoints.length) transcript.push({ role: "system", text: "no checkpoints to rewind to" }); else { const n = parseInt(arg, 10); const idx = isNaN(n) ? checkpoints.length - 1 : n - 1; const ck = checkpoints[idx]; if (!ck) transcript.push({ role: "system", text: "no checkpoint #" + arg + " — /checkpoints to list them" }); else { const ok = nexusRestore(cwd, ck.tree, ck.paths); if (ok) checkpoints.length = idx; transcript.push({ role: "system", text: ok ? ("rewound to checkpoint #" + (idx + 1) + " (before \"" + ck.label + "\") — restored " + ((ck.paths && ck.paths.length) ? ck.paths.length + " file(s) Nexus changed" : "the working tree")) : "rewind failed (git error)" }); } } } else if (cmd === "/clear" || cmd === "/new") { const hasContent = oMsgs.length > 1 || transcript.some((m) => m.role === "user" || m.role === "nexus"); - if (hasContent && !clearWasPending) { clearPending = true; transcript.push({ role: "system", text: yellow("Clear the whole conversation?") + gray(" press " + cmd + " again to confirm · any other input keeps it") }); } - else { clearPending = false; transcript.length = 0; transcript.push({ role: "art" }); cont = false; oMsgs.length = 1; sess.ctxUsed = 0; scroll = 0; sess.readCache = {}; if (sess.fileSnap) sess.fileSnap.clear(); } + const doClear = () => { clearPending = false; transcript.length = 0; transcript.push({ role: "art" }); cont = false; oMsgs.length = 1; sess.ctxUsed = 0; scroll = 0; sess.readCache = {}; if (sess.fileSnap) sess.fileSnap.clear(); render(); }; + if (!hasContent) doClear(); // nothing to lose — just reset + else askUser("Clear the whole conversation? This wipes the chat and the model's memory of it.", ["Keep it", "Clear everything"]).then((ans) => { + if (!ans.cancelled && ans.index === 1) doClear(); + else { transcript.push({ role: "system", text: gray("kept the conversation") }); render(); } + }); } else if (cmd === "/chat-clear" || cmd === "/screen-clear") { // Wipe only the on-screen transcript. The model keeps the full @@ -5703,9 +5725,9 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (isMouse) return; // swallow mouse while choosing (no accidental scroll/edit) const r = Ask.askKey(pendingAsk, s); if (r.cancelled) { const p = pendingAsk; pendingAsk = null; p.resolve({ cancelled: true }); render(); return; } - if (r.done) { const p = pendingAsk; pendingAsk = null; p.resolve({ index: r.index, value: r.value }); render(); return; } - if (r.sel !== pendingAsk.sel) { pendingAsk.sel = r.sel; render(); } - return; + if (r.done) { const p = pendingAsk; pendingAsk = null; p.resolve(r); render(); return; } // r carries value/index (single), indices/values (multi) or value (text) + if (r.sel != null) pendingAsk.sel = r.sel; if (r.picked) pendingAsk.picked = r.picked; if (r.text != null) pendingAsk.text = r.text; + render(); return; } // ---- reverse-i-search owns the keyboard while active (mouse still works) ---- diff --git a/lib/cli/ask.js b/lib/cli/ask.js index 045e456..a8e4ca8 100644 --- a/lib/cli/ask.js +++ b/lib/cli/ask.js @@ -28,6 +28,13 @@ function normOptions(options) { function clampSel(sel, n) { sel = sel | 0; if (sel < 0) return 0; if (sel > n - 1) return Math.max(0, n - 1); return sel; } +// Normalize the multi-select picked set into a sorted array of valid indices. +function normPicked(picked, n) { + const seen = Object.create(null), out = []; + for (const i of (Array.isArray(picked) ? picked : [])) { const k = i | 0; if (k >= 0 && k < n && !seen[k]) { seen[k] = 1; out.push(k); } } + return out.sort((a, b) => a - b); +} + // Plain word-wrap for the question text (no ANSI inside — colored by the caller). function wrapPlain(s, w) { s = String(s || "").replace(/\s+/g, " ").trim(); @@ -50,8 +57,6 @@ function renderAsk(ask, width, colors) { const C = Math.max(24, (width | 0) || 80); const t = theme(colors); const inner = C - 2; // content width after the 1-col gutter - const opts = normOptions(ask && ask.options); - const sel = clampSel(ask && ask.sel, opts.length); const rows = []; const rule = " " + t.gray("─".repeat(Math.max(0, inner))); rows.push(rule); @@ -59,16 +64,36 @@ function renderAsk(ask, width, colors) { const q = wrapPlain(ask && ask.question, Math.max(1, inner - 2)); q.forEach((ln, i) => rows.push(" " + (i === 0 ? t.cyan("● ") : " ") + t.bold(ln))); rows.push(" "); - // Options — numbered; the selected row gets a "›" marker and cyan/bold label. + if (ask && ask.input) { + // ---- free-text input: a single editable field with a block caret. ---- + const text = String(ask.text || ""); + const avail = Math.max(1, inner - 4); + const shown = text.length > avail ? "…" + text.slice(-(avail - 1)) : text; + rows.push(" " + t.cyan(" › ") + (shown ? shown : t.dim(ask.placeholder ? String(ask.placeholder) : "type your answer")) + t.cyan("█")); + rows.push(" "); + rows.push(" " + t.gray("type your answer · enter submit · esc skip")); + rows.push(rule); + return rows; + } + const opts = normOptions(ask && ask.options); + const sel = clampSel(ask && ask.sel, opts.length); + const multi = !!(ask && ask.multi); + const picked = multi ? normPicked(ask && ask.picked, opts.length) : []; + // Options — numbered; the current row gets a "›" marker and cyan/bold label. + // In multi-select mode each row also carries a [x]/[ ] checkbox. opts.forEach((o, i) => { const on = i === sel; const num = (i + 1) + "."; + const box = multi ? (picked.indexOf(i) >= 0 ? t.green("[x] ") : t.gray("[ ] ")) : ""; const head = on ? t.cyan(" › ") : " "; const body = on ? t.bold(t.cyan(num + " " + o.label)) : t.gray(num + " ") + o.label; - rows.push(head + body + (o.hint ? " " + t.dim(o.hint) : "")); + rows.push(head + box + body + (o.hint ? " " + t.dim(o.hint) : "")); }); rows.push(" "); - rows.push(" " + t.gray("up/down move · 1-" + Math.max(1, opts.length) + " pick · enter confirm · esc skip")); + const hint = multi + ? "space toggle · enter confirm · esc skip · " + picked.length + " picked" + : "up/down move · 1-" + Math.max(1, opts.length) + " pick · enter confirm · esc skip"; + rows.push(" " + t.gray(hint)); rows.push(rule); return rows; } @@ -79,16 +104,35 @@ function renderAsk(ask, width, colors) { // confirms the current selection; Esc / Ctrl+C cancel (the model is told the // user skipped). Any other key is a no-op. function askKey(ask, key) { + // ---- free-text input mode ---- + if (ask && ask.input) { + const text = String(ask.text || ""); + if (key === "\x1b" || key === "\x03") return { text, done: false, cancelled: true }; + if (key === "\r" || key === "\n") return { text, done: true, value: text }; + if (key === "\x7f" || key === "\b") return { text: text.slice(0, -1), done: false }; + if (key === "\x15") return { text: "", done: false }; // Ctrl+U clears the field + if (key.length === 1 && key.charCodeAt(0) >= 0x20 && key.charCodeAt(0) !== 0x7f) return { text: text + key, done: false }; + return { text, done: false }; + } const opts = normOptions(ask && ask.options); const n = opts.length; const sel = clampSel(ask && ask.sel, n); - if (key === "\x1b" || key === "\x03") return { sel, done: false, cancelled: true }; + const multi = !!(ask && ask.multi); + if (key === "\x1b" || key === "\x03") return multi ? { sel, picked: normPicked(ask && ask.picked, n), done: false, cancelled: true } : { sel, done: false, cancelled: true }; if (n === 0) return { sel, done: false }; - if (key === "\x1b[A" || key === "[A" || key === "\x1bOA") return { sel: (sel - 1 + n) % n, done: false }; - if (key === "\x1b[B" || key === "[B" || key === "\x1bOB") return { sel: (sel + 1) % n, done: false }; + if (key === "\x1b[A" || key === "[A" || key === "\x1bOA") return multi ? { sel: (sel - 1 + n) % n, picked: normPicked(ask && ask.picked, n), done: false } : { sel: (sel - 1 + n) % n, done: false }; + if (key === "\x1b[B" || key === "[B" || key === "\x1bOB") return multi ? { sel: (sel + 1) % n, picked: normPicked(ask && ask.picked, n), done: false } : { sel: (sel + 1) % n, done: false }; + if (multi) { + // Space or a digit TOGGLES membership; Enter confirms the whole set. + const toggle = (i) => { const cur = normPicked(ask && ask.picked, n); const at = cur.indexOf(i); if (at >= 0) cur.splice(at, 1); else cur.push(i); return normPicked(cur, n); }; + if (key === " ") return { sel, picked: toggle(sel), done: false }; + if (/^[1-9]$/.test(key)) { const i = +key - 1; return i < n ? { sel: i, picked: toggle(i), done: false } : { sel, picked: normPicked(ask && ask.picked, n), done: false }; } + if (key === "\r" || key === "\n") { const idx = normPicked(ask && ask.picked, n); return { sel, picked: idx, done: true, indices: idx, values: idx.map((i) => opts[i]) }; } + return { sel, picked: normPicked(ask && ask.picked, n), done: false }; + } if (key === "\r" || key === "\n") return { sel, done: true, value: opts[sel], index: sel }; if (/^[1-9]$/.test(key)) { const i = +key - 1; return i < n ? { sel: i, done: true, value: opts[i], index: i } : { sel, done: false }; } return { sel, done: false }; } -module.exports = { renderAsk, askKey, normOptions, wrapPlain }; +module.exports = { renderAsk, askKey, normOptions, normPicked, wrapPlain }; diff --git a/test/run.js b/test/run.js index 8022588..a0ca98a 100644 --- a/test/run.js +++ b/test/run.js @@ -2610,6 +2610,38 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("renderAsk tolerates no options", Array.isArray(renderAsk({ question: "q", options: [] }, 40))); } + group("ask — multi-select (checkbox) mode"); + { + const base = { question: "Pick the test suites to run", options: ["unit", "e2e", "lint", "types"], sel: 0, multi: true, picked: [] }; + ok("space toggles the current row on", (() => { const r = askKey(base, " "); return !r.done && JSON.stringify(r.picked) === JSON.stringify([0]); })()); + ok("space again toggles it back off", (() => { const r = askKey({ ...base, picked: [0] }, " "); return JSON.stringify(r.picked) === JSON.stringify([]); })()); + ok("a digit toggles that option", (() => { const r = askKey({ ...base, picked: [0] }, "3"); return JSON.stringify(r.picked) === JSON.stringify([0, 2]); })()); + ok("arrows move without changing the picked set", (() => { const r = askKey({ ...base, picked: [1] }, "\x1b[B"); return r.sel === 1 && JSON.stringify(r.picked) === JSON.stringify([1]); })()); + ok("enter confirms the whole set (sorted)", (() => { const r = askKey({ ...base, picked: [2, 0] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([0, 2]) && r.values[0].label === "unit" && r.values[1].label === "lint"; })()); + ok("enter with nothing picked confirms an empty set", (() => { const r = askKey({ ...base, picked: [] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([]); })()); + ok("esc still cancels in multi mode", askKey(base, "\x1b").cancelled === true); + const rows = renderAsk({ ...base, picked: [1] }, 60); + ok("renders checkboxes", rows.some((r) => r.includes("[x]")) && rows.some((r) => r.includes("[ ]"))); + ok("multi footer mentions space-toggle and the picked count", rows.some((r) => /space/.test(r) && /toggle/.test(r) && /1 picked/.test(r))); + ok("no multi row exceeds width", rows.every((r) => r.length <= 60)); + } + + group("ask — free-text input mode"); + { + const base = { question: "What should the new command be named?", input: true, text: "" }; + ok("a printable char appends to the field", askKey(base, "s").text === "s"); + ok("builds up the answer char by char", (() => { let a = { ...base }; for (const c of "scan") a = { ...a, text: askKey(a, c).text }; return a.text === "scan"; })()); + ok("backspace removes the last char", askKey({ ...base, text: "scan" }, "\x7f").text === "sca"); + ok("ctrl+u clears the field", askKey({ ...base, text: "scan" }, "\x15").text === ""); + ok("enter submits the typed answer", (() => { const r = askKey({ ...base, text: "scan now" }, "\r"); return r.done && r.value === "scan now"; })()); + ok("esc cancels the input", askKey({ ...base, text: "x" }, "\x1b").cancelled === true); + ok("a control byte (not backspace) is ignored", askKey({ ...base, text: "ab" }, "\x02").text === "ab"); + const empty = renderAsk(base, 50), filled = renderAsk({ ...base, text: "scan" }, 50); + ok("shows a placeholder when empty", empty.some((r) => /type your answer/.test(r))); + ok("shows the typed text with a caret", filled.some((r) => r.includes("scan") && r.includes("█"))); + ok("input footer says enter submits", filled.some((r) => /enter submit/.test(r))); + } + group("api-server input validation (shell-out routes reject injection)"); { const { isValidHostname, isSafeUrl } = require("../lib/nexus/url-guard"); From 8b3fac46169004cbacb92b08e1e05832f62ffaf7 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 15:08:12 -0700 Subject: [PATCH 04/16] nexus: give every external engine the ask_user popup via an auto-wired MCP bridge External engines run headless with their own toolset and cannot call Nexus's in-process ask_user. A tiny clean-room MCP bridge closes the gap with zero user setup: Nexus opens a local socket, the engine spawns a stdio MCP shim (ask-mcp.js) that forwards an ask_user call back over the socket, and the TUI shows the real popup (reusing renderAsk) and returns the answer. Per-engine injection (one source of truth in the engine registry): - claude: --mcp-config (live-verified via the pty harness) - codex: repeatable -c mcp_servers.* overrides - opencode: $OPENCODE_CONFIG -> a merged copy of the user's config (verified: opencode reports the nexus server connected) - gemini: $GEMINI_CLI_SYSTEM_SETTINGS_PATH -> a {mcpServers} overrides file (gemini merges mcpServers across scopes, so only nexus is added) User configs are never overwritten; only the reserved 'nexus' server is added. New: lib/nexus/ask-bridge.js, ask-mcp.js, engine-mcp.js. +31 tests (1325 pass). --- darknode.js | 63 ++++++++++++++++++-- lib/nexus/ask-bridge.js | 70 ++++++++++++++++++++++ lib/nexus/ask-mcp.js | 125 ++++++++++++++++++++++++++++++++++++++++ lib/nexus/engine-mcp.js | 88 ++++++++++++++++++++++++++++ lib/nexus/engines.js | 9 +-- test/run.js | 70 ++++++++++++++++++++++ 6 files changed, 415 insertions(+), 10 deletions(-) create mode 100644 lib/nexus/ask-bridge.js create mode 100644 lib/nexus/ask-mcp.js create mode 100644 lib/nexus/engine-mcp.js diff --git a/darknode.js b/darknode.js index 636ad05..13d5e5e 100755 --- a/darknode.js +++ b/darknode.js @@ -53,6 +53,9 @@ const { CMD_MAP } = require("./lib/cli/registry"); // data-driven command regist const { toolResultView, bootHeader, welcomeCard, idleHome, footerLine, helpLines, padRight: padRightV, ansiWrap, modelLabel, effortLabel, explainEngineError } = require("./lib/cli/tui-format"); // pure TUI layout helpers (compact boot header + model/effort display names) const Composer = require("./lib/cli/composer"); // pure composer model + key dispatch + per-project history (lib/cli/composer.js) const Ask = require("./lib/cli/ask"); // pure renderer + key reducer for the model's ask_user multiple-choice prompt (lib/cli/ask.js) +const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) +const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js +const ASK_MCP_PATH = require("path").join(__dirname, "lib", "nexus", "ask-mcp.js"); // stdio MCP shim spawned by the engine const Term = require("./lib/cli/term"); // terminal-mode registry: always restore modes, even on a hard crash (lib/cli/term.js) const Jail = require("./lib/nexus/jail"); // canonical path jail shared by every file tool (symlink/dot-dot safe) (lib/nexus/jail.js) const Redact = require("./lib/nexus/redact"); // central sink redaction + keyed placeholders (lib/nexus/redact.js) @@ -1810,15 +1813,16 @@ function killGroup(child, sig) { } // Delegate a whole task to an external agent binary (claude / opencode). Streams output; returns {ok, output}. -function runEngineTask(engine, prompt, cwd, autonomous, cont, onChunk, ctl, model, effort) { +function runEngineTask(engine, prompt, cwd, autonomous, cont, onChunk, ctl, model, effort, extra) { return new Promise((resolve) => { const m = ENGINES[engine]; // Only this engine's own args() builds its flags — nothing crosses engines. // The "local" (Ollama) engine has no CLI form and is driven separately. if (!m || !m.args || m.kind === "local") return resolve({ ok: false, output: "engine '" + engine + "' cannot run as a CLI task" }); - const cmd = m.bin, args = m.args(prompt, { cont, autonomous, model, effort }); + const cmd = m.bin, args = m.args(prompt, { cont, autonomous, model, effort, mcpServers: extra && extra.mcpServers }); let out = ""; - const p = _cp.spawn(cmd, args, { cwd, env: process.env, detached: process.platform !== "win32" }); // own process group so an interrupt kills the whole tree + const spawnEnv = (extra && extra.env) ? Object.assign({}, process.env, extra.env) : process.env; // e.g. $OPENCODE_CONFIG pointing at the Nexus ask bridge + const p = _cp.spawn(cmd, args, { cwd, env: spawnEnv, detached: process.platform !== "win32" }); // own process group so an interrupt kills the whole tree if (ctl && ctl.kids) ctl.kids.push(() => { killGroup(p, "SIGINT"); setTimeout(() => killGroup(p, "SIGKILL"), 1200); }); // ctrl+c kills this child and everything it spawned try { p.stdin.end(); } catch (_) {} // signal EOF so the CLI doesn't wait on stdin p.stdout.on("data", (d) => { const s = d.toString(); out += s; if (onChunk) onChunk(s); else if (!tuiActive) process.stdout.write(gray(" " + s.replace(/\n/g, "\n "))); }); @@ -1843,6 +1847,7 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) { if (opts.maxBudgetUsd) args.push("--max-budget-usd", String(opts.maxBudgetUsd)); if (opts.maxTurns) args.push("--max-turns", String(opts.maxTurns)); if (opts.disallow && opts.disallow.length) args.push("--disallowed-tools", ...opts.disallow); + if (opts.mcpConfigPath) args.push("--mcp-config", opts.mcpConfigPath); // give claude the Nexus ask bridge (+ any .nexus/mcp.json servers); no --strict so claude keeps its own servers too const env = opts.small ? Object.assign({}, process.env, { ANTHROPIC_SMALL_FAST_MODEL: opts.small, CLAUDE_CODE_BG_CLASSIFIER_MODEL: opts.small }) : process.env; const cp = _cp.spawn("claude", args, { cwd, env, detached: process.platform !== "win32" }); // own process group so an interrupt kills claude and its tool subprocesses try { cp.stdin.end(); } catch (_) {} // signal EOF so claude doesn't wait on stdin @@ -2801,6 +2806,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // Surgical-edit directive — a LOSSLESS token saver (no quality cost: the edit // engine errors on an ambiguous find rather than mis-applying, so a too-short // anchor just retries). Keeps diffs minimal instead of rewriting whole lines. + const ASK_ENGINE_NOTE = "\nYou can ask the operator a question via the mcp__nexus__ask_user tool — it opens a real popup in the Nexus terminal and waits for their answer (pick-one: pass options; pick-many: options + multi:true; free-text: input:true). Use it ONLY when a decision is genuinely theirs (an ambiguous requirement, a destructive/irreversible choice, picking among approaches) — never for something you can decide or look up yourself."; const TIGHT_DIR = "Surgical edits (saves tokens, no quality loss): when editing, make the old/find text the SHORTEST span that is still unique — change only what differs; never reproduce a whole line, block or function just to alter a few characters, but keep enough surrounding context to stay unambiguous. Don't paste file contents or long command output back into your reply."; const bgJobs = createBgJobs(); // long-running background commands (run_background/check_background) const fileGuard = makeFileState(); // stale-write guard: don't let a full overwrite clobber on-disk changes (persists across turns) @@ -3610,6 +3616,51 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { pendingAsk = Object.assign({ question: String(question || ""), options: options || [], sel: 0, picked: [], text: "", resolve }, extra || {}); scroll = 0; render(); }); + // ---- the ask bridge: lets an EXTERNAL engine's model raise this same popup. + // Lazily opened the first time an external engine launches; the out-of-process + // MCP shim (lib/nexus/ask-mcp.js) connects to askBridge.sockPath and forwards + // the question here, where handleBridgeAsk shows the real card and answers. ---- + let askBridge = null; + const handleBridgeAsk = async (req) => { + const q = String((req && req.question) || ""); + if (!q) return { skipped: true }; + transcript.push({ role: "system", text: gray("the model is asking: ") + oneline(q, 60) }); render(); + if (req.input) { const ans = await askUser(q, [], { input: true, placeholder: req.placeholder }); return ans.cancelled ? { skipped: true } : { answer: String(ans.value || "") }; } + const norm = Ask.normOptions(Array.isArray(req.options) ? req.options : []); + if (!norm.length) { const ans = await askUser(q, [], { input: true }); return ans.cancelled ? { skipped: true } : { answer: String(ans.value || "") }; } + if (req.multi) { const ans = await askUser(q, norm, { multi: true, picked: [] }); if (ans.cancelled) return { skipped: true }; return { selected: (ans.values || []).map((v) => (v && v.label != null) ? v.label : String(v)), indices: ans.indices || [] }; } + const ans = await askUser(q, norm); if (ans.cancelled) return { skipped: true }; return { selected: (ans.value && ans.value.label != null) ? ans.value.label : String(ans.value), index: ans.index }; + }; + const ensureAskBridge = () => { if (!askBridge) { try { askBridge = createAskServer(handleBridgeAsk); } catch (_) { askBridge = null; } } return askBridge; }; + // Build (or reuse) the per-engine MCP config: the Nexus ask bridge plus any + // servers the user configured in a trusted .nexus/mcp.json. Returns a file + // path for claude's --mcp-config, or null if the bridge couldn't open. + const engineMcpServers = () => { + const b = ensureAskBridge(); if (!b) return null; + try { return buildEngineMcpServers({ sockPath: b.sockPath, askMcpPath: ASK_MCP_PATH, userServers: loadMcpConfig(cwd) || {} }); } catch (_) { return null; } + }; + const engineMcpConfigPath = () => { const servers = engineMcpServers(); if (!servers) return null; try { return writeMcpConfigFile(path.join(cwd, ".nexus"), servers); } catch (_) { return null; } }; + // Per-engine injection of the ask bridge for the CLI engines (claude uses + // --mcp-config directly). Returns the `extra` to hand runEngineTask: codex + // takes -c overrides via mcpServers; opencode is pointed at a merged config + // file via $OPENCODE_CONFIG (the user's own opencode config is preserved). + const engineMcpLaunch = (eng) => { + const m = ENGINES[eng] || {}; + if (!engineCap(eng, "mcpInject")) return undefined; + const servers = engineMcpServers(); if (!servers) return undefined; + if (m.mcpMode === "env") { + let obj, fname; + if (m.mcpFormat === "opencode") { // opencode's own schema; merge INTO a copy of the user's project config + let base = {}; for (const f of ["opencode.json", "opencode.jsonc"]) { try { base = JSON.parse(fs.readFileSync(path.join(cwd, f), "utf8")); break; } catch (_) {} } + obj = toOpencodeConfig(servers, base); fname = "opencode.json"; + } else { // claude-style { mcpServers } (gemini's system-overrides settings file — gemini merges it, so only 'nexus' is added) + obj = { mcpServers: servers }; fname = ".gemini-settings.json"; + } + const p = writeEngineConfigFile(path.join(cwd, ".nexus"), fname, obj); + return (p && m.mcpEnvVar) ? { env: { [m.mcpEnvVar]: p } } : undefined; + } + return { mcpServers: servers }; // cArgs (codex): -c overrides via args() + }; // ---- animation loop: typewriter reveal + spinners + elapsed ---- const revealing = () => { const b = activeBlock || cur(); if (!b || !b.items) return false; return b.items.some((it) => it.type === "text" && it.shown < it.full.length); }; const startTick = () => { if (tick) return; tick = setInterval(() => { const b = activeBlock || cur(); if (b && b.items) for (const it of b.items) if (it.type === "text" && it.shown < it.full.length) { let ns = Math.min(it.full.length, it.shown + Math.max(2, Math.ceil((it.full.length - it.shown) / 22))); const cc = it.full.charCodeAt(ns - 1); if (cc >= 0xD800 && cc <= 0xDBFF && ns < it.full.length) ns++; it.shown = ns; } render(); if (!busy && !revealing() && !compact.on) { clearInterval(tick); tick = null; } }, 45); }; @@ -3745,7 +3796,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (sess.ctxUsed > compactAt()) doCompact(true); }; const onResize = () => { lastLines = null; if (!loading) render(); }; // geometry changed — force a full repaint - const cleanup = () => { if (cleaned) return; cleaned = true; tuiActive = false; if (tick) { clearInterval(tick); tick = null; } if (_rsT) { clearTimeout(_rsT); _rsT = null; } if (_drainT) { clearTimeout(_drainT); _drainT = null; } if (_escTimer) { clearTimeout(_escTimer); _escTimer = null; } if (compact.cur) { try { compact.cur.ctl.kill(); } catch (_) {} } if (ctl && ctl.kill) try { ctl.kill(); } catch (_) {} try { bgJobs.killAll(); } catch (_) {} try { if (dashServer) dashServer.close(); } catch (_) {} for (const s of mcpServers) { try { s.cp && s.cp.kill(); } catch (_) {} } try { process.stdin.setRawMode(false); } catch (_) {} process.stdin.pause(); process.stdin.removeAllListeners("data"); out.removeListener("resize", onResize); process.removeListener("exit", cleanup); process.removeListener("SIGINT", onSigint); process.removeListener("SIGTERM", onSigterm); process.removeListener("uncaughtException", onFatal); process.removeListener("unhandledRejection", onRejection); try { term.teardown(); } catch (_) {} }; + const cleanup = () => { if (cleaned) return; cleaned = true; tuiActive = false; if (tick) { clearInterval(tick); tick = null; } if (_rsT) { clearTimeout(_rsT); _rsT = null; } if (_drainT) { clearTimeout(_drainT); _drainT = null; } if (_escTimer) { clearTimeout(_escTimer); _escTimer = null; } if (compact.cur) { try { compact.cur.ctl.kill(); } catch (_) {} } if (ctl && ctl.kill) try { ctl.kill(); } catch (_) {} try { bgJobs.killAll(); } catch (_) {} try { if (dashServer) dashServer.close(); } catch (_) {} for (const s of mcpServers) { try { s.cp && s.cp.kill(); } catch (_) {} } try { askBridge && askBridge.close(); } catch (_) {} try { process.stdin.setRawMode(false); } catch (_) {} process.stdin.pause(); process.stdin.removeAllListeners("data"); out.removeListener("resize", onResize); process.removeListener("exit", cleanup); process.removeListener("SIGINT", onSigint); process.removeListener("SIGTERM", onSigterm); process.removeListener("uncaughtException", onFatal); process.removeListener("unhandledRejection", onRejection); try { term.teardown(); } catch (_) {} }; tuiActive = true; const onFatal = (e) => { const sig = e === "SIGINT" || e === "SIGTERM"; try { term.teardown(); } catch (_) {} try { cleanup(); } catch (_) {} if (e && e instanceof Error) { try { process.stderr.write("\nNexus exited on error: " + e.message + "\n"); } catch (_) {} } try { resolve(); } catch (_) {} if (sig) process.exit(0); }; const onSigint = () => onFatal("SIGINT"), onSigterm = () => onFatal("SIGTERM"); @@ -3925,7 +3976,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { addUsage(ev.modelUsage, u, sess.resolvedModel || sess.model); const mu = ev.modelUsage && ev.modelUsage[sess.model]; if (mu && mu.contextWindow) sess.ctxWindow = mu.contextWindow; }, - }, ctl, { resume: _resumeSid, model: cowork.on ? cowork.strong : ((sess.userModel && sess.model && sess.model !== engine) ? sess.model : undefined), small: cowork.on && cowork.weakKind === "claude" ? cowork.weak : undefined, effort: effort || undefined, appendSystemPrompt: ((nexusMd ? "Project (.nexus/NEXUS.md):\n" + nexusMd.slice(0, 1000) : "") + (tightEdits ? "\n" + TIGHT_DIR : "") + (minimizeCalls ? "\nMinimize tool calls: chain shell commands, read only needed lines, never re-read after write. 2-5 calls for simple tasks." : "") + (lean ? "\nTerse output, no preamble." : "") + (styleDir(style) ? "\n" + styleDir(style) : "") + (hack ? "\n" + HACK_DIR : "") + policyPrompt()) || undefined, fallbackModel: fallback || undefined, maxBudgetUsd: costCap ? Math.max(0.01, costCap - sess.cost).toFixed(2) : undefined, disallow: mode === 2 ? READONLY_TOOLS : undefined }).then(finish); + }, ctl, { resume: _resumeSid, model: cowork.on ? cowork.strong : ((sess.userModel && sess.model && sess.model !== engine) ? sess.model : undefined), small: cowork.on && cowork.weakKind === "claude" ? cowork.weak : undefined, effort: effort || undefined, appendSystemPrompt: ((nexusMd ? "Project (.nexus/NEXUS.md):\n" + nexusMd.slice(0, 1000) : "") + (tightEdits ? "\n" + TIGHT_DIR : "") + (minimizeCalls ? "\nMinimize tool calls: chain shell commands, read only needed lines, never re-read after write. 2-5 calls for simple tasks." : "") + (lean ? "\nTerse output, no preamble." : "") + (styleDir(style) ? "\n" + styleDir(style) : "") + (hack ? "\n" + HACK_DIR : "") + policyPrompt() + ASK_ENGINE_NOTE) || undefined, mcpConfigPath: engineMcpConfigPath(), fallbackModel: fallback || undefined, maxBudgetUsd: costCap ? Math.max(0.01, costCap - sess.cost).toFixed(2) : undefined, disallow: mode === 2 ? READONLY_TOOLS : undefined }).then(finish); } else if (ENGINES[engine] && ENGINES[engine].kind === "cli") { // gemini / codex / opencode / aider const eng = ENGINES[engine]; const mdl = sess.model && sess.model !== engine ? sess.model : undefined; // only pass a model the user actually chose @@ -3943,7 +3994,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { renderSoon(); }) : ((chunk) => { textItem().full += chunk; sess.liveOut += Math.ceil(chunk.length / 4); renderSoon(); }); - runEngineTask(engine, promptText, cwd, true, cont, onChunk, ctl, mdl).then((res) => { + runEngineTask(engine, promptText, cwd, true, cont, onChunk, ctl, mdl, undefined, engineMcpLaunch(engine)).then((res) => { const raw = res.output || ""; let display = raw, inD, outD; if (jsonProto) { diff --git a/lib/nexus/ask-bridge.js b/lib/nexus/ask-bridge.js new file mode 100644 index 0000000..96f96ee --- /dev/null +++ b/lib/nexus/ask-bridge.js @@ -0,0 +1,70 @@ +"use strict"; +// ============================================================================ +// ask-bridge — the Nexus-side half of letting an EXTERNAL engine (claude, codex, +// …) raise the real terminal popup. External engines run headless in their own +// process with their OWN toolset, so they can't call Nexus's in-process +// `ask_user`. The bridge closes that gap: Nexus listens on a local socket; the +// out-of-process MCP shim (ask-mcp.js, spawned by the engine) connects to it +// when the model calls the `ask_user` MCP tool, forwards the question, and this +// server shows the real popup via `onAsk` and sends the user's answer back. +// +// Line-delimited JSON, one request/response per connection is fine but the +// protocol tolerates several. No deps; Unix domain socket (or a Windows named +// pipe). Pure wiring — the popup itself lives in the host (darknode.js). +// ============================================================================ +const net = require("net"); +const os = require("os"); +const path = require("path"); +const fs = require("fs"); +const crypto = require("crypto"); + +// A short, collision-resistant socket path. Unix socket paths are length-limited +// (~104-108 bytes), so keep it in the temp dir with a compact random suffix. +function askSockPath() { + const rand = crypto.randomBytes(6).toString("hex"); + if (process.platform === "win32") return "\\\\.\\pipe\\nexus-ask-" + process.pid + "-" + rand; + return path.join(os.tmpdir(), "nexus-ask-" + process.pid + "-" + rand + ".sock"); +} + +// createAskServer(onAsk) -> { sockPath, close } +// onAsk(spec) is called with { question, options?, multi?, input?, placeholder? } +// and must resolve to a normalized answer object: +// { answer: "..." } free-text +// { selected: ["a","b"], indices:[...] } multi-select +// { selected: "a", index: 0 } single-select +// { cancelled:true } / { skipped:true } the user dismissed it +function createAskServer(onAsk) { + const sockPath = askSockPath(); + try { if (process.platform !== "win32" && fs.existsSync(sockPath)) fs.unlinkSync(sockPath); } catch (_) {} + const server = net.createServer((sock) => { + let buf = ""; + sock.setEncoding("utf8"); + sock.on("data", (d) => { + buf += d; + let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl); buf = buf.slice(nl + 1); + if (!line.trim()) continue; + let req; try { req = JSON.parse(line); } catch (_) { continue; } + const id = req.id; + Promise.resolve().then(() => onAsk(req)).then((ans) => { + try { sock.write(JSON.stringify({ id, answer: ans || { skipped: true } }) + "\n"); } catch (_) {} + }).catch((e) => { + try { sock.write(JSON.stringify({ id, error: String((e && e.message) || e) }) + "\n"); } catch (_) {} + }); + } + }); + sock.on("error", () => {}); + }); + server.on("error", () => {}); // a dead socket must never crash the TUI + try { server.listen(sockPath); } catch (_) {} + return { + sockPath, + close() { + try { server.close(); } catch (_) {} + try { if (process.platform !== "win32" && fs.existsSync(sockPath)) fs.unlinkSync(sockPath); } catch (_) {} + }, + }; +} + +module.exports = { createAskServer, askSockPath }; diff --git a/lib/nexus/ask-mcp.js b/lib/nexus/ask-mcp.js new file mode 100644 index 0000000..36d6739 --- /dev/null +++ b/lib/nexus/ask-mcp.js @@ -0,0 +1,125 @@ +#!/usr/bin/env node +"use strict"; +// ============================================================================ +// ask-mcp — a tiny, dependency-free MCP (Model Context Protocol) server, run +// out-of-process by an external engine (claude, codex, …) so its model gains +// ONE Nexus tool it otherwise can't have: `ask_user`, the real terminal popup. +// +// The engine spawns this over stdio and speaks JSON-RPC 2.0. On a tools/call we +// forward the question to the Nexus TUI over the local socket named in +// $NEXUS_ASK_SOCK (see ask-bridge.js), wait for the user's answer, and return it +// as the tool result. Everything else (initialize / tools/list) is answered +// locally. No network, no deps — clean-room MCP, same stdio framing Nexus's own +// MCP client uses. +// ============================================================================ +const net = require("net"); + +const SOCK = process.env.NEXUS_ASK_SOCK || ""; + +const ASK_TOOL = { + name: "ask_user", + description: + "Pause and ask the human operator a question in the Nexus terminal UI, then wait for their answer. " + + "Use ONLY when a real decision is genuinely theirs to make — an ambiguous requirement, a destructive or " + + "irreversible choice, or picking among approaches. Never for something you can decide or look up yourself, " + + "and never more than needed. Three forms: pick-one (pass options), pick-many (pass options and multi:true), " + + "or free-text (pass input:true with no options).", + inputSchema: { + type: "object", + properties: { + question: { type: "string", description: "The question to show the user." }, + options: { type: "array", items: { type: "string" }, description: "2-9 choices for a pick-one or pick-many question." }, + multi: { type: "boolean", description: "Allow selecting several options (checkboxes)." }, + input: { type: "boolean", description: "Free-text answer: the user types a reply (give no options)." }, + placeholder: { type: "string", description: "Short hint text for the free-text field." }, + }, + required: ["question"], + }, +}; + +function send(msg) { try { process.stdout.write(JSON.stringify(msg) + "\n"); } catch (_) {} } +function reply(id, result) { send({ jsonrpc: "2.0", id, result }); } +function replyErr(id, code, message) { send({ jsonrpc: "2.0", id, error: { code, message } }); } + +// Forward one question to the Nexus TUI and resolve with its normalized answer. +function askNexus(args) { + return new Promise((resolve, reject) => { + if (!SOCK) return reject(new Error("Nexus ask bridge is not available (no NEXUS_ASK_SOCK)")); + const sock = net.connect(SOCK); + let buf = "", done = false; + const finish = (fn, v) => { if (done) return; done = true; try { sock.end(); } catch (_) {} fn(v); }; + sock.setEncoding("utf8"); + sock.on("connect", () => { + try { + sock.write(JSON.stringify({ id: 1, question: args.question, options: args.options, multi: args.multi, input: args.input, placeholder: args.placeholder }) + "\n"); + } catch (e) { finish(reject, e instanceof Error ? e : new Error(String(e))); } + }); + sock.on("data", (d) => { + buf += d; + const nl = buf.indexOf("\n"); + if (nl < 0) return; + let resp; try { resp = JSON.parse(buf.slice(0, nl)); } catch (e) { return finish(reject, new Error("bad bridge response")); } + if (resp.error) return finish(reject, new Error(resp.error)); + finish(resolve, resp.answer); + }); + sock.on("error", (e) => finish(reject, e instanceof Error ? e : new Error(String(e)))); + sock.on("close", () => { if (!done) finish(reject, new Error("Nexus ask bridge closed before answering")); }); + }); +} + +// Render the normalized answer as plain text the model reads as its tool result. +function fmtAnswer(ans) { + if (!ans || ans.cancelled || ans.skipped) return "The user dismissed the question without answering. Decide yourself or ask differently."; + if (ans.answer != null) return "The user answered: " + String(ans.answer); + if (Array.isArray(ans.selected)) return "The user selected: " + (ans.selected.join(", ") || "(none)"); + if (ans.selected != null) return "The user chose: " + String(ans.selected); + return JSON.stringify(ans); +} + +async function handle(msg) { + const id = msg.id, method = msg.method; + if (method === "initialize") { + return reply(id, { + protocolVersion: (msg.params && msg.params.protocolVersion) || "2024-11-05", + capabilities: { tools: {} }, + serverInfo: { name: "nexus", version: "1.0.0" }, + }); + } + if (method === "tools/list") return reply(id, { tools: [ASK_TOOL] }); + if (method === "tools/call") { + const p = msg.params || {}; + if (p.name !== "ask_user") return replyErr(id, -32601, "unknown tool: " + p.name); + try { + const ans = await askNexus(p.arguments || {}); + return reply(id, { content: [{ type: "text", text: fmtAnswer(ans) }] }); + } catch (e) { + return reply(id, { content: [{ type: "text", text: "Could not reach the user: " + ((e && e.message) || e) }], isError: true }); + } + } + if (method && method.indexOf("notifications/") === 0) return; // notifications get no reply + if (id != null) return replyErr(id, -32601, "method not found: " + method); +} + +// Drive the stdio JSON-RPC loop only when run as a real MCP server (not when +// required by the test runner — attaching stdin handlers there could exit it). +function main() { + let rbuf = ""; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (d) => { + rbuf += d; + let nl; + while ((nl = rbuf.indexOf("\n")) >= 0) { + const line = rbuf.slice(0, nl); rbuf = rbuf.slice(nl + 1); + if (!line.trim()) continue; + let msg; try { msg = JSON.parse(line); } catch (_) { continue; } + handle(msg); + } + }); + process.stdin.on("end", () => process.exit(0)); + process.on("SIGINT", () => process.exit(0)); + process.on("SIGTERM", () => process.exit(0)); +} + +if (require.main === module) main(); + +module.exports = { fmtAnswer, ASK_TOOL, handle, askNexus }; // for unit tests diff --git a/lib/nexus/engine-mcp.js b/lib/nexus/engine-mcp.js new file mode 100644 index 0000000..cc9aae3 --- /dev/null +++ b/lib/nexus/engine-mcp.js @@ -0,0 +1,88 @@ +"use strict"; +// ============================================================================ +// engine-mcp — builds the MCP-server set an EXTERNAL engine (claude, codex, …) +// is launched with, so its model reaches the same tools the local engine has. +// Always includes the `nexus` ask bridge (the real popup, via ask-mcp.js talking +// back to the TUI over a socket); optionally re-declares the servers the user +// deliberately configured for Nexus (.nexus/mcp.json) so those reach the engine +// too. Bundled defaults are intentionally NOT forwarded — the engine likely has +// its own copies, and duplicate server names only cause confusion. +// ============================================================================ +const fs = require("fs"); +const path = require("path"); + +// buildEngineMcpServers({ sockPath, askMcpPath, nodePath?, userServers? }) +// -> { name: { command, args, env? }, ... } (MCP config shape) +function buildEngineMcpServers(opts) { + opts = opts || {}; + const out = {}; + const userServers = opts.userServers; + if (userServers && typeof userServers === "object") { + for (const k of Object.keys(userServers)) { + const s = userServers[k]; + if (s && s.command && k !== "nexus") out[k] = JSON.parse(JSON.stringify(s)); // 'nexus' is reserved for the ask bridge + } + } + if (opts.sockPath && opts.askMcpPath) { + out.nexus = { command: opts.nodePath || process.execPath || "node", args: [opts.askMcpPath], env: { NEXUS_ASK_SOCK: opts.sockPath } }; + } + return out; +} + +// Write a Claude-style { mcpServers: {...} } config file into `dir` and return +// its path (or null on failure). `dir` is normally the repo's .nexus/ (gitignored). +function writeMcpConfigFile(dir, servers) { + try { + fs.mkdirSync(dir, { recursive: true }); + const p = path.join(dir, ".mcp-engine.json"); + fs.writeFileSync(p, JSON.stringify({ mcpServers: servers || {} }, null, 2)); + return p; + } catch (_) { return null; } +} + +// opencode uses a different schema ({ mcp: { name: { type, command:[bin,...args], +// environment, enabled } } }) and is pointed at a config file via $OPENCODE_CONFIG +// (verified read). We merge our server INTO a copy of the user's project config so +// their own providers / models / MCP servers are preserved, never replaced. +function toOpencodeConfig(servers, baseConfig) { + const out = (baseConfig && typeof baseConfig === "object") ? JSON.parse(JSON.stringify(baseConfig)) : {}; + if (!out["$schema"]) out["$schema"] = "https://opencode.ai/config.json"; + if (!out.mcp || typeof out.mcp !== "object") out.mcp = {}; + for (const k of Object.keys(servers || {})) { + const s = servers[k]; + if (!s || !s.command) continue; + const entry = { type: "local", command: [s.command].concat(s.args || []), enabled: true }; + if (s.env && Object.keys(s.env).length) entry.environment = Object.assign({}, s.env); + out.mcp[k] = entry; + } + return out; +} + +// Write any config object into `dir/filename` and return the path (or null). +function writeEngineConfigFile(dir, filename, obj) { + try { + fs.mkdirSync(dir, { recursive: true }); + const p = path.join(dir, filename); + fs.writeFileSync(p, JSON.stringify(obj || {}, null, 2)); + return p; + } catch (_) { return null; } +} + +// Codex has no per-invocation --mcp-config flag; it takes `-c key=value` config +// overrides instead. Translate one server spec into the `-c` args that register +// it under [mcp_servers.] for this single `codex exec` run only (no global +// config mutation). Values use TOML literals (strings quoted, arrays bracketed). +function codexMcpArgs(name, spec) { + if (!spec || !spec.command) return []; + const toml = (v) => JSON.stringify(v); // JSON string/array literals are valid TOML here + const base = "mcp_servers." + name + "."; + const args = ["-c", base + "command=" + toml(spec.command)]; + if (spec.args && spec.args.length) args.push("-c", base + "args=" + toml(spec.args)); + if (spec.env && Object.keys(spec.env).length) { + const inline = "{ " + Object.keys(spec.env).map((k) => k + " = " + toml(String(spec.env[k]))).join(", ") + " }"; + args.push("-c", base + "env=" + inline); + } + return args; +} + +module.exports = { buildEngineMcpServers, writeMcpConfigFile, codexMcpArgs, toOpencodeConfig, writeEngineConfigFile }; diff --git a/lib/nexus/engines.js b/lib/nexus/engines.js index 15bab45..1726902 100644 --- a/lib/nexus/engines.js +++ b/lib/nexus/engines.js @@ -5,6 +5,7 @@ // another (verified by test/run.js). `kind`: "stream" = the Claude Code NDJSON driver // (rich token/cost/tools), "cli" = spawn the binary and stream its stdout, "local" = // the in-process Ollama tool loop. `caps` documents which cross-engine features apply. +const { codexMcpArgs } = require("./engine-mcp"); // per-run MCP `-c` overrides for codex (pure) const ENGINES = { claude: { label: "Claude Code", bin: "claude", install: "npm i -g @anthropic-ai/claude-code", kind: "stream", paid: true, ctx: 200000, model: "claude-opus-5-5", models: ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-1"], @@ -14,19 +15,19 @@ const ENGINES = { }, gemini: { label: "Gemini CLI", bin: "gemini", install: "npm i -g @google/gemini-cli", kind: "cli", proto: "gemini-json", paid: true, ctx: 1000000, model: "gemini-2.5-pro", models: ["gemini-2.5-pro", "gemini-2.5-flash"], - caps: { model: true }, + caps: { model: true, mcpInject: true }, mcpMode: "env", mcpEnvVar: "GEMINI_CLI_SYSTEM_SETTINGS_PATH", mcpFormat: "mcpServers", // system-overrides settings file; gemini MERGES mcpServers across scopes, so this only ADDS the nexus bridge (user servers kept) args: (p, o) => { const a = ["--output-format", "json"]; if (o.model) a.push("-m", o.model); if (o.autonomous) a.push("--yolo"); a.push("-p", p); return a; }, // JSON mode → real token counts (geminiParse) tips: ["Gemini's very large context window is great for whole-repo questions", "set the model with /model (e.g. gemini-2.5-pro, gemini-2.5-flash)", "needs the Gemini CLI installed and authenticated (`gemini`)"], }, codex: { label: "Codex CLI", bin: "codex", install: "npm i -g @openai/codex", kind: "cli", proto: "codex-json", paid: true, ctx: 272000, model: "gpt-5-codex", models: ["gpt-5-codex", "gpt-5", "o4-mini"], - caps: { model: true }, - args: (p, o) => { const a = ["exec", "--json", "--skip-git-repo-check"]; if (o.model) a.push("-m", o.model); if (o.autonomous) a.push("--dangerously-bypass-approvals-and-sandbox"); a.push(p); return a; }, // JSONL events → real token counts (codexParse) + caps: { model: true, mcpInject: true }, mcpMode: "cArgs", // injects via repeatable -c mcp_servers.* overrides (per run, no global config) + args: (p, o) => { const a = ["exec", "--json", "--skip-git-repo-check"]; if (o.model) a.push("-m", o.model); if (o.autonomous) a.push("--dangerously-bypass-approvals-and-sandbox"); if (o.mcpServers) for (const n of Object.keys(o.mcpServers)) a.push(...codexMcpArgs(n, o.mcpServers[n])); a.push(p); return a; }, // JSONL events → real token counts (codexParse); -c mcp_servers.* gives codex the Nexus ask bridge for this run only tips: ["Codex runs OpenAI models non-interactively via `codex exec`", "set the model with /model (e.g. gpt-5-codex, o4-mini)", "needs the Codex CLI installed and signed in"], }, opencode: { label: "OpenCode", bin: "opencode", install: "npm i -g opencode-ai", kind: "cli", paid: true, ctx: 200000, model: "", models: [], - caps: { model: true }, + caps: { model: true, mcpInject: true }, mcpMode: "env", mcpEnvVar: "OPENCODE_CONFIG", mcpFormat: "opencode", // points at a merged config (per run, user config preserved) args: (p, o) => { const a = ["run"]; if (o.model) a.push("-m", o.model); a.push(p); return a; }, tips: ["OpenCode drives whichever provider/model you've configured for it", "prefer Claude or a private local model? switch with /engine"], }, diff --git a/test/run.js b/test/run.js index a0ca98a..2fa1d8e 100644 --- a/test/run.js +++ b/test/run.js @@ -2706,6 +2706,76 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec npx.parseNmapXML(""))); } + group("engine MCP bridge — external engines get the Nexus ask_user popup"); + { + const { buildEngineMcpServers, writeMcpConfigFile, codexMcpArgs, toOpencodeConfig, writeEngineConfigFile } = require("../lib/nexus/engine-mcp"); + const { fmtAnswer, ASK_TOOL } = require("../lib/nexus/ask-mcp"); + const { createAskServer } = require("../lib/nexus/ask-bridge"); + const cp = require("child_process"); + + // --- config builder --- + const servers = buildEngineMcpServers({ sockPath: "/tmp/s.sock", askMcpPath: "/a/ask-mcp.js", nodePath: "/usr/bin/node", userServers: { github: { command: "npx", args: ["gh"] } } }); + ok("bridge always adds the 'nexus' ask server", servers.nexus && servers.nexus.command === "/usr/bin/node" && servers.nexus.args[0] === "/a/ask-mcp.js"); + ok("bridge passes the socket path via env", servers.nexus.env.NEXUS_ASK_SOCK === "/tmp/s.sock"); + ok("user-configured servers are forwarded too", servers.github && servers.github.command === "npx"); + ok("a malicious user 'nexus' override cannot shadow the bridge", buildEngineMcpServers({ sockPath: "/tmp/s.sock", askMcpPath: "/a.js", userServers: { nexus: { command: "evil" } } }).nexus.command !== "evil"); + ok("no bridge when sockPath is missing", !buildEngineMcpServers({ askMcpPath: "/a.js" }).nexus); + + const cfgDir = fs.mkdtempSync(path.join(os.tmpdir(), "nxmcpcfg-")); + const cfgPath = writeMcpConfigFile(cfgDir, servers); + ok("writeMcpConfigFile emits a { mcpServers } JSON file", cfgPath && JSON.parse(fs.readFileSync(cfgPath, "utf8")).mcpServers.nexus.command === "/usr/bin/node"); + + // --- codex -c override translation --- + const ca = codexMcpArgs("nexus", servers.nexus).join(" "); + ok("codexMcpArgs sets command/args/env as -c overrides", /mcp_servers\.nexus\.command=/.test(ca) && /mcp_servers\.nexus\.args=/.test(ca) && /mcp_servers\.nexus\.env=/.test(ca)); + ok("codexMcpArgs returns nothing for a spec with no command", codexMcpArgs("x", {}).length === 0); + ok("codex engine declares mcpInject + injects the server into its args", engineCap("codex", "mcpInject") && ENGINES.codex.mcpMode === "cArgs" && ENGINES.codex.args("P", { mcpServers: servers }).join(" ").includes("mcp_servers.nexus.command=")); + ok("non-MCP engines ignore mcpServers (no leakage)", !ENGINES.gemini.args("P", { mcpServers: servers }).join(" ").includes("mcp_servers")); + + // --- opencode: env-mode, merge into (not replace) the user's config --- + ok("opencode declares env injection mode", engineCap("opencode", "mcpInject") && ENGINES.opencode.mcpMode === "env"); + const oc = toOpencodeConfig(servers, { model: "anthropic/x", mcp: { mine: { type: "local", command: ["keep"], enabled: true } } }); + ok("opencode config preserves the user's own settings + servers", oc.model === "anthropic/x" && oc.mcp.mine && oc.mcp.mine.command[0] === "keep"); + ok("opencode config adds nexus as a local server (command is [bin,...args])", oc.mcp.nexus.type === "local" && oc.mcp.nexus.command[1] === "/a/ask-mcp.js" && oc.mcp.nexus.enabled === true); + ok("opencode config carries the socket under 'environment'", oc.mcp.nexus.environment.NEXUS_ASK_SOCK === "/tmp/s.sock"); + const ocPath = writeEngineConfigFile(cfgDir, "opencode.json", oc); + ok("writeEngineConfigFile emits valid JSON", ocPath && JSON.parse(fs.readFileSync(ocPath, "utf8")).mcp.nexus.type === "local"); + + // --- gemini: env-mode via the system-overrides settings file (gemini MERGES mcpServers, so only 'nexus' is added) --- + ok("gemini declares env injection via GEMINI_CLI_SYSTEM_SETTINGS_PATH", engineCap("gemini", "mcpInject") && ENGINES.gemini.mcpMode === "env" && ENGINES.gemini.mcpEnvVar === "GEMINI_CLI_SYSTEM_SETTINGS_PATH" && ENGINES.gemini.mcpFormat === "mcpServers"); + const gmPath = writeEngineConfigFile(cfgDir, ".gemini-settings.json", { mcpServers: servers }); + const gm = JSON.parse(fs.readFileSync(gmPath, "utf8")); + ok("gemini settings file carries mcpServers.nexus with the bridge socket", gm.mcpServers.nexus.command === "/usr/bin/node" && gm.mcpServers.nexus.env.NEXUS_ASK_SOCK === "/tmp/s.sock"); + ok("gemini settings file contains ONLY mcpServers (nothing to override user settings)", Object.keys(gm).length === 1 && gm.mcpServers); + ok("gemini still gets no mcp flags leaked into its argv", !ENGINES.gemini.args("P", { mcpServers: servers }).join(" ").includes("mcp")); + + // --- MCP shim answer formatting (what the model reads back) --- + ok("fmtAnswer: free-text", fmtAnswer({ answer: "yes do it" }) === "The user answered: yes do it"); + ok("fmtAnswer: single pick", fmtAnswer({ selected: "Option B", index: 1 }) === "The user chose: Option B"); + ok("fmtAnswer: multi pick", fmtAnswer({ selected: ["A", "C"], indices: [0, 2] }) === "The user selected: A, C"); + ok("fmtAnswer: dismissed/skip", /dismissed the question/.test(fmtAnswer({ skipped: true })) && /dismissed the question/.test(fmtAnswer(null))); + ok("ask_user tool schema requires a question", ASK_TOOL.name === "ask_user" && ASK_TOOL.inputSchema.required.includes("question")); + + // --- real end-to-end: the stdio shim forwards a tools/call to the bridge and returns the user's answer --- + await new Promise((resolve) => { + const srv = createAskServer(async (req) => req.input ? { answer: "typed!" } : { selected: (req.options || [])[1], index: 1 }); + const shim = cp.spawn(process.execPath, [path.join(__dirname, "..", "lib", "nexus", "ask-mcp.js")], { env: Object.assign({}, process.env, { NEXUS_ASK_SOCK: srv.sockPath }), stdio: ["pipe", "pipe", "ignore"] }); + let out = ""; + shim.stdout.on("data", (d) => { out += d.toString(); }); + const send = (o) => shim.stdin.write(JSON.stringify(o) + "\n"); + send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05" } }); + send({ jsonrpc: "2.0", id: 2, method: "tools/list" }); + send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "ask_user", arguments: { question: "Pick", options: ["x", "y", "z"] } } }); + setTimeout(() => { + const byId = {}; for (const l of out.trim().split("\n").filter(Boolean)) { try { const m = JSON.parse(l); byId[m.id] = m; } catch (_) {} } + ok("shim initialize → serverInfo name 'nexus'", byId[1] && byId[1].result.serverInfo.name === "nexus"); + ok("shim tools/list → ask_user", byId[2] && byId[2].result.tools[0].name === "ask_user"); + ok("shim tools/call → forwards to the bridge and returns the user's pick", byId[3] && /The user chose: y/.test(byId[3].result.content[0].text)); + try { shim.kill(); } catch (_) {} srv.close(); resolve(); + }, 800); + }); + } + console.log("\n" + (fail ? "\x1b[31m" : "\x1b[32m") + pass + " passed, " + fail + " failed\x1b[0m"); process.exit(fail ? 1 : 0); })(); From 9ce7f3ebf59c6412e025b47c09e2329a683b8d0f Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 16:19:29 -0700 Subject: [PATCH 05/16] nexus: dashboard activity cards, /session command, and three TUI fixes - dashboard: live Files changed, Tools used (proportional bars) and Uptime, fed by per-session file/tool/start accumulators in the turn-finish path - /session (alias /activity): terminal view of uptime, turns, tokens, tools and files changed, registered in the command list - fix: composer now scrolls to follow the caret up a tall draft (editing an earlier wrapped line no longer hides the text and the cursor) - fix: async slash-command output (/agents, /race, /review, /fix, /dream, ...) now attaches to its own transcript block via ensureText(block) instead of cur(), so an intervening system message can't steal or hide the result - fix: a held Backspace batch is no longer swallowed when a stray ESC report collides with it during a slow /restart (do not glue ESC onto a control run) --- darknode.js | 57 ++++++++++++++++++++++++++++-------------- lib/nexus/dashboard.js | 22 +++++++++++++++- 2 files changed, 59 insertions(+), 20 deletions(-) diff --git a/darknode.js b/darknode.js index 13d5e5e..8c3a65a 100755 --- a/darknode.js +++ b/darknode.js @@ -2653,6 +2653,9 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (S.model && engine === "claude") { sess.model = S.model; sess.userModel = true; } // restore the saved /model choice (the init event replaces it with the resolved id) const READONLY_TOOLS = ["Write", "Edit", "MultiEdit", "NotebookEdit", "Bash"]; // disallowed to enforce read-only (plan mode / /bench) const impact = { localTurns: 0, cloudTurns: 0, localTok: 0, cloudInTok: 0, cloudOutTok: 0, cloudCost: 0, ctxSavedTok: 0, coworkSaved: 0, delegated: 0, cachedHits: 0, cachedSaved: 0, squeezeTok: 0 }; // Impact Receipt tallies + const sessStart = Date.now(); // wall-clock start of this TUI session (dashboard uptime) + const sessFiles = new Set(); // every repo-relative file the agent touched this session (for the dashboard) + const toolUse = Object.create(null); // tool name -> call count this session (for the dashboard) let cacheOn = !!S.cache; // response cache: serve exact-repeat read-only answers for free (off by default — opt in with /cache on) let cowork = { on: false, strong: "", weak: "", weakKind: "claude" }; // strong codes, weak does cheap work; weakKind: claude|ollama(local, free) const auxModel = () => (cowork.on && cowork.weakKind === "claude" && engine === "claude") ? cowork.weak : undefined; // weak CLAUDE model for aux calls @@ -2738,7 +2741,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { ["/undo", "revert the last turn's file changes"], ["/rewind", "restore a specific checkpoint (/rewind N)"], ["/checkpoints", "list undo checkpoints"], ["/invariants", "diff-lint the pending diff against .nexus/invariants.json"], ["/attest", "capability manifest from the hash-chained audit log"], ["/bisect", "find the turn that broke the test (/bisect [test cmd])"], ["/whatbroke", "instant blame: which turn most likely broke a failing test"], ["/shrink", "delta-debug the edits to the minimal breaking file set (/shrink [test cmd])"], ["/resume", "reload the last saved session"], ["/branch", "fork & switch conversation branches (/branch new )"], ["/export", "save the conversation to a markdown file"], ["/copy", "copy the last reply to the clipboard"], - ["/status", "session engine, model, tokens & cost"], ["/doctor", "check engines & tools are available"], ["/init", "scaffold .nexus/ in this project"], + ["/status", "session engine, model, tokens & cost"], ["/session", "this session's uptime, files changed & tools used"], ["/doctor", "check engines & tools are available"], ["/init", "scaffold .nexus/ in this project"], ["/model", "pick the model — lists the engine catalog; /model "], ["/engine", "switch AI: claude · gemini · codex · opencode · aider · ollama"], ["/commands", "list custom project commands"], ["/agents", "run tasks in parallel: /agents a ;; b ;; c"], ["/mcp", "list / connect MCP servers"], ["/hooks", "show configured tool hooks"], ["/race", "run a prompt on every engine at once"], ["/review", "second opinion from a different engine"], ["/codereview", "AI review of your changes for real bugs · /codereview [file|branch|PR#] [--fix]"], ["/redo", "reapply an undone change"], @@ -2928,7 +2931,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const resultText = (c) => { if (c == null) return ""; if (typeof c === "string") return c; if (Array.isArray(c)) return c.map((x) => (x && x.text) || (typeof x === "string" ? x : "")).join(" "); return String(c); }; // ---- transcript block accessors ---- const cur = () => transcript[transcript.length - 1]; - const ensureText = () => { const b = cur(); if (!b.items) b.items = []; let last = b.items[b.items.length - 1]; if (!last || last.type !== "text") { last = { type: "text", full: "", shown: 0 }; b.items.push(last); } return last; }; + const ensureText = (b) => { if (!b) b = cur(); if (!b.items) b.items = []; let last = b.items[b.items.length - 1]; if (!last || last.type !== "text") { last = { type: "text", full: "", shown: 0 }; b.items.push(last); } return last; }; // ---- render body ---- const spin = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; // Darknode logo — the official 2x2 mark (four navy rounded boxes, one yellow). @@ -3542,7 +3545,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { } frame.push(_bd(_rule)); } - const _showStart = Math.max(0, wrapped.length - inRows); + let _showStart = Math.max(0, wrapped.length - inRows); + if (_cLine < _showStart) _showStart = _cLine; // follow the caret up: editing an earlier line of a tall draft must keep that line (and the cursor) on screen const shown = wrapped.slice(_showStart); for (let i = 0; i < inRows; i++) { const raw = shown[i] || ""; const li = _showStart + i; @@ -3890,6 +3894,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (PAID[engine]) { impact.cloudTurns++; impact.cloudInTok += Math.max(0, din); impact.cloudOutTok += Math.max(0, dout); impact.cloudCost += Math.max(0, dcost); } else { impact.localTurns++; impact.localTok += Math.max(0, din + dout); } // Chargeback ledger: one non-sensitive metrics line per turn (no prompt text, no paths). try { appendUsage(cwd, { ts: new Date().toISOString(), operator: ident.operator, team: ident.team, engine, model: sess.model || engine, mode: ["normal", "auto", "plan"][mode] || "normal", inTok: Math.max(0, din), outTok: Math.max(0, dout), cost: Math.max(0, dcost), seconds: +dt, files: stat.files.size, commands: stat.cmds, interrupted: !!(res && res.interrupted) }); } catch (_) {} + for (const p of stat.paths) if (p) sessFiles.add(p); // accumulate session-wide file + tool activity for the dashboard + for (const it of block.items) if (it.type === "tool" && it.name) toolUse[it.name] = (toolUse[it.name] || 0) + 1; const bits = []; const recap = []; if (stat.files.size) { bits.push(stat.files.size + " file" + (stat.files.size > 1 ? "s" : "")); recap.push((res && res.interrupted ? "Touched" : "Wrote") + " " + [...stat.files].slice(0, 4).join(", ") + (stat.files.size > 4 ? " +" + (stat.files.size - 4) + " more" : "")); } @@ -4212,7 +4218,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { startTick(); render(); const agentsCtl = ctl; const pick = (cowork.on && engine === "claude" && cowork.weakKind === "claude") ? ((t) => { const est = Math.ceil(t.length / 4) + 800; if (isMechanical(t) && shouldDelegate(est, est * 4, cowork.strong, cowork.weak)) { impact.delegated++; impact.coworkSaved += (priceOf(cowork.strong).out - priceOf(cowork.weak).out) * (est * 3) / 1e6; return cowork.weak; } return cowork.strong; }) : (cowork.on && engine === "claude" ? ((t) => cowork.strong) : null); (async () => { const mdl = engine === "ollama" ? (sess.model && sess.model !== engine ? sess.model : pickCoderModel(await ollamaTags())) : sess.model; return runSubagents(engine, tasks, cwd, mdl, (i, phase) => { if (phase === "done") { cards[i].status = "ok"; cards[i].end = Date.now(); activeAgents = Math.max(0, activeAgents - 1); } render(); }, agentsCtl, pick); })() .then((outs) => { - const t = ensureText(); + const t = ensureText(block); t.full = outs.map((o, i) => "### agent " + (i + 1) + " — " + oneline(tasks[i], 60) + "\n" + (o || "(no output)")).join("\n\n"); for (const c of cards) if (c.status === "run") { c.status = "ok"; c.end = Date.now(); } sess.outTok += Math.ceil(outs.join("").length / 4); sess.ctxUsed = sess.inTok + sess.outTok; @@ -4244,7 +4250,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { }; Promise.all(race.map(racer)).then((res) => { res.sort((a, b) => a.ms - b.ms); - ensureText().full = res.map((r, i) => "### " + (i === 0 ? "fastest — " : "") + r.e + " (" + fmtDur(r.ms / 1000) + ")\n" + (r.out || "(no output)")).join("\n\n"); + ensureText(block).full = res.map((r, i) => "### " + (i === 0 ? "fastest — " : "") + r.e + " (" + fmtDur(r.ms / 1000) + ")\n" + (r.out || "(no output)")).join("\n\n"); busy = false; ctl = null; block.summary = race.length + " engines raced · " + fmtDur((Date.now() - t0) / 1000); try { saveSession(); } catch (_) {} render(); }).catch(() => { busy = false; ctl = null; render(); }); }; @@ -4261,7 +4267,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { block.items.push(card); startTick(); render(); (async () => { let out; try { if (re === "ollama") { const mdl = pickCoderModel(await ollamaTags()); out = await ollamaChat(mdl, [{ role: "user", content: prompt }], undefined, aSignal(ctl)); } else { out = (await runEngineTask(re, prompt, cwd, false, false, null, ctl)).output; } } catch (e) { out = "error: " + e.message; } - card.status = "ok"; card.end = Date.now(); ensureText().full = "second opinion (" + re + "):\n\n" + (out || "(no output)").trim(); busy = false; ctl = null; try { saveSession(); } catch (_) {} render(); + card.status = "ok"; card.end = Date.now(); ensureText(block).full = "second opinion (" + re + "):\n\n" + (out || "(no output)").trim(); busy = false; ctl = null; try { saveSession(); } catch (_) {} render(); })(); }; // /ultrareview — a rigorous, multi-lens review of the working diff (correctness, @@ -4277,13 +4283,13 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { (async () => { let diff = ""; let src = "working tree"; try { let d = await sh(["diff", "--no-color"]); diff = (d.stdout || "").trim(); if (!diff) { d = await sh(["diff", "--cached", "--no-color"]); diff = (d.stdout || "").trim(); src = "staged"; } if (!diff) { d = await sh(["diff", "--no-color", "HEAD~1"]); diff = (d.stdout || "").trim(); src = "last commit"; } } catch (_) {} - if (!diff) { card.status = "err"; card.end = Date.now(); ensureText().full = "nothing to review — no working, staged, or last-commit changes found (make some edits first)"; busy = false; ctl = null; render(); return; } + if (!diff) { card.status = "err"; card.end = Date.now(); ensureText(block).full = "nothing to review — no working, staged, or last-commit changes found (make some edits first)"; busy = false; ctl = null; render(); return; } const prompt = buildReviewPrompt(diff); let out; try { if (re === "ollama") { const mdl = pickCoderModel(await ollamaTags()); out = await ollamaChat(mdl, [{ role: "user", content: prompt }], undefined, aSignal(ctl)); } else { out = (await runEngineTask(re, prompt, cwd, false, false, null, ctl)).output; } } catch (e) { out = "error: " + e.message; } out = (out || "(no output)").trim(); const sv = countBySeverity(out); const tally = SEVERITY.filter((s) => sv[s]).map((s) => (s === "critical" || s === "high" ? red : s === "medium" ? yellow : gray)(sv[s] + " " + s)).join(gray(" · ")); card.status = "ok"; card.end = Date.now(); - ensureText().full = bold("ultrareview") + gray(" " + re + " · " + src) + (tally ? " " + tally : " " + green("no issues flagged")) + "\n\n" + out; + ensureText(block).full = bold("ultrareview") + gray(" " + re + " · " + src) + (tally ? " " + tally : " " + green("no issues flagged")) + "\n\n" + out; busy = false; ctl = null; try { saveSession(); } catch (_) {} render(); })(); }; @@ -4306,7 +4312,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const sp = res.length + " candidate answers. Combine strengths, fix mistakes, return ONLY the best answer.\n\nQ: " + prompt + "\n\n" + res.map((r, i) => "==" + (i + 1) + " (" + r.e + ")==\n" + r.o).join("\n\n"); let best; try { best = await engineAnswer(se, sp); } catch (_) { best = res[0] && res[0].o; } synth.status = "ok"; synth.end = Date.now(); - ensureText().full = "best-of-" + res.length + " (synthesized by " + se + "):\n\n" + (best || "(no output)").trim(); + ensureText(block).full = "best-of-" + res.length + " (synthesized by " + se + "):\n\n" + (best || "(no output)").trim(); busy = false; ctl = null; block.summary = res.length + " engines + synthesis · " + fmtDur((Date.now() - t0) / 1000); try { saveSession(); } catch (_) {} render(); }).catch(() => { busy = false; ctl = null; render(); }); }; @@ -4329,7 +4335,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const pad = (s, n) => (s + " ".repeat(n)).slice(0, n); let tbl = pad("engine", 10) + pad("time", 9) + pad("in", 8) + pad("out", 8) + "cost\n"; for (const r of res) tbl += pad(r.e + (r.e === fastest ? " *" : ""), 10) + pad(fmtDur(r.ms / 1000), 9) + pad((r.real ? "" : "~") + fmtK(r.inTok), 8) + pad((r.real ? "" : "~") + fmtK(r.outTok), 8) + (r.real ? (r.cost ? "$" + r.cost.toFixed(4) : "-") : "free") + "\n"; - ensureText().full = "benchmark (* = fastest; ~ = estimated; claude tokens/cost are real):\n\n" + tbl; + ensureText(block).full = "benchmark (* = fastest; ~ = estimated; claude tokens/cost are real):\n\n" + tbl; busy = false; ctl = null; block.summary = res.length + " engines benchmarked · " + fmtDur((Date.now() - t0) / 1000); try { saveSession(); } catch (_) {} render(); }).catch(() => { busy = false; ctl = null; render(); }); }; @@ -4344,7 +4350,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { let tasks = []; try { if (cowork.on) { const raw = await weakChat("Break this GOAL into an ordered list of 5-15 concrete, independently-verifiable tasks. Return ONLY a JSON array of short task strings.\n\nGOAL: " + goal + (nexusMd ? "\n\nPROJECT:\n" + nexusMd.slice(0, 1000) : "")); const arr = extractJson(raw, null); tasks = (Array.isArray(arr) && arr.length ? arr : [goal]).slice(0, 20).map((t, i) => ({ title: String(t).slice(0, 300) })); } else tasks = await planGoal(engine, mdl, goal, nexusMd); } catch (_) {} plan = (tasks || []).map((t) => ({ text: String(t.title || t).slice(0, 300), done: false })); savePlan(); card.status = "ok"; card.end = Date.now(); - ensureText().full = "planned " + plan.length + " task(s). /plan run to execute · /plan done to check off · /plan add to add."; + ensureText(block).full = "planned " + plan.length + " task(s). /plan run to execute · /plan done to check off · /plan add to add."; busy = false; ctl = null; transcript.push({ role: "plan" }); try { saveSession(); } catch (_) {} render(); })(); }; @@ -4364,7 +4370,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { try { if (delegate) { await weakTask(t.text); } else if (engine === "ollama") { const mdl = sess.model && sess.model !== engine ? sess.model : pickCoderModel(await ollamaTags()); await ollamaExec(mdl, t.text, "", cwd, aSignal(ctl)); } else { await runEngineTask(engine, t.text, cwd, true, false, null, ctl, cowork.on && engine === "claude" ? cowork.strong : undefined); } } catch (_) {} t.running = false; t.done = true; savePlan(); card.status = "ok"; card.end = Date.now(); activeAgents = 0; render(); } - ensureText().full = plan.every((t) => t.done) ? "all plan tasks completed." : "stopped — some tasks remain (/plan run to resume)."; + ensureText(block).full = plan.every((t) => t.done) ? "all plan tasks completed." : "stopped — some tasks remain (/plan run to resume)."; busy = false; ctl = null; transcript.push({ role: "plan" }); try { saveSession(); } catch (_) {} maybeAutoCompact(); render(); })(); }; @@ -4381,16 +4387,16 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { attempts = att; const rc = { type: "tool", id: "wr" + att, name: "Bash", label: "Bash(" + oneline(command, 40) + ")", status: "run", start: Date.now() }; block.items.push(rc); render(); const r = await coderShell(command, cwd); rc.status = r.code === 0 ? "ok" : "err"; rc.end = Date.now(); rc.detail = oneline(r.output, 260); render(); - if (r.code === 0) { const t = ensureText(); t.full += (t.full ? "\n" : "") + "command passed on attempt " + att + "."; passed = true; break; } + if (r.code === 0) { const t = ensureText(block); t.full += (t.full ? "\n" : "") + "command passed on attempt " + att + "."; passed = true; break; } if (att === 5) break; - const t = ensureText(); t.full += (t.full ? "\n" : "") + "attempt " + att + " failed — asking " + engine + " to fix…"; render(); + const t = ensureText(block); t.full += (t.full ? "\n" : "") + "attempt " + att + " failed — asking " + engine + " to fix…"; render(); const fc = { type: "tool", id: "wf" + att, name: "Task", label: "Task(fix attempt " + att + ")", status: "run", start: Date.now() }; block.items.push(fc); activeAgents = 1; render(); const fixPrompt = "The command `" + command + "` is failing. Its output was:\n\n" + (r.output || "").slice(-3000) + "\n\nEdit the code so the command passes. Make the file edits now — do not ask questions."; try { if (engine === "ollama") { const mdl = sess.model && sess.model !== engine ? sess.model : pickCoderModel(await ollamaTags()); await ollamaExec(mdl, fixPrompt, "", cwd, aSignal(ctl)); } else { await runEngineTask(engine, fixPrompt, cwd, true, false, null, ctl); } } catch (_) {} fc.status = "ok"; fc.end = Date.now(); activeAgents = 0; render(); } for (const it of block.items) if (it.status === "run") { it.status = "ok"; it.end = Date.now(); } - const t = ensureText(); t.full += (passed ? "\n\nAll green." : "\n\nStill failing after " + attempts + " attempt(s) — review the output above."); + const t = ensureText(block); t.full += (passed ? "\n\nAll green." : "\n\nStill failing after " + attempts + " attempt(s) — review the output above."); busy = false; ctl = null; block.summary = "watch · " + attempts + " attempt(s) · " + fmtDur((Date.now() - t0) / 1000) + (ck ? " · undo #" + checkpoints.length : ""); try { saveSession(); } catch (_) {} maybeAutoCompact(); render(); })(); @@ -4409,7 +4415,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { msg = (msg || "").replace(/```[a-z]*\n?|```/g, "").trim().split("\n").slice(0, 8).join("\n").trim() || "chore: update"; card.status = "ok"; card.end = Date.now(); let done = false; try { const subj = msg.split("\n")[0], body = msg.split("\n").slice(1).join("\n").trim(); _cp.execSync("git commit -m " + JSON.stringify(subj) + (body ? " -m " + JSON.stringify(body) : ""), { cwd, stdio: "ignore" }); done = true; } catch (_) {} - ensureText().full = (done ? "committed:\n\n" : "generated message (commit failed — commit manually):\n\n") + msg; + ensureText(block).full = (done ? "committed:\n\n" : "generated message (commit failed — commit manually):\n\n") + msg; busy = false; ctl = null; try { saveSession(); } catch (_) {} render(); })(); }; @@ -4436,7 +4442,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { try { out = _cp.execSync("gh pr create --title " + JSON.stringify(title) + " --body " + JSON.stringify(body || title) + " 2>&1", { cwd, encoding: "utf8" }).trim(); opened = /https?:\/\//.test(out); } catch (e) { out = ((e.stdout || "") + (e.stderr || "") || e.message || "").toString().trim(); } } - ensureText().full = opened + ensureText(block).full = opened ? "pull request opened:\n" + out : (hasBin("gh") ? "gh couldn't open the PR (" + out.slice(0, 200) + ") — title & body below:\n\n" : "gh CLI not installed — PR title & body (create it manually):\n\n") + title + "\n\n" + body; busy = false; ctl = null; try { saveSession(); } catch (_) {} render(); @@ -4546,6 +4552,9 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { plan: plan.map((p) => ({ text: p.text || p.title || "", done: !!p.done, running: !!p.running })), pipelines: pipeInfo(), activity: dashActivity(), + files: [...sessFiles].slice(-80), + tools: Object.keys(toolUse).map((k) => ({ name: k, n: toolUse[k] })).sort((a, b) => b.n - a.n).slice(0, 24), + elapsed: Math.round((Date.now() - (sessStart || Date.now())) / 1000), }); const handleSlash = (t) => { @@ -4658,6 +4667,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { else if (cmd === "/agents" || cmd === "/parallel") { const tasks = argstr.split(/\s*;;\s*/).map((s) => s.trim()).filter(Boolean); if (tasks.length < 2) transcript.push({ role: "system", text: "usage: /agents ;; ;; … — runs each task in parallel on the " + engine + " engine, each in its own isolated git worktree, then merges the changes back" }); else spawnAgents(tasks); } else if (cmd === "/hooks") { transcript.push({ role: "system", text: hooks ? ("hooks (.nexus/hooks.json) active for events: " + Object.keys(hooks).join(", ") + "\n PreToolUse/PostToolUse run for the local engine; UserPromptSubmit & Stop run for every engine") : "no hooks configured. Create .nexus/hooks.json:\n { \"PreToolUse\": [ { \"matcher\": \"run_command|write_file\", \"command\": \"echo $TOOL_NAME >> .nexus/audit.log\" } ] }\n events: UserPromptSubmit · PreToolUse · PostToolUse · Stop (non-zero exit on PreToolUse/UserPromptSubmit blocks the action)" }); } else if (cmd === "/status") transcript.push({ role: "system", text: "status:\n engine " + engine + (sess.model && sess.model !== engine ? " (" + sess.model + ")" : "") + "\n dir " + cwd + "\n mode " + MODES[mode].k + "\n context " + Math.round((sess.ctxUsed / (sess.ctxWindow || 1)) * 100) + "% of " + fmtK(sess.ctxWindow) + "\n tokens ↑" + fmtK(sess.inTok) + " ↓" + fmtK(sess.outTok) + (PAID[engine] ? (sess.cost ? " · $" + sess.cost.toFixed(4) : " · billed") : " · local · free") + "\n budget " + (costCap ? "$" + costCap.toFixed(2) + " cap" : "none") + "\n undo " + checkpoints.length + " checkpoint(s)" }); + else if (cmd === "/session" || cmd === "/activity") { const fl = [...sessFiles]; const tl = Object.keys(toolUse).map((k) => ({ name: k, n: toolUse[k] })).sort((a, b) => b.n - a.n); const up = fmtDur(Math.max(0, (Date.now() - sessStart) / 1000)); const turnCount = transcript.filter((m) => m.role === "user").length; const toolLine = tl.length ? tl.slice(0, 12).map((t) => t.name + " ×" + t.n).join(", ") : "none yet"; const fileLine = fl.length ? fl.slice(-12).join("\n ") : "none yet"; transcript.push({ role: "system", text: "session:\n uptime " + up + "\n turns " + turnCount + "\n tokens ↑" + fmtK(sess.inTok) + " ↓" + fmtK(sess.outTok) + (PAID[engine] ? (sess.cost ? " · $" + sess.cost.toFixed(4) : " · billed") : " · local · free") + "\n tools " + toolLine + "\n files " + fileLine + (fl.length > 12 ? "\n …and " + (fl.length - 12) + " more" : "") + "\n\n the live web view (/dashboard) shows these updating in real time" }); } else if (cmd === "/update") { const apply = /\b(apply|now|-y|yes)\b/.test(argstr); transcript.push({ role: "system", text: (apply ? "" : "checking for updates…\n") + nexusUpdate({ apply }) }); } else if (cmd === "/autoupdate") { const a = (argstr || "").trim().toLowerCase(); @@ -5087,7 +5097,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { let out = ""; try { out = cowork.on ? await weakChat(dreamPrompt) : await engineAnswer(offline ? "ollama" : engine, dreamPrompt); } catch (_) {} const bullets = (out || "").split("\n").map((l) => l.trim()).filter((l) => /^[-*]\s/.test(l)).map((l) => l.replace(/^[*]\s/, "- ")); card.status = "ok"; card.end = Date.now(); - if (bullets.length) { try { const md = path.join(cwd, ".nexus", "NEXUS.md"); fs.mkdirSync(path.join(cwd, ".nexus"), { recursive: true }); let c = ""; try { c = fs.readFileSync(md, "utf8"); } catch (_) {} if (!/\n##\s*Notes/.test(c)) c += (c && !c.endsWith("\n") ? "\n" : "") + "\n## Notes\n"; const lc = c.toLowerCase(); const added = []; for (const b of bullets) { const key = b.toLowerCase().replace(/[^a-z0-9 ]/g, "").slice(0, 28); if (key.length > 8 && !lc.includes(key)) { c += b + "\n"; added.push(b); } } fs.writeFileSync(md, c); ensureText().full = added.length ? ("consolidated " + added.length + " new fact(s) into .nexus/NEXUS.md:\n\n" + added.join("\n")) : "reviewed the session — everything's already in NEXUS.md"; } catch (e) { ensureText().full = "could not write memory: " + e.message; } } else ensureText().full = "no durable facts found to consolidate."; + if (bullets.length) { try { const md = path.join(cwd, ".nexus", "NEXUS.md"); fs.mkdirSync(path.join(cwd, ".nexus"), { recursive: true }); let c = ""; try { c = fs.readFileSync(md, "utf8"); } catch (_) {} if (!/\n##\s*Notes/.test(c)) c += (c && !c.endsWith("\n") ? "\n" : "") + "\n## Notes\n"; const lc = c.toLowerCase(); const added = []; for (const b of bullets) { const key = b.toLowerCase().replace(/[^a-z0-9 ]/g, "").slice(0, 28); if (key.length > 8 && !lc.includes(key)) { c += b + "\n"; added.push(b); } } fs.writeFileSync(md, c); ensureText(block).full = added.length ? ("consolidated " + added.length + " new fact(s) into .nexus/NEXUS.md:\n\n" + added.join("\n")) : "reviewed the session — everything's already in NEXUS.md"; } catch (e) { ensureText(block).full = "could not write memory: " + e.message; } } else ensureText(block).full = "no durable facts found to consolidate."; busy = false; ctl = null; try { saveSession(); } catch (_) {} render(); })(); } else if (cmd === "/plan") { const s = arg; @@ -5693,7 +5703,16 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // next chunk onto it; if nothing follows, deliver it as a real Esc. if (_escHold) { _escHold = false; if (_escTimer) { clearTimeout(_escTimer); _escTimer = null; } - if (s.charCodeAt(0) !== 27) s = "\x1b" + s; // ESC + body → whole sequence + // Glue the held ESC onto this chunk ONLY if it's the body of ONE split + // escape sequence (CSI "[…", SS3 "O…", or a single Alt+ like \x1b\r). + // A MULTI-byte run of control bytes is NOT an escape body — e.g. a held + // Backspace batch ("\x7f\x7f…") buffered during a slow /restart while the + // terminal also emits a report (lone ESC): gluing made "\x1b\x7f\x7f…", + // which keymap can't match and the printable guard drops, so every + // backspace was silently swallowed. Deliver the held ESC on its own and + // let the batch fall through to the control-run splitter below. + const _escBatch = s.length > 1 && /^[\x00-\x08\x0b\x0c\x0e-\x1a\x1c-\x1f\x7f]+$/.test(s); + if (s.charCodeAt(0) !== 27 && !_escBatch) s = "\x1b" + s; // ESC + body → whole sequence else { try { _escFlushing = true; process.stdin.emit("data", "\x1b"); } finally { _escFlushing = false; } } // held ESC was standalone; deliver it, then process this new chunk } else if (s === "\x1b" && !_escFlushing) { _escHold = true; _escTimer = setTimeout(() => { _escHold = false; _escTimer = null; try { _escFlushing = true; process.stdin.emit("data", "\x1b"); } finally { _escFlushing = false; } }, 40); diff --git a/lib/nexus/dashboard.js b/lib/nexus/dashboard.js index 6d44990..638de0c 100644 --- a/lib/nexus/dashboard.js +++ b/lib/nexus/dashboard.js @@ -110,6 +110,8 @@ const PAGE = `

Cowork

Background jobs

Pipelines

+

Files changed

+

Tools used

Recent activity

Nexus dashboard · localhost only
@@ -120,6 +122,7 @@ const PAGE = ` var $=function(id){return document.getElementById(id)}; var liveDot=$("live"), conn=$("conn"); var misses=0; function fmtK(n){n=+n||0; if(n<1000)return String(n); if(n<1e6)return (n/1e3).toFixed(n<1e4?1:0)+"k"; return (n/1e6).toFixed(1)+"m";} + function fmtDur(s){s=+s||0; if(s<60)return s+"s"; var m=Math.floor(s/60); if(m<60)return m+"m "+(s%60)+"s"; var h=Math.floor(m/60); return h+"h "+(m%60)+"m";} function badge(s){s=(s||"").toLowerCase(); if(s==="done"||s==="ok")return "ok"; if(s==="running"||s==="run")return "run"; if(s==="killed"||s==="error"||s==="bad")return "killed"; return "";} function setLive(on){ liveDot.className="dot"+(on?" live":""); conn.textContent=on?"live":"reconnecting"; } @@ -140,7 +143,8 @@ const PAGE = ` ["Context", ""+ctxPct+"% of "+fmtK(s.ctxWindow)+"
"], ["Jobs running", ""+(s.jobsRunning||0)+" of "+(s.jobs?s.jobs.length:0)+""], ["Agents", ""+(s.agents||0)+" active"], - ["Saved by cowork", "$"+((s.impact&&s.impact.coworkSaved)||0).toFixed(3)+""] + ["Saved by cowork", "$"+((s.impact&&s.impact.coworkSaved)||0).toFixed(3)+""], + ["Uptime", ""+fmtDur(s.elapsed||0)+""] ]; $("stats").innerHTML = stats.map(function(x){return "
"+x[0]+"
"+x[1]+"
";}).join(""); @@ -177,6 +181,22 @@ const PAGE = ` ? "
"+esc(s.pipelines.text)+"
" : "
"+(s.pipelines&&s.pipelines.engine===false ? "No pipeline engine configured." : "No pipeline activity.")+"
"; + // files changed + var files=s.files||[]; + $("files-n").textContent = files.length ? String(files.length) : ""; + $("files").innerHTML = files.length ? files.slice().reverse().map(function(f){ + return "
"+esc(f)+"
"; + }).join("") : "
No files changed yet this session.
"; + + // tools used (proportional bars) + var tools=s.tools||[]; var maxN=tools.reduce(function(m,t){return Math.max(m,t.n||0)},1); + $("tools-n").textContent = tools.length ? String(tools.reduce(function(a,t){return a+(t.n||0)},0)) : ""; + $("tools").innerHTML = tools.length ? tools.map(function(t){ + var pct=Math.max(5,Math.round((t.n||0)/maxN*100)); + return "
"+esc(t.name)+""+(t.n||0)+"" + +"
"; + }).join("") : "
No tool calls yet. They appear as the agent works.
"; + // activity $("activity").textContent = (s.activity||[]).join("\\n") || "Waiting for activity…"; $("foot").textContent = "Nexus dashboard · localhost only · updated "+new Date().toLocaleTimeString(); From ebec49c08c70f626fded9217657b54cfd5696b50 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 16:40:09 -0700 Subject: [PATCH 06/16] =?UTF-8?q?nexus:=20add=20"ultracode"=20effort=20?= =?UTF-8?q?=E2=80=94=20max=20thinking=20+=20standing=20multi-agent=20workf?= =?UTF-8?q?lows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new effort level above max, selectable from the /effort slider, "/effort ultracode", or the autocomplete. On the claude engine it: - sends --effort max to the CLI (the highest thinking budget), and - prefixes each non-slash prompt with "ultracode: " so Claude Code opts its Workflow tool into standing orchestration mode, and - appends a short system directive making that opt-in explicit for the Nexus context (fan out, cover from independent angles, adversarially verify; solo only on trivial/conversational turns). The level persists like any other effort setting and is capped by /budget. Other (CLI) engines that take --effort map ultracode -> max; engines without effort ignore it, same as the existing levels. --- darknode.js | 26 ++++++++++++++++---------- lib/cli/settings.js | 2 +- lib/nexus/engines.js | 2 +- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/darknode.js b/darknode.js index 8c3a65a..e2ed832 100755 --- a/darknode.js +++ b/darknode.js @@ -1834,15 +1834,19 @@ function runEngineTask(engine, prompt, cwd, autonomous, cont, onChunk, ctl, mode } // Claude Code stream-json driver — parses NDJSON events so the TUI can render // tool cards, live token usage, cost and context size exactly like Claude Code. +const ULTRACODE_DIR = "ULTRACODE is ON for this session: the user turned it on and it stands for every message until they turn it off. Aim for the most thorough, correct result you can produce; token cost is not a constraint. For any substantive task, orchestrate: use the Workflow tool (or Agent subagents) to split the work into parallel pieces, cover it from independent angles, and adversarially verify findings and changes before reporting them. Multi-phase work (understand, design, implement, review) can be several workflows in sequence. Work solo only on conversational replies or trivial mechanical edits."; function runClaudeStream(prompt, cwd, cont, h, ctl, opts) { opts = opts || {}; + const ultra = opts.effort === "ultracode"; // Nexus level above max: max thinking + standing multi-agent orchestration + if (ultra && !/^\s*\//.test(prompt)) prompt = "ultracode: " + prompt; // the keyword in the prompt is claude's opt-in for its Workflow tool (skip slash commands) return new Promise((resolve) => { const args = opts.readonly ? ["-p", prompt, "--output-format", "stream-json", "--include-partial-messages", "--verbose", "--permission-mode", "plan"] : ["-p", prompt, "--output-format", "stream-json", "--include-partial-messages", "--verbose", "--dangerously-skip-permissions"]; // partial messages = live text/thinking/token deltas so the counter climbs during a long turn instead of freezing between whole messages if (opts.resume) args.push("--resume", opts.resume); // resume a tracked session id (survives intervening one-shot calls that would hijack --continue) else if (cont) args.push("--continue"); if (opts.model) args.push("--model", opts.model); - if (opts.effort) args.push("--effort", opts.effort); - if (opts.appendSystemPrompt) args.push("--append-system-prompt", opts.appendSystemPrompt); + if (opts.effort) args.push("--effort", ultra ? "max" : opts.effort); + const _sys = (opts.appendSystemPrompt || "") + (ultra ? "\n" + ULTRACODE_DIR : ""); + if (_sys) args.push("--append-system-prompt", _sys); if (opts.fallbackModel) args.push("--fallback-model", opts.fallbackModel); if (opts.maxBudgetUsd) args.push("--max-budget-usd", String(opts.maxBudgetUsd)); if (opts.maxTurns) args.push("--max-turns", String(opts.maxTurns)); @@ -2752,7 +2756,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { ["/ensemble", "all engines answer, then synthesize the best"], ["/settings", "all options, neatly arranged (alias /options /config)"], ["/jobs", "background commands the agent started (run_background)"], ["/loop", "autonomous goal loop: /loop [-n rounds] until GOAL-DONE"], ["/team", "multi-model workspace: architect + builder + reviewer, loops to PASS"], ["/policy", "show the enterprise security policy (org + local)"], ["/audit", "audited tool actions · /audit verify (tamper check)"], ["/bench", "speed / tokens / cost table per engine"], ["/explain", "explain the diff or a file in plain English"], ["/test", "generate & run unit tests for a file"], ["/refactor", "restructure code for clarity without changing behavior"], ["/migrate", "migrate code: /migrate to "], ["/pr", "AI-write a PR title+body from the diff and open it (gh)"], ["/index", "index the repo for local auto-context"], ["/map", "show the repo map (file+symbol outline); /map on|off"], ["/verify", "detect + run this project's tests/build"], ["/radar", "codebase complexity + hotspot map"], ["/review-fast", "fast rule-based review of changed code (no AI)"], ["/diffexplain", "explain the current git diff"], ["/testgen", "scaffold tests for a function/file"], ["/snippet", "save / use a prompt macro"], ["/snippets", "list saved prompt macros"], ["/plan", "make & run an editable task checklist"], ["/git", "branch, status & recent commits"], ["/blame", "who last changed a file's lines"], - ["/cowork", "strong model codes, weak model does cheap work"], ["/cheap", "max token savings with ZERO quality loss"], ["/tight", "surgical edits — change only what differs (lossless)"], ["/lean", "ask for minimal output (saves output tokens)"], ["/style", "output style: concise·explanatory·review·tdd·secure·teacher"], ["/effort", "claude thinking level — interactive slider (or low|medium|high|xhigh|max)"], ["/estimate", "rough token/cost of a prompt before sending"], ["/fallback", "auto-switch model on rate-limit"], + ["/cowork", "strong model codes, weak model does cheap work"], ["/cheap", "max token savings with ZERO quality loss"], ["/tight", "surgical edits — change only what differs (lossless)"], ["/lean", "ask for minimal output (saves output tokens)"], ["/style", "output style: concise·explanatory·review·tdd·secure·teacher"], ["/effort", "claude thinking level — interactive slider (or low|medium|high|xhigh|max|ultracode)"], ["/estimate", "rough token/cost of a prompt before sending"], ["/fallback", "auto-switch model on rate-limit"], ["/guard", "preflight destructive commands (enforce|warn|off)"], ["/permissions", "allow/deny tool rules — /allow /deny "], ["/impact", "session savings (tokens & cost avoided)"], ["/savings", "cross-session cost-savings analysis + 30d projection"], ["/cache", "serve exact-repeat read-only answers free (on/off/clear)"], ["/models", "list cloud & local models"], ["/api", "drive ANY model via an OpenAI-compatible API (OpenRouter, Groq, …)"], ["/recent", "recently changed files"], ["/keys", "keyboard shortcuts"], ["/docs", "built-in documentation (/docs )"], ["/gaps", "list TODO/FIXME markers · /gaps plan"], ["/dream", "consolidate the session into NEXUS.md memory"], ["/tree", "show the project file tree"], ["/theme", "change the color theme"], ["/color", "set the accent color · /color · /color reset"], ["/colors", "list accent colors"], ["/gradient", "set the logo gradient · /gradient "], ["/mouse", "toggle mouse capture · /mouse off to select & copy text"], @@ -2920,7 +2924,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (name === "Read") return "Read(" + relP(a.file_path) + ")"; if (name === "Bash") return "Bash(" + oneline(a.command, Math.max(40, cols() - 30)) + ")" + (a.run_in_background ? gray(" &") : ""); if (name === "Grep" || name === "Glob") return "Search(pattern: \"" + oneline(a.pattern, 40) + "\"" + (a.path ? ", path: \"" + relP(a.path) + "\"" : "") + ")"; - if (name === "Task") return "Task(" + oneline(a.subagent_type || a.description || "agent", 30) + ")"; + if (name === "Task" || name === "Agent") return name + "(" + oneline(a.subagent_type || a.description || "agent", 30) + ")"; + if (name === "Workflow") return "Workflow(" + oneline(a.name || (String(a.script || "").match(/name:\s*['"]([^'"]+)/) || [])[1] || "script", 30) + ")"; if (name === "WebFetch") return "Fetch(" + oneline(a.url, 36) + ")"; if (name === "WebSearch") return "Search(" + oneline(a.query, 34) + ")"; if (name === "TodoWrite") return "Update Todos"; @@ -3240,7 +3245,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { "/color": () => Object.keys(COLORS).map((n) => [n, "\x1b[" + COLORS[n] + "m█████\x1b[0m"]), "/gradient": () => Object.keys(THEMES).map((t) => [t, THEMES[t].grad.map((g) => "\x1b[" + g + "m█\x1b[0m").join("")]), "/style": () => [["default", ""], ["concise", "minimal"], ["explanatory", "detailed"], ["review", "code review"], ["tdd", "test-driven"], ["secure", "security-focused"], ["teacher", "educational"]], - "/effort": () => [["low", "fast, less thinking"], ["medium", "balanced"], ["high", "deep reasoning"], ["xhigh", "harder problems"], ["max", "maximum thinking"]], + "/effort": () => [["low", "fast, less thinking"], ["medium", "balanced"], ["high", "deep reasoning"], ["xhigh", "harder problems"], ["max", "maximum thinking"], ["ultracode", "max + multi-agent workflows"]], "/guard": () => [["enforce", "block destructive commands"], ["warn", "warn but allow"], ["off", "no safety checks"]], "/marketplace": () => [["list", "installed packages"], ["install", "install from path/URL"], ["remove", "uninstall a package"], ["init", "scaffold a publishable package"]], "/cron": () => [["list", "show scheduled jobs"], ["add", "schedule a new job"], ["remove", "delete a job"], ["enable", "enable a job"], ["disable", "pause a job"], ["run", "run a job now"]], @@ -3294,7 +3299,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const _goldTxt = (s) => "\x1b[38;5;220m" + s + "\x1b[0m"; const godApply = () => { godSnap = { effort, lean, minimizeCalls, stepCap, trimOutput, repoMapOn }; - if (engineCap(engine, "effort")) effort = "max"; // only the quality levers; nothing that trades quality for cost/speed + if (engineCap(engine, "effort") && effort !== "ultracode") effort = "max"; // only the quality levers; nothing that trades quality for cost/speed lean = false; minimizeCalls = false; stepCap = false; trimOutput = false; repoMapOn = true; }; const godRestore = () => { if (!godSnap) return; ({ effort, lean, minimizeCalls, stepCap, trimOutput, repoMapOn } = godSnap); godSnap = null; }; @@ -3304,6 +3309,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { ["high", "Deeper reasoning on most problems"], ["xhigh", "Hard problems — more thinking, more tokens"], ["max", "Maximum thinking — the hardest problems, most tokens"], + ["ultracode", "Max thinking + multi-agent workflows that fan out and verify — by far the most tokens"], ]; const renderEffortPicker = (C, sel) => { const names = EFFORT_LEVELS.map((l) => l[0]); @@ -3961,13 +3967,13 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (["Write", "Edit", "MultiEdit"].includes(tu.name)) _item.diff = editDiff(tu.name, tu.input); block.items.push(_item); if (tu.name === "Bash") { runningShells++; stat.cmds++; } - if (tu.name === "Task") activeAgents++; + if (tu.name === "Task" || tu.name === "Agent") activeAgents++; if (["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(tu.name) && (tu.input.file_path || tu.input.notebook_path)) { const fp = tu.input.file_path || tu.input.notebook_path; stat.files.add(base(fp)); const r = relOf(fp); if (r) stat.paths.add(r); } render(); }, onToolResult: (tr) => { const it = block.items.find((x) => x.type === "tool" && x.id === tr.id); - if (it) { it.status = tr.isError ? "err" : "ok"; it.end = Date.now(); it.result = tr.content; it.isError = !!tr.isError; it.detail = oneline(resultText(tr.content), 260); if (it.name === "Bash" && runningShells) runningShells--; if (it.name === "Task" && activeAgents) activeAgents--; } + if (it) { it.status = tr.isError ? "err" : "ok"; it.end = Date.now(); it.result = tr.content; it.isError = !!tr.isError; it.detail = oneline(resultText(tr.content), 260); if (it.name === "Bash" && runningShells) runningShells--; if ((it.name === "Task" || it.name === "Agent") && activeAgents) activeAgents--; } render(); }, onUsage: (u, _m, sub) => { confOut += (u.output_tokens || 0); estOut = 0; sess.liveOut = confOut; if (!sub) { const c = (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.cache_read_input_tokens || 0); if (c > 0) lastCtx = c + (u.output_tokens || 0); } }, // lock in the real output tokens for the message that just finished (each agentic tool round is its own assistant message) and clear the streaming estimate; the next message's estimate climbs on top of this. lastCtx tracks the latest main-thread call's prompt = the real context size @@ -4568,7 +4574,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (cmd === "/help") { const HS = [ { title: "Session", rows: [["/clear","start a new conversation"],["/chat-clear","clear the screen but keep the conversation in memory"],["/compact","summarize the conversation to free up context"],["/resume","reload the last saved session"],["/export","save the conversation to a markdown file"],["/copy","copy the last reply to the clipboard"],["/undo","revert the last turn's file changes"],["/status","engine, model, tokens & cost"],["/recap","recap the session so far (/recap [on|off] for after-task recaps)"],["/title","name the terminal tab for this topic (/title [text|on|off])"],["/exit","quit Nexus"]] }, - { title: "Model & cost", rows: [["/model","pick the model (lists the catalog)"],["/engine","switch AI backend"],["/effort","thinking level: low | medium | high"],["/cost","session cost at exact list prices"],["/budget","set a spend cap in USD"],["/cheap","max token savings, zero quality loss"],["/tight","surgical minimal edits (lossless)"],["/cowork","strong model codes, weak model assists"],["/impact","tokens & cost you've saved"]] }, + { title: "Model & cost", rows: [["/model","pick the model (lists the catalog)"],["/engine","switch AI backend"],["/effort","thinking level: low … max | ultracode"],["/cost","session cost at exact list prices"],["/budget","set a spend cap in USD"],["/cheap","max token savings, zero quality loss"],["/tight","surgical minimal edits (lossless)"],["/cowork","strong model codes, weak model assists"],["/impact","tokens & cost you've saved"]] }, { title: "Code & repo", rows: [["/diff","colored word-level diff of your changes"],["/commit","write a commit message & commit"],["/review","second opinion from another engine"],["/codereview","review changes for bugs, ranked by severity (--fix applies)"],["/test","generate & run tests for a file"],["/explain","explain the diff or a file in plain English"],["/plan","make & run an editable task checklist"],["/scan","quick TCP port scan of a host"],["/secrets","scan the repo for leaked credentials"]] }, { title: "Extend", rows: [["/feature","add your own command: /feature create "],["/commands","list your custom project commands"],["/open","launch the live web dashboard in your browser"],["/dashboard","start/stop the localhost web UI"],["/settings","all options, neatly arranged"],["/theme","change the color theme"],["/keys","the full keyboard-shortcut list"]] }, { title: "Input prefixes", rows: [["/command","run a command (type / to browse)"],["@file","attach a file or image (Tab completes the path)"],["!command","run a shell command (output goes to the AI)"],["#note","save a note to memory"]] }, @@ -5029,7 +5035,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { transcript.push({ role: "system", text: bold("/mode " + a2) + " — " + p.desc + " (saved)\n " + gray(bits.join(" · ")) }); return; } - else if (cmd === "/effort") { const _ml = modelLabel(shownModel() || engine); if (["low", "medium", "high", "xhigh", "max"].includes(arg)) { effort = arg; saveSetting("effort", arg); transcript.push({ role: "system", text: "model " + bold(_ml) + " · effort " + bold(arg) + " — the claude engine uses " + (arg === "low" ? "less thinking (fewer tokens, cheaper; good for mechanical work)" : arg === "high" || arg === "xhigh" || arg === "max" ? "more thinking (better on hard problems, more tokens)" : "the default thinking budget") + (engineCap(engine, "effort") ? "" : " · note: only claude uses effort; " + engine + " ignores it") }); } else if (arg === "off" || arg === "default") { effort = ""; saveSetting("effort", ""); transcript.push({ role: "system", text: "model " + bold(_ml) + " · effort reset to the model default" }); } else { const _i = EFFORT_LEVELS.findIndex((l) => l[0] === (effort || "high")); pendingEffort = { sel: _i < 0 ? 2 : _i }; render(); } } + else if (cmd === "/effort") { const _ml = modelLabel(shownModel() || engine); if (["low", "medium", "high", "xhigh", "max", "ultracode"].includes(arg)) { effort = arg; saveSetting("effort", arg); transcript.push({ role: "system", text: "model " + bold(_ml) + " · effort " + bold(arg) + " — the claude engine uses " + (arg === "low" ? "less thinking (fewer tokens, cheaper; good for mechanical work)" : arg === "ultracode" ? "max thinking and orchestrates multi-agent workflows on every substantive task (fans out, adversarially verifies; by far the most tokens — /budget still caps it)" : arg === "high" || arg === "xhigh" || arg === "max" ? "more thinking (better on hard problems, more tokens)" : "the default thinking budget") + (engineCap(engine, "effort") ? "" : " · note: only claude uses effort; " + engine + " ignores it") }); } else if (arg === "off" || arg === "default") { effort = ""; saveSetting("effort", ""); transcript.push({ role: "system", text: "model " + bold(_ml) + " · effort reset to the model default" }); } else { const _i = EFFORT_LEVELS.findIndex((l) => l[0] === (effort || "high")); pendingEffort = { sel: _i < 0 ? 2 : _i }; render(); } } else if (cmd === "/hack") { hack = arg === "on" ? true : arg === "off" ? false : !hack; transcript.push({ role: "system", text: hack ? red("● HACK MODE") + " — Nexus is now an offensive-security specialist for AUTHORIZED engagements, with the full Darknode toolkit (scan · dns · cert · subs · cve · payloads · revshell · dorks · jwt · hash · totp · encode …) available via run_command. Systems you own or are explicitly in-scope to test only. " + gray("/hack off to exit") : "hack mode OFF — back to the standard coding agent" }); } else if (cmd === "/pentest") { const { startPentest } = require("./lib/nexus/pentest-engine"); startPentest(arg || null, { reportDir: process.cwd() }).catch(e => transcript.push({ role: "system", text: "HYDRA error: " + e.message })); } else if (cmd === "/ai-prompt" || cmd === "/aiprompt") { diff --git a/lib/cli/settings.js b/lib/cli/settings.js index cc8b19c..299b7b2 100644 --- a/lib/cli/settings.js +++ b/lib/cli/settings.js @@ -6,7 +6,7 @@ const SETTINGS = [ { group: "Model", items: [ { label: "Engine", cmd: "/engine ", get: (v) => v.engine }, { label: "Model", cmd: "/model ", get: (v) => v.model || "engine default" }, - { label: "Thinking effort", cmd: "/effort low|medium|high|xhigh|max", get: (v) => v.effort || "default" }, + { label: "Thinking effort", cmd: "/effort low|medium|high|xhigh|max|ultracode", get: (v) => v.effort || "default" }, { label: "Fallback model", cmd: "/fallback ", get: (v) => v.fallback || "off" }, ] }, { group: "Output", items: [ diff --git a/lib/nexus/engines.js b/lib/nexus/engines.js index 1726902..444ad09 100644 --- a/lib/nexus/engines.js +++ b/lib/nexus/engines.js @@ -10,7 +10,7 @@ const ENGINES = { claude: { label: "Claude Code", bin: "claude", install: "npm i -g @anthropic-ai/claude-code", kind: "stream", paid: true, ctx: 200000, model: "claude-opus-5-5", models: ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-1"], caps: { effort: true, appendSystemPrompt: true, fallbackModel: true, maxBudget: true, disallowedTools: true, cowork: true, model: true }, - args: (p, o) => { const a = ["-p", p, "--output-format", "text"]; if (o.cont) a.push("--continue"); if (o.autonomous) a.push("--dangerously-skip-permissions"); if (o.model) a.push("--model", o.model); if (o.effort) a.push("--effort", o.effort); if (o.maxTurns) a.push("--max-turns", String(o.maxTurns)); return a; }, + args: (p, o) => { const a = ["-p", p, "--output-format", "text"]; if (o.cont) a.push("--continue"); if (o.autonomous) a.push("--dangerously-skip-permissions"); if (o.model) a.push("--model", o.model); if (o.effort) a.push("--effort", o.effort === "ultracode" ? "max" : o.effort); if (o.maxTurns) a.push("--max-turns", String(o.maxTurns)); return a; }, tips: ["Claude can search the web, run bash, read/write files and spawn sub-agents to parallelize", "your real token usage and dollar cost update live in the status bar", "plan mode (shift+tab) has Claude outline the work before it touches any files", "Claude reads .nexus/NEXUS.md every session — keep project context there"], }, gemini: { From 032540e2b9576f698fe11f79d61e1833327a9fda Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 16:53:31 -0700 Subject: [PATCH 07/16] nexus: fix laggy prompt input on long sessions (memoize transcript render) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The prompt box felt glitchy and laggy after /restart. Cause: bodyLines() re-wraps the ENTIRE transcript (ANSI wrapping, diffs, tool cards) on every paint — O(transcript) — and every keystroke paints synchronously. /restart relaunches with --resume, which reloads the whole session, so the transcript is large and each held-key repeat paid a full rebuild: visible input lag and stutter. Memoize the rendered transcript while idle. Typing never changes the transcript, so when !busy we reuse the cached lines and only the composer repaints; a burst of key-repeats now does one build, not one per key. The cache is keyed on everything bodyLines reads (transcript length + last message's text/tool-item signature, cols, expanded, effort, engine, model, guard, branch, live MCP count, welcome tip, queued prompts) and is bypassed entirely while busy or compacting so streaming text, spinners and running-tool timers stay live. Not tied to /restart — any long session benefits. --- darknode.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/darknode.js b/darknode.js index e2ed832..8fc69cc 100755 --- a/darknode.js +++ b/darknode.js @@ -2963,7 +2963,23 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // One welcome tip chosen once per session (stable across every render so the // card never flickers), rotated by start time for a little variety. const _welcomeTip = NEXUS_TIPS[Math.floor(Date.now() / 1000) % NEXUS_TIPS.length]; + // Memoize the fully-rendered transcript while idle. bodyLines re-wraps every + // message (ANSI, diffs, tool cards) on each paint — O(transcript) — and every + // keystroke paints, so a long session (common after /restart resumes one) made + // held-key input lag: each repeat paid a full rebuild. Typing never changes the + // transcript, so when !busy we reuse the cached lines and only the composer + // repaints. We skip the cache while busy/compacting (live spinners, streaming + // text, running-tool timers) and key the cache on everything bodyLines reads. + const _bodySig = () => { + const m = transcript[transcript.length - 1]; + let last = ""; + if (m) { last = (m.role || "") + ":" + (m.text ? m.text.length : 0); if (m.items) { last += ":" + m.items.length; for (const it of m.items) last += "," + (it.status || "") + "." + (it.label ? it.label.length : 0) + "." + (it.detail ? it.detail.length : 0) + "." + (it.result ? String(it.result).length : 0) + "." + (it.diff ? it.diff.length : 0); } } + return transcript.length + "|" + cols() + "|" + (expanded ? 1 : 0) + "|" + (useColor ? 1 : 0) + "|" + effort + "|" + engine + "|" + shownModel() + "|" + guard + "|" + (gitBranch || "") + "|" + mcpServers.filter((s) => s && !s.error).length + "|" + (_welcomeTip || "") + "|" + nextQueue.length + "/" + nextQueue.join("\u0001").length + "|" + last; + }; + let _blCache = null, _blSig = ""; const bodyLines = () => { + const _sig = (busy || compact.on) ? null : _bodySig(); + if (_sig !== null && _blCache && _sig === _blSig) return _blCache; const L = []; for (const m of transcript) { if (m.role === "art") { @@ -3172,6 +3188,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { L.push(""); L.push(workGlyph() + " " + cyan("Compacting conversation…") + gray(" (" + fmtElapsed(el) + (compact.tok ? " · ↓ " + fmtK(compact.tok) + " tokens" : "") + " · esc to interrupt)")); } + if (_sig !== null) { _blCache = L; _blSig = _sig; } return L; }; // ---- status + hint bars ---- From 6644b03ceb13f0c96b29f42f7961dd687e71d9d5 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 17:03:10 -0700 Subject: [PATCH 08/16] nexus: fix TUI freeze on diffs with a very long changed line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wordHi() word-level diff highlighting called wordFlags(a, b, Infinity), so the O(n*m) LCS table was never bounded. A single long changed line — a minified JS line, a long JSON blob, a packed data row — produces tens of thousands of tokens, and the n*m table then blows up: ~2s at 6k tokens/line, ~30s+ for a ~50KB minified line, all synchronous inside render(). Editing such a file (its diff renders in the transcript and the /undo preview) froze the whole TUI. Bound the LCS to 600 tokens/side (wordFlags already supports a cap and returns null past it) and fall back to showing the line plainly when exceeded — the diff is still correct, just without intra-line word emphasis on that one line. Short lines are unaffected and keep full word-level highlighting. Measured: 6000 tokens/line 2187ms -> 1ms; 20000 tokens 30s+ -> 4ms. --- lib/cli/diff.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/cli/diff.js b/lib/cli/diff.js index 3959307..7cccab0 100644 --- a/lib/cli/diff.js +++ b/lib/cli/diff.js @@ -42,7 +42,13 @@ function wordFlags(a, b, max) { function wordHi(a, b, useColor) { if (useColor === undefined) useColor = DEFAULT_COLOR; if (!useColor) return [a, b]; - const { at, bt, af, bf } = wordFlags(a, b, Infinity); + // Bound the O(n*m) LCS: a single very long changed line (minified JS, a long + // JSON blob) would otherwise build a multi-million-cell table and freeze the + // whole TUI synchronously inside render(). Past the cap, skip word-level + // highlighting and show the lines plainly — the diff is still correct. + const wf = wordFlags(a, b, 600); + if (!wf) return [a, b]; + const { at, bt, af, bf } = wf; const build = (toks, flags, common, changed) => { let s = ""; for (let k = 0; k < toks.length; k++) s += "\x1b[0m" + (flags[k] ? common : changed) + toks[k]; return s + "\x1b[0m"; }; return [build(at, af, "\x1b[2;31m", "\x1b[1;4;31m"), build(bt, bf, "\x1b[2;32m", "\x1b[1;4;32m")]; // dim=carried, bold+underline=changed } From 91bc908fc08ad4d4a81982df67703b8c6424f597 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 17:07:19 -0700 Subject: [PATCH 09/16] nexus: stop the localhost dashboard leaking session state to other websites /api/state and /api/stream sent Access-Control-Allow-Origin: *. Binding to 127.0.0.1 keeps other machines out but not the user's own browser, so any website they had open could fetch http://127.0.0.1:7979/api/state and read the live session: prompts/activity, working dir, changed files, background-job commands. With no Host check it was also reachable via DNS rebinding. The dashboard page is same-origin, so it needs no CORS: drop the header, answer only requests whose Host is this loopback port (127.0.0.1 or localhost), and refuse a foreign Origin with 403. --- lib/nexus/dashboard.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/nexus/dashboard.js b/lib/nexus/dashboard.js index 638de0c..9ed7b20 100644 --- a/lib/nexus/dashboard.js +++ b/lib/nexus/dashboard.js @@ -233,6 +233,15 @@ function startDashboard(opts) { const makeServer = () => http.createServer((req, res) => { const url = (req.url || "/").split("?")[0]; if (req.method !== "GET") { res.writeHead(405); res.end(); return; } + // Loopback binding stops other machines, not the user's own browser: any page + // they visit could read this session (prompts, activity, files, job commands) + // cross-origin, or reach it via DNS rebinding. Serve only requests addressed + // to this loopback port from this origin; no CORS (the page is same-origin). + const port = req.socket.localPort; + const okHosts = ["127.0.0.1:" + port, "localhost:" + port]; + if (!okHosts.includes(String(req.headers.host || "").toLowerCase())) { res.writeHead(403); res.end(); return; } + const origin = req.headers.origin; + if (origin && !okHosts.some((h) => origin.toLowerCase() === "http://" + h)) { res.writeHead(403); res.end(); return; } if (url === "/" || url === "/index.html") { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); @@ -248,7 +257,7 @@ function startDashboard(opts) { } if (url === "/api/state") { let state = {}; try { state = getState() || {}; } catch (_) {} - res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*" }); + res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(state)); return; } @@ -257,7 +266,6 @@ function startDashboard(opts) { "Content-Type": "text/event-stream", "Cache-Control": "no-store", "Connection": "keep-alive", - "Access-Control-Allow-Origin": "*", }); const tick = () => { let s = {}; try { s = getState() || {}; } catch (_) {} try { res.write(sseFrame(s)); } catch (_) {} }; tick(); From f9e15b2e4706d2f97e043f046a8c9b1f59dc7ab9 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 17:27:23 -0700 Subject: [PATCH 10/16] nexus: fix emoji overflowing wrapped transcript lines ansiWrap() charged every glyph one column, but a surrogate-pair character (emoji) is two columns on screen, and visLen/padRight and the scroll-rail layout count it as two. Any reply or file snippet containing emoji wrapped past its width budget and spilled over the right border: ansiWrap of six emoji at width 4 produced a first row 8 columns wide. Charge each glyph its visLen width (ch.length, 2 for a surrogate pair), and always take at least one glyph per row so a glyph wider than the budget can't stall the loop. All-BMP text wraps identically to before. --- lib/cli/tui-format.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cli/tui-format.js b/lib/cli/tui-format.js index 8d266a5..1dc2ef9 100644 --- a/lib/cli/tui-format.js +++ b/lib/cli/tui-format.js @@ -68,7 +68,7 @@ function ansiWrap(text, width) { let i = 0, active = "", carried = ""; while (i < cells.length) { let j = i, count = 0, lastSpace = -1; - while (j < cells.length && count < width) { if (cells[j].sp) lastSpace = j; j++; count++; } + while (j < cells.length && (j === i || count + cells[j].ch.length <= width)) { if (cells[j].sp) lastSpace = j; count += cells[j].ch.length; j++; } // charge each glyph its visLen width (a surrogate pair is 2) so an emoji can't overshoot the column budget; always take >=1 glyph to guarantee progress if (j < cells.length && cells[j].sp) lastSpace = j; // a space sitting exactly at the boundary fills the line, then is dropped let end, nextStart; if (j >= cells.length) { end = nextStart = cells.length; } From 44c76c8bad4b47ee69cac26e254d3b35faac1e12 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 17:51:20 -0700 Subject: [PATCH 11/16] nexus: redesign the ask_user popup (Claude-Code-style box, Type row, explicit Submit) The ask panel is now a rounded, bordered box matching the selection look: an accent dot on the question, a numbered option list with a cursor, a "Type a different answer" row that drops into a free-text field, and an explicit Submit row so you confirm by selecting Submit rather than trusting a bare Enter. Multi-select renders checkboxes and Submit returns the whole set. ask.js stays a pure renderer+reducer; darknode.js wires the typing transition and typed-answer routing through the single, multi, and bridge handlers. --- darknode.js | 11 ++- lib/cli/ask.js | 197 +++++++++++++++++++++++++++++++++---------------- test/run.js | 42 +++++++---- 3 files changed, 169 insertions(+), 81 deletions(-) diff --git a/darknode.js b/darknode.js index 8fc69cc..b3e5072 100755 --- a/darknode.js +++ b/darknode.js @@ -3655,8 +3655,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (req.input) { const ans = await askUser(q, [], { input: true, placeholder: req.placeholder }); return ans.cancelled ? { skipped: true } : { answer: String(ans.value || "") }; } const norm = Ask.normOptions(Array.isArray(req.options) ? req.options : []); if (!norm.length) { const ans = await askUser(q, [], { input: true }); return ans.cancelled ? { skipped: true } : { answer: String(ans.value || "") }; } - if (req.multi) { const ans = await askUser(q, norm, { multi: true, picked: [] }); if (ans.cancelled) return { skipped: true }; return { selected: (ans.values || []).map((v) => (v && v.label != null) ? v.label : String(v)), indices: ans.indices || [] }; } - const ans = await askUser(q, norm); if (ans.cancelled) return { skipped: true }; return { selected: (ans.value && ans.value.label != null) ? ans.value.label : String(ans.value), index: ans.index }; + if (req.multi) { const ans = await askUser(q, norm, { multi: true, picked: [] }); if (ans.cancelled) return { skipped: true }; if (ans.typed) return { answer: String(ans.value || "") }; return { selected: (ans.values || []).map((v) => (v && v.label != null) ? v.label : String(v)), indices: ans.indices || [] }; } + const ans = await askUser(q, norm); if (ans.cancelled) return { skipped: true }; if (ans.typed) return { answer: String(ans.value || "") }; return { selected: (ans.value && ans.value.label != null) ? ans.value.label : String(ans.value), index: ans.index }; }; const ensureAskBridge = () => { if (!askBridge) { try { askBridge = createAskServer(handleBridgeAsk); } catch (_) { askBridge = null; } } return askBridge; }; // Build (or reuse) the per-engine MCP config: the Nexus ask bridge plus any @@ -4173,12 +4173,14 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { card.label = "AskUser(" + oneline(q, 30) + ")"; render(); const ans = await askUser(q, norm, { multi: true, picked: [] }); if (ans.cancelled) { result = skipNote; transcript.push({ role: "system", text: "Nexus asked: " + oneline(q, 48) + " — skipped" }); } + else if (ans.typed) { const answer = String(ans.value || ""); result = { answer }; transcript.push({ role: "system", text: "you answered: " + oneline(answer || "(empty)", 40) + " (" + oneline(q, 36) + ")" }); } else { const labels = (ans.values || []).map((v) => v && v.label != null ? v.label : String(v)); result = { selected: labels, indices: ans.indices || [] }; transcript.push({ role: "system", text: "you chose: " + oneline(labels.join(", ") || "(none)", 42) + " (" + oneline(q, 32) + ")" }); } } else { card.label = "AskUser(" + oneline(q, 30) + ")"; render(); const ans = await askUser(q, norm); if (ans.cancelled) { result = skipNote; transcript.push({ role: "system", text: "Nexus asked: " + oneline(q, 48) + " — skipped" }); } + else if (ans.typed) { const answer = String(ans.value || ""); result = { answer }; transcript.push({ role: "system", text: "you answered: " + oneline(answer || "(empty)", 40) + " (" + oneline(q, 36) + ")" }); } else { const label = ans.value && ans.value.label != null ? ans.value.label : String(ans.value); result = { selected: label, index: ans.index }; transcript.push({ role: "system", text: "you chose: " + oneline(label, 36) + " (" + oneline(q, 40) + ")" }); } } } @@ -5818,8 +5820,9 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (isMouse) return; // swallow mouse while choosing (no accidental scroll/edit) const r = Ask.askKey(pendingAsk, s); if (r.cancelled) { const p = pendingAsk; pendingAsk = null; p.resolve({ cancelled: true }); render(); return; } - if (r.done) { const p = pendingAsk; pendingAsk = null; p.resolve(r); render(); return; } // r carries value/index (single), indices/values (multi) or value (text) - if (r.sel != null) pendingAsk.sel = r.sel; if (r.picked) pendingAsk.picked = r.picked; if (r.text != null) pendingAsk.text = r.text; + if (r.typing) { pendingAsk.input = true; pendingAsk.typed = true; if (pendingAsk.text == null) pendingAsk.text = ""; pendingAsk.placeholder = pendingAsk.placeholder || "type your answer"; render(); return; } // "type a different answer" row → drop into a free-text field + if (r.done) { const p = pendingAsk; pendingAsk = null; p.resolve(r); render(); return; } // r carries value/index (single), indices/values (multi) or value+typed (text) + if (r.sel != null) pendingAsk.sel = r.sel; if (r.pick != null) pendingAsk.pick = r.pick; if (r.picked) pendingAsk.picked = r.picked; if (r.text != null) pendingAsk.text = r.text; render(); return; } diff --git a/lib/cli/ask.js b/lib/cli/ask.js index a8e4ca8..647a91c 100644 --- a/lib/cli/ask.js +++ b/lib/cli/ask.js @@ -2,9 +2,11 @@ // ============================================================================ // ask — a PURE renderer + key reducer for the "the model asks YOU a question" // panel. When the agent raises the `ask_user` tool, the TUI pauses and shows a -// multiple-choice prompt in the same open-rule frame the composer uses (a thin -// horizontal rule above and below, no side walls), with a numbered option list -// and an arrow/number selector — the Claude-Code "pick one" look. +// rounded, bordered box (the Claude-Code selection look): the question with an +// accent dot, a numbered option list with a "❯" cursor, a "Type a different +// answer" row that drops into a free-text field, and an explicit Submit row — +// so you confirm by selecting Submit, not by trusting a bare Enter. Multi-select +// shows ◉/○ checkboxes and Submit returns the whole set. // // Everything here is pure + snapshot-testable: no DOM, no I/O, no module-scope // state. The host (darknode.js) owns the terminal, holds the `pendingAsk` state @@ -35,6 +37,21 @@ function normPicked(picked, n) { return out.sort((a, b) => a - b); } +// Does this question allow a free-text "type a different answer" row? On by +// default for option prompts; the model can suppress it with allowType:false. +function typeAllowed(ask) { return !!(ask && !ask.input && ask.allowType !== false); } + +// The navigable rows for an option prompt, in focus order: +// one row per option, then (optionally) the Type row, then the Submit row. +// Returned as tagged entries so the renderer and reducer agree on the geometry. +function rowModel(ask) { + const opts = normOptions(ask && ask.options); + const rows = opts.map((_, i) => ({ kind: "opt", i })); + if (typeAllowed(ask)) rows.push({ kind: "type" }); + rows.push({ kind: "submit" }); + return { opts, rows }; +} + // Plain word-wrap for the question text (no ANSI inside — colored by the caller). function wrapPlain(s, w) { s = String(s || "").replace(/\s+/g, " ").trim(); @@ -51,88 +68,142 @@ function wrapPlain(s, w) { return out.length ? out : [""]; } -// renderAsk(ask, width, colors) -> string[] (each row ready to paint; the first -// gutter space matches the composer's " " + content convention). +// Truncate a plain string to w columns with a trailing ellipsis. +function fit(s, w) { s = String(s == null ? "" : s); if (w < 0) w = 0; if (s.length <= w) return s; if (w <= 1) return s.slice(0, w); return s.slice(0, w - 1) + "…"; } + +// renderAsk(ask, width, colors) -> string[] (each row ready to paint). The box +// is drawn full width with rounded corners and side walls; the key legend sits +// dimmed beneath it. Rows are padded to `width` visible columns using PLAIN +// text length (injected colors add no columns), so right walls stay aligned. function renderAsk(ask, width, colors) { - const C = Math.max(24, (width | 0) || 80); + const C = Math.max(28, (width | 0) || 80); const t = theme(colors); - const inner = C - 2; // content width after the 1-col gutter - const rows = []; - const rule = " " + t.gray("─".repeat(Math.max(0, inner))); - rows.push(rule); - // Question — an accent dot on the first line, bold text, wrapped. - const q = wrapPlain(ask && ask.question, Math.max(1, inner - 2)); - q.forEach((ln, i) => rows.push(" " + (i === 0 ? t.cyan("● ") : " ") + t.bold(ln))); - rows.push(" "); + const innerW = C - 4; // content width inside "│ " … " │" + const out = []; + const top = t.gray("╭" + "─".repeat(C - 2) + "╮"); + const bot = t.gray("╰" + "─".repeat(C - 2) + "╯"); + // A content row: measure with the PLAIN string, paint with the colored one. + const line = (plain, colored) => { const pad = Math.max(0, innerW - plain.length); out.push(t.gray("│ ") + (colored == null ? plain : colored) + " ".repeat(pad) + t.gray(" │")); }; + const blank = () => line("", ""); + out.push(top); + // Question — accent dot on the first wrapped line, bold throughout. + const q = wrapPlain(ask && ask.question, Math.max(1, innerW - 2)); + q.forEach((ln, i) => line((i === 0 ? "● " : " ") + ln, (i === 0 ? t.cyan("● ") : " ") + t.bold(ln))); + blank(); + if (ask && ask.input) { - // ---- free-text input: a single editable field with a block caret. ---- + // ---- free-text field (either a pure input prompt, or the "type a different + // answer" row expanded into an editable line). A block caret marks the end. ---- const text = String(ask.text || ""); - const avail = Math.max(1, inner - 4); + const avail = Math.max(1, innerW - 3); const shown = text.length > avail ? "…" + text.slice(-(avail - 1)) : text; - rows.push(" " + t.cyan(" › ") + (shown ? shown : t.dim(ask.placeholder ? String(ask.placeholder) : "type your answer")) + t.cyan("█")); - rows.push(" "); - rows.push(" " + t.gray("type your answer · enter submit · esc skip")); - rows.push(rule); - return rows; + const ph = ask.placeholder ? String(ask.placeholder) : "type your answer"; + if (shown) line("› " + shown, t.cyan("› ") + shown + t.cyan("█")); + else line("› " + ph, t.cyan("› ") + t.dim(ph) + t.cyan("█")); + out.push(bot); + out.push(" " + t.gray(fit("enter submit · esc " + (ask.typed ? "cancel" : "skip"), C - 2))); + return out; } - const opts = normOptions(ask && ask.options); - const sel = clampSel(ask && ask.sel, opts.length); + + const { opts, rows } = rowModel(ask); + const sel = clampSel(ask && ask.sel, rows.length); const multi = !!(ask && ask.multi); const picked = multi ? normPicked(ask && ask.picked, opts.length) : []; - // Options — numbered; the current row gets a "›" marker and cyan/bold label. - // In multi-select mode each row also carries a [x]/[ ] checkbox. - opts.forEach((o, i) => { - const on = i === sel; - const num = (i + 1) + "."; - const box = multi ? (picked.indexOf(i) >= 0 ? t.green("[x] ") : t.gray("[ ] ")) : ""; - const head = on ? t.cyan(" › ") : " "; - const body = on ? t.bold(t.cyan(num + " " + o.label)) : t.gray(num + " ") + o.label; - rows.push(head + box + body + (o.hint ? " " + t.dim(o.hint) : "")); + rows.forEach((row, r) => { + const on = r === sel; + const cur = on ? "❯ " : " "; + const curC = on ? t.cyan("❯ ") : " "; + if (row.kind === "opt") { + const o = opts[row.i]; + const num = (row.i + 1) + "."; + const box = multi ? (picked.indexOf(row.i) >= 0 ? "◉ " : "○ ") : ""; + const boxC = multi ? (picked.indexOf(row.i) >= 0 ? t.green("◉ ") : t.gray("○ ")) : ""; + const label = fit(o.label, Math.max(4, innerW - 2 - box.length - num.length - 1 - (o.hint ? o.hint.length + 2 : 0))); + const hintP = o.hint ? " " + o.hint : ""; + const plain = cur + box + num + " " + label + hintP; + const colored = curC + boxC + (on ? t.bold(t.cyan(num + " " + label)) : t.gray(num + " ") + label) + (o.hint ? " " + t.dim(o.hint) : ""); + line(plain, colored); + } else if (row.kind === "type") { + const plain = cur + "✎ Type a different answer"; + const colored = curC + (on ? t.bold(t.cyan("✎ Type a different answer")) : t.gray("✎ Type a different answer")); + line(plain, colored); + } else { // submit + const tag = multi ? "Submit" + (picked.length ? " (" + picked.length + " selected)" : "") : "Submit"; + const plain = cur + tag; + const colored = curC + (on ? t.bold(t.cyan(tag)) : t.gray(tag)); + line(plain, colored); + } }); - rows.push(" "); - const hint = multi - ? "space toggle · enter confirm · esc skip · " + picked.length + " picked" - : "up/down move · 1-" + Math.max(1, opts.length) + " pick · enter confirm · esc skip"; - rows.push(" " + t.gray(hint)); - rows.push(rule); - return rows; + out.push(bot); + const legend = multi + ? "↑↓ move · space toggle · 1-" + Math.max(1, opts.length) + " toggle · enter select · esc skip" + : "↑↓ move · 1-" + Math.max(1, opts.length) + " pick · enter select · esc skip"; + out.push(" " + t.gray(fit(legend, C - 2))); + return out; } -// askKey(ask, key) -> {sel, done, cancelled?, value?, index?} -// Pure reducer over a raw terminal key sequence. Up/Down (and their bare-CSI -// forms) move with wraparound; a digit 1-9 picks that option immediately; Enter -// confirms the current selection; Esc / Ctrl+C cancel (the model is told the -// user skipped). Any other key is a no-op. +// askKey(ask, key) -> a patch describing what the keypress did: +// { cancelled } esc / ctrl+c — the user skipped +// { typing } the user chose the "type a different answer" row +// { sel, pick, picked } a navigation / toggle (host stores these back) +// { done, value, index } single-select confirmed (value is the option) +// { done, indices, values, picked } multi-select confirmed +// { done, value, typed } a free-text answer submitted +// Pure reducer over a raw terminal key sequence. function askKey(ask, key) { - // ---- free-text input mode ---- + // ---- free-text input mode (pure input prompt, or expanded "type" row) ---- if (ask && ask.input) { const text = String(ask.text || ""); + const typed = !!(ask && ask.typed); if (key === "\x1b" || key === "\x03") return { text, done: false, cancelled: true }; - if (key === "\r" || key === "\n") return { text, done: true, value: text }; + if (key === "\r" || key === "\n") return { text, done: true, value: text, typed }; if (key === "\x7f" || key === "\b") return { text: text.slice(0, -1), done: false }; if (key === "\x15") return { text: "", done: false }; // Ctrl+U clears the field if (key.length === 1 && key.charCodeAt(0) >= 0x20 && key.charCodeAt(0) !== 0x7f) return { text: text + key, done: false }; return { text, done: false }; } - const opts = normOptions(ask && ask.options); + const { opts, rows } = rowModel(ask); const n = opts.length; - const sel = clampSel(ask && ask.sel, n); + const R = rows.length; + const sel = clampSel(ask && ask.sel, R); const multi = !!(ask && ask.multi); - if (key === "\x1b" || key === "\x03") return multi ? { sel, picked: normPicked(ask && ask.picked, n), done: false, cancelled: true } : { sel, done: false, cancelled: true }; - if (n === 0) return { sel, done: false }; - if (key === "\x1b[A" || key === "[A" || key === "\x1bOA") return multi ? { sel: (sel - 1 + n) % n, picked: normPicked(ask && ask.picked, n), done: false } : { sel: (sel - 1 + n) % n, done: false }; - if (key === "\x1b[B" || key === "[B" || key === "\x1bOB") return multi ? { sel: (sel + 1) % n, picked: normPicked(ask && ask.picked, n), done: false } : { sel: (sel + 1) % n, done: false }; - if (multi) { - // Space or a digit TOGGLES membership; Enter confirms the whole set. - const toggle = (i) => { const cur = normPicked(ask && ask.picked, n); const at = cur.indexOf(i); if (at >= 0) cur.splice(at, 1); else cur.push(i); return normPicked(cur, n); }; - if (key === " ") return { sel, picked: toggle(sel), done: false }; - if (/^[1-9]$/.test(key)) { const i = +key - 1; return i < n ? { sel: i, picked: toggle(i), done: false } : { sel, picked: normPicked(ask && ask.picked, n), done: false }; } - if (key === "\r" || key === "\n") { const idx = normPicked(ask && ask.picked, n); return { sel, picked: idx, done: true, indices: idx, values: idx.map((i) => opts[i]) }; } - return { sel, picked: normPicked(ask && ask.picked, n), done: false }; + const curPicked = () => normPicked(ask && ask.picked, n); + // The option index to submit in single mode: the last option the cursor sat + // on (tracked as `pick`), falling back to the focused option or the first. + const pickOf = () => { const here = rows[sel]; if (here && here.kind === "opt") return here.i; const p = (ask && ask.pick) | 0; return p >= 0 && p < n ? p : 0; }; + + if (key === "\x1b" || key === "\x03") return multi ? { sel, picked: curPicked(), done: false, cancelled: true } : { sel, done: false, cancelled: true }; + if (R === 0) return { sel, done: false }; + + const move = (d) => { const s2 = (sel + d + R) % R; const here = rows[s2]; const patch = { sel: s2, done: false }; if (here && here.kind === "opt") patch.pick = here.i; if (multi) patch.picked = curPicked(); return patch; }; + if (key === "\x1b[A" || key === "[A" || key === "\x1bOA") return move(-1); + if (key === "\x1b[B" || key === "[B" || key === "\x1bOB") return move(1); + + // A digit always targets an option directly (single: pick+submit; multi: toggle). + if (/^[1-9]$/.test(key)) { + const i = +key - 1; + if (i >= n) return multi ? { sel, picked: curPicked(), done: false } : { sel, done: false }; + if (multi) { const cur = curPicked(); const at = cur.indexOf(i); if (at >= 0) cur.splice(at, 1); else cur.push(i); return { sel, pick: i, picked: normPicked(cur, n), done: false }; } + return { done: true, value: opts[i], index: i }; + } + + const here = rows[sel]; + if (multi && key === " ") { if (here && here.kind === "opt") { const cur = curPicked(); const at = cur.indexOf(here.i); if (at >= 0) cur.splice(at, 1); else cur.push(here.i); return { sel, pick: here.i, picked: normPicked(cur, n), done: false }; } return { sel, picked: curPicked(), done: false }; } + + if (key === "\r" || key === "\n") { + if (here && here.kind === "type") return { typing: true }; + if (here && here.kind === "submit") { + if (multi) { const idx = curPicked(); return { done: true, indices: idx, values: idx.map((i) => opts[i]), picked: idx }; } + const p = pickOf(); return { done: true, value: opts[p], index: p }; + } + // on an option row + if (here && here.kind === "opt") { + if (multi) { const cur = curPicked(); const at = cur.indexOf(here.i); if (at >= 0) cur.splice(at, 1); else cur.push(here.i); return { sel, pick: here.i, picked: normPicked(cur, n), done: false }; } + return { done: true, value: opts[here.i], index: here.i }; + } + return { sel, done: false }; } - if (key === "\r" || key === "\n") return { sel, done: true, value: opts[sel], index: sel }; - if (/^[1-9]$/.test(key)) { const i = +key - 1; return i < n ? { sel: i, done: true, value: opts[i], index: i } : { sel, done: false }; } - return { sel, done: false }; + return multi ? { sel, picked: curPicked(), done: false } : { sel, done: false }; } -module.exports = { renderAsk, askKey, normOptions, normPicked, wrapPlain }; +module.exports = { renderAsk, askKey, normOptions, normPicked, wrapPlain, rowModel, typeAllowed }; diff --git a/test/run.js b/test/run.js index 2fa1d8e..a6786bf 100644 --- a/test/run.js +++ b/test/run.js @@ -2585,45 +2585,54 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec eq("normalizes strings + objects to {label,hint}", JSON.stringify(normOptions(["a", { label: "b", hint: "h" }])), JSON.stringify([{ label: "a", hint: "" }, { label: "b", hint: "h" }])); eq("drops empty labels", normOptions(["", "x", null]).length, 1); eq("caps options at 9 (single-digit pick)", normOptions(Array.from({ length: 20 }, (_, i) => "o" + i)).length, 9); - // ---- askKey: navigation ---- - eq("down moves selection +1", askKey(ask, "\x1b[B").sel, 1); - eq("up from 0 wraps to last", askKey(ask, "\x1b[A").sel, 2); + // ---- askKey: navigation (rows = 3 options + Type + Submit = 5) ---- + eq("down moves focus +1", askKey(ask, "\x1b[B").sel, 1); + eq("up from 0 wraps to last row (Submit)", askKey(ask, "\x1b[A").sel, 4); eq("bare-CSI down (no ESC) also moves", askKey(ask, "[B").sel, 1); - eq("down at last wraps to 0", askKey({ ...ask, sel: 2 }, "\x1b[B").sel, 0); + eq("down tracks pick when landing on an option", askKey(ask, "\x1b[B").pick, 1); // ---- askKey: confirm / pick / cancel ---- - ok("enter confirms the current selection", (() => { const r = askKey({ ...ask, sel: 1 }, "\r"); return r.done && r.index === 1 && r.value.label === "SQLite"; })()); + ok("enter on an option row confirms it", (() => { const r = askKey({ ...ask, sel: 1 }, "\r"); return r.done && r.index === 1 && r.value.label === "SQLite"; })()); ok("a digit picks that option immediately", (() => { const r = askKey(ask, "3"); return r.done && r.index === 2 && r.value.label === "MySQL"; })()); + ok("enter on the Submit row confirms the tracked pick", (() => { const r = askKey({ ...ask, sel: 4, pick: 2 }, "\r"); return r.done && r.index === 2 && r.value.label === "MySQL"; })()); + ok("enter on the Type row signals typing (no answer yet)", (() => { const r = askKey({ ...ask, sel: 3 }, "\r"); return r.typing === true && !r.done; })()); ok("an out-of-range digit is a no-op", (() => { const r = askKey(ask, "7"); return !r.done && !r.cancelled; })()); ok("esc cancels (user skips)", askKey(ask, "\x1b").cancelled === true); ok("ctrl+c cancels", askKey(ask, "\x03").cancelled === true); - ok("an unrelated key is a no-op that keeps selection", (() => { const r = askKey({ ...ask, sel: 1 }, "x"); return !r.done && !r.cancelled && r.sel === 1; })()); + ok("an unrelated key is a no-op that keeps focus", (() => { const r = askKey({ ...ask, sel: 1 }, "x"); return !r.done && !r.cancelled && r.sel === 1; })()); // ---- renderAsk: layout + content (plain, colors identity) ---- const rows = renderAsk({ ...ask, sel: 1 }, 60); - ok("opens and closes with a horizontal rule", /─/.test(rows[0]) && /─/.test(rows[rows.length - 1])); + ok("draws a rounded box (corners + walls)", rows[0].includes("╭") && rows[0].includes("╮") && rows.some((r) => r.includes("╰") && r.includes("╯")) && rows.some((r) => r.includes("│"))); ok("shows the question text", rows.some((r) => r.includes("Which database"))); ok("numbers every option", rows.some((r) => /1\. PostgreSQL/.test(r)) && rows.some((r) => /2\. SQLite/.test(r)) && rows.some((r) => /3\. MySQL/.test(r))); - ok("marks the selected option with ›", rows.some((r) => r.includes("›") && r.includes("SQLite"))); + ok("marks the focused option with ❯", rows.some((r) => r.includes("❯") && r.includes("SQLite"))); ok("renders a hint when provided", rows.some((r) => r.includes("zero-config"))); - ok("has a key-legend footer", rows.some((r) => /enter confirm/.test(r) && /esc skip/.test(r))); + ok("offers a Type-a-different-answer row", rows.some((r) => /Type a different answer/.test(r))); + ok("offers a Submit row", rows.some((r) => /Submit/.test(r))); + ok("has a key-legend footer", rows.some((r) => /enter select/.test(r) && /esc skip/.test(r))); + ok("every box row is exactly the requested width (plain)", rows.filter((r) => r.includes("│")).every((r) => r.length === 60)); ok("no row exceeds the requested width (plain)", rows.every((r) => r.length <= 60)); + ok("allowType:false drops the Type row", !renderAsk({ ...ask, allowType: false }, 60).some((r) => /Type a different answer/.test(r))); ok("empty options + esc still cancels (no crash)", askKey({ question: "q", options: [], sel: 0 }, "\x1b").cancelled === true); ok("renderAsk tolerates no options", Array.isArray(renderAsk({ question: "q", options: [] }, 40))); } group("ask — multi-select (checkbox) mode"); { + // rows = 4 options (0-3) + Type (4) + Submit (5) const base = { question: "Pick the test suites to run", options: ["unit", "e2e", "lint", "types"], sel: 0, multi: true, picked: [] }; ok("space toggles the current row on", (() => { const r = askKey(base, " "); return !r.done && JSON.stringify(r.picked) === JSON.stringify([0]); })()); ok("space again toggles it back off", (() => { const r = askKey({ ...base, picked: [0] }, " "); return JSON.stringify(r.picked) === JSON.stringify([]); })()); + ok("enter on an option row toggles (does not submit)", (() => { const r = askKey({ ...base, sel: 1, picked: [] }, "\r"); return !r.done && JSON.stringify(r.picked) === JSON.stringify([1]); })()); ok("a digit toggles that option", (() => { const r = askKey({ ...base, picked: [0] }, "3"); return JSON.stringify(r.picked) === JSON.stringify([0, 2]); })()); ok("arrows move without changing the picked set", (() => { const r = askKey({ ...base, picked: [1] }, "\x1b[B"); return r.sel === 1 && JSON.stringify(r.picked) === JSON.stringify([1]); })()); - ok("enter confirms the whole set (sorted)", (() => { const r = askKey({ ...base, picked: [2, 0] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([0, 2]) && r.values[0].label === "unit" && r.values[1].label === "lint"; })()); - ok("enter with nothing picked confirms an empty set", (() => { const r = askKey({ ...base, picked: [] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([]); })()); + ok("enter on Submit confirms the whole set (sorted)", (() => { const r = askKey({ ...base, sel: 5, picked: [2, 0] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([0, 2]) && r.values[0].label === "unit" && r.values[1].label === "lint"; })()); + ok("enter on Submit with nothing picked confirms an empty set", (() => { const r = askKey({ ...base, sel: 5, picked: [] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([]); })()); ok("esc still cancels in multi mode", askKey(base, "\x1b").cancelled === true); const rows = renderAsk({ ...base, picked: [1] }, 60); - ok("renders checkboxes", rows.some((r) => r.includes("[x]")) && rows.some((r) => r.includes("[ ]"))); - ok("multi footer mentions space-toggle and the picked count", rows.some((r) => /space/.test(r) && /toggle/.test(r) && /1 picked/.test(r))); - ok("no multi row exceeds width", rows.every((r) => r.length <= 60)); + ok("renders ◉/○ checkboxes", rows.some((r) => r.includes("◉")) && rows.some((r) => r.includes("○"))); + ok("Submit row shows the selected count", rows.some((r) => /Submit \(1 selected\)/.test(r))); + ok("multi footer mentions space-toggle", rows.some((r) => /space/.test(r) && /toggle/.test(r))); + ok("no multi box row exceeds width", rows.every((r) => r.length <= 60)); } group("ask — free-text input mode"); @@ -2640,6 +2649,11 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("shows a placeholder when empty", empty.some((r) => /type your answer/.test(r))); ok("shows the typed text with a caret", filled.some((r) => r.includes("scan") && r.includes("█"))); ok("input footer says enter submits", filled.some((r) => /enter submit/.test(r))); + // ---- the "type a different answer" transition on an option prompt ---- + const optAsk = { question: "Pick one", options: ["A", "B"], sel: 2 }; // sel 2 = Type row (0,1 opts, 2 type, 3 submit) + ok("enter on the Type row asks the host to switch to typing", askKey(optAsk, "\r").typing === true); + ok("once in type mode, a submitted answer is flagged typed", (() => { const r = askKey({ question: "Pick one", options: ["A", "B"], input: true, typed: true, text: "custom" }, "\r"); return r.done && r.value === "custom" && r.typed === true; })()); + ok("a pure free-text prompt is NOT flagged typed", (() => { const r = askKey({ question: "name?", input: true, text: "x" }, "\r"); return r.done && r.value === "x" && !r.typed; })()); } group("api-server input validation (shell-out routes reject injection)"); From 69cbe33cba3f845228bcf503bd7cf5e24fd4f648 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 18:12:49 -0700 Subject: [PATCH 12/16] nexus: Agents panel under the prompt bar (live sub-agent list, Claude-Code style) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A live list of sub-agents now sits under the prompt bar: each spawned agent (via /agents, the spawn_agents tool, or a Claude-engine Task) shows its task, a status glyph and elapsed time. Arrow-down from an empty composer drops focus into the panel; from there ↑↓ move, enter opens an agent to read its full output in a scrollable overlay, s stops a running agent, x clears the finished ones, and esc returns to the composer. Finished agents stay listed with a done / failed / stopped badge. New pure, unit-tested module lib/cli/agents.js (renderer + reducer, 38 tests). runSubagents gains per-agent controllers so a single agent can be stopped without killing the rest of the turn. --- darknode.js | 90 ++++++++++++++++++++---- lib/cli/agents.js | 175 ++++++++++++++++++++++++++++++++++++++++++++++ test/run.js | 60 ++++++++++++++++ 3 files changed, 312 insertions(+), 13 deletions(-) create mode 100644 lib/cli/agents.js diff --git a/darknode.js b/darknode.js index b3e5072..7050eb7 100755 --- a/darknode.js +++ b/darknode.js @@ -53,6 +53,7 @@ const { CMD_MAP } = require("./lib/cli/registry"); // data-driven command regist const { toolResultView, bootHeader, welcomeCard, idleHome, footerLine, helpLines, padRight: padRightV, ansiWrap, modelLabel, effortLabel, explainEngineError } = require("./lib/cli/tui-format"); // pure TUI layout helpers (compact boot header + model/effort display names) const Composer = require("./lib/cli/composer"); // pure composer model + key dispatch + per-project history (lib/cli/composer.js) const Ask = require("./lib/cli/ask"); // pure renderer + key reducer for the model's ask_user multiple-choice prompt (lib/cli/ask.js) +const Agents = require("./lib/cli/agents"); // pure renderer + key reducer for the Agents panel (live sub-agent list under the prompt bar) (lib/cli/agents.js) const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js const ASK_MCP_PATH = require("path").join(__dirname, "lib", "nexus", "ask-mcp.js"); // stdio MCP shim spawned by the engine @@ -2014,7 +2015,7 @@ function runHooks(hooks, event, env, cwd) { // build an AbortSignal wired to a ctl's kill list (so ctrl+c aborts in-flight ollama requests) function ctlSignal(ctl) { if (!ctl || !ctl.kids) return undefined; const ac = new AbortController(); ctl.kids.push(() => { try { ac.abort(); } catch (_) {} }); return ac.signal; } // ---------- Parallel sub-agents: fan a list of independent tasks out across the current engine ---------- -async function runSubagents(engine, tasks, cwd, model, onProgress, ctl, pickModel) { +async function runSubagents(engine, tasks, cwd, model, onProgress, ctl, pickModel, agentCtls) { const path = require("path"), fs = require("fs"), os = require("os"); const results = new Array(tasks.length); // Isolate each concurrent agent in its own git worktree so parallel writers can't @@ -2027,14 +2028,18 @@ async function runSubagents(engine, tasks, cwd, model, onProgress, ctl, pickMode const stamp = Date.now().toString(36); const removeWt = (wt) => { try { _cp.execSync("git worktree remove --force " + JSON.stringify(wt), { cwd, stdio: "ignore" }); } catch (_) { try { fs.rmSync(wt, { recursive: true, force: true }); } catch (__) {} } }; const runOne = async (i) => { - if (ctl && ctl.stopped) { results[i] = "(interrupted)"; if (onProgress) onProgress(i, "done"); return; } + // Each agent may carry its own controller so it can be stopped individually; + // link it to the shared controller so a global interrupt still cascades. + const actl = (agentCtls && agentCtls[i]) || ctl; + if (actl && actl !== ctl && ctl && ctl.kids) ctl.kids.push(() => { try { actl.kill(); } catch (_) {} }); + if ((ctl && ctl.stopped) || (actl && actl.stopped)) { results[i] = "(interrupted)"; if (onProgress) onProgress(i, "done", results[i]); return; } if (onProgress) onProgress(i, "run"); let dir = cwd; if (useWt) { const wt = path.join(os.tmpdir(), "nexus-agent-" + stamp + "-" + i); try { _cp.execSync("git worktree add --detach " + JSON.stringify(wt) + " " + baseCommit, { cwd, stdio: "ignore" }); worktrees[i] = dir = wt; } catch (_) { dir = cwd; } } let out; - try { if (engine === "ollama") { const r = await ollamaExec(model, tasks[i], "", dir, ctlSignal(ctl)); out = (r.output || "").trim(); } else { const r = await runEngineTask(engine, tasks[i], dir, true, false, null, ctl, pickModel ? pickModel(tasks[i]) : undefined); out = (r.output || "").trim(); } } + try { if (engine === "ollama") { const r = await ollamaExec(model, tasks[i], "", dir, ctlSignal(actl)); out = (r.output || "").trim(); } else { const r = await runEngineTask(engine, tasks[i], dir, true, false, null, actl, pickModel ? pickModel(tasks[i]) : undefined); out = (r.output || "").trim(); } } catch (e) { out = "error: " + e.message; } - results[i] = out; if (onProgress) onProgress(i, "done"); + results[i] = out; if (onProgress) onProgress(i, "done", out); }; // With isolation, agents run concurrently; without it (no git, or ollama), serialize to avoid corrupting the shared dir. const conc = useWt ? Math.max(1, Math.min(4, tasks.length)) : 1; @@ -2597,7 +2602,24 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // reached 726 turns / 794K context / one context that never reset). let carryNote = ""; let localReplay = []; // ollama history rebuilt from a restored transcript (oMsgs itself is never persisted) - let expanded = false, mode = 1, runningShells = 0, activeAgents = 0, scroll = 0, menuSel = 0, mouseOn = false, hack = false; let _lastEscTs = 0; // double-Esc (rewind) detector // mode: 0 normal, 1 auto-accept, 2 plan, 3 bypass (waives the destructive-command guard); scroll = lines up from bottom; menuSel = highlighted slash-menu row; mouseOn = capture the mouse (wheel scroll) vs. release it so the terminal can select/copy text + let expanded = false, mode = 1, runningShells = 0, activeAgents = 0, scroll = 0, menuSel = 0, mouseOn = false, hack = false; let _lastEscTs = 0; + // ---- Agents panel (lib/cli/agents.js): a live list of sub-agents under the + // prompt bar. `agents` is the registry (one entry per sub-agent, kept after + // it finishes); `agentSel` is the focused row while the panel has the + // keyboard (-1 = composer has focus); `agentView` is the open transcript + // overlay { i, scroll } or null. addAgent/finishAgent feed the registry. + let agents = [], agentSel = -1, agentView = null; + const AGENTS_MAX = 24; // cap the registry; drop the oldest FINISHED agents past this + const addAgent = (task, opts) => { const a = Object.assign({ id: "ag_" + Date.now().toString(36) + "_" + agents.length, task: String(task || "").slice(0, 300), status: "run", start: Date.now(), result: "", native: true }, opts || {}); agents.push(a); if (agents.length > AGENTS_MAX) { const keep = agents.filter((x) => x.status === "run"); const fin = agents.filter((x) => x.status !== "run"); agents = fin.slice(Math.max(0, fin.length - (AGENTS_MAX - keep.length))).concat(keep).sort((x, y) => x.start - y.start); } return a; }; + const finishAgent = (a, status, result) => { if (!a || a.status !== "run") return; a.status = status || "ok"; a.end = Date.now(); if (result != null) a.result = String(result); }; + // Stop one running agent. Native sub-agents carry their own controller (a.ctl); + // a Claude-engine Task runs inside the main turn and can't be killed on its own, + // so point the user at the turn interrupt instead. + const stopAgent = (a) => { + if (!a || a.status !== "run") return; + if (a.ctl && a.ctl.kill) { try { a.ctl.kill(); } catch (_) {} finishAgent(a, "stopped", a.result || "(stopped by you)"); } + else transcript.push({ role: "system", text: "can't stop a single Claude sub-agent — press Esc to interrupt the whole turn" }); + }; // double-Esc (rewind) detector // mode: 0 normal, 1 auto-accept, 2 plan, 3 bypass (waives the destructive-command guard); scroll = lines up from bottom; menuSel = highlighted slash-menu row; mouseOn = capture the mouse (wheel scroll) vs. release it so the terminal can select/copy text let gitBranch = ""; // cached "branch" (+ "*" when the tree is dirty), shown in the status bar const refreshGit = async () => { try { const b = await sh(["rev-parse", "--abbrev-ref", "HEAD"]); if (b.err) { gitBranch = ""; return; } const st = await sh(["status", "--porcelain"]); const next = (b.stdout || "").trim() + ((st.stdout || "").trim() ? "*" : ""); if (next !== gitBranch) { gitBranch = next; try { render(); } catch (_) {} } } catch (_) { gitBranch = ""; } }; // One-shot project pulse (last commit, commit count, tracked file count) for @@ -3493,13 +3515,18 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const askRows = pendingAsk ? Ask.renderAsk(pendingAsk, C, { cyan, gray, bold, dim, green }) : null; const effortRows = (!askRows && pendingEffort) ? renderEffortPicker(C, pendingEffort.sel) : null; const btwRows = (!askRows && !effortRows && btw) ? renderBtw(C, R, btw) : null; - let cardRows = askRows || effortRows || btwRows; // a full-width card replaces the composer + menu + const agentViewRows = (!askRows && !effortRows && !btwRows && agentView && agents[agentView.i]) ? Agents.viewRows(agents[agentView.i], C, R, agentView.scroll, { cyan, gray, bold, dim, green, red, yellow, mag }, Date.now()) : null; + let cardRows = askRows || effortRows || btwRows || agentViewRows; // a full-width card replaces the composer + menu if (cardRows && cardRows.length > R - 2) cardRows = cardRows.slice(0, Math.max(1, R - 2)); // never build a card taller than the screen (would overflow the diff'd frame) // breathing room below the footer so the composer floats off the terminal // floor (matches Claude Code, which leaves a margin under its prompt). // clamped away on short terminals so it never eats the transcript. const bottomMargin = Math.min(5, Math.max(0, R - 16)); - const chrome = (cardRows ? (1 + cardRows.length + 1) : (fixedChrome + menuReserve + inRows)) + bottomMargin; // spacer + composer + reserved menu + footer + bottom margin + // Agents panel: the live sub-agent list sits between the composer/menu and + // the footer (Claude-Code layout). Hidden while a full-width card owns the + // bottom. Capped so a long list never crowds out the transcript. + const agentPanelRows = (!cardRows && agents.length) ? Agents.panelRows(agents, { now: Date.now(), sel: agentSel, width: C, max: Math.min(6, Math.max(2, (R >> 2))), colors: { cyan, gray, bold, dim, green, red, yellow, mag } }) : []; + const chrome = (cardRows ? (1 + cardRows.length + 1) : (fixedChrome + menuReserve + inRows + agentPanelRows.length)) + bottomMargin; // spacer + composer + reserved menu + agents panel + footer + bottom margin const bodyRows = Math.max(0, R - chrome); const lines = bodyLines(); const maxScroll = Math.max(0, lines.length - bodyRows); @@ -3593,6 +3620,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const idx = menuStart + i; const [nm, ds] = combined[idx]; const sel = idx === menuSel; const pos = (sel && combined.length > menuRows) ? gray(" (" + (menuSel + 1) + "/" + combined.length + ")") : ""; const nmW = Math.min(18, Math.max(10, Math.floor(C / 4))); const incompat = menu.length && nm[0] === "/" && !cmdOkFor(nm); const nmShown = sel ? bold(cyan(padRightV(nm, nmW))) : (incompat ? dim(padRightV(nm, nmW)) : padRightV(nm, nmW)); const tail = incompat ? red(" not compatible with " + _curM) : gray(" " + (ds || "")); frame.push(clip((sel ? cyan(" › ") : " ") + nmShown + tail + pos, C - 2)); } } + for (const r of agentPanelRows) frame.push(clip(r, C)); // the Agents panel, under the prompt bar // footer: contextual hint on the left, status on the right. The status // menu (cost, savings & more) is the clickable "..." at the far right; // when open its buttons take over the row. @@ -3911,6 +3939,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const finish = (res) => { for (const it of block.items) if (it.type === "tool" && it.status === "run") { it.status = res && res.interrupted ? "err" : "ok"; it.interrupted = !!(res && res.interrupted); it.end = Date.now(); } runningShells = 0; activeAgents = 0; ctl = null; + for (const rg of agents) if (rg.status === "run" && rg.native === false) finishAgent(rg, res && res.interrupted ? "stopped" : "ok"); // any Claude sub-agent still open when the turn ends if (!block.items.length || !block.items.some((i) => i.type === "text" && i.full.trim())) { const t = textItem(); if (!t.full.trim()) t.full = res && res.interrupted ? "(interrupted)" : (res && res.output) || "(no output)"; } const dt = ((Date.now() - stat.t0) / 1000).toFixed(1); const din = sess.inTok - stat.inTok0, dout = sess.outTok - stat.outTok0, dcost = sess.cost - stat.cost0; @@ -3984,13 +4013,13 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (["Write", "Edit", "MultiEdit"].includes(tu.name)) _item.diff = editDiff(tu.name, tu.input); block.items.push(_item); if (tu.name === "Bash") { runningShells++; stat.cmds++; } - if (tu.name === "Task" || tu.name === "Agent") activeAgents++; + if (tu.name === "Task" || tu.name === "Agent") { activeAgents++; const _ag = addAgent((tu.input && (tu.input.description || tu.input.subagent_type || tu.input.prompt)) || "agent", { native: false, engine }); _item._agId = _ag.id; } // mirror a Claude-engine sub-agent into the Agents panel if (["Write", "Edit", "MultiEdit", "NotebookEdit"].includes(tu.name) && (tu.input.file_path || tu.input.notebook_path)) { const fp = tu.input.file_path || tu.input.notebook_path; stat.files.add(base(fp)); const r = relOf(fp); if (r) stat.paths.add(r); } render(); }, onToolResult: (tr) => { const it = block.items.find((x) => x.type === "tool" && x.id === tr.id); - if (it) { it.status = tr.isError ? "err" : "ok"; it.end = Date.now(); it.result = tr.content; it.isError = !!tr.isError; it.detail = oneline(resultText(tr.content), 260); if (it.name === "Bash" && runningShells) runningShells--; if ((it.name === "Task" || it.name === "Agent") && activeAgents) activeAgents--; } + if (it) { it.status = tr.isError ? "err" : "ok"; it.end = Date.now(); it.result = tr.content; it.isError = !!tr.isError; it.detail = oneline(resultText(tr.content), 260); if (it.name === "Bash" && runningShells) runningShells--; if ((it.name === "Task" || it.name === "Agent") && activeAgents) activeAgents--; if (it._agId) { const rg = agents.find((x) => x.id === it._agId); if (rg && rg.status === "run") finishAgent(rg, tr.isError ? "fail" : "ok", resultText(tr.content)); } } render(); }, onUsage: (u, _m, sub) => { confOut += (u.output_tokens || 0); estOut = 0; sess.liveOut = confOut; if (!sub) { const c = (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.cache_read_input_tokens || 0); if (c > 0) lastCtx = c + (u.output_tokens || 0); } }, // lock in the real output tokens for the message that just finished (each agentic tool round is its own assistant message) and clear the streaming estimate; the next message's estimate climbs on top of this. lastCtx tracks the latest main-thread call's prompt = the real context size @@ -4141,7 +4170,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { else if (name === "run_background") { if (!a.command || typeof a.command !== "string") { result = { error: "run_background needs a non-empty command string" }; } else { const p = _cp.spawn(process.platform === "win32" ? "cmd" : "sh", process.platform === "win32" ? ["/c", a.command] : ["-c", a.command], { cwd, env: process.env }); const id = bgJobs.start(a.command, p, Date.now()); p.stdout && p.stdout.on("data", (d) => bgJobs.append(id, d)); p.stderr && p.stderr.on("data", (d) => bgJobs.append(id, d)); p.on("close", (code) => bgJobs.finish(id, code)); p.on("error", (e) => { bgJobs.append(id, "spawn error: " + e.message); bgJobs.finish(id, 1); }); result = { ok: true, jobId: id, status: "running", hint: "poll it with check_background{id:'" + id + "'}, stop it with stop_background{id:'" + id + "'}" }; } } else if (name === "check_background") { if (a.id) { const j = bgJobs.get(a.id); result = j ? { id: j.id, status: j.status, code: j.code, output: compactOutput(bgJobs.tail(a.id, 6000), 4000) } : { error: "no such job " + a.id }; } else result = { jobs: bgJobs.list() }; } else if (name === "stop_background") { result = a.id ? { ok: bgJobs.stop(a.id), stopped: a.id } : { error: "stop_background needs a job id" }; } - else if (name === "spawn_agents") { const tasks = (a.tasks || []).map(String).filter(Boolean).slice(0, 8); const outs = await runSubagents(engine, tasks, cwd, mdl, null, ctl); result = { agents: outs.map((o2, i) => ({ task: tasks[i], result: (o2 || "").slice(0, 1500) })) }; } + else if (name === "spawn_agents") { const tasks = (a.tasks || []).map(String).filter(Boolean).slice(0, 8); const actls = tasks.map(() => makeCtl()); const regs = tasks.map((tk, i) => addAgent(tk, { native: engine !== "claude", engine, ctl: actls[i] })); render(); const outs = await runSubagents(engine, tasks, cwd, mdl, (i, phase, out) => { if (phase === "done" && regs[i].status === "run") finishAgent(regs[i], /^error:/.test(String(out || "")) ? "fail" : "ok", out); render(); }, ctl, undefined, actls); regs.forEach((rg, i) => { if (rg.status === "run") finishAgent(rg, "ok", outs[i]); }); result = { agents: outs.map((o2, i) => ({ task: tasks[i], result: (o2 || "").slice(0, 1500) })) }; } else if (String(name).startsWith("mcp__")) { const srv = mcpServers.find((s) => !s.error && String(name).slice(5).startsWith(s.name + "__")); if (!srv) result = { error: "MCP tool not connected: " + name }; else { const tool = String(name).slice(5 + srv.name.length + 2); const r = await srv.call("tools/call", { name: tool, arguments: a }); result = { content: resultText((r && r.content) || r) }; } } else if (name === "discover") { result = { tools: discoverTools(a.query || a.q || "", TOOL_CATALOG.concat(mcpToolList().map((m) => [m.full, m.desc]))) }; } else if (name === "repo_map" || name === "repomap" || name === "map") { const rm = getRepoMap({ fresh: !!a.fresh }); result = rm && rm.map ? { map: rm.text, files: rm.map.fileCount, symbols: rm.map.symbolCount } : { error: "could not build a repo map here" }; } @@ -4240,17 +4269,22 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { activeAgents = tasks.length; const cards = tasks.map((tk, i) => ({ type: "tool", id: "ag" + i, name: "Task", label: "Task(" + oneline(tk, 30) + ")", status: "run", start: Date.now(), detail: tk })); cards.forEach((c) => block.items.push(c)); + // Mirror each task into the Agents panel (live list under the prompt bar), + // each with its own controller so it can be stopped individually. + const agentCtls = tasks.map(() => makeCtl()); + const regs = tasks.map((tk, i) => addAgent(tk, { native: engine !== "claude", engine, ctl: agentCtls[i] })); startTick(); render(); - const agentsCtl = ctl; const pick = (cowork.on && engine === "claude" && cowork.weakKind === "claude") ? ((t) => { const est = Math.ceil(t.length / 4) + 800; if (isMechanical(t) && shouldDelegate(est, est * 4, cowork.strong, cowork.weak)) { impact.delegated++; impact.coworkSaved += (priceOf(cowork.strong).out - priceOf(cowork.weak).out) * (est * 3) / 1e6; return cowork.weak; } return cowork.strong; }) : (cowork.on && engine === "claude" ? ((t) => cowork.strong) : null); (async () => { const mdl = engine === "ollama" ? (sess.model && sess.model !== engine ? sess.model : pickCoderModel(await ollamaTags())) : sess.model; return runSubagents(engine, tasks, cwd, mdl, (i, phase) => { if (phase === "done") { cards[i].status = "ok"; cards[i].end = Date.now(); activeAgents = Math.max(0, activeAgents - 1); } render(); }, agentsCtl, pick); })() + const agentsCtl = ctl; const pick = (cowork.on && engine === "claude" && cowork.weakKind === "claude") ? ((t) => { const est = Math.ceil(t.length / 4) + 800; if (isMechanical(t) && shouldDelegate(est, est * 4, cowork.strong, cowork.weak)) { impact.delegated++; impact.coworkSaved += (priceOf(cowork.strong).out - priceOf(cowork.weak).out) * (est * 3) / 1e6; return cowork.weak; } return cowork.strong; }) : (cowork.on && engine === "claude" ? ((t) => cowork.strong) : null); (async () => { const mdl = engine === "ollama" ? (sess.model && sess.model !== engine ? sess.model : pickCoderModel(await ollamaTags())) : sess.model; return runSubagents(engine, tasks, cwd, mdl, (i, phase, out) => { if (phase === "done") { cards[i].status = "ok"; cards[i].end = Date.now(); activeAgents = Math.max(0, activeAgents - 1); if (regs[i].status === "run") finishAgent(regs[i], /^error:/.test(String(out || "")) ? "fail" : "ok", out); } render(); }, agentsCtl, pick, agentCtls); })() .then((outs) => { const t = ensureText(block); t.full = outs.map((o, i) => "### agent " + (i + 1) + " — " + oneline(tasks[i], 60) + "\n" + (o || "(no output)")).join("\n\n"); for (const c of cards) if (c.status === "run") { c.status = "ok"; c.end = Date.now(); } + regs.forEach((rg, i) => { if (rg.status === "run") finishAgent(rg, /^error:/.test(String(outs[i] || "")) ? "fail" : "ok", outs[i]); }); sess.outTok += Math.ceil(outs.join("").length / 4); sess.ctxUsed = sess.inTok + sess.outTok; activeAgents = 0; busy = false; ctl = null; block.summary = tasks.length + " agents · ↑" + fmtK(sess.inTok - in0) + " ↓" + fmtK(sess.outTok - out0) + " tok · " + fmtDur((Date.now() - t0) / 1000); try { saveSession(); } catch (_) {} render(); - }).catch(() => { activeAgents = 0; busy = false; ctl = null; render(); }); + }).catch(() => { regs.forEach((rg) => { if (rg.status === "run") finishAgent(rg, "fail", "(failed)"); }); activeAgents = 0; busy = false; ctl = null; render(); }); }; // quick TCP connect scan (Nexus ships with the Darknode security toolkit) const quickScan = (host, ports) => new Promise((resolve) => { @@ -5752,7 +5786,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // racing through it three entries a notch. const _burst = s.match(/\x1b[[O][AB]/g); if (_burst && _burst.length > 1 && _burst.join("") === s) { - if (!btw && !pendingAsk && !pendingEffort && !navOpen && !composer.searchMode && !slashMatches().length && !argMatches().length) { const up = s[2] === "A"; scroll = up ? scroll + _burst.length : Math.max(0, scroll - _burst.length); render(); return; } + if (!btw && !agentView && agentSel < 0 && !pendingAsk && !pendingEffort && !navOpen && !composer.searchMode && !slashMatches().length && !argMatches().length) { const up = s[2] === "A"; scroll = up ? scroll + _burst.length : Math.max(0, scroll - _burst.length); render(); return; } for (const k of _burst) process.stdin.emit("data", k); return; } // Several keys can land in one chunk (key repeat, a fast typist over ssh): @@ -5804,6 +5838,22 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (s === "\r" || s === "\n" || s === " " || s === "\x1b" || s === "\x03") { btw = null; render(); return; } return; // overlay owns the keyboard } + // ---- the Agents transcript overlay owns the keyboard while open ---- + if (agentView) { + if (isMouse) return; + const a = agents[agentView.i]; + if (!a) { agentView = null; render(); return; } + if (s === "\x1b[A" || s === "\x1bOA") { agentView.scroll = Math.max(0, agentView.scroll - 1); render(); return; } // up + if (s === "\x1b[B" || s === "\x1bOB") { agentView.scroll++; render(); return; } // down + if (s === "\x1b[5~") { agentView.scroll = Math.max(0, agentView.scroll - 10); render(); return; } // pgup + if (s === "\x1b[6~") { agentView.scroll += 10; render(); return; } // pgdn + if (s === "[" || s === "\x1b[D" || s === "\x1bOD") { if (agentView.i > 0) { agentView.i--; agentView.scroll = 0; } render(); return; } // prev agent + if (s === "]" || s === "\x1b[C" || s === "\x1bOC") { if (agentView.i < agents.length - 1) { agentView.i++; agentView.scroll = 0; } render(); return; } // next agent + if (s === "c" || s === "C") { const txt = String(a.result || ""); if (txt) { try { out.write("\x1b]52;c;" + Buffer.from(txt).toString("base64") + "\x07"); } catch (_) {} } render(); return; } // copy output + if ((s === "s" || s === "S") && a.status === "run") { stopAgent(a); render(); return; } + if (s === "\r" || s === "\n" || s === "\x1b" || s === "\x03" || s === "q") { agentView = null; render(); return; } + return; // overlay owns the keyboard + } // ---- the /effort slider owns the keyboard while open ---- if (pendingEffort) { if (isMouse) return; @@ -5825,6 +5875,18 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (r.sel != null) pendingAsk.sel = r.sel; if (r.pick != null) pendingAsk.pick = r.pick; if (r.picked) pendingAsk.picked = r.picked; if (r.text != null) pendingAsk.text = r.text; render(); return; } + // ---- Agents panel has the keyboard (arrowed down into it from the composer) ---- + if (agentSel >= 0 && agents.length) { + if (isMouse) return; + const r = Agents.panelKey({ sel: agentSel }, s, agents.length); + if (r.leave) { agentSel = -1; render(); return; } + if (r.open != null) { agentView = { i: r.open, scroll: 0 }; agentSel = -1; render(); return; } + if (r.stop != null) { stopAgent(agents[r.stop]); render(); return; } + if (r.clear) { agents = agents.filter((a) => a.status === "run"); if (!agents.length) agentSel = -1; else agentSel = Math.min(agentSel, agents.length - 1); render(); return; } + if (r.sel != null) agentSel = r.sel; + render(); return; + } + if (agentSel >= 0 && !agents.length) agentSel = -1; // the last agent was cleared out from under the focus // ---- reverse-i-search owns the keyboard while active (mouse still works) ---- if (composer.searchMode && !isMouse) { @@ -5927,6 +5989,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (cm.length && s === "\t") { if (_mm.length) { input = (_mm[menuSel] || _mm[0])[0] + " "; refreshArgCache(); } else { const sp = input.indexOf(" "); input = input.slice(0, sp) + " " + (_am[menuSel] || _am[0])[0] + " "; } curPos = input.length; menuSel = 0; render(); return; } if (_mm.length && (s === "\r" || s === "\n")) { const t = (_mm[menuSel] || _mm[0])[0]; nextQueue.push(t); input = ""; curPos = 0; menuSel = 0; render(); return; } if (s === "\x1b" || s === "\x03") { if (ctl && ctl.kill) { ctl.kill(); transcript.push({ role: "system", text: "interrupting current turn…" }); } render(); return; } + if (isDown && agentSel < 0 && !agentView && agents.length && !input) { agentSel = 0; render(); return; } // Down on an empty prompt drops focus into the Agents panel if (isUp || isDown) { arrowVert(isUp ? -1 : 1); return; } // same as idle: visual row, then history / queued recall // Full composer editing mid-turn (arrows, word moves, Ctrl+U/K/W, undo…); // Enter queues the draft instead of sending it. @@ -5952,6 +6015,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { return; } + if (isDown && agentSel < 0 && !agentView && agents.length && !input) { agentSel = 0; render(); return; } // Down on an empty prompt drops focus into the Agents panel if ((isUp || isDown) && !(composer.vim && composer.vimMode === "normal")) { arrowVert(isUp ? -1 : 1); return; } // ---- everything else: the pure composer key dispatch (lib/cli/composer.js) ---- diff --git a/lib/cli/agents.js b/lib/cli/agents.js new file mode 100644 index 0000000..fb59b99 --- /dev/null +++ b/lib/cli/agents.js @@ -0,0 +1,175 @@ +"use strict"; +// ============================================================================ +// agents — a PURE renderer + key reducer for the Agents panel: the live list of +// sub-agents (spawned via /agents, the spawn_agents tool, or a Claude-engine +// Task) that sits under the prompt bar, Claude-Code style. Each agent shows its +// task, a status glyph and elapsed time; a running agent can be opened to read +// its output or stopped from the list, and finished agents stay listed with a +// done / failed / stopped badge until cleared. +// +// Everything here is pure + snapshot-testable: no DOM, no I/O, no timers, no +// module-scope state. The host (darknode.js) owns the registry array and the +// focus/selection state, feeds raw key sequences through `panelKey`, and paints +// the rows from `panelRows` (the compact list) and `viewRows` (the full-screen +// transcript of one agent). `now` is injected so elapsed time is deterministic +// in tests, and colors are injected so tests see plain text. +// ============================================================================ + +const IDENT = (s) => s; +function theme(c) { + c = c || {}; + return { cyan: c.cyan || IDENT, gray: c.gray || IDENT, bold: c.bold || IDENT, dim: c.dim || IDENT, green: c.green || IDENT, red: c.red || IDENT, yellow: c.yellow || IDENT, mag: c.mag || IDENT }; +} + +// Human elapsed time: "5s", "1m23s", "2h04m". Clamped to >= 0. +function fmtDur(ms) { + let s = Math.floor(Math.max(0, ms | 0) / 1000); + if (s < 60) return s + "s"; + const m = Math.floor(s / 60); s = s % 60; + if (m < 60) return m + "m" + (s < 10 ? "0" : "") + s + "s"; + const h = Math.floor(m / 60), mm = m % 60; + return h + "h" + (mm < 10 ? "0" : "") + mm + "m"; +} + +// How long an agent has been (or was) running, given the current clock. +function elapsed(a, now) { return ((a && a.end) || now || 0) - ((a && a.start) || 0); } + +// Status → { glyph, badge, paint }. run is a half-filled dot (yellow), ok a +// solid dot (green), fail a cross (red), stopped a square (dim). +function statusOf(a, t) { + const s = a && a.status; + if (s === "ok") return { glyph: t.green("●"), badge: "done", paint: t.green }; + if (s === "fail") return { glyph: t.red("✗"), badge: "failed", paint: t.red }; + if (s === "stopped") return { glyph: t.dim("■"), badge: "stopped", paint: t.dim }; + return { glyph: t.yellow("◐"), badge: "running", paint: t.yellow }; +} + +// Truncate a plain string to w columns with a trailing ellipsis (no ANSI in). +function fit(s, w) { s = String(s == null ? "" : s).replace(/\s+/g, " ").trim(); if (w < 0) w = 0; if (s.length <= w) return s; if (w <= 1) return s.slice(0, w); return s.slice(0, w - 1) + "…"; } + +// Plain word-wrap for the transcript body (no ANSI inside — colored by caller). +function wrapPlain(s, w) { + if (w < 1) w = 1; + const out = []; + for (const para of String(s == null ? "" : s).replace(/\r/g, "").split("\n")) { + const words = para.replace(/\t/g, " ").split(" "); + let line = ""; + const hard = (word) => { let r = word; while (r.length > w) { out.push(r.slice(0, w)); r = r.slice(w); } return r; }; + for (const word of words) { + if (!line.length) line = word.length <= w ? word : hard(word); + else if (line.length + 1 + word.length <= w) line += " " + word; + else { out.push(line); line = word.length <= w ? word : hard(word); } + } + out.push(line); + } + return out.length ? out : [""]; +} + +// The window of agent rows to show when the list is taller than `max`: a stable +// region that follows the selection (or pins to the most-recent when unfocused). +function windowStart(n, sel, max) { + if (n <= max) return 0; + if (sel < 0) return n - max; // unfocused: show the newest + return Math.max(0, Math.min(sel - (max >> 1), n - max)); +} + +// panelRows(agents, opt) -> string[] (compact list under the prompt bar). +// opt: { now, sel, width, colors, max } +// sel = focused row index when the panel has keyboard focus, else -1 (idle). +// Returns [] when there are no agents (the panel takes no space). Rows are not +// padded — the host's frame diff clears to end-of-line, same as the slash menu. +function panelRows(agents, opt) { + agents = Array.isArray(agents) ? agents : []; + if (!agents.length) return []; + opt = opt || {}; + const t = theme(opt.colors); + const now = opt.now || Date.now(); + const C = Math.max(20, (opt.width | 0) || 80); + const rawSel = opt.sel == null ? -1 : (opt.sel | 0); + const focus = rawSel >= 0; // sel < 0 is the idle (unfocused) sentinel + const sel = focus ? clampSel(rawSel, agents.length) : -1; + const max = Math.max(1, (opt.max | 0) || 5); + const running = agents.filter((a) => a && a.status === "run").length; + const done = agents.length - running; + const out = []; + // header: "agents 2 running · 1 done" + a right-side nav hint. + const sum = []; + if (running) sum.push(running + " running"); + if (done) sum.push(done + " done"); + const hint = focus ? "↑↓ move · enter open · s stop · x clear · esc back" : "↓ to select"; + out.push(" " + t.dim("agents") + t.gray(" " + sum.join(" · ")) + t.gray(" " + hint)); + const start = windowStart(agents.length, sel, max); + const shown = agents.slice(start, start + max); + shown.forEach((a, j) => { + const gi = start + j; + const on = focus && gi === sel; + const st = statusOf(a, t); + const el = fmtDur(elapsed(a, now)); + const cur = on ? t.cyan("❯ ") : " "; + const taskW = Math.max(6, C - 2 - 2 - 2 - 2 - el.length - 1); // indent + cursor + glyph+sp + gap + elapsed + const task = fit(a.task, taskW); + const label = on ? t.bold(task) : (a.status === "run" ? task : t.gray(task)); + out.push(" " + cur + st.glyph + " " + label + " " + t.gray(el)); + }); + if (agents.length > shown.length) out.push(" " + t.dim(" +" + (agents.length - shown.length) + " more")); + return out; +} + +// viewRows(agent, C, R, scroll, colors) -> string[] (full-screen transcript of +// one agent; replaces the composer, mirroring the /btw overlay geometry). The +// body is the agent's output so far, scrollable; a running agent shows its +// partial output (or a "running…" note) and a live elapsed clock. +function viewRows(agent, C, R, scroll, colors, now) { + const t = theme(colors); + const w = Math.max(12, (C | 0) - 4); + const avail = Math.max(8, (R | 0) - 4); + const a = agent || { task: "", status: "run", start: 0 }; + const st = statusOf(a, t); + const head = []; + head.push(" " + t.bold("Agent") + t.gray(" — sub-agent output") + (a.native === false ? t.gray(" · " + (a.engine || "engine")) : "")); + for (const ql of wrapPlain("❯ " + String(a.task || ""), w)) head.push(" " + t.cyan(ql)); + head.push(" " + st.paint(st.badge) + t.gray(" · " + fmtDur(elapsed(a, now || Date.now())))); + head.push(""); + const bodyMax = Math.max(2, avail - head.length - 3); + const resultText = String(a.result == null ? "" : a.result); + const body = resultText ? wrapPlain(resultText, w) : [t.gray(a.status === "run" ? "running…" : "(no output)")]; + let sc = scroll | 0; + const maxSc = Math.max(0, body.length - bodyMax); + if (sc > maxSc) sc = maxSc; + if (sc < 0) sc = 0; + const vis = body.slice(sc, sc + bodyMax); + const rows = head.concat(vis.map((l) => " " + l)); + if (body.length > bodyMax) rows.push(" " + t.gray(" … " + Math.min(body.length, sc + bodyMax) + "/" + body.length + " lines")); + rows.push(""); + rows.push(" " + t.gray("esc close · ↑↓ scroll · " + (a.status === "run" ? "s stop · " : "") + "c copy")); + return rows; +} + +function clampSel(sel, n) { sel = sel | 0; if (n <= 0) return 0; if (sel < 0) return 0; if (sel > n - 1) return n - 1; return sel; } + +// panelKey(state, key, n) -> a patch describing what a keypress did while the +// Agents panel has focus: +// { sel } navigation (host stores it back) +// { open: i } open agent i's transcript +// { stop: i } stop / cancel agent i +// { clear } clear the finished agents from the list +// { leave } release focus back to the composer +// `state` = { sel }; `n` = agent count. Pure reducer over a raw key sequence. +function panelKey(state, key, n) { + n = n | 0; + const sel = clampSel(state && state.sel, n); + if (n <= 0) return { leave: true }; + if (key === "\x1b" || key === "\x03") return { leave: true }; // esc / ctrl+c → back to composer + if (key === "\x1b[A" || key === "[A" || key === "\x1bOA") { // up (off the top row → leave) + if (sel <= 0) return { leave: true }; + return { sel: sel - 1 }; + } + if (key === "\x1b[B" || key === "[B" || key === "\x1bOB") return { sel: Math.min(n - 1, sel + 1) }; // down + if (key === "\r" || key === "\n" || key === "\x1b[C" || key === "\x1bOC") return { open: sel }; // enter / → open + if (key === "s" || key === "S" || key === "\x7f" || key === "\b") return { stop: sel }; // s / backspace stop + if (key === "x" || key === "X") return { clear: true }; // clear finished agents + if (/^[1-9]$/.test(key)) { const i = +key - 1; return i < n ? { open: i } : { sel }; } // digit opens + return { sel }; // unrelated key: keep focus +} + +module.exports = { panelRows, viewRows, panelKey, fmtDur, elapsed, statusOf, wrapPlain, fit, windowStart }; diff --git a/test/run.js b/test/run.js index a6786bf..dc46a44 100644 --- a/test/run.js +++ b/test/run.js @@ -2656,6 +2656,66 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("a pure free-text prompt is NOT flagged typed", (() => { const r = askKey({ question: "name?", input: true, text: "x" }, "\r"); return r.done && r.value === "x" && !r.typed; })()); } + group("agents panel (live sub-agent list under the prompt bar)"); + { + const A = require("../lib/cli/agents"); + const now = 100000; + const agents = [ + { id: "ag0", task: "add unit tests for the parser", status: "ok", start: now - 83000, end: now - 20000, result: "Added 12 tests; all pass." }, + { id: "ag1", task: "write the API docs", status: "run", start: now - 5000 }, + { id: "ag2", task: "fix the lint errors", status: "fail", start: now - 60000, end: now - 10000, result: "could not resolve 3 warnings" }, + ]; + // ---- fmtDur ---- + eq("fmtDur seconds", A.fmtDur(5000), "5s"); + eq("fmtDur minutes+seconds", A.fmtDur(83000), "1m23s"); + eq("fmtDur hours+minutes", A.fmtDur((2 * 3600 + 4 * 60) * 1000), "2h04m"); + eq("fmtDur clamps negatives to 0s", A.fmtDur(-5), "0s"); + // ---- elapsed uses end when finished, now while running ---- + eq("elapsed of a finished agent uses its end", A.elapsed(agents[0], now), 63000); + eq("elapsed of a running agent uses now", A.elapsed(agents[1], now), 5000); + // ---- panelRows ---- + const idle = A.panelRows(agents, { now, sel: -1, width: 70 }); + ok("empty registry renders nothing", A.panelRows([], { now, width: 70 }).length === 0); + ok("header summarises running + done counts", /1 running/.test(idle[0]) && /2 done/.test(idle[0])); + ok("idle header hints how to select", /to select/.test(idle[0])); + ok("lists each agent's task", idle.some((r) => /add unit tests/.test(r)) && idle.some((r) => /write the API docs/.test(r)) && idle.some((r) => /fix the lint errors/.test(r))); + ok("shows elapsed per agent", idle.some((r) => /1m03s/.test(r)) && idle.some((r) => /5s/.test(r))); + ok("idle panel shows no ❯ cursor", !idle.slice(1).some((r) => r.includes("❯"))); + const foc = A.panelRows(agents, { now, sel: 1, width: 70 }); + ok("focused header hints open/stop/back", /enter open/.test(foc[0]) && /stop/.test(foc[0]) && /esc back/.test(foc[0])); + ok("focused row carries the ❯ cursor on the selected task", foc.some((r) => r.includes("❯") && /write the API docs/.test(r))); + ok("long task is truncated with an ellipsis at a narrow width", A.panelRows([{ task: "x".repeat(200), status: "run", start: now }], { now, width: 40 }).some((r) => r.includes("…"))); + const many = Array.from({ length: 9 }, (_, i) => ({ id: "a" + i, task: "task " + i, status: "run", start: now })); + const win = A.panelRows(many, { now, sel: -1, width: 70, max: 4 }); + ok("caps the visible rows and notes the overflow", win.filter((r) => /task \d/.test(r)).length === 4 && win.some((r) => /\+5 more/.test(r))); + ok("unfocused window shows the most-recent agents", win.some((r) => /task 8/.test(r)) && !win.some((r) => /task 0\b/.test(r))); + // ---- windowStart ---- + eq("no window when it fits", A.windowStart(3, 1, 5), 0); + eq("unfocused window pins to the tail", A.windowStart(9, -1, 4), 5); + eq("focused window follows the selection", A.windowStart(9, 7, 4), 5); + // ---- panelKey reducer ---- + eq("down moves selection +1", A.panelKey({ sel: 0 }, "\x1b[B", 3).sel, 1); + eq("down clamps at the last agent", A.panelKey({ sel: 2 }, "\x1b[B", 3).sel, 2); + eq("up moves selection -1", A.panelKey({ sel: 2 }, "\x1b[A", 3).sel, 1); + ok("up off the top row leaves the panel", A.panelKey({ sel: 0 }, "\x1b[A", 3).leave === true); + ok("enter opens the selected agent", A.panelKey({ sel: 1 }, "\r", 3).open === 1); + ok("a digit opens that agent directly", A.panelKey({ sel: 0 }, "2", 3).open === 1); + ok("an out-of-range digit keeps focus (no open)", (() => { const r = A.panelKey({ sel: 0 }, "9", 3); return r.open == null && r.leave == null; })()); + ok("s stops the selected agent", A.panelKey({ sel: 2 }, "s", 3).stop === 2); + ok("x clears the finished agents", A.panelKey({ sel: 0 }, "x", 3).clear === true); + ok("esc leaves the panel", A.panelKey({ sel: 1 }, "\x1b", 3).leave === true); + ok("an empty registry always leaves", A.panelKey({ sel: 0 }, "\x1b[B", 0).leave === true); + ok("an unrelated key keeps focus", (() => { const r = A.panelKey({ sel: 1 }, "z", 3); return r.sel === 1 && r.open == null && r.stop == null; })()); + // ---- viewRows (transcript overlay) ---- + const vr = A.viewRows(agents[0], 70, 24, 0, null, now); + ok("view shows the task", vr.some((r) => /add unit tests/.test(r))); + ok("view shows a done badge + elapsed", vr.some((r) => /done/.test(r)) && vr.some((r) => /1m03s/.test(r))); + ok("view shows the agent's result text", vr.some((r) => /Added 12 tests/.test(r))); + ok("view of a running agent with no output says running", A.viewRows(agents[1], 70, 24, 0, null, now).some((r) => /running/.test(r))); + ok("running view offers a stop key; finished view does not", A.viewRows(agents[1], 70, 24, 0, null, now).some((r) => /s stop/.test(r)) && !A.viewRows(agents[0], 70, 24, 0, null, now).some((r) => /s stop/.test(r))); + ok("view never crashes on a bare agent", Array.isArray(A.viewRows({ task: "x", status: "run", start: now }, 40, 12, 99, null, now))); + } + group("api-server input validation (shell-out routes reject injection)"); { const { isValidHostname, isSafeUrl } = require("../lib/nexus/url-guard"); From 337cc4b197d8cd361884d18e43484af820931dbf Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 18:21:42 -0700 Subject: [PATCH 13/16] nexus: distinct Nexus visuals for questions, agents and compaction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Give the three surfaces their own identity instead of mirroring other CLIs (the prompt bar is unchanged): - Question card: a tab-headed card on a magenta rail ("◆ nexus asks" / "pick any" / "your answer"), [n] keycaps, a ▸ pointer, ■/□ checkboxes, a "write my own answer" row and a real [ Submit ] button that counts picks. - Agents: a tree of lanes (├─ └─) under a "⟡ agents" header; running lanes animate a quarter-moon spinner and a bouncing ▰▱ activity meter, leader dots align a fixed status column (done / failed / stopped), the focused lane gets a ▶ cursor, and the hint shortens instead of being cut off on narrow terminals. The transcript overlay uses the same rail. - Compaction: a new pure "condenser" (lib/cli/compact-anim.js) — the conversation drawn as a bar squeezed from both ends into a ◆ core, looping, with elapsed / tokens / folded size; it finishes as the closed frame "▸◆◂ condensed N tokens of conversation" in the transcript. All pure and unit-tested (+20 tests). --- darknode.js | 12 +++--- lib/cli/agents.js | 81 +++++++++++++++++++++++++----------- lib/cli/ask.js | 91 ++++++++++++++++++++++------------------- lib/cli/compact-anim.js | 78 +++++++++++++++++++++++++++++++++++ test/run.js | 47 ++++++++++++++++----- 5 files changed, 225 insertions(+), 84 deletions(-) create mode 100644 lib/cli/compact-anim.js diff --git a/darknode.js b/darknode.js index 7050eb7..32f6010 100755 --- a/darknode.js +++ b/darknode.js @@ -53,6 +53,7 @@ const { CMD_MAP } = require("./lib/cli/registry"); // data-driven command regist const { toolResultView, bootHeader, welcomeCard, idleHome, footerLine, helpLines, padRight: padRightV, ansiWrap, modelLabel, effortLabel, explainEngineError } = require("./lib/cli/tui-format"); // pure TUI layout helpers (compact boot header + model/effort display names) const Composer = require("./lib/cli/composer"); // pure composer model + key dispatch + per-project history (lib/cli/composer.js) const Ask = require("./lib/cli/ask"); // pure renderer + key reducer for the model's ask_user multiple-choice prompt (lib/cli/ask.js) +const CompactAnim = require("./lib/cli/compact-anim"); // pure renderer for the live compaction "condenser" animation (lib/cli/compact-anim.js) const Agents = require("./lib/cli/agents"); // pure renderer + key reducer for the Agents panel (live sub-agent list under the prompt bar) (lib/cli/agents.js) const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js @@ -3051,8 +3052,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // short one-line notice stays an indented dim line. The rail is the same 2 columns the old // indent used, so wrap/clip widths are unchanged. if (m.role === "compacted") { - L.push(gray("✻ Conversation compacted" + (m.auto && m.before ? " (auto, at " + fmtK(m.before) + " tokens)" : "")) + (m.summary ? gray(" · ctrl+o " + (expanded ? "to hide summary" : "for summary")) : "")); - if (expanded && m.summary) for (const ln of wrap(m.summary)) L.push(" " + gray(ln)); + L.push(CompactAnim.doneRow({ before: m.before, auto: m.auto, hasSummary: !!m.summary, expanded, colors: { cyan, gray, bold, dim, mag } })); // the condenser's closed frame ▸◆◂ + if (expanded && m.summary) for (const ln of wrap(m.summary)) L.push(mag("┃ ") + gray(ln)); L.push(""); continue; } if (m.role === "recap") { recapLines(m.text).forEach((x) => L.push(x)); L.push(""); continue; } @@ -3204,11 +3205,10 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { }); if (busy) L.push(gray(" Ctrl+X / Ctrl+S runs " + (nextQueue.length > 1 ? "the next one" : "it") + " now")); } - // live compaction line, styled like the working line (Claude Code's "Compacting conversation…") + // live compaction: the Nexus "condenser" — a bar squeezed from both ends into a core (lib/cli/compact-anim.js) if (compact.on) { - const el = Math.round((Date.now() - compact.start) / 1000); L.push(""); - L.push(workGlyph() + " " + cyan("Compacting conversation…") + gray(" (" + fmtElapsed(el) + (compact.tok ? " · ↓ " + fmtK(compact.tok) + " tokens" : "") + " · esc to interrupt)")); + for (const r of CompactAnim.compactRows({ now: Date.now(), start: compact.start, tok: compact.tok, before: compact.cur && compact.cur.before, width: cols() - 2, colors: { cyan, gray, bold, dim, mag } })) L.push(r); } if (_sig !== null) { _blCache = L; _blSig = _sig; } return L; @@ -3512,7 +3512,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const menuStart = combined.length > menuRows ? Math.max(0, Math.min(menuSel - (menuRows >> 1), combined.length - menuRows)) : 0; const inRows = Math.max(1, Math.min(wrapped.length, 8, Math.max(1, avail - menuReserve - 1))); // When the model is asking a question, its card replaces the composer + menu. - const askRows = pendingAsk ? Ask.renderAsk(pendingAsk, C, { cyan, gray, bold, dim, green }) : null; + const askRows = pendingAsk ? Ask.renderAsk(pendingAsk, C, { cyan, gray, bold, dim, green, mag }) : null; const effortRows = (!askRows && pendingEffort) ? renderEffortPicker(C, pendingEffort.sel) : null; const btwRows = (!askRows && !effortRows && btw) ? renderBtw(C, R, btw) : null; const agentViewRows = (!askRows && !effortRows && !btwRows && agentView && agents[agentView.i]) ? Agents.viewRows(agents[agentView.i], C, R, agentView.scroll, { cyan, gray, bold, dim, green, red, yellow, mag }, Date.now()) : null; diff --git a/lib/cli/agents.js b/lib/cli/agents.js index fb59b99..5daa009 100644 --- a/lib/cli/agents.js +++ b/lib/cli/agents.js @@ -73,18 +73,33 @@ function windowStart(n, sel, max) { return Math.max(0, Math.min(sel - (max >> 1), n - max)); } -// panelRows(agents, opt) -> string[] (compact list under the prompt bar). +// Running agents animate: a quarter-moon spinner and a 5-cell activity meter +// whose lit pair bounces end to end. Both are pure functions of `now`. +const SPIN = ["◐", "◓", "◑", "◒"]; +function spinGlyph(now) { return SPIN[Math.floor((now | 0) / 120) % SPIN.length]; } +function meter(now, w) { + w = w || 5; + const last = w - 2, span = last * 2, k = Math.floor((now | 0) / 140) % span, pos = k <= last ? k : span - k; // pair start bounces 0..w-2 + let s = ""; for (let i = 0; i < w; i++) s += (i === pos || i === pos + 1) ? "▰" : "▱"; + return s; +} + +// panelRows(agents, opt) -> string[] (the lanes under the prompt bar). // opt: { now, sel, width, colors, max } // sel = focused row index when the panel has keyboard focus, else -1 (idle). -// Returns [] when there are no agents (the panel takes no space). Rows are not -// padded — the host's frame diff clears to end-of-line, same as the slash menu. +// Layout — a tree of lanes with leader dots aligning a right-hand status column: +// ⟡ agents ── 1 running · 2 done ↓ to select +// ├─ ◐ write the docs ·························· ▰▰▱▱▱ 12s +// ▶├─ ● add unit tests ·························· done 1m03s +// └─ ✗ fix the lint errors ····················· failed 50s +// Returns [] when there are no agents (the panel takes no space). function panelRows(agents, opt) { agents = Array.isArray(agents) ? agents : []; if (!agents.length) return []; opt = opt || {}; const t = theme(opt.colors); const now = opt.now || Date.now(); - const C = Math.max(20, (opt.width | 0) || 80); + const C = Math.max(30, (opt.width | 0) || 80); const rawSel = opt.sel == null ? -1 : (opt.sel | 0); const focus = rawSel >= 0; // sel < 0 is the idle (unfocused) sentinel const sel = focus ? clampSel(rawSel, agents.length) : -1; @@ -92,26 +107,40 @@ function panelRows(agents, opt) { const running = agents.filter((a) => a && a.status === "run").length; const done = agents.length - running; const out = []; - // header: "agents 2 running · 1 done" + a right-side nav hint. const sum = []; if (running) sum.push(running + " running"); if (done) sum.push(done + " done"); - const hint = focus ? "↑↓ move · enter open · s stop · x clear · esc back" : "↓ to select"; - out.push(" " + t.dim("agents") + t.gray(" " + sum.join(" · ")) + t.gray(" " + hint)); + const headPlain = "⟡ agents ── " + sum.join(" · "); + // the longest hint that fits beside the header (never cut mid-word) + const hints = focus ? ["enter open · s stop · x clear · esc back", "enter open · s stop · esc back", "↵ open · s stop · esc", "esc back"] : ["↓ to select"]; + const hint = hints.find((h) => headPlain.length + 3 + h.length <= C - 1) || ""; + const gap = Math.max(2, C - 1 - headPlain.length - hint.length); + out.push(" " + t.mag("⟡") + " " + t.bold("agents") + t.gray(" ── ") + (running ? t.yellow(sum[0]) + (sum[1] ? t.gray(" · " + sum[1]) : "") : t.gray(sum.join(" · "))) + " ".repeat(gap) + t.gray(hint)); const start = windowStart(agents.length, sel, max); const shown = agents.slice(start, start + max); + const more = agents.length - shown.length; shown.forEach((a, j) => { const gi = start + j; const on = focus && gi === sel; + const last = j === shown.length - 1 && !more; const st = statusOf(a, t); const el = fmtDur(elapsed(a, now)); - const cur = on ? t.cyan("❯ ") : " "; - const taskW = Math.max(6, C - 2 - 2 - 2 - 2 - el.length - 1); // indent + cursor + glyph+sp + gap + elapsed - const task = fit(a.task, taskW); - const label = on ? t.bold(task) : (a.status === "run" ? task : t.gray(task)); - out.push(" " + cur + st.glyph + " " + label + " " + t.gray(el)); + const isRun = a.status === "run"; + const glyph = isRun ? t.yellow(spinGlyph(now)) : st.glyph; + const midPlain = isRun ? meter(now) : st.badge; + const midPad = " ".repeat(Math.max(0, 7 - midPlain.length)); // fixed 7-col status column ("stopped") + const right = " " + midPad + midPlain + " " + el.padStart(6); + const lead = (on ? "▶" : " ") + (last ? "└─ " : "├─ ") + "x "; // cursor + branch + glyph + space + const room = C - 1 - lead.length - right.length - 1; // keep 1 col slack + const task = fit(a.task, Math.max(4, room - 3)); + const dots = Math.max(1, room - task.length - 1); + const cur = on ? t.cyan("▶") : " "; + const branch = t.gray(last ? "└─ " : "├─ "); + const label = on ? t.bold(t.cyan(task)) : (isRun ? task : t.gray(task)); + const midC = isRun ? t.cyan(midPlain) : st.paint(midPlain); + out.push(" " + cur + branch + glyph + " " + label + " " + t.dim("·".repeat(dots)) + " " + midPad + midC + " " + t.gray(el.padStart(6))); }); - if (agents.length > shown.length) out.push(" " + t.dim(" +" + (agents.length - shown.length) + " more")); + if (more) out.push(" " + t.gray("└─ ") + t.dim("+" + more + " more")); return out; } @@ -121,27 +150,29 @@ function panelRows(agents, opt) { // partial output (or a "running…" note) and a live elapsed clock. function viewRows(agent, C, R, scroll, colors, now) { const t = theme(colors); - const w = Math.max(12, (C | 0) - 4); + const w = Math.max(12, (C | 0) - 6); const avail = Math.max(8, (R | 0) - 4); const a = agent || { task: "", status: "run", start: 0 }; const st = statusOf(a, t); + const isRun = a.status === "run"; + const clock = now || Date.now(); + const rail = t.mag("┃"); const head = []; - head.push(" " + t.bold("Agent") + t.gray(" — sub-agent output") + (a.native === false ? t.gray(" · " + (a.engine || "engine")) : "")); - for (const ql of wrapPlain("❯ " + String(a.task || ""), w)) head.push(" " + t.cyan(ql)); - head.push(" " + st.paint(st.badge) + t.gray(" · " + fmtDur(elapsed(a, now || Date.now())))); - head.push(""); - const bodyMax = Math.max(2, avail - head.length - 3); + const glyph = isRun ? t.yellow(spinGlyph(clock)) : st.glyph; + head.push(" " + t.mag("⟡") + " " + t.bold("agent") + t.gray(" ── ") + glyph + " " + st.paint(st.badge) + t.gray(" · " + fmtDur(elapsed(a, clock)) + (a.native === false ? " · " + (a.engine || "engine") : "")) + (isRun ? " " + t.cyan(meter(clock)) : "")); + for (const ql of wrapPlain(String(a.task || ""), w)) head.push(" " + rail + " " + t.bold(t.cyan(ql))); + head.push(" " + rail); + const bodyMax = Math.max(2, avail - head.length - 2); const resultText = String(a.result == null ? "" : a.result); - const body = resultText ? wrapPlain(resultText, w) : [t.gray(a.status === "run" ? "running…" : "(no output)")]; + const body = resultText ? wrapPlain(resultText, w) : [t.gray(isRun ? "running…" : "(no output)")]; let sc = scroll | 0; const maxSc = Math.max(0, body.length - bodyMax); if (sc > maxSc) sc = maxSc; if (sc < 0) sc = 0; const vis = body.slice(sc, sc + bodyMax); - const rows = head.concat(vis.map((l) => " " + l)); - if (body.length > bodyMax) rows.push(" " + t.gray(" … " + Math.min(body.length, sc + bodyMax) + "/" + body.length + " lines")); - rows.push(""); - rows.push(" " + t.gray("esc close · ↑↓ scroll · " + (a.status === "run" ? "s stop · " : "") + "c copy")); + const rows = head.concat(vis.map((l) => " " + rail + " " + l)); + const pos = body.length > bodyMax ? " " + Math.min(body.length, sc + bodyMax) + "/" + body.length + " lines ·" : ""; + rows.push(" " + t.mag("┗━") + t.gray(pos + " esc close · ↑↓ scroll · [ ] prev/next · " + (isRun ? "s stop · " : "") + "c copy")); return rows; } @@ -172,4 +203,4 @@ function panelKey(state, key, n) { return { sel }; // unrelated key: keep focus } -module.exports = { panelRows, viewRows, panelKey, fmtDur, elapsed, statusOf, wrapPlain, fit, windowStart }; +module.exports = { spinGlyph, meter, panelRows, viewRows, panelKey, fmtDur, elapsed, statusOf, wrapPlain, fit, windowStart }; diff --git a/lib/cli/ask.js b/lib/cli/ask.js index 647a91c..9b3f672 100644 --- a/lib/cli/ask.js +++ b/lib/cli/ask.js @@ -71,74 +71,79 @@ function wrapPlain(s, w) { // Truncate a plain string to w columns with a trailing ellipsis. function fit(s, w) { s = String(s == null ? "" : s); if (w < 0) w = 0; if (s.length <= w) return s; if (w <= 1) return s.slice(0, w); return s.slice(0, w - 1) + "…"; } -// renderAsk(ask, width, colors) -> string[] (each row ready to paint). The box -// is drawn full width with rounded corners and side walls; the key legend sits -// dimmed beneath it. Rows are padded to `width` visible columns using PLAIN -// text length (injected colors add no columns), so right walls stay aligned. +// renderAsk(ask, width, colors) -> string[] (each row ready to paint). +// The Nexus question card — a tab-headed card on a left rail, not a box: +// +// ┏━ ◆ nexus asks ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +// ┃ Which database should the API use? +// ┃ +// ┃ ▸ [1] PostgreSQL +// ┃ [2] SQLite zero-config +// ┃ [3] MySQL +// ┃ [✎] write my own answer +// ┃ +// ┃ [ Submit ] +// ┗━ ↑↓ move · 1-3 pick · enter select · esc skip +// +// The focused row gets a ▸ pointer and an accent; multi-select shows ■/□ +// checkboxes and the Submit button counts the picks. Rows are measured with +// their PLAIN text (injected colors add no columns) and never exceed `width`. function renderAsk(ask, width, colors) { const C = Math.max(28, (width | 0) || 80); const t = theme(colors); - const innerW = C - 4; // content width inside "│ " … " │" + const mag = (colors && colors.mag) || t.cyan; + const innerW = C - 4; // " ┃ " + content const out = []; - const top = t.gray("╭" + "─".repeat(C - 2) + "╮"); - const bot = t.gray("╰" + "─".repeat(C - 2) + "╯"); - // A content row: measure with the PLAIN string, paint with the colored one. - const line = (plain, colored) => { const pad = Math.max(0, innerW - plain.length); out.push(t.gray("│ ") + (colored == null ? plain : colored) + " ".repeat(pad) + t.gray(" │")); }; - const blank = () => line("", ""); - out.push(top); - // Question — accent dot on the first wrapped line, bold throughout. - const q = wrapPlain(ask && ask.question, Math.max(1, innerW - 2)); - q.forEach((ln, i) => line((i === 0 ? "● " : " ") + ln, (i === 0 ? t.cyan("● ") : " ") + t.bold(ln))); + const rail = mag("┃"); + const line = (colored) => out.push(" " + rail + " " + colored); + const blank = () => out.push(" " + rail); + const multi = !!(ask && ask.multi); + const label = ask && ask.input && !ask.typed ? "your answer" : multi ? "pick any" : "nexus asks"; + const tab = " ◆ " + label + " "; + out.push(" " + mag("┏━") + t.bold(mag(tab)) + mag("━".repeat(Math.max(2, C - 3 - tab.length)))); + for (const ln of wrapPlain(ask && ask.question, Math.max(1, innerW))) line(t.bold(ln)); blank(); if (ask && ask.input) { - // ---- free-text field (either a pure input prompt, or the "type a different - // answer" row expanded into an editable line). A block caret marks the end. ---- + // ---- free-text field (a pure input prompt, or "write my own answer" expanded) ---- const text = String(ask.text || ""); const avail = Math.max(1, innerW - 3); const shown = text.length > avail ? "…" + text.slice(-(avail - 1)) : text; const ph = ask.placeholder ? String(ask.placeholder) : "type your answer"; - if (shown) line("› " + shown, t.cyan("› ") + shown + t.cyan("█")); - else line("› " + ph, t.cyan("› ") + t.dim(ph) + t.cyan("█")); - out.push(bot); - out.push(" " + t.gray(fit("enter submit · esc " + (ask.typed ? "cancel" : "skip"), C - 2))); + if (shown) line(t.cyan("› ") + shown + t.cyan("█")); + else line(t.cyan("› ") + t.dim(fit(ph, avail)) + t.cyan("█")); + out.push(" " + mag("┗━") + " " + t.gray(fit("enter submit · esc " + (ask.typed ? "back" : "skip"), C - 4))); return out; } const { opts, rows } = rowModel(ask); const sel = clampSel(ask && ask.sel, rows.length); - const multi = !!(ask && ask.multi); const picked = multi ? normPicked(ask && ask.picked, opts.length) : []; rows.forEach((row, r) => { const on = r === sel; - const cur = on ? "❯ " : " "; - const curC = on ? t.cyan("❯ ") : " "; + const cur = on ? t.cyan("▸ ") : " "; if (row.kind === "opt") { const o = opts[row.i]; - const num = (row.i + 1) + "."; - const box = multi ? (picked.indexOf(row.i) >= 0 ? "◉ " : "○ ") : ""; - const boxC = multi ? (picked.indexOf(row.i) >= 0 ? t.green("◉ ") : t.gray("○ ")) : ""; - const label = fit(o.label, Math.max(4, innerW - 2 - box.length - num.length - 1 - (o.hint ? o.hint.length + 2 : 0))); - const hintP = o.hint ? " " + o.hint : ""; - const plain = cur + box + num + " " + label + hintP; - const colored = curC + boxC + (on ? t.bold(t.cyan(num + " " + label)) : t.gray(num + " ") + label) + (o.hint ? " " + t.dim(o.hint) : ""); - line(plain, colored); + const key = "[" + (row.i + 1) + "] "; + const isP = picked.indexOf(row.i) >= 0; + const box = multi ? (isP ? "■ " : "□ ") : ""; + const boxC = multi ? (isP ? t.green("■ ") : t.gray("□ ")) : ""; + const hintRoom = o.hint ? o.hint.length + 2 : 0; + const lab = fit(o.label, Math.max(4, innerW - 2 - key.length - box.length - hintRoom)); + const hint = o.hint ? " " + t.dim(fit(o.hint, Math.max(0, innerW - 2 - key.length - box.length - lab.length - 2))) : ""; + line(cur + (on ? t.cyan(key) : t.gray(key)) + boxC + (on ? t.bold(t.cyan(lab)) : lab) + hint); } else if (row.kind === "type") { - const plain = cur + "✎ Type a different answer"; - const colored = curC + (on ? t.bold(t.cyan("✎ Type a different answer")) : t.gray("✎ Type a different answer")); - line(plain, colored); - } else { // submit - const tag = multi ? "Submit" + (picked.length ? " (" + picked.length + " selected)" : "") : "Submit"; - const plain = cur + tag; - const colored = curC + (on ? t.bold(t.cyan(tag)) : t.gray(tag)); - line(plain, colored); + line(cur + (on ? t.cyan("[✎] ") + t.bold(t.cyan("write my own answer")) : t.gray("[✎] write my own answer"))); + } else { // submit — a button, separated from the choices + blank(); + const tag = "[ Submit" + (multi && picked.length ? " · " + picked.length + " selected" : "") + " ]"; + line(cur + (on ? t.bold(t.green(tag)) : t.gray(tag))); } }); - out.push(bot); const legend = multi - ? "↑↓ move · space toggle · 1-" + Math.max(1, opts.length) + " toggle · enter select · esc skip" - : "↑↓ move · 1-" + Math.max(1, opts.length) + " pick · enter select · esc skip"; - out.push(" " + t.gray(fit(legend, C - 2))); + ? "↑↓ move · space/1-" + Math.max(1, opts.length) + " toggle · enter select · esc skip" + : "↑↓ move · 1-" + Math.max(1, opts.length) + " pick · enter select · esc skip"; + out.push(" " + mag("┗━") + " " + t.gray(fit(legend, C - 4))); return out; } diff --git a/lib/cli/compact-anim.js b/lib/cli/compact-anim.js new file mode 100644 index 0000000..4ea89e7 --- /dev/null +++ b/lib/cli/compact-anim.js @@ -0,0 +1,78 @@ +"use strict"; +// ============================================================================ +// compact-anim — the Nexus "condenser": a PURE renderer for the live +// compaction status. Instead of a single spinner line, the conversation is +// drawn as a bar that is squeezed inward from both ends toward a bright core, +// over and over, while a counter shows the context being folded down. +// +// ⧉ Condensing conversation 12s · ↓ 1.2k tokens · esc to interrupt +// ·······▸━━━━━◆━━━━━◂······· 48.2k tokens → folding +// +// Pure + deterministic: the frame is a function of (now - start), colors are +// injected, so tests can assert exact frames. +// ============================================================================ + +const IDENT = (s) => s; +function theme(c) { + c = c || {}; + return { cyan: c.cyan || IDENT, gray: c.gray || IDENT, bold: c.bold || IDENT, dim: c.dim || IDENT, mag: c.mag || IDENT }; +} + +const CYCLE_MS = 1600; // one full squeeze, ends → core + +function fmtK(n) { n = Math.max(0, n | 0); return n >= 1000 ? (n / 1000).toFixed(n >= 100000 ? 0 : 1) + "k" : String(n); } +function fmtSec(s) { s = Math.max(0, s | 0); return s < 60 ? s + "s" : Math.floor(s / 60) + "m" + String(s % 60).padStart(2, "0") + "s"; } + +// The squeeze bar for a given elapsed time: `w` cells (odd widths center +// cleanly). The two jaws close from the edges toward the middle over CYCLE_MS; +// cells outside the jaws are dim dots, the jaws are ▸/◂, the squeezed span is a +// heavy rule, and the center is a ◆ core. Returns { plain, colored }. +function squeezeBar(elapsedMs, w, t) { + t = t || theme(); + w = Math.max(7, w | 0); + const mid = (w - 1) / 2; + const phase = ((Math.max(0, elapsedMs) % CYCLE_MS) / CYCLE_MS); // 0 → 1 + const reach = Math.floor(phase * Math.floor(mid)); // how far the jaws have closed + let plain = "", colored = ""; + for (let i = 0; i < w; i++) { + const d = Math.abs(i - mid); + const left = i < mid; + let ch, paint; + if (d < 0.6) { ch = "◆"; paint = (s) => t.bold(t.mag(s)); } // the core + else if (i === reach && left) { ch = "▸"; paint = t.cyan; } // left jaw + else if (i === w - 1 - reach && !left) { ch = "◂"; paint = t.cyan; } // right jaw + else if ((left && i > reach) || (!left && i < w - 1 - reach)) { ch = "━"; paint = (s) => t.cyan(s); } // squeezed span + else { ch = "·"; paint = t.dim; } // already folded away + plain += ch; colored += paint(ch); + } + return { plain, colored }; +} + +// compactRows(o) -> string[] (two rows: title + squeeze bar). +// o: { now, start, tok, before, width, colors } +function compactRows(o) { + o = o || {}; + const t = theme(o.colors); + const now = o.now || Date.now(); + const el = Math.max(0, now - (o.start || now)); + const C = Math.max(24, (o.width | 0) || 80); + const glyph = ["⧉", "⧈", "⧉", "▣"][Math.floor(el / 200) % 4]; + const meta = fmtSec(Math.round(el / 1000)) + (o.tok ? " · ↓ " + fmtK(o.tok) + " tokens" : "") + " · esc to interrupt"; + const title = t.mag(glyph) + " " + t.bold(t.cyan("Condensing conversation")) + t.gray(" " + meta); + const tail = o.before ? " " + fmtK(o.before) + " tokens → folding" : " folding"; + const barW = Math.max(7, Math.min(31, C - 4 - tail.length) | 1); // keep it odd so the core centers + const bar = squeezeBar(el, barW, t); + return [title, " " + bar.colored + t.gray(tail)]; +} + +// doneRow(o) -> string (the marker left in the transcript once compaction is +// done: the squeeze's final, fully-closed frame "▸◆◂" + what was folded). +// o: { before, auto, hasSummary, expanded, colors } +function doneRow(o) { + o = o || {}; + const t = theme(o.colors); + const what = o.before ? (o.auto ? "auto-condensed " : "condensed ") + fmtK(o.before) + " tokens of conversation" : (o.auto ? "auto-condensed the conversation" : "conversation condensed"); + return t.cyan("▸") + t.bold(t.mag("◆")) + t.cyan("◂") + " " + t.gray(what) + (o.hasSummary ? t.gray(" · ctrl+o " + (o.expanded ? "hides" : "shows") + " the summary") : ""); +} + +module.exports = { compactRows, squeezeBar, doneRow, CYCLE_MS }; diff --git a/test/run.js b/test/run.js index dc46a44..da03128 100644 --- a/test/run.js +++ b/test/run.js @@ -2601,17 +2601,17 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("an unrelated key is a no-op that keeps focus", (() => { const r = askKey({ ...ask, sel: 1 }, "x"); return !r.done && !r.cancelled && r.sel === 1; })()); // ---- renderAsk: layout + content (plain, colors identity) ---- const rows = renderAsk({ ...ask, sel: 1 }, 60); - ok("draws a rounded box (corners + walls)", rows[0].includes("╭") && rows[0].includes("╮") && rows.some((r) => r.includes("╰") && r.includes("╯")) && rows.some((r) => r.includes("│"))); + ok("draws the Nexus card (tab header, rail, foot)", rows[0].includes("┏━") && rows[0].includes("◆ nexus asks") && rows.some((r) => r.includes("┃")) && rows[rows.length - 1].includes("┗━")); ok("shows the question text", rows.some((r) => r.includes("Which database"))); - ok("numbers every option", rows.some((r) => /1\. PostgreSQL/.test(r)) && rows.some((r) => /2\. SQLite/.test(r)) && rows.some((r) => /3\. MySQL/.test(r))); - ok("marks the focused option with ❯", rows.some((r) => r.includes("❯") && r.includes("SQLite"))); + ok("keycaps every option", rows.some((r) => /\[1\] PostgreSQL/.test(r)) && rows.some((r) => /\[2\] SQLite/.test(r)) && rows.some((r) => /\[3\] MySQL/.test(r))); + ok("marks the focused option with ▸", rows.some((r) => r.includes("▸") && r.includes("SQLite")) && !rows.some((r) => r.includes("▸") && r.includes("MySQL"))); ok("renders a hint when provided", rows.some((r) => r.includes("zero-config"))); - ok("offers a Type-a-different-answer row", rows.some((r) => /Type a different answer/.test(r))); + ok("offers a write-my-own-answer row", rows.some((r) => /write my own answer/.test(r))); ok("offers a Submit row", rows.some((r) => /Submit/.test(r))); ok("has a key-legend footer", rows.some((r) => /enter select/.test(r) && /esc skip/.test(r))); - ok("every box row is exactly the requested width (plain)", rows.filter((r) => r.includes("│")).every((r) => r.length === 60)); + ok("the tab header spans exactly the requested width (plain)", rows[0].length === 60); ok("no row exceeds the requested width (plain)", rows.every((r) => r.length <= 60)); - ok("allowType:false drops the Type row", !renderAsk({ ...ask, allowType: false }, 60).some((r) => /Type a different answer/.test(r))); + ok("allowType:false drops the Type row", !renderAsk({ ...ask, allowType: false }, 60).some((r) => /write my own answer/.test(r))); ok("empty options + esc still cancels (no crash)", askKey({ question: "q", options: [], sel: 0 }, "\x1b").cancelled === true); ok("renderAsk tolerates no options", Array.isArray(renderAsk({ question: "q", options: [] }, 40))); } @@ -2629,8 +2629,9 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("enter on Submit with nothing picked confirms an empty set", (() => { const r = askKey({ ...base, sel: 5, picked: [] }, "\r"); return r.done && JSON.stringify(r.indices) === JSON.stringify([]); })()); ok("esc still cancels in multi mode", askKey(base, "\x1b").cancelled === true); const rows = renderAsk({ ...base, picked: [1] }, 60); - ok("renders ◉/○ checkboxes", rows.some((r) => r.includes("◉")) && rows.some((r) => r.includes("○"))); - ok("Submit row shows the selected count", rows.some((r) => /Submit \(1 selected\)/.test(r))); + ok("renders ■/□ checkboxes", rows.some((r) => r.includes("■")) && rows.some((r) => r.includes("□"))); + ok("multi card is tabbed \"pick any\"", rows[0].includes("pick any")); + ok("Submit button shows the selected count", rows.some((r) => /\[ Submit · 1 selected \]/.test(r))); ok("multi footer mentions space-toggle", rows.some((r) => /space/.test(r) && /toggle/.test(r))); ok("no multi box row exceeds width", rows.every((r) => r.length <= 60)); } @@ -2680,10 +2681,17 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("idle header hints how to select", /to select/.test(idle[0])); ok("lists each agent's task", idle.some((r) => /add unit tests/.test(r)) && idle.some((r) => /write the API docs/.test(r)) && idle.some((r) => /fix the lint errors/.test(r))); ok("shows elapsed per agent", idle.some((r) => /1m03s/.test(r)) && idle.some((r) => /5s/.test(r))); - ok("idle panel shows no ❯ cursor", !idle.slice(1).some((r) => r.includes("❯"))); + ok("idle panel shows no ▶ cursor", !idle.slice(1).some((r) => r.includes("▶"))); const foc = A.panelRows(agents, { now, sel: 1, width: 70 }); ok("focused header hints open/stop/back", /enter open/.test(foc[0]) && /stop/.test(foc[0]) && /esc back/.test(foc[0])); - ok("focused row carries the ❯ cursor on the selected task", foc.some((r) => r.includes("❯") && /write the API docs/.test(r))); + ok("lanes are drawn as a tree (├─ … └─)", idle.some((r) => r.includes("├─")) && idle[idle.length - 1].includes("└─")); + ok("finished lanes show a status badge", idle.some((r) => /done/.test(r) && /add unit tests/.test(r)) && idle.some((r) => /failed/.test(r))); + ok("status column is aligned across lanes", (() => { const ends = idle.slice(1).map((r) => r.length); return ends.every((n) => n === ends[0]); })()); + ok("no lane exceeds the width", foc.every((r) => r.length <= 70)); + ok("a running lane animates (spinner + meter change over time)", A.panelRows(agents, { now, width: 70 })[2] !== A.panelRows(agents, { now: now + 300, width: 70 })[2]); + eq("meter lights two adjacent cells", (A.meter(0).match(/▰/g) || []).length, 2); + ok("meter bounces back (never runs off the end)", Array.from({ length: 40 }, (_, k) => A.meter(k * 140)).every((m) => m.length === 5 && /▰▰/.test(m))); + ok("focused lane carries the ▶ cursor on the selected task", foc.some((r) => r.includes("▶") && /write the API docs/.test(r))); ok("long task is truncated with an ellipsis at a narrow width", A.panelRows([{ task: "x".repeat(200), status: "run", start: now }], { now, width: 40 }).some((r) => r.includes("…"))); const many = Array.from({ length: 9 }, (_, i) => ({ id: "a" + i, task: "task " + i, status: "run", start: now })); const win = A.panelRows(many, { now, sel: -1, width: 70, max: 4 }); @@ -2716,6 +2724,25 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("view never crashes on a bare agent", Array.isArray(A.viewRows({ task: "x", status: "run", start: now }, 40, 12, 99, null, now))); } + group("compaction condenser animation"); + { + const CA = require("../lib/cli/compact-anim"); + const f0 = CA.squeezeBar(0, 21).plain, fEnd = CA.squeezeBar(CA.CYCLE_MS - 10, 21).plain; + ok("the core ◆ sits dead center", f0[10] === "◆" && fEnd[10] === "◆"); + ok("jaws start at the edges", f0[0] === "▸" && f0[20] === "◂"); + ok("jaws close in on the core over the cycle", fEnd.indexOf("▸") > f0.indexOf("▸") && fEnd.indexOf("◂") < f0.indexOf("◂")); + ok("folded-away cells become dots", /^·+▸/.test(fEnd)); + ok("the bar loops (frame at one full cycle == frame 0)", CA.squeezeBar(CA.CYCLE_MS, 21).plain === f0); + ok("bar width is honored", CA.squeezeBar(700, 15).plain.length === 15); + const rows = CA.compactRows({ now: 13000, start: 1000, tok: 1234, before: 48200, width: 80 }); + ok("title says Condensing conversation with elapsed + tokens + esc", /Condensing conversation/.test(rows[0]) && /12s/.test(rows[0]) && /1\.2k tokens/.test(rows[0]) && /esc to interrupt/.test(rows[0])); + ok("bar row shows the context being folded", /48\.2k tokens → folding/.test(rows[1])); + ok("rows stay within the width", rows.every((r) => r.length <= 80)); + ok("a narrow terminal still renders", CA.compactRows({ now: 5, start: 0, width: 24 }).every((r) => typeof r === "string")); + ok("done marker is the closed frame + folded size", /^▸◆◂ condensed 48\.2k tokens/.test(CA.doneRow({ before: 48200 }))); + ok("done marker notes auto + the summary toggle", /auto-condensed/.test(CA.doneRow({ before: 1, auto: true })) && /ctrl\+o shows the summary/.test(CA.doneRow({ hasSummary: true })) && /hides/.test(CA.doneRow({ hasSummary: true, expanded: true }))); + } + group("api-server input validation (shell-out routes reject injection)"); { const { isValidHostname, isSafeUrl } = require("../lib/nexus/url-guard"); From bfc20f4b7cd8c770d0179e446c1b10c60d1679fc Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 19:02:29 -0700 Subject: [PATCH 14/16] nexus: /turns cost ledger + /cheaper lossless cost advisor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two new commands, both over real per-turn data captured at turn end (no prompt text kept beyond a short label; never persisted): - /turns (alias /ledger): a per-session cost ledger — one row per turn with tokens, cost and duration, the priciest turn flagged, session totals in the header. /turns lists the last n. - /cheaper: a cost advisor that only ever suggests LOSSLESS savings (turn the exact-repeat cache on, note verbatim repeats, explain claude prompt-caching, /compact a full context). The one quality tradeoff — effort — is flagged as such and never auto-applied; /cheap is untouched and stays lossless-only. Pure, unit-tested module lib/cli/ledger.js (+23 tests). Per-turn capture reuses the deltas the turn summary already computes; adds a cache-read baseline to the turn stat so the cache-read delta is per-turn. --- darknode.js | 16 +++++-- lib/cli/ledger.js | 104 ++++++++++++++++++++++++++++++++++++++++++++++ test/run.js | 40 ++++++++++++++++++ 3 files changed, 157 insertions(+), 3 deletions(-) create mode 100644 lib/cli/ledger.js diff --git a/darknode.js b/darknode.js index 32f6010..0e8f435 100755 --- a/darknode.js +++ b/darknode.js @@ -53,7 +53,8 @@ const { CMD_MAP } = require("./lib/cli/registry"); // data-driven command regist const { toolResultView, bootHeader, welcomeCard, idleHome, footerLine, helpLines, padRight: padRightV, ansiWrap, modelLabel, effortLabel, explainEngineError } = require("./lib/cli/tui-format"); // pure TUI layout helpers (compact boot header + model/effort display names) const Composer = require("./lib/cli/composer"); // pure composer model + key dispatch + per-project history (lib/cli/composer.js) const Ask = require("./lib/cli/ask"); // pure renderer + key reducer for the model's ask_user multiple-choice prompt (lib/cli/ask.js) -const CompactAnim = require("./lib/cli/compact-anim"); // pure renderer for the live compaction "condenser" animation (lib/cli/compact-anim.js) +const CompactAnim = require("./lib/cli/compact-anim"); +const Ledger = require("./lib/cli/ledger"); // pure per-session cost ledger (/turns) + lossless cost advisor (/cheaper) (lib/cli/ledger.js) // pure renderer for the live compaction "condenser" animation (lib/cli/compact-anim.js) const Agents = require("./lib/cli/agents"); // pure renderer + key reducer for the Agents panel (live sub-agent list under the prompt bar) (lib/cli/agents.js) const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js @@ -2610,6 +2611,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // keyboard (-1 = composer has focus); `agentView` is the open transcript // overlay { i, scroll } or null. addAgent/finishAgent feed the registry. let agents = [], agentSel = -1, agentView = null; + let turnLog = []; // one entry per finished paid/local turn this session — feeds /turns + /cheaper (never persisted, no prompt text beyond a short label) const AGENTS_MAX = 24; // cap the registry; drop the oldest FINISHED agents past this const addAgent = (task, opts) => { const a = Object.assign({ id: "ag_" + Date.now().toString(36) + "_" + agents.length, task: String(task || "").slice(0, 300), status: "run", start: Date.now(), result: "", native: true }, opts || {}); agents.push(a); if (agents.length > AGENTS_MAX) { const keep = agents.filter((x) => x.status === "run"); const fin = agents.filter((x) => x.status !== "run"); agents = fin.slice(Math.max(0, fin.length - (AGENTS_MAX - keep.length))).concat(keep).sort((x, y) => x.start - y.start); } return a; }; const finishAgent = (a, status, result) => { if (!a || a.status !== "run") return; a.status = status || "ok"; a.end = Date.now(); if (result != null) a.result = String(result); }; @@ -2762,7 +2764,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { ["/help", "commands, input prefixes & keys"], ["/clear", "start a fresh chat"], ["/chat-clear", "clear the screen, keep the conversation memory"], ["/compact", "summarize & shrink the context"], ["/trust", "trust this workspace's .nexus MCP servers + hooks"], ["/connect", "connect an AI: local model · Claude (API) · any provider"], - ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], + ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "lossless ways to spend fewer tokens"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], ["/report", "cost & usage report for chargeback (/report json|save|since )"], ["/compliance", "write a signed audit+usage compliance bundle (SOC2/review)"], ["/undo", "revert the last turn's file changes"], ["/rewind", "restore a specific checkpoint (/rewind N)"], ["/checkpoints", "list undo checkpoints"], @@ -3929,7 +3931,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // result (/scan, /verify…) can push a system message mid-turn and move the tail, // which would otherwise attach the model's reply to that unrelated block. const textItem = () => { let last = block.items[block.items.length - 1]; if (!last || last.type !== "text") { last = { type: "text", full: "", shown: 0 }; block.items.push(last); } return last; }; - const stat = { files: new Set(), paths: new Set(), cmds: 0, inTok0: sess.inTok, outTok0: sess.outTok, cost0: sess.cost, t0: Date.now() }; + const stat = { files: new Set(), paths: new Set(), cmds: 0, inTok0: sess.inTok, outTok0: sess.outTok, cost0: sess.cost, cacheRead0: (sess.byModel && Object.values(sess.byModel).reduce((a, m) => a + (m.cacheRead || 0), 0)) || 0, t0: Date.now() }; const relOf = (p) => { try { return path.relative(cwd, path.resolve(cwd, p)); } catch (_) { return null; } }; const ckTree = nexusCheckpoint(cwd); // every engine can now modify files, so always checkpoint (null if not a git repo) let ckObj = null; if (ckTree) { ckObj = { tree: ckTree, label: oneline(text, 40), ts: Date.now() }; checkpoints.push(ckObj); } @@ -3943,6 +3945,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (!block.items.length || !block.items.some((i) => i.type === "text" && i.full.trim())) { const t = textItem(); if (!t.full.trim()) t.full = res && res.interrupted ? "(interrupted)" : (res && res.output) || "(no output)"; } const dt = ((Date.now() - stat.t0) / 1000).toFixed(1); const din = sess.inTok - stat.inTok0, dout = sess.outTok - stat.outTok0, dcost = sess.cost - stat.cost0; + try { const _cr = (sess.byModel && Object.values(sess.byModel).reduce((a, m) => a + (m.cacheRead || 0), 0)) || 0; turnLog.push({ t: Date.now(), inTok: Math.max(0, din), outTok: Math.max(0, dout), cost: Math.max(0, dcost), dt: +dt || 0, model: sess.model || engine, engine, label: oneline(text || "", 64), paid: !!PAID[engine], cacheRead: Math.max(0, _cr - (stat.cacheRead0 || 0)) }); if (turnLog.length > 300) turnLog.shift(); } catch (_) {} if (PAID[engine]) { impact.cloudTurns++; impact.cloudInTok += Math.max(0, din); impact.cloudOutTok += Math.max(0, dout); impact.cloudCost += Math.max(0, dcost); } else { impact.localTurns++; impact.localTok += Math.max(0, din + dout); } // Chargeback ledger: one non-sensitive metrics line per turn (no prompt text, no paths). try { appendUsage(cwd, { ts: new Date().toISOString(), operator: ident.operator, team: ident.team, engine, model: sess.model || engine, mode: ["normal", "auto", "plan"][mode] || "normal", inTok: Math.max(0, din), outTok: Math.max(0, dout), cost: Math.max(0, dcost), seconds: +dt, files: stat.files.size, commands: stat.cmds, interrupted: !!(res && res.interrupted) }); } catch (_) {} @@ -4788,6 +4791,13 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { transcript.push({ role: "system", text: "screen cleared — the conversation is still in memory" + gray(" · next message continues it · /clear to wipe memory too") }); scroll = 0; } + else if (cmd === "/turns" || cmd === "/ledger") { + const n = parseInt(argstr, 10); + transcript.push({ role: "system", lines: Ledger.renderTurns(turnLog, { colors: { cyan, gray, bold, dim, green, yellow, mag }, width: cols() - 4, max: n > 0 ? n : 12 }) }); + } + else if (cmd === "/cheaper") { + transcript.push({ role: "system", lines: Ledger.renderAdvice(turnLog, { paid: !!PAID[engine], cacheOn, effort, engine, autoCompact, ctxPct: (sess.ctxUsed / (sess.ctxWindow || 200000)) * 100 }, { cyan, gray, bold, dim, green, yellow, mag }) }); + } else if (cmd === "/compact") doCompact(false); else if (cmd === "/context") transcript.push({ role: "system", text: "context: " + fmtK(sess.ctxUsed) + " / " + fmtK(sess.ctxWindow) + " tokens (" + Math.round((sess.ctxUsed / (sess.ctxWindow || 1)) * 100) + "%) · window " + fmtK(sess.ctxWindow) }); else if (cmd === "/cost") { diff --git a/lib/cli/ledger.js b/lib/cli/ledger.js new file mode 100644 index 0000000..c768070 --- /dev/null +++ b/lib/cli/ledger.js @@ -0,0 +1,104 @@ +"use strict"; +// ============================================================================ +// ledger — PURE helpers for the per-session cost ledger (`/turns`) and the +// lossless cost advisor (`/cheaper`). The host records one plain entry per +// finished turn; everything here is a function of that array (+ the current +// settings), so it is fully snapshot-testable. No I/O, no module state. +// +// A turn entry: { t, inTok, outTok, cost, dt, model, engine, label, paid, +// cacheRead } — all already known to the host at turn end. +// ============================================================================ + +const IDENT = (s) => s; +function theme(c) { + c = c || {}; + return { cyan: c.cyan || IDENT, gray: c.gray || IDENT, bold: c.bold || IDENT, dim: c.dim || IDENT, green: c.green || IDENT, yellow: c.yellow || IDENT, mag: c.mag || IDENT }; +} + +function fmtK(n) { n = Math.max(0, Math.round(n || 0)); return n >= 1000 ? (n / 1000).toFixed(n >= 100000 ? 0 : 1) + "k" : String(n); } +function money(n) { n = n || 0; return "$" + (n < 1 ? n.toFixed(4) : n.toFixed(2)); } +function fmtDur(s) { s = Math.max(0, Math.round(s || 0)); return s < 60 ? s + "s" : Math.floor(s / 60) + "m" + String(s % 60).padStart(2, "0") + "s"; } +function fit(s, w) { s = String(s == null ? "" : s).replace(/\s+/g, " ").trim(); if (w < 0) w = 0; if (s.length <= w) return s; if (w <= 1) return s.slice(0, w); return s.slice(0, w - 1) + "…"; } + +// Roll the whole session up: totals + the index of the costliest paid turn + +// how many prompts were sent more than once (candidates for the free cache). +function summarizeTurns(turns) { + turns = Array.isArray(turns) ? turns : []; + const sum = { turns: turns.length, inTok: 0, outTok: 0, cacheRead: 0, cost: 0, dt: 0, paidTurns: 0, topCostIdx: -1, dupPrompts: 0, dupTurns: 0 }; + let topCost = -1; + const seen = Object.create(null), dupKeys = Object.create(null); + turns.forEach((t, i) => { + sum.inTok += t.inTok || 0; sum.outTok += t.outTok || 0; sum.cacheRead += t.cacheRead || 0; + sum.cost += t.cost || 0; sum.dt += t.dt || 0; if (t.paid) sum.paidTurns++; + if ((t.cost || 0) > topCost) { topCost = t.cost || 0; sum.topCostIdx = i; } + const key = (t.label || "").trim().toLowerCase(); + if (key) { if (seen[key]) { sum.dupTurns++; if (!dupKeys[key]) { dupKeys[key] = 1; sum.dupPrompts++; } } else seen[key] = 1; } + }); + if (topCost <= 0) sum.topCostIdx = -1; // no paid cost to highlight + return sum; +} + +// renderTurns(turns, opt) -> string[] (the `/turns` ledger card). +// opt: { colors, width, max } max = how many recent turns to list. +function renderTurns(turns, opt) { + turns = Array.isArray(turns) ? turns : []; + opt = opt || {}; + const t = theme(opt.colors); + const C = Math.max(40, (opt.width | 0) || 80); + const max = Math.max(1, (opt.max | 0) || 12); + if (!turns.length) return [t.gray("no turns yet this session — the ledger fills in as you work")]; + const s = summarizeTurns(turns); + const out = []; + out.push(t.bold("session ledger") + t.gray(" " + s.turns + " turn" + (s.turns === 1 ? "" : "s") + " · ↑" + fmtK(s.inTok) + " ↓" + fmtK(s.outTok) + (s.cacheRead ? " · cache ↓" + fmtK(s.cacheRead) : "") + (s.cost ? " · " + money(s.cost) : " · free") + " · " + fmtDur(s.dt))); + const start = Math.max(0, turns.length - max); + const idxW = String(turns.length).length; + // the money column is right-aligned to the widest value shown + const shown = turns.slice(start); + const costW = Math.max(5, ...shown.map((x) => money(x.cost || 0).length)); + shown.forEach((x, j) => { + const i = start + j; + const n = String(i + 1).padStart(idxW); + const top = i === s.topCostIdx && (x.cost || 0) > 0; + const costStr = (x.paid ? money(x.cost || 0) : "free").padStart(costW); + const tail = " ↑" + fmtK(x.inTok) + " ↓" + fmtK(x.outTok) + " " + costStr + " " + fmtDur(x.dt); + const room = C - 2 - idxW - 2 - tail.length - (top ? 2 : 0); + const label = fit(x.label || "(turn)", Math.max(6, room)); + const line = (top ? t.yellow("▲ ") : "") + t.gray(n + ". ") + label + t.gray(" ".repeat(Math.max(1, room - label.length)) + tail); + out.push(" " + line); + }); + if (start > 0) out.push(t.dim(" … " + start + " earlier turn" + (start === 1 ? "" : "s") + " above")); + if (s.topCostIdx >= 0 && turns[s.topCostIdx] && (turns[s.topCostIdx].cost || 0) > 0) out.push(t.gray(" ▲ priciest: turn " + (s.topCostIdx + 1) + " at " + money(turns[s.topCostIdx].cost) + " — ") + t.dim("/cheaper for ways to spend less")); + return out; +} + +// costAdvice(turns, settings) -> [{ tag, text }] (lossless suggestions only — +// never anything that trades output quality for cost; the one quality tradeoff, +// effort, is flagged as such, not recommended blindly). settings: +// { cacheOn, effort, engine, paid, autoCompact, ctxPct } +function costAdvice(turns, settings) { + turns = Array.isArray(turns) ? turns : []; + settings = settings || {}; + const s = summarizeTurns(turns); + const tips = []; + if (!settings.paid) { tips.push({ tag: "free", text: "this engine is local (Ollama) — turns are already free, nothing to save." }); return tips; } + if (!settings.cacheOn) tips.push({ tag: "cache", text: "exact-repeat cache is OFF — `/cache on` serves an identical read-only turn for free (lossless)." }); + if (s.dupTurns > 0) tips.push({ tag: "dups", text: s.dupTurns + " turn" + (s.dupTurns === 1 ? "" : "s") + " repeated an earlier prompt verbatim" + (settings.cacheOn ? " — the exact-repeat cache already served those free." : " — turn `/cache on` and repeats cost nothing.") }); + if (settings.engine === "claude") tips.push({ tag: "prompt-cache", text: "on the claude engine prompt-caching is automatic — keep a session going (don't `/new`) so the big unchanged context is billed at the cheap cache-read rate." }); + if (settings.effort === "high" || settings.effort === "max" || settings.effort === "xhigh" || settings.effort === "ultracode") tips.push({ tag: "effort", text: "effort is " + settings.effort + " — it buys deeper reasoning but spends far more output tokens; drop to `/effort medium` for routine work (this is a quality tradeoff, your call — not auto-applied)." }); + if ((settings.ctxPct || 0) >= 50 && !settings.autoCompact) tips.push({ tag: "context", text: "context is " + Math.round(settings.ctxPct) + "% full — every turn re-bills the whole thing; `/compact` now folds it down (lossless summary) so later turns are cheaper." }); + if (s.topCostIdx >= 0 && turns[s.topCostIdx] && (turns[s.topCostIdx].cost || 0) > Math.max(0.01, (s.cost / Math.max(1, s.paidTurns)) * 3)) tips.push({ tag: "outlier", text: "turn " + (s.topCostIdx + 1) + " (" + money(turns[s.topCostIdx].cost) + ") cost well above your average — large pastes or wide file reads drive input tokens; trim what you paste in." }); + // "prompt-cache" is informational (always true on claude), so it doesn't count + // as something to fix — reassure when nothing actionable turned up. + if (!tips.some((t) => t.tag !== "prompt-cache")) tips.push({ tag: "ok", text: "nothing obvious to cut — cache is on and effort/context look reasonable. /turns shows where the tokens went." }); + return tips; +} + +function renderAdvice(turns, settings, colors) { + const t = theme(colors); + const tips = costAdvice(turns, settings); + const out = [t.bold("cost advisor") + t.gray(" — lossless ways to spend less (quality unchanged unless noted)")]; + for (const tip of tips) out.push(" " + t.green("•") + " " + t.gray(tip.text)); + return out; +} + +module.exports = { summarizeTurns, renderTurns, costAdvice, renderAdvice, fmtK, money, fmtDur }; diff --git a/test/run.js b/test/run.js index da03128..fa43c98 100644 --- a/test/run.js +++ b/test/run.js @@ -2724,6 +2724,46 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("view never crashes on a bare agent", Array.isArray(A.viewRows({ task: "x", status: "run", start: now }, 40, 12, 99, null, now))); } + group("cost ledger + advisor (/turns, /cheaper)"); + { + const L = require("../lib/cli/ledger"); + const turns = [ + { inTok: 1200, outTok: 400, cost: 0.012, dt: 3, model: "opus", engine: "claude", label: "add a command", paid: true, cacheRead: 0 }, + { inTok: 800, outTok: 120, cost: 0.004, dt: 1, model: "opus", engine: "claude", label: "add a command", paid: true, cacheRead: 500 }, + { inTok: 40000, outTok: 1500, cost: 0.21, dt: 22, model: "opus", engine: "claude", label: "review the engine", paid: true, cacheRead: 0 }, + ]; + // ---- summarizeTurns ---- + const sm = L.summarizeTurns(turns); + eq("sums input tokens", sm.inTok, 42000); + eq("sums output tokens", sm.outTok, 2020); + ok("sums cost", Math.abs(sm.cost - 0.226) < 1e-9); + eq("sums cache reads", sm.cacheRead, 500); + eq("flags the priciest turn", sm.topCostIdx, 2); + eq("counts a verbatim repeat", sm.dupTurns, 1); + eq("counts distinct repeated prompts", sm.dupPrompts, 1); + eq("empty ledger summarizes to zero turns", L.summarizeTurns([]).turns, 0); + eq("all-free session has no priciest turn", L.summarizeTurns([{ inTok: 9, outTok: 9, cost: 0, dt: 1, paid: false, label: "x" }]).topCostIdx, -1); + // ---- renderTurns ---- + const rows = L.renderTurns(turns, { width: 80 }); + ok("header totals the session", /3 turns/.test(rows[0]) && /42\.0k/.test(rows[0]) && /\$0\.2260/.test(rows[0])); + ok("lists each turn label", rows.some((r) => /add a command/.test(r)) && rows.some((r) => /review the engine/.test(r))); + ok("marks the priciest turn with ▲", rows.some((r) => r.includes("▲") && /review the engine/.test(r))); + ok("every row fits the width", rows.every((r) => r.replace(/\x1b\[[0-9;]*m/g, "").length <= 80)); + ok("empty ledger says so", /no turns yet/.test(L.renderTurns([], { width: 60 })[0])); + ok("max caps the listed rows + notes earlier turns", (() => { const many = Array.from({ length: 20 }, (_, i) => ({ inTok: 1, outTok: 1, cost: 0.001, dt: 1, paid: true, label: "t" + i })); const r = L.renderTurns(many, { width: 80, max: 5 }); return r.filter((x) => /\dt\d|t\d+/.test(x)).length <= 7 && r.some((x) => /earlier turn/.test(x)); })()); + // ---- costAdvice: lossless only ---- + const tips = L.costAdvice(turns, { paid: true, cacheOn: false, effort: "high", engine: "claude", ctxPct: 62, autoCompact: false }); + const tagset = tips.map((t) => t.tag); + ok("advises turning the exact-repeat cache on", tagset.includes("cache")); + ok("notes the verbatim repeats", tagset.includes("dups")); + ok("explains claude prompt-caching", tagset.includes("prompt-cache")); + ok("flags effort as a QUALITY tradeoff (not auto)", tips.find((t) => t.tag === "effort") && /quality tradeoff/.test(tips.find((t) => t.tag === "effort").text) && /not auto-applied/.test(tips.find((t) => t.tag === "effort").text)); + ok("suggests /compact on a full context", tagset.includes("context")); + ok("a local engine short-circuits to free", (() => { const r = L.costAdvice(turns, { paid: false }); return r.length === 1 && r[0].tag === "free"; })()); + ok("a tidy session says nothing to cut", (() => { const r = L.costAdvice([{ inTok: 50, outTok: 20, cost: 0.001, dt: 1, paid: true, label: "a" }], { paid: true, cacheOn: true, effort: "", engine: "claude", ctxPct: 10, autoCompact: true }); return r.some((t) => t.tag === "ok"); })()); + ok("renderAdvice frames the tips", (() => { const r = L.renderAdvice(turns, { paid: true, cacheOn: false, engine: "claude" }); return /cost advisor/.test(r[0]) && r.length > 1; })()); + } + group("compaction condenser animation"); { const CA = require("../lib/cli/compact-anim"); From a61ee82f605b020f319700caee870b4f808450a8 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 19:11:01 -0700 Subject: [PATCH 15/16] nexus: /tokens estimator, /alias shortcuts, /retry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three more commands: - /tokens … prices what @-attaching those paths would cost per turn BEFORE you send — walks dirs (skipping .git/node_modules/.nexus/etc), skips binaries + oversize files, ranks the heaviest files with their share, and shows first-turn vs cached-resend cost at the current model's rate. A lossless cost saver: see the bill before you pay it. New pure module lib/cli/tokcount.js (+17 tests); counts are a labelled estimate (~chars/4). - /alias = persisted shortcuts (saved to settings, loaded at startup); /alias lists, /alias rm removes. The rest of the line is appended (or $ARGUMENTS substituted). Refuses to shadow a built-in. - /retry re-runs your last prompt fresh, bypassing the exact-repeat cache for that one send (a new one-shot bypassCacheOnce flag). 1434 run.js tests green. --- darknode.js | 44 ++++++++++++++++++++++++-- lib/cli/tokcount.js | 76 +++++++++++++++++++++++++++++++++++++++++++++ test/run.js | 25 +++++++++++++++ 3 files changed, 142 insertions(+), 3 deletions(-) create mode 100644 lib/cli/tokcount.js diff --git a/darknode.js b/darknode.js index 0e8f435..7fcf61a 100755 --- a/darknode.js +++ b/darknode.js @@ -54,7 +54,8 @@ const { toolResultView, bootHeader, welcomeCard, idleHome, footerLine, helpLines const Composer = require("./lib/cli/composer"); // pure composer model + key dispatch + per-project history (lib/cli/composer.js) const Ask = require("./lib/cli/ask"); // pure renderer + key reducer for the model's ask_user multiple-choice prompt (lib/cli/ask.js) const CompactAnim = require("./lib/cli/compact-anim"); -const Ledger = require("./lib/cli/ledger"); // pure per-session cost ledger (/turns) + lossless cost advisor (/cheaper) (lib/cli/ledger.js) // pure renderer for the live compaction "condenser" animation (lib/cli/compact-anim.js) +const Ledger = require("./lib/cli/ledger"); +const TokCount = require("./lib/cli/tokcount"); // pure /tokens estimator — price files before @-attaching them (lib/cli/tokcount.js) // pure per-session cost ledger (/turns) + lossless cost advisor (/cheaper) (lib/cli/ledger.js) // pure renderer for the live compaction "condenser" animation (lib/cli/compact-anim.js) const Agents = require("./lib/cli/agents"); // pure renderer + key reducer for the Agents panel (live sub-agent list under the prompt bar) (lib/cli/agents.js) const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js @@ -2612,6 +2613,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // overlay { i, scroll } or null. addAgent/finishAgent feed the registry. let agents = [], agentSel = -1, agentView = null; let turnLog = []; // one entry per finished paid/local turn this session — feeds /turns + /cheaper (never persisted, no prompt text beyond a short label) + let bypassCacheOnce = false; // /retry sets this so the next send skips the exact-repeat cache and really re-runs + let aliases = {}; try { const _a = settingsStore.get("aliases"); if (_a && typeof _a === "object") aliases = _a; } catch (_) {} const AGENTS_MAX = 24; // cap the registry; drop the oldest FINISHED agents past this const addAgent = (task, opts) => { const a = Object.assign({ id: "ag_" + Date.now().toString(36) + "_" + agents.length, task: String(task || "").slice(0, 300), status: "run", start: Date.now(), result: "", native: true }, opts || {}); agents.push(a); if (agents.length > AGENTS_MAX) { const keep = agents.filter((x) => x.status === "run"); const fin = agents.filter((x) => x.status !== "run"); agents = fin.slice(Math.max(0, fin.length - (AGENTS_MAX - keep.length))).concat(keep).sort((x, y) => x.start - y.start); } return a; }; const finishAgent = (a, status, result) => { if (!a || a.status !== "run") return; a.status = status || "ok"; a.end = Date.now(); if (result != null) a.result = String(result); }; @@ -2764,7 +2767,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { ["/help", "commands, input prefixes & keys"], ["/clear", "start a fresh chat"], ["/chat-clear", "clear the screen, keep the conversation memory"], ["/compact", "summarize & shrink the context"], ["/trust", "trust this workspace's .nexus MCP servers + hooks"], ["/connect", "connect an AI: local model · Claude (API) · any provider"], - ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "lossless ways to spend fewer tokens"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], + ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "lossless ways to spend fewer tokens"], ["/tokens", "estimate what @-attaching a file/dir costs"], ["/alias", "make a shortcut: /alias name = text|/cmd"], ["/retry", "re-run your last prompt (fresh, no cache)"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], ["/report", "cost & usage report for chargeback (/report json|save|since )"], ["/compliance", "write a signed audit+usage compliance bundle (SOC2/review)"], ["/undo", "revert the last turn's file changes"], ["/rewind", "restore a specific checkpoint (/rewind N)"], ["/checkpoints", "list undo checkpoints"], @@ -3919,7 +3922,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // Response cache: an EXACT repeat of a READ-ONLY answer is served FREE. The key // includes the inlined context, so a changed file yields a new key and re-runs // (never a stale answer). /cache off to disable, /cache clear to wipe. - const ckey = cacheOn ? cacheKey(engine, sess.model || engine, promptText) : null; + const ckey = (cacheOn && !bypassCacheOnce) ? cacheKey(engine, sess.model || engine, promptText) : null; bypassCacheOnce = false; if (ckey) { const hit = cacheGet(cwd, ckey, CACHE_TTL); if (hit && hit.readonly && hit.text) { const blk = { role: "nexus", items: [{ type: "text", full: hit.text, shown: hit.text.length }] }; blk.summary = green("cache hit — free") + gray(" · saved " + ((PAID[engine] && hit.cost) ? "$" + hit.cost.toFixed(4) + " · " : "") + "↑" + fmtK(hit.inTok || 0) + " ↓" + fmtK(hit.outTok || 0) + " tok · /cache off to disable"); @@ -4626,6 +4629,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const arg = argstr.split(/\s+/)[0]; // Any command other than a repeated /clear cancels a pending clear confirmation. const clearWasPending = clearPending; if (cmd !== "/clear" && cmd !== "/new") clearPending = false; + if (aliases[cmd]) { let body = String(aliases[cmd]).replace(/\$ARGUMENTS/g, argstr).replace(/\$(\d+)/g, (_, n) => argstr.split(/\s+/)[+n - 1] || ""); if (!/\$ARGUMENTS|\$\d/.test(aliases[cmd]) && argstr) body += " " + argstr; if (body.trim()[0] === "/") handleSlash(body.trim()); else submit(body.trim()); return; } if (customCmds[cmd]) { let body = customCmds[cmd].body.replace(/\$ARGUMENTS/g, argstr).replace(/\$(\d+)/g, (_, n) => argstr.split(/\s+/)[+n - 1] || ""); submit(body); return; } if (cmd === "/help") { const HS = [ @@ -4795,6 +4799,40 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const n = parseInt(argstr, 10); transcript.push({ role: "system", lines: Ledger.renderTurns(turnLog, { colors: { cyan, gray, bold, dim, green, yellow, mag }, width: cols() - 4, max: n > 0 ? n : 12 }) }); } + else if (cmd === "/tokens") { + if (!argstr) { transcript.push({ role: "system", text: "usage: /tokens [more…] — estimate what @-attaching those would cost per turn (before you send). ≈ chars/4." }); } + else { + const CAP = 2 * 1024 * 1024; // per-file char cap — skip anything bigger + const entries = []; let count = 0; + const walk = (rel) => { + if (count > 4000 || entries.length > 4000) return; + let abs, st; try { abs = path.resolve(cwd, rel); st = fs.statSync(abs); } catch (_) { entries.push({ path: rel, chars: 0, skipped: true }); return; } + if (st.isDirectory()) { if (TokCount.SKIP_DIRS.has(path.basename(abs))) return; let kids = []; try { kids = fs.readdirSync(abs); } catch (_) { return; } for (const k of kids) { count++; walk(path.relative(cwd, path.join(abs, k))); } return; } + if (st.size > CAP) { entries.push({ path: rel, chars: st.size, skipped: true }); return; } + let buf; try { buf = fs.readFileSync(abs); } catch (_) { entries.push({ path: rel, chars: 0, skipped: true }); return; } + if (TokCount.looksBinary(buf)) { entries.push({ path: rel, chars: buf.length, binary: true }); return; } + entries.push({ path: rel, chars: buf.toString("utf8").length }); + }; + for (const a of argstr.split(/\s+/).filter(Boolean)) walk(a.replace(/^@/, "")); + const pr = priceOf(shownModel()); + transcript.push({ role: "system", lines: TokCount.renderTokens(entries, { price: { in: pr.in, cr: pr.cr }, paid: !!PAID[engine], model: pr.label, colors: { cyan, gray, bold, dim, green, yellow }, width: cols() - 4 }) }); + } + } + else if (cmd === "/alias") { + const m = argstr.match(/^([^\s=]+)\s*=\s*(.+)$/); + if (!argstr) { const ks = Object.keys(aliases); transcript.push({ role: "system", text: ks.length ? "aliases:\n" + ks.map((k) => " " + cyan(k) + gray(" → ") + aliases[k]).join("\n") + gray("\n /alias = · /alias rm ($ARGUMENTS forwards the rest)") : "no aliases yet — " + gray("/alias deploy = /pr · /alias fix = find and fix the bug in ($ARGUMENTS gets appended)") }); } + else if (arg === "rm" || arg === "remove" || arg === "del") { const nm = argstr.split(/\s+/)[1]; const key = nm && nm[0] === "/" ? nm : "/" + nm; if (nm && aliases[key]) { delete aliases[key]; saveSetting("aliases", aliases); transcript.push({ role: "system", text: "removed alias " + cyan(key) }); } else transcript.push({ role: "system", text: "no such alias — /alias lists them" }); } + else if (m) { + let name = m[1]; if (name[0] !== "/") name = "/" + name; name = name.toLowerCase(); + if (CMDS.some(([c]) => c === name) || customCmds[name]) transcript.push({ role: "system", text: name + " is a built-in command — pick another alias name" }); + else { aliases[name] = m[2].trim(); saveSetting("aliases", aliases); transcript.push({ role: "system", text: "alias " + cyan(name) + gray(" → ") + m[2].trim() + gray(" — type " + name + " to run it") }); } + } + else transcript.push({ role: "system", text: "usage: /alias = · /alias rm · /alias (list)" }); + } + else if (cmd === "/retry") { + if (busy) transcript.push({ role: "system", text: "a turn is still running — wait for it to finish, then /retry" }); + else { let last = null; for (let i = transcript.length - 1; i >= 0; i--) if (transcript[i].role === "user") { last = transcript[i].text; break; } if (last == null) transcript.push({ role: "system", text: "nothing to retry yet" }); else { bypassCacheOnce = true; transcript.push({ role: "system", text: gray("re-running your last prompt (fresh, skipping the exact-repeat cache)…") }); submit(last); } } + } else if (cmd === "/cheaper") { transcript.push({ role: "system", lines: Ledger.renderAdvice(turnLog, { paid: !!PAID[engine], cacheOn, effort, engine, autoCompact, ctxPct: (sess.ctxUsed / (sess.ctxWindow || 200000)) * 100 }, { cyan, gray, bold, dim, green, yellow, mag }) }); } diff --git a/lib/cli/tokcount.js b/lib/cli/tokcount.js new file mode 100644 index 0000000..9417202 --- /dev/null +++ b/lib/cli/tokcount.js @@ -0,0 +1,76 @@ +"use strict"; +// ============================================================================ +// tokcount — PURE helpers for `/tokens`: price files BEFORE you @-attach them, +// so you can see what a paste or a whole directory will cost per turn. The host +// walks the filesystem and hands in plain { path, chars, binary, skipped } +// entries; everything here is deterministic + snapshot-testable. +// +// Token counts are an ESTIMATE (≈ chars / 4, the usual English/code average) — +// labelled "≈" everywhere so it never pretends to be an exact tokenizer count. +// ============================================================================ + +const IDENT = (s) => s; +function theme(c) { + c = c || {}; + return { cyan: c.cyan || IDENT, gray: c.gray || IDENT, bold: c.bold || IDENT, dim: c.dim || IDENT, green: c.green || IDENT, yellow: c.yellow || IDENT }; +} + +function estimateTokens(chars) { return Math.ceil(Math.max(0, chars | 0) / 4); } +function fmtK(n) { n = Math.max(0, Math.round(n || 0)); return n >= 1000 ? (n / 1000).toFixed(n >= 100000 ? 0 : 1) + "k" : String(n); } +function money(n) { n = n || 0; return "$" + (n < 1 ? n.toFixed(4) : n.toFixed(2)); } +function fit(s, w) { s = String(s == null ? "" : s); if (w < 0) w = 0; if (s.length <= w) return s; if (w <= 1) return s.slice(0, w); return "…" + s.slice(-(w - 1)); } // keep the file-name end + +// Directories never worth attaching — skipped by the host walker. +const SKIP_DIRS = new Set([".git", "node_modules", ".nexus", "dist", "build", ".next", "coverage", "__pycache__", ".venv", "venv", "target", ".cache"]); + +// A buffer looks binary when its first 8KB holds a NUL byte (same rule git uses). +function looksBinary(buf) { if (!buf) return false; const n = Math.min(buf.length, 8192); for (let i = 0; i < n; i++) if (buf[i] === 0) return true; return false; } + +// summarize(entries, price) -> totals. price: { in, cr } USD per million tokens +// (cr = cache-read rate, or null when the model has no prompt caching). +function summarize(entries, price) { + entries = Array.isArray(entries) ? entries : []; + const text = entries.filter((e) => !e.binary && !e.skipped); + const tokens = text.reduce((a, e) => a + estimateTokens(e.chars), 0); + const p = price || {}; + return { + files: text.length, + binary: entries.filter((e) => e.binary).length, + skipped: entries.filter((e) => e.skipped).length, + tokens, + firstSend: p.in != null ? (tokens / 1e6) * p.in : null, // the first turn that carries it + cachedResend: p.cr != null ? (tokens / 1e6) * p.cr : null, // each later turn, when it hits the prompt cache + }; +} + +// renderTokens(entries, opt) -> string[]. opt: { price, paid, model, colors, width, max } +function renderTokens(entries, opt) { + opt = opt || {}; + const t = theme(opt.colors); + const C = Math.max(40, (opt.width | 0) || 80); + const max = Math.max(1, (opt.max | 0) || 10); + entries = Array.isArray(entries) ? entries : []; + if (!entries.length) return [t.gray("nothing matched — /tokens [more…] prices what you'd attach with @")]; + const s = summarize(entries, opt.price); + const out = []; + out.push(t.bold("token estimate") + t.gray(" ≈" + fmtK(s.tokens) + " tokens across " + s.files + " file" + (s.files === 1 ? "" : "s") + (s.binary ? " · " + s.binary + " binary skipped" : "") + (s.skipped ? " · " + s.skipped + " skipped" : ""))); + // the heaviest files first — that's where the cost is + const ranked = entries.filter((e) => !e.binary && !e.skipped).sort((a, b) => b.chars - a.chars); + const shown = ranked.slice(0, max); + const numW = Math.max(4, ...shown.map((e) => ("≈" + fmtK(estimateTokens(e.chars))).length)); + for (const e of shown) { + const n = ("≈" + fmtK(estimateTokens(e.chars))).padStart(numW); + const pct = s.tokens ? Math.round((estimateTokens(e.chars) / s.tokens) * 100) : 0; + const tail = " " + n + " " + String(pct).padStart(3) + "%"; + out.push(" " + fit(e.path, C - 4 - tail.length).padEnd(Math.max(0, C - 4 - tail.length)) + t.gray(tail)); + } + if (ranked.length > shown.length) out.push(t.dim(" … " + (ranked.length - shown.length) + " smaller file" + (ranked.length - shown.length === 1 ? "" : "s"))); + if (!opt.paid) out.push(t.green(" local engine — attaching this is free")); + else if (s.firstSend != null) { + out.push(t.gray(" at " + (opt.model || "this model") + ": ") + t.bold(money(s.firstSend)) + t.gray(" first turn") + (s.cachedResend != null ? t.gray(" · ") + t.bold(money(s.cachedResend)) + t.gray("/turn while cached") : "")); + } + if (s.tokens > 50000) out.push(t.yellow(" large — consider @-attaching just the files you need, or /pin only the key ones")); + return out; +} + +module.exports = { estimateTokens, looksBinary, summarize, renderTokens, SKIP_DIRS }; diff --git a/test/run.js b/test/run.js index fa43c98..a6bac15 100644 --- a/test/run.js +++ b/test/run.js @@ -2724,6 +2724,31 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("view never crashes on a bare agent", Array.isArray(A.viewRows({ task: "x", status: "run", start: now }, 40, 12, 99, null, now))); } + group("token estimator (/tokens — price before attaching)"); + { + const T = require("../lib/cli/tokcount"); + eq("estimates ~chars/4 tokens", T.estimateTokens(4000), 1000); + eq("rounds up a partial token", T.estimateTokens(10), 3); + ok("detects a NUL byte as binary", T.looksBinary(Buffer.from([65, 66, 0, 67])) && !T.looksBinary(Buffer.from("plain text"))); + ok("skip-dirs cover the usual noise", T.SKIP_DIRS.has("node_modules") && T.SKIP_DIRS.has(".git") && T.SKIP_DIRS.has(".nexus")); + const entries = [{ path: "src/big.js", chars: 40000 }, { path: "README.md", chars: 8000 }, { path: "logo.png", chars: 1000, binary: true }, { path: "huge.bin", chars: 9e9, skipped: true }]; + const sm = T.summarize(entries, { in: 5, cr: 0.5 }); + eq("counts only real text files", sm.files, 2); + eq("counts binary + skipped separately", sm.binary + sm.skipped, 2); + eq("sums estimated tokens", sm.tokens, 12000); + ok("prices the first send and a cached resend", Math.abs(sm.firstSend - 0.06) < 1e-9 && Math.abs(sm.cachedResend - 0.006) < 1e-9); + ok("no cache rate → no cached-resend figure", T.summarize(entries, { in: 5, cr: null }).cachedResend === null); + const rows = T.renderTokens(entries, { price: { in: 5, cr: 0.5 }, paid: true, model: "Opus", width: 80 }); + ok("header shows the ≈ total + binary skip", /≈12\.0k tokens across 2 files/.test(rows[0]) && /1 binary/.test(rows[0])); + ok("ranks the heaviest file first with a share %", /src\/big\.js/.test(rows[1]) && /83%/.test(rows[1])); + ok("shows first-turn and cached cost", rows.some((r) => /\$0\.06/.test(r) && /first turn/.test(r) && /while cached/.test(r))); + ok("every row fits the width", rows.every((r) => r.replace(/\x1b\[[0-9;]*m/g, "").length <= 80)); + ok("a local engine says it's free", T.renderTokens(entries, { paid: false, width: 80 }).some((r) => /free/.test(r))); + ok("warns when the attachment is large", T.renderTokens([{ path: "x", chars: 400000 }], { price: { in: 5 }, paid: true, width: 80 }).some((r) => /large/.test(r))); + ok("empty match explains usage", /\/tokens/.test(T.renderTokens([], { width: 60 })[0])); + ok("long paths are truncated keeping the end", (() => { const r = T.renderTokens([{ path: "a/very/deeply/nested/" + "x".repeat(90) + "/file.js", chars: 400 }], { price: { in: 5 }, paid: true, width: 60 }); return r.every((x) => x.replace(/\x1b\[[0-9;]*m/g, "").length <= 60) && r.some((x) => /file\.js/.test(x)); })()); + } + group("cost ledger + advisor (/turns, /cheaper)"); { const L = require("../lib/cli/ledger"); From d1fe6344e166837fd2b1f38b1b5ba200dfae3e90 Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Sat, 24 Oct 2026 19:19:27 -0700 Subject: [PATCH 16/16] nexus: prompt-cache warmth chip + /warm (TTL countdown, warm vs cold follow-up cost) --- darknode.js | 13 ++++++- lib/cli/cachewarm.js | 83 ++++++++++++++++++++++++++++++++++++++++++++ test/run.js | 25 +++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 lib/cli/cachewarm.js diff --git a/darknode.js b/darknode.js index 7fcf61a..919e481 100755 --- a/darknode.js +++ b/darknode.js @@ -56,6 +56,7 @@ const Ask = require("./lib/cli/ask"); // pure renderer + key reducer for the mod const CompactAnim = require("./lib/cli/compact-anim"); const Ledger = require("./lib/cli/ledger"); const TokCount = require("./lib/cli/tokcount"); // pure /tokens estimator — price files before @-attaching them (lib/cli/tokcount.js) // pure per-session cost ledger (/turns) + lossless cost advisor (/cheaper) (lib/cli/ledger.js) // pure renderer for the live compaction "condenser" animation (lib/cli/compact-anim.js) +const CacheWarm = require("./lib/cli/cachewarm"); // pure prompt-cache TTL countdown for the status chip + /warm (lib/cli/cachewarm.js) const Agents = require("./lib/cli/agents"); // pure renderer + key reducer for the Agents panel (live sub-agent list under the prompt bar) (lib/cli/agents.js) const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js @@ -2587,6 +2588,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { const shownModel = () => (sess.model && sess.model !== engine) ? sess.model : (cliDefaultModel() || (ENGINES[engine] || {}).model || ""); const addUsage = (modelUsage, u, mainModel) => { const b = usageBuckets(u); const w = b.cacheWrite5m + b.cacheWrite1h; const r1h = w ? b.cacheWrite1h / w : 0; + if (w || b.cacheRead) { cacheWarm.ttl = CacheWarm.ttlFromWrites(b.cacheWrite5m, b.cacheWrite1h, cacheWarm.ttl); cacheWarm.lastAt = Date.now(); } // any cache touch refreshes the TTL clock const add = (name, x) => { const t = sess.byModel[name] || (sess.byModel[name] = { input: 0, output: 0, cacheWrite5m: 0, cacheWrite1h: 0, cacheRead: 0, reported: 0 }); for (const k of ["input", "output", "cacheWrite5m", "cacheWrite1h", "cacheRead"]) t[k] += x[k] || 0; t.reported += x.reported || 0; }; const names = modelUsage && typeof modelUsage === "object" ? Object.keys(modelUsage) : []; if (names.length) for (const n of names) { const m = modelUsage[n] || {}; const cw = m.cacheCreationInputTokens || 0; add(n, { input: m.inputTokens || 0, output: m.outputTokens || 0, cacheWrite1h: Math.round(cw * r1h), cacheWrite5m: cw - Math.round(cw * r1h), cacheRead: m.cacheReadInputTokens || 0, reported: m.costUSD || 0 }); } @@ -2613,6 +2615,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // overlay { i, scroll } or null. addAgent/finishAgent feed the registry. let agents = [], agentSel = -1, agentView = null; let turnLog = []; // one entry per finished paid/local turn this session — feeds /turns + /cheaper (never persisted, no prompt text beyond a short label) + const cacheWarm = { lastAt: 0, ttl: 0 }; // when a claude call last touched the prompt cache + which TTL it wrote (status chip + /warm) let bypassCacheOnce = false; // /retry sets this so the next send skips the exact-repeat cache and really re-runs let aliases = {}; try { const _a = settingsStore.get("aliases"); if (_a && typeof _a === "object") aliases = _a; } catch (_) {} const AGENTS_MAX = 24; // cap the registry; drop the oldest FINISHED agents past this @@ -2767,7 +2770,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { ["/help", "commands, input prefixes & keys"], ["/clear", "start a fresh chat"], ["/chat-clear", "clear the screen, keep the conversation memory"], ["/compact", "summarize & shrink the context"], ["/trust", "trust this workspace's .nexus MCP servers + hooks"], ["/connect", "connect an AI: local model · Claude (API) · any provider"], - ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "lossless ways to spend fewer tokens"], ["/tokens", "estimate what @-attaching a file/dir costs"], ["/alias", "make a shortcut: /alias name = text|/cmd"], ["/retry", "re-run your last prompt (fresh, no cache)"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], + ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "lossless ways to spend fewer tokens"], ["/warm", "prompt-cache countdown + warm-vs-cold follow-up cost"], ["/tokens", "estimate what @-attaching a file/dir costs"], ["/alias", "make a shortcut: /alias name = text|/cmd"], ["/retry", "re-run your last prompt (fresh, no cache)"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], ["/report", "cost & usage report for chargeback (/report json|save|since )"], ["/compliance", "write a signed audit+usage compliance bundle (SOC2/review)"], ["/undo", "revert the last turn's file changes"], ["/rewind", "restore a specific checkpoint (/rewind N)"], ["/checkpoints", "list undo checkpoints"], @@ -3237,6 +3240,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { if (runningShells) parts.push(yellow(runningShells + " shell" + (runningShells > 1 ? "s" : ""))); if (bgJobs.running()) parts.push(cyan(bgJobs.running() + " bg")); if (activeAgents) parts.push(mag(activeAgents + " agent" + (activeAgents > 1 ? "s" : ""))); + if (engine === "claude") { const wc = CacheWarm.chip(CacheWarm.cacheState({ lastAt: cacheWarm.lastAt, ttl: cacheWarm.ttl, now: Date.now() }), { green, yellow, dim: gray }); if (wc) parts.push(wc); } if (rate && rate.status && rate.status !== "allowed") parts.push(red("rate-limited")); else if (rate && rate.isUsingOverage) parts.push(yellow("overage")); if (pinned.size) parts.push(cyan(pinned.size + " pinned")); @@ -3724,6 +3728,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { // ---- animation loop: typewriter reveal + spinners + elapsed ---- const revealing = () => { const b = activeBlock || cur(); if (!b || !b.items) return false; return b.items.some((it) => it.type === "text" && it.shown < it.full.length); }; const startTick = () => { if (tick) return; tick = setInterval(() => { const b = activeBlock || cur(); if (b && b.items) for (const it of b.items) if (it.type === "text" && it.shown < it.full.length) { let ns = Math.min(it.full.length, it.shown + Math.max(2, Math.ceil((it.full.length - it.shown) / 22))); const cc = it.full.charCodeAt(ns - 1); if (cc >= 0xD800 && cc <= 0xDBFF && ns < it.full.length) ns++; it.shown = ns; } render(); if (!busy && !revealing() && !compact.on) { clearInterval(tick); tick = null; } }, 45); }; + // idle refresh for the prompt-cache chip: re-render only when its text changes (minute steps, then seconds in the last minute) + let lastWarmChip = ""; const warmTimer = setInterval(() => { if (busy || engine !== "claude" || !cacheWarm.lastAt) return; const c = CacheWarm.chip(CacheWarm.cacheState({ lastAt: cacheWarm.lastAt, ttl: cacheWarm.ttl, now: Date.now() })); if (c !== lastWarmChip) { lastWarmChip = c; render(); } }, 5000); if (warmTimer.unref) warmTimer.unref(); // Flatten the kept transcript tail into a short plain-text summary, so a // claude turn that has just dropped --continue still knows what came before. // User lines and the model's own answers only — no tool spew, capped so the @@ -4829,6 +4835,11 @@ function nexusTui(engine, cwd, nexusMd, autoResume) { } else transcript.push({ role: "system", text: "usage: /alias = · /alias rm · /alias (list)" }); } + else if (cmd === "/warm") { + const pr = priceOf(shownModel()); + transcript.push({ role: "system", lines: CacheWarm.explain({ engine, lastAt: cacheWarm.lastAt, ttl: cacheWarm.ttl, now: Date.now(), ctxTok: sess.ctxUsed || 0, price: pr, colors: { gray, green, yellow, bold, dim: gray } }) }); + scroll = 0; render(); + } else if (cmd === "/retry") { if (busy) transcript.push({ role: "system", text: "a turn is still running — wait for it to finish, then /retry" }); else { let last = null; for (let i = transcript.length - 1; i >= 0; i--) if (transcript[i].role === "user") { last = transcript[i].text; break; } if (last == null) transcript.push({ role: "system", text: "nothing to retry yet" }); else { bypassCacheOnce = true; transcript.push({ role: "system", text: gray("re-running your last prompt (fresh, skipping the exact-repeat cache)…") }); submit(last); } } diff --git a/lib/cli/cachewarm.js b/lib/cli/cachewarm.js new file mode 100644 index 0000000..7e36ada --- /dev/null +++ b/lib/cli/cachewarm.js @@ -0,0 +1,83 @@ +"use strict"; +// ============================================================================ +// cachewarm — PURE helpers for prompt-cache warmth. Anthropic's prompt cache +// keeps a conversation's prefix for a TTL (5 minutes by default, or 1 hour); +// a follow-up sent while it is warm re-reads that context at the cheap +// cache-READ rate, but once it goes cold the next turn re-WRITES it at the +// (much higher) write rate. Knowing how long you have left is a lossless saver. +// +// The host records the last time a call touched the cache plus which TTL the +// writes used (both straight from the real API usage buckets). Everything here +// is a function of those numbers + `now`, so it is fully testable. +// ============================================================================ + +const IDENT = (s) => s; +function theme(c) { c = c || {}; return { gray: c.gray || IDENT, green: c.green || IDENT, yellow: c.yellow || IDENT, bold: c.bold || IDENT, dim: c.dim || IDENT }; } + +const TTL_5M = 5 * 60 * 1000, TTL_1H = 60 * 60 * 1000; +const COOLING_MS = 60 * 1000; // last minute: warn +const COLD_SHOW_MS = 10 * 60 * 1000; // keep a "cold" chip this long after expiry, then hide + +// Which TTL did this call's cache writes use? Majority of written tokens wins; +// a call with no writes (pure cache read) keeps the previous TTL. +function ttlFromWrites(w5m, w1h, prevTtl) { + w5m = Math.max(0, w5m || 0); w1h = Math.max(0, w1h || 0); + if (!w5m && !w1h) return prevTtl || TTL_5M; + return w1h > w5m ? TTL_1H : TTL_5M; +} + +// cacheState({ lastAt, ttl, now }) -> { state: "none"|"warm"|"cooling"|"cold"|"hidden", leftMs } +function cacheState(o) { + o = o || {}; + if (!o.lastAt) return { state: "none", leftMs: 0 }; + const ttl = o.ttl || TTL_5M; + const left = o.lastAt + ttl - (o.now || Date.now()); + if (left > COOLING_MS) return { state: "warm", leftMs: left }; + if (left > 0) return { state: "cooling", leftMs: left }; + if (-left < COLD_SHOW_MS) return { state: "cold", leftMs: left }; + return { state: "hidden", leftMs: left }; +} + +function fmtLeft(ms) { const s = Math.max(0, Math.ceil(ms / 1000)); if (s >= 3600) return Math.floor(s / 3600) + "h" + String(Math.floor((s % 3600) / 60)).padStart(2, "0") + "m"; if (s >= 60) return Math.ceil(s / 60) + "m"; return s + "s"; } + +// The status-bar chip: "cache 3m" (green) · "cache 42s" (yellow) · "cache cold" (dim). "" when none/hidden. +function chip(st, colors) { + const t = theme(colors); + if (!st || st.state === "none" || st.state === "hidden") return ""; + if (st.state === "warm") return t.green("cache " + fmtLeft(st.leftMs)); + if (st.state === "cooling") return t.yellow("cache " + fmtLeft(st.leftMs)); + return t.dim("cache cold"); +} + +// What a follow-up would cost for the context NOW (warm → read) vs after it +// goes cold (→ re-write). price: { cr, cw5, cw1h } USD/M; ctxTok = context size. +function followUpCost(ctxTok, price, ttl) { + price = price || {}; + const n = Math.max(0, ctxTok || 0) / 1e6; + const write = ttl === TTL_1H ? price.cw1h : price.cw5; + return { warm: price.cr != null ? n * price.cr : null, cold: write != null ? n * write : null }; +} + +function money(n) { return "$" + ((n || 0) < 1 ? (n || 0).toFixed(4) : n.toFixed(2)); } +function fmtK(n) { n = Math.max(0, Math.round(n || 0)); return n >= 1000 ? (n / 1000).toFixed(n >= 100000 ? 0 : 1) + "k" : String(n); } + +// The /warm explainer. o: { lastAt, ttl, now, ctxTok, price, engine, colors } +function explain(o) { + o = o || {}; + const t = theme(o.colors); + if (o.engine !== "claude") return [t.gray("prompt caching is tracked on the claude engine — this engine (" + (o.engine || "?") + ") doesn't report it")]; + const st = cacheState(o); + if (st.state === "none") return [t.gray("no cached context yet — after your first turn, the conversation prefix is cached and follow-ups re-read it cheaply")]; + const ttlName = (o.ttl || TTL_5M) === TTL_1H ? "1-hour" : "5-minute"; + const out = []; + if (st.state === "warm" || st.state === "cooling") out.push((st.state === "warm" ? t.green("● warm") : t.yellow("◐ cooling")) + t.gray(" prompt cache stays warm for ") + t.bold(fmtLeft(st.leftMs)) + t.gray(" more (" + ttlName + " TTL, refreshed by every turn)")); + else out.push(t.dim("○ cold") + t.gray(" the " + ttlName + " cache expired " + fmtLeft(-st.leftMs) + " ago — the next turn re-writes the context")); + const fc = followUpCost(o.ctxTok, o.price, o.ttl); + if (o.ctxTok && fc.warm != null && fc.cold != null) { + out.push(t.gray(" ≈" + fmtK(o.ctxTok) + " tokens of context: ") + t.bold(money(fc.warm)) + t.gray(" to re-read while warm vs ") + t.bold(money(fc.cold)) + t.gray(" to re-write once cold" + (fc.warm > 0 ? " (" + Math.round(fc.cold / fc.warm) + "×)" : ""))); + } + if (st.state !== "cold") out.push(t.gray(" tip: send the follow-up before it cools — any turn resets the clock")); + return out; +} + +module.exports = { TTL_5M, TTL_1H, ttlFromWrites, cacheState, chip, followUpCost, explain, fmtLeft }; diff --git a/test/run.js b/test/run.js index a6bac15..f7d9e5e 100644 --- a/test/run.js +++ b/test/run.js @@ -2724,6 +2724,31 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec ok("view never crashes on a bare agent", Array.isArray(A.viewRows({ task: "x", status: "run", start: now }, 40, 12, 99, null, now))); } + group("prompt-cache warmth (/warm + status chip)"); + { + const W = require("../lib/cli/cachewarm"); + const now = 1e9, pr = { cr: 0.5, cw5: 6.25, cw1h: 10 }; + eq("1h writes win the TTL vote", W.ttlFromWrites(10, 900, 0), W.TTL_1H); + eq("5m writes win the TTL vote", W.ttlFromWrites(900, 10, 0), W.TTL_5M); + eq("a pure cache read keeps the previous TTL", W.ttlFromWrites(0, 0, W.TTL_1H), W.TTL_1H); + eq("no cache touch yet -> none", W.cacheState({ lastAt: 0, now }).state, "none"); + eq("fresh 5m cache is warm", W.cacheState({ lastAt: now - 60000, ttl: W.TTL_5M, now }).state, "warm"); + eq("last minute is cooling", W.cacheState({ lastAt: now - 250000, ttl: W.TTL_5M, now }).state, "cooling"); + eq("past the TTL is cold", W.cacheState({ lastAt: now - 400000, ttl: W.TTL_5M, now }).state, "cold"); + eq("long-cold hides the chip", W.chip(W.cacheState({ lastAt: now - 3600000, ttl: W.TTL_5M, now })), ""); + eq("1h TTL is still warm after 30m", W.cacheState({ lastAt: now - 1800000, ttl: W.TTL_1H, now }).state, "warm"); + eq("warm chip shows minutes left", W.chip(W.cacheState({ lastAt: now - 60000, ttl: W.TTL_5M, now })), "cache 4m"); + eq("cooling chip shows seconds", W.chip(W.cacheState({ lastAt: now - 250000, ttl: W.TTL_5M, now })), "cache 50s"); + eq("cold chip", W.chip(W.cacheState({ lastAt: now - 400000, ttl: W.TTL_5M, now })), "cache cold"); + const fc = W.followUpCost(1e6, pr, W.TTL_5M); + ok("follow-up: re-read at cr, re-write at cw5", fc.warm === 0.5 && fc.cold === 6.25); + eq("1h TTL re-writes at cw1h", W.followUpCost(1e6, pr, W.TTL_1H).cold, 10); + const ex = W.explain({ engine: "claude", lastAt: now - 60000, ttl: W.TTL_5M, now, ctxTok: 42000, price: pr }).join("\n"); + ok("explainer shows warm, both prices and the ratio", /warm/.test(ex) && /\$0\.0210/.test(ex) && /\$0\.2625/.test(ex) && /13×/.test(ex)); + ok("cold explainer drops the hurry-up tip", !/tip:/.test(W.explain({ engine: "claude", lastAt: now - 400000, ttl: W.TTL_5M, now, ctxTok: 1000, price: pr }).join("\n"))); + ok("non-claude engines say it isn't tracked", /isn't|doesn't report/.test(W.explain({ engine: "ollama" })[0])); + } + group("token estimator (/tokens — price before attaching)"); { const T = require("../lib/cli/tokcount");