@caveman-ai/cli 2.1.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.
package/README.md CHANGED
@@ -175,7 +175,9 @@ grant its access scopes. This connection creates no inference key and does not
175
175
  sync local request history. The CLI's usage telemetry setting remains in effect;
176
176
  `caveman telemetry off` disables it. Credentials use the existing secure store;
177
177
  `caveman logout` revokes the session. HTTPS is required except for HTTP loopback development.
178
- Hosted login remains unavailable during beta.
178
+ For hosted Caveman Cloud, run `caveman login` with no flags. The server decides
179
+ whether sign-in is open; when it is not, the CLI prints
180
+ `Sign-in is not open on <host> yet.`
179
181
 
180
182
  Read agents in the connected project with `caveman cloud agent factory list`
181
183
  and `caveman cloud agent factory show <id>`. These commands need
@@ -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-v2.1.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";
@@ -124,7 +124,7 @@ import { createHash } from "node:crypto";
124
124
  import { homedir } from "node:os";
125
125
  import { join as join2 } from "node:path";
126
126
 
127
- // ../pi-extension/src/portable-command.ts
127
+ // src/portable-command.ts
128
128
  import { existsSync, readFileSync, statSync } from "node:fs";
129
129
  import { dirname, extname, isAbsolute, join, resolve } from "node:path";
130
130
  function parseWindowsNodeShim(source) {
@@ -133,6 +133,14 @@ function parseWindowsNodeShim(source) {
133
133
  const match = line.match(/"%(?:dp0%|~dp0)\\?([^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i) ?? line.match(/"([A-Za-z]:[\\/][^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i);
134
134
  if (match) return match[1];
135
135
  }
136
+ const npm = source.match(/SET\s+"(NP[MX])_CLI_JS=%~dp0\\([^"\r\n]+\.js)"[\s\S]*"%NODE_EXE%"\s+"%\1_CLI_JS%"\s+%\*/i);
137
+ return npm ? npm[2] : null;
138
+ }
139
+ function parseWindowsExeShim(source) {
140
+ for (const line of source.split(/\r?\n/)) {
141
+ const match = line.match(/^[ \t]*@?"(?:%(?:dp0%|~dp0)\\?([^"\r\n]+\.exe)|([A-Za-z]:[\\/][^"\r\n]+\.exe))"[ \t]+%\*[ \t]*$/i);
142
+ if (match) return match[1] ?? match[2];
143
+ }
136
144
  return null;
137
145
  }
138
146
  function parseWindowsNestedShim(source) {
@@ -152,13 +160,14 @@ function resolveWindowsNodeShim(executable, depth = 0, seen = /* @__PURE__ */ ne
152
160
  const nested = parseWindowsNestedShim(source);
153
161
  const forwardsToBatch = /"[^"\r\n]+\.(?:cmd|bat)"[ \t]+%\*/i.test(source);
154
162
  const jsTarget = forwardsToBatch ? null : parseWindowsNodeShim(source);
155
- const child = jsTarget ?? nested;
163
+ const exeTarget = forwardsToBatch || jsTarget ? null : parseWindowsExeShim(source);
164
+ const child = jsTarget ?? nested ?? exeTarget;
156
165
  if (!child) {
157
166
  throw new Error(`cannot safely launch non-Node Windows command shim: ${normalized}; install a native .exe`);
158
167
  }
159
168
  const target = /^[A-Za-z]:[\\/]/.test(child) ? child : resolve(dirname(normalized), ...child.split(/[\\/]+/));
160
169
  if (!existsSync(target) || !statSync(target).isFile()) throw new Error(`Windows command shim target is missing: ${target}`);
161
- return jsTarget ? target : resolveWindowsNodeShim(target, depth + 1, seen);
170
+ return jsTarget || !nested && exeTarget ? target : resolveWindowsNodeShim(target, depth + 1, seen);
162
171
  }
163
172
  function envValue(env, name) {
164
173
  const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
@@ -184,8 +193,8 @@ function portableInvocation(command, args, platform = process.platform, env = pr
184
193
  if (platform !== "win32") return { command, args: [...args] };
185
194
  const executable = resolveWindowsCommand(command, env) ?? command;
186
195
  if (!/\.(?:cmd|bat)$/i.test(executable)) return { command: executable, args: [...args] };
187
- const script = resolveWindowsNodeShim(executable);
188
- return { command: process.execPath, args: [script, ...args] };
196
+ const target = resolveWindowsNodeShim(executable);
197
+ return /\.exe$/i.test(target) ? { command: target, args: [...args] } : { command: process.execPath, args: [target, ...args] };
189
198
  }
190
199
 
191
200
  // ../pi-extension/src/protocol.ts
@@ -269,6 +278,14 @@ function hostOf(url) {
269
278
  return void 0;
270
279
  }
271
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
+ }
272
289
  var COMPAT_NAME_RE2 = /^[a-z0-9][a-z0-9._-]{0,63}$/;
273
290
  function compatUpstreamFor(provider, compatUpstreams) {
274
291
  if (!compatUpstreams || !COMPAT_NAME_RE2.test(provider)) return void 0;
@@ -358,7 +375,7 @@ var HookBridge = class {
358
375
  const child = execFile(
359
376
  portable.command,
360
377
  portable.args,
361
- { 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 },
362
379
  (error, stdout) => {
363
380
  const timedOut = !!error && error.killed === true;
364
381
  if (error && stdout === "") return resolve2(timedOut ? void 0 : TRY_NEXT);
@@ -578,7 +595,8 @@ var ProviderRouter = class {
578
595
  this.warnedModels.add(key);
579
596
  const mount = compatUpstreamFor(model.provider, this.compatUpstreams);
580
597
  const expected = mount !== void 0 ? hostOf(mount) : upstreamHostFor(model.provider);
581
- 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`);
582
600
  this.notify(boundedString(`Caveman: pass-through for ${key} (${reason}); no compression`, MAX_MESSAGE_BYTES), "warning");
583
601
  }
584
602
  return;
@@ -595,7 +613,7 @@ var ProviderRouter = class {
595
613
  hadCompat: Object.hasOwn(model, "compat")
596
614
  };
597
615
  const compat = compatForRoutedModel(model);
598
- if (!await this.pi.setModel({ ...model, baseUrl: route, ...compat === void 0 ? {} : { compat } })) {
616
+ if (!await this.setModelKeepingThinking({ ...model, baseUrl: route, ...compat === void 0 ? {} : { compat } })) {
599
617
  if (await this.restoreCurrentModel(ctx)) {
600
618
  this.notify("Caveman: direct mode, no compression this session (model selection failed)", "warning");
601
619
  }
@@ -612,6 +630,15 @@ var ProviderRouter = class {
612
630
  isOwnedRoute(model) {
613
631
  return !!model && !!this.routed && model.provider === this.routed.provider && model.id === this.routed.id && model.baseUrl === this.routed.route;
614
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
+ }
615
642
  async restoreCurrentModel(ctx) {
616
643
  const current = ctx.model;
617
644
  if (!this.isOwnedRoute(current)) {
@@ -625,7 +652,7 @@ var ProviderRouter = class {
625
652
  const wasApplying = this.applying;
626
653
  this.applying = true;
627
654
  try {
628
- if (await this.pi.setModel(direct)) {
655
+ if (await this.setModelKeepingThinking(direct)) {
629
656
  this.routed = void 0;
630
657
  return true;
631
658
  }
@@ -762,7 +789,7 @@ var RecoveryClient = class {
762
789
  return new Promise((resolve2) => {
763
790
  const portable = this.invocation(["version", "--json"]);
764
791
  if (!portable) return resolve2(false);
765
- 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) => {
766
793
  if (error) return resolve2(false);
767
794
  try {
768
795
  const parsed = JSON.parse(stdout);
@@ -779,7 +806,7 @@ var RecoveryClient = class {
779
806
  try {
780
807
  const portable = this.invocation([]);
781
808
  if (!portable) return false;
782
- child = spawn(portable.command, portable.args, { stdio: ["pipe", "pipe", "ignore"] });
809
+ child = spawn(portable.command, portable.args, { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
783
810
  } catch {
784
811
  return false;
785
812
  }
@@ -795,7 +822,7 @@ var RecoveryClient = class {
795
822
  await this.call("initialize", {
796
823
  protocolVersion: "2024-11-05",
797
824
  capabilities: {},
798
- clientInfo: { name: "caveman-pi-extension", version: "0.3.0" }
825
+ clientInfo: { name: "caveman-pi-extension", version: "0.3.1" }
799
826
  }, void 0, INIT_TIMEOUT_MS);
800
827
  this.notify("notifications/initialized");
801
828
  if (this.disposed) {
@@ -954,10 +981,20 @@ function cavemanHome() {
954
981
  function gatewayUrl() {
955
982
  const env = process.env.CAVE_GATEWAY_URL?.trim();
956
983
  if (env) return env;
957
- try {
958
- const config = JSON.parse(readFileSync2(join4(homedir3(), ".caveman-cloud", "config.json"), "utf8"));
959
- if (typeof config.gatewayUrl === "string" && config.gatewayUrl) return config.gatewayUrl;
960
- } catch {
984
+ for (const path of [join4(cavemanHome(), "cloud.json"), join4(homedir3(), ".caveman-cloud", "config.json")]) {
985
+ let raw;
986
+ try {
987
+ raw = readFileSync2(path, "utf8");
988
+ } catch {
989
+ continue;
990
+ }
991
+ try {
992
+ const config = JSON.parse(raw);
993
+ if (config.managedGateway === true && typeof config.gatewayUrl === "string" && config.gatewayUrl) return config.gatewayUrl;
994
+ if (Number.isInteger(config.localPort) && config.localPort >= 1024 && config.localPort <= 65535) return `http://127.0.0.1:${config.localPort}`;
995
+ } catch {
996
+ }
997
+ break;
961
998
  }
962
999
  return "http://127.0.0.1:8787";
963
1000
  }
@@ -1102,14 +1139,15 @@ function index_default(pi) {
1102
1139
  }));
1103
1140
  pi.on("before_agent_start", GUARD_before_agent_start(async (event, ctx) => {
1104
1141
  if (gateDone) await router?.apply(ctx.model, ctx);
1142
+ const prompt = event.prompt ?? "";
1105
1143
  const response = await bridge.call("UserPromptSubmit", {
1106
1144
  session_id: sessionId,
1107
1145
  model: ctx.model?.id,
1108
1146
  provider: ctx.model?.provider,
1109
- prompt: promptDigest(event.prompt),
1110
- task_type: taskType(event.prompt),
1111
- task_terms: taskTerms(event.prompt),
1112
- task_continuation: taskContinuation(event.prompt)
1147
+ prompt: promptDigest(prompt),
1148
+ task_type: taskType(prompt),
1149
+ task_terms: taskTerms(prompt),
1150
+ task_continuation: taskContinuation(prompt)
1113
1151
  });
1114
1152
  const dynamic = [additionalContextOf(response), ...pendingContext].filter(Boolean);
1115
1153
  pendingContext = [];
@@ -1138,7 +1176,14 @@ function index_default(pi) {
1138
1176
  pendingBytes += bytes;
1139
1177
  }
1140
1178
  }));
1141
- 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)));
1142
1187
  pi.on("session_before_compact", GUARD_session_before_compact(() => {
1143
1188
  void bridge.call("PreCompact", { session_id: sessionId });
1144
1189
  }));
@@ -0,0 +1,176 @@
1
+ export function nextDevicePollIntervalMs(currentMs, errorCode) {
2
+ const current = Math.max(0, Number.isFinite(currentMs) ? currentMs : 0);
3
+ return errorCode === "slow_down" ? current + 5000 : current;
4
+ }
5
+ // DeviceAuthError carries the HTTP status and the server's error code so a
6
+ // caller can tell "sign-in is closed here" (403 cave_device_login_disabled, or
7
+ // 404 where the endpoint does not exist) from a broken network.
8
+ export class DeviceAuthError extends Error {
9
+ status;
10
+ code;
11
+ constructor(message, status, code) {
12
+ super(message);
13
+ this.name = "DeviceAuthError";
14
+ this.status = status;
15
+ this.code = code;
16
+ }
17
+ }
18
+ // An abort ends the wait early; the next request then throws the abort reason.
19
+ function defaultSleep(ms, signal) {
20
+ return new Promise((resolve) => {
21
+ const timer = setTimeout(resolve, ms);
22
+ signal?.addEventListener("abort", () => {
23
+ clearTimeout(timer);
24
+ resolve();
25
+ }, { once: true });
26
+ });
27
+ }
28
+ function errorCode(body) {
29
+ const error = body?.error;
30
+ if (typeof error === "string")
31
+ return error;
32
+ const code = error?.code;
33
+ return typeof code === "string" ? code : undefined;
34
+ }
35
+ function requestSignal(signal, timeoutMs) {
36
+ const timeout = AbortSignal.timeout(timeoutMs);
37
+ return signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
38
+ }
39
+ async function acknowledge(options) {
40
+ const durable = Boolean(options.credentials.refresh_token || options.credentials.gateway_api_key ||
41
+ options.credentials.gateway_key_id || options.credentials.project_id);
42
+ if (!durable)
43
+ return;
44
+ const ackToken = options.credentials.delivery_ack_token;
45
+ if (typeof ackToken !== "string" || ackToken === "") {
46
+ throw new Error("device login failed: server did not provide a delivery acknowledgement token");
47
+ }
48
+ let lastError = "unknown error";
49
+ for (let attempt = 0; attempt < 5; attempt++) {
50
+ try {
51
+ const response = await options.fetcher(`${options.baseURL}/api/v1/auth/device/ack`, {
52
+ method: "POST",
53
+ redirect: "manual",
54
+ headers: {
55
+ authorization: `Bearer ${options.credentials.access_token}`,
56
+ "content-type": "application/json",
57
+ "x-cave-client": options.client,
58
+ },
59
+ body: JSON.stringify({ device_code: options.code.device_code, ack_token: ackToken }),
60
+ signal: requestSignal(options.signal, 5000),
61
+ });
62
+ if (response.ok)
63
+ return;
64
+ const body = await response.json().catch(() => null);
65
+ const code = typeof body?.error?.code === "string" ? body.error.code : `HTTP ${response.status}`;
66
+ lastError = code;
67
+ if (response.status < 500 && response.status !== 429)
68
+ break;
69
+ }
70
+ catch (error) {
71
+ lastError = error instanceof Error ? error.message : String(error);
72
+ }
73
+ if (attempt < 4)
74
+ await options.sleep(Math.min(2000, 200 * 2 ** attempt));
75
+ }
76
+ throw new Error(`device credential delivery acknowledgement failed (${lastError}); credentials were persisted locally but the server may revoke them after the delivery window`);
77
+ }
78
+ export async function runCavemanDeviceFlow(options) {
79
+ const fetcher = options.fetch ?? globalThis.fetch;
80
+ const wait = options.sleep ?? ((ms) => defaultSleep(ms, options.signal));
81
+ const baseURL = options.baseURL.replace(/\/$/, "");
82
+ // Device codes never follow redirects: a redirected endpoint is not the
83
+ // control plane the user asked to sign in to.
84
+ const codeResponse = await fetcher(`${baseURL}/api/v1/auth/device/code`, {
85
+ method: "POST",
86
+ redirect: "error",
87
+ headers: { "content-type": "application/json", "x-cave-client": options.client },
88
+ body: "{}",
89
+ signal: requestSignal(options.signal, 5000),
90
+ });
91
+ if (!codeResponse.ok) {
92
+ const body = await codeResponse.json().catch(() => null);
93
+ throw new DeviceAuthError(`device authorization failed: HTTP ${codeResponse.status}`, codeResponse.status, errorCode(body));
94
+ }
95
+ const rawCode = await codeResponse.json().catch(() => null);
96
+ if (rawCode === null || typeof rawCode.device_code !== "string" || rawCode.device_code === "" ||
97
+ typeof rawCode.user_code !== "string" || typeof rawCode.verification_uri !== "string" ||
98
+ typeof rawCode.expires_in !== "number" || !Number.isFinite(rawCode.expires_in) || rawCode.expires_in <= 0) {
99
+ throw new Error(`device authorization failed: ${JSON.stringify(rawCode)}`);
100
+ }
101
+ const code = rawCode;
102
+ await options.onCode?.(structuredClone(code));
103
+ let intervalMs = Math.max(0, Number(code.interval ?? 5)) * 1000;
104
+ const deadline = Date.now() + code.expires_in * 1000;
105
+ while (Date.now() < deadline) {
106
+ let payload;
107
+ let status = 0;
108
+ let retryAfterMs = 0;
109
+ try {
110
+ const response = await fetcher(`${baseURL}/api/v1/auth/device/token`, {
111
+ method: "POST",
112
+ redirect: "manual",
113
+ headers: { "content-type": "application/json", "x-cave-client": options.client },
114
+ body: JSON.stringify({ device_code: code.device_code }),
115
+ signal: requestSignal(options.signal, 5000),
116
+ });
117
+ status = response.status;
118
+ const retryAfter = response.headers.get("retry-after");
119
+ if (retryAfter !== null) {
120
+ const seconds = Number(retryAfter);
121
+ if (Number.isFinite(seconds) && seconds >= 0)
122
+ retryAfterMs = seconds * 1000;
123
+ }
124
+ payload = status >= 300 && status < 400 ? {} : await response.json();
125
+ }
126
+ catch (error) {
127
+ if (options.signal?.aborted)
128
+ throw options.signal.reason;
129
+ if (Date.now() >= deadline) {
130
+ throw new Error(`device login polling failed: ${error instanceof Error ? error.message : String(error)}`);
131
+ }
132
+ await wait(Math.max(intervalMs, retryAfterMs, 200));
133
+ continue;
134
+ }
135
+ if (status >= 300 && status < 400)
136
+ throw new Error("device login refused a redirected token endpoint");
137
+ if (status === 429) {
138
+ await wait(Math.max(intervalMs, retryAfterMs, 200));
139
+ continue;
140
+ }
141
+ const accessToken = typeof payload.access_token === "string" ? payload.access_token : "";
142
+ if (accessToken !== "") {
143
+ // A token on an error response is not a grant.
144
+ if (status < 200 || status >= 300)
145
+ throw new Error(`device login failed: token response HTTP ${status}`);
146
+ const credentials = { ...payload, access_token: accessToken };
147
+ let acknowledged = false;
148
+ return {
149
+ code: structuredClone(code),
150
+ credentials: structuredClone(credentials),
151
+ async acknowledge() {
152
+ if (acknowledged)
153
+ return;
154
+ await acknowledge({
155
+ baseURL,
156
+ client: options.client,
157
+ code,
158
+ credentials,
159
+ fetcher,
160
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
161
+ sleep: wait,
162
+ });
163
+ acknowledged = true;
164
+ },
165
+ };
166
+ }
167
+ const errorCode = typeof payload.error === "string" ? payload.error : "";
168
+ if (errorCode === "slow_down")
169
+ intervalMs = nextDevicePollIntervalMs(intervalMs, errorCode);
170
+ else if (errorCode !== "" && errorCode !== "authorization_pending") {
171
+ throw new Error(`device login failed: ${errorCode}`);
172
+ }
173
+ await wait(Math.max(intervalMs, 200));
174
+ }
175
+ throw new Error("device login timed out before approval");
176
+ }
@@ -0,0 +1,45 @@
1
+ import { win32 } from "node:path";
2
+ // The names caveman writes at the top of its home; a name continued by
3
+ // OWNED_HOME_SUFFIX is a temp, lock, rotated log or SQLite file beside one of
4
+ // them, and a dot-named temp prefix continued by "-" is a temp file. Mirrors
5
+ // ownedEntries, homeMarkers and ownedSuffix in
6
+ // proxy/internal/securehome/securehome.go: change both together.
7
+ export const OWNED_HOME_ENTRIES = [
8
+ "bin", "browse-profile", "candidates", "cli", "exports", "hooks", "integrations", "mcp", "mem", "openclaw",
9
+ "packs", "provider-logins", "recall-hooks", "receipts", "reports", "run", "runtime", "tmp", "usage",
10
+ "browse-chrome.log", "browse-session.json", "cache-warm-gaps.json", "caveman.db", "caveman.yaml", "ccr.db",
11
+ "chatgpt-host-id", "cloud.json", "credentials", "modules.lock.json", "provider-logins.json", "proxy.log",
12
+ "route-state.json",
13
+ ".browse-session", ".cache-warm", ".caveman-sqlite", ".install.lock",
14
+ ];
15
+ // Files no other program writes. bin, run, tmp or reports alone are any tools
16
+ // folder, so a home holding anything is caveman's only with one of these.
17
+ export const HOME_MARKERS = [
18
+ "caveman.db", "caveman.yaml", "ccr.db", "cloud.json", "modules.lock.json", "provider-logins.json", "route-state.json",
19
+ ];
20
+ // SQLite's -wal, -shm and -journal, a rotated log's .1, a temp (.tmp,
21
+ // .<pid>.<random>.tmp), a lock (.lock, .<purpose>.lock), a lock being broken,
22
+ // a broken lock set aside (.<pid>.<ms>.stale).
23
+ export const OWNED_HOME_SUFFIX = /^(?:-wal|-shm|-journal|\.\d+|(?:\.[^.]+)*\.tmp|(?:\.[^.]+)*\.stale|(?:\.[^.]+)?\.lock(?:\.break\..+)?)$/;
24
+ // Whether a Windows home's permissions are not caveman's to rewrite: a drive
25
+ // root, a network path (\\server\share, or a mapped drive, whose real path is
26
+ // one), a junction or symlink (the permissions would land on its target), or
27
+ // a folder holding anything caveman did not write, or none of its own files
28
+ // (CAVEMAN_HOME pointed at D:\work or D:\tools). icacls /inheritance:r replaces
29
+ // the permissions of everything below for good, and on a share can lock the
30
+ // user out.
31
+ export function leaveHomeAclAlone(home, seen) {
32
+ const clean = win32.resolve(home);
33
+ if (seen.link || win32.dirname(clean) === clean || clean.startsWith("\\\\") || seen.resolved.startsWith("\\\\"))
34
+ return true;
35
+ const owned = (name) => OWNED_HOME_ENTRIES.some((entry) => {
36
+ const rest = name.startsWith(entry) ? name.slice(entry.length) : undefined;
37
+ return rest !== undefined && (rest === "" || OWNED_HOME_SUFFIX.test(rest) || (entry.startsWith(".") && rest.startsWith("-")));
38
+ });
39
+ return !seen.names.every(owned) || (seen.names.length > 0 && !seen.names.some((name) => HOME_MARKERS.includes(name)));
40
+ }
41
+ // A Windows system tool by full path. A bare name is looked up in the current
42
+ // directory first, so a whoami.exe planted in a project would run instead.
43
+ export function systemTool(name, env = process.env) {
44
+ return win32.join(env.SystemRoot || "C:\\Windows", "System32", `${name}.exe`);
45
+ }