@caveman-ai/cli 2.0.0 → 2.1.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 +15 -0
- package/dist/agent-skills.generated.js +27 -3
- package/dist/agents.generated.js +37 -27
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +120 -35
- package/dist/index.js +807 -129
- package/dist/portable-command.js +36 -15
- package/dist/provider-routing.js +11 -0
- package/package.json +3 -3
|
@@ -37,6 +37,14 @@ function compatTarget(base, path) {
|
|
|
37
37
|
while (overlap > 0 && left.slice(-overlap).join("/") !== right.slice(0, overlap).join("/")) overlap--;
|
|
38
38
|
return base.origin + "/" + [...left, ...right.slice(overlap)].join("/");
|
|
39
39
|
}
|
|
40
|
+
function verifiedChatGPTSubscriptionRoute(gateway, api, provider, originalBaseUrl, published) {
|
|
41
|
+
if (api !== "openai-codex-responses" || provider !== "openai-codex") return void 0;
|
|
42
|
+
const original = endpoint(originalBaseUrl);
|
|
43
|
+
const upstream = endpoint(published?.provider_upstreams?.["openai-codex"]);
|
|
44
|
+
if (!original || !upstream || !endpoint(gateway)) return void 0;
|
|
45
|
+
if (append(upstream, "/codex/responses") !== append(original, "/codex/responses")) return void 0;
|
|
46
|
+
return trimTrailingSlashes(gateway);
|
|
47
|
+
}
|
|
40
48
|
function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, published) {
|
|
41
49
|
const original = endpoint(originalBaseUrl);
|
|
42
50
|
if (!original || !endpoint(gateway)) return void 0;
|
|
@@ -122,11 +130,36 @@ import { dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
|
122
130
|
function parseWindowsNodeShim(source) {
|
|
123
131
|
for (const line of source.split(/\r?\n/)) {
|
|
124
132
|
if (!/(?:\bnode(?:\.exe)?\b|_prog)/i.test(line) || !/%\*/.test(line)) continue;
|
|
125
|
-
const match = line.match(/"%(?:dp0%|~dp0)
|
|
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);
|
|
126
134
|
if (match) return match[1];
|
|
127
135
|
}
|
|
128
136
|
return null;
|
|
129
137
|
}
|
|
138
|
+
function parseWindowsNestedShim(source) {
|
|
139
|
+
const match = source.match(/^(?:@echo[ \t]+off[ \t]*\r?\n)?[ \t]*"%~dp0\\?([\w .@+\-\\/]+\.(?:cmd|bat))"[ \t]+%\*[ \t]*(?:\r?\n)?$/i);
|
|
140
|
+
return match?.[1] ?? null;
|
|
141
|
+
}
|
|
142
|
+
function resolveWindowsNodeShim(executable, depth = 0, seen = /* @__PURE__ */ new Set()) {
|
|
143
|
+
if (depth > 4) throw new Error("Windows command shim nesting too deep");
|
|
144
|
+
const normalized = resolve(executable);
|
|
145
|
+
if (seen.has(normalized.toLowerCase())) throw new Error("Windows command shim cycle");
|
|
146
|
+
seen.add(normalized.toLowerCase());
|
|
147
|
+
const stat = statSync(normalized);
|
|
148
|
+
if (!stat.isFile() || stat.size > 256 * 1024) {
|
|
149
|
+
throw new Error(`cannot safely launch Windows command shim: ${normalized}`);
|
|
150
|
+
}
|
|
151
|
+
const source = readFileSync(normalized, "utf8");
|
|
152
|
+
const nested = parseWindowsNestedShim(source);
|
|
153
|
+
const forwardsToBatch = /"[^"\r\n]+\.(?:cmd|bat)"[ \t]+%\*/i.test(source);
|
|
154
|
+
const jsTarget = forwardsToBatch ? null : parseWindowsNodeShim(source);
|
|
155
|
+
const child = jsTarget ?? nested;
|
|
156
|
+
if (!child) {
|
|
157
|
+
throw new Error(`cannot safely launch non-Node Windows command shim: ${normalized}; install a native .exe`);
|
|
158
|
+
}
|
|
159
|
+
const target = /^[A-Za-z]:[\\/]/.test(child) ? child : resolve(dirname(normalized), ...child.split(/[\\/]+/));
|
|
160
|
+
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);
|
|
162
|
+
}
|
|
130
163
|
function envValue(env, name) {
|
|
131
164
|
const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
|
132
165
|
return key === void 0 ? void 0 : env[key];
|
|
@@ -151,18 +184,7 @@ function portableInvocation(command, args, platform = process.platform, env = pr
|
|
|
151
184
|
if (platform !== "win32") return { command, args: [...args] };
|
|
152
185
|
const executable = resolveWindowsCommand(command, env) ?? command;
|
|
153
186
|
if (!/\.(?:cmd|bat)$/i.test(executable)) return { command: executable, args: [...args] };
|
|
154
|
-
const
|
|
155
|
-
if (!stat.isFile() || stat.size > 256 * 1024) {
|
|
156
|
-
throw new Error(`cannot safely launch Windows command shim: ${executable}`);
|
|
157
|
-
}
|
|
158
|
-
const shimScript = parseWindowsNodeShim(readFileSync(executable, "utf8"));
|
|
159
|
-
if (!shimScript) {
|
|
160
|
-
throw new Error(`cannot safely launch non-Node Windows command shim: ${executable}; install a native .exe`);
|
|
161
|
-
}
|
|
162
|
-
const script = /^[A-Za-z]:[\\/]/.test(shimScript) ? shimScript : resolve(dirname(executable), ...shimScript.split(/[\\/]+/));
|
|
163
|
-
if (!statSync(script).isFile()) {
|
|
164
|
-
throw new Error(`Windows command shim target is missing: ${script}`);
|
|
165
|
-
}
|
|
187
|
+
const script = resolveWindowsNodeShim(executable);
|
|
166
188
|
return { command: process.execPath, args: [script, ...args] };
|
|
167
189
|
}
|
|
168
190
|
|
|
@@ -205,6 +227,14 @@ function outputReplacementOf(response) {
|
|
|
205
227
|
const replacement = response?.hookSpecificOutput?.updatedToolOutput ?? response?.output_replacement;
|
|
206
228
|
return replacement ? replacement : void 0;
|
|
207
229
|
}
|
|
230
|
+
function normalizeRecoveryHandle(value) {
|
|
231
|
+
if (!fits(value, MAX_RECOVERY_REF_BYTES)) return void 0;
|
|
232
|
+
let handle = value.trim();
|
|
233
|
+
if (handle.startsWith("<<") && handle.endsWith(">>")) handle = handle.slice(2, -2).trim();
|
|
234
|
+
if (handle.startsWith("ccr://")) handle = handle.slice(6).trim().replace(/^\/+|\/+$/g, "");
|
|
235
|
+
else if (handle.startsWith("ccr:")) handle = handle.slice(4).trim();
|
|
236
|
+
return /^ccr_[A-Za-z0-9_-]+$/.test(handle) ? handle : void 0;
|
|
237
|
+
}
|
|
208
238
|
var ROUTES_BY_API = {
|
|
209
239
|
"anthropic-messages": "/w/pi",
|
|
210
240
|
"openai-completions": "/w/pi/openai/v1",
|
|
@@ -212,6 +242,9 @@ var ROUTES_BY_API = {
|
|
|
212
242
|
"google-generative-ai": "/w/pi/v1beta"
|
|
213
243
|
};
|
|
214
244
|
var ROUTES_BY_PROVIDER_API = {
|
|
245
|
+
"openai-codex": {
|
|
246
|
+
"openai-codex-responses": "/w/pi"
|
|
247
|
+
},
|
|
215
248
|
"opencode-go": {
|
|
216
249
|
"anthropic-messages": "/w/pi/compat/opencode-go",
|
|
217
250
|
"openai-completions": "/w/pi/compat/opencode-go/v1",
|
|
@@ -222,6 +255,7 @@ var UPSTREAM_HOSTS_BY_PROVIDER = {
|
|
|
222
255
|
anthropic: "api.anthropic.com",
|
|
223
256
|
openai: "api.openai.com",
|
|
224
257
|
google: "generativelanguage.googleapis.com",
|
|
258
|
+
"openai-codex": "chatgpt.com",
|
|
225
259
|
"opencode-go": "opencode.ai"
|
|
226
260
|
};
|
|
227
261
|
function upstreamHostFor(provider) {
|
|
@@ -243,13 +277,8 @@ function compatUpstreamFor(provider, compatUpstreams) {
|
|
|
243
277
|
}
|
|
244
278
|
function routeForApi(gateway, api, provider, originalBaseUrl, compatUpstreams, providerUpstreams) {
|
|
245
279
|
if (originalBaseUrl !== void 0) {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
api,
|
|
249
|
-
provider ?? "",
|
|
250
|
-
originalBaseUrl,
|
|
251
|
-
{ compat_upstreams: compatUpstreams, provider_upstreams: providerUpstreams }
|
|
252
|
-
);
|
|
280
|
+
const published = { compat_upstreams: compatUpstreams, provider_upstreams: providerUpstreams };
|
|
281
|
+
return verifiedChatGPTSubscriptionRoute(joinUrl(gateway, "/w/pi"), api, provider ?? "", originalBaseUrl, published) ?? verifiedProviderRoute(joinUrl(gateway, "/w/pi"), api, provider ?? "", originalBaseUrl, published);
|
|
253
282
|
}
|
|
254
283
|
const table = (provider ? ROUTES_BY_PROVIDER_API[provider] : void 0) ?? ROUTES_BY_API;
|
|
255
284
|
if (provider && !UPSTREAM_HOSTS_BY_PROVIDER[provider]) return void 0;
|
|
@@ -413,6 +442,15 @@ function compatForRoutedModel(model) {
|
|
|
413
442
|
const explicit2 = model.compat;
|
|
414
443
|
return { ...explicit2, sessionAffinityFormat: explicit2?.sessionAffinityFormat ?? (openRouter ? "openrouter" : "openai") };
|
|
415
444
|
}
|
|
445
|
+
if (model.api === "anthropic-messages") {
|
|
446
|
+
if (!openRouter) return model.compat;
|
|
447
|
+
const explicit2 = model.compat;
|
|
448
|
+
return {
|
|
449
|
+
...explicit2,
|
|
450
|
+
sendSessionAffinityHeaders: explicit2?.sendSessionAffinityHeaders ?? true,
|
|
451
|
+
sessionAffinityFormat: explicit2?.sessionAffinityFormat ?? "openrouter"
|
|
452
|
+
};
|
|
453
|
+
}
|
|
416
454
|
if (model.api !== "openai-completions") return model.compat;
|
|
417
455
|
const explicit = model.compat;
|
|
418
456
|
const zai = provider === "zai" || provider === "zai-coding-cn" || url.includes("api.z.ai") || url.includes("open.bigmodel.cn");
|
|
@@ -435,7 +473,7 @@ function compatForRoutedModel(model) {
|
|
|
435
473
|
maxTokensField: explicit?.maxTokensField ?? (maxTokens ? "max_tokens" : "max_completion_tokens"),
|
|
436
474
|
requiresReasoningContentOnAssistantMessages: explicit?.requiresReasoningContentOnAssistantMessages ?? deepseek,
|
|
437
475
|
thinkingFormat: explicit?.thinkingFormat ?? (deepseek ? "deepseek" : zai ? "zai" : together ? "together" : antLing ? "ant-ling" : openRouter ? "openrouter" : "openai"),
|
|
438
|
-
|
|
476
|
+
sendSessionAffinityHeaders: explicit?.sendSessionAffinityHeaders ?? openRouter,
|
|
439
477
|
sessionAffinityFormat: explicit?.sessionAffinityFormat ?? (openRouter ? "openrouter" : "openai"),
|
|
440
478
|
supportsLongCacheRetention: explicit?.supportsLongCacheRetention ?? !(together || cloudflareWorkers || cloudflareGateway || nvidia || antLing)
|
|
441
479
|
};
|
|
@@ -495,11 +533,15 @@ var ProviderRouter = class {
|
|
|
495
533
|
const compatibilityIssue = model.api === "openai-completions" && original.includes("api.openai.com") ? "Pi cannot preserve this OpenAI Chat endpoint's prompt cache keys through routing" : void 0;
|
|
496
534
|
let headerIssue;
|
|
497
535
|
let oauth = true;
|
|
536
|
+
let authKnown = false;
|
|
498
537
|
try {
|
|
499
538
|
oauth = ctx.modelRegistry.isUsingOAuth(model);
|
|
539
|
+
authKnown = true;
|
|
500
540
|
} catch {
|
|
501
541
|
}
|
|
502
|
-
|
|
542
|
+
const chatGPTSubscriptionModel = model.provider === "openai-codex" && model.api === "openai-codex-responses";
|
|
543
|
+
const authIssue = !authKnown ? "authentication type could not be verified" : oauth && !chatGPTSubscriptionModel ? "OAuth/subscription credentials are not routed" : !oauth && chatGPTSubscriptionModel && route ? "ChatGPT subscription route requires OAuth" : void 0;
|
|
544
|
+
if (!oauth && route && !compatibilityIssue && !chatGPTSubscriptionModel) {
|
|
503
545
|
try {
|
|
504
546
|
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
505
547
|
if (!auth.ok) throw new Error("request auth unavailable");
|
|
@@ -530,13 +572,13 @@ var ProviderRouter = class {
|
|
|
530
572
|
}
|
|
531
573
|
if (!this.gateOpen || this.gateGeneration !== gateGeneration || ctx.model !== model) return;
|
|
532
574
|
}
|
|
533
|
-
if (!route ||
|
|
575
|
+
if (!route || authIssue || compatibilityIssue || headerIssue) {
|
|
534
576
|
if (!await this.restoreCurrentModel(ctx)) return;
|
|
535
577
|
if (!this.warnedModels.has(key)) {
|
|
536
578
|
this.warnedModels.add(key);
|
|
537
579
|
const mount = compatUpstreamFor(model.provider, this.compatUpstreams);
|
|
538
580
|
const expected = mount !== void 0 ? hostOf(mount) : upstreamHostFor(model.provider);
|
|
539
|
-
const reason =
|
|
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`);
|
|
540
582
|
this.notify(boundedString(`Caveman: pass-through for ${key} (${reason}); no compression`, MAX_MESSAGE_BYTES), "warning");
|
|
541
583
|
}
|
|
542
584
|
return;
|
|
@@ -598,12 +640,14 @@ var ProviderRouter = class {
|
|
|
598
640
|
|
|
599
641
|
// ../pi-extension/src/recovery.ts
|
|
600
642
|
import { execFile as execFile2, spawn } from "node:child_process";
|
|
643
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
601
644
|
import { existsSync as existsSync2 } from "node:fs";
|
|
602
645
|
import { homedir as homedir2 } from "node:os";
|
|
603
646
|
import { delimiter, join as join3 } from "node:path";
|
|
604
647
|
var PROBE_TIMEOUT_MS = 2e3;
|
|
605
648
|
var CALL_TIMEOUT_MS = 3e4;
|
|
606
649
|
var INIT_TIMEOUT_MS = 2e3;
|
|
650
|
+
var VERIFY_TIMEOUT_MS = 2e3;
|
|
607
651
|
function resolveMcpBinary(env = process.env) {
|
|
608
652
|
const explicit = env.CAVEMAN_MCP_BIN?.trim();
|
|
609
653
|
if (explicit) return explicit;
|
|
@@ -619,6 +663,7 @@ var RecoveryClient = class {
|
|
|
619
663
|
child;
|
|
620
664
|
initialized = false;
|
|
621
665
|
probed;
|
|
666
|
+
verificationSupported = false;
|
|
622
667
|
ensuring;
|
|
623
668
|
nextId = 1;
|
|
624
669
|
pending = /* @__PURE__ */ new Map();
|
|
@@ -662,6 +707,28 @@ var RecoveryClient = class {
|
|
|
662
707
|
return { text: JSON.stringify({ error: "cave_recovery_transport", message: error.message }), isError: true };
|
|
663
708
|
}
|
|
664
709
|
}
|
|
710
|
+
// A silent pre-publication proof must not count as delivery to the model.
|
|
711
|
+
// Old companions ignore unknown arguments, so capability proof is mandatory
|
|
712
|
+
// before sending verify_only through the same long-lived recovery child.
|
|
713
|
+
async verify(handle, originalText) {
|
|
714
|
+
const normalized = normalizeRecoveryHandle(handle);
|
|
715
|
+
const bytes = Buffer.byteLength(originalText, "utf8");
|
|
716
|
+
if (!normalized || bytes > MAX_TOOL_OUTPUT_BYTES) return false;
|
|
717
|
+
try {
|
|
718
|
+
if (!await this.ensure() || !this.verificationSupported) return false;
|
|
719
|
+
const result = await this.call("tools/call", {
|
|
720
|
+
name: "caveman_retrieve",
|
|
721
|
+
arguments: { recovery_handle: normalized, verify_only: true }
|
|
722
|
+
}, void 0, VERIFY_TIMEOUT_MS);
|
|
723
|
+
if (result.isError || !Array.isArray(result.content) || result.content.length !== 1) return false;
|
|
724
|
+
const block = result.content[0];
|
|
725
|
+
if (block?.type !== "text" || typeof block.text !== "string" || Buffer.byteLength(block.text, "utf8") > MAX_MESSAGE_BYTES) return false;
|
|
726
|
+
const proof = JSON.parse(block.text);
|
|
727
|
+
return proof?.recovery_handle === normalized && proof.byte_length === bytes && proof.sha256 === createHash2("sha256").update(originalText, "utf8").digest("hex");
|
|
728
|
+
} catch {
|
|
729
|
+
return false;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
665
732
|
dispose() {
|
|
666
733
|
this.disposed = true;
|
|
667
734
|
const child = this.child;
|
|
@@ -699,6 +766,7 @@ var RecoveryClient = class {
|
|
|
699
766
|
if (error) return resolve2(false);
|
|
700
767
|
try {
|
|
701
768
|
const parsed = JSON.parse(stdout);
|
|
769
|
+
this.verificationSupported = Array.isArray(parsed?.capabilities) && parsed.capabilities.includes("recovery_verification");
|
|
702
770
|
resolve2(Array.isArray(parsed?.capabilities) && parsed.capabilities.includes("mcp_recovery"));
|
|
703
771
|
} catch {
|
|
704
772
|
resolve2(false);
|
|
@@ -727,7 +795,7 @@ var RecoveryClient = class {
|
|
|
727
795
|
await this.call("initialize", {
|
|
728
796
|
protocolVersion: "2024-11-05",
|
|
729
797
|
capabilities: {},
|
|
730
|
-
clientInfo: { name: "caveman-pi-extension", version: "0.
|
|
798
|
+
clientInfo: { name: "caveman-pi-extension", version: "0.3.0" }
|
|
731
799
|
}, void 0, INIT_TIMEOUT_MS);
|
|
732
800
|
this.notify("notifications/initialized");
|
|
733
801
|
if (this.disposed) {
|
|
@@ -845,18 +913,35 @@ var RecoveryClient = class {
|
|
|
845
913
|
};
|
|
846
914
|
|
|
847
915
|
// ../pi-extension/src/tool-output.ts
|
|
848
|
-
async function shrinkToolResult(bridge, sessionId, event) {
|
|
916
|
+
async function shrinkToolResult(bridge, sessionId, event, recovery) {
|
|
849
917
|
const text = event.content.map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").join("");
|
|
850
918
|
if (!text) return void 0;
|
|
851
919
|
if (Buffer.byteLength(text, "utf8") > MAX_TOOL_OUTPUT_BYTES) return void 0;
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
920
|
+
let replacement;
|
|
921
|
+
try {
|
|
922
|
+
const response = await bridge.call(event.isError ? "PostToolUseFailure" : "PostToolUse", {
|
|
923
|
+
session_id: sessionId,
|
|
924
|
+
tool_name: event.toolName,
|
|
925
|
+
tool_input: event.input,
|
|
926
|
+
tool_output: text
|
|
927
|
+
});
|
|
928
|
+
const proposed = outputReplacementOf(response);
|
|
929
|
+
if (!proposed || Buffer.byteLength(proposed, "utf8") > MAX_OUTPUT_REPLACEMENT_BYTES) return void 0;
|
|
930
|
+
let handle = normalizeRecoveryHandle(response?.recovery_ref);
|
|
931
|
+
if (response?.recovery_ref !== void 0 && !handle) return void 0;
|
|
932
|
+
let advertised = false;
|
|
933
|
+
for (const match of proposed.matchAll(/(?:<<)?ccr(?::|_)[^\s"'`]*/g)) {
|
|
934
|
+
if (match.index > 0 && /[A-Za-z0-9_<:/]/.test(proposed[match.index - 1])) return void 0;
|
|
935
|
+
const candidate = normalizeRecoveryHandle(match[0]);
|
|
936
|
+
if (!candidate || handle && candidate !== handle) return void 0;
|
|
937
|
+
handle = candidate;
|
|
938
|
+
advertised = true;
|
|
939
|
+
}
|
|
940
|
+
if (!advertised || !handle || !await recovery.verify(handle, text)) return void 0;
|
|
941
|
+
replacement = proposed;
|
|
942
|
+
} catch {
|
|
943
|
+
return void 0;
|
|
944
|
+
}
|
|
860
945
|
return { content: [{ type: "text", text: replacement }, ...event.content.filter((block) => block.type !== "text")] };
|
|
861
946
|
}
|
|
862
947
|
|
|
@@ -1053,7 +1138,7 @@ function index_default(pi) {
|
|
|
1053
1138
|
pendingBytes += bytes;
|
|
1054
1139
|
}
|
|
1055
1140
|
}));
|
|
1056
|
-
pi.on("tool_result", GUARD_tool_result((event) => event.toolName === RECOVERY_TOOL ? void 0 : shrinkToolResult(bridge, sessionId, event)));
|
|
1141
|
+
pi.on("tool_result", GUARD_tool_result((event) => event.toolName === RECOVERY_TOOL ? void 0 : shrinkToolResult(bridge, sessionId, event, recovery)));
|
|
1057
1142
|
pi.on("session_before_compact", GUARD_session_before_compact(() => {
|
|
1058
1143
|
void bridge.call("PreCompact", { session_id: sessionId });
|
|
1059
1144
|
}));
|