@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/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 };
@@ -145,31 +147,45 @@ export function isLossyFinishReason(reason) {
145
147
  return resolveFinishReason(reason).lossy;
146
148
  }
147
149
  // ─── stateful factory helpers ─────────────────────────────────────────────────
148
- // ─── the A2A relay's bookkeeping entries in customMetadata ───────────────────
149
- // ADK's RemoteA2AAgent writes up to four bookkeeping entries into the
150
- // customMetadata of the events it relays: its send request, the peer's raw A2A
151
- // event and their task and context ids. They are the relay's own bookkeeping,
152
- // not event data, and the facet does not carry them, wherever customMetadata
153
- // is carried (the provider-raw carry and the ext.google.unparsed native, where
154
- // an event serialized from Python spells it custom_metadata). Every other
155
- // entry, including one a remote agent wrote, rides unchanged.
150
+ // ─── customMetadata entries the facet does not carry ─────────────────────────
151
+ // Two kinds of customMetadata entry are not event data, and the facet does not
152
+ // carry them, wherever customMetadata is carried (the provider-raw carry and
153
+ // the ext.google.unparsed native, where an event serialized from Python spells
154
+ // it custom_metadata):
155
+ // - ADK's RemoteA2AAgent writes up to four bookkeeping entries into the
156
+ // customMetadata of the events it relays: its send request, the peer's raw
157
+ // A2A event and their task and context ids.
158
+ // - ADK reserves the entries whose name begins with `__adk_internal_` for its
159
+ // own components (events/internal_metadata.js, @google/adk 2.2.1): callers
160
+ // cannot set them, and ADK removes them from the API responses, saved
161
+ // session files and A2A messages it produces. At that version they hold a
162
+ // tool-call integrity stamp and a restored-history marker (SPEC §8.0 item
163
+ // 38).
164
+ // Only top-level entries are matched. Every other entry, including one a
165
+ // remote agent wrote and a value nested below a carried entry, rides
166
+ // unchanged.
156
167
  const RELAY_BOOKKEEPING_KEYS = new Set(["a2a:request", "a2a:response", "a2a:task_id", "a2a:context_id"]);
157
- /** A customMetadata value without the relay's bookkeeping entries, as a new
158
- * value; the argument is not changed. A value holding none of them, or one
159
- * that is not an object, is returned as it is; undefined when the entries
160
- * were all it held. */
161
- function withoutRelayBookkeeping(value) {
162
- if (!isJsonObject(value) || !Object.keys(value).some((k) => RELAY_BOOKKEEPING_KEYS.has(k)))
168
+ const ADK_INTERNAL_METADATA_PREFIX = "__adk_internal_";
169
+ /** Whether a top-level customMetadata entry is one the facet does not carry. */
170
+ function isUncarriedMetadataKey(key) {
171
+ return RELAY_BOOKKEEPING_KEYS.has(key) || key.startsWith(ADK_INTERNAL_METADATA_PREFIX);
172
+ }
173
+ /** A customMetadata value without the entries the facet does not carry, as a
174
+ * new value; the argument is not changed. A value holding none of them, or
175
+ * one that is not an object, is returned as it is; undefined when those
176
+ * entries were all it held. */
177
+ function carriedMetadata(value) {
178
+ if (!isJsonObject(value) || !Object.keys(value).some(isUncarriedMetadataKey))
163
179
  return value;
164
- const kept = Object.entries(value).filter(([k]) => !RELAY_BOOKKEEPING_KEYS.has(k));
180
+ const kept = Object.entries(value).filter(([k]) => !isUncarriedMetadataKey(k));
165
181
  return kept.length > 0 ? Object.fromEntries(kept) : undefined;
166
182
  }
167
183
  /** A native with its customMetadata, or the custom_metadata of an event
168
- * serialized from Python, reduced as by withoutRelayBookkeeping and dropped
169
- * when nothing is left, as a new value; every other member is unchanged, and
170
- * the argument is not changed. The new value's members are defined, never
184
+ * serialized from Python, reduced as by carriedMetadata and dropped when
185
+ * nothing is left, as a new value; every other member is unchanged, and the
186
+ * argument is not changed. The new value's members are defined, never
171
187
  * assigned, and one named __proto__ is not copied (SPEC §13.7). */
172
- function nativeWithoutRelayBookkeeping(native) {
188
+ function nativeWithCarriedMetadata(native) {
173
189
  if (!isJsonObject(native))
174
190
  return native;
175
191
  let changed = false;
@@ -181,7 +197,7 @@ function nativeWithoutRelayBookkeeping(native) {
181
197
  out.push([key, value]);
182
198
  continue;
183
199
  }
184
- const kept = withoutRelayBookkeeping(value);
200
+ const kept = carriedMetadata(value);
185
201
  if (kept !== value)
186
202
  changed = true;
187
203
  if (kept !== undefined)
@@ -365,6 +381,56 @@ const USAGE_SUM_FIELDS = [
365
381
  "toolUsePromptTokenCount",
366
382
  "responseTokenCount",
367
383
  ];
384
+ /** The per-kind count members of AgUsage, which sumUsage sums with an absent
385
+ * count read as 0. */
386
+ const USAGE_COUNTS = [
387
+ "inputTokens",
388
+ "outputTokens",
389
+ "cacheReadTokens",
390
+ "cacheWriteTokens",
391
+ "reasoningTokens",
392
+ "toolUseInputTokens",
393
+ "serverToolRequests",
394
+ ];
395
+ /** The aggregate members of AgUsage, which sumUsage sums only when both
396
+ * records carry them: a total or a cost one record lacks would understate
397
+ * the sum (spec §4: totals are copied, never computed). */
398
+ const USAGE_AGGREGATES = ["totalTokens", "totalTokensRaw", "costUsd"];
399
+ /** The field-wise sum of two usage records: each per-kind count present in
400
+ * either is summed (an absent count is 0), each aggregate only when both
401
+ * carry it (otherwise it is omitted), per model too; every other member is
402
+ * the first record's, else the second's. Either absent returns the other. */
403
+ function sumUsage(a, b) {
404
+ if (a === undefined)
405
+ return b;
406
+ if (b === undefined)
407
+ return a;
408
+ const out = { ...b, ...a };
409
+ for (const key of USAGE_COUNTS) {
410
+ const x = a[key];
411
+ const y = b[key];
412
+ if (x !== undefined || y !== undefined)
413
+ out[key] = (x ?? 0) + (y ?? 0);
414
+ }
415
+ for (const key of USAGE_AGGREGATES) {
416
+ const x = a[key];
417
+ const y = b[key];
418
+ if (x !== undefined && y !== undefined)
419
+ out[key] = x + y;
420
+ else
421
+ delete out[key];
422
+ }
423
+ if (a.byModel !== undefined || b.byModel !== undefined) {
424
+ const byModel = {};
425
+ for (const model of new Set([...Object.keys(a.byModel ?? {}), ...Object.keys(b.byModel ?? {})])) {
426
+ const sum = sumUsage(a.byModel?.[model], b.byModel?.[model]);
427
+ if (sum !== undefined)
428
+ byModel[model] = sum;
429
+ }
430
+ out.byModel = byModel;
431
+ }
432
+ return out;
433
+ }
368
434
  /** Fold one event's usageMetadata into a turn's running accumulator
369
435
  * (field-wise sum; absent fields stay absent so mapUsage's presence checks
370
436
  * keep working). Returns the accumulator (creating it on first use). */
@@ -393,6 +459,49 @@ function mapBlockedSafety(ratings) {
393
459
  }));
394
460
  return out.length > 0 ? out : undefined;
395
461
  }
462
+ // ─── ADK's prompt-block event (errorCode) → prompt.blocked (spec §4) ─────────
463
+ /**
464
+ * The errorCode values that mark an ADK event as a blocked prompt: genai
465
+ * 2.24.0's `BlockedReason` values and the Gemini API's spelling of the
466
+ * unspecified one. In StreamingMode NONE, @google/adk 2.1.0's
467
+ * `createLlmResponse` (models/llm_response.js) turns a blocked prompt into an
468
+ * event whose errorCode is the block reason, with no finishReason, no content
469
+ * and no safety ratings. Exported so the e2e suite's genai pin test
470
+ * (e2e/src/adk-prompt-block-reasons.pin.test.ts) can hold it against genai's
471
+ * own `BlockedReason`. It restates the peer's native values, so it changes
472
+ * when they do.
473
+ *
474
+ * @beta
475
+ */
476
+ export const ADK_PROMPT_BLOCK_REASONS = [
477
+ "BLOCKED_REASON_UNSPECIFIED",
478
+ "SAFETY",
479
+ "OTHER",
480
+ "BLOCKLIST",
481
+ "PROHIBITED_CONTENT",
482
+ "IMAGE_SAFETY",
483
+ "MODEL_ARMOR",
484
+ "JAILBREAK",
485
+ "BLOCK_REASON_UNSPECIFIED",
486
+ ];
487
+ const PROMPT_BLOCK_REASONS = new Set(ADK_PROMPT_BLOCK_REASONS);
488
+ /** The block reason when an event is an ADK prompt block (a treated errorCode,
489
+ * no finishReason, which a response-level block keeps beside errorCode, no
490
+ * content parts, and not relayed), else undefined. ADK's A2A relay marks each
491
+ * event it forwards with an a2a:response entry in customMetadata and drops the
492
+ * finishReason, so a relayed prompt block and a relayed response-level block
493
+ * with the same code arrive alike: no relayed event is read as a prompt block. */
494
+ function adkPromptBlockReason(event) {
495
+ const code = event.errorCode;
496
+ const relayed = isJsonObject(event.customMetadata) && Object.hasOwn(event.customMetadata, "a2a:response");
497
+ return typeof code === "string" &&
498
+ PROMPT_BLOCK_REASONS.has(code) &&
499
+ event.finishReason === undefined &&
500
+ (event.content?.parts ?? []).length === 0 &&
501
+ !relayed
502
+ ? code
503
+ : undefined;
504
+ }
396
505
  // ─── promptFeedback.blockReason → prompt.blocked reason (spec §4) ────────────
397
506
  // Maps Gemini blockReason to the AgJSON prompt.blocked reason enum.
398
507
  function mapBlockReason(reason) {
@@ -572,6 +681,36 @@ function isAdkPauseEnd(event) {
572
681
  function hasLiveContent(ev) {
573
682
  return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
574
683
  }
684
+ // Members of an ADK event that the facet maps to nothing, with the values
685
+ // ADK gives them by default; a member's other value, or any other member,
686
+ // maps to something. The `actions` members are listed below.
687
+ const NO_EMIT_EVENT_MEMBERS = new Set(["invocationId", "author", "id", "timestamp"]);
688
+ const NO_EMIT_ACTION_MEMBERS = new Set(["artifactDelta", "requestedAuthConfigs", "requestedToolConfirmations"]);
689
+ function isEmptyObject(v) {
690
+ return isJsonObject(v) && Object.keys(v).length === 0;
691
+ }
692
+ /** Whether all an event maps to is the state.delta of its stateDelta (or
693
+ * nothing): every member is one the facet maps to nothing, holding ADK's
694
+ * default value, but for `actions.stateDelta`. */
695
+ function onlyStateChange(ev) {
696
+ for (const [key, value] of Object.entries(ev)) {
697
+ if (value === undefined || NO_EMIT_EVENT_MEMBERS.has(key))
698
+ continue;
699
+ if (key === "longRunningToolIds" && Array.isArray(value) && value.length === 0)
700
+ continue;
701
+ if (key !== "actions" || !isJsonObject(value))
702
+ return false;
703
+ for (const [action, member] of Object.entries(value)) {
704
+ if (member === undefined || action === "stateDelta")
705
+ continue;
706
+ if (action === "escalate" && member === false)
707
+ continue;
708
+ if (!NO_EMIT_ACTION_MEMBERS.has(action) || !isEmptyObject(member))
709
+ return false;
710
+ }
711
+ }
712
+ return true;
713
+ }
575
714
  /** Whether an event carries model output: a part of `model`-role content, or
576
715
  * output-transcription text. ADK's function response is `user`-role. */
577
716
  function hasModelOutput(ev) {
@@ -777,17 +916,101 @@ function functionResponseToToolDoneFields(name, response) {
777
916
  function mapGroundingCitations(gm) {
778
917
  if (gm?.groundingSupports === undefined || gm.groundingSupports.length === 0)
779
918
  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
- }));
919
+ return gm.groundingSupports.map((support) => {
920
+ // genai types these members (numbers, a string, number lists). A value of
921
+ // another type has no AgCitation home: the citation takes the member's
922
+ // default (0, "", []) or, for the optional scores, omits it, and the
923
+ // event-level carry holds the native value verbatim
924
+ // (groundingSupportsCarry). Nothing is filtered: ADK pairs each score with
925
+ // the chunk index at the same position.
926
+ const read = readSupport(support);
927
+ return {
928
+ kind: "offset",
929
+ unit: "byte",
930
+ startIndex: read.startIndex ?? 0,
931
+ endIndex: read.endIndex ?? 0,
932
+ bounds: "[start,end)",
933
+ sourceIds: (read.chunkIndices ?? []).map((i) => `grounding_${i}`),
934
+ ...(read.scores !== undefined ? { confidenceScores: read.scores } : {}),
935
+ citedText: read.text ?? "",
936
+ indexFrame: "response",
937
+ };
938
+ });
939
+ }
940
+ /** One grounding support's members as AgCitation takes them. An absent or
941
+ * JSON-null member reads as its default; a member of another type reads as undefined, and its
942
+ * native value is named in `unmapped`. */
943
+ function readSupport(support) {
944
+ const unmapped = {};
945
+ const member = (key) => (isJsonObject(support) ? support[key] : undefined);
946
+ const segment = member("segment");
947
+ const seg = (key) => (isJsonObject(segment) ? segment[key] : undefined);
948
+ const startRaw = seg("startIndex");
949
+ const endRaw = seg("endIndex");
950
+ const textRaw = seg("text");
951
+ const startIndex = startRaw === undefined || startRaw === null ? 0 : finiteNumber(startRaw);
952
+ const endIndex = endRaw === undefined || endRaw === null ? 0 : finiteNumber(endRaw);
953
+ const text = textRaw === undefined || textRaw === null ? "" : typeof textRaw === "string" ? textRaw : undefined;
954
+ const segmentMapped = (segment === undefined || segment === null || isJsonObject(segment)) && startIndex !== undefined && endIndex !== undefined && text !== undefined;
955
+ if (!segmentMapped)
956
+ unmapped["segment"] = JsonValue.parse(segment);
957
+ const indicesRaw = member("groundingChunkIndices");
958
+ const chunkIndices = indicesRaw === undefined || indicesRaw === null ? [] : chunkIndexList(indicesRaw);
959
+ if (chunkIndices === undefined)
960
+ unmapped["groundingChunkIndices"] = JsonValue.parse(indicesRaw);
961
+ const scoresRaw = member("confidenceScores");
962
+ const scores = scoresRaw === undefined || scoresRaw === null ? [] : finiteScores(scoresRaw);
963
+ if (scores === undefined)
964
+ unmapped["confidenceScores"] = JsonValue.parse(scoresRaw);
965
+ return { startIndex, endIndex, text, chunkIndices, scores, unmapped };
966
+ }
967
+ /** The value when it is a finite number, else undefined. */
968
+ function finiteNumber(value) {
969
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
970
+ }
971
+ /** The value when it is a list of finite numbers, else undefined. */
972
+ function finiteScores(value) {
973
+ if (!Array.isArray(value))
974
+ return undefined;
975
+ const scores = [];
976
+ for (const score of value) {
977
+ const n = finiteNumber(score);
978
+ if (n === undefined)
979
+ return undefined;
980
+ scores.push(n);
981
+ }
982
+ return scores;
983
+ }
984
+ /** The value when it is a list of chunk indexes (non-negative integers), else
985
+ * undefined. */
986
+ function chunkIndexList(value) {
987
+ if (!Array.isArray(value))
988
+ return undefined;
989
+ const indices = [];
990
+ for (const index of value) {
991
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0)
992
+ return undefined;
993
+ indices.push(index);
994
+ }
995
+ return indices;
996
+ }
997
+ /** The grounding supports' members that mapGroundingCitations could not map,
998
+ * verbatim at their native path: one entry per support, in order, holding
999
+ * those members (the whole `segment` when one of its members did not map)
1000
+ * and nothing for a support that mapped whole. Undefined when every support
1001
+ * mapped. */
1002
+ function groundingSupportsCarry(gm) {
1003
+ const supports = gm?.groundingSupports;
1004
+ if (!Array.isArray(supports))
1005
+ return undefined;
1006
+ let any = false;
1007
+ const entries = supports.map((support) => {
1008
+ const { unmapped } = readSupport(support);
1009
+ if (Object.keys(unmapped).length > 0)
1010
+ any = true;
1011
+ return unmapped;
1012
+ });
1013
+ return any ? { groundingSupports: entries } : undefined;
791
1014
  }
792
1015
  function toolCallContentKey(turnId, name, args) {
793
1016
  return `${turnId} ${name} ${JSON.stringify(args ?? {})}`;
@@ -861,7 +1084,85 @@ function mintBlockId(m, kind) {
861
1084
  m.set(kind, n + 1);
862
1085
  return `${kind}:${n}`;
863
1086
  }
864
- function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
1087
+ /** Whether a part carries a member one of driveAdkPart's non-text arms maps:
1088
+ * a call, a result, inline or file data, or code or its result. */
1089
+ function carriesPayload(part) {
1090
+ return (part.functionCall !== undefined ||
1091
+ part.functionResponse !== undefined ||
1092
+ part.inlineData !== undefined ||
1093
+ part.fileData !== undefined ||
1094
+ part.executableCode !== undefined ||
1095
+ part.codeExecutionResult !== undefined);
1096
+ }
1097
+ /** An event's parts with each part that holds text beside a payload member,
1098
+ * or two or more payload members, split into one part per payload member in
1099
+ * driveAdkPart's arm order, after a part holding its text (a genai Part holds
1100
+ * one kind of data, so such a part is malformed; every arm returns, and each
1101
+ * arm after the first would never map). The first part keeps the text, the
1102
+ * thought signature and every unmapped member (they are carried once); each
1103
+ * payload part holds its member alone, marked as thought when the original
1104
+ * part was. So the parts map as the same event with the split parts would
1105
+ * (but for the positions below): the text in its text or reasoning block,
1106
+ * and each payload member through its own arm, credential scrubs included
1107
+ * (SPEC.md §8.0, graceful degradation: no native value is dropped
1108
+ * silently). Any other part is
1109
+ * unchanged, and an event with no such part keeps its array. `origin` holds,
1110
+ * for each resulting part, the index of the native part it came from: a
1111
+ * null-id call's providerCallIndex and tool.start's `index` record that
1112
+ * original position (SPEC.md §8.0 item 2), never the split one. */
1113
+ function splitPayloadParts(parts) {
1114
+ if (!parts.some((p) => payloadCount(p) > (typeof p.text === "string" ? 0 : 1)))
1115
+ return { parts, origin: parts.map((_, i) => i) };
1116
+ const out = [];
1117
+ const origin = [];
1118
+ for (const [nativeIndex, part] of parts.entries()) {
1119
+ const textual = typeof part.text === "string";
1120
+ if (payloadCount(part) <= (textual ? 0 : 1)) {
1121
+ out.push(part);
1122
+ origin.push(nativeIndex);
1123
+ continue;
1124
+ }
1125
+ const { functionCall, functionResponse, inlineData, executableCode, codeExecutionResult, fileData, ...rest } = part;
1126
+ const mark = part.thought === true ? { thought: true } : {};
1127
+ const halves = [];
1128
+ if (functionCall !== undefined)
1129
+ halves.push({ functionCall, ...mark });
1130
+ if (functionResponse !== undefined)
1131
+ halves.push({ functionResponse, ...mark });
1132
+ if (inlineData !== undefined)
1133
+ halves.push({ inlineData, ...mark });
1134
+ if (executableCode !== undefined)
1135
+ halves.push({ executableCode, ...mark });
1136
+ if (codeExecutionResult !== undefined)
1137
+ halves.push({ codeExecutionResult, ...mark });
1138
+ if (fileData !== undefined)
1139
+ halves.push({ fileData, ...mark });
1140
+ const [first, ...others] = halves;
1141
+ const split = textual || first === undefined ? [rest, ...halves] : [{ ...rest, ...first }, ...others];
1142
+ out.push(...split);
1143
+ for (let k = 0; k < split.length; k++)
1144
+ origin.push(nativeIndex);
1145
+ }
1146
+ return { parts: out, origin };
1147
+ }
1148
+ /** How many of driveAdkPart's payload members a part holds. */
1149
+ function payloadCount(part) {
1150
+ let n = 0;
1151
+ if (part.functionCall !== undefined)
1152
+ n++;
1153
+ if (part.functionResponse !== undefined)
1154
+ n++;
1155
+ if (part.inlineData !== undefined)
1156
+ n++;
1157
+ if (part.executableCode !== undefined)
1158
+ n++;
1159
+ if (part.codeExecutionResult !== undefined)
1160
+ n++;
1161
+ if (part.fileData !== undefined)
1162
+ n++;
1163
+ return n;
1164
+ }
1165
+ function driveAdkPart(a, part, index, nativeIndex, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
865
1166
  // ── UNMAPPED PART FIELDS (mediaResolution/videoMetadata/toolCall/toolResponse/
866
1167
  // partMetadata/audioTranscription/mediaProcessing/speechMetadata) → provider-raw content.block
867
1168
  // (fixture-drift ratchet finding, google-adk-ratchet task; Tenet-6; SPEC §8 item 23). These
@@ -900,6 +1201,16 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
900
1201
  unmappedPartFields["mediaProcessing"] = JsonValue.parse(part.mediaProcessing);
901
1202
  if (part.speechMetadata !== undefined)
902
1203
  unmappedPartFields["speechMetadata"] = JsonValue.parse(part.speechMetadata);
1204
+ // A part marked as thought that carries no text but a call, a result or
1205
+ // media (ADK-Python's A2A relay marks every part it converts from a remote
1206
+ // agent's in-progress status as thought) maps through that
1207
+ // payload's arm below, as it would unmarked, and not as an empty reasoning
1208
+ // block. Its `thought` flag, which no event of those arms holds, rides this
1209
+ // carry (SPEC.md §8.0, graceful degradation: no native value is dropped
1210
+ // silently).
1211
+ const thoughtPayload = part.thought === true && typeof part.text !== "string" && carriesPayload(part);
1212
+ if (thoughtPayload)
1213
+ unmappedPartFields["thought"] = true;
903
1214
  if (Object.keys(unmappedPartFields).length > 0) {
904
1215
  a.contentBlock(messageId, {
905
1216
  type: "provider-raw",
@@ -908,7 +1219,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
908
1219
  });
909
1220
  }
910
1221
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
911
- if (part.thought === true) {
1222
+ if (part.thought === true && !thoughtPayload) {
912
1223
  const id = mintBlockId(blockIds, "reasoning");
913
1224
  a.reasoningStart(id, messageId);
914
1225
  // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
@@ -978,7 +1289,8 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
978
1289
  return ""; // dedup the partial:false aggregate re-send (window-scoped content identity)
979
1290
  toolCallId = minted.toolCallId;
980
1291
  }
981
- const providerCallIndex = realId !== null ? undefined : index;
1292
+ // The native part's position, not the split one (see splitPayloadParts).
1293
+ const providerCallIndex = realId !== null ? undefined : nativeIndex;
982
1294
  // The reserved credential call's args carry the whole ADK AuthConfig: scrub
983
1295
  // them to the allowlist (see scrubAdkAuthConfig) before they reach
984
1296
  // tool.args.* and the folded tool-call block.
@@ -990,7 +1302,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
990
1302
  a.toolStart({
991
1303
  toolCallId,
992
1304
  name: fc.name,
993
- index,
1305
+ index: nativeIndex,
994
1306
  longRunning,
995
1307
  providerMetadata: providerCallIndex !== undefined
996
1308
  ? AgProviderMeta.parse({ google: { providerCallIndex } })
@@ -1145,7 +1457,7 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
1145
1457
  else
1146
1458
  pendingAsks.set(turnId, [ask]);
1147
1459
  }
1148
- function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription) {
1460
+ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, turnClosed) {
1149
1461
  // Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
1150
1462
  // a `finished: true` transcription whose text is the chunks joined
1151
1463
  // (utils/live_connection_utils.js, @google/adk 2.1.0). That aggregate is not
@@ -1180,8 +1492,17 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1180
1492
  }
1181
1493
  // `interrupted` → turn.abort is closed in drive(), after this event's own
1182
1494
  // content and carries (see closeInterrupted), never here mid-event.
1183
- // ── promptFeedback → prompt.blocked ──
1184
- if (event.promptFeedback?.blockReason !== undefined) {
1495
+ // ── prompt block → prompt.blocked: one record per block event while the turn
1496
+ // is open, never after its terminal. A record runs before the close logic, so
1497
+ // it precedes the terminal the same event may bring; the terminal itself is
1498
+ // unchanged. An event carrying promptFeedback is recorded from it (a
1499
+ // dual-shape event records once); otherwise ADK's own shape records: a treated
1500
+ // errorCode with no finishReason and no content (adkPromptBlockReason), reason
1501
+ // mapped as below and no safety, since that event carries no ratings.
1502
+ if (turnClosed) {
1503
+ // no record after the turn's terminal
1504
+ }
1505
+ else if (event.promptFeedback?.blockReason !== undefined) {
1185
1506
  const blockReason = event.promptFeedback.blockReason;
1186
1507
  const reason = mapBlockReason(blockReason);
1187
1508
  const safety = event.promptFeedback.safetyRatings !== undefined
@@ -1196,10 +1517,9 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1196
1517
  : undefined;
1197
1518
  // draft.8 (§4): an unmapped block reason (reason "other") carries the
1198
1519
  // 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.
1520
+ // lossless finishReason takes no finishReasonRaw. No ADK-built event
1521
+ // carries promptFeedback at @google/adk 2.1.0, so this arm serves events
1522
+ // built elsewhere; ADK's own shape is the branch below.
1203
1523
  a.emit({
1204
1524
  type: "prompt.blocked",
1205
1525
  reason,
@@ -1207,6 +1527,13 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1207
1527
  ...(safety !== undefined ? { safety } : {}),
1208
1528
  });
1209
1529
  }
1530
+ else {
1531
+ const blockReason = adkPromptBlockReason(event);
1532
+ if (blockReason !== undefined) {
1533
+ const reason = mapBlockReason(blockReason);
1534
+ a.emit({ type: "prompt.blocked", reason, ...(reason === "other" ? { reasonRaw: blockReason } : {}) });
1535
+ }
1536
+ }
1210
1537
  // ── groundingMetadata → source + display.required ──────────────────────────
1211
1538
  // groundingSupports (per-segment citations) are handled BEFORE this function
1212
1539
  // runs — collected by `mapGroundingCitations` and attached to the streamed text
@@ -1374,8 +1701,10 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1374
1701
  // absent from `@iqai/adk`'s surface, closed by the same opportunistic-carry
1375
1702
  // precedent (absent from all recorded fixtures — no golden-snapshot impact).
1376
1703
  //
1377
- // `author`/`timestamp` are ALSO real, currently-unread AdkEvent fields
1378
- // (same manifest inventory) but are DELIBERATELY NOT folded into this bag.
1704
+ // `author`/`timestamp` are ALSO real AdkEvent fields (same manifest
1705
+ // inventory) but are DELIBERATELY NOT folded into this bag (`author` is read
1706
+ // only by the aggregate window: its key, aggregateWindowKey, and the
1707
+ // same-author lookup in windowCandidates).
1379
1708
  // On the official `@google/adk` 1.3.0 `Event` interface `timestamp: number`
1380
1709
  // is REQUIRED and `author?: string` is optional in the TYPE — but the
1381
1710
  // runner sets author on every event it appends in practice, so the
@@ -1436,11 +1765,28 @@ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, st
1436
1765
  unmappedEvent["isolationScope"] = JsonValue.parse(event.isolationScope);
1437
1766
  if (event.citationMetadata !== undefined)
1438
1767
  unmappedEvent["citationMetadata"] = JsonValue.parse(event.citationMetadata);
1768
+ const groundingSupports = groundingSupportsCarry(event.groundingMetadata);
1769
+ if (groundingSupports !== undefined)
1770
+ unmappedEvent["groundingMetadata"] = groundingSupports;
1439
1771
  if (event.customMetadata !== undefined) {
1440
- const kept = withoutRelayBookkeeping(JsonValue.parse(event.customMetadata));
1772
+ const kept = carriedMetadata(JsonValue.parse(event.customMetadata));
1441
1773
  if (kept !== undefined)
1442
1774
  unmappedEvent["customMetadata"] = kept;
1443
1775
  }
1776
+ // An error message without an error code (ADK's A2A relay reports its own
1777
+ // failure so, and a remote executor's that it passes on) is not an in-band
1778
+ // invocation error (spec §8.0 item 35), which maps the code and message as a
1779
+ // pair; its message, and a code that is not a string, ride here verbatim
1780
+ // (spec §8.0 graceful degradation and item 23).
1781
+ if (inBandErrorOf(event) === undefined) {
1782
+ const message = event.errorMessage;
1783
+ const code = event.errorCode;
1784
+ if (message !== undefined && message !== null) {
1785
+ if (code !== undefined && code !== null)
1786
+ unmappedEvent["errorCode"] = JsonValue.parse(code);
1787
+ unmappedEvent["errorMessage"] = JsonValue.parse(message);
1788
+ }
1789
+ }
1444
1790
  if (Object.keys(unmappedEvent).length > 0) {
1445
1791
  a.contentBlock(messageId, {
1446
1792
  type: "provider-raw",
@@ -1455,7 +1801,11 @@ export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
1455
1801
  * SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
1456
1802
  * the stream (e.g. its LLM-call limit), the host catches it and pushes
1457
1803
  * `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
1458
- * open turn closes `turn.error` with that code and message. The shape matches the OpenAI
1804
+ * open turn closes `turn.error` with that code and message and the turn's
1805
+ * usage plus `usage`, which covers only work the stream did not report (so
1806
+ * a host passes the usage of unreported work, never a total); a turn whose
1807
+ * pause was signalled closes paused first, and the error then closes on a
1808
+ * new top-level turn (spec §8.0 item 26). The shape matches the OpenAI
1459
1809
  * facet's sentinel. A host may build it from the caught Error itself
1460
1810
  * (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
1461
1811
  * read from the raw native, so the Error's own message is kept.
@@ -1510,6 +1860,177 @@ function isHostCompleteNative(v) {
1510
1860
  * So push() never throws (SPEC §8.0), and no facet state believes a turn,
1511
1861
  * message or block is open that never reached the wire.
1512
1862
  */
1863
+ // ─── ADK in-band invocation errors (spec §8.0 item 35) ───────────────────────
1864
+ // ADK yields an in-band invocation error (errorCode AND errorMessage) without
1865
+ // ending the invocation: a SequentialAgent runs its next sub-agent, a Workflow
1866
+ // node retries, a callback or a further model round follows. So the turn never
1867
+ // closes on one: the push() that receives it emits the non-terminal `error`
1868
+ // event, and the invocation's turn closes with one turn.error at the
1869
+ // invocation's end (the host-completion event, a host-terminal event or
1870
+ // flush()), never as success.
1871
+ /** Spec §8.0 item 35: an in-band invocation error carries both errorCode and
1872
+ * errorMessage. */
1873
+ function inBandErrorOf(event) {
1874
+ const code = event.errorCode;
1875
+ const message = event.errorMessage;
1876
+ return typeof code === "string" && typeof message === "string" ? { code, message } : undefined;
1877
+ }
1878
+ /** The record item 35's relay repeat compares for one in-band error. */
1879
+ function inBandErrorRecord(event, error) {
1880
+ const metadata = event.customMetadata;
1881
+ return {
1882
+ code: error.code,
1883
+ message: error.message,
1884
+ usage: event.usageMetadata !== undefined ? canonicalJson(JsonValue.parse(event.usageMetadata)) : "",
1885
+ taskId: isJsonObject(metadata) && Object.hasOwn(metadata, "a2a:task_id") ? canonicalJson(metadata["a2a:task_id"] ?? null) : "",
1886
+ };
1887
+ }
1888
+ /** Item 35's relay repeat: `RemoteA2AAgent` stamps an `a2a:request` entry on
1889
+ * each relayed event that carries `turnComplete: true`, and at @google/adk
1890
+ * 2.1.0 it reports a remote failure that carries no content only in that
1891
+ * closing event, so one failure can reach the facet twice. The closing event
1892
+ * repeats an earlier in-band error of the same source when the code, message
1893
+ * and usage report are equal (an absent report matches only an absent one)
1894
+ * and both carry the same `a2a:task_id` entry, present on both. */
1895
+ function isRelayRepeat(event, record, earlier) {
1896
+ const metadata = event.customMetadata;
1897
+ if (event.turnComplete !== true || !isJsonObject(metadata) || !Object.hasOwn(metadata, "a2a:request"))
1898
+ return false;
1899
+ if (record.taskId === "")
1900
+ return false;
1901
+ return earlier.some((e) => e.taskId === record.taskId && e.code === record.code && e.message === record.message && e.usage === record.usage);
1902
+ }
1903
+ /** The aggregate window's key: the turn plus the event's source (author,
1904
+ * branch and node path). A missing or non-string value is its own key, never
1905
+ * equal to an empty string. */
1906
+ function aggregateWindowKey(turnId, event, stream = relayStreamOf(event)) {
1907
+ const author = event.author;
1908
+ const branch = event.branch;
1909
+ const path = event.nodeInfo?.path;
1910
+ return JSON.stringify([
1911
+ turnId,
1912
+ typeof author === "string" ? author : null,
1913
+ typeof branch === "string" ? branch : null,
1914
+ typeof path === "string" ? path : null,
1915
+ stream,
1916
+ ]);
1917
+ }
1918
+ /** What a relayed event is, read from the native relay record ADK's
1919
+ * RemoteA2AAgent attaches: its A2A task (the `a2a:task_id` entry, null when
1920
+ * the reply carried none) and its stream, one artifact's chunks and their
1921
+ * aggregate (`artifact:<id>`), the status messages (`status`), or a Task or
1922
+ * Message that restates the task (`snapshot`). null for an event that is not
1923
+ * relayed. */
1924
+ function relayOf(event) {
1925
+ const metadata = event.customMetadata;
1926
+ if (!isJsonObject(metadata))
1927
+ return null;
1928
+ const response = metadata["a2a:response"];
1929
+ if (!isJsonObject(response))
1930
+ return null;
1931
+ const taskId = metadata["a2a:task_id"];
1932
+ const task = typeof taskId === "string" ? taskId : null;
1933
+ const kind = response["kind"];
1934
+ const artifact = response["artifact"];
1935
+ if (kind === "artifact-update" && isJsonObject(artifact) && typeof artifact["artifactId"] === "string")
1936
+ return { task, stream: `artifact:${artifact["artifactId"]}` };
1937
+ if (kind === "status-update")
1938
+ return { task, stream: "status" };
1939
+ if (kind === "task" || kind === "message")
1940
+ return { task, stream: "snapshot" };
1941
+ return null;
1942
+ }
1943
+ /** The window-key part of a relayed stream: the task and the stream, so a new
1944
+ * relay pass (a new A2A task) never reads the windows of an earlier one. */
1945
+ function relayStreamKey(task, stream) {
1946
+ return JSON.stringify([task, stream]);
1947
+ }
1948
+ /** The A2A stream a relayed event belongs to, scoped by its task; null for
1949
+ * every event that is not relayed. */
1950
+ function relayStreamOf(event) {
1951
+ const relay = relayOf(event);
1952
+ return relay === null ? null : relayStreamKey(relay.task, relay.stream);
1953
+ }
1954
+ /** The open windows a non-partial event reads and closes: the one under its
1955
+ * own key; else, for an event without a branch, every open window of the
1956
+ * same turn, author and node path. `own`, `relay` and `wantStream` are the
1957
+ * event's own window key, relay record and relay stream, read once by the
1958
+ * caller. */
1959
+ function windowCandidates(windows, turnId, event, own, relay, wantStream) {
1960
+ if (windows.has(own))
1961
+ return [own];
1962
+ // A relayed artifact with no chunks of its own can repeat the status text
1963
+ // of its own task (a peer that sends its answer as status messages, then
1964
+ // the same text as its final artifact).
1965
+ if (relay !== null && relay.stream.startsWith("artifact:")) {
1966
+ const status = aggregateWindowKey(turnId, event, relayStreamKey(relay.task, "status"));
1967
+ if (windows.has(status))
1968
+ return [status];
1969
+ }
1970
+ if (typeof event.branch === "string")
1971
+ return [];
1972
+ return sourceWindows(windows, turnId, event, true)
1973
+ .filter(([, stream]) => stream === wantStream)
1974
+ .map(([key]) => key);
1975
+ }
1976
+ /** The open windows of the source of an event, as [key, stream] pairs: the
1977
+ * same turn, author and node path, and the same branch unless anyBranch. */
1978
+ function sourceWindows(windows, turnId, event, anyBranch) {
1979
+ const author = event.author;
1980
+ const branch = event.branch;
1981
+ const path = event.nodeInfo?.path;
1982
+ const wantAuthor = typeof author === "string" ? author : null;
1983
+ const wantBranch = typeof branch === "string" ? branch : null;
1984
+ const wantPath = typeof path === "string" ? path : null;
1985
+ const out = [];
1986
+ for (const key of windows.keys()) {
1987
+ const parsed = JSON.parse(key);
1988
+ if (Array.isArray(parsed) &&
1989
+ parsed[0] === turnId &&
1990
+ parsed[1] === wantAuthor &&
1991
+ (anyBranch || parsed[2] === wantBranch) &&
1992
+ parsed[3] === wantPath)
1993
+ out.push([key, parsed[4]]);
1994
+ }
1995
+ return out;
1996
+ }
1997
+ /** The windows a relayed Task or Message restates: its task's open artifact
1998
+ * windows, in the order they opened, and its task's status window. */
1999
+ function snapshotWindows(windows, turnId, event, task) {
2000
+ const own = sourceWindows(windows, turnId, event, false);
2001
+ const artifacts = own.filter(([, stream]) => {
2002
+ if (typeof stream !== "string")
2003
+ return false;
2004
+ const parsed = JSON.parse(stream);
2005
+ return Array.isArray(parsed) && parsed[0] === task && typeof parsed[1] === "string" && parsed[1].startsWith("artifact:");
2006
+ });
2007
+ const status = relayStreamKey(task, "status");
2008
+ return { artifacts: artifacts.map(([key]) => key), status: own.filter(([, stream]) => stream === status).map(([key]) => key) };
2009
+ }
2010
+ /** The streamed text a relayed Task or Message is read against. ADK renders a
2011
+ * Task as its artifacts' parts, then its status message's (taskToAdkEvent), so
2012
+ * the snapshot is matched in that order: against the artifacts and the status
2013
+ * text together (a task still in the state it streamed), else the artifacts
2014
+ * alone (its status message is new, and renders), else the status text alone.
2015
+ * The first reading the snapshot repeats is taken; with none, the first. */
2016
+ function snapshotReading(artifactText, statusText, text) {
2017
+ const readings = [artifactText + statusText, artifactText, statusText].filter((r) => r.length > 0);
2018
+ const repeats = (r) => text.startsWith(r) || r.startsWith(text) || r.endsWith(text);
2019
+ return readings.find(repeats) ?? readings[0] ?? "";
2020
+ }
2021
+ /** The relay windows an event of the relaying agent ends without being
2022
+ * relayed itself: ADK's RemoteA2AAgent reports a failed request with an
2023
+ * event of its own (errorMessage, turnComplete, no relay record), which ends
2024
+ * every relayed stream of that author and node path. */
2025
+ function relayWindowsEndedBy(windows, turnId, event, relay) {
2026
+ if (relay !== null)
2027
+ return [];
2028
+ if (event.errorMessage === undefined && event.turnComplete !== true)
2029
+ return [];
2030
+ return sourceWindows(windows, turnId, event, true)
2031
+ .filter(([, stream]) => stream !== null)
2032
+ .map(([key]) => key);
2033
+ }
1513
2034
  export function createAdkNormalizer(options = {}) {
1514
2035
  // The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
1515
2036
  // re-drives to the same ids and no push() reads randomness.
@@ -1527,7 +2048,8 @@ function createInnerAdkNormalizer(options, invokeStem) {
1527
2048
  const hostCompletion = options.hostCompletion === true;
1528
2049
  const a = new StreamAssembler();
1529
2050
  const threadId = options.threadId ?? "google";
1530
- // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
2051
+ // §8.3 per-instance accumulator (replaces the module-level streamedText Map),
2052
+ // keyed by aggregateWindowKey (turn + source):
1531
2053
  const streamedText = new Map();
1532
2054
  // Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
1533
2055
  const streamedTranscription = new Map();
@@ -1547,6 +2069,18 @@ function createInnerAdkNormalizer(options, invokeStem) {
1547
2069
  // double-render quirk applies to usage too), so counting non-partial
1548
2070
  // events counts each round exactly once.
1549
2071
  const usageByTurn = new Map();
2072
+ // The usage reports summed into usageByTurn, in order, so the report that an
2073
+ // in-band error's repeat supersedes can be replaced (spec §8.0 item 35).
2074
+ const usageReportsByTurn = new Map();
2075
+ // Spec §8.0 item 35: per turn, the invocation's first in-band invocation
2076
+ // error (errorCode AND errorMessage). The turn never closes on one, never
2077
+ // closes as success after one, and closes with one turn.error at the
2078
+ // invocation's end.
2079
+ const firstInBandError = new Map();
2080
+ // Per turn and source (author, branch, node path): the previous event, for
2081
+ // item 35's SSE repeat, and the in-band errors seen, for its relay repeat.
2082
+ const previousBySource = new Map();
2083
+ const inBandErrorsBySource = new Map();
1550
2084
  // Per-turn HITL asks emitted by the two `actions.requested*` arms (audit
1551
2085
  // M26) — populated in emission order by `trackPendingAsk` inside
1552
2086
  // `driveAdkTopLevel`. Consulted ONLY by `maybeCloseTurn`'s REAL close path
@@ -1559,6 +2093,13 @@ function createInnerAdkNormalizer(options, invokeStem) {
1559
2093
  // Host obligation 4 (opt-in): a success close stashed until the sentinel, and
1560
2094
  // the non-HITL long-running calls still unanswered, per turn.
1561
2095
  const deferredClose = new Map();
2096
+ // Per turn: a final response of a pausing agent (the author of a pending
2097
+ // ask's event) arrived while that ask was pending, one of item 26's pause
2098
+ // signals. A final stashed before any ask is not one, and neither is another
2099
+ // agent's final, which only follows the signal.
2100
+ const finalWhileAsking = new Set();
2101
+ const askingAuthors = new Map();
2102
+ const finalOfPausingAgent = (turnId, event) => (pendingAsks.get(turnId)?.length ?? 0) > 0 && askingAuthors.get(turnId)?.has(event.author) === true;
1562
2103
  // Live barge-ins (`interrupted: true`, ADK's live aggregator) awaiting their
1563
2104
  // close. An interrupt on a PARTIAL text event is followed by ADK's full-text
1564
2105
  // aggregate of the same model turn (utils/live_connection_utils.js:175-178),
@@ -1574,6 +2115,16 @@ function createInnerAdkNormalizer(options, invokeStem) {
1574
2115
  // opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
1575
2116
  const generationOf = new Map();
1576
2117
  const interruptClosed = new Set();
2118
+ // Per turn key: whether the previous event carried both turnComplete and
2119
+ // interrupted, the message after which ADK re-yields a bare {interrupted}.
2120
+ const previousBothFlags = new Map();
2121
+ // Turns a final response closed as success before the invocation ended
2122
+ // (without the host-completion event only). ADK keeps running after such a
2123
+ // final (a SequentialAgent's next sub-agent, a LoopAgent's next iteration),
2124
+ // and content that follows opens the next generation of the turn rather
2125
+ // than landing after its terminal (spec §8.0: framework content that
2126
+ // arrives after a terminal opens a new turn).
2127
+ const successClosed = new Set();
1577
2128
  // Turns whose last function response has no model output after it yet. On
1578
2129
  // the Live path the model always answers a tool result with a reply
1579
2130
  // generation, and ADK can yield the call generation's turnComplete between
@@ -1607,12 +2158,6 @@ function createInnerAdkNormalizer(options, invokeStem) {
1607
2158
  function maybeCloseTurn(event, turnId, messageId, isPartial) {
1608
2159
  if (isPartial || closedTurns.has(turnId))
1609
2160
  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
2161
  const parts = event.content?.parts ?? [];
1617
2162
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
1618
2163
  const interrupted = event.interrupted === true || interruptPending.has(turnId);
@@ -1647,23 +2192,31 @@ function createInnerAdkNormalizer(options, invokeStem) {
1647
2192
  // reply ends the call generation, not the turn (see awaitingReply).
1648
2193
  if (event.finishReason === undefined && event.errorCode === undefined && awaitingReply.has(turnId))
1649
2194
  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;
2195
+ // Spec §8.0 item 35: an in-band invocation error never closes the turn
2196
+ // (recordErrorAndUsage emitted its `error` event), and once the invocation
2197
+ // met one, no final response closes it either: the invocation's end does
2198
+ // (hostComplete, hostError, flush). A final response while an ask is
2199
+ // pending still signals the pause (item 26).
2200
+ if (inBandErrorOf(event) !== undefined)
2201
+ return;
2202
+ if (firstInBandError.has(turnId)) {
2203
+ if ((pendingAsks.get(turnId)?.length ?? 0) > 0) {
2204
+ deferredClose.set(turnId, event);
2205
+ if (finalOfPausingAgent(turnId, event))
2206
+ finalWhileAsking.add(turnId);
2207
+ }
2208
+ return;
2209
+ }
1656
2210
  // ── The nodeInfo gate (R&D item 6, step 1) ──
1657
2211
  // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
1658
2212
  // final text (nodeInfo present) is mid-invocation: closing the invocation
1659
2213
  // turn on it put the workflow's later events after the terminal and parked
1660
2214
  // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1661
2215
  // 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)
2216
+ // (NodeTool puts nodeInfo into plain runs too). A completed workflow closes
2217
+ // success only on the host-completion event (the `hostCompletion` opt-in,
2218
+ // §8.0 host obligation 4); without it, it flushes turn.abort.
2219
+ if (event.nodeInfo !== undefined)
1667
2220
  return;
1668
2221
  // Host obligation 4 (opt-in): a success close waits for the
1669
2222
  // host-completion event, because the run may not be over (a
@@ -1671,12 +2224,24 @@ function createInnerAdkNormalizer(options, invokeStem) {
1671
2224
  // while an ask is pending waits on every host (item 26: the invocation's
1672
2225
  // end, the host-completion event or flush()), because the model may run
1673
2226
  // 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)) {
2227
+ // so a stream ending here is byte-identical.
2228
+ if (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0) {
1676
2229
  deferredClose.set(turnId, event);
2230
+ if (finalOfPausingAgent(turnId, event))
2231
+ finalWhileAsking.add(turnId);
1677
2232
  return;
1678
2233
  }
1679
- closeOnFinalResponse(event, turnId, messageId, errorClose);
2234
+ // ── The branch gate ──
2235
+ // A final response that carries a `branch` (a ParallelAgent's sub-agent)
2236
+ // ends that branch, not the invocation: ADK runs the other branches after
2237
+ // it, so closing the turn on it put their events after the terminal and
2238
+ // parked reduce() (INV-TURN). Without the host-completion event such a
2239
+ // turn closes at flush(), as a completed Workflow does.
2240
+ if (typeof event.branch === "string")
2241
+ return;
2242
+ // No ask is pending here, so this close is a success.
2243
+ successClosed.add(turnId);
2244
+ closeOnFinalResponse(event, turnId, messageId);
1680
2245
  }
1681
2246
  /** The paused close at the invocation's end. A final response stashed while
1682
2247
  * the asks were pending closes as it would have on arrival (paused, with its
@@ -1684,7 +2249,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1684
2249
  function closePaused(turnId, messageId, asks) {
1685
2250
  const stashed = deferredClose.get(turnId);
1686
2251
  if (stashed !== undefined) {
1687
- closeOnFinalResponse(stashed, turnId, messageId, undefined);
2252
+ closeOnFinalResponse(stashed, turnId, messageId);
1688
2253
  return;
1689
2254
  }
1690
2255
  closedTurns.add(turnId);
@@ -1697,8 +2262,9 @@ function createInnerAdkNormalizer(options, invokeStem) {
1697
2262
  });
1698
2263
  }
1699
2264
  /** 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) {
2265
+ * turn.done (paused when asks are pending, else success). An in-band
2266
+ * invocation error never reaches it (spec §8.0 item 35). */
2267
+ function closeOnFinalResponse(event, turnId, messageId) {
1702
2268
  closedTurns.add(turnId);
1703
2269
  const rawFinish = event.finishReason ?? event.errorCode;
1704
2270
  const finish = resolveFinishReason(rawFinish);
@@ -1711,9 +2277,8 @@ function createInnerAdkNormalizer(options, invokeStem) {
1711
2277
  // `rawErrorCode`, never fabricated as a finishReason. Lossy-only (unlike
1712
2278
  // vercel-ai's unconditional carry) so no recorded cassette — all STOP
1713
2279
  // 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) {
2280
+ // closedTurns-guarded), never on partials.
2281
+ if (rawFinish !== undefined && finish.lossy) {
1717
2282
  a.emit({
1718
2283
  type: "message.metadata",
1719
2284
  messageId,
@@ -1723,41 +2288,135 @@ function createInnerAdkNormalizer(options, invokeStem) {
1723
2288
  });
1724
2289
  }
1725
2290
  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.
2291
+ // The turn's accrued usage rides its terminal.
1728
2292
  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
- });
2293
+ // SPEC §4's safety_blocked conformance note: a safety_blocked close
2294
+ // carries safety[].category so the collapsed reason stays recoverable. A
2295
+ // blocked rating names it; when no rating does (ADK 2.1.0 delivers none on
2296
+ // a real block), the native value finishReason was mapped from is the
2297
+ // category, as a block.
2298
+ const rated = mapBlockedSafety(event.safetyRatings);
2299
+ const safety = rated === undefined && finish.value === "safety_blocked" && rawFinish !== undefined
2300
+ ? [{ category: rawFinish, blocked: true }]
2301
+ : rated;
2302
+ // A turn with pending HITL asks (requestedAuthConfigs /
2303
+ // requestedToolConfirmations / adk_request_input, tracked by
2304
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
2305
+ // unresolved requests the turn is parked on, never a fabricated success
2306
+ // (SPEC §8 items 12 + 18). A paused close carries finishReason "paused"
2307
+ // (the HITL value), the same as the pause-end close above.
2308
+ const asks = pendingAsks.get(turnId);
2309
+ const paused = asks !== undefined && asks.length > 0;
2310
+ a.closeTurnDone(turnId, {
2311
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
2312
+ finishReason: paused ? "paused" : finish.value,
2313
+ // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
2314
+ // native value verbatim in turn.done.finishReasonRaw. That is the value
2315
+ // finishReason was mapped from: the wire finishReason, or for an
2316
+ // errorCode-only soft close the errorCode. A paused close's "paused" is
2317
+ // not a fallback, so it takes no companion. message.metadata's
2318
+ // rawFinishReason/rawErrorCode carry stays for one cohort.
2319
+ ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
2320
+ ...(usage !== undefined ? { usage } : {}),
2321
+ ...(safety !== undefined ? { safety } : {}),
2322
+ });
2323
+ }
2324
+ /** Count one usage report toward the turn's usage; returns its slot. */
2325
+ function countUsage(turnId, usage) {
2326
+ const reports = usageReportsByTurn.get(turnId) ?? [];
2327
+ reports.push(usage);
2328
+ usageReportsByTurn.set(turnId, reports);
2329
+ const accumulated = accumulateUsage(usageByTurn.get(turnId), usage);
2330
+ if (accumulated !== undefined)
2331
+ usageByTurn.set(turnId, accumulated);
2332
+ return reports.length - 1;
2333
+ }
2334
+ /** Replace the report in one slot and re-sum the turn's usage. */
2335
+ function replaceUsage(turnId, slot, usage) {
2336
+ const reports = usageReportsByTurn.get(turnId);
2337
+ if (reports === undefined || slot >= reports.length)
2338
+ return;
2339
+ reports[slot] = usage;
2340
+ let sum;
2341
+ for (const report of reports)
2342
+ sum = accumulateUsage(sum, report);
2343
+ if (sum !== undefined)
2344
+ usageByTurn.set(turnId, sum);
2345
+ }
2346
+ /** Spec §8.0 item 35 when the event arrives, and the event's usage count.
2347
+ * Every non-partial event of an open turn counts its usage report once,
2348
+ * functionCall rounds included (see the usageByTurn doc above). An in-band
2349
+ * invocation error that repeats an earlier one yields no `error` event: the
2350
+ * SSE aggregate that repeats the previous in-band error of its source as the
2351
+ * model call's stream closes (its report replaces the one it repeats, so
2352
+ * the call counts once, from the later report), and the relay's closing
2353
+ * event (it adds no usage). Any other in-band error emits `error` from this
2354
+ * push and, when it is the invocation's first, latches it. */
2355
+ function recordErrorAndUsage(event, turnId, isPartial, sourceKey) {
2356
+ const previous = previousBySource.get(sourceKey);
2357
+ const error = inBandErrorOf(event);
2358
+ const counting = !isPartial && !closedTurns.has(turnId);
2359
+ let usageSlot;
2360
+ if (error === undefined) {
2361
+ if (counting && event.usageMetadata !== undefined)
2362
+ usageSlot = countUsage(turnId, event.usageMetadata);
1735
2363
  }
1736
2364
  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
- });
2365
+ const record = inBandErrorRecord(event, error);
2366
+ const earlier = inBandErrorsBySource.get(sourceKey) ?? [];
2367
+ const repeatsPrevious = event.partial === false &&
2368
+ previous !== undefined &&
2369
+ !previous.partialFalse &&
2370
+ previous.error !== undefined &&
2371
+ previous.error.code === error.code &&
2372
+ previous.error.message === error.message;
2373
+ if (repeatsPrevious) {
2374
+ const later = event.usageMetadata ?? previous.usage;
2375
+ if (counting && later !== undefined) {
2376
+ if (previous.usageSlot !== undefined) {
2377
+ replaceUsage(turnId, previous.usageSlot, later);
2378
+ usageSlot = previous.usageSlot;
2379
+ }
2380
+ else {
2381
+ usageSlot = countUsage(turnId, later);
2382
+ }
2383
+ }
2384
+ }
2385
+ else if (!isRelayRepeat(event, record, earlier)) {
2386
+ a.emit({ type: "error", turnId, code: error.code, message: error.message });
2387
+ if (!firstInBandError.has(turnId))
2388
+ firstInBandError.set(turnId, error);
2389
+ if (counting && event.usageMetadata !== undefined)
2390
+ usageSlot = countUsage(turnId, event.usageMetadata);
2391
+ }
2392
+ inBandErrorsBySource.set(sourceKey, [...earlier, record]);
1760
2393
  }
2394
+ previousBySource.set(sourceKey, { partialFalse: event.partial === false, error, usage: event.usageMetadata, usageSlot });
2395
+ }
2396
+ /** Item 26's pause signal: an ask is pending and the stream showed the
2397
+ * pause's end (its pause-end event, or a final response while the ask was
2398
+ * pending). An in-band invocation error is never one. */
2399
+ function pauseSignalled(turnId) {
2400
+ return (pendingAsks.get(turnId)?.length ?? 0) > 0 && (pauseEnded.has(turnId) || finalWhileAsking.has(turnId));
2401
+ }
2402
+ /** Spec §8.0 item 35 at the invocation's end: the one turn.error of a turn
2403
+ * whose invocation met an invocation error, with the given code and message
2404
+ * and the turn's accumulated usage. */
2405
+ function closeInvocationError(turnId, error, usage) {
2406
+ closedTurns.add(turnId);
2407
+ a.closeMessage(`msg_${turnId}`);
2408
+ a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
2409
+ }
2410
+ /** Spec §8.0 item 26 with an invocation error: after the paused close, the
2411
+ * error closes on a new top-level turn of the invocation, which carries one
2412
+ * assistant message with no content; its turn.error carries only usage a
2413
+ * host-terminal event reports. */
2414
+ function closeErrorTurn(pausedTurnId, error, usage) {
2415
+ const turnId = `${pausedTurnId}_error`;
2416
+ const messageId = ensureOpen(turnId);
2417
+ closedTurns.add(turnId);
2418
+ a.closeMessage(messageId);
2419
+ a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
1761
2420
  }
1762
2421
  /** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
1763
2422
  * pending until its functionResponse arrives. */
@@ -1781,7 +2440,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1781
2440
  * close with the accumulated usage when the run ended on a non-final event,
1782
2441
  * e.g. a completed Workflow). */
1783
2442
  function hostComplete() {
1784
- for (const turnId of openTurns) {
2443
+ for (const turnId of [...openTurns]) {
1785
2444
  if (closedTurns.has(turnId))
1786
2445
  continue;
1787
2446
  if (interruptPending.has(turnId)) {
@@ -1790,6 +2449,20 @@ function createInnerAdkNormalizer(options, invokeStem) {
1790
2449
  }
1791
2450
  const messageId = `msg_${turnId}`;
1792
2451
  const asks = pendingAsks.get(turnId);
2452
+ // Spec §8.0 items 26 and 35: an invocation that met an in-band error
2453
+ // never closes as success. A signalled pause closes paused, and the
2454
+ // error follows on its own turn; otherwise the turn closes turn.error.
2455
+ const error = firstInBandError.get(turnId);
2456
+ if (error !== undefined) {
2457
+ if (asks !== undefined && pauseSignalled(turnId)) {
2458
+ closePaused(turnId, messageId, asks);
2459
+ closeErrorTurn(turnId, error, undefined);
2460
+ }
2461
+ else {
2462
+ closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
2463
+ }
2464
+ continue;
2465
+ }
1793
2466
  if (asks !== undefined && asks.length > 0) {
1794
2467
  closePaused(turnId, messageId, asks);
1795
2468
  continue;
@@ -1798,7 +2471,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1798
2471
  continue;
1799
2472
  const stashed = deferredClose.get(turnId);
1800
2473
  if (stashed !== undefined) {
1801
- closeOnFinalResponse(stashed, turnId, messageId, undefined);
2474
+ closeOnFinalResponse(stashed, turnId, messageId);
1802
2475
  continue;
1803
2476
  }
1804
2477
  closedTurns.add(turnId);
@@ -1823,8 +2496,21 @@ function createInnerAdkNormalizer(options, invokeStem) {
1823
2496
  for (const turnId of [...openTurns].reverse()) {
1824
2497
  if (closedTurns.has(turnId))
1825
2498
  continue;
2499
+ // A signalled pause on a turn with no interruption closes paused first,
2500
+ // then the error closes on a new top-level turn (spec §8.0 host
2501
+ // obligation 1 and item 26).
2502
+ const asks = pendingAsks.get(turnId);
2503
+ if (asks !== undefined && pauseSignalled(turnId) && !interruptPending.has(turnId)) {
2504
+ closePaused(turnId, `msg_${turnId}`, asks);
2505
+ closeErrorTurn(turnId, { code: err.code, message: err.message }, err.usage);
2506
+ closed++;
2507
+ continue;
2508
+ }
1826
2509
  closedTurns.add(turnId);
1827
- const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
2510
+ // The turn closes with the host's code and message and its accumulated
2511
+ // usage plus any usage the host reports, which covers only work the
2512
+ // stream did not report (spec §8.0 host obligation 1 and item 35).
2513
+ const usage = sumUsage(mapUsage(usageByTurn.get(turnId)), err.usage);
1828
2514
  a.closeMessage(`msg_${turnId}`);
1829
2515
  a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
1830
2516
  closed++;
@@ -1841,12 +2527,87 @@ function createInnerAdkNormalizer(options, invokeStem) {
1841
2527
  ...(err.usage !== undefined ? { usage: err.usage } : {}),
1842
2528
  });
1843
2529
  }
2530
+ /** The part indexes whose text repeats a changed output rendering (see
2531
+ * drive()): skipped here and in the aggregate. */
2532
+ function skippedParts(event, parts) {
2533
+ const renderedOutput = changedOutputRendering(event.output);
2534
+ const skipped = new Set();
2535
+ if (renderedOutput !== undefined)
2536
+ parts.forEach((p, idx) => {
2537
+ if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput)
2538
+ skipped.add(idx);
2539
+ });
2540
+ return skipped;
2541
+ }
2542
+ /** An event's reading against the aggregate windows of a turn (the rules
2543
+ * are stated in drive()). */
2544
+ function readWindow(turnId, event, parts, skipped, isPartial) {
2545
+ const isTextPart = (p, idx) => !skipped.has(idx) &&
2546
+ p.thought !== true &&
2547
+ p.functionCall === undefined &&
2548
+ typeof p.text === "string" &&
2549
+ p.text.length > 0;
2550
+ const carriesText = parts.some(isTextPart);
2551
+ const relay = relayOf(event);
2552
+ const relayStream = relay === null ? null : relayStreamKey(relay.task, relay.stream);
2553
+ const ownKey = aggregateWindowKey(turnId, event, relayStream);
2554
+ const snapshot = !isPartial && relay !== null && relay.stream === "snapshot" ? relay : null;
2555
+ const restated = snapshot !== null ? snapshotWindows(streamedText, turnId, event, snapshot.task) : null;
2556
+ const candidates = isPartial
2557
+ ? []
2558
+ : restated !== null
2559
+ ? [...restated.artifacts, ...restated.status]
2560
+ : windowCandidates(streamedText, turnId, event, ownKey, relay, relayStream);
2561
+ const [onlyCandidate] = candidates;
2562
+ const readKey = !isPartial && candidates.length === 1 && onlyCandidate !== undefined ? onlyCandidate : ownKey;
2563
+ const alreadyStreamed = isPartial
2564
+ ? (streamedText.get(ownKey) ?? "")
2565
+ : restated !== null
2566
+ ? snapshotReading(restated.artifacts.map((key) => streamedText.get(key) ?? "").join(""), restated.status.map((key) => streamedText.get(key) ?? "").join(""), parts
2567
+ .filter(isTextPart)
2568
+ .map((p) => p.text ?? "")
2569
+ .join(""))
2570
+ : candidates.length === 1
2571
+ ? (streamedText.get(readKey) ?? "")
2572
+ : "";
2573
+ const matchesWindow = !isPartial && alreadyStreamed.length > 0 && carriesText;
2574
+ const eventText = matchesWindow
2575
+ ? parts
2576
+ .filter(isTextPart)
2577
+ .map((p) => p.text ?? "")
2578
+ .join("")
2579
+ : "";
2580
+ const suffixRepeat = matchesWindow && alreadyStreamed.endsWith(eventText);
2581
+ const isAggregate = matchesWindow &&
2582
+ (eventText.startsWith(alreadyStreamed) || alreadyStreamed.startsWith(eventText) || suffixRepeat);
2583
+ const aggregateText = isAggregate ? eventText : "";
2584
+ const suppressAggregateText = isAggregate && aggregateText.length > 0 && (alreadyStreamed.startsWith(aggregateText) || suffixRepeat);
2585
+ return { isTextPart, carriesText, ownKey, relay, relayStream, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText };
2586
+ }
2587
+ /** Whether an event after a success close only repeats the closed turn's
2588
+ * streamed text: ADK's aggregate after a message-less block chunk closed
2589
+ * the turn. It stays on that turn, where the window suppresses it, rather
2590
+ * than opening a new one. */
2591
+ function repeatsClosedTurn(turnId, event) {
2592
+ if (event.partial === true)
2593
+ return false;
2594
+ const { parts } = splitPayloadParts(event.content?.parts ?? []);
2595
+ if (parts.length === 0)
2596
+ return false;
2597
+ const skipped = skippedParts(event, parts);
2598
+ const reading = readWindow(turnId, event, parts, skipped, false);
2599
+ return (reading.suppressAggregateText &&
2600
+ parts.every((p, idx) => skipped.has(idx) || reading.isTextPart(p, idx) || (p.thought !== true && p.text === "")));
2601
+ }
1844
2602
  function drive(event, relayEchoOmitted = 0) {
1845
- const turnId = liveTurnFor(event);
2603
+ const turnId = liveTurnFor(event, relayEchoOmitted > 0);
1846
2604
  // ADK re-yields a bare `{interrupted}` after a message that carried both
1847
2605
  // turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
1848
2606
  // 2.1.0). For a generation the barge-in already closed, it adds nothing:
1849
2607
  // no new turn and no second terminal, so the facet emits nothing for it.
2608
+ // An event push() removed parts from is not that re-yield even when
2609
+ // nothing is left of it: its marker needs a turn, so it opens the next
2610
+ // generation as an event with content would.
1850
2611
  if (turnId === undefined)
1851
2612
  return;
1852
2613
  const messageId = ensureOpen(turnId);
@@ -1855,7 +2616,11 @@ function createInnerAdkNormalizer(options, invokeStem) {
1855
2616
  // into.
1856
2617
  if (relayEchoOmitted > 0)
1857
2618
  a.emitExt("google", "relay-echo-omitted", { parts: relayEchoOmitted });
1858
- const parts = event.content?.parts ?? [];
2619
+ // A part holding text beside a payload member, or two payload members, is
2620
+ // split before any reader below classifies it (see splitPayloadParts), so
2621
+ // its text joins the aggregate as text does and each payload member maps
2622
+ // through its own arm.
2623
+ const { parts, origin: nativeIndexOf } = splitPayloadParts(event.content?.parts ?? []);
1859
2624
  const isPartial = event.partial === true;
1860
2625
  // ADK renders an object `output` as the same event's text part, byte-equal
1861
2626
  // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
@@ -1863,13 +2628,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
1863
2628
  // repeat what the reduction removed, so that one part is skipped here and
1864
2629
  // in the aggregate below. Nothing else matches: not a string output, not
1865
2630
  // 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
- });
2631
+ const skipped = skippedParts(event, parts);
1873
2632
  // STREAMED-text citations carrier (audit M22): groundingMetadata is
1874
2633
  // EVENT-level, not per-part. A Gemini grounding response carries the full
1875
2634
  // grounded answer in a single (non-thought, non-function-call) text part, so
@@ -1899,16 +2658,43 @@ function createInnerAdkNormalizer(options, invokeStem) {
1899
2658
  return; // real id — resolved directly, not via this map
1900
2659
  nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
1901
2660
  });
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);
2661
+ // §8.3 — the aggregate suppression (§8.0 item 3). ADK re-yields a model
2662
+ // call's streamed text as one `partial: false` event: when the call closes,
2663
+ // in SSE before a non-text part in the same stream, and on the Live path
2664
+ // before a tool call, on a switch between thought and text, and on a
2665
+ // barge-in. The window holding the
2666
+ // text streamed so far is keyed per turn AND per source (author, branch,
2667
+ // node path, and for an event ADK's A2A relay forwards, the relayed stream:
2668
+ // one artifact, or the status messages; an absent value is its own key), so
2669
+ // interleaved streams never share one. Every non-partial event of the
2670
+ // source closes it, except the ones ADK yields between a call's chunks and
2671
+ // its re-yield, none of which carries text: a block chunk (no content, a
2672
+ // finishReason), a Live usage report or grounding record (no content and
2673
+ // nothing else a closing record carries: no errorCode, errorMessage,
2674
+ // finishReason, turnComplete, session-resumption update, goAway or state or
2675
+ // artifact delta, and for the usage report no interruption), a
2676
+ // transcription event, a `partial: false` event whose
2677
+ // parts are all non-text (a function call or media before the Interactions
2678
+ // route's re-yield), and a function response (progressive SSE runs a tool
2679
+ // mid-stream). A text event that closes the window is its re-yield when
2680
+ // one text starts with the other (equal; longer by text no chunk streamed,
2681
+ // whose tail renders; or shorter, a callback's replacement whose bytes
2682
+ // already streamed) or when the streamed text ends with its text (a later
2683
+ // call's re-yield after a call whose close never arrived, or ADK's
2684
+ // structured-output rewrite); any other text renders in full. An event
2685
+ // without a branch that finds no window under its own key (ADK's A2A relay
2686
+ // rebuilds its re-yield without one, and a failed call's in-band error
2687
+ // carries none) reads the open windows of the same turn, author and node
2688
+ // path: a re-yield matches only when exactly one is open, and a text-less
2689
+ // event that ends the match ends them all (a text with two or more
2690
+ // candidates closes none). A relayed stream is scoped by its A2A task. A
2691
+ // relayed artifact with no window of its own reads its task's status
2692
+ // window; a relayed Task or Message restates its task, so it is read, in
2693
+ // the order ADK renders a Task, against that task's artifact windows and
2694
+ // then its status window (snapshotReading), and closes them; and
2695
+ // the relaying agent's own failure event ends every relayed window of its
2696
+ // author and node path. An empty text part is not text.
2697
+ const { isTextPart, carriesText, ownKey, relay, relayStream, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText, } = readWindow(turnId, event, parts, skipped, isPartial);
1912
2698
  let residualTail = isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
1913
2699
  let accumulated = alreadyStreamed;
1914
2700
  parts.forEach((part, index) => {
@@ -1939,14 +2725,39 @@ function createInnerAdkNormalizer(options, invokeStem) {
1939
2725
  accumulated += part.text ?? "";
1940
2726
  return;
1941
2727
  }
1942
- const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, blockIds, index === citedPartIndex ? citations : undefined);
2728
+ const contributed = driveAdkPart(a, part, index, nativeIndexOf[index] ?? index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, blockIds, index === citedPartIndex ? citations : undefined);
1943
2729
  if (isPartial)
1944
2730
  accumulated += contributed;
1945
2731
  });
2732
+ const stateDelta = event.actions?.stateDelta;
2733
+ const artifactDelta = event.actions?.artifactDelta;
2734
+ // Two records ADK's Live aggregator yields on their own between a call's
2735
+ // chunks and its repeat: its usage report, and the grounding metadata of
2736
+ // a message with no parts (a barge-in's among them). One that also carries
2737
+ // anything that ends a call is neither, and closes the window.
2738
+ const endsNoCall = event.errorCode === undefined &&
2739
+ event.errorMessage === undefined &&
2740
+ event.turnComplete !== true &&
2741
+ !Object.hasOwn(event, "liveSessionResumptionUpdate") &&
2742
+ !Object.hasOwn(event, "goAway") &&
2743
+ !(isJsonObject(stateDelta) && Object.keys(stateDelta).length > 0) &&
2744
+ !(isJsonObject(artifactDelta) && Object.keys(artifactDelta).length > 0);
2745
+ const usageReportOnly = endsNoCall && event.interrupted !== true && event.usageMetadata?.responseTokenCount !== undefined;
2746
+ const groundingOnly = endsNoCall && event.groundingMetadata !== undefined;
2747
+ const keepsWindowOpen = !carriesText &&
2748
+ ((event.partial === undefined && parts.length === 0 && (event.finishReason !== undefined || usageReportOnly || groundingOnly)) ||
2749
+ event.inputTranscription !== undefined ||
2750
+ event.outputTranscription !== undefined ||
2751
+ (event.partial === false && parts.length > 0) ||
2752
+ (parts.length > 0 && parts.every((p) => p.functionResponse !== undefined)));
1946
2753
  if (isPartial)
1947
- streamedText.set(turnId, accumulated);
1948
- else if (isAggregate)
1949
- streamedText.delete(turnId);
2754
+ streamedText.set(ownKey, accumulated);
2755
+ else if (carriesText)
2756
+ for (const key of snapshot !== null ? candidates : [readKey])
2757
+ streamedText.delete(key);
2758
+ else if (!keepsWindowOpen)
2759
+ for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event, relay)])
2760
+ streamedText.delete(key);
1950
2761
  // Round-3 review finding (regression on finding b): the resend window's
1951
2762
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
1952
2763
  // (see the `ToolCallMintState` doc above) already clears each null-id
@@ -1962,7 +2773,13 @@ function createInnerAdkNormalizer(options, invokeStem) {
1962
2773
  // per-invoke.
1963
2774
  if (!isPartial)
1964
2775
  trackLongRunning(event, turnId);
1965
- driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
2776
+ const asksBefore = pendingAsks.get(turnId)?.length ?? 0;
2777
+ driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, closedTurns.has(turnId)); // standalone and content arms
2778
+ if ((pendingAsks.get(turnId)?.length ?? 0) > asksBefore) {
2779
+ const authors = askingAuthors.get(turnId) ?? new Set();
2780
+ authors.add(event.author);
2781
+ askingAuthors.set(turnId, authors);
2782
+ }
1966
2783
  // A turn gets ONE terminal: an interrupt on a turn that already closed
1967
2784
  // (a second barge-in, or one after a success close) adds none.
1968
2785
  if (event.interrupted === true && !closedTurns.has(turnId))
@@ -1972,6 +2789,8 @@ function createInnerAdkNormalizer(options, invokeStem) {
1972
2789
  awaitingReply.add(turnId);
1973
2790
  else if (hasModelOutput(event))
1974
2791
  awaitingReply.delete(turnId);
2792
+ // A non-relayed event's own window key is its source key.
2793
+ recordErrorAndUsage(event, turnId, isPartial, relayStream === null ? ownKey : aggregateWindowKey(turnId, event, null));
1975
2794
  maybeCloseTurn(event, turnId, messageId, isPartial);
1976
2795
  // The interrupted generation closes on its own turnComplete (its trailing
1977
2796
  // usageMetadata arrives before it), or at flush() / host completion.
@@ -2002,16 +2821,33 @@ function createInnerAdkNormalizer(options, invokeStem) {
2002
2821
  }
2003
2822
  /** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
2004
2823
  * 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) {
2824
+ * previous one. `undefined` for ADK's bare `{interrupted}` re-yield: the one
2825
+ * that directly follows a message carrying both turnComplete and
2826
+ * interrupted (utils/live_connection_utils.js yields that message's final
2827
+ * response, then the bare flag). Any other bare `{interrupted}` after a
2828
+ * barge-in closed the generation interrupts the next one. */
2829
+ function liveTurnFor(event, omittedParts = false) {
2008
2830
  const key = turnKey(event);
2009
2831
  const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
2832
+ const reyield = previousBothFlags.get(base) === true;
2833
+ previousBothFlags.set(base, event.turnComplete === true && event.interrupted === true);
2010
2834
  const g = generationOf.get(base) ?? 0;
2011
2835
  const current = g === 0 ? base : `${base}_g${g}`;
2012
- if (!interruptClosed.has(current))
2836
+ // Any event after a success close opens the next generation, so no
2837
+ // message or block event names the closed turn (SPEC :959): content, a
2838
+ // usage report, a carry, an interruption. An `{interrupted}` after a
2839
+ // success close interrupts the next generation, which then closes
2840
+ // turn.abort interrupted; ADK's bare re-yield after a message carrying
2841
+ // both flags follows an interrupt close, handled below. Two stay: an event
2842
+ // whose only mapping is the state.delta of its stateDelta (shared state,
2843
+ // not the turn's content), and an aggregate that only repeats the closed
2844
+ // turn's streamed text (the window suppresses it).
2845
+ const afterSuccess = successClosed.has(current) &&
2846
+ !onlyStateChange(event) &&
2847
+ !repeatsClosedTurn(current, event);
2848
+ if (!interruptClosed.has(current) && !afterSuccess)
2013
2849
  return current;
2014
- if (event.interrupted === true && !hasLiveContent(event))
2850
+ if (!afterSuccess && reyield && event.interrupted === true && !hasLiveContent(event) && !omittedParts)
2015
2851
  return undefined;
2016
2852
  generationOf.set(base, g + 1);
2017
2853
  return `${base}_g${g + 1}`;
@@ -2066,7 +2902,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
2066
2902
  omitted = stripped.omitted;
2067
2903
  }
2068
2904
  if (!isAdkEvent(event)) {
2069
- a.emitExt("google", "unparsed", { native: nativeWithoutRelayBookkeeping(event) });
2905
+ a.emitExt("google", "unparsed", { native: nativeWithCarriedMetadata(event) });
2070
2906
  return a.drain();
2071
2907
  }
2072
2908
  drive(event, omitted);
@@ -2086,7 +2922,7 @@ function createInnerAdkNormalizer(options, invokeStem) {
2086
2922
  // Workflow invoke until the host completion signal exists, still reports
2087
2923
  // the tokens it spent. There is never a turn.done here, so the usage
2088
2924
  // appears only once.
2089
- for (const turnId of openTurns) {
2925
+ for (const turnId of [...openTurns]) {
2090
2926
  if (closedTurns.has(turnId))
2091
2927
  continue;
2092
2928
  if (interruptPending.has(turnId)) {
@@ -2095,11 +2931,21 @@ function createInnerAdkNormalizer(options, invokeStem) {
2095
2931
  }
2096
2932
  // A pause the stream saw end (its pause-end event, or a final response
2097
2933
  // 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.
2934
+ // closes paused here (SPEC §8.0 item 26), and an in-band error of its
2935
+ // invocation then closes on its own turn. Asks with neither stay a
2936
+ // truncation, as above, unless the invocation met an in-band error:
2937
+ // that turn, like any other of such an invocation, closes turn.error
2938
+ // (spec §8.0 item 35, INV-FLUSH (2)).
2100
2939
  const asks = pendingAsks.get(turnId);
2101
- if (asks !== undefined && asks.length > 0 && (pauseEnded.has(turnId) || deferredClose.has(turnId))) {
2940
+ const error = firstInBandError.get(turnId);
2941
+ if (asks !== undefined && pauseSignalled(turnId)) {
2102
2942
  closePaused(turnId, `msg_${turnId}`, asks);
2943
+ if (error !== undefined)
2944
+ closeErrorTurn(turnId, error, undefined);
2945
+ continue;
2946
+ }
2947
+ if (error !== undefined) {
2948
+ closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
2103
2949
  continue;
2104
2950
  }
2105
2951
  closedTurns.add(turnId);