@caveman-ai/cli 1.2.1 → 1.2.3

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
@@ -249,6 +249,9 @@ const LEGACY_HANDLERS = {
249
249
  // humans should not need to.
250
250
  "native-hook": (argv) => nativeHook(argv),
251
251
  setup: (argv) => setup(argv),
252
+ // Unprinted (porcelain caps): sync Go binaries to this CLI's pin, then check
253
+ // npm for a newer CLI — the one verb that answers "am I current?".
254
+ update: (argv) => update(argv),
252
255
  opportunities: (argv) => argv[0] === "list" ? get("/api/v1/opportunities").then(print) : commandUsage("opportunities list"),
253
256
  snippets,
254
257
  dev: (argv) => {
@@ -402,13 +405,15 @@ const TELEMETRY_DISCLOSURE_LINE = "anonymous usage stats on — command counts a
402
405
  // Reading token totals means spawning caveman-proxy to query the local SQLite
403
406
  // store. It runs after the command's own work, so the cost lands on process exit;
404
407
  // a slow or wedged binary drops the token fields rather than holding the CLI.
405
- const TELEMETRY_TOKEN_READ_TIMEOUT_MS = 400;
408
+ // Env-overridable because a loaded CI runner can exceed 400ms just spawning the
409
+ // stub, which made the token-delta tests flaky under concurrency.
410
+ const TELEMETRY_TOKEN_READ_TIMEOUT_MS = Number(process.env.CAVEMAN_TELEMETRY_TOKEN_READ_TIMEOUT_MS) || 400;
406
411
  const SYNC_DISCLOSURE = "sync uploads span metadata to your org's dashboard — tokens, cost, latency, model, status. Imported standalone observations never affect managed budgets, verified savings, or billing. Subscription/OAuth sessions carry token counts only — no dollar figure. Never prompt or response bytes.";
407
412
  const TELEMETRY_COMMAND_ALLOWLIST = [
408
413
  "agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "dev", "doctor", "evals", "experiments",
409
414
  "explore", "help", "hooks", "init", "keys", "learn", "login", "logout", "mcp", "mem", "opportunities", "plan",
410
415
  "projects", "providers", "receipts", "retrieve", "score", "sdk", "setup", "shrink", "shrink-hook", "skills",
411
- "run", "snippets", "start", "stats", "status", "sync", "telemetry", "toon", "traces", "trial", "unknown", "usage", "verify", "version", "welcome", "whoami", "wrap",
416
+ "run", "snippets", "start", "stats", "status", "sync", "telemetry", "toon", "traces", "trial", "unknown", "update", "usage", "verify", "version", "welcome", "whoami", "wrap",
412
417
  ];
413
418
  const TELEMETRY_COMMANDS = new Set(TELEMETRY_COMMAND_ALLOWLIST);
414
419
  const TELEMETRY_SUBCOMMANDS = new Set([
@@ -947,6 +952,11 @@ function classifyTelemetryError(error) {
947
952
  const message = error instanceof Error ? error.message : "";
948
953
  if (telemetryCommandName() === "unknown" || message.startsWith("unknown command:"))
949
954
  return "unknown_command";
955
+ // Spawn failures and Windows shim rejections (portable-command.ts) — keep
956
+ // these out of "other" so agent-launch breakage is visible in telemetry. The
957
+ // bare "spawn E…" form covers sync spawn throws that skip the exec wrappers.
958
+ if (/^failed to exec |^spawn |windows command shim/i.test(message))
959
+ return "exec_failed";
950
960
  if (/not logged in|unauthorized|forbidden|auth/i.test(message))
951
961
  return "auth";
952
962
  if (/fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|network/i.test(message))
@@ -2356,6 +2366,55 @@ async function setupInstall(json, options = {}) {
2356
2366
  await chmod(binaryInstallManifestPath(), 0o600);
2357
2367
  printInstallResult(installed, platform, binDir, json, options.continuing);
2358
2368
  }
2369
+ // ── caveman update ───────────────────────────────────────────────────────────
2370
+ // Syncs the Go binaries in ~/.caveman/bin to the release this CLI pins
2371
+ // (setupInstall is idempotent: stale manifest or checksum mismatch
2372
+ // re-downloads, current binaries print "already installed"), then checks npm
2373
+ // for a newer CLI. A newer CLI pins a newer binary release, so an outdated or
2374
+ // unverifiable CLI means the update is not proven complete — exit non-zero.
2375
+ function cliVersionBehind(current, latest) {
2376
+ const have = current.split(".").map((part) => parseInt(part, 10) || 0);
2377
+ const want = latest.split(".").map((part) => parseInt(part, 10) || 0);
2378
+ for (let i = 0; i < 3; i++) {
2379
+ if ((want[i] ?? 0) !== (have[i] ?? 0))
2380
+ return (want[i] ?? 0) > (have[i] ?? 0);
2381
+ }
2382
+ return false;
2383
+ }
2384
+ async function latestPublishedCliVersion(timeoutSeconds) {
2385
+ const registry = (process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org").replace(/\/+$/, "");
2386
+ try {
2387
+ const response = await fetch(`${registry}/@caveman-ai%2fcli`, {
2388
+ headers: { accept: "application/vnd.npm.install-v1+json" },
2389
+ signal: AbortSignal.timeout(timeoutSeconds * 1000),
2390
+ });
2391
+ if (!response.ok)
2392
+ return null;
2393
+ const parsed = (await response.json());
2394
+ const latest = parsed?.["dist-tags"]?.latest;
2395
+ return typeof latest === "string" && latest ? latest : null;
2396
+ }
2397
+ catch {
2398
+ return null;
2399
+ }
2400
+ }
2401
+ async function update(argv = []) {
2402
+ if (argv.length > 0)
2403
+ commandUsage("update");
2404
+ await setupInstall(false, { continuing: true });
2405
+ const current = cliVersion();
2406
+ const latest = await latestPublishedCliVersion(setupTimeoutSeconds());
2407
+ if (!latest) {
2408
+ console.error(`${mark("warn")} binaries synced to ${BINARY_RELEASE}, but npm was unreachable — cannot confirm CLI ${current} is the latest`);
2409
+ process.exit(1);
2410
+ }
2411
+ if (cliVersionBehind(current, latest)) {
2412
+ console.error(`${mark("warn")} binaries synced for CLI ${current}, but ${latest} is out — update the CLI, then run this again:`);
2413
+ console.error(` ${cyan("npm install -g @caveman-ai/cli@latest")}`);
2414
+ process.exit(1);
2415
+ }
2416
+ console.log(`${mark("ok")} up to date — CLI ${current}, binaries ${BINARY_RELEASE}`);
2417
+ }
2359
2418
  function agentNativeBundleJournalPath(agent, pending = false) {
2360
2419
  return join(cavemanHome(), "integrations", `${agent}.agent-native-bundle${pending ? ".pending" : ""}.json`);
2361
2420
  }
@@ -4012,7 +4071,7 @@ export function formatSessionSavings(kind, s, authModes = [], windowTruncated =
4012
4071
  // `caveman doctor` only accepts these targets; a wrappable agent that isn't
4013
4072
  // one (e.g. openclaw) must fall back to `generic` so the remediation hint is a
4014
4073
  // runnable command, not a usage error.
4015
- const doctorTargets = new Set(["claude", "codex", "hermes", "gemini", "opencode", "aider"]);
4074
+ const doctorTargets = new Set(["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"]);
4016
4075
  const rawTarget = agentId && agentId.trim() ? agentId.trim() : "";
4017
4076
  const doctorTarget = rawTarget ? (doctorTargets.has(rawTarget) ? rawTarget : "generic") : "<agent>";
4018
4077
  // A null summary means the proxy could NOT be read (binary missing, db locked,
@@ -4595,7 +4654,7 @@ function normalizeAgentShortcutWrapArgs(input) {
4595
4654
  // native path would ever start the proxy or apply routedAiderArgs — a direct
4596
4655
  // launch would point it at a dead endpoint. Aider keeps the wrap door.
4597
4656
  function nativeAgentId(id) {
4598
- return id === "claude" || id === "codex" || id === "hermes" || id === "gemini" || id === "opencode" ? id : undefined;
4657
+ return id === "claude" || id === "codex" || id === "hermes" || id === "gemini" || id === "opencode" || id === "pi" ? id : undefined;
4599
4658
  }
4600
4659
  // `caveman <agent>` — the default door. It persistently enables the native
4601
4660
  // integration (the same journaled user-scoped writes as `caveman enable <agent>`)
@@ -4658,7 +4717,15 @@ async function agentShortcut(rest) {
4658
4717
  const stopProxyKeepalive = startProxyKeepalive();
4659
4718
  const code = await new Promise((resolve, reject) => {
4660
4719
  const invocation = portableInvocation(bin, [...agent.args, ...rest.slice(1)]);
4661
- const child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
4720
+ let child;
4721
+ try {
4722
+ child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
4723
+ }
4724
+ catch (error) {
4725
+ // macOS reports some exec failures (e.g. ENOEXEC) synchronously — wrap
4726
+ // them like the async 'error' path so the message names the binary.
4727
+ throw new Error(`failed to exec ${bin}: ${error.message}`);
4728
+ }
4662
4729
  // tty-generated signals (Ctrl+C / Ctrl+\) already reach the child through
4663
4730
  // the shared foreground group — forwarding would double-deliver them. But
4664
4731
  // process-directed SIGTERM/SIGHUP (timeout(1), supervisors, pkill) only hit
@@ -5023,6 +5090,8 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5023
5090
  const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
5024
5091
  childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
5025
5092
  }
5093
+ if (!direct && agent?.id === "pi")
5094
+ childArgs = buildPiWrapArgs(cmdArgs, env, gw);
5026
5095
  if (!direct && agent?.id === "aider")
5027
5096
  childArgs = routedAiderArgs(cmdArgs);
5028
5097
  }
@@ -5057,7 +5126,15 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5057
5126
  try {
5058
5127
  code = await new Promise((resolve, reject) => {
5059
5128
  const invocation = portableInvocation(bin, childArgs);
5060
- const child = spawn(invocation.command, invocation.args, { stdio: "inherit", env });
5129
+ let child;
5130
+ try {
5131
+ child = spawn(invocation.command, invocation.args, { stdio: "inherit", env });
5132
+ }
5133
+ catch (error) {
5134
+ // macOS reports some exec failures (e.g. ENOEXEC) synchronously — wrap
5135
+ // them like the async 'error' path so the message names the binary.
5136
+ throw new Error(`failed to exec ${bin}: ${error.message}`);
5137
+ }
5061
5138
  const signalHandlers = new Map();
5062
5139
  const removeSignalHandlers = () => {
5063
5140
  for (const [signal, handler] of signalHandlers)
@@ -5262,6 +5339,16 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
5262
5339
  // Same reason as `start`: the dead account variable never rides along inherited.
5263
5340
  delete env.CAVEMAN_WRAP_ENTITLED;
5264
5341
  const child = spawn(resolved, [], { stdio: "ignore", env, detached: true, windowsHide: true });
5342
+ // The caller wraps this in try/catch for fail-open startup, but a try/catch
5343
+ // cannot catch an EventEmitter 'error' — it arrives asynchronously and becomes
5344
+ // an uncaughtException that kills the CLI before the agent ever launches. A
5345
+ // wrong-arch binary (ENOEXEC), a lost x-bit between the isExecutable check and
5346
+ // the spawn (EACCES), or CAVEMAN_PROXY_BIN pointing at a Windows .cmd shim
5347
+ // (EINVAL) all take that path. Every other spawn in this file guards it; the
5348
+ // proxy start is exactly the one that must degrade to "no proxy", not die.
5349
+ child.on("error", (error) => {
5350
+ process.stderr.write(`${mark("warn")} could not start ${bin}: ${error.message}\n`);
5351
+ });
5265
5352
  child.unref();
5266
5353
  for (let i = 0; i < 20; i++) {
5267
5354
  await sleep(100);
@@ -5923,6 +6010,7 @@ const NATIVE_CAPABILITY_SUPPORT = {
5923
6010
  hermes: new Set(["provider_proxy", "session_start", "prompt_submit", "model_after", "pre_tool", "post_tool", "session_end", "mcp", "native_package", "local_runtime_available"]),
5924
6011
  gemini: new Set(["provider_proxy", "session_start", "prompt_submit", "model_before", "model_after", "pre_tool", "post_tool", "pre_compact", "session_end", "mcp", "local_runtime_available"]),
5925
6012
  opencode: new Set(["provider_proxy", "session_start", "prompt_submit", "pre_tool", "post_tool", "post_tool_rewrite", "pre_compact", "post_compact", "session_end", "mcp", "native_package", "skills", "local_runtime_available"]),
6013
+ pi: new Set(["provider_proxy", "session_start", "prompt_submit", "model_before", "model_after", "pre_tool", "post_tool", "post_tool_rewrite", "pre_compact", "post_compact", "session_end", "mcp", "native_package", "local_runtime_available"]),
5926
6014
  aider: new Set(["provider_proxy", "local_runtime_available"]),
5927
6015
  };
5928
6016
  function parsedSemver(value) {
@@ -5963,7 +6051,7 @@ function nativeCapabilityReport(agent, components, versionStatus) {
5963
6051
  if (capability === "native_package")
5964
6052
  return components.lifecycle_hooks;
5965
6053
  if (capability === "post_tool_rewrite")
5966
- return lifecycleActive && (agent === "claude" || agent === "opencode");
6054
+ return lifecycleActive && (agent === "claude" || agent === "opencode" || agent === "pi");
5967
6055
  return lifecycleActive;
5968
6056
  };
5969
6057
  const basis = versionStatus === "tested" ? "tested_manifest" : "installed_surface_probe_safe_subset";
@@ -6415,6 +6503,32 @@ function opencodeNativeMutations(gw, mcpBinary) {
6415
6503
  },
6416
6504
  ];
6417
6505
  }
6506
+ function piNativeMutations() {
6507
+ const extensionDir = join(homedir(), ".pi", "agent", "extensions");
6508
+ // Pi's extension auto-discovery accepts only .ts/.js (isExtensionFile in
6509
+ // pi-coding-agent 0.84.2); a .mjs here would journal fine and never load.
6510
+ const extensionPath = join(extensionDir, "caveman-native.js");
6511
+ const before = fileBytes(extensionPath);
6512
+ if (before && !before.toString("utf8").includes("caveman:native-pi")) {
6513
+ throw new Error(`${extensionPath} already exists and is not Caveman-owned; refusing to overwrite it`);
6514
+ }
6515
+ // Plain `pi` launches carry no wrap env, so the persistent artifact bakes in
6516
+ // the invocation this enable resolved (falling back to PATH when unset) —
6517
+ // same pattern as the generated opencode plugin.
6518
+ const { cmd, pre } = cavemanInvocation();
6519
+ const after = Buffer.concat([
6520
+ Buffer.from("// caveman:native-pi — GENERATED by `caveman enable pi`.\n"),
6521
+ Buffer.from(`process.env.CAVEMAN_PI_HOOK_CMD ??= ${JSON.stringify(JSON.stringify([cmd, ...pre]))};\n`),
6522
+ readFileSync(resolvePiExtension()),
6523
+ ]);
6524
+ return [{
6525
+ file: extensionPath,
6526
+ before,
6527
+ after,
6528
+ kind: "pi-extension",
6529
+ owned: { sha256: bytesHash(after), created_extension_dir: !existsSync(extensionDir) },
6530
+ }];
6531
+ }
6418
6532
  function aiderCorePath() {
6419
6533
  return join(cavemanHome(), "packs", "aider", "CAVEMAN.md");
6420
6534
  }
@@ -7023,19 +7137,21 @@ function nativeMutationsFor(agent, gw, mcpBinary) {
7023
7137
  ? geminiNativeMutations(gw, mcpBinary)
7024
7138
  : agent === "opencode"
7025
7139
  ? opencodeNativeMutations(gw, mcpBinary)
7026
- : aiderNativeMutations(gw);
7140
+ : agent === "pi"
7141
+ ? piNativeMutations()
7142
+ : aiderNativeMutations(gw);
7027
7143
  }
7028
7144
  function enableNative(argv) {
7029
7145
  const detected = argv.includes("--detected");
7030
7146
  const target = argv.find((arg) => !arg.startsWith("--"));
7031
7147
  if ((!detected && !target) || (detected && target) || argv.some((arg) => arg !== "--detected" && arg !== target)) {
7032
- commandUsage("enable <claude|codex|hermes|gemini|opencode|aider> | enable --detected");
7148
+ commandUsage("enable <claude|codex|hermes|gemini|opencode|pi|aider> | enable --detected");
7033
7149
  }
7034
7150
  const profiles = detected
7035
- ? AGENTS.filter((agent) => (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "aider") && which(binOf(agent)))
7036
- : AGENTS.filter((agent) => agent.id === target && (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "aider"));
7151
+ ? AGENTS.filter((agent) => (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "pi" || agent.id === "aider") && which(binOf(agent)))
7152
+ : AGENTS.filter((agent) => agent.id === target && (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "pi" || agent.id === "aider"));
7037
7153
  if (profiles.length === 0) {
7038
- console.error(detected ? "no supported native agent detected on PATH" : `caveman enable: supported agents are claude, codex, hermes, gemini, opencode, and aider (got ${target ?? ""})`);
7154
+ console.error(detected ? "no supported native agent detected on PATH" : `caveman enable: supported agents are claude, codex, hermes, gemini, opencode, pi, and aider (got ${target ?? ""})`);
7039
7155
  process.exit(1);
7040
7156
  }
7041
7157
  const gw = gatewayURL();
@@ -7063,7 +7179,9 @@ function enableNative(argv) {
7063
7179
  process.stderr.write(agent === "aider" ? " recovery MCP: unavailable in Aider\n" : ` recovery MCP: ${mcpBinary}\n`);
7064
7180
  process.stderr.write(agent === "aider"
7065
7181
  ? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
7066
- : ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
7182
+ : agent === "pi"
7183
+ ? ` lifecycle/Core/tool rewrite: bundled Pi extension -> ${nativeHookCommand(agent)}\n`
7184
+ : ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
7067
7185
  applyNativeMutations(agent, profile, mutations);
7068
7186
  return "enabled";
7069
7187
  });
@@ -7238,7 +7356,7 @@ function restoreNativeOperation(operation) {
7238
7356
  }
7239
7357
  return Buffer.from(text.replace(`${block}\n\n`, "").replace(`\n\n${block}\n`, "\n").replace(`${block}\n`, "").replace(block, ""));
7240
7358
  }
7241
- if (operation.kind === "opencode-plugin") {
7359
+ if (operation.kind === "opencode-plugin" || operation.kind === "pi-extension") {
7242
7360
  throw new Error(`${operation.file} changed after enable; refusing destructive disable`);
7243
7361
  }
7244
7362
  if (operation.kind === "opencode-config") {
@@ -7372,29 +7490,40 @@ function restoreNativeJournalFiles(journal) {
7372
7490
  }
7373
7491
  return current;
7374
7492
  }
7375
- function cleanupNativeAgentFiles(target) {
7376
- if (target !== "hermes")
7377
- return;
7378
- try {
7379
- if (readdirSync(hermesNativePluginDir()).length === 0)
7380
- rmSync(hermesNativePluginDir(), { recursive: true });
7493
+ function cleanupNativeAgentFiles(target, journal) {
7494
+ if (target === "hermes") {
7495
+ try {
7496
+ if (readdirSync(hermesNativePluginDir()).length === 0)
7497
+ rmSync(hermesNativePluginDir(), { recursive: true });
7498
+ }
7499
+ catch { /* absent or non-empty: preserve */ }
7500
+ }
7501
+ if (target === "pi") {
7502
+ const extension = journal.operations.find((operation) => operation.kind === "pi-extension");
7503
+ if (extension?.owned?.created_extension_dir !== true)
7504
+ return;
7505
+ const extensionDir = dirname(extension.file);
7506
+ try {
7507
+ if (readdirSync(extensionDir).length === 0)
7508
+ rmSync(extensionDir, { recursive: true });
7509
+ }
7510
+ catch { /* absent or non-empty: preserve */ }
7381
7511
  }
7382
- catch { /* absent or non-empty: preserve */ }
7383
7512
  }
7384
7513
  function disableNativeAgent(target) {
7385
7514
  const disabled = withIntegrationLock(target, () => {
7386
7515
  recoverPendingNativeInstallUnlocked(target);
7387
7516
  const journal = readNativeJournal(target);
7388
7517
  if (!journal)
7389
- return false;
7518
+ return undefined;
7390
7519
  restoreNativeJournalFiles(journal);
7391
- return true;
7520
+ return journal;
7392
7521
  });
7393
7522
  if (!disabled) {
7394
7523
  process.stderr.write(`${mark("warn")} ${target}: no native Caveman integration journal found\n`);
7395
7524
  return false;
7396
7525
  }
7397
- cleanupNativeAgentFiles(target);
7526
+ cleanupNativeAgentFiles(target, disabled);
7398
7527
  const name = findAgent(target)?.display_name ?? target;
7399
7528
  process.stderr.write(`${mark("ok")} ${name}: ${target === "aider" ? "shallow" : "native"} Caveman disabled; unrelated host edits preserved\n`);
7400
7529
  return true;
@@ -7436,7 +7565,7 @@ function repairNativeAgent(target) {
7436
7565
  }
7437
7566
  function disableNative(argv) {
7438
7567
  if (argv.length === 1 && argv[0] === "--all") {
7439
- const targets = ["claude", "codex", "hermes", "gemini", "opencode", "aider"]
7568
+ const targets = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"]
7440
7569
  .filter((agent) => Boolean(readNativeJournal(agent) || readPendingNativeJournal(agent)));
7441
7570
  if (targets.length === 0) {
7442
7571
  process.stderr.write(`${mark("warn")} no native Caveman integrations are journaled\n`);
@@ -7457,8 +7586,8 @@ function disableNative(argv) {
7457
7586
  return;
7458
7587
  }
7459
7588
  const target = argv[0];
7460
- if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "aider") || argv.length !== 1)
7461
- commandUsage("disable <claude|codex|hermes|gemini|opencode|aider> | disable --all");
7589
+ if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "pi" && target !== "aider") || argv.length !== 1)
7590
+ commandUsage("disable <claude|codex|hermes|gemini|opencode|pi|aider> | disable --all");
7462
7591
  disableNativeAgent(target);
7463
7592
  }
7464
7593
  function nativeIntegrationStatus(agent) {
@@ -7520,6 +7649,9 @@ function nativeIntegrationStatus(agent) {
7520
7649
  else if (operation.kind === "opencode-plugin") {
7521
7650
  owned = current.toString("utf8").includes("caveman:native-opencode");
7522
7651
  }
7652
+ else if (operation.kind === "pi-extension") {
7653
+ owned = current.toString("utf8").includes("caveman:native-pi");
7654
+ }
7523
7655
  else if (operation.kind === "aider-config") {
7524
7656
  const text = current.toString("utf8");
7525
7657
  owned = typeof operation.owned?.route_block === "string" && typeof operation.owned?.read_block === "string"
@@ -7548,13 +7680,30 @@ function nativeIntegrationStatus(agent) {
7548
7680
  const coreResolution = runtimeConfig.resolution.values["think.core"];
7549
7681
  const coreConfigured = coreResolution.value === true;
7550
7682
  const mcp = probeMcpBinary();
7551
- const expectedRoute = appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "aider" ? "/w/aider/openai/v1" : detectCodexWrapAuthMode() === "subscription" ? "/chatgpt" : "/w/codex");
7552
- const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : "aider-config";
7683
+ const expectedRoute = appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : agent === "aider" ? "/w/aider/openai/v1" : detectCodexWrapAuthMode() === "subscription" ? "/chatgpt" : "/w/codex");
7684
+ 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";
7553
7685
  const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
7686
+ // Pi's artifact encodes no route: the extension resolves the gateway at
7687
+ // runtime through the same env → config → default chain as gatewayURL(), so
7688
+ // route drift between enable and now cannot happen. What CAN drift is the
7689
+ // bundle itself after a CLI upgrade — require the on-disk artifact to end
7690
+ // with the currently shipped bundle bytes so `doctor pi --fix` sees it.
7691
+ const piBundleCurrent = agent !== "pi" || (() => {
7692
+ const current = routeOperation ? fileBytes(routeOperation.file) : null;
7693
+ if (!current)
7694
+ return false;
7695
+ try {
7696
+ const shipped = readFileSync(resolvePiExtension());
7697
+ return current.length >= shipped.length && current.subarray(current.length - shipped.length).equals(shipped);
7698
+ }
7699
+ catch {
7700
+ return false;
7701
+ }
7702
+ })();
7554
7703
  const routeHealthy = ownedHealthy && (agent === "opencode"
7555
7704
  ? routeOperation?.owned?.routes?.openai === appendUrlPath(expectedRoute, "/openai/v1")
7556
7705
  && routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
7557
- : routeOperation?.owned?.route === expectedRoute);
7706
+ : agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
7558
7707
  const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
7559
7708
  const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
7560
7709
  const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy ? "degraded" : "installed";
@@ -7564,11 +7713,11 @@ function nativeIntegrationStatus(agent) {
7564
7713
  : coreSupported && nativeCoreRuntimeState().active;
7565
7714
  const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
7566
7715
  const components = {
7567
- 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") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
7716
+ 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)),
7568
7717
  lifecycle_hooks: agent !== "aider" && ownedHealthy,
7569
7718
  core: coreActive,
7570
7719
  mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
7571
- tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" ? false : fileText.includes("shrink-hook")),
7720
+ tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" ? false : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes("shrink-hook")),
7572
7721
  shared_runtime: proxyHealthy,
7573
7722
  };
7574
7723
  const versionStatus = nativeVersionStatus(host.version, profile.tested_agent_version);
@@ -7651,8 +7800,8 @@ function genericIntegrationStatus(runtimeReachable) {
7651
7800
  async function nativeDoctor(argv) {
7652
7801
  const fix = argv.includes("--fix");
7653
7802
  const target = argv.find((arg) => arg !== "--fix");
7654
- if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "aider" && target !== "generic") || argv.length !== (fix ? 2 : 1) || (fix && target === "generic"))
7655
- commandUsage("doctor <claude|codex|hermes|gemini|opencode|aider|generic> [--fix]");
7803
+ if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "pi" && target !== "aider" && target !== "generic") || argv.length !== (fix ? 2 : 1) || (fix && target === "generic"))
7804
+ commandUsage("doctor <claude|codex|hermes|gemini|opencode|pi|aider|generic> [--fix]");
7656
7805
  if (target === "generic") {
7657
7806
  const { host, port } = gatewayHostPort();
7658
7807
  const result = genericIntegrationStatus(await portListening(host, port));
@@ -8106,7 +8255,10 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
8106
8255
  throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
8107
8256
  }
8108
8257
  const renderedGw = agent ? attributedGatewayUrl(gw, agent) : gw;
8109
- const env = { ...process.env, ...wrapBaseUrlEnv(renderedGw) };
8258
+ const env = {
8259
+ ...process.env,
8260
+ ...(agent?.injection.method === "native-extension" ? {} : wrapBaseUrlEnv(renderedGw)),
8261
+ };
8110
8262
  if (wrapMode(gw) === "managed") {
8111
8263
  const gatewayKey = connectedGatewayAPIKey();
8112
8264
  if (gatewayKey)
@@ -9281,6 +9433,14 @@ function queueStaleMcpBinary(probe) {
9281
9433
  function wrapMcpRecoveryAvailable(agent, opts) {
9282
9434
  if (!wrapRecoveryEligible(opts) || !agent)
9283
9435
  return false;
9436
+ if (agent.id === "pi") {
9437
+ const compatibility = probeMcpBinary();
9438
+ if (!compatibility)
9439
+ return false;
9440
+ if (!compatibility.probe.current)
9441
+ queueStaleMcpBinary(compatibility.probe);
9442
+ return compatibility.probe.current;
9443
+ }
9284
9444
  // Two independent sources of a real caveman_retrieve: a marker from
9285
9445
  // `caveman tools mcp install`, or the profile's own config-file overlay. The
9286
9446
  // second only counts under `auto`, because that is exactly when buildWrapEnv
@@ -9335,6 +9495,25 @@ function resolveDelegateMcpCommand() {
9335
9495
  const script = candidates.find((c) => existsSync(c));
9336
9496
  return script ? { command: process.execPath, args: [script] } : null;
9337
9497
  }
9498
+ function resolvePiExtension() {
9499
+ const extension = process.env.CAVEMAN_PI_EXTENSION?.trim()
9500
+ || join(dirname(fileURLToPath(import.meta.url)), "caveman-pi-extension.mjs");
9501
+ if (!existsSync(extension)) {
9502
+ throw new Error(`Pi extension not found at ${extension}; set CAVEMAN_PI_EXTENSION or run the CLI build step`);
9503
+ }
9504
+ return extension;
9505
+ }
9506
+ function buildPiWrapArgs(cmdArgs, env, gw) {
9507
+ const extension = resolvePiExtension();
9508
+ const { cmd, pre } = cavemanInvocation();
9509
+ env.CAVEMAN_PI_HOOK_CMD = JSON.stringify([cmd, ...pre]);
9510
+ env.CAVE_GATEWAY_URL = gw;
9511
+ // The profile's injection block declares the loader flag; using it here keeps the
9512
+ // compiled registry the single source of truth for how the asset is loaded.
9513
+ const profile = AGENTS.find((a) => a.id === "pi");
9514
+ const loaderFlag = profile?.injection.method === "native-extension" ? profile.injection.loader_flag : "--extension";
9515
+ return [loaderFlag, extension, ...cmdArgs];
9516
+ }
9338
9517
  const HERMES_MCP_BEGIN = "# >>> caveman:mcp";
9339
9518
  const HERMES_MCP_END = "# <<< caveman:mcp";
9340
9519
  const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
@@ -10810,7 +10989,7 @@ function nativeWhy(argv) {
10810
10989
  // never cross the adapter boundary. Any malformed input/write failure stays
10811
10990
  // fail-open and emits no blocking decision.
10812
10991
  async function nativeHook(argv) {
10813
- const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" ? argv[0] : undefined;
10992
+ const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" || argv[0] === "pi" ? argv[0] : undefined;
10814
10993
  if (!agent)
10815
10994
  process.exit(0);
10816
10995
  let raw;
@@ -10935,7 +11114,7 @@ async function nativeHook(argv) {
10935
11114
  hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: runtimeResponse.output_replacement },
10936
11115
  }));
10937
11116
  }
10938
- else if (policyMode !== "record" && agent === "opencode" && normalizedEvent === "PostToolUse" && runtimeResponse) {
11117
+ else if (policyMode !== "record" && (agent === "opencode" || agent === "pi") && (normalizedEvent === "PostToolUse" || normalizedEvent === "PostToolUseFailure") && runtimeResponse) {
10939
11118
  process.stdout.write(JSON.stringify(runtimeResponse));
10940
11119
  }
10941
11120
  }
@@ -11056,11 +11235,15 @@ function expandTilde(p) {
11056
11235
  // commandHookKind classifies an agent's command-output hook surface so callers can
11057
11236
  // speak about it honestly: "hard" = a deterministic pre-exec command rewrite (RTK
11058
11237
  // parity), "soft" = a model nudge in an auto-read instructions file (best-effort,
11059
- // not a rewrite), "none" = no surface we can install (manual `caveman shrink` only).
11238
+ // not a rewrite), "native" = the rewrite ships inside the agent's native
11239
+ // extension (`caveman enable <agent>`), nothing separate to install here,
11240
+ // "none" = no surface we can install (manual `caveman shrink` only).
11060
11241
  function commandHookKind(a) {
11061
11242
  const ch = a.command_hook;
11062
11243
  if (!ch)
11063
11244
  return "none";
11245
+ if (ch.method === "pi-extension")
11246
+ return "native";
11064
11247
  return ch.method === "instruction-note" ? "soft" : "hard";
11065
11248
  }
11066
11249
  function instructionFileForAgent(a) {
@@ -11089,6 +11272,10 @@ function installShrinkHookForAgent(a) {
11089
11272
  return installShrinkPluginHermes();
11090
11273
  case "openclaw-plugin":
11091
11274
  return installShrinkPluginOpenClaw();
11275
+ case "pi-extension":
11276
+ // Pi's rewrite surface IS the native extension (`caveman enable pi`); there is
11277
+ // no separate hook artifact to install here.
11278
+ return false;
11092
11279
  case "instruction-note":
11093
11280
  return installShrinkNote(ch.file);
11094
11281
  }
@@ -11110,6 +11297,9 @@ function removeShrinkHookForAgent(a) {
11110
11297
  return removeShrinkPluginHermes();
11111
11298
  case "openclaw-plugin":
11112
11299
  return removeShrinkPluginOpenClaw();
11300
+ case "pi-extension":
11301
+ // Removed together with the native extension (`caveman disable pi`).
11302
+ return false;
11113
11303
  case "instruction-note":
11114
11304
  return removeShrinkNote(ch.file);
11115
11305
  }
@@ -12035,7 +12225,8 @@ function hooksCmd(rest) {
12035
12225
  else {
12036
12226
  // No agent named: target every known agent with an installable hook surface
12037
12227
  // that is actually present on PATH (mirrors `mcp install`'s detect-all path).
12038
- targets = AGENTS.filter((a) => commandHookKind(a) !== "none" && which(binOf(a)));
12228
+ // "native" surfaces install through `caveman enable <agent>`, not here.
12229
+ targets = AGENTS.filter((a) => commandHookKind(a) !== "none" && commandHookKind(a) !== "native" && which(binOf(a)));
12039
12230
  if (targets.length === 0) {
12040
12231
  console.error("no hookable agents detected on PATH; pass an agent id, e.g. `caveman hooks install claude`");
12041
12232
  process.exit(1);
@@ -12052,6 +12243,9 @@ function hooksCmd(rest) {
12052
12243
  hard++;
12053
12244
  process.stderr.write(`${mark("ok")} ${a.display_name}: ${hookInstalledPhrase(a)}\n`);
12054
12245
  }
12246
+ else if (commandHookKind(a) === "native") {
12247
+ process.stderr.write(`${mark("ok")} ${a.display_name}: command-output rewrite ships with the native extension — run ${cyan(`caveman enable ${a.id}`)}\n`);
12248
+ }
12055
12249
  else if (commandHookKind(a) === "none") {
12056
12250
  process.stderr.write(`${mark("warn")} ${a.display_name}: no automatic command-output hook surface — run noisy commands through ${cyan("caveman shrink -- <cmd>")}\n`);
12057
12251
  }
@@ -12072,6 +12266,10 @@ function hooksCmd(rest) {
12072
12266
  return;
12073
12267
  }
12074
12268
  for (const a of targets) {
12269
+ if (commandHookKind(a) === "native") {
12270
+ process.stderr.write(`${mark("ok")} ${a.display_name}: command-output rewrite ships with the native extension — remove with ${cyan(`caveman disable ${a.id}`)}\n`);
12271
+ continue;
12272
+ }
12075
12273
  const removed = removeShrinkHookForAgent(a);
12076
12274
  try {
12077
12275
  unlinkSync(shrinkHookMarkerPath(a.id));
@@ -13362,6 +13560,13 @@ function usageSecretDir() {
13362
13560
  }
13363
13561
  function readStdin() {
13364
13562
  return new Promise((resolve, reject) => {
13563
+ // No pipe, no input. On a TTY stdin never ends, so `caveman compress` or
13564
+ // `toon encode` typed without a redirect sat there forever looking like a
13565
+ // prompt with nothing to type into.
13566
+ if (process.stdin.isTTY) {
13567
+ reject(new Error("no input on stdin — pipe a file in, e.g. `cat file | caveman …`"));
13568
+ return;
13569
+ }
13365
13570
  const chunks = [];
13366
13571
  process.stdin.on("data", (chunk) => chunks.push(chunk));
13367
13572
  process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
@@ -13755,7 +13960,7 @@ async function status(argv) {
13755
13960
  },
13756
13961
  next,
13757
13962
  };
13758
- const native = ["claude", "codex", "hermes", "gemini", "opencode", "aider"].map((agent) => {
13963
+ const native = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"].map((agent) => {
13759
13964
  const integration = nativeIntegrationStatus(agent);
13760
13965
  return {
13761
13966
  ...integration,
@@ -15100,7 +15305,9 @@ more
15100
15305
  caveman tools local, no account · caveman help tools
15101
15306
  caveman cloud connected · caveman help cloud`;
15102
15307
  function renderedAgentList() {
15103
- const visible = AGENTS.slice(0, 7).map((agent) => agent.id);
15308
+ // 8 fits todays registry on one line; "+N more" would render longer than
15309
+ // the ids it hides.
15310
+ const visible = AGENTS.slice(0, 8).map((agent) => agent.id);
15104
15311
  const remaining = AGENTS.length - visible.length;
15105
15312
  return `${visible.join(" | ")}${remaining > 0 ? ` | +${remaining} more — ${invokedAs()} run` : ""}`;
15106
15313
  }
@@ -78,6 +78,11 @@ function profile() {
78
78
  const mode = policyMode();
79
79
  return mode === "record" ? "record-only" : mode === "max" ? "full-max" : "full-safe";
80
80
  }
81
+ // Return as soon as the accumulated bytes parse as one complete JSON payload
82
+ // instead of waiting for EOF. The host writes one object and closes, but under
83
+ // the Windows pipe implementation that close can lag arbitrarily (#729/#833),
84
+ // and a hook that blocks on EOF spends the host's whole budget waiting for a
85
+ // close it already has all the data for.
81
86
  async function stdin() {
82
87
  const chunks = [];
83
88
  let bytes = 0;
@@ -87,6 +92,15 @@ async function stdin() {
87
92
  if (bytes > 2 * 1024 * 1024)
88
93
  throw new Error("hook payload too large");
89
94
  chunks.push(value);
95
+ const joined = Buffer.concat(chunks);
96
+ // A partial payload throws and we wait for more bytes.
97
+ try {
98
+ JSON.parse(joined.toString("utf8"));
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ return joined;
90
104
  }
91
105
  return Buffer.concat(chunks);
92
106
  }
@@ -378,9 +392,16 @@ function fallback(entry) {
378
392
  }
379
393
  catch { /* host remains fail-open */ }
380
394
  }
395
+ // Budget for the delegated child. This runs inside a host hook, so an
396
+ // unbounded spawnSync could block the user's turn forever if index.js stalls,
397
+ // and on Windows process spawn is ~10x macOS before antivirus (#819) — the
398
+ // double-spawn alone can exceed the host's cap. Cap it below the host's and
399
+ // fall through to the fail-open path on expiry, the way every other subprocess
400
+ // in this package already does (#799).
401
+ const DELEGATE_TIMEOUT_MS = 3000;
381
402
  function delegateToFullCLI(raw, agent) {
382
403
  const cli = join(dirname(fileURLToPath(import.meta.url)), "index.js");
383
- const result = spawnSync(process.execPath, [cli, "native-hook", agent], { input: raw, maxBuffer: 3 * 1024 * 1024, env: process.env });
404
+ const result = spawnSync(process.execPath, [cli, "native-hook", agent], { input: raw, maxBuffer: 3 * 1024 * 1024, env: process.env, timeout: DELEGATE_TIMEOUT_MS });
384
405
  if (!result.error && result.status === 0) {
385
406
  if (result.stdout?.length)
386
407
  process.stdout.write(result.stdout);
@@ -390,7 +411,7 @@ function delegateToFullCLI(raw, agent) {
390
411
  }
391
412
  async function main() {
392
413
  const agentArg = process.argv[2] === "native-hook" ? process.argv[3] : process.argv[2];
393
- const agent = agentArg === "claude" || agentArg === "codex" || agentArg === "hermes" || agentArg === "gemini" || agentArg === "opencode" ? agentArg : undefined;
414
+ const agent = agentArg === "claude" || agentArg === "codex" || agentArg === "hermes" || agentArg === "gemini" || agentArg === "opencode" || agentArg === "pi" ? agentArg : undefined;
394
415
  if (!agent)
395
416
  return;
396
417
  let raw;
@@ -449,7 +470,7 @@ async function main() {
449
470
  else if (mode !== "record" && agent === "claude" && eventName === "PostToolUse" && response?.output_replacement) {
450
471
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: response.output_replacement } }));
451
472
  }
452
- else if (mode !== "record" && agent === "opencode" && eventName === "PostToolUse" && response) {
473
+ else if (mode !== "record" && (agent === "opencode" || agent === "pi") && (eventName === "PostToolUse" || eventName === "PostToolUseFailure") && response) {
453
474
  process.stdout.write(JSON.stringify(response));
454
475
  }
455
476
  }