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