@caveman-ai/cli 4.0.0 → 4.0.1

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.
@@ -64,10 +64,10 @@ export const PROFILES = [
64
64
  "attribution": {
65
65
  "header": "x-cave-agent"
66
66
  },
67
- "tested_agent_version": "2.1.291",
67
+ "tested_agent_version": "2.1.296",
68
68
  "injection_completeness": "builder-assisted",
69
- "last_verified_at": "2026-10-06",
70
- "verified_by": "local pinned-binary probe (claude 2.1.291 on Node 22.22.2, agents/probe-installed.mjs)",
69
+ "last_verified_at": "2026-10-10",
70
+ "verified_by": "local pinned-binary probe (claude 2.1.296 on Node 22.22.0, agents/probe-installed.mjs); route probe: ANTHROPIC_BASE_URL redirection observed reaching POST /v1/messages?beta=true",
71
71
  "fallback": "generic-env",
72
72
  "maintainer": null
73
73
  },
@@ -101,10 +101,10 @@ export const PROFILES = [
101
101
  "attribution": {
102
102
  "header": "x-cave-agent"
103
103
  },
104
- "tested_agent_version": "0.160.1",
104
+ "tested_agent_version": "0.162.1",
105
105
  "injection_completeness": "code-only",
106
- "last_verified_at": "2026-10-06",
107
- "verified_by": "local pinned-binary probe (codex 0.160.1 on Node 24.16.0, agents/probe-installed.mjs)",
106
+ "last_verified_at": "2026-10-10",
107
+ "verified_by": "local pinned-binary probe (codex 0.162.1 on Node 22.22.0, agents/probe-installed.mjs)",
108
108
  "fallback": "generic-env",
109
109
  "maintainer": null
110
110
  },
@@ -133,10 +133,10 @@ export const PROFILES = [
133
133
  "attribution": {
134
134
  "header": "x-cave-agent"
135
135
  },
136
- "tested_agent_version": "0.62.0",
136
+ "tested_agent_version": "0.63.0",
137
137
  "injection_completeness": "declarative",
138
- "last_verified_at": "2026-10-03",
139
- "verified_by": "local pinned-binary probe (gemini 0.62.0 on Node 24.16.0, agents/probe-installed.mjs)",
138
+ "last_verified_at": "2026-10-07",
139
+ "verified_by": "local pinned-binary probe (gemini 0.63.0 on Node 22.22.0, agents/probe-installed.mjs); route probe: GOOGLE_GEMINI_BASE_URL redirection observed reaching POST /v1beta/models/{model}:streamGenerateContent",
140
140
  "fallback": "generic-env",
141
141
  "maintainer": null
142
142
  },
@@ -186,7 +186,7 @@ export const PROFILES = [
186
186
  "kilocode"
187
187
  ],
188
188
  "args": [],
189
- "install": "npm install -g @kilocode/cli@7.8.3",
189
+ "install": "npm install -g @kilocode/cli@7.8.8",
190
190
  "wire_protocol": "openai-chat",
191
191
  "injection": {
192
192
  "method": "config-env-content",
@@ -272,10 +272,10 @@ export const PROFILES = [
272
272
  "attribution": {
273
273
  "header": "X-Cave-Agent"
274
274
  },
275
- "tested_agent_version": "7.8.3",
275
+ "tested_agent_version": "7.8.8",
276
276
  "injection_completeness": "declarative",
277
- "last_verified_at": "2026-10-03",
278
- "verified_by": "local pinned-binary probe (kilo 7.8.3 on Node 24.16.0, agents/probe-installed.mjs)",
277
+ "last_verified_at": "2026-10-08",
278
+ "verified_by": "local pinned-binary route probe (kilo 7.8.8 on Node 22.22.0, agents/probe-installed.mjs); KILO_CONFIG_CONTENT overlay accepted and applied — POST /v1/chat/completions observed at the injected baseURL carrying X-Cave-Agent: kilo",
279
279
  "fallback": "generic-env",
280
280
  "maintainer": null
281
281
  },
@@ -427,10 +427,10 @@ export const PROFILES = [
427
427
  "attribution": {
428
428
  "header": "X-Cave-Agent"
429
429
  },
430
- "tested_agent_version": "1.18.34",
430
+ "tested_agent_version": "1.19.0",
431
431
  "injection_completeness": "declarative",
432
- "last_verified_at": "2026-10-03",
433
- "verified_by": "local pinned-binary probe (opencode 1.18.34 on Node 24.16.0, agents/probe-installed.mjs)",
432
+ "last_verified_at": "2026-10-11",
433
+ "verified_by": "local pinned-binary probe (opencode 1.19.0 on Node 22.22.0, agents/probe-installed.mjs); route probe: this profile's own config_content.local overlay loaded and POST /v1/responses reached the injected baseURL carrying X-Cave-Agent: opencode, run completed (exit 0)",
434
434
  "fallback": "generic-env",
435
435
  "maintainer": null
436
436
  },
@@ -474,7 +474,7 @@ export const PROFILES = [
474
474
  "args": [
475
475
  "--extensions=none"
476
476
  ],
477
- "install": "npm i -g @qwen-code/qwen-code@0.25.0",
477
+ "install": "npm i -g @qwen-code/qwen-code@0.25.1",
478
478
  "wire_protocol": "openai-chat",
479
479
  "injection": {
480
480
  "method": "config-file",
@@ -720,10 +720,10 @@ export const PROFILES = [
720
720
  "attribution": {
721
721
  "header": "X-Cave-Agent"
722
722
  },
723
- "tested_agent_version": "0.25.0",
723
+ "tested_agent_version": "0.25.1",
724
724
  "injection_completeness": "declarative",
725
- "last_verified_at": "2026-10-06",
726
- "verified_by": "local pinned-binary probe (@qwen-code/qwen-code 0.25.0 on Node 24.16.0, agents/probe-installed.mjs) plus route check: the real binary, launched with the CLI buildWrapEnv overlay, sent POST /w/qwen/v1/chat/completions (X-Cave-Agent: qwen, model gpt-5.5) to a loopback recorder",
725
+ "last_verified_at": "2026-10-12",
726
+ "verified_by": "local pinned-binary probe (@qwen-code/qwen-code 0.25.1 on Node 22.22.0, agents/probe-installed.mjs: --version and --help both exit 0) plus config_overlay acceptance: unwrapped, 0.25.1 refuses a non-interactive run with \"No auth type is selected\"; launched through the CLI buildWrapEnv overlay that refusal is gone, so it read security.auth from the injected system-settings. The outbound POST was NOT re-observed at 0.25.1 — the wrapped non-interactive run did not produce a model request against a loopback recorder in this container — so the route claim stands only at 0.25.0, where it was observed as POST /w/qwen/v1/chat/completions (X-Cave-Agent: qwen, model gpt-5.5)",
727
727
  "fallback": "generic-env",
728
728
  "maintainer": null
729
729
  }
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/gen-binaries.mjs. Do not edit.
2
- export const BINARY_RELEASE = "bin-v4.0.0";
2
+ export const BINARY_RELEASE = "bin-v4.0.1";
3
3
  export const BINARY_RELEASE_BASE_DEFAULT = "https://github.com/JuliusBrussee/caveman/releases/download";
4
4
  export const BINARY_SIGNING_PUBKEY = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKR5zq0dz0mTUtkiX0b6jqtyG3uQV\n89PGD2n9UBV1ikbhu0f1c+vHtcN9mk6wKzyBLdEPudI/Jnvci+8OAen/vw==\n-----END PUBLIC KEY-----\n";
@@ -278,6 +278,14 @@ function hostOf(url) {
278
278
  return void 0;
279
279
  }
280
280
  }
281
+ function targetsGateway(gateway, url) {
282
+ if (!url) return false;
283
+ try {
284
+ return new URL(url).origin === new URL(gateway).origin;
285
+ } catch {
286
+ return false;
287
+ }
288
+ }
281
289
  var COMPAT_NAME_RE2 = /^[a-z0-9][a-z0-9._-]{0,63}$/;
282
290
  function compatUpstreamFor(provider, compatUpstreams) {
283
291
  if (!compatUpstreams || !COMPAT_NAME_RE2.test(provider)) return void 0;
@@ -367,7 +375,7 @@ var HookBridge = class {
367
375
  const child = execFile(
368
376
  portable.command,
369
377
  portable.args,
370
- { timeout: event === "SessionStart" ? SESSION_START_TIMEOUT_MS : HOOK_TIMEOUT_MS, maxBuffer: HOOK_MAX_BUFFER, encoding: "utf8" },
378
+ { timeout: event === "SessionStart" ? SESSION_START_TIMEOUT_MS : HOOK_TIMEOUT_MS, maxBuffer: HOOK_MAX_BUFFER, encoding: "utf8", windowsHide: true },
371
379
  (error, stdout) => {
372
380
  const timedOut = !!error && error.killed === true;
373
381
  if (error && stdout === "") return resolve2(timedOut ? void 0 : TRY_NEXT);
@@ -587,7 +595,8 @@ var ProviderRouter = class {
587
595
  this.warnedModels.add(key);
588
596
  const mount = compatUpstreamFor(model.provider, this.compatUpstreams);
589
597
  const expected = mount !== void 0 ? hostOf(mount) : upstreamHostFor(model.provider);
590
- const reason = authIssue ?? compatibilityIssue ?? headerIssue ?? (expected === void 0 ? `no compat mount named "${model.provider}" in the local proxy; add compat.${model.provider}.base_url to caveman.yaml to route it` : hostOf(original) !== expected ? `provider endpoint ${hostOf(original) ?? original} is not ${expected}` : `provider endpoint path or API "${model.provider}/${model.api}" is not verified by the running proxy`);
598
+ const host = hostOf(original);
599
+ const reason = authIssue ?? compatibilityIssue ?? headerIssue ?? (!host ? `provider endpoint "${original}" is not an HTTP URL; this provider sends no routable request` : targetsGateway(this.gateway, original) ? `provider baseUrl ${original} points at the Caveman proxy itself, so no mount can carry it; set it to the real upstream and add compat.${model.provider}.base_url to caveman.yaml to route it` : expected === void 0 ? `no compat mount named "${model.provider}" in the local proxy; add compat.${model.provider}.base_url to caveman.yaml to route it` : host !== expected ? `provider endpoint ${host} is not ${expected}` : `provider endpoint path or API "${model.provider}/${model.api}" is not verified by the running proxy`);
591
600
  this.notify(boundedString(`Caveman: pass-through for ${key} (${reason}); no compression`, MAX_MESSAGE_BYTES), "warning");
592
601
  }
593
602
  return;
@@ -604,7 +613,7 @@ var ProviderRouter = class {
604
613
  hadCompat: Object.hasOwn(model, "compat")
605
614
  };
606
615
  const compat = compatForRoutedModel(model);
607
- if (!await this.pi.setModel({ ...model, baseUrl: route, ...compat === void 0 ? {} : { compat } })) {
616
+ if (!await this.setModelKeepingThinking({ ...model, baseUrl: route, ...compat === void 0 ? {} : { compat } })) {
608
617
  if (await this.restoreCurrentModel(ctx)) {
609
618
  this.notify("Caveman: direct mode, no compression this session (model selection failed)", "warning");
610
619
  }
@@ -621,6 +630,15 @@ var ProviderRouter = class {
621
630
  isOwnedRoute(model) {
622
631
  return !!model && !!this.routed && model.provider === this.routed.provider && model.id === this.routed.id && model.baseUrl === this.routed.route;
623
632
  }
633
+ // Pi's setModel re-derives the thinking level from settings, which would drop
634
+ // a `--thinking high` or a resumed session's level every time we re-point the
635
+ // model. Same model, so the level the user had is still valid: put it back.
636
+ async setModelKeepingThinking(model) {
637
+ const level = this.pi.getThinkingLevel?.();
638
+ const ok = await this.pi.setModel(model);
639
+ if (ok && level !== void 0) this.pi.setThinkingLevel?.(level);
640
+ return ok;
641
+ }
624
642
  async restoreCurrentModel(ctx) {
625
643
  const current = ctx.model;
626
644
  if (!this.isOwnedRoute(current)) {
@@ -634,7 +652,7 @@ var ProviderRouter = class {
634
652
  const wasApplying = this.applying;
635
653
  this.applying = true;
636
654
  try {
637
- if (await this.pi.setModel(direct)) {
655
+ if (await this.setModelKeepingThinking(direct)) {
638
656
  this.routed = void 0;
639
657
  return true;
640
658
  }
@@ -771,7 +789,7 @@ var RecoveryClient = class {
771
789
  return new Promise((resolve2) => {
772
790
  const portable = this.invocation(["version", "--json"]);
773
791
  if (!portable) return resolve2(false);
774
- execFile2(portable.command, portable.args, { timeout: PROBE_TIMEOUT_MS, encoding: "utf8" }, (error, stdout) => {
792
+ execFile2(portable.command, portable.args, { timeout: PROBE_TIMEOUT_MS, encoding: "utf8", windowsHide: true }, (error, stdout) => {
775
793
  if (error) return resolve2(false);
776
794
  try {
777
795
  const parsed = JSON.parse(stdout);
@@ -788,7 +806,7 @@ var RecoveryClient = class {
788
806
  try {
789
807
  const portable = this.invocation([]);
790
808
  if (!portable) return false;
791
- child = spawn(portable.command, portable.args, { stdio: ["pipe", "pipe", "ignore"] });
809
+ child = spawn(portable.command, portable.args, { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
792
810
  } catch {
793
811
  return false;
794
812
  }
@@ -804,7 +822,7 @@ var RecoveryClient = class {
804
822
  await this.call("initialize", {
805
823
  protocolVersion: "2024-11-05",
806
824
  capabilities: {},
807
- clientInfo: { name: "caveman-pi-extension", version: "0.3.0" }
825
+ clientInfo: { name: "caveman-pi-extension", version: "0.3.1" }
808
826
  }, void 0, INIT_TIMEOUT_MS);
809
827
  this.notify("notifications/initialized");
810
828
  if (this.disposed) {
@@ -1121,14 +1139,15 @@ function index_default(pi) {
1121
1139
  }));
1122
1140
  pi.on("before_agent_start", GUARD_before_agent_start(async (event, ctx) => {
1123
1141
  if (gateDone) await router?.apply(ctx.model, ctx);
1142
+ const prompt = event.prompt ?? "";
1124
1143
  const response = await bridge.call("UserPromptSubmit", {
1125
1144
  session_id: sessionId,
1126
1145
  model: ctx.model?.id,
1127
1146
  provider: ctx.model?.provider,
1128
- prompt: promptDigest(event.prompt),
1129
- task_type: taskType(event.prompt),
1130
- task_terms: taskTerms(event.prompt),
1131
- task_continuation: taskContinuation(event.prompt)
1147
+ prompt: promptDigest(prompt),
1148
+ task_type: taskType(prompt),
1149
+ task_terms: taskTerms(prompt),
1150
+ task_continuation: taskContinuation(prompt)
1132
1151
  });
1133
1152
  const dynamic = [additionalContextOf(response), ...pendingContext].filter(Boolean);
1134
1153
  pendingContext = [];
@@ -1157,7 +1176,14 @@ function index_default(pi) {
1157
1176
  pendingBytes += bytes;
1158
1177
  }
1159
1178
  }));
1160
- pi.on("tool_result", GUARD_tool_result((event) => event.toolName === RECOVERY_TOOL ? void 0 : shrinkToolResult(bridge, sessionId, event, recovery)));
1179
+ const recoveryCallable = () => {
1180
+ try {
1181
+ return typeof pi.getActiveTools === "function" && pi.getActiveTools().includes(RECOVERY_TOOL);
1182
+ } catch {
1183
+ return false;
1184
+ }
1185
+ };
1186
+ pi.on("tool_result", GUARD_tool_result((event) => event.toolName === RECOVERY_TOOL || !recoveryCallable() ? void 0 : shrinkToolResult(bridge, sessionId, event, recovery)));
1161
1187
  pi.on("session_before_compact", GUARD_session_before_compact(() => {
1162
1188
  void bridge.call("PreCompact", { session_id: sessionId });
1163
1189
  }));
package/dist/index.js CHANGED
@@ -4573,44 +4573,46 @@ function proxyYamlMode() {
4573
4573
  // through Claude Code's own escape hatch. Never overrides a value the user
4574
4574
  // already set, and never asserts when the upstream cannot be verified.
4575
4575
  const CLAUDE_ASSUME_FIRST_PARTY_ENV = "_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL";
4576
- // yamlProviderBaseUrl scans an indentation-nested `providers.<name>.base_url`
4577
- // key without a YAML dependency (the published CLI has zero runtime deps).
4578
- // Returns the value when found, null when the providers/<name> block or key is
4579
- // absent, and undefined when the document uses a shape the scan cannot follow
4580
- // (flow-style `{...}` blocks) — callers must treat undefined as unverifiable.
4581
- function yamlProviderBaseUrl(raw, provider) {
4576
+ // yamlScopedBaseUrl scans an indentation-nested `<group>.<name>.base_url` key
4577
+ // without a YAML dependency (the published CLI has zero runtime deps). Returns
4578
+ // the value when found, null when the group/<name> block or key is absent, and
4579
+ // undefined when the document uses a shape the scan cannot follow (flow-style
4580
+ // `{...}` blocks) — callers must treat undefined as unverifiable. `providers`
4581
+ // answers which upstream the proxy forwards to; `compat` answers whether a
4582
+ // user-defined mount exists at all (#1254).
4583
+ function yamlScopedBaseUrl(raw, group, name) {
4582
4584
  const lines = raw.split(/\r?\n/);
4583
- let providersIndent = -1;
4584
- let providerIndent = -1;
4585
+ let groupIndent = -1;
4586
+ let nameIndent = -1;
4585
4587
  for (const line of lines) {
4586
4588
  const code = line.split("#", 1)[0];
4587
4589
  if (!code.trim())
4588
4590
  continue;
4589
4591
  const indent = code.length - code.trimStart().length;
4590
4592
  const keyMatch = code.trim().match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
4591
- if (providersIndent !== -1 && indent <= providersIndent)
4592
- providersIndent = -1;
4593
- if (providerIndent !== -1 && indent <= providerIndent)
4594
- providerIndent = -1;
4593
+ if (groupIndent !== -1 && indent <= groupIndent)
4594
+ groupIndent = -1;
4595
+ if (nameIndent !== -1 && indent <= nameIndent)
4596
+ nameIndent = -1;
4595
4597
  if (!keyMatch)
4596
4598
  continue;
4597
4599
  const key = keyMatch[1];
4598
4600
  const rest = keyMatch[2] ?? "";
4599
4601
  if (rest.startsWith("{") || rest.startsWith("[")) {
4600
- // Flow-style collections keep their children on this line; a providers
4602
+ // Flow-style collections keep their children on this line; a group
4601
4603
  // subtree written that way is beyond this scan, so report unverifiable.
4602
- if (key === "providers" || providersIndent !== -1)
4604
+ if (key === group || groupIndent !== -1)
4603
4605
  return undefined;
4604
4606
  continue;
4605
4607
  }
4606
- if (providerIndent !== -1 && key === "base_url") {
4608
+ if (nameIndent !== -1 && key === "base_url") {
4607
4609
  const value = rest.replace(/^["']|["']\s*$/g, "").trim();
4608
4610
  return value || null;
4609
4611
  }
4610
- if (providersIndent !== -1 && key === provider && providerIndent === -1)
4611
- providerIndent = indent;
4612
- else if (key === "providers" && providersIndent === -1 && providerIndent === -1 && indent === 0)
4613
- providersIndent = indent;
4612
+ if (groupIndent !== -1 && key === name && nameIndent === -1)
4613
+ nameIndent = indent;
4614
+ else if (key === group && groupIndent === -1 && nameIndent === -1 && indent === 0)
4615
+ groupIndent = indent;
4614
4616
  }
4615
4617
  return null;
4616
4618
  }
@@ -4633,7 +4635,7 @@ function proxyUpstreamIsFirstParty(provider, host) {
4633
4635
  catch (e) {
4634
4636
  return e?.code === "ENOENT";
4635
4637
  }
4636
- const override = yamlProviderBaseUrl(raw, provider);
4638
+ const override = yamlScopedBaseUrl(raw, "providers", provider);
4637
4639
  if (override === undefined)
4638
4640
  return false;
4639
4641
  if (override === null)
@@ -5407,6 +5409,16 @@ function refreshWrapEntitlementInBackground(options = {}) {
5407
5409
  /* never surface a background rejection */
5408
5410
  });
5409
5411
  }
5412
+ // The refresh outcome and the weekly run claim belong to the credential they ran
5413
+ // under. Login and logout replace that credential, so they drop both: native
5414
+ // wiring never runs the background refresh, and a stale failure would keep
5415
+ // status on "account refresh offline" for good.
5416
+ function dropWrapRefreshState() {
5417
+ mutateRawConfig((out) => {
5418
+ delete out.wrapEntitlementRefresh;
5419
+ delete out.wrapEntitlementRunRefreshWeek;
5420
+ });
5421
+ }
5410
5422
  // ── wrap-start + session-end lines (the §8 golden transcripts) ───────────────────
5411
5423
  // SUBSCRIPTION_TOKENS_ONLY_NOTE is the single honesty line for locally compressed
5412
5424
  // subscription/OAuth sessions. A Claude Pro/Max seat has no per-token price, and an
@@ -8893,6 +8905,10 @@ function call(event, payload = {}) {
8893
8905
  encoding: "utf8",
8894
8906
  timeout: 2000,
8895
8907
  maxBuffer: 2 * 1024 * 1024,
8908
+ // A host with no console of its own — OpenCode under a multiplexer or a
8909
+ // GUI launcher — makes Windows give every console child a NEW console
8910
+ // window, so the user sees one flash per event. Ignored off Windows.
8911
+ windowsHide: true,
8896
8912
  });
8897
8913
  if (!raw.trim()) return undefined;
8898
8914
  const value = JSON.parse(raw);
@@ -9014,6 +9030,7 @@ export const CavemanNative = async () => ({
9014
9030
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command: output.args.command } }),
9015
9031
  encoding: "utf8",
9016
9032
  timeout: 750,
9033
+ windowsHide: true,
9017
9034
  });
9018
9035
  const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
9019
9036
  if (typeof rewritten === "string" && rewritten) output.args.command = rewritten;
@@ -9063,6 +9080,10 @@ function call(event, payload = {}) {
9063
9080
  encoding: "utf8",
9064
9081
  timeout: 2000,
9065
9082
  maxBuffer: 2 * 1024 * 1024,
9083
+ // A host with no console of its own — OpenCode under a multiplexer or a
9084
+ // GUI launcher — makes Windows give every console child a NEW console
9085
+ // window, so the user sees one flash per event. Ignored off Windows.
9086
+ windowsHide: true,
9066
9087
  });
9067
9088
  if (!raw.trim()) return undefined;
9068
9089
  const value = JSON.parse(raw);
@@ -9219,6 +9240,7 @@ export default {
9219
9240
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
9220
9241
  encoding: "utf8",
9221
9242
  timeout: 750,
9243
+ windowsHide: true,
9222
9244
  });
9223
9245
  const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
9224
9246
  if (typeof rewritten === "string" && rewritten) input.command = rewritten;
@@ -9261,27 +9283,102 @@ function opencodeNativeRoutes(gw) {
9261
9283
  "opencode-go": appendUrlPath(base, "/compat/opencode-go/v1"),
9262
9284
  };
9263
9285
  }
9264
- // Only the journaled providers reach the proxy. Anything else (GitHub Copilot,
9265
- // Zen) goes direct while the install reads healthy (#1190), so name it. Global
9266
- // config only, the same file enable edits; a project opencode.json can still
9267
- // pick another model.
9268
- function opencodeUnroutedActiveProvider(routed) {
9286
+ // proxyCompatMount answers whether the local proxy serves a user-defined
9287
+ // compat mount of this name: the value when caveman.yaml declares one, null
9288
+ // when it demonstrably does not, and undefined when the file cannot be read or
9289
+ // uses a shape the scan cannot follow.
9290
+ function proxyCompatMount(name) {
9291
+ const path = process.env.CAVEMAN_CONFIG ?? join(cavemanHome(), "caveman.yaml");
9292
+ try {
9293
+ return yamlScopedBaseUrl(readFileSync(path, "utf8"), "compat", name);
9294
+ }
9295
+ catch {
9296
+ return undefined;
9297
+ }
9298
+ }
9299
+ // opencodeBaseUrlRouting reads a provider's configured endpoint and answers
9300
+ // where its requests actually go. #1190 asked the install journal, which holds
9301
+ // only the three routes `enable` writes, so a provider the user routed by hand
9302
+ // — baseURL pointed at the gateway's own /w/opencode wedge — was reported as
9303
+ // going direct and "not compressed or counted" while the proxy was recording
9304
+ // every one of its requests (#1254). The endpoint is the evidence; the name
9305
+ // never was.
9306
+ //
9307
+ // Origin plus the wedge prefix is the whole test, which covers the built-in
9308
+ // /openai/v1 and /anthropic/v1 paths and any deeper one without enumerating
9309
+ // them. A /compat/<name>/ path needs its mount to exist as well: without one
9310
+ // the request still reaches the proxy and 404s, which is a different problem
9311
+ // with a different remedy, so it is reported as the missing mount rather than
9312
+ // as going direct.
9313
+ function opencodeBaseUrlRouting(baseUrl, gw) {
9314
+ if (typeof baseUrl !== "string" || !baseUrl)
9315
+ return null;
9316
+ let endpoint;
9317
+ let wedge;
9318
+ try {
9319
+ endpoint = new URL(baseUrl);
9320
+ wedge = new URL(appendUrlPath(gw, "/w/opencode"));
9321
+ }
9322
+ catch {
9323
+ return null;
9324
+ }
9325
+ if (endpoint.origin !== wedge.origin)
9326
+ return null;
9327
+ const prefix = wedge.pathname.replace(/\/+$/, "");
9328
+ const path = endpoint.pathname.replace(/\/+$/, "");
9329
+ if (path !== prefix && !path.startsWith(`${prefix}/`))
9330
+ return null;
9331
+ const mount = path.slice(prefix.length).match(/^\/compat\/([^/]+)/);
9332
+ if (!mount)
9333
+ return { routed: true };
9334
+ const name = decodeURIComponent(mount[1]);
9335
+ // Only a readable config that demonstrably lacks the mount is evidence of
9336
+ // one missing. Unverifiable must not bring the false alarm back in another
9337
+ // spelling: the endpoint already proves these requests are not going direct.
9338
+ return proxyCompatMount(name) === null ? { routed: false, mount: name } : { routed: true };
9339
+ }
9340
+ // Only the journaled providers reach the proxy by default. Anything else
9341
+ // (GitHub Copilot, Zen) goes direct while the install reads healthy (#1190), so
9342
+ // name it — unless the user routed it themselves (#1254). Global config only,
9343
+ // the same file enable edits; a project opencode.json can still pick another
9344
+ // model.
9345
+ function opencodeUnroutedActiveProvider(routed, gw) {
9346
+ const configs = [];
9269
9347
  for (const name of ["opencode.jsonc", "opencode.json"]) {
9270
9348
  try {
9271
- const model = parseJsonc(readFileSync(join(opencodeConfigDir(), name), "utf8"))?.model;
9272
- if (typeof model === "string" && model.includes("/")) {
9273
- const provider = model.slice(0, model.indexOf("/"));
9274
- return routed.includes(provider) ? null : provider;
9275
- }
9349
+ configs.push(objectValue(parseJsonc(readFileSync(join(opencodeConfigDir(), name), "utf8"))));
9276
9350
  }
9277
9351
  catch { /* missing or unreadable: try the next source */ }
9278
9352
  }
9353
+ const verdict = (provider) => {
9354
+ if (routed.includes(provider))
9355
+ return null;
9356
+ // Every candidate config is consulted before answering, so a routed
9357
+ // endpoint in one is never shadowed by a missing mount named in another.
9358
+ let missing = null;
9359
+ for (const config of configs) {
9360
+ const routing = opencodeBaseUrlRouting(objectValue(objectValue(objectValue(config.provider)[provider]).options).baseURL, gw);
9361
+ if (routing?.routed === true)
9362
+ return null;
9363
+ if (routing?.routed === false)
9364
+ missing ??= routing.mount;
9365
+ }
9366
+ return { provider, mount: missing };
9367
+ };
9368
+ for (const config of configs) {
9369
+ const model = config.model;
9370
+ if (typeof model === "string" && model.includes("/"))
9371
+ return verdict(model.slice(0, model.indexOf("/")));
9372
+ }
9279
9373
  // No model pinned: OpenCode picks among signed-in providers, so only a
9280
9374
  // sign-in set with no routed provider at all is a sure miss.
9281
9375
  try {
9282
9376
  const dataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
9283
9377
  const signedIn = Object.keys(JSON.parse(readFileSync(join(dataRoot, "opencode", "auth.json"), "utf8")) ?? {});
9284
- return signedIn.length > 0 && !signedIn.some((id) => routed.includes(id)) ? signedIn[0] : null;
9378
+ if (signedIn.length === 0)
9379
+ return null;
9380
+ const verdicts = signedIn.map((id) => verdict(id));
9381
+ return verdicts.every((item) => item !== null) ? verdicts[0] : null;
9285
9382
  }
9286
9383
  catch {
9287
9384
  return null;
@@ -9347,11 +9444,14 @@ function opencodeNativeMutations(gw, mcpBinary, plan = false) {
9347
9444
  },
9348
9445
  ];
9349
9446
  }
9447
+ // Pi's extension auto-discovery accepts only .ts/.js (isExtensionFile in
9448
+ // pi-coding-agent 0.84.2); a .mjs here would journal fine and never load.
9449
+ function piNativeExtensionPath() {
9450
+ return join(homedir(), ".pi", "agent", "extensions", "caveman-native.js");
9451
+ }
9350
9452
  function piNativeMutations() {
9351
- const extensionDir = join(homedir(), ".pi", "agent", "extensions");
9352
- // Pi's extension auto-discovery accepts only .ts/.js (isExtensionFile in
9353
- // pi-coding-agent 0.84.2); a .mjs here would journal fine and never load.
9354
- const extensionPath = join(extensionDir, "caveman-native.js");
9453
+ const extensionPath = piNativeExtensionPath();
9454
+ const extensionDir = dirname(extensionPath);
9355
9455
  const before = fileBytes(extensionPath);
9356
9456
  if (before && !before.toString("utf8").includes("caveman:native-pi")) {
9357
9457
  throw new Error(`${extensionPath} already exists and is not Caveman-owned; refusing to overwrite it`);
@@ -9737,6 +9837,11 @@ import subprocess
9737
9837
 
9738
9838
  _CAVEMAN_CMD = ${JSON.stringify(cmd)}
9739
9839
  _CAVEMAN_PRE = ${JSON.stringify(pre)}
9840
+ # A Hermes host with no console of its own makes Windows give every console
9841
+ # child a NEW console window, so the user sees one flash per hook call.
9842
+ # subprocess ignores Node's windowsHide, and CREATE_NO_WINDOW is absent off
9843
+ # Windows, so resolve it at run time and pass 0 everywhere else (#1214).
9844
+ _CAVEMAN_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
9740
9845
 
9741
9846
 
9742
9847
  def _digest(value):
@@ -9810,6 +9915,7 @@ def _call(event, payload=None):
9810
9915
  text=True,
9811
9916
  capture_output=True,
9812
9917
  timeout=1,
9918
+ creationflags=_CAVEMAN_NO_WINDOW,
9813
9919
  )
9814
9920
  if proc.returncode != 0 or not proc.stdout.strip():
9815
9921
  return None
@@ -11438,9 +11544,16 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
11438
11544
  }
11439
11545
  if (agent === "opencode" && installed) {
11440
11546
  const routed = Object.keys(routeOperation?.owned?.routes ?? {});
11441
- const unrouted = opencodeUnroutedActiveProvider(routed);
11442
- if (unrouted)
11443
- warnings.push(`OpenCode's active provider "${unrouted}" is not routed through Caveman; its requests go direct and are not compressed or counted (routed: ${routed.join(", ")})`);
11547
+ const unrouted = opencodeUnroutedActiveProvider(routed, gatewayURL());
11548
+ if (unrouted?.mount) {
11549
+ // Already pointed at the proxy, just at a mount the proxy does not
11550
+ // serve: those requests reach Caveman and 404, so naming the mount is
11551
+ // the remedy, not "it goes direct" (#1254).
11552
+ warnings.push(`OpenCode's active provider "${unrouted.provider}" points at the Caveman compat mount "${unrouted.mount}", which the local proxy does not serve; add compat.${unrouted.mount}.base_url to caveman.yaml so those requests can be forwarded`);
11553
+ }
11554
+ else if (unrouted) {
11555
+ warnings.push(`OpenCode's active provider "${unrouted.provider}" is not routed through Caveman; its requests go direct and are not compressed or counted (routed: ${routed.join(", ")})`);
11556
+ }
11444
11557
  }
11445
11558
  for (const root of unwiredProfiles)
11446
11559
  warnings.push(`Claude profile ${root} is not routed through Caveman; run \`caveman enable claude\``);
@@ -11719,6 +11832,7 @@ function shrinkText(text) {
11719
11832
  input: text,
11720
11833
  encoding: "utf8",
11721
11834
  maxBuffer: 64 * 1024 * 1024,
11835
+ windowsHide: true,
11722
11836
  });
11723
11837
  return typeof out === "string" && out.trim() ? out : "";
11724
11838
  }
@@ -12644,6 +12758,7 @@ async function login(argv = [], ui) {
12644
12758
  // credential. Do not print authenticated success or continue the post-login
12645
12759
  // bridge until the control plane has recorded that this CLI stored the bundle.
12646
12760
  await saveConfig(saved);
12761
+ dropWrapRefreshState();
12647
12762
  await grant.acknowledge();
12648
12763
  syncAutoEntries();
12649
12764
  // The first-run screen says these its own way.
@@ -12733,6 +12848,7 @@ async function logout() {
12733
12848
  await saveConfig({ ...cfg, logoutPendingLocalCleanup: true });
12734
12849
  clearToken(cfg.tokenStore);
12735
12850
  await saveConfig({ baseURL: "", token: "" });
12851
+ dropWrapRefreshState();
12736
12852
  syncAutoEntries();
12737
12853
  print({ logged_out: true });
12738
12854
  }
@@ -13145,12 +13261,24 @@ async function syncLocalSavings(cfg) {
13145
13261
  // node:sqlite is built into Node ≥22.13 — still zero runtime deps. Imported
13146
13262
  // lazily so only sync paths ever load it (or pay its experimental warning).
13147
13263
  let DatabaseSync;
13264
+ // Node 22-23 print "ExperimentalWarning: SQLite is an experimental feature"
13265
+ // on first load; drop that one line rather than show it on every sync.
13266
+ const emitWarning = process.emitWarning;
13267
+ process.emitWarning = ((warning, ...rest) => {
13268
+ const type = typeof rest[0] === "string" ? rest[0] : rest[0]?.type;
13269
+ if (type === "ExperimentalWarning" && /SQLite/.test(String(warning?.message ?? warning)))
13270
+ return;
13271
+ emitWarning.call(process, warning, ...rest);
13272
+ });
13148
13273
  try {
13149
13274
  ({ DatabaseSync } = await import("node:sqlite"));
13150
13275
  }
13151
13276
  catch {
13152
13277
  throw new Error(`caveman sync requires Node >= 22.13 (it reads the local spend store via node:sqlite); you are running Node ${process.versions.node}`);
13153
13278
  }
13279
+ finally {
13280
+ process.emitWarning = emitWarning;
13281
+ }
13154
13282
  const db = new DatabaseSync(dbPath, { readOnly: true });
13155
13283
  let rows;
13156
13284
  let key;
@@ -13223,23 +13351,40 @@ async function syncLocalSavings(cfg) {
13223
13351
  return [];
13224
13352
  return directiveInstalls.filter((d) => ms >= d.installedAtMs).map((d) => d.id);
13225
13353
  };
13226
- const body = rows.map((r) => syncRequestSpan(r, rowDirectives(r))).join("\n") + "\n";
13227
- const response = await fetch(`${cfg.baseURL}/api/v1/imports?format=caveman-jsonl`, {
13228
- method: "POST",
13229
- headers: {
13230
- authorization: `Bearer ${cfg.token}`,
13231
- "content-type": "application/octet-stream",
13232
- "x-cave-csrf": "cli",
13233
- },
13234
- body,
13235
- });
13236
- const result = (await response.json().catch(() => ({})));
13237
- if (!response.ok || result.status !== "completed") {
13238
- throw new Error(result.error?.message ?? `sync import failed (${response.status})`);
13239
- }
13240
13354
  const num = (v) => (typeof v === "bigint" ? Number(v) : typeof v === "number" && Number.isFinite(v) ? v : 0);
13241
- const maxId = rows.reduce((m, r) => Math.max(m, num(r.id)), since);
13242
- writeSyncWatermark(key, maxId);
13355
+ // The import endpoint caps a body at 16 MiB, and a long-unsynced store is
13356
+ // larger than that. Upload in id order in batches under the cap, moving the
13357
+ // watermark after each, so a failed batch keeps the ones before it.
13358
+ const maxBytes = Number(process.env.CAVEMAN_SYNC_MAX_BATCH_BYTES) || 8 << 20;
13359
+ for (let start = 0; start < rows.length;) {
13360
+ let body = "";
13361
+ let bytes = 0;
13362
+ let end = start;
13363
+ while (end < rows.length) {
13364
+ const line = syncRequestSpan(rows[end], rowDirectives(rows[end])) + "\n";
13365
+ const size = Buffer.byteLength(line);
13366
+ if (body && bytes + size > maxBytes)
13367
+ break;
13368
+ body += line;
13369
+ bytes += size;
13370
+ end++;
13371
+ }
13372
+ const response = await fetch(`${cfg.baseURL}/api/v1/imports?format=caveman-jsonl`, {
13373
+ method: "POST",
13374
+ headers: {
13375
+ authorization: `Bearer ${cfg.token}`,
13376
+ "content-type": "application/octet-stream",
13377
+ "x-cave-csrf": "cli",
13378
+ },
13379
+ body,
13380
+ });
13381
+ const result = (await response.json().catch(() => ({})));
13382
+ if (!response.ok || result.status !== "completed") {
13383
+ throw new Error(result.error?.message ?? `sync import failed (${response.status})`);
13384
+ }
13385
+ writeSyncWatermark(key, num(rows[end - 1].id));
13386
+ start = end;
13387
+ }
13243
13388
  const tokensSaved = rows.reduce((sum, r) => sum + Math.max(0, num(r.compression_tokens_before) - num(r.compression_tokens_after)), 0);
13244
13389
  const tokenBases = new Set(rows.map((r) => (typeof r.compression_token_count_basis === "string" ? r.compression_token_count_basis : "")).filter(Boolean));
13245
13390
  const tokenCountBasis = tokenBases.size === 0 ? "unavailable" : tokenBases.size === 1 ? [...tokenBases][0] ?? "unavailable" : "mixed";
@@ -13776,6 +13921,15 @@ function buildPiWrapArgs(cmdArgs, env, gw) {
13776
13921
  const { cmd, pre } = cavemanInvocation();
13777
13922
  env.CAVEMAN_PI_HOOK_CMD = JSON.stringify([cmd, ...pre]);
13778
13923
  env.CAVE_GATEWAY_URL = gw;
13924
+ // After `caveman enable pi`, Pi already auto-loads the owned copy. A second
13925
+ // copy registers caveman_retrieve twice, which Pi treats as a fatal startup
13926
+ // error, so the session-only copy stays out.
13927
+ // Only when Pi will really load it: a Caveman-owned file, in the directory Pi
13928
+ // reads, with discovery left on. Otherwise the session copy is the only one.
13929
+ const owned = fileBytes(piNativeExtensionPath())?.toString("utf8").includes("caveman:native-pi");
13930
+ const discovery = !env.PI_CODING_AGENT_DIR && !cmdArgs.some((arg) => arg === "--no-extensions" || arg === "-ne");
13931
+ if (owned && discovery)
13932
+ return cmdArgs;
13779
13933
  // The profile's injection block declares the loader flag; using it here keeps the
13780
13934
  // compiled registry the single source of truth for how the asset is loaded.
13781
13935
  const profile = AGENTS.find((a) => a.id === "pi");
@@ -18104,6 +18258,7 @@ export const CavemanShrink = async () => ({
18104
18258
  const res = execFileSync(${JSON.stringify(cmd)}, ${argv}, {
18105
18259
  input: JSON.stringify({ tool_name: "Bash", tool_input: { command } }),
18106
18260
  encoding: "utf8",
18261
+ windowsHide: true,
18107
18262
  });
18108
18263
  if (!res) return;
18109
18264
  const rewritten = JSON.parse(res)?.hookSpecificOutput?.updatedInput?.command;
@@ -18174,6 +18329,11 @@ import subprocess
18174
18329
 
18175
18330
  _CAVEMAN_CMD = ${JSON.stringify(cmd)}
18176
18331
  _CAVEMAN_PRE = ${JSON.stringify(pre)}
18332
+ # A Hermes host with no console of its own makes Windows give every console
18333
+ # child a NEW console window, so the user sees one flash per hook call.
18334
+ # subprocess ignores Node's windowsHide, and CREATE_NO_WINDOW is absent off
18335
+ # Windows, so resolve it at run time and pass 0 everywhere else (#1214).
18336
+ _CAVEMAN_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
18177
18337
 
18178
18338
 
18179
18339
  def _argv(*tail):
@@ -18198,6 +18358,7 @@ def _eligible(command):
18198
18358
  text=True,
18199
18359
  capture_output=True,
18200
18360
  timeout=10,
18361
+ creationflags=_CAVEMAN_NO_WINDOW,
18201
18362
  )
18202
18363
  return proc.returncode == 0 and bool((proc.stdout or "").strip())
18203
18364
  except Exception:
@@ -18221,6 +18382,7 @@ def _transform_terminal_output(command=None, output=None, **kwargs):
18221
18382
  text=True,
18222
18383
  capture_output=True,
18223
18384
  timeout=_int_env("CAVE_HERMES_SHRINK_TIMEOUT_SECONDS", 60),
18385
+ creationflags=_CAVEMAN_NO_WINDOW,
18224
18386
  )
18225
18387
  if proc.returncode != 0 or not proc.stdout:
18226
18388
  return None
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caveman-ai/cli",
3
- "version": "4.0.0",
3
+ "version": "4.0.1",
4
4
  "description": "Caveman CLI — wrap coding agents with recoverable local context compression and truthful metering (`caveman claude`), then drive Caveman Cloud from terminal. Compression and metering run in companion Go binaries: run `caveman setup` to see install state. Local savings stay inferred until verified.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",