diff --git a/darknode.js b/darknode.js index d6a9f7f..f9668d8 100755 --- a/darknode.js +++ b/darknode.js @@ -1983,7 +1983,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); - args.push(...Cheap.launchFlags(opts.cheap)); + args.push(...Cheap.launchFlags(opts.cheap, opts.skillOverrides)); 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 @@ -2002,7 +2002,7 @@ function runClaudeStream(prompt, cwd, cont, h, ctl, opts) { if (!line.trim()) continue; let ev; try { ev = JSON.parse(line); } catch (_) { continue; } bgT.event(ev); - if (ev.type === "system" && ev.subtype === "init") { h.onInit && h.onInit(ev); } + if (ev.type === "system" && ev.subtype === "init") { h.onInit && h.onInit(ev); if (opts.cheap) Cheap.rememberListed(os.homedir(), ev.skills); } else if (ev.type === "rate_limit_event") { h.onRateLimit && h.onRateLimit(ev.rate_limit_info || {}); } else if (ev.type === "assistant" && ev.message) { const pid = ev.parent_tool_use_id || null; // set on a sub-agent's (Task) own messages @@ -4474,7 +4474,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { addUsage(_mu, u, sess.resolvedModel || sess.model); const mu = ev.modelUsage && ev.modelUsage[sess.model]; if (mu && mu.contextWindow) sess.ctxWindow = mu.contextWindow; }, - }, ctl, { resume: _resumeSid, model: cowork.on ? cowork.strong : ((sess.userModel && sess.model && sess.model !== engine) ? sess.model : undefined), small: cowork.on && cowork.weakKind === "claude" ? cowork.weak : undefined, effort: effort || undefined, cheap: !!(cacheOn && tightEdits && cheapSide), appendSystemPrompt: require("./lib/nexus/bg-cutoff").HOST_NOTE + "\n" + ((nexusMd ? "Project (.nexus/NEXUS.md):\n" + nexusMd.slice(0, 1000) : "") + (tightEdits ? "\n" + TIGHT_DIR : "") + (minimizeCalls ? "\nMinimize tool calls: chain shell commands, read only needed lines, never re-read after write. 2-5 calls for simple tasks." : "") + (lean ? "\nTerse output, no preamble." : "") + (styleDir(style) ? "\n" + styleDir(style) : "") + (hack ? "\n" + HACK_DIR : "") + policyPrompt() + ASK_ENGINE_NOTE) || undefined, mcpConfigPath: engineMcpConfigPath(), fallbackModel: fallback || undefined, maxBudgetUsd: costCap ? Math.max(0.01, costCap - sess.cost).toFixed(2) : undefined, disallow: mode === 2 ? READONLY_TOOLS : undefined }).then(finish); + }, ctl, { resume: _resumeSid, model: cowork.on ? cowork.strong : ((sess.userModel && sess.model && sess.model !== engine) ? sess.model : undefined), small: cowork.on && cowork.weakKind === "claude" ? cowork.weak : undefined, effort: effort || undefined, 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 }).then(finish); } else if (ENGINES[engine] && ENGINES[engine].kind === "cli") { // gemini / codex / opencode / aider const eng = ENGINES[engine]; const mdl = sess.model && sess.model !== engine ? sess.model : undefined; // only pass a model the user actually chose @@ -5930,6 +5930,8 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { } const on = cacheOn && tightEdits && cheapSide, tk = (n) => n ? gray(" ~" + fmtK(n) + " tok saved") : ""; const row = (st, label, extra) => " " + (st === true ? green("●") : st === false ? gray("○") : cyan("◆")) + " " + label + (extra || ""); + if (cacheOn && tightEdits && cheapSide && engine === "claude") Cheap.refreshUse(NHOME).catch(() => {}); + const trimmed = Object.keys(Cheap.overridesFor(NHOME, cwd) || {}).length; const isClaude = engine === "claude", localOnly = isClaude ? gray(" (local engines only)") : "", spend = isClaude ? Cheap.spendReport(sess.byModel) : null, usd = (n) => "$" + n.toFixed(n < 1 ? 4 : 2); const measured = !isClaude ? "" : !spend ? "\n " + gray("no claude usage measured yet this session — send a message, then /cheap status") : "\n measured on " + cyan(spend.model) + ": " + fmtK(spend.read) + " read from cache (" + Math.round(spend.hitRate * 100) + "%), " + fmtK(spend.written) + " written, " + fmtK(spend.output) + " output = " + bold(usd(spend.cost)) + gray(" at list price") + "\n " + gray("same tokens on Opus 5.5: " + usd(spend.opus55) + " · on Opus 5: " + usd(spend.opus5) + (onPlan(engine) ? " · on a subscription these are list-price equivalents" : "")); const lossy = [["lean", lean], ["minimizeCalls", minimizeCalls], ["stepCap", stepCap], ["trimOutput", trimOutput], ["autoCompact", autoCompact]].filter((x) => x[1]).map((x) => x[0]); @@ -5937,7 +5939,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { row(tightEdits, "surgical edits — change only what differs, never rewrite whole lines"), row(cacheOn, "exact-repeat cache — free re-answers for unchanged read-only turns", impact.cachedHits ? gray(" " + impact.cachedHits + " hit" + (impact.cachedHits === 1 ? "" : "s") + " · $" + impact.cachedSaved.toFixed(4) + " saved") : isClaude ? gray(" (first message of a session only)") : ""), row(cheapSide, "local tab titles + recaps — no extra Claude Code session per title/recap", impact.sideSkipped ? gray(" " + impact.sideSkipped + " call" + (impact.sideSkipped === 1 ? "" : "s") + " skipped") : ""), - ...(isClaude ? [row(on, "shared cache prefix — per-machine context kept out of the system prompt"), row(on, "model-switch hold — /model waits for a repeat while it would discard a warm cache")] : []), + ...(isClaude ? [row(on, "unused skills listed by name only — still available, long descriptions not resent", trimmed ? gray(" " + trimmed + " skills") : on ? gray(" (starts after your next message)") : ""), row(on, "shared cache prefix — per-machine context kept out of the system prompt"), row(on, "model-switch hold — /model waits for a repeat while it would discard a warm cache")] : []), row(null, "context de-dup, re-read supersession, unchanged-file skip", tk(impact.squeezeTok)), row(null, "repeated / counting output lines + node-internal frames → exact summaries", tk(impact.repeatTok) || localOnly), row(null, "repeated read-only tool calls → pointer to the identical earlier result", tk(impact.memoTok) || localOnly), diff --git a/lib/nexus/cheap.js b/lib/nexus/cheap.js index 16975ba..71af85f 100644 --- a/lib/nexus/cheap.js +++ b/lib/nexus/cheap.js @@ -7,6 +7,7 @@ // every figure is real token counts at Anthropic's list rates. // ============================================================================ +const fs = require("fs"), path = require("path"); const { costOf, priceOf, claudeKey } = require("./pricing"); const HOUR_MS = 60 * 60 * 1000; @@ -19,7 +20,76 @@ const PRESET_KEYS = ["cache", "tightEdits", "cheapSide", "lean", "minimizeCalls" // Moves per-machine context out of the system prompt so sessions in different // folders can share the cached prefix. Safe on --resume in either direction. -function launchFlags(on) { return on ? ["--exclude-dynamic-system-prompt-sections"] : []; } +// skillOverrides ride along per launch, so the user's own settings stay untouched. +function launchFlags(on, overrides) { + if (!on) return []; + const flags = ["--exclude-dynamic-system-prompt-sections"]; + if (overrides) flags.push("--settings", JSON.stringify({ skillOverrides: overrides })); + return flags; +} + +// Every skill's long description is resent in every session, used or not. +// "name-only" keeps the skill listed and invocable and drops just that text. +const DAY_MS = 24 * HOUR_MS, USE_WINDOW_MS = 30 * DAY_MS; +const KEEP_ON = ["claude-api"]; // its description carries the rules for when it must load +const bare = (n) => String(n).split(":").pop(); + +// null unless both the listing and a finished usage scan are known: without +// evidence of what is unused, nothing is trimmed. +function skillOverrides(listed, used, keep) { + if (!Array.isArray(listed) || !listed.length || !Array.isArray(used)) return null; + const on = new Set(used.concat(KEEP_ON, keep || []).map(bare)), out = {}; + for (const n of listed) if (!on.has(bare(n))) out[n] = "name-only"; + return Object.keys(out).length ? out : null; +} + +// Skills that ship with the project describe its own workflows: never trim them. +function projectSkills(cwd) { + const names = (dir) => { try { return fs.readdirSync(path.join(cwd, ".claude", dir)); } catch (_) { return []; } }; + return names("skills").concat(names("commands").map((f) => f.replace(/\.md$/, ""))); +} + +const USE_RE = /"name":"Skill","input":\{[^}]*?"skill":"([^"]+)"|\/([^<]+)<\/command-name>/g; + +// Which skills recent Claude Code transcripts really used. Reads in chunks so a +// large history never blocks the UI; the overlap catches matches split across chunks. +async function scanSkillUse(root, sinceMs, chunk) { + const used = new Set(), size = chunk || (4 << 20), OVERLAP = 512; + const walk = (dir, out) => { let es = []; try { es = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) {} for (const e of es) { const f = path.join(dir, e.name); if (e.isDirectory()) walk(f, out); else if (e.name.endsWith(".jsonl")) out.push(f); } return out; }; + for (const f of walk(root, [])) { + let h; + try { + if (fs.statSync(f).mtimeMs < sinceMs) continue; + h = await fs.promises.open(f, "r"); + const buf = Buffer.alloc(size); let tail = ""; + for (;;) { + const { bytesRead } = await h.read(buf, 0, size, null); + if (!bytesRead) break; + const text = tail + buf.toString("latin1", 0, bytesRead); + for (const m of text.matchAll(USE_RE)) used.add(m[1] || m[2]); + tail = text.slice(-OVERLAP); + } + } catch (_) {} finally { if (h) await h.close().catch(() => {}); } + } + return Array.from(used); +} + +const storeFile = (home) => path.join(home, ".nexus", "cheap-skills.json"); +const readStore = (home) => { try { return JSON.parse(fs.readFileSync(storeFile(home), "utf8")) || {}; } catch (_) { return {}; } }; +const writeStore = (home, patch) => { try { fs.mkdirSync(path.dirname(storeFile(home)), { recursive: true }); fs.writeFileSync(storeFile(home), JSON.stringify(Object.assign(readStore(home), patch))); } catch (_) {} }; + +function rememberListed(home, skills) { if (Array.isArray(skills) && skills.length) writeStore(home, { listed: skills }); } +function overridesFor(home, cwd) { const s = readStore(home); return skillOverrides(s.listed, s.used, projectSkills(cwd)); } + +// Refresh the usage scan at most once a day, off the hot path. +let scanning = false; +async function refreshUse(home, now, root) { + now = now || Date.now(); + if (scanning || now - (readStore(home).at || 0) < DAY_MS) return false; + scanning = true; + try { writeStore(home, { at: now, used: await scanSkillUse(root || path.join(home, ".claude", "projects"), now - USE_WINDOW_MS) }); return true; } + finally { scanning = false; } +} const sameModel = (a, b) => { const ka = claudeKey(a), kb = claudeKey(b); @@ -68,4 +138,4 @@ function switchHold(o) { return { hold: true, pending: { to: o.to, at: o.now }, cost: switchCost(o) }; } -module.exports = { PRESET_KEYS, HOLD_MS, launchFlags, mainBucket, spendReport, switchCost, switchHold }; +module.exports = { PRESET_KEYS, HOLD_MS, skillOverrides, projectSkills, scanSkillUse, rememberListed, overridesFor, refreshUse, launchFlags, mainBucket, spendReport, switchCost, switchHold }; diff --git a/test/run.js b/test/run.js index b190777..60bcffa 100644 --- a/test/run.js +++ b/test/run.js @@ -3718,6 +3718,27 @@ ok("shouldCheck: first launch runs; throttled within 4h; runs after", shouldChec { const CH = require("../lib/nexus/cheap"); eq("flag only when on", CH.launchFlags(true).concat(CH.launchFlags(false)), ["--exclude-dynamic-system-prompt-sections"]); + eq("overrides ride on --settings", CH.launchFlags(true, { pdf: "name-only" }).slice(1), ["--settings", '{"skillOverrides":{"pdf":"name-only"}}']); + eq("overrides ignored when off", CH.launchFlags(false, { pdf: "name-only" }), []); + eq("unused skills go name-only, used and kept stay on", CH.skillOverrides(["pdf", "docs", "ship", "claude-api"], ["anthropic-skills:docs"], ["ship"]), { pdf: "name-only" }); + ok("no scan yet = no trim", CH.skillOverrides(["pdf"], undefined) === null); + ok("no listing yet = no trim", CH.skillOverrides(undefined, []) === null); + ok("everything used = no trim", CH.skillOverrides(["pdf"], ["pdf"]) === null); + { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "cheap-")), proj = path.join(home, ".claude", "projects", "p"), cwd = path.join(home, "repo"); + fs.mkdirSync(proj, { recursive: true }); fs.mkdirSync(path.join(cwd, ".claude", "skills", "ship"), { recursive: true }); + const use = '{"type":"tool_use","id":"t","name":"Skill","input":{"skill":"anthropic-skills:docs"}}'; + fs.writeFileSync(path.join(proj, "a.jsonl"), "x".repeat(1000) + use + "\n/review\n" + '{"name":"Skill","description":"Invoke a skill."}'); + const small = await CH.scanSkillUse(path.join(home, ".claude", "projects"), 0, 700); + eq("scan finds tool and typed uses, even split across chunks", small.sort(), ["anthropic-skills:docs", "review"]); + eq("old files are skipped", await CH.scanSkillUse(path.join(home, ".claude", "projects"), Date.now() + 1e6), []); + ok("nothing before a scan", CH.overridesFor(home, cwd) === null); + CH.rememberListed(home, ["pdf", "docs", "ship"]); + ok("first refresh scans", await CH.refreshUse(home, Date.now()) === true); + ok("second refresh is skipped for a day", await CH.refreshUse(home, Date.now()) === false); + eq("store drives the overrides, project skills kept", CH.overridesFor(home, cwd), { pdf: "name-only" }); + fs.rmSync(home, { recursive: true, force: true }); + } ok("effort is never part of the preset", !CH.PRESET_KEYS.includes("effort")); const t = { input: 0, output: 1e6, cacheWrite5m: 0, cacheWrite1h: 1e6, cacheRead: 1e7, reported: 0 }; const r = CH.spendReport({ "claude-haiku-5-5": { input: 10, output: 10, cacheWrite5m: 0, cacheWrite1h: 0, cacheRead: 0 }, "claude-fable-5-2": t });