@silverprotocol/openai-agents 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,2109 @@
1
+ /**
2
+ * `@silverprotocol/openai-agents` — the OpenAI Agents SDK normalizer.
3
+ *
4
+ * Translates the OpenAI Agents JS SDK stream-event union into AgJSON events
5
+ * (`AgEvent[]`, spec §4). The Agents SDK surfaces TWO event families on its
6
+ * `RunStreamEvent` stream:
7
+ * 1. `RunItemStreamEvent` (type:"run_item_stream_event") — a SEMANTIC wrapper
8
+ * around a completed `RunItem` (message / tool-call / tool-output /
9
+ * reasoning). Its `item.rawItem` is the protocol item.
10
+ * 2. `RunRawModelStreamEvent` (type:"raw_model_stream_event") — its `data` is the
11
+ * Agents SDK's own `ResponseStreamEvent` union (`@openai/agents` protocol
12
+ * `StreamEvent`): the literals `output_text_delta`, `response_started`,
13
+ * `response_done`, and a generic `model` carrier (`{ type:"model"; event }`).
14
+ * The verbatim openai-node Responses events (`response.output_text.delta`,
15
+ * `response.function_call_arguments.delta`/`.done`, `response.completed`) ride
16
+ * INSIDE the `model` carrier's `event` field and use snake_case fields
17
+ * (`item_id`, `arguments`, `delta`, `output_index`, `sequence_number`,
18
+ * `incomplete_details`) — NOT camelCase.
19
+ *
20
+ * Both families are needed: the run-item wrapper gives the assembled tool-call /
21
+ * reasoning items (with the `fc_`/`rs_` ids that are replay-load-bearing), while
22
+ * the raw Responses deltas (in the `model` carrier) carry the streamed text + the
23
+ * per-fragment tool-call argument accumulation the spec mandates (§8.1).
24
+ *
25
+ * The sole entry point is the STATEFUL {@link createOpenaiNormalizer} factory:
26
+ * one fresh `StreamAssembler` per factory call holds the per-invoke closure state
27
+ * (turn anchoring, fc_→call_id correlation, arg buffers, refusal flag) and drives
28
+ * the engine from the SINGLE authoritative source per concern (BINDING canonical
29
+ * model, plan §"Spike Findings"). `seq` is allocated monotonically from 0 by the
30
+ * engine; the Router rebases to a global ordinal downstream (out of scope here).
31
+ * This is the sole normalizer contract for this package — no rule-based
32
+ * alternative exists.
33
+ *
34
+ * The `OpenAIStreamEvent` discriminated union below is a faithful PROJECTION of
35
+ * the verified `@openai/agents` `RunStreamEvent` union + the openai-node
36
+ * `ResponseStreamEvent` shapes — hand-defined as the fixture contract (the
37
+ * subset the normalizer consumes) until the OpenAI runtime is wired. It is NOT a
38
+ * raw-provider-event redefinition with an invented shape; field names match the
39
+ * primary sources (snake_case for the openai-node Responses events). Verified
40
+ * against the primary sources (June 2026):
41
+ * - openai/openai-agents-js packages/agents-core/src/events.ts
42
+ * (`RunItemStreamEvent` + `RunItemStreamEventName`;
43
+ * `RunRawModelStreamEvent.data: ResponseStreamEvent`)
44
+ * - openai/openai-agents-js packages/agents-core/src/items.ts
45
+ * (`RunMessageOutputItem`/`RunToolCallItem`/`RunToolCallOutputItem`/`RunReasoningItem`/
46
+ * `RunHandoffCallItem.{rawItem,agent}`/`RunHandoffOutputItem.{rawItem,sourceAgent,targetAgent}`)
47
+ * - openai/openai-agents-js packages/agents-core/src/types/protocol.ts
48
+ * (`AssistantMessageItem` / `FunctionCallItem.{callId,name,arguments,id}` /
49
+ * `FunctionCallResultItem.{callId,output}` / `ReasoningItem.{id,content,providerData}`;
50
+ * the `StreamEvent` union: `output_text_delta` {delta}, `response_started`,
51
+ * `response_done` {response}, and the generic `model` carrier {type:"model", event})
52
+ * - openai/openai-node responses event types (the `model` carrier's `event`):
53
+ * `response.output_text.delta` (`item_id`/`delta`/`output_index`/`content_index`/`sequence_number`),
54
+ * `response.function_call_arguments.delta` (`item_id`/`delta`),
55
+ * `response.function_call_arguments.done` (`arguments`/`item_id`),
56
+ * `response.completed`/`response.incomplete` (`response.incomplete_details.reason`),
57
+ * and the reasoning item `rs_…` + `encrypted_content` stateless-replay payload
58
+ * (the `reasoning.encrypted_content` include; rides `ReasoningItem.providerData`).
59
+ *
60
+ * `@openai/agents` is declared an OPTIONAL peerDependency (for when its native
61
+ * types are wanted) but is NOT imported — this package is fixture-only and the
62
+ * SDK is not installed.
63
+ */
64
+ import {
65
+ type AgEvent,
66
+ type AgBlock,
67
+ type AgFinishReason,
68
+ type AgUsage,
69
+ type AgSafety,
70
+ type AgCitation,
71
+ JsonValue,
72
+ type Normalizer,
73
+ StreamAssembler,
74
+ type ToolOutcome,
75
+ type TurnDoneFields,
76
+ } from "@silverprotocol/core";
77
+
78
+ // ─────────────────────────────────────────────────────────────────────────────
79
+ // OpenAIStreamEvent — the HAND-DEFINED fixture contract (verified shapes above).
80
+ // A minimal faithful projection of the @openai/agents `RunStreamEvent` union +
81
+ // the underlying OpenAI Responses streaming events the runtime would emit.
82
+ // ─────────────────────────────────────────────────────────────────────────────
83
+
84
+ /** Assistant message content part (protocol `OutputText`). */
85
+ export interface OpenAIOutputText {
86
+ type: "output_text";
87
+ text: string;
88
+ /** url_citation and file_citation annotations on the text part. */
89
+ annotations?: OpenAIAnnotation[];
90
+ }
91
+
92
+ /** url_citation annotation on an output_text part (openai-node `ResponseCitationAnnotation`). */
93
+ export interface OpenAIUrlCitationAnnotation {
94
+ type: "url_citation";
95
+ url: string;
96
+ title?: string;
97
+ start_index?: number;
98
+ end_index?: number;
99
+ }
100
+
101
+ /** file_citation annotation on an output_text part. */
102
+ export interface OpenAIFileCitationAnnotation {
103
+ type: "file_citation";
104
+ file_id?: string;
105
+ filename?: string;
106
+ index?: number;
107
+ }
108
+
109
+ /** The subset of annotations that the normalizer handles. */
110
+ export type OpenAIAnnotation = OpenAIUrlCitationAnnotation | OpenAIFileCitationAnnotation;
111
+
112
+ /** `Refusal` content part — the model refused to answer (openai-node `ResponseOutputRefusal`). */
113
+ export interface OpenAIRefusal {
114
+ type: "refusal";
115
+ refusal: string;
116
+ }
117
+
118
+ /** Union of assistant message content parts the normalizer handles. */
119
+ export type OpenAIContentPart = OpenAIOutputText | OpenAIRefusal;
120
+
121
+ /** protocol `AssistantMessageItem` (the `rawItem` of a message_output_item). */
122
+ export interface OpenAIAssistantMessageItem {
123
+ type?: "message";
124
+ role: "assistant";
125
+ status: "in_progress" | "completed" | "incomplete";
126
+ content: OpenAIContentPart[];
127
+ id?: string;
128
+ providerData?: { [k: string]: JsonValue };
129
+ }
130
+
131
+ /** protocol `FunctionCallItem` (the `rawItem` of a tool_call_item). `callId` is
132
+ * the model's call_id; `id` is the Responses `fc_…` item id (DISTINCT). */
133
+ export interface OpenAIFunctionCallItem {
134
+ type: "function_call";
135
+ callId: string;
136
+ name: string;
137
+ arguments: string; // a JSON STRING — MUST be JSON.parse'd for tool.args.assembled
138
+ status?: "in_progress" | "completed" | "incomplete";
139
+ id?: string; // fc_… Responses item id
140
+ providerData?: { [k: string]: JsonValue };
141
+ }
142
+
143
+ /** protocol `ToolOutputText` — the BARE-OBJECT arm of `FunctionCallResultItem.
144
+ * output` (`output: {type:"text", text}`, not wrapped in an array). */
145
+ export interface OpenAIToolOutputText {
146
+ type: "text";
147
+ text: string;
148
+ }
149
+
150
+ /**
151
+ * protocol array-form element of `FunctionCallResultItem.output`
152
+ * (`output: [...]`) — playbook 2026-07-03 SDK-bump adaptation, Finding #2
153
+ * (critical). `@openai/agents-core` 0.12.0's real zod schema
154
+ * (`protocol.d.ts`'s `FunctionCallResultItem`) discriminates the ARRAY arm's
155
+ * elements with `input_text`/`input_image`/`input_file` literals — DIFFERENT
156
+ * from the bare-object arm's `text`/`image`/`file` literals ({@link
157
+ * OpenAIToolOutputText}). The prior 0.12.0 adaptation missed this: it typed
158
+ * the array arm as `OpenAIToolOutputText[]` (i.e. assumed array elements ALSO
159
+ * use `type:"text"`), so `toolOutputToAgBlocks`'s `part.type === "text"`
160
+ * check never matched a real array-shaped tool result — VERIFIED LIVE
161
+ * (playbook 2026-07-03, echo-gpt55 capture): every MCP tool call's result
162
+ * silently produced `tool.done.content: []`, discarding the tool's entire
163
+ * output text. `@openai/agents-core` 0.12.0 uses this array+`input_text`
164
+ * shape for MCP-routed tool-call results (the common case for this SDK's own
165
+ * MCP client) — this was never exercised by a live capture before now (the
166
+ * committed openai seed cassettes predate 0.12.0). Only the text arm is
167
+ * modeled/handled here, matching the PRE-EXISTING scope of the bare-object
168
+ * arm (which also only maps `type:"text"`, never `type:"image"`/`"file"`) —
169
+ * `input_image`/`input_file` array elements remain intentionally unhandled.
170
+ */
171
+ export interface OpenAIToolOutputInputText {
172
+ type: "input_text";
173
+ text: string;
174
+ }
175
+
176
+ /** protocol `FunctionCallResultItem` (the `rawItem` of a tool_call_output_item).
177
+ * `output` is a string, a bare content object ({@link OpenAIToolOutputText}),
178
+ * or a content-part ARRAY ({@link OpenAIToolOutputInputText}[]) — the wrapper's
179
+ * own `output` field carries the stringified primary output. */
180
+ export interface OpenAIFunctionCallResultItem {
181
+ type: "function_call_result";
182
+ name: string;
183
+ callId: string;
184
+ status: "in_progress" | "completed" | "incomplete";
185
+ output: string | OpenAIToolOutputText | OpenAIToolOutputInputText[];
186
+ providerData?: { [k: string]: JsonValue };
187
+ }
188
+
189
+ // ── OpenAI native BUILT-IN tool call shapes (playbook 2026-07-03 SDK-bump
190
+ // adaptation, Finding #1 — @openai/agents-core 0.2.1 → 0.12.0). Shell /
191
+ // Apply-Patch / Hosted-tool calls carry NO dedicated RunItemStreamEventName —
192
+ // they reuse the pre-existing `tool_called`/`tool_output` names with NEW
193
+ // `rawItem` shapes (verified against @openai/agents-core 0.12.0's
194
+ // `types/protocol.ts`: `ShellCallItem` / `ShellCallResultItem` /
195
+ // `ApplyPatchCallItem` / `ApplyPatchCallResultItem` / `HostedToolCallItem`).
196
+
197
+ /** protocol `ShellAction` — the shell tool's per-call command spec. */
198
+ export interface OpenAIShellAction {
199
+ commands: string[];
200
+ timeoutMs?: number;
201
+ maxOutputLength?: number;
202
+ }
203
+
204
+ /** protocol `ShellCallItem` (a `tool_called` rawItem for OpenAI's native shell
205
+ * built-in tool). Carries NO `name` field — the wire identifies the tool
206
+ * purely by `type`; the facet synthesizes `name:"builtin:shell"` (§8 quirk).
207
+ * Unlike `function_call`, there is no per-fragment argument-delta stream for
208
+ * this shape on this seam — the whole `action` arrives complete on this ONE
209
+ * wrapper, so this run-item (not the raw stream) is the sole tool-start
210
+ * source for it. */
211
+ export interface OpenAIShellCallItem {
212
+ type: "shell_call";
213
+ callId: string;
214
+ status?: "in_progress" | "completed" | "incomplete";
215
+ action: OpenAIShellAction;
216
+ id?: string;
217
+ providerData?: { [k: string]: JsonValue };
218
+ }
219
+
220
+ /** protocol `ShellCallOutcome` (per-command exit signal). */
221
+ export interface OpenAIShellCallOutcome {
222
+ type: "timeout" | "exit";
223
+ exitCode?: number | null;
224
+ }
225
+
226
+ /** protocol `ShellCallOutputContent` (one command's stdout/stderr/outcome). */
227
+ export interface OpenAIShellCallOutputContent {
228
+ stdout: string;
229
+ stderr: string;
230
+ outcome: OpenAIShellCallOutcome;
231
+ }
232
+
233
+ /** protocol `ShellCallResultItem` (the `rawItem` of a `tool_output` run-item for
234
+ * a completed shell call). `output` is an ARRAY of per-command results — a
235
+ * DIFFERENT shape from `OpenAIFunctionCallResultItem.output` (a bare string /
236
+ * content-part union); the two must NOT be handled by the same generic path
237
+ * (that was the orphan-hazard: shape-compatible-enough field NAMES let a
238
+ * `tool.done` fire with silently-empty content). */
239
+ export interface OpenAIShellCallResultItem {
240
+ type: "shell_call_output";
241
+ callId: string;
242
+ maxOutputLength?: number;
243
+ output: OpenAIShellCallOutputContent[];
244
+ id?: string;
245
+ providerData?: { [k: string]: JsonValue };
246
+ }
247
+
248
+ /** protocol `ApplyPatchOperation` (one file edit — create/update/delete). */
249
+ export interface OpenAIApplyPatchOperation {
250
+ type: "create_file" | "update_file" | "delete_file";
251
+ path: string;
252
+ diff?: string;
253
+ moveTo?: string;
254
+ }
255
+
256
+ /** protocol `ApplyPatchCallItem` (a `tool_called` rawItem for OpenAI's native
257
+ * apply-patch built-in tool). Carries NO `name` field; the facet synthesizes
258
+ * `name:"builtin:apply_patch"` (§8 quirk). Same single-wrapper-is-authoritative
259
+ * rationale as {@link OpenAIShellCallItem}. */
260
+ export interface OpenAIApplyPatchCallItem {
261
+ type: "apply_patch_call";
262
+ callId: string;
263
+ status: "in_progress" | "completed";
264
+ operation: OpenAIApplyPatchOperation;
265
+ id?: string;
266
+ providerData?: { [k: string]: JsonValue };
267
+ }
268
+
269
+ /** protocol `ApplyPatchCallResultItem` (the `rawItem` of a `tool_output`
270
+ * run-item for a completed apply-patch call). */
271
+ export interface OpenAIApplyPatchCallResultItem {
272
+ type: "apply_patch_call_output";
273
+ callId: string;
274
+ status: "completed" | "failed";
275
+ output?: string;
276
+ id?: string;
277
+ providerData?: { [k: string]: JsonValue };
278
+ }
279
+
280
+ /** protocol `HostedToolCallItem` (a `tool_called` rawItem for a
281
+ * provider-HOSTED built-in tool — web_search / code_interpreter /
282
+ * file_search / image_generation / mcp / … — normalized into this ONE
283
+ * umbrella shape only at the run-item layer: the raw `response.output_item.
284
+ * added` event NEVER carries `item.type === "hosted_tool_call"` literally —
285
+ * each underlying OpenAI hosted tool has its OWN distinct raw wire type, so
286
+ * this discriminant only exists here). UNLIKE `function_call`/`shell_call`/
287
+ * `apply_patch_call`, this item carries its OWN `output` when it streams:
288
+ * OpenAI's hosted tools execute server-side within the same model turn, so
289
+ * by the time this wrapper delivers it, the call is already resolved —
290
+ * there is no separate `tool_output` run-item for this shape (verified
291
+ * against @openai/agents-core 0.12.0's `runner/modelOutputs.mjs`: a
292
+ * `hosted_tool_call` output item is pushed as a single `RunToolCallItem`,
293
+ * never paired with a `RunToolCallOutputItem`). The facet emits
294
+ * `tool.start` + `tool.done` TOGETHER from this one event. */
295
+ export interface OpenAIHostedToolCallItem {
296
+ type: "hosted_tool_call";
297
+ id?: string;
298
+ name: string;
299
+ arguments?: string;
300
+ status?: string;
301
+ output?: string;
302
+ providerData?: { [k: string]: JsonValue };
303
+ }
304
+
305
+ // ── OpenAI native Computer-Use built-in tool shapes (fixture-drift ratchet
306
+ // finding, 2026-07-03 — Task 6's `sdk-surface.json` inventory surfaced that
307
+ // `computer_call`/`computer_call_result` ride the SAME `tool_called`/
308
+ // `tool_output` event names Finding #1 already fixed for shell/apply-patch,
309
+ // but were left uncovered by that fix. Verified against
310
+ // @openai/agents-core 0.12.0's `dist/types/protocol.d.ts`: `ComputerUseCallItem`
311
+ // / `ComputerCallResultItem`.)
312
+
313
+ /** protocol `ComputerUseCallItem` (a `tool_called` rawItem for OpenAI's native
314
+ * Computer-Use built-in tool). Carries NO `name` field — the facet synthesizes
315
+ * `name:"builtin:computer"` (§8 quirk, mirrors shell_call/apply_patch_call).
316
+ * The wire carries BOTH `action` (a single computer action — click/scroll/type/screenshot/…)
317
+ * and `actions` (a batch array of actions); the SDK's own runtime reads `actions` FIRST
318
+ * (if populated), falling back to `action`. Both are OPTIONAL on the wire and carried
319
+ * through verbatim as the tool's args payload; nested fields are not interpreted here
320
+ * (fixture discipline: type only what is consumed — the facet never branches on a
321
+ * specific action kind). Same single-wrapper-is-authoritative rationale as
322
+ * {@link OpenAIShellCallItem}: no per-fragment argument-delta stream exists for this
323
+ * shape on this seam. The normalizer MUST mirror the SDK's precedence: `actions ?? action ?? {}`. */
324
+ export interface OpenAIComputerCallItem {
325
+ type: "computer_call";
326
+ callId: string;
327
+ status: "in_progress" | "completed" | "incomplete";
328
+ action?: JsonValue;
329
+ actions?: JsonValue;
330
+ id?: string;
331
+ providerData?: { [k: string]: JsonValue };
332
+ }
333
+
334
+ /** protocol `ComputerCallResultItem` (the `rawItem` of a `tool_output` run-item
335
+ * for a completed Computer-Use call). `output` is ALWAYS the
336
+ * `computer_screenshot` shape (a base64-encoded PNG screenshot) — NO
337
+ * `status`/error discriminant exists on this wire arm (unlike shell/apply-
338
+ * patch results), so the facet maps every occurrence to `outcome:"ok"`. */
339
+ export interface OpenAIComputerCallResultItem {
340
+ type: "computer_call_result";
341
+ callId: string;
342
+ output: { type: "computer_screenshot"; data: string };
343
+ id?: string;
344
+ providerData?: { [k: string]: JsonValue };
345
+ }
346
+
347
+ // ── OpenAI native Tool-Search built-in shapes (fixture-drift ratchet
348
+ // disposition, 2026-07-03 — the last weak `carried` entries. Verified against
349
+ // @openai/agents-core 0.12.0's `dist/types/protocol.d.ts`: `ToolSearchCallItem`
350
+ // / `ToolSearchOutputItem`; `dist/events.d.ts`: `tool_search_called`/
351
+ // `tool_search_output_created` are DEDICATED `RunItemStreamEventName` literals
352
+ // — UNLIKE shell/apply-patch/computer/hosted-tool (§8 item 20), which all
353
+ // REUSE the pre-existing `tool_called`/`tool_output` names. `dist/runner/
354
+ // modelOutputs.mjs` confirms the PAIRED shape (mirrors shell_call/
355
+ // apply_patch_call/computer_call, not hosted_tool_call's single-shot
356
+ // collapse): `processModelResponse`/`processModelResponseAsync` push a
357
+ // `RunToolSearchCallItem` then, when the output is already resolved this SAME
358
+ // step — server-hosted execution returns both together in one
359
+ // `modelResponse.output`; client execution resolves synchronously via the
360
+ // SDK's own built-in `{paths}` loader or an AWAITED custom `toolSearchTool.
361
+ // execute()` — a `RunToolSearchOutputItem` right after; `dist/runner/
362
+ // streaming.mjs`'s `getRunItemStreamEventName` maps each RunItem class to its
363
+ // OWN event name, so these stream as TWO SEPARATE `RunItemStreamEvent`s (a
364
+ // `tool_search_called` followed by a `tool_search_output_created`), not one
365
+ // collapsed event.
366
+
367
+ /** protocol `ToolSearchCallItem` (a `tool_search_called` rawItem — the model
368
+ * searching a large tool catalog before invoking a specific tool; hosted
369
+ * server-side (`execution:"server"`) or client-executed (`execution:
370
+ * "client"`, either `Runner`'s built-in `{paths:string[]}` loader or a
371
+ * custom `toolSearchTool({execution:"client", execute})`)). Carries NO
372
+ * `name` field — the facet synthesizes `name:"builtin:tool_search"` (§8
373
+ * quirk, mirrors shell_call/apply_patch_call/computer_call). UNLIKE those
374
+ * three (and unlike every other builtin's REQUIRED `callId: z.ZodString`),
375
+ * `call_id`/`callId` are BOTH optional AND nullable on this wire — the
376
+ * SDK's own runtime (`dist/tooling.mjs`'s `getToolSearchProviderCallId`/
377
+ * `getToolSearchMatchKey`) falls back through `providerData.call_id` →
378
+ * `providerData.callId` → the item's own `id` → (only when NEITHER side of
379
+ * a pairing has ANY identifiable id) blind FIFO positional matching against
380
+ * pending calls. `resolveToolSearchCallId` (below, near `driveToolSearchCalled`)
381
+ * mirrors the id-fallback chain — NOT the FIFO fallback: fabricating a
382
+ * positional-match correlation with no supporting id would risk silently
383
+ * pairing two UNRELATED calls, so that case instead degrades to
384
+ * `ext.openai.unparsed` (Tenet 6 — never fabricate a correlation id).
385
+ * `arguments` is `z.ZodUnknown` (NOT a JSON STRING like `FunctionCallItem.
386
+ * arguments`) — provider-defined (`{paths, query}` for the built-in hosted
387
+ * loader; a custom shape for a registered `toolSearchTool`) — carried
388
+ * through verbatim like `computer_call`'s `action`/`actions`, never
389
+ * JSON.parsed. */
390
+ export interface OpenAIToolSearchCallItem {
391
+ type: "tool_search_call";
392
+ id?: string;
393
+ call_id?: string | null;
394
+ callId?: string | null;
395
+ execution?: "client" | "server";
396
+ arguments?: JsonValue;
397
+ status?: string;
398
+ providerData?: { [k: string]: JsonValue };
399
+ }
400
+
401
+ /** protocol `ToolSearchOutputItem` (the `tool_search_output_created` rawItem
402
+ * for a resolved tool-search call). `tools` is, per the SDK's own zod-schema
403
+ * doc comment, "tool references or concrete tool definitions" — an array of
404
+ * provider-defined records (`{type:"tool_reference", functionName,
405
+ * namespace}` / a serialized function-tool definition / `{type:"namespace",
406
+ * name, description, tools:[...]}` / hosted-MCP provider data) — a
407
+ * structured retrieval LISTING, never natural-language text. Carried
408
+ * verbatim as a single AgBlock `data` block (the spec's escape hatch for
409
+ * structured non-text tool content — mirrors `computer_call_result`'s
410
+ * `file`-block treatment of its OWN non-text payload) rather than inventing
411
+ * a text rendering with no wire precedent; this is ALREADY full-fidelity
412
+ * (unlike `shell_call_output`'s lossy stdout/stderr join), so no separate
413
+ * `structuredContent` duplicate is warranted. `status` is an UNCONSTRAINED
414
+ * string (unlike shell/apply-patch's closed `'in_progress'|'completed'|
415
+ * 'incomplete'` enum) — no documented error discriminant exists on this
416
+ * wire arm, so — mirroring `computer_call_result`'s identical precedent —
417
+ * every occurrence maps to `outcome:"ok"`. */
418
+ export interface OpenAIToolSearchOutputItem {
419
+ type: "tool_search_output";
420
+ id?: string;
421
+ call_id?: string | null;
422
+ callId?: string | null;
423
+ execution?: "client" | "server";
424
+ status?: string;
425
+ tools: { [k: string]: JsonValue }[];
426
+ providerData?: { [k: string]: JsonValue };
427
+ }
428
+
429
+ /** protocol `InputText` (the visible reasoning content part). */
430
+ export interface OpenAIReasoningTextPart {
431
+ type: "input_text";
432
+ text: string;
433
+ }
434
+
435
+ /** protocol `ReasoningItem` (the `rawItem` of a reasoning_item). The `rs_…` id +
436
+ * the `encrypted_content` (under `providerData`, the Responses stateless-replay
437
+ * payload) are replay-load-bearing (spec §8.2/§10.4). */
438
+ export interface OpenAIReasoningItem {
439
+ type: "reasoning";
440
+ id?: string; // rs_… Responses reasoning item id
441
+ content: OpenAIReasoningTextPart[];
442
+ providerData?: { encrypted_content?: string; [k: string]: JsonValue | undefined };
443
+ }
444
+
445
+ // ── run_item_stream_event arms (one per consumed RunItemStreamEventName) ──────
446
+ interface OpenAIMessageOutputEvent {
447
+ type: "run_item_stream_event";
448
+ name: "message_output_created";
449
+ item: { type: "message_output_item"; rawItem: OpenAIAssistantMessageItem };
450
+ }
451
+ interface OpenAIToolCalledEvent {
452
+ type: "run_item_stream_event";
453
+ name: "tool_called";
454
+ // Widened (playbook 2026-07-03 SDK-bump adaptation, Finding #1 + the
455
+ // fixture-drift ratchet's computer_call finding): Shell / Apply-Patch /
456
+ // Computer-Use / Hosted-tool built-ins reuse this SAME event name with a
457
+ // DIFFERENT `rawItem` discriminant — see the four interfaces above.
458
+ item: {
459
+ type: "tool_call_item";
460
+ rawItem:
461
+ | OpenAIFunctionCallItem
462
+ | OpenAIShellCallItem
463
+ | OpenAIApplyPatchCallItem
464
+ | OpenAIComputerCallItem
465
+ | OpenAIHostedToolCallItem;
466
+ };
467
+ }
468
+ interface OpenAIToolOutputEvent {
469
+ type: "run_item_stream_event";
470
+ name: "tool_output";
471
+ // `item.rawItem` carries the protocol FunctionCallResultItem (callId, output, status)
472
+ // — OR, widened (Finding #1 + the fixture-drift ratchet's computer_call_result
473
+ // finding), a Shell/Apply-Patch/Computer-Use result (DIFFERENT `output`
474
+ // shape per discriminant; `hosted_tool_call` never reaches this event, see its
475
+ // own doc).
476
+ //
477
+ // structuredContent (the ggui cache marker, spec §2.1/§4) has TWO
478
+ // peer-supported homes on this wrapper (playbook 2026-07-03 follow-up,
479
+ // `extractStructuredContent`'s doc has the full wire-truth citations):
480
+ // - `item.customData` — populated ONLY when the caller's `MCPServer`
481
+ // config sets `customDataExtractor` (agents-core 0.12.0+); this is the
482
+ // ONLY channel `@openai/agents`'s NATIVE MCP client ever carries real
483
+ // structuredContent through, verified against agents-core 0.12.0's
484
+ // `mcpToFunctionTool`.
485
+ // - `item.output` (the wrapper-level field) — a defensive/legacy home:
486
+ // an object keyed by `.structuredContent`, for callers that front their
487
+ // OWN local (non-MCP-native) function tools returning a full
488
+ // `CallToolResult`-shaped object verbatim. NEVER produced by
489
+ // `@openai/agents`'s native MCP client in any peer-declared version
490
+ // (0.2.0–0.12.x) — kept as defense-in-depth, not a verified wire shape.
491
+ // Under 0.12.0's native MCP client this field is instead a
492
+ // JSON-stringified STRING (e.g. `'{"type":"text","text":"…"}'`) with no
493
+ // structuredContent inside it — parsed SAFELY as a fallback.
494
+ // Cast-free extraction uses `isJsonObject` + `JsonValue.parse` throughout.
495
+ item: {
496
+ type: "tool_call_output_item";
497
+ rawItem:
498
+ | OpenAIFunctionCallResultItem
499
+ | OpenAIShellCallResultItem
500
+ | OpenAIApplyPatchCallResultItem
501
+ | OpenAIComputerCallResultItem;
502
+ output?: JsonValue;
503
+ customData?: JsonValue;
504
+ };
505
+ }
506
+
507
+ /** `tool_search_called` — a DEDICATED run-item event name (verified against
508
+ * @openai/agents-core 0.12.0's `dist/events.d.ts`: `RunItemStreamEventName`
509
+ * gained `'tool_search_called'`/`'tool_search_output_created'` as their OWN
510
+ * literals — UNLIKE shell/apply-patch/computer/hosted-tool, which all reuse
511
+ * the pre-existing `tool_called`/`tool_output` names (§8 item 20). The
512
+ * run-item's own `.type` discriminant is `"tool_search_call_item"` (verified
513
+ * against `dist/items.d.ts`'s `RunToolSearchCallItem`). See
514
+ * `OpenAIToolSearchCallItem`'s doc for the full wire-truth citations. */
515
+ interface OpenAIToolSearchCalledEvent {
516
+ type: "run_item_stream_event";
517
+ name: "tool_search_called";
518
+ item: { type: "tool_search_call_item"; rawItem: OpenAIToolSearchCallItem };
519
+ }
520
+
521
+ /** `tool_search_output_created` — the paired completion event (see
522
+ * `OpenAIToolSearchOutputItem`'s doc for the wire-truth citations on why
523
+ * this is PAIRED, not collapsed like `hosted_tool_call`). The run-item's own
524
+ * `.type` discriminant is `"tool_search_output_item"` (`dist/items.d.ts`'s
525
+ * `RunToolSearchOutputItem`). */
526
+ interface OpenAIToolSearchOutputCreatedEvent {
527
+ type: "run_item_stream_event";
528
+ name: "tool_search_output_created";
529
+ item: { type: "tool_search_output_item"; rawItem: OpenAIToolSearchOutputItem };
530
+ }
531
+
532
+ interface OpenAIReasoningEvent {
533
+ type: "run_item_stream_event";
534
+ name: "reasoning_item_created";
535
+ item: { type: "reasoning_item"; rawItem: OpenAIReasoningItem };
536
+ }
537
+
538
+ /** Minimal projection of `@openai/agents`' `Agent` class — only `.name` is
539
+ * consumed anywhere on this seam (fixture discipline: type ONLY what you
540
+ * consume). Rides on `handoff_requested`'s wrapper (`agent`, the SOURCE
541
+ * agent) and `handoff_occurred`'s wrapper (`sourceAgent`/`targetAgent`) —
542
+ * audit M48 review, Finding 1. */
543
+ export interface OpenAIAgentRef {
544
+ name: string;
545
+ }
546
+
547
+ /** A handoff call item (`RunHandoffCallItem.rawItem`) — verified against
548
+ * @openai/agents-core 0.2.1's `protocol.FunctionCallItem`: `name`,
549
+ * `arguments`, `callId`, `status?`, `id?`, `providerData?`. It carries NO
550
+ * `targetAgent` field — that was an invented field on a false premise
551
+ * (audit M48 review, Finding 1): the transfer target is not resolvable at
552
+ * this point on the real wire (see {@link OpenAIHandoffRequestedEvent}). */
553
+ interface OpenAIHandoffCallItem {
554
+ type: "function_call";
555
+ name: string;
556
+ callId: string;
557
+ arguments: string;
558
+ id?: string;
559
+ providerData?: { [k: string]: JsonValue };
560
+ }
561
+
562
+ /** `handoff_requested` — the run-item wrapper (`RunHandoffCallItem`) carries
563
+ * `agent` (real d.ts naming): the SOURCE agent whose LLM call produced this
564
+ * handoff call — NOT the transfer target. The target agent is resolved only
565
+ * once the handoff actually executes (verified against
566
+ * @openai/agents-core 0.2.1's `runImplementation.mjs`: `executeHandoffCalls`
567
+ * calls `handoff.onInvokeHandoff` — which resolves the new agent — AFTER
568
+ * the `RunHandoffCallItem` carrying this event is already constructed), and
569
+ * only appears on {@link OpenAIHandoffOccurredEvent}'s `targetAgent` below
570
+ * (audit M48 review, Finding 1). */
571
+ interface OpenAIHandoffRequestedEvent {
572
+ type: "run_item_stream_event";
573
+ name: "handoff_requested";
574
+ item: { type: "handoff_call_item"; rawItem: OpenAIHandoffCallItem; agent: OpenAIAgentRef };
575
+ }
576
+
577
+ /** `handoff_occurred` — the REAL completion signal the original
578
+ * `handoff_requested` mapping assumed did not exist (audit M48 review,
579
+ * Finding 1; verified against @openai/agents-core 0.2.1's `events.d.ts`:
580
+ * `RunItemStreamEventName` includes `'handoff_occurred'`). The wrapper is a
581
+ * `RunHandoffOutputItem`: `rawItem` (the transfer's tool-output message,
582
+ * protocol `FunctionCallResultItem`-shaped — reuses
583
+ * {@link OpenAIFunctionCallResultItem}), `sourceAgent`, `targetAgent` (both
584
+ * {@link OpenAIAgentRef}) — this is where BOTH agent identities are finally
585
+ * known. */
586
+ interface OpenAIHandoffOccurredItem {
587
+ type: "handoff_output_item";
588
+ rawItem: OpenAIFunctionCallResultItem;
589
+ sourceAgent: OpenAIAgentRef;
590
+ targetAgent: OpenAIAgentRef;
591
+ }
592
+
593
+ interface OpenAIHandoffOccurredEvent {
594
+ type: "run_item_stream_event";
595
+ name: "handoff_occurred";
596
+ item: OpenAIHandoffOccurredItem;
597
+ }
598
+
599
+ /** A tool approval request item (RunToolApprovalItem) — the function call that
600
+ * needs human approval rides in rawItem. */
601
+ interface OpenAIToolApprovalItem {
602
+ type: "function_call";
603
+ name: string;
604
+ callId: string;
605
+ arguments: string;
606
+ id?: string;
607
+ }
608
+
609
+ interface OpenAIToolApprovalRequestedEvent {
610
+ type: "run_item_stream_event";
611
+ name: "tool_approval_requested";
612
+ item: { type: "tool_approval_item"; rawItem: OpenAIToolApprovalItem };
613
+ }
614
+
615
+ /** The union of every `run_item_stream_event` arm this fixture contract declares
616
+ * (one per consumed `RunItemStreamEventName`). Used to hold a WIDENED reference
617
+ * to a run-item event in the drive() switch's `default` arm (Task 3, audit M48):
618
+ * once every declared `name` literal has its own `case`, TS narrows the switched-
619
+ * on `event` to `never` inside `default` — legally so, since every name this type
620
+ * declares IS handled — but a real-wire `RunItemStreamEventName` this hand-typed
621
+ * union does NOT declare (e.g. `mcp_approval_requested`, `mcp_list_tools`) still
622
+ * reaches `default` at RUNTIME (the outer guard only checks `typeof name ===
623
+ * "string"`, file header). A binding declared at this wider (but still concrete,
624
+ * non-`any`/`unknown`) type reads `.name`/`.item` without the `never` narrowing
625
+ * the switched expression itself is subject to — not a cast, since the runtime
626
+ * value genuinely does have this type shape (any run-item event IS one of these
627
+ * seven interfaces at the TS boundary; `default` is where the STATIC type and the
628
+ * DYNAMIC reality provably diverge, mirroring the M46 "widen, don't cast" fix).
629
+ * `handoff_occurred` used to be cited here as an example of an undeclared name —
630
+ * it is now a declared arm (audit M48 review, Finding 1: the fixture originally
631
+ * claimed no completion signal existed for a handoff; it does). */
632
+ type OpenAIRunItemEvent =
633
+ | OpenAIMessageOutputEvent
634
+ | OpenAIToolCalledEvent
635
+ | OpenAIToolOutputEvent
636
+ | OpenAIToolSearchCalledEvent
637
+ | OpenAIToolSearchOutputCreatedEvent
638
+ | OpenAIReasoningEvent
639
+ | OpenAIHandoffRequestedEvent
640
+ | OpenAIHandoffOccurredEvent
641
+ | OpenAIToolApprovalRequestedEvent;
642
+
643
+ // ── raw_model_stream_event arm ───────────────────────────────────────────────
644
+ // `RunRawModelStreamEvent.data` is the Agents SDK's own `ResponseStreamEvent`
645
+ // union (`@openai/agents` protocol `StreamEvent`): the literals below + the
646
+ // generic `model` carrier. The verbatim openai-node Responses events ride INSIDE
647
+ // the carrier's `event` field, using snake_case.
648
+
649
+ /** openai-node `ResponseCreatedEvent` — the turn-open boundary. The real
650
+ * `response.id` is present here at the START of the stream (spike-confirmed),
651
+ * so it is the authoritative turn-anchor source (A1 canonical model). Carried via
652
+ * the `model` carrier. */
653
+ interface OpenAIResponsesCreated {
654
+ type: "response.created";
655
+ response: { id: string };
656
+ }
657
+ /** openai-node `ResponseFunctionCallArgumentsDeltaEvent` — the per-fragment
658
+ * argument delta (snake_case `item_id`/`delta`). */
659
+ interface OpenAIResponsesFnArgsDelta {
660
+ type: "response.function_call_arguments.delta";
661
+ item_id: string; // the fc_… Responses item id (buffer key + tool-call itemId)
662
+ delta: string;
663
+ }
664
+ /** openai-node `ResponseFunctionCallArgumentsDoneEvent` — the sealed full
665
+ * arguments JSON string (snake_case `arguments`/`item_id`). */
666
+ interface OpenAIResponsesFnArgsDone {
667
+ type: "response.function_call_arguments.done";
668
+ item_id: string; // the fc_… Responses item id
669
+ arguments: string;
670
+ }
671
+ /** openai-node `ResponseTextDeltaEvent` — a streamed assistant-text fragment
672
+ * (snake_case `item_id`/`delta`). Carried via the `model` carrier. */
673
+ interface OpenAIResponsesTextDelta {
674
+ type: "response.output_text.delta";
675
+ item_id: string;
676
+ delta: string;
677
+ }
678
+ /** openai-node `ResponseTextDoneEvent` — the assistant-text stream for `item_id`
679
+ * is complete (`text` carries the full assembled string). Carried via the `model`
680
+ * carrier. Authoritative `text.end` source per the canonical event model (A1). */
681
+ interface OpenAIResponsesTextDone {
682
+ type: "response.output_text.done";
683
+ item_id: string;
684
+ text?: string;
685
+ }
686
+ /** openai-node `ResponseUsage` — per-response token counts (snake_case).
687
+ * Extends to include provider-specific fields like OpenRouter's `cost` superset. */
688
+ interface OpenAIResponseUsage {
689
+ input_tokens?: number;
690
+ output_tokens?: number;
691
+ total_tokens?: number;
692
+ input_tokens_details?: { cached_tokens?: number };
693
+ output_tokens_details?: { reasoning_tokens?: number };
694
+ cost?: number;
695
+ }
696
+
697
+ /** openai-node `ResponseCompletedEvent`/incomplete — `response.incomplete_details`
698
+ * is snake_case. Carried via the `model` carrier. */
699
+ interface OpenAIResponsesCompleted {
700
+ type: "response.completed" | "response.incomplete";
701
+ response: {
702
+ id: string;
703
+ status: "completed" | "incomplete";
704
+ incomplete_details?: { reason?: string };
705
+ usage?: OpenAIResponseUsage;
706
+ };
707
+ }
708
+
709
+ /** openai-node `ResponseOutputItemAddedEvent` — fired when a new output item starts.
710
+ * When `item.type === "function_call"`, this is the AUTHORITATIVE tool-start source
711
+ * (canonical model, A1). Note: the raw Responses event uses snake_case `call_id`
712
+ * (DISTINCT from the run-item's camelCase `callId`). Carried via the `model` carrier. */
713
+ interface OpenAIResponsesOutputItemAdded {
714
+ type: "response.output_item.added";
715
+ item: {
716
+ id: string; // the fc_… Responses item id
717
+ type: string; // "function_call" | "message" | "reasoning" | …
718
+ call_id?: string; // snake_case — only present when type==="function_call"
719
+ name?: string; // tool name — only present when type==="function_call"
720
+ status?: string;
721
+ arguments?: string;
722
+ };
723
+ }
724
+
725
+ /** openai-node `ResponseFailedEvent` — the response itself failed (e.g. rate limit).
726
+ * Carried via the `model` carrier. */
727
+ interface OpenAIResponsesFailed {
728
+ type: "response.failed";
729
+ response: {
730
+ id: string;
731
+ error?: { message?: string; code?: string };
732
+ };
733
+ }
734
+
735
+ /** A top-level streaming error event (non-terminal advisory, spec §4). */
736
+ interface OpenAIResponsesError {
737
+ type: "error";
738
+ message: string;
739
+ code?: string;
740
+ }
741
+
742
+ /** The faithful projection of the openai-node `ResponseStreamEvent` events the
743
+ * normalizer consumes (the carrier `event` payload). */
744
+ type OpenAIRawResponsesEvent =
745
+ | OpenAIResponsesCreated
746
+ | OpenAIResponsesOutputItemAdded
747
+ | OpenAIResponsesFnArgsDelta
748
+ | OpenAIResponsesFnArgsDone
749
+ | OpenAIResponsesTextDelta
750
+ | OpenAIResponsesTextDone
751
+ | OpenAIResponsesCompleted
752
+ | OpenAIResponsesFailed
753
+ | OpenAIResponsesError;
754
+
755
+ // ── the Agents SDK `StreamEvent` union (RunRawModelStreamEvent.data) ──────────
756
+ /** `StreamEventTextStream` — `{ type:"output_text_delta"; delta }`. */
757
+ interface OpenAIStreamEventTextDelta {
758
+ type: "output_text_delta";
759
+ delta: string;
760
+ }
761
+ /** `StreamEventResponseStarted` — `{ type:"response_started" }`. */
762
+ interface OpenAIStreamEventResponseStarted {
763
+ type: "response_started";
764
+ }
765
+ /** `StreamEventResponseCompleted` — `{ type:"response_done"; response? }`. */
766
+ interface OpenAIStreamEventResponseDone {
767
+ type: "response_done";
768
+ response?: { id: string; usage?: OpenAIResponseUsage };
769
+ }
770
+ /** `StreamEventGenericItem` — the generic `model` carrier. The verbatim
771
+ * openai-node Responses event rides in `event`. */
772
+ interface OpenAIStreamEventModel {
773
+ type: "model";
774
+ event: OpenAIRawResponsesEvent;
775
+ }
776
+ /** The SDK `ResponseStreamEvent`/`StreamEvent` union (`RunRawModelStreamEvent.data`). */
777
+ type OpenAIResponseStreamEvent =
778
+ | OpenAIStreamEventTextDelta
779
+ | OpenAIStreamEventResponseStarted
780
+ | OpenAIStreamEventResponseDone
781
+ | OpenAIStreamEventModel;
782
+
783
+ interface OpenAIRawModelStreamEvent {
784
+ type: "raw_model_stream_event";
785
+ data: OpenAIResponseStreamEvent;
786
+ }
787
+
788
+ /** A SYNTHETIC terminal sentinel the host feeds the normalizer when the
789
+ * `@openai/agents` runtime THROWS `MaxTurnsExceededError` from
790
+ * `await stream.completed` after the stream ends (the spike confirmed
791
+ * `max_turns` is NOT a native stream event). The host (T6) catches the throw
792
+ * and injects this; the normalizer maps it to `turn.error{code:"max_turns",…}`.
793
+ * Modeled as a real arm of the native union (NOT cast) so the guard + drive
794
+ * switch handle it type-safely. `usage` mirrors the neutral `AgUsage` shape. */
795
+ export interface OpenAIHostError {
796
+ type: "__host_error__";
797
+ code: string;
798
+ message: string;
799
+ usage?: AgUsage;
800
+ }
801
+
802
+ /** The fixture-contract input union (verified shapes; see file header). */
803
+ export type OpenAIStreamEvent =
804
+ | OpenAIMessageOutputEvent
805
+ | OpenAIToolCalledEvent
806
+ | OpenAIToolOutputEvent
807
+ | OpenAIToolSearchCalledEvent
808
+ | OpenAIToolSearchOutputCreatedEvent
809
+ | OpenAIReasoningEvent
810
+ | OpenAIHandoffRequestedEvent
811
+ | OpenAIHandoffOccurredEvent
812
+ | OpenAIToolApprovalRequestedEvent
813
+ | OpenAIRawModelStreamEvent
814
+ | OpenAIHostError;
815
+
816
+ // ─── finish-reason → AgFinishReason (spec §4) ─────────────────────────────────
817
+ // Maps any OpenAI completion / `response.incomplete_details.reason` to the
818
+ // neutral AgFinishReason superset. A bare `response.completed` (no reason) = stop.
819
+ export function mapFinishReason(reason: string | undefined | null): AgFinishReason {
820
+ switch (reason) {
821
+ case undefined:
822
+ case null:
823
+ case "stop":
824
+ case "completed":
825
+ return "stop";
826
+ case "max_output_tokens":
827
+ case "max_tokens":
828
+ return "token_limit";
829
+ case "content_filter":
830
+ return "safety_blocked";
831
+ default:
832
+ return "unknown";
833
+ }
834
+ }
835
+
836
+ // ─── tool-output content → AgBlock[] (spec §2) ────────────────────────────────
837
+ function toolOutputToAgBlocks(
838
+ output: OpenAIFunctionCallResultItem["output"],
839
+ ): AgBlock[] {
840
+ if (typeof output === "string") {
841
+ return output.length > 0 ? [{ type: "text", text: output }] : [];
842
+ }
843
+ const parts = Array.isArray(output) ? output : [output];
844
+ const out: AgBlock[] = [];
845
+ for (const part of parts) {
846
+ // Two DIFFERENT text discriminants ride this seam (Finding #2 above):
847
+ // "text" on the bare-object arm, "input_text" on the array arm.
848
+ if (part.type === "text" || part.type === "input_text") {
849
+ out.push({ type: "text", text: part.text });
850
+ }
851
+ }
852
+ return out;
853
+ }
854
+
855
+ // ─── usage mapping: OpenAI response usage → AgUsage ──────────────────────────
856
+ // cumulative:false — OpenAI usage is FINAL (not cumulative like Anthropic).
857
+ function mapUsage(usage: OpenAIResponseUsage | undefined): AgUsage | undefined {
858
+ if (usage === undefined) return undefined;
859
+ const u: AgUsage = { cumulative: false };
860
+ if (usage.input_tokens !== undefined) u.inputTokens = usage.input_tokens;
861
+ if (usage.output_tokens !== undefined) u.outputTokens = usage.output_tokens;
862
+ if (usage.total_tokens !== undefined) u.totalTokens = usage.total_tokens;
863
+ if (usage.input_tokens_details?.cached_tokens !== undefined)
864
+ u.cacheReadTokens = usage.input_tokens_details.cached_tokens;
865
+ if (usage.output_tokens_details?.reasoning_tokens !== undefined)
866
+ u.reasoningTokens = usage.output_tokens_details.reasoning_tokens;
867
+ // Provider-reported cost (e.g. OpenRouter `cost`) maps verbatim to costUsd.
868
+ if (usage.cost !== undefined) u.costUsd = usage.cost;
869
+ return u;
870
+ }
871
+
872
+ // ─── url_citation annotation → AgCitation ──────────────────────────────────
873
+ // `partText` is the source output_text part's text string; used to extract the
874
+ // cited substring from the char-offset indices carried by the annotation (Fix 3).
875
+ function mapAnnotationsToCitations(
876
+ annotations: OpenAIAnnotation[] | undefined,
877
+ partText: string,
878
+ ): AgCitation[] | undefined {
879
+ if (annotations === undefined || annotations.length === 0) return undefined;
880
+ const out: AgCitation[] = [];
881
+ for (const ann of annotations) {
882
+ if (ann.type === "url_citation") {
883
+ // Extract the cited substring from the part text when both offsets are present
884
+ // and valid (Fix 3). Fall back to "" when any guard condition fails.
885
+ const startIdx = ann.start_index;
886
+ const endIdx = ann.end_index;
887
+ const citedText =
888
+ startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
889
+ ? partText.slice(startIdx, endIdx)
890
+ : "";
891
+ const cit: AgCitation = {
892
+ kind: "url",
893
+ url: ann.url,
894
+ citedText,
895
+ indexFrame: "response",
896
+ };
897
+ if (ann.title !== undefined) cit.title = ann.title;
898
+ if (startIdx !== undefined) cit.startIndex = startIdx;
899
+ if (endIdx !== undefined) cit.endIndex = endIdx;
900
+ out.push(cit);
901
+ }
902
+ // file_citation: no url-kind match; skip (deferred to a later slice — only remaining silent annotation drop)
903
+ }
904
+ return out.length > 0 ? out : undefined;
905
+ }
906
+
907
+ // ─── structural guard: unknown → OpenAIStreamEvent ────────────────────────────
908
+ // `createOpenaiNormalizer().push` receives the genuine JSON boundary (`JsonValue`,
909
+ // spec §0.1). The run-seam yields well-formed `OpenAIStreamEvent`s, but this is the
910
+ // deserialization boundary, so we confirm the OUTER discriminant before driving the
911
+ // engine. A user-defined type guard (not a cast) narrows on success; a failure routes
912
+ // the raw payload to `ext.openai.unparsed` and returns (graceful, Tenet 6).
913
+ //
914
+ // The guard takes `unknown` (not `JsonValue`): `OpenAIStreamEvent`'s nested
915
+ // interfaces have no index signature, so a `v is OpenAIStreamEvent` predicate over a
916
+ // `JsonValue` param is rejected by TS (TS2677). `unknown` is the genuine boundary
917
+ // input type and is predicate-compatible; the caller passes a `JsonValue`, which
918
+ // widens to `unknown` losslessly (mirrors the Claude facet's `isSDKMessage`).
919
+ function isJsonObject(v: unknown): v is { readonly [k: string]: JsonValue } {
920
+ return typeof v === "object" && v !== null && !Array.isArray(v);
921
+ }
922
+
923
+ /**
924
+ * Extract `structuredContent` (the ggui cache-marker channel, spec §2.1/§4)
925
+ * from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
926
+ * follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
927
+ * would be an object keyed by `.structuredContent`; a live capture
928
+ * (`echo-gpt55`, gpt-5.5 / agents-core 0.12.0) proved that assumption never
929
+ * matches real `@openai/agents` native-MCP wire — `wrapperOutput` there is a
930
+ * JSON-STRINGIFIED string (`'{"type":"text","text":"…"}'`), because
931
+ * `RunToolCallOutputItem.toJSON()` (agents-core 0.12.0's `dist/items.mjs`)
932
+ * runs `.output` through `toSmartString`, which passes strings through
933
+ * unchanged but JSON.stringifies objects — and the object it stringifies
934
+ * (`content[0]`, the raw MCP content ITEM) never had a `.structuredContent`
935
+ * sibling to begin with: `mcpToFunctionTool`'s `invoke()`
936
+ * (agents-core 0.12.0's `dist/mcp.mjs:672-738`) reads
937
+ * `result.structuredContent` off the full `CallToolResult` but discards it
938
+ * unless `useStructuredContent` is `true` (which instead merges it into the
939
+ * MODEL-VISIBLE text — a spec violation, not a fix; rejected, see
940
+ * `packages/e2e/src/agents/openai-agents-sdk/run.ts`) — so under the SDK
941
+ * default, structuredContent is unconditionally dropped BEFORE it ever
942
+ * reaches `item.output`. This is true for `@openai/agents-core` 0.2.1 too
943
+ * (grep-verified: zero mentions of `structuredContent` anywhere in its
944
+ * `dist/`) — the whole `>=0.2.0 <0.13` peer range's native MCP client drops
945
+ * it by default; there is no version where the ORIGINAL assumed shape was
946
+ * ever real wire truth for a native-MCP-routed tool call.
947
+ *
948
+ * The ONE real channel `@openai/agents-core` 0.12.0 offers is
949
+ * `MCPServer.customDataExtractor` (absent before 0.12): a per-server
950
+ * callback that receives `{ …, structuredContent }` and whose (JSON-
951
+ * validated, SDK-normalized) return value lands verbatim on
952
+ * `RunToolCallOutputItem.customData` — a NEW sibling field to `.output`,
953
+ * included as-is (not smart-stringified) by `toJSON()`. This requires the
954
+ * CALLER (the agent/worker that constructs the `MCPServer`) to opt in —
955
+ * the facet cannot conjure data the wire never carries. Two homes are
956
+ * checked, in order:
957
+ *
958
+ * 1. `customData.structuredContent` — the 0.12.0+ channel above.
959
+ * 2. `wrapperOutput.structuredContent` — kept as defense-in-depth for
960
+ * callers whose OWN local (non-MCP-native) tool wrapping manually
961
+ * returns a full `CallToolResult`-shaped object (unverified against the
962
+ * SDK's native MCP client, but a real possible shape for a custom local
963
+ * tool's return value); also tried after a SAFE `JSON.parse` when
964
+ * `wrapperOutput` is a string (never throws out of `push()` — Tenet 6;
965
+ * a parse failure or a parsed value with no `.structuredContent` key is
966
+ * the ordinary case for a plain-text tool result, not an anomaly worth
967
+ * an `ext` carry).
968
+ *
969
+ * Neither home firing (the common case — most tool results carry no
970
+ * structuredContent at all) is NOT a drop: it correctly yields `undefined`.
971
+ */
972
+ function extractStructuredContent(
973
+ wrapperOutput: JsonValue | undefined,
974
+ customData: JsonValue | undefined,
975
+ ): JsonValue | undefined {
976
+ if (isJsonObject(customData) && isJsonObject(customData.structuredContent)) {
977
+ return JsonValue.parse(customData.structuredContent);
978
+ }
979
+ if (isJsonObject(wrapperOutput) && isJsonObject(wrapperOutput.structuredContent)) {
980
+ return JsonValue.parse(wrapperOutput.structuredContent);
981
+ }
982
+ if (typeof wrapperOutput === "string") {
983
+ try {
984
+ const parsed: unknown = JSON.parse(wrapperOutput);
985
+ if (isJsonObject(parsed) && isJsonObject(parsed.structuredContent)) {
986
+ return JsonValue.parse(parsed.structuredContent);
987
+ }
988
+ } catch {
989
+ // Not JSON, or JSON with no `.structuredContent` key — the ordinary
990
+ // shape for a plain-text tool result. No structuredContent to extract;
991
+ // never throw out of push() (Tenet 6).
992
+ }
993
+ }
994
+ return undefined;
995
+ }
996
+
997
+ // Only the OUTER envelope is validated here (the RunStreamEvent families: a
998
+ // `run_item_stream_event` with a string `name`, a `raw_model_stream_event` with a
999
+ // `data` object, or the synthetic `__host_error__` terminal sentinel the host feeds
1000
+ // on `MaxTurnsExceededError`). The inner `drive` switch handles every nested arm
1001
+ // structurally and no-ops anything it does not recognise — so a partially-shaped-but-
1002
+ // well-typed event is never lost, and only a genuinely non-OpenAI-shaped payload
1003
+ // falls to `unparsed`.
1004
+ function isOpenAIStreamEvent(v: unknown): v is OpenAIStreamEvent {
1005
+ if (!isJsonObject(v)) return false;
1006
+ if (v.type === "run_item_stream_event") return typeof v.name === "string";
1007
+ if (v.type === "raw_model_stream_event") return isJsonObject(v.data);
1008
+ if (v.type === "__host_error__")
1009
+ return typeof v.code === "string" && typeof v.message === "string";
1010
+ return false;
1011
+ }
1012
+
1013
+ // ─── the stateful normalizer (A1 §5-6) ────────────────────────────────────────
1014
+ /**
1015
+ * Build a stateful OpenAI-facet normalizer over a fresh {@link StreamAssembler}.
1016
+ *
1017
+ * OpenAI has no native `turn.start` and the assistant turn is delivered as a
1018
+ * stream of redundant representations (the SDK emits `response_started`, a
1019
+ * `model:response.created`, an in-progress duplicate, BOTH a flattened
1020
+ * `output_text_delta` literal and the real item-id-keyed
1021
+ * `model:response.output_text.delta`, a `response_done` literal, and TWO
1022
+ * `model:response.completed` events per response). The normalizer drives the
1023
+ * engine from the SINGLE authoritative source per concern (BINDING canonical
1024
+ * model, plan §"Spike Findings") and ignores the rest:
1025
+ *
1026
+ * - turn open ← `model:response.created` (real `response.id` present at start)
1027
+ * - text ← `model:response.output_text.delta` (carries `item_id`)
1028
+ * - text end ← the `message_output_created` run-item (authoritative close +
1029
+ * citations carrier, audit M22 — `response.output_text.done` is a
1030
+ * no-op; text streams left open by it fall to the defensive
1031
+ * close-any-dangling-stream fallback in `closeResponse()` /
1032
+ * `endOpenStreamsAndCloseMessage()` / `emitRoundClose()`)
1033
+ * - turn close ← `model:response.completed` (guard close-once)
1034
+ *
1035
+ * `ensureResponseOpen()` opens turn + message exactly once per response;
1036
+ * `closeResponse()` resets per-response state so the duplicate `response.completed`
1037
+ * is a no-op.
1038
+ *
1039
+ * `reasoning_item_created` / `tool_approval_requested` (Task 3, audit M48) map to
1040
+ * `reasoning.start/delta/end/opaque` and `hitl.ask{kind:"approval"}` respectively —
1041
+ * see `driveReasoningItemCreated` and the run-item switch below for the full
1042
+ * rationale. `handoff_requested` / `handoff_occurred` (Task 3, audit M48 review
1043
+ * Finding 1) map to a `subagentStart`/`subagentDone` PAIR bracketing the transfer —
1044
+ * the ORIGINAL Task-3 mapping used a standalone `handoff` event on the false premise
1045
+ * that the wire carried no completion signal; `handoff_occurred` IS that signal
1046
+ * (verified against the installed `@openai/agents-core` 0.2.1 peer dep's
1047
+ * `events.d.ts`). The bare `handoff` event still fires — carrying `toAgentName` —
1048
+ * but only once it's actually known, at `handoff_occurred` (the target agent is not
1049
+ * resolvable at `handoff_requested` time on the real wire; see the run-item switch's
1050
+ * `handoff_requested`/`handoff_occurred` cases for the full rationale, including why
1051
+ * identity can't ride the `subagentStart` call itself). `emitExt` is reserved for a
1052
+ * genuinely unrecognisable OUTER envelope AND — per the run-item switch's default
1053
+ * arm — a genuinely-unknown run-item `name` (mirrors the Claude facet).
1054
+ */
1055
+ export function createOpenaiNormalizer(): Normalizer {
1056
+ const a = new StreamAssembler();
1057
+ // OpenAI's native stream carries no thread/session id (unlike Claude's
1058
+ // `session_id`), so the threadId is a fixed facet label. The Router rebases
1059
+ // ids downstream.
1060
+ const threadId = "openai";
1061
+
1062
+ // Per-response anchoring state (one open response at a time on this seam).
1063
+ let turnCounter = 0;
1064
+ let turnId: string | undefined; // current open response's turn id
1065
+ let msgId: string | undefined; // current open message id
1066
+ let responseId: string | undefined; // real response.id once known
1067
+ // Open text streams keyed by Responses item_id (textStart once per id).
1068
+ const openTextStreams = new Set<string>();
1069
+ // Close-once guard: the SDK emits `response.completed` TWICE per response. Once a
1070
+ // response.id (or a synthesized turnId) has been closed, any further terminal event
1071
+ // for it is a no-op — it must NOT reopen a fresh message/turn.
1072
+ const closedResponses = new Set<string>();
1073
+
1074
+ // Task 3 (audit M48 review, Finding 1) — handoff-bracket state. Every
1075
+ // run-item event on this seam arrives AFTER its owning round's
1076
+ // `response.completed` on the real wire (M22 late-citations / Task 4b
1077
+ // late-tool-result precedent — verified against @openai/agents-core
1078
+ // 0.2.1's `run.mjs`/`runImplementation.mjs`: `streamStepItemsToRunResult`
1079
+ // streams `processedResponse.newItems` — which includes the
1080
+ // `handoff_call_item` — only AFTER the raw-event loop for that round
1081
+ // completes, and the `handoff_output_item` from `executeHandoffCalls`
1082
+ // streams later still, before the NEXT round's `response.created`). So by
1083
+ // the time either `handoff_requested` or `handoff_occurred` lands, the
1084
+ // per-response `turnId` var above has already been reset to `undefined` by
1085
+ // `resetResponseState()` — this facet needs a tracker that SURVIVES that
1086
+ // reset to resolve "the round that requested the handoff" as the subagent
1087
+ // bracket's `parentTurnId`. Set once per genuinely-new round in
1088
+ // `ensureResponseOpen()`; never cleared on close (deliberately — that's
1089
+ // the whole point). Intermediate response rounds after a handoff continue
1090
+ // opening their OWN top-level turns from their own `response.id` (openai's
1091
+ // turn model) — the subagent pair BRACKETS the transfer, it does not
1092
+ // re-parent later rounds to it.
1093
+ let lastTopLevelTurnId: string | undefined;
1094
+ // Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
1095
+ let handoffOrdinal = 0;
1096
+ // FIFO queue of open handoff brackets awaiting their matching
1097
+ // `handoff_occurred` (paired turnId + the SAME parentTurnId `subagentStart`
1098
+ // used — `subagentDone` must replay it verbatim, mirroring the
1099
+ // claude-agent-sdk facet's paired start/done convention). Only one handoff
1100
+ // genuinely executes per round on the real wire (`executeHandoffCalls`
1101
+ // rejects the rest), so in practice at most one entry is ever open — FIFO
1102
+ // is the defensively-correct match rule regardless.
1103
+ const openHandoffs: { turnId: string; parentTurnId: string }[] = [];
1104
+
1105
+ // Per-instance tool state (T5b — replaces the module-level statics for the factory path).
1106
+ // fc_… item id → model call_id correlation, populated by response.output_item.added
1107
+ // (the AUTHORITATIVE tool-start source per the canonical model, A1).
1108
+ const instanceCallIdByItemId = new Map<string, string>();
1109
+ // Accumulated function_call_arguments.delta fragments, keyed by fc_ item id.
1110
+ // The engine accumulates for downstream use; `.done.arguments` carries the full
1111
+ // string so argBuffers is primarily for the fallback path.
1112
+ const instanceArgBuffers = new Map<string, string>();
1113
+
1114
+ // Refusal tracking (T5c — instance state mirroring the old module-level
1115
+ // `pendingRefusal`). Set when a `message_output_created` run-item carries a
1116
+ // `refusal` content part; the downstream `response.completed` arm then closes
1117
+ // the turn with `finishReason:"refusal"`. Cleared on every response close so it
1118
+ // never leaks across turns.
1119
+ let pendingRefusal = false;
1120
+
1121
+ // ── Task 4b: defer a round's close past its pending tool results ───────────
1122
+ // (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
1123
+ // AFTER `response.completed` — closing at native-close time would put a later
1124
+ // `tool.done` on an already-sealed message / closed turn, which `reduce()`
1125
+ // correctly parks (resync). Per-turn pending set: toolCallIds that have had
1126
+ // `tool.start` emitted but no `tool.done` yet.
1127
+ const pendingToolsByTurn = new Map<string, Set<string>>();
1128
+ // toolCallId → the turnId it started under. `tool_output` may land after this
1129
+ // response's local `turnId` var has been reset (resetResponseState runs at
1130
+ // native-close time regardless of deferral) and/or after a NEW round has
1131
+ // opened, so the engine's #lastTurn backfill could misattribute a late result
1132
+ // to the wrong turn without this explicit map.
1133
+ const turnIdByToolCallId = new Map<string, string>();
1134
+
1135
+ /**
1136
+ * Register `callId` as pending a `tool.done` under the CURRENT open turn
1137
+ * (Task 4b). Shared by the raw `response.output_item.added` function_call
1138
+ * path and the built-in Shell/Apply-Patch `tool_called` synthesis path
1139
+ * (playbook 2026-07-03 SDK-bump adaptation, Finding #1) — both start a call
1140
+ * whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
1141
+ * is open (defensive; every caller already calls `ensureResponseOpen()` first).
1142
+ */
1143
+ function registerPendingTool(callId: string): void {
1144
+ if (turnId === undefined) return;
1145
+ let pending = pendingToolsByTurn.get(turnId);
1146
+ if (pending === undefined) {
1147
+ pending = new Set<string>();
1148
+ pendingToolsByTurn.set(turnId, pending);
1149
+ }
1150
+ pending.add(callId);
1151
+ turnIdByToolCallId.set(callId, turnId);
1152
+ }
1153
+ // A round's close is MORE than `closeTurnDone`: `reduce()`'s message.end
1154
+ // handler (SPEC §5.0 INV-MSG, same enforcement commit) clears the message's
1155
+ // open-pointer UNCONDITIONALLY — independent of turn state — so a `tool.done`
1156
+ // landing after `message.end` resync-parks just as surely as one landing
1157
+ // after `turn.done`. Deferring `turn.done` alone is NOT sufficient: closing
1158
+ // the message must be deferred too, or the late `tool.done` has nowhere live
1159
+ // to attach. So the stash captures everything `endOpenStreamsAndCloseMessage`
1160
+ // + `closeTurnDone` need — captured because `resetResponseState()` (which
1161
+ // always runs at native-close time, deferred or not) clears the local
1162
+ // `msgId`/`openTextStreams` vars before the drain can replay them.
1163
+ interface StashedRoundClose {
1164
+ msgId: string;
1165
+ openTextStreamIds: string[];
1166
+ fields: TurnDoneFields;
1167
+ }
1168
+ // Stashed close for a turn whose pending set was non-empty at close time,
1169
+ // keyed by turnId. Consumed the moment its pending set drains (emitted right
1170
+ // after the draining `tool.done`, same push() batch), or by `flush()`
1171
+ // verbatim if the result never arrives (the round genuinely completed — a
1172
+ // missing tool result must not swallow the close).
1173
+ const stashedCloseByTurn = new Map<string, StashedRoundClose>();
1174
+
1175
+ /**
1176
+ * End open text streams + close the message + closeTurnDone for `tid`, using
1177
+ * whichever values are live right now (immediate path) or were captured at
1178
+ * defer time (drain path) — same three calls either way.
1179
+ */
1180
+ function emitRoundClose(tid: string, mId: string, textStreamIds: readonly string[], fields: TurnDoneFields): void {
1181
+ for (const streamId of textStreamIds) a.textEnd(streamId, mId);
1182
+ a.closeMessage(mId);
1183
+ a.closeTurnDone(tid, fields);
1184
+ }
1185
+
1186
+ /**
1187
+ * Close the round now, unless `tid`'s pending-tool set is non-empty — in
1188
+ * which case stash everything the close needs (message id, dangling text
1189
+ * stream ids, turn.done fields) for the `tool_output` handler (or `flush()`)
1190
+ * to replay later. `closeTurnError` paths never call this (they close
1191
+ * immediately via `endOpenStreamsAndCloseMessage` — an errored round's
1192
+ * pending results are moot, by design).
1193
+ */
1194
+ function finishOrDeferRound(tid: string, mId: string, textStreamIds: readonly string[], fields: TurnDoneFields): void {
1195
+ const pending = pendingToolsByTurn.get(tid);
1196
+ if (pending !== undefined && pending.size > 0) {
1197
+ stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
1198
+ return;
1199
+ }
1200
+ emitRoundClose(tid, mId, textStreamIds, fields);
1201
+ }
1202
+
1203
+ /**
1204
+ * Open the turn + message exactly once per response. Uses the real `response.id`
1205
+ * (`turn_<id>`) when known; synthesizes a stable id only if `response.created` was
1206
+ * somehow absent (defensive — the spike confirms the id is always present at start).
1207
+ * Returns the close-once key (the real response.id, else the synthesized turnId),
1208
+ * or `undefined` when the response has already been closed (caller must no-op).
1209
+ */
1210
+ function ensureResponseOpen(respId?: string): string | undefined {
1211
+ // Already closed → never reopen (the duplicate `response.completed` lands here).
1212
+ if (respId !== undefined && closedResponses.has(respId)) return undefined;
1213
+ if (turnId !== undefined) {
1214
+ // Backfill the real id if it arrives after a defensive synthesized open.
1215
+ if (respId !== undefined && responseId === undefined) responseId = respId;
1216
+ return responseId ?? turnId;
1217
+ }
1218
+ responseId = respId;
1219
+ turnId = respId !== undefined ? `turn_${respId}` : `turn_${threadId}_${++turnCounter}`;
1220
+ msgId = `msg_${turnId}`;
1221
+ // Task 3 (audit M48 review, Finding 1): survives resetResponseState() —
1222
+ // see the closure-state doc above.
1223
+ lastTopLevelTurnId = turnId;
1224
+ a.openTurn(turnId, threadId);
1225
+ a.openMessage({ id: msgId, role: "assistant", turnId, threadId });
1226
+ return responseId ?? turnId;
1227
+ }
1228
+
1229
+ /** Reset per-response state after a close. Marks the response closed (close-once). */
1230
+ function resetResponseState(): void {
1231
+ const key = responseId ?? turnId;
1232
+ if (key !== undefined) closedResponses.add(key);
1233
+ openTextStreams.clear();
1234
+ turnId = undefined;
1235
+ msgId = undefined;
1236
+ responseId = undefined;
1237
+ pendingRefusal = false;
1238
+ }
1239
+
1240
+ /**
1241
+ * Close any dangling open message/turn (flush path: a stream ended before
1242
+ * `response.completed`). Ends open text streams, closes the message, and reuses
1243
+ * `resetResponseState` so the response is marked closed.
1244
+ */
1245
+ function closeResponse(): void {
1246
+ if (msgId !== undefined) {
1247
+ for (const streamId of openTextStreams) a.textEnd(streamId, msgId);
1248
+ a.closeMessage(msgId);
1249
+ }
1250
+ resetResponseState();
1251
+ }
1252
+
1253
+ /** Drive the engine from one verbatim openai-node Responses event (snake_case). */
1254
+ function driveRawResponsesEvent(ev: OpenAIRawResponsesEvent): void {
1255
+ switch (ev.type) {
1256
+ case "response.created": {
1257
+ // Authoritative turn open — the real response.id is present at start.
1258
+ ensureResponseOpen(ev.response.id);
1259
+ return;
1260
+ }
1261
+ case "response.output_text.delta": {
1262
+ ensureResponseOpen();
1263
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies the narrowing
1264
+ if (!openTextStreams.has(ev.item_id)) {
1265
+ openTextStreams.add(ev.item_id);
1266
+ a.textStart(ev.item_id, msgId, { role: "assistant" });
1267
+ }
1268
+ // OpenAI text deltas are suffix-only fragments (cumulative:false, the default).
1269
+ a.textDelta(ev.item_id, msgId, ev.delta, { cumulative: false });
1270
+ return;
1271
+ }
1272
+ case "response.output_text.done": {
1273
+ // NO-OP (audit M22): the citations carrier — `message_output_created` — is
1274
+ // the authoritative text-end source (it also reports refusal parts and
1275
+ // arrives with the annotated part, so closing here would emit `text.end`
1276
+ // BEFORE citations are known). The stream stays in `openTextStreams`;
1277
+ // `driveMessageOutputCreated` closes it (with citations if present), or —
1278
+ // defensively, if that run-item never arrives — `closeResponse()` /
1279
+ // `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
1280
+ return;
1281
+ }
1282
+ case "response.output_item.added": {
1283
+ // Authoritative tool-start source (canonical model, A1 §"Spike Findings").
1284
+ // Only function_call items carry a tool name + call_id; other item types
1285
+ // (message, reasoning) are no-op'd here — their lifecycle is handled elsewhere.
1286
+ if (ev.item.type === "function_call" && ev.item.call_id !== undefined && ev.item.name !== undefined) {
1287
+ const fcId = ev.item.id;
1288
+ const callId = ev.item.call_id;
1289
+ ensureResponseOpen();
1290
+ // Record the fc_→call_id correlation (the raw argument events carry only
1291
+ // the fc_ item id, not the call_id; this mapping allows recovery).
1292
+ instanceCallIdByItemId.set(fcId, callId);
1293
+ a.toolStart({
1294
+ toolCallId: callId,
1295
+ name: ev.item.name,
1296
+ itemId: fcId,
1297
+ messageId: msgId,
1298
+ });
1299
+ // Task 4b: this call is now pending a tool.done under the current turn
1300
+ // (ensureResponseOpen() above guarantees `turnId` is defined here).
1301
+ registerPendingTool(callId);
1302
+ }
1303
+ return;
1304
+ }
1305
+ case "response.function_call_arguments.delta": {
1306
+ // Accumulate the fragment per fc_ item id (spec §8.1).
1307
+ const prevDelta = instanceArgBuffers.get(ev.item_id) ?? "";
1308
+ instanceArgBuffers.set(ev.item_id, prevDelta + ev.delta);
1309
+ // Resolve to call_id for the engine (fall back to fc_ id defensively).
1310
+ const callIdDelta = instanceCallIdByItemId.get(ev.item_id) ?? ev.item_id;
1311
+ a.toolArgsDelta(callIdDelta, ev.delta, { cumulative: false });
1312
+ return;
1313
+ }
1314
+ case "response.function_call_arguments.done": {
1315
+ // Seal accumulated buffer → toolArgsAssembled. Prefer the event's full
1316
+ // `arguments` string (the engine accumulates the delta path); fall back to
1317
+ // the instance buffer when the done event omits it (defensive).
1318
+ //
1319
+ // `ev.arguments` is typed `string`, but this is the deserialization
1320
+ // boundary (audit M46, §2.B): a nonconforming provider (OpenRouter et
1321
+ // al.) can hand back an empty string, truncated JSON, or omit the
1322
+ // field entirely — `JSON.parse` throws `SyntaxError` on the first two
1323
+ // and `.length` throws `TypeError` on the third, all three of which
1324
+ // used to escape push() uncaught. Widen the local binding (no cast —
1325
+ // the boundary genuinely can hand back less than the type promises)
1326
+ // and guard the parse: on any failure, degrade to a best-effort
1327
+ // `tool.args.assembled` with `input:{}` (keeps the tool-call block
1328
+ // fold-coherent, Tenet 6) and route the untouched raw signal through
1329
+ // `ext.openai.unparsed` instead of throwing — an explicit `null`
1330
+ // marker distinguishes "field never arrived" from "field arrived
1331
+ // empty" (`""`), both preserved losslessly.
1332
+ const rawArguments: string | undefined = ev.arguments;
1333
+ const buffered = instanceArgBuffers.get(ev.item_id) ?? "";
1334
+ const candidate =
1335
+ rawArguments !== undefined && rawArguments.length > 0 ? rawArguments : buffered;
1336
+ const callIdDone = instanceCallIdByItemId.get(ev.item_id) ?? ev.item_id;
1337
+ let input: JsonValue;
1338
+ try {
1339
+ input = JsonValue.parse(JSON.parse(candidate));
1340
+ } catch {
1341
+ input = {};
1342
+ a.emitExt("openai", "unparsed", { itemId: ev.item_id, arguments: rawArguments ?? null });
1343
+ }
1344
+ a.toolArgsAssembled(callIdDone, input);
1345
+ instanceArgBuffers.delete(ev.item_id);
1346
+ return;
1347
+ }
1348
+ case "response.completed":
1349
+ case "response.incomplete": {
1350
+ // Terminal close — guard close-once (the SDK emits completed TWICE). A
1351
+ // `undefined` return means this response is already closed → no-op the dupe.
1352
+ if (ensureResponseOpen(ev.response.id) === undefined) return;
1353
+ if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
1354
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
1355
+ // Snapshot before any deferral: `resetResponseState()` below always
1356
+ // clears these, but a deferred close needs them later (Task 4b).
1357
+ const currentTurnId = turnId;
1358
+ const currentMsgId = msgId;
1359
+ const textStreamIds = Array.from(openTextStreams);
1360
+ const reason = ev.response.incomplete_details?.reason;
1361
+ const usage = mapUsage(ev.response.usage);
1362
+ // Decision tree (mirrors the canonical model, A1):
1363
+ // refusal recorded → closeTurnDone success, finishReason:"refusal"
1364
+ // content_filter → closeTurnDone error-outcome + safety signal
1365
+ // any other incomplete → closeTurnError{code:reason, usage}
1366
+ // plain completed → closeTurnDone success
1367
+ // Task 4b: every closeTurnDone arm below routes through
1368
+ // `finishOrDeferRound` — a round with pending tool results stashes its
1369
+ // ENTIRE close (message + turn) instead of emitting (INV-MSG).
1370
+ // closeTurnError does NOT defer (an errored round's pending results are
1371
+ // moot, by design) — it still closes the message immediately here.
1372
+ if (pendingRefusal) {
1373
+ finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1374
+ outcome: { type: "success" },
1375
+ finishReason: "refusal",
1376
+ ...(usage !== undefined ? { usage } : {}),
1377
+ });
1378
+ } else if (reason === "content_filter") {
1379
+ const safety: AgSafety[] = [{ category: "content_filter", blocked: true }];
1380
+ finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1381
+ outcome: { type: "error", message: "content_filter" },
1382
+ finishReason: mapFinishReason(reason),
1383
+ safety,
1384
+ ...(usage !== undefined ? { usage } : {}),
1385
+ });
1386
+ } else if (ev.type === "response.incomplete") {
1387
+ endOpenStreamsAndCloseMessage();
1388
+ a.closeTurnError(currentTurnId, {
1389
+ message: reason ?? "incomplete",
1390
+ ...(reason !== undefined ? { code: reason } : {}),
1391
+ ...(usage !== undefined ? { usage } : {}),
1392
+ });
1393
+ } else {
1394
+ finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1395
+ outcome: { type: "success" },
1396
+ finishReason: mapFinishReason(reason),
1397
+ ...(usage !== undefined ? { usage } : {}),
1398
+ });
1399
+ }
1400
+ resetResponseState();
1401
+ return;
1402
+ }
1403
+ case "response.failed": {
1404
+ // The response itself failed (rate limit, server error, …). Close-once guard.
1405
+ if (ensureResponseOpen(ev.response.id) === undefined) return;
1406
+ if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
1407
+ endOpenStreamsAndCloseMessage();
1408
+ const err = ev.response.error;
1409
+ a.closeTurnError(turnId, {
1410
+ message: err?.message ?? "response.failed",
1411
+ ...(err?.code !== undefined ? { code: err.code } : {}),
1412
+ });
1413
+ resetResponseState();
1414
+ return;
1415
+ }
1416
+ case "error": {
1417
+ // Top-level NON-terminal advisory (spec §4 bare `error`). It does NOT close
1418
+ // the turn — surface it on the lossless vendor channel without disturbing the
1419
+ // open response lifecycle.
1420
+ a.emitExt("openai", "error", {
1421
+ message: ev.message,
1422
+ ...(ev.code !== undefined ? { code: ev.code } : {}),
1423
+ });
1424
+ return;
1425
+ }
1426
+ // Duplicate raw families IGNORED per the canonical model:
1427
+ // response.output_text.done is its own no-op arm above (audit M22);
1428
+ // response.output_item.done, response.in_progress, content_part.* are not
1429
+ // authoritative sources.
1430
+ default:
1431
+ return;
1432
+ }
1433
+ }
1434
+
1435
+ /** End any still-open text streams (defensive), then close the open message. */
1436
+ function endOpenStreamsAndCloseMessage(): void {
1437
+ if (msgId !== undefined) {
1438
+ for (const streamId of openTextStreams) a.textEnd(streamId, msgId);
1439
+ a.closeMessage(msgId);
1440
+ }
1441
+ }
1442
+
1443
+ /**
1444
+ * Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
1445
+ * citations source (audit M22). The text itself already streamed from the raw
1446
+ * `response.output_text.delta` path — this MUST NOT re-emit it — but the
1447
+ * `output_text` part's annotations are only known here (they are not present on
1448
+ * `response.output_text.done`), so THIS is where the matching open text stream
1449
+ * actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
1450
+ * directly to the streamed block (never a duplicate id-less supplement). A
1451
+ * `refusal` part sets `pendingRefusal` so the downstream `response.completed`
1452
+ * arm closes with `finishReason:"refusal"` (no text stream to close for it).
1453
+ *
1454
+ * Correlation: the Responses `item_id` used by the raw delta/done events and the
1455
+ * run-item wrapper's `rawItem.id` are DIFFERENT id spaces on this SDK's surface,
1456
+ * so the match is positional — FIFO against `openTextStreams` (insertion-ordered;
1457
+ * in practice exactly one open stream per output_text part).
1458
+ *
1459
+ * On the real wire this run-item can arrive AFTER `response.completed` (verified
1460
+ * by the #128 OpenRouter capture — round 2's `message_output_created` lands last,
1461
+ * past the terminal close). Never `ensureResponseOpen()` here: doing so would
1462
+ * open a PHANTOM new turn once the response has already closed. If `msgId` is
1463
+ * `undefined` (already closed) the matching stream was already ended — without
1464
+ * citations — by the native-close fallback (`emitRoundClose` et al.); degrade
1465
+ * gracefully and skip the `text.end` re-target. If the late part still carries
1466
+ * annotations, though, they are NOT yet lost anywhere else — silently dropping
1467
+ * them here would violate Tenet 6. Route them losslessly through the facet's
1468
+ * existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
1469
+ * the run-item id + the raw annotations array verbatim (review finding on M22).
1470
+ * A part with no annotations has nothing to lose — the plain `continue` stays.
1471
+ */
1472
+ function driveMessageOutputCreated(item: OpenAIAssistantMessageItem): void {
1473
+ for (const part of item.content) {
1474
+ if (part.type === "refusal") {
1475
+ pendingRefusal = true;
1476
+ continue;
1477
+ }
1478
+ if (part.type === "output_text") {
1479
+ if (msgId === undefined) {
1480
+ // response already closed — see doc above.
1481
+ if (part.annotations !== undefined && part.annotations.length > 0) {
1482
+ a.emitExt("openai", "late-citations", {
1483
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
1484
+ annotations: JsonValue.parse(part.annotations),
1485
+ });
1486
+ }
1487
+ continue;
1488
+ }
1489
+ const streamId = openTextStreams.values().next().value;
1490
+ if (streamId === undefined) continue; // defensive: no matching open stream
1491
+ openTextStreams.delete(streamId);
1492
+ const citations = mapAnnotationsToCitations(part.annotations, part.text);
1493
+ a.textEnd(streamId, msgId, citations !== undefined ? { citations } : undefined);
1494
+ }
1495
+ }
1496
+ }
1497
+
1498
+ /**
1499
+ * Map a `reasoning_item_created` run-item (Task 3, audit M48): the SOLE source
1500
+ * for reasoning content on this seam — `response.output_item.added` only special-
1501
+ * cases `item.type==="function_call"` (canonical model, A1); it carries no
1502
+ * `content`/`providerData` for a `reasoning` item, so it structurally cannot
1503
+ * supply the summary text or the ZDR blob and is left untouched (single-source
1504
+ * per concern, no double-emit).
1505
+ *
1506
+ * The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
1507
+ * the incremental text/tool-arg deltas elsewhere in this facet), so
1508
+ * start/delta/end/opaque all fire together, in that order, from this single call:
1509
+ * - `reasoning.start` — opens the block; `itemId` carries the `rs_…` id.
1510
+ * - `reasoning.delta` — the joined `input_text` parts, only if non-empty.
1511
+ * - `reasoning.end` — closes the block.
1512
+ * - `reasoning.opaque` — ONLY when `providerData.encrypted_content` is present:
1513
+ * the OpenAI ZDR (`store:false`) stateless-replay blob (spec §8.2/§10.4),
1514
+ * `kind:"ciphertext"`, with `itemId` carrying the `rs_…` id again (REPLAY-
1515
+ * LOAD-BEARING — `reduce()`'s `reasoning.opaque` handler sets `block.itemId`
1516
+ * from it, spec §4 row for `reasoning.opaque`).
1517
+ *
1518
+ * `id`/`itemId` reuse the `rs_…` item id (falling back to a fixed placeholder
1519
+ * only in the defensive case the id is absent — mirrors the original T5 port,
1520
+ * commit c1f6f71, since deleted unported until this task).
1521
+ *
1522
+ * `reasoningStart`/`reasoningOpaque` carry `itemId`, which the StreamAssembler
1523
+ * sugar methods do not expose a parameter for (only `reasoningDelta`/
1524
+ * `reasoningEnd` are used via sugar) — `a.emit()` is the documented base
1525
+ * primitive for exactly this case (StreamAssembler docstring: "guarantees no
1526
+ * AgClosedEventType is ever unreachable").
1527
+ *
1528
+ * Mirrors `driveMessageOutputCreated`/`tool_output`: assumes the response is
1529
+ * already open (every response always opens via `response.created` before any
1530
+ * run-item can arrive) rather than calling `ensureResponseOpen()` — reopening
1531
+ * here would risk a phantom turn on a late arrival. If `msgId` is undefined
1532
+ * (response already closed) this degrades gracefully — but NOT to a bare no-op
1533
+ * when there is something REPLAY-LOAD-BEARING to lose: a plain summary-text-only
1534
+ * late arrival has nothing irrecoverable to drop (the reasoning block itself
1535
+ * never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
1536
+ * correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
1537
+ * is exactly the kind of payload Tenet 6 exists for — silently dropping it here
1538
+ * was a genuine loss (review finding on M48). Mirrors `ext.openai.late-citations`
1539
+ * (M22) exactly: route it through the lossless vendor channel instead of the bare
1540
+ * return.
1541
+ */
1542
+ function driveReasoningItemCreated(item: OpenAIReasoningItem): void {
1543
+ if (msgId === undefined) {
1544
+ // response already closed — see doc above.
1545
+ const lateEncrypted = item.providerData?.encrypted_content;
1546
+ if (typeof lateEncrypted === "string" && lateEncrypted.length > 0) {
1547
+ a.emitExt("openai", "late-reasoning", {
1548
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
1549
+ encryptedContent: lateEncrypted,
1550
+ });
1551
+ }
1552
+ return;
1553
+ }
1554
+ const id = item.id ?? "reasoning";
1555
+ const itemId = item.id;
1556
+ const text = item.content.map((p) => p.text).join("");
1557
+ a.emit({ type: "reasoning.start", id, messageId: msgId, ...(itemId !== undefined ? { itemId } : {}) });
1558
+ if (text.length > 0) a.reasoningDelta(id, msgId, text);
1559
+ a.reasoningEnd(id, msgId);
1560
+ const encrypted = item.providerData?.encrypted_content;
1561
+ if (typeof encrypted === "string" && encrypted.length > 0) {
1562
+ a.emit({
1563
+ type: "reasoning.opaque",
1564
+ id,
1565
+ messageId: msgId,
1566
+ kind: "ciphertext",
1567
+ value: encrypted,
1568
+ provider: "openai",
1569
+ ...(itemId !== undefined ? { itemId } : {}),
1570
+ });
1571
+ }
1572
+ }
1573
+
1574
+ /** Resolve the turn a pending tool call started under (Task 4b) — a plain
1575
+ * lookup, no side effects; call BEFORE `a.toolDone` so its `turnId` field
1576
+ * can be set explicitly (the result may land after a later round opened). */
1577
+ function resolvePendingTurnId(callId: string): string | undefined {
1578
+ return turnIdByToolCallId.get(callId);
1579
+ }
1580
+
1581
+ /**
1582
+ * After `a.toolDone` has fired for `callId` under `doneTurnId`, clear the
1583
+ * pending bookkeeping and — if the turn's pending set just drained to empty
1584
+ * — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
1585
+ * the `function_call` `tool_output` arm and the built-in Shell/Apply-Patch
1586
+ * `tool_output` arm (playbook 2026-07-03 SDK-bump adaptation, Finding #1).
1587
+ */
1588
+ function drainPendingTool(callId: string, doneTurnId: string | undefined): void {
1589
+ if (doneTurnId === undefined) return;
1590
+ turnIdByToolCallId.delete(callId);
1591
+ const pending = pendingToolsByTurn.get(doneTurnId);
1592
+ if (pending === undefined) return;
1593
+ pending.delete(callId);
1594
+ if (pending.size === 0) {
1595
+ const stashed = stashedCloseByTurn.get(doneTurnId);
1596
+ if (stashed !== undefined) {
1597
+ // The pending set just drained — emit the deferred message.end +
1598
+ // turn.done immediately after this tool.done, same push() batch
1599
+ // (INV-MSG: the message must still be open when tool.done lands, so
1600
+ // message.end waits for this too).
1601
+ stashedCloseByTurn.delete(doneTurnId);
1602
+ emitRoundClose(doneTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
1603
+ }
1604
+ }
1605
+ }
1606
+
1607
+ /** True if any shell command in `entries` timed out or exited non-zero. */
1608
+ function shellOutputHasError(entries: readonly OpenAIShellCallOutputContent[]): boolean {
1609
+ for (const entry of entries) {
1610
+ if (entry.outcome.type === "timeout") return true;
1611
+ if (entry.outcome.type === "exit" && entry.outcome.exitCode !== 0) return true;
1612
+ }
1613
+ return false;
1614
+ }
1615
+
1616
+ /**
1617
+ * Map a `tool_output` run-item whose `rawItem` is a Shell, Apply-Patch, or
1618
+ * Computer-Use result (playbook 2026-07-03 SDK-bump adaptation, Finding #1;
1619
+ * `computer_call_result` added by the fixture-drift ratchet finding, same
1620
+ * date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
1621
+ * (a bare string / content-part union) — `shell_call_output.output` is an
1622
+ * ARRAY of per-command `{stdout,stderr,outcome}` records,
1623
+ * `apply_patch_call_output.output` is an optional bare string,
1624
+ * `computer_call_result.output` is a `{type:"computer_screenshot", data}`
1625
+ * base64-PNG record — so they need their OWN mapping, not
1626
+ * `toolOutputToAgBlocks` (that was the orphan hazard: calling the generic
1627
+ * function_call mapper on these shapes silently produced EMPTY content,
1628
+ * since none of these record types has the `.type === "text"` discriminant
1629
+ * `toolOutputToAgBlocks` checks for).
1630
+ */
1631
+ function driveBuiltinToolOutput(
1632
+ rawItem: OpenAIShellCallResultItem | OpenAIApplyPatchCallResultItem | OpenAIComputerCallResultItem,
1633
+ ): void {
1634
+ const toolCallId = rawItem.callId;
1635
+ let content: AgBlock[];
1636
+ let outcome: ToolOutcome;
1637
+ let structuredContent: JsonValue | undefined;
1638
+ if (rawItem.type === "shell_call_output") {
1639
+ content = [];
1640
+ for (const entry of rawItem.output) {
1641
+ const text = [entry.stdout, entry.stderr].filter((s) => s.length > 0).join("\n");
1642
+ if (text.length > 0) content.push({ type: "text", text });
1643
+ }
1644
+ outcome = shellOutputHasError(rawItem.output) ? "error" : "ok";
1645
+ // The full per-command record (stdout/stderr/exit code) is lossy to
1646
+ // collapse into text-only content — carry it verbatim as structuredContent
1647
+ // too (mirrors the function_call path's ggui-cache-marker precedent).
1648
+ structuredContent = JsonValue.parse(rawItem.output);
1649
+ } else if (rawItem.type === "computer_call_result") {
1650
+ // spec §8 item 20's extended discriminant: the screenshot is base64 image
1651
+ // data, not text — land it as an AgBlock `file` block (AgSource's
1652
+ // `base64` arm) rather than dropping it via the text-only path.
1653
+ content = [
1654
+ {
1655
+ type: "file",
1656
+ source: { type: "base64", mediaType: "image/png", data: rawItem.output.data },
1657
+ filename: "screenshot.png",
1658
+ },
1659
+ ];
1660
+ // No status/error discriminant exists on this wire arm (unlike shell/apply-patch).
1661
+ outcome = "ok";
1662
+ } else {
1663
+ content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
1664
+ outcome = rawItem.status === "failed" ? "error" : "ok";
1665
+ }
1666
+ const doneTurnId = resolvePendingTurnId(toolCallId);
1667
+ a.toolDone({
1668
+ toolCallId,
1669
+ content,
1670
+ outcome,
1671
+ isError: outcome === "error",
1672
+ ...(structuredContent !== undefined ? { structuredContent } : {}),
1673
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
1674
+ });
1675
+ drainPendingTool(toolCallId, doneTurnId);
1676
+ }
1677
+
1678
+ /** Synthesize `name` for the built-in discriminants that carry none on the
1679
+ * wire (§8 quirk) — `shell_call`/`apply_patch_call`/`computer_call` have no
1680
+ * `name` field at all; `hosted_tool_call` already carries a real one. */
1681
+ function builtinToolName(
1682
+ rawItem: OpenAIShellCallItem | OpenAIApplyPatchCallItem | OpenAIComputerCallItem | OpenAIHostedToolCallItem,
1683
+ ): string {
1684
+ if (rawItem.type === "shell_call") return "builtin:shell";
1685
+ if (rawItem.type === "apply_patch_call") return "builtin:apply_patch";
1686
+ if (rawItem.type === "computer_call") return "builtin:computer";
1687
+ return rawItem.name;
1688
+ }
1689
+
1690
+ /** Parse a JSON-string tool argument at the deserialization boundary,
1691
+ * degrading gracefully (Tenet 6) rather than throwing on malformed input —
1692
+ * mirrors `response.function_call_arguments.done`'s established degrade
1693
+ * path (audit M46). */
1694
+ function parseJsonArguments(itemId: string | undefined, raw: string | undefined): JsonValue {
1695
+ if (raw === undefined || raw.length === 0) return {};
1696
+ try {
1697
+ return JsonValue.parse(JSON.parse(raw));
1698
+ } catch {
1699
+ a.emitExt("openai", "unparsed", { itemId: itemId ?? null, arguments: raw });
1700
+ return {};
1701
+ }
1702
+ }
1703
+
1704
+ /**
1705
+ * Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
1706
+ * built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
1707
+ * — playbook 2026-07-03 SDK-bump adaptation, Finding #1; `computer_call`
1708
+ * added by the fixture-drift ratchet finding, same date). Unlike
1709
+ * `function_call` (whose tool-start rides the raw `response.output_item.
1710
+ * added` stream — the authoritative source, canonical model A1), this
1711
+ * run-item wrapper is the SOLE source for these four: `shell_call`/
1712
+ * `apply_patch_call`/`computer_call` carry no per-fragment argument-delta
1713
+ * stream on this seam (no equivalent of
1714
+ * `response.function_call_arguments.delta` exists for them — the whole
1715
+ * action/operation arrives complete on this one wrapper), and
1716
+ * `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
1717
+ * an agents-core-internal umbrella normalized only at this run-item layer).
1718
+ * `ensureResponseOpen()` mirrors the raw function_call path's treatment
1719
+ * (both are tool-START signals expected EARLY in a round, unlike the
1720
+ * LATE-arriving `tool_output`/`message_output_created` run-items this file
1721
+ * already documents) — residual ordering risk if a future capture shows
1722
+ * otherwise is flagged in the adaptation report, not silently assumed away.
1723
+ *
1724
+ * `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
1725
+ * result arrives via a LATER `tool_output` run-item, same Task-4b
1726
+ * deferred-round-close discipline as `function_call`) — registered via
1727
+ * `registerPendingTool`. `hosted_tool_call` is different: OpenAI's hosted
1728
+ * tools execute server-side within the SAME model turn, so the item is
1729
+ * already resolved (`output` present) by the time this wrapper streams —
1730
+ * `tool.start` + `tool.done` fire together from this ONE event (see its own
1731
+ * doc) — no pending registration.
1732
+ */
1733
+ function driveBuiltinToolCalled(
1734
+ rawItem: OpenAIShellCallItem | OpenAIApplyPatchCallItem | OpenAIComputerCallItem | OpenAIHostedToolCallItem,
1735
+ ): void {
1736
+ ensureResponseOpen();
1737
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
1738
+ const toolCallId = rawItem.type === "hosted_tool_call" ? (rawItem.id ?? rawItem.name) : rawItem.callId;
1739
+ const name = builtinToolName(rawItem);
1740
+ a.toolStart({
1741
+ toolCallId,
1742
+ name,
1743
+ ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1744
+ messageId: msgId,
1745
+ });
1746
+ const input: JsonValue =
1747
+ rawItem.type === "shell_call"
1748
+ ? JsonValue.parse(rawItem.action)
1749
+ : rawItem.type === "apply_patch_call"
1750
+ ? JsonValue.parse(rawItem.operation)
1751
+ : rawItem.type === "computer_call"
1752
+ ? JsonValue.parse(rawItem.actions ?? rawItem.action ?? {})
1753
+ : parseJsonArguments(rawItem.id, rawItem.arguments);
1754
+ a.toolArgsDelta(toolCallId, JSON.stringify(input));
1755
+ a.toolArgsAssembled(toolCallId, input);
1756
+ if (rawItem.type === "hosted_tool_call") {
1757
+ const content: AgBlock[] =
1758
+ rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
1759
+ a.toolDone({ toolCallId, content, outcome: "ok" });
1760
+ return;
1761
+ }
1762
+ registerPendingTool(toolCallId);
1763
+ }
1764
+
1765
+ /**
1766
+ * Resolve the correlation id for a `tool_search_call`/`tool_search_output`
1767
+ * pair — matches agents-core 0.12.0's own id-fallback chain exactly
1768
+ * (`dist/tooling.mjs`'s `getToolSearchProviderCallId`/`getToolSearchMatchKey`:
1769
+ * `providerData.call_id ?? providerData.callId ?? call_id ?? callId ?? id`),
1770
+ * with providerData fields checked FIRST. Stops short of the SDK's blind FIFO
1771
+ * positional fallback (used by the real runtime only when NEITHER a field NOR
1772
+ * `id` resolves on EITHER side of a pairing — not something this per-event
1773
+ * facet can safely replicate: blindly popping the oldest pending call would
1774
+ * risk silently correlating two UNRELATED tool_search calls with no supporting
1775
+ * id at all). Returns undefined when genuinely unresolvable — the caller
1776
+ * degrades to `ext.openai.unparsed` rather than fabricating a correlation id
1777
+ * (Tenet 6).
1778
+ */
1779
+ function resolveToolSearchCallId(
1780
+ rawItem: OpenAIToolSearchCallItem | OpenAIToolSearchOutputItem,
1781
+ ): string | undefined {
1782
+ const providerData = rawItem.providerData;
1783
+ if (isJsonObject(providerData)) {
1784
+ if (typeof providerData.call_id === "string" && providerData.call_id.length > 0) return providerData.call_id;
1785
+ if (typeof providerData.callId === "string" && providerData.callId.length > 0) return providerData.callId;
1786
+ }
1787
+ if (typeof rawItem.call_id === "string" && rawItem.call_id.length > 0) return rawItem.call_id;
1788
+ if (typeof rawItem.callId === "string" && rawItem.callId.length > 0) return rawItem.callId;
1789
+ if (typeof rawItem.id === "string" && rawItem.id.length > 0) return rawItem.id;
1790
+ return undefined;
1791
+ }
1792
+
1793
+ /**
1794
+ * Map a `tool_search_called` run-item (fixture-drift ratchet disposition,
1795
+ * 2026-07-03 — the manifest's four `tool_search_*` entries flip from
1796
+ * `carried` to `handled`). A DEDICATED event name, not a `tool_called`
1797
+ * reuse (see `OpenAIToolSearchCalledEvent`'s doc) — this run-item wrapper
1798
+ * is the SOLE tool-start source (no raw-stream literal exists for it, same
1799
+ * rationale as `hosted_tool_call`/shell/apply-patch/computer). `arguments`
1800
+ * (`z.ZodUnknown`) is carried through verbatim like `computer_call`'s
1801
+ * `action`/`actions` (never JSON.parsed — it is not a JSON STRING like
1802
+ * `FunctionCallItem.arguments`). Registers as a PENDING tool (Task 4b
1803
+ * discipline) — the paired `tool_search_output_created` typically lands in
1804
+ * the SAME step (server-hosted execution, or synchronously-resolved client
1805
+ * execution — see the file header's wire-truth citations), but if the
1806
+ * call's execution can't be resolved this turn (no client `toolSearchTool`
1807
+ * configured and no immediate hosted-server output), it may never arrive —
1808
+ * the existing INV-FLUSH stream-truncation handling degrades that exactly
1809
+ * like any other unresolved pending tool call, no special-casing needed.
1810
+ */
1811
+ function driveToolSearchCalled(rawItem: OpenAIToolSearchCallItem): void {
1812
+ ensureResponseOpen();
1813
+ if (msgId === undefined) return; // unreachable post-ensure; satisfies narrowing
1814
+ const toolCallId = resolveToolSearchCallId(rawItem);
1815
+ if (toolCallId === undefined) {
1816
+ // Genuinely unresolvable correlation id — never fabricate one (Tenet 6).
1817
+ a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
1818
+ return;
1819
+ }
1820
+ a.toolStart({
1821
+ toolCallId,
1822
+ name: "builtin:tool_search",
1823
+ ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1824
+ messageId: msgId,
1825
+ });
1826
+ const input: JsonValue = JsonValue.parse(rawItem.arguments ?? {});
1827
+ a.toolArgsDelta(toolCallId, JSON.stringify(input));
1828
+ a.toolArgsAssembled(toolCallId, input);
1829
+ registerPendingTool(toolCallId);
1830
+ }
1831
+
1832
+ /**
1833
+ * Map a `tool_search_output_created` run-item — the paired completion (see
1834
+ * `OpenAIToolSearchOutputItem`'s doc). `tools` is a structured retrieval
1835
+ * listing (tool references/definitions), never natural-language text —
1836
+ * carried verbatim as a single AgBlock `data` block (the spec's escape
1837
+ * hatch for structured non-text tool content) rather than inventing a text
1838
+ * rendering with no wire precedent; this is ALREADY full-fidelity (no lossy
1839
+ * collapse occurs, unlike `shell_call_output`'s stdout/stderr join), so no
1840
+ * separate `structuredContent` duplicate is needed. No error discriminant
1841
+ * exists on this wire's free-form `status` string — mirrors
1842
+ * `computer_call_result`'s identical precedent: every occurrence maps to
1843
+ * `outcome:"ok"`.
1844
+ */
1845
+ function driveToolSearchOutput(rawItem: OpenAIToolSearchOutputItem): void {
1846
+ const toolCallId = resolveToolSearchCallId(rawItem);
1847
+ if (toolCallId === undefined) {
1848
+ a.emitExt("openai", "unparsed", { name: "tool_search_output_created", item: JsonValue.parse(rawItem) });
1849
+ return;
1850
+ }
1851
+ const content: AgBlock[] = [{ type: "data", name: "tool_search_results", data: JsonValue.parse(rawItem.tools) }];
1852
+ const doneTurnId = resolvePendingTurnId(toolCallId);
1853
+ a.toolDone({
1854
+ toolCallId,
1855
+ content,
1856
+ outcome: "ok",
1857
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
1858
+ });
1859
+ drainPendingTool(toolCallId, doneTurnId);
1860
+ }
1861
+
1862
+ /**
1863
+ * Map the synthetic `__host_error__` sentinel (host feeds it on
1864
+ * `MaxTurnsExceededError`) to a terminal `turn.error{code, message, usage}`.
1865
+ * - A response turn is OPEN → close THAT turn (end streams, close message,
1866
+ * closeTurnError) so the error lands on the well-formed open turn.
1867
+ * - NO turn open (max_turns fired after the last response already completed) →
1868
+ * open a FRESH terminal turn via `ensureResponseOpen()` (which emits a
1869
+ * `turn.start` + `message.start` — `closeTurnError` alone does NOT synthesize
1870
+ * `turn.start`, so a bare close would leave a malformed start-less turn),
1871
+ * close its message, then closeTurnError. Either way the error is emitted on
1872
+ * a turn that has a `turn.start`.
1873
+ */
1874
+ function driveHostError(event: OpenAIHostError): void {
1875
+ ensureResponseOpen();
1876
+ if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
1877
+ endOpenStreamsAndCloseMessage();
1878
+ a.closeTurnError(turnId, {
1879
+ message: event.message,
1880
+ code: event.code,
1881
+ ...(event.usage !== undefined ? { usage: event.usage } : {}),
1882
+ });
1883
+ resetResponseState();
1884
+ }
1885
+
1886
+ /** Drive the engine from one (already-narrowed) OpenAIStreamEvent. */
1887
+ function drive(event: OpenAIStreamEvent): void {
1888
+ if (event.type === "__host_error__") {
1889
+ driveHostError(event);
1890
+ return;
1891
+ }
1892
+ if (event.type === "run_item_stream_event") {
1893
+ // Widened reference for the switch's `default` arm — see OpenAIRunItemEvent's
1894
+ // docstring (Task 3, audit M48).
1895
+ const runItemEvent: OpenAIRunItemEvent = event;
1896
+ switch (event.name) {
1897
+ case "tool_output": {
1898
+ const rawItem = event.item.rawItem;
1899
+ // Finding #1 (critical) + the fixture-drift ratchet's
1900
+ // computer_call_result finding: Shell/Apply-Patch/Computer-Use
1901
+ // results do NOT share `OpenAIFunctionCallResultItem.output`'s shape
1902
+ // — see `driveBuiltinToolOutput`'s doc for why the generic path
1903
+ // below is wrong for them (the orphan-hazard this adaptation fixes).
1904
+ if (
1905
+ rawItem.type === "shell_call_output" ||
1906
+ rawItem.type === "apply_patch_call_output" ||
1907
+ rawItem.type === "computer_call_result"
1908
+ ) {
1909
+ driveBuiltinToolOutput(rawItem);
1910
+ return;
1911
+ }
1912
+ // Authoritative tool-result source (canonical model, A1). Drives toolDone
1913
+ // with content + structuredContent (the ggui cache marker — see
1914
+ // `extractStructuredContent`'s doc for the two peer-supported homes and
1915
+ // the playbook 2026-07-03 wire-truth findings behind them).
1916
+ const outcome: ToolOutcome = rawItem.status === "incomplete" ? "error" : "ok";
1917
+ const content = toolOutputToAgBlocks(rawItem.output);
1918
+ const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
1919
+ // Task 4b: resolve the OWNING turn explicitly (this result may land
1920
+ // after a later round has opened, so the engine's #lastTurn backfill
1921
+ // could misattribute it) and pass it through so toolDone binds to the
1922
+ // correct — possibly already-closed-pending-this-result — turn.
1923
+ const doneTurnId = resolvePendingTurnId(rawItem.callId);
1924
+ a.toolDone({
1925
+ toolCallId: rawItem.callId,
1926
+ content,
1927
+ outcome,
1928
+ isError: rawItem.status === "incomplete",
1929
+ ...(structuredContent !== undefined ? { structuredContent } : {}),
1930
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
1931
+ });
1932
+ drainPendingTool(rawItem.callId, doneTurnId);
1933
+ return;
1934
+ }
1935
+ case "message_output_created":
1936
+ // CITATIONS SUPPLEMENT only — the text already streamed from the raw delta
1937
+ // (canonical model, A1). Records refusal + emits citation blocks; no text.
1938
+ driveMessageOutputCreated(event.item.rawItem);
1939
+ return;
1940
+ case "tool_called": {
1941
+ const rawItem = event.item.rawItem;
1942
+ if (rawItem.type === "function_call") {
1943
+ // IGNORED — superseded by model:response.output_item.added, which is
1944
+ // the authoritative tool-start source (canonical model, A1
1945
+ // §"Spike Findings").
1946
+ return;
1947
+ }
1948
+ // Finding #1 (critical): Shell / Apply-Patch / Hosted-tool built-ins
1949
+ // — this run-item wrapper (not the raw stream) is the SOLE tool-start
1950
+ // source for these three (see `driveBuiltinToolCalled`'s doc).
1951
+ driveBuiltinToolCalled(rawItem);
1952
+ return;
1953
+ }
1954
+ case "tool_search_called":
1955
+ // Fixture-drift ratchet disposition (2026-07-03) — a DEDICATED
1956
+ // event name (not a `tool_called` reuse). See
1957
+ // `driveToolSearchCalled`'s doc for the full lifecycle rationale.
1958
+ driveToolSearchCalled(event.item.rawItem);
1959
+ return;
1960
+ case "tool_search_output_created":
1961
+ driveToolSearchOutput(event.item.rawItem);
1962
+ return;
1963
+ case "reasoning_item_created":
1964
+ // SOLE source for reasoning content — see driveReasoningItemCreated's
1965
+ // docstring for the single-sourcing rationale (Task 3, audit M48).
1966
+ driveReasoningItemCreated(event.item.rawItem);
1967
+ return;
1968
+ case "handoff_requested": {
1969
+ // Task 3 (audit M48 review, Finding 1) handoff mapping — FALSE-PREMISE
1970
+ // FIX. The original mapping (a standalone `handoff` event) assumed the
1971
+ // wire carried no completion signal for a handoff, so a `subagentStart`
1972
+ // that MUST be matched by `subagentDone` couldn't be used safely (an
1973
+ // unmatched one gets INV-FLUSH-aborted as `turn.abort{reason:"stream-
1974
+ // truncated"}`, audit M21 — misrepresenting a genuinely-completed
1975
+ // handoff). That premise was FALSE: `handoff_occurred` IS the
1976
+ // completion signal (verified against the installed `@openai/agents`
1977
+ // 0.2.1 peer dep's `events.d.ts` — `RunItemStreamEventName` includes
1978
+ // `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
1979
+ // bracket the transfer with `subagentStart` now / `subagentDone` at the
1980
+ // matching `handoff_occurred` below (FIFO via `openHandoffs`).
1981
+ //
1982
+ // `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
1983
+ // LLM call produced this handoff call — NOT the transfer target (see
1984
+ // `OpenAIHandoffRequestedEvent`'s doc: the target isn't resolved until
1985
+ // the handoff actually executes). There is therefore no target identity
1986
+ // to carry at this point — an earlier draft of this fix assumed there
1987
+ // was; corrected. `StreamAssembler.subagentStart`'s SUGAR signature also
1988
+ // carries neither `agentId` nor `agentName` params (only the
1989
+ // `subagent.start` AgEvent SCHEMA arm does, agjson.ts — a live-only
1990
+ // field the fold doesn't land on `AgTurnRecord` either, reduce.ts) and
1991
+ // this fix's commit scope excludes core/stream-assembler.ts, so identity
1992
+ // rides the follow-up bare `handoff` event instead (spec §4 bare-noun
1993
+ // EVENT carve-out), emitted once it's actually known — paired with
1994
+ // `subagentDone` in the `handoff_occurred` case below.
1995
+ const ordinal = ++handoffOrdinal;
1996
+ const handoffTurnId = `turn_handoff_${ordinal}`;
1997
+ const parentTurnId = lastTopLevelTurnId ?? threadId;
1998
+ openHandoffs.push({ turnId: handoffTurnId, parentTurnId });
1999
+ a.subagentStart(handoffTurnId, parentTurnId);
2000
+ return;
2001
+ }
2002
+ case "handoff_occurred": {
2003
+ // Task 3 (audit M48 review, Finding 1) — the REAL completion signal.
2004
+ // Both agent identities are finally known here (`RunHandoffOutputItem.
2005
+ // sourceAgent`/`targetAgent`), so this is where the identity-carrying
2006
+ // `handoff` event fires (mirrors the ORIGINAL mapping's shape —
2007
+ // `kind:"transfer"` + `toAgentName` — just correctly timed to when the
2008
+ // data actually exists on the wire). `fromAgentId`/`toAgentId` are still
2009
+ // never fabricated from a name (no agent-id concept exists anywhere on
2010
+ // this seam, unlike google-adk's per-message agentId/agentName).
2011
+ const item = event.item;
2012
+ const open = openHandoffs.shift(); // FIFO — see openHandoffs' doc.
2013
+ if (open !== undefined) a.subagentDone(open.turnId, open.parentTurnId);
2014
+ // Defensive orphan (no open bracket — e.g. a resumed/truncated stream):
2015
+ // still emit the `handoff` event losslessly rather than dropping the
2016
+ // now-known identity (Tenet 6) — it just doesn't close anything.
2017
+ a.emit({
2018
+ type: "handoff",
2019
+ kind: "transfer",
2020
+ toAgentName: item.targetAgent.name,
2021
+ });
2022
+ return;
2023
+ }
2024
+ case "tool_approval_requested": {
2025
+ // Task 3 (audit M48): a human-in-the-loop approval gate on a pending
2026
+ // tool call. `askId` mirrors the `approval_${callId}` convention already
2027
+ // established by the google-adk facet's `requestedToolConfirmations` arm
2028
+ // (index.ts:653) for the same `kind:"approval"` semantics. The M26
2029
+ // paused-fold discipline (surfacing this on the turn's `outcome.paused`)
2030
+ // is ADK-scoped for this batch — `hitl.ask` is LIVE-ONLY on the fold
2031
+ // (reduce.ts R9: no accumulator mutation), so emitting the ask alone is
2032
+ // complete; the host/turn-close owns any pause semantics.
2033
+ const item = event.item.rawItem;
2034
+ a.emit({
2035
+ type: "hitl.ask",
2036
+ askId: `approval_${item.callId}`,
2037
+ kind: "approval",
2038
+ toolCallId: item.callId,
2039
+ });
2040
+ return;
2041
+ }
2042
+ default:
2043
+ // A genuinely-unknown run-item name (a real-wire RunItemStreamEventName
2044
+ // this fixture-contract union does not declare — e.g.
2045
+ // `mcp_approval_requested`, `mcp_list_tools`). The OUTER guard
2046
+ // (`isOpenAIStreamEvent`) validates only `typeof name === "string"` (file
2047
+ // header), so an unrecognised name reaches here at runtime despite
2048
+ // `event`'s TS-narrowed `never` type (every literal this union declares
2049
+ // is handled by a case above). Route losslessly per Tenet 6 — this is the
2050
+ // file's stated ext.openai.unparsed convention for genuinely-unknown
2051
+ // run-items (audit M48; previously a silent no-op here).
2052
+ a.emitExt("openai", "unparsed", {
2053
+ name: runItemEvent.name,
2054
+ item: JsonValue.parse(runItemEvent.item),
2055
+ });
2056
+ return;
2057
+ }
2058
+ }
2059
+
2060
+ // raw_model_stream_event — `data` is the Agents SDK ResponseStreamEvent union.
2061
+ const data = event.data;
2062
+ switch (data.type) {
2063
+ case "model": {
2064
+ // The verbatim openai-node Responses event rides in `event` (snake_case).
2065
+ driveRawResponsesEvent(data.event);
2066
+ return;
2067
+ }
2068
+ // IGNORE the SDK-flattened duplicates (canonical model):
2069
+ // response_started — duplicate of model:response.created
2070
+ // output_text_delta — flattened duplicate of model:response.output_text.delta
2071
+ // response_done — duplicate of model:response.completed
2072
+ case "response_started":
2073
+ case "output_text_delta":
2074
+ case "response_done":
2075
+ default:
2076
+ return;
2077
+ }
2078
+ }
2079
+
2080
+ return {
2081
+ push(native: JsonValue): AgEvent[] {
2082
+ if (!isOpenAIStreamEvent(native)) {
2083
+ // Graceful guard (Tenet 6): route a genuinely unrecognisable payload through
2084
+ // the lossless vendor channel rather than throwing. Nest under `native` so a
2085
+ // payload carrying its own `type` key does NOT clobber the event type.
2086
+ a.emitExt("openai", "unparsed", { native });
2087
+ return a.drain();
2088
+ }
2089
+ drive(native);
2090
+ return a.drain();
2091
+ },
2092
+ flush(): AgEvent[] {
2093
+ // Close any dangling open response (e.g. a stream that ended before
2094
+ // response.completed) — unrelated to Task 4b: that round never reached a
2095
+ // native close signal at all, so it has no stashed closeTurnDone.
2096
+ if (turnId !== undefined) closeResponse();
2097
+ // Task 4b: emit any still-stashed closes BEFORE delegating to the engine's
2098
+ // flush. Each stashed round genuinely completed on the wire — a tool
2099
+ // result that never arrives must not swallow that close (message.end +
2100
+ // turn.done both replay here, verbatim, in the order INV-MSG requires).
2101
+ for (const [tid, stashed] of stashedCloseByTurn) {
2102
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
2103
+ }
2104
+ stashedCloseByTurn.clear();
2105
+ // Flush the engine's dangling open messages (I7).
2106
+ return a.flush();
2107
+ },
2108
+ };
2109
+ }