diff --git a/darknode.js b/darknode.js index b86f47c..322b72e 100755 --- a/darknode.js +++ b/darknode.js @@ -72,12 +72,14 @@ const TokCount = require("./lib/cli/tokcount"); // pure /tokens estimator — pr const Cheap = require("./lib/nexus/cheap"); // /cheap on the claude engine: launch flags, model-switch hold, measured spend const CacheWarm = require("./lib/cli/cachewarm"); // pure prompt-cache TTL countdown for the status chip + /warm (lib/cli/cachewarm.js) const Agents = require("./lib/cli/agents"); // pure renderer + key reducer for the Agents panel (live sub-agent list under the prompt bar) (lib/cli/agents.js) -const { idleWatchdog } = require("./lib/nexus/engine-watchdog"); // engine hang guard: idle-based (ask_user no longer holds the engine open) +const { idleWatchdog, engineWaits } = require("./lib/nexus/engine-watchdog"); // engine hang guard: idle-based (ask_user no longer holds the engine open) const AskDefer = require("./lib/nexus/ask-defer"); // ask_user never blocks the engine: answer later, sent as the next prompt const { createAskServer } = require("./lib/nexus/ask-bridge"); // socket that lets external engines raise the real popup (lib/nexus/ask-bridge.js) const { buildEngineMcpServers, writeMcpConfigFile, toOpencodeConfig, toGeminiServers, writeEngineConfigFile } = require("./lib/nexus/engine-mcp"); // MCP-server set for external engines (lib/nexus/engine-mcp.js); codexMcpArgs is used inside engines.js const ASK_MCP_PATH = require("path").join(__dirname, "lib", "nexus", "ask-mcp.js"); // stdio MCP shim spawned by the engine const Term = require("./lib/cli/term"); // terminal-mode registry: always restore modes, even on a hard crash (lib/cli/term.js) +const Acp = require("./lib/nexus/acp-client"); // Agent Client Protocol transport for engines that speak it (lib/nexus/acp-client.js) +const Sandbox = require("./lib/nexus/sandbox"); // Landlock engine sandbox (lib/nexus/sandbox.js + landlock.py) const Jail = require("./lib/nexus/jail"); // canonical path jail shared by every file tool (symlink/dot-dot safe) (lib/nexus/jail.js) const Redact = require("./lib/nexus/redact"); // central sink redaction + keyed placeholders (lib/nexus/redact.js) const NexusDocs = require("./lib/cli/nexus-docs"); // the Nexus reference the model reads on questions about Nexus itself @@ -1947,9 +1949,10 @@ function runEngineTask(engine, prompt, cwd, autonomous, cont, onChunk, ctl, mode if (!m || !m.args || m.kind === "local") return resolve({ ok: false, output: "engine '" + engine + "' cannot run as a CLI task" }); // A prompt starting with "-" would be parsed as an option by every engine's CLI // (claude: "unknown option"); a leading space keeps it a value for all of them. - const cmd = m.bin, args = m.args(/^-/.test(prompt) ? " " + prompt : prompt, { cont, autonomous, model, effort, mcpServers: extra && extra.mcpServers, readonly: !!(extra && extra.readonly) }); + let cmd = m.bin, args = m.args(/^-/.test(prompt) ? " " + prompt : prompt, { cont, autonomous, model, effort, mcpServers: extra && extra.mcpServers, readonly: !!(extra && extra.readonly) }); let out = ""; - const spawnEnv = (extra && extra.env) ? Object.assign({}, process.env, extra.env) : process.env; // e.g. $OPENCODE_CONFIG pointing at the Nexus ask bridge + let spawnEnv = (extra && extra.env) ? Object.assign({}, process.env, extra.env) : process.env; // e.g. $OPENCODE_CONFIG pointing at the Nexus ask bridge + if (extra && extra.sandbox) { const w = Sandbox.prepare(cmd, args, spawnEnv, Object.assign({ cwd }, extra.sandbox)); cmd = w.cmd; args = w.args; spawnEnv = w.env; if (extra.onSandbox) extra.onSandbox(w); } // Landlock: no secrets, writes only where allowed const p = _cp.spawn(cmd, args, { cwd, env: spawnEnv, detached: process.platform !== "win32" }); // own process group so an interrupt kills the whole tree const to = idleWatchdog(() => killGroup(p, "SIGKILL")); let killed = false, err = ""; @@ -1989,8 +1992,10 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) { args.push(...Cheap.launchFlags(opts.cheap, opts.skillOverrides, opts.keepWarm)); if (opts.keepWarm) args.push(...Cheap.keepWarmFlags()); // one turn on an unsaved fork: reads the cache, leaves the conversation as it was if (opts.mcpConfigPath) args.push("--mcp-config", opts.mcpConfigPath); // give claude the Nexus ask bridge (+ any .nexus/mcp.json servers); no --strict so claude keeps its own servers too - const env = opts.small ? Object.assign({}, process.env, { ANTHROPIC_SMALL_FAST_MODEL: opts.small, CLAUDE_CODE_BG_CLASSIFIER_MODEL: opts.small }) : process.env; - const cp = _cp.spawn("claude", args, { cwd, env, detached: process.platform !== "win32" }); // own process group so an interrupt kills claude and its tool subprocesses + let env = opts.small ? Object.assign({}, process.env, { ANTHROPIC_SMALL_FAST_MODEL: opts.small, CLAUDE_CODE_BG_CLASSIFIER_MODEL: opts.small }) : process.env; + let bin = "claude"; + if (opts.sandbox) { const w = Sandbox.prepare(bin, args, env, Object.assign({ cwd }, opts.sandbox)); bin = w.cmd; args.splice(0, args.length, ...w.args); env = w.env; if (h.onSandbox) h.onSandbox(w); } // Landlock: no secrets, writes only where allowed + const cp = _cp.spawn(bin, args, { cwd, env, detached: process.platform !== "win32" }); // own process group so an interrupt kills claude and its tool subprocesses const to = idleWatchdog(() => killGroup(cp, "SIGKILL")); 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 = ""; } }; @@ -2918,6 +2923,19 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { const settingsStore = nexusSettings.createStore(NHOME); const S = settingsStore.value, Ssrc = settingsStore.source; const saveSetting = (k, v) => { try { settingsStore.set(k, v); } catch (_) {} }; + // ACP transport (/acp) and the Landlock engine sandbox (/sandbox): both persisted like every other toggle. + let acpMode = S.acp === "off" ? "off" : "auto", sandboxMode = Sandbox.normMode(S.sandbox) || "auto"; + const acpBroken = {}; // engine -> why: its ACP handshake failed this session, so it stays on the classic path + const sbxOpts = () => (sandboxMode === "off" ? null : { setting: sandboxMode, plan: mode === 2, untrusted: !!_untrustedRepoConfig, home: NHOME }); + const sbxNoted = new Set(); + const onSandbox = (w) => { // one note per reason per session: the user sees when (and why) the engine is fenced in + const key = w && w.sandbox ? "on:" + w.sandbox.reason + ":" + w.sandbox.writable : w && w.why && sandboxMode === "always" ? "why:" + w.why : ""; // auto falls back quietly where Landlock is missing (macOS, Windows); only an explicit "always" warns + if (!key || sbxNoted.has(key)) return; sbxNoted.add(key); + let at = activeBlock ? transcript.lastIndexOf(activeBlock) : -1; if (at > 0 && transcript[at - 1] && transcript[at - 1].role === "user") at--; // above this turn's prompt, not under its answer (and an interrupted empty turn still pops cleanly) + transcript.splice(at >= 0 ? at : transcript.length, 0, { role: "system", text: w.sandbox + ? "sandbox on (" + w.sandbox.reason + "): the engine can't read ~/.ssh, cloud/CLI tokens, browser profiles or shell history" + (w.sandbox.writable ? ", and writes only this project, the temp dir and its own state." : ", and can't write this project.") + gray(" Network stays open. /sandbox to change.") + : yellow("sandbox unavailable: " + w.why) + gray(" — this engine runs unsandboxed. /sandbox off hides this note.") }); + }; if (settingsStore.corrupt) transcript.push({ role: "system", text: "your settings file (~/.nexus/settings.json) was unreadable, so Nexus started with defaults. The old file was kept as " + settingsStore.corrupt + " — fix it and copy it back to restore your settings." }); // Signed in to Darknode: let the site owner's admin panel count this account as a Nexus user // (version + OS, at most every 6 hours; /shareusage off). Fire and forget. @@ -3048,7 +3066,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { ["/index", "index the repo for code search; /index finds the code it is about"], ["/map", "show the repo map; /map ranks it for a task; /map on|off"], ["/verify", "detect + run this project's tests/build"], ["/radar", "codebase complexity + hotspot map"], ["/review-fast", "fast rule-based review of changed code (no AI)"], ["/diffexplain", "explain the current git diff"], ["/testgen", "scaffold tests for a function/file"], ["/snippet", "save / use a prompt macro"], ["/snippets", "list saved prompt macros"], ["/plan", "make & run an editable task checklist"], ["/git", "branch, status & recent commits"], ["/blame", "who last changed a file's lines"], ["/cowork", "strong model codes, weak model does cheap work"], ["/cheap", "lossless savers + measured spend · /cheap status · /cheap off"], ["/tight", "surgical edits — change only what differs (lossless)"], ["/lean", "ask for minimal output (saves output tokens) · /lean on|off"], ["/style", "output style: concise·explanatory·review·tdd·secure·teacher"], ["/effort", "claude thinking level — interactive slider (or low|medium|high|xhigh|max|ultracode)"], ["/estimate", "rough token/cost of a prompt before sending"], ["/fallback", "auto-switch model on rate-limit"], - ["/guard", "preflight destructive commands (enforce|warn|off)"], ["/permissions", "allow/deny tool rules — /allow /deny "], ["/impact", "same as /savings — cost-savings analysis"], ["/savings", "cross-session cost-savings analysis + 30d projection"], ["/cache", "serve exact-repeat read-only answers free (on/off/clear)"], ["/models", "list cloud & local models"], ["/api", "drive ANY model via an OpenAI-compatible API (OpenRouter, Groq, …)"], ["/recent", "recently changed files"], ["/keys", "keyboard shortcuts"], ["/docs", "Nexus docs: /docs or /docs to search every command & key"], ["/gaps", "list TODO/FIXME markers · /gaps plan"], ["/dream", "consolidate the session into NEXUS.md memory"], + ["/guard", "preflight destructive commands (enforce|warn|off)"], ["/sandbox", "fence engines in (Landlock): no secrets, writes only the project · /sandbox auto|always|off"], ["/acp", "ACP engines (opencode, gemini): live tool cards, they ask before acting · /acp auto|off"], ["/permissions", "allow/deny tool rules — /allow /deny "], ["/impact", "same as /savings — cost-savings analysis"], ["/savings", "cross-session cost-savings analysis + 30d projection"], ["/cache", "serve exact-repeat read-only answers free (on/off/clear)"], ["/models", "list cloud & local models"], ["/api", "drive ANY model via an OpenAI-compatible API (OpenRouter, Groq, …)"], ["/recent", "recently changed files"], ["/keys", "keyboard shortcuts"], ["/docs", "Nexus docs: /docs or /docs to search every command & key"], ["/gaps", "list TODO/FIXME markers · /gaps plan"], ["/dream", "consolidate the session into NEXUS.md memory"], ["/tree", "show the project file tree"], ["/theme", "change the color theme"], ["/color", "set the accent color · /color · /color reset"], ["/colors", "list accent colors"], ["/gradient", "set the logo gradient · /gradient "], ["/mouse", "toggle mouse capture · /mouse off to select & copy text"], ["/hack", "offensive-security mode — pentest/CTF persona + the Darknode toolkit"], @@ -3631,6 +3649,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { "/cheap": () => [["status", "what each saver did this session"], ["off", "restore your settings from before /cheap"]], "/effort": () => [["low", "fast, less thinking"], ["medium", "balanced"], ["high", "deep reasoning"], ["xhigh", "harder problems"], ["max", "maximum thinking"], ["ultracode", "max + multi-agent workflows"]], "/guard": () => [["enforce", "block destructive commands"], ["warn", "warn but allow"], ["off", "no safety checks"]], + "/sandbox": () => [["auto", "plan mode + untrusted repos (default)"], ["always", "every engine turn"], ["off", "never sandbox"]], + "/acp": () => [["auto", "use ACP where the engine speaks it (default)"], ["off", "classic one-shot runs"]], "/marketplace": () => [["list", "installed packages"], ["install", "install from path/URL"], ["remove", "uninstall a package"], ["init", "scaffold a publishable package"]], "/cron": () => [["list", "show scheduled jobs"], ["add", "schedule a new job"], ["remove", "delete a job"], ["enable", "enable a job"], ["disable", "pause a job"], ["run", "run a job now"]], "/mcp": () => [["catalog", "browse available servers"], ["add", "connect a server"], ["remove", "disconnect a server"], ["connect", "reconnect all"]], @@ -4008,6 +4028,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { case "/fallback": return !!fallback; case "/autocompact": return autoCompact; case "/guard": return guard !== "off"; + case "/sandbox": return sandboxMode !== "off"; + case "/acp": return acpMode !== "off"; default: return null; } }; @@ -4138,13 +4160,95 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } return { mcpServers: servers }; // cArgs (codex): -c overrides via args() }; + // ---- ACP engines (opencode, gemini): live tool cards, and the engine asks Nexus before it acts ---- + const _acpHelp = {}; + const acpLaunchFor = (eng, mdl) => { + const m = ENGINES[eng]; + if (acpMode === "off" || !m || !m.acp || acpBroken[eng]) return null; + let help = ""; + if (m.acp.needsHelp) { if (_acpHelp[eng] == null) { try { const r = _cp.spawnSync(m.bin, ["--help"], { encoding: "utf8", timeout: 8000 }); _acpHelp[eng] = String(r.stdout || "") + String(r.stderr || ""); } catch (_) { _acpHelp[eng] = ""; } } help = _acpHelp[eng]; } // which ACP flag this install has (it was renamed between versions) + const args = m.acp.args({ model: mdl, help }); if (!args) return null; + const env = {}; + if (m.acp.permEnv === "OPENCODE_CONFIG_CONTENT" && !process.env.OPENCODE_CONFIG_CONTENT && mode !== 3) { const ov = Acp.opencodePermOverlay(Acp.opencodeUserConfigs(cwd, NHOME)); if (ov) env.OPENCODE_CONFIG_CONTENT = ov; } // its tools ask Nexus; the user's own permission settings win + return { cmd: m.bin, args, env }; + }; + const ACP_KIND = { read: "Read", edit: "Update", delete: "Delete", move: "Move", search: "Search", execute: "Bash", think: "Think", fetch: "Fetch", switch_mode: "Mode", other: "Tool" }; + const acpEngineTurn = (L, mdl, fallback, T) => { + const { block, textItem, stat, relOf, finish, promptText } = T; + const eng = ENGINES[engine], plan = mode === 2, sb = sbxOpts(); + const w = sb ? Sandbox.prepare(L.cmd, L.args, Object.assign({}, process.env, L.env), Object.assign({ cwd }, sb)) : { cmd: L.cmd, args: L.args, env: Object.assign({}, process.env, L.env), sandbox: null }; + if (sb) onSandbox(w); + const cards = new Map(); + const tcPath = (tc) => (tc.locations && tc.locations[0] && tc.locations[0].path) || (tc.input && typeof tc.input === "object" && (tc.input.path || tc.input.filePath || tc.input.filepath || tc.input.file_path)) || ""; + const tcLabel = (tc) => { const cmd = Acp.commandOf(tc), p = tcPath(tc); return (ACP_KIND[tc.kind] || "Tool") + "(" + oneline(String(tc.kind === "execute" && cmd ? cmd : p ? relP(p) : tc.title || ""), Math.max(30, cols() - 30)) + ")"; }; + const cardOf = (tc) => { + let c = cards.get(tc.id); + if (!c) { c = { type: "tool", id: "acp:" + tc.id, name: ACP_KIND[tc.kind] || "Tool", input: tc.input || {}, label: tcLabel(tc), detail: oneline(tc.title || "", 260), status: "run", start: Date.now() }; cards.set(tc.id, c); block.items.push(c); if (tc.kind === "execute") { stat.cmds++; runningShells++; c._sh = true; } } + return c; + }; + const settle = (c, good, txt) => { if (c.status !== "run") return; c.status = good ? "ok" : "err"; c.isError = !good; c.end = Date.now(); if (txt) { c.result = txt; c.detail = oneline(txt, 260); } if (c._sh && runningShells) runningShells--; }; + const touchFiles = (tc) => { if (!/^(edit|delete|move)$/.test(tc.kind)) return; for (const l of tc.locations || []) if (l && l.path) { stat.files.add(base(l.path)); const r = relOf(l.path); if (r) stat.paths.add(r); } }; + // The same rules the local agent's tools obey: /permissions deny + allow, the destructive-command guard, the project jail. + const check = (tc) => { + const cmd = Acp.commandOf(tc); + if (tc.kind === "execute" && cmd) { + const pd = permDecision(perms, "run_command", { command: cmd }); + if (pd === "deny") return { deny: "permission rule denied " + oneline(cmd, 60) }; + if (pd === "allow" || guard === "off") return {}; + const d = classifyDanger(cmd); + if (d.level === "block" && guard === "enforce") return { deny: "Darknode guard blocked a destructive command — " + d.why + ": " + oneline(cmd, 46) }; + return d.level !== "ok" ? { warn: d.why } : {}; + } + const p = tcPath(tc); + if (!/^(read|search|think|fetch)$/.test(tc.kind)) { // opencode asks "external_directory" (kind other) before touching a path outside the project + const outside = (tc.locations || []).map((l) => l && l.path).concat(p ? [p] : []).filter(Boolean).find((x) => { try { Jail.assertInJail(x, cwd); return false; } catch (_) { return true; } }); + if (outside || tc.title === "external_directory") return { ask: "that is outside this project" }; + } + if (p && /^(edit|delete|move)$/.test(tc.kind) && permDecision(perms, tc.kind === "delete" ? "delete" : "write_file", { path: p }) === "deny") return { deny: "permission rule denied " + tc.kind + " " + p }; + return {}; + }; + const decide = async (tc) => { + const pol = Acp.policyFor(mode, tc, check), c = cardOf(tc); + if (pol.decision === "reject") { settle(c, false, pol.why); if (!/^plan mode/.test(pol.why || "")) transcript.push({ role: "system", text: pol.why }); renderSoon(); return "reject"; } + if (pol.decision === "ask") { + engineWaits.n++; // the hang watchdog never fires while the user decides + try { + const r = await askUser(eng.label + " wants to " + (tc.kind === "execute" ? "run: " + oneline(Acp.commandOf(tc), 80) : (tc.title === "external_directory" ? "access" : (ACP_KIND[tc.kind] || "use").toLowerCase()) + " " + (tcPath(tc) || tc.title)) + " — " + pol.why, ["Allow once", "Reject"]); + const yes = !!(r && !r.cancelled && r.index === 0); if (!yes) settle(c, false, "rejected by you"); return yes ? "allow" : "reject"; + } finally { engineWaits.n--; } + } + return "allow"; + }; + Acp.runTurn({ cmd: w.cmd, args: w.args, env: w.env, cwd, prompt: promptText, plan, model: mdl, mcpServers: engineMcpServers(plan) || undefined, version: VERSION, ctl, idle: idleWatchdog, jail: (p) => Jail.assertInJail(p, cwd), decide, + onText: (t) => { textItem().full += t; sess.liveOut += Math.ceil(t.length / 4); renderSoon(); }, + onThought: (t) => { let last = block.items[block.items.length - 1]; if (!last || last.type !== "thinking") { last = { type: "thinking", full: "" }; block.items.push(last); } last.full += t; sess.liveOut += Math.ceil(t.length / 4); renderSoon(); }, + onTool: (tc) => { cardOf(tc).label = tcLabel(tc); render(); }, + onToolUpdate: (tc) => { const c = cardOf(tc); c.label = tcLabel(tc); if (tc.input) c.input = tc.input; if (tc.status === "completed" || tc.status === "failed") { settle(c, tc.status === "completed", tc.text || (typeof tc.output === "string" ? tc.output : "")); if (tc.status === "completed") touchFiles(tc); } renderSoon(); }, + onWrite: (real) => { stat.files.add(base(real)); const r = relOf(real); if (r) stat.paths.add(r); }, + onUsage: (u) => { if (u && u.size) sess.ctxWindow = u.size; }, + }).then((r) => { + if (r.acpFailed && !r.interrupted && !block.items.length) { // never got a session: this install can't do ACP, so run the classic way (and stay there this session) + acpBroken[engine] = r.error || "handshake failed"; + transcript.push({ role: "system", text: gray(eng.label + " ACP unavailable (" + oneline(r.error || "", 80) + ") — using its classic mode this session. /acp off makes that permanent.") }); + return fallback(); + } + const u = r.usage || {}, display = r.output || ""; + let inD = (u.inputTokens || 0) + (u.cachedReadTokens || 0) + (u.cachedWriteTokens || 0), outD = (u.outputTokens || 0) + (u.thoughtTokens || 0); // REAL usage from the prompt result + if (!inD && !outD) { inD = Math.ceil(promptText.length / 4); outD = Math.ceil(display.length / 4); } // agent sent none: estimate + sess.inTok += inD; sess.outTok += outD; + sess.ctxUsed = (r.ctx && r.ctx.used) || ((sess.inTok + sess.outTok) - (sess.ctxBase || 0)); + if (PAID[engine] && !onPlan(engine)) { const ac = r.ctx && r.ctx.cost && +r.ctx.cost.amount; if (ac > 0) sess.cost += ac; else { const pr = priceOf(mdl || eng.model || ""); sess.cost += (inD * pr.in + outD * pr.out) / 1e6; } } + if (!r.ok && !r.interrupted && r.error && !display.trim()) textItem().full = engine + " error: " + r.error + (r.needsAuth ? "\nsign in by running `" + eng.bin + (engine === "opencode" ? " auth login" : "") + "` in a terminal, then retry" : ""); + finish({ ok: r.ok, interrupted: r.interrupted, output: display || r.error || "" }); + }); + }; // ---- animation loop: typewriter reveal + spinners + elapsed ---- const revealing = () => { const b = activeBlock || cur(); if (!b || !b.items) return false; return b.items.some((it) => it.type === "text" && it.shown < it.full.length); }; const startTick = () => { if (tick) return; tick = setInterval(() => { const b = activeBlock || cur(); if (b && b.items) for (const it of b.items) if (it.type === "text" && it.shown < it.full.length) { let ns = Math.min(it.full.length, it.shown + Math.max(2, Math.ceil((it.full.length - it.shown) / 22))); const cc = it.full.charCodeAt(ns - 1); if (cc >= 0xD800 && cc <= 0xDBFF && ns < it.full.length) ns++; it.shown = ns; } render(); if (!busy && !revealing() && !compact.on) { clearInterval(tick); tick = null; } }, 45); }; // idle refresh for the prompt-cache chip: re-render only when its text changes (minute steps, then seconds in the last minute) // Everything a claude launch depends on besides the prompt. Keep-warm rebuilds it to check // that the next real message would still match the cached prefix it is about to refresh. - const claudeOpts = (resume) => ({ resume, 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, cheap: !!(cacheOn && tightEdits && cheapSide), skillOverrides: cacheOn && tightEdits && cheapSide ? Cheap.overridesFor(NHOME, cwd) : null, 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(mode === 2), readonly: mode === 2, fallbackModel: fallback || undefined, maxBudgetUsd: costCap ? Math.max(0.01, costCap - sess.cost).toFixed(2) : undefined, disallow: mode === 2 ? READONLY_TOOLS : undefined }); + const claudeOpts = (resume) => ({ resume, 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, cheap: !!(cacheOn && tightEdits && cheapSide), skillOverrides: cacheOn && tightEdits && cheapSide ? Cheap.overridesFor(NHOME, cwd) : null, 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(mode === 2), readonly: mode === 2, fallbackModel: fallback || undefined, maxBudgetUsd: costCap ? Math.max(0.01, costCap - sess.cost).toFixed(2) : undefined, disallow: mode === 2 ? READONLY_TOOLS : undefined, sandbox: sbxOpts() || undefined }); // /cheap keep-warm: refresh a 1-hour cache just before it expires while you are away const keepWarm = () => { if (warming || !lastClaudeOpts || !Cheap.keepWarmDue({ cheap: !!(cacheOn && tightEdits && cheapSide), engine, sid: claudeSid, busy, lastAt: cacheWarm.lastAt, ttl: cacheWarm.ttl, now: Date.now(), lastHumanAt: lastAskAt, ctxTok: sess.ctxUsed })) return; @@ -4476,6 +4580,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { lastAskAt = Date.now(); runClaudeStream(promptText, cwd, cont, { onInit: (ev) => { if (ev.model) sess.model = ev.model; if (ev.session_id) claudeSid = ev.session_id; }, + onSandbox, onRateLimit: (info) => { rate = info; }, onThinking: (t, pid) => { const sa = subAgentOf(pid), tg = sa ? sa.items : block.items; let last = tg[tg.length - 1]; if (!last || last.type !== "thinking") { last = { type: "thinking", full: "" }; tg.push(last); } last.full += t; if (!anyDelta) bumpLive(t); renderSoon(); }, onText: (t, pid) => { const sa = subAgentOf(pid); if (sa) { let last = sa.items[sa.items.length - 1]; if (!last || last.type !== "text") { last = { type: "text", full: "", shown: 0 }; sa.items.push(last); } last.full += t; last.shown = last.full.length; } else textItem().full += t; if (!anyDelta) bumpLive(t); renderSoon(); }, @@ -4513,6 +4618,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } 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 + const classicTurn = () => { const jsonProto = eng.proto === "gemini-json" || eng.proto === "codex-json"; // JSON-mode engines emit machine output (not human text), so don't render the // raw chunks. For the live token counter, show the REAL running count, never @@ -4527,7 +4633,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { renderSoon(); }) : ((chunk) => { textItem().full += chunk; sess.liveOut += Math.ceil(chunk.length / 4); renderSoon(); }); - runEngineTask(engine, promptText, cwd, mode !== 2, cont, onChunk, ctl, mdl, undefined, mode === 2 ? Object.assign({}, engineMcpLaunch(engine, true), { readonly: true }) : engineMcpLaunch(engine)).then((res) => { + runEngineTask(engine, promptText, cwd, mode !== 2, cont, onChunk, ctl, mdl, undefined, Object.assign({}, mode === 2 ? Object.assign({}, engineMcpLaunch(engine, true), { readonly: true }) : engineMcpLaunch(engine), { sandbox: sbxOpts() || undefined, onSandbox })).then((res) => { const raw = res.output || ""; let display = raw, inD, outD; if (jsonProto) { @@ -4544,6 +4650,9 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { if (PAID[engine] && !onPlan(engine)) { const pm = mdl || eng.model || ""; const pr = priceOf(pm); sess.cost += (inD * pr.in + outD * pr.out) / 1e6; } // priced from the table → shown as ~$ (a plan login costs nothing per turn) finish(res); }); + }; + const acpL = acpLaunchFor(engine, mdl); + if (acpL) acpEngineTurn(acpL, mdl, classicTurn, { block, textItem, stat, relOf, finish, promptText }); else classicTurn(); } else { // ollama — LOCAL agent with full device access (read/write/edit/list/run_command) const mcps = mcpToolList(); const extra = (mcps.length ? " MCP tools: " + mcps.map((m) => m.full + " — " + oneline(m.desc, 40)).join("; ") + "." : "") + " spawn_agents{tasks:[\"...\",\"...\"]} runs several INDEPENDENT sub-tasks in parallel via sub-agents and returns all their results — use it to split big work."; @@ -4680,7 +4789,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { else if (name === "edit_file") { const fp = path.resolve(cwd, a.path); if (fs.existsSync(fp) && !fileGuard.hasSeen(fp)) throw new Error(unreadEditError(a.path)); const _rd = readEditable(fp, a.path); if (_rd.error) throw new Error(_rd.error); const t = _rd.text; const r = applyEditsFlexible(t, [{ find: a.find, replace: a.replace, replaceAll: a.replace_all || a.replaceAll }]); const _sec = (r.ok && policy.blockSecrets) ? scanSecrets(String(a.replace == null ? "" : a.replace)) : []; if (!r.ok) result = { error: r.error }; else if (_sec.length) { result = { error: "BLOCKED by policy: edit would introduce " + _sec.join(", ") }; blocked = true; } else if (r.content === t) { result = { ok: true, note: "no change — find and replace are identical, nothing was written" }; } else { fs.writeFileSync(fp, r.content); delete readCache[fp]; fileGuard.recordWrite(fp, r.content); invalidateRepoMap(); result = Object.assign({ ok: true }, changedRegion(t, r.content) || {}); if (r.applied[0] && r.applied[0].mode === "flexible") result.note = r.applied[0].fixed ? "matched after dropping the " + r.applied[0].fixed + " your find carried (the file has none) - check the lines above" : "matched ignoring whitespace/indentation — the change was re-indented to fit; check the lines above"; } } else if (name === "multi_edit" || name === "multiedit") { const fp = path.resolve(cwd, a.path); if (fs.existsSync(fp) && !fileGuard.hasSeen(fp)) throw new Error(unreadEditError(a.path)); const _rd = readEditable(fp, a.path), t = _rd.error ? null : _rd.text; if (t == null) result = { error: _rd.error }; else { const edits = (a.edits || a.changes || []).map((e) => ({ find: e.find || e.old || e.search, replace: e.replace == null ? (e.new == null ? "" : e.new) : e.replace, replaceAll: e.replace_all || e.replaceAll })); const r = applyEditsFlexible(t, edits); if (!r.ok) result = { error: r.error }; else { const sec = policy.blockSecrets ? scanSecrets(edits.map((e) => String(e.replace == null ? "" : e.replace)).join("\n")) : []; /* only the NEW text — a secret-shaped value already in the file is not introduced by this edit */ if (sec.length) { result = { error: "BLOCKED by policy: edit would introduce " + sec.join(", ") }; blocked = true; } else if (r.content === t) { result = { ok: true, note: "no change — every edit was a no-op, nothing was written" }; } else { fs.writeFileSync(fp, r.content); delete readCache[fp]; fileGuard.recordWrite(fp, r.content); invalidateRepoMap(); result = Object.assign({ ok: true, edits: r.applied.length, flexible: r.applied.filter((x) => x.mode === "flexible").length }, changedRegion(t, r.content, 16) || {}); } } } } else if (name === "apply_patch" || name === "patch") { const diff = a.patch || a.diff || a.content || a.input || ""; const filesP = parsePatch(diff); if (!filesP.length) result = { error: "no hunks parsed from the patch (need a unified diff with @@ hunks, or a *** Begin Patch envelope)" }; else { let failed = null; const planW = []; for (const f of filesP) { if (!f.file) { failed = "a hunk had no target file (need --- a/path / +++ b/path headers)"; break; } const rp = path.resolve(cwd, f.file); const rel = path.relative(cwd, rp); if (rel.startsWith("..") || path.isAbsolute(rel) || !Jail.resolveInJail(f.file, cwd).inside) { failed = f.file + ": path escapes the workspace"; break; } const pc = policyCheck(policy, { type: "edit", path: f.file }); if (!pc.allow) { failed = f.file + ": blocked by policy — " + pc.reason; break; } if (f.op === "delete" || f.op === "move") { failed = f.file + ": the patch " + (f.op === "delete" ? "deletes this file" : "moves it to " + f.to) + " - apply_patch only edits and creates files; use " + (f.op === "delete" ? "delete{path}" : "move{from,to} first, then patch the new path") + " (nothing was applied)"; break; } let cont = ""; if (fs.existsSync(rp)) { if (f.op !== "add" && !fileGuard.hasSeen(rp)) { failed = f.file + ": " + unreadEditError(f.file); break; } const _rd = readEditable(rp, f.file); if (_rd.error) { failed = f.file + ": " + _rd.error; break; } cont = _rd.text; } const ap = f.op === "add" ? (cont ? { ok: false, error: "already exists, but the patch creates it as a new file (*** Add File or --- /dev/null) - send update hunks instead" } : { ok: true, content: f.hunks.length ? f.hunks[0].after.join("\n") + (f.hunks[0].noEol ? "" : "\n") : "" }) : applyHunks(cont, f.hunks); if (!ap.ok) { failed = f.file + ": " + ap.error; break; } if (policy.blockSecrets) { const added = f.hunks.map((h) => { const had = new Set(h.before); return h.after.filter((l) => !had.has(l)).join("\n"); }).join("\n"); const _ps = scanSecrets(added); if (_ps.length) { failed = f.file + ": patch would introduce " + _ps.join(", "); break; } } /* only ADDED lines — an existing secret-shaped value is not introduced by this patch */ planW.push({ rp, file: f.file, content: ap.content, before: cont }); } if (failed) { result = { error: failed }; if (/blocked by policy|secret/.test(failed)) { blocked = true; } } else { for (const p of planW) { fs.mkdirSync(path.dirname(p.rp), { recursive: true }); fs.writeFileSync(p.rp, p.content); delete readCache[p.rp]; fileGuard.recordWrite(p.rp, p.content); stat.files.add(base(p.file)); const rr = relOf(p.file); if (rr) stat.paths.add(rr); } invalidateRepoMap(); result = { ok: true, files: planW.map((p) => p.file) }; if (planW.length === 1) Object.assign(result, changedRegion(planW[0].before, planW[0].content, 16) || {}); else { result.changed = {}; for (const p of planW) { const cr = changedRegion(p.before, p.content); if (cr) result.changed[p.file] = "lines " + cr.lines; } } } } } - else if (name === "run_command") { const r = await coderShell(a.command, cwd, { ctl, timeoutMs: (require("./lib/nexus/wait-for").parseSecs(a.timeout_s) * 1000) || undefined, onData: (d) => Tail.pushTail(card.live || Object.defineProperty(card, "live", { value: Tail.createTail(), configurable: true }).live, d) /* non-enumerable: never written to session.json */ }); delete card.live; const _out = compactOutput(r.output, lean ? 2000 : (trimOutput ? 4000 : 1e9)); const _d = diagnose(_out, r.code, a.command); result = { code: r.code, output: _out + diagAnnotate(_d) }; if (_d) result.diagnosis = _d.category; } + else if (name === "run_command") { const r = await coderShell(a.command, cwd, { ctl, sandbox: sbxOpts() || undefined, onSandbox, timeoutMs: (require("./lib/nexus/wait-for").parseSecs(a.timeout_s) * 1000) || undefined, onData: (d) => Tail.pushTail(card.live || Object.defineProperty(card, "live", { value: Tail.createTail(), configurable: true }).live, d) /* non-enumerable: never written to session.json */ }); delete card.live; const _out = compactOutput(r.output, lean ? 2000 : (trimOutput ? 4000 : 1e9)); const _d = diagnose(_out, r.code, a.command); result = { code: r.code, output: _out + diagAnnotate(_d) }; if (_d) result.diagnosis = _d.category; } else if (name === "run_background") { if (!a.command || typeof a.command !== "string") { result = { error: "run_background needs a non-empty command string" }; } else { const p = _cp.spawn(process.platform === "win32" ? "cmd" : "sh", process.platform === "win32" ? ["/c", a.command] : ["-c", a.command], { cwd, env: process.env, detached: process.platform !== "win32" }); const id = bgJobs.start(a.command, p, Date.now()); /* own process group → stop kills the whole tree (npm → node), not just sh */ p.stdout && p.stdout.setEncoding("utf8"); p.stderr && p.stderr.setEncoding("utf8"); /* a multi-byte char split across chunks became two U+FFFD */ p.stdout && p.stdout.on("data", (d) => bgJobs.append(id, d)); p.stderr && p.stderr.on("data", (d) => bgJobs.append(id, d)); p.on("close", (code, sig) => bgJobs.finish(id, code, sig)); p.on("error", (e) => { bgJobs.append(id, "spawn error: " + e.message); bgJobs.finish(id, 1); }); result = { ok: true, jobId: id, status: "running", hint: "poll it with check_background{id:'" + id + "'}, stop it with stop_background{id:'" + id + "'}" }; } } else if (name === "check_background") { if (a.id || a.job) { a.id = a.id || a.job; const j = bgJobs.get(a.id); if (!j) result = { error: "no such job " + a.id + bgJobs.known() }; else if (a.full) { result = { id: j.id, status: j.status, code: j.code, output: compactOutput(collapseRepeats(bgJobs.tail(a.id, 6000)).text, 4000) }; bgJobs.readNew(a.id); } else { // only what the agent hasn't seen yet — re-sending the same tail on every poll is pure waste @@ -5779,6 +5888,22 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } } else if (cmd === "/bench") { if (!argstr) transcript.push({ role: "system", text: "usage: /bench — runs it on each engine and reports a speed / tokens / cost table" }); else benchEngines(argstr); } + else if (cmd === "/sandbox") { + const a = Sandbox.normMode(arg); + if (a) { sandboxMode = a; saveSetting("sandbox", a); sbxNoted.clear(); } + const pb = Sandbox.probe(); + const what = sandboxMode === "always" ? "every engine turn is sandboxed (external engines, and the local agent's run_command)" : sandboxMode === "auto" ? "plan-mode turns and untrusted repos are sandboxed" : "engines run unsandboxed"; + transcript.push({ role: "system", text: (a ? "sandbox set to " : "sandbox is ") + cyan(sandboxMode) + " — " + what + "\n" + + (pb.ok ? " " + green("available") + gray(" (Landlock ABI " + pb.abi + ")") : " " + yellow("unavailable here: " + pb.why) + gray(" — engines run unsandboxed")) + + "\n" + gray(" sandboxed engines can read the system but not ~/.ssh, cloud/CLI tokens, browser profiles or shell history,\n and write only the project (not in plan mode), the temp dir and their own state. Network stays open.") + + (a ? "" : "\n" + gray(" usage: /sandbox auto|always|off")) }); + } + else if (cmd === "/acp") { + const a = /^(auto|on)$/i.test(arg) ? "auto" : /^off$/i.test(arg) ? "off" : ""; + if (a) { acpMode = a; saveSetting("acp", a); for (const k of Object.keys(acpBroken)) delete acpBroken[k]; } + const speaks = ENGINE_ORDER.filter((e) => ENGINES[e].acp).map((e) => e + (acpBroken[e] ? gray(" (failed this session: " + oneline(acpBroken[e], 50) + ")") : "")); + transcript.push({ role: "system", text: (a ? "ACP set to " : "ACP is ") + cyan(acpMode) + (acpMode === "off" ? " — every engine runs its classic one-shot mode" : " — " + speaks.join(", ") + " run over the Agent Client Protocol: live tool cards, real token counts, and they ask Nexus before editing or running commands (plan mode, /permissions and /guard apply)") + (a ? "" : "\n" + gray(" usage: /acp auto|off")) }); + } else if (cmd === "/guard") { if (["enforce", "warn", "off"].includes(arg)) { guard = arg; transcript.push({ role: "system", text: "Darknode guard set to " + arg + (arg === "enforce" ? " — destructive agent commands (rm -rf, git reset --hard, dd, mkfs, pipe-to-shell, fork bombs, …) are blocked" : arg === "warn" ? " — destructive commands are flagged but allowed" : " — destructive-command checks disabled") }); } else transcript.push({ role: "system", text: "Darknode guard is " + guard + ". usage: /guard enforce|warn|off — preflights the local agent's shell commands for destructive intent" }); } else if (cmd === "/settings" || cmd === "/options" || cmd === "/config") { // Toggle an off-by-default governance setting inline: /settings [on|off|] @@ -5798,7 +5923,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } render(); return; } - const v = { engine, model: (sess.model && sess.model !== engine ? sess.model : ""), effort, fallback, style, lean, cowork, costCap, cost: sess.cost, mode: (MODES[mode] && MODES[mode].k) || "auto-accept", guard, policyOrg: policy.org, audit: policy.audit, redact, offline, notify, shareUsage: settingsStore.value.shareUsage, ctxPct: sess.ctxWindow ? Math.min(100, Math.round((sess.ctxUsed / sess.ctxWindow) * 100)) : null, pins: pinned.size, bgRunning: bgJobs.running() }; + const v = { engine, model: (sess.model && sess.model !== engine ? sess.model : ""), effort, fallback, style, lean, cowork, costCap, cost: sess.cost, mode: (MODES[mode] && MODES[mode].k) || "auto-accept", guard, sandbox: sandboxMode, acp: acpMode, policyOrg: policy.org, audit: policy.audit, redact, offline, notify, shareUsage: settingsStore.value.shareUsage, ctxPct: sess.ctxWindow ? Math.min(100, Math.round((sess.ctxUsed / sess.ctxWindow) * 100)) : null, pins: pinned.size, bgRunning: bgJobs.running() }; // on/off values read green/red at a glance, matching the slash-menu toggle colours const onOff = (x) => /^on\b/i.test(x) ? green(x) : /^off$/i.test(x) ? red(x) : x; let text = bold("Settings") + gray(" change any option with the command shown"); diff --git a/docs/NEXUS-COMMANDS.md b/docs/NEXUS-COMMANDS.md index 128a0bf..6b31bff 100644 --- a/docs/NEXUS-COMMANDS.md +++ b/docs/NEXUS-COMMANDS.md @@ -160,6 +160,8 @@ File tools are confined to the project folder; secrets are blocked from being wr - `/estimate` — rough token/cost of a prompt before sending (opens in the side panel) - `/fallback` — auto-switch model on rate-limit - `/guard` — preflight destructive commands (enforce|warn|off) +- `/sandbox` — fence engines in (Landlock): no secrets, writes only the project · /sandbox auto|always|off +- `/acp` — ACP engines (opencode, gemini): live tool cards, they ask before acting · /acp auto|off - `/permissions` — allow/deny tool rules — /allow /deny - `/impact` — same as /savings — cost-savings analysis (opens in the side panel) - `/savings` — cross-session cost-savings analysis + 30d projection (opens in the side panel) diff --git a/lib/cli/command-help.js b/lib/cli/command-help.js index 06dd8de..3f66f3f 100644 --- a/lib/cli/command-help.js +++ b/lib/cli/command-help.js @@ -72,6 +72,8 @@ const HELP = { "/estimate": { u: "", ex: ["/estimate refactor the auth module"], see: ["/tokens", "/cost"] }, "/fallback": { u: "|off", a: [["", "auto-switch to it when the main model is rate-limited"], ["off", "clear the fallback"]], ex: ["/fallback sonnet", "/fallback off"], see: ["/model", "/mode"] }, "/guard": { u: "[enforce|warn|off]", ex: ["/guard", "/guard enforce", "/guard off"], see: ["/permissions", "/policy"] }, + "/sandbox": { u: "[auto|always|off]", ex: ["/sandbox", "/sandbox always", "/sandbox off"], see: ["/guard", "/permissions", "/acp"] }, + "/acp": { u: "[auto|off]", ex: ["/acp", "/acp off"], see: ["/engine", "/sandbox", "/permissions"] }, "/permissions": { u: "— use /allow and /deny ", ex: ["/permissions", "/allow run_command(git*)", "/deny write_file(.env)"], see: ["/guard", "/policy"] }, "/cache": { u: "[on|off|clear]", ex: ["/cache", "/cache on", "/cache clear"], see: ["/warm", "/cheap"] }, "/api": { u: " | key | off", a: [["base-url", "any OpenAI-compatible endpoint"], ["key ", "set the API key for this session"], ["off", "stop using the custom endpoint"]], ex: ["/api https://openrouter.ai/api/v1 meta-llama/llama-3-70b", "/api key sk-...", "/api off"], see: ["/engine", "/models"] }, diff --git a/lib/cli/nexus-settings.js b/lib/cli/nexus-settings.js index 8a60736..296ef88 100644 --- a/lib/cli/nexus-settings.js +++ b/lib/cli/nexus-settings.js @@ -43,6 +43,8 @@ const DEFAULTS = { model: "", // "" = the engine default; persists the user's /model choice syntaxGate: "warn", // after an edit, warn (never block) if it introduced a syntax error; "off" disables shareUsage: true, // signed in: tell Darknode this account uses Nexus (version + OS, every 6h); /shareusage off + acp: "auto", // engines that speak ACP (opencode, gemini) run over it: live tool cards, Nexus answers their permission asks; "off" = classic one-shot + sandbox: "auto", // Landlock engine sandbox (protective, Linux): "auto" = plan mode + untrusted repos, "always", "off" }; // Env vars that pin a key for THIS launch (highest precedence). A present + @@ -58,12 +60,14 @@ const ENV_KEYS = { lean: (v) => truthy(v), effort: (v) => v || undefined, syntaxGate: (v) => (/^(off|warn)$/i.test(String(v).trim()) ? String(v).trim().toLowerCase() : undefined), + acp: (v) => (/^(auto|off)$/i.test(String(v).trim()) ? String(v).trim().toLowerCase() : /^(0|false|no)$/i.test(String(v).trim()) ? "off" : undefined), + sandbox: (v) => { const s = String(v).trim().toLowerCase(); return s === "on" || s === "1" || s === "true" ? "always" : /^(auto|always|off)$/.test(s) ? s : s === "0" || s === "false" ? "off" : undefined; }, }; // NEXUS_ env name for each governed key. const ENV_NAME = { budgetCap: "NEXUS_BUDGET", autoCompact: "NEXUS_AUTOCOMPACT", minimizeCalls: "NEXUS_MINIMIZE_CALLS", stepCap: "NEXUS_STEP_CAP", trimOutput: "NEXUS_TRIM_OUTPUT", cache: "NEXUS_CACHE", map: "NEXUS_MAP", - lean: "NEXUS_LEAN", effort: "NEXUS_EFFORT", syntaxGate: "NEXUS_SYNTAX_GATE", + lean: "NEXUS_LEAN", effort: "NEXUS_EFFORT", syntaxGate: "NEXUS_SYNTAX_GATE", acp: "NEXUS_ACP", sandbox: "NEXUS_SANDBOX", }; function truthy(v) { return /^(1|true|on|yes)$/i.test(String(v || "").trim()); } diff --git a/lib/cli/settings.js b/lib/cli/settings.js index ed24358..56f9831 100644 --- a/lib/cli/settings.js +++ b/lib/cli/settings.js @@ -21,6 +21,8 @@ const SETTINGS = [ { group: "Safety & policy", items: [ { label: "Permission mode", cmd: "shift+tab", get: (v) => v.mode || "auto-accept" }, { label: "Command guard", cmd: "/guard enforce|warn|off", get: (v) => v.guard || "enforce" }, + { label: "Engine sandbox", cmd: "/sandbox auto|always|off", get: (v) => v.sandbox || "auto" }, + { label: "ACP engines", cmd: "/acp auto|off", get: (v) => v.acp || "auto" }, { label: "Security policy", cmd: "/policy", get: (v) => (v.policyOrg ? "org-enforced" : "local/default") }, { label: "Audit trail", cmd: "/audit verify", get: (v) => (v.audit ? "on (hash-chained)" : "off") }, ] }, diff --git a/lib/nexus/acp-client.js b/lib/nexus/acp-client.js new file mode 100644 index 0000000..553ec98 --- /dev/null +++ b/lib/nexus/acp-client.js @@ -0,0 +1,293 @@ +"use strict"; +// ================= ACP client (Agent Client Protocol) ================= +// Drives an engine that speaks ACP (JSON-RPC 2.0, one JSON object per line on +// stdio) instead of scraping its plain-text output. What that buys over the +// classic one-shot ` run ""` path: +// - real tool calls as they happen (title, kind, status, files, output) for the +// TUI's tool cards, plus streamed text and thinking +// - the engine ASKS before acting (session/request_permission) and Nexus answers +// from its own mode, guard and permission rules, so plan mode, deny rules and +// the destructive-command guard apply to the engine's tools too +// - file reads/writes the engine routes through the client stay inside the +// project jail; real token usage from the prompt result +// - a clean cancel (session/cancel) before any process kill +// Zero dependencies. The host passes callbacks; this module never touches the TUI. + +const { spawn } = require("child_process"); +const fs = require("fs"); +const path = require("path"); + +const PROTOCOL_VERSION = 1; +const READ_KINDS = new Set(["read", "search", "think", "fetch"]); // what plan mode lets through (fetch = reading the web) + +// ACP mcpServers entries from Nexus's { name: { command, args, env } | { url, headers } } map. +function toAcpMcpServers(servers, caps) { + const out = []; + const pairs = (o) => Object.keys(o || {}).map((k) => ({ name: k, value: String(o[k]) })); + for (const name of Object.keys(servers || {})) { + const s = servers[name]; + if (s && s.command) out.push({ name, command: s.command, args: (s.args || []).map(String), env: pairs(s.env) }); + else if (s && s.url) { + const t = String(s.type || "").toLowerCase() === "sse" ? "sse" : "http"; + if (caps && caps.mcpCapabilities && caps.mcpCapabilities[t]) out.push({ type: t, name, url: s.url, headers: pairs(s.headers) }); + } + } + return out; +} + +// Pick the optionId for a decision ("allow" | "allow_always" | "reject") from the +// options the agent offered. Falls back across once/always of the same polarity. +function pickOption(options, decision) { + const opts = Array.isArray(options) ? options : []; + const want = decision === "allow_always" ? ["allow_always", "allow_once"] : decision === "allow" ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"]; + for (const k of want) { const o = opts.find((x) => x && x.kind === k); if (o) return o.optionId; } + return null; +} + +// Plain text of a tool_call / tool_call_update content array. +function contentText(content) { + if (!Array.isArray(content)) return ""; + const parts = []; + for (const c of content) { + if (!c) continue; + if (c.type === "content" && c.content && c.content.type === "text") parts.push(c.content.text || ""); + else if (c.type === "diff") parts.push("diff " + (c.path || "") + "\n" + diffLines(c.oldText, c.newText)); + else if (c.type === "text") parts.push(c.text || ""); + } + return parts.join("\n"); +} +function diffLines(a, b) { + const A = String(a == null ? "" : a).split("\n"), B = String(b == null ? "" : b).split("\n"); + let i = 0; while (i < A.length && i < B.length && A[i] === B[i]) i++; + let ja = A.length - 1, jb = B.length - 1; while (ja >= i && jb >= i && A[ja] === B[jb]) { ja--; jb--; } + return A.slice(i, ja + 1).map((l) => "-" + l).concat(B.slice(i, jb + 1).map((l) => "+" + l)).slice(0, 200).join("\n"); +} + +class AcpClient { + // opts: { cmd, args, cwd, env, onNotify(method, params), onRequest(method, params) -> Promise, onExit(code, stderr), spawnFn } + constructor(opts) { + this.o = opts; + this.id = 0; this.pend = new Map(); this.buf = ""; this.err = ""; this.closed = false; + const sp = opts.spawnFn || spawn; + this.p = sp(opts.cmd, opts.args || [], { cwd: opts.cwd, env: opts.env || process.env, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"] }); + this.p.stdout.setEncoding("utf8"); this.p.stderr.setEncoding("utf8"); + this.p.stdout.on("data", (d) => this._data(d)); + this.p.stderr.on("data", (d) => { this.err += d; if (this.err.length > 20000) this.err = this.err.slice(-20000); if (opts.onActivity) opts.onActivity(); }); + this.p.stdin.on("error", () => {}); + const done = (code, e) => { + if (this.closed) return; this.closed = true; + const why = e ? "spawn error: " + e.message : "agent exited (code " + code + ")" + (this.err.trim() ? ": " + this.err.trim().split("\n").slice(-3).join(" | ") : ""); + for (const [, r] of this.pend) r.reject(new Error(why)); + this.pend.clear(); + if (opts.onExit) opts.onExit(code, this.err, e); + }; + this.p.on("error", (e) => done(null, e)); + this.p.on("close", (code) => done(code)); + } + get pid() { return this.p.pid; } + _write(obj) { if (this.closed) return; try { this.p.stdin.write(JSON.stringify(obj) + "\n"); } catch (_) {} } + _data(d) { + if (this.o.onActivity) this.o.onActivity(); + this.buf += d; + let nl; + while ((nl = this.buf.indexOf("\n")) >= 0) { + const line = this.buf.slice(0, nl).trim(); this.buf = this.buf.slice(nl + 1); + if (!line || line[0] !== "{") continue; // stray log lines on stdout are skipped, not fatal + let m; try { m = JSON.parse(line); } catch (_) { continue; } + if (m.method && m.id != null) this._serve(m); + else if (m.method) { try { this.o.onNotify && this.o.onNotify(m.method, m.params || {}); } catch (_) {} } + else if (m.id != null && this.pend.has(m.id)) { const r = this.pend.get(m.id); this.pend.delete(m.id); if (m.error) { const e = new Error((m.error && m.error.message) || "ACP error"); e.code = m.error.code; e.data = m.error.data; r.reject(e); } else r.resolve(m.result); } + } + } + async _serve(m) { + let result, error; + try { + if (!this.o.onRequest) throw Object.assign(new Error("method not found: " + m.method), { code: -32601 }); + result = await this.o.onRequest(m.method, m.params || {}); + } catch (e) { error = { code: e.code || -32603, message: e.message || String(e) }; } + this._write(error ? { jsonrpc: "2.0", id: m.id, error } : { jsonrpc: "2.0", id: m.id, result: result === undefined ? null : result }); + } + request(method, params) { + if (this.closed) return Promise.reject(new Error("agent is not running")); + const id = ++this.id; + return new Promise((resolve, reject) => { this.pend.set(id, { resolve, reject }); this._write({ jsonrpc: "2.0", id, method, params: params || {} }); }); + } + notify(method, params) { this._write({ jsonrpc: "2.0", method, params: params || {} }); } + kill(sig) { if (this.p.pid == null) return; try { process.kill(-this.p.pid, sig || "SIGTERM"); } catch (_) { try { this.p.kill(sig || "SIGTERM"); } catch (__) {} } } + close() { try { this.p.stdin.end(); } catch (_) {} } +} + +// Map one session/update into host callbacks. Kept pure for tests. +function routeUpdate(u, h, st) { + if (!u || typeof u !== "object") return; + const t = u.sessionUpdate; + if (t === "agent_message_chunk") { const c = u.content || {}; if (c.type === "text" && c.text) { st.text += c.text; h.onText && h.onText(c.text); } } + else if (t === "agent_thought_chunk") { const c = u.content || {}; if (c.type === "text" && c.text) h.onThought && h.onThought(c.text); } + else if (t === "tool_call") { + const tc = { id: u.toolCallId, title: u.title || u.kind || "tool", kind: u.kind || "other", status: u.status || "pending", input: u.rawInput, locations: u.locations || [], text: contentText(u.content) }; + st.tools.set(tc.id, tc); h.onTool && h.onTool(tc); + } else if (t === "tool_call_update") { + const tc = st.tools.get(u.toolCallId) || { id: u.toolCallId, title: u.title || "tool", kind: u.kind || "other", locations: [] }; + if (u.title) tc.title = u.title; if (u.kind) tc.kind = u.kind; if (u.status) tc.status = u.status; + if (u.rawInput !== undefined) tc.input = u.rawInput; if (u.locations) tc.locations = u.locations; + const txt = contentText(u.content); if (txt) tc.text = txt; + if (u.rawOutput !== undefined) tc.output = u.rawOutput; + st.tools.set(tc.id, tc); h.onToolUpdate && h.onToolUpdate(tc); + } else if (t === "plan") { h.onPlan && h.onPlan(u.entries || []); } + else if (t === "usage_update") { st.ctx = { used: u.used, size: u.size, cost: u.cost }; h.onUsage && h.onUsage(st.ctx); } + else if (t === "current_mode_update") { h.onMode && h.onMode(u.currentModeId); } +} + +// Run ONE prompt turn on an ACP agent. Resolves (never rejects) with +// { ok, interrupted, output, stopReason, usage, ctx, acpFailed, error } +// acpFailed = the handshake itself failed (the host should fall back to its +// classic path); once a session exists, failures are reported as ok:false. +// o: { cmd, args, cwd, env, prompt, plan, model, mcpServers, decide(toolCall, options) -> Promise<"allow"|"allow_always"|"reject"|"cancel">, +// jail(absPath) -> realPath (throws outside), onText, onThought, onTool, onToolUpdate, onPlan, onUsage, onWrite(path), +// ctl: { kids: [] }, idle(kill) -> { touch, clear } (engine-watchdog's idleWatchdog), spawnFn } +function runTurn(o) { + return new Promise((resolve) => { + const st = { text: "", tools: new Map(), ctx: null }; + let sid = null, interrupted = false, settled = false, cancelT = null, wd = null; + const finish = (r) => { if (settled) return; settled = true; if (cancelT) clearTimeout(cancelT); if (wd) wd.clear(); try { client.close(); } catch (_) {} setTimeout(() => client.kill("SIGTERM"), 300); resolve(Object.assign({ output: st.text, ctx: st.ctx, tools: [...st.tools.values()] }, r)); }; + const onRequest = async (method, p) => { + if (method === "session/request_permission") { + if (interrupted) return { outcome: { outcome: "cancelled" } }; + const tc = Object.assign({}, st.tools.get(p.toolCall && p.toolCall.toolCallId) || {}, p.toolCall || {}); + let d = "reject"; + try { d = o.decide ? await o.decide({ id: tc.toolCallId || tc.id, title: tc.title || "", kind: tc.kind || "other", input: tc.rawInput !== undefined ? tc.rawInput : tc.input, locations: tc.locations || [] }, p.options || []) : "allow"; } catch (_) { d = "reject"; } + if (d === "cancel") return { outcome: { outcome: "cancelled" } }; + const optionId = pickOption(p.options, d); + return optionId ? { outcome: { outcome: "selected", optionId } } : { outcome: { outcome: "cancelled" } }; + } + if (method === "fs/read_text_file") { + const real = o.jail(p.path); + let text = fs.readFileSync(real, "utf8"); + if (p.line || p.limit) { const lines = text.split("\n"); const s = Math.max(0, (p.line || 1) - 1); text = lines.slice(s, p.limit ? s + p.limit : undefined).join("\n"); } + return { content: text }; + } + if (method === "fs/write_text_file") { + if (o.plan) throw Object.assign(new Error("plan mode is on: writes are blocked"), { code: -32000 }); + const real = o.jail(p.path); + fs.mkdirSync(path.dirname(real), { recursive: true }); + fs.writeFileSync(real, String(p.content == null ? "" : p.content)); + if (o.onWrite) o.onWrite(real); + return null; + } + throw Object.assign(new Error("method not supported by this client: " + method), { code: -32601 }); + }; + const client = new AcpClient({ + cmd: o.cmd, args: o.args, cwd: o.cwd, env: o.env, spawnFn: o.spawnFn, + onActivity: () => { if (wd) wd.touch(); }, + onNotify: (method, p) => { if (method === "session/update" && (!sid || !p.sessionId || p.sessionId === sid)) routeUpdate(p.update, o, st); }, + onRequest, + onExit: (code, stderr, e) => { if (!settled) finish(sid ? { ok: false, interrupted, error: e ? e.message : "agent exited (code " + code + ")", stderr } : { ok: false, acpFailed: true, interrupted, error: e ? e.message : "agent exited before the handshake (code " + code + ")" + (String(stderr || "").trim() ? ": " + String(stderr).trim().split("\n").slice(-2).join(" | ") : "") }); }, + }); + if (o.idle) wd = o.idle(() => client.kill("SIGKILL")); // hang guard: fires only after a long silence (and never while the user is answering) + if (o.ctl && o.ctl.kids) o.ctl.kids.push(() => { + interrupted = true; + if (sid) client.notify("session/cancel", { sessionId: sid }); + cancelT = setTimeout(() => { client.kill("SIGINT"); setTimeout(() => client.kill("SIGKILL"), 1200); }, 1500); // an agent that ignores cancel is stopped anyway + }); + (async () => { + let init; + try { + init = await withTimeout(client.request("initialize", { protocolVersion: PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: !!o.jail, writeTextFile: !!o.jail }, terminal: false }, clientInfo: { name: "nexus", version: o.version || "" } }), o.handshakeMs || 20000, "initialize timed out"); + if (!init || typeof init.protocolVersion !== "number") throw new Error("not an ACP agent (bad initialize reply)"); + } catch (e) { return finish({ ok: false, acpFailed: true, error: e.message }); } + let sess; + try { + sess = await withTimeout(client.request("session/new", { cwd: o.cwd, mcpServers: toAcpMcpServers(o.mcpServers, init.agentCapabilities) }), o.handshakeMs || 20000, "session/new timed out"); + sid = sess && sess.sessionId; if (!sid) throw new Error("agent returned no session id"); + } catch (e) { return finish({ ok: false, acpFailed: !/auth/i.test(e.message), needsAuth: /auth/i.test(e.message) || e.code === -32000, error: e.message }); } + // Best effort: the engine's own read-only mode for plan, and the user's model. Nexus's + // permission answers enforce plan mode either way, so a refusal here is not fatal. + await applyConfig(client, sid, sess, { plan: o.plan, model: o.model }); + try { + const r = await client.request("session/prompt", { sessionId: sid, prompt: [{ type: "text", text: o.prompt }] }); + const stop = (r && r.stopReason) || "end_turn"; + finish({ ok: stop !== "refusal" && !interrupted && stop !== "cancelled", interrupted: interrupted || stop === "cancelled", stopReason: stop, usage: (r && r.usage) || null }); + } catch (e) { finish({ ok: false, interrupted, error: e.message }); } + })(); + }); +} + +function withTimeout(p, ms, msg) { + let t; return Promise.race([p, new Promise((_, rej) => { t = setTimeout(() => rej(new Error(msg)), ms); })]).finally(() => clearTimeout(t)); +} + +// Select plan mode / model through whichever API the agent exposes: configOptions +// (session/set_config_option) or the older modes list (session/set_mode). +async function applyConfig(client, sid, sess, want) { + const opts = (sess && Array.isArray(sess.configOptions)) ? sess.configOptions : []; + const find = (id) => opts.find((c) => c && (c.id === id || c.category === id)); + const has = (c, v) => c && Array.isArray(c.options) && c.options.some((x) => x && x.value === v); + const tries = []; + const mode = find("mode"); + if (want.plan) { + if (has(mode, "plan")) tries.push(["session/set_config_option", { sessionId: sid, configId: mode.id, value: "plan" }]); + else if (sess && sess.modes && Array.isArray(sess.modes.availableModes) && sess.modes.availableModes.some((m) => m.id === "plan")) tries.push(["session/set_mode", { sessionId: sid, modeId: "plan" }]); + } + const model = find("model"); + if (want.model && has(model, want.model) && model.currentValue !== want.model) tries.push(["session/set_config_option", { sessionId: sid, configId: model.id, value: want.model }]); + const applied = []; + for (const [m, p] of tries) { try { await withTimeout(client.request(m, p), 8000, m + " timed out"); applied.push(m + ":" + (p.value || p.modeId)); } catch (_) {} } + return applied; +} + +// The policy Nexus applies to a permission request. Pure: the host supplies the +// guard/permission checks. Returns "allow" | "reject" | "ask" (host asks the user). +// mode: 0 normal, 1 auto-accept, 2 plan, 3 bypass +// check(toolCall) -> { deny, ask, warn } (strings or null) from guard, permission rules and the project jail +function policyFor(mode, tc, check) { + if (mode === 3) return { decision: "allow" }; + const kind = String(tc.kind || "other"); + if (/(^|[^a-z])ask_user\b/i.test(String(tc.title || "")) || /^mcp__nexus__/.test(String(tc.title || ""))) return { decision: "allow" }; // the Nexus ask bridge (read-only in plan mode) only raises the user's popup + if (mode === 2 && !READ_KINDS.has(kind)) return { decision: "reject", why: "plan mode is on: " + kind + " is blocked" }; + const c = check ? check(tc) || {} : {}; + if (c.deny) return { decision: "reject", why: c.deny }; + if (c.ask) return { decision: "ask", why: c.ask }; // e.g. reaching outside the project: asks even in auto-accept (that accepts edits IN the project) + if (c.warn && mode === 0) return { decision: "ask", why: c.warn }; + return { decision: "allow" }; +} + +// The shell command a tool call will run, when it is an execute call. +function commandOf(tc) { + const i = tc && tc.input; + if (!i || typeof i !== "object") return tc && tc.kind === "execute" ? String(tc.title || "") : ""; + const c = i.command != null ? i.command : i.cmd != null ? i.cmd : i.script; + if (Array.isArray(c)) return c.join(" "); + return c != null ? String(c) : (tc.kind === "execute" ? String(tc.title || "") : ""); +} + +// Tolerant JSONC read (comments, trailing commas) for engine config files. null on failure. +function readJsonc(file) { + let raw; try { raw = fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""); } catch (_) { return null; } + try { return JSON.parse(raw); } catch (_) {} + try { return JSON.parse(raw.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str || "").replace(/,(\s*[}\]])/g, "$1")); } catch (_) { return null; } +} + +// opencode only sends session/request_permission for tools set to "ask". Make edit, bash +// and webfetch ask (so Nexus's plan mode, deny rules and guard apply to them), but never +// override a permission the user configured themselves. Returns the JSON for +// OPENCODE_CONFIG_CONTENT, or null when there is nothing to add. +function opencodePermOverlay(userConfigs) { + const set = new Set(); + for (const c of userConfigs || []) { + if (!c || typeof c !== "object") continue; + if (typeof c.permission === "string") return null; // one blanket setting covers every tool + if (c.permission && typeof c.permission === "object") for (const k of Object.keys(c.permission)) set.add(k); + } + const perm = {}; + for (const k of ["edit", "bash", "webfetch"]) if (!set.has(k)) perm[k] = "ask"; + return Object.keys(perm).length ? JSON.stringify({ permission: perm }) : null; +} +function opencodeUserConfigs(cwd, home, env) { + env = env || process.env; + const xdg = env.XDG_CONFIG_HOME || path.join(home, ".config"); + const files = [path.join(xdg, "opencode", "opencode.json"), path.join(xdg, "opencode", "opencode.jsonc"), path.join(xdg, "opencode", "config.json"), path.join(cwd, "opencode.json"), path.join(cwd, "opencode.jsonc"), path.join(cwd, ".opencode", "opencode.json"), path.join(cwd, ".opencode", "opencode.jsonc")]; + if (env.OPENCODE_CONFIG) files.push(env.OPENCODE_CONFIG); + return files.map(readJsonc).filter(Boolean); +} + +module.exports = { readJsonc, opencodePermOverlay, opencodeUserConfigs, AcpClient, runTurn, routeUpdate, toAcpMcpServers, pickOption, contentText, policyFor, commandOf, applyConfig, PROTOCOL_VERSION, READ_KINDS }; diff --git a/lib/nexus/engines.js b/lib/nexus/engines.js index 9a6b859..632395d 100644 --- a/lib/nexus/engines.js +++ b/lib/nexus/engines.js @@ -5,6 +5,9 @@ // another (verified by test/run.js). `kind`: "stream" = the Claude Code NDJSON driver // (rich token/cost/tools), "cli" = spawn the binary and stream its stdout, "local" = // the in-process Ollama tool loop. `caps` documents which cross-engine features apply. +// `acp` (optional): the engine also speaks the Agent Client Protocol; acp.args(o) builds +// its ACP launch args (o.help = the engine's --help text when acp.needsHelp, so a flag +// that moved between versions is detected, not guessed). null = no ACP on this install. const { codexMcpArgs } = require("./engine-mcp"); // per-run MCP `-c` overrides for codex (pure) const ENGINES = { __proto__: null, // null prototype: a typed name like "toString" is never an engine claude: { @@ -17,6 +20,7 @@ const ENGINES = { __proto__: null, // null prototype: a typed name like "toStrin label: "Gemini CLI", bin: "gemini", install: "npm i -g @google/gemini-cli", kind: "cli", proto: "gemini-json", paid: true, ctx: 1000000, model: "gemini-2.5-pro", models: ["gemini-2.5-pro", "gemini-2.5-flash"], caps: { model: true, mcpInject: true }, mcpMode: "env", mcpEnvVar: "GEMINI_CLI_SYSTEM_SETTINGS_PATH", mcpFormat: "mcpServers", // system-overrides settings file; gemini MERGES mcpServers across scopes, so this only ADDS the nexus bridge (user servers kept) args: (p, o) => { const a = ["--output-format", "json"]; if (o.model) a.push("-m", o.model); if (o.autonomous && !o.readonly) a.push("--yolo"); a.push("-p", p); return a; }, // JSON mode → real token counts (geminiParse) + acp: { needsHelp: true, args: (o) => { const f = /(^|\s)--acp\b/.test(o.help || "") ? "--acp" : /--experimental-acp\b/.test(o.help || "") ? "--experimental-acp" : null; if (!f) return null; const a = []; if (o.model) a.push("-m", o.model); a.push(f); return a; } }, tips: ["Gemini's very large context window is great for whole-repo questions", "set the model with /model (e.g. gemini-2.5-pro, gemini-2.5-flash)", "needs the Gemini CLI installed and authenticated (`gemini`)"], }, codex: { @@ -29,6 +33,7 @@ const ENGINES = { __proto__: null, // null prototype: a typed name like "toStrin label: "OpenCode", bin: "opencode", install: "npm i -g opencode-ai", kind: "cli", paid: true, ctx: 200000, model: "", models: [], caps: { model: true, mcpInject: true }, mcpMode: "env", mcpEnvVar: "OPENCODE_CONFIG", mcpFormat: "opencode", // points at a merged config (per run, user config preserved) args: (p, o) => { const a = ["run"]; if (o.readonly) a.push("--agent", "plan"); if (o.model) a.push("-m", o.model); a.push(p); return a; }, + acp: { args: () => ["acp"], permEnv: "OPENCODE_CONFIG_CONTENT" }, // model + plan agent are chosen over ACP (session config options); permEnv makes its tools ask Nexus tips: ["OpenCode drives whichever provider/model you've configured for it", "prefer Claude or a private local model? switch with /engine"], }, aider: { diff --git a/lib/nexus/landlock.py b/lib/nexus/landlock.py new file mode 100644 index 0000000..4486969 --- /dev/null +++ b/lib/nexus/landlock.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +# Nexus engine sandbox launcher (Linux Landlock, unprivileged, no setuid). +# +# python3 -I landlock.py --probe -> prints the Landlock ABI, exit 0 (or exit 3 + reason) +# NEXUS_LL_POLICY='{"rw":[...],"ro":[...],"deny":[...]}' python3 -I landlock.py -- [args...] +# +# Landlock is allow-list only: the child may read/execute paths under "ro", may also +# write under "rw", and nothing else. "deny" lists paths that must stay unreadable even +# though an ancestor is granted: a granted directory that contains a denied path is not +# granted as a whole; its other entries are granted one by one instead (the directory +# itself gets list-only access). Network access is not restricted. +# The policy is restricted onto this process, then it execs the command, so the engine +# and everything it spawns inherit it. Pure stdlib (ctypes); nothing is installed. +import ctypes, ctypes.util, json, os, struct, sys + +SYS_CREATE, SYS_ADD, SYS_RESTRICT = 444, 445, 446 # same numbers on every architecture +CREATE_VERSION = 1 +RULE_PATH_BENEATH = 1 +PR_SET_NO_NEW_PRIVS = 38 +O_PATH = 0o10000000 +O_CLOEXEC = 0o2000000 + +EXECUTE, WRITE_FILE, READ_FILE, READ_DIR = 1 << 0, 1 << 1, 1 << 2, 1 << 3 +REMOVE_DIR, REMOVE_FILE, MAKE_CHAR, MAKE_DIR = 1 << 4, 1 << 5, 1 << 6, 1 << 7 +MAKE_REG, MAKE_SOCK, MAKE_FIFO, MAKE_BLOCK, MAKE_SYM = 1 << 8, 1 << 9, 1 << 10, 1 << 11, 1 << 12 +REFER, TRUNCATE = 1 << 13, 1 << 14 +FILE_ONLY = EXECUTE | WRITE_FILE | READ_FILE | TRUNCATE + +libc = ctypes.CDLL(ctypes.util.find_library("c") or None, use_errno=True) +libc.syscall.restype = ctypes.c_long +libc.prctl.restype = ctypes.c_int + + +def die(msg, code=3): + sys.stderr.write("nexus-sandbox: " + msg + "\n") + sys.exit(code) + + +def abi(): + v = libc.syscall(SYS_CREATE, None, ctypes.c_size_t(0), ctypes.c_uint32(CREATE_VERSION)) + return v if v > 0 else 0 + + +def handled_for(level): + h = (EXECUTE | WRITE_FILE | READ_FILE | READ_DIR | REMOVE_DIR | REMOVE_FILE | MAKE_CHAR | MAKE_DIR + | MAKE_REG | MAKE_SOCK | MAKE_FIFO | MAKE_BLOCK | MAKE_SYM) + if level >= 2: + h |= REFER + if level >= 3: + h |= TRUNCATE + return h + + +def norm(p): + return os.path.normpath(os.path.abspath(os.path.expanduser(p))) + + +def under(child, parent): + return child == parent or child.startswith(parent.rstrip("/") + "/") + + +def main(): + if len(sys.argv) > 1 and sys.argv[1] == "--probe": + if not sys.platform.startswith("linux"): + die("not Linux") + level = abi() + if not level: + die("Landlock is not enabled in this kernel") + print(level) + return + try: + sep = sys.argv.index("--") + except ValueError: + die("usage: landlock.py -- [args...]", 2) + cmd = sys.argv[sep + 1:] + if not cmd: + die("no command given", 2) + try: + pol = json.loads(os.environ.pop("NEXUS_LL_POLICY", "") or "{}") + except ValueError: + die("bad NEXUS_LL_POLICY", 2) + + level = abi() + if not level: + die("Landlock is not enabled in this kernel") + handled = handled_for(level) + read = EXECUTE | READ_FILE | READ_DIR + write = handled + + attr = struct.pack("=Q", handled) # only handled_access_fs: valid for every ABI + fd = libc.syscall(SYS_CREATE, ctypes.c_char_p(attr), ctypes.c_size_t(len(attr)), ctypes.c_uint32(0)) + if fd < 0: + die("landlock_create_ruleset failed (errno %d)" % ctypes.get_errno()) + + deny = set() + for p in pol.get("deny") or []: + deny.add(norm(p)) + deny.add(os.path.realpath(norm(p))) # a symlinked ~/.ssh is denied at its target too + added = {} + split = set() + + def add(path, access): + try: + pfd = os.open(path, O_PATH | O_CLOEXEC) + except OSError: + return # missing paths are simply not granted + try: + if not os.path.isdir(path): + access &= FILE_ONLY + access &= handled + if not access: + return + buf = ctypes.create_string_buffer(struct.pack("=Qi", access, pfd), 12) + if libc.syscall(SYS_ADD, ctypes.c_int(fd), ctypes.c_int(RULE_PATH_BENEATH), buf, ctypes.c_uint32(0)) != 0: + die("landlock_add_rule failed for %s (errno %d)" % (path, ctypes.get_errno())) + added[path] = added.get(path, 0) | access + finally: + os.close(pfd) + + def grant(path, access, depth=0): + if path in deny: + return + real = os.path.realpath(path) # rules bind to inodes: judge the target, so a link to / or $HOME can't widen the grant + if real in deny: + return + inside = [d for d in deny if under(d, real) and d != real] + if not inside: + add(real, access) + return + if depth > 12 or not os.path.isdir(real) or (real, access) in split: + return + split.add((real, access)) + add(real, READ_DIR) # list the directory, but grant its entries one by one + try: + names = os.listdir(real) + except OSError: + return + for n in names: + grant(os.path.join(real, n), access, depth + 1) + + for p in pol.get("ro") or []: + grant(norm(p), read) + for p in pol.get("rw") or []: + grant(norm(p), write) + + if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0: + die("prctl(NO_NEW_PRIVS) failed (errno %d)" % ctypes.get_errno()) + if libc.syscall(SYS_RESTRICT, ctypes.c_int(fd), ctypes.c_uint32(0)) != 0: + die("landlock_restrict_self failed (errno %d)" % ctypes.get_errno()) + os.close(fd) + os.environ["NEXUS_SANDBOXED"] = "landlock-%d" % level + try: + os.execvp(cmd[0], cmd) + except OSError as e: + die("cannot run %s: %s" % (cmd[0], e.strerror), 127) + + +if __name__ == "__main__": + main() diff --git a/lib/nexus/sandbox.js b/lib/nexus/sandbox.js new file mode 100644 index 0000000..78ed182 --- /dev/null +++ b/lib/nexus/sandbox.js @@ -0,0 +1,100 @@ +"use strict"; +// ================= engine sandbox (Linux Landlock) ================= +// Wraps an engine spawn so the engine, and every process it starts, can read the +// system but NOT the user's secrets (~/.ssh, cloud/CLI tokens, browser profiles, +// shell history), and can write only the project (not in plan mode), the temp dir +// and the engine's own state dirs. Network stays open: cloud engines need it. +// +// Unprivileged: Landlock needs no root, setuid helper or user namespaces (bubblewrap +// is blocked by AppArmor's userns restriction on Ubuntu 24.04+). The policy is applied +// by lib/nexus/landlock.py, a stdlib-only python3 launcher that restricts itself and +// then execs the engine. Where Landlock or python3 is missing, sandboxFor() returns +// null with a reason and the engine runs unsandboxed, as before. +// +// Settings (/sandbox, NEXUS_SANDBOX): "auto" (default) sandboxes plan-mode turns and +// repos whose .nexus config is held back as untrusted; "always" sandboxes every engine +// turn; "off" never does. + +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const { spawnSync } = require("child_process"); + +const LAUNCHER = path.join(__dirname, "landlock.py"); +const MODES = ["auto", "always", "off"]; + +// Under $HOME: never readable by a sandboxed engine. +const HOME_DENY = [ + ".ssh", ".gnupg", ".aws", ".azure", ".kube", ".docker", ".netrc", ".git-credentials", ".npmrc", ".pypirc", + ".vault-token", ".terraform.d", ".password-store", ".pki", ".mozilla", ".thunderbird", ".wrangler", ".darknode", + ".bash_history", ".zsh_history", ".python_history", ".node_repl_history", ".psql_history", ".mysql_history", ".sqlite_history", + ".config/gh", ".config/hub", ".config/gcloud", ".config/doctl", ".config/rclone", ".config/darknode", ".config/configstore", + ".config/.wrangler", ".config/op", ".config/google-chrome", ".config/chromium", ".config/BraveSoftware", ".config/microsoft-edge", + ".config/vivaldi", ".config/opera", ".local/share/keyrings", ".local/share/fish/fish_history", "snap/firefox", "snap/chromium", + ".var/app/org.mozilla.firefox", ".var/app/com.google.Chrome", +]; +// Under $HOME: engine state the engines must write (logins, sessions, caches). +const HOME_WRITE = [ + ".claude", ".claude.json", ".claude.json.backup", ".gemini", ".codex", ".qwen", ".config/goose", ".local/share/goose", + ".config/opencode", ".local/share/opencode", ".local/state/opencode", ".cache", ".npm", ".bun", ".local/state", ".aider", + ".aider.chat.history.md", ".aider.input.history", +]; + +let _probe; // { ok, abi, why } — probed once per process +function probe(force) { + if (_probe && !force) return _probe; + if (process.platform !== "linux") return (_probe = { ok: false, why: "the sandbox needs Linux (Landlock)" }); + if (!fs.existsSync(LAUNCHER)) return (_probe = { ok: false, why: "sandbox launcher missing" }); + const r = spawnSync("python3", ["-I", LAUNCHER, "--probe"], { encoding: "utf8", timeout: 5000 }); + if (r.error) return (_probe = { ok: false, why: "python3 not found (the sandbox launcher needs it)" }); + const abi = parseInt(String(r.stdout || "").trim(), 10); + if (r.status !== 0 || !(abi > 0)) return (_probe = { ok: false, why: (String(r.stderr || "").replace(/^nexus-sandbox: /, "").trim() || "Landlock unavailable") }); + return (_probe = { ok: true, abi }); +} + +const normMode = (v) => { const s = String(v == null ? "" : v).trim().toLowerCase(); return s === "on" ? "always" : MODES.includes(s) ? s : ""; }; + +// Should this turn be sandboxed? -> null, or { writable, reason }. +// setting: "auto" | "always" | "off"; plan: plan mode (read-only); untrusted: repo config held back. +function decide(setting, { plan, untrusted } = {}) { + const s = normMode(setting) || "auto"; + if (s === "off") return null; + if (s === "always") return { writable: !plan, reason: plan ? "plan mode" : "sandbox always" }; + if (plan) return { writable: false, reason: "plan mode" }; + if (untrusted) return { writable: true, reason: "untrusted repo" }; + return null; +} + +// The Landlock policy for one engine run. +function policy({ cwd, home, writable, extraWrite }) { + home = home || os.homedir(); + const tmp = os.tmpdir(); + const rw = ["/dev/null", "/dev/tty", "/dev/pts", "/dev/ptmx", "/dev/shm", tmp]; + if (tmp !== "/tmp") rw.push("/tmp"); + if (writable && cwd) rw.push(path.resolve(cwd)); + for (const r of HOME_WRITE) rw.push(path.join(home, r)); + for (const x of extraWrite || []) if (x) rw.push(path.resolve(x)); + const deny = HOME_DENY.map((r) => path.join(home, r)); + return { ro: ["/"], rw, deny }; +} + +// Rewrite a spawn so it runs under the sandbox. Returns { cmd, args, env }. +function wrap(cmd, args, env, pol) { + const e = Object.assign({}, env || process.env, { NEXUS_LL_POLICY: JSON.stringify(pol) }); + return { cmd: "python3", args: ["-I", LAUNCHER, "--", cmd].concat(args || []), env: e }; +} + +// One call for the host: decide + probe + wrap. Returns { cmd, args, env, sandbox } +// where sandbox is null (not sandboxed; .why says why when it was wanted) or +// { reason, writable, abi }. +function prepare(cmd, args, env, opts) { + opts = opts || {}; + const d = decide(opts.setting, opts); + if (!d) return { cmd, args, env, sandbox: null }; + const pr = probe(); + if (!pr.ok) return { cmd, args, env, sandbox: null, why: pr.why }; + const w = wrap(cmd, args, env, policy({ cwd: opts.cwd, home: opts.home, writable: d.writable, extraWrite: opts.extraWrite })); + return Object.assign(w, { sandbox: { reason: d.reason, writable: d.writable, abi: pr.abi } }); +} + +module.exports = { probe, decide, policy, wrap, prepare, normMode, MODES, HOME_DENY, HOME_WRITE, LAUNCHER }; diff --git a/lib/nexus/shell-run.js b/lib/nexus/shell-run.js index 13e7252..243fe09 100644 --- a/lib/nexus/shell-run.js +++ b/lib/nexus/shell-run.js @@ -15,7 +15,9 @@ function coderShell(command, cwd, opts) { // `sh` left a dev server or test runner holding the output pipe, and the turn hung. // GIT_TERMINAL_PROMPT=0 + a closed stdin make prompts fail fast instead of waiting // for input that can never come. - const p = spawn(win ? "cmd.exe" : "/bin/sh", [win ? "/c" : "-c", command], { cwd, detached: !win, env: Object.assign({}, process.env, { GIT_TERMINAL_PROMPT: "0" }) }); + let bin = win ? "cmd.exe" : "/bin/sh", argv = [win ? "/c" : "-c", command], env = Object.assign({}, process.env, { GIT_TERMINAL_PROMPT: "0" }); + if (opts.sandbox && !win) { const w = require("./sandbox").prepare(bin, argv, env, Object.assign({ cwd }, opts.sandbox)); bin = w.cmd; argv = w.args; env = w.env; if (opts.onSandbox) opts.onSandbox(w); } // /sandbox: the same Landlock fence as engine turns + const p = spawn(bin, argv, { cwd, detached: !win, env }); try { p.stdin.end(); } catch (_) {} // Keep the HEAD and (crucially) the TAIL: test/build runners print the failing // assertions and the "N failed" summary at the END, so a head-only cap hid every diff --git a/package.json b/package.json index 60ee423..b18b21c 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/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 && node test/dashboard.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 && node test/dashboard.test.js && node test/acp-sandbox.test.js", "postinstall": "node scripts/postinstall.js", "docs": "node scripts/gen-nexus-docs.js" }, diff --git a/test/acp-sandbox.test.js b/test/acp-sandbox.test.js new file mode 100644 index 0000000..272530b --- /dev/null +++ b/test/acp-sandbox.test.js @@ -0,0 +1,162 @@ +"use strict"; +// ACP engine transport (lib/nexus/acp-client.js) against a scripted fake agent, and +// the Landlock engine sandbox (lib/nexus/sandbox.js + landlock.py) for real. +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const A = require("../lib/nexus/acp-client"); +const S = require("../lib/nexus/sandbox"); +const Jail = require("../lib/nexus/jail"); + +let pass = 0, fail = 0; +const ok = (name, cond) => { if (cond) pass++; else { fail++; console.log(" FAIL " + name); } }; +const AGENT = path.join(__dirname, "fixtures", "fake-acp-agent.js"); +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nx-acp-")); +const proj = path.join(tmp, "proj"); fs.mkdirSync(proj); +fs.writeFileSync(path.join(tmp, "secret.txt"), "TOPSECRET"); +const logf = path.join(tmp, "agent.log"); +const reqs = () => { try { return fs.readFileSync(logf, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)); } catch (_) { return []; } }; + +const turn = (script, extra) => { + try { fs.unlinkSync(logf); } catch (_) {} + const seen = { text: "", thought: "", tools: [], updates: [], writes: [], asked: [] }; + const o = Object.assign({ + cmd: process.execPath, args: [AGENT], cwd: proj, + env: Object.assign({}, process.env, { FAKE_ACP_SCRIPT: script, FAKE_ACP_LOG: logf }, (extra && extra.env) || {}), + prompt: "do it", jail: (p) => Jail.assertInJail(p, proj), + onText: (t) => { seen.text += t; }, onThought: (t) => { seen.thought += t; }, + onTool: (tc) => seen.tools.push(Object.assign({}, tc)), onToolUpdate: (tc) => seen.updates.push(Object.assign({}, tc)), + onWrite: (p) => seen.writes.push(p), + decide: async (tc, opts) => { seen.asked.push({ tc, opts }); return "allow"; }, + }, Object.assign({}, extra || {}, { env: undefined })); + o.env = Object.assign({}, process.env, { FAKE_ACP_SCRIPT: script, FAKE_ACP_LOG: logf }, (extra && extra.env) || {}); // extra.env adds to the base env instead of replacing it + return A.runTurn(o).then((r) => Object.assign(r, { seen })); +}; + +(async () => { + // ---- pure helpers ---- + ok("pickOption: allow prefers allow_once, reject prefers reject_once, falls back within polarity", + A.pickOption([{ optionId: "a", kind: "allow_always" }, { optionId: "o", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }], "allow") === "o" + && A.pickOption([{ optionId: "a", kind: "allow_always" }], "allow") === "a" + && A.pickOption([{ optionId: "a", kind: "allow_once" }], "reject") === null + && A.pickOption([{ optionId: "r", kind: "reject_always" }], "reject") === "r"); + const ms = A.toAcpMcpServers({ nexus: { command: "node", args: ["x.js"], env: { K: "v" } }, web: { url: "https://h/mcp" }, sse: { type: "sse", url: "https://h/sse" } }, { mcpCapabilities: { http: true } }); + ok("toAcpMcpServers: stdio servers get name/value env pairs; http only when the agent supports it", ms.length === 2 && ms[0].env[0].name === "K" && ms[0].env[0].value === "v" && ms[1].type === "http" && !ms.some((s) => s.type === "sse")); + ok("policyFor: bypass allows everything", A.policyFor(3, { kind: "delete" }).decision === "allow"); + ok("policyFor: plan rejects edit/execute/delete/move/other and allows read/search/think/fetch", + ["edit", "execute", "delete", "move", "other", "switch_mode"].every((k) => A.policyFor(2, { kind: k }).decision === "reject") + && ["read", "search", "think", "fetch"].every((k) => A.policyFor(2, { kind: k }).decision === "allow")); + ok("policyFor: the Nexus ask bridge passes even in plan mode", A.policyFor(2, { kind: "other", title: "nexus_ask_user" }).decision === "allow" && A.policyFor(2, { kind: "other", title: "mcp__nexus__ask_user" }).decision === "allow"); + ok("policyFor: a guard/permission deny rejects in normal and auto-accept", A.policyFor(0, { kind: "execute" }, () => ({ deny: "rm -rf" })).decision === "reject" && A.policyFor(1, { kind: "execute" }, () => ({ deny: "x" })).decision === "reject"); + ok("policyFor: a guard warning asks in normal mode, passes in auto-accept", A.policyFor(0, { kind: "execute" }, () => ({ warn: "w" })).decision === "ask" && A.policyFor(1, { kind: "execute" }, () => ({ warn: "w" })).decision === "allow"); + ok("policyFor: reaching outside the project asks in normal AND auto-accept, is rejected in plan, allowed in bypass", + A.policyFor(0, { kind: "other" }, () => ({ ask: "o" })).decision === "ask" && A.policyFor(1, { kind: "edit" }, () => ({ ask: "o" })).decision === "ask" + && A.policyFor(2, { kind: "other", title: "external_directory" }, () => ({ ask: "o" })).decision === "reject" && A.policyFor(3, { kind: "other" }, () => ({ ask: "o" })).decision === "allow"); + ok("commandOf: reads command/cmd/script and arrays", A.commandOf({ input: { command: "ls -la" } }) === "ls -la" && A.commandOf({ input: { cmd: ["git", "push"] } }) === "git push" && A.commandOf({ kind: "execute", title: "rm x" }) === "rm x" && A.commandOf({ kind: "read", input: {} }) === ""); + ok("contentText: text and diff content", /hello/.test(A.contentText([{ type: "content", content: { type: "text", text: "hello" } }])) && /\+b/.test(A.contentText([{ type: "diff", path: "f", oldText: "a", newText: "b" }]))); + + // ---- end to end with the fake agent ---- + let r = await turn("edit"); + ok("edit: handshake, prompt and end_turn succeed", r.ok && r.stopReason === "end_turn" && !r.acpFailed); + ok("edit: streamed text and thinking reach the host", r.seen.text === "applied" && r.seen.thought === "thinking" && r.output === "applied"); + ok("edit: the tool call and its update reach the host with kind/status", r.seen.tools.length === 1 && r.seen.tools[0].kind === "edit" && r.seen.updates.some((u) => u.status === "completed")); + ok("edit: the permission request goes to decide() with the agent's options", r.seen.asked.length === 1 && r.seen.asked[0].tc.kind === "edit" && r.seen.asked[0].opts.length === 3); + ok("edit: the write lands through the jailed client fs and is reported", fs.readFileSync(path.join(proj, "note.txt"), "utf8") === "hello from acp" && r.seen.writes.length === 1); + ok("edit: real token usage comes back from the prompt result", r.usage && r.usage.inputTokens === 120 && r.usage.outputTokens === 7 && r.usage.cachedReadTokens === 40); + const init = reqs().find((m) => m.method === "initialize"); + ok("initialize advertises protocol 1 and client fs (jail present), no terminal", init && init.params.protocolVersion === 1 && init.params.clientCapabilities.fs.writeTextFile === true && init.params.clientCapabilities.terminal === false); + fs.unlinkSync(path.join(proj, "note.txt")); + + r = await turn("edit", { decide: async () => "reject" }); + ok("reject: a rejected edit is never written", !fs.existsSync(path.join(proj, "note.txt")) && r.seen.text === "skipped"); + const permReply = reqs().find((m) => m.id && m.result && m.result.outcome); + ok("reject: the reply selects the reject_once option", permReply && permReply.result.outcome.optionId === "no1"); + + r = await turn("edit", { plan: true, decide: async () => "allow" }); + ok("plan: plan mode is selected through session/set_config_option", reqs().some((m) => m.method === "session/set_config_option" && m.params.configId === "mode" && m.params.value === "plan")); + ok("plan: client fs refuses writes even when a decision allowed them", !fs.existsSync(path.join(proj, "note.txt")) && /write failed: plan mode/.test(r.seen.text)); + + r = await turn("edit", { model: "b" }); + ok("model: a model the agent offers is selected", reqs().some((m) => m.method === "session/set_config_option" && m.params.configId === "model" && m.params.value === "b")); + r = await turn("edit", { model: "zzz" }); + ok("model: a model the agent does not offer is not sent", !reqs().some((m) => m.method === "session/set_config_option" && m.params.configId === "model")); + fs.rmSync(path.join(proj, "note.txt"), { force: true }); + + r = await turn("outside"); + ok("jail: the client fs refuses a read outside the project", /refused/.test(r.seen.text) && !/TOPSECRET/.test(r.seen.text)); + + r = await turn("exec", { env: { FAKE_ACP_CMD: "git push --force" }, decide: async (tc) => (A.commandOf(tc) === "git push --force" ? "reject" : "allow") }); + ok("exec: the execute call's command reaches decide() and a reject stops it", r.tools[0] && A.commandOf(r.tools[0]) === "git push --force" && r.seen.text === "skipped" && r.tools[0].status === "failed"); + + const ctl = { kids: [] }; + const pr = turn("slow", { ctl }); + await new Promise((res) => setTimeout(res, 400)); + for (const k of ctl.kids) k(); + r = await pr; + ok("cancel: ctl kill sends session/cancel and the turn ends interrupted", r.interrupted && !r.ok && r.stopReason === "cancelled" && reqs().some((m) => m.method === "session/cancel")); + + r = await turn("badinit"); + ok("badinit: a failed handshake is flagged acpFailed so the host falls back", !r.ok && r.acpFailed === true); + r = await A.runTurn({ cmd: path.join(tmp, "no-such-binary"), args: [], cwd: proj, prompt: "x" }); + ok("spawn error: a missing binary is acpFailed, never a throw", !r.ok && r.acpFailed === true); + + // ---- sandbox ---- + ok("sandbox.decide: off never, always everywhere (read-only in plan), auto only plan or untrusted", + S.decide("off", { plan: true, untrusted: true }) === null + && S.decide("always", {}).writable === true && S.decide("always", { plan: true }).writable === false + && S.decide("auto", {}) === null && S.decide("auto", { plan: true }).writable === false && S.decide("auto", { untrusted: true }).writable === true + && S.decide("", { plan: true }).writable === false && S.normMode("on") === "always" && S.normMode("bogus") === ""); + const fakeHome = path.join(tmp, "home"); fs.mkdirSync(path.join(fakeHome, ".ssh"), { recursive: true }); + const pol = S.policy({ cwd: proj, home: fakeHome, writable: true }); + ok("sandbox.policy: reads /, writes the project + tmp + engine state, denies ~/.ssh and tokens", + pol.ro[0] === "/" && pol.rw.includes(proj) && pol.rw.includes(os.tmpdir()) && pol.rw.includes(path.join(fakeHome, ".claude")) + && pol.deny.includes(path.join(fakeHome, ".ssh")) && pol.deny.includes(path.join(fakeHome, ".config", "gh")) && pol.deny.includes(path.join(fakeHome, ".bash_history"))); + ok("sandbox.policy: plan mode leaves the project read-only", !S.policy({ cwd: proj, home: fakeHome, writable: false }).rw.includes(proj)); + ok("sandbox.prepare: off returns the spawn unchanged", (() => { const p = S.prepare("x", ["a"], {}, { setting: "off", plan: true }); return p.cmd === "x" && p.args[0] === "a" && p.sandbox === null; })()); + + const pb = S.probe(); + if (!pb.ok) console.log(" (skipping live sandbox checks: " + pb.why + ")"); + else { + fs.writeFileSync(path.join(fakeHome, ".ssh", "id_ed25519"), "PRIVATE"); + const outside = path.join(fakeHome, "outside.txt"); + // the fake home lives under the (writable) temp dir, so this also proves a denied path + // inside a granted directory stays denied + const run = (writable, target) => { + const w = S.wrap(process.execPath, [AGENT], Object.assign({}, process.env, { FAKE_ACP_SCRIPT: "sandbox", FAKE_ACP_PATH: target, FAKE_ACP_SECRET: path.join(fakeHome, ".ssh", "id_ed25519") }), Object.assign(S.policy({ cwd: proj, home: fakeHome, writable }), { rw: S.policy({ cwd: proj, home: fakeHome, writable }).rw.filter((p) => p !== os.tmpdir() && p !== "/tmp") })); + return A.runTurn({ cmd: w.cmd, args: w.args, env: w.env, cwd: proj, prompt: "x" }); + }; + r = await run(true, path.join(proj, "in.txt")); + ok("sandbox live: the engine runs under Landlock and can write the project", r.ok && /^wrote /.test(r.output) && /landlock-\d/.test(r.output)); + ok("sandbox live: ~/.ssh is unreadable even though its parent is readable", /secret-EACCES/.test(r.output)); + r = await run(true, outside); + ok("sandbox live: a write outside the project is denied", /^denied EACCES/.test(r.output) && !fs.existsSync(outside)); + r = await run(false, path.join(proj, "plan.txt")); + ok("sandbox live: plan mode cannot write the project", /^denied EACCES/.test(r.output) && !fs.existsSync(path.join(proj, "plan.txt"))); + const { coderShell } = require("../lib/nexus/shell-run"); + const cs = await coderShell("echo a > cs.txt; cat " + path.join(fakeHome, ".ssh", "id_ed25519") + "; echo b > " + path.join(fakeHome, "cs-out.txt") + "; echo end", proj, { sandbox: { setting: "always", cwd: proj, home: fakeHome } }); + ok("sandbox live: the local agent's run_command (coderShell) runs fenced: project write ok, secret and outside write denied", /end/.test(cs.output) && fs.existsSync(path.join(proj, "cs.txt")) && !/PRIVATE/.test(cs.output) && !fs.existsSync(path.join(fakeHome, "cs-out.txt"))); + const pp = S.prepare("node", ["-v"], process.env, { setting: "auto", plan: true, cwd: proj, home: fakeHome }); + ok("sandbox.prepare: auto + plan wraps the spawn in the launcher", pp.cmd === "python3" && pp.args.includes(S.LAUNCHER) && pp.sandbox && pp.sandbox.writable === false && JSON.parse(pp.env.NEXUS_LL_POLICY).deny.length > 10); + } + + // ---- settings + host wiring ---- + const NS = require("../lib/cli/nexus-settings"); + const sh = path.join(tmp, "sh"); fs.mkdirSync(sh); + let rs = NS.resolve(sh, {}); + ok("settings: acp and sandbox default to auto", rs.value.acp === "auto" && rs.value.sandbox === "auto"); + rs = NS.resolve(sh, { NEXUS_ACP: "off", NEXUS_SANDBOX: "on" }); + ok("settings: NEXUS_ACP=off and NEXUS_SANDBOX=on (= always) pin one launch", rs.value.acp === "off" && rs.value.sandbox === "always" && rs.source.sandbox === "env"); + rs = NS.resolve(sh, { NEXUS_SANDBOX: "bogus" }); + ok("settings: an invalid NEXUS_SANDBOX is ignored", rs.value.sandbox === "auto"); + const src = fs.readFileSync(path.join(__dirname, "..", "darknode.js"), "utf8"); + ok("host: claude turns and classic engine turns carry the sandbox options", /disallow: mode === 2 \? READONLY_TOOLS : undefined, sandbox: sbxOpts\(\) \|\| undefined \}\);/.test(src) && /\{ sandbox: sbxOpts\(\) \|\| undefined, onSandbox \}\)\)\.then\(\(res\) =>/.test(src)); + ok("host: runEngineTask and runClaudeStream wrap the spawn through Sandbox.prepare", (src.match(/Sandbox\.prepare\(/g) || []).length >= 3); + ok("host: ACP is skipped when /acp is off or the engine failed its handshake this session, and falls back to the classic turn", /if \(acpMode === "off" \|\| !m \|\| !m\.acp \|\| acpBroken\[eng\]\) return null;/.test(src) && /if \(acpL\) acpEngineTurn\(acpL, mdl, classicTurn,/.test(src) && /return fallback\(\);/.test(src)); + ok("host: an engine permission ask holds the hang watchdog while the user decides", /engineWaits\.n\+\+;[\s\S]{0,200}askUser\([\s\S]{0,900}finally \{ engineWaits\.n--; \}/.test(src)); + ok("host: a non-read tool call touching a path outside the project (or opencode's external_directory ask) asks the user", /if \(outside \|\| tc\.title === "external_directory"\) return \{ ask:/.test(src)); + ok("host: the opencode permission overlay is skipped in bypass mode and when the user set OPENCODE_CONFIG_CONTENT", /!process\.env\.OPENCODE_CONFIG_CONTENT && mode !== 3/.test(src)); + + try { fs.rmSync(tmp, { recursive: true, force: true }); } catch (_) {} + console.log("acp-sandbox: " + pass + " passed, " + fail + " failed"); + if (fail) process.exit(1); +})(); diff --git a/test/fixtures/fake-acp-agent.js b/test/fixtures/fake-acp-agent.js new file mode 100644 index 0000000..71ab886 --- /dev/null +++ b/test/fixtures/fake-acp-agent.js @@ -0,0 +1,70 @@ +#!/usr/bin/env node +"use strict"; +// A scripted ACP agent for tests. FAKE_ACP_SCRIPT picks the behaviour: +// edit — asks permission to edit, writes note.txt via the client fs on allow +// exec — asks permission to run FAKE_ACP_CMD (execute kind) +// slow — streams forever until session/cancel, then stops with "cancelled" +// badinit — exits before answering initialize +// outside — tries to read ../secret.txt through the client fs +// sandbox — writes FAKE_ACP_PATH directly from this process and reports the result +// Every request it receives is appended to FAKE_ACP_LOG (one JSON line each). +const fs = require("fs"); +const script = process.env.FAKE_ACP_SCRIPT || "edit"; +const log = (m) => { if (process.env.FAKE_ACP_LOG) fs.appendFileSync(process.env.FAKE_ACP_LOG, JSON.stringify(m) + "\n"); }; +if (script === "badinit") { process.stdout.write("not json at all\n"); process.exit(3); } +let buf = "", id = 1000, cancelled = false; +const pend = new Map(); +const send = (o) => process.stdout.write(JSON.stringify(Object.assign({ jsonrpc: "2.0" }, o)) + "\n"); +const ask = (method, params) => new Promise((res) => { const i = ++id; pend.set(i, res); send({ id: i, method, params }); }); +const update = (sessionId, u) => send({ method: "session/update", params: { sessionId, update: u } }); +const text = (sid, t) => update(sid, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: t } }); + +async function prompt(m) { + const sid = m.params.sessionId; + update(sid, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "thinking" } }); + if (script === "edit" || script === "exec") { + const exec = script === "exec"; + const tc = { toolCallId: "t1", title: exec ? "bash" : "edit note.txt", kind: exec ? "execute" : "edit", status: "pending", rawInput: exec ? { command: process.env.FAKE_ACP_CMD || "ls" } : { path: "note.txt" }, locations: exec ? [] : [{ path: "note.txt" }] }; + update(sid, Object.assign({ sessionUpdate: "tool_call" }, tc)); + const r = await ask("session/request_permission", { sessionId: sid, toolCall: tc, options: [{ optionId: "ok1", name: "Allow", kind: "allow_once" }, { optionId: "ok2", name: "Always", kind: "allow_always" }, { optionId: "no1", name: "Reject", kind: "reject_once" }] }); + const allowed = r.result && r.result.outcome && r.result.outcome.outcome === "selected" && /^ok/.test(r.result.outcome.optionId); + if (allowed && !exec) { const w = await ask("fs/write_text_file", { sessionId: sid, path: process.cwd() + "/note.txt", content: "hello from acp" }); if (w.error) text(sid, "write failed: " + w.error.message); } + update(sid, { sessionUpdate: "tool_call_update", toolCallId: "t1", status: allowed ? "completed" : "failed", content: [{ type: "content", content: { type: "text", text: allowed ? "done" : "rejected" } }] }); + text(sid, allowed ? "applied" : "skipped"); + return { stopReason: "end_turn", usage: { inputTokens: 120, outputTokens: 7, totalTokens: 127, cachedReadTokens: 40 } }; + } + if (script === "outside") { + const r = await ask("fs/read_text_file", { sessionId: sid, path: process.cwd() + "/../secret.txt" }); + text(sid, r.error ? "refused: " + r.error.message : "read: " + r.result.content); + return { stopReason: "end_turn" }; + } + if (script === "sandbox") { + let res; try { fs.writeFileSync(process.env.FAKE_ACP_PATH, "x"); res = "wrote"; } catch (e) { res = "denied " + e.code; } + let rd; try { fs.readFileSync(process.env.FAKE_ACP_SECRET, "utf8"); rd = "read-secret"; } catch (e) { rd = "secret-" + e.code; } + text(sid, res + " " + rd + " " + (process.env.NEXUS_SANDBOXED || "unsandboxed")); + return { stopReason: "end_turn" }; + } + if (script === "slow") { + while (!cancelled) { text(sid, "."); await new Promise((r) => setTimeout(r, 30)); } + return { stopReason: "cancelled" }; + } + text(sid, "hi"); + return { stopReason: "end_turn" }; +} + +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (d) => { + buf += d; let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl); buf = buf.slice(nl + 1); if (!line.trim()) continue; + const m = JSON.parse(line); log(m); + if (m.id != null && !m.method && pend.has(m.id)) { pend.get(m.id)(m); pend.delete(m.id); continue; } + if (m.method === "initialize") send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: { mcpCapabilities: { http: true } }, authMethods: [] } }); + else if (m.method === "session/new") send({ id: m.id, result: { sessionId: "s1", configOptions: [{ id: "mode", category: "mode", type: "select", currentValue: "build", options: [{ value: "build" }, { value: "plan" }] }, { id: "model", category: "model", type: "select", currentValue: "a", options: [{ value: "a" }, { value: "b" }] }] } }); + else if (m.method === "session/set_config_option") send({ id: m.id, result: {} }); + else if (m.method === "session/prompt") prompt(m).then((r) => send({ id: m.id, result: r })); + else if (m.method === "session/cancel") cancelled = true; + else if (m.id != null) send({ id: m.id, error: { code: -32601, message: "nope" } }); + } +}); +process.stdin.on("end", () => process.exit(0)); diff --git a/test/run.js b/test/run.js index 41fcd7c..2f8e3fc 100644 --- a/test/run.js +++ b/test/run.js @@ -1634,7 +1634,7 @@ group("help reference (single source of truth)"); ok("side panel: a known /command typed in the follow-up box runs (or queues mid-turn) instead of being sent to the model as a question; a /path question still asks", /if \(\/\^\\\/\[a-z\]\/i\.test\(q\) && allCmds\(\)\.some\(\(c\) => c\[0\] === sideName\(q\)\)\) \{ btw = null; if \(busy && !isInstant\(q\)\) nextQueue\.push\(q\); else handleSlash\(q\);/.test(src)); ok("Ctrl+X: a side command draft (/btw, /cost...) opens now instead of being queued or interrupting the turn", /if \(v && isInstant\(v\)\) \{ handleSlash\(v\); render\(\); return; \}/.test(src)); ok("trust: an untrusted repo's .nexus/config.json apiBase/apiKey is held back until /trust, and is part of the trust digest", /if \(\(cfg\.apiBase \|\| cfg\.apiKey\) && !isRepoTrusted\(cwd\)\) \{ _heldRepoApi = /.test(src) && /if \(_heldRepoApi\) \{ applyRepoApi\(_heldRepoApi\); _heldRepoApi = null; \}/.test(src) && /const api = repoApiFingerprint\(cwd\); if \(api\) h\.update/.test(src) && !/process\.env\.DARKNODE_API_BASE = cfg\.apiBase/.test(src)); - ok("plan mode: external engines run without autonomy flags in their read-only mode; claude uses --permission-mode plan with only the ask bridge", /runEngineTask\(engine, promptText, cwd, mode !== 2, cont, onChunk, ctl, mdl, undefined, mode === 2 \? Object\.assign\(\{\}, engineMcpLaunch\(engine, true\), \{ readonly: true \}\)/.test(src) && /mcpConfigPath: engineMcpConfigPath\(mode === 2\), readonly: mode === 2,/.test(src)); + ok("plan mode: external engines run without autonomy flags in their read-only mode; claude uses --permission-mode plan with only the ask bridge", /runEngineTask\(engine, promptText, cwd, mode !== 2, cont, onChunk, ctl, mdl, undefined, Object\.assign\(\{\}, mode === 2 \? Object\.assign\(\{\}, engineMcpLaunch\(engine, true\), \{ readonly: true \}\)/.test(src) && /mcpConfigPath: engineMcpConfigPath\(mode === 2\), readonly: mode === 2,/.test(src)); ok("deny rules: a run_command deny also screens verify/bisect/sessions by the command they will run", /if \(kind === "deny" && permCanon\(rtool\) === "run_command" && permCanon\(name\) !== "run_command" && isExecTool\(name\)\)/.test(src)); ok("path jail: file/src/source/destination are canonicalised too, not only path/to/dest/from", /for \(const k of \["path", "file", "to", "dest", "destination", "from", "src", "source"\]\)/.test(src)); ok("Ctrl+X: a newly typed draft always sends now, even after an earlier Ctrl+X started the queue", /if \(curTurnFromQueue && !v\) \{ pasteNotice = "already running your queue/.test(src) && !/queued to run next — /.test(src));