@silverprotocol/openai-agents 0.6.7 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -55,7 +55,8 @@
55
55
  * `response.function_call_arguments.done` (`arguments`/`item_id`),
56
56
  * `response.completed`/`response.incomplete` (`response.incomplete_details.reason`),
57
57
  * `response.failed` (`response.error.{message,code}` + openai-node ≥7.10.0's
58
- * `error.misalignment` block, carried verbatim as `ext.openai.misalignment`),
58
+ * `error.misalignment` block, landed as an adapter notice message whose
59
+ * text block `_meta["openai/misalignment"]` holds it verbatim — rd-15),
59
60
  * and the reasoning item `rs_…` + `encrypted_content` stateless-replay payload
60
61
  * (the `reasoning.encrypted_content` include; rides `ReasoningItem.providerData`).
61
62
  *
@@ -98,10 +99,12 @@ import {
98
99
  AgProviderMeta,
99
100
  type AgUsage,
100
101
  type AgSafety,
102
+ type AgPausedAsk,
101
103
  type AgCitation,
102
104
  JsonValue,
103
105
  type Normalizer,
104
106
  StreamAssembler,
107
+ withAtomicPush,
105
108
  type ToolOutcome,
106
109
  type TurnDoneFields,
107
110
  } from "@silverprotocol/core";
@@ -1112,6 +1115,24 @@ export function mapFinishReason(reason: string | undefined | null): AgFinishReas
1112
1115
  }
1113
1116
  }
1114
1117
 
1118
+ /**
1119
+ * OA-15 (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; sp-protocol
1120
+ * 89c57db): the `turn.done` finish fields for a native reason. `finishReason`
1121
+ * is `mapFinishReason(reason)`; `finishReasonRaw` — the native value byte for
1122
+ * byte — rides along ONLY when that mapping fell back ("other"/"unknown") AND a
1123
+ * native string exists. A real mapping (max_output_tokens → token_limit, a bare
1124
+ * completion → stop, content_filter → safety_blocked) sets nothing: the companion
1125
+ * is for a value with no AgJSON target, not a second copy of a mapped one
1126
+ * (sp-protocol's scope ruling; widening it would be a new normative sentence).
1127
+ */
1128
+ function finishReasonFields(
1129
+ reason: string | undefined | null,
1130
+ ): { finishReason: AgFinishReason; finishReasonRaw?: string } {
1131
+ const finishReason = mapFinishReason(reason);
1132
+ const isFallback = finishReason === "other" || finishReason === "unknown";
1133
+ return isFallback && typeof reason === "string" ? { finishReason, finishReasonRaw: reason } : { finishReason };
1134
+ }
1135
+
1115
1136
  // ─── tool-output content → AgBlock[] (spec §2) ────────────────────────────────
1116
1137
  function toolOutputToAgBlocks(
1117
1138
  output: OpenAIFunctionCallResultItem["output"],
@@ -1193,6 +1214,24 @@ function mapAnnotationsToCitations(
1193
1214
  // Wire names ride verbatim at the top level (the claude facet's wrapper-carry
1194
1215
  // precedent — AgProviderMeta imposes no key namespacing). Drops undefined
1195
1216
  // values; an ALL-absent input yields undefined, never an empty metadata object.
1217
+ /** PH-2 / OA-14: an OpenAI message `phase` as a vendor MARKER — a non-empty
1218
+ * string, verbatim — or `undefined`. openai-node types it
1219
+ * `'commentary' | 'final_answer' | null`; null and "" carry no marker, so they
1220
+ * yield neither a `providerMetadata.phase` carry nor an ext.openai.late-phase
1221
+ * (sp-protocol ruling (a), SPEC §10 item 26). Read through `unknown`: the
1222
+ * run-item field is envelope-only-validated wire data (JsonValue boundary). */
1223
+ function vendorPhase(value: unknown): string | undefined {
1224
+ return typeof value === "string" && value.length > 0 ? value : undefined;
1225
+ }
1226
+
1227
+ /** PH-2 (draft.4, SPEC §8.0 item 27): the first-class `phase` for an OpenAI
1228
+ * vendor marker — `"commentary"` → `"interim"`; "final_answer", absent and
1229
+ * every other value → `undefined` (a vendor spelling is never copied into
1230
+ * `phase`; it stays verbatim in `providerMetadata`). */
1231
+ function interimPhase(vendor: string | undefined): "interim" | undefined {
1232
+ return vendor === "commentary" ? "interim" : undefined;
1233
+ }
1234
+
1196
1235
  function openaiProviderMeta(fields: { [k: string]: JsonValue | undefined }): AgProviderMeta | undefined {
1197
1236
  const raw: { [k: string]: JsonValue } = {};
1198
1237
  for (const [k, v] of Object.entries(fields)) {
@@ -1378,7 +1417,61 @@ function isOpenAIStreamEvent(v: unknown): v is OpenAIStreamEvent {
1378
1417
  * genuinely unrecognisable OUTER envelope AND — per the run-item switch's default
1379
1418
  * arm — a genuinely-unknown run-item `name` (mirrors the Claude facet).
1380
1419
  */
1381
- export function createOpenaiNormalizer(): Normalizer {
1420
+ /**
1421
+ * The OpenAI Agents SDK normalizer. The inner, deterministic normalizer
1422
+ * (`createInnerOpenaiNormalizer` below) is wrapped in core's `withAtomicPush`
1423
+ * (sp-probe; sp-main's binding guard ruling, 2026-09-24). Every `push()` is
1424
+ * atomic, and none of it lives in the facet:
1425
+ * - The native is normalized with `toJsonValueSafe`, so LIVE SDK objects map
1426
+ * exactly like the JSON corpus.
1427
+ * - On a throw anywhere in the facet, this native's partial batch is
1428
+ * discarded. The inner is rebuilt from the journal of accepted natives
1429
+ * (identical state and seq; the facet never reads the clock or randomness),
1430
+ * and ONE core `error {message: "normalizer error", code: <constructor
1431
+ * name>}` takes the next seq. It carries no payload and no message text.
1432
+ * So push() never throws (SPEC.md:933), no seq is consumed by the discarded
1433
+ * batch (INV-SEQ), and no facet state ever believes a block or message is
1434
+ * open that never reached the wire.
1435
+ */
1436
+ /** Options for {@link createOpenaiNormalizer}. */
1437
+ export interface OpenaiNormalizerOptions {
1438
+ /**
1439
+ * The stem for the ids this facet mints on its own: a fallback turn (a
1440
+ * response with no `response.created`, or a host-error sentinel with no turn
1441
+ * open) is `turn_<invokeId>_<n>`, and a handoff's subagent turn is
1442
+ * `turn_<invokeId>_handoff_<n>`.
1443
+ *
1444
+ * These ids must be unique across every invoke folded into one reducer. The
1445
+ * rnd-14 ruling and INV-BLOCK's collision-free derived ids require it: guuey
1446
+ * folds a whole conversation into ONE Reducer, and a repeated turn id
1447
+ * re-opens a closed turn, which parks INV-TURN / INV-MSG consumers.
1448
+ * sp-protocol's D3 bar (wf_9722b7bc-ba9, DC-10) found the old per-normalizer
1449
+ * counters (`turn_openai_<n>`, `turn_handoff_<n>`) repeating across invokes.
1450
+ *
1451
+ * By default each normalizer draws a fresh `openai_<16 hex>` stem from
1452
+ * `crypto.getRandomValues`. It's drawn ONCE, outside the atomic inner
1453
+ * factory, so a `withAtomicPush` rebuild mints the SAME ids. Pass one to make
1454
+ * the output deterministic (replay, tests). A host that passes one MUST keep
1455
+ * it unique per invoke within a fold. Ids taken from the wire
1456
+ * (`turn_<response.id>`, `turn_resume_<callId>`) are unaffected. This mirrors
1457
+ * the vercel facet's e900d03.
1458
+ */
1459
+ invokeId?: string;
1460
+ }
1461
+
1462
+ /** 64 random bits as 16 hex chars: the default per-invoke id stem. */
1463
+ function mintInvokeNonce(): string {
1464
+ const bytes = new Uint8Array(8);
1465
+ globalThis.crypto.getRandomValues(bytes);
1466
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1467
+ }
1468
+
1469
+ export function createOpenaiNormalizer(options: OpenaiNormalizerOptions = {}): Normalizer {
1470
+ const invokeStem = options.invokeId ?? `openai_${mintInvokeNonce()}`;
1471
+ return withAtomicPush(() => createInnerOpenaiNormalizer(invokeStem));
1472
+ }
1473
+
1474
+ function createInnerOpenaiNormalizer(invokeStem: string): Normalizer {
1382
1475
  const a = new StreamAssembler();
1383
1476
  // OpenAI's native stream carries no thread/session id (unlike Claude's
1384
1477
  // `session_id`), so the threadId is a fixed facet label. The Router rebases
@@ -1407,6 +1500,16 @@ export function createOpenaiNormalizer(): Normalizer {
1407
1500
  // `ext.openai.late-phase` against lands AFTER the response closed.
1408
1501
  const pendingPhase = new Map<string, string>();
1409
1502
  const carriedPhase = new Map<string, string>();
1503
+ // PH-2 (draft.4 stage 2): text stream ids whose `text.start` already set the
1504
+ // first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
1505
+ // `text.end` fields learned for a round close that is STASHED (deferred until
1506
+ // its tool results land) — consumed by `emitRoundClose`.
1507
+ const interimAtStart = new Set<string>();
1508
+ const stashedEndFields = new Map<string, { phase?: string; providerMetadata?: AgProviderMeta }>();
1509
+ // O1 (fold/flush option 1): callId → the askId of the `hitl.ask{approval}`
1510
+ // emitted for it. A deferred round whose still-pending call has one flushes
1511
+ // as `paused` naming that ask (INV-FLUSH (2)).
1512
+ const askedApprovals = new Map<string, string>();
1410
1513
  // Close-once guard: the SDK emits `response.completed` TWICE per response. Once a
1411
1514
  // response.id (or a synthesized turnId) has been closed, any further terminal event
1412
1515
  // for it is a no-op — it must NOT reopen a fresh message/turn.
@@ -1518,12 +1621,69 @@ export function createOpenaiNormalizer(): Normalizer {
1518
1621
  * whichever values are live right now (immediate path) or were captured at
1519
1622
  * defer time (drain path) — same three calls either way.
1520
1623
  */
1624
+ /** PH-2: is `streamId`'s text.end still pending in a STASHED round close
1625
+ * (a deferred tool round), i.e. not yet emitted? */
1626
+ function isStashedTextStream(streamId: string): boolean {
1627
+ for (const stashed of stashedCloseByTurn.values()) {
1628
+ if (stashed.openTextStreamIds.includes(streamId)) return true;
1629
+ }
1630
+ return false;
1631
+ }
1632
+
1633
+ function endStashedTextStreams(mId: string, textStreamIds: readonly string[]): void {
1634
+ for (const streamId of textStreamIds) {
1635
+ // PH-2: a phase learned while this close sat stashed rides its text.end.
1636
+ const endFields = stashedEndFields.get(streamId);
1637
+ stashedEndFields.delete(streamId);
1638
+ a.textEnd(streamId, mId, endFields);
1639
+ }
1640
+ }
1641
+
1521
1642
  function emitRoundClose(tid: string, mId: string, textStreamIds: readonly string[], fields: TurnDoneFields): void {
1522
- for (const streamId of textStreamIds) a.textEnd(streamId, mId);
1643
+ endStashedTextStreams(mId, textStreamIds);
1523
1644
  a.closeMessage(mId);
1524
1645
  a.closeTurnDone(tid, fields);
1525
1646
  }
1526
1647
 
1648
+ /**
1649
+ * O1 — release a close deferred under §8.0 item 14 at END OF STREAM (flush) or
1650
+ * ahead of a host-fed error, per INV-FLUSH (2) as sp-protocol's fold/flush
1651
+ * package words it (A.5; founder: Q1 option 1, "honest flush"). A flush never
1652
+ * emits a success turn.done:
1653
+ * - an approval `hitl.ask` was emitted for a still-pending call of this
1654
+ * round ⇒ `turn.done{outcome:{type:"paused", asks}}`, with the deferred
1655
+ * finishReason and usage (the OpenAI approval interruption — the run ends
1656
+ * with no tool_output; sp-probe's live leg-1 capture);
1657
+ * - else a non-success deferred outcome (the content_filter arm) ⇒ released
1658
+ * verbatim;
1659
+ * - else ⇒ `message.end` carrying the round's usage (a per-message usage
1660
+ * carrier, so it isn't lost), then `turn.abort{stream-truncated}`.
1661
+ */
1662
+ function releaseDeferredClose(tid: string, stashed: StashedRoundClose): void {
1663
+ const asks: AgPausedAsk[] = [];
1664
+ for (const callId of pendingToolsByTurn.get(tid) ?? []) {
1665
+ const askId = askedApprovals.get(callId);
1666
+ if (askId !== undefined) asks.push({ askId, kind: "approval", toolCallId: callId });
1667
+ }
1668
+ if (asks.length > 0) {
1669
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, { ...stashed.fields, outcome: { type: "paused", asks } });
1670
+ return;
1671
+ }
1672
+ if (stashed.fields.outcome.type !== "success") {
1673
+ emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
1674
+ return;
1675
+ }
1676
+ endStashedTextStreams(stashed.msgId, stashed.openTextStreamIds);
1677
+ a.closeMessage(stashed.msgId, stashed.fields.usage);
1678
+ a.emit({ type: "turn.abort", turnId: tid, reason: "stream-truncated" });
1679
+ }
1680
+
1681
+ /** O1: release every deferred close (insertion order: older rounds first). */
1682
+ function releaseAllDeferredCloses(): void {
1683
+ for (const [tid, stashed] of stashedCloseByTurn) releaseDeferredClose(tid, stashed);
1684
+ stashedCloseByTurn.clear();
1685
+ }
1686
+
1527
1687
  /**
1528
1688
  * Close the round now, unless `tid`'s pending-tool set is non-empty — in
1529
1689
  * which case stash everything the close needs (message id, dangling text
@@ -1556,10 +1716,17 @@ export function createOpenaiNormalizer(): Normalizer {
1556
1716
  if (turnId !== undefined) {
1557
1717
  // Backfill the real id if it arrives after a defensive synthesized open.
1558
1718
  if (respId !== undefined && responseId === undefined) responseId = respId;
1719
+ // A resumed invoke's turn (`openTurnForLeadingResult`) opens with no
1720
+ // assistant message: the resumed response opens it here, AFTER the
1721
+ // leading tool result's own message, so the fold stays chronological.
1722
+ if (msgId === undefined) {
1723
+ msgId = `msg_${turnId}`;
1724
+ a.openMessage({ id: msgId, role: "assistant", turnId, threadId, ...(model !== undefined ? { model } : {}) });
1725
+ }
1559
1726
  return responseId ?? turnId;
1560
1727
  }
1561
1728
  responseId = respId;
1562
- turnId = respId !== undefined ? `turn_${respId}` : `turn_${threadId}_${++turnCounter}`;
1729
+ turnId = respId !== undefined ? `turn_${respId}` : `turn_${invokeStem}_${++turnCounter}`;
1563
1730
  msgId = `msg_${turnId}`;
1564
1731
  // Task 3 (audit M48 review, Finding 1): survives resetResponseState() —
1565
1732
  // see the closure-state doc above.
@@ -1569,6 +1736,60 @@ export function createOpenaiNormalizer(): Normalizer {
1569
1736
  return responseId ?? turnId;
1570
1737
  }
1571
1738
 
1739
+ /**
1740
+ * INV-TURN (SPEC:743) for a RESUMED invoke — sp-protocol's c20 package, A.6
1741
+ * (openai): when a tool result's round is unknown to this invoke
1742
+ * (`resolvePendingTurnId` misses) and no response is open, the result is the
1743
+ * resumed stream's LEADING event (sp-probe's live approval-resume capture,
1744
+ * 2026-09-24: after `RunState.fromString` + approve/reject, the approved or
1745
+ * rejected call's `tool_output` arrives before any `response.created`). Open a
1746
+ * turn for it — `turn_resume_<callId>`: deterministic, and never a leg-1
1747
+ * `turn_resp_*` id (INV-XINV) — and land the result as its OWN role:"tool"
1748
+ * message (`messageId: "<callId>:result"`). The resumed model response then
1749
+ * opens its assistant message in this same turn (`ensureResponseOpen`) and its
1750
+ * response.completed closes it. Returns the toolDone fields, or `undefined`
1751
+ * when the result joins a known round or an open response (unchanged).
1752
+ */
1753
+ function openTurnForLeadingResult(callId: string): { turnId: string; messageId: string } | undefined {
1754
+ if (turnId === undefined) {
1755
+ const opened = `turn_resume_${callId}`;
1756
+ turnId = opened;
1757
+ lastTopLevelTurnId = opened;
1758
+ a.openTurn(opened, threadId);
1759
+ return { turnId: opened, messageId: `${callId}:result` };
1760
+ }
1761
+ // Approve-all (sp-protocol's D3 pin, 2026-09-24): the resuming invoke can
1762
+ // replay SEVERAL results before its response. While the resume turn is
1763
+ // open with no assistant message yet (turnId set, msgId unset — a state
1764
+ // only this helper creates), each further result joins THAT turn as its
1765
+ // own role:"tool" message; no second turn opens.
1766
+ if (msgId === undefined) return { turnId, messageId: `${callId}:result` };
1767
+ return undefined;
1768
+ }
1769
+
1770
+ /** rd-15: the misalignment notice (see the `response.failed` arm). */
1771
+ function emitMisalignmentNotice(
1772
+ responseIdForNotice: string,
1773
+ tid: string,
1774
+ misalignment: { readonly [k: string]: JsonValue },
1775
+ errorMessage: string | undefined,
1776
+ ): void {
1777
+ const noticeId = `notice_misalignment_${responseIdForNotice}`;
1778
+ const textId = `${noticeId}_text`;
1779
+ const explanation = misalignment.detailed_explanation;
1780
+ const text = typeof explanation === "string" && explanation.length > 0 ? explanation : (errorMessage ?? "");
1781
+ a.openMessage({ id: noticeId, role: "notice", noticeSource: "adapter", turnId: tid, threadId });
1782
+ a.emit({
1783
+ type: "text.start",
1784
+ id: textId,
1785
+ messageId: noticeId,
1786
+ _meta: AgMeta.parse({ "openai/misalignment": JsonValue.parse(misalignment) }),
1787
+ });
1788
+ if (text.length > 0) a.textDelta(textId, noticeId, text);
1789
+ a.textEnd(textId, noticeId);
1790
+ a.closeMessage(noticeId);
1791
+ }
1792
+
1572
1793
  /** Reset per-response state after a close. Marks the response closed (close-once). */
1573
1794
  function resetResponseState(): void {
1574
1795
  const key = responseId ?? turnId;
@@ -1620,14 +1841,19 @@ export function createOpenaiNormalizer(): Normalizer {
1620
1841
  // (rnd 13+17 Stage 1, founder ruling 2026-09-23; vercel parity c4f5981).
1621
1842
  const phase = pendingPhase.get(ev.item_id);
1622
1843
  const startMeta = openaiProviderMeta({ phase });
1844
+ // PH-2 (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
1845
+ // the first delta ⇒ the first-class `phase` goes on text.start.
1846
+ const interim = interimPhase(phase);
1623
1847
  a.textStart(ev.item_id, msgId, {
1624
1848
  role: "assistant",
1625
1849
  ...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
1850
+ ...(interim !== undefined ? { phase: interim } : {}),
1626
1851
  });
1627
1852
  if (phase !== undefined) {
1628
1853
  pendingPhase.delete(ev.item_id);
1629
1854
  carriedPhase.set(ev.item_id, phase);
1630
1855
  }
1856
+ if (interim !== undefined) interimAtStart.add(ev.item_id);
1631
1857
  }
1632
1858
  // OpenAI text deltas are suffix-only fragments (cumulative:false, the default).
1633
1859
  a.textDelta(ev.item_id, msgId, ev.delta, { cumulative: false });
@@ -1797,7 +2023,7 @@ export function createOpenaiNormalizer(): Normalizer {
1797
2023
  const safety: AgSafety[] = [{ category: "content_filter", blocked: true }];
1798
2024
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1799
2025
  outcome: { type: "error", message: "content_filter" },
1800
- finishReason: mapFinishReason(reason),
2026
+ ...finishReasonFields(reason),
1801
2027
  safety,
1802
2028
  ...(usage !== undefined ? { usage } : {}),
1803
2029
  });
@@ -1843,7 +2069,8 @@ export function createOpenaiNormalizer(): Normalizer {
1843
2069
  } else {
1844
2070
  finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
1845
2071
  outcome: { type: "success" },
1846
- finishReason: mapFinishReason(reason),
2072
+ // OA-15: an unmapped native reason also carries finishReasonRaw.
2073
+ ...finishReasonFields(reason),
1847
2074
  ...(usage !== undefined ? { usage } : {}),
1848
2075
  });
1849
2076
  }
@@ -1857,21 +2084,24 @@ export function createOpenaiNormalizer(): Normalizer {
1857
2084
  endOpenStreamsAndCloseMessage();
1858
2085
  const err = ev.response.error;
1859
2086
  // openai-node ≥7.10.0: `error.misalignment` (classification + public
1860
- // explanation + `steer.message` continuation instruction) would otherwise
1861
- // be silently dropped — `turn.error` carries only message/code/usage
1862
- // (spec §4 gives it no providerMetadata slot), so the block rides the
1863
- // lossless vendor channel, turn-scoped, immediately BEFORE the closing
1864
- // turn.error it annotates. Carried VERBATIM (wire names, whole object;
1865
- // no AgSafety mapping — carry only). Absent ⇒ no event (byte-identical
1866
- // to the pre-7.10.0 output). The isJsonObject guard keeps a malformed
1867
- // non-object wire value away from JsonValue.parse (push() never throws).
2087
+ // explanation + `steer.message` continuation instruction). `turn.error`
2088
+ // carries only message/code/usage (spec §4), so rd-15 (sp-protocol's
2089
+ // package A.6; founder: rides 0.7.0; sp-cto: the carry must sit in a
2090
+ // home that FOLDS) lands it as an adapter NOTICE message immediately
2091
+ // BEFORE the closing turn.error, in this turn:
2092
+ // message.start {role:"notice", noticeSource:"adapter"} →
2093
+ // one text block, text = `detailed_explanation` verbatim (else
2094
+ // error.message), text.start `_meta["openai/misalignment"]` = the
2095
+ // WHOLE object verbatim (wire names, steer, unknown keys) →
2096
+ // message.end.
2097
+ // It folds (a notice row + its block `_meta`), so it is readable and
2098
+ // durable. The former live-only ext.openai.misalignment carry is
2099
+ // RETIRED (the item-21 one-carrier precedent; no consumer read it).
2100
+ // Absent or non-object ⇒ nothing new (byte-identical to the pre-7.10.0
2101
+ // output); the isJsonObject guard keeps a malformed wire value away
2102
+ // from JsonValue.parse.
1868
2103
  const misalignment = err?.misalignment;
1869
- if (isJsonObject(misalignment)) {
1870
- a.emitExt("openai", "misalignment", {
1871
- responseId: ev.response.id,
1872
- misalignment: JsonValue.parse(misalignment),
1873
- });
1874
- }
2104
+ if (isJsonObject(misalignment)) emitMisalignmentNotice(ev.response.id, turnId, misalignment, err?.message);
1875
2105
  a.closeTurnError(turnId, {
1876
2106
  message: err?.message ?? "response.failed",
1877
2107
  ...(err?.code !== undefined ? { code: err.code } : {}),
@@ -2034,8 +2264,26 @@ export function createOpenaiNormalizer(): Normalizer {
2034
2264
  // OA-14: RETIRED when this id's SAME phase already rode its text.start
2035
2265
  // (the live case); kept — lossless — when only the run-item knows it,
2036
2266
  // or knows a different value.
2037
- if (item.phase !== undefined && carriedPhase.get(item.id) !== item.phase) {
2038
- a.emitExt("openai", "late-phase", { itemId: item.id, phase: item.phase });
2267
+ // PH-2: null/"" is no marker at all (sp-protocol ruling (a)) — neither
2268
+ // a carry nor a late-phase ext.
2269
+ const lateItemPhase = vendorPhase(item.phase);
2270
+ if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
2271
+ if (isStashedTextStream(item.id)) {
2272
+ // PH-2 case (ii): the round close is STASHED (a deferred tool
2273
+ // round), so this block's text.end is NOT yet emitted — the §5
2274
+ // timing rule makes the end the phase's home (sp-protocol,
2275
+ // 2026-09-23). The marker has a first-class home, so no late-phase.
2276
+ const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
2277
+ const endMeta = openaiProviderMeta({ phase: lateItemPhase });
2278
+ stashedEndFields.set(item.id, {
2279
+ ...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
2280
+ ...(interim !== undefined ? { phase: interim } : {}),
2281
+ });
2282
+ } else {
2283
+ // Case (iii): this block's text.end is already out — never a
2284
+ // second end; the vendor marker rides the lossless ext.
2285
+ a.emitExt("openai", "late-phase", { itemId: item.id, phase: lateItemPhase });
2286
+ }
2039
2287
  }
2040
2288
  continue;
2041
2289
  }
@@ -2050,14 +2298,19 @@ export function createOpenaiNormalizer(): Normalizer {
2050
2298
  // message, and a program-driven turn emits multiple message items with
2051
2299
  // DIFFERENT phases (commentary vs final_answer) whose message-level
2052
2300
  // merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
2053
- const phaseMeta = openaiProviderMeta({ phase: item.phase });
2301
+ const itemPhase = vendorPhase(item.phase);
2302
+ const phaseMeta = openaiProviderMeta({ phase: itemPhase });
2303
+ // PH-2 case (i): known before this block's text.end ⇒ the end carries
2304
+ // the first-class phase, unless text.start already did.
2305
+ const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
2054
2306
  a.textEnd(
2055
2307
  streamId,
2056
2308
  msgId,
2057
- citations !== undefined || phaseMeta !== undefined
2309
+ citations !== undefined || phaseMeta !== undefined || endInterim !== undefined
2058
2310
  ? {
2059
2311
  ...(citations !== undefined ? { citations } : {}),
2060
2312
  ...(phaseMeta !== undefined ? { providerMetadata: phaseMeta } : {}),
2313
+ ...(endInterim !== undefined ? { phase: endInterim } : {}),
2061
2314
  }
2062
2315
  : undefined,
2063
2316
  );
@@ -2344,7 +2597,7 @@ export function createOpenaiNormalizer(): Normalizer {
2344
2597
  isError: outcome === "error",
2345
2598
  ...(structuredContent !== undefined ? { structuredContent } : {}),
2346
2599
  ...(providerMetadata !== undefined ? { providerMetadata } : {}),
2347
- ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
2600
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(toolCallId) ?? {})),
2348
2601
  });
2349
2602
  drainPendingTool(toolCallId, doneTurnId);
2350
2603
  }
@@ -2605,7 +2858,7 @@ export function createOpenaiNormalizer(): Normalizer {
2605
2858
  content,
2606
2859
  outcome: "ok",
2607
2860
  ...(searchMeta !== undefined ? { providerMetadata: searchMeta } : {}),
2608
- ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
2861
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(toolCallId) ?? {})),
2609
2862
  });
2610
2863
  drainPendingTool(toolCallId, doneTurnId);
2611
2864
  }
@@ -2623,6 +2876,10 @@ export function createOpenaiNormalizer(): Normalizer {
2623
2876
  * a turn that has a `turn.start`.
2624
2877
  */
2625
2878
  function driveHostError(event: OpenAIHostError): void {
2879
+ // O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
2880
+ // close is deferred releases that close per INV-FLUSH (2) BEFORE the
2881
+ // normalizer closes the error (PS-21).
2882
+ releaseAllDeferredCloses();
2626
2883
  ensureResponseOpen();
2627
2884
  if (turnId === undefined) return; // unreachable post-ensure; satisfies narrowing
2628
2885
  endOpenStreamsAndCloseMessage();
@@ -2703,7 +2960,7 @@ export function createOpenaiNormalizer(): Normalizer {
2703
2960
  ...(uiData !== undefined ? { uiData } : {}),
2704
2961
  ...(resultMeta !== undefined ? { _meta: resultMeta } : {}),
2705
2962
  ...(doneMeta !== undefined ? { providerMetadata: doneMeta } : {}),
2706
- ...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
2963
+ ...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(rawItem.callId) ?? {})),
2707
2964
  });
2708
2965
  drainPendingTool(rawItem.callId, doneTurnId);
2709
2966
  return;
@@ -2772,7 +3029,7 @@ export function createOpenaiNormalizer(): Normalizer {
2772
3029
  // EVENT carve-out), emitted once it's actually known — paired with
2773
3030
  // `subagentDone` in the `handoff_occurred` case below.
2774
3031
  const ordinal = ++handoffOrdinal;
2775
- const handoffTurnId = `turn_handoff_${ordinal}`;
3032
+ const handoffTurnId = `turn_${invokeStem}_handoff_${ordinal}`;
2776
3033
  const parentTurnId = lastTopLevelTurnId ?? threadId;
2777
3034
  openHandoffs.push({ turnId: handoffTurnId, parentTurnId });
2778
3035
  a.subagentStart(handoffTurnId, parentTurnId);
@@ -2789,15 +3046,48 @@ export function createOpenaiNormalizer(): Normalizer {
2789
3046
  // this seam, unlike google-adk's per-message agentId/agentName).
2790
3047
  const item = event.item;
2791
3048
  const open = openHandoffs.shift(); // FIFO — see openHandoffs' doc.
2792
- if (open !== undefined) a.subagentDone(open.turnId, open.parentTurnId);
3049
+ if (open !== undefined) {
3050
+ // draft.4 nested-run closure (§8.0 item 29, §10 item 36; sp-protocol's
3051
+ // nested-turn package A.6): the bracket closes with its own terminal,
3052
+ // immediately followed by `subagent.done`. `handoff_occurred` IS the
3053
+ // SDK's report that the transfer ran (the handoff span closed and the
3054
+ // new agent resolved), so success; the SDK reports no finish reason
3055
+ // for it ("unknown") and no usage (the top-level round carries the spend).
3056
+ a.closeTurnDone(open.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
3057
+ a.subagentDone(open.turnId, open.parentTurnId);
3058
+ }
3059
+ // HO (0.7.0 regression, sp-probe's live handoff-gpt6sol): the transfer is
3060
+ // an ordinary function_call the model emitted (tool.start from
3061
+ // `response.output_item.added`, registered pending), and THIS item's
3062
+ // rawItem is its result — the SDK never sends a `tool_output` for it.
3063
+ // Land it as that call's tool.done, routed exactly as the tool_output
3064
+ // arm routes a function result, so the pending set drains and the
3065
+ // source round's deferred close (§8.0 item 14) emits here as its real
3066
+ // turn.done, not as O1's flush-time turn.abort. A resumed invoke can
3067
+ // deliver this for a call started in the interrupted invoke
3068
+ // (agents-core 0.18.0 `resolveInterruptedTurn` runs the response's
3069
+ // pending handoffs): that leading result opens its resume turn FIRST,
3070
+ // so the `handoff` event below lands in the same turn as the result.
3071
+ const result = item.rawItem;
3072
+ const doneTurnId = resolvePendingTurnId(result.callId);
3073
+ const owner = doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(result.callId) ?? {});
2793
3074
  // Defensive orphan (no open bracket — e.g. a resumed/truncated stream):
2794
3075
  // still emit the `handoff` event losslessly rather than dropping the
2795
- // now-known identity (Tenet 6) — it just doesn't close anything.
3076
+ // now-known identity (Tenet 6) — it just doesn't close anything. It
3077
+ // precedes the tool.done, which may close the source round.
2796
3078
  a.emit({
2797
3079
  type: "handoff",
2798
3080
  kind: "transfer",
2799
3081
  toAgentName: item.targetAgent.name,
2800
3082
  });
3083
+ a.toolDone({
3084
+ toolCallId: result.callId,
3085
+ content: toolOutputToAgBlocks(result.output),
3086
+ outcome: result.status === "incomplete" ? "error" : "ok",
3087
+ isError: result.status === "incomplete",
3088
+ ...owner,
3089
+ });
3090
+ drainPendingTool(result.callId, doneTurnId);
2801
3091
  return;
2802
3092
  }
2803
3093
  case "compaction_item_created": {
@@ -2839,6 +3129,7 @@ export function createOpenaiNormalizer(): Normalizer {
2839
3129
  kind: "approval",
2840
3130
  toolCallId: item.callId,
2841
3131
  });
3132
+ askedApprovals.set(item.callId, `approval_${item.callId}`);
2842
3133
  return;
2843
3134
  }
2844
3135
  default:
@@ -2881,30 +3172,41 @@ export function createOpenaiNormalizer(): Normalizer {
2881
3172
 
2882
3173
  return {
2883
3174
  push(native: JsonValue): AgEvent[] {
3175
+ // LV: a host may push the SDK's LIVE stream objects (undefined members,
3176
+ // Dates, class instances, cycles), not the JSON round-tripped shape the
3177
+ // corpus records, and the carried-member `JsonValue.parse` sites threw a
3178
+ // ZodError on them (sp-main's no-throw check, 2026-09-24: 6 of 9 live
3179
+ // shapes). The native arrives already normalized: `withAtomicPush` ran core's
3180
+ // `toJsonValueSafe` on it (JSON semantics per node: toJSON honoured,
3181
+ // undefined dropped, Date → ISO string), and it owns the no-throw
3182
+ // guarantee too. This inner push MUST NOT catch; a throw here is the
3183
+ // wrapper's signal to discard the batch and rebuild.
2884
3184
  if (!isOpenAIStreamEvent(native)) {
2885
3185
  // Graceful guard (Tenet 6): route a genuinely unrecognisable payload through
2886
3186
  // the lossless vendor channel rather than throwing. Nest under `native` so a
2887
3187
  // payload carrying its own `type` key does NOT clobber the event type.
2888
- a.emitExt("openai", "unparsed", { native });
3188
+ // A COPY via JsonValue.parse, like every other carry path: plain input
3189
+ // arrives by reference, so carrying it as-is would alias the host's
3190
+ // object into an emitted event, and would forward an own `__proto__`
3191
+ // key (sp-cto's checks, 2026-09-24).
3192
+ a.emitExt("openai", "unparsed", { native: JsonValue.parse(native) });
2889
3193
  return a.drain();
2890
3194
  }
2891
3195
  drive(native);
2892
3196
  return a.drain();
2893
3197
  },
2894
3198
  flush(): AgEvent[] {
2895
- // Close any dangling open response (e.g. a stream that ended before
2896
- // response.completed) — unrelated to Task 4b: that round never reached a
2897
- // native close signal at all, so it has no stashed closeTurnDone.
3199
+ // O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
3200
+ // closes FIRST — they are older rounds, so their message.end precedes the
3201
+ // live response's (insertion order, CB-16) — as paused / verbatim /
3202
+ // message.end+usage then turn.abort (`releaseDeferredClose`); a flush
3203
+ // never emits a success turn.done.
3204
+ releaseAllDeferredCloses();
3205
+ // Then close any dangling open response (a stream that ended before
3206
+ // response.completed): its message ends here and the engine's flush
3207
+ // aborts its turn as stream-truncated.
2898
3208
  if (turnId !== undefined) closeResponse();
2899
- // Task 4b: emit any still-stashed closes BEFORE delegating to the engine's
2900
- // flush. Each stashed round genuinely completed on the wire — a tool
2901
- // result that never arrives must not swallow that close (message.end +
2902
- // turn.done both replay here, verbatim, in the order INV-MSG requires).
2903
- for (const [tid, stashed] of stashedCloseByTurn) {
2904
- emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
2905
- }
2906
- stashedCloseByTurn.clear();
2907
- // Flush the engine's dangling open messages (I7).
3209
+ // Flush the engine's dangling open messages / turns (I7).
2908
3210
  return a.flush();
2909
3211
  },
2910
3212
  };