@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/dist/index.js ADDED
@@ -0,0 +1,1340 @@
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 { JsonValue, StreamAssembler, } from "@silverprotocol/core";
65
+ // ─── finish-reason → AgFinishReason (spec §4) ─────────────────────────────────
66
+ // Maps any OpenAI completion / `response.incomplete_details.reason` to the
67
+ // neutral AgFinishReason superset. A bare `response.completed` (no reason) = stop.
68
+ export function mapFinishReason(reason) {
69
+ switch (reason) {
70
+ case undefined:
71
+ case null:
72
+ case "stop":
73
+ case "completed":
74
+ return "stop";
75
+ case "max_output_tokens":
76
+ case "max_tokens":
77
+ return "token_limit";
78
+ case "content_filter":
79
+ return "safety_blocked";
80
+ default:
81
+ return "unknown";
82
+ }
83
+ }
84
+ // ─── tool-output content → AgBlock[] (spec §2) ────────────────────────────────
85
+ function toolOutputToAgBlocks(output) {
86
+ if (typeof output === "string") {
87
+ return output.length > 0 ? [{ type: "text", text: output }] : [];
88
+ }
89
+ const parts = Array.isArray(output) ? output : [output];
90
+ const out = [];
91
+ for (const part of parts) {
92
+ // Two DIFFERENT text discriminants ride this seam (Finding #2 above):
93
+ // "text" on the bare-object arm, "input_text" on the array arm.
94
+ if (part.type === "text" || part.type === "input_text") {
95
+ out.push({ type: "text", text: part.text });
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+ // ─── usage mapping: OpenAI response usage → AgUsage ──────────────────────────
101
+ // cumulative:false — OpenAI usage is FINAL (not cumulative like Anthropic).
102
+ function mapUsage(usage) {
103
+ if (usage === undefined)
104
+ return undefined;
105
+ const u = { cumulative: false };
106
+ if (usage.input_tokens !== undefined)
107
+ u.inputTokens = usage.input_tokens;
108
+ if (usage.output_tokens !== undefined)
109
+ u.outputTokens = usage.output_tokens;
110
+ if (usage.total_tokens !== undefined)
111
+ u.totalTokens = usage.total_tokens;
112
+ if (usage.input_tokens_details?.cached_tokens !== undefined)
113
+ u.cacheReadTokens = usage.input_tokens_details.cached_tokens;
114
+ if (usage.output_tokens_details?.reasoning_tokens !== undefined)
115
+ u.reasoningTokens = usage.output_tokens_details.reasoning_tokens;
116
+ // Provider-reported cost (e.g. OpenRouter `cost`) maps verbatim to costUsd.
117
+ if (usage.cost !== undefined)
118
+ u.costUsd = usage.cost;
119
+ return u;
120
+ }
121
+ // ─── url_citation annotation → AgCitation ──────────────────────────────────
122
+ // `partText` is the source output_text part's text string; used to extract the
123
+ // cited substring from the char-offset indices carried by the annotation (Fix 3).
124
+ function mapAnnotationsToCitations(annotations, partText) {
125
+ if (annotations === undefined || annotations.length === 0)
126
+ return undefined;
127
+ const out = [];
128
+ for (const ann of annotations) {
129
+ if (ann.type === "url_citation") {
130
+ // Extract the cited substring from the part text when both offsets are present
131
+ // and valid (Fix 3). Fall back to "" when any guard condition fails.
132
+ const startIdx = ann.start_index;
133
+ const endIdx = ann.end_index;
134
+ const citedText = startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
135
+ ? partText.slice(startIdx, endIdx)
136
+ : "";
137
+ const cit = {
138
+ kind: "url",
139
+ url: ann.url,
140
+ citedText,
141
+ indexFrame: "response",
142
+ };
143
+ if (ann.title !== undefined)
144
+ cit.title = ann.title;
145
+ if (startIdx !== undefined)
146
+ cit.startIndex = startIdx;
147
+ if (endIdx !== undefined)
148
+ cit.endIndex = endIdx;
149
+ out.push(cit);
150
+ }
151
+ // file_citation: no url-kind match; skip (deferred to a later slice — only remaining silent annotation drop)
152
+ }
153
+ return out.length > 0 ? out : undefined;
154
+ }
155
+ // ─── structural guard: unknown → OpenAIStreamEvent ────────────────────────────
156
+ // `createOpenaiNormalizer().push` receives the genuine JSON boundary (`JsonValue`,
157
+ // spec §0.1). The run-seam yields well-formed `OpenAIStreamEvent`s, but this is the
158
+ // deserialization boundary, so we confirm the OUTER discriminant before driving the
159
+ // engine. A user-defined type guard (not a cast) narrows on success; a failure routes
160
+ // the raw payload to `ext.openai.unparsed` and returns (graceful, Tenet 6).
161
+ //
162
+ // The guard takes `unknown` (not `JsonValue`): `OpenAIStreamEvent`'s nested
163
+ // interfaces have no index signature, so a `v is OpenAIStreamEvent` predicate over a
164
+ // `JsonValue` param is rejected by TS (TS2677). `unknown` is the genuine boundary
165
+ // input type and is predicate-compatible; the caller passes a `JsonValue`, which
166
+ // widens to `unknown` losslessly (mirrors the Claude facet's `isSDKMessage`).
167
+ function isJsonObject(v) {
168
+ return typeof v === "object" && v !== null && !Array.isArray(v);
169
+ }
170
+ /**
171
+ * Extract `structuredContent` (the ggui cache-marker channel, spec §2.1/§4)
172
+ * from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
173
+ * follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
174
+ * would be an object keyed by `.structuredContent`; a live capture
175
+ * (`echo-gpt55`, gpt-5.5 / agents-core 0.12.0) proved that assumption never
176
+ * matches real `@openai/agents` native-MCP wire — `wrapperOutput` there is a
177
+ * JSON-STRINGIFIED string (`'{"type":"text","text":"…"}'`), because
178
+ * `RunToolCallOutputItem.toJSON()` (agents-core 0.12.0's `dist/items.mjs`)
179
+ * runs `.output` through `toSmartString`, which passes strings through
180
+ * unchanged but JSON.stringifies objects — and the object it stringifies
181
+ * (`content[0]`, the raw MCP content ITEM) never had a `.structuredContent`
182
+ * sibling to begin with: `mcpToFunctionTool`'s `invoke()`
183
+ * (agents-core 0.12.0's `dist/mcp.mjs:672-738`) reads
184
+ * `result.structuredContent` off the full `CallToolResult` but discards it
185
+ * unless `useStructuredContent` is `true` (which instead merges it into the
186
+ * MODEL-VISIBLE text — a spec violation, not a fix; rejected, see
187
+ * `packages/e2e/src/agents/openai-agents-sdk/run.ts`) — so under the SDK
188
+ * default, structuredContent is unconditionally dropped BEFORE it ever
189
+ * reaches `item.output`. This is true for `@openai/agents-core` 0.2.1 too
190
+ * (grep-verified: zero mentions of `structuredContent` anywhere in its
191
+ * `dist/`) — the whole `>=0.2.0 <0.13` peer range's native MCP client drops
192
+ * it by default; there is no version where the ORIGINAL assumed shape was
193
+ * ever real wire truth for a native-MCP-routed tool call.
194
+ *
195
+ * The ONE real channel `@openai/agents-core` 0.12.0 offers is
196
+ * `MCPServer.customDataExtractor` (absent before 0.12): a per-server
197
+ * callback that receives `{ …, structuredContent }` and whose (JSON-
198
+ * validated, SDK-normalized) return value lands verbatim on
199
+ * `RunToolCallOutputItem.customData` — a NEW sibling field to `.output`,
200
+ * included as-is (not smart-stringified) by `toJSON()`. This requires the
201
+ * CALLER (the agent/worker that constructs the `MCPServer`) to opt in —
202
+ * the facet cannot conjure data the wire never carries. Two homes are
203
+ * checked, in order:
204
+ *
205
+ * 1. `customData.structuredContent` — the 0.12.0+ channel above.
206
+ * 2. `wrapperOutput.structuredContent` — kept as defense-in-depth for
207
+ * callers whose OWN local (non-MCP-native) tool wrapping manually
208
+ * returns a full `CallToolResult`-shaped object (unverified against the
209
+ * SDK's native MCP client, but a real possible shape for a custom local
210
+ * tool's return value); also tried after a SAFE `JSON.parse` when
211
+ * `wrapperOutput` is a string (never throws out of `push()` — Tenet 6;
212
+ * a parse failure or a parsed value with no `.structuredContent` key is
213
+ * the ordinary case for a plain-text tool result, not an anomaly worth
214
+ * an `ext` carry).
215
+ *
216
+ * Neither home firing (the common case — most tool results carry no
217
+ * structuredContent at all) is NOT a drop: it correctly yields `undefined`.
218
+ */
219
+ function extractStructuredContent(wrapperOutput, customData) {
220
+ if (isJsonObject(customData) && isJsonObject(customData.structuredContent)) {
221
+ return JsonValue.parse(customData.structuredContent);
222
+ }
223
+ if (isJsonObject(wrapperOutput) && isJsonObject(wrapperOutput.structuredContent)) {
224
+ return JsonValue.parse(wrapperOutput.structuredContent);
225
+ }
226
+ if (typeof wrapperOutput === "string") {
227
+ try {
228
+ const parsed = JSON.parse(wrapperOutput);
229
+ if (isJsonObject(parsed) && isJsonObject(parsed.structuredContent)) {
230
+ return JsonValue.parse(parsed.structuredContent);
231
+ }
232
+ }
233
+ catch {
234
+ // Not JSON, or JSON with no `.structuredContent` key — the ordinary
235
+ // shape for a plain-text tool result. No structuredContent to extract;
236
+ // never throw out of push() (Tenet 6).
237
+ }
238
+ }
239
+ return undefined;
240
+ }
241
+ // Only the OUTER envelope is validated here (the RunStreamEvent families: a
242
+ // `run_item_stream_event` with a string `name`, a `raw_model_stream_event` with a
243
+ // `data` object, or the synthetic `__host_error__` terminal sentinel the host feeds
244
+ // on `MaxTurnsExceededError`). The inner `drive` switch handles every nested arm
245
+ // structurally and no-ops anything it does not recognise — so a partially-shaped-but-
246
+ // well-typed event is never lost, and only a genuinely non-OpenAI-shaped payload
247
+ // falls to `unparsed`.
248
+ function isOpenAIStreamEvent(v) {
249
+ if (!isJsonObject(v))
250
+ return false;
251
+ if (v.type === "run_item_stream_event")
252
+ return typeof v.name === "string";
253
+ if (v.type === "raw_model_stream_event")
254
+ return isJsonObject(v.data);
255
+ if (v.type === "__host_error__")
256
+ return typeof v.code === "string" && typeof v.message === "string";
257
+ return false;
258
+ }
259
+ // ─── the stateful normalizer (A1 §5-6) ────────────────────────────────────────
260
+ /**
261
+ * Build a stateful OpenAI-facet normalizer over a fresh {@link StreamAssembler}.
262
+ *
263
+ * OpenAI has no native `turn.start` and the assistant turn is delivered as a
264
+ * stream of redundant representations (the SDK emits `response_started`, a
265
+ * `model:response.created`, an in-progress duplicate, BOTH a flattened
266
+ * `output_text_delta` literal and the real item-id-keyed
267
+ * `model:response.output_text.delta`, a `response_done` literal, and TWO
268
+ * `model:response.completed` events per response). The normalizer drives the
269
+ * engine from the SINGLE authoritative source per concern (BINDING canonical
270
+ * model, plan §"Spike Findings") and ignores the rest:
271
+ *
272
+ * - turn open ← `model:response.created` (real `response.id` present at start)
273
+ * - text ← `model:response.output_text.delta` (carries `item_id`)
274
+ * - text end ← the `message_output_created` run-item (authoritative close +
275
+ * citations carrier, audit M22 — `response.output_text.done` is a
276
+ * no-op; text streams left open by it fall to the defensive
277
+ * close-any-dangling-stream fallback in `closeResponse()` /
278
+ * `endOpenStreamsAndCloseMessage()` / `emitRoundClose()`)
279
+ * - turn close ← `model:response.completed` (guard close-once)
280
+ *
281
+ * `ensureResponseOpen()` opens turn + message exactly once per response;
282
+ * `closeResponse()` resets per-response state so the duplicate `response.completed`
283
+ * is a no-op.
284
+ *
285
+ * `reasoning_item_created` / `tool_approval_requested` (Task 3, audit M48) map to
286
+ * `reasoning.start/delta/end/opaque` and `hitl.ask{kind:"approval"}` respectively —
287
+ * see `driveReasoningItemCreated` and the run-item switch below for the full
288
+ * rationale. `handoff_requested` / `handoff_occurred` (Task 3, audit M48 review
289
+ * Finding 1) map to a `subagentStart`/`subagentDone` PAIR bracketing the transfer —
290
+ * the ORIGINAL Task-3 mapping used a standalone `handoff` event on the false premise
291
+ * that the wire carried no completion signal; `handoff_occurred` IS that signal
292
+ * (verified against the installed `@openai/agents-core` 0.2.1 peer dep's
293
+ * `events.d.ts`). The bare `handoff` event still fires — carrying `toAgentName` —
294
+ * but only once it's actually known, at `handoff_occurred` (the target agent is not
295
+ * resolvable at `handoff_requested` time on the real wire; see the run-item switch's
296
+ * `handoff_requested`/`handoff_occurred` cases for the full rationale, including why
297
+ * identity can't ride the `subagentStart` call itself). `emitExt` is reserved for a
298
+ * genuinely unrecognisable OUTER envelope AND — per the run-item switch's default
299
+ * arm — a genuinely-unknown run-item `name` (mirrors the Claude facet).
300
+ */
301
+ export function createOpenaiNormalizer() {
302
+ const a = new StreamAssembler();
303
+ // OpenAI's native stream carries no thread/session id (unlike Claude's
304
+ // `session_id`), so the threadId is a fixed facet label. The Router rebases
305
+ // ids downstream.
306
+ const threadId = "openai";
307
+ // Per-response anchoring state (one open response at a time on this seam).
308
+ let turnCounter = 0;
309
+ let turnId; // current open response's turn id
310
+ let msgId; // current open message id
311
+ let responseId; // real response.id once known
312
+ // Open text streams keyed by Responses item_id (textStart once per id).
313
+ const openTextStreams = new Set();
314
+ // Close-once guard: the SDK emits `response.completed` TWICE per response. Once a
315
+ // response.id (or a synthesized turnId) has been closed, any further terminal event
316
+ // for it is a no-op — it must NOT reopen a fresh message/turn.
317
+ const closedResponses = new Set();
318
+ // Task 3 (audit M48 review, Finding 1) — handoff-bracket state. Every
319
+ // run-item event on this seam arrives AFTER its owning round's
320
+ // `response.completed` on the real wire (M22 late-citations / Task 4b
321
+ // late-tool-result precedent — verified against @openai/agents-core
322
+ // 0.2.1's `run.mjs`/`runImplementation.mjs`: `streamStepItemsToRunResult`
323
+ // streams `processedResponse.newItems` — which includes the
324
+ // `handoff_call_item` — only AFTER the raw-event loop for that round
325
+ // completes, and the `handoff_output_item` from `executeHandoffCalls`
326
+ // streams later still, before the NEXT round's `response.created`). So by
327
+ // the time either `handoff_requested` or `handoff_occurred` lands, the
328
+ // per-response `turnId` var above has already been reset to `undefined` by
329
+ // `resetResponseState()` — this facet needs a tracker that SURVIVES that
330
+ // reset to resolve "the round that requested the handoff" as the subagent
331
+ // bracket's `parentTurnId`. Set once per genuinely-new round in
332
+ // `ensureResponseOpen()`; never cleared on close (deliberately — that's
333
+ // the whole point). Intermediate response rounds after a handoff continue
334
+ // opening their OWN top-level turns from their own `response.id` (openai's
335
+ // turn model) — the subagent pair BRACKETS the transfer, it does not
336
+ // re-parent later rounds to it.
337
+ let lastTopLevelTurnId;
338
+ // Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
339
+ let handoffOrdinal = 0;
340
+ // FIFO queue of open handoff brackets awaiting their matching
341
+ // `handoff_occurred` (paired turnId + the SAME parentTurnId `subagentStart`
342
+ // used — `subagentDone` must replay it verbatim, mirroring the
343
+ // claude-agent-sdk facet's paired start/done convention). Only one handoff
344
+ // genuinely executes per round on the real wire (`executeHandoffCalls`
345
+ // rejects the rest), so in practice at most one entry is ever open — FIFO
346
+ // is the defensively-correct match rule regardless.
347
+ const openHandoffs = [];
348
+ // Per-instance tool state (T5b — replaces the module-level statics for the factory path).
349
+ // fc_… item id → model call_id correlation, populated by response.output_item.added
350
+ // (the AUTHORITATIVE tool-start source per the canonical model, A1).
351
+ const instanceCallIdByItemId = new Map();
352
+ // Accumulated function_call_arguments.delta fragments, keyed by fc_ item id.
353
+ // The engine accumulates for downstream use; `.done.arguments` carries the full
354
+ // string so argBuffers is primarily for the fallback path.
355
+ const instanceArgBuffers = new Map();
356
+ // Refusal tracking (T5c — instance state mirroring the old module-level
357
+ // `pendingRefusal`). Set when a `message_output_created` run-item carries a
358
+ // `refusal` content part; the downstream `response.completed` arm then closes
359
+ // the turn with `finishReason:"refusal"`. Cleared on every response close so it
360
+ // never leaks across turns.
361
+ let pendingRefusal = false;
362
+ // ── Task 4b: defer a round's close past its pending tool results ───────────
363
+ // (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
364
+ // AFTER `response.completed` — closing at native-close time would put a later
365
+ // `tool.done` on an already-sealed message / closed turn, which `reduce()`
366
+ // correctly parks (resync). Per-turn pending set: toolCallIds that have had
367
+ // `tool.start` emitted but no `tool.done` yet.
368
+ const pendingToolsByTurn = new Map();
369
+ // toolCallId → the turnId it started under. `tool_output` may land after this
370
+ // response's local `turnId` var has been reset (resetResponseState runs at
371
+ // native-close time regardless of deferral) and/or after a NEW round has
372
+ // opened, so the engine's #lastTurn backfill could misattribute a late result
373
+ // to the wrong turn without this explicit map.
374
+ const turnIdByToolCallId = new Map();
375
+ /**
376
+ * Register `callId` as pending a `tool.done` under the CURRENT open turn
377
+ * (Task 4b). Shared by the raw `response.output_item.added` function_call
378
+ * path and the built-in Shell/Apply-Patch `tool_called` synthesis path
379
+ * (playbook 2026-07-03 SDK-bump adaptation, Finding #1) — both start a call
380
+ * whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
381
+ * is open (defensive; every caller already calls `ensureResponseOpen()` first).
382
+ */
383
+ function registerPendingTool(callId) {
384
+ if (turnId === undefined)
385
+ return;
386
+ let pending = pendingToolsByTurn.get(turnId);
387
+ if (pending === undefined) {
388
+ pending = new Set();
389
+ pendingToolsByTurn.set(turnId, pending);
390
+ }
391
+ pending.add(callId);
392
+ turnIdByToolCallId.set(callId, turnId);
393
+ }
394
+ // Stashed close for a turn whose pending set was non-empty at close time,
395
+ // keyed by turnId. Consumed the moment its pending set drains (emitted right
396
+ // after the draining `tool.done`, same push() batch), or by `flush()`
397
+ // verbatim if the result never arrives (the round genuinely completed — a
398
+ // missing tool result must not swallow the close).
399
+ const stashedCloseByTurn = new Map();
400
+ /**
401
+ * End open text streams + close the message + closeTurnDone for `tid`, using
402
+ * whichever values are live right now (immediate path) or were captured at
403
+ * defer time (drain path) — same three calls either way.
404
+ */
405
+ function emitRoundClose(tid, mId, textStreamIds, fields) {
406
+ for (const streamId of textStreamIds)
407
+ a.textEnd(streamId, mId);
408
+ a.closeMessage(mId);
409
+ a.closeTurnDone(tid, fields);
410
+ }
411
+ /**
412
+ * Close the round now, unless `tid`'s pending-tool set is non-empty — in
413
+ * which case stash everything the close needs (message id, dangling text
414
+ * stream ids, turn.done fields) for the `tool_output` handler (or `flush()`)
415
+ * to replay later. `closeTurnError` paths never call this (they close
416
+ * immediately via `endOpenStreamsAndCloseMessage` — an errored round's
417
+ * pending results are moot, by design).
418
+ */
419
+ function finishOrDeferRound(tid, mId, textStreamIds, fields) {
420
+ const pending = pendingToolsByTurn.get(tid);
421
+ if (pending !== undefined && pending.size > 0) {
422
+ stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
423
+ return;
424
+ }
425
+ emitRoundClose(tid, mId, textStreamIds, fields);
426
+ }
427
+ /**
428
+ * Open the turn + message exactly once per response. Uses the real `response.id`
429
+ * (`turn_<id>`) when known; synthesizes a stable id only if `response.created` was
430
+ * somehow absent (defensive — the spike confirms the id is always present at start).
431
+ * Returns the close-once key (the real response.id, else the synthesized turnId),
432
+ * or `undefined` when the response has already been closed (caller must no-op).
433
+ */
434
+ function ensureResponseOpen(respId) {
435
+ // Already closed → never reopen (the duplicate `response.completed` lands here).
436
+ if (respId !== undefined && closedResponses.has(respId))
437
+ return undefined;
438
+ if (turnId !== undefined) {
439
+ // Backfill the real id if it arrives after a defensive synthesized open.
440
+ if (respId !== undefined && responseId === undefined)
441
+ responseId = respId;
442
+ return responseId ?? turnId;
443
+ }
444
+ responseId = respId;
445
+ turnId = respId !== undefined ? `turn_${respId}` : `turn_${threadId}_${++turnCounter}`;
446
+ msgId = `msg_${turnId}`;
447
+ // Task 3 (audit M48 review, Finding 1): survives resetResponseState() —
448
+ // see the closure-state doc above.
449
+ lastTopLevelTurnId = turnId;
450
+ a.openTurn(turnId, threadId);
451
+ a.openMessage({ id: msgId, role: "assistant", turnId, threadId });
452
+ return responseId ?? turnId;
453
+ }
454
+ /** Reset per-response state after a close. Marks the response closed (close-once). */
455
+ function resetResponseState() {
456
+ const key = responseId ?? turnId;
457
+ if (key !== undefined)
458
+ closedResponses.add(key);
459
+ openTextStreams.clear();
460
+ turnId = undefined;
461
+ msgId = undefined;
462
+ responseId = undefined;
463
+ pendingRefusal = false;
464
+ }
465
+ /**
466
+ * Close any dangling open message/turn (flush path: a stream ended before
467
+ * `response.completed`). Ends open text streams, closes the message, and reuses
468
+ * `resetResponseState` so the response is marked closed.
469
+ */
470
+ function closeResponse() {
471
+ if (msgId !== undefined) {
472
+ for (const streamId of openTextStreams)
473
+ a.textEnd(streamId, msgId);
474
+ a.closeMessage(msgId);
475
+ }
476
+ resetResponseState();
477
+ }
478
+ /** Drive the engine from one verbatim openai-node Responses event (snake_case). */
479
+ function driveRawResponsesEvent(ev) {
480
+ switch (ev.type) {
481
+ case "response.created": {
482
+ // Authoritative turn open — the real response.id is present at start.
483
+ ensureResponseOpen(ev.response.id);
484
+ return;
485
+ }
486
+ case "response.output_text.delta": {
487
+ ensureResponseOpen();
488
+ if (msgId === undefined)
489
+ return; // unreachable post-ensure; satisfies the narrowing
490
+ if (!openTextStreams.has(ev.item_id)) {
491
+ openTextStreams.add(ev.item_id);
492
+ a.textStart(ev.item_id, msgId, { role: "assistant" });
493
+ }
494
+ // OpenAI text deltas are suffix-only fragments (cumulative:false, the default).
495
+ a.textDelta(ev.item_id, msgId, ev.delta, { cumulative: false });
496
+ return;
497
+ }
498
+ case "response.output_text.done": {
499
+ // NO-OP (audit M22): the citations carrier — `message_output_created` — is
500
+ // the authoritative text-end source (it also reports refusal parts and
501
+ // arrives with the annotated part, so closing here would emit `text.end`
502
+ // BEFORE citations are known). The stream stays in `openTextStreams`;
503
+ // `driveMessageOutputCreated` closes it (with citations if present), or —
504
+ // defensively, if that run-item never arrives — `closeResponse()` /
505
+ // `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
506
+ return;
507
+ }
508
+ case "response.output_item.added": {
509
+ // Authoritative tool-start source (canonical model, A1 §"Spike Findings").
510
+ // Only function_call items carry a tool name + call_id; other item types
511
+ // (message, reasoning) are no-op'd here — their lifecycle is handled elsewhere.
512
+ if (ev.item.type === "function_call" && ev.item.call_id !== undefined && ev.item.name !== undefined) {
513
+ const fcId = ev.item.id;
514
+ const callId = ev.item.call_id;
515
+ ensureResponseOpen();
516
+ // Record the fc_→call_id correlation (the raw argument events carry only
517
+ // the fc_ item id, not the call_id; this mapping allows recovery).
518
+ instanceCallIdByItemId.set(fcId, callId);
519
+ a.toolStart({
520
+ toolCallId: callId,
521
+ name: ev.item.name,
522
+ itemId: fcId,
523
+ messageId: msgId,
524
+ });
525
+ // Task 4b: this call is now pending a tool.done under the current turn
526
+ // (ensureResponseOpen() above guarantees `turnId` is defined here).
527
+ registerPendingTool(callId);
528
+ }
529
+ return;
530
+ }
531
+ case "response.function_call_arguments.delta": {
532
+ // Accumulate the fragment per fc_ item id (spec §8.1).
533
+ const prevDelta = instanceArgBuffers.get(ev.item_id) ?? "";
534
+ instanceArgBuffers.set(ev.item_id, prevDelta + ev.delta);
535
+ // Resolve to call_id for the engine (fall back to fc_ id defensively).
536
+ const callIdDelta = instanceCallIdByItemId.get(ev.item_id) ?? ev.item_id;
537
+ a.toolArgsDelta(callIdDelta, ev.delta, { cumulative: false });
538
+ return;
539
+ }
540
+ case "response.function_call_arguments.done": {
541
+ // Seal accumulated buffer → toolArgsAssembled. Prefer the event's full
542
+ // `arguments` string (the engine accumulates the delta path); fall back to
543
+ // the instance buffer when the done event omits it (defensive).
544
+ //
545
+ // `ev.arguments` is typed `string`, but this is the deserialization
546
+ // boundary (audit M46, §2.B): a nonconforming provider (OpenRouter et
547
+ // al.) can hand back an empty string, truncated JSON, or omit the
548
+ // field entirely — `JSON.parse` throws `SyntaxError` on the first two
549
+ // and `.length` throws `TypeError` on the third, all three of which
550
+ // used to escape push() uncaught. Widen the local binding (no cast —
551
+ // the boundary genuinely can hand back less than the type promises)
552
+ // and guard the parse: on any failure, degrade to a best-effort
553
+ // `tool.args.assembled` with `input:{}` (keeps the tool-call block
554
+ // fold-coherent, Tenet 6) and route the untouched raw signal through
555
+ // `ext.openai.unparsed` instead of throwing — an explicit `null`
556
+ // marker distinguishes "field never arrived" from "field arrived
557
+ // empty" (`""`), both preserved losslessly.
558
+ const rawArguments = ev.arguments;
559
+ const buffered = instanceArgBuffers.get(ev.item_id) ?? "";
560
+ const candidate = rawArguments !== undefined && rawArguments.length > 0 ? rawArguments : buffered;
561
+ const callIdDone = instanceCallIdByItemId.get(ev.item_id) ?? ev.item_id;
562
+ let input;
563
+ try {
564
+ input = JsonValue.parse(JSON.parse(candidate));
565
+ }
566
+ catch {
567
+ input = {};
568
+ a.emitExt("openai", "unparsed", { itemId: ev.item_id, arguments: rawArguments ?? null });
569
+ }
570
+ a.toolArgsAssembled(callIdDone, input);
571
+ instanceArgBuffers.delete(ev.item_id);
572
+ return;
573
+ }
574
+ case "response.completed":
575
+ case "response.incomplete": {
576
+ // Terminal close — guard close-once (the SDK emits completed TWICE). A
577
+ // `undefined` return means this response is already closed → no-op the dupe.
578
+ if (ensureResponseOpen(ev.response.id) === undefined)
579
+ return;
580
+ if (turnId === undefined)
581
+ return; // unreachable post-ensure; satisfies narrowing
582
+ if (msgId === undefined)
583
+ return; // unreachable post-ensure; satisfies narrowing
584
+ // Snapshot before any deferral: `resetResponseState()` below always
585
+ // clears these, but a deferred close needs them later (Task 4b).
586
+ const currentTurnId = turnId;
587
+ const currentMsgId = msgId;
588
+ const textStreamIds = Array.from(openTextStreams);
589
+ const reason = ev.response.incomplete_details?.reason;
590
+ const usage = mapUsage(ev.response.usage);
591
+ // Decision tree (mirrors the canonical model, A1):
592
+ // refusal recorded → closeTurnDone success, finishReason:"refusal"
593
+ // content_filter → closeTurnDone error-outcome + safety signal
594
+ // any other incomplete → closeTurnError{code:reason, usage}
595
+ // plain completed → closeTurnDone success
596
+ // Task 4b: every closeTurnDone arm below routes through
597
+ // `finishOrDeferRound` — a round with pending tool results stashes its
598
+ // ENTIRE close (message + turn) instead of emitting (INV-MSG).
599
+ // closeTurnError does NOT defer (an errored round's pending results are
600
+ // moot, by design) — it still closes the message immediately here.
601
+ if (pendingRefusal) {
602
+ finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
603
+ outcome: { type: "success" },
604
+ finishReason: "refusal",
605
+ ...(usage !== undefined ? { usage } : {}),
606
+ });
607
+ }
608
+ else if (reason === "content_filter") {
609
+ const safety = [{ category: "content_filter", blocked: true }];
610
+ finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
611
+ outcome: { type: "error", message: "content_filter" },
612
+ finishReason: mapFinishReason(reason),
613
+ safety,
614
+ ...(usage !== undefined ? { usage } : {}),
615
+ });
616
+ }
617
+ else if (ev.type === "response.incomplete") {
618
+ endOpenStreamsAndCloseMessage();
619
+ a.closeTurnError(currentTurnId, {
620
+ message: reason ?? "incomplete",
621
+ ...(reason !== undefined ? { code: reason } : {}),
622
+ ...(usage !== undefined ? { usage } : {}),
623
+ });
624
+ }
625
+ else {
626
+ finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
627
+ outcome: { type: "success" },
628
+ finishReason: mapFinishReason(reason),
629
+ ...(usage !== undefined ? { usage } : {}),
630
+ });
631
+ }
632
+ resetResponseState();
633
+ return;
634
+ }
635
+ case "response.failed": {
636
+ // The response itself failed (rate limit, server error, …). Close-once guard.
637
+ if (ensureResponseOpen(ev.response.id) === undefined)
638
+ return;
639
+ if (turnId === undefined)
640
+ return; // unreachable post-ensure; satisfies narrowing
641
+ endOpenStreamsAndCloseMessage();
642
+ const err = ev.response.error;
643
+ a.closeTurnError(turnId, {
644
+ message: err?.message ?? "response.failed",
645
+ ...(err?.code !== undefined ? { code: err.code } : {}),
646
+ });
647
+ resetResponseState();
648
+ return;
649
+ }
650
+ case "error": {
651
+ // Top-level NON-terminal advisory (spec §4 bare `error`). It does NOT close
652
+ // the turn — surface it on the lossless vendor channel without disturbing the
653
+ // open response lifecycle.
654
+ a.emitExt("openai", "error", {
655
+ message: ev.message,
656
+ ...(ev.code !== undefined ? { code: ev.code } : {}),
657
+ });
658
+ return;
659
+ }
660
+ // Duplicate raw families IGNORED per the canonical model:
661
+ // response.output_text.done is its own no-op arm above (audit M22);
662
+ // response.output_item.done, response.in_progress, content_part.* are not
663
+ // authoritative sources.
664
+ default:
665
+ return;
666
+ }
667
+ }
668
+ /** End any still-open text streams (defensive), then close the open message. */
669
+ function endOpenStreamsAndCloseMessage() {
670
+ if (msgId !== undefined) {
671
+ for (const streamId of openTextStreams)
672
+ a.textEnd(streamId, msgId);
673
+ a.closeMessage(msgId);
674
+ }
675
+ }
676
+ /**
677
+ * Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
678
+ * citations source (audit M22). The text itself already streamed from the raw
679
+ * `response.output_text.delta` path — this MUST NOT re-emit it — but the
680
+ * `output_text` part's annotations are only known here (they are not present on
681
+ * `response.output_text.done`), so THIS is where the matching open text stream
682
+ * actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
683
+ * directly to the streamed block (never a duplicate id-less supplement). A
684
+ * `refusal` part sets `pendingRefusal` so the downstream `response.completed`
685
+ * arm closes with `finishReason:"refusal"` (no text stream to close for it).
686
+ *
687
+ * Correlation: the Responses `item_id` used by the raw delta/done events and the
688
+ * run-item wrapper's `rawItem.id` are DIFFERENT id spaces on this SDK's surface,
689
+ * so the match is positional — FIFO against `openTextStreams` (insertion-ordered;
690
+ * in practice exactly one open stream per output_text part).
691
+ *
692
+ * On the real wire this run-item can arrive AFTER `response.completed` (verified
693
+ * by the #128 OpenRouter capture — round 2's `message_output_created` lands last,
694
+ * past the terminal close). Never `ensureResponseOpen()` here: doing so would
695
+ * open a PHANTOM new turn once the response has already closed. If `msgId` is
696
+ * `undefined` (already closed) the matching stream was already ended — without
697
+ * citations — by the native-close fallback (`emitRoundClose` et al.); degrade
698
+ * gracefully and skip the `text.end` re-target. If the late part still carries
699
+ * annotations, though, they are NOT yet lost anywhere else — silently dropping
700
+ * them here would violate Tenet 6. Route them losslessly through the facet's
701
+ * existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
702
+ * the run-item id + the raw annotations array verbatim (review finding on M22).
703
+ * A part with no annotations has nothing to lose — the plain `continue` stays.
704
+ */
705
+ function driveMessageOutputCreated(item) {
706
+ for (const part of item.content) {
707
+ if (part.type === "refusal") {
708
+ pendingRefusal = true;
709
+ continue;
710
+ }
711
+ if (part.type === "output_text") {
712
+ if (msgId === undefined) {
713
+ // response already closed — see doc above.
714
+ if (part.annotations !== undefined && part.annotations.length > 0) {
715
+ a.emitExt("openai", "late-citations", {
716
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
717
+ annotations: JsonValue.parse(part.annotations),
718
+ });
719
+ }
720
+ continue;
721
+ }
722
+ const streamId = openTextStreams.values().next().value;
723
+ if (streamId === undefined)
724
+ continue; // defensive: no matching open stream
725
+ openTextStreams.delete(streamId);
726
+ const citations = mapAnnotationsToCitations(part.annotations, part.text);
727
+ a.textEnd(streamId, msgId, citations !== undefined ? { citations } : undefined);
728
+ }
729
+ }
730
+ }
731
+ /**
732
+ * Map a `reasoning_item_created` run-item (Task 3, audit M48): the SOLE source
733
+ * for reasoning content on this seam — `response.output_item.added` only special-
734
+ * cases `item.type==="function_call"` (canonical model, A1); it carries no
735
+ * `content`/`providerData` for a `reasoning` item, so it structurally cannot
736
+ * supply the summary text or the ZDR blob and is left untouched (single-source
737
+ * per concern, no double-emit).
738
+ *
739
+ * The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
740
+ * the incremental text/tool-arg deltas elsewhere in this facet), so
741
+ * start/delta/end/opaque all fire together, in that order, from this single call:
742
+ * - `reasoning.start` — opens the block; `itemId` carries the `rs_…` id.
743
+ * - `reasoning.delta` — the joined `input_text` parts, only if non-empty.
744
+ * - `reasoning.end` — closes the block.
745
+ * - `reasoning.opaque` — ONLY when `providerData.encrypted_content` is present:
746
+ * the OpenAI ZDR (`store:false`) stateless-replay blob (spec §8.2/§10.4),
747
+ * `kind:"ciphertext"`, with `itemId` carrying the `rs_…` id again (REPLAY-
748
+ * LOAD-BEARING — `reduce()`'s `reasoning.opaque` handler sets `block.itemId`
749
+ * from it, spec §4 row for `reasoning.opaque`).
750
+ *
751
+ * `id`/`itemId` reuse the `rs_…` item id (falling back to a fixed placeholder
752
+ * only in the defensive case the id is absent — mirrors the original T5 port,
753
+ * commit c1f6f71, since deleted unported until this task).
754
+ *
755
+ * `reasoningStart`/`reasoningOpaque` carry `itemId`, which the StreamAssembler
756
+ * sugar methods do not expose a parameter for (only `reasoningDelta`/
757
+ * `reasoningEnd` are used via sugar) — `a.emit()` is the documented base
758
+ * primitive for exactly this case (StreamAssembler docstring: "guarantees no
759
+ * AgClosedEventType is ever unreachable").
760
+ *
761
+ * Mirrors `driveMessageOutputCreated`/`tool_output`: assumes the response is
762
+ * already open (every response always opens via `response.created` before any
763
+ * run-item can arrive) rather than calling `ensureResponseOpen()` — reopening
764
+ * here would risk a phantom turn on a late arrival. If `msgId` is undefined
765
+ * (response already closed) this degrades gracefully — but NOT to a bare no-op
766
+ * when there is something REPLAY-LOAD-BEARING to lose: a plain summary-text-only
767
+ * late arrival has nothing irrecoverable to drop (the reasoning block itself
768
+ * never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
769
+ * correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
770
+ * is exactly the kind of payload Tenet 6 exists for — silently dropping it here
771
+ * was a genuine loss (review finding on M48). Mirrors `ext.openai.late-citations`
772
+ * (M22) exactly: route it through the lossless vendor channel instead of the bare
773
+ * return.
774
+ */
775
+ function driveReasoningItemCreated(item) {
776
+ if (msgId === undefined) {
777
+ // response already closed — see doc above.
778
+ const lateEncrypted = item.providerData?.encrypted_content;
779
+ if (typeof lateEncrypted === "string" && lateEncrypted.length > 0) {
780
+ a.emitExt("openai", "late-reasoning", {
781
+ ...(item.id !== undefined ? { itemId: item.id } : {}),
782
+ encryptedContent: lateEncrypted,
783
+ });
784
+ }
785
+ return;
786
+ }
787
+ const id = item.id ?? "reasoning";
788
+ const itemId = item.id;
789
+ const text = item.content.map((p) => p.text).join("");
790
+ a.emit({ type: "reasoning.start", id, messageId: msgId, ...(itemId !== undefined ? { itemId } : {}) });
791
+ if (text.length > 0)
792
+ a.reasoningDelta(id, msgId, text);
793
+ a.reasoningEnd(id, msgId);
794
+ const encrypted = item.providerData?.encrypted_content;
795
+ if (typeof encrypted === "string" && encrypted.length > 0) {
796
+ a.emit({
797
+ type: "reasoning.opaque",
798
+ id,
799
+ messageId: msgId,
800
+ kind: "ciphertext",
801
+ value: encrypted,
802
+ provider: "openai",
803
+ ...(itemId !== undefined ? { itemId } : {}),
804
+ });
805
+ }
806
+ }
807
+ /** Resolve the turn a pending tool call started under (Task 4b) — a plain
808
+ * lookup, no side effects; call BEFORE `a.toolDone` so its `turnId` field
809
+ * can be set explicitly (the result may land after a later round opened). */
810
+ function resolvePendingTurnId(callId) {
811
+ return turnIdByToolCallId.get(callId);
812
+ }
813
+ /**
814
+ * After `a.toolDone` has fired for `callId` under `doneTurnId`, clear the
815
+ * pending bookkeeping and — if the turn's pending set just drained to empty
816
+ * — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
817
+ * the `function_call` `tool_output` arm and the built-in Shell/Apply-Patch
818
+ * `tool_output` arm (playbook 2026-07-03 SDK-bump adaptation, Finding #1).
819
+ */
820
+ function drainPendingTool(callId, doneTurnId) {
821
+ if (doneTurnId === undefined)
822
+ return;
823
+ turnIdByToolCallId.delete(callId);
824
+ const pending = pendingToolsByTurn.get(doneTurnId);
825
+ if (pending === undefined)
826
+ return;
827
+ pending.delete(callId);
828
+ if (pending.size === 0) {
829
+ const stashed = stashedCloseByTurn.get(doneTurnId);
830
+ if (stashed !== undefined) {
831
+ // The pending set just drained — emit the deferred message.end +
832
+ // turn.done immediately after this tool.done, same push() batch
833
+ // (INV-MSG: the message must still be open when tool.done lands, so
834
+ // message.end waits for this too).
835
+ stashedCloseByTurn.delete(doneTurnId);
836
+ emitRoundClose(doneTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
837
+ }
838
+ }
839
+ }
840
+ /** True if any shell command in `entries` timed out or exited non-zero. */
841
+ function shellOutputHasError(entries) {
842
+ for (const entry of entries) {
843
+ if (entry.outcome.type === "timeout")
844
+ return true;
845
+ if (entry.outcome.type === "exit" && entry.outcome.exitCode !== 0)
846
+ return true;
847
+ }
848
+ return false;
849
+ }
850
+ /**
851
+ * Map a `tool_output` run-item whose `rawItem` is a Shell, Apply-Patch, or
852
+ * Computer-Use result (playbook 2026-07-03 SDK-bump adaptation, Finding #1;
853
+ * `computer_call_result` added by the fixture-drift ratchet finding, same
854
+ * date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
855
+ * (a bare string / content-part union) — `shell_call_output.output` is an
856
+ * ARRAY of per-command `{stdout,stderr,outcome}` records,
857
+ * `apply_patch_call_output.output` is an optional bare string,
858
+ * `computer_call_result.output` is a `{type:"computer_screenshot", data}`
859
+ * base64-PNG record — so they need their OWN mapping, not
860
+ * `toolOutputToAgBlocks` (that was the orphan hazard: calling the generic
861
+ * function_call mapper on these shapes silently produced EMPTY content,
862
+ * since none of these record types has the `.type === "text"` discriminant
863
+ * `toolOutputToAgBlocks` checks for).
864
+ */
865
+ function driveBuiltinToolOutput(rawItem) {
866
+ const toolCallId = rawItem.callId;
867
+ let content;
868
+ let outcome;
869
+ let structuredContent;
870
+ if (rawItem.type === "shell_call_output") {
871
+ content = [];
872
+ for (const entry of rawItem.output) {
873
+ const text = [entry.stdout, entry.stderr].filter((s) => s.length > 0).join("\n");
874
+ if (text.length > 0)
875
+ content.push({ type: "text", text });
876
+ }
877
+ outcome = shellOutputHasError(rawItem.output) ? "error" : "ok";
878
+ // The full per-command record (stdout/stderr/exit code) is lossy to
879
+ // collapse into text-only content — carry it verbatim as structuredContent
880
+ // too (mirrors the function_call path's ggui-cache-marker precedent).
881
+ structuredContent = JsonValue.parse(rawItem.output);
882
+ }
883
+ else if (rawItem.type === "computer_call_result") {
884
+ // spec §8 item 20's extended discriminant: the screenshot is base64 image
885
+ // data, not text — land it as an AgBlock `file` block (AgSource's
886
+ // `base64` arm) rather than dropping it via the text-only path.
887
+ content = [
888
+ {
889
+ type: "file",
890
+ source: { type: "base64", mediaType: "image/png", data: rawItem.output.data },
891
+ filename: "screenshot.png",
892
+ },
893
+ ];
894
+ // No status/error discriminant exists on this wire arm (unlike shell/apply-patch).
895
+ outcome = "ok";
896
+ }
897
+ else {
898
+ content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
899
+ outcome = rawItem.status === "failed" ? "error" : "ok";
900
+ }
901
+ const doneTurnId = resolvePendingTurnId(toolCallId);
902
+ a.toolDone({
903
+ toolCallId,
904
+ content,
905
+ outcome,
906
+ isError: outcome === "error",
907
+ ...(structuredContent !== undefined ? { structuredContent } : {}),
908
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
909
+ });
910
+ drainPendingTool(toolCallId, doneTurnId);
911
+ }
912
+ /** Synthesize `name` for the built-in discriminants that carry none on the
913
+ * wire (§8 quirk) — `shell_call`/`apply_patch_call`/`computer_call` have no
914
+ * `name` field at all; `hosted_tool_call` already carries a real one. */
915
+ function builtinToolName(rawItem) {
916
+ if (rawItem.type === "shell_call")
917
+ return "builtin:shell";
918
+ if (rawItem.type === "apply_patch_call")
919
+ return "builtin:apply_patch";
920
+ if (rawItem.type === "computer_call")
921
+ return "builtin:computer";
922
+ return rawItem.name;
923
+ }
924
+ /** Parse a JSON-string tool argument at the deserialization boundary,
925
+ * degrading gracefully (Tenet 6) rather than throwing on malformed input —
926
+ * mirrors `response.function_call_arguments.done`'s established degrade
927
+ * path (audit M46). */
928
+ function parseJsonArguments(itemId, raw) {
929
+ if (raw === undefined || raw.length === 0)
930
+ return {};
931
+ try {
932
+ return JsonValue.parse(JSON.parse(raw));
933
+ }
934
+ catch {
935
+ a.emitExt("openai", "unparsed", { itemId: itemId ?? null, arguments: raw });
936
+ return {};
937
+ }
938
+ }
939
+ /**
940
+ * Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
941
+ * built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
942
+ * — playbook 2026-07-03 SDK-bump adaptation, Finding #1; `computer_call`
943
+ * added by the fixture-drift ratchet finding, same date). Unlike
944
+ * `function_call` (whose tool-start rides the raw `response.output_item.
945
+ * added` stream — the authoritative source, canonical model A1), this
946
+ * run-item wrapper is the SOLE source for these four: `shell_call`/
947
+ * `apply_patch_call`/`computer_call` carry no per-fragment argument-delta
948
+ * stream on this seam (no equivalent of
949
+ * `response.function_call_arguments.delta` exists for them — the whole
950
+ * action/operation arrives complete on this one wrapper), and
951
+ * `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
952
+ * an agents-core-internal umbrella normalized only at this run-item layer).
953
+ * `ensureResponseOpen()` mirrors the raw function_call path's treatment
954
+ * (both are tool-START signals expected EARLY in a round, unlike the
955
+ * LATE-arriving `tool_output`/`message_output_created` run-items this file
956
+ * already documents) — residual ordering risk if a future capture shows
957
+ * otherwise is flagged in the adaptation report, not silently assumed away.
958
+ *
959
+ * `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
960
+ * result arrives via a LATER `tool_output` run-item, same Task-4b
961
+ * deferred-round-close discipline as `function_call`) — registered via
962
+ * `registerPendingTool`. `hosted_tool_call` is different: OpenAI's hosted
963
+ * tools execute server-side within the SAME model turn, so the item is
964
+ * already resolved (`output` present) by the time this wrapper streams —
965
+ * `tool.start` + `tool.done` fire together from this ONE event (see its own
966
+ * doc) — no pending registration.
967
+ */
968
+ function driveBuiltinToolCalled(rawItem) {
969
+ ensureResponseOpen();
970
+ if (msgId === undefined)
971
+ return; // unreachable post-ensure; satisfies narrowing
972
+ const toolCallId = rawItem.type === "hosted_tool_call" ? (rawItem.id ?? rawItem.name) : rawItem.callId;
973
+ const name = builtinToolName(rawItem);
974
+ a.toolStart({
975
+ toolCallId,
976
+ name,
977
+ ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
978
+ messageId: msgId,
979
+ });
980
+ const input = rawItem.type === "shell_call"
981
+ ? JsonValue.parse(rawItem.action)
982
+ : rawItem.type === "apply_patch_call"
983
+ ? JsonValue.parse(rawItem.operation)
984
+ : rawItem.type === "computer_call"
985
+ ? JsonValue.parse(rawItem.actions ?? rawItem.action ?? {})
986
+ : parseJsonArguments(rawItem.id, rawItem.arguments);
987
+ a.toolArgsDelta(toolCallId, JSON.stringify(input));
988
+ a.toolArgsAssembled(toolCallId, input);
989
+ if (rawItem.type === "hosted_tool_call") {
990
+ const content = rawItem.output !== undefined && rawItem.output.length > 0 ? [{ type: "text", text: rawItem.output }] : [];
991
+ a.toolDone({ toolCallId, content, outcome: "ok" });
992
+ return;
993
+ }
994
+ registerPendingTool(toolCallId);
995
+ }
996
+ /**
997
+ * Resolve the correlation id for a `tool_search_call`/`tool_search_output`
998
+ * pair — matches agents-core 0.12.0's own id-fallback chain exactly
999
+ * (`dist/tooling.mjs`'s `getToolSearchProviderCallId`/`getToolSearchMatchKey`:
1000
+ * `providerData.call_id ?? providerData.callId ?? call_id ?? callId ?? id`),
1001
+ * with providerData fields checked FIRST. Stops short of the SDK's blind FIFO
1002
+ * positional fallback (used by the real runtime only when NEITHER a field NOR
1003
+ * `id` resolves on EITHER side of a pairing — not something this per-event
1004
+ * facet can safely replicate: blindly popping the oldest pending call would
1005
+ * risk silently correlating two UNRELATED tool_search calls with no supporting
1006
+ * id at all). Returns undefined when genuinely unresolvable — the caller
1007
+ * degrades to `ext.openai.unparsed` rather than fabricating a correlation id
1008
+ * (Tenet 6).
1009
+ */
1010
+ function resolveToolSearchCallId(rawItem) {
1011
+ const providerData = rawItem.providerData;
1012
+ if (isJsonObject(providerData)) {
1013
+ if (typeof providerData.call_id === "string" && providerData.call_id.length > 0)
1014
+ return providerData.call_id;
1015
+ if (typeof providerData.callId === "string" && providerData.callId.length > 0)
1016
+ return providerData.callId;
1017
+ }
1018
+ if (typeof rawItem.call_id === "string" && rawItem.call_id.length > 0)
1019
+ return rawItem.call_id;
1020
+ if (typeof rawItem.callId === "string" && rawItem.callId.length > 0)
1021
+ return rawItem.callId;
1022
+ if (typeof rawItem.id === "string" && rawItem.id.length > 0)
1023
+ return rawItem.id;
1024
+ return undefined;
1025
+ }
1026
+ /**
1027
+ * Map a `tool_search_called` run-item (fixture-drift ratchet disposition,
1028
+ * 2026-07-03 — the manifest's four `tool_search_*` entries flip from
1029
+ * `carried` to `handled`). A DEDICATED event name, not a `tool_called`
1030
+ * reuse (see `OpenAIToolSearchCalledEvent`'s doc) — this run-item wrapper
1031
+ * is the SOLE tool-start source (no raw-stream literal exists for it, same
1032
+ * rationale as `hosted_tool_call`/shell/apply-patch/computer). `arguments`
1033
+ * (`z.ZodUnknown`) is carried through verbatim like `computer_call`'s
1034
+ * `action`/`actions` (never JSON.parsed — it is not a JSON STRING like
1035
+ * `FunctionCallItem.arguments`). Registers as a PENDING tool (Task 4b
1036
+ * discipline) — the paired `tool_search_output_created` typically lands in
1037
+ * the SAME step (server-hosted execution, or synchronously-resolved client
1038
+ * execution — see the file header's wire-truth citations), but if the
1039
+ * call's execution can't be resolved this turn (no client `toolSearchTool`
1040
+ * configured and no immediate hosted-server output), it may never arrive —
1041
+ * the existing INV-FLUSH stream-truncation handling degrades that exactly
1042
+ * like any other unresolved pending tool call, no special-casing needed.
1043
+ */
1044
+ function driveToolSearchCalled(rawItem) {
1045
+ ensureResponseOpen();
1046
+ if (msgId === undefined)
1047
+ return; // unreachable post-ensure; satisfies narrowing
1048
+ const toolCallId = resolveToolSearchCallId(rawItem);
1049
+ if (toolCallId === undefined) {
1050
+ // Genuinely unresolvable correlation id — never fabricate one (Tenet 6).
1051
+ a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
1052
+ return;
1053
+ }
1054
+ a.toolStart({
1055
+ toolCallId,
1056
+ name: "builtin:tool_search",
1057
+ ...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
1058
+ messageId: msgId,
1059
+ });
1060
+ const input = JsonValue.parse(rawItem.arguments ?? {});
1061
+ a.toolArgsDelta(toolCallId, JSON.stringify(input));
1062
+ a.toolArgsAssembled(toolCallId, input);
1063
+ registerPendingTool(toolCallId);
1064
+ }
1065
+ /**
1066
+ * Map a `tool_search_output_created` run-item — the paired completion (see
1067
+ * `OpenAIToolSearchOutputItem`'s doc). `tools` is a structured retrieval
1068
+ * listing (tool references/definitions), never natural-language text —
1069
+ * carried verbatim as a single AgBlock `data` block (the spec's escape
1070
+ * hatch for structured non-text tool content) rather than inventing a text
1071
+ * rendering with no wire precedent; this is ALREADY full-fidelity (no lossy
1072
+ * collapse occurs, unlike `shell_call_output`'s stdout/stderr join), so no
1073
+ * separate `structuredContent` duplicate is needed. No error discriminant
1074
+ * exists on this wire's free-form `status` string — mirrors
1075
+ * `computer_call_result`'s identical precedent: every occurrence maps to
1076
+ * `outcome:"ok"`.
1077
+ */
1078
+ function driveToolSearchOutput(rawItem) {
1079
+ const toolCallId = resolveToolSearchCallId(rawItem);
1080
+ if (toolCallId === undefined) {
1081
+ a.emitExt("openai", "unparsed", { name: "tool_search_output_created", item: JsonValue.parse(rawItem) });
1082
+ return;
1083
+ }
1084
+ const content = [{ type: "data", name: "tool_search_results", data: JsonValue.parse(rawItem.tools) }];
1085
+ const doneTurnId = resolvePendingTurnId(toolCallId);
1086
+ a.toolDone({
1087
+ toolCallId,
1088
+ content,
1089
+ outcome: "ok",
1090
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
1091
+ });
1092
+ drainPendingTool(toolCallId, doneTurnId);
1093
+ }
1094
+ /**
1095
+ * Map the synthetic `__host_error__` sentinel (host feeds it on
1096
+ * `MaxTurnsExceededError`) to a terminal `turn.error{code, message, usage}`.
1097
+ * - A response turn is OPEN → close THAT turn (end streams, close message,
1098
+ * closeTurnError) so the error lands on the well-formed open turn.
1099
+ * - NO turn open (max_turns fired after the last response already completed) →
1100
+ * open a FRESH terminal turn via `ensureResponseOpen()` (which emits a
1101
+ * `turn.start` + `message.start` — `closeTurnError` alone does NOT synthesize
1102
+ * `turn.start`, so a bare close would leave a malformed start-less turn),
1103
+ * close its message, then closeTurnError. Either way the error is emitted on
1104
+ * a turn that has a `turn.start`.
1105
+ */
1106
+ function driveHostError(event) {
1107
+ ensureResponseOpen();
1108
+ if (turnId === undefined)
1109
+ return; // unreachable post-ensure; satisfies narrowing
1110
+ endOpenStreamsAndCloseMessage();
1111
+ a.closeTurnError(turnId, {
1112
+ message: event.message,
1113
+ code: event.code,
1114
+ ...(event.usage !== undefined ? { usage: event.usage } : {}),
1115
+ });
1116
+ resetResponseState();
1117
+ }
1118
+ /** Drive the engine from one (already-narrowed) OpenAIStreamEvent. */
1119
+ function drive(event) {
1120
+ if (event.type === "__host_error__") {
1121
+ driveHostError(event);
1122
+ return;
1123
+ }
1124
+ if (event.type === "run_item_stream_event") {
1125
+ // Widened reference for the switch's `default` arm — see OpenAIRunItemEvent's
1126
+ // docstring (Task 3, audit M48).
1127
+ const runItemEvent = event;
1128
+ switch (event.name) {
1129
+ case "tool_output": {
1130
+ const rawItem = event.item.rawItem;
1131
+ // Finding #1 (critical) + the fixture-drift ratchet's
1132
+ // computer_call_result finding: Shell/Apply-Patch/Computer-Use
1133
+ // results do NOT share `OpenAIFunctionCallResultItem.output`'s shape
1134
+ // — see `driveBuiltinToolOutput`'s doc for why the generic path
1135
+ // below is wrong for them (the orphan-hazard this adaptation fixes).
1136
+ if (rawItem.type === "shell_call_output" ||
1137
+ rawItem.type === "apply_patch_call_output" ||
1138
+ rawItem.type === "computer_call_result") {
1139
+ driveBuiltinToolOutput(rawItem);
1140
+ return;
1141
+ }
1142
+ // Authoritative tool-result source (canonical model, A1). Drives toolDone
1143
+ // with content + structuredContent (the ggui cache marker — see
1144
+ // `extractStructuredContent`'s doc for the two peer-supported homes and
1145
+ // the playbook 2026-07-03 wire-truth findings behind them).
1146
+ const outcome = rawItem.status === "incomplete" ? "error" : "ok";
1147
+ const content = toolOutputToAgBlocks(rawItem.output);
1148
+ const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
1149
+ // Task 4b: resolve the OWNING turn explicitly (this result may land
1150
+ // after a later round has opened, so the engine's #lastTurn backfill
1151
+ // could misattribute it) and pass it through so toolDone binds to the
1152
+ // correct — possibly already-closed-pending-this-result — turn.
1153
+ const doneTurnId = resolvePendingTurnId(rawItem.callId);
1154
+ a.toolDone({
1155
+ toolCallId: rawItem.callId,
1156
+ content,
1157
+ outcome,
1158
+ isError: rawItem.status === "incomplete",
1159
+ ...(structuredContent !== undefined ? { structuredContent } : {}),
1160
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
1161
+ });
1162
+ drainPendingTool(rawItem.callId, doneTurnId);
1163
+ return;
1164
+ }
1165
+ case "message_output_created":
1166
+ // CITATIONS SUPPLEMENT only — the text already streamed from the raw delta
1167
+ // (canonical model, A1). Records refusal + emits citation blocks; no text.
1168
+ driveMessageOutputCreated(event.item.rawItem);
1169
+ return;
1170
+ case "tool_called": {
1171
+ const rawItem = event.item.rawItem;
1172
+ if (rawItem.type === "function_call") {
1173
+ // IGNORED — superseded by model:response.output_item.added, which is
1174
+ // the authoritative tool-start source (canonical model, A1
1175
+ // §"Spike Findings").
1176
+ return;
1177
+ }
1178
+ // Finding #1 (critical): Shell / Apply-Patch / Hosted-tool built-ins
1179
+ // — this run-item wrapper (not the raw stream) is the SOLE tool-start
1180
+ // source for these three (see `driveBuiltinToolCalled`'s doc).
1181
+ driveBuiltinToolCalled(rawItem);
1182
+ return;
1183
+ }
1184
+ case "tool_search_called":
1185
+ // Fixture-drift ratchet disposition (2026-07-03) — a DEDICATED
1186
+ // event name (not a `tool_called` reuse). See
1187
+ // `driveToolSearchCalled`'s doc for the full lifecycle rationale.
1188
+ driveToolSearchCalled(event.item.rawItem);
1189
+ return;
1190
+ case "tool_search_output_created":
1191
+ driveToolSearchOutput(event.item.rawItem);
1192
+ return;
1193
+ case "reasoning_item_created":
1194
+ // SOLE source for reasoning content — see driveReasoningItemCreated's
1195
+ // docstring for the single-sourcing rationale (Task 3, audit M48).
1196
+ driveReasoningItemCreated(event.item.rawItem);
1197
+ return;
1198
+ case "handoff_requested": {
1199
+ // Task 3 (audit M48 review, Finding 1) handoff mapping — FALSE-PREMISE
1200
+ // FIX. The original mapping (a standalone `handoff` event) assumed the
1201
+ // wire carried no completion signal for a handoff, so a `subagentStart`
1202
+ // that MUST be matched by `subagentDone` couldn't be used safely (an
1203
+ // unmatched one gets INV-FLUSH-aborted as `turn.abort{reason:"stream-
1204
+ // truncated"}`, audit M21 — misrepresenting a genuinely-completed
1205
+ // handoff). That premise was FALSE: `handoff_occurred` IS the
1206
+ // completion signal (verified against the installed `@openai/agents`
1207
+ // 0.2.1 peer dep's `events.d.ts` — `RunItemStreamEventName` includes
1208
+ // `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
1209
+ // bracket the transfer with `subagentStart` now / `subagentDone` at the
1210
+ // matching `handoff_occurred` below (FIFO via `openHandoffs`).
1211
+ //
1212
+ // `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
1213
+ // LLM call produced this handoff call — NOT the transfer target (see
1214
+ // `OpenAIHandoffRequestedEvent`'s doc: the target isn't resolved until
1215
+ // the handoff actually executes). There is therefore no target identity
1216
+ // to carry at this point — an earlier draft of this fix assumed there
1217
+ // was; corrected. `StreamAssembler.subagentStart`'s SUGAR signature also
1218
+ // carries neither `agentId` nor `agentName` params (only the
1219
+ // `subagent.start` AgEvent SCHEMA arm does, agjson.ts — a live-only
1220
+ // field the fold doesn't land on `AgTurnRecord` either, reduce.ts) and
1221
+ // this fix's commit scope excludes core/stream-assembler.ts, so identity
1222
+ // rides the follow-up bare `handoff` event instead (spec §4 bare-noun
1223
+ // EVENT carve-out), emitted once it's actually known — paired with
1224
+ // `subagentDone` in the `handoff_occurred` case below.
1225
+ const ordinal = ++handoffOrdinal;
1226
+ const handoffTurnId = `turn_handoff_${ordinal}`;
1227
+ const parentTurnId = lastTopLevelTurnId ?? threadId;
1228
+ openHandoffs.push({ turnId: handoffTurnId, parentTurnId });
1229
+ a.subagentStart(handoffTurnId, parentTurnId);
1230
+ return;
1231
+ }
1232
+ case "handoff_occurred": {
1233
+ // Task 3 (audit M48 review, Finding 1) — the REAL completion signal.
1234
+ // Both agent identities are finally known here (`RunHandoffOutputItem.
1235
+ // sourceAgent`/`targetAgent`), so this is where the identity-carrying
1236
+ // `handoff` event fires (mirrors the ORIGINAL mapping's shape —
1237
+ // `kind:"transfer"` + `toAgentName` — just correctly timed to when the
1238
+ // data actually exists on the wire). `fromAgentId`/`toAgentId` are still
1239
+ // never fabricated from a name (no agent-id concept exists anywhere on
1240
+ // this seam, unlike google-adk's per-message agentId/agentName).
1241
+ const item = event.item;
1242
+ const open = openHandoffs.shift(); // FIFO — see openHandoffs' doc.
1243
+ if (open !== undefined)
1244
+ a.subagentDone(open.turnId, open.parentTurnId);
1245
+ // Defensive orphan (no open bracket — e.g. a resumed/truncated stream):
1246
+ // still emit the `handoff` event losslessly rather than dropping the
1247
+ // now-known identity (Tenet 6) — it just doesn't close anything.
1248
+ a.emit({
1249
+ type: "handoff",
1250
+ kind: "transfer",
1251
+ toAgentName: item.targetAgent.name,
1252
+ });
1253
+ return;
1254
+ }
1255
+ case "tool_approval_requested": {
1256
+ // Task 3 (audit M48): a human-in-the-loop approval gate on a pending
1257
+ // tool call. `askId` mirrors the `approval_${callId}` convention already
1258
+ // established by the google-adk facet's `requestedToolConfirmations` arm
1259
+ // (index.ts:653) for the same `kind:"approval"` semantics. The M26
1260
+ // paused-fold discipline (surfacing this on the turn's `outcome.paused`)
1261
+ // is ADK-scoped for this batch — `hitl.ask` is LIVE-ONLY on the fold
1262
+ // (reduce.ts R9: no accumulator mutation), so emitting the ask alone is
1263
+ // complete; the host/turn-close owns any pause semantics.
1264
+ const item = event.item.rawItem;
1265
+ a.emit({
1266
+ type: "hitl.ask",
1267
+ askId: `approval_${item.callId}`,
1268
+ kind: "approval",
1269
+ toolCallId: item.callId,
1270
+ });
1271
+ return;
1272
+ }
1273
+ default:
1274
+ // A genuinely-unknown run-item name (a real-wire RunItemStreamEventName
1275
+ // this fixture-contract union does not declare — e.g.
1276
+ // `mcp_approval_requested`, `mcp_list_tools`). The OUTER guard
1277
+ // (`isOpenAIStreamEvent`) validates only `typeof name === "string"` (file
1278
+ // header), so an unrecognised name reaches here at runtime despite
1279
+ // `event`'s TS-narrowed `never` type (every literal this union declares
1280
+ // is handled by a case above). Route losslessly per Tenet 6 — this is the
1281
+ // file's stated ext.openai.unparsed convention for genuinely-unknown
1282
+ // run-items (audit M48; previously a silent no-op here).
1283
+ a.emitExt("openai", "unparsed", {
1284
+ name: runItemEvent.name,
1285
+ item: JsonValue.parse(runItemEvent.item),
1286
+ });
1287
+ return;
1288
+ }
1289
+ }
1290
+ // raw_model_stream_event — `data` is the Agents SDK ResponseStreamEvent union.
1291
+ const data = event.data;
1292
+ switch (data.type) {
1293
+ case "model": {
1294
+ // The verbatim openai-node Responses event rides in `event` (snake_case).
1295
+ driveRawResponsesEvent(data.event);
1296
+ return;
1297
+ }
1298
+ // IGNORE the SDK-flattened duplicates (canonical model):
1299
+ // response_started — duplicate of model:response.created
1300
+ // output_text_delta — flattened duplicate of model:response.output_text.delta
1301
+ // response_done — duplicate of model:response.completed
1302
+ case "response_started":
1303
+ case "output_text_delta":
1304
+ case "response_done":
1305
+ default:
1306
+ return;
1307
+ }
1308
+ }
1309
+ return {
1310
+ push(native) {
1311
+ if (!isOpenAIStreamEvent(native)) {
1312
+ // Graceful guard (Tenet 6): route a genuinely unrecognisable payload through
1313
+ // the lossless vendor channel rather than throwing. Nest under `native` so a
1314
+ // payload carrying its own `type` key does NOT clobber the event type.
1315
+ a.emitExt("openai", "unparsed", { native });
1316
+ return a.drain();
1317
+ }
1318
+ drive(native);
1319
+ return a.drain();
1320
+ },
1321
+ flush() {
1322
+ // Close any dangling open response (e.g. a stream that ended before
1323
+ // response.completed) — unrelated to Task 4b: that round never reached a
1324
+ // native close signal at all, so it has no stashed closeTurnDone.
1325
+ if (turnId !== undefined)
1326
+ closeResponse();
1327
+ // Task 4b: emit any still-stashed closes BEFORE delegating to the engine's
1328
+ // flush. Each stashed round genuinely completed on the wire — a tool
1329
+ // result that never arrives must not swallow that close (message.end +
1330
+ // turn.done both replay here, verbatim, in the order INV-MSG requires).
1331
+ for (const [tid, stashed] of stashedCloseByTurn) {
1332
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
1333
+ }
1334
+ stashedCloseByTurn.clear();
1335
+ // Flush the engine's dangling open messages (I7).
1336
+ return a.flush();
1337
+ },
1338
+ };
1339
+ }
1340
+ //# sourceMappingURL=index.js.map