@caveman-ai/cli 4.0.1 → 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 {
@@ -4952,6 +4970,14 @@ export const OFF_STATES = {
4952
4970
  },
4953
4971
  // The proxy's cache tripwire: the client re-sent bytes the provider had
4954
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
+ }),
4955
4981
  cavemanCacheBust: (count) => ({
4956
4982
  id: "cache-bust",
4957
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`,
@@ -4964,6 +4990,7 @@ const OFF_STATE_PRECEDENCE = [
4964
4990
  "running-mode-mismatch",
4965
4991
  "invalid-mode",
4966
4992
  "user-record",
4993
+ "recovery-store",
4967
4994
  "mcp-missing",
4968
4995
  "mem-missing",
4969
4996
  "zdr",
@@ -5559,6 +5586,36 @@ function readProxyObserveSummary(sinceISO) {
5559
5586
  return null;
5560
5587
  }
5561
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
+ }
5562
5619
  // PROXY_RECENT_ROW_CAP mirrors the store's hard cap on `stats --recent N`: asking
5563
5620
  // for more rows than this silently returns this many, so a full page back is
5564
5621
  // indistinguishable from a truncated window.
@@ -6744,6 +6801,8 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
6744
6801
  Object.assign(env, claudeCaveBuildEnv());
6745
6802
  if (!direct)
6746
6803
  maybeWarnHermesMissingKey(agent, gw);
6804
+ if (!direct)
6805
+ maybeWarnGeminiHeadlessAuth(agent, childArgs);
6747
6806
  if (direct) {
6748
6807
  // buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
6749
6808
  // outer routed wrap may leak the bare form; a direct launch strips both.
@@ -6880,6 +6939,43 @@ function firstEnvSecret(env, keys) {
6880
6939
  }
6881
6940
  return undefined;
6882
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
+ }
6883
6979
  function maybeWarnHermesMissingKey(agent, gw = gatewayURL()) {
6884
6980
  if (agent?.id !== "hermes")
6885
6981
  return;
@@ -7694,6 +7790,34 @@ export function hookExecutableInvocation(executable, script, platform = process.
7694
7790
  // required invocation operator. POSIX hook commands keep their exact shape.
7695
7791
  return platform === "win32" && powershell ? `& ${invocation}` : invocation;
7696
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
+ }
7697
7821
  function nativeHookCommand(agentId) {
7698
7822
  const fastHook = join(dirname(fileURLToPath(import.meta.url)), "native-hook-fast.js");
7699
7823
  const explicitProxy = process.env.CAVEMAN_PROXY_BIN;
@@ -7820,7 +7944,7 @@ function canonicalManagedHookEntry(entry) {
7820
7944
  const clone = JSON.parse(JSON.stringify(entry));
7821
7945
  const hooks = clone.hooks;
7822
7946
  hooks[0].command = identity;
7823
- return JSON.stringify(clone);
7947
+ return canonicalize(clone);
7824
7948
  }
7825
7949
  // Why: `think.shrink` (and its `CAVEMAN_SHRINK` env form) is the persisted
7826
7950
  // switch for the command-output rewrite, but only the ephemeral launcher ever
@@ -7996,6 +8120,37 @@ function generatedArtifactTargetsExist(text) {
7996
8120
  const tokens = generatedInvocation(text);
7997
8121
  return tokens === undefined || invocationTargetsExist(tokens);
7998
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
+ }
7999
8154
  // A managed hook is only healthy while the files its command runs still exist.
8000
8155
  // Identity is judged by basename, so a hook rendered into a directory that has
8001
8156
  // since been deleted (an nvm Node upgrade, #1137) kept matching the expected
@@ -8197,6 +8352,7 @@ const HERMES_NATIVE_PLUGIN_END = "# <<< caveman:native-hermes-plugin";
8197
8352
  const HERMES_NATIVE_MCP_BEGIN = "# >>> caveman:native-hermes-mcp";
8198
8353
  const HERMES_NATIVE_MCP_END = "# <<< caveman:native-hermes-mcp";
8199
8354
  const HERMES_NATIVE_PLUGIN_NAME = "caveman_native";
8355
+ const HERMES_NATIVE_MCP_SERVER = "caveman-native";
8200
8356
  const GEMINI_NATIVE_ENV_BEGIN = "# >>> caveman:native-routing";
8201
8357
  const GEMINI_NATIVE_ENV_END = "# <<< caveman:native-routing";
8202
8358
  const AIDER_NATIVE_ROUTE_BEGIN = "# >>> caveman:native-aider-routing";
@@ -8412,9 +8568,17 @@ function nativeProxyBinaryRequired(gw) {
8412
8568
  // several times, and a hung host would cost the full timeout every time.
8413
8569
  const nativeHostProbes = new Map();
8414
8570
  function nativeHostProbe(agent) {
8415
- 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);
8416
8580
  if (!binary)
8417
- return { binary: null, launchable: false, version: null, error: "binary_not_found" };
8581
+ return null;
8418
8582
  let probe = nativeHostProbes.get(binary);
8419
8583
  if (!probe)
8420
8584
  nativeHostProbes.set(binary, probe = probeNativeHost(binary));
@@ -8798,6 +8962,31 @@ function geminiRouteShadow() {
8798
8962
  return null;
8799
8963
  }
8800
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
+ }
8801
8990
  function geminiNativeMutations(gw, mcpBinary) {
8802
8991
  if (wrapMode(gw) === "managed") {
8803
8992
  throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
@@ -8806,6 +8995,20 @@ function geminiNativeMutations(gw, mcpBinary) {
8806
8995
  const settingsBefore = fileBytes(settingsPath);
8807
8996
  const settings = parseJsonFileObject(settingsPath, settingsBefore);
8808
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
+ }
8809
9012
  if (settings.mcpServers !== undefined && (typeof settings.mcpServers !== "object" || settings.mcpServers === null || Array.isArray(settings.mcpServers))) {
8810
9013
  throw new Error(`${settingsPath} mcpServers must be a JSON object; refusing to overwrite it`);
8811
9014
  }
@@ -8817,8 +9020,6 @@ function geminiNativeMutations(gw, mcpBinary) {
8817
9020
  servers.caveman = installedMcp;
8818
9021
  settings.mcpServers = servers;
8819
9022
  const withHooks = nativeHooksDocument("gemini", nativeShrinkEnabled(), settings);
8820
- const envPath = join(geminiConfigDir(), ".env");
8821
- const envBefore = fileBytes(envPath);
8822
9023
  const route = appendUrlPath(gw, "/w/gemini");
8823
9024
  const nativeEnv = geminiNativeEnv(envBefore?.toString("utf8") ?? "", route);
8824
9025
  // The block goes last in the file, so it would win over the user's own.
@@ -8831,7 +9032,7 @@ function geminiNativeMutations(gw, mcpBinary) {
8831
9032
  before: settingsBefore,
8832
9033
  after: jsonBytes(withHooks, settingsBefore),
8833
9034
  kind: "gemini-settings",
8834
- owned: { installed_mcp: installedMcp, previous_mcp: previousMcp ?? null },
9035
+ owned: { installed_mcp: installedMcp, previous_mcp: previousMcp ?? null, selected_auth: selectedAuth },
8835
9036
  },
8836
9037
  {
8837
9038
  file: envPath,
@@ -8842,9 +9043,15 @@ function geminiNativeMutations(gw, mcpBinary) {
8842
9043
  },
8843
9044
  ];
8844
9045
  }
8845
- // OpenCode reads $XDG_CONFIG_HOME/opencode, else ~/.config/opencode on every
8846
- // 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.
8847
9051
  function opencodeConfigDir() {
9052
+ const selected = (process.env.OPENCODE_CONFIG_DIR ?? "").trim();
9053
+ if (selected)
9054
+ return resolve(selected);
8848
9055
  return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
8849
9056
  }
8850
9057
  function opencodeConfigPath() {
@@ -8854,12 +9061,30 @@ function opencodeConfigPath() {
8854
9061
  function opencodeNativePluginPath() {
8855
9062
  return join(opencodeConfigDir(), "plugins", "caveman-native.js");
8856
9063
  }
8857
- 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() {
8858
9076
  const profile = AGENTS.find((agent) => agent.id === "opencode");
8859
- const host = profile ? nativeHostProbe(profile) : null;
8860
- // A failed probe's text is its error output, not a version.
8861
- const semver = host?.launchable ? parsedSemver(host.version) : undefined;
8862
- 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);
8863
9088
  }
8864
9089
  function opencodeNativePluginSource() {
8865
9090
  // OpenCode 2 replaced the plugin API: a V1 hook map no longer loads
@@ -8872,12 +9097,14 @@ function opencodeNativePluginSource() {
8872
9097
  // V2 { id, setup } beside it. 1.x also calls setup, with a context that has
8873
9098
  // no session or event API, so setup returns there. Checked against real
8874
9099
  // OpenCode 1.18.35 and 2.0.22; 1.0-1.3 call every export and cannot load it.
8875
- const major = opencodePluginMajor();
8876
- 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)
8877
9106
  return opencodeNativePluginSourceBoth();
8878
- if (major < 2)
8879
- return opencodeNativePluginSourceV1();
8880
- return opencodeNativePluginSourceV2();
9107
+ return majors[0] < 2 ? opencodeNativePluginSourceV1() : opencodeNativePluginSourceV2();
8881
9108
  }
8882
9109
  function opencodeNativePluginSourceBoth() {
8883
9110
  const v2 = opencodeNativePluginSourceV2();
@@ -8898,11 +9125,18 @@ const prefix = ${JSON.stringify(pre)};
8898
9125
  const contexts = new Map();
8899
9126
  const pending = new Map();
8900
9127
 
8901
- 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) {
8902
9135
  try {
8903
9136
  const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
8904
- input: JSON.stringify({ event_name: event, ...payload }),
9137
+ input: JSON.stringify({ event_name: event, ...(cwd ? { cwd } : {}), ...payload }),
8905
9138
  encoding: "utf8",
9139
+ cwd: cwd || undefined,
8906
9140
  timeout: 2000,
8907
9141
  maxBuffer: 2 * 1024 * 1024,
8908
9142
  // A host with no console of its own — OpenCode under a multiplexer or a
@@ -8975,7 +9209,7 @@ function sessionContext(sessionID) {
8975
9209
  return contexts.get(sessionID);
8976
9210
  }
8977
9211
 
8978
- export const CavemanNative = async () => ({
9212
+ const hostHooks = {
8979
9213
  event: async ({ event }) => {
8980
9214
  const type = event?.type;
8981
9215
  const props = event?.properties ?? {};
@@ -9029,6 +9263,7 @@ export const CavemanNative = async () => ({
9029
9263
  const raw = execFileSync(command, [...prefix, "shrink-hook"], {
9030
9264
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command: output.args.command } }),
9031
9265
  encoding: "utf8",
9266
+ cwd: projectDir || undefined,
9032
9267
  timeout: 750,
9033
9268
  windowsHide: true,
9034
9269
  });
@@ -9059,7 +9294,15 @@ export const CavemanNative = async () => ({
9059
9294
  contexts.clear();
9060
9295
  pending.clear();
9061
9296
  },
9062
- });
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
+ };
9063
9306
  `;
9064
9307
  }
9065
9308
  function opencodeNativePluginSourceV2() {
@@ -9073,11 +9316,18 @@ import { createHash } from "node:crypto";
9073
9316
  const command = ${JSON.stringify(cmd)};
9074
9317
  const prefix = ${JSON.stringify(pre)};
9075
9318
 
9076
- 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) {
9077
9326
  try {
9078
9327
  const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
9079
- input: JSON.stringify({ event_name: event, ...payload }),
9328
+ input: JSON.stringify({ event_name: event, ...(cwd ? { cwd } : {}), ...payload }),
9080
9329
  encoding: "utf8",
9330
+ cwd: cwd || undefined,
9081
9331
  timeout: 2000,
9082
9332
  maxBuffer: 2 * 1024 * 1024,
9083
9333
  // A host with no console of its own — OpenCode under a multiplexer or a
@@ -9144,13 +9394,19 @@ export default {
9144
9394
  id: "caveman-native",
9145
9395
  async setup(ctx) {
9146
9396
  // Per-plugin-instance state: one setup() runs per location, so two
9147
- // 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).
9148
9400
  const contexts = new Map();
9149
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);
9150
9406
 
9151
9407
  function sessionContext(sessionID) {
9152
9408
  if (!contexts.has(sessionID)) {
9153
- const out = call("SessionStart", { session_id: sessionID, surface: "cli" });
9409
+ const out = emit("SessionStart", { session_id: sessionID, surface: "cli" });
9154
9410
  const context = out?.hookSpecificOutput?.additionalContext;
9155
9411
  contexts.set(sessionID, typeof context === "string" ? context : "");
9156
9412
  }
@@ -9167,8 +9423,16 @@ export default {
9167
9423
  });
9168
9424
 
9169
9425
  function sameLocation(event) {
9170
- return event.location?.directory === ctx.location.directory &&
9171
- 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;
9172
9436
  }
9173
9437
 
9174
9438
  function handleEvent(event) {
@@ -9177,16 +9441,16 @@ export default {
9177
9441
  const sessionID = event.data?.sessionID;
9178
9442
  if (typeof sessionID !== "string" || !sessionID) return;
9179
9443
  if (type === "session.created") sessionContext(sessionID);
9180
- if (type === "session.idle") call("Stop", { session_id: sessionID });
9444
+ if (type === "session.idle") emit("Stop", { session_id: sessionID });
9181
9445
  // "session.compacted" is the V1 event name; V2 reports compaction
9182
9446
  // through "session.compaction.ended". Handle both.
9183
9447
  if (type === "session.compaction.ended" || type === "session.compacted") {
9184
- const out = call("PostCompact", { session_id: sessionID });
9448
+ const out = emit("PostCompact", { session_id: sessionID });
9185
9449
  const context = out?.hookSpecificOutput?.additionalContext;
9186
9450
  if (typeof context === "string" && context) contexts.set(sessionID, context);
9187
9451
  }
9188
9452
  if (type === "session.deleted") {
9189
- call("SessionEnd", { session_id: sessionID });
9453
+ emit("SessionEnd", { session_id: sessionID });
9190
9454
  contexts.delete(sessionID);
9191
9455
  pending.delete(sessionID);
9192
9456
  }
@@ -9194,7 +9458,7 @@ export default {
9194
9458
 
9195
9459
  await ctx.session.hook("prompt", (event) => {
9196
9460
  const prompt = event.prompt ?? {};
9197
- const decision = call("UserPromptSubmit", {
9461
+ const decision = emit("UserPromptSubmit", {
9198
9462
  session_id: event.sessionID,
9199
9463
  prompt: digest(prompt),
9200
9464
  task_type: taskType(prompt),
@@ -9216,13 +9480,13 @@ export default {
9216
9480
  });
9217
9481
 
9218
9482
  await ctx.session.hook("compaction", (event) => {
9219
- call("PreCompact", { session_id: event.sessionID });
9483
+ emit("PreCompact", { session_id: event.sessionID });
9220
9484
  const stable = sessionContext(event.sessionID);
9221
9485
  if (stable) event.system.push({ type: "text", text: stable });
9222
9486
  });
9223
9487
 
9224
9488
  await ctx.tool.hook("execute.before", (event) => {
9225
- const decision = call("PreToolUse", {
9489
+ const decision = emit("PreToolUse", {
9226
9490
  session_id: event.sessionID,
9227
9491
  tool_name: event.tool,
9228
9492
  tool_input: event.input,
@@ -9239,6 +9503,7 @@ export default {
9239
9503
  const raw = execFileSync(command, [...prefix, "shrink-hook"], {
9240
9504
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
9241
9505
  encoding: "utf8",
9506
+ cwd: projectCwd || undefined,
9242
9507
  timeout: 750,
9243
9508
  windowsHide: true,
9244
9509
  });
@@ -9250,7 +9515,7 @@ export default {
9250
9515
 
9251
9516
  await ctx.tool.hook("execute.after", (event) => {
9252
9517
  if (event.status !== "completed") return;
9253
- const decision = call("PostToolUse", {
9518
+ const decision = emit("PostToolUse", {
9254
9519
  session_id: event.sessionID,
9255
9520
  tool_name: event.tool,
9256
9521
  tool_input: event.input,
@@ -9264,7 +9529,7 @@ export default {
9264
9529
 
9265
9530
  return () => {
9266
9531
  controller.abort();
9267
- for (const sessionID of contexts.keys()) call("SessionEnd", { session_id: sessionID });
9532
+ for (const sessionID of contexts.keys()) emit("SessionEnd", { session_id: sessionID });
9268
9533
  contexts.clear();
9269
9534
  pending.clear();
9270
9535
  };
@@ -9999,15 +10264,31 @@ function insertHermesNativeListEntry(lines, sectionName, childName, begin, end,
9999
10264
  lines.push(...whole);
10000
10265
  return whole.join("\n");
10001
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
+ }
10002
10279
  function hermesNativeConfig(source, gw, mcpBinary) {
10003
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]) {
10004
10281
  if (source.includes(marker))
10005
10282
  throw new Error("existing Hermes Caveman native block is unjournaled; run `caveman doctor hermes`");
10006
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
+ }
10007
10288
  const lines = yamlLines(source);
10008
10289
  let model = topLevelSection(lines, "model");
10009
10290
  if (!model) {
10010
- lines.unshift("model:");
10291
+ lines.splice(yamlBodyStart(lines), 0, "model:");
10011
10292
  model = topLevelSection(lines, "model");
10012
10293
  }
10013
10294
  const routeIndexes = [];
@@ -10024,10 +10305,17 @@ function hermesNativeConfig(source, gw, mcpBinary) {
10024
10305
  const insertAt = routeIndexes[0] ?? model.start + 1;
10025
10306
  for (const index of [...routeIndexes].sort((a, b) => b - a))
10026
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);
10027
10315
  const routeBlock = [
10028
10316
  ` ${HERMES_NATIVE_ROUTE_BEGIN}`,
10029
- ' provider: "custom"',
10030
- ` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes/v1"))}`,
10317
+ keptProvider ? ` provider: ${keptProvider}` : ' provider: "custom"',
10318
+ ` base_url: ${yamlQuote(route)}`,
10031
10319
  ` ${HERMES_NATIVE_ROUTE_END}`,
10032
10320
  ];
10033
10321
  lines.splice(insertAt, 0, ...routeBlock);
@@ -10044,8 +10332,9 @@ function hermesNativeConfig(source, gw, mcpBinary) {
10044
10332
  }
10045
10333
  }
10046
10334
  if (enabled >= 0) {
10047
- if (!hermesNamedPluginEnabled(source, HERMES_NATIVE_PLUGIN_NAME)) {
10048
- 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}`];
10049
10338
  lines.splice(enabled + 1, 0, ...block);
10050
10339
  pluginBlock = block.join("\n");
10051
10340
  }
@@ -10065,16 +10354,19 @@ function hermesNativeConfig(source, gw, mcpBinary) {
10065
10354
  }
10066
10355
  const mcpBlockLines = [
10067
10356
  ` ${HERMES_NATIVE_MCP_BEGIN}`,
10068
- " caveman-native:",
10357
+ ` ${HERMES_NATIVE_MCP_SERVER}:`,
10069
10358
  ` command: ${yamlQuote(mcpBinary)}`,
10070
10359
  " enabled: true",
10071
10360
  ` ${HERMES_NATIVE_MCP_END}`,
10072
10361
  ];
10073
- 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);
10074
10363
  return {
10075
10364
  text: yamlText(lines),
10076
10365
  owned: {
10077
- 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",
10078
10370
  route_block: routeBlock.join("\n"),
10079
10371
  previous_route_lines: previousRouteLines,
10080
10372
  plugin_block: pluginBlock,
@@ -10572,8 +10864,9 @@ function enableNative(argv, { quiet = false } = {}) {
10572
10864
  // is not the current target); it is re-wired below, outside the lock.
10573
10865
  // Module apply (quiet) writes only the files its plan showed, so the
10574
10866
  // voice skills ride along with an explicit `caveman enable` only.
10575
- // A Claude profile the journal does not cover is re-wired the same way.
10576
- 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)) {
10577
10870
  if (!quiet)
10578
10871
  installNativeVoiceSkills(agent);
10579
10872
  return "stale";
@@ -10599,6 +10892,8 @@ function enableNative(argv, { quiet = false } = {}) {
10599
10892
  process.stderr.write(` ${mutation.kind}: ${mutation.file}\n`);
10600
10893
  if (typeof route === "string")
10601
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`);
10602
10897
  process.stderr.write(agent === "aider" ? " recovery MCP: unavailable in Aider\n" : ` recovery MCP: ${mcpBinary}\n`);
10603
10898
  process.stderr.write(agent === "aider"
10604
10899
  ? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
@@ -10643,9 +10938,13 @@ function enableNative(argv, { quiet = false } = {}) {
10643
10938
  setNativeOptOut(agent, false);
10644
10939
  if (outcome === "stale") {
10645
10940
  const was = agentStaleRoute(agent);
10941
+ const authUndecided = geminiAuthUndecided(agent);
10646
10942
  repairNativeAgent(agent, { quiet: true });
10647
10943
  if (!quiet)
10648
- 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`));
10649
10948
  }
10650
10949
  ensureLocalProxyForNative(agent, gw);
10651
10950
  if (quiet || outcome === "stale")
@@ -10775,7 +11074,7 @@ function restoreNativeOperation(operation) {
10775
11074
  // Symmetric to the enable-side ENABLE_TOOL_SEARCH write: only withdraw the
10776
11075
  // value we introduced ourselves and only while it is still untouched, so a
10777
11076
  // user who set their own afterwards keeps it.
10778
- 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)))) {
10779
11078
  delete currentEnv.ENABLE_TOOL_SEARCH;
10780
11079
  }
10781
11080
  // Auto's picker keys this enable added, each only while it is still ours.
@@ -10841,6 +11140,18 @@ function restoreNativeOperation(operation) {
10841
11140
  currentRoot.mcpServers = servers;
10842
11141
  else
10843
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
+ }
10844
11155
  return jsonBytes(currentRoot, current);
10845
11156
  }
10846
11157
  if (operation.kind === "gemini-env") {
@@ -10935,18 +11246,33 @@ function restoreNativeOperation(operation) {
10935
11246
  if (typeof routeBlock !== "string" || !Array.isArray(previousRouteLines)) {
10936
11247
  throw new Error("Hermes integration journal lacks owned routing block");
10937
11248
  }
10938
- if (!text.includes(routeBlock))
10939
- throw new Error("Hermes routing block changed after enable; refusing destructive disable");
10940
- text = text.replace(routeBlock, previousRouteLines.filter((line) => typeof line === "string").join("\n"));
10941
- for (const key of ["plugin_block", "mcp_block"]) {
10942
- const block = operation.owned?.[key];
10943
- if (block === null || block === undefined)
10944
- continue;
10945
- if (typeof block !== "string" || !text.includes(block))
10946
- throw new Error(`Hermes ${key.replace("_block", "")} block changed after enable; refusing destructive disable`);
10947
- 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);
10948
11266
  }
10949
- 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));
10950
11276
  }
10951
11277
  const rootBlock = operation.owned?.root_block;
10952
11278
  const tablesBlock = operation.owned?.tables_block;
@@ -11410,10 +11736,15 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11410
11736
  owned = CODEX_NATIVE_TABLES.every((table) => tables.get(table) === true) && codexNativeRouted(lines) && text.indexOf("\uFEFF", 1) === -1;
11411
11737
  }
11412
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).
11413
11743
  const text = current.toString("utf8");
11414
- owned = typeof operation.owned?.route_block === "string" && text.includes(operation.owned.route_block)
11415
- && (operation.owned.plugin_block === null || (typeof operation.owned.plugin_block === "string" && text.includes(operation.owned.plugin_block)))
11416
- && (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);
11417
11748
  }
11418
11749
  else if (operation.kind === "gemini-settings") {
11419
11750
  const root = parseJsonFileObject(operation.file, current);
@@ -11473,11 +11804,16 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11473
11804
  const coreResolution = runtimeConfig.resolution.values["think.core"];
11474
11805
  const coreConfigured = coreResolution.value === true;
11475
11806
  const mcp = probeMcpBinary();
11476
- const expectedRoute = agent === "codex"
11477
- ? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
11478
- : appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
11479
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";
11480
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");
11481
11817
  // Pi's artifact encodes no route: the extension resolves the gateway at
11482
11818
  // runtime through the same env → config → default chain as gatewayURL(), so
11483
11819
  // route drift between enable and now cannot happen. What CAN drift is the
@@ -11507,6 +11843,12 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11507
11843
  // An unreadable version cannot vouch for a single-API file (an old V1 install
11508
11844
  // on a 2.x host whose probe times out); repair rewrites it as the file both
11509
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.
11510
11852
  const opencodePluginApiCurrent = agent !== "opencode" || (() => {
11511
11853
  const operation = journal?.operations.find((item) => item.kind === "opencode-plugin");
11512
11854
  const current = operation ? fileBytes(operation.file)?.toString("utf8") : null;
@@ -11514,19 +11856,24 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11514
11856
  return true;
11515
11857
  const installedV2 = current.includes("async setup(ctx)");
11516
11858
  const installedV1 = current.includes("export const CavemanNative");
11859
+ // Both markers (the dual file) or neither: nothing is pinned to one API.
11517
11860
  if (installedV1 === installedV2)
11518
11861
  return true;
11519
- const semver = host.launchable ? parsedSemver(host.version) : undefined;
11520
- if (!semver)
11862
+ const majors = opencodePluginMajors();
11863
+ if (majors.length !== 1)
11521
11864
  return false;
11522
- return (semver[0] >= 2) === installedV2;
11865
+ return (majors[0] >= 2) === installedV2;
11523
11866
  })();
11524
11867
  const routeHealthy = ownedHealthy && (agent === "opencode"
11525
11868
  ? Object.entries(opencodeNativeRoutes(gatewayURL())).every(([providerID, route]) => routeOperation?.owned?.routes?.[providerID] === route)
11526
11869
  // Claude journals one route per profile; each has to be the current one.
11527
11870
  : agent === "pi" ? piBundleCurrent : Boolean(routeOperation) && journal.operations.every((operation) => operation.kind !== routeKind || operation.owned?.route === expectedRoute));
11528
11871
  const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
11529
- 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;
11530
11877
  const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy || !opencodePluginApiCurrent || unwiredProfiles.length > 0 ? "degraded" : "installed";
11531
11878
  const coreSupported = agent === "aider" ? ownedHealthy : ownedHealthy && Boolean(NATIVE_PACK.core);
11532
11879
  // Codex runs none of the hooks until the user trusts them; Core rides on them.
@@ -11561,12 +11908,17 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11561
11908
  if (own?.routed)
11562
11909
  warnings.push(ownEndpointRoutedMessage(agent, own));
11563
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") ?? "" : "";
11564
11916
  const components = {
11565
- 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)),
11566
11918
  // A plugin the host cannot load runs no hooks, whatever its bytes hash to.
11567
11919
  lifecycle_hooks: agent !== "aider" && ownedHealthy && opencodePluginApiCurrent && hooksTrusted,
11568
11920
  core: coreActive,
11569
- mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
11921
+ mcp_recovery: agent !== "aider" && ownedHealthy && mcpLaunchable,
11570
11922
  // Codex is false for the same reason hermes is: no command rewrite happens.
11571
11923
  // Since #1037 shrinkHook declines every Codex tool event, so Codex gets no
11572
11924
  // shrink-hook entry; an older install's entry reads degraded until --fix.
@@ -11679,7 +12031,7 @@ async function nativeDoctor(argv) {
11679
12031
  enableNative([target]);
11680
12032
  fixResult = "enabled";
11681
12033
  }
11682
- else if (before.state === "installed" && !agentStaleRoute(target)) {
12034
+ else if (before.state === "installed" && !agentStaleRoute(target) && !geminiAuthUndecided(target)) {
11683
12035
  fixResult = "not_needed";
11684
12036
  }
11685
12037
  else {
@@ -13850,8 +14202,9 @@ function nativeMcpRegistered(agent) {
13850
14202
  if (agent === "codex")
13851
14203
  return typeof operation.owned?.tables_block === "string" && codexNativeTables(codexTomlLines(current.toString("utf8")), operation.owned.tables_block).get("mcp_servers.caveman") === true;
13852
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).
13853
14206
  if (agent === "hermes")
13854
- 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);
13855
14208
  if (agent === "pi")
13856
14209
  return current.toString("utf8").includes("caveman:native-pi");
13857
14210
  const servers = objectValue(parseJsonFileObject(operation.file, current).mcpServers);
@@ -14000,6 +14353,36 @@ function stripMarkedBlock(text, begin, end) {
14000
14353
  }
14001
14354
  return { text: yamlText(kept), removed };
14002
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
+ }
14003
14386
  function topLevelSection(lines, key) {
14004
14387
  const start = lines.findIndex((line) => new RegExp(`^${key}:\\s*(?:#.*)?$`).test(line));
14005
14388
  if (start < 0)
@@ -14021,6 +14404,401 @@ function sectionHasChildKey(lines, section, key) {
14021
14404
  }
14022
14405
  return false;
14023
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
+ }
14024
14802
  function hermesMcpMarkers(serverName) {
14025
14803
  return serverName === "caveman"
14026
14804
  ? { begin: HERMES_MCP_BEGIN, end: HERMES_MCP_END }
@@ -16816,13 +17594,15 @@ function shouldShrink(command) {
16816
17594
  return false;
16817
17595
  return SHRINK_ALLOW.has(first);
16818
17596
  }
16819
- // cavemanBinForHook is the invocation a Claude hook uses to call back into this
16820
- // CLI, robust to PATH: a resolved `caveman`/`cave`, else this very script's node.
16821
- 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() {
16822
17602
  // Never a package runner's cached copy when a lasting one exists.
16823
17603
  const command = durableCaveman() ?? which("caveman") ?? which("cave");
16824
17604
  if (!command)
16825
- return hookExecutableInvocation(stableNodePath(), process.argv[1], process.platform, powershell);
17605
+ return { executable: stableNodePath(), script: process.argv[1] };
16826
17606
  // npm links `caveman` to a `#!/usr/bin/env node` script, and a host started
16827
17607
  // from a GUI or launchd often has no node on PATH (nvm, volta, Homebrew):
16828
17608
  // run it with this node, named as the lifecycle hooks name theirs (`--node`)
@@ -16833,9 +17613,20 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
16833
17613
  script = hookCommandBasename(process.execPath) === "node" && /\.[cm]?js$/.test(realpathSync(command));
16834
17614
  }
16835
17615
  catch { /* unresolvable: run it as found */ }
16836
- return script
16837
- ? hookExecutableInvocation(stableNodePath(), command, process.platform, powershell)
16838
- : 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);
16839
17630
  }
16840
17631
  // shrinkHook is the settings-hook callback for the agents whose harness can
16841
17632
  // deterministically rewrite a shell command before it runs: Claude Code (PreToolUse,
@@ -16881,9 +17672,16 @@ async function shrinkHook() {
16881
17672
  const command = evt.tool_input?.command;
16882
17673
  if (typeof command !== "string" || !shouldShrink(command))
16883
17674
  process.exit(0);
16884
- // updatedInput.command executes in host shell (Git Bash on Claude Windows),
16885
- // not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
16886
- 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()}`;
16887
17685
  // Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
16888
17686
  // Claude REPLACES via hookSpecificOutput.updatedInput (camelCase + hookEventName).
16889
17687
  // Because Claude replaces, updatedInput must carry every field the host sent —
@@ -17615,7 +18413,8 @@ async function nativeHook(argv) {
17615
18413
  confirmLearnNudge(learnNudgeToken);
17616
18414
  });
17617
18415
  }
17618
- 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.
17619
18418
  process.stdout.write(JSON.stringify({
17620
18419
  hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: compactContext },
17621
18420
  }));
@@ -18241,7 +19040,25 @@ export function generatedPluginInvocation(onPath, currentScript, platform = proc
18241
19040
  function cavemanInvocation() {
18242
19041
  return generatedPluginInvocation(durableCaveman() ?? which("caveman") ?? which("cave") ?? undefined, process.argv[1] ?? "");
18243
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.
18244
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() {
18245
19062
  const { cmd, pre } = cavemanInvocation();
18246
19063
  const argv = JSON.stringify([...pre, "shrink-hook"]);
18247
19064
  return `// caveman:shrink-plugin — GENERATED by \`caveman hooks install opencode\`.
@@ -18249,27 +19066,71 @@ function opencodePluginSource() {
18249
19066
  // with \`caveman retrieve\`). Remove with \`caveman hooks uninstall opencode\`.
18250
19067
  import { execFileSync } from "node:child_process";
18251
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 `
18252
19091
  export const CavemanShrink = async () => ({
18253
19092
  "tool.execute.before": async (input, output) => {
18254
19093
  if (input?.tool !== "bash") return;
18255
- const command = output?.args?.command;
18256
- if (typeof command !== "string" || !command.trim()) return;
18257
- try {
18258
- const res = execFileSync(${JSON.stringify(cmd)}, ${argv}, {
18259
- input: JSON.stringify({ tool_name: "Bash", tool_input: { command } }),
18260
- encoding: "utf8",
18261
- windowsHide: true,
18262
- });
18263
- if (!res) return;
18264
- const rewritten = JSON.parse(res)?.hookSpecificOutput?.updatedInput?.command;
18265
- if (typeof rewritten === "string" && rewritten) output.args.command = rewritten;
18266
- } catch {
18267
- // byte-safe: any failure leaves the original command untouched.
18268
- }
19094
+ const next = rewrite(output?.args?.command);
19095
+ if (next) output.args.command = next;
18269
19096
  },
18270
19097
  });
18271
19098
  `;
18272
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
+ }
18273
19134
  function installShrinkPluginOpencode() {
18274
19135
  const path = opencodePluginPath();
18275
19136
  try {
@@ -18396,13 +19257,152 @@ def register(ctx):
18396
19257
  # <<< caveman:shrink-plugin
18397
19258
  `;
18398
19259
  }
18399
- function hermesNamedPluginEnabled(text, name) {
18400
- const escaped = escapeRegExp(name);
18401
- return new RegExp(`(^|\\n)\\s*-\\s*["']?${escaped}["']?\\s*(?:#.*)?(?=\\n|$)`).test(text)
18402
- || 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;
19327
+ }
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;
18403
19371
  }
18404
- function hermesPluginEnabled(text) {
18405
- return hermesNamedPluginEnabled(text, HERMES_PLUGIN_NAME);
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;
18406
19406
  }
18407
19407
  function enableHermesPluginInConfig() {
18408
19408
  const path = hermesConfigPath();
@@ -18416,7 +19416,12 @@ function enableHermesPluginInConfig() {
18416
19416
  return false;
18417
19417
  }
18418
19418
  }
18419
- 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")
18420
19425
  return true;
18421
19426
  const stripped = stripMarkedBlock(existing, HERMES_PLUGIN_ENABLE_BEGIN, HERMES_PLUGIN_ENABLE_END).text;
18422
19427
  const lines = yamlLines(stripped);
@@ -18441,7 +19446,10 @@ function enableHermesPluginInConfig() {
18441
19446
  return false;
18442
19447
  }
18443
19448
  if (enabledLine >= 0) {
18444
- 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}`);
18445
19453
  }
18446
19454
  else {
18447
19455
  lines.splice(plugins.start + 1, 0, ` ${HERMES_PLUGIN_ENABLE_BEGIN}`, " enabled:", ` - ${HERMES_PLUGIN_NAME}`, ` ${HERMES_PLUGIN_ENABLE_END}`);
@@ -18518,6 +19526,8 @@ function disableHermesPluginInConfig() {
18518
19526
  }
18519
19527
  }
18520
19528
  function installShrinkPluginHermes() {
19529
+ if (!hermesPluginInstallConfigReady())
19530
+ return false;
18521
19531
  try {
18522
19532
  mkdirSync(hermesPluginDir(), { recursive: true });
18523
19533
  writeFileSync(hermesPluginManifestPath(), hermesPluginManifestSource());
@@ -18529,6 +19539,7 @@ function installShrinkPluginHermes() {
18529
19539
  }
18530
19540
  if (!enableHermesPluginInConfig()) {
18531
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;
18532
19543
  }
18533
19544
  return true;
18534
19545
  }
@@ -18882,6 +19893,11 @@ function evalsRun(argv = []) {
18882
19893
  // stats prints the local spend summary by delegating to the proxy binary, which
18883
19894
  // owns the ~/.caveman/ SQLite store. The CLI carries no database dependency, so
18884
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
+ }
18885
19901
  function stats(argv = []) {
18886
19902
  if (argv.length === 1 && ["--help", "-h", "help"].includes(argv[0])) {
18887
19903
  process.stdout.write(STATS_HELP);
@@ -18902,7 +19918,7 @@ function stats(argv = []) {
18902
19918
  args.push("--write-report");
18903
19919
  if (options.out)
18904
19920
  args.push("--out", resolve(options.out));
18905
- 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 });
18906
19922
  const report = JSON.parse(out);
18907
19923
  // Older companion binaries ignore --report. Keep their measurements
18908
19924
  // readable, but never pretend they generated the new accounting report.
@@ -18924,6 +19940,17 @@ function stats(argv = []) {
18924
19940
  }
18925
19941
  }
18926
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
+ }
18927
19954
  console.error(`failed to read stats via ${bin}: ${error.message}`);
18928
19955
  process.exit(1);
18929
19956
  }
@@ -19110,7 +20137,7 @@ async function trial(rest) {
19110
20137
  // older proxies omit it and always scanned 30d).
19111
20138
  function learnEmpty(plan) {
19112
20139
  const since = learnSince(plan.window?.since || "30d");
19113
- 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`;
19114
20141
  }
19115
20142
  // learnNoScoreYet explains why there is no score: the score needs the same
19116
20143
  // text repeated in at least 3 sessions.
@@ -19302,6 +20329,7 @@ function learnSourceLine(plan, sessions) {
19302
20329
  by.gemini ? `Gemini ${commaCount(by.gemini)}` : "",
19303
20330
  by.opencode ? `opencode ${commaCount(by.opencode)}` : "",
19304
20331
  by.aider ? `aider ${commaCount(by.aider)}` : "",
20332
+ by.pi ? `Pi ${commaCount(by.pi)}` : "",
19305
20333
  ].filter(Boolean);
19306
20334
  return `${commaCount(sessions)} sessions read${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
19307
20335
  }
@@ -19854,7 +20882,7 @@ export function renderLearnReconcile(raw) {
19854
20882
  return `${out.join("\n")}\n`;
19855
20883
  }
19856
20884
  function learnUsage() {
19857
- 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]
19858
20886
  shows where your agent's tokens go, and what to fix first
19859
20887
  default interactive Setup Score + top findings
19860
20888
  --plain short text; no animation or keyboard menu
@@ -20138,7 +21166,11 @@ function resolveCavememCommand() {
20138
21166
  function cavememRun(memArgs, opts = {}) {
20139
21167
  const { command, args: pre } = resolveCavememCommand();
20140
21168
  try {
20141
- 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
+ });
20142
21174
  }
20143
21175
  catch (error) {
20144
21176
  const e = error;
@@ -20154,6 +21186,23 @@ function cavememRun(memArgs, opts = {}) {
20154
21186
  }
20155
21187
  return null;
20156
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
+ }
20157
21206
  // mem is the durable-memory command family (cavemem). remember/recall/recover/
20158
21207
  // forget are mechanical store ops; the editing skill and the opt-in recall hook
20159
21208
  // build on them. Memory edits to a user's config are NEVER done here — only the
@@ -20167,10 +21216,16 @@ function mem(rest) {
20167
21216
  // fall back to dropping flag-looking args (remember takes none) for
20168
21217
  // backward compatibility.
20169
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
+ }
20170
21225
  const sep = args.indexOf("--");
20171
21226
  const text = (sep >= 0 ? args.slice(sep + 1) : args.filter((a) => !a.startsWith("--"))).join(" ");
20172
21227
  if (!text) {
20173
- console.error(`usage: ${invokedCommand("mem")} remember [--] <text>`);
21228
+ console.error(`usage: ${invokedCommand("mem")} remember [--] <text> | --stdin`);
20174
21229
  process.exit(2);
20175
21230
  }
20176
21231
  process.stdout.write(cavememRun(["remember", text]) ?? "");
@@ -20213,10 +21268,21 @@ function mem(rest) {
20213
21268
  // Same `--` end-of-options handling as remember: a replacement block that
20214
21269
  // opens with a `---` rule must survive verbatim instead of filtering empty.
20215
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
+ }
20216
21282
  const sep = rest2.indexOf("--");
20217
21283
  const text = (sep >= 0 ? rest2.slice(sep + 1) : rest2.filter((a) => !a.startsWith("--"))).join(" ");
20218
21284
  if (!id || !text) {
20219
- console.error(`usage: ${invokedCommand("mem")} supersede <id> [--] <text>`);
21285
+ console.error(`usage: ${invokedCommand("mem")} supersede <id> [--] <text> | <id> --stdin`);
20220
21286
  process.exit(2);
20221
21287
  }
20222
21288
  process.stdout.write(cavememRun(["supersede", id, text]) ?? "");
@@ -20268,6 +21334,7 @@ function memRecover(handle) {
20268
21334
  function memUsage() {
20269
21335
  console.log(`caveman mem — durable agent memory (cavemem)
20270
21336
  caveman mem remember <text> store a memory
21337
+ caveman mem remember --stdin store a memory read from stdin, byte for byte
20271
21338
  caveman mem recall <query> [--limit N] recall memories (lexical, conservative threshold)
20272
21339
  caveman mem supersede <id> <text> replace a current fact; preserve history
20273
21340
  caveman mem history <id> show oldest-to-newest versions
@@ -20905,6 +21972,9 @@ async function status(argv) {
20905
21972
  const cavemanBusts = Number(today?.caveman_cache_bust_requests ?? 0);
20906
21973
  if (Number.isSafeInteger(cavemanBusts) && cavemanBusts > 0)
20907
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));
20908
21978
  const runningMode = runtime.owner !== "unknown" && runtime.mode ? runtime.mode : null;
20909
21979
  const resolvedMode = gate.mode;
20910
21980
  const snapshot = readLearnSnapshot();