@codeworksh/aikit 0.12.1-dev.20261024131604 → 0.13.0-dev.20261102120654

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 (50) hide show
  1. package/cli.mjs +5 -5
  2. package/{codex-CLDBTrFm.mjs → codex-DvULd3EJ.mjs} +2 -56
  3. package/codex-DvULd3EJ.mjs.map +1 -0
  4. package/{copilot-DvUXC6Kx.mjs → copilot-D9T1jbpu.mjs} +13 -3
  5. package/copilot-D9T1jbpu.mjs.map +1 -0
  6. package/{copilot-headers-BLnBaJyp.mjs → copilot-headers-I-AOoDed.mjs} +2 -2
  7. package/{copilot-headers-BLnBaJyp.mjs.map → copilot-headers-I-AOoDed.mjs.map} +1 -1
  8. package/{failure-5Wjd-qFH.d.mts → failure-CCCRfhCf.d.mts} +6 -3
  9. package/{failure-DFQNKc-O.mjs → failure-D0qEqOsO.mjs} +37 -5
  10. package/failure-D0qEqOsO.mjs.map +1 -0
  11. package/github-copilot-C75m0xwW.mjs +3 -0
  12. package/{github-copilot-BcmOr0jd.mjs → github-copilot-CdkIxdQS.mjs} +31 -15
  13. package/github-copilot-CdkIxdQS.mjs.map +1 -0
  14. package/index.d.mts +540 -237
  15. package/index.mjs +566 -103
  16. package/index.mjs.map +1 -1
  17. package/interactive-c0deRdi7.mjs +115 -0
  18. package/interactive-c0deRdi7.mjs.map +1 -0
  19. package/llm/failure.d.mts +2 -2
  20. package/llm/failure.mjs +2 -2
  21. package/{model-Cjp-Dr8V.mjs → model-BZZZAySN.mjs} +564 -617
  22. package/{model-Cjp-Dr8V.mjs.map → model-BZZZAySN.mjs.map} +1 -1
  23. package/{model-D3wc9-u4.d.mts → model-Dgf7E5gc.d.mts} +20 -1
  24. package/{openai-codex-C1Yb02kM.mjs → model-av44O6GQ.mjs} +340 -355
  25. package/model-av44O6GQ.mjs.map +1 -0
  26. package/{modelgen-DXMmI80T.mjs → modelgen-f3yv7FiK.mjs} +50 -17
  27. package/modelgen-f3yv7FiK.mjs.map +1 -0
  28. package/modelgen.d.mts +1 -1
  29. package/modelgen.mjs +2 -2
  30. package/oauth/github/copilot.d.mts +10 -0
  31. package/oauth/github/copilot.mjs +2 -2
  32. package/oauth/interactive.d.mts +6 -1
  33. package/oauth/interactive.mjs +2 -2
  34. package/oauth/openai/codex.mjs +1 -1
  35. package/openai-codex-BGNrJzTb.mjs +2 -0
  36. package/openai-codex-DL0lqVuN.mjs +117 -0
  37. package/openai-codex-DL0lqVuN.mjs.map +1 -0
  38. package/package.json +1 -1
  39. package/{registry-u49t0S4S.mjs → registry-BULNTLAP.mjs} +10 -6
  40. package/{registry-u49t0S4S.mjs.map → registry-BULNTLAP.mjs.map} +1 -1
  41. package/codex-CLDBTrFm.mjs.map +0 -1
  42. package/copilot-DvUXC6Kx.mjs.map +0 -1
  43. package/failure-DFQNKc-O.mjs.map +0 -1
  44. package/github-copilot-BcmOr0jd.mjs.map +0 -1
  45. package/github-copilot-llyP2NK4.mjs +0 -3
  46. package/interactive-eoNnscGB.mjs +0 -57
  47. package/interactive-eoNnscGB.mjs.map +0 -1
  48. package/modelgen-DXMmI80T.mjs.map +0 -1
  49. package/openai-codex-C1Yb02kM.mjs.map +0 -1
  50. package/openai-codex-CHxShIN3.mjs +0 -2
package/index.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { E as NamedError, _ as modelsAreEqual, a as KnownProviderEnumSchema, b as registry, f as getModel, g as model_exports, i as KnownProviderEnum, l as calculateCost, m as getProviders, n as APIMethodEnumSchema, p as getModels, r as ActiveThinkingLevel, s as ThinkingBudgets$1, t as APIMethodEnum, u as clampThinkingLevel, x as thinkingTokenBudgetField, y as optionsKey } from "./model-Cjp-Dr8V.mjs";
3
- import { C as ToolCallSchema, E as transformMessages, S as AssistantMessageSchema, T as message_exports, g as shortHash, n as createOpenAICodex, r as openaiCodex, v as openAICodexTools, w as createAssistantMessage$1, x as resolveOpenAICodexToolConstraint } from "./openai-codex-C1Yb02kM.mjs";
4
- import { r as normalize, t as failure_exports } from "./failure-DFQNKc-O.mjs";
5
- import { i as packageForModel, o as resolveLanguageModel, r as loadProviderFactory } from "./registry-u49t0S4S.mjs";
6
- import { i as githubCopilot, r as createGitHubCopilot } from "./github-copilot-BcmOr0jd.mjs";
2
+ import { E as NamedError, _ as modelsAreEqual, a as KnownProviderEnumSchema, b as registry, f as getModel, g as model_exports, i as KnownProviderEnum, l as calculateCost, m as getProviders, n as APIMethodEnumSchema, p as getModels, r as ActiveThinkingLevel, s as ThinkingBudgets$1, t as APIMethodEnum, u as clampThinkingLevel, x as thinkingTokenBudgetField, y as optionsKey } from "./model-BZZZAySN.mjs";
3
+ import { a as AssistantMessageSchema, c as message_exports, i as resolveToolGrammar, l as omitImages, o as ToolCallSchema, r as shortHash, s as createAssistantMessage$1, u as transformMessages } from "./model-av44O6GQ.mjs";
4
+ import { a as strictToolLimitMessage, i as normalize, t as failure_exports } from "./failure-D0qEqOsO.mjs";
5
+ import { i as packageForModel, o as resolveLanguageModel, r as loadProviderFactory, s as resolveMethod } from "./registry-BULNTLAP.mjs";
6
+ import { a as openaiCodex, i as openAICodexTools, r as createOpenAICodex } from "./openai-codex-DL0lqVuN.mjs";
7
+ import { i as githubCopilot, r as createGitHubCopilot } from "./github-copilot-CdkIxdQS.mjs";
7
8
  import Type$2, { Type, Type as Type$1 } from "typebox";
8
9
  import { APICallError } from "@ai-sdk/provider";
9
10
  import { RetryError, jsonSchema, streamText } from "ai";
@@ -222,6 +223,196 @@ function formatThrownError(error) {
222
223
  }
223
224
  }
224
225
  //#endregion
226
+ //#region src/message/transcript.ts
227
+ var transcript_exports = /* @__PURE__ */ __exportAll({
228
+ declarationsEqual: () => declarationsEqual,
229
+ diffSections: () => diffSections,
230
+ getCurrentSections: () => getCurrentSections,
231
+ getCurrentSystemPrompt: () => getCurrentSystemPrompt,
232
+ getCurrentTools: () => getCurrentTools,
233
+ getDeclaredTools: () => getDeclaredTools,
234
+ getToolStateChanges: () => getToolStateChanges,
235
+ renderSystemPrompt: () => renderSystemPrompt,
236
+ renderSystemPromptUpdate: () => renderSystemPromptUpdate,
237
+ resolveTranscriptPrompt: () => resolveTranscriptPrompt,
238
+ resolveTranscriptTools: () => resolveTranscriptTools,
239
+ toToolDeclaration: () => toToolDeclaration
240
+ });
241
+ function isSystemMessage(message) {
242
+ return message.role === "system";
243
+ }
244
+ /** Render a system message as a complete prompt: its content followed by its sections. */
245
+ function renderSystemPrompt(message) {
246
+ const parts = [message.content ?? ""];
247
+ for (const text of Object.values(message.sections ?? {})) if (text !== null) parts.push(text);
248
+ return parts.filter((part) => part.length > 0).join("\n\n");
249
+ }
250
+ /**
251
+ * Render a later system message sent in place. Section changes are framed by name so the
252
+ * model can relate them to the leading prompt.
253
+ */
254
+ function renderSystemPromptUpdate(message) {
255
+ const parts = [];
256
+ if (message.content) parts.push(message.content);
257
+ for (const [name, value] of Object.entries(message.sections ?? {})) parts.push(value === null ? `Removed system prompt section "${name}".` : `Updated system prompt section "${name}":\n\n${value}`);
258
+ return parts.join("\n\n");
259
+ }
260
+ /**
261
+ * The sections after every transcript change in order: replaced by name, removed by `null`, and
262
+ * a removed section added again goes last.
263
+ */
264
+ function getCurrentSections(messages) {
265
+ const sections = /* @__PURE__ */ new Map();
266
+ for (const message of messages) {
267
+ if (!isSystemMessage(message)) continue;
268
+ for (const [name, value] of Object.entries(message.sections ?? {})) if (value === null) sections.delete(name);
269
+ else sections.set(name, value);
270
+ }
271
+ return Object.fromEntries(sections);
272
+ }
273
+ /**
274
+ * The patch that brings `previous` sections to `current`, `null` removing one; `undefined` when
275
+ * they match.
276
+ */
277
+ function diffSections(previous, current) {
278
+ const patch = {};
279
+ for (const [name, text] of Object.entries(current)) if (previous[name] !== text) patch[name] = text;
280
+ for (const name of Object.keys(previous)) if (!Object.hasOwn(current, name)) patch[name] = null;
281
+ return Object.keys(patch).length === 0 ? void 0 : patch;
282
+ }
283
+ /** The prompt after every transcript change in order: content accumulates, sections as {@link getCurrentSections}. */
284
+ function getCurrentSystemPrompt(context) {
285
+ const content = [context.systemPrompt ?? ""];
286
+ for (const message of context.messages) if (isSystemMessage(message)) content.push(message.content ?? "");
287
+ return renderSystemPrompt({
288
+ content: content.filter((part) => part.length > 0).join("\n\n"),
289
+ sections: getCurrentSections(context.messages)
290
+ });
291
+ }
292
+ /**
293
+ * Split the prompt between the head of the request and in-place updates.
294
+ *
295
+ * In place, `Context.systemPrompt` leads; without one (and without initial tools), a leading
296
+ * system message is the prompt. Every other system message is an update. Otherwise the head
297
+ * holds the current prompt and no update is sent, which costs the cached prefix on a change.
298
+ */
299
+ function resolveTranscriptPrompt(context, inPlace) {
300
+ const systemMessages = context.messages.filter(isSystemMessage);
301
+ if (!inPlace) return {
302
+ systemPrompt: getCurrentSystemPrompt(context),
303
+ foldedSystemMessages: systemMessages.length
304
+ };
305
+ const first = context.messages[0];
306
+ if (!context.systemPrompt && (context.tools ?? []).length === 0 && first && isSystemMessage(first)) return {
307
+ systemPrompt: renderSystemPrompt(first),
308
+ foldedSystemMessages: 1
309
+ };
310
+ return {
311
+ systemPrompt: context.systemPrompt ?? "",
312
+ foldedSystemMessages: 0
313
+ };
314
+ }
315
+ /** The tool changes in order, led by `Context.tools` as the initial declaration. */
316
+ function toolDeclarations(context) {
317
+ return [{ toolsAdded: context.tools ?? [] }, ...context.messages.filter(isSystemMessage)];
318
+ }
319
+ function replay(declarations) {
320
+ const tools = /* @__PURE__ */ new Map();
321
+ for (const declaration of declarations) {
322
+ for (const tool of declaration.toolsRemoved ?? []) tools.delete(tool.name);
323
+ for (const tool of declaration.toolsAdded ?? []) tools.set(tool.name, tool);
324
+ }
325
+ return [...tools.values()];
326
+ }
327
+ /** The tools available after applying every transcript change in order. */
328
+ function getCurrentTools(context) {
329
+ return replay(toolDeclarations(context));
330
+ }
331
+ /**
332
+ * Every tool the transcript ever declared, the latest definition of each name winning. Removals
333
+ * are ignored: a removed tool's earlier calls still replay in the form it was called in.
334
+ */
335
+ function getDeclaredTools(context) {
336
+ const tools = /* @__PURE__ */ new Map();
337
+ for (const declaration of toolDeclarations(context)) for (const tool of declaration.toolsAdded ?? []) tools.set(tool.name, tool);
338
+ return [...tools.values()];
339
+ }
340
+ /** Strip a tool to what the model sees, for comparison and persistence. */
341
+ function toToolDeclaration(tool) {
342
+ return {
343
+ name: tool.name,
344
+ description: tool.description,
345
+ parameters: JSON.parse(JSON.stringify(tool.parameters)),
346
+ ...tool.constrainedSampling === void 0 ? {} : { constrainedSampling: tool.constrainedSampling }
347
+ };
348
+ }
349
+ /**
350
+ * Whether two tools declare the same interface to the model. The JSON round trip in
351
+ * {@link toToolDeclaration} drops typebox symbol keys and `undefined` fields and fixes the key
352
+ * order, so comparing the serialized declarations is exact.
353
+ */
354
+ function declarationsEqual(left, right) {
355
+ return JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));
356
+ }
357
+ /** Compare two complete tool states. A changed definition is a removal followed by an addition. */
358
+ function getToolStateChanges(previous, current) {
359
+ const previousTools = new Map(previous.map((tool) => [tool.name, tool]));
360
+ const currentTools = new Map(current.map((tool) => [tool.name, tool]));
361
+ return {
362
+ toolsAdded: current.filter((tool) => {
363
+ const previousTool = previousTools.get(tool.name);
364
+ return previousTool === void 0 || !declarationsEqual(previousTool, tool);
365
+ }).map(toToolDeclaration),
366
+ toolsRemoved: previous.filter((tool) => {
367
+ const currentTool = currentTools.get(tool.name);
368
+ return currentTool === void 0 || !declarationsEqual(tool, currentTool);
369
+ }).map((tool) => ({ name: tool.name }))
370
+ };
371
+ }
372
+ /** Index of the last declaration with a removal or same-name redeclaration, or -1. */
373
+ function lastNonAdditiveChange(declarations) {
374
+ const declared = /* @__PURE__ */ new Set();
375
+ let last = -1;
376
+ for (const [index, declaration] of declarations.entries()) {
377
+ if ((declaration.toolsRemoved?.length ?? 0) > 0) last = index;
378
+ for (const tool of declaration.toolsAdded ?? []) {
379
+ if (declared.has(tool.name)) last = index;
380
+ declared.add(tool.name);
381
+ }
382
+ }
383
+ return last;
384
+ }
385
+ /**
386
+ * Split tool declarations between the top-level request field and in-place changes.
387
+ *
388
+ * With `"changes"`, the top-level list stays empty and every declaration, including
389
+ * `Context.tools`, goes in place: an in-place declaration can replace an earlier in-place one,
390
+ * but not a top-level one. With `"additions"`, a removal or redefinition cannot be expressed in
391
+ * place, so the top-level list becomes the tool state after the last such change; later
392
+ * additions stay in place, and the cached prefix is invalidated once per removal instead of on
393
+ * every later addition. With `"none"`, the top-level list is the current tool set.
394
+ */
395
+ function resolveTranscriptTools(context, support) {
396
+ const declarations = toolDeclarations(context);
397
+ const transcriptMessages = declarations.length - 1;
398
+ if (support === "none") return {
399
+ requestTools: replay(declarations),
400
+ initialToolsInPlace: false,
401
+ foldedSystemMessages: transcriptMessages
402
+ };
403
+ if (support === "changes") return {
404
+ requestTools: [],
405
+ initialToolsInPlace: true,
406
+ foldedSystemMessages: 0
407
+ };
408
+ const folded = Math.max(1, lastNonAdditiveChange(declarations) + 1);
409
+ return {
410
+ requestTools: replay(declarations.slice(0, folded)),
411
+ initialToolsInPlace: false,
412
+ foldedSystemMessages: folded - 1
413
+ };
414
+ }
415
+ //#endregion
225
416
  //#region src/utils/estimate.ts
226
417
  /** Rough characters-per-token ratio across the tokenizers in use. */
227
418
  const CHARS_PER_TOKEN = 4;
@@ -259,6 +450,7 @@ function toolResultChars(part) {
259
450
  return "result" in part && part.result ? contentChars(part.result.content) : 0;
260
451
  }
261
452
  function estimateMessageTokens(message) {
453
+ if (message.role === "system") return estimateTextTokens(renderSystemPromptUpdate(message)) + estimateToolsTokens(message.toolsAdded);
262
454
  if (message.role === "user") return estimateContentTokens(message.parts);
263
455
  let chars = 0;
264
456
  for (const part of message.parts) switch (part.type) {
@@ -319,31 +511,9 @@ function estimateToolsTokens(tools) {
319
511
  if (!tools || tools.length === 0) return 0;
320
512
  return estimateTextTokens(safeJsonStringify(tools));
321
513
  }
322
- /** Tools discovered by execution of the given assistant turn or later turns. */
323
- function toolNamesAddedAfter(messages, index) {
324
- const names = /* @__PURE__ */ new Set();
325
- for (let i = index; i < messages.length; i++) {
326
- const message = messages[i];
327
- if (message.role !== "assistant") continue;
328
- for (const part of message.parts) {
329
- if (part.type !== "toolCall") continue;
330
- for (const name of part.addedToolNames ?? []) names.add(name);
331
- }
332
- }
333
- return names;
334
- }
335
514
  function estimateContextTokens(context) {
336
515
  const estimate = estimateMessages(context.messages);
337
- if (estimate.lastUsageIndex !== null) {
338
- const added = toolNamesAddedAfter(context.messages, estimate.lastUsageIndex);
339
- const addedTokens = estimateToolsTokens(context.tools?.filter((tool) => added.has(tool.name)));
340
- return {
341
- tokens: estimate.tokens + addedTokens,
342
- usageTokens: estimate.usageTokens,
343
- trailingTokens: estimate.trailingTokens + addedTokens,
344
- lastUsageIndex: estimate.lastUsageIndex
345
- };
346
- }
516
+ if (estimate.lastUsageIndex !== null) return estimate;
347
517
  const prefixTokens = (context.systemPrompt ? estimateTextTokens(context.systemPrompt) : 0) + estimateToolsTokens(context.tools);
348
518
  return {
349
519
  tokens: estimate.tokens + prefixTokens,
@@ -634,17 +804,20 @@ async function resolveAISDKLanguageModel(model, options, thinkingTokenBudget) {
634
804
  const budgetField = thinkingTokenBudgetField(model);
635
805
  if (budgetField && thinkingTokenBudget !== void 0 && thinkingTokenBudget > 0) factoryOptions.transformRequestBody = thinkingTokenBudgetTransform(budgetField, thinkingTokenBudget, factoryOptions.transformRequestBody);
636
806
  }
807
+ const cacheDisabled = options.cacheRetention === "none" || typeof process !== "undefined" && process.env.CODEWORK_CACHE_RETENTION === "none";
808
+ const responsesCompat = () => ({
809
+ ...model.compat,
810
+ supportsImages: model.input.includes("image"),
811
+ ...typeof factoryOptions.compat === "object" && factoryOptions.compat !== null ? factoryOptions.compat : {}
812
+ });
637
813
  if (npm === "@codeworksh/ai-sdk-openai-codex") {
638
- const cacheDisabled = options.cacheRetention === "none" || typeof process !== "undefined" && process.env.CODEWORK_CACHE_RETENTION === "none";
639
814
  if (options.sessionId && !cacheDisabled) factoryOptions.sessionId ??= options.sessionId;
640
- factoryOptions.compat = {
641
- ...model.compat,
642
- supportsImages: model.input.includes("image"),
643
- ...typeof factoryOptions.compat === "object" && factoryOptions.compat !== null ? factoryOptions.compat : {}
644
- };
815
+ factoryOptions.compat = responsesCompat();
645
816
  }
646
817
  if (npm === "@codeworksh/ai-sdk-github-copilot") {
647
818
  if (options.sessionId) factoryOptions.sessionId ??= options.sessionId;
819
+ if (options.sessionId && !cacheDisabled) factoryOptions.promptCacheKey ??= options.sessionId;
820
+ factoryOptions.compat = responsesCompat();
648
821
  const budgetField = thinkingTokenBudgetField(model);
649
822
  if (budgetField && thinkingTokenBudget !== void 0 && thinkingTokenBudget > 0) factoryOptions.transformRequestBody = thinkingTokenBudgetTransform(budgetField, thinkingTokenBudget, factoryOptions.transformRequestBody);
650
823
  }
@@ -735,7 +908,9 @@ function disabledProviderOptions(model) {
735
908
  return { [key]: { thinking: { type: "disabled" } } };
736
909
  }
737
910
  if (key === "github-copilot") {
738
- if (model.api?.method === APIMethodEnum.messages) return { [key]: { thinking: { type: "disabled" } } };
911
+ const off = model.thinkingLevelMap?.off;
912
+ if (model.api?.method === APIMethodEnum.messages) return off === null ? {} : { [key]: { thinking: { type: "disabled" } } };
913
+ if (model.api?.method === APIMethodEnum.responses && typeof off === "string") return { [key]: { reasoningEffort: off } };
739
914
  return {};
740
915
  }
741
916
  if (key === "google" || key === "google-vertex") {
@@ -1086,11 +1261,12 @@ function makeStrictJsonSchema(schema, isUnsupportedKeyword) {
1086
1261
  /**
1087
1262
  * The strict parameter schema to send for a JSON-schema constrained tool, or `undefined` to send it non-strict.
1088
1263
  * A `"prefer"` tool whose schema the model's strict mode cannot express falls back to non-strict; a `"require"`
1089
- * tool throws instead.
1264
+ * tool throws instead. `preferNonStrict` sends every `"prefer"` tool non-strict.
1090
1265
  */
1091
- function resolveStrictParameters(tool, model) {
1266
+ function resolveStrictParameters(tool, model, preferNonStrict = false) {
1092
1267
  const config = tool.constrainedSampling;
1093
1268
  if (!config || config.type !== "json_schema") return;
1269
+ if (preferNonStrict && config.strict === "prefer") return;
1094
1270
  if (model?.compat?.supportsStrictMode ?? true) {
1095
1271
  const isAnthropic = model?.protocol === KnownProviderEnum.anthropic || model?.protocol === KnownProviderEnum.googleVertexAnthropic;
1096
1272
  try {
@@ -1170,10 +1346,46 @@ function sanitizeValue(value) {
1170
1346
  function sanitizeRecord(value) {
1171
1347
  return sanitizeValue(value);
1172
1348
  }
1173
- function toolResultOutput(toolCall) {
1174
- const text = toolCall.result.content.filter((content) => content.type === "text").map((content) => sanitizeSurrogates(content.text)).join("\n");
1175
- const images = toolCall.result.content.filter((content) => content.type === "image");
1176
- if (toolCall.result.isError) return {
1349
+ const ERROR_TOOL_IMAGE_PLACEHOLDER = "(image attached after the tool results)";
1350
+ const MOVED_TOOL_IMAGE_PLACEHOLDER = "(see attached image)";
1351
+ const CHAT_TOOL_IMAGES_CAPTION = "Attached image(s) from tool result:";
1352
+ const GEMINI_TOOL_IMAGES_CAPTION = "Tool result image:";
1353
+ const COPILOT = "@codeworksh/ai-sdk-github-copilot";
1354
+ function isAnthropicWire(model, method) {
1355
+ if (packageForModel(model) === COPILOT) return method === APIMethodEnum.messages;
1356
+ return isAnthropicMessagesModel(model);
1357
+ }
1358
+ /** Whether the model runs on our own Responses transport: Codex, and Copilot's `/responses`. */
1359
+ function isOwnResponses(model, methodOverride) {
1360
+ if (model.protocol === KnownProviderEnum.openaiCodex) return true;
1361
+ return model.protocol === KnownProviderEnum.githubCopilot && resolveMethod(model, methodOverride) === APIMethodEnum.responses;
1362
+ }
1363
+ function isChatCompletions(model, method) {
1364
+ const npm = packageForModel(model);
1365
+ if (npm === "@ai-sdk/openai-compatible") return true;
1366
+ if (npm === COPILOT) return method !== APIMethodEnum.responses && method !== APIMethodEnum.messages;
1367
+ return npm === "@ai-sdk/openai" && method === APIMethodEnum.chat;
1368
+ }
1369
+ /** The Google adapter's own split: anything but Gemini 3 and later gets the legacy function response. */
1370
+ function isLegacyGoogleToolResults(model) {
1371
+ if (model.protocol !== KnownProviderEnum.google && model.protocol !== KnownProviderEnum.googleVertex) return false;
1372
+ const id = model.api?.id ?? model.id;
1373
+ const gemini = /(^|[/.])gemini-/i.test(id);
1374
+ const legacy = /(^|[/.])gemini-[12](?:[.-]|$)/i.test(id) || /(^|[/.])gemini-pro(?:-vision)?$/i.test(id) || /(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(id);
1375
+ return !gemini || legacy;
1376
+ }
1377
+ function movedImages(toolCall, model, method) {
1378
+ if (!toolCall.result.content.some((content) => content.type === "image")) return;
1379
+ if (isAnthropicWire(model, method)) return toolCall.result.isError ? "anthropicError" : void 0;
1380
+ if (isChatCompletions(model, method)) return "chat";
1381
+ if (isLegacyGoogleToolResults(model)) return "gemini";
1382
+ }
1383
+ function toolResultOutput(toolCall, moved) {
1384
+ const content = moved === "anthropicError" ? omitImages(toolCall.result.content, ERROR_TOOL_IMAGE_PLACEHOLDER) : moved ? toolCall.result.content.filter((content) => content.type === "text") : toolCall.result.content;
1385
+ const joined = content.filter((content) => content.type === "text").map((content) => sanitizeSurrogates(content.text)).join("\n");
1386
+ const text = moved && moved !== "anthropicError" && joined.trim().length === 0 ? MOVED_TOOL_IMAGE_PLACEHOLDER : joined;
1387
+ const images = content.filter((content) => content.type === "image");
1388
+ if (toolCall.result.isError && images.length === 0) return {
1177
1389
  type: "error-text",
1178
1390
  value: text || "tool returned an error"
1179
1391
  };
@@ -1216,7 +1428,8 @@ function normalizeForeignToolCallId(id) {
1216
1428
  if (/^[a-zA-Z0-9_-]{1,64}$/.test(id)) return id;
1217
1429
  return normalizeOpenAICodexIdPart(id.split("|")[0] ?? id);
1218
1430
  }
1219
- function toolCallIdNormalizer(model) {
1431
+ function toolCallIdNormalizer(model, method) {
1432
+ if (isOwnResponses(model, method)) return normalizeOpenAICodexToolCallId;
1220
1433
  switch (model.protocol) {
1221
1434
  case KnownProviderEnum.openaiCodex: return normalizeOpenAICodexToolCallId;
1222
1435
  case KnownProviderEnum.openai:
@@ -1231,7 +1444,7 @@ function isRecord(value) {
1231
1444
  }
1232
1445
  function encodeOpenAIReasoningSignature(providerMetadata) {
1233
1446
  if (!isRecord(providerMetadata)) return;
1234
- const metadata = providerMetadata.openai ?? providerMetadata["github-copilot"];
1447
+ const metadata = providerMetadata.openai;
1235
1448
  if (!isRecord(metadata) || typeof metadata.itemId !== "string") return;
1236
1449
  const signature = { itemId: metadata.itemId };
1237
1450
  if (typeof metadata.reasoningEncryptedContent === "string" || metadata.reasoningEncryptedContent === null) signature.reasoningEncryptedContent = metadata.reasoningEncryptedContent;
@@ -1248,6 +1461,28 @@ function decodeOpenAIReasoningSignature(signature) {
1248
1461
  return;
1249
1462
  }
1250
1463
  }
1464
+ /**
1465
+ * The reasoning item our Responses transport replays from a thinking signature. Copilot
1466
+ * messages from before it ran on that transport carry `{ itemId, reasoningEncryptedContent }`
1467
+ * instead of the item; those replay when they hold encrypted content.
1468
+ */
1469
+ function responsesReasoningItem(signature) {
1470
+ try {
1471
+ const parsed = JSON.parse(signature);
1472
+ if (!isRecord(parsed)) return;
1473
+ if (parsed.type === "reasoning" && typeof parsed.id === "string") return signature;
1474
+ const legacy = decodeOpenAIReasoningSignature(signature);
1475
+ if (!legacy || typeof legacy.reasoningEncryptedContent !== "string") return;
1476
+ return JSON.stringify({
1477
+ type: "reasoning",
1478
+ id: legacy.itemId,
1479
+ encrypted_content: legacy.reasoningEncryptedContent,
1480
+ summary: []
1481
+ });
1482
+ } catch {
1483
+ return;
1484
+ }
1485
+ }
1251
1486
  function googleThoughtSignature(metadata) {
1252
1487
  if (!isRecord(metadata)) return;
1253
1488
  for (const key of ["google", "google-vertex"]) {
@@ -1255,10 +1490,12 @@ function googleThoughtSignature(metadata) {
1255
1490
  if (isRecord(provider) && typeof provider.thoughtSignature === "string") return provider.thoughtSignature;
1256
1491
  }
1257
1492
  }
1258
- function assistantMessages(message, model) {
1493
+ function assistantMessages(message, model, method) {
1259
1494
  if (message.stopReason === "error" || message.stopReason === "aborted") return [];
1260
1495
  const assistantContent = [];
1261
1496
  const toolResults = [];
1497
+ const movedImageContent = [];
1498
+ const responsesKey = isOwnResponses(model, method) && message.protocol === model.protocol && message.provider.id === model.provider.id ? optionsKey(model) : void 0;
1262
1499
  const googleReplay = (model.protocol === "google" || model.protocol === "google-vertex") && message.protocol === model.protocol && message.provider.id === model.provider.id && message.model === model.id;
1263
1500
  const googleOptions = (signature) => googleReplay && signature ? { [optionsKey(model)]: { thoughtSignature: signature } } : void 0;
1264
1501
  for (const part of message.parts) {
@@ -1270,22 +1507,26 @@ function assistantMessages(message, model) {
1270
1507
  type: "text",
1271
1508
  text,
1272
1509
  ...google ? { providerOptions: google } : {},
1273
- ...part.textSignature && message.protocol === KnownProviderEnum.openaiCodex ? { providerOptions: { "openai-codex": { messageId: part.textSignature } } } : {}
1510
+ ...part.textSignature && responsesKey ? { providerOptions: { [responsesKey]: { messageId: part.textSignature } } } : {}
1274
1511
  });
1275
1512
  continue;
1276
1513
  }
1277
1514
  if (part.type === "thinking") {
1278
1515
  const thinking = sanitizeSurrogates(part.thinking);
1279
1516
  if (thinking.trim().length === 0 && !part.thinkingSignature) continue;
1280
- if (message.protocol === KnownProviderEnum.githubCopilot) {
1281
- const method = model.api?.method;
1282
- const openai = part.thinkingSignature ? decodeOpenAIReasoningSignature(part.thinkingSignature) : void 0;
1283
- if (method === APIMethodEnum.responses && openai) assistantContent.push({
1517
+ if (responsesKey) {
1518
+ const reasoningItem = part.thinkingSignature ? responsesReasoningItem(part.thinkingSignature) : void 0;
1519
+ if (!reasoningItem) continue;
1520
+ assistantContent.push({
1284
1521
  type: "reasoning",
1285
1522
  text: thinking,
1286
- providerOptions: { "github-copilot": openai }
1523
+ providerOptions: { [responsesKey]: { reasoningItem } }
1287
1524
  });
1288
- else if (method === APIMethodEnum.messages && part.thinkingSignature && !openai) assistantContent.push({
1525
+ continue;
1526
+ }
1527
+ if (message.protocol === KnownProviderEnum.githubCopilot) {
1528
+ const openai = part.thinkingSignature ? decodeOpenAIReasoningSignature(part.thinkingSignature) : void 0;
1529
+ if (method === APIMethodEnum.messages && part.thinkingSignature && !openai) assistantContent.push({
1289
1530
  type: "reasoning",
1290
1531
  text: thinking,
1291
1532
  providerOptions: { anthropic: { signature: part.thinkingSignature } }
@@ -1306,33 +1547,44 @@ function assistantMessages(message, model) {
1306
1547
  if (!openai) continue;
1307
1548
  reasoning.providerOptions = { openai };
1308
1549
  } else if (google) reasoning.providerOptions = google;
1309
- else if (part.thinkingSignature && message.protocol !== "google" && message.protocol !== "google-vertex") reasoning.providerOptions = message.protocol === KnownProviderEnum.openaiCodex ? { "openai-codex": { reasoningItem: part.thinkingSignature } } : { anthropic: { signature: part.thinkingSignature } };
1550
+ else if (part.thinkingSignature && message.protocol !== "google" && message.protocol !== "google-vertex") reasoning.providerOptions = { anthropic: { signature: part.thinkingSignature } };
1310
1551
  assistantContent.push(reasoning);
1311
1552
  continue;
1312
1553
  }
1313
1554
  if (part.type !== "toolCall") continue;
1314
- const codexToolMetadata = {};
1315
- if (part.namespace && message.protocol === KnownProviderEnum.openaiCodex) codexToolMetadata.namespace = part.namespace;
1316
- if (model.protocol === KnownProviderEnum.openaiCodex && message.protocol === model.protocol && message.provider.id === model.provider.id && message.model !== model.id) codexToolMetadata.omitItemId = true;
1555
+ const responsesToolMetadata = {};
1556
+ if (responsesKey && part.namespace) responsesToolMetadata.namespace = part.namespace;
1557
+ if (responsesKey && message.model !== model.id) responsesToolMetadata.omitItemId = true;
1317
1558
  assistantContent.push({
1318
1559
  type: "tool-call",
1319
1560
  toolCallId: part.callID,
1320
1561
  toolName: part.name,
1321
1562
  input: sanitizeRecord(part.arguments ?? {}),
1322
1563
  ...google ? { providerOptions: google } : {},
1323
- ...Object.keys(codexToolMetadata).length > 0 ? { providerOptions: { "openai-codex": codexToolMetadata } } : {}
1564
+ ...responsesKey && Object.keys(responsesToolMetadata).length > 0 ? { providerOptions: { [responsesKey]: responsesToolMetadata } } : {}
1324
1565
  });
1325
1566
  const terminal = part.status === "pending" || part.status === "running" ? void 0 : part;
1567
+ const moved = terminal ? movedImages(terminal, model, method) : void 0;
1326
1568
  toolResults.push({
1327
1569
  type: "tool-result",
1328
1570
  toolCallId: part.callID,
1329
1571
  toolName: part.name,
1330
- ...terminal?.addedToolNames?.length ? { providerOptions: { "openai-codex": { addedToolNames: terminal.addedToolNames } } } : {},
1331
- output: terminal ? toolResultOutput(terminal) : {
1572
+ output: terminal ? toolResultOutput(terminal, moved) : {
1332
1573
  type: "error-text",
1333
1574
  value: "no result provided"
1334
1575
  }
1335
1576
  });
1577
+ if (terminal && moved) {
1578
+ const caption = moved === "anthropicError" ? `Images from the error result of tool call ${part.callID} (${part.name}):` : moved === "gemini" ? GEMINI_TOOL_IMAGES_CAPTION : movedImageContent.length === 0 ? CHAT_TOOL_IMAGES_CAPTION : void 0;
1579
+ movedImageContent.push(...caption === void 0 ? [] : [{
1580
+ type: "text",
1581
+ text: caption
1582
+ }], ...terminal.result.content.flatMap((content) => content.type === "image" ? [{
1583
+ type: "file",
1584
+ data: content.data,
1585
+ mediaType: content.mimeType
1586
+ }] : []));
1587
+ }
1336
1588
  }
1337
1589
  const result = [];
1338
1590
  if (assistantContent.length > 0) result.push({
@@ -1343,31 +1595,216 @@ function assistantMessages(message, model) {
1343
1595
  role: "tool",
1344
1596
  content: toolResults
1345
1597
  });
1598
+ if (movedImageContent.length > 0) result.push({
1599
+ role: "user",
1600
+ content: movedImageContent
1601
+ });
1346
1602
  return result;
1347
1603
  }
1348
- function convertMessages(context, model) {
1604
+ /**
1605
+ * How the model's transport expresses tool changes after the first request. Only our own
1606
+ * Responses transport can declare tools in place; the AI SDK adapters take the current tool
1607
+ * set top-level. A request limited to some tools (`activeTools`) takes them top-level too,
1608
+ * since only that list is filtered.
1609
+ */
1610
+ function transcriptToolSupport(model, method, restricted = false) {
1611
+ if (restricted || !isOwnResponses(model, method)) return "none";
1612
+ if (supportsMidConvoSystemMessages(model, method) && model.compat?.supportsAdditionalTools) return "changes";
1613
+ return model.compat?.supportsToolSearch ? "additions" : "none";
1614
+ }
1615
+ /**
1616
+ * Whether prompt changes go in place as system messages. Our own Responses transport and the
1617
+ * AI SDK's OpenAI Responses and Anthropic Messages adapters keep them where they stand; Chat
1618
+ * Completions takes the current prompt as the leading system prompt.
1619
+ */
1620
+ function supportsMidConvoSystemMessages(model, method) {
1621
+ if (model.compat?.supportsMidConvoSystemMessages !== true) return false;
1622
+ return isOwnResponses(model, method) || !isChatCompletions(model, resolveMethod(model, method));
1623
+ }
1624
+ /**
1625
+ * Anthropic with tool changes in place: every tool the thread can reach is declared up front, the
1626
+ * ones beyond its initial set deferred, and later changes name them by reference. Adding a tool
1627
+ * to the top-level list costs the cached prefix; referencing a deferred one does not.
1628
+ */
1629
+ function anthropicToolReferences(model, method, restricted) {
1630
+ return !restricted && isAnthropicWire(model, method) && supportsMidConvoSystemMessages(model, method) && model.compat?.supportsAdditionalTools === true;
1631
+ }
1632
+ /** Messages before the first reply: on Anthropic their system messages join the leading prompt and tools. */
1633
+ function beforeFirstReply(messages) {
1634
+ const reply = messages.findIndex((message) => message.role === "assistant");
1635
+ return reply === -1 ? [...messages] : messages.slice(0, reply);
1636
+ }
1637
+ /**
1638
+ * The tools the request declares top-level, and which of them are deferred. Usually every tool
1639
+ * callable now. With Anthropic tool references, the initial set, then the deferred catalog and
1640
+ * every other tool the transcript declared, deferred, in an order that holds across requests.
1641
+ */
1642
+ function requestTools(context, model, methodOverride, activeTools) {
1643
+ if (!anthropicToolReferences(model, resolveMethod(model, methodOverride), activeTools !== void 0)) return {
1644
+ tools: getCurrentTools(context),
1645
+ deferred: /* @__PURE__ */ new Set()
1646
+ };
1647
+ const initial = getCurrentTools({
1648
+ ...context,
1649
+ messages: beforeFirstReply(context.messages)
1650
+ });
1651
+ const latest = new Map(getDeclaredTools(context).map((tool) => [tool.name, tool]));
1652
+ const tools = new Map(initial.map((tool) => [tool.name, tool]));
1653
+ const deferred = /* @__PURE__ */ new Set();
1654
+ for (const tool of [...context.deferredTools ?? [], ...latest.values()]) {
1655
+ if (tools.has(tool.name)) continue;
1656
+ tools.set(tool.name, latest.get(tool.name) ?? tool);
1657
+ deferred.add(tool.name);
1658
+ }
1659
+ return {
1660
+ tools: [...tools.values()],
1661
+ deferred
1662
+ };
1663
+ }
1664
+ /** A later system message's tool changes as Anthropic tool references; a redefinition needs no removal. */
1665
+ function toolReferences(message) {
1666
+ const added = new Set((message.toolsAdded ?? []).map((tool) => tool.name));
1667
+ return [...(message.toolsRemoved ?? []).filter((tool) => !added.has(tool.name)).map((tool) => ({
1668
+ type: "tool_removal",
1669
+ toolName: tool.name
1670
+ })), ...[...added].map((name) => ({
1671
+ type: "tool_addition",
1672
+ toolName: name
1673
+ }))];
1674
+ }
1675
+ /**
1676
+ * The prompt the AI SDK adapters take as `system`: the leading one when changes go in place,
1677
+ * else the current one, every change folded in.
1678
+ */
1679
+ function leadingSystemPrompt(context, model, method) {
1680
+ return resolveTranscriptPrompt(context, supportsMidConvoSystemMessages(model, method)).systemPrompt || void 0;
1681
+ }
1682
+ /** A tool as the language model receives it, for declaring it inside the prompt. */
1683
+ function functionTool(tool, model, method) {
1684
+ const { inputSchema, strict, providerOptions } = toolWire(tool, model, method);
1685
+ return {
1686
+ type: "function",
1687
+ name: tool.name,
1688
+ description: tool.description,
1689
+ inputSchema: JSON.parse(JSON.stringify(inputSchema)),
1690
+ ...strict ? { strict } : {},
1691
+ ...providerOptions ? { providerOptions } : {}
1692
+ };
1693
+ }
1694
+ /** A system message sent in place: the prompt update `content`, then the tool change, if any. */
1695
+ function systemChangeMessage(content, toolsAdded, toolsRemoved, support, model, method) {
1696
+ if (toolsAdded.length === 0 && toolsRemoved.length === 0) return content.length > 0 ? {
1697
+ role: "system",
1698
+ content: sanitizeSurrogates(content)
1699
+ } : void 0;
1700
+ const toolChange = {
1701
+ mode: support === "changes" ? "changes" : "additions",
1702
+ tools: toolsAdded.map((tool) => functionTool(tool, model, method)),
1703
+ removed: toolsRemoved.map((tool) => tool.name)
1704
+ };
1705
+ return {
1706
+ role: "system",
1707
+ content: sanitizeSurrogates(content),
1708
+ providerOptions: { [optionsKey(model)]: { toolChange } }
1709
+ };
1710
+ }
1711
+ function convertMessages(context, model, methodOverride, activeTools) {
1712
+ const method = resolveMethod(model, methodOverride);
1349
1713
  const messages = [];
1350
- const transformedMessages = transformMessages(context.messages, model, toolCallIdNormalizer(model));
1714
+ const transformedMessages = transformMessages(context.messages, model, toolCallIdNormalizer(model, method));
1715
+ const support = transcriptToolSupport(model, method, activeTools !== void 0);
1716
+ const transcript = resolveTranscriptTools(context, support);
1717
+ const prompt = resolveTranscriptPrompt(context, supportsMidConvoSystemMessages(model, method));
1718
+ if (transcript.initialToolsInPlace) {
1719
+ const head = systemChangeMessage("", context.tools ?? [], [], support, model, method);
1720
+ if (head) messages.push(head);
1721
+ }
1722
+ if (isOwnResponses(model, method) && prompt.systemPrompt) messages.push({
1723
+ role: "system",
1724
+ content: sanitizeSurrogates(prompt.systemPrompt)
1725
+ });
1726
+ const anthropic = isAnthropicWire(model, method);
1727
+ const references = anthropicToolReferences(model, method, activeTools !== void 0);
1728
+ const leading = [];
1729
+ const held = [];
1730
+ let replied = false;
1731
+ let systemIndex = 0;
1351
1732
  for (const msg of transformedMessages) {
1733
+ if (msg.role === "system") {
1734
+ const index = systemIndex++;
1735
+ const update = index < prompt.foldedSystemMessages ? "" : renderSystemPromptUpdate(msg);
1736
+ const toolChanges = references && replied ? toolReferences(msg) : [];
1737
+ if (toolChanges.length > 0) {
1738
+ held.push({
1739
+ role: "system",
1740
+ content: sanitizeSurrogates(update),
1741
+ providerOptions: { [optionsKey(model)]: { toolChanges } }
1742
+ });
1743
+ continue;
1744
+ }
1745
+ const folded = index < transcript.foldedSystemMessages;
1746
+ const change = systemChangeMessage(update, folded ? [] : msg.toolsAdded ?? [], folded ? [] : msg.toolsRemoved ?? [], support, model, method);
1747
+ if (change) (!anthropic ? messages : replied ? held : leading).push(change);
1748
+ continue;
1749
+ }
1352
1750
  if (msg.role === "user") {
1353
1751
  messages.push(...userContent(msg.parts));
1354
1752
  continue;
1355
1753
  }
1356
- messages.push(...assistantMessages(msg, model));
1754
+ const converted = assistantMessages(msg, model, method);
1755
+ if (converted.length > 0) {
1756
+ replied = true;
1757
+ messages.push(...held.splice(0));
1758
+ }
1759
+ messages.push(...converted);
1760
+ }
1761
+ return [
1762
+ ...leading,
1763
+ ...messages,
1764
+ ...held
1765
+ ];
1766
+ }
1767
+ /**
1768
+ * The string input property of every grammar tool the transcript declared, for our Responses
1769
+ * transport: earlier calls to a tool since removed or redefined still replay as grammar calls.
1770
+ */
1771
+ function grammarToolInputProperties(context, model, method) {
1772
+ if (!isOwnResponses(model, method)) return;
1773
+ const properties = {};
1774
+ for (const tool of getDeclaredTools(context)) {
1775
+ const grammar = resolveToolGrammar(tool, model.compat);
1776
+ if (grammar) properties[tool.name] = grammar.inputProperty;
1357
1777
  }
1358
- return messages;
1778
+ return Object.keys(properties).length > 0 ? properties : void 0;
1779
+ }
1780
+ /** The parameter schema, strict flag and grammar a tool goes out with on this model. */
1781
+ function toolWire(tool, model, method, preferNonStrict = false) {
1782
+ const strictParameters = resolveStrictParameters(tool, model, preferNonStrict);
1783
+ const grammarConstraint = model && isOwnResponses(model, method) ? resolveToolGrammar(tool, model.compat) : void 0;
1784
+ return {
1785
+ inputSchema: strictParameters ?? tool.parameters,
1786
+ strict: strictParameters ? true : void 0,
1787
+ providerOptions: model && grammarConstraint ? { [optionsKey(model)]: { grammar: grammarConstraint } } : void 0
1788
+ };
1359
1789
  }
1360
- function convertTools(tools, model) {
1790
+ function convertTools(tools, model, method, deferred = /* @__PURE__ */ new Set(), preferNonStrict = false) {
1361
1791
  if (!tools || tools.length === 0) return;
1362
1792
  const result = {};
1363
1793
  for (const tool of tools) {
1364
- const strictParameters = resolveStrictParameters(tool, model);
1365
- const grammarConstraint = model?.protocol === KnownProviderEnum.openaiCodex ? resolveOpenAICodexToolConstraint(tool, model.compat) : void 0;
1794
+ const { inputSchema, strict, providerOptions } = toolWire(tool, model, method, preferNonStrict);
1795
+ const key = model && deferred.has(tool.name) ? optionsKey(model) : void 0;
1796
+ const options = key === void 0 ? providerOptions : {
1797
+ ...providerOptions,
1798
+ [key]: {
1799
+ ...providerOptions?.[key],
1800
+ deferLoading: true
1801
+ }
1802
+ };
1366
1803
  result[tool.name] = {
1367
1804
  description: tool.description,
1368
- inputSchema: jsonSchema(strictParameters ?? tool.parameters),
1369
- ...strictParameters ? { strict: true } : {},
1370
- ...grammarConstraint ? { providerOptions: { "openai-codex": { grammar: grammarConstraint } } } : {}
1805
+ inputSchema: jsonSchema(inputSchema),
1806
+ ...strict ? { strict } : {},
1807
+ ...options ? { providerOptions: options } : {}
1371
1808
  };
1372
1809
  }
1373
1810
  return result;
@@ -1471,15 +1908,17 @@ function cacheProviderOptions(model, options) {
1471
1908
  } } };
1472
1909
  return {};
1473
1910
  }
1474
- function resolveProviderOptions(model, options, plan) {
1475
- return mergeProviderOptions(model.providerOptions, cacheProviderOptions(model, options), reasoningProviderOptions(model, plan), options.providerOptions);
1911
+ function resolveProviderOptions(model, context, options, plan) {
1912
+ const grammars = grammarToolInputProperties(context, model, options.method);
1913
+ return mergeProviderOptions(model.providerOptions, cacheProviderOptions(model, options), reasoningProviderOptions(model, plan), grammars === void 0 ? void 0 : { [optionsKey(model)]: { grammarToolInputProperties: grammars } }, options.providerOptions);
1476
1914
  }
1477
1915
  function partIndex(output, block) {
1478
1916
  return output.parts.indexOf(block);
1479
1917
  }
1480
- function openAICodexMetadata(value) {
1918
+ /** Metadata our Responses transport attaches under the model's provider key. */
1919
+ function responsesMetadata(value, model) {
1481
1920
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1482
- const metadata = value["openai-codex"];
1921
+ const metadata = value[optionsKey(model)];
1483
1922
  return typeof metadata === "object" && metadata !== null && !Array.isArray(metadata) ? metadata : void 0;
1484
1923
  }
1485
1924
  function ensureTextBlock(output, id, stream) {
@@ -1577,13 +2016,13 @@ function finishToolInput(output, id, stream) {
1577
2016
  partial: output
1578
2017
  });
1579
2018
  }
1580
- function finalizeToolCall(output, part, stream) {
2019
+ function finalizeToolCall(output, part, model, stream) {
1581
2020
  const existing = output.parts.find((item) => item.type === "toolCall" && item.callID === part.toolCallId);
1582
2021
  const block = existing ?? toolCallFromPart(part);
1583
2022
  block.callID = part.toolCallId;
1584
2023
  block.name = part.toolName;
1585
2024
  block.arguments = typeof part.input === "object" && part.input !== null ? part.input : {};
1586
- const namespace = openAICodexMetadata(part.providerMetadata)?.namespace;
2025
+ const namespace = responsesMetadata(part.providerMetadata, model)?.namespace;
1587
2026
  const thoughtSignature = googleThoughtSignature(part.providerMetadata);
1588
2027
  if (thoughtSignature) block.thoughtSignature = thoughtSignature;
1589
2028
  if (typeof namespace === "string") block.namespace = namespace;
@@ -1617,7 +2056,7 @@ function handlePart(part, output, model, stream, pricing) {
1617
2056
  break;
1618
2057
  }
1619
2058
  case "text-end": {
1620
- const messageId = openAICodexMetadata(part.providerMetadata)?.messageId;
2059
+ const messageId = responsesMetadata(part.providerMetadata, model)?.messageId;
1621
2060
  finishTextBlock(output, part.id, stream, typeof messageId === "string" ? messageId : void 0);
1622
2061
  break;
1623
2062
  }
@@ -1638,7 +2077,7 @@ function handlePart(part, output, model, stream, pricing) {
1638
2077
  break;
1639
2078
  }
1640
2079
  case "reasoning-end": {
1641
- const reasoningItem = openAICodexMetadata(part.providerMetadata)?.reasoningItem;
2080
+ const reasoningItem = responsesMetadata(part.providerMetadata, model)?.reasoningItem;
1642
2081
  const openAISignature = encodeOpenAIReasoningSignature(part.providerMetadata);
1643
2082
  finishThinkingBlock(output, part.id, stream, typeof reasoningItem === "string" ? reasoningItem : openAISignature);
1644
2083
  break;
@@ -1661,7 +2100,7 @@ function handlePart(part, output, model, stream, pricing) {
1661
2100
  finishToolInput(output, part.id, stream);
1662
2101
  break;
1663
2102
  case "tool-call":
1664
- finalizeToolCall(output, part, stream);
2103
+ finalizeToolCall(output, part, model, stream);
1665
2104
  break;
1666
2105
  case "start-step":
1667
2106
  stampProviderThinkingLevel(output, part.request.body);
@@ -1734,36 +2173,60 @@ const stream$1 = (model, context, options) => {
1734
2173
  try {
1735
2174
  const plan = resolvePlan(model, context, runtimeOptions);
1736
2175
  const languageModel = await resolveAISDKLanguageModel(model, runtimeOptions, plan.budget);
1737
- const tools = convertTools(context.tools, model);
1738
- const messages = convertMessages(context, model);
1739
- const providerOptions = resolveProviderOptions(model, runtimeOptions, plan);
2176
+ const declared = requestTools(context, model, runtimeOptions.method, runtimeOptions.activeTools);
2177
+ const messages = convertMessages(context, model, runtimeOptions.method, runtimeOptions.activeTools);
2178
+ const providerOptions = resolveProviderOptions(model, context, runtimeOptions, plan);
1740
2179
  const pricing = { requestedServiceTier: requestedServiceTier(model, runtimeOptions, providerOptions) };
1741
- const activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);
1742
- let params = compact({
1743
- model: languageModel,
1744
- system: context.systemPrompt,
1745
- messages,
1746
- tools,
1747
- toolChoice: runtimeOptions.toolChoice,
1748
- activeTools,
1749
- maxOutputTokens: resolveMaxOutputTokens(model, plan),
1750
- temperature: model.compat?.supportsTemperature === false ? void 0 : runtimeOptions.temperature,
1751
- providerOptions,
1752
- include: { requestBody: true },
1753
- abortSignal: runtimeOptions.signal,
1754
- timeout: resolveTimeout(runtimeOptions),
1755
- maxRetries: runtimeOptions.maxRetries,
1756
- headers: runtimeOptions.headers,
1757
- onError: () => {}
1758
- });
1759
- const payload = await runtimeOptions.onPayload?.(params, model);
1760
- if (payload !== void 0) params = payload;
1761
- const result = streamText(params);
2180
+ const buildParams = async (preferNonStrict) => {
2181
+ const tools = convertTools(declared.tools, model, runtimeOptions.method, declared.deferred, preferNonStrict);
2182
+ const sentPreferStrict = declared.tools?.some((tool) => tool.constrainedSampling && tool.constrainedSampling.type === "json_schema" && tool.constrainedSampling.strict === "prefer" && tools?.[tool.name]?.strict === true) ?? false;
2183
+ const activeTools = runtimeOptions.activeTools?.filter((name) => !tools || name in tools);
2184
+ let params = compact({
2185
+ model: languageModel,
2186
+ system: isOwnResponses(model, runtimeOptions.method) ? void 0 : leadingSystemPrompt(context, model, runtimeOptions.method),
2187
+ messages,
2188
+ allowSystemInMessages: messages.some((message) => message.role === "system") || void 0,
2189
+ tools,
2190
+ toolChoice: runtimeOptions.toolChoice,
2191
+ activeTools,
2192
+ maxOutputTokens: resolveMaxOutputTokens(model, plan),
2193
+ temperature: model.compat?.supportsTemperature === false ? void 0 : runtimeOptions.temperature,
2194
+ providerOptions,
2195
+ include: { requestBody: true },
2196
+ abortSignal: runtimeOptions.signal,
2197
+ timeout: resolveTimeout(runtimeOptions),
2198
+ maxRetries: runtimeOptions.maxRetries,
2199
+ headers: runtimeOptions.headers,
2200
+ onError: () => {}
2201
+ });
2202
+ const payload = await runtimeOptions.onPayload?.(params, model);
2203
+ if (payload !== void 0) params = payload;
2204
+ return {
2205
+ params,
2206
+ sentPreferStrict
2207
+ };
2208
+ };
2209
+ let preferNonStrict = false;
2210
+ let built = await buildParams(preferNonStrict);
1762
2211
  stream.push({
1763
2212
  type: "start",
1764
2213
  partial: output
1765
2214
  });
1766
- for await (const part of result.fullStream) handlePart(part, output, model, stream, pricing);
2215
+ for (;;) try {
2216
+ for await (const part of streamText(built.params).fullStream) handlePart(part, output, model, stream, pricing);
2217
+ break;
2218
+ } catch (error) {
2219
+ const limitMessage = strictToolLimitMessage(error);
2220
+ if (preferNonStrict || runtimeOptions.signal?.aborted || output.parts.length > 0 || !built.sentPreferStrict || !isAnthropicWire(model, resolveMethod(model, runtimeOptions.method)) || limitMessage === void 0) throw error;
2221
+ (output.diagnostics ??= []).push({
2222
+ type: "strictToolsFallback",
2223
+ timestamp: Date.now(),
2224
+ error: { message: limitMessage },
2225
+ details: { reason: "strictToolLimits" }
2226
+ });
2227
+ preferNonStrict = true;
2228
+ built = await buildParams(preferNonStrict);
2229
+ }
1767
2230
  if (runtimeOptions.signal?.aborted || output.stopReason === "aborted") throw new Error(output.errorMessage || "request was aborted");
1768
2231
  if (output.stopReason === "error") throw new Error(output.errorMessage || "provider returned an error stop reason");
1769
2232
  output.time.completed = Date.now();
@@ -1913,6 +2376,6 @@ function validateToolArguments(tool, toolExecution) {
1913
2376
  return validateSchema(tool.parameters, args, `Tool "${toolExecution.name}"`);
1914
2377
  }
1915
2378
  //#endregion
1916
- export { event_exports as Event, EventStream, failure_exports as Failure, message_exports as Message, model_exports as Model, protocol_exports as Protocol, ThinkingBudgets, Type, createAssistantMessageEventStream, createGitHubCopilot, createOpenAICodex, getEnvApiKey, githubCopilot, llm, normalizeOptionalNulls, openAICodexTools, openaiCodex, stream, validateSchema, validateToolArguments, validateToolCall };
2379
+ export { event_exports as Event, EventStream, failure_exports as Failure, message_exports as Message, model_exports as Model, protocol_exports as Protocol, ThinkingBudgets, transcript_exports as Transcript, Type, createAssistantMessageEventStream, createGitHubCopilot, createOpenAICodex, getEnvApiKey, githubCopilot, llm, normalizeOptionalNulls, openAICodexTools, openaiCodex, stream, validateSchema, validateToolArguments, validateToolCall };
1917
2380
 
1918
2381
  //# sourceMappingURL=index.mjs.map