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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions darknode.js
Original file line number Diff line number Diff line change
Expand Up @@ -1988,6 +1988,7 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) {
try { cp.stdin.on("error", () => {}); cp.stdin.end(viaStdin ? prompt : undefined); } catch (_) {} // big prompt on stdin, else EOF so claude doesn't wait on stdin
const dropSys = () => { if (sysFile) { try { require("fs").unlinkSync(sysFile); } catch (_) {} sysFile = ""; } };
let buf = "", finalText = "", res = null, killed = false;
const bgT = require("./lib/nexus/bg-cutoff").createBgTracker(); // background agents still working when claude exits
if (ctl) ctl.kill = () => { killed = true; killGroup(cp, "SIGINT"); setTimeout(() => killGroup(cp, "SIGKILL"), 1500); };
cp.stdout.setEncoding("utf8");
cp.stdout.on("data", (d) => {
Expand All @@ -1997,6 +1998,7 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) {
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
if (!line.trim()) continue;
let ev; try { ev = JSON.parse(line); } catch (_) { continue; }
bgT.event(ev);
if (ev.type === "system" && ev.subtype === "init") { h.onInit && h.onInit(ev); }
else if (ev.type === "rate_limit_event") { h.onRateLimit && h.onRateLimit(ev.rate_limit_info || {}); }
else if (ev.type === "assistant" && ev.message) {
Expand All @@ -2022,7 +2024,7 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) {
}
});
cp.stderr.on("data", () => { to.touch(); });
cp.on("close", (code) => { to.clear(); dropSys(); resolve({ ok: code === 0 && !killed, interrupted: killed, output: finalText, result: res }); });
cp.on("close", (code) => { to.clear(); dropSys(); resolve({ ok: code === 0 && !killed, interrupted: killed, output: finalText, result: res, bgCut: killed ? 0 : bgT.cut() }); });
cp.on("error", (e) => { to.clear(); dropSys(); resolve({ ok: false, output: "engine spawn error: " + e.message + (e.code === "E2BIG" ? " (the environment is too large to start a process; run /fixshell)" : " (is claude installed & logged in?)") }); });
});
}
Expand Down Expand Up @@ -4257,8 +4259,12 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) {
const onRejection = (e) => { if (busy || (ctl)) { busy = false; ctl = null; try { transcript.push({ role: "system", text: "recovered from an internal error: " + (e && e.message || e) }); } catch (_) {} try { render(); } catch (_) {} } };
process.on("exit", cleanup); process.on("SIGINT", onSigint); process.on("SIGTERM", onSigterm); process.on("SIGHUP", onHup); process.on("uncaughtException", onFatal); process.on("unhandledRejection", onRejection); // SIGHUP = terminal closed: still stop background jobs (they run in their own process groups)
// ---- engine turn ----
// Automatic resumes after Claude Code stopped background agents (lib/nexus/bg-cutoff.js):
// capped per message the user typed; a prompt Nexus queued itself does not reset the count.
let bgResumes = 0; const bgResumeTexts = new Set();
const submit = (text) => {
if (compact.on) { nextQueue.push(text); render(); return; } // runs once the compaction finishes
if (!bgResumeTexts.delete(text)) bgResumes = 0;
clearPending = false; // sending a message cancels a pending /clear confirmation
// Only enforce budget cap on API-billed engines, not Claude Max subscription
const isSubEngine = onPlan(engine);
Expand Down Expand Up @@ -4342,7 +4348,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) {
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
const bgCut = (res && !res.interrupted && res.bgCut) || 0; // Claude Code exited with background agents mid-task
for (const rg of agents) if (rg.status === "run" && rg.native === false) finishAgent(rg, (res && res.interrupted) || bgCut ? "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;
Expand Down Expand Up @@ -4393,6 +4400,13 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) {
input = text; curPos = input.length; composer.text = input; composer.cursor = curPos; composer.draft = ""; hIdx = history.length; composer.histIndex = history.length;
}
}
if (bgCut) {
const BG = require("./lib/nexus/bg-cutoff"), what = bgCut === 1 ? "a background agent" : bgCut + " background agents";
if (bgResumes < BG.RESUME_LIMIT) {
bgResumes++; const rp = BG.resumePrompt(bgCut); bgResumeTexts.add(rp); nextQueue.unshift(rp);
transcript.push({ role: "system", text: yellow("Claude Code ended its session while " + what + " " + (bgCut === 1 ? "was" : "were") + " still working, which stops them.") + gray(" Resuming them automatically (" + bgResumes + " of " + BG.RESUME_LIMIT + "). Esc stops it.") });
} else transcript.push({ role: "system", text: yellow("Claude Code ended its session while " + what + " " + (bgCut === 1 ? "was" : "were") + " still working, which stops them.") + gray(" Nexus already resumed " + BG.RESUME_LIMIT + " times for this message; type continue to resume again.") });
}
if (!(res && res.interrupted) && (stat.files.size || stat.cmds || +dt >= 20 || block.items.filter((i) => i.type === "tool").length >= 3)) maybeRecap(block, text, { files: [...stat.files], cmds: stat.cmds });
maybeAutoCompact(); maybeAutoTitle(); idleTitle(); render(); refreshGit();
if (nextQueue.length && !busy && !compact.on) scheduleDrain(300);
Expand Down Expand Up @@ -4446,7 +4460,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) {
addUsage(_mu, 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() + 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);
}, 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: require("./lib/nexus/bg-cutoff").HOST_NOTE + "\n" + ((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
Expand Down
45 changes: 45 additions & 0 deletions lib/nexus/bg-cutoff.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"use strict";
// bg-cutoff — notices when Claude Code ends a Nexus turn while its background agents are
// still working. Nexus runs the claude engine one message at a time (`claude -p`). After
// Claude's reply ends, that process keeps its background agents running for a while
// (about 10 minutes) and then exits, and the agents stop mid-task. Before this, the turn
// just ended and the agents were shown as done, so it looked like Nexus cut out at random.
//
// The tracker reads the same stream-json events runClaudeStream parses: once a `result`
// arrives (the reply is over), any further event from a sub-agent (parent_tool_use_id set)
// means background work is in flight; a new `result` clears it (Claude picked the work up
// again). If the process then closes, that work was cut off.

const RESUME_LIMIT = 6; // automatic resumes per message the user typed

function createBgTracker() {
let afterResult = false;
const live = new Set();
return {
event(ev) {
if (!ev || typeof ev !== "object") return;
if (ev.type === "result") { afterResult = true; live.clear(); return; }
if (!afterResult) return;
const pid = ev.parent_tool_use_id;
if (pid && (ev.type === "assistant" || ev.type === "user" || ev.type === "stream_event")) live.add(pid);
},
// -> number of sub-agents that were still working when the process closed (0 = none)
cut() { return live.size; },
};
}

// Told to the model on every claude-engine turn, so long work is not started in a way
// that dies with the process.
const HOST_NOTE = "Host note (Nexus): each message runs as a separate `claude -p` session. " +
"Background agents and background commands are stopped about 10 minutes after your reply ends, even mid-task. " +
"For work that takes longer: run the agents in the foreground (run_in_background: false) and stay in the turn until they finish, " +
"or start them as Nexus background sessions with the mcp__nexus__sessions tool (action=spawn, then wait), which keep running between messages. " +
"Have long jobs save progress as they go so a stopped job can resume.";

function resumePrompt(n) {
return "Your " + (n === 1 ? "background agent was" : n + " background agents were") +
" stopped mid-task because the previous session ended (Claude Code stops background work about 10 minutes after a reply). " +
"Check what each one finished, then continue the unfinished work. Prefer foreground agents (run_in_background: false) so this session stays open until they are done.";
}

module.exports = { createBgTracker, HOST_NOTE, resumePrompt, RESUME_LIMIT };
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"scripts": {
"start": "node darknode.js",
"build": "pkg . --out-path dist",
"test": "node test/run.js && node test/usage-ping.test.js && node test/authz.test.js && node test/composer.test.js && node test/term.test.js && node test/md-render.test.js && node test/links.test.js && node test/pager.test.js && node test/tool-tail.test.js && node test/os-notify.test.js && node test/repo-map-rank.test.js && node test/bm25.test.js && node test/danger-audit.test.js && node test/url-guard-audit.test.js && node test/edit-audit.test.js && node test/jail-audit.test.js && node test/mcp-audit.test.js && node test/git-search-audit.test.js && node test/state-audit.test.js && node test/exec-audit.test.js && node test/cli-audit.test.js && node test/governance-audit.test.js && node test/toolkit-audit.test.js && node test/devhelpers-audit.test.js && node test/radar-audit.test.js && node test/pentest-audit.test.js && node test/shellfix-audit.test.js && node test/convo-lifecycle-audit.test.js && node test/local-loop-audit.test.js && node test/undo-audit.test.js && node test/at-mentions-audit.test.js && node test/clipboard-audit.test.js && node test/notes-audit.test.js && node test/snippets-audit.test.js && node test/typed-names-audit.test.js && node test/sighup-audit.test.js && node test/tui-stderr-audit.test.js && node test/piped-stdin-audit.test.js && node test/oneshot-escape-audit.test.js && node test/hot-path-speed-audit.test.js && node test/command-help.test.js && node test/session-save.test.js && node test/agents-panel.test.js && node test/tui-layout.test.js && node test/hub.test.js",
"test": "node test/run.js && node test/bg-cutoff.test.js && node test/usage-ping.test.js && node test/authz.test.js && node test/composer.test.js && node test/term.test.js && node test/md-render.test.js && node test/links.test.js && node test/pager.test.js && node test/tool-tail.test.js && node test/os-notify.test.js && node test/repo-map-rank.test.js && node test/bm25.test.js && node test/danger-audit.test.js && node test/url-guard-audit.test.js && node test/edit-audit.test.js && node test/jail-audit.test.js && node test/mcp-audit.test.js && node test/git-search-audit.test.js && node test/state-audit.test.js && node test/exec-audit.test.js && node test/cli-audit.test.js && node test/governance-audit.test.js && node test/toolkit-audit.test.js && node test/devhelpers-audit.test.js && node test/radar-audit.test.js && node test/pentest-audit.test.js && node test/shellfix-audit.test.js && node test/convo-lifecycle-audit.test.js && node test/local-loop-audit.test.js && node test/undo-audit.test.js && node test/at-mentions-audit.test.js && node test/clipboard-audit.test.js && node test/notes-audit.test.js && node test/snippets-audit.test.js && node test/typed-names-audit.test.js && node test/sighup-audit.test.js && node test/tui-stderr-audit.test.js && node test/piped-stdin-audit.test.js && node test/oneshot-escape-audit.test.js && node test/hot-path-speed-audit.test.js && node test/command-help.test.js && node test/session-save.test.js && node test/agents-panel.test.js && node test/tui-layout.test.js && node test/hub.test.js",
"postinstall": "node scripts/postinstall.js",
"docs": "node scripts/gen-nexus-docs.js"
},
Expand Down
22 changes: 22 additions & 0 deletions test/bg-cutoff.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"use strict";
// bg-cutoff: spot Claude Code ending a turn while its background agents are mid-task.
const { createBgTracker, HOST_NOTE, resumePrompt, RESUME_LIMIT } = require("../lib/nexus/bg-cutoff");
let pass = 0, fail = 0;
const ok = (name, cond) => { if (cond) pass++; else { fail++; console.log(" FAIL " + name); } };
const run = (evs) => { const t = createBgTracker(); for (const e of evs) t.event(e); return t.cut(); };
const sub = (pid, type = "assistant") => ({ type, parent_tool_use_id: pid, message: { content: [] } });
const main = { type: "assistant", parent_tool_use_id: null, message: { content: [] } };
const result = { type: "result", subtype: "success" };

ok("a plain turn is not a cut-off", run([main, result]) === 0);
ok("foreground agents that finish before the reply are not a cut-off", run([main, sub("t1"), sub("t1", "user"), main, result]) === 0);
ok("agents still working after the reply, then exit = cut off", run([main, result, sub("t1"), sub("t2"), sub("t1", "user"), sub("t3", "stream_event")]) === 3);
ok("agents that finish and Claude replies again = not cut off", run([main, result, sub("t1"), main, result]) === 0);
ok("a later burst after the second reply still counts", run([result, sub("a"), result, sub("b")]) === 1);
ok("system and rate-limit events are ignored", run([result, { type: "system", subtype: "task_progress", parent_tool_use_id: "x" }, { type: "rate_limit_event" }]) === 0);
ok("junk input never throws", (() => { const t = createBgTracker(); t.event(null); t.event("x"); return t.cut() === 0; })());
ok("host note names the 10-minute stop and both ways out", /10 minutes/.test(HOST_NOTE) && /run_in_background: false/.test(HOST_NOTE) && /mcp__nexus__sessions/.test(HOST_NOTE));
ok("resume prompt counts agents", /^Your 3 background agents were/.test(resumePrompt(3)) && /^Your background agent was/.test(resumePrompt(1)));
ok("resumes are capped", RESUME_LIMIT > 0 && RESUME_LIMIT <= 10);
console.log("bg-cutoff: " + pass + " passed, " + fail + " failed");
if (fail) process.exit(1);
Loading