diff --git a/darknode.js b/darknode.js index be226dd..8f254f8 100755 --- a/darknode.js +++ b/darknode.js @@ -71,7 +71,8 @@ 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 (/costtips) (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 { idleWatchdog, engineWaits } = require("./lib/nexus/engine-watchdog"); // engine hang guard: idle-based, paused while the user answers a popup +const { idleWatchdog } = require("./lib/nexus/engine-watchdog"); // engine hang guard: idle-based (ask_user no longer holds the engine open) +const AskDefer = require("./lib/nexus/ask-defer"); // ask_user never blocks the engine: answer later, sent as the next prompt 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, toGeminiServers, 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 @@ -4056,20 +4057,30 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { // 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, link) => { + // The engine's call returns at once ({ deferred }), so its model ends the turn: no + // timeout, and no tokens spent while the question waits. The popup stays until the + // user answers or dismisses it; an answer goes out as the next ordinary prompt. + const deferredAsks = []; + const handleBridgeAsk = async (req) => { const q = String((req && req.question) || ""); if (!q) return { skipped: true }; - // live while the popup is open; once settled it becomes a record of the answer, so it never - // keeps saying the model is asking - const line = { role: "system", text: gray("the model is asking: ") + oneline(q, 60) }; transcript.push(line); render(); - const settle = (r) => { const a = r && (r.selected != null ? [].concat(r.selected).join(", ") : r.answer); const i = transcript.indexOf(line); if (i >= 0) transcript[i] = { role: "system", text: gray("asked: ") + oneline(q, 50) + gray(" → ") + (a != null && a !== "" ? oneline(String(a), 50) : gray((r && r.withdrawn) || tok.gone ? "withdrawn" : "skipped")) }; _blCache = null; _pre = null; render(); return r; }; // a new object: lines are cached per message and by the last message only - // Tag this request's popup; if the engine disconnects before the user answers, - // withdraw it (with a notice) rather than accept an answer that goes nowhere. - const tok = {}; - const tagAsk = (qq, oo, ex) => { const pr = askUser(qq, oo, ex); if (pendingAsk) pendingAsk._bridge = tok; return pr; }; - if (link && link.onGone) link.onGone(() => { if (pendingAsk && pendingAsk._bridge === tok) { tok.gone = true; const p = pendingAsk; pendingAsk = null; transcript.push({ role: "system", text: yellow("the engine stopped before you answered — the question was withdrawn (your answer was not sent)") }); p.resolve({ cancelled: true }); render(); } }); - engineWaits.n++; // the engine is silent while it waits on the user — never treat that as hung - try { return settle(await answerBridgeAsk(req, q, tagAsk)); } catch (e) { settle({ withdrawn: true }); throw e; } finally { engineWaits.n--; } + deferredAsks.push(req); + if (deferredAsks.length === 1) showDeferredAsk(); + return { deferred: true }; + }; + const showDeferredAsk = () => { + const req = deferredAsks[0]; if (!req) return; + const q = String(req.question); + const line = { role: "system", text: gray("the model asked: ") + oneline(q, 60) + gray(" · answer whenever you are ready") }; transcript.push(line); render(); + const next = () => { deferredAsks.shift(); showDeferredAsk(); }; + answerBridgeAsk(req, q, askUser).then((r) => { + const a = AskDefer.answerText(r); + const i = transcript.indexOf(line); // a new object: lines are cached per message and by the last message only + if (i >= 0) transcript[i] = { role: "system", text: gray("asked: ") + oneline(q, 50) + gray(" → ") + (a != null ? oneline(a, 50) : gray("dismissed, nothing sent")) }; + _blCache = null; _pre = null; + if (a != null) { nextQueue.push(AskDefer.answerPrompt(q, a)); scheduleDrain(0); } + render(); next(); + }, next); }; const answerBridgeAsk = async (req, q, askUser) => { if (req.input) { const ans = await askUser(q, [], { input: true, placeholder: req.placeholder }); return ans.cancelled ? { skipped: true } : { answer: String(ans.value || "") }; } diff --git a/lib/nexus/ask-defer.js b/lib/nexus/ask-defer.js new file mode 100644 index 0000000..8b84800 --- /dev/null +++ b/lib/nexus/ask-defer.js @@ -0,0 +1,27 @@ +"use strict"; +// ask-defer — ask_user for external engines without a blocking wait. The model's +// ask_user call returns at once with DEFERRED_NOTE, so the model ends its turn and +// nothing spends tokens or times out while the question waits. The popup stays on +// screen until the user answers (no expiry); the answer is then sent as the user's +// next ordinary message in the same session. Dismissing it sends nothing. + +const DEFERRED_NOTE = + "Your question is now on the user's screen. End your turn now: no more tool calls and no closing text. " + + "The user's answer will arrive as their next message."; + +const QMAX = 300; +// The message sent once the user answers. Short: it is billed as input on the next turn. +function answerPrompt(question, answer) { + const q = String(question || "").replace(/\s+/g, " ").trim(); + const qq = q.length > QMAX ? q.slice(0, QMAX - 1) + "…" : q; + return "Answer to your question \"" + qq + "\": " + String(answer); +} + +// The answer text from a normalized bridge answer, or null when the user dismissed it. +function answerText(r) { + if (!r || r.cancelled || r.skipped) return null; + const a = r.selected != null ? [].concat(r.selected).join(", ") : r.answer; + return a == null || String(a) === "" ? null : String(a); +} + +module.exports = { DEFERRED_NOTE, answerPrompt, answerText }; diff --git a/lib/nexus/ask-mcp.js b/lib/nexus/ask-mcp.js index b2fdc42..2970b8e 100644 --- a/lib/nexus/ask-mcp.js +++ b/lib/nexus/ask-mcp.js @@ -24,7 +24,8 @@ const ASK_TOOL = { "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).", + "or free-text (pass input:true with no options). Under Nexus the call returns at once: end your turn right " + + "after it, and the user's answer arrives as their next message.", inputSchema: { type: "object", properties: { @@ -72,6 +73,7 @@ function askNexus(args) { // Render the normalized answer as plain text the model reads as its tool result. function fmtAnswer(ans) { + if (ans && ans.deferred) return require("./ask-defer").DEFERRED_NOTE; 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)"); diff --git a/test/run.js b/test/run.js index f15feac..0a841a5 100644 --- a/test/run.js +++ b/test/run.js @@ -3648,6 +3648,13 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec 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))); + { const AD = require("../lib/nexus/ask-defer"); + ok("fmtAnswer: deferred tells the model to end its turn", fmtAnswer({ deferred: true }) === AD.DEFERRED_NOTE && /End your turn now/.test(AD.DEFERRED_NOTE)); + ok("ask_user description says the answer comes as the next message", /next message/.test(ASK_TOOL.description)); + ok("ask-defer: picks and typed answers become text", AD.answerText({ selected: "B", index: 1 }) === "B" && AD.answerText({ selected: ["A", "C"] }) === "A, C" && AD.answerText({ answer: "go" }) === "go"); + ok("ask-defer: a dismissed question sends nothing", AD.answerText({ skipped: true }) === null && AD.answerText({ cancelled: true }) === null && AD.answerText({ answer: "" }) === null && AD.answerText(null) === null); + ok("ask-defer: answer prompt quotes the question", AD.answerPrompt("Ship it?\nnow", "Yes") === 'Answer to your question "Ship it? now": Yes'); + ok("ask-defer: a long question is shortened in the prompt", AD.answerPrompt("x".repeat(1000), "y").length < 330); } 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 ---