@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/src/index.ts
CHANGED
|
@@ -49,30 +49,34 @@
|
|
|
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
81
|
import {
|
|
78
82
|
type AgEvent,
|
|
@@ -85,6 +89,7 @@ import {
|
|
|
85
89
|
type AgSafety,
|
|
86
90
|
AgUsage,
|
|
87
91
|
AgProviderMeta,
|
|
92
|
+
AgResourceLinkBlock,
|
|
88
93
|
JsonValue,
|
|
89
94
|
type Normalizer,
|
|
90
95
|
StreamAssembler,
|
|
@@ -250,7 +255,9 @@ export interface AdkEvent {
|
|
|
250
255
|
skipSummarization?: boolean;
|
|
251
256
|
/** Transfer control to another named agent. */
|
|
252
257
|
transferToAgent?: string;
|
|
253
|
-
/**
|
|
258
|
+
/** "The agent is escalating to a higher level agent" (ADK's declaration,
|
|
259
|
+
* events/event_actions.d.ts): the exit_loop tool sets it, and a LoopAgent
|
|
260
|
+
* stops iterating on it. */
|
|
254
261
|
escalate?: boolean;
|
|
255
262
|
/** Request OAuth/auth configs from the caller. ADK serializes this as a
|
|
256
263
|
* dict keyed by the function-call-id (`dict[str, AuthConfig]`); the value
|
|
@@ -292,6 +299,11 @@ export interface AdkEvent {
|
|
|
292
299
|
cachedContentTokenCount?: number;
|
|
293
300
|
thoughtsTokenCount?: number;
|
|
294
301
|
toolUsePromptTokenCount?: number;
|
|
302
|
+
/** Gemini Live's output counter, in place of `candidatesTokenCount`. */
|
|
303
|
+
responseTokenCount?: number;
|
|
304
|
+
/** Per-modality token counts (carried verbatim on the Live path only). */
|
|
305
|
+
promptTokensDetails?: JsonValue;
|
|
306
|
+
responseTokensDetails?: JsonValue;
|
|
295
307
|
};
|
|
296
308
|
/** Per-part safety ratings from the Gemini Candidate. */
|
|
297
309
|
safetyRatings?: Array<{
|
|
@@ -338,9 +350,9 @@ export interface AdkEvent {
|
|
|
338
350
|
/** ISO timestamp of the event. */
|
|
339
351
|
timestamp?: string;
|
|
340
352
|
/** Speech-to-text transcription of the user's audio input. */
|
|
341
|
-
inputTranscription?: { text?: string };
|
|
353
|
+
inputTranscription?: { text?: string; finished?: boolean };
|
|
342
354
|
/** Text-to-speech transcription of the model's audio output. */
|
|
343
|
-
outputTranscription?: { text?: string };
|
|
355
|
+
outputTranscription?: { text?: string; finished?: boolean };
|
|
344
356
|
/** Opaque per-event custom metadata bag. */
|
|
345
357
|
customMetadata?: { [k: string]: JsonValue };
|
|
346
358
|
/** Index of the candidate response (meaningful when the request's
|
|
@@ -509,7 +521,16 @@ function isAdkEvent(v: unknown): v is AdkEvent {
|
|
|
509
521
|
* inclusive on that endpoint — carry it as-is, never add twice. A thoughts-free
|
|
510
522
|
* usageMetadata normalizes byte-identically to draft.2. `reasoningTokens` stays
|
|
511
523
|
* the breakdown (`thoughtsTokenCount` verbatim); `totalTokens` is copied, never
|
|
512
|
-
* computed
|
|
524
|
+
* computed, with ONE exception, the Gemini Live API (draft.5): Live reports its
|
|
525
|
+
* output as `responseTokenCount`, and its `totalTokenCount` may leave thoughts
|
|
526
|
+
* out (609 + 25 = 634 with 256 thoughts beside them), so thoughts always fold
|
|
527
|
+
* into outputTokens there. Where Live reports a total, `totalTokens` is
|
|
528
|
+
* derived as input + output + toolUseInput over the turn's summed counters,
|
|
529
|
+
* and Google's own summed total rides `totalTokensRaw` only where it differs;
|
|
530
|
+
* with no reported total, neither is emitted. This facet recognises the Live
|
|
531
|
+
* API by the field: `responseTokenCount` appears only on @google/genai's Live
|
|
532
|
+
* UsageMetadata. A normalizer reading the raw Vertex Live wire decides by the
|
|
533
|
+
* API, not by the field name. Known upstream gap: @google/adk's Interactions-API route synthesizes
|
|
513
534
|
* usageMetadata WITHOUT thoughts (candidates = total_output_tokens, total =
|
|
514
535
|
* in + out), so on that route outputTokens is exclusive and reasoningTokens
|
|
515
536
|
* absent — nothing the facet can recover (see README).
|
|
@@ -521,7 +542,15 @@ function mapUsage(um: AdkEvent["usageMetadata"]): AgUsage | undefined {
|
|
|
521
542
|
if (um === undefined) return undefined;
|
|
522
543
|
const candidates = um.candidatesTokenCount;
|
|
523
544
|
const thoughts = um.thoughtsTokenCount;
|
|
545
|
+
// Gemini Live reports its output as `responseTokenCount`, and its total is
|
|
546
|
+
// prompt + response, EXCLUDING thoughts (the capture
|
|
547
|
+
// live-bargein-gemini38live: 609 + 25 = 634, with 256 thoughts beside them).
|
|
548
|
+
// So on Live the total cannot show whether thoughts are included, and they
|
|
549
|
+
// always fold in: outputTokens = response + thoughts (SPEC §4 inclusion).
|
|
550
|
+
const response = candidates === undefined ? um.responseTokenCount : undefined;
|
|
551
|
+
const generated = candidates ?? response;
|
|
524
552
|
const alreadyInclusive =
|
|
553
|
+
response === undefined &&
|
|
525
554
|
candidates !== undefined &&
|
|
526
555
|
thoughts !== undefined &&
|
|
527
556
|
thoughts > 0 &&
|
|
@@ -529,15 +558,26 @@ function mapUsage(um: AdkEvent["usageMetadata"]): AgUsage | undefined {
|
|
|
529
558
|
um.promptTokenCount !== undefined &&
|
|
530
559
|
um.promptTokenCount + (candidates ?? 0) + (um.toolUsePromptTokenCount ?? 0) === um.totalTokenCount;
|
|
531
560
|
const outputTokens =
|
|
532
|
-
|
|
561
|
+
generated === undefined && thoughts === undefined
|
|
533
562
|
? undefined
|
|
534
563
|
: alreadyInclusive
|
|
535
564
|
? candidates
|
|
536
|
-
: (
|
|
565
|
+
: (generated ?? 0) + (thoughts ?? 0);
|
|
566
|
+
// On the Live path the total is derived, and Google's figure is kept beside
|
|
567
|
+
// it only where it differs; elsewhere the provider's total is copied.
|
|
568
|
+
const totalTokens =
|
|
569
|
+
response !== undefined && um.totalTokenCount !== undefined
|
|
570
|
+
? (um.promptTokenCount ?? 0) + (outputTokens ?? 0) + (um.toolUsePromptTokenCount ?? 0)
|
|
571
|
+
: um.totalTokenCount;
|
|
572
|
+
const totalTokensRaw =
|
|
573
|
+
response !== undefined && um.totalTokenCount !== undefined && um.totalTokenCount !== totalTokens
|
|
574
|
+
? um.totalTokenCount
|
|
575
|
+
: undefined;
|
|
537
576
|
return {
|
|
538
577
|
...(um.promptTokenCount !== undefined ? { inputTokens: um.promptTokenCount } : {}),
|
|
539
578
|
...(outputTokens !== undefined ? { outputTokens } : {}),
|
|
540
|
-
...(
|
|
579
|
+
...(totalTokens !== undefined ? { totalTokens } : {}),
|
|
580
|
+
...(totalTokensRaw !== undefined ? { totalTokensRaw } : {}),
|
|
541
581
|
...(um.cachedContentTokenCount !== undefined
|
|
542
582
|
? { cacheReadTokens: um.cachedContentTokenCount }
|
|
543
583
|
: {}),
|
|
@@ -558,6 +598,7 @@ const USAGE_SUM_FIELDS = [
|
|
|
558
598
|
"cachedContentTokenCount",
|
|
559
599
|
"thoughtsTokenCount",
|
|
560
600
|
"toolUsePromptTokenCount",
|
|
601
|
+
"responseTokenCount",
|
|
561
602
|
] as const;
|
|
562
603
|
|
|
563
604
|
/** Fold one event's usageMetadata into a turn's running accumulator
|
|
@@ -790,9 +831,16 @@ function isAdkPauseEnd(event: AdkEvent): boolean {
|
|
|
790
831
|
);
|
|
791
832
|
}
|
|
792
833
|
|
|
834
|
+
/** Whether an event carries any content of a generation: a part, or an input
|
|
835
|
+
* or output transcription. */
|
|
836
|
+
function hasLiveContent(ev: AdkEvent): boolean {
|
|
837
|
+
return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
|
|
838
|
+
}
|
|
839
|
+
|
|
793
840
|
/** The event's own turn key: its invocationId, else its id. `undefined` when it
|
|
794
|
-
* has neither; the
|
|
795
|
-
* never a
|
|
841
|
+
* has neither; the turn is then named from the per-invoke stem alone. The key
|
|
842
|
+
* is never a turn id by itself: ADK-Python's resumable resume reuses
|
|
843
|
+
* `invocation_id`, so every turn id carries the per-invoke stem too. */
|
|
796
844
|
function turnKey(ev: AdkEvent): string | undefined {
|
|
797
845
|
if (ev.invocationId && ev.invocationId.length > 0) return ev.invocationId;
|
|
798
846
|
return ev.id !== undefined && ev.id !== null && ev.id.length > 0 ? ev.id : undefined;
|
|
@@ -805,7 +853,7 @@ function turnKey(ev: AdkEvent): string | undefined {
|
|
|
805
853
|
// restore name+position correlation when echoing functionResponse parts.
|
|
806
854
|
|
|
807
855
|
// ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
|
|
808
|
-
// adk-10,
|
|
856
|
+
// adk-10, ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
|
|
809
857
|
// answers a failed tool call with a response carrying Gemini's documented
|
|
810
858
|
// `error` key: an unresolvable tool name (functions.js:264), a thrown tool
|
|
811
859
|
// including a thrown MCP call (functions.js:282), several built-in tools.
|
|
@@ -896,6 +944,87 @@ interface FunctionResponseToolDoneFields {
|
|
|
896
944
|
structuredContent?: JsonValue;
|
|
897
945
|
_meta?: AgMeta;
|
|
898
946
|
}
|
|
947
|
+
/** Sorted-key JSON: "does parsing change this value" compares members, not
|
|
948
|
+
* the order a schema writes them in. */
|
|
949
|
+
function canonicalJson(v: JsonValue): string {
|
|
950
|
+
if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;
|
|
951
|
+
if (!isJsonObject(v)) return JSON.stringify(v);
|
|
952
|
+
return `{${Object.keys(v)
|
|
953
|
+
.sort()
|
|
954
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
|
|
955
|
+
.join(",")}}`;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/** A native member that fits the resource-link block: core's own schema for
|
|
959
|
+
* that member accepts it AND leaves it unchanged, so the block carries it
|
|
960
|
+
* verbatim. `undefined` when it does not fit (it then rides the residual). */
|
|
961
|
+
function fitMember<T>(
|
|
962
|
+
parse: (v: unknown) => { success: true; data: T } | { success: false },
|
|
963
|
+
v: JsonValue | undefined,
|
|
964
|
+
): T | undefined {
|
|
965
|
+
if (v === undefined) return undefined;
|
|
966
|
+
const r = parse(v);
|
|
967
|
+
if (!r.success || r.data === undefined) return undefined;
|
|
968
|
+
const back = JsonValue.safeParse(r.data);
|
|
969
|
+
return back.success && canonicalJson(back.data) === canonicalJson(v) ? r.data : undefined;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const RESOURCE_LINK_MEMBERS: ReadonlySet<string> = new Set(["name", "title", "description", "mimeType", "size", "annotations", "_meta"]);
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* SPEC §8.0 item 31 (draft.5): an MCP `resource_link` content part of a tool
|
|
976
|
+
* result becomes ONE `resource-link` block carrying its native `uri`, `name`,
|
|
977
|
+
* `title`, `description`, `mimeType`, `size`, `annotations` and `_meta`
|
|
978
|
+
* verbatim where present, after item 28's reductions (applied as for a
|
|
979
|
+
* provider-raw carry; a `uri` is neither a credential object nor a
|
|
980
|
+
* credential-request response, so it passes unchanged, signed query included).
|
|
981
|
+
* The members the block cannot hold (a member it does not define, such as
|
|
982
|
+
* `icons`, or a defined one whose native value core's schema rejects or would
|
|
983
|
+
* alter) ride exactly one provider-raw block right after it, carrying only
|
|
984
|
+
* those members; with none, no such block is emitted.
|
|
985
|
+
*
|
|
986
|
+
* Item 31 binds MCP-schema-valid `resource_link` parts. A part without a string
|
|
987
|
+
* `uri` fails MCP's own schema (uri is required): it is an unmappable part, so
|
|
988
|
+
* §8.0's graceful degradation applies, and it stays one reduced provider-raw
|
|
989
|
+
* (`undefined` here), never dropped and never forced into a uri-less block.
|
|
990
|
+
*/
|
|
991
|
+
function resourceLinkBlocks(part: { readonly [k: string]: JsonValue }): AgBlock[] | undefined {
|
|
992
|
+
const reduced = reduceCarried(part);
|
|
993
|
+
if (!isJsonObject(reduced) || typeof reduced["uri"] !== "string") return undefined;
|
|
994
|
+
const S = AgResourceLinkBlock.shape;
|
|
995
|
+
const name = fitMember((v) => S.name.safeParse(v), reduced["name"]);
|
|
996
|
+
const title = fitMember((v) => S.title.safeParse(v), reduced["title"]);
|
|
997
|
+
const description = fitMember((v) => S.description.safeParse(v), reduced["description"]);
|
|
998
|
+
const mimeType = fitMember((v) => S.mimeType.safeParse(v), reduced["mimeType"]);
|
|
999
|
+
const size = fitMember((v) => S.size.safeParse(v), reduced["size"]);
|
|
1000
|
+
const annotations = fitMember((v) => S.annotations.safeParse(v), reduced["annotations"]);
|
|
1001
|
+
const meta = fitMember((v) => S._meta.safeParse(v), reduced["_meta"]);
|
|
1002
|
+
const fitted: { readonly [k: string]: boolean } = {
|
|
1003
|
+
name: name !== undefined,
|
|
1004
|
+
title: title !== undefined,
|
|
1005
|
+
description: description !== undefined,
|
|
1006
|
+
mimeType: mimeType !== undefined,
|
|
1007
|
+
size: size !== undefined,
|
|
1008
|
+
annotations: annotations !== undefined,
|
|
1009
|
+
_meta: meta !== undefined,
|
|
1010
|
+
};
|
|
1011
|
+
const block: AgBlock = {
|
|
1012
|
+
type: "resource-link",
|
|
1013
|
+
uri: reduced["uri"],
|
|
1014
|
+
...(name !== undefined ? { name } : {}),
|
|
1015
|
+
...(title !== undefined ? { title } : {}),
|
|
1016
|
+
...(description !== undefined ? { description } : {}),
|
|
1017
|
+
...(mimeType !== undefined ? { mimeType } : {}),
|
|
1018
|
+
...(size !== undefined ? { size } : {}),
|
|
1019
|
+
...(annotations !== undefined ? { annotations } : {}),
|
|
1020
|
+
...(meta !== undefined ? { _meta: meta } : {}),
|
|
1021
|
+
};
|
|
1022
|
+
const residual = Object.fromEntries(
|
|
1023
|
+
Object.entries(reduced).filter(([k]) => k !== "type" && k !== "uri" && !(RESOURCE_LINK_MEMBERS.has(k) && fitted[k] === true)),
|
|
1024
|
+
);
|
|
1025
|
+
return Object.keys(residual).length > 0 ? [block, { type: "provider-raw", vendor: "google", raw: residual }] : [block];
|
|
1026
|
+
}
|
|
1027
|
+
|
|
899
1028
|
function functionResponseToToolDoneFields(
|
|
900
1029
|
name: string,
|
|
901
1030
|
response: { [k: string]: JsonValue } | undefined,
|
|
@@ -912,8 +1041,17 @@ function functionResponseToToolDoneFields(
|
|
|
912
1041
|
out.push({ type: "text", text: part["text"] });
|
|
913
1042
|
continue;
|
|
914
1043
|
}
|
|
1044
|
+
if (t === "resource_link") {
|
|
1045
|
+
const link = resourceLinkBlocks(part);
|
|
1046
|
+
if (link !== undefined) {
|
|
1047
|
+
out.push(...link);
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
915
1051
|
}
|
|
916
|
-
// Preserve any non-text MCP content part losslessly as a provider-raw
|
|
1052
|
+
// Preserve any other non-text MCP content part losslessly as a provider-raw
|
|
1053
|
+
// block (image, audio and embedded resource parts; a resource_link that
|
|
1054
|
+
// is not MCP-schema-valid, see resourceLinkBlocks).
|
|
917
1055
|
out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
|
|
918
1056
|
}
|
|
919
1057
|
const meta = response["_meta"];
|
|
@@ -1449,22 +1587,33 @@ function driveAdkTopLevel(
|
|
|
1449
1587
|
messageId: string,
|
|
1450
1588
|
turnId: string,
|
|
1451
1589
|
pendingAsks: Map<string, AgPausedAsk[]>,
|
|
1452
|
-
reserved: ReservedAskState
|
|
1590
|
+
reserved: ReservedAskState,
|
|
1591
|
+
streamedTranscription: Map<string, string>
|
|
1453
1592
|
): void {
|
|
1593
|
+
// Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
|
|
1594
|
+
// a `finished: true` transcription whose text is the chunks joined
|
|
1595
|
+
// (utils/live_connection_utils.js, @google/adk 2.1.0). That aggregate is not
|
|
1596
|
+
// re-emitted when it repeats this turn's streamed chunks exactly, so the
|
|
1597
|
+
// turn's transcription reads once; one that differs rides as its own block.
|
|
1454
1598
|
// typeof: a JSON-null transcription text is absent (null guard; it rode the
|
|
1455
1599
|
// text block as `null`, which the schema rejects).
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
}
|
|
1462
|
-
|
|
1463
|
-
|
|
1600
|
+
for (const [role, t] of [
|
|
1601
|
+
["input", event.inputTranscription],
|
|
1602
|
+
["output", event.outputTranscription],
|
|
1603
|
+
] as const) {
|
|
1604
|
+
if (typeof t?.text !== "string") continue;
|
|
1605
|
+
const key = `${turnId}\u0000${role}`;
|
|
1606
|
+
if (t.finished === true) {
|
|
1607
|
+
const streamed = streamedTranscription.get(key);
|
|
1608
|
+
streamedTranscription.delete(key);
|
|
1609
|
+
if (streamed === t.text) continue;
|
|
1610
|
+
} else {
|
|
1611
|
+
streamedTranscription.set(key, (streamedTranscription.get(key) ?? "") + t.text);
|
|
1612
|
+
}
|
|
1464
1613
|
a.contentBlock(messageId, {
|
|
1465
1614
|
type: "text",
|
|
1466
|
-
text:
|
|
1467
|
-
_meta: { "agjson/transcription": { role
|
|
1615
|
+
text: t.text,
|
|
1616
|
+
_meta: { "agjson/transcription": { role, kind: "transcription" } },
|
|
1468
1617
|
});
|
|
1469
1618
|
}
|
|
1470
1619
|
|
|
@@ -1719,6 +1868,35 @@ export interface AdkNormalizerOptions {
|
|
|
1719
1868
|
* else `success`. Default off: the step-1 behaviour.
|
|
1720
1869
|
*/
|
|
1721
1870
|
hostCompletion?: boolean;
|
|
1871
|
+
/**
|
|
1872
|
+
* The host's thread id (SPEC §1.2, the partition root), stamped on every
|
|
1873
|
+
* `turn.start` and assistant `message.start` of this invoke. An ADK `Event`
|
|
1874
|
+
* carries no thread or session id, so without it the facet stamps the fixed
|
|
1875
|
+
* label `"google"`, a facet-local placeholder, not a partition root. A host
|
|
1876
|
+
* that persists by `threadId` supplies its own.
|
|
1877
|
+
*/
|
|
1878
|
+
threadId?: string;
|
|
1879
|
+
/**
|
|
1880
|
+
* The stem this invoke's ids are minted from: a turn id is
|
|
1881
|
+
* `turn_<invokeId>_<key>`, where `<key>` is the event's `invocationId`, else
|
|
1882
|
+
* its `id`; an event with neither is `turn_<invokeId>`, and a host error with
|
|
1883
|
+
* no turn open is `turn_<invokeId>_host_error_<n>`. On the Live path, the
|
|
1884
|
+
* n-th generation after a barge-in adds `_g<n>`. Message ids are
|
|
1885
|
+
* `msg_<turnId>`.
|
|
1886
|
+
*
|
|
1887
|
+
* Turn and message ids must be unique across every invoke folded into one
|
|
1888
|
+
* reducer (SPEC §8.0 "Ids across invokes"; a repeated turn id re-opens a
|
|
1889
|
+
* closed turn, which INV-MSG parks). ADK's `invocationId` is not enough on its
|
|
1890
|
+
* own: ADK-Python's resumable resume reuses it. By default each normalizer
|
|
1891
|
+
* draws a fresh `adk_<16 hex>` stem from `crypto.getRandomValues`, ONCE, at
|
|
1892
|
+
* construction and outside the atomic inner factory, so a `withAtomicPush`
|
|
1893
|
+
* rebuild mints the SAME ids.
|
|
1894
|
+
*
|
|
1895
|
+
* Pass one to make the output deterministic (replay, capture, tests). A host
|
|
1896
|
+
* that passes one MUST keep it unique per invoke within a fold. This mirrors
|
|
1897
|
+
* the vercel, openai and claude facets' `invokeId`.
|
|
1898
|
+
*/
|
|
1899
|
+
invokeId?: string;
|
|
1722
1900
|
}
|
|
1723
1901
|
|
|
1724
1902
|
/** The facet-local host-completion native (§8.0 host obligation 4). */
|
|
@@ -1739,9 +1917,6 @@ interface AdkHostError {
|
|
|
1739
1917
|
code: string;
|
|
1740
1918
|
message: string;
|
|
1741
1919
|
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
1920
|
}
|
|
1746
1921
|
|
|
1747
1922
|
/** The host-error sentinel, read from the RAW native (an Error's message is
|
|
@@ -1756,12 +1931,10 @@ function hostErrorOf(raw: unknown): AdkHostError | undefined {
|
|
|
1756
1931
|
if (typeof code !== "string" || typeof message !== "string") return undefined;
|
|
1757
1932
|
const usageRaw: unknown = Reflect.get(raw, "usage");
|
|
1758
1933
|
const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
|
|
1759
|
-
const invocationId: unknown = Reflect.get(raw, "invocationId");
|
|
1760
1934
|
return {
|
|
1761
1935
|
code,
|
|
1762
1936
|
message,
|
|
1763
1937
|
...(usage?.success === true ? { usage: usage.data } : {}),
|
|
1764
|
-
...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
|
|
1765
1938
|
};
|
|
1766
1939
|
} catch {
|
|
1767
1940
|
return undefined;
|
|
@@ -1775,7 +1948,7 @@ function isHostCompleteNative(v: JsonValue): boolean {
|
|
|
1775
1948
|
|
|
1776
1949
|
/**
|
|
1777
1950
|
* The google-adk Normalizer: the inner, deterministic normalizer below wrapped
|
|
1778
|
-
* in core's withAtomicPush (the
|
|
1951
|
+
* in core's withAtomicPush (the guard ruling). Every push() is atomic:
|
|
1779
1952
|
* - The native is read once as plain JSON through core's toJsonValueSafe, so a
|
|
1780
1953
|
* host may push the live Event objects ADK yields (undefined members, a
|
|
1781
1954
|
* Date, an Error, a cycle) and they map exactly like the recorded corpus.
|
|
@@ -1783,8 +1956,8 @@ function isHostCompleteNative(v: JsonValue): boolean {
|
|
|
1783
1956
|
* inner members have unexpected types), its partial batch is discarded
|
|
1784
1957
|
* without consuming seq, the inner is rebuilt by re-driving every native
|
|
1785
1958
|
* accepted so far (the inner never reads the clock or randomness; ids come
|
|
1786
|
-
* from invocationId and per-invoke ordinals, and the
|
|
1787
|
-
*
|
|
1959
|
+
* from the per-invoke stem, invocationId and per-invoke ordinals, and the
|
|
1960
|
+
* stem is drawn once, outside the inner, and kept), and
|
|
1788
1961
|
* ONE core `error {message:
|
|
1789
1962
|
* "normalizer error", code: <constructor name>}` takes the next seq, with no
|
|
1790
1963
|
* payload and no message text.
|
|
@@ -1794,44 +1967,30 @@ function isHostCompleteNative(v: JsonValue): boolean {
|
|
|
1794
1967
|
* message or block is open that never reached the wire.
|
|
1795
1968
|
*/
|
|
1796
1969
|
export function createAdkNormalizer(options: AdkNormalizerOptions = {}): Normalizer {
|
|
1797
|
-
//
|
|
1798
|
-
//
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
const stem: IdStem = {};
|
|
1802
|
-
return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
|
|
1970
|
+
// The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
|
|
1971
|
+
// re-drives to the same ids and no push() reads randomness.
|
|
1972
|
+
const invokeStem = options.invokeId ?? `adk_${mintInvokeNonce()}`;
|
|
1973
|
+
return withAtomicPush(() => createInnerAdkNormalizer(options, invokeStem));
|
|
1803
1974
|
}
|
|
1804
1975
|
|
|
1805
|
-
/**
|
|
1806
|
-
|
|
1807
|
-
|
|
1976
|
+
/** 64 random bits as 16 hex chars: the default per-invoke id stem (as the
|
|
1977
|
+
* vercel, openai and claude facets draw theirs). */
|
|
1978
|
+
function mintInvokeNonce(): string {
|
|
1979
|
+
const bytes = new Uint8Array(8);
|
|
1980
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1981
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1808
1982
|
}
|
|
1809
1983
|
|
|
1810
|
-
|
|
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 {
|
|
1984
|
+
function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: string): Normalizer {
|
|
1830
1985
|
const hostCompletion = options.hostCompletion === true;
|
|
1831
1986
|
const a = new StreamAssembler();
|
|
1832
|
-
const threadId = "google";
|
|
1987
|
+
const threadId = options.threadId ?? "google";
|
|
1833
1988
|
// §8.3 per-instance accumulator (replaces the module-level streamedText Map):
|
|
1834
1989
|
const streamedText = new Map<string, string>();
|
|
1990
|
+
// Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
|
|
1991
|
+
const streamedTranscription = new Map<string, string>();
|
|
1992
|
+
// Per turn: the Live usage reports' modality details, one entry per report.
|
|
1993
|
+
const usageDetailsByTurn = new Map<string, JsonValue[]>();
|
|
1835
1994
|
const openTurns = new Set<string>();
|
|
1836
1995
|
const closedTurns = new Set<string>();
|
|
1837
1996
|
// Per-turn usageMetadata accumulator (2026-07-13, echo-gemini35 live-capture
|
|
@@ -1864,6 +2023,15 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
1864
2023
|
// so the close waits for the next non-partial event of the turn, or for
|
|
1865
2024
|
// flush() / host completion.
|
|
1866
2025
|
const interruptPending = new Set<string>();
|
|
2026
|
+
// Live generations. One live session is one ADK invocation, so one turn key
|
|
2027
|
+
// spans every model generation of the session. ADK delivers a barge-in's
|
|
2028
|
+
// flag FIRST, then the interrupted generation's own usageMetadata and
|
|
2029
|
+
// turnComplete, then the reply generation (a gemini-3.8-live capture
|
|
2030
|
+
// `live-bargein-gemini38live`). So an interrupted generation closes on its own
|
|
2031
|
+
// turnComplete (closeInterrupted), and the next generation after a barge-in
|
|
2032
|
+
// opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
|
|
2033
|
+
const generationOf = new Map<string, number>();
|
|
2034
|
+
const interruptClosed = new Set<string>();
|
|
1867
2035
|
const pendingLongRunning = new Map<string, Set<string>>();
|
|
1868
2036
|
const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
|
|
1869
2037
|
// Null-id call mint state (audit M47) — per-invoke ordinal counter + the
|
|
@@ -2083,10 +2251,6 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2083
2251
|
* complete. With no turn open, a fresh terminal turn carries the error, so
|
|
2084
2252
|
* it is never start-less. */
|
|
2085
2253
|
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
2254
|
function hostError(err: AdkHostError): void {
|
|
2091
2255
|
let closed = 0;
|
|
2092
2256
|
for (const turnId of [...openTurns].reverse()) {
|
|
@@ -2098,8 +2262,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2098
2262
|
closed++;
|
|
2099
2263
|
}
|
|
2100
2264
|
if (closed > 0) return;
|
|
2101
|
-
const
|
|
2102
|
-
const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
|
|
2265
|
+
const turnId = `turn_${invokeStem}_host_error_${hostErrorTurns++}`;
|
|
2103
2266
|
const messageId = ensureOpen(turnId);
|
|
2104
2267
|
closedTurns.add(turnId);
|
|
2105
2268
|
a.closeMessage(messageId);
|
|
@@ -2111,9 +2274,12 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2111
2274
|
}
|
|
2112
2275
|
|
|
2113
2276
|
function drive(event: AdkEvent): void {
|
|
2114
|
-
const
|
|
2115
|
-
|
|
2116
|
-
|
|
2277
|
+
const turnId = liveTurnFor(event);
|
|
2278
|
+
// ADK re-yields a bare `{interrupted}` after a message that carried both
|
|
2279
|
+
// turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
|
|
2280
|
+
// 2.1.0). For a generation the barge-in already closed, it adds nothing:
|
|
2281
|
+
// no new turn and no second terminal, so the facet emits nothing for it.
|
|
2282
|
+
if (turnId === undefined) return;
|
|
2117
2283
|
const messageId = ensureOpen(turnId);
|
|
2118
2284
|
const parts = event.content?.parts ?? [];
|
|
2119
2285
|
const isPartial = event.partial === true;
|
|
@@ -2163,7 +2329,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2163
2329
|
});
|
|
2164
2330
|
|
|
2165
2331
|
// §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
|
|
2166
|
-
const alreadyStreamed = streamedText.get(
|
|
2332
|
+
const alreadyStreamed = streamedText.get(turnId) ?? "";
|
|
2167
2333
|
const isAggregate = !isPartial && alreadyStreamed.length > 0;
|
|
2168
2334
|
const aggregateText = isAggregate
|
|
2169
2335
|
? parts
|
|
@@ -2224,8 +2390,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2224
2390
|
if (isPartial) accumulated += contributed;
|
|
2225
2391
|
});
|
|
2226
2392
|
|
|
2227
|
-
if (isPartial) streamedText.set(
|
|
2228
|
-
else if (isAggregate) streamedText.delete(
|
|
2393
|
+
if (isPartial) streamedText.set(turnId, accumulated);
|
|
2394
|
+
else if (isAggregate) streamedText.delete(turnId);
|
|
2229
2395
|
|
|
2230
2396
|
// Round-3 review finding (regression on finding b): the resend window's
|
|
2231
2397
|
// lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
|
|
@@ -2242,12 +2408,51 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2242
2408
|
// per-invoke.
|
|
2243
2409
|
|
|
2244
2410
|
if (!isPartial) trackLongRunning(event, turnId);
|
|
2245
|
-
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
|
|
2411
|
+
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone/content arms (Tasks 4–5)
|
|
2246
2412
|
// A turn gets ONE terminal: an interrupt on a turn that already closed
|
|
2247
2413
|
// (a second barge-in, or one after a success close) adds none.
|
|
2248
2414
|
if (event.interrupted === true && !closedTurns.has(turnId)) interruptPending.add(turnId);
|
|
2415
|
+
carryLiveUsageDetails(event, turnId, messageId, isPartial);
|
|
2249
2416
|
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
2250
|
-
|
|
2417
|
+
// The interrupted generation closes on its own turnComplete (its trailing
|
|
2418
|
+
// usageMetadata arrives before it), or at flush() / host completion.
|
|
2419
|
+
if (!isPartial && event.turnComplete === true && interruptPending.has(turnId)) closeInterrupted(turnId);
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
/** Gemini Live prices per modality (text vs audio), so its usage reports'
|
|
2423
|
+
* `promptTokensDetails` / `responseTokensDetails` ride the message's
|
|
2424
|
+
* metadata (a `message.metadata` event, key `usageDetails`), one entry per report, verbatim and never
|
|
2425
|
+
* summed. Each report re-emits the whole list (message metadata folds by
|
|
2426
|
+
* key, so the last emission holds every report). The list is the TURN's,
|
|
2427
|
+
* like the turn-summed `usage`, and rides the turn's current message; a turn
|
|
2428
|
+
* with more than one message carries it on the later one. Live path only
|
|
2429
|
+
* (`responseTokenCount` present): generateContent streams are unchanged. */
|
|
2430
|
+
function carryLiveUsageDetails(event: AdkEvent, turnId: string, messageId: string, isPartial: boolean): void {
|
|
2431
|
+
const um = event.usageMetadata;
|
|
2432
|
+
if (isPartial || um === undefined || um.responseTokenCount === undefined || um.candidatesTokenCount !== undefined) return;
|
|
2433
|
+
const entry: { [k: string]: JsonValue } = {
|
|
2434
|
+
...(um.promptTokensDetails !== undefined ? { promptTokensDetails: um.promptTokensDetails } : {}),
|
|
2435
|
+
...(um.responseTokensDetails !== undefined ? { responseTokensDetails: um.responseTokensDetails } : {}),
|
|
2436
|
+
};
|
|
2437
|
+
if (Object.keys(entry).length === 0) return;
|
|
2438
|
+
const list = [...(usageDetailsByTurn.get(turnId) ?? []), entry];
|
|
2439
|
+
usageDetailsByTurn.set(turnId, list);
|
|
2440
|
+
a.emit({ type: "message.metadata", messageId, metadata: { usageDetails: list } });
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
/** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
|
|
2444
|
+
* key), with `_g<n>` for the n-th generation after a barge-in closed the
|
|
2445
|
+
* previous one. `undefined` for ADK's bare `{interrupted}` re-yield on a
|
|
2446
|
+
* generation a barge-in already closed. */
|
|
2447
|
+
function liveTurnFor(event: AdkEvent): string | undefined {
|
|
2448
|
+
const key = turnKey(event);
|
|
2449
|
+
const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
|
|
2450
|
+
const g = generationOf.get(base) ?? 0;
|
|
2451
|
+
const current = g === 0 ? base : `${base}_g${g}`;
|
|
2452
|
+
if (!interruptClosed.has(current)) return current;
|
|
2453
|
+
if (event.interrupted === true && !hasLiveContent(event)) return undefined;
|
|
2454
|
+
generationOf.set(base, g + 1);
|
|
2455
|
+
return `${base}_g${g + 1}`;
|
|
2251
2456
|
}
|
|
2252
2457
|
|
|
2253
2458
|
/** interrupted → turn.abort, after the event's own content and carries and
|
|
@@ -2257,6 +2462,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem):
|
|
|
2257
2462
|
* message.end carries the turn's accumulated usage, as flush()'s does. */
|
|
2258
2463
|
function closeInterrupted(turnId: string): void {
|
|
2259
2464
|
interruptPending.delete(turnId);
|
|
2465
|
+
interruptClosed.add(turnId);
|
|
2260
2466
|
closedTurns.add(turnId);
|
|
2261
2467
|
a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
|
|
2262
2468
|
a.emit({ type: "turn.abort", turnId, reason: "interrupted" });
|