diff --git a/command-ref.json b/command-ref.json index 8ce1f0c..9e17e57 100644 --- a/command-ref.json +++ b/command-ref.json @@ -1,7 +1,7 @@ { "generatedFrom": "lib/cli/reference.js COMMAND_GROUPS", "version": "2.46.3", - "commandCount": 89, + "commandCount": 93, "groups": [ { "title": "AI & Nexus", @@ -14,6 +14,22 @@ "usage": "nexus run \"\" [opts]", "desc": "autonomous multi-level runner: -e engine, --overnight, --until, --resume" }, + { + "usage": "nexus bg [-- agent args]", + "desc": "start a background session (Nexus, or e.g. -- claude) that keeps running after you close the terminal" + }, + { + "usage": "nexus ls / nexus sessions", + "desc": "every background session marked working, blocked or idle; sessions = live list (Enter attaches)" + }, + { + "usage": "nexus attach ", + "desc": "take over a background session in this terminal; Ctrl+] detaches and leaves it running" + }, + { + "usage": "nexus hub send|wait|peek|kill ", + "desc": "drive a session from scripts or other agents; wait --until blocked|idle|done; hub restore after a restart" + }, { "usage": "nexus serve [port]", "desc": "headless Nexus service: POST /run {goal} (loopback-only, token-gated)" diff --git a/darknode.js b/darknode.js index e717500..6f8a090 100755 --- a/darknode.js +++ b/darknode.js @@ -1209,6 +1209,12 @@ async function cliRun(args, gate) { else if (sub === "run" || sub === "supervise" || sub === "loop") await nexusRun(rest.slice(1)); else if (sub === "overnight") await nexusRun(["--overnight"].concat(rest.slice(1))); else if (sub === "agents" || sub === "parallel") await nexusAgents(rest.slice(1)); + // Background sessions (lib/nexus/hub): bg / ls / attach / send / wait / peek / kill / sessions / hub. + else if (await require("./lib/nexus/hub/cli").claims(sub, rest.slice(1))) { + const Hub = require("./lib/nexus/hub/cli"), C = { bold, gray, cyan, yellow, green, red }; + try { await (sub === "hub" ? Hub.hubMain(rest.slice(1), C) : Hub.main(sub, rest.slice(1), C)); } + catch (e) { console.error(" " + red(e.message)); process.exitCode = 1; } + } // Operator-facing headless equivalents of the in-TUI self-check slash commands: they run the // exact same tool engines the agent calls (via deviceTool), print the result, and exit non-zero // when the check fails so they double as CI gates. @@ -1451,7 +1457,7 @@ const CODER_SCHEMA = { type: "object", properties: { thought: { type: "string" } // it has no tools. normalizeToolCall recovers the real name + args so tools still fire. const TOOL_ARGKEY = { run_command: "command", run_background: "command", read_file: "path", write_file: "path", edit_file: "path", multi_edit: "path", multiedit: "path", apply_patch: "patch", patch: "patch", list_dir: "path", make_dir: "path", mkdir: "path", delete: "path", delete_file: "path", rm: "path", move: "from", copy: "from", search: "pattern", grep: "pattern", find: "glob", glob: "glob", http_fetch: "url", web_fetch: "url", fetch_url: "url", http: "url", web_search: "query", discover: "query", remember: "text", check_background: "id", stop_background: "id", list_processes: "filter", batch: "ops", batch_read: "ops", browser_read: "target", browser_page: "target", browser_eval: "expression", browser_exec: "expression", browser_screenshot: "path", browser_shot: "path", ask_user: "question", ask_question: "question", ask: "question" }; const KNOWN_ARGKEYS = new Set(["path", "command", "content", "query", "q", "url", "pattern", "glob", "find", "text", "note", "id", "filter", "to", "from", "dest", "name", "tasks", "todos", "items", "method", "replace", "recursive"]); -const KNOWN_TOOLS = new Set(["code_search", "read_file", "write_file", "edit_file", "list_dir", "run_command", "run_background", "check_background", "stop_background", "search", "grep", "find", "find_files", "glob", "http_fetch", "web_fetch", "fetch_url", "http", "web_search", "search_web", "google", "todo_write", "todos", "todo_list", "write_todos", "sysinfo", "system_info", "list_processes", "ps", "make_dir", "mkdir", "move", "rename", "move_file", "copy", "copy_file", "delete", "delete_file", "rm", "remember", "discover", "spawn_agents", "repo_map", "repomap", "multi_edit", "multiedit", "apply_patch", "patch", "verify", "run_tests", "test_project", "find_symbol", "symbol", "goto", "find_references", "references", "find_refs", "usages", "callers", "module_graph", "import_graph", "deps_graph", "dependents", "importers", "outline", "file_outline", "symbols", "read_symbol", "read_function", "show_symbol", "json_query", "jq", "read_json", "undo_edit", "replace_in_files", "wait_for", "write_stdin", "batch", "batch_read", "invariants", "check_invariants", "difflint", "attest", "attestation", "capability_attest", "bisect", "regression_bisect", "explain_break", "explainbreak", "blame_turn", "shrink", "minimize_change", "ddmin", "browser_status", "browser_tabs", "browser_list", "browser_read", "browser_page", "browser_eval", "browser_exec", "browser_screenshot", "browser_shot", "ask_user", "ask_question", "ask"]); +const KNOWN_TOOLS = new Set(["sessions", "code_search", "read_file", "write_file", "edit_file", "list_dir", "run_command", "run_background", "check_background", "stop_background", "search", "grep", "find", "find_files", "glob", "http_fetch", "web_fetch", "fetch_url", "http", "web_search", "search_web", "google", "todo_write", "todos", "todo_list", "write_todos", "sysinfo", "system_info", "list_processes", "ps", "make_dir", "mkdir", "move", "rename", "move_file", "copy", "copy_file", "delete", "delete_file", "rm", "remember", "discover", "spawn_agents", "repo_map", "repomap", "multi_edit", "multiedit", "apply_patch", "patch", "verify", "run_tests", "test_project", "find_symbol", "symbol", "goto", "find_references", "references", "find_refs", "usages", "callers", "module_graph", "import_graph", "deps_graph", "dependents", "importers", "outline", "file_outline", "symbols", "read_symbol", "read_function", "show_symbol", "json_query", "jq", "read_json", "undo_edit", "replace_in_files", "wait_for", "write_stdin", "batch", "batch_read", "invariants", "check_invariants", "difflint", "attest", "attestation", "capability_attest", "bisect", "regression_bisect", "explain_break", "explainbreak", "blame_turn", "shrink", "minimize_change", "ddmin", "browser_status", "browser_tabs", "browser_list", "browser_read", "browser_page", "browser_eval", "browser_exec", "browser_screenshot", "browser_shot", "ask_user", "ask_question", "ask"]); // A tool "name" that is really a shell command line — weak models often emit // {tool:"cat /etc/passwd"} or {tool:"ls /bin/*"} instead of run_command. const SHELL_CMD = /^(sudo\s+)?(ls|cat|grep|egrep|fgrep|echo|cd|pwd|whoami|id|uname|hostname|ps|top|df|du|free|date|env|printenv|which|type|find|locate|head|tail|awk|sed|cut|tr|sort|uniq|wc|xargs|tee|curl|wget|ping|traceroute|nmap|nc|ncat|dig|host|nslookup|ip|ifconfig|iwconfig|netstat|ss|arp|route|cp|mv|rm|mkdir|rmdir|touch|ln|stat|file|chmod|chown|tar|gzip|gunzip|zip|unzip|git|make|gcc|python3?|node|npm|npx|pip3?|bash|sh|zsh|kill|pkill|killall|systemctl|service|apt|apt-get|dpkg|ssh|scp|rsync|darknode|sentinel|nexus|nikto|sqlmap|hydra|john|hashcat|gobuster|ffuf|masscan|whatweb|searchsploit|msfconsole)(\s|$)/i; @@ -2489,6 +2495,7 @@ async function deviceTool(name, a, cwd) { if (!syms.length) res.note = /\.jsonc?$/i.test(fp) ? "JSON has no symbols — use json_query {path, query, keys_only:true} to see its structure" : "no functions/classes recognized in this file type — use read_file or search"; return res; } + if (name === "sessions") return require("./lib/nexus/hub/tool").sessionsTool(a, cwd); // background agent sessions (lib/nexus/hub) return null; } // Render one of the agentic self-check tools' result objects (invariants/attest/bisect/ @@ -3651,6 +3658,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { // ---- /effort interactive slider (Claude-Code-style): a Faster↔Smarter bar // the user nudges with ←/→ and confirms with Enter, instead of typing a level. let pendingEffort = null; // { sel } while the picker is open + // Inside a background session (nexus bg), tell the hub whether this TUI is working, waiting on a question, or idle. + const hubPoke = require("./lib/nexus/hub/report").startReporter(() => (pendingAsk ? "blocked" : busy ? "working" : "idle")); // ---- /god-prompt: a one-shot "maximum quality" mode for the NEXT message. // Arming turns the composer border gold; the settings apply for that single // turn only and revert automatically when it finishes. @@ -3807,6 +3816,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { const render = () => { pruneAgents(); if (cleaned) return; // after teardown: never touch the terminal again (a pending timer could still fire) + hubPoke(); if (_wasBusy && !busy && nextQueue.length) scheduleDrain(300); _wasBusy = busy; if (godActive && !busy) { godRestore(); godActive = false; } // /god-prompt reverts once its one turn finishes diff --git a/docs/NEXUS.md b/docs/NEXUS.md index 2a5c133..0a1f905 100644 --- a/docs/NEXUS.md +++ b/docs/NEXUS.md @@ -586,6 +586,33 @@ They apply to every engine. Add custom styles as `.nexus/styles/.md`. /update check for Darknode CLI updates ``` +### Background sessions + +Run agents in the background so they keep working after you close the terminal or lose an SSH connection. A small per-user hub (started on first use) owns each session under a real terminal. Linux and macOS. + +``` +nexus bg start Nexus here in the background +nexus bg --name api -- claude any agent or command after -- +nexus bg --prompt "add tests" type a first prompt once it is ready +nexus ls every session: working, blocked (needs you), idle, done +nexus sessions live list: Enter attaches, n new, x stop, r restore +nexus attach api take it over in this terminal; Ctrl+] detaches +nexus hub send api "run the tests" +nexus hub wait api --until blocked|idle|done|stopped [--timeout 600] +nexus hub peek api [--lines 40 | --screen] +nexus hub kill api +nexus hub restore after a reboot: relaunch saved sessions (Nexus resumes its conversation) +nexus hub stop | status +``` + +`send`, `wait`, `peek` and `kill` also work without `hub` when the next word is a session name (`nexus wait api`). + +- **States.** Nexus reports its own state exactly. Other agents are read from their screen: recent output (or a shell running a foreground command) means working, and a permission menu or a y/n question on the last line means blocked. +- **Notifications.** When a session nobody is attached to becomes blocked or finishes, you get a desktop notification. +- **Agents driving agents.** The `sessions` tool (list, spawn, send, wait, peek, kill) gives the agent the same control. It is available in Nexus's own loop and to Claude Code, Codex and other engines through the `nexus` MCP bridge. It goes through the same danger gate and policy as `run_command`, is blocked in plan mode, and only spawns inside the project folder. +- **Where things live.** `~/.nexus/hub/` (mode 700): the socket and `sessions.json`. `NEXUS_HUB_DIR` points it elsewhere. +- **Limits.** Processes do not survive a reboot or `nexus hub stop`; `hub restore` starts them again. Two Nexus sessions in one folder share that folder's saved conversation. Windows is not supported yet. + --- ## Misc Commands diff --git a/lib/cli/reference.js b/lib/cli/reference.js index 24ae30c..cc42a5c 100644 --- a/lib/cli/reference.js +++ b/lib/cli/reference.js @@ -12,6 +12,10 @@ const COMMAND_GROUPS = [ { title: "AI & Nexus", rows: [ ["nexus [opts] [task]", "Nexus AI coder chat: -e claude|gemini|codex|opencode|aider|ollama, -y skip prompts, --print headless"], ["nexus run \"\" [opts]", "autonomous multi-level runner: -e engine, --overnight, --until, --resume"], + ["nexus bg [-- agent args]", "start a background session (Nexus, or e.g. -- claude) that keeps running after you close the terminal"], + ["nexus ls / nexus sessions", "every background session marked working, blocked or idle; sessions = live list (Enter attaches)"], + ["nexus attach ", "take over a background session in this terminal; Ctrl+] detaches and leaves it running"], + ["nexus hub send|wait|peek|kill ", "drive a session from scripts or other agents; wait --until blocked|idle|done; hub restore after a restart"], ["nexus serve [port]", "headless Nexus service: POST /run {goal} (loopback-only, token-gated)"], ["update [--check]", "self-update to the latest version (git fast-forward; --check only reports)"], ["init", "scaffold Nexus in this project (.nexus/NEXUS.md + config)"], diff --git a/lib/nexus/ask-mcp.js b/lib/nexus/ask-mcp.js index 1c57d90..b2fdc42 100644 --- a/lib/nexus/ask-mcp.js +++ b/lib/nexus/ask-mcp.js @@ -38,6 +38,8 @@ const ASK_TOOL = { }, }; +const SESSIONS_TOOL = (() => { const s = require("./hub/tool").SCHEMA; return { name: "sessions", description: s.description, inputSchema: { type: "object", properties: s.properties, required: s.required } }; })(); + 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 } }); } @@ -88,9 +90,13 @@ async function handle(msg) { }); } if (method === "ping") return reply(id, {}); // MCP liveness check: an empty result, never an error - if (method === "tools/list") return reply(id, { tools: [ASK_TOOL] }); + if (method === "tools/list") return reply(id, { tools: [ASK_TOOL, SESSIONS_TOOL] }); if (method === "tools/call") { const p = msg.params || {}; + if (p.name === "sessions") { // background agent sessions (lib/nexus/hub/tool.js), for the engine's own model + const r = await require("./hub/tool").sessionsTool(p.arguments || {}, process.cwd()); + return reply(id, { content: [{ type: "text", text: JSON.stringify(r, null, 2) }], isError: !!r.error }); + } if (p.name !== "ask_user") return replyErr(id, -32602, "Unknown tool: " + p.name); // the spec's code for an unknown tool const a = p.arguments; if (!a || typeof a !== "object" || typeof a.question !== "string" || !a.question.trim()) return replyErr(id, -32602, "Invalid params: ask_user needs a non-empty string question"); @@ -130,4 +136,4 @@ function main() { if (require.main === module) main(); -module.exports = { fmtAnswer, ASK_TOOL, handle, askNexus }; // for unit tests +module.exports = { fmtAnswer, ASK_TOOL, SESSIONS_TOOL, handle, askNexus }; // for unit tests diff --git a/lib/nexus/hub/cli.js b/lib/nexus/hub/cli.js new file mode 100644 index 0000000..38b168b --- /dev/null +++ b/lib/nexus/hub/cli.js @@ -0,0 +1,251 @@ +"use strict"; +// ============================================================================ +// hub/cli — the commands people (and agents) use to run Nexus sessions in the +// background. See hub/server.js for what the hub is. +// +// nexus bg [--name N] [--cwd DIR] [--prompt TEXT] [-- command args...] +// nexus ls [--json] nexus attach [id|name] (Ctrl+] detaches) +// nexus send nexus peek [--lines N | --screen] +// nexus wait [--until blocked|idle|done|stopped] [--timeout SECS] +// nexus kill nexus sessions (live list: Enter attaches) +// nexus hub restore | stop | serve +// ============================================================================ +const path = require("path"), cp = require("child_process"), net = require("net"); +const P = require("./paths"); +const { RESET_CLIENT } = require("./screen"); +const { WAIT_STATES } = require("./status"); + +const DETACH = 0x1d; // Ctrl+] +const IDENT = (s) => s; + +function fmtAge(ms) { + const s = Math.max(0, Math.floor(ms / 1000)); + if (s < 60) return s + "s"; const m = Math.floor(s / 60); if (m < 60) return m + "m"; + const h = Math.floor(m / 60); if (h < 48) return h + "h" + String(m % 60).padStart(2, "0"); return Math.floor(h / 24) + "d"; +} +const home = (p) => { const h = require("os").homedir(); return p && p.startsWith(h) ? "~" + p.slice(h.length) : p; }; +const cut = (s, n) => { s = String(s || ""); return s.length > n ? s.slice(0, Math.max(0, n - 1)) + "…" : s; }; + +// The session table, used by `nexus ls` and the live list. Pure. +function renderTable(list, o = {}) { + const c = o.colors || {}, now = o.now || Date.now(), width = o.width || 100, sel = o.sel == null ? -1 : o.sel; + const paint = { working: c.cyan || IDENT, blocked: c.yellow || IDENT, idle: c.gray || IDENT, done: c.green || IDENT, failed: c.red || IDENT, stopped: c.gray || IDENT }; + const label = (s) => (s.saved ? "stopped" : s.state === "done" && s.exitCode ? "failed" : s.state); + const rows = list.map((s, i) => { + const st = label(s); + const name = cut(s.name, 22).padEnd(22), state = st.padEnd(8); + const age = (s.saved ? "" : fmtAge(now - (s.since != null ? s.since : now))).padStart(5); + const extra = (s.attached ? "attached " : "") + (s.title && s.title !== s.name ? s.title : ""); + const lead = i === sel ? "›" : " "; + const room = Math.max(0, width - 46); + const tail = cut(home(s.cwd) + (extra ? " " + extra : ""), room); + const line = lead + " " + String(s.id).padStart(3) + " " + name + " " + paint[st](state) + " " + (c.gray || IDENT)(age) + " " + (c.gray || IDENT)(tail); + return i === sel && c.bold ? c.bold(line) : line; + }); + return rows; +} + +async function ensureHub(o = {}) { + if (!P.supported()) throw new Error("background sessions need Linux or macOS for now"); + try { return await P.call({ op: "ping" }, { timeout: 1500 }); } catch (e) { if (o.noStart) throw e; } + const entry = process.pkg ? [process.execPath] : [process.execPath, path.join(__dirname, "..", "..", "..", "darknode.js")]; + const child = cp.spawn(entry[0], entry.slice(1).concat(["nexus", "hub", "serve"]), { detached: true, stdio: "ignore", cwd: require("os").homedir() }); + child.unref(); + for (let i = 0; i < 40; i++) { + await new Promise((r) => setTimeout(r, 100)); + try { return await P.call({ op: "ping" }, { timeout: 800 }); } catch (_) {} + } + throw new Error("could not start the session hub"); +} +async function req(msg, o) { await ensureHub(); const r = await P.call(msg, o); if (!r.ok) throw new Error(r.error || "the hub refused"); return r; } + +// ---- attach: this terminal becomes the session's terminal until Ctrl+] ---- +function attach(id, o = {}) { + return new Promise((resolve, reject) => { + const out = o.stdout || process.stdout, inp = o.stdin || process.stdin; + if (!inp.isTTY) return reject(new Error("attach needs a terminal")); + const sock = net.connect(P.sockPath()); + let ready = false, buf = Buffer.alloc(0), name = String(id || ""), ended = false; + const size = () => ({ cols: out.columns || 100, rows: out.rows || 30 }); + const onResize = () => { const z = size(); P.call({ op: "resize", id: name, cols: z.cols, rows: z.rows }).catch(() => {}); }; + const onKey = (d) => { + const k = d.indexOf(DETACH); + if (k >= 0) { if (k > 0) sock.write(d.slice(0, k)); return finish("detached"); } + sock.write(d); + }; + const finish = (why) => { + if (ended) return; ended = true; + try { inp.removeListener("data", onKey); inp.setRawMode(false); inp.pause(); } catch (_) {} + out.removeListener("resize", onResize); + try { sock.destroy(); } catch (_) {} + out.write(RESET_CLIENT + "\r\n"); + resolve({ why, name }); + }; + sock.on("connect", () => { const z = size(); sock.write(JSON.stringify({ op: "attach", id, cols: z.cols, rows: z.rows }) + "\n"); }); + sock.on("data", (d) => { + if (ready) return out.write(d); + buf = Buffer.concat([buf, d]); + const i = buf.indexOf(10); if (i < 0) return; + let r; try { r = JSON.parse(buf.slice(0, i).toString("utf8")); } catch (_) { r = { ok: false, error: "bad reply from the hub" }; } + if (!r.ok) { sock.destroy(); ended = true; return reject(new Error(r.error)); } + ready = true; name = r.session.name; + const rest = buf.slice(i + 1); buf = null; + inp.setRawMode(true); inp.resume(); inp.on("data", onKey); + out.on("resize", onResize); + if (rest.length) out.write(rest); + }); + sock.on("close", () => (ready ? finish("ended") : !ended && reject(new Error("the session hub closed the connection")))); + sock.on("error", (e) => (ready ? finish("ended") : reject(e))); + }); +} + +function parseFlags(args, spec) { + const o = { _: [] }; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--") { o["--"] = args.slice(i + 1); break; } + const m = /^--([\w-]+)(?:=(.*))?$/.exec(a); + if (m && spec[m[1]] === "bool") o[m[1]] = true; + else if (m && spec[m[1]]) o[m[1]] = m[2] != null ? m[2] : args[++i]; + else o._.push(a); + } + return o; +} + +// ---- live list (nexus sessions / nexus hub) ---- +async function liveList(C) { + const out = process.stdout, inp = process.stdin; + if (!inp.isTTY) { await printList(C); return; } + let sel = 0, list = [], note = "", armedKill = null, timer = null, closed = false, busy = false; + const fetch = async () => { const r = await req({ op: "list" }); list = r.sessions.slice().sort(order).concat((r.saved || []).map((m) => ({ ...m, saved: true, state: "stopped" }))); if (sel >= list.length) sel = Math.max(0, list.length - 1); }; + const draw = () => { + if (closed) return; + const w = out.columns || 100; + const lines = [C.bold(" Nexus sessions") + C.gray(" " + list.filter((s) => !s.saved && s.state !== "done").length + " running"), ""]; + if (!list.length) lines.push(C.gray(" nothing running. Press n to start Nexus here in the background.")); + else lines.push(...renderTable(list, { colors: C, sel, width: w })); + lines.push("", C.gray(" enter attach n new here x stop r restore stopped q quit (Ctrl+] inside a session comes back here)")); + if (note) lines.push(" " + note); + out.write("\x1b[H\x1b[2J" + lines.join("\r\n")); + }; + const enter = () => { out.write("\x1b[?1049h\x1b[?25l"); inp.setRawMode(true); inp.resume(); inp.on("data", onKey); }; + const leave = () => { inp.removeListener("data", onKey); try { inp.setRawMode(false); } catch (_) {} inp.pause(); out.write("\x1b[?25h\x1b[?1049l"); }; + const refresh = async () => { if (busy) return; try { await fetch(); } catch (e) { note = C.red(e.message); } draw(); }; + let done; + const onKey = async (d) => { + const k = d.toString("utf8"); + if (k === "q" || k === "\x1b" || k === "\x03") { closed = true; clearInterval(timer); leave(); return done(); } + if (k === "\x1b[A" || k === "k") sel = Math.max(0, sel - 1); + else if (k === "\x1b[B" || k === "j") sel = Math.min(list.length - 1, sel + 1); + else if (k === "n") { try { const r = await req({ op: "spawn", cwd: process.cwd(), cols: out.columns, rows: out.rows }); note = "started " + r.session.name; } catch (e) { note = C.red(e.message); } } + else if (k === "r") { try { const r = await req({ op: "restore" }); note = r.sessions.length ? "restored " + r.sessions.map((s) => s.name).join(", ") : "nothing to restore"; } catch (e) { note = C.red(e.message); } } + else if (k === "x" && list[sel] && !list[sel].saved) { + const s = list[sel]; + if (armedKill === s.id) { armedKill = null; try { await req({ op: "kill", id: s.id }); note = "stopping " + s.name; } catch (e) { note = C.red(e.message); } } + else { armedKill = s.id; note = C.yellow("press x again to stop " + s.name); } + } + else if ((k === "\r" || k === "\n") && list[sel] && !list[sel].saved && list[sel].state !== "done") { + busy = true; clearInterval(timer); leave(); + try { const r = await attach(list[sel].id); note = r.why === "detached" ? "detached from " + r.name + " (still running)" : r.name + " ended"; } + catch (e) { note = C.red(e.message); } + busy = false; enter(); timer = setInterval(refresh, 700); + } + if (k !== "x") armedKill = null; + await refresh(); + }; + enter(); await refresh(); timer = setInterval(refresh, 700); + return new Promise((r) => { done = r; }); +} +// blocked first (they need you), then working, idle, done +const RANK = { blocked: 0, working: 1, idle: 2, done: 3 }; +const order = (a, b) => (RANK[a.state] - RANK[b.state]) || (a.id - b.id); + +async function printList(C, json) { + const r = await req({ op: "list" }); + if (json) return console.log(JSON.stringify({ sessions: r.sessions, saved: r.saved || [] }, null, 2)); + const list = r.sessions.slice().sort(order).concat((r.saved || []).map((m) => ({ ...m, saved: true, state: "stopped" }))); + if (!list.length) return console.log(C.gray(" no sessions. Start one: nexus bg (or: nexus bg -- claude)")); + console.log(C.gray(" ID NAME STATE AGE FOLDER")); + renderTable(list, { colors: C, width: process.stdout.columns || 100 }).forEach((l) => console.log(l)); + if (list.some((s) => s.saved)) console.log(C.gray("\n stopped sessions came from an earlier hub: nexus hub restore brings them back")); +} + +async function main(sub, args, C) { + C = Object.assign({ bold: IDENT, gray: IDENT, cyan: IDENT, yellow: IDENT, green: IDENT, red: IDENT }, C || {}); + const say = (s) => console.log(" " + s); + if (sub === "bg") { + const f = parseFlags(args, { name: 1, cwd: 1, prompt: 1, attach: "bool" }); + const cmd = f["--"] && f["--"].length ? f["--"] : null; + const nexusArgs = cmd ? [] : f._; + const r = await req({ op: "spawn", name: f.name, cwd: f.cwd || process.cwd(), cmd, nexusArgs, prompt: f.prompt, cols: process.stdout.columns, rows: process.stdout.rows }); + const s = r.session; + if (f.attach) return attach(s.id).then((x) => say(x.why === "detached" ? "detached from " + x.name + " — it keeps running. nexus attach " + x.name : x.name + " ended")); + say("started " + C.bold(s.name) + C.gray(" (id " + s.id + ", " + (s.kind === "nexus" ? "Nexus" : s.cmd.join(" ")) + ")")); + say(C.gray("attach: nexus attach " + s.name + " list: nexus ls Ctrl+] detaches")); + return; + } + if (sub === "ls") return printList(C, args.includes("--json")); + if (sub === "sessions" || sub === "hub" && !args[0]) return liveList(C); + if (sub === "attach") { + const id = args[0]; + await ensureHub(); + const x = await attach(id); + return say(x.why === "detached" ? "detached from " + C.bold(x.name) + " — it keeps running. nexus attach " + x.name : x.name + " ended"); + } + if (sub === "send") { + const [id, ...rest] = args; const f = parseFlags(rest, { "no-enter": "bool" }); + if (!id || !f._.length) throw new Error("usage: nexus send "); + await req({ op: "send", id, text: f._.join(" "), enter: !f["no-enter"] }); + return say("sent to " + id); + } + if (sub === "peek") { + const [id, ...rest] = args; const f = parseFlags(rest, { lines: 1, screen: "bool" }); + const r = await req({ op: "peek", id, lines: Number(f.lines) || 40, screen: !!f.screen }); + console.log(C.gray("── " + r.session.name + " · " + r.session.state + (r.session.title ? " · " + r.session.title : "") + " ──")); + return console.log(r.text); + } + if (sub === "wait") { + const [id, ...rest] = args; const f = parseFlags(rest, { until: 1, timeout: 1, quiet: "bool" }); + const until = f.until || "stopped"; + for (const u of until.split(/[,|]/)) if (!WAIT_STATES.has(u)) throw new Error("--until takes blocked, idle, done, stopped or working"); + const r = await req({ op: "wait", id, until, timeout: Number(f.timeout) || 0 }); + if (!f.quiet) say(r.session.name + " is " + r.session.state + (r.reached ? "" : " (timed out waiting for " + until + ")")); + if (!r.reached) process.exitCode = 2; + return; + } + if (sub === "kill") { const r = await req({ op: "kill", id: args[0] }); return say("stopping " + r.session.name); } + if (sub === "hub") { + const a = args[0]; + if (a === "serve") return require("./server").serve().then(() => new Promise(() => {})); + if (a === "stop") { try { await P.call({ op: "stop" }, { timeout: 2000 }); say("hub stopped (its sessions were ended)"); } catch (_) { say("no hub running"); } return; } + if (a === "restore") { const r = await req({ op: "restore" }); return say(r.sessions.length ? "restored " + r.sessions.map((s) => s.name + (s.error ? " (" + s.error + ")" : "")).join(", ") : "nothing to restore"); } + if (a === "forget") { await req({ op: "forget", id: args[1] }); return say("forgot stopped sessions" + (args[1] ? " named " + args[1] : "")); } + if (a === "status") { try { const r = await P.call({ op: "ping" }, { timeout: 1500 }); say("hub running (pid " + r.pid + ", " + r.sessions + " sessions)"); } catch (_) { say("no hub running"); } return; } + throw new Error("nexus hub: serve | stop | restore | forget | status (no argument opens the live list)"); + } + throw new Error("unknown sessions command " + sub); +} + +// `nexus ` is also a one-shot prompt, so only words that cannot start a prompt are +// always commands. send / wait / peek / kill are commands only when the next word names a +// session that exists (`nexus kill the dev server` stays a prompt); `nexus hub ` always works. +const ALWAYS = new Set(["bg", "attach", "sessions", "hub"]); +const IF_SESSION = new Set(["send", "wait", "peek", "kill"]); +async function claims(sub, args) { + if (!P.supported()) return false; + if (ALWAYS.has(sub)) return true; + if (sub === "ls") return args.length === 0 || (args.length === 1 && args[0] === "--json"); + if (!IF_SESSION.has(sub) || !args[0]) return false; + try { + const r = await P.call({ op: "list" }, { timeout: 800 }); + return r.sessions.some((x) => String(x.id) === args[0] || x.name === args[0]); + } catch (_) { return false; } +} +// `nexus hub ...` routes every command, so nothing is ambiguous there. +async function hubMain(args, C) { + const [a, ...rest] = args; + if (a && a !== "serve" && a !== "stop" && a !== "restore" && a !== "forget" && a !== "status" && (ALWAYS.has(a) || IF_SESSION.has(a) || a === "ls")) return main(a, rest, C); + return main("hub", args, C); +} + +module.exports = { main, hubMain, claims, ALWAYS, IF_SESSION, renderTable, parseFlags, attach, ensureHub, req, fmtAge }; diff --git a/lib/nexus/hub/paths.js b/lib/nexus/hub/paths.js new file mode 100644 index 0000000..e7976b6 --- /dev/null +++ b/lib/nexus/hub/paths.js @@ -0,0 +1,40 @@ +"use strict"; +// hub/paths — where the session hub keeps its socket and state, and how to talk to it. +// Everything lives in ~/.nexus/hub (mode 700, so only this user can reach the socket). +// NEXUS_HUB_DIR overrides it (tests, or a second hub). +const fs = require("fs"), path = require("path"), os = require("os"), net = require("net"); + +function hubDir() { + const d = process.env.NEXUS_HUB_DIR || path.join(os.homedir(), ".nexus", "hub"); + try { fs.mkdirSync(d, { recursive: true, mode: 0o700 }); fs.chmodSync(d, 0o700); } catch (_) {} + return d; +} +const sockPath = (dir) => path.join(dir || hubDir(), "hub.sock"); +const statePath = (dir) => path.join(dir || hubDir(), "sessions.json"); +const supported = () => process.platform === "linux" || process.platform === "darwin"; + +// One JSON line in, JSON lines out. `onLine` gets each reply; return true to keep listening. +function call(msg, opts = {}) { + return new Promise((resolve, reject) => { + const sock = net.connect(opts.sock || sockPath(opts.dir)); + let buf = "", done = false; + const finish = (err, v) => { if (done) return; done = true; try { sock.destroy(); } catch (_) {} err ? reject(err) : resolve(v); }; + const t = opts.timeout ? setTimeout(() => finish(new Error("the session hub did not answer")), opts.timeout) : null; + sock.on("connect", () => sock.write(JSON.stringify(msg) + "\n")); + sock.on("data", (d) => { + buf += d.toString("utf8"); + let i; + while ((i = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, i); buf = buf.slice(i + 1); + let j; try { j = JSON.parse(line); } catch (_) { continue; } + if (opts.onLine && opts.onLine(j)) continue; + if (t) clearTimeout(t); + return finish(null, j); + } + }); + sock.on("error", (e) => { if (t) clearTimeout(t); finish(e); }); + sock.on("close", () => { if (t) clearTimeout(t); finish(new Error("the session hub closed the connection")); }); + }); +} + +module.exports = { hubDir, sockPath, statePath, supported, call }; diff --git a/lib/nexus/hub/report.js b/lib/nexus/hub/report.js new file mode 100644 index 0000000..999bc15 --- /dev/null +++ b/lib/nexus/hub/report.js @@ -0,0 +1,33 @@ +"use strict"; +// hub/report — a Nexus TUI running inside a background session tells the hub its exact +// state (working / blocked on an ask_user or approval / idle), so `nexus ls` and `wait` +// do not have to guess from the screen. Does nothing outside a hub session. +const net = require("net"); +const REFRESH_MS = 4000; // the hub trusts a report for 15s; refresh well inside that + +function startReporter(getState, env = process.env) { + const id = env.NEXUS_HUB_ID, sock = env.NEXUS_HUB_SOCK; + if (!id || !sock) return () => {}; + let conn = null, last = "", lastAt = 0; + const send = (state) => { + try { + if (!conn || conn.destroyed) { + conn = net.connect(sock); + conn.on("error", () => { conn = null; }); + conn.on("data", () => {}); + conn.unref(); + } + conn.write(JSON.stringify({ op: "report", id, state }) + "\n"); + } catch (_) { conn = null; } + }; + const poke = () => { + let st; try { st = getState(); } catch (_) { return; } + const now = Date.now(); + if (st === last && now - lastAt < REFRESH_MS) return; + last = st; lastAt = now; send(st); + }; + const t = setInterval(poke, REFRESH_MS); if (t.unref) t.unref(); + return poke; +} + +module.exports = { startReporter }; diff --git a/lib/nexus/hub/screen.js b/lib/nexus/hub/screen.js new file mode 100644 index 0000000..795a705 --- /dev/null +++ b/lib/nexus/hub/screen.js @@ -0,0 +1,203 @@ +"use strict"; +// ============================================================================ +// hub/screen — a small terminal screen model for background sessions. +// +// A background session's program (Nexus, Claude Code, Codex, a shell) draws with +// cursor moves and erases, so the raw output is not readable text. This model +// applies the common VT/xterm sequences to a cols x rows grid, so the hub can: +// - show what a session looks like right now (`nexus peek`, the sessions tool), +// - spot an agent waiting on a question (hub/status.js reads the bottom lines), +// - repaint a client that attaches mid-session (alt screen + modes + text). +// It is not a full emulator: colors and attributes are dropped, every character is +// one cell wide. Pure, no I/O. +// ============================================================================ + +const SCROLLBACK = 400; // main-screen lines kept above the visible area + +class Screen { + constructor(cols, rows) { + this.cols = Math.max(10, cols | 0 || 80); + this.rows = Math.max(3, rows | 0 || 24); + this.title = ""; + this.cursorHidden = false; + this.modes = new Set(); // private modes currently set (?2004 bracketed paste, ?1000 mouse...) + this._st = 0; this._buf = ""; // parser state: 0 text, 1 ESC, 2 CSI, 3 OSC, 4 ESC-in-OSC, 5 charset (ESC ( x) + this._main = this._blank(); this._alt = null; this.scrollback = []; + this.x = 0; this.y = 0; this._wrap = false; this._saved = { x: 0, y: 0 }; + this.top = 0; this.bot = this.rows - 1; + } + get alt() { return !!this._alt; } + get lines() { return this._alt || this._main; } + _blank() { const a = []; for (let i = 0; i < this.rows; i++) a.push(this._row()); return a; } + _row() { return new Array(this.cols).fill(" "); } + + resize(cols, rows) { + cols = Math.max(10, cols | 0); rows = Math.max(3, rows | 0); + if (cols === this.cols && rows === this.rows) return; + // Drop rows from the top only as far as needed to keep the cursor on screen (the + // dropped main-screen rows go to scrollback); keep the rest from the top down. + const fit = (grid, cut) => { + let g = grid.map((r) => (r.length >= cols ? r.slice(0, cols) : r.concat(new Array(cols - r.length).fill(" ")))); + if (cut > 0 && grid === this._main) this.scrollback.push(...g.slice(0, cut).map((r) => r.join("").replace(/\s+$/, ""))); + g = g.slice(cut, cut + rows); + while (g.length < rows) g.push(new Array(cols).fill(" ")); + return g; + }; + const shift = Math.max(0, this.y - (rows - 1)); + this.cols = cols; this.rows = rows; + this._main = fit(this._main, this._alt ? 0 : shift); if (this._alt) this._alt = fit(this._alt, shift); + this._trimBack(); + this.y = Math.min(rows - 1, this.y - shift); this.x = Math.min(cols - 1, this.x); + this.top = 0; this.bot = rows - 1; this._wrap = false; + } + _trimBack() { if (this.scrollback.length > SCROLLBACK) this.scrollback.splice(0, this.scrollback.length - SCROLLBACK); } + + // ---- output ---- + write(s) { + s = String(s || ""); + for (let i = 0; i < s.length; i++) { + const ch = s[i], c = s.charCodeAt(i); + if (this._st === 0) { + if (c === 0x1b) { this._st = 1; continue; } + if (c < 0x20 || c === 0x7f) { this._ctl(c); continue; } + // a surrogate pair is one character on screen + if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) { this._put(ch + s[++i]); continue; } + this._put(ch); + } else if (this._st === 1) { + this._st = 0; + if (ch === "[") { this._st = 2; this._buf = ""; } + else if (ch === "]") { this._st = 3; this._buf = ""; } + else if (ch === "(" || ch === ")" || ch === "*" || ch === "+" || ch === "#") this._st = 5; + else if (ch === "7") this._saved = { x: this.x, y: this.y }; + else if (ch === "8") { this.x = this._saved.x; this.y = this._saved.y; this._wrap = false; } + else if (ch === "D") this._lf(); + else if (ch === "E") { this.x = 0; this._lf(); } + else if (ch === "M") this._ri(); + else if (ch === "c") this._reset(); + // anything else (=, >, \, P/X/^/_ strings are rare in agent TUIs) is ignored + } else if (this._st === 2) { + if (c >= 0x40 && c <= 0x7e) { this._csi(this._buf, ch); this._st = 0; } + else if (this._buf.length < 64) this._buf += ch; + else this._st = 0; // runaway sequence: drop it + } else if (this._st === 3) { + if (c === 0x07) { this._osc(this._buf); this._st = 0; } + else if (c === 0x1b) this._st = 4; + else if (this._buf.length < 512) this._buf += ch; + } else if (this._st === 4) { this._osc(this._buf); this._st = ch === "\\" ? 0 : 1; if (this._st === 1) i--; } + else if (this._st === 5) this._st = 0; + } + } + _ctl(c) { + if (c === 0x0a || c === 0x0b || c === 0x0c) this._lf(); + else if (c === 0x0d) { this.x = 0; this._wrap = false; } + else if (c === 0x08) { if (this.x > 0) this.x--; this._wrap = false; } + else if (c === 0x09) { this.x = Math.min(this.cols - 1, (Math.floor(this.x / 8) + 1) * 8); } + } + _put(ch) { + if (this._wrap) { this.x = 0; this._lf(); this._wrap = false; } + this.lines[this.y][this.x] = ch; + if (this.x >= this.cols - 1) this._wrap = true; else this.x++; + } + _lf() { + this._wrap = false; + if (this.y === this.bot) this._scrollUp(1); + else if (this.y < this.rows - 1) this.y++; + } + _ri() { if (this.y === this.top) this._scrollDown(1); else if (this.y > 0) this.y--; } + _scrollUp(n) { + const L = this.lines; + for (let k = 0; k < n; k++) { + const gone = L.splice(this.top, 1)[0]; + if (!this._alt && this.top === 0) { this.scrollback.push(gone.join("").replace(/\s+$/, "")); } + L.splice(this.bot, 0, this._row()); + } + this._trimBack(); + } + _scrollDown(n) { const L = this.lines; for (let k = 0; k < n; k++) { L.splice(this.bot, 1); L.splice(this.top, 0, this._row()); } } + _reset() { this._main = this._blank(); this._alt = null; this.x = this.y = 0; this.top = 0; this.bot = this.rows - 1; this.modes.clear(); this.cursorHidden = false; this._wrap = false; } + + _osc(body) { + const m = /^(0|2);([\s\S]*)$/.exec(body); + if (m) this.title = m[2].replace(/[\x00-\x1f]/g, "").slice(0, 200); + } + _csi(params, f) { + const priv = params[0] === "?"; + const p = (priv ? params.slice(1) : params).replace(/[<=>!]/g, "").split(";").map((v) => (v === "" ? NaN : parseInt(v, 10))); + const n = (i, d) => (Number.isFinite(p[i]) && p[i] > 0 ? p[i] : d); + const R = this.rows, C = this.cols; + this._wrap = f === "m" ? this._wrap : false; + switch (f) { + case "A": this.y = Math.max(this.y < this.top ? 0 : this.top, this.y - n(0, 1)); break; + case "B": case "e": this.y = Math.min(this.y > this.bot ? R - 1 : this.bot, this.y + n(0, 1)); break; + case "C": case "a": this.x = Math.min(C - 1, this.x + n(0, 1)); break; + case "D": this.x = Math.max(0, this.x - n(0, 1)); break; + case "E": this.x = 0; this.y = Math.min(R - 1, this.y + n(0, 1)); break; + case "F": this.x = 0; this.y = Math.max(0, this.y - n(0, 1)); break; + case "G": case "`": this.x = Math.min(C - 1, n(0, 1) - 1); break; + case "d": this.y = Math.min(R - 1, n(0, 1) - 1); break; + case "H": case "f": this.y = Math.min(R - 1, n(0, 1) - 1); this.x = Math.min(C - 1, n(1, 1) - 1); break; + case "J": { + const m = Number.isFinite(p[0]) ? p[0] : 0, L = this.lines; + if (m === 0) { this._eraseRow(this.y, this.x, C); for (let r = this.y + 1; r < R; r++) L[r] = this._row(); } + else if (m === 1) { for (let r = 0; r < this.y; r++) L[r] = this._row(); this._eraseRow(this.y, 0, this.x + 1); } + else if (m === 2) { for (let r = 0; r < R; r++) L[r] = this._row(); } + else if (m === 3) this.scrollback = []; + break; + } + case "K": { + const m = Number.isFinite(p[0]) ? p[0] : 0; + if (m === 0) this._eraseRow(this.y, this.x, C); else if (m === 1) this._eraseRow(this.y, 0, this.x + 1); else this._eraseRow(this.y, 0, C); + break; + } + case "X": this._eraseRow(this.y, this.x, Math.min(C, this.x + n(0, 1))); break; + case "P": { const row = this.lines[this.y], k = Math.min(n(0, 1), C - this.x); row.splice(this.x, k); while (row.length < C) row.push(" "); break; } + case "@": { const row = this.lines[this.y], k = Math.min(n(0, 1), C - this.x); row.splice(this.x, 0, ...new Array(k).fill(" ")); row.length = C; break; } + case "L": if (this.y >= this.top && this.y <= this.bot) { const L = this.lines; for (let k = 0; k < n(0, 1); k++) { L.splice(this.bot, 1); L.splice(this.y, 0, this._row()); } } break; + case "M": if (this.y >= this.top && this.y <= this.bot) { const L = this.lines; for (let k = 0; k < n(0, 1); k++) { L.splice(this.y, 1); L.splice(this.bot, 0, this._row()); } } break; + case "S": this._scrollUp(n(0, 1)); break; + case "T": if (!priv) this._scrollDown(n(0, 1)); break; + case "r": { const t = n(0, 1) - 1, b = n(1, R) - 1; if (t < b && b < R) { this.top = t; this.bot = b; } else { this.top = 0; this.bot = R - 1; } this.x = 0; this.y = 0; break; } + case "s": if (!priv) this._saved = { x: this.x, y: this.y }; break; + case "u": if (!priv) { this.x = this._saved.x; this.y = this._saved.y; } break; + case "h": case "l": if (priv) for (const v of p) if (Number.isFinite(v)) this._mode(v, f === "h"); break; + default: break; // m (colors), n (reports), q, t, c ... carry no text + } + } + _eraseRow(r, a, b) { const row = this.lines[r]; for (let i = Math.max(0, a); i < Math.min(this.cols, b); i++) row[i] = " "; } + _mode(v, on) { + if (v === 1049 || v === 1047 || v === 47) { + if (on && !this._alt) { if (v === 1049) this._saved = { x: this.x, y: this.y }; this._alt = this._blank(); } + else if (!on && this._alt) { this._alt = null; if (v === 1049) { this.x = this._saved.x; this.y = this._saved.y; } } + this.top = 0; this.bot = this.rows - 1; + return; + } + if (v === 25) { this.cursorHidden = !on; return; } + if (on) this.modes.add(v); else this.modes.delete(v); + } + + // ---- reading ---- + // Visible screen as text, right-trimmed, trailing blank lines dropped. + text() { const out = this.lines.map((r) => r.join("").replace(/\s+$/, "")); while (out.length && !out[out.length - 1]) out.pop(); return out.join("\n"); } + // The last `n` non-empty-tail lines, including scrollback on the main screen. + tail(n) { + const vis = this.lines.map((r) => r.join("").replace(/\s+$/, "")); + const all = (this._alt ? [] : this.scrollback).concat(vis); + while (all.length && !all[all.length - 1]) all.pop(); + return all.slice(-Math.max(1, n | 0 || 40)).join("\n"); + } + // Bytes that rebuild this screen on a fresh terminal: the alt screen, the modes that + // change input (bracketed paste, mouse), the text, then the cursor. + repaint() { + let s = "\x1b[0m" + (this._alt ? "\x1b[?1049h" : "") + "\x1b[H\x1b[2J"; + for (const m of [1, 1000, 1002, 1003, 1006, 2004]) if (this.modes.has(m)) s += "\x1b[?" + m + "h"; + const L = this.lines; + for (let r = 0; r < this.rows; r++) { const t = L[r].join("").replace(/\s+$/, ""); if (t) s += "\x1b[" + (r + 1) + ";1H" + t; } + s += "\x1b[" + (this.y + 1) + ";" + (this.x + 1) + "H" + (this.cursorHidden ? "\x1b[?25l" : ""); + return s; + } +} + +// The bytes that put a client terminal back to normal after a detach. +const RESET_CLIENT = "\x1b[0m\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?1l\x1b[?25h\x1b[?1049l"; + +module.exports = { Screen, RESET_CLIENT }; diff --git a/lib/nexus/hub/server.js b/lib/nexus/hub/server.js new file mode 100644 index 0000000..03f0dff --- /dev/null +++ b/lib/nexus/hub/server.js @@ -0,0 +1,281 @@ +"use strict"; +// ============================================================================ +// hub/server — the Nexus session hub: a small per-user background process that +// owns agent sessions so they keep running when you close the terminal. +// +// nexus bg start a session (Nexus by default, or any agent: -- claude) +// nexus attach watch and drive it; Ctrl+] detaches, the session keeps going +// nexus ls every session marked working / blocked / idle / done +// nexus send|wait|peek|kill ... the same things, scriptable (and the agent tool) +// +// Each session runs under a real pseudo-terminal. Nexus has no native modules, so the +// terminal comes from the system `script` program (util-linux on Linux, BSD on macOS); +// resizing is `stty` on the session's tty, which makes the kernel send SIGWINCH. +// +// Protocol: one JSON object per line over a unix socket in ~/.nexus/hub (mode 700). +// `attach` turns the connection into a raw byte stream until it closes. +// ============================================================================ +const fs = require("fs"), path = require("path"), net = require("net"), cp = require("child_process"); +const { StringDecoder } = require("string_decoder"); +const { Screen } = require("./screen"); +const { classify, reached } = require("./status"); +const { hubDir, sockPath, statePath } = require("./paths"); + +const RAW_KEEP = 256 * 1024; // raw output kept per session (not replayed; the screen model repaints) +const IDLE_EXIT_MS = 10 * 60 * 1000; // hub exits after this long with no sessions and no clients +const TICK_MS = 400; +const DONE_KEEP_MS = 30 * 60 * 1000; // a finished session stays listed this long + +const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'"; +const nexusEntry = () => (process.pkg ? [process.execPath] : [process.execPath, path.join(__dirname, "..", "..", "..", "darknode.js")]); + +function createHub(opts = {}) { + const dir = opts.dir || hubDir(); + const sock = sockPath(dir), stateFile = statePath(dir); + const notify = opts.notify || (() => {}); + const sessions = new Map(); // id -> session + const waiters = new Set(); // { id, until, resolve } + let seq = 0, server = null, clients = 0, lastBusy = Date.now(), ticker = null; + let saved = []; // sessions from a previous hub that are not running (restorable) + try { const j = JSON.parse(fs.readFileSync(stateFile, "utf8")); saved = Array.isArray(j.sessions) ? j.sessions : []; seq = j.seq | 0; } catch (_) {} + + const persist = () => { + const live = [...sessions.values()].filter((s) => !s.exited).map(meta); + const keep = saved.filter((x) => !live.some((l) => l.id === x.id)); + try { fs.writeFileSync(stateFile, JSON.stringify({ seq, sessions: live.concat(keep) }, null, 2), { mode: 0o600 }); } catch (_) {} + }; + const meta = (s) => ({ id: s.id, name: s.name, cwd: s.cwd, kind: s.kind, cmd: s.cmd, created: s.created }); + const summary = (s) => ({ ...meta(s), state: s.state, since: s.since, title: s.screen.title, attached: s.clients.size, pid: s.proc && s.proc.pid, exitCode: s.exitCode == null ? null : s.exitCode }); + + function find(key) { + if (key == null || key === "") { const live = [...sessions.values()].filter((s) => !s.exited); return live.length === 1 ? live[0] : null; } + const k = String(key); + if (sessions.has(k)) return sessions.get(k); + const all = [...sessions.values()]; + return all.find((s) => s.name === k) || (all.filter((s) => s.name.startsWith(k)).length === 1 ? all.find((s) => s.name.startsWith(k)) : null); + } + function uniqueName(base) { + base = String(base || "session").replace(/[^\w.-]+/g, "-").slice(0, 40) || "session"; + const taken = new Set([...sessions.values()].filter((s) => !s.exited).map((s) => s.name)); + if (!taken.has(base)) return base; + for (let i = 2; ; i++) if (!taken.has(base + "-" + i)) return base + "-" + i; + } + + function spawnSession(o) { + const cwd = path.resolve(o.cwd || process.cwd()); + if (!fs.existsSync(cwd)) throw new Error("no such folder: " + cwd); + const cols = Math.max(20, o.cols | 0 || 120), rows = Math.max(5, o.rows | 0 || 34); + const kind = o.cmd && o.cmd.length ? "cmd" : "nexus"; + const argv = kind === "nexus" ? nexusEntry().concat(["nexus"], o.nexusArgs || []) : o.cmd.map(String); + const id = String(o.id || ++seq); + const name = o.name ? uniqueName(o.name) : uniqueName(kind === "nexus" ? path.basename(cwd) : path.basename(String(argv[0]))); + const ttyFile = path.join(dir, "s" + id + ".tty"); + try { fs.unlinkSync(ttyFile); } catch (_) {} + const inner = "tty > " + q(ttyFile) + " 2>/dev/null; stty rows " + rows + " cols " + cols + " 2>/dev/null; exec " + argv.map(q).join(" "); + const env = Object.assign({}, process.env, o.env || {}, { TERM: process.env.TERM && process.env.TERM !== "dumb" ? process.env.TERM : "xterm-256color", NEXUS_HUB_ID: id, NEXUS_HUB_SOCK: sock, NEXUS_HUB_NAME: name }); + const args = process.platform === "darwin" ? ["-q", "/dev/null", "/bin/sh", "-c", inner] : ["-qfec", inner, "/dev/null"]; + const proc = (opts.spawn || cp.spawn)("script", args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: true }); + const s = { + id, name, cwd, kind, cmd: kind === "cmd" ? o.cmd.map(String) : null, nexusArgs: o.nexusArgs || [], created: Date.now(), + proc, screen: new Screen(cols, rows), raw: [], rawLen: 0, dec: new StringDecoder("utf8"), + lastOutputAt: Date.now(), report: null, exited: false, exitCode: null, clients: new Set(), ttyFile, tty: "", + state: "working", since: Date.now(), prompt: o.prompt ? String(o.prompt) : "", promptSent: false, + }; + const onOut = (d) => { + s.lastOutputAt = Date.now(); + s.raw.push(d); s.rawLen += d.length; + while (s.rawLen > RAW_KEEP && s.raw.length > 1) s.rawLen -= s.raw.shift().length; + s.screen.write(s.dec.write(d)); + for (const c of s.clients) { try { c.write(d); } catch (_) {} } + }; + proc.stdout.on("data", onOut); proc.stderr.on("data", onOut); + proc.on("error", (e) => { onOut(Buffer.from("\r\n[nexus hub] could not start the session: " + e.message + "\r\n")); end(s, 127); }); + proc.on("exit", (code) => end(s, code)); + proc.stdin.on("error", () => {}); + sessions.set(id, s); + saved = saved.filter((x) => x.id !== id); + persist(); bump(); + return s; + } + function end(s, code) { + if (s.exited) return; + s.exited = true; s.exitCode = code == null ? null : code; + try { fs.unlinkSync(s.ttyFile); } catch (_) {} + for (const c of s.clients) { try { c.end("\r\n[nexus hub] session " + s.name + " ended" + (code ? " (exit " + code + ")" : "") + "\r\n"); } catch (_) {} } + s.clients.clear(); + persist(); tick(); + } + function tty(s) { + if (s.tty) return s.tty; + try { s.tty = fs.readFileSync(s.ttyFile, "utf8").trim(); } catch (_) {} + return /^\/dev\//.test(s.tty) ? s.tty : ""; + } + function resize(s, cols, rows) { + cols = Math.max(20, Math.min(1000, cols | 0)); rows = Math.max(5, Math.min(500, rows | 0)); + s.screen.resize(cols, rows); + const t = tty(s); if (!t) return; + (opts.spawnSync || cp.spawnSync)("stty", [process.platform === "darwin" ? "-f" : "-F", t, "rows", String(rows), "cols", String(cols)], { stdio: "ignore" }); + } + function input(s, data) { if (!s.exited) try { s.proc.stdin.write(data); } catch (_) {} } + // Type a prompt the way a person would: pasted as one block when the program asked for + // bracketed paste (so a newline inside it does not submit early), then Enter. + function sendText(s, text, enter = true) { + const t = String(text == null ? "" : text); + if (t) input(s, s.screen.modes.has(2004) ? "\x1b[200~" + t + "\x1b[201~" : t.replace(/\r?\n/g, "\r")); + if (enter) setTimeout(() => input(s, "\r"), t ? 60 : 0); + } + + // Linux: is the session's program (a shell) running a job in the foreground? The tty's + // foreground process group moves off the shell while `sleep 30` or `npm test` runs, so a + // quiet command still counts as working. Agents keep their tools in their own group. + function fgJob(s) { + if (process.platform !== "linux" || s.exited || !s.proc || !s.proc.pid) return false; + try { + if (!s.childPid) s.childPid = Number(fs.readFileSync("/proc/" + s.proc.pid + "/task/" + s.proc.pid + "/children", "utf8").trim().split(/\s+/)[0]) || 0; + if (!s.childPid) return false; + const st = fs.readFileSync("/proc/" + s.childPid + "/stat", "utf8"); + const tpgid = Number(st.slice(st.lastIndexOf(")") + 2).split(" ")[5]); + return tpgid > 0 && tpgid !== s.childPid; + } catch (_) { return false; } + } + + function tick() { + const now = Date.now(); + for (const [k, s] of sessions) if (s.exited && now - s.since > DONE_KEEP_MS && !s.clients.size) sessions.delete(k); + for (const s of sessions.values()) { + const st = classify({ exited: s.exited, lastOutputAt: s.lastOutputAt, report: s.report, fgJob: fgJob(s), tail: s.exited ? "" : s.screen.text() }, now); + if (st !== s.state) { + const prev = s.state; s.state = st; s.since = now; + if (st === "blocked" && !s.clients.size) notify("Nexus: " + s.name + " needs you", (s.screen.title || s.name) + " is waiting for an answer. Run: nexus attach " + s.name); + if (st === "done" && prev !== "done" && !s.clients.size) notify("Nexus: " + s.name + " finished", s.exitCode ? "exited with code " + s.exitCode : "the session ended"); + } + // A prompt given at spawn is typed once the program first settles. + if (s.prompt && !s.promptSent && !s.exited && st !== "working" && now - s.created > 800) { s.promptSent = true; sendText(s, s.prompt); } + } + for (const w of [...waiters]) { + const s = sessions.get(w.id); + if (!s) { waiters.delete(w); w.resolve({ ok: false, error: "no such session" }); continue; } + // a just-sent prompt has not been read yet: a wait right after `send` must not see the old idle + if (now < w.notBefore && s.state !== "done") continue; + if (reached(s.state, w.until)) { waiters.delete(w); w.resolve({ ok: true, reached: true, session: summary(s), tail: s.screen.tail(w.lines || 30) }); } + else if (w.deadline && now > w.deadline) { waiters.delete(w); w.resolve({ ok: true, reached: false, session: summary(s), tail: s.screen.tail(w.lines || 30) }); } + } + if ([...sessions.values()].some((s) => !s.exited) || clients > 0 || waiters.size) lastBusy = now; + else if (!opts.stayUp && now - lastBusy > IDLE_EXIT_MS) stop(); + } + const bump = () => { lastBusy = Date.now(); }; + + function restore() { + const out = []; + for (const m of saved.slice()) { + if (sessions.has(m.id) && !sessions.get(m.id).exited) continue; + try { + const s = spawnSession(m.kind === "nexus" ? { id: m.id, name: m.name, cwd: m.cwd, nexusArgs: ["--resume"] } : { id: m.id, name: m.name, cwd: m.cwd, cmd: m.cmd }); + out.push(summary(s)); + } catch (e) { out.push({ id: m.id, name: m.name, error: e.message }); } + } + return out; + } + + // ---- protocol ---- + function handle(c, msg, reply) { + const op = msg && msg.op; + if (op === "ping") return reply({ ok: true, pid: process.pid, sessions: sessions.size }); + if (op === "list") return reply({ ok: true, sessions: [...sessions.values()].map(summary), saved: saved.filter((m) => !sessions.has(m.id) || sessions.get(m.id).exited) }); + if (op === "spawn") { + try { const s = spawnSession(msg); return reply({ ok: true, session: summary(s) }); } + catch (e) { return reply({ ok: false, error: e.message }); } + } + if (op === "restore") return reply({ ok: true, sessions: restore() }); + if (op === "forget") { saved = msg.id ? saved.filter((m) => m.id !== String(msg.id) && m.name !== msg.id) : []; for (const [k, s] of sessions) if (s.exited) sessions.delete(k); persist(); return reply({ ok: true }); } + if (op === "stop") { reply({ ok: true }); return setTimeout(stop, 50); } + const s = find(msg.id); + if (op === "report") { // from a Nexus TUI running inside a session + const r = sessions.get(String(msg.id)); + if (r && ["working", "blocked", "idle"].includes(msg.state)) { r.report = { state: msg.state, at: Date.now() }; tick(); } + return reply({ ok: true }); + } + if (!s) return reply({ ok: false, error: msg.id ? "no session named " + msg.id + " (see: nexus ls)" : "more than one session is running: name one (see: nexus ls)" }); + if (op === "send") { if (s.exited) return reply({ ok: false, error: s.name + " has ended" }); sendText(s, msg.text, msg.enter !== false); return reply({ ok: true, session: summary(s) }); } + if (op === "keys") { input(s, Buffer.from(String(msg.data || ""), "base64")); return reply({ ok: true }); } + if (op === "peek") return reply({ ok: true, session: summary(s), text: msg.screen ? s.screen.text() : s.screen.tail(Math.min(400, msg.lines | 0 || 40)) }); + if (op === "resize") { resize(s, msg.cols, msg.rows); return reply({ ok: true }); } + if (op === "kill") { + if (!s.exited) { try { process.kill(-s.proc.pid, "SIGTERM"); } catch (_) { try { s.proc.kill("SIGTERM"); } catch (_) {} } setTimeout(() => { if (!s.exited) { try { process.kill(-s.proc.pid, "SIGKILL"); } catch (_) {} } }, 3000); } + return reply({ ok: true, session: summary(s) }); + } + if (op === "wait") { + const secs = Number(msg.timeout); const now = Date.now(); + waiters.add({ id: s.id, until: msg.until || "stopped", lines: msg.lines, notBefore: now + (msg.settle === false ? 0 : 1200), deadline: Number.isFinite(secs) && secs > 0 ? now + secs * 1000 : 0, resolve: reply, _c: c }); + return tick(); + } + if (op === "attach") { + if (s.exited) return reply({ ok: false, error: s.name + " has ended" }); + reply({ ok: true, session: summary(s) }); + c._attached = s; s.clients.add(c); + if (msg.cols && msg.rows) resize(s, msg.cols, msg.rows); + try { c.write(s.screen.repaint()); } catch (_) {} + // Nudge the program to redraw itself at the client's size: a size change, then back. + if (msg.cols && msg.rows) setTimeout(() => { resize(s, msg.cols, Math.max(5, msg.rows - 1)); setTimeout(() => resize(s, msg.cols, msg.rows), 60); }, 30); + return; + } + return reply({ ok: false, error: "unknown op " + op }); + } + + function onConn(c) { + clients++; bump(); + let buf = ""; + c.on("data", (d) => { + if (c._attached) { input(c._attached, d); return; } + buf += d.toString("utf8"); + if (buf.length > 1024 * 1024) return c.destroy(); + let i; + while (!c._attached && (i = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, i); buf = buf.slice(i + 1); + let msg; try { msg = JSON.parse(line); } catch (_) { continue; } + handle(c, msg, (obj) => { try { c.write(JSON.stringify(obj) + "\n"); } catch (_) {} }); + if (c._attached && buf) { input(c._attached, Buffer.from(buf, "utf8")); buf = ""; } + } + }); + const gone = () => { if (c._gone) return; c._gone = true; clients--; if (c._attached) c._attached.clients.delete(c); for (const w of waiters) if (w._c === c) waiters.delete(w); }; + c.on("close", gone); c.on("error", gone); + } + + function listen() { + return new Promise((resolve, reject) => { + server = net.createServer(onConn); + const go = () => server.listen(sock, () => { try { fs.chmodSync(sock, 0o600); } catch (_) {} ticker = setInterval(tick, TICK_MS); resolve(api); }); + server.on("error", (e) => { + if (e.code !== "EADDRINUSE") return reject(e); + // a socket file is there: another hub is alive, or it is stale from a crash + const probe = net.connect(sock); + probe.on("connect", () => { probe.destroy(); reject(Object.assign(new Error("a session hub is already running"), { code: "HUB_RUNNING" })); }); + probe.on("error", () => { try { fs.unlinkSync(sock); } catch (_) {} server.removeAllListeners("error"); server.on("error", reject); go(); }); + }); + go(); + }); + } + function stop() { + if (ticker) clearInterval(ticker); ticker = null; + for (const s of sessions.values()) if (!s.exited) { try { process.kill(-s.proc.pid, "SIGTERM"); } catch (_) {} } + persist(); + try { server && server.close(); } catch (_) {} + try { fs.unlinkSync(sock); } catch (_) {} + if (opts.onStop) opts.onStop(); + } + const api = { listen, stop, tick, sessions, spawnSession, find, sock, dir, _handle: handle }; + return api; +} + +// Entry point for `nexus hub serve` (started in the background by the client). +async function serve() { + let osNotify = () => {}; + try { osNotify = require("../os-notify").osNotify; } catch (_) {} + const hub = createHub({ notify: (t, b) => { try { osNotify(t, b); } catch (_) {} }, onStop: () => process.exit(0) }); + try { await hub.listen(); } + catch (e) { if (e.code === "HUB_RUNNING") process.exit(0); throw e; } + process.on("SIGTERM", () => hub.stop()); + process.on("SIGHUP", () => {}); // the terminal that started us closing must not end the sessions +} + +module.exports = { createHub, serve }; diff --git a/lib/nexus/hub/status.js b/lib/nexus/hub/status.js new file mode 100644 index 0000000..728df4e --- /dev/null +++ b/lib/nexus/hub/status.js @@ -0,0 +1,60 @@ +"use strict"; +// ============================================================================ +// hub/status — is a background session working, blocked or idle? +// +// working the program is producing output (or Nexus says it is mid-turn) +// blocked it stopped and is waiting for a person: a permission prompt, a +// yes/no question, an ask_user popup +// idle it is waiting for the next prompt +// done the process exited +// +// Nexus reports its own state exactly (hub/report.js), so a fresh report wins. +// Other agents (Claude Code, Codex, OpenCode, Gemini, a shell) are read from the +// screen: recent output means working; otherwise the bottom of the screen is +// checked for a question. Pure: the caller passes the clock and the screen text. +// ============================================================================ + +const QUIET_MS = 1500; // no output for this long = the program has stopped +const REPORT_TTL = 15000; // a Nexus report is trusted this long without a refresh + +// Prompts that mean "a person has to answer before I continue". A menu with a highlighted +// first choice (the agent permission dialogs) counts anywhere in the last few lines; a +// one-line question only when it is the last line (where the cursor waits), so a question that was +// already answered and has output under it does not keep the session marked blocked. +const MENU = [ + /^\s*[│|]?\s*[❯>›]\s*1[.)]\s*(yes|allow|approve|proceed|run)/im, +]; +const QUESTION = [ + /\bdo you want to (proceed|continue|make this edit|create|run|allow|apply|overwrite)/i, + /\b(allow|approve|permit|trust)\b[^\n]{0,80}\?/i, + /\((y\/n)\)|\[(y\/n|y\/N|Y\/n)\]|\(yes\/no\)/, + /\bpress enter to (continue|confirm)/i, + /\bwaiting for (your )?(input|approval|confirmation|answer)/i, +]; + +function asking(screenTail) { + const lines = String(screenTail || "").split("\n").filter((l) => l.trim()); + const menu = lines.slice(-8).join("\n"), last = lines.slice(-1).join("\n"); + return MENU.some((re) => re.test(menu)) || QUESTION.some((re) => re.test(last)); +} + +// s: { exited, lastOutputAt, report: { state, at } | null, fgJob, tail } +function classify(s, now) { + if (!s) return "idle"; + if (s.exited) return "done"; + const r = s.report; + if (r && (r.state === "working" || r.state === "blocked" || r.state === "idle") && now - r.at < REPORT_TTL) return r.state; + if (s.fgJob) return "working"; // a shell is running a command in the foreground (quiet or not) + if (s.lastOutputAt && now - s.lastOutputAt < QUIET_MS) return "working"; + return asking(s.tail) ? "blocked" : "idle"; +} + +// What `wait --until` accepts. "stopped" = anything but working (the usual thing an +// agent wants: wait until the other one needs me or is finished). +const WAIT_STATES = new Set(["blocked", "idle", "done", "stopped", "working"]); +function reached(state, until) { + const want = Array.isArray(until) ? until : String(until || "stopped").split(/[,|]/).map((x) => x.trim()).filter(Boolean); + return want.some((w) => w === state || (w === "stopped" && state !== "working")); +} + +module.exports = { classify, asking, reached, WAIT_STATES, QUIET_MS, REPORT_TTL }; diff --git a/lib/nexus/hub/tool.js b/lib/nexus/hub/tool.js new file mode 100644 index 0000000..7936ed8 --- /dev/null +++ b/lib/nexus/hub/tool.js @@ -0,0 +1,78 @@ +"use strict"; +// hub/tool — the `sessions` agent tool: lets an agent run other agents in background +// sessions, hand them a task, wait until they finish or need a person, and read their +// screen. The same tool is offered to Nexus's own loop (darknode.js deviceTool) and to +// external engines through the nexus MCP bridge (ask-mcp.js). Returns { error } instead +// of throwing. +const path = require("path"), fs = require("fs"); +const P = require("./paths"); + +const SCHEMA = { + description: "Run other coding agents in background sessions (the Nexus session hub) and coordinate with them. " + + "action=spawn starts one (Nexus by default, or agent: claude|codex|opencode|gemini, or a shell command) in a folder inside this project, optionally with a first prompt; " + + "send types a prompt into a session; wait blocks until a session is idle, blocked (waiting for a person) or done; " + + "peek reads its screen; list shows every session with working/blocked/idle/done; kill stops one. " + + "A person can watch or take over any session with `nexus attach `.", + properties: { + action: { type: "string", enum: ["list", "spawn", "send", "wait", "peek", "kill"], description: "what to do" }, + id: { type: "string", description: "session id or name (send, wait, peek, kill)" }, + name: { type: "string", description: "spawn: a short name for the new session" }, + agent: { type: "string", description: "spawn: nexus (default), claude, codex, opencode or gemini" }, + command: { type: "string", description: "spawn: run this shell command instead of an agent" }, + cwd: { type: "string", description: "spawn: folder inside this project (default: the project root)" }, + prompt: { type: "string", description: "spawn: first prompt, typed once the agent is ready" }, + text: { type: "string", description: "send: the prompt or reply to type (Enter is pressed after it)" }, + until: { type: "string", description: "wait: idle, blocked, done, or stopped (= anything but working; the default)" }, + timeout_s: { type: "number", description: "wait: give up after this many seconds (default 600, max 3600)" }, + lines: { type: "number", description: "peek/wait: how many screen lines to return (default 40)" }, + }, + required: ["action"], +}; + +const AGENTS = new Set(["nexus", "claude", "codex", "opencode", "gemini"]); +const slim = (s) => ({ id: s.id, name: s.name, state: s.state, kind: s.kind === "nexus" ? "nexus" : (s.cmd || []).join(" "), cwd: s.cwd, title: s.title || "", attached: s.attached || 0, exitCode: s.exitCode }); + +async function sessionsTool(a, cwd, deps = {}) { + a = a || {}; + try { + if (!P.supported()) return { error: "background sessions need Linux or macOS" }; + const ensure = deps.ensureHub || require("./cli").ensureHub, call = deps.call || P.call; + const action = String(a.action || "list").toLowerCase(); + const root = path.resolve(cwd || process.cwd()); + await ensure(); + const ask = async (m, o) => { const r = await call(m, o); if (!r.ok) throw new Error(r.error || "the hub refused"); return r; }; + if (action === "list") { const r = await ask({ op: "list" }); return { sessions: r.sessions.map(slim) }; } + if (action === "spawn") { + const dir = path.resolve(root, a.cwd || "."); + if (dir !== root && !dir.startsWith(root + path.sep)) return { error: "spawn: cwd must be inside the project (" + root + ")" }; + if (!fs.existsSync(dir)) return { error: "spawn: no such folder " + dir }; + const agent = String(a.agent || "nexus").toLowerCase(); + if (!a.command && !AGENTS.has(agent)) return { error: "spawn: agent must be nexus, claude, codex, opencode or gemini (or give a command)" }; + const cmd = a.command ? ["/bin/sh", "-c", String(a.command)] : agent === "nexus" ? null : [agent]; + const r = await ask({ op: "spawn", name: a.name, cwd: dir, cmd, prompt: a.prompt, cols: 120, rows: 40 }); + return { session: slim(r.session), hint: "watch it with: nexus attach " + r.session.name }; + } + if (!a.id) return { error: action + " needs id (a session id or name; action=list shows them)" }; + if (action === "send") { + if (a.text == null || String(a.text) === "") return { error: "send needs text" }; + const r = await ask({ op: "send", id: String(a.id), text: String(a.text) }); + return { sent: true, session: slim(r.session) }; + } + if (action === "wait") { + const t = Math.min(3600, Math.max(1, Number(a.timeout_s) || 600)); + const r = await ask({ op: "wait", id: String(a.id), until: a.until || "stopped", timeout: t, lines: Number(a.lines) || 40 }, { timeout: (t + 10) * 1000 }); + return { reached: r.reached, state: r.session.state, session: slim(r.session), screen: r.tail }; + } + if (action === "peek") { const r = await ask({ op: "peek", id: String(a.id), lines: Number(a.lines) || 40 }); return { session: slim(r.session), screen: r.text }; } + if (action === "kill") { + if (process.env.NEXUS_HUB_ID && (String(a.id) === process.env.NEXUS_HUB_ID || String(a.id) === process.env.NEXUS_HUB_NAME)) return { error: "kill: that is this session" }; + const r = await ask({ op: "kill", id: String(a.id) }); return { stopping: slim(r.session) }; + } + return { error: "unknown action " + action + " (list, spawn, send, wait, peek, kill)" }; + } catch (e) { return { error: (e && e.message) || String(e) }; } +} + +// The shell command a call will run, for the danger gate and policy (tool-gates execCommand). +const gateCommand = (a) => { a = a || {}; const act = String(a.action || "").toLowerCase(); return act === "spawn" ? (a.command || a.agent || "nexus") : act === "send" ? a.text : ""; }; + +module.exports = { sessionsTool, SCHEMA, gateCommand, slim }; diff --git a/lib/nexus/native-tools.js b/lib/nexus/native-tools.js index 0c70b20..be51aa5 100644 --- a/lib/nexus/native-tools.js +++ b/lib/nexus/native-tools.js @@ -61,6 +61,7 @@ const TOOL_SCHEMAS = { remember: { description: "Save a durable project convention or preference to NEXUS.md.", properties: { text: S("the fact to remember") }, required: ["text"] }, discover: { description: "Search available tools by keyword.", properties: { query: S("keywords") }, required: ["query"] }, todo_write: { description: "Record or update the task todo list.", properties: { todos: { type: "array", description: "todo items", items: { type: "object" } } }, required: ["todos"] }, + sessions: require("./hub/tool").SCHEMA, spawn_agents: { description: "Run several independent sub-tasks in parallel via sub-agents.", properties: { tasks: { type: "array", description: "independent task descriptions", items: { type: "string" } } }, required: ["tasks"] }, batch: { description: "Run SEVERAL read-only lookups in ONE call and get all results back together: read files, grep patterns, glob/list files. Use this instead of many separate read_file/search/find/list_dir calls to save round-trips and tokens when investigating. Read-only: no writes, no shell. Up to 20 ops; output is size-capped.", properties: { ops: { type: "array", description: "list of read-only ops, in order", items: { type: "object", properties: { op: S("'read' (a file), 'search' (grep a pattern), 'glob' (find files by name/glob), or 'list' (list a directory)"), path: S("file or directory path (read/list, or search/glob root)"), pattern: S("regex or text to grep (op:search)"), glob: S("glob or name fragment to match (op:glob); with op:search, only search files matching it"), literal: { type: "boolean", description: "op:search: treat pattern as plain text" }, case_sensitive: { type: "boolean", description: "op:search: match case exactly" }, start: { type: "number", description: "first line to return, 1-based (op:read)" }, end: { type: "number", description: "last line to return (op:read)" } }, required: ["op"] } } }, required: ["ops"] }, browser_status: { description: "Check whether the user's own browser is reachable for agentic control (started with a remote-debugging port). If not, returns the exact command to start one that keeps their profile/logins.", properties: { port: S("debug port (default 9222)") }, required: [] }, diff --git a/lib/nexus/tool-gates.js b/lib/nexus/tool-gates.js index 5d7f72d..6c4d508 100644 --- a/lib/nexus/tool-gates.js +++ b/lib/nexus/tool-gates.js @@ -19,6 +19,7 @@ const EXEC_TOOLS = new Set([ "shrink", "minimize_change", "ddmin", "explain_break", "explainbreak", "blame_turn", "lint_format", "lint", "format", "fmt", + "sessions", // spawn runs an agent or a shell command; send types into one ]); // Tools blocked while plan mode is on: everything mutating, executing or egressing. @@ -39,7 +40,7 @@ const isExecTool = (name) => EXEC_TOOLS.has(name); const TEST_FIRST = new Set(["bisect", "regression_bisect", "shrink", "minimize_change", "ddmin", "explain_break", "explainbreak", "blame_turn"]); // write_stdin sends `input` (else `text`) whatever `command` says, and the tools pick by TRUTHINESS // (`a.test || a.command`), so {test: false, command: "rm -rf ~"} must show the gate the rm, not "false". -const execCommand = (name, a) => { a = a || {}; const c = name === "write_stdin" ? (a.input != null ? a.input : a.text) : TEST_FIRST.has(name) ? (a.test || a.command) : (a.command || a.test); return c == null || c === "" ? undefined : String(c); }; +const execCommand = (name, a) => { a = a || {}; const c = name === "sessions" ? require("./hub/tool").gateCommand(a) : name === "write_stdin" ? (a.input != null ? a.input : a.text) : TEST_FIRST.has(name) ? (a.test || a.command) : (a.command || a.test); return c == null || c === "" ? undefined : String(c); }; const isPlanBlocked = (name) => PLAN_BLOCKED.has(name) || String(name || "").startsWith("mcp__"); module.exports = { EXEC_TOOLS, PLAN_BLOCKED, isExecTool, isPlanBlocked, execCommand }; diff --git a/package.json b/package.json index 3c480d9..28d57f5 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "scripts": { "start": "node darknode.js", "build": "pkg . --out-path dist", - "test": "node test/run.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", + "test": "node test/run.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" }, diff --git a/test/hub.test.js b/test/hub.test.js new file mode 100644 index 0000000..0d71d33 --- /dev/null +++ b/test/hub.test.js @@ -0,0 +1,137 @@ +"use strict"; +// Background sessions suite (lib/nexus/hub): the screen model, working/blocked/idle +// detection, the command guard that keeps `nexus ` working, the sessions tool's +// safety checks, and a real hub driving a real shell under a pseudo-terminal. +const fs = require("fs"), os = require("os"), path = require("path"); +const DIR = fs.mkdtempSync(path.join(os.tmpdir(), "nxhub-test-")); +process.env.NEXUS_HUB_DIR = DIR; // never the real ~/.nexus/hub +const { Screen } = require("../lib/nexus/hub/screen"); +const St = require("../lib/nexus/hub/status"); +const Cli = require("../lib/nexus/hub/cli"); +const Tool = require("../lib/nexus/hub/tool"); +const P = require("../lib/nexus/hub/paths"); +const { createHub } = require("../lib/nexus/hub/server"); +const Gates = require("../lib/nexus/tool-gates"); + +let pass = 0, fail = 0; +const ok = (name, cond) => { if (cond) pass++; else { fail++; console.log(" \x1b[31mFAIL\x1b[0m " + name); } }; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +(async () => { + // ---- screen model ---- + const s = new Screen(20, 4); + s.write("hello\r\nworld\x1b[1;1HJ"); + ok("screen: cursor moves overwrite text", s.text() === "Jello\nworld"); + s.write("\x1b]0;Fix login\x07\x1b[?2004h"); + ok("screen: OSC title is captured", s.title === "Fix login"); + ok("screen: private modes are tracked", s.modes.has(2004)); + s.write("\x1b[?1049h\x1b[2J\x1b[2;3Hin alt"); + ok("screen: alternate screen is separate", s.alt && s.text() === "\n in alt"); + s.write("\x1b[?1049l"); + ok("screen: leaving alt restores the main screen", !s.alt && s.text().startsWith("Jello")); + for (let i = 0; i < 6; i++) s.write("\r\nline" + i); + ok("screen: scrolled lines go to scrollback", s.tail(6).split("\n").includes("line0") && s.tail(2) === "line4\nline5"); + s.write("\x1b[2K\x1b[1G"); + ok("screen: erase line", !s.text().includes("line5")); + const rp = new Screen(30, 5); rp.write("\x1b[?1049h\x1b[?2004habc"); const bytes = rp.repaint(); + ok("screen: repaint rebuilds alt screen, modes and text", bytes.includes("\x1b[?1049h") && bytes.includes("\x1b[?2004h") && bytes.includes("abc")); + const big = new Screen(10, 3); big.write("\x1b[" + "9".repeat(200) + "m" + "x"); + ok("screen: a runaway escape sequence does not swallow later text forever", typeof big.text() === "string"); + big.resize(5, 2); ok("screen: resize clamps", big.cols === 10 || big.cols === 5); + const top = new Screen(120, 34); top.write("Do you want to proceed? (y/n) "); top.resize(110, 20); + ok("screen: shrinking keeps text near the cursor (a prompt on row 1 survives)", top.text() === "Do you want to proceed? (y/n)"); + const tall = new Screen(20, 10); for (let i = 0; i < 10; i++) tall.write((i ? "\r\n" : "") + "r" + i); tall.resize(20, 4); + ok("screen: shrinking a full screen keeps the cursor's rows", tall.text() === "r6\nr7\nr8\nr9" && tall.y === 3); + + // ---- status ---- + const now = 1e6; + ok("status: recent output is working", St.classify({ lastOutputAt: now - 200 }, now) === "working"); + ok("status: quiet with a shell prompt is idle", St.classify({ lastOutputAt: now - 5000, tail: "bash-5.2$ " }, now) === "idle"); + ok("status: a y/n question on the last line is blocked", St.classify({ lastOutputAt: now - 5000, tail: "Do you want to proceed? (y/n) " }, now) === "blocked"); + ok("status: an answered question is not blocked", St.classify({ lastOutputAt: now - 5000, tail: "Do you want to proceed? (y/n) y\ngot y" }, now) === "idle"); + ok("status: an agent permission menu is blocked", St.asking("│ Do you want to proceed? │\n│ ❯ 1. Yes │\n│ 2. No │\n╰────╯")); + ok("status: a foreground job is working even when quiet", St.classify({ lastOutputAt: now - 9000, fgJob: true, tail: "$ sleep 30" }, now) === "working"); + ok("status: a fresh Nexus report wins", St.classify({ lastOutputAt: now - 100, report: { state: "blocked", at: now - 1000 } }, now) === "blocked"); + ok("status: a stale report is ignored", St.classify({ lastOutputAt: now - 9000, report: { state: "working", at: now - 60000 }, tail: "" }, now) === "idle"); + ok("status: exited is done", St.classify({ exited: true }, now) === "done"); + ok("status: stopped means anything but working", St.reached("blocked", "stopped") && St.reached("done", "stopped") && !St.reached("working", "stopped")); + ok("status: lists of states", St.reached("idle", "blocked,idle") && !St.reached("working", "blocked|idle")); + + // ---- cli helpers ---- + const f = Cli.parseFlags(["--name", "api", "--attach", "x", "--", "claude", "--resume"], { name: 1, attach: "bool" }); + ok("cli: flags and the -- command", f.name === "api" && f.attach === true && f._[0] === "x" && f["--"].join(" ") === "claude --resume"); + const rows = Cli.renderTable([{ id: "1", name: "web", state: "blocked", since: 0, cwd: "/x", title: "Fix" }, { id: "2", name: "old", saved: true, cwd: "/y" }], { now: 65000, width: 90 }); + ok("cli: table shows state, age and title", /web\s+blocked\s+1m\s+\/x\s+Fix/.test(rows[0]) && /old\s+stopped/.test(rows[1])); + ok("cli: ages", Cli.fmtAge(5000) === "5s" && Cli.fmtAge(3 * 3600e3 + 120e3) === "3h02"); + // with no hub running, prompt-like words stay prompts + ok("guard: bg / attach / sessions / hub are always commands", (await Cli.claims("bg", [])) && (await Cli.claims("hub", ["status"]))); + ok("guard: `nexus ls` only bare", (await Cli.claims("ls", [])) && !(await Cli.claims("ls", ["the", "files"]))); + ok("guard: `nexus send an email ...` stays a prompt", !(await Cli.claims("send", ["an", "email"]))); + ok("guard: `nexus kill the dev server` stays a prompt", !(await Cli.claims("kill", ["the", "dev", "server"]))); + + // ---- gates + tool safety (no hub needed) ---- + ok("gate: sessions is an exec tool and blocked in plan mode", Gates.isExecTool("sessions") && Gates.isPlanBlocked("sessions")); + ok("gate: spawn shows the danger gate its command", Gates.execCommand("sessions", { action: "spawn", command: "rm -rf ~" }) === "rm -rf ~"); + ok("gate: send shows the danger gate its text", Gates.execCommand("sessions", { action: "send", text: "git push -f" }) === "git push -f"); + const fake = { ensureHub: async () => {}, call: async (m) => ({ ok: true, session: { id: "1", name: "n", state: "idle", kind: "nexus" }, sessions: [] }) }; + ok("tool: spawn outside the project is refused", /inside the project/.test((await Tool.sessionsTool({ action: "spawn", cwd: "../../etc" }, DIR, fake)).error || "")); + ok("tool: unknown agent is refused", /agent must be/.test((await Tool.sessionsTool({ action: "spawn", agent: "rm" }, DIR, fake)).error || "")); + ok("tool: send needs text", /needs text/.test((await Tool.sessionsTool({ action: "send", id: "1" }, DIR, fake)).error || "")); + ok("tool: id required", /needs id/.test((await Tool.sessionsTool({ action: "peek" }, DIR, fake)).error || "")); + const mcp = require("../lib/nexus/ask-mcp"); + ok("mcp bridge lists the sessions tool", mcp.SESSIONS_TOOL.name === "sessions" && mcp.SESSIONS_TOOL.inputSchema.properties.action.enum.includes("wait")); + ok("native schema has sessions", !!require("../lib/nexus/native-tools").TOOL_SCHEMAS.sessions); + + // ---- a real hub with a real shell ---- + if (!P.supported()) { console.log(" (skipping live hub tests on " + process.platform + ")"); return done(); } + const hub = createHub({ dir: DIR, stayUp: true }); + await hub.listen(); + ok("hub: socket is private", (fs.statSync(hub.sock).mode & 0o077) === 0 && (fs.statSync(DIR).mode & 0o077) === 0); + const call = (m, o) => P.call(m, Object.assign({ dir: DIR, timeout: 15000 }, o)); + try { + const sp = await call({ op: "spawn", name: "sh", cwd: DIR, cmd: ["/bin/sh", "-i"], cols: 80, rows: 20, env: { PS1: "hub$ ", ENV: "" } }); + ok("hub: spawn", sp.ok && sp.session.name === "sh"); + await call({ op: "wait", id: "sh", until: "idle", timeout: 10, settle: false }); + await call({ op: "send", id: "sh", text: "echo one-$((40+2)); sleep 2; echo two-done" }); + const w = await call({ op: "wait", id: "sh", until: "idle", timeout: 15 }); + ok("hub: wait holds through a quiet foreground command", w.reached && /two-done/.test(w.tail)); + const pk = await call({ op: "peek", id: "sh", lines: 10 }); + ok("hub: peek reads the screen as text", /one-42/.test(pk.text) && !/\x1b/.test(pk.text)); + ok("hub: the shell sees a real terminal of the requested size", await (async () => { await call({ op: "send", id: "sh", text: "stty size" }); await call({ op: "wait", id: "sh", until: "idle", timeout: 10 }); return /\b20 80\b/.test((await call({ op: "peek", id: "sh", lines: 4 })).text); })()); + await call({ op: "resize", id: "sh", cols: 100, rows: 30 }); + await call({ op: "send", id: "sh", text: "stty size" }); await call({ op: "wait", id: "sh", until: "idle", timeout: 10 }); + ok("hub: resize reaches the program", /\b30 100\b/.test((await call({ op: "peek", id: "sh", lines: 3 })).text)); + await call({ op: "send", id: "sh", text: "printf 'Do you want to proceed? (y/n) '; read a; echo answered-$a" }); + const b = await call({ op: "wait", id: "sh", until: "blocked", timeout: 10 }); + ok("hub: a question marks the session blocked", b.reached && b.session.state === "blocked"); + await call({ op: "send", id: "sh", text: "y" }); + const a2 = await call({ op: "wait", id: "sh", until: "idle", timeout: 10 }); + ok("hub: answering unblocks it", a2.reached && /answered-y/.test(a2.tail)); + await call({ op: "report", id: "1", state: "working" }); + ok("hub: a Nexus report is taken as the state", (await call({ op: "list" })).sessions[0].state === "working"); + const bad = await call({ op: "send", id: "nope", text: "x" }); + ok("hub: unknown session is a clear error", !bad.ok && /no session named nope/.test(bad.error)); + await call({ op: "kill", id: "sh" }); + const d = await call({ op: "wait", id: "sh", until: "done", timeout: 10, settle: false }); + ok("hub: kill ends the session", d.reached && d.session.state === "done"); + const saved = JSON.parse(fs.readFileSync(P.statePath(DIR), "utf8")); + ok("hub: a killed session is not kept for restore", !saved.sessions.some((x) => x.name === "sh")); + await call({ op: "spawn", name: "keep", cwd: DIR, cmd: ["/bin/sh", "-c", "sleep 60"] }); + } catch (e) { ok("hub: live tests threw " + e.message, false); } + hub.stop(); + const after = JSON.parse(fs.readFileSync(P.statePath(DIR), "utf8")); + ok("hub: stopping keeps running sessions restorable", after.sessions.some((x) => x.name === "keep")); + const hub2 = createHub({ dir: DIR, stayUp: true }); await hub2.listen(); + const l2 = await P.call({ op: "list" }, { dir: DIR, timeout: 5000 }); + ok("hub: a new hub lists the earlier sessions as restorable", l2.saved.some((x) => x.name === "keep")); + await P.call({ op: "forget" }, { dir: DIR, timeout: 5000 }); + ok("hub: forget with no name clears every stopped session", (await P.call({ op: "list" }, { dir: DIR, timeout: 5000 })).saved.length === 0); + hub2.stop(); + done(); +})(); + +function done() { + try { fs.rmSync(DIR, { recursive: true, force: true }); } catch (_) {} + console.log("\n" + (fail ? "\x1b[31m" : "\x1b[32m") + pass + " passed, " + fail + " failed\x1b[0m (background sessions)"); + process.exit(fail ? 1 : 0); +} diff --git a/test/mcp-audit.test.js b/test/mcp-audit.test.js index 79df053..e757db4 100644 --- a/test/mcp-audit.test.js +++ b/test/mcp-audit.test.js @@ -83,7 +83,7 @@ function runAsk(input, env) { ok("initialize with an unknown version answers one the shim speaks", by(0).result && by(0).result.protocolVersion === "2025-06-18"); ok("malformed JSON gets a -32700 parse error", m.some((x) => x.id === null && x.error && x.error.code === -32700)); ok("a notification of any method gets no reply (no id-less responses)", !m.some((x) => !("id" in x))); - ok("a batch has every member answered", by("b1").result && by("b2").result && by("b2").result.tools.length === 1); + ok("a batch has every member answered", by("b1").result && by("b2").result && by("b2").result.tools.map((t) => t.name).join(",") === "ask_user,sessions"); ok("an unknown tool is -32602", by("u").error && by("u").error.code === -32602); ok("ask_user without a question is -32602, not a blank popup", by("q").error && by("q").error.code === -32602 && by("t").error && by("t").error.code === -32602); ok("an unknown method is -32601", by(5).error && by(5).error.code === -32601);