@openclaw/ai 2026.9.6 → 2026.9.8

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 (99) hide show
  1. package/dist/{anthropic-DZQ_7gD1.mjs → anthropic-CTXJlfnS.mjs} +37 -66
  2. package/dist/{anthropic-payload-policy-DyfwikYJ.d.mts → anthropic-payload-policy-NIPVYXPq.d.mts} +7 -5
  3. package/dist/{anthropic-stream-reducer-D6ZI1wwj.mjs → anthropic-stream-reducer-DrsBCsFY.mjs} +192 -261
  4. package/dist/{api-registry-C2T3lTV7.d.mts → api-registry-D-nbmSqr.d.mts} +2 -2
  5. package/dist/{azure-openai-responses-DS86GYzq.mjs → azure-openai-responses-BBxv4QVI.mjs} +22 -33
  6. package/dist/{base64-CPmadnUf.mjs → base64-C1PsYcRQ.mjs} +15 -9
  7. package/dist/{diagnostics-CH8j2wIG.mjs → diagnostics-CJaB6g8J.mjs} +3 -3
  8. package/dist/diagnostics.d.mts +4 -4
  9. package/dist/diagnostics.mjs +2 -2
  10. package/dist/{env-api-keys-bktO00EJ.mjs → env-api-keys-CyX4VKGO.mjs} +7 -5
  11. package/dist/event-stream-CMQfX_yr.d.mts +1 -0
  12. package/dist/{event-stream-CjnIZZst.d.mts → event-stream-DOPFYVqs.d.mts} +2 -2
  13. package/dist/{event-stream-D8PARQfL.mjs → event-stream-vd9UnCAU.mjs} +10 -0
  14. package/dist/event-stream.d.mts +2 -2
  15. package/dist/event-stream.mjs +1 -1
  16. package/dist/{google-BZJFjhuC.mjs → google-B3HEK0Ag.mjs} +8 -11
  17. package/dist/google-interactions-vMlEfPAA.mjs +574 -0
  18. package/dist/{google-messages-DB7GKkDk.mjs → google-messages-Dz2dAnGo.mjs} +35 -71
  19. package/dist/{google-shared-Bok4I6zB.mjs → google-shared-B58i3c8H.mjs} +43 -47
  20. package/dist/{google-vertex-3eVNR2qW.mjs → google-vertex-DYFXzEbh.mjs} +16 -30
  21. package/dist/{host-yTvBrYM2.mjs → host-DwBmNMCC.mjs} +29 -188
  22. package/dist/{host-policy-DZO3oPPk.mjs → host-policy-wK-ay_RK.mjs} +2 -14
  23. package/dist/{host-DH-Z-LDb.d.mts → host-rxlNaBwm.d.mts} +9 -3
  24. package/dist/{index-C25RT6bP.d.mts → index-D6KsSE74.d.mts} +28 -8
  25. package/dist/index.d.mts +7 -7
  26. package/dist/index.mjs +6 -6
  27. package/dist/internal/anthropic.d.mts +8 -7
  28. package/dist/internal/anthropic.mjs +5 -5
  29. package/dist/internal/openai-completions-compat.d.mts +1 -1
  30. package/dist/internal/openai-completions-compat.mjs +1 -1
  31. package/dist/internal/openai-responses-payload-policy.d.mts +1 -1
  32. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  33. package/dist/internal/openai.d.mts +31 -8
  34. package/dist/internal/openai.mjs +13 -13
  35. package/dist/internal/runtime.d.mts +31 -70
  36. package/dist/internal/runtime.mjs +10 -65
  37. package/dist/internal/shared.d.mts +14 -12
  38. package/dist/internal/shared.mjs +5 -4
  39. package/dist/internal/tool-schema.d.mts +1 -1
  40. package/dist/internal/tool-schema.mjs +2 -2
  41. package/dist/{mistral-C_13dVBn.mjs → mistral-7wDWcjfF.mjs} +46 -93
  42. package/dist/{openai-chatgpt-responses-sTxPl4zM.mjs → openai-chatgpt-responses-Bc7NZrQR.mjs} +26 -30
  43. package/dist/{openai-completions-BO6D_hrB.mjs → openai-completions-CHnwIV-W.mjs} +14 -12
  44. package/dist/{openai-completions-compat-CUollwl6.mjs → openai-completions-compat-BJf57ZxN.mjs} +3 -5
  45. package/dist/{openai-completions-compat-DfJG1wSO.d.mts → openai-completions-compat-qJjmqQ71.d.mts} +3 -3
  46. package/dist/{openai-completions-stream-BpuJ0ZOA.mjs → openai-completions-stream-dju_5F3P.mjs} +101 -173
  47. package/dist/{openai-prompt-cache-CjV_2IRI.mjs → openai-prompt-cache-BTMs80_O.mjs} +1 -1
  48. package/dist/{openai-prompt-cache-C4RHdN4n.d.mts → openai-prompt-cache-CouErLh7.d.mts} +2 -2
  49. package/dist/{openai-provider-client-BP8J1aeg.mjs → openai-provider-client-G8Otsq2Q.mjs} +2 -2
  50. package/dist/{openai-reasoning-effort-ash8dPrd.mjs → openai-reasoning-effort-C_0p3psG.mjs} +5 -4
  51. package/dist/{openai-responses-BJ_IEoMU.mjs → openai-responses-DbPe3-Py.mjs} +12 -11
  52. package/dist/openai-responses-compaction-replay-DiYn-gFM.d.mts +12 -0
  53. package/dist/{openai-responses-compaction-window-BiNCT0bS.mjs → openai-responses-compaction-window-CYGCjAQz.mjs} +5 -5
  54. package/dist/{openai-responses-contracts-DWrfMODE.mjs → openai-responses-contracts-CLxnqS9p.mjs} +1 -1
  55. package/dist/{openai-responses-contracts-B1ENJFpI.d.mts → openai-responses-contracts-D1iZ0njF.d.mts} +4 -4
  56. package/dist/{openai-responses-prompt-observer-internal-DPHWgbBH.mjs → openai-responses-prompt-observer-internal-BX3QTNSv.mjs} +12 -12
  57. package/dist/{openai-responses-request-lifecycle-DFuyO1pQ.mjs → openai-responses-request-lifecycle-Fsag-IGZ.mjs} +1 -1
  58. package/dist/{openai-responses-shared-DvSqtJ6_.mjs → openai-responses-shared-CIEHiKx7.mjs} +312 -122
  59. package/dist/{openai-responses-terminal-usage-BNFbvY9f.d.mts → openai-responses-terminal-usage-BE7lf7nW.d.mts} +2 -2
  60. package/dist/{openai-stop-reason-Drnn_6Qj.mjs → openai-stop-reason-8s70vDXj.mjs} +2 -12
  61. package/dist/{openai-tool-schema-ynZBgqW-.d.mts → openai-tool-schema-a5ysBBga.d.mts} +0 -6
  62. package/dist/{openai-tool-schema-D4BMcj2D.mjs → openai-tool-schema-vsl-cE-n.mjs} +243 -383
  63. package/dist/{openai-transport-params-DZKOTSfH.mjs → openai-transport-params-DyFJ4cgR.mjs} +60 -105
  64. package/dist/{positive-integer-BiUxrd71.mjs → positive-integer-CjN5OJbH.mjs} +1 -1
  65. package/dist/{provider-error-CRhW7lkJ.mjs → provider-error-CwT_j2v0.mjs} +43 -4
  66. package/dist/{provider-options-DZYq53lj.d.mts → provider-options-Df7ov0K1.d.mts} +2 -2
  67. package/dist/{provider-replay-context-DPr3w20a.mjs → provider-replay-context-Bs5aWE1d.mjs} +1 -1
  68. package/dist/{provider-transcript-transform-BTocjCRs.mjs → provider-transcript-transform-DjA5Fk2P.mjs} +17 -2
  69. package/dist/{provider-transport-turn-state-lrXEFkYr.mjs → provider-transport-turn-state-Dw7OtYUs.mjs} +1 -1
  70. package/dist/{provider-types-w1rEqrGP.d.mts → provider-types-d4XnoZMd.d.mts} +3 -3
  71. package/dist/provider-types.d.mts +6 -6
  72. package/dist/providers.d.mts +2 -2
  73. package/dist/providers.mjs +15 -11
  74. package/dist/{reasoning-tag-text-partitioner-Di38crhI.mjs → reasoning-tag-text-partitioner-B6FIIBt6.mjs} +47 -71
  75. package/dist/{record-coerce-DwRYMj3t.mjs → record-coerce-CNDovvft.mjs} +1 -1
  76. package/dist/simple-options-BkDPMuxw.mjs +349 -0
  77. package/dist/{src-DwGYYyZp.mjs → src-H4aXcFuX.mjs} +43 -25
  78. package/dist/{stream-CREqxHgU.mjs → stream-DDsCBgd-.mjs} +1 -7
  79. package/dist/{stream-first-event-timeout-BeptfRL6.mjs → stream-first-event-timeout-B9o0S4SZ.mjs} +1 -1
  80. package/dist/{tool-schema-json-projection-CD9c_fK8.mjs → tool-schema-json-projection-Ct8SeBeJ.mjs} +63 -23
  81. package/dist/{transport-stream-shared-B5RioB_Q.mjs → transport-stream-shared-BU5pwY6W.mjs} +62 -28
  82. package/dist/{transport-stream-shared-B7Z9oCYg.d.mts → transport-stream-shared-yYhXa4kX.d.mts} +12 -6
  83. package/dist/{transport-utils-03Qi0CN2.mjs → transport-utils-CqXzku3R.mjs} +3 -4
  84. package/dist/transports.d.mts +36 -32
  85. package/dist/transports.mjs +160 -216
  86. package/dist/types-CB-_vNyI.d.mts +1 -0
  87. package/dist/{types-qZFbaDbK.d.mts → types-CLLR3eB4.d.mts} +3 -1
  88. package/dist/types.d.mts +6 -6
  89. package/dist/types.mjs +4 -4
  90. package/dist/{validation-Dw7cb6BV.mjs → validation-BFZc40Ig.mjs} +80 -54
  91. package/dist/{validation-DhQhmt6t.d.mts → validation-Cat2wQsc.d.mts} +1 -1
  92. package/dist/validation.d.mts +1 -1
  93. package/dist/validation.mjs +1 -1
  94. package/package.json +5 -5
  95. package/dist/assistant-output-DM1JBNs1.mjs +0 -16
  96. package/dist/event-stream-C0nsgbj2.d.mts +0 -1
  97. package/dist/simple-options-np1XPuhm.mjs +0 -175
  98. package/dist/types-DTvddOfm.d.mts +0 -1
  99. package/dist/utf16-slice-CvGodqok.mjs +0 -29
@@ -1,13 +1,13 @@
1
1
  import { a as isProviderRefusalAssistantError } from "../diagnostics-DzrF1h4J.mjs";
2
- import { a as getEventStreamCompletion } from "../event-stream-D8PARQfL.mjs";
3
- import { n as createApiRegistry, t as createLlmRuntime } from "../stream-CREqxHgU.mjs";
4
- import { A as headersToRecord, F as modelsAreEqual, M as calculateCost, N as clampThinkingLevel, P as getSupportedThinkingLevels, j as applyProviderReportedUsageCost, v as sanitizeSurrogates } from "../host-yTvBrYM2.mjs";
5
- import { n as getEnvApiKey, t as findEnvKeys } from "../env-api-keys-bktO00EJ.mjs";
6
- import { D as repairJson, E as parseStreamingJson, O as shortHash, T as parseJsonWithRepair, h as parseTerminalToolCallArguments, w as createToolArgumentPreviewSchedule } from "../transport-stream-shared-B5RioB_Q.mjs";
2
+ import { a as getEventStreamCompletion } from "../event-stream-vd9UnCAU.mjs";
3
+ import { n as createApiRegistry, t as createLlmRuntime } from "../stream-DDsCBgd-.mjs";
4
+ import { C as applyProviderReportedUsageCost, D as modelsAreEqual, E as getSupportedThinkingLevels, S as headersToRecord, T as clampThinkingLevel, w as calculateCost } from "../host-DwBmNMCC.mjs";
5
+ import { A as shortHash, D as parseJsonWithRepair, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, g as parseTerminalToolCallArguments, j as sanitizeSurrogates, k as repairJson } from "../transport-stream-shared-BU5pwY6W.mjs";
6
+ import { n as getEnvApiKey, t as findEnvKeys } from "../env-api-keys-CyX4VKGO.mjs";
7
7
  import { t as createDeferredEventBuffer } from "../deferred-event-buffer-DAvyP7qA.mjs";
8
8
  import { n as onLlmRequestActivity, t as notifyLlmRequestActivity } from "../llm-request-activity-BjtkplhG.mjs";
9
- import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, n as createFirstStreamEventTimeoutError, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "../stream-first-event-timeout-BeptfRL6.mjs";
10
- import { t as createReasoningTagTextPartitioner } from "../reasoning-tag-text-partitioner-Di38crhI.mjs";
9
+ import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, n as createFirstStreamEventTimeoutError, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "../stream-first-event-timeout-B9o0S4SZ.mjs";
10
+ import { t as createReasoningTagTextPartitioner } from "../reasoning-tag-text-partitioner-B6FIIBt6.mjs";
11
11
  import { t as createSseByteGuard } from "../streaming-byte-guard-CC-HMn_u.mjs";
12
12
  import { n as registerSessionResourceCleanup, t as cleanupSessionResources } from "../session-resources-CkR4WWy1.mjs";
13
13
  import { n as resolveOpenAICodexAccountId, t as decodeOpenAICodexJwtPayload } from "../openai-chatgpt-jwt-KWcgd0d_.mjs";
@@ -108,15 +108,6 @@ const CONTEXT_OVERFLOW_PATTERN_SCOPES = {
108
108
  function matchesContextOverflowMessage(errorMessage, scope) {
109
109
  return CONTEXT_OVERFLOW_PATTERN_SCOPES[scope].some((pattern) => pattern.test(errorMessage));
110
110
  }
111
- /**
112
- * Patterns that indicate non-overflow errors (e.g. rate limiting, server errors).
113
- * Error messages matching any of these are excluded from overflow detection
114
- * even if they also match an OVERFLOW_PATTERN.
115
- *
116
- * Example: Bedrock formats throttling errors as "ThrottlingException: Too many tokens,
117
- * please wait before trying again." which would match the /too many tokens/i overflow
118
- * pattern without this exclusion.
119
- */
120
111
  const NON_OVERFLOW_PATTERNS = [
121
112
  /^(Throttling error|Service unavailable):/i,
122
113
  /rate limit/i,
@@ -128,55 +119,9 @@ function resolveContextInputTokens(message) {
128
119
  return message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
129
120
  }
130
121
  /**
131
- * Check if an assistant message represents a context overflow error.
132
- *
133
- * This handles two cases:
134
- * 1. Error-based overflow: Most providers return stopReason "error" with a
135
- * specific error message pattern.
136
- * 2. Silent overflow: Some providers accept overflow requests and return
137
- * successfully. For these, we check if usage.input exceeds the context window.
138
- *
139
- * ## Reliability by Provider
140
- *
141
- * **Reliable detection (returns error with detectable message):**
142
- * - Anthropic: "prompt is too long: X tokens > Y maximum" or "request_too_large"
143
- * - OpenAI (Completions & Responses): "exceeds the context window" or "exceeds the model's maximum context length of X tokens"
144
- * - Google Gemini: "input token count exceeds the maximum"
145
- * - xAI (Grok): "maximum prompt length is X but request contains Y"
146
- * - Groq: "reduce the length of the messages"
147
- * - Cerebras: 413 status code (no body)
148
- * - Mistral: "Prompt contains X tokens ... too large for model with Y maximum context length"
149
- * - OpenRouter (all backends): "maximum context length is X tokens"
150
- * - Together AI: "The input (X tokens) is longer than the model's context length (Y tokens)."
151
- * - llama.cpp: "exceeds the available context size"
152
- * - LM Studio: "greater than the context length"
153
- * - Kimi For Coding: "exceeded model token limit: X (requested: Y)"
154
- * - z.ai: "tokens in request more than max tokens allowed" or "Prompt exceeds max length"
155
- *
156
- * **Unreliable detection:**
157
- * - z.ai: Sometimes accepts overflow silently (detectable via usage.input > contextWindow),
158
- * sometimes returns rate limit errors instead of the explicit overflow error above. Pass
159
- * contextWindow param to detect silent overflow.
160
- * - Xiaomi MiMo: Truncates input to fit contextWindow then returns stopReason "length" with
161
- * output=0. Pass contextWindow param to detect via the "filled context + zero output" signal.
162
- * - Ollama: May truncate input silently for some setups, but may also return explicit
163
- * overflow errors that match the patterns above. Silent truncation still cannot be
164
- * detected here because we do not know the expected token count.
165
- *
166
- * ## Custom Providers
167
- *
168
- * If you've added custom models via settings.json, this function may not detect
169
- * overflow errors from those providers. To add support:
170
- *
171
- * 1. Send a request that exceeds the model's context window
172
- * 2. Check the errorMessage in the response
173
- * 3. Create a regex pattern that matches the error
174
- * 4. The pattern should be added to the appropriate canonical scope in this file, or
175
- * check the errorMessage yourself before calling this function
176
- *
177
- * @param message - The assistant message to check
178
- * @param contextWindow - Optional context window size for detecting silent overflow (z.ai)
179
- * @returns true if the message indicates a context overflow
122
+ * Match provider overflow errors, or infer overflow from reported context usage.
123
+ * A context window enables silent-overflow detection; silent truncation without
124
+ * a length stop remains undetectable because the original token count is unknown.
180
125
  */
181
126
  function isContextOverflow(message, contextWindow) {
182
127
  if (isProviderRefusalAssistantError(message)) return false;
@@ -1,6 +1,6 @@
1
- import { D as Message, G as SimpleStreamOptions, O as Model, Q as ThinkingBudgets, Y as StreamOptions, a as AssistantMessage, et as ThinkingLevel, n as Api } from "../types-qZFbaDbK.mjs";
2
- import { a as readAssistantThinkingAppend } from "../event-stream-CjnIZZst.mjs";
3
- import "../types-DTvddOfm.mjs";
1
+ import { D as Message, G as SimpleStreamOptions, O as Model, Q as ThinkingBudgets, Y as StreamOptions, a as AssistantMessage, et as ThinkingLevel, n as Api } from "../types-CLLR3eB4.mjs";
2
+ import { a as readAssistantThinkingAppend } from "../event-stream-DOPFYVqs.mjs";
3
+ import "../types-CB-_vNyI.mjs";
4
4
  import { t as sanitizeSurrogates } from "../sanitize-unicode-BZiVbGwK.mjs";
5
5
  import { i as projectProviderError } from "../provider-error-xumb1V3F.mjs";
6
6
  import { n as createDiagnosticRecord } from "../credential-redaction-BKv49aiv.mjs";
@@ -21,15 +21,6 @@ export declare function adjustMaxTokensForThinking(baseMaxTokens: number | undef
21
21
  };
22
22
  //#endregion
23
23
  //#region packages/ai/src/providers/tool-result-text.d.ts
24
- /** Media metadata alone is not an attachment; provider emitters need inline bytes. */
25
- export declare function hasMediaPayload(block: unknown): block is Record<string, unknown> & {
26
- data: string;
27
- };
28
- /** Image metadata alone is not an attachment; provider emitters need inline bytes. */
29
- export declare function isImageWithMediaPayload<T>(block: T): block is T & {
30
- type: "image";
31
- data: string;
32
- };
33
24
  export declare function describeToolResultMediaPlaceholder(blocks: readonly unknown[]): string | undefined;
34
25
  export declare function extractToolResultBlockText(block: unknown): string | undefined;
35
26
  export declare function extractToolResultText(blocks: readonly unknown[], options?: {
@@ -48,6 +39,17 @@ export declare function formatToolResultText(params: {
48
39
  isError: boolean;
49
40
  }): string;
50
41
  //#endregion
42
+ //#region packages/ai/src/media-payload.d.ts
43
+ /** Media metadata alone is not an attachment; provider emitters need inline bytes. */
44
+ export declare function hasMediaPayload(block: unknown): block is Record<string, unknown> & {
45
+ data: string;
46
+ };
47
+ /** Image metadata alone is not an attachment; provider emitters need inline bytes. */
48
+ export declare function isImageWithMediaPayload<T>(block: T): block is T & {
49
+ type: "image";
50
+ data: string;
51
+ };
52
+ //#endregion
51
53
  //#region packages/ai/src/transcript-transform.d.ts
52
54
  export declare function transformMessages<TApi extends Api>(messages: Message[], model: Model<TApi>, normalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string): Message[];
53
55
  //#endregion
@@ -1,7 +1,8 @@
1
- import { o as readAssistantThinkingAppend } from "../event-stream-D8PARQfL.mjs";
2
- import { _ as isImageWithMediaPayload, a as FAILED_ASSISTANT_REPLAY_TEXT, c as isReasoningOnlyLengthAssistantTurn, d as describeToolResultMediaPlaceholder, f as describeUnsupportedToolResultMedia, g as hasMediaPayload, h as formatToolResultText, i as transformMessages, l as isStreamErrorFallbackContent, m as extractToolResultText, o as STREAM_ERROR_FALLBACK_TEXT, p as extractToolResultBlockText, s as hasOnlyAssistantReasoningContent, u as resolveFailedAssistantReplay, v as sanitizeSurrogates } from "../host-yTvBrYM2.mjs";
3
- import { n as projectProviderError, r as createDiagnosticRecord } from "../provider-error-CRhW7lkJ.mjs";
4
- import { _ as normalizeStructuredPromptSection, c as SYSTEM_PROMPT_RELOCATABLE_BOUNDARY, d as prependSystemPromptAdditionAfterCacheBoundary, f as splitSystemPromptCacheBoundary, g as normalizePromptCapabilityIds, h as stripSystemPromptRelocatableBoundary, i as clampReasoning, l as SYSTEM_PROMPT_RELOCATABLE_BOUNDARY_END, m as stripSystemPromptCacheBoundary, n as buildBaseOptions, p as splitSystemPromptRelocatableBoundary, r as clampMaxTokensToModel, s as SYSTEM_PROMPT_CACHE_BOUNDARY, t as adjustMaxTokensForThinking, u as ensureSystemPromptCacheBoundary, v as sortPromptCacheToolsByName } from "../simple-options-np1XPuhm.mjs";
1
+ import { o as readAssistantThinkingAppend } from "../event-stream-vd9UnCAU.mjs";
2
+ import { O as hasMediaPayload, a as FAILED_ASSISTANT_REPLAY_TEXT, c as isReasoningOnlyLengthAssistantTurn, i as transformMessages, k as isImageWithMediaPayload, l as isStreamErrorFallbackContent, o as STREAM_ERROR_FALLBACK_TEXT, s as hasOnlyAssistantReasoningContent, u as resolveFailedAssistantReplay } from "../host-DwBmNMCC.mjs";
3
+ import { n as projectProviderError, r as createDiagnosticRecord } from "../provider-error-CwT_j2v0.mjs";
4
+ import { j as sanitizeSurrogates } from "../transport-stream-shared-BU5pwY6W.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-BkDPMuxw.mjs";
5
6
  import { t as projectCopilotRequestFacts } from "../github-copilot-request-facts-BTEBMeOv.mjs";
6
7
  //#region packages/ai/src/utils/tls-certificate-errors.ts
7
8
  const HOSTNAME_MISMATCH_CODES = /* @__PURE__ */ new Set(["ERR_TLS_CERT_ALTNAME_INVALID", "HOSTNAME_MISMATCH"]);
@@ -1,4 +1,4 @@
1
- import { a as resolveOpenAIProjectedToolsStrictToolFlag, i as normalizeStrictOpenAIJsonSchema, n as isStrictOpenAIJsonSchemaCompatible, o as findOpenAIStrictSchemaViolations, r as normalizeOpenAIStrictToolParameters, s as normalizeOpenAIStrictCompatSchema, t as findOpenAIStrictToolProjectionDiagnostics } from "../openai-tool-schema-ynZBgqW-.mjs";
1
+ import { a as resolveOpenAIProjectedToolsStrictToolFlag, i as normalizeStrictOpenAIJsonSchema, n as isStrictOpenAIJsonSchemaCompatible, o as findOpenAIStrictSchemaViolations, r as normalizeOpenAIStrictToolParameters, s as normalizeOpenAIStrictCompatSchema, t as findOpenAIStrictToolProjectionDiagnostics } from "../openai-tool-schema-a5ysBBga.mjs";
2
2
  import { TSchema } from "typebox";
3
3
  //#region packages/ai/src/providers/agent-tools-parameter-schema.d.ts
4
4
  /**
@@ -1,3 +1,3 @@
1
- import { n as projectRuntimeToolInputSchema } from "../tool-schema-json-projection-CD9c_fK8.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-D4BMcj2D.mjs";
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-vsl-cE-n.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,12 +1,11 @@
1
- import { r as appendAssistantThinking, t as AssistantMessageEventStream } from "./event-stream-D8PARQfL.mjs";
2
- import { M as calculateCost, N as clampThinkingLevel, _ as isImageWithMediaPayload, d as describeToolResultMediaPlaceholder, h as formatToolResultText, m as extractToolResultText, n as getAiTransportHost, v as sanitizeSurrogates } from "./host-yTvBrYM2.mjs";
3
- import { m as stripSystemPromptCacheBoundary, n as buildBaseOptions, r as clampMaxTokensToModel, v as sortPromptCacheToolsByName } from "./simple-options-np1XPuhm.mjs";
4
- import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
5
- import { E as parseStreamingJson, O as shortHash, c as finalizeTerminalToolCallArguments, n as assignTransportErrorDetails, p as notifyProviderHttpResponse, v as transportAbortError, w as createToolArgumentPreviewSchedule } from "./transport-stream-shared-B5RioB_Q.mjs";
1
+ import { r as appendAssistantThinking, t as AssistantMessageEventStream } from "./event-stream-vd9UnCAU.mjs";
2
+ import { T as clampThinkingLevel, k as isImageWithMediaPayload, n as getAiTransportHost, w as calculateCost } from "./host-DwBmNMCC.mjs";
3
+ import { A as shortHash, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, j as sanitizeSurrogates, l as finalizeTerminalToolCallArguments, m as notifyProviderHttpResponse, n as assignTransportErrorDetails, u as finalizeTransportStream } from "./transport-stream-shared-BU5pwY6W.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-BkDPMuxw.mjs";
5
+ import { n as getEnvApiKey } from "./env-api-keys-CyX4VKGO.mjs";
6
6
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
7
- import { t as createAssistantOutput } from "./assistant-output-DM1JBNs1.mjs";
8
- import { t as transformProviderMessages } from "./provider-transcript-transform-BTocjCRs.mjs";
9
- import { t as mapOpenAIStopReason } from "./openai-stop-reason-Drnn_6Qj.mjs";
7
+ import { n as createAssistantOutput, t as transformProviderMessages } from "./provider-transcript-transform-DjA5Fk2P.mjs";
8
+ import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
10
9
  import { t as createSseByteGuard } from "./streaming-byte-guard-CC-HMn_u.mjs";
11
10
  import { randomUUID } from "node:crypto";
12
11
  import { HTTPClient } from "@mistralai/mistralai/lib/http";
@@ -15,17 +14,7 @@ import { Chat } from "@mistralai/mistralai/sdk/chat";
15
14
  //#region packages/ai/src/providers/mistral.ts
16
15
  const MISTRAL_TOOL_CALL_ID_LENGTH = 9;
17
16
  const MISTRAL_STREAM_BODY_MAX_BYTES = 16777216;
18
- /**
19
- * Builds a `Fetcher` that wraps the default `fetch` with a 16 MiB byte cap
20
- * on streamed response bodies. The wrapped `Response.body` exposes a
21
- * `ReadableStream` whose chunks flow through `createSseByteGuard`, so the
22
- * SDK's internal SSE parser (`EventStream` in
23
- * `@mistralai/mistralai/lib/event-streams.ts`) reads exactly as it would on
24
- * an unbounded body — but bounded.
25
- *
26
- * Bodyless responses (no `body` or no `getReader`) are returned unchanged so
27
- * the SDK's error-path `res.arrayBuffer()` call still works.
28
- */
17
+ /** Cap the SDK's response reader while preserving bodyless error responses. */
29
18
  function createBoundedMistralFetcher(maxBytes = MISTRAL_STREAM_BODY_MAX_BYTES, upstreamFetch = fetch) {
30
19
  return async (input, init) => {
31
20
  const response = init == null ? await upstreamFetch(input) : await upstreamFetch(input, init);
@@ -55,9 +44,6 @@ function createBoundedMistralFetcher(maxBytes = MISTRAL_STREAM_BODY_MAX_BYTES, u
55
44
  });
56
45
  };
57
46
  }
58
- /**
59
- * Stream responses from Mistral using `chat.stream`.
60
- */
61
47
  const streamMistral = (model, context, options) => {
62
48
  const stream = new AssistantMessageEventStream();
63
49
  (async () => {
@@ -87,7 +73,7 @@ const streamMistral = (model, context, options) => {
87
73
  retryConfig: { strategy: "none" }
88
74
  });
89
75
  const normalizeMistralToolCallId = createMistralToolCallIdNormalizer();
90
- let payload = buildChatPayload(model, context, transformProviderMessages(context.messages, model, (id) => normalizeMistralToolCallId(id)), options);
76
+ let payload = buildChatPayload(model, context, transformProviderMessages(context.messages, model, normalizeMistralToolCallId), options);
91
77
  const nextPayload = await options?.onPayload?.(payload, model);
92
78
  if (nextPayload !== void 0) payload = nextPayload;
93
79
  const headers = {
@@ -110,14 +96,11 @@ const streamMistral = (model, context, options) => {
110
96
  partial: output
111
97
  });
112
98
  await consumeChatStream(model, output, stream, mistralStream, options?.signal);
113
- if (options?.signal?.aborted) throw transportAbortError(options.signal);
114
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
115
- stream.push({
116
- type: "done",
117
- reason: output.stopReason,
118
- message: output
99
+ finalizeTransportStream({
100
+ stream,
101
+ output,
102
+ signal: options?.signal
119
103
  });
120
- stream.end();
121
104
  } catch (error) {
122
105
  const terminal = assignTransportErrorDetails(output, error, options?.signal);
123
106
  output.content = output.content.filter((block) => block.type !== "toolCall");
@@ -131,9 +114,6 @@ const streamMistral = (model, context, options) => {
131
114
  })();
132
115
  return stream;
133
116
  };
134
- /**
135
- * Maps provider-agnostic `SimpleStreamOptions` to Mistral options.
136
- */
137
117
  const streamSimpleMistral = (model, context, options) => {
138
118
  const apiKey = options?.apiKey || getEnvApiKey(model.provider);
139
119
  if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
@@ -231,6 +211,10 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
231
211
  return candidates;
232
212
  };
233
213
  const intersectCandidates = (left, right) => new Set([...left].filter((contentIndex) => right.has(contentIndex)));
214
+ const filterIdentityCandidates = (candidates, matches) => new Set([...candidates].filter((contentIndex) => {
215
+ const identity = toolBlockIdentities.get(contentIndex);
216
+ return identity !== void 0 && matches(identity);
217
+ }));
234
218
  const requireSingleCandidate = (candidates) => {
235
219
  if (candidates.size > 1) throw new Error("Mistral streamed tool-call continuation is ambiguous; refusing to merge arguments");
236
220
  return candidates.values().next().value;
@@ -252,30 +236,18 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
252
236
  return requireExistingCandidate(candidates);
253
237
  }
254
238
  if (nameCandidates.size > 0) {
255
- const idCompatibleCandidates = new Set([...nameCandidates].filter((contentIndex) => {
256
- const identity = toolBlockIdentities.get(contentIndex);
257
- if (!identity) return false;
258
- return !explicitId || identity.explicitIds.size === 0;
259
- }));
239
+ const idCompatibleCandidates = filterIdentityCandidates(nameCandidates, (identity) => !explicitId || identity.explicitIds.size === 0);
260
240
  if (idCompatibleCandidates.size <= 1 && (toolCallIndex === void 0 || toolCallIndex === 0)) return requireSingleCandidate(idCompatibleCandidates);
261
- const indexCompatibleCandidates = new Set([...idCompatibleCandidates].filter((contentIndex) => {
262
- const identity = toolBlockIdentities.get(contentIndex);
263
- if (!identity) return false;
264
- return toolCallIndex === void 0 || identity.indexes.size === 0 || identity.indexes.has(toolCallIndex);
265
- }));
266
- if (indexCompatibleCandidates.size === 0) return;
241
+ const indexCompatibleCandidates = filterIdentityCandidates(idCompatibleCandidates, (identity) => toolCallIndex === void 0 || identity.indexes.size === 0 || identity.indexes.has(toolCallIndex));
267
242
  return requireSingleCandidate(indexCompatibleCandidates);
268
243
  }
269
244
  const indexCandidates = toolCallIndex === void 0 ? /* @__PURE__ */ new Set() : findIdentityCandidates((identity) => identity.indexes.has(toolCallIndex), params.usedContentIndexes);
270
245
  if (functionName) {
271
- const namelessCandidates = new Set([...indexCandidates].filter((contentIndex) => {
272
- const identity = toolBlockIdentities.get(contentIndex);
273
- return identity?.functionNames.size === 0 && (!explicitId || identity.explicitIds.size === 0);
274
- }));
246
+ const namelessCandidates = filterIdentityCandidates(indexCandidates, (identity) => identity.functionNames.size === 0 && (!explicitId || identity.explicitIds.size === 0));
275
247
  return requireSingleCandidate(namelessCandidates);
276
248
  }
277
249
  if (explicitId) {
278
- const idlessCandidates = new Set([...indexCandidates].filter((contentIndex) => toolBlockIdentities.get(contentIndex)?.explicitIds.size === 0));
250
+ const idlessCandidates = filterIdentityCandidates(indexCandidates, (identity) => identity.explicitIds.size === 0);
279
251
  return requireSingleCandidate(idlessCandidates);
280
252
  }
281
253
  return requireSingleCandidate(indexCandidates);
@@ -298,6 +270,29 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
298
270
  partial: output
299
271
  });
300
272
  };
273
+ const appendTextDelta = (text) => {
274
+ const textDelta = sanitizeSurrogates(text);
275
+ if (!currentBlock || currentBlock.type !== "text") {
276
+ finishCurrentBlock(currentBlock);
277
+ currentBlock = {
278
+ type: "text",
279
+ text: ""
280
+ };
281
+ output.content.push(currentBlock);
282
+ stream.push({
283
+ type: "text_start",
284
+ contentIndex: blockIndex(),
285
+ partial: output
286
+ });
287
+ }
288
+ currentBlock.text += textDelta;
289
+ stream.push({
290
+ type: "text_delta",
291
+ contentIndex: blockIndex(),
292
+ delta: textDelta,
293
+ partial: output
294
+ });
295
+ };
301
296
  for await (const event of mistralStream) {
302
297
  notifyLlmRequestActivity(signal);
303
298
  const chunk = event.data;
@@ -326,27 +321,7 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
326
321
  const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content;
327
322
  for (const item of contentItems) {
328
323
  if (typeof item === "string") {
329
- const textDelta = sanitizeSurrogates(item);
330
- if (!currentBlock || currentBlock.type !== "text") {
331
- finishCurrentBlock(currentBlock);
332
- currentBlock = {
333
- type: "text",
334
- text: ""
335
- };
336
- output.content.push(currentBlock);
337
- stream.push({
338
- type: "text_start",
339
- contentIndex: blockIndex(),
340
- partial: output
341
- });
342
- }
343
- currentBlock.text += textDelta;
344
- stream.push({
345
- type: "text_delta",
346
- contentIndex: blockIndex(),
347
- delta: textDelta,
348
- partial: output
349
- });
324
+ appendTextDelta(item);
350
325
  continue;
351
326
  }
352
327
  if (item.type === "thinking") {
@@ -375,29 +350,7 @@ async function consumeChatStream(model, output, stream, mistralStream, signal) {
375
350
  });
376
351
  continue;
377
352
  }
378
- if (item.type === "text") {
379
- const textDelta = sanitizeSurrogates(item.text);
380
- if (!currentBlock || currentBlock.type !== "text") {
381
- finishCurrentBlock(currentBlock);
382
- currentBlock = {
383
- type: "text",
384
- text: ""
385
- };
386
- output.content.push(currentBlock);
387
- stream.push({
388
- type: "text_start",
389
- contentIndex: blockIndex(),
390
- partial: output
391
- });
392
- }
393
- currentBlock.text += textDelta;
394
- stream.push({
395
- type: "text_delta",
396
- contentIndex: blockIndex(),
397
- delta: textDelta,
398
- partial: output
399
- });
400
- }
353
+ if (item.type === "text") appendTextDelta(item.text);
401
354
  }
402
355
  }
403
356
  const toolCalls = delta.toolCalls || [];
@@ -1,24 +1,25 @@
1
1
  import { i as formatThrownValue, n as createAssistantMessageDiagnostic, t as appendAssistantMessageDiagnostic } from "./diagnostics-DzrF1h4J.mjs";
2
- import { t as AssistantMessageEventStream } from "./event-stream-D8PARQfL.mjs";
3
- import { o as isRecord } from "./record-coerce-DwRYMj3t.mjs";
4
- import { d as supportsOpenAITemperature } from "./openai-reasoning-effort-ash8dPrd.mjs";
5
- import { A as headersToRecord, n as getAiTransportHost, r as resolveAiTransportHeaderSentinels } from "./host-yTvBrYM2.mjs";
6
- import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-CjV_2IRI.mjs";
7
- import { _ as extractErrorCodeOrErrno, o as WEBSOCKET_NON_RETRYABLE_CLOSE_ERROR_CODE, v as toErrorObject } from "./diagnostics-CH8j2wIG.mjs";
8
- import { s as resolveTimerTimeoutMs } from "./base64-CPmadnUf.mjs";
9
- import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-03Qi0CN2.mjs";
2
+ import { t as AssistantMessageEventStream } from "./event-stream-vd9UnCAU.mjs";
3
+ import { o as isRecord } from "./record-coerce-CNDovvft.mjs";
4
+ import { S as headersToRecord, n as getAiTransportHost, r as resolveAiTransportHeaderSentinels } from "./host-DwBmNMCC.mjs";
5
+ import { d as supportsOpenAITemperature } from "./openai-reasoning-effort-C_0p3psG.mjs";
6
+ import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-BTMs80_O.mjs";
7
+ import { _ as extractErrorCodeOrErrno, o as WEBSOCKET_NON_RETRYABLE_CLOSE_ERROR_CODE, v as toErrorObject } from "./diagnostics-CJaB6g8J.mjs";
8
+ import { s as resolveTimerTimeoutMs } from "./base64-C1PsYcRQ.mjs";
9
+ import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-CqXzku3R.mjs";
10
10
  import { parseRetryAfterHeadersSeconds } from "./internal/retry-after.mjs";
11
- import { m as stripSystemPromptCacheBoundary, n as buildBaseOptions } from "./simple-options-np1XPuhm.mjs";
12
- import { S as createResponseModelTracker, b as createOpenAIProviderAcceptanceHook, g as resolveOpenAISimpleReasoningEffort, h as resolveOpenAIRequestReasoning, x as createOpenAIResponseHook } from "./openai-transport-params-DZKOTSfH.mjs";
13
- import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
14
- import { b as withProviderResponseHook, m as notifyProviderStreamOpened, n as assignTransportErrorDetails, v as transportAbortError } from "./transport-stream-shared-B5RioB_Q.mjs";
15
- import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-BeptfRL6.mjs";
16
- import { h as responsesPromptObserver } from "./openai-responses-contracts-DWrfMODE.mjs";
17
- import { D as ResponsesStreamFailure, E as resolveNextResponsesEncryptedContentAttempt, M as recordResponsesContextUsage, S as commitResponsesEncryptedContentAttempt, Z as suppressOpenAIResponsesCompaction, c as readOpenAIMisalignmentReview, i as createResponsesAssistantOutput, l as processResponsesStream, n as applyResponsesServiceTierPricing, o as convertResponsesToolPayload, q as buildOpenAIResponsesReasoningReplayMetadata, r as convertResponsesMessages, w as isInvalidEncryptedContentError } from "./openai-responses-shared-DvSqtJ6_.mjs";
11
+ import { S as withProviderResponseHook, b as transportAbortError, h as notifyProviderStreamOpened, n as assignTransportErrorDetails } from "./transport-stream-shared-BU5pwY6W.mjs";
12
+ import { C as stripSystemPromptCacheBoundary, n as buildBaseOptions } from "./simple-options-BkDPMuxw.mjs";
13
+ import { b as createOpenAIResponseHook, g as resolveOpenAISimpleReasoningEffort, h as resolveOpenAIRequestReasoning, x as createResponseModelTracker, y as createOpenAIProviderAcceptanceHook } from "./openai-transport-params-DyFJ4cgR.mjs";
14
+ import { n as getEnvApiKey } from "./env-api-keys-CyX4VKGO.mjs";
15
+ import { n as createAssistantOutput } from "./provider-transcript-transform-DjA5Fk2P.mjs";
16
+ import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-B9o0S4SZ.mjs";
17
+ import { h as responsesPromptObserver } from "./openai-responses-contracts-CLxnqS9p.mjs";
18
+ import { A as recordResponsesContextUsage, P as convertProviderResponsesMessages, S as isInvalidEncryptedContentError, T as ResponsesStreamFailure, Z as suppressOpenAIResponsesCompaction, b as commitResponsesEncryptedContentAttempt, i as convertResponsesToolPayload, n as applyResponsesServiceTierPricing, o as readOpenAIMisalignmentReview, q as buildOpenAIResponsesReasoningReplayMetadata, s as processResponsesStream, w as resolveNextResponsesEncryptedContentAttempt } from "./openai-responses-shared-CIEHiKx7.mjs";
18
19
  import { t as createSseByteGuard } from "./streaming-byte-guard-CC-HMn_u.mjs";
19
20
  import { n as registerSessionResourceCleanup } from "./session-resources-CkR4WWy1.mjs";
20
- import { i as resolveOpenAIResponsesTextFormat, t as createResponsesPromptEgressObserver } from "./openai-responses-prompt-observer-internal-DPHWgbBH.mjs";
21
- import { n as withResponsesRequestAcceptance, t as responsesRequestLifecycle } from "./openai-responses-request-lifecycle-DFuyO1pQ.mjs";
21
+ import { i as resolveOpenAIResponsesTextFormat, t as createResponsesPromptEgressObserver } from "./openai-responses-prompt-observer-internal-BX3QTNSv.mjs";
22
+ import { n as withResponsesRequestAcceptance, t as responsesRequestLifecycle } from "./openai-responses-request-lifecycle-Fsag-IGZ.mjs";
22
23
  import { n as resolveOpenAICodexAccountId } from "./openai-chatgpt-jwt-KWcgd0d_.mjs";
23
24
  //#region packages/ai/src/providers/openai-chatgpt-responses-events.ts
24
25
  var CodexApiError = class extends Error {
@@ -205,7 +206,7 @@ const streamOpenAICodexResponses = (model, context, options) => {
205
206
  let requestTimeoutSignal;
206
207
  let activeSignal;
207
208
  let firstEventAbort;
208
- const output = createResponsesAssistantOutput(model);
209
+ const output = createAssistantOutput(model);
209
210
  try {
210
211
  const unresolvedApiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
211
212
  if (!unresolvedApiKey) throw new Error(`No API key for provider: ${model.provider}`);
@@ -436,7 +437,7 @@ const streamSimpleOpenAICodexResponses = (model, context, options) => {
436
437
  return streamOpenAICodexResponses(model, context, resolvedOptions);
437
438
  };
438
439
  function buildRequestBody(model, context, options, replayMode = "checkpoint") {
439
- const messages = convertResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {
440
+ const messages = convertProviderResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {
440
441
  includeSystemPrompt: false,
441
442
  replayResponsesItemIds: false,
442
443
  sessionId: options?.sessionId,
@@ -490,9 +491,6 @@ function resolveCodexWebSocketUrl(baseUrl) {
490
491
  if (url.protocol === "http:") url.protocol = "ws:";
491
492
  return url.toString();
492
493
  }
493
- function isJsonRecord(value) {
494
- return value !== null && typeof value === "object" && !Array.isArray(value);
495
- }
496
494
  /**
497
495
  * Structured refusal code carried by the OpenAI Responses transport. Every
498
496
  * terminal Responses path preserves it: a non-OK HTTP body parsed by
@@ -503,8 +501,8 @@ function isJsonRecord(value) {
503
501
  */
504
502
  function readCodexProviderRefusal(error) {
505
503
  if (!(error instanceof ResponsesStreamFailure || error instanceof CodexApiError)) return;
506
- const payload = error instanceof CodexApiError ? error.payload : isJsonRecord(error.response) ? error.response : void 0;
507
- const nested = isJsonRecord(payload?.error) ? payload.error : void 0;
504
+ const payload = error instanceof CodexApiError ? error.payload : isRecord(error.response) ? error.response : void 0;
505
+ const nested = isRecord(payload?.error) ? payload.error : void 0;
508
506
  const codexErrorInfo = payload?.codexErrorInfo ?? nested?.codexErrorInfo;
509
507
  if (error.code === "cyber_policy" || codexErrorInfo === "cyberPolicy") return { category: "cyber" };
510
508
  if (error.code === "misalignment_policy_violation" || codexErrorInfo === "misalignmentPolicyViolation") {
@@ -863,9 +861,6 @@ function requestBodyWithoutInput(body) {
863
861
  const { input: _input, previous_response_id: _previousResponseId, ...rest } = body;
864
862
  return rest;
865
863
  }
866
- function responseInputsEqual(a, b) {
867
- return JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
868
- }
869
864
  function requestBodiesMatchExceptInput(a, b) {
870
865
  return JSON.stringify(requestBodyWithoutInput(a)) === JSON.stringify(requestBodyWithoutInput(b));
871
866
  }
@@ -874,7 +869,8 @@ function getCachedWebSocketInputDelta(body, continuation) {
874
869
  const currentInput = body.input ?? [];
875
870
  const baseline = [...continuation.lastRequestBody.input ?? [], ...continuation.lastResponseItems];
876
871
  if (currentInput.length < baseline.length) return;
877
- if (!responseInputsEqual(currentInput.slice(0, baseline.length), baseline)) return;
872
+ const prefix = currentInput.slice(0, baseline.length);
873
+ if (JSON.stringify(prefix) !== JSON.stringify(baseline)) return;
878
874
  return currentInput.slice(baseline.length);
879
875
  }
880
876
  function buildCachedWebSocketRequestBody(entry, body) {
@@ -951,7 +947,7 @@ async function processWebSocketStream(url, body, headers, output, stream, model,
951
947
  });
952
948
  if (options?.signal?.aborted) keepConnection = false;
953
949
  else if (useCachedContext && entry && output.responseId) {
954
- const responseItems = convertResponsesMessages(model, { messages: [output] }, CODEX_TOOL_CALL_PROVIDERS, {
950
+ const responseItems = convertProviderResponsesMessages(model, { messages: [output] }, CODEX_TOOL_CALL_PROVIDERS, {
955
951
  includeSystemPrompt: false,
956
952
  replayResponsesItemIds: false,
957
953
  sessionId: options?.sessionId,
@@ -1029,7 +1025,7 @@ function parseErrorResponse(raw, response) {
1029
1025
  let payload;
1030
1026
  try {
1031
1027
  const parsed = JSON.parse(raw);
1032
- payload = isJsonRecord(parsed) ? parsed : void 0;
1028
+ payload = isRecord(parsed) ? parsed : void 0;
1033
1029
  const err = parsed?.error;
1034
1030
  if (err) {
1035
1031
  code = err.code || err.type || void 0;
@@ -1,19 +1,19 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { t as AssistantMessageEventStream } from "./event-stream-D8PARQfL.mjs";
3
- import { N as clampThinkingLevel } from "./host-yTvBrYM2.mjs";
4
- import { i as resolveOpenAICompletionsCompat } from "./openai-completions-compat-CUollwl6.mjs";
2
+ import { t as AssistantMessageEventStream } from "./event-stream-vd9UnCAU.mjs";
3
+ import { T as clampThinkingLevel } from "./host-DwBmNMCC.mjs";
4
+ import { i as resolveOpenAICompletionsCompat } from "./openai-completions-compat-BJf57ZxN.mjs";
5
5
  import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
6
- import { n as buildBaseOptions, o as reasoningTagTextPolicy } from "./simple-options-np1XPuhm.mjs";
7
- import { C as isOpenAICompletionsThinkingEnabled, b as createOpenAIProviderAcceptanceHook } from "./openai-transport-params-DZKOTSfH.mjs";
8
- import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
9
- import { b as withProviderResponseHook, n as assignTransportErrorDetails, v as transportAbortError } from "./transport-stream-shared-B5RioB_Q.mjs";
6
+ import { S as withProviderResponseHook, b as transportAbortError, n as assignTransportErrorDetails } from "./transport-stream-shared-BU5pwY6W.mjs";
7
+ import { n as buildBaseOptions, s as prepareModelRequestBody, u as reasoningTagTextPolicy } from "./simple-options-BkDPMuxw.mjs";
8
+ import { S as isOpenAICompletionsThinkingEnabled, y as createOpenAIProviderAcceptanceHook } from "./openai-transport-params-DyFJ4cgR.mjs";
9
+ import { n as getEnvApiKey } from "./env-api-keys-CyX4VKGO.mjs";
10
10
  import { a as tagUnresolvedTextAsCommentary, t as clearPendingCommentaryText } from "./assistant-text-phase-C20rxWwP.mjs";
11
- import { t as createAssistantOutput } from "./assistant-output-DM1JBNs1.mjs";
12
- import { a as convertMessages, i as buildOpenAICompletionsRequest, s as finalizeOpenAICompletionsToolCalls, t as processCompletionsStream } from "./openai-completions-stream-BpuJ0ZOA.mjs";
13
- import { i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-BeptfRL6.mjs";
14
- import { n as resolveProviderSimpleCompletionHeaders } from "./provider-transport-turn-state-lrXEFkYr.mjs";
11
+ import { n as createAssistantOutput } from "./provider-transcript-transform-DjA5Fk2P.mjs";
12
+ import { a as convertMessages, i as buildOpenAICompletionsRequest, s as finalizeOpenAICompletionsToolCalls, t as processCompletionsStream } from "./openai-completions-stream-dju_5F3P.mjs";
13
+ import { i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-B9o0S4SZ.mjs";
14
+ import { n as resolveProviderSimpleCompletionHeaders } from "./provider-transport-turn-state-Dw7OtYUs.mjs";
15
15
  import { n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-B37TB3rB.mjs";
16
- import { t as createOpenAIProviderClient } from "./openai-provider-client-BP8J1aeg.mjs";
16
+ import { t as createOpenAIProviderClient } from "./openai-provider-client-G8Otsq2Q.mjs";
17
17
  //#region packages/ai/src/providers/openai-completions.ts
18
18
  var openai_completions_exports = /* @__PURE__ */ __exportAll({
19
19
  convertMessages: () => convertMessages,
@@ -38,10 +38,12 @@ const streamOpenAICompletions = (model, context, options) => {
38
38
  compat,
39
39
  cacheRetention
40
40
  });
41
+ const encodeBody = prepareModelRequestBody(options);
41
42
  const nextParams = await options?.onPayload?.(params, model);
42
43
  if (nextParams !== void 0) params = nextParams;
43
44
  firstEventAbort = createFirstStreamEventAbortController(options?.signal);
44
45
  const requestOptions = {
46
+ ...await encodeBody(params),
45
47
  signal: firstEventAbort.signal,
46
48
  ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
47
49
  maxRetries: 0
@@ -1,5 +1,5 @@
1
- import { o as isRecord } from "./record-coerce-DwRYMj3t.mjs";
2
- import { a as resolveProviderRequestCapabilities } from "./host-policy-DZO3oPPk.mjs";
1
+ import { o as isRecord } from "./record-coerce-CNDovvft.mjs";
2
+ import { i as resolveProviderRequestCapabilities } from "./host-policy-wK-ay_RK.mjs";
3
3
  //#region packages/ai/src/providers/openai-response-format.ts
4
4
  const JSON_SCHEMA_RESPONSE_FORMAT_NAME = "openclaw_response";
5
5
  const OLLAMA_CLOUD_ORIGIN = "https://ollama.com";
@@ -28,9 +28,7 @@ function shouldOmitOllamaCompatResponseFormat(params) {
28
28
  */
29
29
  function resolveOpenAICompletionsResponseFormat(responseFormat, supportsJsonSchemaResponseFormat) {
30
30
  if (!responseFormat) return;
31
- if (responseFormat.type === "json_object") return responseFormat;
32
- if (responseFormat.type === "text") return responseFormat;
33
- if (responseFormat.type === "json_schema" && isRecord(responseFormat.json_schema)) return responseFormat;
31
+ if (responseFormat.type === "json_object" || responseFormat.type === "text" || responseFormat.type === "json_schema" && isRecord(responseFormat.json_schema)) return responseFormat;
34
32
  if (!supportsJsonSchemaResponseFormat) return;
35
33
  return {
36
34
  type: "json_schema",
@@ -1,6 +1,6 @@
1
- import "./index-C25RT6bP.mjs";
2
- import { M as OpenAICompletionsCompat, O as Model } from "./types-qZFbaDbK.mjs";
3
- import { a as AiProviderRequestPolicyInput, i as AiProviderRequestCapabilities } from "./host-DH-Z-LDb.mjs";
1
+ import "./index-D6KsSE74.mjs";
2
+ import { M as OpenAICompletionsCompat, O as Model } from "./types-CLLR3eB4.mjs";
3
+ import { a as AiProviderRequestPolicyInput, i as AiProviderRequestCapabilities } from "./host-rxlNaBwm.mjs";
4
4
  //#region packages/ai/src/transports/openai-completions-compat.d.ts
5
5
  type ProviderRequestCapabilities = AiProviderRequestCapabilities;
6
6
  type OpenAICompletionsSessionAffinity = "none" | "openai" | "openrouter";