@silverprotocol/google-adk 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -49,30 +49,39 @@
49
49
  * `function_call`); a runtime adapter would map those before this seam. This
50
50
  * fixture contract is the camelCase wire projection.
51
51
  *
52
- * NOTE on turn ids across invokes: google-adk derives turn ids from ADK's
53
- * `invocationId`, which ADK-JS mints fresh on every `runAsync` (including a
54
- * resume), so they don't repeat across the invokes of a fold. ADK-Python's
55
- * resumable resume reuses `invocation_id`, and this facet also accepts events
56
- * serialized from Python: fed that resume, it would repeat `turn_${invocationId}`
57
- * (and the message id derived from it) across the fold. Supporting that path
58
- * needs a per-invoke stem, which this release does not have.
52
+ * NOTE on turn ids across invokes: a turn id is `turn_<invokeId>_<invocationId>`,
53
+ * and its message id `msg_<turnId>`. ADK's `invocationId` alone is not unique
54
+ * across the invokes a host folds together: ADK-JS mints a fresh one on every
55
+ * `runAsync`, but ADK-Python's resumable resume reuses `invocation_id`, and this
56
+ * facet also accepts events serialized from Python (SPEC §8.0 "Ids across
57
+ * invokes": a resumed-invocation id never satisfies the rule). The per-invoke
58
+ * stem makes the ids unique; see {@link AdkNormalizerOptions.invokeId}.
59
59
  *
60
- * NOTE on the Live (bidi) path: a barge-in (`interrupted: true`, from ADK's live
61
- * aggregator) closes the message, then the turn, as `turn.abort{interrupted}`,
62
- * after the event's own content, and a turn gets one terminal. That does NOT
63
- * make a real barge-in session fold. One live session is one ADK invocation,
64
- * and so one turn here, and ADK delivers the flag first: the interrupted
65
- * generation's own `usageMetadata` and `turnComplete` follow it, then the
66
- * reply generation. Those events land in the closed turn until the facet opens
67
- * a turn per generation, and a reducer parks on them (probe's gemini-3.8-live
68
- * capture `live-bargein-gemini38live`, @google/adk 2.1.0: the interrupt at
69
- * native 6, then usage, turnComplete and the reply). A second barge-in, or
70
- * model content after a completed reply closed the turn (unless
71
- * `hostCompletion` defers that close), parks the same way. Separately, when
72
- * text is buffered at the interrupt, ADK yields
73
- * only the text aggregate, without the flag (utils/live_connection_utils.js,
74
- * @google/adk 2.1.0), so this facet sees no interrupt and the turn closes at
75
- * flush as `stream-truncated`.
60
+ * NOTE on the Live (bidi) path: one live session is one ADK invocation, and it
61
+ * can hold several model generations. ADK delivers a barge-in's flag
62
+ * (`interrupted: true`) first, then the interrupted generation's own
63
+ * `usageMetadata` and `turnComplete`, then the reply generation (a
64
+ * gemini-3.8-live capture `live-bargein-gemini38live`, @google/adk 2.1.0). So
65
+ * the interrupted generation closes as `turn.abort{interrupted}` on its own
66
+ * `turnComplete` (or at flush), with its usage on its message.end, and the next
67
+ * generation opens a new turn, `turn_<invokeId>_<invocationId>_g<n>`. That
68
+ * relies on the wire's order, where a generation's usage and turnComplete
69
+ * arrive before the next generation's first event. An event that arrived after
70
+ * the interrupted generation closed, even a usage-only one, would open the next
71
+ * turn early and carry its usage there; the capture shows no such event. ADK's
72
+ * bare `{interrupted}` re-yield, after a message that carried both flags, adds
73
+ * nothing and is not emitted, and neither is ADK's `finished` transcription
74
+ * when it repeats the chunks already streamed for the turn. A tool call and
75
+ * the model's reply share one turn: ADK yields the call generation's
76
+ * turnComplete after the function response and before the reply (a
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
83
+ * aggregate, without the flag (utils/live_connection_utils.js), so this facet
84
+ * sees no interrupt and the turn closes at flush as `stream-truncated`.
76
85
  */
77
86
  import {
78
87
  type AgEvent,
@@ -85,6 +94,7 @@ import {
85
94
  type AgSafety,
86
95
  AgUsage,
87
96
  AgProviderMeta,
97
+ AgResourceLinkBlock,
88
98
  JsonValue,
89
99
  type Normalizer,
90
100
  StreamAssembler,
@@ -250,7 +260,9 @@ export interface AdkEvent {
250
260
  skipSummarization?: boolean;
251
261
  /** Transfer control to another named agent. */
252
262
  transferToAgent?: string;
253
- /** Escalate to a human or supervisor. */
263
+ /** "The agent is escalating to a higher level agent" (ADK's declaration,
264
+ * events/event_actions.d.ts): the exit_loop tool sets it, and a LoopAgent
265
+ * stops iterating on it. */
254
266
  escalate?: boolean;
255
267
  /** Request OAuth/auth configs from the caller. ADK serializes this as a
256
268
  * dict keyed by the function-call-id (`dict[str, AuthConfig]`); the value
@@ -292,6 +304,11 @@ export interface AdkEvent {
292
304
  cachedContentTokenCount?: number;
293
305
  thoughtsTokenCount?: number;
294
306
  toolUsePromptTokenCount?: number;
307
+ /** Gemini Live's output counter, in place of `candidatesTokenCount`. */
308
+ responseTokenCount?: number;
309
+ /** Per-modality token counts (carried verbatim on the Live path only). */
310
+ promptTokensDetails?: JsonValue;
311
+ responseTokensDetails?: JsonValue;
295
312
  };
296
313
  /** Per-part safety ratings from the Gemini Candidate. */
297
314
  safetyRatings?: Array<{
@@ -338,9 +355,9 @@ export interface AdkEvent {
338
355
  /** ISO timestamp of the event. */
339
356
  timestamp?: string;
340
357
  /** Speech-to-text transcription of the user's audio input. */
341
- inputTranscription?: { text?: string };
358
+ inputTranscription?: { text?: string; finished?: boolean };
342
359
  /** Text-to-speech transcription of the model's audio output. */
343
- outputTranscription?: { text?: string };
360
+ outputTranscription?: { text?: string; finished?: boolean };
344
361
  /** Opaque per-event custom metadata bag. */
345
362
  customMetadata?: { [k: string]: JsonValue };
346
363
  /** Index of the candidate response (meaningful when the request's
@@ -509,7 +526,16 @@ function isAdkEvent(v: unknown): v is AdkEvent {
509
526
  * inclusive on that endpoint — carry it as-is, never add twice. A thoughts-free
510
527
  * usageMetadata normalizes byte-identically to draft.2. `reasoningTokens` stays
511
528
  * the breakdown (`thoughtsTokenCount` verbatim); `totalTokens` is copied, never
512
- * computed. Known upstream gap: @google/adk's Interactions-API route synthesizes
529
+ * computed, with ONE exception, the Gemini Live API (draft.5): Live reports its
530
+ * output as `responseTokenCount`, and its `totalTokenCount` may leave thoughts
531
+ * out (609 + 25 = 634 with 256 thoughts beside them), so thoughts always fold
532
+ * into outputTokens there. Where Live reports a total, `totalTokens` is
533
+ * derived as input + output + toolUseInput over the turn's summed counters,
534
+ * and Google's own summed total rides `totalTokensRaw` only where it differs;
535
+ * with no reported total, neither is emitted. This facet recognises the Live
536
+ * API by the field: `responseTokenCount` appears only on @google/genai's Live
537
+ * UsageMetadata. A normalizer reading the raw Vertex Live wire decides by the
538
+ * API, not by the field name. Known upstream gap: @google/adk's Interactions-API route synthesizes
513
539
  * usageMetadata WITHOUT thoughts (candidates = total_output_tokens, total =
514
540
  * in + out), so on that route outputTokens is exclusive and reasoningTokens
515
541
  * absent — nothing the facet can recover (see README).
@@ -521,7 +547,15 @@ function mapUsage(um: AdkEvent["usageMetadata"]): AgUsage | undefined {
521
547
  if (um === undefined) return undefined;
522
548
  const candidates = um.candidatesTokenCount;
523
549
  const thoughts = um.thoughtsTokenCount;
550
+ // Gemini Live reports its output as `responseTokenCount`, and its total is
551
+ // prompt + response, EXCLUDING thoughts (the capture
552
+ // live-bargein-gemini38live: 609 + 25 = 634, with 256 thoughts beside them).
553
+ // So on Live the total cannot show whether thoughts are included, and they
554
+ // always fold in: outputTokens = response + thoughts (SPEC §4 inclusion).
555
+ const response = candidates === undefined ? um.responseTokenCount : undefined;
556
+ const generated = candidates ?? response;
524
557
  const alreadyInclusive =
558
+ response === undefined &&
525
559
  candidates !== undefined &&
526
560
  thoughts !== undefined &&
527
561
  thoughts > 0 &&
@@ -529,15 +563,26 @@ function mapUsage(um: AdkEvent["usageMetadata"]): AgUsage | undefined {
529
563
  um.promptTokenCount !== undefined &&
530
564
  um.promptTokenCount + (candidates ?? 0) + (um.toolUsePromptTokenCount ?? 0) === um.totalTokenCount;
531
565
  const outputTokens =
532
- candidates === undefined && thoughts === undefined
566
+ generated === undefined && thoughts === undefined
533
567
  ? undefined
534
568
  : alreadyInclusive
535
569
  ? candidates
536
- : (candidates ?? 0) + (thoughts ?? 0);
570
+ : (generated ?? 0) + (thoughts ?? 0);
571
+ // On the Live path the total is derived, and Google's figure is kept beside
572
+ // it only where it differs; elsewhere the provider's total is copied.
573
+ const totalTokens =
574
+ response !== undefined && um.totalTokenCount !== undefined
575
+ ? (um.promptTokenCount ?? 0) + (outputTokens ?? 0) + (um.toolUsePromptTokenCount ?? 0)
576
+ : um.totalTokenCount;
577
+ const totalTokensRaw =
578
+ response !== undefined && um.totalTokenCount !== undefined && um.totalTokenCount !== totalTokens
579
+ ? um.totalTokenCount
580
+ : undefined;
537
581
  return {
538
582
  ...(um.promptTokenCount !== undefined ? { inputTokens: um.promptTokenCount } : {}),
539
583
  ...(outputTokens !== undefined ? { outputTokens } : {}),
540
- ...(um.totalTokenCount !== undefined ? { totalTokens: um.totalTokenCount } : {}),
584
+ ...(totalTokens !== undefined ? { totalTokens } : {}),
585
+ ...(totalTokensRaw !== undefined ? { totalTokensRaw } : {}),
541
586
  ...(um.cachedContentTokenCount !== undefined
542
587
  ? { cacheReadTokens: um.cachedContentTokenCount }
543
588
  : {}),
@@ -558,6 +603,7 @@ const USAGE_SUM_FIELDS = [
558
603
  "cachedContentTokenCount",
559
604
  "thoughtsTokenCount",
560
605
  "toolUsePromptTokenCount",
606
+ "responseTokenCount",
561
607
  ] as const;
562
608
 
563
609
  /** Fold one event's usageMetadata into a turn's running accumulator
@@ -790,9 +836,24 @@ function isAdkPauseEnd(event: AdkEvent): boolean {
790
836
  );
791
837
  }
792
838
 
839
+ /** Whether an event carries any content of a generation: a part, or an input
840
+ * or output transcription. */
841
+ function hasLiveContent(ev: AdkEvent): boolean {
842
+ return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
843
+ }
844
+
845
+ /** Whether an event carries model output: a part of `model`-role content, or
846
+ * output-transcription text. ADK's function response is `user`-role. */
847
+ function hasModelOutput(ev: AdkEvent): boolean {
848
+ if (ev.content?.role === "model" && (ev.content.parts?.length ?? 0) > 0) return true;
849
+ const transcribed = ev.outputTranscription?.text;
850
+ return typeof transcribed === "string" && transcribed.length > 0;
851
+ }
852
+
793
853
  /** The event's own turn key: its invocationId, else its id. `undefined` when it
794
- * has neither; the normalizer then names the turn from its per-instance stem,
795
- * never a constant that would repeat across the invokes a host folds together. */
854
+ * has neither; the turn is then named from the per-invoke stem alone. The key
855
+ * is never a turn id by itself: ADK-Python's resumable resume reuses
856
+ * `invocation_id`, so every turn id carries the per-invoke stem too. */
796
857
  function turnKey(ev: AdkEvent): string | undefined {
797
858
  if (ev.invocationId && ev.invocationId.length > 0) return ev.invocationId;
798
859
  return ev.id !== undefined && ev.id !== null && ev.id.length > 0 ? ev.id : undefined;
@@ -805,7 +866,7 @@ function turnKey(ev: AdkEvent): string | undefined {
805
866
  // restore name+position correlation when echoing functionResponse parts.
806
867
 
807
868
  // ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
808
- // adk-10, founder-ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
869
+ // adk-10, ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
809
870
  // answers a failed tool call with a response carrying Gemini's documented
810
871
  // `error` key: an unresolvable tool name (functions.js:264), a thrown tool
811
872
  // including a thrown MCP call (functions.js:282), several built-in tools.
@@ -896,6 +957,87 @@ interface FunctionResponseToolDoneFields {
896
957
  structuredContent?: JsonValue;
897
958
  _meta?: AgMeta;
898
959
  }
960
+ /** Sorted-key JSON: "does parsing change this value" compares members, not
961
+ * the order a schema writes them in. */
962
+ function canonicalJson(v: JsonValue): string {
963
+ if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;
964
+ if (!isJsonObject(v)) return JSON.stringify(v);
965
+ return `{${Object.keys(v)
966
+ .sort()
967
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
968
+ .join(",")}}`;
969
+ }
970
+
971
+ /** A native member that fits the resource-link block: core's own schema for
972
+ * that member accepts it AND leaves it unchanged, so the block carries it
973
+ * verbatim. `undefined` when it does not fit (it then rides the residual). */
974
+ function fitMember<T>(
975
+ parse: (v: unknown) => { success: true; data: T } | { success: false },
976
+ v: JsonValue | undefined,
977
+ ): T | undefined {
978
+ if (v === undefined) return undefined;
979
+ const r = parse(v);
980
+ if (!r.success || r.data === undefined) return undefined;
981
+ const back = JsonValue.safeParse(r.data);
982
+ return back.success && canonicalJson(back.data) === canonicalJson(v) ? r.data : undefined;
983
+ }
984
+
985
+ const RESOURCE_LINK_MEMBERS: ReadonlySet<string> = new Set(["name", "title", "description", "mimeType", "size", "annotations", "_meta"]);
986
+
987
+ /**
988
+ * SPEC §8.0 item 31 (draft.5): an MCP `resource_link` content part of a tool
989
+ * result becomes ONE `resource-link` block carrying its native `uri`, `name`,
990
+ * `title`, `description`, `mimeType`, `size`, `annotations` and `_meta`
991
+ * verbatim where present, after item 28's reductions (applied as for a
992
+ * provider-raw carry; a `uri` is neither a credential object nor a
993
+ * credential-request response, so it passes unchanged, signed query included).
994
+ * The members the block cannot hold (a member it does not define, such as
995
+ * `icons`, or a defined one whose native value core's schema rejects or would
996
+ * alter) ride exactly one provider-raw block right after it, carrying only
997
+ * those members; with none, no such block is emitted.
998
+ *
999
+ * Item 31 binds MCP-schema-valid `resource_link` parts. A part without a string
1000
+ * `uri` fails MCP's own schema (uri is required): it is an unmappable part, so
1001
+ * §8.0's graceful degradation applies, and it stays one reduced provider-raw
1002
+ * (`undefined` here), never dropped and never forced into a uri-less block.
1003
+ */
1004
+ function resourceLinkBlocks(part: { readonly [k: string]: JsonValue }): AgBlock[] | undefined {
1005
+ const reduced = reduceCarried(part);
1006
+ if (!isJsonObject(reduced) || typeof reduced["uri"] !== "string") return undefined;
1007
+ const S = AgResourceLinkBlock.shape;
1008
+ const name = fitMember((v) => S.name.safeParse(v), reduced["name"]);
1009
+ const title = fitMember((v) => S.title.safeParse(v), reduced["title"]);
1010
+ const description = fitMember((v) => S.description.safeParse(v), reduced["description"]);
1011
+ const mimeType = fitMember((v) => S.mimeType.safeParse(v), reduced["mimeType"]);
1012
+ const size = fitMember((v) => S.size.safeParse(v), reduced["size"]);
1013
+ const annotations = fitMember((v) => S.annotations.safeParse(v), reduced["annotations"]);
1014
+ const meta = fitMember((v) => S._meta.safeParse(v), reduced["_meta"]);
1015
+ const fitted: { readonly [k: string]: boolean } = {
1016
+ name: name !== undefined,
1017
+ title: title !== undefined,
1018
+ description: description !== undefined,
1019
+ mimeType: mimeType !== undefined,
1020
+ size: size !== undefined,
1021
+ annotations: annotations !== undefined,
1022
+ _meta: meta !== undefined,
1023
+ };
1024
+ const block: AgBlock = {
1025
+ type: "resource-link",
1026
+ uri: reduced["uri"],
1027
+ ...(name !== undefined ? { name } : {}),
1028
+ ...(title !== undefined ? { title } : {}),
1029
+ ...(description !== undefined ? { description } : {}),
1030
+ ...(mimeType !== undefined ? { mimeType } : {}),
1031
+ ...(size !== undefined ? { size } : {}),
1032
+ ...(annotations !== undefined ? { annotations } : {}),
1033
+ ...(meta !== undefined ? { _meta: meta } : {}),
1034
+ };
1035
+ const residual = Object.fromEntries(
1036
+ Object.entries(reduced).filter(([k]) => k !== "type" && k !== "uri" && !(RESOURCE_LINK_MEMBERS.has(k) && fitted[k] === true)),
1037
+ );
1038
+ return Object.keys(residual).length > 0 ? [block, { type: "provider-raw", vendor: "google", raw: residual }] : [block];
1039
+ }
1040
+
899
1041
  function functionResponseToToolDoneFields(
900
1042
  name: string,
901
1043
  response: { [k: string]: JsonValue } | undefined,
@@ -912,8 +1054,17 @@ function functionResponseToToolDoneFields(
912
1054
  out.push({ type: "text", text: part["text"] });
913
1055
  continue;
914
1056
  }
1057
+ if (t === "resource_link") {
1058
+ const link = resourceLinkBlocks(part);
1059
+ if (link !== undefined) {
1060
+ out.push(...link);
1061
+ continue;
1062
+ }
1063
+ }
915
1064
  }
916
- // Preserve any non-text MCP content part losslessly as a provider-raw block.
1065
+ // Preserve any other non-text MCP content part losslessly as a provider-raw
1066
+ // block (image, audio and embedded resource parts; a resource_link that
1067
+ // is not MCP-schema-valid, see resourceLinkBlocks).
917
1068
  out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
918
1069
  }
919
1070
  const meta = response["_meta"];
@@ -1449,22 +1600,33 @@ function driveAdkTopLevel(
1449
1600
  messageId: string,
1450
1601
  turnId: string,
1451
1602
  pendingAsks: Map<string, AgPausedAsk[]>,
1452
- reserved: ReservedAskState
1603
+ reserved: ReservedAskState,
1604
+ streamedTranscription: Map<string, string>
1453
1605
  ): void {
1606
+ // Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
1607
+ // a `finished: true` transcription whose text is the chunks joined
1608
+ // (utils/live_connection_utils.js, @google/adk 2.1.0). That aggregate is not
1609
+ // re-emitted when it repeats this turn's streamed chunks exactly, so the
1610
+ // turn's transcription reads once; one that differs rides as its own block.
1454
1611
  // typeof: a JSON-null transcription text is absent (null guard; it rode the
1455
1612
  // text block as `null`, which the schema rejects).
1456
- if (typeof event.inputTranscription?.text === "string") {
1457
- a.contentBlock(messageId, {
1458
- type: "text",
1459
- text: event.inputTranscription.text,
1460
- _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
1461
- });
1462
- }
1463
- if (typeof event.outputTranscription?.text === "string") {
1613
+ for (const [role, t] of [
1614
+ ["input", event.inputTranscription],
1615
+ ["output", event.outputTranscription],
1616
+ ] as const) {
1617
+ if (typeof t?.text !== "string") continue;
1618
+ const key = `${turnId}\u0000${role}`;
1619
+ if (t.finished === true) {
1620
+ const streamed = streamedTranscription.get(key);
1621
+ streamedTranscription.delete(key);
1622
+ if (streamed === t.text) continue;
1623
+ } else {
1624
+ streamedTranscription.set(key, (streamedTranscription.get(key) ?? "") + t.text);
1625
+ }
1464
1626
  a.contentBlock(messageId, {
1465
1627
  type: "text",
1466
- text: event.outputTranscription.text,
1467
- _meta: { "agjson/transcription": { role: "output", kind: "transcription" } },
1628
+ text: t.text,
1629
+ _meta: { "agjson/transcription": { role, kind: "transcription" } },
1468
1630
  });
1469
1631
  }
1470
1632
 
@@ -1719,6 +1881,35 @@ export interface AdkNormalizerOptions {
1719
1881
  * else `success`. Default off: the step-1 behaviour.
1720
1882
  */
1721
1883
  hostCompletion?: boolean;
1884
+ /**
1885
+ * The host's thread id (SPEC §1.2, the partition root), stamped on every
1886
+ * `turn.start` and assistant `message.start` of this invoke. An ADK `Event`
1887
+ * carries no thread or session id, so without it the facet stamps the fixed
1888
+ * label `"google"`, a facet-local placeholder, not a partition root. A host
1889
+ * that persists by `threadId` supplies its own.
1890
+ */
1891
+ threadId?: string;
1892
+ /**
1893
+ * The stem this invoke's ids are minted from: a turn id is
1894
+ * `turn_<invokeId>_<key>`, where `<key>` is the event's `invocationId`, else
1895
+ * its `id`; an event with neither is `turn_<invokeId>`, and a host error with
1896
+ * no turn open is `turn_<invokeId>_host_error_<n>`. On the Live path, the
1897
+ * n-th generation after a barge-in adds `_g<n>`. Message ids are
1898
+ * `msg_<turnId>`.
1899
+ *
1900
+ * Turn and message ids must be unique across every invoke folded into one
1901
+ * reducer (SPEC §8.0 "Ids across invokes"; a repeated turn id re-opens a
1902
+ * closed turn, which INV-MSG parks). ADK's `invocationId` is not enough on its
1903
+ * own: ADK-Python's resumable resume reuses it. By default each normalizer
1904
+ * draws a fresh `adk_<16 hex>` stem from `crypto.getRandomValues`, ONCE, at
1905
+ * construction and outside the atomic inner factory, so a `withAtomicPush`
1906
+ * rebuild mints the SAME ids.
1907
+ *
1908
+ * Pass one to make the output deterministic (replay, capture, tests). A host
1909
+ * that passes one MUST keep it unique per invoke within a fold. This mirrors
1910
+ * the vercel, openai and claude facets' `invokeId`.
1911
+ */
1912
+ invokeId?: string;
1722
1913
  }
1723
1914
 
1724
1915
  /** The facet-local host-completion native (§8.0 host obligation 4). */
@@ -1739,9 +1930,6 @@ interface AdkHostError {
1739
1930
  code: string;
1740
1931
  message: string;
1741
1932
  usage?: AgUsage;
1742
- /** The invoke's ADK invocationId, when the host has it: used to name a
1743
- * fresh terminal turn if the error arrives before any event. */
1744
- invocationId?: string;
1745
1933
  }
1746
1934
 
1747
1935
  /** The host-error sentinel, read from the RAW native (an Error's message is
@@ -1756,12 +1944,10 @@ function hostErrorOf(raw: unknown): AdkHostError | undefined {
1756
1944
  if (typeof code !== "string" || typeof message !== "string") return undefined;
1757
1945
  const usageRaw: unknown = Reflect.get(raw, "usage");
1758
1946
  const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
1759
- const invocationId: unknown = Reflect.get(raw, "invocationId");
1760
1947
  return {
1761
1948
  code,
1762
1949
  message,
1763
1950
  ...(usage?.success === true ? { usage: usage.data } : {}),
1764
- ...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
1765
1951
  };
1766
1952
  } catch {
1767
1953
  return undefined;
@@ -1775,7 +1961,7 @@ function isHostCompleteNative(v: JsonValue): boolean {
1775
1961
 
1776
1962
  /**
1777
1963
  * The google-adk Normalizer: the inner, deterministic normalizer below wrapped
1778
- * in core's withAtomicPush (the fleet guard ruling). Every push() is atomic:
1964
+ * in core's withAtomicPush (the guard ruling). Every push() is atomic:
1779
1965
  * - The native is read once as plain JSON through core's toJsonValueSafe, so a
1780
1966
  * host may push the live Event objects ADK yields (undefined members, a
1781
1967
  * Date, an Error, a cycle) and they map exactly like the recorded corpus.
@@ -1783,8 +1969,8 @@ function isHostCompleteNative(v: JsonValue): boolean {
1783
1969
  * inner members have unexpected types), its partial batch is discarded
1784
1970
  * without consuming seq, the inner is rebuilt by re-driving every native
1785
1971
  * accepted so far (the inner never reads the clock or randomness; ids come
1786
- * from invocationId and per-invoke ordinals, and the one random stem, for a
1787
- * host error before any event, is drawn outside the inner and kept), and
1972
+ * from the per-invoke stem, invocationId and per-invoke ordinals, and the
1973
+ * stem is drawn once, outside the inner, and kept), and
1788
1974
  * ONE core `error {message:
1789
1975
  * "normalizer error", code: <constructor name>}` takes the next seq, with no
1790
1976
  * payload and no message text.
@@ -1794,44 +1980,30 @@ function isHostCompleteNative(v: JsonValue): boolean {
1794
1980
  * message or block is open that never reached the wire.
1795
1981
  */
1796
1982
  export function createAdkNormalizer(options: AdkNormalizerOptions = {}): Normalizer {
1797
- // A per-instance id stem, drawn lazily and only on the paths that need it (an
1798
- // event with neither invocationId nor id; a host error before any event,
1799
- // with no invocationId on the sentinel). It lives OUTSIDE the inner, so a
1800
- // rebuild re-drives to the same ids.
1801
- const stem: IdStem = {};
1802
- return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
1983
+ // The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
1984
+ // re-drives to the same ids and no push() reads randomness.
1985
+ const invokeStem = options.invokeId ?? `adk_${mintInvokeNonce()}`;
1986
+ return withAtomicPush(() => createInnerAdkNormalizer(options, invokeStem));
1803
1987
  }
1804
1988
 
1805
- /** Holds the lazily drawn per-instance id stem across inner rebuilds. */
1806
- interface IdStem {
1807
- value?: string;
1989
+ /** 64 random bits as 16 hex chars: the default per-invoke id stem (as the
1990
+ * vercel, openai and claude facets draw theirs). */
1991
+ function mintInvokeNonce(): string {
1992
+ const bytes = new Uint8Array(8);
1993
+ globalThis.crypto.getRandomValues(bytes);
1994
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1808
1995
  }
1809
1996
 
1810
- /** A random per-instance stem; never called while a replay re-drives, since
1811
- * the stem is drawn once and kept.
1812
- *
1813
- * The `Date.now` + `Math.random` fallback runs only when `crypto.randomUUID`
1814
- * is absent, which cannot happen on Node >= 19 (a global `crypto`). It is the
1815
- * facet's one read of the clock or a random source, and it is safe for
1816
- * determinism: the stem is drawn outside the inner, once, and a
1817
- * withAtomicPush rebuild reuses it, so the corpus legs that poison the clock
1818
- * and randomness never reach this call. */
1819
- function drawIdStem(): string {
1820
- const cryptoObj: unknown = Reflect.get(globalThis, "crypto");
1821
- const randomUUID: unknown = cryptoObj !== undefined && cryptoObj !== null ? Reflect.get(cryptoObj, "randomUUID") : undefined;
1822
- if (typeof randomUUID === "function") {
1823
- const id: unknown = Reflect.apply(randomUUID, cryptoObj, []);
1824
- if (typeof id === "string") return id;
1825
- }
1826
- return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1827
- }
1828
-
1829
- function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem): Normalizer {
1997
+ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: string): Normalizer {
1830
1998
  const hostCompletion = options.hostCompletion === true;
1831
1999
  const a = new StreamAssembler();
1832
- const threadId = "google";
2000
+ const threadId = options.threadId ?? "google";
1833
2001
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
1834
2002
  const streamedText = new Map<string, string>();
2003
+ // Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
2004
+ const streamedTranscription = new Map<string, string>();
2005
+ // Per turn: the Live usage reports' modality details, one entry per report.
2006
+ const usageDetailsByTurn = new Map<string, JsonValue[]>();
1835
2007
  const openTurns = new Set<string>();
1836
2008
  const closedTurns = new Set<string>();
1837
2009
  // Per-turn usageMetadata accumulator (2026-07-13, echo-gemini35 live-capture
@@ -1864,6 +2036,21 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
1864
2036
  // so the close waits for the next non-partial event of the turn, or for
1865
2037
  // flush() / host completion.
1866
2038
  const interruptPending = new Set<string>();
2039
+ // Live generations. One live session is one ADK invocation, so one turn key
2040
+ // spans every model generation of the session. ADK delivers a barge-in's
2041
+ // flag FIRST, then the interrupted generation's own usageMetadata and
2042
+ // turnComplete, then the reply generation (a gemini-3.8-live capture
2043
+ // `live-bargein-gemini38live`). So an interrupted generation closes on its own
2044
+ // turnComplete (closeInterrupted), and the next generation after a barge-in
2045
+ // opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
2046
+ const generationOf = new Map<string, number>();
2047
+ const interruptClosed = new Set<string>();
2048
+ // Turns whose last function response has no model output after it yet. On
2049
+ // the Live path the model always answers a tool result with a reply
2050
+ // generation, and ADK can yield the call generation's turnComplete between
2051
+ // the response and that reply (a gemini-3.8-live capture,
2052
+ // `live-tool-gemini38live`), so that turnComplete does not end the turn.
2053
+ const awaitingReply = new Set<string>();
1867
2054
  const pendingLongRunning = new Map<string, Set<string>>();
1868
2055
  const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
1869
2056
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
@@ -1911,6 +2098,16 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
1911
2098
  // before, their close never fired and the turn flushed as an abort.
1912
2099
  const pending = pendingAsks.get(turnId);
1913
2100
  if (!interrupted && pending !== undefined && pending.length > 0 && isAdkPauseEnd(event)) {
2101
+ // With the host-completion opt-in, the paused close waits for the
2102
+ // host-completion event (item 26: "at the latest, on the host-completion
2103
+ // event"; hostComplete() closes a turn whose asks are pending as paused).
2104
+ // ADK ends the invocation at a confirmation but not at a credential
2105
+ // request or a request-input call, so an ADK event can follow the pause
2106
+ // end in the same invocation and carry state and content: the model run
2107
+ // again when its stream ended with a usage-only chunk
2108
+ // (agents/llm_agent.js:458), an after-agent callback, the next sub-agent
2109
+ // of a SequentialAgent root. Without the opt-in the close stays here.
2110
+ if (hostCompletion) return;
1914
2111
  closedTurns.add(turnId);
1915
2112
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1916
2113
  a.closeMessage(messageId);
@@ -1927,6 +2124,9 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
1927
2124
  event.errorCode !== undefined;
1928
2125
  // is_final_response: a non-partial event with no pending function call and not interrupted.
1929
2126
  if (hasFunctionCall || interrupted || !hasCompletion) return;
2127
+ // A bare Live turnComplete between a function response and the model's
2128
+ // reply ends the call generation, not the turn (see awaitingReply).
2129
+ if (event.finishReason === undefined && event.errorCode === undefined && awaitingReply.has(turnId)) return;
1930
2130
  // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
1931
2131
  // present ⇒ turn.error (values captured here so the close below needs no
1932
2132
  // re-narrowing).
@@ -1945,12 +2145,13 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
1945
2145
  // event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
1946
2146
  // it flushes turn.abort.
1947
2147
  if (errorClose === undefined && event.nodeInfo !== undefined) return;
1948
- // Host obligation 4 (opt-in): a SUCCESS close waits for the host-completion
1949
- // event, because the run may not be over (a SequentialAgent's next agent,
1950
- // after-agent callback content). The final response is stashed and closed
2148
+ // Host obligation 4 (opt-in): a success or paused close waits for the
2149
+ // host-completion event, because the run may not be over (a
2150
+ // SequentialAgent's next agent, after-agent callback content, the model
2151
+ // run again after a pause). The final response is stashed and closed
1951
2152
  // unchanged on the sentinel, so a stream ending here is byte-identical.
1952
- // Error and paused closes stay immediate.
1953
- if (hostCompletion && errorClose === undefined && !((pendingAsks.get(turnId)?.length ?? 0) > 0)) {
2153
+ // Error closes stay immediate.
2154
+ if (hostCompletion && errorClose === undefined) {
1954
2155
  deferredClose.set(turnId, event);
1955
2156
  return;
1956
2157
  }
@@ -2049,6 +2250,13 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2049
2250
  const messageId = `msg_${turnId}`;
2050
2251
  const asks = pendingAsks.get(turnId);
2051
2252
  if (asks !== undefined && asks.length > 0) {
2253
+ // A final response stashed while the asks were pending closes as it
2254
+ // would have on arrival (paused, with its safety and lossy-finish carries).
2255
+ const stashedPaused = deferredClose.get(turnId);
2256
+ if (stashedPaused !== undefined) {
2257
+ closeOnFinalResponse(stashedPaused, turnId, messageId, undefined);
2258
+ continue;
2259
+ }
2052
2260
  closedTurns.add(turnId);
2053
2261
  const usage = mapUsage(usageByTurn.get(turnId));
2054
2262
  a.closeMessage(messageId);
@@ -2083,10 +2291,6 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2083
2291
  * complete. With no turn open, a fresh terminal turn carries the error, so
2084
2292
  * it is never start-less. */
2085
2293
  let hostErrorTurns = 0;
2086
- // The first turn key this invoke drove (its ADK invocationId): the stem of a
2087
- // fresh terminal turn's id, so the id is unique across the invokes a host
2088
- // folds together, not only within this one.
2089
- let firstKey: string | undefined;
2090
2294
  function hostError(err: AdkHostError): void {
2091
2295
  let closed = 0;
2092
2296
  for (const turnId of [...openTurns].reverse()) {
@@ -2098,8 +2302,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2098
2302
  closed++;
2099
2303
  }
2100
2304
  if (closed > 0) return;
2101
- const base = firstKey ?? err.invocationId ?? (stem.value ??= drawIdStem());
2102
- const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
2305
+ const turnId = `turn_${invokeStem}_host_error_${hostErrorTurns++}`;
2103
2306
  const messageId = ensureOpen(turnId);
2104
2307
  closedTurns.add(turnId);
2105
2308
  a.closeMessage(messageId);
@@ -2111,9 +2314,12 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2111
2314
  }
2112
2315
 
2113
2316
  function drive(event: AdkEvent): void {
2114
- const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
2115
- firstKey ??= key;
2116
- const turnId = `turn_${key}`;
2317
+ const turnId = liveTurnFor(event);
2318
+ // ADK re-yields a bare `{interrupted}` after a message that carried both
2319
+ // turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
2320
+ // 2.1.0). For a generation the barge-in already closed, it adds nothing:
2321
+ // no new turn and no second terminal, so the facet emits nothing for it.
2322
+ if (turnId === undefined) return;
2117
2323
  const messageId = ensureOpen(turnId);
2118
2324
  const parts = event.content?.parts ?? [];
2119
2325
  const isPartial = event.partial === true;
@@ -2163,7 +2369,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2163
2369
  });
2164
2370
 
2165
2371
  // §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
2166
- const alreadyStreamed = streamedText.get(key) ?? "";
2372
+ const alreadyStreamed = streamedText.get(turnId) ?? "";
2167
2373
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
2168
2374
  const aggregateText = isAggregate
2169
2375
  ? parts
@@ -2224,8 +2430,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2224
2430
  if (isPartial) accumulated += contributed;
2225
2431
  });
2226
2432
 
2227
- if (isPartial) streamedText.set(key, accumulated);
2228
- else if (isAggregate) streamedText.delete(key);
2433
+ if (isPartial) streamedText.set(turnId, accumulated);
2434
+ else if (isAggregate) streamedText.delete(turnId);
2229
2435
 
2230
2436
  // Round-3 review finding (regression on finding b): the resend window's
2231
2437
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
@@ -2242,12 +2448,53 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2242
2448
  // per-invoke.
2243
2449
 
2244
2450
  if (!isPartial) trackLongRunning(event, turnId);
2245
- driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
2451
+ driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
2246
2452
  // A turn gets ONE terminal: an interrupt on a turn that already closed
2247
2453
  // (a second barge-in, or one after a success close) adds none.
2248
2454
  if (event.interrupted === true && !closedTurns.has(turnId)) interruptPending.add(turnId);
2455
+ carryLiveUsageDetails(event, turnId, messageId, isPartial);
2456
+ if (parts.some((p) => p.functionResponse !== undefined)) awaitingReply.add(turnId);
2457
+ else if (hasModelOutput(event)) awaitingReply.delete(turnId);
2249
2458
  maybeCloseTurn(event, turnId, messageId, isPartial);
2250
- if (!isPartial && interruptPending.has(turnId)) closeInterrupted(turnId);
2459
+ // The interrupted generation closes on its own turnComplete (its trailing
2460
+ // usageMetadata arrives before it), or at flush() / host completion.
2461
+ if (!isPartial && event.turnComplete === true && interruptPending.has(turnId)) closeInterrupted(turnId);
2462
+ }
2463
+
2464
+ /** Gemini Live prices per modality (text vs audio), so its usage reports'
2465
+ * `promptTokensDetails` / `responseTokensDetails` ride the message's
2466
+ * metadata (a `message.metadata` event, key `usageDetails`), one entry per report, verbatim and never
2467
+ * summed. Each report re-emits the whole list (message metadata folds by
2468
+ * key, so the last emission holds every report). The list is the TURN's,
2469
+ * like the turn-summed `usage`, and rides the turn's current message; a turn
2470
+ * with more than one message carries it on the later one. Live path only
2471
+ * (`responseTokenCount` present): generateContent streams are unchanged. */
2472
+ function carryLiveUsageDetails(event: AdkEvent, turnId: string, messageId: string, isPartial: boolean): void {
2473
+ const um = event.usageMetadata;
2474
+ if (isPartial || um === undefined || um.responseTokenCount === undefined || um.candidatesTokenCount !== undefined) return;
2475
+ const entry: { [k: string]: JsonValue } = {
2476
+ ...(um.promptTokensDetails !== undefined ? { promptTokensDetails: um.promptTokensDetails } : {}),
2477
+ ...(um.responseTokensDetails !== undefined ? { responseTokensDetails: um.responseTokensDetails } : {}),
2478
+ };
2479
+ if (Object.keys(entry).length === 0) return;
2480
+ const list = [...(usageDetailsByTurn.get(turnId) ?? []), entry];
2481
+ usageDetailsByTurn.set(turnId, list);
2482
+ a.emit({ type: "message.metadata", messageId, metadata: { usageDetails: list } });
2483
+ }
2484
+
2485
+ /** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
2486
+ * key), with `_g<n>` for the n-th generation after a barge-in closed the
2487
+ * previous one. `undefined` for ADK's bare `{interrupted}` re-yield on a
2488
+ * generation a barge-in already closed. */
2489
+ function liveTurnFor(event: AdkEvent): string | undefined {
2490
+ const key = turnKey(event);
2491
+ const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
2492
+ const g = generationOf.get(base) ?? 0;
2493
+ const current = g === 0 ? base : `${base}_g${g}`;
2494
+ if (!interruptClosed.has(current)) return current;
2495
+ if (event.interrupted === true && !hasLiveContent(event)) return undefined;
2496
+ generationOf.set(base, g + 1);
2497
+ return `${base}_g${g + 1}`;
2251
2498
  }
2252
2499
 
2253
2500
  /** interrupted → turn.abort, after the event's own content and carries and
@@ -2257,6 +2504,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
2257
2504
  * message.end carries the turn's accumulated usage, as flush()'s does. */
2258
2505
  function closeInterrupted(turnId: string): void {
2259
2506
  interruptPending.delete(turnId);
2507
+ interruptClosed.add(turnId);
2260
2508
  closedTurns.add(turnId);
2261
2509
  a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
2262
2510
  a.emit({ type: "turn.abort", turnId, reason: "interrupted" });