From 2243c0434c2cef1a33eef5a19c3423a319a7ae6a Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Fri, 20 Nov 2026 17:09:49 -0800 Subject: [PATCH] fix(nexus): gate repo API config behind trust, make plan mode read-only, close deny/jail gaps - An untrusted repo's .nexus/config.json apiBase/apiKey is no longer applied until /trust (or DARKNODE_TRUST_REPO=1); those keys are folded into the trust digest so changing them re-prompts. - Plan mode now runs every engine in its own read-only mode: claude --permission-mode plan (ask bridge still allowed), codex --sandbox read-only, gemini without --yolo, opencode --agent plan, aider --dry-run. The MCP bridge drops user servers and hides the sessions tool in plan mode. - A run_command deny rule now also screens verify/bisect/sessions and the other shell-running tools by the command they will run. - The path jail canonicalises file/src/source/destination as well. --- darknode.js | 46 +++++++++++++++++++++++++++-------------- lib/nexus/ask-mcp.js | 4 +++- lib/nexus/engine-mcp.js | 4 ++-- lib/nexus/engines.js | 10 ++++----- test/run.js | 10 +++++++++ 5 files changed, 50 insertions(+), 24 deletions(-) diff --git a/darknode.js b/darknode.js index 535b7ae..b86f47c 100755 --- a/darknode.js +++ b/darknode.js @@ -1642,8 +1642,10 @@ async function aiCoder(argv) { const lean = leanFlag || !!cfg.lean; // minimal-output mode (also used for read/step budgets) // Any-model support: an OpenAI-compatible endpoint (from .nexus/config.json or // env) turns the local engine into a driver for ANY model. Env wins over config. - if (cfg.apiBase && !process.env.DARKNODE_API_BASE) process.env.DARKNODE_API_BASE = cfg.apiBase; - if (cfg.apiKey && !process.env.DARKNODE_API_KEY) process.env.DARKNODE_API_KEY = cfg.apiKey; + // A repo's apiBase/apiKey would send your prompts, code and API key to whatever server + // it names, and that server's tool calls would run here, so they wait for /trust. + if ((cfg.apiBase || cfg.apiKey) && !isRepoTrusted(cwd)) { _heldRepoApi = { apiBase: cfg.apiBase, apiKey: cfg.apiKey }; _untrustedRepoConfig = true; delete cfg.apiBase; delete cfg.apiKey; if (printMode) console.error(" " + yellow("note: ignoring apiBase/apiKey in this repo's .nexus/config.json until you trust it (/trust in the TUI, or DARKNODE_TRUST_REPO=1)")); } + applyRepoApi(cfg); const _instr = require("./lib/nexus/instructions").loadInstructions(cwd, { allowOutside: isRepoTrusted(cwd) }); // AGENTS.md / CLAUDE.md / GEMINI.md / .cursorrules root->cwd, then .nexus/NEXUS.md let nexusMd = _instr.text; const avail = {}; for (const e of ENGINE_ORDER) avail[e] = engineAvail(e); @@ -1945,7 +1947,7 @@ 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 }); + const 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 const p = _cp.spawn(cmd, args, { cwd, env: spawnEnv, detached: process.platform !== "win32" }); // own process group so an interrupt kills the whole tree @@ -1983,6 +1985,7 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) { if (opts.maxBudgetUsd) args.push("--max-budget-usd", String(opts.maxBudgetUsd)); if (opts.maxTurns) args.push("--max-turns", String(opts.maxTurns)); if (opts.disallow && opts.disallow.length) args.push("--disallowed-tools", ...opts.disallow); + if (opts.readonly && opts.mcpConfigPath) args.push("--allowed-tools", "mcp__nexus__ask_user"); // plan mode still lets the model ask the user 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 @@ -2102,12 +2105,20 @@ const keptNote = () => { const k = nexusRestore.kept || []; return k.length ? " // them for repos the operator has explicitly trusted. Trust lives OUTSIDE the repo // (~/.darknode/trusted-repos.json) so a malicious repo can't mark itself trusted. let _untrustedRepoConfig = false; +let _heldRepoApi = null; // a repo's apiBase/apiKey held back until /trust +function applyRepoApi(c) { + if (c && c.apiBase && !process.env.DARKNODE_API_BASE) process.env.DARKNODE_API_BASE = c.apiBase; + if (c && c.apiKey && !process.env.DARKNODE_API_KEY) process.env.DARKNODE_API_KEY = c.apiKey; +} +// Only the risky keys of .nexus/config.json are bound into trust (Nexus itself rewrites +// engine/model there), and only when present, so existing trust entries stay valid. +function repoApiFingerprint(cwd) { try { const c = JSON.parse(stripBom(require("fs").readFileSync(require("path").join(cwd, ".nexus", "config.json"), "utf8"))); return c && (c.apiBase || c.apiKey) ? JSON.stringify([String(c.apiBase || ""), String(c.apiKey || "")]) : ""; } catch (_) { return ""; } } function trustFile() { return require("path").join(darknodeHome(), "trusted-repos.json"); } // Trust is bound to the CONTENT of the files that run commands or loosen the guard: a git pull or an // agent edit that changes them after /trust leaves the repo untrusted again until the operator re-trusts it. const TRUST_FILES = [".nexus/mcp.json", ".mcp.json", ".nexus/hooks.json", ".nexus/permissions.json", ".nexus/policy.json"]; let _trustChanged = false; -function trustDigest(cwd) { const fs = require("fs"), path = require("path"); const h = require("crypto").createHash("sha256"); for (const f of TRUST_FILES) { let c = "\u0000missing"; try { c = fs.readFileSync(path.join(cwd, f), "utf8"); } catch (_) {} h.update(f + "\u0000" + c + "\u0000"); } return h.digest("hex"); } +function trustDigest(cwd) { const fs = require("fs"), path = require("path"); const h = require("crypto").createHash("sha256"); for (const f of TRUST_FILES) { let c = "\u0000missing"; try { c = fs.readFileSync(path.join(cwd, f), "utf8"); } catch (_) {} h.update(f + "\u0000" + c + "\u0000"); } const api = repoApiFingerprint(cwd); if (api) h.update(".nexus/config.json#api\u0000" + api + "\u0000"); return h.digest("hex"); } function readTrustList() { try { const l = JSON.parse(require("fs").readFileSync(trustFile(), "utf8")); return Array.isArray(l) ? l : []; } catch (_) { return []; } } function trustState(cwd) { // "ok" | "changed" | "no" const rp = require("path").resolve(cwd), list = readTrustList(); @@ -2296,10 +2307,13 @@ function permMatch(rule, name, a, kind) { let r = String(rule || "").trim(); if (!r) return false; const bm = /^Bash\((.*)\)$/i.exec(r); if (bm) r = "run_command:" + bm[1]; const ix = r.indexOf(":"); const rtool = ix < 0 ? r : r.slice(0, ix); const rpat = ix < 0 ? "" : r.slice(ix + 1); - const tool = name; + let tool = name; + // a run_command deny also covers every other tool that reaches a shell (verify, bisect, sessions...), + // judged on the command it will actually run - else a denied `git push` slips through as verify {command} + if (kind === "deny" && permCanon(rtool) === "run_command" && permCanon(name) !== "run_command" && isExecTool(name)) { const c = execCommand(name, a); if (c == null) return !rpat || rpat === "*"; tool = "run_command"; a = { command: c }; } if (rtool.trim() !== "*" && permCanon(rtool) !== permCanon(tool)) return false; if (!rpat || rpat === "*") return true; - const target = String(a.command || a.path || a.to || a.dest || a.from || a.url || a.query || ""); + const target = String(a.command || a.path || a.file || a.to || a.dest || a.destination || a.from || a.src || a.source || a.url || a.query || ""); if (a.command && permCanon(tool) === "run_command") { const { segs, hidden } = cmdSegments(a.command); const glob = rpat.includes("*") ? (() => { try { return new RegExp("^" + rpat.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$"); } catch (_) { return null; } })() : null; @@ -4098,19 +4112,19 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { // Build (or reuse) the per-engine MCP config: the Nexus ask bridge plus any // servers the user configured in a trusted .nexus/mcp.json. Returns a file // path for claude's --mcp-config, or null if the bridge couldn't open. - const engineMcpServers = () => { + const engineMcpServers = (readonly) => { const b = ensureAskBridge(); if (!b) return null; - try { return buildEngineMcpServers({ sockPath: b.sockPath, askMcpPath: ASK_MCP_PATH, userServers: loadMcpConfig(cwd) || {} }); } catch (_) { return null; } + try { return buildEngineMcpServers({ sockPath: b.sockPath, askMcpPath: ASK_MCP_PATH, userServers: loadMcpConfig(cwd) || {}, readonly: !!readonly }); } catch (_) { return null; } }; - const engineMcpConfigPath = () => { const servers = engineMcpServers(); if (!servers) return null; try { return writeMcpConfigFile(path.join(cwd, ".nexus"), servers); } catch (_) { return null; } }; + const engineMcpConfigPath = (readonly) => { const servers = engineMcpServers(readonly); if (!servers) return null; try { return writeMcpConfigFile(path.join(cwd, ".nexus"), servers); } catch (_) { return null; } }; // Per-engine injection of the ask bridge for the CLI engines (claude uses // --mcp-config directly). Returns the `extra` to hand runEngineTask: codex // takes -c overrides via mcpServers; opencode is pointed at a merged config // file via $OPENCODE_CONFIG (the user's own opencode config is preserved). - const engineMcpLaunch = (eng) => { + const engineMcpLaunch = (eng, readonly) => { const m = ENGINES[eng] || {}; if (!engineCap(eng, "mcpInject")) return undefined; - const servers = engineMcpServers(); if (!servers) return undefined; + const servers = engineMcpServers(readonly); if (!servers) return undefined; if (m.mcpMode === "env") { let obj, fname; if (m.mcpFormat === "opencode") { // opencode's own schema; merge INTO a copy of the user's project config @@ -4130,7 +4144,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { // 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(), 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 }); // /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; @@ -4513,7 +4527,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, true, cont, onChunk, ctl, mdl, undefined, engineMcpLaunch(engine)).then((res) => { + runEngineTask(engine, promptText, cwd, mode !== 2, cont, onChunk, ctl, mdl, undefined, mode === 2 ? Object.assign({}, engineMcpLaunch(engine, true), { readonly: true }) : engineMcpLaunch(engine)).then((res) => { const raw = res.output || ""; let display = raw, inD, outD; if (jsonProto) { @@ -4608,7 +4622,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { // and hand every later check + the tool itself the canonical project- // relative path — so `cfg -> .env`, `.nexus/./x` or `../x` can't slip past. if (/^(read_file|list_dir|write_file|edit_file|multi_edit|multiedit|undo_edit|delete|delete_file|rm|move|move_file|rename|copy|copy_file)$/.test(name)) { - try { for (const k of ["path", "to", "dest", "from"]) if (a[k] != null && a[k] !== "") { const real = Jail.assertInJail(a[k], cwd); a[k] = path.relative(Jail.canonical(path.resolve(cwd)), real) || "."; } } + try { for (const k of ["path", "file", "to", "dest", "destination", "from", "src", "source"]) if (a[k] != null && a[k] !== "") { const real = Jail.assertInJail(a[k], cwd); a[k] = path.relative(Jail.canonical(path.resolve(cwd)), real) || "."; } } catch (e) { result = { error: e.message }; blocked = true; card.status = "err"; } } if (!blocked && mode === 2 && isPlanBlocked(name) && !(name === "replace_in_files" && (a.dry_run === true || a.preview === true))) { result = { error: "plan mode is on — file/system changes are blocked. Describe the plan instead, then switch mode with shift+tab to execute." }; blocked = true; card.status = "err"; } @@ -5445,7 +5459,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { }); } else if (cmd === "/trust") { - if (trustRepo(cwd)) { _untrustedRepoConfig = false; if (heldAllow.length) { perms.allow = heldAllow.concat(perms.allow.filter((r) => !heldAllow.includes(r))); heldAllow = []; } mcpServers = []; connectMcp().then(() => render()); transcript.push({ role: "system", text: "trusted this workspace (" + gray(cwd) + ") — its .nexus MCP servers and permission allow rules now load; hooks and any policy.json relaxations apply on next launch." }); } + if (trustRepo(cwd)) { _untrustedRepoConfig = false; if (_heldRepoApi) { applyRepoApi(_heldRepoApi); _heldRepoApi = null; } if (heldAllow.length) { perms.allow = heldAllow.concat(perms.allow.filter((r) => !heldAllow.includes(r))); heldAllow = []; } mcpServers = []; connectMcp().then(() => render()); transcript.push({ role: "system", text: "trusted this workspace (" + gray(cwd) + ") — its .nexus MCP servers and permission allow rules now load; hooks and any policy.json relaxations apply on next launch." }); } else transcript.push({ role: "system", text: red("could not record trust") }); } else if (cmd === "/mcp") { @@ -6597,7 +6611,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } catch (_) {} })(); // warn once if this repo ships MCP servers / hooks but isn't trusted (they were NOT run) - if (_untrustedRepoConfig) transcript.push({ role: "system", text: yellow(_trustChanged ? "warning: this workspace's MCP servers, hooks, permission rules or policy changed since you trusted it — not loaded until you review them and re-trust. " : "warning: this workspace defines MCP servers, hooks, permission allow rules and/or policy relaxations — not loaded because the repo isn't trusted. ") + "Run " + cyan("/trust") + " to enable them" + gray(" (or export DARKNODE_TRUST_REPO=1)") }); + if (_untrustedRepoConfig) transcript.push({ role: "system", text: yellow(_trustChanged ? "warning: this workspace's MCP servers, hooks, permission rules, policy or API endpoint changed since you trusted it — not loaded until you review them and re-trust. " : "warning: this workspace defines MCP servers, hooks, permission allow rules, policy relaxations and/or an API endpoint (apiBase) — not loaded because the repo isn't trusted. ") + "Run " + cyan("/trust") + " to enable them" + gray(" (or export DARKNODE_TRUST_REPO=1)") }); refreshGit(); // populate the status-bar branch indicator try { Composer.cleanupDroppedTails(); } catch (_) {} // sweep paste-remainder temp files older than 24h let imgCounter = 0; // fallback running number when an image's folder position can't be read diff --git a/lib/nexus/ask-mcp.js b/lib/nexus/ask-mcp.js index 2970b8e..25c996c 100644 --- a/lib/nexus/ask-mcp.js +++ b/lib/nexus/ask-mcp.js @@ -15,6 +15,7 @@ const net = require("net"); const SOCK = process.env.NEXUS_ASK_SOCK || ""; +const READONLY = process.env.NEXUS_MCP_READONLY === "1"; // plan mode: no `sessions` tool (it can spawn agents that write and run commands) const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"]; const ASK_TOOL = { @@ -92,9 +93,10 @@ async function handle(msg) { }); } if (method === "ping") return reply(id, {}); // MCP liveness check: an empty result, never an error - if (method === "tools/list") return reply(id, { tools: [ASK_TOOL, SESSIONS_TOOL] }); + if (method === "tools/list") return reply(id, { tools: READONLY ? [ASK_TOOL] : [ASK_TOOL, SESSIONS_TOOL] }); if (method === "tools/call") { const p = msg.params || {}; + if (p.name === "sessions" && READONLY) return reply(id, { content: [{ type: "text", text: "sessions is not available in plan mode (read-only)" }], isError: true }); if (p.name === "sessions") { // background agent sessions (lib/nexus/hub/tool.js), for the engine's own model const r = await require("./hub/tool").sessionsTool(p.arguments || {}, process.cwd()); return reply(id, { content: [{ type: "text", text: JSON.stringify(r, null, 2) }], isError: !!r.error }); diff --git a/lib/nexus/engine-mcp.js b/lib/nexus/engine-mcp.js index 9220539..7578014 100644 --- a/lib/nexus/engine-mcp.js +++ b/lib/nexus/engine-mcp.js @@ -17,14 +17,14 @@ function buildEngineMcpServers(opts) { opts = opts || {}; const out = {}; const userServers = opts.userServers; - if (userServers && typeof userServers === "object") { + if (userServers && typeof userServers === "object" && !opts.readonly) { // plan mode: only the ask bridge, no user servers that could write for (const k of Object.keys(userServers)) { const s = userServers[k]; if (s && (s.command || s.url) && k !== "nexus") out[k] = JSON.parse(JSON.stringify(s)); // 'nexus' is reserved for the ask bridge } } if (opts.sockPath && opts.askMcpPath) { - out.nexus = { command: opts.nodePath || process.execPath || "node", args: [opts.askMcpPath], env: { NEXUS_ASK_SOCK: opts.sockPath } }; + out.nexus = { command: opts.nodePath || process.execPath || "node", args: [opts.askMcpPath], env: Object.assign({ NEXUS_ASK_SOCK: opts.sockPath }, opts.readonly ? { NEXUS_MCP_READONLY: "1" } : {}) }; } return out; } diff --git a/lib/nexus/engines.js b/lib/nexus/engines.js index 8bba9a4..9a6b859 100644 --- a/lib/nexus/engines.js +++ b/lib/nexus/engines.js @@ -10,31 +10,31 @@ const ENGINES = { __proto__: null, // null prototype: a typed name like "toStrin claude: { label: "Claude Code", bin: "claude", install: "npm i -g @anthropic-ai/claude-code", kind: "stream", paid: true, ctx: 200000, model: "claude-opus-5-5", models: ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-2"], caps: { effort: true, appendSystemPrompt: true, fallbackModel: true, maxBudget: true, disallowedTools: true, cowork: true, model: true }, - args: (p, o) => { const a = ["-p", p, "--output-format", "text"]; if (o.cont) a.push("--continue"); if (o.autonomous) a.push("--dangerously-skip-permissions"); if (o.model) a.push("--model", o.model); if (o.effort) a.push("--effort", o.effort === "ultracode" ? "max" : o.effort); if (o.maxTurns) a.push("--max-turns", String(o.maxTurns)); return a; }, + args: (p, o) => { const a = ["-p", p, "--output-format", "text"]; if (o.cont) a.push("--continue"); if (o.readonly) a.push("--permission-mode", "plan"); else if (o.autonomous) a.push("--dangerously-skip-permissions"); if (o.model) a.push("--model", o.model); if (o.effort) a.push("--effort", o.effort === "ultracode" ? "max" : o.effort); if (o.maxTurns) a.push("--max-turns", String(o.maxTurns)); return a; }, tips: ["Claude can search the web, run bash, read/write files and spawn sub-agents to parallelize", "your real token usage and dollar cost update live in the status bar", "plan mode (shift+tab) has Claude outline the work before it touches any files", "Claude reads .nexus/NEXUS.md every session — keep project context there"], }, gemini: { 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) a.push("--yolo"); a.push("-p", p); return a; }, // JSON mode → real token counts (geminiParse) + 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) tips: ["Gemini's very large context window is great for whole-repo questions", "set the model with /model (e.g. gemini-2.5-pro, gemini-2.5-flash)", "needs the Gemini CLI installed and authenticated (`gemini`)"], }, codex: { label: "Codex CLI", bin: "codex", install: "npm i -g @openai/codex", kind: "cli", proto: "codex-json", paid: true, ctx: 272000, model: "gpt-5-codex", models: ["gpt-5-codex", "gpt-5", "o4-mini"], caps: { model: true, mcpInject: true }, mcpMode: "cArgs", // injects via repeatable -c mcp_servers.* overrides (per run, no global config) - args: (p, o) => { const a = ["exec", "--json", "--skip-git-repo-check"]; if (o.model) a.push("-m", o.model); if (o.autonomous) a.push("--dangerously-bypass-approvals-and-sandbox"); if (o.mcpServers) for (const n of Object.keys(o.mcpServers)) a.push(...codexMcpArgs(n, o.mcpServers[n])); a.push(p); return a; }, // JSONL events → real token counts (codexParse); -c mcp_servers.* gives codex the Nexus ask bridge for this run only + args: (p, o) => { const a = ["exec", "--json", "--skip-git-repo-check"]; if (o.model) a.push("-m", o.model); if (o.readonly) a.push("--sandbox", "read-only"); else if (o.autonomous) a.push("--dangerously-bypass-approvals-and-sandbox"); if (o.mcpServers) for (const n of Object.keys(o.mcpServers)) a.push(...codexMcpArgs(n, o.mcpServers[n])); a.push(p); return a; }, // JSONL events → real token counts (codexParse); -c mcp_servers.* gives codex the Nexus ask bridge for this run only tips: ["Codex runs OpenAI models non-interactively via `codex exec`", "set the model with /model (e.g. gpt-5-codex, o4-mini)", "needs the Codex CLI installed and signed in"], }, opencode: { label: "OpenCode", bin: "opencode", install: "npm i -g opencode-ai", kind: "cli", paid: true, ctx: 200000, model: "", models: [], caps: { model: true, mcpInject: true }, mcpMode: "env", mcpEnvVar: "OPENCODE_CONFIG", mcpFormat: "opencode", // points at a merged config (per run, user config preserved) - args: (p, o) => { const a = ["run"]; if (o.model) a.push("-m", o.model); a.push(p); return a; }, + 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; }, tips: ["OpenCode drives whichever provider/model you've configured for it", "prefer Claude or a private local model? switch with /engine"], }, aider: { label: "Aider", bin: "aider", install: "pipx install aider-chat", kind: "cli", paid: true, ctx: 200000, model: "", models: [], caps: { model: true }, - args: (p, o) => { const a = ["--message", p, "--yes-always", "--no-auto-commit"]; if (o.model) a.push("--model", o.model); return a; }, + args: (p, o) => { const a = ["--message", p, "--yes-always", "--no-auto-commit"]; if (o.readonly) a.push("--dry-run", "--no-suggest-shell-commands"); if (o.model) a.push("--model", o.model); return a; }, tips: ["Aider applies edits and shows diffs — pass a model with /model", "runs one message per turn via `aider --message`"], }, ollama: { diff --git a/test/run.js b/test/run.js index 2ac66c1..41fcd7c 100644 --- a/test/run.js +++ b/test/run.js @@ -1633,6 +1633,10 @@ group("help reference (single source of truth)"); ok("undo: restore checks files out of the snapshot tree (no commit, so no git identity needed); the agents base commit falls back to a nexus identity", /const commit = tree;/.test(src) && !/commit-tree " \+ tree \+ " -m nexus-restore/.test(src) && /env: gitIdEnv\(cwd\)(, stdio: \[[^\]]*\])? \}\)/.test(src)); 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("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)); ok("mid-turn: picking /btw from the menu opens it for a question instead of queueing a bare /btw", /if \(t === "\/btw"\) \{ input = "\/btw "; curPos = input\.length; composer\.text = input;/.test(src)); ok("/notify rejects an unknown value instead of silently toggling; /export writes to that path", /if \(a && a !== "on" && a !== "off"\) \{ transcript\.push\(\{ role: "system", text: "usage: \/notify \[on\|off\]/.test(src) && /const fp = argstr \? path\.resolve\(cwd, /.test(src)); @@ -3631,6 +3635,12 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec const ca = codexMcpArgs("nexus", servers.nexus).join(" "); ok("codexMcpArgs sets command/args/env as -c overrides", /mcp_servers\.nexus\.command=/.test(ca) && /mcp_servers\.nexus\.args=/.test(ca) && /mcp_servers\.nexus\.env=/.test(ca)); ok("codexMcpArgs returns nothing for a spec with no command", codexMcpArgs("x", {}).length === 0); + { const ro = buildEngineMcpServers({ sockPath: "/tmp/s.sock", askMcpPath: "/a.js", userServers: { github: { command: "npx" } }, readonly: true }); + ok("plan mode MCP: only the ask bridge, flagged read-only (no user servers, no sessions tool)", !ro.github && ro.nexus && ro.nexus.env.NEXUS_MCP_READONLY === "1"); } + { const ro = { readonly: true, autonomous: false }, j = (e) => ENGINES[e].args("P", ro).join(" "); + ok("plan mode engine flags: claude plan, codex read-only sandbox, opencode plan agent, aider dry-run, gemini no --yolo", /--permission-mode plan/.test(j("claude")) && !/dangerously/.test(j("claude")) && /--sandbox read-only/.test(j("codex")) && !/dangerously/.test(j("codex")) && /--agent plan/.test(j("opencode")) && /--dry-run/.test(j("aider")) && !/--yolo/.test(ENGINES.gemini.args("P", { readonly: true, autonomous: true }).join(" "))); } + { const r = require("child_process").spawnSync(process.execPath, [require("path").join(__dirname, "../lib/nexus/ask-mcp.js")], { input: '{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sessions","arguments":{"action":"ls"}}}\n', env: Object.assign({}, process.env, { NEXUS_MCP_READONLY: "1" }), timeout: 10000, encoding: "utf8" }); + ok("plan mode MCP shim hides and refuses the sessions tool", /"ask_user"/.test(r.stdout) && !/"name":"sessions"/.test(r.stdout) && /not available in plan mode/.test(r.stdout)); } ok("codex engine declares mcpInject + injects the server into its args", engineCap("codex", "mcpInject") && ENGINES.codex.mcpMode === "cArgs" && ENGINES.codex.args("P", { mcpServers: servers }).join(" ").includes("mcp_servers.nexus.command=")); ok("non-MCP engines ignore mcpServers (no leakage)", !ENGINES.gemini.args("P", { mcpServers: servers }).join(" ").includes("mcp_servers"));