@openclaw/ai 2026.11.3 → 2026.11.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +11 -8
  2. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
  3. package/dist/anthropic-DEKgalVg.mjs +182 -0
  4. package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
  5. package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
  6. package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
  7. package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
  8. package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
  9. package/dist/assistant-output-CD4kY9gu.mjs +16 -0
  10. package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
  11. package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
  12. package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
  13. package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
  14. package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
  15. package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
  16. package/dist/diagnostics.d.mts +6 -7
  17. package/dist/diagnostics.mjs +4 -4
  18. package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
  19. package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
  20. package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
  21. package/dist/event-stream.d.mts +2 -2
  22. package/dist/event-stream.mjs +1 -2
  23. package/dist/expect-lbe3Hgrh.mjs +8 -0
  24. package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
  25. package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
  26. package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
  27. package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
  28. package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
  29. package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
  30. package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
  31. package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
  32. package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
  33. package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
  34. package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
  35. package/dist/index-Bczt0MnO.d.mts +17 -0
  36. package/dist/index.d.mts +8 -7
  37. package/dist/index.mjs +9 -7
  38. package/dist/internal/anthropic.d.mts +21 -26
  39. package/dist/internal/anthropic.mjs +6 -6
  40. package/dist/internal/google-model-family.mjs +1 -1
  41. package/dist/internal/google.d.mts +15 -0
  42. package/dist/internal/google.mjs +1 -0
  43. package/dist/internal/model-request-body.d.mts +37 -0
  44. package/dist/internal/model-request-body.mjs +106 -0
  45. package/dist/internal/openai-completions-compat.d.mts +1 -1
  46. package/dist/internal/openai-completions-compat.mjs +1 -1
  47. package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
  48. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  49. package/dist/internal/openai.d.mts +14 -12
  50. package/dist/internal/openai.mjs +11 -10
  51. package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
  52. package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
  53. package/dist/internal/retry-after.d.mts +2 -2
  54. package/dist/internal/retry-after.mjs +96 -32
  55. package/dist/internal/runtime.d.mts +15 -41
  56. package/dist/internal/runtime.mjs +9 -10
  57. package/dist/internal/shared.d.mts +21 -25
  58. package/dist/internal/shared.mjs +9 -98
  59. package/dist/internal/tool-schema.d.mts +10 -10
  60. package/dist/internal/tool-schema.mjs +4 -4
  61. package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
  62. package/dist/mistral-CjHkvsqR.mjs +3741 -0
  63. package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
  64. package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
  65. package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
  66. package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
  67. package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
  68. package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
  69. package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
  70. package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
  71. package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
  72. package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
  73. package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
  74. package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
  75. package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
  76. package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
  77. package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
  78. package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
  79. package/dist/openai-responses-ev_c6oTy.mjs +89 -0
  80. package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
  81. package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
  82. package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
  83. package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
  84. package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
  85. package/dist/otel-Buswj0Mf.mjs +766 -0
  86. package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
  87. package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
  88. package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
  89. package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
  90. package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
  91. package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
  92. package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
  93. package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
  94. package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
  95. package/dist/provider-types.d.mts +7 -6
  96. package/dist/providers.d.mts +2 -2
  97. package/dist/providers.mjs +26 -29
  98. package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
  99. package/dist/request-headers-DO4Mqhw1.mjs +10 -0
  100. package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
  101. package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
  102. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  103. package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
  104. package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
  105. package/dist/src-BUsVkrNt.mjs +105 -0
  106. package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
  107. package/dist/stable-stringify-CchQEmeA.mjs +84 -0
  108. package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
  109. package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
  110. package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
  111. package/dist/string-normalization-B8TDDBX_.mjs +32 -0
  112. package/dist/telemetry-CvK1yQg7.mjs +582 -0
  113. package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
  114. package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
  115. package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
  116. package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
  117. package/dist/transports.d.mts +42 -39
  118. package/dist/transports.mjs +215 -296
  119. package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
  120. package/dist/types-Cb3-5WM9.d.mts +1 -0
  121. package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
  122. package/dist/types.d.mts +7 -6
  123. package/dist/types.mjs +7 -5
  124. package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
  125. package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
  126. package/dist/validation.d.mts +1 -1
  127. package/dist/validation.mjs +1 -2
  128. package/package.json +40 -6
  129. package/dist/anthropic-lueA8LUg.mjs +0 -221
  130. package/dist/assistant-output-BnQm3fov.mjs +0 -47
  131. package/dist/event-stream-CDpFza-M.d.mts +0 -1
  132. package/dist/index-DSprYWaz.d.mts +0 -185
  133. package/dist/mistral-CQ7aoWg2.mjs +0 -512
  134. package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
  135. package/dist/openai-CiRi-nVE.mjs +0 -20077
  136. package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
  137. package/dist/openai-responses-DQsZKUoI.mjs +0 -87
  138. package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
  139. package/dist/types-CBJthzJX.d.mts +0 -1
  140. package/dist/ws.LICENSE +0 -20
@@ -0,0 +1,3406 @@
1
+ import "./src-CQ7nH2mL.mjs";
2
+ import { m as isRuntimeContextMessage, p as hasRuntimeContextMarker, v as runtimeContextContentToText } from "./types-OVEWUaDh.mjs";
3
+ import { s as recordSuppressedReasoning, t as appendAssistantMessageDiagnostic } from "./diagnostics-o1PrVNQb.mjs";
4
+ import { t as omitNullRequestHeaders } from "./request-headers-DO4Mqhw1.mjs";
5
+ import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
6
+ import { i as asOptionalRecord, o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-BQaoiN3r.mjs";
7
+ import { c as readNonEmptyStringPreservingWhitespace, t as hasNonEmptyString } from "./string-coerce-BCuWMIrk.mjs";
8
+ import { n as asNonNegativeFiniteNumber, r as asPositiveFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
9
+ import { N as isImageWithMediaPayload, O as calculateCost, a as resolveAiTransportHeaderSentinels, r as getAiTransportHost } from "./host-DX7ORpeH.mjs";
10
+ import { E as isOpenAIGpt6Model, N as supportsOpenAITemperature, R as resolveOpenAIThinkingApi, S as applyOpenAICompletionsToolReasoning, _ as parseOpenAIResponsesWebSocketServerError, b as isResponsesServiceTierRejection, d as OpenAIResponsesWebSocketPreDispatchError, f as OpenAIResponsesWebSocketSafeRetryError, g as isResponsesTerminalEventType, l as OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, r as OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS, t as AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS, u as OpenAIResponsesWebSocketPostDispatchError, x as nextResponsesServiceTier, y as responsesServiceTierObserver } from "./openai-responses-contracts-xU-n9AJJ.mjs";
11
+ import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-vKvGIE3J.mjs";
12
+ import { c as truncateUtf16Safe } from "./provider-error-DD-fo4Rz.mjs";
13
+ import { t as estimateStringChars } from "./src-BUsVkrNt.mjs";
14
+ import { r as resolveOpenAIPromptCacheParams } from "./openai-prompt-cache-CgDoFhO0.mjs";
15
+ import { g as applyResponsesCacheWritePricing, p as hasOnlyResponsesFunctionTools, r as emitModelTransportDebug, t as formatModelTransportDebugBaseUrl, u as DegenerateToolCallArgumentsError, v as mapResponsesTerminalUsage, y as readResponsesReasoningTokens } from "./diagnostics-CloVGQiK.mjs";
16
+ import { o as supportsModelTools } from "./transport-utils-Da_39MYi.mjs";
17
+ import { t as stableStringify } from "./stable-stringify-CchQEmeA.mjs";
18
+ import { t as createZeroUsage } from "./usage-CJH5D6Ea.mjs";
19
+ import { a as resolveOpenAICompletionsCompat, c as isAzureOpenAICompatibleHost, d as shouldOmitOllamaCompatResponseFormat, i as isOpenAICodexResponsesModel, l as resolveOpenAICompletionsResponseFormat, n as isKnownOpenAIEndpoint, r as isNativeOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, t as detectOpenAICompletionsCompat, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-CstlTQuF.mjs";
20
+ import { t as buildGuardedModelFetch } from "./host-policy-jCZebuXx.mjs";
21
+ import { i as resolveCacheRetention, r as buildCopilotDynamicHeaders } from "./cloudflare-BJ2_Xabx.mjs";
22
+ import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
23
+ import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-w-ICeyOI.mjs";
24
+ import { C as stripSystemPromptCacheBoundary, S as splitSystemPromptRelocatableBoundary, a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as measuredRequestPressure, f as preparedRequestSuffix, p as reasoningTagTextPolicy, r as clampMaxTokensToModel, u as codeModeToolSurfaceObserver, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary, y as prepareSystemPrompt } from "./simple-options-tLSeECry.mjs";
25
+ import { A as parseStreamingJson, C as withProviderResponseHook, D as shortHash, N as racePromiseWithAbortSignal, O as createToolArgumentPreviewSchedule, b as throwIfModelStreamAborted, c as failTransportStream, d as iterateModelStream, g as notifyProviderStreamOpened, l as finalizeTerminalToolCallArguments, o as createWritableTransportEventStream, u as finalizeTransportStream, x as transportAbortError } from "./transport-stream-shared-D2uFMhMc.mjs";
26
+ import { C as sha256Hex, S as redactIdentifier } from "./tool-schema-json-projection-BQpiJlXJ.mjs";
27
+ import { n as getEnvApiKey } from "./env-api-keys-BuHc86ya.mjs";
28
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
29
+ import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-xyU7-CiT.mjs";
30
+ import { t as transformProviderMessages } from "./provider-transcript-transform-DtaxNcC1.mjs";
31
+ import { prepareModelRequestBody } from "./internal/model-request-body.mjs";
32
+ import { PROVIDER_MODEL_INPUT, resolveProviderContext } from "./provider-types.mjs";
33
+ import { t as createAssistantOutput } from "./assistant-output-CD4kY9gu.mjs";
34
+ import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
35
+ import { isGoogleGemini3ThinkingLevelModel } from "./internal/google-model-family.mjs";
36
+ import "./types.mjs";
37
+ import { $ as isConfigurationUpdate, A as summarizeResponsesPayload, At as log, B as recordResponsesInputReplay, C as isInvalidEncryptedContentError, Ct as toOpenAIResponsesToolChoice, Dt as createResponseModelTracker, E as resolveNextResponsesEncryptedContentAttempt, Ft as resolveOpenAIClientBaseUrl, G as responsesContinuationPrefixFingerprint, H as claimOpenAIResponsesHttpContinuation, I as convertResponsesMessages, It as resolvePromptCacheKey, K as responsesContinuationRequestFingerprint, Lt as withOpenAIErrorResponseHook, Mt as parseOpenAICompletionsUsage, Nt as readOpenAICompletionsContentDeltas, O as observeResponsesTransportFailure, Ot as detachPartialSnapshot, P as buildResponsesInputMessage, Pt as readOpenAICompletionsReasoningBatch, S as createResponsesStreamWithRecovery, St as reconcileOpenAIResponsesToolChoice, T as resolveAzureOpenAIApiVersion, Tt as createOpenAIProviderAcceptanceHook, U as recordResponsesContinuationState, V as responsesInputFingerprint, W as resolveResponsesContinuationRequest, _t as resolveOpenAIRequestReasoning, a as prepareResponsesTools, bt as projectOpenAITools, c as observeResponsesStream, ct as buildOpenAIClientHeaders, dt as enforceCodeModeResponsesToolSurface, et as replayResponsesReasoningUpdates, gt as resolveOpenAIStrictToolFlagWithDiagnostics, ht as resolveCodeModeResponsesVisibleToolNames, j as recordResponsesContextUsage, jt as measureUtf8AppendBytes, k as safeDebugValue, kt as isOpenAICompletionsThinkingEnabled, lt as buildOpenAISdkClientOptions, n as applyResponsesServiceTierPricing, ot as suppressOpenAIResponsesCompaction, pt as getCompat, rt as buildOpenAIResponsesReasoningReplayMetadata, s as processResponsesStream, st as assertCodeModeResponsesToolSurface, tt as supportsResponsesReasoningUpdate, ut as buildOpenAISdkRequestOptions, vt as resolveOpenAISimpleReasoningEffort, w as readResponsesRecoveryEvent, wt as GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP, xt as reconcileOpenAICompletionsToolChoice, yt as prepareOpenAITools, z as readResponsesInputReplayState } from "./openai-responses-shared-BmRQnUPP.mjs";
38
+ import { i as createOpenAIProviderClient, n as resolveProviderSimpleCompletionHeaders, r as resolveProviderTransportTurnState, t as filterProviderTurnHeadersForExplicitOpencodeSession } from "./provider-transport-turn-state-BIS8maBK.mjs";
39
+ import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-B7RcufAV.mjs";
40
+ import { t as boundResponseBody } from "./streaming-byte-guard-DBXr1XYn.mjs";
41
+ import { m as withPreparedToolSchemaNormalization, p as normalizeToolSchema, r as normalizeOpenAIStrictToolParameters, x as prepareOpenAIFunctionTool } from "./openai-tool-schema-CsoYgnWy.mjs";
42
+ import { t as requiresReasoningContentReplay } from "./openai-completions-reasoning-replay-BwT1xwRI.mjs";
43
+ import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
44
+ import { i as resolveAzureDeploymentNameFromMap, t as isOpenAICompatibleAzureResponsesBaseUrl } from "./azure-openai-responses-client-compat-D0dvJMbZ.mjs";
45
+ import { a as isOpenAIResponsesCompactionOutput, c as sanitizeResponsesImagePayload, f as resolveOpenAIResponsesPayloadPolicy, i as getOpenAIResponsesCompactionOutputError, l as applyOpenAIResponsesPayloadPolicy, n as supportsNativeOpenAIResponsesEndpoint, r as createBoundedOpenAIResponsesCompactionFetch, t as isOfficialOpenAIResponsesBaseUrl } from "./openai-responses-endpoint-DCkURKS0.mjs";
46
+ import { a as createResponsesV2CompactionCollector, i as createResponsesPromptEgressObserver, n as responsesRequestLifecycle, o as claimResponsesCompactRequest, r as withResponsesRequestAcceptance, t as independentResponsesRequest } from "./openai-responses-request-lifecycle-BuOs0mwI.mjs";
47
+ import { randomUUID } from "node:crypto";
48
+ import { isDeepStrictEqual } from "node:util";
49
+ import OpenAI, { AzureOpenAI } from "openai";
50
+ import { ResponsesWS } from "openai/resources/responses/ws.js";
51
+ //#region packages/ai/src/transports/deepseek-dsml-grammar.ts
52
+ const DEEPSEEK_DSML_MARKERS = [
53
+ "|",
54
+ "|",
55
+ "||"
56
+ ].flatMap((bar) => [`${bar}DSML${bar}`, `${bar}DSML${bar} `]);
57
+ const DEEPSEEK_DSML_TOOL_OPEN_TOKENS = DEEPSEEK_DSML_MARKERS.flatMap((marker) => [
58
+ "calls",
59
+ "tool_calls",
60
+ "tool_call",
61
+ "function_calls"
62
+ ].map((kind) => `<${marker}${kind}>`));
63
+ const DEEPSEEK_DSML_MARKER_PATTERN = `(${DEEPSEEK_DSML_MARKERS.map((marker) => marker.replaceAll("|", "\\|")).join("|")})`;
64
+ function findEarliestDsmlToken(text, tokens, fromIndex = 0) {
65
+ let best = null;
66
+ for (const token of tokens) {
67
+ const index = text.indexOf(token, fromIndex);
68
+ if (index !== -1 && (!best || index < best.index)) best = {
69
+ index,
70
+ token
71
+ };
72
+ }
73
+ return best;
74
+ }
75
+ function longestDsmlTokenPrefixSuffixLength(text, tokens, maxTokenLength) {
76
+ const maxLength = Math.min(text.length, maxTokenLength - 1);
77
+ for (let length = maxLength; length > 0; length--) {
78
+ const suffix = text.slice(text.length - length);
79
+ if (tokens.some((token) => token.startsWith(suffix))) return length;
80
+ }
81
+ return 0;
82
+ }
83
+ //#endregion
84
+ //#region packages/ai/src/transports/deepseek-text-filter.ts
85
+ /**
86
+ * DeepSeek DSML streaming text filter.
87
+ * Removes provider-emitted DSML tool markup while buffering split tag prefixes
88
+ * across streamed chunks.
89
+ */
90
+ const DSML_OPEN_TOKENS = [...DEEPSEEK_DSML_TOOL_OPEN_TOKENS, ...DEEPSEEK_DSML_MARKERS.map((marker) => `<${marker}tool_use_error>`)];
91
+ const MAX_OPEN_TOKEN_LEN = Math.max(...DSML_OPEN_TOKENS.map((token) => token.length));
92
+ /** Create an incremental text filter that strips DeepSeek DSML tool blocks. */
93
+ function createDeepSeekTextFilter() {
94
+ let buffer = "";
95
+ let closeToken;
96
+ const consume = (final) => {
97
+ const output = [];
98
+ const emit = (text) => {
99
+ if (text) output.push(text);
100
+ };
101
+ while (buffer) {
102
+ if (closeToken) {
103
+ const closeIndex = buffer.indexOf(closeToken);
104
+ if (closeIndex !== -1) {
105
+ buffer = buffer.slice(closeIndex + closeToken.length);
106
+ closeToken = void 0;
107
+ continue;
108
+ }
109
+ const keep = final ? 0 : Math.min(buffer.length, closeToken.length - 1);
110
+ buffer = buffer.slice(buffer.length - keep);
111
+ if (final) closeToken = void 0;
112
+ return output;
113
+ }
114
+ const open = findEarliestDsmlToken(buffer, DSML_OPEN_TOKENS);
115
+ if (open) {
116
+ emit(buffer.slice(0, open.index));
117
+ buffer = buffer.slice(open.index + open.token.length);
118
+ closeToken = open.token.replace("<", "</");
119
+ continue;
120
+ }
121
+ if (final) {
122
+ emit(buffer);
123
+ buffer = "";
124
+ return output;
125
+ }
126
+ const keep = longestDsmlTokenPrefixSuffixLength(buffer, DSML_OPEN_TOKENS, MAX_OPEN_TOKEN_LEN);
127
+ const emitLength = buffer.length - keep;
128
+ if (emitLength <= 0) return output;
129
+ emit(buffer.slice(0, emitLength));
130
+ buffer = buffer.slice(emitLength);
131
+ return output;
132
+ }
133
+ return output;
134
+ };
135
+ return {
136
+ push(chunk) {
137
+ buffer += chunk;
138
+ return consume(false);
139
+ },
140
+ flush() {
141
+ return consume(true);
142
+ }
143
+ };
144
+ }
145
+ //#endregion
146
+ //#region packages/ai/src/transports/model-max-tokens-params.ts
147
+ /**
148
+ * Max-token parameter normalization across provider/native naming variants.
149
+ * Callers canonicalize aliases before dispatch so payloads cannot carry
150
+ * conflicting limits.
151
+ */
152
+ const MAX_TOKENS_PARAM_KEYS = [
153
+ "maxTokens",
154
+ "max_completion_tokens",
155
+ "max_tokens"
156
+ ];
157
+ /** Resolve the first supported max-token parameter present in a params object. */
158
+ function resolveMaxTokensParam(params) {
159
+ if (!params) return;
160
+ for (const key of MAX_TOKENS_PARAM_KEYS) {
161
+ const resolved = asNonNegativeFiniteNumber(params[key]);
162
+ if (resolved !== void 0) return resolved;
163
+ }
164
+ }
165
+ /**
166
+ * Canonicalize merged params to `maxTokens`, preserving source precedence from
167
+ * left to right across the provided source objects.
168
+ */
169
+ function canonicalizeMaxTokensParam(params) {
170
+ let resolved;
171
+ for (const source of params.sources) {
172
+ const sourceValue = resolveMaxTokensParam(source);
173
+ if (sourceValue !== void 0) resolved = sourceValue;
174
+ }
175
+ if (resolved === void 0) return;
176
+ for (const key of MAX_TOKENS_PARAM_KEYS) delete params.merged[key];
177
+ params.merged.maxTokens = resolved;
178
+ }
179
+ //#endregion
180
+ //#region packages/ai/src/transports/openai-compatible-conversation-turn.ts
181
+ function hasNonEmptyMessageContent(content) {
182
+ if (hasNonEmptyString(content)) return true;
183
+ if (!Array.isArray(content)) return false;
184
+ return content.some((part) => {
185
+ if (!part || typeof part !== "object") return false;
186
+ const record = part;
187
+ if (record.type === "text") return hasNonEmptyString(record.text);
188
+ return true;
189
+ });
190
+ }
191
+ /** Returns whether an OpenAI-compatible messages payload contains a usable turn. */
192
+ function hasOpenAICompatibleConversationTurn(messages) {
193
+ if (!Array.isArray(messages)) return false;
194
+ return messages.some((message) => {
195
+ if (!message || typeof message !== "object") return false;
196
+ const record = message;
197
+ if (record.role === "user") return hasNonEmptyMessageContent(record.content);
198
+ if (record.role === "assistant") {
199
+ if (hasNonEmptyMessageContent(record.content)) return true;
200
+ const toolCalls = record.tool_calls;
201
+ return Array.isArray(toolCalls) && toolCalls.some((toolCall) => toolCall && typeof toolCall === "object");
202
+ }
203
+ return false;
204
+ });
205
+ }
206
+ //#endregion
207
+ //#region packages/ai/src/transports/openai-completions-cache-control.ts
208
+ const shapedPayloads = /* @__PURE__ */ new WeakSet();
209
+ function resolveCompletionsCacheControl(compat, retention, openRouterRoute) {
210
+ if (compat.cacheControlFormat !== "anthropic" || retention === "none") return;
211
+ return {
212
+ type: "ephemeral",
213
+ ...retention === "long" && compat.supportsLongCacheRetention && (openRouterRoute || compat.configuredSupportsLongCacheRetention === true) ? { ttl: "1h" } : {}
214
+ };
215
+ }
216
+ /** Shared Chat Completions policy; repeated wrapper application preserves existing checkpoints. */
217
+ function applyCompletionsAnthropicCacheControl(payload, cacheControl = { type: "ephemeral" }, cacheOptOutIndexes = /* @__PURE__ */ new Set(), markTools = true, markMessages = true, systemOnly = false) {
218
+ if (shapedPayloads.has(payload)) return;
219
+ shapedPayloads.add(payload);
220
+ const messages = Array.isArray(payload.messages) ? payload.messages : [];
221
+ const tools = Array.isArray(payload.tools) ? payload.tools : [];
222
+ let lastToolIndex = -1;
223
+ for (let index = 0; index < tools.length; index++) {
224
+ const tool = tools[index];
225
+ if (isRecord(tool)) {
226
+ lastToolIndex = index;
227
+ if (Object.hasOwn(tool, "cache_control")) {
228
+ const unmarked = { ...tool };
229
+ delete unmarked.cache_control;
230
+ tools[index] = unmarked;
231
+ }
232
+ }
233
+ }
234
+ const blocks = messages.filter(isRecord).flatMap((message) => Array.isArray(message.content) ? message.content.filter(isRecord) : []);
235
+ for (const block of blocks) delete block.cache_control;
236
+ if (!cacheControl) return;
237
+ const markText = (message, splitBoundary) => {
238
+ if (typeof message.content === "string" && message.content) message.content = [{
239
+ type: "text",
240
+ text: message.content
241
+ }];
242
+ const content = message.content;
243
+ if (!Array.isArray(content)) return false;
244
+ for (let i = content.length - 1; i >= 0; i--) {
245
+ const block = content[i];
246
+ if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string" || !block.text) continue;
247
+ const split = splitBoundary ? splitSystemPromptCacheBoundary(block.text) : void 0;
248
+ if (split) {
249
+ content.splice(i, 1, ...split.stablePrefix ? [{
250
+ type: "text",
251
+ text: split.stablePrefix,
252
+ cache_control: cacheControl
253
+ }] : [], ...split.dynamicSuffix ? [{
254
+ type: "text",
255
+ text: split.dynamicSuffix
256
+ }] : []);
257
+ if (!split.stablePrefix) return false;
258
+ } else block.cache_control = cacheControl;
259
+ return true;
260
+ }
261
+ return false;
262
+ };
263
+ if (!systemOnly && markTools && lastToolIndex >= 0) tools[lastToolIndex] = {
264
+ ...tools[lastToolIndex],
265
+ cache_control: cacheControl
266
+ };
267
+ if (!markMessages) return;
268
+ const system = messages.find((message) => isRecord(message) && (message.role === "system" || message.role === "developer"));
269
+ if (isRecord(system)) markText(system, true);
270
+ if (systemOnly) return;
271
+ for (let i = messages.length - 1; i >= 0; i--) {
272
+ const message = messages[i];
273
+ if (!cacheOptOutIndexes.has(i) && isRecord(message) && (message.role === "user" || message.role === "tool") && markText(message, false)) return;
274
+ }
275
+ }
276
+ //#endregion
277
+ //#region packages/ai/src/transports/openai-completions-string-content.ts
278
+ /**
279
+ * OpenAI Chat Completions compatibility helpers. Some providers only accept
280
+ * role/content messages with plain string content instead of text block arrays.
281
+ */
282
+ /** Flatten string-only text block content arrays into newline-joined strings. */
283
+ function flattenCompletionMessagesToStringContent(messages) {
284
+ return messages.map((message) => {
285
+ const record = asOptionalObjectRecord(message);
286
+ const content = record?.content;
287
+ if (!Array.isArray(content)) return message;
288
+ const textParts = [];
289
+ for (const item of content) {
290
+ const part = asOptionalObjectRecord(item);
291
+ if (part?.type !== "text" || typeof part.text !== "string") return message;
292
+ textParts.push(part.text);
293
+ }
294
+ return {
295
+ ...record,
296
+ content: textParts.join("\n")
297
+ };
298
+ });
299
+ }
300
+ /** Strip completion messages to role/content fields for strict providers. */
301
+ function stripCompletionMessagesToRoleContent(messages) {
302
+ return messages.map((message) => {
303
+ const record = asOptionalRecord(message);
304
+ if (!record) return message;
305
+ return {
306
+ ...Object.hasOwn(record, "role") ? { role: record.role } : {},
307
+ ...Object.hasOwn(record, "content") ? { content: record.content } : {}
308
+ };
309
+ });
310
+ }
311
+ //#endregion
312
+ //#region packages/ai/src/providers/openai-completions-tool-calls.ts
313
+ const MAX_BUFFERED_TOOL_CALL_ARGUMENT_BYTES = 256e3;
314
+ const MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES = 256e3;
315
+ const MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS = 1024;
316
+ /** Keep encrypted provider reasoning attached to the first matching tool call. */
317
+ function createOpenAIEncryptedToolCallReasoningTracker() {
318
+ const firstBlocks = /* @__PURE__ */ new Map();
319
+ const pendingDetails = /* @__PURE__ */ new Map();
320
+ return {
321
+ rememberToolCall(id, block, previousId = id) {
322
+ const previous = firstBlocks.get(previousId);
323
+ if (previousId !== id && previous?.block === block) {
324
+ firstBlocks.delete(previousId);
325
+ if (previous.signature && block.thoughtSignature === previous.signature) delete block.thoughtSignature;
326
+ }
327
+ if (!id || firstBlocks.has(id)) return;
328
+ const pendingDetail = pendingDetails.get(id);
329
+ firstBlocks.set(id, {
330
+ block,
331
+ signature: pendingDetail
332
+ });
333
+ if (pendingDetail) {
334
+ block.thoughtSignature = pendingDetail;
335
+ pendingDetails.delete(id);
336
+ }
337
+ },
338
+ consumeDetails(details) {
339
+ if (!Array.isArray(details)) return;
340
+ for (const detail of details) {
341
+ if (!isRecord(detail) || detail.type !== "reasoning.encrypted" || typeof detail.id !== "string" || detail.id.length === 0 || typeof detail.data !== "string" || detail.data.length === 0) continue;
342
+ const serializedDetail = JSON.stringify(detail);
343
+ const matchingBlock = firstBlocks.get(detail.id);
344
+ if (matchingBlock) {
345
+ matchingBlock.signature = serializedDetail;
346
+ matchingBlock.block.thoughtSignature = serializedDetail;
347
+ } else pendingDetails.set(detail.id, serializedDetail);
348
+ }
349
+ }
350
+ };
351
+ }
352
+ function hasObservableContent(value) {
353
+ if (typeof value === "string") return value.length > 0;
354
+ if (Array.isArray(value)) return value.some(hasObservableContent);
355
+ if (isRecord(value)) return Object.entries(value).some(([field, nestedValue]) => field !== "type" && field !== "id" && field !== "index" && hasObservableContent(nestedValue));
356
+ return false;
357
+ }
358
+ function hasOpenAICompletionsDeltaContent(delta) {
359
+ return Object.entries(delta).some(([field, value]) => field !== "role" && hasObservableContent(value));
360
+ }
361
+ /** Normalize the SDK's legacy single-function lane into its modern tool-call shape. */
362
+ function createOpenAICompletionsToolCallDeltaNormalizer() {
363
+ let sawModernToolCall = false;
364
+ let pendingLegacyArgumentBytes = 0;
365
+ let pendingFollowingDeltaBytes = 0;
366
+ let pendingLegacyToolCall;
367
+ const modernArguments = /* @__PURE__ */ new Map();
368
+ const pendingFollowingDeltas = [];
369
+ const takePendingFollowingDeltas = () => {
370
+ pendingFollowingDeltaBytes = 0;
371
+ return pendingFollowingDeltas.splice(0).map((delta) => ({
372
+ delta,
373
+ toolCalls: []
374
+ }));
375
+ };
376
+ return (delta, finishReason) => {
377
+ const ordinaryDelta = { ...delta };
378
+ delete ordinaryDelta.function_call;
379
+ delete ordinaryDelta.tool_calls;
380
+ if (delta.tool_calls && delta.tool_calls.length > 0) {
381
+ for (const toolCall of delta.tool_calls) {
382
+ const index = typeof toolCall.index === "number" ? toolCall.index : void 0;
383
+ const state = (index === void 0 ? void 0 : modernArguments.get(index)) ?? (toolCall.id ? modernArguments.get(toolCall.id) : void 0) ?? {
384
+ bytes: 0,
385
+ pendingHighSurrogate: false
386
+ };
387
+ if (index !== void 0) modernArguments.set(index, state);
388
+ if (toolCall.id) modernArguments.set(toolCall.id, state);
389
+ const argumentDelta = toolCall.function?.arguments ?? "";
390
+ const append = measureUtf8AppendBytes(state.pendingHighSurrogate, argumentDelta);
391
+ state.bytes += append.bytes;
392
+ if (state.bytes > MAX_BUFFERED_TOOL_CALL_ARGUMENT_BYTES) throw new Error("Exceeded tool-call argument buffer limit");
393
+ state.pendingHighSurrogate = append.endsWithHighSurrogate;
394
+ }
395
+ const precedingDeltas = takePendingFollowingDeltas();
396
+ sawModernToolCall = true;
397
+ pendingLegacyArgumentBytes = 0;
398
+ pendingLegacyToolCall = void 0;
399
+ return [...precedingDeltas, {
400
+ delta: ordinaryDelta,
401
+ toolCalls: delta.tool_calls
402
+ }];
403
+ }
404
+ const functionCall = delta.function_call;
405
+ if (sawModernToolCall || !functionCall && !pendingLegacyToolCall) return [{
406
+ delta: ordinaryDelta,
407
+ toolCalls: []
408
+ }];
409
+ const hadPendingLegacyCall = pendingLegacyToolCall !== void 0;
410
+ const leadingDeltas = [];
411
+ if (hasOpenAICompletionsDeltaContent(ordinaryDelta)) {
412
+ if (hadPendingLegacyCall) {
413
+ const nextDeltaBytes = Buffer.byteLength(JSON.stringify(ordinaryDelta), "utf8");
414
+ if (pendingFollowingDeltaBytes + nextDeltaBytes > MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES || pendingFollowingDeltas.length >= MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS) throw new Error("Exceeded legacy tool-call content buffer limit");
415
+ pendingFollowingDeltaBytes += nextDeltaBytes;
416
+ pendingFollowingDeltas.push(ordinaryDelta);
417
+ } else leadingDeltas.push({
418
+ delta: ordinaryDelta,
419
+ toolCalls: []
420
+ });
421
+ }
422
+ if (functionCall && (functionCall.name || functionCall.arguments)) {
423
+ const nextFunctionName = pendingLegacyToolCall?.function?.name ? void 0 : functionCall.name;
424
+ const nextArgumentBytes = Buffer.byteLength(functionCall.arguments ?? "", "utf8") + Buffer.byteLength(nextFunctionName ?? "", "utf8");
425
+ if (pendingLegacyArgumentBytes + nextArgumentBytes > MAX_BUFFERED_TOOL_CALL_ARGUMENT_BYTES) throw new Error("Exceeded tool-call argument buffer limit");
426
+ pendingLegacyArgumentBytes += nextArgumentBytes;
427
+ pendingLegacyToolCall ??= {
428
+ index: 0,
429
+ id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`,
430
+ type: "function",
431
+ function: {}
432
+ };
433
+ const pendingFunction = pendingLegacyToolCall.function ??= {};
434
+ if (nextFunctionName) pendingFunction.name = nextFunctionName;
435
+ if (functionCall.arguments) pendingFunction.arguments = (pendingFunction.arguments ?? "") + functionCall.arguments;
436
+ }
437
+ if (!pendingLegacyToolCall) return leadingDeltas.length > 0 ? leadingDeltas : [{
438
+ delta: ordinaryDelta,
439
+ toolCalls: []
440
+ }];
441
+ if (finishReason === "function_call") {
442
+ const confirmedLegacyToolCall = pendingLegacyToolCall;
443
+ pendingLegacyToolCall = void 0;
444
+ pendingLegacyArgumentBytes = 0;
445
+ return [
446
+ ...leadingDeltas,
447
+ {
448
+ delta: {},
449
+ toolCalls: [confirmedLegacyToolCall]
450
+ },
451
+ ...takePendingFollowingDeltas()
452
+ ];
453
+ }
454
+ if (finishReason) {
455
+ pendingLegacyArgumentBytes = 0;
456
+ pendingLegacyToolCall = void 0;
457
+ return [...leadingDeltas, ...takePendingFollowingDeltas()];
458
+ }
459
+ return leadingDeltas;
460
+ };
461
+ }
462
+ /** Publish only executable calls; streaming scratch state never belongs in replay. */
463
+ function finalizeOpenAICompletionsToolCalls(output, options = {}) {
464
+ const isToolCall = (block) => block.type === "toolCall";
465
+ const hasToolCalls = output.content.some(isToolCall);
466
+ if (output.stopReason === "toolUse" && !hasToolCalls) output.stopReason = "stop";
467
+ if (output.stopReason === "stop" && hasToolCalls && options.allowSilentToolCallPromotion !== false && !output.content.some((block) => block.type === "text" && block.text.trim().length > 0)) output.stopReason = "toolUse";
468
+ if (output.stopReason !== "toolUse") {
469
+ if (hasToolCalls) output.content = output.content.filter((block) => !isToolCall(block));
470
+ return;
471
+ }
472
+ const toolCalls = output.content.filter(isToolCall);
473
+ const rejectToolCalls = () => {
474
+ output.stopReason = "error";
475
+ output.errorMessage = "Provider returned an incomplete or malformed tool call";
476
+ output.content = output.content.filter((candidate) => !isToolCall(candidate));
477
+ };
478
+ if (toolCalls.some((call) => typeof call.name !== "string" || call.name.trim().length === 0 || typeof call.partialJson !== "string" || call.partialJson.trim().length === 0)) {
479
+ rejectToolCalls();
480
+ return;
481
+ }
482
+ try {
483
+ finalizeTerminalToolCallArguments(toolCalls, (call) => call.partialJson);
484
+ } catch {
485
+ rejectToolCalls();
486
+ return;
487
+ }
488
+ for (let contentIndex = 0; contentIndex < output.content.length; contentIndex += 1) {
489
+ const block = output.content[contentIndex];
490
+ if (!block || !isToolCall(block)) continue;
491
+ delete block.partialJson;
492
+ options.onConfirmedToolCall?.(block, contentIndex);
493
+ }
494
+ }
495
+ //#endregion
496
+ //#region packages/ai/src/openai-completions-messages.ts
497
+ /** Whether replayed messages require a tools marker for proxy compatibility. */
498
+ function hasToolCallHistory(messages) {
499
+ return messages.some((message) => message.role === "toolResult" || message.role === "assistant" && Array.isArray(message.content) && message.content.some((block) => block.type === "toolCall"));
500
+ }
501
+ /** Convert a normalized transcript to OpenAI Chat Completions messages. */
502
+ function convertMessages(model, context, compat, options = {}) {
503
+ const params = [];
504
+ const supportsTools = options.supportsTools !== false;
505
+ const declaredToolNames = options.declaredToolNames ?? new Set(context.tools?.map((tool) => tool.name));
506
+ const toolNamesByCallId = /* @__PURE__ */ new Map();
507
+ const normalizeToolCallId = (id) => {
508
+ if (id.includes("|")) return id.slice(0, id.indexOf("|")).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
509
+ if (model.provider === "openai") return id.length > 40 ? truncateUtf16Safe(id, 40) : id;
510
+ return id;
511
+ };
512
+ const transformedMessages = transformProviderMessages(context.messages, model, normalizeToolCallId);
513
+ let relocatableSplit;
514
+ let systemParamIndex;
515
+ if (context.systemPrompt) {
516
+ const role = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";
517
+ let systemPrompt;
518
+ if (options.preserveSystemPromptCacheBoundary) systemPrompt = stripSystemPromptRelocatableBoundary(context.systemPrompt);
519
+ else {
520
+ const split = splitSystemPromptRelocatableBoundary(context.systemPrompt);
521
+ if (split && split.relocatable.length > 0) relocatableSplit = split;
522
+ systemPrompt = stripSystemPromptCacheBoundary(context.systemPrompt);
523
+ }
524
+ systemParamIndex = params.length;
525
+ params.push({
526
+ role,
527
+ content: sanitizeSurrogates(systemPrompt)
528
+ });
529
+ }
530
+ let lastRole = null;
531
+ for (let i = 0; i < transformedMessages.length; i++) {
532
+ const msg = transformedMessages[i];
533
+ if (!msg) continue;
534
+ if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") params.push({
535
+ role: "assistant",
536
+ content: "I have processed the tool results."
537
+ });
538
+ if (isRuntimeContextMessage(msg)) {
539
+ params.push({
540
+ role: compat.supportsDeveloperRole ? "developer" : "user",
541
+ content: sanitizeSurrogates(runtimeContextContentToText(msg.content))
542
+ });
543
+ options.cacheOptOutIndexes?.add(params.length - 1);
544
+ } else if (msg.role === "user") {
545
+ let userParam;
546
+ if (typeof msg.content === "string") userParam = {
547
+ role: "user",
548
+ content: sanitizeSurrogates(msg.content)
549
+ };
550
+ else {
551
+ const content = msg.content.map((item) => {
552
+ if (item.type === "text") return {
553
+ type: "text",
554
+ text: sanitizeSurrogates(item.text)
555
+ };
556
+ if (item.type === "video") return {
557
+ type: "video_url",
558
+ video_url: { url: `data:${item.mimeType};base64,${item.data}` }
559
+ };
560
+ return {
561
+ type: "image_url",
562
+ image_url: { url: `data:${item.mimeType};base64,${item.data}` }
563
+ };
564
+ });
565
+ if (content.length === 0) continue;
566
+ userParam = {
567
+ role: "user",
568
+ content
569
+ };
570
+ }
571
+ if (hasRuntimeContextMarker(msg)) options.cacheOptOutIndexes?.add(params.length);
572
+ params.push(userParam);
573
+ } else if (msg.role === "assistant") {
574
+ const assistantMsg = {
575
+ role: "assistant",
576
+ content: compat.requiresAssistantAfterToolResult ? "" : null
577
+ };
578
+ const assistantTexts = [];
579
+ const nonEmptyThinkingBlocks = [];
580
+ const toolCalls = [];
581
+ msg.content.forEach((block) => {
582
+ if (block.type === "text" && block.text.trim().length > 0) assistantTexts.push(sanitizeSurrogates(block.text));
583
+ else if (block.type === "thinking" && block.thinking.trim().length > 0) nonEmptyThinkingBlocks.push(block);
584
+ else if (block.type === "toolCall") {
585
+ toolNamesByCallId.set(block.id, block.name);
586
+ if (supportsTools && declaredToolNames.has(block.name)) toolCalls.push(block);
587
+ else assistantTexts.push(sanitizeSurrogates(`[tool call id=${block.id} name=${block.name}] ${JSON.stringify(block.arguments)}`));
588
+ }
589
+ });
590
+ if (nonEmptyThinkingBlocks.length > 0 && compat.requiresThinkingAsText) assistantMsg.content = [{
591
+ type: "text",
592
+ text: nonEmptyThinkingBlocks.map((block) => sanitizeSurrogates(block.thinking)).join("\n\n")
593
+ }, ...assistantTexts.map((text) => ({
594
+ type: "text",
595
+ text
596
+ }))];
597
+ else {
598
+ const assistantText = assistantTexts.join("\n");
599
+ if (assistantText.length > 0) assistantMsg.content = assistantText;
600
+ if (nonEmptyThinkingBlocks.length > 0) {
601
+ let signature = nonEmptyThinkingBlocks.at(0)?.thinkingSignature;
602
+ if (model.provider === "opencode-go" && signature === "reasoning") signature = "reasoning_content";
603
+ if (signature && signature.length > 0) assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join("\n");
604
+ }
605
+ }
606
+ if (toolCalls.length > 0) {
607
+ assistantMsg.tool_calls = toolCalls.map((toolCall) => ({
608
+ id: toolCall.id,
609
+ type: "function",
610
+ function: {
611
+ name: toolCall.name,
612
+ arguments: JSON.stringify(toolCall.arguments)
613
+ }
614
+ }));
615
+ const reasoningDetails = toolCalls.flatMap((toolCall) => {
616
+ const signature = toolCall.thoughtSignature;
617
+ if (!signature) return [];
618
+ try {
619
+ const parsed = JSON.parse(signature);
620
+ return parsed ? [parsed] : [];
621
+ } catch {
622
+ return [];
623
+ }
624
+ });
625
+ if (reasoningDetails.length > 0) assistantMsg.reasoning_details = reasoningDetails;
626
+ }
627
+ if (compat.requiresReasoningContentOnAssistantMessages && model.reasoning && assistantMsg.reasoning_content === void 0) assistantMsg.reasoning_content = "";
628
+ const content = assistantMsg.content;
629
+ if (!(content !== null && content !== void 0 && content.length > 0) && !assistantMsg.tool_calls) continue;
630
+ params.push(assistantMsg);
631
+ } else if (msg.role === "toolResult") {
632
+ const imageContentParts = [];
633
+ const textResults = [];
634
+ let j = i;
635
+ while (j < transformedMessages.length) {
636
+ const toolMsg = transformedMessages.at(j);
637
+ if (toolMsg?.role !== "toolResult") break;
638
+ const textResult = extractToolResultText(toolMsg.content);
639
+ const mediaPlaceholder = describeToolResultMediaPlaceholder(toolMsg.content);
640
+ const images = toolMsg.content.filter(isImageWithMediaPayload);
641
+ const content = textResult.trim() ? textResult : mediaPlaceholder ?? "(no output)";
642
+ const normalizedId = normalizeToolCallId(toolMsg.toolCallId);
643
+ const pairedToolName = toolNamesByCallId.get(toolMsg.toolCallId) ?? toolNamesByCallId.get(normalizedId);
644
+ const isNativeResult = pairedToolName !== void 0 ? declaredToolNames.has(pairedToolName) : preparedRequestSuffix.hasToolCall(context, toolMsg.toolCallId) || preparedRequestSuffix.hasToolCall(context, normalizedId);
645
+ if (supportsTools && isNativeResult) {
646
+ const toolResultMsg = {
647
+ role: "tool",
648
+ content,
649
+ tool_call_id: preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, toolMsg.toolCallId, normalizedId) : toolMsg.toolCallId
650
+ };
651
+ if (compat.requiresToolResultName && toolMsg.toolName) toolResultMsg.name = toolMsg.toolName;
652
+ params.push(toolResultMsg);
653
+ } else textResults.push(sanitizeSurrogates(`[tool result id=${toolMsg.toolCallId} name=${toolMsg.toolName}] ${content}`));
654
+ if (images.length > 0 && model.input.includes("image")) {
655
+ const boundedToolName = sanitizeSurrogates(truncateUtf16Safe(toolMsg.toolName ?? "", 64));
656
+ imageContentParts.push({
657
+ type: "text",
658
+ text: `Image(s) from tool result #${j - i + 1}${boundedToolName ? ` (${boundedToolName})` : ""}:`
659
+ });
660
+ for (const block of images) imageContentParts.push({
661
+ type: "image_url",
662
+ image_url: { url: `data:${block.mimeType};base64,${block.data}` }
663
+ });
664
+ }
665
+ j += 1;
666
+ }
667
+ i = j - 1;
668
+ if (textResults.length > 0) {
669
+ const previous = params.at(-1);
670
+ const text = textResults.join("\n");
671
+ if (previous?.role !== "assistant") params.push({
672
+ role: "assistant",
673
+ content: text
674
+ });
675
+ else if (Array.isArray(previous.content)) previous.content.push(...textResults.map((result) => ({
676
+ type: "text",
677
+ text: result
678
+ })));
679
+ else previous.content = previous.content ? `${previous.content}\n${text}` : text;
680
+ }
681
+ if (imageContentParts.length > 0) {
682
+ if (supportsTools && textResults.length === 0 && compat.requiresAssistantAfterToolResult) params.push({
683
+ role: "assistant",
684
+ content: "I have processed the tool results."
685
+ });
686
+ params.push({
687
+ role: "user",
688
+ content: imageContentParts
689
+ });
690
+ lastRole = "user";
691
+ } else lastRole = supportsTools && textResults.length === 0 ? "toolResult" : "assistant";
692
+ continue;
693
+ }
694
+ lastRole = msg.role;
695
+ }
696
+ if (relocatableSplit !== void 0 && systemParamIndex !== void 0) {
697
+ const cacheOptOutIndexes = options.cacheOptOutIndexes;
698
+ const text = sanitizeSurrogates(stripSystemPromptCacheBoundary(relocatableSplit.relocatable));
699
+ for (let index = systemParamIndex + 1; index < params.length; index++) {
700
+ const param = params[index];
701
+ if (!param || param.role !== "user") continue;
702
+ if (typeof param.content === "string") param.content = `${param.content}\n\n${text}`;
703
+ else if (Array.isArray(param.content)) param.content = [...param.content, {
704
+ type: "text",
705
+ text
706
+ }];
707
+ else continue;
708
+ const systemParam = params[systemParamIndex];
709
+ if (systemParam) systemParam.content = sanitizeSurrogates(stripSystemPromptCacheBoundary(relocatableSplit.remainingPrompt));
710
+ cacheOptOutIndexes?.add(index);
711
+ break;
712
+ }
713
+ }
714
+ return params;
715
+ }
716
+ //#endregion
717
+ //#region packages/ai/src/transports/openai-completions-replay.ts
718
+ function isGoogleOpenAICompatModel(model) {
719
+ const endpointClass = detectOpenAICompletionsCompat(model).capabilities.endpointClass;
720
+ return model.provider === "google" || endpointClass === "google-generative-ai" || endpointClass === "google-vertex";
721
+ }
722
+ const GOOGLE_COMPAT_THOUGHT_SIGNATURE_ELLIPSIS_RE = /[\u2026]|\.\.\./;
723
+ const GOOGLE_COMPAT_THOUGHT_SIGNATURE_BASE64_RE = /^[A-Za-z0-9+/=]+$/;
724
+ function hasGoogleCompatThoughtSignatureTruncationFootprint(value) {
725
+ return GOOGLE_COMPAT_THOUGHT_SIGNATURE_ELLIPSIS_RE.test(value) || GOOGLE_COMPAT_THOUGHT_SIGNATURE_BASE64_RE.test(value) && value.length % 4 !== 0;
726
+ }
727
+ function injectToolCallThoughtSignatures(outgoingMessages, context, model) {
728
+ if (!isGoogleOpenAICompatModel(model)) return;
729
+ const sigById = /* @__PURE__ */ new Map();
730
+ const fallbackSig = isGoogleGemini3ThinkingLevelModel(model.id) ? GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP : void 0;
731
+ for (const msg of context.messages ?? []) {
732
+ if (msg.role !== "assistant") continue;
733
+ if (!Array.isArray(msg.content)) continue;
734
+ for (const block of msg.content) {
735
+ if (block.type !== "toolCall") continue;
736
+ const id = block.id;
737
+ const sig = block.thoughtSignature;
738
+ if (typeof id === "string" && typeof sig === "string" && sig.length > 0) {
739
+ const isSameRoute = msg.api === model.api && msg.provider === model.provider && msg.model === model.id;
740
+ if (!isSameRoute && !fallbackSig) continue;
741
+ sigById.set(id, isSameRoute ? sig : fallbackSig ?? sig);
742
+ }
743
+ }
744
+ }
745
+ if (sigById.size === 0 && !fallbackSig) return;
746
+ for (const message of outgoingMessages) {
747
+ const toolCalls = "tool_calls" in message ? message.tool_calls : void 0;
748
+ if (!Array.isArray(toolCalls)) continue;
749
+ for (const toolCall of toolCalls) {
750
+ let sig = sigById.get(toolCall.id) ?? fallbackSig;
751
+ if (sig) {
752
+ if (hasGoogleCompatThoughtSignatureTruncationFootprint(sig.trim())) sig = fallbackSig;
753
+ }
754
+ if (!sig) continue;
755
+ Object.assign(toolCall, { extra_content: { google: { thought_signature: sig } } });
756
+ }
757
+ }
758
+ }
759
+ const COMPLETIONS_REASONING_REPLAY_FIELDS = [
760
+ "reasoning_details",
761
+ "reasoning_content",
762
+ "reasoning",
763
+ "reasoning_text"
764
+ ];
765
+ function sanitizeOpenRouterReasoningReplayFields(record) {
766
+ const reasoningDetails = record.reasoning_details;
767
+ if (typeof reasoningDetails === "string") {
768
+ if (reasoningDetails.length > 0 && typeof record.reasoning !== "string") record.reasoning = reasoningDetails;
769
+ delete record.reasoning_details;
770
+ } else if (reasoningDetails !== void 0 && !Array.isArray(reasoningDetails)) delete record.reasoning_details;
771
+ for (const field of ["reasoning", "reasoning_content"]) if (field in record && (typeof record[field] !== "string" || record[field] === "")) delete record[field];
772
+ const reasoningText = record.reasoning_text;
773
+ if (typeof reasoningText === "string" && reasoningText.length > 0 && typeof record.reasoning !== "string" && typeof record.reasoning_content !== "string") record.reasoning = reasoningText;
774
+ delete record.reasoning_text;
775
+ }
776
+ function shouldPreserveOpenRouterReasoningReplay(model) {
777
+ if (model.provider !== "openrouter") return true;
778
+ const normalizedModelId = model.id.trim().toLowerCase();
779
+ return !(normalizedModelId.startsWith("anthropic/") || normalizedModelId.startsWith("x-ai/"));
780
+ }
781
+ function applyCompletionsReplay(outgoingMessages, context, model, compat) {
782
+ injectToolCallThoughtSignatures(outgoingMessages, context, model);
783
+ const preserveOpenRouterReasoning = compat.thinkingFormat === "openrouter" && shouldPreserveOpenRouterReasoningReplay(model);
784
+ const preserveReasoningContent = compat.requiresReasoningContentOnAssistantMessages || compat.thinkingFormat === "deepseek" || compat.thinkingFormat === "zai" || model.reasoning && model.provider.trim().toLowerCase() !== "openai" && shouldPreserveOpenRouterReasoningReplay(model) || requiresReasoningContentReplay(model.id);
785
+ for (const message of outgoingMessages) {
786
+ if (message.role !== "assistant") continue;
787
+ if (preserveOpenRouterReasoning) sanitizeOpenRouterReasoningReplayFields(message);
788
+ else {
789
+ const record = message;
790
+ const requiresReasoningContent = model.compat?.requiresReasoningContentOnAssistantMessages === true;
791
+ if (preserveReasoningContent && requiresReasoningContent) {
792
+ for (const field of [
793
+ "reasoning_content",
794
+ "reasoning",
795
+ "reasoning_text"
796
+ ]) if (typeof record[field] === "string" && record[field].length > 0) {
797
+ record.reasoning_content = record[field];
798
+ break;
799
+ }
800
+ }
801
+ for (const field of COMPLETIONS_REASONING_REPLAY_FIELDS) {
802
+ if (preserveReasoningContent && field !== "reasoning_details" && (!requiresReasoningContent || field === "reasoning_content") && typeof record[field] === "string") continue;
803
+ delete record[field];
804
+ }
805
+ }
806
+ }
807
+ }
808
+ //#endregion
809
+ //#region packages/ai/src/transports/openai-completions-params.ts
810
+ const OPENAI_COMPLETIONS_INPUT_TOKEN_SAFETY_MARGIN = 1.25;
811
+ const OPENAI_COMPLETIONS_IMAGE_CHAR_ESTIMATE = 8e3;
812
+ const OPENAI_COMPLETIONS_VIDEO_CHAR_ESTIMATE = 96e3;
813
+ const MIN_USEFUL_OUTPUT_TOKENS = 16;
814
+ function estimateJsonChars(value, fallback) {
815
+ try {
816
+ return estimateStringChars(JSON.stringify(value));
817
+ } catch {
818
+ return fallback;
819
+ }
820
+ }
821
+ function estimateOpenAICompletionsInputTokens(payload) {
822
+ let adjustedChars = estimateOpenAICompletionsMessagesChars(payload.messages);
823
+ if (payload.tools?.length) adjustedChars += estimateJsonChars(payload.tools, 1024);
824
+ if (payload.response_format !== void 0) adjustedChars += estimateJsonChars(payload.response_format, 256);
825
+ return Math.ceil(adjustedChars / 4 * OPENAI_COMPLETIONS_INPUT_TOKEN_SAFETY_MARGIN);
826
+ }
827
+ function estimateOpenAICompletionsMessagesChars(messages) {
828
+ let adjustedChars = 0;
829
+ for (const message of messages) {
830
+ if (!message || typeof message !== "object") continue;
831
+ const record = message;
832
+ adjustedChars += estimateOpenAICompletionsContentChars(record.content);
833
+ for (const field of COMPLETIONS_REASONING_REPLAY_FIELDS) adjustedChars += estimateOpenAICompletionsContentChars(record[field]);
834
+ if (record.tool_calls !== void 0) adjustedChars += estimateJsonChars(record.tool_calls, 256);
835
+ }
836
+ return adjustedChars;
837
+ }
838
+ function estimateOpenAICompletionsContentChars(value) {
839
+ if (typeof value === "string") return estimateStringChars(value);
840
+ if (!Array.isArray(value)) return 0;
841
+ let adjustedChars = 0;
842
+ for (const block of value) {
843
+ if (!block || typeof block !== "object") continue;
844
+ const record = block;
845
+ if (record.type === "image_url" || record.type === "input_image") {
846
+ adjustedChars += OPENAI_COMPLETIONS_IMAGE_CHAR_ESTIMATE;
847
+ continue;
848
+ }
849
+ if (record.type === "video_url" || record.type === "input_video") {
850
+ adjustedChars += OPENAI_COMPLETIONS_VIDEO_CHAR_ESTIMATE;
851
+ continue;
852
+ }
853
+ const text = record.text;
854
+ if (typeof text === "string") {
855
+ adjustedChars += estimateStringChars(text);
856
+ continue;
857
+ }
858
+ adjustedChars += estimateJsonChars(block, 256);
859
+ }
860
+ return adjustedChars;
861
+ }
862
+ function convertTools(tools, compat, model, mode, mutableParameters) {
863
+ const prepared = mode === "managed" ? prepareOpenAITools(tools) : void 0;
864
+ const projection = prepared?.projection ?? projectOpenAITools(tools);
865
+ const convert = () => {
866
+ const strict = mode === "direct" ? compat.supportsStrictMode ? false : void 0 : resolveOpenAIStrictToolFlagWithDiagnostics(projection, getAiTransportHost().resolveOpenAIStrictToolSetting(model, {
867
+ transport: "stream",
868
+ supportsStrictMode: compat?.supportsStrictMode
869
+ }), {
870
+ transport: "completions",
871
+ model
872
+ });
873
+ return {
874
+ projection,
875
+ tools: sortPromptCacheToolsByName(projection.tools).map((tool) => {
876
+ const parameters = compat.requiresTypedUnionBranches ? normalizeToolSchema(tool.parameters, "moonshot") : tool.parameters;
877
+ return prepareOpenAIFunctionTool(tool.name, tool.description, mode === "direct" ? parameters : normalizeOpenAIStrictToolParameters(parameters, strict === true, model.compat), strict, mutableParameters).completions;
878
+ })
879
+ };
880
+ };
881
+ return prepared ? withPreparedToolSchemaNormalization(prepared.schemas, convert) : convert();
882
+ }
883
+ function buildOpenAICompletionsParams(model, context, options) {
884
+ return buildOpenAICompletionsRequest(model, context, options, { mode: "managed" });
885
+ }
886
+ const contextOutputBudgets = /* @__PURE__ */ new WeakMap();
887
+ function completionsInputHash(payload) {
888
+ return shortHash(JSON.stringify([
889
+ payload.messages,
890
+ payload.tools,
891
+ payload.response_format
892
+ ]));
893
+ }
894
+ function resolveCompletionsContextOutputBudget(request, payload) {
895
+ const budget = contextOutputBudgets.get(request);
896
+ const limits = [payload.max_tokens, payload.max_completion_tokens].filter((value) => value !== void 0);
897
+ if (!budget || payload.model !== budget.model || !Array.isArray(payload.messages) || payload.tools !== void 0 && !Array.isArray(payload.tools) || limits.length === 0 || limits.some((value) => value !== budget.cap) || completionsInputHash(payload) !== budget.inputHash) return;
898
+ return budget.cap;
899
+ }
900
+ function buildOpenAICompletionsRequest(model, context, options, policy) {
901
+ let contextOutputCap;
902
+ const resolvedPolicy = policy.mode === "direct" ? policy : {
903
+ ...policy,
904
+ compat: getCompat(model)
905
+ };
906
+ const compat = resolvedPolicy.compat;
907
+ const managedCompat = resolvedPolicy.mode === "managed" ? resolvedPolicy.compat : void 0;
908
+ const endpointDetection = detectOpenAICompletionsCompat(model);
909
+ const compatDetection = policy.mode === "managed" ? endpointDetection : void 0;
910
+ const { endpointClass } = endpointDetection.capabilities;
911
+ const cacheRetention = policy.mode === "direct" ? policy.cacheRetention : resolveCacheRetention(options?.cacheRetention);
912
+ const cacheControl = resolveCompletionsCacheControl(compat, cacheRetention, endpointClass === "openrouter" || endpointClass === "default" && model.provider === "openrouter");
913
+ const markTools = endpointClass !== "modelstudio-native" && !(endpointClass === "default" && [
914
+ "modelstudio",
915
+ "dashscope",
916
+ "qwen"
917
+ ].includes(model.provider));
918
+ const cacheOptOutIndexes = /* @__PURE__ */ new Set();
919
+ const supportsTools = policy.mode === "direct" || supportsModelTools(model);
920
+ const converted = supportsTools && context.tools ? convertTools(context.tools, compat, model, policy.mode, Boolean(options?.onPayload)) : void 0;
921
+ const convertedMessages = convertMessages({
922
+ ...model,
923
+ input: options?.[PROVIDER_MODEL_INPUT] ?? model.input,
924
+ compat
925
+ }, context, compat, {
926
+ cacheOptOutIndexes,
927
+ supportsTools,
928
+ declaredToolNames: new Set(converted?.projection.tools.map((tool) => tool.name)),
929
+ preserveSystemPromptCacheBoundary: cacheControl !== void 0 && !managedCompat?.requiresStringContent
930
+ });
931
+ applyCompletionsReplay(convertedMessages, context, model, compat);
932
+ let messages = convertedMessages;
933
+ if (managedCompat) {
934
+ if (managedCompat.strictMessageKeys) messages = stripCompletionMessagesToRoleContent(messages);
935
+ if (managedCompat.requiresStringContent) messages = flattenCompletionMessagesToStringContent(messages);
936
+ }
937
+ const promptCacheKey = resolvePromptCacheKey(options, cacheRetention);
938
+ const params = {
939
+ model: model.id,
940
+ messages,
941
+ stream: (options?.streaming ?? model.params?.streaming) !== false,
942
+ ...resolveOpenAIPromptCacheParams(model, cacheRetention, compat)
943
+ };
944
+ if (params.stream && compat.supportsUsageInStreaming) params.stream_options = { include_usage: true };
945
+ if (compat.supportsStore) params.store = false;
946
+ if (policy.mode === "direct" || compat.supportsPromptCacheKey && promptCacheKey) params.prompt_cache_key = compat.supportsPromptCacheKey ? promptCacheKey : void 0;
947
+ if (options?.temperature !== void 0) params.temperature = options.temperature;
948
+ if (policy.mode === "managed" && options?.topP !== void 0) params.top_p = options.topP;
949
+ const requestedResponseFormat = options?.responseFormat;
950
+ const responseFormat = policy.mode === "direct" && requestedResponseFormat === void 0 ? void 0 : resolveOpenAICompletionsResponseFormat(shouldOmitOllamaCompatResponseFormat({
951
+ provider: model.provider,
952
+ baseUrl: model.baseUrl,
953
+ hasTools: () => Boolean(context.tools?.length)
954
+ }) ? void 0 : requestedResponseFormat, compat.supportsJsonSchemaResponseFormat);
955
+ if (responseFormat !== void 0) params.response_format = responseFormat;
956
+ if (policy.mode === "managed" && options?.frequencyPenalty !== void 0) params.frequency_penalty = options.frequencyPenalty;
957
+ if (policy.mode === "managed" && options?.presencePenalty !== void 0) params.presence_penalty = options.presencePenalty;
958
+ if (policy.mode === "managed" && options?.seed !== void 0) params.seed = options.seed;
959
+ if (options?.stop !== void 0 && options.stop.length > 0) params.stop = options.stop;
960
+ let directToolProjection;
961
+ if (supportsTools) {
962
+ if (converted) {
963
+ if (policy.mode === "direct") directToolProjection = converted.projection;
964
+ if (converted.tools.length > 0 || policy.mode === "managed" && converted.projection.inputToolCount === 0 && converted.projection.diagnostics.length === 0) params.tools = converted.tools;
965
+ else if (hasToolCallHistory(context.messages)) params.tools = [];
966
+ if (policy.mode === "direct" && params.stream && compat.zaiToolStream && converted.tools.length > 0) params.tool_stream = true;
967
+ if (policy.mode === "managed" && options?.toolChoice) {
968
+ const toolChoice = reconcileOpenAICompletionsToolChoice(options.toolChoice, converted.projection);
969
+ if (toolChoice !== void 0) params.tool_choice = toolChoice;
970
+ } else if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && params.tools?.length) params.tool_choice = "auto";
971
+ } else if (hasToolCallHistory(context.messages)) params.tools = [];
972
+ if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && params.tools?.length === 0) {
973
+ delete params.tools;
974
+ delete params.tool_choice;
975
+ }
976
+ }
977
+ if (policy.mode === "direct" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools, true, compat.cacheControlSystemOnly);
978
+ if (policy.mode === "direct" && options?.toolChoice) {
979
+ const toolChoice = reconcileOpenAICompletionsToolChoice(options.toolChoice, directToolProjection ?? projectOpenAITools([]));
980
+ if (toolChoice !== void 0) params.tool_choice = toolChoice;
981
+ }
982
+ const isOpenRouter = compat.thinkingFormat === "openrouter";
983
+ const usesBinaryOpenRouterThinking = isOpenRouter && (model.compat?.supportsReasoningEffort === false || model.compat?.supportedReasoningEfforts?.length === 0);
984
+ const simpleReasoning = options?.reasoning;
985
+ const requestedEffort = policy.mode === "direct" ? options?.reasoningEffort : options?.reasoningEffort ?? (simpleReasoning === "none" ? "none" : resolveOpenAISimpleReasoningEffort({
986
+ ...model,
987
+ compat: model.compat ?? void 0
988
+ }, simpleReasoning)) ?? (usesBinaryOpenRouterThinking ? void 0 : "high");
989
+ const thinkingExplicit = options?.openclawThinkingExplicit ?? (options?.reasoningEffort !== void 0 || options?.reasoning !== void 0);
990
+ const { effort, thinkingEnabled } = resolveOpenAIRequestReasoning(model, requestedEffort);
991
+ const direct = policy.mode === "direct";
992
+ {
993
+ let effectiveMaxTokens = options?.maxTokens;
994
+ const clampToModelMaxTokens = direct || Boolean(effectiveMaxTokens);
995
+ if (!direct && !effectiveMaxTokens) effectiveMaxTokens = resolveMaxTokensParam(model.params) || model.maxTokens;
996
+ const effectiveContextTokens = asPositiveFiniteNumber(model.contextTokens) ?? asPositiveFiniteNumber(model.contextWindow);
997
+ let clampedMaxTokens = effectiveMaxTokens;
998
+ const modelOutputLimit = asPositiveFiniteNumber(model.maxTokens);
999
+ const modelMaxTokens = modelOutputLimit === void 0 ? void 0 : Math.floor(modelOutputLimit);
1000
+ if (clampToModelMaxTokens && clampedMaxTokens !== void 0 && modelMaxTokens !== void 0 && clampedMaxTokens > modelMaxTokens) {
1001
+ clampedMaxTokens = modelMaxTokens;
1002
+ if (policy.mode === "managed") emitModelTransportDebug(log, () => `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} modelMaxTokens=${modelMaxTokens}`);
1003
+ }
1004
+ if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && clampedMaxTokens !== void 0 && effectiveContextTokens !== void 0) {
1005
+ const estimatedInputTokens = (params.response_format === void 0 ? measuredRequestPressure.get(model, context) : void 0) ?? estimateOpenAICompletionsInputTokens(params);
1006
+ const remainingBudget = Math.max(0, effectiveContextTokens - estimatedInputTokens - 1);
1007
+ if (clampedMaxTokens > remainingBudget) {
1008
+ if (remainingBudget < (params.tools?.length && params.tool_choice !== "none" ? Math.max(MIN_USEFUL_OUTPUT_TOKENS, Math.min(2048, Math.ceil((modelMaxTokens ?? 0) / 8))) : MIN_USEFUL_OUTPUT_TOKENS)) throw Object.assign(/* @__PURE__ */ new Error(`Context window exceeded: estimated input ${estimatedInputTokens} leaves only ${remainingBudget} output tokens within the ${effectiveContextTokens}-token context.`), { code: "context_length_exceeded" });
1009
+ clampedMaxTokens = remainingBudget;
1010
+ contextOutputCap = remainingBudget;
1011
+ emitModelTransportDebug(log, () => `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} effectiveContext=${effectiveContextTokens} estimatedInput=${estimatedInputTokens}`);
1012
+ }
1013
+ }
1014
+ if (policy.mode === "direct" ? options?.maxTokens : clampedMaxTokens) {
1015
+ if (compat.maxTokensField === "max_tokens") params.max_tokens = clampedMaxTokens;
1016
+ else params.max_completion_tokens = clampedMaxTokens;
1017
+ }
1018
+ }
1019
+ if (isOpenRouter && model.reasoning) {
1020
+ if (usesBinaryOpenRouterThinking && thinkingEnabled !== void 0) params.reasoning = { enabled: thinkingEnabled };
1021
+ else if (effort !== void 0) params.reasoning = { effort };
1022
+ }
1023
+ const nativeEffort = compat.thinkingFormat === "openrouter" ? void 0 : effort;
1024
+ const enabled = thinkingEnabled ?? false;
1025
+ const useBinaryThinking = direct || thinkingEnabled === false && (nativeEffort === void 0 || !compat.supportsReasoningEffort);
1026
+ if (model.reasoning && (!compat.thinkingOffControlUndeclared || thinkingEnabled === true || !thinkingExplicit)) {
1027
+ let allowScalarEffort = true;
1028
+ if (useBinaryThinking && compat.thinkingFormat === "zai") {
1029
+ params.thinking = enabled ? {
1030
+ type: "enabled",
1031
+ clear_thinking: false
1032
+ } : { type: "disabled" };
1033
+ allowScalarEffort = false;
1034
+ } else if (compat.thinkingFormat === "qwen") {
1035
+ params.enable_thinking = enabled;
1036
+ allowScalarEffort = false;
1037
+ } else if (compat.thinkingFormat === "qwen-chat-template") {
1038
+ const chatTemplateReasoningEffort = enabled && thinkingExplicit && model.compat?.supportedReasoningEfforts?.length ? effort : void 0;
1039
+ params.chat_template_kwargs = {
1040
+ enable_thinking: enabled,
1041
+ ...direct ? { preserve_thinking: true } : {},
1042
+ ...chatTemplateReasoningEffort ? { reasoning_effort: chatTemplateReasoningEffort } : {}
1043
+ };
1044
+ allowScalarEffort = false;
1045
+ } else if (compat.thinkingFormat === "together" || useBinaryThinking && compat.thinkingFormat === "deepseek") {
1046
+ if (compat.thinkingFormat === "deepseek") params.thinking = { type: enabled ? "enabled" : "disabled" };
1047
+ else params.reasoning = { enabled };
1048
+ allowScalarEffort = enabled;
1049
+ }
1050
+ if (allowScalarEffort && compat.supportsReasoningEffort && (direct ? nativeEffort !== void 0 : nativeEffort)) params.reasoning_effort = nativeEffort;
1051
+ }
1052
+ if (direct) {
1053
+ if (compat.openRouterRouting) params.provider = compat.openRouterRouting;
1054
+ if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
1055
+ const routing = model.compat.vercelGatewayRouting;
1056
+ if (routing.only || routing.order) {
1057
+ const gatewayOptions = {};
1058
+ if (routing.only) gatewayOptions.only = routing.only;
1059
+ if (routing.order) gatewayOptions.order = routing.order;
1060
+ params.providerOptions = { gateway: gatewayOptions };
1061
+ }
1062
+ }
1063
+ }
1064
+ if (policy.mode === "managed" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools, !managedCompat?.requiresStringContent, compat.cacheControlSystemOnly);
1065
+ if (params.tools?.length && isKnownOpenAIEndpoint(model)) applyOpenAICompletionsToolReasoning(params, model);
1066
+ if (contextOutputCap !== void 0) contextOutputBudgets.set(params, {
1067
+ model: params.model,
1068
+ cap: contextOutputCap,
1069
+ inputHash: completionsInputHash(params)
1070
+ });
1071
+ return params;
1072
+ }
1073
+ //#endregion
1074
+ //#region packages/ai/src/transports/openai-completions-dsml.ts
1075
+ const DEEPSEEK_DSML_INVOKE_OPEN_PREFIXES = DEEPSEEK_DSML_MARKERS.map((marker) => `<${marker}invoke`);
1076
+ const DEEPSEEK_DSML_INVOKE_OPEN_TAG = new RegExp(`^<${DEEPSEEK_DSML_MARKER_PATTERN}invoke\\b[^<>]*>$`);
1077
+ const DEEPSEEK_DSML_TOOL_MAX_OPEN_TOKEN_LEN = Math.max(...DEEPSEEK_DSML_TOOL_OPEN_TOKENS.map((token) => token.length));
1078
+ const DEEPSEEK_DSML_RECOVERY_MAX_BOUNDARY_LEN = Math.max(...DEEPSEEK_DSML_TOOL_OPEN_TOKENS.map((token) => token.length + 1), ...DEEPSEEK_DSML_INVOKE_OPEN_PREFIXES.map((token) => token.length + 2));
1079
+ const MAX_DSML_RECOVERY_BUFFER_BYTES = 256e3;
1080
+ const DEEPSEEK_DSML_SCAN_BATCH_CHARS = 65536;
1081
+ const DSML_NAME_ATTRIBUTE_RE = /\bname=("([^"]*)"|'([^']*)'|([^\s>]+))/;
1082
+ function createDsmlRecoverer() {
1083
+ let buffer = "";
1084
+ let bufferBytes = 0;
1085
+ let bufferEndsWithHighSurrogate = false;
1086
+ let pendingScanChars = 0;
1087
+ let activeOpenToken = null;
1088
+ let blockScanState = { offset: 0 };
1089
+ const resetBlockScan = () => {
1090
+ activeOpenToken = null;
1091
+ pendingScanChars = 0;
1092
+ blockScanState = { offset: 0 };
1093
+ };
1094
+ const consume = (final) => {
1095
+ const output = [];
1096
+ while (buffer) {
1097
+ const open = activeOpenToken ? {
1098
+ index: 0,
1099
+ token: activeOpenToken
1100
+ } : findEarliestDsmlToken(buffer, DEEPSEEK_DSML_TOOL_OPEN_TOKENS);
1101
+ if (!open) {
1102
+ resetBlockScan();
1103
+ if (final) {
1104
+ output.push({
1105
+ kind: "text",
1106
+ text: buffer
1107
+ });
1108
+ buffer = "";
1109
+ bufferBytes = 0;
1110
+ bufferEndsWithHighSurrogate = false;
1111
+ return output;
1112
+ }
1113
+ const keep = longestDsmlTokenPrefixSuffixLength(buffer, DEEPSEEK_DSML_TOOL_OPEN_TOKENS, DEEPSEEK_DSML_TOOL_MAX_OPEN_TOKEN_LEN);
1114
+ const emitLength = buffer.length - keep;
1115
+ if (emitLength > 0) {
1116
+ const emitted = buffer.slice(0, emitLength);
1117
+ output.push({
1118
+ kind: "text",
1119
+ text: emitted
1120
+ });
1121
+ bufferBytes -= Buffer.byteLength(emitted, "utf8");
1122
+ buffer = buffer.slice(emitted.length);
1123
+ if (!buffer) bufferEndsWithHighSurrogate = false;
1124
+ }
1125
+ return output;
1126
+ }
1127
+ if (open.index > 0) {
1128
+ const prefix = buffer.slice(0, open.index);
1129
+ output.push({
1130
+ kind: "text",
1131
+ text: prefix
1132
+ });
1133
+ bufferBytes -= Buffer.byteLength(prefix, "utf8");
1134
+ buffer = buffer.slice(prefix.length);
1135
+ resetBlockScan();
1136
+ }
1137
+ activeOpenToken = open.token;
1138
+ if (blockScanState.offset === 0) blockScanState.offset = open.token.length;
1139
+ const blockScan = scanDeepSeekDsmlToolBlock(buffer, open.token.replace("<", "</"), open.token.length, blockScanState);
1140
+ if (blockScan.kind === "nested-open") throw new Error("Nested DeepSeek DSML recovery wrappers are not supported");
1141
+ const close = blockScan.kind === "close" ? blockScan : null;
1142
+ if (!close) {
1143
+ if (final) {
1144
+ output.push({
1145
+ kind: "text",
1146
+ text: buffer
1147
+ });
1148
+ buffer = "";
1149
+ bufferBytes = 0;
1150
+ bufferEndsWithHighSurrogate = false;
1151
+ return output;
1152
+ }
1153
+ if (bufferBytes > MAX_DSML_RECOVERY_BUFFER_BYTES) throw new Error("Exceeded DeepSeek DSML recovery buffer limit");
1154
+ return output;
1155
+ }
1156
+ resetBlockScan();
1157
+ const body = buffer.slice(open.token.length, close.index);
1158
+ const blockText = buffer.slice(0, close.index + close.token.length);
1159
+ if (Buffer.byteLength(blockText, "utf8") > MAX_DSML_RECOVERY_BUFFER_BYTES) throw new Error("Exceeded DeepSeek DSML recovery buffer limit");
1160
+ const recoveredToolCalls = parseDeepSeekDsmlToolCallBlock(body);
1161
+ if (recoveredToolCalls.length > 0) output.push(...recoveredToolCalls);
1162
+ else output.push({
1163
+ kind: "text",
1164
+ text: blockText
1165
+ });
1166
+ bufferBytes -= Buffer.byteLength(blockText, "utf8");
1167
+ buffer = buffer.slice(blockText.length);
1168
+ if (!buffer) bufferEndsWithHighSurrogate = false;
1169
+ }
1170
+ return output;
1171
+ };
1172
+ return {
1173
+ push(chunk) {
1174
+ const append = measureUtf8AppendBytes(bufferEndsWithHighSurrogate, chunk);
1175
+ bufferBytes += append.bytes;
1176
+ bufferEndsWithHighSurrogate = append.endsWithHighSurrogate;
1177
+ buffer += chunk;
1178
+ pendingScanChars += chunk.length;
1179
+ if (activeOpenToken && pendingScanChars < DEEPSEEK_DSML_SCAN_BATCH_CHARS && !chunk.includes("<") && !chunk.includes(">") && bufferBytes <= MAX_DSML_RECOVERY_BUFFER_BYTES) return [];
1180
+ pendingScanChars = 0;
1181
+ return consume(false);
1182
+ },
1183
+ flush() {
1184
+ return consume(true);
1185
+ }
1186
+ };
1187
+ }
1188
+ function parseDeepSeekDsmlToolCallBlock(body) {
1189
+ const toolCalls = [];
1190
+ const invokeOpenRegex = new RegExp(`<${DEEPSEEK_DSML_MARKER_PATTERN}invoke\\b([^<>]*)>`, "g");
1191
+ let openMatch;
1192
+ while ((openMatch = invokeOpenRegex.exec(body)) !== null) {
1193
+ const invokeBodyStart = openMatch.index + openMatch[0].length;
1194
+ const invokeCloseToken = `</${openMatch[1]}invoke>`;
1195
+ const invokeCloseIndex = body.indexOf(invokeCloseToken, invokeBodyStart);
1196
+ if (invokeCloseIndex === -1) break;
1197
+ const invokeBody = body.slice(invokeBodyStart, invokeCloseIndex);
1198
+ invokeOpenRegex.lastIndex = invokeCloseIndex + invokeCloseToken.length;
1199
+ const invokeName = parseDsmlNameAttribute(openMatch[2] ?? "");
1200
+ if (!invokeName) continue;
1201
+ const parsedArguments = parseDeepSeekDsmlInvokeArguments(invokeBody);
1202
+ if (!parsedArguments) continue;
1203
+ toolCalls.push({
1204
+ kind: "toolCall",
1205
+ name: invokeName,
1206
+ arguments: parsedArguments,
1207
+ partialJson: JSON.stringify(parsedArguments)
1208
+ });
1209
+ }
1210
+ return toolCalls;
1211
+ }
1212
+ function parseDeepSeekDsmlInvokeArguments(body) {
1213
+ const args = {};
1214
+ const parameterRegex = new RegExp(`<${DEEPSEEK_DSML_MARKER_PATTERN}parameter\\b([^>]*)>([\\s\\S]*?)</\\1parameter>`, "g");
1215
+ let parameterMatch;
1216
+ while ((parameterMatch = parameterRegex.exec(body)) !== null) {
1217
+ const name = parseDsmlNameAttribute(parameterMatch[2] ?? "");
1218
+ if (!name) continue;
1219
+ const rawValue = parameterMatch[3] ?? "";
1220
+ if (rawValue.length === 0) {
1221
+ const stringAttribute = Array.from((parameterMatch[2] ?? "").matchAll(/(?:^|\s)([^\s=]+)=(?:"([^"]*)"|'([^']*)'|([^\s"']+))(?=\s|$)/g)).find((attribute) => attribute[1] === "string");
1222
+ if ((stringAttribute?.[2] ?? stringAttribute?.[3] ?? stringAttribute?.[4]) !== "true") continue;
1223
+ }
1224
+ Object.defineProperty(args, name, {
1225
+ value: decodeDeepSeekDsmlText(rawValue),
1226
+ enumerable: true,
1227
+ configurable: true,
1228
+ writable: true
1229
+ });
1230
+ }
1231
+ if (Object.keys(args).length > 0) return args;
1232
+ const trimmed = body.trim();
1233
+ if (!trimmed.startsWith("{")) return null;
1234
+ try {
1235
+ const parsed = JSON.parse(trimmed);
1236
+ if (isRecord(parsed) && Object.keys(parsed).length > 0) return parsed;
1237
+ } catch {
1238
+ return null;
1239
+ }
1240
+ return null;
1241
+ }
1242
+ function parseDsmlNameAttribute(attributes) {
1243
+ const match = DSML_NAME_ATTRIBUTE_RE.exec(attributes);
1244
+ const value = match?.[2] ?? match?.[3] ?? match?.[4];
1245
+ return value ? decodeDeepSeekDsmlText(value) : null;
1246
+ }
1247
+ function decodeDeepSeekDsmlText(value) {
1248
+ return value.replaceAll("&quot;", "\"").replaceAll("&apos;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
1249
+ }
1250
+ function scanDeepSeekDsmlToolBlock(text, closeToken, contentStartIndex, state) {
1251
+ while (state.offset < text.length) {
1252
+ if (state.invoke?.kind === "open") {
1253
+ const nextOpen = text.indexOf("<", state.offset);
1254
+ const nextClose = text.indexOf(">", state.offset);
1255
+ if (nextClose === -1 && nextOpen === -1) {
1256
+ state.offset = text.length;
1257
+ return { kind: "incomplete" };
1258
+ }
1259
+ if (nextOpen !== -1 && (nextClose === -1 || nextOpen < nextClose)) {
1260
+ state.invoke = void 0;
1261
+ state.offset = nextOpen;
1262
+ continue;
1263
+ }
1264
+ const invokeOpenTag = text.slice(state.invoke.start, nextClose + 1);
1265
+ const open = DEEPSEEK_DSML_INVOKE_OPEN_TAG.exec(invokeOpenTag);
1266
+ if (!open) {
1267
+ state.offset = state.invoke.start + 1;
1268
+ state.invoke = void 0;
1269
+ continue;
1270
+ }
1271
+ state.invoke = {
1272
+ kind: "body",
1273
+ closeToken: `</${open[1]}invoke>`
1274
+ };
1275
+ state.offset = nextClose + 1;
1276
+ continue;
1277
+ }
1278
+ if (state.invoke?.kind === "body") {
1279
+ const invokeCloseIndex = text.indexOf(state.invoke.closeToken, state.offset);
1280
+ if (invokeCloseIndex === -1) {
1281
+ state.offset = Math.max(0, text.length - DEEPSEEK_DSML_RECOVERY_MAX_BOUNDARY_LEN + 1);
1282
+ return { kind: "incomplete" };
1283
+ }
1284
+ state.offset = invokeCloseIndex + state.invoke.closeToken.length;
1285
+ state.invoke = void 0;
1286
+ continue;
1287
+ }
1288
+ const toolOpen = findEarliestDsmlToken(text, DEEPSEEK_DSML_TOOL_OPEN_TOKENS, state.offset);
1289
+ const toolCloseIndex = text.indexOf(closeToken, state.offset);
1290
+ const invokeOpen = findEarliestDsmlToken(text, DEEPSEEK_DSML_INVOKE_OPEN_PREFIXES, state.offset);
1291
+ const next = [
1292
+ toolOpen ? {
1293
+ kind: "nested-open",
1294
+ ...toolOpen
1295
+ } : null,
1296
+ toolCloseIndex === -1 ? null : {
1297
+ kind: "close",
1298
+ index: toolCloseIndex,
1299
+ token: closeToken
1300
+ },
1301
+ invokeOpen ? {
1302
+ kind: "invoke-open",
1303
+ ...invokeOpen
1304
+ } : null
1305
+ ].filter((candidate) => candidate !== null).toSorted((left, right) => left.index - right.index)[0];
1306
+ if (!next) {
1307
+ state.offset = Math.max(contentStartIndex, text.length - DEEPSEEK_DSML_RECOVERY_MAX_BOUNDARY_LEN + 1);
1308
+ return { kind: "incomplete" };
1309
+ }
1310
+ if (next.kind === "invoke-open") {
1311
+ state.invoke = {
1312
+ kind: "open",
1313
+ start: next.index
1314
+ };
1315
+ state.offset = next.index + next.token.length;
1316
+ continue;
1317
+ }
1318
+ return next;
1319
+ }
1320
+ return { kind: "incomplete" };
1321
+ }
1322
+ //#endregion
1323
+ //#region packages/ai/src/transports/openai-completions-gemma.ts
1324
+ const OPEN = "<|tool_call>";
1325
+ const CLOSE = "<tool_call|>";
1326
+ const QUOTE = "<|\"|>";
1327
+ const MAX_RECOVERY_BYTES = 256e3;
1328
+ function recoverGemmaCalls(text) {
1329
+ const parts = [];
1330
+ const opener = /\s*<\|tool_call>\s*call:([\w.-]+)\s*/y;
1331
+ const token = /\s*(<\|"\|>[\s\S]*?<\|"\|>|[\w.+-]+|[{}[\],:])\s*/y;
1332
+ let offset = 0;
1333
+ while (offset < text.length) {
1334
+ if (!text.slice(offset).trim()) {
1335
+ parts.push({
1336
+ kind: "text",
1337
+ text: text.slice(offset)
1338
+ });
1339
+ break;
1340
+ }
1341
+ opener.lastIndex = offset;
1342
+ const head = opener.exec(text);
1343
+ const name = head?.[1];
1344
+ if (!head || !name) return;
1345
+ const leading = /^\s*/.exec(head[0])?.[0] ?? "";
1346
+ if (leading) parts.push({
1347
+ kind: "text",
1348
+ text: leading
1349
+ });
1350
+ token.lastIndex = opener.lastIndex;
1351
+ let depth = 0;
1352
+ const json = [];
1353
+ do {
1354
+ const value = token.exec(text)?.[1];
1355
+ if (!value || json.length === 0 && value !== "{") return;
1356
+ if (value === "{") depth += 1;
1357
+ else if (value === "}") depth -= 1;
1358
+ json.push(value.startsWith(QUOTE) ? JSON.stringify(value.slice(5, -5)) : text[token.lastIndex] === ":" && /^[A-Za-z_][\w.-]*$/.test(value) ? JSON.stringify(value) : value);
1359
+ } while (depth > 0);
1360
+ if (!text.startsWith(CLOSE, token.lastIndex)) return;
1361
+ try {
1362
+ const argumentsValue = JSON.parse(json.join(" "));
1363
+ if (!isRecord(argumentsValue)) return;
1364
+ parts.push({
1365
+ kind: "toolCall",
1366
+ name,
1367
+ arguments: argumentsValue,
1368
+ partialJson: JSON.stringify(argumentsValue)
1369
+ });
1370
+ } catch {
1371
+ return;
1372
+ }
1373
+ offset = token.lastIndex + 12;
1374
+ }
1375
+ return parts;
1376
+ }
1377
+ /** Buffer only a possible standalone call batch; prose and examples stay text. */
1378
+ function createGemmaToolCallRecoverer() {
1379
+ let buffer = "";
1380
+ let bytes = 0;
1381
+ let highSurrogate = false;
1382
+ let passthrough = false;
1383
+ return {
1384
+ push(text) {
1385
+ if (passthrough) return [{
1386
+ kind: "text",
1387
+ text
1388
+ }];
1389
+ const append = measureUtf8AppendBytes(highSurrogate, text);
1390
+ bytes += append.bytes;
1391
+ highSurrogate = append.endsWithHighSurrogate;
1392
+ buffer += text;
1393
+ const candidate = buffer.trimStart();
1394
+ if (OPEN.startsWith(candidate) || candidate.startsWith(OPEN)) {
1395
+ if (bytes > MAX_RECOVERY_BYTES) throw new Error("Exceeded Gemma tool-call recovery buffer limit");
1396
+ return [];
1397
+ }
1398
+ passthrough = true;
1399
+ const result = [{
1400
+ kind: "text",
1401
+ text: buffer
1402
+ }];
1403
+ buffer = "";
1404
+ return result;
1405
+ },
1406
+ flush(allowRecovery = true) {
1407
+ const text = buffer;
1408
+ buffer = "";
1409
+ passthrough ||= !allowRecovery;
1410
+ const recovered = allowRecovery ? recoverGemmaCalls(text) : void 0;
1411
+ return text ? recovered ?? [{
1412
+ kind: "text",
1413
+ text
1414
+ }] : [];
1415
+ }
1416
+ };
1417
+ }
1418
+ //#endregion
1419
+ //#region packages/ai/src/transports/openai-completions-stream.ts
1420
+ let reasoningParserModule;
1421
+ function extractToolCallThoughtSignature(toolCall) {
1422
+ const tc = toolCall;
1423
+ if (!tc) return;
1424
+ const extra = tc.extra_content?.google;
1425
+ return readNonEmptyStringPreservingWhitespace(extra?.thought_signature) ?? readNonEmptyStringPreservingWhitespace(tc.function?.thought_signature) ?? readNonEmptyStringPreservingWhitespace(tc.thought_signature);
1426
+ }
1427
+ async function* observeOpenAICompletionsProgress(responseStream, signal) {
1428
+ const maxUsageTokens = {
1429
+ prompt: 0,
1430
+ completion: 0,
1431
+ total: 0,
1432
+ reasoning: 0
1433
+ };
1434
+ for await (const rawChunk of responseStream) {
1435
+ throwIfModelStreamAborted(signal);
1436
+ if (rawChunk && typeof rawChunk === "object") {
1437
+ const chunk = rawChunk;
1438
+ const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
1439
+ const usage = chunk.usage || choice?.usage;
1440
+ let hasUsageProgress = false;
1441
+ for (const [counter, reported] of [
1442
+ ["prompt", usage?.prompt_tokens],
1443
+ ["completion", usage?.completion_tokens],
1444
+ ["total", usage?.total_tokens],
1445
+ ["reasoning", usage?.completion_tokens_details?.reasoning_tokens]
1446
+ ]) {
1447
+ const tokens = asPositiveFiniteNumber(reported) ?? 0;
1448
+ if (tokens > maxUsageTokens[counter]) {
1449
+ maxUsageTokens[counter] = tokens;
1450
+ hasUsageProgress = true;
1451
+ }
1452
+ }
1453
+ const rawChoiceDelta = choice?.delta ?? choice?.message;
1454
+ notifyLlmRequestActivity(signal, Boolean(hasUsageProgress || choice?.finish_reason || rawChoiceDelta && (rawChoiceDelta.tool_calls?.length || hasOpenAICompletionsDeltaContent(rawChoiceDelta))));
1455
+ }
1456
+ yield rawChunk;
1457
+ }
1458
+ }
1459
+ async function processCompletionsStream(responseStream, output, model, stream, options) {
1460
+ const { createReasoningTagTextPartitioner } = await (reasoningParserModule ??= import("./internal/reasoning-tag-text-partitioner.mjs"));
1461
+ const MAX_POST_TOOL_CALL_BUFFER_BYTES = 256e3;
1462
+ const directMode = options?.mode === "direct";
1463
+ const emitReasoning = options?.emitReasoning ?? true;
1464
+ const openAIModel = model;
1465
+ const compat = getCompat(openAIModel);
1466
+ const visibleReasoningDetailTypes = new Set(compat.visibleReasoningDetailTypes);
1467
+ const deepSeekTextFilter = compat.emitsDsmlToolCalls ? createDeepSeekTextFilter() : null;
1468
+ const deepSeekToolCallRecoverer = !directMode && compat.emitsDsmlToolCalls ? createDsmlRecoverer() : null;
1469
+ const gemmaToolCallRecoverer = !directMode && /gemma-?4/i.test(model.id) ? createGemmaToolCallRecoverer() : null;
1470
+ const reasoningTagTextPartitioner = createReasoningTagTextPartitioner();
1471
+ if (options?.strictReasoningTags) reasoningTagTextPartitioner.markStrict();
1472
+ let currentBlock = null;
1473
+ const directContent = { block: null };
1474
+ let currentTextSource;
1475
+ let sawReasoning = false;
1476
+ let suppressedReasoning = false;
1477
+ let pendingPostToolCallDeltas = [];
1478
+ let pendingPostToolCallBytes = 0;
1479
+ const toolCallBlocksByIndex = /* @__PURE__ */ new Map();
1480
+ const toolCallBlocksById = /* @__PURE__ */ new Map();
1481
+ const encryptedReasoning = createOpenAIEncryptedToolCallReasoningTracker();
1482
+ const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
1483
+ const blockIndices = /* @__PURE__ */ new WeakMap();
1484
+ const normalizeToolCallDeltas = createOpenAICompletionsToolCallDeltaNormalizer();
1485
+ let finishReason;
1486
+ let sawNativeToolCallDelta = false;
1487
+ const blockIndex = () => directMode && currentBlock && currentBlock.type !== "toolCall" ? blockIndices.get(currentBlock) ?? output.content.length - 1 : output.content.length - 1;
1488
+ let chunkPushedEvent = false;
1489
+ const pushStreamEvent = (event) => {
1490
+ chunkPushedEvent = true;
1491
+ stream.push(detachPartialSnapshot(event));
1492
+ };
1493
+ const appendToolCallBlock = (block) => {
1494
+ output.content.push(block);
1495
+ blockIndices.set(block, output.content.length - 1);
1496
+ pushStreamEvent({
1497
+ type: "toolcall_start",
1498
+ contentIndex: blockIndices.get(block) ?? -1,
1499
+ partial: output
1500
+ });
1501
+ };
1502
+ const queuePostToolCallDelta = (next) => {
1503
+ const nextBytes = Buffer.byteLength(next.text, "utf8");
1504
+ if (pendingPostToolCallBytes + nextBytes > MAX_POST_TOOL_CALL_BUFFER_BYTES) throw new Error("Exceeded post-tool-call delta buffer limit");
1505
+ pendingPostToolCallBytes += nextBytes;
1506
+ const previous = pendingPostToolCallDeltas[pendingPostToolCallDeltas.length - 1];
1507
+ if (!previous || previous.kind !== next.kind || previous.kind === "text" && next.kind === "text" && previous.source !== next.source || previous.kind === "thinking" && next.kind === "thinking" && previous.signature !== next.signature) {
1508
+ pendingPostToolCallDeltas.push(next);
1509
+ return;
1510
+ }
1511
+ previous.text += next.text;
1512
+ };
1513
+ const appendContentDelta = (delta) => {
1514
+ flushPendingPostToolCallDeltas();
1515
+ if (directMode && directContent.block?.type === delta.kind) currentBlock = directContent.block;
1516
+ if (delta.kind === "text" && currentBlock?.type === "text" && currentTextSource !== delta.source) currentBlock = null;
1517
+ if (!currentBlock || currentBlock.type !== delta.kind) {
1518
+ options?.beforeContentBlock?.(delta.kind);
1519
+ if (delta.kind === "text") {
1520
+ currentBlock = {
1521
+ type: "text",
1522
+ text: ""
1523
+ };
1524
+ currentTextSource = delta.source;
1525
+ } else currentBlock = {
1526
+ type: "thinking",
1527
+ thinking: "",
1528
+ ...delta.signature ? { thinkingSignature: delta.signature } : {}
1529
+ };
1530
+ if (directMode) directContent.block = currentBlock;
1531
+ output.content.push(currentBlock);
1532
+ blockIndices.set(currentBlock, output.content.length - 1);
1533
+ pushStreamEvent({
1534
+ type: `${delta.kind}_start`,
1535
+ contentIndex: blockIndex(),
1536
+ partial: output
1537
+ });
1538
+ }
1539
+ if (currentBlock.type === "thinking") appendAssistantThinking(currentBlock, delta.text);
1540
+ else currentBlock.text += delta.text;
1541
+ const event = {
1542
+ contentIndex: blockIndex(),
1543
+ delta: delta.text
1544
+ };
1545
+ if (delta.kind === "thinking") pushStreamEvent({
1546
+ type: "thinking_delta",
1547
+ ...event,
1548
+ partial: output
1549
+ });
1550
+ else pushStreamEvent({
1551
+ type: "text_delta",
1552
+ ...event,
1553
+ ...directMode ? { partial: output } : {}
1554
+ });
1555
+ };
1556
+ const flushPendingPostToolCallDeltas = () => {
1557
+ if (currentBlock?.type === "toolCall" || pendingPostToolCallDeltas.length === 0) return;
1558
+ const bufferedDeltas = pendingPostToolCallDeltas;
1559
+ pendingPostToolCallDeltas = [];
1560
+ pendingPostToolCallBytes = 0;
1561
+ for (const delta of bufferedDeltas) if (delta.kind === "text" || emitReasoning) appendContentDelta(delta);
1562
+ };
1563
+ const appendVisibleTextDelta = (text) => {
1564
+ if (!text) return;
1565
+ if (currentBlock?.type === "toolCall" && !directMode) queuePostToolCallDelta({
1566
+ kind: "text",
1567
+ text
1568
+ });
1569
+ else appendContentDelta({
1570
+ kind: "text",
1571
+ text
1572
+ });
1573
+ };
1574
+ const appendReasoningDeltas = (reasoningDeltas) => {
1575
+ for (const delta of reasoningDeltas) {
1576
+ if (delta.kind === "thinking" && !emitReasoning) continue;
1577
+ if (currentBlock?.type === "toolCall" && !directMode) {
1578
+ queuePostToolCallDelta({ ...delta });
1579
+ continue;
1580
+ }
1581
+ appendContentDelta(delta.kind === "thinking" && directMode && model.provider === "opencode-go" && delta.signature === "reasoning" ? {
1582
+ ...delta,
1583
+ signature: "reasoning_content"
1584
+ } : delta);
1585
+ }
1586
+ };
1587
+ const recoveredToolCallBlocks = /* @__PURE__ */ new Set();
1588
+ const appendRecoveredToolCall = (toolCall) => {
1589
+ if (currentBlock?.type === "toolCall") {
1590
+ currentBlock = null;
1591
+ flushPendingPostToolCallDeltas();
1592
+ }
1593
+ const block = {
1594
+ type: "toolCall",
1595
+ id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`,
1596
+ name: toolCall.name,
1597
+ arguments: toolCall.arguments,
1598
+ partialJson: toolCall.partialJson
1599
+ };
1600
+ recoveredToolCallBlocks.add(block);
1601
+ currentBlock = block;
1602
+ appendToolCallBlock(block);
1603
+ pushStreamEvent({
1604
+ type: "toolcall_delta",
1605
+ contentIndex: blockIndices.get(block) ?? -1,
1606
+ delta: toolCall.partialJson,
1607
+ partial: output
1608
+ });
1609
+ };
1610
+ const appendRecoveredParts = (recoveredParts) => {
1611
+ for (const recoveredPart of recoveredParts) {
1612
+ if (recoveredPart.kind === "toolCall") {
1613
+ appendRecoveredToolCall(recoveredPart);
1614
+ continue;
1615
+ }
1616
+ const parts = deepSeekTextFilter?.push(recoveredPart.text) ?? [recoveredPart.text];
1617
+ for (const part of parts) appendVisibleTextDelta(part);
1618
+ }
1619
+ };
1620
+ const appendPartitionedVisibleDelta = (delta) => {
1621
+ if (delta.kind === "text") appendRecoveredParts(deepSeekToolCallRecoverer?.push(delta.text) ?? [{
1622
+ kind: "text",
1623
+ text: delta.text
1624
+ }]);
1625
+ };
1626
+ const emitReasoningUsageActivity = (hasReasoningUsageActivity) => {
1627
+ if (directMode || !hasReasoningUsageActivity || chunkPushedEvent || !emitReasoning) return;
1628
+ const latestBlock = output.content[output.content.length - 1];
1629
+ if (currentBlock?.type === "text" || currentBlock?.type === "toolCall") return;
1630
+ if (latestBlock?.type === "text" || latestBlock?.type === "toolCall") return;
1631
+ appendContentDelta({
1632
+ kind: "thinking",
1633
+ text: ""
1634
+ });
1635
+ };
1636
+ const flushReasoningTagTextPartitioner = (allowRecovery = true) => {
1637
+ const recoverUnclosed = allowRecovery && !sawReasoning && output.stopReason !== "length" && output.stopReason !== "error" && output.stopReason !== "aborted";
1638
+ for (const delta of reasoningTagTextPartitioner.flush({ recoverUnclosed })) appendPartitionedVisibleDelta(delta);
1639
+ };
1640
+ const flushGemmaToolCallRecoverer = (allowRecovery = true) => {
1641
+ for (const part of gemmaToolCallRecoverer?.flush(allowRecovery) ?? []) if (part.kind === "toolCall") appendRecoveredToolCall(part);
1642
+ else for (const delta of reasoningTagTextPartitioner.pushVisible(part.text)) appendPartitionedVisibleDelta(delta);
1643
+ };
1644
+ const sealTextBeforeReasoning = () => {
1645
+ if (currentBlock?.type !== "text" && !reasoningTagTextPartitioner.hasPending()) return;
1646
+ flushReasoningTagTextPartitioner();
1647
+ if (currentBlock?.type !== "text") return;
1648
+ currentBlock = null;
1649
+ if (directMode) directContent.block = null;
1650
+ currentTextSource = void 0;
1651
+ };
1652
+ const beginReasoning = (hasFollowingVisibleText) => {
1653
+ sawReasoning = true;
1654
+ if (!hasFollowingVisibleText || !reasoningTagTextPartitioner.hasPendingSyntax()) sealTextBeforeReasoning();
1655
+ };
1656
+ const events = directMode ? responseStream : iterateModelStream(responseStream, options?.signal);
1657
+ let maxReasoningTokens = 0;
1658
+ let providerProcessingMs;
1659
+ for await (const rawChunk of events) {
1660
+ throwIfModelStreamAborted(options?.signal);
1661
+ chunkPushedEvent = false;
1662
+ if (!rawChunk || typeof rawChunk !== "object") continue;
1663
+ const chunk = rawChunk;
1664
+ const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
1665
+ const usage = chunk.usage || choice?.usage;
1666
+ const rawChoiceDelta = choice?.delta ?? choice?.message;
1667
+ if (Boolean(choice?.finish_reason || rawChoiceDelta && (rawChoiceDelta.tool_calls?.length || hasOpenAICompletionsDeltaContent(rawChoiceDelta)) || asNonNegativeFiniteNumber(usage?.prompt_tokens) !== void 0 || asNonNegativeFiniteNumber(usage?.completion_tokens) !== void 0 || asNonNegativeFiniteNumber(usage?.total_tokens) !== void 0 || asNonNegativeFiniteNumber(usage?.completion_tokens_details?.reasoning_tokens) !== void 0)) {
1668
+ output.responseId ||= chunk.id;
1669
+ if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
1670
+ }
1671
+ if (chunk.timings !== void 0 && (choice?.finish_reason || Array.isArray(chunk.choices) && chunk.choices.length === 0 && chunk.usage)) {
1672
+ const promptMs = asNonNegativeFiniteNumber(chunk.timings?.prompt_ms);
1673
+ const predictedMs = asNonNegativeFiniteNumber(chunk.timings?.predicted_ms);
1674
+ providerProcessingMs = promptMs !== void 0 && predictedMs !== void 0 ? asNonNegativeFiniteNumber(promptMs + predictedMs) : void 0;
1675
+ }
1676
+ const reasoningTokens = asPositiveFiniteNumber(usage?.completion_tokens_details?.reasoning_tokens) ?? 0;
1677
+ const hasReasoningUsageActivity = reasoningTokens > maxReasoningTokens;
1678
+ maxReasoningTokens = Math.max(maxReasoningTokens, reasoningTokens);
1679
+ if (usage) {
1680
+ output.usage = parseOpenAICompletionsUsage(usage, model, { includeReasoningTokens: !directMode });
1681
+ const terminalUsage = Boolean(finishReason || choice?.finish_reason || chunk.choices?.length === 0);
1682
+ const completeCounts = [usage.prompt_tokens, usage.completion_tokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
1683
+ output.usage.usageReport = { state: terminalUsage && completeCounts ? "available" : "unavailable" };
1684
+ }
1685
+ if (!choice) {
1686
+ emitReasoningUsageActivity(hasReasoningUsageActivity);
1687
+ continue;
1688
+ }
1689
+ if (choice.finish_reason) {
1690
+ const finishReasonResult = mapOpenAIStopReason(choice.finish_reason, { allowSingularToolCall: true });
1691
+ output.stopReason = finishReasonResult.stopReason;
1692
+ finishReason = finishReasonResult.stopReason;
1693
+ if (finishReasonResult.errorMessage) output.errorMessage = finishReasonResult.errorMessage;
1694
+ }
1695
+ if (!rawChoiceDelta) {
1696
+ emitReasoningUsageActivity(hasReasoningUsageActivity);
1697
+ continue;
1698
+ }
1699
+ for (const normalizedDelta of normalizeToolCallDeltas(rawChoiceDelta, choice.finish_reason)) {
1700
+ const choiceDelta = normalizedDelta.delta;
1701
+ const deltaFields = choiceDelta;
1702
+ const reasoningBatch = readOpenAICompletionsReasoningBatch(deltaFields, visibleReasoningDetailTypes);
1703
+ const reasoningDeltas = reasoningBatch.deltas;
1704
+ const hasReasoningThinking = reasoningBatch.hasThinking;
1705
+ if (hasReasoningThinking && !model.reasoning && !emitReasoning && !suppressedReasoning) {
1706
+ suppressedReasoning = true;
1707
+ recordSuppressedReasoning(output);
1708
+ }
1709
+ const contentDeltas = readOpenAICompletionsContentDeltas(choiceDelta.content, choiceDelta.refusal, reasoningBatch.mirroredThinking);
1710
+ const lastVisibleTextIndex = contentDeltas.findLastIndex((delta) => delta.kind === "text");
1711
+ const hasSameChunkVisibleText = reasoningBatch.hasVisibleText || lastVisibleTextIndex !== -1;
1712
+ if (hasReasoningThinking) {
1713
+ beginReasoning(hasSameChunkVisibleText);
1714
+ appendReasoningDeltas(reasoningDeltas);
1715
+ }
1716
+ for (const [contentDeltaIndex, contentDelta] of contentDeltas.entries()) if (contentDelta.kind === "text") {
1717
+ const parts = gemmaToolCallRecoverer?.push(contentDelta.text) ?? [contentDelta];
1718
+ for (const part of parts) for (const routedDelta of reasoningTagTextPartitioner.pushVisible(part.text)) appendPartitionedVisibleDelta(routedDelta);
1719
+ } else {
1720
+ beginReasoning(contentDeltaIndex < lastVisibleTextIndex);
1721
+ if (emitReasoning) {
1722
+ if (currentBlock?.type === "toolCall" && !directMode) queuePostToolCallDelta(contentDelta);
1723
+ else appendContentDelta(contentDelta);
1724
+ }
1725
+ }
1726
+ if (!hasReasoningThinking) appendReasoningDeltas(reasoningDeltas);
1727
+ const toolCallDeltas = normalizedDelta.toolCalls;
1728
+ if (toolCallDeltas.length > 0) {
1729
+ flushGemmaToolCallRecoverer(false);
1730
+ sawNativeToolCallDelta = true;
1731
+ flushReasoningTagTextPartitioner(false);
1732
+ for (const toolCall of toolCallDeltas) {
1733
+ const streamIndex = typeof toolCall.index === "number" ? toolCall.index : void 0;
1734
+ let block = streamIndex !== void 0 ? toolCallBlocksByIndex.get(streamIndex) : void 0;
1735
+ if (!block && toolCall.id) block = toolCallBlocksById.get(toolCall.id);
1736
+ if (!block) {
1737
+ if (currentBlock?.type === "toolCall") {
1738
+ currentBlock = null;
1739
+ flushPendingPostToolCallDeltas();
1740
+ }
1741
+ const initialSig = directMode ? void 0 : extractToolCallThoughtSignature(toolCall);
1742
+ options?.beforeContentBlock?.("toolCall");
1743
+ if (directMode && directContent.block?.type === "thinking") directContent.block = null;
1744
+ block = {
1745
+ type: "toolCall",
1746
+ id: toolCall.id || "",
1747
+ name: toolCall.function?.name || "",
1748
+ arguments: {},
1749
+ partialJson: "",
1750
+ ...initialSig ? { thoughtSignature: initialSig } : {}
1751
+ };
1752
+ encryptedReasoning.rememberToolCall(block.id, block);
1753
+ toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
1754
+ appendToolCallBlock(block);
1755
+ }
1756
+ if (streamIndex !== void 0 && !toolCallBlocksByIndex.has(streamIndex)) toolCallBlocksByIndex.set(streamIndex, block);
1757
+ if (toolCall.id) {
1758
+ const previousId = block.id;
1759
+ if (!directMode || !block.id) block.id = toolCall.id;
1760
+ toolCallBlocksById.set(toolCall.id, block);
1761
+ if (block.id === toolCall.id) encryptedReasoning.rememberToolCall(toolCall.id, block, previousId);
1762
+ }
1763
+ currentBlock = block;
1764
+ const conflictingId = directMode && block.id && toolCall.id && block.id !== toolCall.id;
1765
+ if (toolCall.function?.name && !conflictingId) block.name = toolCall.function.name;
1766
+ const deltaSig = directMode ? void 0 : extractToolCallThoughtSignature(toolCall);
1767
+ if (deltaSig) block.thoughtSignature = deltaSig;
1768
+ const toolArgumentsDelta = toolCall.function?.arguments;
1769
+ if (toolArgumentsDelta) {
1770
+ block.partialJson += toolArgumentsDelta;
1771
+ if (toolArgumentPreviewSchedules.get(block)?.(block.partialJson.length)) block.arguments = parseStreamingJson(block.partialJson);
1772
+ }
1773
+ if (toolArgumentsDelta || directMode) pushStreamEvent({
1774
+ type: "toolcall_delta",
1775
+ contentIndex: blockIndices.get(block) ?? -1,
1776
+ delta: toolArgumentsDelta ?? "",
1777
+ partial: output
1778
+ });
1779
+ }
1780
+ }
1781
+ encryptedReasoning.consumeDetails(deltaFields.reasoning_details);
1782
+ }
1783
+ flushPendingPostToolCallDeltas();
1784
+ emitReasoningUsageActivity(hasReasoningUsageActivity);
1785
+ }
1786
+ throwIfModelStreamAborted(options?.signal);
1787
+ if (!finishReason && (directMode || options?.sawStreamDONE?.() === false)) throw new Error("Stream ended without finish_reason");
1788
+ flushGemmaToolCallRecoverer();
1789
+ flushReasoningTagTextPartitioner();
1790
+ appendRecoveredParts(deepSeekToolCallRecoverer?.flush() ?? []);
1791
+ for (const part of deepSeekTextFilter?.flush() ?? []) appendVisibleTextDelta(part);
1792
+ currentBlock = null;
1793
+ flushPendingPostToolCallDeltas();
1794
+ if (sawNativeToolCallDelta && recoveredToolCallBlocks.size > 0) output.content = output.content.filter((block) => block.type !== "toolCall" || !recoveredToolCallBlocks.has(block));
1795
+ finalizeOpenAICompletionsToolCalls(output, {
1796
+ allowSilentToolCallPromotion: finishReason === "stop" || sawNativeToolCallDelta && (options?.sawStreamDONE?.() ?? false),
1797
+ onConfirmedToolCall(block, contentIndex) {
1798
+ if (directMode) return;
1799
+ pushStreamEvent({
1800
+ type: "toolcall_end",
1801
+ contentIndex,
1802
+ toolCall: block,
1803
+ partial: output
1804
+ });
1805
+ }
1806
+ });
1807
+ output.usage.usageReport ??= { state: "unavailable" };
1808
+ if ((!output.usage.contextUsage || output.usage.usageReport.state === "unavailable") && !options?.signal?.aborted && output.stopReason !== "error" && output.stopReason !== "aborted") {
1809
+ output.usage.contextUsage = { state: "unavailable" };
1810
+ if (!compat.supportsUsageInStreaming) warnMissingStreamingUsage(openAIModel);
1811
+ }
1812
+ if (providerProcessingMs !== void 0) appendAssistantMessageDiagnostic(output, {
1813
+ type: "provider_timing",
1814
+ timestamp: Date.now(),
1815
+ details: { processingMs: providerProcessingMs }
1816
+ });
1817
+ if (suppressedReasoning) {
1818
+ const error = recordSuppressedReasoning(output);
1819
+ if (error) throw error;
1820
+ }
1821
+ }
1822
+ const MAX_MISSING_USAGE_HINT_KEYS = 256;
1823
+ const missingUsageHintKeys = /* @__PURE__ */ new Set();
1824
+ function warnMissingStreamingUsage(model) {
1825
+ if (detectOpenAICompletionsCompat(model).capabilities.endpointClass !== "custom") return;
1826
+ const key = `${model.provider}/${model.id}`;
1827
+ if (missingUsageHintKeys.has(key) || missingUsageHintKeys.size >= MAX_MISSING_USAGE_HINT_KEYS) return;
1828
+ missingUsageHintKeys.add(key);
1829
+ log.warn(`${key} returned no token usage; context size is estimated and token accounting is unavailable. If this endpoint supports stream_options.include_usage, set compat.supportsUsageInStreaming: true on the model in models.providers.${model.provider}.models.`, {
1830
+ provider: model.provider,
1831
+ model: model.id
1832
+ });
1833
+ }
1834
+ function shouldEmitOpenAICompletionsReasoning(model, options, mode = "managed") {
1835
+ if (model.compat?.requiresReasoningContentOnAssistantMessages || requiresReasoningContentReplay(model.id)) return true;
1836
+ if (!model.reasoning) return false;
1837
+ const effort = options?.reasoningEffort ?? (mode === "managed" ? options?.reasoning ?? "high" : void 0);
1838
+ return Boolean(effort && isOpenAICompletionsThinkingEnabled(effort));
1839
+ }
1840
+ //#endregion
1841
+ //#region packages/ai/src/providers/openai-web-search-tools.ts
1842
+ function hasResponsesWebSearchTool(tools) {
1843
+ if (!Array.isArray(tools)) return false;
1844
+ return tools.some((tool) => {
1845
+ if (!isRecord(tool)) return false;
1846
+ if (tool.type === "web_search") return true;
1847
+ if (tool.type === "function" && tool.name === "web_search") return true;
1848
+ const fn = tool.function;
1849
+ return isRecord(fn) && fn.name === "web_search";
1850
+ });
1851
+ }
1852
+ //#endregion
1853
+ //#region packages/ai/src/transports/openai-responses-params-internal.ts
1854
+ const OPENAI_CODEX_RESPONSES_UNSUPPORTED_PARAMS = [
1855
+ "max_output_tokens",
1856
+ "metadata",
1857
+ "prompt_cache_retention",
1858
+ "prompt_cache_options",
1859
+ "service_tier",
1860
+ "temperature",
1861
+ "top_p"
1862
+ ];
1863
+ function stripOpenAICodexResponsesUnsupportedTextFields(params) {
1864
+ const text = params.text;
1865
+ if (!text || typeof text !== "object" || Array.isArray(text)) return;
1866
+ const sanitizedText = { ...text };
1867
+ delete sanitizedText.format;
1868
+ if (Object.keys(sanitizedText).length > 0) params.text = sanitizedText;
1869
+ else delete params.text;
1870
+ }
1871
+ function sanitizeOpenAICodexResponsesParams(model, params) {
1872
+ if (!usesNativeOpenAICodexResponsesBackend(model)) return params;
1873
+ for (const key of OPENAI_CODEX_RESPONSES_UNSUPPORTED_PARAMS) delete params[key];
1874
+ Object.assign(params, { store: false });
1875
+ stripOpenAICodexResponsesUnsupportedTextFields(params);
1876
+ return params;
1877
+ }
1878
+ function buildOpenAIResponsesInstructionsText(context) {
1879
+ if (!context.systemPrompt) return;
1880
+ return prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions;
1881
+ }
1882
+ function buildOpenAIResponsesCompactSystemMessage(model, instructions) {
1883
+ const compat = getCompat(model);
1884
+ const role = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";
1885
+ return buildResponsesInputMessage(role, [{
1886
+ type: "input_text",
1887
+ text: instructions
1888
+ }]);
1889
+ }
1890
+ function buildOpenAIResponsesParams(model, context, options, metadata, replayMode = "checkpoint", retainUserProvenance = false) {
1891
+ const payloadPolicy = resolveOpenAIResponsesPayloadPolicy(model, { storeMode: "transport-default" });
1892
+ const policyAllowsReplayIds = payloadPolicy.explicitStore !== false && !payloadPolicy.shouldStripStore;
1893
+ const replayResponsesItemIds = !usesNativeOpenAICodexResponsesBackend(model) && (options?.replayResponsesItemIds ?? policyAllowsReplayIds);
1894
+ const messages = convertResponsesMessages(model, context, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
1895
+ includeSystemPrompt: !payloadPolicy.usesInstructionsField,
1896
+ replayResponsesItemIds,
1897
+ authProfileId: options?.authProfileId,
1898
+ mutableInput: Boolean(options?.onPayload),
1899
+ sessionId: options?.sessionId,
1900
+ replayMode,
1901
+ retainUserProvenance
1902
+ });
1903
+ if (messages.length === 0 && context.systemPrompt) {
1904
+ if (!buildOpenAIResponsesInstructionsText(context)) throw new Error("OpenAI Responses requires non-empty input when only systemPrompt is provided.");
1905
+ messages.push(buildResponsesInputMessage("user", [{
1906
+ type: "input_text",
1907
+ text: " "
1908
+ }]));
1909
+ }
1910
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention);
1911
+ const compat = getCompat(model);
1912
+ const promptCacheKey = compat.supportsPromptCacheKey ? resolvePromptCacheKey(options, cacheRetention) : void 0;
1913
+ let instructions = payloadPolicy.usesInstructionsField ? buildOpenAIResponsesInstructionsText(context) : void 0;
1914
+ if (payloadPolicy.usesInstructionsField && (!instructions || instructions.trim().length === 0)) instructions = usesNativeOpenAICodexResponsesBackend(model) ? OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS : void 0;
1915
+ const params = {
1916
+ model: model.id,
1917
+ input: messages,
1918
+ stream: true,
1919
+ prompt_cache_key: promptCacheKey,
1920
+ ...resolveOpenAIPromptCacheParams(model, cacheRetention, compat, options?.promptCacheTtl),
1921
+ ...instructions ? { instructions } : {},
1922
+ ...metadata ? { metadata } : {}
1923
+ };
1924
+ const effectiveMaxTokens = options?.maxTokens || model.maxTokens;
1925
+ if (effectiveMaxTokens) params.max_output_tokens = clampMaxTokensToModel(model, Math.max(effectiveMaxTokens, 16));
1926
+ if (options?.temperature !== void 0 && supportsOpenAITemperature(model)) params.temperature = options.temperature;
1927
+ if (options?.topP !== void 0 && (!isOpenAIGpt6Model(model) || resolveOpenAIThinkingApi(model.api) === "azure-openai-responses")) params.top_p = options.topP;
1928
+ if (options?.responseFormat !== void 0) params.text = {
1929
+ ...params.text,
1930
+ format: resolveOpenAIResponsesTextFormat(options.responseFormat)
1931
+ };
1932
+ if (options?.serviceTier !== void 0 && payloadPolicy.allowsServiceTier) params.service_tier = options.serviceTier;
1933
+ if (context.tools) {
1934
+ const tools = context.tools;
1935
+ const strict = getAiTransportHost().resolveOpenAIStrictToolSetting(model, {
1936
+ transport: "stream",
1937
+ supportsStrictMode: compat.supportsStrictMode
1938
+ });
1939
+ const { projection, tools: converted } = prepareResponsesTools(tools, strict, model, Boolean(options?.onPayload));
1940
+ if (converted.length > 0 || projection.inputToolCount === 0 && projection.diagnostics.length === 0) params.tools = converted;
1941
+ if (options?.toolChoice) {
1942
+ const toolChoice = reconcileOpenAIResponsesToolChoice(options.toolChoice, projection);
1943
+ if (toolChoice !== void 0) params.tool_choice = toolChoice;
1944
+ }
1945
+ }
1946
+ if (model.reasoning) {
1947
+ const reasoning = options?.reasoning;
1948
+ const requestedEffort = options?.reasoningEffort ?? (reasoning === "none" ? "none" : resolveOpenAISimpleReasoningEffort(model, reasoning)) ?? (options?.reasoningSummary ? "high" : payloadPolicy.defaultManagedReasoningEffort);
1949
+ const resolvedEffort = requestedEffort === void 0 ? void 0 : resolveOpenAIRequestReasoning(model, requestedEffort).effort;
1950
+ if (resolvedEffort !== void 0) {
1951
+ let effort = resolvedEffort;
1952
+ if (effort === "minimal" && hasResponsesWebSearchTool(params.tools)) for (const candidate of [
1953
+ "low",
1954
+ "medium",
1955
+ "high"
1956
+ ]) {
1957
+ const resolved = resolveOpenAIRequestReasoning(model, candidate).effort;
1958
+ if (resolved && resolved !== "none" && resolved !== "minimal") {
1959
+ effort = resolved;
1960
+ break;
1961
+ }
1962
+ }
1963
+ const summary = effort !== "none" && (options?.reasoningEffort || options?.reasoning || options?.reasoningSummary !== void 0) ? options.reasoningSummary === void 0 ? "auto" : options.reasoningSummary : void 0;
1964
+ params.reasoning = {
1965
+ effort,
1966
+ ...summary !== void 0 ? { summary } : {}
1967
+ };
1968
+ if (summary !== void 0) params.include = ["reasoning.encrypted_content"];
1969
+ }
1970
+ }
1971
+ applyOpenAIResponsesPayloadPolicy(params, payloadPolicy);
1972
+ return sanitizeOpenAICodexResponsesParams(model, params);
1973
+ }
1974
+ //#endregion
1975
+ //#region packages/ai/src/transports/openai-responses-compact-client.ts
1976
+ async function postOpenAIResponsesCompaction(params) {
1977
+ const instructions = typeof params.request.instructions === "string" && params.request.instructions.length > 0 ? params.request.instructions : void 0;
1978
+ const body = instructions && !supportsNativeOpenAIResponsesEndpoint(params.model) ? {
1979
+ model: params.request.model,
1980
+ input: [buildOpenAIResponsesCompactSystemMessage(params.model, instructions), ...params.request.input ?? []]
1981
+ } : {
1982
+ model: params.request.model,
1983
+ input: params.request.input,
1984
+ ...instructions ? { instructions } : {}
1985
+ };
1986
+ const response = await params.client.post("/responses/compact", {
1987
+ ...buildOpenAISdkRequestOptions(params.model, params.options?.signal, { timeoutMs: params.options?.timeoutMs }),
1988
+ body
1989
+ });
1990
+ if (!isRecord(response) || response.object !== "response.compaction") throw new Error("Responses compact endpoint must return a response.compaction object");
1991
+ const output = response.output;
1992
+ if (!isOpenAIResponsesCompactionOutput(output, params.model)) throw new Error(`Responses compact endpoint: ${getOpenAIResponsesCompactionOutputError(output, params.model)}`);
1993
+ const window = output;
1994
+ const item = window.at(-1);
1995
+ if (window.length > 1 && !supportsNativeOpenAIResponsesEndpoint(params.model)) throw new Error("Responses compact endpoint: retained messages require native OpenAI");
1996
+ const usage = isRecord(response.usage) ? response.usage : void 0;
1997
+ if (!usage || typeof usage.input_tokens !== "number" || typeof usage.output_tokens !== "number") throw new Error("Responses compact endpoint: usage must include input_tokens and output_tokens");
1998
+ const reasoningTokens = readResponsesReasoningTokens(usage);
1999
+ const modelUsage = {
2000
+ ...createZeroUsage(),
2001
+ ...mapResponsesTerminalUsage(usage),
2002
+ ...reasoningTokens === void 0 ? {} : { reasoningTokens },
2003
+ usageReport: { state: "available" }
2004
+ };
2005
+ calculateCost(params.model, modelUsage);
2006
+ applyResponsesCacheWritePricing(modelUsage, usage);
2007
+ return {
2008
+ output: window,
2009
+ item,
2010
+ historyMode: window.length > 1 ? "retained-users" : "compacted-prefix",
2011
+ usage,
2012
+ modelUsage,
2013
+ model: params.model,
2014
+ replayMetadata: buildOpenAIResponsesReasoningReplayMetadata(params.model, {
2015
+ authProfileId: params.options?.authProfileId,
2016
+ sessionId: params.options?.sessionId
2017
+ })
2018
+ };
2019
+ }
2020
+ //#endregion
2021
+ //#region packages/ai/src/transports/openai-responses-reasoning-state.ts
2022
+ /** Save only admitted settings and hashes, never another copy of the conversation. */
2023
+ function recordResponsesReasoningState(message, model, identity, request, output) {
2024
+ if (!supportsResponsesReasoningUpdate(request) || !isRecord(request.reasoning) || !request.input || request.previous_response_id || message.providerReplay || output.some((item) => isRecord(item) && item.type === "compaction")) return;
2025
+ const reasoning = {
2026
+ ...buildProviderReplayContext(model, identity),
2027
+ effort: request.reasoning.effort,
2028
+ controls: request.input.flatMap((item, index) => isConfigurationUpdate(item) ? [{
2029
+ index,
2030
+ item
2031
+ }] : []),
2032
+ inputLength: request.input.length,
2033
+ outputLength: output.length,
2034
+ prefixHash: responsesContinuationPrefixFingerprint(request.input, output),
2035
+ requestHash: responsesContinuationRequestFingerprint(request)
2036
+ };
2037
+ Object.assign(message, { openclawResponsesInputReplay: {
2038
+ ...readResponsesInputReplayState(message),
2039
+ reasoning
2040
+ } });
2041
+ }
2042
+ /** A cold transport can replay controls, but cannot resurrect a server response handle. */
2043
+ function restoreResponsesReasoningState(context, model, identity, request) {
2044
+ const latest = context.messages.findLast((message) => message.role === "assistant");
2045
+ const state = latest ? readResponsesInputReplayState(latest)?.reasoning : void 0;
2046
+ if (!isRecord(state)) return request;
2047
+ const { effort, inputLength, outputLength, controls, prefixHash, requestHash } = state;
2048
+ if (!isProviderReplayContext(state) || !providerReplayContextMatches(state, buildProviderReplayContext(model, identity)) || latest?.providerReplay || !supportsResponsesReasoningUpdate(request) || !isRecord(request.reasoning) || !request.input || request.previous_response_id || request.input.some(isConfigurationUpdate) || typeof effort !== "string" || typeof inputLength !== "number" || !Number.isSafeInteger(inputLength) || inputLength < 0 || typeof outputLength !== "number" || !Number.isSafeInteger(outputLength) || outputLength < 0 || !Array.isArray(controls) || controls.length > inputLength || inputLength + outputLength > request.input.length + controls.length) return request;
2049
+ const previousInput = request.input.slice(0, inputLength - controls.length);
2050
+ let lastIndex = -1;
2051
+ for (const control of controls) {
2052
+ if (!isRecord(control) || typeof control.index !== "number" || !Number.isSafeInteger(control.index) || control.index <= lastIndex || control.index > previousInput.length || !isConfigurationUpdate(control.item)) return request;
2053
+ previousInput.splice(control.index, 0, control.item);
2054
+ lastIndex = control.index;
2055
+ }
2056
+ const previous = {
2057
+ ...request,
2058
+ reasoning: {
2059
+ ...request.reasoning,
2060
+ effort
2061
+ },
2062
+ input: previousInput
2063
+ };
2064
+ if (responsesContinuationRequestFingerprint(previous) !== requestHash) return request;
2065
+ const prepared = replayResponsesReasoningUpdates(previous, request, outputLength);
2066
+ if (responsesContinuationPrefixFingerprint((prepared.input ?? []).slice(0, inputLength + outputLength)) !== prefixHash) return request;
2067
+ return prepared;
2068
+ }
2069
+ //#endregion
2070
+ //#region packages/ai/src/transports/openai-responses-request-fetch.ts
2071
+ function withDefaultResponsesStreamEncoding(fetch) {
2072
+ return (input, init) => {
2073
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
2074
+ if (headers.has("accept-encoding")) return fetch(input, init);
2075
+ headers.set("accept-encoding", "identity");
2076
+ return fetch(input, {
2077
+ ...init,
2078
+ headers
2079
+ });
2080
+ };
2081
+ }
2082
+ /** Preserve the existing fetch policy while binding explicit continuation dispatch to its signal. */
2083
+ function createResponsesRequestFetch(model, options) {
2084
+ const lifecycle = options.lifecycle;
2085
+ if (lifecycle && options.compact) throw new Error("Provider review continuation cannot replace its reviewed input with compaction");
2086
+ let fetchOverride = options.compact ? createBoundedOpenAIResponsesCompactionFetch(buildGuardedModelFetch(model)) : options.stream ? withDefaultResponsesStreamEncoding(buildGuardedModelFetch(model, void 0, { onSseComment: options.onSseComment })) : void 0;
2087
+ if (lifecycle) {
2088
+ const dispatchFetch = fetchOverride ?? buildGuardedModelFetch(model);
2089
+ fetchOverride = async (input, init) => {
2090
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
2091
+ await lifecycle.beforeDispatch(signal ?? void 0);
2092
+ signal?.throwIfAborted();
2093
+ lifecycle.assertCurrent();
2094
+ return dispatchFetch(input, init);
2095
+ };
2096
+ }
2097
+ return fetchOverride;
2098
+ }
2099
+ //#endregion
2100
+ //#region packages/ai/src/transports/openai-responses-steering.ts
2101
+ function cloneWireRequest(request) {
2102
+ const serialized = JSON.stringify(request);
2103
+ return JSON.parse(serialized);
2104
+ }
2105
+ async function projectResponsesSteeringInput(request, project) {
2106
+ const { input: activeInput, ...activeSettings } = cloneWireRequest(request);
2107
+ if (!Array.isArray(activeInput)) return [];
2108
+ const { input, ...settings } = cloneWireRequest(await project());
2109
+ if (!Array.isArray(input) || !isDeepStrictEqual(settings, activeSettings) || !isDeepStrictEqual(input.slice(0, activeInput.length), activeInput)) return [];
2110
+ const projected = input.slice(activeInput.length);
2111
+ return projected.every((item) => isRecord(item) && item.role === "user") ? projected : [];
2112
+ }
2113
+ /** One response owns admission; accepted input stays on this connection until continuation. */
2114
+ function createResponsesSteering(params) {
2115
+ const needsContinuation = params.needsContinuation;
2116
+ let responseId;
2117
+ let active = params;
2118
+ let unsubscribe;
2119
+ const pending = [];
2120
+ const accepted = /* @__PURE__ */ new Map();
2121
+ const acknowledged = /* @__PURE__ */ new Set();
2122
+ const seal = () => {
2123
+ active = void 0;
2124
+ const cleanup = unsubscribe;
2125
+ unsubscribe = void 0;
2126
+ cleanup?.();
2127
+ };
2128
+ return {
2129
+ get responseId() {
2130
+ return responseId;
2131
+ },
2132
+ get pending() {
2133
+ return pending.length > 0;
2134
+ },
2135
+ get acceptedInput() {
2136
+ return [...accepted.values()].flat();
2137
+ },
2138
+ seal,
2139
+ close(error) {
2140
+ seal();
2141
+ for (const submission of pending.splice(0)) submission.reject(error);
2142
+ },
2143
+ handle(event) {
2144
+ if (!isRecord(event)) return false;
2145
+ if (event.type === "response.created" && !responseId && active) {
2146
+ const response = isRecord(event.response) ? event.response : void 0;
2147
+ if (typeof response?.id !== "string" || !response.id.trim()) throw new Error("Responses steering requires a response identity");
2148
+ const activeResponseId = response.id;
2149
+ responseId = activeResponseId;
2150
+ const cleanup = active.onActiveResponse({
2151
+ needsContinuation: needsContinuation === void 0 ? void 0 : () => needsContinuation,
2152
+ steer(messages) {
2153
+ if (!active || messages.length === 0) return Promise.resolve(false);
2154
+ active.assertActive();
2155
+ const converted = active.toInput(messages);
2156
+ const submit = (input) => {
2157
+ const callbacks = active;
2158
+ if (!callbacks || input.length === 0) return Promise.resolve(false);
2159
+ callbacks.assertActive();
2160
+ return new Promise((resolve, reject) => {
2161
+ pending.push({
2162
+ input,
2163
+ resolve,
2164
+ reject
2165
+ });
2166
+ callbacks.send({
2167
+ type: "response.steer",
2168
+ previous_response_id: activeResponseId,
2169
+ input
2170
+ });
2171
+ });
2172
+ };
2173
+ return Array.isArray(converted) ? submit(converted) : converted.then(submit);
2174
+ }
2175
+ });
2176
+ if (!active) cleanup?.();
2177
+ else unsubscribe = cleanup;
2178
+ return false;
2179
+ }
2180
+ if (event.type !== "response.steer.accepted" && event.type !== "response.steer.failed" && event.type !== "response.steer.pending") return false;
2181
+ const steer = isRecord(event.steer) ? event.steer : void 0;
2182
+ if (!responseId || steer?.previous_response_id !== responseId) throw new Error("Responses steering acknowledgement has an unexpected identity");
2183
+ if (event.type === "response.steer.failed" && steer.id === void 0) {
2184
+ const index = pending.findIndex((submission) => stableStringify(submission.input) === stableStringify(steer.input));
2185
+ const submission = pending[index];
2186
+ if (!submission) throw new Error("Responses steering acknowledgement has no pending submission");
2187
+ pending.splice(index, 1);
2188
+ submission.resolve(false);
2189
+ return true;
2190
+ }
2191
+ if (typeof steer.id !== "string" || !steer.id.trim()) throw new Error("Responses steering acknowledgement has an unexpected identity");
2192
+ if (event.type === "response.steer.pending") {
2193
+ if (!accepted.has(steer.id)) throw new Error("Responses steering pending event has no accepted submission");
2194
+ return true;
2195
+ }
2196
+ if (event.type === "response.steer.failed" && accepted.has(steer.id)) throw new Error("OpenAI could not apply accepted steering; the queued message remains in the conversation");
2197
+ if (acknowledged.has(steer.id)) throw new Error("Responses steering acknowledgement was already applied");
2198
+ const submission = pending.shift();
2199
+ if (!submission) throw new Error("Responses steering acknowledgement has no pending submission");
2200
+ acknowledged.add(steer.id);
2201
+ if (event.type === "response.steer.accepted") {
2202
+ accepted.set(steer.id, submission.input);
2203
+ submission.resolve(true);
2204
+ } else submission.resolve(false);
2205
+ return true;
2206
+ }
2207
+ };
2208
+ }
2209
+ /** Accepted steering is prepended by the server, so never repeat it in response.create. */
2210
+ function omitAcceptedSteering(input, accepted) {
2211
+ const remaining = [...input];
2212
+ for (const message of accepted) {
2213
+ const index = remaining.findIndex((item) => stableStringify(item) === stableStringify(message));
2214
+ if (index < 0) throw new Error("Responses steering continuation no longer contains the accepted user input");
2215
+ remaining.splice(index, 1);
2216
+ }
2217
+ return remaining;
2218
+ }
2219
+ //#endregion
2220
+ //#region packages/ai/src/transports/openai-responses-websocket-recovery.ts
2221
+ /** Owns safe WebSocket rejection recovery; transport selection and session leases stay with the caller. */
2222
+ function createRecoverableResponsesWebSocketStream(params) {
2223
+ const { trackedWebSocketStream, websocket, websocketSignal, options, output, buildRequest, createSseStream, closeWebSocketForFallback, logWebSocketFallback, startStream } = params;
2224
+ return { async *[Symbol.asyncIterator]() {
2225
+ let acceptance = "pending";
2226
+ let outputObserved = false;
2227
+ try {
2228
+ for await (const event of trackedWebSocketStream) {
2229
+ const { failure, hasResponseOutput, isPrelude } = readResponsesRecoveryEvent(event);
2230
+ outputObserved ||= hasResponseOutput;
2231
+ if (isResponsesServiceTierRejection(failure) && !websocket.hasActiveResponse) throw new OpenAIResponsesWebSocketSafeRetryError("invalid_request_error", void 0, "service_tier", "Invalid service_tier argument", failure);
2232
+ outputObserved ||= !isPrelude;
2233
+ if (acceptance === "pending") {
2234
+ acceptance = "observing";
2235
+ await notifyProviderStreamOpened({
2236
+ options,
2237
+ cancelStream: () => websocket.finish({ keep: false })
2238
+ });
2239
+ acceptance = "accepted";
2240
+ }
2241
+ startStream();
2242
+ yield event;
2243
+ }
2244
+ } catch (error) {
2245
+ if (error instanceof OpenAIResponsesWebSocketSafeRetryError) {
2246
+ if (isResponsesServiceTierRejection(error)) {
2247
+ const nextTier = nextResponsesServiceTier(websocket.request.service_tier, error);
2248
+ if (!nextTier || outputObserved || acceptance === "observing" || output.content.length || websocketSignal.aborted || websocket.hasActiveResponse) throw error;
2249
+ closeWebSocketForFallback("service_tier_rejected");
2250
+ const rejectedTier = websocket.request.service_tier;
2251
+ if (rejectedTier === "ultrafast" || rejectedTier === "priority") responsesServiceTierObserver.reject(options, rejectedTier);
2252
+ yield* await createSseStream({
2253
+ ...await buildRequest("full-history"),
2254
+ service_tier: nextTier
2255
+ });
2256
+ return;
2257
+ }
2258
+ const encryptedContentRejected = isInvalidEncryptedContentError(error);
2259
+ const recovery = encryptedContentRejected ? await resolveNextResponsesEncryptedContentAttempt({
2260
+ kind: "initial",
2261
+ request: {
2262
+ ...websocket.request,
2263
+ stream: true
2264
+ }
2265
+ }, error, { buildFullHistoryRequest: () => buildRequest("full-history") }) : void 0;
2266
+ if (encryptedContentRejected && !recovery) throw error;
2267
+ closeWebSocketForFallback(`safe_server_error code=${error.code} status=${safeDebugValue(error.status)} param=${safeDebugValue(error.param)}`);
2268
+ yield* await createSseStream(recovery?.request ?? await buildRequest("full-history"), recovery?.kind ?? "continuation-rejected", recovery?.rejectedCompaction);
2269
+ return;
2270
+ }
2271
+ if (websocketSignal.aborted || !(error instanceof OpenAIResponsesWebSocketPreDispatchError)) throw error;
2272
+ params.setTransportToSse();
2273
+ logWebSocketFallback("before_first_event");
2274
+ yield* await createSseStream();
2275
+ }
2276
+ } };
2277
+ }
2278
+ //#endregion
2279
+ //#region packages/ai/src/transports/openai-responses-websocket.ts
2280
+ const SESSION_WEBSOCKET_CACHE_TTL_MS = 3e5;
2281
+ const SESSION_WEBSOCKET_MAX_AGE_MS = 33e5;
2282
+ const WEBSOCKET_OPEN_STATE = 1;
2283
+ function resolveNativeOpenAIResponsesWebSocketMode(model, transport) {
2284
+ if (transport !== "websocket" && transport !== "websocket-cached" && transport !== "auto") return;
2285
+ if (getAiTransportHost().requiresManagedTransport(model, "fetch")) return;
2286
+ return supportsNativeOpenAIResponsesEndpoint(model) ? transport : void 0;
2287
+ }
2288
+ function combineWebSocketTimeoutSignal(signal, model, timeoutMs) {
2289
+ const resolvedTimeoutMs = timeoutMs !== void 0 && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : getAiTransportHost().resolveModelRequestTimeoutMs(model);
2290
+ if (resolvedTimeoutMs === void 0 || !Number.isFinite(resolvedTimeoutMs)) return signal;
2291
+ return AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, resolvedTimeoutMs))]);
2292
+ }
2293
+ const websocketSessionCache = /* @__PURE__ */ new Map();
2294
+ const degradedWebSocketConnections = /* @__PURE__ */ new Map();
2295
+ function closeWebSocketSilently(socket, reason = "done") {
2296
+ try {
2297
+ socket.close({
2298
+ code: 1e3,
2299
+ reason
2300
+ });
2301
+ } catch {}
2302
+ }
2303
+ function invalidateOwnedWebSocketSession(cacheKey, entry, reason = "done") {
2304
+ if (entry.idleTimer) {
2305
+ clearTimeout(entry.idleTimer);
2306
+ entry.idleTimer = void 0;
2307
+ }
2308
+ closeWebSocketSilently(entry.socket, reason);
2309
+ entry.steeringContinuation?.steering.close(/* @__PURE__ */ new Error("Responses steering connection closed"));
2310
+ entry.steeringContinuation?.iterator.return?.().catch(() => void 0);
2311
+ entry.steeringContinuation = void 0;
2312
+ if (websocketSessionCache.get(cacheKey) === entry) websocketSessionCache.delete(cacheKey);
2313
+ }
2314
+ function scheduleSessionWebSocketExpiry(cacheKey, entry) {
2315
+ if (entry.idleTimer) clearTimeout(entry.idleTimer);
2316
+ entry.idleTimer = entry.owner.runInDetachedAsyncContext(() => setTimeout(() => {
2317
+ if (entry.busy) return;
2318
+ invalidateOwnedWebSocketSession(cacheKey, entry, "idle_timeout");
2319
+ }, SESSION_WEBSOCKET_CACHE_TTL_MS));
2320
+ entry.idleTimer.unref?.();
2321
+ }
2322
+ function markDegradedWebSocketConnection(key, owner, sessionId, cooldownMs) {
2323
+ if (cooldownMs === void 0 || !Number.isFinite(cooldownMs) || cooldownMs <= 0) return;
2324
+ const entry = {
2325
+ sessionId,
2326
+ owner,
2327
+ retryAt: Date.now() + cooldownMs,
2328
+ expiryTimer: owner.runInDetachedAsyncContext(() => setTimeout(() => {
2329
+ if (degradedWebSocketConnections.get(key) === entry) degradedWebSocketConnections.delete(key);
2330
+ }, cooldownMs))
2331
+ };
2332
+ entry.expiryTimer.unref?.();
2333
+ degradedWebSocketConnections.set(key, entry);
2334
+ }
2335
+ function prepareWebSocketConnection(client, headers) {
2336
+ if (!isOfficialOpenAIResponsesBaseUrl(client.baseURL)) throw new Error("OpenAI Responses WebSocket requires the official API endpoint");
2337
+ if (typeof client.apiKey !== "string" || client.apiKey.length === 0) throw new Error("OpenAI Responses WebSocket requires an API key");
2338
+ const owner = getAiTransportHost();
2339
+ const resolvedApiKey = owner.resolveSecretSentinel(client.apiKey);
2340
+ const resolvedHeaders = { ...omitNullRequestHeaders(resolveAiTransportHeaderSentinels(headers)) };
2341
+ for (const key of Object.keys(resolvedHeaders)) {
2342
+ const normalizedKey = key.toLowerCase();
2343
+ if (normalizedKey === "authorization" || normalizedKey === "traceparent") delete resolvedHeaders[key];
2344
+ }
2345
+ if (!resolvedApiKey) throw new Error("OpenAI Responses WebSocket requires a resolved API key");
2346
+ return {
2347
+ client: client.withOptions({
2348
+ apiKey: resolvedApiKey,
2349
+ fetch: void 0,
2350
+ logger: void 0
2351
+ }),
2352
+ headers: resolvedHeaders,
2353
+ owner,
2354
+ ownerId: getSessionResourceOwnerId(owner),
2355
+ identity: sha256Hex(JSON.stringify([
2356
+ resolvedApiKey,
2357
+ client.baseURL,
2358
+ Object.entries(resolvedHeaders).toSorted(([a], [b]) => a.localeCompare(b))
2359
+ ]))
2360
+ };
2361
+ }
2362
+ function createWebSocket(connection, onError) {
2363
+ const socket = connection.owner.runInDetachedAsyncContext(() => new ResponsesWS(connection.client, {
2364
+ headers: connection.headers,
2365
+ maxQueueSize: 1
2366
+ }));
2367
+ socket.on("error", () => onError(socket));
2368
+ return socket;
2369
+ }
2370
+ function createTransientWebSocketLease(connection) {
2371
+ const socket = createWebSocket(connection, (failedSocket) => closeWebSocketSilently(failedSocket, "transport_error"));
2372
+ return {
2373
+ socket,
2374
+ iterator: socket.stream(),
2375
+ reusedConnection: false,
2376
+ release: () => closeWebSocketSilently(socket)
2377
+ };
2378
+ }
2379
+ function createCachedWebSocketLease(cacheKey, entry, reusedConnection) {
2380
+ entry.busy = true;
2381
+ const steeringContinuation = entry.steeringContinuation;
2382
+ entry.steeringContinuation = void 0;
2383
+ return {
2384
+ socket: entry.socket,
2385
+ iterator: steeringContinuation?.iterator ?? entry.socket.stream(),
2386
+ entry,
2387
+ reusedConnection,
2388
+ steeringContinuation,
2389
+ release: (options = {}) => {
2390
+ const { keep } = options;
2391
+ if (!keep || entry.socket.socket.readyState !== WEBSOCKET_OPEN_STATE) {
2392
+ invalidateOwnedWebSocketSession(cacheKey, entry);
2393
+ return;
2394
+ }
2395
+ entry.busy = false;
2396
+ scheduleSessionWebSocketExpiry(cacheKey, entry);
2397
+ }
2398
+ };
2399
+ }
2400
+ function acquireWebSocket(params, connection) {
2401
+ if (params.mode === "websocket" || !params.sessionId) return createTransientWebSocketLease(connection);
2402
+ const cacheKey = `${connection.ownerId}\0${params.sessionId}\0${connection.identity}`;
2403
+ const cached = websocketSessionCache.get(cacheKey);
2404
+ if (cached) {
2405
+ if (cached.idleTimer) {
2406
+ clearTimeout(cached.idleTimer);
2407
+ cached.idleTimer = void 0;
2408
+ }
2409
+ if (cached.busy) return createTransientWebSocketLease(connection);
2410
+ const expired = Date.now() - cached.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS;
2411
+ if (!expired && cached.socket.socket.readyState === WEBSOCKET_OPEN_STATE) return createCachedWebSocketLease(cacheKey, cached, true);
2412
+ invalidateOwnedWebSocketSession(cacheKey, cached, expired ? "connection_age_limit" : "done");
2413
+ }
2414
+ const entry = {
2415
+ socket: createWebSocket(connection, (failedSocket) => {
2416
+ const failedEntry = websocketSessionCache.get(cacheKey);
2417
+ if (failedEntry?.socket === failedSocket) invalidateOwnedWebSocketSession(cacheKey, failedEntry, "transport_error");
2418
+ else closeWebSocketSilently(failedSocket, "transport_error");
2419
+ }),
2420
+ sessionId: params.sessionId,
2421
+ owner: connection.owner,
2422
+ busy: true,
2423
+ createdAt: Date.now()
2424
+ };
2425
+ websocketSessionCache.set(cacheKey, entry);
2426
+ return createCachedWebSocketLease(cacheKey, entry, false);
2427
+ }
2428
+ function sanitizeWebSocketRequest(request) {
2429
+ const { stream: _stream, background: _background, ...websocketRequest } = request;
2430
+ return websocketRequest;
2431
+ }
2432
+ async function nextWebSocketMessage(iterator, signal) {
2433
+ if (signal?.aborted) throw transportAbortError(signal);
2434
+ return await racePromiseWithAbortSignal(iterator.next(), signal, transportAbortError);
2435
+ }
2436
+ function readServerEvent(message) {
2437
+ if (message.type === "message") return message.message;
2438
+ if (message.type === "error") throw parseOpenAIResponsesWebSocketServerError(message.error) ?? new Error("OpenAI Responses WebSocket transport failed", { cause: message.error });
2439
+ if (message.type === "close") throw new Error(`OpenAI Responses WebSocket closed before completion (code ${message.code})`);
2440
+ }
2441
+ function createOpenAIResponsesWebSocketStream(params) {
2442
+ const connection = prepareWebSocketConnection(params.client, params.headers);
2443
+ let fullRequest = sanitizeWebSocketRequest(params.request);
2444
+ const requestModel = typeof fullRequest.model === "string" ? fullRequest.model : "";
2445
+ const degradationKey = `${connection.ownerId}\0${params.sessionId ?? ""}\0${connection.identity}\0${requestModel}`;
2446
+ const degraded = degradedWebSocketConnections.get(degradationKey);
2447
+ if (degraded && degraded.retryAt > Date.now()) throw new OpenAIResponsesWebSocketPreDispatchError(/* @__PURE__ */ new Error("OpenAI Responses WebSocket is cooling down after a transport failure"));
2448
+ if (degraded) clearTimeout(degraded.expiryTimer);
2449
+ degradedWebSocketConnections.delete(degradationKey);
2450
+ const markDegraded = () => markDegradedWebSocketConnection(degradationKey, connection.owner, params.sessionId, params.degradeCooldownMs);
2451
+ let lease;
2452
+ try {
2453
+ lease = acquireWebSocket(params, connection);
2454
+ } catch (error) {
2455
+ markDegraded();
2456
+ throw new OpenAIResponsesWebSocketPreDispatchError(error);
2457
+ }
2458
+ let prepared;
2459
+ let previousContinuation;
2460
+ const resumedSteering = lease.steeringContinuation;
2461
+ const steeringMode = resumedSteering ? resumedSteering.requiresInput ? "required-input" : "automatic" : void 0;
2462
+ try {
2463
+ const continuation = previousContinuation = lease.entry?.continuation;
2464
+ if (continuation && lease.entry) {
2465
+ lease.entry.continuation = void 0;
2466
+ prepared = resolveResponsesContinuationRequest(continuation, fullRequest, steeringMode);
2467
+ } else {
2468
+ fullRequest = params.restoreRequest?.(fullRequest) ?? fullRequest;
2469
+ prepared = {
2470
+ request: fullRequest,
2471
+ continuationStatus: lease.entry ? "no_previous_response" : "socket_not_cached"
2472
+ };
2473
+ }
2474
+ } catch (error) {
2475
+ lease.iterator.return?.().catch(() => void 0);
2476
+ lease.release({ keep: false });
2477
+ throw error;
2478
+ }
2479
+ let streamStarted = false;
2480
+ let terminalResponse;
2481
+ let terminalReceived = false;
2482
+ let released = false;
2483
+ let retainIterator = false;
2484
+ let deferredInput = false;
2485
+ let inputReplay;
2486
+ if (resumedSteering) try {
2487
+ if (prepared.continuationStatus !== "continued" || !prepared.request.previous_response_id) throw new Error("Responses steering continuation changed its request or history");
2488
+ const input = omitAcceptedSteering(prepared.request.input ?? [], resumedSteering.acceptedInput);
2489
+ if (!resumedSteering.requiresInput && (stableStringify(fullRequest.instructions) !== stableStringify(resumedSteering.instructions) || stableStringify(fullRequest.tools) !== stableStringify(resumedSteering.tools))) throw new Error("Responses automatic steering continuation cannot change instructions or tools");
2490
+ const baseline = prepared.fullRequest ?? fullRequest;
2491
+ const priorLength = (baseline.input?.length ?? 0) - (prepared.request.input?.length ?? 0);
2492
+ const fingerprints = input.map(responsesInputFingerprint);
2493
+ if (fingerprints.length > 0) inputReplay = {
2494
+ afterResponseId: prepared.request.previous_response_id,
2495
+ before: resumedSteering.requiresInput ? fingerprints : [],
2496
+ after: resumedSteering.requiresInput ? [] : fingerprints
2497
+ };
2498
+ const delivered = resumedSteering.requiresInput ? input : [];
2499
+ prepared.fullRequest = {
2500
+ ...baseline,
2501
+ input: [
2502
+ ...(baseline.input ?? []).slice(0, priorLength),
2503
+ ...resumedSteering.acceptedInput,
2504
+ ...delivered
2505
+ ]
2506
+ };
2507
+ prepared.request = {
2508
+ ...prepared.request,
2509
+ input: delivered
2510
+ };
2511
+ deferredInput = !resumedSteering.requiresInput && input.length > 0;
2512
+ } catch (error) {
2513
+ lease.iterator.return?.().catch(() => void 0);
2514
+ lease.release({ keep: false });
2515
+ throw new OpenAIResponsesWebSocketPostDispatchError(error);
2516
+ }
2517
+ const steering = lease.entry && params.onActiveResponse && params.steeringInput ? createResponsesSteering({
2518
+ onActiveResponse: params.onActiveResponse,
2519
+ toInput: params.steeringInput,
2520
+ send: (event) => lease.socket.sendRaw(JSON.stringify(event)),
2521
+ needsContinuation: deferredInput,
2522
+ assertActive: () => {
2523
+ if (released || terminalReceived || params.signal?.aborted) throw new Error("Responses steering is no longer active");
2524
+ }
2525
+ }) : void 0;
2526
+ const finish = ({ keep = true } = {}) => {
2527
+ if (released) return;
2528
+ released = true;
2529
+ if (keep && lease.entry && terminalResponse) lease.entry.continuation = recordResponsesContinuationState(previousContinuation, prepared.fullRequest ?? fullRequest, terminalResponse, previousContinuation?.lastResponseId === prepared.request.previous_response_id);
2530
+ lease.release({ keep });
2531
+ };
2532
+ return {
2533
+ stream: { async *[Symbol.asyncIterator]() {
2534
+ if (streamStarted) throw new Error("OpenAI Responses WebSocket stream can only be consumed once");
2535
+ streamStarted = true;
2536
+ const iterator = lease.iterator;
2537
+ let requestDispatched = false;
2538
+ try {
2539
+ if (params.signal?.aborted) throw transportAbortError(params.signal);
2540
+ if (resumedSteering) {
2541
+ requestDispatched = true;
2542
+ if (resumedSteering.requiresInput) lease.socket.send({
2543
+ ...prepared.request,
2544
+ type: "response.create"
2545
+ });
2546
+ }
2547
+ for (;;) {
2548
+ const buffered = resumedSteering?.buffered.shift();
2549
+ const next = buffered ? {
2550
+ value: buffered,
2551
+ done: false
2552
+ } : await nextWebSocketMessage(iterator, params.signal);
2553
+ if (next.done) throw new Error("OpenAI Responses WebSocket closed before a terminal response event");
2554
+ if (next.value.type === "open") {
2555
+ if (!requestDispatched) {
2556
+ requestDispatched = true;
2557
+ lease.socket.send({
2558
+ ...prepared.request,
2559
+ type: "response.create"
2560
+ });
2561
+ }
2562
+ continue;
2563
+ }
2564
+ const event = readServerEvent(next.value);
2565
+ if (!event) continue;
2566
+ if (isRecord(event) && typeof event.type === "string" && event.type.startsWith("response.steer.")) {
2567
+ if ((isRecord(event.steer) && event.steer.previous_response_id === steering?.responseId ? steering : resumedSteering?.steering ?? steering)?.handle(event)) continue;
2568
+ }
2569
+ steering?.handle(event);
2570
+ if (event.type === "response.completed") terminalResponse = event.response;
2571
+ terminalReceived = isResponsesTerminalEventType(event.type);
2572
+ if (terminalReceived) {
2573
+ steering?.seal();
2574
+ if (event.type === "response.failed") steering?.close(/* @__PURE__ */ new Error("Responses failed before steering could be applied"));
2575
+ const continuationBuffer = [];
2576
+ for (;;) {
2577
+ if (!steering?.pending) break;
2578
+ const acknowledgement = await nextWebSocketMessage(iterator, params.signal);
2579
+ if (acknowledgement.done) throw new Error("Responses closed before acknowledging steering");
2580
+ const acknowledgedEvent = readServerEvent(acknowledgement.value);
2581
+ if (!steering.handle(acknowledgedEvent)) continuationBuffer.push(acknowledgement.value);
2582
+ }
2583
+ const acceptedInput = steering?.acceptedInput ?? [];
2584
+ const isSteered = event.type === "response.incomplete" && isRecord(event.response.incomplete_details) && event.response.incomplete_details.reason === "steered";
2585
+ if (lease.entry && steering && acceptedInput.length > 0 && (event.type === "response.completed" || isSteered)) {
2586
+ if (event.type === "response.incomplete") terminalResponse = event.response;
2587
+ lease.entry.steeringContinuation = {
2588
+ iterator,
2589
+ buffered: continuationBuffer,
2590
+ acceptedInput,
2591
+ requiresInput: (terminalResponse?.output ?? []).some((item) => (item.type === "function_call" || item.type === "custom_tool_call") && !(isRecord(item) && item.async === true) || item.type === "mcp_approval_request"),
2592
+ steering,
2593
+ instructions: fullRequest.instructions,
2594
+ tools: fullRequest.tools
2595
+ };
2596
+ retainIterator = true;
2597
+ if (isSteered) {
2598
+ yield {
2599
+ ...event,
2600
+ type: "response.completed",
2601
+ response: {
2602
+ ...event.response,
2603
+ status: "completed",
2604
+ incomplete_details: null
2605
+ }
2606
+ };
2607
+ return;
2608
+ }
2609
+ }
2610
+ }
2611
+ yield event;
2612
+ if (terminalReceived) {
2613
+ degradedWebSocketConnections.delete(degradationKey);
2614
+ return;
2615
+ }
2616
+ }
2617
+ } catch (error) {
2618
+ const steeringDispatched = Boolean(steering?.pending || steering?.acceptedInput.length || resumedSteering);
2619
+ steering?.close(error instanceof Error ? error : /* @__PURE__ */ new Error("Responses steering failed"));
2620
+ if (lease.entry) lease.entry.continuation = void 0;
2621
+ const safeRetry = error instanceof OpenAIResponsesWebSocketSafeRetryError && !steeringDispatched;
2622
+ if (!params.callerSignal?.aborted && !safeRetry) markDegraded();
2623
+ if (!requestDispatched && !params.signal?.aborted) throw new OpenAIResponsesWebSocketPreDispatchError(error);
2624
+ if (!requestDispatched || params.callerSignal?.aborted || safeRetry) throw error;
2625
+ throw new OpenAIResponsesWebSocketPostDispatchError(error);
2626
+ } finally {
2627
+ steering?.seal();
2628
+ if (!retainIterator) {
2629
+ steering?.close(/* @__PURE__ */ new Error("Responses stream ended before steering was confirmed"));
2630
+ await iterator.return?.().catch(() => void 0);
2631
+ }
2632
+ if (!terminalReceived) finish({ keep: false });
2633
+ }
2634
+ } },
2635
+ request: prepared.request,
2636
+ fullRequest: prepared.fullRequest ?? fullRequest,
2637
+ reusedConnection: lease.reusedConnection,
2638
+ continuationStatus: prepared.continuationStatus,
2639
+ inputReplay,
2640
+ get hasActiveResponse() {
2641
+ return Boolean(steering?.responseId || resumedSteering);
2642
+ },
2643
+ finish
2644
+ };
2645
+ }
2646
+ function closeOpenAIResponsesWebSocketSessions(sessionId, owner) {
2647
+ for (const [cacheKey, entry] of websocketSessionCache) {
2648
+ if (owner && entry.owner !== owner || sessionId && entry.sessionId !== sessionId) continue;
2649
+ invalidateOwnedWebSocketSession(cacheKey, entry, "session_cleanup");
2650
+ }
2651
+ for (const [key, entry] of degradedWebSocketConnections) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) {
2652
+ clearTimeout(entry.expiryTimer);
2653
+ degradedWebSocketConnections.delete(key);
2654
+ }
2655
+ }
2656
+ registerSessionResourceCleanup(closeOpenAIResponsesWebSocketSessions);
2657
+ //#endregion
2658
+ //#region packages/ai/src/transports/openai-responses-client.ts
2659
+ function createOpenAIResponsesClient(model, apiKey, defaultHeaders, fetchOverride) {
2660
+ return new OpenAI({
2661
+ apiKey,
2662
+ baseURL: resolveOpenAIClientBaseUrl(model),
2663
+ dangerouslyAllowBrowser: true,
2664
+ defaultHeaders,
2665
+ fetch: fetchOverride ?? buildGuardedModelFetch(model),
2666
+ ...buildOpenAISdkClientOptions(model)
2667
+ });
2668
+ }
2669
+ function createResponsesTransportExecutor(config) {
2670
+ return (model, context, options) => {
2671
+ const responsesOptions = options;
2672
+ const independent = independentResponsesRequest.has(options);
2673
+ const compactRequest = claimResponsesCompactRequest(responsesOptions);
2674
+ const v2Compaction = compactRequest?.mode === "v2" ? createResponsesV2CompactionCollector(compactRequest.replayBudget) : void 0;
2675
+ const { eventStream, stream } = createWritableTransportEventStream();
2676
+ (async () => {
2677
+ const output = createAssistantOutput(model, config.outputApi);
2678
+ let firstEventAbort;
2679
+ let requestSignal = options?.signal;
2680
+ let continuationClaim;
2681
+ const requestLifecycle = responsesRequestLifecycle.get(options);
2682
+ try {
2683
+ if (compactRequest && requestLifecycle) throw new Error("Provider review continuation cannot replace its reviewed input with compaction");
2684
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
2685
+ const websocketMode = independent ? void 0 : resolveNativeOpenAIResponsesWebSocketMode(model, responsesOptions?.transport);
2686
+ const encodeBody = prepareModelRequestBody(websocketMode || compactRequest?.mode === "endpoint" ? void 0 : options);
2687
+ const turnState = resolveProviderTransportTurnState(model, {
2688
+ sessionId: options?.sessionId,
2689
+ turnId: randomUUID(),
2690
+ attempt: 1,
2691
+ transport: websocketMode ? "websocket" : "stream"
2692
+ });
2693
+ const websocketSessionPolicy = websocketMode ? turnState?.websocket : void 0;
2694
+ const httpTurnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, turnState?.headers);
2695
+ const websocketTurnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, websocketSessionPolicy?.headers);
2696
+ const websocketHeaders = websocketMode ? buildOpenAIClientHeaders(model, context, options?.headers, websocketTurnHeaders, options?.sessionId, options?.cacheRetention) : void 0;
2697
+ const httpHeaders = buildOpenAIClientHeaders(model, context, options?.headers, httpTurnHeaders, options?.sessionId, options?.cacheRetention);
2698
+ const fetchOverride = withOpenAIErrorResponseHook(createResponsesRequestFetch(model, {
2699
+ compact: compactRequest?.mode === "endpoint",
2700
+ stream: config.streamRequest,
2701
+ lifecycle: requestLifecycle,
2702
+ onSseComment: () => notifyLlmRequestActivity(options?.signal, false, 9e5)
2703
+ }) ?? buildGuardedModelFetch(model), options?.onResponse, model);
2704
+ const client = config.createClient(model, apiKey, httpHeaders, fetchOverride);
2705
+ const nativeAstra = model.id === "gpt-6-astra" && supportsNativeOpenAIResponsesEndpoint(model);
2706
+ const asyncToolExecutionEligible = nativeAstra && options?.asyncToolExecution === true && !responsesOptions?.openclawCodeModeToolSurface;
2707
+ const prepareRequest = async (request) => {
2708
+ let params = request;
2709
+ const preserveUsers = v2Compaction?.preserveUsers(request.input ?? []);
2710
+ const nextParams = await options?.onPayload?.(params, model);
2711
+ if (nextParams !== void 0) params = nextParams;
2712
+ if (preserveUsers) params = {
2713
+ ...params,
2714
+ input: preserveUsers(params.input ?? [])
2715
+ };
2716
+ params = sanitizeOpenAICodexResponsesParams(model, params);
2717
+ params = v2Compaction ? v2Compaction.sanitizeImages(params) : sanitizeResponsesImagePayload(params);
2718
+ if (responsesOptions?.openclawCodeModeToolSurface === true) {
2719
+ const visibleToolNames = resolveCodeModeResponsesVisibleToolNames(context);
2720
+ const allowedHostedToolTypes = responsesOptions?.openclawCodeModeAllowedHostedToolTypes;
2721
+ enforceCodeModeResponsesToolSurface(params, visibleToolNames, allowedHostedToolTypes, codeModeToolSurfaceObserver.get(options));
2722
+ assertCodeModeResponsesToolSurface(params, visibleToolNames, allowedHostedToolTypes);
2723
+ }
2724
+ if (asyncToolExecutionEligible && params.model === "gpt-6-astra" && params.multi_agent?.enabled !== true && params.tools) {
2725
+ const synchronousTools = new Set(context.tools?.flatMap((tool) => tool.async === false ? [tool.name] : []));
2726
+ params.tools = params.tools.map((tool) => tool.type === "function" && !synchronousTools.has(tool.name) ? {
2727
+ ...tool,
2728
+ async: true
2729
+ } : tool);
2730
+ }
2731
+ if (v2Compaction) {
2732
+ params.input = [...params.input ?? [], { type: "compaction_trigger" }];
2733
+ v2Compaction.assertReplayFits(params.input, model);
2734
+ }
2735
+ return params;
2736
+ };
2737
+ const buildRequest = (replayMode, requestContext = context) => prepareRequest(config.buildRequest(model, requestContext, responsesOptions, turnState?.metadata, replayMode, Boolean(v2Compaction)));
2738
+ let params = await buildRequest("checkpoint");
2739
+ const asyncTools = !compactRequest && asyncToolExecutionEligible && params.model === "gpt-6-astra" && params.multi_agent?.enabled !== true;
2740
+ if (compactRequest?.mode === "endpoint") {
2741
+ const compacted = await postOpenAIResponsesCompaction({
2742
+ client,
2743
+ model,
2744
+ request: params,
2745
+ options: responsesOptions
2746
+ });
2747
+ output.usage = compacted.modelUsage;
2748
+ compactRequest.resolve(compacted);
2749
+ finalizeTransportStream({
2750
+ stream,
2751
+ output,
2752
+ signal: options?.signal
2753
+ });
2754
+ return;
2755
+ }
2756
+ const sessionId = options?.sessionId;
2757
+ if (config.httpContinuation && !compactRequest && !independent && !websocketMode && !getAiTransportHost().requiresManagedTransport(model) && (supportsNativeOpenAIResponsesEndpoint(model) || resolveOpenAIResponsesPayloadPolicy(model).explicitContinuationOptIn) && sessionId && (params.store === true || supportsResponsesReasoningUpdate(params)) && !params.previous_response_id) {
2758
+ const restoreRequest = () => restoreResponsesReasoningState(context, model, responsesOptions, params);
2759
+ continuationClaim = claimOpenAIResponsesHttpContinuation({
2760
+ sessionId,
2761
+ apiKey,
2762
+ baseUrl: model.baseUrl,
2763
+ headers: httpHeaders,
2764
+ request: params,
2765
+ restoreRequest
2766
+ });
2767
+ params = continuationClaim?.fullRequest ?? restoreRequest();
2768
+ }
2769
+ const observePrompt = createResponsesPromptEgressObserver(responsesOptions, context);
2770
+ const requestStartedAt = Date.now();
2771
+ let started = false;
2772
+ const startStream = () => {
2773
+ if (!started) {
2774
+ started = true;
2775
+ stream.push({
2776
+ type: "start",
2777
+ partial: output
2778
+ });
2779
+ }
2780
+ };
2781
+ const firstEvent = createFirstStreamEventAbortController(options?.signal);
2782
+ firstEventAbort = firstEvent;
2783
+ const requestOptions = buildOpenAISdkRequestOptions(model, firstEvent.signal, {
2784
+ stream: config.streamRequest,
2785
+ timeoutMs: options?.timeoutMs
2786
+ });
2787
+ const websocketSignal = combineWebSocketTimeoutSignal(firstEvent.signal, model, requestOptions?.timeout);
2788
+ emitModelTransportDebug(log, () => `[responses] start provider=${model.provider} api=${model.api} model=${model.id} requestIdHash=${redactIdentifier(options?.requestId, { len: 64 })} baseUrl=${formatModelTransportDebugBaseUrl(model.baseUrl)} timeoutMs=${safeDebugValue(requestOptions?.timeout)} apiKey=${apiKey ? "present" : "missing"} ${summarizeResponsesPayload(params)}`);
2789
+ const responseModelTracker = createResponseModelTracker(isOpenAICodexResponsesModel(model));
2790
+ let continuationBaseline;
2791
+ let dispatchedPreviousResponseId;
2792
+ let contextUsageEligible = true;
2793
+ let requestedTier;
2794
+ const createSseStream = async (initialRequest = continuationClaim?.request ?? params, initialAttemptKind = "initial", initialRejectedCompaction) => {
2795
+ requestSignal = firstEvent.signal;
2796
+ const { stream: responseStream } = await createResponsesStreamWithRecovery({
2797
+ client,
2798
+ request: initialRequest,
2799
+ requestOptions,
2800
+ model,
2801
+ encodeBody,
2802
+ observePrompt,
2803
+ initialAttemptKind,
2804
+ initialRejectedCompaction,
2805
+ buildFullHistoryRequest: () => buildRequest("full-history"),
2806
+ onCompactionRejected: (checkpoint) => suppressOpenAIResponsesCompaction(output, model, responsesOptions, checkpoint),
2807
+ canRetryStream: () => output.content.length === 0,
2808
+ onServiceTierRejected: (tier) => responsesServiceTierObserver.reject(options, tier),
2809
+ wrapStream: ({ stream: rawResponseStream, response, attempt }) => {
2810
+ requestedTier = attempt.request.service_tier;
2811
+ contextUsageEligible &&= attempt.kind === "initial";
2812
+ dispatchedPreviousResponseId = attempt.request.previous_response_id;
2813
+ continuationBaseline = attempt.request.previous_response_id ? params : attempt.request;
2814
+ const trackedResponseStream = responseModelTracker.track(response, rawResponseStream);
2815
+ return withProviderResponseHook({
2816
+ stream: observeResponsesStream(v2Compaction ? v2Compaction.observe(trackedResponseStream) : trackedResponseStream, model, requestStartedAt, attempt.request),
2817
+ signal: firstEvent.signal,
2818
+ abort: firstEvent.abort,
2819
+ hook: createOpenAIProviderAcceptanceHook(options, response, model),
2820
+ onReady: () => {
2821
+ emitModelTransportDebug(log, () => `[responses] headers provider=${model.provider} api=${model.api} model=${model.id} transport=sse elapsedMs=${Date.now() - requestStartedAt}`);
2822
+ startStream();
2823
+ }
2824
+ });
2825
+ }
2826
+ });
2827
+ return responseStream;
2828
+ };
2829
+ let responseStream;
2830
+ let websocketBaseline;
2831
+ let finishWebSocket;
2832
+ let transport = "sse";
2833
+ const logWebSocketFallback = (reason) => emitModelTransportDebug(log, () => `[responses] websocket_fallback provider=${model.provider} api=${model.api} model=${model.id} reason=${reason}`);
2834
+ const closeWebSocketForFallback = (reason) => {
2835
+ finishWebSocket?.({ keep: false });
2836
+ finishWebSocket = void 0;
2837
+ transport = "sse";
2838
+ logWebSocketFallback(reason);
2839
+ };
2840
+ if (websocketMode) {
2841
+ requestSignal = websocketSignal;
2842
+ try {
2843
+ const websocket = createOpenAIResponsesWebSocketStream({
2844
+ client,
2845
+ request: params,
2846
+ restoreRequest: (request) => restoreResponsesReasoningState(context, model, responsesOptions, request),
2847
+ mode: websocketMode,
2848
+ sessionId: options?.sessionId,
2849
+ headers: websocketHeaders,
2850
+ signal: websocketSignal,
2851
+ callerSignal: options?.signal,
2852
+ degradeCooldownMs: websocketSessionPolicy?.degradeCooldownMs,
2853
+ onActiveResponse: !compactRequest && nativeAstra && params.model === "gpt-6-astra" ? options?.onActiveResponse : void 0,
2854
+ steeringInput: (messages) => {
2855
+ contextUsageEligible = false;
2856
+ return projectResponsesSteeringInput(params, () => buildRequest("checkpoint", {
2857
+ ...context,
2858
+ messages: [...context.messages, ...messages]
2859
+ }));
2860
+ }
2861
+ });
2862
+ finishWebSocket = websocket.finish;
2863
+ requestedTier = websocket.request.service_tier;
2864
+ websocketBaseline = websocket.fullRequest;
2865
+ recordResponsesInputReplay(output, websocket.inputReplay);
2866
+ contextUsageEligible &&= websocket.inputReplay === void 0;
2867
+ observePrompt?.(websocket.request, {
2868
+ egress: "responses-websocket",
2869
+ payloadVariant: "initial"
2870
+ });
2871
+ transport = "websocket";
2872
+ emitModelTransportDebug(log, () => `[responses] websocket_selected provider=${model.provider} api=${model.api} model=${model.id} mode=${websocketMode} reused=${websocket.reusedConnection} continuation=${websocket.continuationStatus === "continued"} continuationStatus=${websocket.continuationStatus} sessionIdHash=${redactIdentifier(options?.sessionId)} headersHash=${redactIdentifier(JSON.stringify(Object.entries(websocketHeaders ?? {}).toSorted(([a], [b]) => a.localeCompare(b))))}`);
2873
+ responseStream = createRecoverableResponsesWebSocketStream({
2874
+ trackedWebSocketStream: observeResponsesStream(v2Compaction ? v2Compaction.observe(responseModelTracker.track(void 0, websocket.stream)) : responseModelTracker.track(void 0, websocket.stream), model, requestStartedAt, websocket.request, "websocket"),
2875
+ websocket,
2876
+ websocketSignal,
2877
+ options,
2878
+ output,
2879
+ buildRequest,
2880
+ createSseStream,
2881
+ closeWebSocketForFallback,
2882
+ logWebSocketFallback,
2883
+ startStream,
2884
+ setTransportToSse: () => {
2885
+ transport = "sse";
2886
+ }
2887
+ });
2888
+ } catch (error) {
2889
+ if (error instanceof OpenAIResponsesWebSocketPostDispatchError) throw error;
2890
+ closeWebSocketForFallback("setup_failure");
2891
+ responseStream = await createSseStream();
2892
+ }
2893
+ } else responseStream = await createSseStream();
2894
+ try {
2895
+ const acceptedResponseStream = withResponsesRequestAcceptance(responseStream, requestLifecycle, transport === "websocket" ? websocketSignal : firstEvent.signal);
2896
+ const terminal = await processResponsesStream(acceptedResponseStream, output, stream, model, {
2897
+ canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(transport === "websocket" ? websocketBaseline : continuationBaseline),
2898
+ ...config.pricingOptions?.(responsesOptions, model),
2899
+ promptCacheTtl: params.prompt_cache_options?.ttl,
2900
+ resolveServiceTier: (responseTier, originalTier) => responseTier ?? (requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier),
2901
+ onServiceTier: (tier, response) => responsesServiceTierObserver.observe(options, requestedTier, tier, response),
2902
+ firstEventTimeoutMs: getFirstStreamEventTimeoutMs(options) ?? config.firstEventTimeoutMs,
2903
+ abortFirstEventStream: firstEvent.abort,
2904
+ onFirstEventTimeout: getFirstStreamEventTimeoutHandler(options),
2905
+ signal: options?.signal,
2906
+ reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
2907
+ authProfileId: responsesOptions?.authProfileId,
2908
+ sessionId: options?.sessionId
2909
+ }),
2910
+ asyncToolExecution: asyncTools,
2911
+ ...responseModelTracker.terminalOptions
2912
+ });
2913
+ finishWebSocket?.();
2914
+ if (options?.signal?.aborted) throw transportAbortError(options.signal);
2915
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
2916
+ const admitted = !independent && (transport === "websocket" ? websocketBaseline : continuationBaseline);
2917
+ if (v2Compaction && compactRequest) {
2918
+ const compacted = v2Compaction.finish({
2919
+ terminal,
2920
+ input: params.input ?? [],
2921
+ model,
2922
+ options: responsesOptions
2923
+ });
2924
+ compactRequest.resolve({
2925
+ ...compacted,
2926
+ modelUsage: output.usage
2927
+ });
2928
+ finalizeTransportStream({
2929
+ stream,
2930
+ output,
2931
+ signal: options?.signal
2932
+ });
2933
+ return;
2934
+ }
2935
+ if (terminal && admitted && supportsNativeOpenAIResponsesEndpoint(model)) recordResponsesReasoningState(output, model, responsesOptions, admitted, terminal.output);
2936
+ if (continuationClaim && continuationBaseline && terminal) continuationClaim.commit(continuationBaseline, terminal, dispatchedPreviousResponseId);
2937
+ if (terminal && admitted && contextUsageEligible) recordResponsesContextUsage(output, model, responsesOptions, admitted, terminal.output, "transport");
2938
+ } catch (error) {
2939
+ finishWebSocket?.({ keep: false });
2940
+ throw error;
2941
+ }
2942
+ emitModelTransportDebug(log, () => `[responses] completed provider=${model.provider} api=${model.api} model=${model.id} transport=${transport} elapsedMs=${Date.now() - requestStartedAt}`);
2943
+ finalizeTransportStream({
2944
+ stream,
2945
+ output,
2946
+ signal: options?.signal
2947
+ });
2948
+ } catch (error) {
2949
+ if (error instanceof DegenerateToolCallArgumentsError) firstEventAbort?.abort(error);
2950
+ if (requestLifecycle) await requestLifecycle.settle().catch(() => void 0);
2951
+ if (compactRequest) {
2952
+ compactRequest.reject(error);
2953
+ failTransportStream({
2954
+ stream,
2955
+ output,
2956
+ signal: options?.signal,
2957
+ error
2958
+ });
2959
+ return;
2960
+ }
2961
+ failTransportStream({
2962
+ stream,
2963
+ output,
2964
+ signal: options?.signal,
2965
+ error,
2966
+ diagnostic: observeResponsesTransportFailure({
2967
+ error,
2968
+ model,
2969
+ output,
2970
+ signal: options?.signal,
2971
+ requestSignal
2972
+ })
2973
+ });
2974
+ } finally {
2975
+ continuationClaim?.release();
2976
+ firstEventAbort?.dispose();
2977
+ }
2978
+ })();
2979
+ return eventStream;
2980
+ };
2981
+ }
2982
+ function createOpenAIResponsesTransportStreamFn() {
2983
+ return createResponsesTransportExecutor({
2984
+ streamRequest: true,
2985
+ httpContinuation: true,
2986
+ createClient: createOpenAIResponsesClient,
2987
+ buildRequest: buildOpenAIResponsesParams,
2988
+ pricingOptions: (options, model) => ({
2989
+ serviceTier: options?.serviceTier,
2990
+ applyServiceTierPricing: (usage, serviceTier) => applyResponsesServiceTierPricing(usage, serviceTier, model)
2991
+ })
2992
+ });
2993
+ }
2994
+ function createAzureOpenAIResponsesTransportStreamFn() {
2995
+ return createResponsesTransportExecutor({
2996
+ outputApi: "azure-openai-responses",
2997
+ firstEventTimeoutMs: AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS,
2998
+ createClient: createAzureOpenAIClient,
2999
+ buildRequest: (model, context, options, metadata, replayMode) => {
3000
+ const deploymentName = resolveAzureDeploymentNameFromMap({
3001
+ modelId: model.id,
3002
+ deploymentMap: process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP
3003
+ });
3004
+ const params = buildOpenAIResponsesParams(model, context, options, metadata, replayMode);
3005
+ params.model = deploymentName;
3006
+ delete params.store;
3007
+ return params;
3008
+ }
3009
+ });
3010
+ }
3011
+ function createAzureOpenAIClient(model, apiKey, defaultHeaders, fetchOverride) {
3012
+ const baseURL = model.baseUrl.replace(/\/+$/, "");
3013
+ const clientOptions = {
3014
+ apiKey,
3015
+ dangerouslyAllowBrowser: true,
3016
+ defaultHeaders,
3017
+ baseURL,
3018
+ fetch: fetchOverride ?? buildGuardedModelFetch(model),
3019
+ ...buildOpenAISdkClientOptions(model)
3020
+ };
3021
+ if (isOpenAICompatibleAzureResponsesBaseUrl(baseURL)) return new OpenAI(clientOptions);
3022
+ return new AzureOpenAI({
3023
+ ...clientOptions,
3024
+ apiVersion: resolveAzureOpenAIApiVersion()
3025
+ });
3026
+ }
3027
+ //#endregion
3028
+ //#region packages/ai/src/transports/openai-completions-transport.ts
3029
+ function assertOpenAICompletionsPayloadHasConversationTurn(params, model) {
3030
+ const messages = params.messages;
3031
+ if (!Array.isArray(messages) || hasOpenAICompatibleConversationTurn(messages)) return;
3032
+ throw new Error(`OpenAI-compatible chat payload for ${model.provider}/${model.id} contains no non-empty user or assistant messages after compaction and transport transforms; refusing to send a system/tool-only request. Start a new user turn or repair the compacted session history.`);
3033
+ }
3034
+ const MAX_CONTEXT_BUDGET_BUFFER_CHUNKS = 8192;
3035
+ const MAX_CONTEXT_BUDGET_BUFFER_BYTES = 4194304;
3036
+ const SSE_DONE_LINE_RE = /^data:[ \t]*\[DONE\][ \t]*$/i;
3037
+ const SSE_DONE_MAX_LINE_CHARS = 1024;
3038
+ function createSseDoneDetector() {
3039
+ const decoder = new TextDecoder();
3040
+ let line = "";
3041
+ let lineOverflowed = false;
3042
+ let sawDone = false;
3043
+ const finishLine = () => {
3044
+ if (!lineOverflowed && SSE_DONE_LINE_RE.test(line)) sawDone = true;
3045
+ line = "";
3046
+ lineOverflowed = false;
3047
+ };
3048
+ const observeText = (text) => {
3049
+ for (const [index, segment] of text.split(/[\r\n]/).entries()) {
3050
+ if (index > 0) finishLine();
3051
+ if (!lineOverflowed && line.length + segment.length <= SSE_DONE_MAX_LINE_CHARS) line += segment;
3052
+ else lineOverflowed = true;
3053
+ }
3054
+ };
3055
+ return {
3056
+ observe(chunk) {
3057
+ if (!sawDone) observeText(decoder.decode(chunk, { stream: true }));
3058
+ },
3059
+ finish() {
3060
+ if (sawDone) return;
3061
+ observeText(decoder.decode());
3062
+ if (line || lineOverflowed) finishLine();
3063
+ },
3064
+ sawDone: () => sawDone
3065
+ };
3066
+ }
3067
+ function createDirectCompletionsEventStream(output, stream) {
3068
+ const finishedBlocks = /* @__PURE__ */ new Set();
3069
+ const contentIndices = /* @__PURE__ */ new WeakMap();
3070
+ let openTextBlock;
3071
+ let openThinkingBlock;
3072
+ const finishBlock = (block) => {
3073
+ const contentIndex = contentIndices.get(block);
3074
+ if (contentIndex === void 0 || finishedBlocks.has(block)) return;
3075
+ finishedBlocks.add(block);
3076
+ if (block.type === "text") {
3077
+ openTextBlock = void 0;
3078
+ stream.push({
3079
+ type: "text_end",
3080
+ contentIndex,
3081
+ content: block.text,
3082
+ partial: output
3083
+ });
3084
+ } else if (block.type === "thinking") {
3085
+ openThinkingBlock = void 0;
3086
+ stream.push({
3087
+ type: "thinking_end",
3088
+ contentIndex,
3089
+ content: block.thinking,
3090
+ partial: output
3091
+ });
3092
+ } else if (block.type === "toolCall") stream.push({
3093
+ type: "toolcall_end",
3094
+ contentIndex,
3095
+ toolCall: block,
3096
+ partial: output
3097
+ });
3098
+ };
3099
+ return {
3100
+ stream: { push(event) {
3101
+ if (event.type === "text_start" || event.type === "thinking_start" || event.type === "toolcall_start") {
3102
+ const block = output.content[event.contentIndex];
3103
+ if (block) {
3104
+ contentIndices.set(block, event.contentIndex);
3105
+ if (block.type === "text") openTextBlock = block;
3106
+ else if (block.type === "thinking") openThinkingBlock = block;
3107
+ }
3108
+ }
3109
+ stream.push(event);
3110
+ } },
3111
+ beforeContentBlock: (nextType) => {
3112
+ if (openThinkingBlock) finishBlock(openThinkingBlock);
3113
+ if (openTextBlock && nextType !== "toolCall") finishBlock(openTextBlock);
3114
+ },
3115
+ finish(includeToolCalls) {
3116
+ for (const block of output.content) if (block.type !== "toolCall" || includeToolCalls) finishBlock(block);
3117
+ }
3118
+ };
3119
+ }
3120
+ function createOpenAICompletionsTransportStreamFn() {
3121
+ const streamResponses = createOpenAIResponsesTransportStreamFn();
3122
+ return (model, context, options) => {
3123
+ const completionsOptions = options;
3124
+ if (model.reasoning && context.tools?.length && supportsModelTools(model) && isNativeOpenAIEndpoint(model)) {
3125
+ const toolChoice = completionsOptions?.toolChoice;
3126
+ const responsesOptions = {
3127
+ ...options,
3128
+ ...completionsOptions?.reasoning === void 0 && completionsOptions?.reasoningEffort === void 0 ? { reasoningEffort: "high" } : {},
3129
+ ...toolChoice && typeof toolChoice === "object" ? { toolChoice: toOpenAIResponsesToolChoice(toolChoice) } : {}
3130
+ };
3131
+ return streamResponses(getAiTransportHost().inheritManagedTransport(model, {
3132
+ ...model,
3133
+ api: "openai-responses"
3134
+ }), context, responsesOptions);
3135
+ }
3136
+ return streamOpenAICompletionsRequest(model, context, completionsOptions, "managed");
3137
+ };
3138
+ }
3139
+ function streamOpenAICompletionsRequest(model, context, options, mode) {
3140
+ const { eventStream, stream } = createWritableTransportEventStream();
3141
+ (async () => {
3142
+ const output = createAssistantOutput(model);
3143
+ let discardCandidate = false;
3144
+ let firstEventAbort;
3145
+ try {
3146
+ const requestContext = await resolveProviderContext(context, options);
3147
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
3148
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention);
3149
+ const policy = mode === "direct" ? {
3150
+ mode,
3151
+ compat: resolveOpenAICompletionsCompat(model),
3152
+ cacheRetention
3153
+ } : { mode };
3154
+ const { client, sawStreamDONE } = policy.mode === "direct" ? {
3155
+ client: (() => {
3156
+ const sessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
3157
+ const compat = policy.compat;
3158
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
3159
+ const headers = { ...model.headers };
3160
+ if (model.provider === "github-copilot") Object.assign(headers, buildCopilotDynamicHeaders(context.messages));
3161
+ if (sessionId && compat.sessionAffinity !== "none") {
3162
+ if (compat.sessionAffinity === "openrouter") headers["x-session-id"] = sessionId;
3163
+ else {
3164
+ headers.session_id = sessionId;
3165
+ headers["x-client-request-id"] = sessionId;
3166
+ headers["x-session-affinity"] = sessionId;
3167
+ }
3168
+ }
3169
+ return createOpenAIProviderClient(model, apiKey, headers, resolveProviderSimpleCompletionHeaders(model, options), options?.onResponse);
3170
+ })(),
3171
+ sawStreamDONE: void 0
3172
+ } : (() => {
3173
+ const turnState = resolveProviderTransportTurnState(model, {
3174
+ sessionId: options?.sessionId,
3175
+ turnId: randomUUID(),
3176
+ attempt: 1,
3177
+ transport: "stream"
3178
+ });
3179
+ const optionHeaders = resolveOpencodeSessionHeaders(model, options);
3180
+ const turnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, turnState?.headers);
3181
+ const doneDetector = createSseDoneDetector();
3182
+ const baseFetch = withOpenAIErrorResponseHook(buildGuardedModelFetch(model, void 0, { onSseComment: () => notifyLlmRequestActivity(options?.signal, false) }), options?.onResponse, model);
3183
+ const doneDetectingFetch = async (url, init) => {
3184
+ const response = await baseFetch(url, init);
3185
+ if (!response.body || !response.ok) return response;
3186
+ if (typeof TransformStream === "undefined" || !response.body.pipeThrough) return response;
3187
+ const transformed = response.body.pipeThrough(new TransformStream({
3188
+ transform(chunk, controller) {
3189
+ doneDetector.observe(chunk);
3190
+ controller.enqueue(chunk);
3191
+ },
3192
+ flush() {
3193
+ doneDetector.finish();
3194
+ }
3195
+ }));
3196
+ return new Response(transformed, response);
3197
+ };
3198
+ const headers = buildOpenAIClientHeaders(model, context, {
3199
+ ...turnHeaders,
3200
+ ...optionHeaders
3201
+ }, void 0, resolvePromptCacheKey(options, cacheRetention), cacheRetention);
3202
+ const defaultQuery = {};
3203
+ let baseURL = model.baseUrl;
3204
+ let isAzureHost = false;
3205
+ const parsed = URL.parse(model.baseUrl);
3206
+ if (parsed) {
3207
+ isAzureHost = isAzureOpenAICompatibleHost(parsed.hostname.toLowerCase());
3208
+ parsed.searchParams.forEach((value, key) => {
3209
+ if (value) defaultQuery[key] = value;
3210
+ });
3211
+ parsed.search = "";
3212
+ baseURL = parsed.toString().replace(/\/$/, "");
3213
+ }
3214
+ if (isAzureHost) {
3215
+ const apiVersionHeader = Object.keys(headers).find((key) => key.toLowerCase() === "api-version");
3216
+ if (apiVersionHeader) {
3217
+ const apiVersion = headers[apiVersionHeader]?.trim();
3218
+ delete headers[apiVersionHeader];
3219
+ if (apiVersion && !defaultQuery["api-version"]) defaultQuery["api-version"] = apiVersion;
3220
+ }
3221
+ }
3222
+ const resolvedBaseURL = resolveOpenAIClientBaseUrl(model, baseURL);
3223
+ const resolvedDefaultQuery = Object.keys(defaultQuery).length > 0 ? defaultQuery : void 0;
3224
+ return {
3225
+ client: new OpenAI({
3226
+ apiKey,
3227
+ baseURL: resolvedBaseURL,
3228
+ dangerouslyAllowBrowser: true,
3229
+ defaultHeaders: headers,
3230
+ defaultQuery: resolvedDefaultQuery,
3231
+ fetch: doneDetectingFetch,
3232
+ ...buildOpenAISdkClientOptions(model)
3233
+ }),
3234
+ sawStreamDONE: doneDetector.sawDone
3235
+ };
3236
+ })();
3237
+ const builtParams = buildOpenAICompletionsRequest(model, requestContext, options, policy);
3238
+ let params = builtParams;
3239
+ const encodeBody = prepareModelRequestBody(options);
3240
+ const nextParams = await options?.onPayload?.(params, model);
3241
+ if (nextParams !== void 0) params = nextParams;
3242
+ if (mode === "managed") {
3243
+ if (options?.openclawCodeModeToolSurface === true) {
3244
+ const visibleToolNames = resolveCodeModeResponsesVisibleToolNames(context);
3245
+ enforceCodeModeResponsesToolSurface(params, visibleToolNames, void 0, codeModeToolSurfaceObserver.get(options));
3246
+ assertCodeModeResponsesToolSurface(params, visibleToolNames);
3247
+ }
3248
+ if (getCompat(model).requiresNonEmptyUserOrAssistantMessage) assertOpenAICompletionsPayloadHasConversationTurn(params, model);
3249
+ }
3250
+ const contextOutputBudget = resolveCompletionsContextOutputBudget(builtParams, params);
3251
+ const emitReasoning = shouldEmitOpenAICompletionsReasoning(model, options, mode);
3252
+ firstEventAbort = createFirstStreamEventAbortController(options?.signal);
3253
+ const requestOptions = mode === "direct" ? {
3254
+ ...await encodeBody(params),
3255
+ signal: firstEventAbort.signal,
3256
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
3257
+ maxRetries: 0
3258
+ } : {
3259
+ ...buildOpenAISdkRequestOptions(model, firstEventAbort.signal, { timeoutMs: options?.timeoutMs }),
3260
+ ...await encodeBody(params)
3261
+ };
3262
+ const request = client.chat.completions.create(params, requestOptions);
3263
+ const response = await request.asResponse();
3264
+ const hookedResponseStream = withProviderResponseHook({
3265
+ stream: { async *[Symbol.asyncIterator]() {
3266
+ if (!params.stream) {
3267
+ yield await boundResponseBody(response, {
3268
+ maxBytes: 16777216,
3269
+ onOverflow: ({ maxBytes }) => /* @__PURE__ */ new Error(`Chat Completions JSON response exceeds ${maxBytes} bytes`)
3270
+ }).json();
3271
+ return;
3272
+ }
3273
+ const data = await request;
3274
+ if (Symbol.asyncIterator in data) yield* data;
3275
+ else yield data;
3276
+ } },
3277
+ signal: firstEventAbort.signal,
3278
+ abort: firstEventAbort.abort,
3279
+ hook: createOpenAIProviderAcceptanceHook(options, response, model),
3280
+ onReady: () => {
3281
+ if (contextOutputBudget === void 0) stream.push({
3282
+ type: "start",
3283
+ partial: output
3284
+ });
3285
+ }
3286
+ });
3287
+ const providerStream = observeOpenAICompletionsProgress(withFirstStreamEventTimeout(hookedResponseStream, {
3288
+ provider: model.provider,
3289
+ api: model.api,
3290
+ model: model.id,
3291
+ timeoutMs: getFirstStreamEventTimeoutMs(options) ?? 0,
3292
+ stage: "completions",
3293
+ abort: firstEventAbort.abort,
3294
+ onTimeout: getFirstStreamEventTimeoutHandler(options),
3295
+ hint: "The provider may be stalled while parsing the tool payload; retry with a smaller tool surface or enable OPENCLAW_DEBUG_MODEL_PAYLOAD=tools to inspect exposed tools."
3296
+ }), options?.signal);
3297
+ const buffered = contextOutputBudget === void 0 ? void 0 : await (async () => {
3298
+ const iterator = providerStream[Symbol.asyncIterator]();
3299
+ const chunks = [];
3300
+ let bufferedBytes = 0;
3301
+ let overflow;
3302
+ let finished = false;
3303
+ let failed = false;
3304
+ let sourceError;
3305
+ let finishReason;
3306
+ try {
3307
+ for (;;) {
3308
+ const next = await iterator.next();
3309
+ if (next.done) {
3310
+ finished = true;
3311
+ break;
3312
+ }
3313
+ const chunk = next.value;
3314
+ const chunkBytes = Buffer.byteLength(JSON.stringify(chunk) ?? "", "utf8");
3315
+ if (chunks.length >= MAX_CONTEXT_BUDGET_BUFFER_CHUNKS || bufferedBytes + chunkBytes > MAX_CONTEXT_BUDGET_BUFFER_BYTES) {
3316
+ overflow = next;
3317
+ break;
3318
+ }
3319
+ chunks.push(chunk);
3320
+ bufferedBytes += chunkBytes;
3321
+ const chunkFinishReason = chunk?.choices?.[0]?.finish_reason;
3322
+ if (chunkFinishReason) finishReason = chunkFinishReason;
3323
+ options?.signal?.throwIfAborted();
3324
+ }
3325
+ } catch (error) {
3326
+ failed = true;
3327
+ sourceError = error;
3328
+ iterator.return?.(void 0).catch(() => void 0);
3329
+ }
3330
+ return {
3331
+ bounded: overflow === void 0,
3332
+ failed,
3333
+ finishReason,
3334
+ stream: { async *[Symbol.asyncIterator]() {
3335
+ try {
3336
+ yield* chunks;
3337
+ if (failed) throw sourceError;
3338
+ if (overflow !== void 0) {
3339
+ yield overflow.value;
3340
+ for (;;) {
3341
+ const next = await iterator.next();
3342
+ if (next.done) {
3343
+ finished = true;
3344
+ return;
3345
+ }
3346
+ yield next.value;
3347
+ }
3348
+ }
3349
+ } finally {
3350
+ chunks.length = 0;
3351
+ if (!finished && !failed) iterator.return?.(void 0).catch(() => void 0);
3352
+ }
3353
+ } }
3354
+ };
3355
+ })();
3356
+ discardCandidate = Boolean(buffered?.bounded && (buffered.failed || buffered.finishReason === "length"));
3357
+ if (buffered && !discardCandidate) stream.push({
3358
+ type: "start",
3359
+ partial: output
3360
+ });
3361
+ const directEvents = mode === "direct" ? createDirectCompletionsEventStream(output, stream) : void 0;
3362
+ try {
3363
+ await processCompletionsStream(buffered?.stream ?? providerStream, output, model, discardCandidate ? { push() {} } : directEvents?.stream ?? stream, {
3364
+ ...directEvents ? {
3365
+ mode: "direct",
3366
+ beforeContentBlock: directEvents.beforeContentBlock
3367
+ } : { mode: "managed" },
3368
+ signal: discardCandidate ? void 0 : options?.signal,
3369
+ emitReasoning,
3370
+ strictReasoningTags: reasoningTagTextPolicy.isStrict(options),
3371
+ sawStreamDONE
3372
+ });
3373
+ if (discardCandidate) throw new Error(`Context length exceeded: automatic output budget of ${contextOutputBudget} tokens exhausted before completion.`);
3374
+ if (directEvents) {
3375
+ if (options?.signal?.aborted) throw transportAbortError(options.signal);
3376
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage || (output.stopReason === "aborted" ? "Request was aborted" : "Provider returned an invalid tool call"));
3377
+ }
3378
+ } catch (error) {
3379
+ directEvents?.finish(false);
3380
+ throw error;
3381
+ }
3382
+ directEvents?.finish(output.stopReason === "toolUse");
3383
+ finalizeTransportStream({
3384
+ stream,
3385
+ output,
3386
+ signal: options?.signal
3387
+ });
3388
+ } catch (error) {
3389
+ if (discardCandidate) output.content = [];
3390
+ failTransportStream({
3391
+ stream,
3392
+ output,
3393
+ signal: options?.signal,
3394
+ error,
3395
+ cleanup: () => {
3396
+ finalizeOpenAICompletionsToolCalls(output, { allowSilentToolCallPromotion: false });
3397
+ }
3398
+ });
3399
+ } finally {
3400
+ firstEventAbort?.dispose();
3401
+ }
3402
+ })();
3403
+ return eventStream;
3404
+ }
3405
+ //#endregion
3406
+ export { hasResponsesWebSearchTool as a, flattenCompletionMessagesToStringContent as c, hasOpenAICompatibleConversationTurn as d, canonicalizeMaxTokensParam as f, createOpenAIResponsesTransportStreamFn as i, stripCompletionMessagesToRoleContent as l, createDeepSeekTextFilter as m, streamOpenAICompletionsRequest as n, buildOpenAICompletionsParams as o, resolveMaxTokensParam as p, createAzureOpenAIResponsesTransportStreamFn as r, convertMessages as s, createOpenAICompletionsTransportStreamFn as t, applyCompletionsAnthropicCacheControl as u };