@caveman-ai/cli 4.0.0 → 4.1.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
@@ -49,10 +49,13 @@ const wrapTempDirs = new Set();
49
49
  const PROXY_ADDR = "127.0.0.1:8787";
50
50
  const PROXY_URL = `http://${PROXY_ADDR}`;
51
51
  // Restores Claude Code's tool search after we take over ANTHROPIC_BASE_URL.
52
- // "auto" defers to Claude Code's own tool-catalog size threshold, so a user with
53
- // two small MCP servers pays no extra round-trip while a heavy setup stops
54
- // inlining every schema. "true" would force it on regardless.
55
- const TOOL_SEARCH_DEFAULT = "auto";
52
+ // "true" matches Claude Code's own default when the variable is unset. "auto"
53
+ // would gate it on a tool-catalog size threshold, which hosts that connect MCP
54
+ // servers after the first request (Agent SDK apps) cross mid-session: early
55
+ // turns inline every schema and the flip to deferred busts the prompt cache.
56
+ const TOOL_SEARCH_DEFAULT = "true";
57
+ // Earlier releases wrote "auto"; disable still withdraws it as ours.
58
+ const LEGACY_TOOL_SEARCH_DEFAULTS = ["auto"];
56
59
  // The agent traffic target (wrap, `enable <agent>`, module wiring), resolved per
57
60
  // invocation. Signing in never moves agent traffic through a Caveman hop: the
58
61
  // managed gateway is the target only when chosen explicitly. Precedence:
@@ -674,6 +677,10 @@ setModuleHost({
674
677
  }));
675
678
  },
676
679
  agentAsk: (agent) => agent === "codex" && readNativeJournal("codex") && !codexHooksTrusted() ? CODEX_TRUST_ASK : undefined,
680
+ recoveryStoreProblem: () => {
681
+ const store = readRecoveryStore(true);
682
+ return store?.writes_refused && store.reason ? `${store.reason} — new input passes through uncompressed${store.fix ? ` · fix: ${store.fix}` : ""}` : undefined;
683
+ },
677
684
  runtimeDown: async () => {
678
685
  const wired = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"].filter((agent) => readNativeJournal(agent));
679
686
  return wired.length && await agentRuntimeState() === "down" ? agentRuntimeLine("down", wired) : undefined;
@@ -4552,11 +4559,22 @@ function nestedCapabilityValue(doc, key) {
4552
4559
  return block[first];
4553
4560
  return objectValue(block[first])[second];
4554
4561
  }
4562
+ // proxyYamlMode reads the proxy's own TOP-LEVEL `mode:` out of caveman.yaml.
4563
+ // The pattern is anchored at column 0 on purpose (#1457). `^\s*mode\s*:` with
4564
+ // /m matched the key at ANY indentation, and caveman.yaml legitimately carries
4565
+ // a second, nested one — `middleware.mode`, the documented "proxy records while
4566
+ // the middleware compresses" shape — so the nested value was read as the
4567
+ // proxy's. The proxy itself resolves keys by name (yaml.v3), which made the two
4568
+ // disagree about one file in both directions: a nested-only mode was adopted as
4569
+ // the proxy's, and a nested key written ABOVE a real top-level one won on
4570
+ // textual order, which also surfaced as a `caveman status` mode mismatch that
4571
+ // was not real. yamlScopedBaseUrl() below tracks indentation deliberately and
4572
+ // is unaffected; this key is top-level or it is not ours to read.
4555
4573
  function proxyYamlMode() {
4556
4574
  const path = process.env.CAVEMAN_CONFIG ?? join(cavemanHome(), "caveman.yaml");
4557
4575
  try {
4558
4576
  const raw = readFileSync(path, "utf8");
4559
- const match = raw.match(/^\s*mode\s*:\s*["']?([^#\s"']+)/m);
4577
+ const match = raw.match(/^mode[ \t]*:[ \t]*["']?([^#\s"']+)/m);
4560
4578
  return match?.[1];
4561
4579
  }
4562
4580
  catch {
@@ -4573,44 +4591,46 @@ function proxyYamlMode() {
4573
4591
  // through Claude Code's own escape hatch. Never overrides a value the user
4574
4592
  // already set, and never asserts when the upstream cannot be verified.
4575
4593
  const CLAUDE_ASSUME_FIRST_PARTY_ENV = "_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL";
4576
- // yamlProviderBaseUrl scans an indentation-nested `providers.<name>.base_url`
4577
- // key without a YAML dependency (the published CLI has zero runtime deps).
4578
- // Returns the value when found, null when the providers/<name> block or key is
4579
- // absent, and undefined when the document uses a shape the scan cannot follow
4580
- // (flow-style `{...}` blocks) — callers must treat undefined as unverifiable.
4581
- function yamlProviderBaseUrl(raw, provider) {
4594
+ // yamlScopedBaseUrl scans an indentation-nested `<group>.<name>.base_url` key
4595
+ // without a YAML dependency (the published CLI has zero runtime deps). Returns
4596
+ // the value when found, null when the group/<name> block or key is absent, and
4597
+ // undefined when the document uses a shape the scan cannot follow (flow-style
4598
+ // `{...}` blocks) — callers must treat undefined as unverifiable. `providers`
4599
+ // answers which upstream the proxy forwards to; `compat` answers whether a
4600
+ // user-defined mount exists at all (#1254).
4601
+ function yamlScopedBaseUrl(raw, group, name) {
4582
4602
  const lines = raw.split(/\r?\n/);
4583
- let providersIndent = -1;
4584
- let providerIndent = -1;
4603
+ let groupIndent = -1;
4604
+ let nameIndent = -1;
4585
4605
  for (const line of lines) {
4586
4606
  const code = line.split("#", 1)[0];
4587
4607
  if (!code.trim())
4588
4608
  continue;
4589
4609
  const indent = code.length - code.trimStart().length;
4590
4610
  const keyMatch = code.trim().match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
4591
- if (providersIndent !== -1 && indent <= providersIndent)
4592
- providersIndent = -1;
4593
- if (providerIndent !== -1 && indent <= providerIndent)
4594
- providerIndent = -1;
4611
+ if (groupIndent !== -1 && indent <= groupIndent)
4612
+ groupIndent = -1;
4613
+ if (nameIndent !== -1 && indent <= nameIndent)
4614
+ nameIndent = -1;
4595
4615
  if (!keyMatch)
4596
4616
  continue;
4597
4617
  const key = keyMatch[1];
4598
4618
  const rest = keyMatch[2] ?? "";
4599
4619
  if (rest.startsWith("{") || rest.startsWith("[")) {
4600
- // Flow-style collections keep their children on this line; a providers
4620
+ // Flow-style collections keep their children on this line; a group
4601
4621
  // subtree written that way is beyond this scan, so report unverifiable.
4602
- if (key === "providers" || providersIndent !== -1)
4622
+ if (key === group || groupIndent !== -1)
4603
4623
  return undefined;
4604
4624
  continue;
4605
4625
  }
4606
- if (providerIndent !== -1 && key === "base_url") {
4626
+ if (nameIndent !== -1 && key === "base_url") {
4607
4627
  const value = rest.replace(/^["']|["']\s*$/g, "").trim();
4608
4628
  return value || null;
4609
4629
  }
4610
- if (providersIndent !== -1 && key === provider && providerIndent === -1)
4611
- providerIndent = indent;
4612
- else if (key === "providers" && providersIndent === -1 && providerIndent === -1 && indent === 0)
4613
- providersIndent = indent;
4630
+ if (groupIndent !== -1 && key === name && nameIndent === -1)
4631
+ nameIndent = indent;
4632
+ else if (key === group && groupIndent === -1 && nameIndent === -1 && indent === 0)
4633
+ groupIndent = indent;
4614
4634
  }
4615
4635
  return null;
4616
4636
  }
@@ -4633,7 +4653,7 @@ function proxyUpstreamIsFirstParty(provider, host) {
4633
4653
  catch (e) {
4634
4654
  return e?.code === "ENOENT";
4635
4655
  }
4636
- const override = yamlProviderBaseUrl(raw, provider);
4656
+ const override = yamlScopedBaseUrl(raw, "providers", provider);
4637
4657
  if (override === undefined)
4638
4658
  return false;
4639
4659
  if (override === null)
@@ -4950,6 +4970,14 @@ export const OFF_STATES = {
4950
4970
  },
4951
4971
  // The proxy's cache tripwire: the client re-sent bytes the provider had
4952
4972
  // cached and caveman forwarded them differently. Never expected; a bug.
4973
+ // The recovery store (ccr.db) refuses new recoveries: it is damaged, or full
4974
+ // with nothing old enough to expire. Every lossy compression needs one, so
4975
+ // inputs pass through uncompressed until the fix (#1369, #1370).
4976
+ recoveryStore: (reason, fix) => ({
4977
+ id: "recovery-store",
4978
+ line: `${reason} — new input passes through uncompressed`,
4979
+ ...(fix ? { fix } : {}),
4980
+ }),
4953
4981
  cavemanCacheBust: (count) => ({
4954
4982
  id: "cache-bust",
4955
4983
  line: `caveman changed bytes the provider had already cached on ${count} request${count === 1 ? "" : "s"} today — those turns paid to re-cache their prompt; this is a caveman bug`,
@@ -4962,6 +4990,7 @@ const OFF_STATE_PRECEDENCE = [
4962
4990
  "running-mode-mismatch",
4963
4991
  "invalid-mode",
4964
4992
  "user-record",
4993
+ "recovery-store",
4965
4994
  "mcp-missing",
4966
4995
  "mem-missing",
4967
4996
  "zdr",
@@ -5407,6 +5436,16 @@ function refreshWrapEntitlementInBackground(options = {}) {
5407
5436
  /* never surface a background rejection */
5408
5437
  });
5409
5438
  }
5439
+ // The refresh outcome and the weekly run claim belong to the credential they ran
5440
+ // under. Login and logout replace that credential, so they drop both: native
5441
+ // wiring never runs the background refresh, and a stale failure would keep
5442
+ // status on "account refresh offline" for good.
5443
+ function dropWrapRefreshState() {
5444
+ mutateRawConfig((out) => {
5445
+ delete out.wrapEntitlementRefresh;
5446
+ delete out.wrapEntitlementRunRefreshWeek;
5447
+ });
5448
+ }
5410
5449
  // ── wrap-start + session-end lines (the §8 golden transcripts) ───────────────────
5411
5450
  // SUBSCRIPTION_TOKENS_ONLY_NOTE is the single honesty line for locally compressed
5412
5451
  // subscription/OAuth sessions. A Claude Pro/Max seat has no per-token price, and an
@@ -5547,6 +5586,36 @@ function readProxyObserveSummary(sinceISO) {
5547
5586
  return null;
5548
5587
  }
5549
5588
  }
5589
+ function readRecoveryStore(check) {
5590
+ if (!probeProxyVersion()?.capabilities.includes("recovery_store_v1"))
5591
+ return undefined;
5592
+ const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
5593
+ let out;
5594
+ try {
5595
+ out = execFileSync(bin, ["recovery-store", check ? "check" : "status"], {
5596
+ encoding: "utf8",
5597
+ env: process.env,
5598
+ timeout: check ? 120_000 : 10_000,
5599
+ stdio: ["ignore", "pipe", "ignore"],
5600
+ });
5601
+ }
5602
+ catch (error) {
5603
+ out = String(error.stdout ?? "");
5604
+ }
5605
+ try {
5606
+ const parsed = JSON.parse(out);
5607
+ if (parsed?.schema !== "caveman.recovery_store.v1")
5608
+ return undefined;
5609
+ // The fix names the subcommand; spell out the binary, which is not on PATH.
5610
+ const shown = /[^\w@%+=:,./\\-]/.test(bin) ? quoteHookPath(bin) : bin;
5611
+ if (parsed.fix)
5612
+ parsed.fix = parsed.fix.replace("caveman-proxy recovery-store", `${shown} recovery-store`);
5613
+ return parsed;
5614
+ }
5615
+ catch {
5616
+ return undefined;
5617
+ }
5618
+ }
5550
5619
  // PROXY_RECENT_ROW_CAP mirrors the store's hard cap on `stats --recent N`: asking
5551
5620
  // for more rows than this silently returns this many, so a full page back is
5552
5621
  // indistinguishable from a truncated window.
@@ -6732,6 +6801,8 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
6732
6801
  Object.assign(env, claudeCaveBuildEnv());
6733
6802
  if (!direct)
6734
6803
  maybeWarnHermesMissingKey(agent, gw);
6804
+ if (!direct)
6805
+ maybeWarnGeminiHeadlessAuth(agent, childArgs);
6735
6806
  if (direct) {
6736
6807
  // buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
6737
6808
  // outer routed wrap may leak the bare form; a direct launch strips both.
@@ -6868,6 +6939,43 @@ function firstEnvSecret(env, keys) {
6868
6939
  }
6869
6940
  return undefined;
6870
6941
  }
6942
+ // Wrap writes no user config, so where Gemini would reject the `gateway` auth
6943
+ // type our route makes it pick (see geminiEnvSelectsAuth), a headless launch
6944
+ // names the fix instead. Headless mirrors Gemini's isHeadlessMode.
6945
+ // ponytail: a positional query and system-level settings files are not read;
6946
+ // a miss only means Gemini's own error shows without this line.
6947
+ function maybeWarnGeminiHeadlessAuth(agent, args) {
6948
+ if (agent?.id !== "gemini")
6949
+ return;
6950
+ const flag = (names) => args.some((arg) => names.some((name) => arg === name || arg.startsWith(`${name}=`)));
6951
+ // Interactive and ACP sessions pick auth their own way; subcommands and
6952
+ // version/help never authenticate.
6953
+ if (flag(["-i", "--prompt-interactive", "--acp", "--experimental-acp", "-v", "--version", "-h", "--help"]))
6954
+ return;
6955
+ if (["mcp", "extensions", "skills", "hooks"].includes(args[0] ?? ""))
6956
+ return;
6957
+ const headless = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true"
6958
+ || !process.stdin.isTTY || !process.stdout.isTTY || flag(["-p", "--prompt"]);
6959
+ if (!headless)
6960
+ return;
6961
+ for (const file of [geminiSettingsPath(), join(process.cwd(), ".gemini", "settings.json")]) {
6962
+ try {
6963
+ if (getObject(readJson5Lenient(file), ["security", "auth"])?.selectedType)
6964
+ return;
6965
+ }
6966
+ catch {
6967
+ // Missing or unreadable: no auth type chosen there.
6968
+ }
6969
+ }
6970
+ let dotenv = "";
6971
+ try {
6972
+ dotenv = readFileSync(join(geminiConfigDir(), ".env"), "utf8");
6973
+ }
6974
+ catch { /* no global .env */ }
6975
+ if (geminiEnvSelectsAuth(dotenv))
6976
+ return;
6977
+ process.stderr.write(`caveman: headless Gemini CLI needs an auth type of your own or it exits "Invalid auth method selected."; add "security": {"auth": {"selectedType": "${GEMINI_PINNED_AUTH}"}} to ${geminiSettingsPath()}\n`);
6978
+ }
6871
6979
  function maybeWarnHermesMissingKey(agent, gw = gatewayURL()) {
6872
6980
  if (agent?.id !== "hermes")
6873
6981
  return;
@@ -7682,6 +7790,34 @@ export function hookExecutableInvocation(executable, script, platform = process.
7682
7790
  // required invocation operator. POSIX hook commands keep their exact shape.
7683
7791
  return platform === "win32" && powershell ? `& ${invocation}` : invocation;
7684
7792
  }
7793
+ // hostShellInvocation renders the same invocation for a command string we hand
7794
+ // BACK to the host for the host's own shell to run — a `shrink` rewrite, not a
7795
+ // hook the host dispatches itself. That shell differs per host on Windows: Git
7796
+ // Bash under Claude Code, PowerShell under the opencode plugin, cmd.exe under
7797
+ // Gemini CLI, and the three share no quoting syntax. A quoted path is only a
7798
+ // string literal in PowerShell, so the quoted prefix died with
7799
+ // `ParserError: Unexpected token 'shrink'` before the command ran (#1263);
7800
+ // single quotes are literal characters in cmd.exe; and the `&` call operator
7801
+ // PowerShell needs is a syntax error in bash. An unquoted, forward-slashed path
7802
+ // is the one form all three execute, so emit that when every component allows
7803
+ // it and return null when one does not — a path with a space has no portable
7804
+ // form at all, and the caller then declines the rewrite, which leaves the
7805
+ // command running exactly as the host sent it. POSIX hosts all run an sh-family
7806
+ // shell, where the quoted form is both correct and space-safe: unchanged there.
7807
+ const BARE_HOST_SHELL_PATH = /^[A-Za-z0-9_:./-]+$/;
7808
+ export function hostShellInvocation(executable, script, platform = process.platform) {
7809
+ const parts = script ? [executable, script] : [executable];
7810
+ if (platform !== "win32")
7811
+ return parts.map((part) => quoteHookPath(part, platform)).join(" ");
7812
+ const bare = [];
7813
+ for (const part of parts) {
7814
+ const normalized = normalizeHookPath(part, platform);
7815
+ if (!BARE_HOST_SHELL_PATH.test(normalized))
7816
+ return null;
7817
+ bare.push(normalized);
7818
+ }
7819
+ return bare.join(" ");
7820
+ }
7685
7821
  function nativeHookCommand(agentId) {
7686
7822
  const fastHook = join(dirname(fileURLToPath(import.meta.url)), "native-hook-fast.js");
7687
7823
  const explicitProxy = process.env.CAVEMAN_PROXY_BIN;
@@ -7808,7 +7944,7 @@ function canonicalManagedHookEntry(entry) {
7808
7944
  const clone = JSON.parse(JSON.stringify(entry));
7809
7945
  const hooks = clone.hooks;
7810
7946
  hooks[0].command = identity;
7811
- return JSON.stringify(clone);
7947
+ return canonicalize(clone);
7812
7948
  }
7813
7949
  // Why: `think.shrink` (and its `CAVEMAN_SHRINK` env form) is the persisted
7814
7950
  // switch for the command-output rewrite, but only the ephemeral launcher ever
@@ -7984,6 +8120,37 @@ function generatedArtifactTargetsExist(text) {
7984
8120
  const tokens = generatedInvocation(text);
7985
8121
  return tokens === undefined || invocationTargetsExist(tokens);
7986
8122
  }
8123
+ // Same question as managedHookTargetsExist below, asked of an MCP registration
8124
+ // instead of a hook: the recovery tool is only real while the command the host
8125
+ // will launch still exists and can be executed. probeMcpBinary() answers a
8126
+ // DIFFERENT question — whether some compatible caveman-mcp is resolvable on
8127
+ // this machine right now — so an install whose registered binary was removed,
8128
+ // or left non-executable, kept attesting recovery while an actual launch raised
8129
+ // FileNotFoundError or PermissionError (#1392). That is the MCP twin of the
8130
+ // disappearing hook/plugin targets in #1137.
8131
+ //
8132
+ // Existence and permission only: a registration may have been edited by the
8133
+ // user, and probing it must never run it, nor adopt it as owned. Registrations
8134
+ // journaled as config text (codex tables, the hermes mcp_servers block) carry
8135
+ // no structured command and are not inspected here.
8136
+ function journaledMcpTargetsExist(journal) {
8137
+ // Same filter the ownership checks apply: a deleted Claude profile's entry
8138
+ // has nothing left to launch, and a stale path in one must not report the
8139
+ // remaining profiles degraded.
8140
+ for (const operation of (journal?.operations ?? []).filter((item) => !claudeProfileGone(item))) {
8141
+ const installed = operation.owned?.installed_mcp;
8142
+ if (!installed || typeof installed !== "object" || Array.isArray(installed))
8143
+ continue;
8144
+ const { command, args } = installed;
8145
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
8146
+ // claude: { command: "<bin>", args: [] } · gemini: { command, args }
8147
+ // opencode: { type: "local", command: ["<bin>"] }
8148
+ const tokens = Array.isArray(command) ? strings(command) : typeof command === "string" ? [command, ...strings(args)] : [];
8149
+ if (tokens.length > 0 && !invocationTargetsExist(tokens))
8150
+ return false;
8151
+ }
8152
+ return true;
8153
+ }
7987
8154
  // A managed hook is only healthy while the files its command runs still exist.
7988
8155
  // Identity is judged by basename, so a hook rendered into a directory that has
7989
8156
  // since been deleted (an nvm Node upgrade, #1137) kept matching the expected
@@ -8185,6 +8352,7 @@ const HERMES_NATIVE_PLUGIN_END = "# <<< caveman:native-hermes-plugin";
8185
8352
  const HERMES_NATIVE_MCP_BEGIN = "# >>> caveman:native-hermes-mcp";
8186
8353
  const HERMES_NATIVE_MCP_END = "# <<< caveman:native-hermes-mcp";
8187
8354
  const HERMES_NATIVE_PLUGIN_NAME = "caveman_native";
8355
+ const HERMES_NATIVE_MCP_SERVER = "caveman-native";
8188
8356
  const GEMINI_NATIVE_ENV_BEGIN = "# >>> caveman:native-routing";
8189
8357
  const GEMINI_NATIVE_ENV_END = "# <<< caveman:native-routing";
8190
8358
  const AIDER_NATIVE_ROUTE_BEGIN = "# >>> caveman:native-aider-routing";
@@ -8400,9 +8568,17 @@ function nativeProxyBinaryRequired(gw) {
8400
8568
  // several times, and a hung host would cost the full timeout every time.
8401
8569
  const nativeHostProbes = new Map();
8402
8570
  function nativeHostProbe(agent) {
8403
- const binary = which(binOf(agent));
8571
+ return nativeBinaryProbe(binOf(agent))
8572
+ ?? { binary: null, launchable: false, version: null, error: "binary_not_found" };
8573
+ }
8574
+ // One named binary, or null when it is not installed — so a caller that cares
8575
+ // about EVERY published name (opencodePluginMajors) can ask per name instead of
8576
+ // only about binOf's first hit. Shares the probe cache, keyed on the resolved
8577
+ // path, so two names resolving to the same file cost one spawn.
8578
+ function nativeBinaryProbe(name) {
8579
+ const binary = which(name);
8404
8580
  if (!binary)
8405
- return { binary: null, launchable: false, version: null, error: "binary_not_found" };
8581
+ return null;
8406
8582
  let probe = nativeHostProbes.get(binary);
8407
8583
  if (!probe)
8408
8584
  nativeHostProbes.set(binary, probe = probeNativeHost(binary));
@@ -8786,6 +8962,31 @@ function geminiRouteShadow() {
8786
8962
  return null;
8787
8963
  }
8788
8964
  }
8965
+ // Gemini CLI resolves an unset (or empty) auth type from env: GOOGLE_GENAI_USE_GCA,
8966
+ // then GOOGLE_GENAI_USE_VERTEXAI, then GOOGLE_GEMINI_BASE_URL -> `gateway`, a type
8967
+ // its own headless validator rejects ("Invalid auth method selected.", exit 41;
8968
+ // google-gemini/gemini-cli#27550, closed not planned). Our route always sets the
8969
+ // base URL, so the API-key type is pinned unless one of these switches is on:
8970
+ // GCA and Vertex resolve before the base URL, and Cloud Shell / compute ADC users
8971
+ // get their type written by Gemini itself. The shell wins over the .env file and
8972
+ // the last line wins within it, as in Gemini.
8973
+ const GEMINI_PINNED_AUTH = "gemini-api-key";
8974
+ const GEMINI_PINNED_AUTH_NOTE = `auth: security.auth.selectedType = ${GEMINI_PINNED_AUTH} (Gemini CLI rejects the gateway type it picks for a routed base URL; /auth in Gemini changes it)`;
8975
+ function geminiEnvSelectsAuth(dotenv) {
8976
+ return ["GOOGLE_GENAI_USE_GCA", "GOOGLE_GENAI_USE_VERTEXAI", "CLOUD_SHELL", "GEMINI_CLI_USE_COMPUTE_ADC"].some((key) => {
8977
+ const line = dotenv.split(/\r?\n/).findLast((item) => new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`).test(item));
8978
+ return (process.env[key] ?? configValue(line?.slice(line.indexOf("=") + 1))) === "true";
8979
+ });
8980
+ }
8981
+ // An install from before the pin existed journals no `selected_auth` at all
8982
+ // (an install that chose not to pin records null): enable and doctor --fix
8983
+ // re-wire it so the pin is decided once.
8984
+ function geminiAuthUndecided(agent) {
8985
+ if (agent !== "gemini")
8986
+ return false;
8987
+ const operation = readNativeJournal("gemini")?.operations.find((item) => item.kind === "gemini-settings");
8988
+ return Boolean(operation && !("selected_auth" in (operation.owned ?? {})));
8989
+ }
8789
8990
  function geminiNativeMutations(gw, mcpBinary) {
8790
8991
  if (wrapMode(gw) === "managed") {
8791
8992
  throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
@@ -8794,6 +8995,20 @@ function geminiNativeMutations(gw, mcpBinary) {
8794
8995
  const settingsBefore = fileBytes(settingsPath);
8795
8996
  const settings = parseJsonFileObject(settingsPath, settingsBefore);
8796
8997
  assertNativeHooksShape(settingsPath, settings, "gemini");
8998
+ const envPath = join(geminiConfigDir(), ".env");
8999
+ const envBefore = fileBytes(envPath);
9000
+ // Pin the API-key type only where the user chose none (see geminiEnvSelectsAuth);
9001
+ // a non-object security/auth value is left as is.
9002
+ const security = settings.security === undefined ? {} : asJsonObject(settings.security);
9003
+ const auth = security && (security.auth === undefined ? {} : asJsonObject(security.auth));
9004
+ const selectedAuth = auth && !auth.selectedType && !geminiEnvSelectsAuth(envBefore?.toString("utf8") ?? "")
9005
+ ? GEMINI_PINNED_AUTH
9006
+ : null;
9007
+ if (selectedAuth) {
9008
+ auth.selectedType = selectedAuth;
9009
+ security.auth = auth;
9010
+ settings.security = security;
9011
+ }
8797
9012
  if (settings.mcpServers !== undefined && (typeof settings.mcpServers !== "object" || settings.mcpServers === null || Array.isArray(settings.mcpServers))) {
8798
9013
  throw new Error(`${settingsPath} mcpServers must be a JSON object; refusing to overwrite it`);
8799
9014
  }
@@ -8805,8 +9020,6 @@ function geminiNativeMutations(gw, mcpBinary) {
8805
9020
  servers.caveman = installedMcp;
8806
9021
  settings.mcpServers = servers;
8807
9022
  const withHooks = nativeHooksDocument("gemini", nativeShrinkEnabled(), settings);
8808
- const envPath = join(geminiConfigDir(), ".env");
8809
- const envBefore = fileBytes(envPath);
8810
9023
  const route = appendUrlPath(gw, "/w/gemini");
8811
9024
  const nativeEnv = geminiNativeEnv(envBefore?.toString("utf8") ?? "", route);
8812
9025
  // The block goes last in the file, so it would win over the user's own.
@@ -8819,7 +9032,7 @@ function geminiNativeMutations(gw, mcpBinary) {
8819
9032
  before: settingsBefore,
8820
9033
  after: jsonBytes(withHooks, settingsBefore),
8821
9034
  kind: "gemini-settings",
8822
- owned: { installed_mcp: installedMcp, previous_mcp: previousMcp ?? null },
9035
+ owned: { installed_mcp: installedMcp, previous_mcp: previousMcp ?? null, selected_auth: selectedAuth },
8823
9036
  },
8824
9037
  {
8825
9038
  file: envPath,
@@ -8830,9 +9043,15 @@ function geminiNativeMutations(gw, mcpBinary) {
8830
9043
  },
8831
9044
  ];
8832
9045
  }
8833
- // OpenCode reads $XDG_CONFIG_HOME/opencode, else ~/.config/opencode on every
8834
- // platform, and opencode.jsonc over opencode.json when both are there.
9046
+ // OpenCode reads OPENCODE_CONFIG_DIR when that is set to a nonempty value,
9047
+ // else $XDG_CONFIG_HOME/opencode, else ~/.config/opencode on every platform,
9048
+ // and opencode.jsonc over opencode.json when both are there. Skipping the
9049
+ // variable installed into a root the host never reads, while still reporting
9050
+ // success (#1441); the installer and the mode plugin resolve it the same way.
8835
9051
  function opencodeConfigDir() {
9052
+ const selected = (process.env.OPENCODE_CONFIG_DIR ?? "").trim();
9053
+ if (selected)
9054
+ return resolve(selected);
8836
9055
  return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
8837
9056
  }
8838
9057
  function opencodeConfigPath() {
@@ -8842,12 +9061,30 @@ function opencodeConfigPath() {
8842
9061
  function opencodeNativePluginPath() {
8843
9062
  return join(opencodeConfigDir(), "plugins", "caveman-native.js");
8844
9063
  }
8845
- function opencodePluginMajor() {
9064
+ // The plugin APIs this machine has to satisfy, ascending and deduplicated.
9065
+ //
9066
+ // Asking which major "the" host is was the wrong question: the generated plugin
9067
+ // lives at ONE path every opencode on the machine reads, and @opencode/cli
9068
+ // publishes `opencode` and `opencode2` from the same package, so two majors run
9069
+ // side by side routinely. A 1.x kept on PATH for other projects won binOf's
9070
+ // first-found probe, the gate read major 1, and OpenCode 2 refused the V1 hook
9071
+ // map outright: PluginModule.LoadError, missing "default" (#1316).
9072
+ //
9073
+ // Empty means no installed binary named a readable version — evidence of
9074
+ // neither major, not of absence.
9075
+ function opencodePluginMajors() {
8846
9076
  const profile = AGENTS.find((agent) => agent.id === "opencode");
8847
- const host = profile ? nativeHostProbe(profile) : null;
8848
- // A failed probe's text is its error output, not a version.
8849
- const semver = host?.launchable ? parsedSemver(host.version) : undefined;
8850
- return semver ? semver[0] : null;
9077
+ if (!profile)
9078
+ return [];
9079
+ const majors = new Set();
9080
+ for (const name of profile.binary_names) {
9081
+ const probe = nativeBinaryProbe(name);
9082
+ // A failed probe's text is its error output, not a version.
9083
+ const semver = probe?.launchable ? parsedSemver(probe.version) : undefined;
9084
+ if (semver)
9085
+ majors.add(semver[0]);
9086
+ }
9087
+ return [...majors].sort((a, b) => a - b);
8851
9088
  }
8852
9089
  function opencodeNativePluginSource() {
8853
9090
  // OpenCode 2 replaced the plugin API: a V1 hook map no longer loads
@@ -8860,12 +9097,14 @@ function opencodeNativePluginSource() {
8860
9097
  // V2 { id, setup } beside it. 1.x also calls setup, with a context that has
8861
9098
  // no session or event API, so setup returns there. Checked against real
8862
9099
  // OpenCode 1.18.35 and 2.0.22; 1.0-1.3 call every export and cannot load it.
8863
- const major = opencodePluginMajor();
8864
- if (major === null)
9100
+ //
9101
+ // Two installed majors take that same file, for the same reason: they share
9102
+ // this one plugins directory, so a file pinned to either API is one the other
9103
+ // host refuses to load (#1316).
9104
+ const majors = opencodePluginMajors();
9105
+ if (majors.length !== 1)
8865
9106
  return opencodeNativePluginSourceBoth();
8866
- if (major < 2)
8867
- return opencodeNativePluginSourceV1();
8868
- return opencodeNativePluginSourceV2();
9107
+ return majors[0] < 2 ? opencodeNativePluginSourceV1() : opencodeNativePluginSourceV2();
8869
9108
  }
8870
9109
  function opencodeNativePluginSourceBoth() {
8871
9110
  const v2 = opencodeNativePluginSourceV2();
@@ -8886,13 +9125,24 @@ const prefix = ${JSON.stringify(pre)};
8886
9125
  const contexts = new Map();
8887
9126
  const pending = new Map();
8888
9127
 
8889
- function call(event, payload = {}) {
9128
+ // A host process can serve a project that is not its own launch directory, so
9129
+ // the served project travels with every call: in the payload, which
9130
+ // nativeRuntimeRequest reads as the session cwd, and as the child's working
9131
+ // directory, so anything it resolves relatively resolves there (#1443).
9132
+ let projectDir;
9133
+
9134
+ function call(event, payload = {}, cwd = projectDir) {
8890
9135
  try {
8891
9136
  const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
8892
- input: JSON.stringify({ event_name: event, ...payload }),
9137
+ input: JSON.stringify({ event_name: event, ...(cwd ? { cwd } : {}), ...payload }),
8893
9138
  encoding: "utf8",
9139
+ cwd: cwd || undefined,
8894
9140
  timeout: 2000,
8895
9141
  maxBuffer: 2 * 1024 * 1024,
9142
+ // A host with no console of its own — OpenCode under a multiplexer or a
9143
+ // GUI launcher — makes Windows give every console child a NEW console
9144
+ // window, so the user sees one flash per event. Ignored off Windows.
9145
+ windowsHide: true,
8896
9146
  });
8897
9147
  if (!raw.trim()) return undefined;
8898
9148
  const value = JSON.parse(raw);
@@ -8959,7 +9209,7 @@ function sessionContext(sessionID) {
8959
9209
  return contexts.get(sessionID);
8960
9210
  }
8961
9211
 
8962
- export const CavemanNative = async () => ({
9212
+ const hostHooks = {
8963
9213
  event: async ({ event }) => {
8964
9214
  const type = event?.type;
8965
9215
  const props = event?.properties ?? {};
@@ -9013,7 +9263,9 @@ export const CavemanNative = async () => ({
9013
9263
  const raw = execFileSync(command, [...prefix, "shrink-hook"], {
9014
9264
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command: output.args.command } }),
9015
9265
  encoding: "utf8",
9266
+ cwd: projectDir || undefined,
9016
9267
  timeout: 750,
9268
+ windowsHide: true,
9017
9269
  });
9018
9270
  const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
9019
9271
  if (typeof rewritten === "string" && rewritten) output.args.command = rewritten;
@@ -9042,7 +9294,15 @@ export const CavemanNative = async () => ({
9042
9294
  contexts.clear();
9043
9295
  pending.clear();
9044
9296
  },
9045
- });
9297
+ };
9298
+
9299
+ // OpenCode's V1 plugin context names the served project \`directory\`. A host
9300
+ // that supplies none (or a caller that supplies no context at all) leaves
9301
+ // projectDir unset and every child inherits this process's cwd, as before.
9302
+ export const CavemanNative = async (ctx) => {
9303
+ if (typeof ctx?.directory === "string" && ctx.directory) projectDir = ctx.directory;
9304
+ return hostHooks;
9305
+ };
9046
9306
  `;
9047
9307
  }
9048
9308
  function opencodeNativePluginSourceV2() {
@@ -9056,13 +9316,24 @@ import { createHash } from "node:crypto";
9056
9316
  const command = ${JSON.stringify(cmd)};
9057
9317
  const prefix = ${JSON.stringify(pre)};
9058
9318
 
9059
- function call(event, payload = {}) {
9319
+ // A host process can serve a project that is not its own launch directory, so
9320
+ // the served project travels with every call: in the payload, which
9321
+ // nativeRuntimeRequest reads as the session cwd, and as the child's working
9322
+ // directory, so anything it resolves relatively resolves there (#1443).
9323
+ let projectDir;
9324
+
9325
+ function call(event, payload = {}, cwd = projectDir) {
9060
9326
  try {
9061
9327
  const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
9062
- input: JSON.stringify({ event_name: event, ...payload }),
9328
+ input: JSON.stringify({ event_name: event, ...(cwd ? { cwd } : {}), ...payload }),
9063
9329
  encoding: "utf8",
9330
+ cwd: cwd || undefined,
9064
9331
  timeout: 2000,
9065
9332
  maxBuffer: 2 * 1024 * 1024,
9333
+ // A host with no console of its own — OpenCode under a multiplexer or a
9334
+ // GUI launcher — makes Windows give every console child a NEW console
9335
+ // window, so the user sees one flash per event. Ignored off Windows.
9336
+ windowsHide: true,
9066
9337
  });
9067
9338
  if (!raw.trim()) return undefined;
9068
9339
  const value = JSON.parse(raw);
@@ -9123,13 +9394,19 @@ export default {
9123
9394
  id: "caveman-native",
9124
9395
  async setup(ctx) {
9125
9396
  // Per-plugin-instance state: one setup() runs per location, so two
9126
- // projects never share session context through module scope.
9397
+ // projects never share session context through module scope. The served
9398
+ // project directory is per-instance for the same reason, so it is passed
9399
+ // to each child explicitly rather than parked in module scope (#1443).
9127
9400
  const contexts = new Map();
9128
9401
  const pending = new Map();
9402
+ const projectCwd = typeof ctx.location?.directory === "string" && ctx.location.directory
9403
+ ? ctx.location.directory
9404
+ : undefined;
9405
+ const emit = (event, payload = {}) => call(event, payload, projectCwd);
9129
9406
 
9130
9407
  function sessionContext(sessionID) {
9131
9408
  if (!contexts.has(sessionID)) {
9132
- const out = call("SessionStart", { session_id: sessionID, surface: "cli" });
9409
+ const out = emit("SessionStart", { session_id: sessionID, surface: "cli" });
9133
9410
  const context = out?.hookSpecificOutput?.additionalContext;
9134
9411
  contexts.set(sessionID, typeof context === "string" ? context : "");
9135
9412
  }
@@ -9146,8 +9423,16 @@ export default {
9146
9423
  });
9147
9424
 
9148
9425
  function sameLocation(event) {
9149
- return event.location?.directory === ctx.location.directory &&
9150
- event.location?.workspaceID === ctx.location.workspaceID;
9426
+ // OpenCode keeps routing metadata separate from the public event: the bus
9427
+ // resolves a locationless session event through that session's owner and
9428
+ // then filters each location subscription with the routing snapshot. So
9429
+ // an event delivered to THIS instance with no public location is already
9430
+ // ours — session.deleted publishes only { sessionID } — and dropping it
9431
+ // skipped SessionEnd and leaked the cached context until disposal
9432
+ // (#1444). A location that is present and different is somebody else's.
9433
+ if (!event.location) return true;
9434
+ return event.location.directory === ctx.location.directory &&
9435
+ event.location.workspaceID === ctx.location.workspaceID;
9151
9436
  }
9152
9437
 
9153
9438
  function handleEvent(event) {
@@ -9156,16 +9441,16 @@ export default {
9156
9441
  const sessionID = event.data?.sessionID;
9157
9442
  if (typeof sessionID !== "string" || !sessionID) return;
9158
9443
  if (type === "session.created") sessionContext(sessionID);
9159
- if (type === "session.idle") call("Stop", { session_id: sessionID });
9444
+ if (type === "session.idle") emit("Stop", { session_id: sessionID });
9160
9445
  // "session.compacted" is the V1 event name; V2 reports compaction
9161
9446
  // through "session.compaction.ended". Handle both.
9162
9447
  if (type === "session.compaction.ended" || type === "session.compacted") {
9163
- const out = call("PostCompact", { session_id: sessionID });
9448
+ const out = emit("PostCompact", { session_id: sessionID });
9164
9449
  const context = out?.hookSpecificOutput?.additionalContext;
9165
9450
  if (typeof context === "string" && context) contexts.set(sessionID, context);
9166
9451
  }
9167
9452
  if (type === "session.deleted") {
9168
- call("SessionEnd", { session_id: sessionID });
9453
+ emit("SessionEnd", { session_id: sessionID });
9169
9454
  contexts.delete(sessionID);
9170
9455
  pending.delete(sessionID);
9171
9456
  }
@@ -9173,7 +9458,7 @@ export default {
9173
9458
 
9174
9459
  await ctx.session.hook("prompt", (event) => {
9175
9460
  const prompt = event.prompt ?? {};
9176
- const decision = call("UserPromptSubmit", {
9461
+ const decision = emit("UserPromptSubmit", {
9177
9462
  session_id: event.sessionID,
9178
9463
  prompt: digest(prompt),
9179
9464
  task_type: taskType(prompt),
@@ -9195,13 +9480,13 @@ export default {
9195
9480
  });
9196
9481
 
9197
9482
  await ctx.session.hook("compaction", (event) => {
9198
- call("PreCompact", { session_id: event.sessionID });
9483
+ emit("PreCompact", { session_id: event.sessionID });
9199
9484
  const stable = sessionContext(event.sessionID);
9200
9485
  if (stable) event.system.push({ type: "text", text: stable });
9201
9486
  });
9202
9487
 
9203
9488
  await ctx.tool.hook("execute.before", (event) => {
9204
- const decision = call("PreToolUse", {
9489
+ const decision = emit("PreToolUse", {
9205
9490
  session_id: event.sessionID,
9206
9491
  tool_name: event.tool,
9207
9492
  tool_input: event.input,
@@ -9218,7 +9503,9 @@ export default {
9218
9503
  const raw = execFileSync(command, [...prefix, "shrink-hook"], {
9219
9504
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
9220
9505
  encoding: "utf8",
9506
+ cwd: projectCwd || undefined,
9221
9507
  timeout: 750,
9508
+ windowsHide: true,
9222
9509
  });
9223
9510
  const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
9224
9511
  if (typeof rewritten === "string" && rewritten) input.command = rewritten;
@@ -9228,7 +9515,7 @@ export default {
9228
9515
 
9229
9516
  await ctx.tool.hook("execute.after", (event) => {
9230
9517
  if (event.status !== "completed") return;
9231
- const decision = call("PostToolUse", {
9518
+ const decision = emit("PostToolUse", {
9232
9519
  session_id: event.sessionID,
9233
9520
  tool_name: event.tool,
9234
9521
  tool_input: event.input,
@@ -9242,7 +9529,7 @@ export default {
9242
9529
 
9243
9530
  return () => {
9244
9531
  controller.abort();
9245
- for (const sessionID of contexts.keys()) call("SessionEnd", { session_id: sessionID });
9532
+ for (const sessionID of contexts.keys()) emit("SessionEnd", { session_id: sessionID });
9246
9533
  contexts.clear();
9247
9534
  pending.clear();
9248
9535
  };
@@ -9261,27 +9548,102 @@ function opencodeNativeRoutes(gw) {
9261
9548
  "opencode-go": appendUrlPath(base, "/compat/opencode-go/v1"),
9262
9549
  };
9263
9550
  }
9264
- // Only the journaled providers reach the proxy. Anything else (GitHub Copilot,
9265
- // Zen) goes direct while the install reads healthy (#1190), so name it. Global
9266
- // config only, the same file enable edits; a project opencode.json can still
9267
- // pick another model.
9268
- function opencodeUnroutedActiveProvider(routed) {
9551
+ // proxyCompatMount answers whether the local proxy serves a user-defined
9552
+ // compat mount of this name: the value when caveman.yaml declares one, null
9553
+ // when it demonstrably does not, and undefined when the file cannot be read or
9554
+ // uses a shape the scan cannot follow.
9555
+ function proxyCompatMount(name) {
9556
+ const path = process.env.CAVEMAN_CONFIG ?? join(cavemanHome(), "caveman.yaml");
9557
+ try {
9558
+ return yamlScopedBaseUrl(readFileSync(path, "utf8"), "compat", name);
9559
+ }
9560
+ catch {
9561
+ return undefined;
9562
+ }
9563
+ }
9564
+ // opencodeBaseUrlRouting reads a provider's configured endpoint and answers
9565
+ // where its requests actually go. #1190 asked the install journal, which holds
9566
+ // only the three routes `enable` writes, so a provider the user routed by hand
9567
+ // — baseURL pointed at the gateway's own /w/opencode wedge — was reported as
9568
+ // going direct and "not compressed or counted" while the proxy was recording
9569
+ // every one of its requests (#1254). The endpoint is the evidence; the name
9570
+ // never was.
9571
+ //
9572
+ // Origin plus the wedge prefix is the whole test, which covers the built-in
9573
+ // /openai/v1 and /anthropic/v1 paths and any deeper one without enumerating
9574
+ // them. A /compat/<name>/ path needs its mount to exist as well: without one
9575
+ // the request still reaches the proxy and 404s, which is a different problem
9576
+ // with a different remedy, so it is reported as the missing mount rather than
9577
+ // as going direct.
9578
+ function opencodeBaseUrlRouting(baseUrl, gw) {
9579
+ if (typeof baseUrl !== "string" || !baseUrl)
9580
+ return null;
9581
+ let endpoint;
9582
+ let wedge;
9583
+ try {
9584
+ endpoint = new URL(baseUrl);
9585
+ wedge = new URL(appendUrlPath(gw, "/w/opencode"));
9586
+ }
9587
+ catch {
9588
+ return null;
9589
+ }
9590
+ if (endpoint.origin !== wedge.origin)
9591
+ return null;
9592
+ const prefix = wedge.pathname.replace(/\/+$/, "");
9593
+ const path = endpoint.pathname.replace(/\/+$/, "");
9594
+ if (path !== prefix && !path.startsWith(`${prefix}/`))
9595
+ return null;
9596
+ const mount = path.slice(prefix.length).match(/^\/compat\/([^/]+)/);
9597
+ if (!mount)
9598
+ return { routed: true };
9599
+ const name = decodeURIComponent(mount[1]);
9600
+ // Only a readable config that demonstrably lacks the mount is evidence of
9601
+ // one missing. Unverifiable must not bring the false alarm back in another
9602
+ // spelling: the endpoint already proves these requests are not going direct.
9603
+ return proxyCompatMount(name) === null ? { routed: false, mount: name } : { routed: true };
9604
+ }
9605
+ // Only the journaled providers reach the proxy by default. Anything else
9606
+ // (GitHub Copilot, Zen) goes direct while the install reads healthy (#1190), so
9607
+ // name it — unless the user routed it themselves (#1254). Global config only,
9608
+ // the same file enable edits; a project opencode.json can still pick another
9609
+ // model.
9610
+ function opencodeUnroutedActiveProvider(routed, gw) {
9611
+ const configs = [];
9269
9612
  for (const name of ["opencode.jsonc", "opencode.json"]) {
9270
9613
  try {
9271
- const model = parseJsonc(readFileSync(join(opencodeConfigDir(), name), "utf8"))?.model;
9272
- if (typeof model === "string" && model.includes("/")) {
9273
- const provider = model.slice(0, model.indexOf("/"));
9274
- return routed.includes(provider) ? null : provider;
9275
- }
9614
+ configs.push(objectValue(parseJsonc(readFileSync(join(opencodeConfigDir(), name), "utf8"))));
9276
9615
  }
9277
9616
  catch { /* missing or unreadable: try the next source */ }
9278
9617
  }
9618
+ const verdict = (provider) => {
9619
+ if (routed.includes(provider))
9620
+ return null;
9621
+ // Every candidate config is consulted before answering, so a routed
9622
+ // endpoint in one is never shadowed by a missing mount named in another.
9623
+ let missing = null;
9624
+ for (const config of configs) {
9625
+ const routing = opencodeBaseUrlRouting(objectValue(objectValue(objectValue(config.provider)[provider]).options).baseURL, gw);
9626
+ if (routing?.routed === true)
9627
+ return null;
9628
+ if (routing?.routed === false)
9629
+ missing ??= routing.mount;
9630
+ }
9631
+ return { provider, mount: missing };
9632
+ };
9633
+ for (const config of configs) {
9634
+ const model = config.model;
9635
+ if (typeof model === "string" && model.includes("/"))
9636
+ return verdict(model.slice(0, model.indexOf("/")));
9637
+ }
9279
9638
  // No model pinned: OpenCode picks among signed-in providers, so only a
9280
9639
  // sign-in set with no routed provider at all is a sure miss.
9281
9640
  try {
9282
9641
  const dataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
9283
9642
  const signedIn = Object.keys(JSON.parse(readFileSync(join(dataRoot, "opencode", "auth.json"), "utf8")) ?? {});
9284
- return signedIn.length > 0 && !signedIn.some((id) => routed.includes(id)) ? signedIn[0] : null;
9643
+ if (signedIn.length === 0)
9644
+ return null;
9645
+ const verdicts = signedIn.map((id) => verdict(id));
9646
+ return verdicts.every((item) => item !== null) ? verdicts[0] : null;
9285
9647
  }
9286
9648
  catch {
9287
9649
  return null;
@@ -9347,11 +9709,14 @@ function opencodeNativeMutations(gw, mcpBinary, plan = false) {
9347
9709
  },
9348
9710
  ];
9349
9711
  }
9712
+ // Pi's extension auto-discovery accepts only .ts/.js (isExtensionFile in
9713
+ // pi-coding-agent 0.84.2); a .mjs here would journal fine and never load.
9714
+ function piNativeExtensionPath() {
9715
+ return join(homedir(), ".pi", "agent", "extensions", "caveman-native.js");
9716
+ }
9350
9717
  function piNativeMutations() {
9351
- const extensionDir = join(homedir(), ".pi", "agent", "extensions");
9352
- // Pi's extension auto-discovery accepts only .ts/.js (isExtensionFile in
9353
- // pi-coding-agent 0.84.2); a .mjs here would journal fine and never load.
9354
- const extensionPath = join(extensionDir, "caveman-native.js");
9718
+ const extensionPath = piNativeExtensionPath();
9719
+ const extensionDir = dirname(extensionPath);
9355
9720
  const before = fileBytes(extensionPath);
9356
9721
  if (before && !before.toString("utf8").includes("caveman:native-pi")) {
9357
9722
  throw new Error(`${extensionPath} already exists and is not Caveman-owned; refusing to overwrite it`);
@@ -9737,6 +10102,11 @@ import subprocess
9737
10102
 
9738
10103
  _CAVEMAN_CMD = ${JSON.stringify(cmd)}
9739
10104
  _CAVEMAN_PRE = ${JSON.stringify(pre)}
10105
+ # A Hermes host with no console of its own makes Windows give every console
10106
+ # child a NEW console window, so the user sees one flash per hook call.
10107
+ # subprocess ignores Node's windowsHide, and CREATE_NO_WINDOW is absent off
10108
+ # Windows, so resolve it at run time and pass 0 everywhere else (#1214).
10109
+ _CAVEMAN_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
9740
10110
 
9741
10111
 
9742
10112
  def _digest(value):
@@ -9810,6 +10180,7 @@ def _call(event, payload=None):
9810
10180
  text=True,
9811
10181
  capture_output=True,
9812
10182
  timeout=1,
10183
+ creationflags=_CAVEMAN_NO_WINDOW,
9813
10184
  )
9814
10185
  if proc.returncode != 0 or not proc.stdout.strip():
9815
10186
  return None
@@ -9893,15 +10264,31 @@ function insertHermesNativeListEntry(lines, sectionName, childName, begin, end,
9893
10264
  lines.push(...whole);
9894
10265
  return whole.join("\n");
9895
10266
  }
10267
+ // Hermes provider ids that carry their OWN OAuth credential and the ChatGPT
10268
+ // Responses transport. Rewriting one to the generic `custom` provider drops
10269
+ // both: the installed resolver then picks chat_completions with
10270
+ // `no-key-required` and every request 401s (#1391). These keep their provider
10271
+ // and ride the proxy's existing ChatGPT handler instead.
10272
+ const HERMES_CHATGPT_OAUTH_PROVIDERS = new Set(["openai-codex"]);
10273
+ // `/chatgpt` is the ChatGPT mux handler, which takes its suffix verbatim — the
10274
+ // Responses operation is `/chatgpt/responses`, so this must NOT gain a "/v1".
10275
+ // Same reasoning as codexGatewayBase().
10276
+ function hermesGatewayBase(gw, keptProvider) {
10277
+ return appendUrlPath(gw, keptProvider && HERMES_CHATGPT_OAUTH_PROVIDERS.has(keptProvider) ? "/chatgpt" : "/w/hermes/v1");
10278
+ }
9896
10279
  function hermesNativeConfig(source, gw, mcpBinary) {
9897
10280
  for (const marker of [HERMES_NATIVE_ROUTE_BEGIN, HERMES_NATIVE_ROUTE_END, HERMES_NATIVE_PLUGIN_BEGIN, HERMES_NATIVE_PLUGIN_END, HERMES_NATIVE_MCP_BEGIN, HERMES_NATIVE_MCP_END]) {
9898
10281
  if (source.includes(marker))
9899
10282
  throw new Error("existing Hermes Caveman native block is unjournaled; run `caveman doctor hermes`");
9900
10283
  }
10284
+ const nativePluginMembership = hermesNamedPluginMembership(source, HERMES_NATIVE_PLUGIN_NAME);
10285
+ if (nativePluginMembership === "disabled") {
10286
+ throw new Error(`Hermes plugin ${HERMES_NATIVE_PLUGIN_NAME} is explicitly disabled in plugins.disabled; remove that entry before enabling Caveman`);
10287
+ }
9901
10288
  const lines = yamlLines(source);
9902
10289
  let model = topLevelSection(lines, "model");
9903
10290
  if (!model) {
9904
- lines.unshift("model:");
10291
+ lines.splice(yamlBodyStart(lines), 0, "model:");
9905
10292
  model = topLevelSection(lines, "model");
9906
10293
  }
9907
10294
  const routeIndexes = [];
@@ -9918,10 +10305,17 @@ function hermesNativeConfig(source, gw, mcpBinary) {
9918
10305
  const insertAt = routeIndexes[0] ?? model.start + 1;
9919
10306
  for (const index of [...routeIndexes].sort((a, b) => b - a))
9920
10307
  lines.splice(index, 1);
10308
+ // A named OAuth provider selects a credential and a transport that the
10309
+ // generic custom route cannot carry, so keep it and route to the handler
10310
+ // that speaks it. `api_mode` is not a route key, so it already survives.
10311
+ const providerLine = previousRouteLines.find((line) => /^ provider:/.test(line));
10312
+ const previousProvider = providerLine ? configValue(providerLine.slice(providerLine.indexOf(":") + 1)) : undefined;
10313
+ const keptProvider = previousProvider && HERMES_CHATGPT_OAUTH_PROVIDERS.has(previousProvider) ? previousProvider : null;
10314
+ const route = hermesGatewayBase(gw, keptProvider);
9921
10315
  const routeBlock = [
9922
10316
  ` ${HERMES_NATIVE_ROUTE_BEGIN}`,
9923
- ' provider: "custom"',
9924
- ` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes/v1"))}`,
10317
+ keptProvider ? ` provider: ${keptProvider}` : ' provider: "custom"',
10318
+ ` base_url: ${yamlQuote(route)}`,
9925
10319
  ` ${HERMES_NATIVE_ROUTE_END}`,
9926
10320
  ];
9927
10321
  lines.splice(insertAt, 0, ...routeBlock);
@@ -9938,8 +10332,9 @@ function hermesNativeConfig(source, gw, mcpBinary) {
9938
10332
  }
9939
10333
  }
9940
10334
  if (enabled >= 0) {
9941
- if (!hermesNamedPluginEnabled(source, HERMES_NATIVE_PLUGIN_NAME)) {
9942
- const block = [` ${HERMES_NATIVE_PLUGIN_BEGIN}`, ` - ${HERMES_NATIVE_PLUGIN_NAME}`, ` ${HERMES_NATIVE_PLUGIN_END}`];
10335
+ if (nativePluginMembership !== "enabled") {
10336
+ const pad = " ".repeat(yamlListItemIndent(lines, enabled, plugins.end) ?? 4);
10337
+ const block = [`${pad}${HERMES_NATIVE_PLUGIN_BEGIN}`, `${pad}- ${HERMES_NATIVE_PLUGIN_NAME}`, `${pad}${HERMES_NATIVE_PLUGIN_END}`];
9943
10338
  lines.splice(enabled + 1, 0, ...block);
9944
10339
  pluginBlock = block.join("\n");
9945
10340
  }
@@ -9959,16 +10354,19 @@ function hermesNativeConfig(source, gw, mcpBinary) {
9959
10354
  }
9960
10355
  const mcpBlockLines = [
9961
10356
  ` ${HERMES_NATIVE_MCP_BEGIN}`,
9962
- " caveman-native:",
10357
+ ` ${HERMES_NATIVE_MCP_SERVER}:`,
9963
10358
  ` command: ${yamlQuote(mcpBinary)}`,
9964
10359
  " enabled: true",
9965
10360
  ` ${HERMES_NATIVE_MCP_END}`,
9966
10361
  ];
9967
- const mcpBlock = insertHermesNativeListEntry(lines, "mcp_servers", "caveman-native", HERMES_NATIVE_MCP_BEGIN, HERMES_NATIVE_MCP_END, mcpBlockLines);
10362
+ const mcpBlock = insertHermesNativeListEntry(lines, "mcp_servers", HERMES_NATIVE_MCP_SERVER, HERMES_NATIVE_MCP_BEGIN, HERMES_NATIVE_MCP_END, mcpBlockLines);
9968
10363
  return {
9969
10364
  text: yamlText(lines),
9970
10365
  owned: {
9971
- route: appendUrlPath(gw, "/w/hermes/v1"),
10366
+ route,
10367
+ // Absent in journals written before #1391; doctor reads that as the
10368
+ // generic route, which is what those installs actually carry.
10369
+ provider: keptProvider ?? "custom",
9972
10370
  route_block: routeBlock.join("\n"),
9973
10371
  previous_route_lines: previousRouteLines,
9974
10372
  plugin_block: pluginBlock,
@@ -10466,8 +10864,9 @@ function enableNative(argv, { quiet = false } = {}) {
10466
10864
  // is not the current target); it is re-wired below, outside the lock.
10467
10865
  // Module apply (quiet) writes only the files its plan showed, so the
10468
10866
  // voice skills ride along with an explicit `caveman enable` only.
10469
- // A Claude profile the journal does not cover is re-wired the same way.
10470
- if (agentStaleRoute(agent) || existing.unwired_profiles.length > 0) {
10867
+ // A Claude profile the journal does not cover is re-wired the same way,
10868
+ // and so is a Gemini install that predates the auth pin.
10869
+ if (agentStaleRoute(agent) || existing.unwired_profiles.length > 0 || geminiAuthUndecided(agent)) {
10471
10870
  if (!quiet)
10472
10871
  installNativeVoiceSkills(agent);
10473
10872
  return "stale";
@@ -10493,6 +10892,8 @@ function enableNative(argv, { quiet = false } = {}) {
10493
10892
  process.stderr.write(` ${mutation.kind}: ${mutation.file}\n`);
10494
10893
  if (typeof route === "string")
10495
10894
  process.stderr.write(` routing: ${route}\n`);
10895
+ if (mutations.some((item) => typeof item.owned?.selected_auth === "string"))
10896
+ process.stderr.write(` ${GEMINI_PINNED_AUTH_NOTE}\n`);
10496
10897
  process.stderr.write(agent === "aider" ? " recovery MCP: unavailable in Aider\n" : ` recovery MCP: ${mcpBinary}\n`);
10497
10898
  process.stderr.write(agent === "aider"
10498
10899
  ? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
@@ -10537,9 +10938,13 @@ function enableNative(argv, { quiet = false } = {}) {
10537
10938
  setNativeOptOut(agent, false);
10538
10939
  if (outcome === "stale") {
10539
10940
  const was = agentStaleRoute(agent);
10941
+ const authUndecided = geminiAuthUndecided(agent);
10540
10942
  repairNativeAgent(agent, { quiet: true });
10541
10943
  if (!quiet)
10542
- process.stderr.write(`${mark("ok")} ${profile.display_name}: ${was ? `routing: ${was} → ${new URL(gw).origin}` : "native Caveman now covers every profile"}\n`);
10944
+ process.stderr.write(`${mark("ok")} ${profile.display_name}: ${was ? `routing: ${was} → ${new URL(gw).origin}` : authUndecided ? "native Caveman wiring refreshed" : "native Caveman now covers every profile"}\n`);
10945
+ const pinned = readNativeJournal(agent)?.operations.find((item) => item.kind === "gemini-settings")?.owned?.selected_auth;
10946
+ if (!quiet && authUndecided && typeof pinned === "string")
10947
+ process.stderr.write(dim(`→ ${GEMINI_PINNED_AUTH_NOTE}\n`));
10543
10948
  }
10544
10949
  ensureLocalProxyForNative(agent, gw);
10545
10950
  if (quiet || outcome === "stale")
@@ -10669,7 +11074,7 @@ function restoreNativeOperation(operation) {
10669
11074
  // Symmetric to the enable-side ENABLE_TOOL_SEARCH write: only withdraw the
10670
11075
  // value we introduced ourselves and only while it is still untouched, so a
10671
11076
  // user who set their own afterwards keeps it.
10672
- if (beforeEnv.ENABLE_TOOL_SEARCH === undefined && currentEnv.ENABLE_TOOL_SEARCH === TOOL_SEARCH_DEFAULT) {
11077
+ if (beforeEnv.ENABLE_TOOL_SEARCH === undefined && (currentEnv.ENABLE_TOOL_SEARCH === TOOL_SEARCH_DEFAULT || LEGACY_TOOL_SEARCH_DEFAULTS.includes(String(currentEnv.ENABLE_TOOL_SEARCH)))) {
10673
11078
  delete currentEnv.ENABLE_TOOL_SEARCH;
10674
11079
  }
10675
11080
  // Auto's picker keys this enable added, each only while it is still ours.
@@ -10735,6 +11140,18 @@ function restoreNativeOperation(operation) {
10735
11140
  currentRoot.mcpServers = servers;
10736
11141
  else
10737
11142
  delete currentRoot.mcpServers;
11143
+ // Withdraw the pinned auth type only while it is still ours; a type the
11144
+ // user picked since (Gemini's /auth rewrites it) outlives disable.
11145
+ const selected = operation.owned?.selected_auth;
11146
+ const security = asJsonObject(currentRoot.security);
11147
+ const auth = asJsonObject(security?.auth);
11148
+ if (typeof selected === "string" && auth?.selectedType === selected) {
11149
+ delete auth.selectedType;
11150
+ if (Object.keys(auth).length === 0 && !getObject(beforeRoot, ["security", "auth"]))
11151
+ delete security.auth;
11152
+ if (Object.keys(security).length === 0 && !asJsonObject(beforeRoot.security))
11153
+ delete currentRoot.security;
11154
+ }
10738
11155
  return jsonBytes(currentRoot, current);
10739
11156
  }
10740
11157
  if (operation.kind === "gemini-env") {
@@ -10829,18 +11246,33 @@ function restoreNativeOperation(operation) {
10829
11246
  if (typeof routeBlock !== "string" || !Array.isArray(previousRouteLines)) {
10830
11247
  throw new Error("Hermes integration journal lacks owned routing block");
10831
11248
  }
10832
- if (!text.includes(routeBlock))
10833
- throw new Error("Hermes routing block changed after enable; refusing destructive disable");
10834
- text = text.replace(routeBlock, previousRouteLines.filter((line) => typeof line === "string").join("\n"));
10835
- for (const key of ["plugin_block", "mcp_block"]) {
10836
- const block = operation.owned?.[key];
10837
- if (block === null || block === undefined)
10838
- continue;
10839
- if (typeof block !== "string" || !text.includes(block))
10840
- throw new Error(`Hermes ${key.replace("_block", "")} block changed after enable; refusing destructive disable`);
10841
- text = text.replace(block, "");
11249
+ // The blocks are still there verbatim: restore byte for byte, as before.
11250
+ // A reserialised document (#1410) has the same VALUES under different
11251
+ // layout, and the markers are gone with the comments — so prove ownership
11252
+ // by value and then remove the settings by key. Anything that proof does
11253
+ // not cover keeps refusing: a changed owned value, a duplicate key, or a
11254
+ // shape the scoped reader will not decode.
11255
+ if (text.includes(routeBlock)) {
11256
+ text = text.replace(routeBlock, previousRouteLines.filter((line) => typeof line === "string").join("\n"));
11257
+ for (const key of ["plugin_block", "mcp_block"]) {
11258
+ const block = operation.owned?.[key];
11259
+ if (block === null || block === undefined)
11260
+ continue;
11261
+ if (typeof block !== "string" || !text.includes(block))
11262
+ throw new Error(`Hermes ${key.replace("_block", "")} block changed after enable; refusing destructive disable`);
11263
+ text = text.replace(block, "");
11264
+ }
11265
+ return Buffer.from(text);
10842
11266
  }
10843
- return Buffer.from(text);
11267
+ if (!hermesRouteOwned(text, operation.owned))
11268
+ throw new Error("Hermes routing block changed after enable; refusing destructive disable");
11269
+ // An absent block is a journal that never wrote one: nothing of ours to
11270
+ // prove and nothing to remove, exactly as the literal loop above skips it.
11271
+ if (operation.owned?.plugin_block !== undefined && !hermesPluginOwned(text, operation.owned))
11272
+ throw new Error("Hermes plugin block changed after enable; refusing destructive disable");
11273
+ if (operation.owned?.mcp_block !== undefined && !hermesMcpOwned(text, operation.owned))
11274
+ throw new Error("Hermes mcp block changed after enable; refusing destructive disable");
11275
+ return Buffer.from(hermesRestoreOwnedByValue(text, operation.owned));
10844
11276
  }
10845
11277
  const rootBlock = operation.owned?.root_block;
10846
11278
  const tablesBlock = operation.owned?.tables_block;
@@ -11304,10 +11736,15 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11304
11736
  owned = CODEX_NATIVE_TABLES.every((table) => tables.get(table) === true) && codexNativeRouted(lines) && text.indexOf("\uFEFF", 1) === -1;
11305
11737
  }
11306
11738
  else if (operation.kind === "hermes-config") {
11739
+ // By name and value, like codex-config above and for the same reason:
11740
+ // a YAML round-trip that changes no value at all drops our marker
11741
+ // comments and renormalises quoting, and a literal read called that
11742
+ // drift (#1410).
11307
11743
  const text = current.toString("utf8");
11308
- owned = typeof operation.owned?.route_block === "string" && text.includes(operation.owned.route_block)
11309
- && (operation.owned.plugin_block === null || (typeof operation.owned.plugin_block === "string" && text.includes(operation.owned.plugin_block)))
11310
- && (operation.owned.mcp_block === null || (typeof operation.owned.mcp_block === "string" && text.includes(operation.owned.mcp_block)));
11744
+ owned = typeof operation.owned?.route_block === "string"
11745
+ && hermesRouteOwned(text, operation.owned)
11746
+ && hermesPluginOwned(text, operation.owned)
11747
+ && hermesMcpOwned(text, operation.owned);
11311
11748
  }
11312
11749
  else if (operation.kind === "gemini-settings") {
11313
11750
  const root = parseJsonFileObject(operation.file, current);
@@ -11367,11 +11804,16 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11367
11804
  const coreResolution = runtimeConfig.resolution.values["think.core"];
11368
11805
  const coreConfigured = coreResolution.value === true;
11369
11806
  const mcp = probeMcpBinary();
11370
- const expectedRoute = agent === "codex"
11371
- ? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
11372
- : appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
11373
11807
  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";
11374
11808
  const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
11809
+ // Hermes has two routes: the generic one, and `/chatgpt` for an install that
11810
+ // kept a named OAuth provider. The journal records which, so doctor expects
11811
+ // the route this install actually wrote rather than one of them always.
11812
+ const expectedRoute = agent === "codex"
11813
+ ? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
11814
+ : agent === "hermes"
11815
+ ? hermesGatewayBase(gatewayURL(), typeof routeOperation?.owned?.provider === "string" ? routeOperation.owned.provider : null)
11816
+ : appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
11375
11817
  // Pi's artifact encodes no route: the extension resolves the gateway at
11376
11818
  // runtime through the same env → config → default chain as gatewayURL(), so
11377
11819
  // route drift between enable and now cannot happen. What CAN drift is the
@@ -11401,6 +11843,12 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11401
11843
  // An unreadable version cannot vouch for a single-API file (an old V1 install
11402
11844
  // on a 2.x host whose probe times out); repair rewrites it as the file both
11403
11845
  // majors load, which reads current whatever the version.
11846
+ //
11847
+ // Neither can ONE readable version when the machine has two of them: the same
11848
+ // drift arrives sideways when a second bin shows up rather than when the first
11849
+ // one upgrades (`opencode` stays 1.19.3, `opencode2` is new, and the shared
11850
+ // plugins dir now has a host that refuses the installed file — #1316). So the
11851
+ // question is the full set of installed majors, exactly as it is for emission.
11404
11852
  const opencodePluginApiCurrent = agent !== "opencode" || (() => {
11405
11853
  const operation = journal?.operations.find((item) => item.kind === "opencode-plugin");
11406
11854
  const current = operation ? fileBytes(operation.file)?.toString("utf8") : null;
@@ -11408,19 +11856,24 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11408
11856
  return true;
11409
11857
  const installedV2 = current.includes("async setup(ctx)");
11410
11858
  const installedV1 = current.includes("export const CavemanNative");
11859
+ // Both markers (the dual file) or neither: nothing is pinned to one API.
11411
11860
  if (installedV1 === installedV2)
11412
11861
  return true;
11413
- const semver = host.launchable ? parsedSemver(host.version) : undefined;
11414
- if (!semver)
11862
+ const majors = opencodePluginMajors();
11863
+ if (majors.length !== 1)
11415
11864
  return false;
11416
- return (semver[0] >= 2) === installedV2;
11865
+ return (majors[0] >= 2) === installedV2;
11417
11866
  })();
11418
11867
  const routeHealthy = ownedHealthy && (agent === "opencode"
11419
11868
  ? Object.entries(opencodeNativeRoutes(gatewayURL())).every(([providerID, route]) => routeOperation?.owned?.routes?.[providerID] === route)
11420
11869
  // Claude journals one route per profile; each has to be the current one.
11421
11870
  : agent === "pi" ? piBundleCurrent : Boolean(routeOperation) && journal.operations.every((operation) => operation.kind !== routeKind || operation.owned?.route === expectedRoute));
11422
11871
  const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
11423
- const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
11872
+ // Recovery is real only when a current caveman-mcp is resolvable AND the
11873
+ // command the host will actually launch still exists. Both the component
11874
+ // below and this verdict read the one term, so they cannot disagree.
11875
+ const mcpLaunchable = Boolean(mcp?.probe.current) && journaledMcpTargetsExist(journal);
11876
+ const recoveryHealthy = agent === "aider" || mcpLaunchable;
11424
11877
  const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy || !opencodePluginApiCurrent || unwiredProfiles.length > 0 ? "degraded" : "installed";
11425
11878
  const coreSupported = agent === "aider" ? ownedHealthy : ownedHealthy && Boolean(NATIVE_PACK.core);
11426
11879
  // Codex runs none of the hooks until the user trusts them; Core rides on them.
@@ -11438,9 +11891,16 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11438
11891
  }
11439
11892
  if (agent === "opencode" && installed) {
11440
11893
  const routed = Object.keys(routeOperation?.owned?.routes ?? {});
11441
- const unrouted = opencodeUnroutedActiveProvider(routed);
11442
- if (unrouted)
11443
- warnings.push(`OpenCode's active provider "${unrouted}" is not routed through Caveman; its requests go direct and are not compressed or counted (routed: ${routed.join(", ")})`);
11894
+ const unrouted = opencodeUnroutedActiveProvider(routed, gatewayURL());
11895
+ if (unrouted?.mount) {
11896
+ // Already pointed at the proxy, just at a mount the proxy does not
11897
+ // serve: those requests reach Caveman and 404, so naming the mount is
11898
+ // the remedy, not "it goes direct" (#1254).
11899
+ warnings.push(`OpenCode's active provider "${unrouted.provider}" points at the Caveman compat mount "${unrouted.mount}", which the local proxy does not serve; add compat.${unrouted.mount}.base_url to caveman.yaml so those requests can be forwarded`);
11900
+ }
11901
+ else if (unrouted) {
11902
+ warnings.push(`OpenCode's active provider "${unrouted.provider}" is not routed through Caveman; its requests go direct and are not compressed or counted (routed: ${routed.join(", ")})`);
11903
+ }
11444
11904
  }
11445
11905
  for (const root of unwiredProfiles)
11446
11906
  warnings.push(`Claude profile ${root} is not routed through Caveman; run \`caveman enable claude\``);
@@ -11448,12 +11908,17 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11448
11908
  if (own?.routed)
11449
11909
  warnings.push(ownEndpointRoutedMessage(agent, own));
11450
11910
  const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
11911
+ // Hermes reads its routing by PARSING the document, so it gets the config
11912
+ // file on its own rather than every journalled file concatenated: a `model:`
11913
+ // or `mcp_servers:` key appearing in the plugin manifest later must not be
11914
+ // able to answer for the one in config.yaml.
11915
+ const hermesRouteFileText = agent === "hermes" && routeOperation ? fileBytes(routeOperation.file)?.toString("utf8") ?? "" : "";
11451
11916
  const components = {
11452
- routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? fileText.includes(HERMES_NATIVE_ROUTE_BEGIN) : agent === "gemini" ? fileText.includes(GEMINI_NATIVE_ENV_BEGIN) : agent === "opencode" ? fileText.includes("caveman:native-opencode") : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
11917
+ routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? hermesRouteOwned(hermesRouteFileText, routeOperation?.owned) : agent === "gemini" ? fileText.includes(GEMINI_NATIVE_ENV_BEGIN) : agent === "opencode" ? fileText.includes("caveman:native-opencode") : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
11453
11918
  // A plugin the host cannot load runs no hooks, whatever its bytes hash to.
11454
11919
  lifecycle_hooks: agent !== "aider" && ownedHealthy && opencodePluginApiCurrent && hooksTrusted,
11455
11920
  core: coreActive,
11456
- mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
11921
+ mcp_recovery: agent !== "aider" && ownedHealthy && mcpLaunchable,
11457
11922
  // Codex is false for the same reason hermes is: no command rewrite happens.
11458
11923
  // Since #1037 shrinkHook declines every Codex tool event, so Codex gets no
11459
11924
  // shrink-hook entry; an older install's entry reads degraded until --fix.
@@ -11566,7 +12031,7 @@ async function nativeDoctor(argv) {
11566
12031
  enableNative([target]);
11567
12032
  fixResult = "enabled";
11568
12033
  }
11569
- else if (before.state === "installed" && !agentStaleRoute(target)) {
12034
+ else if (before.state === "installed" && !agentStaleRoute(target) && !geminiAuthUndecided(target)) {
11570
12035
  fixResult = "not_needed";
11571
12036
  }
11572
12037
  else {
@@ -11719,6 +12184,7 @@ function shrinkText(text) {
11719
12184
  input: text,
11720
12185
  encoding: "utf8",
11721
12186
  maxBuffer: 64 * 1024 * 1024,
12187
+ windowsHide: true,
11722
12188
  });
11723
12189
  return typeof out === "string" && out.trim() ? out : "";
11724
12190
  }
@@ -12644,6 +13110,7 @@ async function login(argv = [], ui) {
12644
13110
  // credential. Do not print authenticated success or continue the post-login
12645
13111
  // bridge until the control plane has recorded that this CLI stored the bundle.
12646
13112
  await saveConfig(saved);
13113
+ dropWrapRefreshState();
12647
13114
  await grant.acknowledge();
12648
13115
  syncAutoEntries();
12649
13116
  // The first-run screen says these its own way.
@@ -12733,6 +13200,7 @@ async function logout() {
12733
13200
  await saveConfig({ ...cfg, logoutPendingLocalCleanup: true });
12734
13201
  clearToken(cfg.tokenStore);
12735
13202
  await saveConfig({ baseURL: "", token: "" });
13203
+ dropWrapRefreshState();
12736
13204
  syncAutoEntries();
12737
13205
  print({ logged_out: true });
12738
13206
  }
@@ -13145,12 +13613,24 @@ async function syncLocalSavings(cfg) {
13145
13613
  // node:sqlite is built into Node ≥22.13 — still zero runtime deps. Imported
13146
13614
  // lazily so only sync paths ever load it (or pay its experimental warning).
13147
13615
  let DatabaseSync;
13616
+ // Node 22-23 print "ExperimentalWarning: SQLite is an experimental feature"
13617
+ // on first load; drop that one line rather than show it on every sync.
13618
+ const emitWarning = process.emitWarning;
13619
+ process.emitWarning = ((warning, ...rest) => {
13620
+ const type = typeof rest[0] === "string" ? rest[0] : rest[0]?.type;
13621
+ if (type === "ExperimentalWarning" && /SQLite/.test(String(warning?.message ?? warning)))
13622
+ return;
13623
+ emitWarning.call(process, warning, ...rest);
13624
+ });
13148
13625
  try {
13149
13626
  ({ DatabaseSync } = await import("node:sqlite"));
13150
13627
  }
13151
13628
  catch {
13152
13629
  throw new Error(`caveman sync requires Node >= 22.13 (it reads the local spend store via node:sqlite); you are running Node ${process.versions.node}`);
13153
13630
  }
13631
+ finally {
13632
+ process.emitWarning = emitWarning;
13633
+ }
13154
13634
  const db = new DatabaseSync(dbPath, { readOnly: true });
13155
13635
  let rows;
13156
13636
  let key;
@@ -13223,23 +13703,40 @@ async function syncLocalSavings(cfg) {
13223
13703
  return [];
13224
13704
  return directiveInstalls.filter((d) => ms >= d.installedAtMs).map((d) => d.id);
13225
13705
  };
13226
- const body = rows.map((r) => syncRequestSpan(r, rowDirectives(r))).join("\n") + "\n";
13227
- const response = await fetch(`${cfg.baseURL}/api/v1/imports?format=caveman-jsonl`, {
13228
- method: "POST",
13229
- headers: {
13230
- authorization: `Bearer ${cfg.token}`,
13231
- "content-type": "application/octet-stream",
13232
- "x-cave-csrf": "cli",
13233
- },
13234
- body,
13235
- });
13236
- const result = (await response.json().catch(() => ({})));
13237
- if (!response.ok || result.status !== "completed") {
13238
- throw new Error(result.error?.message ?? `sync import failed (${response.status})`);
13239
- }
13240
13706
  const num = (v) => (typeof v === "bigint" ? Number(v) : typeof v === "number" && Number.isFinite(v) ? v : 0);
13241
- const maxId = rows.reduce((m, r) => Math.max(m, num(r.id)), since);
13242
- writeSyncWatermark(key, maxId);
13707
+ // The import endpoint caps a body at 16 MiB, and a long-unsynced store is
13708
+ // larger than that. Upload in id order in batches under the cap, moving the
13709
+ // watermark after each, so a failed batch keeps the ones before it.
13710
+ const maxBytes = Number(process.env.CAVEMAN_SYNC_MAX_BATCH_BYTES) || 8 << 20;
13711
+ for (let start = 0; start < rows.length;) {
13712
+ let body = "";
13713
+ let bytes = 0;
13714
+ let end = start;
13715
+ while (end < rows.length) {
13716
+ const line = syncRequestSpan(rows[end], rowDirectives(rows[end])) + "\n";
13717
+ const size = Buffer.byteLength(line);
13718
+ if (body && bytes + size > maxBytes)
13719
+ break;
13720
+ body += line;
13721
+ bytes += size;
13722
+ end++;
13723
+ }
13724
+ const response = await fetch(`${cfg.baseURL}/api/v1/imports?format=caveman-jsonl`, {
13725
+ method: "POST",
13726
+ headers: {
13727
+ authorization: `Bearer ${cfg.token}`,
13728
+ "content-type": "application/octet-stream",
13729
+ "x-cave-csrf": "cli",
13730
+ },
13731
+ body,
13732
+ });
13733
+ const result = (await response.json().catch(() => ({})));
13734
+ if (!response.ok || result.status !== "completed") {
13735
+ throw new Error(result.error?.message ?? `sync import failed (${response.status})`);
13736
+ }
13737
+ writeSyncWatermark(key, num(rows[end - 1].id));
13738
+ start = end;
13739
+ }
13243
13740
  const tokensSaved = rows.reduce((sum, r) => sum + Math.max(0, num(r.compression_tokens_before) - num(r.compression_tokens_after)), 0);
13244
13741
  const tokenBases = new Set(rows.map((r) => (typeof r.compression_token_count_basis === "string" ? r.compression_token_count_basis : "")).filter(Boolean));
13245
13742
  const tokenCountBasis = tokenBases.size === 0 ? "unavailable" : tokenBases.size === 1 ? [...tokenBases][0] ?? "unavailable" : "mixed";
@@ -13705,8 +14202,9 @@ function nativeMcpRegistered(agent) {
13705
14202
  if (agent === "codex")
13706
14203
  return typeof operation.owned?.tables_block === "string" && codexNativeTables(codexTomlLines(current.toString("utf8")), operation.owned.tables_block).get("mcp_servers.caveman") === true;
13707
14204
  // A null block: the user's own caveman-native entry was already there.
14205
+ // Read by value, so a reserialised config still counts (#1410).
13708
14206
  if (agent === "hermes")
13709
- return operation.owned?.mcp_block === null || (typeof operation.owned?.mcp_block === "string" && current.toString("utf8").includes(operation.owned.mcp_block));
14207
+ return hermesMcpOwned(current.toString("utf8"), operation.owned);
13710
14208
  if (agent === "pi")
13711
14209
  return current.toString("utf8").includes("caveman:native-pi");
13712
14210
  const servers = objectValue(parseJsonFileObject(operation.file, current).mcpServers);
@@ -13776,6 +14274,15 @@ function buildPiWrapArgs(cmdArgs, env, gw) {
13776
14274
  const { cmd, pre } = cavemanInvocation();
13777
14275
  env.CAVEMAN_PI_HOOK_CMD = JSON.stringify([cmd, ...pre]);
13778
14276
  env.CAVE_GATEWAY_URL = gw;
14277
+ // After `caveman enable pi`, Pi already auto-loads the owned copy. A second
14278
+ // copy registers caveman_retrieve twice, which Pi treats as a fatal startup
14279
+ // error, so the session-only copy stays out.
14280
+ // Only when Pi will really load it: a Caveman-owned file, in the directory Pi
14281
+ // reads, with discovery left on. Otherwise the session copy is the only one.
14282
+ const owned = fileBytes(piNativeExtensionPath())?.toString("utf8").includes("caveman:native-pi");
14283
+ const discovery = !env.PI_CODING_AGENT_DIR && !cmdArgs.some((arg) => arg === "--no-extensions" || arg === "-ne");
14284
+ if (owned && discovery)
14285
+ return cmdArgs;
13779
14286
  // The profile's injection block declares the loader flag; using it here keeps the
13780
14287
  // compiled registry the single source of truth for how the asset is loaded.
13781
14288
  const profile = AGENTS.find((a) => a.id === "pi");
@@ -13846,6 +14353,36 @@ function stripMarkedBlock(text, begin, end) {
13846
14353
  }
13847
14354
  return { text: yamlText(kept), removed };
13848
14355
  }
14356
+ // A YAML stream may open with `%`-directives and a `---` marker, which is what
14357
+ // Hermes itself writes. Content must go AFTER them: a directive that follows
14358
+ // content opens a second document, and `yaml.safe_load` then fails with
14359
+ // "expected a single document in the stream" (#1405). Leading comments are
14360
+ // skipped too, so a header comment keeps describing the file.
14361
+ function yamlBodyStart(lines) {
14362
+ let i = 0;
14363
+ while (i < lines.length && (/^\s*(?:#.*)?$/.test(lines[i]) || /^%/.test(lines[i])))
14364
+ i++;
14365
+ if (i < lines.length && /^---(?:\s|$)/.test(lines[i]))
14366
+ i++;
14367
+ return i;
14368
+ }
14369
+ // Indent of the sequence items already under `lines[keyAt]`, so an inserted
14370
+ // entry joins its siblings instead of opening a deeper block. Hermes writes
14371
+ // two-space items; a fixed four-space insert into one of those lists is a
14372
+ // "expected <block end>, but found '-'" parse error (#1405). null when the
14373
+ // list is empty or the shape is not a plain block sequence.
14374
+ function yamlListItemIndent(lines, keyAt, end) {
14375
+ for (let i = keyAt + 1; i < end; i++) {
14376
+ const line = lines[i];
14377
+ if (/^\s*(?:#.*)?$/.test(line))
14378
+ continue;
14379
+ const item = line.match(/^(\s+)- /);
14380
+ if (item)
14381
+ return item[1].length;
14382
+ return null;
14383
+ }
14384
+ return null;
14385
+ }
13849
14386
  function topLevelSection(lines, key) {
13850
14387
  const start = lines.findIndex((line) => new RegExp(`^${key}:\\s*(?:#.*)?$`).test(line));
13851
14388
  if (start < 0)
@@ -13867,6 +14404,401 @@ function sectionHasChildKey(lines, section, key) {
13867
14404
  }
13868
14405
  return false;
13869
14406
  }
14407
+ // #1410: Hermes ownership used to be keyed on the literal comment-delimited
14408
+ // blocks we wrote into config.yaml. Any YAML round-trip — an editor, a config
14409
+ // manager, `yaml.safe_dump` — drops comments and renormalises quoting and
14410
+ // indentation without changing one value, and every check then read the install
14411
+ // as gone: `doctor hermes` said `degraded`, and `doctor --fix` and `disable`
14412
+ // both refused to touch it, so the user could not uninstall. Codex's branch
14413
+ // already compares by name and value for exactly this reason (its own rewrites
14414
+ // of the file must not read as drift); the readers below let Hermes do the same.
14415
+ //
14416
+ // Only the scalar shapes a normaliser emits are decoded. A flow collection, a
14417
+ // block scalar, an anchor, an alias or a tag returns null, and every caller
14418
+ // reads null as "cannot prove ownership" — so an unparsed shape keeps today's
14419
+ // refusal rather than guessing at a destructive restore.
14420
+ function decodeYamlDoubleQuoted(body) {
14421
+ const simple = {
14422
+ "0": "\0", a: "\x07", b: "\b", t: "\t", "\t": "\t", n: "\n", v: "\v", f: "\f",
14423
+ r: "\r", e: "\x1b", " ": " ", '"': '"', "/": "/", "\\": "\\",
14424
+ N: "\u0085", _: " ", L: "
", P: "
",
14425
+ };
14426
+ let out = "";
14427
+ for (let i = 0; i < body.length; i++) {
14428
+ const ch = body[i];
14429
+ if (ch !== "\\") {
14430
+ out += ch;
14431
+ continue;
14432
+ }
14433
+ const esc = body[++i];
14434
+ if (esc === undefined)
14435
+ return null;
14436
+ if (esc === "x" || esc === "u" || esc === "U") {
14437
+ const width = esc === "x" ? 2 : esc === "u" ? 4 : 8;
14438
+ const hex = body.slice(i + 1, i + 1 + width);
14439
+ if (hex.length !== width || !/^[0-9a-fA-F]+$/.test(hex))
14440
+ return null;
14441
+ const code = parseInt(hex, 16);
14442
+ if (code > 0x10ffff)
14443
+ return null;
14444
+ out += String.fromCodePoint(code);
14445
+ i += width;
14446
+ continue;
14447
+ }
14448
+ const mapped = simple[esc];
14449
+ if (mapped === undefined)
14450
+ return null;
14451
+ out += mapped;
14452
+ }
14453
+ return out;
14454
+ }
14455
+ // The scalar of `key:` at lines[index], as a YAML loader would read it, plus the
14456
+ // index of the last line it spans. A quoted scalar may be folded across lines:
14457
+ // a plain line break folds to one space, a `\` at end of line inside double
14458
+ // quotes joins with none — both are shapes PyYAML emits past its 80-column
14459
+ // width. `null` means "not a scalar this reader decodes".
14460
+ function yamlScalarAfterKey(lines, index) {
14461
+ const line = lines[index];
14462
+ if (line === undefined)
14463
+ return { value: null, last: index };
14464
+ const raw = line.slice(line.indexOf(":") + 1);
14465
+ const head = raw.replace(/^[ \t]+/, "");
14466
+ // An empty value is YAML's null. Kept as "" so a caller comparing it against
14467
+ // a journalled route simply finds no match (an empty endpoint is restorable,
14468
+ // never owned), without being mistaken for an unreadable shape.
14469
+ if (head === "" || /^#/.test(head))
14470
+ return { value: "", last: index };
14471
+ if (/^[[{|>&*!]/.test(head))
14472
+ return { value: null, last: index };
14473
+ const quote = head[0];
14474
+ if (quote !== '"' && quote !== "'") {
14475
+ let plain = head.replace(/\s+#.*$/, "").trimEnd();
14476
+ const keyIndent = line.length - line.replace(/^[ \t]*/, "").length;
14477
+ let row = index;
14478
+ // A long plain scalar is folded onto more-indented continuation lines, each
14479
+ // break folding to one space — what PyYAML emits past its 80-column width
14480
+ // for a value with spaces in it, such as an executable path. A plain scalar
14481
+ // cannot contain ": ", so a line that reads as a key or a sequence item is
14482
+ // the next node and ends this one.
14483
+ while (row + 1 < lines.length) {
14484
+ const next = lines[row + 1];
14485
+ if (/^\s*(?:#.*)?$/.test(next))
14486
+ break;
14487
+ if (next.length - next.replace(/^[ \t]*/, "").length <= keyIndent)
14488
+ break;
14489
+ const body = next.trim();
14490
+ if (/^-(?:\s|$)/.test(body) || /:(?:\s|$)/.test(body))
14491
+ break;
14492
+ plain = `${plain} ${body.replace(/\s+#.*$/, "").trimEnd()}`;
14493
+ row += 1;
14494
+ }
14495
+ return { value: plain, last: row };
14496
+ }
14497
+ let body = "";
14498
+ let segment = head.slice(1);
14499
+ let at = index;
14500
+ // Bounded: a scalar may not outrun the document.
14501
+ for (;;) {
14502
+ let closed = -1;
14503
+ for (let i = 0; i < segment.length; i++) {
14504
+ if (quote === '"' && segment[i] === "\\") {
14505
+ i++;
14506
+ continue;
14507
+ }
14508
+ if (segment[i] !== quote)
14509
+ continue;
14510
+ if (quote === "'" && segment[i + 1] === "'") {
14511
+ i++;
14512
+ continue;
14513
+ }
14514
+ closed = i;
14515
+ break;
14516
+ }
14517
+ if (closed >= 0) {
14518
+ body += segment.slice(0, closed);
14519
+ break;
14520
+ }
14521
+ if (quote === '"' && /\\$/.test(segment))
14522
+ body += segment.slice(0, -1);
14523
+ else
14524
+ body += `${segment.replace(/[ \t]+$/, "")}\n`;
14525
+ at += 1;
14526
+ if (at >= lines.length)
14527
+ return { value: null, last: index };
14528
+ segment = lines[at].replace(/^[ \t]+/, "");
14529
+ }
14530
+ // A raw newline can only be a fold marker added above: YAML folds it to one
14531
+ // space. Escape decoding runs after, so a `\n` ESCAPE stays a newline.
14532
+ const folded = body.replace(/\n/g, " ");
14533
+ if (quote === "'")
14534
+ return { value: folded.replace(/''/g, "'"), last: at };
14535
+ const decoded = decodeYamlDoubleQuoted(folded);
14536
+ return { value: decoded, last: decoded === null ? index : at };
14537
+ }
14538
+ // Direct children of a block mapping: `{ key → scalar }` at the shallowest
14539
+ // indent in the section, so a reindented document reads the same as the one we
14540
+ // wrote. `null` when a key repeats (a duplicate key is the ambiguous shape
14541
+ // #1410 asks us to keep refusing) or when a child is not a scalar this reader
14542
+ // decodes.
14543
+ function yamlMappingChildren(lines, start, end) {
14544
+ let indent = null;
14545
+ for (let i = start; i < end; i++) {
14546
+ const line = lines[i];
14547
+ if (/^\s*(?:#.*)?$/.test(line))
14548
+ continue;
14549
+ const width = line.length - line.replace(/^[ \t]*/, "").length;
14550
+ if (indent === null || width < indent)
14551
+ indent = width;
14552
+ }
14553
+ if (indent === null)
14554
+ return new Map();
14555
+ const children = new Map();
14556
+ const key = new RegExp(`^[ \\t]{${indent}}(["']?)([^:"'\\s][^:"']*)\\1\\s*:(?=\\s|$)`);
14557
+ for (let i = start; i < end; i++) {
14558
+ const line = lines[i];
14559
+ if (/^\s*(?:#.*)?$/.test(line))
14560
+ continue;
14561
+ const width = line.length - line.replace(/^[ \t]*/, "").length;
14562
+ if (width !== indent)
14563
+ continue;
14564
+ const match = key.exec(line);
14565
+ if (!match)
14566
+ continue;
14567
+ const name = match[2];
14568
+ if (children.has(name))
14569
+ return null;
14570
+ const scalar = yamlScalarAfterKey(lines, i);
14571
+ if (scalar.value === null)
14572
+ return null;
14573
+ children.set(name, scalar.value);
14574
+ i = scalar.last;
14575
+ }
14576
+ return children;
14577
+ }
14578
+ // Span of the direct child `name` inside [start, end): its own line through the
14579
+ // last line indented deeper than it.
14580
+ function yamlChildSpan(lines, start, end, name) {
14581
+ let indent = null;
14582
+ for (let i = start; i < end; i++) {
14583
+ const line = lines[i];
14584
+ if (/^\s*(?:#.*)?$/.test(line))
14585
+ continue;
14586
+ const width = line.length - line.replace(/^[ \t]*/, "").length;
14587
+ if (indent === null || width < indent)
14588
+ indent = width;
14589
+ }
14590
+ if (indent === null)
14591
+ return null;
14592
+ const key = new RegExp(`^[ \\t]{${indent}}(["']?)${escapeRegExp(name)}\\1\\s*:(?=\\s|$)`);
14593
+ for (let i = start; i < end; i++) {
14594
+ if (/^\s*(?:#.*)?$/.test(lines[i]))
14595
+ continue;
14596
+ if (!key.test(lines[i]))
14597
+ continue;
14598
+ let last = i;
14599
+ for (let j = i + 1; j < end; j++) {
14600
+ const line = lines[j];
14601
+ if (/^\s*(?:#.*)?$/.test(line))
14602
+ continue;
14603
+ const width = line.length - line.replace(/^[ \t]*/, "").length;
14604
+ if (width <= indent)
14605
+ break;
14606
+ // A child's quoted scalar may be folded onto continuation lines, and one
14607
+ // of those can begin with `#`. Reading the value keeps those lines
14608
+ // attributed to their key; skipping them as comments left them outside
14609
+ // the span, so removing the block spliced out everything around an
14610
+ // orphaned fragment and produced a config that no longer parses.
14611
+ const scalar = /:(?:\s|$)/.test(line) ? yamlScalarAfterKey(lines, j) : null;
14612
+ last = scalar ? Math.max(j, scalar.last) : j;
14613
+ if (scalar)
14614
+ j = last;
14615
+ }
14616
+ return { start: i, end: last + 1 };
14617
+ }
14618
+ return null;
14619
+ }
14620
+ // What a Hermes config.yaml actually SAYS about the settings Caveman owns,
14621
+ // independent of how it is laid out. `model` and the `caveman-native` MCP entry
14622
+ // are read as values; plugin membership has its own layout-independent reader
14623
+ // in hermesPluginListContains.
14624
+ function hermesOwnedValues(text) {
14625
+ const lines = yamlLines(text);
14626
+ const model = topLevelSection(lines, "model");
14627
+ const servers = topLevelSection(lines, "mcp_servers");
14628
+ const native = servers ? yamlChildSpan(lines, servers.start + 1, servers.end, HERMES_NATIVE_MCP_SERVER) : null;
14629
+ return {
14630
+ model: model ? yamlMappingChildren(lines, model.start + 1, model.end) : null,
14631
+ mcp: native ? yamlMappingChildren(lines, native.start + 1, native.end) : null,
14632
+ };
14633
+ }
14634
+ // The `command` the journalled MCP block registered, read back out of the block
14635
+ // itself so no journal format change is needed: an install made before this fix
14636
+ // is checked by value too.
14637
+ function hermesJournaledMcpCommand(block) {
14638
+ const lines = yamlLines(block);
14639
+ for (let i = 0; i < lines.length; i++) {
14640
+ if (!/^\s*command\s*:/.test(lines[i]))
14641
+ continue;
14642
+ return yamlScalarAfterKey(lines, i).value;
14643
+ }
14644
+ return null;
14645
+ }
14646
+ // Does this config still carry Caveman's own Hermes routing, by value?
14647
+ function hermesRouteOwned(text, owned) {
14648
+ const route = owned?.route;
14649
+ if (typeof route !== "string")
14650
+ return false;
14651
+ // Journals written before #1391 carry no provider; those installs wrote the
14652
+ // generic one, which is what the enable path recorded from then on.
14653
+ const provider = typeof owned?.provider === "string" ? owned.provider : "custom";
14654
+ const values = hermesOwnedValues(text).model;
14655
+ return values?.get("base_url") === route && values.get("provider") === provider;
14656
+ }
14657
+ // Is the journalled `caveman-native` MCP server still registered, by value? A
14658
+ // null block means the user's own entry was already there, which disable never
14659
+ // owned and so never has to prove.
14660
+ function hermesMcpOwned(text, owned) {
14661
+ const block = owned?.mcp_block;
14662
+ if (block === null)
14663
+ return true;
14664
+ if (typeof block !== "string")
14665
+ return false;
14666
+ if (text.includes(block))
14667
+ return true;
14668
+ const command = hermesJournaledMcpCommand(block);
14669
+ if (command === null)
14670
+ return false;
14671
+ const values = hermesOwnedValues(text).mcp;
14672
+ return values?.get("command") === command && values.get("enabled") === "true";
14673
+ }
14674
+ // Is the journalled `caveman_native` plugin still enabled? Same null rule.
14675
+ //
14676
+ // This asks whether OUR entry is still in plugins.enabled, which is a different
14677
+ // question from whether Hermes would load the plugin: a user who ALSO lists the
14678
+ // name under plugins.disabled has not taken our entry away, and disable still
14679
+ // has to reverse it. So this reads the enabled list directly rather than going
14680
+ // through hermesNamedPluginMembership, whose disabled-first precedence answers
14681
+ // the load question. It inherits the exact-scalar, plugins-scoped matching
14682
+ // either way, so a `caveman_native_extra` entry no longer passes for ours.
14683
+ function hermesPluginOwned(text, owned) {
14684
+ const block = owned?.plugin_block;
14685
+ if (block === null)
14686
+ return true;
14687
+ if (typeof block !== "string")
14688
+ return false;
14689
+ return hermesPluginListContains(text, "enabled", HERMES_NATIVE_PLUGIN_NAME);
14690
+ }
14691
+ // Indent shared by the direct children of [start, end), or null when there are
14692
+ // none — the width an inserted sibling has to take in THIS document.
14693
+ function yamlChildIndent(lines, start, end) {
14694
+ let indent = null;
14695
+ for (let i = start; i < end; i++) {
14696
+ const line = lines[i];
14697
+ if (/^\s*(?:#.*)?$/.test(line))
14698
+ continue;
14699
+ const width = line.length - line.replace(/^[ \t]*/, "").length;
14700
+ if (indent === null || width < indent)
14701
+ indent = width;
14702
+ }
14703
+ return indent;
14704
+ }
14705
+ // Undo Caveman's Hermes settings on a document whose layout no longer matches
14706
+ // the journalled blocks (#1410). Only ever reached once hermesRouteOwned,
14707
+ // hermesPluginOwned and hermesMcpOwned have all proved, by value, that what is
14708
+ // in the file is still ours — so this removes Caveman's own settings and leaves
14709
+ // every unrelated sibling, comment and key where it is. Each removal mirrors
14710
+ // the shape of the block that was written: an entry we added to a list the user
14711
+ // already had takes the list with it only if we created the list too.
14712
+ function hermesRestoreOwnedByValue(text, owned) {
14713
+ const lines = yamlLines(text);
14714
+ const previous = (Array.isArray(owned?.previous_route_lines) ? owned.previous_route_lines : [])
14715
+ .filter((line) => typeof line === "string");
14716
+ // --- routing: our provider/base_url go, the user's come back ---
14717
+ const model = topLevelSection(lines, "model");
14718
+ if (!model)
14719
+ throw new Error("Hermes model section is gone; refusing destructive disable");
14720
+ const modelIndent = yamlChildIndent(lines, model.start + 1, model.end);
14721
+ if (modelIndent === null)
14722
+ throw new Error("Hermes model section is empty; refusing destructive disable");
14723
+ const ownedRouteRows = [];
14724
+ for (let i = model.start + 1; i < model.end; i++) {
14725
+ const line = lines[i];
14726
+ if (/^\s*(?:#.*)?$/.test(line))
14727
+ continue;
14728
+ const width = line.length - line.replace(/^[ \t]*/, "").length;
14729
+ if (width !== modelIndent)
14730
+ continue;
14731
+ if (!new RegExp(`^[ \\t]{${modelIndent}}(["']?)(provider|base_url)\\1\\s*:(?=\\s|$)`).test(line))
14732
+ continue;
14733
+ const scalar = yamlScalarAfterKey(lines, i);
14734
+ for (let row = i; row <= scalar.last; row++)
14735
+ ownedRouteRows.push(row);
14736
+ i = scalar.last;
14737
+ }
14738
+ if (ownedRouteRows.length === 0)
14739
+ throw new Error("Hermes routing keys are gone; refusing destructive disable");
14740
+ const pad = " ".repeat(modelIndent);
14741
+ const restoredRoute = previous.map((line) => {
14742
+ const parsed = /^\s*(["']?)([^:"']+)\1\s*:([\s\S]*)$/.exec(line);
14743
+ if (!parsed)
14744
+ throw new Error("Hermes integration journal holds an unreadable previous routing line");
14745
+ return `${pad}${parsed[2]}:${parsed[3]}`;
14746
+ });
14747
+ const insertAt = ownedRouteRows[0];
14748
+ for (const row of [...ownedRouteRows].reverse())
14749
+ lines.splice(row, 1);
14750
+ lines.splice(insertAt, 0, ...restoredRoute);
14751
+ // --- plugin membership ---
14752
+ const pluginBlock = owned?.plugin_block;
14753
+ if (typeof pluginBlock === "string") {
14754
+ const createdSection = /^plugins:/m.test(pluginBlock);
14755
+ const createdEnabled = createdSection || /^\s+enabled:/m.test(pluginBlock);
14756
+ const plugins = topLevelSection(lines, "plugins");
14757
+ if (!plugins)
14758
+ throw new Error("Hermes plugins section is gone; refusing destructive disable");
14759
+ let enabledAt = -1;
14760
+ for (let i = plugins.start + 1; i < plugins.end; i++) {
14761
+ if (/^\s+enabled\s*:(?=\s|$)/.test(lines[i])) {
14762
+ enabledAt = i;
14763
+ break;
14764
+ }
14765
+ }
14766
+ if (enabledAt < 0)
14767
+ throw new Error("Hermes plugins.enabled is gone; refusing destructive disable");
14768
+ let itemAt = -1;
14769
+ for (let i = enabledAt + 1; i < plugins.end; i++) {
14770
+ if (new RegExp(`^\\s*-\\s*(["']?)${escapeRegExp(HERMES_NATIVE_PLUGIN_NAME)}\\1\\s*(?:#.*)?$`).test(lines[i])) {
14771
+ itemAt = i;
14772
+ break;
14773
+ }
14774
+ }
14775
+ if (itemAt < 0)
14776
+ throw new Error("Hermes plugin entry is gone; refusing destructive disable");
14777
+ lines.splice(itemAt, 1);
14778
+ if (createdEnabled)
14779
+ lines.splice(enabledAt, 1);
14780
+ if (createdSection)
14781
+ lines.splice(plugins.start, 1);
14782
+ }
14783
+ // --- MCP registration ---
14784
+ const mcpBlock = owned?.mcp_block;
14785
+ if (typeof mcpBlock === "string") {
14786
+ const createdSection = /^mcp_servers:/m.test(mcpBlock);
14787
+ const servers = topLevelSection(lines, "mcp_servers");
14788
+ if (!servers)
14789
+ throw new Error("Hermes mcp_servers section is gone; refusing destructive disable");
14790
+ const native = yamlChildSpan(lines, servers.start + 1, servers.end, HERMES_NATIVE_MCP_SERVER);
14791
+ if (!native)
14792
+ throw new Error("Hermes MCP entry is gone; refusing destructive disable");
14793
+ lines.splice(native.start, native.end - native.start);
14794
+ if (createdSection)
14795
+ lines.splice(servers.start, 1);
14796
+ }
14797
+ // yamlText joins with \n. The literal path edits the raw string and so keeps
14798
+ // whatever the file used; this one must not quietly convert a Windows user's
14799
+ // config to LF on the way out.
14800
+ return text.includes("\r\n") ? yamlText(lines).replace(/\n/g, "\r\n") : yamlText(lines);
14801
+ }
13870
14802
  function hermesMcpMarkers(serverName) {
13871
14803
  return serverName === "caveman"
13872
14804
  ? { begin: HERMES_MCP_BEGIN, end: HERMES_MCP_END }
@@ -16662,13 +17594,15 @@ function shouldShrink(command) {
16662
17594
  return false;
16663
17595
  return SHRINK_ALLOW.has(first);
16664
17596
  }
16665
- // cavemanBinForHook is the invocation a Claude hook uses to call back into this
16666
- // CLI, robust to PATH: a resolved `caveman`/`cave`, else this very script's node.
16667
- function cavemanBinForHook(powershell = process.platform === "win32") {
17597
+ // cavemanHookTarget resolves what a hook runs to call back into this CLI, robust
17598
+ // to PATH: a resolved `caveman`/`cave`, else this very script's node. Rendering it
17599
+ // into a command string is the caller's job, because the two callers target
17600
+ // different shells (see hookExecutableInvocation vs hostShellInvocation).
17601
+ function cavemanHookTarget() {
16668
17602
  // Never a package runner's cached copy when a lasting one exists.
16669
17603
  const command = durableCaveman() ?? which("caveman") ?? which("cave");
16670
17604
  if (!command)
16671
- return hookExecutableInvocation(stableNodePath(), process.argv[1], process.platform, powershell);
17605
+ return { executable: stableNodePath(), script: process.argv[1] };
16672
17606
  // npm links `caveman` to a `#!/usr/bin/env node` script, and a host started
16673
17607
  // from a GUI or launchd often has no node on PATH (nvm, volta, Homebrew):
16674
17608
  // run it with this node, named as the lifecycle hooks name theirs (`--node`)
@@ -16679,9 +17613,20 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
16679
17613
  script = hookCommandBasename(process.execPath) === "node" && /\.[cm]?js$/.test(realpathSync(command));
16680
17614
  }
16681
17615
  catch { /* unresolvable: run it as found */ }
16682
- return script
16683
- ? hookExecutableInvocation(stableNodePath(), command, process.platform, powershell)
16684
- : hookExecutableInvocation(command, undefined, process.platform, powershell);
17616
+ return script ? { executable: stableNodePath(), script: command } : { executable: command };
17617
+ }
17618
+ // cavemanBinForHook is that invocation as the HOST will dispatch it — on native
17619
+ // Windows the hosts run command hooks through PowerShell, which needs `&`.
17620
+ function cavemanBinForHook(powershell = process.platform === "win32") {
17621
+ const target = cavemanHookTarget();
17622
+ return hookExecutableInvocation(target.executable, target.script, process.platform, powershell);
17623
+ }
17624
+ // cavemanBinForHostShell is that invocation for the host's OWN shell, which we do
17625
+ // not know. null = no portable form; the caller must decline rather than emit a
17626
+ // command one of the three Windows shells cannot parse (#1263).
17627
+ function cavemanBinForHostShell() {
17628
+ const target = cavemanHookTarget();
17629
+ return hostShellInvocation(target.executable, target.script, process.platform);
16685
17630
  }
16686
17631
  // shrinkHook is the settings-hook callback for the agents whose harness can
16687
17632
  // deterministically rewrite a shell command before it runs: Claude Code (PreToolUse,
@@ -16727,9 +17672,16 @@ async function shrinkHook() {
16727
17672
  const command = evt.tool_input?.command;
16728
17673
  if (typeof command !== "string" || !shouldShrink(command))
16729
17674
  process.exit(0);
16730
- // updatedInput.command executes in host shell (Git Bash on Claude Windows),
16731
- // not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
16732
- const rewritten = `${cavemanBinForHook(false)} shrink -- ${command.trim()}`;
17675
+ // updatedInput.command executes in the host's own shell — Git Bash under Claude
17676
+ // Code on Windows, PowerShell under the opencode plugin, cmd.exe under Gemini —
17677
+ // never the hook's explicit PowerShell shell, so this prefix is rendered bare
17678
+ // rather than quoted or `&`-prefixed. When no form serves all three (a space in
17679
+ // the path), there is no rewrite: the command runs as the host sent it, which is
17680
+ // the same safe direction as every other decline above.
17681
+ const prefix = cavemanBinForHostShell();
17682
+ if (!prefix)
17683
+ process.exit(0);
17684
+ const rewritten = `${prefix} shrink -- ${command.trim()}`;
16733
17685
  // Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
16734
17686
  // Claude REPLACES via hookSpecificOutput.updatedInput (camelCase + hookEventName).
16735
17687
  // Because Claude replaces, updatedInput must carry every field the host sent —
@@ -17461,7 +18413,8 @@ async function nativeHook(argv) {
17461
18413
  confirmLearnNudge(learnNudgeToken);
17462
18414
  });
17463
18415
  }
17464
- else if (normalizedEvent === "PostCompact" && agent !== "hermes" && compactContext) {
18416
+ else if (normalizedEvent === "PostCompact" && agent !== "hermes" && agent !== "codex" && compactContext) {
18417
+ // Codex PostCompact accepts only common fields; SessionStart source=compact restores Core.
17465
18418
  process.stdout.write(JSON.stringify({
17466
18419
  hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: compactContext },
17467
18420
  }));
@@ -18087,7 +19040,25 @@ export function generatedPluginInvocation(onPath, currentScript, platform = proc
18087
19040
  function cavemanInvocation() {
18088
19041
  return generatedPluginInvocation(durableCaveman() ?? which("caveman") ?? which("cave") ?? undefined, process.argv[1] ?? "");
18089
19042
  }
19043
+ // OpenCode 2 replaced the plugin API: its loader requires a default export
19044
+ // `{ id, setup | effect }` and REJECTS a bare V1 hook map with
19045
+ // "Plugin must export a default definition with an id and an effect or setup
19046
+ // function". A V1-only shrink plugin therefore never loaded on an OpenCode 2
19047
+ // host while the installer still reported the hook installed (#1445).
19048
+ //
19049
+ // `caveman enable opencode` already answers this for the native plugin; the
19050
+ // shrink plugin shares that one decision (opencodePluginMajors) so the two
19051
+ // generated files can never disagree about which API the host speaks.
18090
19052
  function opencodePluginSource() {
19053
+ const majors = opencodePluginMajors();
19054
+ if (majors.length !== 1)
19055
+ return opencodeShrinkPluginSourceBoth();
19056
+ return majors[0] < 2 ? opencodeShrinkPluginSourceV1() : opencodeShrinkPluginSourceV2();
19057
+ }
19058
+ // The shared preamble: the marker, and one `rewrite()` both APIs call. Keeping
19059
+ // the subprocess in a single helper is what lets the "both" file carry two hook
19060
+ // shapes without two copies of the byte-safety contract.
19061
+ function opencodeShrinkPluginPreamble() {
18091
19062
  const { cmd, pre } = cavemanInvocation();
18092
19063
  const argv = JSON.stringify([...pre, "shrink-hook"]);
18093
19064
  return `// caveman:shrink-plugin — GENERATED by \`caveman hooks install opencode\`.
@@ -18095,26 +19066,71 @@ function opencodePluginSource() {
18095
19066
  // with \`caveman retrieve\`). Remove with \`caveman hooks uninstall opencode\`.
18096
19067
  import { execFileSync } from "node:child_process";
18097
19068
 
19069
+ // Returns the rewritten command, or undefined to leave the original alone.
19070
+ function rewrite(command) {
19071
+ if (typeof command !== "string" || !command.trim()) return undefined;
19072
+ try {
19073
+ const res = execFileSync(${JSON.stringify(cmd)}, ${argv}, {
19074
+ input: JSON.stringify({ tool_name: "Bash", tool_input: { command } }),
19075
+ encoding: "utf8",
19076
+ windowsHide: true,
19077
+ });
19078
+ if (!res) return undefined;
19079
+ const rewritten = JSON.parse(res)?.hookSpecificOutput?.updatedInput?.command;
19080
+ return typeof rewritten === "string" && rewritten ? rewritten : undefined;
19081
+ } catch {
19082
+ // byte-safe: any failure leaves the original command untouched.
19083
+ return undefined;
19084
+ }
19085
+ }
19086
+ `;
19087
+ }
19088
+ // V1: a named factory returning a hook map, mutating output.args.command.
19089
+ function opencodeShrinkPluginHookMapV1() {
19090
+ return `
18098
19091
  export const CavemanShrink = async () => ({
18099
19092
  "tool.execute.before": async (input, output) => {
18100
19093
  if (input?.tool !== "bash") return;
18101
- const command = output?.args?.command;
18102
- if (typeof command !== "string" || !command.trim()) return;
18103
- try {
18104
- const res = execFileSync(${JSON.stringify(cmd)}, ${argv}, {
18105
- input: JSON.stringify({ tool_name: "Bash", tool_input: { command } }),
18106
- encoding: "utf8",
18107
- });
18108
- if (!res) return;
18109
- const rewritten = JSON.parse(res)?.hookSpecificOutput?.updatedInput?.command;
18110
- if (typeof rewritten === "string" && rewritten) output.args.command = rewritten;
18111
- } catch {
18112
- // byte-safe: any failure leaves the original command untouched.
18113
- }
19094
+ const next = rewrite(output?.args?.command);
19095
+ if (next) output.args.command = next;
18114
19096
  },
18115
19097
  });
18116
19098
  `;
18117
19099
  }
19100
+ // V2: default { id, setup }, registering through ctx.tool.hook and mutating
19101
+ // event.input.command. V1 named this tool "bash"; V2 renamed the permission
19102
+ // action to "shell" — accept both, as the native V2 plugin does.
19103
+ function opencodeShrinkPluginDefinitionV2(extra = "") {
19104
+ return `
19105
+ export default {
19106
+ id: "caveman-shrink",
19107
+ ${extra} async setup(ctx) {
19108
+ // A 1.x host also calls setup, with a context that has no tool hook API.
19109
+ if (!ctx?.tool?.hook) return;
19110
+ await ctx.tool.hook("execute.before", (event) => {
19111
+ if (event?.tool !== "bash" && event?.tool !== "shell") return;
19112
+ const input = event.input;
19113
+ if (!input || typeof input !== "object") return;
19114
+ const next = rewrite(input.command);
19115
+ if (next) input.command = next;
19116
+ });
19117
+ },
19118
+ };
19119
+ `;
19120
+ }
19121
+ function opencodeShrinkPluginSourceV1() {
19122
+ return `${opencodeShrinkPluginPreamble()}${opencodeShrinkPluginHookMapV1()}`;
19123
+ }
19124
+ function opencodeShrinkPluginSourceV2() {
19125
+ return `${opencodeShrinkPluginPreamble()}${opencodeShrinkPluginDefinitionV2()}`;
19126
+ }
19127
+ // An unreadable version is evidence of neither major, and two installed majors
19128
+ // share this one plugins directory, so both get the single file each host can
19129
+ // load: the V1 map behind `default.server` for OpenCode 1.4+, and the V2
19130
+ // { id, setup } beside it. Same rule, same reason as the native plugin (#1316).
19131
+ function opencodeShrinkPluginSourceBoth() {
19132
+ return `${opencodeShrinkPluginPreamble()}${opencodeShrinkPluginHookMapV1()}${opencodeShrinkPluginDefinitionV2(" server: CavemanShrink,\n")}`;
19133
+ }
18118
19134
  function installShrinkPluginOpencode() {
18119
19135
  const path = opencodePluginPath();
18120
19136
  try {
@@ -18174,6 +19190,11 @@ import subprocess
18174
19190
 
18175
19191
  _CAVEMAN_CMD = ${JSON.stringify(cmd)}
18176
19192
  _CAVEMAN_PRE = ${JSON.stringify(pre)}
19193
+ # A Hermes host with no console of its own makes Windows give every console
19194
+ # child a NEW console window, so the user sees one flash per hook call.
19195
+ # subprocess ignores Node's windowsHide, and CREATE_NO_WINDOW is absent off
19196
+ # Windows, so resolve it at run time and pass 0 everywhere else (#1214).
19197
+ _CAVEMAN_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
18177
19198
 
18178
19199
 
18179
19200
  def _argv(*tail):
@@ -18198,6 +19219,7 @@ def _eligible(command):
18198
19219
  text=True,
18199
19220
  capture_output=True,
18200
19221
  timeout=10,
19222
+ creationflags=_CAVEMAN_NO_WINDOW,
18201
19223
  )
18202
19224
  return proc.returncode == 0 and bool((proc.stdout or "").strip())
18203
19225
  except Exception:
@@ -18221,6 +19243,7 @@ def _transform_terminal_output(command=None, output=None, **kwargs):
18221
19243
  text=True,
18222
19244
  capture_output=True,
18223
19245
  timeout=_int_env("CAVE_HERMES_SHRINK_TIMEOUT_SECONDS", 60),
19246
+ creationflags=_CAVEMAN_NO_WINDOW,
18224
19247
  )
18225
19248
  if proc.returncode != 0 or not proc.stdout:
18226
19249
  return None
@@ -18234,13 +19257,152 @@ def register(ctx):
18234
19257
  # <<< caveman:shrink-plugin
18235
19258
  `;
18236
19259
  }
18237
- function hermesNamedPluginEnabled(text, name) {
18238
- const escaped = escapeRegExp(name);
18239
- return new RegExp(`(^|\\n)\\s*-\\s*["']?${escaped}["']?\\s*(?:#.*)?(?=\\n|$)`).test(text)
18240
- || new RegExp(`enabled:\\s*\\[[^\\]]*["']?${escaped}["']?`).test(text);
19260
+ function hermesFlowSequenceItems(raw) {
19261
+ const start = raw.indexOf("[");
19262
+ if (start < 0)
19263
+ return null;
19264
+ const items = [];
19265
+ let item = "";
19266
+ let quote = null;
19267
+ let escaped = false;
19268
+ let depth = 0;
19269
+ for (let i = start + 1; i < raw.length; i++) {
19270
+ const char = raw[i];
19271
+ if (quote) {
19272
+ if (quote === "'" && char === "'" && raw[i + 1] === "'") {
19273
+ item += "''";
19274
+ i++;
19275
+ continue;
19276
+ }
19277
+ item += char;
19278
+ if (quote === '"' && escaped) {
19279
+ escaped = false;
19280
+ continue;
19281
+ }
19282
+ if (quote === '"' && char === "\\") {
19283
+ escaped = true;
19284
+ continue;
19285
+ }
19286
+ if (char === quote)
19287
+ quote = null;
19288
+ continue;
19289
+ }
19290
+ if (char === "#" && (i === start + 1 || /\s/.test(raw[i - 1]))) {
19291
+ while (i < raw.length && raw[i] !== "\n")
19292
+ i++;
19293
+ continue;
19294
+ }
19295
+ if (char === "'" || char === '"') {
19296
+ quote = char;
19297
+ item += char;
19298
+ continue;
19299
+ }
19300
+ if (char === "[" || char === "{") {
19301
+ depth++;
19302
+ item += char;
19303
+ continue;
19304
+ }
19305
+ if (char === "]") {
19306
+ if (depth === 0) {
19307
+ items.push(item);
19308
+ return items.map(configValue).filter((value) => value !== undefined);
19309
+ }
19310
+ depth--;
19311
+ item += char;
19312
+ continue;
19313
+ }
19314
+ if (char === "}" && depth > 0) {
19315
+ depth--;
19316
+ item += char;
19317
+ continue;
19318
+ }
19319
+ if (char === "," && depth === 0) {
19320
+ items.push(item);
19321
+ item = "";
19322
+ continue;
19323
+ }
19324
+ item += char;
19325
+ }
19326
+ return null;
18241
19327
  }
18242
- function hermesPluginEnabled(text) {
18243
- return hermesNamedPluginEnabled(text, HERMES_PLUGIN_NAME);
19328
+ function hermesPluginListContains(text, listName, name) {
19329
+ const lines = yamlLines(text);
19330
+ const plugins = topLevelSection(lines, "plugins");
19331
+ if (!plugins)
19332
+ return false;
19333
+ for (let i = plugins.start + 1; i < plugins.end; i++) {
19334
+ const match = lines[i].match(/^ (enabled|disabled):(?:\s*(.*))?$/);
19335
+ if (!match || match[1] !== listName)
19336
+ continue;
19337
+ const raw = (match[2] ?? "").replace(/\s+#.*$/, "").trim();
19338
+ if (raw.startsWith("[")) {
19339
+ let flow = raw;
19340
+ let items = hermesFlowSequenceItems(flow);
19341
+ for (let next = i + 1; items === null && next < plugins.end; next++) {
19342
+ flow += `\n${lines[next]}`;
19343
+ items = hermesFlowSequenceItems(flow);
19344
+ }
19345
+ return items?.includes(name) ?? false;
19346
+ }
19347
+ if (raw && !raw.startsWith("#"))
19348
+ return false;
19349
+ let sequenceIndent = null;
19350
+ for (let next = i + 1; next < plugins.end; next++) {
19351
+ const line = lines[next];
19352
+ if (/^ [A-Za-z0-9_-]+:\s*/.test(line))
19353
+ break;
19354
+ if (!line.trim() || /^\s*#/.test(line))
19355
+ continue;
19356
+ const item = line.match(/^(\s*)-\s*(.*?)\s*$/);
19357
+ if (!item) {
19358
+ if (sequenceIndent !== null && line.search(/\S/) > sequenceIndent)
19359
+ continue;
19360
+ break;
19361
+ }
19362
+ const indent = item[1].length;
19363
+ if (sequenceIndent === null)
19364
+ sequenceIndent = indent;
19365
+ if (indent === sequenceIndent && configValue(item[2]) === name)
19366
+ return true;
19367
+ }
19368
+ return false;
19369
+ }
19370
+ return false;
19371
+ }
19372
+ function hermesNamedPluginMembership(text, name) {
19373
+ if (hermesPluginListContains(text, "disabled", name))
19374
+ return "disabled";
19375
+ if (hermesPluginListContains(text, "enabled", name))
19376
+ return "enabled";
19377
+ return "not-enabled";
19378
+ }
19379
+ function hermesEnabledListIsInline(text) {
19380
+ const lines = yamlLines(text);
19381
+ const plugins = topLevelSection(lines, "plugins");
19382
+ return Boolean(plugins && lines.slice(plugins.start + 1, plugins.end).some((line) => /^ enabled:\s*\[/.test(line)));
19383
+ }
19384
+ function hermesPluginInstallConfigReady() {
19385
+ const path = hermesConfigPath();
19386
+ let existing = "";
19387
+ try {
19388
+ existing = readFileSync(path, "utf8");
19389
+ }
19390
+ catch (error) {
19391
+ if (error.code !== "ENOENT") {
19392
+ console.error(`${mark("warn")} cannot read ${path}: ${error.message}`);
19393
+ return false;
19394
+ }
19395
+ }
19396
+ const membership = hermesNamedPluginMembership(existing, HERMES_PLUGIN_NAME);
19397
+ if (membership === "disabled") {
19398
+ console.error(`${mark("warn")} ${path} explicitly disables ${HERMES_PLUGIN_NAME} in plugins.disabled; no hook was installed`);
19399
+ return false;
19400
+ }
19401
+ if (membership !== "enabled" && hermesEnabledListIsInline(existing)) {
19402
+ console.error(`${mark("warn")} ${path} uses inline plugins.enabled; refusing to claim the Hermes plugin is installed`);
19403
+ return false;
19404
+ }
19405
+ return true;
18244
19406
  }
18245
19407
  function enableHermesPluginInConfig() {
18246
19408
  const path = hermesConfigPath();
@@ -18254,7 +19416,12 @@ function enableHermesPluginInConfig() {
18254
19416
  return false;
18255
19417
  }
18256
19418
  }
18257
- if (hermesPluginEnabled(existing))
19419
+ const membership = hermesNamedPluginMembership(existing, HERMES_PLUGIN_NAME);
19420
+ if (membership === "disabled") {
19421
+ console.error(`${mark("warn")} ${path} explicitly disables ${HERMES_PLUGIN_NAME} in plugins.disabled; remove that entry before installing`);
19422
+ return false;
19423
+ }
19424
+ if (membership === "enabled")
18258
19425
  return true;
18259
19426
  const stripped = stripMarkedBlock(existing, HERMES_PLUGIN_ENABLE_BEGIN, HERMES_PLUGIN_ENABLE_END).text;
18260
19427
  const lines = yamlLines(stripped);
@@ -18279,7 +19446,10 @@ function enableHermesPluginInConfig() {
18279
19446
  return false;
18280
19447
  }
18281
19448
  if (enabledLine >= 0) {
18282
- lines.splice(enabledLine + 1, 0, ` ${HERMES_PLUGIN_ENABLE_BEGIN}`, ` - ${HERMES_PLUGIN_NAME}`, ` ${HERMES_PLUGIN_ENABLE_END}`);
19449
+ // Same sibling-indent rule as hermesNativeConfig: a fixed four-space
19450
+ // entry in a two-space list is a parse error (#1405).
19451
+ const pad = " ".repeat(yamlListItemIndent(lines, enabledLine, plugins.end) ?? 4);
19452
+ lines.splice(enabledLine + 1, 0, `${pad}${HERMES_PLUGIN_ENABLE_BEGIN}`, `${pad}- ${HERMES_PLUGIN_NAME}`, `${pad}${HERMES_PLUGIN_ENABLE_END}`);
18283
19453
  }
18284
19454
  else {
18285
19455
  lines.splice(plugins.start + 1, 0, ` ${HERMES_PLUGIN_ENABLE_BEGIN}`, " enabled:", ` - ${HERMES_PLUGIN_NAME}`, ` ${HERMES_PLUGIN_ENABLE_END}`);
@@ -18356,6 +19526,8 @@ function disableHermesPluginInConfig() {
18356
19526
  }
18357
19527
  }
18358
19528
  function installShrinkPluginHermes() {
19529
+ if (!hermesPluginInstallConfigReady())
19530
+ return false;
18359
19531
  try {
18360
19532
  mkdirSync(hermesPluginDir(), { recursive: true });
18361
19533
  writeFileSync(hermesPluginManifestPath(), hermesPluginManifestSource());
@@ -18367,6 +19539,7 @@ function installShrinkPluginHermes() {
18367
19539
  }
18368
19540
  if (!enableHermesPluginInConfig()) {
18369
19541
  process.stderr.write(`${mark("warn")} Hermes plugin written to ${hermesPluginDir()}, but plugins.enabled was not updated; run ${cyan(`hermes plugins enable ${HERMES_PLUGIN_NAME}`)}\n`);
19542
+ return false;
18370
19543
  }
18371
19544
  return true;
18372
19545
  }
@@ -18720,6 +19893,11 @@ function evalsRun(argv = []) {
18720
19893
  // stats prints the local spend summary by delegating to the proxy binary, which
18721
19894
  // owns the ~/.caveman/ SQLite store. The CLI carries no database dependency, so
18722
19895
  // it reads through the same Go binary `caveman start` launches.
19896
+ // The report reads every request row in its window; CAVE_STATS_TIMEOUT_MS
19897
+ // overrides the 60s it may take.
19898
+ function statsTimeoutMs() {
19899
+ return Number(process.env.CAVE_STATS_TIMEOUT_MS) || 60_000;
19900
+ }
18723
19901
  function stats(argv = []) {
18724
19902
  if (argv.length === 1 && ["--help", "-h", "help"].includes(argv[0])) {
18725
19903
  process.stdout.write(STATS_HELP);
@@ -18740,7 +19918,7 @@ function stats(argv = []) {
18740
19918
  args.push("--write-report");
18741
19919
  if (options.out)
18742
19920
  args.push("--out", resolve(options.out));
18743
- const out = execFileSync(bin, args, { encoding: "utf8", timeout: 60_000, maxBuffer: 32 * 1024 * 1024 });
19921
+ const out = execFileSync(bin, args, { encoding: "utf8", timeout: statsTimeoutMs(), maxBuffer: 32 * 1024 * 1024 });
18744
19922
  const report = JSON.parse(out);
18745
19923
  // Older companion binaries ignore --report. Keep their measurements
18746
19924
  // readable, but never pretend they generated the new accounting report.
@@ -18762,6 +19940,17 @@ function stats(argv = []) {
18762
19940
  }
18763
19941
  }
18764
19942
  catch (error) {
19943
+ // A report that ran out of time says so, with the size it had to read
19944
+ // and the narrower window that reads less (#1371).
19945
+ if (error.code === "ETIMEDOUT") {
19946
+ let size = "";
19947
+ try {
19948
+ size = ` (${Math.round(statSync(join(cavemanHome(), "caveman.db")).size / 1048576)} MB)`;
19949
+ }
19950
+ catch { /* no local store */ }
19951
+ console.error(`caveman stats timed out after ${Math.round(statsTimeoutMs() / 1000)}s reading the local stats database${size}. Try a shorter window: caveman stats --days 7`);
19952
+ process.exit(1);
19953
+ }
18765
19954
  console.error(`failed to read stats via ${bin}: ${error.message}`);
18766
19955
  process.exit(1);
18767
19956
  }
@@ -18948,7 +20137,7 @@ async function trial(rest) {
18948
20137
  // older proxies omit it and always scanned 30d).
18949
20138
  function learnEmpty(plan) {
18950
20139
  const since = learnSince(plan.window?.since || "30d");
18951
- return `no Claude Code, Codex, Gemini CLI, opencode or aider sessions found in the last ${since}. A score needs the same text repeated in at least 3 sessions. Use your agent a few times (for example \`caveman claude\`), then run \`caveman learn\` again`;
20140
+ return `no Claude Code, Codex, Gemini CLI, opencode, aider or Pi sessions found in the last ${since}. A score needs the same text repeated in at least 3 sessions. Use your agent a few times (for example \`caveman claude\`), then run \`caveman learn\` again`;
18952
20141
  }
18953
20142
  // learnNoScoreYet explains why there is no score: the score needs the same
18954
20143
  // text repeated in at least 3 sessions.
@@ -19140,6 +20329,7 @@ function learnSourceLine(plan, sessions) {
19140
20329
  by.gemini ? `Gemini ${commaCount(by.gemini)}` : "",
19141
20330
  by.opencode ? `opencode ${commaCount(by.opencode)}` : "",
19142
20331
  by.aider ? `aider ${commaCount(by.aider)}` : "",
20332
+ by.pi ? `Pi ${commaCount(by.pi)}` : "",
19143
20333
  ].filter(Boolean);
19144
20334
  return `${commaCount(sessions)} sessions read${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
19145
20335
  }
@@ -19692,7 +20882,7 @@ export function renderLearnReconcile(raw) {
19692
20882
  return `${out.join("\n")}\n`;
19693
20883
  }
19694
20884
  function learnUsage() {
19695
- console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
20885
+ console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider,pi]
19696
20886
  shows where your agent's tokens go, and what to fix first
19697
20887
  default interactive Setup Score + top findings
19698
20888
  --plain short text; no animation or keyboard menu
@@ -19976,7 +21166,11 @@ function resolveCavememCommand() {
19976
21166
  function cavememRun(memArgs, opts = {}) {
19977
21167
  const { command, args: pre } = resolveCavememCommand();
19978
21168
  try {
19979
- return execFileSync(command, [...pre, ...memArgs], { encoding: "utf8", env: process.env });
21169
+ return execFileSync(command, [...pre, ...memArgs], {
21170
+ encoding: "utf8",
21171
+ env: process.env,
21172
+ stdio: [opts.stdin ? "inherit" : "pipe", "pipe", "pipe"],
21173
+ });
19980
21174
  }
19981
21175
  catch (error) {
19982
21176
  const e = error;
@@ -19992,6 +21186,23 @@ function cavememRun(memArgs, opts = {}) {
19992
21186
  }
19993
21187
  return null;
19994
21188
  }
21189
+ // A cavemem older than `supersede --stdin` reads supersede's second argument as
21190
+ // the replacement TEXT, so handing one "--stdin" stores the literal flag,
21191
+ // expires the real memory and exits 0. The binary advertises the capability, so
21192
+ // ask before sending a replacement over stdin. Soft: an unreadable version
21193
+ // answers "no", which refuses rather than risking the write.
21194
+ function cavememSupersedeStdin() {
21195
+ const out = cavememRun(["version", "--json"], { soft: true });
21196
+ if (!out)
21197
+ return false;
21198
+ try {
21199
+ const { capabilities } = JSON.parse(out);
21200
+ return Array.isArray(capabilities) && capabilities.includes("supersede-stdin");
21201
+ }
21202
+ catch {
21203
+ return false;
21204
+ }
21205
+ }
19995
21206
  // mem is the durable-memory command family (cavemem). remember/recall/recover/
19996
21207
  // forget are mechanical store ops; the editing skill and the opt-in recall hook
19997
21208
  // build on them. Memory edits to a user's config are NEVER done here — only the
@@ -20005,10 +21216,16 @@ function mem(rest) {
20005
21216
  // fall back to dropping flag-looking args (remember takes none) for
20006
21217
  // backward compatibility.
20007
21218
  const args = rest.slice(1);
21219
+ // --stdin hands our stdin straight to cavemem, so the block reaches the
21220
+ // store byte for byte and never passes through a shell command line.
21221
+ if (args.length === 1 && args[0] === "--stdin") {
21222
+ process.stdout.write(cavememRun(["remember", "--stdin"], { stdin: true }) ?? "");
21223
+ return;
21224
+ }
20008
21225
  const sep = args.indexOf("--");
20009
21226
  const text = (sep >= 0 ? args.slice(sep + 1) : args.filter((a) => !a.startsWith("--"))).join(" ");
20010
21227
  if (!text) {
20011
- console.error(`usage: ${invokedCommand("mem")} remember [--] <text>`);
21228
+ console.error(`usage: ${invokedCommand("mem")} remember [--] <text> | --stdin`);
20012
21229
  process.exit(2);
20013
21230
  }
20014
21231
  process.stdout.write(cavememRun(["remember", text]) ?? "");
@@ -20051,10 +21268,21 @@ function mem(rest) {
20051
21268
  // Same `--` end-of-options handling as remember: a replacement block that
20052
21269
  // opens with a `---` rule must survive verbatim instead of filtering empty.
20053
21270
  const rest2 = rest.slice(2);
21271
+ // --stdin hands our stdin straight to cavemem, exactly as remember does,
21272
+ // so a replacement bigger than one argv element (~128 KB on Linux,
21273
+ // ~32 KB of whole command line on Windows) reaches the store at all.
21274
+ if (id && rest2.length === 1 && rest2[0] === "--stdin") {
21275
+ if (!cavememSupersedeStdin()) {
21276
+ console.error("caveman: this cavemem build cannot read a replacement from stdin (no supersede-stdin capability); upgrade it, or pass the text as an argument");
21277
+ process.exit(1);
21278
+ }
21279
+ process.stdout.write(cavememRun(["supersede", id, "--stdin"], { stdin: true }) ?? "");
21280
+ return;
21281
+ }
20054
21282
  const sep = rest2.indexOf("--");
20055
21283
  const text = (sep >= 0 ? rest2.slice(sep + 1) : rest2.filter((a) => !a.startsWith("--"))).join(" ");
20056
21284
  if (!id || !text) {
20057
- console.error(`usage: ${invokedCommand("mem")} supersede <id> [--] <text>`);
21285
+ console.error(`usage: ${invokedCommand("mem")} supersede <id> [--] <text> | <id> --stdin`);
20058
21286
  process.exit(2);
20059
21287
  }
20060
21288
  process.stdout.write(cavememRun(["supersede", id, text]) ?? "");
@@ -20106,6 +21334,7 @@ function memRecover(handle) {
20106
21334
  function memUsage() {
20107
21335
  console.log(`caveman mem — durable agent memory (cavemem)
20108
21336
  caveman mem remember <text> store a memory
21337
+ caveman mem remember --stdin store a memory read from stdin, byte for byte
20109
21338
  caveman mem recall <query> [--limit N] recall memories (lexical, conservative threshold)
20110
21339
  caveman mem supersede <id> <text> replace a current fact; preserve history
20111
21340
  caveman mem history <id> show oldest-to-newest versions
@@ -20743,6 +21972,9 @@ async function status(argv) {
20743
21972
  const cavemanBusts = Number(today?.caveman_cache_bust_requests ?? 0);
20744
21973
  if (Number.isSafeInteger(cavemanBusts) && cavemanBusts > 0)
20745
21974
  states.push(OFF_STATES.cavemanCacheBust(cavemanBusts));
21975
+ const recoveryStore = versionInfo ? readRecoveryStore(false) : undefined;
21976
+ if (recoveryStore?.writes_refused && recoveryStore.reason)
21977
+ states.push(OFF_STATES.recoveryStore(recoveryStore.reason, recoveryStore.fix));
20746
21978
  const runningMode = runtime.owner !== "unknown" && runtime.mode ? runtime.mode : null;
20747
21979
  const resolvedMode = gate.mode;
20748
21980
  const snapshot = readLearnSnapshot();