@caveman-ai/cli 1.2.1 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,787 @@
1
+ // ../pi-extension/src/index.ts
2
+ import { readFileSync as readFileSync2 } from "node:fs";
3
+ import { homedir as homedir3 } from "node:os";
4
+ import { join as join4 } from "node:path";
5
+ import { Type } from "typebox";
6
+
7
+ // ../pi-extension/src/lifecycle.ts
8
+ import { execFile } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { homedir } from "node:os";
11
+ import { join as join2 } from "node:path";
12
+
13
+ // ../pi-extension/src/portable-command.ts
14
+ import { existsSync, readFileSync, statSync } from "node:fs";
15
+ import { dirname, extname, isAbsolute, join, resolve } from "node:path";
16
+ function parseWindowsNodeShim(source) {
17
+ for (const line of source.split(/\r?\n/)) {
18
+ if (!/(?:\bnode(?:\.exe)?\b|_prog)/i.test(line) || !/%\*/.test(line)) continue;
19
+ 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);
20
+ if (match) return match[1];
21
+ }
22
+ return null;
23
+ }
24
+ function envValue(env, name) {
25
+ const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
26
+ return key === void 0 ? void 0 : env[key];
27
+ }
28
+ function resolveWindowsCommand(command, env) {
29
+ const pathExt = envValue(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD";
30
+ const names = extname(command) ? [command] : pathExt.split(";").map((extension) => `${command}${extension.startsWith(".") ? extension : `.${extension}`}`);
31
+ if (isAbsolute(command) || /[\\/]/.test(command)) {
32
+ for (const name of names) if (existsSync(name)) return name;
33
+ return existsSync(command) ? command : void 0;
34
+ }
35
+ for (const directory of (envValue(env, "PATH") ?? "").split(";")) {
36
+ if (!directory) continue;
37
+ for (const name of names) {
38
+ const candidate = join(directory, name);
39
+ if (existsSync(candidate)) return candidate;
40
+ }
41
+ }
42
+ return void 0;
43
+ }
44
+ function portableInvocation(command, args, platform = process.platform, env = process.env) {
45
+ if (platform !== "win32") return { command, args: [...args] };
46
+ const executable = resolveWindowsCommand(command, env) ?? command;
47
+ if (!/\.(?:cmd|bat)$/i.test(executable)) return { command: executable, args: [...args] };
48
+ const stat = statSync(executable);
49
+ if (!stat.isFile() || stat.size > 256 * 1024) {
50
+ throw new Error(`cannot safely launch Windows command shim: ${executable}`);
51
+ }
52
+ const shimScript = parseWindowsNodeShim(readFileSync(executable, "utf8"));
53
+ if (!shimScript) {
54
+ throw new Error(`cannot safely launch non-Node Windows command shim: ${executable}; install a native .exe`);
55
+ }
56
+ const script = /^[A-Za-z]:[\\/]/.test(shimScript) ? shimScript : resolve(dirname(executable), ...shimScript.split(/[\\/]+/));
57
+ if (!statSync(script).isFile()) {
58
+ throw new Error(`Windows command shim target is missing: ${script}`);
59
+ }
60
+ return { command: process.execPath, args: [script, ...args] };
61
+ }
62
+
63
+ // ../pi-extension/src/protocol.ts
64
+ var MAX_CONTEXT_BYTES = 64 * 1024;
65
+ var MAX_MESSAGE_BYTES = 4 * 1024;
66
+ var MAX_OUTPUT_REPLACEMENT_BYTES = 2 * 1024 * 1024;
67
+ var MAX_RECOVERY_REF_BYTES = 1024;
68
+ var MAX_DECISION_ID_BYTES = 256;
69
+ var MAX_TOOL_OUTPUT_BYTES = 2 * 1024 * 1024;
70
+ function fits(value, max) {
71
+ return typeof value === "string" && Buffer.byteLength(value, "utf8") <= max;
72
+ }
73
+ function sanitizeHookResponse(raw) {
74
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
75
+ const value = raw;
76
+ const out = {};
77
+ if (fits(value.context, MAX_CONTEXT_BYTES)) out.context = value.context;
78
+ if (fits(value.message, MAX_MESSAGE_BYTES)) out.message = value.message;
79
+ if (fits(value.output_replacement, MAX_OUTPUT_REPLACEMENT_BYTES)) out.output_replacement = value.output_replacement;
80
+ if (fits(value.recovery_ref, MAX_RECOVERY_REF_BYTES)) out.recovery_ref = value.recovery_ref;
81
+ if (fits(value.decision_id, MAX_DECISION_ID_BYTES)) out.decision_id = value.decision_id;
82
+ if (typeof value.action === "string") out.action = value.action;
83
+ const hso = value.hookSpecificOutput;
84
+ if (hso && typeof hso === "object" && !Array.isArray(hso)) {
85
+ const nested = hso;
86
+ const cleaned = {};
87
+ if (typeof nested.hookEventName === "string") cleaned.hookEventName = nested.hookEventName;
88
+ if (fits(nested.additionalContext, MAX_CONTEXT_BYTES)) cleaned.additionalContext = nested.additionalContext;
89
+ if (fits(nested.updatedToolOutput, MAX_OUTPUT_REPLACEMENT_BYTES)) cleaned.updatedToolOutput = nested.updatedToolOutput;
90
+ out.hookSpecificOutput = cleaned;
91
+ }
92
+ return out;
93
+ }
94
+ function additionalContextOf(response) {
95
+ const context = response?.hookSpecificOutput?.additionalContext ?? response?.context;
96
+ return context ? context : void 0;
97
+ }
98
+ function outputReplacementOf(response) {
99
+ const replacement = response?.hookSpecificOutput?.updatedToolOutput ?? response?.output_replacement;
100
+ return replacement ? replacement : void 0;
101
+ }
102
+ var ROUTES_BY_API = {
103
+ "anthropic-messages": "/w/pi",
104
+ "openai-completions": "/w/pi/openai/v1",
105
+ "openai-responses": "/w/pi/openai/v1",
106
+ "google-generative-ai": "/w/pi/v1beta"
107
+ };
108
+ function routeForApi(gateway, api) {
109
+ const path = api ? ROUTES_BY_API[api] : void 0;
110
+ return path ? joinUrl(gateway, path) : void 0;
111
+ }
112
+ function joinUrl(base, path) {
113
+ return `${base.replace(/\/+$/, "")}${path}`;
114
+ }
115
+ function isLoopbackUrl(url) {
116
+ try {
117
+ const host = new URL(url).hostname;
118
+ return host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "localhost";
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ // ../pi-extension/src/lifecycle.ts
125
+ var HOOK_TIMEOUT_MS = 2e3;
126
+ var SESSION_START_TIMEOUT_MS = 6e3;
127
+ var HOOK_MAX_BUFFER = 2 * 1024 * 1024;
128
+ function resolveHookInvocations(env = process.env) {
129
+ const localBin = join2(env.CAVEMAN_HOME || join2(homedir(), ".caveman"), "bin", "caveman");
130
+ const candidates = [
131
+ { command: "caveman", args: [] },
132
+ { command: "cave", args: [] },
133
+ { command: localBin, args: [] }
134
+ ];
135
+ const stamped = env.CAVEMAN_PI_HOOK_CMD;
136
+ if (stamped) {
137
+ try {
138
+ const parsed = JSON.parse(stamped);
139
+ if (Array.isArray(parsed) && parsed.length > 0 && parsed.every((part) => typeof part === "string" && part.length > 0)) {
140
+ candidates.unshift({ command: parsed[0], args: parsed.slice(1) });
141
+ }
142
+ } catch {
143
+ }
144
+ }
145
+ return candidates;
146
+ }
147
+ var TRY_NEXT = "__caveman_try_next__";
148
+ var HookBridge = class {
149
+ invocations;
150
+ constructor(invocations = resolveHookInvocations()) {
151
+ this.invocations = invocations;
152
+ }
153
+ // call runs one native-hook event. Fail-open by contract: any spawn error,
154
+ // timeout, or unparseable output resolves to undefined.
155
+ async call(event, payload) {
156
+ const input = JSON.stringify({ event_name: event, surface: "cli", ...payload });
157
+ for (const invocation of this.invocations) {
158
+ const raw = await this.invoke(invocation, event, input);
159
+ if (raw === TRY_NEXT) continue;
160
+ if (raw === void 0 || !raw.trim()) return void 0;
161
+ try {
162
+ return sanitizeHookResponse(JSON.parse(raw));
163
+ } catch {
164
+ return void 0;
165
+ }
166
+ }
167
+ return void 0;
168
+ }
169
+ invoke(invocation, event, input) {
170
+ return new Promise((resolve2) => {
171
+ let portable;
172
+ try {
173
+ portable = portableInvocation(invocation.command, [...invocation.args, "native-hook", "pi", event]);
174
+ } catch {
175
+ resolve2(TRY_NEXT);
176
+ return;
177
+ }
178
+ const child = execFile(
179
+ portable.command,
180
+ portable.args,
181
+ { timeout: event === "SessionStart" ? SESSION_START_TIMEOUT_MS : HOOK_TIMEOUT_MS, maxBuffer: HOOK_MAX_BUFFER, encoding: "utf8" },
182
+ (error, stdout) => {
183
+ const timedOut = !!error && error.killed === true;
184
+ if (error && stdout === "") return resolve2(timedOut ? void 0 : TRY_NEXT);
185
+ resolve2(stdout);
186
+ }
187
+ );
188
+ child.stdin?.on("error", () => {
189
+ });
190
+ child.stdin?.end(input);
191
+ });
192
+ }
193
+ };
194
+ function promptDigest(prompt) {
195
+ return {
196
+ bytes: Buffer.byteLength(prompt, "utf8"),
197
+ sha256: `sha256:${createHash("sha256").update(prompt, "utf8").digest("hex")}`
198
+ };
199
+ }
200
+ function taskType(text) {
201
+ const lower = text.toLowerCase();
202
+ const has = (...terms) => terms.some((term) => lower.includes(term));
203
+ if (has("migration", "migrate", "schema change", "backfill", "rollback")) return "migration";
204
+ if (has("bug", "fix", "broken", "regression", "crash", "error", "incorrect")) return "bugfix";
205
+ if (has("investigate", "diagnose", "root cause", "why does", "trace")) return "investigation";
206
+ if (has("refactor", "restructure", "reorganize", "cleanup")) return "refactor";
207
+ if (has("review", "audit", "critique", "assess")) return "review";
208
+ if (has("verify", "verification", "prove", "validate", "check that")) return "verification";
209
+ if (has("build", "implement", "add", "create", "ship", "feature")) return "feature";
210
+ return "general";
211
+ }
212
+ var TASK_STOPWORDS = /* @__PURE__ */ new Set(["about", "after", "agent", "before", "build", "change", "code", "create", "from", "have", "help", "implement", "into", "make", "please", "project", "repository", "should", "spec", "task", "that", "then", "there", "these", "they", "this", "through", "user", "want", "what", "when", "where", "which", "with", "would", "your"]);
213
+ function taskTerms(text) {
214
+ const out = [];
215
+ const seen = /* @__PURE__ */ new Set();
216
+ for (const raw of text.match(/[A-Za-z][A-Za-z0-9_./-]{2,63}/g) ?? []) {
217
+ const term = raw.toLowerCase().replace(/^[-./]+|[-./]+$/g, "");
218
+ if (!term || term.includes("..") || TASK_STOPWORDS.has(term) || seen.has(term)) continue;
219
+ if (/^(?:sk|pk|rk|ghp|github_pat|xox[baprs]|akia)[-_]/i.test(term) || /^[a-z0-9_-]{40,}$/i.test(term)) continue;
220
+ seen.add(term);
221
+ out.push(term);
222
+ if (out.length === 12) break;
223
+ }
224
+ return out;
225
+ }
226
+ function taskContinuation(text) {
227
+ const prompt = text.trim().toLowerCase();
228
+ if (!prompt || prompt.length > 160 || prompt.split(/\s+/).length > 14) return false;
229
+ return /^(?:please\s+)?(?:continue|go ahead|keep going|proceed|do (?:it|that)|fix (?:it|that)|retry|try again|explain (?:it|that)|what do you mean|yes|yep|yeah|why\??|how\??)[.!?\s]*$/.test(prompt);
230
+ }
231
+
232
+ // ../pi-extension/src/provider.ts
233
+ var ProviderRouter = class {
234
+ pi;
235
+ notify;
236
+ gateway;
237
+ gateOpen = false;
238
+ overridden = /* @__PURE__ */ new Set();
239
+ applying = false;
240
+ warnedModels = /* @__PURE__ */ new Set();
241
+ constructor(pi, notify) {
242
+ this.pi = pi;
243
+ this.notify = notify;
244
+ }
245
+ // openGate is called once per session after the recovery gate held. Refuses
246
+ // non-loopback gateways: managed routing needs auth proof v1 does not carry.
247
+ async openGate(gateway, ctx) {
248
+ if (!isLoopbackUrl(gateway)) {
249
+ this.notify("Caveman: direct mode, no compression this session (gateway is not loopback)", "warning");
250
+ return;
251
+ }
252
+ this.gateway = gateway;
253
+ this.gateOpen = true;
254
+ await this.apply(ctx.model, ctx);
255
+ }
256
+ closeGate() {
257
+ this.gateOpen = false;
258
+ this.clearOverrides();
259
+ }
260
+ routing() {
261
+ return this.gateOpen && this.overridden.size > 0;
262
+ }
263
+ // apply routes one model's provider, or restores direct mode when the model
264
+ // has no verified route. Called from the gate and from model_select; the
265
+ // applying flag swallows the model_select echo of our own setModel call.
266
+ async apply(model, ctx) {
267
+ if (!this.gateOpen || this.applying || !this.gateway) return;
268
+ if (!model) return;
269
+ const route = routeForApi(this.gateway, model.api);
270
+ let oauth = true;
271
+ try {
272
+ oauth = ctx.modelRegistry.isUsingOAuth(model);
273
+ } catch {
274
+ }
275
+ if (!route || oauth) {
276
+ this.clearOverrides();
277
+ const key = `${model.provider}/${model.id}`;
278
+ if (!this.warnedModels.has(key)) {
279
+ this.warnedModels.add(key);
280
+ const reason = oauth ? "OAuth/subscription credentials are not routed" : `unsupported API "${model.api}"`;
281
+ this.notify(`Caveman: pass-through for ${key} (${reason}); no compression`, "warning");
282
+ }
283
+ return;
284
+ }
285
+ this.applying = true;
286
+ try {
287
+ for (const provider of this.overridden) {
288
+ if (provider !== model.provider) {
289
+ this.pi.unregisterProvider(provider);
290
+ this.overridden.delete(provider);
291
+ }
292
+ }
293
+ this.pi.registerProvider(model.provider, { baseUrl: route });
294
+ this.overridden.add(model.provider);
295
+ const refreshed = ctx.modelRegistry.find(model.provider, model.id);
296
+ if (!refreshed || !await this.pi.setModel(refreshed)) {
297
+ this.clearOverrides();
298
+ this.notify("Caveman: direct mode, no compression this session (model re-resolution failed)", "warning");
299
+ return;
300
+ }
301
+ } catch {
302
+ this.clearOverrides();
303
+ this.notify("Caveman: direct mode, no compression this session (provider override failed)", "warning");
304
+ } finally {
305
+ this.applying = false;
306
+ }
307
+ }
308
+ clearOverrides() {
309
+ for (const provider of this.overridden) {
310
+ try {
311
+ this.pi.unregisterProvider(provider);
312
+ } catch {
313
+ }
314
+ }
315
+ this.overridden.clear();
316
+ }
317
+ };
318
+
319
+ // ../pi-extension/src/recovery.ts
320
+ import { execFile as execFile2, spawn } from "node:child_process";
321
+ import { existsSync as existsSync2 } from "node:fs";
322
+ import { homedir as homedir2 } from "node:os";
323
+ import { delimiter, join as join3 } from "node:path";
324
+ var PROBE_TIMEOUT_MS = 2e3;
325
+ var CALL_TIMEOUT_MS = 3e4;
326
+ var INIT_TIMEOUT_MS = 2e3;
327
+ function resolveMcpBinary(env = process.env) {
328
+ const explicit = env.CAVEMAN_MCP_BIN?.trim();
329
+ if (explicit) return explicit;
330
+ const name = process.platform === "win32" ? "caveman-mcp.exe" : "caveman-mcp";
331
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
332
+ if (dir && existsSync2(join3(dir, name))) return join3(dir, name);
333
+ }
334
+ const local = join3(env.CAVEMAN_HOME || join3(homedir2(), ".caveman"), "bin", name);
335
+ return existsSync2(local) ? local : void 0;
336
+ }
337
+ var RecoveryClient = class {
338
+ binary;
339
+ child;
340
+ initialized = false;
341
+ probed;
342
+ ensuring;
343
+ nextId = 1;
344
+ pending = /* @__PURE__ */ new Map();
345
+ buffer = "";
346
+ disposed = false;
347
+ constructor(binary = resolveMcpBinary()) {
348
+ this.binary = binary;
349
+ }
350
+ // ensure probes the binary once and brings up an initialized child. Returns
351
+ // false (never throws) when recovery cannot hold — the caller passes through.
352
+ async ensure() {
353
+ if (this.disposed || !this.binary) return false;
354
+ if (this.child && this.initialized) return true;
355
+ this.ensuring ??= this.bringUp().finally(() => {
356
+ this.ensuring = void 0;
357
+ });
358
+ return this.ensuring;
359
+ }
360
+ async bringUp() {
361
+ if (this.probed === void 0) this.probed = await this.probe();
362
+ if (!this.probed || this.disposed) return false;
363
+ if (this.child && this.initialized) return true;
364
+ return this.start();
365
+ }
366
+ ready() {
367
+ return Boolean(this.child && this.initialized && !this.disposed);
368
+ }
369
+ async retrieve(handle, query, signal) {
370
+ if (!await this.ensure()) {
371
+ return { text: JSON.stringify({ error: "cave_recovery_unavailable", message: "caveman-mcp is not available this session" }), isError: true };
372
+ }
373
+ try {
374
+ const result = await this.call("tools/call", {
375
+ name: "caveman_retrieve",
376
+ arguments: { recovery_handle: handle, ...query ? { query } : {} }
377
+ }, signal);
378
+ const value = result;
379
+ const text = (value.content ?? []).map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").join("");
380
+ return { text, isError: Boolean(value.isError) };
381
+ } catch (error) {
382
+ return { text: JSON.stringify({ error: "cave_recovery_transport", message: error.message }), isError: true };
383
+ }
384
+ }
385
+ dispose() {
386
+ this.disposed = true;
387
+ const child = this.child;
388
+ this.child = void 0;
389
+ this.initialized = false;
390
+ for (const [, entry] of this.pending) {
391
+ clearTimeout(entry.timer);
392
+ entry.reject(new Error("recovery client disposed"));
393
+ }
394
+ this.pending.clear();
395
+ this.stop(child);
396
+ void this.ensuring?.then(() => {
397
+ const late = this.child;
398
+ this.child = void 0;
399
+ this.stop(late);
400
+ });
401
+ }
402
+ // resolveMcpBinary appends .exe on win32, but CAVEMAN_MCP_BIN is an operator
403
+ // override that can name anything — including a .cmd shim, which execFile
404
+ // and spawn both refuse with EFTYPE. Route through the same resolver the hook
405
+ // bridge uses so the override is as spawnable as the default. Fail-closed:
406
+ // callers treat a throw as "recovery cannot hold" and pass through.
407
+ invocation(args) {
408
+ try {
409
+ return portableInvocation(this.binary, args);
410
+ } catch {
411
+ return void 0;
412
+ }
413
+ }
414
+ probe() {
415
+ return new Promise((resolve2) => {
416
+ const portable = this.invocation(["version", "--json"]);
417
+ if (!portable) return resolve2(false);
418
+ execFile2(portable.command, portable.args, { timeout: PROBE_TIMEOUT_MS, encoding: "utf8" }, (error, stdout) => {
419
+ if (error) return resolve2(false);
420
+ try {
421
+ const parsed = JSON.parse(stdout);
422
+ resolve2(Array.isArray(parsed?.capabilities) && parsed.capabilities.includes("mcp_recovery"));
423
+ } catch {
424
+ resolve2(false);
425
+ }
426
+ });
427
+ });
428
+ }
429
+ async start() {
430
+ let child;
431
+ try {
432
+ const portable = this.invocation([]);
433
+ if (!portable) return false;
434
+ child = spawn(portable.command, portable.args, { stdio: ["pipe", "pipe", "ignore"] });
435
+ } catch {
436
+ return false;
437
+ }
438
+ this.child = child;
439
+ this.initialized = false;
440
+ this.buffer = "";
441
+ child.on("error", () => this.onChildGone(child));
442
+ child.on("exit", () => this.onChildGone(child));
443
+ child.stdin?.on("error", () => this.onChildGone(child));
444
+ child.stdout?.setEncoding("utf8");
445
+ child.stdout?.on("data", (chunk) => this.onData(chunk));
446
+ try {
447
+ await this.call("initialize", {
448
+ protocolVersion: "2024-11-05",
449
+ capabilities: {},
450
+ clientInfo: { name: "caveman-pi-extension", version: "0.1.0" }
451
+ }, void 0, INIT_TIMEOUT_MS);
452
+ this.notify("notifications/initialized");
453
+ if (this.disposed) {
454
+ this.onChildGone(child);
455
+ this.stop(child);
456
+ return false;
457
+ }
458
+ this.initialized = true;
459
+ return true;
460
+ } catch {
461
+ this.onChildGone(child);
462
+ this.stop(child);
463
+ return false;
464
+ }
465
+ }
466
+ stop(child) {
467
+ if (!child) return;
468
+ try {
469
+ child.stdin?.end();
470
+ } catch {
471
+ }
472
+ const term = setTimeout(() => {
473
+ try {
474
+ child.kill("SIGTERM");
475
+ } catch {
476
+ }
477
+ }, 500);
478
+ const kill = setTimeout(() => {
479
+ try {
480
+ child.kill("SIGKILL");
481
+ } catch {
482
+ }
483
+ }, 2e3);
484
+ child.once("exit", () => {
485
+ clearTimeout(term);
486
+ clearTimeout(kill);
487
+ });
488
+ }
489
+ onChildGone(child) {
490
+ if (this.child !== child) return;
491
+ this.child = void 0;
492
+ this.initialized = false;
493
+ for (const [, entry] of this.pending) {
494
+ clearTimeout(entry.timer);
495
+ entry.reject(new Error("caveman-mcp exited"));
496
+ }
497
+ this.pending.clear();
498
+ }
499
+ onData(chunk) {
500
+ this.buffer += chunk;
501
+ let newline;
502
+ while ((newline = this.buffer.indexOf("\n")) !== -1) {
503
+ const line = this.buffer.slice(0, newline).trim();
504
+ this.buffer = this.buffer.slice(newline + 1);
505
+ if (!line) continue;
506
+ let message;
507
+ try {
508
+ message = JSON.parse(line);
509
+ } catch {
510
+ continue;
511
+ }
512
+ if (typeof message.id !== "number") continue;
513
+ const entry = this.pending.get(message.id);
514
+ if (!entry) continue;
515
+ this.pending.delete(message.id);
516
+ clearTimeout(entry.timer);
517
+ if (message.error) entry.reject(new Error(message.error.message || "caveman-mcp error"));
518
+ else entry.resolve(message.result);
519
+ }
520
+ }
521
+ call(method, params, signal, timeoutMs = CALL_TIMEOUT_MS) {
522
+ const child = this.child;
523
+ if (!child?.stdin?.writable) return Promise.reject(new Error("caveman-mcp not running"));
524
+ if (signal?.aborted) return Promise.reject(new Error("retrieve cancelled"));
525
+ const id = this.nextId++;
526
+ return new Promise((resolve2, reject) => {
527
+ const timer = setTimeout(() => {
528
+ this.pending.delete(id);
529
+ reject(new Error(`caveman-mcp ${method} timed out`));
530
+ }, timeoutMs);
531
+ timer.unref?.();
532
+ const onAbort = () => {
533
+ this.pending.delete(id);
534
+ clearTimeout(timer);
535
+ reject(new Error("retrieve cancelled"));
536
+ };
537
+ signal?.addEventListener("abort", onAbort, { once: true });
538
+ this.pending.set(id, {
539
+ resolve: (value) => {
540
+ signal?.removeEventListener("abort", onAbort);
541
+ resolve2(value);
542
+ },
543
+ reject: (error) => {
544
+ signal?.removeEventListener("abort", onAbort);
545
+ reject(error);
546
+ },
547
+ timer
548
+ });
549
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n", (error) => {
550
+ if (error) {
551
+ this.pending.delete(id);
552
+ clearTimeout(timer);
553
+ signal?.removeEventListener("abort", onAbort);
554
+ reject(error);
555
+ }
556
+ });
557
+ });
558
+ }
559
+ notify(method) {
560
+ try {
561
+ this.child?.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method }) + "\n");
562
+ } catch {
563
+ }
564
+ }
565
+ };
566
+
567
+ // ../pi-extension/src/tool-output.ts
568
+ async function shrinkToolResult(bridge, sessionId, event) {
569
+ const text = event.content.map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").join("");
570
+ if (!text) return void 0;
571
+ if (Buffer.byteLength(text, "utf8") > MAX_TOOL_OUTPUT_BYTES) return void 0;
572
+ const response = await bridge.call(event.isError ? "PostToolUseFailure" : "PostToolUse", {
573
+ session_id: sessionId,
574
+ tool_name: event.toolName,
575
+ tool_input: event.input,
576
+ tool_output: text
577
+ });
578
+ const replacement = outputReplacementOf(response);
579
+ if (!replacement) return void 0;
580
+ return { content: [{ type: "text", text: replacement }, ...event.content.filter((block) => block.type !== "text")] };
581
+ }
582
+
583
+ // ../pi-extension/src/index.ts
584
+ var HEALTH_TIMEOUT_MS = 750;
585
+ var RECOVERY_TOOL = "caveman_retrieve";
586
+ function cavemanHome() {
587
+ return process.env.CAVEMAN_HOME || join4(homedir3(), ".caveman");
588
+ }
589
+ function gatewayUrl() {
590
+ const env = process.env.CAVE_GATEWAY_URL?.trim();
591
+ if (env) return env;
592
+ try {
593
+ const config = JSON.parse(readFileSync2(join4(homedir3(), ".caveman-cloud", "config.json"), "utf8"));
594
+ if (typeof config.gatewayUrl === "string" && config.gatewayUrl) return config.gatewayUrl;
595
+ } catch {
596
+ }
597
+ return "http://127.0.0.1:8787";
598
+ }
599
+ function runStateRecoveryViaMcp(gateway) {
600
+ let port;
601
+ try {
602
+ const url = new URL(gateway);
603
+ port = url.port || (url.protocol === "https:" ? "443" : "80");
604
+ } catch {
605
+ return void 0;
606
+ }
607
+ try {
608
+ const state = JSON.parse(readFileSync2(join4(cavemanHome(), "run", `${port}.json`), "utf8"));
609
+ if (state?.schema !== "caveman.proxy.run.v1") return void 0;
610
+ if (typeof state.pid !== "number" || typeof state.instance_token !== "string") return void 0;
611
+ if (state.owner !== "wrap" && state.owner !== "start") return void 0;
612
+ try {
613
+ process.kill(state.pid, 0);
614
+ } catch {
615
+ return void 0;
616
+ }
617
+ return Boolean(state.recovery_via_mcp);
618
+ } catch {
619
+ return void 0;
620
+ }
621
+ }
622
+ async function proxyAliveOnce(gateway) {
623
+ const controller = new AbortController();
624
+ const timer = setTimeout(() => controller.abort(), HEALTH_TIMEOUT_MS);
625
+ try {
626
+ const response = await fetch(`${gateway.replace(/\/+$/, "")}/health/live`, { signal: controller.signal });
627
+ await response.body?.cancel();
628
+ return response.ok;
629
+ } catch {
630
+ return false;
631
+ } finally {
632
+ clearTimeout(timer);
633
+ }
634
+ }
635
+ async function proxyAlive(gateway) {
636
+ for (let attempt = 0; attempt < 3; attempt++) {
637
+ if (await proxyAliveOnce(gateway)) return true;
638
+ await new Promise((resolve2) => setTimeout(resolve2, 300));
639
+ }
640
+ return false;
641
+ }
642
+ function index_default(pi) {
643
+ const bridge = new HookBridge();
644
+ const recovery = new RecoveryClient();
645
+ let router;
646
+ let sessionId = "default";
647
+ let coreContext;
648
+ let pendingContext = [];
649
+ let pendingBytes = 0;
650
+ let gateDone = false;
651
+ const notify = (ctx, message, kind) => {
652
+ if (ctx?.hasUI) ctx.ui.notify(message, kind);
653
+ else process.stderr.write(`${message}
654
+ `);
655
+ };
656
+ const debug = (message) => {
657
+ if (process.env.CAVEMAN_PI_DEBUG === "1") process.stderr.write(`[caveman-pi] ${message}
658
+ `);
659
+ };
660
+ const guardedBase = (fn, label = fn.name || "handler") => (async (...args) => {
661
+ try {
662
+ debug(`enter ${label}`);
663
+ const result = await fn(...args);
664
+ debug(`exit ${label}`);
665
+ return result;
666
+ } catch (error) {
667
+ process.stderr.write(`caveman pi extension: ${error.message}
668
+ `);
669
+ return void 0;
670
+ }
671
+ });
672
+ const GUARD = (label) => (fn) => guardedBase(fn, label);
673
+ const GUARD_session_start = GUARD("session_start");
674
+ const GUARD_model_select = GUARD("model_select");
675
+ const GUARD_before_agent_start = GUARD("before_agent_start");
676
+ const GUARD_turn_start = GUARD("turn_start");
677
+ const GUARD_turn_end = GUARD("turn_end");
678
+ const GUARD_tool_call = GUARD("tool_call");
679
+ const GUARD_tool_result = GUARD("tool_result");
680
+ const GUARD_session_before_compact = GUARD("session_before_compact");
681
+ const GUARD_session_compact = GUARD("session_compact");
682
+ const GUARD_session_shutdown = GUARD("session_shutdown");
683
+ pi.registerTool({
684
+ name: RECOVERY_TOOL,
685
+ label: "Retrieve compressed context",
686
+ description: "Recover exact original content from a Caveman recovery handle.",
687
+ parameters: Type.Object({
688
+ recovery_handle: Type.String({ description: "Exact ccr_ handle returned by Caveman or copied from a <<ccr:HANDLE>> marker." }),
689
+ query: Type.Optional(Type.String({ description: "One broad description covering every detail needed from this handle." }))
690
+ }),
691
+ async execute(_toolCallId, params, signal) {
692
+ const result = await recovery.retrieve(params.recovery_handle, params.query, signal);
693
+ if (result.isError) throw new Error(result.text || "caveman_retrieve failed");
694
+ return { content: [{ type: "text", text: result.text }], details: { recovery_handle: params.recovery_handle } };
695
+ }
696
+ });
697
+ pi.on("session_start", GUARD_session_start(async (_event, ctx) => {
698
+ router ??= new ProviderRouter(pi, (message, kind) => notify(ctx, message, kind));
699
+ gateDone = false;
700
+ coreContext = void 0;
701
+ pendingContext = [];
702
+ pendingBytes = 0;
703
+ try {
704
+ sessionId = ctx.sessionManager.getSessionId() || "default";
705
+ } catch {
706
+ sessionId = "default";
707
+ }
708
+ const start = await bridge.call("SessionStart", { session_id: sessionId });
709
+ coreContext = additionalContextOf(start);
710
+ if (!start) {
711
+ gateDone = true;
712
+ notify(ctx, "Caveman: direct mode, no compression this session (caveman native runtime unreachable)", "warning");
713
+ return;
714
+ }
715
+ const gateway = gatewayUrl();
716
+ const alive = await proxyAlive(gateway);
717
+ const published = runStateRecoveryViaMcp(gateway);
718
+ const recoveryReady = alive ? await recovery.ensure() : false;
719
+ gateDone = true;
720
+ if (!alive || published === void 0) {
721
+ notify(ctx, "Caveman: direct mode, no compression this session (local proxy not running)", "warning");
722
+ return;
723
+ }
724
+ if (!published || !recoveryReady) {
725
+ notify(ctx, "Caveman: direct mode, no compression this session (recovery not available \u2014 run `caveman doctor pi`)", "warning");
726
+ return;
727
+ }
728
+ await router.openGate(gateway, ctx);
729
+ }));
730
+ pi.on("model_select", GUARD_model_select(async (event, ctx) => {
731
+ if (gateDone) await router?.apply(event.model, ctx);
732
+ }));
733
+ pi.on("before_agent_start", GUARD_before_agent_start(async (event, ctx) => {
734
+ const response = await bridge.call("UserPromptSubmit", {
735
+ session_id: sessionId,
736
+ model: ctx.model?.id,
737
+ provider: ctx.model?.provider,
738
+ prompt: promptDigest(event.prompt),
739
+ task_type: taskType(event.prompt),
740
+ task_terms: taskTerms(event.prompt),
741
+ task_continuation: taskContinuation(event.prompt)
742
+ });
743
+ const dynamic = [additionalContextOf(response), ...pendingContext].filter(Boolean);
744
+ pendingContext = [];
745
+ pendingBytes = 0;
746
+ if (!coreContext && dynamic.length === 0) return void 0;
747
+ const parts = [event.systemPrompt, coreContext, ...dynamic].filter(Boolean);
748
+ return { systemPrompt: parts.join("\n\n") };
749
+ }));
750
+ pi.on("turn_start", GUARD_turn_start(() => {
751
+ void bridge.call("ModelBefore", { session_id: sessionId });
752
+ }));
753
+ pi.on("turn_end", GUARD_turn_end(async () => {
754
+ await bridge.call("ModelAfter", { session_id: sessionId });
755
+ void bridge.call("Stop", { session_id: sessionId });
756
+ }));
757
+ pi.on("tool_call", GUARD_tool_call(async (event) => {
758
+ const response = await bridge.call("PreToolUse", {
759
+ session_id: sessionId,
760
+ tool_name: event.toolName,
761
+ tool_input: event.input
762
+ });
763
+ const context = additionalContextOf(response);
764
+ const bytes = context ? Buffer.byteLength(context, "utf8") : 0;
765
+ if (context && pendingBytes + bytes <= MAX_CONTEXT_BYTES) {
766
+ pendingContext.push(context);
767
+ pendingBytes += bytes;
768
+ }
769
+ }));
770
+ pi.on("tool_result", GUARD_tool_result((event) => event.toolName === RECOVERY_TOOL ? void 0 : shrinkToolResult(bridge, sessionId, event)));
771
+ pi.on("session_before_compact", GUARD_session_before_compact(() => {
772
+ void bridge.call("PreCompact", { session_id: sessionId });
773
+ }));
774
+ pi.on("session_compact", GUARD_session_compact(async () => {
775
+ const response = await bridge.call("PostCompact", { session_id: sessionId });
776
+ const context = additionalContextOf(response);
777
+ if (context) coreContext = context;
778
+ }));
779
+ pi.on("session_shutdown", GUARD_session_shutdown(async () => {
780
+ await bridge.call("SessionEnd", { session_id: sessionId });
781
+ router?.closeGate();
782
+ recovery.dispose();
783
+ }));
784
+ }
785
+ export {
786
+ index_default as default
787
+ };