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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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`.)
@@ -495,16 +500,18 @@ export interface OpenAIComputerCallItem {
495
500
  }
496
501
 
497
502
  /** protocol `ComputerCallResultItem` (the `rawItem` of a `tool_output` run-item
498
- * for a completed Computer-Use call). `output` is ALWAYS the
499
- * `computer_screenshot` shape (a base64-encoded PNG screenshot) — NO
500
- * `status`/error discriminant exists on this wire arm (unlike shell/apply-
501
- * patch results), so the facet maps every occurrence to `outcome:"ok"`.
503
+ * for a Computer-Use call). `output` is ALWAYS the `computer_screenshot`
504
+ * shape, whose `data` is a `data:image/png;base64,…` URL (the SDK mirrors the
505
+ * Responses API `image_url` slot). When the SDK refuses the action (a declined
506
+ * approval, or an `onSafetyCheck` that returns false), `data` is its constant
507
+ * 1×1 placeholder and `output.providerData` carries
508
+ * `{approvalStatus: "rejected", message}`.
502
509
  * @beta
503
510
  */
504
511
  export interface OpenAIComputerCallResultItem {
505
512
  type: "computer_call_result";
506
513
  callId: string;
507
- output: { type: "computer_screenshot"; data: string };
514
+ output: { type: "computer_screenshot"; data: string; providerData?: { [k: string]: JsonValue } };
508
515
  id?: string;
509
516
  providerData?: { [k: string]: JsonValue };
510
517
  }
@@ -602,6 +609,17 @@ export interface OpenAIToolSearchOutputItem {
602
609
  * it is fixture-tested only.
603
610
  */
604
611
  toolSearchAgentName?: string;
612
+ /**
613
+ * agents-core 0.20.0 (`ToolSearchOutputItem.toolSearchMcpToolNames`): the
614
+ * hosted MCP tool names a server-executed search's namespace results
615
+ * established, recorded by the SDK so a later deferred MCP call can be
616
+ * matched to its discovery. Upstream doc: "SDK-only hosted MCP namespace
617
+ * identities established when this output was received. Excluded from
618
+ * provider requests. … This records discovery, not permission to execute a
619
+ * tool." Carried verbatim on `tool.done` providerMetadata, like
620
+ * `toolSearchAgentName`.
621
+ */
622
+ toolSearchMcpToolNames?: string[];
605
623
  call_id?: string | null;
606
624
  callId?: string | null;
607
625
  execution?: "client" | "server";
@@ -639,7 +657,7 @@ interface OpenAIMessageOutputEvent {
639
657
  interface OpenAIToolCalledEvent {
640
658
  type: "run_item_stream_event";
641
659
  name: "tool_called";
642
- // Widened (playbook 2026-07-03 SDK-bump adaptation, Finding #1 + the
660
+ // Widened (the 2026-07-03 SDK-bump adaptation + the
643
661
  // fixture-drift ratchet's computer_call finding + the 0.14.0 programmatic-
644
662
  // tool-calling carry): Shell / Apply-Patch / Computer-Use / Hosted-tool /
645
663
  // Program built-ins reuse this SAME event name with a DIFFERENT `rawItem`
@@ -659,12 +677,12 @@ interface OpenAIToolOutputEvent {
659
677
  type: "run_item_stream_event";
660
678
  name: "tool_output";
661
679
  // `item.rawItem` carries the protocol FunctionCallResultItem (callId, output, status)
662
- // — OR, widened (Finding #1 + the fixture-drift ratchet's computer_call_result
680
+ // — OR, widened (the 2026-07-03 adaptation + the fixture-drift ratchet's computer_call_result
663
681
  // finding), a Shell/Apply-Patch/Computer-Use result (DIFFERENT `output`
664
682
  // shape per discriminant; `hosted_tool_call` never reaches this event, see its
665
683
  // own doc).
666
684
  //
667
- // structuredContent (the ggui cache marker, spec §2.1/§4) has TWO
685
+ // structuredContent (a reference client's cache marker, spec §2.1/§4) has TWO
668
686
  // peer-supported homes on this wrapper (playbook 2026-07-03 follow-up,
669
687
  // `extractStructuredContent`'s doc has the full wire-truth citations):
670
688
  // - `item.customData` — populated ONLY when the caller's `MCPServer`
@@ -693,17 +711,17 @@ interface OpenAIToolOutputEvent {
693
711
  output?: JsonValue;
694
712
  customData?: JsonValue;
695
713
  /**
696
- * agents-core 0.15.0+ (`RunToolCallOutputItem.executionStatus`, a single
697
- * literal): present ONLY when the runner actually invoked the function
698
- * tool (`toolExecution.mjs` sets it right after `invokeFunctionTool`
699
- * returns). Absent when the result item was synthesized instead — an
700
- * input-guardrail rejection, a sibling cancellation, an approval refusal —
701
- * so a consumer can tell a tool's own result from a runner-substituted
702
- * one. Wrapper-level (not a protocol item field), so the fixture-drift
703
- * inventory cannot see it; census-caught on the first live capture after
704
- * 0.14.2 (echo-gpt56 @ 0.17.0). Carried verbatim on `tool.done`
705
- * providerMetadata alongside `caller`. Built-in tool results (shell /
706
- * apply_patch / computer / program) never carry it on the SDK side.
714
+ * agents-core 0.14.3+ (`RunToolCallOutputItem.executionStatus`, a single
715
+ * literal): present ONLY when the runner actually ran the tool
716
+ * (`toolExecution.mjs` sets it after a function tool returns, and on an
717
+ * executed shell, apply_patch or computer result). Absent when the result
718
+ * item was synthesized instead — an input-guardrail rejection, a sibling
719
+ * cancellation, an approval refusal — so a consumer can tell a tool's own
720
+ * result from a runner-substituted one. Wrapper-level (not a protocol item
721
+ * field), so the fixture-drift inventory cannot see it; census-caught on
722
+ * the first live capture after 0.14.2 (echo-gpt56 @ 0.17.0). Carried
723
+ * verbatim on `tool.done` providerMetadata, for function and built-in
724
+ * results alike.
707
725
  */
708
726
  executionStatus?: "executed";
709
727
  };
@@ -820,14 +838,20 @@ interface OpenAIHandoffOccurredEvent {
820
838
  item: OpenAIHandoffOccurredItem;
821
839
  }
822
840
 
823
- /** A tool approval request item (RunToolApprovalItem) — the function call that
824
- * needs human approval rides in rawItem. */
841
+ /** A tool approval request item (RunToolApprovalItem) — the call that needs
842
+ * human approval rides in rawItem. A function, shell, apply-patch or computer
843
+ * call carries its `callId`. A hosted-MCP approval request is a
844
+ * `hosted_tool_call` with NO callId: `{name: <the MCP tool's name>, id: <the
845
+ * request id>, status, providerData}` (agents-core 0.18.0
846
+ * runner/modelOutputs.mjs:463-470), and its request id is agents-core's own
847
+ * identity for it. */
825
848
  interface OpenAIToolApprovalItem {
826
- type: "function_call";
827
- name: string;
828
- callId: string;
829
- arguments: string;
849
+ type: string;
850
+ name?: string;
851
+ callId?: string;
852
+ arguments?: string;
830
853
  id?: string;
854
+ providerData?: { [k: string]: JsonValue };
831
855
  }
832
856
 
833
857
  interface OpenAIToolApprovalRequestedEvent {
@@ -877,7 +901,7 @@ type OpenAIRunItemEvent =
877
901
  * the `model` carrier. */
878
902
  interface OpenAIResponsesCreated {
879
903
  type: "response.created";
880
- /** `model` (OA-12): openai-node `Response.model` — the model id the API
904
+ /** `model` (the per-message model): openai-node `Response.model` — the model id the API
881
905
  * resolved for THIS response (live echo-gpt6sol: `"gpt-6-sol"`), known before
882
906
  * the message opens → `message.start.model`. Typed as the raw `JsonValue` it
883
907
  * is on this seam; string-guarded at the read. */
@@ -912,6 +936,21 @@ interface OpenAIResponsesTextDone {
912
936
  item_id: string;
913
937
  text?: string;
914
938
  }
939
+ /** openai-node `ResponseRefusalDeltaEvent` — a streamed fragment of a
940
+ * `refusal` content part's text (snake_case `item_id`/`delta`). Carried via the
941
+ * `model` carrier. */
942
+ interface OpenAIResponsesRefusalDelta {
943
+ type: "response.refusal.delta";
944
+ item_id: string;
945
+ delta: string;
946
+ }
947
+ /** openai-node `ResponseRefusalDoneEvent` — the `refusal` part of `item_id` is
948
+ * complete; `refusal` carries its whole text. Carried via the `model` carrier. */
949
+ interface OpenAIResponsesRefusalDone {
950
+ type: "response.refusal.done";
951
+ item_id: string;
952
+ refusal: string;
953
+ }
915
954
  /** openai-node `ResponseUsage` — per-response token counts (snake_case).
916
955
  * Extends to include provider-specific fields like OpenRouter's `cost` superset.
917
956
  * `cache_write_tokens` is openai ≥6.46 wire (GPT-5.6-era explicit prompt
@@ -945,7 +984,7 @@ interface OpenAIResponsesCompleted {
945
984
  incomplete_details?: { reason?: string };
946
985
  usage?: OpenAIResponseUsage;
947
986
  /** openai-node `Response.output: ResponseOutputItem[]` — consumed ONLY for its
948
- * `type:"reasoning"` members (OA-11; see `terminalReasoningItems`). Typed as
987
+ * `type:"reasoning"` members (reasoning from the terminal output; see `terminalReasoningItems`). Typed as
949
988
  * the raw `JsonValue` it is on this seam and narrowed item-by-item there:
950
989
  * the outer guard (`isOpenAIStreamEvent`) validates the envelope only. */
951
990
  output?: JsonValue;
@@ -963,8 +1002,148 @@ interface TerminalReasoningItem {
963
1002
  encryptedContent?: string;
964
1003
  }
965
1004
 
1005
+ /** One `refusal` content part of a terminal event's `response.output` message
1006
+ * member, narrowed from `JsonValue`: its item's id and vendor phase marker
1007
+ * (when present) and its text. */
1008
+ interface TerminalRefusalPart {
1009
+ itemId?: string;
1010
+ phase?: string;
1011
+ text: string;
1012
+ }
1013
+
1014
+ /**
1015
+ * The refusal parts of a terminal event's `response.output`, in wire order —
1016
+ * the source of a round's refusal text when no refusal event streamed
1017
+ * (see "Refusal text" in the normalizer). Deserialization boundary: a
1018
+ * non-array output, a non-message member and a part whose `refusal` is not a
1019
+ * string are skipped; an empty id is no id.
1020
+ */
1021
+ function terminalRefusalParts(output: JsonValue | undefined): TerminalRefusalPart[] {
1022
+ const out: TerminalRefusalPart[] = [];
1023
+ if (!Array.isArray(output)) return out;
1024
+ for (const member of output) {
1025
+ if (!isJsonObject(member) || member.type !== "message") continue;
1026
+ const content = member.content;
1027
+ if (!Array.isArray(content)) continue;
1028
+ const itemId = typeof member.id === "string" && member.id.length > 0 ? member.id : undefined;
1029
+ const phase = vendorPhase(member.phase);
1030
+ for (const part of content) {
1031
+ if (!isJsonObject(part) || part.type !== "refusal" || typeof part.refusal !== "string") continue;
1032
+ out.push({
1033
+ ...(itemId !== undefined ? { itemId } : {}),
1034
+ ...(phase !== undefined ? { phase } : {}),
1035
+ text: part.refusal,
1036
+ });
1037
+ }
1038
+ }
1039
+ return out;
1040
+ }
1041
+
1042
+ /**
1043
+ * Did the model refuse in this response? True when any `message` member of a
1044
+ * terminal event's `response.output` carries a `refusal` content part. On the
1045
+ * live wire the `message_output_created` run-item lands AFTER the terminal
1046
+ * event, so the terminal output is where the round's own refusal is known when
1047
+ * the round closes. Absent/non-array output, or no refusal part, ⇒ false.
1048
+ */
1049
+ function terminalHasRefusal(output: JsonValue | undefined): boolean {
1050
+ if (!Array.isArray(output)) return false;
1051
+ for (const member of output) {
1052
+ if (!isJsonObject(member) || member.type !== "message") continue;
1053
+ const content = member.content;
1054
+ if (!Array.isArray(content)) continue;
1055
+ for (const part of content) {
1056
+ if (isJsonObject(part) && part.type === "refusal") return true;
1057
+ }
1058
+ }
1059
+ return false;
1060
+ }
1061
+
1062
+ /**
1063
+ * The media type of an image_generation result (base64): the item's
1064
+ * `output_format` when it carries one (openai-node 7.22.0 declares it
1065
+ * optional and nullable on ImageGenerationCall), else read from the image's
1066
+ * own signature, else `application/octet-stream`.
1067
+ */
1068
+ function imageResultMediaType(providerData: { [k: string]: JsonValue } | undefined, data: string): string {
1069
+ const format = providerData?.output_format;
1070
+ if (format === "png" || format === "jpeg" || format === "webp" || format === "gif") return `image/${format}`;
1071
+ if (data.startsWith("iVBORw0KGgo")) return "image/png";
1072
+ if (data.startsWith("/9j/")) return "image/jpeg";
1073
+ if (data.startsWith("UklGR")) return "image/webp";
1074
+ if (data.startsWith("R0lGOD")) return "image/gif";
1075
+ return "application/octet-stream";
1076
+ }
1077
+
1078
+ /**
1079
+ * The raw Responses output item types that @openai/agents 0.18.0 turns into a
1080
+ * built-in call run-item keeping the item's id: agents-openai's converter
1081
+ * (openaiResponsesConverter.mjs `convertToOutputItem`) maps the hosted kinds
1082
+ * to a `hosted_tool_call` with `id: item.id`, and keeps shell, apply-patch,
1083
+ * computer, program and tool-search calls under their own type. agents-core
1084
+ * streams each as a `tool_called` / `tool_search_called` run-item AFTER the
1085
+ * response's `response.completed` (it streams a response's step items after
1086
+ * the raw loop, run.mjs:1935). `local_shell_call` converts to an unknown item
1087
+ * and never streams as a call, so it is not listed.
1088
+ */
1089
+ const BUILTIN_OUTPUT_ITEM_TYPES: ReadonlySet<string> = new Set([
1090
+ "web_search_call",
1091
+ "file_search_call",
1092
+ "image_generation_call",
1093
+ "code_interpreter_call",
1094
+ "mcp_list_tools",
1095
+ "mcp_approval_request",
1096
+ "mcp_call",
1097
+ "computer_call",
1098
+ "shell_call",
1099
+ "apply_patch_call",
1100
+ "program",
1101
+ "tool_search_call",
1102
+ ]);
1103
+
1104
+ /** A built-in call a terminal event's `response.output` lists: its item id
1105
+ * and raw type. */
1106
+ interface TerminalBuiltinItem {
1107
+ id: string;
1108
+ type: string;
1109
+ }
1110
+
1111
+ /**
1112
+ * The built-in calls a terminal event's `response.output` lists, in wire
1113
+ * order (see {@link BUILTIN_OUTPUT_ITEM_TYPES}). Deserialization boundary: a
1114
+ * non-array output, a non-object member and a member with no non-empty string
1115
+ * id are skipped.
1116
+ */
1117
+ function terminalBuiltinItems(output: JsonValue | undefined): TerminalBuiltinItem[] {
1118
+ const out: TerminalBuiltinItem[] = [];
1119
+ if (!Array.isArray(output)) return out;
1120
+ for (const member of output) {
1121
+ if (!isJsonObject(member)) continue;
1122
+ const type = member.type;
1123
+ const id = member.id;
1124
+ if (typeof type !== "string" || !BUILTIN_OUTPUT_ITEM_TYPES.has(type)) continue;
1125
+ if (typeof id !== "string" || id.length === 0) continue;
1126
+ out.push({ id, type });
1127
+ }
1128
+ return out;
1129
+ }
1130
+
1131
+ /** The ids of the `message` items a terminal event's `response.output` lists,
1132
+ * in wire order (a non-object member or a member with no non-empty string
1133
+ * id is skipped). */
1134
+ function terminalMessageIds(output: JsonValue | undefined): string[] {
1135
+ const out: string[] = [];
1136
+ if (!Array.isArray(output)) return out;
1137
+ for (const member of output) {
1138
+ if (!isJsonObject(member) || member.type !== "message") continue;
1139
+ const id = member.id;
1140
+ if (typeof id === "string" && id.length > 0) out.push(id);
1141
+ }
1142
+ return out;
1143
+ }
1144
+
966
1145
  /**
967
- * OA-11: extract the reasoning items from a terminal event's `response.output`.
1146
+ * Reasoning from the terminal output: extract the reasoning items from a terminal event's `response.output`.
968
1147
  * This — not `response.output_item.done` — is the replayable source: OpenAI
969
1148
  * re-encrypts `encrypted_content` per stage (live, echo-gpt6sol natives [4] vs
970
1149
  * [21]: two different blobs for one `rs_`), and only the terminal blob is the
@@ -976,7 +1155,7 @@ interface TerminalReasoningItem {
976
1155
  * Deserialization boundary: a non-array `output`, a non-object member, a member
977
1156
  * with no string `id`, and a non-string summary `text` are all skipped (an
978
1157
  * 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.
1158
+ * it losslessly). Absent/empty output ⇒ `[]` ⇒ nothing is emitted from it (byte-identical).
980
1159
  */
981
1160
  function terminalReasoningItems(output: JsonValue | undefined): TerminalReasoningItem[] {
982
1161
  if (!Array.isArray(output)) return [];
@@ -1035,7 +1214,7 @@ interface OpenAIResponsesOutputItemAdded {
1035
1214
  // AUTHORITATIVE tool.start source for function_call, so caller provenance
1036
1215
  // must ride HERE — the run-item wrapper occurrence stays ignored.
1037
1216
  caller?: { type: "direct" } | { type: "program"; caller_id: string } | null;
1038
- // OA-14: openai-node `ResponseOutputMessage.phase` (`'commentary' |
1217
+ // The phase read at the raw add: openai-node `ResponseOutputMessage.phase` (`'commentary' |
1039
1218
  // 'final_answer' | null`) — present on a `type:"message"` item AT ADD time
1040
1219
  // (6/8 live openai seeds). Raw `JsonValue`; string-guarded at the read.
1041
1220
  phase?: JsonValue;
@@ -1090,6 +1269,8 @@ type OpenAIRawResponsesEvent =
1090
1269
  | OpenAIResponsesFnArgsDone
1091
1270
  | OpenAIResponsesTextDelta
1092
1271
  | OpenAIResponsesTextDone
1272
+ | OpenAIResponsesRefusalDelta
1273
+ | OpenAIResponsesRefusalDone
1093
1274
  | OpenAIResponsesCompleted
1094
1275
  | OpenAIResponsesFailed
1095
1276
  | OpenAIResponsesError;
@@ -1179,7 +1360,7 @@ export function mapFinishReason(reason: string | undefined | null): AgFinishReas
1179
1360
  }
1180
1361
 
1181
1362
  /**
1182
- * OA-15 (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
1363
+ * The finish-reason raw companion (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
1183
1364
  * 89c57db): the `turn.done` finish fields for a native reason. `finishReason`
1184
1365
  * is `mapFinishReason(reason)`; `finishReasonRaw` — the native value byte for
1185
1366
  * byte — rides along ONLY when that mapping fell back ("other"/"unknown") AND a
@@ -1238,46 +1419,69 @@ function mapUsage(usage: OpenAIResponseUsage | undefined): AgUsage | undefined {
1238
1419
  return u;
1239
1420
  }
1240
1421
 
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);
1422
+ // ─── output_text annotations → AgCitation ──────────────────────────────────
1423
+ // In `splitAnnotations`, `partText` is the source output_text part's text
1424
+ // string, used to extract the cited substring from the char-offset indices
1425
+ // carried by the annotation.
1426
+ /**
1427
+ * An output_text part's annotations, raw. agents-openai 0.18.0's converter
1428
+ * nests every part field but `type` and `text` under `providerData`
1429
+ * (openaiResponsesConverter.mjs `convertToMessageContentItem`), so on the real
1430
+ * wire they are `part.providerData.annotations` (15 of 17 recorded parts carry
1431
+ * them there, 0 at the top level); a top-level `annotations` is read first.
1432
+ * Anything but an array is no annotations.
1433
+ */
1434
+ function partAnnotations(part: OpenAIOutputText): JsonValue[] {
1435
+ const top: unknown = part.annotations;
1436
+ const nested: unknown = part.providerData?.annotations;
1437
+ const raw = Array.isArray(top) ? top : Array.isArray(nested) ? nested : undefined;
1438
+ if (raw === undefined) return [];
1439
+ const parsed = JsonValue.parse(raw);
1440
+ return Array.isArray(parsed) ? parsed : [];
1441
+ }
1442
+
1443
+ /**
1444
+ * Split a part's raw annotations. A `url_citation` with a string `url` maps
1445
+ * to an AgCitation; every other annotation (file_citation,
1446
+ * container_file_citation, file_path, …) has no citation target and stays
1447
+ * verbatim in `unmapped`, for the `ext.openai.late-citations` carry (SPEC:965:
1448
+ * never dropped silently).
1449
+ */
1450
+ function splitAnnotations(raw: readonly JsonValue[], partText: string): { citations?: AgCitation[]; unmapped: JsonValue[] } {
1451
+ const citations: AgCitation[] = [];
1452
+ const unmapped: JsonValue[] = [];
1453
+ for (const ann of raw) {
1454
+ if (!isJsonObject(ann) || ann.type !== "url_citation" || typeof ann.url !== "string") {
1455
+ unmapped.push(ann);
1456
+ continue;
1270
1457
  }
1271
- // file_citation: no url-kind match; skip (deferred to a later slice — only remaining silent annotation drop)
1458
+ // Extract the cited substring from the part text when both offsets are present
1459
+ // and valid. Fall back to "" when any guard condition fails.
1460
+ const startIdx = typeof ann.start_index === "number" ? ann.start_index : undefined;
1461
+ const endIdx = typeof ann.end_index === "number" ? ann.end_index : undefined;
1462
+ const citedText =
1463
+ startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
1464
+ ? partText.slice(startIdx, endIdx)
1465
+ : "";
1466
+ const cit: AgCitation = {
1467
+ kind: "url",
1468
+ url: ann.url,
1469
+ citedText,
1470
+ indexFrame: "response",
1471
+ };
1472
+ if (typeof ann.title === "string") cit.title = ann.title;
1473
+ if (startIdx !== undefined) cit.startIndex = startIdx;
1474
+ if (endIdx !== undefined) cit.endIndex = endIdx;
1475
+ citations.push(cit);
1272
1476
  }
1273
- return out.length > 0 ? out : undefined;
1477
+ return { ...(citations.length > 0 ? { citations } : {}), unmapped };
1274
1478
  }
1275
1479
 
1276
1480
  // ─── optional 0.14.0 wire fields → providerMetadata (spec §2) ─────────────────
1277
1481
  // Wire names ride verbatim at the top level (the claude facet's wrapper-carry
1278
1482
  // precedent — AgProviderMeta imposes no key namespacing). Drops undefined
1279
1483
  // 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
1484
+ /** The phase marker: an OpenAI message `phase` as a vendor MARKER — a non-empty
1281
1485
  * string, verbatim — or `undefined`. openai-node types it
1282
1486
  * `'commentary' | 'final_answer' | null`; null and "" carry no marker, so they
1283
1487
  * yield neither a `providerMetadata.phase` carry nor an ext.openai.late-phase
@@ -1287,7 +1491,7 @@ function vendorPhase(value: unknown): string | undefined {
1287
1491
  return typeof value === "string" && value.length > 0 ? value : undefined;
1288
1492
  }
1289
1493
 
1290
- /** PH-2 (draft.4, SPEC §8.0 item 27): the first-class `phase` for an OpenAI
1494
+ /** SPEC §8.0 item 27 (draft.4): the first-class `phase` for an OpenAI
1291
1495
  * vendor marker — `"commentary"` → `"interim"`; "final_answer", absent and
1292
1496
  * every other value → `undefined` (a vendor spelling is never copied into
1293
1497
  * `phase`; it stays verbatim in `providerMetadata`). */
@@ -1327,7 +1531,19 @@ function isJsonObject(v: unknown): v is { readonly [k: string]: JsonValue } {
1327
1531
  }
1328
1532
 
1329
1533
  /**
1330
- * Extract `structuredContent` (the ggui cache-marker channel, spec §2.1/§4)
1534
+ * A computer screenshot's `data` as an AgSource `base64` arm. The SDK sends a
1535
+ * `data:<media type>;base64,<payload>` URL; the payload lands as `data` and the
1536
+ * header's media type as `mediaType`. A value with no such header lands
1537
+ * verbatim as image/png.
1538
+ */
1539
+ function screenshotSource(data: string): { type: "base64"; mediaType: string; data: string } {
1540
+ const header = /^data:([^;,]+);base64,/.exec(data);
1541
+ if (header === null || header[1] === undefined) return { type: "base64", mediaType: "image/png", data };
1542
+ return { type: "base64", mediaType: header[1], data: data.slice(header[0].length) };
1543
+ }
1544
+
1545
+ /**
1546
+ * Extract `structuredContent` (a reference client's cache-marker channel, spec §2.1/§4)
1331
1547
  * from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
1332
1548
  * follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
1333
1549
  * would be an object keyed by `.structuredContent`; a live capture
@@ -1416,11 +1632,11 @@ function extractStructuredContent(
1416
1632
  }
1417
1633
 
1418
1634
  /**
1419
- * workspace#21 (guuey#981): the MCP tool result's `_meta`, riding the same
1635
+ * workspace#21 (a reference host's ask): the MCP tool result's `_meta`, riding the same
1420
1636
  * host-convention `customData` channel as `structuredContent` (SPEC.md:340) —
1421
1637
  * agents-core 0.18.0 hands it to `MCPServer.customDataExtractor` as
1422
1638
  * `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
1639
+ * at `dist/mcp.mjs`:700); a reference host's worker and this repo's capture agent return it
1424
1640
  * as `customData._meta`. It is a host/protocol annotation (MCP-Apps `ui.*`), so
1425
1641
  * it rides the tool-result block's own `_meta` VERBATIM (SPEC.md:338; §8.0
1426
1642
  * no-drop). Ruled option A on 2026-09-23. A non-object `_meta`
@@ -1469,14 +1685,17 @@ function isOpenAIStreamEvent(v: unknown): v is OpenAIStreamEvent {
1469
1685
  *
1470
1686
  * - turn open ← `model:response.created` (real `response.id` present at start)
1471
1687
  * - text ← `model:response.output_text.delta` (carries `item_id`)
1688
+ * - refusal ← `model:response.refusal.delta` / `.done` (a `text` block,
1689
+ * id `<item_id>:refusal`); with no refusal event in the round,
1690
+ * the terminal output's refusal part (see "Refusal text")
1472
1691
  * - text end ← the `message_output_created` run-item (authoritative close +
1473
- * citations carrier, audit M22 — `response.output_text.done` is a
1692
+ * citations carrier — `response.output_text.done` is a
1474
1693
  * no-op; text streams left open by it fall to the defensive
1475
1694
  * close-any-dangling-stream fallback in `closeResponse()` /
1476
1695
  * `endOpenStreamsAndCloseMessage()` / `emitRoundClose()`)
1477
1696
  * - reasoning ← opens at `model:response.output_item.added{reasoning}` (wire
1478
1697
  * position), filled from the `model:response.completed` /
1479
- * `.incomplete` `response.output` (OA-11 — the final, replayable
1698
+ * `.incomplete` `response.output` (reasoning from the terminal output — the final, replayable
1480
1699
  * `encrypted_content`); `reasoning_item_created` is the fallback
1481
1700
  * - turn close ← `model:response.completed` (guard close-once)
1482
1701
  *
@@ -1525,10 +1744,10 @@ export interface OpenaiNormalizerOptions {
1525
1744
  * `turn_<invokeId>_handoff_<n>`.
1526
1745
  *
1527
1746
  * 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
1747
+ * delivery-integrity rule and INV-BLOCK's collision-free derived ids require it: a reference host
1529
1748
  * folds a whole conversation into ONE Reducer, and a repeated turn id
1530
1749
  * re-opens a closed turn, which parks INV-TURN / INV-MSG consumers.
1531
- * The D3 review (finding DC-10) found the old per-normalizer
1750
+ * A review of the minted ids found the old per-normalizer
1532
1751
  * counters (`turn_openai_<n>`, `turn_handoff_<n>`) repeating across invokes.
1533
1752
  *
1534
1753
  * By default each normalizer draws a fresh `openai_<16 hex>` stem from
@@ -1579,7 +1798,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1579
1798
  let responseId: string | undefined; // real response.id once known
1580
1799
  // Open text streams keyed by Responses item_id (textStart once per id).
1581
1800
  const openTextStreams = new Set<string>();
1582
- // OA-11 reasoning-block state. `openReasoning`: rs_ id → the message id its
1801
+ // Reasoning-block state (reasoning from the terminal output). `openReasoning`: rs_ id → the message id its
1583
1802
  // block opened in (at `output_item.added{reasoning}`), awaiting its fill from
1584
1803
  // the terminal output; per-response (cleared by `resetResponseState`).
1585
1804
  // `filledReasoning`: every rs_ id whose block has been filled — normalizer-
@@ -1587,19 +1806,19 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1587
1806
  // response closed and must dedupe against it (single source per rs_ id).
1588
1807
  const openReasoning = new Map<string, string>();
1589
1808
  const filledReasoning = new Set<string>();
1590
- // OA-14 phase state. `pendingPhase`: message item id → the phase its raw
1809
+ // Phase state (the phase read at the raw add). `pendingPhase`: message item id → the phase its raw
1591
1810
  // `output_item.added` announced, awaiting that item's `text.start`
1592
1811
  // (per-response). `carriedPhase`: item id → the phase that rode its
1593
1812
  // `text.start` — normalizer-lifetime, because the run-item it retires
1594
1813
  // `ext.openai.late-phase` against lands AFTER the response closed.
1595
1814
  const pendingPhase = new Map<string, string>();
1596
1815
  const carriedPhase = new Map<string, string>();
1597
- // PH-2 (draft.4 stage 2): text stream ids whose `text.start` already set the
1816
+ // The first-class phase (draft.4): text stream ids whose `text.start` already set the
1598
1817
  // first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
1599
1818
  // `text.end` fields learned for a round close that is STASHED (deferred until
1600
1819
  // its tool results land) — consumed by `emitRoundClose`.
1601
1820
  const interimAtStart = new Set<string>();
1602
- const stashedEndFields = new Map<string, { phase?: string; providerMetadata?: AgProviderMeta }>();
1821
+ const stashedEndFields = new Map<string, { phase?: string; providerMetadata?: AgProviderMeta; citations?: AgCitation[] }>();
1603
1822
  // O1 (fold/flush option 1): callId → the askId of the `hitl.ask{approval}`
1604
1823
  // emitted for it. A deferred round whose still-pending call has one flushes
1605
1824
  // as `paused` naming that ask (INV-FLUSH (2)).
@@ -1647,17 +1866,20 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1647
1866
  let lastTopLevelTurnId: string | undefined;
1648
1867
  // Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
1649
1868
  let handoffOrdinal = 0;
1869
+ // Per-invoke ordinal for a derived id (INV-BLOCK, SPEC:767) when a native
1870
+ // item carries no id the facet can key on.
1871
+ let derivedOrdinal = 0;
1650
1872
  // Open handoff brackets, keyed by the transfer call's callId (paired turnId
1651
1873
  // + the SAME parentTurnId `subagentStart` used — `subagentDone` must replay
1652
1874
  // 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,
1875
+ // convention). Matched by callId,
1654
1876
  // not FIFO, because agents-core <=0.8.0 opens a bracket for EVERY transfer
1655
1877
  // the model calls but runs only the first: a bracket closes at
1656
1878
  // `handoff_occurred` for its own call, or at that call's `tool_output` (the
1657
1879
  // handoff never ran).
1658
1880
  const openHandoffs: { turnId: string; parentTurnId: string; callId: string }[] = [];
1659
1881
 
1660
- /** HO-2: remove and return the open bracket for `callId`, if any. */
1882
+ /** Remove and return the open bracket for `callId`, if any. */
1661
1883
  function takeOpenHandoff(callId: string): { turnId: string; parentTurnId: string; callId: string } | undefined {
1662
1884
  const i = openHandoffs.findIndex((h) => h.callId === callId);
1663
1885
  if (i === -1) return undefined;
@@ -1675,13 +1897,93 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1675
1897
  // string so argBuffers is primarily for the fallback path.
1676
1898
  const instanceArgBuffers = new Map<string, string>();
1677
1899
 
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.
1900
+ // Refusal tracking (T5c). Set when a refusal event streams, or when a
1901
+ // `message_output_created` run-item carries a `refusal` content part BEFORE
1902
+ // its response's terminal event (a synthetic order); the terminal arm also
1903
+ // reads the refusal from its own `response.output` (`terminalHasRefusal`),
1904
+ // which is the live order: the run-item lands after the close. Cleared on
1905
+ // every response close and at every `response.created`, so a late run-item's
1906
+ // refusal never reaches the next round.
1683
1907
  let pendingRefusal = false;
1684
1908
 
1909
+ // Refusal text (SPEC §8.0 graceful degradation: a native event the
1910
+ // normalizer can map is never dropped silently). A `refusal` content part's
1911
+ // text is a `text` block in the round's message, id `<item id>:refusal` (the
1912
+ // same item can also carry an `output_text` part, whose block id is the item
1913
+ // id), its `text.start` carrying `providerMetadata.type: "refusal"`, the
1914
+ // part's own wire discriminant and the marker a replay reads to send a
1915
+ // refusal part back, beside the item's `phase` marker as an output_text
1916
+ // block carries it. ONE source per round:
1917
+ // - the raw `response.refusal.delta` / `.done` events, when any arrived;
1918
+ // - else the refusal part itself, from whichever comes first of the
1919
+ // terminal output (read before the round closes) and a
1920
+ // `message_output_created` run-item that lands while the round is open.
1921
+ // A run-item that lands after the close, with no copy emitted, rides
1922
+ // `ext.openai.late-message` (the message is sealed).
1923
+ // The source is chosen per round, not matched per item id: a run-item's ids
1924
+ // can be a different id space from the raw `item_id`s (the OpenRouter
1925
+ // surface mints `msg_tmp_` run-item ids), where an id match would copy the
1926
+ // text twice.
1927
+ // `openRefusalBlocks`: this response's refusal blocks not yet ended;
1928
+ // `refusalBlocks`: every refusal block this response opened (a repeated
1929
+ // `.done` never reopens one); `refusalTextEmitted`: the round has its
1930
+ // refusal text, cleared at `response.created` only, because the run-item
1931
+ // that reads it lands after the round closed. `refusalCarriedPhase`: item id
1932
+ // → the phase marker its refusal block carried (normalizer-lifetime, like
1933
+ // `carriedPhase`, which stays the output_text blocks' own record).
1934
+ const openRefusalBlocks = new Set<string>();
1935
+ const refusalBlocks = new Set<string>();
1936
+ let refusalTextEmitted = false;
1937
+ const refusalCarriedPhase = new Map<string, string>();
1938
+
1939
+ /** The item's vendor phase marker for a refusal block's `text.start`: the one
1940
+ * announced at `output_item.added`, else the one an output_text block of the
1941
+ * same item already carried. */
1942
+ function refusalItemPhase(itemId: string): string | undefined {
1943
+ return pendingPhase.get(itemId) ?? carriedPhase.get(itemId);
1944
+ }
1945
+
1946
+ /** A refusal block id not yet used this response, for the whole-part sources
1947
+ * (an id-less item keys on the message id). */
1948
+ function freshRefusalBlockId(itemId: string | undefined, mId: string): string {
1949
+ const base = `${itemId ?? mId}:refusal`;
1950
+ let id = base;
1951
+ for (let k = 2; refusalBlocks.has(id); k++) id = `${base}:${k}`;
1952
+ return id;
1953
+ }
1954
+
1955
+ /** Open refusal block `blockId` in message `mId`. The phase marker rides
1956
+ * `text.start` as on an output_text block (the first-class `phase:"interim"`
1957
+ * for "commentary"), and is recorded as carried for the late run-item. */
1958
+ function openRefusalBlock(blockId: string, mId: string, phase: string | undefined, itemId: string | undefined): void {
1959
+ const startMeta = openaiProviderMeta({ phase, type: "refusal" });
1960
+ const interim = interimPhase(phase);
1961
+ a.textStart(blockId, mId, {
1962
+ role: "assistant",
1963
+ ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
1964
+ ...(interim !== undefined ? { phase: interim } : {}),
1965
+ });
1966
+ if (phase !== undefined && itemId !== undefined) refusalCarriedPhase.set(itemId, phase);
1967
+ openRefusalBlocks.add(blockId);
1968
+ refusalBlocks.add(blockId);
1969
+ refusalTextEmitted = true;
1970
+ }
1971
+
1972
+ /** A whole refusal part as one block: start, the text as one delta (none for
1973
+ * an empty text), end. */
1974
+ function emitWholeRefusal(blockId: string, mId: string, text: string, phase: string | undefined, itemId: string | undefined): void {
1975
+ openRefusalBlock(blockId, mId, phase, itemId);
1976
+ if (text.length > 0) a.textDelta(blockId, mId, text, { cumulative: false });
1977
+ a.textEnd(blockId, mId);
1978
+ openRefusalBlocks.delete(blockId);
1979
+ }
1980
+
1981
+ /** End every refusal block the stream left open (no `.done` before the close). */
1982
+ function endOpenRefusalBlocks(mId: string): void {
1983
+ for (const blockId of openRefusalBlocks) a.textEnd(blockId, mId);
1984
+ openRefusalBlocks.clear();
1985
+ }
1986
+
1685
1987
  // ── Task 4b: defer a round's close past its pending tool results ───────────
1686
1988
  // (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
1687
1989
  // AFTER `response.completed` — closing at native-close time would put a later
@@ -1700,19 +2002,121 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1700
2002
  * Register `callId` as pending a `tool.done` under the CURRENT open turn
1701
2003
  * (Task 4b). Shared by the raw `response.output_item.added` function_call
1702
2004
  * 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
2005
+ * (the 2026-07-03 SDK-bump adaptation) — both start a call
1704
2006
  * whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
1705
2007
  * is open (defensive; every caller already calls `ensureResponseOpen()` first).
1706
2008
  */
1707
2009
  function registerPendingTool(callId: string): void {
1708
- if (turnId === undefined) return;
1709
- let pending = pendingToolsByTurn.get(turnId);
2010
+ registerPendingToolFor(turnId, callId);
2011
+ }
2012
+
2013
+ /** Register `callId` as pending a `tool.done` under round `tid`. */
2014
+ function registerPendingToolFor(tid: string | undefined, callId: string): void {
2015
+ if (tid === undefined) return;
2016
+ let pending = pendingToolsByTurn.get(tid);
1710
2017
  if (pending === undefined) {
1711
2018
  pending = new Set<string>();
1712
- pendingToolsByTurn.set(turnId, pending);
2019
+ pendingToolsByTurn.set(tid, pending);
1713
2020
  }
1714
2021
  pending.add(callId);
1715
- turnIdByToolCallId.set(callId, turnId);
2022
+ turnIdByToolCallId.set(callId, tid);
2023
+ }
2024
+
2025
+ // ── Built-in round attach ───────────────────────────────────────────────────
2026
+ // agents-core streams a response's built-in call run-items (`tool_called`,
2027
+ // `tool_search_called`) after its `response.completed`, so the round has
2028
+ // already reached its terminal when they land. A round whose terminal
2029
+ // `response.output` lists a built-in call (see BUILTIN_OUTPUT_ITEM_TYPES)
2030
+ // defers its close as §8.0 item 14 defers a round for its pending tool
2031
+ // results, and each late run-item attaches to THAT round's turn and message
2032
+ // (never a turn opened for it). The close is released:
2033
+ // - when every listed call has its run-item and every pending result has
2034
+ // landed (`maybeReleaseRound`);
2035
+ // - at the next `response.created`, when the round still waits only on
2036
+ // listed calls whose run-item never streamed (agents-core can suppress
2037
+ // one), so the new response keeps its own turn; those calls stop being
2038
+ // the round's;
2039
+ // - at flush, per INV-FLUSH (2).
2040
+ // A listed `mcp_approval_request` becomes a pending call of its round when
2041
+ // its `tool_called` lands, and its answer (`mcp_approval_response`) closes
2042
+ // it; with no answer, the round flushes paused naming its ask (INV-FLUSH
2043
+ // (2)). `listedBuiltinsByTurn`: round → listed item ids still waiting.
2044
+ // `builtinTurnByItemId`: listed item id → its round.
2045
+ // `seenBuiltinItemIds`: built-in items whose run-item already landed (one
2046
+ // that lands before its terminal, a synthetic order), so the terminal never
2047
+ // lists them.
2048
+ const listedBuiltinsByTurn = new Map<string, Set<string>>();
2049
+ const builtinTurnByItemId = new Map<string, string>();
2050
+ const seenBuiltinItemIds = new Set<string>();
2051
+ // Approval requests an `mcp_approval_response` has closed in this invoke.
2052
+ const answeredRequests = new Set<string>();
2053
+
2054
+ /** List round `tid`'s built-in calls (those whose run-item has not landed). */
2055
+ /** List round `tid`'s built-in calls whose run-item has not landed. When
2056
+ * it lists any, the round's `message` items are listed too, so their
2057
+ * `message_output_created` (and the citations it carries) lands while the
2058
+ * round's close is still deferred. */
2059
+ function listBuiltins(tid: string, items: readonly TerminalBuiltinItem[], messageIds: readonly string[]): string[] {
2060
+ const ids: string[] = [];
2061
+ for (const item of items) {
2062
+ if (seenBuiltinItemIds.has(item.id)) continue;
2063
+ ids.push(item.id);
2064
+ builtinTurnByItemId.set(item.id, tid);
2065
+ }
2066
+ if (ids.length === 0) return ids;
2067
+ for (const id of messageIds) {
2068
+ if (seenBuiltinItemIds.has(id)) continue;
2069
+ ids.push(id);
2070
+ builtinTurnByItemId.set(id, tid);
2071
+ }
2072
+ listedBuiltinsByTurn.set(tid, new Set(ids));
2073
+ return ids;
2074
+ }
2075
+
2076
+ /** The stashed round a late built-in run-item belongs to: the round whose
2077
+ * terminal listed `key`, else, when no response is open, the invoke's last
2078
+ * round if its close is still stashed (a run-item its terminal did not
2079
+ * list). Undefined when neither holds. */
2080
+ function lateBuiltinRound(key: string | undefined): { tid: string; mId: string } | undefined {
2081
+ const listedTid = key !== undefined ? builtinTurnByItemId.get(key) : undefined;
2082
+ const tid = listedTid ?? (turnId === undefined ? lastTopLevelTurnId : undefined);
2083
+ if (tid === undefined) return undefined;
2084
+ const stashed = stashedCloseByTurn.get(tid);
2085
+ return stashed !== undefined ? { tid, mId: stashed.msgId } : undefined;
2086
+ }
2087
+
2088
+ /** The listed item `key` has what it waited for: drop it, and release its
2089
+ * round if nothing else keeps the round open. */
2090
+ function drainListedBuiltin(key: string | undefined): void {
2091
+ if (key === undefined) return;
2092
+ const tid = builtinTurnByItemId.get(key);
2093
+ if (tid === undefined) return;
2094
+ const listed = listedBuiltinsByTurn.get(tid);
2095
+ if (listed === undefined || !listed.delete(key)) return;
2096
+ maybeReleaseRound(tid);
2097
+ }
2098
+
2099
+ /** Release round `tid`'s stashed close when no pending result and no listed
2100
+ * built-in call keeps it open. */
2101
+ function maybeReleaseRound(tid: string): void {
2102
+ const stashed = stashedCloseByTurn.get(tid);
2103
+ if (stashed === undefined) return;
2104
+ if ((pendingToolsByTurn.get(tid)?.size ?? 0) > 0) return;
2105
+ if ((listedBuiltinsByTurn.get(tid)?.size ?? 0) > 0) return;
2106
+ stashedCloseByTurn.delete(tid);
2107
+ listedBuiltinsByTurn.delete(tid);
2108
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
2109
+ }
2110
+
2111
+ /** At a new `response.created`: every round still waiting on listed calls
2112
+ * whose run-item never streamed stops waiting on them, and is released if
2113
+ * no pending result keeps it open. */
2114
+ function releaseListedAtNextResponse(): void {
2115
+ for (const [tid, listed] of [...listedBuiltinsByTurn]) {
2116
+ listed.clear();
2117
+ listedBuiltinsByTurn.delete(tid);
2118
+ maybeReleaseRound(tid);
2119
+ }
1716
2120
  }
1717
2121
  // A round's close is MORE than `closeTurnDone`: `reduce()`'s message.end
1718
2122
  // handler (SPEC §5.0 INV-MSG, same enforcement commit) clears the message's
@@ -1741,7 +2145,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1741
2145
  * whichever values are live right now (immediate path) or were captured at
1742
2146
  * defer time (drain path) — same three calls either way.
1743
2147
  */
1744
- /** PH-2: is `streamId`'s text.end still pending in a STASHED round close
2148
+ /** Is `streamId`'s text.end still pending in a STASHED round close
1745
2149
  * (a deferred tool round), i.e. not yet emitted? */
1746
2150
  function isStashedTextStream(streamId: string): boolean {
1747
2151
  for (const stashed of stashedCloseByTurn.values()) {
@@ -1752,10 +2156,21 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1752
2156
 
1753
2157
  function endStashedTextStreams(mId: string, textStreamIds: readonly string[]): void {
1754
2158
  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);
2159
+ // Citations and a phase learned while this close sat stashed ride its
2160
+ // text.end, in the live path's field order.
2161
+ const f = stashedEndFields.get(streamId);
1757
2162
  stashedEndFields.delete(streamId);
1758
- a.textEnd(streamId, mId, endFields);
2163
+ a.textEnd(
2164
+ streamId,
2165
+ mId,
2166
+ f === undefined
2167
+ ? undefined
2168
+ : {
2169
+ ...(f.citations !== undefined ? { citations: f.citations } : {}),
2170
+ ...(f.providerMetadata !== undefined ? { providerMetadata: f.providerMetadata } : {}),
2171
+ ...(f.phase !== undefined ? { phase: f.phase } : {}),
2172
+ },
2173
+ );
1759
2174
  }
1760
2175
  }
1761
2176
 
@@ -1802,6 +2217,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1802
2217
  function releaseAllDeferredCloses(): void {
1803
2218
  for (const [tid, stashed] of stashedCloseByTurn) releaseDeferredClose(tid, stashed);
1804
2219
  stashedCloseByTurn.clear();
2220
+ listedBuiltinsByTurn.clear();
1805
2221
  }
1806
2222
 
1807
2223
  /**
@@ -1812,9 +2228,16 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1812
2228
  * immediately via `endOpenStreamsAndCloseMessage` — an errored round's
1813
2229
  * pending results are moot, by design).
1814
2230
  */
1815
- function finishOrDeferRound(tid: string, mId: string, textStreamIds: readonly string[], fields: TurnDoneFields): void {
2231
+ function finishOrDeferRound(
2232
+ tid: string,
2233
+ mId: string,
2234
+ textStreamIds: readonly string[],
2235
+ fields: TurnDoneFields,
2236
+ listing: { builtins: readonly TerminalBuiltinItem[]; messageIds: readonly string[] } = { builtins: [], messageIds: [] },
2237
+ ): void {
2238
+ const listed = listBuiltins(tid, listing.builtins, listing.messageIds);
1816
2239
  const pending = pendingToolsByTurn.get(tid);
1817
- if (pending !== undefined && pending.size > 0) {
2240
+ if ((pending !== undefined && pending.size > 0) || listed.length > 0) {
1818
2241
  stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
1819
2242
  return;
1820
2243
  }
@@ -1827,7 +2250,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1827
2250
  * somehow absent (defensive — the spike confirms the id is always present at start).
1828
2251
  * Returns the close-once key (the real response.id, else the synthesized turnId),
1829
2252
  * or `undefined` when the response has already been closed (caller must no-op).
1830
- * `model` (OA-12) rides `message.start.model` — only the authoritative
2253
+ * `model` (the per-message model) rides `message.start.model` — only the authoritative
1831
2254
  * `response.created` open passes it; a defensive open never invents one.
1832
2255
  */
1833
2256
  function ensureResponseOpen(respId?: string, model?: string): string | undefined {
@@ -1878,7 +2301,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1878
2301
  a.openTurn(opened, threadId);
1879
2302
  return { turnId: opened, messageId: `${callId}:result` };
1880
2303
  }
1881
- // Approve-all (the D3 pin, 2026-09-24): the resuming invoke can
2304
+ // Approve-all (pinned 2026-09-24): the resuming invoke can
1882
2305
  // replay SEVERAL results before its response. While the resume turn is
1883
2306
  // open with no assistant message yet (turnId set, msgId unset — a state
1884
2307
  // only this helper creates), each further result joins THAT turn as its
@@ -1915,11 +2338,13 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1915
2338
  const key = responseId ?? turnId;
1916
2339
  if (key !== undefined) closedResponses.add(key);
1917
2340
  openTextStreams.clear();
1918
- // OA-11: an rs_ block opened but never filled (e.g. `response.failed`) stays
2341
+ // An rs_ block opened but never filled (e.g. `response.failed`) stays
1919
2342
  // as the spec's own unsealed-block outcome (INV-FLUSH (3)); forget it so a
1920
2343
  // late run-item for it takes the existing `late-reasoning` degrade.
1921
2344
  openReasoning.clear();
1922
2345
  pendingPhase.clear();
2346
+ openRefusalBlocks.clear();
2347
+ refusalBlocks.clear();
1923
2348
  turnId = undefined;
1924
2349
  msgId = undefined;
1925
2350
  responseId = undefined;
@@ -1934,6 +2359,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1934
2359
  function closeResponse(): void {
1935
2360
  if (msgId !== undefined) {
1936
2361
  for (const streamId of openTextStreams) a.textEnd(streamId, msgId);
2362
+ endOpenRefusalBlocks(msgId);
1937
2363
  a.closeMessage(msgId);
1938
2364
  }
1939
2365
  resetResponseState();
@@ -1943,8 +2369,16 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1943
2369
  function driveRawResponsesEvent(ev: OpenAIRawResponsesEvent): void {
1944
2370
  switch (ev.type) {
1945
2371
  case "response.created": {
2372
+ // A new response: a refusal recorded by a late run-item belongs to the
2373
+ // response before it, never to this one; so does its refusal text.
2374
+ pendingRefusal = false;
2375
+ refusalTextEmitted = false;
2376
+ // A round still waiting only on listed built-in calls whose run-item
2377
+ // never streamed is released before this response's turn opens (see
2378
+ // "Built-in round attach").
2379
+ releaseListedAtNextResponse();
1946
2380
  // Authoritative turn open — the real response.id is present at start.
1947
- // OA-12: so is the resolved model id (JsonValue boundary: string-guarded).
2381
+ // So is the resolved model id (JsonValue boundary: string-guarded).
1948
2382
  const rawModelId: unknown = ev.response.model;
1949
2383
  ensureResponseOpen(
1950
2384
  ev.response.id,
@@ -1957,11 +2391,11 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1957
2391
  if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
1958
2392
  if (!openTextStreams.has(ev.item_id)) {
1959
2393
  openTextStreams.add(ev.item_id);
1960
- // OA-14: the phase announced at output_item.added rides text.start
2394
+ // The phase announced at output_item.added rides text.start
1961
2395
  // (R&D items 13+17, stage 1, ruled 2026-09-23; vercel parity c4f5981).
1962
2396
  const phase = pendingPhase.get(ev.item_id);
1963
2397
  const startMeta = openaiProviderMeta({ phase });
1964
- // PH-2 (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
2398
+ // The first-class phase (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
1965
2399
  // the first delta ⇒ the first-class `phase` goes on text.start.
1966
2400
  const interim = interimPhase(phase);
1967
2401
  a.textStart(ev.item_id, msgId, {
@@ -1980,7 +2414,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1980
2414
  return;
1981
2415
  }
1982
2416
  case "response.output_text.done": {
1983
- // NO-OP (audit M22): the citations carrier — `message_output_created` — is
2417
+ // NO-OP: the citations carrier — `message_output_created` — is
1984
2418
  // the authoritative text-end source (it also reports refusal parts and
1985
2419
  // arrives with the annotated part, so closing here would emit `text.end`
1986
2420
  // BEFORE citations are known). The stream stays in `openTextStreams`;
@@ -1989,8 +2423,34 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
1989
2423
  // `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
1990
2424
  return;
1991
2425
  }
2426
+ case "response.refusal.delta": {
2427
+ // Refusal text streams like output_text (see "Refusal text"): the raw
2428
+ // refusal events are this round's source once any arrives.
2429
+ ensureResponseOpen();
2430
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
2431
+ pendingRefusal = true;
2432
+ const blockId = `${ev.item_id}:refusal`;
2433
+ if (!refusalBlocks.has(blockId)) openRefusalBlock(blockId, msgId, refusalItemPhase(ev.item_id), ev.item_id);
2434
+ a.textDelta(blockId, msgId, ev.delta, { cumulative: false });
2435
+ return;
2436
+ }
2437
+ case "response.refusal.done": {
2438
+ // Ends the part's block. With no delta before it, its `refusal` is the
2439
+ // whole text. A refusal part carries no annotations, so unlike
2440
+ // `response.output_text.done` nothing arrives later for its `text.end`.
2441
+ ensureResponseOpen();
2442
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
2443
+ pendingRefusal = true;
2444
+ const blockId = `${ev.item_id}:refusal`;
2445
+ if (!refusalBlocks.has(blockId)) {
2446
+ emitWholeRefusal(blockId, msgId, ev.refusal, refusalItemPhase(ev.item_id), ev.item_id);
2447
+ return;
2448
+ }
2449
+ if (openRefusalBlocks.delete(blockId)) a.textEnd(blockId, msgId);
2450
+ return;
2451
+ }
1992
2452
  case "response.output_item.added": {
1993
- // OA-11: a reasoning item OPENS its block here — id only, the added event
2453
+ // A reasoning item OPENS its block here — id only, the added event
1994
2454
  // carries no replayable content — so the block takes its wire position
1995
2455
  // ahead of the `fc_` it precedes (§5 block insertion order, SPEC:763;
1996
2456
  // §10 item 4's stateless loop replays `rs_` before its `fc_`). It is
@@ -2002,7 +2462,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2002
2462
  if (typeof rsId === "string") openReasoningBlock(rsId);
2003
2463
  return;
2004
2464
  }
2005
- // OA-14: a message item announces its `phase` here, BEFORE its first
2465
+ // A message item announces its `phase` here, BEFORE its first
2006
2466
  // text delta — record it for that item's `text.start`. Record only: no
2007
2467
  // response open, no emit, so an absent/null/non-string/empty phase is
2008
2468
  // byte-identical to a stream without this event.
@@ -2103,11 +2563,22 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2103
2563
  if (ensureResponseOpen(ev.response.id) === undefined) return;
2104
2564
  if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
2105
2565
  if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
2106
- // OA-11: fill every reasoning block from THIS output (the replayable blob)
2566
+ // Fill every reasoning block from THIS output (the replayable blob)
2107
2567
  // FIRST — before any branch below can emit message.end / turn.* (INV-MSG:
2108
2568
  // a reasoning.* event must never target a sealed message; core's reduce()
2109
2569
  // does not check that for reasoning.*, so the order is this facet's job).
2110
2570
  fillReasoningFromTerminalOutput(ev.response.output);
2571
+ // Refusal text (see "Refusal text"): with no refusal event in this
2572
+ // round, the terminal output's refusal parts are its source, emitted
2573
+ // now while the message is open (the run-item lands after the close).
2574
+ // Then any refusal block the stream left open ends here, before every
2575
+ // branch below closes the message.
2576
+ if (!refusalTextEmitted) {
2577
+ for (const part of terminalRefusalParts(ev.response.output)) {
2578
+ emitWholeRefusal(freshRefusalBlockId(part.itemId, msgId), msgId, part.text, part.phase, part.itemId);
2579
+ }
2580
+ }
2581
+ endOpenRefusalBlocks(msgId);
2111
2582
  // Snapshot before any deferral: `resetResponseState()` below always
2112
2583
  // clears these, but a deferred close needs them later (Task 4b).
2113
2584
  const currentTurnId = turnId;
@@ -2115,6 +2586,10 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2115
2586
  const textStreamIds = Array.from(openTextStreams);
2116
2587
  const reason = ev.response.incomplete_details?.reason;
2117
2588
  const usage = mapUsage(ev.response.usage);
2589
+ // The built-in calls (and, with them, the messages) this response
2590
+ // lists, whose run-items land after this event (see "Built-in round
2591
+ // attach").
2592
+ const listing = { builtins: terminalBuiltinItems(ev.response.output), messageIds: terminalMessageIds(ev.response.output) };
2118
2593
  // `status` is OPTIONAL upstream and its enum is OPEN ("clients must
2119
2594
  // accept additional values"), so it is read through `unknown` + a typeof
2120
2595
  // guard rather than trusted through the declared union — this is the
@@ -2126,7 +2601,8 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2126
2601
  const unsuccessfulStatus =
2127
2602
  typeof rawStatus === "string" && UNSUCCESSFUL_RESPONSE_STATUSES.has(rawStatus) ? rawStatus : undefined;
2128
2603
  // Decision tree (mirrors the canonical model, A1):
2129
- // refusal recorded → closeTurnDone success, finishReason:"refusal"
2604
+ // refusal (in the terminal
2605
+ // output, or recorded) → closeTurnDone success, finishReason:"refusal"
2130
2606
  // content_filter → closeTurnDone error-outcome + safety signal
2131
2607
  // any other incomplete → closeTurnError{code:reason, usage}
2132
2608
  // completed, status failed/
@@ -2137,12 +2613,12 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2137
2613
  // ENTIRE close (message + turn) instead of emitting (INV-MSG).
2138
2614
  // closeTurnError does NOT defer (an errored round's pending results are
2139
2615
  // moot, by design) — it still closes the message immediately here.
2140
- if (pendingRefusal) {
2616
+ if (pendingRefusal || terminalHasRefusal(ev.response.output)) {
2141
2617
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
2142
2618
  outcome: { type: "success" },
2143
2619
  finishReason: "refusal",
2144
2620
  ...(usage !== undefined ? { usage } : {}),
2145
- });
2621
+ }, listing);
2146
2622
  } else if (reason === "content_filter") {
2147
2623
  const safety: AgSafety[] = [{ category: "content_filter", blocked: true }];
2148
2624
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
@@ -2150,7 +2626,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2150
2626
  ...finishReasonFields(reason),
2151
2627
  safety,
2152
2628
  ...(usage !== undefined ? { usage } : {}),
2153
- });
2629
+ }, listing);
2154
2630
  } else if (ev.type === "response.incomplete") {
2155
2631
  endOpenStreamsAndCloseMessage();
2156
2632
  a.closeTurnError(currentTurnId, {
@@ -2193,10 +2669,10 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2193
2669
  } else {
2194
2670
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
2195
2671
  outcome: { type: "success" },
2196
- // OA-15: an unmapped native reason also carries finishReasonRaw.
2672
+ // An unmapped native reason also carries finishReasonRaw.
2197
2673
  ...finishReasonFields(reason),
2198
2674
  ...(usage !== undefined ? { usage } : {}),
2199
- });
2675
+ }, listing);
2200
2676
  }
2201
2677
  resetResponseState();
2202
2678
  return;
@@ -2214,7 +2690,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2214
2690
  // message/code/usage (§4), so per §8.0 item 33 it rides verbatim in a
2215
2691
  // carrier the §5 table folds, never as remedy data on the terminal: an
2216
2692
  // adapter NOTICE message immediately BEFORE the closing turn.error, in
2217
- // this turn (rd-15):
2693
+ // this turn (remedy-shaped vendor data):
2218
2694
  // message.start {role:"notice", noticeSource:"adapter"} →
2219
2695
  // one text block, text = `detailed_explanation` verbatim (else
2220
2696
  // error.message), text.start `_meta["openai/misalignment"]` = the
@@ -2270,7 +2746,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2270
2746
  return;
2271
2747
  }
2272
2748
  // Duplicate raw families IGNORED per the canonical model:
2273
- // response.output_text.done is its own no-op arm above (audit M22);
2749
+ // response.output_text.done is its own no-op arm above;
2274
2750
  // response.output_item.done, response.in_progress, content_part.* are not
2275
2751
  // authoritative sources.
2276
2752
  default:
@@ -2278,27 +2754,70 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2278
2754
  }
2279
2755
  }
2280
2756
 
2757
+ /**
2758
+ * A `message_output_created` run-item's refusal part (see "Refusal text").
2759
+ * - The round already has its refusal text (the raw events or the terminal
2760
+ * output): no second copy. The item's phase marker, if that block did
2761
+ * not carry it, rides `ext.openai.late-phase` (the block's `text.end` is
2762
+ * out: case (iii) of the output_text arm), once per item: an item that
2763
+ * also carries an output_text part leaves it to that part's arm.
2764
+ * - The round is open (a synthetic order): the part is the source.
2765
+ * - The round closed with no copy: the message is sealed, so the text rides
2766
+ * `ext.openai.late-message` with `partType: "refusal"`, anchored to the
2767
+ * round like the id-less late message.
2768
+ */
2769
+ function driveRunItemRefusal(item: OpenAIAssistantMessageItem, text: string): void {
2770
+ const itemPhase = vendorPhase(item.phase);
2771
+ if (refusalTextEmitted) {
2772
+ if (
2773
+ item.id !== undefined &&
2774
+ itemPhase !== undefined &&
2775
+ refusalCarriedPhase.get(item.id) !== itemPhase &&
2776
+ !item.content.some((p) => p.type === "output_text")
2777
+ ) {
2778
+ a.emitExt("openai", "late-phase", { itemId: item.id, phase: itemPhase });
2779
+ }
2780
+ return;
2781
+ }
2782
+ if (msgId !== undefined) {
2783
+ emitWholeRefusal(freshRefusalBlockId(item.id, msgId), msgId, text, itemPhase, item.id);
2784
+ return;
2785
+ }
2786
+ const anchor = turnId ?? lastTopLevelTurnId;
2787
+ a.emitExt("openai", "late-message", {
2788
+ text,
2789
+ partType: "refusal",
2790
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
2791
+ ...(anchor !== undefined ? { forTurnId: anchor } : {}),
2792
+ ...(itemPhase !== undefined ? { phase: itemPhase } : {}),
2793
+ });
2794
+ }
2795
+
2281
2796
  /** End any still-open text streams (defensive), then close the open message. */
2282
2797
  function endOpenStreamsAndCloseMessage(): void {
2283
2798
  if (msgId !== undefined) {
2284
2799
  for (const streamId of openTextStreams) a.textEnd(streamId, msgId);
2800
+ endOpenRefusalBlocks(msgId);
2285
2801
  a.closeMessage(msgId);
2286
2802
  }
2287
2803
  }
2288
2804
 
2289
2805
  /**
2290
2806
  * Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
2291
- * citations source (audit M22). The text itself already streamed from the raw
2807
+ * citations source. The text itself already streamed from the raw
2292
2808
  * `response.output_text.delta` path — this MUST NOT re-emit it — but the
2293
2809
  * `output_text` part's annotations are only known here (they are not present on
2294
2810
  * `response.output_text.done`), so THIS is where the matching open text stream
2295
2811
  * actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
2296
2812
  * 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).
2813
+ * `refusal` part sets `pendingRefusal`, which counts only when the run-item
2814
+ * lands before its response's terminal event (a synthetic order). On the
2815
+ * live wire it lands after the close, and the terminal arm reads the round's
2816
+ * refusal from its own `response.output` (`terminalHasRefusal`). Its text is
2817
+ * a single-source fallback (`driveRunItemRefusal`, see "Refusal text").
2299
2818
  *
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
2819
+ * Correlation (id FIRST, FIFO fallback; the narration-phase rule, stage
2820
+ * 1): on the direct OpenAI wire the raw delta's `item_id` and the
2302
2821
  * run-item's `rawItem.id` are the SAME id (all 8 openai corpus seeds), so the
2303
2822
  * stream is matched by id — a completion can no longer land on an earlier
2304
2823
  * part's stream when two are open. Only when the id is unknown to
@@ -2316,7 +2835,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2316
2835
  * annotations, though, they are NOT yet lost anywhere else — silently dropping
2317
2836
  * them here would violate Tenet 6. Route them losslessly through the facet's
2318
2837
  * existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
2319
- * the run-item id + the raw annotations array verbatim (review finding on M22).
2838
+ * the run-item id + the raw annotations array verbatim.
2320
2839
  * A part with no annotations has nothing to lose — the plain `continue` stays.
2321
2840
  *
2322
2841
  * ID-LESS SYNTHESIZED MESSAGE (agents-core ≥0.13.2): `errorHandlers.
@@ -2345,9 +2864,22 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2345
2864
  * never a duplicated or corrupted core stream.
2346
2865
  */
2347
2866
  function driveMessageOutputCreated(item: OpenAIAssistantMessageItem): void {
2867
+ if (item.id !== undefined) seenBuiltinItemIds.add(item.id);
2868
+ driveMessageParts(item);
2869
+ // A listed message has landed; its round may now close (see "Built-in
2870
+ // round attach"), with any citations stashed above on its text.end.
2871
+ drainListedBuiltin(item.id);
2872
+ }
2873
+
2874
+ /** The per-part body of {@link driveMessageOutputCreated} (see its doc). */
2875
+ function driveMessageParts(item: OpenAIAssistantMessageItem): void {
2348
2876
  for (const part of item.content) {
2349
2877
  if (part.type === "refusal") {
2350
2878
  pendingRefusal = true;
2879
+ // The typeof guard is load-bearing: rawItem is envelope-only-validated
2880
+ // wire data, and push() must never throw.
2881
+ const text: unknown = part.refusal;
2882
+ if (typeof text === "string") driveRunItemRefusal(item, text);
2351
2883
  continue;
2352
2884
  }
2353
2885
  if (part.type === "output_text") {
@@ -2368,20 +2900,34 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2368
2900
  ...(item.phase !== undefined ? { phase: item.phase } : {}),
2369
2901
  });
2370
2902
  }
2371
- if (part.annotations !== undefined && part.annotations.length > 0) {
2903
+ const idlessAnnotations = partAnnotations(part);
2904
+ if (idlessAnnotations.length > 0) {
2372
2905
  a.emitExt("openai", "late-citations", {
2373
- annotations: JsonValue.parse(part.annotations),
2906
+ annotations: idlessAnnotations,
2374
2907
  });
2375
2908
  }
2376
2909
  continue;
2377
2910
  }
2378
2911
  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
- });
2912
+ // response already closed — see doc above. While the round's close
2913
+ // is STASHED (deferred for its tool results or built-in calls), this
2914
+ // block's text.end is not out yet, so its url citations ride it (the
2915
+ // phase marker's case (ii) below), and any other annotation takes
2916
+ // the ext carry; a message that lands after the close was released
2917
+ // carries every annotation on the ext.
2918
+ const closedAnnotations = partAnnotations(part);
2919
+ if (closedAnnotations.length > 0) {
2920
+ const split = isStashedTextStream(item.id) ? splitAnnotations(closedAnnotations, part.text) : undefined;
2921
+ if (split?.citations !== undefined) {
2922
+ stashedEndFields.set(item.id, { ...stashedEndFields.get(item.id), citations: split.citations });
2923
+ }
2924
+ const carry = split?.citations !== undefined ? split.unmapped : closedAnnotations;
2925
+ if (carry.length > 0) {
2926
+ a.emitExt("openai", "late-citations", {
2927
+ itemId: item.id,
2928
+ annotations: carry,
2929
+ });
2930
+ }
2385
2931
  }
2386
2932
  // phase (0.14.0): the live wire delivers the FINAL round's
2387
2933
  // message_output_created AFTER response_done has closed the message
@@ -2390,21 +2936,22 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2390
2936
  // (deferred-close) messages ever reach it. Same post-close degrade
2391
2937
  // convention as late-citations: a dedicated itemId-keyed vendor
2392
2938
  // carry, one per phase-bearing part.
2393
- // OA-14: RETIRED when this id's SAME phase already rode its text.start
2939
+ // RETIRED when this id's SAME phase already rode its text.start
2394
2940
  // (the live case); kept — lossless — when only the run-item knows it,
2395
2941
  // or knows a different value.
2396
- // PH-2: null/"" is no marker at all (spec ruling (a)) — neither
2942
+ // A null/"" phase is no marker at all (spec ruling (a)) — neither
2397
2943
  // a carry nor a late-phase ext.
2398
2944
  const lateItemPhase = vendorPhase(item.phase);
2399
2945
  if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
2400
2946
  if (isStashedTextStream(item.id)) {
2401
- // PH-2 case (ii): the round close is STASHED (a deferred tool
2947
+ // Case (ii): the round close is STASHED (a deferred tool
2402
2948
  // round), so this block's text.end is NOT yet emitted — the §5
2403
2949
  // timing rule makes the end the phase's home (ruled
2404
2950
  // 2026-09-23). The marker has a first-class home, so no late-phase.
2405
2951
  const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
2406
2952
  const endMeta = openaiProviderMeta({ phase: lateItemPhase });
2407
2953
  stashedEndFields.set(item.id, {
2954
+ ...stashedEndFields.get(item.id),
2408
2955
  ...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
2409
2956
  ...(interim !== undefined ? { phase: interim } : {}),
2410
2957
  });
@@ -2416,12 +2963,15 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2416
2963
  }
2417
2964
  continue;
2418
2965
  }
2419
- // OA-14: id first, FIFO fallback — see "Correlation" in the doc above.
2966
+ // Id first, FIFO fallback — see "Correlation" in the doc above.
2420
2967
  const streamId =
2421
2968
  item.id !== undefined && openTextStreams.has(item.id) ? item.id : openTextStreams.values().next().value;
2422
2969
  if (streamId === undefined) continue; // defensive: no matching open stream
2423
2970
  openTextStreams.delete(streamId);
2424
- const citations = mapAnnotationsToCitations(part.annotations, part.text);
2971
+ // A url citation rides text.end; any other annotation has no citation
2972
+ // target and takes the ext carry, after the text.end (SPEC:965).
2973
+ const liveSplit = splitAnnotations(partAnnotations(part), part.text);
2974
+ const citations = liveSplit.citations;
2425
2975
  // phase (0.14.0) rides the matching text.end's providerMetadata —
2426
2976
  // PER-PART, not message.metadata: this facet folds a response into ONE
2427
2977
  // message, and a program-driven turn emits multiple message items with
@@ -2429,7 +2979,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2429
2979
  // merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
2430
2980
  const itemPhase = vendorPhase(item.phase);
2431
2981
  const phaseMeta = openaiProviderMeta({ phase: itemPhase });
2432
- // PH-2 case (i): known before this block's text.end ⇒ the end carries
2982
+ // Case (i): known before this block's text.end ⇒ the end carries
2433
2983
  // the first-class phase, unless text.start already did.
2434
2984
  const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
2435
2985
  a.textEnd(
@@ -2443,12 +2993,15 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2443
2993
  }
2444
2994
  : undefined,
2445
2995
  );
2996
+ if (liveSplit.unmapped.length > 0) {
2997
+ a.emitExt("openai", "late-citations", { itemId: item.id ?? streamId, annotations: liveSplit.unmapped });
2998
+ }
2446
2999
  }
2447
3000
  }
2448
3001
  }
2449
3002
 
2450
3003
  /**
2451
- * OA-11: open the reasoning block for `rsId` in the current message — once per
3004
+ * Open the reasoning block for `rsId` in the current message — once per
2452
3005
  * id (a re-announce, or an id already filled, is a no-op). `id` and `itemId`
2453
3006
  * are both the `rs_` id (the run-item path's convention). Called from
2454
3007
  * `output_item.added{reasoning}` so the block takes its WIRE position, and
@@ -2462,7 +3015,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2462
3015
  }
2463
3016
 
2464
3017
  /**
2465
- * OA-11: fill + seal an OPEN reasoning block: one `reasoning.delta` per
3018
+ * Fill + seal an OPEN reasoning block: one `reasoning.delta` per
2466
3019
  * non-empty summary part (`partIndex` = the wire `summary_index`), then
2467
3020
  * `reasoning.opaque` (the replayable ciphertext, `itemId` = rs_) BEFORE
2468
3021
  * `reasoning.end`, so "sealed" means complete (the spec's recommendation;
@@ -2498,7 +3051,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2498
3051
  filledReasoning.add(rsId);
2499
3052
  }
2500
3053
 
2501
- /** OA-11: fill every reasoning block from a terminal event's `response.output`
3054
+ /** Fill every reasoning block from a terminal event's `response.output`
2502
3055
  * (see `terminalReasoningItems` for why this, not `output_item.done`, is the
2503
3056
  * source). An item never announced by `output_item.added` opens here
2504
3057
  * (defensive — position is then the terminal event's). */
@@ -2511,14 +3064,14 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2511
3064
  }
2512
3065
 
2513
3066
  /**
2514
- * Map a `reasoning_item_created` run-item (Task 3, audit M48). Since OA-11 it
3067
+ * Map a `reasoning_item_created` run-item. Since reasoning is sourced from the terminal output it
2515
3068
  * is the FALLBACK source: on the live wire it lands after `response.completed`,
2516
3069
  * whose output already filled the block, so a run-item whose `rs_` id is in
2517
3070
  * `filledReasoning` is a no-op (single source per id — no duplicate block, no
2518
3071
  * `late-reasoning` ext). If raw `output_item.added` opened the block but no
2519
3072
  * terminal output has filled it yet, the run-item fills that block in place.
2520
3073
  * Only with NO raw reasoning events for the id (run-item-only streams) does the
2521
- * pre-OA-11 mapping below still run, unchanged:
3074
+ * run-item-only mapping below still run, unchanged:
2522
3075
  *
2523
3076
  * The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
2524
3077
  * the incremental text/tool-arg deltas elsewhere in this facet), so
@@ -2552,14 +3105,14 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2552
3105
  * never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
2553
3106
  * correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
2554
3107
  * 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
3108
+ * was a genuine loss. Mirrors `ext.openai.late-citations` exactly: route it
3109
+ * through the lossless vendor channel instead of the bare
2557
3110
  * return.
2558
3111
  */
2559
3112
  function driveReasoningItemCreated(item: OpenAIReasoningItem): void {
2560
- // OA-11 dedupe: already filled from the terminal output (or an earlier run-item).
3113
+ // Dedupe: already filled from the terminal output (or an earlier run-item).
2561
3114
  if (item.id !== undefined && filledReasoning.has(item.id)) return;
2562
- // OA-11: raw `output_item.added` opened this block; no terminal output has
3115
+ // Raw `output_item.added` opened this block; no terminal output has
2563
3116
  // filled it yet (synthetic ordering) — fill it in place from the run-item,
2564
3117
  // whose `content[]` IS the raw `summary[]` (one part per index).
2565
3118
  if (msgId !== undefined && item.id !== undefined && openReasoning.has(item.id)) {
@@ -2600,7 +3153,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2600
3153
  ...(itemId !== undefined ? { itemId } : {}),
2601
3154
  });
2602
3155
  }
2603
- // OA-11: a terminal output naming this rs_ later must not open a second block.
3156
+ // A terminal output naming this rs_ later must not open a second block.
2604
3157
  if (itemId !== undefined) filledReasoning.add(itemId);
2605
3158
  }
2606
3159
 
@@ -2616,7 +3169,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2616
3169
  * pending bookkeeping and — if the turn's pending set just drained to empty
2617
3170
  * — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
2618
3171
  * 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).
3172
+ * `tool_output` arm (the 2026-07-03 SDK-bump adaptation).
2620
3173
  */
2621
3174
  /**
2622
3175
  * HO-P, the handoff round release (§8.0 item 14, draft.5). Called at
@@ -2652,10 +3205,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2652
3205
  turnIdByToolCallId.delete(callId);
2653
3206
  }
2654
3207
  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);
3208
+ maybeReleaseRound(sourceTurnId);
2659
3209
  }
2660
3210
 
2661
3211
  function drainPendingTool(callId: string, doneTurnId: string | undefined): void {
@@ -2664,17 +3214,12 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2664
3214
  const pending = pendingToolsByTurn.get(doneTurnId);
2665
3215
  if (pending === undefined) return;
2666
3216
  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
- }
3217
+ // The pending set just drained — emit the deferred message.end +
3218
+ // turn.done immediately after this tool.done, same push() batch
3219
+ // (INV-MSG: the message must still be open when tool.done lands, so
3220
+ // message.end waits for this too), unless a listed built-in call of the
3221
+ // round has yet to land (see "Built-in round attach").
3222
+ if (pending.size === 0) maybeReleaseRound(doneTurnId);
2678
3223
  }
2679
3224
 
2680
3225
  /** True if any shell command in `entries` timed out or exited non-zero. */
@@ -2688,7 +3233,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2688
3233
 
2689
3234
  /**
2690
3235
  * 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;
3236
+ * Computer-Use result (the 2026-07-03 SDK-bump adaptation;
2692
3237
  * `computer_call_result` added by the fixture-drift ratchet finding, same
2693
3238
  * date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
2694
3239
  * (a bare string / content-part union) — `shell_call_output.output` is an
@@ -2707,6 +3252,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2707
3252
  | OpenAIApplyPatchCallResultItem
2708
3253
  | OpenAIComputerCallResultItem
2709
3254
  | OpenAIProgramCallResultItem,
3255
+ executionStatus: string | undefined,
2710
3256
  ): void {
2711
3257
  const toolCallId = rawItem.callId;
2712
3258
  let content: AgBlock[];
@@ -2726,44 +3272,68 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2726
3272
  shellOutputHasError(rawItem.output) || rawItem.status === "incomplete" ? "error" : "ok";
2727
3273
  // The full per-command record (stdout/stderr/exit code) is lossy to
2728
3274
  // collapse into text-only content — carry it verbatim as structuredContent
2729
- // too (mirrors the function_call path's ggui-cache-marker precedent).
3275
+ // too (mirrors the function_call path's cache-marker precedent).
2730
3276
  structuredContent = JsonValue.parse(rawItem.output);
2731
3277
  // The outcome mapping alone cannot recover `status` ('in_progress' vs
2732
3278
  // 'completed' vs absent all map ok) — carry it verbatim, with caller.
2733
3279
  providerMetadata = openaiProviderMeta({
2734
3280
  caller: callerToJson(rawItem.caller),
2735
3281
  status: rawItem.status,
3282
+ executionStatus,
2736
3283
  });
2737
3284
  } else if (rawItem.type === "computer_call_result") {
2738
- // spec §8 item 20's extended discriminant: the screenshot is base64 image
2739
- // data, not text — land it as an AgBlock `file` block (AgSource's
2740
- // `base64` arm) rather than dropping it via the text-only path.
2741
- content = [
2742
- {
2743
- type: "file",
2744
- source: { type: "base64", mediaType: "image/png", data: rawItem.output.data },
2745
- filename: "screenshot.png",
2746
- },
2747
- ];
2748
- // No status/error discriminant exists on this wire arm (unlike shell/apply-patch).
2749
- outcome = "ok";
3285
+ // spec §8 item 20's extended discriminant: the screenshot is image data,
3286
+ // not text — land it as an AgBlock `file` block (AgSource's `base64` arm)
3287
+ // rather than dropping it via the text-only path. The SDK sends a
3288
+ // `data:<media type>;base64,<payload>` URL; AgSource's `base64` arm holds
3289
+ // the base64 text alone with its media type (SPEC.md:140, "must match
3290
+ // bytes"), so the header is split off. A value with no `data:` header
3291
+ // lands verbatim as image/png.
3292
+ const outputPd = rawItem.output.providerData;
3293
+ const file: AgBlock = { type: "file", source: screenshotSource(rawItem.output.data), filename: "screenshot.png" };
3294
+ // A refused action (a declined approval, or an `onSafetyCheck` that
3295
+ // returns false) is the SDK's rejection result: its
3296
+ // `output.providerData.approvalStatus` is "rejected" and its screenshot is
3297
+ // the SDK's 1×1 placeholder. It closes `denied` (§8.0 item 20), with the
3298
+ // SDK's message as a text block before the file block. Every other
3299
+ // computer result closes `ok`.
3300
+ if (outputPd?.approvalStatus === "rejected") {
3301
+ const message = outputPd.message;
3302
+ content = typeof message === "string" && message.length > 0 ? [{ type: "text", text: message }, file] : [file];
3303
+ outcome = "denied";
3304
+ } else {
3305
+ content = [file];
3306
+ outcome = "ok";
3307
+ }
3308
+ // The SDK's own markers, verbatim: the run-item's `executionStatus`
3309
+ // (present only when the action ran), the refusal's
3310
+ // `output.providerData.approvalStatus` and `message`, and the item's
3311
+ // `providerData.acknowledgedSafetyChecks`.
3312
+ providerMetadata = openaiProviderMeta({
3313
+ executionStatus,
3314
+ approvalStatus: outputPd?.approvalStatus,
3315
+ message: outputPd?.message,
3316
+ acknowledgedSafetyChecks: rawItem.providerData?.acknowledgedSafetyChecks,
3317
+ });
2750
3318
  } else if (rawItem.type === "program_output") {
2751
3319
  // 0.14.0 programmatic tool calling: bare-string output (mirrors the
2752
3320
  // apply_patch arm); the CLOSED status enum's `incomplete` -> error
2753
3321
  // (same rule as function_call_result — never success).
2754
3322
  content = rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
2755
3323
  outcome = rawItem.status === "incomplete" ? "error" : "ok";
3324
+ providerMetadata = openaiProviderMeta({ executionStatus });
2756
3325
  } else {
2757
3326
  content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
2758
3327
  outcome = rawItem.status === "failed" ? "error" : "ok";
2759
- providerMetadata = openaiProviderMeta({ caller: callerToJson(rawItem.caller) });
3328
+ providerMetadata = openaiProviderMeta({ caller: callerToJson(rawItem.caller), executionStatus });
2760
3329
  }
2761
3330
  const doneTurnId = resolvePendingTurnId(toolCallId);
2762
3331
  a.toolDone({
2763
3332
  toolCallId,
2764
3333
  content,
2765
3334
  outcome,
2766
- isError: outcome === "error",
3335
+ // A denied close carries no isError (§6 Pattern 4).
3336
+ ...(outcome === "denied" ? {} : { isError: outcome === "error" }),
2767
3337
  ...(structuredContent !== undefined ? { structuredContent } : {}),
2768
3338
  ...(providerMetadata !== undefined ? { providerMetadata } : {}),
2769
3339
  ...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(toolCallId) ?? {})),
@@ -2813,7 +3383,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2813
3383
  /**
2814
3384
  * Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
2815
3385
  * built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
2816
- * — playbook 2026-07-03 SDK-bump adaptation, Finding #1; `computer_call`
3386
+ * — the 2026-07-03 SDK-bump adaptation; `computer_call`
2817
3387
  * added by the fixture-drift ratchet finding, same date). Unlike
2818
3388
  * `function_call` (whose tool-start rides the raw `response.output_item.
2819
3389
  * added` stream — the authoritative source, canonical model A1), this
@@ -2824,11 +3394,12 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2824
3394
  * action/operation arrives complete on this one wrapper), and
2825
3395
  * `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
2826
3396
  * 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.
3397
+ * Like every run-item, this wrapper lands AFTER its response's
3398
+ * `response.completed` (agents-core 0.18.0 streams a response's step items
3399
+ * after the raw loop, run.mjs:1935), so it attaches to the round its
3400
+ * terminal listed, whose close is deferred for it (see "Built-in round
3401
+ * attach"); it opens a response only when none has been seen for it (a
3402
+ * run-item that lands while its response is open joins that response).
2832
3403
  *
2833
3404
  * `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
2834
3405
  * result arrives via a LATER `tool_output` run-item, same Task-4b
@@ -2840,7 +3411,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2840
3411
  * doc) — no pending registration.
2841
3412
  */
2842
3413
  /**
2843
- * OA-13: did OpenAI (the provider) already execute this built-in call? →
3414
+ * Did OpenAI (the provider) already execute this built-in call? →
2844
3415
  * `tool.start.providerExecuted` (SPEC:632; SPEC:496 "client MUST NOT
2845
3416
  * execute"). Per the installed runtime (agents-core 0.18.0
2846
3417
  * `dist/runner/modelOutputs.mjs`): `hosted_tool_call` always (resolved
@@ -2869,6 +3440,209 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2869
3440
  return false;
2870
3441
  }
2871
3442
 
3443
+ /**
3444
+ * The toolCallId of a `hosted_tool_call`: its item id when it has one. An
3445
+ * id-less item gets a derived id, `<name>_<invoke stem>_<n>` (INV-BLOCK,
3446
+ * SPEC:767: "Normalizers MUST mint collision-free **derived** ids when the
3447
+ * framework omits one"), never its `name`, which two items of one invoke
3448
+ * can share. An `mcp_approval_response` (which agents-core 0.18.0 builds
3449
+ * with no id, runner/mcpApprovals.mjs:39-49) is no call of its own: it
3450
+ * closes the request it answers (`driveApprovalAnswer`).
3451
+ */
3452
+ function hostedToolCallId(rawItem: OpenAIHostedToolCallItem): string {
3453
+ if (rawItem.id !== undefined && rawItem.id.length > 0) return rawItem.id;
3454
+ return `${rawItem.name}_${invokeStem}_${++derivedOrdinal}`;
3455
+ }
3456
+
3457
+ /** The hosted-MCP kind of a `hosted_tool_call`, by its `name` or its
3458
+ * `providerData.type` (agents-openai's converter matches either,
3459
+ * openaiResponsesConverter.mjs:1066-1115). */
3460
+ function hostedMcpKind(
3461
+ rawItem: OpenAIHostedToolCallItem,
3462
+ ): "mcp_call" | "mcp_approval_request" | "mcp_approval_response" | undefined {
3463
+ const type: unknown = rawItem.providerData?.type;
3464
+ for (const kind of ["mcp_call", "mcp_approval_request", "mcp_approval_response"] as const) {
3465
+ if (rawItem.name === kind || type === kind) return kind;
3466
+ }
3467
+ return undefined;
3468
+ }
3469
+
3470
+ /**
3471
+ * An `mcp_approval_response` run-item closes the request it answers
3472
+ * (`providerData.approval_request_id`) with exactly one `tool.done`:
3473
+ * outcome "ok" when `providerData.approve` is true, which records the
3474
+ * approval and not the result of the call it gates, and "denied" when it is
3475
+ * not. It creates no block of its own, and the `mcp_call` it gates is a
3476
+ * separate call under its own id. The request is a pending call of its
3477
+ * round in the same invoke (the onApproval flow); in a resuming invoke it
3478
+ * is unknown, and the answer lands as a leading result does
3479
+ * (`openTurnForLeadingResult`, INV-XINV). An answer's `reason` rides
3480
+ * tool.done providerMetadata. Three answers have nothing to close, and each
3481
+ * is carried verbatim on ext.openai.unparsed: one that names no request; a
3482
+ * second answer to a request this invoke already closed (agents-core
3483
+ * answers each request once, runner/mcpApprovals.mjs), which would close it
3484
+ * twice; and one naming a request this invoke does not hold while a
3485
+ * response is open, which no leading turn can take.
3486
+ */
3487
+ function driveApprovalAnswer(rawItem: OpenAIHostedToolCallItem): void {
3488
+ const requestId: unknown = rawItem.providerData?.approval_request_id;
3489
+ if (typeof requestId !== "string" || requestId.length === 0 || answeredRequests.has(requestId)) {
3490
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
3491
+ return;
3492
+ }
3493
+ const reason: unknown = rawItem.providerData?.reason;
3494
+ const meta = openaiProviderMeta({
3495
+ reason: typeof reason === "string" && reason.length > 0 ? reason : undefined,
3496
+ caller: callerToJson(rawItem.caller),
3497
+ });
3498
+ const doneTurnId = resolvePendingTurnId(requestId);
3499
+ const leading = doneTurnId === undefined ? openTurnForLeadingResult(requestId) : undefined;
3500
+ if (doneTurnId === undefined && leading === undefined) {
3501
+ a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
3502
+ return;
3503
+ }
3504
+ answeredRequests.add(requestId);
3505
+ a.toolDone({
3506
+ toolCallId: requestId,
3507
+ content: [],
3508
+ outcome: rawItem.providerData?.approve === true ? "ok" : "denied",
3509
+ ...(meta !== undefined ? { providerMetadata: meta } : {}),
3510
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : leading),
3511
+ });
3512
+ drainPendingTool(requestId, doneTurnId);
3513
+ }
3514
+
3515
+ /**
3516
+ * A hosted call's input. agents-openai's converter keeps a hosted item's
3517
+ * fields in `providerData` (SPEC:965: a native value is never dropped
3518
+ * silently):
3519
+ * - its `arguments` (top-level when present, else in providerData — the
3520
+ * MCP kinds);
3521
+ * - else a web_search's `action` without its `sources`, which are the
3522
+ * call's result, not its input;
3523
+ * - else a file_search's `queries`;
3524
+ * - else a code_interpreter's `code` and `container_id` (its call payload
3525
+ * without its `outputs`, the program precedent).
3526
+ */
3527
+ function hostedInput(rawItem: OpenAIHostedToolCallItem): JsonValue {
3528
+ const pd = rawItem.providerData;
3529
+ const args: unknown = rawItem.arguments ?? pd?.arguments;
3530
+ if (typeof args === "string") return parseJsonArguments(rawItem.id, args);
3531
+ const action = pd?.action;
3532
+ if (isJsonObject(action)) {
3533
+ const input: { [k: string]: JsonValue } = {};
3534
+ for (const [k, v] of Object.entries(action)) if (k !== "sources") input[k] = v;
3535
+ return JsonValue.parse(input);
3536
+ }
3537
+ if (rawItem.name === "file_search_call" && pd?.queries !== undefined) return JsonValue.parse({ queries: pd.queries });
3538
+ if (rawItem.name === "code_interpreter_call" && (pd?.code !== undefined || pd?.container_id !== undefined)) {
3539
+ return JsonValue.parse({
3540
+ ...(pd?.code !== undefined ? { code: pd.code } : {}),
3541
+ ...(pd?.container_id !== undefined ? { container_id: pd.container_id } : {}),
3542
+ });
3543
+ }
3544
+ return {};
3545
+ }
3546
+
3547
+ /**
3548
+ * A hosted call's result: its `output` (an image_generation result, which
3549
+ * is base64 image data, as a file block; any other as text), a
3550
+ * web_search's `sources`, an mcp_list_tools listing, a file_search's
3551
+ * `results` and a code_interpreter's `outputs` as data blocks, and its
3552
+ * outcome. The outcome is "error" when the native status is `failed` or
3553
+ * `incomplete`, as a shell, program or function result's `incomplete` is
3554
+ * (and an apply-patch result's `failed`); for an mcp_call, whose top-level
3555
+ * status the converter always sets to "completed", the status in
3556
+ * providerData. It is also "error" when the item carries a non-null
3557
+ * `error`, an empty string included, even with a `completed` status. Any
3558
+ * other status (`in_progress`,
3559
+ * `searching`, `interpreting`, …) closes "ok"; a status other than
3560
+ * `completed` rides tool.done providerMetadata.status verbatim.
3561
+ */
3562
+ function hostedResult(rawItem: OpenAIHostedToolCallItem): {
3563
+ content: AgBlock[];
3564
+ outcome: ToolOutcome;
3565
+ isError?: true;
3566
+ errorText?: string;
3567
+ errorCode?: string;
3568
+ providerMetadata?: AgProviderMeta;
3569
+ } {
3570
+ const pd = rawItem.providerData;
3571
+ const content: AgBlock[] = [];
3572
+ const output: unknown = rawItem.output;
3573
+ if (typeof output === "string" && output.length > 0) {
3574
+ content.push(
3575
+ rawItem.name === "image_generation_call"
3576
+ ? { type: "file", source: { type: "base64", mediaType: imageResultMediaType(pd, output), data: output } }
3577
+ : { type: "text", text: output },
3578
+ );
3579
+ }
3580
+ const action = pd?.action;
3581
+ if (isJsonObject(action) && Array.isArray(action.sources)) {
3582
+ content.push({ type: "data", name: "web_search_sources", data: JsonValue.parse(action.sources) });
3583
+ }
3584
+ const tools = pd?.tools;
3585
+ if (rawItem.name === "mcp_list_tools" && Array.isArray(tools)) {
3586
+ content.push({ type: "data", name: "mcp_list_tools", data: JsonValue.parse(tools) });
3587
+ }
3588
+ const results = pd?.results;
3589
+ if (rawItem.name === "file_search_call" && Array.isArray(results)) {
3590
+ content.push({ type: "data", name: "file_search_results", data: JsonValue.parse(results) });
3591
+ }
3592
+ const outputs = pd?.outputs;
3593
+ if (rawItem.name === "code_interpreter_call" && Array.isArray(outputs)) {
3594
+ content.push({ type: "data", name: "code_interpreter_outputs", data: JsonValue.parse(outputs) });
3595
+ }
3596
+ const status: unknown = hostedMcpKind(rawItem) === "mcp_call" ? (pd?.status ?? rawItem.status) : rawItem.status;
3597
+ // An mcp_call's `error` is an object on the wire (openai-node 7.22.0
3598
+ // McpToolCallError: a protocol or HTTP error {code, message, type}, or a
3599
+ // tool execution error {content, type}): its message (else the object as
3600
+ // JSON) is the errorText, its type the errorCode, and the object rides
3601
+ // tool.done providerMetadata verbatim. A non-empty string error is its own
3602
+ // text; any other non-null error (an empty string) rides providerMetadata.
3603
+ const error: unknown = pd?.error;
3604
+ const hasError = error !== undefined && error !== null;
3605
+ const errorMessage: unknown = isJsonObject(error) ? error.message : undefined;
3606
+ const errorText =
3607
+ typeof error === "string" && error.length > 0
3608
+ ? error
3609
+ : typeof errorMessage === "string" && errorMessage.length > 0
3610
+ ? errorMessage
3611
+ : isJsonObject(error)
3612
+ ? JSON.stringify(error)
3613
+ : undefined;
3614
+ const errorType: unknown = isJsonObject(error) ? error.type : undefined;
3615
+ // An image_generation result's own fields (revised prompt, size, quality,
3616
+ // background, action, format) ride tool.done providerMetadata verbatim.
3617
+ const image = rawItem.name === "image_generation_call" ? pd : undefined;
3618
+ const imageField = (k: string): JsonValue | undefined => {
3619
+ const v = image?.[k];
3620
+ return v === null ? undefined : v;
3621
+ };
3622
+ const providerMetadata = openaiProviderMeta({
3623
+ status: typeof status === "string" && status.length > 0 && status !== "completed" ? status : undefined,
3624
+ error: hasError && errorText !== error ? JsonValue.parse(error) : undefined,
3625
+ revised_prompt: imageField("revised_prompt"),
3626
+ size: imageField("size"),
3627
+ quality: imageField("quality"),
3628
+ background: imageField("background"),
3629
+ action: imageField("action"),
3630
+ output_format: imageField("output_format"),
3631
+ });
3632
+ const meta = providerMetadata !== undefined ? { providerMetadata } : {};
3633
+ if (status === "failed" || status === "incomplete" || hasError) {
3634
+ return {
3635
+ content,
3636
+ outcome: "error",
3637
+ isError: true,
3638
+ ...(errorText !== undefined ? { errorText } : {}),
3639
+ ...(typeof errorType === "string" && errorType.length > 0 ? { errorCode: errorType } : {}),
3640
+ ...meta,
3641
+ };
3642
+ }
3643
+ return { content, outcome: "ok", ...meta };
3644
+ }
3645
+
2872
3646
  function driveBuiltinToolCalled(
2873
3647
  rawItem:
2874
3648
  | OpenAIShellCallItem
@@ -2877,25 +3651,65 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2877
3651
  | OpenAIHostedToolCallItem
2878
3652
  | OpenAIProgramCallItem,
2879
3653
  ): 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);
3654
+ const mcpKind = rawItem.type === "hosted_tool_call" ? hostedMcpKind(rawItem) : undefined;
3655
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_response") {
3656
+ driveApprovalAnswer(rawItem);
3657
+ return;
3658
+ }
3659
+ // The listed item this run-item is (see "Built-in round attach").
3660
+ const key = rawItem.id;
3661
+ if (rawItem.id !== undefined) seenBuiltinItemIds.add(rawItem.id);
3662
+ const toolCallId = rawItem.type === "hosted_tool_call" ? hostedToolCallId(rawItem) : rawItem.callId;
3663
+ // A run-item that lands after its round's terminal attaches to that round;
3664
+ // one that lands while a response is open belongs to it. A hosted call
3665
+ // that no round claims while no response is open (not a 0.18.0 shape: a
3666
+ // resuming invoke leads with a tool result or an approval's answer) opens
3667
+ // its turn as a leading tool result does (`openTurnForLeadingResult`), in
3668
+ // an assistant message of its own, `<toolCallId>:call`, closed after the
3669
+ // call: the response that follows then opens its own message in that
3670
+ // turn, with its model. A leading client-executed or tool-search call
3671
+ // keeps the response open.
3672
+ const late = lateBuiltinRound(key);
3673
+ // openTurnForLeadingResult returns undefined while a response is open.
3674
+ const leading = late === undefined && rawItem.type === "hosted_tool_call" ? openTurnForLeadingResult(toolCallId) : undefined;
3675
+ const callMsgId = leading !== undefined ? `${toolCallId}:call` : undefined;
3676
+ if (leading !== undefined && callMsgId !== undefined) {
3677
+ a.openMessage({ id: callMsgId, role: "assistant", turnId: leading.turnId, threadId });
3678
+ } else if (late === undefined) {
3679
+ ensureResponseOpen();
3680
+ }
3681
+ const ownerMsgId = late !== undefined ? late.mId : (callMsgId ?? msgId);
3682
+ const ownerTurnId = late !== undefined ? late.tid : (leading?.turnId ?? turnId);
3683
+ if (ownerMsgId === undefined) return; // unreachable post-ensure; satisfies narrowing
3684
+ // An MCP call or approval request is named by the MCP tool it calls
3685
+ // (`providerData.name`); the item's own name is the umbrella (`mcp_call` /
3686
+ // `mcp_approval_request`), which rides providerMetadata.type.
3687
+ const mcpToolName: unknown = mcpKind !== undefined ? rawItem.providerData?.name : undefined;
3688
+ const name = typeof mcpToolName === "string" && mcpToolName.length > 0 ? mcpToolName : builtinToolName(rawItem);
2884
3689
  // Caller provenance (0.14.0): typed only on the shapes the wire declares
2885
3690
  // it for — computer_call and program carry none (protocol.d.ts).
2886
3691
  const caller =
2887
3692
  rawItem.type === "shell_call" || rawItem.type === "apply_patch_call" || rawItem.type === "hosted_tool_call"
2888
3693
  ? rawItem.caller
2889
3694
  : undefined;
2890
- const startMeta = openaiProviderMeta({ caller: callerToJson(caller) });
3695
+ // An mcp_call that an approval gated names that request (verbatim).
3696
+ const approvalRequestId: unknown = mcpKind === "mcp_call" ? rawItem.providerData?.approval_request_id : undefined;
3697
+ const startMeta = openaiProviderMeta({
3698
+ caller: callerToJson(caller),
3699
+ type: mcpKind,
3700
+ approval_request_id: typeof approvalRequestId === "string" && approvalRequestId.length > 0 ? approvalRequestId : undefined,
3701
+ });
3702
+ // An MCP item's server label (SPEC tool.start.serverName).
3703
+ const serverLabel: unknown = rawItem.type === "hosted_tool_call" ? rawItem.providerData?.server_label : undefined;
2891
3704
  a.toolStart({
2892
3705
  toolCallId,
2893
3706
  name,
3707
+ ...(typeof serverLabel === "string" && serverLabel.length > 0 ? { serverName: serverLabel } : {}),
2894
3708
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
2895
3709
  ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
2896
- // OA-13: see builtinProviderExecuted().
3710
+ // See builtinProviderExecuted().
2897
3711
  ...(builtinProviderExecuted(rawItem) ? { providerExecuted: true } : {}),
2898
- messageId: msgId,
3712
+ messageId: ownerMsgId,
2899
3713
  });
2900
3714
  const input: JsonValue =
2901
3715
  rawItem.type === "shell_call"
@@ -2908,16 +3722,28 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2908
3722
  ? // The call's whole wire payload, verbatim (the shell/apply-patch
2909
3723
  // precedent): `code` is the model-authored program source.
2910
3724
  { code: rawItem.code, fingerprint: rawItem.fingerprint }
2911
- : parseJsonArguments(rawItem.id, rawItem.arguments);
3725
+ : hostedInput(rawItem);
2912
3726
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
2913
3727
  a.toolArgsAssembled(toolCallId, input);
3728
+ if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_request") {
3729
+ // Not resolved: the request stays a pending call of its round until its
3730
+ // answer closes it; with no answer, the round flushes paused naming its
3731
+ // ask (§8.0 items 14 and 20, INV-FLUSH (2)).
3732
+ if (callMsgId !== undefined) a.closeMessage(callMsgId);
3733
+ registerPendingToolFor(ownerTurnId, toolCallId);
3734
+ drainListedBuiltin(key);
3735
+ return;
3736
+ }
2914
3737
  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" });
3738
+ const doneTurnId = late?.tid ?? leading?.turnId;
3739
+ a.toolDone({ toolCallId, ...hostedResult(rawItem), ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}) });
3740
+ if (callMsgId !== undefined) a.closeMessage(callMsgId);
3741
+ drainListedBuiltin(key);
2918
3742
  return;
2919
3743
  }
2920
- registerPendingTool(toolCallId);
3744
+ registerPendingToolFor(ownerTurnId, toolCallId);
3745
+ // Its run-item has landed; the round now waits on its result.
3746
+ drainListedBuiltin(key);
2921
3747
  }
2922
3748
 
2923
3749
  /**
@@ -2967,28 +3793,37 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
2967
3793
  * like any other unresolved pending tool call, no special-casing needed.
2968
3794
  */
2969
3795
  function driveToolSearchCalled(rawItem: OpenAIToolSearchCallItem): void {
2970
- ensureResponseOpen();
2971
- if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
3796
+ if (rawItem.id !== undefined) seenBuiltinItemIds.add(rawItem.id);
2972
3797
  const toolCallId = resolveToolSearchCallId(rawItem);
2973
3798
  if (toolCallId === undefined) {
2974
- // Genuinely unresolvable correlation id — never fabricate one (Tenet 6).
3799
+ // Genuinely unresolvable correlation id — never fabricate one (Tenet 6),
3800
+ // and open no turn for it: the carry is not block content.
2975
3801
  a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
3802
+ drainListedBuiltin(rawItem.id);
2976
3803
  return;
2977
3804
  }
3805
+ // A run-item that lands after its round's terminal attaches to that round
3806
+ // (see "Built-in round attach").
3807
+ const late = lateBuiltinRound(rawItem.id);
3808
+ if (late === undefined) ensureResponseOpen();
3809
+ const ownerMsgId = late !== undefined ? late.mId : msgId;
3810
+ const ownerTurnId = late !== undefined ? late.tid : turnId;
3811
+ if (ownerMsgId === undefined) return; // unreachable post-ensure; satisfies narrowing
2978
3812
  a.toolStart({
2979
3813
  toolCallId,
2980
3814
  name: "builtin:tool_search",
2981
3815
  ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
2982
- // OA-13: the item says where it ran — only `execution:"server"` is the
3816
+ // The item says where it ran — only `execution:"server"` is the
2983
3817
  // provider's (SPEC:496); "client" (the SDK's own loader / a custom
2984
3818
  // execute()) and absent leave the key off.
2985
3819
  ...(rawItem.execution === "server" ? { providerExecuted: true } : {}),
2986
- messageId: msgId,
3820
+ messageId: ownerMsgId,
2987
3821
  });
2988
3822
  const input: JsonValue = JsonValue.parse(rawItem.arguments ?? {});
2989
3823
  a.toolArgsDelta(toolCallId, JSON.stringify(input));
2990
3824
  a.toolArgsAssembled(toolCallId, input);
2991
- registerPendingTool(toolCallId);
3825
+ registerPendingToolFor(ownerTurnId, toolCallId);
3826
+ drainListedBuiltin(rawItem.id);
2992
3827
  }
2993
3828
 
2994
3829
  /**
@@ -3022,8 +3857,15 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3022
3857
  // the deserialization boundary, where a non-string would otherwise reach
3023
3858
  // `AgProviderMeta.parse`.
3024
3859
  const rawAgentName: unknown = rawItem.toolSearchAgentName;
3860
+ // agents-core 0.20.0 adds the hosted MCP names this search established
3861
+ // (`toolSearchMcpToolNames`), carried the same way: an array of strings,
3862
+ // verbatim; anything else at this boundary is no carry.
3863
+ const rawMcpNames: unknown = rawItem.toolSearchMcpToolNames;
3864
+ const mcpNames =
3865
+ Array.isArray(rawMcpNames) && rawMcpNames.every((v) => typeof v === "string") ? JsonValue.parse(rawMcpNames) : undefined;
3025
3866
  const searchMeta = openaiProviderMeta({
3026
3867
  toolSearchAgentName: typeof rawAgentName === "string" ? rawAgentName : undefined,
3868
+ toolSearchMcpToolNames: mcpNames,
3027
3869
  });
3028
3870
  a.toolDone({
3029
3871
  toolCallId,
@@ -3050,7 +3892,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3050
3892
  function driveHostError(event: OpenAIHostError): void {
3051
3893
  // O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
3052
3894
  // close is deferred releases that close per INV-FLUSH (2) BEFORE the
3053
- // normalizer closes the error (PS-21).
3895
+ // normalizer closes the error.
3054
3896
  releaseAllDeferredCloses();
3055
3897
  ensureResponseOpen();
3056
3898
  if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
@@ -3098,7 +3940,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3098
3940
  switch (event.name) {
3099
3941
  case "tool_output": {
3100
3942
  const rawItem = event.item.rawItem;
3101
- // Finding #1 (critical) + the fixture-drift ratchet's
3943
+ // The 2026-07-03 SDK-bump adaptation + the fixture-drift ratchet's
3102
3944
  // computer_call_result finding + the 0.14.0 program_output carry:
3103
3945
  // Shell/Apply-Patch/Computer-Use/Program results do NOT share
3104
3946
  // `OpenAIFunctionCallResultItem.output`'s shape — see
@@ -3110,7 +3952,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3110
3952
  rawItem.type === "computer_call_result" ||
3111
3953
  rawItem.type === "program_output"
3112
3954
  ) {
3113
- driveBuiltinToolOutput(rawItem);
3955
+ driveBuiltinToolOutput(rawItem, event.item.executionStatus);
3114
3956
  return;
3115
3957
  }
3116
3958
  const releasedFrom = droppedCalls.get(rawItem.callId);
@@ -3127,7 +3969,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3127
3969
  return;
3128
3970
  }
3129
3971
  // Authoritative tool-result source (canonical model, A1). Drives toolDone
3130
- // with content + structuredContent (the ggui cache marker — see
3972
+ // with content + structuredContent (a reference client's cache marker — see
3131
3973
  // `extractStructuredContent`'s doc for the two peer-supported homes and
3132
3974
  // the playbook 2026-07-03 wire-truth findings behind them).
3133
3975
  const outcome: ToolOutcome = rawItem.status === "incomplete" ? "error" : "ok";
@@ -3135,7 +3977,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3135
3977
  const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
3136
3978
  // workspace#21: `customData._meta` → block `_meta`; with `_meta.ui` the
3137
3979
  // payload is MCP-Apps view data → ALSO `uiData` (SPEC.md:332), leaving
3138
- // `structuredContent` as it was (the :340 mapping; ggui's cache marker
3980
+ // `structuredContent` as it was (the :340 mapping; a reference client's cache marker
3139
3981
  // rides it). §2.1's "exactly one consumer" is per channel (ruled
3140
3982
  // option A). Mirrors claude-agent-sdk/src/index.ts:1926-1946.
3141
3983
  const resultMeta = extractResultMeta(event.item.customData);
@@ -3150,7 +3992,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3150
3992
  // could misattribute it) and pass it through so toolDone binds to the
3151
3993
  // correct — possibly already-closed-pending-this-result — turn.
3152
3994
  const doneTurnId = resolvePendingTurnId(rawItem.callId);
3153
- // HO-2 (the handoff-drop review, PS-4): a result for a transfer call
3995
+ // A result for a transfer call
3154
3996
  // whose bracket is still open means that handoff never ran —
3155
3997
  // agents-core <=0.8.0's "Multiple handoffs detected, ignoring this
3156
3998
  // one." (0.8.0 toolExecution.mjs:750-755), the one streamed producer.
@@ -3171,7 +4013,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3171
4013
  a.subagentDone(unrun.turnId, unrun.parentTurnId);
3172
4014
  }
3173
4015
  // Caller provenance (0.14.0) — the result item's own optional field,
3174
- // distinct from the call-side carry on tool.start — and the 0.15.0
4016
+ // distinct from the call-side carry on tool.start — and the 0.14.3
3175
4017
  // wrapper-level `executionStatus` marker (see the projection's doc):
3176
4018
  // both verbatim, both dropped when absent.
3177
4019
  const doneMeta = openaiProviderMeta({
@@ -3207,7 +4049,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3207
4049
  // ignoring the wrapper copy here loses nothing.
3208
4050
  return;
3209
4051
  }
3210
- // Finding #1 (critical): Shell / Apply-Patch / Hosted-tool /
4052
+ // The 2026-07-03 SDK-bump adaptation: Shell / Apply-Patch / Hosted-tool /
3211
4053
  // Program built-ins — this run-item wrapper (not the raw stream) is
3212
4054
  // the SOLE tool-start source for these (see `driveBuiltinToolCalled`'s
3213
4055
  // doc).
@@ -3224,7 +4066,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3224
4066
  driveToolSearchOutput(event.item.rawItem);
3225
4067
  return;
3226
4068
  case "reasoning_item_created":
3227
- // FALLBACK source since OA-11 (the raw terminal output fills first; an
4069
+ // FALLBACK source (the raw terminal output fills first; an
3228
4070
  // already-filled rs_ is a no-op) — see driveReasoningItemCreated's docstring.
3229
4071
  driveReasoningItemCreated(event.item.rawItem);
3230
4072
  return;
@@ -3241,7 +4083,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3241
4083
  // `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
3242
4084
  // bracket the transfer with `subagentStart` now / `subagentDone` at the
3243
4085
  // matching `handoff_occurred` below (by callId via `openHandoffs`; or at
3244
- // the call's `tool_output` when the handoff never ran — HO-2).
4086
+ // the call's `tool_output` when the handoff never ran).
3245
4087
  //
3246
4088
  // `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
3247
4089
  // LLM call produced this handoff call — NOT the transfer target (see
@@ -3314,7 +4156,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3314
4156
  // still emit the `handoff` event losslessly rather than dropping the
3315
4157
  // now-known identity (Tenet 6) — it just doesn't close anything. It
3316
4158
  // precedes the tool.done, which may close the source round.
3317
- // HO-2: the handoff is owned by the SOURCE turn, explicitly. With two
4159
+ // The handoff is owned by the SOURCE turn, explicitly. With two
3318
4160
  // brackets open (agents-core <=0.8.0) the engine's backfill would pick
3319
4161
  // the last-restored nested turn; on every single-bracket stream this is
3320
4162
  // the value the backfill gave.
@@ -3360,22 +4202,31 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3360
4202
  return;
3361
4203
  }
3362
4204
  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.
4205
+ // A human-in-the-loop approval gate on a pending tool call. `askId`
4206
+ // mirrors the `approval_${callId}` convention of the google-adk
4207
+ // facet's `requestedToolConfirmations` arm for the same
4208
+ // `kind:"approval"` semantics. The gated call stays pending, so a
4209
+ // round the stream leaves waiting on it flushes paused naming this
4210
+ // ask (INV-FLUSH (2)).
3371
4211
  const item = event.item.rawItem;
4212
+ // The call the ask gates: a function, shell, apply-patch or computer
4213
+ // call's callId, else the item's id. A hosted-MCP approval request
4214
+ // has no callId, and its id is the request id its tool.start uses.
4215
+ // callId comes first, so a function approval's ask is unchanged.
4216
+ const gatedId = item.callId ?? item.id;
4217
+ if (gatedId === undefined) {
4218
+ // No id to key on: a collision-free derived askId (INV-BLOCK) and
4219
+ // no toolCallId, rather than naming a call the facet cannot find.
4220
+ a.emit({ type: "hitl.ask", askId: `approval_${invokeStem}_${++derivedOrdinal}`, kind: "approval" });
4221
+ return;
4222
+ }
3372
4223
  a.emit({
3373
4224
  type: "hitl.ask",
3374
- askId: `approval_${item.callId}`,
4225
+ askId: `approval_${gatedId}`,
3375
4226
  kind: "approval",
3376
- toolCallId: item.callId,
4227
+ toolCallId: gatedId,
3377
4228
  });
3378
- askedApprovals.set(item.callId, `approval_${item.callId}`);
4229
+ askedApprovals.set(gatedId, `approval_${gatedId}`);
3379
4230
  return;
3380
4231
  }
3381
4232
  default:
@@ -3444,7 +4295,7 @@ function createInnerOpenaiNormalizer(invokeStem: string, threadId: string): Norm
3444
4295
  flush(): AgEvent[] {
3445
4296
  // O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
3446
4297
  // closes FIRST — they are older rounds, so their message.end precedes the
3447
- // live response's (insertion order, CB-16) — as paused / verbatim /
4298
+ // live response's (insertion order) — as paused / verbatim /
3448
4299
  // message.end+usage then turn.abort (`releaseDeferredClose`); a flush
3449
4300
  // never emits a success turn.done.
3450
4301
  releaseAllDeferredCloses();