@silverprotocol/google-adk 0.12.5 → 1.0.0-rc.2

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
@@ -75,11 +75,11 @@
75
75
  * the model's reply share one turn: ADK yields the call generation's
76
76
  * turnComplete after the function response and before the reply (a
77
77
  * gemini-3.8-live capture `live-tool-gemini38live`), so a turnComplete with no
78
- * model output since the last function response does not close the turn. Two
79
- * limits remain. A generation that follows a completed generation with no
80
- * pending tool exchange, and with no barge-in, lands in the closed turn and
81
- * parks a reducer, unless `hostCompletion` defers that close.
82
- * And when text is buffered at the interrupt, ADK yields only the text
78
+ * model output since the last function response does not close the turn. A
79
+ * generation that follows a completed generation opens the next turn
80
+ * (liveTurnFor), and an `{interrupted}` that follows a completed generation
81
+ * interrupts the next one, which closes `turn.abort{interrupted}`. One limit
82
+ * remains. When text is buffered at the interrupt, ADK yields only the text
83
83
  * aggregate, without the flag (utils/live_connection_utils.js), so this facet
84
84
  * sees no interrupt and the turn closes at flush as `stream-truncated`.
85
85
  */
@@ -258,8 +258,11 @@ export interface AdkEvent {
258
258
  finishReason?: string;
259
259
  /** Provider error code (Gemini block reason) — surfaces a non-STOP finish. */
260
260
  errorCode?: string;
261
- /** Free-text error message accompanying errorCode for hard errors. When BOTH
262
- * errorCode AND errorMessage are set, a turn.error is emitted instead of turn.done. */
261
+ /** Free-text error message accompanying errorCode for hard errors. An event
262
+ * with BOTH errorCode AND errorMessage is an in-band invocation error: the
263
+ * facet emits a non-terminal `error` event when it arrives, and the
264
+ * invocation's turn closes with turn.error at the invocation's end (spec
265
+ * §8.0 item 35). */
263
266
  errorMessage?: string;
264
267
  /** Event id (stable per ADK event). */
265
268
  id?: string;
@@ -482,6 +485,8 @@ function resolveFinishReason(reason: string | undefined | null): {
482
485
  case "PROHIBITED_CONTENT":
483
486
  case "SPII":
484
487
  case "IMAGE_SAFETY":
488
+ case "IMAGE_PROHIBITED_CONTENT":
489
+ case "IMAGE_RECITATION":
485
490
  return { value: "safety_blocked", lossy: false };
486
491
  case "MALFORMED_FUNCTION_CALL":
487
492
  return { value: "malformed_tool_call", lossy: false };
@@ -518,32 +523,47 @@ export function isLossyFinishReason(reason: string): boolean {
518
523
  // ─── stateful factory helpers ─────────────────────────────────────────────────
519
524
 
520
525
 
521
- // ─── the A2A relay's bookkeeping entries in customMetadata ───────────────────
522
- // ADK's RemoteA2AAgent writes up to four bookkeeping entries into the
523
- // customMetadata of the events it relays: its send request, the peer's raw A2A
524
- // event and their task and context ids. They are the relay's own bookkeeping,
525
- // not event data, and the facet does not carry them, wherever customMetadata
526
- // is carried (the provider-raw carry and the ext.google.unparsed native, where
527
- // an event serialized from Python spells it custom_metadata). Every other
528
- // entry, including one a remote agent wrote, rides unchanged.
526
+ // ─── customMetadata entries the facet does not carry ─────────────────────────
527
+ // Two kinds of customMetadata entry are not event data, and the facet does not
528
+ // carry them, wherever customMetadata is carried (the provider-raw carry and
529
+ // the ext.google.unparsed native, where an event serialized from Python spells
530
+ // it custom_metadata):
531
+ // - ADK's RemoteA2AAgent writes up to four bookkeeping entries into the
532
+ // customMetadata of the events it relays: its send request, the peer's raw
533
+ // A2A event and their task and context ids.
534
+ // - ADK reserves the entries whose name begins with `__adk_internal_` for its
535
+ // own components (events/internal_metadata.js, @google/adk 2.2.1): callers
536
+ // cannot set them, and ADK removes them from the API responses, saved
537
+ // session files and A2A messages it produces. At that version they hold a
538
+ // tool-call integrity stamp and a restored-history marker (SPEC §8.0 item
539
+ // 38).
540
+ // Only top-level entries are matched. Every other entry, including one a
541
+ // remote agent wrote and a value nested below a carried entry, rides
542
+ // unchanged.
529
543
  const RELAY_BOOKKEEPING_KEYS: ReadonlySet<string> = new Set(["a2a:request", "a2a:response", "a2a:task_id", "a2a:context_id"]);
544
+ const ADK_INTERNAL_METADATA_PREFIX = "__adk_internal_";
530
545
 
531
- /** A customMetadata value without the relay's bookkeeping entries, as a new
532
- * value; the argument is not changed. A value holding none of them, or one
533
- * that is not an object, is returned as it is; undefined when the entries
534
- * were all it held. */
535
- function withoutRelayBookkeeping(value: JsonValue): JsonValue | undefined {
536
- if (!isJsonObject(value) || !Object.keys(value).some((k) => RELAY_BOOKKEEPING_KEYS.has(k))) return value;
537
- const kept = Object.entries(value).filter(([k]) => !RELAY_BOOKKEEPING_KEYS.has(k));
546
+ /** Whether a top-level customMetadata entry is one the facet does not carry. */
547
+ function isUncarriedMetadataKey(key: string): boolean {
548
+ return RELAY_BOOKKEEPING_KEYS.has(key) || key.startsWith(ADK_INTERNAL_METADATA_PREFIX);
549
+ }
550
+
551
+ /** A customMetadata value without the entries the facet does not carry, as a
552
+ * new value; the argument is not changed. A value holding none of them, or
553
+ * one that is not an object, is returned as it is; undefined when those
554
+ * entries were all it held. */
555
+ function carriedMetadata(value: JsonValue): JsonValue | undefined {
556
+ if (!isJsonObject(value) || !Object.keys(value).some(isUncarriedMetadataKey)) return value;
557
+ const kept = Object.entries(value).filter(([k]) => !isUncarriedMetadataKey(k));
538
558
  return kept.length > 0 ? Object.fromEntries(kept) : undefined;
539
559
  }
540
560
 
541
561
  /** A native with its customMetadata, or the custom_metadata of an event
542
- * serialized from Python, reduced as by withoutRelayBookkeeping and dropped
543
- * when nothing is left, as a new value; every other member is unchanged, and
544
- * the argument is not changed. The new value's members are defined, never
562
+ * serialized from Python, reduced as by carriedMetadata and dropped when
563
+ * nothing is left, as a new value; every other member is unchanged, and the
564
+ * argument is not changed. The new value's members are defined, never
545
565
  * assigned, and one named __proto__ is not copied (SPEC §13.7). */
546
- function nativeWithoutRelayBookkeeping(native: JsonValue): JsonValue {
566
+ function nativeWithCarriedMetadata(native: JsonValue): JsonValue {
547
567
  if (!isJsonObject(native)) return native;
548
568
  let changed = false;
549
569
  const out: Array<[string, JsonValue]> = [];
@@ -553,7 +573,7 @@ function nativeWithoutRelayBookkeeping(native: JsonValue): JsonValue {
553
573
  out.push([key, value]);
554
574
  continue;
555
575
  }
556
- const kept = withoutRelayBookkeeping(value);
576
+ const kept = carriedMetadata(value);
557
577
  if (kept !== value) changed = true;
558
578
  if (kept !== undefined) out.push([key, kept]);
559
579
  }
@@ -734,6 +754,53 @@ const USAGE_SUM_FIELDS = [
734
754
  "responseTokenCount",
735
755
  ] as const;
736
756
 
757
+ /** The per-kind count members of AgUsage, which sumUsage sums with an absent
758
+ * count read as 0. */
759
+ const USAGE_COUNTS = [
760
+ "inputTokens",
761
+ "outputTokens",
762
+ "cacheReadTokens",
763
+ "cacheWriteTokens",
764
+ "reasoningTokens",
765
+ "toolUseInputTokens",
766
+ "serverToolRequests",
767
+ ] as const;
768
+
769
+ /** The aggregate members of AgUsage, which sumUsage sums only when both
770
+ * records carry them: a total or a cost one record lacks would understate
771
+ * the sum (spec §4: totals are copied, never computed). */
772
+ const USAGE_AGGREGATES = ["totalTokens", "totalTokensRaw", "costUsd"] as const;
773
+
774
+ /** The field-wise sum of two usage records: each per-kind count present in
775
+ * either is summed (an absent count is 0), each aggregate only when both
776
+ * carry it (otherwise it is omitted), per model too; every other member is
777
+ * the first record's, else the second's. Either absent returns the other. */
778
+ function sumUsage(a: AgUsage | undefined, b: AgUsage | undefined): AgUsage | undefined {
779
+ if (a === undefined) return b;
780
+ if (b === undefined) return a;
781
+ const out: AgUsage = { ...b, ...a };
782
+ for (const key of USAGE_COUNTS) {
783
+ const x = a[key];
784
+ const y = b[key];
785
+ if (x !== undefined || y !== undefined) out[key] = (x ?? 0) + (y ?? 0);
786
+ }
787
+ for (const key of USAGE_AGGREGATES) {
788
+ const x = a[key];
789
+ const y = b[key];
790
+ if (x !== undefined && y !== undefined) out[key] = x + y;
791
+ else delete out[key];
792
+ }
793
+ if (a.byModel !== undefined || b.byModel !== undefined) {
794
+ const byModel: { [model: string]: AgUsage } = {};
795
+ for (const model of new Set([...Object.keys(a.byModel ?? {}), ...Object.keys(b.byModel ?? {})])) {
796
+ const sum = sumUsage(a.byModel?.[model], b.byModel?.[model]);
797
+ if (sum !== undefined) byModel[model] = sum;
798
+ }
799
+ out.byModel = byModel;
800
+ }
801
+ return out;
802
+ }
803
+
737
804
  /** Fold one event's usageMetadata into a turn's running accumulator
738
805
  * (field-wise sum; absent fields stay absent so mapUsage's presence checks
739
806
  * keep working). Returns the accumulator (creating it on first use). */
@@ -766,6 +833,51 @@ function mapBlockedSafety(ratings: AdkEvent["safetyRatings"]): AgSafety[] | unde
766
833
  return out.length > 0 ? out : undefined;
767
834
  }
768
835
 
836
+ // ─── ADK's prompt-block event (errorCode) → prompt.blocked (spec §4) ─────────
837
+ /**
838
+ * The errorCode values that mark an ADK event as a blocked prompt: genai
839
+ * 2.24.0's `BlockedReason` values and the Gemini API's spelling of the
840
+ * unspecified one. In StreamingMode NONE, @google/adk 2.1.0's
841
+ * `createLlmResponse` (models/llm_response.js) turns a blocked prompt into an
842
+ * event whose errorCode is the block reason, with no finishReason, no content
843
+ * and no safety ratings. Exported so the e2e suite's genai pin test
844
+ * (e2e/src/adk-prompt-block-reasons.pin.test.ts) can hold it against genai's
845
+ * own `BlockedReason`. It restates the peer's native values, so it changes
846
+ * when they do.
847
+ *
848
+ * @beta
849
+ */
850
+ export const ADK_PROMPT_BLOCK_REASONS: readonly string[] = [
851
+ "BLOCKED_REASON_UNSPECIFIED",
852
+ "SAFETY",
853
+ "OTHER",
854
+ "BLOCKLIST",
855
+ "PROHIBITED_CONTENT",
856
+ "IMAGE_SAFETY",
857
+ "MODEL_ARMOR",
858
+ "JAILBREAK",
859
+ "BLOCK_REASON_UNSPECIFIED",
860
+ ];
861
+ const PROMPT_BLOCK_REASONS: ReadonlySet<string> = new Set(ADK_PROMPT_BLOCK_REASONS);
862
+
863
+ /** The block reason when an event is an ADK prompt block (a treated errorCode,
864
+ * no finishReason, which a response-level block keeps beside errorCode, no
865
+ * content parts, and not relayed), else undefined. ADK's A2A relay marks each
866
+ * event it forwards with an a2a:response entry in customMetadata and drops the
867
+ * finishReason, so a relayed prompt block and a relayed response-level block
868
+ * with the same code arrive alike: no relayed event is read as a prompt block. */
869
+ function adkPromptBlockReason(event: AdkEvent): string | undefined {
870
+ const code: unknown = event.errorCode;
871
+ const relayed = isJsonObject(event.customMetadata) && Object.hasOwn(event.customMetadata, "a2a:response");
872
+ return typeof code === "string" &&
873
+ PROMPT_BLOCK_REASONS.has(code) &&
874
+ event.finishReason === undefined &&
875
+ (event.content?.parts ?? []).length === 0 &&
876
+ !relayed
877
+ ? code
878
+ : undefined;
879
+ }
880
+
769
881
  // ─── promptFeedback.blockReason → prompt.blocked reason (spec §4) ────────────
770
882
  // Maps Gemini blockReason to the AgJSON prompt.blocked reason enum.
771
883
  function mapBlockReason(reason: string): "safety" | "blocklist" | "prohibited" | "other" {
@@ -970,6 +1082,33 @@ function hasLiveContent(ev: AdkEvent): boolean {
970
1082
  return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
971
1083
  }
972
1084
 
1085
+ // Members of an ADK event that the facet maps to nothing, with the values
1086
+ // ADK gives them by default; a member's other value, or any other member,
1087
+ // maps to something. The `actions` members are listed below.
1088
+ const NO_EMIT_EVENT_MEMBERS: ReadonlySet<string> = new Set(["invocationId", "author", "id", "timestamp"]);
1089
+ const NO_EMIT_ACTION_MEMBERS: ReadonlySet<string> = new Set(["artifactDelta", "requestedAuthConfigs", "requestedToolConfirmations"]);
1090
+
1091
+ function isEmptyObject(v: unknown): boolean {
1092
+ return isJsonObject(v) && Object.keys(v).length === 0;
1093
+ }
1094
+
1095
+ /** Whether all an event maps to is the state.delta of its stateDelta (or
1096
+ * nothing): every member is one the facet maps to nothing, holding ADK's
1097
+ * default value, but for `actions.stateDelta`. */
1098
+ function onlyStateChange(ev: AdkEvent): boolean {
1099
+ for (const [key, value] of Object.entries(ev)) {
1100
+ if (value === undefined || NO_EMIT_EVENT_MEMBERS.has(key)) continue;
1101
+ if (key === "longRunningToolIds" && Array.isArray(value) && value.length === 0) continue;
1102
+ if (key !== "actions" || !isJsonObject(value)) return false;
1103
+ for (const [action, member] of Object.entries(value)) {
1104
+ if (member === undefined || action === "stateDelta") continue;
1105
+ if (action === "escalate" && member === false) continue;
1106
+ if (!NO_EMIT_ACTION_MEMBERS.has(action) || !isEmptyObject(member)) return false;
1107
+ }
1108
+ }
1109
+ return true;
1110
+ }
1111
+
973
1112
  /** Whether an event carries model output: a part of `model`-role content, or
974
1113
  * output-transcription text. ADK's function response is `user`-role. */
975
1114
  function hasModelOutput(ev: AdkEvent): boolean {
@@ -1219,17 +1358,104 @@ function mapGroundingCitations(
1219
1358
  gm: AdkEvent["groundingMetadata"]
1220
1359
  ): AgCitation[] | undefined {
1221
1360
  if (gm?.groundingSupports === undefined || gm.groundingSupports.length === 0) return undefined;
1222
- return gm.groundingSupports.map((support): AgCitation => ({
1223
- kind: "offset",
1224
- unit: "byte",
1225
- startIndex: support.segment?.startIndex ?? 0,
1226
- endIndex: support.segment?.endIndex ?? 0,
1227
- bounds: "[start,end)",
1228
- sourceIds: support.groundingChunkIndices?.map((i) => `grounding_${i}`) ?? [],
1229
- confidenceScores: support.confidenceScores ?? [],
1230
- citedText: support.segment?.text ?? "",
1231
- indexFrame: "response",
1232
- }));
1361
+ return gm.groundingSupports.map((support: unknown): AgCitation => {
1362
+ // genai types these members (numbers, a string, number lists). A value of
1363
+ // another type has no AgCitation home: the citation takes the member's
1364
+ // default (0, "", []) or, for the optional scores, omits it, and the
1365
+ // event-level carry holds the native value verbatim
1366
+ // (groundingSupportsCarry). Nothing is filtered: ADK pairs each score with
1367
+ // the chunk index at the same position.
1368
+ const read = readSupport(support);
1369
+ return {
1370
+ kind: "offset",
1371
+ unit: "byte",
1372
+ startIndex: read.startIndex ?? 0,
1373
+ endIndex: read.endIndex ?? 0,
1374
+ bounds: "[start,end)",
1375
+ sourceIds: (read.chunkIndices ?? []).map((i) => `grounding_${i}`),
1376
+ ...(read.scores !== undefined ? { confidenceScores: read.scores } : {}),
1377
+ citedText: read.text ?? "",
1378
+ indexFrame: "response",
1379
+ };
1380
+ });
1381
+ }
1382
+
1383
+ /** One grounding support's members as AgCitation takes them. An absent or
1384
+ * JSON-null member reads as its default; a member of another type reads as undefined, and its
1385
+ * native value is named in `unmapped`. */
1386
+ function readSupport(support: unknown): {
1387
+ startIndex: number | undefined;
1388
+ endIndex: number | undefined;
1389
+ text: string | undefined;
1390
+ chunkIndices: number[] | undefined;
1391
+ scores: number[] | undefined;
1392
+ unmapped: { [k: string]: JsonValue };
1393
+ } {
1394
+ const unmapped: { [k: string]: JsonValue } = {};
1395
+ const member = (key: string): unknown => (isJsonObject(support) ? support[key] : undefined);
1396
+ const segment = member("segment");
1397
+ const seg = (key: string): unknown => (isJsonObject(segment) ? segment[key] : undefined);
1398
+ const startRaw = seg("startIndex");
1399
+ const endRaw = seg("endIndex");
1400
+ const textRaw = seg("text");
1401
+ const startIndex = startRaw === undefined || startRaw === null ? 0 : finiteNumber(startRaw);
1402
+ const endIndex = endRaw === undefined || endRaw === null ? 0 : finiteNumber(endRaw);
1403
+ const text = textRaw === undefined || textRaw === null ? "" : typeof textRaw === "string" ? textRaw : undefined;
1404
+ const segmentMapped = (segment === undefined || segment === null || isJsonObject(segment)) && startIndex !== undefined && endIndex !== undefined && text !== undefined;
1405
+ if (!segmentMapped) unmapped["segment"] = JsonValue.parse(segment);
1406
+ const indicesRaw = member("groundingChunkIndices");
1407
+ const chunkIndices = indicesRaw === undefined || indicesRaw === null ? [] : chunkIndexList(indicesRaw);
1408
+ if (chunkIndices === undefined) unmapped["groundingChunkIndices"] = JsonValue.parse(indicesRaw);
1409
+ const scoresRaw = member("confidenceScores");
1410
+ const scores = scoresRaw === undefined || scoresRaw === null ? [] : finiteScores(scoresRaw);
1411
+ if (scores === undefined) unmapped["confidenceScores"] = JsonValue.parse(scoresRaw);
1412
+ return { startIndex, endIndex, text, chunkIndices, scores, unmapped };
1413
+ }
1414
+
1415
+ /** The value when it is a finite number, else undefined. */
1416
+ function finiteNumber(value: unknown): number | undefined {
1417
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
1418
+ }
1419
+
1420
+ /** The value when it is a list of finite numbers, else undefined. */
1421
+ function finiteScores(value: unknown): number[] | undefined {
1422
+ if (!Array.isArray(value)) return undefined;
1423
+ const scores: number[] = [];
1424
+ for (const score of value) {
1425
+ const n = finiteNumber(score);
1426
+ if (n === undefined) return undefined;
1427
+ scores.push(n);
1428
+ }
1429
+ return scores;
1430
+ }
1431
+
1432
+ /** The value when it is a list of chunk indexes (non-negative integers), else
1433
+ * undefined. */
1434
+ function chunkIndexList(value: unknown): number[] | undefined {
1435
+ if (!Array.isArray(value)) return undefined;
1436
+ const indices: number[] = [];
1437
+ for (const index of value) {
1438
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return undefined;
1439
+ indices.push(index);
1440
+ }
1441
+ return indices;
1442
+ }
1443
+
1444
+ /** The grounding supports' members that mapGroundingCitations could not map,
1445
+ * verbatim at their native path: one entry per support, in order, holding
1446
+ * those members (the whole `segment` when one of its members did not map)
1447
+ * and nothing for a support that mapped whole. Undefined when every support
1448
+ * mapped. */
1449
+ function groundingSupportsCarry(gm: AdkEvent["groundingMetadata"]): JsonValue | undefined {
1450
+ const supports: unknown = gm?.groundingSupports;
1451
+ if (!Array.isArray(supports)) return undefined;
1452
+ let any = false;
1453
+ const entries = supports.map((support: unknown): JsonValue => {
1454
+ const { unmapped } = readSupport(support);
1455
+ if (Object.keys(unmapped).length > 0) any = true;
1456
+ return unmapped;
1457
+ });
1458
+ return any ? { groundingSupports: entries } : undefined;
1233
1459
  }
1234
1460
 
1235
1461
  // ─── null-id call mint state (audit M47; window/correlation redesign — review
@@ -1416,10 +1642,80 @@ function mintBlockId(m: BlockIdMint, kind: "text" | "reasoning"): string {
1416
1642
  return `${kind}:${n}`;
1417
1643
  }
1418
1644
 
1645
+ /** Whether a part carries a member one of driveAdkPart's non-text arms maps:
1646
+ * a call, a result, inline or file data, or code or its result. */
1647
+ function carriesPayload(part: AdkPart): boolean {
1648
+ return (
1649
+ part.functionCall !== undefined ||
1650
+ part.functionResponse !== undefined ||
1651
+ part.inlineData !== undefined ||
1652
+ part.fileData !== undefined ||
1653
+ part.executableCode !== undefined ||
1654
+ part.codeExecutionResult !== undefined
1655
+ );
1656
+ }
1657
+
1658
+ /** An event's parts with each part that holds text beside a payload member,
1659
+ * or two or more payload members, split into one part per payload member in
1660
+ * driveAdkPart's arm order, after a part holding its text (a genai Part holds
1661
+ * one kind of data, so such a part is malformed; every arm returns, and each
1662
+ * arm after the first would never map). The first part keeps the text, the
1663
+ * thought signature and every unmapped member (they are carried once); each
1664
+ * payload part holds its member alone, marked as thought when the original
1665
+ * part was. So the parts map as the same event with the split parts would
1666
+ * (but for the positions below): the text in its text or reasoning block,
1667
+ * and each payload member through its own arm, credential scrubs included
1668
+ * (SPEC.md §8.0, graceful degradation: no native value is dropped
1669
+ * silently). Any other part is
1670
+ * unchanged, and an event with no such part keeps its array. `origin` holds,
1671
+ * for each resulting part, the index of the native part it came from: a
1672
+ * null-id call's providerCallIndex and tool.start's `index` record that
1673
+ * original position (SPEC.md §8.0 item 2), never the split one. */
1674
+ function splitPayloadParts(parts: readonly AdkPart[]): { parts: readonly AdkPart[]; origin: readonly number[] } {
1675
+ if (!parts.some((p) => payloadCount(p) > (typeof p.text === "string" ? 0 : 1))) return { parts, origin: parts.map((_, i) => i) };
1676
+ const out: AdkPart[] = [];
1677
+ const origin: number[] = [];
1678
+ for (const [nativeIndex, part] of parts.entries()) {
1679
+ const textual = typeof part.text === "string";
1680
+ if (payloadCount(part) <= (textual ? 0 : 1)) {
1681
+ out.push(part);
1682
+ origin.push(nativeIndex);
1683
+ continue;
1684
+ }
1685
+ const { functionCall, functionResponse, inlineData, executableCode, codeExecutionResult, fileData, ...rest } = part;
1686
+ const mark: AdkPart = part.thought === true ? { thought: true } : {};
1687
+ const halves: AdkPart[] = [];
1688
+ if (functionCall !== undefined) halves.push({ functionCall, ...mark });
1689
+ if (functionResponse !== undefined) halves.push({ functionResponse, ...mark });
1690
+ if (inlineData !== undefined) halves.push({ inlineData, ...mark });
1691
+ if (executableCode !== undefined) halves.push({ executableCode, ...mark });
1692
+ if (codeExecutionResult !== undefined) halves.push({ codeExecutionResult, ...mark });
1693
+ if (fileData !== undefined) halves.push({ fileData, ...mark });
1694
+ const [first, ...others] = halves;
1695
+ const split: AdkPart[] = textual || first === undefined ? [rest, ...halves] : [{ ...rest, ...first }, ...others];
1696
+ out.push(...split);
1697
+ for (let k = 0; k < split.length; k++) origin.push(nativeIndex);
1698
+ }
1699
+ return { parts: out, origin };
1700
+ }
1701
+
1702
+ /** How many of driveAdkPart's payload members a part holds. */
1703
+ function payloadCount(part: AdkPart): number {
1704
+ let n = 0;
1705
+ if (part.functionCall !== undefined) n++;
1706
+ if (part.functionResponse !== undefined) n++;
1707
+ if (part.inlineData !== undefined) n++;
1708
+ if (part.executableCode !== undefined) n++;
1709
+ if (part.codeExecutionResult !== undefined) n++;
1710
+ if (part.fileData !== undefined) n++;
1711
+ return n;
1712
+ }
1713
+
1419
1714
  function driveAdkPart(
1420
1715
  a: StreamAssembler,
1421
1716
  part: AdkPart,
1422
1717
  index: number,
1718
+ nativeIndex: number,
1423
1719
  event: AdkEvent,
1424
1720
  messageId: string,
1425
1721
  turnId: string,
@@ -1467,6 +1763,15 @@ function driveAdkPart(
1467
1763
  unmappedPartFields["mediaProcessing"] = JsonValue.parse(part.mediaProcessing);
1468
1764
  if (part.speechMetadata !== undefined)
1469
1765
  unmappedPartFields["speechMetadata"] = JsonValue.parse(part.speechMetadata);
1766
+ // A part marked as thought that carries no text but a call, a result or
1767
+ // media (ADK-Python's A2A relay marks every part it converts from a remote
1768
+ // agent's in-progress status as thought) maps through that
1769
+ // payload's arm below, as it would unmarked, and not as an empty reasoning
1770
+ // block. Its `thought` flag, which no event of those arms holds, rides this
1771
+ // carry (SPEC.md §8.0, graceful degradation: no native value is dropped
1772
+ // silently).
1773
+ const thoughtPayload = part.thought === true && typeof part.text !== "string" && carriesPayload(part);
1774
+ if (thoughtPayload) unmappedPartFields["thought"] = true;
1470
1775
  if (Object.keys(unmappedPartFields).length > 0) {
1471
1776
  a.contentBlock(messageId, {
1472
1777
  type: "provider-raw",
@@ -1476,7 +1781,7 @@ function driveAdkPart(
1476
1781
  }
1477
1782
 
1478
1783
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
1479
- if (part.thought === true) {
1784
+ if (part.thought === true && !thoughtPayload) {
1480
1785
  const id = mintBlockId(blockIds, "reasoning");
1481
1786
  a.reasoningStart(id, messageId);
1482
1787
  // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
@@ -1543,7 +1848,8 @@ function driveAdkPart(
1543
1848
  if (minted.resend) return ""; // dedup the partial:false aggregate re-send (window-scoped content identity)
1544
1849
  toolCallId = minted.toolCallId;
1545
1850
  }
1546
- const providerCallIndex = realId !== null ? undefined : index;
1851
+ // The native part's position, not the split one (see splitPayloadParts).
1852
+ const providerCallIndex = realId !== null ? undefined : nativeIndex;
1547
1853
  // The reserved credential call's args carry the whole ADK AuthConfig: scrub
1548
1854
  // them to the allowlist (see scrubAdkAuthConfig) before they reach
1549
1855
  // tool.args.* and the folded tool-call block.
@@ -1556,7 +1862,7 @@ function driveAdkPart(
1556
1862
  a.toolStart({
1557
1863
  toolCallId,
1558
1864
  name: fc.name,
1559
- index,
1865
+ index: nativeIndex,
1560
1866
  longRunning,
1561
1867
  providerMetadata:
1562
1868
  providerCallIndex !== undefined
@@ -1729,7 +2035,8 @@ function driveAdkTopLevel(
1729
2035
  turnId: string,
1730
2036
  pendingAsks: Map<string, AgPausedAsk[]>,
1731
2037
  reserved: ReservedAskState,
1732
- streamedTranscription: Map<string, string>
2038
+ streamedTranscription: Map<string, string>,
2039
+ turnClosed: boolean
1733
2040
  ): void {
1734
2041
  // Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
1735
2042
  // a `finished: true` transcription whose text is the chunks joined
@@ -1764,8 +2071,16 @@ function driveAdkTopLevel(
1764
2071
  // `interrupted` → turn.abort is closed in drive(), after this event's own
1765
2072
  // content and carries (see closeInterrupted), never here mid-event.
1766
2073
 
1767
- // ── promptFeedback → prompt.blocked ──
1768
- if (event.promptFeedback?.blockReason !== undefined) {
2074
+ // ── prompt block → prompt.blocked: one record per block event while the turn
2075
+ // is open, never after its terminal. A record runs before the close logic, so
2076
+ // it precedes the terminal the same event may bring; the terminal itself is
2077
+ // unchanged. An event carrying promptFeedback is recorded from it (a
2078
+ // dual-shape event records once); otherwise ADK's own shape records: a treated
2079
+ // errorCode with no finishReason and no content (adkPromptBlockReason), reason
2080
+ // mapped as below and no safety, since that event carries no ratings.
2081
+ if (turnClosed) {
2082
+ // no record after the turn's terminal
2083
+ } else if (event.promptFeedback?.blockReason !== undefined) {
1769
2084
  const blockReason = event.promptFeedback.blockReason;
1770
2085
  const reason = mapBlockReason(blockReason);
1771
2086
  const safety =
@@ -1781,16 +2096,21 @@ function driveAdkTopLevel(
1781
2096
  : undefined;
1782
2097
  // draft.8 (§4): an unmapped block reason (reason "other") carries the
1783
2098
  // native value verbatim in reasonRaw; a mapped reason carries none, as a
1784
- // lossless finishReason takes no finishReasonRaw (§10 item 23). On
1785
- // @google/adk 2.1.0 no ADK-built event carries promptFeedback: its
1786
- // createLlmResponse turns a prompt block into errorCode/errorMessage
1787
- // (models/llm_response.js), so this arm serves events built elsewhere.
2099
+ // lossless finishReason takes no finishReasonRaw. No ADK-built event
2100
+ // carries promptFeedback at @google/adk 2.1.0, so this arm serves events
2101
+ // built elsewhere; ADK's own shape is the branch below.
1788
2102
  a.emit({
1789
2103
  type: "prompt.blocked",
1790
2104
  reason,
1791
2105
  ...(reason === "other" ? { reasonRaw: blockReason } : {}),
1792
2106
  ...(safety !== undefined ? { safety } : {}),
1793
2107
  });
2108
+ } else {
2109
+ const blockReason = adkPromptBlockReason(event);
2110
+ if (blockReason !== undefined) {
2111
+ const reason = mapBlockReason(blockReason);
2112
+ a.emit({ type: "prompt.blocked", reason, ...(reason === "other" ? { reasonRaw: blockReason } : {}) });
2113
+ }
1794
2114
  }
1795
2115
 
1796
2116
  // ── groundingMetadata → source + display.required ──────────────────────────
@@ -1955,8 +2275,10 @@ function driveAdkTopLevel(
1955
2275
  // absent from `@iqai/adk`'s surface, closed by the same opportunistic-carry
1956
2276
  // precedent (absent from all recorded fixtures — no golden-snapshot impact).
1957
2277
  //
1958
- // `author`/`timestamp` are ALSO real, currently-unread AdkEvent fields
1959
- // (same manifest inventory) but are DELIBERATELY NOT folded into this bag.
2278
+ // `author`/`timestamp` are ALSO real AdkEvent fields (same manifest
2279
+ // inventory) but are DELIBERATELY NOT folded into this bag (`author` is read
2280
+ // only by the aggregate window: its key, aggregateWindowKey, and the
2281
+ // same-author lookup in windowCandidates).
1960
2282
  // On the official `@google/adk` 1.3.0 `Event` interface `timestamp: number`
1961
2283
  // is REQUIRED and `author?: string` is optional in the TYPE — but the
1962
2284
  // runner sets author on every event it appends in practice, so the
@@ -2006,10 +2328,25 @@ function driveAdkTopLevel(
2006
2328
  unmappedEvent["isolationScope"] = JsonValue.parse(event.isolationScope);
2007
2329
  if (event.citationMetadata !== undefined)
2008
2330
  unmappedEvent["citationMetadata"] = JsonValue.parse(event.citationMetadata);
2331
+ const groundingSupports = groundingSupportsCarry(event.groundingMetadata);
2332
+ if (groundingSupports !== undefined) unmappedEvent["groundingMetadata"] = groundingSupports;
2009
2333
  if (event.customMetadata !== undefined) {
2010
- const kept = withoutRelayBookkeeping(JsonValue.parse(event.customMetadata));
2334
+ const kept = carriedMetadata(JsonValue.parse(event.customMetadata));
2011
2335
  if (kept !== undefined) unmappedEvent["customMetadata"] = kept;
2012
2336
  }
2337
+ // An error message without an error code (ADK's A2A relay reports its own
2338
+ // failure so, and a remote executor's that it passes on) is not an in-band
2339
+ // invocation error (spec §8.0 item 35), which maps the code and message as a
2340
+ // pair; its message, and a code that is not a string, ride here verbatim
2341
+ // (spec §8.0 graceful degradation and item 23).
2342
+ if (inBandErrorOf(event) === undefined) {
2343
+ const message: unknown = event.errorMessage;
2344
+ const code: unknown = event.errorCode;
2345
+ if (message !== undefined && message !== null) {
2346
+ if (code !== undefined && code !== null) unmappedEvent["errorCode"] = JsonValue.parse(code);
2347
+ unmappedEvent["errorMessage"] = JsonValue.parse(message);
2348
+ }
2349
+ }
2013
2350
  if (Object.keys(unmappedEvent).length > 0) {
2014
2351
  a.contentBlock(messageId, {
2015
2352
  type: "provider-raw",
@@ -2071,7 +2408,11 @@ export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
2071
2408
  * SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
2072
2409
  * the stream (e.g. its LLM-call limit), the host catches it and pushes
2073
2410
  * `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
2074
- * open turn closes `turn.error` with that code and message. The shape matches the OpenAI
2411
+ * open turn closes `turn.error` with that code and message and the turn's
2412
+ * usage plus `usage`, which covers only work the stream did not report (so
2413
+ * a host passes the usage of unreported work, never a total); a turn whose
2414
+ * pause was signalled closes paused first, and the error then closes on a
2415
+ * new top-level turn (spec §8.0 item 26). The shape matches the OpenAI
2075
2416
  * facet's sentinel. A host may build it from the caught Error itself
2076
2417
  * (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
2077
2418
  * read from the raw native, so the Error's own message is kept.
@@ -2131,6 +2472,220 @@ function isHostCompleteNative(v: JsonValue): boolean {
2131
2472
  * So push() never throws (SPEC §8.0), and no facet state believes a turn,
2132
2473
  * message or block is open that never reached the wire.
2133
2474
  */
2475
+ // ─── ADK in-band invocation errors (spec §8.0 item 35) ───────────────────────
2476
+ // ADK yields an in-band invocation error (errorCode AND errorMessage) without
2477
+ // ending the invocation: a SequentialAgent runs its next sub-agent, a Workflow
2478
+ // node retries, a callback or a further model round follows. So the turn never
2479
+ // closes on one: the push() that receives it emits the non-terminal `error`
2480
+ // event, and the invocation's turn closes with one turn.error at the
2481
+ // invocation's end (the host-completion event, a host-terminal event or
2482
+ // flush()), never as success.
2483
+
2484
+ /** Spec §8.0 item 35: an in-band invocation error carries both errorCode and
2485
+ * errorMessage. */
2486
+ function inBandErrorOf(event: AdkEvent): { code: string; message: string } | undefined {
2487
+ const code: unknown = event.errorCode;
2488
+ const message: unknown = event.errorMessage;
2489
+ return typeof code === "string" && typeof message === "string" ? { code, message } : undefined;
2490
+ }
2491
+
2492
+ /** The previous event of one source, for item 35's SSE repeat: whether it
2493
+ * carried `partial: false`, the in-band error it carried, its usage report,
2494
+ * and the slot that report took among the turn's counted reports (absent when
2495
+ * it was not counted). */
2496
+ interface PreviousSourceEvent {
2497
+ partialFalse: boolean;
2498
+ error: { code: string; message: string } | undefined;
2499
+ usage: NonNullable<AdkEvent["usageMetadata"]> | undefined;
2500
+ usageSlot: number | undefined;
2501
+ }
2502
+
2503
+ /** An in-band invocation error seen on one source, for item 35's relay
2504
+ * repeat: its code and message, and its usage report and `a2a:task_id`
2505
+ * entry as sorted-key JSON ("" when absent). */
2506
+ interface InBandErrorRecord {
2507
+ code: string;
2508
+ message: string;
2509
+ usage: string;
2510
+ taskId: string;
2511
+ }
2512
+
2513
+ /** The record item 35's relay repeat compares for one in-band error. */
2514
+ function inBandErrorRecord(event: AdkEvent, error: { code: string; message: string }): InBandErrorRecord {
2515
+ const metadata: unknown = event.customMetadata;
2516
+ return {
2517
+ code: error.code,
2518
+ message: error.message,
2519
+ usage: event.usageMetadata !== undefined ? canonicalJson(JsonValue.parse(event.usageMetadata)) : "",
2520
+ taskId: isJsonObject(metadata) && Object.hasOwn(metadata, "a2a:task_id") ? canonicalJson(metadata["a2a:task_id"] ?? null) : "",
2521
+ };
2522
+ }
2523
+
2524
+ /** Item 35's relay repeat: `RemoteA2AAgent` stamps an `a2a:request` entry on
2525
+ * each relayed event that carries `turnComplete: true`, and at @google/adk
2526
+ * 2.1.0 it reports a remote failure that carries no content only in that
2527
+ * closing event, so one failure can reach the facet twice. The closing event
2528
+ * repeats an earlier in-band error of the same source when the code, message
2529
+ * and usage report are equal (an absent report matches only an absent one)
2530
+ * and both carry the same `a2a:task_id` entry, present on both. */
2531
+ function isRelayRepeat(event: AdkEvent, record: InBandErrorRecord, earlier: readonly InBandErrorRecord[]): boolean {
2532
+ const metadata: unknown = event.customMetadata;
2533
+ if (event.turnComplete !== true || !isJsonObject(metadata) || !Object.hasOwn(metadata, "a2a:request")) return false;
2534
+ if (record.taskId === "") return false;
2535
+ return earlier.some(
2536
+ (e) => e.taskId === record.taskId && e.code === record.code && e.message === record.message && e.usage === record.usage,
2537
+ );
2538
+ }
2539
+
2540
+ /** The aggregate window's key: the turn plus the event's source (author,
2541
+ * branch and node path). A missing or non-string value is its own key, never
2542
+ * equal to an empty string. */
2543
+ function aggregateWindowKey(turnId: string, event: AdkEvent, stream: string | null = relayStreamOf(event)): string {
2544
+ const author: unknown = event.author;
2545
+ const branch: unknown = event.branch;
2546
+ const path: unknown = event.nodeInfo?.path;
2547
+ return JSON.stringify([
2548
+ turnId,
2549
+ typeof author === "string" ? author : null,
2550
+ typeof branch === "string" ? branch : null,
2551
+ typeof path === "string" ? path : null,
2552
+ stream,
2553
+ ]);
2554
+ }
2555
+
2556
+ /** What a relayed event is, read from the native relay record ADK's
2557
+ * RemoteA2AAgent attaches: its A2A task (the `a2a:task_id` entry, null when
2558
+ * the reply carried none) and its stream, one artifact's chunks and their
2559
+ * aggregate (`artifact:<id>`), the status messages (`status`), or a Task or
2560
+ * Message that restates the task (`snapshot`). null for an event that is not
2561
+ * relayed. */
2562
+ function relayOf(event: AdkEvent): { task: string | null; stream: string } | null {
2563
+ const metadata: unknown = event.customMetadata;
2564
+ if (!isJsonObject(metadata)) return null;
2565
+ const response: unknown = metadata["a2a:response"];
2566
+ if (!isJsonObject(response)) return null;
2567
+ const taskId: unknown = metadata["a2a:task_id"];
2568
+ const task = typeof taskId === "string" ? taskId : null;
2569
+ const kind: unknown = response["kind"];
2570
+ const artifact: unknown = response["artifact"];
2571
+ if (kind === "artifact-update" && isJsonObject(artifact) && typeof artifact["artifactId"] === "string")
2572
+ return { task, stream: `artifact:${artifact["artifactId"]}` };
2573
+ if (kind === "status-update") return { task, stream: "status" };
2574
+ if (kind === "task" || kind === "message") return { task, stream: "snapshot" };
2575
+ return null;
2576
+ }
2577
+
2578
+ /** The window-key part of a relayed stream: the task and the stream, so a new
2579
+ * relay pass (a new A2A task) never reads the windows of an earlier one. */
2580
+ function relayStreamKey(task: string | null, stream: string): string {
2581
+ return JSON.stringify([task, stream]);
2582
+ }
2583
+
2584
+ /** The A2A stream a relayed event belongs to, scoped by its task; null for
2585
+ * every event that is not relayed. */
2586
+ function relayStreamOf(event: AdkEvent): string | null {
2587
+ const relay = relayOf(event);
2588
+ return relay === null ? null : relayStreamKey(relay.task, relay.stream);
2589
+ }
2590
+
2591
+ /** The open windows a non-partial event reads and closes: the one under its
2592
+ * own key; else, for an event without a branch, every open window of the
2593
+ * same turn, author and node path. `own`, `relay` and `wantStream` are the
2594
+ * event's own window key, relay record and relay stream, read once by the
2595
+ * caller. */
2596
+ function windowCandidates(
2597
+ windows: ReadonlyMap<string, string>,
2598
+ turnId: string,
2599
+ event: AdkEvent,
2600
+ own: string,
2601
+ relay: { task: string | null; stream: string } | null,
2602
+ wantStream: string | null,
2603
+ ): string[] {
2604
+ if (windows.has(own)) return [own];
2605
+ // A relayed artifact with no chunks of its own can repeat the status text
2606
+ // of its own task (a peer that sends its answer as status messages, then
2607
+ // the same text as its final artifact).
2608
+ if (relay !== null && relay.stream.startsWith("artifact:")) {
2609
+ const status = aggregateWindowKey(turnId, event, relayStreamKey(relay.task, "status"));
2610
+ if (windows.has(status)) return [status];
2611
+ }
2612
+ if (typeof event.branch === "string") return [];
2613
+ return sourceWindows(windows, turnId, event, true)
2614
+ .filter(([, stream]) => stream === wantStream)
2615
+ .map(([key]) => key);
2616
+ }
2617
+
2618
+ /** The open windows of the source of an event, as [key, stream] pairs: the
2619
+ * same turn, author and node path, and the same branch unless anyBranch. */
2620
+ function sourceWindows(windows: ReadonlyMap<string, string>, turnId: string, event: AdkEvent, anyBranch: boolean): Array<[string, unknown]> {
2621
+ const author: unknown = event.author;
2622
+ const branch: unknown = event.branch;
2623
+ const path: unknown = event.nodeInfo?.path;
2624
+ const wantAuthor = typeof author === "string" ? author : null;
2625
+ const wantBranch = typeof branch === "string" ? branch : null;
2626
+ const wantPath = typeof path === "string" ? path : null;
2627
+ const out: Array<[string, unknown]> = [];
2628
+ for (const key of windows.keys()) {
2629
+ const parsed: unknown = JSON.parse(key);
2630
+ if (
2631
+ Array.isArray(parsed) &&
2632
+ parsed[0] === turnId &&
2633
+ parsed[1] === wantAuthor &&
2634
+ (anyBranch || parsed[2] === wantBranch) &&
2635
+ parsed[3] === wantPath
2636
+ )
2637
+ out.push([key, parsed[4]]);
2638
+ }
2639
+ return out;
2640
+ }
2641
+
2642
+ /** The windows a relayed Task or Message restates: its task's open artifact
2643
+ * windows, in the order they opened, and its task's status window. */
2644
+ function snapshotWindows(
2645
+ windows: ReadonlyMap<string, string>,
2646
+ turnId: string,
2647
+ event: AdkEvent,
2648
+ task: string | null,
2649
+ ): { artifacts: string[]; status: string[] } {
2650
+ const own = sourceWindows(windows, turnId, event, false);
2651
+ const artifacts = own.filter(([, stream]) => {
2652
+ if (typeof stream !== "string") return false;
2653
+ const parsed: unknown = JSON.parse(stream);
2654
+ return Array.isArray(parsed) && parsed[0] === task && typeof parsed[1] === "string" && parsed[1].startsWith("artifact:");
2655
+ });
2656
+ const status = relayStreamKey(task, "status");
2657
+ return { artifacts: artifacts.map(([key]) => key), status: own.filter(([, stream]) => stream === status).map(([key]) => key) };
2658
+ }
2659
+
2660
+ /** The streamed text a relayed Task or Message is read against. ADK renders a
2661
+ * Task as its artifacts' parts, then its status message's (taskToAdkEvent), so
2662
+ * the snapshot is matched in that order: against the artifacts and the status
2663
+ * text together (a task still in the state it streamed), else the artifacts
2664
+ * alone (its status message is new, and renders), else the status text alone.
2665
+ * The first reading the snapshot repeats is taken; with none, the first. */
2666
+ function snapshotReading(artifactText: string, statusText: string, text: string): string {
2667
+ const readings = [artifactText + statusText, artifactText, statusText].filter((r) => r.length > 0);
2668
+ const repeats = (r: string) => text.startsWith(r) || r.startsWith(text) || r.endsWith(text);
2669
+ return readings.find(repeats) ?? readings[0] ?? "";
2670
+ }
2671
+
2672
+ /** The relay windows an event of the relaying agent ends without being
2673
+ * relayed itself: ADK's RemoteA2AAgent reports a failed request with an
2674
+ * event of its own (errorMessage, turnComplete, no relay record), which ends
2675
+ * every relayed stream of that author and node path. */
2676
+ function relayWindowsEndedBy(
2677
+ windows: ReadonlyMap<string, string>,
2678
+ turnId: string,
2679
+ event: AdkEvent,
2680
+ relay: { task: string | null; stream: string } | null,
2681
+ ): string[] {
2682
+ if (relay !== null) return [];
2683
+ if (event.errorMessage === undefined && event.turnComplete !== true) return [];
2684
+ return sourceWindows(windows, turnId, event, true)
2685
+ .filter(([, stream]) => stream !== null)
2686
+ .map(([key]) => key);
2687
+ }
2688
+
2134
2689
  export function createAdkNormalizer(options: AdkNormalizerOptions = {}): Normalizer {
2135
2690
  // The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
2136
2691
  // re-drives to the same ids and no push() reads randomness.
@@ -2150,7 +2705,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2150
2705
  const hostCompletion = options.hostCompletion === true;
2151
2706
  const a = new StreamAssembler();
2152
2707
  const threadId = options.threadId ?? "google";
2153
- // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
2708
+ // §8.3 per-instance accumulator (replaces the module-level streamedText Map),
2709
+ // keyed by aggregateWindowKey (turn + source):
2154
2710
  const streamedText = new Map<string, string>();
2155
2711
  // Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
2156
2712
  const streamedTranscription = new Map<string, string>();
@@ -2170,6 +2726,18 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2170
2726
  // double-render quirk applies to usage too), so counting non-partial
2171
2727
  // events counts each round exactly once.
2172
2728
  const usageByTurn = new Map<string, NonNullable<AdkEvent["usageMetadata"]>>();
2729
+ // The usage reports summed into usageByTurn, in order, so the report that an
2730
+ // in-band error's repeat supersedes can be replaced (spec §8.0 item 35).
2731
+ const usageReportsByTurn = new Map<string, Array<NonNullable<AdkEvent["usageMetadata"]>>>();
2732
+ // Spec §8.0 item 35: per turn, the invocation's first in-band invocation
2733
+ // error (errorCode AND errorMessage). The turn never closes on one, never
2734
+ // closes as success after one, and closes with one turn.error at the
2735
+ // invocation's end.
2736
+ const firstInBandError = new Map<string, { code: string; message: string }>();
2737
+ // Per turn and source (author, branch, node path): the previous event, for
2738
+ // item 35's SSE repeat, and the in-band errors seen, for its relay repeat.
2739
+ const previousBySource = new Map<string, PreviousSourceEvent>();
2740
+ const inBandErrorsBySource = new Map<string, InBandErrorRecord[]>();
2173
2741
  // Per-turn HITL asks emitted by the two `actions.requested*` arms (audit
2174
2742
  // M26) — populated in emission order by `trackPendingAsk` inside
2175
2743
  // `driveAdkTopLevel`. Consulted ONLY by `maybeCloseTurn`'s REAL close path
@@ -2182,6 +2750,14 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2182
2750
  // Host obligation 4 (opt-in): a success close stashed until the sentinel, and
2183
2751
  // the non-HITL long-running calls still unanswered, per turn.
2184
2752
  const deferredClose = new Map<string, AdkEvent>();
2753
+ // Per turn: a final response of a pausing agent (the author of a pending
2754
+ // ask's event) arrived while that ask was pending, one of item 26's pause
2755
+ // signals. A final stashed before any ask is not one, and neither is another
2756
+ // agent's final, which only follows the signal.
2757
+ const finalWhileAsking = new Set<string>();
2758
+ const askingAuthors = new Map<string, Set<string | undefined>>();
2759
+ const finalOfPausingAgent = (turnId: string, event: AdkEvent): boolean =>
2760
+ (pendingAsks.get(turnId)?.length ?? 0) > 0 && askingAuthors.get(turnId)?.has(event.author) === true;
2185
2761
  // Live barge-ins (`interrupted: true`, ADK's live aggregator) awaiting their
2186
2762
  // close. An interrupt on a PARTIAL text event is followed by ADK's full-text
2187
2763
  // aggregate of the same model turn (utils/live_connection_utils.js:175-178),
@@ -2197,6 +2773,16 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2197
2773
  // opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
2198
2774
  const generationOf = new Map<string, number>();
2199
2775
  const interruptClosed = new Set<string>();
2776
+ // Per turn key: whether the previous event carried both turnComplete and
2777
+ // interrupted, the message after which ADK re-yields a bare {interrupted}.
2778
+ const previousBothFlags = new Map<string, boolean>();
2779
+ // Turns a final response closed as success before the invocation ended
2780
+ // (without the host-completion event only). ADK keeps running after such a
2781
+ // final (a SequentialAgent's next sub-agent, a LoopAgent's next iteration),
2782
+ // and content that follows opens the next generation of the turn rather
2783
+ // than landing after its terminal (spec §8.0: framework content that
2784
+ // arrives after a terminal opens a new turn).
2785
+ const successClosed = new Set<string>();
2200
2786
  // Turns whose last function response has no model output after it yet. On
2201
2787
  // the Live path the model always answers a tool result with a reply
2202
2788
  // generation, and ADK can yield the call generation's turnComplete between
@@ -2236,11 +2822,6 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2236
2822
  isPartial: boolean
2237
2823
  ): void {
2238
2824
  if (isPartial || closedTurns.has(turnId)) return;
2239
- // Every non-partial event contributes its per-round usage to the turn's
2240
- // accumulator — including functionCall rounds, which never close the
2241
- // turn themselves (see the usageByTurn doc above).
2242
- const accumulated = accumulateUsage(usageByTurn.get(turnId), event.usageMetadata);
2243
- if (accumulated !== undefined) usageByTurn.set(turnId, accumulated);
2244
2825
  const parts = event.content?.parts ?? [];
2245
2826
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
2246
2827
  const interrupted = event.interrupted === true || interruptPending.has(turnId);
@@ -2274,36 +2855,51 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2274
2855
  // A bare Live turnComplete between a function response and the model's
2275
2856
  // reply ends the call generation, not the turn (see awaitingReply).
2276
2857
  if (event.finishReason === undefined && event.errorCode === undefined && awaitingReply.has(turnId)) return;
2277
- // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
2278
- // present ⇒ turn.error (values captured here so the close below needs no
2279
- // re-narrowing).
2280
- const errorClose =
2281
- event.errorCode !== undefined && event.errorMessage !== undefined
2282
- ? { code: event.errorCode, message: event.errorMessage }
2283
- : undefined;
2858
+ // Spec §8.0 item 35: an in-band invocation error never closes the turn
2859
+ // (recordErrorAndUsage emitted its `error` event), and once the invocation
2860
+ // met one, no final response closes it either: the invocation's end does
2861
+ // (hostComplete, hostError, flush). A final response while an ask is
2862
+ // pending still signals the pause (item 26).
2863
+ if (inBandErrorOf(event) !== undefined) return;
2864
+ if (firstInBandError.has(turnId)) {
2865
+ if ((pendingAsks.get(turnId)?.length ?? 0) > 0) {
2866
+ deferredClose.set(turnId, event);
2867
+ if (finalOfPausingAgent(turnId, event)) finalWhileAsking.add(turnId);
2868
+ }
2869
+ return;
2870
+ }
2284
2871
  // ── The nodeInfo gate (R&D item 6, step 1) ──
2285
2872
  // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
2286
2873
  // final text (nodeInfo present) is mid-invocation: closing the invocation
2287
2874
  // turn on it put the workflow's later events after the terminal and parked
2288
2875
  // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
2289
2876
  // closes the turn as success. It is a per-EVENT test, never a latch
2290
- // (NodeTool puts nodeInfo into plain runs too). Error closes stay
2291
- // immediate. A completed workflow closes success only on the host-completion
2292
- // event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
2293
- // it flushes turn.abort.
2294
- if (errorClose === undefined && event.nodeInfo !== undefined) return;
2877
+ // (NodeTool puts nodeInfo into plain runs too). A completed workflow closes
2878
+ // success only on the host-completion event (the `hostCompletion` opt-in,
2879
+ // §8.0 host obligation 4); without it, it flushes turn.abort.
2880
+ if (event.nodeInfo !== undefined) return;
2295
2881
  // Host obligation 4 (opt-in): a success close waits for the
2296
2882
  // host-completion event, because the run may not be over (a
2297
2883
  // SequentialAgent's next agent, after-agent callback content). A close
2298
2884
  // while an ask is pending waits on every host (item 26: the invocation's
2299
2885
  // end, the host-completion event or flush()), because the model may run
2300
2886
  // again after a pause. The final response is stashed and closed unchanged,
2301
- // so a stream ending here is byte-identical. Error closes stay immediate.
2302
- if (errorClose === undefined && (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0)) {
2887
+ // so a stream ending here is byte-identical.
2888
+ if (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0) {
2303
2889
  deferredClose.set(turnId, event);
2890
+ if (finalOfPausingAgent(turnId, event)) finalWhileAsking.add(turnId);
2304
2891
  return;
2305
2892
  }
2306
- closeOnFinalResponse(event, turnId, messageId, errorClose);
2893
+ // ── The branch gate ──
2894
+ // A final response that carries a `branch` (a ParallelAgent's sub-agent)
2895
+ // ends that branch, not the invocation: ADK runs the other branches after
2896
+ // it, so closing the turn on it put their events after the terminal and
2897
+ // parked reduce() (INV-TURN). Without the host-completion event such a
2898
+ // turn closes at flush(), as a completed Workflow does.
2899
+ if (typeof event.branch === "string") return;
2900
+ // No ask is pending here, so this close is a success.
2901
+ successClosed.add(turnId);
2902
+ closeOnFinalResponse(event, turnId, messageId);
2307
2903
  }
2308
2904
 
2309
2905
  /** The paused close at the invocation's end. A final response stashed while
@@ -2312,7 +2908,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2312
2908
  function closePaused(turnId: string, messageId: string, asks: AgPausedAsk[]): void {
2313
2909
  const stashed = deferredClose.get(turnId);
2314
2910
  if (stashed !== undefined) {
2315
- closeOnFinalResponse(stashed, turnId, messageId, undefined);
2911
+ closeOnFinalResponse(stashed, turnId, messageId);
2316
2912
  return;
2317
2913
  }
2318
2914
  closedTurns.add(turnId);
@@ -2326,13 +2922,9 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2326
2922
  }
2327
2923
 
2328
2924
  /** The close on a final response: lossy-finish metadata, message.end, then
2329
- * turn.error or turn.done (paused when asks are pending, else success). */
2330
- function closeOnFinalResponse(
2331
- event: AdkEvent,
2332
- turnId: string,
2333
- messageId: string,
2334
- errorClose: { code: string; message: string } | undefined,
2335
- ): void {
2925
+ * turn.done (paused when asks are pending, else success). An in-band
2926
+ * invocation error never reaches it (spec §8.0 item 35). */
2927
+ function closeOnFinalResponse(event: AdkEvent, turnId: string, messageId: string): void {
2336
2928
  closedTurns.add(turnId);
2337
2929
  const rawFinish = event.finishReason ?? event.errorCode;
2338
2930
  const finish = resolveFinishReason(rawFinish);
@@ -2345,9 +2937,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2345
2937
  // `rawErrorCode`, never fabricated as a finishReason. Lossy-only (unlike
2346
2938
  // vercel-ai's unconditional carry) so no recorded cassette — all STOP
2347
2939
  // closes — gains noise. Runs exactly once per turn (real-close path,
2348
- // closedTurns-guarded), never on partials; the error-close path skips it
2349
- // (closeTurnError carries the wire errorCode verbatim in `code`).
2350
- if (errorClose === undefined && rawFinish !== undefined && finish.lossy) {
2940
+ // closedTurns-guarded), never on partials.
2941
+ if (rawFinish !== undefined && finish.lossy) {
2351
2942
  a.emit({
2352
2943
  type: "message.metadata",
2353
2944
  messageId,
@@ -2357,40 +2948,133 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2357
2948
  });
2358
2949
  }
2359
2950
  a.closeMessage(messageId);
2360
- // The turn's accrued usage rides its terminal on both closes (SPEC §4:
2361
- // turn.error.usage mirrors turn.done), as the host-error close does.
2951
+ // The turn's accrued usage rides its terminal.
2362
2952
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
2363
- if (errorClose !== undefined) {
2364
- a.closeTurnError(turnId, {
2365
- message: errorClose.message,
2366
- code: errorClose.code,
2367
- ...(usage !== undefined ? { usage } : {}),
2368
- });
2953
+ // SPEC §4's safety_blocked conformance note: a safety_blocked close
2954
+ // carries safety[].category so the collapsed reason stays recoverable. A
2955
+ // blocked rating names it; when no rating does (ADK 2.1.0 delivers none on
2956
+ // a real block), the native value finishReason was mapped from is the
2957
+ // category, as a block.
2958
+ const rated = mapBlockedSafety(event.safetyRatings);
2959
+ const safety =
2960
+ rated === undefined && finish.value === "safety_blocked" && rawFinish !== undefined
2961
+ ? [{ category: rawFinish, blocked: true }]
2962
+ : rated;
2963
+ // A turn with pending HITL asks (requestedAuthConfigs /
2964
+ // requestedToolConfirmations / adk_request_input, tracked by
2965
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
2966
+ // unresolved requests the turn is parked on, never a fabricated success
2967
+ // (SPEC §8 items 12 + 18). A paused close carries finishReason "paused"
2968
+ // (the HITL value), the same as the pause-end close above.
2969
+ const asks = pendingAsks.get(turnId);
2970
+ const paused = asks !== undefined && asks.length > 0;
2971
+ a.closeTurnDone(turnId, {
2972
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
2973
+ finishReason: paused ? "paused" : finish.value,
2974
+ // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
2975
+ // native value verbatim in turn.done.finishReasonRaw. That is the value
2976
+ // finishReason was mapped from: the wire finishReason, or for an
2977
+ // errorCode-only soft close the errorCode. A paused close's "paused" is
2978
+ // not a fallback, so it takes no companion. message.metadata's
2979
+ // rawFinishReason/rawErrorCode carry stays for one cohort.
2980
+ ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
2981
+ ...(usage !== undefined ? { usage } : {}),
2982
+ ...(safety !== undefined ? { safety } : {}),
2983
+ });
2984
+ }
2985
+
2986
+ /** Count one usage report toward the turn's usage; returns its slot. */
2987
+ function countUsage(turnId: string, usage: NonNullable<AdkEvent["usageMetadata"]>): number {
2988
+ const reports = usageReportsByTurn.get(turnId) ?? [];
2989
+ reports.push(usage);
2990
+ usageReportsByTurn.set(turnId, reports);
2991
+ const accumulated = accumulateUsage(usageByTurn.get(turnId), usage);
2992
+ if (accumulated !== undefined) usageByTurn.set(turnId, accumulated);
2993
+ return reports.length - 1;
2994
+ }
2995
+
2996
+ /** Replace the report in one slot and re-sum the turn's usage. */
2997
+ function replaceUsage(turnId: string, slot: number, usage: NonNullable<AdkEvent["usageMetadata"]>): void {
2998
+ const reports = usageReportsByTurn.get(turnId);
2999
+ if (reports === undefined || slot >= reports.length) return;
3000
+ reports[slot] = usage;
3001
+ let sum: NonNullable<AdkEvent["usageMetadata"]> | undefined;
3002
+ for (const report of reports) sum = accumulateUsage(sum, report);
3003
+ if (sum !== undefined) usageByTurn.set(turnId, sum);
3004
+ }
3005
+
3006
+ /** Spec §8.0 item 35 when the event arrives, and the event's usage count.
3007
+ * Every non-partial event of an open turn counts its usage report once,
3008
+ * functionCall rounds included (see the usageByTurn doc above). An in-band
3009
+ * invocation error that repeats an earlier one yields no `error` event: the
3010
+ * SSE aggregate that repeats the previous in-band error of its source as the
3011
+ * model call's stream closes (its report replaces the one it repeats, so
3012
+ * the call counts once, from the later report), and the relay's closing
3013
+ * event (it adds no usage). Any other in-band error emits `error` from this
3014
+ * push and, when it is the invocation's first, latches it. */
3015
+ function recordErrorAndUsage(event: AdkEvent, turnId: string, isPartial: boolean, sourceKey: string): void {
3016
+ const previous = previousBySource.get(sourceKey);
3017
+ const error = inBandErrorOf(event);
3018
+ const counting = !isPartial && !closedTurns.has(turnId);
3019
+ let usageSlot: number | undefined;
3020
+ if (error === undefined) {
3021
+ if (counting && event.usageMetadata !== undefined) usageSlot = countUsage(turnId, event.usageMetadata);
2369
3022
  } else {
2370
- const safety = mapBlockedSafety(event.safetyRatings);
2371
- // A turn with pending HITL asks (requestedAuthConfigs /
2372
- // requestedToolConfirmations / adk_request_input, tracked by
2373
- // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
2374
- // unresolved requests the turn is parked on, never a fabricated success
2375
- // (audit M26 / SPEC §8 items 12 + 18). A paused close carries
2376
- // finishReason "paused" (the HITL value, R&D item 6 step 1), the same as
2377
- // the pause-end close above.
2378
- const asks = pendingAsks.get(turnId);
2379
- const paused = asks !== undefined && asks.length > 0;
2380
- a.closeTurnDone(turnId, {
2381
- outcome: paused ? { type: "paused", asks } : { type: "success" },
2382
- finishReason: paused ? "paused" : finish.value,
2383
- // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
2384
- // native value verbatim in turn.done.finishReasonRaw. That is the value
2385
- // finishReason was mapped from: the wire finishReason, or for an
2386
- // errorCode-only soft close the errorCode. A paused close's "paused" is
2387
- // not a fallback, so it takes no companion. message.metadata's
2388
- // rawFinishReason/rawErrorCode carry stays for one cohort.
2389
- ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
2390
- ...(usage !== undefined ? { usage } : {}),
2391
- ...(safety !== undefined ? { safety } : {}),
2392
- });
3023
+ const record = inBandErrorRecord(event, error);
3024
+ const earlier = inBandErrorsBySource.get(sourceKey) ?? [];
3025
+ const repeatsPrevious =
3026
+ event.partial === false &&
3027
+ previous !== undefined &&
3028
+ !previous.partialFalse &&
3029
+ previous.error !== undefined &&
3030
+ previous.error.code === error.code &&
3031
+ previous.error.message === error.message;
3032
+ if (repeatsPrevious) {
3033
+ const later = event.usageMetadata ?? previous.usage;
3034
+ if (counting && later !== undefined) {
3035
+ if (previous.usageSlot !== undefined) {
3036
+ replaceUsage(turnId, previous.usageSlot, later);
3037
+ usageSlot = previous.usageSlot;
3038
+ } else {
3039
+ usageSlot = countUsage(turnId, later);
3040
+ }
3041
+ }
3042
+ } else if (!isRelayRepeat(event, record, earlier)) {
3043
+ a.emit({ type: "error", turnId, code: error.code, message: error.message });
3044
+ if (!firstInBandError.has(turnId)) firstInBandError.set(turnId, error);
3045
+ if (counting && event.usageMetadata !== undefined) usageSlot = countUsage(turnId, event.usageMetadata);
3046
+ }
3047
+ inBandErrorsBySource.set(sourceKey, [...earlier, record]);
2393
3048
  }
3049
+ previousBySource.set(sourceKey, { partialFalse: event.partial === false, error, usage: event.usageMetadata, usageSlot });
3050
+ }
3051
+
3052
+ /** Item 26's pause signal: an ask is pending and the stream showed the
3053
+ * pause's end (its pause-end event, or a final response while the ask was
3054
+ * pending). An in-band invocation error is never one. */
3055
+ function pauseSignalled(turnId: string): boolean {
3056
+ return (pendingAsks.get(turnId)?.length ?? 0) > 0 && (pauseEnded.has(turnId) || finalWhileAsking.has(turnId));
3057
+ }
3058
+
3059
+ /** Spec §8.0 item 35 at the invocation's end: the one turn.error of a turn
3060
+ * whose invocation met an invocation error, with the given code and message
3061
+ * and the turn's accumulated usage. */
3062
+ function closeInvocationError(turnId: string, error: { code: string; message: string }, usage: AgUsage | undefined): void {
3063
+ closedTurns.add(turnId);
3064
+ a.closeMessage(`msg_${turnId}`);
3065
+ a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
3066
+ }
3067
+
3068
+ /** Spec §8.0 item 26 with an invocation error: after the paused close, the
3069
+ * error closes on a new top-level turn of the invocation, which carries one
3070
+ * assistant message with no content; its turn.error carries only usage a
3071
+ * host-terminal event reports. */
3072
+ function closeErrorTurn(pausedTurnId: string, error: { code: string; message: string }, usage: AgUsage | undefined): void {
3073
+ const turnId = `${pausedTurnId}_error`;
3074
+ const messageId = ensureOpen(turnId);
3075
+ closedTurns.add(turnId);
3076
+ a.closeMessage(messageId);
3077
+ a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
2394
3078
  }
2395
3079
 
2396
3080
  /** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
@@ -2414,7 +3098,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2414
3098
  * close with the accumulated usage when the run ended on a non-final event,
2415
3099
  * e.g. a completed Workflow). */
2416
3100
  function hostComplete(): void {
2417
- for (const turnId of openTurns) {
3101
+ for (const turnId of [...openTurns]) {
2418
3102
  if (closedTurns.has(turnId)) continue;
2419
3103
  if (interruptPending.has(turnId)) {
2420
3104
  closeInterrupted(turnId);
@@ -2422,6 +3106,19 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2422
3106
  }
2423
3107
  const messageId = `msg_${turnId}`;
2424
3108
  const asks = pendingAsks.get(turnId);
3109
+ // Spec §8.0 items 26 and 35: an invocation that met an in-band error
3110
+ // never closes as success. A signalled pause closes paused, and the
3111
+ // error follows on its own turn; otherwise the turn closes turn.error.
3112
+ const error = firstInBandError.get(turnId);
3113
+ if (error !== undefined) {
3114
+ if (asks !== undefined && pauseSignalled(turnId)) {
3115
+ closePaused(turnId, messageId, asks);
3116
+ closeErrorTurn(turnId, error, undefined);
3117
+ } else {
3118
+ closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
3119
+ }
3120
+ continue;
3121
+ }
2425
3122
  if (asks !== undefined && asks.length > 0) {
2426
3123
  closePaused(turnId, messageId, asks);
2427
3124
  continue;
@@ -2429,7 +3126,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2429
3126
  if ((pendingLongRunning.get(turnId)?.size ?? 0) > 0) continue;
2430
3127
  const stashed = deferredClose.get(turnId);
2431
3128
  if (stashed !== undefined) {
2432
- closeOnFinalResponse(stashed, turnId, messageId, undefined);
3129
+ closeOnFinalResponse(stashed, turnId, messageId);
2433
3130
  continue;
2434
3131
  }
2435
3132
  closedTurns.add(turnId);
@@ -2454,8 +3151,21 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2454
3151
  let closed = 0;
2455
3152
  for (const turnId of [...openTurns].reverse()) {
2456
3153
  if (closedTurns.has(turnId)) continue;
3154
+ // A signalled pause on a turn with no interruption closes paused first,
3155
+ // then the error closes on a new top-level turn (spec §8.0 host
3156
+ // obligation 1 and item 26).
3157
+ const asks = pendingAsks.get(turnId);
3158
+ if (asks !== undefined && pauseSignalled(turnId) && !interruptPending.has(turnId)) {
3159
+ closePaused(turnId, `msg_${turnId}`, asks);
3160
+ closeErrorTurn(turnId, { code: err.code, message: err.message }, err.usage);
3161
+ closed++;
3162
+ continue;
3163
+ }
2457
3164
  closedTurns.add(turnId);
2458
- const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
3165
+ // The turn closes with the host's code and message and its accumulated
3166
+ // usage plus any usage the host reports, which covers only work the
3167
+ // stream did not report (spec §8.0 host obligation 1 and item 35).
3168
+ const usage = sumUsage(mapUsage(usageByTurn.get(turnId)), err.usage);
2459
3169
  a.closeMessage(`msg_${turnId}`);
2460
3170
  a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
2461
3171
  closed++;
@@ -2472,19 +3182,107 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2472
3182
  });
2473
3183
  }
2474
3184
 
3185
+ /** The part indexes whose text repeats a changed output rendering (see
3186
+ * drive()): skipped here and in the aggregate. */
3187
+ function skippedParts(event: AdkEvent, parts: readonly AdkPart[]): Set<number> {
3188
+ const renderedOutput = changedOutputRendering(event.output);
3189
+ const skipped = new Set<number>();
3190
+ if (renderedOutput !== undefined)
3191
+ parts.forEach((p, idx) => {
3192
+ if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput) skipped.add(idx);
3193
+ });
3194
+ return skipped;
3195
+ }
3196
+
3197
+ /** An event's reading against the aggregate windows of a turn (the rules
3198
+ * are stated in drive()). */
3199
+ function readWindow(turnId: string, event: AdkEvent, parts: readonly AdkPart[], skipped: ReadonlySet<number>, isPartial: boolean) {
3200
+ const isTextPart = (p: AdkPart, idx: number): boolean =>
3201
+ !skipped.has(idx) &&
3202
+ p.thought !== true &&
3203
+ p.functionCall === undefined &&
3204
+ typeof p.text === "string" &&
3205
+ p.text.length > 0;
3206
+ const carriesText = parts.some(isTextPart);
3207
+ const relay = relayOf(event);
3208
+ const relayStream = relay === null ? null : relayStreamKey(relay.task, relay.stream);
3209
+ const ownKey = aggregateWindowKey(turnId, event, relayStream);
3210
+ const snapshot = !isPartial && relay !== null && relay.stream === "snapshot" ? relay : null;
3211
+ const restated = snapshot !== null ? snapshotWindows(streamedText, turnId, event, snapshot.task) : null;
3212
+ const candidates = isPartial
3213
+ ? []
3214
+ : restated !== null
3215
+ ? [...restated.artifacts, ...restated.status]
3216
+ : windowCandidates(streamedText, turnId, event, ownKey, relay, relayStream);
3217
+ const [onlyCandidate] = candidates;
3218
+ const readKey = !isPartial && candidates.length === 1 && onlyCandidate !== undefined ? onlyCandidate : ownKey;
3219
+ const alreadyStreamed = isPartial
3220
+ ? (streamedText.get(ownKey) ?? "")
3221
+ : restated !== null
3222
+ ? snapshotReading(
3223
+ restated.artifacts.map((key) => streamedText.get(key) ?? "").join(""),
3224
+ restated.status.map((key) => streamedText.get(key) ?? "").join(""),
3225
+ parts
3226
+ .filter(isTextPart)
3227
+ .map((p) => p.text ?? "")
3228
+ .join(""),
3229
+ )
3230
+ : candidates.length === 1
3231
+ ? (streamedText.get(readKey) ?? "")
3232
+ : "";
3233
+ const matchesWindow = !isPartial && alreadyStreamed.length > 0 && carriesText;
3234
+ const eventText = matchesWindow
3235
+ ? parts
3236
+ .filter(isTextPart)
3237
+ .map((p) => p.text ?? "")
3238
+ .join("")
3239
+ : "";
3240
+ const suffixRepeat = matchesWindow && alreadyStreamed.endsWith(eventText);
3241
+ const isAggregate =
3242
+ matchesWindow &&
3243
+ (eventText.startsWith(alreadyStreamed) || alreadyStreamed.startsWith(eventText) || suffixRepeat);
3244
+ const aggregateText = isAggregate ? eventText : "";
3245
+ const suppressAggregateText =
3246
+ isAggregate && aggregateText.length > 0 && (alreadyStreamed.startsWith(aggregateText) || suffixRepeat);
3247
+ return { isTextPart, carriesText, ownKey, relay, relayStream, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText };
3248
+ }
3249
+
3250
+ /** Whether an event after a success close only repeats the closed turn's
3251
+ * streamed text: ADK's aggregate after a message-less block chunk closed
3252
+ * the turn. It stays on that turn, where the window suppresses it, rather
3253
+ * than opening a new one. */
3254
+ function repeatsClosedTurn(turnId: string, event: AdkEvent): boolean {
3255
+ if (event.partial === true) return false;
3256
+ const { parts } = splitPayloadParts(event.content?.parts ?? []);
3257
+ if (parts.length === 0) return false;
3258
+ const skipped = skippedParts(event, parts);
3259
+ const reading = readWindow(turnId, event, parts, skipped, false);
3260
+ return (
3261
+ reading.suppressAggregateText &&
3262
+ parts.every((p, idx) => skipped.has(idx) || reading.isTextPart(p, idx) || (p.thought !== true && p.text === ""))
3263
+ );
3264
+ }
3265
+
2475
3266
  function drive(event: AdkEvent, relayEchoOmitted = 0): void {
2476
- const turnId = liveTurnFor(event);
3267
+ const turnId = liveTurnFor(event, relayEchoOmitted > 0);
2477
3268
  // ADK re-yields a bare `{interrupted}` after a message that carried both
2478
3269
  // turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
2479
3270
  // 2.1.0). For a generation the barge-in already closed, it adds nothing:
2480
3271
  // no new turn and no second terminal, so the facet emits nothing for it.
3272
+ // An event push() removed parts from is not that re-yield even when
3273
+ // nothing is left of it: its marker needs a turn, so it opens the next
3274
+ // generation as an event with content would.
2481
3275
  if (turnId === undefined) return;
2482
3276
  const messageId = ensureOpen(turnId);
2483
3277
  // A relayed repeat of the forwarded request whose parts push() removed:
2484
3278
  // one content-free marker, after the opening of the turn the event maps
2485
3279
  // into.
2486
3280
  if (relayEchoOmitted > 0) a.emitExt("google", "relay-echo-omitted", { parts: relayEchoOmitted });
2487
- const parts = event.content?.parts ?? [];
3281
+ // A part holding text beside a payload member, or two payload members, is
3282
+ // split before any reader below classifies it (see splitPayloadParts), so
3283
+ // its text joins the aggregate as text does and each payload member maps
3284
+ // through its own arm.
3285
+ const { parts, origin: nativeIndexOf } = splitPayloadParts(event.content?.parts ?? []);
2488
3286
  const isPartial = event.partial === true;
2489
3287
  // ADK renders an object `output` as the same event's text part, byte-equal
2490
3288
  // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
@@ -2492,12 +3290,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2492
3290
  // repeat what the reduction removed, so that one part is skipped here and
2493
3291
  // in the aggregate below. Nothing else matches: not a string output, not
2494
3292
  // a substring, not model text.
2495
- const renderedOutput = changedOutputRendering(event.output);
2496
- const skipped = new Set<number>();
2497
- if (renderedOutput !== undefined)
2498
- parts.forEach((p, idx) => {
2499
- if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput) skipped.add(idx);
2500
- });
3293
+ const skipped = skippedParts(event, parts);
2501
3294
 
2502
3295
  // STREAMED-text citations carrier (audit M22): groundingMetadata is
2503
3296
  // EVENT-level, not per-part. A Gemini grounding response carries the full
@@ -2531,19 +3324,56 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2531
3324
  nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
2532
3325
  });
2533
3326
 
2534
- // §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
2535
- const alreadyStreamed = streamedText.get(turnId) ?? "";
2536
- const isAggregate = !isPartial && alreadyStreamed.length > 0;
2537
- const aggregateText = isAggregate
2538
- ? parts
2539
- .filter(
2540
- (p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string",
2541
- )
2542
- .map((p) => p.text ?? "")
2543
- .join("")
2544
- : "";
2545
- const suppressAggregateText =
2546
- isAggregate && aggregateText.length > 0 && alreadyStreamed.startsWith(aggregateText);
3327
+ // §8.3 — the aggregate suppression (§8.0 item 3). ADK re-yields a model
3328
+ // call's streamed text as one `partial: false` event: when the call closes,
3329
+ // in SSE before a non-text part in the same stream, and on the Live path
3330
+ // before a tool call, on a switch between thought and text, and on a
3331
+ // barge-in. The window holding the
3332
+ // text streamed so far is keyed per turn AND per source (author, branch,
3333
+ // node path, and for an event ADK's A2A relay forwards, the relayed stream:
3334
+ // one artifact, or the status messages; an absent value is its own key), so
3335
+ // interleaved streams never share one. Every non-partial event of the
3336
+ // source closes it, except the ones ADK yields between a call's chunks and
3337
+ // its re-yield, none of which carries text: a block chunk (no content, a
3338
+ // finishReason), a Live usage report or grounding record (no content and
3339
+ // nothing else a closing record carries: no errorCode, errorMessage,
3340
+ // finishReason, turnComplete, session-resumption update, goAway or state or
3341
+ // artifact delta, and for the usage report no interruption), a
3342
+ // transcription event, a `partial: false` event whose
3343
+ // parts are all non-text (a function call or media before the Interactions
3344
+ // route's re-yield), and a function response (progressive SSE runs a tool
3345
+ // mid-stream). A text event that closes the window is its re-yield when
3346
+ // one text starts with the other (equal; longer by text no chunk streamed,
3347
+ // whose tail renders; or shorter, a callback's replacement whose bytes
3348
+ // already streamed) or when the streamed text ends with its text (a later
3349
+ // call's re-yield after a call whose close never arrived, or ADK's
3350
+ // structured-output rewrite); any other text renders in full. An event
3351
+ // without a branch that finds no window under its own key (ADK's A2A relay
3352
+ // rebuilds its re-yield without one, and a failed call's in-band error
3353
+ // carries none) reads the open windows of the same turn, author and node
3354
+ // path: a re-yield matches only when exactly one is open, and a text-less
3355
+ // event that ends the match ends them all (a text with two or more
3356
+ // candidates closes none). A relayed stream is scoped by its A2A task. A
3357
+ // relayed artifact with no window of its own reads its task's status
3358
+ // window; a relayed Task or Message restates its task, so it is read, in
3359
+ // the order ADK renders a Task, against that task's artifact windows and
3360
+ // then its status window (snapshotReading), and closes them; and
3361
+ // the relaying agent's own failure event ends every relayed window of its
3362
+ // author and node path. An empty text part is not text.
3363
+ const {
3364
+ isTextPart,
3365
+ carriesText,
3366
+ ownKey,
3367
+ relay,
3368
+ relayStream,
3369
+ snapshot,
3370
+ candidates,
3371
+ readKey,
3372
+ alreadyStreamed,
3373
+ isAggregate,
3374
+ aggregateText,
3375
+ suppressAggregateText,
3376
+ } = readWindow(turnId, event, parts, skipped, isPartial);
2547
3377
  let residualTail =
2548
3378
  isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
2549
3379
  let accumulated = alreadyStreamed;
@@ -2580,6 +3410,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2580
3410
  a,
2581
3411
  part,
2582
3412
  index,
3413
+ nativeIndexOf[index] ?? index,
2583
3414
  event,
2584
3415
  messageId,
2585
3416
  turnId,
@@ -2593,8 +3424,32 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2593
3424
  if (isPartial) accumulated += contributed;
2594
3425
  });
2595
3426
 
2596
- if (isPartial) streamedText.set(turnId, accumulated);
2597
- else if (isAggregate) streamedText.delete(turnId);
3427
+ const stateDelta: unknown = event.actions?.stateDelta;
3428
+ const artifactDelta: unknown = event.actions?.artifactDelta;
3429
+ // Two records ADK's Live aggregator yields on their own between a call's
3430
+ // chunks and its repeat: its usage report, and the grounding metadata of
3431
+ // a message with no parts (a barge-in's among them). One that also carries
3432
+ // anything that ends a call is neither, and closes the window.
3433
+ const endsNoCall =
3434
+ event.errorCode === undefined &&
3435
+ event.errorMessage === undefined &&
3436
+ event.turnComplete !== true &&
3437
+ !Object.hasOwn(event, "liveSessionResumptionUpdate") &&
3438
+ !Object.hasOwn(event, "goAway") &&
3439
+ !(isJsonObject(stateDelta) && Object.keys(stateDelta).length > 0) &&
3440
+ !(isJsonObject(artifactDelta) && Object.keys(artifactDelta).length > 0);
3441
+ const usageReportOnly = endsNoCall && event.interrupted !== true && event.usageMetadata?.responseTokenCount !== undefined;
3442
+ const groundingOnly = endsNoCall && event.groundingMetadata !== undefined;
3443
+ const keepsWindowOpen =
3444
+ !carriesText &&
3445
+ ((event.partial === undefined && parts.length === 0 && (event.finishReason !== undefined || usageReportOnly || groundingOnly)) ||
3446
+ event.inputTranscription !== undefined ||
3447
+ event.outputTranscription !== undefined ||
3448
+ (event.partial === false && parts.length > 0) ||
3449
+ (parts.length > 0 && parts.every((p) => p.functionResponse !== undefined)));
3450
+ if (isPartial) streamedText.set(ownKey, accumulated);
3451
+ else if (carriesText) for (const key of snapshot !== null ? candidates : [readKey]) streamedText.delete(key);
3452
+ else if (!keepsWindowOpen) for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event, relay)]) streamedText.delete(key);
2598
3453
 
2599
3454
  // Round-3 review finding (regression on finding b): the resend window's
2600
3455
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
@@ -2611,13 +3466,21 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2611
3466
  // per-invoke.
2612
3467
 
2613
3468
  if (!isPartial) trackLongRunning(event, turnId);
2614
- driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
3469
+ const asksBefore = pendingAsks.get(turnId)?.length ?? 0;
3470
+ driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, closedTurns.has(turnId)); // standalone and content arms
3471
+ if ((pendingAsks.get(turnId)?.length ?? 0) > asksBefore) {
3472
+ const authors = askingAuthors.get(turnId) ?? new Set<string | undefined>();
3473
+ authors.add(event.author);
3474
+ askingAuthors.set(turnId, authors);
3475
+ }
2615
3476
  // A turn gets ONE terminal: an interrupt on a turn that already closed
2616
3477
  // (a second barge-in, or one after a success close) adds none.
2617
3478
  if (event.interrupted === true && !closedTurns.has(turnId)) interruptPending.add(turnId);
2618
3479
  carryLiveUsageDetails(event, turnId, messageId, isPartial);
2619
3480
  if (parts.some((p) => p.functionResponse !== undefined)) awaitingReply.add(turnId);
2620
3481
  else if (hasModelOutput(event)) awaitingReply.delete(turnId);
3482
+ // A non-relayed event's own window key is its source key.
3483
+ recordErrorAndUsage(event, turnId, isPartial, relayStream === null ? ownKey : aggregateWindowKey(turnId, event, null));
2621
3484
  maybeCloseTurn(event, turnId, messageId, isPartial);
2622
3485
  // The interrupted generation closes on its own turnComplete (its trailing
2623
3486
  // usageMetadata arrives before it), or at flush() / host completion.
@@ -2647,15 +3510,33 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2647
3510
 
2648
3511
  /** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
2649
3512
  * key), with `_g<n>` for the n-th generation after a barge-in closed the
2650
- * previous one. `undefined` for ADK's bare `{interrupted}` re-yield on a
2651
- * generation a barge-in already closed. */
2652
- function liveTurnFor(event: AdkEvent): string | undefined {
3513
+ * previous one. `undefined` for ADK's bare `{interrupted}` re-yield: the one
3514
+ * that directly follows a message carrying both turnComplete and
3515
+ * interrupted (utils/live_connection_utils.js yields that message's final
3516
+ * response, then the bare flag). Any other bare `{interrupted}` after a
3517
+ * barge-in closed the generation interrupts the next one. */
3518
+ function liveTurnFor(event: AdkEvent, omittedParts = false): string | undefined {
2653
3519
  const key = turnKey(event);
2654
3520
  const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
3521
+ const reyield = previousBothFlags.get(base) === true;
3522
+ previousBothFlags.set(base, event.turnComplete === true && event.interrupted === true);
2655
3523
  const g = generationOf.get(base) ?? 0;
2656
3524
  const current = g === 0 ? base : `${base}_g${g}`;
2657
- if (!interruptClosed.has(current)) return current;
2658
- if (event.interrupted === true && !hasLiveContent(event)) return undefined;
3525
+ // Any event after a success close opens the next generation, so no
3526
+ // message or block event names the closed turn (SPEC :959): content, a
3527
+ // usage report, a carry, an interruption. An `{interrupted}` after a
3528
+ // success close interrupts the next generation, which then closes
3529
+ // turn.abort interrupted; ADK's bare re-yield after a message carrying
3530
+ // both flags follows an interrupt close, handled below. Two stay: an event
3531
+ // whose only mapping is the state.delta of its stateDelta (shared state,
3532
+ // not the turn's content), and an aggregate that only repeats the closed
3533
+ // turn's streamed text (the window suppresses it).
3534
+ const afterSuccess =
3535
+ successClosed.has(current) &&
3536
+ !onlyStateChange(event) &&
3537
+ !repeatsClosedTurn(current, event);
3538
+ if (!interruptClosed.has(current) && !afterSuccess) return current;
3539
+ if (!afterSuccess && reyield && event.interrupted === true && !hasLiveContent(event) && !omittedParts) return undefined;
2659
3540
  generationOf.set(base, g + 1);
2660
3541
  return `${base}_g${g + 1}`;
2661
3542
  }
@@ -2710,7 +3591,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2710
3591
  omitted = stripped.omitted;
2711
3592
  }
2712
3593
  if (!isAdkEvent(event)) {
2713
- a.emitExt("google", "unparsed", { native: nativeWithoutRelayBookkeeping(event) });
3594
+ a.emitExt("google", "unparsed", { native: nativeWithCarriedMetadata(event) });
2714
3595
  return a.drain();
2715
3596
  }
2716
3597
  drive(event, omitted);
@@ -2730,7 +3611,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2730
3611
  // Workflow invoke until the host completion signal exists, still reports
2731
3612
  // the tokens it spent. There is never a turn.done here, so the usage
2732
3613
  // appears only once.
2733
- for (const turnId of openTurns) {
3614
+ for (const turnId of [...openTurns]) {
2734
3615
  if (closedTurns.has(turnId)) continue;
2735
3616
  if (interruptPending.has(turnId)) {
2736
3617
  closeInterrupted(turnId);
@@ -2738,11 +3619,20 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2738
3619
  }
2739
3620
  // A pause the stream saw end (its pause-end event, or a final response
2740
3621
  // while an ask was pending) is a resolved pause, not a truncation: it
2741
- // closes paused here (SPEC §8.0 item 26). Asks with neither stay a
2742
- // truncation, as above.
3622
+ // closes paused here (SPEC §8.0 item 26), and an in-band error of its
3623
+ // invocation then closes on its own turn. Asks with neither stay a
3624
+ // truncation, as above, unless the invocation met an in-band error:
3625
+ // that turn, like any other of such an invocation, closes turn.error
3626
+ // (spec §8.0 item 35, INV-FLUSH (2)).
2743
3627
  const asks = pendingAsks.get(turnId);
2744
- if (asks !== undefined && asks.length > 0 && (pauseEnded.has(turnId) || deferredClose.has(turnId))) {
3628
+ const error = firstInBandError.get(turnId);
3629
+ if (asks !== undefined && pauseSignalled(turnId)) {
2745
3630
  closePaused(turnId, `msg_${turnId}`, asks);
3631
+ if (error !== undefined) closeErrorTurn(turnId, error, undefined);
3632
+ continue;
3633
+ }
3634
+ if (error !== undefined) {
3635
+ closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
2746
3636
  continue;
2747
3637
  }
2748
3638
  closedTurns.add(turnId);