@skydiveai/pi-extensions 0.1.258-beta.134 → 0.1.258-beta.135

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.
Files changed (2) hide show
  1. package/dist/index.mjs +196 -50
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -25,6 +25,8 @@ import { execFile, spawn } from "node:child_process";
25
25
  import os, { availableParallelism } from "node:os";
26
26
  import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
27
27
  import { adjustMaxTokensForThinking, clampMaxTokensToContext } from "@earendil-works/pi-ai-runtime/api/simple-options";
28
+ import { createServer } from "node:http";
29
+ import { buffer } from "node:stream/consumers";
28
30
  import { quote } from "shell-quote";
29
31
  import { ROOT_CONTEXT, SpanStatusCode, propagation, trace } from "@opentelemetry/api";
30
32
  import { W3CTraceContextPropagator } from "@opentelemetry/core";
@@ -265,7 +267,7 @@ function createHealthHandler({ metadata }) {
265
267
  const CAPABILITY_SOUL_NUDGE = "New capability gained — once the current task is done, if this changes what you can do for the user, record it in `soul.md` so it carries into future conversations rather than being rediscovered from scratch (then commit and push).";
266
268
  //#endregion
267
269
  //#region src/extensions/tool-call-summary.ts
268
- const log$22 = logger.child({ module: "tool-call-summary-extension" });
270
+ const log$23 = logger.child({ module: "tool-call-summary-extension" });
269
271
  /**
270
272
  * The injected parameter name. Deliberately markdown-safe: the previous wire
271
273
  * name (`__skydive_summary__`, now `TOOL_CALL_SUMMARY_FIELD_LEGACY`) carried
@@ -499,7 +501,7 @@ function withSummaryStrippedBeforeValidation(tool) {
499
501
  try {
500
502
  stripped = withoutInjectedSummary(args);
501
503
  } catch (err) {
502
- log$22.error({
504
+ log$23.error({
503
505
  err,
504
506
  event: "tool_call_summary_prepare_strip_failed",
505
507
  toolName: tool.name
@@ -530,7 +532,7 @@ function stripInjectedSummary(pi, toolName, input) {
530
532
  if (toolDeclaresSummaryParam(pi, toolName)) return;
531
533
  for (const field of TOOL_CALL_SUMMARY_FIELDS) delete input[field];
532
534
  } catch (err) {
533
- log$22.error({
535
+ log$23.error({
534
536
  err,
535
537
  event: "tool_call_summary_strip_failed",
536
538
  toolName
@@ -546,7 +548,7 @@ function buildInjectedPayload(pi, payload) {
546
548
  try {
547
549
  return injectToolCallSummary(payload, getStrictToolNames(pi));
548
550
  } catch (err) {
549
- log$22.error({
551
+ log$23.error({
550
552
  err,
551
553
  event: "tool_call_summary_injection_failed"
552
554
  }, "tool_call_summary injection failed; passing payload through unchanged");
@@ -565,7 +567,7 @@ const toolCallSummaryExtension = (pi) => {
565
567
  pi.registerTool(withSummaryStrippedBeforeValidation(createEditToolDefinition(ctx.cwd)));
566
568
  editOverrideRegistered = true;
567
569
  } catch (err) {
568
- log$22.error({
570
+ log$23.error({
569
571
  err,
570
572
  event: "tool_call_summary_edit_override_failed"
571
573
  }, "failed to register summary-tolerant edit tool; built-in remains active");
@@ -596,7 +598,7 @@ const toolCallSummaryExtension = (pi) => {
596
598
  * or `ToolDefinition[]`. Files starting with `_` or `.` are skipped, so
597
599
  * `tools/_example.ts` documents the shape without registering.
598
600
  */
599
- const log$21 = logger.child({ module: "local-tools-extension" });
601
+ const log$22 = logger.child({ module: "local-tools-extension" });
600
602
  const TOOLS_DIRNAME = "tools";
601
603
  const fileState = /* @__PURE__ */ new Map();
602
604
  let pendingLocalToolsUpdate = null;
@@ -740,7 +742,7 @@ async function reconcileAndQueue({ pi, dir, reason }) {
740
742
  dir
741
743
  });
742
744
  if (reason !== "session_start" && summaryHasChanges$1(summary)) pendingLocalToolsUpdate = summary;
743
- log$21.info({
745
+ log$22.info({
744
746
  event: "local_tools_reconcile",
745
747
  reason,
746
748
  total_tools: summary.totalTools,
@@ -762,7 +764,7 @@ const localToolsExtension = (pi) => {
762
764
  reason: "session_start"
763
765
  });
764
766
  } catch (err) {
765
- log$21.error({
767
+ log$22.error({
766
768
  err,
767
769
  event: "local_tools_reconcile_failed"
768
770
  }, "local tools reconcile failed");
@@ -774,7 +776,7 @@ const localToolsExtension = (pi) => {
774
776
  try {
775
777
  current = await listToolFiles(dir);
776
778
  } catch (err) {
777
- log$21.warn({
779
+ log$22.warn({
778
780
  err,
779
781
  event: "local_tools_listing_failed"
780
782
  }, "tools/ listing failed");
@@ -796,7 +798,7 @@ const localToolsExtension = (pi) => {
796
798
  reason: "auto_reload"
797
799
  });
798
800
  } catch (err) {
799
- log$21.error({
801
+ log$22.error({
800
802
  err,
801
803
  event: "local_tools_auto_reload_failed"
802
804
  }, "auto-reload after tools/ change failed");
@@ -1500,7 +1502,7 @@ function toProviderSafeSchema(inputSchema) {
1500
1502
  * Clients are keyed by JSON-stringified config and reused across
1501
1503
  * reloads — only changed configs reconnect.
1502
1504
  */
1503
- const log$20 = logger.child({ module: "mcp-extension" });
1505
+ const log$21 = logger.child({ module: "mcp-extension" });
1504
1506
  function resolveToolSelection(server) {
1505
1507
  return {
1506
1508
  allow: server?.tools?.length ? new Set(server.tools) : null,
@@ -1698,7 +1700,7 @@ function providerSafeTools({ serverId, tools }) {
1698
1700
  for (const tool of tools) {
1699
1701
  const result = toProviderSafeSchema(tool.inputSchema);
1700
1702
  if (!result.ok) {
1701
- log$20.warn({
1703
+ log$21.warn({
1702
1704
  event: "mcp_tool_schema_unsupported",
1703
1705
  server_id: serverId,
1704
1706
  tool_name: tool.name,
@@ -2172,7 +2174,7 @@ var McpExtension = class {
2172
2174
  });
2173
2175
  this.lastConfigMtimeMs = await readConfigMtimeMs(configPath);
2174
2176
  if (reason !== "session_start" && summaryHasChanges(summary)) this.pendingMcpUpdate = summary;
2175
- log$20.info({
2177
+ log$21.info({
2176
2178
  event: "mcp_reconcile",
2177
2179
  reason,
2178
2180
  total_tools: summary.totalTools,
@@ -2199,7 +2201,7 @@ var McpExtension = class {
2199
2201
  contextWindow: ctx.model?.contextWindow
2200
2202
  });
2201
2203
  } catch (err) {
2202
- log$20.error({
2204
+ log$21.error({
2203
2205
  err,
2204
2206
  event: "mcp_reconcile_failed"
2205
2207
  }, "MCP reconcile failed");
@@ -2213,7 +2215,7 @@ var McpExtension = class {
2213
2215
  for (const legacy of renamed) {
2214
2216
  if (this.loggedLegacyToolNames.has(legacy)) continue;
2215
2217
  this.loggedLegacyToolNames.add(legacy);
2216
- log$20.info({
2218
+ log$21.info({
2217
2219
  event: "mcp_tool_legacy_name",
2218
2220
  legacy_name: legacy,
2219
2221
  tool_name: this.legacyToolNames.get(legacy)
@@ -2227,7 +2229,7 @@ var McpExtension = class {
2227
2229
  try {
2228
2230
  mtime = await readConfigMtimeMs(configPath);
2229
2231
  } catch (err) {
2230
- log$20.warn({
2232
+ log$21.warn({
2231
2233
  err,
2232
2234
  event: "mcp_mtime_check_failed"
2233
2235
  }, "mtime check on mcp.config.json failed");
@@ -2242,7 +2244,7 @@ var McpExtension = class {
2242
2244
  contextWindow: ctx.model?.contextWindow
2243
2245
  });
2244
2246
  } catch (err) {
2245
- log$20.error({
2247
+ log$21.error({
2246
2248
  err,
2247
2249
  event: "mcp_auto_reload_failed"
2248
2250
  }, "auto-reload after mcp.config.json change failed");
@@ -2608,12 +2610,6 @@ const assistantSchema = z.object({
2608
2610
  id: z.string(),
2609
2611
  model: z.string()
2610
2612
  });
2611
- /** Sent as the SDK prompt when Pi's context ends with tool results. */
2612
- const SEAT_CONTINUE_PROMPT = "Continue from the existing conversation and tool results.";
2613
- const continuePromptSchema = z.object({ content: z.union([z.literal(SEAT_CONTINUE_PROMPT), z.tuple([z.object({
2614
- type: z.literal("text"),
2615
- text: z.literal(SEAT_CONTINUE_PROMPT)
2616
- })])]) });
2617
2613
  const sdkToolResultSchema = z.object({ content: z.array(z.object({ type: z.literal("tool_result") })).min(1) });
2618
2614
  function assistantMessage(entry) {
2619
2615
  if (entry.type !== "assistant") return null;
@@ -2629,30 +2625,6 @@ function assistantMessage(entry) {
2629
2625
  function isSdkToolResult(entry) {
2630
2626
  return entry.type === "user" && sdkToolResultSchema.safeParse(entry.message).success;
2631
2627
  }
2632
- /**
2633
- * On resume, the pinned CLI inserts a `<synthetic>` "No response requested."
2634
- * assistant turn after a trailing tool_result, before the continuation prompt.
2635
- * Each tool step therefore stores one placeholder pair. Inside the current turn
2636
- * the pair must stay so the cached prefix is byte-identical between steps, but
2637
- * once a newer user message exists it is dropped: otherwise the model rereads
2638
- * itself saying "No response requested." once per historical tool step.
2639
- * Only our own continuation prompt goes with it; when a steer was the prompt,
2640
- * the user's text follows the synthetic turn and must be kept.
2641
- */
2642
- function withoutResumePlaceholders(entries) {
2643
- let dropPrompt = false;
2644
- return entries.filter((entry) => {
2645
- if (assistantMessage(entry)?.model === "<synthetic>") {
2646
- dropPrompt = true;
2647
- return false;
2648
- }
2649
- if (dropPrompt && entry.type === "user") {
2650
- dropPrompt = false;
2651
- return !continuePromptSchema.safeParse(entry.message).success;
2652
- }
2653
- return true;
2654
- });
2655
- }
2656
2628
  function contentHash(message) {
2657
2629
  return createHash("sha256").update(JSON.stringify(message.content)).digest("hex");
2658
2630
  }
@@ -2719,6 +2691,8 @@ async function captureSeatTranscript({ configDir, sessionId, boundaryId, lastAss
2719
2691
  }
2720
2692
  //#endregion
2721
2693
  //#region src/extensions/claude-seat-history.ts
2694
+ /** Sent as the SDK prompt when Pi's context ends with tool results. */
2695
+ const SEAT_CONTINUE_PROMPT = "Continue from the existing conversation and tool results.";
2722
2696
  const imageType = z.enum([
2723
2697
  "image/jpeg",
2724
2698
  "image/png",
@@ -2810,7 +2784,6 @@ async function prepareSeatHistory({ context, configDir, cwd, toolName, model })
2810
2784
  resume: null,
2811
2785
  boundaryId: null
2812
2786
  };
2813
- const lastUserIndex = context.messages.findLastIndex((message) => message.role === "user");
2814
2787
  const sessionId = randomUUID();
2815
2788
  let parentUuid = null;
2816
2789
  const entries = messages.flatMap((message, index) => {
@@ -2820,7 +2793,7 @@ async function prepareSeatHistory({ context, configDir, cwd, toolName, model })
2820
2793
  const nextHash = hashes[index + 1];
2821
2794
  if (message.role === "user" && next?.role === "assistant" && nextHash && seatTranscript(next, nextHash)?.replacesUser) return [];
2822
2795
  const preserved = message.role === "assistant" ? seatTranscript(message, prefixHash) : null;
2823
- if (preserved) return (index < lastUserIndex ? withoutResumePlaceholders(preserved.entries) : preserved.entries).map((entry) => {
2796
+ if (preserved) return preserved.entries.map((entry) => {
2824
2797
  const uuid = randomUUID();
2825
2798
  const replay = {
2826
2799
  ...entry,
@@ -2918,6 +2891,176 @@ function seatReasoningOptions({ model, context, options }) {
2918
2891
  };
2919
2892
  }
2920
2893
  //#endregion
2894
+ //#region src/extensions/claude-seat-request-proxy.ts
2895
+ const log$20 = logger.child({ module: "claude-seat-request-proxy" });
2896
+ const RESUME_PLACEHOLDER = "No response requested.";
2897
+ const blockSchema = z.record(z.string(), z.json());
2898
+ const messageSchema = z.object({
2899
+ role: z.string(),
2900
+ content: z.union([z.string(), z.array(blockSchema)])
2901
+ }).catchall(z.json());
2902
+ const requestSchema = z.object({ messages: z.array(messageSchema) }).catchall(z.json());
2903
+ function blocks(message) {
2904
+ return typeof message.content === "string" ? [{
2905
+ type: "text",
2906
+ text: message.content
2907
+ }] : message.content;
2908
+ }
2909
+ /** The text of a message made of exactly one text block, else null. */
2910
+ function soleText(message) {
2911
+ if (!message) return null;
2912
+ const [only, ...rest] = blocks(message);
2913
+ return only?.type === "text" && rest.length === 0 ? only.text : null;
2914
+ }
2915
+ function hasToolResult(message) {
2916
+ return message?.role === "user" && blocks(message).some((block) => block.type === "tool_result");
2917
+ }
2918
+ function isPlaceholder(message) {
2919
+ return message.role === "assistant" && soleText(message) === RESUME_PLACEHOLDER;
2920
+ }
2921
+ function isContinuePrompt(message) {
2922
+ return message?.role === "user" && soleText(message) === "Continue from the existing conversation and tool results.";
2923
+ }
2924
+ /**
2925
+ * On resume, the pinned Claude Code CLI inserts a synthetic "No response
2926
+ * requested." assistant turn before any prompt that follows a tool_result.
2927
+ * Removing it (and our own continuation prompt) from every request keeps the
2928
+ * model from rereading itself saying it once per tool step. Applying the same
2929
+ * rewrite to every request keeps prefixes byte-identical across steps, so the
2930
+ * prompt cache and thinking signatures see one stable history.
2931
+ */
2932
+ function stripResumePlaceholders(messages) {
2933
+ const kept = [];
2934
+ let cacheControl = null;
2935
+ for (let index = 0; index < messages.length; index++) {
2936
+ const message = messages[index];
2937
+ if (!message) continue;
2938
+ const next = messages[index + 1];
2939
+ if (isPlaceholder(message) && hasToolResult(messages[index - 1]) && next?.role === "user") {
2940
+ const dropped = isContinuePrompt(next) ? [message, next] : [message];
2941
+ for (const block of dropped.flatMap(blocks)) if (block.cache_control !== void 0) cacheControl = block.cache_control;
2942
+ if (dropped.length === 2) index++;
2943
+ continue;
2944
+ }
2945
+ kept.push(message);
2946
+ }
2947
+ const merged = [];
2948
+ for (const message of kept) {
2949
+ const previous = merged.at(-1);
2950
+ if (previous?.role === message.role && (message.role === "user" || message.role === "assistant")) merged[merged.length - 1] = {
2951
+ ...previous,
2952
+ content: [...blocks(previous), ...blocks(message)]
2953
+ };
2954
+ else merged.push(message);
2955
+ }
2956
+ const last = merged.at(-1);
2957
+ if (cacheControl !== null && last) {
2958
+ const content = blocks(last).map((block) => {
2959
+ const { cache_control: _, ...rest } = block;
2960
+ return rest;
2961
+ });
2962
+ const tail = content.at(-1);
2963
+ if (tail) content[content.length - 1] = {
2964
+ ...tail,
2965
+ cache_control: cacheControl
2966
+ };
2967
+ merged[merged.length - 1] = {
2968
+ ...last,
2969
+ content
2970
+ };
2971
+ }
2972
+ return {
2973
+ messages: merged,
2974
+ removed: messages.length - kept.length
2975
+ };
2976
+ }
2977
+ const jsonSchema = z.string().transform((text, ctx) => {
2978
+ try {
2979
+ return JSON.parse(text);
2980
+ } catch {
2981
+ ctx.addIssue({
2982
+ code: "custom",
2983
+ message: "Request body is not JSON"
2984
+ });
2985
+ return z.NEVER;
2986
+ }
2987
+ });
2988
+ function rewriteBody(body) {
2989
+ const parsed = jsonSchema.pipe(requestSchema).safeParse(body.toString());
2990
+ if (!parsed.success) {
2991
+ log$20.warn({ err: parsed.error }, "Claude seat request did not match the expected shape; forwarding as is");
2992
+ return body;
2993
+ }
2994
+ const { messages, removed } = stripResumePlaceholders(parsed.data.messages);
2995
+ if (removed === 0) return body;
2996
+ return Buffer.from(JSON.stringify({
2997
+ ...parsed.data,
2998
+ messages
2999
+ }));
3000
+ }
3001
+ const HOP_BY_HOP = new Set([
3002
+ "host",
3003
+ "connection",
3004
+ "content-length",
3005
+ "transfer-encoding",
3006
+ "keep-alive"
3007
+ ]);
3008
+ /**
3009
+ * Local hop between the Claude Code CLI and the seat's upstream base URL. It
3010
+ * forwards everything unchanged except Messages API bodies, which lose the
3011
+ * CLI's resume placeholders (see `stripResumePlaceholders`).
3012
+ */
3013
+ async function startSeatRequestProxy({ target }) {
3014
+ const base = target.replace(/\/+$/, "");
3015
+ const server = createServer(async (request, response) => {
3016
+ const upstreamAbort = new AbortController();
3017
+ response.once("close", () => upstreamAbort.abort());
3018
+ try {
3019
+ const raw = await buffer(request);
3020
+ const body = request.method === "POST" && request.url?.startsWith("/v1/messages") ? rewriteBody(raw) : raw;
3021
+ const headers = new Headers();
3022
+ for (const [name, value] of Object.entries(request.headers)) {
3023
+ if (value === void 0 || HOP_BY_HOP.has(name)) continue;
3024
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
3025
+ }
3026
+ const upstream = await fetch(`${base}${request.url ?? ""}`, {
3027
+ method: request.method,
3028
+ headers,
3029
+ body: ["GET", "HEAD"].includes(request.method ?? "") ? null : new Uint8Array(body),
3030
+ signal: upstreamAbort.signal
3031
+ });
3032
+ const responseHeaders = {};
3033
+ upstream.headers.forEach((value, name) => {
3034
+ if (!HOP_BY_HOP.has(name) && name !== "content-encoding") responseHeaders[name] = value;
3035
+ });
3036
+ response.writeHead(upstream.status, responseHeaders);
3037
+ if (!upstream.body) {
3038
+ response.end();
3039
+ return;
3040
+ }
3041
+ const reader = upstream.body.getReader();
3042
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) if (!response.write(chunk.value)) await once(response, "drain", { signal: upstreamAbort.signal });
3043
+ response.end();
3044
+ } catch (err) {
3045
+ if (upstreamAbort.signal.aborted) return;
3046
+ log$20.error({ err }, "Claude seat request proxy failed to forward");
3047
+ if (!response.headersSent) response.writeHead(502);
3048
+ response.end();
3049
+ }
3050
+ });
3051
+ server.listen(0, "127.0.0.1");
3052
+ await once(server, "listening");
3053
+ const address = server.address();
3054
+ if (!address || typeof address === "string") throw new Error("Claude seat request proxy has no TCP address");
3055
+ return {
3056
+ url: `http://127.0.0.1:${address.port}`,
3057
+ close: () => {
3058
+ server.closeAllConnections();
3059
+ server.close();
3060
+ }
3061
+ };
3062
+ }
3063
+ //#endregion
2921
3064
  //#region src/extensions/claude-seat-payload.ts
2922
3065
  const payloadSchema = z.strictObject({
2923
3066
  model: z.string(),
@@ -3088,10 +3231,12 @@ var SeatQuery = class {
3088
3231
  async run({ sessionId, cwd }) {
3089
3232
  const { model, context, options } = this.request;
3090
3233
  let configDir = null;
3234
+ let requestProxy = null;
3091
3235
  try {
3092
3236
  if (!options.apiKey) throw new Error("Claude seat SDK requires a seat credential sentinel");
3093
3237
  this.controller.signal.throwIfAborted();
3094
3238
  configDir = await mkdtemp(path.join(os.tmpdir(), "claude-seat-sdk-"));
3239
+ requestProxy = await startSeatRequestProxy({ target: model.baseUrl });
3095
3240
  this.controller.signal.throwIfAborted();
3096
3241
  const bindings = toolBindings(context);
3097
3242
  const servers = /* @__PURE__ */ new Map();
@@ -3186,7 +3331,7 @@ var SeatQuery = class {
3186
3331
  env: buildStdioEnv({
3187
3332
  ANTHROPIC_AUTH_TOKEN: options.apiKey,
3188
3333
  ANTHROPIC_API_KEY: "",
3189
- ANTHROPIC_BASE_URL: model.baseUrl,
3334
+ ANTHROPIC_BASE_URL: requestProxy.url,
3190
3335
  ANTHROPIC_CUSTOM_HEADERS: platformHeaders({
3191
3336
  model,
3192
3337
  options,
@@ -3237,6 +3382,7 @@ var SeatQuery = class {
3237
3382
  if (this.deadline) clearTimeout(this.deadline);
3238
3383
  this.deadline = null;
3239
3384
  this.wake?.();
3385
+ requestProxy?.close();
3240
3386
  if (configDir) try {
3241
3387
  await rm(configDir, {
3242
3388
  recursive: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skydiveai/pi-extensions",
3
- "version": "0.1.258-beta.134",
3
+ "version": "0.1.258-beta.135",
4
4
  "homepage": "https://skydive.com",
5
5
  "license": "MIT",
6
6
  "author": "Create, Inc.",