@silverprotocol/google-adk 0.12.4 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js 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
  */
@@ -114,6 +114,8 @@ function resolveFinishReason(reason) {
114
114
  case "PROHIBITED_CONTENT":
115
115
  case "SPII":
116
116
  case "IMAGE_SAFETY":
117
+ case "IMAGE_PROHIBITED_CONTENT":
118
+ case "IMAGE_RECITATION":
117
119
  return { value: "safety_blocked", lossy: false };
118
120
  case "MALFORMED_FUNCTION_CALL":
119
121
  return { value: "malformed_tool_call", lossy: false };
@@ -365,6 +367,56 @@ const USAGE_SUM_FIELDS = [
365
367
  "toolUsePromptTokenCount",
366
368
  "responseTokenCount",
367
369
  ];
370
+ /** The per-kind count members of AgUsage, which sumUsage sums with an absent
371
+ * count read as 0. */
372
+ const USAGE_COUNTS = [
373
+ "inputTokens",
374
+ "outputTokens",
375
+ "cacheReadTokens",
376
+ "cacheWriteTokens",
377
+ "reasoningTokens",
378
+ "toolUseInputTokens",
379
+ "serverToolRequests",
380
+ ];
381
+ /** The aggregate members of AgUsage, which sumUsage sums only when both
382
+ * records carry them: a total or a cost one record lacks would understate
383
+ * the sum (spec §4: totals are copied, never computed). */
384
+ const USAGE_AGGREGATES = ["totalTokens", "totalTokensRaw", "costUsd"];
385
+ /** The field-wise sum of two usage records: each per-kind count present in
386
+ * either is summed (an absent count is 0), each aggregate only when both
387
+ * carry it (otherwise it is omitted), per model too; every other member is
388
+ * the first record's, else the second's. Either absent returns the other. */
389
+ function sumUsage(a, b) {
390
+ if (a === undefined)
391
+ return b;
392
+ if (b === undefined)
393
+ return a;
394
+ const out = { ...b, ...a };
395
+ for (const key of USAGE_COUNTS) {
396
+ const x = a[key];
397
+ const y = b[key];
398
+ if (x !== undefined || y !== undefined)
399
+ out[key] = (x ?? 0) + (y ?? 0);
400
+ }
401
+ for (const key of USAGE_AGGREGATES) {
402
+ const x = a[key];
403
+ const y = b[key];
404
+ if (x !== undefined && y !== undefined)
405
+ out[key] = x + y;
406
+ else
407
+ delete out[key];
408
+ }
409
+ if (a.byModel !== undefined || b.byModel !== undefined) {
410
+ const byModel = {};
411
+ for (const model of new Set([...Object.keys(a.byModel ?? {}), ...Object.keys(b.byModel ?? {})])) {
412
+ const sum = sumUsage(a.byModel?.[model], b.byModel?.[model]);
413
+ if (sum !== undefined)
414
+ byModel[model] = sum;
415
+ }
416
+ out.byModel = byModel;
417
+ }
418
+ return out;
419
+ }
368
420
  /** Fold one event's usageMetadata into a turn's running accumulator
369
421
  * (field-wise sum; absent fields stay absent so mapUsage's presence checks
370
422
  * keep working). Returns the accumulator (creating it on first use). */
@@ -393,6 +445,49 @@ function mapBlockedSafety(ratings) {
393
445
  }));
394
446
  return out.length > 0 ? out : undefined;
395
447
  }
448
+ // ─── ADK's prompt-block event (errorCode) → prompt.blocked (spec §4) ─────────
449
+ /**
450
+ * The errorCode values that mark an ADK event as a blocked prompt: genai
451
+ * 2.24.0's `BlockedReason` values and the Gemini API's spelling of the
452
+ * unspecified one. In StreamingMode NONE, @google/adk 2.1.0's
453
+ * `createLlmResponse` (models/llm_response.js) turns a blocked prompt into an
454
+ * event whose errorCode is the block reason, with no finishReason, no content
455
+ * and no safety ratings. Exported so the e2e suite's genai pin test
456
+ * (e2e/src/adk-prompt-block-reasons.pin.test.ts) can hold it against genai's
457
+ * own `BlockedReason`. It restates the peer's native values, so it changes
458
+ * when they do.
459
+ *
460
+ * @beta
461
+ */
462
+ export const ADK_PROMPT_BLOCK_REASONS = [
463
+ "BLOCKED_REASON_UNSPECIFIED",
464
+ "SAFETY",
465
+ "OTHER",
466
+ "BLOCKLIST",
467
+ "PROHIBITED_CONTENT",
468
+ "IMAGE_SAFETY",
469
+ "MODEL_ARMOR",
470
+ "JAILBREAK",
471
+ "BLOCK_REASON_UNSPECIFIED",
472
+ ];
473
+ const PROMPT_BLOCK_REASONS = new Set(ADK_PROMPT_BLOCK_REASONS);
474
+ /** The block reason when an event is an ADK prompt block (a treated errorCode,
475
+ * no finishReason, which a response-level block keeps beside errorCode, no
476
+ * content parts, and not relayed), else undefined. ADK's A2A relay marks each
477
+ * event it forwards with an a2a:response entry in customMetadata and drops the
478
+ * finishReason, so a relayed prompt block and a relayed response-level block
479
+ * with the same code arrive alike: no relayed event is read as a prompt block. */
480
+ function adkPromptBlockReason(event) {
481
+ const code = event.errorCode;
482
+ const relayed = isJsonObject(event.customMetadata) && Object.hasOwn(event.customMetadata, "a2a:response");
483
+ return typeof code === "string" &&
484
+ PROMPT_BLOCK_REASONS.has(code) &&
485
+ event.finishReason === undefined &&
486
+ (event.content?.parts ?? []).length === 0 &&
487
+ !relayed
488
+ ? code
489
+ : undefined;
490
+ }
396
491
  // ─── promptFeedback.blockReason → prompt.blocked reason (spec §4) ────────────
397
492
  // Maps Gemini blockReason to the AgJSON prompt.blocked reason enum.
398
493
  function mapBlockReason(reason) {
@@ -572,6 +667,36 @@ function isAdkPauseEnd(event) {
572
667
  function hasLiveContent(ev) {
573
668
  return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
574
669
  }
670
+ // Members of an ADK event that the facet maps to nothing, with the values
671
+ // ADK gives them by default; a member's other value, or any other member,
672
+ // maps to something. The `actions` members are listed below.
673
+ const NO_EMIT_EVENT_MEMBERS = new Set(["invocationId", "author", "id", "timestamp"]);
674
+ const NO_EMIT_ACTION_MEMBERS = new Set(["artifactDelta", "requestedAuthConfigs", "requestedToolConfirmations"]);
675
+ function isEmptyObject(v) {
676
+ return isJsonObject(v) && Object.keys(v).length === 0;
677
+ }
678
+ /** Whether all an event maps to is the state.delta of its stateDelta (or
679
+ * nothing): every member is one the facet maps to nothing, holding ADK's
680
+ * default value, but for `actions.stateDelta`. */
681
+ function onlyStateChange(ev) {
682
+ for (const [key, value] of Object.entries(ev)) {
683
+ if (value === undefined || NO_EMIT_EVENT_MEMBERS.has(key))
684
+ continue;
685
+ if (key === "longRunningToolIds" && Array.isArray(value) && value.length === 0)
686
+ continue;
687
+ if (key !== "actions" || !isJsonObject(value))
688
+ return false;
689
+ for (const [action, member] of Object.entries(value)) {
690
+ if (member === undefined || action === "stateDelta")
691
+ continue;
692
+ if (action === "escalate" && member === false)
693
+ continue;
694
+ if (!NO_EMIT_ACTION_MEMBERS.has(action) || !isEmptyObject(member))
695
+ return false;
696
+ }
697
+ }
698
+ return true;
699
+ }
575
700
  /** Whether an event carries model output: a part of `model`-role content, or
576
701
  * output-transcription text. ADK's function response is `user`-role. */
577
702
  function hasModelOutput(ev) {
@@ -777,17 +902,101 @@ function functionResponseToToolDoneFields(name, response) {
777
902
  function mapGroundingCitations(gm) {
778
903
  if (gm?.groundingSupports === undefined || gm.groundingSupports.length === 0)
779
904
  return undefined;
780
- return gm.groundingSupports.map((support) => ({
781
- kind: "offset",
782
- unit: "byte",
783
- startIndex: support.segment?.startIndex ?? 0,
784
- endIndex: support.segment?.endIndex ?? 0,
785
- bounds: "[start,end)",
786
- sourceIds: support.groundingChunkIndices?.map((i) => `grounding_${i}`) ?? [],
787
- confidenceScores: support.confidenceScores ?? [],
788
- citedText: support.segment?.text ?? "",
789
- indexFrame: "response",
790
- }));
905
+ return gm.groundingSupports.map((support) => {
906
+ // genai types these members (numbers, a string, number lists). A value of
907
+ // another type has no AgCitation home: the citation takes the member's
908
+ // default (0, "", []) or, for the optional scores, omits it, and the
909
+ // event-level carry holds the native value verbatim
910
+ // (groundingSupportsCarry). Nothing is filtered: ADK pairs each score with
911
+ // the chunk index at the same position.
912
+ const read = readSupport(support);
913
+ return {
914
+ kind: "offset",
915
+ unit: "byte",
916
+ startIndex: read.startIndex ?? 0,
917
+ endIndex: read.endIndex ?? 0,
918
+ bounds: "[start,end)",
919
+ sourceIds: (read.chunkIndices ?? []).map((i) => `grounding_${i}`),
920
+ ...(read.scores !== undefined ? { confidenceScores: read.scores } : {}),
921
+ citedText: read.text ?? "",
922
+ indexFrame: "response",
923
+ };
924
+ });
925
+ }
926
+ /** One grounding support's members as AgCitation takes them. An absent or
927
+ * JSON-null member reads as its default; a member of another type reads as undefined, and its
928
+ * native value is named in `unmapped`. */
929
+ function readSupport(support) {
930
+ const unmapped = {};
931
+ const member = (key) => (isJsonObject(support) ? support[key] : undefined);
932
+ const segment = member("segment");
933
+ const seg = (key) => (isJsonObject(segment) ? segment[key] : undefined);
934
+ const startRaw = seg("startIndex");
935
+ const endRaw = seg("endIndex");
936
+ const textRaw = seg("text");
937
+ const startIndex = startRaw === undefined || startRaw === null ? 0 : finiteNumber(startRaw);
938
+ const endIndex = endRaw === undefined || endRaw === null ? 0 : finiteNumber(endRaw);
939
+ const text = textRaw === undefined || textRaw === null ? "" : typeof textRaw === "string" ? textRaw : undefined;
940
+ const segmentMapped = (segment === undefined || segment === null || isJsonObject(segment)) && startIndex !== undefined && endIndex !== undefined && text !== undefined;
941
+ if (!segmentMapped)
942
+ unmapped["segment"] = JsonValue.parse(segment);
943
+ const indicesRaw = member("groundingChunkIndices");
944
+ const chunkIndices = indicesRaw === undefined || indicesRaw === null ? [] : chunkIndexList(indicesRaw);
945
+ if (chunkIndices === undefined)
946
+ unmapped["groundingChunkIndices"] = JsonValue.parse(indicesRaw);
947
+ const scoresRaw = member("confidenceScores");
948
+ const scores = scoresRaw === undefined || scoresRaw === null ? [] : finiteScores(scoresRaw);
949
+ if (scores === undefined)
950
+ unmapped["confidenceScores"] = JsonValue.parse(scoresRaw);
951
+ return { startIndex, endIndex, text, chunkIndices, scores, unmapped };
952
+ }
953
+ /** The value when it is a finite number, else undefined. */
954
+ function finiteNumber(value) {
955
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
956
+ }
957
+ /** The value when it is a list of finite numbers, else undefined. */
958
+ function finiteScores(value) {
959
+ if (!Array.isArray(value))
960
+ return undefined;
961
+ const scores = [];
962
+ for (const score of value) {
963
+ const n = finiteNumber(score);
964
+ if (n === undefined)
965
+ return undefined;
966
+ scores.push(n);
967
+ }
968
+ return scores;
969
+ }
970
+ /** The value when it is a list of chunk indexes (non-negative integers), else
971
+ * undefined. */
972
+ function chunkIndexList(value) {
973
+ if (!Array.isArray(value))
974
+ return undefined;
975
+ const indices = [];
976
+ for (const index of value) {
977
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0)
978
+ return undefined;
979
+ indices.push(index);
980
+ }
981
+ return indices;
982
+ }
983
+ /** The grounding supports' members that mapGroundingCitations could not map,
984
+ * verbatim at their native path: one entry per support, in order, holding
985
+ * those members (the whole `segment` when one of its members did not map)
986
+ * and nothing for a support that mapped whole. Undefined when every support
987
+ * mapped. */
988
+ function groundingSupportsCarry(gm) {
989
+ const supports = gm?.groundingSupports;
990
+ if (!Array.isArray(supports))
991
+ return undefined;
992
+ let any = false;
993
+ const entries = supports.map((support) => {
994
+ const { unmapped } = readSupport(support);
995
+ if (Object.keys(unmapped).length > 0)
996
+ any = true;
997
+ return unmapped;
998
+ });
999
+ return any ? { groundingSupports: entries } : undefined;
791
1000
  }
792
1001
  function toolCallContentKey(turnId, name, args) {
793
1002
  return `${turnId} ${name} ${JSON.stringify(args ?? {})}`;
@@ -861,7 +1070,85 @@ function mintBlockId(m, kind) {
861
1070
  m.set(kind, n + 1);
862
1071
  return `${kind}:${n}`;
863
1072
  }
864
- function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
1073
+ /** Whether a part carries a member one of driveAdkPart's non-text arms maps:
1074
+ * a call, a result, inline or file data, or code or its result. */
1075
+ function carriesPayload(part) {
1076
+ return (part.functionCall !== undefined ||
1077
+ part.functionResponse !== undefined ||
1078
+ part.inlineData !== undefined ||
1079
+ part.fileData !== undefined ||
1080
+ part.executableCode !== undefined ||
1081
+ part.codeExecutionResult !== undefined);
1082
+ }
1083
+ /** An event's parts with each part that holds text beside a payload member,
1084
+ * or two or more payload members, split into one part per payload member in
1085
+ * driveAdkPart's arm order, after a part holding its text (a genai Part holds
1086
+ * one kind of data, so such a part is malformed; every arm returns, and each
1087
+ * arm after the first would never map). The first part keeps the text, the
1088
+ * thought signature and every unmapped member (they are carried once); each
1089
+ * payload part holds its member alone, marked as thought when the original
1090
+ * part was. So the parts map as the same event with the split parts would
1091
+ * (but for the positions below): the text in its text or reasoning block,
1092
+ * and each payload member through its own arm, credential scrubs included
1093
+ * (SPEC.md §8.0, graceful degradation: no native value is dropped
1094
+ * silently). Any other part is
1095
+ * unchanged, and an event with no such part keeps its array. `origin` holds,
1096
+ * for each resulting part, the index of the native part it came from: a
1097
+ * null-id call's providerCallIndex and tool.start's `index` record that
1098
+ * original position (SPEC.md §8.0 item 2), never the split one. */
1099
+ function splitPayloadParts(parts) {
1100
+ if (!parts.some((p) => payloadCount(p) > (typeof p.text === "string" ? 0 : 1)))
1101
+ return { parts, origin: parts.map((_, i) => i) };
1102
+ const out = [];
1103
+ const origin = [];
1104
+ for (const [nativeIndex, part] of parts.entries()) {
1105
+ const textual = typeof part.text === "string";
1106
+ if (payloadCount(part) <= (textual ? 0 : 1)) {
1107
+ out.push(part);
1108
+ origin.push(nativeIndex);
1109
+ continue;
1110
+ }
1111
+ const { functionCall, functionResponse, inlineData, executableCode, codeExecutionResult, fileData, ...rest } = part;
1112
+ const mark = part.thought === true ? { thought: true } : {};
1113
+ const halves = [];
1114
+ if (functionCall !== undefined)
1115
+ halves.push({ functionCall, ...mark });
1116
+ if (functionResponse !== undefined)
1117
+ halves.push({ functionResponse, ...mark });
1118
+ if (inlineData !== undefined)
1119
+ halves.push({ inlineData, ...mark });
1120
+ if (executableCode !== undefined)
1121
+ halves.push({ executableCode, ...mark });
1122
+ if (codeExecutionResult !== undefined)
1123
+ halves.push({ codeExecutionResult, ...mark });
1124
+ if (fileData !== undefined)
1125
+ halves.push({ fileData, ...mark });
1126
+ const [first, ...others] = halves;
1127
+ const split = textual || first === undefined ? [rest, ...halves] : [{ ...rest, ...first }, ...others];
1128
+ out.push(...split);
1129
+ for (let k = 0; k < split.length; k++)
1130
+ origin.push(nativeIndex);
1131
+ }
1132
+ return { parts: out, origin };
1133
+ }
1134
+ /** How many of driveAdkPart's payload members a part holds. */
1135
+ function payloadCount(part) {
1136
+ let n = 0;
1137
+ if (part.functionCall !== undefined)
1138
+ n++;
1139
+ if (part.functionResponse !== undefined)
1140
+ n++;
1141
+ if (part.inlineData !== undefined)
1142
+ n++;
1143
+ if (part.executableCode !== undefined)
1144
+ n++;
1145
+ if (part.codeExecutionResult !== undefined)
1146
+ n++;
1147
+ if (part.fileData !== undefined)
1148
+ n++;
1149
+ return n;
1150
+ }
1151
+ function driveAdkPart(a, part, index, nativeIndex, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
865
1152
  // ── UNMAPPED PART FIELDS (mediaResolution/videoMetadata/toolCall/toolResponse/
866
1153
  // partMetadata/audioTranscription/mediaProcessing/speechMetadata) → provider-raw content.block
867
1154
  // (fixture-drift ratchet finding, google-adk-ratchet task; Tenet-6; SPEC §8 item 23). These
@@ -900,6 +1187,16 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
900
1187
  unmappedPartFields["mediaProcessing"] = JsonValue.parse(part.mediaProcessing);
901
1188
  if (part.speechMetadata !== undefined)
902
1189
  unmappedPartFields["speechMetadata"] = JsonValue.parse(part.speechMetadata);
1190
+ // A part marked as thought that carries no text but a call, a result or
1191
+ // media (ADK-Python's A2A relay marks every part it converts from a remote
1192
+ // agent's in-progress status as thought) maps through that
1193
+ // payload's arm below, as it would unmarked, and not as an empty reasoning
1194
+ // block. Its `thought` flag, which no event of those arms holds, rides this
1195
+ // carry (SPEC.md §8.0, graceful degradation: no native value is dropped
1196
+ // silently).
1197
+ const thoughtPayload = part.thought === true && typeof part.text !== "string" && carriesPayload(part);
1198
+ if (thoughtPayload)
1199
+ unmappedPartFields["thought"] = true;
903
1200
  if (Object.keys(unmappedPartFields).length > 0) {
904
1201
  a.contentBlock(messageId, {
905
1202
  type: "provider-raw",
@@ -908,7 +1205,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
908
1205
  });
909
1206
  }
910
1207
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
911
- if (part.thought === true) {
1208
+ if (part.thought === true && !thoughtPayload) {
912
1209
  const id = mintBlockId(blockIds, "reasoning");
913
1210
  a.reasoningStart(id, messageId);
914
1211
  // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
@@ -978,7 +1275,8 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
978
1275
  return ""; // dedup the partial:false aggregate re-send (window-scoped content identity)
979
1276
  toolCallId = minted.toolCallId;
980
1277
  }
981
- const providerCallIndex = realId !== null ? undefined : index;
1278
+ // The native part's position, not the split one (see splitPayloadParts).
1279
+ const providerCallIndex = realId !== null ? undefined : nativeIndex;
982
1280
  // The reserved credential call's args carry the whole ADK AuthConfig: scrub
983
1281
  // them to the allowlist (see scrubAdkAuthConfig) before they reach
984
1282
  // tool.args.* and the folded tool-call block.
@@ -990,7 +1288,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
990
1288
  a.toolStart({
991
1289
  toolCallId,
992
1290
  name: fc.name,
993
- index,
1291
+ index: nativeIndex,
994
1292
  longRunning,
995
1293
  providerMetadata: providerCallIndex !== undefined
996
1294
  ? AgProviderMeta.parse({ google: { providerCallIndex } })
@@ -1145,7 +1443,7 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
1145
1443
  else
1146
1444
  pendingAsks.set(turnId, [ask]);
1147
1445
  }
1148
- function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription) {
1446
+ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, turnClosed) {
1149
1447
  // Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
1150
1448
  // a `finished: true` transcription whose text is the chunks joined
1151
1449
  // (utils/live_connection_utils.js, @google/adk 2.1.0). That aggregate is not
@@ -1180,8 +1478,17 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1180
1478
  }
1181
1479
  // `interrupted` → turn.abort is closed in drive(), after this event's own
1182
1480
  // content and carries (see closeInterrupted), never here mid-event.
1183
- // ── promptFeedback → prompt.blocked ──
1184
- if (event.promptFeedback?.blockReason !== undefined) {
1481
+ // ── prompt block → prompt.blocked: one record per block event while the turn
1482
+ // is open, never after its terminal. A record runs before the close logic, so
1483
+ // it precedes the terminal the same event may bring; the terminal itself is
1484
+ // unchanged. An event carrying promptFeedback is recorded from it (a
1485
+ // dual-shape event records once); otherwise ADK's own shape records: a treated
1486
+ // errorCode with no finishReason and no content (adkPromptBlockReason), reason
1487
+ // mapped as below and no safety, since that event carries no ratings.
1488
+ if (turnClosed) {
1489
+ // no record after the turn's terminal
1490
+ }
1491
+ else if (event.promptFeedback?.blockReason !== undefined) {
1185
1492
  const blockReason = event.promptFeedback.blockReason;
1186
1493
  const reason = mapBlockReason(blockReason);
1187
1494
  const safety = event.promptFeedback.safetyRatings !== undefined
@@ -1196,10 +1503,9 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1196
1503
  : undefined;
1197
1504
  // draft.8 (§4): an unmapped block reason (reason "other") carries the
1198
1505
  // native value verbatim in reasonRaw; a mapped reason carries none, as a
1199
- // lossless finishReason takes no finishReasonRaw (§10 item 23). On
1200
- // @google/adk 2.1.0 no ADK-built event carries promptFeedback: its
1201
- // createLlmResponse turns a prompt block into errorCode/errorMessage
1202
- // (models/llm_response.js), so this arm serves events built elsewhere.
1506
+ // lossless finishReason takes no finishReasonRaw. No ADK-built event
1507
+ // carries promptFeedback at @google/adk 2.1.0, so this arm serves events
1508
+ // built elsewhere; ADK's own shape is the branch below.
1203
1509
  a.emit({
1204
1510
  type: "prompt.blocked",
1205
1511
  reason,
@@ -1207,6 +1513,13 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1207
1513
  ...(safety !== undefined ? { safety } : {}),
1208
1514
  });
1209
1515
  }
1516
+ else {
1517
+ const blockReason = adkPromptBlockReason(event);
1518
+ if (blockReason !== undefined) {
1519
+ const reason = mapBlockReason(blockReason);
1520
+ a.emit({ type: "prompt.blocked", reason, ...(reason === "other" ? { reasonRaw: blockReason } : {}) });
1521
+ }
1522
+ }
1210
1523
  // ── groundingMetadata → source + display.required ──────────────────────────
1211
1524
  // groundingSupports (per-segment citations) are handled BEFORE this function
1212
1525
  // runs — collected by `mapGroundingCitations` and attached to the streamed text
@@ -1374,8 +1687,10 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1374
1687
  // absent from `@iqai/adk`'s surface, closed by the same opportunistic-carry
1375
1688
  // precedent (absent from all recorded fixtures — no golden-snapshot impact).
1376
1689
  //
1377
- // `author`/`timestamp` are ALSO real, currently-unread AdkEvent fields
1378
- // (same manifest inventory) but are DELIBERATELY NOT folded into this bag.
1690
+ // `author`/`timestamp` are ALSO real AdkEvent fields (same manifest
1691
+ // inventory) but are DELIBERATELY NOT folded into this bag (`author` is read
1692
+ // only by the aggregate window: its key, aggregateWindowKey, and the
1693
+ // same-author lookup in windowCandidates).
1379
1694
  // On the official `@google/adk` 1.3.0 `Event` interface `timestamp: number`
1380
1695
  // is REQUIRED and `author?: string` is optional in the TYPE — but the
1381
1696
  // runner sets author on every event it appends in practice, so the
@@ -1436,11 +1751,28 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1436
1751
  unmappedEvent["isolationScope"] = JsonValue.parse(event.isolationScope);
1437
1752
  if (event.citationMetadata !== undefined)
1438
1753
  unmappedEvent["citationMetadata"] = JsonValue.parse(event.citationMetadata);
1754
+ const groundingSupports = groundingSupportsCarry(event.groundingMetadata);
1755
+ if (groundingSupports !== undefined)
1756
+ unmappedEvent["groundingMetadata"] = groundingSupports;
1439
1757
  if (event.customMetadata !== undefined) {
1440
1758
  const kept = withoutRelayBookkeeping(JsonValue.parse(event.customMetadata));
1441
1759
  if (kept !== undefined)
1442
1760
  unmappedEvent["customMetadata"] = kept;
1443
1761
  }
1762
+ // An error message without an error code (ADK's A2A relay reports its own
1763
+ // failure so, and a remote executor's that it passes on) is not an in-band
1764
+ // invocation error (spec §8.0 item 35), which maps the code and message as a
1765
+ // pair; its message, and a code that is not a string, ride here verbatim
1766
+ // (spec §8.0 graceful degradation and item 23).
1767
+ if (inBandErrorOf(event) === undefined) {
1768
+ const message = event.errorMessage;
1769
+ const code = event.errorCode;
1770
+ if (message !== undefined && message !== null) {
1771
+ if (code !== undefined && code !== null)
1772
+ unmappedEvent["errorCode"] = JsonValue.parse(code);
1773
+ unmappedEvent["errorMessage"] = JsonValue.parse(message);
1774
+ }
1775
+ }
1444
1776
  if (Object.keys(unmappedEvent).length > 0) {
1445
1777
  a.contentBlock(messageId, {
1446
1778
  type: "provider-raw",
@@ -1455,7 +1787,11 @@ export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
1455
1787
  * SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
1456
1788
  * the stream (e.g. its LLM-call limit), the host catches it and pushes
1457
1789
  * `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
1458
- * open turn closes `turn.error` with that code and message. The shape matches the OpenAI
1790
+ * open turn closes `turn.error` with that code and message and the turn's
1791
+ * usage plus `usage`, which covers only work the stream did not report (so
1792
+ * a host passes the usage of unreported work, never a total); a turn whose
1793
+ * pause was signalled closes paused first, and the error then closes on a
1794
+ * new top-level turn (spec §8.0 item 26). The shape matches the OpenAI
1459
1795
  * facet's sentinel. A host may build it from the caught Error itself
1460
1796
  * (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
1461
1797
  * read from the raw native, so the Error's own message is kept.
@@ -1510,6 +1846,178 @@ function isHostCompleteNative(v) {
1510
1846
  * So push() never throws (SPEC §8.0), and no facet state believes a turn,
1511
1847
  * message or block is open that never reached the wire.
1512
1848
  */
1849
+ // ─── ADK in-band invocation errors (spec §8.0 item 35) ───────────────────────
1850
+ // ADK yields an in-band invocation error (errorCode AND errorMessage) without
1851
+ // ending the invocation: a SequentialAgent runs its next sub-agent, a Workflow
1852
+ // node retries, a callback or a further model round follows. So the turn never
1853
+ // closes on one: the push() that receives it emits the non-terminal `error`
1854
+ // event, and the invocation's turn closes with one turn.error at the
1855
+ // invocation's end (the host-completion event, a host-terminal event or
1856
+ // flush()), never as success.
1857
+ /** Spec §8.0 item 35: an in-band invocation error carries both errorCode and
1858
+ * errorMessage. */
1859
+ function inBandErrorOf(event) {
1860
+ const code = event.errorCode;
1861
+ const message = event.errorMessage;
1862
+ return typeof code === "string" && typeof message === "string" ? { code, message } : undefined;
1863
+ }
1864
+ /** The record item 35's relay repeat compares for one in-band error. */
1865
+ function inBandErrorRecord(event, error) {
1866
+ const metadata = event.customMetadata;
1867
+ return {
1868
+ code: error.code,
1869
+ message: error.message,
1870
+ usage: event.usageMetadata !== undefined ? canonicalJson(JsonValue.parse(event.usageMetadata)) : "",
1871
+ taskId: isJsonObject(metadata) && Object.hasOwn(metadata, "a2a:task_id") ? canonicalJson(metadata["a2a:task_id"] ?? null) : "",
1872
+ };
1873
+ }
1874
+ /** Item 35's relay repeat: `RemoteA2AAgent` stamps an `a2a:request` entry on
1875
+ * each relayed event that carries `turnComplete: true`, and at @google/adk
1876
+ * 2.1.0 it reports a remote failure that carries no content only in that
1877
+ * closing event, so one failure can reach the facet twice. The closing event
1878
+ * repeats an earlier in-band error of the same source when the code, message
1879
+ * and usage report are equal (an absent report matches only an absent one)
1880
+ * and both carry the same `a2a:task_id` entry, present on both. */
1881
+ function isRelayRepeat(event, record, earlier) {
1882
+ const metadata = event.customMetadata;
1883
+ if (event.turnComplete !== true || !isJsonObject(metadata) || !Object.hasOwn(metadata, "a2a:request"))
1884
+ return false;
1885
+ if (record.taskId === "")
1886
+ return false;
1887
+ return earlier.some((e) => e.taskId === record.taskId && e.code === record.code && e.message === record.message && e.usage === record.usage);
1888
+ }
1889
+ /** The aggregate window's key: the turn plus the event's source (author,
1890
+ * branch and node path). A missing or non-string value is its own key, never
1891
+ * equal to an empty string. */
1892
+ function aggregateWindowKey(turnId, event, stream = relayStreamOf(event)) {
1893
+ const author = event.author;
1894
+ const branch = event.branch;
1895
+ const path = event.nodeInfo?.path;
1896
+ return JSON.stringify([
1897
+ turnId,
1898
+ typeof author === "string" ? author : null,
1899
+ typeof branch === "string" ? branch : null,
1900
+ typeof path === "string" ? path : null,
1901
+ stream,
1902
+ ]);
1903
+ }
1904
+ /** What a relayed event is, read from the native relay record ADK's
1905
+ * RemoteA2AAgent attaches: its A2A task (the `a2a:task_id` entry, null when
1906
+ * the reply carried none) and its stream, one artifact's chunks and their
1907
+ * aggregate (`artifact:<id>`), the status messages (`status`), or a Task or
1908
+ * Message that restates the task (`snapshot`). null for an event that is not
1909
+ * relayed. */
1910
+ function relayOf(event) {
1911
+ const metadata = event.customMetadata;
1912
+ if (!isJsonObject(metadata))
1913
+ return null;
1914
+ const response = metadata["a2a:response"];
1915
+ if (!isJsonObject(response))
1916
+ return null;
1917
+ const taskId = metadata["a2a:task_id"];
1918
+ const task = typeof taskId === "string" ? taskId : null;
1919
+ const kind = response["kind"];
1920
+ const artifact = response["artifact"];
1921
+ if (kind === "artifact-update" && isJsonObject(artifact) && typeof artifact["artifactId"] === "string")
1922
+ return { task, stream: `artifact:${artifact["artifactId"]}` };
1923
+ if (kind === "status-update")
1924
+ return { task, stream: "status" };
1925
+ if (kind === "task" || kind === "message")
1926
+ return { task, stream: "snapshot" };
1927
+ return null;
1928
+ }
1929
+ /** The window-key part of a relayed stream: the task and the stream, so a new
1930
+ * relay pass (a new A2A task) never reads the windows of an earlier one. */
1931
+ function relayStreamKey(task, stream) {
1932
+ return JSON.stringify([task, stream]);
1933
+ }
1934
+ /** The A2A stream a relayed event belongs to, scoped by its task; null for
1935
+ * every event that is not relayed. */
1936
+ function relayStreamOf(event) {
1937
+ const relay = relayOf(event);
1938
+ return relay === null ? null : relayStreamKey(relay.task, relay.stream);
1939
+ }
1940
+ /** The open windows a non-partial event reads and closes: the one under its
1941
+ * own key; else, for an event without a branch, every open window of the
1942
+ * same turn, author and node path. */
1943
+ function windowCandidates(windows, turnId, event) {
1944
+ const own = aggregateWindowKey(turnId, event);
1945
+ if (windows.has(own))
1946
+ return [own];
1947
+ // A relayed artifact with no chunks of its own can repeat the status text
1948
+ // of its own task (a peer that sends its answer as status messages, then
1949
+ // the same text as its final artifact).
1950
+ const relay = relayOf(event);
1951
+ if (relay !== null && relay.stream.startsWith("artifact:")) {
1952
+ const status = aggregateWindowKey(turnId, event, relayStreamKey(relay.task, "status"));
1953
+ if (windows.has(status))
1954
+ return [status];
1955
+ }
1956
+ if (typeof event.branch === "string")
1957
+ return [];
1958
+ const wantStream = relayStreamOf(event);
1959
+ return sourceWindows(windows, turnId, event, true)
1960
+ .filter(([, stream]) => stream === wantStream)
1961
+ .map(([key]) => key);
1962
+ }
1963
+ /** The open windows of the source of an event, as [key, stream] pairs: the
1964
+ * same turn, author and node path, and the same branch unless anyBranch. */
1965
+ function sourceWindows(windows, turnId, event, anyBranch) {
1966
+ const author = event.author;
1967
+ const branch = event.branch;
1968
+ const path = event.nodeInfo?.path;
1969
+ const wantAuthor = typeof author === "string" ? author : null;
1970
+ const wantBranch = typeof branch === "string" ? branch : null;
1971
+ const wantPath = typeof path === "string" ? path : null;
1972
+ const out = [];
1973
+ for (const key of windows.keys()) {
1974
+ const parsed = JSON.parse(key);
1975
+ if (Array.isArray(parsed) &&
1976
+ parsed[0] === turnId &&
1977
+ parsed[1] === wantAuthor &&
1978
+ (anyBranch || parsed[2] === wantBranch) &&
1979
+ parsed[3] === wantPath)
1980
+ out.push([key, parsed[4]]);
1981
+ }
1982
+ return out;
1983
+ }
1984
+ /** The windows a relayed Task or Message restates: its task's open artifact
1985
+ * windows, in the order they opened, and its task's status window. */
1986
+ function snapshotWindows(windows, turnId, event, task) {
1987
+ const own = sourceWindows(windows, turnId, event, false);
1988
+ const artifacts = own.filter(([, stream]) => {
1989
+ if (typeof stream !== "string")
1990
+ return false;
1991
+ const parsed = JSON.parse(stream);
1992
+ return Array.isArray(parsed) && parsed[0] === task && typeof parsed[1] === "string" && parsed[1].startsWith("artifact:");
1993
+ });
1994
+ const status = relayStreamKey(task, "status");
1995
+ return { artifacts: artifacts.map(([key]) => key), status: own.filter(([, stream]) => stream === status).map(([key]) => key) };
1996
+ }
1997
+ /** The streamed text a relayed Task or Message is read against. ADK renders a
1998
+ * Task as its artifacts' parts, then its status message's (taskToAdkEvent), so
1999
+ * the snapshot is matched in that order: against the artifacts and the status
2000
+ * text together (a task still in the state it streamed), else the artifacts
2001
+ * alone (its status message is new, and renders), else the status text alone.
2002
+ * The first reading the snapshot repeats is taken; with none, the first. */
2003
+ function snapshotReading(artifactText, statusText, text) {
2004
+ const readings = [artifactText + statusText, artifactText, statusText].filter((r) => r.length > 0);
2005
+ const repeats = (r) => text.startsWith(r) || r.startsWith(text) || r.endsWith(text);
2006
+ return readings.find(repeats) ?? readings[0] ?? "";
2007
+ }
2008
+ /** The relay windows an event of the relaying agent ends without being
2009
+ * relayed itself: ADK's RemoteA2AAgent reports a failed request with an
2010
+ * event of its own (errorMessage, turnComplete, no relay record), which ends
2011
+ * every relayed stream of that author and node path. */
2012
+ function relayWindowsEndedBy(windows, turnId, event) {
2013
+ if (relayOf(event) !== null)
2014
+ return [];
2015
+ if (event.errorMessage === undefined && event.turnComplete !== true)
2016
+ return [];
2017
+ return sourceWindows(windows, turnId, event, true)
2018
+ .filter(([, stream]) => stream !== null)
2019
+ .map(([key]) => key);
2020
+ }
1513
2021
  export function createAdkNormalizer(options = {}) {
1514
2022
  // The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
1515
2023
  // re-drives to the same ids and no push() reads randomness.
@@ -1527,7 +2035,8 @@ function createInnerAdkNormalizer(options, invokeStem) {
1527
2035
  const hostCompletion = options.hostCompletion === true;
1528
2036
  const a = new StreamAssembler();
1529
2037
  const threadId = options.threadId ?? "google";
1530
- // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
2038
+ // §8.3 per-instance accumulator (replaces the module-level streamedText Map),
2039
+ // keyed by aggregateWindowKey (turn + source):
1531
2040
  const streamedText = new Map();
1532
2041
  // Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
1533
2042
  const streamedTranscription = new Map();
@@ -1547,6 +2056,18 @@ function createInnerAdkNormalizer(options, invokeStem) {
1547
2056
  // double-render quirk applies to usage too), so counting non-partial
1548
2057
  // events counts each round exactly once.
1549
2058
  const usageByTurn = new Map();
2059
+ // The usage reports summed into usageByTurn, in order, so the report that an
2060
+ // in-band error's repeat supersedes can be replaced (spec §8.0 item 35).
2061
+ const usageReportsByTurn = new Map();
2062
+ // Spec §8.0 item 35: per turn, the invocation's first in-band invocation
2063
+ // error (errorCode AND errorMessage). The turn never closes on one, never
2064
+ // closes as success after one, and closes with one turn.error at the
2065
+ // invocation's end.
2066
+ const firstInBandError = new Map();
2067
+ // Per turn and source (author, branch, node path): the previous event, for
2068
+ // item 35's SSE repeat, and the in-band errors seen, for its relay repeat.
2069
+ const previousBySource = new Map();
2070
+ const inBandErrorsBySource = new Map();
1550
2071
  // Per-turn HITL asks emitted by the two `actions.requested*` arms (audit
1551
2072
  // M26) — populated in emission order by `trackPendingAsk` inside
1552
2073
  // `driveAdkTopLevel`. Consulted ONLY by `maybeCloseTurn`'s REAL close path
@@ -1574,6 +2095,16 @@ function createInnerAdkNormalizer(options, invokeStem) {
1574
2095
  // opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
1575
2096
  const generationOf = new Map();
1576
2097
  const interruptClosed = new Set();
2098
+ // Per turn key: whether the previous event carried both turnComplete and
2099
+ // interrupted, the message after which ADK re-yields a bare {interrupted}.
2100
+ const previousBothFlags = new Map();
2101
+ // Turns a final response closed as success before the invocation ended
2102
+ // (without the host-completion event only). ADK keeps running after such a
2103
+ // final (a SequentialAgent's next sub-agent, a LoopAgent's next iteration),
2104
+ // and content that follows opens the next generation of the turn rather
2105
+ // than landing after its terminal (spec §8.0: framework content that
2106
+ // arrives after a terminal opens a new turn).
2107
+ const successClosed = new Set();
1577
2108
  // Turns whose last function response has no model output after it yet. On
1578
2109
  // the Live path the model always answers a tool result with a reply
1579
2110
  // generation, and ADK can yield the call generation's turnComplete between
@@ -1607,12 +2138,6 @@ function createInnerAdkNormalizer(options, invokeStem) {
1607
2138
  function maybeCloseTurn(event, turnId, messageId, isPartial) {
1608
2139
  if (isPartial || closedTurns.has(turnId))
1609
2140
  return;
1610
- // Every non-partial event contributes its per-round usage to the turn's
1611
- // accumulator — including functionCall rounds, which never close the
1612
- // turn themselves (see the usageByTurn doc above).
1613
- const accumulated = accumulateUsage(usageByTurn.get(turnId), event.usageMetadata);
1614
- if (accumulated !== undefined)
1615
- usageByTurn.set(turnId, accumulated);
1616
2141
  const parts = event.content?.parts ?? [];
1617
2142
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
1618
2143
  const interrupted = event.interrupted === true || interruptPending.has(turnId);
@@ -1647,23 +2172,28 @@ function createInnerAdkNormalizer(options, invokeStem) {
1647
2172
  // reply ends the call generation, not the turn (see awaitingReply).
1648
2173
  if (event.finishReason === undefined && event.errorCode === undefined && awaitingReply.has(turnId))
1649
2174
  return;
1650
- // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
1651
- // present ⇒ turn.error (values captured here so the close below needs no
1652
- // re-narrowing).
1653
- const errorClose = event.errorCode !== undefined && event.errorMessage !== undefined
1654
- ? { code: event.errorCode, message: event.errorMessage }
1655
- : undefined;
2175
+ // Spec §8.0 item 35: an in-band invocation error never closes the turn
2176
+ // (recordErrorAndUsage emitted its `error` event), and once the invocation
2177
+ // met one, no final response closes it either: the invocation's end does
2178
+ // (hostComplete, hostError, flush). A final response while an ask is
2179
+ // pending still signals the pause (item 26).
2180
+ if (inBandErrorOf(event) !== undefined)
2181
+ return;
2182
+ if (firstInBandError.has(turnId)) {
2183
+ if ((pendingAsks.get(turnId)?.length ?? 0) > 0)
2184
+ deferredClose.set(turnId, event);
2185
+ return;
2186
+ }
1656
2187
  // ── The nodeInfo gate (R&D item 6, step 1) ──
1657
2188
  // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
1658
2189
  // final text (nodeInfo present) is mid-invocation: closing the invocation
1659
2190
  // turn on it put the workflow's later events after the terminal and parked
1660
2191
  // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1661
2192
  // closes the turn as success. It is a per-EVENT test, never a latch
1662
- // (NodeTool puts nodeInfo into plain runs too). Error closes stay
1663
- // immediate. A completed workflow closes success only on the host-completion
1664
- // event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
1665
- // it flushes turn.abort.
1666
- if (errorClose === undefined && event.nodeInfo !== undefined)
2193
+ // (NodeTool puts nodeInfo into plain runs too). A completed workflow closes
2194
+ // success only on the host-completion event (the `hostCompletion` opt-in,
2195
+ // §8.0 host obligation 4); without it, it flushes turn.abort.
2196
+ if (event.nodeInfo !== undefined)
1667
2197
  return;
1668
2198
  // Host obligation 4 (opt-in): a success close waits for the
1669
2199
  // host-completion event, because the run may not be over (a
@@ -1671,12 +2201,22 @@ function createInnerAdkNormalizer(options, invokeStem) {
1671
2201
  // while an ask is pending waits on every host (item 26: the invocation's
1672
2202
  // end, the host-completion event or flush()), because the model may run
1673
2203
  // again after a pause. The final response is stashed and closed unchanged,
1674
- // so a stream ending here is byte-identical. Error closes stay immediate.
1675
- if (errorClose === undefined && (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0)) {
2204
+ // so a stream ending here is byte-identical.
2205
+ if (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0) {
1676
2206
  deferredClose.set(turnId, event);
1677
2207
  return;
1678
2208
  }
1679
- closeOnFinalResponse(event, turnId, messageId, errorClose);
2209
+ // ── The branch gate ──
2210
+ // A final response that carries a `branch` (a ParallelAgent's sub-agent)
2211
+ // ends that branch, not the invocation: ADK runs the other branches after
2212
+ // it, so closing the turn on it put their events after the terminal and
2213
+ // parked reduce() (INV-TURN). Without the host-completion event such a
2214
+ // turn closes at flush(), as a completed Workflow does.
2215
+ if (typeof event.branch === "string")
2216
+ return;
2217
+ // No ask is pending here, so this close is a success.
2218
+ successClosed.add(turnId);
2219
+ closeOnFinalResponse(event, turnId, messageId);
1680
2220
  }
1681
2221
  /** The paused close at the invocation's end. A final response stashed while
1682
2222
  * the asks were pending closes as it would have on arrival (paused, with its
@@ -1684,7 +2224,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1684
2224
  function closePaused(turnId, messageId, asks) {
1685
2225
  const stashed = deferredClose.get(turnId);
1686
2226
  if (stashed !== undefined) {
1687
- closeOnFinalResponse(stashed, turnId, messageId, undefined);
2227
+ closeOnFinalResponse(stashed, turnId, messageId);
1688
2228
  return;
1689
2229
  }
1690
2230
  closedTurns.add(turnId);
@@ -1697,8 +2237,9 @@ function createInnerAdkNormalizer(options, invokeStem) {
1697
2237
  });
1698
2238
  }
1699
2239
  /** The close on a final response: lossy-finish metadata, message.end, then
1700
- * turn.error or turn.done (paused when asks are pending, else success). */
1701
- function closeOnFinalResponse(event, turnId, messageId, errorClose) {
2240
+ * turn.done (paused when asks are pending, else success). An in-band
2241
+ * invocation error never reaches it (spec §8.0 item 35). */
2242
+ function closeOnFinalResponse(event, turnId, messageId) {
1702
2243
  closedTurns.add(turnId);
1703
2244
  const rawFinish = event.finishReason ?? event.errorCode;
1704
2245
  const finish = resolveFinishReason(rawFinish);
@@ -1711,9 +2252,8 @@ function createInnerAdkNormalizer(options, invokeStem) {
1711
2252
  // `rawErrorCode`, never fabricated as a finishReason. Lossy-only (unlike
1712
2253
  // vercel-ai's unconditional carry) so no recorded cassette — all STOP
1713
2254
  // closes — gains noise. Runs exactly once per turn (real-close path,
1714
- // closedTurns-guarded), never on partials; the error-close path skips it
1715
- // (closeTurnError carries the wire errorCode verbatim in `code`).
1716
- if (errorClose === undefined && rawFinish !== undefined && finish.lossy) {
2255
+ // closedTurns-guarded), never on partials.
2256
+ if (rawFinish !== undefined && finish.lossy) {
1717
2257
  a.emit({
1718
2258
  type: "message.metadata",
1719
2259
  messageId,
@@ -1723,41 +2263,136 @@ function createInnerAdkNormalizer(options, invokeStem) {
1723
2263
  });
1724
2264
  }
1725
2265
  a.closeMessage(messageId);
1726
- // The turn's accrued usage rides its terminal on both closes (SPEC §4:
1727
- // turn.error.usage mirrors turn.done), as the host-error close does.
2266
+ // The turn's accrued usage rides its terminal.
1728
2267
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1729
- if (errorClose !== undefined) {
1730
- a.closeTurnError(turnId, {
1731
- message: errorClose.message,
1732
- code: errorClose.code,
1733
- ...(usage !== undefined ? { usage } : {}),
1734
- });
2268
+ // SPEC §4's safety_blocked conformance note: a safety_blocked close
2269
+ // carries safety[].category so the collapsed reason stays recoverable. A
2270
+ // blocked rating names it; when no rating does (ADK 2.1.0 delivers none on
2271
+ // a real block), the native value finishReason was mapped from is the
2272
+ // category, as a block.
2273
+ const rated = mapBlockedSafety(event.safetyRatings);
2274
+ const safety = rated === undefined && finish.value === "safety_blocked" && rawFinish !== undefined
2275
+ ? [{ category: rawFinish, blocked: true }]
2276
+ : rated;
2277
+ // A turn with pending HITL asks (requestedAuthConfigs /
2278
+ // requestedToolConfirmations / adk_request_input, tracked by
2279
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
2280
+ // unresolved requests the turn is parked on, never a fabricated success
2281
+ // (SPEC §8 items 12 + 18). A paused close carries finishReason "paused"
2282
+ // (the HITL value), the same as the pause-end close above.
2283
+ const asks = pendingAsks.get(turnId);
2284
+ const paused = asks !== undefined && asks.length > 0;
2285
+ a.closeTurnDone(turnId, {
2286
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
2287
+ finishReason: paused ? "paused" : finish.value,
2288
+ // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
2289
+ // native value verbatim in turn.done.finishReasonRaw. That is the value
2290
+ // finishReason was mapped from: the wire finishReason, or for an
2291
+ // errorCode-only soft close the errorCode. A paused close's "paused" is
2292
+ // not a fallback, so it takes no companion. message.metadata's
2293
+ // rawFinishReason/rawErrorCode carry stays for one cohort.
2294
+ ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
2295
+ ...(usage !== undefined ? { usage } : {}),
2296
+ ...(safety !== undefined ? { safety } : {}),
2297
+ });
2298
+ }
2299
+ /** Count one usage report toward the turn's usage; returns its slot. */
2300
+ function countUsage(turnId, usage) {
2301
+ const reports = usageReportsByTurn.get(turnId) ?? [];
2302
+ reports.push(usage);
2303
+ usageReportsByTurn.set(turnId, reports);
2304
+ const accumulated = accumulateUsage(usageByTurn.get(turnId), usage);
2305
+ if (accumulated !== undefined)
2306
+ usageByTurn.set(turnId, accumulated);
2307
+ return reports.length - 1;
2308
+ }
2309
+ /** Replace the report in one slot and re-sum the turn's usage. */
2310
+ function replaceUsage(turnId, slot, usage) {
2311
+ const reports = usageReportsByTurn.get(turnId);
2312
+ if (reports === undefined || slot >= reports.length)
2313
+ return;
2314
+ reports[slot] = usage;
2315
+ let sum;
2316
+ for (const report of reports)
2317
+ sum = accumulateUsage(sum, report);
2318
+ if (sum !== undefined)
2319
+ usageByTurn.set(turnId, sum);
2320
+ }
2321
+ /** Spec §8.0 item 35 when the event arrives, and the event's usage count.
2322
+ * Every non-partial event of an open turn counts its usage report once,
2323
+ * functionCall rounds included (see the usageByTurn doc above). An in-band
2324
+ * invocation error that repeats an earlier one yields no `error` event: the
2325
+ * SSE aggregate that repeats the previous in-band error of its source as the
2326
+ * model call's stream closes (its report replaces the one it repeats, so
2327
+ * the call counts once, from the later report), and the relay's closing
2328
+ * event (it adds no usage). Any other in-band error emits `error` from this
2329
+ * push and, when it is the invocation's first, latches it. */
2330
+ function recordErrorAndUsage(event, turnId, isPartial) {
2331
+ const sourceKey = aggregateWindowKey(turnId, event, null);
2332
+ const previous = previousBySource.get(sourceKey);
2333
+ const error = inBandErrorOf(event);
2334
+ const counting = !isPartial && !closedTurns.has(turnId);
2335
+ let usageSlot;
2336
+ if (error === undefined) {
2337
+ if (counting && event.usageMetadata !== undefined)
2338
+ usageSlot = countUsage(turnId, event.usageMetadata);
1735
2339
  }
1736
2340
  else {
1737
- const safety = mapBlockedSafety(event.safetyRatings);
1738
- // A turn with pending HITL asks (requestedAuthConfigs /
1739
- // requestedToolConfirmations / adk_request_input, tracked by
1740
- // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
1741
- // unresolved requests the turn is parked on, never a fabricated success
1742
- // (audit M26 / SPEC §8 items 12 + 18). A paused close carries
1743
- // finishReason "paused" (the HITL value, R&D item 6 step 1), the same as
1744
- // the pause-end close above.
1745
- const asks = pendingAsks.get(turnId);
1746
- const paused = asks !== undefined && asks.length > 0;
1747
- a.closeTurnDone(turnId, {
1748
- outcome: paused ? { type: "paused", asks } : { type: "success" },
1749
- finishReason: paused ? "paused" : finish.value,
1750
- // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
1751
- // native value verbatim in turn.done.finishReasonRaw. That is the value
1752
- // finishReason was mapped from: the wire finishReason, or for an
1753
- // errorCode-only soft close the errorCode. A paused close's "paused" is
1754
- // not a fallback, so it takes no companion. message.metadata's
1755
- // rawFinishReason/rawErrorCode carry stays for one cohort.
1756
- ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
1757
- ...(usage !== undefined ? { usage } : {}),
1758
- ...(safety !== undefined ? { safety } : {}),
1759
- });
2341
+ const record = inBandErrorRecord(event, error);
2342
+ const earlier = inBandErrorsBySource.get(sourceKey) ?? [];
2343
+ const repeatsPrevious = event.partial === false &&
2344
+ previous !== undefined &&
2345
+ !previous.partialFalse &&
2346
+ previous.error !== undefined &&
2347
+ previous.error.code === error.code &&
2348
+ previous.error.message === error.message;
2349
+ if (repeatsPrevious) {
2350
+ const later = event.usageMetadata ?? previous.usage;
2351
+ if (counting && later !== undefined) {
2352
+ if (previous.usageSlot !== undefined) {
2353
+ replaceUsage(turnId, previous.usageSlot, later);
2354
+ usageSlot = previous.usageSlot;
2355
+ }
2356
+ else {
2357
+ usageSlot = countUsage(turnId, later);
2358
+ }
2359
+ }
2360
+ }
2361
+ else if (!isRelayRepeat(event, record, earlier)) {
2362
+ a.emit({ type: "error", turnId, code: error.code, message: error.message });
2363
+ if (!firstInBandError.has(turnId))
2364
+ firstInBandError.set(turnId, error);
2365
+ if (counting && event.usageMetadata !== undefined)
2366
+ usageSlot = countUsage(turnId, event.usageMetadata);
2367
+ }
2368
+ inBandErrorsBySource.set(sourceKey, [...earlier, record]);
1760
2369
  }
2370
+ previousBySource.set(sourceKey, { partialFalse: event.partial === false, error, usage: event.usageMetadata, usageSlot });
2371
+ }
2372
+ /** Item 26's pause signal: an ask is pending and the stream showed the
2373
+ * pause's end (its pause-end event, or a final response while the ask was
2374
+ * pending). An in-band invocation error is never one. */
2375
+ function pauseSignalled(turnId) {
2376
+ return (pendingAsks.get(turnId)?.length ?? 0) > 0 && (pauseEnded.has(turnId) || deferredClose.has(turnId));
2377
+ }
2378
+ /** Spec §8.0 item 35 at the invocation's end: the one turn.error of a turn
2379
+ * whose invocation met an invocation error, with the given code and message
2380
+ * and the turn's accumulated usage. */
2381
+ function closeInvocationError(turnId, error, usage) {
2382
+ closedTurns.add(turnId);
2383
+ a.closeMessage(`msg_${turnId}`);
2384
+ a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
2385
+ }
2386
+ /** Spec §8.0 item 26 with an invocation error: after the paused close, the
2387
+ * error closes on a new top-level turn of the invocation, which carries one
2388
+ * assistant message with no content; its turn.error carries only usage a
2389
+ * host-terminal event reports. */
2390
+ function closeErrorTurn(pausedTurnId, error, usage) {
2391
+ const turnId = `${pausedTurnId}_error`;
2392
+ const messageId = ensureOpen(turnId);
2393
+ closedTurns.add(turnId);
2394
+ a.closeMessage(messageId);
2395
+ a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
1761
2396
  }
1762
2397
  /** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
1763
2398
  * pending until its functionResponse arrives. */
@@ -1781,7 +2416,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1781
2416
  * close with the accumulated usage when the run ended on a non-final event,
1782
2417
  * e.g. a completed Workflow). */
1783
2418
  function hostComplete() {
1784
- for (const turnId of openTurns) {
2419
+ for (const turnId of [...openTurns]) {
1785
2420
  if (closedTurns.has(turnId))
1786
2421
  continue;
1787
2422
  if (interruptPending.has(turnId)) {
@@ -1790,6 +2425,20 @@ function createInnerAdkNormalizer(options, invokeStem) {
1790
2425
  }
1791
2426
  const messageId = `msg_${turnId}`;
1792
2427
  const asks = pendingAsks.get(turnId);
2428
+ // Spec §8.0 items 26 and 35: an invocation that met an in-band error
2429
+ // never closes as success. A signalled pause closes paused, and the
2430
+ // error follows on its own turn; otherwise the turn closes turn.error.
2431
+ const error = firstInBandError.get(turnId);
2432
+ if (error !== undefined) {
2433
+ if (asks !== undefined && pauseSignalled(turnId)) {
2434
+ closePaused(turnId, messageId, asks);
2435
+ closeErrorTurn(turnId, error, undefined);
2436
+ }
2437
+ else {
2438
+ closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
2439
+ }
2440
+ continue;
2441
+ }
1793
2442
  if (asks !== undefined && asks.length > 0) {
1794
2443
  closePaused(turnId, messageId, asks);
1795
2444
  continue;
@@ -1798,7 +2447,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1798
2447
  continue;
1799
2448
  const stashed = deferredClose.get(turnId);
1800
2449
  if (stashed !== undefined) {
1801
- closeOnFinalResponse(stashed, turnId, messageId, undefined);
2450
+ closeOnFinalResponse(stashed, turnId, messageId);
1802
2451
  continue;
1803
2452
  }
1804
2453
  closedTurns.add(turnId);
@@ -1823,8 +2472,21 @@ function createInnerAdkNormalizer(options, invokeStem) {
1823
2472
  for (const turnId of [...openTurns].reverse()) {
1824
2473
  if (closedTurns.has(turnId))
1825
2474
  continue;
2475
+ // A signalled pause on a turn with no interruption closes paused first,
2476
+ // then the error closes on a new top-level turn (spec §8.0 host
2477
+ // obligation 1 and item 26).
2478
+ const asks = pendingAsks.get(turnId);
2479
+ if (asks !== undefined && pauseSignalled(turnId) && !interruptPending.has(turnId)) {
2480
+ closePaused(turnId, `msg_${turnId}`, asks);
2481
+ closeErrorTurn(turnId, { code: err.code, message: err.message }, err.usage);
2482
+ closed++;
2483
+ continue;
2484
+ }
1826
2485
  closedTurns.add(turnId);
1827
- const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
2486
+ // The turn closes with the host's code and message and its accumulated
2487
+ // usage plus any usage the host reports, which covers only work the
2488
+ // stream did not report (spec §8.0 host obligation 1 and item 35).
2489
+ const usage = sumUsage(mapUsage(usageByTurn.get(turnId)), err.usage);
1828
2490
  a.closeMessage(`msg_${turnId}`);
1829
2491
  a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
1830
2492
  closed++;
@@ -1841,12 +2503,86 @@ function createInnerAdkNormalizer(options, invokeStem) {
1841
2503
  ...(err.usage !== undefined ? { usage: err.usage } : {}),
1842
2504
  });
1843
2505
  }
2506
+ /** The part indexes whose text repeats a changed output rendering (see
2507
+ * drive()): skipped here and in the aggregate. */
2508
+ function skippedParts(event, parts) {
2509
+ const renderedOutput = changedOutputRendering(event.output);
2510
+ const skipped = new Set();
2511
+ if (renderedOutput !== undefined)
2512
+ parts.forEach((p, idx) => {
2513
+ if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput)
2514
+ skipped.add(idx);
2515
+ });
2516
+ return skipped;
2517
+ }
2518
+ /** An event's reading against the aggregate windows of a turn (the rules
2519
+ * are stated in drive()). */
2520
+ function readWindow(turnId, event, parts, skipped, isPartial) {
2521
+ const isTextPart = (p, idx) => !skipped.has(idx) &&
2522
+ p.thought !== true &&
2523
+ p.functionCall === undefined &&
2524
+ typeof p.text === "string" &&
2525
+ p.text.length > 0;
2526
+ const carriesText = parts.some(isTextPart);
2527
+ const ownKey = aggregateWindowKey(turnId, event);
2528
+ const relay = relayOf(event);
2529
+ const snapshot = !isPartial && relay !== null && relay.stream === "snapshot" ? relay : null;
2530
+ const restated = snapshot !== null ? snapshotWindows(streamedText, turnId, event, snapshot.task) : null;
2531
+ const candidates = isPartial
2532
+ ? []
2533
+ : restated !== null
2534
+ ? [...restated.artifacts, ...restated.status]
2535
+ : windowCandidates(streamedText, turnId, event);
2536
+ const [onlyCandidate] = candidates;
2537
+ const readKey = !isPartial && candidates.length === 1 && onlyCandidate !== undefined ? onlyCandidate : ownKey;
2538
+ const alreadyStreamed = isPartial
2539
+ ? (streamedText.get(ownKey) ?? "")
2540
+ : restated !== null
2541
+ ? snapshotReading(restated.artifacts.map((key) => streamedText.get(key) ?? "").join(""), restated.status.map((key) => streamedText.get(key) ?? "").join(""), parts
2542
+ .filter(isTextPart)
2543
+ .map((p) => p.text ?? "")
2544
+ .join(""))
2545
+ : candidates.length === 1
2546
+ ? (streamedText.get(readKey) ?? "")
2547
+ : "";
2548
+ const matchesWindow = !isPartial && alreadyStreamed.length > 0 && carriesText;
2549
+ const eventText = matchesWindow
2550
+ ? parts
2551
+ .filter(isTextPart)
2552
+ .map((p) => p.text ?? "")
2553
+ .join("")
2554
+ : "";
2555
+ const suffixRepeat = matchesWindow && alreadyStreamed.endsWith(eventText);
2556
+ const isAggregate = matchesWindow &&
2557
+ (eventText.startsWith(alreadyStreamed) || alreadyStreamed.startsWith(eventText) || suffixRepeat);
2558
+ const aggregateText = isAggregate ? eventText : "";
2559
+ const suppressAggregateText = isAggregate && aggregateText.length > 0 && (alreadyStreamed.startsWith(aggregateText) || suffixRepeat);
2560
+ return { isTextPart, carriesText, ownKey, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText };
2561
+ }
2562
+ /** Whether an event after a success close only repeats the closed turn's
2563
+ * streamed text: ADK's aggregate after a message-less block chunk closed
2564
+ * the turn. It stays on that turn, where the window suppresses it, rather
2565
+ * than opening a new one. */
2566
+ function repeatsClosedTurn(turnId, event) {
2567
+ if (event.partial === true)
2568
+ return false;
2569
+ const { parts } = splitPayloadParts(event.content?.parts ?? []);
2570
+ if (parts.length === 0)
2571
+ return false;
2572
+ const skipped = skippedParts(event, parts);
2573
+ const reading = readWindow(turnId, event, parts, skipped, false);
2574
+ return (reading.suppressAggregateText &&
2575
+ parts.every((p, idx) => skipped.has(idx) || reading.isTextPart(p, idx) || (p.thought !== true && p.text === "")));
2576
+ }
1844
2577
  function drive(event, relayEchoOmitted = 0) {
1845
- const turnId = liveTurnFor(event);
2578
+ const turnId = liveTurnFor(event, relayEchoOmitted > 0);
1846
2579
  // ADK re-yields a bare `{interrupted}` after a message that carried both
1847
2580
  // turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
1848
2581
  // 2.1.0). For a generation the barge-in already closed, it adds nothing:
1849
2582
  // no new turn and no second terminal, so the facet emits nothing for it.
2583
+ // An event push() removed parts from is not that re-yield even when
2584
+ // nothing is left of it: its marker needs a turn, so it opens the next
2585
+ // generation as an event with content would.
1850
2586
  if (turnId === undefined)
1851
2587
  return;
1852
2588
  const messageId = ensureOpen(turnId);
@@ -1855,7 +2591,11 @@ function createInnerAdkNormalizer(options, invokeStem) {
1855
2591
  // into.
1856
2592
  if (relayEchoOmitted > 0)
1857
2593
  a.emitExt("google", "relay-echo-omitted", { parts: relayEchoOmitted });
1858
- const parts = event.content?.parts ?? [];
2594
+ // A part holding text beside a payload member, or two payload members, is
2595
+ // split before any reader below classifies it (see splitPayloadParts), so
2596
+ // its text joins the aggregate as text does and each payload member maps
2597
+ // through its own arm.
2598
+ const { parts, origin: nativeIndexOf } = splitPayloadParts(event.content?.parts ?? []);
1859
2599
  const isPartial = event.partial === true;
1860
2600
  // ADK renders an object `output` as the same event's text part, byte-equal
1861
2601
  // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
@@ -1863,13 +2603,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1863
2603
  // repeat what the reduction removed, so that one part is skipped here and
1864
2604
  // in the aggregate below. Nothing else matches: not a string output, not
1865
2605
  // a substring, not model text.
1866
- const renderedOutput = changedOutputRendering(event.output);
1867
- const skipped = new Set();
1868
- if (renderedOutput !== undefined)
1869
- parts.forEach((p, idx) => {
1870
- if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput)
1871
- skipped.add(idx);
1872
- });
2606
+ const skipped = skippedParts(event, parts);
1873
2607
  // STREAMED-text citations carrier (audit M22): groundingMetadata is
1874
2608
  // EVENT-level, not per-part. A Gemini grounding response carries the full
1875
2609
  // grounded answer in a single (non-thought, non-function-call) text part, so
@@ -1899,16 +2633,43 @@ function createInnerAdkNormalizer(options, invokeStem) {
1899
2633
  return; // real id — resolved directly, not via this map
1900
2634
  nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
1901
2635
  });
1902
- // §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
1903
- const alreadyStreamed = streamedText.get(turnId) ?? "";
1904
- const isAggregate = !isPartial && alreadyStreamed.length > 0;
1905
- const aggregateText = isAggregate
1906
- ? parts
1907
- .filter((p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1908
- .map((p) => p.text ?? "")
1909
- .join("")
1910
- : "";
1911
- const suppressAggregateText = isAggregate && aggregateText.length > 0 && alreadyStreamed.startsWith(aggregateText);
2636
+ // §8.3 — the aggregate suppression (§8.0 item 3). ADK re-yields a model
2637
+ // call's streamed text as one `partial: false` event: when the call closes,
2638
+ // in SSE before a non-text part in the same stream, and on the Live path
2639
+ // before a tool call, on a switch between thought and text, and on a
2640
+ // barge-in. The window holding the
2641
+ // text streamed so far is keyed per turn AND per source (author, branch,
2642
+ // node path, and for an event ADK's A2A relay forwards, the relayed stream:
2643
+ // one artifact, or the status messages; an absent value is its own key), so
2644
+ // interleaved streams never share one. Every non-partial event of the
2645
+ // source closes it, except the ones ADK yields between a call's chunks and
2646
+ // its re-yield, none of which carries text: a block chunk (no content, a
2647
+ // finishReason), a Live usage report or grounding record (no content and
2648
+ // nothing else a closing record carries: no errorCode, errorMessage,
2649
+ // finishReason, turnComplete, session-resumption update, goAway or state or
2650
+ // artifact delta, and for the usage report no interruption), a
2651
+ // transcription event, a `partial: false` event whose
2652
+ // parts are all non-text (a function call or media before the Interactions
2653
+ // route's re-yield), and a function response (progressive SSE runs a tool
2654
+ // mid-stream). A text event that closes the window is its re-yield when
2655
+ // one text starts with the other (equal; longer by text no chunk streamed,
2656
+ // whose tail renders; or shorter, a callback's replacement whose bytes
2657
+ // already streamed) or when the streamed text ends with its text (a later
2658
+ // call's re-yield after a call whose close never arrived, or ADK's
2659
+ // structured-output rewrite); any other text renders in full. An event
2660
+ // without a branch that finds no window under its own key (ADK's A2A relay
2661
+ // rebuilds its re-yield without one, and a failed call's in-band error
2662
+ // carries none) reads the open windows of the same turn, author and node
2663
+ // path: a re-yield matches only when exactly one is open, and a text-less
2664
+ // event that ends the match ends them all (a text with two or more
2665
+ // candidates closes none). A relayed stream is scoped by its A2A task. A
2666
+ // relayed artifact with no window of its own reads its task's status
2667
+ // window; a relayed Task or Message restates its task, so it is read, in
2668
+ // the order ADK renders a Task, against that task's artifact windows and
2669
+ // then its status window (snapshotReading), and closes them; and
2670
+ // the relaying agent's own failure event ends every relayed window of its
2671
+ // author and node path. An empty text part is not text.
2672
+ const { isTextPart, carriesText, ownKey, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText, } = readWindow(turnId, event, parts, skipped, isPartial);
1912
2673
  let residualTail = isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
1913
2674
  let accumulated = alreadyStreamed;
1914
2675
  parts.forEach((part, index) => {
@@ -1939,14 +2700,39 @@ function createInnerAdkNormalizer(options, invokeStem) {
1939
2700
  accumulated += part.text ?? "";
1940
2701
  return;
1941
2702
  }
1942
- const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, blockIds, index === citedPartIndex ? citations : undefined);
2703
+ const contributed = driveAdkPart(a, part, index, nativeIndexOf[index] ?? index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, blockIds, index === citedPartIndex ? citations : undefined);
1943
2704
  if (isPartial)
1944
2705
  accumulated += contributed;
1945
2706
  });
2707
+ const stateDelta = event.actions?.stateDelta;
2708
+ const artifactDelta = event.actions?.artifactDelta;
2709
+ // Two records ADK's Live aggregator yields on their own between a call's
2710
+ // chunks and its repeat: its usage report, and the grounding metadata of
2711
+ // a message with no parts (a barge-in's among them). One that also carries
2712
+ // anything that ends a call is neither, and closes the window.
2713
+ const endsNoCall = event.errorCode === undefined &&
2714
+ event.errorMessage === undefined &&
2715
+ event.turnComplete !== true &&
2716
+ !Object.hasOwn(event, "liveSessionResumptionUpdate") &&
2717
+ !Object.hasOwn(event, "goAway") &&
2718
+ !(isJsonObject(stateDelta) && Object.keys(stateDelta).length > 0) &&
2719
+ !(isJsonObject(artifactDelta) && Object.keys(artifactDelta).length > 0);
2720
+ const usageReportOnly = endsNoCall && event.interrupted !== true && event.usageMetadata?.responseTokenCount !== undefined;
2721
+ const groundingOnly = endsNoCall && event.groundingMetadata !== undefined;
2722
+ const keepsWindowOpen = !carriesText &&
2723
+ ((event.partial === undefined && parts.length === 0 && (event.finishReason !== undefined || usageReportOnly || groundingOnly)) ||
2724
+ event.inputTranscription !== undefined ||
2725
+ event.outputTranscription !== undefined ||
2726
+ (event.partial === false && parts.length > 0) ||
2727
+ (parts.length > 0 && parts.every((p) => p.functionResponse !== undefined)));
1946
2728
  if (isPartial)
1947
- streamedText.set(turnId, accumulated);
1948
- else if (isAggregate)
1949
- streamedText.delete(turnId);
2729
+ streamedText.set(ownKey, accumulated);
2730
+ else if (carriesText)
2731
+ for (const key of snapshot !== null ? candidates : [readKey])
2732
+ streamedText.delete(key);
2733
+ else if (!keepsWindowOpen)
2734
+ for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event)])
2735
+ streamedText.delete(key);
1950
2736
  // Round-3 review finding (regression on finding b): the resend window's
1951
2737
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
1952
2738
  // (see the `ToolCallMintState` doc above) already clears each null-id
@@ -1962,7 +2748,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1962
2748
  // per-invoke.
1963
2749
  if (!isPartial)
1964
2750
  trackLongRunning(event, turnId);
1965
- driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
2751
+ driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, closedTurns.has(turnId)); // standalone and content arms
1966
2752
  // A turn gets ONE terminal: an interrupt on a turn that already closed
1967
2753
  // (a second barge-in, or one after a success close) adds none.
1968
2754
  if (event.interrupted === true && !closedTurns.has(turnId))
@@ -1972,6 +2758,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1972
2758
  awaitingReply.add(turnId);
1973
2759
  else if (hasModelOutput(event))
1974
2760
  awaitingReply.delete(turnId);
2761
+ recordErrorAndUsage(event, turnId, isPartial);
1975
2762
  maybeCloseTurn(event, turnId, messageId, isPartial);
1976
2763
  // The interrupted generation closes on its own turnComplete (its trailing
1977
2764
  // usageMetadata arrives before it), or at flush() / host completion.
@@ -2002,16 +2789,33 @@ function createInnerAdkNormalizer(options, invokeStem) {
2002
2789
  }
2003
2790
  /** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
2004
2791
  * key), with `_g<n>` for the n-th generation after a barge-in closed the
2005
- * previous one. `undefined` for ADK's bare `{interrupted}` re-yield on a
2006
- * generation a barge-in already closed. */
2007
- function liveTurnFor(event) {
2792
+ * previous one. `undefined` for ADK's bare `{interrupted}` re-yield: the one
2793
+ * that directly follows a message carrying both turnComplete and
2794
+ * interrupted (utils/live_connection_utils.js yields that message's final
2795
+ * response, then the bare flag). Any other bare `{interrupted}` after a
2796
+ * barge-in closed the generation interrupts the next one. */
2797
+ function liveTurnFor(event, omittedParts = false) {
2008
2798
  const key = turnKey(event);
2009
2799
  const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
2800
+ const reyield = previousBothFlags.get(base) === true;
2801
+ previousBothFlags.set(base, event.turnComplete === true && event.interrupted === true);
2010
2802
  const g = generationOf.get(base) ?? 0;
2011
2803
  const current = g === 0 ? base : `${base}_g${g}`;
2012
- if (!interruptClosed.has(current))
2804
+ // Any event after a success close opens the next generation, so no
2805
+ // message or block event names the closed turn (SPEC :959): content, a
2806
+ // usage report, a carry, an interruption. An `{interrupted}` after a
2807
+ // success close interrupts the next generation, which then closes
2808
+ // turn.abort interrupted; ADK's bare re-yield after a message carrying
2809
+ // both flags follows an interrupt close, handled below. Two stay: an event
2810
+ // whose only mapping is the state.delta of its stateDelta (shared state,
2811
+ // not the turn's content), and an aggregate that only repeats the closed
2812
+ // turn's streamed text (the window suppresses it).
2813
+ const afterSuccess = successClosed.has(current) &&
2814
+ !onlyStateChange(event) &&
2815
+ !repeatsClosedTurn(current, event);
2816
+ if (!interruptClosed.has(current) && !afterSuccess)
2013
2817
  return current;
2014
- if (event.interrupted === true && !hasLiveContent(event))
2818
+ if (!afterSuccess && reyield && event.interrupted === true && !hasLiveContent(event) && !omittedParts)
2015
2819
  return undefined;
2016
2820
  generationOf.set(base, g + 1);
2017
2821
  return `${base}_g${g + 1}`;
@@ -2086,7 +2890,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
2086
2890
  // Workflow invoke until the host completion signal exists, still reports
2087
2891
  // the tokens it spent. There is never a turn.done here, so the usage
2088
2892
  // appears only once.
2089
- for (const turnId of openTurns) {
2893
+ for (const turnId of [...openTurns]) {
2090
2894
  if (closedTurns.has(turnId))
2091
2895
  continue;
2092
2896
  if (interruptPending.has(turnId)) {
@@ -2095,11 +2899,21 @@ function createInnerAdkNormalizer(options, invokeStem) {
2095
2899
  }
2096
2900
  // A pause the stream saw end (its pause-end event, or a final response
2097
2901
  // while an ask was pending) is a resolved pause, not a truncation: it
2098
- // closes paused here (SPEC §8.0 item 26). Asks with neither stay a
2099
- // truncation, as above.
2902
+ // closes paused here (SPEC §8.0 item 26), and an in-band error of its
2903
+ // invocation then closes on its own turn. Asks with neither stay a
2904
+ // truncation, as above, unless the invocation met an in-band error:
2905
+ // that turn, like any other of such an invocation, closes turn.error
2906
+ // (spec §8.0 item 35, INV-FLUSH (2)).
2100
2907
  const asks = pendingAsks.get(turnId);
2101
- if (asks !== undefined && asks.length > 0 && (pauseEnded.has(turnId) || deferredClose.has(turnId))) {
2908
+ const error = firstInBandError.get(turnId);
2909
+ if (asks !== undefined && pauseSignalled(turnId)) {
2102
2910
  closePaused(turnId, `msg_${turnId}`, asks);
2911
+ if (error !== undefined)
2912
+ closeErrorTurn(turnId, error, undefined);
2913
+ continue;
2914
+ }
2915
+ if (error !== undefined) {
2916
+ closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
2103
2917
  continue;
2104
2918
  }
2105
2919
  closedTurns.add(turnId);