@caveman-ai/cli 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { homedir, hostname, tmpdir, userInfo } from "node:os";
6
6
  import { basename, delimiter, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
7
7
  import { connect as netConnect, createServer as netCreateServer, isIP } from "node:net";
8
8
  import { request as httpRequest } from "node:http";
9
+ import { applyKiloCodemodeOverlay, applyOpenCodeCodemodeOverlay, buildHermesEphemeralCodemodeHome, discoverCodemodeServers, discoverKiloOwnServerNames, discoverOpenCodeOwnServerNames, NATIVE_CODEMODE_AGENTS, patchEphemeralOpenClawCodemode, patchEphemeralQwenCodemode, stripExternalCodexMcpTables, syncBackHermesEphemeralHome, writeEphemeralCodemodeConfig, writeGeminiCodemodeSettingsOverlay, } from "./codemode.js";
9
10
  import { request as httpsRequest } from "node:https";
10
11
  import { createHash, createHmac, createPublicKey, randomBytes, randomUUID, verify as edVerify } from "node:crypto";
11
12
  import { fileURLToPath } from "node:url";
@@ -44,6 +45,7 @@ import { endRuntimes, stopRuntime } from "./modules/stop.js";
44
45
  import { foundKeys, providersAdd, providersCloud, providersLocal, providersLogin, providersRemove } from "./modules/provider-logins.js";
45
46
  export const overlayBuilders = {};
46
47
  const wrapTempDirs = new Set();
48
+ const hermesEphemeralSyncPairs = new Map();
47
49
  // The standalone proxy listens here; `caveman start` launches it and
48
50
  // `caveman wrap` points agents at it.
49
51
  const PROXY_ADDR = "127.0.0.1:8787";
@@ -236,7 +238,7 @@ function agentTraffic() {
236
238
  return { target: "local", line: "agent traffic: local runtime" };
237
239
  }
238
240
  // Known agents `caveman wrap` can launch by short id come from the agent-profile
239
- // registry (public/agents/profiles/*.json, compiled to agents.generated.ts). The
241
+ // registry (agents/profiles/*.json, compiled to agents.generated.ts). The
240
242
  // data drives detection, the interactive picker, the install hint, and — crucially
241
243
  // — HOW each agent is pointed at the gateway (env vs inline-config injection). So
242
244
  // adding an agent is a new profile file, not a code change. Any other command
@@ -478,25 +480,12 @@ const LEGACY_HANDLERS = {
478
480
  update: (argv) => update(argv),
479
481
  opportunities: (argv) => argv[0] === "list" ? get("/api/v1/opportunities").then(print) : commandUsage("opportunities list"),
480
482
  snippets,
481
- dev: (argv) => {
482
- if (argv[0] === "up")
483
- return shellHint("make dev");
484
- if (argv[0] === "down")
485
- return shellHint("make down");
486
- if (argv[0] === "reset")
487
- return shellHint("make reset-local");
488
- return commandUsage("dev up|down|reset");
489
- },
490
- deploy: (argv) => {
491
- if (argv[0] === "aws")
492
- return shellHint("make deploy-aws");
493
- if (argv[0] === "status")
494
- return get("/api/v1/system/status").then(print);
495
- return commandUsage("deploy aws|status");
496
- },
483
+ deploy: (argv) => argv[0] === "status" ? get("/api/v1/system/status").then(print) : commandUsage("deploy status"),
497
484
  start: (argv) => start(argv),
498
485
  wrap,
499
486
  run: wrap,
487
+ // Unprinted (porcelain caps): stdio Code-Mode MCP gateway bridging existing MCP servers behind 3 meta-tools.
488
+ codemode: codemodeCmd,
500
489
  status,
501
490
  explore,
502
491
  verify: verifyFirstRequest,
@@ -824,7 +813,7 @@ const TELEMETRY_DISCLOSURE_LINE = "usage stats on — commands, agent sessions,
824
813
  const TELEMETRY_TOKEN_READ_TIMEOUT_MS = Number(process.env.CAVEMAN_TELEMETRY_TOKEN_READ_TIMEOUT_MS) || 400;
825
814
  const SYNC_DISCLOSURE = "sync uploads span metadata to your org's dashboard — tokens, cost, latency, model, status. Imported standalone observations never affect managed budgets, verified savings, or billing. Subscription/OAuth sessions carry token counts only — no dollar figure. Never prompt or response bytes.";
826
815
  const TELEMETRY_COMMAND_ALLOWLIST = [
827
- "agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "dev", "doctor", "evals", "experiments",
816
+ "agent", "audit", "billing", "browse", "codemode", "compress", "convert", "costs", "deploy", "doctor", "evals", "experiments",
828
817
  "explore", "help", "hooks", "init", "keys", "learn", "login", "logout", "mcp", "mem", "opportunities", "plan",
829
818
  "projects", "providers", "receipts", "retrieve", "score", "sdk", "setup", "shrink", "shrink-hook", "skills",
830
819
  "run", "snippets", "start", "stats", "status", "sync", "telemetry", "toon", "traces", "trial", "unknown", "update", "usage", "verify", "version", "welcome", "whoami", "wrap",
@@ -832,9 +821,9 @@ const TELEMETRY_COMMAND_ALLOWLIST = [
832
821
  ];
833
822
  const TELEMETRY_COMMANDS = new Set(TELEMETRY_COMMAND_ALLOWLIST);
834
823
  const TELEMETRY_SUBCOMMANDS = new Set([
835
- "act", "apply", "aws", "charges", "create", "decode", "down", "encode", "eval", "export", "forget", "import",
824
+ "act", "apply", "charges", "create", "decode", "encode", "eval", "export", "forget", "import",
836
825
  "catalog", "implement", "install", "link", "list", "off", "on", "recall", "recover", "refresh", "remember", "report", "reset", "revoke",
837
- "run", "show", "snippet", "status", "uninstall", "unlink", "up", "verify",
826
+ "run", "show", "snippet", "status", "uninstall", "unlink", "verify",
838
827
  ]);
839
828
  const TELEMETRY_START_MS = Date.now();
840
829
  let telemetryCommandSent = false;
@@ -4536,22 +4525,23 @@ function capabilityInputValue(key, value) {
4536
4525
  // `config get` output are unchanged; anything unrecognized returns undefined,
4537
4526
  // which leaves the key at its previous (default "auto") value rather than
4538
4527
  // silently inventing a surface.
4539
- if (key === "execute.mcp" && (value === "auto" || value === "marker-only"))
4528
+ if (key === "execute.mcp" && (value === "auto" || value === "codemode" || value === "marker-only"))
4540
4529
  return value;
4541
4530
  return wrapBoolValue(value);
4542
4531
  }
4543
- // mcpSurfaceMode collapses the stored execute.mcp value into the three-way mode
4544
- // the wrap path acts on. Only the four values capabilityInputValue accepts can
4545
- // reach it. It decides how much surface we INJECT — never what we tell the
4532
+ // mcpSurfaceMode collapses the stored execute.mcp value into the mode the wrap
4533
+ // path acts on. It decides how much surface we INJECT — never what we tell the
4546
4534
  // proxy about recovery, which is answered from real install evidence.
4547
4535
  function mcpSurfaceMode(value) {
4548
4536
  if (value === false)
4549
4537
  return "off";
4538
+ if (value === "codemode")
4539
+ return "codemode";
4550
4540
  if (value === "marker-only")
4551
4541
  return "marker-only";
4552
4542
  return "auto";
4553
4543
  }
4554
- const MCP_SURFACE_VALUES = "auto | marker-only | true | false";
4544
+ const MCP_SURFACE_VALUES = "auto | codemode | marker-only | true | false";
4555
4545
  function nestedCapabilityValue(doc, key) {
4556
4546
  const [group, first, second] = key.split(".");
4557
4547
  const block = objectValue(doc[group]);
@@ -4856,6 +4846,7 @@ function defaultWrapOptions() {
4856
4846
  delegate: cfg.delegate,
4857
4847
  minimal: false,
4858
4848
  autoRecall: cfg.autoRecall,
4849
+ codemode: cfg.mcp === "codemode",
4859
4850
  command: [],
4860
4851
  };
4861
4852
  if (cfg.pixelModels !== undefined)
@@ -5800,6 +5791,45 @@ function printSessionSavings(kind, sinceISO, agentId) {
5800
5791
  // compression-first: it starts the standalone proxy in `compress` mode unless
5801
5792
  // config/env or --off selects record mode. Known agents (claude, codex, …) are launchable by short id
5802
5793
  // and get detected; any other command still runs verbatim.
5794
+ async function codemodeCmd(rest) {
5795
+ const probed = probeMcpBinary();
5796
+ if (!probed) {
5797
+ console.error("caveman codemode: caveman-mcp binary not found. Run `caveman setup --install` first.");
5798
+ process.exit(1);
5799
+ }
5800
+ if (!probed.probe.current || !probed.probe.capabilities.includes("codemode")) {
5801
+ console.error(`caveman codemode: caveman-mcp (${probed.probe.version || "unknown"}) lacks Code Mode support. Run \`caveman setup --install\` to upgrade.`);
5802
+ process.exit(1);
5803
+ }
5804
+ const toolsOnlyIdx = rest.indexOf("--tools-only");
5805
+ const subArgs = toolsOnlyIdx >= 0
5806
+ ? ["tools", ...rest.filter((_, idx) => idx !== toolsOnlyIdx)]
5807
+ : ["codemode", ...rest];
5808
+ const invocation = portableInvocation(probed.binary, subArgs);
5809
+ const res = spawnSync(invocation.command, invocation.args, {
5810
+ stdio: "inherit",
5811
+ windowsHide: true,
5812
+ });
5813
+ if (res.error) {
5814
+ console.error(`caveman codemode: failed to run ${probed.binary}: ${res.error.message}`);
5815
+ process.exit(127);
5816
+ }
5817
+ process.exitCode = res.status ?? (res.signal ? signalExitCode(res.signal) : 1);
5818
+ }
5819
+ const HERMES_NON_CHAT_SUBCOMMANDS = new Set([
5820
+ "status", "model", "mcp", "config", "cron", "profile", "plugins", "skills",
5821
+ "sessions", "version", "doctor", "setup", "login", "logout", "gateway", "acp",
5822
+ "insights", "memory", "tools", "update", "uninstall", "security", "backup", "restore",
5823
+ ]);
5824
+ function hermesNeedsCustomProviderArgs(userArgs) {
5825
+ if (userArgs.length === 0)
5826
+ return true;
5827
+ if (HERMES_NON_CHAT_SUBCOMMANDS.has(userArgs[0]))
5828
+ return false;
5829
+ if (userArgs.some((a) => a === "--help" || a === "-h" || a === "--version" || a === "-V"))
5830
+ return false;
5831
+ return true;
5832
+ }
5803
5833
  async function wrap(rest) {
5804
5834
  pendingRunOffStates.length = 0;
5805
5835
  const parsed = parseWrapArgs(rest);
@@ -5819,7 +5849,12 @@ async function wrap(rest) {
5819
5849
  const requested = rest[0];
5820
5850
  const agent = findAgent(requested);
5821
5851
  const bin = agent ? binOf(agent) : requested;
5822
- const extra = agent ? [...agent.args, ...rest.slice(1)] : rest.slice(1);
5852
+ const userArgs = rest.slice(1);
5853
+ const extra = agent
5854
+ ? agent.id === "hermes" && !hermesNeedsCustomProviderArgs(userArgs)
5855
+ ? userArgs
5856
+ : [...agent.args, ...userArgs]
5857
+ : userArgs;
5823
5858
  const resolved = which(bin);
5824
5859
  if (!resolved) {
5825
5860
  wrapNotFoundUI(requested, agent);
@@ -6197,6 +6232,36 @@ function parseWrapArgs(rest) {
6197
6232
  cmd.shift();
6198
6233
  continue;
6199
6234
  }
6235
+ if (a === "--codemode") {
6236
+ out.codemode = true;
6237
+ cmd.shift();
6238
+ continue;
6239
+ }
6240
+ if (a === "--trust-workspace-mcp") {
6241
+ out.trustWorkspaceMcp = true;
6242
+ cmd.shift();
6243
+ continue;
6244
+ }
6245
+ if (a === "--shrink-tools") {
6246
+ out.shrinkTools = true;
6247
+ cmd.shift();
6248
+ continue;
6249
+ }
6250
+ if (a === "--defer-mcp-tools") {
6251
+ out.deferMcpTools = true;
6252
+ cmd.shift();
6253
+ continue;
6254
+ }
6255
+ if (a === "--canonical-tools") {
6256
+ out.canonicalTools = true;
6257
+ cmd.shift();
6258
+ continue;
6259
+ }
6260
+ if (a === "--turn-effort") {
6261
+ out.turnEffort = true;
6262
+ cmd.shift();
6263
+ continue;
6264
+ }
6200
6265
  if (deletedFlags.has(a ?? "")) {
6201
6266
  console.error(`caveman wrap: ${a} moved to capability config — inspect with \`${invokedAs()} tools config get\``);
6202
6267
  process.exit(2);
@@ -6229,11 +6294,16 @@ function wrapUsage(stream = "stderr") {
6229
6294
  else
6230
6295
  console.error(line);
6231
6296
  };
6232
- write(`usage: ${invokedCommand("wrap")} [--off|--pixel] [--workflow <slug>] <agent> [args...]`);
6233
- write(" (default) ephemeral stack: S4 compression + TOON best-of + recovery/output shrink where host supports a temp pack");
6234
- write(" --off byte-safe pass-through metering only — nothing is rewritten");
6235
- write(" --pixel lossy text→PNG pixel mode (model-gated); originals recoverable via caveman_retrieve");
6236
- write(" --workflow label this session's traffic (x-cave-workflow) so it groups by name in the dashboard");
6297
+ write(`usage: ${invokedCommand("wrap")} [--off|--pixel] [--codemode] [--shrink-tools] [--defer-mcp-tools] [--canonical-tools] [--turn-effort] [--workflow <slug>] <agent> [args...]`);
6298
+ write(" (default) ephemeral stack: S4 compression + TOON best-of + recovery/output shrink where host supports a temp pack");
6299
+ write(" --off byte-safe pass-through metering only — nothing is rewritten");
6300
+ write(" --pixel lossy text→PNG pixel mode (model-gated); originals recoverable via caveman_retrieve");
6301
+ write(" --codemode opt-in QuickJS Code-Mode MCP gateway (4 read/write-split meta-tools + CCR recovery + repo/pr/browse); Claude Code, Codex, OpenCode & Hermes also ship native codemodes");
6302
+ write(" --shrink-tools opt-in caveman-shrink compression on tools[] schemas in the local proxy");
6303
+ write(" --defer-mcp-tools opt-in provider-native defer_loading on non-core MCP tools (Anthropic + OpenAI Responses)");
6304
+ write(" --canonical-tools opt-in deterministic tools[] sorting so MCP reconnect shuffles never bust the prompt cache");
6305
+ write(" --turn-effort opt-in cache-safe per-message reasoning effort stepping (Claude 5+/Opus 5.5 marks & GPT-6 configuration_update; 0 cache bust)");
6306
+ write(" --workflow label this session's traffic (x-cave-workflow) so it groups by name in the dashboard");
6237
6307
  write(`Capability groups: think / remember / execute — inspect with \`${invokedAs()} tools config get\`.`);
6238
6308
  write("Auth passes through untouched: API keys AND subscription OAuth logins (Claude Pro/Max) both work.");
6239
6309
  write("Subscription logins compress locally too, no account needed (live zone only — compressed turns are re-sent byte-identically so the provider cache stays warm;");
@@ -6247,7 +6317,7 @@ function normalizeAgentShortcutWrapArgs(input) {
6247
6317
  const agentArgs = [];
6248
6318
  for (let i = 1; i < input.length; i++) {
6249
6319
  const item = input[i];
6250
- if (item === "--off" || item === "--pixel") {
6320
+ if (item === "--off" || item === "--pixel" || item === "--codemode" || item === "--trust-workspace-mcp" || item === "--shrink-tools" || item === "--defer-mcp-tools" || item === "--canonical-tools" || item === "--turn-effort") {
6251
6321
  wrapFlags.push(item);
6252
6322
  continue;
6253
6323
  }
@@ -6295,7 +6365,8 @@ async function agentShortcut(rest) {
6295
6365
  process.exitCode = 127;
6296
6366
  return;
6297
6367
  }
6298
- const invocation = portableInvocation(bin, [...agent.args, ...rest.slice(1)]);
6368
+ const helpArgs = agent.id === "hermes" ? rest.slice(1) : [...agent.args, ...rest.slice(1)];
6369
+ const invocation = portableInvocation(bin, helpArgs);
6299
6370
  const result = spawnSync(invocation.command, invocation.args, { stdio: "inherit" });
6300
6371
  if (result.error)
6301
6372
  throw new Error(`failed to exec ${bin}: ${result.error.message}`);
@@ -6399,7 +6470,11 @@ async function agentShortcut(rest) {
6399
6470
  maybeWarnHermesMissingKey(agent, gatewayURL());
6400
6471
  const stopProxyKeepalive = startProxyKeepalive();
6401
6472
  const code = await new Promise((resolve, reject) => {
6402
- const invocation = portableInvocation(bin, [...agent.args, ...rest.slice(1)]);
6473
+ // Native Hermes installs already own model.provider/base_url in config.yaml
6474
+ // (including openai-codex OAuth on /chatgpt); prepending `--provider custom`
6475
+ // would override that OAuth provider and break Hermes subcommands.
6476
+ const launchArgs = native === "hermes" ? rest.slice(1) : [...agent.args, ...rest.slice(1)];
6477
+ const invocation = portableInvocation(bin, launchArgs);
6403
6478
  let child;
6404
6479
  try {
6405
6480
  child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
@@ -6581,14 +6656,42 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
6581
6656
  // detail itself — i.e. it has the caveman MCP retrieve tool installed (run
6582
6657
  // `caveman mcp install <agent>`). When it does, signal the proxy to use MCP
6583
6658
  // recovery (which lets it compress streams); otherwise streams pass through.
6584
- const ephemeralMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex")
6585
- && !opts.minimal && opts.mcpMode === "auto" && wrapRecoveryEligible(opts)
6659
+ const codemodeSupportedAgents = new Set(["claude", "codex", "gemini", "qwen", "opencode", "openclaw", "kilo", "hermes", "pi"]);
6660
+ const codemodeRequested = Boolean(!direct && opts.codemode && agent && codemodeSupportedAgents.has(agent.id));
6661
+ const ephemeralMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex" || codemodeRequested)
6662
+ && !opts.minimal && (opts.mcpMode === "auto" || opts.mcpMode === "codemode" || opts.codemode) && wrapRecoveryEligible(opts)
6586
6663
  ? probeMcpBinary()
6587
6664
  : null;
6588
6665
  if (ephemeralMcp && !ephemeralMcp.probe.current)
6589
6666
  queueStaleMcpBinary(ephemeralMcp.probe);
6590
6667
  const ephemeralMcpBinary = ephemeralMcp?.probe.current ? ephemeralMcp.binary : undefined;
6591
- const mcpRecovery = !direct && (Boolean(ephemeralMcpBinary) || wrapMcpRecoveryAvailable(agent, opts, cmdArgs));
6668
+ let codemodeLaunch;
6669
+ let codemodeVerifiedRecovery = false;
6670
+ if (codemodeRequested) {
6671
+ if (ephemeralMcp) {
6672
+ if (ephemeralMcp.probe.current && ephemeralMcp.probe.capabilities.includes("codemode")) {
6673
+ codemodeLaunch = mcpServerLaunch(ephemeralMcp.binary, []);
6674
+ // Kilo and Qwen can apply policy after user-owned config; they prove
6675
+ // recovery in band rather than via a proxy-wide recovery assertion.
6676
+ codemodeVerifiedRecovery = agent.id !== "kilo" && agent.id !== "qwen";
6677
+ }
6678
+ else {
6679
+ queueStaleMcpBinary(ephemeralMcp.probe);
6680
+ process.stderr.write(`${mark("warn")} caveman-mcp (${ephemeralMcp.probe.version}) lacks Code Mode support; run \`caveman setup --install\` — launching without --codemode\n`);
6681
+ }
6682
+ }
6683
+ else {
6684
+ process.stderr.write(`${mark("warn")} caveman-mcp not found; run \`caveman setup --install\` — launching without --codemode\n`);
6685
+ }
6686
+ }
6687
+ const codemodeEnabled = Boolean(codemodeRequested && codemodeLaunch);
6688
+ const trustWorkspaceMcp = Boolean(opts.trustWorkspaceMcp || process.env.CAVEMAN_TRUST_WORKSPACE_MCP === "1");
6689
+ const codemodeServers = codemodeEnabled
6690
+ ? discoverCodemodeServers(process.cwd(), homedir(), process.env, trustWorkspaceMcp)
6691
+ : {};
6692
+ const mcpRecovery = !direct && (Boolean(ephemeralMcpBinary && (agent?.id === "claude" || agent?.id === "codex"))
6693
+ || codemodeVerifiedRecovery
6694
+ || wrapMcpRecoveryAvailable(agent, opts, cmdArgs));
6592
6695
  const delegateAlreadyInstalled = Boolean(!direct && agent && mcpServerInstalled(agent.id, "caveman-delegate"));
6593
6696
  const ephemeralDelegateMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex")
6594
6697
  && !opts.minimal && opts.delegate && !delegateAlreadyInstalled
@@ -6625,7 +6728,33 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
6625
6728
  : null;
6626
6729
  }
6627
6730
  }
6731
+ if (proxyReady && !direct) {
6732
+ const startOnlyFlags = [];
6733
+ if (opts.shrinkTools)
6734
+ startOnlyFlags.push("--shrink-tools");
6735
+ if (opts.deferMcpTools)
6736
+ startOnlyFlags.push("--defer-mcp-tools");
6737
+ if (opts.canonicalTools)
6738
+ startOnlyFlags.push("--canonical-tools");
6739
+ if (opts.turnEffort)
6740
+ startOnlyFlags.push("--turn-effort");
6741
+ if (startOnlyFlags.length > 0) {
6742
+ process.stderr.write(`${mark("warn")} Caveman proxy is already running on ${host}:${port}; ${startOnlyFlags.join(", ")} only take effect when starting the proxy (run \`caveman stop\` first to restart with those flags)\n`);
6743
+ }
6744
+ }
6628
6745
  if (!proxyReady && !direct) {
6746
+ if (opts.shrinkTools && !process.env.CAVEMAN_TOOLSCHEMA_STRIP) {
6747
+ process.env.CAVEMAN_TOOLSCHEMA_STRIP = "shrink";
6748
+ }
6749
+ if (opts.deferMcpTools && !process.env.CAVEMAN_DEFER_MCP_TOOLS) {
6750
+ process.env.CAVEMAN_DEFER_MCP_TOOLS = "1";
6751
+ }
6752
+ if (opts.canonicalTools && !process.env.CAVEMAN_CANONICAL_TOOLS) {
6753
+ process.env.CAVEMAN_CANONICAL_TOOLS = "1";
6754
+ }
6755
+ if (opts.turnEffort && !process.env.CAVEMAN_TURN_EFFORT) {
6756
+ process.env.CAVEMAN_TURN_EFFORT = "1";
6757
+ }
6629
6758
  if (local && !opts.noProxy) {
6630
6759
  proxyStarted = codexSubscription
6631
6760
  ? await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, false, undefined, undefined, gw, "codex-subscription", observeEstimate)
@@ -6773,14 +6902,73 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
6773
6902
  env = direct
6774
6903
  ? { ...process.env }
6775
6904
  : agent?.id === "codex"
6776
- ? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, ephemeralDelegateMcp)
6905
+ ? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, ephemeralDelegateMcp, codemodeEnabled && codemodeLaunch ? { launch: codemodeLaunch, servers: codemodeServers, workspace: process.cwd() } : null)
6777
6906
  : buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs, runtime.owner === "unknown" ? undefined : runtime);
6778
6907
  if (!direct && agent?.id === "claude") {
6779
- const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
6780
- childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
6908
+ const codemodeSpec = codemodeEnabled && codemodeLaunch ? { launch: codemodeLaunch, servers: codemodeServers, workspace: process.cwd() } : null;
6909
+ const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp, codemodeSpec);
6910
+ if (codemodeSpec) {
6911
+ // Strict MCP config isolates Claude to the 3 Code-Mode meta-tools while
6912
+ // caveman-mcp codemode bridges all discovered MCP servers behind them.
6913
+ childArgs = ["--plugin-dir", pluginDir, "--strict-mcp-config", "--mcp-config", join(pluginDir, ".mcp.json"), ...cmdArgs];
6914
+ }
6915
+ else {
6916
+ childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
6917
+ }
6781
6918
  }
6782
- if (!direct && agent?.id === "pi")
6919
+ if (!direct && codemodeEnabled) {
6920
+ const bridgedCount = Object.keys(codemodeServers).length;
6921
+ const nativeNote = agent && NATIVE_CODEMODE_AGENTS.has(agent.id)
6922
+ ? ` (opt-in alongside ${agent.display_name}'s native codemode)`
6923
+ : "";
6924
+ process.stderr.write(dim(`→ codemode active (${agent?.id}) · QuickJS sandbox bridging ${bridgedCount} MCP server${bridgedCount === 1 ? "" : "s"} + built-ins (repo, pr, browse) behind 4 read/write-split meta-tools + CCR recovery${nativeNote}\n`));
6925
+ }
6926
+ if (!direct && agent?.id === "pi") {
6783
6927
  childArgs = buildPiWrapArgs(cmdArgs, env, gw);
6928
+ if (codemodeEnabled && codemodeLaunch) {
6929
+ const cmDir = mkdtempSync(join(tmpdir(), "caveman-wrap-pi-cm-"));
6930
+ wrapTempDirs.add(cmDir);
6931
+ env.CAVEMAN_PI_CODEMODE = "1";
6932
+ env.CAVEMAN_PI_CODEMODE_CONFIG = writeEphemeralCodemodeConfig(cmDir, codemodeServers);
6933
+ env.CAVEMAN_PI_CODEMODE_WORKSPACE = process.cwd();
6934
+ if (!env.CAVEMAN_MCP_BIN) {
6935
+ env.CAVEMAN_MCP_BIN = codemodeLaunch.command;
6936
+ if (codemodeLaunch.args.length > 0 && !env.CAVEMAN_MCP_PREFIX_ARGS) {
6937
+ env.CAVEMAN_MCP_PREFIX_ARGS = JSON.stringify(codemodeLaunch.args);
6938
+ }
6939
+ }
6940
+ }
6941
+ }
6942
+ if (!direct && codemodeEnabled && codemodeLaunch && agent && agent.id !== "claude" && agent.id !== "codex" && agent.id !== "pi") {
6943
+ const cmDir = mkdtempSync(join(tmpdir(), `caveman-wrap-${agent.id}-cm-`));
6944
+ wrapTempDirs.add(cmDir);
6945
+ const cfgPath = writeEphemeralCodemodeConfig(cmDir, codemodeServers);
6946
+ const cmEntry = {
6947
+ command: codemodeLaunch.command,
6948
+ args: [...codemodeLaunch.args, "codemode", "--config", cfgPath, "--workspace", process.cwd()],
6949
+ };
6950
+ if (agent.id === "gemini") {
6951
+ env.GEMINI_CLI_SYSTEM_SETTINGS_PATH = writeGeminiCodemodeSettingsOverlay(cmDir, process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? "", cmEntry);
6952
+ }
6953
+ else if (agent.id === "qwen" && env.QWEN_CODE_SYSTEM_SETTINGS_PATH) {
6954
+ patchEphemeralQwenCodemode(env.QWEN_CODE_SYSTEM_SETTINGS_PATH, cmEntry);
6955
+ env.QWEN_CODE_LEGACY_MCP_BLOCKING = "1";
6956
+ }
6957
+ else if (agent.id === "opencode") {
6958
+ env.OPENCODE_CONFIG_CONTENT = applyOpenCodeCodemodeOverlay(env.OPENCODE_CONFIG_CONTENT, discoverOpenCodeOwnServerNames(process.cwd(), homedir(), process.env, trustWorkspaceMcp), cmEntry);
6959
+ }
6960
+ else if (agent.id === "kilo") {
6961
+ env.KILO_CONFIG_CONTENT = applyKiloCodemodeOverlay(env.KILO_CONFIG_CONTENT, cmEntry, discoverKiloOwnServerNames(process.cwd(), homedir(), process.env, trustWorkspaceMcp));
6962
+ }
6963
+ else if (agent.id === "openclaw" && env.OPENCLAW_CONFIG_PATH) {
6964
+ patchEphemeralOpenClawCodemode(env.OPENCLAW_CONFIG_PATH, cmEntry);
6965
+ }
6966
+ else if (agent.id === "hermes") {
6967
+ const srcHermesHome = hermesHome();
6968
+ hermesEphemeralSyncPairs.set(cmDir, srcHermesHome);
6969
+ env.HERMES_HOME = buildHermesEphemeralCodemodeHome(srcHermesHome, cmDir, cmEntry);
6970
+ }
6971
+ }
6784
6972
  if (!direct && agent?.id === "aider")
6785
6973
  childArgs = routedAiderArgs(cmdArgs);
6786
6974
  }
@@ -7024,6 +7212,11 @@ function hermesHostDerivedApiKeyEnvName(gw) {
7024
7212
  }
7025
7213
  function applyHermesAuthEnv(env, gw, modeGw = gw) {
7026
7214
  delete env.CUSTOM_API_KEY;
7215
+ // Hermes OpenAI-compatible auxiliary clients (summary/compression/vision)
7216
+ // append /chat/completions to OPENAI_BASE_URL / OPENAI_API_BASE and expect /v1.
7217
+ const v1Base = appendUrlPath(gw, "/v1");
7218
+ env.OPENAI_BASE_URL = v1Base;
7219
+ env.OPENAI_API_BASE = v1Base;
7027
7220
  if (wrapMode(modeGw) !== "managed")
7028
7221
  return;
7029
7222
  const key = firstEnvSecret(env, ["CAVE_API_KEY"]) ?? connectedGatewayAPIKey();
@@ -8202,7 +8395,7 @@ function nativeHookEntriesHealthy(root, agentId) {
8202
8395
  });
8203
8396
  });
8204
8397
  }
8205
- function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp) {
8398
+ function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp, codemodeSpec = null) {
8206
8399
  const sourceHome = codexHomeDir();
8207
8400
  const outDir = mkdtempSync(join(tmpdir(), "caveman-wrap-"));
8208
8401
  wrapTempDirs.add(outDir);
@@ -8220,14 +8413,21 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp) {
8220
8413
  catch {
8221
8414
  sourceConfig = "";
8222
8415
  }
8223
- const stripped = stripCodexCavemanMcpToml(stripCodexCavemanProviderToml(sourceConfig));
8416
+ const baseStripped = stripCodexCavemanMcpToml(stripCodexCavemanProviderToml(sourceConfig));
8417
+ const stripped = codemodeSpec ? stripExternalCodexMcpTables(baseStripped) : baseStripped;
8224
8418
  const providerLines = codexCavemanProviderToml(gw, subscription).split("\n");
8225
8419
  const providerRoot = providerLines.shift();
8226
8420
  const providerTables = providerLines.join("\n");
8227
8421
  const recoveryEnv = codexRecoveryEnv();
8228
- const mcp = mcpBinary
8229
- ? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n${recoveryEnv ? `${recoveryEnv}\n` : ""}`
8230
- : "\n";
8422
+ let mcp = "\n";
8423
+ if (codemodeSpec) {
8424
+ const cfgPath = writeEphemeralCodemodeConfig(outDir, codemodeSpec.servers);
8425
+ const cmArgs = [...codemodeSpec.launch.args, "codemode", "--config", cfgPath, "--workspace", codemodeSpec.workspace];
8426
+ mcp = `\n\n[mcp_servers.caveman-codemode]\ncommand = ${JSON.stringify(codemodeSpec.launch.command)}\nargs = [${cmArgs.map((arg) => JSON.stringify(arg)).join(", ")}]\n${recoveryEnv ? `${recoveryEnv}\n` : ""}`;
8427
+ }
8428
+ else if (mcpBinary) {
8429
+ mcp = `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n${recoveryEnv ? `${recoveryEnv}\n` : ""}`;
8430
+ }
8231
8431
  const delegateArgs = delegateMcp?.args.length
8232
8432
  ? `\nargs = [${delegateMcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]`
8233
8433
  : "";
@@ -8243,17 +8443,17 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp) {
8243
8443
  linkCodexReadOnly(sourceHome, outDir, "AGENTS.md");
8244
8444
  return outDir;
8245
8445
  }
8246
- function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, delegateMcp) {
8446
+ function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, delegateMcp, codemodeSpec = null) {
8247
8447
  const env = { ...process.env };
8248
8448
  for (const key of WRAP_BASE_URL_ENV_VARS)
8249
8449
  delete env[key];
8250
8450
  // The ephemeral CODEX_HOME points Codex at the same loopback gateway, so it
8251
8451
  // needs the same proxy exemption the base-url wrap path gets.
8252
8452
  Object.assign(env, gatewayNoProxyEnv(gw));
8253
- env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp);
8453
+ env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp, codemodeSpec);
8254
8454
  return env;
8255
8455
  }
8256
- function buildClaudeEphemeralPlugin(mcpBinary, includeShrink, includeRecall, delegateMcp) {
8456
+ function buildClaudeEphemeralPlugin(mcpBinary, includeShrink, includeRecall, delegateMcp, codemodeSpec = null) {
8257
8457
  const dir = mkdtempSync(join(tmpdir(), "caveman-wrap-claude-"));
8258
8458
  wrapTempDirs.add(dir);
8259
8459
  mkdirSync(join(dir, ".claude-plugin"), { recursive: true });
@@ -8264,10 +8464,18 @@ function buildClaudeEphemeralPlugin(mcpBinary, includeShrink, includeRecall, del
8264
8464
  description: "Ephemeral Caveman local-engine pack",
8265
8465
  }, null, 2) + "\n", { mode: 0o600 });
8266
8466
  writeFileSync(join(dir, "hooks", "hooks.json"), JSON.stringify(nativeHooksDocument("claude", includeShrink, {}, includeRecall), null, 2) + "\n", { mode: 0o600 });
8267
- if (mcpBinary || delegateMcp) {
8467
+ if (codemodeSpec || mcpBinary || delegateMcp) {
8268
8468
  const mcpServers = {};
8269
- if (mcpBinary)
8469
+ if (codemodeSpec) {
8470
+ const cfgPath = writeEphemeralCodemodeConfig(dir, codemodeSpec.servers);
8471
+ mcpServers["caveman-codemode"] = {
8472
+ command: codemodeSpec.launch.command,
8473
+ args: [...codemodeSpec.launch.args, "codemode", "--config", cfgPath, "--workspace", codemodeSpec.workspace],
8474
+ };
8475
+ }
8476
+ else if (mcpBinary) {
8270
8477
  mcpServers.caveman = { command: mcpBinary, args: [] };
8478
+ }
8271
8479
  if (delegateMcp)
8272
8480
  mcpServers["caveman-delegate"] = delegateMcp;
8273
8481
  writeFileSync(join(dir, ".mcp.json"), JSON.stringify({
@@ -9049,8 +9257,8 @@ function geminiNativeMutations(gw, mcpBinary) {
9049
9257
  // variable installed into a root the host never reads, while still reporting
9050
9258
  // success (#1441); the installer and the mode plugin resolve it the same way.
9051
9259
  function opencodeConfigDir() {
9052
- const selected = (process.env.OPENCODE_CONFIG_DIR ?? "").trim();
9053
- if (selected)
9260
+ const selected = process.env.OPENCODE_CONFIG_DIR ?? "";
9261
+ if (selected.trim())
9054
9262
  return resolve(selected);
9055
9263
  return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
9056
9264
  }
@@ -12455,6 +12663,11 @@ function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "a
12455
12663
  function cleanupWrapTempDirs() {
12456
12664
  for (const dir of [...wrapTempDirs]) {
12457
12665
  try {
12666
+ const syncTarget = hermesEphemeralSyncPairs.get(dir);
12667
+ if (syncTarget) {
12668
+ syncBackHermesEphemeralHome(dir, syncTarget);
12669
+ hermesEphemeralSyncPairs.delete(dir);
12670
+ }
12458
12671
  rmSync(dir, { recursive: true, force: true });
12459
12672
  }
12460
12673
  catch {
@@ -13367,7 +13580,7 @@ function readLocalScanState() {
13367
13580
  }
13368
13581
  // dbFingerprint returns a stable identity for THIS local spend DB so the sync
13369
13582
  // high-water mark is scoped to the specific database it was measured against.
13370
- // If the DB is deleted and recreated (e.g. `make reset-local` wipes ~/.caveman),
13583
+ // If the DB is deleted and recreated (for example ~/.caveman is wiped),
13371
13584
  // SQLite rowids restart at 1; without a per-DB fingerprint the stale watermark
13372
13585
  // in ~/.caveman-cloud/sync.json would make `WHERE id > watermark` skip every new
13373
13586
  // span forever. We persist a random UUID in a CLI-owned marker table on the
@@ -13544,7 +13757,7 @@ function localScanSyncLine(out) {
13544
13757
  return `synced 30-day local scan · inferred token summary · separate from gateway spend and verified savings${destination}`;
13545
13758
  }
13546
13759
  // syncRequestSpan converts one local `requests` row into a caveman-jsonl span
13547
- // line (Caveman-Cloud public/shared/platform/importers Span shape; timestamps are already in
13760
+ // line (the Caveman Cloud importer's Span shape; timestamps are already in
13548
13761
  // the ClickHouse layout because the proxy writes them that way). The basis and
13549
13762
  // per-row inferred savings ride in attributes — the spans schema has no savings
13550
13763
  // column, and imported rows must never look like verified ledger entries.
@@ -23367,9 +23580,6 @@ function configPath() {
23367
23580
  function print(value) {
23368
23581
  console.log(JSON.stringify(value, null, 2));
23369
23582
  }
23370
- function shellHint(commandLine) {
23371
- console.log(commandLine);
23372
- }
23373
23583
  export const HELP_SCREEN = `caveman
23374
23584
 
23375
23585
  run
@@ -23614,19 +23824,6 @@ function which(cmd) {
23614
23824
  }
23615
23825
  return null;
23616
23826
  }
23617
- // dockerState reports whether the Docker daemon is reachable, so `caveman start`
23618
- // can give an honest hint about the `make dev` path.
23619
- function dockerState() {
23620
- if (!which("docker"))
23621
- return "absent";
23622
- try {
23623
- execFileSync("docker", ["info"], { stdio: "ignore", timeout: 4000 });
23624
- return "running";
23625
- }
23626
- catch {
23627
- return "stopped";
23628
- }
23629
- }
23630
23827
  // portListening probes a TCP port with a short timeout — used to detect whether
23631
23828
  // the proxy is already up, so start/wrap can say so without false positives.
23632
23829
  function portListening(host, port) {
@@ -109,7 +109,7 @@ export function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, p
109
109
  // preserving them in an overlay alone does not make the proxy forward them.
110
110
  const COPIED_HEADERS = ["content-type", "content-encoding", "accept", "accept-encoding", "idempotency-key", "openai-organization", "openai-project", "session_id", "x-session-id", "x-client-request-id", "x-session-affinity", "anthropic-version", "anthropic-beta", "api-version", "user-agent"];
111
111
  const COMPAT_HEADERS = {
112
- openrouter: ["http-referer", "x-openrouter-title", "x-openrouter-categories"],
112
+ openrouter: ["http-referer", "x-title", "x-openrouter-title", "x-openrouter-categories"],
113
113
  nvidia: ["x-billing-invoke-origin"],
114
114
  opencode: ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
115
115
  "opencode-go": ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
@@ -12,7 +12,6 @@ export const RESERVED_VERBS = new Set([
12
12
  "convert",
13
13
  "costs",
14
14
  "deploy",
15
- "dev",
16
15
  "disable",
17
16
  "doctor",
18
17
  "enable",
@@ -1,6 +1,6 @@
1
- // Pinned mirror of cloud/internal/verifiedmethod.Methods(). DO NOT EDIT.
2
- // The receipt runtime contract test fails if this list drifts from the Go
3
- // registry that signs and ingests billable receipts.
1
+ // Pinned mirror of the Caveman Cloud verified-method registry. DO NOT EDIT.
2
+ // Where that Go registry (which signs and ingests billable receipts) is present,
3
+ // the receipts runtime test fails if this list drifts from it.
4
4
  export const VERIFIED_SAVINGS_METHODS = [
5
5
  "provider_causal_cache",
6
6
  "provider_causal_cache_bedrock",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caveman-ai/cli",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
4
4
  "description": "Caveman CLI — wrap coding agents with recoverable local context compression and truthful metering (`caveman claude`), then drive Caveman Cloud from terminal. Compression and metering run in companion Go binaries: run `caveman setup` to see install state. Local savings stay inferred until verified.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",