@silverprotocol/google-adk 0.7.2 → 0.8.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/README.md +16 -4
- package/dist/index.d.ts +69 -27
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +263 -89
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +303 -97
package/dist/index.js
CHANGED
|
@@ -49,32 +49,36 @@
|
|
|
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:
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
* resumable resume reuses `invocation_id`, and this
|
|
56
|
-
* serialized from Python
|
|
57
|
-
*
|
|
58
|
-
*
|
|
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:
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* generation
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
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. Two limits remain.
|
|
75
|
+
* A generation that follows a completed reply, with no barge-in, lands in the
|
|
76
|
+
* closed turn and parks a reducer, unless `hostCompletion` defers that close.
|
|
77
|
+
* And when text is buffered at the interrupt, ADK yields only the text
|
|
78
|
+
* aggregate, without the flag (utils/live_connection_utils.js), so this facet
|
|
79
|
+
* sees no interrupt and the turn closes at flush as `stream-truncated`.
|
|
76
80
|
*/
|
|
77
|
-
import { AgUsage, AgProviderMeta, JsonValue, StreamAssembler, toJsonValueSafe, withAtomicPush, } from "@silverprotocol/core";
|
|
81
|
+
import { AgUsage, AgProviderMeta, AgResourceLinkBlock, JsonValue, StreamAssembler, toJsonValueSafe, withAtomicPush, } from "@silverprotocol/core";
|
|
78
82
|
import { ADK_REQUEST_CREDENTIAL, snakeKey, pickAllowed, scrubStateMap, scrubAdkAuthConfig, scrubbedResponse, carryNodeValue, changedOutputRendering, reduceCarried, scrubCredentialCallArgs, adkAuthConfigView, } from "./auth-objects.js";
|
|
79
83
|
import { isJsonObject, stringMember } from "./json-guards.js";
|
|
80
84
|
// ─── finishReason → AgFinishReason (spec §4) ──────────────────────────────────
|
|
@@ -156,7 +160,16 @@ function isAdkEvent(v) {
|
|
|
156
160
|
* inclusive on that endpoint — carry it as-is, never add twice. A thoughts-free
|
|
157
161
|
* usageMetadata normalizes byte-identically to draft.2. `reasoningTokens` stays
|
|
158
162
|
* the breakdown (`thoughtsTokenCount` verbatim); `totalTokens` is copied, never
|
|
159
|
-
* computed
|
|
163
|
+
* computed, with ONE exception, the Gemini Live API (draft.5): Live reports its
|
|
164
|
+
* output as `responseTokenCount`, and its `totalTokenCount` may leave thoughts
|
|
165
|
+
* out (609 + 25 = 634 with 256 thoughts beside them), so thoughts always fold
|
|
166
|
+
* into outputTokens there. Where Live reports a total, `totalTokens` is
|
|
167
|
+
* derived as input + output + toolUseInput over the turn's summed counters,
|
|
168
|
+
* and Google's own summed total rides `totalTokensRaw` only where it differs;
|
|
169
|
+
* with no reported total, neither is emitted. This facet recognises the Live
|
|
170
|
+
* API by the field: `responseTokenCount` appears only on @google/genai's Live
|
|
171
|
+
* UsageMetadata. A normalizer reading the raw Vertex Live wire decides by the
|
|
172
|
+
* API, not by the field name. Known upstream gap: @google/adk's Interactions-API route synthesizes
|
|
160
173
|
* usageMetadata WITHOUT thoughts (candidates = total_output_tokens, total =
|
|
161
174
|
* in + out), so on that route outputTokens is exclusive and reasoningTokens
|
|
162
175
|
* absent — nothing the facet can recover (see README).
|
|
@@ -169,21 +182,38 @@ function mapUsage(um) {
|
|
|
169
182
|
return undefined;
|
|
170
183
|
const candidates = um.candidatesTokenCount;
|
|
171
184
|
const thoughts = um.thoughtsTokenCount;
|
|
172
|
-
|
|
185
|
+
// Gemini Live reports its output as `responseTokenCount`, and its total is
|
|
186
|
+
// prompt + response, EXCLUDING thoughts (the capture
|
|
187
|
+
// live-bargein-gemini38live: 609 + 25 = 634, with 256 thoughts beside them).
|
|
188
|
+
// So on Live the total cannot show whether thoughts are included, and they
|
|
189
|
+
// always fold in: outputTokens = response + thoughts (SPEC §4 inclusion).
|
|
190
|
+
const response = candidates === undefined ? um.responseTokenCount : undefined;
|
|
191
|
+
const generated = candidates ?? response;
|
|
192
|
+
const alreadyInclusive = response === undefined &&
|
|
193
|
+
candidates !== undefined &&
|
|
173
194
|
thoughts !== undefined &&
|
|
174
195
|
thoughts > 0 &&
|
|
175
196
|
um.totalTokenCount !== undefined &&
|
|
176
197
|
um.promptTokenCount !== undefined &&
|
|
177
198
|
um.promptTokenCount + (candidates ?? 0) + (um.toolUsePromptTokenCount ?? 0) === um.totalTokenCount;
|
|
178
|
-
const outputTokens =
|
|
199
|
+
const outputTokens = generated === undefined && thoughts === undefined
|
|
179
200
|
? undefined
|
|
180
201
|
: alreadyInclusive
|
|
181
202
|
? candidates
|
|
182
|
-
: (
|
|
203
|
+
: (generated ?? 0) + (thoughts ?? 0);
|
|
204
|
+
// On the Live path the total is derived, and Google's figure is kept beside
|
|
205
|
+
// it only where it differs; elsewhere the provider's total is copied.
|
|
206
|
+
const totalTokens = response !== undefined && um.totalTokenCount !== undefined
|
|
207
|
+
? (um.promptTokenCount ?? 0) + (outputTokens ?? 0) + (um.toolUsePromptTokenCount ?? 0)
|
|
208
|
+
: um.totalTokenCount;
|
|
209
|
+
const totalTokensRaw = response !== undefined && um.totalTokenCount !== undefined && um.totalTokenCount !== totalTokens
|
|
210
|
+
? um.totalTokenCount
|
|
211
|
+
: undefined;
|
|
183
212
|
return {
|
|
184
213
|
...(um.promptTokenCount !== undefined ? { inputTokens: um.promptTokenCount } : {}),
|
|
185
214
|
...(outputTokens !== undefined ? { outputTokens } : {}),
|
|
186
|
-
...(
|
|
215
|
+
...(totalTokens !== undefined ? { totalTokens } : {}),
|
|
216
|
+
...(totalTokensRaw !== undefined ? { totalTokensRaw } : {}),
|
|
187
217
|
...(um.cachedContentTokenCount !== undefined
|
|
188
218
|
? { cacheReadTokens: um.cachedContentTokenCount }
|
|
189
219
|
: {}),
|
|
@@ -203,6 +233,7 @@ const USAGE_SUM_FIELDS = [
|
|
|
203
233
|
"cachedContentTokenCount",
|
|
204
234
|
"thoughtsTokenCount",
|
|
205
235
|
"toolUsePromptTokenCount",
|
|
236
|
+
"responseTokenCount",
|
|
206
237
|
];
|
|
207
238
|
/** Fold one event's usageMetadata into a turn's running accumulator
|
|
208
239
|
* (field-wise sum; absent fields stay absent so mapUsage's presence checks
|
|
@@ -406,9 +437,15 @@ function isAdkPauseEnd(event) {
|
|
|
406
437
|
!path.includes(".") &&
|
|
407
438
|
(event.longRunningToolIds?.length ?? 0) > 0);
|
|
408
439
|
}
|
|
440
|
+
/** Whether an event carries any content of a generation: a part, or an input
|
|
441
|
+
* or output transcription. */
|
|
442
|
+
function hasLiveContent(ev) {
|
|
443
|
+
return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
|
|
444
|
+
}
|
|
409
445
|
/** The event's own turn key: its invocationId, else its id. `undefined` when it
|
|
410
|
-
* has neither; the
|
|
411
|
-
* never a
|
|
446
|
+
* has neither; the turn is then named from the per-invoke stem alone. The key
|
|
447
|
+
* is never a turn id by itself: ADK-Python's resumable resume reuses
|
|
448
|
+
* `invocation_id`, so every turn id carries the per-invoke stem too. */
|
|
412
449
|
function turnKey(ev) {
|
|
413
450
|
if (ev.invocationId && ev.invocationId.length > 0)
|
|
414
451
|
return ev.invocationId;
|
|
@@ -420,7 +457,7 @@ function turnKey(ev) {
|
|
|
420
457
|
// the positional index on tool.start/tool-call `providerCallIndex` so re-input can
|
|
421
458
|
// restore name+position correlation when echoing functionResponse parts.
|
|
422
459
|
// ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
|
|
423
|
-
// adk-10,
|
|
460
|
+
// adk-10, ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
|
|
424
461
|
// answers a failed tool call with a response carrying Gemini's documented
|
|
425
462
|
// `error` key: an unresolvable tool name (functions.js:264), a thrown tool
|
|
426
463
|
// including a thrown MCP call (functions.js:282), several built-in tools.
|
|
@@ -476,6 +513,83 @@ function classifyFunctionResponse(response, toolCallId, actions) {
|
|
|
476
513
|
}
|
|
477
514
|
return { outcome: "ok" };
|
|
478
515
|
}
|
|
516
|
+
/** Sorted-key JSON: "does parsing change this value" compares members, not
|
|
517
|
+
* the order a schema writes them in. */
|
|
518
|
+
function canonicalJson(v) {
|
|
519
|
+
if (Array.isArray(v))
|
|
520
|
+
return `[${v.map(canonicalJson).join(",")}]`;
|
|
521
|
+
if (!isJsonObject(v))
|
|
522
|
+
return JSON.stringify(v);
|
|
523
|
+
return `{${Object.keys(v)
|
|
524
|
+
.sort()
|
|
525
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
|
|
526
|
+
.join(",")}}`;
|
|
527
|
+
}
|
|
528
|
+
/** A native member that fits the resource-link block: core's own schema for
|
|
529
|
+
* that member accepts it AND leaves it unchanged, so the block carries it
|
|
530
|
+
* verbatim. `undefined` when it does not fit (it then rides the residual). */
|
|
531
|
+
function fitMember(parse, v) {
|
|
532
|
+
if (v === undefined)
|
|
533
|
+
return undefined;
|
|
534
|
+
const r = parse(v);
|
|
535
|
+
if (!r.success || r.data === undefined)
|
|
536
|
+
return undefined;
|
|
537
|
+
const back = JsonValue.safeParse(r.data);
|
|
538
|
+
return back.success && canonicalJson(back.data) === canonicalJson(v) ? r.data : undefined;
|
|
539
|
+
}
|
|
540
|
+
const RESOURCE_LINK_MEMBERS = new Set(["name", "title", "description", "mimeType", "size", "annotations", "_meta"]);
|
|
541
|
+
/**
|
|
542
|
+
* SPEC §8.0 item 31 (draft.5): an MCP `resource_link` content part of a tool
|
|
543
|
+
* result becomes ONE `resource-link` block carrying its native `uri`, `name`,
|
|
544
|
+
* `title`, `description`, `mimeType`, `size`, `annotations` and `_meta`
|
|
545
|
+
* verbatim where present, after item 28's reductions (applied as for a
|
|
546
|
+
* provider-raw carry; a `uri` is neither a credential object nor a
|
|
547
|
+
* credential-request response, so it passes unchanged, signed query included).
|
|
548
|
+
* The members the block cannot hold (a member it does not define, such as
|
|
549
|
+
* `icons`, or a defined one whose native value core's schema rejects or would
|
|
550
|
+
* alter) ride exactly one provider-raw block right after it, carrying only
|
|
551
|
+
* those members; with none, no such block is emitted.
|
|
552
|
+
*
|
|
553
|
+
* Item 31 binds MCP-schema-valid `resource_link` parts. A part without a string
|
|
554
|
+
* `uri` fails MCP's own schema (uri is required): it is an unmappable part, so
|
|
555
|
+
* §8.0's graceful degradation applies, and it stays one reduced provider-raw
|
|
556
|
+
* (`undefined` here), never dropped and never forced into a uri-less block.
|
|
557
|
+
*/
|
|
558
|
+
function resourceLinkBlocks(part) {
|
|
559
|
+
const reduced = reduceCarried(part);
|
|
560
|
+
if (!isJsonObject(reduced) || typeof reduced["uri"] !== "string")
|
|
561
|
+
return undefined;
|
|
562
|
+
const S = AgResourceLinkBlock.shape;
|
|
563
|
+
const name = fitMember((v) => S.name.safeParse(v), reduced["name"]);
|
|
564
|
+
const title = fitMember((v) => S.title.safeParse(v), reduced["title"]);
|
|
565
|
+
const description = fitMember((v) => S.description.safeParse(v), reduced["description"]);
|
|
566
|
+
const mimeType = fitMember((v) => S.mimeType.safeParse(v), reduced["mimeType"]);
|
|
567
|
+
const size = fitMember((v) => S.size.safeParse(v), reduced["size"]);
|
|
568
|
+
const annotations = fitMember((v) => S.annotations.safeParse(v), reduced["annotations"]);
|
|
569
|
+
const meta = fitMember((v) => S._meta.safeParse(v), reduced["_meta"]);
|
|
570
|
+
const fitted = {
|
|
571
|
+
name: name !== undefined,
|
|
572
|
+
title: title !== undefined,
|
|
573
|
+
description: description !== undefined,
|
|
574
|
+
mimeType: mimeType !== undefined,
|
|
575
|
+
size: size !== undefined,
|
|
576
|
+
annotations: annotations !== undefined,
|
|
577
|
+
_meta: meta !== undefined,
|
|
578
|
+
};
|
|
579
|
+
const block = {
|
|
580
|
+
type: "resource-link",
|
|
581
|
+
uri: reduced["uri"],
|
|
582
|
+
...(name !== undefined ? { name } : {}),
|
|
583
|
+
...(title !== undefined ? { title } : {}),
|
|
584
|
+
...(description !== undefined ? { description } : {}),
|
|
585
|
+
...(mimeType !== undefined ? { mimeType } : {}),
|
|
586
|
+
...(size !== undefined ? { size } : {}),
|
|
587
|
+
...(annotations !== undefined ? { annotations } : {}),
|
|
588
|
+
...(meta !== undefined ? { _meta: meta } : {}),
|
|
589
|
+
};
|
|
590
|
+
const residual = Object.fromEntries(Object.entries(reduced).filter(([k]) => k !== "type" && k !== "uri" && !(RESOURCE_LINK_MEMBERS.has(k) && fitted[k] === true)));
|
|
591
|
+
return Object.keys(residual).length > 0 ? [block, { type: "provider-raw", vendor: "google", raw: residual }] : [block];
|
|
592
|
+
}
|
|
479
593
|
function functionResponseToToolDoneFields(name, response) {
|
|
480
594
|
if (response === undefined)
|
|
481
595
|
return { content: [] };
|
|
@@ -490,8 +604,17 @@ function functionResponseToToolDoneFields(name, response) {
|
|
|
490
604
|
out.push({ type: "text", text: part["text"] });
|
|
491
605
|
continue;
|
|
492
606
|
}
|
|
607
|
+
if (t === "resource_link") {
|
|
608
|
+
const link = resourceLinkBlocks(part);
|
|
609
|
+
if (link !== undefined) {
|
|
610
|
+
out.push(...link);
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
493
614
|
}
|
|
494
|
-
// Preserve any non-text MCP content part losslessly as a provider-raw
|
|
615
|
+
// Preserve any other non-text MCP content part losslessly as a provider-raw
|
|
616
|
+
// block (image, audio and embedded resource parts; a resource_link that
|
|
617
|
+
// is not MCP-schema-valid, see resourceLinkBlocks).
|
|
495
618
|
out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
|
|
496
619
|
}
|
|
497
620
|
const meta = response["_meta"];
|
|
@@ -884,21 +1007,34 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
|
|
|
884
1007
|
else
|
|
885
1008
|
pendingAsks.set(turnId, [ask]);
|
|
886
1009
|
}
|
|
887
|
-
function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved) {
|
|
1010
|
+
function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription) {
|
|
1011
|
+
// Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
|
|
1012
|
+
// a `finished: true` transcription whose text is the chunks joined
|
|
1013
|
+
// (utils/live_connection_utils.js, @google/adk 2.1.0). That aggregate is not
|
|
1014
|
+
// re-emitted when it repeats this turn's streamed chunks exactly, so the
|
|
1015
|
+
// turn's transcription reads once; one that differs rides as its own block.
|
|
888
1016
|
// typeof: a JSON-null transcription text is absent (null guard; it rode the
|
|
889
1017
|
// text block as `null`, which the schema rejects).
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1018
|
+
for (const [role, t] of [
|
|
1019
|
+
["input", event.inputTranscription],
|
|
1020
|
+
["output", event.outputTranscription],
|
|
1021
|
+
]) {
|
|
1022
|
+
if (typeof t?.text !== "string")
|
|
1023
|
+
continue;
|
|
1024
|
+
const key = `${turnId}\u0000${role}`;
|
|
1025
|
+
if (t.finished === true) {
|
|
1026
|
+
const streamed = streamedTranscription.get(key);
|
|
1027
|
+
streamedTranscription.delete(key);
|
|
1028
|
+
if (streamed === t.text)
|
|
1029
|
+
continue;
|
|
1030
|
+
}
|
|
1031
|
+
else {
|
|
1032
|
+
streamedTranscription.set(key, (streamedTranscription.get(key) ?? "") + t.text);
|
|
1033
|
+
}
|
|
898
1034
|
a.contentBlock(messageId, {
|
|
899
1035
|
type: "text",
|
|
900
|
-
text:
|
|
901
|
-
_meta: { "agjson/transcription": { role
|
|
1036
|
+
text: t.text,
|
|
1037
|
+
_meta: { "agjson/transcription": { role, kind: "transcription" } },
|
|
902
1038
|
});
|
|
903
1039
|
}
|
|
904
1040
|
// `interrupted` → turn.abort is closed in drive(), after this event's own
|
|
@@ -1177,12 +1313,10 @@ function hostErrorOf(raw) {
|
|
|
1177
1313
|
return undefined;
|
|
1178
1314
|
const usageRaw = Reflect.get(raw, "usage");
|
|
1179
1315
|
const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
|
|
1180
|
-
const invocationId = Reflect.get(raw, "invocationId");
|
|
1181
1316
|
return {
|
|
1182
1317
|
code,
|
|
1183
1318
|
message,
|
|
1184
1319
|
...(usage?.success === true ? { usage: usage.data } : {}),
|
|
1185
|
-
...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
|
|
1186
1320
|
};
|
|
1187
1321
|
}
|
|
1188
1322
|
catch {
|
|
@@ -1195,7 +1329,7 @@ function isHostCompleteNative(v) {
|
|
|
1195
1329
|
}
|
|
1196
1330
|
/**
|
|
1197
1331
|
* The google-adk Normalizer: the inner, deterministic normalizer below wrapped
|
|
1198
|
-
* in core's withAtomicPush (the
|
|
1332
|
+
* in core's withAtomicPush (the guard ruling). Every push() is atomic:
|
|
1199
1333
|
* - The native is read once as plain JSON through core's toJsonValueSafe, so a
|
|
1200
1334
|
* host may push the live Event objects ADK yields (undefined members, a
|
|
1201
1335
|
* Date, an Error, a cycle) and they map exactly like the recorded corpus.
|
|
@@ -1203,8 +1337,8 @@ function isHostCompleteNative(v) {
|
|
|
1203
1337
|
* inner members have unexpected types), its partial batch is discarded
|
|
1204
1338
|
* without consuming seq, the inner is rebuilt by re-driving every native
|
|
1205
1339
|
* accepted so far (the inner never reads the clock or randomness; ids come
|
|
1206
|
-
* from invocationId and per-invoke ordinals, and the
|
|
1207
|
-
*
|
|
1340
|
+
* from the per-invoke stem, invocationId and per-invoke ordinals, and the
|
|
1341
|
+
* stem is drawn once, outside the inner, and kept), and
|
|
1208
1342
|
* ONE core `error {message:
|
|
1209
1343
|
* "normalizer error", code: <constructor name>}` takes the next seq, with no
|
|
1210
1344
|
* payload and no message text.
|
|
@@ -1214,38 +1348,28 @@ function isHostCompleteNative(v) {
|
|
|
1214
1348
|
* message or block is open that never reached the wire.
|
|
1215
1349
|
*/
|
|
1216
1350
|
export function createAdkNormalizer(options = {}) {
|
|
1217
|
-
//
|
|
1218
|
-
//
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
const stem = {};
|
|
1222
|
-
return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
|
|
1351
|
+
// The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
|
|
1352
|
+
// re-drives to the same ids and no push() reads randomness.
|
|
1353
|
+
const invokeStem = options.invokeId ?? `adk_${mintInvokeNonce()}`;
|
|
1354
|
+
return withAtomicPush(() => createInnerAdkNormalizer(options, invokeStem));
|
|
1223
1355
|
}
|
|
1224
|
-
/**
|
|
1225
|
-
*
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
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)}`;
|
|
1356
|
+
/** 64 random bits as 16 hex chars: the default per-invoke id stem (as the
|
|
1357
|
+
* vercel, openai and claude facets draw theirs). */
|
|
1358
|
+
function mintInvokeNonce() {
|
|
1359
|
+
const bytes = new Uint8Array(8);
|
|
1360
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1361
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1242
1362
|
}
|
|
1243
|
-
function createInnerAdkNormalizer(options,
|
|
1363
|
+
function createInnerAdkNormalizer(options, invokeStem) {
|
|
1244
1364
|
const hostCompletion = options.hostCompletion === true;
|
|
1245
1365
|
const a = new StreamAssembler();
|
|
1246
|
-
const threadId = "google";
|
|
1366
|
+
const threadId = options.threadId ?? "google";
|
|
1247
1367
|
// §8.3 per-instance accumulator (replaces the module-level streamedText Map):
|
|
1248
1368
|
const streamedText = new Map();
|
|
1369
|
+
// Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
|
|
1370
|
+
const streamedTranscription = new Map();
|
|
1371
|
+
// Per turn: the Live usage reports' modality details, one entry per report.
|
|
1372
|
+
const usageDetailsByTurn = new Map();
|
|
1249
1373
|
const openTurns = new Set();
|
|
1250
1374
|
const closedTurns = new Set();
|
|
1251
1375
|
// Per-turn usageMetadata accumulator (2026-07-13, echo-gemini35 live-capture
|
|
@@ -1278,6 +1402,15 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1278
1402
|
// so the close waits for the next non-partial event of the turn, or for
|
|
1279
1403
|
// flush() / host completion.
|
|
1280
1404
|
const interruptPending = new Set();
|
|
1405
|
+
// Live generations. One live session is one ADK invocation, so one turn key
|
|
1406
|
+
// spans every model generation of the session. ADK delivers a barge-in's
|
|
1407
|
+
// flag FIRST, then the interrupted generation's own usageMetadata and
|
|
1408
|
+
// turnComplete, then the reply generation (a gemini-3.8-live capture
|
|
1409
|
+
// `live-bargein-gemini38live`). So an interrupted generation closes on its own
|
|
1410
|
+
// turnComplete (closeInterrupted), and the next generation after a barge-in
|
|
1411
|
+
// opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
|
|
1412
|
+
const generationOf = new Map();
|
|
1413
|
+
const interruptClosed = new Set();
|
|
1281
1414
|
const pendingLongRunning = new Map();
|
|
1282
1415
|
const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
|
|
1283
1416
|
// Null-id call mint state (audit M47) — per-invoke ordinal counter + the
|
|
@@ -1488,10 +1621,6 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1488
1621
|
* complete. With no turn open, a fresh terminal turn carries the error, so
|
|
1489
1622
|
* it is never start-less. */
|
|
1490
1623
|
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
1624
|
function hostError(err) {
|
|
1496
1625
|
let closed = 0;
|
|
1497
1626
|
for (const turnId of [...openTurns].reverse()) {
|
|
@@ -1505,8 +1634,7 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1505
1634
|
}
|
|
1506
1635
|
if (closed > 0)
|
|
1507
1636
|
return;
|
|
1508
|
-
const
|
|
1509
|
-
const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
|
|
1637
|
+
const turnId = `turn_${invokeStem}_host_error_${hostErrorTurns++}`;
|
|
1510
1638
|
const messageId = ensureOpen(turnId);
|
|
1511
1639
|
closedTurns.add(turnId);
|
|
1512
1640
|
a.closeMessage(messageId);
|
|
@@ -1517,9 +1645,13 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1517
1645
|
});
|
|
1518
1646
|
}
|
|
1519
1647
|
function drive(event) {
|
|
1520
|
-
const
|
|
1521
|
-
|
|
1522
|
-
|
|
1648
|
+
const turnId = liveTurnFor(event);
|
|
1649
|
+
// ADK re-yields a bare `{interrupted}` after a message that carried both
|
|
1650
|
+
// turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
|
|
1651
|
+
// 2.1.0). For a generation the barge-in already closed, it adds nothing:
|
|
1652
|
+
// no new turn and no second terminal, so the facet emits nothing for it.
|
|
1653
|
+
if (turnId === undefined)
|
|
1654
|
+
return;
|
|
1523
1655
|
const messageId = ensureOpen(turnId);
|
|
1524
1656
|
const parts = event.content?.parts ?? [];
|
|
1525
1657
|
const isPartial = event.partial === true;
|
|
@@ -1566,7 +1698,7 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1566
1698
|
nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
|
|
1567
1699
|
});
|
|
1568
1700
|
// §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
|
|
1569
|
-
const alreadyStreamed = streamedText.get(
|
|
1701
|
+
const alreadyStreamed = streamedText.get(turnId) ?? "";
|
|
1570
1702
|
const isAggregate = !isPartial && alreadyStreamed.length > 0;
|
|
1571
1703
|
const aggregateText = isAggregate
|
|
1572
1704
|
? parts
|
|
@@ -1610,9 +1742,9 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1610
1742
|
accumulated += contributed;
|
|
1611
1743
|
});
|
|
1612
1744
|
if (isPartial)
|
|
1613
|
-
streamedText.set(
|
|
1745
|
+
streamedText.set(turnId, accumulated);
|
|
1614
1746
|
else if (isAggregate)
|
|
1615
|
-
streamedText.delete(
|
|
1747
|
+
streamedText.delete(turnId);
|
|
1616
1748
|
// Round-3 review finding (regression on finding b): the resend window's
|
|
1617
1749
|
// lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
|
|
1618
1750
|
// (see the `ToolCallMintState` doc above) already clears each null-id
|
|
@@ -1628,15 +1760,56 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1628
1760
|
// per-invoke.
|
|
1629
1761
|
if (!isPartial)
|
|
1630
1762
|
trackLongRunning(event, turnId);
|
|
1631
|
-
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
|
|
1763
|
+
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
|
|
1632
1764
|
// A turn gets ONE terminal: an interrupt on a turn that already closed
|
|
1633
1765
|
// (a second barge-in, or one after a success close) adds none.
|
|
1634
1766
|
if (event.interrupted === true && !closedTurns.has(turnId))
|
|
1635
1767
|
interruptPending.add(turnId);
|
|
1768
|
+
carryLiveUsageDetails(event, turnId, messageId, isPartial);
|
|
1636
1769
|
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
1637
|
-
|
|
1770
|
+
// The interrupted generation closes on its own turnComplete (its trailing
|
|
1771
|
+
// usageMetadata arrives before it), or at flush() / host completion.
|
|
1772
|
+
if (!isPartial && event.turnComplete === true && interruptPending.has(turnId))
|
|
1638
1773
|
closeInterrupted(turnId);
|
|
1639
1774
|
}
|
|
1775
|
+
/** Gemini Live prices per modality (text vs audio), so its usage reports'
|
|
1776
|
+
* `promptTokensDetails` / `responseTokensDetails` ride the message's
|
|
1777
|
+
* metadata (a `message.metadata` event, key `usageDetails`), one entry per report, verbatim and never
|
|
1778
|
+
* summed. Each report re-emits the whole list (message metadata folds by
|
|
1779
|
+
* key, so the last emission holds every report). The list is the TURN's,
|
|
1780
|
+
* like the turn-summed `usage`, and rides the turn's current message; a turn
|
|
1781
|
+
* with more than one message carries it on the later one. Live path only
|
|
1782
|
+
* (`responseTokenCount` present): generateContent streams are unchanged. */
|
|
1783
|
+
function carryLiveUsageDetails(event, turnId, messageId, isPartial) {
|
|
1784
|
+
const um = event.usageMetadata;
|
|
1785
|
+
if (isPartial || um === undefined || um.responseTokenCount === undefined || um.candidatesTokenCount !== undefined)
|
|
1786
|
+
return;
|
|
1787
|
+
const entry = {
|
|
1788
|
+
...(um.promptTokensDetails !== undefined ? { promptTokensDetails: um.promptTokensDetails } : {}),
|
|
1789
|
+
...(um.responseTokensDetails !== undefined ? { responseTokensDetails: um.responseTokensDetails } : {}),
|
|
1790
|
+
};
|
|
1791
|
+
if (Object.keys(entry).length === 0)
|
|
1792
|
+
return;
|
|
1793
|
+
const list = [...(usageDetailsByTurn.get(turnId) ?? []), entry];
|
|
1794
|
+
usageDetailsByTurn.set(turnId, list);
|
|
1795
|
+
a.emit({ type: "message.metadata", messageId, metadata: { usageDetails: list } });
|
|
1796
|
+
}
|
|
1797
|
+
/** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
|
|
1798
|
+
* key), with `_g<n>` for the n-th generation after a barge-in closed the
|
|
1799
|
+
* previous one. `undefined` for ADK's bare `{interrupted}` re-yield on a
|
|
1800
|
+
* generation a barge-in already closed. */
|
|
1801
|
+
function liveTurnFor(event) {
|
|
1802
|
+
const key = turnKey(event);
|
|
1803
|
+
const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
|
|
1804
|
+
const g = generationOf.get(base) ?? 0;
|
|
1805
|
+
const current = g === 0 ? base : `${base}_g${g}`;
|
|
1806
|
+
if (!interruptClosed.has(current))
|
|
1807
|
+
return current;
|
|
1808
|
+
if (event.interrupted === true && !hasLiveContent(event))
|
|
1809
|
+
return undefined;
|
|
1810
|
+
generationOf.set(base, g + 1);
|
|
1811
|
+
return `${base}_g${g + 1}`;
|
|
1812
|
+
}
|
|
1640
1813
|
/** interrupted → turn.abort, after the event's own content and carries and
|
|
1641
1814
|
* after its message.end (INV-MSG: nothing of the turn follows its terminal).
|
|
1642
1815
|
* The turn is marked closed in the facet's own bookkeeping too (audit M21),
|
|
@@ -1644,6 +1817,7 @@ function createInnerAdkNormalizer(options, stem) {
|
|
|
1644
1817
|
* message.end carries the turn's accumulated usage, as flush()'s does. */
|
|
1645
1818
|
function closeInterrupted(turnId) {
|
|
1646
1819
|
interruptPending.delete(turnId);
|
|
1820
|
+
interruptClosed.add(turnId);
|
|
1647
1821
|
closedTurns.add(turnId);
|
|
1648
1822
|
a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
|
|
1649
1823
|
a.emit({ type: "turn.abort", turnId, reason: "interrupted" });
|