@caveman-ai/cli 2.0.1 → 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.
@@ -0,0 +1,292 @@
1
+ // `caveman providers add|remove|login|local`: the provider credentials the
2
+ // local runtime may route to, beyond the harness's own. The routing ask sends
3
+ // Cloud a pool built from these (which models each login reaches, never a
4
+ // secret); requests Cloud sends to one of them go straight from this machine
5
+ // to that provider on that credential.
6
+ //
7
+ // Same split as the Cloud login: $CAVEMAN_HOME/provider-logins.json lists ids
8
+ // and where each secret lives; the secret goes to the macOS keychain (service
9
+ // caveman-provider) or a 0600 file under $CAVEMAN_HOME/provider-logins/. The
10
+ // runtime (proxy/internal/pool) reads both; its providers.json is the
11
+ // registry this list mirrors (a test keeps them in step).
12
+ import { execFileSync, spawnSync } from "node:child_process";
13
+ import { randomBytes } from "node:crypto";
14
+ import { chmodSync, closeSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { cavemanHome } from "./config-home.js";
17
+ export const PROVIDER_LOGINS = [
18
+ { id: "anthropic", name: "Anthropic", kind: "api_key", env: ["ANTHROPIC_API_KEY"] },
19
+ { id: "openai", name: "OpenAI", kind: "api_key", env: ["OPENAI_API_KEY"] },
20
+ { id: "chatgpt", name: "ChatGPT plan (Sign in with ChatGPT)", kind: "oauth", env: [], terms: "OpenAI's Sign in with ChatGPT for local apps (preview): a login of Caveman's own, never Codex's. Experimental." },
21
+ { id: "opencode-go", name: "OpenCode Go", kind: "api_key", env: ["OPENCODE_API_KEY"], terms: "Used with your agent's own User-Agent and a stable session header, as OpenCode Go allows." },
22
+ { id: "openrouter", name: "OpenRouter", kind: "api_key", env: ["OPENROUTER_API_KEY"] },
23
+ { id: "fireworks", name: "Fireworks AI", kind: "api_key", env: ["FIREWORKS_API_KEY"] },
24
+ { id: "deepseek", name: "DeepSeek", kind: "api_key", env: ["DEEPSEEK_API_KEY"] },
25
+ { id: "moonshot", name: "Moonshot (Kimi)", kind: "api_key", env: ["MOONSHOT_API_KEY"] },
26
+ { id: "zai", name: "Z.ai (GLM, pay as you go)", kind: "api_key", env: ["ZAI_API_KEY", "ZHIPU_API_KEY"] },
27
+ { id: "zai-coding-plan", name: "Z.ai GLM Coding Plan", kind: "api_key", env: [], terms: "Only Claude Code, Codex and OpenCode requests use the plan, as Z.ai's terms list." },
28
+ { id: "gemini", name: "Google Gemini API", kind: "api_key", env: ["GEMINI_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"], terms: "An API key only; Google logins are never used." },
29
+ { id: "xai", name: "xAI", kind: "api_key", env: ["XAI_API_KEY"] },
30
+ { id: "groq", name: "Groq", kind: "api_key", env: ["GROQ_API_KEY"] },
31
+ { id: "together", name: "Together AI", kind: "api_key", env: ["TOGETHER_API_KEY"] },
32
+ ];
33
+ // Logins that cannot be added, and why: their terms forbid a third-party client.
34
+ export const REFUSED_LOGINS = {
35
+ claude: "Claude Pro/Max logins work only in Anthropic's own apps; add an Anthropic API key instead (caveman providers add anthropic).",
36
+ "claude-code": "Claude Pro/Max logins work only in Anthropic's own apps; add an Anthropic API key instead (caveman providers add anthropic).",
37
+ google: "Google bans accounts whose Gemini CLI or Antigravity login is used by other tools; add a Gemini API key instead (caveman providers add gemini).",
38
+ "gemini-cli": "Google bans accounts whose Gemini CLI or Antigravity login is used by other tools; add a Gemini API key instead (caveman providers add gemini).",
39
+ copilot: "GitHub Copilot is supported only through OpenCode's own GitHub login.",
40
+ "github-copilot": "GitHub Copilot is supported only through OpenCode's own GitHub login.",
41
+ codex: "Codex's own login stays Codex's; sign in for Caveman with `caveman providers login chatgpt`.",
42
+ };
43
+ const KEYCHAIN_SERVICE = "caveman-provider";
44
+ function indexPath() {
45
+ return join(cavemanHome(), "provider-logins.json");
46
+ }
47
+ function secretPath(id) {
48
+ return join(cavemanHome(), "provider-logins", id);
49
+ }
50
+ function readIndex() {
51
+ try {
52
+ const parsed = JSON.parse(readFileSync(indexPath(), "utf8"));
53
+ return { ...parsed, version: 1, logins: Array.isArray(parsed.logins) ? parsed.logins : [] };
54
+ }
55
+ catch {
56
+ return { version: 1, logins: [] };
57
+ }
58
+ }
59
+ // withIndexLock runs one read-modify-write of the index under
60
+ // provider-logins.json.lock, the lock the runtime takes too (a background
61
+ // token refresh). The lock holds a token of its own and is removed only while
62
+ // it still holds it. A lock older than 10 s is a crashed writer's: it is
63
+ // renamed aside first, so of two waiters only one breaks it, and a fresh lock
64
+ // that slipped in between is put back.
65
+ function withIndexLock(fn) {
66
+ mkdirSync(cavemanHome(), { recursive: true, mode: 0o700 });
67
+ const lock = `${indexPath()}.lock`;
68
+ const token = randomBytes(16).toString("hex");
69
+ const deadline = Date.now() + 3000;
70
+ for (;;) {
71
+ try {
72
+ const fd = openSync(lock, "wx", 0o600);
73
+ writeSync(fd, token);
74
+ closeSync(fd);
75
+ break;
76
+ }
77
+ catch (error) {
78
+ if (error.code !== "EEXIST")
79
+ throw error;
80
+ try {
81
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
82
+ const aside = `${lock}.break.${token}`;
83
+ renameSync(lock, aside);
84
+ // ponytail: a writer that takes the lock between our stat and rename
85
+ // loses it here until linkSync puts it back; a lock file holding the
86
+ // owner's pid (or flock) closes that window if it ever bites.
87
+ if (Date.now() - statSync(aside).mtimeMs <= LOCK_STALE_MS) {
88
+ try {
89
+ linkSync(aside, lock);
90
+ }
91
+ catch { /* another writer took the place */ }
92
+ }
93
+ unlinkSync(aside);
94
+ continue;
95
+ }
96
+ }
97
+ catch { /* released or broken meanwhile */ }
98
+ if (Date.now() > deadline)
99
+ throw new Error("caveman: provider-logins.json is locked by another caveman process; try again");
100
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
101
+ }
102
+ }
103
+ try {
104
+ return fn();
105
+ }
106
+ finally {
107
+ try {
108
+ if (readFileSync(lock, "utf8") === token)
109
+ unlinkSync(lock);
110
+ }
111
+ catch { /* already gone */ }
112
+ }
113
+ }
114
+ const LOCK_STALE_MS = 10_000;
115
+ // One write under the lock runs at most three keychain commands (add, read
116
+ // back, delete the old copy): 3 x 2.5 s stays under the stale-lock age.
117
+ const SECURITY_TIMEOUT_MS = 2_500;
118
+ function writeIndex(index) {
119
+ mkdirSync(cavemanHome(), { recursive: true, mode: 0o700 });
120
+ const tmp = `${indexPath()}.${process.pid}.tmp`;
121
+ writeFileSync(tmp, JSON.stringify(index, null, 2) + "\n", { mode: 0o600 });
122
+ renameSync(tmp, indexPath());
123
+ }
124
+ function useKeychain() {
125
+ return process.platform === "darwin" && !process.env.CAVE_NO_KEYCHAIN;
126
+ }
127
+ // keychainSet sends the secret on stdin through `security -i`, never argv.
128
+ function keychainSet(id, secret) {
129
+ const quote = (value) => `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
130
+ const run = spawnSync("security", ["-i"], { input: `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${quote(id)} -w ${quote(secret)}\n`, stdio: ["pipe", "ignore", "ignore"], timeout: SECURITY_TIMEOUT_MS });
131
+ if (run.status !== 0)
132
+ return false;
133
+ try {
134
+ return execFileSync("security", ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", id, "-w"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: SECURITY_TIMEOUT_MS }).trim() === secret;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ }
140
+ function keychainDelete(id) {
141
+ try {
142
+ execFileSync("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", id], { stdio: "ignore", timeout: SECURITY_TIMEOUT_MS });
143
+ }
144
+ catch (error) {
145
+ if (error.status !== 44)
146
+ throw new Error("could not remove the key from macOS Keychain");
147
+ }
148
+ }
149
+ function find(id) {
150
+ const provider = PROVIDER_LOGINS.find((entry) => entry.id === id);
151
+ if (provider)
152
+ return provider;
153
+ if (id && REFUSED_LOGINS[id])
154
+ throw new Error(`caveman: ${REFUSED_LOGINS[id]}`);
155
+ throw new Error(`caveman: unknown provider ${JSON.stringify(id ?? "")}; one of: ${PROVIDER_LOGINS.map((entry) => entry.id).join(", ")}`);
156
+ }
157
+ function flag(argv, name) {
158
+ const index = argv.indexOf(name);
159
+ if (index >= 0)
160
+ return argv[index + 1];
161
+ return argv.find((value) => value.startsWith(`${name}=`))?.slice(name.length + 1);
162
+ }
163
+ // providersAdd stores an API key. The key comes from --key-env NAME, --stdin,
164
+ // or the provider's usual environment variable; never from argv, which any
165
+ // local process can read.
166
+ export function providersAdd(argv, readStdin) {
167
+ const provider = find(argv[0]);
168
+ if (provider.kind !== "api_key")
169
+ throw new Error(`caveman: ${provider.id} is a sign-in, not a key: caveman providers login ${provider.id}`);
170
+ let key = "";
171
+ let source = "";
172
+ const named = flag(argv, "--key-env");
173
+ if (named) {
174
+ key = process.env[named] ?? "";
175
+ source = named;
176
+ }
177
+ else if (argv.includes("--stdin")) {
178
+ key = readStdin();
179
+ source = "stdin";
180
+ }
181
+ else {
182
+ for (const name of provider.env) {
183
+ if (process.env[name]) {
184
+ key = process.env[name];
185
+ source = name;
186
+ break;
187
+ }
188
+ }
189
+ }
190
+ key = key.trim();
191
+ if (!key) {
192
+ const from = provider.env.length ? provider.env.join(" or ") : "--key-env NAME";
193
+ throw new Error(`caveman: no key for ${provider.id}: set ${from}, or pipe it: caveman providers add ${provider.id} --stdin`);
194
+ }
195
+ if (/\s/.test(key) || key.length > 4096)
196
+ throw new Error("caveman: that does not look like an API key");
197
+ return withIndexLock(() => {
198
+ const index = readIndex();
199
+ const previous = index.logins.find((entry) => entry.id === provider.id);
200
+ let store = "file";
201
+ if (useKeychain() && keychainSet(provider.id, key)) {
202
+ store = "keychain";
203
+ removeSecretFile(provider.id); // a key never lives in both stores
204
+ }
205
+ else {
206
+ mkdirSync(join(cavemanHome(), "provider-logins"), { recursive: true, mode: 0o700 });
207
+ writeFileSync(secretPath(provider.id), key, { mode: 0o600 });
208
+ chmodSync(secretPath(provider.id), 0o600);
209
+ // Even under CAVE_NO_KEYCHAIN, which only stops new keychain writes: an
210
+ // older keychain copy must not outlive the move. Deleting never prompts.
211
+ if (previous?.store === "keychain" && process.platform === "darwin")
212
+ keychainDelete(provider.id);
213
+ }
214
+ index.logins = index.logins.filter((entry) => entry.id !== provider.id);
215
+ index.logins.push({ id: provider.id, kind: "api_key", store, added_at: previous?.added_at ?? new Date().toISOString() });
216
+ writeIndex(index);
217
+ return { added: provider.id, name: provider.name, store, from: source };
218
+ });
219
+ }
220
+ export function foundKeys(env = process.env) {
221
+ const added = new Set(readIndex().logins.map((login) => login.id));
222
+ return PROVIDER_LOGINS.flatMap((provider) => {
223
+ const name = provider.kind === "api_key" ? provider.env.find((variable) => env[variable]?.trim()) : undefined;
224
+ return name ? [{ id: provider.id, name: provider.name, env: name, added: added.has(provider.id) }] : [];
225
+ });
226
+ }
227
+ function removeSecretFile(id) {
228
+ try {
229
+ unlinkSync(secretPath(id));
230
+ }
231
+ catch (error) {
232
+ if (error.code !== "ENOENT")
233
+ throw error;
234
+ }
235
+ }
236
+ export function providersRemove(argv) {
237
+ const provider = find(argv[0]);
238
+ return withIndexLock(() => {
239
+ const index = readIndex();
240
+ const entry = index.logins.find((login) => login.id === provider.id);
241
+ if (process.platform === "darwin" && (entry?.store === "keychain" || (!entry && useKeychain())))
242
+ keychainDelete(provider.id);
243
+ removeSecretFile(provider.id);
244
+ index.logins = index.logins.filter((login) => login.id !== provider.id);
245
+ writeIndex(index);
246
+ return { removed: provider.id, was_added: Boolean(entry) };
247
+ });
248
+ }
249
+ // providersCloud is `caveman providers cloud on|off`: whether routing may send
250
+ // a request through Caveman Cloud (on by default while signed in). Off, such
251
+ // an answer runs the model the agent asked for on its own credential.
252
+ export function providersCloud(argv) {
253
+ const setting = argv[0];
254
+ if (setting !== "on" && setting !== "off") {
255
+ return { cloud: readIndex().cloud === false ? "off" : "on" };
256
+ }
257
+ return withIndexLock(() => {
258
+ const index = readIndex();
259
+ index.cloud = setting === "on";
260
+ writeIndex(index);
261
+ return { cloud: setting };
262
+ });
263
+ }
264
+ export function providersLocal() {
265
+ const logins = readIndex().logins
266
+ .filter((login) => PROVIDER_LOGINS.some((provider) => provider.id === login.id))
267
+ .map((login) => {
268
+ const provider = PROVIDER_LOGINS.find((entry) => entry.id === login.id);
269
+ return { id: login.id, name: provider.name, kind: login.kind, store: login.store, added_at: login.added_at, ...(provider.terms ? { terms: provider.terms } : {}) };
270
+ });
271
+ return {
272
+ logins,
273
+ cloud: readIndex().cloud === false ? "off" : "on",
274
+ available: PROVIDER_LOGINS.map((provider) => `${provider.id} (${provider.kind === "oauth" ? "login" : "key"})`),
275
+ traffic: "Requests routed to one of these go straight from this machine to that provider. Only requests routed to a Caveman Cloud model pass through Caveman Cloud, whole (system prompt, tool results, code), on your Caveman project's stored provider key; `caveman providers cloud off` stops that.",
276
+ };
277
+ }
278
+ // providersLogin runs a subscription sign-in in the runtime binary, which also
279
+ // refreshes it: only Sign in with ChatGPT today.
280
+ export function providersLogin(argv, proxyBin) {
281
+ const provider = find(argv[0]);
282
+ if (provider.kind !== "oauth")
283
+ throw new Error(`caveman: ${provider.id} takes an API key: caveman providers add ${provider.id}`);
284
+ const run = spawnSync(proxyBin, ["provider-login", provider.id], { stdio: "inherit" });
285
+ if (run.error)
286
+ throw new Error(`caveman: could not start ${proxyBin}: run \`caveman setup\` to install the runtime`);
287
+ // Exit 2 is a caveman-proxy from before provider logins: the command
288
+ // checked the provider already, so only the subcommand is unknown to it.
289
+ if (run.status === 2)
290
+ throw new Error(`caveman: ${proxyBin} is too old for provider login: run \`caveman setup --install\``);
291
+ return run.status ?? 1;
292
+ }
@@ -0,0 +1,96 @@
1
+ // Caveman modules: the things a developer switches on and off with
2
+ // `caveman on|off <module>`. One entry per module; onboarding, status,
3
+ // doctor and the signed modules.json all read this table.
4
+ //
5
+ // Every module is on by default in onboarding. A module that cannot run yet
6
+ // (routing before Cloud answers) still shows, with its reason.
7
+ // Auto: the model the routing module adds to an agent's model picker.
8
+ // caveman-proxy asks Caveman Cloud only about requests naming it
9
+ // (proxy/internal/gateway/route.go AutoModel); every other model goes as sent.
10
+ export const AUTO_MODEL = "caveman-auto";
11
+ export const AUTO_NAME = "Auto";
12
+ export const AUTO_DESCRIPTION = "Caveman pick model + effort each turn. Hard ask, big brain. Easy ask, save rocks.";
13
+ export const MODULES = [
14
+ {
15
+ id: "output",
16
+ title: "output",
17
+ summary: "the agent says less",
18
+ defaultOn: true,
19
+ needsSignIn: false,
20
+ wiresAgents: true,
21
+ capabilities: [{ key: "think.core", on: true, off: false }],
22
+ binaries: ["caveman-proxy", "caveman-mcp"],
23
+ },
24
+ {
25
+ id: "input",
26
+ title: "input",
27
+ summary: "logs, JSON, code and diffs shrink before the model reads them",
28
+ defaultOn: true,
29
+ needsSignIn: false,
30
+ wiresAgents: true,
31
+ capabilities: [
32
+ { key: "think.mode", on: "compress", off: "record" },
33
+ { key: "think.toon", on: true, off: false },
34
+ { key: "think.shrink", on: true, off: false },
35
+ ],
36
+ binaries: ["caveman-proxy", "caveman-engine", "caveman-mcp", "cavemem", "caveman-shrink"],
37
+ },
38
+ {
39
+ id: "waste-fixes",
40
+ title: "waste fixes",
41
+ summary: "finds your agent's worst waste and fixes it",
42
+ defaultOn: true,
43
+ needsSignIn: false,
44
+ wiresAgents: true,
45
+ // The learn autopilot the native SessionEnd hook starts. caveman-proxy's
46
+ // prompt-cache warming reads `modules["waste-fixes"]` itself (off only
47
+ // when false), so no capability key carries it.
48
+ capabilities: [{ key: "learnAutopilot", on: true, off: false }],
49
+ binaries: ["caveman-proxy", "caveman-mcp"],
50
+ },
51
+ {
52
+ id: "routing",
53
+ title: "routing",
54
+ // The onboarding picker cuts hints at the terminal width (62 characters at
55
+ // 80 columns): what leaves the machine comes first.
56
+ summary: "asks to Auto go to Cloud to pick model + effort",
57
+ defaultOn: true,
58
+ // Adds Auto (AUTO_MODEL) to each wired agent's model picker; only
59
+ // requests naming it are routed. Decisions come from Cloud (POST
60
+ // /v1/route), so it acts only once signed in; caveman-proxy's route stage
61
+ // reads `modules.routing` itself, so no capability key carries it.
62
+ needsSignIn: true,
63
+ wiresAgents: true,
64
+ capabilities: [],
65
+ binaries: ["caveman-proxy", "caveman-mcp"],
66
+ },
67
+ {
68
+ id: "scripts",
69
+ title: "scripts",
70
+ summary: "reusable scripts your agent keeps",
71
+ defaultOn: true,
72
+ needsSignIn: false,
73
+ wiresAgents: false,
74
+ capabilities: [],
75
+ binaries: [],
76
+ external: {
77
+ binary: "caveman-blocks",
78
+ install: ["hooks", "install"],
79
+ uninstall: ["hooks", "uninstall"],
80
+ status: ["hooks", "status", "--json"],
81
+ },
82
+ },
83
+ {
84
+ id: "browse",
85
+ title: "browse",
86
+ summary: "compressed pages for browser tools",
87
+ defaultOn: true,
88
+ needsSignIn: false,
89
+ wiresAgents: false,
90
+ capabilities: [{ key: "execute.browse_tool", on: true, off: false }],
91
+ binaries: ["caveman-browse"],
92
+ },
93
+ ];
94
+ export function findModule(id) {
95
+ return MODULES.find((m) => m.id === id);
96
+ }
@@ -0,0 +1,71 @@
1
+ import { findModule } from "./registry.js";
2
+ // The command that clears an on-but-inactive module, when there is one.
3
+ export function moduleFix(state) {
4
+ const reason = state.reason ?? "";
5
+ if (reason === "not set up")
6
+ return "caveman setup";
7
+ if (reason.startsWith("sign in") || reason === "login expired")
8
+ return "caveman login";
9
+ if (reason.startsWith(`${state.id} paused · `))
10
+ return "caveman billing";
11
+ if (reason.startsWith(`${state.id} degraded · `))
12
+ return "caveman login";
13
+ if (reason === "paused while input is off")
14
+ return "caveman on input";
15
+ if (reason.endsWith(" in config") || reason.includes(" has an invalid value: "))
16
+ return `caveman on ${state.id}`;
17
+ if (reason.endsWith(" not installed") && !findModule(state.id)?.external)
18
+ return "caveman setup --install";
19
+ return undefined;
20
+ }
21
+ // An inactive module the user's own choices explain (not signed in, an
22
+ // override, input off, setup not run yet) rather than something broken.
23
+ export function moduleChoice(state) {
24
+ const reason = state.reason ?? "";
25
+ return ["not set up", "sign in", "waiting for Cloud", "overridden by", "paused while", "record mode", `${state.id} paused · `].some((start) => reason.startsWith(start))
26
+ || reason.endsWith(" in config");
27
+ }
28
+ // `leftAlone`: agents on an endpoint of their own, which enable refuses.
29
+ export function nextStep(states, opts) {
30
+ const inactive = states.filter((state) => state.on && !state.active && moduleFix(state));
31
+ if (inactive.some((state) => moduleFix(state) === "caveman setup --install"))
32
+ return "caveman setup --install";
33
+ const broken = inactive.find((state) => !moduleChoice(state));
34
+ if (broken)
35
+ return moduleFix(broken);
36
+ if (opts.degraded)
37
+ return `caveman doctor ${opts.degraded} --fix`;
38
+ const wiredOn = states.filter((state) => state.on && findModule(state.id)?.wiresAgents);
39
+ const unwired = Object.keys(wiredOn[0]?.perAgent ?? {}).filter((agent) => wiredOn[0].perAgent[agent] === "not wired" && !opts.leftAlone?.includes(agent));
40
+ if (unwired.length)
41
+ return `caveman enable ${unwired.length > 1 ? "--detected" : unwired[0]}`;
42
+ if (inactive[0])
43
+ return moduleFix(inactive[0]);
44
+ return opts.fallback;
45
+ }
46
+ // `degraded` names wired agents whose wiring no longer checks out; their cells
47
+ // say so instead of "wired". `lines` print under the grid, before next.
48
+ export function renderModuleGrid(states, opts) {
49
+ const agents = Object.keys(states[0]?.perAgent ?? {});
50
+ const width = Math.max(9, ...agents.map((agent) => agent.length)) + 2;
51
+ const row = (head, cells, note) => `${head}${cells.map((cell) => cell.padEnd(width)).join("")}${note}`.trimEnd();
52
+ const lines = ["caveman status", row(" ".repeat(19), agents, "")];
53
+ for (const state of states) {
54
+ const notApplicable = Object.values(state.perAgent).every((cell) => cell === "n/a");
55
+ const cells = !state.on ? agents.map(() => "")
56
+ : !state.active ? agents.map(() => "—")
57
+ : notApplicable ? ["✓", ...agents.slice(1).map(() => "")]
58
+ : agents.map((agent) => state.perAgent[agent] === "n/a" ? ""
59
+ : state.perAgent[agent] === "wired" && findModule(state.id)?.wiresAgents && opts.degraded?.includes(agent) ? "degraded"
60
+ : state.perAgent[agent]);
61
+ const fix = moduleFix(state);
62
+ const note = !state.on ? `caveman on ${state.id}`
63
+ : !state.active ? `${state.reason}${fix ? ` · ${fix}` : ""}`
64
+ : opts.notes?.[state.id] ?? "";
65
+ lines.push(row(` ${state.on ? "on " : "off"} ${state.id.padEnd(13)}`, cells, note));
66
+ }
67
+ lines.push(...(opts.lines ?? []));
68
+ if (opts.next)
69
+ lines.push(`next: ${opts.next}`);
70
+ return `${lines.join("\n")}\n`;
71
+ }
@@ -0,0 +1,99 @@
1
+ // `caveman stop`: end the local runtime `caveman start` or `caveman <agent>`
2
+ // started. Only a proxy whose run state answers for its own listener is
3
+ // signalled; anything else on the port is left alone. Idempotent.
4
+ import { readFileSync, unlinkSync } from "node:fs";
5
+ import { request } from "node:http";
6
+ import { moduleHost } from "./apply.js";
7
+ function alive(pid) {
8
+ try {
9
+ process.kill(pid, 0);
10
+ return true;
11
+ }
12
+ catch (error) {
13
+ return error.code === "EPERM";
14
+ }
15
+ }
16
+ function signal(pids) {
17
+ for (const pid of pids) {
18
+ try {
19
+ process.kill(pid, "SIGTERM");
20
+ }
21
+ catch (error) {
22
+ if (error.code !== "ESRCH")
23
+ throw error;
24
+ }
25
+ }
26
+ }
27
+ async function exited(pids, ms) {
28
+ const deadline = Date.now() + ms;
29
+ while (pids.some(alive) && Date.now() < deadline)
30
+ await new Promise((resolve) => setTimeout(resolve, 100));
31
+ }
32
+ // POST /caveman/shutdown with the run state's shutdown token (runtime.token;
33
+ // never the instance token /health/live publishes): the proxy drains and exits
34
+ // as it does on SIGTERM. Plain loopback HTTP, never the CLI's proxy-aware
35
+ // fetch. False when the proxy does not take it (older ones 404 or 403).
36
+ function askToStop(runtime) {
37
+ return new Promise((resolve) => {
38
+ if (!runtime.token)
39
+ return resolve(false);
40
+ const req = request({ host: runtime.host, port: runtime.port, path: "/caveman/shutdown", method: "POST", headers: { "x-caveman-shutdown": runtime.token }, timeout: 2000 }, (res) => {
41
+ res.resume();
42
+ resolve(res.statusCode === 202);
43
+ });
44
+ req.on("timeout", () => req.destroy());
45
+ req.on("error", () => resolve(false));
46
+ req.end();
47
+ });
48
+ }
49
+ // Ends the given runtimes and returns the pids still alive. On Windows
50
+ // process.kill ends a process at once, with no drain, so each proxy is first
51
+ // asked over its listener to shut down; one that does not take the request,
52
+ // or is still up after the drain, is then ended the hard way. A runtime from
53
+ // before the shutdown token is never sent its public instance token: it has
54
+ // no shutdown endpoint, and that token is no credential.
55
+ export async function endRuntimes(runtimes, platform = process.platform) {
56
+ const owned = runtimes.filter((runtime, index) => runtime.pid !== undefined && alive(runtime.pid)
57
+ && runtimes.findIndex((other) => other.pid === runtime.pid) === index);
58
+ const pids = owned.map((runtime) => runtime.pid);
59
+ const asked = platform === "win32" ? await Promise.all(owned.map(askToStop)) : [];
60
+ const accepted = pids.filter((_, index) => asked[index]);
61
+ signal(pids.filter((pid) => !accepted.includes(pid)));
62
+ // The proxy drains for up to 5s before it removes its run state and exits.
63
+ await exited(pids, 7000);
64
+ const late = accepted.filter(alive);
65
+ if (late.length) {
66
+ signal(late);
67
+ await exited(late, 2000);
68
+ }
69
+ // Ended the hard way, a runtime leaves its run state behind: drop a record
70
+ // that still names a process that is gone.
71
+ if (platform === "win32") {
72
+ for (const runtime of owned) {
73
+ if (!runtime.runFile || alive(runtime.pid))
74
+ continue;
75
+ try {
76
+ if (JSON.parse(readFileSync(runtime.runFile, "utf8")).pid === runtime.pid)
77
+ unlinkSync(runtime.runFile);
78
+ }
79
+ catch { /* gone already, or not a record to touch */ }
80
+ }
81
+ }
82
+ return pids.filter(alive);
83
+ }
84
+ export async function stopRuntime() {
85
+ const runtimes = await moduleHost().localRuntimes();
86
+ const owned = runtimes.filter((runtime) => runtime.pid !== undefined);
87
+ if (!owned.some((runtime) => alive(runtime.pid))) {
88
+ const foreign = runtimes.find((runtime) => runtime.listening);
89
+ console.log(foreign ? `not running · ${foreign.host}:${foreign.port} is held by something else; left alone` : "not running");
90
+ return;
91
+ }
92
+ const stuck = await endRuntimes(owned);
93
+ if (stuck.length) {
94
+ console.error(`✗ runtime did not stop (pid ${stuck.join(", ")})`);
95
+ process.exitCode = 1;
96
+ return;
97
+ }
98
+ console.log(`✓ stopped · ${owned.map((runtime) => `${runtime.host}:${runtime.port}`).join(", ")}`);
99
+ }
@@ -6,7 +6,9 @@ import { connect as netConnect } from "node:net";
6
6
  import { createHash, randomUUID } from "node:crypto";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { hardenedGitArgs, hardenedGitEnv } from "./git-safe.js";
9
+ import { nativePipePath } from "./native-pipe.js";
9
10
  import { confirmLearnNudge, maybeSpawnAutopilot } from "./learn-autopilot.js";
11
+ import { cloudConfigPath } from "./modules/config-home.js";
10
12
  const PROFILES = new Set(["record-only", "core", "core-lean-build", "ledger", "ccr-masking", "cache-aware", "full-safe", "full-max"]);
11
13
  const ACTIONS = new Set(["allow", "observe", "block", "ask", "defer"]);
12
14
  const VISIBILITY = new Set(["silent", "advisory", "user"]);
@@ -23,14 +25,20 @@ function caveHome() {
23
25
  }
24
26
  // localGatewayEndpoint resolves the gateway target and returns its host/port
25
27
  // only when it is a loopback proxy — the only case where a dead port means
26
- // "the local proxy needs restarting". Managed gateways (CAVE_GATEWAY_URL /
27
- // persisted gatewayUrl off-loopback) return undefined and never pay a
28
- // per-prompt delegate spawn. Default mirrors the full CLI's PROXY_ADDR.
28
+ // "the local proxy needs restarting". Managed gateways (CAVE_GATEWAY_URL, or a
29
+ // gatewayUrl chosen at login, managedGateway) off-loopback return undefined and
30
+ // never pay a per-prompt delegate spawn. Signing in alone keeps the local
31
+ // proxy. Default mirrors the full CLI's PROXY_ADDR, as does `localPort`.
29
32
  function localGatewayEndpoint() {
30
33
  let gw = process.env.CAVE_GATEWAY_URL;
31
34
  if (typeof gw !== "string" || !gw.trim()) {
32
35
  try {
33
- gw = object(JSON.parse(readFileSync(join(homedir(), ".caveman-cloud", "config.json"), "utf8"))).gatewayUrl;
36
+ const config = object(JSON.parse(readFileSync(cloudConfigPath(), "utf8")));
37
+ if (config.managedGateway === true)
38
+ gw = config.gatewayUrl;
39
+ // The port setup moved the runtime to (index.ts gatewayUrlFromConfigFile).
40
+ else if (typeof config.localPort === "number" && Number.isInteger(config.localPort) && config.localPort >= 1024 && config.localPort <= 65535)
41
+ gw = `http://127.0.0.1:${config.localPort}`;
34
42
  }
35
43
  catch { /* local default */ }
36
44
  }
@@ -68,7 +76,7 @@ function configuredMode() {
68
76
  if (explicit !== undefined)
69
77
  return explicit === "compress" || explicit === "pixel" || explicit === "record" ? explicit : "record";
70
78
  try {
71
- const config = object(JSON.parse(readFileSync(join(homedir(), ".caveman-cloud", "config.json"), "utf8")));
79
+ const config = object(JSON.parse(readFileSync(cloudConfigPath(), "utf8")));
72
80
  const legacy = object(config.wrap).mode;
73
81
  const current = object(config.think).mode;
74
82
  const value = current ?? legacy;
@@ -93,7 +101,7 @@ function configuredCore() {
93
101
  };
94
102
  let configured = true;
95
103
  try {
96
- const config = object(JSON.parse(readFileSync(join(homedir(), ".caveman-cloud", "config.json"), "utf8")));
104
+ const config = object(JSON.parse(readFileSync(cloudConfigPath(), "utf8")));
97
105
  configured = parse(object(config.think).core) ?? true;
98
106
  }
99
107
  catch { /* default above */ }
@@ -399,7 +407,7 @@ function callRuntime(value) {
399
407
  let bytes = 0;
400
408
  const chunks = [];
401
409
  const endpoint = process.platform === "win32"
402
- ? `\\\\.\\pipe\\caveman-native-${createHash("sha256").update(resolve(caveHome()).replaceAll("/", "\\").toLowerCase()).digest("hex").slice(0, 16)}`
410
+ ? nativePipePath(caveHome())
403
411
  : join(caveHome(), "run", "native.sock");
404
412
  const socket = netConnect({ path: endpoint });
405
413
  const finish = (response) => {
@@ -0,0 +1,17 @@
1
+ import { createHash } from "node:crypto";
2
+ import { win32 } from "node:path";
3
+ // The Windows named pipe the native runtime listens on for this home. Mirrors
4
+ // SocketPath in proxy/internal/nativeruntime/server_windows.go: sha256 of the
5
+ // absolute home lowercased the way Go's strings.ToLower does, one code point to
6
+ // one. String.toLowerCase() is not that: it turns İ into i + U+0307 and a
7
+ // word-final Σ into ς, so a Turkish or all-caps Greek profile hashed to a pipe
8
+ // the runtime never opened. Keep the two in step; both test the same vector.
9
+ // ponytail: follows each runtime's Unicode tables, so a capital letter added
10
+ // after Go's (Unicode 15) can still differ; ASCII-only folding on both sides
11
+ // fixes that, once every installed proxy is new enough to agree.
12
+ export function nativePipePath(home) {
13
+ let folded = "";
14
+ for (const char of win32.resolve(home))
15
+ folded += String.fromCodePoint(char.toLowerCase().codePointAt(0));
16
+ return `\\\\.\\pipe\\caveman-native-${createHash("sha256").update(folded).digest("hex").slice(0, 16)}`;
17
+ }