@silverprotocol/openai-agents 0.12.5 → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -3
- package/dist/index.d.ts +58 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +931 -173
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +1005 -193
package/dist/index.js
CHANGED
|
@@ -94,7 +94,145 @@
|
|
|
94
94
|
*/
|
|
95
95
|
import { AgMeta, AgProviderMeta, AgUsage, JsonValue, StreamAssembler, withAtomicPush, toJsonValueSafeWithIssues, } from "@silverprotocol/core";
|
|
96
96
|
/**
|
|
97
|
-
*
|
|
97
|
+
* The refusal parts of a terminal event's `response.output`, in wire order —
|
|
98
|
+
* the source of a round's refusal text when no refusal event streamed
|
|
99
|
+
* (see "Refusal text" in the normalizer). Deserialization boundary: a
|
|
100
|
+
* non-array output, a non-message member and a part whose `refusal` is not a
|
|
101
|
+
* string are skipped; an empty id is no id.
|
|
102
|
+
*/
|
|
103
|
+
function terminalRefusalParts(output) {
|
|
104
|
+
const out = [];
|
|
105
|
+
if (!Array.isArray(output))
|
|
106
|
+
return out;
|
|
107
|
+
for (const member of output) {
|
|
108
|
+
if (!isJsonObject(member) || member.type !== "message")
|
|
109
|
+
continue;
|
|
110
|
+
const content = member.content;
|
|
111
|
+
if (!Array.isArray(content))
|
|
112
|
+
continue;
|
|
113
|
+
const itemId = typeof member.id === "string" && member.id.length > 0 ? member.id : undefined;
|
|
114
|
+
const phase = vendorPhase(member.phase);
|
|
115
|
+
for (const part of content) {
|
|
116
|
+
if (!isJsonObject(part) || part.type !== "refusal" || typeof part.refusal !== "string")
|
|
117
|
+
continue;
|
|
118
|
+
out.push({
|
|
119
|
+
...(itemId !== undefined ? { itemId } : {}),
|
|
120
|
+
...(phase !== undefined ? { phase } : {}),
|
|
121
|
+
text: part.refusal,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Did the model refuse in this response? True when any `message` member of a
|
|
129
|
+
* terminal event's `response.output` carries a `refusal` content part. On the
|
|
130
|
+
* live wire the `message_output_created` run-item lands AFTER the terminal
|
|
131
|
+
* event, so the terminal output is where the round's own refusal is known when
|
|
132
|
+
* the round closes. Absent/non-array output, or no refusal part, ⇒ false.
|
|
133
|
+
*/
|
|
134
|
+
function terminalHasRefusal(output) {
|
|
135
|
+
if (!Array.isArray(output))
|
|
136
|
+
return false;
|
|
137
|
+
for (const member of output) {
|
|
138
|
+
if (!isJsonObject(member) || member.type !== "message")
|
|
139
|
+
continue;
|
|
140
|
+
const content = member.content;
|
|
141
|
+
if (!Array.isArray(content))
|
|
142
|
+
continue;
|
|
143
|
+
for (const part of content) {
|
|
144
|
+
if (isJsonObject(part) && part.type === "refusal")
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The media type of an image_generation result (base64): the item's
|
|
152
|
+
* `output_format` when it carries one (openai-node 7.22.0 declares it
|
|
153
|
+
* optional and nullable on ImageGenerationCall), else read from the image's
|
|
154
|
+
* own signature, else `application/octet-stream`.
|
|
155
|
+
*/
|
|
156
|
+
function imageResultMediaType(providerData, data) {
|
|
157
|
+
const format = providerData?.output_format;
|
|
158
|
+
if (format === "png" || format === "jpeg" || format === "webp" || format === "gif")
|
|
159
|
+
return `image/${format}`;
|
|
160
|
+
if (data.startsWith("iVBORw0KGgo"))
|
|
161
|
+
return "image/png";
|
|
162
|
+
if (data.startsWith("/9j/"))
|
|
163
|
+
return "image/jpeg";
|
|
164
|
+
if (data.startsWith("UklGR"))
|
|
165
|
+
return "image/webp";
|
|
166
|
+
if (data.startsWith("R0lGOD"))
|
|
167
|
+
return "image/gif";
|
|
168
|
+
return "application/octet-stream";
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* The raw Responses output item types that @openai/agents 0.18.0 turns into a
|
|
172
|
+
* built-in call run-item keeping the item's id: agents-openai's converter
|
|
173
|
+
* (openaiResponsesConverter.mjs `convertToOutputItem`) maps the hosted kinds
|
|
174
|
+
* to a `hosted_tool_call` with `id: item.id`, and keeps shell, apply-patch,
|
|
175
|
+
* computer, program and tool-search calls under their own type. agents-core
|
|
176
|
+
* streams each as a `tool_called` / `tool_search_called` run-item AFTER the
|
|
177
|
+
* response's `response.completed` (it streams a response's step items after
|
|
178
|
+
* the raw loop, run.mjs:1935). `local_shell_call` converts to an unknown item
|
|
179
|
+
* and never streams as a call, so it is not listed.
|
|
180
|
+
*/
|
|
181
|
+
const BUILTIN_OUTPUT_ITEM_TYPES = new Set([
|
|
182
|
+
"web_search_call",
|
|
183
|
+
"file_search_call",
|
|
184
|
+
"image_generation_call",
|
|
185
|
+
"code_interpreter_call",
|
|
186
|
+
"mcp_list_tools",
|
|
187
|
+
"mcp_approval_request",
|
|
188
|
+
"mcp_call",
|
|
189
|
+
"computer_call",
|
|
190
|
+
"shell_call",
|
|
191
|
+
"apply_patch_call",
|
|
192
|
+
"program",
|
|
193
|
+
"tool_search_call",
|
|
194
|
+
]);
|
|
195
|
+
/**
|
|
196
|
+
* The built-in calls a terminal event's `response.output` lists, in wire
|
|
197
|
+
* order (see {@link BUILTIN_OUTPUT_ITEM_TYPES}). Deserialization boundary: a
|
|
198
|
+
* non-array output, a non-object member and a member with no non-empty string
|
|
199
|
+
* id are skipped.
|
|
200
|
+
*/
|
|
201
|
+
function terminalBuiltinItems(output) {
|
|
202
|
+
const out = [];
|
|
203
|
+
if (!Array.isArray(output))
|
|
204
|
+
return out;
|
|
205
|
+
for (const member of output) {
|
|
206
|
+
if (!isJsonObject(member))
|
|
207
|
+
continue;
|
|
208
|
+
const type = member.type;
|
|
209
|
+
const id = member.id;
|
|
210
|
+
if (typeof type !== "string" || !BUILTIN_OUTPUT_ITEM_TYPES.has(type))
|
|
211
|
+
continue;
|
|
212
|
+
if (typeof id !== "string" || id.length === 0)
|
|
213
|
+
continue;
|
|
214
|
+
out.push({ id, type });
|
|
215
|
+
}
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
/** The ids of the `message` items a terminal event's `response.output` lists,
|
|
219
|
+
* in wire order (a non-object member or a member with no non-empty string
|
|
220
|
+
* id is skipped). */
|
|
221
|
+
function terminalMessageIds(output) {
|
|
222
|
+
const out = [];
|
|
223
|
+
if (!Array.isArray(output))
|
|
224
|
+
return out;
|
|
225
|
+
for (const member of output) {
|
|
226
|
+
if (!isJsonObject(member) || member.type !== "message")
|
|
227
|
+
continue;
|
|
228
|
+
const id = member.id;
|
|
229
|
+
if (typeof id === "string" && id.length > 0)
|
|
230
|
+
out.push(id);
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Reasoning from the terminal output: extract the reasoning items from a terminal event's `response.output`.
|
|
98
236
|
* This — not `response.output_item.done` — is the replayable source: OpenAI
|
|
99
237
|
* re-encrypts `encrypted_content` per stage (live, echo-gpt6sol natives [4] vs
|
|
100
238
|
* [21]: two different blobs for one `rs_`), and only the terminal blob is the
|
|
@@ -106,7 +244,7 @@ import { AgMeta, AgProviderMeta, AgUsage, JsonValue, StreamAssembler, withAtomic
|
|
|
106
244
|
* Deserialization boundary: a non-array `output`, a non-object member, a member
|
|
107
245
|
* with no string `id`, and a non-string summary `text` are all skipped (an
|
|
108
246
|
* id-less reasoning item stays with the run-item path, which already degrades
|
|
109
|
-
* it losslessly). Absent/empty output ⇒ `[]` ⇒ byte-identical
|
|
247
|
+
* it losslessly). Absent/empty output ⇒ `[]` ⇒ nothing is emitted from it (byte-identical).
|
|
110
248
|
*/
|
|
111
249
|
function terminalReasoningItems(output) {
|
|
112
250
|
if (!Array.isArray(output))
|
|
@@ -167,7 +305,7 @@ export function mapFinishReason(reason) {
|
|
|
167
305
|
}
|
|
168
306
|
}
|
|
169
307
|
/**
|
|
170
|
-
*
|
|
308
|
+
* The finish-reason raw companion (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; spec
|
|
171
309
|
* 89c57db): the `turn.done` finish fields for a native reason. `finishReason`
|
|
172
310
|
* is `mapFinishReason(reason)`; `finishReasonRaw` — the native value byte for
|
|
173
311
|
* byte — rides along ONLY when that mapping fell back ("other"/"unknown") AND a
|
|
@@ -224,45 +362,70 @@ function mapUsage(usage) {
|
|
|
224
362
|
u.costUsd = usage.cost;
|
|
225
363
|
return u;
|
|
226
364
|
}
|
|
227
|
-
// ───
|
|
228
|
-
// `partText` is the source output_text part's text
|
|
229
|
-
// cited substring from the char-offset indices
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
365
|
+
// ─── output_text annotations → AgCitation ──────────────────────────────────
|
|
366
|
+
// In `splitAnnotations`, `partText` is the source output_text part's text
|
|
367
|
+
// string, used to extract the cited substring from the char-offset indices
|
|
368
|
+
// carried by the annotation.
|
|
369
|
+
/**
|
|
370
|
+
* An output_text part's annotations, raw. agents-openai 0.18.0's converter
|
|
371
|
+
* nests every part field but `type` and `text` under `providerData`
|
|
372
|
+
* (openaiResponsesConverter.mjs `convertToMessageContentItem`), so on the real
|
|
373
|
+
* wire they are `part.providerData.annotations` (15 of 17 recorded parts carry
|
|
374
|
+
* them there, 0 at the top level); a top-level `annotations` is read first.
|
|
375
|
+
* Anything but an array is no annotations.
|
|
376
|
+
*/
|
|
377
|
+
function partAnnotations(part) {
|
|
378
|
+
const top = part.annotations;
|
|
379
|
+
const nested = part.providerData?.annotations;
|
|
380
|
+
const raw = Array.isArray(top) ? top : Array.isArray(nested) ? nested : undefined;
|
|
381
|
+
if (raw === undefined)
|
|
382
|
+
return [];
|
|
383
|
+
const parsed = JsonValue.parse(raw);
|
|
384
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Split a part's raw annotations. A `url_citation` with a string `url` maps
|
|
388
|
+
* to an AgCitation; every other annotation (file_citation,
|
|
389
|
+
* container_file_citation, file_path, …) has no citation target and stays
|
|
390
|
+
* verbatim in `unmapped`, for the `ext.openai.late-citations` carry (SPEC:965:
|
|
391
|
+
* never dropped silently).
|
|
392
|
+
*/
|
|
393
|
+
function splitAnnotations(raw, partText) {
|
|
394
|
+
const citations = [];
|
|
395
|
+
const unmapped = [];
|
|
396
|
+
for (const ann of raw) {
|
|
397
|
+
if (!isJsonObject(ann) || ann.type !== "url_citation" || typeof ann.url !== "string") {
|
|
398
|
+
unmapped.push(ann);
|
|
399
|
+
continue;
|
|
256
400
|
}
|
|
257
|
-
//
|
|
401
|
+
// Extract the cited substring from the part text when both offsets are present
|
|
402
|
+
// and valid. Fall back to "" when any guard condition fails.
|
|
403
|
+
const startIdx = typeof ann.start_index === "number" ? ann.start_index : undefined;
|
|
404
|
+
const endIdx = typeof ann.end_index === "number" ? ann.end_index : undefined;
|
|
405
|
+
const citedText = startIdx !== undefined && endIdx !== undefined && startIdx >= 0 && endIdx <= partText.length
|
|
406
|
+
? partText.slice(startIdx, endIdx)
|
|
407
|
+
: "";
|
|
408
|
+
const cit = {
|
|
409
|
+
kind: "url",
|
|
410
|
+
url: ann.url,
|
|
411
|
+
citedText,
|
|
412
|
+
indexFrame: "response",
|
|
413
|
+
};
|
|
414
|
+
if (typeof ann.title === "string")
|
|
415
|
+
cit.title = ann.title;
|
|
416
|
+
if (startIdx !== undefined)
|
|
417
|
+
cit.startIndex = startIdx;
|
|
418
|
+
if (endIdx !== undefined)
|
|
419
|
+
cit.endIndex = endIdx;
|
|
420
|
+
citations.push(cit);
|
|
258
421
|
}
|
|
259
|
-
return
|
|
422
|
+
return { ...(citations.length > 0 ? { citations } : {}), unmapped };
|
|
260
423
|
}
|
|
261
424
|
// ─── optional 0.14.0 wire fields → providerMetadata (spec §2) ─────────────────
|
|
262
425
|
// Wire names ride verbatim at the top level (the claude facet's wrapper-carry
|
|
263
426
|
// precedent — AgProviderMeta imposes no key namespacing). Drops undefined
|
|
264
427
|
// values; an ALL-absent input yields undefined, never an empty metadata object.
|
|
265
|
-
/**
|
|
428
|
+
/** The phase marker: an OpenAI message `phase` as a vendor MARKER — a non-empty
|
|
266
429
|
* string, verbatim — or `undefined`. openai-node types it
|
|
267
430
|
* `'commentary' | 'final_answer' | null`; null and "" carry no marker, so they
|
|
268
431
|
* yield neither a `providerMetadata.phase` carry nor an ext.openai.late-phase
|
|
@@ -271,7 +434,7 @@ function mapAnnotationsToCitations(annotations, partText) {
|
|
|
271
434
|
function vendorPhase(value) {
|
|
272
435
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
273
436
|
}
|
|
274
|
-
/**
|
|
437
|
+
/** SPEC §8.0 item 27 (draft.4): the first-class `phase` for an OpenAI
|
|
275
438
|
* vendor marker — `"commentary"` → `"interim"`; "final_answer", absent and
|
|
276
439
|
* every other value → `undefined` (a vendor spelling is never copied into
|
|
277
440
|
* `phase`; it stays verbatim in `providerMetadata`). */
|
|
@@ -308,7 +471,7 @@ function isJsonObject(v) {
|
|
|
308
471
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
309
472
|
}
|
|
310
473
|
/**
|
|
311
|
-
* Extract `structuredContent` (
|
|
474
|
+
* Extract `structuredContent` (a reference client's cache-marker channel, spec §2.1/§4)
|
|
312
475
|
* from a `tool_output` run-item's wrapper fields. Playbook 2026-07-03
|
|
313
476
|
* follow-up — the ORIGINAL extraction (feat 0969469) assumed `wrapperOutput`
|
|
314
477
|
* would be an object keyed by `.structuredContent`; a live capture
|
|
@@ -393,11 +556,11 @@ function extractStructuredContent(wrapperOutput, customData) {
|
|
|
393
556
|
return undefined;
|
|
394
557
|
}
|
|
395
558
|
/**
|
|
396
|
-
* workspace#21 (
|
|
559
|
+
* workspace#21 (a reference host's ask): the MCP tool result's `_meta`, riding the same
|
|
397
560
|
* host-convention `customData` channel as `structuredContent` (SPEC.md:340) —
|
|
398
561
|
* agents-core 0.18.0 hands it to `MCPServer.customDataExtractor` as
|
|
399
562
|
* `context.resultMeta` (`dist/mcpUtil.d.ts`:41, `result._meta ?? content._meta`
|
|
400
|
-
* at `dist/mcp.mjs`:700);
|
|
563
|
+
* at `dist/mcp.mjs`:700); a reference host's worker and this repo's capture agent return it
|
|
401
564
|
* as `customData._meta`. It is a host/protocol annotation (MCP-Apps `ui.*`), so
|
|
402
565
|
* it rides the tool-result block's own `_meta` VERBATIM (SPEC.md:338; §8.0
|
|
403
566
|
* no-drop). Ruled option A on 2026-09-23. A non-object `_meta`
|
|
@@ -456,7 +619,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
456
619
|
let responseId; // real response.id once known
|
|
457
620
|
// Open text streams keyed by Responses item_id (textStart once per id).
|
|
458
621
|
const openTextStreams = new Set();
|
|
459
|
-
//
|
|
622
|
+
// Reasoning-block state (reasoning from the terminal output). `openReasoning`: rs_ id → the message id its
|
|
460
623
|
// block opened in (at `output_item.added{reasoning}`), awaiting its fill from
|
|
461
624
|
// the terminal output; per-response (cleared by `resetResponseState`).
|
|
462
625
|
// `filledReasoning`: every rs_ id whose block has been filled — normalizer-
|
|
@@ -464,14 +627,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
464
627
|
// response closed and must dedupe against it (single source per rs_ id).
|
|
465
628
|
const openReasoning = new Map();
|
|
466
629
|
const filledReasoning = new Set();
|
|
467
|
-
//
|
|
630
|
+
// Phase state (the phase read at the raw add). `pendingPhase`: message item id → the phase its raw
|
|
468
631
|
// `output_item.added` announced, awaiting that item's `text.start`
|
|
469
632
|
// (per-response). `carriedPhase`: item id → the phase that rode its
|
|
470
633
|
// `text.start` — normalizer-lifetime, because the run-item it retires
|
|
471
634
|
// `ext.openai.late-phase` against lands AFTER the response closed.
|
|
472
635
|
const pendingPhase = new Map();
|
|
473
636
|
const carriedPhase = new Map();
|
|
474
|
-
//
|
|
637
|
+
// The first-class phase (draft.4): text stream ids whose `text.start` already set the
|
|
475
638
|
// first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
|
|
476
639
|
// `text.end` fields learned for a round close that is STASHED (deferred until
|
|
477
640
|
// its tool results land) — consumed by `emitRoundClose`.
|
|
@@ -524,16 +687,19 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
524
687
|
let lastTopLevelTurnId;
|
|
525
688
|
// Per-invoke ordinal for the synthetic subagent turnId (`turn_handoff_<n>`).
|
|
526
689
|
let handoffOrdinal = 0;
|
|
690
|
+
// Per-invoke ordinal for a derived id (INV-BLOCK, SPEC:767) when a native
|
|
691
|
+
// item carries no id the facet can key on.
|
|
692
|
+
let derivedOrdinal = 0;
|
|
527
693
|
// Open handoff brackets, keyed by the transfer call's callId (paired turnId
|
|
528
694
|
// + the SAME parentTurnId `subagentStart` used — `subagentDone` must replay
|
|
529
695
|
// it verbatim, mirroring the claude-agent-sdk facet's paired start/done
|
|
530
|
-
// convention).
|
|
696
|
+
// convention). Matched by callId,
|
|
531
697
|
// not FIFO, because agents-core <=0.8.0 opens a bracket for EVERY transfer
|
|
532
698
|
// the model calls but runs only the first: a bracket closes at
|
|
533
699
|
// `handoff_occurred` for its own call, or at that call's `tool_output` (the
|
|
534
700
|
// handoff never ran).
|
|
535
701
|
const openHandoffs = [];
|
|
536
|
-
/**
|
|
702
|
+
/** Remove and return the open bracket for `callId`, if any. */
|
|
537
703
|
function takeOpenHandoff(callId) {
|
|
538
704
|
const i = openHandoffs.findIndex((h) => h.callId === callId);
|
|
539
705
|
if (i === -1)
|
|
@@ -550,12 +716,90 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
550
716
|
// The engine accumulates for downstream use; `.done.arguments` carries the full
|
|
551
717
|
// string so argBuffers is primarily for the fallback path.
|
|
552
718
|
const instanceArgBuffers = new Map();
|
|
553
|
-
// Refusal tracking (T5c
|
|
554
|
-
// `
|
|
555
|
-
//
|
|
556
|
-
// the
|
|
557
|
-
//
|
|
719
|
+
// Refusal tracking (T5c). Set when a refusal event streams, or when a
|
|
720
|
+
// `message_output_created` run-item carries a `refusal` content part BEFORE
|
|
721
|
+
// its response's terminal event (a synthetic order); the terminal arm also
|
|
722
|
+
// reads the refusal from its own `response.output` (`terminalHasRefusal`),
|
|
723
|
+
// which is the live order: the run-item lands after the close. Cleared on
|
|
724
|
+
// every response close and at every `response.created`, so a late run-item's
|
|
725
|
+
// refusal never reaches the next round.
|
|
558
726
|
let pendingRefusal = false;
|
|
727
|
+
// Refusal text (SPEC §8.0 graceful degradation: a native event the
|
|
728
|
+
// normalizer can map is never dropped silently). A `refusal` content part's
|
|
729
|
+
// text is a `text` block in the round's message, id `<item id>:refusal` (the
|
|
730
|
+
// same item can also carry an `output_text` part, whose block id is the item
|
|
731
|
+
// id), its `text.start` carrying `providerMetadata.type: "refusal"`, the
|
|
732
|
+
// part's own wire discriminant and the marker a replay reads to send a
|
|
733
|
+
// refusal part back, beside the item's `phase` marker as an output_text
|
|
734
|
+
// block carries it. ONE source per round:
|
|
735
|
+
// - the raw `response.refusal.delta` / `.done` events, when any arrived;
|
|
736
|
+
// - else the refusal part itself, from whichever comes first of the
|
|
737
|
+
// terminal output (read before the round closes) and a
|
|
738
|
+
// `message_output_created` run-item that lands while the round is open.
|
|
739
|
+
// A run-item that lands after the close, with no copy emitted, rides
|
|
740
|
+
// `ext.openai.late-message` (the message is sealed).
|
|
741
|
+
// The source is chosen per round, not matched per item id: a run-item's ids
|
|
742
|
+
// can be a different id space from the raw `item_id`s (the OpenRouter
|
|
743
|
+
// surface mints `msg_tmp_` run-item ids), where an id match would copy the
|
|
744
|
+
// text twice.
|
|
745
|
+
// `openRefusalBlocks`: this response's refusal blocks not yet ended;
|
|
746
|
+
// `refusalBlocks`: every refusal block this response opened (a repeated
|
|
747
|
+
// `.done` never reopens one); `refusalTextEmitted`: the round has its
|
|
748
|
+
// refusal text, cleared at `response.created` only, because the run-item
|
|
749
|
+
// that reads it lands after the round closed. `refusalCarriedPhase`: item id
|
|
750
|
+
// → the phase marker its refusal block carried (normalizer-lifetime, like
|
|
751
|
+
// `carriedPhase`, which stays the output_text blocks' own record).
|
|
752
|
+
const openRefusalBlocks = new Set();
|
|
753
|
+
const refusalBlocks = new Set();
|
|
754
|
+
let refusalTextEmitted = false;
|
|
755
|
+
const refusalCarriedPhase = new Map();
|
|
756
|
+
/** The item's vendor phase marker for a refusal block's `text.start`: the one
|
|
757
|
+
* announced at `output_item.added`, else the one an output_text block of the
|
|
758
|
+
* same item already carried. */
|
|
759
|
+
function refusalItemPhase(itemId) {
|
|
760
|
+
return pendingPhase.get(itemId) ?? carriedPhase.get(itemId);
|
|
761
|
+
}
|
|
762
|
+
/** A refusal block id not yet used this response, for the whole-part sources
|
|
763
|
+
* (an id-less item keys on the message id). */
|
|
764
|
+
function freshRefusalBlockId(itemId, mId) {
|
|
765
|
+
const base = `${itemId ?? mId}:refusal`;
|
|
766
|
+
let id = base;
|
|
767
|
+
for (let k = 2; refusalBlocks.has(id); k++)
|
|
768
|
+
id = `${base}:${k}`;
|
|
769
|
+
return id;
|
|
770
|
+
}
|
|
771
|
+
/** Open refusal block `blockId` in message `mId`. The phase marker rides
|
|
772
|
+
* `text.start` as on an output_text block (the first-class `phase:"interim"`
|
|
773
|
+
* for "commentary"), and is recorded as carried for the late run-item. */
|
|
774
|
+
function openRefusalBlock(blockId, mId, phase, itemId) {
|
|
775
|
+
const startMeta = openaiProviderMeta({ phase, type: "refusal" });
|
|
776
|
+
const interim = interimPhase(phase);
|
|
777
|
+
a.textStart(blockId, mId, {
|
|
778
|
+
role: "assistant",
|
|
779
|
+
...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
|
|
780
|
+
...(interim !== undefined ? { phase: interim } : {}),
|
|
781
|
+
});
|
|
782
|
+
if (phase !== undefined && itemId !== undefined)
|
|
783
|
+
refusalCarriedPhase.set(itemId, phase);
|
|
784
|
+
openRefusalBlocks.add(blockId);
|
|
785
|
+
refusalBlocks.add(blockId);
|
|
786
|
+
refusalTextEmitted = true;
|
|
787
|
+
}
|
|
788
|
+
/** A whole refusal part as one block: start, the text as one delta (none for
|
|
789
|
+
* an empty text), end. */
|
|
790
|
+
function emitWholeRefusal(blockId, mId, text, phase, itemId) {
|
|
791
|
+
openRefusalBlock(blockId, mId, phase, itemId);
|
|
792
|
+
if (text.length > 0)
|
|
793
|
+
a.textDelta(blockId, mId, text, { cumulative: false });
|
|
794
|
+
a.textEnd(blockId, mId);
|
|
795
|
+
openRefusalBlocks.delete(blockId);
|
|
796
|
+
}
|
|
797
|
+
/** End every refusal block the stream left open (no `.done` before the close). */
|
|
798
|
+
function endOpenRefusalBlocks(mId) {
|
|
799
|
+
for (const blockId of openRefusalBlocks)
|
|
800
|
+
a.textEnd(blockId, mId);
|
|
801
|
+
openRefusalBlocks.clear();
|
|
802
|
+
}
|
|
559
803
|
// ── Task 4b: defer a round's close past its pending tool results ───────────
|
|
560
804
|
// (SPEC §5.0 INV-MSG). On the real wire, the `tool_output` run-item arrives
|
|
561
805
|
// AFTER `response.completed` — closing at native-close time would put a later
|
|
@@ -573,20 +817,125 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
573
817
|
* Register `callId` as pending a `tool.done` under the CURRENT open turn
|
|
574
818
|
* (Task 4b). Shared by the raw `response.output_item.added` function_call
|
|
575
819
|
* path and the built-in Shell/Apply-Patch `tool_called` synthesis path
|
|
576
|
-
* (
|
|
820
|
+
* (the 2026-07-03 SDK-bump adaptation) — both start a call
|
|
577
821
|
* whose result arrives via a LATER `tool_output` run-item. No-ops if no turn
|
|
578
822
|
* is open (defensive; every caller already calls `ensureResponseOpen()` first).
|
|
579
823
|
*/
|
|
580
824
|
function registerPendingTool(callId) {
|
|
581
|
-
|
|
825
|
+
registerPendingToolFor(turnId, callId);
|
|
826
|
+
}
|
|
827
|
+
/** Register `callId` as pending a `tool.done` under round `tid`. */
|
|
828
|
+
function registerPendingToolFor(tid, callId) {
|
|
829
|
+
if (tid === undefined)
|
|
582
830
|
return;
|
|
583
|
-
let pending = pendingToolsByTurn.get(
|
|
831
|
+
let pending = pendingToolsByTurn.get(tid);
|
|
584
832
|
if (pending === undefined) {
|
|
585
833
|
pending = new Set();
|
|
586
|
-
pendingToolsByTurn.set(
|
|
834
|
+
pendingToolsByTurn.set(tid, pending);
|
|
587
835
|
}
|
|
588
836
|
pending.add(callId);
|
|
589
|
-
turnIdByToolCallId.set(callId,
|
|
837
|
+
turnIdByToolCallId.set(callId, tid);
|
|
838
|
+
}
|
|
839
|
+
// ── Built-in round attach ───────────────────────────────────────────────────
|
|
840
|
+
// agents-core streams a response's built-in call run-items (`tool_called`,
|
|
841
|
+
// `tool_search_called`) after its `response.completed`, so the round has
|
|
842
|
+
// already reached its terminal when they land. A round whose terminal
|
|
843
|
+
// `response.output` lists a built-in call (see BUILTIN_OUTPUT_ITEM_TYPES)
|
|
844
|
+
// defers its close as §8.0 item 14 defers a round for its pending tool
|
|
845
|
+
// results, and each late run-item attaches to THAT round's turn and message
|
|
846
|
+
// (never a turn opened for it). The close is released:
|
|
847
|
+
// - when every listed call has its run-item and every pending result has
|
|
848
|
+
// landed (`maybeReleaseRound`);
|
|
849
|
+
// - at the next `response.created`, when the round still waits only on
|
|
850
|
+
// listed calls whose run-item never streamed (agents-core can suppress
|
|
851
|
+
// one), so the new response keeps its own turn; those calls stop being
|
|
852
|
+
// the round's;
|
|
853
|
+
// - at flush, per INV-FLUSH (2).
|
|
854
|
+
// A listed `mcp_approval_request` becomes a pending call of its round when
|
|
855
|
+
// its `tool_called` lands, and its answer (`mcp_approval_response`) closes
|
|
856
|
+
// it; with no answer, the round flushes paused naming its ask (INV-FLUSH
|
|
857
|
+
// (2)). `listedBuiltinsByTurn`: round → listed item ids still waiting.
|
|
858
|
+
// `builtinTurnByItemId`: listed item id → its round.
|
|
859
|
+
// `seenBuiltinItemIds`: built-in items whose run-item already landed (one
|
|
860
|
+
// that lands before its terminal, a synthetic order), so the terminal never
|
|
861
|
+
// lists them.
|
|
862
|
+
const listedBuiltinsByTurn = new Map();
|
|
863
|
+
const builtinTurnByItemId = new Map();
|
|
864
|
+
const seenBuiltinItemIds = new Set();
|
|
865
|
+
// Approval requests an `mcp_approval_response` has closed in this invoke.
|
|
866
|
+
const answeredRequests = new Set();
|
|
867
|
+
/** List round `tid`'s built-in calls (those whose run-item has not landed). */
|
|
868
|
+
/** List round `tid`'s built-in calls whose run-item has not landed. When
|
|
869
|
+
* it lists any, the round's `message` items are listed too, so their
|
|
870
|
+
* `message_output_created` (and the citations it carries) lands while the
|
|
871
|
+
* round's close is still deferred. */
|
|
872
|
+
function listBuiltins(tid, items, messageIds) {
|
|
873
|
+
const ids = [];
|
|
874
|
+
for (const item of items) {
|
|
875
|
+
if (seenBuiltinItemIds.has(item.id))
|
|
876
|
+
continue;
|
|
877
|
+
ids.push(item.id);
|
|
878
|
+
builtinTurnByItemId.set(item.id, tid);
|
|
879
|
+
}
|
|
880
|
+
if (ids.length === 0)
|
|
881
|
+
return ids;
|
|
882
|
+
for (const id of messageIds) {
|
|
883
|
+
if (seenBuiltinItemIds.has(id))
|
|
884
|
+
continue;
|
|
885
|
+
ids.push(id);
|
|
886
|
+
builtinTurnByItemId.set(id, tid);
|
|
887
|
+
}
|
|
888
|
+
listedBuiltinsByTurn.set(tid, new Set(ids));
|
|
889
|
+
return ids;
|
|
890
|
+
}
|
|
891
|
+
/** The stashed round a late built-in run-item belongs to: the round whose
|
|
892
|
+
* terminal listed `key`, else, when no response is open, the invoke's last
|
|
893
|
+
* round if its close is still stashed (a run-item its terminal did not
|
|
894
|
+
* list). Undefined when neither holds. */
|
|
895
|
+
function lateBuiltinRound(key) {
|
|
896
|
+
const listedTid = key !== undefined ? builtinTurnByItemId.get(key) : undefined;
|
|
897
|
+
const tid = listedTid ?? (turnId === undefined ? lastTopLevelTurnId : undefined);
|
|
898
|
+
if (tid === undefined)
|
|
899
|
+
return undefined;
|
|
900
|
+
const stashed = stashedCloseByTurn.get(tid);
|
|
901
|
+
return stashed !== undefined ? { tid, mId: stashed.msgId } : undefined;
|
|
902
|
+
}
|
|
903
|
+
/** The listed item `key` has what it waited for: drop it, and release its
|
|
904
|
+
* round if nothing else keeps the round open. */
|
|
905
|
+
function drainListedBuiltin(key) {
|
|
906
|
+
if (key === undefined)
|
|
907
|
+
return;
|
|
908
|
+
const tid = builtinTurnByItemId.get(key);
|
|
909
|
+
if (tid === undefined)
|
|
910
|
+
return;
|
|
911
|
+
const listed = listedBuiltinsByTurn.get(tid);
|
|
912
|
+
if (listed === undefined || !listed.delete(key))
|
|
913
|
+
return;
|
|
914
|
+
maybeReleaseRound(tid);
|
|
915
|
+
}
|
|
916
|
+
/** Release round `tid`'s stashed close when no pending result and no listed
|
|
917
|
+
* built-in call keeps it open. */
|
|
918
|
+
function maybeReleaseRound(tid) {
|
|
919
|
+
const stashed = stashedCloseByTurn.get(tid);
|
|
920
|
+
if (stashed === undefined)
|
|
921
|
+
return;
|
|
922
|
+
if ((pendingToolsByTurn.get(tid)?.size ?? 0) > 0)
|
|
923
|
+
return;
|
|
924
|
+
if ((listedBuiltinsByTurn.get(tid)?.size ?? 0) > 0)
|
|
925
|
+
return;
|
|
926
|
+
stashedCloseByTurn.delete(tid);
|
|
927
|
+
listedBuiltinsByTurn.delete(tid);
|
|
928
|
+
emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
|
|
929
|
+
}
|
|
930
|
+
/** At a new `response.created`: every round still waiting on listed calls
|
|
931
|
+
* whose run-item never streamed stops waiting on them, and is released if
|
|
932
|
+
* no pending result keeps it open. */
|
|
933
|
+
function releaseListedAtNextResponse() {
|
|
934
|
+
for (const [tid, listed] of [...listedBuiltinsByTurn]) {
|
|
935
|
+
listed.clear();
|
|
936
|
+
listedBuiltinsByTurn.delete(tid);
|
|
937
|
+
maybeReleaseRound(tid);
|
|
938
|
+
}
|
|
590
939
|
}
|
|
591
940
|
// Stashed close for a turn whose pending set was non-empty at close time,
|
|
592
941
|
// keyed by turnId. Consumed the moment its pending set drains (emitted right
|
|
@@ -599,7 +948,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
599
948
|
* whichever values are live right now (immediate path) or were captured at
|
|
600
949
|
* defer time (drain path) — same three calls either way.
|
|
601
950
|
*/
|
|
602
|
-
/**
|
|
951
|
+
/** Is `streamId`'s text.end still pending in a STASHED round close
|
|
603
952
|
* (a deferred tool round), i.e. not yet emitted? */
|
|
604
953
|
function isStashedTextStream(streamId) {
|
|
605
954
|
for (const stashed of stashedCloseByTurn.values()) {
|
|
@@ -610,10 +959,17 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
610
959
|
}
|
|
611
960
|
function endStashedTextStreams(mId, textStreamIds) {
|
|
612
961
|
for (const streamId of textStreamIds) {
|
|
613
|
-
//
|
|
614
|
-
|
|
962
|
+
// Citations and a phase learned while this close sat stashed ride its
|
|
963
|
+
// text.end, in the live path's field order.
|
|
964
|
+
const f = stashedEndFields.get(streamId);
|
|
615
965
|
stashedEndFields.delete(streamId);
|
|
616
|
-
a.textEnd(streamId, mId,
|
|
966
|
+
a.textEnd(streamId, mId, f === undefined
|
|
967
|
+
? undefined
|
|
968
|
+
: {
|
|
969
|
+
...(f.citations !== undefined ? { citations: f.citations } : {}),
|
|
970
|
+
...(f.providerMetadata !== undefined ? { providerMetadata: f.providerMetadata } : {}),
|
|
971
|
+
...(f.phase !== undefined ? { phase: f.phase } : {}),
|
|
972
|
+
});
|
|
617
973
|
}
|
|
618
974
|
}
|
|
619
975
|
function emitRoundClose(tid, mId, textStreamIds, fields) {
|
|
@@ -659,6 +1015,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
659
1015
|
for (const [tid, stashed] of stashedCloseByTurn)
|
|
660
1016
|
releaseDeferredClose(tid, stashed);
|
|
661
1017
|
stashedCloseByTurn.clear();
|
|
1018
|
+
listedBuiltinsByTurn.clear();
|
|
662
1019
|
}
|
|
663
1020
|
/**
|
|
664
1021
|
* Close the round now, unless `tid`'s pending-tool set is non-empty — in
|
|
@@ -668,9 +1025,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
668
1025
|
* immediately via `endOpenStreamsAndCloseMessage` — an errored round's
|
|
669
1026
|
* pending results are moot, by design).
|
|
670
1027
|
*/
|
|
671
|
-
function finishOrDeferRound(tid, mId, textStreamIds, fields) {
|
|
1028
|
+
function finishOrDeferRound(tid, mId, textStreamIds, fields, listing = { builtins: [], messageIds: [] }) {
|
|
1029
|
+
const listed = listBuiltins(tid, listing.builtins, listing.messageIds);
|
|
672
1030
|
const pending = pendingToolsByTurn.get(tid);
|
|
673
|
-
if (pending !== undefined && pending.size > 0) {
|
|
1031
|
+
if ((pending !== undefined && pending.size > 0) || listed.length > 0) {
|
|
674
1032
|
stashedCloseByTurn.set(tid, { msgId: mId, openTextStreamIds: [...textStreamIds], fields });
|
|
675
1033
|
return;
|
|
676
1034
|
}
|
|
@@ -682,7 +1040,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
682
1040
|
* somehow absent (defensive — the spike confirms the id is always present at start).
|
|
683
1041
|
* Returns the close-once key (the real response.id, else the synthesized turnId),
|
|
684
1042
|
* or `undefined` when the response has already been closed (caller must no-op).
|
|
685
|
-
* `model` (
|
|
1043
|
+
* `model` (the per-message model) rides `message.start.model` — only the authoritative
|
|
686
1044
|
* `response.created` open passes it; a defensive open never invents one.
|
|
687
1045
|
*/
|
|
688
1046
|
function ensureResponseOpen(respId, model) {
|
|
@@ -734,7 +1092,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
734
1092
|
a.openTurn(opened, threadId);
|
|
735
1093
|
return { turnId: opened, messageId: `${callId}:result` };
|
|
736
1094
|
}
|
|
737
|
-
// Approve-all (
|
|
1095
|
+
// Approve-all (pinned 2026-09-24): the resuming invoke can
|
|
738
1096
|
// replay SEVERAL results before its response. While the resume turn is
|
|
739
1097
|
// open with no assistant message yet (turnId set, msgId unset — a state
|
|
740
1098
|
// only this helper creates), each further result joins THAT turn as its
|
|
@@ -767,11 +1125,13 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
767
1125
|
if (key !== undefined)
|
|
768
1126
|
closedResponses.add(key);
|
|
769
1127
|
openTextStreams.clear();
|
|
770
|
-
//
|
|
1128
|
+
// An rs_ block opened but never filled (e.g. `response.failed`) stays
|
|
771
1129
|
// as the spec's own unsealed-block outcome (INV-FLUSH (3)); forget it so a
|
|
772
1130
|
// late run-item for it takes the existing `late-reasoning` degrade.
|
|
773
1131
|
openReasoning.clear();
|
|
774
1132
|
pendingPhase.clear();
|
|
1133
|
+
openRefusalBlocks.clear();
|
|
1134
|
+
refusalBlocks.clear();
|
|
775
1135
|
turnId = undefined;
|
|
776
1136
|
msgId = undefined;
|
|
777
1137
|
responseId = undefined;
|
|
@@ -786,6 +1146,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
786
1146
|
if (msgId !== undefined) {
|
|
787
1147
|
for (const streamId of openTextStreams)
|
|
788
1148
|
a.textEnd(streamId, msgId);
|
|
1149
|
+
endOpenRefusalBlocks(msgId);
|
|
789
1150
|
a.closeMessage(msgId);
|
|
790
1151
|
}
|
|
791
1152
|
resetResponseState();
|
|
@@ -794,8 +1155,16 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
794
1155
|
function driveRawResponsesEvent(ev) {
|
|
795
1156
|
switch (ev.type) {
|
|
796
1157
|
case "response.created": {
|
|
1158
|
+
// A new response: a refusal recorded by a late run-item belongs to the
|
|
1159
|
+
// response before it, never to this one; so does its refusal text.
|
|
1160
|
+
pendingRefusal = false;
|
|
1161
|
+
refusalTextEmitted = false;
|
|
1162
|
+
// A round still waiting only on listed built-in calls whose run-item
|
|
1163
|
+
// never streamed is released before this response's turn opens (see
|
|
1164
|
+
// "Built-in round attach").
|
|
1165
|
+
releaseListedAtNextResponse();
|
|
797
1166
|
// Authoritative turn open — the real response.id is present at start.
|
|
798
|
-
//
|
|
1167
|
+
// So is the resolved model id (JsonValue boundary: string-guarded).
|
|
799
1168
|
const rawModelId = ev.response.model;
|
|
800
1169
|
ensureResponseOpen(ev.response.id, typeof rawModelId === "string" && rawModelId.length > 0 ? rawModelId : undefined);
|
|
801
1170
|
return;
|
|
@@ -806,11 +1175,11 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
806
1175
|
return; // unreachable post-ensure; satisfies the narrowing
|
|
807
1176
|
if (!openTextStreams.has(ev.item_id)) {
|
|
808
1177
|
openTextStreams.add(ev.item_id);
|
|
809
|
-
//
|
|
1178
|
+
// The phase announced at output_item.added rides text.start
|
|
810
1179
|
// (R&D items 13+17, stage 1, ruled 2026-09-23; vercel parity c4f5981).
|
|
811
1180
|
const phase = pendingPhase.get(ev.item_id);
|
|
812
1181
|
const startMeta = openaiProviderMeta({ phase });
|
|
813
|
-
//
|
|
1182
|
+
// The first-class phase (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
|
|
814
1183
|
// the first delta ⇒ the first-class `phase` goes on text.start.
|
|
815
1184
|
const interim = interimPhase(phase);
|
|
816
1185
|
a.textStart(ev.item_id, msgId, {
|
|
@@ -830,7 +1199,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
830
1199
|
return;
|
|
831
1200
|
}
|
|
832
1201
|
case "response.output_text.done": {
|
|
833
|
-
// NO-OP
|
|
1202
|
+
// NO-OP: the citations carrier — `message_output_created` — is
|
|
834
1203
|
// the authoritative text-end source (it also reports refusal parts and
|
|
835
1204
|
// arrives with the annotated part, so closing here would emit `text.end`
|
|
836
1205
|
// BEFORE citations are known). The stream stays in `openTextStreams`;
|
|
@@ -839,8 +1208,38 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
839
1208
|
// `endOpenStreamsAndCloseMessage()` / `emitRoundClose()` do at native close.
|
|
840
1209
|
return;
|
|
841
1210
|
}
|
|
1211
|
+
case "response.refusal.delta": {
|
|
1212
|
+
// Refusal text streams like output_text (see "Refusal text"): the raw
|
|
1213
|
+
// refusal events are this round's source once any arrives.
|
|
1214
|
+
ensureResponseOpen();
|
|
1215
|
+
if (msgId === undefined)
|
|
1216
|
+
return; // unreachable post-ensure; satisfies the narrowing
|
|
1217
|
+
pendingRefusal = true;
|
|
1218
|
+
const blockId = `${ev.item_id}:refusal`;
|
|
1219
|
+
if (!refusalBlocks.has(blockId))
|
|
1220
|
+
openRefusalBlock(blockId, msgId, refusalItemPhase(ev.item_id), ev.item_id);
|
|
1221
|
+
a.textDelta(blockId, msgId, ev.delta, { cumulative: false });
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
case "response.refusal.done": {
|
|
1225
|
+
// Ends the part's block. With no delta before it, its `refusal` is the
|
|
1226
|
+
// whole text. A refusal part carries no annotations, so unlike
|
|
1227
|
+
// `response.output_text.done` nothing arrives later for its `text.end`.
|
|
1228
|
+
ensureResponseOpen();
|
|
1229
|
+
if (msgId === undefined)
|
|
1230
|
+
return; // unreachable post-ensure; satisfies the narrowing
|
|
1231
|
+
pendingRefusal = true;
|
|
1232
|
+
const blockId = `${ev.item_id}:refusal`;
|
|
1233
|
+
if (!refusalBlocks.has(blockId)) {
|
|
1234
|
+
emitWholeRefusal(blockId, msgId, ev.refusal, refusalItemPhase(ev.item_id), ev.item_id);
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
if (openRefusalBlocks.delete(blockId))
|
|
1238
|
+
a.textEnd(blockId, msgId);
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
842
1241
|
case "response.output_item.added": {
|
|
843
|
-
//
|
|
1242
|
+
// A reasoning item OPENS its block here — id only, the added event
|
|
844
1243
|
// carries no replayable content — so the block takes its wire position
|
|
845
1244
|
// ahead of the `fc_` it precedes (§5 block insertion order, SPEC:763;
|
|
846
1245
|
// §10 item 4's stateless loop replays `rs_` before its `fc_`). It is
|
|
@@ -853,7 +1252,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
853
1252
|
openReasoningBlock(rsId);
|
|
854
1253
|
return;
|
|
855
1254
|
}
|
|
856
|
-
//
|
|
1255
|
+
// A message item announces its `phase` here, BEFORE its first
|
|
857
1256
|
// text delta — record it for that item's `text.start`. Record only: no
|
|
858
1257
|
// response open, no emit, so an absent/null/non-string/empty phase is
|
|
859
1258
|
// byte-identical to a stream without this event.
|
|
@@ -957,11 +1356,22 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
957
1356
|
return; // unreachable post-ensure; satisfies narrowing
|
|
958
1357
|
if (msgId === undefined)
|
|
959
1358
|
return; // unreachable post-ensure; satisfies narrowing
|
|
960
|
-
//
|
|
1359
|
+
// Fill every reasoning block from THIS output (the replayable blob)
|
|
961
1360
|
// FIRST — before any branch below can emit message.end / turn.* (INV-MSG:
|
|
962
1361
|
// a reasoning.* event must never target a sealed message; core's reduce()
|
|
963
1362
|
// does not check that for reasoning.*, so the order is this facet's job).
|
|
964
1363
|
fillReasoningFromTerminalOutput(ev.response.output);
|
|
1364
|
+
// Refusal text (see "Refusal text"): with no refusal event in this
|
|
1365
|
+
// round, the terminal output's refusal parts are its source, emitted
|
|
1366
|
+
// now while the message is open (the run-item lands after the close).
|
|
1367
|
+
// Then any refusal block the stream left open ends here, before every
|
|
1368
|
+
// branch below closes the message.
|
|
1369
|
+
if (!refusalTextEmitted) {
|
|
1370
|
+
for (const part of terminalRefusalParts(ev.response.output)) {
|
|
1371
|
+
emitWholeRefusal(freshRefusalBlockId(part.itemId, msgId), msgId, part.text, part.phase, part.itemId);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
endOpenRefusalBlocks(msgId);
|
|
965
1375
|
// Snapshot before any deferral: `resetResponseState()` below always
|
|
966
1376
|
// clears these, but a deferred close needs them later (Task 4b).
|
|
967
1377
|
const currentTurnId = turnId;
|
|
@@ -969,6 +1379,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
969
1379
|
const textStreamIds = Array.from(openTextStreams);
|
|
970
1380
|
const reason = ev.response.incomplete_details?.reason;
|
|
971
1381
|
const usage = mapUsage(ev.response.usage);
|
|
1382
|
+
// The built-in calls (and, with them, the messages) this response
|
|
1383
|
+
// lists, whose run-items land after this event (see "Built-in round
|
|
1384
|
+
// attach").
|
|
1385
|
+
const listing = { builtins: terminalBuiltinItems(ev.response.output), messageIds: terminalMessageIds(ev.response.output) };
|
|
972
1386
|
// `status` is OPTIONAL upstream and its enum is OPEN ("clients must
|
|
973
1387
|
// accept additional values"), so it is read through `unknown` + a typeof
|
|
974
1388
|
// guard rather than trusted through the declared union — this is the
|
|
@@ -979,7 +1393,8 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
979
1393
|
const rawStatus = ev.response.status;
|
|
980
1394
|
const unsuccessfulStatus = typeof rawStatus === "string" && UNSUCCESSFUL_RESPONSE_STATUSES.has(rawStatus) ? rawStatus : undefined;
|
|
981
1395
|
// Decision tree (mirrors the canonical model, A1):
|
|
982
|
-
// refusal
|
|
1396
|
+
// refusal (in the terminal
|
|
1397
|
+
// output, or recorded) → closeTurnDone success, finishReason:"refusal"
|
|
983
1398
|
// content_filter → closeTurnDone error-outcome + safety signal
|
|
984
1399
|
// any other incomplete → closeTurnError{code:reason, usage}
|
|
985
1400
|
// completed, status failed/
|
|
@@ -990,12 +1405,12 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
990
1405
|
// ENTIRE close (message + turn) instead of emitting (INV-MSG).
|
|
991
1406
|
// closeTurnError does NOT defer (an errored round's pending results are
|
|
992
1407
|
// moot, by design) — it still closes the message immediately here.
|
|
993
|
-
if (pendingRefusal) {
|
|
1408
|
+
if (pendingRefusal || terminalHasRefusal(ev.response.output)) {
|
|
994
1409
|
finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
|
|
995
1410
|
outcome: { type: "success" },
|
|
996
1411
|
finishReason: "refusal",
|
|
997
1412
|
...(usage !== undefined ? { usage } : {}),
|
|
998
|
-
});
|
|
1413
|
+
}, listing);
|
|
999
1414
|
}
|
|
1000
1415
|
else if (reason === "content_filter") {
|
|
1001
1416
|
const safety = [{ category: "content_filter", blocked: true }];
|
|
@@ -1004,7 +1419,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1004
1419
|
...finishReasonFields(reason),
|
|
1005
1420
|
safety,
|
|
1006
1421
|
...(usage !== undefined ? { usage } : {}),
|
|
1007
|
-
});
|
|
1422
|
+
}, listing);
|
|
1008
1423
|
}
|
|
1009
1424
|
else if (ev.type === "response.incomplete") {
|
|
1010
1425
|
endOpenStreamsAndCloseMessage();
|
|
@@ -1049,10 +1464,10 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1049
1464
|
else {
|
|
1050
1465
|
finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
|
|
1051
1466
|
outcome: { type: "success" },
|
|
1052
|
-
//
|
|
1467
|
+
// An unmapped native reason also carries finishReasonRaw.
|
|
1053
1468
|
...finishReasonFields(reason),
|
|
1054
1469
|
...(usage !== undefined ? { usage } : {}),
|
|
1055
|
-
});
|
|
1470
|
+
}, listing);
|
|
1056
1471
|
}
|
|
1057
1472
|
resetResponseState();
|
|
1058
1473
|
return;
|
|
@@ -1072,7 +1487,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1072
1487
|
// message/code/usage (§4), so per §8.0 item 33 it rides verbatim in a
|
|
1073
1488
|
// carrier the §5 table folds, never as remedy data on the terminal: an
|
|
1074
1489
|
// adapter NOTICE message immediately BEFORE the closing turn.error, in
|
|
1075
|
-
// this turn (
|
|
1490
|
+
// this turn (remedy-shaped vendor data):
|
|
1076
1491
|
// message.start {role:"notice", noticeSource:"adapter"} →
|
|
1077
1492
|
// one text block, text = `detailed_explanation` verbatim (else
|
|
1078
1493
|
// error.message), text.start `_meta["openai/misalignment"]` = the
|
|
@@ -1129,34 +1544,74 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1129
1544
|
return;
|
|
1130
1545
|
}
|
|
1131
1546
|
// Duplicate raw families IGNORED per the canonical model:
|
|
1132
|
-
// response.output_text.done is its own no-op arm above
|
|
1547
|
+
// response.output_text.done is its own no-op arm above;
|
|
1133
1548
|
// response.output_item.done, response.in_progress, content_part.* are not
|
|
1134
1549
|
// authoritative sources.
|
|
1135
1550
|
default:
|
|
1136
1551
|
return;
|
|
1137
1552
|
}
|
|
1138
1553
|
}
|
|
1554
|
+
/**
|
|
1555
|
+
* A `message_output_created` run-item's refusal part (see "Refusal text").
|
|
1556
|
+
* - The round already has its refusal text (the raw events or the terminal
|
|
1557
|
+
* output): no second copy. The item's phase marker, if that block did
|
|
1558
|
+
* not carry it, rides `ext.openai.late-phase` (the block's `text.end` is
|
|
1559
|
+
* out: case (iii) of the output_text arm), once per item: an item that
|
|
1560
|
+
* also carries an output_text part leaves it to that part's arm.
|
|
1561
|
+
* - The round is open (a synthetic order): the part is the source.
|
|
1562
|
+
* - The round closed with no copy: the message is sealed, so the text rides
|
|
1563
|
+
* `ext.openai.late-message` with `partType: "refusal"`, anchored to the
|
|
1564
|
+
* round like the id-less late message.
|
|
1565
|
+
*/
|
|
1566
|
+
function driveRunItemRefusal(item, text) {
|
|
1567
|
+
const itemPhase = vendorPhase(item.phase);
|
|
1568
|
+
if (refusalTextEmitted) {
|
|
1569
|
+
if (item.id !== undefined &&
|
|
1570
|
+
itemPhase !== undefined &&
|
|
1571
|
+
refusalCarriedPhase.get(item.id) !== itemPhase &&
|
|
1572
|
+
!item.content.some((p) => p.type === "output_text")) {
|
|
1573
|
+
a.emitExt("openai", "late-phase", { itemId: item.id, phase: itemPhase });
|
|
1574
|
+
}
|
|
1575
|
+
return;
|
|
1576
|
+
}
|
|
1577
|
+
if (msgId !== undefined) {
|
|
1578
|
+
emitWholeRefusal(freshRefusalBlockId(item.id, msgId), msgId, text, itemPhase, item.id);
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
const anchor = turnId ?? lastTopLevelTurnId;
|
|
1582
|
+
a.emitExt("openai", "late-message", {
|
|
1583
|
+
text,
|
|
1584
|
+
partType: "refusal",
|
|
1585
|
+
...(item.id !== undefined ? { itemId: item.id } : {}),
|
|
1586
|
+
...(anchor !== undefined ? { forTurnId: anchor } : {}),
|
|
1587
|
+
...(itemPhase !== undefined ? { phase: itemPhase } : {}),
|
|
1588
|
+
});
|
|
1589
|
+
}
|
|
1139
1590
|
/** End any still-open text streams (defensive), then close the open message. */
|
|
1140
1591
|
function endOpenStreamsAndCloseMessage() {
|
|
1141
1592
|
if (msgId !== undefined) {
|
|
1142
1593
|
for (const streamId of openTextStreams)
|
|
1143
1594
|
a.textEnd(streamId, msgId);
|
|
1595
|
+
endOpenRefusalBlocks(msgId);
|
|
1144
1596
|
a.closeMessage(msgId);
|
|
1145
1597
|
}
|
|
1146
1598
|
}
|
|
1147
1599
|
/**
|
|
1148
1600
|
* Map a `message_output_created` run-item: the AUTHORITATIVE text-end +
|
|
1149
|
-
* citations source
|
|
1601
|
+
* citations source. The text itself already streamed from the raw
|
|
1150
1602
|
* `response.output_text.delta` path — this MUST NOT re-emit it — but the
|
|
1151
1603
|
* `output_text` part's annotations are only known here (they are not present on
|
|
1152
1604
|
* `response.output_text.done`), so THIS is where the matching open text stream
|
|
1153
1605
|
* actually closes: `a.textEnd(id, msgId, { citations })`, citations attached
|
|
1154
1606
|
* directly to the streamed block (never a duplicate id-less supplement). A
|
|
1155
|
-
* `refusal` part sets `pendingRefusal
|
|
1156
|
-
*
|
|
1607
|
+
* `refusal` part sets `pendingRefusal`, which counts only when the run-item
|
|
1608
|
+
* lands before its response's terminal event (a synthetic order). On the
|
|
1609
|
+
* live wire it lands after the close, and the terminal arm reads the round's
|
|
1610
|
+
* refusal from its own `response.output` (`terminalHasRefusal`). Its text is
|
|
1611
|
+
* a single-source fallback (`driveRunItemRefusal`, see "Refusal text").
|
|
1157
1612
|
*
|
|
1158
|
-
* Correlation (
|
|
1159
|
-
*
|
|
1613
|
+
* Correlation (id FIRST, FIFO fallback; the narration-phase rule, stage
|
|
1614
|
+
* 1): on the direct OpenAI wire the raw delta's `item_id` and the
|
|
1160
1615
|
* run-item's `rawItem.id` are the SAME id (all 8 openai corpus seeds), so the
|
|
1161
1616
|
* stream is matched by id — a completion can no longer land on an earlier
|
|
1162
1617
|
* part's stream when two are open. Only when the id is unknown to
|
|
@@ -1174,7 +1629,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1174
1629
|
* annotations, though, they are NOT yet lost anywhere else — silently dropping
|
|
1175
1630
|
* them here would violate Tenet 6. Route them losslessly through the facet's
|
|
1176
1631
|
* existing unparsed/ext convention instead: `ext.openai.late-citations` carrying
|
|
1177
|
-
* the run-item id + the raw annotations array verbatim
|
|
1632
|
+
* the run-item id + the raw annotations array verbatim.
|
|
1178
1633
|
* A part with no annotations has nothing to lose — the plain `continue` stays.
|
|
1179
1634
|
*
|
|
1180
1635
|
* ID-LESS SYNTHESIZED MESSAGE (agents-core ≥0.13.2): `errorHandlers.
|
|
@@ -1203,9 +1658,23 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1203
1658
|
* never a duplicated or corrupted core stream.
|
|
1204
1659
|
*/
|
|
1205
1660
|
function driveMessageOutputCreated(item) {
|
|
1661
|
+
if (item.id !== undefined)
|
|
1662
|
+
seenBuiltinItemIds.add(item.id);
|
|
1663
|
+
driveMessageParts(item);
|
|
1664
|
+
// A listed message has landed; its round may now close (see "Built-in
|
|
1665
|
+
// round attach"), with any citations stashed above on its text.end.
|
|
1666
|
+
drainListedBuiltin(item.id);
|
|
1667
|
+
}
|
|
1668
|
+
/** The per-part body of {@link driveMessageOutputCreated} (see its doc). */
|
|
1669
|
+
function driveMessageParts(item) {
|
|
1206
1670
|
for (const part of item.content) {
|
|
1207
1671
|
if (part.type === "refusal") {
|
|
1208
1672
|
pendingRefusal = true;
|
|
1673
|
+
// The typeof guard is load-bearing: rawItem is envelope-only-validated
|
|
1674
|
+
// wire data, and push() must never throw.
|
|
1675
|
+
const text = part.refusal;
|
|
1676
|
+
if (typeof text === "string")
|
|
1677
|
+
driveRunItemRefusal(item, text);
|
|
1209
1678
|
continue;
|
|
1210
1679
|
}
|
|
1211
1680
|
if (part.type === "output_text") {
|
|
@@ -1226,20 +1695,34 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1226
1695
|
...(item.phase !== undefined ? { phase: item.phase } : {}),
|
|
1227
1696
|
});
|
|
1228
1697
|
}
|
|
1229
|
-
|
|
1698
|
+
const idlessAnnotations = partAnnotations(part);
|
|
1699
|
+
if (idlessAnnotations.length > 0) {
|
|
1230
1700
|
a.emitExt("openai", "late-citations", {
|
|
1231
|
-
annotations:
|
|
1701
|
+
annotations: idlessAnnotations,
|
|
1232
1702
|
});
|
|
1233
1703
|
}
|
|
1234
1704
|
continue;
|
|
1235
1705
|
}
|
|
1236
1706
|
if (msgId === undefined) {
|
|
1237
|
-
// response already closed — see doc above.
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1707
|
+
// response already closed — see doc above. While the round's close
|
|
1708
|
+
// is STASHED (deferred for its tool results or built-in calls), this
|
|
1709
|
+
// block's text.end is not out yet, so its url citations ride it (the
|
|
1710
|
+
// phase marker's case (ii) below), and any other annotation takes
|
|
1711
|
+
// the ext carry; a message that lands after the close was released
|
|
1712
|
+
// carries every annotation on the ext.
|
|
1713
|
+
const closedAnnotations = partAnnotations(part);
|
|
1714
|
+
if (closedAnnotations.length > 0) {
|
|
1715
|
+
const split = isStashedTextStream(item.id) ? splitAnnotations(closedAnnotations, part.text) : undefined;
|
|
1716
|
+
if (split?.citations !== undefined) {
|
|
1717
|
+
stashedEndFields.set(item.id, { ...stashedEndFields.get(item.id), citations: split.citations });
|
|
1718
|
+
}
|
|
1719
|
+
const carry = split?.citations !== undefined ? split.unmapped : closedAnnotations;
|
|
1720
|
+
if (carry.length > 0) {
|
|
1721
|
+
a.emitExt("openai", "late-citations", {
|
|
1722
|
+
itemId: item.id,
|
|
1723
|
+
annotations: carry,
|
|
1724
|
+
});
|
|
1725
|
+
}
|
|
1243
1726
|
}
|
|
1244
1727
|
// phase (0.14.0): the live wire delivers the FINAL round's
|
|
1245
1728
|
// message_output_created AFTER response_done has closed the message
|
|
@@ -1248,21 +1731,22 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1248
1731
|
// (deferred-close) messages ever reach it. Same post-close degrade
|
|
1249
1732
|
// convention as late-citations: a dedicated itemId-keyed vendor
|
|
1250
1733
|
// carry, one per phase-bearing part.
|
|
1251
|
-
//
|
|
1734
|
+
// RETIRED when this id's SAME phase already rode its text.start
|
|
1252
1735
|
// (the live case); kept — lossless — when only the run-item knows it,
|
|
1253
1736
|
// or knows a different value.
|
|
1254
|
-
//
|
|
1737
|
+
// A null/"" phase is no marker at all (spec ruling (a)) — neither
|
|
1255
1738
|
// a carry nor a late-phase ext.
|
|
1256
1739
|
const lateItemPhase = vendorPhase(item.phase);
|
|
1257
1740
|
if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
|
|
1258
1741
|
if (isStashedTextStream(item.id)) {
|
|
1259
|
-
//
|
|
1742
|
+
// Case (ii): the round close is STASHED (a deferred tool
|
|
1260
1743
|
// round), so this block's text.end is NOT yet emitted — the §5
|
|
1261
1744
|
// timing rule makes the end the phase's home (ruled
|
|
1262
1745
|
// 2026-09-23). The marker has a first-class home, so no late-phase.
|
|
1263
1746
|
const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
|
|
1264
1747
|
const endMeta = openaiProviderMeta({ phase: lateItemPhase });
|
|
1265
1748
|
stashedEndFields.set(item.id, {
|
|
1749
|
+
...stashedEndFields.get(item.id),
|
|
1266
1750
|
...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
|
|
1267
1751
|
...(interim !== undefined ? { phase: interim } : {}),
|
|
1268
1752
|
});
|
|
@@ -1275,12 +1759,15 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1275
1759
|
}
|
|
1276
1760
|
continue;
|
|
1277
1761
|
}
|
|
1278
|
-
//
|
|
1762
|
+
// Id first, FIFO fallback — see "Correlation" in the doc above.
|
|
1279
1763
|
const streamId = item.id !== undefined && openTextStreams.has(item.id) ? item.id : openTextStreams.values().next().value;
|
|
1280
1764
|
if (streamId === undefined)
|
|
1281
1765
|
continue; // defensive: no matching open stream
|
|
1282
1766
|
openTextStreams.delete(streamId);
|
|
1283
|
-
|
|
1767
|
+
// A url citation rides text.end; any other annotation has no citation
|
|
1768
|
+
// target and takes the ext carry, after the text.end (SPEC:965).
|
|
1769
|
+
const liveSplit = splitAnnotations(partAnnotations(part), part.text);
|
|
1770
|
+
const citations = liveSplit.citations;
|
|
1284
1771
|
// phase (0.14.0) rides the matching text.end's providerMetadata —
|
|
1285
1772
|
// PER-PART, not message.metadata: this facet folds a response into ONE
|
|
1286
1773
|
// message, and a program-driven turn emits multiple message items with
|
|
@@ -1288,7 +1775,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1288
1775
|
// merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
|
|
1289
1776
|
const itemPhase = vendorPhase(item.phase);
|
|
1290
1777
|
const phaseMeta = openaiProviderMeta({ phase: itemPhase });
|
|
1291
|
-
//
|
|
1778
|
+
// Case (i): known before this block's text.end ⇒ the end carries
|
|
1292
1779
|
// the first-class phase, unless text.start already did.
|
|
1293
1780
|
const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
|
|
1294
1781
|
a.textEnd(streamId, msgId, citations !== undefined || phaseMeta !== undefined || endInterim !== undefined
|
|
@@ -1298,11 +1785,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1298
1785
|
...(endInterim !== undefined ? { phase: endInterim } : {}),
|
|
1299
1786
|
}
|
|
1300
1787
|
: undefined);
|
|
1788
|
+
if (liveSplit.unmapped.length > 0) {
|
|
1789
|
+
a.emitExt("openai", "late-citations", { itemId: item.id ?? streamId, annotations: liveSplit.unmapped });
|
|
1790
|
+
}
|
|
1301
1791
|
}
|
|
1302
1792
|
}
|
|
1303
1793
|
}
|
|
1304
1794
|
/**
|
|
1305
|
-
*
|
|
1795
|
+
* Open the reasoning block for `rsId` in the current message — once per
|
|
1306
1796
|
* id (a re-announce, or an id already filled, is a no-op). `id` and `itemId`
|
|
1307
1797
|
* are both the `rs_` id (the run-item path's convention). Called from
|
|
1308
1798
|
* `output_item.added{reasoning}` so the block takes its WIRE position, and
|
|
@@ -1317,7 +1807,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1317
1807
|
openReasoning.set(rsId, msgId);
|
|
1318
1808
|
}
|
|
1319
1809
|
/**
|
|
1320
|
-
*
|
|
1810
|
+
* Fill + seal an OPEN reasoning block: one `reasoning.delta` per
|
|
1321
1811
|
* non-empty summary part (`partIndex` = the wire `summary_index`), then
|
|
1322
1812
|
* `reasoning.opaque` (the replayable ciphertext, `itemId` = rs_) BEFORE
|
|
1323
1813
|
* `reasoning.end`, so "sealed" means complete (the spec's recommendation;
|
|
@@ -1349,7 +1839,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1349
1839
|
openReasoning.delete(rsId);
|
|
1350
1840
|
filledReasoning.add(rsId);
|
|
1351
1841
|
}
|
|
1352
|
-
/**
|
|
1842
|
+
/** Fill every reasoning block from a terminal event's `response.output`
|
|
1353
1843
|
* (see `terminalReasoningItems` for why this, not `output_item.done`, is the
|
|
1354
1844
|
* source). An item never announced by `output_item.added` opens here
|
|
1355
1845
|
* (defensive — position is then the terminal event's). */
|
|
@@ -1362,14 +1852,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1362
1852
|
}
|
|
1363
1853
|
}
|
|
1364
1854
|
/**
|
|
1365
|
-
* Map a `reasoning_item_created` run-item
|
|
1855
|
+
* Map a `reasoning_item_created` run-item. Since reasoning is sourced from the terminal output it
|
|
1366
1856
|
* is the FALLBACK source: on the live wire it lands after `response.completed`,
|
|
1367
1857
|
* whose output already filled the block, so a run-item whose `rs_` id is in
|
|
1368
1858
|
* `filledReasoning` is a no-op (single source per id — no duplicate block, no
|
|
1369
1859
|
* `late-reasoning` ext). If raw `output_item.added` opened the block but no
|
|
1370
1860
|
* terminal output has filled it yet, the run-item fills that block in place.
|
|
1371
1861
|
* Only with NO raw reasoning events for the id (run-item-only streams) does the
|
|
1372
|
-
*
|
|
1862
|
+
* run-item-only mapping below still run, unchanged:
|
|
1373
1863
|
*
|
|
1374
1864
|
* The run-item wrapper delivers the reasoning item as ONE completed unit (unlike
|
|
1375
1865
|
* the incremental text/tool-arg deltas elsewhere in this facet), so
|
|
@@ -1403,15 +1893,15 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1403
1893
|
* never got opened, so `reasoning.start`/`.delta`/`.end` staying unemitted is the
|
|
1404
1894
|
* correct degrade), but the `rs_`/`encrypted_content` ZDR blob (spec §8.2/§10.4)
|
|
1405
1895
|
* is exactly the kind of payload Tenet 6 exists for — silently dropping it here
|
|
1406
|
-
* was a genuine loss
|
|
1407
|
-
*
|
|
1896
|
+
* was a genuine loss. Mirrors `ext.openai.late-citations` exactly: route it
|
|
1897
|
+
* through the lossless vendor channel instead of the bare
|
|
1408
1898
|
* return.
|
|
1409
1899
|
*/
|
|
1410
1900
|
function driveReasoningItemCreated(item) {
|
|
1411
|
-
//
|
|
1901
|
+
// Dedupe: already filled from the terminal output (or an earlier run-item).
|
|
1412
1902
|
if (item.id !== undefined && filledReasoning.has(item.id))
|
|
1413
1903
|
return;
|
|
1414
|
-
//
|
|
1904
|
+
// Raw `output_item.added` opened this block; no terminal output has
|
|
1415
1905
|
// filled it yet (synthetic ordering) — fill it in place from the run-item,
|
|
1416
1906
|
// whose `content[]` IS the raw `summary[]` (one part per index).
|
|
1417
1907
|
if (msgId !== undefined && item.id !== undefined && openReasoning.has(item.id)) {
|
|
@@ -1449,7 +1939,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1449
1939
|
...(itemId !== undefined ? { itemId } : {}),
|
|
1450
1940
|
});
|
|
1451
1941
|
}
|
|
1452
|
-
//
|
|
1942
|
+
// A terminal output naming this rs_ later must not open a second block.
|
|
1453
1943
|
if (itemId !== undefined)
|
|
1454
1944
|
filledReasoning.add(itemId);
|
|
1455
1945
|
}
|
|
@@ -1464,7 +1954,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1464
1954
|
* pending bookkeeping and — if the turn's pending set just drained to empty
|
|
1465
1955
|
* — replay any stashed deferred round-close (Task 4b, INV-MSG). Shared by
|
|
1466
1956
|
* the `function_call` `tool_output` arm and the built-in Shell/Apply-Patch
|
|
1467
|
-
* `tool_output` arm (
|
|
1957
|
+
* `tool_output` arm (the 2026-07-03 SDK-bump adaptation).
|
|
1468
1958
|
*/
|
|
1469
1959
|
/**
|
|
1470
1960
|
* HO-P, the handoff round release (§8.0 item 14, draft.5). Called at
|
|
@@ -1504,11 +1994,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1504
1994
|
}
|
|
1505
1995
|
if (pending.size > 0)
|
|
1506
1996
|
return;
|
|
1507
|
-
|
|
1508
|
-
if (stashed === undefined)
|
|
1509
|
-
return;
|
|
1510
|
-
stashedCloseByTurn.delete(sourceTurnId);
|
|
1511
|
-
emitRoundClose(sourceTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
|
|
1997
|
+
maybeReleaseRound(sourceTurnId);
|
|
1512
1998
|
}
|
|
1513
1999
|
function drainPendingTool(callId, doneTurnId) {
|
|
1514
2000
|
if (doneTurnId === undefined)
|
|
@@ -1518,17 +2004,13 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1518
2004
|
if (pending === undefined)
|
|
1519
2005
|
return;
|
|
1520
2006
|
pending.delete(callId);
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
stashedCloseByTurn.delete(doneTurnId);
|
|
1529
|
-
emitRoundClose(doneTurnId, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
|
|
1530
|
-
}
|
|
1531
|
-
}
|
|
2007
|
+
// The pending set just drained — emit the deferred message.end +
|
|
2008
|
+
// turn.done immediately after this tool.done, same push() batch
|
|
2009
|
+
// (INV-MSG: the message must still be open when tool.done lands, so
|
|
2010
|
+
// message.end waits for this too), unless a listed built-in call of the
|
|
2011
|
+
// round has yet to land (see "Built-in round attach").
|
|
2012
|
+
if (pending.size === 0)
|
|
2013
|
+
maybeReleaseRound(doneTurnId);
|
|
1532
2014
|
}
|
|
1533
2015
|
/** True if any shell command in `entries` timed out or exited non-zero. */
|
|
1534
2016
|
function shellOutputHasError(entries) {
|
|
@@ -1542,7 +2024,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1542
2024
|
}
|
|
1543
2025
|
/**
|
|
1544
2026
|
* Map a `tool_output` run-item whose `rawItem` is a Shell, Apply-Patch, or
|
|
1545
|
-
* Computer-Use result (
|
|
2027
|
+
* Computer-Use result (the 2026-07-03 SDK-bump adaptation;
|
|
1546
2028
|
* `computer_call_result` added by the fixture-drift ratchet finding, same
|
|
1547
2029
|
* date). These do NOT share `OpenAIFunctionCallResultItem`'s `output` shape
|
|
1548
2030
|
* (a bare string / content-part union) — `shell_call_output.output` is an
|
|
@@ -1575,7 +2057,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1575
2057
|
shellOutputHasError(rawItem.output) || rawItem.status === "incomplete" ? "error" : "ok";
|
|
1576
2058
|
// The full per-command record (stdout/stderr/exit code) is lossy to
|
|
1577
2059
|
// collapse into text-only content — carry it verbatim as structuredContent
|
|
1578
|
-
// too (mirrors the function_call path's
|
|
2060
|
+
// too (mirrors the function_call path's cache-marker precedent).
|
|
1579
2061
|
structuredContent = JsonValue.parse(rawItem.output);
|
|
1580
2062
|
// The outcome mapping alone cannot recover `status` ('in_progress' vs
|
|
1581
2063
|
// 'completed' vs absent all map ok) — carry it verbatim, with caller.
|
|
@@ -1662,7 +2144,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1662
2144
|
/**
|
|
1663
2145
|
* Map a `tool_called` run-item whose `rawItem` is one of OpenAI's native
|
|
1664
2146
|
* built-in tool call shapes (Shell / Apply-Patch / Computer-Use / Hosted-tool
|
|
1665
|
-
* —
|
|
2147
|
+
* — the 2026-07-03 SDK-bump adaptation; `computer_call`
|
|
1666
2148
|
* added by the fixture-drift ratchet finding, same date). Unlike
|
|
1667
2149
|
* `function_call` (whose tool-start rides the raw `response.output_item.
|
|
1668
2150
|
* added` stream — the authoritative source, canonical model A1), this
|
|
@@ -1673,11 +2155,12 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1673
2155
|
* action/operation arrives complete on this one wrapper), and
|
|
1674
2156
|
* `hosted_tool_call` has no raw-wire literal AT ALL (see its own doc — it is
|
|
1675
2157
|
* an agents-core-internal umbrella normalized only at this run-item layer).
|
|
1676
|
-
*
|
|
1677
|
-
* (
|
|
1678
|
-
*
|
|
1679
|
-
*
|
|
1680
|
-
*
|
|
2158
|
+
* Like every run-item, this wrapper lands AFTER its response's
|
|
2159
|
+
* `response.completed` (agents-core 0.18.0 streams a response's step items
|
|
2160
|
+
* after the raw loop, run.mjs:1935), so it attaches to the round its
|
|
2161
|
+
* terminal listed, whose close is deferred for it (see "Built-in round
|
|
2162
|
+
* attach"); it opens a response only when none has been seen for it (a
|
|
2163
|
+
* run-item that lands while its response is open joins that response).
|
|
1681
2164
|
*
|
|
1682
2165
|
* `shell_call`/`apply_patch_call`/`computer_call` are PENDING calls (their
|
|
1683
2166
|
* result arrives via a LATER `tool_output` run-item, same Task-4b
|
|
@@ -1689,7 +2172,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1689
2172
|
* doc) — no pending registration.
|
|
1690
2173
|
*/
|
|
1691
2174
|
/**
|
|
1692
|
-
*
|
|
2175
|
+
* Did OpenAI (the provider) already execute this built-in call? →
|
|
1693
2176
|
* `tool.start.providerExecuted` (SPEC:632; SPEC:496 "client MUST NOT
|
|
1694
2177
|
* execute"). Per the installed runtime (agents-core 0.18.0
|
|
1695
2178
|
* `dist/runner/modelOutputs.mjs`): `hosted_tool_call` always (resolved
|
|
@@ -1711,26 +2194,260 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1711
2194
|
}
|
|
1712
2195
|
return false;
|
|
1713
2196
|
}
|
|
2197
|
+
/**
|
|
2198
|
+
* The toolCallId of a `hosted_tool_call`: its item id when it has one. An
|
|
2199
|
+
* id-less item gets a derived id, `<name>_<invoke stem>_<n>` (INV-BLOCK,
|
|
2200
|
+
* SPEC:767: "Normalizers MUST mint collision-free **derived** ids when the
|
|
2201
|
+
* framework omits one"), never its `name`, which two items of one invoke
|
|
2202
|
+
* can share. An `mcp_approval_response` (which agents-core 0.18.0 builds
|
|
2203
|
+
* with no id, runner/mcpApprovals.mjs:39-49) is no call of its own: it
|
|
2204
|
+
* closes the request it answers (`driveApprovalAnswer`).
|
|
2205
|
+
*/
|
|
2206
|
+
function hostedToolCallId(rawItem) {
|
|
2207
|
+
if (rawItem.id !== undefined && rawItem.id.length > 0)
|
|
2208
|
+
return rawItem.id;
|
|
2209
|
+
return `${rawItem.name}_${invokeStem}_${++derivedOrdinal}`;
|
|
2210
|
+
}
|
|
2211
|
+
/** The hosted-MCP kind of a `hosted_tool_call`, by its `name` or its
|
|
2212
|
+
* `providerData.type` (agents-openai's converter matches either,
|
|
2213
|
+
* openaiResponsesConverter.mjs:1066-1115). */
|
|
2214
|
+
function hostedMcpKind(rawItem) {
|
|
2215
|
+
const type = rawItem.providerData?.type;
|
|
2216
|
+
for (const kind of ["mcp_call", "mcp_approval_request", "mcp_approval_response"]) {
|
|
2217
|
+
if (rawItem.name === kind || type === kind)
|
|
2218
|
+
return kind;
|
|
2219
|
+
}
|
|
2220
|
+
return undefined;
|
|
2221
|
+
}
|
|
2222
|
+
/**
|
|
2223
|
+
* An `mcp_approval_response` run-item closes the request it answers
|
|
2224
|
+
* (`providerData.approval_request_id`) with exactly one `tool.done`:
|
|
2225
|
+
* outcome "ok" when `providerData.approve` is true, which records the
|
|
2226
|
+
* approval and not the result of the call it gates, and "denied" when it is
|
|
2227
|
+
* not. It creates no block of its own, and the `mcp_call` it gates is a
|
|
2228
|
+
* separate call under its own id. The request is a pending call of its
|
|
2229
|
+
* round in the same invoke (the onApproval flow); in a resuming invoke it
|
|
2230
|
+
* is unknown, and the answer lands as a leading result does
|
|
2231
|
+
* (`openTurnForLeadingResult`, INV-XINV). An answer's `reason` rides
|
|
2232
|
+
* tool.done providerMetadata. Three answers have nothing to close, and each
|
|
2233
|
+
* is carried verbatim on ext.openai.unparsed: one that names no request; a
|
|
2234
|
+
* second answer to a request this invoke already closed (agents-core
|
|
2235
|
+
* answers each request once, runner/mcpApprovals.mjs), which would close it
|
|
2236
|
+
* twice; and one naming a request this invoke does not hold while a
|
|
2237
|
+
* response is open, which no leading turn can take.
|
|
2238
|
+
*/
|
|
2239
|
+
function driveApprovalAnswer(rawItem) {
|
|
2240
|
+
const requestId = rawItem.providerData?.approval_request_id;
|
|
2241
|
+
if (typeof requestId !== "string" || requestId.length === 0 || answeredRequests.has(requestId)) {
|
|
2242
|
+
a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
|
|
2243
|
+
return;
|
|
2244
|
+
}
|
|
2245
|
+
const reason = rawItem.providerData?.reason;
|
|
2246
|
+
const meta = openaiProviderMeta({
|
|
2247
|
+
reason: typeof reason === "string" && reason.length > 0 ? reason : undefined,
|
|
2248
|
+
caller: callerToJson(rawItem.caller),
|
|
2249
|
+
});
|
|
2250
|
+
const doneTurnId = resolvePendingTurnId(requestId);
|
|
2251
|
+
const leading = doneTurnId === undefined ? openTurnForLeadingResult(requestId) : undefined;
|
|
2252
|
+
if (doneTurnId === undefined && leading === undefined) {
|
|
2253
|
+
a.emitExt("openai", "unparsed", { name: "tool_called", item: JsonValue.parse(rawItem) });
|
|
2254
|
+
return;
|
|
2255
|
+
}
|
|
2256
|
+
answeredRequests.add(requestId);
|
|
2257
|
+
a.toolDone({
|
|
2258
|
+
toolCallId: requestId,
|
|
2259
|
+
content: [],
|
|
2260
|
+
outcome: rawItem.providerData?.approve === true ? "ok" : "denied",
|
|
2261
|
+
...(meta !== undefined ? { providerMetadata: meta } : {}),
|
|
2262
|
+
...(doneTurnId !== undefined ? { turnId: doneTurnId } : leading),
|
|
2263
|
+
});
|
|
2264
|
+
drainPendingTool(requestId, doneTurnId);
|
|
2265
|
+
}
|
|
2266
|
+
/**
|
|
2267
|
+
* A hosted call's input. agents-openai's converter keeps a hosted item's
|
|
2268
|
+
* fields in `providerData` (SPEC:965: a native value is never dropped
|
|
2269
|
+
* silently):
|
|
2270
|
+
* - its `arguments` (top-level when present, else in providerData — the
|
|
2271
|
+
* MCP kinds);
|
|
2272
|
+
* - else a web_search's `action` without its `sources`, which are the
|
|
2273
|
+
* call's result, not its input;
|
|
2274
|
+
* - else a file_search's `queries`;
|
|
2275
|
+
* - else a code_interpreter's `code` and `container_id` (its call payload
|
|
2276
|
+
* without its `outputs`, the program precedent).
|
|
2277
|
+
*/
|
|
2278
|
+
function hostedInput(rawItem) {
|
|
2279
|
+
const pd = rawItem.providerData;
|
|
2280
|
+
const args = rawItem.arguments ?? pd?.arguments;
|
|
2281
|
+
if (typeof args === "string")
|
|
2282
|
+
return parseJsonArguments(rawItem.id, args);
|
|
2283
|
+
const action = pd?.action;
|
|
2284
|
+
if (isJsonObject(action)) {
|
|
2285
|
+
const input = {};
|
|
2286
|
+
for (const [k, v] of Object.entries(action))
|
|
2287
|
+
if (k !== "sources")
|
|
2288
|
+
input[k] = v;
|
|
2289
|
+
return JsonValue.parse(input);
|
|
2290
|
+
}
|
|
2291
|
+
if (rawItem.name === "file_search_call" && pd?.queries !== undefined)
|
|
2292
|
+
return JsonValue.parse({ queries: pd.queries });
|
|
2293
|
+
if (rawItem.name === "code_interpreter_call" && (pd?.code !== undefined || pd?.container_id !== undefined)) {
|
|
2294
|
+
return JsonValue.parse({
|
|
2295
|
+
...(pd?.code !== undefined ? { code: pd.code } : {}),
|
|
2296
|
+
...(pd?.container_id !== undefined ? { container_id: pd.container_id } : {}),
|
|
2297
|
+
});
|
|
2298
|
+
}
|
|
2299
|
+
return {};
|
|
2300
|
+
}
|
|
2301
|
+
/**
|
|
2302
|
+
* A hosted call's result: its `output` (an image_generation result, which
|
|
2303
|
+
* is base64 image data, as a file block; any other as text), a
|
|
2304
|
+
* web_search's `sources`, an mcp_list_tools listing, a file_search's
|
|
2305
|
+
* `results` and a code_interpreter's `outputs` as data blocks, and its
|
|
2306
|
+
* outcome. The outcome is "error" when the native status is `failed` or
|
|
2307
|
+
* `incomplete`, as a shell, program or function result's `incomplete` is
|
|
2308
|
+
* (and an apply-patch result's `failed`); for an mcp_call, whose top-level
|
|
2309
|
+
* status the converter always sets to "completed", the status in
|
|
2310
|
+
* providerData. It is also "error" when the item carries a non-null
|
|
2311
|
+
* `error`, an empty string included, even with a `completed` status. Any
|
|
2312
|
+
* other status (`in_progress`,
|
|
2313
|
+
* `searching`, `interpreting`, …) closes "ok"; a status other than
|
|
2314
|
+
* `completed` rides tool.done providerMetadata.status verbatim.
|
|
2315
|
+
*/
|
|
2316
|
+
function hostedResult(rawItem) {
|
|
2317
|
+
const pd = rawItem.providerData;
|
|
2318
|
+
const content = [];
|
|
2319
|
+
const output = rawItem.output;
|
|
2320
|
+
if (typeof output === "string" && output.length > 0) {
|
|
2321
|
+
content.push(rawItem.name === "image_generation_call"
|
|
2322
|
+
? { type: "file", source: { type: "base64", mediaType: imageResultMediaType(pd, output), data: output } }
|
|
2323
|
+
: { type: "text", text: output });
|
|
2324
|
+
}
|
|
2325
|
+
const action = pd?.action;
|
|
2326
|
+
if (isJsonObject(action) && Array.isArray(action.sources)) {
|
|
2327
|
+
content.push({ type: "data", name: "web_search_sources", data: JsonValue.parse(action.sources) });
|
|
2328
|
+
}
|
|
2329
|
+
const tools = pd?.tools;
|
|
2330
|
+
if (rawItem.name === "mcp_list_tools" && Array.isArray(tools)) {
|
|
2331
|
+
content.push({ type: "data", name: "mcp_list_tools", data: JsonValue.parse(tools) });
|
|
2332
|
+
}
|
|
2333
|
+
const results = pd?.results;
|
|
2334
|
+
if (rawItem.name === "file_search_call" && Array.isArray(results)) {
|
|
2335
|
+
content.push({ type: "data", name: "file_search_results", data: JsonValue.parse(results) });
|
|
2336
|
+
}
|
|
2337
|
+
const outputs = pd?.outputs;
|
|
2338
|
+
if (rawItem.name === "code_interpreter_call" && Array.isArray(outputs)) {
|
|
2339
|
+
content.push({ type: "data", name: "code_interpreter_outputs", data: JsonValue.parse(outputs) });
|
|
2340
|
+
}
|
|
2341
|
+
const status = hostedMcpKind(rawItem) === "mcp_call" ? (pd?.status ?? rawItem.status) : rawItem.status;
|
|
2342
|
+
// An mcp_call's `error` is an object on the wire (openai-node 7.22.0
|
|
2343
|
+
// McpToolCallError: a protocol or HTTP error {code, message, type}, or a
|
|
2344
|
+
// tool execution error {content, type}): its message (else the object as
|
|
2345
|
+
// JSON) is the errorText, its type the errorCode, and the object rides
|
|
2346
|
+
// tool.done providerMetadata verbatim. A non-empty string error is its own
|
|
2347
|
+
// text; any other non-null error (an empty string) rides providerMetadata.
|
|
2348
|
+
const error = pd?.error;
|
|
2349
|
+
const hasError = error !== undefined && error !== null;
|
|
2350
|
+
const errorMessage = isJsonObject(error) ? error.message : undefined;
|
|
2351
|
+
const errorText = typeof error === "string" && error.length > 0
|
|
2352
|
+
? error
|
|
2353
|
+
: typeof errorMessage === "string" && errorMessage.length > 0
|
|
2354
|
+
? errorMessage
|
|
2355
|
+
: isJsonObject(error)
|
|
2356
|
+
? JSON.stringify(error)
|
|
2357
|
+
: undefined;
|
|
2358
|
+
const errorType = isJsonObject(error) ? error.type : undefined;
|
|
2359
|
+
// An image_generation result's own fields (revised prompt, size, quality,
|
|
2360
|
+
// background, action, format) ride tool.done providerMetadata verbatim.
|
|
2361
|
+
const image = rawItem.name === "image_generation_call" ? pd : undefined;
|
|
2362
|
+
const imageField = (k) => {
|
|
2363
|
+
const v = image?.[k];
|
|
2364
|
+
return v === null ? undefined : v;
|
|
2365
|
+
};
|
|
2366
|
+
const providerMetadata = openaiProviderMeta({
|
|
2367
|
+
status: typeof status === "string" && status.length > 0 && status !== "completed" ? status : undefined,
|
|
2368
|
+
error: hasError && errorText !== error ? JsonValue.parse(error) : undefined,
|
|
2369
|
+
revised_prompt: imageField("revised_prompt"),
|
|
2370
|
+
size: imageField("size"),
|
|
2371
|
+
quality: imageField("quality"),
|
|
2372
|
+
background: imageField("background"),
|
|
2373
|
+
action: imageField("action"),
|
|
2374
|
+
output_format: imageField("output_format"),
|
|
2375
|
+
});
|
|
2376
|
+
const meta = providerMetadata !== undefined ? { providerMetadata } : {};
|
|
2377
|
+
if (status === "failed" || status === "incomplete" || hasError) {
|
|
2378
|
+
return {
|
|
2379
|
+
content,
|
|
2380
|
+
outcome: "error",
|
|
2381
|
+
isError: true,
|
|
2382
|
+
...(errorText !== undefined ? { errorText } : {}),
|
|
2383
|
+
...(typeof errorType === "string" && errorType.length > 0 ? { errorCode: errorType } : {}),
|
|
2384
|
+
...meta,
|
|
2385
|
+
};
|
|
2386
|
+
}
|
|
2387
|
+
return { content, outcome: "ok", ...meta };
|
|
2388
|
+
}
|
|
1714
2389
|
function driveBuiltinToolCalled(rawItem) {
|
|
1715
|
-
|
|
1716
|
-
if (
|
|
2390
|
+
const mcpKind = rawItem.type === "hosted_tool_call" ? hostedMcpKind(rawItem) : undefined;
|
|
2391
|
+
if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_response") {
|
|
2392
|
+
driveApprovalAnswer(rawItem);
|
|
2393
|
+
return;
|
|
2394
|
+
}
|
|
2395
|
+
// The listed item this run-item is (see "Built-in round attach").
|
|
2396
|
+
const key = rawItem.id;
|
|
2397
|
+
if (rawItem.id !== undefined)
|
|
2398
|
+
seenBuiltinItemIds.add(rawItem.id);
|
|
2399
|
+
const toolCallId = rawItem.type === "hosted_tool_call" ? hostedToolCallId(rawItem) : rawItem.callId;
|
|
2400
|
+
// A run-item that lands after its round's terminal attaches to that round;
|
|
2401
|
+
// one that lands while a response is open belongs to it. A hosted call
|
|
2402
|
+
// that no round claims while no response is open (not a 0.18.0 shape: a
|
|
2403
|
+
// resuming invoke leads with a tool result or an approval's answer) opens
|
|
2404
|
+
// its turn as a leading tool result does (`openTurnForLeadingResult`), in
|
|
2405
|
+
// an assistant message of its own, `<toolCallId>:call`, closed after the
|
|
2406
|
+
// call: the response that follows then opens its own message in that
|
|
2407
|
+
// turn, with its model. A leading client-executed or tool-search call
|
|
2408
|
+
// keeps the response open.
|
|
2409
|
+
const late = lateBuiltinRound(key);
|
|
2410
|
+
// openTurnForLeadingResult returns undefined while a response is open.
|
|
2411
|
+
const leading = late === undefined && rawItem.type === "hosted_tool_call" ? openTurnForLeadingResult(toolCallId) : undefined;
|
|
2412
|
+
const callMsgId = leading !== undefined ? `${toolCallId}:call` : undefined;
|
|
2413
|
+
if (leading !== undefined && callMsgId !== undefined) {
|
|
2414
|
+
a.openMessage({ id: callMsgId, role: "assistant", turnId: leading.turnId, threadId });
|
|
2415
|
+
}
|
|
2416
|
+
else if (late === undefined) {
|
|
2417
|
+
ensureResponseOpen();
|
|
2418
|
+
}
|
|
2419
|
+
const ownerMsgId = late !== undefined ? late.mId : (callMsgId ?? msgId);
|
|
2420
|
+
const ownerTurnId = late !== undefined ? late.tid : (leading?.turnId ?? turnId);
|
|
2421
|
+
if (ownerMsgId === undefined)
|
|
1717
2422
|
return; // unreachable post-ensure; satisfies narrowing
|
|
1718
|
-
|
|
1719
|
-
|
|
2423
|
+
// An MCP call or approval request is named by the MCP tool it calls
|
|
2424
|
+
// (`providerData.name`); the item's own name is the umbrella (`mcp_call` /
|
|
2425
|
+
// `mcp_approval_request`), which rides providerMetadata.type.
|
|
2426
|
+
const mcpToolName = mcpKind !== undefined ? rawItem.providerData?.name : undefined;
|
|
2427
|
+
const name = typeof mcpToolName === "string" && mcpToolName.length > 0 ? mcpToolName : builtinToolName(rawItem);
|
|
1720
2428
|
// Caller provenance (0.14.0): typed only on the shapes the wire declares
|
|
1721
2429
|
// it for — computer_call and program carry none (protocol.d.ts).
|
|
1722
2430
|
const caller = rawItem.type === "shell_call" || rawItem.type === "apply_patch_call" || rawItem.type === "hosted_tool_call"
|
|
1723
2431
|
? rawItem.caller
|
|
1724
2432
|
: undefined;
|
|
1725
|
-
|
|
2433
|
+
// An mcp_call that an approval gated names that request (verbatim).
|
|
2434
|
+
const approvalRequestId = mcpKind === "mcp_call" ? rawItem.providerData?.approval_request_id : undefined;
|
|
2435
|
+
const startMeta = openaiProviderMeta({
|
|
2436
|
+
caller: callerToJson(caller),
|
|
2437
|
+
type: mcpKind,
|
|
2438
|
+
approval_request_id: typeof approvalRequestId === "string" && approvalRequestId.length > 0 ? approvalRequestId : undefined,
|
|
2439
|
+
});
|
|
2440
|
+
// An MCP item's server label (SPEC tool.start.serverName).
|
|
2441
|
+
const serverLabel = rawItem.type === "hosted_tool_call" ? rawItem.providerData?.server_label : undefined;
|
|
1726
2442
|
a.toolStart({
|
|
1727
2443
|
toolCallId,
|
|
1728
2444
|
name,
|
|
2445
|
+
...(typeof serverLabel === "string" && serverLabel.length > 0 ? { serverName: serverLabel } : {}),
|
|
1729
2446
|
...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
|
|
1730
2447
|
...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
|
|
1731
|
-
//
|
|
2448
|
+
// See builtinProviderExecuted().
|
|
1732
2449
|
...(builtinProviderExecuted(rawItem) ? { providerExecuted: true } : {}),
|
|
1733
|
-
messageId:
|
|
2450
|
+
messageId: ownerMsgId,
|
|
1734
2451
|
});
|
|
1735
2452
|
const input = rawItem.type === "shell_call"
|
|
1736
2453
|
? JsonValue.parse(rawItem.action)
|
|
@@ -1742,15 +2459,30 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1742
2459
|
? // The call's whole wire payload, verbatim (the shell/apply-patch
|
|
1743
2460
|
// precedent): `code` is the model-authored program source.
|
|
1744
2461
|
{ code: rawItem.code, fingerprint: rawItem.fingerprint }
|
|
1745
|
-
:
|
|
2462
|
+
: hostedInput(rawItem);
|
|
1746
2463
|
a.toolArgsDelta(toolCallId, JSON.stringify(input));
|
|
1747
2464
|
a.toolArgsAssembled(toolCallId, input);
|
|
2465
|
+
if (rawItem.type === "hosted_tool_call" && mcpKind === "mcp_approval_request") {
|
|
2466
|
+
// Not resolved: the request stays a pending call of its round until its
|
|
2467
|
+
// answer closes it; with no answer, the round flushes paused naming its
|
|
2468
|
+
// ask (§8.0 items 14 and 20, INV-FLUSH (2)).
|
|
2469
|
+
if (callMsgId !== undefined)
|
|
2470
|
+
a.closeMessage(callMsgId);
|
|
2471
|
+
registerPendingToolFor(ownerTurnId, toolCallId);
|
|
2472
|
+
drainListedBuiltin(key);
|
|
2473
|
+
return;
|
|
2474
|
+
}
|
|
1748
2475
|
if (rawItem.type === "hosted_tool_call") {
|
|
1749
|
-
const
|
|
1750
|
-
a.toolDone({ toolCallId,
|
|
2476
|
+
const doneTurnId = late?.tid ?? leading?.turnId;
|
|
2477
|
+
a.toolDone({ toolCallId, ...hostedResult(rawItem), ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}) });
|
|
2478
|
+
if (callMsgId !== undefined)
|
|
2479
|
+
a.closeMessage(callMsgId);
|
|
2480
|
+
drainListedBuiltin(key);
|
|
1751
2481
|
return;
|
|
1752
2482
|
}
|
|
1753
|
-
|
|
2483
|
+
registerPendingToolFor(ownerTurnId, toolCallId);
|
|
2484
|
+
// Its run-item has landed; the round now waits on its result.
|
|
2485
|
+
drainListedBuiltin(key);
|
|
1754
2486
|
}
|
|
1755
2487
|
/**
|
|
1756
2488
|
* Resolve the correlation id for a `tool_search_call`/`tool_search_output`
|
|
@@ -1801,29 +2533,40 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1801
2533
|
* like any other unresolved pending tool call, no special-casing needed.
|
|
1802
2534
|
*/
|
|
1803
2535
|
function driveToolSearchCalled(rawItem) {
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
return; // unreachable post-ensure; satisfies narrowing
|
|
2536
|
+
if (rawItem.id !== undefined)
|
|
2537
|
+
seenBuiltinItemIds.add(rawItem.id);
|
|
1807
2538
|
const toolCallId = resolveToolSearchCallId(rawItem);
|
|
1808
2539
|
if (toolCallId === undefined) {
|
|
1809
|
-
// Genuinely unresolvable correlation id — never fabricate one (Tenet 6)
|
|
2540
|
+
// Genuinely unresolvable correlation id — never fabricate one (Tenet 6),
|
|
2541
|
+
// and open no turn for it: the carry is not block content.
|
|
1810
2542
|
a.emitExt("openai", "unparsed", { name: "tool_search_called", item: JsonValue.parse(rawItem) });
|
|
2543
|
+
drainListedBuiltin(rawItem.id);
|
|
1811
2544
|
return;
|
|
1812
2545
|
}
|
|
2546
|
+
// A run-item that lands after its round's terminal attaches to that round
|
|
2547
|
+
// (see "Built-in round attach").
|
|
2548
|
+
const late = lateBuiltinRound(rawItem.id);
|
|
2549
|
+
if (late === undefined)
|
|
2550
|
+
ensureResponseOpen();
|
|
2551
|
+
const ownerMsgId = late !== undefined ? late.mId : msgId;
|
|
2552
|
+
const ownerTurnId = late !== undefined ? late.tid : turnId;
|
|
2553
|
+
if (ownerMsgId === undefined)
|
|
2554
|
+
return; // unreachable post-ensure; satisfies narrowing
|
|
1813
2555
|
a.toolStart({
|
|
1814
2556
|
toolCallId,
|
|
1815
2557
|
name: "builtin:tool_search",
|
|
1816
2558
|
...(rawItem.id !== undefined ? { itemId: rawItem.id } : {}),
|
|
1817
|
-
//
|
|
2559
|
+
// The item says where it ran — only `execution:"server"` is the
|
|
1818
2560
|
// provider's (SPEC:496); "client" (the SDK's own loader / a custom
|
|
1819
2561
|
// execute()) and absent leave the key off.
|
|
1820
2562
|
...(rawItem.execution === "server" ? { providerExecuted: true } : {}),
|
|
1821
|
-
messageId:
|
|
2563
|
+
messageId: ownerMsgId,
|
|
1822
2564
|
});
|
|
1823
2565
|
const input = JsonValue.parse(rawItem.arguments ?? {});
|
|
1824
2566
|
a.toolArgsDelta(toolCallId, JSON.stringify(input));
|
|
1825
2567
|
a.toolArgsAssembled(toolCallId, input);
|
|
1826
|
-
|
|
2568
|
+
registerPendingToolFor(ownerTurnId, toolCallId);
|
|
2569
|
+
drainListedBuiltin(rawItem.id);
|
|
1827
2570
|
}
|
|
1828
2571
|
/**
|
|
1829
2572
|
* Map a `tool_search_output_created` run-item — the paired completion (see
|
|
@@ -1856,8 +2599,14 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1856
2599
|
// the deserialization boundary, where a non-string would otherwise reach
|
|
1857
2600
|
// `AgProviderMeta.parse`.
|
|
1858
2601
|
const rawAgentName = rawItem.toolSearchAgentName;
|
|
2602
|
+
// agents-core 0.20.0 adds the hosted MCP names this search established
|
|
2603
|
+
// (`toolSearchMcpToolNames`), carried the same way: an array of strings,
|
|
2604
|
+
// verbatim; anything else at this boundary is no carry.
|
|
2605
|
+
const rawMcpNames = rawItem.toolSearchMcpToolNames;
|
|
2606
|
+
const mcpNames = Array.isArray(rawMcpNames) && rawMcpNames.every((v) => typeof v === "string") ? JsonValue.parse(rawMcpNames) : undefined;
|
|
1859
2607
|
const searchMeta = openaiProviderMeta({
|
|
1860
2608
|
toolSearchAgentName: typeof rawAgentName === "string" ? rawAgentName : undefined,
|
|
2609
|
+
toolSearchMcpToolNames: mcpNames,
|
|
1861
2610
|
});
|
|
1862
2611
|
a.toolDone({
|
|
1863
2612
|
toolCallId,
|
|
@@ -1883,7 +2632,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1883
2632
|
function driveHostError(event) {
|
|
1884
2633
|
// O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
|
|
1885
2634
|
// close is deferred releases that close per INV-FLUSH (2) BEFORE the
|
|
1886
|
-
// normalizer closes the error
|
|
2635
|
+
// normalizer closes the error.
|
|
1887
2636
|
releaseAllDeferredCloses();
|
|
1888
2637
|
ensureResponseOpen();
|
|
1889
2638
|
if (turnId === undefined)
|
|
@@ -1933,7 +2682,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1933
2682
|
switch (event.name) {
|
|
1934
2683
|
case "tool_output": {
|
|
1935
2684
|
const rawItem = event.item.rawItem;
|
|
1936
|
-
//
|
|
2685
|
+
// The 2026-07-03 SDK-bump adaptation + the fixture-drift ratchet's
|
|
1937
2686
|
// computer_call_result finding + the 0.14.0 program_output carry:
|
|
1938
2687
|
// Shell/Apply-Patch/Computer-Use/Program results do NOT share
|
|
1939
2688
|
// `OpenAIFunctionCallResultItem.output`'s shape — see
|
|
@@ -1960,7 +2709,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1960
2709
|
return;
|
|
1961
2710
|
}
|
|
1962
2711
|
// Authoritative tool-result source (canonical model, A1). Drives toolDone
|
|
1963
|
-
// with content + structuredContent (
|
|
2712
|
+
// with content + structuredContent (a reference client's cache marker — see
|
|
1964
2713
|
// `extractStructuredContent`'s doc for the two peer-supported homes and
|
|
1965
2714
|
// the playbook 2026-07-03 wire-truth findings behind them).
|
|
1966
2715
|
const outcome = rawItem.status === "incomplete" ? "error" : "ok";
|
|
@@ -1968,7 +2717,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1968
2717
|
const structuredContent = extractStructuredContent(event.item.output, event.item.customData);
|
|
1969
2718
|
// workspace#21: `customData._meta` → block `_meta`; with `_meta.ui` the
|
|
1970
2719
|
// payload is MCP-Apps view data → ALSO `uiData` (SPEC.md:332), leaving
|
|
1971
|
-
// `structuredContent` as it was (the :340 mapping;
|
|
2720
|
+
// `structuredContent` as it was (the :340 mapping; a reference client's cache marker
|
|
1972
2721
|
// rides it). §2.1's "exactly one consumer" is per channel (ruled
|
|
1973
2722
|
// option A). Mirrors claude-agent-sdk/src/index.ts:1926-1946.
|
|
1974
2723
|
const resultMeta = extractResultMeta(event.item.customData);
|
|
@@ -1982,7 +2731,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
1982
2731
|
// could misattribute it) and pass it through so toolDone binds to the
|
|
1983
2732
|
// correct — possibly already-closed-pending-this-result — turn.
|
|
1984
2733
|
const doneTurnId = resolvePendingTurnId(rawItem.callId);
|
|
1985
|
-
//
|
|
2734
|
+
// A result for a transfer call
|
|
1986
2735
|
// whose bracket is still open means that handoff never ran —
|
|
1987
2736
|
// agents-core <=0.8.0's "Multiple handoffs detected, ignoring this
|
|
1988
2737
|
// one." (0.8.0 toolExecution.mjs:750-755), the one streamed producer.
|
|
@@ -2039,7 +2788,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
2039
2788
|
// ignoring the wrapper copy here loses nothing.
|
|
2040
2789
|
return;
|
|
2041
2790
|
}
|
|
2042
|
-
//
|
|
2791
|
+
// The 2026-07-03 SDK-bump adaptation: Shell / Apply-Patch / Hosted-tool /
|
|
2043
2792
|
// Program built-ins — this run-item wrapper (not the raw stream) is
|
|
2044
2793
|
// the SOLE tool-start source for these (see `driveBuiltinToolCalled`'s
|
|
2045
2794
|
// doc).
|
|
@@ -2056,7 +2805,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
2056
2805
|
driveToolSearchOutput(event.item.rawItem);
|
|
2057
2806
|
return;
|
|
2058
2807
|
case "reasoning_item_created":
|
|
2059
|
-
// FALLBACK source
|
|
2808
|
+
// FALLBACK source (the raw terminal output fills first; an
|
|
2060
2809
|
// already-filled rs_ is a no-op) — see driveReasoningItemCreated's docstring.
|
|
2061
2810
|
driveReasoningItemCreated(event.item.rawItem);
|
|
2062
2811
|
return;
|
|
@@ -2073,7 +2822,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
2073
2822
|
// `'handoff_occurred'`). So the nested-turn lifecycle IS determinable:
|
|
2074
2823
|
// bracket the transfer with `subagentStart` now / `subagentDone` at the
|
|
2075
2824
|
// matching `handoff_occurred` below (by callId via `openHandoffs`; or at
|
|
2076
|
-
// the call's `tool_output` when the handoff never ran
|
|
2825
|
+
// the call's `tool_output` when the handoff never ran).
|
|
2077
2826
|
//
|
|
2078
2827
|
// `item.agent` (real d.ts naming) is the SOURCE agent — the one whose
|
|
2079
2828
|
// LLM call produced this handoff call — NOT the transfer target (see
|
|
@@ -2145,7 +2894,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
2145
2894
|
// still emit the `handoff` event losslessly rather than dropping the
|
|
2146
2895
|
// now-known identity (Tenet 6) — it just doesn't close anything. It
|
|
2147
2896
|
// precedes the tool.done, which may close the source round.
|
|
2148
|
-
//
|
|
2897
|
+
// The handoff is owned by the SOURCE turn, explicitly. With two
|
|
2149
2898
|
// brackets open (agents-core <=0.8.0) the engine's backfill would pick
|
|
2150
2899
|
// the last-restored nested turn; on every single-bracket stream this is
|
|
2151
2900
|
// the value the backfill gave.
|
|
@@ -2191,22 +2940,31 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
2191
2940
|
return;
|
|
2192
2941
|
}
|
|
2193
2942
|
case "tool_approval_requested": {
|
|
2194
|
-
//
|
|
2195
|
-
//
|
|
2196
|
-
//
|
|
2197
|
-
//
|
|
2198
|
-
//
|
|
2199
|
-
//
|
|
2200
|
-
// (reduce.ts R9: no accumulator mutation), so emitting the ask alone is
|
|
2201
|
-
// complete; the host/turn-close owns any pause semantics.
|
|
2943
|
+
// A human-in-the-loop approval gate on a pending tool call. `askId`
|
|
2944
|
+
// mirrors the `approval_${callId}` convention of the google-adk
|
|
2945
|
+
// facet's `requestedToolConfirmations` arm for the same
|
|
2946
|
+
// `kind:"approval"` semantics. The gated call stays pending, so a
|
|
2947
|
+
// round the stream leaves waiting on it flushes paused naming this
|
|
2948
|
+
// ask (INV-FLUSH (2)).
|
|
2202
2949
|
const item = event.item.rawItem;
|
|
2950
|
+
// The call the ask gates: a function, shell, apply-patch or computer
|
|
2951
|
+
// call's callId, else the item's id. A hosted-MCP approval request
|
|
2952
|
+
// has no callId, and its id is the request id its tool.start uses.
|
|
2953
|
+
// callId comes first, so a function approval's ask is unchanged.
|
|
2954
|
+
const gatedId = item.callId ?? item.id;
|
|
2955
|
+
if (gatedId === undefined) {
|
|
2956
|
+
// No id to key on: a collision-free derived askId (INV-BLOCK) and
|
|
2957
|
+
// no toolCallId, rather than naming a call the facet cannot find.
|
|
2958
|
+
a.emit({ type: "hitl.ask", askId: `approval_${invokeStem}_${++derivedOrdinal}`, kind: "approval" });
|
|
2959
|
+
return;
|
|
2960
|
+
}
|
|
2203
2961
|
a.emit({
|
|
2204
2962
|
type: "hitl.ask",
|
|
2205
|
-
askId: `approval_${
|
|
2963
|
+
askId: `approval_${gatedId}`,
|
|
2206
2964
|
kind: "approval",
|
|
2207
|
-
toolCallId:
|
|
2965
|
+
toolCallId: gatedId,
|
|
2208
2966
|
});
|
|
2209
|
-
askedApprovals.set(
|
|
2967
|
+
askedApprovals.set(gatedId, `approval_${gatedId}`);
|
|
2210
2968
|
return;
|
|
2211
2969
|
}
|
|
2212
2970
|
default:
|
|
@@ -2273,7 +3031,7 @@ function createInnerOpenaiNormalizer(invokeStem, threadId) {
|
|
|
2273
3031
|
flush() {
|
|
2274
3032
|
// O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
|
|
2275
3033
|
// closes FIRST — they are older rounds, so their message.end precedes the
|
|
2276
|
-
// live response's (insertion order
|
|
3034
|
+
// live response's (insertion order) — as paused / verbatim /
|
|
2277
3035
|
// message.end+usage then turn.abort (`releaseDeferredClose`); a flush
|
|
2278
3036
|
// never emits a success turn.done.
|
|
2279
3037
|
releaseAllDeferredCloses();
|