@bitkyc08/opencodex 2.55.0 → 2.57.0

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 (256) hide show
  1. package/bin/ocx.mjs +10 -0
  2. package/gui/dist/assets/{index-BBOZWGB6.css → index-C5-RdDmD.css} +1 -1
  3. package/gui/dist/assets/{index-VuoiWj9J.js → index-Cz7CLdif.js} +21 -21
  4. package/gui/dist/index.html +2 -2
  5. package/package.json +4 -3
  6. package/src/adapters/base.ts +21 -0
  7. package/src/adapters/codebuddy/adapter.ts +2 -1
  8. package/src/adapters/codebuddy/scaffold-guard.ts +248 -0
  9. package/src/adapters/command-code.ts +1 -1
  10. package/src/adapters/cursor/envelope-echo.ts +8 -2
  11. package/src/adapters/cursor/transport-retry.ts +46 -1
  12. package/src/adapters/cursor.ts +4 -0
  13. package/src/adapters/google.ts +7 -7
  14. package/src/adapters/kiro/adapter.ts +42 -1
  15. package/src/adapters/kiro/payload.ts +17 -3
  16. package/src/adapters/kiro/reasoning.ts +70 -7
  17. package/src/adapters/kiro/stream.ts +8 -2
  18. package/src/adapters/kiro/wire.ts +2 -1
  19. package/src/adapters/kiro-events.ts +21 -13
  20. package/src/adapters/kiro-retry.ts +23 -4
  21. package/src/adapters/openai-chat/errors.ts +116 -0
  22. package/src/adapters/openai-chat/messages.ts +346 -0
  23. package/src/adapters/openai-chat/passthrough.ts +146 -0
  24. package/src/adapters/openai-chat/response-events.ts +117 -0
  25. package/src/adapters/openai-chat/tool-call-validation.ts +200 -0
  26. package/src/adapters/openai-chat/tool-name-registry.ts +166 -0
  27. package/src/adapters/openai-chat/tool-schema.ts +495 -0
  28. package/src/adapters/openai-chat/wire.ts +50 -0
  29. package/src/adapters/openai-chat.ts +40 -1452
  30. package/src/adapters/openai-responses/canonical-forward.ts +202 -0
  31. package/src/adapters/openai-responses/image-gen.ts +406 -0
  32. package/src/adapters/openai-responses/internal.ts +3 -0
  33. package/src/adapters/openai-responses/passthrough.ts +642 -0
  34. package/src/adapters/openai-responses/prompt-cache.ts +83 -0
  35. package/src/adapters/openai-responses/reasoning.ts +220 -0
  36. package/src/adapters/openai-responses/request-strips.ts +185 -0
  37. package/src/adapters/openai-responses/tool-output-recovery.ts +509 -0
  38. package/src/adapters/openai-responses/tool-schema.ts +293 -0
  39. package/src/adapters/openai-responses/web-search.ts +156 -0
  40. package/src/adapters/openai-responses.ts +4 -2625
  41. package/src/bridge/errors.ts +58 -0
  42. package/src/bridge/internal.ts +174 -0
  43. package/src/bridge/response-json.ts +630 -0
  44. package/src/bridge/sse.ts +1462 -0
  45. package/src/bridge.ts +5 -2204
  46. package/src/chat/inbound.ts +12 -1
  47. package/src/claude/desktop-profile.ts +66 -9
  48. package/src/claude/outbound.ts +18 -0
  49. package/src/cli/account-main.ts +1 -1
  50. package/src/cli/capabilities.ts +2 -2
  51. package/src/cli/combo.ts +10 -1
  52. package/src/cli/index.ts +48 -5
  53. package/src/cli/registry.ts +2 -1
  54. package/src/cli/system-command.ts +4 -4
  55. package/src/clients/config-export.ts +7 -3
  56. package/src/codex/account-label.ts +14 -3
  57. package/src/codex/account-lifecycle.ts +3 -0
  58. package/src/codex/account-store.ts +184 -35
  59. package/src/codex/account-usability.ts +21 -0
  60. package/src/codex/auth-api/account-list.ts +507 -0
  61. package/src/codex/auth-api/http.ts +32 -0
  62. package/src/codex/auth-api/login-flow.ts +566 -0
  63. package/src/codex/auth-api/login-state.ts +64 -0
  64. package/src/codex/auth-api/main-account-probe.ts +331 -0
  65. package/src/codex/auth-api/pool-mode-gate.ts +274 -0
  66. package/src/codex/auth-api/pool-quota-probe.ts +512 -0
  67. package/src/codex/auth-api/reset-credit-service.ts +431 -0
  68. package/src/codex/auth-api/routes.ts +425 -0
  69. package/src/codex/auth-api/runtime-config.ts +48 -0
  70. package/src/codex/auth-api.ts +27 -3118
  71. package/src/codex/auth-context.ts +252 -35
  72. package/src/codex/catalog/aggregation.ts +80 -1
  73. package/src/codex/catalog/auto-review.ts +507 -0
  74. package/src/codex/catalog/build-entries.ts +981 -0
  75. package/src/codex/catalog/combo-member.ts +375 -0
  76. package/src/codex/catalog/derive-entry.ts +229 -0
  77. package/src/codex/catalog/effort.ts +0 -1
  78. package/src/codex/catalog/gated-native-warn.ts +63 -0
  79. package/src/codex/catalog/gather-capture.ts +533 -0
  80. package/src/codex/catalog/model-hints.ts +691 -0
  81. package/src/codex/catalog/model-visibility.ts +305 -0
  82. package/src/codex/catalog/provider-fetch.ts +52 -2942
  83. package/src/codex/catalog/provider-models.ts +685 -0
  84. package/src/codex/catalog/remote.ts +30 -0
  85. package/src/codex/catalog/restore.ts +132 -0
  86. package/src/codex/catalog/retained-sync.ts +714 -0
  87. package/src/codex/catalog/routed-gather.ts +895 -0
  88. package/src/codex/catalog/subagent-roster.ts +176 -0
  89. package/src/codex/catalog/sync.ts +52 -2698
  90. package/src/codex/cli-install-provenance.ts +7 -1
  91. package/src/codex/convergence.ts +7 -2
  92. package/src/codex/desktop-app/types.ts +11 -2
  93. package/src/codex/desktop-app/windows.ts +5 -5
  94. package/src/codex/inject/config-toml.ts +563 -0
  95. package/src/codex/inject/remove.ts +192 -0
  96. package/src/codex/inject/restore.ts +567 -0
  97. package/src/codex/inject/routing-classify.ts +109 -0
  98. package/src/codex/inject/routing-target.ts +125 -0
  99. package/src/codex/inject.ts +89 -1444
  100. package/src/codex/lineage.ts +458 -0
  101. package/src/codex/model-entitlements.ts +152 -15
  102. package/src/codex/pool-refresh-backoff.ts +161 -0
  103. package/src/codex/quota-rejection.ts +104 -15
  104. package/src/codex/routing/active-account.ts +194 -0
  105. package/src/codex/routing/cache-affinity.ts +70 -0
  106. package/src/codex/routing/cooldown-math.ts +285 -0
  107. package/src/codex/routing/health-store.ts +402 -0
  108. package/src/codex/routing/probe-lease.ts +358 -0
  109. package/src/codex/routing/selection.ts +780 -0
  110. package/src/codex/routing/thread-affinity.ts +586 -0
  111. package/src/codex/routing/transient-hold-dispatch.ts +141 -0
  112. package/src/codex/routing.ts +370 -2271
  113. package/src/codex/shim-fingerprint.ts +223 -0
  114. package/src/codex/shim-inspect.ts +175 -0
  115. package/src/codex/shim-probe.ts +367 -0
  116. package/src/codex/shim-restore-lock.ts +169 -0
  117. package/src/codex/shim-state-file.ts +151 -0
  118. package/src/codex/shim-templates.ts +265 -0
  119. package/src/codex/shim.ts +48 -1268
  120. package/src/codex/warmup.ts +1 -1
  121. package/src/combos/failover.ts +85 -0
  122. package/src/combos/request.ts +17 -10
  123. package/src/combos/types.ts +23 -2
  124. package/src/config/diagnostics.ts +705 -0
  125. package/src/config/feature-flags.ts +55 -0
  126. package/src/config/live-reconcile.ts +403 -0
  127. package/src/config/load-degrade.ts +880 -0
  128. package/src/config/mutation-lock.ts +244 -0
  129. package/src/config/openai-tier-backup.ts +268 -0
  130. package/src/config/pending-teardown.ts +31 -0
  131. package/src/config/persist-unlocked.ts +92 -0
  132. package/src/config/proxy-env.ts +188 -0
  133. package/src/config/salvage.ts +244 -0
  134. package/src/config/schema/config-schema.ts +640 -0
  135. package/src/config/schema/leaf-validators.ts +855 -0
  136. package/src/config/warn-memo.ts +28 -0
  137. package/src/config.ts +234 -4481
  138. package/src/generated/compatibility-version.json +649 -121
  139. package/src/images/loop.ts +1 -1
  140. package/src/lib/errors.ts +17 -0
  141. package/src/lib/request-execution-budget.ts +198 -23
  142. package/src/lib/spend-reservation-ledger.ts +958 -0
  143. package/src/lib/state-store-registrations.ts +6 -2
  144. package/src/lib/test-home-guard.ts +85 -1
  145. package/src/lib/upstream-retry.ts +132 -21
  146. package/src/lib/windows-elevation.ts +76 -14
  147. package/src/lib/workflow-budget.ts +553 -30
  148. package/src/oauth/index.ts +2 -2
  149. package/src/oauth/key-providers.ts +2 -2
  150. package/src/providers/kiro-models.ts +4 -3
  151. package/src/providers/label.ts +19 -1
  152. package/src/providers/model-discovery.ts +16 -0
  153. package/src/providers/quota/account-cache.ts +441 -0
  154. package/src/providers/quota/antigravity.ts +295 -0
  155. package/src/providers/quota/report-cache.ts +320 -0
  156. package/src/providers/quota/vendor-probes-key.ts +1243 -0
  157. package/src/providers/quota/vendor-probes-oauth.ts +590 -0
  158. package/src/providers/quota.ts +324 -3079
  159. package/src/providers/registry/entries-core.ts +1228 -0
  160. package/src/providers/registry/entries-extended.ts +1213 -0
  161. package/src/providers/registry/model-seeds.ts +912 -0
  162. package/src/providers/registry/types.ts +352 -0
  163. package/src/providers/registry.ts +24 -3536
  164. package/src/responses/continuation-ownership.ts +29 -0
  165. package/src/responses/reasoning-envelope.ts +6 -3
  166. package/src/responses/state/replay-fingerprint.ts +80 -0
  167. package/src/responses/state/snapshot-codec.ts +104 -0
  168. package/src/responses/state/spill-failure.ts +118 -0
  169. package/src/responses/state/spill-queue.ts +665 -0
  170. package/src/responses/state/temp-recovery.ts +257 -0
  171. package/src/responses/state.ts +82 -1143
  172. package/src/routing/identity-domains.ts +456 -0
  173. package/src/routing/probe-lease.ts +613 -0
  174. package/src/server/chat-completions.ts +3 -1
  175. package/src/server/chat-native.ts +37 -9
  176. package/src/server/index/bounded-request.ts +88 -0
  177. package/src/server/index/live-sideband.ts +601 -0
  178. package/src/server/index/serve-options.ts +1766 -0
  179. package/src/server/index/startup-warnings.ts +213 -0
  180. package/src/server/index/websocket-handler.ts +339 -0
  181. package/src/server/index.ts +45 -2552
  182. package/src/server/inspection-tee.ts +107 -0
  183. package/src/server/live.ts +46 -1
  184. package/src/server/management/combo-routes.ts +10 -1
  185. package/src/server/management/route-registry.ts +26 -23
  186. package/src/server/management/shared.ts +8 -5
  187. package/src/server/management/workflow-budget-routes.ts +133 -0
  188. package/src/server/management-api.ts +12 -0
  189. package/src/server/relay-eager.ts +2 -0
  190. package/src/server/relay.ts +14 -19
  191. package/src/server/request-log-conversation.ts +9 -7
  192. package/src/server/request-log.ts +372 -4
  193. package/src/server/response-log-body.ts +153 -0
  194. package/src/server/responses/account-change-state.ts +307 -0
  195. package/src/server/responses/adapter-continuation.ts +540 -0
  196. package/src/server/responses/adapter-delivery.ts +208 -0
  197. package/src/server/responses/adapter-dispatch.ts +1042 -0
  198. package/src/server/responses/codex-ws-wire.ts +5 -0
  199. package/src/server/responses/collaboration.ts +74 -4
  200. package/src/server/responses/combo-session-recall.ts +68 -8
  201. package/src/server/responses/compact.ts +113 -17
  202. package/src/server/responses/completion-policy.ts +33 -0
  203. package/src/server/responses/core-auth.ts +529 -0
  204. package/src/server/responses/core-codex-account.ts +907 -0
  205. package/src/server/responses/core-combo-failure.ts +210 -0
  206. package/src/server/responses/core-combo.ts +787 -0
  207. package/src/server/responses/core-errors.ts +170 -0
  208. package/src/server/responses/core-lifetime.ts +95 -0
  209. package/src/server/responses/core-normalize.ts +350 -0
  210. package/src/server/responses/core-opaque-recovery.ts +380 -0
  211. package/src/server/responses/core-options.ts +159 -0
  212. package/src/server/responses/core-replay.ts +298 -0
  213. package/src/server/responses/core.ts +192 -8893
  214. package/src/server/responses/encrypted-payload.ts +0 -1
  215. package/src/server/responses/input-admission.ts +126 -6
  216. package/src/server/responses/passthrough-delivery.ts +869 -0
  217. package/src/server/responses/passthrough-dispatch.ts +1494 -0
  218. package/src/server/responses/passthrough-error.ts +38 -2
  219. package/src/server/responses/passthrough-execution.ts +54 -0
  220. package/src/server/responses/request-prepare.ts +1080 -0
  221. package/src/server/responses/request-send-budget.ts +259 -0
  222. package/src/server/responses/request-sidecar-auth.ts +149 -0
  223. package/src/server/responses/request-spend.ts +147 -0
  224. package/src/server/responses/request-transport.ts +803 -0
  225. package/src/server/responses/response-effects.ts +157 -0
  226. package/src/server/responses/run-turn-execution.ts +476 -0
  227. package/src/server/responses/sidecar-execution.ts +463 -0
  228. package/src/server/responses/terminal-guard.ts +65 -4
  229. package/src/server/responses-image-gen-repair.ts +1 -1
  230. package/src/server/responses-undeclared-tool-guard.ts +9 -5
  231. package/src/server/workflow-refusal.ts +84 -0
  232. package/src/service/windows-ops.ts +210 -16
  233. package/src/service/windows-scheduler.ts +28 -21
  234. package/src/service.ts +1 -1
  235. package/src/types/config.ts +34 -1
  236. package/src/types/request.ts +8 -5
  237. package/src/types/tools.ts +24 -0
  238. package/src/types.ts +2 -0
  239. package/src/update/index.ts +10 -0
  240. package/src/update/stop-contract.d.mts +1 -0
  241. package/src/update/stop-contract.mjs +19 -0
  242. package/src/update/stop-decision.d.mts +1 -1
  243. package/src/update/stop-decision.mjs +12 -3
  244. package/src/usage/log.ts +147 -1
  245. package/src/usage/summary.ts +171 -21
  246. package/src/vision/anthropic-describe.ts +1 -1
  247. package/src/vision/describe.ts +5 -5
  248. package/src/web-search/anthropic-executor.ts +1 -1
  249. package/src/web-search/exa-executor.ts +1 -1
  250. package/src/web-search/executor.ts +1 -1
  251. package/src/web-search/gemini-executor.ts +1 -1
  252. package/src/web-search/loop.ts +1 -1
  253. package/src/web-search/ollama-executor.ts +1 -1
  254. package/src/web-search/parse.ts +67 -14
  255. package/src/web-search/passthrough-bridge.ts +64 -31
  256. package/src/web-search/xai-executor.ts +1 -1
@@ -0,0 +1,1462 @@
1
+ import type {
2
+ AdapterEvent,
3
+ OcxMessagePhase,
4
+ OcxProviderContinuationState,
5
+ OcxProviderOpaqueToolCallMetadata,
6
+ OcxReasoningReplayScopeRef,
7
+ OcxUsage,
8
+ } from "../types";
9
+ import { coerceIntegerToolArguments } from "../lib/tool-argument-integers";
10
+ import {
11
+ adapterFailureFromMessage,
12
+ classifyError,
13
+ cyberPolicyErrorType,
14
+ CYBER_POLICY_ERROR_CODE,
15
+ isCyberPolicyCode,
16
+ type OcxErrorPayload,
17
+ } from "../lib/errors";
18
+ import { redactSecretString } from "../lib/redact";
19
+ import { mayBecomePatchEnvelope, repairFreeformToolInput } from "../responses/apply-patch-envelope";
20
+ import { encodeCompactionSummary } from "../responses/compaction";
21
+ import { compileCodeModeHelperInput, resolveCodeModeHelperName } from "../responses/code-mode-helper-compat";
22
+ import { isTruncatedStopReason, truncationReasonFor } from "../responses/truncated-stop-reason";
23
+ import { encodeReasoningEnvelope, type ReasoningEnvelope } from "../responses/reasoning-envelope";
24
+ import { rememberReasoningForCall } from "../responses/reasoning-replay-cache";
25
+ import {
26
+ rememberAndSerializeExtraContent,
27
+ rememberExtraContentForReplay,
28
+ awaitThoughtSignatureDurability,
29
+ } from "../responses/thought-signature-replay";
30
+ import { resolveStallTimeoutSec } from "../stall-timeout";
31
+ import {
32
+ createCitationMarkerFilter,
33
+ stripCitationMarkers,
34
+ type CitationMarkerFilter,
35
+ } from "../responses/citation-markers";
36
+ import { declaresCodeModeExec, normalizeDeclaredToolName } from "../types";
37
+ import { appendSafeWebSearchSource, safeWebSearchSources } from "../web-search/sources";
38
+ import {
39
+ isTranslatorBudgetExceededError,
40
+ releaseTranslatedEvent,
41
+ createTranslatorBudget,
42
+ type TranslatorBudget,
43
+ type TranslatorBufferKind,
44
+ } from "../lib/translator-budget";
45
+ import { adapterFailureFromEvent, emptyChunks, joinChunks, ownedBudgetAbandonedMs, responsesUsage, toolCallArgumentsUsable, uuid, webSearchAction } from "./internal";
46
+ import type { OutputItem, StringChunks } from "./internal";
47
+
48
+ function sseEvent(name: string, data: Record<string, unknown>): string {
49
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
50
+ }
51
+
52
+ function responseError(status: number, type: string, message: string): OcxErrorPayload {
53
+ return classifyError(status, type, message);
54
+ }
55
+
56
+ export type ResponsesTerminalStatus = "completed" | "failed" | "incomplete";
57
+
58
+ export function bridgeToResponsesSSE(
59
+ events: AsyncIterable<AdapterEvent>,
60
+ modelId: string,
61
+ toolNsMap?: Map<string, { namespace: string; name: string; freeform?: true }>,
62
+ freeformToolNames?: Set<string>,
63
+ toolSearchToolNames?: Set<string>,
64
+ onCancel?: () => void,
65
+ heartbeatMs = 2_000,
66
+ options?: {
67
+ responseId?: string;
68
+ stallTimeoutSec?: number;
69
+ hideThinkingSummary?: boolean;
70
+ /**
71
+ * Remote compaction v2 turn: accumulate all assistant text and, on done, emit ONE synthetic
72
+ * `{type:"compaction", encrypted_content:"ocx1:"+base64(text)}` output item before
73
+ * response.completed — codex-rs collect_compaction_output requires exactly one.
74
+ */
75
+ compaction?: boolean;
76
+ /** One-shot: first non-empty text/thinking/raw-reasoning delta observed (WP4 TTFT). */
77
+ onFirstOutput?: () => void;
78
+ onTerminal?: (status: ResponsesTerminalStatus) => void;
79
+ onCompletedResponse?: (response: Record<string, unknown>, providerState?: OcxProviderContinuationState) => void;
80
+ /**
81
+ * Raw adapter-reported usage at the terminal event, BEFORE wire normalization.
82
+ * responsesUsage() always emits token-detail objects with zero defaults for strict
83
+ * clients (grok-build), which makes the wire unusable as a provenance source: the
84
+ * request log must not read synthetic zeros as measured cache/reasoning numbers
85
+ * (cache_detail_missing would be silently suppressed). Callers set logCtx.usage
86
+ * from this callback instead of re-parsing the bridged SSE.
87
+ */
88
+ onUsage?: (usage: OcxUsage | undefined) => void;
89
+ /** Request-visible tool names. When present, an upstream call outside this set fails closed. */
90
+ declaredToolNames?: ReadonlySet<string>;
91
+ /**
92
+ * Whether `declaredToolNames` is an authorization boundary this proxy enforces, or only the
93
+ * catalog used to normalize provider-invented names back to declared ones.
94
+ *
95
+ * Defaults to enforcing. The chat and Anthropic inbound wires set it false: those specs make
96
+ * the server relay a tool call and leave execution or refusal to the client's own runner, and
97
+ * harnesses on them legitimately defer part of their catalog (#4735).
98
+ *
99
+ * It is a separate flag rather than simply withholding `declaredToolNames`, because the set
100
+ * also drives `normalizeDeclaredToolName` and `declaresCodeModeExec`. Passing `undefined`
101
+ * turns those off too, so a provider that invents `default.lookup` for a declared `lookup`
102
+ * would reach the client under the invented name instead of the normalized one.
103
+ */
104
+ enforceDeclaredToolNames?: boolean;
105
+ /** Declared parameter schema per tool name; repairs integral-float integer args (#1611). */
106
+ toolParameterSchemas?: ReadonlyMap<string, Record<string, unknown>>;
107
+ /**
108
+ * Wire keep-alive shape. Codex-rs parses at the EVENT level (timeout(idle_timeout,
109
+ * stream.next()) over an eventsource_stream), so an SSE comment line dispatches no event
110
+ * and does NOT re-arm its idle timer — the keep-alive must be a typed frame the parser
111
+ * ignores via its catch-all (110 RCA, 30_patch-direction.md). grok-build's strict
112
+ * async-openai fork is the opposite: it dies on the unknown `response.heartbeat`
113
+ * variant but, being eventsource-based at the byte level, its idle handling tolerates
114
+ * comment lines. Default stays the typed frame; the grok surface opts into comments.
115
+ */
116
+ heartbeatStyle?: "typed" | "comment";
117
+ translatorBudget?: TranslatorBudget;
118
+ /**
119
+ * Conversation identity for the reasoning replay cache (issue #950).
120
+ * Provider call ids are not globally unique; scoping by thread keeps one
121
+ * conversation's reasoning out of another's continuations.
122
+ */
123
+ replayCacheScope?: OcxReasoningReplayScopeRef;
124
+ /**
125
+ * Test seam for the wire/stall beat loop. Production omits this and uses the
126
+ * global timers; injecting here must not change scheduling semantics.
127
+ */
128
+ timers?: {
129
+ setInterval: (handler: () => void, ms: number) => unknown;
130
+ clearInterval: (id: unknown) => void;
131
+ };
132
+ },
133
+ ): ReadableStream<Uint8Array> {
134
+ const replayCacheScope = options?.replayCacheScope;
135
+ const setBeatInterval = options?.timers?.setInterval ?? ((handler: () => void, ms: number) => setInterval(handler, ms));
136
+ const clearBeatInterval = options?.timers?.clearInterval ?? ((id: unknown) => clearInterval(id as ReturnType<typeof setInterval>));
137
+ // Freeform/custom tools (apply_patch, code-mode exec) carry their body in `input`; the
138
+ // model is given a function with `{input:string}`, so unwrap it here when relaying back
139
+ // as a custom_tool_call. Decorated apply_patch envelopes are repaired at this boundary.
140
+ const freeformInput = (
141
+ args: string,
142
+ toolName: string,
143
+ namespace?: string,
144
+ codeModeHelperName?: string,
145
+ ): string => {
146
+ const helper = resolveCodeModeHelperName(codeModeHelperName, toolName, args, namespace, options?.declaredToolNames);
147
+ return helper
148
+ ? compileCodeModeHelperInput(args, helper)
149
+ : repairFreeformToolInput(args, toolName, namespace);
150
+ };
151
+ // Best-effort unwrap of a PARTIAL freeform arg buffer for live input streaming
152
+ // (`response.custom_tool_call_input.delta` — codex-rs uses it for UI preview only;
153
+ // the completed custom_tool_call item stays authoritative). Compact `{"input":"...`
154
+ // buffers get their string value progressively unescaped; anything else streams raw.
155
+ const FREEFORM_WRAP_PREFIX = '{"input":"';
156
+ const freeformPartialInput = (args: string): string => {
157
+ if (!args.startsWith(FREEFORM_WRAP_PREFIX)) return args;
158
+ const body = args.slice(FREEFORM_WRAP_PREFIX.length);
159
+ let out = "";
160
+ for (let i = 0; i < body.length; i++) {
161
+ const c = body[i];
162
+ if (c === '"') break; // unescaped closing quote: value complete
163
+ if (c === "\\") {
164
+ const n = body[i + 1];
165
+ if (n === undefined) break; // escape split across chunks: wait for more
166
+ i++;
167
+ if (n === "n") out += "\n";
168
+ else if (n === "t") out += "\t";
169
+ else if (n === "r") out += "\r";
170
+ else if (n === "u") {
171
+ const hex = body.slice(i + 1, i + 5);
172
+ if (hex.length === 4 && /^[0-9a-fA-F]{4}$/.test(hex)) { out += String.fromCharCode(parseInt(hex, 16)); i += 4; }
173
+ else break; // incomplete \uXXXX: wait for more
174
+ } else out += n; // \" \\ \/ etc.
175
+ } else out += c;
176
+ }
177
+ return out;
178
+ };
179
+ // tool_search_call carries arguments as a JSON object ({query, limit}); parse the model's arg string.
180
+ const parseArgsObj = (args: string): Record<string, unknown> => {
181
+ try { const o = JSON.parse(args); return o && typeof o === "object" ? o : {}; } catch { return {}; }
182
+ };
183
+ const encoder = new TextEncoder();
184
+ // Default-budget safety net: omission is SAFE (default turn limits), never
185
+ // unbounded. Production callers always pass one; an owned default is disposed
186
+ // at terminal/cancel below.
187
+ const ownsBudget = !options?.translatorBudget;
188
+ const budget = options?.translatorBudget ?? createTranslatorBudget();
189
+ // Idempotent: safe to call at every stream-death path; disposal must come
190
+ // AFTER the final charges (emitDone), never inside reportTerminal.
191
+ const disposeOwnedBudget = () => { if (ownsBudget) budget.dispose(); };
192
+ // A dropped stream (never read, never cancelled) reaches no terminal path,
193
+ // so the owned budget would sit in liveBudgets for the process lifetime.
194
+ // One unref'd watchdog per owned budget bounds that to a timeout and clears
195
+ // itself on any settle (the delay is test-overridable).
196
+ const ownedWatchdog = ownsBudget
197
+ ? setTimeout(() => disposeOwnedBudget(), ownedBudgetAbandonedMs)
198
+ : undefined;
199
+ ownedWatchdog?.unref?.();
200
+ const clearOwnedWatchdog = () => {
201
+ if (ownedWatchdog !== undefined) clearTimeout(ownedWatchdog);
202
+ };
203
+ const bytesOf = (value: string): number => Buffer.byteLength(value);
204
+ const appendString = (
205
+ previous: StringChunks,
206
+ fragment: string,
207
+ kind: TranslatorBufferKind,
208
+ callId?: string,
209
+ ): StringChunks => {
210
+ const fragmentBytes = bytesOf(fragment);
211
+ if (fragmentBytes === 0) return previous;
212
+ const nextBytes = previous.bytes + fragmentBytes;
213
+ const scope = { kind, ...(callId ? { callId } : {}) };
214
+ const reservation = budget.reserveTransient(nextBytes, scope);
215
+ try {
216
+ previous.chunks.push(fragment);
217
+ const result: StringChunks = { chunks: previous.chunks, bytes: nextBytes };
218
+ reservation.commitRetained();
219
+ budget.releaseRetained(previous.bytes, scope);
220
+ return result;
221
+ } catch (error) {
222
+ reservation.release();
223
+ throw error;
224
+ }
225
+ };
226
+ // Tool-call arguments deliberately use plain string concatenation because
227
+ // downstream parsers and intermediate inspectors perform incremental JSON reads mid-stream.
228
+ // Converting tool args to StringChunks would require frequent join operations.
229
+ const appendStringDirect = (
230
+ previous: string,
231
+ previousBytes: number,
232
+ fragment: string,
233
+ kind: TranslatorBufferKind,
234
+ callId?: string,
235
+ ): { value: string; bytes: number } => {
236
+ const fragmentBytes = bytesOf(fragment);
237
+ const nextBytes = previousBytes + fragmentBytes;
238
+ const scope = { kind, ...(callId ? { callId } : {}) };
239
+ const reservation = budget.reserveTransient(nextBytes, scope);
240
+ try {
241
+ const value = previous + fragment;
242
+ reservation.commitRetained();
243
+ budget.releaseRetained(previousBytes, scope);
244
+ return { value, bytes: nextBytes };
245
+ } catch (error) {
246
+ reservation.release();
247
+ throw error;
248
+ }
249
+ };
250
+ const replaceRetainedString = (previousBytes: number, next: string, kind: TranslatorBufferKind): number => {
251
+ const nextBytes = bytesOf(next);
252
+ if (!budget) return nextBytes;
253
+ const reservation = budget.reserveTransient(nextBytes, { kind });
254
+ reservation.commitRetained();
255
+ budget.releaseRetained(previousBytes, { kind });
256
+ return nextBytes;
257
+ };
258
+ const chargeValue = (value: unknown, kind: TranslatorBufferKind): number => {
259
+ const bytes = bytesOf(JSON.stringify(value));
260
+ budget?.chargeRetained(bytes, { kind });
261
+ return bytes;
262
+ };
263
+ const responseId = options?.responseId ?? `resp_${uuid()}`;
264
+ let seq = 0;
265
+ // Set once the client is gone (cancel) or an enqueue throws on a torn-down controller, so we
266
+ // never enqueue again and never throw a second time inside start() — the RC2 double-throw that
267
+ // otherwise surfaced as proxy-side stream noise on every client disconnect.
268
+ let closed = false;
269
+ let clientCancelled = false;
270
+ let terminalReported = false;
271
+ const reportTerminal = (status: ResponsesTerminalStatus) => {
272
+ if (terminalReported || clientCancelled || closed) return;
273
+ terminalReported = true;
274
+ try { options?.onTerminal?.(status); } catch { /* terminal metrics must not break the stream */ }
275
+ clearOwnedWatchdog();
276
+ };
277
+ // RC3 keep-alive: Codex's idle timer is timeout(idle_timeout, stream.next()) over an
278
+ // eventsource_stream, which parses at the EVENT level — a comment-only frame dispatches no
279
+ // event, so it does NOT re-arm the timer (110 RCA). The default keep-alive is therefore a
280
+ // typed `response.heartbeat` frame the codex-rs parser ignores via `_ => Ok(None)`. The
281
+ // grok surface (strict async-openai decoder that dies on unknown variants) opts into SSE
282
+ // comment lines instead via options.heartbeatStyle. Emit whenever the *wire* has been
283
+ // silent, even if invisible adapter heartbeats are still flowing (web-search buffering +
284
+ // raw-byte progress). Upstream activity only resets the stall watchdog.
285
+ let upstreamActivity = false;
286
+ let wireActivity = false;
287
+ let beat: unknown;
288
+ let controller: ReadableStreamDefaultController<Uint8Array>;
289
+ let emittedFrames = 0;
290
+ let gated = false;
291
+ let stepping = false;
292
+ let terminateForTranslatorOverflow: ((error: unknown) => void) | undefined;
293
+ const emit = (name: string, data: Record<string, unknown>) => {
294
+ if (closed) return;
295
+ wireActivity = true;
296
+ try {
297
+ const frameText = sseEvent(name, { type: name, sequence_number: seq++, ...data });
298
+ const frameBytes = bytesOf(frameText);
299
+ const reservation = budget?.reserveTransient(frameBytes, { kind: "live_transient" });
300
+ const frame = encoder.encode(frameText);
301
+ reservation?.commitRetained();
302
+ controller.enqueue(frame);
303
+ budget?.releaseRetained(frameBytes, { kind: "live_transient" });
304
+ emittedFrames++;
305
+ } catch (error) {
306
+ if (isTranslatorBudgetExceededError(error)) {
307
+ terminateForTranslatorOverflow?.(error);
308
+ return;
309
+ }
310
+ closed = true;
311
+ disposeOwnedBudget();
312
+ }
313
+ };
314
+ const emitDone = () => {
315
+ if (closed) return;
316
+ try {
317
+ const done = "data: [DONE]\n\n";
318
+ const doneBytes = bytesOf(done);
319
+ const reservation = budget?.reserveTransient(doneBytes, { kind: "live_transient" });
320
+ const frame = encoder.encode(done);
321
+ reservation?.commitRetained();
322
+ controller.enqueue(frame);
323
+ budget?.releaseRetained(doneBytes, { kind: "live_transient" });
324
+ emittedFrames++;
325
+ } catch (error) {
326
+ if (isTranslatorBudgetExceededError(error)) {
327
+ terminateForTranslatorOverflow?.(error);
328
+ return;
329
+ }
330
+ closed = true;
331
+ }
332
+ };
333
+
334
+ const createdAt = Math.floor(Date.now() / 1000);
335
+ let outputIndex = 0;
336
+ const finishedItems: OutputItem[] = [];
337
+ const retainFinishedItem = (item: OutputItem, replacedBytes = 0, kind: TranslatorBufferKind = "retained_collectors") => {
338
+ const itemBytes = bytesOf(JSON.stringify(item));
339
+ const reservation = budget?.reserveTransient(itemBytes, { kind });
340
+ finishedItems.push(item);
341
+ reservation?.commitRetained();
342
+ if (replacedBytes > 0) budget?.releaseRetained(replacedBytes, { kind });
343
+ };
344
+
345
+ const responseSnapshot = (status: string, output: OutputItem[], endTurn?: boolean) => ({
346
+ id: responseId, object: "response", created_at: createdAt,
347
+ status, model: modelId, output, usage: null,
348
+ ...(endTurn !== undefined ? { end_turn: endTurn } : {}),
349
+ });
350
+
351
+ const heartbeatFrame = options?.heartbeatStyle === "comment"
352
+ ? encoder.encode(': opencodex heartbeat\n\n')
353
+ : encoder.encode('event: response.heartbeat\ndata: {"type":"response.heartbeat"}\n\n');
354
+ let stallTicks = 0;
355
+ const stallSec = resolveStallTimeoutSec(options?.stallTimeoutSec);
356
+ const maxStallTicks = Math.ceil((stallSec * 1000) / heartbeatMs);
357
+
358
+ let currentMsg: {
359
+ itemId: string;
360
+ outputIndex: number;
361
+ text: StringChunks;
362
+ citationFilter: CitationMarkerFilter;
363
+ phase?: OcxMessagePhase;
364
+ } | null = null;
365
+ let currentReasoning: { itemId: string; outputIndex: number; text: StringChunks } | null = null;
366
+ let currentRawReasoning: { itemId: string; outputIndex: number; text: StringChunks } | null = null;
367
+ // Anthropic extended-thinking round-trip state: the signature signs the CURRENT thinking
368
+ // block; redacted blocks are opaque payloads replayed verbatim. Attached to the reasoning
369
+ // item as an ocxr1 encrypted_content envelope on close. hiddenThinkingText collects the
370
+ // suppressed text under hideThinkingSummary so the signed text still round-trips.
371
+ let pendingSignature: string | undefined;
372
+ let pendingSignatureBytes = 0;
373
+ let pendingRedacted: string[] = [];
374
+ let hiddenThinking = emptyChunks();
375
+ const takeReasoningEnvelope = (hiddenText?: string): string | undefined => {
376
+ if (!pendingSignature && pendingRedacted.length === 0) return undefined;
377
+ const envelope: ReasoningEnvelope = {};
378
+ if (pendingSignature) envelope.sig = pendingSignature;
379
+ if (pendingRedacted.length > 0) envelope.red = pendingRedacted;
380
+ if (hiddenText) envelope.txt = hiddenText;
381
+ const previousBytes = pendingSignatureBytes
382
+ + pendingRedacted.reduce((sum, value) => sum + bytesOf(value), 0)
383
+ + (hiddenText ? hiddenThinking.bytes : 0);
384
+ const encoded = encodeReasoningEnvelope(envelope, budget);
385
+ const reservation = budget?.reserveTransient(bytesOf(encoded), { kind: "reasoning" });
386
+ pendingSignature = undefined;
387
+ pendingSignatureBytes = 0;
388
+ pendingRedacted = [];
389
+ reservation?.commitRetained();
390
+ budget?.releaseRetained(previousBytes, { kind: "reasoning" });
391
+ return encoded;
392
+ };
393
+ // hideThinkingSummary path: no visible reasoning item exists, but a signed thinking block
394
+ // must still round-trip — emit an envelope-only reasoning item (empty summary, no text leak).
395
+ const flushHiddenReasoningEnvelope = () => {
396
+ const hiddenText = joinChunks(hiddenThinking);
397
+ const encrypted = takeReasoningEnvelope(hiddenText || undefined);
398
+ hiddenThinking = emptyChunks();
399
+ if (!encrypted) return;
400
+ const itemId = `rs_${uuid()}`;
401
+ const item = { type: "reasoning", id: itemId, summary: [] as never[], encrypted_content: encrypted };
402
+ emit("response.output_item.added", { output_index: outputIndex, item });
403
+ emit("response.output_item.done", { output_index: outputIndex, item });
404
+ retainFinishedItem(item as OutputItem, bytesOf(encrypted), "reasoning");
405
+ outputIndex++;
406
+ };
407
+ // hideThinkingSummary for RAW reasoning (openai-chat reasoning_content, kiro tags): no
408
+ // visible reasoning item is emitted — the app renders nothing, so tool cells keep grouping
409
+ // like native models — but the text still round-trips in a txt-only ocxr1 envelope so
410
+ // preserveReasoningContentModels replay (GLM interleaved thinking) keeps working. Direct
411
+ // encodeReasoningEnvelope: takeReasoningEnvelope's sig/red guard would drop txt-only.
412
+ let hiddenRawReasoning = emptyChunks();
413
+ // Raw reasoning text flushed most recently, waiting for the tool call it
414
+ // preceded. Recorded into the replay cache on tool_call_start so a later
415
+ // continuation can re-attach it when history lost the reasoning item
416
+ // (issue #950). Kept until new reasoning/text arrives: parallel tool
417
+ // calls share the same preceding reasoning block.
418
+ let rawReasoningForNextToolCall = "";
419
+ const flushHiddenRawReasoning = () => {
420
+ const hiddenRawText = joinChunks(hiddenRawReasoning);
421
+ if (!hiddenRawText) return;
422
+ rawReasoningForNextToolCall = hiddenRawText;
423
+ const previousBytes = hiddenRawReasoning.bytes;
424
+ const encrypted = encodeReasoningEnvelope({ txt: hiddenRawText }, budget);
425
+ const reservation = budget?.reserveTransient(bytesOf(encrypted), { kind: "reasoning" });
426
+ hiddenRawReasoning = emptyChunks();
427
+ reservation?.commitRetained();
428
+ budget?.releaseRetained(previousBytes, { kind: "reasoning" });
429
+ const itemId = `rs_${uuid()}`;
430
+ const item = { type: "reasoning", id: itemId, summary: [] as never[], encrypted_content: encrypted };
431
+ emit("response.output_item.added", { output_index: outputIndex, item });
432
+ emit("response.output_item.done", { output_index: outputIndex, item });
433
+ retainFinishedItem(item as OutputItem, bytesOf(encrypted), "reasoning");
434
+ outputIndex++;
435
+ };
436
+ // Kiro reasoning round-trip. Kiro sends its encrypted blob at the END of a turn, while the
437
+ // assistant message is still open, so this CANNOT emit on arrival: the open message still
438
+ // owns `outputIndex` (it only advances on close), and an item emitted here would both reuse
439
+ // that index and land BEFORE the message — where the parser's backwards pairing drops it as
440
+ // orphaned. Stash it and flush after `done` has closed every open item instead.
441
+ let pendingKiroRedacted: string | undefined;
442
+ let pendingKiroRedactedBytes = 0;
443
+ const flushKiroRedactedReasoning = () => {
444
+ if (!pendingKiroRedacted) return;
445
+ const previousBytes = pendingKiroRedactedBytes;
446
+ const encrypted = encodeReasoningEnvelope({ krc: pendingKiroRedacted }, budget);
447
+ const reservation = budget?.reserveTransient(bytesOf(encrypted), { kind: "reasoning" });
448
+ pendingKiroRedacted = undefined;
449
+ pendingKiroRedactedBytes = 0;
450
+ reservation?.commitRetained();
451
+ budget?.releaseRetained(previousBytes, { kind: "reasoning" });
452
+ const itemId = `rs_${uuid()}`;
453
+ const item = { type: "reasoning", id: itemId, summary: [] as never[], encrypted_content: encrypted };
454
+ emit("response.output_item.added", { output_index: outputIndex, item });
455
+ emit("response.output_item.done", { output_index: outputIndex, item });
456
+ retainFinishedItem(item as OutputItem, bytesOf(encrypted), "reasoning");
457
+ outputIndex++;
458
+ };
459
+ // Full assistant text of a compaction turn (across message boundaries) — becomes the
460
+ // synthetic compaction item's payload on done.
461
+ let compaction = emptyChunks();
462
+ let currentToolCall: { itemId: string; outputIndex: number; callId: string; name: string; args: string; argsBytes: number; namespace?: string; freeform?: boolean; toolSearch?: boolean; inputEmitted?: string; codeModeHelperName?: string; providerMetadata?: OcxProviderOpaqueToolCallMetadata } | null = null;
463
+ // Open native web-search cell (between begin and end). Holds the output index allocated on
464
+ // begin so the matching done reuses it; closed as `failed` if the stream terminates early.
465
+ let currentWebSearch: { itemId: string; eventId: string; outputIndex: number } | null = null;
466
+ // Sources from completed web searches, awaiting the next assistant message. Attached as
467
+ // url_citation annotations on that message (the desktop app's Sources chip), then cleared so
468
+ // they bind to exactly one message. Deduped by URL across multiple searches in the turn.
469
+ let pendingWebSources: { url: string; title?: string }[] = [];
470
+ let pendingWebSourceBytes = 0;
471
+ const releasePendingWebSources = () => {
472
+ if (pendingWebSources.length === 0) return;
473
+ pendingWebSources = [];
474
+ budget?.releaseRetained(pendingWebSourceBytes, { kind: "tool_search_sources" });
475
+ pendingWebSourceBytes = 0;
476
+ };
477
+ const takeWebAnnotations = (): { type: string; url: string; title?: string; start_index: number; end_index: number }[] => {
478
+ if (pendingWebSources.length === 0) return [];
479
+ const anns = pendingWebSources.map(s => ({
480
+ type: "url_citation", url: s.url, ...(s.title ? { title: s.title } : {}), start_index: 0, end_index: 0,
481
+ }));
482
+ const annotationBytes = bytesOf(JSON.stringify(anns));
483
+ const reservation = budget?.reserveTransient(annotationBytes, { kind: "retained_collectors" });
484
+ reservation?.commitRetained();
485
+ releasePendingWebSources();
486
+ return anns;
487
+ };
488
+
489
+ const closeCurrentMessage = (inferredPhase?: OcxMessagePhase) => {
490
+ if (!currentMsg) return;
491
+ // Release anything the citation filter was holding for this message, then strip the
492
+ // accumulated text: closeCurrentMessage re-sends it in output_text.done and
493
+ // output_item.done, so filtering only the deltas would leave the markers in both.
494
+ const trailing = currentMsg.citationFilter.flush();
495
+ if (trailing) {
496
+ emit("response.output_text.delta", {
497
+ item_id: currentMsg.itemId, output_index: currentMsg.outputIndex,
498
+ content_index: 0, delta: trailing,
499
+ });
500
+ }
501
+ const messageText = stripCitationMarkers(joinChunks(currentMsg.text));
502
+ // Chat Completions has no message-phase field. Keep its live item provisional, then
503
+ // classify it only when the next adapter event proves whether this text led into more
504
+ // work or completed the turn. Explicit adapter phases always outrank this inference.
505
+ const phase = currentMsg.phase ?? inferredPhase;
506
+ // Bind any pending web-search citations to this assistant message (then they clear).
507
+ const annotations = takeWebAnnotations();
508
+ // Finalize the text part (Responses protocol). Without these .done events Codex never
509
+ // commits the content part and renders the message as truncated / cut off.
510
+ emit("response.output_text.done", {
511
+ item_id: currentMsg.itemId, output_index: currentMsg.outputIndex, content_index: 0, text: messageText,
512
+ });
513
+ emit("response.content_part.done", {
514
+ item_id: currentMsg.itemId, output_index: currentMsg.outputIndex, content_index: 0,
515
+ part: { type: "output_text", text: messageText, annotations },
516
+ });
517
+ const item = {
518
+ type: "message", id: currentMsg.itemId, status: "completed", role: "assistant",
519
+ content: [{ type: "output_text", text: messageText, annotations }],
520
+ ...(phase ? { phase } : {}),
521
+ };
522
+ emit("response.output_item.done", { output_index: currentMsg.outputIndex, item });
523
+ retainFinishedItem(item as OutputItem, currentMsg.text.bytes + bytesOf(JSON.stringify(annotations)));
524
+ outputIndex++;
525
+ currentMsg = null;
526
+ };
527
+
528
+ const closeCurrentReasoning = () => {
529
+ if (!currentReasoning) return;
530
+ const reasoningText = joinChunks(currentReasoning.text);
531
+ emit("response.reasoning_summary_text.done", {
532
+ item_id: currentReasoning.itemId, output_index: currentReasoning.outputIndex, summary_index: 0, text: reasoningText,
533
+ });
534
+ emit("response.reasoning_summary_part.done", {
535
+ item_id: currentReasoning.itemId, output_index: currentReasoning.outputIndex, summary_index: 0,
536
+ part: { type: "summary_text", text: reasoningText },
537
+ });
538
+ const encrypted = takeReasoningEnvelope();
539
+ const item = {
540
+ type: "reasoning", id: currentReasoning.itemId,
541
+ summary: [{ type: "summary_text", text: reasoningText }],
542
+ ...(encrypted ? { encrypted_content: encrypted } : {}),
543
+ };
544
+ emit("response.output_item.done", { output_index: currentReasoning.outputIndex, item });
545
+ retainFinishedItem(item as OutputItem, currentReasoning.text.bytes + bytesOf(encrypted ?? ""), "reasoning");
546
+ outputIndex++;
547
+ currentReasoning = null;
548
+ };
549
+
550
+ const closeCurrentRawReasoning = () => {
551
+ if (!currentRawReasoning) return;
552
+ const rawText = joinChunks(currentRawReasoning.text);
553
+ rawReasoningForNextToolCall = rawText;
554
+ emit("response.reasoning_text.done", {
555
+ item_id: currentRawReasoning.itemId, output_index: currentRawReasoning.outputIndex, content_index: 0, text: rawText,
556
+ });
557
+ const item = {
558
+ type: "reasoning", id: currentRawReasoning.itemId,
559
+ summary: [] as never[],
560
+ content: [{ type: "reasoning_text", text: rawText }],
561
+ };
562
+ emit("response.output_item.done", { output_index: currentRawReasoning.outputIndex, item });
563
+ retainFinishedItem(item as OutputItem, currentRawReasoning.text.bytes, "reasoning");
564
+ outputIndex++;
565
+ currentRawReasoning = null;
566
+ };
567
+
568
+ const closeCurrentToolCall = () => {
569
+ if (!currentToolCall) return;
570
+ // Empty input (no-arg tools like computer_use get_app_state / list_apps) must serialize as
571
+ // "{}", never "" — Codex echoes the call back as a function_call next turn, and JSON.parse("")
572
+ // would 400 the whole session ("invalid JSON arguments"), poisoning all later turns.
573
+ // #1611: Grok serializes integer arguments through a float, so `120000.0`
574
+ // reaches Codex and is REJECTED before the tool runs. Repair integral floats
575
+ // against the declared schema; a non-integral value stays an error.
576
+ const argsStr = coerceIntegerToolArguments(
577
+ currentToolCall.args || "{}",
578
+ options?.toolParameterSchemas?.get(currentToolCall.name),
579
+ currentToolCall.namespace === undefined ? currentToolCall.name : undefined,
580
+ );
581
+ // Finalize streamed function-call arguments so Codex commits the call (incl. MCP / computer_use).
582
+ if (!currentToolCall.freeform && !currentToolCall.toolSearch) {
583
+ emit("response.function_call_arguments.done", {
584
+ item_id: currentToolCall.itemId, output_index: currentToolCall.outputIndex, arguments: argsStr,
585
+ });
586
+ }
587
+ if (currentToolCall.freeform) {
588
+ emit("response.custom_tool_call_input.done", {
589
+ item_id: currentToolCall.itemId, output_index: currentToolCall.outputIndex,
590
+ ...(currentToolCall.namespace ? { namespace: currentToolCall.namespace } : {}),
591
+ input: freeformInput(currentToolCall.args, currentToolCall.name, currentToolCall.namespace, currentToolCall.codeModeHelperName),
592
+ });
593
+ }
594
+ // Freeform tools serialize as custom_tool_call without extra_content; remember the
595
+ // signature server-side regardless so the replayed call can be re-signed (#1735).
596
+ void rememberExtraContentForReplay(currentToolCall.callId, currentToolCall.providerMetadata, replayCacheScope);
597
+ const item = currentToolCall.toolSearch
598
+ ? {
599
+ type: "tool_search_call", id: currentToolCall.itemId,
600
+ call_id: currentToolCall.callId, execution: "client",
601
+ arguments: parseArgsObj(currentToolCall.args), status: "completed",
602
+ }
603
+ : currentToolCall.freeform
604
+ ? {
605
+ type: "custom_tool_call", id: currentToolCall.itemId,
606
+ call_id: currentToolCall.callId, name: currentToolCall.name,
607
+ ...(currentToolCall.namespace ? { namespace: currentToolCall.namespace } : {}),
608
+ input: freeformInput(currentToolCall.args, currentToolCall.name, currentToolCall.namespace, currentToolCall.codeModeHelperName), status: "completed",
609
+ }
610
+ : {
611
+ type: "function_call", id: currentToolCall.itemId,
612
+ call_id: currentToolCall.callId, name: currentToolCall.name,
613
+ arguments: argsStr, status: "completed",
614
+ ...(currentToolCall.namespace ? { namespace: currentToolCall.namespace } : {}),
615
+ // Provider-opaque metadata (issue #1735) rides the item so a client that replays
616
+ // this history can hand the signature back on the part it belongs to. The proxy
617
+ // also remembers it server-side for clients that never echo extra_content.
618
+ ...(rememberAndSerializeExtraContent(currentToolCall.callId, currentToolCall.providerMetadata, replayCacheScope).extra ?? {}),
619
+ };
620
+ emit("response.output_item.done", { output_index: currentToolCall.outputIndex, item });
621
+ retainFinishedItem(item as OutputItem);
622
+ budget?.closeCall(currentToolCall.callId);
623
+ outputIndex++;
624
+ currentToolCall = null;
625
+ };
626
+
627
+ // Terminal-error / incomplete path for an open tool call (#765 remainder).
628
+ // Closing via closeCurrentToolCall() would emit function_call_arguments.done and
629
+ // status:"completed" BEFORE response.failed — the client still sees an issued call.
630
+ // Cancel instead: no *.done argument frames, status:"incomplete" (same pattern as an
631
+ // in-flight web_search_call closing as "failed"). Args still serialize as "{}" when
632
+ // empty so echoed items cannot poison the next turn with JSON.parse("").
633
+ const failCurrentToolCall = () => {
634
+ if (!currentToolCall) return;
635
+ const argsStr = currentToolCall.args || "{}";
636
+ void rememberExtraContentForReplay(currentToolCall.callId, currentToolCall.providerMetadata, replayCacheScope);
637
+ const item = currentToolCall.toolSearch
638
+ ? {
639
+ type: "tool_search_call", id: currentToolCall.itemId,
640
+ call_id: currentToolCall.callId, execution: "client",
641
+ arguments: parseArgsObj(currentToolCall.args), status: "incomplete",
642
+ }
643
+ : currentToolCall.freeform
644
+ ? {
645
+ type: "custom_tool_call", id: currentToolCall.itemId,
646
+ call_id: currentToolCall.callId, name: currentToolCall.name,
647
+ ...(currentToolCall.namespace ? { namespace: currentToolCall.namespace } : {}),
648
+ input: freeformInput(currentToolCall.args, currentToolCall.name, currentToolCall.namespace, currentToolCall.codeModeHelperName), status: "incomplete",
649
+ }
650
+ : {
651
+ type: "function_call", id: currentToolCall.itemId,
652
+ call_id: currentToolCall.callId, name: currentToolCall.name,
653
+ arguments: argsStr, status: "incomplete",
654
+ ...(currentToolCall.namespace ? { namespace: currentToolCall.namespace } : {}),
655
+ // An incomplete call can still be persisted and replayed (max_output_tokens), so it
656
+ // carries the same metadata as the completed item — otherwise SSE and buffered JSON
657
+ // would disagree about whether the signature survives.
658
+ ...(rememberAndSerializeExtraContent(currentToolCall.callId, currentToolCall.providerMetadata, replayCacheScope).extra ?? {}),
659
+ };
660
+ emit("response.output_item.done", { output_index: currentToolCall.outputIndex, item });
661
+ retainFinishedItem(item as OutputItem);
662
+ budget?.closeCall(currentToolCall.callId);
663
+ outputIndex++;
664
+ currentToolCall = null;
665
+ };
666
+
667
+ const abortCurrentToolCallForTranslatorOverflow = () => {
668
+ if (!currentToolCall) return;
669
+ budget?.closeCall(currentToolCall.callId);
670
+ currentToolCall = null;
671
+ };
672
+
673
+ // Finalize an open web-search cell. `status` is "completed" on a normal end, or "failed" when
674
+ // the stream terminates (error/incomplete) while a search was still in flight, so Codex never
675
+ // leaves a "Searching the web" spinner spinning forever.
676
+ // `sources` rides on the done item (additive field; codex-rs serde ignores unknown fields) so
677
+ // downstream translators (claude outbound) can fill web_search_tool_result content.
678
+ const closeCurrentWebSearch = (status: "completed" | "failed", queries: string[], sources?: { url: string; title?: string }[]) => {
679
+ if (!currentWebSearch) return;
680
+ const item = {
681
+ type: "web_search_call", id: currentWebSearch.itemId, status,
682
+ action: webSearchAction(queries),
683
+ ...(sources && sources.length > 0 ? { sources } : {}),
684
+ };
685
+ emit("response.output_item.done", { output_index: currentWebSearch.outputIndex, item });
686
+ retainFinishedItem(item as OutputItem);
687
+ outputIndex++;
688
+ currentWebSearch = null;
689
+ };
690
+
691
+ // RC1: guarantee the Responses stream always ends with exactly one terminal event. Set true
692
+ // when a done/error/catch terminal is emitted; if the adapter generator returns without one
693
+ // we synthesize a terminal below, so Codex never hits the parser's
694
+ // "stream closed before response.completed" (responses.rs) -> ApiError::Stream.
695
+ // That synthesized terminal is response.incomplete with reason "adapter_eof", NOT
696
+ // response.completed: a generator that returns without a terminal event is a truncated
697
+ // stream, and reporting it as a clean finish is the failure mode this whole path exists
698
+ // to avoid. The comment said "completed" long after the code stopped doing that.
699
+ let terminated = false;
700
+ let firstOutputReported = false;
701
+ const reportFirstOutput = (event: AdapterEvent): void => {
702
+ if (firstOutputReported) return;
703
+ const nonEmpty = event.type === "text_delta"
704
+ ? event.text.length > 0
705
+ : event.type === "thinking_delta"
706
+ ? event.thinking.length > 0
707
+ : event.type === "reasoning_raw_delta"
708
+ ? event.text.length > 0
709
+ : false;
710
+ if (!nonEmpty) return;
711
+ firstOutputReported = true;
712
+ try { options?.onFirstOutput?.(); } catch { /* metrics must not break the stream */ }
713
+ };
714
+ const it = events[Symbol.asyncIterator]();
715
+ let iteratorStarted = false;
716
+ let iteratorReturned = false;
717
+ let upstreamDone = false;
718
+ const returnIterator = () => {
719
+ if (iteratorReturned) return;
720
+ iteratorReturned = true;
721
+ const finishReturn = () => {
722
+ try {
723
+ void it.return?.()?.catch(() => {});
724
+ } catch {
725
+ /* synchronous iterator cleanup failure is also best-effort */
726
+ }
727
+ };
728
+ // Async-generator return() before the first next() does not enter the generator, so its
729
+ // finally blocks cannot cancel prepared upstream bodies. The cancel hook has already
730
+ // aborted the turn; bootstrap one cleanup step, then close the iterator without awaiting it.
731
+ if (!iteratorStarted) {
732
+ iteratorStarted = true;
733
+ try {
734
+ void it.next().then(finishReturn, () => {}).catch(() => {});
735
+ } catch {
736
+ /* synchronous iterator start failure is also best-effort */
737
+ }
738
+ return;
739
+ }
740
+ finishReturn();
741
+ };
742
+ let upstreamCancelled = false;
743
+ const cancelUpstreamOnce = () => {
744
+ if (upstreamCancelled) return;
745
+ upstreamCancelled = true;
746
+ try { onCancel?.(); } catch { /* cancellation must not strand the client stream */ }
747
+ returnIterator();
748
+ };
749
+ let handlingTranslatorOverflow = false;
750
+ terminateForTranslatorOverflow = _error => {
751
+ if (handlingTranslatorOverflow || terminated || clientCancelled || closed) return;
752
+ handlingTranslatorOverflow = true;
753
+ abortCurrentToolCallForTranslatorOverflow();
754
+ currentWebSearch = null;
755
+ releasePendingWebSources();
756
+ const failure = adapterFailureFromEvent({
757
+ type: "error",
758
+ status: 502,
759
+ errorType: "upstream_error",
760
+ code: "translation_buffer_limit",
761
+ message: "upstream translation buffer exceeded the safe limit",
762
+ }).error;
763
+ const failedFrame = sseEvent("response.failed", {
764
+ type: "response.failed",
765
+ sequence_number: seq++,
766
+ response: {
767
+ ...responseSnapshot("failed", finishedItems),
768
+ error: failure,
769
+ last_error: failure,
770
+ },
771
+ });
772
+ try {
773
+ controller.enqueue(encoder.encode(failedFrame));
774
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
775
+ emittedFrames += 2;
776
+ } catch {
777
+ /* client already tore down the stream */
778
+ }
779
+ reportTerminal("failed");
780
+ terminated = true;
781
+ cancelUpstreamOnce();
782
+ if (beat !== undefined) clearBeatInterval(beat);
783
+ beat = undefined;
784
+ try { controller.close(); } catch { /* already closed */ }
785
+ closed = true;
786
+ disposeOwnedBudget();
787
+ gated = true;
788
+ stepping = false;
789
+ };
790
+ const attemptTerminationCleanup = (action: () => void): boolean => {
791
+ try {
792
+ action();
793
+ return !terminated && !closed;
794
+ } catch (error) {
795
+ if (!isTranslatorBudgetExceededError(error)) throw error;
796
+ terminateForTranslatorOverflow(error);
797
+ return false;
798
+ }
799
+ };
800
+ const step = async () => {
801
+ if (stepping || closed) return;
802
+ stepping = true;
803
+ gated = false;
804
+ const emittedAtStart = emittedFrames;
805
+ try {
806
+ while (!terminated && !closed && emittedFrames === emittedAtStart) {
807
+ iteratorStarted = true;
808
+ const next = await it.next();
809
+ // A cancel during this await disposes the owned budget; a late event
810
+ // must never be processed or charged against it. Exit step() outright:
811
+ // falling into EOF synthesis would let closeCurrentMessage() charge
812
+ // finished-item retention against the disposed budget.
813
+ if (closed || clientCancelled) {
814
+ gated = true;
815
+ stepping = false;
816
+ return;
817
+ }
818
+ if (next.done) { upstreamDone = true; break; }
819
+ const event = next.value;
820
+ let terminalEvent = false;
821
+ // Invisible adapter heartbeats (and buffered web-search progress) count as upstream
822
+ // liveness only — they must not suppress wire keepalives that re-arm Codex idle timers.
823
+ upstreamActivity = true;
824
+ stallTicks = 0;
825
+ reportFirstOutput(event);
826
+ // Compaction turns emit ONLY the synthetic compaction item + response.completed. The
827
+ // summary text is accumulated silently: emitting it as a normal assistant message would
828
+ // duplicate the summary if this response is ever replayed via previous_response_id
829
+ // expansion (rememberResponseState stores input + output). Codex ignores extra items but
830
+ // its compaction UI renders nothing mid-turn, so nothing is lost visually.
831
+ if (options?.compaction) {
832
+ if (event.type === "text_delta") {
833
+ compaction = appendString(
834
+ compaction,
835
+ event.text,
836
+ "retained_collectors",
837
+ );
838
+ continue;
839
+ }
840
+ if (event.type !== "done" && event.type !== "incomplete" && event.type !== "error") continue;
841
+ }
842
+ // Anthropic signature_delta supplies the latest signature, not an append-only
843
+ // fragment (anthropic-sdk-typescript MessageStream). Keep consecutive updates
844
+ // together; the next semantic event belongs to the following block.
845
+ if (pendingSignature !== undefined && event.type !== "thinking_signature" && event.type !== "heartbeat") {
846
+ if (currentReasoning) closeCurrentReasoning();
847
+ else flushHiddenReasoningEnvelope();
848
+ }
849
+ switch (event.type) {
850
+ case "assistant_boundary": {
851
+ // A guarded continuation starts a fresh assistant output item while keeping the
852
+ // intermediate, suspicious text in the same Responses turn.
853
+ if (currentMsg) closeCurrentMessage("commentary");
854
+ if (currentReasoning) closeCurrentReasoning();
855
+ if (currentRawReasoning) closeCurrentRawReasoning();
856
+ flushHiddenRawReasoning();
857
+ rawReasoningForNextToolCall = "";
858
+ if (currentToolCall) closeCurrentToolCall();
859
+ flushHiddenReasoningEnvelope();
860
+ break;
861
+ }
862
+ case "text_delta": {
863
+ if (currentReasoning) closeCurrentReasoning();
864
+ if (currentRawReasoning) closeCurrentRawReasoning();
865
+ flushHiddenRawReasoning();
866
+ // Reasoning consumed by a REAL text turn, not a tool call: no cache target.
867
+ // Empty text deltas must not wipe reasoning that precedes a tool call
868
+ // (chat-completions providers emit empty content deltas mid-tool-turn).
869
+ if (event.text.length > 0) rawReasoningForNextToolCall = "";
870
+ if (currentToolCall) closeCurrentToolCall();
871
+ // Only flush on an explicit phase change. A later delta that omits `phase` must
872
+ // keep appending to the current message rather than wiping the earlier phase.
873
+ if (currentMsg && event.phase !== undefined && currentMsg.phase !== event.phase) {
874
+ closeCurrentMessage("commentary");
875
+ }
876
+ if (!currentMsg) {
877
+ const itemId = `msg_${uuid()}`;
878
+ const item = {
879
+ type: "message", id: itemId, status: "in_progress", role: "assistant",
880
+ content: [] as { type: string; text: string; annotations: never[] }[],
881
+ ...(event.phase ? { phase: event.phase } : {}),
882
+ };
883
+ emit("response.output_item.added", { output_index: outputIndex, item });
884
+ emit("response.content_part.added", {
885
+ item_id: itemId, output_index: outputIndex, content_index: 0,
886
+ part: { type: "output_text", text: "", annotations: [] },
887
+ });
888
+ currentMsg = {
889
+ itemId, outputIndex, text: emptyChunks(),
890
+ citationFilter: createCitationMarkerFilter(),
891
+ ...(event.phase ? { phase: event.phase } : {}),
892
+ };
893
+ }
894
+ currentMsg.text = appendString(
895
+ currentMsg.text,
896
+ event.text,
897
+ "retained_collectors",
898
+ );
899
+ // A citation span can straddle a delta boundary, so the filter withholds an
900
+ // unterminated tail and releases it at close (#3150). The accumulator above
901
+ // keeps the raw text; it is stripped once in closeCurrentMessage.
902
+ const visible = currentMsg.citationFilter.push(event.text);
903
+ if (visible) {
904
+ emit("response.output_text.delta", {
905
+ item_id: currentMsg.itemId, output_index: currentMsg.outputIndex,
906
+ content_index: 0, delta: visible,
907
+ });
908
+ }
909
+ break;
910
+ }
911
+ case "thinking_delta": {
912
+ if (options?.hideThinkingSummary) {
913
+ // The hidden branch returns early, so flush any raw reasoning
914
+ // that preceded the thinking block and clear the replay-cache
915
+ // candidate — otherwise a stale reasoning_raw_delta would be
916
+ // recorded for a LATER tool call (CodeRabbit on #971).
917
+ flushHiddenRawReasoning();
918
+ rawReasoningForNextToolCall = "";
919
+ hiddenThinking = appendString(
920
+ hiddenThinking,
921
+ event.thinking,
922
+ "reasoning",
923
+ );
924
+ break;
925
+ }
926
+ if (currentMsg) closeCurrentMessage("commentary");
927
+ if (currentRawReasoning) closeCurrentRawReasoning();
928
+ flushHiddenRawReasoning();
929
+ if (event.thinking.length > 0) rawReasoningForNextToolCall = "";
930
+ if (currentToolCall) closeCurrentToolCall();
931
+ if (!currentReasoning) {
932
+ const itemId = `rs_${uuid()}`;
933
+ const item = { type: "reasoning", id: itemId, summary: [] as { type: string; text: string }[] };
934
+ emit("response.output_item.added", { output_index: outputIndex, item });
935
+ emit("response.reasoning_summary_part.added", {
936
+ item_id: itemId, output_index: outputIndex, summary_index: 0,
937
+ part: { type: "summary_text", text: "" },
938
+ });
939
+ currentReasoning = { itemId, outputIndex, text: emptyChunks() };
940
+ }
941
+ currentReasoning.text = appendString(
942
+ currentReasoning.text,
943
+ event.thinking,
944
+ "reasoning",
945
+ );
946
+ emit("response.reasoning_summary_text.delta", {
947
+ item_id: currentReasoning.itemId, output_index: currentReasoning.outputIndex,
948
+ summary_index: 0, delta: event.thinking,
949
+ });
950
+ break;
951
+ }
952
+ case "thinking_signature": {
953
+ pendingSignatureBytes = replaceRetainedString(pendingSignatureBytes, event.signature, "reasoning");
954
+ pendingSignature = event.signature;
955
+ // Delay closing until the next semantic event so a signature update cannot
956
+ // create another block or become attached to the following thinking text.
957
+ break;
958
+ }
959
+ case "redacted_thinking": {
960
+ if (currentMsg) closeCurrentMessage("commentary");
961
+ if (currentReasoning) closeCurrentReasoning();
962
+ if (currentRawReasoning) closeCurrentRawReasoning();
963
+ flushHiddenRawReasoning();
964
+ if (currentToolCall) closeCurrentToolCall();
965
+ budget?.chargeRetained(bytesOf(event.data), { kind: "reasoning" });
966
+ pendingRedacted.push(event.data);
967
+ // A redacted block is complete at content_block_start. Emit it here,
968
+ // not with a later thinking block or after a tool call at turn end.
969
+ flushHiddenReasoningEnvelope();
970
+ break;
971
+ }
972
+ case "kiro_redacted_reasoning": {
973
+ // Stash only — see flushKiroRedactedReasoning. One blob per turn, so last wins.
974
+ pendingKiroRedactedBytes = replaceRetainedString(pendingKiroRedactedBytes, event.data, "reasoning");
975
+ pendingKiroRedacted = event.data;
976
+ break;
977
+ }
978
+ case "reasoning_raw_delta": {
979
+ if (options?.hideThinkingSummary) {
980
+ hiddenRawReasoning = appendString(
981
+ hiddenRawReasoning,
982
+ event.text,
983
+ "reasoning",
984
+ );
985
+ break;
986
+ }
987
+ if (currentMsg) closeCurrentMessage("commentary");
988
+ if (currentReasoning) closeCurrentReasoning();
989
+ if (currentToolCall) closeCurrentToolCall();
990
+ if (!currentRawReasoning) {
991
+ const itemId = `rs_${uuid()}`;
992
+ const item = { type: "reasoning", id: itemId, summary: [] as { type: string; text: string }[] };
993
+ emit("response.output_item.added", { output_index: outputIndex, item });
994
+ currentRawReasoning = { itemId, outputIndex, text: emptyChunks() };
995
+ }
996
+ currentRawReasoning.text = appendString(
997
+ currentRawReasoning.text,
998
+ event.text,
999
+ "reasoning",
1000
+ );
1001
+ // Raw reasoning (openai-chat reasoning_content, kiro tags) rides the CONTENT
1002
+ // channel. Clients control raw-reasoning display; this text is not a
1003
+ // provider-authored summary.
1004
+ emit("response.reasoning_text.delta", {
1005
+ item_id: currentRawReasoning.itemId, output_index: currentRawReasoning.outputIndex,
1006
+ content_index: 0, delta: event.text,
1007
+ });
1008
+ break;
1009
+ }
1010
+ case "tool_call_start": {
1011
+ if (currentMsg) closeCurrentMessage("commentary");
1012
+ if (currentReasoning) closeCurrentReasoning();
1013
+ if (currentRawReasoning) closeCurrentRawReasoning();
1014
+ flushHiddenRawReasoning();
1015
+ if (rawReasoningForNextToolCall) {
1016
+ rememberReasoningForCall(event.id, rawReasoningForNextToolCall, replayCacheScope);
1017
+ }
1018
+ if (currentToolCall) closeCurrentToolCall();
1019
+ const effectiveName = normalizeDeclaredToolName(event.name, options?.declaredToolNames);
1020
+ const codeModeHelperName = effectiveName === "exec" && event.name !== effectiveName
1021
+ ? event.name
1022
+ : undefined;
1023
+ const mapped = toolNsMap?.get(effectiveName);
1024
+ const realName = mapped?.name ?? effectiveName;
1025
+ if (
1026
+ options?.declaredToolNames
1027
+ && options.enforceDeclaredToolNames !== false
1028
+ && !options.declaredToolNames.has(effectiveName)
1029
+ ) {
1030
+ const failure = responseError(
1031
+ 502,
1032
+ "upstream_error",
1033
+ `routed provider emitted undeclared client tool "${effectiveName}"; only request-declared tools may be called`,
1034
+ );
1035
+ emit("response.failed", {
1036
+ response: {
1037
+ ...responseSnapshot("failed", finishedItems),
1038
+ error: failure,
1039
+ last_error: failure,
1040
+ },
1041
+ });
1042
+ reportTerminal("failed");
1043
+ terminalEvent = true;
1044
+ break;
1045
+ }
1046
+ const ns = mapped?.namespace;
1047
+ const toolSearch = toolSearchToolNames?.has(realName) ?? false;
1048
+ const freeform = !toolSearch && (mapped
1049
+ ? mapped.freeform === true
1050
+ : (freeformToolNames?.has(realName) ?? false));
1051
+ const itemId = `${toolSearch ? "tsc" : freeform ? "ctc" : "fc"}_${uuid()}`;
1052
+ const item = toolSearch
1053
+ ? { type: "tool_search_call", id: itemId, call_id: event.id, execution: "client", arguments: {}, status: "in_progress" }
1054
+ : freeform
1055
+ ? { type: "custom_tool_call", id: itemId, call_id: event.id, name: realName, ...(ns ? { namespace: ns } : {}), input: "", status: "in_progress" }
1056
+ : { type: "function_call", id: itemId, call_id: event.id, name: realName, arguments: "", status: "in_progress", ...(ns ? { namespace: ns } : {}) };
1057
+ emit("response.output_item.added", { output_index: outputIndex, item });
1058
+ currentToolCall = { itemId, outputIndex, callId: event.id, name: realName, args: "", argsBytes: 0, namespace: ns, freeform, toolSearch, codeModeHelperName, providerMetadata: event.providerMetadata };
1059
+ budget?.openCall(event.id);
1060
+ break;
1061
+ }
1062
+ case "tool_call_delta": {
1063
+ if (currentToolCall) {
1064
+ ({ value: currentToolCall.args, bytes: currentToolCall.argsBytes } = appendStringDirect(
1065
+ currentToolCall.args,
1066
+ currentToolCall.argsBytes,
1067
+ event.arguments,
1068
+ "tool_args",
1069
+ currentToolCall.callId,
1070
+ ));
1071
+ if (!currentToolCall.freeform && !currentToolCall.toolSearch) {
1072
+ emit("response.function_call_arguments.delta", {
1073
+ item_id: currentToolCall.itemId, output_index: currentToolCall.outputIndex,
1074
+ delta: event.arguments,
1075
+ });
1076
+ }
1077
+ if (currentToolCall.freeform && !currentToolCall.codeModeHelperName) {
1078
+ // Hold while the buffer is still an ambiguous prefix of the JSON wrapper,
1079
+ // then stream only the unwrapped input suffix (never rewind on mode flips).
1080
+ if (!FREEFORM_WRAP_PREFIX.startsWith(currentToolCall.args)) {
1081
+ const full = freeformPartialInput(currentToolCall.args);
1082
+ const emitted = currentToolCall.inputEmitted ?? "";
1083
+ // Also hold a buffer that could still become a complete patch envelope:
1084
+ // at completion such a body is recompiled into an apply_patch helper call,
1085
+ // and streaming the envelope bytes first would be that same rewind.
1086
+ const mayCompile = declaresCodeModeExec(options?.declaredToolNames)
1087
+ && !currentToolCall.namespace
1088
+ && currentToolCall.name === "exec";
1089
+ if (!(mayCompile && mayBecomePatchEnvelope(full)) && full.startsWith(emitted) && full.length > emitted.length) {
1090
+ emit("response.custom_tool_call_input.delta", {
1091
+ item_id: currentToolCall.itemId, output_index: currentToolCall.outputIndex,
1092
+ delta: full.slice(emitted.length),
1093
+ });
1094
+ currentToolCall.inputEmitted = full;
1095
+ }
1096
+ }
1097
+ }
1098
+ }
1099
+ break;
1100
+ }
1101
+ case "tool_call_end": {
1102
+ // Fragments already streamed cannot be repaired. Refuse to complete a function call
1103
+ // whose assembled arguments do not parse — cancel the item and fail the turn so the
1104
+ // client never sees status:"completed" for unusable args (#765 stream remainder).
1105
+ if (
1106
+ currentToolCall
1107
+ && !currentToolCall.freeform
1108
+ && !currentToolCall.toolSearch
1109
+ && !toolCallArgumentsUsable(currentToolCall.args)
1110
+ ) {
1111
+ failCurrentToolCall();
1112
+ const failure = responseError(
1113
+ 502,
1114
+ "upstream_error",
1115
+ "upstream stream produced malformed tool call arguments",
1116
+ );
1117
+ emit("response.failed", {
1118
+ response: {
1119
+ ...responseSnapshot("failed", finishedItems),
1120
+ error: failure,
1121
+ last_error: failure,
1122
+ },
1123
+ });
1124
+ reportTerminal("failed");
1125
+ terminalEvent = true;
1126
+ break;
1127
+ }
1128
+ closeCurrentToolCall();
1129
+ break;
1130
+ }
1131
+ case "web_search_call_begin": {
1132
+ // Open the native search cell so Codex shows the "Searching the web" spinner WHILE the
1133
+ // sidecar runs. Close any other open item first, allocate this item's output index, and
1134
+ // hold it open until the matching `web_search_call_end` (or a terminal close).
1135
+ if (currentMsg) closeCurrentMessage("commentary");
1136
+ if (currentReasoning) closeCurrentReasoning();
1137
+ if (currentRawReasoning) closeCurrentRawReasoning();
1138
+ flushHiddenRawReasoning();
1139
+ if (currentToolCall) closeCurrentToolCall();
1140
+ if (currentWebSearch) closeCurrentWebSearch("completed", []);
1141
+ const wsItemId = `ws_${uuid()}`;
1142
+ emit("response.output_item.added", {
1143
+ output_index: outputIndex,
1144
+ item: { type: "web_search_call", id: wsItemId, status: "in_progress" },
1145
+ });
1146
+ currentWebSearch = { itemId: wsItemId, eventId: event.id, outputIndex };
1147
+ break;
1148
+ }
1149
+ case "web_search_call_end": {
1150
+ // The sidecar resolved — finalize the cell as "Searched <query>". If no begin opened
1151
+ // (defensive), synthesize the added frame first so the done has a matching item.
1152
+ if (!currentWebSearch || currentWebSearch.eventId !== event.id) {
1153
+ if (currentWebSearch) closeCurrentWebSearch("completed", []);
1154
+ const wsItemId2 = `ws_${uuid()}`;
1155
+ emit("response.output_item.added", {
1156
+ output_index: outputIndex,
1157
+ item: { type: "web_search_call", id: wsItemId2, status: "in_progress" },
1158
+ });
1159
+ currentWebSearch = { itemId: wsItemId2, eventId: event.id, outputIndex };
1160
+ }
1161
+ const safeSources = safeWebSearchSources(event.sources);
1162
+ closeCurrentWebSearch(event.status ?? "completed", event.queries, safeSources);
1163
+ // Queue this search's sources for the next assistant message (dedup by URL).
1164
+ if (safeSources.length > 0) {
1165
+ for (const source of safeSources) {
1166
+ if (appendSafeWebSearchSource(pendingWebSources, source)) {
1167
+ pendingWebSourceBytes += chargeValue(source, "tool_search_sources");
1168
+ }
1169
+ }
1170
+ }
1171
+ break;
1172
+ }
1173
+ case "done": {
1174
+ if (currentMsg) closeCurrentMessage(event.stopReason ? undefined : "final_answer");
1175
+ if (currentReasoning) closeCurrentReasoning();
1176
+ if (currentRawReasoning) closeCurrentRawReasoning();
1177
+ flushHiddenRawReasoning();
1178
+ if (currentToolCall) {
1179
+ if (isTruncatedStopReason(event.stopReason)) failCurrentToolCall();
1180
+ else closeCurrentToolCall();
1181
+ }
1182
+ // A search still in flight when upstream truncates never returned results, so it
1183
+ // takes the same "failed" status as the error/incomplete terminals below.
1184
+ if (currentWebSearch) closeCurrentWebSearch(isTruncatedStopReason(event.stopReason) ? "failed" : "completed", []);
1185
+ releasePendingWebSources();
1186
+ // Redacted-only turns (or hidden thinking without a trailing signature event) still
1187
+ // need their envelope-only reasoning item so the blocks replay next turn.
1188
+ flushHiddenReasoningEnvelope();
1189
+ // After every close above, so the blob lands AFTER the assistant message it belongs
1190
+ // to and the parser's backwards pairing finds it.
1191
+ flushKiroRedactedReasoning();
1192
+ // Truncated turns must never install replacement history (#422). The buffered path
1193
+ // has always checked this; streaming emitted the item BEFORE reading stopReason, so
1194
+ // a max_tokens/content_filter turn shipped a half-written summary and then declared
1195
+ // itself incomplete — the same hazard, one branch over.
1196
+ if (options?.compaction && !isTruncatedStopReason(event.stopReason)) {
1197
+ // Exactly one compaction item per turn; codex-rs takes the first and fatals on 0.
1198
+ const item = {
1199
+ type: "compaction", id: `cmp_${uuid()}`,
1200
+ encrypted_content: event.compactionEncryptedContent ?? encodeCompactionSummary(joinChunks(compaction)),
1201
+ };
1202
+ emit("response.output_item.done", { output_index: outputIndex, item });
1203
+ retainFinishedItem(item as OutputItem, event.compactionEncryptedContent
1204
+ ? bytesOf(event.compactionEncryptedContent)
1205
+ : compaction.bytes);
1206
+ outputIndex++;
1207
+ }
1208
+ // Recognize every adapter's truncation vocabulary, not just the canonical pair.
1209
+ // Suppression and terminal status must agree: withholding the compaction item while
1210
+ // still reporting success hands codex-rs a completed response with zero compaction
1211
+ // items, which it treats as fatal.
1212
+ if (truncationReasonFor(event.stopReason)) {
1213
+ // Upstream stopped before a normal completion. Surface as incomplete so the
1214
+ // client can distinguish a truncated/filtered turn from a finished one.
1215
+ // #1926 gap 2: bound the window in which a handed-out thought signature is
1216
+ // not yet durable before the turn becomes externally terminal.
1217
+ await awaitThoughtSignatureDurability();
1218
+ const response = {
1219
+ ...responseSnapshot("incomplete", finishedItems, event.endTurn),
1220
+ usage: responsesUsage(event.usage),
1221
+ incomplete_details: {
1222
+ reason: truncationReasonFor(event.stopReason) ?? "content_filter",
1223
+ },
1224
+ };
1225
+ // Cache max-output partials so previous_response_id replay can continue them;
1226
+ // rememberResponseState rejects content-filtered incomplete responses.
1227
+ options?.onCompletedResponse?.(response, event.providerState);
1228
+ options?.onUsage?.(event.usage);
1229
+ emit("response.incomplete", { response });
1230
+ reportTerminal("incomplete");
1231
+ } else {
1232
+ await awaitThoughtSignatureDurability();
1233
+ const response = { ...responseSnapshot("completed", finishedItems, event.endTurn), usage: responsesUsage(event.usage) };
1234
+ options?.onCompletedResponse?.(response, event.providerState);
1235
+ options?.onUsage?.(event.usage);
1236
+ emit("response.completed", {
1237
+ response,
1238
+ });
1239
+ reportTerminal("completed");
1240
+ }
1241
+ terminalEvent = true;
1242
+ break;
1243
+ }
1244
+ case "incomplete": {
1245
+ if (currentMsg) closeCurrentMessage();
1246
+ if (currentReasoning) closeCurrentReasoning();
1247
+ if (currentRawReasoning) closeCurrentRawReasoning();
1248
+ flushHiddenRawReasoning();
1249
+ if (currentToolCall) failCurrentToolCall();
1250
+ if (currentWebSearch) closeCurrentWebSearch("failed", []);
1251
+ releasePendingWebSources();
1252
+ flushHiddenReasoningEnvelope();
1253
+ options?.onUsage?.(event.usage);
1254
+ await awaitThoughtSignatureDurability();
1255
+ emit("response.incomplete", {
1256
+ response: {
1257
+ ...responseSnapshot("incomplete", finishedItems, event.endTurn),
1258
+ usage: responsesUsage(event.usage),
1259
+ incomplete_details: {
1260
+ reason: event.reason,
1261
+ ...(event.message ? { message: event.message } : {}),
1262
+ ...(event.retryable !== undefined ? { retryable: event.retryable } : {}),
1263
+ },
1264
+ },
1265
+ });
1266
+ reportTerminal("incomplete");
1267
+ terminalEvent = true;
1268
+ break;
1269
+ }
1270
+ case "error": {
1271
+ if (event.code === "translation_buffer_limit") {
1272
+ terminateForTranslatorOverflow(event);
1273
+ return;
1274
+ }
1275
+ if (currentMsg) closeCurrentMessage();
1276
+ if (currentReasoning) closeCurrentReasoning();
1277
+ if (currentRawReasoning) closeCurrentRawReasoning();
1278
+ flushHiddenRawReasoning();
1279
+ if (currentToolCall) failCurrentToolCall();
1280
+ if (currentWebSearch) closeCurrentWebSearch("failed", []);
1281
+ releasePendingWebSources();
1282
+ const failure = adapterFailureFromEvent(event);
1283
+ if (event.usage) options?.onUsage?.(event.usage);
1284
+ await awaitThoughtSignatureDurability();
1285
+ emit("response.failed", {
1286
+ response: {
1287
+ ...responseSnapshot("failed", finishedItems),
1288
+ // Partial consumption from a mid-stream upstream failure: surfaced so the request
1289
+ // log can record real tokens instead of usageStatus "unreported" with 0.
1290
+ ...(event.usage ? { usage: responsesUsage(event.usage) } : {}),
1291
+ error: failure.error,
1292
+ last_error: failure.error,
1293
+ ...(isCyberPolicyCode(failure.error.code)
1294
+ ? { retryable: false }
1295
+ : event.retryable !== undefined ? { retryable: event.retryable } : {}),
1296
+ },
1297
+ });
1298
+ reportTerminal("failed");
1299
+ terminalEvent = true;
1300
+ break;
1301
+ }
1302
+ }
1303
+ if (terminalEvent) {
1304
+ cancelUpstreamOnce();
1305
+ terminated = true;
1306
+ break;
1307
+ }
1308
+ }
1309
+ } catch (err) {
1310
+ if (isTranslatorBudgetExceededError(err)) {
1311
+ terminateForTranslatorOverflow(err);
1312
+ return;
1313
+ }
1314
+ if (!terminated) {
1315
+ if (!attemptTerminationCleanup(() => {
1316
+ flushHiddenRawReasoning();
1317
+ if (currentToolCall) failCurrentToolCall();
1318
+ if (currentWebSearch) closeCurrentWebSearch("failed", []);
1319
+ releasePendingWebSources();
1320
+ })) return;
1321
+ const failure = responseError(
1322
+ 500,
1323
+ "proxy_error",
1324
+ redactSecretString(err instanceof Error ? err.message : String(err)),
1325
+ );
1326
+ emit("response.failed", {
1327
+ response: {
1328
+ ...responseSnapshot("failed", finishedItems),
1329
+ error: failure,
1330
+ last_error: failure,
1331
+ ...(isCyberPolicyCode(failure.code) ? { retryable: false } : {}),
1332
+ },
1333
+ });
1334
+ reportTerminal("failed");
1335
+ cancelUpstreamOnce();
1336
+ terminated = true;
1337
+ }
1338
+ }
1339
+
1340
+ if (!terminated && !upstreamDone) {
1341
+ gated = true;
1342
+ stepping = false;
1343
+ return;
1344
+ }
1345
+ if (beat !== undefined) { clearBeatInterval(beat); beat = undefined; }
1346
+
1347
+ if (!terminated) {
1348
+ // The adapter generator ended without an explicit done/error event. Mark as incomplete
1349
+ // rather than completed so Codex can distinguish a clean finish from a truncated stream.
1350
+ if (!attemptTerminationCleanup(() => {
1351
+ if (currentMsg) closeCurrentMessage();
1352
+ if (currentReasoning) closeCurrentReasoning();
1353
+ if (currentRawReasoning) closeCurrentRawReasoning();
1354
+ flushHiddenRawReasoning();
1355
+ if (currentToolCall) failCurrentToolCall();
1356
+ if (currentWebSearch) closeCurrentWebSearch("failed", []);
1357
+ releasePendingWebSources();
1358
+ })) return;
1359
+ options?.onUsage?.(undefined);
1360
+ await awaitThoughtSignatureDurability();
1361
+ emit("response.incomplete", {
1362
+ response: {
1363
+ ...responseSnapshot("incomplete", finishedItems),
1364
+ usage: responsesUsage(undefined),
1365
+ incomplete_details: { reason: "adapter_eof" },
1366
+ },
1367
+ });
1368
+ reportTerminal("incomplete");
1369
+ terminated = true;
1370
+ }
1371
+
1372
+ emitDone();
1373
+ try {
1374
+ controller.close();
1375
+ } catch {
1376
+ /* already closed (e.g. client cancelled) */
1377
+ }
1378
+ closed = true;
1379
+ disposeOwnedBudget();
1380
+ gated = true;
1381
+ stepping = false;
1382
+ };
1383
+
1384
+ const startStream = () => {
1385
+ emit("response.created", { response: responseSnapshot("in_progress", []) });
1386
+ // Responses spec parity: clients expect an explicit in_progress frame after created.
1387
+ emit("response.in_progress", { response: responseSnapshot("in_progress", []) });
1388
+ // The default ReadableStream strategy has HWM=1. Once one event's frames fill that
1389
+ // queue, pull stepping pauses; no custom FIFO or queuing strategy is layered on top.
1390
+ gated = true;
1391
+ beat = setBeatInterval(() => {
1392
+ if (closed || gated) return;
1393
+ if (upstreamActivity) {
1394
+ upstreamActivity = false;
1395
+ stallTicks = 0;
1396
+ } else if (++stallTicks >= maxStallTicks) {
1397
+ if (!attemptTerminationCleanup(() => {
1398
+ if (currentMsg) closeCurrentMessage();
1399
+ if (currentReasoning) closeCurrentReasoning();
1400
+ if (currentRawReasoning) closeCurrentRawReasoning();
1401
+ flushHiddenRawReasoning();
1402
+ if (currentToolCall) failCurrentToolCall();
1403
+ if (currentWebSearch) closeCurrentWebSearch("failed", []);
1404
+ releasePendingWebSources();
1405
+ })) return;
1406
+ // #1926 gap 2 residual: this beat callback is synchronous, so the durability
1407
+ // barrier is not awaited on the stall-timeout kill path. The in-memory store is
1408
+ // already updated; only a crash between here and the queued write loses it,
1409
+ // which is the pre-#1926 status quo for an already-abnormal termination.
1410
+ emit("response.incomplete", {
1411
+ response: {
1412
+ ...responseSnapshot("incomplete", finishedItems),
1413
+ incomplete_details: { reason: "upstream_stall_timeout" },
1414
+ },
1415
+ });
1416
+ reportTerminal("incomplete");
1417
+ cancelUpstreamOnce();
1418
+ terminated = true;
1419
+ emitDone();
1420
+ if (beat !== undefined) clearBeatInterval(beat);
1421
+ beat = undefined;
1422
+ try { controller.close(); } catch { /* already closed */ }
1423
+ closed = true;
1424
+ disposeOwnedBudget();
1425
+ return;
1426
+ }
1427
+ // Wire silence is independent of upstream adapter heartbeats.
1428
+ if (wireActivity) {
1429
+ wireActivity = false;
1430
+ return;
1431
+ }
1432
+ try {
1433
+ controller.enqueue(heartbeatFrame);
1434
+ emittedFrames++;
1435
+ } catch {
1436
+ closed = true;
1437
+ disposeOwnedBudget();
1438
+ }
1439
+ }, heartbeatMs);
1440
+ };
1441
+
1442
+ return new ReadableStream<Uint8Array>({
1443
+ start(streamController) {
1444
+ controller = streamController;
1445
+ startStream();
1446
+ },
1447
+ pull() {
1448
+ return step();
1449
+ },
1450
+ cancel() {
1451
+ // Client (Codex) disconnected. Stop emitting and let the caller abort the upstream fetch so a
1452
+ // cancelled turn does not leak the upstream stream or keep draining tokens (RC2).
1453
+ clientCancelled = true;
1454
+ closed = true;
1455
+ clearOwnedWatchdog();
1456
+ if (beat !== undefined) clearBeatInterval(beat);
1457
+ cancelUpstreamOnce();
1458
+ releasePendingWebSources();
1459
+ disposeOwnedBudget();
1460
+ },
1461
+ });
1462
+ }