@openclaw/ai 2026.11.3 → 2026.11.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +11 -8
  2. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
  3. package/dist/anthropic-DEKgalVg.mjs +182 -0
  4. package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
  5. package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
  6. package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
  7. package/dist/{anthropic-tool-projection-DZOKfAmL.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-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
  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-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
  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-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
  26. package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
  27. package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
  28. package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
  29. package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
  30. package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
  31. package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
  32. package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
  33. package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
  34. package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
  35. package/dist/index-Bczt0MnO.d.mts +17 -0
  36. package/dist/index.d.mts +8 -7
  37. package/dist/index.mjs +9 -7
  38. package/dist/internal/anthropic.d.mts +21 -26
  39. package/dist/internal/anthropic.mjs +6 -6
  40. package/dist/internal/google-model-family.mjs +1 -1
  41. package/dist/internal/google.d.mts +15 -0
  42. package/dist/internal/google.mjs +1 -0
  43. package/dist/internal/model-request-body.d.mts +37 -0
  44. package/dist/internal/model-request-body.mjs +106 -0
  45. package/dist/internal/openai-completions-compat.d.mts +1 -1
  46. package/dist/internal/openai-completions-compat.mjs +1 -1
  47. package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
  48. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  49. package/dist/internal/openai.d.mts +14 -12
  50. package/dist/internal/openai.mjs +11 -10
  51. package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
  52. package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
  53. package/dist/internal/retry-after.d.mts +2 -2
  54. package/dist/internal/retry-after.mjs +96 -32
  55. package/dist/internal/runtime.d.mts +15 -41
  56. package/dist/internal/runtime.mjs +9 -10
  57. package/dist/internal/shared.d.mts +21 -25
  58. package/dist/internal/shared.mjs +9 -98
  59. package/dist/internal/tool-schema.d.mts +10 -10
  60. package/dist/internal/tool-schema.mjs +4 -4
  61. package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
  62. package/dist/mistral-CjHkvsqR.mjs +3741 -0
  63. package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
  64. package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
  65. package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
  66. package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
  67. package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
  68. package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
  69. package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
  70. package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
  71. package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
  72. package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
  73. package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
  74. package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
  75. package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
  76. package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
  77. package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
  78. package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
  79. package/dist/openai-responses-ev_c6oTy.mjs +89 -0
  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-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
  82. package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
  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-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
  85. package/dist/otel-Buswj0Mf.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-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
  91. package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
  92. package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
  93. package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
  94. package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
  95. package/dist/provider-types.d.mts +7 -6
  96. package/dist/providers.d.mts +2 -2
  97. package/dist/providers.mjs +26 -29
  98. package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
  99. package/dist/request-headers-DO4Mqhw1.mjs +10 -0
  100. package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
  101. package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
  102. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  103. package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
  104. package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
  105. package/dist/src-BUsVkrNt.mjs +105 -0
  106. package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
  107. package/dist/stable-stringify-CchQEmeA.mjs +84 -0
  108. package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
  109. package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
  110. package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
  111. package/dist/string-normalization-B8TDDBX_.mjs +32 -0
  112. package/dist/telemetry-CvK1yQg7.mjs +582 -0
  113. package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
  114. package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
  115. package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
  116. package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
  117. package/dist/transports.d.mts +42 -39
  118. package/dist/transports.mjs +215 -296
  119. package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
  120. package/dist/types-Cb3-5WM9.d.mts +1 -0
  121. package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
  122. package/dist/types.d.mts +7 -6
  123. package/dist/types.mjs +7 -5
  124. package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
  125. package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
  126. package/dist/validation.d.mts +1 -1
  127. package/dist/validation.mjs +1 -2
  128. package/package.json +40 -6
  129. package/dist/anthropic-lueA8LUg.mjs +0 -221
  130. package/dist/assistant-output-BnQm3fov.mjs +0 -47
  131. package/dist/event-stream-CDpFza-M.d.mts +0 -1
  132. package/dist/index-DSprYWaz.d.mts +0 -185
  133. package/dist/mistral-CQ7aoWg2.mjs +0 -512
  134. package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
  135. package/dist/openai-CiRi-nVE.mjs +0 -20077
  136. package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
  137. package/dist/openai-responses-DQsZKUoI.mjs +0 -87
  138. package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
  139. package/dist/types-CBJthzJX.d.mts +0 -1
  140. package/dist/ws.LICENSE +0 -20
@@ -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-CWt55nnF.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-xJkqrG_E.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-lhgkTOz3.mjs";
7
- import { n as transformProviderMessages, t as createAssistantOutput } from "./assistant-output-BnQm3fov.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 };