@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/dist/index.js CHANGED
@@ -49,32 +49,41 @@
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
- import { AgUsage, AgProviderMeta, JsonValue, StreamAssembler, toJsonValueSafe, withAtomicPush, } from "@silverprotocol/core";
86
+ import { AgUsage, AgProviderMeta, AgResourceLinkBlock, JsonValue, StreamAssembler, toJsonValueSafe, withAtomicPush, } from "@silverprotocol/core";
78
87
  import { ADK_REQUEST_CREDENTIAL, snakeKey, pickAllowed, scrubStateMap, scrubAdkAuthConfig, scrubbedResponse, carryNodeValue, changedOutputRendering, reduceCarried, scrubCredentialCallArgs, adkAuthConfigView, } from "./auth-objects.js";
79
88
  import { isJsonObject, stringMember } from "./json-guards.js";
80
89
  // ─── finishReason → AgFinishReason (spec §4) ──────────────────────────────────
@@ -156,7 +165,16 @@ function isAdkEvent(v) {
156
165
  * inclusive on that endpoint — carry it as-is, never add twice. A thoughts-free
157
166
  * usageMetadata normalizes byte-identically to draft.2. `reasoningTokens` stays
158
167
  * the breakdown (`thoughtsTokenCount` verbatim); `totalTokens` is copied, never
159
- * computed. Known upstream gap: @google/adk's Interactions-API route synthesizes
168
+ * computed, with ONE exception, the Gemini Live API (draft.5): Live reports its
169
+ * output as `responseTokenCount`, and its `totalTokenCount` may leave thoughts
170
+ * out (609 + 25 = 634 with 256 thoughts beside them), so thoughts always fold
171
+ * into outputTokens there. Where Live reports a total, `totalTokens` is
172
+ * derived as input + output + toolUseInput over the turn's summed counters,
173
+ * and Google's own summed total rides `totalTokensRaw` only where it differs;
174
+ * with no reported total, neither is emitted. This facet recognises the Live
175
+ * API by the field: `responseTokenCount` appears only on @google/genai's Live
176
+ * UsageMetadata. A normalizer reading the raw Vertex Live wire decides by the
177
+ * API, not by the field name. Known upstream gap: @google/adk's Interactions-API route synthesizes
160
178
  * usageMetadata WITHOUT thoughts (candidates = total_output_tokens, total =
161
179
  * in + out), so on that route outputTokens is exclusive and reasoningTokens
162
180
  * absent — nothing the facet can recover (see README).
@@ -169,21 +187,38 @@ function mapUsage(um) {
169
187
  return undefined;
170
188
  const candidates = um.candidatesTokenCount;
171
189
  const thoughts = um.thoughtsTokenCount;
172
- const alreadyInclusive = candidates !== undefined &&
190
+ // Gemini Live reports its output as `responseTokenCount`, and its total is
191
+ // prompt + response, EXCLUDING thoughts (the capture
192
+ // live-bargein-gemini38live: 609 + 25 = 634, with 256 thoughts beside them).
193
+ // So on Live the total cannot show whether thoughts are included, and they
194
+ // always fold in: outputTokens = response + thoughts (SPEC §4 inclusion).
195
+ const response = candidates === undefined ? um.responseTokenCount : undefined;
196
+ const generated = candidates ?? response;
197
+ const alreadyInclusive = response === undefined &&
198
+ candidates !== undefined &&
173
199
  thoughts !== undefined &&
174
200
  thoughts > 0 &&
175
201
  um.totalTokenCount !== undefined &&
176
202
  um.promptTokenCount !== undefined &&
177
203
  um.promptTokenCount + (candidates ?? 0) + (um.toolUsePromptTokenCount ?? 0) === um.totalTokenCount;
178
- const outputTokens = candidates === undefined && thoughts === undefined
204
+ const outputTokens = generated === undefined && thoughts === undefined
179
205
  ? undefined
180
206
  : alreadyInclusive
181
207
  ? candidates
182
- : (candidates ?? 0) + (thoughts ?? 0);
208
+ : (generated ?? 0) + (thoughts ?? 0);
209
+ // On the Live path the total is derived, and Google's figure is kept beside
210
+ // it only where it differs; elsewhere the provider's total is copied.
211
+ const totalTokens = response !== undefined && um.totalTokenCount !== undefined
212
+ ? (um.promptTokenCount ?? 0) + (outputTokens ?? 0) + (um.toolUsePromptTokenCount ?? 0)
213
+ : um.totalTokenCount;
214
+ const totalTokensRaw = response !== undefined && um.totalTokenCount !== undefined && um.totalTokenCount !== totalTokens
215
+ ? um.totalTokenCount
216
+ : undefined;
183
217
  return {
184
218
  ...(um.promptTokenCount !== undefined ? { inputTokens: um.promptTokenCount } : {}),
185
219
  ...(outputTokens !== undefined ? { outputTokens } : {}),
186
- ...(um.totalTokenCount !== undefined ? { totalTokens: um.totalTokenCount } : {}),
220
+ ...(totalTokens !== undefined ? { totalTokens } : {}),
221
+ ...(totalTokensRaw !== undefined ? { totalTokensRaw } : {}),
187
222
  ...(um.cachedContentTokenCount !== undefined
188
223
  ? { cacheReadTokens: um.cachedContentTokenCount }
189
224
  : {}),
@@ -203,6 +238,7 @@ const USAGE_SUM_FIELDS = [
203
238
  "cachedContentTokenCount",
204
239
  "thoughtsTokenCount",
205
240
  "toolUsePromptTokenCount",
241
+ "responseTokenCount",
206
242
  ];
207
243
  /** Fold one event's usageMetadata into a turn's running accumulator
208
244
  * (field-wise sum; absent fields stay absent so mapUsage's presence checks
@@ -406,9 +442,23 @@ function isAdkPauseEnd(event) {
406
442
  !path.includes(".") &&
407
443
  (event.longRunningToolIds?.length ?? 0) > 0);
408
444
  }
445
+ /** Whether an event carries any content of a generation: a part, or an input
446
+ * or output transcription. */
447
+ function hasLiveContent(ev) {
448
+ return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
449
+ }
450
+ /** Whether an event carries model output: a part of `model`-role content, or
451
+ * output-transcription text. ADK's function response is `user`-role. */
452
+ function hasModelOutput(ev) {
453
+ if (ev.content?.role === "model" && (ev.content.parts?.length ?? 0) > 0)
454
+ return true;
455
+ const transcribed = ev.outputTranscription?.text;
456
+ return typeof transcribed === "string" && transcribed.length > 0;
457
+ }
409
458
  /** The event's own turn key: its invocationId, else its id. `undefined` when it
410
- * has neither; the normalizer then names the turn from its per-instance stem,
411
- * never a constant that would repeat across the invokes a host folds together. */
459
+ * has neither; the turn is then named from the per-invoke stem alone. The key
460
+ * is never a turn id by itself: ADK-Python's resumable resume reuses
461
+ * `invocation_id`, so every turn id carries the per-invoke stem too. */
412
462
  function turnKey(ev) {
413
463
  if (ev.invocationId && ev.invocationId.length > 0)
414
464
  return ev.invocationId;
@@ -420,7 +470,7 @@ function turnKey(ev) {
420
470
  // the positional index on tool.start/tool-call `providerCallIndex` so re-input can
421
471
  // restore name+position correlation when echoing functionResponse parts.
422
472
  // ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
423
- // adk-10, founder-ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
473
+ // adk-10, ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
424
474
  // answers a failed tool call with a response carrying Gemini's documented
425
475
  // `error` key: an unresolvable tool name (functions.js:264), a thrown tool
426
476
  // including a thrown MCP call (functions.js:282), several built-in tools.
@@ -476,6 +526,83 @@ function classifyFunctionResponse(response, toolCallId, actions) {
476
526
  }
477
527
  return { outcome: "ok" };
478
528
  }
529
+ /** Sorted-key JSON: "does parsing change this value" compares members, not
530
+ * the order a schema writes them in. */
531
+ function canonicalJson(v) {
532
+ if (Array.isArray(v))
533
+ return `[${v.map(canonicalJson).join(",")}]`;
534
+ if (!isJsonObject(v))
535
+ return JSON.stringify(v);
536
+ return `{${Object.keys(v)
537
+ .sort()
538
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
539
+ .join(",")}}`;
540
+ }
541
+ /** A native member that fits the resource-link block: core's own schema for
542
+ * that member accepts it AND leaves it unchanged, so the block carries it
543
+ * verbatim. `undefined` when it does not fit (it then rides the residual). */
544
+ function fitMember(parse, v) {
545
+ if (v === undefined)
546
+ return undefined;
547
+ const r = parse(v);
548
+ if (!r.success || r.data === undefined)
549
+ return undefined;
550
+ const back = JsonValue.safeParse(r.data);
551
+ return back.success && canonicalJson(back.data) === canonicalJson(v) ? r.data : undefined;
552
+ }
553
+ const RESOURCE_LINK_MEMBERS = new Set(["name", "title", "description", "mimeType", "size", "annotations", "_meta"]);
554
+ /**
555
+ * SPEC §8.0 item 31 (draft.5): an MCP `resource_link` content part of a tool
556
+ * result becomes ONE `resource-link` block carrying its native `uri`, `name`,
557
+ * `title`, `description`, `mimeType`, `size`, `annotations` and `_meta`
558
+ * verbatim where present, after item 28's reductions (applied as for a
559
+ * provider-raw carry; a `uri` is neither a credential object nor a
560
+ * credential-request response, so it passes unchanged, signed query included).
561
+ * The members the block cannot hold (a member it does not define, such as
562
+ * `icons`, or a defined one whose native value core's schema rejects or would
563
+ * alter) ride exactly one provider-raw block right after it, carrying only
564
+ * those members; with none, no such block is emitted.
565
+ *
566
+ * Item 31 binds MCP-schema-valid `resource_link` parts. A part without a string
567
+ * `uri` fails MCP's own schema (uri is required): it is an unmappable part, so
568
+ * §8.0's graceful degradation applies, and it stays one reduced provider-raw
569
+ * (`undefined` here), never dropped and never forced into a uri-less block.
570
+ */
571
+ function resourceLinkBlocks(part) {
572
+ const reduced = reduceCarried(part);
573
+ if (!isJsonObject(reduced) || typeof reduced["uri"] !== "string")
574
+ return undefined;
575
+ const S = AgResourceLinkBlock.shape;
576
+ const name = fitMember((v) => S.name.safeParse(v), reduced["name"]);
577
+ const title = fitMember((v) => S.title.safeParse(v), reduced["title"]);
578
+ const description = fitMember((v) => S.description.safeParse(v), reduced["description"]);
579
+ const mimeType = fitMember((v) => S.mimeType.safeParse(v), reduced["mimeType"]);
580
+ const size = fitMember((v) => S.size.safeParse(v), reduced["size"]);
581
+ const annotations = fitMember((v) => S.annotations.safeParse(v), reduced["annotations"]);
582
+ const meta = fitMember((v) => S._meta.safeParse(v), reduced["_meta"]);
583
+ const fitted = {
584
+ name: name !== undefined,
585
+ title: title !== undefined,
586
+ description: description !== undefined,
587
+ mimeType: mimeType !== undefined,
588
+ size: size !== undefined,
589
+ annotations: annotations !== undefined,
590
+ _meta: meta !== undefined,
591
+ };
592
+ const block = {
593
+ type: "resource-link",
594
+ uri: reduced["uri"],
595
+ ...(name !== undefined ? { name } : {}),
596
+ ...(title !== undefined ? { title } : {}),
597
+ ...(description !== undefined ? { description } : {}),
598
+ ...(mimeType !== undefined ? { mimeType } : {}),
599
+ ...(size !== undefined ? { size } : {}),
600
+ ...(annotations !== undefined ? { annotations } : {}),
601
+ ...(meta !== undefined ? { _meta: meta } : {}),
602
+ };
603
+ const residual = Object.fromEntries(Object.entries(reduced).filter(([k]) => k !== "type" && k !== "uri" && !(RESOURCE_LINK_MEMBERS.has(k) && fitted[k] === true)));
604
+ return Object.keys(residual).length > 0 ? [block, { type: "provider-raw", vendor: "google", raw: residual }] : [block];
605
+ }
479
606
  function functionResponseToToolDoneFields(name, response) {
480
607
  if (response === undefined)
481
608
  return { content: [] };
@@ -490,8 +617,17 @@ function functionResponseToToolDoneFields(name, response) {
490
617
  out.push({ type: "text", text: part["text"] });
491
618
  continue;
492
619
  }
620
+ if (t === "resource_link") {
621
+ const link = resourceLinkBlocks(part);
622
+ if (link !== undefined) {
623
+ out.push(...link);
624
+ continue;
625
+ }
626
+ }
493
627
  }
494
- // Preserve any non-text MCP content part losslessly as a provider-raw block.
628
+ // Preserve any other non-text MCP content part losslessly as a provider-raw
629
+ // block (image, audio and embedded resource parts; a resource_link that
630
+ // is not MCP-schema-valid, see resourceLinkBlocks).
495
631
  out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
496
632
  }
497
633
  const meta = response["_meta"];
@@ -884,21 +1020,34 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
884
1020
  else
885
1021
  pendingAsks.set(turnId, [ask]);
886
1022
  }
887
- function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved) {
1023
+ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription) {
1024
+ // Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
1025
+ // a `finished: true` transcription whose text is the chunks joined
1026
+ // (utils/live_connection_utils.js, @google/adk 2.1.0). That aggregate is not
1027
+ // re-emitted when it repeats this turn's streamed chunks exactly, so the
1028
+ // turn's transcription reads once; one that differs rides as its own block.
888
1029
  // typeof: a JSON-null transcription text is absent (null guard; it rode the
889
1030
  // text block as `null`, which the schema rejects).
890
- if (typeof event.inputTranscription?.text === "string") {
891
- a.contentBlock(messageId, {
892
- type: "text",
893
- text: event.inputTranscription.text,
894
- _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
895
- });
896
- }
897
- if (typeof event.outputTranscription?.text === "string") {
1031
+ for (const [role, t] of [
1032
+ ["input", event.inputTranscription],
1033
+ ["output", event.outputTranscription],
1034
+ ]) {
1035
+ if (typeof t?.text !== "string")
1036
+ continue;
1037
+ const key = `${turnId}\u0000${role}`;
1038
+ if (t.finished === true) {
1039
+ const streamed = streamedTranscription.get(key);
1040
+ streamedTranscription.delete(key);
1041
+ if (streamed === t.text)
1042
+ continue;
1043
+ }
1044
+ else {
1045
+ streamedTranscription.set(key, (streamedTranscription.get(key) ?? "") + t.text);
1046
+ }
898
1047
  a.contentBlock(messageId, {
899
1048
  type: "text",
900
- text: event.outputTranscription.text,
901
- _meta: { "agjson/transcription": { role: "output", kind: "transcription" } },
1049
+ text: t.text,
1050
+ _meta: { "agjson/transcription": { role, kind: "transcription" } },
902
1051
  });
903
1052
  }
904
1053
  // `interrupted` → turn.abort is closed in drive(), after this event's own
@@ -1177,12 +1326,10 @@ function hostErrorOf(raw) {
1177
1326
  return undefined;
1178
1327
  const usageRaw = Reflect.get(raw, "usage");
1179
1328
  const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
1180
- const invocationId = Reflect.get(raw, "invocationId");
1181
1329
  return {
1182
1330
  code,
1183
1331
  message,
1184
1332
  ...(usage?.success === true ? { usage: usage.data } : {}),
1185
- ...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
1186
1333
  };
1187
1334
  }
1188
1335
  catch {
@@ -1195,7 +1342,7 @@ function isHostCompleteNative(v) {
1195
1342
  }
1196
1343
  /**
1197
1344
  * The google-adk Normalizer: the inner, deterministic normalizer below wrapped
1198
- * in core's withAtomicPush (the fleet guard ruling). Every push() is atomic:
1345
+ * in core's withAtomicPush (the guard ruling). Every push() is atomic:
1199
1346
  * - The native is read once as plain JSON through core's toJsonValueSafe, so a
1200
1347
  * host may push the live Event objects ADK yields (undefined members, a
1201
1348
  * Date, an Error, a cycle) and they map exactly like the recorded corpus.
@@ -1203,8 +1350,8 @@ function isHostCompleteNative(v) {
1203
1350
  * inner members have unexpected types), its partial batch is discarded
1204
1351
  * without consuming seq, the inner is rebuilt by re-driving every native
1205
1352
  * accepted so far (the inner never reads the clock or randomness; ids come
1206
- * from invocationId and per-invoke ordinals, and the one random stem, for a
1207
- * host error before any event, is drawn outside the inner and kept), and
1353
+ * from the per-invoke stem, invocationId and per-invoke ordinals, and the
1354
+ * stem is drawn once, outside the inner, and kept), and
1208
1355
  * ONE core `error {message:
1209
1356
  * "normalizer error", code: <constructor name>}` takes the next seq, with no
1210
1357
  * payload and no message text.
@@ -1214,38 +1361,28 @@ function isHostCompleteNative(v) {
1214
1361
  * message or block is open that never reached the wire.
1215
1362
  */
1216
1363
  export function createAdkNormalizer(options = {}) {
1217
- // A per-instance id stem, drawn lazily and only on the paths that need it (an
1218
- // event with neither invocationId nor id; a host error before any event,
1219
- // with no invocationId on the sentinel). It lives OUTSIDE the inner, so a
1220
- // rebuild re-drives to the same ids.
1221
- const stem = {};
1222
- return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
1364
+ // The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
1365
+ // re-drives to the same ids and no push() reads randomness.
1366
+ const invokeStem = options.invokeId ?? `adk_${mintInvokeNonce()}`;
1367
+ return withAtomicPush(() => createInnerAdkNormalizer(options, invokeStem));
1223
1368
  }
1224
- /** A random per-instance stem; never called while a replay re-drives, since
1225
- * the stem is drawn once and kept.
1226
- *
1227
- * The `Date.now` + `Math.random` fallback runs only when `crypto.randomUUID`
1228
- * is absent, which cannot happen on Node >= 19 (a global `crypto`). It is the
1229
- * facet's one read of the clock or a random source, and it is safe for
1230
- * determinism: the stem is drawn outside the inner, once, and a
1231
- * withAtomicPush rebuild reuses it, so the corpus legs that poison the clock
1232
- * and randomness never reach this call. */
1233
- function drawIdStem() {
1234
- const cryptoObj = Reflect.get(globalThis, "crypto");
1235
- const randomUUID = cryptoObj !== undefined && cryptoObj !== null ? Reflect.get(cryptoObj, "randomUUID") : undefined;
1236
- if (typeof randomUUID === "function") {
1237
- const id = Reflect.apply(randomUUID, cryptoObj, []);
1238
- if (typeof id === "string")
1239
- return id;
1240
- }
1241
- return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1369
+ /** 64 random bits as 16 hex chars: the default per-invoke id stem (as the
1370
+ * vercel, openai and claude facets draw theirs). */
1371
+ function mintInvokeNonce() {
1372
+ const bytes = new Uint8Array(8);
1373
+ globalThis.crypto.getRandomValues(bytes);
1374
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1242
1375
  }
1243
- function createInnerAdkNormalizer(options, stem) {
1376
+ function createInnerAdkNormalizer(options, invokeStem) {
1244
1377
  const hostCompletion = options.hostCompletion === true;
1245
1378
  const a = new StreamAssembler();
1246
- const threadId = "google";
1379
+ const threadId = options.threadId ?? "google";
1247
1380
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
1248
1381
  const streamedText = new Map();
1382
+ // Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
1383
+ const streamedTranscription = new Map();
1384
+ // Per turn: the Live usage reports' modality details, one entry per report.
1385
+ const usageDetailsByTurn = new Map();
1249
1386
  const openTurns = new Set();
1250
1387
  const closedTurns = new Set();
1251
1388
  // Per-turn usageMetadata accumulator (2026-07-13, echo-gemini35 live-capture
@@ -1278,6 +1415,21 @@ function createInnerAdkNormalizer(options, stem) {
1278
1415
  // so the close waits for the next non-partial event of the turn, or for
1279
1416
  // flush() / host completion.
1280
1417
  const interruptPending = new Set();
1418
+ // Live generations. One live session is one ADK invocation, so one turn key
1419
+ // spans every model generation of the session. ADK delivers a barge-in's
1420
+ // flag FIRST, then the interrupted generation's own usageMetadata and
1421
+ // turnComplete, then the reply generation (a gemini-3.8-live capture
1422
+ // `live-bargein-gemini38live`). So an interrupted generation closes on its own
1423
+ // turnComplete (closeInterrupted), and the next generation after a barge-in
1424
+ // opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
1425
+ const generationOf = new Map();
1426
+ const interruptClosed = new Set();
1427
+ // Turns whose last function response has no model output after it yet. On
1428
+ // the Live path the model always answers a tool result with a reply
1429
+ // generation, and ADK can yield the call generation's turnComplete between
1430
+ // the response and that reply (a gemini-3.8-live capture,
1431
+ // `live-tool-gemini38live`), so that turnComplete does not end the turn.
1432
+ const awaitingReply = new Set();
1281
1433
  const pendingLongRunning = new Map();
1282
1434
  const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
1283
1435
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
@@ -1320,6 +1472,17 @@ function createInnerAdkNormalizer(options, stem) {
1320
1472
  // before, their close never fired and the turn flushed as an abort.
1321
1473
  const pending = pendingAsks.get(turnId);
1322
1474
  if (!interrupted && pending !== undefined && pending.length > 0 && isAdkPauseEnd(event)) {
1475
+ // With the host-completion opt-in, the paused close waits for the
1476
+ // host-completion event (item 26: "at the latest, on the host-completion
1477
+ // event"; hostComplete() closes a turn whose asks are pending as paused).
1478
+ // ADK ends the invocation at a confirmation but not at a credential
1479
+ // request or a request-input call, so an ADK event can follow the pause
1480
+ // end in the same invocation and carry state and content: the model run
1481
+ // again when its stream ended with a usage-only chunk
1482
+ // (agents/llm_agent.js:458), an after-agent callback, the next sub-agent
1483
+ // of a SequentialAgent root. Without the opt-in the close stays here.
1484
+ if (hostCompletion)
1485
+ return;
1323
1486
  closedTurns.add(turnId);
1324
1487
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1325
1488
  a.closeMessage(messageId);
@@ -1336,6 +1499,10 @@ function createInnerAdkNormalizer(options, stem) {
1336
1499
  // is_final_response: a non-partial event with no pending function call and not interrupted.
1337
1500
  if (hasFunctionCall || interrupted || !hasCompletion)
1338
1501
  return;
1502
+ // A bare Live turnComplete between a function response and the model's
1503
+ // reply ends the call generation, not the turn (see awaitingReply).
1504
+ if (event.finishReason === undefined && event.errorCode === undefined && awaitingReply.has(turnId))
1505
+ return;
1339
1506
  // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
1340
1507
  // present ⇒ turn.error (values captured here so the close below needs no
1341
1508
  // re-narrowing).
@@ -1354,12 +1521,13 @@ function createInnerAdkNormalizer(options, stem) {
1354
1521
  // it flushes turn.abort.
1355
1522
  if (errorClose === undefined && event.nodeInfo !== undefined)
1356
1523
  return;
1357
- // Host obligation 4 (opt-in): a SUCCESS close waits for the host-completion
1358
- // event, because the run may not be over (a SequentialAgent's next agent,
1359
- // after-agent callback content). The final response is stashed and closed
1524
+ // Host obligation 4 (opt-in): a success or paused close waits for the
1525
+ // host-completion event, because the run may not be over (a
1526
+ // SequentialAgent's next agent, after-agent callback content, the model
1527
+ // run again after a pause). The final response is stashed and closed
1360
1528
  // unchanged on the sentinel, so a stream ending here is byte-identical.
1361
- // Error and paused closes stay immediate.
1362
- if (hostCompletion && errorClose === undefined && !((pendingAsks.get(turnId)?.length ?? 0) > 0)) {
1529
+ // Error closes stay immediate.
1530
+ if (hostCompletion && errorClose === undefined) {
1363
1531
  deferredClose.set(turnId, event);
1364
1532
  return;
1365
1533
  }
@@ -1454,6 +1622,13 @@ function createInnerAdkNormalizer(options, stem) {
1454
1622
  const messageId = `msg_${turnId}`;
1455
1623
  const asks = pendingAsks.get(turnId);
1456
1624
  if (asks !== undefined && asks.length > 0) {
1625
+ // A final response stashed while the asks were pending closes as it
1626
+ // would have on arrival (paused, with its safety and lossy-finish carries).
1627
+ const stashedPaused = deferredClose.get(turnId);
1628
+ if (stashedPaused !== undefined) {
1629
+ closeOnFinalResponse(stashedPaused, turnId, messageId, undefined);
1630
+ continue;
1631
+ }
1457
1632
  closedTurns.add(turnId);
1458
1633
  const usage = mapUsage(usageByTurn.get(turnId));
1459
1634
  a.closeMessage(messageId);
@@ -1488,10 +1663,6 @@ function createInnerAdkNormalizer(options, stem) {
1488
1663
  * complete. With no turn open, a fresh terminal turn carries the error, so
1489
1664
  * it is never start-less. */
1490
1665
  let hostErrorTurns = 0;
1491
- // The first turn key this invoke drove (its ADK invocationId): the stem of a
1492
- // fresh terminal turn's id, so the id is unique across the invokes a host
1493
- // folds together, not only within this one.
1494
- let firstKey;
1495
1666
  function hostError(err) {
1496
1667
  let closed = 0;
1497
1668
  for (const turnId of [...openTurns].reverse()) {
@@ -1505,8 +1676,7 @@ function createInnerAdkNormalizer(options, stem) {
1505
1676
  }
1506
1677
  if (closed > 0)
1507
1678
  return;
1508
- const base = firstKey ?? err.invocationId ?? (stem.value ??= drawIdStem());
1509
- const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
1679
+ const turnId = `turn_${invokeStem}_host_error_${hostErrorTurns++}`;
1510
1680
  const messageId = ensureOpen(turnId);
1511
1681
  closedTurns.add(turnId);
1512
1682
  a.closeMessage(messageId);
@@ -1517,9 +1687,13 @@ function createInnerAdkNormalizer(options, stem) {
1517
1687
  });
1518
1688
  }
1519
1689
  function drive(event) {
1520
- const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
1521
- firstKey ??= key;
1522
- const turnId = `turn_${key}`;
1690
+ const turnId = liveTurnFor(event);
1691
+ // ADK re-yields a bare `{interrupted}` after a message that carried both
1692
+ // turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
1693
+ // 2.1.0). For a generation the barge-in already closed, it adds nothing:
1694
+ // no new turn and no second terminal, so the facet emits nothing for it.
1695
+ if (turnId === undefined)
1696
+ return;
1523
1697
  const messageId = ensureOpen(turnId);
1524
1698
  const parts = event.content?.parts ?? [];
1525
1699
  const isPartial = event.partial === true;
@@ -1566,7 +1740,7 @@ function createInnerAdkNormalizer(options, stem) {
1566
1740
  nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
1567
1741
  });
1568
1742
  // §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
1569
- const alreadyStreamed = streamedText.get(key) ?? "";
1743
+ const alreadyStreamed = streamedText.get(turnId) ?? "";
1570
1744
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
1571
1745
  const aggregateText = isAggregate
1572
1746
  ? parts
@@ -1610,9 +1784,9 @@ function createInnerAdkNormalizer(options, stem) {
1610
1784
  accumulated += contributed;
1611
1785
  });
1612
1786
  if (isPartial)
1613
- streamedText.set(key, accumulated);
1787
+ streamedText.set(turnId, accumulated);
1614
1788
  else if (isAggregate)
1615
- streamedText.delete(key);
1789
+ streamedText.delete(turnId);
1616
1790
  // Round-3 review finding (regression on finding b): the resend window's
1617
1791
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
1618
1792
  // (see the `ToolCallMintState` doc above) already clears each null-id
@@ -1628,15 +1802,60 @@ function createInnerAdkNormalizer(options, stem) {
1628
1802
  // per-invoke.
1629
1803
  if (!isPartial)
1630
1804
  trackLongRunning(event, turnId);
1631
- driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
1805
+ driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
1632
1806
  // A turn gets ONE terminal: an interrupt on a turn that already closed
1633
1807
  // (a second barge-in, or one after a success close) adds none.
1634
1808
  if (event.interrupted === true && !closedTurns.has(turnId))
1635
1809
  interruptPending.add(turnId);
1810
+ carryLiveUsageDetails(event, turnId, messageId, isPartial);
1811
+ if (parts.some((p) => p.functionResponse !== undefined))
1812
+ awaitingReply.add(turnId);
1813
+ else if (hasModelOutput(event))
1814
+ awaitingReply.delete(turnId);
1636
1815
  maybeCloseTurn(event, turnId, messageId, isPartial);
1637
- if (!isPartial && interruptPending.has(turnId))
1816
+ // The interrupted generation closes on its own turnComplete (its trailing
1817
+ // usageMetadata arrives before it), or at flush() / host completion.
1818
+ if (!isPartial && event.turnComplete === true && interruptPending.has(turnId))
1638
1819
  closeInterrupted(turnId);
1639
1820
  }
1821
+ /** Gemini Live prices per modality (text vs audio), so its usage reports'
1822
+ * `promptTokensDetails` / `responseTokensDetails` ride the message's
1823
+ * metadata (a `message.metadata` event, key `usageDetails`), one entry per report, verbatim and never
1824
+ * summed. Each report re-emits the whole list (message metadata folds by
1825
+ * key, so the last emission holds every report). The list is the TURN's,
1826
+ * like the turn-summed `usage`, and rides the turn's current message; a turn
1827
+ * with more than one message carries it on the later one. Live path only
1828
+ * (`responseTokenCount` present): generateContent streams are unchanged. */
1829
+ function carryLiveUsageDetails(event, turnId, messageId, isPartial) {
1830
+ const um = event.usageMetadata;
1831
+ if (isPartial || um === undefined || um.responseTokenCount === undefined || um.candidatesTokenCount !== undefined)
1832
+ return;
1833
+ const entry = {
1834
+ ...(um.promptTokensDetails !== undefined ? { promptTokensDetails: um.promptTokensDetails } : {}),
1835
+ ...(um.responseTokensDetails !== undefined ? { responseTokensDetails: um.responseTokensDetails } : {}),
1836
+ };
1837
+ if (Object.keys(entry).length === 0)
1838
+ return;
1839
+ const list = [...(usageDetailsByTurn.get(turnId) ?? []), entry];
1840
+ usageDetailsByTurn.set(turnId, list);
1841
+ a.emit({ type: "message.metadata", messageId, metadata: { usageDetails: list } });
1842
+ }
1843
+ /** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
1844
+ * key), with `_g<n>` for the n-th generation after a barge-in closed the
1845
+ * previous one. `undefined` for ADK's bare `{interrupted}` re-yield on a
1846
+ * generation a barge-in already closed. */
1847
+ function liveTurnFor(event) {
1848
+ const key = turnKey(event);
1849
+ const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
1850
+ const g = generationOf.get(base) ?? 0;
1851
+ const current = g === 0 ? base : `${base}_g${g}`;
1852
+ if (!interruptClosed.has(current))
1853
+ return current;
1854
+ if (event.interrupted === true && !hasLiveContent(event))
1855
+ return undefined;
1856
+ generationOf.set(base, g + 1);
1857
+ return `${base}_g${g + 1}`;
1858
+ }
1640
1859
  /** interrupted → turn.abort, after the event's own content and carries and
1641
1860
  * after its message.end (INV-MSG: nothing of the turn follows its terminal).
1642
1861
  * The turn is marked closed in the facet's own bookkeeping too (audit M21),
@@ -1644,6 +1863,7 @@ function createInnerAdkNormalizer(options, stem) {
1644
1863
  * message.end carries the turn's accumulated usage, as flush()'s does. */
1645
1864
  function closeInterrupted(turnId) {
1646
1865
  interruptPending.delete(turnId);
1866
+ interruptClosed.add(turnId);
1647
1867
  closedTurns.add(turnId);
1648
1868
  a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
1649
1869
  a.emit({ type: "turn.abort", turnId, reason: "interrupted" });