@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/README.md +33 -1
- package/dist/index.d.ts +44 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +291 -91
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +345 -43
package/dist/index.js
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,
|
|
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
|
*
|
|
@@ -90,7 +91,7 @@
|
|
|
90
91
|
* - `response.inject.created`/`.failed` (hosted multi-agent lifecycle):
|
|
91
92
|
* verified immaterial — client-initiated echo, no content loss.
|
|
92
93
|
*/
|
|
93
|
-
import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
|
|
94
|
+
import { AgMeta, AgProviderMeta, JsonValue, StreamAssembler, withAtomicPush, } from "@silverprotocol/core";
|
|
94
95
|
/**
|
|
95
96
|
* OA-11: extract the reasoning items from a terminal event's `response.output`.
|
|
96
97
|
* This — not `response.output_item.done` — is the replayable source: OpenAI
|
|
@@ -164,6 +165,21 @@ export function mapFinishReason(reason) {
|
|
|
164
165
|
return "unknown";
|
|
165
166
|
}
|
|
166
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* OA-15 (draft.4 — SPEC.md §8.0 graceful degradation, §10 item 23; sp-protocol
|
|
170
|
+
* 89c57db): the `turn.done` finish fields for a native reason. `finishReason`
|
|
171
|
+
* is `mapFinishReason(reason)`; `finishReasonRaw` — the native value byte for
|
|
172
|
+
* byte — rides along ONLY when that mapping fell back ("other"/"unknown") AND a
|
|
173
|
+
* native string exists. A real mapping (max_output_tokens → token_limit, a bare
|
|
174
|
+
* completion → stop, content_filter → safety_blocked) sets nothing: the companion
|
|
175
|
+
* is for a value with no AgJSON target, not a second copy of a mapped one
|
|
176
|
+
* (sp-protocol's scope ruling; widening it would be a new normative sentence).
|
|
177
|
+
*/
|
|
178
|
+
function finishReasonFields(reason) {
|
|
179
|
+
const finishReason = mapFinishReason(reason);
|
|
180
|
+
const isFallback = finishReason === "other" || finishReason === "unknown";
|
|
181
|
+
return isFallback && typeof reason === "string" ? { finishReason, finishReasonRaw: reason } : { finishReason };
|
|
182
|
+
}
|
|
167
183
|
// ─── tool-output content → AgBlock[] (spec §2) ────────────────────────────────
|
|
168
184
|
function toolOutputToAgBlocks(output) {
|
|
169
185
|
if (typeof output === "string") {
|
|
@@ -245,6 +261,22 @@ function mapAnnotationsToCitations(annotations, partText) {
|
|
|
245
261
|
// Wire names ride verbatim at the top level (the claude facet's wrapper-carry
|
|
246
262
|
// precedent — AgProviderMeta imposes no key namespacing). Drops undefined
|
|
247
263
|
// values; an ALL-absent input yields undefined, never an empty metadata object.
|
|
264
|
+
/** PH-2 / OA-14: an OpenAI message `phase` as a vendor MARKER — a non-empty
|
|
265
|
+
* string, verbatim — or `undefined`. openai-node types it
|
|
266
|
+
* `'commentary' | 'final_answer' | null`; null and "" carry no marker, so they
|
|
267
|
+
* yield neither a `providerMetadata.phase` carry nor an ext.openai.late-phase
|
|
268
|
+
* (sp-protocol ruling (a), SPEC §10 item 26). Read through `unknown`: the
|
|
269
|
+
* run-item field is envelope-only-validated wire data (JsonValue boundary). */
|
|
270
|
+
function vendorPhase(value) {
|
|
271
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
272
|
+
}
|
|
273
|
+
/** PH-2 (draft.4, SPEC §8.0 item 27): the first-class `phase` for an OpenAI
|
|
274
|
+
* vendor marker — `"commentary"` → `"interim"`; "final_answer", absent and
|
|
275
|
+
* every other value → `undefined` (a vendor spelling is never copied into
|
|
276
|
+
* `phase`; it stays verbatim in `providerMetadata`). */
|
|
277
|
+
function interimPhase(vendor) {
|
|
278
|
+
return vendor === "commentary" ? "interim" : undefined;
|
|
279
|
+
}
|
|
248
280
|
function openaiProviderMeta(fields) {
|
|
249
281
|
const raw = {};
|
|
250
282
|
for (const [k, v] of Object.entries(fields)) {
|
|
@@ -381,53 +413,17 @@ function isOpenAIStreamEvent(v) {
|
|
|
381
413
|
return typeof v.code === "string" && typeof v.message === "string";
|
|
382
414
|
return false;
|
|
383
415
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
* model, plan §"Spike Findings") and ignores the rest:
|
|
396
|
-
*
|
|
397
|
-
* - turn open ← `model:response.created` (real `response.id` present at start)
|
|
398
|
-
* - text ← `model:response.output_text.delta` (carries `item_id`)
|
|
399
|
-
* - text end ← the `message_output_created` run-item (authoritative close +
|
|
400
|
-
* citations carrier, audit M22 — `response.output_text.done` is a
|
|
401
|
-
* no-op; text streams left open by it fall to the defensive
|
|
402
|
-
* close-any-dangling-stream fallback in `closeResponse()` /
|
|
403
|
-
* `endOpenStreamsAndCloseMessage()` / `emitRoundClose()`)
|
|
404
|
-
* - reasoning ← opens at `model:response.output_item.added{reasoning}` (wire
|
|
405
|
-
* position), filled from the `model:response.completed` /
|
|
406
|
-
* `.incomplete` `response.output` (OA-11 — the final, replayable
|
|
407
|
-
* `encrypted_content`); `reasoning_item_created` is the fallback
|
|
408
|
-
* - turn close ← `model:response.completed` (guard close-once)
|
|
409
|
-
*
|
|
410
|
-
* `ensureResponseOpen()` opens turn + message exactly once per response;
|
|
411
|
-
* `closeResponse()` resets per-response state so the duplicate `response.completed`
|
|
412
|
-
* is a no-op.
|
|
413
|
-
*
|
|
414
|
-
* `reasoning_item_created` / `tool_approval_requested` (Task 3, audit M48) map to
|
|
415
|
-
* `reasoning.start/delta/end/opaque` and `hitl.ask{kind:"approval"}` respectively —
|
|
416
|
-
* see `driveReasoningItemCreated` and the run-item switch below for the full
|
|
417
|
-
* rationale. `handoff_requested` / `handoff_occurred` (Task 3, audit M48 review
|
|
418
|
-
* Finding 1) map to a `subagentStart`/`subagentDone` PAIR bracketing the transfer —
|
|
419
|
-
* the ORIGINAL Task-3 mapping used a standalone `handoff` event on the false premise
|
|
420
|
-
* that the wire carried no completion signal; `handoff_occurred` IS that signal
|
|
421
|
-
* (verified against the installed `@openai/agents-core` 0.2.1 peer dep's
|
|
422
|
-
* `events.d.ts`). The bare `handoff` event still fires — carrying `toAgentName` —
|
|
423
|
-
* but only once it's actually known, at `handoff_occurred` (the target agent is not
|
|
424
|
-
* resolvable at `handoff_requested` time on the real wire; see the run-item switch's
|
|
425
|
-
* `handoff_requested`/`handoff_occurred` cases for the full rationale, including why
|
|
426
|
-
* identity can't ride the `subagentStart` call itself). `emitExt` is reserved for a
|
|
427
|
-
* genuinely unrecognisable OUTER envelope AND — per the run-item switch's default
|
|
428
|
-
* arm — a genuinely-unknown run-item `name` (mirrors the Claude facet).
|
|
429
|
-
*/
|
|
430
|
-
export function createOpenaiNormalizer() {
|
|
416
|
+
/** 64 random bits as 16 hex chars: the default per-invoke id stem. */
|
|
417
|
+
function mintInvokeNonce() {
|
|
418
|
+
const bytes = new Uint8Array(8);
|
|
419
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
420
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
421
|
+
}
|
|
422
|
+
export function createOpenaiNormalizer(options = {}) {
|
|
423
|
+
const invokeStem = options.invokeId ?? `openai_${mintInvokeNonce()}`;
|
|
424
|
+
return withAtomicPush(() => createInnerOpenaiNormalizer(invokeStem));
|
|
425
|
+
}
|
|
426
|
+
function createInnerOpenaiNormalizer(invokeStem) {
|
|
431
427
|
const a = new StreamAssembler();
|
|
432
428
|
// OpenAI's native stream carries no thread/session id (unlike Claude's
|
|
433
429
|
// `session_id`), so the threadId is a fixed facet label. The Router rebases
|
|
@@ -455,6 +451,16 @@ export function createOpenaiNormalizer() {
|
|
|
455
451
|
// `ext.openai.late-phase` against lands AFTER the response closed.
|
|
456
452
|
const pendingPhase = new Map();
|
|
457
453
|
const carriedPhase = new Map();
|
|
454
|
+
// PH-2 (draft.4 stage 2): text stream ids whose `text.start` already set the
|
|
455
|
+
// first-class `phase:"interim"` (so no `*.end` repeats it), and per-stream
|
|
456
|
+
// `text.end` fields learned for a round close that is STASHED (deferred until
|
|
457
|
+
// its tool results land) — consumed by `emitRoundClose`.
|
|
458
|
+
const interimAtStart = new Set();
|
|
459
|
+
const stashedEndFields = new Map();
|
|
460
|
+
// O1 (fold/flush option 1): callId → the askId of the `hitl.ask{approval}`
|
|
461
|
+
// emitted for it. A deferred round whose still-pending call has one flushes
|
|
462
|
+
// as `paused` naming that ask (INV-FLUSH (2)).
|
|
463
|
+
const askedApprovals = new Map();
|
|
458
464
|
// Close-once guard: the SDK emits `response.completed` TWICE per response. Once a
|
|
459
465
|
// response.id (or a synthesized turnId) has been closed, any further terminal event
|
|
460
466
|
// for it is a no-op — it must NOT reopen a fresh message/turn.
|
|
@@ -546,12 +552,67 @@ export function createOpenaiNormalizer() {
|
|
|
546
552
|
* whichever values are live right now (immediate path) or were captured at
|
|
547
553
|
* defer time (drain path) — same three calls either way.
|
|
548
554
|
*/
|
|
555
|
+
/** PH-2: is `streamId`'s text.end still pending in a STASHED round close
|
|
556
|
+
* (a deferred tool round), i.e. not yet emitted? */
|
|
557
|
+
function isStashedTextStream(streamId) {
|
|
558
|
+
for (const stashed of stashedCloseByTurn.values()) {
|
|
559
|
+
if (stashed.openTextStreamIds.includes(streamId))
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
function endStashedTextStreams(mId, textStreamIds) {
|
|
565
|
+
for (const streamId of textStreamIds) {
|
|
566
|
+
// PH-2: a phase learned while this close sat stashed rides its text.end.
|
|
567
|
+
const endFields = stashedEndFields.get(streamId);
|
|
568
|
+
stashedEndFields.delete(streamId);
|
|
569
|
+
a.textEnd(streamId, mId, endFields);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
549
572
|
function emitRoundClose(tid, mId, textStreamIds, fields) {
|
|
550
|
-
|
|
551
|
-
a.textEnd(streamId, mId);
|
|
573
|
+
endStashedTextStreams(mId, textStreamIds);
|
|
552
574
|
a.closeMessage(mId);
|
|
553
575
|
a.closeTurnDone(tid, fields);
|
|
554
576
|
}
|
|
577
|
+
/**
|
|
578
|
+
* O1 — release a close deferred under §8.0 item 14 at END OF STREAM (flush) or
|
|
579
|
+
* ahead of a host-fed error, per INV-FLUSH (2) as sp-protocol's fold/flush
|
|
580
|
+
* package words it (A.5; founder: Q1 option 1, "honest flush"). A flush never
|
|
581
|
+
* emits a success turn.done:
|
|
582
|
+
* - an approval `hitl.ask` was emitted for a still-pending call of this
|
|
583
|
+
* round ⇒ `turn.done{outcome:{type:"paused", asks}}`, with the deferred
|
|
584
|
+
* finishReason and usage (the OpenAI approval interruption — the run ends
|
|
585
|
+
* with no tool_output; sp-probe's live leg-1 capture);
|
|
586
|
+
* - else a non-success deferred outcome (the content_filter arm) ⇒ released
|
|
587
|
+
* verbatim;
|
|
588
|
+
* - else ⇒ `message.end` carrying the round's usage (a per-message usage
|
|
589
|
+
* carrier, so it isn't lost), then `turn.abort{stream-truncated}`.
|
|
590
|
+
*/
|
|
591
|
+
function releaseDeferredClose(tid, stashed) {
|
|
592
|
+
const asks = [];
|
|
593
|
+
for (const callId of pendingToolsByTurn.get(tid) ?? []) {
|
|
594
|
+
const askId = askedApprovals.get(callId);
|
|
595
|
+
if (askId !== undefined)
|
|
596
|
+
asks.push({ askId, kind: "approval", toolCallId: callId });
|
|
597
|
+
}
|
|
598
|
+
if (asks.length > 0) {
|
|
599
|
+
emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, { ...stashed.fields, outcome: { type: "paused", asks } });
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
if (stashed.fields.outcome.type !== "success") {
|
|
603
|
+
emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
endStashedTextStreams(stashed.msgId, stashed.openTextStreamIds);
|
|
607
|
+
a.closeMessage(stashed.msgId, stashed.fields.usage);
|
|
608
|
+
a.emit({ type: "turn.abort", turnId: tid, reason: "stream-truncated" });
|
|
609
|
+
}
|
|
610
|
+
/** O1: release every deferred close (insertion order: older rounds first). */
|
|
611
|
+
function releaseAllDeferredCloses() {
|
|
612
|
+
for (const [tid, stashed] of stashedCloseByTurn)
|
|
613
|
+
releaseDeferredClose(tid, stashed);
|
|
614
|
+
stashedCloseByTurn.clear();
|
|
615
|
+
}
|
|
555
616
|
/**
|
|
556
617
|
* Close the round now, unless `tid`'s pending-tool set is non-empty — in
|
|
557
618
|
* which case stash everything the close needs (message id, dangling text
|
|
@@ -585,10 +646,17 @@ export function createOpenaiNormalizer() {
|
|
|
585
646
|
// Backfill the real id if it arrives after a defensive synthesized open.
|
|
586
647
|
if (respId !== undefined && responseId === undefined)
|
|
587
648
|
responseId = respId;
|
|
649
|
+
// A resumed invoke's turn (`openTurnForLeadingResult`) opens with no
|
|
650
|
+
// assistant message: the resumed response opens it here, AFTER the
|
|
651
|
+
// leading tool result's own message, so the fold stays chronological.
|
|
652
|
+
if (msgId === undefined) {
|
|
653
|
+
msgId = `msg_${turnId}`;
|
|
654
|
+
a.openMessage({ id: msgId, role: "assistant", turnId, threadId, ...(model !== undefined ? { model } : {}) });
|
|
655
|
+
}
|
|
588
656
|
return responseId ?? turnId;
|
|
589
657
|
}
|
|
590
658
|
responseId = respId;
|
|
591
|
-
turnId = respId !== undefined ? `turn_${respId}` : `turn_${
|
|
659
|
+
turnId = respId !== undefined ? `turn_${respId}` : `turn_${invokeStem}_${++turnCounter}`;
|
|
592
660
|
msgId = `msg_${turnId}`;
|
|
593
661
|
// Task 3 (audit M48 review, Finding 1): survives resetResponseState() —
|
|
594
662
|
// see the closure-state doc above.
|
|
@@ -597,6 +665,55 @@ export function createOpenaiNormalizer() {
|
|
|
597
665
|
a.openMessage({ id: msgId, role: "assistant", turnId, threadId, ...(model !== undefined ? { model } : {}) });
|
|
598
666
|
return responseId ?? turnId;
|
|
599
667
|
}
|
|
668
|
+
/**
|
|
669
|
+
* INV-TURN (SPEC:743) for a RESUMED invoke — sp-protocol's c20 package, A.6
|
|
670
|
+
* (openai): when a tool result's round is unknown to this invoke
|
|
671
|
+
* (`resolvePendingTurnId` misses) and no response is open, the result is the
|
|
672
|
+
* resumed stream's LEADING event (sp-probe's live approval-resume capture,
|
|
673
|
+
* 2026-09-24: after `RunState.fromString` + approve/reject, the approved or
|
|
674
|
+
* rejected call's `tool_output` arrives before any `response.created`). Open a
|
|
675
|
+
* turn for it — `turn_resume_<callId>`: deterministic, and never a leg-1
|
|
676
|
+
* `turn_resp_*` id (INV-XINV) — and land the result as its OWN role:"tool"
|
|
677
|
+
* message (`messageId: "<callId>:result"`). The resumed model response then
|
|
678
|
+
* opens its assistant message in this same turn (`ensureResponseOpen`) and its
|
|
679
|
+
* response.completed closes it. Returns the toolDone fields, or `undefined`
|
|
680
|
+
* when the result joins a known round or an open response (unchanged).
|
|
681
|
+
*/
|
|
682
|
+
function openTurnForLeadingResult(callId) {
|
|
683
|
+
if (turnId === undefined) {
|
|
684
|
+
const opened = `turn_resume_${callId}`;
|
|
685
|
+
turnId = opened;
|
|
686
|
+
lastTopLevelTurnId = opened;
|
|
687
|
+
a.openTurn(opened, threadId);
|
|
688
|
+
return { turnId: opened, messageId: `${callId}:result` };
|
|
689
|
+
}
|
|
690
|
+
// Approve-all (sp-protocol's D3 pin, 2026-09-24): the resuming invoke can
|
|
691
|
+
// replay SEVERAL results before its response. While the resume turn is
|
|
692
|
+
// open with no assistant message yet (turnId set, msgId unset — a state
|
|
693
|
+
// only this helper creates), each further result joins THAT turn as its
|
|
694
|
+
// own role:"tool" message; no second turn opens.
|
|
695
|
+
if (msgId === undefined)
|
|
696
|
+
return { turnId, messageId: `${callId}:result` };
|
|
697
|
+
return undefined;
|
|
698
|
+
}
|
|
699
|
+
/** rd-15: the misalignment notice (see the `response.failed` arm). */
|
|
700
|
+
function emitMisalignmentNotice(responseIdForNotice, tid, misalignment, errorMessage) {
|
|
701
|
+
const noticeId = `notice_misalignment_${responseIdForNotice}`;
|
|
702
|
+
const textId = `${noticeId}_text`;
|
|
703
|
+
const explanation = misalignment.detailed_explanation;
|
|
704
|
+
const text = typeof explanation === "string" && explanation.length > 0 ? explanation : (errorMessage ?? "");
|
|
705
|
+
a.openMessage({ id: noticeId, role: "notice", noticeSource: "adapter", turnId: tid, threadId });
|
|
706
|
+
a.emit({
|
|
707
|
+
type: "text.start",
|
|
708
|
+
id: textId,
|
|
709
|
+
messageId: noticeId,
|
|
710
|
+
_meta: AgMeta.parse({ "openai/misalignment": JsonValue.parse(misalignment) }),
|
|
711
|
+
});
|
|
712
|
+
if (text.length > 0)
|
|
713
|
+
a.textDelta(textId, noticeId, text);
|
|
714
|
+
a.textEnd(textId, noticeId);
|
|
715
|
+
a.closeMessage(noticeId);
|
|
716
|
+
}
|
|
600
717
|
/** Reset per-response state after a close. Marks the response closed (close-once). */
|
|
601
718
|
function resetResponseState() {
|
|
602
719
|
const key = responseId ?? turnId;
|
|
@@ -646,14 +763,20 @@ export function createOpenaiNormalizer() {
|
|
|
646
763
|
// (rnd 13+17 Stage 1, founder ruling 2026-09-23; vercel parity c4f5981).
|
|
647
764
|
const phase = pendingPhase.get(ev.item_id);
|
|
648
765
|
const startMeta = openaiProviderMeta({ phase });
|
|
766
|
+
// PH-2 (draft.4, SPEC §8.0 item 27 + §5 "phase timing"): known before
|
|
767
|
+
// the first delta ⇒ the first-class `phase` goes on text.start.
|
|
768
|
+
const interim = interimPhase(phase);
|
|
649
769
|
a.textStart(ev.item_id, msgId, {
|
|
650
770
|
role: "assistant",
|
|
651
771
|
...(startMeta !== undefined ? { providerMetadata: startMeta } : {}),
|
|
772
|
+
...(interim !== undefined ? { phase: interim } : {}),
|
|
652
773
|
});
|
|
653
774
|
if (phase !== undefined) {
|
|
654
775
|
pendingPhase.delete(ev.item_id);
|
|
655
776
|
carriedPhase.set(ev.item_id, phase);
|
|
656
777
|
}
|
|
778
|
+
if (interim !== undefined)
|
|
779
|
+
interimAtStart.add(ev.item_id);
|
|
657
780
|
}
|
|
658
781
|
// OpenAI text deltas are suffix-only fragments (cumulative:false, the default).
|
|
659
782
|
a.textDelta(ev.item_id, msgId, ev.delta, { cumulative: false });
|
|
@@ -826,7 +949,7 @@ export function createOpenaiNormalizer() {
|
|
|
826
949
|
const safety = [{ category: "content_filter", blocked: true }];
|
|
827
950
|
finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
|
|
828
951
|
outcome: { type: "error", message: "content_filter" },
|
|
829
|
-
|
|
952
|
+
...finishReasonFields(reason),
|
|
830
953
|
safety,
|
|
831
954
|
...(usage !== undefined ? { usage } : {}),
|
|
832
955
|
});
|
|
@@ -874,7 +997,8 @@ export function createOpenaiNormalizer() {
|
|
|
874
997
|
else {
|
|
875
998
|
finishOrDeferRound(currentTurnId, currentMsgId, textStreamIds, {
|
|
876
999
|
outcome: { type: "success" },
|
|
877
|
-
|
|
1000
|
+
// OA-15: an unmapped native reason also carries finishReasonRaw.
|
|
1001
|
+
...finishReasonFields(reason),
|
|
878
1002
|
...(usage !== undefined ? { usage } : {}),
|
|
879
1003
|
});
|
|
880
1004
|
}
|
|
@@ -890,21 +1014,25 @@ export function createOpenaiNormalizer() {
|
|
|
890
1014
|
endOpenStreamsAndCloseMessage();
|
|
891
1015
|
const err = ev.response.error;
|
|
892
1016
|
// openai-node ≥7.10.0: `error.misalignment` (classification + public
|
|
893
|
-
// explanation + `steer.message` continuation instruction)
|
|
894
|
-
//
|
|
895
|
-
//
|
|
896
|
-
//
|
|
897
|
-
// turn.error
|
|
898
|
-
//
|
|
899
|
-
//
|
|
900
|
-
//
|
|
1017
|
+
// explanation + `steer.message` continuation instruction). `turn.error`
|
|
1018
|
+
// carries only message/code/usage (spec §4), so rd-15 (sp-protocol's
|
|
1019
|
+
// package A.6; founder: rides 0.7.0; sp-cto: the carry must sit in a
|
|
1020
|
+
// home that FOLDS) lands it as an adapter NOTICE message immediately
|
|
1021
|
+
// BEFORE the closing turn.error, in this turn:
|
|
1022
|
+
// message.start {role:"notice", noticeSource:"adapter"} →
|
|
1023
|
+
// one text block, text = `detailed_explanation` verbatim (else
|
|
1024
|
+
// error.message), text.start `_meta["openai/misalignment"]` = the
|
|
1025
|
+
// WHOLE object verbatim (wire names, steer, unknown keys) →
|
|
1026
|
+
// message.end.
|
|
1027
|
+
// It folds (a notice row + its block `_meta`), so it is readable and
|
|
1028
|
+
// durable. The former live-only ext.openai.misalignment carry is
|
|
1029
|
+
// RETIRED (the item-21 one-carrier precedent; no consumer read it).
|
|
1030
|
+
// Absent or non-object ⇒ nothing new (byte-identical to the pre-7.10.0
|
|
1031
|
+
// output); the isJsonObject guard keeps a malformed wire value away
|
|
1032
|
+
// from JsonValue.parse.
|
|
901
1033
|
const misalignment = err?.misalignment;
|
|
902
|
-
if (isJsonObject(misalignment))
|
|
903
|
-
|
|
904
|
-
responseId: ev.response.id,
|
|
905
|
-
misalignment: JsonValue.parse(misalignment),
|
|
906
|
-
});
|
|
907
|
-
}
|
|
1034
|
+
if (isJsonObject(misalignment))
|
|
1035
|
+
emitMisalignmentNotice(ev.response.id, turnId, misalignment, err?.message);
|
|
908
1036
|
a.closeTurnError(turnId, {
|
|
909
1037
|
message: err?.message ?? "response.failed",
|
|
910
1038
|
...(err?.code !== undefined ? { code: err.code } : {}),
|
|
@@ -1066,8 +1194,27 @@ export function createOpenaiNormalizer() {
|
|
|
1066
1194
|
// OA-14: RETIRED when this id's SAME phase already rode its text.start
|
|
1067
1195
|
// (the live case); kept — lossless — when only the run-item knows it,
|
|
1068
1196
|
// or knows a different value.
|
|
1069
|
-
|
|
1070
|
-
|
|
1197
|
+
// PH-2: null/"" is no marker at all (sp-protocol ruling (a)) — neither
|
|
1198
|
+
// a carry nor a late-phase ext.
|
|
1199
|
+
const lateItemPhase = vendorPhase(item.phase);
|
|
1200
|
+
if (lateItemPhase !== undefined && carriedPhase.get(item.id) !== lateItemPhase) {
|
|
1201
|
+
if (isStashedTextStream(item.id)) {
|
|
1202
|
+
// PH-2 case (ii): the round close is STASHED (a deferred tool
|
|
1203
|
+
// round), so this block's text.end is NOT yet emitted — the §5
|
|
1204
|
+
// timing rule makes the end the phase's home (sp-protocol,
|
|
1205
|
+
// 2026-09-23). The marker has a first-class home, so no late-phase.
|
|
1206
|
+
const interim = interimAtStart.has(item.id) ? undefined : interimPhase(lateItemPhase);
|
|
1207
|
+
const endMeta = openaiProviderMeta({ phase: lateItemPhase });
|
|
1208
|
+
stashedEndFields.set(item.id, {
|
|
1209
|
+
...(endMeta !== undefined ? { providerMetadata: endMeta } : {}),
|
|
1210
|
+
...(interim !== undefined ? { phase: interim } : {}),
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
else {
|
|
1214
|
+
// Case (iii): this block's text.end is already out — never a
|
|
1215
|
+
// second end; the vendor marker rides the lossless ext.
|
|
1216
|
+
a.emitExt("openai", "late-phase", { itemId: item.id, phase: lateItemPhase });
|
|
1217
|
+
}
|
|
1071
1218
|
}
|
|
1072
1219
|
continue;
|
|
1073
1220
|
}
|
|
@@ -1082,11 +1229,16 @@ export function createOpenaiNormalizer() {
|
|
|
1082
1229
|
// message, and a program-driven turn emits multiple message items with
|
|
1083
1230
|
// DIFFERENT phases (commentary vs final_answer) whose message-level
|
|
1084
1231
|
// merge would clobber (see OpenAIAssistantMessageItem.phase's doc).
|
|
1085
|
-
const
|
|
1086
|
-
|
|
1232
|
+
const itemPhase = vendorPhase(item.phase);
|
|
1233
|
+
const phaseMeta = openaiProviderMeta({ phase: itemPhase });
|
|
1234
|
+
// PH-2 case (i): known before this block's text.end ⇒ the end carries
|
|
1235
|
+
// the first-class phase, unless text.start already did.
|
|
1236
|
+
const endInterim = interimAtStart.has(streamId) ? undefined : interimPhase(itemPhase);
|
|
1237
|
+
a.textEnd(streamId, msgId, citations !== undefined || phaseMeta !== undefined || endInterim !== undefined
|
|
1087
1238
|
? {
|
|
1088
1239
|
...(citations !== undefined ? { citations } : {}),
|
|
1089
1240
|
...(phaseMeta !== undefined ? { providerMetadata: phaseMeta } : {}),
|
|
1241
|
+
...(endInterim !== undefined ? { phase: endInterim } : {}),
|
|
1090
1242
|
}
|
|
1091
1243
|
: undefined);
|
|
1092
1244
|
}
|
|
@@ -1365,7 +1517,7 @@ export function createOpenaiNormalizer() {
|
|
|
1365
1517
|
isError: outcome === "error",
|
|
1366
1518
|
...(structuredContent !== undefined ? { structuredContent } : {}),
|
|
1367
1519
|
...(providerMetadata !== undefined ? { providerMetadata } : {}),
|
|
1368
|
-
...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
|
|
1520
|
+
...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(toolCallId) ?? {})),
|
|
1369
1521
|
});
|
|
1370
1522
|
drainPendingTool(toolCallId, doneTurnId);
|
|
1371
1523
|
}
|
|
@@ -1607,7 +1759,7 @@ export function createOpenaiNormalizer() {
|
|
|
1607
1759
|
content,
|
|
1608
1760
|
outcome: "ok",
|
|
1609
1761
|
...(searchMeta !== undefined ? { providerMetadata: searchMeta } : {}),
|
|
1610
|
-
...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
|
|
1762
|
+
...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(toolCallId) ?? {})),
|
|
1611
1763
|
});
|
|
1612
1764
|
drainPendingTool(toolCallId, doneTurnId);
|
|
1613
1765
|
}
|
|
@@ -1624,6 +1776,10 @@ export function createOpenaiNormalizer() {
|
|
|
1624
1776
|
* a turn that has a `turn.start`.
|
|
1625
1777
|
*/
|
|
1626
1778
|
function driveHostError(event) {
|
|
1779
|
+
// O1 (§8.0 item 14 as amended): a host-fed error arriving while a round's
|
|
1780
|
+
// close is deferred releases that close per INV-FLUSH (2) BEFORE the
|
|
1781
|
+
// normalizer closes the error (PS-21).
|
|
1782
|
+
releaseAllDeferredCloses();
|
|
1627
1783
|
ensureResponseOpen();
|
|
1628
1784
|
if (turnId === undefined)
|
|
1629
1785
|
return; // unreachable post-ensure; satisfies narrowing
|
|
@@ -1701,7 +1857,7 @@ export function createOpenaiNormalizer() {
|
|
|
1701
1857
|
...(uiData !== undefined ? { uiData } : {}),
|
|
1702
1858
|
...(resultMeta !== undefined ? { _meta: resultMeta } : {}),
|
|
1703
1859
|
...(doneMeta !== undefined ? { providerMetadata: doneMeta } : {}),
|
|
1704
|
-
...(doneTurnId !== undefined ? { turnId: doneTurnId } : {}),
|
|
1860
|
+
...(doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(rawItem.callId) ?? {})),
|
|
1705
1861
|
});
|
|
1706
1862
|
drainPendingTool(rawItem.callId, doneTurnId);
|
|
1707
1863
|
return;
|
|
@@ -1770,7 +1926,7 @@ export function createOpenaiNormalizer() {
|
|
|
1770
1926
|
// EVENT carve-out), emitted once it's actually known — paired with
|
|
1771
1927
|
// `subagentDone` in the `handoff_occurred` case below.
|
|
1772
1928
|
const ordinal = ++handoffOrdinal;
|
|
1773
|
-
const handoffTurnId = `
|
|
1929
|
+
const handoffTurnId = `turn_${invokeStem}_handoff_${ordinal}`;
|
|
1774
1930
|
const parentTurnId = lastTopLevelTurnId ?? threadId;
|
|
1775
1931
|
openHandoffs.push({ turnId: handoffTurnId, parentTurnId });
|
|
1776
1932
|
a.subagentStart(handoffTurnId, parentTurnId);
|
|
@@ -1787,16 +1943,48 @@ export function createOpenaiNormalizer() {
|
|
|
1787
1943
|
// this seam, unlike google-adk's per-message agentId/agentName).
|
|
1788
1944
|
const item = event.item;
|
|
1789
1945
|
const open = openHandoffs.shift(); // FIFO — see openHandoffs' doc.
|
|
1790
|
-
if (open !== undefined)
|
|
1946
|
+
if (open !== undefined) {
|
|
1947
|
+
// draft.4 nested-run closure (§8.0 item 29, §10 item 36; sp-protocol's
|
|
1948
|
+
// nested-turn package A.6): the bracket closes with its own terminal,
|
|
1949
|
+
// immediately followed by `subagent.done`. `handoff_occurred` IS the
|
|
1950
|
+
// SDK's report that the transfer ran (the handoff span closed and the
|
|
1951
|
+
// new agent resolved), so success; the SDK reports no finish reason
|
|
1952
|
+
// for it ("unknown") and no usage (the top-level round carries the spend).
|
|
1953
|
+
a.closeTurnDone(open.turnId, { outcome: { type: "success" }, finishReason: "unknown" });
|
|
1791
1954
|
a.subagentDone(open.turnId, open.parentTurnId);
|
|
1955
|
+
}
|
|
1956
|
+
// HO (0.7.0 regression, sp-probe's live handoff-gpt6sol): the transfer is
|
|
1957
|
+
// an ordinary function_call the model emitted (tool.start from
|
|
1958
|
+
// `response.output_item.added`, registered pending), and THIS item's
|
|
1959
|
+
// rawItem is its result — the SDK never sends a `tool_output` for it.
|
|
1960
|
+
// Land it as that call's tool.done, routed exactly as the tool_output
|
|
1961
|
+
// arm routes a function result, so the pending set drains and the
|
|
1962
|
+
// source round's deferred close (§8.0 item 14) emits here as its real
|
|
1963
|
+
// turn.done, not as O1's flush-time turn.abort. A resumed invoke can
|
|
1964
|
+
// deliver this for a call started in the interrupted invoke
|
|
1965
|
+
// (agents-core 0.18.0 `resolveInterruptedTurn` runs the response's
|
|
1966
|
+
// pending handoffs): that leading result opens its resume turn FIRST,
|
|
1967
|
+
// so the `handoff` event below lands in the same turn as the result.
|
|
1968
|
+
const result = item.rawItem;
|
|
1969
|
+
const doneTurnId = resolvePendingTurnId(result.callId);
|
|
1970
|
+
const owner = doneTurnId !== undefined ? { turnId: doneTurnId } : (openTurnForLeadingResult(result.callId) ?? {});
|
|
1792
1971
|
// Defensive orphan (no open bracket — e.g. a resumed/truncated stream):
|
|
1793
1972
|
// still emit the `handoff` event losslessly rather than dropping the
|
|
1794
|
-
// now-known identity (Tenet 6) — it just doesn't close anything.
|
|
1973
|
+
// now-known identity (Tenet 6) — it just doesn't close anything. It
|
|
1974
|
+
// precedes the tool.done, which may close the source round.
|
|
1795
1975
|
a.emit({
|
|
1796
1976
|
type: "handoff",
|
|
1797
1977
|
kind: "transfer",
|
|
1798
1978
|
toAgentName: item.targetAgent.name,
|
|
1799
1979
|
});
|
|
1980
|
+
a.toolDone({
|
|
1981
|
+
toolCallId: result.callId,
|
|
1982
|
+
content: toolOutputToAgBlocks(result.output),
|
|
1983
|
+
outcome: result.status === "incomplete" ? "error" : "ok",
|
|
1984
|
+
isError: result.status === "incomplete",
|
|
1985
|
+
...owner,
|
|
1986
|
+
});
|
|
1987
|
+
drainPendingTool(result.callId, doneTurnId);
|
|
1800
1988
|
return;
|
|
1801
1989
|
}
|
|
1802
1990
|
case "compaction_item_created": {
|
|
@@ -1838,6 +2026,7 @@ export function createOpenaiNormalizer() {
|
|
|
1838
2026
|
kind: "approval",
|
|
1839
2027
|
toolCallId: item.callId,
|
|
1840
2028
|
});
|
|
2029
|
+
askedApprovals.set(item.callId, `approval_${item.callId}`);
|
|
1841
2030
|
return;
|
|
1842
2031
|
}
|
|
1843
2032
|
default:
|
|
@@ -1878,31 +2067,42 @@ export function createOpenaiNormalizer() {
|
|
|
1878
2067
|
}
|
|
1879
2068
|
return {
|
|
1880
2069
|
push(native) {
|
|
2070
|
+
// LV: a host may push the SDK's LIVE stream objects (undefined members,
|
|
2071
|
+
// Dates, class instances, cycles), not the JSON round-tripped shape the
|
|
2072
|
+
// corpus records, and the carried-member `JsonValue.parse` sites threw a
|
|
2073
|
+
// ZodError on them (sp-main's no-throw check, 2026-09-24: 6 of 9 live
|
|
2074
|
+
// shapes). The native arrives already normalized: `withAtomicPush` ran core's
|
|
2075
|
+
// `toJsonValueSafe` on it (JSON semantics per node: toJSON honoured,
|
|
2076
|
+
// undefined dropped, Date → ISO string), and it owns the no-throw
|
|
2077
|
+
// guarantee too. This inner push MUST NOT catch; a throw here is the
|
|
2078
|
+
// wrapper's signal to discard the batch and rebuild.
|
|
1881
2079
|
if (!isOpenAIStreamEvent(native)) {
|
|
1882
2080
|
// Graceful guard (Tenet 6): route a genuinely unrecognisable payload through
|
|
1883
2081
|
// the lossless vendor channel rather than throwing. Nest under `native` so a
|
|
1884
2082
|
// payload carrying its own `type` key does NOT clobber the event type.
|
|
1885
|
-
|
|
2083
|
+
// A COPY via JsonValue.parse, like every other carry path: plain input
|
|
2084
|
+
// arrives by reference, so carrying it as-is would alias the host's
|
|
2085
|
+
// object into an emitted event, and would forward an own `__proto__`
|
|
2086
|
+
// key (sp-cto's checks, 2026-09-24).
|
|
2087
|
+
a.emitExt("openai", "unparsed", { native: JsonValue.parse(native) });
|
|
1886
2088
|
return a.drain();
|
|
1887
2089
|
}
|
|
1888
2090
|
drive(native);
|
|
1889
2091
|
return a.drain();
|
|
1890
2092
|
},
|
|
1891
2093
|
flush() {
|
|
1892
|
-
//
|
|
1893
|
-
//
|
|
1894
|
-
//
|
|
2094
|
+
// O1 (INV-FLUSH as amended; fold/flush option 1): release the deferred
|
|
2095
|
+
// closes FIRST — they are older rounds, so their message.end precedes the
|
|
2096
|
+
// live response's (insertion order, CB-16) — as paused / verbatim /
|
|
2097
|
+
// message.end+usage then turn.abort (`releaseDeferredClose`); a flush
|
|
2098
|
+
// never emits a success turn.done.
|
|
2099
|
+
releaseAllDeferredCloses();
|
|
2100
|
+
// Then close any dangling open response (a stream that ended before
|
|
2101
|
+
// response.completed): its message ends here and the engine's flush
|
|
2102
|
+
// aborts its turn as stream-truncated.
|
|
1895
2103
|
if (turnId !== undefined)
|
|
1896
2104
|
closeResponse();
|
|
1897
|
-
//
|
|
1898
|
-
// flush. Each stashed round genuinely completed on the wire — a tool
|
|
1899
|
-
// result that never arrives must not swallow that close (message.end +
|
|
1900
|
-
// turn.done both replay here, verbatim, in the order INV-MSG requires).
|
|
1901
|
-
for (const [tid, stashed] of stashedCloseByTurn) {
|
|
1902
|
-
emitRoundClose(tid, stashed.msgId, stashed.openTextStreamIds, stashed.fields);
|
|
1903
|
-
}
|
|
1904
|
-
stashedCloseByTurn.clear();
|
|
1905
|
-
// Flush the engine's dangling open messages (I7).
|
|
2105
|
+
// Flush the engine's dangling open messages / turns (I7).
|
|
1906
2106
|
return a.flush();
|
|
1907
2107
|
},
|
|
1908
2108
|
};
|