@openclaw/ai 2026.10.1 → 2026.10.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 (106) hide show
  1. package/README.md +6 -0
  2. package/dist/{anthropic-BDfXKgF1.mjs → anthropic-BAHKgWam.mjs} +30 -59
  3. package/dist/{anthropic-payload-policy-BZUAchqb.d.mts → anthropic-payload-policy-DGblkHL5.d.mts} +19 -16
  4. package/dist/{anthropic-stream-reducer-DHt9uFWX.mjs → anthropic-stream-reducer-g6w1YVii.mjs} +195 -283
  5. package/dist/{api-registry-DcEP_o4h.d.mts → api-registry-BhXXYdRA.d.mts} +2 -2
  6. package/dist/assistant-message-events-CHMJgbhs.mjs +18 -0
  7. package/dist/{assistant-output-mJ9cL4Qg.mjs → assistant-output-CUEeSotf.mjs} +2 -2
  8. package/dist/{assistant-text-phase-DAv1BdTm.mjs → assistant-text-phase-BrV8KdFO.mjs} +7 -6
  9. package/dist/{azure-openai-responses-gn9hMf8x.mjs → azure-openai-responses-C7qBuR23.mjs} +8 -9
  10. package/dist/{credential-redaction-BKv49aiv.d.mts → credential-redaction-BHxruEH6.d.mts} +3 -1
  11. package/dist/{diagnostics-Caj-4RBA.mjs → diagnostics-tQasYct1.mjs} +10 -3
  12. package/dist/diagnostics.d.mts +7 -7
  13. package/dist/diagnostics.mjs +3 -3
  14. package/dist/{env-api-keys-CyX4VKGO.mjs → env-api-keys-CrxwdylR.mjs} +24 -35
  15. package/dist/event-stream-6UNs-AhN.d.mts +1 -0
  16. package/dist/{event-stream-DrRM_90c.d.mts → event-stream-BcqWLo_u.d.mts} +1 -1
  17. package/dist/{event-stream-C5AbCAaZ.mjs → event-stream-X2gmsUWv.mjs} +5 -8
  18. package/dist/event-stream.d.mts +2 -2
  19. package/dist/event-stream.mjs +1 -1
  20. package/dist/google-Boz2QcpK.mjs +20 -0
  21. package/dist/{google-interactions-DXu4IYGb.mjs → google-interactions-tjAb1mc5.mjs} +52 -84
  22. package/dist/{google-messages-Bmheetdg.mjs → google-messages-C-RZzloH.mjs} +25 -35
  23. package/dist/google-provider-stream-CMImyxbX.mjs +58 -0
  24. package/dist/{google-shared-DE_ddfsC.mjs → google-shared-OyAtMTZv.mjs} +6 -15
  25. package/dist/google-vertex-hCxTJea7.mjs +40 -0
  26. package/dist/{host-BjIYEjwT.d.mts → host-CTDz7LXD.d.mts} +6 -3
  27. package/dist/{host-JpNulOOs.mjs → host-JWXZWa-c.mjs} +3 -2
  28. package/dist/{host-policy-CC5H0iRZ.mjs → host-policy-q4Azym9F.mjs} +1 -1
  29. package/dist/{index-DJrNQnKw.d.mts → index-BYDvopUB.d.mts} +8 -5
  30. package/dist/index.d.mts +7 -7
  31. package/dist/index.mjs +7 -6
  32. package/dist/internal/anthropic.d.mts +5 -5
  33. package/dist/internal/anthropic.mjs +4 -4
  34. package/dist/internal/openai-completions-compat.d.mts +1 -1
  35. package/dist/internal/openai-completions-compat.mjs +1 -1
  36. package/dist/internal/openai-responses-payload-policy.d.mts +8 -1
  37. package/dist/internal/openai-responses-payload-policy.mjs +3 -3
  38. package/dist/internal/openai.d.mts +9 -9
  39. package/dist/internal/openai.mjs +9 -11
  40. package/dist/internal/runtime.d.mts +31 -13
  41. package/dist/internal/runtime.mjs +10 -13
  42. package/dist/internal/shared.d.mts +5 -5
  43. package/dist/internal/shared.mjs +6 -7
  44. package/dist/internal/tool-schema.mjs +2 -2
  45. package/dist/{llm-request-activity-D8f_oxHj.mjs → llm-request-activity-CfMuh5cC.mjs} +2 -2
  46. package/dist/{mistral-1Bnbneg1.mjs → mistral-DUveP4hF.mjs} +71 -146
  47. package/dist/{model-transport-url-C5f59L3Y.d.mts → model-transport-url-BrsjjdjR.d.mts} +5 -1
  48. package/dist/{number-coercion-V8-BhME4.mjs → number-coercion-C3hztWoY.mjs} +5 -4
  49. package/dist/{openai-chatgpt-responses-CB1JwNFF.mjs → openai-chatgpt-responses-OCwckGhY.mjs} +164 -234
  50. package/dist/{openai-completions-BPadHHKe.mjs → openai-completions-DOltBUe9.mjs} +7 -6
  51. package/dist/{openai-completions-compat-CJ0ktmGy.d.mts → openai-completions-compat-i-nLZxFy.d.mts} +10 -11
  52. package/dist/{openai-completions-compat-D7hWYB0G.mjs → openai-completions-compat-pg1q4uNG.mjs} +10 -6
  53. package/dist/{openai-completions-transport-DITBEALX.mjs → openai-completions-transport-OMrn7gnZ.mjs} +1429 -294
  54. package/dist/{openai-prompt-cache-Dj8qeOHT.mjs → openai-prompt-cache-Cr2xKVrS.mjs} +1 -1
  55. package/dist/{openai-prompt-cache-C-Q1Ksfs.d.mts → openai-prompt-cache-DIPMrMFy.d.mts} +2 -2
  56. package/dist/{openai-responses-1_TvcWI3.mjs → openai-responses-BSBJUA19.mjs} +9 -10
  57. package/dist/{openai-responses-compaction-replay-BB2SWdsx.d.mts → openai-responses-compaction-replay-B2FE4Nw8.d.mts} +4 -4
  58. package/dist/{openai-responses-contracts-sAvdqNjS.d.mts → openai-responses-contracts-DKqMJ1Ct.d.mts} +9 -4
  59. package/dist/{openai-responses-contracts-BKu8O7l4.mjs → openai-responses-contracts-DlKMMTxK.mjs} +26 -6
  60. package/dist/{openai-responses-compaction-window-m878aVpU.mjs → openai-responses-endpoint-CinGh4VZ.mjs} +14 -4
  61. package/dist/{openai-responses-prompt-observer-internal-CbH84xIS.mjs → openai-responses-request-lifecycle-D2IFiI0-.mjs} +39 -4
  62. package/dist/{openai-responses-shared-TCJRAoMW.mjs → openai-responses-shared-DVGhq5xF.mjs} +1036 -327
  63. package/dist/{openai-responses-terminal-usage-BVvyXZ8u.d.mts → openai-responses-terminal-usage-BygjiAdi.d.mts} +2 -2
  64. package/dist/{openai-tool-schema-DYNePiF8.mjs → openai-tool-schema-DDPXsvJP.mjs} +236 -399
  65. package/dist/{positive-integer-CwLi8LUL.mjs → positive-integer-CqWjqSi9.mjs} +1 -1
  66. package/dist/{provider-error-DQBE1bUQ.mjs → provider-error-CF9GWCs2.mjs} +5 -3
  67. package/dist/{provider-options-Dk4PeQV3.d.mts → provider-options-CVrXZBtA.d.mts} +3 -2
  68. package/dist/{provider-transport-turn-state-8c_Nj2NS.mjs → provider-transport-turn-state-LuCaTsSO.mjs} +2 -2
  69. package/dist/{provider-types-De8PRdR0.d.mts → provider-types-CHtRx0dI.d.mts} +3 -3
  70. package/dist/provider-types.d.mts +6 -6
  71. package/dist/providers.d.mts +2 -2
  72. package/dist/providers.mjs +12 -12
  73. package/dist/{reasoning-tag-text-partitioner-Ju9VpUGl.mjs → reasoning-tag-text-partitioner-0-Rsezog.mjs} +13 -12
  74. package/dist/{required-api-key-D4kn3252.mjs → required-api-key-CFJvcFy_.mjs} +1 -1
  75. package/dist/{simple-options-wW3117Fu.mjs → simple-options-BARFAzk9.mjs} +9 -11
  76. package/dist/{src-DWJq14pn.mjs → src-C_wfIUmV.mjs} +19 -4
  77. package/dist/{stream-CElngO8h.mjs → stream-DwrETW0_.mjs} +12 -21
  78. package/dist/{stream-first-event-timeout-D9ZmL_s9.mjs → stream-first-event-timeout-Dc42hKv6.mjs} +8 -21
  79. package/dist/{streaming-byte-guard-CC-HMn_u.mjs → streaming-byte-guard-DBXr1XYn.mjs} +16 -1
  80. package/dist/{string-normalization-PN10hf6d.mjs → string-normalization-I3ux50s9.mjs} +1 -1
  81. package/dist/{text-signature-rOn31nxc.mjs → text-signature-B_MB6U_9.mjs} +32 -5
  82. package/dist/{tool-schema-json-projection-Ct8SeBeJ.mjs → tool-schema-json-projection-B8sG1I9v.mjs} +29 -23
  83. package/dist/{transport-stream-shared-CAxkgOSj.d.mts → transport-stream-shared-BmpzDtdQ.d.mts} +4 -4
  84. package/dist/{transport-stream-shared-C5TAc3U_.mjs → transport-stream-shared-DH08b7Il.mjs} +8 -16
  85. package/dist/transports.d.mts +33 -22
  86. package/dist/transports.mjs +73 -1234
  87. package/dist/{types-DvzmWW8J.d.mts → types-Bd2T86VJ.d.mts} +5 -23
  88. package/dist/types-Kdfw_04V.d.mts +1 -0
  89. package/dist/types.d.mts +6 -6
  90. package/dist/types.mjs +5 -4
  91. package/dist/{validation-B3lQt_VE.d.mts → validation-DdGB1yy3.d.mts} +1 -1
  92. package/dist/{validation-DbqlIfDn.mjs → validation-opC2pjk9.mjs} +2 -3
  93. package/dist/validation.d.mts +1 -1
  94. package/dist/validation.mjs +1 -1
  95. package/package.json +4 -9
  96. package/dist/env-api-keys-BR0MUYYD.d.mts +0 -17
  97. package/dist/event-stream-DqDQWqiy.d.mts +0 -1
  98. package/dist/google-CyMz2jF_.mjs +0 -54
  99. package/dist/google-vertex-BEW0OQIA.mjs +0 -88
  100. package/dist/internal/env-api-keys.d.mts +0 -2
  101. package/dist/internal/env-api-keys.mjs +0 -2
  102. package/dist/openai-responses-request-lifecycle-Fsag-IGZ.mjs +0 -36
  103. package/dist/openai-transport-params-ildrm49s.mjs +0 -735
  104. package/dist/openai-web-search-tools-Cfu0uLyN.mjs +0 -14
  105. package/dist/provider-replay-context-ywPKKLjL.mjs +0 -25
  106. package/dist/types-Dlz-8qcy.d.mts +0 -1
@@ -1,12 +1,11 @@
1
- import "../index-DJrNQnKw.mjs";
2
- import { M as ModelThinkingLevel, Q as SimpleStreamOptions, U as ProviderStreamOptions, a as AssistantMessage, d as Context, k as Model, n as Api, nt as StreamOptions, pt as Usage, s as AssistantMessageEventStreamContract } from "../types-DvzmWW8J.mjs";
3
- import { i as getEventStreamCompletion } from "../event-stream-DrRM_90c.mjs";
4
- import { a as RegisteredApiProvider, t as ApiProvider } from "../api-registry-DcEP_o4h.mjs";
5
- import { m as getDefaultAiTransportHost } from "../host-BjIYEjwT.mjs";
6
- import "../types-Dlz-8qcy.mjs";
7
- import { n as getEnvApiKey, t as findEnvKeys } from "../env-api-keys-BR0MUYYD.mjs";
1
+ import "../index-BYDvopUB.mjs";
2
+ import { M as ModelThinkingLevel, Q as SimpleStreamOptions, U as ProviderStreamOptions, a as AssistantMessage, d as Context, k as Model, n as Api, nt as StreamOptions, pt as Usage, s as AssistantMessageEventStreamContract } from "../types-Bd2T86VJ.mjs";
3
+ import { i as getEventStreamCompletion } from "../event-stream-BcqWLo_u.mjs";
4
+ import { a as RegisteredApiProvider, t as ApiProvider } from "../api-registry-BhXXYdRA.mjs";
5
+ import { m as getDefaultAiTransportHost } from "../host-CTDz7LXD.mjs";
6
+ import "../types-Kdfw_04V.mjs";
8
7
  import { t as sanitizeSurrogates } from "../sanitize-unicode-CjDG6jJx.mjs";
9
- import { v as parseTerminalToolCallArguments } from "../transport-stream-shared-CAxkgOSj.mjs";
8
+ import { v as parseTerminalToolCallArguments } from "../transport-stream-shared-BmpzDtdQ.mjs";
10
9
  //#region packages/ai/src/internal/default-runtime.d.ts
11
10
  export declare const defaultApiRegistry: {
12
11
  registerApiProvider: <TApi extends Api, TOptions extends StreamOptions>(provider: ApiProvider<TApi, TOptions>, sourceId?: string) => void;
@@ -36,7 +35,6 @@ declare const { getApiProvider, getApiProviders }: {
36
35
  unregisterApiProviders: (sourceId: string) => void;
37
36
  clearApiProviders: () => void;
38
37
  };
39
- export declare function clearApiProviders(): void;
40
38
  declare const { stream, complete, streamSimple, completeSimple }: {
41
39
  registry: {
42
40
  registerApiProvider: <TApi extends Api, TOptions extends StreamOptions>(provider: ApiProvider<TApi, TOptions>, sourceId?: string) => void;
@@ -52,6 +50,22 @@ declare const { stream, complete, streamSimple, completeSimple }: {
52
50
  cleanupSessionResources: (sessionId?: string) => void;
53
51
  };
54
52
  //#endregion
53
+ //#region packages/ai/src/env-api-keys.d.ts
54
+ /**
55
+ * Find configured environment variables that can provide an API key for a provider.
56
+ *
57
+ * This only reports actual API key variables. It intentionally excludes ambient
58
+ * credential sources such as AWS profiles, AWS IAM credentials, and Google
59
+ * Application Default Credentials.
60
+ */
61
+ export declare function findEnvKeys(provider: string): string[] | undefined;
62
+ /**
63
+ * Get API key for provider from known environment variables, e.g. OPENAI_API_KEY.
64
+ *
65
+ * Will not return API keys for providers that require OAuth tokens.
66
+ */
67
+ export declare function getEnvApiKey(provider: string): string | undefined;
68
+ //#endregion
55
69
  //#region packages/ai/src/model-utils.d.ts
56
70
  /** Calculates and stores model cost fields from token usage and per-million pricing. */
57
71
  export declare function calculateCost<TApi extends Api>(model: Model<TApi>, usage: Usage): Usage["cost"];
@@ -131,8 +145,8 @@ export type ToolArgumentPreviewSchedule = (accumulatedChars: number) => boolean;
131
145
  export declare function createToolArgumentPreviewSchedule(): ToolArgumentPreviewSchedule;
132
146
  //#endregion
133
147
  //#region packages/ai/src/utils/llm-request-activity.d.ts
134
- export declare function notifyLlmRequestActivity(signal: AbortSignal | undefined): void;
135
- export declare function onLlmRequestActivity(signal: AbortSignal, listener: () => void): () => void;
148
+ export declare function notifyLlmRequestActivity(signal: AbortSignal | undefined, progress?: boolean): void;
149
+ export declare function onLlmRequestActivity(signal: AbortSignal, listener: (progress: boolean) => void): () => void;
136
150
  //#endregion
137
151
  //#region packages/ai/src/utils/oauth/openai-chatgpt-jwt.d.ts
138
152
  declare const OPENAI_CODEX_AUTH_CLAIM = "https://api.openai.com/auth";
@@ -179,7 +193,9 @@ interface ReasoningTagTextPartitioner {
179
193
  markStrict(): void;
180
194
  push(chunk: string): ReasoningTagTextDelta[];
181
195
  pushVisible(chunk: string): ReasoningTagTextDelta[];
182
- flush(): ReasoningTagTextDelta[];
196
+ flush(options?: {
197
+ recoverUnclosed?: boolean;
198
+ }): ReasoningTagTextDelta[];
183
199
  hasPending(): boolean;
184
200
  /** Whether more input can change buffered Markdown or reasoning-tag ownership. */
185
201
  hasPendingSyntax(): boolean;
@@ -234,5 +250,7 @@ export type SseByteGuard = {
234
250
  cancelled(): boolean;
235
251
  };
236
252
  export declare function createSseByteGuard(reader: ReadableStreamDefaultReader<Uint8Array>, opts: ReadSseStreamWithLimitOptions): SseByteGuard;
253
+ /** Lazily bound an SDK response while preserving upstream cancellation. */
254
+ export declare function boundResponseBody(response: Response, options: ReadSseStreamWithLimitOptions): Response;
237
255
  //#endregion
238
- export { type ReasoningTagTextDelta, type ReasoningTagTextPartitioner, complete, completeSimple, findEnvKeys, getApiProvider, getApiProviders, getEnvApiKey, getEventStreamCompletion, parseTerminalToolCallArguments, sanitizeSurrogates, stream, streamSimple };
256
+ export { type ReasoningTagTextDelta, type ReasoningTagTextPartitioner, complete, completeSimple, getApiProvider, getApiProviders, getEventStreamCompletion, parseTerminalToolCallArguments, sanitizeSurrogates, stream, streamSimple };
@@ -1,15 +1,15 @@
1
1
  import { a as isProviderRefusalAssistantError } from "../diagnostics-DzrF1h4J.mjs";
2
- import { o as getEventStreamCompletion } from "../event-stream-C5AbCAaZ.mjs";
3
- import { r as createApiRegistry, t as createLlmRuntime } from "../stream-CElngO8h.mjs";
4
- import { A as getSupportedThinkingLevels, D as applyProviderReportedUsageCost, E as headersToRecord, O as calculateCost, j as modelsAreEqual, k as clampThinkingLevel } from "../host-JpNulOOs.mjs";
2
+ import { o as getEventStreamCompletion } from "../event-stream-X2gmsUWv.mjs";
3
+ import { r as createApiRegistry, t as createLlmRuntime } from "../stream-DwrETW0_.mjs";
4
+ import { A as getSupportedThinkingLevels, D as applyProviderReportedUsageCost, E as headersToRecord, O as calculateCost, j as modelsAreEqual, k as clampThinkingLevel } from "../host-JWXZWa-c.mjs";
5
5
  import { i as registerSessionResourceCleanupObserver, n as getSessionResourceOwnerId, r as registerSessionResourceCleanup, t as cleanupSessionResources } from "../session-resources-D1wgDQ8C.mjs";
6
- import { A as shortHash, D as parseJsonWithRepair, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, P as sanitizeSurrogates, g as parseTerminalToolCallArguments, k as repairJson } from "../transport-stream-shared-C5TAc3U_.mjs";
7
- import { n as getEnvApiKey, t as findEnvKeys } from "../env-api-keys-CyX4VKGO.mjs";
6
+ import { A as shortHash, D as parseJsonWithRepair, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, P as sanitizeSurrogates, g as parseTerminalToolCallArguments, k as repairJson } from "../transport-stream-shared-DH08b7Il.mjs";
7
+ import { n as getEnvApiKey, t as findEnvKeys } from "../env-api-keys-CrxwdylR.mjs";
8
8
  import { t as createDeferredEventBuffer } from "../deferred-event-buffer-DAvyP7qA.mjs";
9
- import { n as onLlmRequestActivity, t as notifyLlmRequestActivity } from "../llm-request-activity-D8f_oxHj.mjs";
10
- import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, n as createFirstStreamEventTimeoutError, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "../stream-first-event-timeout-D9ZmL_s9.mjs";
11
- import { t as createReasoningTagTextPartitioner } from "../reasoning-tag-text-partitioner-Ju9VpUGl.mjs";
12
- import { t as createSseByteGuard } from "../streaming-byte-guard-CC-HMn_u.mjs";
9
+ import { n as onLlmRequestActivity, t as notifyLlmRequestActivity } from "../llm-request-activity-CfMuh5cC.mjs";
10
+ import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, n as createFirstStreamEventTimeoutError, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "../stream-first-event-timeout-Dc42hKv6.mjs";
11
+ import { n as createSseByteGuard, t as boundResponseBody } from "../streaming-byte-guard-DBXr1XYn.mjs";
12
+ import { t as createReasoningTagTextPartitioner } from "../reasoning-tag-text-partitioner-0-Rsezog.mjs";
13
13
  import { n as resolveOpenAICodexAccountId, t as decodeOpenAICodexJwtPayload } from "../openai-chatgpt-jwt-KWcgd0d_.mjs";
14
14
  //#region packages/ai/src/internal/default-runtime.ts
15
15
  const DEFAULT_RUNTIME_KEY = Symbol.for("openclaw.ai.defaultRuntime");
@@ -28,9 +28,6 @@ const defaultRuntime = resolveDefaultRuntime();
28
28
  const defaultApiRegistry = defaultRuntime.registry;
29
29
  const defaultLlmRuntime = defaultRuntime.runtime;
30
30
  const { getApiProvider, getApiProviders } = defaultApiRegistry;
31
- function clearApiProviders() {
32
- defaultApiRegistry.clearApiProviders();
33
- }
34
31
  const { stream, complete, streamSimple, completeSimple } = defaultLlmRuntime;
35
32
  //#endregion
36
33
  //#region packages/ai/src/utils/overflow.ts
@@ -140,4 +137,4 @@ function isContextOverflow(message, contextWindow) {
140
137
  return false;
141
138
  }
142
139
  //#endregion
143
- export { applyProviderReportedUsageCost, calculateCost, clampThinkingLevel, cleanupSessionResources, clearApiProviders, complete, completeSimple, createDeferredEventBuffer, createFirstStreamEventAbortController, createFirstStreamEventTimeoutError, createReasoningTagTextPartitioner, createSseByteGuard, createToolArgumentPreviewSchedule, decodeOpenAICodexJwtPayload, defaultApiRegistry, defaultLlmRuntime, findEnvKeys, getApiProvider, getApiProviders, getEnvApiKey, getEventStreamCompletion, getFirstStreamEventTimeoutHandler, getFirstStreamEventTimeoutMs, getSessionResourceOwnerId, getSupportedThinkingLevels, headersToRecord, isContextOverflow, matchesContextOverflowMessage, modelsAreEqual, notifyLlmRequestActivity, onLlmRequestActivity, parseJsonWithRepair, parseStreamingJson, parseTerminalToolCallArguments, registerSessionResourceCleanup, registerSessionResourceCleanupObserver, repairJson, resolveOpenAICodexAccountId, sanitizeSurrogates, shortHash, stream, streamSimple, withFirstStreamEventTimeout };
140
+ export { applyProviderReportedUsageCost, boundResponseBody, calculateCost, clampThinkingLevel, cleanupSessionResources, complete, completeSimple, createDeferredEventBuffer, createFirstStreamEventAbortController, createFirstStreamEventTimeoutError, createReasoningTagTextPartitioner, createSseByteGuard, createToolArgumentPreviewSchedule, decodeOpenAICodexJwtPayload, defaultApiRegistry, defaultLlmRuntime, findEnvKeys, getApiProvider, getApiProviders, getEnvApiKey, getEventStreamCompletion, getFirstStreamEventTimeoutHandler, getFirstStreamEventTimeoutMs, getSessionResourceOwnerId, getSupportedThinkingLevels, headersToRecord, isContextOverflow, matchesContextOverflowMessage, modelsAreEqual, notifyLlmRequestActivity, onLlmRequestActivity, parseJsonWithRepair, parseStreamingJson, parseTerminalToolCallArguments, registerSessionResourceCleanup, registerSessionResourceCleanupObserver, repairJson, resolveOpenAICodexAccountId, sanitizeSurrogates, shortHash, stream, streamSimple, withFirstStreamEventTimeout };
@@ -1,9 +1,9 @@
1
- import { O as Message, Q as SimpleStreamOptions, a as AssistantMessage, at as ThinkingBudgets, k as Model, n as Api, nt as StreamOptions, st as ThinkingLevel } from "../types-DvzmWW8J.mjs";
2
- import { a as readAssistantThinkingAppend } from "../event-stream-DrRM_90c.mjs";
3
- import "../types-Dlz-8qcy.mjs";
1
+ import { O as Message, Q as SimpleStreamOptions, a as AssistantMessage, at as ThinkingBudgets, k as Model, n as Api, nt as StreamOptions, st as ThinkingLevel } from "../types-Bd2T86VJ.mjs";
2
+ import { a as readAssistantThinkingAppend } from "../event-stream-BcqWLo_u.mjs";
3
+ import "../types-Kdfw_04V.mjs";
4
4
  import { t as sanitizeSurrogates } from "../sanitize-unicode-CjDG6jJx.mjs";
5
5
  import { i as projectProviderError } from "../provider-error-xumb1V3F.mjs";
6
- import { n as createDiagnosticRecord } from "../credential-redaction-BKv49aiv.mjs";
6
+ import { n as createDiagnosticRecord, r as isCredentialFieldName } from "../credential-redaction-BHxruEH6.mjs";
7
7
  import { n as normalizeStructuredPromptSection, r as sortPromptCacheToolsByName, t as normalizePromptCapabilityIds } from "../prompt-cache-stability-Cwcjv_fx.mjs";
8
8
  //#region packages/ai/src/providers/simple-options.d.ts
9
9
  type FirstEventStreamOptions = {
@@ -117,4 +117,4 @@ export declare function projectCopilotRequestFacts(messages: readonly {
117
117
  hasImages: boolean;
118
118
  };
119
119
  //#endregion
120
- export { createDiagnosticRecord, normalizePromptCapabilityIds, normalizeStructuredPromptSection, projectProviderError, readAssistantThinkingAppend, sanitizeSurrogates, sortPromptCacheToolsByName };
120
+ export { createDiagnosticRecord, isCredentialFieldName, normalizePromptCapabilityIds, normalizeStructuredPromptSection, projectProviderError, readAssistantThinkingAppend, sanitizeSurrogates, sortPromptCacheToolsByName };
@@ -1,8 +1,8 @@
1
- import { s as readAssistantThinkingAppend } from "../event-stream-C5AbCAaZ.mjs";
2
- import { M as hasMediaPayload, N as isImageWithMediaPayload, c as transformMessages, d as hasOnlyAssistantReasoningContent, f as isReasoningOnlyLengthAssistantTurn, l as FAILED_ASSISTANT_REPLAY_TEXT, m as resolveFailedAssistantReplay, p as isStreamErrorFallbackContent, u as STREAM_ERROR_FALLBACK_TEXT } from "../host-JpNulOOs.mjs";
3
- import { n as projectProviderError, r as createDiagnosticRecord } from "../provider-error-DQBE1bUQ.mjs";
4
- import { P as sanitizeSurrogates } from "../transport-stream-shared-C5TAc3U_.mjs";
5
- import { C as stripSystemPromptCacheBoundary, D as sortPromptCacheToolsByName, E as normalizeStructuredPromptSection, S as splitSystemPromptRelocatableBoundary, T as normalizePromptCapabilityIds, _ as SYSTEM_PROMPT_RELOCATABLE_BOUNDARY, b as prependSystemPromptAdditionAfterCacheBoundary, d as describeToolResultMediaPlaceholder, f as describeUnsupportedToolResultMedia, g as SYSTEM_PROMPT_CACHE_BOUNDARY, h as formatToolResultText, i as clampReasoning, m as extractToolResultText, n as buildBaseOptions, p as extractToolResultBlockText, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking, v as SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary, y as ensureSystemPromptCacheBoundary } from "../simple-options-wW3117Fu.mjs";
1
+ import { s as readAssistantThinkingAppend } from "../event-stream-X2gmsUWv.mjs";
2
+ import { M as hasMediaPayload, N as isImageWithMediaPayload, c as transformMessages, d as hasOnlyAssistantReasoningContent, f as isReasoningOnlyLengthAssistantTurn, l as FAILED_ASSISTANT_REPLAY_TEXT, m as resolveFailedAssistantReplay, p as isStreamErrorFallbackContent, u as STREAM_ERROR_FALLBACK_TEXT } from "../host-JWXZWa-c.mjs";
3
+ import { i as isCredentialFieldName, n as projectProviderError, r as createDiagnosticRecord } from "../provider-error-CF9GWCs2.mjs";
4
+ import { P as sanitizeSurrogates } from "../transport-stream-shared-DH08b7Il.mjs";
5
+ import { C as stripSystemPromptCacheBoundary, D as sortPromptCacheToolsByName, E as normalizeStructuredPromptSection, S as splitSystemPromptRelocatableBoundary, T as normalizePromptCapabilityIds, _ as SYSTEM_PROMPT_RELOCATABLE_BOUNDARY, b as prependSystemPromptAdditionAfterCacheBoundary, d as describeToolResultMediaPlaceholder, f as describeUnsupportedToolResultMedia, g as SYSTEM_PROMPT_CACHE_BOUNDARY, h as formatToolResultText, i as clampReasoning, m as extractToolResultText, n as buildBaseOptions, p as extractToolResultBlockText, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking, v as SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary, y as ensureSystemPromptCacheBoundary } from "../simple-options-BARFAzk9.mjs";
6
6
  import { t as projectCopilotRequestFacts } from "../github-copilot-request-facts-DEE6gcB9.mjs";
7
7
  //#region packages/ai/src/utils/tls-certificate-errors.ts
8
8
  const HOSTNAME_MISMATCH_CODES = /* @__PURE__ */ new Set(["ERR_TLS_CERT_ALTNAME_INVALID", "HOSTNAME_MISMATCH"]);
@@ -81,7 +81,6 @@ function inspectTlsCertificateErrorInternal(error, seen, depth) {
81
81
  candidate.error,
82
82
  ...nestedErrors
83
83
  ]) {
84
- if (nested === void 0 || nested === error) continue;
85
84
  const details = inspectTlsCertificateErrorInternal(nested, seen, depth + 1);
86
85
  if (details) return details;
87
86
  }
@@ -96,4 +95,4 @@ function inspectTlsCertificateError(error) {
96
95
  return inspectTlsCertificateErrorInternal(error, /* @__PURE__ */ new Set(), 0);
97
96
  }
98
97
  //#endregion
99
- export { FAILED_ASSISTANT_REPLAY_TEXT, STREAM_ERROR_FALLBACK_TEXT, SYSTEM_PROMPT_CACHE_BOUNDARY, SYSTEM_PROMPT_RELOCATABLE_BOUNDARY, SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END, adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToModel, clampReasoning, createDiagnosticRecord, describeToolResultMediaPlaceholder, describeUnsupportedToolResultMedia, ensureSystemPromptCacheBoundary, extractToolResultBlockText, extractToolResultText, formatToolResultText, hasMediaPayload, hasOnlyAssistantReasoningContent, inspectTlsCertificateError, isImageWithMediaPayload, isReasoningOnlyLengthAssistantTurn, isStreamErrorFallbackContent, normalizePromptCapabilityIds, normalizeStructuredPromptSection, prependSystemPromptAdditionAfterCacheBoundary, projectCopilotRequestFacts, projectProviderError, readAssistantThinkingAppend, resolveFailedAssistantReplay, sanitizeSurrogates, sortPromptCacheToolsByName, splitSystemPromptCacheBoundary, splitSystemPromptRelocatableBoundary, stripSystemPromptCacheBoundary, stripSystemPromptRelocatableBoundary, transformMessages };
98
+ export { FAILED_ASSISTANT_REPLAY_TEXT, STREAM_ERROR_FALLBACK_TEXT, SYSTEM_PROMPT_CACHE_BOUNDARY, SYSTEM_PROMPT_RELOCATABLE_BOUNDARY, SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END, adjustMaxTokensForThinking, buildBaseOptions, clampMaxTokensToModel, clampReasoning, createDiagnosticRecord, describeToolResultMediaPlaceholder, describeUnsupportedToolResultMedia, ensureSystemPromptCacheBoundary, extractToolResultBlockText, extractToolResultText, formatToolResultText, hasMediaPayload, hasOnlyAssistantReasoningContent, inspectTlsCertificateError, isCredentialFieldName, isImageWithMediaPayload, isReasoningOnlyLengthAssistantTurn, isStreamErrorFallbackContent, normalizePromptCapabilityIds, normalizeStructuredPromptSection, prependSystemPromptAdditionAfterCacheBoundary, projectCopilotRequestFacts, projectProviderError, readAssistantThinkingAppend, resolveFailedAssistantReplay, sanitizeSurrogates, sortPromptCacheToolsByName, splitSystemPromptCacheBoundary, splitSystemPromptRelocatableBoundary, stripSystemPromptCacheBoundary, stripSystemPromptRelocatableBoundary, transformMessages };
@@ -1,3 +1,3 @@
1
- import { n as projectRuntimeToolInputSchema } from "../tool-schema-json-projection-Ct8SeBeJ.mjs";
2
- import { _ as GEMINI_UNSUPPORTED_SCHEMA_KEYWORDS, a as resolveOpenAIProjectedToolsStrictToolFlag, c as extractToolSchemaModelCompat, d as shouldOmitEmptyArrayItems, g as findLlamacppGbnfSchemaViolations, h as cleanSchemaForLlamacppGbnf, i as normalizeStrictOpenAIJsonSchema, l as normalizeToolParameterSchema, m as LLAMACPP_GBNF_MAX_REPETITION_THRESHOLD, n as isStrictOpenAIJsonSchemaCompatible, o as findOpenAIStrictSchemaViolations, p as stripUnsupportedSchemaKeywords, r as normalizeOpenAIStrictToolParameters, s as normalizeOpenAIStrictCompatSchema, t as findOpenAIStrictToolProjectionDiagnostics, u as resolveUnsupportedToolSchemaKeywords, v as cleanSchemaForGemini } from "../openai-tool-schema-DYNePiF8.mjs";
1
+ import { n as projectRuntimeToolInputSchema } from "../tool-schema-json-projection-B8sG1I9v.mjs";
2
+ import { _ as GEMINI_UNSUPPORTED_SCHEMA_KEYWORDS, a as resolveOpenAIProjectedToolsStrictToolFlag, c as extractToolSchemaModelCompat, d as shouldOmitEmptyArrayItems, g as findLlamacppGbnfSchemaViolations, h as cleanSchemaForLlamacppGbnf, i as normalizeStrictOpenAIJsonSchema, l as normalizeToolParameterSchema, m as LLAMACPP_GBNF_MAX_REPETITION_THRESHOLD, n as isStrictOpenAIJsonSchemaCompatible, o as findOpenAIStrictSchemaViolations, p as stripUnsupportedSchemaKeywords, r as normalizeOpenAIStrictToolParameters, s as normalizeOpenAIStrictCompatSchema, t as findOpenAIStrictToolProjectionDiagnostics, u as resolveUnsupportedToolSchemaKeywords, v as cleanSchemaForGemini } from "../openai-tool-schema-DDPXsvJP.mjs";
3
3
  export { GEMINI_UNSUPPORTED_SCHEMA_KEYWORDS, LLAMACPP_GBNF_MAX_REPETITION_THRESHOLD, cleanSchemaForGemini, cleanSchemaForLlamacppGbnf, extractToolSchemaModelCompat, findLlamacppGbnfSchemaViolations, findOpenAIStrictSchemaViolations, findOpenAIStrictToolProjectionDiagnostics, isStrictOpenAIJsonSchemaCompatible, normalizeOpenAIStrictCompatSchema, normalizeOpenAIStrictToolParameters, normalizeStrictOpenAIJsonSchema, normalizeToolParameterSchema, projectRuntimeToolInputSchema, resolveOpenAIProjectedToolsStrictToolFlag, resolveUnsupportedToolSchemaKeywords, shouldOmitEmptyArrayItems, stripUnsupportedSchemaKeywords };
@@ -1,8 +1,8 @@
1
1
  //#region packages/ai/src/utils/llm-request-activity.ts
2
2
  const requestActivityListeners = /* @__PURE__ */ new WeakMap();
3
- function notifyLlmRequestActivity(signal) {
3
+ function notifyLlmRequestActivity(signal, progress = true) {
4
4
  if (!signal) return;
5
- for (const listener of requestActivityListeners.get(signal) ?? []) listener();
5
+ for (const listener of requestActivityListeners.get(signal) ?? []) listener(progress);
6
6
  }
7
7
  function onLlmRequestActivity(signal, listener) {
8
8
  const listeners = requestActivityListeners.get(signal) ?? /* @__PURE__ */ new Set();
@@ -1,12 +1,12 @@
1
- import { r as appendAssistantThinking, t as AssistantMessageEventStream } from "./event-stream-C5AbCAaZ.mjs";
2
- import { N as isImageWithMediaPayload, O as calculateCost, k as clampThinkingLevel, r as getAiTransportHost } from "./host-JpNulOOs.mjs";
3
- import { A as shortHash, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, P as sanitizeSurrogates, l as finalizeTerminalToolCallArguments, m as notifyProviderHttpResponse, n as assignTransportErrorDetails, u as finalizeTransportStream } from "./transport-stream-shared-C5TAc3U_.mjs";
4
- import { C as stripSystemPromptCacheBoundary, D as sortPromptCacheToolsByName, d as describeToolResultMediaPlaceholder, h as formatToolResultText, m as extractToolResultText, n as buildBaseOptions, r as clampMaxTokensToModel } from "./simple-options-wW3117Fu.mjs";
5
- import { n as transformProviderMessages, t as createAssistantOutput } from "./assistant-output-mJ9cL4Qg.mjs";
6
- import { t as notifyLlmRequestActivity } from "./llm-request-activity-D8f_oxHj.mjs";
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-JWXZWa-c.mjs";
3
+ import { A as shortHash, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, P as sanitizeSurrogates, l as finalizeTerminalToolCallArguments, m as notifyProviderHttpResponse, n as assignTransportErrorDetails, u as finalizeTransportStream } from "./transport-stream-shared-DH08b7Il.mjs";
4
+ import { C as stripSystemPromptCacheBoundary, D as sortPromptCacheToolsByName, d as describeToolResultMediaPlaceholder, h as formatToolResultText, m as extractToolResultText, n as buildBaseOptions, r as clampMaxTokensToModel } from "./simple-options-BARFAzk9.mjs";
5
+ import { n as transformProviderMessages, t as createAssistantOutput } from "./assistant-output-CUEeSotf.mjs";
6
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
7
+ import { t as boundResponseBody } from "./streaming-byte-guard-DBXr1XYn.mjs";
7
8
  import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
8
- import { t as createSseByteGuard } from "./streaming-byte-guard-CC-HMn_u.mjs";
9
- import { t as requireApiKey } from "./required-api-key-D4kn3252.mjs";
9
+ import { t as requireApiKey } from "./required-api-key-CFJvcFy_.mjs";
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { HTTPClient } from "@mistralai/mistralai/lib/http";
12
12
  import { ReasoningEffort$inboundSchema } from "@mistralai/mistralai/models/components/reasoningeffort.js";
@@ -18,30 +18,10 @@ const MISTRAL_STREAM_BODY_MAX_BYTES = 16777216;
18
18
  function createBoundedMistralFetcher(maxBytes = MISTRAL_STREAM_BODY_MAX_BYTES, upstreamFetch = fetch) {
19
19
  return async (input, init) => {
20
20
  const response = init == null ? await upstreamFetch(input) : await upstreamFetch(input, init);
21
- if (!response.body || typeof response.body.getReader !== "function") return response;
22
- const reader = response.body.getReader();
23
- const guard = createSseByteGuard(reader, {
21
+ return boundResponseBody(response, {
24
22
  maxBytes,
25
23
  onOverflow: ({ size, maxBytes: cap }) => /* @__PURE__ */ new Error(`mistral: stream body exceeds ${cap} bytes (got ${size})`)
26
24
  });
27
- const guardedStream = new ReadableStream({
28
- async pull(controller) {
29
- const { done, value } = await guard.read();
30
- if (done) {
31
- controller.close();
32
- return;
33
- }
34
- controller.enqueue(value);
35
- },
36
- async cancel(reason) {
37
- await guard.cancel(reason);
38
- }
39
- });
40
- return new Response(guardedStream, {
41
- status: response.status,
42
- statusText: response.statusText,
43
- headers: response.headers
44
- });
45
25
  };
46
26
  }
47
27
  const streamMistral = (model, context, options) => {
@@ -198,57 +178,36 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
198
178
  let terminalFinishReason;
199
179
  const blocks = output.content;
200
180
  const blockIndex = () => blocks.length - 1;
201
- const toolBlockIdentities = /* @__PURE__ */ new Map();
202
- const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
181
+ const toolBlocks = [];
203
182
  const normalizeMissingToolCallId = createMistralToolCallIdNormalizer();
204
183
  const missingToolCallIdScope = randomUUID();
205
184
  const createMissingToolCallId = (contentIndex) => normalizeMissingToolCallId(`${missingToolCallIdScope}:toolcall:${contentIndex}`);
206
- const findIdentityCandidates = (matches, excludedContentIndexes) => {
207
- const candidates = /* @__PURE__ */ new Set();
208
- for (const [contentIndex, identity] of toolBlockIdentities) if (!excludedContentIndexes?.has(contentIndex) && matches(identity)) candidates.add(contentIndex);
209
- return candidates;
210
- };
211
- const intersectCandidates = (left, right) => new Set([...left].filter((contentIndex) => right.has(contentIndex)));
212
- const filterIdentityCandidates = (candidates, matches) => new Set([...candidates].filter((contentIndex) => {
213
- const identity = toolBlockIdentities.get(contentIndex);
214
- return identity !== void 0 && matches(identity);
215
- }));
216
185
  const requireSingleCandidate = (candidates) => {
217
- if (candidates.size > 1) throw new Error("Mistral streamed tool-call continuation is ambiguous; refusing to merge arguments");
218
- return candidates.values().next().value;
219
- };
220
- const requireExistingCandidate = (candidates) => {
221
- const candidate = requireSingleCandidate(candidates);
222
- if (candidate === void 0) throw new Error("Mistral streamed tool-call identities conflict; refusing to merge arguments");
223
- return candidate;
186
+ if (candidates.length > 1) throw new Error("Mistral streamed tool-call continuation is ambiguous; refusing to merge arguments");
187
+ return candidates[0];
224
188
  };
225
- const resolveToolBlockIndex = (params) => {
189
+ const resolveToolBlock = (params) => {
226
190
  const explicitId = params.explicitId;
227
191
  const functionName = params.functionName;
228
192
  const toolCallIndex = params.index;
229
- const idCandidates = explicitId ? findIdentityCandidates((identity) => identity.explicitIds.has(explicitId), params.usedContentIndexes) : /* @__PURE__ */ new Set();
230
- const nameCandidates = functionName ? findIdentityCandidates((identity) => identity.functionNames.has(functionName), params.usedContentIndexes) : /* @__PURE__ */ new Set();
231
- if (idCandidates.size > 0) {
193
+ const available = toolBlocks.filter((identity) => !params.usedContentIndexes.has(identity.contentIndex));
194
+ const idCandidates = explicitId ? available.filter((identity) => identity.explicitIds.has(explicitId)) : [];
195
+ const nameCandidates = functionName ? available.filter((identity) => identity.functionNames.has(functionName)) : [];
196
+ if (idCandidates.length > 0) {
232
197
  let candidates = idCandidates;
233
- if (nameCandidates.size > 0) candidates = intersectCandidates(candidates, nameCandidates);
234
- return requireExistingCandidate(candidates);
198
+ if (nameCandidates.length > 0) candidates = candidates.filter((identity) => nameCandidates.includes(identity));
199
+ const candidate = requireSingleCandidate(candidates);
200
+ if (!candidate) throw new Error("Mistral streamed tool-call identities conflict; refusing to merge arguments");
201
+ return candidate;
235
202
  }
236
- if (nameCandidates.size > 0) {
237
- const idCompatibleCandidates = filterIdentityCandidates(nameCandidates, (identity) => !explicitId || identity.explicitIds.size === 0);
238
- if (idCompatibleCandidates.size <= 1 && (toolCallIndex === void 0 || toolCallIndex === 0)) return requireSingleCandidate(idCompatibleCandidates);
239
- const indexCompatibleCandidates = filterIdentityCandidates(idCompatibleCandidates, (identity) => toolCallIndex === void 0 || identity.indexes.size === 0 || identity.indexes.has(toolCallIndex));
203
+ if (nameCandidates.length > 0) {
204
+ const idCompatibleCandidates = nameCandidates.filter((identity) => !explicitId || identity.explicitIds.size === 0);
205
+ if (idCompatibleCandidates.length <= 1 && (toolCallIndex === void 0 || toolCallIndex === 0)) return requireSingleCandidate(idCompatibleCandidates);
206
+ const indexCompatibleCandidates = idCompatibleCandidates.filter((identity) => toolCallIndex === void 0 || identity.indexes.size === 0 || identity.indexes.has(toolCallIndex));
240
207
  return requireSingleCandidate(indexCompatibleCandidates);
241
208
  }
242
- const indexCandidates = toolCallIndex === void 0 ? /* @__PURE__ */ new Set() : findIdentityCandidates((identity) => identity.indexes.has(toolCallIndex), params.usedContentIndexes);
243
- if (functionName) {
244
- const namelessCandidates = filterIdentityCandidates(indexCandidates, (identity) => identity.functionNames.size === 0 && (!explicitId || identity.explicitIds.size === 0));
245
- return requireSingleCandidate(namelessCandidates);
246
- }
247
- if (explicitId) {
248
- const idlessCandidates = filterIdentityCandidates(indexCandidates, (identity) => identity.explicitIds.size === 0);
249
- return requireSingleCandidate(idlessCandidates);
250
- }
251
- return requireSingleCandidate(indexCandidates);
209
+ const indexCandidates = toolCallIndex === void 0 ? [] : available.filter((identity) => identity.indexes.has(toolCallIndex));
210
+ return requireSingleCandidate(indexCandidates.filter((identity) => (!functionName || identity.functionNames.size === 0) && (!explicitId || identity.explicitIds.size === 0)));
252
211
  };
253
212
  const finishCurrentBlock = () => {
254
213
  if (!currentBlock) return;
@@ -259,26 +218,31 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
259
218
  partial: output
260
219
  });
261
220
  };
262
- const appendTextDelta = (text) => {
263
- const textDelta = sanitizeSurrogates(text);
264
- if (!currentBlock || currentBlock.type !== "text") {
221
+ const appendContentDelta = (type, text) => {
222
+ const delta = sanitizeSurrogates(text);
223
+ if (type === "thinking" && !delta) return;
224
+ if (!currentBlock || currentBlock.type !== type) {
265
225
  finishCurrentBlock();
266
- currentBlock = {
267
- type: "text",
226
+ currentBlock = type === "text" ? {
227
+ type,
268
228
  text: ""
229
+ } : {
230
+ type,
231
+ thinking: ""
269
232
  };
270
233
  output.content.push(currentBlock);
271
234
  stream.push({
272
- type: "text_start",
235
+ type: `${type}_start`,
273
236
  contentIndex: blockIndex(),
274
237
  partial: output
275
238
  });
276
239
  }
277
- currentBlock.text += textDelta;
240
+ if (currentBlock.type === "text") currentBlock.text += delta;
241
+ else appendAssistantThinking(currentBlock, delta);
278
242
  stream.push({
279
- type: "text_delta",
243
+ type: `${type}_delta`,
280
244
  contentIndex: blockIndex(),
281
- delta: textDelta,
245
+ delta,
282
246
  partial: output
283
247
  });
284
248
  };
@@ -310,36 +274,11 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
310
274
  const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content;
311
275
  for (const item of contentItems) {
312
276
  if (typeof item === "string") {
313
- appendTextDelta(item);
314
- continue;
315
- }
316
- if (item.type === "thinking") {
317
- const deltaText = item.thinking.map((part) => "text" in part ? part.text : "").join("");
318
- const thinkingDelta = sanitizeSurrogates(deltaText);
319
- if (!thinkingDelta) continue;
320
- if (!currentBlock || currentBlock.type !== "thinking") {
321
- finishCurrentBlock();
322
- currentBlock = {
323
- type: "thinking",
324
- thinking: ""
325
- };
326
- output.content.push(currentBlock);
327
- stream.push({
328
- type: "thinking_start",
329
- contentIndex: blockIndex(),
330
- partial: output
331
- });
332
- }
333
- appendAssistantThinking(currentBlock, thinkingDelta);
334
- stream.push({
335
- type: "thinking_delta",
336
- contentIndex: blockIndex(),
337
- delta: thinkingDelta,
338
- partial: output
339
- });
277
+ appendContentDelta("text", item);
340
278
  continue;
341
279
  }
342
- if (item.type === "text") appendTextDelta(item.text);
280
+ if (item.type === "thinking") appendContentDelta("thinking", item.thinking.map((part) => "text" in part ? part.text : "").join(""));
281
+ else if (item.type === "text") appendContentDelta("text", item.text);
343
282
  }
344
283
  }
345
284
  const toolCalls = delta.toolCalls || [];
@@ -352,20 +291,15 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
352
291
  const toolCallIndex = typeof toolCall.index === "number" && Number.isInteger(toolCall.index) ? toolCall.index : void 0;
353
292
  const providedCallId = toolCall.id && toolCall.id !== "null" ? toolCall.id : void 0;
354
293
  const functionName = toolCall.function.name.trim() || void 0;
355
- const existingIndex = resolveToolBlockIndex({
294
+ let identity = resolveToolBlock({
356
295
  explicitId: providedCallId,
357
296
  functionName,
358
297
  index: toolCallIndex,
359
298
  usedContentIndexes: usedToolBlockIndexes
360
299
  });
361
- let block;
362
- if (existingIndex !== void 0) {
363
- const existing = output.content[existingIndex];
364
- if (existing?.type === "toolCall") block = existing;
365
- }
366
- if (!block) {
300
+ if (!identity) {
367
301
  const contentIndex = output.content.length;
368
- block = {
302
+ const block = {
369
303
  type: "toolCall",
370
304
  id: providedCallId ?? createMissingToolCallId(contentIndex),
371
305
  name: functionName ?? "",
@@ -373,21 +307,22 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
373
307
  partialArgs: ""
374
308
  };
375
309
  output.content.push(block);
376
- toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
377
- toolBlockIdentities.set(contentIndex, {
378
- explicitIds: new Set(providedCallId ? [providedCallId] : []),
379
- functionNames: new Set(functionName ? [functionName] : []),
380
- indexes: new Set(toolCallIndex === void 0 ? [] : [toolCallIndex])
381
- });
310
+ identity = {
311
+ block,
312
+ contentIndex,
313
+ preview: createToolArgumentPreviewSchedule(),
314
+ explicitIds: /* @__PURE__ */ new Set(),
315
+ functionNames: /* @__PURE__ */ new Set(),
316
+ indexes: /* @__PURE__ */ new Set()
317
+ };
318
+ toolBlocks.push(identity);
382
319
  stream.push({
383
320
  type: "toolcall_start",
384
321
  contentIndex,
385
322
  partial: output
386
323
  });
387
324
  }
388
- const contentIndex = output.content.indexOf(block);
389
- const identity = toolBlockIdentities.get(contentIndex);
390
- if (!identity) throw new Error("Mistral streamed tool-call identity is missing");
325
+ const { block, contentIndex } = identity;
391
326
  usedToolBlockIndexes.add(contentIndex);
392
327
  if (providedCallId) {
393
328
  block.id = providedCallId;
@@ -401,7 +336,7 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
401
336
  if (toolCallIndex !== void 0) identity.indexes.add(toolCallIndex);
402
337
  const argsDelta = typeof toolCall.function.arguments === "string" ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments || {});
403
338
  block.partialArgs = (block.partialArgs || "") + argsDelta;
404
- if (toolArgumentPreviewSchedules.get(block)?.(block.partialArgs.length)) block.arguments = parseStreamingJson(block.partialArgs);
339
+ if (identity.preview(block.partialArgs.length)) block.arguments = parseStreamingJson(block.partialArgs);
405
340
  stream.push({
406
341
  type: "toolcall_delta",
407
342
  contentIndex,
@@ -416,15 +351,8 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
416
351
  if (!terminalFinishReason) throw new Error("Mistral stream ended without a terminal finish reason");
417
352
  return;
418
353
  }
419
- const completedToolCalls = [...toolBlockIdentities.keys()].flatMap((contentIndex) => {
420
- const block = blocks[contentIndex];
421
- return block?.type === "toolCall" ? [{
422
- block,
423
- contentIndex
424
- }] : [];
425
- });
426
- finalizeTerminalToolCallArguments(completedToolCalls.map(({ block }) => block), (block) => block.partialArgs ?? "", "Mistral completed tool call has invalid JSON arguments");
427
- for (const { block, contentIndex } of completedToolCalls) {
354
+ finalizeTerminalToolCallArguments(toolBlocks.map(({ block }) => block), (block) => block.partialArgs ?? "", "Mistral completed tool call has invalid JSON arguments");
355
+ for (const { block, contentIndex } of toolBlocks) {
428
356
  delete block.partialArgs;
429
357
  stream.push({
430
358
  type: "toolcall_end",
@@ -506,21 +434,18 @@ function toChatMessages(messages, supportsImages) {
506
434
  const contentParts = [];
507
435
  const toolCalls = [];
508
436
  for (const block of msg.content) {
509
- if (block.type === "text") {
510
- if (block.text.trim().length > 0) contentParts.push({
511
- type: "text",
512
- text: sanitizeSurrogates(block.text)
513
- });
514
- continue;
515
- }
516
- if (block.type === "thinking") {
517
- if (block.thinking.trim().length > 0) contentParts.push({
518
- type: "thinking",
519
- thinking: [{
437
+ if (block.type === "text" || block.type === "thinking") {
438
+ const text = block.type === "text" ? block.text : block.thinking;
439
+ if (text.trim().length > 0) {
440
+ const part = {
520
441
  type: "text",
521
- text: sanitizeSurrogates(block.thinking)
522
- }]
523
- });
442
+ text: sanitizeSurrogates(text)
443
+ };
444
+ contentParts.push(block.type === "text" ? part : {
445
+ type: "thinking",
446
+ thinking: [part]
447
+ });
448
+ }
524
449
  continue;
525
450
  }
526
451
  toolCalls.push({
@@ -14,6 +14,10 @@ declare function resolveModelPayloadDebugMode(env?: ModelTransportDebugEnv): Mod
14
14
  declare function resolveModelSseDebugMode(env?: ModelTransportDebugEnv): ModelSseDebugMode;
15
15
  /** Emits transport diagnostics at debug, promoted to info by explicit debug flags. */
16
16
  declare function emitModelTransportDebug(log: SubsystemLogger, message: string): void;
17
+ /** The requesting layer owns AbortError classification; deadlines remain failures here. */
18
+ declare function emitModelTransportError(log: SubsystemLogger & {
19
+ warn(message: string): void;
20
+ }, label: string, detail: string, signal?: AbortSignal): void;
17
21
  //#endregion
18
22
  //#region packages/ai/src/transports/model-transport-url.d.ts
19
23
  /**
@@ -25,4 +29,4 @@ declare function formatModelTransportDebugUrl(rawUrl: string): string;
25
29
  /** Format a configured base URL for debug output, or the implicit default. */
26
30
  declare function formatModelTransportDebugBaseUrl(rawUrl: string | undefined): string;
27
31
  //#endregion
28
- export { resolveModelSseDebugMode as a, resolveModelPayloadDebugMode as i, formatModelTransportDebugUrl as n, emitModelTransportDebug as r, formatModelTransportDebugBaseUrl as t };
32
+ export { resolveModelPayloadDebugMode as a, emitModelTransportError as i, formatModelTransportDebugUrl as n, resolveModelSseDebugMode as o, emitModelTransportDebug as r, formatModelTransportDebugBaseUrl as t };
@@ -1,10 +1,12 @@
1
1
  import { a as normalizeOptionalString } from "./string-coerce-CtgOVOSv.mjs";
2
2
  //#region packages/normalization-core/src/number-coercion.ts
3
- /** Returns a number only when the input is already finite. */
4
3
  function asFiniteNumber(value) {
5
4
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
6
5
  }
7
- /** Returns a finite number only when it is zero or greater. */
6
+ function asPositiveFiniteNumber(value) {
7
+ const number = asFiniteNumber(value);
8
+ return number && number > 0 ? number : void 0;
9
+ }
8
10
  function asNonNegativeFiniteNumber(value) {
9
11
  const number = asFiniteNumber(value);
10
12
  return number && number < 0 ? void 0 : number;
@@ -38,10 +40,9 @@ function clampPositiveTimerTimeoutMs(valueMs) {
38
40
  if (value === void 0 || value <= 0) return;
39
41
  return clampTimerTimeoutMs(value);
40
42
  }
41
- /** Parses strict positive integer values from numbers or strings. */
42
43
  function parseStrictPositiveInteger(value) {
43
44
  const parsed = parseStrictInteger(value);
44
45
  return parsed !== void 0 && parsed > 0 ? parsed : void 0;
45
46
  }
46
47
  //#endregion
47
- export { parseStrictFiniteNumber as a, clampTimerTimeoutMs as i, asNonNegativeFiniteNumber as n, parseStrictPositiveInteger as o, clampPositiveTimerTimeoutMs as r, asFiniteNumber as t };
48
+ export { clampTimerTimeoutMs as a, clampPositiveTimerTimeoutMs as i, asNonNegativeFiniteNumber as n, parseStrictFiniteNumber as o, asPositiveFiniteNumber as r, parseStrictPositiveInteger as s, asFiniteNumber as t };