@openclaw/ai 2026.11.5 → 2026.11.6

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 (88) hide show
  1. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -1
  2. package/dist/{anthropic-CNEzO12C.mjs → anthropic-BNkSFJGp.mjs} +5 -5
  3. package/dist/{anthropic-payload-policy-DVk38bnY.d.mts → anthropic-payload-policy-DxijyMFH.d.mts} +3 -3
  4. package/dist/{anthropic-stream-lifecycle-DJUtasDB.mjs → anthropic-stream-lifecycle-Dp5TblwC.mjs} +9 -9
  5. package/dist/{anthropic-tool-projection-DKAlondV.d.mts → anthropic-tool-projection-DX_igbpX.d.mts} +1 -1
  6. package/dist/{anthropic-tool-projection-DcvsDiyX.mjs → anthropic-tool-projection-DpN77rtb.mjs} +1 -1
  7. package/dist/{api-registry-DY2MLUyg.d.mts → api-registry-CCdcCPSA.d.mts} +2 -2
  8. package/dist/{assistant-output-C3czmoN4.mjs → assistant-output-BEE6TWdj.mjs} +1 -1
  9. package/dist/{azure-openai-responses-client-compat-D0dvJMbZ.mjs → azure-deployment-map-DKJ8Xc4c.mjs} +1 -14
  10. package/dist/{azure-openai-responses-DRkduRmW.mjs → azure-openai-responses-BjX0owXR.mjs} +6 -5
  11. package/dist/azure-openai-responses-client-compat-a5PrPIdL.mjs +14 -0
  12. package/dist/diagnostics.d.mts +3 -3
  13. package/dist/{event-stream-BYmtRe8-.d.mts → event-stream-CDyUvxkI.d.mts} +1 -1
  14. package/dist/event-stream-X0f18GAs.d.mts +1 -0
  15. package/dist/event-stream.d.mts +2 -2
  16. package/dist/{google-DqG05iBa.mjs → google-BJwjWpAX.mjs} +2 -2
  17. package/dist/{google-interactions-BE7cxFPc.mjs → google-interactions-BEOEOp0d.mjs} +10 -10
  18. package/dist/{google-messages-p2iBzsAp.mjs → google-messages-Bja86PP8.mjs} +3 -3
  19. package/dist/{google-provider-stream-DZ6tqteU.mjs → google-provider-stream-GYgtu60C.mjs} +6 -6
  20. package/dist/{google-shared-BMYt1xSI.mjs → google-shared-7sAuYDNq.mjs} +5 -5
  21. package/dist/{google-vertex-CAq2q1Ln.mjs → google-vertex-2zavNJkj.mjs} +2 -2
  22. package/dist/{host-ccbwPC3A.d.mts → host-C2_6_j-L.d.mts} +3 -3
  23. package/dist/{host-DqX-64Pb.mjs → host-DZ29cEYd.mjs} +1 -1
  24. package/dist/{host-policy-Bk85E9ue.mjs → host-policy-DqFgGiV6.mjs} +1 -1
  25. package/dist/{index-Bczt0MnO.d.mts → index-DkF8J4yH.d.mts} +3 -3
  26. package/dist/index.d.mts +6 -6
  27. package/dist/index.mjs +2 -2
  28. package/dist/internal/anthropic.d.mts +6 -6
  29. package/dist/internal/anthropic.mjs +4 -4
  30. package/dist/internal/google.d.mts +3 -3
  31. package/dist/internal/google.mjs +1 -1
  32. package/dist/internal/openai-completions-compat.d.mts +1 -1
  33. package/dist/internal/openai-completions-compat.mjs +1 -1
  34. package/dist/internal/openai-responses-payload-policy.d.mts +1 -1
  35. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  36. package/dist/internal/openai.d.mts +10 -10
  37. package/dist/internal/openai.mjs +10 -9
  38. package/dist/internal/runtime.d.mts +8 -8
  39. package/dist/internal/runtime.mjs +4 -4
  40. package/dist/internal/shared.d.mts +8 -8
  41. package/dist/internal/shared.mjs +3 -3
  42. package/dist/internal/tool-schema.d.mts +2 -2
  43. package/dist/internal/tool-schema.mjs +3 -3
  44. package/dist/{mistral-DIGInqJI.mjs → mistral-CjTsnfIz.mjs} +8 -8
  45. package/dist/{openai-chatgpt-responses-C6rEZcsZ.mjs → openai-chatgpt-responses-BinD_u6y.mjs} +11 -11
  46. package/dist/{openai-completions-B93R3N3b.mjs → openai-completions-B380Vg0n.mjs} +3 -3
  47. package/dist/{openai-completions-compat-CJ-NsDzg.d.mts → openai-completions-compat-CEj778te.d.mts} +3 -3
  48. package/dist/{openai-completions-compat-CS3dlDBR.mjs → openai-completions-compat-CmyT3piu.mjs} +2 -2
  49. package/dist/{openai-completions-transport-DHTFq-BM.mjs → openai-completions-transport-BGoKrb3z.mjs} +57 -431
  50. package/dist/{openai-tool-schema-CvxySRyf.mjs → openai-function-tool-DUT14vv6.mjs} +22 -22
  51. package/dist/{openai-prompt-cache-BZGaIWYh.d.mts → openai-prompt-cache-C_XCgsDn.d.mts} +2 -2
  52. package/dist/{openai-prompt-cache-3H_Fz0ya.mjs → openai-prompt-cache-DV1t-7dP.mjs} +1 -1
  53. package/dist/{openai-responses-DSxPKV0U.mjs → openai-responses-ClgomgWG.mjs} +6 -6
  54. package/dist/{openai-responses-compaction-replay-DXF5BjD2.d.mts → openai-responses-compaction-replay-6MNmDBBu.d.mts} +6 -5
  55. package/dist/{openai-responses-contracts-xU-n9AJJ.mjs → openai-responses-contracts-BpyK1Ygq.mjs} +1 -1
  56. package/dist/{openai-responses-contracts-Cb1IIRRG.d.mts → openai-responses-contracts-D-saZnr_.d.mts} +5 -5
  57. package/dist/{openai-responses-endpoint-CqO3ejTe.mjs → openai-responses-endpoint-BGwjxesS.mjs} +1 -1
  58. package/dist/{openai-responses-request-lifecycle-C_3FKkl7.mjs → openai-responses-request-lifecycle-pjoJ2KB8.mjs} +6 -6
  59. package/dist/{openai-responses-shared-En3Jf0Vg.mjs → openai-responses-shared-BE2zSjin.mjs} +2034 -1918
  60. package/dist/{openai-responses-terminal-usage-D7IhRA6i.d.mts → openai-responses-terminal-usage-CuXS9TCK.d.mts} +2 -2
  61. package/dist/openai-responses-websocket-Bzo4ykRX.mjs +385 -0
  62. package/dist/{otel-B2u5HGvm.mjs → otel-VKlSbm9p.mjs} +1 -1
  63. package/dist/{provider-options-BQ2Msop2.d.mts → provider-options-Bo0XJEeK.d.mts} +3 -3
  64. package/dist/{provider-replay-context--QGWotXx.mjs → provider-replay-context-BAwe7OIR.mjs} +1 -1
  65. package/dist/{provider-transcript-transform-Hr1kCoMX.mjs → provider-transcript-transform-BA4B0NIr.mjs} +1 -1
  66. package/dist/{provider-transport-turn-state-DyaOKAYm.mjs → provider-transport-turn-state-BU7KCpkK.mjs} +22 -4
  67. package/dist/{provider-types-B1e98js5.d.mts → provider-types-wHqA9oSz.d.mts} +3 -3
  68. package/dist/provider-types.d.mts +5 -5
  69. package/dist/providers.d.mts +2 -2
  70. package/dist/providers.mjs +10 -10
  71. package/dist/{sanitize-unicode-BISmUlUv.d.mts → sanitize-unicode-D0B2CDXP.d.mts} +2 -2
  72. package/dist/{simple-options-CQNPKCEb.mjs → simple-options-BPzChce1.mjs} +3 -3
  73. package/dist/{stream-DM-q0y5H.mjs → stream-WbisbzUF.mjs} +1 -1
  74. package/dist/{telemetry-DJibfNKZ.mjs → telemetry-BS2h0FVa.mjs} +2 -2
  75. package/dist/{tool-schema-json-projection-BSHb4gaJ.mjs → tool-schema-json-projection-C9KSjPuG.mjs} +1 -1
  76. package/dist/{transport-stream-shared-D3IAU4jn.d.mts → transport-stream-shared-Cwd9ZIqy.d.mts} +4 -4
  77. package/dist/{transport-stream-shared-CBVh6QEc.mjs → transport-stream-shared-DtOk207K.mjs} +1 -1
  78. package/dist/{transport-utils-rxOHnq9y.mjs → transport-utils-Czu6bnbQ.mjs} +2 -2
  79. package/dist/transports.d.mts +15 -13
  80. package/dist/transports.mjs +14 -14
  81. package/dist/{types-BVdTf0YV.d.mts → types-DrqxFIh9.d.mts} +5 -0
  82. package/dist/types-g3molYjD.d.mts +1 -0
  83. package/dist/types.d.mts +5 -5
  84. package/dist/{validation-QmyD0E5A.d.mts → validation-ByHJvdN2.d.mts} +1 -1
  85. package/dist/validation.d.mts +1 -1
  86. package/package.json +1 -1
  87. package/dist/event-stream-B4ZcSvsu.d.mts +0 -1
  88. package/dist/types-Cb3-5WM9.d.mts +0 -1
@@ -6,30 +6,30 @@ import { i as asOptionalRecord, o as isRecord, s as isStringArray } from "./reco
6
6
  import { l as readStringValue, o as normalizeOptionalString, r as normalizeLowercaseStringOrEmpty, s as normalizeStringifiedOptionalString } from "./string-coerce-BCuWMIrk.mjs";
7
7
  import { t as asFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
8
8
  import { t as observeAsyncIterator } from "./observe-async-iterator-DgmegcZR.mjs";
9
- import { A as applyProviderReportedUsageCost, I as isImageWithMediaPayload, M as clampThinkingLevel, a as resolveAiTransportHeaderSentinels, j as calculateCost, k as headersToRecord, r as getAiTransportHost } from "./host-DqX-64Pb.mjs";
10
- import { A as resolveOpenAIReasoningEffortMapping, D as normalizeOpenAIReasoningEffort, F as MODEL_CATALOG_THINKING_LEVELS, M as supportsOpenAIReasoningEffort, N as supportsOpenAITemperature, O as resolveOpenAIModelReasoningEfforts, P as resolveOpenAIReasoningEffortMap, R as resolveOpenAIThinkingApi, a as OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE, b as isResponsesServiceTierRejection, c as OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE, g as isResponsesTerminalEventType, h as isPreviousResponseRejection, i as OPENAI_RESPONSES_APIS, k as resolveOpenAIReasoningEffortForModel, l as OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, m as RESPONSE_FAILED_NO_DETAILS_MESSAGE, o as OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY, p as RESPONSES_RETAINED_USER, s as OPENAI_RESPONSES_REASONING_REPLAY_META_KEY, x as nextResponsesServiceTier, y as responsesServiceTierObserver } from "./openai-responses-contracts-xU-n9AJJ.mjs";
9
+ import { A as applyProviderReportedUsageCost, I as isImageWithMediaPayload, M as clampThinkingLevel, a as resolveAiTransportHeaderSentinels, j as calculateCost, k as headersToRecord, m as resolveFailedAssistantReplay, r as getAiTransportHost } from "./host-DZ29cEYd.mjs";
10
+ import { A as resolveOpenAIReasoningEffortMapping, D as normalizeOpenAIReasoningEffort, F as MODEL_CATALOG_THINKING_LEVELS, M as supportsOpenAIReasoningEffort, N as supportsOpenAITemperature, O as resolveOpenAIModelReasoningEfforts, P as resolveOpenAIReasoningEffortMap, R as resolveOpenAIThinkingApi, a as OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE, b as isResponsesServiceTierRejection, c as OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE, g as isResponsesTerminalEventType, h as isPreviousResponseRejection, i as OPENAI_RESPONSES_APIS, k as resolveOpenAIReasoningEffortForModel, l as OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, m as RESPONSE_FAILED_NO_DETAILS_MESSAGE, o as OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY, p as RESPONSES_RETAINED_USER, s as OPENAI_RESPONSES_REASONING_REPLAY_META_KEY, x as nextResponsesServiceTier, y as responsesServiceTierObserver } from "./openai-responses-contracts-BpyK1Ygq.mjs";
11
11
  import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-vKvGIE3J.mjs";
12
12
  import { r as readTransportDiagnosticLabel } from "./provider-error-DD-fo4Rz.mjs";
13
13
  import "./src-BUsVkrNt.mjs";
14
- import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-3H_Fz0ya.mjs";
14
+ import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-DV1t-7dP.mjs";
15
15
  import { a as resolveModelPayloadDebugMode, b as resolveResponsesTerminalStopReason, d as ResponsesOutputIdentityError, f as countToolCallTrailingWhitespace, g as applyResponsesCacheWritePricing, i as emitModelTransportError, m as isResponsesProviderTool, p as hasOnlyResponsesFunctionTools, r as emitModelTransportDebug, v as mapResponsesTerminalUsage, y as readResponsesReasoningTokens } from "./diagnostics-CloVGQiK.mjs";
16
- import { n as isCodeModeModelVisibleToolName } from "./transport-utils-rxOHnq9y.mjs";
16
+ import { n as isCodeModeModelVisibleToolName } from "./transport-utils-Czu6bnbQ.mjs";
17
17
  import { t as stableStringify } from "./stable-stringify-CchQEmeA.mjs";
18
- import { a as resolveOpenAICompletionsCompat, n as isKnownOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-CS3dlDBR.mjs";
19
- import { r as resolveModelRequestTimeoutMs } from "./host-policy-Bk85E9ue.mjs";
18
+ import { a as resolveOpenAICompletionsCompat, n as isKnownOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-CmyT3piu.mjs";
19
+ import { r as resolveModelRequestTimeoutMs } from "./host-policy-DqFgGiV6.mjs";
20
20
  import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-w-ICeyOI.mjs";
21
- import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, f as preparedRequestSuffix, r as clampMaxTokensToModel, s as extractToolResultBlockText, u as codeModeToolSurfaceObserver, y as prepareSystemPrompt } from "./simple-options-CQNPKCEb.mjs";
22
- import { A as parseStreamingJson, C as withProviderResponseHook, D as shortHash, O as createToolArgumentPreviewSchedule, _ as parseTerminalToolCallArguments, c as failTransportStream, d as iterateModelStream, h as notifyProviderHttpResponse, s as decodeSseFrames, t as IncompleteToolCallError, u as finalizeTransportStream, w as parseJsonObjectPreservingUnsafeIntegers, x as transportAbortError, y as sanitizeTransportPayloadText } from "./transport-stream-shared-CBVh6QEc.mjs";
23
- import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-BSHb4gaJ.mjs";
21
+ import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, f as preparedRequestSuffix, r as clampMaxTokensToModel, s as extractToolResultBlockText, u as codeModeToolSurfaceObserver, y as prepareSystemPrompt } from "./simple-options-BPzChce1.mjs";
22
+ import { A as parseStreamingJson, C as withProviderResponseHook, D as shortHash, O as createToolArgumentPreviewSchedule, _ as parseTerminalToolCallArguments, c as failTransportStream, d as iterateModelStream, h as notifyProviderHttpResponse, s as decodeSseFrames, t as IncompleteToolCallError, u as finalizeTransportStream, w as parseJsonObjectPreservingUnsafeIntegers, x as transportAbortError, y as sanitizeTransportPayloadText } from "./transport-stream-shared-DtOk207K.mjs";
23
+ import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-C9KSjPuG.mjs";
24
24
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
25
- import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context--QGWotXx.mjs";
26
- import { t as transformProviderMessages } from "./provider-transcript-transform-Hr1kCoMX.mjs";
25
+ import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-BAwe7OIR.mjs";
26
+ import { t as transformProviderMessages } from "./provider-transcript-transform-BA4B0NIr.mjs";
27
27
  import { prepareModelRequestBody } from "./internal/model-request-body.mjs";
28
- import "./assistant-output-C3czmoN4.mjs";
28
+ import "./assistant-output-BEE6TWdj.mjs";
29
29
  import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
30
+ import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow, s as buildResponsesInputImage } from "./openai-responses-endpoint-BGwjxesS.mjs";
31
+ import { h as withPreparedToolSchemaNormalization, i as normalizeOpenAIStrictToolParameters, n as findOpenAIStrictToolProjectionDiagnostics, o as resolveOpenAIProjectedToolsStrictToolFlag, t as prepareOpenAIFunctionTool } from "./openai-function-tool-DUT14vv6.mjs";
30
32
  import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-B7RcufAV.mjs";
31
- import { a as resolveOpenAIProjectedToolsStrictToolFlag, m as withPreparedToolSchemaNormalization, r as normalizeOpenAIStrictToolParameters, t as findOpenAIStrictToolProjectionDiagnostics, x as prepareOpenAIFunctionTool } from "./openai-tool-schema-CvxySRyf.mjs";
32
- import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow, s as buildResponsesInputImage } from "./openai-responses-endpoint-CqO3ejTe.mjs";
33
33
  import { randomUUID } from "node:crypto";
34
34
  import { isDeepStrictEqual } from "node:util";
35
35
  import { isProxy } from "node:util/types";
@@ -352,1524 +352,1929 @@ function readOpenAICompletionsContentPartDeltas(content) {
352
352
  return [];
353
353
  }
354
354
  //#endregion
355
- //#region packages/ai/src/providers/openai-tool-projection.ts
356
- function unreadableToolDiagnostic(toolIndex) {
357
- return {
358
- toolIndex,
359
- violations: [`tool[${toolIndex}] is unreadable`]
355
+ //#region packages/ai/src/transports/openai-responses-compaction-replay.ts
356
+ const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE = "openai-responses-compaction-suppression";
357
+ const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA = "rejected";
358
+ function isOpenAIResponsesCompactionState(state) {
359
+ if (typeof state.baseUrlHash !== "string" || state.v !== 1) return false;
360
+ if (state.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) return state.data === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA;
361
+ const retained = state.type === OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE;
362
+ return (retained || state.type === "openai-responses-compaction") && typeof state.data === "string" && state.data.length > 0 && (state.id === void 0 || typeof state.id === "string") && (state.replayIndex === void 0 || !retained && typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
363
+ }
364
+ function readOpenAIResponsesCompactionReplayState(value) {
365
+ return isRecord(value) && isProviderReplayContext(value) && isOpenAIResponsesCompactionState(value) ? value : void 0;
366
+ }
367
+ function readOpenAIResponsesItemRecoveryAnchor(replay) {
368
+ const state = readOpenAIResponsesCompactionReplayState(replay);
369
+ return state?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE && typeof state.itemRecovery === "string" ? state.itemRecovery : void 0;
370
+ }
371
+ function captureOpenAIResponsesCompaction(output, item, boundary, model, captureMetadata, compactedOutput, outputTokens) {
372
+ const metadata = captureMetadata ?? buildOpenAIResponsesReasoningReplayMetadata(model);
373
+ if (!item.encrypted_content) return;
374
+ if (!metadata?.baseUrlHash) {
375
+ log.debug("[responses] skipping compaction capture: missing base URL hash");
376
+ return;
377
+ }
378
+ const currentReplay = readOpenAIResponsesCompactionReplayState(output.providerReplay);
379
+ if (typeof boundary === "number" && currentReplay?.type === "openai-responses-compaction" && (currentReplay.replayIndex ?? -1) > boundary) return;
380
+ if (compactedOutput && !isOpenAIResponsesCompactionOutput(compactedOutput, model)) throw new Error("Responses compact endpoint checkpoint is invalid");
381
+ const replay = {
382
+ v: 1,
383
+ ...boundary === "retained-users" ? { type: OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE } : {
384
+ type: OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE,
385
+ replayIndex: boundary
386
+ },
387
+ ...item.id ? { id: item.id } : {},
388
+ data: item.encrypted_content,
389
+ provider: metadata.provider,
390
+ api: metadata.api,
391
+ model: metadata.model,
392
+ baseUrlHash: metadata.baseUrlHash,
393
+ ...metadata.sessionHash ? { sessionHash: metadata.sessionHash } : {},
394
+ ...compactedOutput ? { compactedWindow: {
395
+ state: "ready",
396
+ output: JSON.stringify(compactedOutput),
397
+ ...outputTokens !== void 0 ? { outputTokens } : {}
398
+ } } : {}
360
399
  };
400
+ if (compactedOutput && !readOpenAIResponsesCompactionWindow(replay, model)) throw new Error("Responses compact endpoint checkpoint is invalid or exceeds 16 MiB");
401
+ output.providerReplay = replay;
361
402
  }
362
- /** Snapshots direct/custom tool descriptors before OpenAI payload construction. */
363
- function projectOpenAITools(tools) {
364
- return projectOpenAIToolDescriptors(tools);
403
+ function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheckpoint, itemRecovery) {
404
+ const context = buildProviderReplayContext(model, options);
405
+ if (!context.baseUrlHash) return;
406
+ output.providerReplay = {
407
+ v: 1,
408
+ type: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE,
409
+ data: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA,
410
+ ...context,
411
+ baseUrlHash: context.baseUrlHash,
412
+ ...itemRecovery ? { itemRecovery } : {}
413
+ };
414
+ if (rejectedCheckpoint) options?.onCompactionRejected?.(rejectedCheckpoint);
365
415
  }
366
- /** Package-private facts are consumed before the projection or payload can escape. */
367
- function prepareOpenAITools(tools) {
368
- const schemas = /* @__PURE__ */ new Map();
416
+ function createCompactionTracker(output, model, options) {
417
+ const replayIndexes = /* @__PURE__ */ new Map();
369
418
  return {
370
- projection: projectOpenAIToolDescriptors(tools, schemas),
371
- schemas
419
+ added(item, replayIndex) {
420
+ if (item.type === "compaction" && item.id) replayIndexes.set(item.id, replayIndex);
421
+ },
422
+ completed(item, fallbackReplayIndex) {
423
+ if (item.type !== "compaction" || !item.encrypted_content) return;
424
+ captureOpenAIResponsesCompaction(output, {
425
+ type: "compaction",
426
+ ...item.id ? { id: item.id } : {},
427
+ encrypted_content: item.encrypted_content
428
+ }, (item.id ? replayIndexes.get(item.id) : void 0) ?? fallbackReplayIndex, model, options?.reasoningReplayMetadata);
429
+ if (item.id) replayIndexes.delete(item.id);
430
+ }
372
431
  };
373
432
  }
374
- function projectOpenAIToolDescriptors(tools, schemas) {
375
- let inputToolCount;
376
- try {
377
- inputToolCount = tools.length;
378
- } catch {
379
- return {
380
- inputToolCount: 0,
381
- tools: [],
382
- diagnostics: [unreadableToolDiagnostic(0)]
383
- };
384
- }
385
- const projectedTools = [];
386
- const diagnostics = [];
387
- for (let toolIndex = 0; toolIndex < inputToolCount; toolIndex += 1) {
388
- let tool;
389
- let name;
390
- let parameters;
391
- let readPath = `tool[${toolIndex}]`;
392
- try {
393
- const candidate = tools[toolIndex];
394
- if (!candidate) {
395
- diagnostics.push(unreadableToolDiagnostic(toolIndex));
396
- continue;
397
- }
398
- tool = candidate;
399
- readPath += ".name";
400
- const nameValue = tool.name;
401
- if (typeof nameValue !== "string" || !nameValue) {
402
- diagnostics.push({
403
- toolIndex,
404
- violations: [`${readPath} is empty`]
405
- });
406
- continue;
407
- }
408
- name = nameValue;
409
- readPath = `${name}.parameters`;
410
- parameters = tool.parameters;
411
- } catch {
412
- diagnostics.push({
413
- toolIndex,
414
- ...name ? { toolName: name } : {},
415
- violations: [`${readPath} is unreadable`]
416
- });
433
+ function isSafeResponsesReplayItemId(id) {
434
+ return typeof id === "string" && id.length > 0 && id.length <= 64;
435
+ }
436
+ function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options) {
437
+ const context = buildProviderReplayContext(model, options);
438
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
439
+ const message = messages[index];
440
+ if (message?.role !== "assistant") continue;
441
+ const replay = readOpenAIResponsesCompactionReplayState(message.providerReplay);
442
+ if (replay?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) {
443
+ if (providerReplayContextMatches(replay, typeof replay.itemRecovery === "string" ? {
444
+ ...context,
445
+ sessionHash: replay.sessionHash
446
+ } : context)) return typeof replay.itemRecovery === "string" ? {
447
+ owner: message,
448
+ mode: "item-recovery",
449
+ anchor: replay.itemRecovery
450
+ } : void 0;
417
451
  continue;
418
452
  }
419
- const prepared = schemas ? prepareRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name) : void 0;
420
- const schemaProjection = prepared?.projection ?? projectRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name);
421
- if (!isRecord(schemaProjection.schema) || schemaProjection.violations.length > 0) {
422
- diagnostics.push({
423
- toolIndex,
424
- toolName: name,
425
- violations: schemaProjection.violations.length > 0 ? schemaProjection.violations : [`${name}.parameters must be a JSON object schema`]
426
- });
453
+ if (replay?.type !== "openai-responses-compaction" && replay?.type !== "openai-responses-retained-compaction") {
454
+ if (message.providerReplay?.type === "openai-responses-compaction" || message.providerReplay?.type === "openai-responses-retained-compaction") return;
427
455
  continue;
428
456
  }
429
- if (prepared?.normalization) schemas?.set(schemaProjection.schema, prepared.normalization);
430
- let descriptionValue;
431
- try {
432
- descriptionValue = tool.description;
433
- } catch {}
434
- const description = typeof descriptionValue === "string" ? descriptionValue : void 0;
435
- projectedTools.push({
436
- toolIndex,
437
- name,
438
- ...description !== void 0 ? { description } : {},
439
- parameters: schemaProjection.schema
440
- });
457
+ if (!providerReplayContextMatches(replay, context)) return;
458
+ if (replay.compactedWindow !== void 0 || replay.type === "openai-responses-retained-compaction") {
459
+ const output = readOpenAIResponsesCompactionWindow(replay, model);
460
+ const item = output?.at(-1);
461
+ if (!output || item?.type !== "compaction") return {
462
+ owner: message,
463
+ mode: "refresh-required"
464
+ };
465
+ return {
466
+ owner: message,
467
+ mode: "complete-window",
468
+ output,
469
+ ...replay.compactedWindow?.state === "ready" && replay.compactedWindow.outputTokens !== void 0 ? { outputTokens: replay.compactedWindow.outputTokens } : {},
470
+ item,
471
+ replayIndex: replay.type === "openai-responses-retained-compaction" ? message.content.length : replay.replayIndex ?? 0
472
+ };
473
+ }
474
+ return {
475
+ owner: message,
476
+ item: {
477
+ type: "compaction",
478
+ ...isSafeResponsesReplayItemId(replay.id) ? { id: replay.id } : {},
479
+ encrypted_content: replay.data
480
+ },
481
+ mode: "compacted-prefix",
482
+ replayIndex: replay.replayIndex ?? 0
483
+ };
441
484
  }
442
- return {
443
- inputToolCount,
444
- tools: projectedTools,
445
- diagnostics
446
- };
447
485
  }
448
- function reconcileToolChoice(choice, projection, responses) {
449
- const label = responses ? "OpenAI Responses" : "OpenAI Chat Completions";
450
- if (choice === "auto") return projection.tools.length > 0 ? choice : void 0;
451
- if (choice === "required") {
452
- if (projection.tools.length === 0) throw new Error(`${label} tool_choice requires a tool, but no tools survived schema conversion`);
453
- return choice;
454
- }
455
- if (choice === "none" || !isRecord(choice)) return choice;
456
- const choiceType = choice.type;
457
- if (!responses && choiceType === "custom") throw new Error("OpenAI Chat Completions custom tool_choice is unsupported because this adapter emits function tools only");
458
- if (choiceType === "function") {
459
- const functionChoice = responses ? choice : choice.function;
460
- const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
461
- if (typeof functionName !== "string") return choice;
462
- if (!projection.tools.some((tool) => tool.name === functionName)) throw new Error(`${label} tool_choice requested unavailable tool "${functionName}" after schema conversion`);
463
- return responses ? {
464
- type: "function",
465
- name: functionName
466
- } : {
467
- type: "function",
468
- function: { name: functionName }
469
- };
486
+ var CompactionReplayRefreshRequiredError = class extends Error {
487
+ constructor() {
488
+ super("Provider compaction checkpoint needs rebuilding. Run /compact to rebuild from saved conversation history.");
489
+ this.name = "CompactionReplayRefreshRequiredError";
470
490
  }
471
- if (choiceType !== "allowed_tools") return choice;
472
- const allowedConfig = responses ? choice : choice.allowed_tools;
473
- if (!isRecord(allowedConfig)) return choice;
474
- const { mode, tools } = allowedConfig;
475
- if (mode !== "auto" && mode !== "required" || !Array.isArray(tools)) return choice;
476
- const responseTools = [];
477
- const completionTools = [];
478
- for (const tool of tools) {
479
- if (!isRecord(tool) || tool.type !== "function") {
480
- if (responses) responseTools.push(tool);
481
- continue;
482
- }
483
- const functionChoice = responses ? tool : tool.function;
484
- const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
485
- if (typeof functionName === "string" && projection.tools.some((projectedTool) => projectedTool.name === functionName)) {
486
- if (responses) responseTools.push({
487
- type: "function",
488
- name: functionName
489
- });
490
- else completionTools.push({
491
- type: "function",
492
- function: { name: functionName }
493
- });
491
+ };
492
+ function buildOpenAIResponsesCompactionReplayPlan(messages, model, options) {
493
+ if (typeof options?.mode === "object") return {
494
+ messages,
495
+ preserveUnframedToolResults: false,
496
+ itemRecovery: { anchor: options.mode.itemRecovery }
497
+ };
498
+ const compaction = resolveNewestOpenAIResponsesCompactionReplay(messages, model, options);
499
+ if (!compaction) return {
500
+ messages,
501
+ preserveUnframedToolResults: false
502
+ };
503
+ if (compaction.mode === "item-recovery") {
504
+ const owner = compaction.owner;
505
+ let replayMessages = messages;
506
+ if (resolveFailedAssistantReplay(owner, { pairingAware: false }) === "drop") {
507
+ const boundary = {
508
+ role: "assistant",
509
+ content: [],
510
+ stopReason: "stop",
511
+ api: owner.api,
512
+ provider: owner.provider,
513
+ model: owner.model,
514
+ usage: owner.usage,
515
+ timestamp: owner.timestamp,
516
+ providerReplay: owner.providerReplay
517
+ };
518
+ replayMessages = [...messages];
519
+ replayMessages.splice(messages.indexOf(owner), 0, boundary);
494
520
  }
521
+ return {
522
+ messages: replayMessages,
523
+ preserveUnframedToolResults: false,
524
+ itemRecovery: { anchor: compaction.anchor }
525
+ };
495
526
  }
496
- if (responseTools.length === 0 && completionTools.length === 0) {
497
- if (mode === "auto") return "none";
498
- throw new Error(`${label} tool_choice requires a tool, but no allowed tools survived schema conversion`);
499
- }
500
- return responses ? {
501
- type: "allowed_tools",
502
- mode,
503
- tools: responseTools
504
- } : {
505
- type: "allowed_tools",
506
- allowed_tools: {
507
- mode,
508
- tools: completionTools
509
- }
527
+ if (options?.mode === "full-history") return {
528
+ messages,
529
+ preserveUnframedToolResults: false
530
+ };
531
+ if (compaction.mode === "refresh-required") throw new CompactionReplayRefreshRequiredError();
532
+ const ownerIndex = messages.indexOf(compaction.owner);
533
+ return {
534
+ messages: [{
535
+ ...compaction.owner,
536
+ content: compaction.owner.content.slice(compaction.replayIndex)
537
+ }, ...messages.slice(ownerIndex + 1)],
538
+ ...compaction.mode === "complete-window" ? { compactedWindow: compaction.output } : { compaction: compaction.item },
539
+ preserveUnframedToolResults: true
510
540
  };
511
541
  }
512
- /** Keeps Responses tool choices aligned with surviving function schemas. */
513
- function reconcileOpenAIResponsesToolChoice(choice, projection) {
514
- return reconcileToolChoice(choice, projection, true);
542
+ function buildOpenAIResponsesReasoningReplayMetadata(model, options) {
543
+ return {
544
+ v: 1,
545
+ source: "openai-responses",
546
+ ...buildProviderReplayContext(model, options)
547
+ };
515
548
  }
516
- /** Keeps Chat Completions tool choices aligned with surviving function schemas. */
517
- function reconcileOpenAICompletionsToolChoice(choice, projection) {
518
- return reconcileToolChoice(choice, projection, false);
549
+ //#endregion
550
+ //#region packages/ai/src/utils/text-signature.ts
551
+ function encodeTextSignatureV1(id, phase) {
552
+ return JSON.stringify({
553
+ v: 1,
554
+ id,
555
+ ...phase ? { phase } : {}
556
+ });
519
557
  }
520
- /** Re-expresses an object Chat Completions tool choice in the Responses wire shape. */
521
- function toOpenAIResponsesToolChoice(choice) {
522
- if (choice.type === "function") return {
523
- type: "function",
524
- name: choice.function.name
558
+ function parseOpenAIResponsesTextSignature(signature) {
559
+ if (!signature) return;
560
+ if (signature.startsWith("{")) try {
561
+ const parsed = JSON.parse(signature);
562
+ if (parsed.v === 1) {
563
+ const id = typeof parsed.id === "string" ? parsed.id : void 0;
564
+ const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
565
+ if (id !== void 0 || phase !== void 0) return {
566
+ id,
567
+ phase,
568
+ ...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
569
+ };
570
+ return;
571
+ }
572
+ } catch {}
573
+ return { id: signature };
574
+ }
575
+ //#endregion
576
+ //#region packages/ai/src/transports/openai-responses-input-replay.ts
577
+ function recordResponsesInputReplay(message, replay) {
578
+ if (replay) Object.assign(message, { openclawResponsesInputReplay: replay });
579
+ }
580
+ function readResponsesInputReplayState(message) {
581
+ const replay = "openclawResponsesInputReplay" in message ? message.openclawResponsesInputReplay : void 0;
582
+ return isRecord(replay) ? replay : void 0;
583
+ }
584
+ function readResponsesInputReplay(message) {
585
+ const replay = readResponsesInputReplayState(message);
586
+ if (replay && typeof replay.afterResponseId === "string" && isStringArray(replay.before) && isStringArray(replay.after)) return {
587
+ afterResponseId: replay.afterResponseId,
588
+ before: replay.before,
589
+ after: replay.after
525
590
  };
526
- return {
527
- type: "allowed_tools",
528
- mode: choice.allowed_tools.mode,
529
- tools: choice.allowed_tools.tools.map((tool) => tool.type === "function" && isRecord(tool.function) && typeof tool.function.name === "string" ? {
530
- type: "function",
531
- name: tool.function.name
532
- } : tool)
591
+ }
592
+ function responsesInputFingerprint(item) {
593
+ if (isRecord(item) && (item.type === "function_call_output" || item.type === "custom_tool_call_output") && typeof item.call_id === "string") return sha256Hex(stableStringify({
594
+ type: item.type,
595
+ call_id: item.call_id
596
+ }));
597
+ return sha256Hex(stableStringify(item));
598
+ }
599
+ /** Reconstruct delivery order without rewriting durable local completion events. */
600
+ function createResponsesInputReplay(model) {
601
+ const starts = /* @__PURE__ */ new Map();
602
+ const ends = /* @__PURE__ */ new Map();
603
+ const fingerprints = /* @__PURE__ */ new Map();
604
+ const fingerprint = (item) => {
605
+ const value = fingerprints.get(item) ?? responsesInputFingerprint(item);
606
+ fingerprints.set(item, value);
607
+ return value;
608
+ };
609
+ return (input, output, message) => {
610
+ const key = message.turnId || message.responseId;
611
+ const start = (key ? starts.get(key) : void 0) ?? output[0];
612
+ if (key && start) starts.set(key, start);
613
+ input.push(...output);
614
+ let end = input.at(-1);
615
+ const replay = readResponsesInputReplay(message);
616
+ const parent = replay ? ends.get(replay.afterResponseId) : void 0;
617
+ if (replay && parent && message.provider === model.provider && message.api === model.api && message.model === model.id) {
618
+ const take = (keys) => {
619
+ const moved = [];
620
+ for (const inputKey of keys.toReversed()) {
621
+ const boundary = input.indexOf(parent);
622
+ const index = input.findLastIndex((item, position) => position > boundary && fingerprint(item) === inputKey);
623
+ if (index > boundary) moved.unshift(...input.splice(index, 1));
624
+ }
625
+ return moved;
626
+ };
627
+ const before = take(replay.before);
628
+ const after = take(replay.after);
629
+ input.splice(start ? input.indexOf(start) : input.length, 0, ...before);
630
+ end = input.at(-1);
631
+ input.push(...after);
632
+ }
633
+ if (message.responseId && end) ends.set(message.responseId, end);
533
634
  };
534
635
  }
535
636
  //#endregion
536
- //#region packages/ai/src/providers/openai-request-reasoning.ts
537
- /** Preserve explicit off until the selected route maps it to its native value. */
538
- function resolveOpenAISimpleReasoningEffort(model, reasoning) {
539
- return reasoning === void 0 ? void 0 : clampThinkingLevel(model, reasoning);
637
+ //#region packages/ai/src/transports/openai-responses-replay.ts
638
+ /** Resolves the assistant message id that can be replayed to OpenAI Responses. */
639
+ function resolveReplayableResponsesMessageId(params) {
640
+ if (!params.replayResponsesItemIds) return;
641
+ if (!params.textSignatureId) return params.fallbackOrdinal === 0 ? params.fallbackId : `${params.fallbackId}_${params.fallbackOrdinal}`;
642
+ return params.previousReplayItemWasReasoning ? params.textSignatureId : void 0;
540
643
  }
541
- function resolveOpenAIRequestReasoning(model, reasoning) {
542
- const requested = normalizeOpenAIReasoningEffort(reasoning ?? "off");
543
- const modelLevel = MODEL_CATALOG_THINKING_LEVELS.find((candidate) => candidate === requested);
544
- const modelMapped = modelLevel ? model.thinkingLevelMap?.[modelLevel] : void 0;
545
- const mapped = modelMapped === null ? null : resolveOpenAIReasoningEffortMapping(requested, resolveOpenAIReasoningEffortMap(model)) ?? modelMapped;
546
- const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0 ? void 0 : requested;
547
- const normalizedIntent = normalizeOpenAIReasoningEffort(intent ?? "off");
548
- const disabled = requested === "off" || requested === "none";
549
- const supported = resolveOpenAIModelReasoningEfforts(disabled && resolveOpenAIThinkingApi(model.api) !== "openai-chatgpt-responses" && !isKnownOpenAIEndpoint(model) ? { compat: model.compat } : model);
550
- const effort = !model.reasoning || supported?.length === 0 || intent === void 0 ? void 0 : supported === void 0 ? disabled && mapped === void 0 ? void 0 : intent : resolveOpenAIReasoningEffortForModel({
551
- model,
552
- effort: requested,
553
- fallbackMap: { [requested]: intent }
554
- });
644
+ function normalizeOpenAIResponsesReasoningReplayItem(item, api) {
645
+ if (api === "openai-chatgpt-responses") return Array.isArray(item.summary) ? item : {
646
+ ...item,
647
+ summary: []
648
+ };
555
649
  return {
556
- effort: effort === "none" && resolveOpenAIThinkingApi(model.api) === "openai-chatgpt-responses" && !supportsOpenAIReasoningEffort(model.id === "gpt-6-sol" || model.id === "gpt-6-luna" ? model : {
557
- compat: model.compat,
558
- thinkingLevelMap: model.thinkingLevelMap
559
- }, "none") ? void 0 : effort,
560
- thinkingEnabled: intent === void 0 ? void 0 : model.reasoning && normalizedIntent !== "off" && normalizedIntent !== "none"
650
+ id: item.id,
651
+ type: "reasoning",
652
+ summary: [],
653
+ ...Array.isArray(item.content) && item.content.length === 0 ? { content: [] } : {},
654
+ status: item.status,
655
+ encrypted_content: item.encrypted_content
561
656
  };
562
657
  }
563
- //#endregion
564
- //#region packages/ai/src/transports/openai-transport-params.ts
565
- const MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS = 256;
566
- const loggedOpenAIStrictToolDowngradeDiagnosticKeys = /* @__PURE__ */ new Set();
567
- const OPENAI_COMPLETIONS_APIS = /* @__PURE__ */ new Set(["openai-completions", "openclaw-openai-completions-transport"]);
568
- function readToolPayloadField(record, field) {
569
- try {
570
- return Object.hasOwn(record, field) ? record[field] : void 0;
571
- } catch {
572
- return;
573
- }
658
+ /** Replay original bytes only while the normalized arguments still match the saved call. */
659
+ function replayOpenAIResponsesToolArguments(block, providerStyle, sameModel) {
660
+ const value = providerStyle ? JSON.stringify(block.arguments) : typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {});
661
+ const signature = sameModel && block.argumentsSignature;
662
+ return signature && signature.value === value && typeof signature.raw === "string" ? signature.raw : value;
574
663
  }
575
- function readCodeModePayloadToolName(tool) {
576
- if (!isRecord(tool)) return;
577
- const name = readToolPayloadField(tool, "name");
578
- if (typeof name === "string") return name;
579
- const fn = readToolPayloadField(tool, "function");
580
- if (!isRecord(fn)) return;
581
- const fnName = readToolPayloadField(fn, "name");
582
- return typeof fnName === "string" ? fnName : void 0;
664
+ //#endregion
665
+ //#region packages/ai/src/transports/openai-responses-replay-messages-internal.ts
666
+ function resolveResponsesInstructionRole(model) {
667
+ const supportsDeveloperRole = !isRecord(model.compat) || model.compat.supportsDeveloperRole !== false;
668
+ return model.reasoning && supportsDeveloperRole ? "developer" : "system";
583
669
  }
584
- function readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes) {
585
- if (!isRecord(tool)) return;
586
- const type = readToolPayloadField(tool, "type");
587
- if (typeof type === "string" && allowedHostedToolTypes?.has(type)) {
588
- try {
589
- if (Object.hasOwn(tool, "name") || Object.hasOwn(tool, "function") || Object.hasOwn(tool, "functionDeclarations") || Object.hasOwn(tool, "function_declarations")) return false;
590
- } catch {
591
- return false;
670
+ function stripEncryptedReasoningContentFields(value) {
671
+ if (!value || typeof value !== "object") return value;
672
+ if (Array.isArray(value)) {
673
+ let changed = false;
674
+ const next = value.map((item) => {
675
+ const stripped = stripEncryptedReasoningContentFields(item);
676
+ changed ||= !Object.is(stripped, item);
677
+ return stripped;
678
+ });
679
+ return changed ? next : value;
680
+ }
681
+ const source = value;
682
+ if (source.type === "compaction") return value;
683
+ let changed = false;
684
+ const next = {};
685
+ for (const [key, child] of Object.entries(source)) {
686
+ if (key === "encrypted_content") {
687
+ changed = true;
688
+ continue;
592
689
  }
593
- return `hosted:${type}`;
690
+ const stripped = stripEncryptedReasoningContentFields(child);
691
+ changed ||= !Object.is(stripped, child);
692
+ next[key] = stripped;
594
693
  }
595
- const name = readCodeModePayloadToolName(tool);
596
- return typeof name === "string" && isCodeModeModelVisibleToolName(name, visibleToolNames) ? `client:${name}` : void 0;
694
+ return changed ? next : value;
597
695
  }
598
- function readCodeModePayloadToolIdentities(payload) {
599
- if (!isRecord(payload)) return [];
600
- const tools = readToolPayloadField(payload, "tools");
601
- if (!Array.isArray(tools)) return [];
602
- return tools.flatMap((tool) => {
603
- if (!isRecord(tool)) return [];
604
- const identities = [];
605
- const name = readCodeModePayloadToolName(tool);
606
- if (name) identities.push(`client:${name}`);
607
- for (const key of ["functionDeclarations", "function_declarations"]) {
608
- const declarations = readToolPayloadField(tool, key);
609
- if (!Array.isArray(declarations)) continue;
610
- for (const declaration of declarations) {
611
- const declarationName = readCodeModePayloadToolName(declaration);
612
- if (declarationName) identities.push(`client:${declarationName}`);
613
- }
614
- }
615
- const type = readToolPayloadField(tool, "type");
616
- if (typeof type === "string" && type !== "function") identities.push(`hosted:${type}`);
617
- return identities;
618
- });
696
+ function isOpenAIResponsesReasoningReplayMetadata(value) {
697
+ return isProviderReplayContext(value) && value.v === 1 && value.source === "openai-responses";
619
698
  }
620
- function filterCodeModePayloadTools(payload, visibleToolNames, allowedHostedToolTypes, observer) {
621
- if (!isRecord(payload)) return;
622
- const tools = readToolPayloadField(payload, "tools");
623
- if (!Array.isArray(tools)) return;
624
- const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
625
- payload.tools = tools.flatMap((tool) => {
626
- const identity = readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes);
627
- if (identity) return [tool];
628
- if (identity === false) return [];
629
- if (!isRecord(tool)) return [];
630
- const filteredGroups = {};
631
- for (const key of ["functionDeclarations", "function_declarations"]) {
632
- const declarations = readToolPayloadField(tool, key);
633
- if (!Array.isArray(declarations)) continue;
634
- const filtered = declarations.filter((declaration) => {
635
- const declarationName = readCodeModePayloadToolName(declaration);
636
- return typeof declarationName === "string" && isCodeModeModelVisibleToolName(declarationName, visibleToolNames);
637
- });
638
- if (filtered.length > 0) filteredGroups[key] = filtered;
639
- }
640
- return Object.keys(filteredGroups).length > 0 ? [filteredGroups] : [];
641
- });
642
- if (beforeToolIdentities) observer?.({
643
- beforeToolIdentities,
644
- afterToolIdentities: readCodeModePayloadToolIdentities(payload)
645
- });
699
+ function readOpenAIResponsesReasoningReplayBlockMetadata(block) {
700
+ if (!Object.hasOwn(block, "openclawReasoningReplay")) return;
701
+ const value = block[OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY];
702
+ return isOpenAIResponsesReasoningReplayMetadata(value) ? value : null;
646
703
  }
647
- function resolveCodeModeResponsesVisibleToolNames(context) {
648
- return new Set((context.tools ?? []).map(readCodeModePayloadToolName).filter((name) => typeof name === "string"));
704
+ function prepareOpenAIResponsesReasoningItemForReplay(item, context, blockMetadata, options) {
705
+ const hasRawMetadata = Object.hasOwn(item, OPENAI_RESPONSES_REASONING_REPLAY_META_KEY);
706
+ const { [OPENAI_RESPONSES_REASONING_REPLAY_META_KEY]: rawMetadata, ...rest } = item;
707
+ if (!("encrypted_content" in rest)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
708
+ const metadata = blockMetadata !== void 0 ? blockMetadata ?? void 0 : isOpenAIResponsesReasoningReplayMetadata(rawMetadata) ? rawMetadata : void 0;
709
+ if (blockMetadata === void 0 && !hasRawMetadata && options?.preserveUnattributedEncryptedContent === true || metadata && providerReplayContextMatches(metadata, context)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
710
+ return normalizeOpenAIResponsesReasoningReplayItem(stripEncryptedReasoningContentFields(rest), context.api);
649
711
  }
650
- function enforceCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes, observer) {
651
- if (!isRecord(payload)) return;
652
- const tools = readToolPayloadField(payload, "tools");
653
- if (!Array.isArray(tools)) return;
654
- const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
655
- payload.tools = tools.filter((tool) => Boolean(readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes)));
656
- if (beforeToolIdentities) observer?.({
657
- beforeToolIdentities,
658
- afterToolIdentities: readCodeModePayloadToolIdentities(payload)
659
- });
712
+ function normalizeResponsesReplayItemId(id) {
713
+ if (!id) return;
714
+ if (id.length <= 64) return id;
715
+ return `msg_${shortHash(id)}`;
660
716
  }
661
- function assertCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes) {
662
- const tools = isRecord(payload) ? readToolPayloadField(payload, "tools") : void 0;
663
- if (!Array.isArray(tools)) throw new Error("Code mode payload tool surface violation: expected exec,wait; got no tools");
664
- const identities = tools.map((tool) => readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes));
665
- const names = identities.flatMap((identity) => typeof identity === "string" && identity.startsWith("client:") ? [identity.slice(7)] : []).toSorted((left, right) => left.localeCompare(right));
666
- if (names.length >= 2 && identities.every((identity) => typeof identity === "string") && new Set(identities).size === identities.length && names.includes("exec") && names.includes("wait")) return;
667
- throw new Error(`Code mode payload tool surface violation: expected exec,wait plus direct-only tools; got ${names.length > 0 ? names.join(",") : "none"}`);
717
+ function responsesAssistantTurnKey(message) {
718
+ const id = message.turnId || message.responseId;
719
+ return id ? `${message.provider}:${message.api}:${message.model}:${id}` : void 0;
668
720
  }
669
- function resolveOpenAIStrictToolFlagWithDiagnostics(projection, strictSetting, context) {
670
- const strict = resolveOpenAIProjectedToolsStrictToolFlag(projection, strictSetting);
671
- if (strictSetting === true && strict === false) getAiTransportHost().logDebug("openai-transport", () => {
672
- const diagnostics = findOpenAIStrictToolProjectionDiagnostics(projection);
673
- const key = sha256Hex(JSON.stringify({
674
- transport: context.transport,
675
- provider: context.model.provider ?? null,
676
- model: context.model.id ?? null,
677
- diagnostics: diagnostics.map((entry) => ({
678
- toolIndex: entry.toolIndex,
679
- toolName: entry.toolName ?? null,
680
- violations: entry.violations
681
- }))
682
- }));
683
- if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.has(key)) return null;
684
- if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.size >= MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS) loggedOpenAIStrictToolDowngradeDiagnosticKeys.clear();
685
- loggedOpenAIStrictToolDowngradeDiagnosticKeys.add(key);
686
- const sample = diagnostics.slice(0, 5).map((entry) => ({
687
- tool: entry.toolName ?? `tool[${entry.toolIndex}]`,
688
- violations: entry.violations.slice(0, 8)
689
- }));
690
- return {
691
- message: `OpenAI ${context.transport} tool schema strict mode downgraded to strict=false for ${context.model.provider ?? "unknown"}/${context.model.id ?? "unknown"} because ${diagnostics.length} tool schema(s) are not strict-compatible`,
692
- data: {
693
- transport: context.transport,
694
- provider: context.model.provider,
695
- model: context.model.id,
696
- incompatibleToolCount: diagnostics.length,
697
- sample
721
+ function orderResponsesAsyncToolResults(source) {
722
+ const lastAssistant = /* @__PURE__ */ new Map();
723
+ for (const [index, message] of source.entries()) if (message.role === "assistant") {
724
+ const key = responsesAssistantTurnKey(message);
725
+ if (key) lastAssistant.set(key, index);
726
+ }
727
+ const owners = /* @__PURE__ */ new Map();
728
+ const pending = /* @__PURE__ */ new Map();
729
+ const ordered = [];
730
+ for (const [index, message] of source.entries()) {
731
+ if (message.role === "assistant") {
732
+ const key = responsesAssistantTurnKey(message);
733
+ if (key) {
734
+ for (const block of message.content) if (block.type === "toolCall" && block.async) owners.set(block.id, key);
698
735
  }
699
- };
700
- });
701
- return strict;
702
- }
703
- function buildOpenAIClientHeaders(model, context, optionHeaders, turnHeaders, sessionId, cacheRetention) {
704
- const providerHeaders = { ...model.headers };
705
- if (model.provider === "github-copilot") Object.assign(providerHeaders, getAiTransportHost().buildCopilotDynamicHeaders(context.messages));
706
- if (OPENAI_COMPLETIONS_APIS.has(model.api) && sessionId && cacheRetention !== "none") {
707
- const { sessionAffinity } = resolveOpenAICompletionsCompat(model);
708
- if (sessionAffinity !== "none") {
709
- const affinityValue = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
710
- const affinityHeaders = sessionAffinity === "openrouter" ? ["x-session-id"] : [
711
- "session_id",
712
- "x-client-request-id",
713
- "x-session-affinity"
714
- ];
715
- const configuredHeaders = new Set(Object.keys(providerHeaders).map((key) => key.toLowerCase()));
716
- for (const name of affinityHeaders) if (!configuredHeaders.has(name)) providerHeaders[name] = affinityValue;
736
+ }
737
+ const owner = message.role === "toolResult" ? owners.get(message.toolCallId) : void 0;
738
+ const lastIndex = owner ? lastAssistant.get(owner) : void 0;
739
+ if (lastIndex !== void 0 && lastIndex > index) {
740
+ const results = pending.get(lastIndex) ?? [];
741
+ results.push(message);
742
+ pending.set(lastIndex, results);
743
+ } else ordered.push(message);
744
+ const results = pending.get(index);
745
+ if (results) {
746
+ ordered.push(...results);
747
+ pending.delete(index);
717
748
  }
718
749
  }
719
- const callerHeaders = {
720
- ...optionHeaders,
721
- ...turnHeaders
722
- };
723
- const resolvedHeaders = getAiTransportHost().resolveProviderRequestHeaders({
724
- provider: model.provider,
725
- api: model.api,
726
- baseUrl: model.baseUrl,
727
- providerHeaders,
728
- callerHeaders: Object.keys(callerHeaders).length > 0 ? callerHeaders : void 0,
729
- precedence: "caller-wins",
730
- model
731
- }) ?? {};
732
- const sendSessionIdHeader = (OPENAI_RESPONSES_APIS.has(model.api) && model.compat && "sendSessionIdHeader" in model.compat ? model.compat?.sendSessionIdHeader : void 0) ?? usesNativeOpenAICodexResponsesBackend(model);
733
- if (sessionId && cacheRetention !== "none" && sendSessionIdHeader && !Object.keys(resolvedHeaders).some((key) => normalizeLowercaseStringOrEmpty(key) === "session_id")) resolvedHeaders.session_id = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
734
- return resolveOpencodeSessionHeaders(model, {
735
- sessionId,
736
- headers: resolvedHeaders
737
- }) ?? resolvedHeaders;
738
- }
739
- function buildOpenAISdkClientOptions(model) {
740
- const timeout = resolveModelRequestTimeoutMs(model);
741
- return {
742
- ...timeout === void 0 ? {} : { timeout },
743
- maxRetries: 0
744
- };
750
+ return ordered;
745
751
  }
746
- function buildOpenAISdkRequestOptions(model, signal, options) {
747
- const timeout = resolveModelRequestTimeoutMs(model, options?.timeoutMs);
748
- const headers = options?.stream === true && usesNativeOpenAICodexResponsesBackend(model) ? { Accept: "text/event-stream" } : void 0;
749
- if (timeout === void 0 && !signal && !headers) return;
750
- return {
751
- ...headers ? { headers } : {},
752
- ...signal ? { signal } : {},
753
- ...timeout !== void 0 ? { timeout } : {},
754
- maxRetries: 0
755
- };
752
+ const responsesInputSource = Symbol("openclaw.responsesInputSource");
753
+ /** Source identity survives payload spreads but never enters serialized provider input. */
754
+ function bindResponsesInputMessage(source) {
755
+ const identity = {};
756
+ Object.defineProperty(source, responsesInputSource, {
757
+ value: identity,
758
+ enumerable: true
759
+ });
760
+ return (input) => typeof input === "object" && input !== null && Reflect.get(input, responsesInputSource) === identity;
756
761
  }
757
- function getCompat(model) {
758
- const resolved = resolveOpenAICompletionsCompat(model);
759
- const compat = model.compat ?? {};
762
+ function buildResponsesInputMessage(role, content, source) {
763
+ const identity = source && Reflect.get(source, responsesInputSource);
760
764
  return {
761
- ...resolved,
762
- reasoningEffortMap: resolveOpenAIReasoningEffortMap(model, {}),
763
- openRouterRouting: resolved.openRouterRouting ?? {},
764
- requiresStringContent: compat.requiresStringContent ?? false,
765
- strictMessageKeys: compat.strictMessageKeys === true
765
+ type: "message",
766
+ role,
767
+ content,
768
+ ...identity ? { [responsesInputSource]: identity } : {}
766
769
  };
767
770
  }
768
- //#endregion
769
- //#region packages/ai/src/transports/openai-responses-compaction-replay.ts
770
- const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE = "openai-responses-compaction-suppression";
771
- const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA = "rejected";
772
- function isOpenAIResponsesCompactionState(state) {
773
- if (typeof state.baseUrlHash !== "string" || state.v !== 1) return false;
774
- if (state.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) return state.data === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA;
775
- const retained = state.type === OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE;
776
- return (retained || state.type === "openai-responses-compaction") && typeof state.data === "string" && state.data.length > 0 && (state.id === void 0 || typeof state.id === "string") && (state.replayIndex === void 0 || !retained && typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
777
- }
778
- function readOpenAIResponsesCompactionReplayState(value) {
779
- return isRecord(value) && isProviderReplayContext(value) && isOpenAIResponsesCompactionState(value) ? value : void 0;
780
- }
781
- function captureOpenAIResponsesCompaction(output, item, boundary, model, captureMetadata, compactedOutput, outputTokens) {
782
- const metadata = captureMetadata ?? buildOpenAIResponsesReasoningReplayMetadata(model);
783
- if (!item.encrypted_content) return;
784
- if (!metadata?.baseUrlHash) {
785
- log.debug("[responses] skipping compaction capture: missing base URL hash");
786
- return;
787
- }
788
- const currentReplay = readOpenAIResponsesCompactionReplayState(output.providerReplay);
789
- if (typeof boundary === "number" && currentReplay?.type === "openai-responses-compaction" && (currentReplay.replayIndex ?? -1) > boundary) return;
790
- if (compactedOutput && !isOpenAIResponsesCompactionOutput(compactedOutput, model)) throw new Error("Responses compact endpoint checkpoint is invalid");
791
- const replay = {
792
- v: 1,
793
- ...boundary === "retained-users" ? { type: OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE } : {
794
- type: OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE,
795
- replayIndex: boundary
796
- },
797
- ...item.id ? { id: item.id } : {},
798
- data: item.encrypted_content,
799
- provider: metadata.provider,
800
- api: metadata.api,
801
- model: metadata.model,
802
- baseUrlHash: metadata.baseUrlHash,
803
- ...metadata.sessionHash ? { sessionHash: metadata.sessionHash } : {},
804
- ...compactedOutput ? { compactedWindow: {
805
- state: "ready",
806
- output: JSON.stringify(compactedOutput),
807
- ...outputTokens !== void 0 ? { outputTokens } : {}
808
- } } : {}
809
- };
810
- if (compactedOutput && !readOpenAIResponsesCompactionWindow(replay, model)) throw new Error("Responses compact endpoint checkpoint is invalid or exceeds 16 MiB");
811
- output.providerReplay = replay;
771
+ const responsesMessageProjections = /* @__PURE__ */ new WeakMap();
772
+ /** Detach hook-editable JSON containers while retaining scalar strings. */
773
+ function cloneResponsesInputForPayloadHook(value) {
774
+ if (!value || typeof value !== "object") return value;
775
+ if (Array.isArray(value)) return value.map(cloneResponsesInputForPayloadHook);
776
+ const copy = { ...value };
777
+ for (const key of Object.keys(copy)) Reflect.set(copy, key, cloneResponsesInputForPayloadHook(Reflect.get(value, key)));
778
+ return copy;
812
779
  }
813
- function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheckpoint) {
814
- const context = buildProviderReplayContext(model, options);
815
- if (!context.baseUrlHash) return;
816
- output.providerReplay = {
817
- v: 1,
818
- type: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE,
819
- data: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA,
820
- ...context,
821
- baseUrlHash: context.baseUrlHash
780
+ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, conversionStyle) {
781
+ const messages = [];
782
+ const providerStyle = conversionStyle === "provider";
783
+ const shouldReplayResponsesItemIds = options?.replayResponsesItemIds ?? true;
784
+ const replayContext = buildProviderReplayContext(model, { sessionId: options?.sessionId });
785
+ const shouldNormalizeSameModelToolCallIds = model.provider === "github-copilot";
786
+ const sanitizeIdPart = (part) => {
787
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
788
+ return providerStyle ? sanitized : sanitized.replace(/_+$/, "");
822
789
  };
823
- if (rejectedCheckpoint) options?.onCompactionRejected?.(rejectedCheckpoint);
824
- }
825
- function createCompactionTracker(output, model, options) {
826
- const replayIndexes = /* @__PURE__ */ new Map();
827
- return {
828
- added(item, replayIndex) {
829
- if (item.type === "compaction" && item.id) replayIndexes.set(item.id, replayIndex);
830
- },
831
- completed(item, fallbackReplayIndex) {
832
- if (item.type !== "compaction" || !item.encrypted_content) return;
833
- captureOpenAIResponsesCompaction(output, {
834
- type: "compaction",
835
- ...item.id ? { id: item.id } : {},
836
- encrypted_content: item.encrypted_content
837
- }, (item.id ? replayIndexes.get(item.id) : void 0) ?? fallbackReplayIndex, model, options?.reasoningReplayMetadata);
838
- if (item.id) replayIndexes.delete(item.id);
790
+ const normalizeIdPart = (part) => {
791
+ const sanitized = sanitizeIdPart(part);
792
+ return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
793
+ };
794
+ const buildForeignResponsesItemId = (itemId) => `fc_${shortHash(itemId)}`;
795
+ const buildSameProviderCopilotResponsesItemId = (itemId) => {
796
+ const sanitized = sanitizeIdPart(itemId);
797
+ const candidate = sanitized.startsWith("fc_") ? sanitized : `fc_${sanitized}`;
798
+ return candidate.length > 64 ? buildForeignResponsesItemId(itemId) : candidate;
799
+ };
800
+ const normalizeToolCallId = (id, _targetModel, source) => {
801
+ if (!allowedToolCallProviders.has(model.provider) || !id.includes("|")) return normalizeIdPart(id);
802
+ const separatorIndex = id.indexOf("|");
803
+ const callId = id.slice(0, separatorIndex);
804
+ const itemId = id.slice(separatorIndex + 1);
805
+ const normalizedCallId = normalizeIdPart(callId);
806
+ let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : model.provider === "github-copilot" ? providerStyle ? normalizeIdPart(itemId) : buildSameProviderCopilotResponsesItemId(itemId) : normalizeIdPart(itemId);
807
+ if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
808
+ return `${normalizedCallId}|${normalizedItemId}`;
809
+ };
810
+ const replayPlan = buildOpenAIResponsesCompactionReplayPlan(context.messages, model, {
811
+ sessionId: options?.sessionId,
812
+ mode: options?.replayMode
813
+ });
814
+ if (replayPlan.itemRecovery) options?.onItemRecovery?.();
815
+ const transformMessages = (source) => providerStyle ? transformProviderMessages(source, model, normalizeToolCallId) : getAiTransportHost().transformTransportMessages(source, model, normalizeToolCallId, {
816
+ normalizeSameModelToolCallIds: shouldNormalizeSameModelToolCallIds,
817
+ preserveUnframedToolResults: replayPlan.preserveUnframedToolResults || preparedRequestSuffix.has(context)
818
+ });
819
+ const transformedMessages = orderResponsesAsyncToolResults(transformMessages(replayPlan.messages));
820
+ if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
821
+ type: "input_text",
822
+ text: prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions
823
+ }]));
824
+ if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow.map((item) => {
825
+ if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return Object.assign({}, item, { [RESPONSES_RETAINED_USER]: true });
826
+ return item;
827
+ }));
828
+ let replayMessages = replayPlan.compaction ? [replayPlan.compaction, ...transformedMessages] : transformedMessages;
829
+ const isCarrier = (message) => "role" in message && hasRuntimeContextMarker(message);
830
+ if (replayMessages.some(isCarrier)) {
831
+ const anchored = [];
832
+ let insertionIndex = replayPlan.compactedWindow ? 0 : void 0;
833
+ for (const message of replayMessages) {
834
+ if (isCarrier(message) && insertionIndex !== void 0) {
835
+ anchored.splice(insertionIndex++, 0, message);
836
+ continue;
837
+ }
838
+ anchored.push(message);
839
+ if (!isCarrier(message) && ("role" in message ? message.role === "user" : message.type === "compaction")) insertionIndex = anchored.length;
840
+ }
841
+ replayMessages = anchored;
842
+ }
843
+ let msgIndex = 0;
844
+ let recoveryAnchor = replayPlan.itemRecovery?.anchor;
845
+ let pastRecoveryBoundary = false;
846
+ const recoveredCalls = recoveryAnchor ? /* @__PURE__ */ new Set() : void 0;
847
+ const replayCallId = (id) => recoveryAnchor ? `call_${shortHash(`${recoveryAnchor}:${id}`)}` : id;
848
+ const appendAssistant = createResponsesInputReplay(model);
849
+ const inHistorySystemUpdates = supportsNativeOpenAIResponsesEndpoint(model);
850
+ const convertMessage = (msg, messageIndex) => {
851
+ const replayItemIds = shouldReplayResponsesItemIds && !recoveryAnchor;
852
+ const converted = [];
853
+ if (inHistorySystemUpdates && isRuntimeContextMessage(msg)) converted.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
854
+ type: "input_text",
855
+ text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
856
+ }]));
857
+ else if (msg.role === "user") {
858
+ const role = msg.operatorMessage && inHistorySystemUpdates && (typeof msg.content === "string" || msg.content.every((block) => block.type === "text")) ? resolveResponsesInstructionRole(model) : "user";
859
+ const content = typeof msg.content === "string" ? [{
860
+ type: "input_text",
861
+ text: sanitizeTransportPayloadText(msg.content)
862
+ }] : msg.content.map((item) => item.type === "text" ? {
863
+ type: "input_text",
864
+ text: sanitizeTransportPayloadText(item.text)
865
+ } : buildResponsesInputImage(item)).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
866
+ if (content.length > 0) {
867
+ const input = buildResponsesInputMessage(role, content, msg);
868
+ if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
869
+ converted.push(input);
870
+ }
871
+ } else if (msg.role === "assistant") {
872
+ const output = converted;
873
+ const sourceTurnKey = responsesAssistantTurnKey(msg);
874
+ const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
875
+ let textFallbackOrdinal = 0;
876
+ let previousReasoningHasId = false;
877
+ let seenReplayableReasoning = false;
878
+ const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
879
+ for (const block of msg.content) if (block.type === "thinking") {
880
+ if (recoveryAnchor) continue;
881
+ if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
882
+ let reasoningItem;
883
+ try {
884
+ reasoningItem = JSON.parse(block.thinkingSignature);
885
+ } catch {
886
+ continue;
887
+ }
888
+ if (!isRecord(reasoningItem) || reasoningItem.type !== "reasoning") continue;
889
+ const replayableReasoningItem = prepareOpenAIResponsesReasoningItemForReplay(reasoningItem, replayContext, readOpenAIResponsesReasoningReplayBlockMetadata(isRecord(block) ? block : {}), providerStyle ? { preserveUnattributedEncryptedContent: true } : void 0);
890
+ if (replayableReasoningItem.encrypted_content && (inHistorySystemUpdates || !replayItemIds)) delete replayableReasoningItem.id;
891
+ else if (!replayItemIds || !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
892
+ output.push(replayableReasoningItem);
893
+ const reasoningId = replayableReasoningItem.id;
894
+ previousReasoningHasId = typeof reasoningId === "string";
895
+ seenReplayableReasoning ||= typeof reasoningId === "string" && reasoningId.startsWith("rs_");
896
+ }
897
+ } else if (block.type === "text") {
898
+ const textSignature = parseOpenAIResponsesTextSignature(block.textSignature);
899
+ let msgId = resolveReplayableResponsesMessageId({
900
+ replayResponsesItemIds: replayItemIds,
901
+ textSignatureId: textSignature?.id,
902
+ fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`,
903
+ fallbackOrdinal: textFallbackOrdinal,
904
+ previousReplayItemWasReasoning: previousReasoningHasId
905
+ });
906
+ if (!textSignature?.id) textFallbackOrdinal += 1;
907
+ msgId = normalizeResponsesReplayItemId(msgId);
908
+ const sources = textSignature?.sources;
909
+ const providerText = sources && block.text.endsWith(sources) ? block.text.slice(0, -sources.length) : block.text;
910
+ const messageItem = {
911
+ type: "message",
912
+ role: "assistant",
913
+ content: [{
914
+ type: "output_text",
915
+ text: sanitizeTransportPayloadText(providerText),
916
+ annotations: []
917
+ }],
918
+ status: "completed",
919
+ ...msgId ? { id: msgId } : {},
920
+ phase: textSignature?.phase
921
+ };
922
+ output.push(messageItem);
923
+ previousReasoningHasId = false;
924
+ } else if (block.type === "toolCall") {
925
+ const separatorIndex = block.id.indexOf("|");
926
+ const callId = separatorIndex === -1 ? block.id : block.id.slice(0, separatorIndex);
927
+ const itemIdRaw = separatorIndex === -1 ? void 0 : block.id.slice(separatorIndex + 1);
928
+ const itemId = replayItemIds && (!itemIdRaw?.startsWith("fc_") || seenReplayableReasoning && !isDifferentModel) ? itemIdRaw : void 0;
929
+ output.push({
930
+ type: "function_call",
931
+ ...itemId ? { id: itemId } : {},
932
+ call_id: replayCallId(callId),
933
+ name: block.name,
934
+ ...block.async ? { async: true } : {},
935
+ arguments: replayOpenAIResponsesToolArguments(block, providerStyle, msg.model === model.id && msg.provider === model.provider && msg.api === model.api)
936
+ });
937
+ previousReasoningHasId = false;
938
+ }
939
+ while (true) {
940
+ const last = output.at(-1);
941
+ if (last?.type !== "reasoning" || !last.id?.startsWith("rs_") || typeof last.encrypted_content === "string" && last.encrypted_content.length > 0) break;
942
+ output.pop();
943
+ }
944
+ return output;
945
+ } else if (msg.role === "toolResult") {
946
+ const textResult = extractToolResultText(msg.content);
947
+ const hasText = textResult.trim().length > 0;
948
+ const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
949
+ const hasImages = msg.content.some(isImageWithMediaPayload);
950
+ const separatorIndex = msg.toolCallId.indexOf("|");
951
+ const rawCallId = separatorIndex === -1 ? msg.toolCallId : msg.toolCallId.slice(0, separatorIndex);
952
+ const callId = preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, rawCallId, normalizeToolCallId(rawCallId, model, model)) : rawCallId;
953
+ let output = hasText ? textResult : mediaPlaceholder ?? "(no output)";
954
+ if (hasImages && model.input.includes("image")) {
955
+ const parts = [];
956
+ let hasExplicitText = false;
957
+ for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(buildResponsesInputImage(item));
958
+ else if (hasText && item.type === "text") {
959
+ const text = extractToolResultBlockText(item);
960
+ if (text) {
961
+ const joinedText = `${hasExplicitText ? "\n" : ""}${text}`;
962
+ hasExplicitText = true;
963
+ const previous = parts.at(-1);
964
+ if (previous?.type === "input_text") previous.text += joinedText;
965
+ else parts.push({
966
+ type: "input_text",
967
+ text: joinedText
968
+ });
969
+ }
970
+ }
971
+ if (hasText && !hasExplicitText) parts.unshift({
972
+ type: "input_text",
973
+ text: textResult
974
+ });
975
+ else if (!hasText && mediaPlaceholder === "(see attached media)") parts.unshift({
976
+ type: "input_text",
977
+ text: mediaPlaceholder
978
+ });
979
+ output = parts;
980
+ }
981
+ converted.push({
982
+ type: "function_call_output",
983
+ call_id: replayCallId(callId),
984
+ output
985
+ });
839
986
  }
987
+ return converted;
840
988
  };
841
- }
842
- function isSafeResponsesReplayItemId(id) {
843
- return typeof id === "string" && id.length > 0 && id.length <= 64;
844
- }
845
- function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options) {
846
- const context = buildProviderReplayContext(model, options);
847
- for (let index = messages.length - 1; index >= 0; index -= 1) {
848
- const message = messages[index];
849
- if (message?.role !== "assistant") continue;
850
- const replay = readOpenAIResponsesCompactionReplayState(message.providerReplay);
851
- if (replay?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) {
852
- if (providerReplayContextMatches(replay, context)) return;
989
+ const immutable = getAiTransportHost().immutableData;
990
+ const projectionKey = JSON.stringify([
991
+ conversionStyle,
992
+ replayContext,
993
+ shouldReplayResponsesItemIds,
994
+ inHistorySystemUpdates,
995
+ resolveResponsesInstructionRole(model),
996
+ model.input.includes("image"),
997
+ options?.retainUserProvenance === true
998
+ ]);
999
+ for (const msg of replayMessages) {
1000
+ if ("role" in msg && msg.role === "assistant" && replayPlan.itemRecovery && readOpenAIResponsesItemRecoveryAnchor(msg.providerReplay) === replayPlan.itemRecovery.anchor) pastRecoveryBoundary = true;
1001
+ if (!("role" in msg)) {
1002
+ messages.push(msg);
853
1003
  continue;
854
1004
  }
855
- if (replay?.type !== "openai-responses-compaction" && replay?.type !== "openai-responses-retained-compaction") {
856
- if (message.providerReplay?.type === "openai-responses-compaction" || message.providerReplay?.type === "openai-responses-retained-compaction") return;
857
- continue;
1005
+ recoveryAnchor = !pastRecoveryBoundary || msg.role === "toolResult" && recoveredCalls?.has(msg.toolCallId) ? replayPlan.itemRecovery?.anchor : void 0;
1006
+ if (recoveryAnchor && msg.role === "assistant") {
1007
+ for (const block of msg.content) if (block.type === "toolCall") recoveredCalls?.add(block.id);
858
1008
  }
859
- if (!providerReplayContextMatches(replay, context)) return;
860
- if (replay.compactedWindow !== void 0 || replay.type === "openai-responses-retained-compaction") {
861
- const output = readOpenAIResponsesCompactionWindow(replay, model);
862
- const item = output?.at(-1);
863
- if (!output || item?.type !== "compaction") return {
864
- owner: message,
865
- mode: "refresh-required"
866
- };
867
- return {
868
- owner: message,
869
- mode: "complete-window",
870
- output,
871
- ...replay.compactedWindow?.state === "ready" && replay.compactedWindow.outputTokens !== void 0 ? { outputTokens: replay.compactedWindow.outputTokens } : {},
872
- item,
873
- replayIndex: replay.type === "openai-responses-retained-compaction" ? message.content.length : replay.replayIndex ?? 0
874
- };
1009
+ const reusable = immutable && !preparedRequestSuffix.has(context) && immutable.isDeeplyFrozenPlainData(msg) && (typeof msg.content === "string" || !msg.content.some((block) => block.type === "image"));
1010
+ const key = recoveryAnchor ? `${projectionKey}:${msgIndex}:${recoveryAnchor}` : `${projectionKey}:${msgIndex}`;
1011
+ let projections = reusable ? responsesMessageProjections.get(msg) : void 0;
1012
+ let output = projections?.get(key);
1013
+ if (!output) {
1014
+ output = convertMessage(msg, msgIndex);
1015
+ if (reusable) {
1016
+ immutable.freezeJsonSnapshot(output);
1017
+ if (!projections) {
1018
+ projections = /* @__PURE__ */ new Map();
1019
+ responsesMessageProjections.set(msg, projections);
1020
+ }
1021
+ if (projections.size >= 8) {
1022
+ const oldest = projections.keys().next().value;
1023
+ if (oldest !== void 0) projections.delete(oldest);
1024
+ }
1025
+ projections.set(key, output);
1026
+ }
875
1027
  }
876
- return {
877
- owner: message,
878
- item: {
879
- type: "compaction",
880
- ...isSafeResponsesReplayItemId(replay.id) ? { id: replay.id } : {},
881
- encrypted_content: replay.data
882
- },
883
- mode: "compacted-prefix",
884
- replayIndex: replay.replayIndex ?? 0
885
- };
1028
+ if (reusable && options?.mutableInput) output = cloneResponsesInputForPayloadHook(output);
1029
+ if (msg.role === "assistant") appendAssistant(messages, output, msg);
1030
+ else messages.push(...output);
1031
+ if (output.length > 0 || !providerStyle) msgIndex += 1;
886
1032
  }
1033
+ return messages;
887
1034
  }
888
- var CompactionReplayRefreshRequiredError = class extends Error {
889
- constructor() {
890
- super("Provider compaction checkpoint needs rebuilding. Run /compact to rebuild from saved conversation history.");
891
- this.name = "CompactionReplayRefreshRequiredError";
892
- }
893
- };
894
- function buildOpenAIResponsesCompactionReplayPlan(messages, model, options) {
895
- if (options?.mode === "full-history") return {
896
- messages,
897
- preserveUnframedToolResults: false
898
- };
899
- const compaction = resolveNewestOpenAIResponsesCompactionReplay(messages, model, options);
900
- if (!compaction) return {
901
- messages,
902
- preserveUnframedToolResults: false
903
- };
904
- if (compaction.mode === "refresh-required") throw new CompactionReplayRefreshRequiredError();
905
- const ownerIndex = messages.indexOf(compaction.owner);
906
- return {
907
- messages: [{
908
- ...compaction.owner,
909
- content: compaction.owner.content.slice(compaction.replayIndex)
910
- }, ...messages.slice(ownerIndex + 1)],
911
- ...compaction.mode === "complete-window" ? { compactedWindow: compaction.output } : { compaction: compaction.item },
912
- preserveUnframedToolResults: true
913
- };
1035
+ function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
1036
+ return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "transport");
914
1037
  }
915
- function buildOpenAIResponsesReasoningReplayMetadata(model, options) {
1038
+ function convertProviderResponsesMessages(model, context, allowedToolCallProviders, options) {
1039
+ return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "provider");
1040
+ }
1041
+ //#endregion
1042
+ //#region packages/ai/src/transports/openai-responses-replay-internal.ts
1043
+ function isAsyncIterable(value) {
1044
+ return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
1045
+ }
1046
+ function isEmittedResponsesItem(item, failedSnapshot = false) {
1047
+ return isRecord(item) && item.type !== "compaction" && !(failedSnapshot && (item.type === "message" || item.type === "reasoning"));
1048
+ }
1049
+ function readResponsesRecoveryEvent(event) {
1050
+ const record = isRecord(event) ? event : void 0;
1051
+ const response = isRecord(record?.response) ? record.response : void 0;
916
1052
  return {
917
- v: 1,
918
- source: "openai-responses",
919
- ...buildProviderReplayContext(model, options)
1053
+ failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
1054
+ hasResponseOutput: Array.isArray(response?.output) && response.output.some((item) => isEmittedResponsesItem(item, record?.type === "response.failed")) || isEmittedResponsesItem(record?.item) || typeof record?.type === "string" && (record.type.endsWith(".delta") || record.type.includes("_call"))
920
1055
  };
921
1056
  }
922
- //#endregion
923
- //#region packages/ai/src/transports/openai-responses-reasoning-update.ts
924
- function isConfigurationUpdate(value) {
925
- return isRecord(value) && value.type === "configuration_update" && isRecord(value.reasoning) && typeof value.reasoning.effort === "string";
1057
+ function isInvalidEncryptedContentError(error) {
1058
+ if (!error || typeof error !== "object") return false;
1059
+ const record = error;
1060
+ if (record.code === "invalid_encrypted_content" || record.code === "thinking_signature_invalid") return true;
1061
+ const message = typeof record.message === "string" ? record.message.toLowerCase() : "";
1062
+ return message.includes("invalid_encrypted_content") || message.includes("thinking_signature_invalid") || (record.status === 400 || record.status == null && /(?:^|[\s(])400(?:[\s):]|$)/.test(message)) && (message.includes("could not decrypt the provided encrypted_content") || message.includes("encrypted content") && (message.includes("could not be verified") || message.includes("could not be decrypted or parsed")));
926
1063
  }
927
- function isResponsesReasoningUpdateCompatible(request) {
928
- const mode = isRecord(request.reasoning) ? request.reasoning.mode : void 0;
929
- return request.model === "gpt-6-astra" && (mode === void 0 || mode === "standard") && (!isRecord(request.multi_agent) || request.multi_agent.enabled !== true) && request.truncation !== "auto" && (!Array.isArray(request.context_management) || !request.context_management.some((item) => isRecord(item) && item.type === "compaction"));
1064
+ function isResponsesItemConflict(error) {
1065
+ return isRecord(error) && error.code === "item_conflict";
930
1066
  }
931
- function supportsResponsesReasoningUpdate(request) {
932
- return isResponsesReasoningUpdateCompatible(request) && isRecord(request.reasoning) && typeof request.reasoning.effort === "string";
1067
+ /** One repair budget and durable replay receipt shared by HTTP and WebSocket recovery. */
1068
+ function createResponsesItemConflictRecovery(output, model, options) {
1069
+ let anchor;
1070
+ let attempted = false;
1071
+ let applied = false;
1072
+ return {
1073
+ applied: () => {
1074
+ applied = true;
1075
+ },
1076
+ async retry(buildRequest) {
1077
+ if (anchor || options?.signal?.aborted) throw Object.assign(/* @__PURE__ */ new Error("Saved conversation items could not be recovered"), { code: "item_conflict" });
1078
+ anchor = globalThis.crypto.randomUUID();
1079
+ attempted = true;
1080
+ const request = await buildRequest({ itemRecovery: anchor });
1081
+ delete request.previous_response_id;
1082
+ suppressOpenAIResponsesCompaction(output, model, options, void 0, anchor);
1083
+ log.warn(`[responses] item_conflict_recovery sessionHash=${redactIdentifier(options?.sessionId)} outcome=started`);
1084
+ return request;
1085
+ },
1086
+ reject(error) {
1087
+ if (!anchor && isResponsesItemConflict(error)) {
1088
+ anchor = globalThis.crypto.randomUUID();
1089
+ suppressOpenAIResponsesCompaction(output, model, options, void 0, anchor);
1090
+ }
1091
+ },
1092
+ finish() {
1093
+ if (anchor || applied) {
1094
+ const outcome = anchor && !attempted ? "deferred" : output.stopReason === "error" || output.stopReason === "aborted" ? "failed" : "recovered";
1095
+ log.info(`[responses] item_conflict_recovery sessionHash=${redactIdentifier(options?.sessionId)} outcome=${outcome}`);
1096
+ }
1097
+ }
1098
+ };
933
1099
  }
934
- function canReferenceResponsesReasoningHistory(previous, request) {
935
- return !previous.input?.some(isConfigurationUpdate) || isResponsesReasoningUpdateCompatible(request);
1100
+ function isOrphanedFunctionCallOutputError(error) {
1101
+ if (!error || typeof error !== "object") return false;
1102
+ const record = error;
1103
+ const message = typeof record.message === "string" ? record.message : "";
1104
+ return /No tool call found for function call output with call_id [A-Za-z0-9_-]+/.test(message);
936
1105
  }
937
- /** Rehydrate input controls only provisionally; continuation must validate the full prefix. */
938
- function replayResponsesReasoningUpdates(previous, request, previousOutputLength, steering) {
939
- if (steering !== "required-input" && (!supportsResponsesReasoningUpdate(previous) || !supportsResponsesReasoningUpdate(request)) || !Array.isArray(previous.input) || !Array.isArray(request.input) || request.input.some(isConfigurationUpdate)) return request;
940
- const input = [...request.input];
941
- let activeEffort = isRecord(previous.reasoning) ? previous.reasoning.effort : void 0;
942
- for (const [index, item] of previous.input.entries()) if (isConfigurationUpdate(item)) {
943
- input.splice(index, 0, item);
944
- activeEffort = item.reasoning.effort;
945
- }
946
- if (steering === "required-input") return input.length === request.input.length ? request : {
1106
+ function commitResponsesEncryptedContentAttempt(attempt, commit) {
1107
+ if (attempt.kind === "compaction-stripped") commit(attempt.rejectedCompaction);
1108
+ }
1109
+ function stripResponsesRequestEncryptedReasoning(request) {
1110
+ const stripped = stripEncryptedReasoningContentFields(request.input);
1111
+ return stripped === request.input ? request : {
947
1112
  ...request,
948
- input
1113
+ input: stripped
949
1114
  };
950
- if (!isRecord(previous.reasoning) || !isRecord(request.reasoning) || typeof request.reasoning.effort !== "string") return request;
951
- if (activeEffort !== request.reasoning.effort && steering !== "automatic") {
952
- const baselineLength = previous.input.length + previousOutputLength;
953
- const nextUser = input.findIndex((item, index) => index >= baselineLength && "role" in item && item.role === "user");
954
- if (nextUser === -1) return request;
955
- input.splice(nextUser, 0, {
956
- type: "configuration_update",
957
- reasoning: { effort: request.reasoning.effort }
958
- });
959
- }
960
- if (input.length === request.input.length && activeEffort === request.reasoning.effort) return request;
961
- return {
1115
+ }
1116
+ function stripResponsesRequestCompaction(request) {
1117
+ if (!Array.isArray(request.input)) return request;
1118
+ const input = request.input.filter((item) => !(item !== null && typeof item === "object" && item.type === "compaction"));
1119
+ return input.length === request.input.length ? request : {
962
1120
  ...request,
963
- reasoning: {
964
- ...request.reasoning,
965
- effort: previous.reasoning.effort
966
- },
967
1121
  input
968
1122
  };
969
1123
  }
970
- //#endregion
971
- //#region packages/ai/src/transports/openai-responses-tool-call-id-shape.ts
972
- /**
973
- * Pure OpenAI Responses `call_*`/`fc_*` tool-call-id shape helpers.
974
- *
975
- * Moved out of embedded-agent-helpers/openai.ts (the AgentMessage[]-walking
976
- * caller lives in src/agents and imports from packages/ai, so the reverse
977
- * import direction is not available) so the continuation transport can
978
- * recognize its own cached raw ids after this same reshaping and restore
979
- * them on a replayed wire request -- see openai-responses-continuation.ts.
980
- */
981
- const OPENAI_RESPONSES_ID_MAX_LENGTH = 64;
982
- const OPENAI_RESPONSES_CALL_ID_RE = /^call_[A-Za-z0-9_-]{1,59}$/;
983
- const OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE = /^fc_[A-Za-z0-9_-]{1,61}$/;
984
- function splitOpenAIFunctionCallPairing(id) {
985
- const separator = id.indexOf("|");
986
- if (separator <= 0 || separator >= id.length - 1) return { callId: id };
1124
+ function readOpenAIResponsesCompactionRejection(request) {
1125
+ if (!Array.isArray(request.input)) return;
1126
+ const item = request.input.find((candidate) => candidate !== null && typeof candidate === "object" && candidate.type === "compaction" && typeof candidate.encrypted_content === "string");
1127
+ return item ? {
1128
+ data: item.encrypted_content,
1129
+ ...typeof item.id === "string" ? { id: item.id } : {}
1130
+ } : void 0;
1131
+ }
1132
+ async function resolveNextResponsesEncryptedContentAttempt(attempt, error, options) {
1133
+ if (isResponsesItemConflict(error)) return attempt.kind !== "items-reanchored" && options.buildItemConflictRequest ? {
1134
+ kind: "items-reanchored",
1135
+ request: await options.buildItemConflictRequest()
1136
+ } : void 0;
1137
+ const orphanedFunctionOutput = isOrphanedFunctionCallOutputError(error);
1138
+ if (!isInvalidEncryptedContentError(error) && !orphanedFunctionOutput || attempt.kind === "compaction-stripped") return;
1139
+ if (!orphanedFunctionOutput && (attempt.kind === "initial" || attempt.kind === "continuation-rejected")) {
1140
+ const reasoningStripped = stripResponsesRequestEncryptedReasoning(attempt.request);
1141
+ if (reasoningStripped !== attempt.request) return {
1142
+ kind: "reasoning-stripped",
1143
+ request: reasoningStripped
1144
+ };
1145
+ }
1146
+ if (stripResponsesRequestCompaction(attempt.request) === attempt.request) return;
1147
+ let compactionStripped = await options.buildFullHistoryRequest();
1148
+ compactionStripped = stripResponsesRequestCompaction(compactionStripped);
1149
+ if (attempt.kind === "reasoning-stripped") compactionStripped = stripResponsesRequestEncryptedReasoning(compactionStripped);
987
1150
  return {
988
- callId: id.slice(0, separator),
989
- itemId: id.slice(separator + 1)
1151
+ kind: "compaction-stripped",
1152
+ request: compactionStripped,
1153
+ rejectedCompaction: readOpenAIResponsesCompactionRejection(attempt.request)
990
1154
  };
991
1155
  }
992
- function normalizeOpenAIResponsesIdPart(value, prefix) {
993
- const trimmed = value.trim();
994
- if ((prefix === "call_" ? OPENAI_RESPONSES_CALL_ID_RE : OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE).test(trimmed)) return trimmed;
995
- const rawTail = trimmed.startsWith(prefix) ? trimmed.slice(prefix.length) : trimmed;
996
- const hash = sha256Hex(trimmed || prefix).slice(0, 10);
997
- const maxTailLength = 64 - prefix.length;
998
- const hashSuffix = `_${hash}`;
999
- return `${prefix}${`${rawTail.replace(/[^A-Za-z0-9_-]/g, "_").replace(/^_+|_+$/g, "").slice(0, Math.max(1, maxTailLength - hashSuffix.length)) || "id"}${hashSuffix}`.slice(0, maxTailLength)}`;
1000
- }
1001
- /** Same shaping `normalizeOpenAIResponsesToolCallIds` applies to a replayed `call_id`/`call_id|fc_id` pair. */
1002
- function normalizeOpenAIResponsesFunctionCallId(id) {
1003
- const { callId, itemId } = splitOpenAIFunctionCallPairing(id);
1004
- const normalizedCallId = normalizeOpenAIResponsesIdPart(itemId ? `${callId}|${itemId}` : callId, "call_");
1005
- if (!itemId) return normalizedCallId;
1006
- return `${normalizedCallId}|${normalizeOpenAIResponsesIdPart(itemId, "fc_")}`;
1007
- }
1008
- function shouldNormalizeOpenAIResponsesToolCallId(id) {
1009
- const pairing = splitOpenAIFunctionCallPairing(id);
1010
- if (!OPENAI_RESPONSES_CALL_ID_RE.test(pairing.callId)) return true;
1011
- if (pairing.itemId === void 0) return false;
1012
- return !OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE.test(pairing.itemId);
1013
- }
1014
- //#endregion
1015
- //#region packages/ai/src/transports/openai-responses-continuation.ts
1016
- const HTTP_CONTINUATION_IDLE_TTL_MS = 54e5;
1017
- const MAX_HTTP_CONTINUATION_READY_ENTRIES = 1e3;
1018
- const MAX_HTTP_CONTINUATION_RETAINED_BYTES = 67108864;
1019
- const TURN_HEADERS = /* @__PURE__ */ new Set([
1020
- "traceparent",
1021
- "x-openclaw-turn-id",
1022
- "x-openclaw-turn-attempt"
1023
- ]);
1024
- function projectJsonValue(value, key, ancestors) {
1025
- if (typeof value === "number") return Number.isFinite(value) ? value + 0 : null;
1026
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1027
- if (value === void 0 || typeof value === "symbol") return;
1028
- if (typeof value !== "object" || isProxy(value) || Object.getPrototypeOf(value) !== (Array.isArray(value) ? Array.prototype : Object.prototype) || "toJSON" in value || ancestors.has(value)) {
1029
- const projected = JSON.parse(JSON.stringify({
1030
- __proto__: null,
1031
- [key]: value
1032
- }));
1033
- return Object.hasOwn(projected, key) ? projected[key] : void 0;
1034
- }
1035
- ancestors.add(value);
1036
- try {
1037
- if (Array.isArray(value)) {
1038
- const result = [];
1039
- const length = value.length;
1040
- for (let index = 0; index < length; index++) result.push(projectJsonValue(value[index], String(index), ancestors) ?? null);
1041
- return result;
1156
+ async function createResponsesStreamWithRecovery(params) {
1157
+ async function* streamWithTerminalDrain(response, body) {
1158
+ const reader = body.getReader();
1159
+ let terminal = false;
1160
+ let firstFrame = true;
1161
+ const decoder = decodeSseFrames();
1162
+ try {
1163
+ frames: for (let next = decoder.next(); !next.done;) {
1164
+ if (next.value === void 0) {
1165
+ next = decoder.next(await reader.read());
1166
+ continue;
1167
+ }
1168
+ const { frame } = next.value;
1169
+ let eventName = null;
1170
+ let data;
1171
+ let start = 0;
1172
+ let cr = frame.indexOf("\r");
1173
+ let lf = frame.indexOf("\n");
1174
+ while (start < frame.length) {
1175
+ const end = cr < 0 ? lf < 0 ? frame.length : lf : lf < 0 ? cr : Math.min(cr, lf);
1176
+ const lineStart = !(firstFrame && start === 0) && frame.charCodeAt(start) === 65279 ? start + 1 : start;
1177
+ start = end + (frame[end] === "\r" && frame[end + 1] === "\n" ? 2 : 1);
1178
+ if (cr >= 0 && cr < start) cr = frame.indexOf("\r", start);
1179
+ if (lf >= 0 && lf < start) lf = frame.indexOf("\n", start);
1180
+ if (lineStart < end) {
1181
+ const fieldLength = frame.startsWith("data", lineStart) ? 4 : frame.startsWith("event", lineStart) ? 5 : 0;
1182
+ const colon = lineStart + fieldLength;
1183
+ if (fieldLength && (colon === end || frame[colon] === ":")) {
1184
+ const value = colon === end ? "" : frame.slice(colon + (frame[colon + 1] === " " ? 2 : 1), end);
1185
+ if (fieldLength === 5) eventName = value;
1186
+ else data = data === void 0 ? value : `${data}\n${value}`;
1187
+ }
1188
+ if (start < frame.length) continue;
1189
+ }
1190
+ if (!eventName && data === void 0) continue;
1191
+ if (data === "[DONE]") break frames;
1192
+ let event;
1193
+ try {
1194
+ event = JSON.parse(data ?? "");
1195
+ } catch {
1196
+ throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
1197
+ }
1198
+ if (eventName?.startsWith("thread.")) event = {
1199
+ event: eventName,
1200
+ data: event
1201
+ };
1202
+ else if (eventName === "error" || isRecord(event) && event.error) throw new APIError(void 0, isRecord(event) ? event.error ?? event : event, void 0, response.headers);
1203
+ terminal ||= isRecord(event) && (event.type === "response.completed" || event.type === "response.incomplete");
1204
+ yield event;
1205
+ eventName = null;
1206
+ data = void 0;
1207
+ }
1208
+ firstFrame = false;
1209
+ next = decoder.next();
1210
+ }
1211
+ } catch (error) {
1212
+ if (error instanceof APIError || !isRecord(error) || error.name !== "AbortError" && !String(error.message).includes("FetchRequestCanceledException")) throw error;
1213
+ } finally {
1214
+ if (!terminal) {
1215
+ await reader.cancel().catch(() => void 0);
1216
+ reader.releaseLock();
1217
+ } else {
1218
+ const controller = new AbortController();
1219
+ const unregister = registerSessionResourceCleanup((sessionId) => {
1220
+ if (!sessionId) controller.abort();
1221
+ });
1222
+ const signal = AbortSignal.any([
1223
+ controller.signal,
1224
+ AbortSignal.timeout(250),
1225
+ ...params.requestOptions?.signal ? [params.requestOptions.signal] : []
1226
+ ]);
1227
+ const cancel = () => {
1228
+ reader.cancel().catch(() => void 0);
1229
+ };
1230
+ signal.addEventListener("abort", cancel, { once: true });
1231
+ (async () => {
1232
+ try {
1233
+ let bytes = 0;
1234
+ while (!signal.aborted && bytes < 65536) {
1235
+ const { done, value } = await reader.read();
1236
+ if (done) break;
1237
+ bytes += value.byteLength;
1238
+ }
1239
+ } catch {} finally {
1240
+ cancel();
1241
+ reader.releaseLock();
1242
+ signal.removeEventListener("abort", cancel);
1243
+ unregister();
1244
+ }
1245
+ })();
1246
+ }
1042
1247
  }
1043
- const result = {};
1044
- for (const name of Object.keys(value)) {
1045
- const member = projectJsonValue(Reflect.get(value, name), name, ancestors);
1046
- if (member !== void 0) {
1047
- if (name in result) Object.defineProperty(result, name, {
1048
- value: member,
1049
- enumerable: true,
1050
- configurable: true,
1051
- writable: true
1248
+ }
1249
+ const encodeBody = params.encodeBody ?? prepareModelRequestBody(void 0);
1250
+ let tierCeiling;
1251
+ const limitTier = (request) => tierCeiling && (request.service_tier === "ultrafast" || tierCeiling === "default" && request.service_tier === "priority") ? {
1252
+ ...request,
1253
+ service_tier: tierCeiling
1254
+ } : request;
1255
+ const recoverServiceTier = (attempt, error) => {
1256
+ if (params.requestOptions?.signal?.aborted || !supportsNativeOpenAIResponsesEndpoint(params.model)) return;
1257
+ const tier = attempt.request.service_tier;
1258
+ const next = nextResponsesServiceTier(tier, error);
1259
+ if (!next || tier !== "ultrafast" && tier !== "priority") return;
1260
+ tierCeiling = next;
1261
+ params.onServiceTierRejected?.(tier);
1262
+ log.info(`[responses] rejected ${tier} tier; retrying with ${next}`);
1263
+ return {
1264
+ ...attempt,
1265
+ request: {
1266
+ ...attempt.request,
1267
+ service_tier: next
1268
+ }
1269
+ };
1270
+ };
1271
+ const send = async (initialAttempt) => {
1272
+ let attempt = initialAttempt;
1273
+ for (;;) {
1274
+ const cappedRequest = limitTier(attempt.request);
1275
+ if (cappedRequest !== attempt.request) attempt = {
1276
+ kind: attempt.kind,
1277
+ request: cappedRequest,
1278
+ rejectedCompaction: attempt.rejectedCompaction
1279
+ };
1280
+ params.observePrompt?.(attempt.request, {
1281
+ egress: "responses-sdk",
1282
+ payloadVariant: attempt.kind
1283
+ });
1284
+ const bodyOptions = await encodeBody(attempt.request);
1285
+ let responseAccepted = false;
1286
+ try {
1287
+ const { data, response } = await params.client.responses.create(attempt.request, {
1288
+ ...params.requestOptions,
1289
+ ...bodyOptions,
1290
+ headers: {
1291
+ ...bodyOptions.headers,
1292
+ ...params.requestOptions?.headers
1293
+ }
1294
+ }).withResponse();
1295
+ responseAccepted = true;
1296
+ commitResponsesEncryptedContentAttempt(attempt, (checkpoint) => {
1297
+ if (checkpoint) params.onCompactionRejected?.(checkpoint);
1052
1298
  });
1053
- else result[name] = member;
1299
+ if (!isAsyncIterable(data)) throw new Error("OpenAI Responses streaming request returned a non-stream response");
1300
+ return {
1301
+ stream: data instanceof Stream && response.body ? streamWithTerminalDrain(response, response.body) : data,
1302
+ response,
1303
+ attempt
1304
+ };
1305
+ } catch (error) {
1306
+ let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, {
1307
+ buildFullHistoryRequest: params.buildFullHistoryRequest,
1308
+ buildItemConflictRequest: params.buildItemConflictRequest
1309
+ });
1310
+ if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
1311
+ const request = { ...await params.buildFullHistoryRequest() };
1312
+ delete request.previous_response_id;
1313
+ nextAttempt = {
1314
+ kind: "continuation-rejected",
1315
+ request
1316
+ };
1317
+ }
1318
+ if (!nextAttempt) throw error;
1319
+ const retryDescription = nextAttempt.request.service_tier !== attempt.request.service_tier ? "with a slower service tier" : nextAttempt.kind === "reasoning-stripped" ? "without encrypted reasoning content" : nextAttempt.kind === "compaction-stripped" ? "without encrypted compaction content" : nextAttempt.kind === "items-reanchored" ? "with reanchored conversation items" : "full history after rejected previous_response_id";
1320
+ log.warn(`[responses] retrying ${retryDescription} provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
1321
+ attempt = nextAttempt;
1322
+ }
1323
+ }
1324
+ };
1325
+ const result = await send({
1326
+ kind: params.initialAttemptKind ?? "initial",
1327
+ request: params.request,
1328
+ ...params.initialRejectedCompaction ? { rejectedCompaction: params.initialRejectedCompaction } : {}
1329
+ });
1330
+ return { stream: { async *[Symbol.asyncIterator]() {
1331
+ let current = result;
1332
+ let outputObserved = false;
1333
+ for (;;) {
1334
+ let rejectedEvent;
1335
+ let sourceError;
1336
+ const source = current.stream;
1337
+ const providerStream = { async *[Symbol.asyncIterator]() {
1338
+ try {
1339
+ yield* source;
1340
+ } catch (error) {
1341
+ sourceError = error;
1342
+ throw error;
1343
+ }
1344
+ } };
1345
+ try {
1346
+ for await (const event of params.wrapStream?.({
1347
+ ...current,
1348
+ stream: providerStream
1349
+ }) ?? providerStream) {
1350
+ const { failure, hasResponseOutput } = readResponsesRecoveryEvent(event);
1351
+ outputObserved ||= hasResponseOutput;
1352
+ if (isRecord(failure) && params.canRetryStream?.() === true && (isInvalidEncryptedContentError(failure) || !outputObserved && isResponsesItemConflict(failure) || !outputObserved && isResponsesServiceTierRejection(failure))) {
1353
+ rejectedEvent = event;
1354
+ const message = typeof failure.message === "string" ? failure.message : "";
1355
+ throw Object.assign(new Error(message), {
1356
+ code: failure.code,
1357
+ status: failure.status,
1358
+ type: failure.type,
1359
+ param: failure.param
1360
+ });
1361
+ }
1362
+ yield event;
1363
+ }
1364
+ return;
1365
+ } catch (error) {
1366
+ const nextAttempt = params.canRetryStream?.() === true && !params.requestOptions?.signal?.aborted ? (!outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? recoverServiceTier(current.attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(current.attempt, error, {
1367
+ buildFullHistoryRequest: params.buildFullHistoryRequest,
1368
+ buildItemConflictRequest: !outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? params.buildItemConflictRequest : void 0
1369
+ }) : void 0;
1370
+ if (!nextAttempt) {
1371
+ if (rejectedEvent !== void 0) {
1372
+ yield rejectedEvent;
1373
+ return;
1374
+ }
1375
+ throw error;
1376
+ }
1377
+ log.warn(`[responses] retrying explicitly rejected stream provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
1378
+ current = await send(nextAttempt);
1054
1379
  }
1055
1380
  }
1056
- return result;
1057
- } finally {
1058
- ancestors.delete(value);
1059
- }
1381
+ } } };
1060
1382
  }
1061
- function projectJsonObject(value) {
1062
- const projected = projectJsonValue(value, "", /* @__PURE__ */ new Set());
1063
- return projected === void 0 ? JSON.parse("undefined") : projected;
1383
+ function resolveAzureOpenAIApiVersion(env = process.env) {
1384
+ return env.AZURE_OPENAI_API_VERSION?.trim() || "preview";
1064
1385
  }
1065
- function jsonValuesEqual(left, right) {
1066
- return isDeepStrictEqual(projectJsonObject(left), projectJsonObject(right));
1386
+ //#endregion
1387
+ //#region packages/ai/src/transports/openai-transport-params.ts
1388
+ const MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS = 256;
1389
+ const loggedOpenAIStrictToolDowngradeDiagnosticKeys = /* @__PURE__ */ new Set();
1390
+ const OPENAI_COMPLETIONS_APIS = /* @__PURE__ */ new Set(["openai-completions", "openclaw-openai-completions-transport"]);
1391
+ function readToolPayloadField(record, field) {
1392
+ try {
1393
+ return Object.hasOwn(record, field) ? record[field] : void 0;
1394
+ } catch {
1395
+ return;
1396
+ }
1067
1397
  }
1068
- function requestWithoutInput(request) {
1069
- const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
1070
- if (!isRecord(rest.metadata)) return rest;
1071
- const metadata = Object.fromEntries(Object.entries(rest.metadata).filter(([key]) => key !== "openclaw_turn_id" && key !== "openclaw_turn_attempt"));
1072
- return {
1073
- ...rest,
1074
- metadata
1075
- };
1398
+ function readCodeModePayloadToolName(tool) {
1399
+ if (!isRecord(tool)) return;
1400
+ const name = readToolPayloadField(tool, "name");
1401
+ if (typeof name === "string") return name;
1402
+ const fn = readToolPayloadField(tool, "function");
1403
+ if (!isRecord(fn)) return;
1404
+ const fnName = readToolPayloadField(fn, "name");
1405
+ return typeof fnName === "string" ? fnName : void 0;
1076
1406
  }
1077
- function canonicalizeToolCallId(callId, itemId) {
1078
- if (typeof callId !== "string") return callId;
1079
- const paired = typeof itemId === "string" && itemId ? `${callId}|${itemId}` : callId;
1080
- if (!shouldNormalizeOpenAIResponsesToolCallId(paired)) return callId;
1081
- return splitOpenAIFunctionCallPairing(normalizeOpenAIResponsesFunctionCallId(paired)).callId;
1407
+ function readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes) {
1408
+ if (!isRecord(tool)) return;
1409
+ const type = readToolPayloadField(tool, "type");
1410
+ if (typeof type === "string" && allowedHostedToolTypes?.has(type)) {
1411
+ try {
1412
+ if (Object.hasOwn(tool, "name") || Object.hasOwn(tool, "function") || Object.hasOwn(tool, "functionDeclarations") || Object.hasOwn(tool, "function_declarations")) return false;
1413
+ } catch {
1414
+ return false;
1415
+ }
1416
+ return `hosted:${type}`;
1417
+ }
1418
+ const name = readCodeModePayloadToolName(tool);
1419
+ return typeof name === "string" && isCodeModeModelVisibleToolName(name, visibleToolNames) ? `client:${name}` : void 0;
1082
1420
  }
1083
- function responseToolCalls(items) {
1084
- return items.flatMap((item) => {
1085
- if (!isRecord(item) || item.type !== "function_call" || typeof item.call_id !== "string") return [];
1086
- return [{
1087
- callId: item.call_id,
1088
- ...typeof item.id === "string" ? { itemId: item.id } : {}
1089
- }];
1421
+ function readCodeModePayloadToolIdentities(payload) {
1422
+ if (!isRecord(payload)) return [];
1423
+ const tools = readToolPayloadField(payload, "tools");
1424
+ if (!Array.isArray(tools)) return [];
1425
+ return tools.flatMap((tool) => {
1426
+ if (!isRecord(tool)) return [];
1427
+ const identities = [];
1428
+ const name = readCodeModePayloadToolName(tool);
1429
+ if (name) identities.push(`client:${name}`);
1430
+ for (const key of ["functionDeclarations", "function_declarations"]) {
1431
+ const declarations = readToolPayloadField(tool, key);
1432
+ if (!Array.isArray(declarations)) continue;
1433
+ for (const declaration of declarations) {
1434
+ const declarationName = readCodeModePayloadToolName(declaration);
1435
+ if (declarationName) identities.push(`client:${declarationName}`);
1436
+ }
1437
+ }
1438
+ const type = readToolPayloadField(tool, "type");
1439
+ if (typeof type === "string" && type !== "function") identities.push(`hosted:${type}`);
1440
+ return identities;
1090
1441
  });
1091
1442
  }
1092
- function toolCallReplayShapes(call) {
1093
- return new Set([
1094
- call.callId,
1095
- canonicalizeToolCallId(call.callId, call.itemId),
1096
- canonicalizeToolCallId(call.callId, void 0)
1097
- ].filter((shape) => typeof shape === "string"));
1443
+ function filterCodeModePayloadTools(payload, visibleToolNames, allowedHostedToolTypes, observer) {
1444
+ if (!isRecord(payload)) return;
1445
+ const tools = readToolPayloadField(payload, "tools");
1446
+ if (!Array.isArray(tools)) return;
1447
+ const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
1448
+ payload.tools = tools.flatMap((tool) => {
1449
+ const identity = readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes);
1450
+ if (identity) return [tool];
1451
+ if (identity === false) return [];
1452
+ if (!isRecord(tool)) return [];
1453
+ const filteredGroups = {};
1454
+ for (const key of ["functionDeclarations", "function_declarations"]) {
1455
+ const declarations = readToolPayloadField(tool, key);
1456
+ if (!Array.isArray(declarations)) continue;
1457
+ const filtered = declarations.filter((declaration) => {
1458
+ const declarationName = readCodeModePayloadToolName(declaration);
1459
+ return typeof declarationName === "string" && isCodeModeModelVisibleToolName(declarationName, visibleToolNames);
1460
+ });
1461
+ if (filtered.length > 0) filteredGroups[key] = filtered;
1462
+ }
1463
+ return Object.keys(filteredGroups).length > 0 ? [filteredGroups] : [];
1464
+ });
1465
+ if (beforeToolIdentities) observer?.({
1466
+ beforeToolIdentities,
1467
+ afterToolIdentities: readCodeModePayloadToolIdentities(payload)
1468
+ });
1098
1469
  }
1099
- function toolCallOwnerByReplayShape(calls) {
1100
- const ownerByReplayShape = /* @__PURE__ */ new Map();
1101
- for (const [index, call] of calls.entries()) for (const replayShape of toolCallReplayShapes(call)) {
1102
- const owner = ownerByReplayShape.get(replayShape);
1103
- ownerByReplayShape.set(replayShape, owner === void 0 || owner === index ? index : null);
1104
- }
1105
- return ownerByReplayShape;
1470
+ function resolveCodeModeResponsesVisibleToolNames(context) {
1471
+ return new Set((context.tools ?? []).map(readCodeModePayloadToolName).filter((name) => typeof name === "string"));
1106
1472
  }
1107
- function recordResponsesContinuationState(previous, lastRequest, response, continued = false) {
1108
- const calls = previous && continued ? [...previous.pendingToolCalls ?? [], ...responseToolCalls(previous.lastResponseItems)] : responseToolCalls(lastRequest.input ?? []);
1109
- const seenCalls = /* @__PURE__ */ new Set();
1110
- const uniqueCalls = calls.filter((call) => {
1111
- const key = JSON.stringify([call.callId, call.itemId]);
1112
- if (seenCalls.has(key)) return false;
1113
- seenCalls.add(key);
1114
- return true;
1115
- });
1116
- const input = lastRequest.input ?? [];
1117
- const ownerByReplayShape = toolCallOwnerByReplayShape(uniqueCalls);
1118
- const replayedCallIds = /* @__PURE__ */ new Set();
1119
- const lastCallPosition = /* @__PURE__ */ new Map();
1120
- const lastOutputPosition = /* @__PURE__ */ new Map();
1121
- for (const [inputIndex, item] of input.entries()) {
1122
- if (!isRecord(item) || typeof item.call_id !== "string") continue;
1123
- const owner = ownerByReplayShape.get(item.call_id);
1124
- if (item.type === "function_call") replayedCallIds.add(item.call_id);
1125
- const positions = item.type === "function_call" ? lastCallPosition : item.type === "function_call_output" ? lastOutputPosition : void 0;
1126
- if (positions && owner !== void 0 && owner !== null) positions.set(owner, inputIndex);
1127
- }
1128
- const pendingToolCalls = uniqueCalls.filter((_call, index) => {
1129
- const callPosition = lastCallPosition.get(index);
1130
- return [...toolCallReplayShapes(_call)].some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
1473
+ function enforceCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes, observer) {
1474
+ if (!isRecord(payload)) return;
1475
+ const tools = readToolPayloadField(payload, "tools");
1476
+ if (!Array.isArray(tools)) return;
1477
+ const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
1478
+ payload.tools = tools.filter((tool) => Boolean(readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes)));
1479
+ if (beforeToolIdentities) observer?.({
1480
+ beforeToolIdentities,
1481
+ afterToolIdentities: readCodeModePayloadToolIdentities(payload)
1131
1482
  });
1132
- return {
1133
- lastRequest,
1134
- lastResponseId: response.id,
1135
- lastResponseItems: response.output.filter((item) => item.type !== "web_search_call"),
1136
- pendingToolCalls
1137
- };
1138
1483
  }
1139
- function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCachedItemIds = false) {
1140
- return input.map((item) => {
1141
- if (!isRecord(item)) return item;
1142
- if (item.type === "reasoning") return { type: "reasoning" };
1143
- if (item.type !== "function_call" && item.type !== "function_call_output" && !(item.type === "message" && item.role === "assistant")) return item;
1144
- const { id: rawId, status: _status, ...stableItem } = item;
1145
- if (item.type === "function_call_output") {
1146
- if ("id" in item) stableItem.id = item.id;
1147
- if ("status" in item) stableItem.status = item.status;
1148
- }
1149
- if ("call_id" in stableItem) {
1150
- const itemId = item.type === "function_call" && !(fromResponse && ignoreCachedItemIds) ? rawId : void 0;
1151
- stableItem.call_id = canonicalizeToolCallId(stableItem.call_id, itemId);
1152
- }
1153
- if (fromResponse && item.type === "function_call") {
1154
- const args = parseJsonObjectPreservingUnsafeIntegers(stableItem.arguments);
1155
- stableItem.arguments = args ? JSON.stringify(args) : stableItem.arguments;
1156
- }
1157
- if (item.type === "message" && Array.isArray(stableItem.content)) stableItem.content = stableItem.content.map((part) => {
1158
- if (!isRecord(part) || part.type !== "output_text") return part;
1159
- const { annotations: _annotations, logprobs: _logprobs, ...stablePart } = part;
1160
- return stablePart;
1161
- });
1162
- return stableItem;
1484
+ function assertCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes) {
1485
+ const tools = isRecord(payload) ? readToolPayloadField(payload, "tools") : void 0;
1486
+ if (!Array.isArray(tools)) throw new Error("Code mode payload tool surface violation: expected exec,wait; got no tools");
1487
+ const identities = tools.map((tool) => readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes));
1488
+ const names = identities.flatMap((identity) => typeof identity === "string" && identity.startsWith("client:") ? [identity.slice(7)] : []).toSorted((left, right) => left.localeCompare(right));
1489
+ if (names.length >= 2 && identities.every((identity) => typeof identity === "string") && new Set(identities).size === identities.length && names.includes("exec") && names.includes("wait")) return;
1490
+ throw new Error(`Code mode payload tool surface violation: expected exec,wait plus direct-only tools; got ${names.length > 0 ? names.join(",") : "none"}`);
1491
+ }
1492
+ function resolveOpenAIStrictToolFlagWithDiagnostics(projection, strictSetting, context) {
1493
+ const strict = resolveOpenAIProjectedToolsStrictToolFlag(projection, strictSetting);
1494
+ if (strictSetting === true && strict === false) getAiTransportHost().logDebug("openai-transport", () => {
1495
+ const diagnostics = findOpenAIStrictToolProjectionDiagnostics(projection);
1496
+ const key = sha256Hex(JSON.stringify({
1497
+ transport: context.transport,
1498
+ provider: context.model.provider ?? null,
1499
+ model: context.model.id ?? null,
1500
+ diagnostics: diagnostics.map((entry) => ({
1501
+ toolIndex: entry.toolIndex,
1502
+ toolName: entry.toolName ?? null,
1503
+ violations: entry.violations
1504
+ }))
1505
+ }));
1506
+ if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.has(key)) return null;
1507
+ if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.size >= MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS) loggedOpenAIStrictToolDowngradeDiagnosticKeys.clear();
1508
+ loggedOpenAIStrictToolDowngradeDiagnosticKeys.add(key);
1509
+ const sample = diagnostics.slice(0, 5).map((entry) => ({
1510
+ tool: entry.toolName ?? `tool[${entry.toolIndex}]`,
1511
+ violations: entry.violations.slice(0, 8)
1512
+ }));
1513
+ return {
1514
+ message: `OpenAI ${context.transport} tool schema strict mode downgraded to strict=false for ${context.model.provider ?? "unknown"}/${context.model.id ?? "unknown"} because ${diagnostics.length} tool schema(s) are not strict-compatible`,
1515
+ data: {
1516
+ transport: context.transport,
1517
+ provider: context.model.provider,
1518
+ model: context.model.id,
1519
+ incompatibleToolCount: diagnostics.length,
1520
+ sample
1521
+ }
1522
+ };
1163
1523
  });
1524
+ return strict;
1164
1525
  }
1165
- function normalizeContinuationHistory(input) {
1166
- const normalized = normalizeAssistantReplayInput(input);
1167
- const ownerByReplayShape = toolCallOwnerByReplayShape(responseToolCalls(input));
1168
- let callIndex = 0;
1169
- for (const [index, item] of input.entries()) {
1170
- const normalizedItem = normalized[index];
1171
- if (!isRecord(item) || !isRecord(normalizedItem)) continue;
1172
- if (item.type === "function_call") {
1173
- if (typeof normalizedItem.call_id !== "string") return;
1174
- const callOwner = ownerByReplayShape.get(normalizedItem.call_id);
1175
- if (callOwner !== callIndex) return;
1176
- normalizedItem.call_id = { callOwner };
1177
- callIndex += 1;
1178
- continue;
1526
+ function buildOpenAIClientHeaders(model, context, optionHeaders, turnHeaders, sessionId, cacheRetention) {
1527
+ const providerHeaders = { ...model.headers };
1528
+ if (model.provider === "github-copilot") Object.assign(providerHeaders, getAiTransportHost().buildCopilotDynamicHeaders(context.messages));
1529
+ if (OPENAI_COMPLETIONS_APIS.has(model.api) && sessionId && cacheRetention !== "none") {
1530
+ const { sessionAffinity } = resolveOpenAICompletionsCompat(model);
1531
+ if (sessionAffinity !== "none") {
1532
+ const affinityValue = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
1533
+ const affinityHeaders = sessionAffinity === "openrouter" ? ["x-session-id"] : [
1534
+ "session_id",
1535
+ "x-client-request-id",
1536
+ "x-session-affinity"
1537
+ ];
1538
+ const configuredHeaders = new Set(Object.keys(providerHeaders).map((key) => key.toLowerCase()));
1539
+ for (const name of affinityHeaders) if (!configuredHeaders.has(name)) providerHeaders[name] = affinityValue;
1179
1540
  }
1180
- if (item.type !== "function_call_output" || typeof item.call_id !== "string") continue;
1181
- const owner = ownerByReplayShape.get(item.call_id);
1182
- if (owner === null) return;
1183
- normalizedItem.call_id = owner === void 0 ? { unknownCallId: canonicalizeToolCallId(item.call_id, void 0) } : { callOwner: owner };
1184
1541
  }
1185
- return normalized;
1186
- }
1187
- function responsesContinuationRequestFingerprint(request) {
1188
- return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
1189
- }
1190
- function responsesContinuationPrefixFingerprint(input, output = []) {
1191
- return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true)])).digest;
1192
- }
1193
- function resolveResponsesContinuationRequest(continuation, request, steering) {
1194
- if (!continuation) return {
1195
- request,
1196
- continuationStatus: "no_previous_response"
1197
- };
1198
- if (request.previous_response_id) return {
1199
- request,
1200
- continuationStatus: "explicit_previous_response_id"
1542
+ const callerHeaders = {
1543
+ ...optionHeaders,
1544
+ ...turnHeaders
1201
1545
  };
1202
- if (!canReferenceResponsesReasoningHistory(continuation.lastRequest, request)) return {
1203
- request,
1204
- continuationStatus: "request_changed"
1546
+ const resolvedHeaders = getAiTransportHost().resolveProviderRequestHeaders({
1547
+ provider: model.provider,
1548
+ api: model.api,
1549
+ baseUrl: model.baseUrl,
1550
+ providerHeaders,
1551
+ callerHeaders: Object.keys(callerHeaders).length > 0 ? callerHeaders : void 0,
1552
+ precedence: "caller-wins",
1553
+ model
1554
+ }) ?? {};
1555
+ const sendSessionIdHeader = (OPENAI_RESPONSES_APIS.has(model.api) && model.compat && "sendSessionIdHeader" in model.compat ? model.compat?.sendSessionIdHeader : void 0) ?? usesNativeOpenAICodexResponsesBackend(model);
1556
+ if (sessionId && cacheRetention !== "none" && sendSessionIdHeader && !Object.keys(resolvedHeaders).some((key) => normalizeLowercaseStringOrEmpty(key) === "session_id")) resolvedHeaders.session_id = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
1557
+ return resolveOpencodeSessionHeaders(model, {
1558
+ sessionId,
1559
+ headers: resolvedHeaders
1560
+ }) ?? resolvedHeaders;
1561
+ }
1562
+ function buildOpenAISdkClientOptions(model) {
1563
+ const timeout = resolveModelRequestTimeoutMs(model);
1564
+ return {
1565
+ ...timeout === void 0 ? {} : { timeout },
1566
+ maxRetries: 0
1205
1567
  };
1206
- const prepared = replayResponsesReasoningUpdates(continuation.lastRequest, request, continuation.lastResponseItems.length, steering);
1207
- if (steering !== "required-input" && !jsonValuesEqual(requestWithoutInput(prepared), requestWithoutInput(continuation.lastRequest))) return {
1208
- request,
1209
- continuationStatus: "request_changed"
1568
+ }
1569
+ function buildOpenAISdkRequestOptions(model, signal, options) {
1570
+ const timeout = resolveModelRequestTimeoutMs(model, options?.timeoutMs);
1571
+ const headers = options?.stream === true && usesNativeOpenAICodexResponsesBackend(model) ? { Accept: "text/event-stream" } : void 0;
1572
+ if (timeout === void 0 && !signal && !headers) return;
1573
+ return {
1574
+ ...headers ? { headers } : {},
1575
+ ...signal ? { signal } : {},
1576
+ ...timeout !== void 0 ? { timeout } : {},
1577
+ maxRetries: 0
1210
1578
  };
1211
- const currentInput = prepared.input ?? [];
1212
- const previousInput = continuation.lastRequest.input ?? [];
1213
- const baselineLength = previousInput.length + continuation.lastResponseItems.length;
1214
- if (currentInput.length < baselineLength) return {
1215
- request,
1216
- continuationStatus: "history_shorter"
1579
+ }
1580
+ function getCompat(model) {
1581
+ const resolved = resolveOpenAICompletionsCompat(model);
1582
+ const compat = model.compat ?? {};
1583
+ return {
1584
+ ...resolved,
1585
+ reasoningEffortMap: resolveOpenAIReasoningEffortMap(model, {}),
1586
+ openRouterRouting: resolved.openRouterRouting ?? {},
1587
+ requiresStringContent: compat.requiresStringContent ?? false,
1588
+ strictMessageKeys: compat.strictMessageKeys === true
1217
1589
  };
1218
- const replayedToolRoundInput = currentInput.slice(previousInput.length, baselineLength);
1219
- const replayedToolRound = normalizeAssistantReplayInput(replayedToolRoundInput);
1220
- const historyToolRoundUnchanged = [false, true].some((ignoreCachedItemIds) => jsonValuesEqual(replayedToolRound, normalizeAssistantReplayInput(continuation.lastResponseItems, true, ignoreCachedItemIds)));
1221
- const historyCurrentInput = currentInput.slice(0, previousInput.length);
1222
- for (const [index, previousItem] of previousInput.entries()) {
1223
- const currentItem = historyCurrentInput[index];
1224
- if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
1225
- if (previousItem.type === "function_call" && currentItem.type === "function_call") {
1226
- if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
1227
- callId: previousItem.call_id,
1228
- ...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
1229
- }).has(currentItem.call_id)) return {
1230
- request,
1231
- continuationStatus: "history_changed"
1232
- };
1233
- }
1234
- if (previousItem.type === "function_call_output" && currentItem.type === "function_call_output" && typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && currentItem.call_id !== previousItem.call_id && currentItem.call_id !== canonicalizeToolCallId(previousItem.call_id, void 0)) return {
1235
- request,
1236
- continuationStatus: "history_changed"
1237
- };
1238
- }
1239
- const normalizedPrevious = normalizeContinuationHistory(previousInput);
1240
- const normalizedCurrent = normalizeContinuationHistory(historyCurrentInput);
1241
- if (!(normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious)) || !historyToolRoundUnchanged) return {
1242
- request,
1243
- continuationStatus: "history_changed"
1590
+ }
1591
+ //#endregion
1592
+ //#region packages/ai/src/providers/openai-tool-projection.ts
1593
+ function unreadableToolDiagnostic(toolIndex) {
1594
+ return {
1595
+ toolIndex,
1596
+ violations: [`tool[${toolIndex}] is unreadable`]
1244
1597
  };
1245
- const delta = currentInput.slice(baselineLength);
1246
- const cachedResponseItems = continuation.lastResponseItems;
1247
- const pendingToolCalls = continuation.pendingToolCalls ?? [];
1248
- const currentResponseCalls = responseToolCalls(cachedResponseItems);
1249
- const replayedCalls = replayedToolRoundInput.filter((item) => isRecord(item) && item.type === "function_call");
1250
- if (currentResponseCalls.length !== replayedCalls.length) return {
1251
- request,
1252
- continuationStatus: "history_changed"
1598
+ }
1599
+ /** Snapshots direct/custom tool descriptors before OpenAI payload construction. */
1600
+ function projectOpenAITools(tools) {
1601
+ return projectOpenAIToolDescriptors(tools);
1602
+ }
1603
+ /** Package-private facts are consumed before the projection or payload can escape. */
1604
+ function prepareOpenAITools(tools) {
1605
+ const schemas = /* @__PURE__ */ new Map();
1606
+ return {
1607
+ projection: projectOpenAIToolDescriptors(tools, schemas),
1608
+ schemas
1253
1609
  };
1254
- const cachedCalls = [...pendingToolCalls, ...currentResponseCalls];
1255
- const currentCallOffset = pendingToolCalls.length;
1256
- const ownerByReplayShape = toolCallOwnerByReplayShape(cachedCalls);
1257
- for (const index of currentResponseCalls.keys()) {
1258
- const replayedCallId = replayedCalls[index]?.call_id;
1259
- if (typeof replayedCallId !== "string" || ownerByReplayShape.get(replayedCallId) !== currentCallOffset + index) return {
1260
- request,
1261
- continuationStatus: "history_changed"
1610
+ }
1611
+ function projectOpenAIToolDescriptors(tools, schemas) {
1612
+ let inputToolCount;
1613
+ try {
1614
+ inputToolCount = tools.length;
1615
+ } catch {
1616
+ return {
1617
+ inputToolCount: 0,
1618
+ tools: [],
1619
+ diagnostics: [unreadableToolDiagnostic(0)]
1262
1620
  };
1263
1621
  }
1264
- const restoredInput = [];
1265
- for (const item of delta) {
1266
- if (!isRecord(item) || item.type !== "function_call_output" || typeof item.call_id !== "string") {
1267
- restoredInput.push(item);
1622
+ const projectedTools = [];
1623
+ const diagnostics = [];
1624
+ for (let toolIndex = 0; toolIndex < inputToolCount; toolIndex += 1) {
1625
+ let tool;
1626
+ let name;
1627
+ let parameters;
1628
+ let readPath = `tool[${toolIndex}]`;
1629
+ try {
1630
+ const candidate = tools[toolIndex];
1631
+ if (!candidate) {
1632
+ diagnostics.push(unreadableToolDiagnostic(toolIndex));
1633
+ continue;
1634
+ }
1635
+ tool = candidate;
1636
+ readPath += ".name";
1637
+ const nameValue = tool.name;
1638
+ if (typeof nameValue !== "string" || !nameValue) {
1639
+ diagnostics.push({
1640
+ toolIndex,
1641
+ violations: [`${readPath} is empty`]
1642
+ });
1643
+ continue;
1644
+ }
1645
+ name = nameValue;
1646
+ readPath = `${name}.parameters`;
1647
+ parameters = tool.parameters;
1648
+ } catch {
1649
+ diagnostics.push({
1650
+ toolIndex,
1651
+ ...name ? { toolName: name } : {},
1652
+ violations: [`${readPath} is unreadable`]
1653
+ });
1268
1654
  continue;
1269
1655
  }
1270
- const owner = ownerByReplayShape.get(item.call_id);
1271
- if (owner === void 0 || owner === null) return {
1272
- request,
1273
- continuationStatus: "history_changed"
1274
- };
1275
- const rawCallId = cachedCalls[owner]?.callId;
1276
- if (!rawCallId) return {
1277
- request,
1278
- continuationStatus: "history_changed"
1279
- };
1280
- restoredInput.push(rawCallId === item.call_id ? item : {
1281
- ...item,
1282
- call_id: rawCallId
1283
- });
1284
- }
1285
- const restoredResponseInput = restoredInput;
1286
- return {
1287
- request: {
1288
- ...prepared,
1289
- previous_response_id: continuation.lastResponseId,
1290
- input: restoredResponseInput
1291
- },
1292
- ...prepared !== request ? { fullRequest: prepared } : {},
1293
- continuationStatus: "continued"
1294
- };
1295
- }
1296
- const httpContinuationEntries = /* @__PURE__ */ new Map();
1297
- const readyHttpContinuationEntries = /* @__PURE__ */ new Map();
1298
- let httpContinuationRetainedBytes = 0;
1299
- function createHttpContinuationTimer(key) {
1300
- const timer = setTimeout(() => {
1301
- const entry = httpContinuationEntries.get(key);
1302
- if (entry?.kind === "ready" && entry.idleTimer === timer) deleteHttpContinuationIfOwned(key, entry);
1303
- }, HTTP_CONTINUATION_IDLE_TTL_MS);
1304
- timer.unref?.();
1305
- return timer;
1306
- }
1307
- function deleteHttpContinuationIfOwned(key, entry) {
1308
- if (httpContinuationEntries.get(key) !== entry) return;
1309
- if (entry.kind === "ready") {
1310
- clearTimeout(entry.idleTimer);
1311
- httpContinuationRetainedBytes -= entry.retainedBytes;
1312
- readyHttpContinuationEntries.delete(key);
1313
- }
1314
- httpContinuationEntries.delete(key);
1315
- }
1316
- function evictReadyEntriesForCapacity(pendingBytes) {
1317
- for (;;) {
1318
- const overCapacity = readyHttpContinuationEntries.size >= MAX_HTTP_CONTINUATION_READY_ENTRIES;
1319
- const overBudget = httpContinuationRetainedBytes + pendingBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES;
1320
- if (!overCapacity && !overBudget) return;
1321
- const oldest = readyHttpContinuationEntries.entries().next();
1322
- if (oldest.done) return;
1323
- const [oldestKey, oldestEntry] = oldest.value;
1324
- deleteHttpContinuationIfOwned(oldestKey, oldestEntry);
1656
+ const prepared = schemas ? prepareRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name) : void 0;
1657
+ const schemaProjection = prepared?.projection ?? projectRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name);
1658
+ if (!isRecord(schemaProjection.schema) || schemaProjection.violations.length > 0) {
1659
+ diagnostics.push({
1660
+ toolIndex,
1661
+ toolName: name,
1662
+ violations: schemaProjection.violations.length > 0 ? schemaProjection.violations : [`${name}.parameters must be a JSON object schema`]
1663
+ });
1664
+ continue;
1665
+ }
1666
+ if (prepared?.normalization) schemas?.set(schemaProjection.schema, prepared.normalization);
1667
+ let descriptionValue;
1668
+ try {
1669
+ descriptionValue = tool.description;
1670
+ } catch {}
1671
+ const description = typeof descriptionValue === "string" ? descriptionValue : void 0;
1672
+ projectedTools.push({
1673
+ toolIndex,
1674
+ name,
1675
+ ...description !== void 0 ? { description } : {},
1676
+ parameters: schemaProjection.schema
1677
+ });
1325
1678
  }
1326
- }
1327
- function connectionIdentity(params) {
1328
- const headers = Object.entries(resolveAiTransportHeaderSentinels(params.headers) ?? {}).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => !TURN_HEADERS.has(name)).toSorted(([a], [b]) => a.localeCompare(b));
1329
- return sha256Hex(JSON.stringify([
1330
- getAiTransportHost().resolveSecretSentinel(params.apiKey),
1331
- params.baseUrl,
1332
- headers
1333
- ]));
1334
- }
1335
- function retainedJsonBytes(value, previous) {
1336
- const strings = /* @__PURE__ */ new Map();
1337
- let stringBytes = 0;
1338
- const skeleton = JSON.stringify(value, (_key, member) => {
1339
- if (typeof member !== "string") return member;
1340
- let bytes = strings.get(member) ?? previous?.get(member);
1341
- if (bytes === void 0) bytes = Buffer.byteLength(JSON.stringify(member), "utf8") - 2;
1342
- strings.set(member, bytes);
1343
- stringBytes += bytes;
1344
- return "";
1345
- });
1346
1679
  return {
1347
- retainedBytes: stringBytes + Buffer.byteLength(skeleton, "utf8"),
1348
- strings
1680
+ inputToolCount,
1681
+ tools: projectedTools,
1682
+ diagnostics
1349
1683
  };
1350
1684
  }
1351
- function claimOpenAIResponsesHttpContinuation(params) {
1352
- const owner = getAiTransportHost();
1353
- const key = `${getSessionResourceOwnerId(owner)}\0${params.sessionId}\0${connectionIdentity(params)}`;
1354
- const previous = httpContinuationEntries.get(key);
1355
- if (previous?.kind === "claimed") return;
1356
- if (previous) deleteHttpContinuationIfOwned(key, previous);
1357
- const request = previous ? params.request : params.restoreRequest?.() ?? params.request;
1358
- const resolved = resolveResponsesContinuationRequest(previous?.state, request);
1359
- const fullRequest = resolved.fullRequest ?? request;
1360
- const continuationRequest = params.request.store === false ? fullRequest : resolved.request;
1361
- const claimed = {
1362
- kind: "claimed",
1363
- sessionId: params.sessionId,
1364
- owner
1365
- };
1366
- httpContinuationEntries.set(key, claimed);
1367
- return {
1368
- request: continuationRequest,
1369
- fullRequest,
1370
- commit: (effectiveRequest, response, dispatchedPreviousResponseId) => {
1371
- if (httpContinuationEntries.get(key) !== claimed) return;
1372
- const state = recordResponsesContinuationState(previous?.state, effectiveRequest, response, previous !== void 0 && dispatchedPreviousResponseId === previous.state.lastResponseId);
1373
- const { retainedBytes, strings } = retainedJsonBytes(state, previous?.strings);
1374
- if (retainedBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES) {
1375
- deleteHttpContinuationIfOwned(key, claimed);
1376
- return;
1377
- }
1378
- evictReadyEntriesForCapacity(retainedBytes);
1379
- const ready = {
1380
- ...claimed,
1381
- kind: "ready",
1382
- state,
1383
- idleTimer: owner.runInDetachedAsyncContext(() => createHttpContinuationTimer(key)),
1384
- retainedBytes,
1385
- strings
1386
- };
1387
- httpContinuationRetainedBytes += retainedBytes;
1388
- httpContinuationEntries.set(key, ready);
1389
- readyHttpContinuationEntries.set(key, ready);
1390
- },
1391
- release: () => deleteHttpContinuationIfOwned(key, claimed)
1685
+ function reconcileToolChoice(choice, projection, responses) {
1686
+ const label = responses ? "OpenAI Responses" : "OpenAI Chat Completions";
1687
+ if (choice === "auto") return projection.tools.length > 0 ? choice : void 0;
1688
+ if (choice === "required") {
1689
+ if (projection.tools.length === 0) throw new Error(`${label} tool_choice requires a tool, but no tools survived schema conversion`);
1690
+ return choice;
1691
+ }
1692
+ if (choice === "none" || !isRecord(choice)) return choice;
1693
+ const choiceType = choice.type;
1694
+ if (!responses && choiceType === "custom") throw new Error("OpenAI Chat Completions custom tool_choice is unsupported because this adapter emits function tools only");
1695
+ if (choiceType === "function") {
1696
+ const functionChoice = responses ? choice : choice.function;
1697
+ const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
1698
+ if (typeof functionName !== "string") return choice;
1699
+ if (!projection.tools.some((tool) => tool.name === functionName)) throw new Error(`${label} tool_choice requested unavailable tool "${functionName}" after schema conversion`);
1700
+ return responses ? {
1701
+ type: "function",
1702
+ name: functionName
1703
+ } : {
1704
+ type: "function",
1705
+ function: { name: functionName }
1706
+ };
1707
+ }
1708
+ if (choiceType !== "allowed_tools") return choice;
1709
+ const allowedConfig = responses ? choice : choice.allowed_tools;
1710
+ if (!isRecord(allowedConfig)) return choice;
1711
+ const { mode, tools } = allowedConfig;
1712
+ if (mode !== "auto" && mode !== "required" || !Array.isArray(tools)) return choice;
1713
+ const responseTools = [];
1714
+ const completionTools = [];
1715
+ for (const tool of tools) {
1716
+ if (!isRecord(tool) || tool.type !== "function") {
1717
+ if (responses) responseTools.push(tool);
1718
+ continue;
1719
+ }
1720
+ const functionChoice = responses ? tool : tool.function;
1721
+ const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
1722
+ if (typeof functionName === "string" && projection.tools.some((projectedTool) => projectedTool.name === functionName)) {
1723
+ if (responses) responseTools.push({
1724
+ type: "function",
1725
+ name: functionName
1726
+ });
1727
+ else completionTools.push({
1728
+ type: "function",
1729
+ function: { name: functionName }
1730
+ });
1731
+ }
1732
+ }
1733
+ if (responseTools.length === 0 && completionTools.length === 0) {
1734
+ if (mode === "auto") return "none";
1735
+ throw new Error(`${label} tool_choice requires a tool, but no allowed tools survived schema conversion`);
1736
+ }
1737
+ return responses ? {
1738
+ type: "allowed_tools",
1739
+ mode,
1740
+ tools: responseTools
1741
+ } : {
1742
+ type: "allowed_tools",
1743
+ allowed_tools: {
1744
+ mode,
1745
+ tools: completionTools
1746
+ }
1392
1747
  };
1393
1748
  }
1394
- registerSessionResourceCleanup((sessionId, owner) => {
1395
- for (const [key, entry] of httpContinuationEntries) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) deleteHttpContinuationIfOwned(key, entry);
1396
- });
1397
- //#endregion
1398
- //#region packages/ai/src/transports/openai-responses-input-replay.ts
1399
- function recordResponsesInputReplay(message, replay) {
1400
- if (replay) Object.assign(message, { openclawResponsesInputReplay: replay });
1401
- }
1402
- function readResponsesInputReplayState(message) {
1403
- const replay = "openclawResponsesInputReplay" in message ? message.openclawResponsesInputReplay : void 0;
1404
- return isRecord(replay) ? replay : void 0;
1405
- }
1406
- function readResponsesInputReplay(message) {
1407
- const replay = readResponsesInputReplayState(message);
1408
- if (replay && typeof replay.afterResponseId === "string" && isStringArray(replay.before) && isStringArray(replay.after)) return {
1409
- afterResponseId: replay.afterResponseId,
1410
- before: replay.before,
1411
- after: replay.after
1412
- };
1749
+ /** Keeps Responses tool choices aligned with surviving function schemas. */
1750
+ function reconcileOpenAIResponsesToolChoice(choice, projection) {
1751
+ return reconcileToolChoice(choice, projection, true);
1413
1752
  }
1414
- function responsesInputFingerprint(item) {
1415
- if (isRecord(item) && (item.type === "function_call_output" || item.type === "custom_tool_call_output") && typeof item.call_id === "string") return sha256Hex(stableStringify({
1416
- type: item.type,
1417
- call_id: item.call_id
1418
- }));
1419
- return sha256Hex(stableStringify(item));
1753
+ /** Keeps Chat Completions tool choices aligned with surviving function schemas. */
1754
+ function reconcileOpenAICompletionsToolChoice(choice, projection) {
1755
+ return reconcileToolChoice(choice, projection, false);
1420
1756
  }
1421
- /** Reconstruct delivery order without rewriting durable local completion events. */
1422
- function createResponsesInputReplay(model) {
1423
- const starts = /* @__PURE__ */ new Map();
1424
- const ends = /* @__PURE__ */ new Map();
1425
- const fingerprints = /* @__PURE__ */ new Map();
1426
- const fingerprint = (item) => {
1427
- const value = fingerprints.get(item) ?? responsesInputFingerprint(item);
1428
- fingerprints.set(item, value);
1429
- return value;
1757
+ /** Re-expresses an object Chat Completions tool choice in the Responses wire shape. */
1758
+ function toOpenAIResponsesToolChoice(choice) {
1759
+ if (choice.type === "function") return {
1760
+ type: "function",
1761
+ name: choice.function.name
1430
1762
  };
1431
- return (input, output, message) => {
1432
- const key = message.turnId || message.responseId;
1433
- const start = (key ? starts.get(key) : void 0) ?? output[0];
1434
- if (key && start) starts.set(key, start);
1435
- input.push(...output);
1436
- let end = input.at(-1);
1437
- const replay = readResponsesInputReplay(message);
1438
- const parent = replay ? ends.get(replay.afterResponseId) : void 0;
1439
- if (replay && parent && message.provider === model.provider && message.api === model.api && message.model === model.id) {
1440
- const take = (keys) => {
1441
- const moved = [];
1442
- for (const inputKey of keys.toReversed()) {
1443
- const boundary = input.indexOf(parent);
1444
- const index = input.findLastIndex((item, position) => position > boundary && fingerprint(item) === inputKey);
1445
- if (index > boundary) moved.unshift(...input.splice(index, 1));
1446
- }
1447
- return moved;
1448
- };
1449
- const before = take(replay.before);
1450
- const after = take(replay.after);
1451
- input.splice(start ? input.indexOf(start) : input.length, 0, ...before);
1452
- end = input.at(-1);
1453
- input.push(...after);
1454
- }
1455
- if (message.responseId && end) ends.set(message.responseId, end);
1763
+ return {
1764
+ type: "allowed_tools",
1765
+ mode: choice.allowed_tools.mode,
1766
+ tools: choice.allowed_tools.tools.map((tool) => tool.type === "function" && isRecord(tool.function) && typeof tool.function.name === "string" ? {
1767
+ type: "function",
1768
+ name: tool.function.name
1769
+ } : tool)
1456
1770
  };
1457
1771
  }
1458
1772
  //#endregion
1459
- //#region packages/ai/src/transports/openai-responses-replay.ts
1460
- /** Resolves the assistant message id that can be replayed to OpenAI Responses. */
1461
- function resolveReplayableResponsesMessageId(params) {
1462
- if (!params.replayResponsesItemIds) return;
1463
- if (!params.textSignatureId) return params.fallbackOrdinal === 0 ? params.fallbackId : `${params.fallbackId}_${params.fallbackOrdinal}`;
1464
- return params.previousReplayItemWasReasoning ? params.textSignatureId : void 0;
1773
+ //#region packages/ai/src/providers/openai-request-reasoning.ts
1774
+ /** Preserve explicit off until the selected route maps it to its native value. */
1775
+ function resolveOpenAISimpleReasoningEffort(model, reasoning) {
1776
+ return reasoning === void 0 ? void 0 : clampThinkingLevel(model, reasoning);
1465
1777
  }
1466
- function normalizeOpenAIResponsesReasoningReplayItem(item, api) {
1467
- if (api === "openai-chatgpt-responses") return Array.isArray(item.summary) ? item : {
1468
- ...item,
1469
- summary: []
1470
- };
1778
+ function resolveOpenAIRequestReasoning(model, reasoning) {
1779
+ const requested = normalizeOpenAIReasoningEffort(reasoning ?? "off");
1780
+ const modelLevel = MODEL_CATALOG_THINKING_LEVELS.find((candidate) => candidate === requested);
1781
+ const modelMapped = modelLevel ? model.thinkingLevelMap?.[modelLevel] : void 0;
1782
+ const mapped = modelMapped === null ? null : resolveOpenAIReasoningEffortMapping(requested, resolveOpenAIReasoningEffortMap(model)) ?? modelMapped;
1783
+ const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0 ? void 0 : requested;
1784
+ const normalizedIntent = normalizeOpenAIReasoningEffort(intent ?? "off");
1785
+ const disabled = requested === "off" || requested === "none";
1786
+ const supported = resolveOpenAIModelReasoningEfforts(disabled && resolveOpenAIThinkingApi(model.api) !== "openai-chatgpt-responses" && !isKnownOpenAIEndpoint(model) ? { compat: model.compat } : model);
1787
+ const effort = !model.reasoning || supported?.length === 0 || intent === void 0 ? void 0 : supported === void 0 ? disabled && mapped === void 0 ? void 0 : intent : resolveOpenAIReasoningEffortForModel({
1788
+ model,
1789
+ effort: requested,
1790
+ fallbackMap: { [requested]: intent }
1791
+ });
1471
1792
  return {
1472
- id: item.id,
1473
- type: "reasoning",
1474
- summary: [],
1475
- ...Array.isArray(item.content) && item.content.length === 0 ? { content: [] } : {},
1476
- status: item.status,
1477
- encrypted_content: item.encrypted_content
1793
+ effort: effort === "none" && resolveOpenAIThinkingApi(model.api) === "openai-chatgpt-responses" && !supportsOpenAIReasoningEffort(model.id === "gpt-6-sol" || model.id === "gpt-6-luna" ? model : {
1794
+ compat: model.compat,
1795
+ thinkingLevelMap: model.thinkingLevelMap
1796
+ }, "none") ? void 0 : effort,
1797
+ thinkingEnabled: intent === void 0 ? void 0 : model.reasoning && normalizedIntent !== "off" && normalizedIntent !== "none"
1478
1798
  };
1479
1799
  }
1480
1800
  //#endregion
1481
- //#region packages/ai/src/utils/text-signature.ts
1482
- function encodeTextSignatureV1(id, phase) {
1483
- return JSON.stringify({
1484
- v: 1,
1485
- id,
1486
- ...phase ? { phase } : {}
1487
- });
1801
+ //#region packages/ai/src/transports/openai-responses-reasoning-update.ts
1802
+ function isConfigurationUpdate(value) {
1803
+ return isRecord(value) && value.type === "configuration_update" && isRecord(value.reasoning) && typeof value.reasoning.effort === "string";
1488
1804
  }
1489
- //#endregion
1490
- //#region packages/ai/src/transports/openai-responses-replay-messages-internal.ts
1491
- function resolveResponsesInstructionRole(model) {
1492
- const supportsDeveloperRole = !isRecord(model.compat) || model.compat.supportsDeveloperRole !== false;
1493
- return model.reasoning && supportsDeveloperRole ? "developer" : "system";
1805
+ function isResponsesReasoningUpdateCompatible(request) {
1806
+ const mode = isRecord(request.reasoning) ? request.reasoning.mode : void 0;
1807
+ return request.model === "gpt-6-astra" && (mode === void 0 || mode === "standard") && (!isRecord(request.multi_agent) || request.multi_agent.enabled !== true) && request.truncation !== "auto" && (!Array.isArray(request.context_management) || !request.context_management.some((item) => isRecord(item) && item.type === "compaction"));
1494
1808
  }
1495
- function stripEncryptedReasoningContentFields(value) {
1496
- if (!value || typeof value !== "object") return value;
1497
- if (Array.isArray(value)) {
1498
- let changed = false;
1499
- const next = value.map((item) => {
1500
- const stripped = stripEncryptedReasoningContentFields(item);
1501
- changed ||= !Object.is(stripped, item);
1502
- return stripped;
1503
- });
1504
- return changed ? next : value;
1809
+ function supportsResponsesReasoningUpdate(request) {
1810
+ return isResponsesReasoningUpdateCompatible(request) && isRecord(request.reasoning) && typeof request.reasoning.effort === "string";
1811
+ }
1812
+ function canReferenceResponsesReasoningHistory(previous, request) {
1813
+ return !previous.input?.some(isConfigurationUpdate) || isResponsesReasoningUpdateCompatible(request);
1814
+ }
1815
+ /** Rehydrate input controls only provisionally; continuation must validate the full prefix. */
1816
+ function replayResponsesReasoningUpdates(previous, request, previousOutputLength, steering) {
1817
+ if (steering !== "required-input" && (!supportsResponsesReasoningUpdate(previous) || !supportsResponsesReasoningUpdate(request)) || !Array.isArray(previous.input) || !Array.isArray(request.input) || request.input.some(isConfigurationUpdate)) return request;
1818
+ const input = [...request.input];
1819
+ let activeEffort = isRecord(previous.reasoning) ? previous.reasoning.effort : void 0;
1820
+ for (const [index, item] of previous.input.entries()) if (isConfigurationUpdate(item)) {
1821
+ input.splice(index, 0, item);
1822
+ activeEffort = item.reasoning.effort;
1505
1823
  }
1506
- const source = value;
1507
- if (source.type === "compaction") return value;
1508
- let changed = false;
1509
- const next = {};
1510
- for (const [key, child] of Object.entries(source)) {
1511
- if (key === "encrypted_content") {
1512
- changed = true;
1513
- continue;
1514
- }
1515
- const stripped = stripEncryptedReasoningContentFields(child);
1516
- changed ||= !Object.is(stripped, child);
1517
- next[key] = stripped;
1824
+ if (steering === "required-input") return input.length === request.input.length ? request : {
1825
+ ...request,
1826
+ input
1827
+ };
1828
+ if (!isRecord(previous.reasoning) || !isRecord(request.reasoning) || typeof request.reasoning.effort !== "string") return request;
1829
+ if (activeEffort !== request.reasoning.effort && steering !== "automatic") {
1830
+ const baselineLength = previous.input.length + previousOutputLength;
1831
+ const nextUser = input.findIndex((item, index) => index >= baselineLength && "role" in item && item.role === "user");
1832
+ if (nextUser === -1) return request;
1833
+ input.splice(nextUser, 0, {
1834
+ type: "configuration_update",
1835
+ reasoning: { effort: request.reasoning.effort }
1836
+ });
1518
1837
  }
1519
- return changed ? next : value;
1520
- }
1521
- function isOpenAIResponsesReasoningReplayMetadata(value) {
1522
- return isProviderReplayContext(value) && value.v === 1 && value.source === "openai-responses";
1838
+ if (input.length === request.input.length && activeEffort === request.reasoning.effort) return request;
1839
+ return {
1840
+ ...request,
1841
+ reasoning: {
1842
+ ...request.reasoning,
1843
+ effort: previous.reasoning.effort
1844
+ },
1845
+ input
1846
+ };
1523
1847
  }
1524
- function readOpenAIResponsesReasoningReplayBlockMetadata(block) {
1525
- if (!Object.hasOwn(block, "openclawReasoningReplay")) return;
1526
- const value = block[OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY];
1527
- return isOpenAIResponsesReasoningReplayMetadata(value) ? value : null;
1848
+ //#endregion
1849
+ //#region packages/ai/src/transports/openai-responses-tool-call-id-shape.ts
1850
+ /**
1851
+ * Pure OpenAI Responses `call_*`/`fc_*` tool-call-id shape helpers.
1852
+ *
1853
+ * Moved out of embedded-agent-helpers/openai.ts (the AgentMessage[]-walking
1854
+ * caller lives in src/agents and imports from packages/ai, so the reverse
1855
+ * import direction is not available) so the continuation transport can
1856
+ * recognize its own cached raw ids after this same reshaping and restore
1857
+ * them on a replayed wire request -- see openai-responses-continuation.ts.
1858
+ */
1859
+ const OPENAI_RESPONSES_ID_MAX_LENGTH = 64;
1860
+ const OPENAI_RESPONSES_CALL_ID_RE = /^call_[A-Za-z0-9_-]{1,59}$/;
1861
+ const OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE = /^fc_[A-Za-z0-9_-]{1,61}$/;
1862
+ function splitOpenAIFunctionCallPairing(id) {
1863
+ const separator = id.indexOf("|");
1864
+ if (separator <= 0 || separator >= id.length - 1) return { callId: id };
1865
+ return {
1866
+ callId: id.slice(0, separator),
1867
+ itemId: id.slice(separator + 1)
1868
+ };
1528
1869
  }
1529
- function prepareOpenAIResponsesReasoningItemForReplay(item, context, blockMetadata, options) {
1530
- const hasRawMetadata = Object.hasOwn(item, OPENAI_RESPONSES_REASONING_REPLAY_META_KEY);
1531
- const { [OPENAI_RESPONSES_REASONING_REPLAY_META_KEY]: rawMetadata, ...rest } = item;
1532
- if (!("encrypted_content" in rest)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
1533
- const metadata = blockMetadata !== void 0 ? blockMetadata ?? void 0 : isOpenAIResponsesReasoningReplayMetadata(rawMetadata) ? rawMetadata : void 0;
1534
- if (blockMetadata === void 0 && !hasRawMetadata && options?.preserveUnattributedEncryptedContent === true || metadata && providerReplayContextMatches(metadata, context)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
1535
- return normalizeOpenAIResponsesReasoningReplayItem(stripEncryptedReasoningContentFields(rest), context.api);
1870
+ function normalizeOpenAIResponsesIdPart(value, prefix) {
1871
+ const trimmed = value.trim();
1872
+ if ((prefix === "call_" ? OPENAI_RESPONSES_CALL_ID_RE : OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE).test(trimmed)) return trimmed;
1873
+ const rawTail = trimmed.startsWith(prefix) ? trimmed.slice(prefix.length) : trimmed;
1874
+ const hash = sha256Hex(trimmed || prefix).slice(0, 10);
1875
+ const maxTailLength = 64 - prefix.length;
1876
+ const hashSuffix = `_${hash}`;
1877
+ return `${prefix}${`${rawTail.replace(/[^A-Za-z0-9_-]/g, "_").replace(/^_+|_+$/g, "").slice(0, Math.max(1, maxTailLength - hashSuffix.length)) || "id"}${hashSuffix}`.slice(0, maxTailLength)}`;
1536
1878
  }
1537
- function normalizeResponsesReplayItemId(id) {
1538
- if (!id) return;
1539
- if (id.length <= 64) return id;
1540
- return `msg_${shortHash(id)}`;
1879
+ /** Same shaping `normalizeOpenAIResponsesToolCallIds` applies to a replayed `call_id`/`call_id|fc_id` pair. */
1880
+ function normalizeOpenAIResponsesFunctionCallId(id) {
1881
+ const { callId, itemId } = splitOpenAIFunctionCallPairing(id);
1882
+ const normalizedCallId = normalizeOpenAIResponsesIdPart(itemId ? `${callId}|${itemId}` : callId, "call_");
1883
+ if (!itemId) return normalizedCallId;
1884
+ return `${normalizedCallId}|${normalizeOpenAIResponsesIdPart(itemId, "fc_")}`;
1541
1885
  }
1542
- function responsesAssistantTurnKey(message) {
1543
- const id = message.turnId || message.responseId;
1544
- return id ? `${message.provider}:${message.api}:${message.model}:${id}` : void 0;
1886
+ function shouldNormalizeOpenAIResponsesToolCallId(id) {
1887
+ const pairing = splitOpenAIFunctionCallPairing(id);
1888
+ if (!OPENAI_RESPONSES_CALL_ID_RE.test(pairing.callId)) return true;
1889
+ if (pairing.itemId === void 0) return false;
1890
+ return !OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE.test(pairing.itemId);
1545
1891
  }
1546
- function orderResponsesAsyncToolResults(source) {
1547
- const lastAssistant = /* @__PURE__ */ new Map();
1548
- for (const [index, message] of source.entries()) if (message.role === "assistant") {
1549
- const key = responsesAssistantTurnKey(message);
1550
- if (key) lastAssistant.set(key, index);
1892
+ //#endregion
1893
+ //#region packages/ai/src/transports/openai-responses-continuation.ts
1894
+ const HTTP_CONTINUATION_IDLE_TTL_MS = 54e5;
1895
+ const MAX_HTTP_CONTINUATION_READY_ENTRIES = 1e3;
1896
+ const MAX_HTTP_CONTINUATION_RETAINED_BYTES = 67108864;
1897
+ const TURN_HEADERS = /* @__PURE__ */ new Set([
1898
+ "traceparent",
1899
+ "x-openclaw-turn-id",
1900
+ "x-openclaw-turn-attempt"
1901
+ ]);
1902
+ function projectJsonValue(value, key, ancestors) {
1903
+ if (typeof value === "number") return Number.isFinite(value) ? value + 0 : null;
1904
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1905
+ if (value === void 0 || typeof value === "symbol") return;
1906
+ if (typeof value !== "object" || isProxy(value) || Object.getPrototypeOf(value) !== (Array.isArray(value) ? Array.prototype : Object.prototype) || "toJSON" in value || ancestors.has(value)) {
1907
+ const projected = JSON.parse(JSON.stringify({
1908
+ __proto__: null,
1909
+ [key]: value
1910
+ }));
1911
+ return Object.hasOwn(projected, key) ? projected[key] : void 0;
1551
1912
  }
1552
- const owners = /* @__PURE__ */ new Map();
1553
- const pending = /* @__PURE__ */ new Map();
1554
- const ordered = [];
1555
- for (const [index, message] of source.entries()) {
1556
- if (message.role === "assistant") {
1557
- const key = responsesAssistantTurnKey(message);
1558
- if (key) {
1559
- for (const block of message.content) if (block.type === "toolCall" && block.async) owners.set(block.id, key);
1560
- }
1913
+ ancestors.add(value);
1914
+ try {
1915
+ if (Array.isArray(value)) {
1916
+ const result = [];
1917
+ const length = value.length;
1918
+ for (let index = 0; index < length; index++) result.push(projectJsonValue(value[index], String(index), ancestors) ?? null);
1919
+ return result;
1561
1920
  }
1562
- const owner = message.role === "toolResult" ? owners.get(message.toolCallId) : void 0;
1563
- const lastIndex = owner ? lastAssistant.get(owner) : void 0;
1564
- if (lastIndex !== void 0 && lastIndex > index) {
1565
- const results = pending.get(lastIndex) ?? [];
1566
- results.push(message);
1567
- pending.set(lastIndex, results);
1568
- } else ordered.push(message);
1569
- const results = pending.get(index);
1570
- if (results) {
1571
- ordered.push(...results);
1572
- pending.delete(index);
1921
+ const result = {};
1922
+ for (const name of Object.keys(value)) {
1923
+ const member = projectJsonValue(Reflect.get(value, name), name, ancestors);
1924
+ if (member !== void 0) {
1925
+ if (name in result) Object.defineProperty(result, name, {
1926
+ value: member,
1927
+ enumerable: true,
1928
+ configurable: true,
1929
+ writable: true
1930
+ });
1931
+ else result[name] = member;
1932
+ }
1573
1933
  }
1934
+ return result;
1935
+ } finally {
1936
+ ancestors.delete(value);
1574
1937
  }
1575
- return ordered;
1576
1938
  }
1577
- function parseOpenAIResponsesTextSignature(signature) {
1578
- if (!signature) return;
1579
- if (signature.startsWith("{")) try {
1580
- const parsed = JSON.parse(signature);
1581
- if (parsed.v === 1) {
1582
- const id = typeof parsed.id === "string" ? parsed.id : void 0;
1583
- const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
1584
- if (id !== void 0 || phase !== void 0) return {
1585
- id,
1586
- phase,
1587
- ...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
1588
- };
1589
- return;
1590
- }
1591
- } catch {}
1592
- return { id: signature };
1939
+ function projectJsonObject(value) {
1940
+ const projected = projectJsonValue(value, "", /* @__PURE__ */ new Set());
1941
+ return projected === void 0 ? JSON.parse("undefined") : projected;
1593
1942
  }
1594
- const responsesInputSource = Symbol("openclaw.responsesInputSource");
1595
- /** Source identity survives payload spreads but never enters serialized provider input. */
1596
- function bindResponsesInputMessage(source) {
1597
- const identity = {};
1598
- Object.defineProperty(source, responsesInputSource, {
1599
- value: identity,
1600
- enumerable: true
1943
+ function jsonValuesEqual(left, right) {
1944
+ return isDeepStrictEqual(projectJsonObject(left), projectJsonObject(right));
1945
+ }
1946
+ function requestWithoutInput(request) {
1947
+ const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
1948
+ if (!isRecord(rest.metadata)) return rest;
1949
+ const metadata = Object.fromEntries(Object.entries(rest.metadata).filter(([key]) => key !== "openclaw_turn_id" && key !== "openclaw_turn_attempt"));
1950
+ return {
1951
+ ...rest,
1952
+ metadata
1953
+ };
1954
+ }
1955
+ function canonicalizeToolCallId(callId, itemId) {
1956
+ if (typeof callId !== "string") return callId;
1957
+ const paired = typeof itemId === "string" && itemId ? `${callId}|${itemId}` : callId;
1958
+ if (!shouldNormalizeOpenAIResponsesToolCallId(paired)) return callId;
1959
+ return splitOpenAIFunctionCallPairing(normalizeOpenAIResponsesFunctionCallId(paired)).callId;
1960
+ }
1961
+ function responseToolCalls(items) {
1962
+ return items.flatMap((item) => {
1963
+ if (!isRecord(item) || item.type !== "function_call" || typeof item.call_id !== "string") return [];
1964
+ return [{
1965
+ callId: item.call_id,
1966
+ ...typeof item.id === "string" ? { itemId: item.id } : {}
1967
+ }];
1601
1968
  });
1602
- return (input) => typeof input === "object" && input !== null && Reflect.get(input, responsesInputSource) === identity;
1603
1969
  }
1604
- function buildResponsesInputMessage(role, content, source) {
1605
- const identity = source && Reflect.get(source, responsesInputSource);
1606
- return {
1607
- type: "message",
1608
- role,
1609
- content,
1610
- ...identity ? { [responsesInputSource]: identity } : {}
1611
- };
1970
+ function toolCallReplayShapes(call) {
1971
+ return new Set([
1972
+ call.callId,
1973
+ canonicalizeToolCallId(call.callId, call.itemId),
1974
+ canonicalizeToolCallId(call.callId, void 0)
1975
+ ].filter((shape) => typeof shape === "string"));
1612
1976
  }
1613
- const responsesMessageProjections = /* @__PURE__ */ new WeakMap();
1614
- /** Detach hook-editable JSON containers while retaining scalar strings. */
1615
- function cloneResponsesInputForPayloadHook(value) {
1616
- if (!value || typeof value !== "object") return value;
1617
- if (Array.isArray(value)) return value.map(cloneResponsesInputForPayloadHook);
1618
- const copy = { ...value };
1619
- for (const key of Object.keys(copy)) Reflect.set(copy, key, cloneResponsesInputForPayloadHook(Reflect.get(value, key)));
1620
- return copy;
1977
+ function toolCallOwnerByReplayShape(calls) {
1978
+ const ownerByReplayShape = /* @__PURE__ */ new Map();
1979
+ for (const [index, call] of calls.entries()) for (const replayShape of toolCallReplayShapes(call)) {
1980
+ const owner = ownerByReplayShape.get(replayShape);
1981
+ ownerByReplayShape.set(replayShape, owner === void 0 || owner === index ? index : null);
1982
+ }
1983
+ return ownerByReplayShape;
1621
1984
  }
1622
- function convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, conversionStyle) {
1623
- const messages = [];
1624
- const providerStyle = conversionStyle === "provider";
1625
- const shouldReplayResponsesItemIds = options?.replayResponsesItemIds ?? true;
1626
- const replayContext = buildProviderReplayContext(model, { sessionId: options?.sessionId });
1627
- const shouldNormalizeSameModelToolCallIds = model.provider === "github-copilot";
1628
- const sanitizeIdPart = (part) => {
1629
- const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
1630
- return providerStyle ? sanitized : sanitized.replace(/_+$/, "");
1631
- };
1632
- const normalizeIdPart = (part) => {
1633
- const sanitized = sanitizeIdPart(part);
1634
- return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
1635
- };
1636
- const buildForeignResponsesItemId = (itemId) => `fc_${shortHash(itemId)}`;
1637
- const buildSameProviderCopilotResponsesItemId = (itemId) => {
1638
- const sanitized = sanitizeIdPart(itemId);
1639
- const candidate = sanitized.startsWith("fc_") ? sanitized : `fc_${sanitized}`;
1640
- return candidate.length > 64 ? buildForeignResponsesItemId(itemId) : candidate;
1641
- };
1642
- const normalizeToolCallId = (id, _targetModel, source) => {
1643
- if (!allowedToolCallProviders.has(model.provider) || !id.includes("|")) return normalizeIdPart(id);
1644
- const separatorIndex = id.indexOf("|");
1645
- const callId = id.slice(0, separatorIndex);
1646
- const itemId = id.slice(separatorIndex + 1);
1647
- const normalizedCallId = normalizeIdPart(callId);
1648
- let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : model.provider === "github-copilot" ? providerStyle ? normalizeIdPart(itemId) : buildSameProviderCopilotResponsesItemId(itemId) : normalizeIdPart(itemId);
1649
- if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
1650
- return `${normalizedCallId}|${normalizedItemId}`;
1651
- };
1652
- const replayPlan = buildOpenAIResponsesCompactionReplayPlan(context.messages, model, {
1653
- sessionId: options?.sessionId,
1654
- mode: options?.replayMode
1985
+ function recordResponsesContinuationState(previous, lastRequest, response, continued = false) {
1986
+ const calls = previous && continued ? [...previous.pendingToolCalls ?? [], ...responseToolCalls(previous.lastResponseItems)] : responseToolCalls(lastRequest.input ?? []);
1987
+ const seenCalls = /* @__PURE__ */ new Set();
1988
+ const uniqueCalls = calls.filter((call) => {
1989
+ const key = JSON.stringify([call.callId, call.itemId]);
1990
+ if (seenCalls.has(key)) return false;
1991
+ seenCalls.add(key);
1992
+ return true;
1655
1993
  });
1656
- const transformMessages = (source) => providerStyle ? transformProviderMessages(source, model, normalizeToolCallId) : getAiTransportHost().transformTransportMessages(source, model, normalizeToolCallId, {
1657
- normalizeSameModelToolCallIds: shouldNormalizeSameModelToolCallIds,
1658
- preserveUnframedToolResults: replayPlan.preserveUnframedToolResults || preparedRequestSuffix.has(context)
1994
+ const input = lastRequest.input ?? [];
1995
+ const ownerByReplayShape = toolCallOwnerByReplayShape(uniqueCalls);
1996
+ const replayedCallIds = /* @__PURE__ */ new Set();
1997
+ const lastCallPosition = /* @__PURE__ */ new Map();
1998
+ const lastOutputPosition = /* @__PURE__ */ new Map();
1999
+ for (const [inputIndex, item] of input.entries()) {
2000
+ if (!isRecord(item) || typeof item.call_id !== "string") continue;
2001
+ const owner = ownerByReplayShape.get(item.call_id);
2002
+ if (item.type === "function_call") replayedCallIds.add(item.call_id);
2003
+ const positions = item.type === "function_call" ? lastCallPosition : item.type === "function_call_output" ? lastOutputPosition : void 0;
2004
+ if (positions && owner !== void 0 && owner !== null) positions.set(owner, inputIndex);
2005
+ }
2006
+ const pendingToolCalls = uniqueCalls.filter((_call, index) => {
2007
+ const callPosition = lastCallPosition.get(index);
2008
+ return [...toolCallReplayShapes(_call)].some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
1659
2009
  });
1660
- const transformedMessages = orderResponsesAsyncToolResults(transformMessages(replayPlan.messages));
1661
- if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
1662
- type: "input_text",
1663
- text: prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions
1664
- }]));
1665
- if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow.map((item) => {
1666
- if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return Object.assign({}, item, { [RESPONSES_RETAINED_USER]: true });
1667
- return item;
1668
- }));
1669
- let replayMessages = replayPlan.compaction ? [replayPlan.compaction, ...transformedMessages] : transformedMessages;
1670
- const isCarrier = (message) => "role" in message && hasRuntimeContextMarker(message);
1671
- if (replayMessages.some(isCarrier)) {
1672
- const anchored = [];
1673
- let insertionIndex = replayPlan.compactedWindow ? 0 : void 0;
1674
- for (const message of replayMessages) {
1675
- if (isCarrier(message) && insertionIndex !== void 0) {
1676
- anchored.splice(insertionIndex++, 0, message);
1677
- continue;
1678
- }
1679
- anchored.push(message);
1680
- if (!isCarrier(message) && ("role" in message ? message.role === "user" : message.type === "compaction")) insertionIndex = anchored.length;
2010
+ return {
2011
+ lastRequest,
2012
+ lastResponseId: response.id,
2013
+ lastResponseItems: response.output.filter((item) => item.type !== "web_search_call"),
2014
+ pendingToolCalls
2015
+ };
2016
+ }
2017
+ function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCachedItemIds = false, replayedInput) {
2018
+ return input.map((item, index) => {
2019
+ if (!isRecord(item)) return item;
2020
+ if (item.type === "reasoning") return { type: "reasoning" };
2021
+ if (item.type !== "function_call" && item.type !== "function_call_output" && !(item.type === "message" && item.role === "assistant")) return item;
2022
+ const { id: rawId, status: _status, ...stableItem } = item;
2023
+ if (item.type === "function_call_output") {
2024
+ if ("id" in item) stableItem.id = item.id;
2025
+ if ("status" in item) stableItem.status = item.status;
1681
2026
  }
1682
- replayMessages = anchored;
1683
- }
1684
- let msgIndex = 0;
1685
- const appendAssistant = createResponsesInputReplay(model);
1686
- const inHistorySystemUpdates = supportsNativeOpenAIResponsesEndpoint(model);
1687
- const convertMessage = (msg, messageIndex) => {
1688
- const converted = [];
1689
- if (inHistorySystemUpdates && isRuntimeContextMessage(msg)) converted.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
1690
- type: "input_text",
1691
- text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
1692
- }]));
1693
- else if (msg.role === "user") {
1694
- const role = msg.operatorMessage && inHistorySystemUpdates && (typeof msg.content === "string" || msg.content.every((block) => block.type === "text")) ? resolveResponsesInstructionRole(model) : "user";
1695
- const content = typeof msg.content === "string" ? [{
1696
- type: "input_text",
1697
- text: sanitizeTransportPayloadText(msg.content)
1698
- }] : msg.content.map((item) => item.type === "text" ? {
1699
- type: "input_text",
1700
- text: sanitizeTransportPayloadText(item.text)
1701
- } : buildResponsesInputImage(item)).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
1702
- if (content.length > 0) {
1703
- const input = buildResponsesInputMessage(role, content, msg);
1704
- if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
1705
- converted.push(input);
1706
- }
1707
- } else if (msg.role === "assistant") {
1708
- const output = converted;
1709
- const sourceTurnKey = responsesAssistantTurnKey(msg);
1710
- const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
1711
- let textFallbackOrdinal = 0;
1712
- let previousReplayItemWasReasoning = false;
1713
- let seenReplayableReasoning = false;
1714
- const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
1715
- for (const block of msg.content) if (block.type === "thinking") {
1716
- if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
1717
- let reasoningItem;
1718
- try {
1719
- reasoningItem = JSON.parse(block.thinkingSignature);
1720
- } catch {
1721
- continue;
1722
- }
1723
- if (!isRecord(reasoningItem) || reasoningItem.type !== "reasoning") continue;
1724
- const replayableReasoningItem = prepareOpenAIResponsesReasoningItemForReplay(reasoningItem, replayContext, readOpenAIResponsesReasoningReplayBlockMetadata(isRecord(block) ? block : {}), providerStyle ? { preserveUnattributedEncryptedContent: true } : void 0);
1725
- if (!shouldReplayResponsesItemIds) {
1726
- delete replayableReasoningItem.id;
1727
- if (!replayableReasoningItem.encrypted_content) continue;
1728
- }
1729
- if (shouldReplayResponsesItemIds && !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
1730
- output.push(replayableReasoningItem);
1731
- previousReplayItemWasReasoning = true;
1732
- seenReplayableReasoning ||= typeof replayableReasoningItem.id === "string" && replayableReasoningItem.id.startsWith("rs_");
1733
- }
1734
- } else if (block.type === "text") {
1735
- const textSignature = parseOpenAIResponsesTextSignature(block.textSignature);
1736
- let msgId = resolveReplayableResponsesMessageId({
1737
- replayResponsesItemIds: shouldReplayResponsesItemIds,
1738
- textSignatureId: textSignature?.id,
1739
- fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`,
1740
- fallbackOrdinal: textFallbackOrdinal,
1741
- previousReplayItemWasReasoning
1742
- });
1743
- if (!textSignature?.id) textFallbackOrdinal += 1;
1744
- msgId = normalizeResponsesReplayItemId(msgId);
1745
- const sources = textSignature?.sources;
1746
- const providerText = sources && block.text.endsWith(sources) ? block.text.slice(0, -sources.length) : block.text;
1747
- const messageItem = {
1748
- type: "message",
1749
- role: "assistant",
1750
- content: [{
1751
- type: "output_text",
1752
- text: sanitizeTransportPayloadText(providerText),
1753
- annotations: []
1754
- }],
1755
- status: "completed",
1756
- ...msgId ? { id: msgId } : {},
1757
- phase: textSignature?.phase
1758
- };
1759
- output.push(messageItem);
1760
- previousReplayItemWasReasoning = false;
1761
- } else if (block.type === "toolCall") {
1762
- const separatorIndex = block.id.indexOf("|");
1763
- const callId = separatorIndex === -1 ? block.id : block.id.slice(0, separatorIndex);
1764
- const itemIdRaw = separatorIndex === -1 ? void 0 : block.id.slice(separatorIndex + 1);
1765
- const itemId = shouldReplayResponsesItemIds && (!itemIdRaw?.startsWith("fc_") || seenReplayableReasoning && !isDifferentModel) ? itemIdRaw : void 0;
1766
- output.push({
1767
- type: "function_call",
1768
- ...itemId ? { id: itemId } : {},
1769
- call_id: callId,
1770
- name: block.name,
1771
- ...block.async ? { async: true } : {},
1772
- arguments: providerStyle ? JSON.stringify(block.arguments) : typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {})
1773
- });
1774
- previousReplayItemWasReasoning = false;
1775
- }
1776
- while (true) {
1777
- const last = output.at(-1);
1778
- if (last?.type !== "reasoning" || !last.id?.startsWith("rs_") || typeof last.encrypted_content === "string" && last.encrypted_content.length > 0) break;
1779
- output.pop();
1780
- }
1781
- return output;
1782
- } else if (msg.role === "toolResult") {
1783
- const textResult = extractToolResultText(msg.content);
1784
- const hasText = textResult.trim().length > 0;
1785
- const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
1786
- const hasImages = msg.content.some(isImageWithMediaPayload);
1787
- const separatorIndex = msg.toolCallId.indexOf("|");
1788
- const rawCallId = separatorIndex === -1 ? msg.toolCallId : msg.toolCallId.slice(0, separatorIndex);
1789
- const callId = preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, rawCallId, normalizeToolCallId(rawCallId, model, model)) : rawCallId;
1790
- let output = hasText ? textResult : mediaPlaceholder ?? "(no output)";
1791
- if (hasImages && model.input.includes("image")) {
1792
- const parts = [];
1793
- let hasExplicitText = false;
1794
- for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(buildResponsesInputImage(item));
1795
- else if (hasText && item.type === "text") {
1796
- const text = extractToolResultBlockText(item);
1797
- if (text) {
1798
- const joinedText = `${hasExplicitText ? "\n" : ""}${text}`;
1799
- hasExplicitText = true;
1800
- const previous = parts.at(-1);
1801
- if (previous?.type === "input_text") previous.text += joinedText;
1802
- else parts.push({
1803
- type: "input_text",
1804
- text: joinedText
1805
- });
1806
- }
1807
- }
1808
- if (hasText && !hasExplicitText) parts.unshift({
1809
- type: "input_text",
1810
- text: textResult
1811
- });
1812
- else if (!hasText && mediaPlaceholder === "(see attached media)") parts.unshift({
1813
- type: "input_text",
1814
- text: mediaPlaceholder
1815
- });
1816
- output = parts;
2027
+ if ("call_id" in stableItem) {
2028
+ const itemId = item.type === "function_call" && !(fromResponse && ignoreCachedItemIds) ? rawId : void 0;
2029
+ stableItem.call_id = canonicalizeToolCallId(stableItem.call_id, itemId);
2030
+ }
2031
+ if (fromResponse && item.type === "function_call") {
2032
+ const replayed = replayedInput?.[index];
2033
+ if (!isRecord(replayed) || replayed.arguments !== stableItem.arguments) {
2034
+ const args = parseJsonObjectPreservingUnsafeIntegers(stableItem.arguments);
2035
+ stableItem.arguments = args ? JSON.stringify(args) : stableItem.arguments;
1817
2036
  }
1818
- converted.push({
1819
- type: "function_call_output",
1820
- call_id: callId,
1821
- output
1822
- });
1823
2037
  }
1824
- return converted;
1825
- };
1826
- const immutable = getAiTransportHost().immutableData;
1827
- const projectionKey = JSON.stringify([
1828
- conversionStyle,
1829
- replayContext,
1830
- shouldReplayResponsesItemIds,
1831
- inHistorySystemUpdates,
1832
- resolveResponsesInstructionRole(model),
1833
- model.input.includes("image"),
1834
- options?.retainUserProvenance === true
1835
- ]);
1836
- for (const msg of replayMessages) {
1837
- if (!("role" in msg)) {
1838
- messages.push(msg);
2038
+ if (item.type === "message" && Array.isArray(stableItem.content)) stableItem.content = stableItem.content.map((part) => {
2039
+ if (!isRecord(part) || part.type !== "output_text") return part;
2040
+ const { annotations: _annotations, logprobs: _logprobs, ...stablePart } = part;
2041
+ return stablePart;
2042
+ });
2043
+ return stableItem;
2044
+ });
2045
+ }
2046
+ function normalizeContinuationHistory(input) {
2047
+ const normalized = normalizeAssistantReplayInput(input);
2048
+ const ownerByReplayShape = toolCallOwnerByReplayShape(responseToolCalls(input));
2049
+ let callIndex = 0;
2050
+ for (const [index, item] of input.entries()) {
2051
+ const normalizedItem = normalized[index];
2052
+ if (!isRecord(item) || !isRecord(normalizedItem)) continue;
2053
+ if (item.type === "function_call") {
2054
+ if (typeof normalizedItem.call_id !== "string") return;
2055
+ const callOwner = ownerByReplayShape.get(normalizedItem.call_id);
2056
+ if (callOwner !== callIndex) return;
2057
+ normalizedItem.call_id = { callOwner };
2058
+ callIndex += 1;
1839
2059
  continue;
1840
2060
  }
1841
- const reusable = immutable && !preparedRequestSuffix.has(context) && immutable.isDeeplyFrozenPlainData(msg) && (typeof msg.content === "string" || !msg.content.some((block) => block.type === "image"));
1842
- const key = `${projectionKey}:${msgIndex}`;
1843
- let projections = reusable ? responsesMessageProjections.get(msg) : void 0;
1844
- let output = projections?.get(key);
1845
- if (!output) {
1846
- output = convertMessage(msg, msgIndex);
1847
- if (reusable) {
1848
- immutable.freezeJsonSnapshot(output);
1849
- if (!projections) {
1850
- projections = /* @__PURE__ */ new Map();
1851
- responsesMessageProjections.set(msg, projections);
1852
- }
1853
- if (projections.size >= 8) {
1854
- const oldest = projections.keys().next().value;
1855
- if (oldest !== void 0) projections.delete(oldest);
1856
- }
1857
- projections.set(key, output);
1858
- }
2061
+ if (item.type !== "function_call_output" || typeof item.call_id !== "string") continue;
2062
+ const owner = ownerByReplayShape.get(item.call_id);
2063
+ if (owner === null) return;
2064
+ normalizedItem.call_id = owner === void 0 ? { unknownCallId: canonicalizeToolCallId(item.call_id, void 0) } : { callOwner: owner };
2065
+ }
2066
+ return normalized;
2067
+ }
2068
+ function responsesContinuationRequestFingerprint(request) {
2069
+ return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
2070
+ }
2071
+ function responsesContinuationPrefixFingerprint(input, output = []) {
2072
+ return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true, false, output)])).digest;
2073
+ }
2074
+ function resolveResponsesContinuationRequest(continuation, request, steering) {
2075
+ if (!continuation) return {
2076
+ request,
2077
+ continuationStatus: "no_previous_response"
2078
+ };
2079
+ if (request.previous_response_id) return {
2080
+ request,
2081
+ continuationStatus: "explicit_previous_response_id"
2082
+ };
2083
+ if (!canReferenceResponsesReasoningHistory(continuation.lastRequest, request)) return {
2084
+ request,
2085
+ continuationStatus: "request_changed"
2086
+ };
2087
+ const prepared = replayResponsesReasoningUpdates(continuation.lastRequest, request, continuation.lastResponseItems.length, steering);
2088
+ if (steering !== "required-input" && !jsonValuesEqual(requestWithoutInput(prepared), requestWithoutInput(continuation.lastRequest))) return {
2089
+ request,
2090
+ continuationStatus: "request_changed"
2091
+ };
2092
+ const currentInput = prepared.input ?? [];
2093
+ const previousInput = continuation.lastRequest.input ?? [];
2094
+ const baselineLength = previousInput.length + continuation.lastResponseItems.length;
2095
+ if (currentInput.length < baselineLength) return {
2096
+ request,
2097
+ continuationStatus: "history_shorter"
2098
+ };
2099
+ const replayedToolRoundInput = currentInput.slice(previousInput.length, baselineLength);
2100
+ const replayedToolRound = normalizeAssistantReplayInput(replayedToolRoundInput);
2101
+ const historyToolRoundUnchanged = [false, true].some((ignoreCachedItemIds) => jsonValuesEqual(replayedToolRound, normalizeAssistantReplayInput(continuation.lastResponseItems, true, ignoreCachedItemIds, replayedToolRoundInput)));
2102
+ const historyCurrentInput = currentInput.slice(0, previousInput.length);
2103
+ for (const [index, previousItem] of previousInput.entries()) {
2104
+ const currentItem = historyCurrentInput[index];
2105
+ if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
2106
+ if (previousItem.type === "function_call" && currentItem.type === "function_call") {
2107
+ if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
2108
+ callId: previousItem.call_id,
2109
+ ...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
2110
+ }).has(currentItem.call_id)) return {
2111
+ request,
2112
+ continuationStatus: "history_changed"
2113
+ };
1859
2114
  }
1860
- if (reusable && options?.mutableInput) output = cloneResponsesInputForPayloadHook(output);
1861
- if (msg.role === "assistant") appendAssistant(messages, output, msg);
1862
- else messages.push(...output);
1863
- if (output.length > 0 || !providerStyle) msgIndex += 1;
2115
+ if (previousItem.type === "function_call_output" && currentItem.type === "function_call_output" && typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && currentItem.call_id !== previousItem.call_id && currentItem.call_id !== canonicalizeToolCallId(previousItem.call_id, void 0)) return {
2116
+ request,
2117
+ continuationStatus: "history_changed"
2118
+ };
1864
2119
  }
1865
- return messages;
2120
+ const normalizedPrevious = normalizeContinuationHistory(previousInput);
2121
+ const normalizedCurrent = normalizeContinuationHistory(historyCurrentInput);
2122
+ if (!(normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious)) || !historyToolRoundUnchanged) return {
2123
+ request,
2124
+ continuationStatus: "history_changed"
2125
+ };
2126
+ const delta = currentInput.slice(baselineLength);
2127
+ const cachedResponseItems = continuation.lastResponseItems;
2128
+ const pendingToolCalls = continuation.pendingToolCalls ?? [];
2129
+ const currentResponseCalls = responseToolCalls(cachedResponseItems);
2130
+ const replayedCalls = replayedToolRoundInput.filter((item) => isRecord(item) && item.type === "function_call");
2131
+ if (currentResponseCalls.length !== replayedCalls.length) return {
2132
+ request,
2133
+ continuationStatus: "history_changed"
2134
+ };
2135
+ const cachedCalls = [...pendingToolCalls, ...currentResponseCalls];
2136
+ const currentCallOffset = pendingToolCalls.length;
2137
+ const ownerByReplayShape = toolCallOwnerByReplayShape(cachedCalls);
2138
+ for (const index of currentResponseCalls.keys()) {
2139
+ const replayedCallId = replayedCalls[index]?.call_id;
2140
+ if (typeof replayedCallId !== "string" || ownerByReplayShape.get(replayedCallId) !== currentCallOffset + index) return {
2141
+ request,
2142
+ continuationStatus: "history_changed"
2143
+ };
2144
+ }
2145
+ const restoredInput = [];
2146
+ for (const item of delta) {
2147
+ if (!isRecord(item) || item.type !== "function_call_output" || typeof item.call_id !== "string") {
2148
+ restoredInput.push(item);
2149
+ continue;
2150
+ }
2151
+ const owner = ownerByReplayShape.get(item.call_id);
2152
+ if (owner === void 0 || owner === null) return {
2153
+ request,
2154
+ continuationStatus: "history_changed"
2155
+ };
2156
+ const rawCallId = cachedCalls[owner]?.callId;
2157
+ if (!rawCallId) return {
2158
+ request,
2159
+ continuationStatus: "history_changed"
2160
+ };
2161
+ restoredInput.push(rawCallId === item.call_id ? item : {
2162
+ ...item,
2163
+ call_id: rawCallId
2164
+ });
2165
+ }
2166
+ const restoredResponseInput = restoredInput;
2167
+ return {
2168
+ request: {
2169
+ ...prepared,
2170
+ previous_response_id: continuation.lastResponseId,
2171
+ input: restoredResponseInput
2172
+ },
2173
+ ...prepared !== request ? { fullRequest: prepared } : {},
2174
+ continuationStatus: "continued"
2175
+ };
1866
2176
  }
1867
- function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
1868
- return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "transport");
2177
+ const httpContinuationEntries = /* @__PURE__ */ new Map();
2178
+ const readyHttpContinuationEntries = /* @__PURE__ */ new Map();
2179
+ let httpContinuationRetainedBytes = 0;
2180
+ function createHttpContinuationTimer(key) {
2181
+ const timer = setTimeout(() => {
2182
+ const entry = httpContinuationEntries.get(key);
2183
+ if (entry?.kind === "ready" && entry.idleTimer === timer) deleteHttpContinuationIfOwned(key, entry);
2184
+ }, HTTP_CONTINUATION_IDLE_TTL_MS);
2185
+ timer.unref?.();
2186
+ return timer;
1869
2187
  }
1870
- function convertProviderResponsesMessages(model, context, allowedToolCallProviders, options) {
1871
- return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "provider");
2188
+ function deleteHttpContinuationIfOwned(key, entry) {
2189
+ if (httpContinuationEntries.get(key) !== entry) return;
2190
+ if (entry.kind === "ready") {
2191
+ clearTimeout(entry.idleTimer);
2192
+ httpContinuationRetainedBytes -= entry.retainedBytes;
2193
+ readyHttpContinuationEntries.delete(key);
2194
+ }
2195
+ httpContinuationEntries.delete(key);
2196
+ }
2197
+ function evictReadyEntriesForCapacity(pendingBytes) {
2198
+ for (;;) {
2199
+ const overCapacity = readyHttpContinuationEntries.size >= MAX_HTTP_CONTINUATION_READY_ENTRIES;
2200
+ const overBudget = httpContinuationRetainedBytes + pendingBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES;
2201
+ if (!overCapacity && !overBudget) return;
2202
+ const oldest = readyHttpContinuationEntries.entries().next();
2203
+ if (oldest.done) return;
2204
+ const [oldestKey, oldestEntry] = oldest.value;
2205
+ deleteHttpContinuationIfOwned(oldestKey, oldestEntry);
2206
+ }
2207
+ }
2208
+ function connectionIdentity(params) {
2209
+ const headers = Object.entries(resolveAiTransportHeaderSentinels(params.headers) ?? {}).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => !TURN_HEADERS.has(name)).toSorted(([a], [b]) => a.localeCompare(b));
2210
+ return sha256Hex(JSON.stringify([
2211
+ getAiTransportHost().resolveSecretSentinel(params.apiKey),
2212
+ params.baseUrl,
2213
+ headers
2214
+ ]));
2215
+ }
2216
+ function retainedJsonBytes(value, previous) {
2217
+ const strings = /* @__PURE__ */ new Map();
2218
+ let stringBytes = 0;
2219
+ const skeleton = JSON.stringify(value, (_key, member) => {
2220
+ if (typeof member !== "string") return member;
2221
+ let bytes = strings.get(member) ?? previous?.get(member);
2222
+ if (bytes === void 0) bytes = Buffer.byteLength(JSON.stringify(member), "utf8") - 2;
2223
+ strings.set(member, bytes);
2224
+ stringBytes += bytes;
2225
+ return "";
2226
+ });
2227
+ return {
2228
+ retainedBytes: stringBytes + Buffer.byteLength(skeleton, "utf8"),
2229
+ strings
2230
+ };
2231
+ }
2232
+ function claimOpenAIResponsesHttpContinuation(params) {
2233
+ const owner = getAiTransportHost();
2234
+ const key = `${getSessionResourceOwnerId(owner)}\0${params.sessionId}\0${connectionIdentity(params)}`;
2235
+ const previous = httpContinuationEntries.get(key);
2236
+ if (previous?.kind === "claimed") return;
2237
+ if (previous) deleteHttpContinuationIfOwned(key, previous);
2238
+ const request = previous ? params.request : params.restoreRequest?.() ?? params.request;
2239
+ const resolved = resolveResponsesContinuationRequest(previous?.state, request);
2240
+ const fullRequest = resolved.fullRequest ?? request;
2241
+ const continuationRequest = params.request.store === false ? fullRequest : resolved.request;
2242
+ const claimed = {
2243
+ kind: "claimed",
2244
+ sessionId: params.sessionId,
2245
+ owner
2246
+ };
2247
+ httpContinuationEntries.set(key, claimed);
2248
+ return {
2249
+ request: continuationRequest,
2250
+ fullRequest,
2251
+ commit: (effectiveRequest, response, dispatchedPreviousResponseId) => {
2252
+ if (httpContinuationEntries.get(key) !== claimed) return;
2253
+ const state = recordResponsesContinuationState(previous?.state, effectiveRequest, response, previous !== void 0 && dispatchedPreviousResponseId === previous.state.lastResponseId);
2254
+ const { retainedBytes, strings } = retainedJsonBytes(state, previous?.strings);
2255
+ if (retainedBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES) {
2256
+ deleteHttpContinuationIfOwned(key, claimed);
2257
+ return;
2258
+ }
2259
+ evictReadyEntriesForCapacity(retainedBytes);
2260
+ const ready = {
2261
+ ...claimed,
2262
+ kind: "ready",
2263
+ state,
2264
+ idleTimer: owner.runInDetachedAsyncContext(() => createHttpContinuationTimer(key)),
2265
+ retainedBytes,
2266
+ strings
2267
+ };
2268
+ httpContinuationRetainedBytes += retainedBytes;
2269
+ httpContinuationEntries.set(key, ready);
2270
+ readyHttpContinuationEntries.set(key, ready);
2271
+ },
2272
+ release: () => deleteHttpContinuationIfOwned(key, claimed)
2273
+ };
1872
2274
  }
2275
+ registerSessionResourceCleanup((sessionId, owner) => {
2276
+ for (const [key, entry] of httpContinuationEntries) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) deleteHttpContinuationIfOwned(key, entry);
2277
+ });
1873
2278
  //#endregion
1874
2279
  //#region packages/ai/src/transports/openai-responses-context-usage.ts
1875
2280
  function contextFingerprint(input, output = []) {
@@ -1924,554 +2329,251 @@ function resolveResponsesContextUsageBoundary(messages, model, identity, systemP
1924
2329
  includeSystemPrompt: includeSystemPrompt === true
1925
2330
  });
1926
2331
  if (input.length < prefixLength || contextFingerprint(input.slice(0, prefixLength)) !== prefixHash) return;
1927
- return {
1928
- index,
1929
- totalTokens: usage.totalTokens,
1930
- suffix: input.slice(prefixLength)
1931
- };
1932
- }
1933
- }
1934
- function isAssistant(message) {
1935
- return message.role === "assistant";
1936
- }
1937
- function isProviderMessage(message) {
1938
- return message.role === "user" || message.role === "assistant" || message.role === "toolResult";
1939
- }
1940
- //#endregion
1941
- //#region packages/ai/src/transports/openai-responses-debug.ts
1942
- function stringifyUnknown(value) {
1943
- if (typeof value === "string") return value;
1944
- if (typeof value === "number" || typeof value === "boolean") return String(value);
1945
- return "";
1946
- }
1947
- function safeDebugValue(value) {
1948
- if (value == null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
1949
- return Array.isArray(value) ? "array" : typeof value;
1950
- }
1951
- function responseInputTextChars(input) {
1952
- if (typeof input === "string") return input.length;
1953
- if (Array.isArray(input)) return input.reduce((total, item) => total + responseInputTextChars(item), 0);
1954
- if (!input || typeof input !== "object") return 0;
1955
- const record = input;
1956
- let total = 0;
1957
- if (typeof record.text === "string") total += record.text.length;
1958
- if (typeof record.content === "string") total += record.content.length;
1959
- else if (Array.isArray(record.content)) total += responseInputTextChars(record.content);
1960
- return total;
1961
- }
1962
- function responseInputRoles(input) {
1963
- if (!Array.isArray(input)) return "";
1964
- const roles = /* @__PURE__ */ new Set();
1965
- for (const item of input) if (item && typeof item === "object") {
1966
- const role = item.role;
1967
- if (typeof role === "string" && role.trim()) roles.add(role.trim());
1968
- }
1969
- return [...roles].toSorted().join(",");
1970
- }
1971
- function responseInputItemShape(input) {
1972
- if (!Array.isArray(input)) return "none";
1973
- return input.map((item) => {
1974
- if (!isRecord(item) || typeof item.type !== "string") return "unknown";
1975
- if (item.type === "message" && typeof item.role === "string") return `message:${item.role}`;
1976
- return item.type;
1977
- }).join(",") || "none";
1978
- }
1979
- function summarizeResponsesCompactionItems(input) {
1980
- const compactions = (Array.isArray(input) ? input : []).flatMap((item, inputIndex) => {
1981
- if (!isRecord(item) || item.type !== "compaction") return [];
1982
- return [{
1983
- idHash: typeof item.id === "string" ? sha256Hex(item.id) : void 0,
1984
- inputIndex,
1985
- payloadHash: typeof item.encrypted_content === "string" ? sha256Hex(item.encrypted_content) : void 0
1986
- }];
1987
- });
1988
- return [
1989
- `compactionItems=${compactions.length}`,
1990
- `compactionIdHashes=${compactions.flatMap((item) => item.idHash ?? []).join(",") || "none"}`,
1991
- `compactionPayloadHashes=${compactions.flatMap((item) => item.payloadHash ?? []).join(",") || "none"}`,
1992
- `compactionInputIndexes=${compactions.map((item) => item.inputIndex).join(",") || "none"}`
1993
- ];
1994
- }
1995
- function readResponsesToolDisplayName(tool) {
1996
- if (!tool || typeof tool !== "object") return "";
1997
- const record = tool;
1998
- const name = record.name;
1999
- if (typeof name === "string") return name;
2000
- const fn = record.function;
2001
- if (fn && typeof fn === "object") {
2002
- const fnName = fn.name;
2003
- if (typeof fnName === "string") return fnName;
2004
- }
2005
- const type = record.type;
2006
- return typeof type === "string" && type !== "function" ? type : "";
2007
- }
2008
- function summarizeResponsesTools(tools) {
2009
- if (!Array.isArray(tools)) return "count=0";
2010
- const names = tools.map(readResponsesToolDisplayName).filter(Boolean);
2011
- const mode = resolveModelPayloadDebugMode();
2012
- const maxNames = mode === "tools" || mode === "full-redacted" ? names.length : 12;
2013
- const label = maxNames >= names.length ? "names" : "sample";
2014
- const shown = names.slice(0, maxNames).join(",");
2015
- return `count=${tools.length}${shown ? ` ${label}=${shown}` : ""}`;
2016
- }
2017
- const RESPONSE_FAILED_FAILURE_FIELD_KEYS = [
2018
- "error",
2019
- "incomplete_details",
2020
- "status_details",
2021
- "failure_reason",
2022
- "last_error",
2023
- "provider_error",
2024
- "error_details"
2025
- ];
2026
- function buildResponsesFailedEventSummary(message, responseId, code, observation) {
2027
- return {
2028
- message,
2029
- ...responseId ? { responseId } : {},
2030
- ...code ? { code } : {},
2031
- ...observation ? { observation } : {}
2032
- };
2033
- }
2034
- function collectResponseFailedIdentifierHashes(input) {
2035
- const out = [];
2036
- const seen = /* @__PURE__ */ new WeakSet();
2037
- const visit = (value, path, depth, identifierKey) => {
2038
- if (out.length >= 12 || depth > 4 || !value || typeof value !== "object" || seen.has(value)) return;
2039
- seen.add(value);
2040
- const entries = Array.isArray(value) ? value.entries() : Object.entries(value);
2041
- for (const [key, child] of entries) {
2042
- if (out.length >= 12 || typeof key === "number" && key >= 8) break;
2043
- const childPath = typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key;
2044
- const childIdentifierKey = typeof key === "number" ? identifierKey : key;
2045
- const normalizedKey = childIdentifierKey.replace(/[-_\s]/g, "").toLowerCase();
2046
- const isIdentifier = normalizedKey.includes("request") && normalizedKey.endsWith("id") || normalizedKey.includes("provider") && normalizedKey.endsWith("id");
2047
- const childString = typeof child === "string" || typeof child === "number" ? String(child).trim() : "";
2048
- if (isIdentifier && childString) out.push(`${childPath}=${redactIdentifier(childString, { len: 12 })}`);
2049
- else visit(child, childPath, depth + 1, isIdentifier ? childIdentifierKey : "");
2050
- }
2051
- };
2052
- visit(input, "", 0, "");
2053
- return out;
2054
- }
2055
- function buildResponsesFailedNoDetailsObservation(event, model, response) {
2056
- const failureFieldNames = RESPONSE_FAILED_FAILURE_FIELD_KEYS.filter((key) => response?.[key] !== void 0 && response[key] !== null);
2057
- const metadataKeys = isRecord(response?.metadata) ? Object.keys(response.metadata).toSorted() : [];
2058
- return {
2059
- event: "openai_responses_response_failed_without_details",
2060
- provider: model.provider,
2061
- api: model.api,
2062
- transportModel: model.id,
2063
- providerRuntimeFailureKind: "no_error_details",
2064
- responseId: stringifyUnknown(response?.id),
2065
- responseStatus: stringifyUnknown(response?.status),
2066
- responseModel: stringifyUnknown(response?.model),
2067
- responseObject: stringifyUnknown(response?.object),
2068
- metadataKeys,
2069
- requestIdHashes: collectResponseFailedIdentifierHashes(event),
2070
- failureFieldNames
2071
- };
2072
- }
2073
- function normalizeResponsesFailedEvent(event, model) {
2074
- const response = isRecord(event.response) ? event.response : void 0;
2075
- const responseId = stringifyUnknown(response?.id) || void 0;
2076
- const error = isRecord(response?.error) ? response.error : void 0;
2077
- if (error) {
2078
- const code = stringifyUnknown(error.code).trim();
2079
- const message = stringifyUnknown(error.message).trim();
2080
- if (code || message) return buildResponsesFailedEventSummary(`${code || "unknown"}: ${message || "no message"}`, responseId, code || void 0);
2081
- }
2082
- const incompleteReason = stringifyUnknown((isRecord(response?.incomplete_details) ? response.incomplete_details : void 0)?.reason);
2083
- if (incompleteReason) return buildResponsesFailedEventSummary(`incomplete: ${incompleteReason}`, responseId);
2084
- return buildResponsesFailedEventSummary(RESPONSE_FAILED_NO_DETAILS_MESSAGE, responseId, void 0, buildResponsesFailedNoDetailsObservation(event, model, response));
2085
- }
2086
- var ResponsesStreamFailure = class extends Error {
2087
- constructor(failure, response) {
2088
- super(failure.message);
2089
- this.name = "ResponsesStreamFailure";
2090
- this.responseId = failure.responseId;
2091
- this.response = response;
2092
- this.code = failure.code;
2093
- this.observation = failure.observation;
2094
- }
2095
- };
2096
- function logResponsesFailedNoDetails(observation) {
2097
- const requestIds = observation.requestIdHashes.join(",");
2098
- const metadataKeys = observation.metadataKeys.join(",");
2099
- log.warn(`[responses] response.failed missing error details provider=${observation.provider} api=${observation.api} model=${observation.transportModel} responseId=${safeDebugValue(observation.responseId || void 0)} responseStatus=${safeDebugValue(observation.responseStatus || void 0)} responseModel=${safeDebugValue(observation.responseModel || void 0)} requestIds=${requestIds || "none"} metadataKeys=${metadataKeys || "none"} failureFields=${observation.failureFieldNames.join(",") || "none"}`, observation);
2100
- }
2101
- function summarizeResponsesPayload(params) {
2102
- if (!params || typeof params !== "object") return "payload=non-object";
2103
- const record = params;
2104
- const input = record.input;
2105
- const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
2106
- const text = record.text && typeof record.text === "object" ? record.text : void 0;
2107
- return [
2108
- `fields=${Object.keys(record).toSorted().join(",")}`,
2109
- `model=${safeDebugValue(record.model)}`,
2110
- `stream=${safeDebugValue(record.stream)}`,
2111
- `inputItems=${Array.isArray(input) ? input.length : typeof input}`,
2112
- `inputItemShape=${responseInputItemShape(input)}`,
2113
- `inputRoles=${responseInputRoles(input) || "none"}`,
2114
- `inputTextChars=${responseInputTextChars(input)}`,
2115
- `tools=${summarizeResponsesTools(record.tools)}`,
2116
- `reasoningEffort=${safeDebugValue(reasoning?.effort)}`,
2117
- `reasoningSummary=${safeDebugValue(reasoning?.summary)}`,
2118
- `textVerbosity=${safeDebugValue(text?.verbosity)}`,
2119
- `serviceTier=${safeDebugValue(record.service_tier)}`,
2120
- ...summarizeResponsesCompactionItems(input),
2121
- `store=${safeDebugValue(record.store)}`,
2122
- `promptCacheKey=${record.prompt_cache_key === void 0 ? "absent" : "present"}`,
2123
- `metadataKeys=${record.metadata && typeof record.metadata === "object" ? Object.keys(record.metadata).toSorted().join(",") : "none"}`
2124
- ].join(" ");
2125
- }
2126
- const ABORT_REASON_LABELS = /* @__PURE__ */ new Map([
2127
- ["LlmIdleTimeoutError", "idle_timeout"],
2128
- ["LlmNoProgressError", "no_progress"],
2129
- ["FirstStreamEventTimeoutError", "first_event_timeout"],
2130
- ["OPENCLAW_SESSION_WATCHDOG", "session_watchdog"],
2131
- ["degenerate_output", "degenerate_output"],
2132
- ["OPENCLAW_RESTART_ABORT", "restart"],
2133
- ["ERR_STALE_GATEWAY_LIFECYCLE", "restart"],
2134
- ["AGENT_RUN_SUPERSEDED_ABORT", "superseded"]
2135
- ]);
2136
- function resolveOpenAITransportAbortReason(signal) {
2137
- if (!signal?.aborted) return;
2138
- const reason = isRecord(signal.reason) ? signal.reason : void 0;
2139
- const defaultReason = reason?.name === "TimeoutError" ? "request_deadline" : "caller_abort";
2140
- const reasonKey = reason?.code ?? reason?.name;
2141
- return (typeof reasonKey === "string" ? ABORT_REASON_LABELS.get(reasonKey) : void 0) ?? defaultReason;
2142
- }
2143
- function summarizeOpenAITransportError(error, signal) {
2144
- const record = isRecord(error) ? error : void 0;
2145
- const cause = record?.cause && typeof record.cause === "object" ? record.cause : void 0;
2146
- const parts = record ? Object.entries({
2147
- name: readTransportDiagnosticLabel(record.name),
2148
- status: readTransportDiagnosticLabel(record.status),
2149
- code: readTransportDiagnosticLabel(record.code),
2150
- type: readTransportDiagnosticLabel(record.type),
2151
- causeName: readTransportDiagnosticLabel(cause?.name),
2152
- causeCode: readTransportDiagnosticLabel(cause?.code)
2153
- }).flatMap(([key, value]) => value === void 0 ? [] : [`${key}=${value}`]) : [`type=${typeof error}`];
2154
- const abortReason = resolveOpenAITransportAbortReason(signal);
2155
- if (abortReason) parts.push(`abortReason=${abortReason}`);
2156
- return parts.join(" ");
2157
- }
2158
- /** Protocol-specific labels join the shared failure line; caller aborts keep their own diagnostic. */
2159
- function observeResponsesTransportFailure(params) {
2160
- const { error, model, output, signal, requestSignal } = params;
2161
- if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
2162
- const incomplete = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
2163
- const incompleteReason = typeof incomplete === "string" ? incomplete : void 0;
2164
- if (signal?.aborted) {
2165
- emitModelTransportError(log, "responses", () => `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error, requestSignal) + (incompleteReason ? ` incompleteReason=${incompleteReason}` : ""), signal);
2166
- return;
2332
+ return {
2333
+ index,
2334
+ totalTokens: usage.totalTokens,
2335
+ suffix: input.slice(prefixLength)
2336
+ };
2167
2337
  }
2168
- return {
2169
- abortReason: resolveOpenAITransportAbortReason(requestSignal),
2170
- incompleteReason
2171
- };
2172
2338
  }
2173
- //#endregion
2174
- //#region packages/ai/src/transports/openai-responses-replay-internal.ts
2175
- const PRELUDE_TYPES = /* @__PURE__ */ new Set([
2176
- "response.created",
2177
- "response.in_progress",
2178
- "response.queued"
2179
- ]);
2180
- function isAsyncIterable(value) {
2181
- return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
2339
+ function isAssistant(message) {
2340
+ return message.role === "assistant";
2182
2341
  }
2183
- function readResponsesRecoveryEvent(event) {
2184
- const record = isRecord(event) ? event : void 0;
2185
- const response = isRecord(record?.response) ? record.response : void 0;
2186
- return {
2187
- failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
2188
- hasResponseOutput: Array.isArray(response?.output) && response.output.length > 0,
2189
- isPrelude: record !== void 0 && PRELUDE_TYPES.has(String(record.type))
2190
- };
2342
+ function isProviderMessage(message) {
2343
+ return message.role === "user" || message.role === "assistant" || message.role === "toolResult";
2191
2344
  }
2192
- function isInvalidEncryptedContentError(error) {
2193
- if (!error || typeof error !== "object") return false;
2194
- const record = error;
2195
- if (record.code === "invalid_encrypted_content" || record.code === "thinking_signature_invalid") return true;
2196
- const message = typeof record.message === "string" ? record.message.toLowerCase() : "";
2197
- return message.includes("invalid_encrypted_content") || message.includes("thinking_signature_invalid") || (record.status === 400 || record.status == null && /(?:^|[\s(])400(?:[\s):]|$)/.test(message)) && (message.includes("could not decrypt the provided encrypted_content") || message.includes("encrypted content") && (message.includes("could not be verified") || message.includes("could not be decrypted or parsed")));
2345
+ //#endregion
2346
+ //#region packages/ai/src/transports/openai-responses-debug.ts
2347
+ function stringifyUnknown(value) {
2348
+ if (typeof value === "string") return value;
2349
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
2350
+ return "";
2198
2351
  }
2199
- function isOrphanedFunctionCallOutputError(error) {
2200
- if (!error || typeof error !== "object") return false;
2201
- const record = error;
2202
- const message = typeof record.message === "string" ? record.message : "";
2203
- return /No tool call found for function call output with call_id [A-Za-z0-9_-]+/.test(message);
2352
+ function safeDebugValue(value) {
2353
+ if (value == null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
2354
+ return Array.isArray(value) ? "array" : typeof value;
2204
2355
  }
2205
- function commitResponsesEncryptedContentAttempt(attempt, commit) {
2206
- if (attempt.kind === "compaction-stripped") commit(attempt.rejectedCompaction);
2356
+ function responseInputTextChars(input) {
2357
+ if (typeof input === "string") return input.length;
2358
+ if (Array.isArray(input)) return input.reduce((total, item) => total + responseInputTextChars(item), 0);
2359
+ if (!input || typeof input !== "object") return 0;
2360
+ const record = input;
2361
+ let total = 0;
2362
+ if (typeof record.text === "string") total += record.text.length;
2363
+ if (typeof record.content === "string") total += record.content.length;
2364
+ else if (Array.isArray(record.content)) total += responseInputTextChars(record.content);
2365
+ return total;
2207
2366
  }
2208
- function stripResponsesRequestEncryptedReasoning(request) {
2209
- const stripped = stripEncryptedReasoningContentFields(request.input);
2210
- return stripped === request.input ? request : {
2211
- ...request,
2212
- input: stripped
2213
- };
2367
+ function responseInputRoles(input) {
2368
+ if (!Array.isArray(input)) return "";
2369
+ const roles = /* @__PURE__ */ new Set();
2370
+ for (const item of input) if (item && typeof item === "object") {
2371
+ const role = item.role;
2372
+ if (typeof role === "string" && role.trim()) roles.add(role.trim());
2373
+ }
2374
+ return [...roles].toSorted().join(",");
2214
2375
  }
2215
- function stripResponsesRequestCompaction(request) {
2216
- if (!Array.isArray(request.input)) return request;
2217
- const input = request.input.filter((item) => !(item !== null && typeof item === "object" && item.type === "compaction"));
2218
- return input.length === request.input.length ? request : {
2219
- ...request,
2220
- input
2221
- };
2376
+ function responseInputItemShape(input) {
2377
+ if (!Array.isArray(input)) return "none";
2378
+ return input.map((item) => {
2379
+ if (!isRecord(item) || typeof item.type !== "string") return "unknown";
2380
+ if (item.type === "message" && typeof item.role === "string") return `message:${item.role}`;
2381
+ return item.type;
2382
+ }).join(",") || "none";
2222
2383
  }
2223
- function readOpenAIResponsesCompactionRejection(request) {
2224
- if (!Array.isArray(request.input)) return;
2225
- const item = request.input.find((candidate) => candidate !== null && typeof candidate === "object" && candidate.type === "compaction" && typeof candidate.encrypted_content === "string");
2226
- return item ? {
2227
- data: item.encrypted_content,
2228
- ...typeof item.id === "string" ? { id: item.id } : {}
2229
- } : void 0;
2384
+ function summarizeResponsesCompactionItems(input) {
2385
+ const compactions = (Array.isArray(input) ? input : []).flatMap((item, inputIndex) => {
2386
+ if (!isRecord(item) || item.type !== "compaction") return [];
2387
+ return [{
2388
+ idHash: typeof item.id === "string" ? sha256Hex(item.id) : void 0,
2389
+ inputIndex,
2390
+ payloadHash: typeof item.encrypted_content === "string" ? sha256Hex(item.encrypted_content) : void 0
2391
+ }];
2392
+ });
2393
+ return [
2394
+ `compactionItems=${compactions.length}`,
2395
+ `compactionIdHashes=${compactions.flatMap((item) => item.idHash ?? []).join(",") || "none"}`,
2396
+ `compactionPayloadHashes=${compactions.flatMap((item) => item.payloadHash ?? []).join(",") || "none"}`,
2397
+ `compactionInputIndexes=${compactions.map((item) => item.inputIndex).join(",") || "none"}`
2398
+ ];
2230
2399
  }
2231
- async function resolveNextResponsesEncryptedContentAttempt(attempt, error, options) {
2232
- const orphanedFunctionOutput = isOrphanedFunctionCallOutputError(error);
2233
- if (!isInvalidEncryptedContentError(error) && !orphanedFunctionOutput || attempt.kind === "compaction-stripped") return;
2234
- if (!orphanedFunctionOutput && (attempt.kind === "initial" || attempt.kind === "continuation-rejected")) {
2235
- const reasoningStripped = stripResponsesRequestEncryptedReasoning(attempt.request);
2236
- if (reasoningStripped !== attempt.request) return {
2237
- kind: "reasoning-stripped",
2238
- request: reasoningStripped
2239
- };
2400
+ function readResponsesToolDisplayName(tool) {
2401
+ if (!tool || typeof tool !== "object") return "";
2402
+ const record = tool;
2403
+ const name = record.name;
2404
+ if (typeof name === "string") return name;
2405
+ const fn = record.function;
2406
+ if (fn && typeof fn === "object") {
2407
+ const fnName = fn.name;
2408
+ if (typeof fnName === "string") return fnName;
2240
2409
  }
2241
- if (stripResponsesRequestCompaction(attempt.request) === attempt.request) return;
2242
- let compactionStripped = await options.buildFullHistoryRequest();
2243
- compactionStripped = stripResponsesRequestCompaction(compactionStripped);
2244
- if (attempt.kind === "reasoning-stripped") compactionStripped = stripResponsesRequestEncryptedReasoning(compactionStripped);
2245
- return {
2246
- kind: "compaction-stripped",
2247
- request: compactionStripped,
2248
- rejectedCompaction: readOpenAIResponsesCompactionRejection(attempt.request)
2249
- };
2410
+ const type = record.type;
2411
+ return typeof type === "string" && type !== "function" ? type : "";
2250
2412
  }
2251
- async function createResponsesStreamWithRecovery(params) {
2252
- async function* streamWithTerminalDrain(response, body) {
2253
- const reader = body.getReader();
2254
- let terminal = false;
2255
- let firstFrame = true;
2256
- const decoder = decodeSseFrames();
2257
- try {
2258
- frames: for (let next = decoder.next(); !next.done;) {
2259
- if (next.value === void 0) {
2260
- next = decoder.next(await reader.read());
2261
- continue;
2262
- }
2263
- const { frame } = next.value;
2264
- let eventName = null;
2265
- let data;
2266
- let start = 0;
2267
- let cr = frame.indexOf("\r");
2268
- let lf = frame.indexOf("\n");
2269
- while (start < frame.length) {
2270
- const end = cr < 0 ? lf < 0 ? frame.length : lf : lf < 0 ? cr : Math.min(cr, lf);
2271
- const lineStart = !(firstFrame && start === 0) && frame.charCodeAt(start) === 65279 ? start + 1 : start;
2272
- start = end + (frame[end] === "\r" && frame[end + 1] === "\n" ? 2 : 1);
2273
- if (cr >= 0 && cr < start) cr = frame.indexOf("\r", start);
2274
- if (lf >= 0 && lf < start) lf = frame.indexOf("\n", start);
2275
- if (lineStart < end) {
2276
- const fieldLength = frame.startsWith("data", lineStart) ? 4 : frame.startsWith("event", lineStart) ? 5 : 0;
2277
- const colon = lineStart + fieldLength;
2278
- if (fieldLength && (colon === end || frame[colon] === ":")) {
2279
- const value = colon === end ? "" : frame.slice(colon + (frame[colon + 1] === " " ? 2 : 1), end);
2280
- if (fieldLength === 5) eventName = value;
2281
- else data = data === void 0 ? value : `${data}\n${value}`;
2282
- }
2283
- if (start < frame.length) continue;
2284
- }
2285
- if (!eventName && data === void 0) continue;
2286
- if (data === "[DONE]") break frames;
2287
- let event;
2288
- try {
2289
- event = JSON.parse(data ?? "");
2290
- } catch {
2291
- throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
2292
- }
2293
- if (eventName?.startsWith("thread.")) event = {
2294
- event: eventName,
2295
- data: event
2296
- };
2297
- else if (eventName === "error" || isRecord(event) && event.error) throw new APIError(void 0, isRecord(event) ? event.error ?? event : event, void 0, response.headers);
2298
- terminal ||= isRecord(event) && (event.type === "response.completed" || event.type === "response.incomplete");
2299
- yield event;
2300
- eventName = null;
2301
- data = void 0;
2302
- }
2303
- firstFrame = false;
2304
- next = decoder.next();
2305
- }
2306
- } catch (error) {
2307
- if (error instanceof APIError || !isRecord(error) || error.name !== "AbortError" && !String(error.message).includes("FetchRequestCanceledException")) throw error;
2308
- } finally {
2309
- if (!terminal) {
2310
- await reader.cancel().catch(() => void 0);
2311
- reader.releaseLock();
2312
- } else {
2313
- const controller = new AbortController();
2314
- const unregister = registerSessionResourceCleanup((sessionId) => {
2315
- if (!sessionId) controller.abort();
2316
- });
2317
- const signal = AbortSignal.any([
2318
- controller.signal,
2319
- AbortSignal.timeout(250),
2320
- ...params.requestOptions?.signal ? [params.requestOptions.signal] : []
2321
- ]);
2322
- const cancel = () => {
2323
- reader.cancel().catch(() => void 0);
2324
- };
2325
- signal.addEventListener("abort", cancel, { once: true });
2326
- (async () => {
2327
- try {
2328
- let bytes = 0;
2329
- while (!signal.aborted && bytes < 65536) {
2330
- const { done, value } = await reader.read();
2331
- if (done) break;
2332
- bytes += value.byteLength;
2333
- }
2334
- } catch {} finally {
2335
- cancel();
2336
- reader.releaseLock();
2337
- signal.removeEventListener("abort", cancel);
2338
- unregister();
2339
- }
2340
- })();
2341
- }
2342
- }
2343
- }
2344
- const encodeBody = params.encodeBody ?? prepareModelRequestBody(void 0);
2345
- let tierCeiling;
2346
- const limitTier = (request) => tierCeiling && (request.service_tier === "ultrafast" || tierCeiling === "default" && request.service_tier === "priority") ? {
2347
- ...request,
2348
- service_tier: tierCeiling
2349
- } : request;
2350
- const recoverServiceTier = (attempt, error) => {
2351
- if (params.requestOptions?.signal?.aborted || !supportsNativeOpenAIResponsesEndpoint(params.model)) return;
2352
- const tier = attempt.request.service_tier;
2353
- const next = nextResponsesServiceTier(tier, error);
2354
- if (!next || tier !== "ultrafast" && tier !== "priority") return;
2355
- tierCeiling = next;
2356
- params.onServiceTierRejected?.(tier);
2357
- log.info(`[responses] rejected ${tier} tier; retrying with ${next}`);
2358
- return {
2359
- ...attempt,
2360
- request: {
2361
- ...attempt.request,
2362
- service_tier: next
2363
- }
2364
- };
2413
+ function summarizeResponsesTools(tools) {
2414
+ if (!Array.isArray(tools)) return "count=0";
2415
+ const names = tools.map(readResponsesToolDisplayName).filter(Boolean);
2416
+ const mode = resolveModelPayloadDebugMode();
2417
+ const maxNames = mode === "tools" || mode === "full-redacted" ? names.length : 12;
2418
+ const label = maxNames >= names.length ? "names" : "sample";
2419
+ const shown = names.slice(0, maxNames).join(",");
2420
+ return `count=${tools.length}${shown ? ` ${label}=${shown}` : ""}`;
2421
+ }
2422
+ const RESPONSE_FAILED_FAILURE_FIELD_KEYS = [
2423
+ "error",
2424
+ "incomplete_details",
2425
+ "status_details",
2426
+ "failure_reason",
2427
+ "last_error",
2428
+ "provider_error",
2429
+ "error_details"
2430
+ ];
2431
+ function buildResponsesFailedEventSummary(message, responseId, code, observation) {
2432
+ return {
2433
+ message,
2434
+ ...responseId ? { responseId } : {},
2435
+ ...code ? { code } : {},
2436
+ ...observation ? { observation } : {}
2365
2437
  };
2366
- const send = async (initialAttempt) => {
2367
- let attempt = initialAttempt;
2368
- for (;;) {
2369
- const cappedRequest = limitTier(attempt.request);
2370
- if (cappedRequest !== attempt.request) attempt = {
2371
- kind: attempt.kind,
2372
- request: cappedRequest,
2373
- rejectedCompaction: attempt.rejectedCompaction
2374
- };
2375
- params.observePrompt?.(attempt.request, {
2376
- egress: "responses-sdk",
2377
- payloadVariant: attempt.kind
2378
- });
2379
- const bodyOptions = await encodeBody(attempt.request);
2380
- let responseAccepted = false;
2381
- try {
2382
- const { data, response } = await params.client.responses.create(attempt.request, {
2383
- ...params.requestOptions,
2384
- ...bodyOptions,
2385
- headers: {
2386
- ...bodyOptions.headers,
2387
- ...params.requestOptions?.headers
2388
- }
2389
- }).withResponse();
2390
- responseAccepted = true;
2391
- commitResponsesEncryptedContentAttempt(attempt, (checkpoint) => {
2392
- if (checkpoint) params.onCompactionRejected?.(checkpoint);
2393
- });
2394
- if (!isAsyncIterable(data)) throw new Error("OpenAI Responses streaming request returned a non-stream response");
2395
- return {
2396
- stream: data instanceof Stream && response.body ? streamWithTerminalDrain(response, response.body) : data,
2397
- response,
2398
- attempt
2399
- };
2400
- } catch (error) {
2401
- let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, { buildFullHistoryRequest: params.buildFullHistoryRequest });
2402
- if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
2403
- const request = { ...await params.buildFullHistoryRequest() };
2404
- delete request.previous_response_id;
2405
- nextAttempt = {
2406
- kind: "continuation-rejected",
2407
- request
2408
- };
2409
- }
2410
- if (!nextAttempt) throw error;
2411
- const retryDescription = nextAttempt.request.service_tier !== attempt.request.service_tier ? "with a slower service tier" : nextAttempt.kind === "reasoning-stripped" ? "without encrypted reasoning content" : nextAttempt.kind === "compaction-stripped" ? "without encrypted compaction content" : "full history after rejected previous_response_id";
2412
- log.warn(`[responses] retrying ${retryDescription} provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
2413
- attempt = nextAttempt;
2414
- }
2438
+ }
2439
+ function collectResponseFailedIdentifierHashes(input) {
2440
+ const out = [];
2441
+ const seen = /* @__PURE__ */ new WeakSet();
2442
+ const visit = (value, path, depth, identifierKey) => {
2443
+ if (out.length >= 12 || depth > 4 || !value || typeof value !== "object" || seen.has(value)) return;
2444
+ seen.add(value);
2445
+ const entries = Array.isArray(value) ? value.entries() : Object.entries(value);
2446
+ for (const [key, child] of entries) {
2447
+ if (out.length >= 12 || typeof key === "number" && key >= 8) break;
2448
+ const childPath = typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key;
2449
+ const childIdentifierKey = typeof key === "number" ? identifierKey : key;
2450
+ const normalizedKey = childIdentifierKey.replace(/[-_\s]/g, "").toLowerCase();
2451
+ const isIdentifier = normalizedKey.includes("request") && normalizedKey.endsWith("id") || normalizedKey.includes("provider") && normalizedKey.endsWith("id");
2452
+ const childString = typeof child === "string" || typeof child === "number" ? String(child).trim() : "";
2453
+ if (isIdentifier && childString) out.push(`${childPath}=${redactIdentifier(childString, { len: 12 })}`);
2454
+ else visit(child, childPath, depth + 1, isIdentifier ? childIdentifierKey : "");
2415
2455
  }
2416
2456
  };
2417
- const result = await send({
2418
- kind: params.initialAttemptKind ?? "initial",
2419
- request: params.request,
2420
- ...params.initialRejectedCompaction ? { rejectedCompaction: params.initialRejectedCompaction } : {}
2421
- });
2422
- return { stream: { async *[Symbol.asyncIterator]() {
2423
- let current = result;
2424
- let outputObserved = false;
2425
- for (;;) {
2426
- let rejectedEvent;
2427
- let sourceError;
2428
- const source = current.stream;
2429
- const providerStream = { async *[Symbol.asyncIterator]() {
2430
- try {
2431
- yield* source;
2432
- } catch (error) {
2433
- sourceError = error;
2434
- throw error;
2435
- }
2436
- } };
2437
- try {
2438
- for await (const event of params.wrapStream?.({
2439
- ...current,
2440
- stream: providerStream
2441
- }) ?? providerStream) {
2442
- const { failure, hasResponseOutput, isPrelude } = readResponsesRecoveryEvent(event);
2443
- outputObserved ||= hasResponseOutput;
2444
- if (isRecord(failure) && params.canRetryStream?.() === true && (isInvalidEncryptedContentError(failure) || !outputObserved && isResponsesServiceTierRejection(failure))) {
2445
- rejectedEvent = event;
2446
- const message = typeof failure.message === "string" ? failure.message : "";
2447
- throw Object.assign(new Error(message), {
2448
- code: failure.code,
2449
- status: failure.status,
2450
- type: failure.type,
2451
- param: failure.param
2452
- });
2453
- }
2454
- outputObserved ||= !isPrelude;
2455
- yield event;
2456
- }
2457
- return;
2458
- } catch (error) {
2459
- const nextAttempt = params.canRetryStream?.() === true && !params.requestOptions?.signal?.aborted ? (!outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? recoverServiceTier(current.attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(current.attempt, error, { buildFullHistoryRequest: params.buildFullHistoryRequest }) : void 0;
2460
- if (!nextAttempt) {
2461
- if (rejectedEvent !== void 0) {
2462
- yield rejectedEvent;
2463
- return;
2464
- }
2465
- throw error;
2466
- }
2467
- log.warn(`[responses] retrying explicitly rejected stream provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
2468
- current = await send(nextAttempt);
2469
- }
2470
- }
2471
- } } };
2457
+ visit(input, "", 0, "");
2458
+ return out;
2472
2459
  }
2473
- function resolveAzureOpenAIApiVersion(env = process.env) {
2474
- return env.AZURE_OPENAI_API_VERSION?.trim() || "preview";
2460
+ function buildResponsesFailedNoDetailsObservation(event, model, response) {
2461
+ const failureFieldNames = RESPONSE_FAILED_FAILURE_FIELD_KEYS.filter((key) => response?.[key] !== void 0 && response[key] !== null);
2462
+ const metadataKeys = isRecord(response?.metadata) ? Object.keys(response.metadata).toSorted() : [];
2463
+ return {
2464
+ event: "openai_responses_response_failed_without_details",
2465
+ provider: model.provider,
2466
+ api: model.api,
2467
+ transportModel: model.id,
2468
+ providerRuntimeFailureKind: "no_error_details",
2469
+ responseId: stringifyUnknown(response?.id),
2470
+ responseStatus: stringifyUnknown(response?.status),
2471
+ responseModel: stringifyUnknown(response?.model),
2472
+ responseObject: stringifyUnknown(response?.object),
2473
+ metadataKeys,
2474
+ requestIdHashes: collectResponseFailedIdentifierHashes(event),
2475
+ failureFieldNames
2476
+ };
2477
+ }
2478
+ function normalizeResponsesFailedEvent(event, model) {
2479
+ const response = isRecord(event.response) ? event.response : void 0;
2480
+ const responseId = stringifyUnknown(response?.id) || void 0;
2481
+ const error = isRecord(response?.error) ? response.error : void 0;
2482
+ if (error) {
2483
+ const code = stringifyUnknown(error.code).trim();
2484
+ const message = stringifyUnknown(error.message).trim();
2485
+ if (code || message) return buildResponsesFailedEventSummary(`${code || "unknown"}: ${message || "no message"}`, responseId, code || void 0);
2486
+ }
2487
+ const incompleteReason = stringifyUnknown((isRecord(response?.incomplete_details) ? response.incomplete_details : void 0)?.reason);
2488
+ if (incompleteReason) return buildResponsesFailedEventSummary(`incomplete: ${incompleteReason}`, responseId);
2489
+ return buildResponsesFailedEventSummary(RESPONSE_FAILED_NO_DETAILS_MESSAGE, responseId, void 0, buildResponsesFailedNoDetailsObservation(event, model, response));
2490
+ }
2491
+ var ResponsesStreamFailure = class extends Error {
2492
+ constructor(failure, response) {
2493
+ super(failure.message);
2494
+ this.name = "ResponsesStreamFailure";
2495
+ this.responseId = failure.responseId;
2496
+ this.response = response;
2497
+ this.code = failure.code;
2498
+ this.observation = failure.observation;
2499
+ }
2500
+ };
2501
+ function logResponsesFailedNoDetails(observation) {
2502
+ const requestIds = observation.requestIdHashes.join(",");
2503
+ const metadataKeys = observation.metadataKeys.join(",");
2504
+ log.warn(`[responses] response.failed missing error details provider=${observation.provider} api=${observation.api} model=${observation.transportModel} responseId=${safeDebugValue(observation.responseId || void 0)} responseStatus=${safeDebugValue(observation.responseStatus || void 0)} responseModel=${safeDebugValue(observation.responseModel || void 0)} requestIds=${requestIds || "none"} metadataKeys=${metadataKeys || "none"} failureFields=${observation.failureFieldNames.join(",") || "none"}`, observation);
2505
+ }
2506
+ function summarizeResponsesPayload(params) {
2507
+ if (!params || typeof params !== "object") return "payload=non-object";
2508
+ const record = params;
2509
+ const input = record.input;
2510
+ const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
2511
+ const text = record.text && typeof record.text === "object" ? record.text : void 0;
2512
+ return [
2513
+ `fields=${Object.keys(record).toSorted().join(",")}`,
2514
+ `model=${safeDebugValue(record.model)}`,
2515
+ `stream=${safeDebugValue(record.stream)}`,
2516
+ `inputItems=${Array.isArray(input) ? input.length : typeof input}`,
2517
+ `inputItemShape=${responseInputItemShape(input)}`,
2518
+ `inputRoles=${responseInputRoles(input) || "none"}`,
2519
+ `inputTextChars=${responseInputTextChars(input)}`,
2520
+ `tools=${summarizeResponsesTools(record.tools)}`,
2521
+ `reasoningEffort=${safeDebugValue(reasoning?.effort)}`,
2522
+ `reasoningSummary=${safeDebugValue(reasoning?.summary)}`,
2523
+ `textVerbosity=${safeDebugValue(text?.verbosity)}`,
2524
+ `serviceTier=${safeDebugValue(record.service_tier)}`,
2525
+ ...summarizeResponsesCompactionItems(input),
2526
+ `store=${safeDebugValue(record.store)}`,
2527
+ `promptCacheKey=${record.prompt_cache_key === void 0 ? "absent" : "present"}`,
2528
+ `metadataKeys=${record.metadata && typeof record.metadata === "object" ? Object.keys(record.metadata).toSorted().join(",") : "none"}`
2529
+ ].join(" ");
2530
+ }
2531
+ const ABORT_REASON_LABELS = /* @__PURE__ */ new Map([
2532
+ ["LlmIdleTimeoutError", "idle_timeout"],
2533
+ ["LlmNoProgressError", "no_progress"],
2534
+ ["FirstStreamEventTimeoutError", "first_event_timeout"],
2535
+ ["OPENCLAW_SESSION_WATCHDOG", "session_watchdog"],
2536
+ ["degenerate_output", "degenerate_output"],
2537
+ ["OPENCLAW_RESTART_ABORT", "restart"],
2538
+ ["ERR_STALE_GATEWAY_LIFECYCLE", "restart"],
2539
+ ["AGENT_RUN_SUPERSEDED_ABORT", "superseded"]
2540
+ ]);
2541
+ function resolveOpenAITransportAbortReason(signal) {
2542
+ if (!signal?.aborted) return;
2543
+ const reason = isRecord(signal.reason) ? signal.reason : void 0;
2544
+ const defaultReason = reason?.name === "TimeoutError" ? "request_deadline" : "caller_abort";
2545
+ const reasonKey = reason?.code ?? reason?.name;
2546
+ return (typeof reasonKey === "string" ? ABORT_REASON_LABELS.get(reasonKey) : void 0) ?? defaultReason;
2547
+ }
2548
+ function summarizeOpenAITransportError(error, signal) {
2549
+ const record = isRecord(error) ? error : void 0;
2550
+ const cause = record?.cause && typeof record.cause === "object" ? record.cause : void 0;
2551
+ const parts = record ? Object.entries({
2552
+ name: readTransportDiagnosticLabel(record.name),
2553
+ status: readTransportDiagnosticLabel(record.status),
2554
+ code: readTransportDiagnosticLabel(record.code),
2555
+ type: readTransportDiagnosticLabel(record.type),
2556
+ causeName: readTransportDiagnosticLabel(cause?.name),
2557
+ causeCode: readTransportDiagnosticLabel(cause?.code)
2558
+ }).flatMap(([key, value]) => value === void 0 ? [] : [`${key}=${value}`]) : [`type=${typeof error}`];
2559
+ const abortReason = resolveOpenAITransportAbortReason(signal);
2560
+ if (abortReason) parts.push(`abortReason=${abortReason}`);
2561
+ return parts.join(" ");
2562
+ }
2563
+ /** Protocol-specific labels join the shared failure line; caller aborts keep their own diagnostic. */
2564
+ function observeResponsesTransportFailure(params) {
2565
+ const { error, model, output, signal, requestSignal } = params;
2566
+ if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
2567
+ const incomplete = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
2568
+ const incompleteReason = typeof incomplete === "string" ? incomplete : void 0;
2569
+ if (signal?.aborted) {
2570
+ emitModelTransportError(log, "responses", () => `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error, requestSignal) + (incompleteReason ? ` incompleteReason=${incompleteReason}` : ""), signal);
2571
+ return;
2572
+ }
2573
+ return {
2574
+ abortReason: resolveOpenAITransportAbortReason(requestSignal),
2575
+ incompleteReason
2576
+ };
2475
2577
  }
2476
2578
  //#endregion
2477
2579
  //#region packages/ai/src/providers/openai-responses-message-text.ts
@@ -2861,9 +2963,16 @@ function resolveCompletedResponsesToolCall(item, streamed) {
2861
2963
  if (streamedName && completedName && streamedName !== completedName) throw new Error(`Responses stream changed tool-call function name from ${streamedName} to ${completedName}`);
2862
2964
  const name = completedName ?? streamedName;
2863
2965
  if (!name) throw new Error("Responses stream completed tool call without a function name");
2966
+ const raw = streamed?.rawArguments ?? streamed?.arguments ?? item.arguments;
2967
+ const argumentsValue = parseTerminalToolCallArguments(streamed?.arguments ?? item.arguments, "Responses stream completed tool call with invalid JSON arguments");
2968
+ const value = JSON.stringify(argumentsValue);
2864
2969
  return {
2865
2970
  name,
2866
- arguments: parseTerminalToolCallArguments(streamed?.arguments ?? item.arguments, "Responses stream completed tool call with invalid JSON arguments")
2971
+ arguments: argumentsValue,
2972
+ ...typeof raw === "string" && raw !== value ? { argumentsSignature: {
2973
+ value,
2974
+ raw
2975
+ } } : {}
2867
2976
  };
2868
2977
  }
2869
2978
  function createResponsesTerminalController(params) {
@@ -3529,7 +3638,8 @@ async function processResponsesStream(openaiStream, output, sink, model, options
3529
3638
  try {
3530
3639
  validated = resolveCompletedResponsesToolCall(item, {
3531
3640
  name: streamingToolCall?.providerName,
3532
- arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments)
3641
+ arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments),
3642
+ rawArguments: parsedStreamedArguments ? streamedArguments : void 0
3533
3643
  });
3534
3644
  } catch (error) {
3535
3645
  rejectedToolCall = { error };
@@ -3655,9 +3765,12 @@ function applyCommonResponsesParams(params, model, context, options, config) {
3655
3765
  }
3656
3766
  async function runResponsesStreamLifecycle(params) {
3657
3767
  const { stream, output, options } = params;
3768
+ let itemRecovery;
3658
3769
  let firstEventAbort;
3659
3770
  try {
3660
3771
  const model = params.resolveRequestModel?.(params.model) ?? params.model;
3772
+ itemRecovery = createResponsesItemConflictRecovery(output, model, options);
3773
+ const recovery = itemRecovery;
3661
3774
  const client = params.createClient(model);
3662
3775
  const encodeBody = prepareModelRequestBody(options);
3663
3776
  const buildRequest = async (replayMode) => {
@@ -3689,6 +3802,7 @@ async function runResponsesStreamLifecycle(params) {
3689
3802
  model,
3690
3803
  encodeBody,
3691
3804
  buildFullHistoryRequest: () => buildRequest("full-history"),
3805
+ buildItemConflictRequest: () => recovery.retry(buildRequest),
3692
3806
  onCompactionRejected: (checkpoint) => suppressOpenAIResponsesCompaction(output, model, options, checkpoint),
3693
3807
  canRetryStream: () => output.content.length === 0,
3694
3808
  onServiceTierRejected: (tier) => responsesServiceTierObserver.reject(options, tier),
@@ -3735,6 +3849,7 @@ async function runResponsesStreamLifecycle(params) {
3735
3849
  signal: options?.signal
3736
3850
  });
3737
3851
  } catch (error) {
3852
+ itemRecovery?.reject(error);
3738
3853
  const response = error instanceof ResponsesStreamFailure ? error.response : error;
3739
3854
  const rawError = isRecord(response) && isRecord(response.error) ? response.error : response;
3740
3855
  if (params.model.provider === "openai" && params.model.api === "openai-responses" && isRecord(rawError) && rawError.code === "misalignment_policy_violation") {
@@ -3756,8 +3871,9 @@ async function runResponsesStreamLifecycle(params) {
3756
3871
  error
3757
3872
  });
3758
3873
  } finally {
3874
+ itemRecovery?.finish();
3759
3875
  firstEventAbort?.dispose();
3760
3876
  }
3761
3877
  }
3762
3878
  //#endregion
3763
- export { isConfigurationUpdate as $, summarizeResponsesPayload as A, log as At, recordResponsesInputReplay as B, isInvalidEncryptedContentError as C, toOpenAIResponsesToolChoice as Ct, ResponsesStreamFailure as D, createResponseModelTracker as Dt, resolveNextResponsesEncryptedContentAttempt as E, createOpenAIResponseHook as Et, convertProviderResponsesMessages as F, resolveOpenAIClientBaseUrl as Ft, responsesContinuationPrefixFingerprint as G, claimOpenAIResponsesHttpContinuation as H, convertResponsesMessages as I, resolvePromptCacheKey as It, OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE as J, responsesContinuationRequestFingerprint as K, normalizeOpenAIResponsesReasoningReplayItem as L, withOpenAIErrorResponseHook as Lt, resolveResponsesContextUsageBoundary as M, parseOpenAICompletionsUsage as Mt, bindResponsesInputMessage as N, readOpenAICompletionsContentDeltas as Nt, observeResponsesTransportFailure as O, detachPartialSnapshot as Ot, buildResponsesInputMessage as P, readOpenAICompletionsReasoningBatch as Pt, splitOpenAIFunctionCallPairing as Q, resolveReplayableResponsesMessageId as R, createResponsesStreamWithRecovery as S, reconcileOpenAIResponsesToolChoice as St, resolveAzureOpenAIApiVersion as T, createOpenAIProviderAcceptanceHook as Tt, recordResponsesContinuationState as U, responsesInputFingerprint as V, resolveResponsesContinuationRequest as W, normalizeOpenAIResponsesFunctionCallId as X, OPENAI_RESPONSES_ID_MAX_LENGTH as Y, shouldNormalizeOpenAIResponsesToolCallId as Z, isAzureResponsesTextDeltaEventType as _, resolveOpenAIRequestReasoning as _t, prepareResponsesTools as a, resolveNewestOpenAIResponsesCompactionReplay as at, resolveResponsesMessageSnapshotCollapse as b, projectOpenAITools as bt, observeResponsesStream as c, buildOpenAIClientHeaders as ct, RESPONSES_BOOKKEEPING_TIMEOUT_MS as d, enforceCodeModeResponsesToolSurface as dt, replayResponsesReasoningUpdates as et, AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE as f, filterCodeModePayloadTools as ft, isAzureResponsesTextDeltaEvent as g, resolveOpenAIStrictToolFlagWithDiagnostics as gt, OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE as h, resolveCodeModeResponsesVisibleToolNames as ht, convertResponsesToolPayload as i, captureOpenAIResponsesCompaction as it, recordResponsesContextUsage as j, measureUtf8AppendBytes as jt, safeDebugValue as k, isOpenAICompletionsThinkingEnabled as kt, createResponsesToolCallTracker as l, buildOpenAISdkClientOptions as lt, OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE as m, readCodeModePayloadToolName as mt, applyResponsesServiceTierPricing as n, CompactionReplayRefreshRequiredError as nt, readOpenAIMisalignmentReview as o, suppressOpenAIResponsesCompaction as ot, AZURE_RESPONSES_TEXT_DELTA_EVENT_TYPE as p, getCompat as pt, OPENAI_RESPONSES_CALL_ID_RE as q, runResponsesStreamLifecycle as r, buildOpenAIResponsesReasoningReplayMetadata as rt, processResponsesStream as s, assertCodeModeResponsesToolSurface as st, applyCommonResponsesParams as t, supportsResponsesReasoningUpdate as tt, readResponsesToolCallItemIdentity as u, buildOpenAISdkRequestOptions as ut, isResponsesTextContentPartType as v, resolveOpenAISimpleReasoningEffort as vt, readResponsesRecoveryEvent as w, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP as wt, commitResponsesEncryptedContentAttempt as x, reconcileOpenAICompletionsToolChoice as xt, isResponsesTextDeltaEventType as y, prepareOpenAITools as yt, readResponsesInputReplayState as z };
3879
+ export { filterCodeModePayloadTools as $, responsesContinuationPrefixFingerprint as A, createOpenAIResponseHook as At, supportsResponsesReasoningUpdate as B, resolvePromptCacheKey as Bt, safeDebugValue as C, buildOpenAIResponsesReasoningReplayMetadata as Ct, claimOpenAIResponsesHttpContinuation as D, suppressOpenAIResponsesCompaction as Dt, resolveResponsesContextUsageBoundary as E, resolveNewestOpenAIResponsesCompactionReplay as Et, normalizeOpenAIResponsesFunctionCallId as F, measureUtf8AppendBytes as Ft, reconcileOpenAICompletionsToolChoice as G, resolveOpenAISimpleReasoningEffort as H, shouldNormalizeOpenAIResponsesToolCallId as I, parseOpenAICompletionsUsage as It, assertCodeModeResponsesToolSurface as J, reconcileOpenAIResponsesToolChoice as K, splitOpenAIFunctionCallPairing as L, readOpenAICompletionsContentDeltas as Lt, OPENAI_RESPONSES_CALL_ID_RE as M, detachPartialSnapshot as Mt, OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE as N, isOpenAICompletionsThinkingEnabled as Nt, recordResponsesContinuationState as O, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP as Ot, OPENAI_RESPONSES_ID_MAX_LENGTH as P, log as Pt, enforceCodeModeResponsesToolSurface as Q, isConfigurationUpdate as R, readOpenAICompletionsReasoningBatch as Rt, observeResponsesTransportFailure as S, CompactionReplayRefreshRequiredError as St, recordResponsesContextUsage as T, readOpenAIResponsesItemRecoveryAnchor as Tt, prepareOpenAITools as U, resolveOpenAIRequestReasoning as V, withOpenAIErrorResponseHook as Vt, projectOpenAITools as W, buildOpenAISdkClientOptions as X, buildOpenAIClientHeaders as Y, buildOpenAISdkRequestOptions as Z, isAzureResponsesTextDeltaEventType as _, replayOpenAIResponsesToolArguments as _t, prepareResponsesTools as a, createResponsesItemConflictRecovery as at, resolveResponsesMessageSnapshotCollapse as b, recordResponsesInputReplay as bt, observeResponsesStream as c, isResponsesItemConflict as ct, RESPONSES_BOOKKEEPING_TIMEOUT_MS as d, resolveNextResponsesEncryptedContentAttempt as dt, getCompat as et, AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE as f, bindResponsesInputMessage as ft, isAzureResponsesTextDeltaEvent as g, normalizeOpenAIResponsesReasoningReplayItem as gt, OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE as h, convertResponsesMessages as ht, convertResponsesToolPayload as i, commitResponsesEncryptedContentAttempt as it, responsesContinuationRequestFingerprint as j, createResponseModelTracker as jt, resolveResponsesContinuationRequest as k, createOpenAIProviderAcceptanceHook as kt, createResponsesToolCallTracker as l, readResponsesRecoveryEvent as lt, OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE as m, convertProviderResponsesMessages as mt, applyResponsesServiceTierPricing as n, resolveCodeModeResponsesVisibleToolNames as nt, readOpenAIMisalignmentReview as o, createResponsesStreamWithRecovery as ot, AZURE_RESPONSES_TEXT_DELTA_EVENT_TYPE as p, buildResponsesInputMessage as pt, toOpenAIResponsesToolChoice as q, runResponsesStreamLifecycle as r, resolveOpenAIStrictToolFlagWithDiagnostics as rt, processResponsesStream as s, isInvalidEncryptedContentError as st, applyCommonResponsesParams as t, readCodeModePayloadToolName as tt, readResponsesToolCallItemIdentity as u, resolveAzureOpenAIApiVersion as ut, isResponsesTextContentPartType as v, resolveReplayableResponsesMessageId as vt, summarizeResponsesPayload as w, captureOpenAIResponsesCompaction as wt, ResponsesStreamFailure as x, responsesInputFingerprint as xt, isResponsesTextDeltaEventType as y, readResponsesInputReplayState as yt, replayResponsesReasoningUpdates as z, resolveOpenAIClientBaseUrl as zt };