@caveman-ai/cli 4.0.1 → 4.2.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.
@@ -56,9 +56,13 @@ function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, publishe
56
56
  if (mount !== void 0) {
57
57
  const upstream2 = endpoint(mount);
58
58
  if (!upstream2 || family === "gemini") return void 0;
59
- const suffix = family === "openai" ? "/v1" : "";
60
- if (compatTarget(upstream2, suffix + operation) !== expected) return void 0;
61
- return trimTrailingSlashes(gateway) + `/compat/${provider}${suffix}`;
59
+ const suffixes = family === "openai" ? ["/v1", ""] : [""];
60
+ for (const suffix of suffixes) {
61
+ if (compatTarget(upstream2, suffix + operation) === expected) {
62
+ return trimTrailingSlashes(gateway) + `/compat/${provider}${suffix}`;
63
+ }
64
+ }
65
+ return void 0;
62
66
  }
63
67
  const upstream = endpoint(published?.provider_upstreams?.[family]);
64
68
  if (!upstream) return void 0;
@@ -72,7 +76,7 @@ function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, publishe
72
76
  }
73
77
  var COPIED_HEADERS = ["content-type", "content-encoding", "accept", "accept-encoding", "idempotency-key", "openai-organization", "openai-project", "session_id", "x-session-id", "x-client-request-id", "x-session-affinity", "anthropic-version", "anthropic-beta", "api-version", "user-agent"];
74
78
  var COMPAT_HEADERS = {
75
- openrouter: ["http-referer", "x-openrouter-title", "x-openrouter-categories"],
79
+ openrouter: ["http-referer", "x-title", "x-openrouter-title", "x-openrouter-categories"],
76
80
  nvidia: ["x-billing-invoke-origin"],
77
81
  opencode: ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"],
78
82
  "opencode-go": ["x-opencode-session", "x-opencode-client", "x-opencode-project", "x-opencode-request"]
@@ -545,6 +549,10 @@ var ProviderRouter = class {
545
549
  if (!model) return;
546
550
  const gateGeneration = this.gateGeneration;
547
551
  const key = `${model.provider}/${model.id}`;
552
+ if (model.api === "pi-virtual") {
553
+ await this.restoreCurrentModel(ctx);
554
+ return;
555
+ }
548
556
  const original = this.isOwnedRoute(model) ? this.routed.originalBaseUrl : model.baseUrl;
549
557
  const route = routeForApi(this.gateway, model.api, model.provider, original, this.compatUpstreams, this.providerUpstreams);
550
558
  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;
@@ -822,7 +830,7 @@ var RecoveryClient = class {
822
830
  await this.call("initialize", {
823
831
  protocolVersion: "2024-11-05",
824
832
  capabilities: {},
825
- clientInfo: { name: "caveman-pi-extension", version: "0.3.1" }
833
+ clientInfo: { name: "caveman-pi-extension", version: "0.4.0" }
826
834
  }, void 0, INIT_TIMEOUT_MS);
827
835
  this.notify("notifications/initialized");
828
836
  if (this.disposed) {
@@ -938,9 +946,221 @@ var RecoveryClient = class {
938
946
  }
939
947
  }
940
948
  };
949
+ var CodemodeClient = class {
950
+ binary;
951
+ extraArgs;
952
+ child;
953
+ initialized = false;
954
+ ensuring;
955
+ nextId = 1;
956
+ pending = /* @__PURE__ */ new Map();
957
+ buffer = "";
958
+ disposed = false;
959
+ constructor(binary = resolveMcpBinary(), extraArgs = defaultCodemodeArgs()) {
960
+ this.binary = binary;
961
+ this.extraArgs = extraArgs;
962
+ }
963
+ async ensure() {
964
+ if (this.disposed || !this.binary) return false;
965
+ if (this.child && this.initialized) return true;
966
+ this.ensuring ??= this.start().finally(() => {
967
+ this.ensuring = void 0;
968
+ });
969
+ return this.ensuring;
970
+ }
971
+ async callTool(name, args, signal) {
972
+ if (!await this.ensure()) {
973
+ return { text: JSON.stringify({ error: "cave_codemode_unavailable", message: "caveman-mcp codemode is not available this session" }), isError: true };
974
+ }
975
+ try {
976
+ const timeoutMs = codemodeCallTimeoutMs(name, args);
977
+ const result = await this.call("tools/call", { name, arguments: args }, signal, timeoutMs);
978
+ const text = (result.content ?? []).map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").join("");
979
+ return { text, isError: Boolean(result.isError) };
980
+ } catch (error) {
981
+ return { text: JSON.stringify({ error: "cave_codemode_transport", message: error.message }), isError: true };
982
+ }
983
+ }
984
+ dispose() {
985
+ this.disposed = true;
986
+ const child = this.child;
987
+ this.child = void 0;
988
+ this.initialized = false;
989
+ for (const [, entry] of this.pending) {
990
+ clearTimeout(entry.timer);
991
+ entry.reject(new Error("codemode client disposed"));
992
+ }
993
+ this.pending.clear();
994
+ if (child) {
995
+ try {
996
+ child.stdin?.end();
997
+ } catch {
998
+ }
999
+ const term = setTimeout(() => {
1000
+ try {
1001
+ child.kill("SIGTERM");
1002
+ } catch {
1003
+ }
1004
+ }, 500);
1005
+ const kill = setTimeout(() => {
1006
+ try {
1007
+ child.kill("SIGKILL");
1008
+ } catch {
1009
+ }
1010
+ }, 2e3);
1011
+ child.once("exit", () => {
1012
+ clearTimeout(term);
1013
+ clearTimeout(kill);
1014
+ });
1015
+ }
1016
+ }
1017
+ async start() {
1018
+ let child;
1019
+ try {
1020
+ const prefixArgs = codemodePrefixArgs();
1021
+ const portable = portableInvocation(this.binary, [...prefixArgs, "codemode", ...this.extraArgs]);
1022
+ child = spawn(portable.command, portable.args, { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
1023
+ } catch {
1024
+ return false;
1025
+ }
1026
+ this.child = child;
1027
+ this.initialized = false;
1028
+ this.buffer = "";
1029
+ child.on("error", () => this.onChildGone(child));
1030
+ child.on("exit", () => this.onChildGone(child));
1031
+ child.stdin?.on("error", () => this.onChildGone(child));
1032
+ child.stdout?.setEncoding("utf8");
1033
+ child.stdout?.on("data", (chunk) => this.onData(chunk));
1034
+ try {
1035
+ await this.call("initialize", {
1036
+ protocolVersion: "2024-11-05",
1037
+ capabilities: {},
1038
+ clientInfo: { name: "caveman-pi-codemode", version: "0.4.0" }
1039
+ }, void 0, CALL_TIMEOUT_MS);
1040
+ try {
1041
+ this.child?.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
1042
+ } catch {
1043
+ }
1044
+ if (this.disposed) {
1045
+ this.onChildGone(child);
1046
+ try {
1047
+ child.kill("SIGTERM");
1048
+ } catch {
1049
+ }
1050
+ return false;
1051
+ }
1052
+ this.initialized = true;
1053
+ return true;
1054
+ } catch {
1055
+ this.onChildGone(child);
1056
+ try {
1057
+ child.kill("SIGTERM");
1058
+ } catch {
1059
+ }
1060
+ return false;
1061
+ }
1062
+ }
1063
+ onChildGone(child) {
1064
+ if (this.child !== child) return;
1065
+ this.child = void 0;
1066
+ this.initialized = false;
1067
+ for (const [, entry] of this.pending) {
1068
+ clearTimeout(entry.timer);
1069
+ entry.reject(new Error("caveman-mcp codemode exited"));
1070
+ }
1071
+ this.pending.clear();
1072
+ }
1073
+ onData(chunk) {
1074
+ this.buffer += chunk;
1075
+ let newline;
1076
+ while ((newline = this.buffer.indexOf("\n")) !== -1) {
1077
+ const line = this.buffer.slice(0, newline).trim();
1078
+ this.buffer = this.buffer.slice(newline + 1);
1079
+ if (!line) continue;
1080
+ let message;
1081
+ try {
1082
+ message = JSON.parse(line);
1083
+ } catch {
1084
+ continue;
1085
+ }
1086
+ if (typeof message.id !== "number") continue;
1087
+ const entry = this.pending.get(message.id);
1088
+ if (!entry) continue;
1089
+ this.pending.delete(message.id);
1090
+ clearTimeout(entry.timer);
1091
+ if (message.error) entry.reject(new Error(message.error.message || "caveman-mcp codemode error"));
1092
+ else entry.resolve(message.result);
1093
+ }
1094
+ }
1095
+ call(method, params, signal, timeoutMs = CALL_TIMEOUT_MS) {
1096
+ const child = this.child;
1097
+ if (!child?.stdin?.writable) return Promise.reject(new Error("caveman-mcp codemode not running"));
1098
+ if (signal?.aborted) return Promise.reject(new Error("codemode call cancelled"));
1099
+ const id = this.nextId++;
1100
+ return new Promise((resolve2, reject) => {
1101
+ const timer = setTimeout(() => {
1102
+ this.pending.delete(id);
1103
+ reject(new Error(`caveman-mcp codemode ${method} timed out`));
1104
+ }, timeoutMs);
1105
+ timer.unref?.();
1106
+ const onAbort = () => {
1107
+ this.pending.delete(id);
1108
+ clearTimeout(timer);
1109
+ reject(new Error("codemode call cancelled"));
1110
+ };
1111
+ signal?.addEventListener("abort", onAbort, { once: true });
1112
+ this.pending.set(id, {
1113
+ resolve: (value) => {
1114
+ signal?.removeEventListener("abort", onAbort);
1115
+ resolve2(value);
1116
+ },
1117
+ reject: (error) => {
1118
+ signal?.removeEventListener("abort", onAbort);
1119
+ reject(error);
1120
+ },
1121
+ timer
1122
+ });
1123
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n", (error) => {
1124
+ if (error) {
1125
+ this.pending.delete(id);
1126
+ clearTimeout(timer);
1127
+ signal?.removeEventListener("abort", onAbort);
1128
+ reject(error);
1129
+ }
1130
+ });
1131
+ });
1132
+ }
1133
+ };
1134
+ function codemodeCallTimeoutMs(name, args) {
1135
+ const isExec = name === "codemode_execute" || name === "codemode_mutate";
1136
+ const raw = typeof args.timeout_ms === "number" && Number.isFinite(args.timeout_ms) && args.timeout_ms > 0 ? Math.min(args.timeout_ms, 3e5) : 0;
1137
+ const minExecMs = isExec ? 75e3 : CALL_TIMEOUT_MS;
1138
+ return Math.max(CALL_TIMEOUT_MS, minExecMs, raw > 0 ? raw + 15e3 : 0);
1139
+ }
1140
+ function codemodePrefixArgs(env = process.env) {
1141
+ const raw = env.CAVEMAN_MCP_PREFIX_ARGS?.trim();
1142
+ if (!raw) return [];
1143
+ try {
1144
+ const parsed = JSON.parse(raw);
1145
+ if (Array.isArray(parsed)) {
1146
+ return parsed.filter((item) => typeof item === "string");
1147
+ }
1148
+ } catch {
1149
+ }
1150
+ return [];
1151
+ }
1152
+ function defaultCodemodeArgs(env = process.env) {
1153
+ const args = [];
1154
+ const cfg = env.CAVEMAN_PI_CODEMODE_CONFIG?.trim();
1155
+ if (cfg) args.push("--config", cfg);
1156
+ else args.push("--discover");
1157
+ const ws = env.CAVEMAN_PI_CODEMODE_WORKSPACE?.trim();
1158
+ if (ws) args.push("--workspace", ws);
1159
+ return args;
1160
+ }
941
1161
 
942
1162
  // ../pi-extension/src/tool-output.ts
943
- async function shrinkToolResult(bridge, sessionId, event, recovery) {
1163
+ async function shrinkToolResult(bridge, sessionId, event, recovery, onNoReply) {
944
1164
  const text = event.content.map((block) => block.type === "text" && typeof block.text === "string" ? block.text : "").join("");
945
1165
  if (!text) return void 0;
946
1166
  if (Buffer.byteLength(text, "utf8") > MAX_TOOL_OUTPUT_BYTES) return void 0;
@@ -952,6 +1172,10 @@ async function shrinkToolResult(bridge, sessionId, event, recovery) {
952
1172
  tool_input: event.input,
953
1173
  tool_output: text
954
1174
  });
1175
+ if (!response) {
1176
+ onNoReply?.();
1177
+ return void 0;
1178
+ }
955
1179
  const proposed = outputReplacementOf(response);
956
1180
  if (!proposed || Buffer.byteLength(proposed, "utf8") > MAX_OUTPUT_REPLACEMENT_BYTES) return void 0;
957
1181
  let handle = normalizeRecoveryHandle(response?.recovery_ref);
@@ -1046,12 +1270,16 @@ async function readLiveRunState(gateway) {
1046
1270
  function index_default(pi) {
1047
1271
  const bridge = new HookBridge();
1048
1272
  const recovery = new RecoveryClient();
1273
+ const codemodeEnabled = process.env.CAVEMAN_PI_CODEMODE === "1";
1274
+ const codemode = codemodeEnabled ? new CodemodeClient() : void 0;
1049
1275
  let router;
1050
1276
  let sessionId = "default";
1051
1277
  let coreContext;
1052
1278
  let pendingContext = [];
1053
1279
  let pendingBytes = 0;
1054
1280
  let gateDone = false;
1281
+ let runtimeReachable = false;
1282
+ let warnedNoReply = false;
1055
1283
  const notify = (ctx, message, kind) => {
1056
1284
  if (ctx?.hasUI) ctx.ui.notify(message, kind);
1057
1285
  else process.stderr.write(`${message}
@@ -1090,7 +1318,7 @@ function index_default(pi) {
1090
1318
  description: "Recover exact original content from a Caveman recovery handle.",
1091
1319
  parameters: Type.Object({
1092
1320
  recovery_handle: Type.String({ description: "Exact ccr_ handle returned by Caveman or copied from a <<ccr:HANDLE>> marker." }),
1093
- query: Type.Optional(Type.String({ description: "One broad description covering every detail needed from this handle." }))
1321
+ query: Type.Optional(Type.String({ description: "Optional. Omit it to get the entire original. With it, only a matching excerpt is returned, with gaps marked. Use one broad description covering every detail needed." }))
1094
1322
  }),
1095
1323
  async execute(_toolCallId, params, signal) {
1096
1324
  const result = await recovery.retrieve(params.recovery_handle, params.query, signal);
@@ -1098,12 +1326,67 @@ function index_default(pi) {
1098
1326
  return { content: [{ type: "text", text: result.text }], details: { recovery_handle: params.recovery_handle } };
1099
1327
  }
1100
1328
  });
1329
+ if (codemode) {
1330
+ pi.registerTool({
1331
+ name: "codemode_search_tools",
1332
+ label: "Search Code-Mode MCP tools",
1333
+ description: "Search connected MCP & built-in repo/pr/browse tools by keyword and return compact typed signatures plus read/write access tags.",
1334
+ parameters: Type.Object({
1335
+ query: Type.String({ description: "Keywords describing the action or resource." }),
1336
+ server: Type.Optional(Type.String({ description: "Optional MCP server filter." })),
1337
+ limit: Type.Optional(Type.Number({ description: "Max tools to return (default 8, max 25)." }))
1338
+ }),
1339
+ async execute(_toolCallId, params, signal) {
1340
+ const result = await codemode.callTool("codemode_search_tools", params, signal);
1341
+ if (result.isError) throw new Error(result.text || "codemode_search_tools failed");
1342
+ return { content: [{ type: "text", text: result.text }], details: { tool: "codemode_search_tools" } };
1343
+ }
1344
+ });
1345
+ pi.registerTool({
1346
+ name: "codemode_execute",
1347
+ label: "Run read-only Code-Mode pipeline",
1348
+ description: "Run a read-only multi-step sandboxed MCP pipeline (`steps`) or embedded QuickJS async JS snippet (`code`) in one turn. Large raw payloads are archived in CCR.",
1349
+ parameters: Type.Object({
1350
+ steps: Type.Optional(Type.Array(Type.Record(Type.String(), Type.Unknown()), { description: "Ordered read-only pipeline steps." })),
1351
+ code: Type.Optional(Type.String({ description: "Embedded QuickJS async JS body using `await mcp.server.tool(args)`." })),
1352
+ return_step: Type.Optional(Type.String({ description: "Step id to return in steps mode." })),
1353
+ max_output_chars: Type.Optional(Type.Number({ description: "Optional max output chars before engine compression." })),
1354
+ timeout_ms: Type.Optional(Type.Number({ description: "Optional timeout ms for code mode." }))
1355
+ }),
1356
+ async execute(_toolCallId, params, signal) {
1357
+ const result = await codemode.callTool("codemode_execute", params, signal);
1358
+ if (result.isError) throw new Error(result.text || "codemode_execute failed");
1359
+ return { content: [{ type: "text", text: result.text }], details: { tool: "codemode_execute" } };
1360
+ }
1361
+ });
1362
+ pi.registerTool({
1363
+ name: "codemode_mutate",
1364
+ label: "Run write-capable Code-Mode call",
1365
+ description: "Execute state-changing MCP tool call(s) via single `tool`+`args`, `steps`, or `code`.",
1366
+ parameters: Type.Object({
1367
+ tool: Type.Optional(Type.String({ description: "Single tool formatted as `server.tool_name`." })),
1368
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Arguments for single-tool mode." })),
1369
+ steps: Type.Optional(Type.Array(Type.Record(Type.String(), Type.Unknown()), { description: "Optional multi-step pipeline with writes permitted." })),
1370
+ code: Type.Optional(Type.String({ description: "Optional embedded QuickJS async JS body with writes permitted." })),
1371
+ return_step: Type.Optional(Type.String({ description: "Step id to return in steps mode." })),
1372
+ max_output_chars: Type.Optional(Type.Number({ description: "Optional max output chars." })),
1373
+ timeout_ms: Type.Optional(Type.Number({ description: "Optional timeout ms for code mode." }))
1374
+ }),
1375
+ async execute(_toolCallId, params, signal) {
1376
+ const result = await codemode.callTool("codemode_mutate", params, signal);
1377
+ if (result.isError) throw new Error(result.text || "codemode_mutate failed");
1378
+ return { content: [{ type: "text", text: result.text }], details: { tool: "codemode_mutate" } };
1379
+ }
1380
+ });
1381
+ }
1101
1382
  pi.on("session_start", GUARD_session_start(async (_event, ctx) => {
1102
1383
  router ??= new ProviderRouter(pi, (message, kind) => notify(ctx, message, kind));
1103
1384
  gateDone = false;
1104
1385
  coreContext = void 0;
1105
1386
  pendingContext = [];
1106
1387
  pendingBytes = 0;
1388
+ runtimeReachable = false;
1389
+ warnedNoReply = false;
1107
1390
  if (!await router.closeGate(ctx)) {
1108
1391
  gateDone = true;
1109
1392
  return;
@@ -1115,6 +1398,7 @@ function index_default(pi) {
1115
1398
  }
1116
1399
  const start = await bridge.call("SessionStart", { session_id: sessionId });
1117
1400
  coreContext = additionalContextOf(start);
1401
+ runtimeReachable = start !== void 0;
1118
1402
  if (!start) {
1119
1403
  gateDone = true;
1120
1404
  notify(ctx, "Caveman: direct mode, no compression this session (caveman native runtime unreachable)", "warning");
@@ -1153,8 +1437,10 @@ function index_default(pi) {
1153
1437
  pendingContext = [];
1154
1438
  pendingBytes = 0;
1155
1439
  if (!coreContext && dynamic.length === 0) return void 0;
1156
- const parts = [event.systemPrompt, coreContext, ...dynamic].filter(Boolean);
1157
- return { systemPrompt: parts.join("\n\n") };
1440
+ const result = {};
1441
+ if (coreContext) result.systemPrompt = [event.systemPrompt, coreContext].filter(Boolean).join("\n\n");
1442
+ if (dynamic.length > 0) result.message = { customType: "caveman-context", content: dynamic.join("\n\n"), display: false };
1443
+ return result;
1158
1444
  }));
1159
1445
  pi.on("turn_start", GUARD_turn_start(() => {
1160
1446
  void bridge.call("ModelBefore", { session_id: sessionId });
@@ -1183,7 +1469,12 @@ function index_default(pi) {
1183
1469
  return false;
1184
1470
  }
1185
1471
  };
1186
- pi.on("tool_result", GUARD_tool_result((event) => event.toolName === RECOVERY_TOOL || !recoveryCallable() ? void 0 : shrinkToolResult(bridge, sessionId, event, recovery)));
1472
+ const isCodeModeTool = (name) => name === "codemode_execute" || name === "codemode_mutate" || name === "codemode_search_tools";
1473
+ pi.on("tool_result", GUARD_tool_result((event, ctx) => event.toolName === RECOVERY_TOOL || isCodeModeTool(event.toolName) || !recoveryCallable() ? void 0 : shrinkToolResult(bridge, sessionId, event, recovery, () => {
1474
+ if (!runtimeReachable || warnedNoReply) return;
1475
+ warnedNoReply = true;
1476
+ notify(ctx, "Caveman: tool-output shrinking may be off this session (the native runtime gave no reply)", "warning");
1477
+ })));
1187
1478
  pi.on("session_before_compact", GUARD_session_before_compact(() => {
1188
1479
  void bridge.call("PreCompact", { session_id: sessionId });
1189
1480
  }));
@@ -1196,6 +1487,7 @@ function index_default(pi) {
1196
1487
  await bridge.call("SessionEnd", { session_id: sessionId });
1197
1488
  await router?.closeGate(ctx);
1198
1489
  recovery.dispose();
1490
+ codemode?.dispose();
1199
1491
  }));
1200
1492
  }
1201
1493
  export {