@bastani/atomic-ai 0.10.1 → 0.10.2-alpha.1
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/CHANGELOG.md +17 -0
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +108 -40
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.js +2 -2
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +51 -19
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/google-generative-ai.js +2 -2
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.js +2 -2
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/google-vertex.js +2 -2
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/mistral-conversations.d.ts.map +1 -1
- package/dist/api/mistral-conversations.js +13 -7
- package/dist/api/mistral-conversations.js.map +1 -1
- package/dist/api/openai-codex-responses.js +2 -2
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +35 -11
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +2 -2
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.js +2 -2
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/simple-options.d.ts +13 -0
- package/dist/api/simple-options.d.ts.map +1 -1
- package/dist/api/simple-options.js +19 -0
- package/dist/api/simple-options.js.map +1 -1
- package/dist/api/strict-tool-limits.d.ts +9 -0
- package/dist/api/strict-tool-limits.d.ts.map +1 -1
- package/dist/api/strict-tool-limits.js +22 -0
- package/dist/api/strict-tool-limits.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/types.d.ts +23 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/tool-results-bridge.d.ts +7 -0
- package/dist/utils/tool-results-bridge.d.ts.map +1 -0
- package/dist/utils/tool-results-bridge.js +7 -0
- package/dist/utils/tool-results-bridge.js.map +1 -0
- package/dist/utils/transcript.d.ts +35 -3
- package/dist/utils/transcript.d.ts.map +1 -1
- package/dist/utils/transcript.js +136 -5
- package/dist/utils/transcript.js.map +1 -1
- package/dist/utils/version.d.ts +1 -1
- package/dist/utils/version.d.ts.map +1 -1
- package/dist/utils/version.js +1 -1
- package/dist/utils/version.js.map +1 -1
- package/package.json +3 -3
package/dist/utils/transcript.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { contentText, getSystemMessageText } from "./text.js";
|
|
1
|
+
import { contentText, getSystemMessageText, renderSystemMessageUpdate } from "./text.js";
|
|
2
2
|
/**
|
|
3
3
|
* Build the leading system message for a prompt and tool set. Returns undefined when
|
|
4
4
|
* both are empty, so an empty transcript stays empty.
|
|
@@ -102,6 +102,122 @@ export function collapseSystemMessages(context) {
|
|
|
102
102
|
export function resolveTranscript(context, supportsMidConvoSystemMessages) {
|
|
103
103
|
return supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);
|
|
104
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Rebuild the transcript for APIs without mid-conversation system messages without changing the
|
|
107
|
+
* prompt earlier requests sent, so a prompt change after the first reply extends the cached prefix
|
|
108
|
+
* instead of rewriting it.
|
|
109
|
+
*
|
|
110
|
+
* The system messages that open the conversation, from the first one up to the next message, fold
|
|
111
|
+
* into the leading message, exactly as {@link collapseSystemMessages} folds them, and the leading
|
|
112
|
+
* message holds the current tools. The first request sends them all, so nothing is rewritten.
|
|
113
|
+
*
|
|
114
|
+
* Each later system message's {@link renderSystemMessageUpdate} text is sent as text blocks at its
|
|
115
|
+
* place in the transcript, after any tool results that follow it, so that user and assistant turns
|
|
116
|
+
* still alternate: added after the blocks of the user message before it; after tool results, as a
|
|
117
|
+
* user message of its own marked by {@link followsToolResults}, which user input that follows joins;
|
|
118
|
+
* or else put before the blocks of the user message after it, or else, between two assistant messages
|
|
119
|
+
* or after the last one, as a user message of its own. An update never goes inside a tool result.
|
|
120
|
+
* Blocks are only ever added after what an earlier request sent, so its cached prefix stays the same.
|
|
121
|
+
*/
|
|
122
|
+
export function appendSystemMessageUpdates(context) {
|
|
123
|
+
const messages = context.messages;
|
|
124
|
+
const firstSystem = messages.findIndex(isSystemMessage);
|
|
125
|
+
const firstInput = firstSystem === -1 ? -1 : messages.findIndex((message, index) => index > firstSystem && message.role !== "system");
|
|
126
|
+
const cut = firstInput === -1 ? messages.length : firstInput;
|
|
127
|
+
const folded = getCurrentSystemMessage(messages.slice(0, cut));
|
|
128
|
+
const tools = getCurrentTools(messages);
|
|
129
|
+
const result = [];
|
|
130
|
+
if (folded || tools.length > 0) {
|
|
131
|
+
const { toolsAdded: _toolsAdded, ...prompt } = folded ?? { role: "system", content: "", timestamp: 0 };
|
|
132
|
+
result.push({ ...prompt, ...(tools.length > 0 ? { toolsAdded: tools } : {}) });
|
|
133
|
+
}
|
|
134
|
+
let updates;
|
|
135
|
+
/** Replaces the last message with `message`, which keeps its place after tool results. */
|
|
136
|
+
const replaceLast = (message) => {
|
|
137
|
+
if (afterToolResults.has(result[result.length - 1]))
|
|
138
|
+
afterToolResults.add(message);
|
|
139
|
+
result[result.length - 1] = message;
|
|
140
|
+
};
|
|
141
|
+
/** Places the pending updates before `next`, the message about to be added, or at the end; returns `next` to add. */
|
|
142
|
+
const placeUpdates = (next) => {
|
|
143
|
+
if (!updates)
|
|
144
|
+
return next;
|
|
145
|
+
const { texts, timestamp } = updates;
|
|
146
|
+
updates = undefined;
|
|
147
|
+
// Appended blocks only ever follow blocks an earlier request already sent, so the cached block prefix stays
|
|
148
|
+
// intact; a leading block goes into a message no request has sent yet.
|
|
149
|
+
const last = result.at(-1);
|
|
150
|
+
if (last?.role === "user") {
|
|
151
|
+
replaceLast({ ...last, content: [...asBlocks(last.content), ...texts] });
|
|
152
|
+
return next;
|
|
153
|
+
}
|
|
154
|
+
// Never inside a tool result, where the model would read it as tool output.
|
|
155
|
+
if (last?.role === "toolResult") {
|
|
156
|
+
const update = { role: "user", content: texts, timestamp };
|
|
157
|
+
afterToolResults.add(update);
|
|
158
|
+
result.push(update);
|
|
159
|
+
return next;
|
|
160
|
+
}
|
|
161
|
+
if (next?.role === "user")
|
|
162
|
+
return { ...next, content: [...texts, ...asBlocks(next.content)] };
|
|
163
|
+
result.push({ role: "user", content: texts, timestamp });
|
|
164
|
+
return next;
|
|
165
|
+
};
|
|
166
|
+
for (let index = 0; index < messages.length; index++) {
|
|
167
|
+
const message = messages[index];
|
|
168
|
+
if (message.role === "system") {
|
|
169
|
+
if (index < cut)
|
|
170
|
+
continue;
|
|
171
|
+
const text = renderSystemMessageUpdate(message);
|
|
172
|
+
if (text.length === 0)
|
|
173
|
+
continue;
|
|
174
|
+
updates ??= { texts: [], timestamp: message.timestamp };
|
|
175
|
+
updates.texts.push({ type: "text", text });
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
// A tool call's results must directly follow it, so an update waits until after them.
|
|
179
|
+
if (message.role === "toolResult") {
|
|
180
|
+
result.push(message);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const placed = placeUpdates(message);
|
|
184
|
+
const last = result.at(-1);
|
|
185
|
+
// User input after an update that follows tool results joins it, so user messages never sit side by side.
|
|
186
|
+
if (placed.role === "user" && last?.role === "user" && afterToolResults.has(last)) {
|
|
187
|
+
replaceLast({
|
|
188
|
+
...last,
|
|
189
|
+
content: [...asBlocks(last.content), ...asBlocks(placed.content)],
|
|
190
|
+
...(placed.cacheBreakpoint ? { cacheBreakpoint: true } : {}),
|
|
191
|
+
});
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
result.push(placed);
|
|
195
|
+
}
|
|
196
|
+
placeUpdates(undefined);
|
|
197
|
+
return { messages: result };
|
|
198
|
+
}
|
|
199
|
+
/** User messages of prompt updates that {@link appendSystemMessageUpdates} placed directly after tool results. */
|
|
200
|
+
const afterToolResults = new WeakSet();
|
|
201
|
+
/**
|
|
202
|
+
* Whether `message` is a user message of prompt updates, possibly followed by user input, that
|
|
203
|
+
* {@link appendSystemMessageUpdates} placed directly after tool results. Providers whose tool results are user content
|
|
204
|
+
* send its blocks after the tool results in the same user message, so user turns never sit side by side; others send
|
|
205
|
+
* it as the user message after the tool messages, with a fixed assistant message between them where the endpoint
|
|
206
|
+
* rejects a user message directly after a tool message.
|
|
207
|
+
*/
|
|
208
|
+
export function followsToolResults(message) {
|
|
209
|
+
return afterToolResults.has(message);
|
|
210
|
+
}
|
|
211
|
+
function asBlocks(content) {
|
|
212
|
+
return typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Keep later system messages in place when the model accepts them; otherwise append each prompt
|
|
216
|
+
* change after the history earlier requests sent ({@link appendSystemMessageUpdates}).
|
|
217
|
+
*/
|
|
218
|
+
export function resolveRequestTranscript(context, supportsMidConvoSystemMessages) {
|
|
219
|
+
return supportsMidConvoSystemMessages ? context : appendSystemMessageUpdates(context);
|
|
220
|
+
}
|
|
105
221
|
/** Strip executable and display-only fields from a tool before transcript comparison or persistence. */
|
|
106
222
|
export function toToolDeclaration(tool) {
|
|
107
223
|
return {
|
|
@@ -111,16 +227,31 @@ export function toToolDeclaration(tool) {
|
|
|
111
227
|
...(tool.constrainedSampling === undefined ? {} : { constrainedSampling: tool.constrainedSampling }),
|
|
112
228
|
};
|
|
113
229
|
}
|
|
230
|
+
/** `value` serialized with every object's keys in code point order; array order is kept. */
|
|
231
|
+
function canonicalJson(value) {
|
|
232
|
+
if (Array.isArray(value))
|
|
233
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
234
|
+
if (typeof value !== "object" || value === null)
|
|
235
|
+
return JSON.stringify(value);
|
|
236
|
+
const entries = Object.entries(value)
|
|
237
|
+
.filter(([, item]) => item !== undefined)
|
|
238
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
|
|
239
|
+
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
|
|
240
|
+
}
|
|
114
241
|
/**
|
|
115
242
|
* Whether two tools declare the same interface to the model.
|
|
116
243
|
*
|
|
117
244
|
* Both sides go through {@link toToolDeclaration} first: its JSON round-trip drops the
|
|
118
|
-
* schema metadata keys (TypeBox's non-enumerable kind marks) and `undefined` fields that a structural comparison would see
|
|
119
|
-
*
|
|
120
|
-
* is
|
|
245
|
+
* schema metadata keys (TypeBox's non-enumerable kind marks) and `undefined` fields that a structural comparison would see.
|
|
246
|
+
* Object keys are compared in a canonical order, so a schema rebuilt with its keys in another order, as a server may
|
|
247
|
+
* send it after reconnecting, is not a new definition. Array order counts. This avoids a deep-equal dependency in a
|
|
248
|
+
* browser-safe package.
|
|
121
249
|
*/
|
|
122
250
|
export function declarationsEqual(left, right) {
|
|
123
|
-
|
|
251
|
+
const leftDeclaration = toToolDeclaration(left);
|
|
252
|
+
const rightDeclaration = toToolDeclaration(right);
|
|
253
|
+
return (JSON.stringify(leftDeclaration) === JSON.stringify(rightDeclaration) ||
|
|
254
|
+
canonicalJson(leftDeclaration) === canonicalJson(rightDeclaration));
|
|
124
255
|
}
|
|
125
256
|
/** Compare two complete tool states. A changed definition is a removal followed by an addition. */
|
|
126
257
|
export function getToolStateChanges(previous, current) {
|
|
@@ -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,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,OAAO,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;YAC7C,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;gBAAE,IAAI,GAAG,KAAK,CAAC;YAC1C,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;IACF,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC;AAuBD;;;;;;;;;GASG;AACH,MAAM,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 * schema metadata keys (TypeBox's non-enumerable kind marks) 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"]}
|
|
1
|
+
{"version":3,"file":"transcript.js","sourceRoot":"","sources":["../../src/utils/transcript.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,WAAW,CAAC;AAIzF;;;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;QA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,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 {\n\tContext,\n\tMessage,\n\tSystemMessage,\n\tTextContent,\n\tTool,\n\tToolReference,\n\tTranscriptContext,\n\tUserMessage,\n} from \"../types.ts\";\nimport { contentText, getSystemMessageText, renderSystemMessageUpdate } 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/**\n * Rebuild the transcript for APIs without mid-conversation system messages without changing the\n * prompt earlier requests sent, so a prompt change after the first reply extends the cached prefix\n * instead of rewriting it.\n *\n * The system messages that open the conversation, from the first one up to the next message, fold\n * into the leading message, exactly as {@link collapseSystemMessages} folds them, and the leading\n * message holds the current tools. The first request sends them all, so nothing is rewritten.\n *\n * Each later system message's {@link renderSystemMessageUpdate} text is sent as text blocks at its\n * place in the transcript, after any tool results that follow it, so that user and assistant turns\n * still alternate: added after the blocks of the user message before it; after tool results, as a\n * user message of its own marked by {@link followsToolResults}, which user input that follows joins;\n * or else put before the blocks of the user message after it, or else, between two assistant messages\n * or after the last one, as a user message of its own. An update never goes inside a tool result.\n * Blocks are only ever added after what an earlier request sent, so its cached prefix stays the same.\n */\nexport function appendSystemMessageUpdates(context: TranscriptContext): TranscriptContext {\n\tconst messages = context.messages;\n\tconst firstSystem = messages.findIndex(isSystemMessage);\n\tconst firstInput =\n\t\tfirstSystem === -1 ? -1 : messages.findIndex((message, index) => index > firstSystem && message.role !== \"system\");\n\tconst cut = firstInput === -1 ? messages.length : firstInput;\n\tconst folded = getCurrentSystemMessage(messages.slice(0, cut));\n\tconst tools = getCurrentTools(messages);\n\tconst result: Message[] = [];\n\tif (folded || tools.length > 0) {\n\t\tconst { toolsAdded: _toolsAdded, ...prompt } = folded ?? { role: \"system\" as const, content: \"\", timestamp: 0 };\n\t\tresult.push({ ...prompt, ...(tools.length > 0 ? { toolsAdded: tools } : {}) });\n\t}\n\tlet updates: { texts: TextContent[]; timestamp: number } | undefined;\n\t/** Replaces the last message with `message`, which keeps its place after tool results. */\n\tconst replaceLast = (message: UserMessage): void => {\n\t\tif (afterToolResults.has(result[result.length - 1]!)) afterToolResults.add(message);\n\t\tresult[result.length - 1] = message;\n\t};\n\t/** Places the pending updates before `next`, the message about to be added, or at the end; returns `next` to add. */\n\tconst placeUpdates = (next: Message | undefined): Message | undefined => {\n\t\tif (!updates) return next;\n\t\tconst { texts, timestamp } = updates;\n\t\tupdates = undefined;\n\t\t// Appended blocks only ever follow blocks an earlier request already sent, so the cached block prefix stays\n\t\t// intact; a leading block goes into a message no request has sent yet.\n\t\tconst last = result.at(-1);\n\t\tif (last?.role === \"user\") {\n\t\t\treplaceLast({ ...last, content: [...asBlocks(last.content), ...texts] });\n\t\t\treturn next;\n\t\t}\n\t\t// Never inside a tool result, where the model would read it as tool output.\n\t\tif (last?.role === \"toolResult\") {\n\t\t\tconst update: UserMessage = { role: \"user\", content: texts, timestamp };\n\t\t\tafterToolResults.add(update);\n\t\t\tresult.push(update);\n\t\t\treturn next;\n\t\t}\n\t\tif (next?.role === \"user\") return { ...next, content: [...texts, ...asBlocks(next.content)] };\n\t\tresult.push({ role: \"user\", content: texts, timestamp });\n\t\treturn next;\n\t};\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index]!;\n\t\tif (message.role === \"system\") {\n\t\t\tif (index < cut) continue;\n\t\t\tconst text = renderSystemMessageUpdate(message);\n\t\t\tif (text.length === 0) continue;\n\t\t\tupdates ??= { texts: [], timestamp: message.timestamp };\n\t\t\tupdates.texts.push({ type: \"text\", text });\n\t\t\tcontinue;\n\t\t}\n\t\t// A tool call's results must directly follow it, so an update waits until after them.\n\t\tif (message.role === \"toolResult\") {\n\t\t\tresult.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst placed = placeUpdates(message)!;\n\t\tconst last = result.at(-1);\n\t\t// User input after an update that follows tool results joins it, so user messages never sit side by side.\n\t\tif (placed.role === \"user\" && last?.role === \"user\" && afterToolResults.has(last)) {\n\t\t\treplaceLast({\n\t\t\t\t...last,\n\t\t\t\tcontent: [...asBlocks(last.content), ...asBlocks(placed.content)],\n\t\t\t\t...(placed.cacheBreakpoint ? { cacheBreakpoint: true } : {}),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push(placed);\n\t}\n\tplaceUpdates(undefined);\n\treturn { messages: result } as TranscriptContext;\n}\n\n/** User messages of prompt updates that {@link appendSystemMessageUpdates} placed directly after tool results. */\nconst afterToolResults = new WeakSet<Message>();\n\n/**\n * Whether `message` is a user message of prompt updates, possibly followed by user input, that\n * {@link appendSystemMessageUpdates} placed directly after tool results. Providers whose tool results are user content\n * send its blocks after the tool results in the same user message, so user turns never sit side by side; others send\n * it as the user message after the tool messages, with a fixed assistant message between them where the endpoint\n * rejects a user message directly after a tool message.\n */\nexport function followsToolResults(message: Message): boolean {\n\treturn afterToolResults.has(message);\n}\n\nfunction asBlocks(content: UserMessage[\"content\"]): Exclude<UserMessage[\"content\"], string> {\n\treturn typeof content === \"string\" ? [{ type: \"text\", text: content }] : content;\n}\n\n/**\n * Keep later system messages in place when the model accepts them; otherwise append each prompt\n * change after the history earlier requests sent ({@link appendSystemMessageUpdates}).\n */\nexport function resolveRequestTranscript(\n\tcontext: TranscriptContext,\n\tsupportsMidConvoSystemMessages: boolean | undefined,\n): TranscriptContext {\n\treturn supportsMidConvoSystemMessages ? context : appendSystemMessageUpdates(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/** `value` serialized with every object's keys in code point order; array order is kept. */\nfunction canonicalJson(value: unknown): string {\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\tif (typeof value !== \"object\" || value === null) return JSON.stringify(value);\n\tconst entries = Object.entries(value)\n\t\t.filter(([, item]) => item !== undefined)\n\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n\treturn `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(\",\")}}`;\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 * schema metadata keys (TypeBox's non-enumerable kind marks) and `undefined` fields that a structural comparison would see.\n * Object keys are compared in a canonical order, so a schema rebuilt with its keys in another order, as a server may\n * send it after reconnecting, is not a new definition. Array order counts. This avoids a deep-equal dependency in a\n * browser-safe package.\n */\nexport function declarationsEqual(left: Tool, right: Tool): boolean {\n\tconst leftDeclaration = toToolDeclaration(left);\n\tconst rightDeclaration = toToolDeclaration(right);\n\treturn (\n\t\tJSON.stringify(leftDeclaration) === JSON.stringify(rightDeclaration) ||\n\t\tcanonicalJson(leftDeclaration) === canonicalJson(rightDeclaration)\n\t);\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/dist/utils/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const PI_AI_VERSION = "0.10.1";
|
|
1
|
+
export declare const PI_AI_VERSION = "0.10.2-alpha.1";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,aAAa,
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,aAAa,mBAAmB,CAAC"}
|
package/dist/utils/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,MAAM,CAAC,MAAM,aAAa,GAAG,
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC","sourcesContent":["// The @bastani/atomic-ai package version. scripts/bump-version.ts keeps it in sync with package.json.\nexport const PI_AI_VERSION = \"0.10.2-alpha.1\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/atomic-ai",
|
|
3
|
-
"version": "0.10.1",
|
|
3
|
+
"version": "0.10.2-alpha.1",
|
|
4
4
|
"description": "Atomic's unified LLM API: providers, models, auth, streaming, tools, images and classification",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -90,8 +90,8 @@
|
|
|
90
90
|
"dependencies": {
|
|
91
91
|
"@anthropic-ai/sdk": "0.129.0",
|
|
92
92
|
"@aws-sdk/client-bedrock-runtime": "3.1127.0",
|
|
93
|
-
"@bastani/atomic-schema": "0.10.1",
|
|
94
|
-
"@bastani/atomic-telemetry": "0.10.1",
|
|
93
|
+
"@bastani/atomic-schema": "0.10.2-alpha.1",
|
|
94
|
+
"@bastani/atomic-telemetry": "0.10.2-alpha.1",
|
|
95
95
|
"@google/genai": "2.32.0",
|
|
96
96
|
"@smithy/node-http-handler": "4.13.0",
|
|
97
97
|
"http-proxy-agent": "9.1.0",
|