@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.
@@ -0,0 +1,728 @@
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 { type AgFinishReason, type AgUsage, JsonValue, type Normalizer } from "@silverprotocol/core";
65
+ /** Assistant message content part (protocol `OutputText`). */
66
+ export interface OpenAIOutputText {
67
+ type: "output_text";
68
+ text: string;
69
+ /** url_citation and file_citation annotations on the text part. */
70
+ annotations?: OpenAIAnnotation[];
71
+ }
72
+ /** url_citation annotation on an output_text part (openai-node `ResponseCitationAnnotation`). */
73
+ export interface OpenAIUrlCitationAnnotation {
74
+ type: "url_citation";
75
+ url: string;
76
+ title?: string;
77
+ start_index?: number;
78
+ end_index?: number;
79
+ }
80
+ /** file_citation annotation on an output_text part. */
81
+ export interface OpenAIFileCitationAnnotation {
82
+ type: "file_citation";
83
+ file_id?: string;
84
+ filename?: string;
85
+ index?: number;
86
+ }
87
+ /** The subset of annotations that the normalizer handles. */
88
+ export type OpenAIAnnotation = OpenAIUrlCitationAnnotation | OpenAIFileCitationAnnotation;
89
+ /** `Refusal` content part — the model refused to answer (openai-node `ResponseOutputRefusal`). */
90
+ export interface OpenAIRefusal {
91
+ type: "refusal";
92
+ refusal: string;
93
+ }
94
+ /** Union of assistant message content parts the normalizer handles. */
95
+ export type OpenAIContentPart = OpenAIOutputText | OpenAIRefusal;
96
+ /** protocol `AssistantMessageItem` (the `rawItem` of a message_output_item). */
97
+ export interface OpenAIAssistantMessageItem {
98
+ type?: "message";
99
+ role: "assistant";
100
+ status: "in_progress" | "completed" | "incomplete";
101
+ content: OpenAIContentPart[];
102
+ id?: string;
103
+ providerData?: {
104
+ [k: string]: JsonValue;
105
+ };
106
+ }
107
+ /** protocol `FunctionCallItem` (the `rawItem` of a tool_call_item). `callId` is
108
+ * the model's call_id; `id` is the Responses `fc_…` item id (DISTINCT). */
109
+ export interface OpenAIFunctionCallItem {
110
+ type: "function_call";
111
+ callId: string;
112
+ name: string;
113
+ arguments: string;
114
+ status?: "in_progress" | "completed" | "incomplete";
115
+ id?: string;
116
+ providerData?: {
117
+ [k: string]: JsonValue;
118
+ };
119
+ }
120
+ /** protocol `ToolOutputText` — the BARE-OBJECT arm of `FunctionCallResultItem.
121
+ * output` (`output: {type:"text", text}`, not wrapped in an array). */
122
+ export interface OpenAIToolOutputText {
123
+ type: "text";
124
+ text: string;
125
+ }
126
+ /**
127
+ * protocol array-form element of `FunctionCallResultItem.output`
128
+ * (`output: [...]`) — playbook 2026-07-03 SDK-bump adaptation, Finding #2
129
+ * (critical). `@openai/agents-core` 0.12.0's real zod schema
130
+ * (`protocol.d.ts`'s `FunctionCallResultItem`) discriminates the ARRAY arm's
131
+ * elements with `input_text`/`input_image`/`input_file` literals — DIFFERENT
132
+ * from the bare-object arm's `text`/`image`/`file` literals ({@link
133
+ * OpenAIToolOutputText}). The prior 0.12.0 adaptation missed this: it typed
134
+ * the array arm as `OpenAIToolOutputText[]` (i.e. assumed array elements ALSO
135
+ * use `type:"text"`), so `toolOutputToAgBlocks`'s `part.type === "text"`
136
+ * check never matched a real array-shaped tool result — VERIFIED LIVE
137
+ * (playbook 2026-07-03, echo-gpt55 capture): every MCP tool call's result
138
+ * silently produced `tool.done.content: []`, discarding the tool's entire
139
+ * output text. `@openai/agents-core` 0.12.0 uses this array+`input_text`
140
+ * shape for MCP-routed tool-call results (the common case for this SDK's own
141
+ * MCP client) — this was never exercised by a live capture before now (the
142
+ * committed openai seed cassettes predate 0.12.0). Only the text arm is
143
+ * modeled/handled here, matching the PRE-EXISTING scope of the bare-object
144
+ * arm (which also only maps `type:"text"`, never `type:"image"`/`"file"`) —
145
+ * `input_image`/`input_file` array elements remain intentionally unhandled.
146
+ */
147
+ export interface OpenAIToolOutputInputText {
148
+ type: "input_text";
149
+ text: string;
150
+ }
151
+ /** protocol `FunctionCallResultItem` (the `rawItem` of a tool_call_output_item).
152
+ * `output` is a string, a bare content object ({@link OpenAIToolOutputText}),
153
+ * or a content-part ARRAY ({@link OpenAIToolOutputInputText}[]) — the wrapper's
154
+ * own `output` field carries the stringified primary output. */
155
+ export interface OpenAIFunctionCallResultItem {
156
+ type: "function_call_result";
157
+ name: string;
158
+ callId: string;
159
+ status: "in_progress" | "completed" | "incomplete";
160
+ output: string | OpenAIToolOutputText | OpenAIToolOutputInputText[];
161
+ providerData?: {
162
+ [k: string]: JsonValue;
163
+ };
164
+ }
165
+ /** protocol `ShellAction` — the shell tool's per-call command spec. */
166
+ export interface OpenAIShellAction {
167
+ commands: string[];
168
+ timeoutMs?: number;
169
+ maxOutputLength?: number;
170
+ }
171
+ /** protocol `ShellCallItem` (a `tool_called` rawItem for OpenAI's native shell
172
+ * built-in tool). Carries NO `name` field — the wire identifies the tool
173
+ * purely by `type`; the facet synthesizes `name:"builtin:shell"` (§8 quirk).
174
+ * Unlike `function_call`, there is no per-fragment argument-delta stream for
175
+ * this shape on this seam — the whole `action` arrives complete on this ONE
176
+ * wrapper, so this run-item (not the raw stream) is the sole tool-start
177
+ * source for it. */
178
+ export interface OpenAIShellCallItem {
179
+ type: "shell_call";
180
+ callId: string;
181
+ status?: "in_progress" | "completed" | "incomplete";
182
+ action: OpenAIShellAction;
183
+ id?: string;
184
+ providerData?: {
185
+ [k: string]: JsonValue;
186
+ };
187
+ }
188
+ /** protocol `ShellCallOutcome` (per-command exit signal). */
189
+ export interface OpenAIShellCallOutcome {
190
+ type: "timeout" | "exit";
191
+ exitCode?: number | null;
192
+ }
193
+ /** protocol `ShellCallOutputContent` (one command's stdout/stderr/outcome). */
194
+ export interface OpenAIShellCallOutputContent {
195
+ stdout: string;
196
+ stderr: string;
197
+ outcome: OpenAIShellCallOutcome;
198
+ }
199
+ /** protocol `ShellCallResultItem` (the `rawItem` of a `tool_output` run-item for
200
+ * a completed shell call). `output` is an ARRAY of per-command results — a
201
+ * DIFFERENT shape from `OpenAIFunctionCallResultItem.output` (a bare string /
202
+ * content-part union); the two must NOT be handled by the same generic path
203
+ * (that was the orphan-hazard: shape-compatible-enough field NAMES let a
204
+ * `tool.done` fire with silently-empty content). */
205
+ export interface OpenAIShellCallResultItem {
206
+ type: "shell_call_output";
207
+ callId: string;
208
+ maxOutputLength?: number;
209
+ output: OpenAIShellCallOutputContent[];
210
+ id?: string;
211
+ providerData?: {
212
+ [k: string]: JsonValue;
213
+ };
214
+ }
215
+ /** protocol `ApplyPatchOperation` (one file edit — create/update/delete). */
216
+ export interface OpenAIApplyPatchOperation {
217
+ type: "create_file" | "update_file" | "delete_file";
218
+ path: string;
219
+ diff?: string;
220
+ moveTo?: string;
221
+ }
222
+ /** protocol `ApplyPatchCallItem` (a `tool_called` rawItem for OpenAI's native
223
+ * apply-patch built-in tool). Carries NO `name` field; the facet synthesizes
224
+ * `name:"builtin:apply_patch"` (§8 quirk). Same single-wrapper-is-authoritative
225
+ * rationale as {@link OpenAIShellCallItem}. */
226
+ export interface OpenAIApplyPatchCallItem {
227
+ type: "apply_patch_call";
228
+ callId: string;
229
+ status: "in_progress" | "completed";
230
+ operation: OpenAIApplyPatchOperation;
231
+ id?: string;
232
+ providerData?: {
233
+ [k: string]: JsonValue;
234
+ };
235
+ }
236
+ /** protocol `ApplyPatchCallResultItem` (the `rawItem` of a `tool_output`
237
+ * run-item for a completed apply-patch call). */
238
+ export interface OpenAIApplyPatchCallResultItem {
239
+ type: "apply_patch_call_output";
240
+ callId: string;
241
+ status: "completed" | "failed";
242
+ output?: string;
243
+ id?: string;
244
+ providerData?: {
245
+ [k: string]: JsonValue;
246
+ };
247
+ }
248
+ /** protocol `HostedToolCallItem` (a `tool_called` rawItem for a
249
+ * provider-HOSTED built-in tool — web_search / code_interpreter /
250
+ * file_search / image_generation / mcp / … — normalized into this ONE
251
+ * umbrella shape only at the run-item layer: the raw `response.output_item.
252
+ * added` event NEVER carries `item.type === "hosted_tool_call"` literally —
253
+ * each underlying OpenAI hosted tool has its OWN distinct raw wire type, so
254
+ * this discriminant only exists here). UNLIKE `function_call`/`shell_call`/
255
+ * `apply_patch_call`, this item carries its OWN `output` when it streams:
256
+ * OpenAI's hosted tools execute server-side within the same model turn, so
257
+ * by the time this wrapper delivers it, the call is already resolved —
258
+ * there is no separate `tool_output` run-item for this shape (verified
259
+ * against @openai/agents-core 0.12.0's `runner/modelOutputs.mjs`: a
260
+ * `hosted_tool_call` output item is pushed as a single `RunToolCallItem`,
261
+ * never paired with a `RunToolCallOutputItem`). The facet emits
262
+ * `tool.start` + `tool.done` TOGETHER from this one event. */
263
+ export interface OpenAIHostedToolCallItem {
264
+ type: "hosted_tool_call";
265
+ id?: string;
266
+ name: string;
267
+ arguments?: string;
268
+ status?: string;
269
+ output?: string;
270
+ providerData?: {
271
+ [k: string]: JsonValue;
272
+ };
273
+ }
274
+ /** protocol `ComputerUseCallItem` (a `tool_called` rawItem for OpenAI's native
275
+ * Computer-Use built-in tool). Carries NO `name` field — the facet synthesizes
276
+ * `name:"builtin:computer"` (§8 quirk, mirrors shell_call/apply_patch_call).
277
+ * The wire carries BOTH `action` (a single computer action — click/scroll/type/screenshot/…)
278
+ * and `actions` (a batch array of actions); the SDK's own runtime reads `actions` FIRST
279
+ * (if populated), falling back to `action`. Both are OPTIONAL on the wire and carried
280
+ * through verbatim as the tool's args payload; nested fields are not interpreted here
281
+ * (fixture discipline: type only what is consumed — the facet never branches on a
282
+ * specific action kind). Same single-wrapper-is-authoritative rationale as
283
+ * {@link OpenAIShellCallItem}: no per-fragment argument-delta stream exists for this
284
+ * shape on this seam. The normalizer MUST mirror the SDK's precedence: `actions ?? action ?? {}`. */
285
+ export interface OpenAIComputerCallItem {
286
+ type: "computer_call";
287
+ callId: string;
288
+ status: "in_progress" | "completed" | "incomplete";
289
+ action?: JsonValue;
290
+ actions?: JsonValue;
291
+ id?: string;
292
+ providerData?: {
293
+ [k: string]: JsonValue;
294
+ };
295
+ }
296
+ /** protocol `ComputerCallResultItem` (the `rawItem` of a `tool_output` run-item
297
+ * for a completed Computer-Use call). `output` is ALWAYS the
298
+ * `computer_screenshot` shape (a base64-encoded PNG screenshot) — NO
299
+ * `status`/error discriminant exists on this wire arm (unlike shell/apply-
300
+ * patch results), so the facet maps every occurrence to `outcome:"ok"`. */
301
+ export interface OpenAIComputerCallResultItem {
302
+ type: "computer_call_result";
303
+ callId: string;
304
+ output: {
305
+ type: "computer_screenshot";
306
+ data: string;
307
+ };
308
+ id?: string;
309
+ providerData?: {
310
+ [k: string]: JsonValue;
311
+ };
312
+ }
313
+ /** protocol `ToolSearchCallItem` (a `tool_search_called` rawItem — the model
314
+ * searching a large tool catalog before invoking a specific tool; hosted
315
+ * server-side (`execution:"server"`) or client-executed (`execution:
316
+ * "client"`, either `Runner`'s built-in `{paths:string[]}` loader or a
317
+ * custom `toolSearchTool({execution:"client", execute})`)). Carries NO
318
+ * `name` field — the facet synthesizes `name:"builtin:tool_search"` (§8
319
+ * quirk, mirrors shell_call/apply_patch_call/computer_call). UNLIKE those
320
+ * three (and unlike every other builtin's REQUIRED `callId: z.ZodString`),
321
+ * `call_id`/`callId` are BOTH optional AND nullable on this wire — the
322
+ * SDK's own runtime (`dist/tooling.mjs`'s `getToolSearchProviderCallId`/
323
+ * `getToolSearchMatchKey`) falls back through `providerData.call_id` →
324
+ * `providerData.callId` → the item's own `id` → (only when NEITHER side of
325
+ * a pairing has ANY identifiable id) blind FIFO positional matching against
326
+ * pending calls. `resolveToolSearchCallId` (below, near `driveToolSearchCalled`)
327
+ * mirrors the id-fallback chain — NOT the FIFO fallback: fabricating a
328
+ * positional-match correlation with no supporting id would risk silently
329
+ * pairing two UNRELATED calls, so that case instead degrades to
330
+ * `ext.openai.unparsed` (Tenet 6 — never fabricate a correlation id).
331
+ * `arguments` is `z.ZodUnknown` (NOT a JSON STRING like `FunctionCallItem.
332
+ * arguments`) — provider-defined (`{paths, query}` for the built-in hosted
333
+ * loader; a custom shape for a registered `toolSearchTool`) — carried
334
+ * through verbatim like `computer_call`'s `action`/`actions`, never
335
+ * JSON.parsed. */
336
+ export interface OpenAIToolSearchCallItem {
337
+ type: "tool_search_call";
338
+ id?: string;
339
+ call_id?: string | null;
340
+ callId?: string | null;
341
+ execution?: "client" | "server";
342
+ arguments?: JsonValue;
343
+ status?: string;
344
+ providerData?: {
345
+ [k: string]: JsonValue;
346
+ };
347
+ }
348
+ /** protocol `ToolSearchOutputItem` (the `tool_search_output_created` rawItem
349
+ * for a resolved tool-search call). `tools` is, per the SDK's own zod-schema
350
+ * doc comment, "tool references or concrete tool definitions" — an array of
351
+ * provider-defined records (`{type:"tool_reference", functionName,
352
+ * namespace}` / a serialized function-tool definition / `{type:"namespace",
353
+ * name, description, tools:[...]}` / hosted-MCP provider data) — a
354
+ * structured retrieval LISTING, never natural-language text. Carried
355
+ * verbatim as a single AgBlock `data` block (the spec's escape hatch for
356
+ * structured non-text tool content — mirrors `computer_call_result`'s
357
+ * `file`-block treatment of its OWN non-text payload) rather than inventing
358
+ * a text rendering with no wire precedent; this is ALREADY full-fidelity
359
+ * (unlike `shell_call_output`'s lossy stdout/stderr join), so no separate
360
+ * `structuredContent` duplicate is warranted. `status` is an UNCONSTRAINED
361
+ * string (unlike shell/apply-patch's closed `'in_progress'|'completed'|
362
+ * 'incomplete'` enum) — no documented error discriminant exists on this
363
+ * wire arm, so — mirroring `computer_call_result`'s identical precedent —
364
+ * every occurrence maps to `outcome:"ok"`. */
365
+ export interface OpenAIToolSearchOutputItem {
366
+ type: "tool_search_output";
367
+ id?: string;
368
+ call_id?: string | null;
369
+ callId?: string | null;
370
+ execution?: "client" | "server";
371
+ status?: string;
372
+ tools: {
373
+ [k: string]: JsonValue;
374
+ }[];
375
+ providerData?: {
376
+ [k: string]: JsonValue;
377
+ };
378
+ }
379
+ /** protocol `InputText` (the visible reasoning content part). */
380
+ export interface OpenAIReasoningTextPart {
381
+ type: "input_text";
382
+ text: string;
383
+ }
384
+ /** protocol `ReasoningItem` (the `rawItem` of a reasoning_item). The `rs_…` id +
385
+ * the `encrypted_content` (under `providerData`, the Responses stateless-replay
386
+ * payload) are replay-load-bearing (spec §8.2/§10.4). */
387
+ export interface OpenAIReasoningItem {
388
+ type: "reasoning";
389
+ id?: string;
390
+ content: OpenAIReasoningTextPart[];
391
+ providerData?: {
392
+ encrypted_content?: string;
393
+ [k: string]: JsonValue | undefined;
394
+ };
395
+ }
396
+ interface OpenAIMessageOutputEvent {
397
+ type: "run_item_stream_event";
398
+ name: "message_output_created";
399
+ item: {
400
+ type: "message_output_item";
401
+ rawItem: OpenAIAssistantMessageItem;
402
+ };
403
+ }
404
+ interface OpenAIToolCalledEvent {
405
+ type: "run_item_stream_event";
406
+ name: "tool_called";
407
+ item: {
408
+ type: "tool_call_item";
409
+ rawItem: OpenAIFunctionCallItem | OpenAIShellCallItem | OpenAIApplyPatchCallItem | OpenAIComputerCallItem | OpenAIHostedToolCallItem;
410
+ };
411
+ }
412
+ interface OpenAIToolOutputEvent {
413
+ type: "run_item_stream_event";
414
+ name: "tool_output";
415
+ item: {
416
+ type: "tool_call_output_item";
417
+ rawItem: OpenAIFunctionCallResultItem | OpenAIShellCallResultItem | OpenAIApplyPatchCallResultItem | OpenAIComputerCallResultItem;
418
+ output?: JsonValue;
419
+ customData?: JsonValue;
420
+ };
421
+ }
422
+ /** `tool_search_called` — a DEDICATED run-item event name (verified against
423
+ * @openai/agents-core 0.12.0's `dist/events.d.ts`: `RunItemStreamEventName`
424
+ * gained `'tool_search_called'`/`'tool_search_output_created'` as their OWN
425
+ * literals — UNLIKE shell/apply-patch/computer/hosted-tool, which all reuse
426
+ * the pre-existing `tool_called`/`tool_output` names (§8 item 20). The
427
+ * run-item's own `.type` discriminant is `"tool_search_call_item"` (verified
428
+ * against `dist/items.d.ts`'s `RunToolSearchCallItem`). See
429
+ * `OpenAIToolSearchCallItem`'s doc for the full wire-truth citations. */
430
+ interface OpenAIToolSearchCalledEvent {
431
+ type: "run_item_stream_event";
432
+ name: "tool_search_called";
433
+ item: {
434
+ type: "tool_search_call_item";
435
+ rawItem: OpenAIToolSearchCallItem;
436
+ };
437
+ }
438
+ /** `tool_search_output_created` — the paired completion event (see
439
+ * `OpenAIToolSearchOutputItem`'s doc for the wire-truth citations on why
440
+ * this is PAIRED, not collapsed like `hosted_tool_call`). The run-item's own
441
+ * `.type` discriminant is `"tool_search_output_item"` (`dist/items.d.ts`'s
442
+ * `RunToolSearchOutputItem`). */
443
+ interface OpenAIToolSearchOutputCreatedEvent {
444
+ type: "run_item_stream_event";
445
+ name: "tool_search_output_created";
446
+ item: {
447
+ type: "tool_search_output_item";
448
+ rawItem: OpenAIToolSearchOutputItem;
449
+ };
450
+ }
451
+ interface OpenAIReasoningEvent {
452
+ type: "run_item_stream_event";
453
+ name: "reasoning_item_created";
454
+ item: {
455
+ type: "reasoning_item";
456
+ rawItem: OpenAIReasoningItem;
457
+ };
458
+ }
459
+ /** Minimal projection of `@openai/agents`' `Agent` class — only `.name` is
460
+ * consumed anywhere on this seam (fixture discipline: type ONLY what you
461
+ * consume). Rides on `handoff_requested`'s wrapper (`agent`, the SOURCE
462
+ * agent) and `handoff_occurred`'s wrapper (`sourceAgent`/`targetAgent`) —
463
+ * audit M48 review, Finding 1. */
464
+ export interface OpenAIAgentRef {
465
+ name: string;
466
+ }
467
+ /** A handoff call item (`RunHandoffCallItem.rawItem`) — verified against
468
+ * @openai/agents-core 0.2.1's `protocol.FunctionCallItem`: `name`,
469
+ * `arguments`, `callId`, `status?`, `id?`, `providerData?`. It carries NO
470
+ * `targetAgent` field — that was an invented field on a false premise
471
+ * (audit M48 review, Finding 1): the transfer target is not resolvable at
472
+ * this point on the real wire (see {@link OpenAIHandoffRequestedEvent}). */
473
+ interface OpenAIHandoffCallItem {
474
+ type: "function_call";
475
+ name: string;
476
+ callId: string;
477
+ arguments: string;
478
+ id?: string;
479
+ providerData?: {
480
+ [k: string]: JsonValue;
481
+ };
482
+ }
483
+ /** `handoff_requested` — the run-item wrapper (`RunHandoffCallItem`) carries
484
+ * `agent` (real d.ts naming): the SOURCE agent whose LLM call produced this
485
+ * handoff call — NOT the transfer target. The target agent is resolved only
486
+ * once the handoff actually executes (verified against
487
+ * @openai/agents-core 0.2.1's `runImplementation.mjs`: `executeHandoffCalls`
488
+ * calls `handoff.onInvokeHandoff` — which resolves the new agent — AFTER
489
+ * the `RunHandoffCallItem` carrying this event is already constructed), and
490
+ * only appears on {@link OpenAIHandoffOccurredEvent}'s `targetAgent` below
491
+ * (audit M48 review, Finding 1). */
492
+ interface OpenAIHandoffRequestedEvent {
493
+ type: "run_item_stream_event";
494
+ name: "handoff_requested";
495
+ item: {
496
+ type: "handoff_call_item";
497
+ rawItem: OpenAIHandoffCallItem;
498
+ agent: OpenAIAgentRef;
499
+ };
500
+ }
501
+ /** `handoff_occurred` — the REAL completion signal the original
502
+ * `handoff_requested` mapping assumed did not exist (audit M48 review,
503
+ * Finding 1; verified against @openai/agents-core 0.2.1's `events.d.ts`:
504
+ * `RunItemStreamEventName` includes `'handoff_occurred'`). The wrapper is a
505
+ * `RunHandoffOutputItem`: `rawItem` (the transfer's tool-output message,
506
+ * protocol `FunctionCallResultItem`-shaped — reuses
507
+ * {@link OpenAIFunctionCallResultItem}), `sourceAgent`, `targetAgent` (both
508
+ * {@link OpenAIAgentRef}) — this is where BOTH agent identities are finally
509
+ * known. */
510
+ interface OpenAIHandoffOccurredItem {
511
+ type: "handoff_output_item";
512
+ rawItem: OpenAIFunctionCallResultItem;
513
+ sourceAgent: OpenAIAgentRef;
514
+ targetAgent: OpenAIAgentRef;
515
+ }
516
+ interface OpenAIHandoffOccurredEvent {
517
+ type: "run_item_stream_event";
518
+ name: "handoff_occurred";
519
+ item: OpenAIHandoffOccurredItem;
520
+ }
521
+ /** A tool approval request item (RunToolApprovalItem) — the function call that
522
+ * needs human approval rides in rawItem. */
523
+ interface OpenAIToolApprovalItem {
524
+ type: "function_call";
525
+ name: string;
526
+ callId: string;
527
+ arguments: string;
528
+ id?: string;
529
+ }
530
+ interface OpenAIToolApprovalRequestedEvent {
531
+ type: "run_item_stream_event";
532
+ name: "tool_approval_requested";
533
+ item: {
534
+ type: "tool_approval_item";
535
+ rawItem: OpenAIToolApprovalItem;
536
+ };
537
+ }
538
+ /** openai-node `ResponseCreatedEvent` — the turn-open boundary. The real
539
+ * `response.id` is present here at the START of the stream (spike-confirmed),
540
+ * so it is the authoritative turn-anchor source (A1 canonical model). Carried via
541
+ * the `model` carrier. */
542
+ interface OpenAIResponsesCreated {
543
+ type: "response.created";
544
+ response: {
545
+ id: string;
546
+ };
547
+ }
548
+ /** openai-node `ResponseFunctionCallArgumentsDeltaEvent` — the per-fragment
549
+ * argument delta (snake_case `item_id`/`delta`). */
550
+ interface OpenAIResponsesFnArgsDelta {
551
+ type: "response.function_call_arguments.delta";
552
+ item_id: string;
553
+ delta: string;
554
+ }
555
+ /** openai-node `ResponseFunctionCallArgumentsDoneEvent` — the sealed full
556
+ * arguments JSON string (snake_case `arguments`/`item_id`). */
557
+ interface OpenAIResponsesFnArgsDone {
558
+ type: "response.function_call_arguments.done";
559
+ item_id: string;
560
+ arguments: string;
561
+ }
562
+ /** openai-node `ResponseTextDeltaEvent` — a streamed assistant-text fragment
563
+ * (snake_case `item_id`/`delta`). Carried via the `model` carrier. */
564
+ interface OpenAIResponsesTextDelta {
565
+ type: "response.output_text.delta";
566
+ item_id: string;
567
+ delta: string;
568
+ }
569
+ /** openai-node `ResponseTextDoneEvent` — the assistant-text stream for `item_id`
570
+ * is complete (`text` carries the full assembled string). Carried via the `model`
571
+ * carrier. Authoritative `text.end` source per the canonical event model (A1). */
572
+ interface OpenAIResponsesTextDone {
573
+ type: "response.output_text.done";
574
+ item_id: string;
575
+ text?: string;
576
+ }
577
+ /** openai-node `ResponseUsage` — per-response token counts (snake_case).
578
+ * Extends to include provider-specific fields like OpenRouter's `cost` superset. */
579
+ interface OpenAIResponseUsage {
580
+ input_tokens?: number;
581
+ output_tokens?: number;
582
+ total_tokens?: number;
583
+ input_tokens_details?: {
584
+ cached_tokens?: number;
585
+ };
586
+ output_tokens_details?: {
587
+ reasoning_tokens?: number;
588
+ };
589
+ cost?: number;
590
+ }
591
+ /** openai-node `ResponseCompletedEvent`/incomplete — `response.incomplete_details`
592
+ * is snake_case. Carried via the `model` carrier. */
593
+ interface OpenAIResponsesCompleted {
594
+ type: "response.completed" | "response.incomplete";
595
+ response: {
596
+ id: string;
597
+ status: "completed" | "incomplete";
598
+ incomplete_details?: {
599
+ reason?: string;
600
+ };
601
+ usage?: OpenAIResponseUsage;
602
+ };
603
+ }
604
+ /** openai-node `ResponseOutputItemAddedEvent` — fired when a new output item starts.
605
+ * When `item.type === "function_call"`, this is the AUTHORITATIVE tool-start source
606
+ * (canonical model, A1). Note: the raw Responses event uses snake_case `call_id`
607
+ * (DISTINCT from the run-item's camelCase `callId`). Carried via the `model` carrier. */
608
+ interface OpenAIResponsesOutputItemAdded {
609
+ type: "response.output_item.added";
610
+ item: {
611
+ id: string;
612
+ type: string;
613
+ call_id?: string;
614
+ name?: string;
615
+ status?: string;
616
+ arguments?: string;
617
+ };
618
+ }
619
+ /** openai-node `ResponseFailedEvent` — the response itself failed (e.g. rate limit).
620
+ * Carried via the `model` carrier. */
621
+ interface OpenAIResponsesFailed {
622
+ type: "response.failed";
623
+ response: {
624
+ id: string;
625
+ error?: {
626
+ message?: string;
627
+ code?: string;
628
+ };
629
+ };
630
+ }
631
+ /** A top-level streaming error event (non-terminal advisory, spec §4). */
632
+ interface OpenAIResponsesError {
633
+ type: "error";
634
+ message: string;
635
+ code?: string;
636
+ }
637
+ /** The faithful projection of the openai-node `ResponseStreamEvent` events the
638
+ * normalizer consumes (the carrier `event` payload). */
639
+ type OpenAIRawResponsesEvent = OpenAIResponsesCreated | OpenAIResponsesOutputItemAdded | OpenAIResponsesFnArgsDelta | OpenAIResponsesFnArgsDone | OpenAIResponsesTextDelta | OpenAIResponsesTextDone | OpenAIResponsesCompleted | OpenAIResponsesFailed | OpenAIResponsesError;
640
+ /** `StreamEventTextStream` — `{ type:"output_text_delta"; delta }`. */
641
+ interface OpenAIStreamEventTextDelta {
642
+ type: "output_text_delta";
643
+ delta: string;
644
+ }
645
+ /** `StreamEventResponseStarted` — `{ type:"response_started" }`. */
646
+ interface OpenAIStreamEventResponseStarted {
647
+ type: "response_started";
648
+ }
649
+ /** `StreamEventResponseCompleted` — `{ type:"response_done"; response? }`. */
650
+ interface OpenAIStreamEventResponseDone {
651
+ type: "response_done";
652
+ response?: {
653
+ id: string;
654
+ usage?: OpenAIResponseUsage;
655
+ };
656
+ }
657
+ /** `StreamEventGenericItem` — the generic `model` carrier. The verbatim
658
+ * openai-node Responses event rides in `event`. */
659
+ interface OpenAIStreamEventModel {
660
+ type: "model";
661
+ event: OpenAIRawResponsesEvent;
662
+ }
663
+ /** The SDK `ResponseStreamEvent`/`StreamEvent` union (`RunRawModelStreamEvent.data`). */
664
+ type OpenAIResponseStreamEvent = OpenAIStreamEventTextDelta | OpenAIStreamEventResponseStarted | OpenAIStreamEventResponseDone | OpenAIStreamEventModel;
665
+ interface OpenAIRawModelStreamEvent {
666
+ type: "raw_model_stream_event";
667
+ data: OpenAIResponseStreamEvent;
668
+ }
669
+ /** A SYNTHETIC terminal sentinel the host feeds the normalizer when the
670
+ * `@openai/agents` runtime THROWS `MaxTurnsExceededError` from
671
+ * `await stream.completed` after the stream ends (the spike confirmed
672
+ * `max_turns` is NOT a native stream event). The host (T6) catches the throw
673
+ * and injects this; the normalizer maps it to `turn.error{code:"max_turns",…}`.
674
+ * Modeled as a real arm of the native union (NOT cast) so the guard + drive
675
+ * switch handle it type-safely. `usage` mirrors the neutral `AgUsage` shape. */
676
+ export interface OpenAIHostError {
677
+ type: "__host_error__";
678
+ code: string;
679
+ message: string;
680
+ usage?: AgUsage;
681
+ }
682
+ /** The fixture-contract input union (verified shapes; see file header). */
683
+ export type OpenAIStreamEvent = OpenAIMessageOutputEvent | OpenAIToolCalledEvent | OpenAIToolOutputEvent | OpenAIToolSearchCalledEvent | OpenAIToolSearchOutputCreatedEvent | OpenAIReasoningEvent | OpenAIHandoffRequestedEvent | OpenAIHandoffOccurredEvent | OpenAIToolApprovalRequestedEvent | OpenAIRawModelStreamEvent | OpenAIHostError;
684
+ export declare function mapFinishReason(reason: string | undefined | null): AgFinishReason;
685
+ /**
686
+ * Build a stateful OpenAI-facet normalizer over a fresh {@link StreamAssembler}.
687
+ *
688
+ * OpenAI has no native `turn.start` and the assistant turn is delivered as a
689
+ * stream of redundant representations (the SDK emits `response_started`, a
690
+ * `model:response.created`, an in-progress duplicate, BOTH a flattened
691
+ * `output_text_delta` literal and the real item-id-keyed
692
+ * `model:response.output_text.delta`, a `response_done` literal, and TWO
693
+ * `model:response.completed` events per response). The normalizer drives the
694
+ * engine from the SINGLE authoritative source per concern (BINDING canonical
695
+ * model, plan §"Spike Findings") and ignores the rest:
696
+ *
697
+ * - turn open ← `model:response.created` (real `response.id` present at start)
698
+ * - text ← `model:response.output_text.delta` (carries `item_id`)
699
+ * - text end ← the `message_output_created` run-item (authoritative close +
700
+ * citations carrier, audit M22 — `response.output_text.done` is a
701
+ * no-op; text streams left open by it fall to the defensive
702
+ * close-any-dangling-stream fallback in `closeResponse()` /
703
+ * `endOpenStreamsAndCloseMessage()` / `emitRoundClose()`)
704
+ * - turn close ← `model:response.completed` (guard close-once)
705
+ *
706
+ * `ensureResponseOpen()` opens turn + message exactly once per response;
707
+ * `closeResponse()` resets per-response state so the duplicate `response.completed`
708
+ * is a no-op.
709
+ *
710
+ * `reasoning_item_created` / `tool_approval_requested` (Task 3, audit M48) map to
711
+ * `reasoning.start/delta/end/opaque` and `hitl.ask{kind:"approval"}` respectively —
712
+ * see `driveReasoningItemCreated` and the run-item switch below for the full
713
+ * rationale. `handoff_requested` / `handoff_occurred` (Task 3, audit M48 review
714
+ * Finding 1) map to a `subagentStart`/`subagentDone` PAIR bracketing the transfer —
715
+ * the ORIGINAL Task-3 mapping used a standalone `handoff` event on the false premise
716
+ * that the wire carried no completion signal; `handoff_occurred` IS that signal
717
+ * (verified against the installed `@openai/agents-core` 0.2.1 peer dep's
718
+ * `events.d.ts`). The bare `handoff` event still fires — carrying `toAgentName` —
719
+ * but only once it's actually known, at `handoff_occurred` (the target agent is not
720
+ * resolvable at `handoff_requested` time on the real wire; see the run-item switch's
721
+ * `handoff_requested`/`handoff_occurred` cases for the full rationale, including why
722
+ * identity can't ride the `subagentStart` call itself). `emitExt` is reserved for a
723
+ * genuinely unrecognisable OUTER envelope AND — per the run-item switch's default
724
+ * arm — a genuinely-unknown run-item `name` (mirrors the Claude facet).
725
+ */
726
+ export declare function createOpenaiNormalizer(): Normalizer;
727
+ export {};
728
+ //# sourceMappingURL=index.d.ts.map