@caveman-ai/cli 2.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -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.0";
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
@@ -954,10 +963,20 @@ function cavemanHome() {
954
963
  function gatewayUrl() {
955
964
  const env = process.env.CAVE_GATEWAY_URL?.trim();
956
965
  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 {
966
+ for (const path of [join4(cavemanHome(), "cloud.json"), join4(homedir3(), ".caveman-cloud", "config.json")]) {
967
+ let raw;
968
+ try {
969
+ raw = readFileSync2(path, "utf8");
970
+ } catch {
971
+ continue;
972
+ }
973
+ try {
974
+ const config = JSON.parse(raw);
975
+ if (config.managedGateway === true && typeof config.gatewayUrl === "string" && config.gatewayUrl) return config.gatewayUrl;
976
+ if (Number.isInteger(config.localPort) && config.localPort >= 1024 && config.localPort <= 65535) return `http://127.0.0.1:${config.localPort}`;
977
+ } catch {
978
+ }
979
+ break;
961
980
  }
962
981
  return "http://127.0.0.1:8787";
963
982
  }
@@ -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
+ }