@skydiveai/pi-extensions 0.1.251-beta.1 → 0.1.251-beta.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.
Files changed (2) hide show
  1. package/dist/index.mjs +154 -37
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -27,7 +27,7 @@ import { promisify } from "node:util";
27
27
  import { parse } from "yaml";
28
28
  import { getModels } from "@earendil-works/pi-ai";
29
29
  import { quote } from "shell-quote";
30
- import { createHash } from "node:crypto";
30
+ import { createHash, randomUUID } from "node:crypto";
31
31
  import { createWriteStream } from "node:fs";
32
32
  import { finished } from "node:stream/promises";
33
33
  //#region src/platform-env-middleware.ts
@@ -262,11 +262,26 @@ const CAPABILITY_SOUL_NUDGE = "New capability gained — once the current task i
262
262
  //#region src/extensions/tool-call-summary.ts
263
263
  const log$15 = logger.child({ module: "tool-call-summary-extension" });
264
264
  /**
265
- * The injected parameter name: a namespaced sentinel, so it can never collide
266
- * with a real tool argument and is unmistakable in transcripts and logs. The
267
- * frontend renderer (ANY-2723) duplicates this literal — keep the two in sync.
265
+ * The injected parameter name. Deliberately markdown-safe: the previous wire
266
+ * name (`__skydive_summary__`, now `TOOL_CALL_SUMMARY_FIELD_LEGACY`) carried
267
+ * double underscores, which emphasis-happy models mangle into
268
+ * `_skydive_summary_` / `*skydive_summary*` when they emit tool calls as raw
269
+ * text, breaking the runtime's parse and leaking the raw template into chat
270
+ * (the leak-rejection guard lives in anyone-transparent-proxy, PR #24339).
271
+ * snake_case is markdown-safe: intraword underscores never open an emphasis
272
+ * run in CommonMark, so there is nothing to mangle.
273
+ *
274
+ * Unlike the old namespaced sentinel this is not collision-proof against a
275
+ * real tool argument named `skydive_summary`; the schema-declares checks below
276
+ * still guard that case (we never inject into — or strip from — a tool that
277
+ * declares a summary property of its own).
278
+ *
279
+ * The frontend renderers (ANY-2723) duplicate this literal (web, CLI, and the
280
+ * Slack plan labels) — keep them in sync.
268
281
  */
269
- const TOOL_CALL_SUMMARY_FIELD = "__skydive_summary__";
282
+ const TOOL_CALL_SUMMARY_FIELD = "skydive_summary";
283
+ /** Every name an injected summary may ride under, newest first. */
284
+ const TOOL_CALL_SUMMARY_FIELDS = [TOOL_CALL_SUMMARY_FIELD, "__skydive_summary__"];
270
285
  /** JSON Schema fragment for the injected parameter. */
271
286
  const SUMMARY_PROPERTY = {
272
287
  type: "string",
@@ -292,12 +307,13 @@ const payloadWithToolsSchema = z.object({ tools: z.array(z.unknown()) }).passthr
292
307
  * Add the summary property to one JSON Schema object. Returns the augmented
293
308
  * copy, or `null` when the tool should be left untouched: a strict schema
294
309
  * (`additionalProperties: false`) whose validation would reject the extra
295
- * field, or one that already declares a `__skydive_summary__` property of its own.
310
+ * field, or one that already declares a summary property of its own (either
311
+ * name — such a tool's value is a real argument, not ours).
296
312
  */
297
313
  function augmentSchema(schema) {
298
314
  if (schema.additionalProperties === false) return null;
299
315
  const properties = schema.properties ?? {};
300
- if ("__skydive_summary__" in properties) return null;
316
+ if (TOOL_CALL_SUMMARY_FIELDS.some((field) => field in properties)) return null;
301
317
  const required = schema.required ?? [];
302
318
  return {
303
319
  ...schema,
@@ -306,7 +322,7 @@ function augmentSchema(schema) {
306
322
  [TOOL_CALL_SUMMARY_FIELD]: SUMMARY_PROPERTY,
307
323
  ...properties
308
324
  },
309
- required: required.includes("__skydive_summary__") ? required : [...required, TOOL_CALL_SUMMARY_FIELD]
325
+ required: required.includes("skydive_summary") ? required : [...required, TOOL_CALL_SUMMARY_FIELD]
310
326
  };
311
327
  }
312
328
  /**
@@ -415,13 +431,14 @@ function getStrictToolNames(pi) {
415
431
  return names;
416
432
  }
417
433
  /**
418
- * Whether a tool's own schema declares a `__skydive_summary__` property. We
419
- * never inject into such a tool, so any value it carries is a real argument
420
- * and must be left alone.
434
+ * Whether a tool's own schema declares a summary property (under either
435
+ * name). We never inject into such a tool, so any value it carries is a real
436
+ * argument and must be left alone.
421
437
  */
422
438
  function schemaDeclaresSummary(parameters) {
423
439
  const parsed = jsonSchemaObjectSchema.safeParse(parameters);
424
- return parsed.success && parsed.data.properties != null && "__skydive_summary__" in parsed.data.properties;
440
+ const properties = parsed.success ? parsed.data.properties : void 0;
441
+ return parsed.success && properties != null && TOOL_CALL_SUMMARY_FIELDS.some((field) => field in properties);
425
442
  }
426
443
  function toolDeclaresSummaryParam(pi, toolName) {
427
444
  const tool = pi.getAllTools().find((candidate) => candidate.name === toolName);
@@ -431,8 +448,10 @@ function toolDeclaresSummaryParam(pi, toolName) {
431
448
  /** A copy of `args` without the injected summary. Never mutates its input. */
432
449
  function withoutInjectedSummary(args) {
433
450
  if (args == null || typeof args !== "object" || Array.isArray(args)) return args;
434
- if (!("__skydive_summary__" in args)) return args;
435
- const { [TOOL_CALL_SUMMARY_FIELD]: _summary, ...rest } = args;
451
+ const present = TOOL_CALL_SUMMARY_FIELDS.filter((field) => field in args);
452
+ if (present.length === 0) return args;
453
+ const rest = { ...args };
454
+ for (const field of present) delete rest[field];
436
455
  return rest;
437
456
  }
438
457
  /**
@@ -489,10 +508,11 @@ function withSummaryStrippedBeforeValidation(tool) {
489
508
  };
490
509
  }
491
510
  /**
492
- * Remove the injected summary from a tool's execution input. No-op when the
493
- * field is absent, or when the tool genuinely declares a `__skydive_summary__`
494
- * parameter of its own (which we never inject into, so its value is real).
495
- * Mutates `input` in place, matching the `tool_call` contract.
511
+ * Remove the injected summary from a tool's execution input (under either
512
+ * name — see `TOOL_CALL_SUMMARY_FIELD_LEGACY`). No-op when no summary field
513
+ * is present, or when the tool genuinely declares a summary parameter of its
514
+ * own (which we never inject into, so its value is real). Mutates `input` in
515
+ * place, matching the `tool_call` contract.
496
516
  *
497
517
  * Fails open: this runs on the critical path of tool execution, and the
498
518
  * `getAllTools()` lookup can throw. On any error we leave `input` untouched
@@ -501,9 +521,9 @@ function withSummaryStrippedBeforeValidation(tool) {
501
521
  */
502
522
  function stripInjectedSummary(pi, toolName, input) {
503
523
  try {
504
- if (!("__skydive_summary__" in input)) return;
524
+ if (!TOOL_CALL_SUMMARY_FIELDS.some((field) => field in input)) return;
505
525
  if (toolDeclaresSummaryParam(pi, toolName)) return;
506
- delete input[TOOL_CALL_SUMMARY_FIELD];
526
+ for (const field of TOOL_CALL_SUMMARY_FIELDS) delete input[field];
507
527
  } catch (err) {
508
528
  log$15.error({
509
529
  err,
@@ -4524,31 +4544,128 @@ const toolCallEnvExtension = (pi) => {
4524
4544
  };
4525
4545
  //#endregion
4526
4546
  //#region src/extensions/tool-history.ts
4527
- function historyToolName(name) {
4528
- if (/^[a-zA-Z0-9_-]{1,64}$/.test(name)) return name;
4529
- return `invalid_tool_${createHash("sha256").update(name).digest("hex").slice(0, 32)}`;
4547
+ const VALID_NAME_RE = /^[a-zA-Z0-9_-]+$/;
4548
+ function isValidToolName(name) {
4549
+ return typeof name === "string" && name.length > 0 && name.length <= 64 && VALID_NAME_RE.test(name);
4550
+ }
4551
+ function historyToolName(rawName) {
4552
+ if (isValidToolName(rawName)) return rawName;
4553
+ return `invalid_tool_${createHash("sha1").update(String(rawName)).digest("hex").slice(0, 10)}`;
4530
4554
  }
4531
- /** Repair provider-bound history, never tool execution or persisted messages. */
4555
+ /**
4556
+ * Some models (observed on the OpenRouter path, e.g. GLM emitting the call
4557
+ * inline as text that a salvage parser turns into a degenerate call) produce
4558
+ * tool calls whose `id` and/or `name` arrive empty. The name was already
4559
+ * repaired here; an empty id is worse: the tool result gets persisted with
4560
+ * `toolCallId: ""`, and every later replay of that conversation then fails
4561
+ * the provider-side validation with a 400 ("tool messages must include a
4562
+ * non-empty string tool_call_id"), permanently bricking the conversation.
4563
+ *
4564
+ * Repair the provider-bound context before it is serialized:
4565
+ * 1. Assistant `toolCall` blocks with an empty id get a synthesized id.
4566
+ * 2. A `toolResult` with an empty `toolCallId` adopts the id of the next
4567
+ * unconsumed toolCall on the preceding assistant message; if the call
4568
+ * never persisted on the assistant message, a matching synthetic call is
4569
+ * appended so the pair stays valid; with no assistant anchor at all the
4570
+ * orphaned result is dropped.
4571
+ */
4532
4572
  function repairToolHistory(messages) {
4533
- if (!messages.some((message) => message.role === "assistant" && message.content.some((block) => block.type === "toolCall" && historyToolName(block.name) !== block.name) || message.role === "toolResult" && historyToolName(message.toolName) !== message.toolName)) return messages;
4534
- return messages.map((message) => {
4535
- if (message.role === "assistant") return {
4536
- ...message,
4537
- content: message.content.map((block) => block.type === "toolCall" ? {
4573
+ let needsRepair = false;
4574
+ for (const message of messages) {
4575
+ if (message.role === "assistant") {
4576
+ for (const block of message.content) if (block.type === "toolCall" && (!block.id || !isValidToolName(block.name))) {
4577
+ needsRepair = true;
4578
+ break;
4579
+ }
4580
+ }
4581
+ if (message.role === "toolResult") {
4582
+ if (!message.toolCallId || !isValidToolName(message.toolName)) needsRepair = true;
4583
+ }
4584
+ if (needsRepair) break;
4585
+ }
4586
+ if (!needsRepair) return messages;
4587
+ const out = messages.map((message) => {
4588
+ if (message.role === "assistant") {
4589
+ const repaired = message.content.map((block) => {
4590
+ if (block.type === "toolCall" && !isValidToolName(block.name)) return {
4591
+ ...block,
4592
+ name: historyToolName(block.name)
4593
+ };
4594
+ return block;
4595
+ }).map((block) => block.type === "toolCall" && !block.id ? {
4538
4596
  ...block,
4539
- name: historyToolName(block.name)
4540
- } : block)
4541
- };
4542
- if (message.role === "toolResult") return {
4597
+ id: `call_${randomUUID()}`
4598
+ } : block);
4599
+ return {
4600
+ ...message,
4601
+ content: repaired
4602
+ };
4603
+ }
4604
+ if (message.role === "toolResult" && !isValidToolName(message.toolName)) return {
4543
4605
  ...message,
4544
4606
  toolName: historyToolName(message.toolName)
4545
4607
  };
4546
4608
  return message;
4547
4609
  });
4610
+ let lastAssistant;
4611
+ for (let i = 0; i < out.length; i++) {
4612
+ const message = out[i];
4613
+ if (!message) continue;
4614
+ if (message.role === "assistant") {
4615
+ lastAssistant = {
4616
+ index: i,
4617
+ message,
4618
+ consumed: /* @__PURE__ */ new Set()
4619
+ };
4620
+ continue;
4621
+ }
4622
+ if (message.role !== "toolResult" || message.toolCallId) continue;
4623
+ if (!lastAssistant) {
4624
+ out.splice(i, 1);
4625
+ i--;
4626
+ continue;
4627
+ }
4628
+ const anchor = lastAssistant.message;
4629
+ const callIdx = anchor.content.findIndex((block, idx) => block.type === "toolCall" && !lastAssistant.consumed.has(idx));
4630
+ const pairedCall = callIdx >= 0 ? anchor.content[callIdx] : void 0;
4631
+ const pairedCallId = pairedCall?.type === "toolCall" ? pairedCall.id : void 0;
4632
+ if (pairedCallId) {
4633
+ lastAssistant.consumed.add(callIdx);
4634
+ out[i] = {
4635
+ ...message,
4636
+ toolCallId: pairedCallId
4637
+ };
4638
+ continue;
4639
+ }
4640
+ const id = `call_${randomUUID()}`;
4641
+ const content = [...anchor.content, {
4642
+ type: "toolCall",
4643
+ id,
4644
+ name: message.toolName,
4645
+ arguments: {}
4646
+ }];
4647
+ const repaired = {
4648
+ ...anchor,
4649
+ content
4650
+ };
4651
+ out[lastAssistant.index] = repaired;
4652
+ lastAssistant.message = repaired;
4653
+ lastAssistant.consumed.add(content.length - 1);
4654
+ out[i] = {
4655
+ ...message,
4656
+ toolCallId: id
4657
+ };
4658
+ }
4659
+ return out;
4548
4660
  }
4549
- const toolHistoryExtension = (pi) => {
4550
- pi.on("context", ({ messages }) => ({ messages: repairToolHistory(messages) }));
4551
- };
4661
+ function createToolHistoryExtension() {
4662
+ return (pi) => {
4663
+ pi.on("context", (event) => {
4664
+ return { messages: repairToolHistory(event.messages) };
4665
+ });
4666
+ };
4667
+ }
4668
+ var tool_history_default = createToolHistoryExtension();
4552
4669
  //#endregion
4553
4670
  //#region src/extensions/background-tasks.ts
4554
4671
  /**
@@ -5262,7 +5379,7 @@ function platformExtensions({ sessionId, channelContext }) {
5262
5379
  createProactiveResultExtension({ channelContext }),
5263
5380
  createContextManagementExtension(),
5264
5381
  resourcePressureWarningExtension,
5265
- toolHistoryExtension
5382
+ tool_history_default
5266
5383
  ];
5267
5384
  }
5268
5385
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skydiveai/pi-extensions",
3
- "version": "0.1.251-beta.1",
3
+ "version": "0.1.251-beta.3",
4
4
  "homepage": "https://skydive.com",
5
5
  "license": "MIT",
6
6
  "author": "Create, Inc.",