@silverprotocol/openai-agents 0.12.4 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -92,9 +92,147 @@
92
92
  * - `response.inject.created`/`.failed` (hosted multi-agent lifecycle):
93
93
  * verified immaterial — client-initiated echo, no content loss.
94
94
  */
95
- import { AgMeta, AgProviderMeta, AgUsage, JsonValue, StreamAssembler, withAtomicPush, } from "@silverprotocol/core";
95
+ import { AgMeta, AgProviderMeta, AgUsage, JsonValue, StreamAssembler, withAtomicPush, toJsonValueSafeWithIssues, } from "@silverprotocol/core";
96
96
  /**
97
- * OA-11: extract the reasoning items from a terminal event's `response.output`.
97
+ * The refusal parts of a terminal event's `response.output`, in wire order —
98
+ * the source of a round's refusal text when no refusal event streamed
99
+ * (see "Refusal text" in the normalizer). Deserialization boundary: a
100
+ * non-array output, a non-message member and a part whose `refusal` is not a
101
+ * string are skipped; an empty id is no id.
102
+ */
103
+ function terminalRefusalParts(output) {
104
+ const out = [];
105
+ if (!Array.isArray(output))
106
+ return out;
107
+ for (const member of output) {
108
+ if (!isJsonObject(member) || member.type !== "message")
109
+ continue;
110
+ const content = member.content;
111
+ if (!Array.isArray(content))
112
+ continue;
113
+ const itemId = typeof member.id === "string" && member.id.length > 0 ? member.id : undefined;
114
+ const phase = vendorPhase(member.phase);
115
+ for (const part of content) {
116
+ if (!isJsonObject(part) || part.type !== "refusal" || typeof part.refusal !== "string")
117
+ continue;
118
+ out.push({
119
+ ...(itemId !== undefined ? { itemId } : {}),
120
+ ...(phase !== undefined ? { phase } : {}),
121
+ text: part.refusal,
122
+ });
123
+ }
124
+ }
125
+ return out;
126
+ }
127
+ /**
128
+ * Did the model refuse in this response? True when any `message` member of a
129
+ * terminal event's `response.output` carries a `refusal` content part. On the
130
+ * live wire the `message_output_created` run-item lands AFTER the terminal
131
+ * event, so the terminal output is where the round's own refusal is known when
132
+ * the round closes. Absent/non-array output, or no refusal part, ⇒ false.
133
+ */
134
+ function terminalHasRefusal(output) {
135
+ if (!Array.isArray(output))
136
+ return false;
137
+ for (const member of output) {
138
+ if (!isJsonObject(member) || member.type !== "message")
139
+ continue;
140
+ const content = member.content;
141
+ if (!Array.isArray(content))
142
+ continue;
143
+ for (const part of content) {
144
+ if (isJsonObject(part) && part.type === "refusal")
145
+ return true;
146
+ }
147
+ }
148
+ return false;
149
+ }
150
+ /**
151
+ * The media type of an image_generation result (base64): the item's
152
+ * `output_format` when it carries one (openai-node 7.22.0 declares it
153
+ * optional and nullable on ImageGenerationCall), else read from the image's
154
+ * own signature, else `application/octet-stream`.
155
+ */
156
+ function imageResultMediaType(providerData, data) {
157
+ const format = providerData?.output_format;
158
+ if (format === "png" || format === "jpeg" || format === "webp" || format === "gif")
159
+ return `image/${format}`;
160
+ if (data.startsWith("iVBORw0KGgo"))
161
+ return "image/png";
162
+ if (data.startsWith("/9j/"))
163
+ return "image/jpeg";
164
+ if (data.startsWith("UklGR"))
165
+ return "image/webp";
166
+ if (data.startsWith("R0lGOD"))
167
+ return "image/gif";
168
+ return "application/octet-stream";
169
+ }
170
+ /**
171
+ * The raw Responses output item types that @openai/agents 0.18.0 turns into a
172
+ * built-in call run-item keeping the item's id: agents-openai's converter
173
+ * (openaiResponsesConverter.mjs `convertToOutputItem`) maps the hosted kinds
174
+ * to a `hosted_tool_call` with `id: item.id`, and keeps shell, apply-patch,
175
+ * computer, program and tool-search calls under their own type. agents-core
176
+ * streams each as a `tool_called` / `tool_search_called` run-item AFTER the
177
+ * response's `response.completed` (it streams a response's step items after
178
+ * the raw loop, run.mjs:1935). `local_shell_call` converts to an unknown item
179
+ * and never streams as a call, so it is not listed.
180
+ */
181
+ const BUILTIN_OUTPUT_ITEM_TYPES = new Set([
182
+ "web_search_call",
183
+ "file_search_call",
184
+ "image_generation_call",
185
+ "code_interpreter_call",
186
+ "mcp_list_tools",
187
+ "mcp_approval_request",
188
+ "mcp_call",
189
+ "computer_call",
190
+ "shell_call",
191
+ "apply_patch_call",
192
+ "program",
193
+ "tool_search_call",
194
+ ]);
195
+ /**
196
+ * The built-in calls a terminal event's `response.output` lists, in wire
197
+ * order (see {@link BUILTIN_OUTPUT_ITEM_TYPES}). Deserialization boundary: a
198
+ * non-array output, a non-object member and a member with no non-empty string
199
+ * id are skipped.
200
+ */
201
+ function terminalBuiltinItems(output) {
202
+ const out = [];
203
+ if (!Array.isArray(output))
204
+ return out;
205
+ for (const member of output) {
206
+ if (!isJsonObject(member))
207
+ continue;
208
+ const type = member.type;
209
+ const id = member.id;
210
+ if (typeof type !== "string" || !BUILTIN_OUTPUT_ITEM_TYPES.has(type))
211
+ continue;
212
+ if (typeof id !== "string" || id.length === 0)
213
+ continue;
214
+ out.push({ id, type });
215
+ }
216
+ return out;
217
+ }
218
+ /** The ids of the `message` items a terminal event's `response.output` lists,
219
+ * in wire order (a non-object member or a member with no non-empty string
220
+ * id is skipped). */
221
+ function terminalMessageIds(output) {
222
+ const out = [];
223
+ if (!Array.isArray(output))
224
+ return out;
225
+ for (const member of output) {
226
+ if (!isJsonObject(member) || member.type !== "message")
227
+ continue;
228
+ const id = member.id;
229
+ if (typeof id === "string" && id.length > 0)
230
+ out.push(id);
231
+ }
232
+ return out;
233
+ }
234
+ /**
235
+ * Reasoning from the terminal output: extract the reasoning items from a terminal event's `response.output`.
98
236
  * This — not `response.output_item.done` — is the replayable source: OpenAI
99
237
  * re-encrypts `encrypted_content` per stage (live, echo-gpt6sol natives [4] vs
100
238
  * [21]: two different blobs for one `rs_`), and only the terminal blob is the
@@ -106,7 +244,7 @@ import { AgMeta, AgProviderMeta, AgUsage, JsonValue, StreamAssembler, withAtomic
106
244
  * Deserialization boundary: a non-array `output`, a non-object member, a member
107
245
  * with no string `id`, and a non-string summary `text` are all skipped (an
108
246
  * id-less reasoning item stays with the run-item path, which already degrades
109
- * it losslessly). Absent/empty output ⇒ `[]` ⇒ byte-identical to pre-OA-11.
247
+ * it losslessly). Absent/empty output ⇒ `[]` ⇒ nothing is emitted from it (byte-identical).
110
248
  */
111
249
  function terminalReasoningItems(output) {
112
250
  if (!Array.isArray(output))
@@ -167,7 +305,7 @@ export function mapFinishReason(reason) {
167
305
  }
168
306
  }
169
307
  /**
170
- * OA-15 (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
308
+ * The finish-reason raw companion (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
171
309
  * 89c57db): the `turn.done` finish fields for a native reason. `finishReason`
172
310
  * is `mapFinishReason(reason)`; `finishReasonRaw` — the native value byte for
173
311
  * byte — rides along ONLY when that mapping fell back ("other"/"unknown") AND a
@@ -224,45 +362,70 @@ function mapUsage(usage) {
224
362
  u.costUsd = usage.cost;
225
363
  return u;
226
364
  }
227
- // ─── url_citation annotation → AgCitation ──────────────────────────────────
228
- // `partText` is the source output_text part's text string; used to extract the
229
- // cited substring from the char-offset indices carried by the annotation (Fix 3).
230
- function mapAnnotationsToCitations(annotations, partText) {
231
- if (annotations === undefined || annotations.length === 0)
232
- return undefined;
233
- const out = [];
234
- for (const ann of annotations) {
235
- if (ann.type === "url_citation") {
236
- // Extract the cited substring from the part text when both offsets are present
237
- // and valid (Fix 3). Fall back to "" when any guard condition fails.
238
- const startIdx = ann.start_index;
239
- const endIdx = ann.end_index;
240
- const citedText = startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
241
- ? partText.slice(startIdx, endIdx)
242
- : "";
243
- const cit = {
244
- kind: "url",
245
- url: ann.url,
246
- citedText,
247
- indexFrame: "response",
248
- };
249
- if (ann.title !== undefined)
250
- cit.title = ann.title;
251
- if (startIdx !== undefined)
252
- cit.startIndex = startIdx;
253
- if (endIdx !== undefined)
254
- cit.endIndex = endIdx;
255
- out.push(cit);
365
+ // ─── output_text annotations → AgCitation ──────────────────────────────────
366
+ // In `splitAnnotations`, `partText` is the source output_text part's text
367
+ // string, used to extract the cited substring from the char-offset indices
368
+ // carried by the annotation.
369
+ /**
370
+ * An output_text part's annotations, raw. agents-openai 0.18.0's converter
371
+ * nests every part field but `type` and `text` under `providerData`
372
+ * (openaiResponsesConverter.mjs `convertToMessageContentItem`), so on the real
373
+ * wire they are `part.providerData.annotations` (15 of 17 recorded parts carry
374
+ * them there, 0 at the top level); a top-level `annotations` is read first.
375
+ * Anything but an array is no annotations.
376
+ */
377
+ function partAnnotations(part) {
378
+ const top = part.annotations;
379
+ const nested = part.providerData?.annotations;
380
+ const raw = Array.isArray(top) ? top : Array.isArray(nested) ? nested : undefined;
381
+ if (raw === undefined)
382
+ return [];
383
+ const parsed = JsonValue.parse(raw);
384
+ return Array.isArray(parsed) ? parsed : [];
385
+ }
386
+ /**
387
+ * Split a part's raw annotations. A `url_citation` with a string `url` maps
388
+ * to an AgCitation; every other annotation (file_citation,
389
+ * container_file_citation, file_path, …) has no citation target and stays
390
+ * verbatim in `unmapped`, for the `ext.openai.late-citations` carry (SPEC:965:
391
+ * never dropped silently).
392
+ */
393
+ function splitAnnotations(raw, partText) {
394
+ const citations = [];
395
+ const unmapped = [];
396
+ for (const ann of raw) {
397
+ if (!isJsonObject(ann) || ann.type !== "url_citation" || typeof ann.url !== "string") {
398
+ unmapped.push(ann);
399
+ continue;
256
400
  }
257
- // file_citation: no url-kind match; skip (deferred to a later slice — only remaining silent annotation drop)
401
+ // Extract the cited substring from the part text when both offsets are present
402
+ // and valid. Fall back to "" when any guard condition fails.
403
+ const startIdx = typeof ann.start_index === "number" ? ann.start_index : undefined;
404
+ const endIdx = typeof ann.end_index === "number" ? ann.end_index : undefined;
405
+ const citedText = startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
406
+ ? partText.slice(startIdx, endIdx)
407
+ : "";
408
+ const cit = {
409
+ kind: "url",
410
+ url: ann.url,
411
+ citedText,
412
+ indexFrame: "response",
413
+ };
414
+ if (typeof ann.title === "string")
415
+ cit.title = ann.title;
416
+ if (startIdx !== undefined)
417
+ cit.startIndex = startIdx;
418
+ if (endIdx !== undefined)
419
+ cit.endIndex = endIdx;
420
+ citations.push(cit);
258
421
  }
259
- return out.length > 0 ? out : undefined;
422
+ return { ...(citations.length > 0 ? { citations } : {}), unmapped };
260
423
  }
261
424
  // ─── optional 0.14.0 wire fields → providerMetadata (spec §2) ─────────────────
262
425
  // Wire names ride verbatim at the top level (the claude facet's wrapper-carry
263
426
  // precedent — AgProviderMeta imposes no key namespacing). Drops undefined
264
427
  // values; an ALL-absent input yields undefined, never an empty metadata object.
265
- /** PH-2 / OA-14: an OpenAI message `phase` as a vendor MARKER — a non-empty
428
+ /** The phase marker: an OpenAI message `phase` as a vendor MARKER — a non-empty
266
429
  * string, verbatim — or `undefined`. openai-node types it
267
430
  * `'commentary' | 'final_answer' | null`; null and "" carry no marker, so they
268
431
  * yield neither a `providerMetadata.phase` carry nor an ext.openai.late-phase
@@ -271,7 +434,7 @@ function mapAnnotationsToCitations(annotations, partText) {
271
434
  function vendorPhase(value) {
272
435
  return typeof value === "string" && value.length > 0 ? value : undefined;
273
436
  }
274
- /** PH-2 (draft.4, SPEC §8.0 item 27): the first-class `phase` for an OpenAI
437
+ /** SPEC §8.0 item 27 (draft.4): the first-class `phase` for an OpenAI
275
438
  * vendor marker — `"commentary"` → `"interim"`; "final_answer", absent and
276
439
  * every other value → `undefined` (a vendor spelling is never copied into
277
440
  * `phase`; it stays verbatim in `providerMetadata`). */
@@ -308,7 +471,7 @@ function isJsonObject(v) {
308
471
  return typeof v === "object" && v !== null && !Array.isArray(v);
309
472
  }
310
473
  /**
311
- * Extract `structuredContent` (the ggui cache-marker channel, spec §2.1/§4)
474
+ * Extract `structuredContent` (a reference client's cache-marker channel, spec §2.1/§4)
312
475
  * from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
313
476
  * follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
314
477
  * would be an object keyed by `.structuredContent`; a live capture
@@ -356,6 +519,18 @@ function isJsonObject(v) {
356
519
  * Neither home firing (the common case — most tool results carry no
357
520
  * structuredContent at all) is NOT a drop: it correctly yields `undefined`.
358
521
  */
522
+ /**
523
+ * Parse a JSON string the vendor hands over (tool arguments, a tool's string
524
+ * output) into a JsonValue nested no deeper than core's JSON_SAFE_MAX_DEPTH,
525
+ * the bound every carried native value already has. A node at or below that
526
+ * depth becomes core's max-depth mark, so the emitted event stays inside the depth a
527
+ * consumer folds (AG_EVENT_MAX_DEPTH). `capped` says whether any node was cut.
528
+ * Throws on a string that is not JSON, as `JSON.parse` does.
529
+ */
530
+ function parseVendorJson(raw) {
531
+ const { value, issues } = toJsonValueSafeWithIssues(JSON.parse(raw));
532
+ return { value: JsonValue.parse(value), capped: issues.some((i) => i.kind === "max-depth") };
533
+ }
359
534
  function extractStructuredContent(wrapperOutput, customData) {
360
535
  if (isJsonObject(customData) && isJsonObject(customData.structuredContent)) {
361
536
  return JsonValue.parse(customData.structuredContent);
@@ -365,7 +540,9 @@ function extractStructuredContent(wrapperOutput, customData) {
365
540
  }
366
541
  if (typeof wrapperOutput === "string") {
367
542
  try {
368
- const parsed = JSON.parse(wrapperOutput);
543
+ // The output string itself rides tool.done content whole, so a capped
544
+ // parse loses nothing.
545
+ const parsed = parseVendorJson(wrapperOutput).value;
369
546
  if (isJsonObject(parsed) && isJsonObject(parsed.structuredContent)) {
370
547
  return JsonValue.parse(parsed.structuredContent);
371
548
  }
@@ -379,11 +556,11 @@ function extractStructuredContent(wrapperOutput, customData) {
379
556
  return undefined;
380
557
  }
381
558
  /**
382
- * workspace#21 (guuey#981): the MCP tool result's `_meta`, riding the same
559
+ * workspace#21 (a reference host's ask): the MCP tool result's `_meta`, riding the same
383
560
  * host-convention `customData` channel as `structuredContent` (SPEC.md:340) —
384
561
  * agents-core 0.18.0 hands it to `MCPServer.customDataExtractor` as
385
562
  * `context.resultMeta` (`dist/mcpUtil.d.ts`:41, `result._meta ?? content._meta`
386
- * at `dist/mcp.mjs`:700); guuey's worker and this repo's capture agent return it
563
+ * at `dist/mcp.mjs`:700); a reference host's worker and this repo's capture agent return it
387
564
  * as `customData._meta`. It is a host/protocol annotation (MCP-Apps `ui.*`), so
388
565
  * it rides the tool-result block's own `_meta` VERBATIM (SPEC.md:338; §8.0
389
566
  * no-drop). Ruled option A on 2026-09-23. A non-object `_meta`
@@ -442,7 +619,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
442
619
  let responseId; // real response.id once known
443
620
  // Open text streams keyed by Responses item_id (textStart once per id).
444
621
  const openTextStreams = new Set();
445
- // OA-11 reasoning-block state. `openReasoning`: rs_ id → the message id its
622
+ // Reasoning-block state (reasoning from the terminal output). `openReasoning`: rs_ id → the message id its
446
623
  // block opened in (at `output_item.added{reasoning}`), awaiting its fill from
447
624
  // the terminal output; per-response (cleared by `resetResponseState`).
448
625
  // `filledReasoning`: every rs_ id whose block has been filled — normalizer-
@@ -450,14 +627,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
450
627
  // response closed and must dedupe against it (single source per rs_ id).
451
628
  const openReasoning = new Map();
452
629
  const filledReasoning = new Set();
453
- // OA-14 phase state. `pendingPhase`: message item id → the phase its raw
630
+ // Phase state (the phase read at the raw add). `pendingPhase`: message item id → the phase its raw
454
631
  // `output_item.added` announced, awaiting that item's `text.start`
455
632
  // (per-response). `carriedPhase`: item id → the phase that rode its
456
633
  // `text.start` — normalizer-lifetime, because the run-item it retires
457
634
  // `ext.openai.late-phase` against lands AFTER the response closed.
458
635
  const pendingPhase = new Map();
459
636
  const carriedPhase = new Map();
460
- // PH-2 (draft.4 stage 2): text stream ids whose `text.start` already set the
637
+ // The first-class phase (draft.4): text stream ids whose `text.start` already set the
461
638
  // first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
462
639
  // `text.end` fields learned for a round close that is STASHED (deferred until
463
640
  // its tool results land) — consumed by `emitRoundClose`.
@@ -510,16 +687,19 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
510
687
  let lastTopLevelTurnId;
511
688
  // Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
512
689
  let handoffOrdinal = 0;
690
+ // Per-invoke ordinal for a derived id (INV-BLOCK, SPEC:767) when a native
691
+ // item carries no id the facet can key on.
692
+ let derivedOrdinal = 0;
513
693
  // Open handoff brackets, keyed by the transfer call's callId (paired turnId
514
694
  // + the SAME parentTurnId `subagentStart` used — `subagentDone` must replay
515
695
  // it verbatim, mirroring the claude-agent-sdk facet's paired start/done
516
- // convention). HO-2 (the handoff-drop review, PS-4): matched by callId,
696
+ // convention). Matched by callId,
517
697
  // not FIFO, because agents-core <=0.8.0 opens a bracket for EVERY transfer
518
698
  // the model calls but runs only the first: a bracket closes at
519
699
  // `handoff_occurred` for its own call, or at that call's `tool_output` (the
520
700
  // handoff never ran).
521
701
  const openHandoffs = [];
522
- /** HO-2: remove and return the open bracket for `callId`, if any. */
702
+ /** Remove and return the open bracket for `callId`, if any. */
523
703
  function takeOpenHandoff(callId) {
524
704
  const i = openHandoffs.findIndex((h) => h.callId === callId);
525
705
  if (i === -1)
@@ -536,12 +716,90 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
536
716
  // The engine accumulates for downstream use; `.done.arguments` carries the full
537
717
  // string so argBuffers is primarily for the fallback path.
538
718
  const instanceArgBuffers = new Map();
539
- // Refusal tracking (T5c — instance state mirroring the old module-level
540
- // `pendingRefusal`). Set when a `message_output_created` run-item carries a
541
- // `refusal` content part; the downstream `response.completed` arm then closes
542
- // the turn with `finishReason:"refusal"`. Cleared on every response close so it
543
- // never leaks across turns.
719
+ // Refusal tracking (T5c). Set when a refusal event streams, or when a
720
+ // `message_output_created` run-item carries a `refusal` content part BEFORE
721
+ // its response's terminal event (a synthetic order); the terminal arm also
722
+ // reads the refusal from its own `response.output` (`terminalHasRefusal`),
723
+ // which is the live order: the run-item lands after the close. Cleared on
724
+ // every response close and at every `response.created`, so a late run-item's
725
+ // refusal never reaches the next round.
544
726
  let pendingRefusal = false;
727
+ // Refusal text (SPEC §8.0 graceful degradation: a native event the
728
+ // normalizer can map is never dropped silently). A `refusal` content part's
729
+ // text is a `text` block in the round's message, id `<item id>:refusal` (the
730
+ // same item can also carry an `output_text` part, whose block id is the item
731
+ // id), its `text.start` carrying `providerMetadata.type: "refusal"`, the
732
+ // part's own wire discriminant and the marker a replay reads to send a
733
+ // refusal part back, beside the item's `phase` marker as an output_text
734
+ // block carries it. ONE source per round:
735
+ // - the raw `response.refusal.delta` / `.done` events, when any arrived;
736
+ // - else the refusal part itself, from whichever comes first of the
737
+ // terminal output (read before the round closes) and a
738
+ // `message_output_created` run-item that lands while the round is open.
739
+ // A run-item that lands after the close, with no copy emitted, rides
740
+ // `ext.openai.late-message` (the message is sealed).
741
+ // The source is chosen per round, not matched per item id: a run-item's ids
742
+ // can be a different id space from the raw `item_id`s (the OpenRouter
743
+ // surface mints `msg_tmp_` run-item ids), where an id match would copy the
744
+ // text twice.
745
+ // `openRefusalBlocks`: this response's refusal blocks not yet ended;
746
+ // `refusalBlocks`: every refusal block this response opened (a repeated
747
+ // `.done` never reopens one); `refusalTextEmitted`: the round has its
748
+ // refusal text, cleared at `response.created` only, because the run-item
749
+ // that reads it lands after the round closed. `refusalCarriedPhase`: item id
750
+ // → the phase marker its refusal block carried (normalizer-lifetime, like
751
+ // `carriedPhase`, which stays the output_text blocks' own record).
752
+ const openRefusalBlocks = new Set();
753
+ const refusalBlocks = new Set();
754
+ let refusalTextEmitted = false;
755
+ const refusalCarriedPhase = new Map();
756
+ /** The item's vendor phase marker for a refusal block's `text.start`: the one
757
+ * announced at `output_item.added`, else the one an output_text block of the
758
+ * same item already carried. */
759
+ function refusalItemPhase(itemId) {
760
+ return pendingPhase.get(itemId) ?? carriedPhase.get(itemId);
761
+ }
762
+ /** A refusal block id not yet used this response, for the whole-part sources
763
+ * (an id-less item keys on the message id). */
764
+ function freshRefusalBlockId(itemId, mId) {
765
+ const base = `${itemId ?? mId}:refusal`;
766
+ let id = base;
767
+ for (let k = 2; refusalBlocks.has(id); k++)
768
+ id = `${base}:${k}`;
769
+ return id;
770
+ }
771
+ /** Open refusal block `blockId` in message `mId`. The phase marker rides
772
+ * `text.start` as on an output_text block (the first-class `phase:"interim"`
773
+ * for "commentary"), and is recorded as carried for the late run-item. */
774
+ function openRefusalBlock(blockId, mId, phase, itemId) {
775
+ const startMeta = openaiProviderMeta({ phase, type: "refusal" });
776
+ const interim = interimPhase(phase);
777
+ a.textStart(blockId, mId, {
778
+ role: "assistant",
779
+ ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
780
+ ...(interim !== undefined ? { phase: interim } : {}),
781
+ });
782
+ if (phase !== undefined && itemId !== undefined)
783
+ refusalCarriedPhase.set(itemId, phase);
784
+ openRefusalBlocks.add(blockId);
785
+ refusalBlocks.add(blockId);
786
+ refusalTextEmitted = true;
787
+ }
788
+ /** A whole refusal part as one block: start, the text as one delta (none for
789
+ * an empty text), end. */
790
+ function emitWholeRefusal(blockId, mId, text, phase, itemId) {
791
+ openRefusalBlock(blockId, mId, phase, itemId);
792
+ if (text.length > 0)
793
+ a.textDelta(blockId, mId, text, { cumulative: false });
794
+ a.textEnd(blockId, mId);
795
+ openRefusalBlocks.delete(blockId);
796
+ }
797
+ /** End every refusal block the stream left open (no `.done` before the close). */
798
+ function endOpenRefusalBlocks(mId) {
799
+ for (const blockId of openRefusalBlocks)
800
+ a.textEnd(blockId, mId);
801
+ openRefusalBlocks.clear();
802
+ }
545
803
  // ── Task 4b: defer a round's close past its pending tool results ───────────
546
804
  // (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
547
805
  // AFTER `response.completed` — closing at native-close time would put a later
@@ -559,20 +817,125 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
559
817
  * Register `callId` as pending a `tool.done` under the CURRENT open turn
560
818
  * (Task 4b). Shared by the raw `response.output_item.added` function_call
561
819
  * path and the built-in Shell/Apply-Patch `tool_called` synthesis path
562
- * (playbook 2026-07-03 SDK-bump adaptation, Finding #1) — both start a call
820
+ * (the 2026-07-03 SDK-bump adaptation) — both start a call
563
821
  * whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
564
822
  * is open (defensive; every caller already calls `ensureResponseOpen()` first).
565
823
  */
566
824
  function registerPendingTool(callId) {
567
- if (turnId === undefined)
825
+ registerPendingToolFor(turnId, callId);
826
+ }
827
+ /** Register `callId` as pending a `tool.done` under round `tid`. */
828
+ function registerPendingToolFor(tid, callId) {
829
+ if (tid === undefined)
568
830
  return;
569
- let pending = pendingToolsByTurn.get(turnId);
831
+ let pending = pendingToolsByTurn.get(tid);
570
832
  if (pending === undefined) {
571
833
  pending = new Set();
572
- pendingToolsByTurn.set(turnId, pending);
834
+ pendingToolsByTurn.set(tid, pending);
573
835
  }
574
836
  pending.add(callId);
575
- turnIdByToolCallId.set(callId, turnId);
837
+ turnIdByToolCallId.set(callId, tid);
838
+ }
839
+ // ── Built-in round attach ───────────────────────────────────────────────────
840
+ // agents-core streams a response's built-in call run-items (`tool_called`,
841
+ // `tool_search_called`) after its `response.completed`, so the round has
842
+ // already reached its terminal when they land. A round whose terminal
843
+ // `response.output` lists a built-in call (see BUILTIN_OUTPUT_ITEM_TYPES)
844
+ // defers its close as §8.0 item 14 defers a round for its pending tool
845
+ // results, and each late run-item attaches to THAT round's turn and message
846
+ // (never a turn opened for it). The close is released:
847
+ // - when every listed call has its run-item and every pending result has
848
+ // landed (`maybeReleaseRound`);
849
+ // - at the next `response.created`, when the round still waits only on
850
+ // listed calls whose run-item never streamed (agents-core can suppress
851
+ // one), so the new response keeps its own turn; those calls stop being
852
+ // the round's;
853
+ // - at flush, per INV-FLUSH (2).
854
+ // A listed `mcp_approval_request` becomes a pending call of its round when
855
+ // its `tool_called` lands, and its answer (`mcp_approval_response`) closes
856
+ // it; with no answer, the round flushes paused naming its ask (INV-FLUSH
857
+ // (2)). `listedBuiltinsByTurn`: round → listed item ids still waiting.
858
+ // `builtinTurnByItemId`: listed item id → its round.
859
+ // `seenBuiltinItemIds`: built-in items whose run-item already landed (one
860
+ // that lands before its terminal, a synthetic order), so the terminal never
861
+ // lists them.
862
+ const listedBuiltinsByTurn = new Map();
863
+ const builtinTurnByItemId = new Map();
864
+ const seenBuiltinItemIds = new Set();
865
+ // Approval requests an `mcp_approval_response` has closed in this invoke.
866
+ const answeredRequests = new Set();
867
+ /** List round `tid`'s built-in calls (those whose run-item has not landed). */
868
+ /** List round `tid`'s built-in calls whose run-item has not landed. When
869
+ * it lists any, the round's `message` items are listed too, so their
870
+ * `message_output_created` (and the citations it carries) lands while the
871
+ * round's close is still deferred. */
872
+ function listBuiltins(tid, items, messageIds) {
873
+ const ids = [];
874
+ for (const item of items) {
875
+ if (seenBuiltinItemIds.has(item.id))
876
+ continue;
877
+ ids.push(item.id);
878
+ builtinTurnByItemId.set(item.id, tid);
879
+ }
880
+ if (ids.length === 0)
881
+ return ids;
882
+ for (const id of messageIds) {
883
+ if (seenBuiltinItemIds.has(id))
884
+ continue;
885
+ ids.push(id);
886
+ builtinTurnByItemId.set(id, tid);
887
+ }
888
+ listedBuiltinsByTurn.set(tid, new Set(ids));
889
+ return ids;
890
+ }
891
+ /** The stashed round a late built-in run-item belongs to: the round whose
892
+ * terminal listed `key`, else, when no response is open, the invoke's last
893
+ * round if its close is still stashed (a run-item its terminal did not
894
+ * list). Undefined when neither holds. */
895
+ function lateBuiltinRound(key) {
896
+ const listedTid = key !== undefined ? builtinTurnByItemId.get(key) : undefined;
897
+ const tid = listedTid ?? (turnId === undefined ? lastTopLevelTurnId : undefined);
898
+ if (tid === undefined)
899
+ return undefined;
900
+ const stashed = stashedCloseByTurn.get(tid);
901
+ return stashed !== undefined ? { tid, mId: stashed.msgId } : undefined;
902
+ }
903
+ /** The listed item `key` has what it waited for: drop it, and release its
904
+ * round if nothing else keeps the round open. */
905
+ function drainListedBuiltin(key) {
906
+ if (key === undefined)
907
+ return;
908
+ const tid = builtinTurnByItemId.get(key);
909
+ if (tid === undefined)
910
+ return;
911
+ const listed = listedBuiltinsByTurn.get(tid);
912
+ if (listed === undefined || !listed.delete(key))
913
+ return;
914
+ maybeReleaseRound(tid);
915
+ }
916
+ /** Release round `tid`'s stashed close when no pending result and no listed
917
+ * built-in call keeps it open. */
918
+ function maybeReleaseRound(tid) {
919
+ const stashed = stashedCloseByTurn.get(tid);
920
+ if (stashed === undefined)
921
+ return;
922
+ if ((pendingToolsByTurn.get(tid)?.size ?? 0) > 0)
923
+ return;
924
+ if ((listedBuiltinsByTurn.get(tid)?.size ?? 0) > 0)
925
+ return;
926
+ stashedCloseByTurn.delete(tid);
927
+ listedBuiltinsByTurn.delete(tid);
928
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
929
+ }
930
+ /** At a new `response.created`: every round still waiting on listed calls
931
+ * whose run-item never streamed stops waiting on them, and is released if
932
+ * no pending result keeps it open. */
933
+ function releaseListedAtNextResponse() {
934
+ for (const [tid, listed] of [...listedBuiltinsByTurn]) {
935
+ listed.clear();
936
+ listedBuiltinsByTurn.delete(tid);
937
+ maybeReleaseRound(tid);
938
+ }
576
939
  }
577
940
  // Stashed close for a turn whose pending set was non-empty at close time,
578
941
  // keyed by turnId. Consumed the moment its pending set drains (emitted right
@@ -585,7 +948,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
585
948
  * whichever values are live right now (immediate path) or were captured at
586
949
  * defer time (drain path) — same three calls either way.
587
950
  */
588
- /** PH-2: is `streamId`'s text.end still pending in a STASHED round close
951
+ /** Is `streamId`'s text.end still pending in a STASHED round close
589
952
  * (a deferred tool round), i.e. not yet emitted? */
590
953
  function isStashedTextStream(streamId) {
591
954
  for (const stashed of stashedCloseByTurn.values()) {
@@ -596,10 +959,17 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
596
959
  }
597
960
  function endStashedTextStreams(mId, textStreamIds) {
598
961
  for (const streamId of textStreamIds) {
599
- // PH-2: a phase learned while this close sat stashed rides its text.end.
600
- const endFields = stashedEndFields.get(streamId);
962
+ // Citations and a phase learned while this close sat stashed ride its
963
+ // text.end, in the live path's field order.
964
+ const f = stashedEndFields.get(streamId);
601
965
  stashedEndFields.delete(streamId);
602
- a.textEnd(streamId, mId, endFields);
966
+ a.textEnd(streamId, mId, f === undefined
967
+ ? undefined
968
+ : {
969
+ ...(f.citations !== undefined ? { citations: f.citations } : {}),
970
+ ...(f.providerMetadata !== undefined ? { providerMetadata: f.providerMetadata } : {}),
971
+ ...(f.phase !== undefined ? { phase: f.phase } : {}),
972
+ });
603
973
  }
604
974
  }
605
975
  function emitRoundClose(tid, mId, textStreamIds, fields) {
@@ -645,6 +1015,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
645
1015
  for (const [tid, stashed] of stashedCloseByTurn)
646
1016
  releaseDeferredClose(tid, stashed);
647
1017
  stashedCloseByTurn.clear();
1018
+ listedBuiltinsByTurn.clear();
648
1019
  }
649
1020
  /**
650
1021
  * Close the round now, unless `tid`'s pending-tool set is non-empty — in
@@ -654,9 +1025,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
654
1025
  * immediately via `endOpenStreamsAndCloseMessage` — an errored round's
655
1026
  * pending results are moot, by design).
656
1027
  */
657
- function finishOrDeferRound(tid, mId, textStreamIds, fields) {
1028
+ function finishOrDeferRound(tid, mId, textStreamIds, fields, listing = { builtins: [], messageIds: [] }) {
1029
+ const listed = listBuiltins(tid, listing.builtins, listing.messageIds);
658
1030
  const pending = pendingToolsByTurn.get(tid);
659
- if (pending !== undefined && pending.size > 0) {
1031
+ if ((pending !== undefined && pending.size > 0) || listed.length > 0) {
660
1032
  stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
661
1033
  return;
662
1034
  }
@@ -668,7 +1040,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
668
1040
  * somehow absent (defensive — the spike confirms the id is always present at start).
669
1041
  * Returns the close-once key (the real response.id, else the synthesized turnId),
670
1042
  * or `undefined` when the response has already been closed (caller must no-op).
671
- * `model` (OA-12) rides `message.start.model` — only the authoritative
1043
+ * `model` (the per-message model) rides `message.start.model` — only the authoritative
672
1044
  * `response.created` open passes it; a defensive open never invents one.
673
1045
  */
674
1046
  function ensureResponseOpen(respId, model) {
@@ -720,7 +1092,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
720
1092
  a.openTurn(opened, threadId);
721
1093
  return { turnId: opened, messageId: `${callId}:result` };
722
1094
  }
723
- // Approve-all (the D3 pin, 2026-09-24): the resuming invoke can
1095
+ // Approve-all (pinned 2026-09-24): the resuming invoke can
724
1096
  // replay SEVERAL results before its response. While the resume turn is
725
1097
  // open with no assistant message yet (turnId set, msgId unset — a state
726
1098
  // only this helper creates), each further result joins THAT turn as its
@@ -753,11 +1125,13 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
753
1125
  if (key !== undefined)
754
1126
  closedResponses.add(key);
755
1127
  openTextStreams.clear();
756
- // OA-11: an rs_ block opened but never filled (e.g. `response.failed`) stays
1128
+ // An rs_ block opened but never filled (e.g. `response.failed`) stays
757
1129
  // as the spec's own unsealed-block outcome (INV-FLUSH (3)); forget it so a
758
1130
  // late run-item for it takes the existing `late-reasoning` degrade.
759
1131
  openReasoning.clear();
760
1132
  pendingPhase.clear();
1133
+ openRefusalBlocks.clear();
1134
+ refusalBlocks.clear();
761
1135
  turnId = undefined;
762
1136
  msgId = undefined;
763
1137
  responseId = undefined;
@@ -772,6 +1146,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
772
1146
  if (msgId !== undefined) {
773
1147
  for (const streamId of openTextStreams)
774
1148
  a.textEnd(streamId, msgId);
1149
+ endOpenRefusalBlocks(msgId);
775
1150
  a.closeMessage(msgId);
776
1151
  }
777
1152
  resetResponseState();
@@ -780,8 +1155,16 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
780
1155
  function driveRawResponsesEvent(ev) {
781
1156
  switch (ev.type) {
782
1157
  case "response.created": {
1158
+ // A new response: a refusal recorded by a late run-item belongs to the
1159
+ // response before it, never to this one; so does its refusal text.
1160
+ pendingRefusal = false;
1161
+ refusalTextEmitted = false;
1162
+ // A round still waiting only on listed built-in calls whose run-item
1163
+ // never streamed is released before this response's turn opens (see
1164
+ // "Built-in round attach").
1165
+ releaseListedAtNextResponse();
783
1166
  // Authoritative turn open — the real response.id is present at start.
784
- // OA-12: so is the resolved model id (JsonValue boundary: string-guarded).
1167
+ // So is the resolved model id (JsonValue boundary: string-guarded).
785
1168
  const rawModelId = ev.response.model;
786
1169
  ensureResponseOpen(ev.response.id, typeof rawModelId === "string" && rawModelId.length > 0 ? rawModelId : undefined);
787
1170
  return;
@@ -792,11 +1175,11 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
792
1175
  return; // unreachable post-ensure; satisfies the narrowing
793
1176
  if (!openTextStreams.has(ev.item_id)) {
794
1177
  openTextStreams.add(ev.item_id);
795
- // OA-14: the phase announced at output_item.added rides text.start
1178
+ // The phase announced at output_item.added rides text.start
796
1179
  // (R&D items 13+17, stage 1, ruled 2026-09-23; vercel parity c4f5981).
797
1180
  const phase = pendingPhase.get(ev.item_id);
798
1181
  const startMeta = openaiProviderMeta({ phase });
799
- // PH-2 (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
1182
+ // The first-class phase (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
800
1183
  // the first delta ⇒ the first-class `phase` goes on text.start.
801
1184
  const interim = interimPhase(phase);
802
1185
  a.textStart(ev.item_id, msgId, {
@@ -816,7 +1199,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
816
1199
  return;
817
1200
  }
818
1201
  case "response.output_text.done": {
819
- // NO-OP (audit M22): the citations carrier — `message_output_created` — is
1202
+ // NO-OP: the citations carrier — `message_output_created` — is
820
1203
  // the authoritative text-end source (it also reports refusal parts and
821
1204
  // arrives with the annotated part, so closing here would emit `text.end`
822
1205
  // BEFORE citations are known). The stream stays in `openTextStreams`;
@@ -825,8 +1208,38 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
825
1208
  // `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
826
1209
  return;
827
1210
  }
1211
+ case "response.refusal.delta": {
1212
+ // Refusal text streams like output_text (see "Refusal text"): the raw
1213
+ // refusal events are this round's source once any arrives.
1214
+ ensureResponseOpen();
1215
+ if (msgId === undefined)
1216
+ return; // unreachable post-ensure; satisfies the narrowing
1217
+ pendingRefusal = true;
1218
+ const blockId = `${ev.item_id}:refusal`;
1219
+ if (!refusalBlocks.has(blockId))
1220
+ openRefusalBlock(blockId, msgId, refusalItemPhase(ev.item_id), ev.item_id);
1221
+ a.textDelta(blockId, msgId, ev.delta, { cumulative: false });
1222
+ return;
1223
+ }
1224
+ case "response.refusal.done": {
1225
+ // Ends the part's block. With no delta before it, its `refusal` is the
1226
+ // whole text. A refusal part carries no annotations, so unlike
1227
+ // `response.output_text.done` nothing arrives later for its `text.end`.
1228
+ ensureResponseOpen();
1229
+ if (msgId === undefined)
1230
+ return; // unreachable post-ensure; satisfies the narrowing
1231
+ pendingRefusal = true;
1232
+ const blockId = `${ev.item_id}:refusal`;
1233
+ if (!refusalBlocks.has(blockId)) {
1234
+ emitWholeRefusal(blockId, msgId, ev.refusal, refusalItemPhase(ev.item_id), ev.item_id);
1235
+ return;
1236
+ }
1237
+ if (openRefusalBlocks.delete(blockId))
1238
+ a.textEnd(blockId, msgId);
1239
+ return;
1240
+ }
828
1241
  case "response.output_item.added": {
829
- // OA-11: a reasoning item OPENS its block here — id only, the added event
1242
+ // A reasoning item OPENS its block here — id only, the added event
830
1243
  // carries no replayable content — so the block takes its wire position
831
1244
  // ahead of the `fc_` it precedes (§5 block insertion order, SPEC:763;
832
1245
  // §10 item 4's stateless loop replays `rs_` before its `fc_`). It is
@@ -839,7 +1252,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
839
1252
  openReasoningBlock(rsId);
840
1253
  return;
841
1254
  }
842
- // OA-14: a message item announces its `phase` here, BEFORE its first
1255
+ // A message item announces its `phase` here, BEFORE its first
843
1256
  // text delta — record it for that item's `text.start`. Record only: no
844
1257
  // response open, no emit, so an absent/null/non-string/empty phase is
845
1258
  // byte-identical to a stream without this event.
@@ -919,7 +1332,11 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
919
1332
  const callIdDone = instanceCallIdByItemId.get(ev.item_id) ?? ev.item_id;
920
1333
  let input;
921
1334
  try {
922
- input = JsonValue.parse(JSON.parse(candidate));
1335
+ const parsed = parseVendorJson(candidate);
1336
+ input = parsed.value;
1337
+ // A capped value keeps the arguments, verbatim, on the ext carry.
1338
+ if (parsed.capped)
1339
+ a.emitExt("openai", "unparsed", { itemId: ev.item_id, arguments: candidate });
923
1340
  }
924
1341
  catch {
925
1342
  input = {};
@@ -939,11 +1356,22 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
939
1356
  return; // unreachable post-ensure; satisfies narrowing
940
1357
  if (msgId === undefined)
941
1358
  return; // unreachable post-ensure; satisfies narrowing
942
- // OA-11: fill every reasoning block from THIS output (the replayable blob)
1359
+ // Fill every reasoning block from THIS output (the replayable blob)
943
1360
  // FIRST — before any branch below can emit message.end / turn.* (INV-MSG:
944
1361
  // a reasoning.* event must never target a sealed message; core's reduce()
945
1362
  // does not check that for reasoning.*, so the order is this facet's job).
946
1363
  fillReasoningFromTerminalOutput(ev.response.output);
1364
+ // Refusal text (see "Refusal text"): with no refusal event in this
1365
+ // round, the terminal output's refusal parts are its source, emitted
1366
+ // now while the message is open (the run-item lands after the close).
1367
+ // Then any refusal block the stream left open ends here, before every
1368
+ // branch below closes the message.
1369
+ if (!refusalTextEmitted) {
1370
+ for (const part of terminalRefusalParts(ev.response.output)) {
1371
+ emitWholeRefusal(freshRefusalBlockId(part.itemId, msgId), msgId, part.text, part.phase, part.itemId);
1372
+ }
1373
+ }
1374
+ endOpenRefusalBlocks(msgId);
947
1375
  // Snapshot before any deferral: `resetResponseState()` below always
948
1376
  // clears these, but a deferred close needs them later (Task 4b).
949
1377
  const currentTurnId = turnId;
@@ -951,6 +1379,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
951
1379
  const textStreamIds = Array.from(openTextStreams);
952
1380
  const reason = ev.response.incomplete_details?.reason;
953
1381
  const usage = mapUsage(ev.response.usage);
1382
+ // The built-in calls (and, with them, the messages) this response
1383
+ // lists, whose run-items land after this event (see "Built-in round
1384
+ // attach").
1385
+ const listing = { builtins: terminalBuiltinItems(ev.response.output), messageIds: terminalMessageIds(ev.response.output) };
954
1386
  // `status` is OPTIONAL upstream and its enum is OPEN ("clients must
955
1387
  // accept additional values"), so it is read through `unknown` + a typeof
956
1388
  // guard rather than trusted through the declared union — this is the
@@ -961,7 +1393,8 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
961
1393
  const rawStatus = ev.response.status;
962
1394
  const unsuccessfulStatus = typeof rawStatus === "string" && UNSUCCESSFUL_RESPONSE_STATUSES.has(rawStatus) ? rawStatus : undefined;
963
1395
  // Decision tree (mirrors the canonical model, A1):
964
- // refusal recorded → closeTurnDone success, finishReason:"refusal"
1396
+ // refusal (in the terminal
1397
+ // output, or recorded) → closeTurnDone success, finishReason:"refusal"
965
1398
  // content_filter → closeTurnDone error-outcome + safety signal
966
1399
  // any other incomplete → closeTurnError{code:reason, usage}
967
1400
  // completed, status failed/
@@ -972,12 +1405,12 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
972
1405
  // ENTIRE close (message + turn) instead of emitting (INV-MSG).
973
1406
  // closeTurnError does NOT defer (an errored round's pending results are
974
1407
  // moot, by design) — it still closes the message immediately here.
975
- if (pendingRefusal) {
1408
+ if (pendingRefusal || terminalHasRefusal(ev.response.output)) {
976
1409
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
977
1410
  outcome: { type: "success" },
978
1411
  finishReason: "refusal",
979
1412
  ...(usage !== undefined ? { usage } : {}),
980
- });
1413
+ }, listing);
981
1414
  }
982
1415
  else if (reason === "content_filter") {
983
1416
  const safety = [{ category: "content_filter", blocked: true }];
@@ -986,7 +1419,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
986
1419
  ...finishReasonFields(reason),
987
1420
  safety,
988
1421
  ...(usage !== undefined ? { usage } : {}),
989
- });
1422
+ }, listing);
990
1423
  }
991
1424
  else if (ev.type === "response.incomplete") {
992
1425
  endOpenStreamsAndCloseMessage();
@@ -1031,10 +1464,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1031
1464
  else {
1032
1465
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1033
1466
  outcome: { type: "success" },
1034
- // OA-15: an unmapped native reason also carries finishReasonRaw.
1467
+ // An unmapped native reason also carries finishReasonRaw.
1035
1468
  ...finishReasonFields(reason),
1036
1469
  ...(usage !== undefined ? { usage } : {}),
1037
- });
1470
+ }, listing);
1038
1471
  }
1039
1472
  resetResponseState();
1040
1473
  return;
@@ -1054,7 +1487,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1054
1487
  // message/code/usage (§4), so per §8.0 item 33 it rides verbatim in a
1055
1488
  // carrier the §5 table folds, never as remedy data on the terminal: an
1056
1489
  // adapter NOTICE message immediately BEFORE the closing turn.error, in
1057
- // this turn (rd-15):
1490
+ // this turn (remedy-shaped vendor data):
1058
1491
  // message.start {role:"notice", noticeSource:"adapter"} →
1059
1492
  // one text block, text = `detailed_explanation` verbatim (else
1060
1493
  // error.message), text.start `_meta["openai/misalignment"]` = the
@@ -1111,34 +1544,74 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1111
1544
  return;
1112
1545
  }
1113
1546
  // Duplicate raw families IGNORED per the canonical model:
1114
- // response.output_text.done is its own no-op arm above (audit M22);
1547
+ // response.output_text.done is its own no-op arm above;
1115
1548
  // response.output_item.done, response.in_progress, content_part.* are not
1116
1549
  // authoritative sources.
1117
1550
  default:
1118
1551
  return;
1119
1552
  }
1120
1553
  }
1554
+ /**
1555
+ * A `message_output_created` run-item's refusal part (see "Refusal text").
1556
+ * - The round already has its refusal text (the raw events or the terminal
1557
+ * output): no second copy. The item's phase marker, if that block did
1558
+ * not carry it, rides `ext.openai.late-phase` (the block's `text.end` is
1559
+ * out: case (iii) of the output_text arm), once per item: an item that
1560
+ * also carries an output_text part leaves it to that part's arm.
1561
+ * - The round is open (a synthetic order): the part is the source.
1562
+ * - The round closed with no copy: the message is sealed, so the text rides
1563
+ * `ext.openai.late-message` with `partType: "refusal"`, anchored to the
1564
+ * round like the id-less late message.
1565
+ */
1566
+ function driveRunItemRefusal(item, text) {
1567
+ const itemPhase = vendorPhase(item.phase);
1568
+ if (refusalTextEmitted) {
1569
+ if (item.id !== undefined &&
1570
+ itemPhase !== undefined &&
1571
+ refusalCarriedPhase.get(item.id) !== itemPhase &&
1572
+ !item.content.some((p) => p.type === "output_text")) {
1573
+ a.emitExt("openai", "late-phase", { itemId: item.id, phase: itemPhase });
1574
+ }
1575
+ return;
1576
+ }
1577
+ if (msgId !== undefined) {
1578
+ emitWholeRefusal(freshRefusalBlockId(item.id, msgId), msgId, text, itemPhase, item.id);
1579
+ return;
1580
+ }
1581
+ const anchor = turnId ?? lastTopLevelTurnId;
1582
+ a.emitExt("openai", "late-message", {
1583
+ text,
1584
+ partType: "refusal",
1585
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
1586
+ ...(anchor !== undefined ? { forTurnId: anchor } : {}),
1587
+ ...(itemPhase !== undefined ? { phase: itemPhase } : {}),
1588
+ });
1589
+ }
1121
1590
  /** End any still-open text streams (defensive), then close the open message. */
1122
1591
  function endOpenStreamsAndCloseMessage() {
1123
1592
  if (msgId !== undefined) {
1124
1593
  for (const streamId of openTextStreams)
1125
1594
  a.textEnd(streamId, msgId);
1595
+ endOpenRefusalBlocks(msgId);
1126
1596
  a.closeMessage(msgId);
1127
1597
  }
1128
1598
  }
1129
1599
  /**
1130
1600
  * Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
1131
- * citations source (audit M22). The text itself already streamed from the raw
1601
+ * citations source. The text itself already streamed from the raw
1132
1602
  * `response.output_text.delta` path — this MUST NOT re-emit it — but the
1133
1603
  * `output_text` part's annotations are only known here (they are not present on
1134
1604
  * `response.output_text.done`), so THIS is where the matching open text stream
1135
1605
  * actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
1136
1606
  * directly to the streamed block (never a duplicate id-less supplement). A
1137
- * `refusal` part sets `pendingRefusal` so the downstream `response.completed`
1138
- * arm closes with `finishReason:"refusal"` (no text stream to close for it).
1607
+ * `refusal` part sets `pendingRefusal`, which counts only when the run-item
1608
+ * lands before its response's terminal event (a synthetic order). On the
1609
+ * live wire it lands after the close, and the terminal arm reads the round's
1610
+ * refusal from its own `response.output` (`terminalHasRefusal`). Its text is
1611
+ * a single-source fallback (`driveRunItemRefusal`, see "Refusal text").
1139
1612
  *
1140
- * Correlation (OA-14 — id FIRST, FIFO fallback; protocol package rd-13-17
1141
- * §2 stage 1): on the direct OpenAI wire the raw delta's `item_id` and the
1613
+ * Correlation (id FIRST, FIFO fallback; the narration-phase rule, stage
1614
+ * 1): on the direct OpenAI wire the raw delta's `item_id` and the
1142
1615
  * run-item's `rawItem.id` are the SAME id (all 8 openai corpus seeds), so the
1143
1616
  * stream is matched by id — a completion can no longer land on an earlier
1144
1617
  * part's stream when two are open. Only when the id is unknown to
@@ -1156,7 +1629,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1156
1629
  * annotations, though, they are NOT yet lost anywhere else — silently dropping
1157
1630
  * them here would violate Tenet 6. Route them losslessly through the facet's
1158
1631
  * existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
1159
- * the run-item id + the raw annotations array verbatim (review finding on M22).
1632
+ * the run-item id + the raw annotations array verbatim.
1160
1633
  * A part with no annotations has nothing to lose — the plain `continue` stays.
1161
1634
  *
1162
1635
  * ID-LESS SYNTHESIZED MESSAGE (agents-core ≥0.13.2): `errorHandlers.
@@ -1185,9 +1658,23 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1185
1658
  * never a duplicated or corrupted core stream.
1186
1659
  */
1187
1660
  function driveMessageOutputCreated(item) {
1661
+ if (item.id !== undefined)
1662
+ seenBuiltinItemIds.add(item.id);
1663
+ driveMessageParts(item);
1664
+ // A listed message has landed; its round may now close (see "Built-in
1665
+ // round attach"), with any citations stashed above on its text.end.
1666
+ drainListedBuiltin(item.id);
1667
+ }
1668
+ /** The per-part body of {@link driveMessageOutputCreated} (see its doc). */
1669
+ function driveMessageParts(item) {
1188
1670
  for (const part of item.content) {
1189
1671
  if (part.type === "refusal") {
1190
1672
  pendingRefusal = true;
1673
+ // The typeof guard is load-bearing: rawItem is envelope-only-validated
1674
+ // wire data, and push() must never throw.
1675
+ const text = part.refusal;
1676
+ if (typeof text === "string")
1677
+ driveRunItemRefusal(item, text);
1191
1678
  continue;
1192
1679
  }
1193
1680
  if (part.type === "output_text") {
@@ -1208,20 +1695,34 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1208
1695
  ...(item.phase !== undefined ? { phase: item.phase } : {}),
1209
1696
  });
1210
1697
  }
1211
- if (part.annotations !== undefined && part.annotations.length > 0) {
1698
+ const idlessAnnotations = partAnnotations(part);
1699
+ if (idlessAnnotations.length > 0) {
1212
1700
  a.emitExt("openai", "late-citations", {
1213
- annotations: JsonValue.parse(part.annotations),
1701
+ annotations: idlessAnnotations,
1214
1702
  });
1215
1703
  }
1216
1704
  continue;
1217
1705
  }
1218
1706
  if (msgId === undefined) {
1219
- // response already closed — see doc above.
1220
- if (part.annotations !== undefined && part.annotations.length > 0) {
1221
- a.emitExt("openai", "late-citations", {
1222
- itemId: item.id,
1223
- annotations: JsonValue.parse(part.annotations),
1224
- });
1707
+ // response already closed — see doc above. While the round's close
1708
+ // is STASHED (deferred for its tool results or built-in calls), this
1709
+ // block's text.end is not out yet, so its url citations ride it (the
1710
+ // phase marker's case (ii) below), and any other annotation takes
1711
+ // the ext carry; a message that lands after the close was released
1712
+ // carries every annotation on the ext.
1713
+ const closedAnnotations = partAnnotations(part);
1714
+ if (closedAnnotations.length > 0) {
1715
+ const split = isStashedTextStream(item.id) ? splitAnnotations(closedAnnotations, part.text) : undefined;
1716
+ if (split?.citations !== undefined) {
1717
+ stashedEndFields.set(item.id, { ...stashedEndFields.get(item.id), citations: split.citations });
1718
+ }
1719
+ const carry = split?.citations !== undefined ? split.unmapped : closedAnnotations;
1720
+ if (carry.length > 0) {
1721
+ a.emitExt("openai", "late-citations", {
1722
+ itemId: item.id,
1723
+ annotations: carry,
1724
+ });
1725
+ }
1225
1726
  }
1226
1727
  // phase (0.14.0): the live wire delivers the FINAL round's
1227
1728
  // message_output_created AFTER response_done has closed the message
@@ -1230,21 +1731,22 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1230
1731
  // (deferred-close) messages ever reach it. Same post-close degrade
1231
1732
  // convention as late-citations: a dedicated itemId-keyed vendor
1232
1733
  // carry, one per phase-bearing part.
1233
- // OA-14: RETIRED when this id's SAME phase already rode its text.start
1734
+ // RETIRED when this id's SAME phase already rode its text.start
1234
1735
  // (the live case); kept — lossless — when only the run-item knows it,
1235
1736
  // or knows a different value.
1236
- // PH-2: null/"" is no marker at all (spec ruling (a)) — neither
1737
+ // A null/"" phase is no marker at all (spec ruling (a)) — neither
1237
1738
  // a carry nor a late-phase ext.
1238
1739
  const lateItemPhase = vendorPhase(item.phase);
1239
1740
  if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
1240
1741
  if (isStashedTextStream(item.id)) {
1241
- // PH-2 case (ii): the round close is STASHED (a deferred tool
1742
+ // Case (ii): the round close is STASHED (a deferred tool
1242
1743
  // round), so this block's text.end is NOT yet emitted — the §5
1243
1744
  // timing rule makes the end the phase's home (ruled
1244
1745
  // 2026-09-23). The marker has a first-class home, so no late-phase.
1245
1746
  const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
1246
1747
  const endMeta = openaiProviderMeta({ phase: lateItemPhase });
1247
1748
  stashedEndFields.set(item.id, {
1749
+ ...stashedEndFields.get(item.id),
1248
1750
  ...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
1249
1751
  ...(interim !== undefined ? { phase: interim } : {}),
1250
1752
  });
@@ -1257,12 +1759,15 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1257
1759
  }
1258
1760
  continue;
1259
1761
  }
1260
- // OA-14: id first, FIFO fallback — see "Correlation" in the doc above.
1762
+ // Id first, FIFO fallback — see "Correlation" in the doc above.
1261
1763
  const streamId = item.id !== undefined && openTextStreams.has(item.id) ? item.id : openTextStreams.values().next().value;
1262
1764
  if (streamId === undefined)
1263
1765
  continue; // defensive: no matching open stream
1264
1766
  openTextStreams.delete(streamId);
1265
- const citations = mapAnnotationsToCitations(part.annotations, part.text);
1767
+ // A url citation rides text.end; any other annotation has no citation
1768
+ // target and takes the ext carry, after the text.end (SPEC:965).
1769
+ const liveSplit = splitAnnotations(partAnnotations(part), part.text);
1770
+ const citations = liveSplit.citations;
1266
1771
  // phase (0.14.0) rides the matching text.end's providerMetadata —
1267
1772
  // PER-PART, not message.metadata: this facet folds a response into ONE
1268
1773
  // message, and a program-driven turn emits multiple message items with
@@ -1270,7 +1775,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1270
1775
  // merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
1271
1776
  const itemPhase = vendorPhase(item.phase);
1272
1777
  const phaseMeta = openaiProviderMeta({ phase: itemPhase });
1273
- // PH-2 case (i): known before this block's text.end ⇒ the end carries
1778
+ // Case (i): known before this block's text.end ⇒ the end carries
1274
1779
  // the first-class phase, unless text.start already did.
1275
1780
  const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
1276
1781
  a.textEnd(streamId, msgId, citations !== undefined || phaseMeta !== undefined || endInterim !== undefined
@@ -1280,11 +1785,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1280
1785
  ...(endInterim !== undefined ? { phase: endInterim } : {}),
1281
1786
  }
1282
1787
  : undefined);
1788
+ if (liveSplit.unmapped.length > 0) {
1789
+ a.emitExt("openai", "late-citations", { itemId: item.id ?? streamId, annotations: liveSplit.unmapped });
1790
+ }
1283
1791
  }
1284
1792
  }
1285
1793
  }
1286
1794
  /**
1287
- * OA-11: open the reasoning block for `rsId` in the current message — once per
1795
+ * Open the reasoning block for `rsId` in the current message — once per
1288
1796
  * id (a re-announce, or an id already filled, is a no-op). `id` and `itemId`
1289
1797
  * are both the `rs_` id (the run-item path's convention). Called from
1290
1798
  * `output_item.added{reasoning}` so the block takes its WIRE position, and
@@ -1299,7 +1807,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1299
1807
  openReasoning.set(rsId, msgId);
1300
1808
  }
1301
1809
  /**
1302
- * OA-11: fill + seal an OPEN reasoning block: one `reasoning.delta` per
1810
+ * Fill + seal an OPEN reasoning block: one `reasoning.delta` per
1303
1811
  * non-empty summary part (`partIndex` = the wire `summary_index`), then
1304
1812
  * `reasoning.opaque` (the replayable ciphertext, `itemId` = rs_) BEFORE
1305
1813
  * `reasoning.end`, so "sealed" means complete (the spec's recommendation;
@@ -1331,7 +1839,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1331
1839
  openReasoning.delete(rsId);
1332
1840
  filledReasoning.add(rsId);
1333
1841
  }
1334
- /** OA-11: fill every reasoning block from a terminal event's `response.output`
1842
+ /** Fill every reasoning block from a terminal event's `response.output`
1335
1843
  * (see `terminalReasoningItems` for why this, not `output_item.done`, is the
1336
1844
  * source). An item never announced by `output_item.added` opens here
1337
1845
  * (defensive — position is then the terminal event's). */
@@ -1344,14 +1852,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1344
1852
  }
1345
1853
  }
1346
1854
  /**
1347
- * Map a `reasoning_item_created` run-item (Task 3, audit M48). Since OA-11 it
1855
+ * Map a `reasoning_item_created` run-item. Since reasoning is sourced from the terminal output it
1348
1856
  * is the FALLBACK source: on the live wire it lands after `response.completed`,
1349
1857
  * whose output already filled the block, so a run-item whose `rs_` id is in
1350
1858
  * `filledReasoning` is a no-op (single source per id — no duplicate block, no
1351
1859
  * `late-reasoning` ext). If raw `output_item.added` opened the block but no
1352
1860
  * terminal output has filled it yet, the run-item fills that block in place.
1353
1861
  * Only with NO raw reasoning events for the id (run-item-only streams) does the
1354
- * pre-OA-11 mapping below still run, unchanged:
1862
+ * run-item-only mapping below still run, unchanged:
1355
1863
  *
1356
1864
  * The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
1357
1865
  * the incremental text/tool-arg deltas elsewhere in this facet), so
@@ -1385,15 +1893,15 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1385
1893
  * never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
1386
1894
  * correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
1387
1895
  * is exactly the kind of payload Tenet 6 exists for — silently dropping it here
1388
- * was a genuine loss (review finding on M48). Mirrors `ext.openai.late-citations`
1389
- * (M22) exactly: route it through the lossless vendor channel instead of the bare
1896
+ * was a genuine loss. Mirrors `ext.openai.late-citations` exactly: route it
1897
+ * through the lossless vendor channel instead of the bare
1390
1898
  * return.
1391
1899
  */
1392
1900
  function driveReasoningItemCreated(item) {
1393
- // OA-11 dedupe: already filled from the terminal output (or an earlier run-item).
1901
+ // Dedupe: already filled from the terminal output (or an earlier run-item).
1394
1902
  if (item.id !== undefined && filledReasoning.has(item.id))
1395
1903
  return;
1396
- // OA-11: raw `output_item.added` opened this block; no terminal output has
1904
+ // Raw `output_item.added` opened this block; no terminal output has
1397
1905
  // filled it yet (synthetic ordering) — fill it in place from the run-item,
1398
1906
  // whose `content[]` IS the raw `summary[]` (one part per index).
1399
1907
  if (msgId !== undefined && item.id !== undefined && openReasoning.has(item.id)) {
@@ -1431,7 +1939,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1431
1939
  ...(itemId !== undefined ? { itemId } : {}),
1432
1940
  });
1433
1941
  }
1434
- // OA-11: a terminal output naming this rs_ later must not open a second block.
1942
+ // A terminal output naming this rs_ later must not open a second block.
1435
1943
  if (itemId !== undefined)
1436
1944
  filledReasoning.add(itemId);
1437
1945
  }
@@ -1446,7 +1954,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1446
1954
  * pending bookkeeping and — if the turn's pending set just drained to empty
1447
1955
  * — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
1448
1956
  * the `function_call` `tool_output` arm and the built-in Shell/Apply-Patch
1449
- * `tool_output` arm (playbook 2026-07-03 SDK-bump adaptation, Finding #1).
1957
+ * `tool_output` arm (the 2026-07-03 SDK-bump adaptation).
1450
1958
  */
1451
1959
  /**
1452
1960
  * HO-P, the handoff round release (§8.0 item 14, draft.5). Called at
@@ -1486,11 +1994,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1486
1994
  }
1487
1995
  if (pending.size > 0)
1488
1996
  return;
1489
- const stashed = stashedCloseByTurn.get(sourceTurnId);
1490
- if (stashed === undefined)
1491
- return;
1492
- stashedCloseByTurn.delete(sourceTurnId);
1493
- emitRoundClose(sourceTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
1997
+ maybeReleaseRound(sourceTurnId);
1494
1998
  }
1495
1999
  function drainPendingTool(callId, doneTurnId) {
1496
2000
  if (doneTurnId === undefined)
@@ -1500,17 +2004,13 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1500
2004
  if (pending === undefined)
1501
2005
  return;
1502
2006
  pending.delete(callId);
1503
- if (pending.size === 0) {
1504
- const stashed = stashedCloseByTurn.get(doneTurnId);
1505
- if (stashed !== undefined) {
1506
- // The pending set just drained — emit the deferred message.end +
1507
- // turn.done immediately after this tool.done, same push() batch
1508
- // (INV-MSG: the message must still be open when tool.done lands, so
1509
- // message.end waits for this too).
1510
- stashedCloseByTurn.delete(doneTurnId);
1511
- emitRoundClose(doneTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
1512
- }
1513
- }
2007
+ // The pending set just drained — emit the deferred message.end +
2008
+ // turn.done immediately after this tool.done, same push() batch
2009
+ // (INV-MSG: the message must still be open when tool.done lands, so
2010
+ // message.end waits for this too), unless a listed built-in call of the
2011
+ // round has yet to land (see "Built-in round attach").
2012
+ if (pending.size === 0)
2013
+ maybeReleaseRound(doneTurnId);
1514
2014
  }
1515
2015
  /** True if any shell command in `entries` timed out or exited non-zero. */
1516
2016
  function shellOutputHasError(entries) {
@@ -1524,7 +2024,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1524
2024
  }
1525
2025
  /**
1526
2026
  * Map a `tool_output` run-item whose `rawItem` is a Shell, Apply-Patch, or
1527
- * Computer-Use result (playbook 2026-07-03 SDK-bump adaptation, Finding #1;
2027
+ * Computer-Use result (the 2026-07-03 SDK-bump adaptation;
1528
2028
  * `computer_call_result` added by the fixture-drift ratchet finding, same
1529
2029
  * date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
1530
2030
  * (a bare string / content-part union) — `shell_call_output.output` is an
@@ -1557,7 +2057,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1557
2057
  shellOutputHasError(rawItem.output) || rawItem.status === "incomplete" ? "error" : "ok";
1558
2058
  // The full per-command record (stdout/stderr/exit code) is lossy to
1559
2059
  // collapse into text-only content — carry it verbatim as structuredContent
1560
- // too (mirrors the function_call path's ggui-cache-marker precedent).
2060
+ // too (mirrors the function_call path's cache-marker precedent).
1561
2061
  structuredContent = JsonValue.parse(rawItem.output);
1562
2062
  // The outcome mapping alone cannot recover `status` ('in_progress' vs
1563
2063
  // 'completed' vs absent all map ok) — carry it verbatim, with caller.
@@ -1630,7 +2130,11 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1630
2130
  if (raw === undefined || raw.length === 0)
1631
2131
  return {};
1632
2132
  try {
1633
- return JsonValue.parse(JSON.parse(raw));
2133
+ const parsed = parseVendorJson(raw);
2134
+ // A capped value keeps the arguments, verbatim, on the ext carry.
2135
+ if (parsed.capped)
2136
+ a.emitExt("openai", "unparsed", { itemId: itemId ?? null, arguments: raw });
2137
+ return parsed.value;
1634
2138
  }
1635
2139
  catch {
1636
2140
  a.emitExt("openai", "unparsed", { itemId: itemId ?? null, arguments: raw });
@@ -1640,7 +2144,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1640
2144
  /**
1641
2145
  * Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
1642
2146
  * built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
1643
- * — playbook 2026-07-03 SDK-bump adaptation, Finding #1; `computer_call`
2147
+ * — the 2026-07-03 SDK-bump adaptation; `computer_call`
1644
2148
  * added by the fixture-drift ratchet finding, same date). Unlike
1645
2149
  * `function_call` (whose tool-start rides the raw `response.output_item.
1646
2150
  * added` stream — the authoritative source, canonical model A1), this
@@ -1651,11 +2155,12 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1651
2155
  * action/operation arrives complete on this one wrapper), and
1652
2156
  * `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
1653
2157
  * an agents-core-internal umbrella normalized only at this run-item layer).
1654
- * `ensureResponseOpen()` mirrors the raw function_call path's treatment
1655
- * (both are tool-START signals expected EARLY in a round, unlike the
1656
- * LATE-arriving `tool_output`/`message_output_created` run-items this file
1657
- * already documents) — residual ordering risk if a future capture shows
1658
- * otherwise is flagged in the adaptation report, not silently assumed away.
2158
+ * Like every run-item, this wrapper lands AFTER its response's
2159
+ * `response.completed` (agents-core 0.18.0 streams a response's step items
2160
+ * after the raw loop, run.mjs:1935), so it attaches to the round its
2161
+ * terminal listed, whose close is deferred for it (see "Built-in round
2162
+ * attach"); it opens a response only when none has been seen for it (a
2163
+ * run-item that lands while its response is open joins that response).
1659
2164
  *
1660
2165
  * `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
1661
2166
  * result arrives via a LATER `tool_output` run-item, same Task-4b
@@ -1667,7 +2172,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1667
2172
  * doc) — no pending registration.
1668
2173
  */
1669
2174
  /**
1670
- * OA-13: did OpenAI (the provider) already execute this built-in call? →
2175
+ * Did OpenAI (the provider) already execute this built-in call? →
1671
2176
  * `tool.start.providerExecuted` (SPEC:632; SPEC:496 "client MUST NOT
1672
2177
  * execute"). Per the installed runtime (agents-core 0.18.0
1673
2178
  * `dist/runner/modelOutputs.mjs`): `hosted_tool_call` always (resolved
@@ -1689,26 +2194,260 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1689
2194
  }
1690
2195
  return false;
1691
2196
  }
2197
+ /**
2198
+ * The toolCallId of a `hosted_tool_call`: its item id when it has one. An
2199
+ * id-less item gets a derived id, `<name>_<invoke stem>_<n>` (INV-BLOCK,
2200
+ * SPEC:767: "Normalizers MUST mint collision-free **derived** ids when the
2201
+ * framework omits one"), never its `name`, which two items of one invoke
2202
+ * can share. An `mcp_approval_response` (which agents-core 0.18.0 builds
2203
+ * with no id, runner/mcpApprovals.mjs:39-49) is no call of its own: it
2204
+ * closes the request it answers (`driveApprovalAnswer`).
2205
+ */
2206
+ function hostedToolCallId(rawItem) {
2207
+ if (rawItem.id !== undefined && rawItem.id.length > 0)
2208
+ return rawItem.id;
2209
+ return `${rawItem.name}_${invokeStem}_${++derivedOrdinal}`;
2210
+ }
2211
+ /** The hosted-MCP kind of a `hosted_tool_call`, by its `name` or its
2212
+ * `providerData.type` (agents-openai's converter matches either,
2213
+ * openaiResponsesConverter.mjs:1066-1115). */
2214
+ function hostedMcpKind(rawItem) {
2215
+ const type = rawItem.providerData?.type;
2216
+ for (const kind of ["mcp_call", "mcp_approval_request", "mcp_approval_response"]) {
2217
+ if (rawItem.name === kind || type === kind)
2218
+ return kind;
2219
+ }
2220
+ return undefined;
2221
+ }
2222
+ /**
2223
+ * An `mcp_approval_response` run-item closes the request it answers
2224
+ * (`providerData.approval_request_id`) with exactly one `tool.done`:
2225
+ * outcome "ok" when `providerData.approve` is true, which records the
2226
+ * approval and not the result of the call it gates, and "denied" when it is
2227
+ * not. It creates no block of its own, and the `mcp_call` it gates is a
2228
+ * separate call under its own id. The request is a pending call of its
2229
+ * round in the same invoke (the onApproval flow); in a resuming invoke it
2230
+ * is unknown, and the answer lands as a leading result does
2231
+ * (`openTurnForLeadingResult`, INV-XINV). An answer's `reason` rides
2232
+ * tool.done providerMetadata. Three answers have nothing to close, and each
2233
+ * is carried verbatim on ext.openai.unparsed: one that names no request; a
2234
+ * second answer to a request this invoke already closed (agents-core
2235
+ * answers each request once, runner/mcpApprovals.mjs), which would close it
2236
+ * twice; and one naming a request this invoke does not hold while a
2237
+ * response is open, which no leading turn can take.
2238
+ */
2239
+ function driveApprovalAnswer(rawItem) {
2240
+ const requestId = rawItem.providerData?.approval_request_id;
2241
+ if (typeof requestId !== "string" || requestId.length === 0 || answeredRequests.has(requestId)) {
2242
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
2243
+ return;
2244
+ }
2245
+ const reason = rawItem.providerData?.reason;
2246
+ const meta = openaiProviderMeta({
2247
+ reason: typeof reason === "string" && reason.length > 0 ? reason : undefined,
2248
+ caller: callerToJson(rawItem.caller),
2249
+ });
2250
+ const doneTurnId = resolvePendingTurnId(requestId);
2251
+ const leading = doneTurnId === undefined ? openTurnForLeadingResult(requestId) : undefined;
2252
+ if (doneTurnId === undefined && leading === undefined) {
2253
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
2254
+ return;
2255
+ }
2256
+ answeredRequests.add(requestId);
2257
+ a.toolDone({
2258
+ toolCallId: requestId,
2259
+ content: [],
2260
+ outcome: rawItem.providerData?.approve === true ? "ok" : "denied",
2261
+ ...(meta !== undefined ? { providerMetadata: meta } : {}),
2262
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : leading),
2263
+ });
2264
+ drainPendingTool(requestId, doneTurnId);
2265
+ }
2266
+ /**
2267
+ * A hosted call's input. agents-openai's converter keeps a hosted item's
2268
+ * fields in `providerData` (SPEC:965: a native value is never dropped
2269
+ * silently):
2270
+ * - its `arguments` (top-level when present, else in providerData — the
2271
+ * MCP kinds);
2272
+ * - else a web_search's `action` without its `sources`, which are the
2273
+ * call's result, not its input;
2274
+ * - else a file_search's `queries`;
2275
+ * - else a code_interpreter's `code` and `container_id` (its call payload
2276
+ * without its `outputs`, the program precedent).
2277
+ */
2278
+ function hostedInput(rawItem) {
2279
+ const pd = rawItem.providerData;
2280
+ const args = rawItem.arguments ?? pd?.arguments;
2281
+ if (typeof args === "string")
2282
+ return parseJsonArguments(rawItem.id, args);
2283
+ const action = pd?.action;
2284
+ if (isJsonObject(action)) {
2285
+ const input = {};
2286
+ for (const [k, v] of Object.entries(action))
2287
+ if (k !== "sources")
2288
+ input[k] = v;
2289
+ return JsonValue.parse(input);
2290
+ }
2291
+ if (rawItem.name === "file_search_call" && pd?.queries !== undefined)
2292
+ return JsonValue.parse({ queries: pd.queries });
2293
+ if (rawItem.name === "code_interpreter_call" && (pd?.code !== undefined || pd?.container_id !== undefined)) {
2294
+ return JsonValue.parse({
2295
+ ...(pd?.code !== undefined ? { code: pd.code } : {}),
2296
+ ...(pd?.container_id !== undefined ? { container_id: pd.container_id } : {}),
2297
+ });
2298
+ }
2299
+ return {};
2300
+ }
2301
+ /**
2302
+ * A hosted call's result: its `output` (an image_generation result, which
2303
+ * is base64 image data, as a file block; any other as text), a
2304
+ * web_search's `sources`, an mcp_list_tools listing, a file_search's
2305
+ * `results` and a code_interpreter's `outputs` as data blocks, and its
2306
+ * outcome. The outcome is "error" when the native status is `failed` or
2307
+ * `incomplete`, as a shell, program or function result's `incomplete` is
2308
+ * (and an apply-patch result's `failed`); for an mcp_call, whose top-level
2309
+ * status the converter always sets to "completed", the status in
2310
+ * providerData. It is also "error" when the item carries a non-null
2311
+ * `error`, an empty string included, even with a `completed` status. Any
2312
+ * other status (`in_progress`,
2313
+ * `searching`, `interpreting`, …) closes "ok"; a status other than
2314
+ * `completed` rides tool.done providerMetadata.status verbatim.
2315
+ */
2316
+ function hostedResult(rawItem) {
2317
+ const pd = rawItem.providerData;
2318
+ const content = [];
2319
+ const output = rawItem.output;
2320
+ if (typeof output === "string" && output.length > 0) {
2321
+ content.push(rawItem.name === "image_generation_call"
2322
+ ? { type: "file", source: { type: "base64", mediaType: imageResultMediaType(pd, output), data: output } }
2323
+ : { type: "text", text: output });
2324
+ }
2325
+ const action = pd?.action;
2326
+ if (isJsonObject(action) && Array.isArray(action.sources)) {
2327
+ content.push({ type: "data", name: "web_search_sources", data: JsonValue.parse(action.sources) });
2328
+ }
2329
+ const tools = pd?.tools;
2330
+ if (rawItem.name === "mcp_list_tools" && Array.isArray(tools)) {
2331
+ content.push({ type: "data", name: "mcp_list_tools", data: JsonValue.parse(tools) });
2332
+ }
2333
+ const results = pd?.results;
2334
+ if (rawItem.name === "file_search_call" && Array.isArray(results)) {
2335
+ content.push({ type: "data", name: "file_search_results", data: JsonValue.parse(results) });
2336
+ }
2337
+ const outputs = pd?.outputs;
2338
+ if (rawItem.name === "code_interpreter_call" && Array.isArray(outputs)) {
2339
+ content.push({ type: "data", name: "code_interpreter_outputs", data: JsonValue.parse(outputs) });
2340
+ }
2341
+ const status = hostedMcpKind(rawItem) === "mcp_call" ? (pd?.status ?? rawItem.status) : rawItem.status;
2342
+ // An mcp_call's `error` is an object on the wire (openai-node 7.22.0
2343
+ // McpToolCallError: a protocol or HTTP error {code, message, type}, or a
2344
+ // tool execution error {content, type}): its message (else the object as
2345
+ // JSON) is the errorText, its type the errorCode, and the object rides
2346
+ // tool.done providerMetadata verbatim. A non-empty string error is its own
2347
+ // text; any other non-null error (an empty string) rides providerMetadata.
2348
+ const error = pd?.error;
2349
+ const hasError = error !== undefined && error !== null;
2350
+ const errorMessage = isJsonObject(error) ? error.message : undefined;
2351
+ const errorText = typeof error === "string" && error.length > 0
2352
+ ? error
2353
+ : typeof errorMessage === "string" && errorMessage.length > 0
2354
+ ? errorMessage
2355
+ : isJsonObject(error)
2356
+ ? JSON.stringify(error)
2357
+ : undefined;
2358
+ const errorType = isJsonObject(error) ? error.type : undefined;
2359
+ // An image_generation result's own fields (revised prompt, size, quality,
2360
+ // background, action, format) ride tool.done providerMetadata verbatim.
2361
+ const image = rawItem.name === "image_generation_call" ? pd : undefined;
2362
+ const imageField = (k) => {
2363
+ const v = image?.[k];
2364
+ return v === null ? undefined : v;
2365
+ };
2366
+ const providerMetadata = openaiProviderMeta({
2367
+ status: typeof status === "string" && status.length > 0 && status !== "completed" ? status : undefined,
2368
+ error: hasError && errorText !== error ? JsonValue.parse(error) : undefined,
2369
+ revised_prompt: imageField("revised_prompt"),
2370
+ size: imageField("size"),
2371
+ quality: imageField("quality"),
2372
+ background: imageField("background"),
2373
+ action: imageField("action"),
2374
+ output_format: imageField("output_format"),
2375
+ });
2376
+ const meta = providerMetadata !== undefined ? { providerMetadata } : {};
2377
+ if (status === "failed" || status === "incomplete" || hasError) {
2378
+ return {
2379
+ content,
2380
+ outcome: "error",
2381
+ isError: true,
2382
+ ...(errorText !== undefined ? { errorText } : {}),
2383
+ ...(typeof errorType === "string" && errorType.length > 0 ? { errorCode: errorType } : {}),
2384
+ ...meta,
2385
+ };
2386
+ }
2387
+ return { content, outcome: "ok", ...meta };
2388
+ }
1692
2389
  function driveBuiltinToolCalled(rawItem) {
1693
- ensureResponseOpen();
1694
- if (msgId === undefined)
2390
+ const mcpKind = rawItem.type === "hosted_tool_call" ? hostedMcpKind(rawItem) : undefined;
2391
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_response") {
2392
+ driveApprovalAnswer(rawItem);
2393
+ return;
2394
+ }
2395
+ // The listed item this run-item is (see "Built-in round attach").
2396
+ const key = rawItem.id;
2397
+ if (rawItem.id !== undefined)
2398
+ seenBuiltinItemIds.add(rawItem.id);
2399
+ const toolCallId = rawItem.type === "hosted_tool_call" ? hostedToolCallId(rawItem) : rawItem.callId;
2400
+ // A run-item that lands after its round's terminal attaches to that round;
2401
+ // one that lands while a response is open belongs to it. A hosted call
2402
+ // that no round claims while no response is open (not a 0.18.0 shape: a
2403
+ // resuming invoke leads with a tool result or an approval's answer) opens
2404
+ // its turn as a leading tool result does (`openTurnForLeadingResult`), in
2405
+ // an assistant message of its own, `<toolCallId>:call`, closed after the
2406
+ // call: the response that follows then opens its own message in that
2407
+ // turn, with its model. A leading client-executed or tool-search call
2408
+ // keeps the response open.
2409
+ const late = lateBuiltinRound(key);
2410
+ // openTurnForLeadingResult returns undefined while a response is open.
2411
+ const leading = late === undefined && rawItem.type === "hosted_tool_call" ? openTurnForLeadingResult(toolCallId) : undefined;
2412
+ const callMsgId = leading !== undefined ? `${toolCallId}:call` : undefined;
2413
+ if (leading !== undefined && callMsgId !== undefined) {
2414
+ a.openMessage({ id: callMsgId, role: "assistant", turnId: leading.turnId, threadId });
2415
+ }
2416
+ else if (late === undefined) {
2417
+ ensureResponseOpen();
2418
+ }
2419
+ const ownerMsgId = late !== undefined ? late.mId : (callMsgId ?? msgId);
2420
+ const ownerTurnId = late !== undefined ? late.tid : (leading?.turnId ?? turnId);
2421
+ if (ownerMsgId === undefined)
1695
2422
  return; // unreachable post-ensure; satisfies narrowing
1696
- const toolCallId = rawItem.type === "hosted_tool_call" ? (rawItem.id ?? rawItem.name) : rawItem.callId;
1697
- const name = builtinToolName(rawItem);
2423
+ // An MCP call or approval request is named by the MCP tool it calls
2424
+ // (`providerData.name`); the item's own name is the umbrella (`mcp_call` /
2425
+ // `mcp_approval_request`), which rides providerMetadata.type.
2426
+ const mcpToolName = mcpKind !== undefined ? rawItem.providerData?.name : undefined;
2427
+ const name = typeof mcpToolName === "string" && mcpToolName.length > 0 ? mcpToolName : builtinToolName(rawItem);
1698
2428
  // Caller provenance (0.14.0): typed only on the shapes the wire declares
1699
2429
  // it for — computer_call and program carry none (protocol.d.ts).
1700
2430
  const caller = rawItem.type === "shell_call" || rawItem.type === "apply_patch_call" || rawItem.type === "hosted_tool_call"
1701
2431
  ? rawItem.caller
1702
2432
  : undefined;
1703
- const startMeta = openaiProviderMeta({ caller: callerToJson(caller) });
2433
+ // An mcp_call that an approval gated names that request (verbatim).
2434
+ const approvalRequestId = mcpKind === "mcp_call" ? rawItem.providerData?.approval_request_id : undefined;
2435
+ const startMeta = openaiProviderMeta({
2436
+ caller: callerToJson(caller),
2437
+ type: mcpKind,
2438
+ approval_request_id: typeof approvalRequestId === "string" && approvalRequestId.length > 0 ? approvalRequestId : undefined,
2439
+ });
2440
+ // An MCP item's server label (SPEC tool.start.serverName).
2441
+ const serverLabel = rawItem.type === "hosted_tool_call" ? rawItem.providerData?.server_label : undefined;
1704
2442
  a.toolStart({
1705
2443
  toolCallId,
1706
2444
  name,
2445
+ ...(typeof serverLabel === "string" && serverLabel.length > 0 ? { serverName: serverLabel } : {}),
1707
2446
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1708
2447
  ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
1709
- // OA-13: see builtinProviderExecuted().
2448
+ // See builtinProviderExecuted().
1710
2449
  ...(builtinProviderExecuted(rawItem) ? { providerExecuted: true } : {}),
1711
- messageId: msgId,
2450
+ messageId: ownerMsgId,
1712
2451
  });
1713
2452
  const input = rawItem.type === "shell_call"
1714
2453
  ? JsonValue.parse(rawItem.action)
@@ -1720,15 +2459,30 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1720
2459
  ? // The call's whole wire payload, verbatim (the shell/apply-patch
1721
2460
  // precedent): `code` is the model-authored program source.
1722
2461
  { code: rawItem.code, fingerprint: rawItem.fingerprint }
1723
- : parseJsonArguments(rawItem.id, rawItem.arguments);
2462
+ : hostedInput(rawItem);
1724
2463
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
1725
2464
  a.toolArgsAssembled(toolCallId, input);
2465
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_request") {
2466
+ // Not resolved: the request stays a pending call of its round until its
2467
+ // answer closes it; with no answer, the round flushes paused naming its
2468
+ // ask (§8.0 items 14 and 20, INV-FLUSH (2)).
2469
+ if (callMsgId !== undefined)
2470
+ a.closeMessage(callMsgId);
2471
+ registerPendingToolFor(ownerTurnId, toolCallId);
2472
+ drainListedBuiltin(key);
2473
+ return;
2474
+ }
1726
2475
  if (rawItem.type === "hosted_tool_call") {
1727
- const content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
1728
- a.toolDone({ toolCallId, content, outcome: "ok" });
2476
+ const doneTurnId = late?.tid ?? leading?.turnId;
2477
+ a.toolDone({ toolCallId, ...hostedResult(rawItem), ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}) });
2478
+ if (callMsgId !== undefined)
2479
+ a.closeMessage(callMsgId);
2480
+ drainListedBuiltin(key);
1729
2481
  return;
1730
2482
  }
1731
- registerPendingTool(toolCallId);
2483
+ registerPendingToolFor(ownerTurnId, toolCallId);
2484
+ // Its run-item has landed; the round now waits on its result.
2485
+ drainListedBuiltin(key);
1732
2486
  }
1733
2487
  /**
1734
2488
  * Resolve the correlation id for a `tool_search_call`/`tool_search_output`
@@ -1779,29 +2533,40 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1779
2533
  * like any other unresolved pending tool call, no special-casing needed.
1780
2534
  */
1781
2535
  function driveToolSearchCalled(rawItem) {
1782
- ensureResponseOpen();
1783
- if (msgId === undefined)
1784
- return; // unreachable post-ensure; satisfies narrowing
2536
+ if (rawItem.id !== undefined)
2537
+ seenBuiltinItemIds.add(rawItem.id);
1785
2538
  const toolCallId = resolveToolSearchCallId(rawItem);
1786
2539
  if (toolCallId === undefined) {
1787
- // Genuinely unresolvable correlation id — never fabricate one (Tenet 6).
2540
+ // Genuinely unresolvable correlation id — never fabricate one (Tenet 6),
2541
+ // and open no turn for it: the carry is not block content.
1788
2542
  a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
2543
+ drainListedBuiltin(rawItem.id);
1789
2544
  return;
1790
2545
  }
2546
+ // A run-item that lands after its round's terminal attaches to that round
2547
+ // (see "Built-in round attach").
2548
+ const late = lateBuiltinRound(rawItem.id);
2549
+ if (late === undefined)
2550
+ ensureResponseOpen();
2551
+ const ownerMsgId = late !== undefined ? late.mId : msgId;
2552
+ const ownerTurnId = late !== undefined ? late.tid : turnId;
2553
+ if (ownerMsgId === undefined)
2554
+ return; // unreachable post-ensure; satisfies narrowing
1791
2555
  a.toolStart({
1792
2556
  toolCallId,
1793
2557
  name: "builtin:tool_search",
1794
2558
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1795
- // OA-13: the item says where it ran — only `execution:"server"` is the
2559
+ // The item says where it ran — only `execution:"server"` is the
1796
2560
  // provider's (SPEC:496); "client" (the SDK's own loader / a custom
1797
2561
  // execute()) and absent leave the key off.
1798
2562
  ...(rawItem.execution === "server" ? { providerExecuted: true } : {}),
1799
- messageId: msgId,
2563
+ messageId: ownerMsgId,
1800
2564
  });
1801
2565
  const input = JsonValue.parse(rawItem.arguments ?? {});
1802
2566
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
1803
2567
  a.toolArgsAssembled(toolCallId, input);
1804
- registerPendingTool(toolCallId);
2568
+ registerPendingToolFor(ownerTurnId, toolCallId);
2569
+ drainListedBuiltin(rawItem.id);
1805
2570
  }
1806
2571
  /**
1807
2572
  * Map a `tool_search_output_created` run-item — the paired completion (see
@@ -1834,8 +2599,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1834
2599
  // the deserialization boundary, where a non-string would otherwise reach
1835
2600
  // `AgProviderMeta.parse`.
1836
2601
  const rawAgentName = rawItem.toolSearchAgentName;
2602
+ // agents-core 0.20.0 adds the hosted MCP names this search established
2603
+ // (`toolSearchMcpToolNames`), carried the same way: an array of strings,
2604
+ // verbatim; anything else at this boundary is no carry.
2605
+ const rawMcpNames = rawItem.toolSearchMcpToolNames;
2606
+ const mcpNames = Array.isArray(rawMcpNames) && rawMcpNames.every((v) => typeof v === "string") ? JsonValue.parse(rawMcpNames) : undefined;
1837
2607
  const searchMeta = openaiProviderMeta({
1838
2608
  toolSearchAgentName: typeof rawAgentName === "string" ? rawAgentName : undefined,
2609
+ toolSearchMcpToolNames: mcpNames,
1839
2610
  });
1840
2611
  a.toolDone({
1841
2612
  toolCallId,
@@ -1861,7 +2632,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1861
2632
  function driveHostError(event) {
1862
2633
  // O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
1863
2634
  // close is deferred releases that close per INV-FLUSH (2) BEFORE the
1864
- // normalizer closes the error (PS-21).
2635
+ // normalizer closes the error.
1865
2636
  releaseAllDeferredCloses();
1866
2637
  ensureResponseOpen();
1867
2638
  if (turnId === undefined)
@@ -1911,7 +2682,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1911
2682
  switch (event.name) {
1912
2683
  case "tool_output": {
1913
2684
  const rawItem = event.item.rawItem;
1914
- // Finding #1 (critical) + the fixture-drift ratchet's
2685
+ // The 2026-07-03 SDK-bump adaptation + the fixture-drift ratchet's
1915
2686
  // computer_call_result finding + the 0.14.0 program_output carry:
1916
2687
  // Shell/Apply-Patch/Computer-Use/Program results do NOT share
1917
2688
  // `OpenAIFunctionCallResultItem.output`'s shape — see
@@ -1938,7 +2709,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1938
2709
  return;
1939
2710
  }
1940
2711
  // Authoritative tool-result source (canonical model, A1). Drives toolDone
1941
- // with content + structuredContent (the ggui cache marker — see
2712
+ // with content + structuredContent (a reference client's cache marker — see
1942
2713
  // `extractStructuredContent`'s doc for the two peer-supported homes and
1943
2714
  // the playbook 2026-07-03 wire-truth findings behind them).
1944
2715
  const outcome = rawItem.status === "incomplete" ? "error" : "ok";
@@ -1946,7 +2717,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1946
2717
  const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
1947
2718
  // workspace#21: `customData._meta` → block `_meta`; with `_meta.ui` the
1948
2719
  // payload is MCP-Apps view data → ALSO `uiData` (SPEC.md:332), leaving
1949
- // `structuredContent` as it was (the :340 mapping; ggui's cache marker
2720
+ // `structuredContent` as it was (the :340 mapping; a reference client's cache marker
1950
2721
  // rides it). §2.1's "exactly one consumer" is per channel (ruled
1951
2722
  // option A). Mirrors claude-agent-sdk/src/index.ts:1926-1946.
1952
2723
  const resultMeta = extractResultMeta(event.item.customData);
@@ -1960,7 +2731,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1960
2731
  // could misattribute it) and pass it through so toolDone binds to the
1961
2732
  // correct — possibly already-closed-pending-this-result — turn.
1962
2733
  const doneTurnId = resolvePendingTurnId(rawItem.callId);
1963
- // HO-2 (the handoff-drop review, PS-4): a result for a transfer call
2734
+ // A result for a transfer call
1964
2735
  // whose bracket is still open means that handoff never ran —
1965
2736
  // agents-core <=0.8.0's "Multiple handoffs detected, ignoring this
1966
2737
  // one." (0.8.0 toolExecution.mjs:750-755), the one streamed producer.
@@ -2017,7 +2788,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2017
2788
  // ignoring the wrapper copy here loses nothing.
2018
2789
  return;
2019
2790
  }
2020
- // Finding #1 (critical): Shell / Apply-Patch / Hosted-tool /
2791
+ // The 2026-07-03 SDK-bump adaptation: Shell / Apply-Patch / Hosted-tool /
2021
2792
  // Program built-ins — this run-item wrapper (not the raw stream) is
2022
2793
  // the SOLE tool-start source for these (see `driveBuiltinToolCalled`'s
2023
2794
  // doc).
@@ -2034,7 +2805,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2034
2805
  driveToolSearchOutput(event.item.rawItem);
2035
2806
  return;
2036
2807
  case "reasoning_item_created":
2037
- // FALLBACK source since OA-11 (the raw terminal output fills first; an
2808
+ // FALLBACK source (the raw terminal output fills first; an
2038
2809
  // already-filled rs_ is a no-op) — see driveReasoningItemCreated's docstring.
2039
2810
  driveReasoningItemCreated(event.item.rawItem);
2040
2811
  return;
@@ -2051,7 +2822,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2051
2822
  // `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
2052
2823
  // bracket the transfer with `subagentStart` now / `subagentDone` at the
2053
2824
  // matching `handoff_occurred` below (by callId via `openHandoffs`; or at
2054
- // the call's `tool_output` when the handoff never ran — HO-2).
2825
+ // the call's `tool_output` when the handoff never ran).
2055
2826
  //
2056
2827
  // `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
2057
2828
  // LLM call produced this handoff call — NOT the transfer target (see
@@ -2123,7 +2894,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2123
2894
  // still emit the `handoff` event losslessly rather than dropping the
2124
2895
  // now-known identity (Tenet 6) — it just doesn't close anything. It
2125
2896
  // precedes the tool.done, which may close the source round.
2126
- // HO-2: the handoff is owned by the SOURCE turn, explicitly. With two
2897
+ // The handoff is owned by the SOURCE turn, explicitly. With two
2127
2898
  // brackets open (agents-core <=0.8.0) the engine's backfill would pick
2128
2899
  // the last-restored nested turn; on every single-bracket stream this is
2129
2900
  // the value the backfill gave.
@@ -2169,22 +2940,31 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2169
2940
  return;
2170
2941
  }
2171
2942
  case "tool_approval_requested": {
2172
- // Task 3 (audit M48): a human-in-the-loop approval gate on a pending
2173
- // tool call. `askId` mirrors the `approval_${callId}` convention already
2174
- // established by the google-adk facet's `requestedToolConfirmations` arm
2175
- // (index.ts:653) for the same `kind:"approval"` semantics. The M26
2176
- // paused-fold discipline (surfacing this on the turn's `outcome.paused`)
2177
- // is ADK-scoped for this batch — `hitl.ask` is LIVE-ONLY on the fold
2178
- // (reduce.ts R9: no accumulator mutation), so emitting the ask alone is
2179
- // complete; the host/turn-close owns any pause semantics.
2943
+ // A human-in-the-loop approval gate on a pending tool call. `askId`
2944
+ // mirrors the `approval_${callId}` convention of the google-adk
2945
+ // facet's `requestedToolConfirmations` arm for the same
2946
+ // `kind:"approval"` semantics. The gated call stays pending, so a
2947
+ // round the stream leaves waiting on it flushes paused naming this
2948
+ // ask (INV-FLUSH (2)).
2180
2949
  const item = event.item.rawItem;
2950
+ // The call the ask gates: a function, shell, apply-patch or computer
2951
+ // call's callId, else the item's id. A hosted-MCP approval request
2952
+ // has no callId, and its id is the request id its tool.start uses.
2953
+ // callId comes first, so a function approval's ask is unchanged.
2954
+ const gatedId = item.callId ?? item.id;
2955
+ if (gatedId === undefined) {
2956
+ // No id to key on: a collision-free derived askId (INV-BLOCK) and
2957
+ // no toolCallId, rather than naming a call the facet cannot find.
2958
+ a.emit({ type: "hitl.ask", askId: `approval_${invokeStem}_${++derivedOrdinal}`, kind: "approval" });
2959
+ return;
2960
+ }
2181
2961
  a.emit({
2182
2962
  type: "hitl.ask",
2183
- askId: `approval_${item.callId}`,
2963
+ askId: `approval_${gatedId}`,
2184
2964
  kind: "approval",
2185
- toolCallId: item.callId,
2965
+ toolCallId: gatedId,
2186
2966
  });
2187
- askedApprovals.set(item.callId, `approval_${item.callId}`);
2967
+ askedApprovals.set(gatedId, `approval_${gatedId}`);
2188
2968
  return;
2189
2969
  }
2190
2970
  default:
@@ -2251,7 +3031,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2251
3031
  flush() {
2252
3032
  // O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
2253
3033
  // closes FIRST — they are older rounds, so their message.end precedes the
2254
- // live response's (insertion order, CB-16) — as paused / verbatim /
3034
+ // live response's (insertion order) — as paused / verbatim /
2255
3035
  // message.end+usage then turn.abort (`releaseDeferredClose`); a flush
2256
3036
  // never emits a success turn.done.
2257
3037
  releaseAllDeferredCloses();