@openclaw/ai 2026.10.10 → 2026.11.5-beta.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.
Files changed (138) hide show
  1. package/README.md +11 -1
  2. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
  3. package/dist/anthropic-CTND83W3.mjs +182 -0
  4. package/dist/{anthropic-payload-policy-rqCq9sT_.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
  5. package/dist/{anthropic-stream-reducer-C__ByTq1.mjs → anthropic-stream-lifecycle-rJe4OH5H.mjs} +845 -649
  6. package/dist/{anthropic-tool-projection-JTvMo4KG.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
  7. package/dist/{anthropic-tool-projection-DA_KeluM.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
  8. package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
  9. package/dist/assistant-output-CD4kY9gu.mjs +16 -0
  10. package/dist/{azure-openai-responses-DHzTwi-y.mjs → azure-openai-responses-BhoLtP4Z.mjs} +46 -52
  11. package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
  12. package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
  13. package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
  14. package/dist/{diagnostics-Cv7cW3pS.mjs → diagnostics-CloVGQiK.mjs} +42 -19
  15. package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
  16. package/dist/diagnostics.d.mts +6 -7
  17. package/dist/diagnostics.mjs +4 -4
  18. package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
  19. package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
  20. package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
  21. package/dist/event-stream.d.mts +2 -2
  22. package/dist/event-stream.mjs +1 -2
  23. package/dist/expect-lbe3Hgrh.mjs +8 -0
  24. package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
  25. package/dist/{google-CZ6uGVkV.mjs → google-1uObh-eI.mjs} +7 -8
  26. package/dist/{google-interactions-qd4flmND.mjs → google-interactions-CY8Xb87S.mjs} +208 -233
  27. package/dist/{google-messages-B-svbJuN.mjs → google-messages-CwBqSoa4.mjs} +16 -13
  28. package/dist/{google-provider-stream-DlhaCvCf.mjs → google-provider-stream-D30s9EZp.mjs} +17 -10
  29. package/dist/{google-shared-Cif7nve-.mjs → google-shared-li0lmEZK.mjs} +70 -42
  30. package/dist/{google-vertex-BZTcYnWU.mjs → google-vertex-B5CHglca.mjs} +3 -3
  31. package/dist/{host-rCxf5Tjd.mjs → host-DX7ORpeH.mjs} +57 -46
  32. package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
  33. package/dist/{host-policy-Ci1cKluf.mjs → host-policy-jCZebuXx.mjs} +2 -2
  34. package/dist/index-Bczt0MnO.d.mts +17 -0
  35. package/dist/index.d.mts +8 -7
  36. package/dist/index.mjs +9 -7
  37. package/dist/internal/anthropic.d.mts +21 -26
  38. package/dist/internal/anthropic.mjs +6 -6
  39. package/dist/internal/google-model-family.mjs +1 -1
  40. package/dist/internal/google.d.mts +15 -0
  41. package/dist/internal/google.mjs +1 -0
  42. package/dist/internal/model-request-body.d.mts +37 -0
  43. package/dist/internal/model-request-body.mjs +106 -0
  44. package/dist/internal/openai-completions-compat.d.mts +5 -1
  45. package/dist/internal/openai-completions-compat.mjs +3 -2
  46. package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
  47. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  48. package/dist/internal/openai.d.mts +14 -12
  49. package/dist/internal/openai.mjs +11 -10
  50. package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
  51. package/dist/{reasoning-tag-text-partitioner-DzlRubwU.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -122
  52. package/dist/internal/retry-after.d.mts +2 -2
  53. package/dist/internal/retry-after.mjs +165 -27
  54. package/dist/internal/runtime.d.mts +15 -41
  55. package/dist/internal/runtime.mjs +9 -10
  56. package/dist/internal/shared.d.mts +21 -25
  57. package/dist/internal/shared.mjs +9 -98
  58. package/dist/internal/tool-schema.d.mts +10 -10
  59. package/dist/internal/tool-schema.mjs +4 -4
  60. package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
  61. package/dist/mistral-F5_asrmU.mjs +3741 -0
  62. package/dist/mistral.LICENSE +201 -0
  63. package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
  64. package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
  65. package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
  66. package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
  67. package/dist/{openai-chatgpt-responses-iGYDPbmc.mjs → openai-chatgpt-responses-BIK7HROH.mjs} +61 -80
  68. package/dist/{openai-completions-CDy5u1mv.mjs → openai-completions-ClJ7QHEB.mjs} +5 -5
  69. package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
  70. package/dist/{openai-completions-compat-CJ0OXZgi.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
  71. package/dist/openai-completions-reasoning-replay-BwT1xwRI.mjs +45 -0
  72. package/dist/{openai-completions-transport-DLrm5EWi.mjs → openai-completions-transport-C6J4_oGf.mjs} +501 -563
  73. package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
  74. package/dist/{openai-prompt-cache-h8vXRiaH.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
  75. package/dist/openai-responses-Beifmf1s.mjs +89 -0
  76. package/dist/{openai-responses-compaction-replay-DUBbsfku.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
  77. package/dist/{openai-responses-contracts-gnl6ZRs1.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
  78. package/dist/{openai-responses-contracts-DCG51Us0.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
  79. package/dist/{openai-responses-endpoint-JbBT8IDv.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
  80. package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
  81. package/dist/{openai-responses-request-lifecycle-DuMpdA6y.mjs → openai-responses-request-lifecycle-o-ODC_rF.mjs} +12 -26
  82. package/dist/{openai-responses-shared-CNfHudFg.mjs → openai-responses-shared-CrFDkZ0N.mjs} +637 -389
  83. package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
  84. package/dist/{openai-tool-schema-CGhEl7ao.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
  85. package/dist/otel-D-BkX8bB.mjs +766 -0
  86. package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
  87. package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
  88. package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
  89. package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
  90. package/dist/{provider-options-Bo8GzTGX.d.mts → provider-options-Mo8NM5d1.d.mts} +15 -4
  91. package/dist/{provider-replay-context-BC23HyZo.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
  92. package/dist/provider-transcript-transform-BHq3Q4nc.mjs +32 -0
  93. package/dist/{provider-transport-turn-state-B11rmZpv.mjs → provider-transport-turn-state-DQd9K4Pd.mjs} +3 -3
  94. package/dist/{provider-types-ODq57rG_.d.mts → provider-types-B1e98js5.d.mts} +6 -4
  95. package/dist/provider-types.d.mts +7 -6
  96. package/dist/provider-types.mjs +2 -1
  97. package/dist/providers.d.mts +2 -2
  98. package/dist/providers.mjs +26 -29
  99. package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
  100. package/dist/request-headers-DO4Mqhw1.mjs +10 -0
  101. package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
  102. package/dist/retry-after-DnHBlFS2.d.mts +45 -0
  103. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  104. package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
  105. package/dist/{simple-options-BdJJbzZk.mjs → simple-options-tLSeECry.mjs} +108 -82
  106. package/dist/src-BUsVkrNt.mjs +105 -0
  107. package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
  108. package/dist/stable-stringify-CchQEmeA.mjs +84 -0
  109. package/dist/{stream-DQqGjhbq.mjs → stream-DrtAWu7c.mjs} +2 -6
  110. package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
  111. package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
  112. package/dist/string-normalization-B8TDDBX_.mjs +32 -0
  113. package/dist/telemetry-B9f7K_Xe.mjs +582 -0
  114. package/dist/{tool-schema-json-projection-Cvq69Ajp.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
  115. package/dist/{transport-stream-shared-DdnJGEj0.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
  116. package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
  117. package/dist/{transport-utils-CcCAuFVS.mjs → transport-utils-Da_39MYi.mjs} +23 -38
  118. package/dist/transports.d.mts +39 -38
  119. package/dist/transports.mjs +214 -295
  120. package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
  121. package/dist/types-Cb3-5WM9.d.mts +1 -0
  122. package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
  123. package/dist/types.d.mts +7 -6
  124. package/dist/types.mjs +7 -5
  125. package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
  126. package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
  127. package/dist/validation.d.mts +1 -1
  128. package/dist/validation.mjs +1 -2
  129. package/package.json +40 -6
  130. package/dist/anthropic-B54Ts1tV.mjs +0 -221
  131. package/dist/assistant-output-DbgdWAhJ.mjs +0 -47
  132. package/dist/event-stream-CDpFza-M.d.mts +0 -1
  133. package/dist/index-DSprYWaz.d.mts +0 -185
  134. package/dist/mistral-C_ImzxlK.mjs +0 -512
  135. package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
  136. package/dist/openai-responses-Cp2QPq7K.mjs +0 -87
  137. package/dist/retry-after-sw-XX8aC.d.mts +0 -15
  138. package/dist/types-CBJthzJX.d.mts +0 -1
@@ -1,512 +0,0 @@
1
- import { r as appendAssistantThinking, t as AssistantMessageEventStream } from "./event-stream-X2gmsUWv.mjs";
2
- import { N as isImageWithMediaPayload, O as calculateCost, k as clampThinkingLevel, r as getAiTransportHost } from "./host-rCxf5Tjd.mjs";
3
- import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
4
- import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-D_MeCQFI.mjs";
5
- import { f as extractToolResultText, l as describeToolResultMediaPlaceholder, n as buildBaseOptions, p as formatToolResultText, r as clampMaxTokensToModel, w as stripSystemPromptCacheBoundary } from "./simple-options-BdJJbzZk.mjs";
6
- import { A as shortHash, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, l as finalizeTerminalToolCallArguments, m as notifyProviderHttpResponse, n as assignTransportErrorDetails, u as finalizeTransportStream } from "./transport-stream-shared-DdnJGEj0.mjs";
7
- import { n as transformProviderMessages, t as createAssistantOutput } from "./assistant-output-DbgdWAhJ.mjs";
8
- import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
9
- import { t as boundResponseBody } from "./streaming-byte-guard-DBXr1XYn.mjs";
10
- import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
11
- import { t as requireApiKey } from "./required-api-key-D088S4Cd.mjs";
12
- import { randomUUID } from "node:crypto";
13
- import { HTTPClient } from "@mistralai/mistralai/lib/http";
14
- import { ReasoningEffort$inboundSchema } from "@mistralai/mistralai/models/components/reasoningeffort.js";
15
- import { Chat } from "@mistralai/mistralai/sdk/chat";
16
- //#region packages/ai/src/providers/mistral-usage.ts
17
- function readMistralCachedPromptTokens(usage, promptTokens) {
18
- const record = usage;
19
- const rawCachedTokens = record.promptTokensDetails?.cachedTokens ?? record.prompt_tokens_details?.cached_tokens ?? record.cachedTokens ?? record.cached_tokens;
20
- return Math.min(promptTokens, Math.max(0, typeof rawCachedTokens === "number" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0));
21
- }
22
- function applyMistralUsage(output, usage, model, terminal) {
23
- const promptTokens = usage.promptTokens || 0;
24
- const cacheRead = readMistralCachedPromptTokens(usage, promptTokens);
25
- output.input = Math.max(0, promptTokens - cacheRead);
26
- output.output = usage.completionTokens || 0;
27
- output.cacheRead = cacheRead;
28
- output.cacheWrite = 0;
29
- output.totalTokens = usage.totalTokens || output.input + output.output + cacheRead;
30
- output.usageReport = { state: terminal ? "available" : "unavailable" };
31
- calculateCost(model, output);
32
- }
33
- //#endregion
34
- //#region packages/ai/src/providers/mistral.ts
35
- const MISTRAL_TOOL_CALL_ID_LENGTH = 9;
36
- const MISTRAL_STREAM_BODY_MAX_BYTES = 16777216;
37
- /** Cap the SDK's response reader while preserving bodyless error responses. */
38
- function createBoundedMistralFetcher(maxBytes = MISTRAL_STREAM_BODY_MAX_BYTES, upstreamFetch = fetch) {
39
- return async (input, init) => {
40
- const response = init == null ? await upstreamFetch(input) : await upstreamFetch(input, init);
41
- return boundResponseBody(response, {
42
- maxBytes,
43
- onOverflow: ({ size, maxBytes: cap }) => /* @__PURE__ */ new Error(`mistral: stream body exceeds ${cap} bytes (got ${size})`)
44
- });
45
- };
46
- }
47
- const streamMistral = (model, context, options) => {
48
- const stream = new AssistantMessageEventStream();
49
- (async () => {
50
- const output = createAssistantOutput(model);
51
- try {
52
- const apiKey = requireApiKey(model.provider, options?.apiKey);
53
- const boundedFetcher = createBoundedMistralFetcher(MISTRAL_STREAM_BODY_MAX_BYTES, getAiTransportHost().buildModelFetch(model) ?? fetch);
54
- let mistralResponse;
55
- let reportedResponse;
56
- const httpClient = new HTTPClient({ fetcher: boundedFetcher });
57
- httpClient.addHook("response", async (response) => {
58
- mistralResponse = response;
59
- if (!response.ok) {
60
- await notifyProviderHttpResponse({
61
- options,
62
- response,
63
- model
64
- });
65
- reportedResponse = response;
66
- }
67
- });
68
- const chat = new Chat({
69
- apiKey,
70
- serverURL: model.baseUrl,
71
- httpClient,
72
- retryConfig: { strategy: "none" }
73
- });
74
- const normalizeMistralToolCallId = createMistralToolCallIdNormalizer();
75
- let payload = buildChatPayload(model, context, transformProviderMessages(context.messages, model, normalizeMistralToolCallId), options);
76
- const nextPayload = await options?.onPayload?.(payload, model);
77
- if (nextPayload !== void 0) payload = nextPayload;
78
- const headers = {
79
- ...model.headers,
80
- ...options?.headers
81
- };
82
- if (resolveMistralPromptCacheKey(options) && options?.sessionId) headers["x-affinity"] ||= options.sessionId;
83
- const mistralStream = await chat.stream(payload, {
84
- headers,
85
- signal: options?.signal
86
- });
87
- if (mistralResponse && mistralResponse !== reportedResponse) await notifyProviderHttpResponse({
88
- options,
89
- response: mistralResponse,
90
- model,
91
- cancelStream: (reason) => mistralStream.cancel(reason)
92
- });
93
- stream.push({
94
- type: "start",
95
- partial: output
96
- });
97
- await consumeChatStream(model, output, stream, mistralStream, options?.signal);
98
- finalizeTransportStream({
99
- stream,
100
- output,
101
- signal: options?.signal
102
- });
103
- } catch (error) {
104
- const terminal = assignTransportErrorDetails(output, error, options?.signal);
105
- output.content = output.content.filter((block) => block.type !== "toolCall");
106
- stream.push({
107
- type: "error",
108
- reason: terminal.stopReason,
109
- error: output
110
- });
111
- stream.end();
112
- }
113
- })();
114
- return stream;
115
- };
116
- const streamSimpleMistral = (model, context, options) => {
117
- const apiKey = requireApiKey(model.provider, options?.apiKey);
118
- const base = {
119
- ...buildBaseOptions(model, options, apiKey),
120
- maxTokens: clampMaxTokensToModel(model, options?.maxTokens)
121
- };
122
- const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
123
- const reasoning = clampedReasoning === "off" ? void 0 : clampedReasoning;
124
- const shouldUseReasoning = model.reasoning && reasoning !== void 0;
125
- const supportsReasoningEffort = usesReasoningEffort(model);
126
- return streamMistral(model, context, {
127
- ...base,
128
- promptMode: shouldUseReasoning && !supportsReasoningEffort ? "reasoning" : void 0,
129
- reasoningEffort: shouldUseReasoning && supportsReasoningEffort ? ReasoningEffort$inboundSchema.parse(model.thinkingLevelMap?.[reasoning] ?? (reasoning === "minimal" ? "none" : "high")) : void 0
130
- });
131
- };
132
- function createMistralToolCallIdNormalizer() {
133
- const idMap = /* @__PURE__ */ new Map();
134
- const reverseMap = /* @__PURE__ */ new Map();
135
- return (id) => {
136
- const existing = idMap.get(id);
137
- if (existing) return existing;
138
- let attempt = 0;
139
- while (true) {
140
- const candidate = deriveMistralToolCallId(id, attempt);
141
- const owner = reverseMap.get(candidate);
142
- if (!owner || owner === id) {
143
- idMap.set(id, candidate);
144
- reverseMap.set(candidate, id);
145
- return candidate;
146
- }
147
- attempt++;
148
- }
149
- };
150
- }
151
- function deriveMistralToolCallId(id, attempt) {
152
- const normalized = id.replace(/[^a-zA-Z0-9]/g, "");
153
- if (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) return normalized;
154
- const seedBase = normalized || id;
155
- const seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;
156
- return shortHash(seed).replace(/[^a-zA-Z0-9]/g, "").padEnd(MISTRAL_TOOL_CALL_ID_LENGTH, "0").slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);
157
- }
158
- function buildChatPayload(model, context, messages, options) {
159
- const payload = {
160
- model: model.id,
161
- stream: true,
162
- messages: toChatMessages(messages, model.input.includes("image"))
163
- };
164
- let convertedToolNames;
165
- if (context.tools?.length) {
166
- const tools = toFunctionTools(context.tools);
167
- convertedToolNames = new Set(tools.map((tool) => tool.function.name));
168
- if (tools.length > 0) payload.tools = tools;
169
- }
170
- if (options?.temperature !== void 0) payload.temperature = options.temperature;
171
- if (options?.maxTokens !== void 0) payload.maxTokens = options.maxTokens;
172
- if (options?.stop !== void 0 && options.stop.length > 0) payload.stop = options.stop;
173
- if (options?.toolChoice) {
174
- const toolChoice = mapToolChoice(options.toolChoice, convertedToolNames);
175
- if (toolChoice) payload.toolChoice = toolChoice;
176
- }
177
- if (options?.promptMode) payload.promptMode = options.promptMode;
178
- if (options?.reasoningEffort) payload.reasoningEffort = options.reasoningEffort;
179
- const promptCacheKey = resolveMistralPromptCacheKey(options);
180
- if (promptCacheKey) payload.promptCacheKey = promptCacheKey;
181
- if (context.systemPrompt) payload.messages.unshift({
182
- role: "system",
183
- content: sanitizeSurrogates(stripSystemPromptCacheBoundary(context.systemPrompt))
184
- });
185
- return payload;
186
- }
187
- function resolveMistralPromptCacheKey(options) {
188
- if (options?.cacheRetention === "none") return;
189
- return options?.promptCacheKey?.trim() || options?.sessionId?.trim() || void 0;
190
- }
191
- async function consumeChatStream(model, output, stream, mistralStream, signal) {
192
- let currentBlock = null;
193
- let terminalFinishReason;
194
- const blocks = output.content;
195
- const blockIndex = () => blocks.length - 1;
196
- const toolBlocks = [];
197
- const normalizeMissingToolCallId = createMistralToolCallIdNormalizer();
198
- const missingToolCallIdScope = randomUUID();
199
- const createMissingToolCallId = (contentIndex) => normalizeMissingToolCallId(`${missingToolCallIdScope}:toolcall:${contentIndex}`);
200
- const requireSingleCandidate = (candidates) => {
201
- if (candidates.length > 1) throw new Error("Mistral streamed tool-call continuation is ambiguous; refusing to merge arguments");
202
- return candidates[0];
203
- };
204
- const resolveToolBlock = (params) => {
205
- const explicitId = params.explicitId;
206
- const functionName = params.functionName;
207
- const toolCallIndex = params.index;
208
- const available = toolBlocks.filter((identity) => !params.usedContentIndexes.has(identity.contentIndex));
209
- const idCandidates = explicitId ? available.filter((identity) => identity.explicitIds.has(explicitId)) : [];
210
- const nameCandidates = functionName ? available.filter((identity) => identity.functionNames.has(functionName)) : [];
211
- if (idCandidates.length > 0) {
212
- let candidates = idCandidates;
213
- if (nameCandidates.length > 0) candidates = candidates.filter((identity) => nameCandidates.includes(identity));
214
- const candidate = requireSingleCandidate(candidates);
215
- if (!candidate) throw new Error("Mistral streamed tool-call identities conflict; refusing to merge arguments");
216
- return candidate;
217
- }
218
- if (nameCandidates.length > 0) {
219
- const idCompatibleCandidates = nameCandidates.filter((identity) => !explicitId || identity.explicitIds.size === 0);
220
- if (idCompatibleCandidates.length <= 1 && (toolCallIndex === void 0 || toolCallIndex === 0)) return requireSingleCandidate(idCompatibleCandidates);
221
- const indexCompatibleCandidates = idCompatibleCandidates.filter((identity) => toolCallIndex === void 0 || identity.indexes.size === 0 || identity.indexes.has(toolCallIndex));
222
- return requireSingleCandidate(indexCompatibleCandidates);
223
- }
224
- const indexCandidates = toolCallIndex === void 0 ? [] : available.filter((identity) => identity.indexes.has(toolCallIndex));
225
- return requireSingleCandidate(indexCandidates.filter((identity) => (!functionName || identity.functionNames.size === 0) && (!explicitId || identity.explicitIds.size === 0)));
226
- };
227
- const finishCurrentBlock = () => {
228
- if (!currentBlock) return;
229
- stream.push({
230
- type: currentBlock.type === "text" ? "text_end" : "thinking_end",
231
- contentIndex: blockIndex(),
232
- content: currentBlock.type === "text" ? currentBlock.text : currentBlock.thinking,
233
- partial: output
234
- });
235
- };
236
- const appendContentDelta = (type, text) => {
237
- const delta = sanitizeSurrogates(text);
238
- if (type === "thinking" && !delta) return;
239
- if (!currentBlock || currentBlock.type !== type) {
240
- finishCurrentBlock();
241
- currentBlock = type === "text" ? {
242
- type,
243
- text: ""
244
- } : {
245
- type,
246
- thinking: ""
247
- };
248
- output.content.push(currentBlock);
249
- stream.push({
250
- type: `${type}_start`,
251
- contentIndex: blockIndex(),
252
- partial: output
253
- });
254
- }
255
- if (currentBlock.type === "text") currentBlock.text += delta;
256
- else appendAssistantThinking(currentBlock, delta);
257
- stream.push({
258
- type: `${type}_delta`,
259
- contentIndex: blockIndex(),
260
- delta,
261
- partial: output
262
- });
263
- };
264
- for await (const event of mistralStream) {
265
- notifyLlmRequestActivity(signal);
266
- const chunk = event.data;
267
- output.responseId ||= chunk.id;
268
- if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
269
- if (chunk.usage) applyMistralUsage(output.usage, chunk.usage, model, Boolean(terminalFinishReason || chunk.choices[0]?.finishReason));
270
- const choice = chunk.choices[0];
271
- if (!choice) continue;
272
- if (choice.finishReason) {
273
- terminalFinishReason = choice.finishReason;
274
- const { stopReason, errorMessage } = mapOpenAIStopReason(choice.finishReason === "model_length" ? "length" : choice.finishReason);
275
- output.stopReason = stopReason;
276
- if (errorMessage) output.errorMessage = errorMessage;
277
- }
278
- const delta = choice.delta;
279
- if (delta.content !== null && delta.content !== void 0) {
280
- const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content;
281
- for (const item of contentItems) {
282
- if (typeof item === "string") {
283
- appendContentDelta("text", item);
284
- continue;
285
- }
286
- if (item.type === "thinking") appendContentDelta("thinking", item.thinking.map((part) => "text" in part ? part.text : "").join(""));
287
- else if (item.type === "text") appendContentDelta("text", item.text);
288
- }
289
- }
290
- const toolCalls = delta.toolCalls || [];
291
- const usedToolBlockIndexes = /* @__PURE__ */ new Set();
292
- for (const toolCall of toolCalls) {
293
- if (currentBlock) {
294
- finishCurrentBlock();
295
- currentBlock = null;
296
- }
297
- const toolCallIndex = typeof toolCall.index === "number" && Number.isInteger(toolCall.index) ? toolCall.index : void 0;
298
- const providedCallId = toolCall.id && toolCall.id !== "null" ? toolCall.id : void 0;
299
- const functionName = toolCall.function.name.trim() || void 0;
300
- let identity = resolveToolBlock({
301
- explicitId: providedCallId,
302
- functionName,
303
- index: toolCallIndex,
304
- usedContentIndexes: usedToolBlockIndexes
305
- });
306
- if (!identity) {
307
- const contentIndex = output.content.length;
308
- const block = {
309
- type: "toolCall",
310
- id: providedCallId ?? createMissingToolCallId(contentIndex),
311
- name: functionName ?? "",
312
- arguments: {},
313
- partialJson: ""
314
- };
315
- output.content.push(block);
316
- identity = {
317
- block,
318
- contentIndex,
319
- preview: createToolArgumentPreviewSchedule(),
320
- explicitIds: /* @__PURE__ */ new Set(),
321
- functionNames: /* @__PURE__ */ new Set(),
322
- indexes: /* @__PURE__ */ new Set()
323
- };
324
- toolBlocks.push(identity);
325
- stream.push({
326
- type: "toolcall_start",
327
- contentIndex,
328
- partial: output
329
- });
330
- }
331
- const { block, contentIndex } = identity;
332
- usedToolBlockIndexes.add(contentIndex);
333
- if (providedCallId) {
334
- block.id = providedCallId;
335
- identity.explicitIds.add(providedCallId);
336
- }
337
- if (functionName) {
338
- if (identity.functionNames.size > 0 && !identity.functionNames.has(functionName)) throw new Error("Mistral streamed tool-call continuation changed function name; refusing to merge arguments");
339
- block.name = functionName;
340
- identity.functionNames.add(functionName);
341
- }
342
- if (toolCallIndex !== void 0) identity.indexes.add(toolCallIndex);
343
- const argsDelta = typeof toolCall.function.arguments === "string" ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments || {});
344
- block.partialJson = (block.partialJson || "") + argsDelta;
345
- if (identity.preview(block.partialJson.length)) block.arguments = parseStreamingJson(block.partialJson);
346
- stream.push({
347
- type: "toolcall_delta",
348
- contentIndex,
349
- delta: argsDelta,
350
- partial: output
351
- });
352
- }
353
- }
354
- finishCurrentBlock();
355
- if (!terminalFinishReason || output.stopReason !== "toolUse") {
356
- blocks.splice(0, blocks.length, ...blocks.filter((block) => block.type !== "toolCall"));
357
- if (!terminalFinishReason) throw new Error("Mistral stream ended without a terminal finish reason");
358
- return;
359
- }
360
- finalizeTerminalToolCallArguments(toolBlocks.map(({ block }) => block), (block) => block.partialJson ?? "", "Mistral completed tool call has invalid JSON arguments");
361
- for (const { block, contentIndex } of toolBlocks) {
362
- delete block.partialJson;
363
- stream.push({
364
- type: "toolcall_end",
365
- contentIndex,
366
- toolCall: block,
367
- partial: output
368
- });
369
- }
370
- }
371
- function toFunctionTools(tools) {
372
- const converted = tools.flatMap((tool) => {
373
- try {
374
- const name = tool.name;
375
- const description = tool.description;
376
- return {
377
- name,
378
- description,
379
- value: {
380
- type: "function",
381
- function: {
382
- name,
383
- description,
384
- parameters: structuredClone(tool.parameters),
385
- strict: false
386
- }
387
- }
388
- };
389
- } catch {
390
- return [];
391
- }
392
- });
393
- return sortPromptCacheToolsByName(converted).map(({ value }) => value);
394
- }
395
- function toChatMessages(messages, supportsImages) {
396
- const result = [];
397
- for (const msg of messages) {
398
- if (msg.role === "user") {
399
- if (typeof msg.content === "string") {
400
- result.push({
401
- role: "user",
402
- content: sanitizeSurrogates(msg.content)
403
- });
404
- continue;
405
- }
406
- const hadImages = msg.content.some((item) => item.type === "image");
407
- const content = msg.content.filter((item) => item.type === "text" || supportsImages).map((item) => {
408
- if (item.type === "text") return {
409
- type: "text",
410
- text: sanitizeSurrogates(item.text)
411
- };
412
- return {
413
- type: "image_url",
414
- imageUrl: `data:${item.mimeType};base64,${item.data}`
415
- };
416
- });
417
- if (content.length > 0) {
418
- result.push({
419
- role: "user",
420
- content
421
- });
422
- continue;
423
- }
424
- if (hadImages && !supportsImages) result.push({
425
- role: "user",
426
- content: "(image omitted: model does not support images)"
427
- });
428
- continue;
429
- }
430
- if (msg.role === "assistant") {
431
- const contentParts = [];
432
- const toolCalls = [];
433
- for (const block of msg.content) {
434
- if (block.type === "text" || block.type === "thinking") {
435
- const text = block.type === "text" ? block.text : block.thinking;
436
- if (text.trim().length > 0) {
437
- const part = {
438
- type: "text",
439
- text: sanitizeSurrogates(text)
440
- };
441
- contentParts.push(block.type === "text" ? part : {
442
- type: "thinking",
443
- thinking: [part]
444
- });
445
- }
446
- continue;
447
- }
448
- toolCalls.push({
449
- id: block.id,
450
- type: "function",
451
- function: {
452
- name: block.name,
453
- arguments: JSON.stringify(block.arguments || {})
454
- }
455
- });
456
- }
457
- const assistantMessage = { role: "assistant" };
458
- if (contentParts.length > 0) assistantMessage.content = contentParts;
459
- if (toolCalls.length > 0) assistantMessage.toolCalls = toolCalls;
460
- if (contentParts.length > 0 || toolCalls.length > 0) result.push(assistantMessage);
461
- continue;
462
- }
463
- const toolContent = [];
464
- const textResult = extractToolResultText(msg.content);
465
- const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
466
- const omittedMediaPlaceholder = msg.content.some(isImageWithMediaPayload) && !supportsImages ? textResult.trim() ? "[tool image omitted: model does not support images]" : mediaPlaceholder === "(see attached media)" ? "(media omitted: model does not support images)" : "(image omitted: model does not support images)" : void 0;
467
- const toolText = formatToolResultText({
468
- text: textResult,
469
- mediaPlaceholder,
470
- omittedMediaPlaceholder,
471
- isError: msg.isError
472
- });
473
- toolContent.push({
474
- type: "text",
475
- text: toolText
476
- });
477
- for (const part of msg.content) {
478
- if (!supportsImages) continue;
479
- if (!isImageWithMediaPayload(part)) continue;
480
- toolContent.push({
481
- type: "image_url",
482
- imageUrl: `data:${part.mimeType};base64,${part.data}`
483
- });
484
- }
485
- result.push({
486
- role: "tool",
487
- toolCallId: msg.toolCallId,
488
- name: msg.toolName,
489
- content: toolContent
490
- });
491
- }
492
- return result;
493
- }
494
- function usesReasoningEffort(model) {
495
- return model.id === "mistral-small-2603" || model.id === "mistral-small-latest" || model.id === "mistral-medium-3-5";
496
- }
497
- function mapToolChoice(choice, convertedToolNames) {
498
- if (!choice) return;
499
- if (convertedToolNames && convertedToolNames.size === 0) {
500
- if (choice === "none" || choice === "auto") return choice === "none" ? "none" : void 0;
501
- throw new Error("Mistral tool_choice requires a tool, but no tools survived schema conversion");
502
- }
503
- if (choice === "auto" || choice === "none" || choice === "any" || choice === "required") return choice;
504
- const toolName = choice.function.name;
505
- if (convertedToolNames && !convertedToolNames.has(toolName)) throw new Error(`Mistral tool_choice requested unavailable tool "${toolName}" after schema conversion`);
506
- return {
507
- type: "function",
508
- function: { name: toolName }
509
- };
510
- }
511
- //#endregion
512
- export { createBoundedMistralFetcher, streamMistral, streamSimpleMistral };
@@ -1,17 +0,0 @@
1
- //#region packages/ai/src/transports/model-request-body.d.ts
2
- type EncodedModelRequestBody = {
3
- body: Uint8Array<ArrayBuffer>;
4
- stream: boolean;
5
- };
6
- type ModelRequestBodyState = {
7
- enabled?: boolean;
8
- encode?: (payload: unknown) => Promise<EncodedModelRequestBody>;
9
- onEncoded?: (body: Blob, payload: unknown) => void;
10
- onBytes?: (bytes: number) => void;
11
- };
12
- /** Call-local state survives option spreads; no payload is cached across requests. */
13
- declare function modelRequestBodyState(options: object, inheritFrom?: object): ModelRequestBodyState;
14
- declare function serializeModelRequestBody(payload: unknown, onSerializedPayload?: (payload: unknown) => void): EncodedModelRequestBody;
15
- declare function encodedModelRequestBodyStream(body: unknown): boolean | undefined;
16
- //#endregion
17
- export { modelRequestBodyState as n, serializeModelRequestBody as r, encodedModelRequestBodyStream as t };
@@ -1,87 +0,0 @@
1
- import { n as __exportAll } from "./reasoning-tag-text-partitioner-DzlRubwU.mjs";
2
- import { t as AssistantMessageEventStream } from "./event-stream-X2gmsUWv.mjs";
3
- import { n as clampOpenAIPromptCacheKey, r as resolveOpenAIPromptCacheParams } from "./openai-prompt-cache-h8vXRiaH.mjs";
4
- import { i as resolveOpenAICompletionsCompat } from "./openai-completions-compat-CJ0OXZgi.mjs";
5
- import { i as resolveCacheRetention, r as buildCopilotDynamicHeaders } from "./cloudflare-Dttf8jKq.mjs";
6
- import { n as buildBaseOptions } from "./simple-options-BdJJbzZk.mjs";
7
- import { n as getEnvApiKey } from "./env-api-keys-Xd8dm_aV.mjs";
8
- import { t as createAssistantOutput } from "./assistant-output-DbgdWAhJ.mjs";
9
- import { F as convertProviderResponsesMessages, n as applyResponsesServiceTierPricing, r as runResponsesStreamLifecycle, t as applyCommonResponsesParams, vt as resolveOpenAISimpleReasoningEffort } from "./openai-responses-shared-CNfHudFg.mjs";
10
- import { i as createOpenAIProviderClient, n as resolveProviderSimpleCompletionHeaders } from "./provider-transport-turn-state-B11rmZpv.mjs";
11
- import { t as requireApiKey } from "./required-api-key-D088S4Cd.mjs";
12
- //#region packages/ai/src/providers/openai-responses.ts
13
- var openai_responses_exports = /* @__PURE__ */ __exportAll({
14
- streamOpenAIResponses: () => streamOpenAIResponses,
15
- streamSimpleOpenAIResponses: () => streamSimpleOpenAIResponses
16
- });
17
- const OPENAI_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "opencode"]);
18
- function getCompat(model) {
19
- return {
20
- ...resolveOpenAICompletionsCompat(model),
21
- sendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true
22
- };
23
- }
24
- const streamOpenAIResponses = (model, context, options) => {
25
- const stream = new AssistantMessageEventStream();
26
- const output = createAssistantOutput(model);
27
- runResponsesStreamLifecycle({
28
- stream,
29
- model,
30
- output,
31
- options,
32
- createClient: () => {
33
- return createClient(model, context, options?.apiKey || getEnvApiKey(model.provider) || "", options, resolveCacheRetention(options?.cacheRetention) === "none" ? void 0 : options?.sessionId);
34
- },
35
- buildParams: (_requestModel, replayMode) => buildParams(model, context, options, replayMode),
36
- processStreamOptions: {
37
- serviceTier: options?.serviceTier,
38
- applyServiceTierPricing: (usage, serviceTier) => applyResponsesServiceTierPricing(usage, serviceTier, model)
39
- }
40
- });
41
- return stream;
42
- };
43
- const streamSimpleOpenAIResponses = (model, context, options) => {
44
- const apiKey = requireApiKey(model.provider, options?.apiKey);
45
- const base = buildBaseOptions(model, options, apiKey);
46
- const replayOptions = options;
47
- return streamOpenAIResponses(model, context, {
48
- ...base,
49
- authProfileId: replayOptions?.authProfileId,
50
- reasoningEffort: resolveOpenAISimpleReasoningEffort(model, options?.reasoning),
51
- replayResponsesItemIds: replayOptions?.replayResponsesItemIds
52
- });
53
- };
54
- function createClient(model, context, apiKey, options, sessionId) {
55
- if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
56
- const compat = getCompat(model);
57
- const headers = { ...model.headers };
58
- if (model.provider === "github-copilot") Object.assign(headers, buildCopilotDynamicHeaders(context.messages));
59
- if (sessionId) {
60
- if (compat.sendSessionIdHeader) headers.session_id = sessionId;
61
- headers["x-client-request-id"] = sessionId;
62
- }
63
- return createOpenAIProviderClient(model, apiKey, headers, resolveProviderSimpleCompletionHeaders(model, options), options?.onResponse);
64
- }
65
- function buildParams(model, context, options, replayMode = "checkpoint") {
66
- const messages = convertProviderResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {
67
- replayResponsesItemIds: options?.replayResponsesItemIds ?? false,
68
- sessionId: options?.sessionId,
69
- authProfileId: options?.authProfileId,
70
- replayMode
71
- });
72
- const cacheRetention = resolveCacheRetention(options?.cacheRetention);
73
- const compat = getCompat(model);
74
- const params = {
75
- model: model.id,
76
- input: messages,
77
- stream: true,
78
- prompt_cache_key: cacheRetention === "none" || !compat.supportsPromptCacheKey ? void 0 : clampOpenAIPromptCacheKey(options?.promptCacheKey ?? options?.sessionId),
79
- ...resolveOpenAIPromptCacheParams(model, cacheRetention, compat),
80
- store: false
81
- };
82
- if (options?.serviceTier !== void 0) params.service_tier = options.serviceTier;
83
- applyCommonResponsesParams(params, model, context, options, { setDefaultReasoningOff: model.provider !== "github-copilot" });
84
- return params;
85
- }
86
- //#endregion
87
- export { streamOpenAIResponses as n, streamSimpleOpenAIResponses as r, openai_responses_exports as t };
@@ -1,15 +0,0 @@
1
- //#region packages/ai/src/internal/retry-after.d.ts
2
- type HttpDateInstant = {
3
- timestampMs: number;
4
- leapSecond: boolean;
5
- };
6
- /** Reads only retry timing metadata, without invoking provider getters or serialization hooks. */
7
- declare function parseRetryAfterHeadersSeconds(headers: unknown, nowMs?: number, status?: number): number | undefined;
8
- /** SDK errors carry native response headers separately from their error body. */
9
- declare function parseRetryAfterErrorSeconds(error: unknown, nowMs?: number): number | undefined;
10
- /** Round leap seconds forward for Retry-After so an unrepresentable instant cannot retry early. */
11
- declare function parseRetryAfterHttpDateMs(value: string, nowMs?: number): number | undefined;
12
- /** Parse all three HTTP-date forms while retaining leap-second ordering. */
13
- declare function parseHttpDateInstant(value: string, nowMs?: number): HttpDateInstant | undefined;
14
- //#endregion
15
- export { parseRetryAfterHttpDateMs as i, parseRetryAfterErrorSeconds as n, parseRetryAfterHeadersSeconds as r, parseHttpDateInstant as t };
@@ -1 +0,0 @@
1
- import "./index-DSprYWaz.mjs";