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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -123,8 +123,13 @@ import {
123
123
  export interface OpenAIOutputText {
124
124
  type: "output_text";
125
125
  text: string;
126
- /** url_citation and file_citation annotations on the text part. */
126
+ /** url_citation and file_citation annotations on the text part (a fixture
127
+ * shape; the run-item wire carries them under `providerData`). */
127
128
  annotations?: OpenAIAnnotation[];
129
+ /** Every part field but `type` and `text`, as agents-openai's converter
130
+ * nests them (`annotations`, `logprobs`; openaiResponsesConverter.mjs
131
+ * `convertToMessageContentItem`). */
132
+ providerData?: { [k: string]: JsonValue };
128
133
  }
129
134
 
130
135
  /** url_citation annotation on an output_text part (openai-node `ResponseCitationAnnotation`).
@@ -266,8 +271,8 @@ export interface OpenAIFunctionCallResultItem {
266
271
  providerData?: { [k: string]: JsonValue };
267
272
  }
268
273
 
269
- // ── OpenAI native BUILT-IN tool call shapes (playbook 2026-07-03 SDK-bump
270
- // adaptation, Finding #1 — @openai/agents-core 0.2.1 → 0.12.0). Shell /
274
+ // ── OpenAI native BUILT-IN tool call shapes (the 2026-07-03 SDK-bump
275
+ // adaptation, @openai/agents-core 0.2.1 → 0.12.0). Shell /
271
276
  // Apply-Patch / Hosted-tool calls carry NO dedicated RunItemStreamEventName —
272
277
  // they reuse the pre-existing `tool_called`/`tool_output` names with NEW
273
278
  // `rawItem` shapes (verified against @openai/agents-core 0.12.0's
@@ -466,7 +471,7 @@ export interface OpenAIProgramCallResultItem {
466
471
  // ── OpenAI native Computer-Use built-in tool shapes (fixture-drift ratchet
467
472
  // finding, 2026-07-03 — Task 6's `sdk-surface.json` inventory surfaced that
468
473
  // `computer_call`/`computer_call_result` ride the SAME `tool_called`/
469
- // `tool_output` event names Finding #1 already fixed for shell/apply-patch,
474
+ // `tool_output` event names the 2026-07-03 adaptation already fixed for shell/apply-patch,
470
475
  // but were left uncovered by that fix. Verified against
471
476
  // @openai/agents-core 0.12.0's `dist/types/protocol.d.ts`: `ComputerUseCallItem`
472
477
  // / `ComputerCallResultItem`.)
@@ -602,6 +607,17 @@ export interface OpenAIToolSearchOutputItem {
602
607
  * it is fixture-tested only.
603
608
  */
604
609
  toolSearchAgentName?: string;
610
+ /**
611
+ * agents-core 0.20.0 (`ToolSearchOutputItem.toolSearchMcpToolNames`): the
612
+ * hosted MCP tool names a server-executed search's namespace results
613
+ * established, recorded by the SDK so a later deferred MCP call can be
614
+ * matched to its discovery. Upstream doc: "SDK-only hosted MCP namespace
615
+ * identities established when this output was received. Excluded from
616
+ * provider requests. … This records discovery, not permission to execute a
617
+ * tool." Carried verbatim on `tool.done` providerMetadata, like
618
+ * `toolSearchAgentName`.
619
+ */
620
+ toolSearchMcpToolNames?: string[];
605
621
  call_id?: string | null;
606
622
  callId?: string | null;
607
623
  execution?: "client" | "server";
@@ -639,7 +655,7 @@ interface OpenAIMessageOutputEvent {
639
655
  interface OpenAIToolCalledEvent {
640
656
  type: "run_item_stream_event";
641
657
  name: "tool_called";
642
- // Widened (playbook 2026-07-03 SDK-bump adaptation, Finding #1 + the
658
+ // Widened (the 2026-07-03 SDK-bump adaptation + the
643
659
  // fixture-drift ratchet's computer_call finding + the 0.14.0 programmatic-
644
660
  // tool-calling carry): Shell / Apply-Patch / Computer-Use / Hosted-tool /
645
661
  // Program built-ins reuse this SAME event name with a DIFFERENT `rawItem`
@@ -659,12 +675,12 @@ interface OpenAIToolOutputEvent {
659
675
  type: "run_item_stream_event";
660
676
  name: "tool_output";
661
677
  // `item.rawItem` carries the protocol FunctionCallResultItem (callId, output, status)
662
- // — OR, widened (Finding #1 + the fixture-drift ratchet's computer_call_result
678
+ // — OR, widened (the 2026-07-03 adaptation + the fixture-drift ratchet's computer_call_result
663
679
  // finding), a Shell/Apply-Patch/Computer-Use result (DIFFERENT `output`
664
680
  // shape per discriminant; `hosted_tool_call` never reaches this event, see its
665
681
  // own doc).
666
682
  //
667
- // structuredContent (the ggui cache marker, spec §2.1/§4) has TWO
683
+ // structuredContent (a reference client's cache marker, spec §2.1/§4) has TWO
668
684
  // peer-supported homes on this wrapper (playbook 2026-07-03 follow-up,
669
685
  // `extractStructuredContent`'s doc has the full wire-truth citations):
670
686
  // - `item.customData` — populated ONLY when the caller's `MCPServer`
@@ -820,14 +836,20 @@ interface OpenAIHandoffOccurredEvent {
820
836
  item: OpenAIHandoffOccurredItem;
821
837
  }
822
838
 
823
- /** A tool approval request item (RunToolApprovalItem) — the function call that
824
- * needs human approval rides in rawItem. */
839
+ /** A tool approval request item (RunToolApprovalItem) — the call that needs
840
+ * human approval rides in rawItem. A function, shell, apply-patch or computer
841
+ * call carries its `callId`. A hosted-MCP approval request is a
842
+ * `hosted_tool_call` with NO callId: `{name: <the MCP tool's name>, id: <the
843
+ * request id>, status, providerData}` (agents-core 0.18.0
844
+ * runner/modelOutputs.mjs:463-470), and its request id is agents-core's own
845
+ * identity for it. */
825
846
  interface OpenAIToolApprovalItem {
826
- type: "function_call";
827
- name: string;
828
- callId: string;
829
- arguments: string;
847
+ type: string;
848
+ name?: string;
849
+ callId?: string;
850
+ arguments?: string;
830
851
  id?: string;
852
+ providerData?: { [k: string]: JsonValue };
831
853
  }
832
854
 
833
855
  interface OpenAIToolApprovalRequestedEvent {
@@ -877,7 +899,7 @@ type OpenAIRunItemEvent =
877
899
  * the `model` carrier. */
878
900
  interface OpenAIResponsesCreated {
879
901
  type: "response.created";
880
- /** `model` (OA-12): openai-node `Response.model` — the model id the API
902
+ /** `model` (the per-message model): openai-node `Response.model` — the model id the API
881
903
  * resolved for THIS response (live echo-gpt6sol: `"gpt-6-sol"`), known before
882
904
  * the message opens → `message.start.model`. Typed as the raw `JsonValue` it
883
905
  * is on this seam; string-guarded at the read. */
@@ -912,6 +934,21 @@ interface OpenAIResponsesTextDone {
912
934
  item_id: string;
913
935
  text?: string;
914
936
  }
937
+ /** openai-node `ResponseRefusalDeltaEvent` — a streamed fragment of a
938
+ * `refusal` content part's text (snake_case `item_id`/`delta`). Carried via the
939
+ * `model` carrier. */
940
+ interface OpenAIResponsesRefusalDelta {
941
+ type: "response.refusal.delta";
942
+ item_id: string;
943
+ delta: string;
944
+ }
945
+ /** openai-node `ResponseRefusalDoneEvent` — the `refusal` part of `item_id` is
946
+ * complete; `refusal` carries its whole text. Carried via the `model` carrier. */
947
+ interface OpenAIResponsesRefusalDone {
948
+ type: "response.refusal.done";
949
+ item_id: string;
950
+ refusal: string;
951
+ }
915
952
  /** openai-node `ResponseUsage` — per-response token counts (snake_case).
916
953
  * Extends to include provider-specific fields like OpenRouter's `cost` superset.
917
954
  * `cache_write_tokens` is openai ≥6.46 wire (GPT-5.6-era explicit prompt
@@ -945,7 +982,7 @@ interface OpenAIResponsesCompleted {
945
982
  incomplete_details?: { reason?: string };
946
983
  usage?: OpenAIResponseUsage;
947
984
  /** openai-node `Response.output: ResponseOutputItem[]` — consumed ONLY for its
948
- * `type:"reasoning"` members (OA-11; see `terminalReasoningItems`). Typed as
985
+ * `type:"reasoning"` members (reasoning from the terminal output; see `terminalReasoningItems`). Typed as
949
986
  * the raw `JsonValue` it is on this seam and narrowed item-by-item there:
950
987
  * the outer guard (`isOpenAIStreamEvent`) validates the envelope only. */
951
988
  output?: JsonValue;
@@ -963,8 +1000,148 @@ interface TerminalReasoningItem {
963
1000
  encryptedContent?: string;
964
1001
  }
965
1002
 
1003
+ /** One `refusal` content part of a terminal event's `response.output` message
1004
+ * member, narrowed from `JsonValue`: its item's id and vendor phase marker
1005
+ * (when present) and its text. */
1006
+ interface TerminalRefusalPart {
1007
+ itemId?: string;
1008
+ phase?: string;
1009
+ text: string;
1010
+ }
1011
+
1012
+ /**
1013
+ * The refusal parts of a terminal event's `response.output`, in wire order —
1014
+ * the source of a round's refusal text when no refusal event streamed
1015
+ * (see "Refusal text" in the normalizer). Deserialization boundary: a
1016
+ * non-array output, a non-message member and a part whose `refusal` is not a
1017
+ * string are skipped; an empty id is no id.
1018
+ */
1019
+ function terminalRefusalParts(output: JsonValue | undefined): TerminalRefusalPart[] {
1020
+ const out: TerminalRefusalPart[] = [];
1021
+ if (!Array.isArray(output)) return out;
1022
+ for (const member of output) {
1023
+ if (!isJsonObject(member) || member.type !== "message") continue;
1024
+ const content = member.content;
1025
+ if (!Array.isArray(content)) continue;
1026
+ const itemId = typeof member.id === "string" && member.id.length > 0 ? member.id : undefined;
1027
+ const phase = vendorPhase(member.phase);
1028
+ for (const part of content) {
1029
+ if (!isJsonObject(part) || part.type !== "refusal" || typeof part.refusal !== "string") continue;
1030
+ out.push({
1031
+ ...(itemId !== undefined ? { itemId } : {}),
1032
+ ...(phase !== undefined ? { phase } : {}),
1033
+ text: part.refusal,
1034
+ });
1035
+ }
1036
+ }
1037
+ return out;
1038
+ }
1039
+
1040
+ /**
1041
+ * Did the model refuse in this response? True when any `message` member of a
1042
+ * terminal event's `response.output` carries a `refusal` content part. On the
1043
+ * live wire the `message_output_created` run-item lands AFTER the terminal
1044
+ * event, so the terminal output is where the round's own refusal is known when
1045
+ * the round closes. Absent/non-array output, or no refusal part, ⇒ false.
1046
+ */
1047
+ function terminalHasRefusal(output: JsonValue | undefined): boolean {
1048
+ if (!Array.isArray(output)) return false;
1049
+ for (const member of output) {
1050
+ if (!isJsonObject(member) || member.type !== "message") continue;
1051
+ const content = member.content;
1052
+ if (!Array.isArray(content)) continue;
1053
+ for (const part of content) {
1054
+ if (isJsonObject(part) && part.type === "refusal") return true;
1055
+ }
1056
+ }
1057
+ return false;
1058
+ }
1059
+
1060
+ /**
1061
+ * The media type of an image_generation result (base64): the item's
1062
+ * `output_format` when it carries one (openai-node 7.22.0 declares it
1063
+ * optional and nullable on ImageGenerationCall), else read from the image's
1064
+ * own signature, else `application/octet-stream`.
1065
+ */
1066
+ function imageResultMediaType(providerData: { [k: string]: JsonValue } | undefined, data: string): string {
1067
+ const format = providerData?.output_format;
1068
+ if (format === "png" || format === "jpeg" || format === "webp" || format === "gif") return `image/${format}`;
1069
+ if (data.startsWith("iVBORw0KGgo")) return "image/png";
1070
+ if (data.startsWith("/9j/")) return "image/jpeg";
1071
+ if (data.startsWith("UklGR")) return "image/webp";
1072
+ if (data.startsWith("R0lGOD")) return "image/gif";
1073
+ return "application/octet-stream";
1074
+ }
1075
+
1076
+ /**
1077
+ * The raw Responses output item types that @openai/agents 0.18.0 turns into a
1078
+ * built-in call run-item keeping the item's id: agents-openai's converter
1079
+ * (openaiResponsesConverter.mjs `convertToOutputItem`) maps the hosted kinds
1080
+ * to a `hosted_tool_call` with `id: item.id`, and keeps shell, apply-patch,
1081
+ * computer, program and tool-search calls under their own type. agents-core
1082
+ * streams each as a `tool_called` / `tool_search_called` run-item AFTER the
1083
+ * response's `response.completed` (it streams a response's step items after
1084
+ * the raw loop, run.mjs:1935). `local_shell_call` converts to an unknown item
1085
+ * and never streams as a call, so it is not listed.
1086
+ */
1087
+ const BUILTIN_OUTPUT_ITEM_TYPES: ReadonlySet<string> = new Set([
1088
+ "web_search_call",
1089
+ "file_search_call",
1090
+ "image_generation_call",
1091
+ "code_interpreter_call",
1092
+ "mcp_list_tools",
1093
+ "mcp_approval_request",
1094
+ "mcp_call",
1095
+ "computer_call",
1096
+ "shell_call",
1097
+ "apply_patch_call",
1098
+ "program",
1099
+ "tool_search_call",
1100
+ ]);
1101
+
1102
+ /** A built-in call a terminal event's `response.output` lists: its item id
1103
+ * and raw type. */
1104
+ interface TerminalBuiltinItem {
1105
+ id: string;
1106
+ type: string;
1107
+ }
1108
+
1109
+ /**
1110
+ * The built-in calls a terminal event's `response.output` lists, in wire
1111
+ * order (see {@link BUILTIN_OUTPUT_ITEM_TYPES}). Deserialization boundary: a
1112
+ * non-array output, a non-object member and a member with no non-empty string
1113
+ * id are skipped.
1114
+ */
1115
+ function terminalBuiltinItems(output: JsonValue | undefined): TerminalBuiltinItem[] {
1116
+ const out: TerminalBuiltinItem[] = [];
1117
+ if (!Array.isArray(output)) return out;
1118
+ for (const member of output) {
1119
+ if (!isJsonObject(member)) continue;
1120
+ const type = member.type;
1121
+ const id = member.id;
1122
+ if (typeof type !== "string" || !BUILTIN_OUTPUT_ITEM_TYPES.has(type)) continue;
1123
+ if (typeof id !== "string" || id.length === 0) continue;
1124
+ out.push({ id, type });
1125
+ }
1126
+ return out;
1127
+ }
1128
+
1129
+ /** The ids of the `message` items a terminal event's `response.output` lists,
1130
+ * in wire order (a non-object member or a member with no non-empty string
1131
+ * id is skipped). */
1132
+ function terminalMessageIds(output: JsonValue | undefined): string[] {
1133
+ const out: string[] = [];
1134
+ if (!Array.isArray(output)) return out;
1135
+ for (const member of output) {
1136
+ if (!isJsonObject(member) || member.type !== "message") continue;
1137
+ const id = member.id;
1138
+ if (typeof id === "string" && id.length > 0) out.push(id);
1139
+ }
1140
+ return out;
1141
+ }
1142
+
966
1143
  /**
967
- * OA-11: extract the reasoning items from a terminal event's `response.output`.
1144
+ * Reasoning from the terminal output: extract the reasoning items from a terminal event's `response.output`.
968
1145
  * This — not `response.output_item.done` — is the replayable source: OpenAI
969
1146
  * re-encrypts `encrypted_content` per stage (live, echo-gpt6sol natives [4] vs
970
1147
  * [21]: two different blobs for one `rs_`), and only the terminal blob is the
@@ -976,7 +1153,7 @@ interface TerminalReasoningItem {
976
1153
  * Deserialization boundary: a non-array `output`, a non-object member, a member
977
1154
  * with no string `id`, and a non-string summary `text` are all skipped (an
978
1155
  * id-less reasoning item stays with the run-item path, which already degrades
979
- * it losslessly). Absent/empty output ⇒ `[]` ⇒ byte-identical to pre-OA-11.
1156
+ * it losslessly). Absent/empty output ⇒ `[]` ⇒ nothing is emitted from it (byte-identical).
980
1157
  */
981
1158
  function terminalReasoningItems(output: JsonValue | undefined): TerminalReasoningItem[] {
982
1159
  if (!Array.isArray(output)) return [];
@@ -1035,7 +1212,7 @@ interface OpenAIResponsesOutputItemAdded {
1035
1212
  // AUTHORITATIVE tool.start source for function_call, so caller provenance
1036
1213
  // must ride HERE — the run-item wrapper occurrence stays ignored.
1037
1214
  caller?: { type: "direct" } | { type: "program"; caller_id: string } | null;
1038
- // OA-14: openai-node `ResponseOutputMessage.phase` (`'commentary' |
1215
+ // The phase read at the raw add: openai-node `ResponseOutputMessage.phase` (`'commentary' |
1039
1216
  // 'final_answer' | null`) — present on a `type:"message"` item AT ADD time
1040
1217
  // (6/8 live openai seeds). Raw `JsonValue`; string-guarded at the read.
1041
1218
  phase?: JsonValue;
@@ -1090,6 +1267,8 @@ type OpenAIRawResponsesEvent =
1090
1267
  | OpenAIResponsesFnArgsDone
1091
1268
  | OpenAIResponsesTextDelta
1092
1269
  | OpenAIResponsesTextDone
1270
+ | OpenAIResponsesRefusalDelta
1271
+ | OpenAIResponsesRefusalDone
1093
1272
  | OpenAIResponsesCompleted
1094
1273
  | OpenAIResponsesFailed
1095
1274
  | OpenAIResponsesError;
@@ -1179,7 +1358,7 @@ export function mapFinishReason(reason: string | undefined | null): AgFinishReas
1179
1358
  }
1180
1359
 
1181
1360
  /**
1182
- * OA-15 (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
1361
+ * The finish-reason raw companion (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
1183
1362
  * 89c57db): the `turn.done` finish fields for a native reason. `finishReason`
1184
1363
  * is `mapFinishReason(reason)`; `finishReasonRaw` — the native value byte for
1185
1364
  * byte — rides along ONLY when that mapping fell back ("other"/"unknown") AND a
@@ -1238,46 +1417,69 @@ function mapUsage(usage: OpenAIResponseUsage | undefined): AgUsage | undefined {
1238
1417
  return u;
1239
1418
  }
1240
1419
 
1241
- // ─── url_citation annotation → AgCitation ──────────────────────────────────
1242
- // `partText` is the source output_text part's text string; used to extract the
1243
- // cited substring from the char-offset indices carried by the annotation (Fix 3).
1244
- function mapAnnotationsToCitations(
1245
- annotations: OpenAIAnnotation[] | undefined,
1246
- partText: string,
1247
- ): AgCitation[] | undefined {
1248
- if (annotations === undefined || annotations.length === 0) return undefined;
1249
- const out: AgCitation[] = [];
1250
- for (const ann of annotations) {
1251
- if (ann.type === "url_citation") {
1252
- // Extract the cited substring from the part text when both offsets are present
1253
- // and valid (Fix 3). Fall back to "" when any guard condition fails.
1254
- const startIdx = ann.start_index;
1255
- const endIdx = ann.end_index;
1256
- const citedText =
1257
- startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
1258
- ? partText.slice(startIdx, endIdx)
1259
- : "";
1260
- const cit: AgCitation = {
1261
- kind: "url",
1262
- url: ann.url,
1263
- citedText,
1264
- indexFrame: "response",
1265
- };
1266
- if (ann.title !== undefined) cit.title = ann.title;
1267
- if (startIdx !== undefined) cit.startIndex = startIdx;
1268
- if (endIdx !== undefined) cit.endIndex = endIdx;
1269
- out.push(cit);
1420
+ // ─── output_text annotations → AgCitation ──────────────────────────────────
1421
+ // In `splitAnnotations`, `partText` is the source output_text part's text
1422
+ // string, used to extract the cited substring from the char-offset indices
1423
+ // carried by the annotation.
1424
+ /**
1425
+ * An output_text part's annotations, raw. agents-openai 0.18.0's converter
1426
+ * nests every part field but `type` and `text` under `providerData`
1427
+ * (openaiResponsesConverter.mjs `convertToMessageContentItem`), so on the real
1428
+ * wire they are `part.providerData.annotations` (15 of 17 recorded parts carry
1429
+ * them there, 0 at the top level); a top-level `annotations` is read first.
1430
+ * Anything but an array is no annotations.
1431
+ */
1432
+ function partAnnotations(part: OpenAIOutputText): JsonValue[] {
1433
+ const top: unknown = part.annotations;
1434
+ const nested: unknown = part.providerData?.annotations;
1435
+ const raw = Array.isArray(top) ? top : Array.isArray(nested) ? nested : undefined;
1436
+ if (raw === undefined) return [];
1437
+ const parsed = JsonValue.parse(raw);
1438
+ return Array.isArray(parsed) ? parsed : [];
1439
+ }
1440
+
1441
+ /**
1442
+ * Split a part's raw annotations. A `url_citation` with a string `url` maps
1443
+ * to an AgCitation; every other annotation (file_citation,
1444
+ * container_file_citation, file_path, …) has no citation target and stays
1445
+ * verbatim in `unmapped`, for the `ext.openai.late-citations` carry (SPEC:965:
1446
+ * never dropped silently).
1447
+ */
1448
+ function splitAnnotations(raw: readonly JsonValue[], partText: string): { citations?: AgCitation[]; unmapped: JsonValue[] } {
1449
+ const citations: AgCitation[] = [];
1450
+ const unmapped: JsonValue[] = [];
1451
+ for (const ann of raw) {
1452
+ if (!isJsonObject(ann) || ann.type !== "url_citation" || typeof ann.url !== "string") {
1453
+ unmapped.push(ann);
1454
+ continue;
1270
1455
  }
1271
- // file_citation: no url-kind match; skip (deferred to a later slice — only remaining silent annotation drop)
1456
+ // Extract the cited substring from the part text when both offsets are present
1457
+ // and valid. Fall back to "" when any guard condition fails.
1458
+ const startIdx = typeof ann.start_index === "number" ? ann.start_index : undefined;
1459
+ const endIdx = typeof ann.end_index === "number" ? ann.end_index : undefined;
1460
+ const citedText =
1461
+ startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
1462
+ ? partText.slice(startIdx, endIdx)
1463
+ : "";
1464
+ const cit: AgCitation = {
1465
+ kind: "url",
1466
+ url: ann.url,
1467
+ citedText,
1468
+ indexFrame: "response",
1469
+ };
1470
+ if (typeof ann.title === "string") cit.title = ann.title;
1471
+ if (startIdx !== undefined) cit.startIndex = startIdx;
1472
+ if (endIdx !== undefined) cit.endIndex = endIdx;
1473
+ citations.push(cit);
1272
1474
  }
1273
- return out.length > 0 ? out : undefined;
1475
+ return { ...(citations.length > 0 ? { citations } : {}), unmapped };
1274
1476
  }
1275
1477
 
1276
1478
  // ─── optional 0.14.0 wire fields → providerMetadata (spec §2) ─────────────────
1277
1479
  // Wire names ride verbatim at the top level (the claude facet's wrapper-carry
1278
1480
  // precedent — AgProviderMeta imposes no key namespacing). Drops undefined
1279
1481
  // values; an ALL-absent input yields undefined, never an empty metadata object.
1280
- /** PH-2 / OA-14: an OpenAI message `phase` as a vendor MARKER — a non-empty
1482
+ /** The phase marker: an OpenAI message `phase` as a vendor MARKER — a non-empty
1281
1483
  * string, verbatim — or `undefined`. openai-node types it
1282
1484
  * `'commentary' | 'final_answer' | null`; null and "" carry no marker, so they
1283
1485
  * yield neither a `providerMetadata.phase` carry nor an ext.openai.late-phase
@@ -1287,7 +1489,7 @@ function vendorPhase(value: unknown): string | undefined {
1287
1489
  return typeof value === "string" && value.length > 0 ? value : undefined;
1288
1490
  }
1289
1491
 
1290
- /** PH-2 (draft.4, SPEC §8.0 item 27): the first-class `phase` for an OpenAI
1492
+ /** SPEC §8.0 item 27 (draft.4): the first-class `phase` for an OpenAI
1291
1493
  * vendor marker — `"commentary"` → `"interim"`; "final_answer", absent and
1292
1494
  * every other value → `undefined` (a vendor spelling is never copied into
1293
1495
  * `phase`; it stays verbatim in `providerMetadata`). */
@@ -1327,7 +1529,7 @@ function isJsonObject(v: unknown): v is { readonly [k: string]: JsonValue } {
1327
1529
  }
1328
1530
 
1329
1531
  /**
1330
- * Extract `structuredContent` (the ggui cache-marker channel, spec §2.1/§4)
1532
+ * Extract `structuredContent` (a reference client's cache-marker channel, spec §2.1/§4)
1331
1533
  * from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
1332
1534
  * follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
1333
1535
  * would be an object keyed by `.structuredContent`; a live capture
@@ -1416,11 +1618,11 @@ function extractStructuredContent(
1416
1618
  }
1417
1619
 
1418
1620
  /**
1419
- * workspace#21 (guuey#981): the MCP tool result's `_meta`, riding the same
1621
+ * workspace#21 (a reference host's ask): the MCP tool result's `_meta`, riding the same
1420
1622
  * host-convention `customData` channel as `structuredContent` (SPEC.md:340) —
1421
1623
  * agents-core 0.18.0 hands it to `MCPServer.customDataExtractor` as
1422
1624
  * `context.resultMeta` (`dist/mcpUtil.d.ts`:41, `result._meta ?? content._meta`
1423
- * at `dist/mcp.mjs`:700); guuey's worker and this repo's capture agent return it
1625
+ * at `dist/mcp.mjs`:700); a reference host's worker and this repo's capture agent return it
1424
1626
  * as `customData._meta`. It is a host/protocol annotation (MCP-Apps `ui.*`), so
1425
1627
  * it rides the tool-result block's own `_meta` VERBATIM (SPEC.md:338; §8.0
1426
1628
  * no-drop). Ruled option A on 2026-09-23. A non-object `_meta`
@@ -1469,14 +1671,17 @@ function isOpenAIStreamEvent(v: unknown): v is OpenAIStreamEvent {
1469
1671
  *
1470
1672
  * - turn open ← `model:response.created` (real `response.id` present at start)
1471
1673
  * - text ← `model:response.output_text.delta` (carries `item_id`)
1674
+ * - refusal ← `model:response.refusal.delta` / `.done` (a `text` block,
1675
+ * id `<item_id>:refusal`); with no refusal event in the round,
1676
+ * the terminal output's refusal part (see "Refusal text")
1472
1677
  * - text end ← the `message_output_created` run-item (authoritative close +
1473
- * citations carrier, audit M22 — `response.output_text.done` is a
1678
+ * citations carrier — `response.output_text.done` is a
1474
1679
  * no-op; text streams left open by it fall to the defensive
1475
1680
  * close-any-dangling-stream fallback in `closeResponse()` /
1476
1681
  * `endOpenStreamsAndCloseMessage()` / `emitRoundClose()`)
1477
1682
  * - reasoning ← opens at `model:response.output_item.added{reasoning}` (wire
1478
1683
  * position), filled from the `model:response.completed` /
1479
- * `.incomplete` `response.output` (OA-11 — the final, replayable
1684
+ * `.incomplete` `response.output` (reasoning from the terminal output — the final, replayable
1480
1685
  * `encrypted_content`); `reasoning_item_created` is the fallback
1481
1686
  * - turn close ← `model:response.completed` (guard close-once)
1482
1687
  *
@@ -1525,10 +1730,10 @@ export interface OpenaiNormalizerOptions {
1525
1730
  * `turn_<invokeId>_handoff_<n>`.
1526
1731
  *
1527
1732
  * These ids must be unique across every invoke folded into one reducer. The
1528
- * rnd-14 ruling and INV-BLOCK's collision-free derived ids require it: guuey
1733
+ * delivery-integrity rule and INV-BLOCK's collision-free derived ids require it: a reference host
1529
1734
  * folds a whole conversation into ONE Reducer, and a repeated turn id
1530
1735
  * re-opens a closed turn, which parks INV-TURN / INV-MSG consumers.
1531
- * The D3 review (finding DC-10) found the old per-normalizer
1736
+ * A review of the minted ids found the old per-normalizer
1532
1737
  * counters (`turn_openai_<n>`, `turn_handoff_<n>`) repeating across invokes.
1533
1738
  *
1534
1739
  * By default each normalizer draws a fresh `openai_<16 hex>` stem from
@@ -1579,7 +1784,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1579
1784
  let responseId: string | undefined; // real response.id once known
1580
1785
  // Open text streams keyed by Responses item_id (textStart once per id).
1581
1786
  const openTextStreams = new Set<string>();
1582
- // OA-11 reasoning-block state. `openReasoning`: rs_ id → the message id its
1787
+ // Reasoning-block state (reasoning from the terminal output). `openReasoning`: rs_ id → the message id its
1583
1788
  // block opened in (at `output_item.added{reasoning}`), awaiting its fill from
1584
1789
  // the terminal output; per-response (cleared by `resetResponseState`).
1585
1790
  // `filledReasoning`: every rs_ id whose block has been filled — normalizer-
@@ -1587,19 +1792,19 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1587
1792
  // response closed and must dedupe against it (single source per rs_ id).
1588
1793
  const openReasoning = new Map<string, string>();
1589
1794
  const filledReasoning = new Set<string>();
1590
- // OA-14 phase state. `pendingPhase`: message item id → the phase its raw
1795
+ // Phase state (the phase read at the raw add). `pendingPhase`: message item id → the phase its raw
1591
1796
  // `output_item.added` announced, awaiting that item's `text.start`
1592
1797
  // (per-response). `carriedPhase`: item id → the phase that rode its
1593
1798
  // `text.start` — normalizer-lifetime, because the run-item it retires
1594
1799
  // `ext.openai.late-phase` against lands AFTER the response closed.
1595
1800
  const pendingPhase = new Map<string, string>();
1596
1801
  const carriedPhase = new Map<string, string>();
1597
- // PH-2 (draft.4 stage 2): text stream ids whose `text.start` already set the
1802
+ // The first-class phase (draft.4): text stream ids whose `text.start` already set the
1598
1803
  // first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
1599
1804
  // `text.end` fields learned for a round close that is STASHED (deferred until
1600
1805
  // its tool results land) — consumed by `emitRoundClose`.
1601
1806
  const interimAtStart = new Set<string>();
1602
- const stashedEndFields = new Map<string, { phase?: string; providerMetadata?: AgProviderMeta }>();
1807
+ const stashedEndFields = new Map<string, { phase?: string; providerMetadata?: AgProviderMeta; citations?: AgCitation[] }>();
1603
1808
  // O1 (fold/flush option 1): callId → the askId of the `hitl.ask{approval}`
1604
1809
  // emitted for it. A deferred round whose still-pending call has one flushes
1605
1810
  // as `paused` naming that ask (INV-FLUSH (2)).
@@ -1647,17 +1852,20 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1647
1852
  let lastTopLevelTurnId: string | undefined;
1648
1853
  // Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
1649
1854
  let handoffOrdinal = 0;
1855
+ // Per-invoke ordinal for a derived id (INV-BLOCK, SPEC:767) when a native
1856
+ // item carries no id the facet can key on.
1857
+ let derivedOrdinal = 0;
1650
1858
  // Open handoff brackets, keyed by the transfer call's callId (paired turnId
1651
1859
  // + the SAME parentTurnId `subagentStart` used — `subagentDone` must replay
1652
1860
  // it verbatim, mirroring the claude-agent-sdk facet's paired start/done
1653
- // convention). HO-2 (the handoff-drop review, PS-4): matched by callId,
1861
+ // convention). Matched by callId,
1654
1862
  // not FIFO, because agents-core <=0.8.0 opens a bracket for EVERY transfer
1655
1863
  // the model calls but runs only the first: a bracket closes at
1656
1864
  // `handoff_occurred` for its own call, or at that call's `tool_output` (the
1657
1865
  // handoff never ran).
1658
1866
  const openHandoffs: { turnId: string; parentTurnId: string; callId: string }[] = [];
1659
1867
 
1660
- /** HO-2: remove and return the open bracket for `callId`, if any. */
1868
+ /** Remove and return the open bracket for `callId`, if any. */
1661
1869
  function takeOpenHandoff(callId: string): { turnId: string; parentTurnId: string; callId: string } | undefined {
1662
1870
  const i = openHandoffs.findIndex((h) => h.callId === callId);
1663
1871
  if (i === -1) return undefined;
@@ -1675,13 +1883,93 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1675
1883
  // string so argBuffers is primarily for the fallback path.
1676
1884
  const instanceArgBuffers = new Map<string, string>();
1677
1885
 
1678
- // Refusal tracking (T5c — instance state mirroring the old module-level
1679
- // `pendingRefusal`). Set when a `message_output_created` run-item carries a
1680
- // `refusal` content part; the downstream `response.completed` arm then closes
1681
- // the turn with `finishReason:"refusal"`. Cleared on every response close so it
1682
- // never leaks across turns.
1886
+ // Refusal tracking (T5c). Set when a refusal event streams, or when a
1887
+ // `message_output_created` run-item carries a `refusal` content part BEFORE
1888
+ // its response's terminal event (a synthetic order); the terminal arm also
1889
+ // reads the refusal from its own `response.output` (`terminalHasRefusal`),
1890
+ // which is the live order: the run-item lands after the close. Cleared on
1891
+ // every response close and at every `response.created`, so a late run-item's
1892
+ // refusal never reaches the next round.
1683
1893
  let pendingRefusal = false;
1684
1894
 
1895
+ // Refusal text (SPEC §8.0 graceful degradation: a native event the
1896
+ // normalizer can map is never dropped silently). A `refusal` content part's
1897
+ // text is a `text` block in the round's message, id `<item id>:refusal` (the
1898
+ // same item can also carry an `output_text` part, whose block id is the item
1899
+ // id), its `text.start` carrying `providerMetadata.type: "refusal"`, the
1900
+ // part's own wire discriminant and the marker a replay reads to send a
1901
+ // refusal part back, beside the item's `phase` marker as an output_text
1902
+ // block carries it. ONE source per round:
1903
+ // - the raw `response.refusal.delta` / `.done` events, when any arrived;
1904
+ // - else the refusal part itself, from whichever comes first of the
1905
+ // terminal output (read before the round closes) and a
1906
+ // `message_output_created` run-item that lands while the round is open.
1907
+ // A run-item that lands after the close, with no copy emitted, rides
1908
+ // `ext.openai.late-message` (the message is sealed).
1909
+ // The source is chosen per round, not matched per item id: a run-item's ids
1910
+ // can be a different id space from the raw `item_id`s (the OpenRouter
1911
+ // surface mints `msg_tmp_` run-item ids), where an id match would copy the
1912
+ // text twice.
1913
+ // `openRefusalBlocks`: this response's refusal blocks not yet ended;
1914
+ // `refusalBlocks`: every refusal block this response opened (a repeated
1915
+ // `.done` never reopens one); `refusalTextEmitted`: the round has its
1916
+ // refusal text, cleared at `response.created` only, because the run-item
1917
+ // that reads it lands after the round closed. `refusalCarriedPhase`: item id
1918
+ // → the phase marker its refusal block carried (normalizer-lifetime, like
1919
+ // `carriedPhase`, which stays the output_text blocks' own record).
1920
+ const openRefusalBlocks = new Set<string>();
1921
+ const refusalBlocks = new Set<string>();
1922
+ let refusalTextEmitted = false;
1923
+ const refusalCarriedPhase = new Map<string, string>();
1924
+
1925
+ /** The item's vendor phase marker for a refusal block's `text.start`: the one
1926
+ * announced at `output_item.added`, else the one an output_text block of the
1927
+ * same item already carried. */
1928
+ function refusalItemPhase(itemId: string): string | undefined {
1929
+ return pendingPhase.get(itemId) ?? carriedPhase.get(itemId);
1930
+ }
1931
+
1932
+ /** A refusal block id not yet used this response, for the whole-part sources
1933
+ * (an id-less item keys on the message id). */
1934
+ function freshRefusalBlockId(itemId: string | undefined, mId: string): string {
1935
+ const base = `${itemId ?? mId}:refusal`;
1936
+ let id = base;
1937
+ for (let k = 2; refusalBlocks.has(id); k++) id = `${base}:${k}`;
1938
+ return id;
1939
+ }
1940
+
1941
+ /** Open refusal block `blockId` in message `mId`. The phase marker rides
1942
+ * `text.start` as on an output_text block (the first-class `phase:"interim"`
1943
+ * for "commentary"), and is recorded as carried for the late run-item. */
1944
+ function openRefusalBlock(blockId: string, mId: string, phase: string | undefined, itemId: string | undefined): void {
1945
+ const startMeta = openaiProviderMeta({ phase, type: "refusal" });
1946
+ const interim = interimPhase(phase);
1947
+ a.textStart(blockId, mId, {
1948
+ role: "assistant",
1949
+ ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
1950
+ ...(interim !== undefined ? { phase: interim } : {}),
1951
+ });
1952
+ if (phase !== undefined && itemId !== undefined) refusalCarriedPhase.set(itemId, phase);
1953
+ openRefusalBlocks.add(blockId);
1954
+ refusalBlocks.add(blockId);
1955
+ refusalTextEmitted = true;
1956
+ }
1957
+
1958
+ /** A whole refusal part as one block: start, the text as one delta (none for
1959
+ * an empty text), end. */
1960
+ function emitWholeRefusal(blockId: string, mId: string, text: string, phase: string | undefined, itemId: string | undefined): void {
1961
+ openRefusalBlock(blockId, mId, phase, itemId);
1962
+ if (text.length > 0) a.textDelta(blockId, mId, text, { cumulative: false });
1963
+ a.textEnd(blockId, mId);
1964
+ openRefusalBlocks.delete(blockId);
1965
+ }
1966
+
1967
+ /** End every refusal block the stream left open (no `.done` before the close). */
1968
+ function endOpenRefusalBlocks(mId: string): void {
1969
+ for (const blockId of openRefusalBlocks) a.textEnd(blockId, mId);
1970
+ openRefusalBlocks.clear();
1971
+ }
1972
+
1685
1973
  // ── Task 4b: defer a round's close past its pending tool results ───────────
1686
1974
  // (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
1687
1975
  // AFTER `response.completed` — closing at native-close time would put a later
@@ -1700,19 +1988,121 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1700
1988
  * Register `callId` as pending a `tool.done` under the CURRENT open turn
1701
1989
  * (Task 4b). Shared by the raw `response.output_item.added` function_call
1702
1990
  * path and the built-in Shell/Apply-Patch `tool_called` synthesis path
1703
- * (playbook 2026-07-03 SDK-bump adaptation, Finding #1) — both start a call
1991
+ * (the 2026-07-03 SDK-bump adaptation) — both start a call
1704
1992
  * whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
1705
1993
  * is open (defensive; every caller already calls `ensureResponseOpen()` first).
1706
1994
  */
1707
1995
  function registerPendingTool(callId: string): void {
1708
- if (turnId === undefined) return;
1709
- let pending = pendingToolsByTurn.get(turnId);
1996
+ registerPendingToolFor(turnId, callId);
1997
+ }
1998
+
1999
+ /** Register `callId` as pending a `tool.done` under round `tid`. */
2000
+ function registerPendingToolFor(tid: string | undefined, callId: string): void {
2001
+ if (tid === undefined) return;
2002
+ let pending = pendingToolsByTurn.get(tid);
1710
2003
  if (pending === undefined) {
1711
2004
  pending = new Set<string>();
1712
- pendingToolsByTurn.set(turnId, pending);
2005
+ pendingToolsByTurn.set(tid, pending);
1713
2006
  }
1714
2007
  pending.add(callId);
1715
- turnIdByToolCallId.set(callId, turnId);
2008
+ turnIdByToolCallId.set(callId, tid);
2009
+ }
2010
+
2011
+ // ── Built-in round attach ───────────────────────────────────────────────────
2012
+ // agents-core streams a response's built-in call run-items (`tool_called`,
2013
+ // `tool_search_called`) after its `response.completed`, so the round has
2014
+ // already reached its terminal when they land. A round whose terminal
2015
+ // `response.output` lists a built-in call (see BUILTIN_OUTPUT_ITEM_TYPES)
2016
+ // defers its close as §8.0 item 14 defers a round for its pending tool
2017
+ // results, and each late run-item attaches to THAT round's turn and message
2018
+ // (never a turn opened for it). The close is released:
2019
+ // - when every listed call has its run-item and every pending result has
2020
+ // landed (`maybeReleaseRound`);
2021
+ // - at the next `response.created`, when the round still waits only on
2022
+ // listed calls whose run-item never streamed (agents-core can suppress
2023
+ // one), so the new response keeps its own turn; those calls stop being
2024
+ // the round's;
2025
+ // - at flush, per INV-FLUSH (2).
2026
+ // A listed `mcp_approval_request` becomes a pending call of its round when
2027
+ // its `tool_called` lands, and its answer (`mcp_approval_response`) closes
2028
+ // it; with no answer, the round flushes paused naming its ask (INV-FLUSH
2029
+ // (2)). `listedBuiltinsByTurn`: round → listed item ids still waiting.
2030
+ // `builtinTurnByItemId`: listed item id → its round.
2031
+ // `seenBuiltinItemIds`: built-in items whose run-item already landed (one
2032
+ // that lands before its terminal, a synthetic order), so the terminal never
2033
+ // lists them.
2034
+ const listedBuiltinsByTurn = new Map<string, Set<string>>();
2035
+ const builtinTurnByItemId = new Map<string, string>();
2036
+ const seenBuiltinItemIds = new Set<string>();
2037
+ // Approval requests an `mcp_approval_response` has closed in this invoke.
2038
+ const answeredRequests = new Set<string>();
2039
+
2040
+ /** List round `tid`'s built-in calls (those whose run-item has not landed). */
2041
+ /** List round `tid`'s built-in calls whose run-item has not landed. When
2042
+ * it lists any, the round's `message` items are listed too, so their
2043
+ * `message_output_created` (and the citations it carries) lands while the
2044
+ * round's close is still deferred. */
2045
+ function listBuiltins(tid: string, items: readonly TerminalBuiltinItem[], messageIds: readonly string[]): string[] {
2046
+ const ids: string[] = [];
2047
+ for (const item of items) {
2048
+ if (seenBuiltinItemIds.has(item.id)) continue;
2049
+ ids.push(item.id);
2050
+ builtinTurnByItemId.set(item.id, tid);
2051
+ }
2052
+ if (ids.length === 0) return ids;
2053
+ for (const id of messageIds) {
2054
+ if (seenBuiltinItemIds.has(id)) continue;
2055
+ ids.push(id);
2056
+ builtinTurnByItemId.set(id, tid);
2057
+ }
2058
+ listedBuiltinsByTurn.set(tid, new Set(ids));
2059
+ return ids;
2060
+ }
2061
+
2062
+ /** The stashed round a late built-in run-item belongs to: the round whose
2063
+ * terminal listed `key`, else, when no response is open, the invoke's last
2064
+ * round if its close is still stashed (a run-item its terminal did not
2065
+ * list). Undefined when neither holds. */
2066
+ function lateBuiltinRound(key: string | undefined): { tid: string; mId: string } | undefined {
2067
+ const listedTid = key !== undefined ? builtinTurnByItemId.get(key) : undefined;
2068
+ const tid = listedTid ?? (turnId === undefined ? lastTopLevelTurnId : undefined);
2069
+ if (tid === undefined) return undefined;
2070
+ const stashed = stashedCloseByTurn.get(tid);
2071
+ return stashed !== undefined ? { tid, mId: stashed.msgId } : undefined;
2072
+ }
2073
+
2074
+ /** The listed item `key` has what it waited for: drop it, and release its
2075
+ * round if nothing else keeps the round open. */
2076
+ function drainListedBuiltin(key: string | undefined): void {
2077
+ if (key === undefined) return;
2078
+ const tid = builtinTurnByItemId.get(key);
2079
+ if (tid === undefined) return;
2080
+ const listed = listedBuiltinsByTurn.get(tid);
2081
+ if (listed === undefined || !listed.delete(key)) return;
2082
+ maybeReleaseRound(tid);
2083
+ }
2084
+
2085
+ /** Release round `tid`'s stashed close when no pending result and no listed
2086
+ * built-in call keeps it open. */
2087
+ function maybeReleaseRound(tid: string): void {
2088
+ const stashed = stashedCloseByTurn.get(tid);
2089
+ if (stashed === undefined) return;
2090
+ if ((pendingToolsByTurn.get(tid)?.size ?? 0) > 0) return;
2091
+ if ((listedBuiltinsByTurn.get(tid)?.size ?? 0) > 0) return;
2092
+ stashedCloseByTurn.delete(tid);
2093
+ listedBuiltinsByTurn.delete(tid);
2094
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
2095
+ }
2096
+
2097
+ /** At a new `response.created`: every round still waiting on listed calls
2098
+ * whose run-item never streamed stops waiting on them, and is released if
2099
+ * no pending result keeps it open. */
2100
+ function releaseListedAtNextResponse(): void {
2101
+ for (const [tid, listed] of [...listedBuiltinsByTurn]) {
2102
+ listed.clear();
2103
+ listedBuiltinsByTurn.delete(tid);
2104
+ maybeReleaseRound(tid);
2105
+ }
1716
2106
  }
1717
2107
  // A round's close is MORE than `closeTurnDone`: `reduce()`'s message.end
1718
2108
  // handler (SPEC §5.0 INV-MSG, same enforcement commit) clears the message's
@@ -1741,7 +2131,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1741
2131
  * whichever values are live right now (immediate path) or were captured at
1742
2132
  * defer time (drain path) — same three calls either way.
1743
2133
  */
1744
- /** PH-2: is `streamId`'s text.end still pending in a STASHED round close
2134
+ /** Is `streamId`'s text.end still pending in a STASHED round close
1745
2135
  * (a deferred tool round), i.e. not yet emitted? */
1746
2136
  function isStashedTextStream(streamId: string): boolean {
1747
2137
  for (const stashed of stashedCloseByTurn.values()) {
@@ -1752,10 +2142,21 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1752
2142
 
1753
2143
  function endStashedTextStreams(mId: string, textStreamIds: readonly string[]): void {
1754
2144
  for (const streamId of textStreamIds) {
1755
- // PH-2: a phase learned while this close sat stashed rides its text.end.
1756
- const endFields = stashedEndFields.get(streamId);
2145
+ // Citations and a phase learned while this close sat stashed ride its
2146
+ // text.end, in the live path's field order.
2147
+ const f = stashedEndFields.get(streamId);
1757
2148
  stashedEndFields.delete(streamId);
1758
- a.textEnd(streamId, mId, endFields);
2149
+ a.textEnd(
2150
+ streamId,
2151
+ mId,
2152
+ f === undefined
2153
+ ? undefined
2154
+ : {
2155
+ ...(f.citations !== undefined ? { citations: f.citations } : {}),
2156
+ ...(f.providerMetadata !== undefined ? { providerMetadata: f.providerMetadata } : {}),
2157
+ ...(f.phase !== undefined ? { phase: f.phase } : {}),
2158
+ },
2159
+ );
1759
2160
  }
1760
2161
  }
1761
2162
 
@@ -1802,6 +2203,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1802
2203
  function releaseAllDeferredCloses(): void {
1803
2204
  for (const [tid, stashed] of stashedCloseByTurn) releaseDeferredClose(tid, stashed);
1804
2205
  stashedCloseByTurn.clear();
2206
+ listedBuiltinsByTurn.clear();
1805
2207
  }
1806
2208
 
1807
2209
  /**
@@ -1812,9 +2214,16 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1812
2214
  * immediately via `endOpenStreamsAndCloseMessage` — an errored round's
1813
2215
  * pending results are moot, by design).
1814
2216
  */
1815
- function finishOrDeferRound(tid: string, mId: string, textStreamIds: readonly string[], fields: TurnDoneFields): void {
2217
+ function finishOrDeferRound(
2218
+ tid: string,
2219
+ mId: string,
2220
+ textStreamIds: readonly string[],
2221
+ fields: TurnDoneFields,
2222
+ listing: { builtins: readonly TerminalBuiltinItem[]; messageIds: readonly string[] } = { builtins: [], messageIds: [] },
2223
+ ): void {
2224
+ const listed = listBuiltins(tid, listing.builtins, listing.messageIds);
1816
2225
  const pending = pendingToolsByTurn.get(tid);
1817
- if (pending !== undefined && pending.size > 0) {
2226
+ if ((pending !== undefined && pending.size > 0) || listed.length > 0) {
1818
2227
  stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
1819
2228
  return;
1820
2229
  }
@@ -1827,7 +2236,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1827
2236
  * somehow absent (defensive — the spike confirms the id is always present at start).
1828
2237
  * Returns the close-once key (the real response.id, else the synthesized turnId),
1829
2238
  * or `undefined` when the response has already been closed (caller must no-op).
1830
- * `model` (OA-12) rides `message.start.model` — only the authoritative
2239
+ * `model` (the per-message model) rides `message.start.model` — only the authoritative
1831
2240
  * `response.created` open passes it; a defensive open never invents one.
1832
2241
  */
1833
2242
  function ensureResponseOpen(respId?: string, model?: string): string | undefined {
@@ -1878,7 +2287,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1878
2287
  a.openTurn(opened, threadId);
1879
2288
  return { turnId: opened, messageId: `${callId}:result` };
1880
2289
  }
1881
- // Approve-all (the D3 pin, 2026-09-24): the resuming invoke can
2290
+ // Approve-all (pinned 2026-09-24): the resuming invoke can
1882
2291
  // replay SEVERAL results before its response. While the resume turn is
1883
2292
  // open with no assistant message yet (turnId set, msgId unset — a state
1884
2293
  // only this helper creates), each further result joins THAT turn as its
@@ -1915,11 +2324,13 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1915
2324
  const key = responseId ?? turnId;
1916
2325
  if (key !== undefined) closedResponses.add(key);
1917
2326
  openTextStreams.clear();
1918
- // OA-11: an rs_ block opened but never filled (e.g. `response.failed`) stays
2327
+ // An rs_ block opened but never filled (e.g. `response.failed`) stays
1919
2328
  // as the spec's own unsealed-block outcome (INV-FLUSH (3)); forget it so a
1920
2329
  // late run-item for it takes the existing `late-reasoning` degrade.
1921
2330
  openReasoning.clear();
1922
2331
  pendingPhase.clear();
2332
+ openRefusalBlocks.clear();
2333
+ refusalBlocks.clear();
1923
2334
  turnId = undefined;
1924
2335
  msgId = undefined;
1925
2336
  responseId = undefined;
@@ -1934,6 +2345,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1934
2345
  function closeResponse(): void {
1935
2346
  if (msgId !== undefined) {
1936
2347
  for (const streamId of openTextStreams) a.textEnd(streamId, msgId);
2348
+ endOpenRefusalBlocks(msgId);
1937
2349
  a.closeMessage(msgId);
1938
2350
  }
1939
2351
  resetResponseState();
@@ -1943,8 +2355,16 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1943
2355
  function driveRawResponsesEvent(ev: OpenAIRawResponsesEvent): void {
1944
2356
  switch (ev.type) {
1945
2357
  case "response.created": {
2358
+ // A new response: a refusal recorded by a late run-item belongs to the
2359
+ // response before it, never to this one; so does its refusal text.
2360
+ pendingRefusal = false;
2361
+ refusalTextEmitted = false;
2362
+ // A round still waiting only on listed built-in calls whose run-item
2363
+ // never streamed is released before this response's turn opens (see
2364
+ // "Built-in round attach").
2365
+ releaseListedAtNextResponse();
1946
2366
  // Authoritative turn open — the real response.id is present at start.
1947
- // OA-12: so is the resolved model id (JsonValue boundary: string-guarded).
2367
+ // So is the resolved model id (JsonValue boundary: string-guarded).
1948
2368
  const rawModelId: unknown = ev.response.model;
1949
2369
  ensureResponseOpen(
1950
2370
  ev.response.id,
@@ -1957,11 +2377,11 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1957
2377
  if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
1958
2378
  if (!openTextStreams.has(ev.item_id)) {
1959
2379
  openTextStreams.add(ev.item_id);
1960
- // OA-14: the phase announced at output_item.added rides text.start
2380
+ // The phase announced at output_item.added rides text.start
1961
2381
  // (R&D items 13+17, stage 1, ruled 2026-09-23; vercel parity c4f5981).
1962
2382
  const phase = pendingPhase.get(ev.item_id);
1963
2383
  const startMeta = openaiProviderMeta({ phase });
1964
- // PH-2 (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
2384
+ // The first-class phase (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
1965
2385
  // the first delta ⇒ the first-class `phase` goes on text.start.
1966
2386
  const interim = interimPhase(phase);
1967
2387
  a.textStart(ev.item_id, msgId, {
@@ -1980,7 +2400,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1980
2400
  return;
1981
2401
  }
1982
2402
  case "response.output_text.done": {
1983
- // NO-OP (audit M22): the citations carrier — `message_output_created` — is
2403
+ // NO-OP: the citations carrier — `message_output_created` — is
1984
2404
  // the authoritative text-end source (it also reports refusal parts and
1985
2405
  // arrives with the annotated part, so closing here would emit `text.end`
1986
2406
  // BEFORE citations are known). The stream stays in `openTextStreams`;
@@ -1989,8 +2409,34 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1989
2409
  // `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
1990
2410
  return;
1991
2411
  }
2412
+ case "response.refusal.delta": {
2413
+ // Refusal text streams like output_text (see "Refusal text"): the raw
2414
+ // refusal events are this round's source once any arrives.
2415
+ ensureResponseOpen();
2416
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
2417
+ pendingRefusal = true;
2418
+ const blockId = `${ev.item_id}:refusal`;
2419
+ if (!refusalBlocks.has(blockId)) openRefusalBlock(blockId, msgId, refusalItemPhase(ev.item_id), ev.item_id);
2420
+ a.textDelta(blockId, msgId, ev.delta, { cumulative: false });
2421
+ return;
2422
+ }
2423
+ case "response.refusal.done": {
2424
+ // Ends the part's block. With no delta before it, its `refusal` is the
2425
+ // whole text. A refusal part carries no annotations, so unlike
2426
+ // `response.output_text.done` nothing arrives later for its `text.end`.
2427
+ ensureResponseOpen();
2428
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
2429
+ pendingRefusal = true;
2430
+ const blockId = `${ev.item_id}:refusal`;
2431
+ if (!refusalBlocks.has(blockId)) {
2432
+ emitWholeRefusal(blockId, msgId, ev.refusal, refusalItemPhase(ev.item_id), ev.item_id);
2433
+ return;
2434
+ }
2435
+ if (openRefusalBlocks.delete(blockId)) a.textEnd(blockId, msgId);
2436
+ return;
2437
+ }
1992
2438
  case "response.output_item.added": {
1993
- // OA-11: a reasoning item OPENS its block here — id only, the added event
2439
+ // A reasoning item OPENS its block here — id only, the added event
1994
2440
  // carries no replayable content — so the block takes its wire position
1995
2441
  // ahead of the `fc_` it precedes (§5 block insertion order, SPEC:763;
1996
2442
  // §10 item 4's stateless loop replays `rs_` before its `fc_`). It is
@@ -2002,7 +2448,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2002
2448
  if (typeof rsId === "string") openReasoningBlock(rsId);
2003
2449
  return;
2004
2450
  }
2005
- // OA-14: a message item announces its `phase` here, BEFORE its first
2451
+ // A message item announces its `phase` here, BEFORE its first
2006
2452
  // text delta — record it for that item's `text.start`. Record only: no
2007
2453
  // response open, no emit, so an absent/null/non-string/empty phase is
2008
2454
  // byte-identical to a stream without this event.
@@ -2103,11 +2549,22 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2103
2549
  if (ensureResponseOpen(ev.response.id) === undefined) return;
2104
2550
  if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
2105
2551
  if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
2106
- // OA-11: fill every reasoning block from THIS output (the replayable blob)
2552
+ // Fill every reasoning block from THIS output (the replayable blob)
2107
2553
  // FIRST — before any branch below can emit message.end / turn.* (INV-MSG:
2108
2554
  // a reasoning.* event must never target a sealed message; core's reduce()
2109
2555
  // does not check that for reasoning.*, so the order is this facet's job).
2110
2556
  fillReasoningFromTerminalOutput(ev.response.output);
2557
+ // Refusal text (see "Refusal text"): with no refusal event in this
2558
+ // round, the terminal output's refusal parts are its source, emitted
2559
+ // now while the message is open (the run-item lands after the close).
2560
+ // Then any refusal block the stream left open ends here, before every
2561
+ // branch below closes the message.
2562
+ if (!refusalTextEmitted) {
2563
+ for (const part of terminalRefusalParts(ev.response.output)) {
2564
+ emitWholeRefusal(freshRefusalBlockId(part.itemId, msgId), msgId, part.text, part.phase, part.itemId);
2565
+ }
2566
+ }
2567
+ endOpenRefusalBlocks(msgId);
2111
2568
  // Snapshot before any deferral: `resetResponseState()` below always
2112
2569
  // clears these, but a deferred close needs them later (Task 4b).
2113
2570
  const currentTurnId = turnId;
@@ -2115,6 +2572,10 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2115
2572
  const textStreamIds = Array.from(openTextStreams);
2116
2573
  const reason = ev.response.incomplete_details?.reason;
2117
2574
  const usage = mapUsage(ev.response.usage);
2575
+ // The built-in calls (and, with them, the messages) this response
2576
+ // lists, whose run-items land after this event (see "Built-in round
2577
+ // attach").
2578
+ const listing = { builtins: terminalBuiltinItems(ev.response.output), messageIds: terminalMessageIds(ev.response.output) };
2118
2579
  // `status` is OPTIONAL upstream and its enum is OPEN ("clients must
2119
2580
  // accept additional values"), so it is read through `unknown` + a typeof
2120
2581
  // guard rather than trusted through the declared union — this is the
@@ -2126,7 +2587,8 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2126
2587
  const unsuccessfulStatus =
2127
2588
  typeof rawStatus === "string" && UNSUCCESSFUL_RESPONSE_STATUSES.has(rawStatus) ? rawStatus : undefined;
2128
2589
  // Decision tree (mirrors the canonical model, A1):
2129
- // refusal recorded → closeTurnDone success, finishReason:"refusal"
2590
+ // refusal (in the terminal
2591
+ // output, or recorded) → closeTurnDone success, finishReason:"refusal"
2130
2592
  // content_filter → closeTurnDone error-outcome + safety signal
2131
2593
  // any other incomplete → closeTurnError{code:reason, usage}
2132
2594
  // completed, status failed/
@@ -2137,12 +2599,12 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2137
2599
  // ENTIRE close (message + turn) instead of emitting (INV-MSG).
2138
2600
  // closeTurnError does NOT defer (an errored round's pending results are
2139
2601
  // moot, by design) — it still closes the message immediately here.
2140
- if (pendingRefusal) {
2602
+ if (pendingRefusal || terminalHasRefusal(ev.response.output)) {
2141
2603
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
2142
2604
  outcome: { type: "success" },
2143
2605
  finishReason: "refusal",
2144
2606
  ...(usage !== undefined ? { usage } : {}),
2145
- });
2607
+ }, listing);
2146
2608
  } else if (reason === "content_filter") {
2147
2609
  const safety: AgSafety[] = [{ category: "content_filter", blocked: true }];
2148
2610
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
@@ -2150,7 +2612,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2150
2612
  ...finishReasonFields(reason),
2151
2613
  safety,
2152
2614
  ...(usage !== undefined ? { usage } : {}),
2153
- });
2615
+ }, listing);
2154
2616
  } else if (ev.type === "response.incomplete") {
2155
2617
  endOpenStreamsAndCloseMessage();
2156
2618
  a.closeTurnError(currentTurnId, {
@@ -2193,10 +2655,10 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2193
2655
  } else {
2194
2656
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
2195
2657
  outcome: { type: "success" },
2196
- // OA-15: an unmapped native reason also carries finishReasonRaw.
2658
+ // An unmapped native reason also carries finishReasonRaw.
2197
2659
  ...finishReasonFields(reason),
2198
2660
  ...(usage !== undefined ? { usage } : {}),
2199
- });
2661
+ }, listing);
2200
2662
  }
2201
2663
  resetResponseState();
2202
2664
  return;
@@ -2214,7 +2676,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2214
2676
  // message/code/usage (§4), so per §8.0 item 33 it rides verbatim in a
2215
2677
  // carrier the §5 table folds, never as remedy data on the terminal: an
2216
2678
  // adapter NOTICE message immediately BEFORE the closing turn.error, in
2217
- // this turn (rd-15):
2679
+ // this turn (remedy-shaped vendor data):
2218
2680
  // message.start {role:"notice", noticeSource:"adapter"} →
2219
2681
  // one text block, text = `detailed_explanation` verbatim (else
2220
2682
  // error.message), text.start `_meta["openai/misalignment"]` = the
@@ -2270,7 +2732,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2270
2732
  return;
2271
2733
  }
2272
2734
  // Duplicate raw families IGNORED per the canonical model:
2273
- // response.output_text.done is its own no-op arm above (audit M22);
2735
+ // response.output_text.done is its own no-op arm above;
2274
2736
  // response.output_item.done, response.in_progress, content_part.* are not
2275
2737
  // authoritative sources.
2276
2738
  default:
@@ -2278,27 +2740,70 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2278
2740
  }
2279
2741
  }
2280
2742
 
2743
+ /**
2744
+ * A `message_output_created` run-item's refusal part (see "Refusal text").
2745
+ * - The round already has its refusal text (the raw events or the terminal
2746
+ * output): no second copy. The item's phase marker, if that block did
2747
+ * not carry it, rides `ext.openai.late-phase` (the block's `text.end` is
2748
+ * out: case (iii) of the output_text arm), once per item: an item that
2749
+ * also carries an output_text part leaves it to that part's arm.
2750
+ * - The round is open (a synthetic order): the part is the source.
2751
+ * - The round closed with no copy: the message is sealed, so the text rides
2752
+ * `ext.openai.late-message` with `partType: "refusal"`, anchored to the
2753
+ * round like the id-less late message.
2754
+ */
2755
+ function driveRunItemRefusal(item: OpenAIAssistantMessageItem, text: string): void {
2756
+ const itemPhase = vendorPhase(item.phase);
2757
+ if (refusalTextEmitted) {
2758
+ if (
2759
+ item.id !== undefined &&
2760
+ itemPhase !== undefined &&
2761
+ refusalCarriedPhase.get(item.id) !== itemPhase &&
2762
+ !item.content.some((p) => p.type === "output_text")
2763
+ ) {
2764
+ a.emitExt("openai", "late-phase", { itemId: item.id, phase: itemPhase });
2765
+ }
2766
+ return;
2767
+ }
2768
+ if (msgId !== undefined) {
2769
+ emitWholeRefusal(freshRefusalBlockId(item.id, msgId), msgId, text, itemPhase, item.id);
2770
+ return;
2771
+ }
2772
+ const anchor = turnId ?? lastTopLevelTurnId;
2773
+ a.emitExt("openai", "late-message", {
2774
+ text,
2775
+ partType: "refusal",
2776
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
2777
+ ...(anchor !== undefined ? { forTurnId: anchor } : {}),
2778
+ ...(itemPhase !== undefined ? { phase: itemPhase } : {}),
2779
+ });
2780
+ }
2781
+
2281
2782
  /** End any still-open text streams (defensive), then close the open message. */
2282
2783
  function endOpenStreamsAndCloseMessage(): void {
2283
2784
  if (msgId !== undefined) {
2284
2785
  for (const streamId of openTextStreams) a.textEnd(streamId, msgId);
2786
+ endOpenRefusalBlocks(msgId);
2285
2787
  a.closeMessage(msgId);
2286
2788
  }
2287
2789
  }
2288
2790
 
2289
2791
  /**
2290
2792
  * Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
2291
- * citations source (audit M22). The text itself already streamed from the raw
2793
+ * citations source. The text itself already streamed from the raw
2292
2794
  * `response.output_text.delta` path — this MUST NOT re-emit it — but the
2293
2795
  * `output_text` part's annotations are only known here (they are not present on
2294
2796
  * `response.output_text.done`), so THIS is where the matching open text stream
2295
2797
  * actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
2296
2798
  * directly to the streamed block (never a duplicate id-less supplement). A
2297
- * `refusal` part sets `pendingRefusal` so the downstream `response.completed`
2298
- * arm closes with `finishReason:"refusal"` (no text stream to close for it).
2799
+ * `refusal` part sets `pendingRefusal`, which counts only when the run-item
2800
+ * lands before its response's terminal event (a synthetic order). On the
2801
+ * live wire it lands after the close, and the terminal arm reads the round's
2802
+ * refusal from its own `response.output` (`terminalHasRefusal`). Its text is
2803
+ * a single-source fallback (`driveRunItemRefusal`, see "Refusal text").
2299
2804
  *
2300
- * Correlation (OA-14 — id FIRST, FIFO fallback; protocol package rd-13-17
2301
- * §2 stage 1): on the direct OpenAI wire the raw delta's `item_id` and the
2805
+ * Correlation (id FIRST, FIFO fallback; the narration-phase rule, stage
2806
+ * 1): on the direct OpenAI wire the raw delta's `item_id` and the
2302
2807
  * run-item's `rawItem.id` are the SAME id (all 8 openai corpus seeds), so the
2303
2808
  * stream is matched by id — a completion can no longer land on an earlier
2304
2809
  * part's stream when two are open. Only when the id is unknown to
@@ -2316,7 +2821,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2316
2821
  * annotations, though, they are NOT yet lost anywhere else — silently dropping
2317
2822
  * them here would violate Tenet 6. Route them losslessly through the facet's
2318
2823
  * existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
2319
- * the run-item id + the raw annotations array verbatim (review finding on M22).
2824
+ * the run-item id + the raw annotations array verbatim.
2320
2825
  * A part with no annotations has nothing to lose — the plain `continue` stays.
2321
2826
  *
2322
2827
  * ID-LESS SYNTHESIZED MESSAGE (agents-core ≥0.13.2): `errorHandlers.
@@ -2345,9 +2850,22 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2345
2850
  * never a duplicated or corrupted core stream.
2346
2851
  */
2347
2852
  function driveMessageOutputCreated(item: OpenAIAssistantMessageItem): void {
2853
+ if (item.id !== undefined) seenBuiltinItemIds.add(item.id);
2854
+ driveMessageParts(item);
2855
+ // A listed message has landed; its round may now close (see "Built-in
2856
+ // round attach"), with any citations stashed above on its text.end.
2857
+ drainListedBuiltin(item.id);
2858
+ }
2859
+
2860
+ /** The per-part body of {@link driveMessageOutputCreated} (see its doc). */
2861
+ function driveMessageParts(item: OpenAIAssistantMessageItem): void {
2348
2862
  for (const part of item.content) {
2349
2863
  if (part.type === "refusal") {
2350
2864
  pendingRefusal = true;
2865
+ // The typeof guard is load-bearing: rawItem is envelope-only-validated
2866
+ // wire data, and push() must never throw.
2867
+ const text: unknown = part.refusal;
2868
+ if (typeof text === "string") driveRunItemRefusal(item, text);
2351
2869
  continue;
2352
2870
  }
2353
2871
  if (part.type === "output_text") {
@@ -2368,20 +2886,34 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2368
2886
  ...(item.phase !== undefined ? { phase: item.phase } : {}),
2369
2887
  });
2370
2888
  }
2371
- if (part.annotations !== undefined && part.annotations.length > 0) {
2889
+ const idlessAnnotations = partAnnotations(part);
2890
+ if (idlessAnnotations.length > 0) {
2372
2891
  a.emitExt("openai", "late-citations", {
2373
- annotations: JsonValue.parse(part.annotations),
2892
+ annotations: idlessAnnotations,
2374
2893
  });
2375
2894
  }
2376
2895
  continue;
2377
2896
  }
2378
2897
  if (msgId === undefined) {
2379
- // response already closed — see doc above.
2380
- if (part.annotations !== undefined && part.annotations.length > 0) {
2381
- a.emitExt("openai", "late-citations", {
2382
- itemId: item.id,
2383
- annotations: JsonValue.parse(part.annotations),
2384
- });
2898
+ // response already closed — see doc above. While the round's close
2899
+ // is STASHED (deferred for its tool results or built-in calls), this
2900
+ // block's text.end is not out yet, so its url citations ride it (the
2901
+ // phase marker's case (ii) below), and any other annotation takes
2902
+ // the ext carry; a message that lands after the close was released
2903
+ // carries every annotation on the ext.
2904
+ const closedAnnotations = partAnnotations(part);
2905
+ if (closedAnnotations.length > 0) {
2906
+ const split = isStashedTextStream(item.id) ? splitAnnotations(closedAnnotations, part.text) : undefined;
2907
+ if (split?.citations !== undefined) {
2908
+ stashedEndFields.set(item.id, { ...stashedEndFields.get(item.id), citations: split.citations });
2909
+ }
2910
+ const carry = split?.citations !== undefined ? split.unmapped : closedAnnotations;
2911
+ if (carry.length > 0) {
2912
+ a.emitExt("openai", "late-citations", {
2913
+ itemId: item.id,
2914
+ annotations: carry,
2915
+ });
2916
+ }
2385
2917
  }
2386
2918
  // phase (0.14.0): the live wire delivers the FINAL round's
2387
2919
  // message_output_created AFTER response_done has closed the message
@@ -2390,21 +2922,22 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2390
2922
  // (deferred-close) messages ever reach it. Same post-close degrade
2391
2923
  // convention as late-citations: a dedicated itemId-keyed vendor
2392
2924
  // carry, one per phase-bearing part.
2393
- // OA-14: RETIRED when this id's SAME phase already rode its text.start
2925
+ // RETIRED when this id's SAME phase already rode its text.start
2394
2926
  // (the live case); kept — lossless — when only the run-item knows it,
2395
2927
  // or knows a different value.
2396
- // PH-2: null/"" is no marker at all (spec ruling (a)) — neither
2928
+ // A null/"" phase is no marker at all (spec ruling (a)) — neither
2397
2929
  // a carry nor a late-phase ext.
2398
2930
  const lateItemPhase = vendorPhase(item.phase);
2399
2931
  if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
2400
2932
  if (isStashedTextStream(item.id)) {
2401
- // PH-2 case (ii): the round close is STASHED (a deferred tool
2933
+ // Case (ii): the round close is STASHED (a deferred tool
2402
2934
  // round), so this block's text.end is NOT yet emitted — the §5
2403
2935
  // timing rule makes the end the phase's home (ruled
2404
2936
  // 2026-09-23). The marker has a first-class home, so no late-phase.
2405
2937
  const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
2406
2938
  const endMeta = openaiProviderMeta({ phase: lateItemPhase });
2407
2939
  stashedEndFields.set(item.id, {
2940
+ ...stashedEndFields.get(item.id),
2408
2941
  ...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
2409
2942
  ...(interim !== undefined ? { phase: interim } : {}),
2410
2943
  });
@@ -2416,12 +2949,15 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2416
2949
  }
2417
2950
  continue;
2418
2951
  }
2419
- // OA-14: id first, FIFO fallback — see "Correlation" in the doc above.
2952
+ // Id first, FIFO fallback — see "Correlation" in the doc above.
2420
2953
  const streamId =
2421
2954
  item.id !== undefined && openTextStreams.has(item.id) ? item.id : openTextStreams.values().next().value;
2422
2955
  if (streamId === undefined) continue; // defensive: no matching open stream
2423
2956
  openTextStreams.delete(streamId);
2424
- const citations = mapAnnotationsToCitations(part.annotations, part.text);
2957
+ // A url citation rides text.end; any other annotation has no citation
2958
+ // target and takes the ext carry, after the text.end (SPEC:965).
2959
+ const liveSplit = splitAnnotations(partAnnotations(part), part.text);
2960
+ const citations = liveSplit.citations;
2425
2961
  // phase (0.14.0) rides the matching text.end's providerMetadata —
2426
2962
  // PER-PART, not message.metadata: this facet folds a response into ONE
2427
2963
  // message, and a program-driven turn emits multiple message items with
@@ -2429,7 +2965,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2429
2965
  // merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
2430
2966
  const itemPhase = vendorPhase(item.phase);
2431
2967
  const phaseMeta = openaiProviderMeta({ phase: itemPhase });
2432
- // PH-2 case (i): known before this block's text.end ⇒ the end carries
2968
+ // Case (i): known before this block's text.end ⇒ the end carries
2433
2969
  // the first-class phase, unless text.start already did.
2434
2970
  const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
2435
2971
  a.textEnd(
@@ -2443,12 +2979,15 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2443
2979
  }
2444
2980
  : undefined,
2445
2981
  );
2982
+ if (liveSplit.unmapped.length > 0) {
2983
+ a.emitExt("openai", "late-citations", { itemId: item.id ?? streamId, annotations: liveSplit.unmapped });
2984
+ }
2446
2985
  }
2447
2986
  }
2448
2987
  }
2449
2988
 
2450
2989
  /**
2451
- * OA-11: open the reasoning block for `rsId` in the current message — once per
2990
+ * Open the reasoning block for `rsId` in the current message — once per
2452
2991
  * id (a re-announce, or an id already filled, is a no-op). `id` and `itemId`
2453
2992
  * are both the `rs_` id (the run-item path's convention). Called from
2454
2993
  * `output_item.added{reasoning}` so the block takes its WIRE position, and
@@ -2462,7 +3001,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2462
3001
  }
2463
3002
 
2464
3003
  /**
2465
- * OA-11: fill + seal an OPEN reasoning block: one `reasoning.delta` per
3004
+ * Fill + seal an OPEN reasoning block: one `reasoning.delta` per
2466
3005
  * non-empty summary part (`partIndex` = the wire `summary_index`), then
2467
3006
  * `reasoning.opaque` (the replayable ciphertext, `itemId` = rs_) BEFORE
2468
3007
  * `reasoning.end`, so "sealed" means complete (the spec's recommendation;
@@ -2498,7 +3037,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2498
3037
  filledReasoning.add(rsId);
2499
3038
  }
2500
3039
 
2501
- /** OA-11: fill every reasoning block from a terminal event's `response.output`
3040
+ /** Fill every reasoning block from a terminal event's `response.output`
2502
3041
  * (see `terminalReasoningItems` for why this, not `output_item.done`, is the
2503
3042
  * source). An item never announced by `output_item.added` opens here
2504
3043
  * (defensive — position is then the terminal event's). */
@@ -2511,14 +3050,14 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2511
3050
  }
2512
3051
 
2513
3052
  /**
2514
- * Map a `reasoning_item_created` run-item (Task 3, audit M48). Since OA-11 it
3053
+ * Map a `reasoning_item_created` run-item. Since reasoning is sourced from the terminal output it
2515
3054
  * is the FALLBACK source: on the live wire it lands after `response.completed`,
2516
3055
  * whose output already filled the block, so a run-item whose `rs_` id is in
2517
3056
  * `filledReasoning` is a no-op (single source per id — no duplicate block, no
2518
3057
  * `late-reasoning` ext). If raw `output_item.added` opened the block but no
2519
3058
  * terminal output has filled it yet, the run-item fills that block in place.
2520
3059
  * Only with NO raw reasoning events for the id (run-item-only streams) does the
2521
- * pre-OA-11 mapping below still run, unchanged:
3060
+ * run-item-only mapping below still run, unchanged:
2522
3061
  *
2523
3062
  * The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
2524
3063
  * the incremental text/tool-arg deltas elsewhere in this facet), so
@@ -2552,14 +3091,14 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2552
3091
  * never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
2553
3092
  * correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
2554
3093
  * is exactly the kind of payload Tenet 6 exists for — silently dropping it here
2555
- * was a genuine loss (review finding on M48). Mirrors `ext.openai.late-citations`
2556
- * (M22) exactly: route it through the lossless vendor channel instead of the bare
3094
+ * was a genuine loss. Mirrors `ext.openai.late-citations` exactly: route it
3095
+ * through the lossless vendor channel instead of the bare
2557
3096
  * return.
2558
3097
  */
2559
3098
  function driveReasoningItemCreated(item: OpenAIReasoningItem): void {
2560
- // OA-11 dedupe: already filled from the terminal output (or an earlier run-item).
3099
+ // Dedupe: already filled from the terminal output (or an earlier run-item).
2561
3100
  if (item.id !== undefined && filledReasoning.has(item.id)) return;
2562
- // OA-11: raw `output_item.added` opened this block; no terminal output has
3101
+ // Raw `output_item.added` opened this block; no terminal output has
2563
3102
  // filled it yet (synthetic ordering) — fill it in place from the run-item,
2564
3103
  // whose `content[]` IS the raw `summary[]` (one part per index).
2565
3104
  if (msgId !== undefined && item.id !== undefined && openReasoning.has(item.id)) {
@@ -2600,7 +3139,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2600
3139
  ...(itemId !== undefined ? { itemId } : {}),
2601
3140
  });
2602
3141
  }
2603
- // OA-11: a terminal output naming this rs_ later must not open a second block.
3142
+ // A terminal output naming this rs_ later must not open a second block.
2604
3143
  if (itemId !== undefined) filledReasoning.add(itemId);
2605
3144
  }
2606
3145
 
@@ -2616,7 +3155,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2616
3155
  * pending bookkeeping and — if the turn's pending set just drained to empty
2617
3156
  * — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
2618
3157
  * the `function_call` `tool_output` arm and the built-in Shell/Apply-Patch
2619
- * `tool_output` arm (playbook 2026-07-03 SDK-bump adaptation, Finding #1).
3158
+ * `tool_output` arm (the 2026-07-03 SDK-bump adaptation).
2620
3159
  */
2621
3160
  /**
2622
3161
  * HO-P, the handoff round release (§8.0 item 14, draft.5). Called at
@@ -2652,10 +3191,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2652
3191
  turnIdByToolCallId.delete(callId);
2653
3192
  }
2654
3193
  if (pending.size > 0) return;
2655
- const stashed = stashedCloseByTurn.get(sourceTurnId);
2656
- if (stashed === undefined) return;
2657
- stashedCloseByTurn.delete(sourceTurnId);
2658
- emitRoundClose(sourceTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
3194
+ maybeReleaseRound(sourceTurnId);
2659
3195
  }
2660
3196
 
2661
3197
  function drainPendingTool(callId: string, doneTurnId: string | undefined): void {
@@ -2664,17 +3200,12 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2664
3200
  const pending = pendingToolsByTurn.get(doneTurnId);
2665
3201
  if (pending === undefined) return;
2666
3202
  pending.delete(callId);
2667
- if (pending.size === 0) {
2668
- const stashed = stashedCloseByTurn.get(doneTurnId);
2669
- if (stashed !== undefined) {
2670
- // The pending set just drained — emit the deferred message.end +
2671
- // turn.done immediately after this tool.done, same push() batch
2672
- // (INV-MSG: the message must still be open when tool.done lands, so
2673
- // message.end waits for this too).
2674
- stashedCloseByTurn.delete(doneTurnId);
2675
- emitRoundClose(doneTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
2676
- }
2677
- }
3203
+ // The pending set just drained — emit the deferred message.end +
3204
+ // turn.done immediately after this tool.done, same push() batch
3205
+ // (INV-MSG: the message must still be open when tool.done lands, so
3206
+ // message.end waits for this too), unless a listed built-in call of the
3207
+ // round has yet to land (see "Built-in round attach").
3208
+ if (pending.size === 0) maybeReleaseRound(doneTurnId);
2678
3209
  }
2679
3210
 
2680
3211
  /** True if any shell command in `entries` timed out or exited non-zero. */
@@ -2688,7 +3219,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2688
3219
 
2689
3220
  /**
2690
3221
  * Map a `tool_output` run-item whose `rawItem` is a Shell, Apply-Patch, or
2691
- * Computer-Use result (playbook 2026-07-03 SDK-bump adaptation, Finding #1;
3222
+ * Computer-Use result (the 2026-07-03 SDK-bump adaptation;
2692
3223
  * `computer_call_result` added by the fixture-drift ratchet finding, same
2693
3224
  * date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
2694
3225
  * (a bare string / content-part union) — `shell_call_output.output` is an
@@ -2726,7 +3257,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2726
3257
  shellOutputHasError(rawItem.output) || rawItem.status === "incomplete" ? "error" : "ok";
2727
3258
  // The full per-command record (stdout/stderr/exit code) is lossy to
2728
3259
  // collapse into text-only content — carry it verbatim as structuredContent
2729
- // too (mirrors the function_call path's ggui-cache-marker precedent).
3260
+ // too (mirrors the function_call path's cache-marker precedent).
2730
3261
  structuredContent = JsonValue.parse(rawItem.output);
2731
3262
  // The outcome mapping alone cannot recover `status` ('in_progress' vs
2732
3263
  // 'completed' vs absent all map ok) — carry it verbatim, with caller.
@@ -2813,7 +3344,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2813
3344
  /**
2814
3345
  * Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
2815
3346
  * built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
2816
- * — playbook 2026-07-03 SDK-bump adaptation, Finding #1; `computer_call`
3347
+ * — the 2026-07-03 SDK-bump adaptation; `computer_call`
2817
3348
  * added by the fixture-drift ratchet finding, same date). Unlike
2818
3349
  * `function_call` (whose tool-start rides the raw `response.output_item.
2819
3350
  * added` stream — the authoritative source, canonical model A1), this
@@ -2824,11 +3355,12 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2824
3355
  * action/operation arrives complete on this one wrapper), and
2825
3356
  * `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
2826
3357
  * an agents-core-internal umbrella normalized only at this run-item layer).
2827
- * `ensureResponseOpen()` mirrors the raw function_call path's treatment
2828
- * (both are tool-START signals expected EARLY in a round, unlike the
2829
- * LATE-arriving `tool_output`/`message_output_created` run-items this file
2830
- * already documents) — residual ordering risk if a future capture shows
2831
- * otherwise is flagged in the adaptation report, not silently assumed away.
3358
+ * Like every run-item, this wrapper lands AFTER its response's
3359
+ * `response.completed` (agents-core 0.18.0 streams a response's step items
3360
+ * after the raw loop, run.mjs:1935), so it attaches to the round its
3361
+ * terminal listed, whose close is deferred for it (see "Built-in round
3362
+ * attach"); it opens a response only when none has been seen for it (a
3363
+ * run-item that lands while its response is open joins that response).
2832
3364
  *
2833
3365
  * `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
2834
3366
  * result arrives via a LATER `tool_output` run-item, same Task-4b
@@ -2840,7 +3372,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2840
3372
  * doc) — no pending registration.
2841
3373
  */
2842
3374
  /**
2843
- * OA-13: did OpenAI (the provider) already execute this built-in call? →
3375
+ * Did OpenAI (the provider) already execute this built-in call? →
2844
3376
  * `tool.start.providerExecuted` (SPEC:632; SPEC:496 "client MUST NOT
2845
3377
  * execute"). Per the installed runtime (agents-core 0.18.0
2846
3378
  * `dist/runner/modelOutputs.mjs`): `hosted_tool_call` always (resolved
@@ -2869,6 +3401,209 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2869
3401
  return false;
2870
3402
  }
2871
3403
 
3404
+ /**
3405
+ * The toolCallId of a `hosted_tool_call`: its item id when it has one. An
3406
+ * id-less item gets a derived id, `<name>_<invoke stem>_<n>` (INV-BLOCK,
3407
+ * SPEC:767: "Normalizers MUST mint collision-free **derived** ids when the
3408
+ * framework omits one"), never its `name`, which two items of one invoke
3409
+ * can share. An `mcp_approval_response` (which agents-core 0.18.0 builds
3410
+ * with no id, runner/mcpApprovals.mjs:39-49) is no call of its own: it
3411
+ * closes the request it answers (`driveApprovalAnswer`).
3412
+ */
3413
+ function hostedToolCallId(rawItem: OpenAIHostedToolCallItem): string {
3414
+ if (rawItem.id !== undefined && rawItem.id.length > 0) return rawItem.id;
3415
+ return `${rawItem.name}_${invokeStem}_${++derivedOrdinal}`;
3416
+ }
3417
+
3418
+ /** The hosted-MCP kind of a `hosted_tool_call`, by its `name` or its
3419
+ * `providerData.type` (agents-openai's converter matches either,
3420
+ * openaiResponsesConverter.mjs:1066-1115). */
3421
+ function hostedMcpKind(
3422
+ rawItem: OpenAIHostedToolCallItem,
3423
+ ): "mcp_call" | "mcp_approval_request" | "mcp_approval_response" | undefined {
3424
+ const type: unknown = rawItem.providerData?.type;
3425
+ for (const kind of ["mcp_call", "mcp_approval_request", "mcp_approval_response"] as const) {
3426
+ if (rawItem.name === kind || type === kind) return kind;
3427
+ }
3428
+ return undefined;
3429
+ }
3430
+
3431
+ /**
3432
+ * An `mcp_approval_response` run-item closes the request it answers
3433
+ * (`providerData.approval_request_id`) with exactly one `tool.done`:
3434
+ * outcome "ok" when `providerData.approve` is true, which records the
3435
+ * approval and not the result of the call it gates, and "denied" when it is
3436
+ * not. It creates no block of its own, and the `mcp_call` it gates is a
3437
+ * separate call under its own id. The request is a pending call of its
3438
+ * round in the same invoke (the onApproval flow); in a resuming invoke it
3439
+ * is unknown, and the answer lands as a leading result does
3440
+ * (`openTurnForLeadingResult`, INV-XINV). An answer's `reason` rides
3441
+ * tool.done providerMetadata. Three answers have nothing to close, and each
3442
+ * is carried verbatim on ext.openai.unparsed: one that names no request; a
3443
+ * second answer to a request this invoke already closed (agents-core
3444
+ * answers each request once, runner/mcpApprovals.mjs), which would close it
3445
+ * twice; and one naming a request this invoke does not hold while a
3446
+ * response is open, which no leading turn can take.
3447
+ */
3448
+ function driveApprovalAnswer(rawItem: OpenAIHostedToolCallItem): void {
3449
+ const requestId: unknown = rawItem.providerData?.approval_request_id;
3450
+ if (typeof requestId !== "string" || requestId.length === 0 || answeredRequests.has(requestId)) {
3451
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
3452
+ return;
3453
+ }
3454
+ const reason: unknown = rawItem.providerData?.reason;
3455
+ const meta = openaiProviderMeta({
3456
+ reason: typeof reason === "string" && reason.length > 0 ? reason : undefined,
3457
+ caller: callerToJson(rawItem.caller),
3458
+ });
3459
+ const doneTurnId = resolvePendingTurnId(requestId);
3460
+ const leading = doneTurnId === undefined ? openTurnForLeadingResult(requestId) : undefined;
3461
+ if (doneTurnId === undefined && leading === undefined) {
3462
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
3463
+ return;
3464
+ }
3465
+ answeredRequests.add(requestId);
3466
+ a.toolDone({
3467
+ toolCallId: requestId,
3468
+ content: [],
3469
+ outcome: rawItem.providerData?.approve === true ? "ok" : "denied",
3470
+ ...(meta !== undefined ? { providerMetadata: meta } : {}),
3471
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : leading),
3472
+ });
3473
+ drainPendingTool(requestId, doneTurnId);
3474
+ }
3475
+
3476
+ /**
3477
+ * A hosted call's input. agents-openai's converter keeps a hosted item's
3478
+ * fields in `providerData` (SPEC:965: a native value is never dropped
3479
+ * silently):
3480
+ * - its `arguments` (top-level when present, else in providerData — the
3481
+ * MCP kinds);
3482
+ * - else a web_search's `action` without its `sources`, which are the
3483
+ * call's result, not its input;
3484
+ * - else a file_search's `queries`;
3485
+ * - else a code_interpreter's `code` and `container_id` (its call payload
3486
+ * without its `outputs`, the program precedent).
3487
+ */
3488
+ function hostedInput(rawItem: OpenAIHostedToolCallItem): JsonValue {
3489
+ const pd = rawItem.providerData;
3490
+ const args: unknown = rawItem.arguments ?? pd?.arguments;
3491
+ if (typeof args === "string") return parseJsonArguments(rawItem.id, args);
3492
+ const action = pd?.action;
3493
+ if (isJsonObject(action)) {
3494
+ const input: { [k: string]: JsonValue } = {};
3495
+ for (const [k, v] of Object.entries(action)) if (k !== "sources") input[k] = v;
3496
+ return JsonValue.parse(input);
3497
+ }
3498
+ if (rawItem.name === "file_search_call" && pd?.queries !== undefined) return JsonValue.parse({ queries: pd.queries });
3499
+ if (rawItem.name === "code_interpreter_call" && (pd?.code !== undefined || pd?.container_id !== undefined)) {
3500
+ return JsonValue.parse({
3501
+ ...(pd?.code !== undefined ? { code: pd.code } : {}),
3502
+ ...(pd?.container_id !== undefined ? { container_id: pd.container_id } : {}),
3503
+ });
3504
+ }
3505
+ return {};
3506
+ }
3507
+
3508
+ /**
3509
+ * A hosted call's result: its `output` (an image_generation result, which
3510
+ * is base64 image data, as a file block; any other as text), a
3511
+ * web_search's `sources`, an mcp_list_tools listing, a file_search's
3512
+ * `results` and a code_interpreter's `outputs` as data blocks, and its
3513
+ * outcome. The outcome is "error" when the native status is `failed` or
3514
+ * `incomplete`, as a shell, program or function result's `incomplete` is
3515
+ * (and an apply-patch result's `failed`); for an mcp_call, whose top-level
3516
+ * status the converter always sets to "completed", the status in
3517
+ * providerData. It is also "error" when the item carries a non-null
3518
+ * `error`, an empty string included, even with a `completed` status. Any
3519
+ * other status (`in_progress`,
3520
+ * `searching`, `interpreting`, …) closes "ok"; a status other than
3521
+ * `completed` rides tool.done providerMetadata.status verbatim.
3522
+ */
3523
+ function hostedResult(rawItem: OpenAIHostedToolCallItem): {
3524
+ content: AgBlock[];
3525
+ outcome: ToolOutcome;
3526
+ isError?: true;
3527
+ errorText?: string;
3528
+ errorCode?: string;
3529
+ providerMetadata?: AgProviderMeta;
3530
+ } {
3531
+ const pd = rawItem.providerData;
3532
+ const content: AgBlock[] = [];
3533
+ const output: unknown = rawItem.output;
3534
+ if (typeof output === "string" && output.length > 0) {
3535
+ content.push(
3536
+ rawItem.name === "image_generation_call"
3537
+ ? { type: "file", source: { type: "base64", mediaType: imageResultMediaType(pd, output), data: output } }
3538
+ : { type: "text", text: output },
3539
+ );
3540
+ }
3541
+ const action = pd?.action;
3542
+ if (isJsonObject(action) && Array.isArray(action.sources)) {
3543
+ content.push({ type: "data", name: "web_search_sources", data: JsonValue.parse(action.sources) });
3544
+ }
3545
+ const tools = pd?.tools;
3546
+ if (rawItem.name === "mcp_list_tools" && Array.isArray(tools)) {
3547
+ content.push({ type: "data", name: "mcp_list_tools", data: JsonValue.parse(tools) });
3548
+ }
3549
+ const results = pd?.results;
3550
+ if (rawItem.name === "file_search_call" && Array.isArray(results)) {
3551
+ content.push({ type: "data", name: "file_search_results", data: JsonValue.parse(results) });
3552
+ }
3553
+ const outputs = pd?.outputs;
3554
+ if (rawItem.name === "code_interpreter_call" && Array.isArray(outputs)) {
3555
+ content.push({ type: "data", name: "code_interpreter_outputs", data: JsonValue.parse(outputs) });
3556
+ }
3557
+ const status: unknown = hostedMcpKind(rawItem) === "mcp_call" ? (pd?.status ?? rawItem.status) : rawItem.status;
3558
+ // An mcp_call's `error` is an object on the wire (openai-node 7.22.0
3559
+ // McpToolCallError: a protocol or HTTP error {code, message, type}, or a
3560
+ // tool execution error {content, type}): its message (else the object as
3561
+ // JSON) is the errorText, its type the errorCode, and the object rides
3562
+ // tool.done providerMetadata verbatim. A non-empty string error is its own
3563
+ // text; any other non-null error (an empty string) rides providerMetadata.
3564
+ const error: unknown = pd?.error;
3565
+ const hasError = error !== undefined && error !== null;
3566
+ const errorMessage: unknown = isJsonObject(error) ? error.message : undefined;
3567
+ const errorText =
3568
+ typeof error === "string" && error.length > 0
3569
+ ? error
3570
+ : typeof errorMessage === "string" && errorMessage.length > 0
3571
+ ? errorMessage
3572
+ : isJsonObject(error)
3573
+ ? JSON.stringify(error)
3574
+ : undefined;
3575
+ const errorType: unknown = isJsonObject(error) ? error.type : undefined;
3576
+ // An image_generation result's own fields (revised prompt, size, quality,
3577
+ // background, action, format) ride tool.done providerMetadata verbatim.
3578
+ const image = rawItem.name === "image_generation_call" ? pd : undefined;
3579
+ const imageField = (k: string): JsonValue | undefined => {
3580
+ const v = image?.[k];
3581
+ return v === null ? undefined : v;
3582
+ };
3583
+ const providerMetadata = openaiProviderMeta({
3584
+ status: typeof status === "string" && status.length > 0 && status !== "completed" ? status : undefined,
3585
+ error: hasError && errorText !== error ? JsonValue.parse(error) : undefined,
3586
+ revised_prompt: imageField("revised_prompt"),
3587
+ size: imageField("size"),
3588
+ quality: imageField("quality"),
3589
+ background: imageField("background"),
3590
+ action: imageField("action"),
3591
+ output_format: imageField("output_format"),
3592
+ });
3593
+ const meta = providerMetadata !== undefined ? { providerMetadata } : {};
3594
+ if (status === "failed" || status === "incomplete" || hasError) {
3595
+ return {
3596
+ content,
3597
+ outcome: "error",
3598
+ isError: true,
3599
+ ...(errorText !== undefined ? { errorText } : {}),
3600
+ ...(typeof errorType === "string" && errorType.length > 0 ? { errorCode: errorType } : {}),
3601
+ ...meta,
3602
+ };
3603
+ }
3604
+ return { content, outcome: "ok", ...meta };
3605
+ }
3606
+
2872
3607
  function driveBuiltinToolCalled(
2873
3608
  rawItem:
2874
3609
  | OpenAIShellCallItem
@@ -2877,25 +3612,65 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2877
3612
  | OpenAIHostedToolCallItem
2878
3613
  | OpenAIProgramCallItem,
2879
3614
  ): void {
2880
- ensureResponseOpen();
2881
- if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
2882
- const toolCallId = rawItem.type === "hosted_tool_call" ? (rawItem.id ?? rawItem.name) : rawItem.callId;
2883
- const name = builtinToolName(rawItem);
3615
+ const mcpKind = rawItem.type === "hosted_tool_call" ? hostedMcpKind(rawItem) : undefined;
3616
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_response") {
3617
+ driveApprovalAnswer(rawItem);
3618
+ return;
3619
+ }
3620
+ // The listed item this run-item is (see "Built-in round attach").
3621
+ const key = rawItem.id;
3622
+ if (rawItem.id !== undefined) seenBuiltinItemIds.add(rawItem.id);
3623
+ const toolCallId = rawItem.type === "hosted_tool_call" ? hostedToolCallId(rawItem) : rawItem.callId;
3624
+ // A run-item that lands after its round's terminal attaches to that round;
3625
+ // one that lands while a response is open belongs to it. A hosted call
3626
+ // that no round claims while no response is open (not a 0.18.0 shape: a
3627
+ // resuming invoke leads with a tool result or an approval's answer) opens
3628
+ // its turn as a leading tool result does (`openTurnForLeadingResult`), in
3629
+ // an assistant message of its own, `<toolCallId>:call`, closed after the
3630
+ // call: the response that follows then opens its own message in that
3631
+ // turn, with its model. A leading client-executed or tool-search call
3632
+ // keeps the response open.
3633
+ const late = lateBuiltinRound(key);
3634
+ // openTurnForLeadingResult returns undefined while a response is open.
3635
+ const leading = late === undefined && rawItem.type === "hosted_tool_call" ? openTurnForLeadingResult(toolCallId) : undefined;
3636
+ const callMsgId = leading !== undefined ? `${toolCallId}:call` : undefined;
3637
+ if (leading !== undefined && callMsgId !== undefined) {
3638
+ a.openMessage({ id: callMsgId, role: "assistant", turnId: leading.turnId, threadId });
3639
+ } else if (late === undefined) {
3640
+ ensureResponseOpen();
3641
+ }
3642
+ const ownerMsgId = late !== undefined ? late.mId : (callMsgId ?? msgId);
3643
+ const ownerTurnId = late !== undefined ? late.tid : (leading?.turnId ?? turnId);
3644
+ if (ownerMsgId === undefined) return; // unreachable post-ensure; satisfies narrowing
3645
+ // An MCP call or approval request is named by the MCP tool it calls
3646
+ // (`providerData.name`); the item's own name is the umbrella (`mcp_call` /
3647
+ // `mcp_approval_request`), which rides providerMetadata.type.
3648
+ const mcpToolName: unknown = mcpKind !== undefined ? rawItem.providerData?.name : undefined;
3649
+ const name = typeof mcpToolName === "string" && mcpToolName.length > 0 ? mcpToolName : builtinToolName(rawItem);
2884
3650
  // Caller provenance (0.14.0): typed only on the shapes the wire declares
2885
3651
  // it for — computer_call and program carry none (protocol.d.ts).
2886
3652
  const caller =
2887
3653
  rawItem.type === "shell_call" || rawItem.type === "apply_patch_call" || rawItem.type === "hosted_tool_call"
2888
3654
  ? rawItem.caller
2889
3655
  : undefined;
2890
- const startMeta = openaiProviderMeta({ caller: callerToJson(caller) });
3656
+ // An mcp_call that an approval gated names that request (verbatim).
3657
+ const approvalRequestId: unknown = mcpKind === "mcp_call" ? rawItem.providerData?.approval_request_id : undefined;
3658
+ const startMeta = openaiProviderMeta({
3659
+ caller: callerToJson(caller),
3660
+ type: mcpKind,
3661
+ approval_request_id: typeof approvalRequestId === "string" && approvalRequestId.length > 0 ? approvalRequestId : undefined,
3662
+ });
3663
+ // An MCP item's server label (SPEC tool.start.serverName).
3664
+ const serverLabel: unknown = rawItem.type === "hosted_tool_call" ? rawItem.providerData?.server_label : undefined;
2891
3665
  a.toolStart({
2892
3666
  toolCallId,
2893
3667
  name,
3668
+ ...(typeof serverLabel === "string" && serverLabel.length > 0 ? { serverName: serverLabel } : {}),
2894
3669
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
2895
3670
  ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
2896
- // OA-13: see builtinProviderExecuted().
3671
+ // See builtinProviderExecuted().
2897
3672
  ...(builtinProviderExecuted(rawItem) ? { providerExecuted: true } : {}),
2898
- messageId: msgId,
3673
+ messageId: ownerMsgId,
2899
3674
  });
2900
3675
  const input: JsonValue =
2901
3676
  rawItem.type === "shell_call"
@@ -2908,16 +3683,28 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2908
3683
  ? // The call's whole wire payload, verbatim (the shell/apply-patch
2909
3684
  // precedent): `code` is the model-authored program source.
2910
3685
  { code: rawItem.code, fingerprint: rawItem.fingerprint }
2911
- : parseJsonArguments(rawItem.id, rawItem.arguments);
3686
+ : hostedInput(rawItem);
2912
3687
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
2913
3688
  a.toolArgsAssembled(toolCallId, input);
3689
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_request") {
3690
+ // Not resolved: the request stays a pending call of its round until its
3691
+ // answer closes it; with no answer, the round flushes paused naming its
3692
+ // ask (§8.0 items 14 and 20, INV-FLUSH (2)).
3693
+ if (callMsgId !== undefined) a.closeMessage(callMsgId);
3694
+ registerPendingToolFor(ownerTurnId, toolCallId);
3695
+ drainListedBuiltin(key);
3696
+ return;
3697
+ }
2914
3698
  if (rawItem.type === "hosted_tool_call") {
2915
- const content: AgBlock[] =
2916
- rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
2917
- a.toolDone({ toolCallId, content, outcome: "ok" });
3699
+ const doneTurnId = late?.tid ?? leading?.turnId;
3700
+ a.toolDone({ toolCallId, ...hostedResult(rawItem), ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}) });
3701
+ if (callMsgId !== undefined) a.closeMessage(callMsgId);
3702
+ drainListedBuiltin(key);
2918
3703
  return;
2919
3704
  }
2920
- registerPendingTool(toolCallId);
3705
+ registerPendingToolFor(ownerTurnId, toolCallId);
3706
+ // Its run-item has landed; the round now waits on its result.
3707
+ drainListedBuiltin(key);
2921
3708
  }
2922
3709
 
2923
3710
  /**
@@ -2967,28 +3754,37 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2967
3754
  * like any other unresolved pending tool call, no special-casing needed.
2968
3755
  */
2969
3756
  function driveToolSearchCalled(rawItem: OpenAIToolSearchCallItem): void {
2970
- ensureResponseOpen();
2971
- if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
3757
+ if (rawItem.id !== undefined) seenBuiltinItemIds.add(rawItem.id);
2972
3758
  const toolCallId = resolveToolSearchCallId(rawItem);
2973
3759
  if (toolCallId === undefined) {
2974
- // Genuinely unresolvable correlation id — never fabricate one (Tenet 6).
3760
+ // Genuinely unresolvable correlation id — never fabricate one (Tenet 6),
3761
+ // and open no turn for it: the carry is not block content.
2975
3762
  a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
3763
+ drainListedBuiltin(rawItem.id);
2976
3764
  return;
2977
3765
  }
3766
+ // A run-item that lands after its round's terminal attaches to that round
3767
+ // (see "Built-in round attach").
3768
+ const late = lateBuiltinRound(rawItem.id);
3769
+ if (late === undefined) ensureResponseOpen();
3770
+ const ownerMsgId = late !== undefined ? late.mId : msgId;
3771
+ const ownerTurnId = late !== undefined ? late.tid : turnId;
3772
+ if (ownerMsgId === undefined) return; // unreachable post-ensure; satisfies narrowing
2978
3773
  a.toolStart({
2979
3774
  toolCallId,
2980
3775
  name: "builtin:tool_search",
2981
3776
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
2982
- // OA-13: the item says where it ran — only `execution:"server"` is the
3777
+ // The item says where it ran — only `execution:"server"` is the
2983
3778
  // provider's (SPEC:496); "client" (the SDK's own loader / a custom
2984
3779
  // execute()) and absent leave the key off.
2985
3780
  ...(rawItem.execution === "server" ? { providerExecuted: true } : {}),
2986
- messageId: msgId,
3781
+ messageId: ownerMsgId,
2987
3782
  });
2988
3783
  const input: JsonValue = JsonValue.parse(rawItem.arguments ?? {});
2989
3784
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
2990
3785
  a.toolArgsAssembled(toolCallId, input);
2991
- registerPendingTool(toolCallId);
3786
+ registerPendingToolFor(ownerTurnId, toolCallId);
3787
+ drainListedBuiltin(rawItem.id);
2992
3788
  }
2993
3789
 
2994
3790
  /**
@@ -3022,8 +3818,15 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3022
3818
  // the deserialization boundary, where a non-string would otherwise reach
3023
3819
  // `AgProviderMeta.parse`.
3024
3820
  const rawAgentName: unknown = rawItem.toolSearchAgentName;
3821
+ // agents-core 0.20.0 adds the hosted MCP names this search established
3822
+ // (`toolSearchMcpToolNames`), carried the same way: an array of strings,
3823
+ // verbatim; anything else at this boundary is no carry.
3824
+ const rawMcpNames: unknown = rawItem.toolSearchMcpToolNames;
3825
+ const mcpNames =
3826
+ Array.isArray(rawMcpNames) && rawMcpNames.every((v) => typeof v === "string") ? JsonValue.parse(rawMcpNames) : undefined;
3025
3827
  const searchMeta = openaiProviderMeta({
3026
3828
  toolSearchAgentName: typeof rawAgentName === "string" ? rawAgentName : undefined,
3829
+ toolSearchMcpToolNames: mcpNames,
3027
3830
  });
3028
3831
  a.toolDone({
3029
3832
  toolCallId,
@@ -3050,7 +3853,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3050
3853
  function driveHostError(event: OpenAIHostError): void {
3051
3854
  // O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
3052
3855
  // close is deferred releases that close per INV-FLUSH (2) BEFORE the
3053
- // normalizer closes the error (PS-21).
3856
+ // normalizer closes the error.
3054
3857
  releaseAllDeferredCloses();
3055
3858
  ensureResponseOpen();
3056
3859
  if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
@@ -3098,7 +3901,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3098
3901
  switch (event.name) {
3099
3902
  case "tool_output": {
3100
3903
  const rawItem = event.item.rawItem;
3101
- // Finding #1 (critical) + the fixture-drift ratchet's
3904
+ // The 2026-07-03 SDK-bump adaptation + the fixture-drift ratchet's
3102
3905
  // computer_call_result finding + the 0.14.0 program_output carry:
3103
3906
  // Shell/Apply-Patch/Computer-Use/Program results do NOT share
3104
3907
  // `OpenAIFunctionCallResultItem.output`'s shape — see
@@ -3127,7 +3930,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3127
3930
  return;
3128
3931
  }
3129
3932
  // Authoritative tool-result source (canonical model, A1). Drives toolDone
3130
- // with content + structuredContent (the ggui cache marker — see
3933
+ // with content + structuredContent (a reference client's cache marker — see
3131
3934
  // `extractStructuredContent`'s doc for the two peer-supported homes and
3132
3935
  // the playbook 2026-07-03 wire-truth findings behind them).
3133
3936
  const outcome: ToolOutcome = rawItem.status === "incomplete" ? "error" : "ok";
@@ -3135,7 +3938,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3135
3938
  const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
3136
3939
  // workspace#21: `customData._meta` → block `_meta`; with `_meta.ui` the
3137
3940
  // payload is MCP-Apps view data → ALSO `uiData` (SPEC.md:332), leaving
3138
- // `structuredContent` as it was (the :340 mapping; ggui's cache marker
3941
+ // `structuredContent` as it was (the :340 mapping; a reference client's cache marker
3139
3942
  // rides it). §2.1's "exactly one consumer" is per channel (ruled
3140
3943
  // option A). Mirrors claude-agent-sdk/src/index.ts:1926-1946.
3141
3944
  const resultMeta = extractResultMeta(event.item.customData);
@@ -3150,7 +3953,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3150
3953
  // could misattribute it) and pass it through so toolDone binds to the
3151
3954
  // correct — possibly already-closed-pending-this-result — turn.
3152
3955
  const doneTurnId = resolvePendingTurnId(rawItem.callId);
3153
- // HO-2 (the handoff-drop review, PS-4): a result for a transfer call
3956
+ // A result for a transfer call
3154
3957
  // whose bracket is still open means that handoff never ran —
3155
3958
  // agents-core <=0.8.0's "Multiple handoffs detected, ignoring this
3156
3959
  // one." (0.8.0 toolExecution.mjs:750-755), the one streamed producer.
@@ -3207,7 +4010,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3207
4010
  // ignoring the wrapper copy here loses nothing.
3208
4011
  return;
3209
4012
  }
3210
- // Finding #1 (critical): Shell / Apply-Patch / Hosted-tool /
4013
+ // The 2026-07-03 SDK-bump adaptation: Shell / Apply-Patch / Hosted-tool /
3211
4014
  // Program built-ins — this run-item wrapper (not the raw stream) is
3212
4015
  // the SOLE tool-start source for these (see `driveBuiltinToolCalled`'s
3213
4016
  // doc).
@@ -3224,7 +4027,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3224
4027
  driveToolSearchOutput(event.item.rawItem);
3225
4028
  return;
3226
4029
  case "reasoning_item_created":
3227
- // FALLBACK source since OA-11 (the raw terminal output fills first; an
4030
+ // FALLBACK source (the raw terminal output fills first; an
3228
4031
  // already-filled rs_ is a no-op) — see driveReasoningItemCreated's docstring.
3229
4032
  driveReasoningItemCreated(event.item.rawItem);
3230
4033
  return;
@@ -3241,7 +4044,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3241
4044
  // `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
3242
4045
  // bracket the transfer with `subagentStart` now / `subagentDone` at the
3243
4046
  // matching `handoff_occurred` below (by callId via `openHandoffs`; or at
3244
- // the call's `tool_output` when the handoff never ran — HO-2).
4047
+ // the call's `tool_output` when the handoff never ran).
3245
4048
  //
3246
4049
  // `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
3247
4050
  // LLM call produced this handoff call — NOT the transfer target (see
@@ -3314,7 +4117,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3314
4117
  // still emit the `handoff` event losslessly rather than dropping the
3315
4118
  // now-known identity (Tenet 6) — it just doesn't close anything. It
3316
4119
  // precedes the tool.done, which may close the source round.
3317
- // HO-2: the handoff is owned by the SOURCE turn, explicitly. With two
4120
+ // The handoff is owned by the SOURCE turn, explicitly. With two
3318
4121
  // brackets open (agents-core <=0.8.0) the engine's backfill would pick
3319
4122
  // the last-restored nested turn; on every single-bracket stream this is
3320
4123
  // the value the backfill gave.
@@ -3360,22 +4163,31 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3360
4163
  return;
3361
4164
  }
3362
4165
  case "tool_approval_requested": {
3363
- // Task 3 (audit M48): a human-in-the-loop approval gate on a pending
3364
- // tool call. `askId` mirrors the `approval_${callId}` convention already
3365
- // established by the google-adk facet's `requestedToolConfirmations` arm
3366
- // (index.ts:653) for the same `kind:"approval"` semantics. The M26
3367
- // paused-fold discipline (surfacing this on the turn's `outcome.paused`)
3368
- // is ADK-scoped for this batch — `hitl.ask` is LIVE-ONLY on the fold
3369
- // (reduce.ts R9: no accumulator mutation), so emitting the ask alone is
3370
- // complete; the host/turn-close owns any pause semantics.
4166
+ // A human-in-the-loop approval gate on a pending tool call. `askId`
4167
+ // mirrors the `approval_${callId}` convention of the google-adk
4168
+ // facet's `requestedToolConfirmations` arm for the same
4169
+ // `kind:"approval"` semantics. The gated call stays pending, so a
4170
+ // round the stream leaves waiting on it flushes paused naming this
4171
+ // ask (INV-FLUSH (2)).
3371
4172
  const item = event.item.rawItem;
4173
+ // The call the ask gates: a function, shell, apply-patch or computer
4174
+ // call's callId, else the item's id. A hosted-MCP approval request
4175
+ // has no callId, and its id is the request id its tool.start uses.
4176
+ // callId comes first, so a function approval's ask is unchanged.
4177
+ const gatedId = item.callId ?? item.id;
4178
+ if (gatedId === undefined) {
4179
+ // No id to key on: a collision-free derived askId (INV-BLOCK) and
4180
+ // no toolCallId, rather than naming a call the facet cannot find.
4181
+ a.emit({ type: "hitl.ask", askId: `approval_${invokeStem}_${++derivedOrdinal}`, kind: "approval" });
4182
+ return;
4183
+ }
3372
4184
  a.emit({
3373
4185
  type: "hitl.ask",
3374
- askId: `approval_${item.callId}`,
4186
+ askId: `approval_${gatedId}`,
3375
4187
  kind: "approval",
3376
- toolCallId: item.callId,
4188
+ toolCallId: gatedId,
3377
4189
  });
3378
- askedApprovals.set(item.callId, `approval_${item.callId}`);
4190
+ askedApprovals.set(gatedId, `approval_${gatedId}`);
3379
4191
  return;
3380
4192
  }
3381
4193
  default:
@@ -3444,7 +4256,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3444
4256
  flush(): AgEvent[] {
3445
4257
  // O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
3446
4258
  // closes FIRST — they are older rounds, so their message.end precedes the
3447
- // live response's (insertion order, CB-16) — as paused / verbatim /
4259
+ // live response's (insertion order) — as paused / verbatim /
3448
4260
  // message.end+usage then turn.abort (`releaseDeferredClose`); a flush
3449
4261
  // never emits a success turn.done.
3450
4262
  releaseAllDeferredCloses();