@caveman-ai/cli 1.3.3 → 1.3.4

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
@@ -12,7 +12,7 @@ import { fileURLToPath } from "node:url";
12
12
  import { parseEnv } from "node:util";
13
13
  import { PROFILES } from "./agents.generated.js";
14
14
  import { BINARY_RELEASE, BINARY_RELEASE_BASE_DEFAULT, BINARY_SIGNING_PUBKEY, } from "./binaries.generated.js";
15
- import { installProxyAwareFetch } from "./proxy-fetch.js";
15
+ import { installProxyAwareFetch, resolveProxyUrl } from "./proxy-fetch.js";
16
16
  import { RECIPES } from "./recipes.generated.js";
17
17
  import { PRACTICE_REGISTRY } from "./practices.generated.js";
18
18
  import { RESERVED_VERBS } from "./reserved-verbs.generated.js";
@@ -22,6 +22,9 @@ import { NATIVE_CORE, NATIVE_PACK, NATIVE_SKILL_INSTRUCTIONS } from "./native-pa
22
22
  import { serveAgentMcp, } from "./agent-mcp.js";
23
23
  import { portableInvocation } from "./portable-command.js";
24
24
  import { hardenedGitArgs, hardenedGitEnv } from "./git-safe.js";
25
+ import { publishedForwardHeadersOf, publishedUpstreamsOf, unforwardedProviderHeaders, verifiedProviderRoute } from "./provider-routing.js";
26
+ import { openClawRequestCompatibilityIssue, preserveOpenClawProviderCompat } from "./openclaw-provider-compat.js";
27
+ import { parseStatsOptions, renderStatsSummary, STATS_HELP, STATS_USAGE } from "./stats-cli.js";
25
28
  export const overlayBuilders = {};
26
29
  const wrapTempDirs = new Set();
27
30
  // The standalone proxy listens here; `caveman start` launches it and
@@ -1041,7 +1044,7 @@ function exploreUsage() {
1041
1044
  console.error(`usage: ${invokedCommand("explore")} install [--agent claude] [--user] [--dir <path>]`);
1042
1045
  console.error(" legacy alias for tools skills install caveman-explore");
1043
1046
  console.error(" --agent claude target Claude Code (default; codex is not wired yet)");
1044
- console.error(" --user install for all repos (~/.claude/skills) instead of this one");
1047
+ console.error(" --user install in the Claude profile's skills directory for all repos");
1045
1048
  console.error(" --dir <path> write SKILL.md into <path>");
1046
1049
  process.exit(2);
1047
1050
  }
@@ -1206,7 +1209,7 @@ function discoverSkillTargets(rest) {
1206
1209
  targets.push({ name: profile.id, dir: "", agent: profile.id });
1207
1210
  continue;
1208
1211
  }
1209
- const roots = [...profile.skills.user_dirs.map(resolveSkillRoot)];
1212
+ const roots = profile.skills.user_dirs.map((path) => resolveSkillRoot(agentUserPath(profile.id, path)));
1210
1213
  if (rest.includes("--project"))
1211
1214
  roots.push(...(profile.skills.project_dirs ?? []).map(resolveSkillRoot));
1212
1215
  for (const root of roots)
@@ -1475,8 +1478,8 @@ function skillsUsage() {
1475
1478
  console.error(" add <source> install any Git/URL/local source through the official Skills CLI, then pixelize new Claude Code/Codex skills");
1476
1479
  console.error(" accepts npx skills add flags such as --skill, --agent, --global, --list, --yes, and --all");
1477
1480
  console.error(" --agent claude Claude Code (default) — writes .claude/skills/<name>/SKILL.md");
1478
- console.error(" --agent codex Codex — writes ~/.codex/skills/<name>/SKILL.md");
1479
- console.error(" --user install for all repos (~/.claude/skills) instead of this one");
1481
+ console.error(" --agent codex Codex — writes skills/<name>/SKILL.md inside CODEX_HOME (default ~/.codex)");
1482
+ console.error(" --user install in the Claude profile's skills directory for all repos");
1480
1483
  console.error(" --dir <path> single: write SKILL.md there; suite: write <path>/<name>/SKILL.md");
1481
1484
  console.error(" --density LEVEL pixel pack geometry (default balanced): conservative|balanced|max");
1482
1485
  console.error(" --no-pixel install plain SKILL.md without pixel conversion");
@@ -1677,12 +1680,12 @@ function skillDestination(name, rest, multiple, agent) {
1677
1680
  return join(directDir, ...(multiple ? [name, "SKILL.md"] : ["SKILL.md"]));
1678
1681
  if (agent === "claude") {
1679
1682
  const root = rest.includes("--user")
1680
- ? join(homedir(), ".claude", "skills")
1683
+ ? join(claudeConfigDir(), "skills")
1681
1684
  : join(process.cwd(), ".claude", "skills");
1682
1685
  return join(root, name, "SKILL.md");
1683
1686
  }
1684
1687
  if (agent === "codex")
1685
- return join(homedir(), ".codex", "skills", name, "SKILL.md");
1688
+ return join(codexHomeDir(), "skills", name, "SKILL.md");
1686
1689
  console.error(`caveman skills: --agent must be claude or codex (got ${agent})`);
1687
1690
  process.exit(2);
1688
1691
  }
@@ -1690,9 +1693,9 @@ function externalSkillRoots(args) {
1690
1693
  const global = args.includes("--global") || args.includes("-g");
1691
1694
  if (global) {
1692
1695
  return [
1693
- { root: join(homedir(), ".claude", "skills"), agent: "claude" },
1696
+ { root: join(claudeConfigDir(), "skills"), agent: "claude" },
1694
1697
  { root: join(homedir(), ".agents", "skills"), agent: "codex" },
1695
- { root: join(homedir(), ".codex", "skills"), agent: "codex" },
1698
+ { root: join(codexHomeDir(), "skills"), agent: "codex" },
1696
1699
  ];
1697
1700
  }
1698
1701
  return [
@@ -1755,7 +1758,9 @@ function runExternalSkillAdd(rest) {
1755
1758
  const noPixel = rest.includes("--no-pixel");
1756
1759
  const args = stripCavemanSkillAddOptions(rest);
1757
1760
  const listOnly = args.includes("--list") || args.includes("-l");
1758
- const roots = externalSkillRoots(args);
1761
+ // Listing and plain installation delegate all path decisions upstream.
1762
+ // Resolving unrelated profiles here can reject an otherwise valid command.
1763
+ const roots = noPixel || listOnly ? [] : externalSkillRoots(args);
1759
1764
  const before = noPixel || listOnly ? new Map() : snapshotExternalSkills(roots);
1760
1765
  if (!noPixel && !listOnly && !args.includes("--copy"))
1761
1766
  args.push("--copy");
@@ -1867,7 +1872,7 @@ async function skills(rest) {
1867
1872
  installed.push({ name, dest, pixelResult });
1868
1873
  }
1869
1874
  const note = agent === "codex"
1870
- ? "Codex auto-loads skill directories from ~/.codex/skills."
1875
+ ? `Codex auto-loads skill directories from ${join(codexHomeDir(), "skills")}.`
1871
1876
  : "Claude Code auto-loads this skill when its description matches.";
1872
1877
  const lines = installed.flatMap(({ name, dest, pixelResult }) => [
1873
1878
  `${mark("ok")} ${name}: ${cyan(dest)}`,
@@ -2079,7 +2084,12 @@ function probeVersionedBinary(binary, requiredCapability) {
2079
2084
  return { ...cached, current: cached.capabilities.includes(requiredCapability) };
2080
2085
  let result = { version: "pre-versioned", capabilities: [] };
2081
2086
  try {
2082
- const raw = execFileSync(binary, ["version", "--json"], {
2087
+ // An npm-installed caveman-mcp on Windows is a `.cmd` shim, which Node
2088
+ // refuses to execFile directly (CVE-2024-27980). Route through the same
2089
+ // shim-aware invocation every other launch site uses; a shim that cannot
2090
+ // be launched safely throws and lands in the fail-closed branch below.
2091
+ const invocation = portableInvocation(binary, ["version", "--json"]);
2092
+ const raw = execFileSync(invocation.command, invocation.args, {
2083
2093
  encoding: "utf8",
2084
2094
  env: process.env,
2085
2095
  timeout: versionedBinaryProbeTimeoutMs(),
@@ -2530,7 +2540,7 @@ function readMcpServerMarker(agent, serverName) {
2530
2540
  }
2531
2541
  }
2532
2542
  function claudeMcpRegistration(serverName) {
2533
- const path = join(homedir(), ".claude.json");
2543
+ const path = claudeGlobalConfigPath();
2534
2544
  const bytes = fileBytes(path);
2535
2545
  if (!bytes)
2536
2546
  return { present: false, command: "", args: [], exact_shape: false };
@@ -2564,7 +2574,7 @@ function installAgentNativeCloudMcp(agent, mcp) {
2564
2574
  return;
2565
2575
  }
2566
2576
  const installed = agent === "claude"
2567
- ? installMcpJson(join(homedir(), ".claude.json"), ["mcpServers", "caveman-cloud"], { command: mcp.command, args: mcp.args })
2577
+ ? installMcpJson(claudeGlobalConfigPath(), ["mcpServers", "caveman-cloud"], { command: mcp.command, args: mcp.args })
2568
2578
  : installMcpForAgent(findAgent(agent), mcp, "caveman-cloud");
2569
2579
  if (!installed)
2570
2580
  throw new Error(`could not install caveman-cloud MCP for ${agent}`);
@@ -2572,7 +2582,7 @@ function installAgentNativeCloudMcp(agent, mcp) {
2572
2582
  }
2573
2583
  function uninstallAgentNativeCloudMcp(agent) {
2574
2584
  const removed = agent === "claude"
2575
- ? removeMcpJson(join(homedir(), ".claude.json"), ["mcpServers", "caveman-cloud"])
2585
+ ? removeMcpJson(claudeGlobalConfigPath(), ["mcpServers", "caveman-cloud"])
2576
2586
  : uninstallMcpForAgent(findAgent(agent), "caveman-cloud");
2577
2587
  if (!removed)
2578
2588
  throw new Error(`could not remove caveman-cloud MCP for ${agent}`);
@@ -2586,7 +2596,7 @@ function uninstallAgentNativeCloudMcp(agent) {
2586
2596
  }
2587
2597
  function agentNativeSkillFiles(agent) {
2588
2598
  const names = AGENT_SKILL_SUITES["agent-native"] ?? [];
2589
- const root = agent === "claude" ? join(homedir(), ".claude", "skills") : join(homedir(), ".codex", "skills");
2599
+ const root = agent === "claude" ? join(claudeConfigDir(), "skills") : join(codexHomeDir(), "skills");
2590
2600
  return names.map((name) => ({ name, file: join(root, name, "SKILL.md"), body: SKILLS[name] }));
2591
2601
  }
2592
2602
  function restoreAgentNativeBundleSkills(skills) {
@@ -2658,7 +2668,7 @@ function skillMatchesBefore(skill) {
2658
2668
  function agentNativeCloudMcpHostAbsent(agent) {
2659
2669
  if (agent === "claude")
2660
2670
  return !claudeMcpRegistration("caveman-cloud").present;
2661
- const config = fileBytes(join(homedir(), ".codex", "config.toml"))?.toString("utf8") ?? "";
2671
+ const config = fileBytes(join(codexHomeDir(), "config.toml"))?.toString("utf8") ?? "";
2662
2672
  return !config.includes("[mcp_servers.caveman-cloud]");
2663
2673
  }
2664
2674
  function agentNativeCloudMcpAbsent(agent) {
@@ -2763,7 +2773,7 @@ function preflightAgentNativeBundleComponents(agent, existingBundle) {
2763
2773
  }
2764
2774
  return;
2765
2775
  }
2766
- const config = fileBytes(join(homedir(), ".codex", "config.toml"))?.toString("utf8") ?? "";
2776
+ const config = fileBytes(join(codexHomeDir(), "config.toml"))?.toString("utf8") ?? "";
2767
2777
  if (!config.includes("[mcp_servers.caveman-cloud]"))
2768
2778
  return;
2769
2779
  if (!readMcpServerMarker("codex", "caveman-cloud")) {
@@ -3424,23 +3434,13 @@ export const OFF_STATES = {
3424
3434
  },
3425
3435
  runningModeMismatch: (running, resolvedMode) => ({
3426
3436
  id: "running-mode-mismatch",
3427
- line: `a caveman proxy is already running in ${running} mode — this session is not compressed; the next run restarts it to pick up ${resolvedMode}`,
3428
- fix: "caveman run -- <your agent>",
3429
- }),
3430
- runningModeHeld: (running, resolvedMode) => ({
3431
- id: "running-mode-mismatch",
3432
- line: `a caveman proxy is already running in ${running} mode — another live session holds it, so this session keeps that mode instead of restarting to ${resolvedMode}`,
3433
- fix: "caveman run -- <your agent>",
3437
+ line: `a caveman proxy is already running in ${running} mode; keeping it running to protect existing sessions instead of switching to ${resolvedMode}`,
3438
+ fix: "restart the proxy explicitly after existing sessions finish, then retry",
3434
3439
  }),
3435
3440
  runningGateMismatch: {
3436
3441
  id: "running-gate-mismatch",
3437
3442
  line: "running caveman proxy has stale recovery state — launching this agent direct to avoid unsafe compression",
3438
- fix: "stop other wrapped sessions, then run this command again",
3439
- },
3440
- runningGateHeld: {
3441
- id: "running-gate-mismatch",
3442
- line: "another live session holds a caveman proxy with different recovery state — launching this agent direct to avoid unsafe compression",
3443
- fix: "stop other wrapped sessions, then run this command again",
3443
+ fix: "restart the proxy explicitly after existing sessions finish, then retry",
3444
3444
  },
3445
3445
  foreignProcess: (host, port) => ({
3446
3446
  id: "foreign-process",
@@ -4986,67 +4986,18 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
4986
4986
  : OFF_STATES.staleBinary("caveman-proxy", proxyVersion?.version ?? "unknown", cliVersion());
4987
4987
  }
4988
4988
  else if (!proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
4989
- if (countOtherLiveProxySessions(port, sessionMarker) > 0) {
4990
- runtimeState = !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
4991
- ? OFF_STATES.runningGateHeld
4992
- : OFF_STATES.runningModeHeld(runtime.mode ?? "unknown", effectiveMode);
4993
- }
4994
- else {
4995
- const beforeSignal = readRawProxyRunState(port);
4996
- const sameGeneration = beforeSignal.owner !== "unknown"
4997
- && beforeSignal.instance_token === runtime.instance_token
4998
- && beforeSignal.pid === runtime.pid;
4999
- if (sameGeneration && typeof runtime.pid === "number") {
5000
- try {
5001
- process.kill(runtime.pid, "SIGTERM");
5002
- const deadline = Date.now() + proxyRestartTimeoutMs();
5003
- let successor = false;
5004
- while (Date.now() < deadline) {
5005
- await sleep(100);
5006
- const generation = readRawProxyRunState(port);
5007
- if (generation.owner !== "unknown" && generation.instance_token !== runtime.instance_token) {
5008
- successor = true;
5009
- break;
5010
- }
5011
- if (!(await portListening(host, port)))
5012
- break;
5013
- }
5014
- proxyReady = await portListening(host, port);
5015
- if (!proxyReady && !successor) {
5016
- proxyStarted = await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, codexSubscription ? false : observeEstimate ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, codexSubscription ? "codex-subscription" : "standard", observeEstimate);
5017
- proxyReady = await portListening(host, port);
5018
- }
5019
- runtime = proxyReady ? await awaitProxyRuntimeState(port, proxyVersion) : { owner: "unknown" };
5020
- if (runtime.owner === "unknown" || !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
5021
- runtimeState = runtime.owner === "unknown"
5022
- ? OFF_STATES.foreignProcess(host, port)
5023
- : !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
5024
- ? OFF_STATES.runningGateMismatch
5025
- : OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode);
5026
- }
5027
- }
5028
- catch {
5029
- runtime = readProxyRuntimeState(port, proxyVersion);
5030
- runtimeState = runtime.owner === "unknown"
5031
- ? OFF_STATES.foreignProcess(host, port)
5032
- : !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
5033
- ? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
5034
- ? OFF_STATES.runningGateMismatch
5035
- : OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
5036
- : null;
5037
- }
5038
- }
5039
- else {
5040
- runtime = readProxyRuntimeState(port, proxyVersion);
5041
- runtimeState = runtime.owner === "unknown"
5042
- ? OFF_STATES.foreignProcess(host, port)
5043
- : !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
5044
- ? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
5045
- ? OFF_STATES.runningGateMismatch
5046
- : OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
5047
- : null;
5048
- }
5049
- }
4989
+ // A missing wrapper marker does not prove this listener is unused:
4990
+ // native hooks, IDEs, and resumed sessions retain its base URL. Never
4991
+ // signal a shared proxy to change this new session's mode or recovery.
4992
+ // Re-read once in case another operator already replaced the generation.
4993
+ runtime = readProxyRuntimeState(port, proxyVersion);
4994
+ runtimeState = runtime.owner === "unknown"
4995
+ ? OFF_STATES.foreignProcess(host, port)
4996
+ : !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
4997
+ ? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
4998
+ ? OFF_STATES.runningGateMismatch
4999
+ : OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
5000
+ : null;
5050
5001
  }
5051
5002
  }
5052
5003
  if (!proxyReady && !direct) {
@@ -5070,6 +5021,12 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5070
5021
  // Explicit proxy:false leaves subscription Codex in pass-through launch mode
5071
5022
  // without extra status noise; useful for tests and managed launchers.
5072
5023
  }
5024
+ else if (local && !opts.noProxy) {
5025
+ // A failed local optimization layer must not wire the agent to a dead
5026
+ // listener. Direct launch preserves the agent's own provider setup.
5027
+ direct = true;
5028
+ process.stderr.write(`${mark("warn")} Caveman proxy not reachable on ${host}:${port}; launching directly without compression or metering\n`);
5029
+ }
5073
5030
  else if (interactive()) {
5074
5031
  // The proxy is down and we couldn't bring it up. Launching the agent now
5075
5032
  // would wire it to a dead endpoint (every request fails), so offer to run
@@ -5098,7 +5055,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5098
5055
  // A foreign listener on the proxy port is the same failure as a gate
5099
5056
  // mismatch, with a worse consequence: launching routed would hand the
5100
5057
  // operator's provider keys to a process caveman does not own (#945).
5101
- if (runtimeState?.id === "running-gate-mismatch") {
5058
+ if (runtimeState?.id === "running-gate-mismatch" || runtimeState?.id === "running-mode-mismatch") {
5102
5059
  process.stderr.write(`${mark("warn")} ${runtimeState.line}\n`);
5103
5060
  direct = true;
5104
5061
  }
@@ -5178,7 +5135,13 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5178
5135
  // Direct mode: inherit the shell env with NO profile injection, stripping only
5179
5136
  // our own routing if it leaked in — so the agent talks straight to the provider
5180
5137
  // with its own key. Any unrelated base URL the user set themselves stays put.
5181
- const includeShrink = !opts.noShrink && wrapCompressEnabled(opts);
5138
+ // Codex is excluded by design, and the README has said so all along: its runtime
5139
+ // rejects the rewrite (openai/codex#18491). No door actually implemented that, and
5140
+ // since #1037 shrinkHook declines every Codex tool event — so registering it here
5141
+ // bought nothing but a node spawn per tool call. The persistent `caveman enable
5142
+ // codex` door still writes the entry; removing it there needs a migration, since
5143
+ // nativeHookEntriesHealthy would read every existing install as degraded.
5144
+ const includeShrink = !opts.noShrink && wrapCompressEnabled(opts) && agent?.id !== "codex";
5182
5145
  let childArgs = cmdArgs;
5183
5146
  let env;
5184
5147
  try {
@@ -5186,7 +5149,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5186
5149
  ? { ...process.env }
5187
5150
  : agent?.id === "codex"
5188
5151
  ? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, includeShrink, ephemeralDelegateMcp)
5189
- : buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs);
5152
+ : buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs, runtime.owner === "unknown" ? undefined : runtime);
5190
5153
  if (!direct && agent?.id === "claude") {
5191
5154
  const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
5192
5155
  childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
@@ -5202,10 +5165,10 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5202
5165
  childArgs = cmdArgs;
5203
5166
  process.stderr.write(`${mark("warn")} temporary native pack unavailable: ${error.message}; launching ${agent?.display_name ?? bin} directly\n`);
5204
5167
  }
5205
- // Profile args are routing injection too. Qwen's extension lock must never
5206
- // leak into a launch we explicitly classified as direct; preserve only the
5207
- // user's argv on every bypass and native-pack failure path.
5208
- if (direct && agent?.id === "qwen"
5168
+ // Qwen's extension lock and Hermes's forced custom provider are routing
5169
+ // injection too. Remove them on direct fallback so the host keeps the user's
5170
+ // provider and policy. OpenClaw's `chat` is a command, not a routing override.
5171
+ if (direct && (agent?.id === "qwen" || agent?.id === "hermes")
5209
5172
  && agent.args.every((arg, index) => childArgs[index] === arg)) {
5210
5173
  childArgs = childArgs.slice(agent.args.length);
5211
5174
  }
@@ -5473,8 +5436,8 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
5473
5436
  return false;
5474
5437
  }
5475
5438
  // startProxyKeepalive heartbeats the local proxy while the wrapped agent process
5476
- // is alive, so a wrap-owned proxy's idle exit cannot fire under an open-but-quiet
5477
- // session whose ANTHROPIC_BASE_URL still points at it (#860). The proxy treats
5439
+ // is alive, for compatibility with older proxies that still idle-exit (#860).
5440
+ // Current proxy versions never idle-exit. The proxy treats
5478
5441
  // the beat as activity only — nothing is recorded. No immediate beat: launching
5479
5442
  // is already activity, and short-lived runs should never touch the port. The
5480
5443
  // timer is unref'd and every failure is ignored (fail-open, like the hooks).
@@ -5631,8 +5594,7 @@ function stripTrailingCommas(s) {
5631
5594
  }
5632
5595
  return out;
5633
5596
  }
5634
- export function readJson5Lenient(path) {
5635
- const raw = readFileSync(path, "utf8");
5597
+ function parseJsonc(raw) {
5636
5598
  try {
5637
5599
  return JSON.parse(raw);
5638
5600
  }
@@ -5640,6 +5602,9 @@ export function readJson5Lenient(path) {
5640
5602
  return JSON.parse(stripTrailingCommas(stripJson5Comments(raw)));
5641
5603
  }
5642
5604
  }
5605
+ export function readJson5Lenient(path) {
5606
+ return parseJsonc(readFileSync(path, "utf8"));
5607
+ }
5643
5608
  function isPlainObject(v) {
5644
5609
  if (!v || typeof v !== "object" || Array.isArray(v))
5645
5610
  return false;
@@ -5721,9 +5686,9 @@ const OPENCLAW_API_BASE_PATH = {
5721
5686
  "google-generative-ai": "/v1beta",
5722
5687
  };
5723
5688
  const OPENCLAW_WELL_KNOWN_PROVIDERS = {
5724
- openai: { api: "openai-responses", apiKey: "${OPENAI_API_KEY}" },
5725
- anthropic: { api: "anthropic-messages", apiKey: "${ANTHROPIC_API_KEY}" },
5726
- google: { api: "google-generative-ai", apiKey: "${GEMINI_API_KEY}" },
5689
+ openai: { baseUrl: "https://api.openai.com/v1", api: "openai-responses", apiKey: "${OPENAI_API_KEY}" },
5690
+ anthropic: { baseUrl: "https://api.anthropic.com", api: "anthropic-messages", apiKey: "${ANTHROPIC_API_KEY}" },
5691
+ google: { baseUrl: "https://generativelanguage.googleapis.com/v1beta", api: "google-generative-ai", apiKey: "${GEMINI_API_KEY}" },
5727
5692
  "openai-codex": { api: "openai-chatgpt-responses", auth: "oauth" },
5728
5693
  };
5729
5694
  const OPENCLAW_MODEL_DEFAULTS = {
@@ -5829,6 +5794,11 @@ function openClawProviderApi(providerId, provider, model) {
5829
5794
  : undefined;
5830
5795
  return modelApi || providerApi || wellKnownApi;
5831
5796
  }
5797
+ function openClawEffectiveBaseUrl(api, baseUrl) {
5798
+ // OpenClaw normalizeModelCompat removes /v1 before the Anthropic SDK appends
5799
+ // /v1/messages. Pi passes its model base URL to that SDK unchanged.
5800
+ return api === "anthropic-messages" ? baseUrl?.replace(/\/v1\/?$/, "") : baseUrl;
5801
+ }
5832
5802
  function openClawProviderModel(provider, modelId) {
5833
5803
  const models = Array.isArray(provider.models) ? provider.models : [];
5834
5804
  for (const item of models) {
@@ -5865,8 +5835,51 @@ function freshOpenClawModelRef(ctx) {
5865
5835
  function appendUrlPath(base, path) {
5866
5836
  return `${base.replace(/\/+$/, "")}${path}`;
5867
5837
  }
5868
- function codexHomeDir() {
5869
- return join(homedir(), ".codex");
5838
+ export function claudeConfigDir(env = process.env) {
5839
+ return env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(homedir(), ".claude");
5840
+ }
5841
+ export function claudeGlobalConfigPath(env = process.env) {
5842
+ // Claude keeps its default global/MCP config beside ~/.claude, but moves
5843
+ // that file inside a nonempty CLAUDE_CONFIG_DIR override.
5844
+ return env.CLAUDE_CONFIG_DIR ? join(claudeConfigDir(env), ".claude.json") : join(homedir(), ".claude.json");
5845
+ }
5846
+ export function geminiConfigDir(env = process.env) {
5847
+ // GEMINI_CLI_HOME replaces the home directory, not the .gemini directory.
5848
+ return resolve(env.GEMINI_CLI_HOME || homedir(), ".gemini");
5849
+ }
5850
+ function agentUserPath(agent, path) {
5851
+ const prefix = agent === "claude" ? "~/.claude/" : agent === "codex" ? "~/.codex/" : undefined;
5852
+ if (!prefix || !path.startsWith(prefix))
5853
+ return path;
5854
+ const root = agent === "claude" ? claudeConfigDir() : codexHomeDir();
5855
+ return join(root, path.slice(prefix.length));
5856
+ }
5857
+ export function codexHomeDir(env = process.env) {
5858
+ const configured = env.CODEX_HOME;
5859
+ if (!configured)
5860
+ return join(homedir(), ".codex");
5861
+ // Match Codex's own home resolver: a nonempty override may be relative, but
5862
+ // must already be a directory and is canonicalized before use. Never fall
5863
+ // back to another account's default home when the override is invalid.
5864
+ let metadata;
5865
+ try {
5866
+ metadata = statSync(configured);
5867
+ }
5868
+ catch (error) {
5869
+ if (error.code === "ENOENT") {
5870
+ throw new Error(`CODEX_HOME points to ${JSON.stringify(configured)}, but that path does not exist`);
5871
+ }
5872
+ throw new Error(`failed to read CODEX_HOME ${JSON.stringify(configured)}: ${error.message}`);
5873
+ }
5874
+ if (!metadata.isDirectory()) {
5875
+ throw new Error(`CODEX_HOME points to ${JSON.stringify(configured)}, but that path is not a directory`);
5876
+ }
5877
+ try {
5878
+ return realpathSync(configured);
5879
+ }
5880
+ catch (error) {
5881
+ throw new Error(`failed to canonicalize CODEX_HOME ${JSON.stringify(configured)}: ${error.message}`);
5882
+ }
5870
5883
  }
5871
5884
  function codexAuthPath() {
5872
5885
  return join(codexHomeDir(), "auth.json");
@@ -5936,12 +5949,32 @@ function stripCodexCavemanProviderToml(text) {
5936
5949
  }
5937
5950
  return out.join("\n").trimEnd();
5938
5951
  }
5952
+ // The api-key Codex route, in ONE place: the provider TOML writes it, the
5953
+ // install journal records it, and the doctor compares against it, and a route
5954
+ // only three of those four agree on reads as permanently degraded.
5955
+ const CODEX_API_KEY_ROUTE = "/w/codex/v1";
5956
+ function codexGatewayBase(gw, subscription) {
5957
+ // Codex's OpenAI-Responses client appends "/responses" onto base_url itself,
5958
+ // exactly as it does against the real api.openai.com, so what the proxy
5959
+ // receives is `<this path>/responses`. The openai adapter's Routes are a
5960
+ // closed, exact allowlist holding "/v1/responses" and never "/responses", so
5961
+ // the api-key route needs the "/v1" or every api-key Codex session 404s with
5962
+ // cave_route_not_found before one request reaches OpenAI (#1045). Same
5963
+ // convention aider already uses (`/w/aider/openai/v1`). The subscription
5964
+ // route is a different mux handler (`/chatgpt/`) that takes the suffix
5965
+ // verbatim, so it must NOT gain a "/v1".
5966
+ return appendUrlPath(gw, subscription ? "/chatgpt" : CODEX_API_KEY_ROUTE);
5967
+ }
5968
+ // Codex clears the stdio MCP environment, including these non-secret store
5969
+ // selectors. Forward their names so the proxy and recovery server share the
5970
+ // current launch's store without persisting provider credentials or stale paths.
5971
+ const CODEX_RECOVERY_ENV = 'env_vars = ["CAVEMAN_HOME", "CAVEMAN_CCR_DB"]';
5939
5972
  function codexCavemanProviderToml(gw, subscription = true) {
5940
5973
  return [
5941
5974
  `model_provider = "caveman"`,
5942
5975
  `[model_providers.caveman]`,
5943
5976
  `name = "Caveman"`,
5944
- `base_url = ${JSON.stringify(subscription ? appendUrlPath(gw, "/chatgpt") : appendUrlPath(gw, "/w/codex"))}`,
5977
+ `base_url = ${JSON.stringify(codexGatewayBase(gw, subscription))}`,
5945
5978
  `wire_api = "responses"`,
5946
5979
  `requires_openai_auth = true`,
5947
5980
  ].join("\n");
@@ -6134,6 +6167,16 @@ function canonicalManagedHookEntry(entry) {
6134
6167
  hooks[0].command = identity;
6135
6168
  return JSON.stringify(clone);
6136
6169
  }
6170
+ // Why: `think.shrink` (and its `CAVEMAN_SHRINK` env form) is the persisted
6171
+ // switch for the command-output rewrite, but only the ephemeral launcher ever
6172
+ // read it — every native writer passed a literal `true`, so `caveman enable` /
6173
+ // `doctor --fix` / `repairNativeAgent` reinstated `shrink-hook` no matter what
6174
+ // the config said and there was no persistent way to run the native
6175
+ // integration without it (#1049). Read in ONE place so the writers and the
6176
+ // health check that judges them cannot disagree about what is expected.
6177
+ function nativeShrinkEnabled() {
6178
+ return resolveCapabilities().values["think.shrink"].value;
6179
+ }
6137
6180
  function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall = false) {
6138
6181
  const root = JSON.parse(JSON.stringify(base));
6139
6182
  const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
@@ -6157,23 +6200,34 @@ function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall =
6157
6200
  list.push(nativeHookEntry(command, agentId));
6158
6201
  hooks[event] = list;
6159
6202
  }
6160
- if (includeShrink) {
6203
+ {
6161
6204
  const shrinkEvent = agentId === "gemini" ? "BeforeTool" : "PreToolUse";
6162
6205
  const list = Array.isArray(hooks[shrinkEvent]) ? hooks[shrinkEvent] : [];
6163
6206
  const shrinkCommand = `${cavemanBinForHook()} shrink-hook`;
6164
6207
  // Same replace-not-accumulate rule as the native hook: a shrink-hook entry
6165
- // under another caveman path is ours.
6208
+ // under another caveman path is ours. When the switch is OFF the rule has
6209
+ // to reach OUR path too (#1049): `base` is the host's live file, so a
6210
+ // standalone install, or any caveman old enough to predate the switch,
6211
+ // leaves an entry here that honoring the switch only on the entries we ADD
6212
+ // would merge straight through — the rewrite stays live on exactly the
6213
+ // machines that asked for it off, and the install is born degraded because
6214
+ // nativeHookEntriesHealthy rejects a managed entry the expected document
6215
+ // lacks. Withdrawing ours is not a claim on the user's other hooks:
6216
+ // managedHookIdentity only matches a caveman binary.
6166
6217
  for (let i = list.length - 1; i >= 0; i--) {
6167
6218
  const entry = list[i];
6168
6219
  const existing = entry ? hookEntryCommand(entry) : undefined;
6169
- if (existing !== undefined && existing !== shrinkCommand && managedHookIdentity(existing) === "shrink-hook")
6220
+ if (existing === undefined || managedHookIdentity(existing) !== "shrink-hook")
6221
+ continue;
6222
+ if (!includeShrink || existing !== shrinkCommand)
6170
6223
  list.splice(i, 1);
6171
6224
  }
6172
- if (!list.some((entry) => hookEntryCommand(entry) === shrinkCommand)) {
6225
+ if (includeShrink && !list.some((entry) => hookEntryCommand(entry) === shrinkCommand)) {
6173
6226
  list.push(agentId === "gemini"
6174
6227
  ? { matcher: "run_shell_command", ...nativeHookEntry(shrinkCommand, agentId) }
6175
6228
  : nativeHookEntry(shrinkCommand, agentId));
6176
6229
  }
6230
+ // The lifecycle loop above always writes this event, so the key exists either way.
6177
6231
  hooks[shrinkEvent] = list;
6178
6232
  }
6179
6233
  if (agentId === "claude" && includeRecall) {
@@ -6194,6 +6248,8 @@ function assertNativeHooksShape(path, root, agentId) {
6194
6248
  const hooks = root.hooks;
6195
6249
  if (!hooks)
6196
6250
  return;
6251
+ // `true` on purpose, unlike the writers: this only reads the event NAMES to
6252
+ // refuse a non-array, so the superset is the safer set to check.
6197
6253
  const expected = nativeHooksDocument(agentId, true).hooks;
6198
6254
  for (const event of Object.keys(expected)) {
6199
6255
  if (hooks[event] !== undefined && !Array.isArray(hooks[event])) {
@@ -6207,7 +6263,7 @@ function nativeHookEntriesHealthy(root, agentId) {
6207
6263
  : undefined;
6208
6264
  if (!hooks)
6209
6265
  return false;
6210
- const expected = nativeHooksDocument(agentId, true).hooks;
6266
+ const expected = nativeHooksDocument(agentId, nativeShrinkEnabled()).hooks;
6211
6267
  const required = Object.entries(expected).every(([event, expectedRaw]) => {
6212
6268
  const actual = Array.isArray(hooks[event]) ? hooks[event] : [];
6213
6269
  const actualEntries = new Set(actual.map(canonicalManagedHookEntry).filter(Boolean));
@@ -6251,7 +6307,7 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, includeShrink, del
6251
6307
  const providerRoot = providerLines.shift();
6252
6308
  const providerTables = providerLines.join("\n");
6253
6309
  const mcp = mcpBinary
6254
- ? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n`
6310
+ ? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n${CODEX_RECOVERY_ENV}\n`
6255
6311
  : "\n";
6256
6312
  const delegateArgs = delegateMcp?.args.length
6257
6313
  ? `\nargs = [${delegateMcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]`
@@ -6270,6 +6326,9 @@ function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, includeShrink,
6270
6326
  const env = { ...process.env };
6271
6327
  for (const key of WRAP_BASE_URL_ENV_VARS)
6272
6328
  delete env[key];
6329
+ // The ephemeral CODEX_HOME points Codex at the same loopback gateway, so it
6330
+ // needs the same proxy exemption the base-url wrap path gets.
6331
+ Object.assign(env, gatewayNoProxyEnv(gw));
6273
6332
  env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, includeShrink, delegateMcp);
6274
6333
  return env;
6275
6334
  }
@@ -6601,6 +6660,13 @@ function claudeNativeMutations(gw, mcpBinary) {
6601
6660
  && wrapMode(gw) === "local" && proxyAnthropicUpstreamIsFirstParty();
6602
6661
  if (assumeFirstParty)
6603
6662
  env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
6663
+ // Native routing points every later turn at the same loopback gateway, so it
6664
+ // needs the wrap path's proxy exemption too (#1001). Never clobber a value the
6665
+ // user already carries in settings.
6666
+ for (const [key, value] of Object.entries(gatewayNoProxyEnv(gw))) {
6667
+ if (env[key] === undefined)
6668
+ env[key] = value;
6669
+ }
6604
6670
  // Claude Code turns tool search (progressive MCP tool disclosure) OFF as soon
6605
6671
  // as ANTHROPIC_BASE_URL is not a first-party Anthropic host, so pointing it at
6606
6672
  // caveman would otherwise force every MCP tool schema inline on every request
@@ -6610,8 +6676,8 @@ function claudeNativeMutations(gw, mcpBinary) {
6610
6676
  if (env.ENABLE_TOOL_SEARCH === undefined)
6611
6677
  env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
6612
6678
  settings.env = env;
6613
- const withHooks = nativeHooksDocument("claude", true, settings);
6614
- const mcpPath = join(homedir(), ".claude.json");
6679
+ const withHooks = nativeHooksDocument("claude", nativeShrinkEnabled(), settings);
6680
+ const mcpPath = claudeGlobalConfigPath();
6615
6681
  const mcpBefore = fileBytes(mcpPath);
6616
6682
  const mcpRoot = parseJsonFileObject(mcpPath, mcpBefore);
6617
6683
  if (mcpRoot.mcpServers !== undefined && (typeof mcpRoot.mcpServers !== "object" || mcpRoot.mcpServers === null || Array.isArray(mcpRoot.mcpServers))) {
@@ -6677,8 +6743,8 @@ function geminiNativeMutations(gw, mcpBinary) {
6677
6743
  const installedMcp = { command: mcpBinary, args: [] };
6678
6744
  servers.caveman = installedMcp;
6679
6745
  settings.mcpServers = servers;
6680
- const withHooks = nativeHooksDocument("gemini", true, settings);
6681
- const envPath = join(homedir(), ".gemini", ".env");
6746
+ const withHooks = nativeHooksDocument("gemini", nativeShrinkEnabled(), settings);
6747
+ const envPath = join(geminiConfigDir(), ".env");
6682
6748
  const envBefore = fileBytes(envPath);
6683
6749
  const route = appendUrlPath(gw, "/w/gemini");
6684
6750
  const nativeEnv = geminiNativeEnv(envBefore?.toString("utf8") ?? "", route);
@@ -7052,6 +7118,7 @@ function codexNativeConfig(source, gw, subscription, mcpBinary) {
7052
7118
  "",
7053
7119
  "[mcp_servers.caveman]",
7054
7120
  `command = ${JSON.stringify(mcpBinary)}`,
7121
+ CODEX_RECOVERY_ENV,
7055
7122
  CODEX_NATIVE_TABLES_END,
7056
7123
  ].join("\n");
7057
7124
  const middle = stripped ? `\n\n${stripped}` : "";
@@ -7062,12 +7129,12 @@ function codexNativeMutations(gw, mcpBinary) {
7062
7129
  const hooksBefore = fileBytes(hooksPath);
7063
7130
  const hooksRoot = parseJsonFileObject(hooksPath, hooksBefore);
7064
7131
  assertNativeHooksShape(hooksPath, hooksRoot, "codex");
7065
- const hooks = nativeHooksDocument("codex", true, hooksRoot);
7132
+ const hooks = nativeHooksDocument("codex", nativeShrinkEnabled(), hooksRoot);
7066
7133
  const configPath = join(codexHomeDir(), "config.toml");
7067
7134
  const configBefore = fileBytes(configPath);
7068
7135
  const subscription = detectCodexWrapAuthMode() === "subscription";
7069
7136
  const native = codexNativeConfig(configBefore?.toString("utf8") ?? "", gw, subscription, mcpBinary);
7070
- const route = appendUrlPath(gw, subscription ? "/chatgpt" : "/w/codex");
7137
+ const route = codexGatewayBase(gw, subscription);
7071
7138
  return [
7072
7139
  { file: hooksPath, before: hooksBefore, after: Buffer.from(JSON.stringify(hooks, null, 2) + "\n"), kind: "codex-hooks" },
7073
7140
  {
@@ -7296,7 +7363,7 @@ function hermesNativeConfig(source, gw, mcpBinary) {
7296
7363
  const routeBlock = [
7297
7364
  ` ${HERMES_NATIVE_ROUTE_BEGIN}`,
7298
7365
  ' provider: "custom"',
7299
- ` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes"))}`,
7366
+ ` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes/v1"))}`,
7300
7367
  ` ${HERMES_NATIVE_ROUTE_END}`,
7301
7368
  ];
7302
7369
  lines.splice(insertAt, 0, ...routeBlock);
@@ -7343,7 +7410,7 @@ function hermesNativeConfig(source, gw, mcpBinary) {
7343
7410
  return {
7344
7411
  text: yamlText(lines),
7345
7412
  owned: {
7346
- route: appendUrlPath(gw, "/w/hermes"),
7413
+ route: appendUrlPath(gw, "/w/hermes/v1"),
7347
7414
  route_block: routeBlock.join("\n"),
7348
7415
  previous_route_lines: previousRouteLines,
7349
7416
  plugin_block: pluginBlock,
@@ -7687,7 +7754,10 @@ function enableNative(argv) {
7687
7754
  if (existing.installed) {
7688
7755
  if (existing.state === "installed")
7689
7756
  return "already";
7690
- throw new Error(`${profile.display_name} integration is degraded; run \`caveman doctor ${agent}\` before changing it`);
7757
+ // `--fix` on purpose: bare `caveman doctor <agent>` prints JSON that says
7758
+ // `degraded` and nothing that says how to leave that state, so pointing
7759
+ // at it alone dead-ends the user who followed this line here (#1049).
7760
+ throw new Error(`${profile.display_name} integration is degraded; run \`caveman doctor ${agent} --fix\` before changing it`);
7691
7761
  }
7692
7762
  const mutations = nativeMutationsFor(agent, gw, mcpBinary);
7693
7763
  const route = mutations.find((item) => typeof item.owned?.route === "string")?.owned?.route;
@@ -7701,7 +7771,12 @@ function enableNative(argv) {
7701
7771
  ? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
7702
7772
  : agent === "pi"
7703
7773
  ? ` lifecycle/Core/tool rewrite: bundled Pi extension -> ${nativeHookCommand(agent)}\n`
7704
- : ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
7774
+ // Codex gets the lifecycle line without the "tool rewrite" claim: since
7775
+ // #1037 shrink-hook declines every Codex tool event, so promising one here
7776
+ // would be the same false claim `doctor` used to report.
7777
+ : agent === "codex"
7778
+ ? ` lifecycle/Core: ${nativeHookCommand(agent)}; command-output rewrite unavailable in Codex\n`
7779
+ : ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
7705
7780
  applyNativeMutations(agent, profile, mutations);
7706
7781
  return "enabled";
7707
7782
  });
@@ -7738,6 +7813,8 @@ function removeNativeHookEntries(root, agent) {
7738
7813
  : undefined;
7739
7814
  if (!hooks)
7740
7815
  return root;
7816
+ // `true` on purpose, unlike the writers: disable must withdraw a shrink entry
7817
+ // an earlier install wrote, whatever the config says now.
7741
7818
  const expected = nativeHooksDocument(agent, true).hooks;
7742
7819
  const allowedManaged = new Set(Object.values(expected)
7743
7820
  .flatMap((raw) => Array.isArray(raw) ? raw : [])
@@ -8212,7 +8289,9 @@ function nativeIntegrationStatus(agent) {
8212
8289
  const coreResolution = runtimeConfig.resolution.values["think.core"];
8213
8290
  const coreConfigured = coreResolution.value === true;
8214
8291
  const mcp = probeMcpBinary();
8215
- const expectedRoute = appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : agent === "aider" ? "/w/aider/openai/v1" : detectCodexWrapAuthMode() === "subscription" ? "/chatgpt" : "/w/codex");
8292
+ const expectedRoute = agent === "codex"
8293
+ ? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
8294
+ : appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
8216
8295
  const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : agent === "pi" ? "pi-extension" : "aider-config";
8217
8296
  const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
8218
8297
  // Pi's artifact encodes no route: the extension resolves the gateway at
@@ -8249,7 +8328,13 @@ function nativeIntegrationStatus(agent) {
8249
8328
  lifecycle_hooks: agent !== "aider" && ownedHealthy,
8250
8329
  core: coreActive,
8251
8330
  mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
8252
- tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" ? false : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes("shrink-hook")),
8331
+ // Codex is false for the same reason hermes is: no command rewrite happens. The
8332
+ // shrink-hook entry is still written into ~/.codex/hooks.json (removing it from
8333
+ // nativeHooksDocument would make every existing install read as degraded, since
8334
+ // nativeHookEntriesHealthy rejects a managed entry the expected document lacks),
8335
+ // but since #1037 shrinkHook declines every Codex tool event, so the presence of
8336
+ // that entry no longer evidences a rewrite. Report the behavior, not the file.
8337
+ tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" || agent === "codex" ? false : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes("shrink-hook")),
8253
8338
  shared_runtime: proxyHealthy,
8254
8339
  };
8255
8340
  const versionStatus = nativeVersionStatus(host.version, profile.tested_agent_version);
@@ -8550,9 +8635,6 @@ function buildOpenClawOverlay(_agent, baseConfig, ctx) {
8550
8635
  const configuredRef = resolveOpenClawPrimaryRef(baseConfig);
8551
8636
  const ref = configuredRef ?? freshOpenClawModelRef(ctx);
8552
8637
  const synthesized = configuredRef === undefined;
8553
- if (synthesized) {
8554
- process.stderr.write(`caveman: openclaw primary model not found; routing fresh config through caveman/${ref.model}\n`);
8555
- }
8556
8638
  const provider = resolveOpenClawProvider(baseConfig, ref.provider);
8557
8639
  if (!provider) {
8558
8640
  process.stderr.write(`caveman: openclaw provider "${ref.provider}" not found; leaving primary model unchanged\n`);
@@ -8569,11 +8651,74 @@ function buildOpenClawOverlay(_agent, baseConfig, ctx) {
8569
8651
  process.stderr.write(`caveman: openclaw provider "${ref.provider}" has no API adapter; leaving primary model unchanged\n`);
8570
8652
  return overlay;
8571
8653
  }
8572
- const baseUrl = openClawProxyBaseUrl(api, ctx.gatewayUrl);
8654
+ const originalBaseUrl = getString(provider, ["baseUrl"]) ?? getString(OPENCLAW_WELL_KNOWN_PROVIDERS[ref.provider], ["baseUrl"]);
8655
+ // A fresh managed setup has no original provider endpoint to preserve. An
8656
+ // existing setup needs the actual listener's routing map, unavailable from a
8657
+ // managed gateway. Preserve it until that endpoint proof exists.
8658
+ const baseUrl = synthesized && ctx.mode === "managed"
8659
+ ? openClawProxyBaseUrl(api, ctx.gatewayUrl)
8660
+ : ctx.mode === "local" ? verifiedProviderRoute(ctx.gatewayUrl, api, ref.provider, openClawEffectiveBaseUrl(api, originalBaseUrl), ctx.upstreams) : undefined;
8573
8661
  if (!baseUrl) {
8574
- process.stderr.write(`caveman: openclaw provider API "${api}" is not mapped to Caveman; leaving primary model unchanged\n`);
8662
+ process.stderr.write(`caveman: openclaw provider "${ref.provider}" endpoint is not verified by the running proxy; leaving primary model unchanged\n`);
8575
8663
  return overlay;
8576
8664
  }
8665
+ if (ctx.mode === "local") {
8666
+ // baseUrl is provider-wide in OpenClaw. A fallback or later model switch
8667
+ // must retain its own API, and every model sharing this override must map
8668
+ // to the same verified SDK base URL.
8669
+ const catalog = Array.isArray(provider.models) ? provider.models : [];
8670
+ const providerApi = openClawProviderApi(ref.provider, provider);
8671
+ const modelApis = [providerApi, ...catalog.map(model => openClawProviderApi(ref.provider, provider, asJsonObject(model)))].filter((value) => value !== undefined);
8672
+ if (modelApis.some(modelApi => verifiedProviderRoute(ctx.gatewayUrl, modelApi, ref.provider, openClawEffectiveBaseUrl(modelApi, originalBaseUrl), ctx.upstreams) !== baseUrl)) {
8673
+ process.stderr.write(`caveman: openclaw provider "${ref.provider}" uses model APIs with different routes; leaving provider unchanged\n`);
8674
+ return overlay;
8675
+ }
8676
+ const request = asJsonObject(provider.request);
8677
+ const requestIssue = openClawRequestCompatibilityIssue(provider.request);
8678
+ if (requestIssue) {
8679
+ process.stderr.write(`caveman: openclaw provider "${ref.provider}" stays direct because ${requestIssue}; proxy compression is off for this provider\n`);
8680
+ return overlay;
8681
+ }
8682
+ const headerRequirements = [{ api: providerApi ?? api, headers: { ...asJsonObject(provider.headers), ...asJsonObject(request?.headers) } }, ...catalog.map(model => ({
8683
+ api: openClawProviderApi(ref.provider, provider, asJsonObject(model)),
8684
+ headers: { ...asJsonObject(provider.headers), ...asJsonObject(asJsonObject(model)?.headers), ...asJsonObject(request?.headers) },
8685
+ }))];
8686
+ const missingHeaders = uniqueStrings(headerRequirements.flatMap(requirement => unforwardedProviderHeaders(requirement.api, ref.provider, requirement.headers, ctx.upstreams)));
8687
+ if (missingHeaders.length) {
8688
+ const remedy = missingHeaders.some(name => ["authorization", "x-api-key", "x-goog-api-key"].includes(name.toLowerCase()))
8689
+ ? "the proxy cannot preserve this authentication override; keep the provider direct"
8690
+ : `configure compat.${ref.provider}.forward_headers or keep the provider direct`;
8691
+ process.stderr.write(`caveman: openclaw provider "${ref.provider}" requires headers not preserved by the running proxy (${missingHeaders.join(", ")}); ${remedy}\n`);
8692
+ return overlay;
8693
+ }
8694
+ const routedModels = [];
8695
+ for (const rawModel of catalog.length ? catalog : [openClawMirroredModel(ref, provider, providerModel)]) {
8696
+ const model = asJsonObject(rawModel);
8697
+ const modelApi = openClawProviderApi(ref.provider, provider, model);
8698
+ if (!model || typeof model.id !== "string" || !modelApi || !originalBaseUrl) {
8699
+ process.stderr.write(`caveman: openclaw provider "${ref.provider}" has an unresolved model catalog; leaving provider unchanged\n`);
8700
+ return overlay;
8701
+ }
8702
+ const preserved = preserveOpenClawProviderCompat({ provider: ref.provider, id: model.id, api: modelApi, baseUrl: originalBaseUrl, compat: model.compat });
8703
+ if (!preserved.ok) {
8704
+ process.stderr.write(`caveman: openclaw provider "${ref.provider}" stays direct because ${preserved.reason}; proxy compression is off for this provider\n`);
8705
+ return overlay;
8706
+ }
8707
+ routedModels.push({ ...model, ...(preserved.compat ? { compat: preserved.compat } : {}) });
8708
+ }
8709
+ const headers = { ...asJsonObject(provider.headers), [OPENCLAW_AGENT_HEADER]: "openclaw" };
8710
+ const workflowSlug = normalizeWorkflowSlug(process.env["CAVE_WORKFLOW"]);
8711
+ if (workflowSlug)
8712
+ headers["x-cave-workflow"] = workflowSlug;
8713
+ const routedProvider = { ...provider, baseUrl, ...(providerApi ? { api: providerApi } : {}), headers,
8714
+ models: routedModels };
8715
+ return deepMerge(overlay, {
8716
+ models: { mode: "merge", providers: { [ref.provider]: routedProvider } },
8717
+ ...(synthesized ? { agents: { defaults: { model: { primary: ref.raw } } } } : {}),
8718
+ });
8719
+ }
8720
+ if (synthesized)
8721
+ process.stderr.write(`caveman: openclaw primary model not found; routing fresh config through caveman/${ref.model}\n`);
8577
8722
  const sourceApiKey = openClawResolvedProviderApiKey(ref.provider, provider);
8578
8723
  const headers = { [OPENCLAW_AGENT_HEADER]: "openclaw" };
8579
8724
  const workflowSlug = normalizeWorkflowSlug(process.env["CAVE_WORKFLOW"]);
@@ -8630,7 +8775,7 @@ function withoutCavemanMcpServer(overlay) {
8630
8775
  delete next["mcp"];
8631
8776
  return next;
8632
8777
  }
8633
- function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto", agentArgs = []) {
8778
+ function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto", agentArgs = [], upstreams) {
8634
8779
  const baseConfig = readBaseConfig(inj);
8635
8780
  const mode = wrapMode(modeGw);
8636
8781
  const staticOverlay = mode === "managed" && inj.config_overlay.managed !== undefined ? inj.config_overlay.managed : inj.config_overlay.local;
@@ -8642,7 +8787,7 @@ function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "a
8642
8787
  throw new Error("cannot safely resolve Qwen's effective OPENAI_API_KEY");
8643
8788
  renderOptions.optionalOpenAIKeyEnvAvailable = available;
8644
8789
  }
8645
- let rawOverlay = renderDeep(builder ? builder(agent, baseConfig, { mode, gatewayUrl: gw, env }) : staticOverlay, gw, env, renderOptions);
8790
+ let rawOverlay = renderDeep(builder ? builder(agent, baseConfig, { mode, gatewayUrl: gw, env, upstreams }) : staticOverlay, gw, env, renderOptions);
8646
8791
  if (agent.id === "qwen" && mcpMode === "auto") {
8647
8792
  const ownedMcp = ownedMcpRegistration(agent.id, agentArgs);
8648
8793
  if (ownedMcp) {
@@ -8700,10 +8845,46 @@ function cleanupWrapTempDirs() {
8700
8845
  }
8701
8846
  }
8702
8847
  const WRAP_BASE_URL_ENV_VARS = ["ANTHROPIC_BASE_URL", "OPENAI_BASE_URL", "OPENAI_API_BASE", "GOOGLE_GEMINI_BASE_URL"];
8848
+ // A corporate HTTP(S)_PROXY in the operator's shell applies to the wrapped agent
8849
+ // too, so the agent's own hop to caveman's loopback listener gets handed to that
8850
+ // proxy and times out — #1001's symptom, one layer above the proxy's own
8851
+ // upstream_proxy support. Exempt exactly the gateway host, appending to whatever
8852
+ // NO_PROXY the operator already set and using the spelling they already use.
8853
+ // resolveProxyUrl returns null both when no proxy applies and when NO_PROXY
8854
+ // already covers the gateway, which are precisely the cases needing no change.
8855
+ function gatewayNoProxyEnv(gw, env = process.env) {
8856
+ let target;
8857
+ try {
8858
+ target = new URL(gw);
8859
+ }
8860
+ catch {
8861
+ return {};
8862
+ }
8863
+ // Only a loopback listener needs the exemption. A managed gateway is a public
8864
+ // host that the operator's proxy is supposed to carry; exempting it there
8865
+ // sends the agent straight at a firewall that drops direct egress.
8866
+ if (wrapMode(gw) !== "local")
8867
+ return {};
8868
+ if (!resolveProxyUrl(target, env))
8869
+ return {};
8870
+ // Append to each spelling the operator actually set, reading the value from
8871
+ // the same variable it is written back to. Choosing the name by definedness
8872
+ // and the value with ?? dropped the other spelling's entries.
8873
+ const names = env.NO_PROXY === undefined && env.no_proxy !== undefined ? ["no_proxy"] : ["NO_PROXY"];
8874
+ if (env.NO_PROXY !== undefined && env.no_proxy !== undefined)
8875
+ names.push("no_proxy");
8876
+ const out = {};
8877
+ for (const name of names) {
8878
+ const current = (env[name] ?? "").trim();
8879
+ out[name] = current ? `${current},${target.hostname}` : target.hostname;
8880
+ }
8881
+ return out;
8882
+ }
8703
8883
  function wrapBaseUrlEnv(gw) {
8704
8884
  const env = {};
8705
8885
  for (const key of WRAP_BASE_URL_ENV_VARS)
8706
8886
  env[key] = gw;
8887
+ Object.assign(env, gatewayNoProxyEnv(gw));
8707
8888
  // Same reason as the native-enable path: redirecting ANTHROPIC_BASE_URL makes
8708
8889
  // Claude Code drop tool search and inline every MCP tool schema. Inert for the
8709
8890
  // other wrappable agents, which never read this variable. A value already in
@@ -8821,7 +9002,7 @@ function applyClaudeBedrockWrap(env, agent, renderedGw, modeGw) {
8821
9002
  // one production caller passes the SAME opts.mcpMode that wrapMcpRecoveryAvailable
8822
9003
  // reads, which is what keeps "what we inject" and "what we tell the proxy" from
8823
9004
  // ever disagreeing.
8824
- export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentArgs = []) {
9005
+ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentArgs = [], upstreams) {
8825
9006
  if (agent?.id === "gemini" && wrapMode(gw) === "managed") {
8826
9007
  throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
8827
9008
  }
@@ -8880,11 +9061,27 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentAr
8880
9061
  rendered = deepMerge(rendered, { mcp: { caveman: kiloMcpEntry(ownedMcp) } });
8881
9062
  }
8882
9063
  }
9064
+ if (agent.id === "opencode" && process.env[inj.env_var]) {
9065
+ // OpenCode treats inline JSONC as its own configuration layer. Replacing
9066
+ // that layer loses the user's model, account, permissions and MCP servers.
9067
+ // Preserve native {env:...}/{file:...} references for OpenCode to resolve
9068
+ // in the same context; only our routing fields take precedence.
9069
+ let original;
9070
+ try {
9071
+ original = parseJsonc(process.env[inj.env_var]);
9072
+ }
9073
+ catch {
9074
+ throw new Error("cannot preserve opencode inline configuration; launching with the original configuration is required");
9075
+ }
9076
+ if (!isPlainObject(original))
9077
+ throw new Error("opencode inline configuration must be a JSON object");
9078
+ rendered = deepMerge(original, rendered);
9079
+ }
8883
9080
  env[inj.env_var] = JSON.stringify(rendered);
8884
9081
  }
8885
9082
  else if (inj.method === "config-file") {
8886
9083
  try {
8887
- applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode, agentArgs);
9084
+ applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode, agentArgs, upstreams);
8888
9085
  }
8889
9086
  catch (e) {
8890
9087
  // OpenClaw ignores the generic base-URL union. Config injection is its only
@@ -10176,8 +10373,16 @@ const HERMES_MCP_END = "# <<< caveman:mcp";
10176
10373
  const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
10177
10374
  const HERMES_PLUGIN_ENABLE_END = "# <<< caveman:hermes-plugin-enable";
10178
10375
  const HERMES_PLUGIN_NAME = "caveman_shrink";
10179
- function hermesHome() {
10180
- return expandTilde(process.env.HERMES_HOME || "~/.hermes");
10376
+ export function hermesHome(env = process.env, platform = process.platform) {
10377
+ // Hermes 0.19.1 hermes_constants.py: native Windows uses LOCALAPPDATA,
10378
+ // overrides are stripped, and Path(value) does not expand a literal tilde.
10379
+ const override = env.HERMES_HOME?.trim();
10380
+ if (override)
10381
+ return resolve(override);
10382
+ if (platform === "win32") {
10383
+ return join(env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "hermes");
10384
+ }
10385
+ return join(homedir(), ".hermes");
10181
10386
  }
10182
10387
  function hermesConfigPath() {
10183
10388
  return join(hermesHome(), "config.yaml");
@@ -10400,7 +10605,7 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
10400
10605
  case "qwen":
10401
10606
  throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
10402
10607
  case "gemini":
10403
- return removeMcpJson(join(homedir(), ".gemini", "settings.json"), ["mcpServers", serverName]);
10608
+ return removeMcpJson(geminiSettingsPath(), ["mcpServers", serverName]);
10404
10609
  case "hermes":
10405
10610
  return removeMcpHermesYaml(serverName);
10406
10611
  case "openclaw":
@@ -10412,7 +10617,7 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
10412
10617
  // removeMcpCodexToml drops the exact [mcp_servers.<name>] block mcpInstall wrote
10413
10618
  // (header + its command/args lines, up to the next section or EOF).
10414
10619
  function removeMcpCodexToml(serverName = "caveman") {
10415
- const path = join(homedir(), ".codex", "config.toml");
10620
+ const path = join(codexHomeDir(), "config.toml");
10416
10621
  let existing = "";
10417
10622
  try {
10418
10623
  existing = readFileSync(path, "utf8");
@@ -12476,7 +12681,7 @@ function installMcpForAgent(a, mcp, serverName = "caveman") {
12476
12681
  case "qwen":
12477
12682
  throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
12478
12683
  case "gemini":
12479
- return installMcpJson(join(homedir(), ".gemini", "settings.json"), ["mcpServers", serverName], {
12684
+ return installMcpJson(geminiSettingsPath(), ["mcpServers", serverName], {
12480
12685
  command: mcp.command,
12481
12686
  args: mcp.args,
12482
12687
  });
@@ -12557,7 +12762,7 @@ function installMcpClaude(mcp, serverName = "caveman") {
12557
12762
  }
12558
12763
  }
12559
12764
  function installMcpCodexToml(mcp, serverName = "caveman") {
12560
- const path = join(homedir(), ".codex", "config.toml");
12765
+ const path = join(codexHomeDir(), "config.toml");
12561
12766
  let existing = "";
12562
12767
  try {
12563
12768
  existing = readFileSync(path, "utf8");
@@ -12570,7 +12775,8 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
12570
12775
  }
12571
12776
  const header = `[mcp_servers.${serverName}]`;
12572
12777
  const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((s) => JSON.stringify(s)).join(", ")}]` : "";
12573
- const expectedBlock = `${header}\ncommand = ${JSON.stringify(mcp.command)}${argsLine}\n`;
12778
+ const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
12779
+ const expectedBlock = `${header}\ncommand = ${JSON.stringify(mcp.command)}${argsLine}${recoveryEnv}\n`;
12574
12780
  if (existing.includes(header)) {
12575
12781
  const headerMatch = new RegExp(`(^|\\n)[ \\t]*\\[mcp_servers\\.${escapeRegExp(serverName)}\\][ \\t]*(?:\\r?\\n|$)`, "m").exec(existing);
12576
12782
  if (!headerMatch) {
@@ -12607,7 +12813,7 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
12607
12813
  }
12608
12814
  }
12609
12815
  function codexMcpRegistrationMatches(serverName, mcp) {
12610
- const path = join(homedir(), ".codex", "config.toml");
12816
+ const path = join(codexHomeDir(), "config.toml");
12611
12817
  let existing = "";
12612
12818
  try {
12613
12819
  existing = readFileSync(path, "utf8");
@@ -12623,7 +12829,8 @@ function codexMcpRegistrationMatches(serverName, mcp) {
12623
12829
  const nextHeaderOffset = existing.slice(contentStart).search(/^[ \\t]*\[/m);
12624
12830
  const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
12625
12831
  const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]` : "";
12626
- const expected = `[mcp_servers.${serverName}]\ncommand = ${JSON.stringify(mcp.command)}${argsLine}`;
12832
+ const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
12833
+ const expected = `[mcp_servers.${serverName}]\ncommand = ${JSON.stringify(mcp.command)}${argsLine}${recoveryEnv}`;
12627
12834
  return existing.slice(blockStart, blockEnd).trim() === expected.trim();
12628
12835
  }
12629
12836
  // installMcpJson merges a value at a nested key into an agent's JSON config without
@@ -12969,6 +13176,15 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
12969
13176
  // CLI (BeforeTool, tool "run_shell_command"). It reads the tool event on stdin and,
12970
13177
  // for a noisy command, rewrites it to run through `caveman shrink`. Anything it won't
12971
13178
  // safely shrink it passes through: exit 0 with NO stdout = "no rewrite, run as-is".
13179
+ //
13180
+ // Codex is deliberately NOT in that list, and re-adding it is the #1037 regression:
13181
+ // Codex matches a saved approval against the command text itself (`prefix_rule`), so
13182
+ // any rewrite makes an already-approved command look new and re-prompts the user —
13183
+ // and the rewrite leads with the resolved caveman/node path, which differs per
13184
+ // machine, so no rule the user writes can cover it either. The old Codex branch also
13185
+ // answered the host's approval question with permissionDecision:"allow" against an
13186
+ // unverified contract; if Codex ever honors that, caveman silently auto-approves a
13187
+ // command the user's `approval_policy` meant to gate. Both ends fail closed instead.
12972
13188
  async function shrinkHook() {
12973
13189
  if (nativePolicyMode() === "record" || !new Set(["full-safe", "full-max"]).has(nativeProfile()))
12974
13190
  process.exit(0);
@@ -12989,8 +13205,9 @@ async function shrinkHook() {
12989
13205
  const tool = evt?.tool_name;
12990
13206
  const isGemini = tool === "run_shell_command"; // Gemini CLI's shell tool
12991
13207
  const isBash = tool === "Bash"; // Claude Code + the opencode plugin
12992
- const isCodex = tool === "shell" || tool === "shell_command" || tool === "exec_command";
12993
- if (!isGemini && !isBash && !isCodex)
13208
+ // Every other tool name — Codex's shell/shell_command/exec_command included — runs
13209
+ // as the host received it. See the #1037 note above before widening this.
13210
+ if (!isGemini && !isBash)
12994
13211
  process.exit(0);
12995
13212
  const command = evt.tool_input?.command;
12996
13213
  if (typeof command !== "string" || !shouldShrink(command))
@@ -12998,9 +13215,8 @@ async function shrinkHook() {
12998
13215
  // updatedInput.command executes in host shell (Git Bash on Claude Windows),
12999
13216
  // not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
13000
13217
  const rewritten = `${cavemanBinForHook(false)} shrink -- ${command.trim()}`;
13001
- // Each harness has a different (silent-on-mismatch) override contract: Gemini merges
13002
- // hookSpecificOutput.tool_input (snake_case, no event discriminator); Claude replaces
13003
- // via hookSpecificOutput.updatedInput (camelCase + hookEventName). Emit the right one.
13218
+ // Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
13219
+ // Claude replaces via hookSpecificOutput.updatedInput (camelCase + hookEventName).
13004
13220
  const out = isGemini
13005
13221
  ? { hookSpecificOutput: { tool_input: { command: rewritten } } }
13006
13222
  : { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { command: rewritten } } };
@@ -13619,10 +13835,10 @@ async function nativeHook(argv) {
13619
13835
  if (cwd)
13620
13836
  entry.cwd_sha256 = `sha256:${createHash("sha256").update(cwd).digest("hex")}`;
13621
13837
  // SessionStart revives a missing local proxy, but native routing points every
13622
- // LATER turn of the session at that proxy too, and a wrap-owned instance
13623
- // idle-exits ~30m after its wrap dies. A plain (unwrapped) session then
13624
- // hard-fails with ConnectionRefused on its next prompt, with nothing left to
13625
- // restart the proxy. The port check below makes the revive idempotent, so run
13838
+ // LATER turn of the session at that proxy too. Current proxies never expire,
13839
+ // but crashes and older binaries can still leave a dead base URL. A plain
13840
+ // session needs prompt-time recovery as well. The port check makes revival
13841
+ // idempotent, so run
13626
13842
  // it for the mid-session events that reach the full CLI as well.
13627
13843
  if (normalizedEvent === "SessionStart" || normalizedEvent === "UserPromptSubmit" || normalizedEvent === "PostCompact") {
13628
13844
  try {
@@ -13704,13 +13920,13 @@ async function nativeHook(argv) {
13704
13920
  }
13705
13921
  }
13706
13922
  function claudeSettingsPath() {
13707
- return join(homedir(), ".claude", "settings.json");
13923
+ return join(claudeConfigDir(), "settings.json");
13708
13924
  }
13709
13925
  function geminiSettingsPath() {
13710
- return join(homedir(), ".gemini", "settings.json");
13926
+ return join(geminiConfigDir(), "settings.json");
13711
13927
  }
13712
13928
  function codexHooksPath() {
13713
- return join(homedir(), ".codex", "hooks.json");
13929
+ return join(codexHomeDir(), "hooks.json");
13714
13930
  }
13715
13931
  // installSettingsHook registers a command-output shrink hook in a settings.json that
13716
13932
  // follows the Claude/Gemini shape — root.hooks[<event>] is an array of
@@ -13833,7 +14049,7 @@ function commandHookKind(a) {
13833
14049
  }
13834
14050
  function instructionFileForAgent(a) {
13835
14051
  const hook = a.command_hook;
13836
- return hook && "file" in hook ? hook.file : undefined;
14052
+ return hook && "file" in hook ? agentUserPath(a.id, hook.file) : undefined;
13837
14053
  }
13838
14054
  // (hard methods: claude-pretooluse, codex-pretooluse, opencode-plugin, gemini-beforetool, hermes-plugin, openclaw-plugin.)
13839
14055
  // installShrinkHookForAgent installs the command-output compression hook using the
@@ -14049,6 +14265,17 @@ function hookInstalledPhrase(a) {
14049
14265
  return `shrink preference added to ${ch.file} ${dim("(a model nudge, not a hard rewrite)")}`;
14050
14266
  return "command-output rewrite hook installed";
14051
14267
  }
14268
+ // codexRewriteRetired: codex's profile still declares the `codex-pretooluse` hard
14269
+ // tier, but shrinkHook has declined every Codex tool event since #1037 — rewriting
14270
+ // the command breaks the user's saved approval rules. Installing that hook would
14271
+ // register a callback with no behavior behind it and report a rewrite that does not
14272
+ // happen. Retiring the tier in the profile is the real fix and is NOT done here: the
14273
+ // same `command_hook` entry carries codex's directives instructions-file, and
14274
+ // nativeHooksDocument would have to migrate the entry `caveman enable codex` already
14275
+ // wrote. Both are maintainer decisions; this just stops making the false claim.
14276
+ function codexRewriteRetired(a) {
14277
+ return a.id === "codex";
14278
+ }
14052
14279
  // ── soft tier: instruction-note ──────────────────────────────────────────────
14053
14280
  // For agents with no deterministic command-rewrite surface, we append a
14054
14281
  // clearly-delimited note to a file the agent auto-reads as model instructions,
@@ -14821,6 +15048,10 @@ function hooksCmd(rest) {
14821
15048
  let n = 0;
14822
15049
  let hard = 0;
14823
15050
  for (const a of targets) {
15051
+ if (codexRewriteRetired(a)) {
15052
+ process.stderr.write(`${mark("warn")} ${a.display_name}: no command-output rewrite — it breaks saved Codex approval rules (#1037); run noisy commands through ${cyan("caveman shrink -- <cmd>")}\n`);
15053
+ continue;
15054
+ }
14824
15055
  if (installShrinkHookForAgent(a)) {
14825
15056
  writeShrinkHookMarker(a.id);
14826
15057
  n++;
@@ -14908,12 +15139,45 @@ function evalsRun(argv = []) {
14908
15139
  // owns the ~/.caveman/ SQLite store. The CLI carries no database dependency, so
14909
15140
  // it reads through the same Go binary `caveman start` launches.
14910
15141
  function stats(argv = []) {
14911
- if (argv.length > 1 || (argv.length === 1 && argv[0] !== "--json"))
14912
- commandUsage("stats [--json]");
15142
+ if (argv.length === 1 && ["--help", "-h", "help"].includes(argv[0])) {
15143
+ process.stdout.write(STATS_HELP);
15144
+ return;
15145
+ }
15146
+ let options;
15147
+ try {
15148
+ options = parseStatsOptions(argv);
15149
+ }
15150
+ catch (error) {
15151
+ console.error(error.message);
15152
+ commandUsage(STATS_USAGE);
15153
+ }
14913
15154
  const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
14914
15155
  try {
14915
- const out = execFileSync(bin, ["stats", ...argv], { encoding: "utf8" });
14916
- process.stdout.write(out);
15156
+ const args = ["stats", "--report", ...options.filters];
15157
+ if (!options.json || options.out)
15158
+ args.push("--write-report");
15159
+ if (options.out)
15160
+ args.push("--out", resolve(options.out));
15161
+ const out = execFileSync(bin, args, { encoding: "utf8", timeout: 60_000, maxBuffer: 32 * 1024 * 1024 });
15162
+ const report = JSON.parse(out);
15163
+ // Older companion binaries ignore --report. Keep their measurements
15164
+ // readable, but never pretend they generated the new accounting report.
15165
+ if (report.schema !== "caveman.stats.v1") {
15166
+ if (options.filters.length || options.out || options.open) {
15167
+ throw new Error("installed proxy does not support filtered stats or HTML reports; run caveman setup --install");
15168
+ }
15169
+ process.stdout.write(out);
15170
+ if (!options.json)
15171
+ process.stderr.write("Detailed stats require an updated proxy: caveman setup --install\n");
15172
+ return;
15173
+ }
15174
+ if (options.json)
15175
+ process.stdout.write(out);
15176
+ else {
15177
+ process.stdout.write(renderStatsSummary(report));
15178
+ if (report.report_path && (options.open || (!options.plain && learnTuiTerminal())))
15179
+ openLearnReport(report.report_path);
15180
+ }
14917
15181
  }
14918
15182
  catch (error) {
14919
15183
  console.error(`failed to read stats via ${bin}: ${error.message}`);
@@ -15740,7 +16004,7 @@ function learnImplementPrompt(focus) {
15740
16004
  function ensureLearnAgentGuide(agent) {
15741
16005
  const path = agent.id === "claude"
15742
16006
  ? join(process.cwd(), ".claude", "skills", "caveman-learn", "SKILL.md")
15743
- : join(homedir(), ".codex", "skills", "caveman-learn", "SKILL.md");
16007
+ : join(codexHomeDir(), "skills", "caveman-learn", "SKILL.md");
15744
16008
  try {
15745
16009
  readFileSync(path);
15746
16010
  return "";
@@ -16421,6 +16685,9 @@ function readRawProxyRunState(port) {
16421
16685
  ...(typeof parsed.started_at === "string" ? { started_at: parsed.started_at } : {}),
16422
16686
  ...(typeof parsed.version === "string" ? { version: parsed.version } : {}),
16423
16687
  ...(typeof parsed.recovery_via_mcp === "boolean" ? { recovery_via_mcp: parsed.recovery_via_mcp } : {}),
16688
+ provider_upstreams: publishedUpstreamsOf(parsed.provider_upstreams),
16689
+ compat_upstreams: publishedUpstreamsOf(parsed.compat_upstreams),
16690
+ compat_forward_headers: publishedForwardHeadersOf(parsed.compat_forward_headers),
16424
16691
  };
16425
16692
  }
16426
16693
  catch {
@@ -16437,6 +16704,7 @@ function processAlive(pid) {
16437
16704
  }
16438
16705
  }
16439
16706
  function createProxySessionMarker(port) {
16707
+ pruneDeadProxySessionMarkers(port);
16440
16708
  const dir = proxySessionDir(port);
16441
16709
  try {
16442
16710
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -16458,51 +16726,40 @@ function createProxySessionMarker(port) {
16458
16726
  }
16459
16727
  return null;
16460
16728
  }
16461
- function removeProxySessionMarker(marker) {
16462
- if (!marker)
16463
- return;
16464
- try {
16465
- unlinkSync(marker);
16466
- }
16467
- catch (error) {
16468
- if (error.code !== "ENOENT") {
16469
- // Marker cleanup is best-effort; the next reader prunes a dead owner.
16470
- }
16471
- }
16472
- }
16473
- function countOtherLiveProxySessions(port, ownMarker) {
16729
+ // pruneDeadProxySessionMarkers removes markers whose owner died. Their absence
16730
+ // never authorizes a restart, so nothing reads the surviving count.
16731
+ function pruneDeadProxySessionMarkers(port) {
16474
16732
  let names;
16475
16733
  try {
16476
16734
  names = readdirSync(proxySessionDir(port));
16477
16735
  }
16478
16736
  catch {
16479
- return 0;
16737
+ return;
16480
16738
  }
16481
- let live = 0;
16482
16739
  for (const name of names) {
16483
- const marker = join(proxySessionDir(port), name);
16484
- if (ownMarker && marker === ownMarker)
16485
- continue;
16486
16740
  const match = /^(\d+)-/.exec(name);
16487
16741
  const pid = match ? Number(match[1]) : NaN;
16488
- if (!Number.isSafeInteger(pid) || pid <= 0 || !processAlive(pid)) {
16489
- try {
16490
- unlinkSync(marker);
16491
- }
16492
- catch {
16493
- // Concurrent cleanup or a read-only directory: neither upgrades ownership.
16494
- }
16742
+ if (Number.isSafeInteger(pid) && pid > 0 && processAlive(pid))
16495
16743
  continue;
16744
+ try {
16745
+ unlinkSync(join(proxySessionDir(port), name));
16746
+ }
16747
+ catch {
16748
+ // Concurrent cleanup or a read-only directory: neither upgrades ownership.
16496
16749
  }
16497
- live++;
16498
16750
  }
16499
- return live;
16500
16751
  }
16501
- function proxyRestartTimeoutMs() {
16502
- const seconds = Number(process.env.CAVE_PROXY_RESTART_TIMEOUT ?? "10");
16503
- if (!Number.isFinite(seconds))
16504
- return 10_000;
16505
- return Math.max(100, Math.min(60_000, Math.round(seconds * 1000)));
16752
+ function removeProxySessionMarker(marker) {
16753
+ if (!marker)
16754
+ return;
16755
+ try {
16756
+ unlinkSync(marker);
16757
+ }
16758
+ catch (error) {
16759
+ if (error.code !== "ENOENT") {
16760
+ // Marker cleanup is best-effort; the next reader prunes a dead owner.
16761
+ }
16762
+ }
16506
16763
  }
16507
16764
  function probeProxyVersion() {
16508
16765
  const binary = resolveGoBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
@@ -16552,6 +16809,9 @@ function readProxyRuntimeState(port, versionInfo) {
16552
16809
  ...(typeof parsed.started_at === "string" ? { started_at: parsed.started_at } : {}),
16553
16810
  ...(typeof parsed.version === "string" ? { version: parsed.version } : {}),
16554
16811
  ...(typeof parsed.recovery_via_mcp === "boolean" ? { recovery_via_mcp: parsed.recovery_via_mcp } : {}),
16812
+ provider_upstreams: publishedUpstreamsOf(parsed.provider_upstreams),
16813
+ compat_upstreams: publishedUpstreamsOf(parsed.compat_upstreams),
16814
+ compat_forward_headers: publishedForwardHeadersOf(parsed.compat_forward_headers),
16555
16815
  };
16556
16816
  }
16557
16817
  catch {