@bastani/pi-ai 0.9.40-alpha.1 → 0.9.40-alpha.2

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.
@@ -68,20 +68,34 @@ export declare function getDeclaredTools(messages: TranscriptMessages): Tool[];
68
68
  export declare function hasToolRedefinitions(messages: TranscriptMessages): boolean;
69
69
  /** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */
70
70
  export declare function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean;
71
+ /**
72
+ * How a transport can express tool changes after the first request.
73
+ *
74
+ * - `"none"`: only the top-level tool list exists; it always holds the current tools.
75
+ * - `"additions"`: tools can be added at a later message, but not removed or redefined.
76
+ * - `"changes"`: every tool, including the initial ones, is declared in place, and a later
77
+ * declaration under the same name replaces the earlier one. Removals are not expressible on
78
+ * the wire, so the transport announces them as text and the removed tools stay declared.
79
+ */
80
+ export type TranscriptToolSupport = "none" | "additions" | "changes";
71
81
  export interface TranscriptTools {
72
82
  /** Tools sent in the top-level request field. */
73
83
  requestTools: Tool[];
74
84
  /**
75
- * Whether later system messages carry their own `toolsAdded` as in-place additions.
76
- * When false, `requestTools` already holds the complete current tool set.
85
+ * Number of leading system messages whose tool changes `requestTools` already holds. Every
86
+ * later system message carries its own tool changes in place.
77
87
  */
78
- anchorsAdditions: boolean;
88
+ foldedSystemMessages: number;
79
89
  }
80
90
  /**
81
- * Split tool declarations between the top-level request field and in-place additions.
82
- * Transports that can anchor additions at a system message keep the initial tools at the
83
- * top and load later ones where they appear; that only works when no tool was removed or
84
- * redeclared, so everything else sends the current tool list.
91
+ * Split tool declarations between the top-level request field and in-place changes.
92
+ *
93
+ * With `"changes"`, the top-level list stays empty and every system message, including the
94
+ * leading one, declares its tools in place: an in-place declaration can replace an earlier
95
+ * in-place one, but not a top-level one. With `"additions"`, a removal or redefinition cannot be
96
+ * expressed in place, so the top-level list becomes the tool state after the last such change;
97
+ * later additions stay anchored, and the cached prefix is invalidated once per removal instead
98
+ * of on every later addition. With `"none"`, the top-level list is the current tool set.
85
99
  */
86
- export declare function resolveTranscriptTools(messages: TranscriptMessages, supportsToolAdditions: boolean): TranscriptTools;
100
+ export declare function resolveTranscriptTools(messages: TranscriptMessages, support: TranscriptToolSupport): TranscriptTools;
87
101
  //# sourceMappingURL=transcript.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG3G,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD;;;GAGG;AACH,wBAAgB,0BAA0B,CACzC,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,KAAK,EAAE,IAAI,EAAE,GAAG,SAAS,GACvB,aAAa,GAAG,SAAS,CAU3B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,GAAG,iBAAiB,CAIpE;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC;AAM7D,4EAA4E;AAC5E,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,kBAAkB,GAAG,aAAa,GAAG,SAAS,CAG/F;AAED,+FAA+F;AAC/F,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAE1E;AAED,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,kBAAkB,GAAG,IAAI,EAAE,CAQpE;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,kBAAkB,GAAG,aAAa,GAAG,SAAS,CAuB/F;AAED,kFAAkF;AAClF,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,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OlD;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,OAAO,CAElE;AAED,MAAM,WAAW,gBAAgB;IAChC,UAAU,EAAE,IAAI,EAAE,CAAC;IACnB,YAAY,EAAE,aAAa,EAAE,CAAC;CAC9B;AAED,mGAAmG;AACnG,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,GAAG,gBAAgB,CAiBzG;AAED,wFAAwF;AACxF,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,kBAAkB,GAAG,IAAI,EAAE,CAOrE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAW1E;AAED,wHAAwH;AACxH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAE/E;AAmBD;;;;;;;;GAQG;AACH,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,WAAW,GAAG,SAAS,CAAC;AAErE,MAAM,WAAW,eAAe;IAC/B,iDAAiD;IACjD,YAAY,EAAE,IAAI,EAAE,CAAC;IACrB;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;CAC7B;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,qBAAqB,GAAG,eAAe,CAWpH"}
@@ -175,33 +175,44 @@ export function hasToolRedefinitions(messages) {
175
175
  }
176
176
  /** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */
177
177
  export function hasNonAdditiveToolChanges(messages) {
178
+ return findLastNonAdditiveToolChange(messages.filter(isSystemMessage)) >= 0;
179
+ }
180
+ /** Index of the last system message with a removal or same-name redeclaration, or -1. */
181
+ function findLastNonAdditiveToolChange(systemMessages) {
182
+ // A name declared before counts as a redeclaration even after its removal: Kimi K3 ignores a
183
+ // removed tool that a later tool message declares again (verified October 2026).
178
184
  const declared = new Set();
179
- for (const message of messages) {
180
- if (!isSystemMessage(message))
181
- continue;
185
+ let last = -1;
186
+ for (let index = 0; index < systemMessages.length; index++) {
187
+ const message = systemMessages[index];
182
188
  if ((message.toolsRemoved?.length ?? 0) > 0)
183
- return true;
189
+ last = index;
184
190
  for (const tool of message.toolsAdded ?? []) {
185
191
  if (declared.has(tool.name))
186
- return true;
192
+ last = index;
187
193
  declared.add(tool.name);
188
194
  }
189
195
  }
190
- return false;
196
+ return last;
191
197
  }
192
198
  /**
193
- * Split tool declarations between the top-level request field and in-place additions.
194
- * Transports that can anchor additions at a system message keep the initial tools at the
195
- * top and load later ones where they appear; that only works when no tool was removed or
196
- * redeclared, so everything else sends the current tool list.
199
+ * Split tool declarations between the top-level request field and in-place changes.
200
+ *
201
+ * With `"changes"`, the top-level list stays empty and every system message, including the
202
+ * leading one, declares its tools in place: an in-place declaration can replace an earlier
203
+ * in-place one, but not a top-level one. With `"additions"`, a removal or redefinition cannot be
204
+ * expressed in place, so the top-level list becomes the tool state after the last such change;
205
+ * later additions stay anchored, and the cached prefix is invalidated once per removal instead
206
+ * of on every later addition. With `"none"`, the top-level list is the current tool set.
197
207
  */
198
- export function resolveTranscriptTools(messages, supportsToolAdditions) {
199
- const anchorsAdditions = supportsToolAdditions && !hasNonAdditiveToolChanges(messages);
200
- return {
201
- requestTools: anchorsAdditions
202
- ? (getInitialSystemMessage(messages)?.toolsAdded ?? [])
203
- : getCurrentTools(messages),
204
- anchorsAdditions,
205
- };
208
+ export function resolveTranscriptTools(messages, support) {
209
+ const systemMessages = messages.filter(isSystemMessage);
210
+ if (support === "none") {
211
+ return { requestTools: getCurrentTools(systemMessages), foldedSystemMessages: systemMessages.length };
212
+ }
213
+ if (support === "changes")
214
+ return { requestTools: [], foldedSystemMessages: 0 };
215
+ const folded = Math.max(getInitialSystemMessage(messages) ? 1 : 0, findLastNonAdditiveToolChange(systemMessages) + 1);
216
+ return { requestTools: getCurrentTools(systemMessages.slice(0, folded)), foldedSystemMessages: folded };
206
217
  }
207
218
  //# sourceMappingURL=transcript.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAI9D;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CACzC,YAAgC,EAChC,KAAyB;IAEzB,MAAM,eAAe,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9E,MAAM,QAAQ,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IACzD,IAAI,CAAC,eAAe,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IACpD,OAAO;QACN,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE,YAAY,IAAI,EAAE;QAC3B,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1C,SAAS,EAAE,CAAC;KACZ,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAChD,MAAM,cAAc,GAAG,0BAA0B,CAAC,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IACvF,MAAM,QAAQ,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC;IAC3F,OAAO,EAAE,QAAQ,EAAuB,CAAC;AAC1C,CAAC;AAQD,SAAS,eAAe,CAAC,OAAyB;IACjD,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC;AAClC,CAAC;AAED,4EAA4E;AAC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,CAAC;YAC7C,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YACzC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAYD;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,QAA4B,EAAE,qBAA8B;IAClG,MAAM,gBAAgB,GAAG,qBAAqB,IAAI,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC;IACvF,OAAO;QACN,YAAY,EAAE,gBAAgB;YAC7B,CAAC,CAAC,CAAC,uBAAuB,CAAC,QAAQ,CAAC,EAAE,UAAU,IAAI,EAAE,CAAC;YACvD,CAAC,CAAC,eAAe,CAAC,QAAQ,CAAC;QAC5B,gBAAgB;KAChB,CAAC;AACH,CAAC","sourcesContent":["import type { Context, Message, SystemMessage, Tool, ToolReference, TranscriptContext } from \"../types.ts\";\nimport { contentText, getSystemMessageText } from \"./text.ts\";\n\nexport type { TranscriptContext } from \"../types.ts\";\n\n/**\n * Build the leading system message for a prompt and tool set. Returns undefined when\n * both are empty, so an empty transcript stays empty.\n */\nexport function createInitialSystemMessage(\n\tsystemPrompt: string | undefined,\n\ttools: Tool[] | undefined,\n): SystemMessage | undefined {\n\tconst hasSystemPrompt = systemPrompt !== undefined && systemPrompt.length > 0;\n\tconst hasTools = tools !== undefined && tools.length > 0;\n\tif (!hasSystemPrompt && !hasTools) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: systemPrompt ?? \"\",\n\t\t...(hasTools ? { toolsAdded: tools } : {}),\n\t\ttimestamp: 0,\n\t};\n}\n\n/**\n * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.\n * This is the only entry point that produces a {@link TranscriptContext}; every\n * provider-facing function expects the result.\n */\nexport function normalizeContext(context: Context): TranscriptContext {\n\tconst initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);\n\tconst messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;\n\treturn { messages } as TranscriptContext;\n}\n\n/**\n * Any message list. The replay helpers only read entries whose role is `\"system\"`, so\n * agent transcripts that carry custom message roles can be passed without filtering.\n */\nexport type TranscriptMessages = readonly { role: string }[];\n\nfunction isSystemMessage(message: { role: string }): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Return the leading system message, if the transcript starts with one. */\nexport function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst first = messages[0];\n\treturn first && isSystemMessage(first) ? first : undefined;\n}\n\n/** Drop the leading system message for APIs that carry the prompt outside the message list. */\nexport function withoutInitialSystemMessage(messages: Message[]): Message[] {\n\treturn getInitialSystemMessage(messages) ? messages.slice(1) : messages;\n}\n\n/** Resolve the tools available after applying every transcript delta in order. */\nexport function getCurrentTools(messages: TranscriptMessages): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/**\n * Replay every system message into one leading system message holding the current\n * prompt and tools. Later `content` is appended to the base prompt, `sections` are\n * patched by name, and tools are resolved with {@link getCurrentTools}.\n */\nexport function getCurrentSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst content: string[] = [];\n\tconst sections = new Map<string, string>();\n\tlet timestamp: number | undefined;\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\ttimestamp ??= message.timestamp;\n\t\tconst text = contentText(message.content);\n\t\tif (text.length > 0) content.push(text);\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\tconst tools = getCurrentTools(messages);\n\tif (timestamp === undefined && tools.length === 0) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: content.join(\"\\n\\n\"),\n\t\t...(sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}),\n\t\t...(tools.length > 0 ? { toolsAdded: tools } : {}),\n\t\ttimestamp: timestamp ?? 0,\n\t};\n}\n\n/** Render the current system prompt text after replaying every system message. */\nexport function getCurrentSystemPrompt(messages: TranscriptMessages): string {\n\tconst message = getCurrentSystemMessage(messages);\n\treturn message ? getSystemMessageText(message) : \"\";\n}\n\n/**\n * Rebuild the transcript for APIs without mid-conversation system messages: the replayed\n * system message leads, and every later system message is dropped.\n */\nexport function collapseSystemMessages(context: TranscriptContext): TranscriptContext {\n\tconst head = getCurrentSystemMessage(context.messages);\n\tconst messages = context.messages.filter((message) => message.role !== \"system\");\n\treturn { messages: head ? [head, ...messages] : messages } as TranscriptContext;\n}\n\n/** Keep later system messages in place when the model accepts them; otherwise collapse them. */\nexport function resolveTranscript(\n\tcontext: TranscriptContext,\n\tsupportsMidConvoSystemMessages: boolean | undefined,\n): TranscriptContext {\n\treturn supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);\n}\n\n/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model.\n *\n * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the\n * typebox symbol keys and `undefined` fields that a structural comparison would see, and\n * builds both objects with the same key order, so comparing the serialized declarations\n * is exact. This avoids a deep-equal dependency in a browser-safe package.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Every definition referenced by transcript tool state, in first-declaration order. */\nexport function getDeclaredTools(messages: TranscriptMessages): Tool[] {\n\tconst definitions = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);\n\t}\n\treturn [...definitions.values()];\n}\n\n/**\n * Whether a tool name was declared twice with different definitions. A transport that can\n * only reference previously declared tools by name cannot replay such a history.\n *\n * @deprecated No built-in transport needs this anymore: Anthropic expresses redefinitions with\n * inline `tool_definition` blocks. Kept for API compatibility and will be removed in a future release.\n */\nexport function hasToolRedefinitions(messages: TranscriptMessages): boolean {\n\tconst declared = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tconst previous = declared.get(tool.name);\n\t\t\tif (previous !== undefined && !declarationsEqual(previous, tool)) return true;\n\t\t\tdeclared.set(tool.name, tool);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */\nexport function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean {\n\tconst declared = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tif ((message.toolsRemoved?.length ?? 0) > 0) return true;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) return true;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn false;\n}\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/**\n\t * Whether later system messages carry their own `toolsAdded` as in-place additions.\n\t * When false, `requestTools` already holds the complete current tool set.\n\t */\n\tanchorsAdditions: boolean;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place additions.\n * Transports that can anchor additions at a system message keep the initial tools at the\n * top and load later ones where they appear; that only works when no tool was removed or\n * redeclared, so everything else sends the current tool list.\n */\nexport function resolveTranscriptTools(messages: TranscriptMessages, supportsToolAdditions: boolean): TranscriptTools {\n\tconst anchorsAdditions = supportsToolAdditions && !hasNonAdditiveToolChanges(messages);\n\treturn {\n\t\trequestTools: anchorsAdditions\n\t\t\t? (getInitialSystemMessage(messages)?.toolsAdded ?? [])\n\t\t\t: getCurrentTools(messages),\n\t\tanchorsAdditions,\n\t};\n}\n"]}
1
+ {"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAI9D;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CACzC,YAAgC,EAChC,KAAyB;IAEzB,MAAM,eAAe,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9E,MAAM,QAAQ,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IACzD,IAAI,CAAC,eAAe,IAAI,CAAC,QAAQ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,UAAU,sBAAsB,CAAC,QAA4B,EAAE,OAA8B;IAClG,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;IACxD,IAAI,OAAO,KAAK,MAAM,EAAE,CAAC;QACxB,OAAO,EAAE,YAAY,EAAE,eAAe,CAAC,cAAc,CAAC,EAAE,oBAAoB,EAAE,cAAc,CAAC,MAAM,EAAE,CAAC;IACvG,CAAC;IACD,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,EAAE,YAAY,EAAE,EAAE,EAAE,oBAAoB,EAAE,CAAC,EAAE,CAAC;IAChF,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CACtB,uBAAuB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EACzC,6BAA6B,CAAC,cAAc,CAAC,GAAG,CAAC,CACjD,CAAC;IACF,OAAO,EAAE,YAAY,EAAE,eAAe,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,EAAE,oBAAoB,EAAE,MAAM,EAAE,CAAC;AACzG,CAAC","sourcesContent":["import type { Context, Message, SystemMessage, Tool, ToolReference, TranscriptContext } from \"../types.ts\";\nimport { contentText, getSystemMessageText } from \"./text.ts\";\n\nexport type { TranscriptContext } from \"../types.ts\";\n\n/**\n * Build the leading system message for a prompt and tool set. Returns undefined when\n * both are empty, so an empty transcript stays empty.\n */\nexport function createInitialSystemMessage(\n\tsystemPrompt: string | undefined,\n\ttools: Tool[] | undefined,\n): SystemMessage | undefined {\n\tconst hasSystemPrompt = systemPrompt !== undefined && systemPrompt.length > 0;\n\tconst hasTools = tools !== undefined && tools.length > 0;\n\tif (!hasSystemPrompt && !hasTools) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: systemPrompt ?? \"\",\n\t\t...(hasTools ? { toolsAdded: tools } : {}),\n\t\ttimestamp: 0,\n\t};\n}\n\n/**\n * Fold `Context.systemPrompt` and `Context.tools` into a leading system message.\n * This is the only entry point that produces a {@link TranscriptContext}; every\n * provider-facing function expects the result.\n */\nexport function normalizeContext(context: Context): TranscriptContext {\n\tconst initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);\n\tconst messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;\n\treturn { messages } as TranscriptContext;\n}\n\n/**\n * Any message list. The replay helpers only read entries whose role is `\"system\"`, so\n * agent transcripts that carry custom message roles can be passed without filtering.\n */\nexport type TranscriptMessages = readonly { role: string }[];\n\nfunction isSystemMessage(message: { role: string }): message is SystemMessage {\n\treturn message.role === \"system\";\n}\n\n/** Return the leading system message, if the transcript starts with one. */\nexport function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst first = messages[0];\n\treturn first && isSystemMessage(first) ? first : undefined;\n}\n\n/** Drop the leading system message for APIs that carry the prompt outside the message list. */\nexport function withoutInitialSystemMessage(messages: Message[]): Message[] {\n\treturn getInitialSystemMessage(messages) ? messages.slice(1) : messages;\n}\n\n/** Resolve the tools available after applying every transcript delta in order. */\nexport function getCurrentTools(messages: TranscriptMessages): Tool[] {\n\tconst tools = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);\n\t\tfor (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);\n\t}\n\treturn [...tools.values()];\n}\n\n/**\n * Replay every system message into one leading system message holding the current\n * prompt and tools. Later `content` is appended to the base prompt, `sections` are\n * patched by name, and tools are resolved with {@link getCurrentTools}.\n */\nexport function getCurrentSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {\n\tconst content: string[] = [];\n\tconst sections = new Map<string, string>();\n\tlet timestamp: number | undefined;\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\ttimestamp ??= message.timestamp;\n\t\tconst text = contentText(message.content);\n\t\tif (text.length > 0) content.push(text);\n\t\tfor (const [name, value] of Object.entries(message.sections ?? {})) {\n\t\t\tif (value === null) sections.delete(name);\n\t\t\telse sections.set(name, value);\n\t\t}\n\t}\n\tconst tools = getCurrentTools(messages);\n\tif (timestamp === undefined && tools.length === 0) return undefined;\n\treturn {\n\t\trole: \"system\",\n\t\tcontent: content.join(\"\\n\\n\"),\n\t\t...(sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}),\n\t\t...(tools.length > 0 ? { toolsAdded: tools } : {}),\n\t\ttimestamp: timestamp ?? 0,\n\t};\n}\n\n/** Render the current system prompt text after replaying every system message. */\nexport function getCurrentSystemPrompt(messages: TranscriptMessages): string {\n\tconst message = getCurrentSystemMessage(messages);\n\treturn message ? getSystemMessageText(message) : \"\";\n}\n\n/**\n * Rebuild the transcript for APIs without mid-conversation system messages: the replayed\n * system message leads, and every later system message is dropped.\n */\nexport function collapseSystemMessages(context: TranscriptContext): TranscriptContext {\n\tconst head = getCurrentSystemMessage(context.messages);\n\tconst messages = context.messages.filter((message) => message.role !== \"system\");\n\treturn { messages: head ? [head, ...messages] : messages } as TranscriptContext;\n}\n\n/** Keep later system messages in place when the model accepts them; otherwise collapse them. */\nexport function resolveTranscript(\n\tcontext: TranscriptContext,\n\tsupportsMidConvoSystemMessages: boolean | undefined,\n): TranscriptContext {\n\treturn supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);\n}\n\n/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */\nexport function toToolDeclaration(tool: Tool): Tool {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: JSON.parse(JSON.stringify(tool.parameters)) as Tool[\"parameters\"],\n\t\t...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),\n\t};\n}\n\n/**\n * Whether two tools declare the same interface to the model.\n *\n * Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the\n * typebox symbol keys and `undefined` fields that a structural comparison would see, and\n * builds both objects with the same key order, so comparing the serialized declarations\n * is exact. This avoids a deep-equal dependency in a browser-safe package.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\treturn JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));\n}\n\nexport interface ToolStateChanges {\n\ttoolsAdded: Tool[];\n\ttoolsRemoved: ToolReference[];\n}\n\n/** Compare two complete tool states. A changed definition is a removal followed by an addition. */\nexport function getToolStateChanges(previous: readonly Tool[], current: readonly Tool[]): ToolStateChanges {\n\tconst previousTools = new Map(previous.map((tool) => [tool.name, tool]));\n\tconst currentTools = new Map(current.map((tool) => [tool.name, tool]));\n\treturn {\n\t\ttoolsAdded: current\n\t\t\t.filter((tool) => {\n\t\t\t\tconst previousTool = previousTools.get(tool.name);\n\t\t\t\treturn previousTool === undefined || !declarationsEqual(previousTool, tool);\n\t\t\t})\n\t\t\t.map(toToolDeclaration),\n\t\ttoolsRemoved: previous\n\t\t\t.filter((tool) => {\n\t\t\t\tconst currentTool = currentTools.get(tool.name);\n\t\t\t\treturn currentTool === undefined || !declarationsEqual(tool, currentTool);\n\t\t\t})\n\t\t\t.map((tool) => ({ name: tool.name })),\n\t};\n}\n\n/** Every definition referenced by transcript tool state, in first-declaration order. */\nexport function getDeclaredTools(messages: TranscriptMessages): Tool[] {\n\tconst definitions = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) definitions.set(tool.name, tool);\n\t}\n\treturn [...definitions.values()];\n}\n\n/**\n * Whether a tool name was declared twice with different definitions. A transport that can\n * only reference previously declared tools by name cannot replay such a history.\n *\n * @deprecated No built-in transport needs this anymore: Anthropic expresses redefinitions with\n * inline `tool_definition` blocks. Kept for API compatibility and will be removed in a future release.\n */\nexport function hasToolRedefinitions(messages: TranscriptMessages): boolean {\n\tconst declared = new Map<string, Tool>();\n\tfor (const message of messages) {\n\t\tif (!isSystemMessage(message)) continue;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tconst previous = declared.get(tool.name);\n\t\t\tif (previous !== undefined && !declarationsEqual(previous, tool)) return true;\n\t\t\tdeclared.set(tool.name, tool);\n\t\t}\n\t}\n\treturn false;\n}\n\n/** Whether tool history contains a removal or same-name redeclaration that an addition-only transport cannot replay. */\nexport function hasNonAdditiveToolChanges(messages: TranscriptMessages): boolean {\n\treturn findLastNonAdditiveToolChange(messages.filter(isSystemMessage)) >= 0;\n}\n\n/** Index of the last system message with a removal or same-name redeclaration, or -1. */\nfunction findLastNonAdditiveToolChange(systemMessages: readonly SystemMessage[]): number {\n\t// A name declared before counts as a redeclaration even after its removal: Kimi K3 ignores a\n\t// removed tool that a later tool message declares again (verified October 2026).\n\tconst declared = new Set<string>();\n\tlet last = -1;\n\tfor (let index = 0; index < systemMessages.length; index++) {\n\t\tconst message = systemMessages[index];\n\t\tif ((message.toolsRemoved?.length ?? 0) > 0) last = index;\n\t\tfor (const tool of message.toolsAdded ?? []) {\n\t\t\tif (declared.has(tool.name)) last = index;\n\t\t\tdeclared.add(tool.name);\n\t\t}\n\t}\n\treturn last;\n}\n\n/**\n * How a transport can express tool changes after the first request.\n *\n * - `\"none\"`: only the top-level tool list exists; it always holds the current tools.\n * - `\"additions\"`: tools can be added at a later message, but not removed or redefined.\n * - `\"changes\"`: every tool, including the initial ones, is declared in place, and a later\n * declaration under the same name replaces the earlier one. Removals are not expressible on\n * the wire, so the transport announces them as text and the removed tools stay declared.\n */\nexport type TranscriptToolSupport = \"none\" | \"additions\" | \"changes\";\n\nexport interface TranscriptTools {\n\t/** Tools sent in the top-level request field. */\n\trequestTools: Tool[];\n\t/**\n\t * Number of leading system messages whose tool changes `requestTools` already holds. Every\n\t * later system message carries its own tool changes in place.\n\t */\n\tfoldedSystemMessages: number;\n}\n\n/**\n * Split tool declarations between the top-level request field and in-place changes.\n *\n * With `\"changes\"`, the top-level list stays empty and every system message, including the\n * leading one, declares its tools in place: an in-place declaration can replace an earlier\n * in-place one, but not a top-level one. With `\"additions\"`, a removal or redefinition cannot be\n * expressed in place, so the top-level list becomes the tool state after the last such change;\n * later additions stay anchored, and the cached prefix is invalidated once per removal instead\n * of on every later addition. With `\"none\"`, the top-level list is the current tool set.\n */\nexport function resolveTranscriptTools(messages: TranscriptMessages, support: TranscriptToolSupport): TranscriptTools {\n\tconst systemMessages = messages.filter(isSystemMessage);\n\tif (support === \"none\") {\n\t\treturn { requestTools: getCurrentTools(systemMessages), foldedSystemMessages: systemMessages.length };\n\t}\n\tif (support === \"changes\") return { requestTools: [], foldedSystemMessages: 0 };\n\tconst folded = Math.max(\n\t\tgetInitialSystemMessage(messages) ? 1 : 0,\n\t\tfindLastNonAdditiveToolChange(systemMessages) + 1,\n\t);\n\treturn { requestTools: getCurrentTools(systemMessages.slice(0, folded)), foldedSystemMessages: folded };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/pi-ai",
3
- "version": "0.9.40-alpha.1",
3
+ "version": "0.9.40-alpha.2",
4
4
  "description": "Bastani-branded unified LLM API with automatic model discovery and provider configuration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",