@silverprotocol/openai-agents 0.12.5 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -94,7 +94,145 @@
94
94
  */
95
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,19 @@ 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
+ * A computer screenshot's `data` as an AgSource `base64` arm. The SDK sends a
475
+ * `data:<media type>;base64,<payload>` URL; the payload lands as `data` and the
476
+ * header's media type as `mediaType`. A value with no such header lands
477
+ * verbatim as image/png.
478
+ */
479
+ function screenshotSource(data) {
480
+ const header = /^data:([^;,]+);base64,/.exec(data);
481
+ if (header === null || header[1] === undefined)
482
+ return { type: "base64", mediaType: "image/png", data };
483
+ return { type: "base64", mediaType: header[1], data: data.slice(header[0].length) };
484
+ }
485
+ /**
486
+ * Extract `structuredContent` (a reference client's cache-marker channel, spec §2.1/§4)
312
487
  * from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
313
488
  * follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
314
489
  * would be an object keyed by `.structuredContent`; a live capture
@@ -393,11 +568,11 @@ function extractStructuredContent(wrapperOutput, customData) {
393
568
  return undefined;
394
569
  }
395
570
  /**
396
- * workspace#21 (guuey#981): the MCP tool result's `_meta`, riding the same
571
+ * workspace#21 (a reference host's ask): the MCP tool result's `_meta`, riding the same
397
572
  * host-convention `customData` channel as `structuredContent` (SPEC.md:340) —
398
573
  * agents-core 0.18.0 hands it to `MCPServer.customDataExtractor` as
399
574
  * `context.resultMeta` (`dist/mcpUtil.d.ts`:41, `result._meta ?? content._meta`
400
- * at `dist/mcp.mjs`:700); guuey's worker and this repo's capture agent return it
575
+ * at `dist/mcp.mjs`:700); a reference host's worker and this repo's capture agent return it
401
576
  * as `customData._meta`. It is a host/protocol annotation (MCP-Apps `ui.*`), so
402
577
  * it rides the tool-result block's own `_meta` VERBATIM (SPEC.md:338; §8.0
403
578
  * no-drop). Ruled option A on 2026-09-23. A non-object `_meta`
@@ -456,7 +631,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
456
631
  let responseId; // real response.id once known
457
632
  // Open text streams keyed by Responses item_id (textStart once per id).
458
633
  const openTextStreams = new Set();
459
- // OA-11 reasoning-block state. `openReasoning`: rs_ id → the message id its
634
+ // Reasoning-block state (reasoning from the terminal output). `openReasoning`: rs_ id → the message id its
460
635
  // block opened in (at `output_item.added{reasoning}`), awaiting its fill from
461
636
  // the terminal output; per-response (cleared by `resetResponseState`).
462
637
  // `filledReasoning`: every rs_ id whose block has been filled — normalizer-
@@ -464,14 +639,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
464
639
  // response closed and must dedupe against it (single source per rs_ id).
465
640
  const openReasoning = new Map();
466
641
  const filledReasoning = new Set();
467
- // OA-14 phase state. `pendingPhase`: message item id → the phase its raw
642
+ // Phase state (the phase read at the raw add). `pendingPhase`: message item id → the phase its raw
468
643
  // `output_item.added` announced, awaiting that item's `text.start`
469
644
  // (per-response). `carriedPhase`: item id → the phase that rode its
470
645
  // `text.start` — normalizer-lifetime, because the run-item it retires
471
646
  // `ext.openai.late-phase` against lands AFTER the response closed.
472
647
  const pendingPhase = new Map();
473
648
  const carriedPhase = new Map();
474
- // PH-2 (draft.4 stage 2): text stream ids whose `text.start` already set the
649
+ // The first-class phase (draft.4): text stream ids whose `text.start` already set the
475
650
  // first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
476
651
  // `text.end` fields learned for a round close that is STASHED (deferred until
477
652
  // its tool results land) — consumed by `emitRoundClose`.
@@ -524,16 +699,19 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
524
699
  let lastTopLevelTurnId;
525
700
  // Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
526
701
  let handoffOrdinal = 0;
702
+ // Per-invoke ordinal for a derived id (INV-BLOCK, SPEC:767) when a native
703
+ // item carries no id the facet can key on.
704
+ let derivedOrdinal = 0;
527
705
  // Open handoff brackets, keyed by the transfer call's callId (paired turnId
528
706
  // + the SAME parentTurnId `subagentStart` used — `subagentDone` must replay
529
707
  // it verbatim, mirroring the claude-agent-sdk facet's paired start/done
530
- // convention). HO-2 (the handoff-drop review, PS-4): matched by callId,
708
+ // convention). Matched by callId,
531
709
  // not FIFO, because agents-core <=0.8.0 opens a bracket for EVERY transfer
532
710
  // the model calls but runs only the first: a bracket closes at
533
711
  // `handoff_occurred` for its own call, or at that call's `tool_output` (the
534
712
  // handoff never ran).
535
713
  const openHandoffs = [];
536
- /** HO-2: remove and return the open bracket for `callId`, if any. */
714
+ /** Remove and return the open bracket for `callId`, if any. */
537
715
  function takeOpenHandoff(callId) {
538
716
  const i = openHandoffs.findIndex((h) => h.callId === callId);
539
717
  if (i === -1)
@@ -550,12 +728,90 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
550
728
  // The engine accumulates for downstream use; `.done.arguments` carries the full
551
729
  // string so argBuffers is primarily for the fallback path.
552
730
  const instanceArgBuffers = new Map();
553
- // Refusal tracking (T5c — instance state mirroring the old module-level
554
- // `pendingRefusal`). Set when a `message_output_created` run-item carries a
555
- // `refusal` content part; the downstream `response.completed` arm then closes
556
- // the turn with `finishReason:"refusal"`. Cleared on every response close so it
557
- // never leaks across turns.
731
+ // Refusal tracking (T5c). Set when a refusal event streams, or when a
732
+ // `message_output_created` run-item carries a `refusal` content part BEFORE
733
+ // its response's terminal event (a synthetic order); the terminal arm also
734
+ // reads the refusal from its own `response.output` (`terminalHasRefusal`),
735
+ // which is the live order: the run-item lands after the close. Cleared on
736
+ // every response close and at every `response.created`, so a late run-item's
737
+ // refusal never reaches the next round.
558
738
  let pendingRefusal = false;
739
+ // Refusal text (SPEC §8.0 graceful degradation: a native event the
740
+ // normalizer can map is never dropped silently). A `refusal` content part's
741
+ // text is a `text` block in the round's message, id `<item id>:refusal` (the
742
+ // same item can also carry an `output_text` part, whose block id is the item
743
+ // id), its `text.start` carrying `providerMetadata.type: "refusal"`, the
744
+ // part's own wire discriminant and the marker a replay reads to send a
745
+ // refusal part back, beside the item's `phase` marker as an output_text
746
+ // block carries it. ONE source per round:
747
+ // - the raw `response.refusal.delta` / `.done` events, when any arrived;
748
+ // - else the refusal part itself, from whichever comes first of the
749
+ // terminal output (read before the round closes) and a
750
+ // `message_output_created` run-item that lands while the round is open.
751
+ // A run-item that lands after the close, with no copy emitted, rides
752
+ // `ext.openai.late-message` (the message is sealed).
753
+ // The source is chosen per round, not matched per item id: a run-item's ids
754
+ // can be a different id space from the raw `item_id`s (the OpenRouter
755
+ // surface mints `msg_tmp_` run-item ids), where an id match would copy the
756
+ // text twice.
757
+ // `openRefusalBlocks`: this response's refusal blocks not yet ended;
758
+ // `refusalBlocks`: every refusal block this response opened (a repeated
759
+ // `.done` never reopens one); `refusalTextEmitted`: the round has its
760
+ // refusal text, cleared at `response.created` only, because the run-item
761
+ // that reads it lands after the round closed. `refusalCarriedPhase`: item id
762
+ // → the phase marker its refusal block carried (normalizer-lifetime, like
763
+ // `carriedPhase`, which stays the output_text blocks' own record).
764
+ const openRefusalBlocks = new Set();
765
+ const refusalBlocks = new Set();
766
+ let refusalTextEmitted = false;
767
+ const refusalCarriedPhase = new Map();
768
+ /** The item's vendor phase marker for a refusal block's `text.start`: the one
769
+ * announced at `output_item.added`, else the one an output_text block of the
770
+ * same item already carried. */
771
+ function refusalItemPhase(itemId) {
772
+ return pendingPhase.get(itemId) ?? carriedPhase.get(itemId);
773
+ }
774
+ /** A refusal block id not yet used this response, for the whole-part sources
775
+ * (an id-less item keys on the message id). */
776
+ function freshRefusalBlockId(itemId, mId) {
777
+ const base = `${itemId ?? mId}:refusal`;
778
+ let id = base;
779
+ for (let k = 2; refusalBlocks.has(id); k++)
780
+ id = `${base}:${k}`;
781
+ return id;
782
+ }
783
+ /** Open refusal block `blockId` in message `mId`. The phase marker rides
784
+ * `text.start` as on an output_text block (the first-class `phase:"interim"`
785
+ * for "commentary"), and is recorded as carried for the late run-item. */
786
+ function openRefusalBlock(blockId, mId, phase, itemId) {
787
+ const startMeta = openaiProviderMeta({ phase, type: "refusal" });
788
+ const interim = interimPhase(phase);
789
+ a.textStart(blockId, mId, {
790
+ role: "assistant",
791
+ ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
792
+ ...(interim !== undefined ? { phase: interim } : {}),
793
+ });
794
+ if (phase !== undefined && itemId !== undefined)
795
+ refusalCarriedPhase.set(itemId, phase);
796
+ openRefusalBlocks.add(blockId);
797
+ refusalBlocks.add(blockId);
798
+ refusalTextEmitted = true;
799
+ }
800
+ /** A whole refusal part as one block: start, the text as one delta (none for
801
+ * an empty text), end. */
802
+ function emitWholeRefusal(blockId, mId, text, phase, itemId) {
803
+ openRefusalBlock(blockId, mId, phase, itemId);
804
+ if (text.length > 0)
805
+ a.textDelta(blockId, mId, text, { cumulative: false });
806
+ a.textEnd(blockId, mId);
807
+ openRefusalBlocks.delete(blockId);
808
+ }
809
+ /** End every refusal block the stream left open (no `.done` before the close). */
810
+ function endOpenRefusalBlocks(mId) {
811
+ for (const blockId of openRefusalBlocks)
812
+ a.textEnd(blockId, mId);
813
+ openRefusalBlocks.clear();
814
+ }
559
815
  // ── Task 4b: defer a round's close past its pending tool results ───────────
560
816
  // (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
561
817
  // AFTER `response.completed` — closing at native-close time would put a later
@@ -573,20 +829,125 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
573
829
  * Register `callId` as pending a `tool.done` under the CURRENT open turn
574
830
  * (Task 4b). Shared by the raw `response.output_item.added` function_call
575
831
  * path and the built-in Shell/Apply-Patch `tool_called` synthesis path
576
- * (playbook 2026-07-03 SDK-bump adaptation, Finding #1) — both start a call
832
+ * (the 2026-07-03 SDK-bump adaptation) — both start a call
577
833
  * whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
578
834
  * is open (defensive; every caller already calls `ensureResponseOpen()` first).
579
835
  */
580
836
  function registerPendingTool(callId) {
581
- if (turnId === undefined)
837
+ registerPendingToolFor(turnId, callId);
838
+ }
839
+ /** Register `callId` as pending a `tool.done` under round `tid`. */
840
+ function registerPendingToolFor(tid, callId) {
841
+ if (tid === undefined)
582
842
  return;
583
- let pending = pendingToolsByTurn.get(turnId);
843
+ let pending = pendingToolsByTurn.get(tid);
584
844
  if (pending === undefined) {
585
845
  pending = new Set();
586
- pendingToolsByTurn.set(turnId, pending);
846
+ pendingToolsByTurn.set(tid, pending);
587
847
  }
588
848
  pending.add(callId);
589
- turnIdByToolCallId.set(callId, turnId);
849
+ turnIdByToolCallId.set(callId, tid);
850
+ }
851
+ // ── Built-in round attach ───────────────────────────────────────────────────
852
+ // agents-core streams a response's built-in call run-items (`tool_called`,
853
+ // `tool_search_called`) after its `response.completed`, so the round has
854
+ // already reached its terminal when they land. A round whose terminal
855
+ // `response.output` lists a built-in call (see BUILTIN_OUTPUT_ITEM_TYPES)
856
+ // defers its close as §8.0 item 14 defers a round for its pending tool
857
+ // results, and each late run-item attaches to THAT round's turn and message
858
+ // (never a turn opened for it). The close is released:
859
+ // - when every listed call has its run-item and every pending result has
860
+ // landed (`maybeReleaseRound`);
861
+ // - at the next `response.created`, when the round still waits only on
862
+ // listed calls whose run-item never streamed (agents-core can suppress
863
+ // one), so the new response keeps its own turn; those calls stop being
864
+ // the round's;
865
+ // - at flush, per INV-FLUSH (2).
866
+ // A listed `mcp_approval_request` becomes a pending call of its round when
867
+ // its `tool_called` lands, and its answer (`mcp_approval_response`) closes
868
+ // it; with no answer, the round flushes paused naming its ask (INV-FLUSH
869
+ // (2)). `listedBuiltinsByTurn`: round → listed item ids still waiting.
870
+ // `builtinTurnByItemId`: listed item id → its round.
871
+ // `seenBuiltinItemIds`: built-in items whose run-item already landed (one
872
+ // that lands before its terminal, a synthetic order), so the terminal never
873
+ // lists them.
874
+ const listedBuiltinsByTurn = new Map();
875
+ const builtinTurnByItemId = new Map();
876
+ const seenBuiltinItemIds = new Set();
877
+ // Approval requests an `mcp_approval_response` has closed in this invoke.
878
+ const answeredRequests = new Set();
879
+ /** List round `tid`'s built-in calls (those whose run-item has not landed). */
880
+ /** List round `tid`'s built-in calls whose run-item has not landed. When
881
+ * it lists any, the round's `message` items are listed too, so their
882
+ * `message_output_created` (and the citations it carries) lands while the
883
+ * round's close is still deferred. */
884
+ function listBuiltins(tid, items, messageIds) {
885
+ const ids = [];
886
+ for (const item of items) {
887
+ if (seenBuiltinItemIds.has(item.id))
888
+ continue;
889
+ ids.push(item.id);
890
+ builtinTurnByItemId.set(item.id, tid);
891
+ }
892
+ if (ids.length === 0)
893
+ return ids;
894
+ for (const id of messageIds) {
895
+ if (seenBuiltinItemIds.has(id))
896
+ continue;
897
+ ids.push(id);
898
+ builtinTurnByItemId.set(id, tid);
899
+ }
900
+ listedBuiltinsByTurn.set(tid, new Set(ids));
901
+ return ids;
902
+ }
903
+ /** The stashed round a late built-in run-item belongs to: the round whose
904
+ * terminal listed `key`, else, when no response is open, the invoke's last
905
+ * round if its close is still stashed (a run-item its terminal did not
906
+ * list). Undefined when neither holds. */
907
+ function lateBuiltinRound(key) {
908
+ const listedTid = key !== undefined ? builtinTurnByItemId.get(key) : undefined;
909
+ const tid = listedTid ?? (turnId === undefined ? lastTopLevelTurnId : undefined);
910
+ if (tid === undefined)
911
+ return undefined;
912
+ const stashed = stashedCloseByTurn.get(tid);
913
+ return stashed !== undefined ? { tid, mId: stashed.msgId } : undefined;
914
+ }
915
+ /** The listed item `key` has what it waited for: drop it, and release its
916
+ * round if nothing else keeps the round open. */
917
+ function drainListedBuiltin(key) {
918
+ if (key === undefined)
919
+ return;
920
+ const tid = builtinTurnByItemId.get(key);
921
+ if (tid === undefined)
922
+ return;
923
+ const listed = listedBuiltinsByTurn.get(tid);
924
+ if (listed === undefined || !listed.delete(key))
925
+ return;
926
+ maybeReleaseRound(tid);
927
+ }
928
+ /** Release round `tid`'s stashed close when no pending result and no listed
929
+ * built-in call keeps it open. */
930
+ function maybeReleaseRound(tid) {
931
+ const stashed = stashedCloseByTurn.get(tid);
932
+ if (stashed === undefined)
933
+ return;
934
+ if ((pendingToolsByTurn.get(tid)?.size ?? 0) > 0)
935
+ return;
936
+ if ((listedBuiltinsByTurn.get(tid)?.size ?? 0) > 0)
937
+ return;
938
+ stashedCloseByTurn.delete(tid);
939
+ listedBuiltinsByTurn.delete(tid);
940
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
941
+ }
942
+ /** At a new `response.created`: every round still waiting on listed calls
943
+ * whose run-item never streamed stops waiting on them, and is released if
944
+ * no pending result keeps it open. */
945
+ function releaseListedAtNextResponse() {
946
+ for (const [tid, listed] of [...listedBuiltinsByTurn]) {
947
+ listed.clear();
948
+ listedBuiltinsByTurn.delete(tid);
949
+ maybeReleaseRound(tid);
950
+ }
590
951
  }
591
952
  // Stashed close for a turn whose pending set was non-empty at close time,
592
953
  // keyed by turnId. Consumed the moment its pending set drains (emitted right
@@ -599,7 +960,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
599
960
  * whichever values are live right now (immediate path) or were captured at
600
961
  * defer time (drain path) — same three calls either way.
601
962
  */
602
- /** PH-2: is `streamId`'s text.end still pending in a STASHED round close
963
+ /** Is `streamId`'s text.end still pending in a STASHED round close
603
964
  * (a deferred tool round), i.e. not yet emitted? */
604
965
  function isStashedTextStream(streamId) {
605
966
  for (const stashed of stashedCloseByTurn.values()) {
@@ -610,10 +971,17 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
610
971
  }
611
972
  function endStashedTextStreams(mId, textStreamIds) {
612
973
  for (const streamId of textStreamIds) {
613
- // PH-2: a phase learned while this close sat stashed rides its text.end.
614
- const endFields = stashedEndFields.get(streamId);
974
+ // Citations and a phase learned while this close sat stashed ride its
975
+ // text.end, in the live path's field order.
976
+ const f = stashedEndFields.get(streamId);
615
977
  stashedEndFields.delete(streamId);
616
- a.textEnd(streamId, mId, endFields);
978
+ a.textEnd(streamId, mId, f === undefined
979
+ ? undefined
980
+ : {
981
+ ...(f.citations !== undefined ? { citations: f.citations } : {}),
982
+ ...(f.providerMetadata !== undefined ? { providerMetadata: f.providerMetadata } : {}),
983
+ ...(f.phase !== undefined ? { phase: f.phase } : {}),
984
+ });
617
985
  }
618
986
  }
619
987
  function emitRoundClose(tid, mId, textStreamIds, fields) {
@@ -659,6 +1027,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
659
1027
  for (const [tid, stashed] of stashedCloseByTurn)
660
1028
  releaseDeferredClose(tid, stashed);
661
1029
  stashedCloseByTurn.clear();
1030
+ listedBuiltinsByTurn.clear();
662
1031
  }
663
1032
  /**
664
1033
  * Close the round now, unless `tid`'s pending-tool set is non-empty — in
@@ -668,9 +1037,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
668
1037
  * immediately via `endOpenStreamsAndCloseMessage` — an errored round's
669
1038
  * pending results are moot, by design).
670
1039
  */
671
- function finishOrDeferRound(tid, mId, textStreamIds, fields) {
1040
+ function finishOrDeferRound(tid, mId, textStreamIds, fields, listing = { builtins: [], messageIds: [] }) {
1041
+ const listed = listBuiltins(tid, listing.builtins, listing.messageIds);
672
1042
  const pending = pendingToolsByTurn.get(tid);
673
- if (pending !== undefined && pending.size > 0) {
1043
+ if ((pending !== undefined && pending.size > 0) || listed.length > 0) {
674
1044
  stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
675
1045
  return;
676
1046
  }
@@ -682,7 +1052,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
682
1052
  * somehow absent (defensive — the spike confirms the id is always present at start).
683
1053
  * Returns the close-once key (the real response.id, else the synthesized turnId),
684
1054
  * or `undefined` when the response has already been closed (caller must no-op).
685
- * `model` (OA-12) rides `message.start.model` — only the authoritative
1055
+ * `model` (the per-message model) rides `message.start.model` — only the authoritative
686
1056
  * `response.created` open passes it; a defensive open never invents one.
687
1057
  */
688
1058
  function ensureResponseOpen(respId, model) {
@@ -734,7 +1104,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
734
1104
  a.openTurn(opened, threadId);
735
1105
  return { turnId: opened, messageId: `${callId}:result` };
736
1106
  }
737
- // Approve-all (the D3 pin, 2026-09-24): the resuming invoke can
1107
+ // Approve-all (pinned 2026-09-24): the resuming invoke can
738
1108
  // replay SEVERAL results before its response. While the resume turn is
739
1109
  // open with no assistant message yet (turnId set, msgId unset — a state
740
1110
  // only this helper creates), each further result joins THAT turn as its
@@ -767,11 +1137,13 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
767
1137
  if (key !== undefined)
768
1138
  closedResponses.add(key);
769
1139
  openTextStreams.clear();
770
- // OA-11: an rs_ block opened but never filled (e.g. `response.failed`) stays
1140
+ // An rs_ block opened but never filled (e.g. `response.failed`) stays
771
1141
  // as the spec's own unsealed-block outcome (INV-FLUSH (3)); forget it so a
772
1142
  // late run-item for it takes the existing `late-reasoning` degrade.
773
1143
  openReasoning.clear();
774
1144
  pendingPhase.clear();
1145
+ openRefusalBlocks.clear();
1146
+ refusalBlocks.clear();
775
1147
  turnId = undefined;
776
1148
  msgId = undefined;
777
1149
  responseId = undefined;
@@ -786,6 +1158,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
786
1158
  if (msgId !== undefined) {
787
1159
  for (const streamId of openTextStreams)
788
1160
  a.textEnd(streamId, msgId);
1161
+ endOpenRefusalBlocks(msgId);
789
1162
  a.closeMessage(msgId);
790
1163
  }
791
1164
  resetResponseState();
@@ -794,8 +1167,16 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
794
1167
  function driveRawResponsesEvent(ev) {
795
1168
  switch (ev.type) {
796
1169
  case "response.created": {
1170
+ // A new response: a refusal recorded by a late run-item belongs to the
1171
+ // response before it, never to this one; so does its refusal text.
1172
+ pendingRefusal = false;
1173
+ refusalTextEmitted = false;
1174
+ // A round still waiting only on listed built-in calls whose run-item
1175
+ // never streamed is released before this response's turn opens (see
1176
+ // "Built-in round attach").
1177
+ releaseListedAtNextResponse();
797
1178
  // Authoritative turn open — the real response.id is present at start.
798
- // OA-12: so is the resolved model id (JsonValue boundary: string-guarded).
1179
+ // So is the resolved model id (JsonValue boundary: string-guarded).
799
1180
  const rawModelId = ev.response.model;
800
1181
  ensureResponseOpen(ev.response.id, typeof rawModelId === "string" && rawModelId.length > 0 ? rawModelId : undefined);
801
1182
  return;
@@ -806,11 +1187,11 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
806
1187
  return; // unreachable post-ensure; satisfies the narrowing
807
1188
  if (!openTextStreams.has(ev.item_id)) {
808
1189
  openTextStreams.add(ev.item_id);
809
- // OA-14: the phase announced at output_item.added rides text.start
1190
+ // The phase announced at output_item.added rides text.start
810
1191
  // (R&D items 13+17, stage 1, ruled 2026-09-23; vercel parity c4f5981).
811
1192
  const phase = pendingPhase.get(ev.item_id);
812
1193
  const startMeta = openaiProviderMeta({ phase });
813
- // PH-2 (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
1194
+ // The first-class phase (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
814
1195
  // the first delta ⇒ the first-class `phase` goes on text.start.
815
1196
  const interim = interimPhase(phase);
816
1197
  a.textStart(ev.item_id, msgId, {
@@ -830,7 +1211,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
830
1211
  return;
831
1212
  }
832
1213
  case "response.output_text.done": {
833
- // NO-OP (audit M22): the citations carrier — `message_output_created` — is
1214
+ // NO-OP: the citations carrier — `message_output_created` — is
834
1215
  // the authoritative text-end source (it also reports refusal parts and
835
1216
  // arrives with the annotated part, so closing here would emit `text.end`
836
1217
  // BEFORE citations are known). The stream stays in `openTextStreams`;
@@ -839,8 +1220,38 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
839
1220
  // `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
840
1221
  return;
841
1222
  }
1223
+ case "response.refusal.delta": {
1224
+ // Refusal text streams like output_text (see "Refusal text"): the raw
1225
+ // refusal events are this round's source once any arrives.
1226
+ ensureResponseOpen();
1227
+ if (msgId === undefined)
1228
+ return; // unreachable post-ensure; satisfies the narrowing
1229
+ pendingRefusal = true;
1230
+ const blockId = `${ev.item_id}:refusal`;
1231
+ if (!refusalBlocks.has(blockId))
1232
+ openRefusalBlock(blockId, msgId, refusalItemPhase(ev.item_id), ev.item_id);
1233
+ a.textDelta(blockId, msgId, ev.delta, { cumulative: false });
1234
+ return;
1235
+ }
1236
+ case "response.refusal.done": {
1237
+ // Ends the part's block. With no delta before it, its `refusal` is the
1238
+ // whole text. A refusal part carries no annotations, so unlike
1239
+ // `response.output_text.done` nothing arrives later for its `text.end`.
1240
+ ensureResponseOpen();
1241
+ if (msgId === undefined)
1242
+ return; // unreachable post-ensure; satisfies the narrowing
1243
+ pendingRefusal = true;
1244
+ const blockId = `${ev.item_id}:refusal`;
1245
+ if (!refusalBlocks.has(blockId)) {
1246
+ emitWholeRefusal(blockId, msgId, ev.refusal, refusalItemPhase(ev.item_id), ev.item_id);
1247
+ return;
1248
+ }
1249
+ if (openRefusalBlocks.delete(blockId))
1250
+ a.textEnd(blockId, msgId);
1251
+ return;
1252
+ }
842
1253
  case "response.output_item.added": {
843
- // OA-11: a reasoning item OPENS its block here — id only, the added event
1254
+ // A reasoning item OPENS its block here — id only, the added event
844
1255
  // carries no replayable content — so the block takes its wire position
845
1256
  // ahead of the `fc_` it precedes (§5 block insertion order, SPEC:763;
846
1257
  // §10 item 4's stateless loop replays `rs_` before its `fc_`). It is
@@ -853,7 +1264,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
853
1264
  openReasoningBlock(rsId);
854
1265
  return;
855
1266
  }
856
- // OA-14: a message item announces its `phase` here, BEFORE its first
1267
+ // A message item announces its `phase` here, BEFORE its first
857
1268
  // text delta — record it for that item's `text.start`. Record only: no
858
1269
  // response open, no emit, so an absent/null/non-string/empty phase is
859
1270
  // byte-identical to a stream without this event.
@@ -957,11 +1368,22 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
957
1368
  return; // unreachable post-ensure; satisfies narrowing
958
1369
  if (msgId === undefined)
959
1370
  return; // unreachable post-ensure; satisfies narrowing
960
- // OA-11: fill every reasoning block from THIS output (the replayable blob)
1371
+ // Fill every reasoning block from THIS output (the replayable blob)
961
1372
  // FIRST — before any branch below can emit message.end / turn.* (INV-MSG:
962
1373
  // a reasoning.* event must never target a sealed message; core's reduce()
963
1374
  // does not check that for reasoning.*, so the order is this facet's job).
964
1375
  fillReasoningFromTerminalOutput(ev.response.output);
1376
+ // Refusal text (see "Refusal text"): with no refusal event in this
1377
+ // round, the terminal output's refusal parts are its source, emitted
1378
+ // now while the message is open (the run-item lands after the close).
1379
+ // Then any refusal block the stream left open ends here, before every
1380
+ // branch below closes the message.
1381
+ if (!refusalTextEmitted) {
1382
+ for (const part of terminalRefusalParts(ev.response.output)) {
1383
+ emitWholeRefusal(freshRefusalBlockId(part.itemId, msgId), msgId, part.text, part.phase, part.itemId);
1384
+ }
1385
+ }
1386
+ endOpenRefusalBlocks(msgId);
965
1387
  // Snapshot before any deferral: `resetResponseState()` below always
966
1388
  // clears these, but a deferred close needs them later (Task 4b).
967
1389
  const currentTurnId = turnId;
@@ -969,6 +1391,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
969
1391
  const textStreamIds = Array.from(openTextStreams);
970
1392
  const reason = ev.response.incomplete_details?.reason;
971
1393
  const usage = mapUsage(ev.response.usage);
1394
+ // The built-in calls (and, with them, the messages) this response
1395
+ // lists, whose run-items land after this event (see "Built-in round
1396
+ // attach").
1397
+ const listing = { builtins: terminalBuiltinItems(ev.response.output), messageIds: terminalMessageIds(ev.response.output) };
972
1398
  // `status` is OPTIONAL upstream and its enum is OPEN ("clients must
973
1399
  // accept additional values"), so it is read through `unknown` + a typeof
974
1400
  // guard rather than trusted through the declared union — this is the
@@ -979,7 +1405,8 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
979
1405
  const rawStatus = ev.response.status;
980
1406
  const unsuccessfulStatus = typeof rawStatus === "string" && UNSUCCESSFUL_RESPONSE_STATUSES.has(rawStatus) ? rawStatus : undefined;
981
1407
  // Decision tree (mirrors the canonical model, A1):
982
- // refusal recorded → closeTurnDone success, finishReason:"refusal"
1408
+ // refusal (in the terminal
1409
+ // output, or recorded) → closeTurnDone success, finishReason:"refusal"
983
1410
  // content_filter → closeTurnDone error-outcome + safety signal
984
1411
  // any other incomplete → closeTurnError{code:reason, usage}
985
1412
  // completed, status failed/
@@ -990,12 +1417,12 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
990
1417
  // ENTIRE close (message + turn) instead of emitting (INV-MSG).
991
1418
  // closeTurnError does NOT defer (an errored round's pending results are
992
1419
  // moot, by design) — it still closes the message immediately here.
993
- if (pendingRefusal) {
1420
+ if (pendingRefusal || terminalHasRefusal(ev.response.output)) {
994
1421
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
995
1422
  outcome: { type: "success" },
996
1423
  finishReason: "refusal",
997
1424
  ...(usage !== undefined ? { usage } : {}),
998
- });
1425
+ }, listing);
999
1426
  }
1000
1427
  else if (reason === "content_filter") {
1001
1428
  const safety = [{ category: "content_filter", blocked: true }];
@@ -1004,7 +1431,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1004
1431
  ...finishReasonFields(reason),
1005
1432
  safety,
1006
1433
  ...(usage !== undefined ? { usage } : {}),
1007
- });
1434
+ }, listing);
1008
1435
  }
1009
1436
  else if (ev.type === "response.incomplete") {
1010
1437
  endOpenStreamsAndCloseMessage();
@@ -1049,10 +1476,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1049
1476
  else {
1050
1477
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1051
1478
  outcome: { type: "success" },
1052
- // OA-15: an unmapped native reason also carries finishReasonRaw.
1479
+ // An unmapped native reason also carries finishReasonRaw.
1053
1480
  ...finishReasonFields(reason),
1054
1481
  ...(usage !== undefined ? { usage } : {}),
1055
- });
1482
+ }, listing);
1056
1483
  }
1057
1484
  resetResponseState();
1058
1485
  return;
@@ -1072,7 +1499,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1072
1499
  // message/code/usage (§4), so per §8.0 item 33 it rides verbatim in a
1073
1500
  // carrier the §5 table folds, never as remedy data on the terminal: an
1074
1501
  // adapter NOTICE message immediately BEFORE the closing turn.error, in
1075
- // this turn (rd-15):
1502
+ // this turn (remedy-shaped vendor data):
1076
1503
  // message.start {role:"notice", noticeSource:"adapter"} →
1077
1504
  // one text block, text = `detailed_explanation` verbatim (else
1078
1505
  // error.message), text.start `_meta["openai/misalignment"]` = the
@@ -1129,34 +1556,74 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1129
1556
  return;
1130
1557
  }
1131
1558
  // Duplicate raw families IGNORED per the canonical model:
1132
- // response.output_text.done is its own no-op arm above (audit M22);
1559
+ // response.output_text.done is its own no-op arm above;
1133
1560
  // response.output_item.done, response.in_progress, content_part.* are not
1134
1561
  // authoritative sources.
1135
1562
  default:
1136
1563
  return;
1137
1564
  }
1138
1565
  }
1566
+ /**
1567
+ * A `message_output_created` run-item's refusal part (see "Refusal text").
1568
+ * - The round already has its refusal text (the raw events or the terminal
1569
+ * output): no second copy. The item's phase marker, if that block did
1570
+ * not carry it, rides `ext.openai.late-phase` (the block's `text.end` is
1571
+ * out: case (iii) of the output_text arm), once per item: an item that
1572
+ * also carries an output_text part leaves it to that part's arm.
1573
+ * - The round is open (a synthetic order): the part is the source.
1574
+ * - The round closed with no copy: the message is sealed, so the text rides
1575
+ * `ext.openai.late-message` with `partType: "refusal"`, anchored to the
1576
+ * round like the id-less late message.
1577
+ */
1578
+ function driveRunItemRefusal(item, text) {
1579
+ const itemPhase = vendorPhase(item.phase);
1580
+ if (refusalTextEmitted) {
1581
+ if (item.id !== undefined &&
1582
+ itemPhase !== undefined &&
1583
+ refusalCarriedPhase.get(item.id) !== itemPhase &&
1584
+ !item.content.some((p) => p.type === "output_text")) {
1585
+ a.emitExt("openai", "late-phase", { itemId: item.id, phase: itemPhase });
1586
+ }
1587
+ return;
1588
+ }
1589
+ if (msgId !== undefined) {
1590
+ emitWholeRefusal(freshRefusalBlockId(item.id, msgId), msgId, text, itemPhase, item.id);
1591
+ return;
1592
+ }
1593
+ const anchor = turnId ?? lastTopLevelTurnId;
1594
+ a.emitExt("openai", "late-message", {
1595
+ text,
1596
+ partType: "refusal",
1597
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
1598
+ ...(anchor !== undefined ? { forTurnId: anchor } : {}),
1599
+ ...(itemPhase !== undefined ? { phase: itemPhase } : {}),
1600
+ });
1601
+ }
1139
1602
  /** End any still-open text streams (defensive), then close the open message. */
1140
1603
  function endOpenStreamsAndCloseMessage() {
1141
1604
  if (msgId !== undefined) {
1142
1605
  for (const streamId of openTextStreams)
1143
1606
  a.textEnd(streamId, msgId);
1607
+ endOpenRefusalBlocks(msgId);
1144
1608
  a.closeMessage(msgId);
1145
1609
  }
1146
1610
  }
1147
1611
  /**
1148
1612
  * Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
1149
- * citations source (audit M22). The text itself already streamed from the raw
1613
+ * citations source. The text itself already streamed from the raw
1150
1614
  * `response.output_text.delta` path — this MUST NOT re-emit it — but the
1151
1615
  * `output_text` part's annotations are only known here (they are not present on
1152
1616
  * `response.output_text.done`), so THIS is where the matching open text stream
1153
1617
  * actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
1154
1618
  * directly to the streamed block (never a duplicate id-less supplement). A
1155
- * `refusal` part sets `pendingRefusal` so the downstream `response.completed`
1156
- * arm closes with `finishReason:"refusal"` (no text stream to close for it).
1619
+ * `refusal` part sets `pendingRefusal`, which counts only when the run-item
1620
+ * lands before its response's terminal event (a synthetic order). On the
1621
+ * live wire it lands after the close, and the terminal arm reads the round's
1622
+ * refusal from its own `response.output` (`terminalHasRefusal`). Its text is
1623
+ * a single-source fallback (`driveRunItemRefusal`, see "Refusal text").
1157
1624
  *
1158
- * Correlation (OA-14 — id FIRST, FIFO fallback; protocol package rd-13-17
1159
- * §2 stage 1): on the direct OpenAI wire the raw delta's `item_id` and the
1625
+ * Correlation (id FIRST, FIFO fallback; the narration-phase rule, stage
1626
+ * 1): on the direct OpenAI wire the raw delta's `item_id` and the
1160
1627
  * run-item's `rawItem.id` are the SAME id (all 8 openai corpus seeds), so the
1161
1628
  * stream is matched by id — a completion can no longer land on an earlier
1162
1629
  * part's stream when two are open. Only when the id is unknown to
@@ -1174,7 +1641,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1174
1641
  * annotations, though, they are NOT yet lost anywhere else — silently dropping
1175
1642
  * them here would violate Tenet 6. Route them losslessly through the facet's
1176
1643
  * existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
1177
- * the run-item id + the raw annotations array verbatim (review finding on M22).
1644
+ * the run-item id + the raw annotations array verbatim.
1178
1645
  * A part with no annotations has nothing to lose — the plain `continue` stays.
1179
1646
  *
1180
1647
  * ID-LESS SYNTHESIZED MESSAGE (agents-core ≥0.13.2): `errorHandlers.
@@ -1203,9 +1670,23 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1203
1670
  * never a duplicated or corrupted core stream.
1204
1671
  */
1205
1672
  function driveMessageOutputCreated(item) {
1673
+ if (item.id !== undefined)
1674
+ seenBuiltinItemIds.add(item.id);
1675
+ driveMessageParts(item);
1676
+ // A listed message has landed; its round may now close (see "Built-in
1677
+ // round attach"), with any citations stashed above on its text.end.
1678
+ drainListedBuiltin(item.id);
1679
+ }
1680
+ /** The per-part body of {@link driveMessageOutputCreated} (see its doc). */
1681
+ function driveMessageParts(item) {
1206
1682
  for (const part of item.content) {
1207
1683
  if (part.type === "refusal") {
1208
1684
  pendingRefusal = true;
1685
+ // The typeof guard is load-bearing: rawItem is envelope-only-validated
1686
+ // wire data, and push() must never throw.
1687
+ const text = part.refusal;
1688
+ if (typeof text === "string")
1689
+ driveRunItemRefusal(item, text);
1209
1690
  continue;
1210
1691
  }
1211
1692
  if (part.type === "output_text") {
@@ -1226,20 +1707,34 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1226
1707
  ...(item.phase !== undefined ? { phase: item.phase } : {}),
1227
1708
  });
1228
1709
  }
1229
- if (part.annotations !== undefined && part.annotations.length > 0) {
1710
+ const idlessAnnotations = partAnnotations(part);
1711
+ if (idlessAnnotations.length > 0) {
1230
1712
  a.emitExt("openai", "late-citations", {
1231
- annotations: JsonValue.parse(part.annotations),
1713
+ annotations: idlessAnnotations,
1232
1714
  });
1233
1715
  }
1234
1716
  continue;
1235
1717
  }
1236
1718
  if (msgId === undefined) {
1237
- // response already closed — see doc above.
1238
- if (part.annotations !== undefined && part.annotations.length > 0) {
1239
- a.emitExt("openai", "late-citations", {
1240
- itemId: item.id,
1241
- annotations: JsonValue.parse(part.annotations),
1242
- });
1719
+ // response already closed — see doc above. While the round's close
1720
+ // is STASHED (deferred for its tool results or built-in calls), this
1721
+ // block's text.end is not out yet, so its url citations ride it (the
1722
+ // phase marker's case (ii) below), and any other annotation takes
1723
+ // the ext carry; a message that lands after the close was released
1724
+ // carries every annotation on the ext.
1725
+ const closedAnnotations = partAnnotations(part);
1726
+ if (closedAnnotations.length > 0) {
1727
+ const split = isStashedTextStream(item.id) ? splitAnnotations(closedAnnotations, part.text) : undefined;
1728
+ if (split?.citations !== undefined) {
1729
+ stashedEndFields.set(item.id, { ...stashedEndFields.get(item.id), citations: split.citations });
1730
+ }
1731
+ const carry = split?.citations !== undefined ? split.unmapped : closedAnnotations;
1732
+ if (carry.length > 0) {
1733
+ a.emitExt("openai", "late-citations", {
1734
+ itemId: item.id,
1735
+ annotations: carry,
1736
+ });
1737
+ }
1243
1738
  }
1244
1739
  // phase (0.14.0): the live wire delivers the FINAL round's
1245
1740
  // message_output_created AFTER response_done has closed the message
@@ -1248,21 +1743,22 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1248
1743
  // (deferred-close) messages ever reach it. Same post-close degrade
1249
1744
  // convention as late-citations: a dedicated itemId-keyed vendor
1250
1745
  // carry, one per phase-bearing part.
1251
- // OA-14: RETIRED when this id's SAME phase already rode its text.start
1746
+ // RETIRED when this id's SAME phase already rode its text.start
1252
1747
  // (the live case); kept — lossless — when only the run-item knows it,
1253
1748
  // or knows a different value.
1254
- // PH-2: null/"" is no marker at all (spec ruling (a)) — neither
1749
+ // A null/"" phase is no marker at all (spec ruling (a)) — neither
1255
1750
  // a carry nor a late-phase ext.
1256
1751
  const lateItemPhase = vendorPhase(item.phase);
1257
1752
  if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
1258
1753
  if (isStashedTextStream(item.id)) {
1259
- // PH-2 case (ii): the round close is STASHED (a deferred tool
1754
+ // Case (ii): the round close is STASHED (a deferred tool
1260
1755
  // round), so this block's text.end is NOT yet emitted — the §5
1261
1756
  // timing rule makes the end the phase's home (ruled
1262
1757
  // 2026-09-23). The marker has a first-class home, so no late-phase.
1263
1758
  const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
1264
1759
  const endMeta = openaiProviderMeta({ phase: lateItemPhase });
1265
1760
  stashedEndFields.set(item.id, {
1761
+ ...stashedEndFields.get(item.id),
1266
1762
  ...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
1267
1763
  ...(interim !== undefined ? { phase: interim } : {}),
1268
1764
  });
@@ -1275,12 +1771,15 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1275
1771
  }
1276
1772
  continue;
1277
1773
  }
1278
- // OA-14: id first, FIFO fallback — see "Correlation" in the doc above.
1774
+ // Id first, FIFO fallback — see "Correlation" in the doc above.
1279
1775
  const streamId = item.id !== undefined && openTextStreams.has(item.id) ? item.id : openTextStreams.values().next().value;
1280
1776
  if (streamId === undefined)
1281
1777
  continue; // defensive: no matching open stream
1282
1778
  openTextStreams.delete(streamId);
1283
- const citations = mapAnnotationsToCitations(part.annotations, part.text);
1779
+ // A url citation rides text.end; any other annotation has no citation
1780
+ // target and takes the ext carry, after the text.end (SPEC:965).
1781
+ const liveSplit = splitAnnotations(partAnnotations(part), part.text);
1782
+ const citations = liveSplit.citations;
1284
1783
  // phase (0.14.0) rides the matching text.end's providerMetadata —
1285
1784
  // PER-PART, not message.metadata: this facet folds a response into ONE
1286
1785
  // message, and a program-driven turn emits multiple message items with
@@ -1288,7 +1787,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1288
1787
  // merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
1289
1788
  const itemPhase = vendorPhase(item.phase);
1290
1789
  const phaseMeta = openaiProviderMeta({ phase: itemPhase });
1291
- // PH-2 case (i): known before this block's text.end ⇒ the end carries
1790
+ // Case (i): known before this block's text.end ⇒ the end carries
1292
1791
  // the first-class phase, unless text.start already did.
1293
1792
  const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
1294
1793
  a.textEnd(streamId, msgId, citations !== undefined || phaseMeta !== undefined || endInterim !== undefined
@@ -1298,11 +1797,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1298
1797
  ...(endInterim !== undefined ? { phase: endInterim } : {}),
1299
1798
  }
1300
1799
  : undefined);
1800
+ if (liveSplit.unmapped.length > 0) {
1801
+ a.emitExt("openai", "late-citations", { itemId: item.id ?? streamId, annotations: liveSplit.unmapped });
1802
+ }
1301
1803
  }
1302
1804
  }
1303
1805
  }
1304
1806
  /**
1305
- * OA-11: open the reasoning block for `rsId` in the current message — once per
1807
+ * Open the reasoning block for `rsId` in the current message — once per
1306
1808
  * id (a re-announce, or an id already filled, is a no-op). `id` and `itemId`
1307
1809
  * are both the `rs_` id (the run-item path's convention). Called from
1308
1810
  * `output_item.added{reasoning}` so the block takes its WIRE position, and
@@ -1317,7 +1819,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1317
1819
  openReasoning.set(rsId, msgId);
1318
1820
  }
1319
1821
  /**
1320
- * OA-11: fill + seal an OPEN reasoning block: one `reasoning.delta` per
1822
+ * Fill + seal an OPEN reasoning block: one `reasoning.delta` per
1321
1823
  * non-empty summary part (`partIndex` = the wire `summary_index`), then
1322
1824
  * `reasoning.opaque` (the replayable ciphertext, `itemId` = rs_) BEFORE
1323
1825
  * `reasoning.end`, so "sealed" means complete (the spec's recommendation;
@@ -1349,7 +1851,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1349
1851
  openReasoning.delete(rsId);
1350
1852
  filledReasoning.add(rsId);
1351
1853
  }
1352
- /** OA-11: fill every reasoning block from a terminal event's `response.output`
1854
+ /** Fill every reasoning block from a terminal event's `response.output`
1353
1855
  * (see `terminalReasoningItems` for why this, not `output_item.done`, is the
1354
1856
  * source). An item never announced by `output_item.added` opens here
1355
1857
  * (defensive — position is then the terminal event's). */
@@ -1362,14 +1864,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1362
1864
  }
1363
1865
  }
1364
1866
  /**
1365
- * Map a `reasoning_item_created` run-item (Task 3, audit M48). Since OA-11 it
1867
+ * Map a `reasoning_item_created` run-item. Since reasoning is sourced from the terminal output it
1366
1868
  * is the FALLBACK source: on the live wire it lands after `response.completed`,
1367
1869
  * whose output already filled the block, so a run-item whose `rs_` id is in
1368
1870
  * `filledReasoning` is a no-op (single source per id — no duplicate block, no
1369
1871
  * `late-reasoning` ext). If raw `output_item.added` opened the block but no
1370
1872
  * terminal output has filled it yet, the run-item fills that block in place.
1371
1873
  * Only with NO raw reasoning events for the id (run-item-only streams) does the
1372
- * pre-OA-11 mapping below still run, unchanged:
1874
+ * run-item-only mapping below still run, unchanged:
1373
1875
  *
1374
1876
  * The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
1375
1877
  * the incremental text/tool-arg deltas elsewhere in this facet), so
@@ -1403,15 +1905,15 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1403
1905
  * never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
1404
1906
  * correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
1405
1907
  * is exactly the kind of payload Tenet 6 exists for — silently dropping it here
1406
- * was a genuine loss (review finding on M48). Mirrors `ext.openai.late-citations`
1407
- * (M22) exactly: route it through the lossless vendor channel instead of the bare
1908
+ * was a genuine loss. Mirrors `ext.openai.late-citations` exactly: route it
1909
+ * through the lossless vendor channel instead of the bare
1408
1910
  * return.
1409
1911
  */
1410
1912
  function driveReasoningItemCreated(item) {
1411
- // OA-11 dedupe: already filled from the terminal output (or an earlier run-item).
1913
+ // Dedupe: already filled from the terminal output (or an earlier run-item).
1412
1914
  if (item.id !== undefined && filledReasoning.has(item.id))
1413
1915
  return;
1414
- // OA-11: raw `output_item.added` opened this block; no terminal output has
1916
+ // Raw `output_item.added` opened this block; no terminal output has
1415
1917
  // filled it yet (synthetic ordering) — fill it in place from the run-item,
1416
1918
  // whose `content[]` IS the raw `summary[]` (one part per index).
1417
1919
  if (msgId !== undefined && item.id !== undefined && openReasoning.has(item.id)) {
@@ -1449,7 +1951,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1449
1951
  ...(itemId !== undefined ? { itemId } : {}),
1450
1952
  });
1451
1953
  }
1452
- // OA-11: a terminal output naming this rs_ later must not open a second block.
1954
+ // A terminal output naming this rs_ later must not open a second block.
1453
1955
  if (itemId !== undefined)
1454
1956
  filledReasoning.add(itemId);
1455
1957
  }
@@ -1464,7 +1966,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1464
1966
  * pending bookkeeping and — if the turn's pending set just drained to empty
1465
1967
  * — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
1466
1968
  * the `function_call` `tool_output` arm and the built-in Shell/Apply-Patch
1467
- * `tool_output` arm (playbook 2026-07-03 SDK-bump adaptation, Finding #1).
1969
+ * `tool_output` arm (the 2026-07-03 SDK-bump adaptation).
1468
1970
  */
1469
1971
  /**
1470
1972
  * HO-P, the handoff round release (§8.0 item 14, draft.5). Called at
@@ -1504,11 +2006,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1504
2006
  }
1505
2007
  if (pending.size > 0)
1506
2008
  return;
1507
- const stashed = stashedCloseByTurn.get(sourceTurnId);
1508
- if (stashed === undefined)
1509
- return;
1510
- stashedCloseByTurn.delete(sourceTurnId);
1511
- emitRoundClose(sourceTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
2009
+ maybeReleaseRound(sourceTurnId);
1512
2010
  }
1513
2011
  function drainPendingTool(callId, doneTurnId) {
1514
2012
  if (doneTurnId === undefined)
@@ -1518,17 +2016,13 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1518
2016
  if (pending === undefined)
1519
2017
  return;
1520
2018
  pending.delete(callId);
1521
- if (pending.size === 0) {
1522
- const stashed = stashedCloseByTurn.get(doneTurnId);
1523
- if (stashed !== undefined) {
1524
- // The pending set just drained — emit the deferred message.end +
1525
- // turn.done immediately after this tool.done, same push() batch
1526
- // (INV-MSG: the message must still be open when tool.done lands, so
1527
- // message.end waits for this too).
1528
- stashedCloseByTurn.delete(doneTurnId);
1529
- emitRoundClose(doneTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
1530
- }
1531
- }
2019
+ // The pending set just drained — emit the deferred message.end +
2020
+ // turn.done immediately after this tool.done, same push() batch
2021
+ // (INV-MSG: the message must still be open when tool.done lands, so
2022
+ // message.end waits for this too), unless a listed built-in call of the
2023
+ // round has yet to land (see "Built-in round attach").
2024
+ if (pending.size === 0)
2025
+ maybeReleaseRound(doneTurnId);
1532
2026
  }
1533
2027
  /** True if any shell command in `entries` timed out or exited non-zero. */
1534
2028
  function shellOutputHasError(entries) {
@@ -1542,7 +2036,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1542
2036
  }
1543
2037
  /**
1544
2038
  * Map a `tool_output` run-item whose `rawItem` is a Shell, Apply-Patch, or
1545
- * Computer-Use result (playbook 2026-07-03 SDK-bump adaptation, Finding #1;
2039
+ * Computer-Use result (the 2026-07-03 SDK-bump adaptation;
1546
2040
  * `computer_call_result` added by the fixture-drift ratchet finding, same
1547
2041
  * date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
1548
2042
  * (a bare string / content-part union) — `shell_call_output.output` is an
@@ -1555,7 +2049,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1555
2049
  * since none of these record types has the `.type === "text"` discriminant
1556
2050
  * `toolOutputToAgBlocks` checks for).
1557
2051
  */
1558
- function driveBuiltinToolOutput(rawItem) {
2052
+ function driveBuiltinToolOutput(rawItem, executionStatus) {
1559
2053
  const toolCallId = rawItem.callId;
1560
2054
  let content;
1561
2055
  let outcome;
@@ -1575,28 +2069,51 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1575
2069
  shellOutputHasError(rawItem.output) || rawItem.status === "incomplete" ? "error" : "ok";
1576
2070
  // The full per-command record (stdout/stderr/exit code) is lossy to
1577
2071
  // collapse into text-only content — carry it verbatim as structuredContent
1578
- // too (mirrors the function_call path's ggui-cache-marker precedent).
2072
+ // too (mirrors the function_call path's cache-marker precedent).
1579
2073
  structuredContent = JsonValue.parse(rawItem.output);
1580
2074
  // The outcome mapping alone cannot recover `status` ('in_progress' vs
1581
2075
  // 'completed' vs absent all map ok) — carry it verbatim, with caller.
1582
2076
  providerMetadata = openaiProviderMeta({
1583
2077
  caller: callerToJson(rawItem.caller),
1584
2078
  status: rawItem.status,
2079
+ executionStatus,
1585
2080
  });
1586
2081
  }
1587
2082
  else if (rawItem.type === "computer_call_result") {
1588
- // spec §8 item 20's extended discriminant: the screenshot is base64 image
1589
- // data, not text — land it as an AgBlock `file` block (AgSource's
1590
- // `base64` arm) rather than dropping it via the text-only path.
1591
- content = [
1592
- {
1593
- type: "file",
1594
- source: { type: "base64", mediaType: "image/png", data: rawItem.output.data },
1595
- filename: "screenshot.png",
1596
- },
1597
- ];
1598
- // No status/error discriminant exists on this wire arm (unlike shell/apply-patch).
1599
- outcome = "ok";
2083
+ // spec §8 item 20's extended discriminant: the screenshot is image data,
2084
+ // not text — land it as an AgBlock `file` block (AgSource's `base64` arm)
2085
+ // rather than dropping it via the text-only path. The SDK sends a
2086
+ // `data:<media type>;base64,<payload>` URL; AgSource's `base64` arm holds
2087
+ // the base64 text alone with its media type (SPEC.md:140, "must match
2088
+ // bytes"), so the header is split off. A value with no `data:` header
2089
+ // lands verbatim as image/png.
2090
+ const outputPd = rawItem.output.providerData;
2091
+ const file = { type: "file", source: screenshotSource(rawItem.output.data), filename: "screenshot.png" };
2092
+ // A refused action (a declined approval, or an `onSafetyCheck` that
2093
+ // returns false) is the SDK's rejection result: its
2094
+ // `output.providerData.approvalStatus` is "rejected" and its screenshot is
2095
+ // the SDK's 1×1 placeholder. It closes `denied` (§8.0 item 20), with the
2096
+ // SDK's message as a text block before the file block. Every other
2097
+ // computer result closes `ok`.
2098
+ if (outputPd?.approvalStatus === "rejected") {
2099
+ const message = outputPd.message;
2100
+ content = typeof message === "string" && message.length > 0 ? [{ type: "text", text: message }, file] : [file];
2101
+ outcome = "denied";
2102
+ }
2103
+ else {
2104
+ content = [file];
2105
+ outcome = "ok";
2106
+ }
2107
+ // The SDK's own markers, verbatim: the run-item's `executionStatus`
2108
+ // (present only when the action ran), the refusal's
2109
+ // `output.providerData.approvalStatus` and `message`, and the item's
2110
+ // `providerData.acknowledgedSafetyChecks`.
2111
+ providerMetadata = openaiProviderMeta({
2112
+ executionStatus,
2113
+ approvalStatus: outputPd?.approvalStatus,
2114
+ message: outputPd?.message,
2115
+ acknowledgedSafetyChecks: rawItem.providerData?.acknowledgedSafetyChecks,
2116
+ });
1600
2117
  }
1601
2118
  else if (rawItem.type === "program_output") {
1602
2119
  // 0.14.0 programmatic tool calling: bare-string output (mirrors the
@@ -1604,18 +2121,20 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1604
2121
  // (same rule as function_call_result — never success).
1605
2122
  content = rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
1606
2123
  outcome = rawItem.status === "incomplete" ? "error" : "ok";
2124
+ providerMetadata = openaiProviderMeta({ executionStatus });
1607
2125
  }
1608
2126
  else {
1609
2127
  content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
1610
2128
  outcome = rawItem.status === "failed" ? "error" : "ok";
1611
- providerMetadata = openaiProviderMeta({ caller: callerToJson(rawItem.caller) });
2129
+ providerMetadata = openaiProviderMeta({ caller: callerToJson(rawItem.caller), executionStatus });
1612
2130
  }
1613
2131
  const doneTurnId = resolvePendingTurnId(toolCallId);
1614
2132
  a.toolDone({
1615
2133
  toolCallId,
1616
2134
  content,
1617
2135
  outcome,
1618
- isError: outcome === "error",
2136
+ // A denied close carries no isError (§6 Pattern 4).
2137
+ ...(outcome === "denied" ? {} : { isError: outcome === "error" }),
1619
2138
  ...(structuredContent !== undefined ? { structuredContent } : {}),
1620
2139
  ...(providerMetadata !== undefined ? { providerMetadata } : {}),
1621
2140
  ...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(toolCallId) ?? {})),
@@ -1662,7 +2181,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1662
2181
  /**
1663
2182
  * Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
1664
2183
  * built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
1665
- * — playbook 2026-07-03 SDK-bump adaptation, Finding #1; `computer_call`
2184
+ * — the 2026-07-03 SDK-bump adaptation; `computer_call`
1666
2185
  * added by the fixture-drift ratchet finding, same date). Unlike
1667
2186
  * `function_call` (whose tool-start rides the raw `response.output_item.
1668
2187
  * added` stream — the authoritative source, canonical model A1), this
@@ -1673,11 +2192,12 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1673
2192
  * action/operation arrives complete on this one wrapper), and
1674
2193
  * `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
1675
2194
  * an agents-core-internal umbrella normalized only at this run-item layer).
1676
- * `ensureResponseOpen()` mirrors the raw function_call path's treatment
1677
- * (both are tool-START signals expected EARLY in a round, unlike the
1678
- * LATE-arriving `tool_output`/`message_output_created` run-items this file
1679
- * already documents) — residual ordering risk if a future capture shows
1680
- * otherwise is flagged in the adaptation report, not silently assumed away.
2195
+ * Like every run-item, this wrapper lands AFTER its response's
2196
+ * `response.completed` (agents-core 0.18.0 streams a response's step items
2197
+ * after the raw loop, run.mjs:1935), so it attaches to the round its
2198
+ * terminal listed, whose close is deferred for it (see "Built-in round
2199
+ * attach"); it opens a response only when none has been seen for it (a
2200
+ * run-item that lands while its response is open joins that response).
1681
2201
  *
1682
2202
  * `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
1683
2203
  * result arrives via a LATER `tool_output` run-item, same Task-4b
@@ -1689,7 +2209,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1689
2209
  * doc) — no pending registration.
1690
2210
  */
1691
2211
  /**
1692
- * OA-13: did OpenAI (the provider) already execute this built-in call? →
2212
+ * Did OpenAI (the provider) already execute this built-in call? →
1693
2213
  * `tool.start.providerExecuted` (SPEC:632; SPEC:496 "client MUST NOT
1694
2214
  * execute"). Per the installed runtime (agents-core 0.18.0
1695
2215
  * `dist/runner/modelOutputs.mjs`): `hosted_tool_call` always (resolved
@@ -1711,26 +2231,260 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1711
2231
  }
1712
2232
  return false;
1713
2233
  }
2234
+ /**
2235
+ * The toolCallId of a `hosted_tool_call`: its item id when it has one. An
2236
+ * id-less item gets a derived id, `<name>_<invoke stem>_<n>` (INV-BLOCK,
2237
+ * SPEC:767: "Normalizers MUST mint collision-free **derived** ids when the
2238
+ * framework omits one"), never its `name`, which two items of one invoke
2239
+ * can share. An `mcp_approval_response` (which agents-core 0.18.0 builds
2240
+ * with no id, runner/mcpApprovals.mjs:39-49) is no call of its own: it
2241
+ * closes the request it answers (`driveApprovalAnswer`).
2242
+ */
2243
+ function hostedToolCallId(rawItem) {
2244
+ if (rawItem.id !== undefined && rawItem.id.length > 0)
2245
+ return rawItem.id;
2246
+ return `${rawItem.name}_${invokeStem}_${++derivedOrdinal}`;
2247
+ }
2248
+ /** The hosted-MCP kind of a `hosted_tool_call`, by its `name` or its
2249
+ * `providerData.type` (agents-openai's converter matches either,
2250
+ * openaiResponsesConverter.mjs:1066-1115). */
2251
+ function hostedMcpKind(rawItem) {
2252
+ const type = rawItem.providerData?.type;
2253
+ for (const kind of ["mcp_call", "mcp_approval_request", "mcp_approval_response"]) {
2254
+ if (rawItem.name === kind || type === kind)
2255
+ return kind;
2256
+ }
2257
+ return undefined;
2258
+ }
2259
+ /**
2260
+ * An `mcp_approval_response` run-item closes the request it answers
2261
+ * (`providerData.approval_request_id`) with exactly one `tool.done`:
2262
+ * outcome "ok" when `providerData.approve` is true, which records the
2263
+ * approval and not the result of the call it gates, and "denied" when it is
2264
+ * not. It creates no block of its own, and the `mcp_call` it gates is a
2265
+ * separate call under its own id. The request is a pending call of its
2266
+ * round in the same invoke (the onApproval flow); in a resuming invoke it
2267
+ * is unknown, and the answer lands as a leading result does
2268
+ * (`openTurnForLeadingResult`, INV-XINV). An answer's `reason` rides
2269
+ * tool.done providerMetadata. Three answers have nothing to close, and each
2270
+ * is carried verbatim on ext.openai.unparsed: one that names no request; a
2271
+ * second answer to a request this invoke already closed (agents-core
2272
+ * answers each request once, runner/mcpApprovals.mjs), which would close it
2273
+ * twice; and one naming a request this invoke does not hold while a
2274
+ * response is open, which no leading turn can take.
2275
+ */
2276
+ function driveApprovalAnswer(rawItem) {
2277
+ const requestId = rawItem.providerData?.approval_request_id;
2278
+ if (typeof requestId !== "string" || requestId.length === 0 || answeredRequests.has(requestId)) {
2279
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
2280
+ return;
2281
+ }
2282
+ const reason = rawItem.providerData?.reason;
2283
+ const meta = openaiProviderMeta({
2284
+ reason: typeof reason === "string" && reason.length > 0 ? reason : undefined,
2285
+ caller: callerToJson(rawItem.caller),
2286
+ });
2287
+ const doneTurnId = resolvePendingTurnId(requestId);
2288
+ const leading = doneTurnId === undefined ? openTurnForLeadingResult(requestId) : undefined;
2289
+ if (doneTurnId === undefined && leading === undefined) {
2290
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
2291
+ return;
2292
+ }
2293
+ answeredRequests.add(requestId);
2294
+ a.toolDone({
2295
+ toolCallId: requestId,
2296
+ content: [],
2297
+ outcome: rawItem.providerData?.approve === true ? "ok" : "denied",
2298
+ ...(meta !== undefined ? { providerMetadata: meta } : {}),
2299
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : leading),
2300
+ });
2301
+ drainPendingTool(requestId, doneTurnId);
2302
+ }
2303
+ /**
2304
+ * A hosted call's input. agents-openai's converter keeps a hosted item's
2305
+ * fields in `providerData` (SPEC:965: a native value is never dropped
2306
+ * silently):
2307
+ * - its `arguments` (top-level when present, else in providerData — the
2308
+ * MCP kinds);
2309
+ * - else a web_search's `action` without its `sources`, which are the
2310
+ * call's result, not its input;
2311
+ * - else a file_search's `queries`;
2312
+ * - else a code_interpreter's `code` and `container_id` (its call payload
2313
+ * without its `outputs`, the program precedent).
2314
+ */
2315
+ function hostedInput(rawItem) {
2316
+ const pd = rawItem.providerData;
2317
+ const args = rawItem.arguments ?? pd?.arguments;
2318
+ if (typeof args === "string")
2319
+ return parseJsonArguments(rawItem.id, args);
2320
+ const action = pd?.action;
2321
+ if (isJsonObject(action)) {
2322
+ const input = {};
2323
+ for (const [k, v] of Object.entries(action))
2324
+ if (k !== "sources")
2325
+ input[k] = v;
2326
+ return JsonValue.parse(input);
2327
+ }
2328
+ if (rawItem.name === "file_search_call" && pd?.queries !== undefined)
2329
+ return JsonValue.parse({ queries: pd.queries });
2330
+ if (rawItem.name === "code_interpreter_call" && (pd?.code !== undefined || pd?.container_id !== undefined)) {
2331
+ return JsonValue.parse({
2332
+ ...(pd?.code !== undefined ? { code: pd.code } : {}),
2333
+ ...(pd?.container_id !== undefined ? { container_id: pd.container_id } : {}),
2334
+ });
2335
+ }
2336
+ return {};
2337
+ }
2338
+ /**
2339
+ * A hosted call's result: its `output` (an image_generation result, which
2340
+ * is base64 image data, as a file block; any other as text), a
2341
+ * web_search's `sources`, an mcp_list_tools listing, a file_search's
2342
+ * `results` and a code_interpreter's `outputs` as data blocks, and its
2343
+ * outcome. The outcome is "error" when the native status is `failed` or
2344
+ * `incomplete`, as a shell, program or function result's `incomplete` is
2345
+ * (and an apply-patch result's `failed`); for an mcp_call, whose top-level
2346
+ * status the converter always sets to "completed", the status in
2347
+ * providerData. It is also "error" when the item carries a non-null
2348
+ * `error`, an empty string included, even with a `completed` status. Any
2349
+ * other status (`in_progress`,
2350
+ * `searching`, `interpreting`, …) closes "ok"; a status other than
2351
+ * `completed` rides tool.done providerMetadata.status verbatim.
2352
+ */
2353
+ function hostedResult(rawItem) {
2354
+ const pd = rawItem.providerData;
2355
+ const content = [];
2356
+ const output = rawItem.output;
2357
+ if (typeof output === "string" && output.length > 0) {
2358
+ content.push(rawItem.name === "image_generation_call"
2359
+ ? { type: "file", source: { type: "base64", mediaType: imageResultMediaType(pd, output), data: output } }
2360
+ : { type: "text", text: output });
2361
+ }
2362
+ const action = pd?.action;
2363
+ if (isJsonObject(action) && Array.isArray(action.sources)) {
2364
+ content.push({ type: "data", name: "web_search_sources", data: JsonValue.parse(action.sources) });
2365
+ }
2366
+ const tools = pd?.tools;
2367
+ if (rawItem.name === "mcp_list_tools" && Array.isArray(tools)) {
2368
+ content.push({ type: "data", name: "mcp_list_tools", data: JsonValue.parse(tools) });
2369
+ }
2370
+ const results = pd?.results;
2371
+ if (rawItem.name === "file_search_call" && Array.isArray(results)) {
2372
+ content.push({ type: "data", name: "file_search_results", data: JsonValue.parse(results) });
2373
+ }
2374
+ const outputs = pd?.outputs;
2375
+ if (rawItem.name === "code_interpreter_call" && Array.isArray(outputs)) {
2376
+ content.push({ type: "data", name: "code_interpreter_outputs", data: JsonValue.parse(outputs) });
2377
+ }
2378
+ const status = hostedMcpKind(rawItem) === "mcp_call" ? (pd?.status ?? rawItem.status) : rawItem.status;
2379
+ // An mcp_call's `error` is an object on the wire (openai-node 7.22.0
2380
+ // McpToolCallError: a protocol or HTTP error {code, message, type}, or a
2381
+ // tool execution error {content, type}): its message (else the object as
2382
+ // JSON) is the errorText, its type the errorCode, and the object rides
2383
+ // tool.done providerMetadata verbatim. A non-empty string error is its own
2384
+ // text; any other non-null error (an empty string) rides providerMetadata.
2385
+ const error = pd?.error;
2386
+ const hasError = error !== undefined && error !== null;
2387
+ const errorMessage = isJsonObject(error) ? error.message : undefined;
2388
+ const errorText = typeof error === "string" && error.length > 0
2389
+ ? error
2390
+ : typeof errorMessage === "string" && errorMessage.length > 0
2391
+ ? errorMessage
2392
+ : isJsonObject(error)
2393
+ ? JSON.stringify(error)
2394
+ : undefined;
2395
+ const errorType = isJsonObject(error) ? error.type : undefined;
2396
+ // An image_generation result's own fields (revised prompt, size, quality,
2397
+ // background, action, format) ride tool.done providerMetadata verbatim.
2398
+ const image = rawItem.name === "image_generation_call" ? pd : undefined;
2399
+ const imageField = (k) => {
2400
+ const v = image?.[k];
2401
+ return v === null ? undefined : v;
2402
+ };
2403
+ const providerMetadata = openaiProviderMeta({
2404
+ status: typeof status === "string" && status.length > 0 && status !== "completed" ? status : undefined,
2405
+ error: hasError && errorText !== error ? JsonValue.parse(error) : undefined,
2406
+ revised_prompt: imageField("revised_prompt"),
2407
+ size: imageField("size"),
2408
+ quality: imageField("quality"),
2409
+ background: imageField("background"),
2410
+ action: imageField("action"),
2411
+ output_format: imageField("output_format"),
2412
+ });
2413
+ const meta = providerMetadata !== undefined ? { providerMetadata } : {};
2414
+ if (status === "failed" || status === "incomplete" || hasError) {
2415
+ return {
2416
+ content,
2417
+ outcome: "error",
2418
+ isError: true,
2419
+ ...(errorText !== undefined ? { errorText } : {}),
2420
+ ...(typeof errorType === "string" && errorType.length > 0 ? { errorCode: errorType } : {}),
2421
+ ...meta,
2422
+ };
2423
+ }
2424
+ return { content, outcome: "ok", ...meta };
2425
+ }
1714
2426
  function driveBuiltinToolCalled(rawItem) {
1715
- ensureResponseOpen();
1716
- if (msgId === undefined)
2427
+ const mcpKind = rawItem.type === "hosted_tool_call" ? hostedMcpKind(rawItem) : undefined;
2428
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_response") {
2429
+ driveApprovalAnswer(rawItem);
2430
+ return;
2431
+ }
2432
+ // The listed item this run-item is (see "Built-in round attach").
2433
+ const key = rawItem.id;
2434
+ if (rawItem.id !== undefined)
2435
+ seenBuiltinItemIds.add(rawItem.id);
2436
+ const toolCallId = rawItem.type === "hosted_tool_call" ? hostedToolCallId(rawItem) : rawItem.callId;
2437
+ // A run-item that lands after its round's terminal attaches to that round;
2438
+ // one that lands while a response is open belongs to it. A hosted call
2439
+ // that no round claims while no response is open (not a 0.18.0 shape: a
2440
+ // resuming invoke leads with a tool result or an approval's answer) opens
2441
+ // its turn as a leading tool result does (`openTurnForLeadingResult`), in
2442
+ // an assistant message of its own, `<toolCallId>:call`, closed after the
2443
+ // call: the response that follows then opens its own message in that
2444
+ // turn, with its model. A leading client-executed or tool-search call
2445
+ // keeps the response open.
2446
+ const late = lateBuiltinRound(key);
2447
+ // openTurnForLeadingResult returns undefined while a response is open.
2448
+ const leading = late === undefined && rawItem.type === "hosted_tool_call" ? openTurnForLeadingResult(toolCallId) : undefined;
2449
+ const callMsgId = leading !== undefined ? `${toolCallId}:call` : undefined;
2450
+ if (leading !== undefined && callMsgId !== undefined) {
2451
+ a.openMessage({ id: callMsgId, role: "assistant", turnId: leading.turnId, threadId });
2452
+ }
2453
+ else if (late === undefined) {
2454
+ ensureResponseOpen();
2455
+ }
2456
+ const ownerMsgId = late !== undefined ? late.mId : (callMsgId ?? msgId);
2457
+ const ownerTurnId = late !== undefined ? late.tid : (leading?.turnId ?? turnId);
2458
+ if (ownerMsgId === undefined)
1717
2459
  return; // unreachable post-ensure; satisfies narrowing
1718
- const toolCallId = rawItem.type === "hosted_tool_call" ? (rawItem.id ?? rawItem.name) : rawItem.callId;
1719
- const name = builtinToolName(rawItem);
2460
+ // An MCP call or approval request is named by the MCP tool it calls
2461
+ // (`providerData.name`); the item's own name is the umbrella (`mcp_call` /
2462
+ // `mcp_approval_request`), which rides providerMetadata.type.
2463
+ const mcpToolName = mcpKind !== undefined ? rawItem.providerData?.name : undefined;
2464
+ const name = typeof mcpToolName === "string" && mcpToolName.length > 0 ? mcpToolName : builtinToolName(rawItem);
1720
2465
  // Caller provenance (0.14.0): typed only on the shapes the wire declares
1721
2466
  // it for — computer_call and program carry none (protocol.d.ts).
1722
2467
  const caller = rawItem.type === "shell_call" || rawItem.type === "apply_patch_call" || rawItem.type === "hosted_tool_call"
1723
2468
  ? rawItem.caller
1724
2469
  : undefined;
1725
- const startMeta = openaiProviderMeta({ caller: callerToJson(caller) });
2470
+ // An mcp_call that an approval gated names that request (verbatim).
2471
+ const approvalRequestId = mcpKind === "mcp_call" ? rawItem.providerData?.approval_request_id : undefined;
2472
+ const startMeta = openaiProviderMeta({
2473
+ caller: callerToJson(caller),
2474
+ type: mcpKind,
2475
+ approval_request_id: typeof approvalRequestId === "string" && approvalRequestId.length > 0 ? approvalRequestId : undefined,
2476
+ });
2477
+ // An MCP item's server label (SPEC tool.start.serverName).
2478
+ const serverLabel = rawItem.type === "hosted_tool_call" ? rawItem.providerData?.server_label : undefined;
1726
2479
  a.toolStart({
1727
2480
  toolCallId,
1728
2481
  name,
2482
+ ...(typeof serverLabel === "string" && serverLabel.length > 0 ? { serverName: serverLabel } : {}),
1729
2483
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1730
2484
  ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
1731
- // OA-13: see builtinProviderExecuted().
2485
+ // See builtinProviderExecuted().
1732
2486
  ...(builtinProviderExecuted(rawItem) ? { providerExecuted: true } : {}),
1733
- messageId: msgId,
2487
+ messageId: ownerMsgId,
1734
2488
  });
1735
2489
  const input = rawItem.type === "shell_call"
1736
2490
  ? JsonValue.parse(rawItem.action)
@@ -1742,15 +2496,30 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1742
2496
  ? // The call's whole wire payload, verbatim (the shell/apply-patch
1743
2497
  // precedent): `code` is the model-authored program source.
1744
2498
  { code: rawItem.code, fingerprint: rawItem.fingerprint }
1745
- : parseJsonArguments(rawItem.id, rawItem.arguments);
2499
+ : hostedInput(rawItem);
1746
2500
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
1747
2501
  a.toolArgsAssembled(toolCallId, input);
2502
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_request") {
2503
+ // Not resolved: the request stays a pending call of its round until its
2504
+ // answer closes it; with no answer, the round flushes paused naming its
2505
+ // ask (§8.0 items 14 and 20, INV-FLUSH (2)).
2506
+ if (callMsgId !== undefined)
2507
+ a.closeMessage(callMsgId);
2508
+ registerPendingToolFor(ownerTurnId, toolCallId);
2509
+ drainListedBuiltin(key);
2510
+ return;
2511
+ }
1748
2512
  if (rawItem.type === "hosted_tool_call") {
1749
- const content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
1750
- a.toolDone({ toolCallId, content, outcome: "ok" });
2513
+ const doneTurnId = late?.tid ?? leading?.turnId;
2514
+ a.toolDone({ toolCallId, ...hostedResult(rawItem), ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}) });
2515
+ if (callMsgId !== undefined)
2516
+ a.closeMessage(callMsgId);
2517
+ drainListedBuiltin(key);
1751
2518
  return;
1752
2519
  }
1753
- registerPendingTool(toolCallId);
2520
+ registerPendingToolFor(ownerTurnId, toolCallId);
2521
+ // Its run-item has landed; the round now waits on its result.
2522
+ drainListedBuiltin(key);
1754
2523
  }
1755
2524
  /**
1756
2525
  * Resolve the correlation id for a `tool_search_call`/`tool_search_output`
@@ -1801,29 +2570,40 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1801
2570
  * like any other unresolved pending tool call, no special-casing needed.
1802
2571
  */
1803
2572
  function driveToolSearchCalled(rawItem) {
1804
- ensureResponseOpen();
1805
- if (msgId === undefined)
1806
- return; // unreachable post-ensure; satisfies narrowing
2573
+ if (rawItem.id !== undefined)
2574
+ seenBuiltinItemIds.add(rawItem.id);
1807
2575
  const toolCallId = resolveToolSearchCallId(rawItem);
1808
2576
  if (toolCallId === undefined) {
1809
- // Genuinely unresolvable correlation id — never fabricate one (Tenet 6).
2577
+ // Genuinely unresolvable correlation id — never fabricate one (Tenet 6),
2578
+ // and open no turn for it: the carry is not block content.
1810
2579
  a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
2580
+ drainListedBuiltin(rawItem.id);
1811
2581
  return;
1812
2582
  }
2583
+ // A run-item that lands after its round's terminal attaches to that round
2584
+ // (see "Built-in round attach").
2585
+ const late = lateBuiltinRound(rawItem.id);
2586
+ if (late === undefined)
2587
+ ensureResponseOpen();
2588
+ const ownerMsgId = late !== undefined ? late.mId : msgId;
2589
+ const ownerTurnId = late !== undefined ? late.tid : turnId;
2590
+ if (ownerMsgId === undefined)
2591
+ return; // unreachable post-ensure; satisfies narrowing
1813
2592
  a.toolStart({
1814
2593
  toolCallId,
1815
2594
  name: "builtin:tool_search",
1816
2595
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1817
- // OA-13: the item says where it ran — only `execution:"server"` is the
2596
+ // The item says where it ran — only `execution:"server"` is the
1818
2597
  // provider's (SPEC:496); "client" (the SDK's own loader / a custom
1819
2598
  // execute()) and absent leave the key off.
1820
2599
  ...(rawItem.execution === "server" ? { providerExecuted: true } : {}),
1821
- messageId: msgId,
2600
+ messageId: ownerMsgId,
1822
2601
  });
1823
2602
  const input = JsonValue.parse(rawItem.arguments ?? {});
1824
2603
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
1825
2604
  a.toolArgsAssembled(toolCallId, input);
1826
- registerPendingTool(toolCallId);
2605
+ registerPendingToolFor(ownerTurnId, toolCallId);
2606
+ drainListedBuiltin(rawItem.id);
1827
2607
  }
1828
2608
  /**
1829
2609
  * Map a `tool_search_output_created` run-item — the paired completion (see
@@ -1856,8 +2636,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1856
2636
  // the deserialization boundary, where a non-string would otherwise reach
1857
2637
  // `AgProviderMeta.parse`.
1858
2638
  const rawAgentName = rawItem.toolSearchAgentName;
2639
+ // agents-core 0.20.0 adds the hosted MCP names this search established
2640
+ // (`toolSearchMcpToolNames`), carried the same way: an array of strings,
2641
+ // verbatim; anything else at this boundary is no carry.
2642
+ const rawMcpNames = rawItem.toolSearchMcpToolNames;
2643
+ const mcpNames = Array.isArray(rawMcpNames) && rawMcpNames.every((v) => typeof v === "string") ? JsonValue.parse(rawMcpNames) : undefined;
1859
2644
  const searchMeta = openaiProviderMeta({
1860
2645
  toolSearchAgentName: typeof rawAgentName === "string" ? rawAgentName : undefined,
2646
+ toolSearchMcpToolNames: mcpNames,
1861
2647
  });
1862
2648
  a.toolDone({
1863
2649
  toolCallId,
@@ -1883,7 +2669,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1883
2669
  function driveHostError(event) {
1884
2670
  // O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
1885
2671
  // close is deferred releases that close per INV-FLUSH (2) BEFORE the
1886
- // normalizer closes the error (PS-21).
2672
+ // normalizer closes the error.
1887
2673
  releaseAllDeferredCloses();
1888
2674
  ensureResponseOpen();
1889
2675
  if (turnId === undefined)
@@ -1933,7 +2719,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1933
2719
  switch (event.name) {
1934
2720
  case "tool_output": {
1935
2721
  const rawItem = event.item.rawItem;
1936
- // Finding #1 (critical) + the fixture-drift ratchet's
2722
+ // The 2026-07-03 SDK-bump adaptation + the fixture-drift ratchet's
1937
2723
  // computer_call_result finding + the 0.14.0 program_output carry:
1938
2724
  // Shell/Apply-Patch/Computer-Use/Program results do NOT share
1939
2725
  // `OpenAIFunctionCallResultItem.output`'s shape — see
@@ -1943,7 +2729,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1943
2729
  rawItem.type === "apply_patch_call_output" ||
1944
2730
  rawItem.type === "computer_call_result" ||
1945
2731
  rawItem.type === "program_output") {
1946
- driveBuiltinToolOutput(rawItem);
2732
+ driveBuiltinToolOutput(rawItem, event.item.executionStatus);
1947
2733
  return;
1948
2734
  }
1949
2735
  const releasedFrom = droppedCalls.get(rawItem.callId);
@@ -1960,7 +2746,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1960
2746
  return;
1961
2747
  }
1962
2748
  // Authoritative tool-result source (canonical model, A1). Drives toolDone
1963
- // with content + structuredContent (the ggui cache marker — see
2749
+ // with content + structuredContent (a reference client's cache marker — see
1964
2750
  // `extractStructuredContent`'s doc for the two peer-supported homes and
1965
2751
  // the playbook 2026-07-03 wire-truth findings behind them).
1966
2752
  const outcome = rawItem.status === "incomplete" ? "error" : "ok";
@@ -1968,7 +2754,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1968
2754
  const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
1969
2755
  // workspace#21: `customData._meta` → block `_meta`; with `_meta.ui` the
1970
2756
  // payload is MCP-Apps view data → ALSO `uiData` (SPEC.md:332), leaving
1971
- // `structuredContent` as it was (the :340 mapping; ggui's cache marker
2757
+ // `structuredContent` as it was (the :340 mapping; a reference client's cache marker
1972
2758
  // rides it). §2.1's "exactly one consumer" is per channel (ruled
1973
2759
  // option A). Mirrors claude-agent-sdk/src/index.ts:1926-1946.
1974
2760
  const resultMeta = extractResultMeta(event.item.customData);
@@ -1982,7 +2768,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
1982
2768
  // could misattribute it) and pass it through so toolDone binds to the
1983
2769
  // correct — possibly already-closed-pending-this-result — turn.
1984
2770
  const doneTurnId = resolvePendingTurnId(rawItem.callId);
1985
- // HO-2 (the handoff-drop review, PS-4): a result for a transfer call
2771
+ // A result for a transfer call
1986
2772
  // whose bracket is still open means that handoff never ran —
1987
2773
  // agents-core <=0.8.0's "Multiple handoffs detected, ignoring this
1988
2774
  // one." (0.8.0 toolExecution.mjs:750-755), the one streamed producer.
@@ -2003,7 +2789,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2003
2789
  a.subagentDone(unrun.turnId, unrun.parentTurnId);
2004
2790
  }
2005
2791
  // Caller provenance (0.14.0) — the result item's own optional field,
2006
- // distinct from the call-side carry on tool.start — and the 0.15.0
2792
+ // distinct from the call-side carry on tool.start — and the 0.14.3
2007
2793
  // wrapper-level `executionStatus` marker (see the projection's doc):
2008
2794
  // both verbatim, both dropped when absent.
2009
2795
  const doneMeta = openaiProviderMeta({
@@ -2039,7 +2825,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2039
2825
  // ignoring the wrapper copy here loses nothing.
2040
2826
  return;
2041
2827
  }
2042
- // Finding #1 (critical): Shell / Apply-Patch / Hosted-tool /
2828
+ // The 2026-07-03 SDK-bump adaptation: Shell / Apply-Patch / Hosted-tool /
2043
2829
  // Program built-ins — this run-item wrapper (not the raw stream) is
2044
2830
  // the SOLE tool-start source for these (see `driveBuiltinToolCalled`'s
2045
2831
  // doc).
@@ -2056,7 +2842,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2056
2842
  driveToolSearchOutput(event.item.rawItem);
2057
2843
  return;
2058
2844
  case "reasoning_item_created":
2059
- // FALLBACK source since OA-11 (the raw terminal output fills first; an
2845
+ // FALLBACK source (the raw terminal output fills first; an
2060
2846
  // already-filled rs_ is a no-op) — see driveReasoningItemCreated's docstring.
2061
2847
  driveReasoningItemCreated(event.item.rawItem);
2062
2848
  return;
@@ -2073,7 +2859,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2073
2859
  // `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
2074
2860
  // bracket the transfer with `subagentStart` now / `subagentDone` at the
2075
2861
  // matching `handoff_occurred` below (by callId via `openHandoffs`; or at
2076
- // the call's `tool_output` when the handoff never ran — HO-2).
2862
+ // the call's `tool_output` when the handoff never ran).
2077
2863
  //
2078
2864
  // `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
2079
2865
  // LLM call produced this handoff call — NOT the transfer target (see
@@ -2145,7 +2931,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2145
2931
  // still emit the `handoff` event losslessly rather than dropping the
2146
2932
  // now-known identity (Tenet 6) — it just doesn't close anything. It
2147
2933
  // precedes the tool.done, which may close the source round.
2148
- // HO-2: the handoff is owned by the SOURCE turn, explicitly. With two
2934
+ // The handoff is owned by the SOURCE turn, explicitly. With two
2149
2935
  // brackets open (agents-core <=0.8.0) the engine's backfill would pick
2150
2936
  // the last-restored nested turn; on every single-bracket stream this is
2151
2937
  // the value the backfill gave.
@@ -2191,22 +2977,31 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2191
2977
  return;
2192
2978
  }
2193
2979
  case "tool_approval_requested": {
2194
- // Task 3 (audit M48): a human-in-the-loop approval gate on a pending
2195
- // tool call. `askId` mirrors the `approval_${callId}` convention already
2196
- // established by the google-adk facet's `requestedToolConfirmations` arm
2197
- // (index.ts:653) for the same `kind:"approval"` semantics. The M26
2198
- // paused-fold discipline (surfacing this on the turn's `outcome.paused`)
2199
- // is ADK-scoped for this batch — `hitl.ask` is LIVE-ONLY on the fold
2200
- // (reduce.ts R9: no accumulator mutation), so emitting the ask alone is
2201
- // complete; the host/turn-close owns any pause semantics.
2980
+ // A human-in-the-loop approval gate on a pending tool call. `askId`
2981
+ // mirrors the `approval_${callId}` convention of the google-adk
2982
+ // facet's `requestedToolConfirmations` arm for the same
2983
+ // `kind:"approval"` semantics. The gated call stays pending, so a
2984
+ // round the stream leaves waiting on it flushes paused naming this
2985
+ // ask (INV-FLUSH (2)).
2202
2986
  const item = event.item.rawItem;
2987
+ // The call the ask gates: a function, shell, apply-patch or computer
2988
+ // call's callId, else the item's id. A hosted-MCP approval request
2989
+ // has no callId, and its id is the request id its tool.start uses.
2990
+ // callId comes first, so a function approval's ask is unchanged.
2991
+ const gatedId = item.callId ?? item.id;
2992
+ if (gatedId === undefined) {
2993
+ // No id to key on: a collision-free derived askId (INV-BLOCK) and
2994
+ // no toolCallId, rather than naming a call the facet cannot find.
2995
+ a.emit({ type: "hitl.ask", askId: `approval_${invokeStem}_${++derivedOrdinal}`, kind: "approval" });
2996
+ return;
2997
+ }
2203
2998
  a.emit({
2204
2999
  type: "hitl.ask",
2205
- askId: `approval_${item.callId}`,
3000
+ askId: `approval_${gatedId}`,
2206
3001
  kind: "approval",
2207
- toolCallId: item.callId,
3002
+ toolCallId: gatedId,
2208
3003
  });
2209
- askedApprovals.set(item.callId, `approval_${item.callId}`);
3004
+ askedApprovals.set(gatedId, `approval_${gatedId}`);
2210
3005
  return;
2211
3006
  }
2212
3007
  default:
@@ -2273,7 +3068,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
2273
3068
  flush() {
2274
3069
  // O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
2275
3070
  // closes FIRST — they are older rounds, so their message.end precedes the
2276
- // live response's (insertion order, CB-16) — as paused / verbatim /
3071
+ // live response's (insertion order) — as paused / verbatim /
2277
3072
  // message.end+usage then turn.abort (`releaseDeferredClose`); a flush
2278
3073
  // never emits a success turn.done.
2279
3074
  releaseAllDeferredCloses();