@silverprotocol/google-adk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,1209 @@
1
+ /**
2
+ * `@silverprotocol/google-adk` — the Google Agent Development Kit normalizer.
3
+ *
4
+ * Translates a Google ADK `Event` (a Gemini `Content` — role + `parts[]` — plus
5
+ * the event metadata `partial` / `turnComplete` / `errorCode` / `finishReason` /
6
+ * `actions`, inherited from `LlmResponse`) into AgJSON events (`AgEvent[]`,
7
+ * spec §4). The `content.parts[]` fan-out is the HIGHEST structural fan-out in
8
+ * the family: one event maps to a BURST of lifecycle events (`seq` monotonic
9
+ * from 0 within the call; the Router rebases to a global ordinal downstream, out
10
+ * of scope here).
11
+ *
12
+ * The normalizer is STATEFUL across calls (spec §8): it tracks the per-thread
13
+ * already-streamed parts so the ADK `partial:false` AGGREGATE event (which
14
+ * re-sends the full accumulated content) is SUPPRESSED — the #1 ADK
15
+ * double-render quirk (§8.3). It also synthesizes a stable `toolCallId` +
16
+ * records the positional `providerCallIndex` when a Gemini `functionCall.id` is
17
+ * null on the Developer API (§8.2), and preserves the Gemini `thoughtSignature`
18
+ * on EVERY signed part (§8.8) — on the reasoning block's `opaque` for a thought
19
+ * part, on the text event's `providerMetadata.google` for a signed NON-thought
20
+ * (Google-Search-grounded) text part, and on `tool.args.assembled.signature` for
21
+ * a functionCall part. Echo-or-400: a dropped signature breaks turn N+1.
22
+ *
23
+ * ── PRIMARY-SOURCE VERIFICATION (June 2026; the ADK SDK is NOT installed —
24
+ * `@iqai/adk` is an OPTIONAL peerDependency, NOT imported). The `AdkEvent` type
25
+ * below is a faithful PROJECTION of the verified shapes, hand-defined as the
26
+ * fixture contract until the ADK runtime is wired:
27
+ * - google/adk-python src/google/adk/events/event.py — the `Event` class
28
+ * (`author`, `invocationId`, `id`, `actions`, `branch`) extends `LlmResponse`
29
+ * (`content`, `partial`, `turnComplete`, `errorCode`, `finishReason`).
30
+ * `is_final_response()` = no functionCalls AND no functionResponses AND not
31
+ * `partial` AND no trailing codeExecutionResult (or skipSummarization /
32
+ * longRunningToolIds short-circuit) — the aggregate/final disposition (§8.3).
33
+ * - Gemini API `Content` (role + parts[]) and the `Part` union
34
+ * (`Content` REST reference + the Thought-Signatures / Function-Calling /
35
+ * Code-Execution docs): `{ text, thought?: boolean, thoughtSignature?: base64
36
+ * string }`, `{ functionCall: { name, args: OBJECT/dict, id? } }`,
37
+ * `{ functionResponse: { name, response: OBJECT, id? } }`,
38
+ * `{ inlineData: { mimeType, data: base64 } }`,
39
+ * `{ executableCode: { language: enum, code } }`,
40
+ * `{ codeExecutionResult: { outcome: "OUTCOME_OK"|"OUTCOME_FAILED"|
41
+ * "OUTCOME_DEADLINE_EXCEEDED", output } }`, `{ fileData }`.
42
+ * - `thoughtSignature` is a PER-PART base64 field; `functionCall.id` is OFTEN
43
+ * null on the Developer API (echoed parts must restore name+position).
44
+ *
45
+ * NOTE on field casing: the verified Gemini wire shape uses camelCase
46
+ * (`functionCall`, `thoughtSignature`, `inlineData`, `mimeType`, `executableCode`,
47
+ * `codeExecutionResult`, `turnComplete`, `finishReason`) — the genai REST/JS
48
+ * surface. The Python ADK uses the snake_case aliases (`turn_complete`,
49
+ * `function_call`); a runtime adapter would map those before this seam. This
50
+ * fixture contract is the camelCase wire projection.
51
+ */
52
+ import {
53
+ type AgEvent,
54
+ type AgBlock,
55
+ type AgCitation,
56
+ type AgFinishReason,
57
+ type AgPausedAsk,
58
+ type AgSafety,
59
+ type AgUsage,
60
+ AgProviderMeta,
61
+ JsonValue,
62
+ type Normalizer,
63
+ StreamAssembler,
64
+ type ToolOutcome,
65
+ } from "@silverprotocol/core";
66
+
67
+ // ─────────────────────────────────────────────────────────────────────────────
68
+ // AdkEvent — the HAND-DEFINED fixture contract (a faithful PROJECTION of the
69
+ // verified ADK Event + Gemini Content/Part shapes; see file header for the
70
+ // primary sources). Until the ADK runtime is wired, this is the input contract.
71
+ // ─────────────────────────────────────────────────────────────────────────────
72
+
73
+ /** A Gemini `Part` — the discriminated-by-presence union (one of the arms
74
+ * carries content; `thought` / `thoughtSignature` ride alongside). Fields are
75
+ * optional so a fixture sets exactly the arm it exercises. `args` / `response`
76
+ * are JSON OBJECTS/dicts (NOT JSON strings — do NOT JSON.parse). */
77
+ export interface AdkPart {
78
+ /** Visible text (or, with `thought:true`, the visible reasoning text). */
79
+ text?: string;
80
+ /** Marks a reasoning part (the model's thought) — routes to `reasoning.*`. */
81
+ thought?: boolean;
82
+ /** Per-part base64 thought signature — replay-load-bearing (§8.8). */
83
+ thoughtSignature?: string;
84
+ /** A tool call. `args` is an OBJECT/dict; `id` is OFTEN null on the Dev API. */
85
+ functionCall?: { name: string; args?: { [k: string]: JsonValue }; id?: string | null };
86
+ /** A tool result. `response` is an OBJECT (the function result, JSON object).
87
+ * `thoughtSignature` carries the per-response replay signature (§8.8). */
88
+ functionResponse?: {
89
+ name: string;
90
+ response?: { [k: string]: JsonValue };
91
+ id?: string | null;
92
+ thoughtSignature?: string;
93
+ };
94
+ /** Embedded media bytes (base64). */
95
+ inlineData?: { mimeType: string; data: string };
96
+ /** Model-generated code (the Code Execution tool). */
97
+ executableCode?: { language?: string; code: string };
98
+ /** Code-execution result (the Code Execution tool). */
99
+ codeExecutionResult?: { outcome?: string; output?: string };
100
+ /** A reference to an uploaded file (passed through opaquely). */
101
+ fileData?: { mimeType?: string; fileUri: string };
102
+ /** Media resolution hint for the input media (fixture-drift ratchet finding,
103
+ * google-adk-ratchet task) — carried opaquely via `driveAdkPart`'s
104
+ * unmapped-part-fields provider-raw block; never interpreted. */
105
+ mediaResolution?: JsonValue;
106
+ /** Video metadata accompanying `inlineData`/`fileData` (fixture-drift
107
+ * ratchet finding): the genai `Part` doc states it "should only be
108
+ * specified while the video data is presented in inline_data or
109
+ * file_data" — i.e. it normally rides ALONGSIDE an already-handled kind,
110
+ * not standalone. Carried opaquely via the same unmapped-part-fields
111
+ * provider-raw block (checked unconditionally, before the primary
112
+ * if-chain's early return — see `driveAdkPart`). */
113
+ videoMetadata?: JsonValue;
114
+ /** A server-side tool call the model predicts, which the client is
115
+ * expected to echo back (fixture-drift ratchet finding) — distinct from
116
+ * the client-executed `functionCall`. Carried opaquely via provider-raw. */
117
+ toolCall?: JsonValue;
118
+ /** The client-supplied result of a server-side `toolCall` (fixture-drift
119
+ * ratchet finding). Carried opaquely via provider-raw. */
120
+ toolResponse?: JsonValue;
121
+ /** Free-form per-part custom metadata, e.g. a source-file name or a
122
+ * multiplex hint for multiple Part streams (fixture-drift ratchet
123
+ * finding). Carried opaquely via provider-raw. */
124
+ partMetadata?: JsonValue;
125
+ }
126
+
127
+ /** A Gemini `Content` — the role + the part list. ADK normalizes Gemini's
128
+ * "model" role; we map "model" → "assistant" downstream where needed. */
129
+ export interface AdkContent {
130
+ role?: string;
131
+ parts?: AdkPart[];
132
+ }
133
+
134
+ /** A Google ADK `Event` — a Gemini `Content` plus the `LlmResponse` /
135
+ * `Event` metadata (verified shapes; see file header). */
136
+ export interface AdkEvent {
137
+ content?: AdkContent;
138
+ /** true on an incremental/streamed event; false (or absent) on the FINAL
139
+ * aggregate that re-sends the full content (§8.3). */
140
+ partial?: boolean;
141
+ /** Signals the user-input gate may re-open — the turn boundary (§4 turn.done). */
142
+ turnComplete?: boolean;
143
+ /** Provider finish reason (Gemini `Candidate.finishReason`): STOP / MAX_TOKENS
144
+ * / SAFETY / RECITATION / … — mapped to the AgFinishReason superset. */
145
+ finishReason?: string;
146
+ /** Provider error code (Gemini block reason) — surfaces a non-STOP finish. */
147
+ errorCode?: string;
148
+ /** Free-text error message accompanying errorCode for hard errors. When BOTH
149
+ * errorCode AND errorMessage are set, a turn.error is emitted instead of turn.done. */
150
+ errorMessage?: string;
151
+ /** Event id (stable per ADK event). */
152
+ id?: string;
153
+ /** The whole-interaction run id (the turn key). */
154
+ invocationId?: string;
155
+ /** 'user' or the agent name. */
156
+ author?: string;
157
+ /** Side-effect / control signals. */
158
+ actions?: {
159
+ skipSummarization?: boolean;
160
+ /** Transfer control to another named agent. */
161
+ transferToAgent?: string;
162
+ /** Escalate to a human or supervisor. */
163
+ escalate?: boolean;
164
+ /** Request OAuth/auth configs from the caller. ADK serializes this as a
165
+ * dict keyed by the function-call-id (`dict[str, AuthConfig]`); the value
166
+ * is a complex, framework-specific AuthConfig (auth-scheme union +
167
+ * credentials) we carry opaquely. Empty -> `{}` (NOT an array, NOT
168
+ * omitted) — iterating it as an array throws "not iterable". */
169
+ requestedAuthConfigs?: { [callId: string]: JsonValue };
170
+ /** Request user confirmation before executing a tool. ADK serializes this
171
+ * as a dict keyed by the function-call-id (`dict[str, ToolConfirmation]`).
172
+ * Empty -> `{}`. */
173
+ requestedToolConfirmations?: {
174
+ [callId: string]: { hint?: string; confirmed?: boolean; payload?: JsonValue };
175
+ };
176
+ /** State deltas to merge into the shared working copy. */
177
+ stateDelta?: { [k: string]: JsonValue };
178
+ /** Artifact deltas (keyed artifact patches). */
179
+ artifactDelta?: { [k: string]: JsonValue };
180
+ /** UI widgets to render inline. */
181
+ renderUiWidgets?: Array<{ name?: string; code?: string }>;
182
+ /** Opaque agent state string (runtime passthrough). */
183
+ agentState?: string;
184
+ /** Signals the end of the agent processing pipeline for this turn. */
185
+ endOfAgent?: boolean;
186
+ };
187
+ /** Gemini token usage metadata (maps to AgUsage on turn.done). */
188
+ usageMetadata?: {
189
+ promptTokenCount?: number;
190
+ candidatesTokenCount?: number;
191
+ totalTokenCount?: number;
192
+ cachedContentTokenCount?: number;
193
+ thoughtsTokenCount?: number;
194
+ toolUsePromptTokenCount?: number;
195
+ };
196
+ /** Per-part safety ratings from the Gemini Candidate. */
197
+ safetyRatings?: Array<{
198
+ category?: string;
199
+ probability?: string;
200
+ score?: number;
201
+ blocked?: boolean;
202
+ }>;
203
+ /** Prompt-level safety feedback (block reason + ratings). */
204
+ promptFeedback?: {
205
+ blockReason?: string;
206
+ safetyRatings?: Array<{
207
+ category?: string;
208
+ probability?: string;
209
+ score?: number;
210
+ blocked?: boolean;
211
+ }>;
212
+ };
213
+ /** Gemini grounding metadata (search result chunks, citations, search widget). */
214
+ groundingMetadata?: {
215
+ groundingChunks?: Array<{ web?: { uri?: string; title?: string } }>;
216
+ groundingSupports?: Array<{
217
+ groundingChunkIndices?: number[];
218
+ confidenceScores?: number[];
219
+ segment?: { startIndex?: number; endIndex?: number; text?: string };
220
+ }>;
221
+ searchEntryPoint?: { renderedContent?: string };
222
+ };
223
+ /** Citation metadata (Gemini Candidate.citationMetadata). */
224
+ citationMetadata?: {
225
+ citations?: Array<{
226
+ uri?: string;
227
+ title?: string;
228
+ startIndex?: number;
229
+ endIndex?: number;
230
+ }>;
231
+ };
232
+ /** When true, the turn was interrupted mid-stream — emit turn.abort. */
233
+ interrupted?: boolean;
234
+ /** Tool call ids that are long-running (hint: set longRunning:true on tool.start). */
235
+ longRunningToolIds?: string[];
236
+ /** ADK event branch (multi-agent routing). */
237
+ branch?: string;
238
+ /** ISO timestamp of the event. */
239
+ timestamp?: string;
240
+ /** Speech-to-text transcription of the user's audio input. */
241
+ inputTranscription?: { text?: string };
242
+ /** Text-to-speech transcription of the model's audio output. */
243
+ outputTranscription?: { text?: string };
244
+ /** Opaque per-event custom metadata bag. */
245
+ customMetadata?: { [k: string]: JsonValue };
246
+ /** Index of the candidate response (meaningful when the request's
247
+ * candidateCount > 1) — fixture-drift ratchet finding (google-adk-ratchet
248
+ * task): absent from this contract entirely until now. Carried via the
249
+ * event-level unmapped-fields provider-raw block (`driveAdkTopLevel`,
250
+ * alongside `citationMetadata`/`customMetadata`; SPEC §8 item 23). */
251
+ candidateIndex?: number;
252
+ }
253
+
254
+ // ─── finishReason → AgFinishReason (spec §4) ──────────────────────────────────
255
+ // Maps any Gemini/ADK Candidate.finishReason to the neutral AgFinishReason
256
+ // superset. A bare turnComplete with no reason ⇒ stop.
257
+ export function mapFinishReason(reason: string | undefined | null): AgFinishReason {
258
+ switch (reason) {
259
+ case undefined:
260
+ case null:
261
+ case "":
262
+ case "STOP":
263
+ case "FINISH_REASON_STOP":
264
+ return "stop";
265
+ case "MAX_TOKENS":
266
+ return "token_limit";
267
+ case "SAFETY":
268
+ case "RECITATION":
269
+ case "BLOCKLIST":
270
+ case "PROHIBITED_CONTENT":
271
+ case "SPII":
272
+ case "IMAGE_SAFETY":
273
+ return "safety_blocked";
274
+ case "MALFORMED_FUNCTION_CALL":
275
+ return "malformed_tool_call";
276
+ case "OTHER":
277
+ return "other";
278
+ default:
279
+ return "unknown";
280
+ }
281
+ }
282
+
283
+ // ─── stateful factory helpers ─────────────────────────────────────────────────
284
+
285
+ /** True for a non-null, non-array plain JSON object (guard idiom from the OpenAI facet). */
286
+ function isJsonObject(v: unknown): v is { readonly [k: string]: JsonValue } {
287
+ return typeof v === "object" && v !== null && !Array.isArray(v);
288
+ }
289
+
290
+ /** Outer-discriminant guard. ADK events carry an object `content` and/or an `invocationId`. */
291
+ function isAdkEvent(v: unknown): v is AdkEvent {
292
+ if (!isJsonObject(v)) return false;
293
+ return isJsonObject(v["content"]) || typeof v["invocationId"] === "string";
294
+ }
295
+
296
+ /** ADK usageMetadata → neutral AgUsage (cumulative:false). Extracted from the legacy turn.done arm. */
297
+ function mapUsage(um: AdkEvent["usageMetadata"]): AgUsage | undefined {
298
+ if (um === undefined) return undefined;
299
+ return {
300
+ ...(um.promptTokenCount !== undefined ? { inputTokens: um.promptTokenCount } : {}),
301
+ ...(um.candidatesTokenCount !== undefined ? { outputTokens: um.candidatesTokenCount } : {}),
302
+ ...(um.totalTokenCount !== undefined ? { totalTokens: um.totalTokenCount } : {}),
303
+ ...(um.cachedContentTokenCount !== undefined
304
+ ? { cacheReadTokens: um.cachedContentTokenCount }
305
+ : {}),
306
+ ...(um.thoughtsTokenCount !== undefined ? { reasoningTokens: um.thoughtsTokenCount } : {}),
307
+ ...(um.toolUsePromptTokenCount !== undefined
308
+ ? { toolUseInputTokens: um.toolUsePromptTokenCount }
309
+ : {}),
310
+ cumulative: false as const,
311
+ };
312
+ }
313
+
314
+ /** ADK blocked safetyRatings → neutral AgSafety[]. Extracted from the legacy turn.done arm. */
315
+ function mapBlockedSafety(ratings: AdkEvent["safetyRatings"]): AgSafety[] | undefined {
316
+ if (ratings === undefined) return undefined;
317
+ const out = ratings
318
+ .filter(
319
+ (r): r is typeof r & { category: string } => r.blocked === true && r.category !== undefined
320
+ )
321
+ .map((r) => ({
322
+ category: r.category,
323
+ probability: r.probability,
324
+ score: r.score,
325
+ blocked: r.blocked,
326
+ }));
327
+ return out.length > 0 ? out : undefined;
328
+ }
329
+
330
+ // ─── promptFeedback.blockReason → prompt.blocked reason (spec §4) ────────────
331
+ // Maps Gemini blockReason to the AgJSON prompt.blocked reason enum.
332
+ function mapBlockReason(reason: string): "safety" | "blocklist" | "prohibited" | "other" {
333
+ switch (reason) {
334
+ case "SAFETY":
335
+ return "safety";
336
+ case "BLOCKLIST":
337
+ return "blocklist";
338
+ case "PROHIBITED_CONTENT":
339
+ return "prohibited";
340
+ default:
341
+ return "other";
342
+ }
343
+ }
344
+
345
+ // ─── inlineData.mimeType → AgBlock type (spec §2) ─────────────────────────────
346
+ // Route a Gemini Blob by its MIME type to the matching AgBlock media arm. base64
347
+ // is the only source kind Gemini inlineData carries (Blob = {mimeType, data}).
348
+ function inlineDataBlock(d: { mimeType: string; data: string }): AgBlock {
349
+ const source = { type: "base64", mediaType: d.mimeType, data: d.data } as const;
350
+ if (d.mimeType.startsWith("image/")) return { type: "image", source };
351
+ if (d.mimeType.startsWith("audio/")) return { type: "audio", source };
352
+ // Everything else (video/*, application/*, text/*, …) rides the file arm
353
+ // (spec §2: video = mediaType video/*). It is still a typed media block.
354
+ return { type: "file", source };
355
+ }
356
+
357
+ // ─── executableCode.language → AgBlock.code.language (spec §2) ────────────────
358
+ // Gemini ExecutableCode.language is a closed enum (LANGUAGE_UNSPECIFIED|PYTHON);
359
+ // AgJSON code.language is a free string. Map defensively (spec §2 round-trip note).
360
+ function codeLanguage(lang: string | undefined): string {
361
+ if (lang === undefined || lang === "LANGUAGE_UNSPECIFIED" || lang === "") return "python";
362
+ return lang.toLowerCase();
363
+ }
364
+
365
+ // ─── codeExecutionResult.outcome → code-result.outcome (spec §2) ──────────────
366
+ function codeOutcome(outcome: string | undefined): "ok" | "failed" | "deadline_exceeded" {
367
+ switch (outcome) {
368
+ case "OUTCOME_OK":
369
+ return "ok";
370
+ case "OUTCOME_DEADLINE_EXCEEDED":
371
+ return "deadline_exceeded";
372
+ default:
373
+ // OUTCOME_FAILED / OUTCOME_UNSPECIFIED / unknown → failed.
374
+ return "failed";
375
+ }
376
+ }
377
+
378
+ function turnKey(ev: AdkEvent): string {
379
+ return ev.invocationId && ev.invocationId.length > 0 ? ev.invocationId : ev.id ?? "adk";
380
+ }
381
+
382
+ // ─── tool-call positional index (spec §8.2) ───────────────────────────────────
383
+ // Gemini parallel functionCall parts arrive in positional order; when a part's
384
+ // `functionCall.id` is null/absent we synthesize a stable toolCallId AND record
385
+ // the positional index on tool.start/tool-call `providerCallIndex` so re-input can
386
+ // restore name+position correlation when echoing functionResponse parts.
387
+
388
+ // ─── functionResponse.response → AgBlock[] (spec §2, MCP resource shape) ──────
389
+ // The Gemini functionResponse.response is a JSON OBJECT (the function result).
390
+ // Preserve its shape: an MCP-style { content: AgBlock[] } passes through as the
391
+ // model-facing content blocks; otherwise the whole object rides a single `data`
392
+ // block (typed, addressable by the function name) so nothing is dropped.
393
+ function functionResponseToAgBlocks(name: string, response: { [k: string]: JsonValue } | undefined): AgBlock[] {
394
+ if (response === undefined) return [];
395
+ // MCP resource shape: a `content` array of MCP content blocks (text/image/…).
396
+ const content = response["content"];
397
+ if (Array.isArray(content)) {
398
+ const out: AgBlock[] = [];
399
+ for (const part of content) {
400
+ if (part !== null && typeof part === "object" && !Array.isArray(part)) {
401
+ const t = part["type"];
402
+ if (t === "text" && typeof part["text"] === "string") {
403
+ out.push({ type: "text", text: part["text"] });
404
+ continue;
405
+ }
406
+ }
407
+ // Preserve any non-text MCP content part losslessly as a provider-raw block.
408
+ out.push({ type: "provider-raw", vendor: "google", raw: part });
409
+ }
410
+ return out;
411
+ }
412
+ // Non-MCP plain object result → a typed `data` block keyed by the tool name.
413
+ return [{ type: "data", name, data: response }];
414
+ }
415
+
416
+ // ─── groundingMetadata.groundingSupports → ONE citations[] (audit M22) ────────
417
+ // Each `groundingSupports` entry is a distinct SEGMENT of the SAME grounded text
418
+ // output (its own offsets + sourceIds, self-contained), so collecting them into
419
+ // one array — attached to the ONE streamed text block's `text.end` — is correct:
420
+ // no per-segment supplement block, no duplicate-fold.
421
+ function mapGroundingCitations(
422
+ gm: AdkEvent["groundingMetadata"]
423
+ ): AgCitation[] | undefined {
424
+ if (gm?.groundingSupports === undefined || gm.groundingSupports.length === 0) return undefined;
425
+ return gm.groundingSupports.map((support): AgCitation => ({
426
+ kind: "offset",
427
+ unit: "byte",
428
+ startIndex: support.segment?.startIndex ?? 0,
429
+ endIndex: support.segment?.endIndex ?? 0,
430
+ bounds: "[start,end)",
431
+ sourceIds: support.groundingChunkIndices?.map((i) => `grounding_${i}`) ?? [],
432
+ confidenceScores: support.confidenceScores ?? [],
433
+ citedText: support.segment?.text ?? "",
434
+ indexFrame: "response",
435
+ }));
436
+ }
437
+
438
+ // ─── null-id call mint state (audit M47; window/correlation redesign — review
439
+ // findings b/c on M47) ──────────────────────────────────────────────────────
440
+ // Gemini `functionCall.id` is often null on the Developer API (§8.2). Identity
441
+ // MUST NOT derive from a per-event positional index (INV-BLOCK): two DIFFERENT
442
+ // null-id calls that each land at parts[0] of DIFFERENT events would otherwise
443
+ // collide on the same synthesized id — the M47 repro (sequential toolA/toolB,
444
+ // both at parts[0]; toolB silently dropped, both results mis-keyed to toolA).
445
+ //
446
+ // Fix: mint a per-INVOKE ordinal id (`${turnId}:call:${ordinal}` — the ordinal
447
+ // counter lives in this closure, once per Normalizer instance/invoke).
448
+ //
449
+ // ── review finding (b): window-scoped multiset dedup, not "unresolved" ─────
450
+ // The ADK `partial:false` AGGREGATE re-send (§8 item 3) repeats the exact same
451
+ // functionCall content (name+args) the partial event(s) already streamed —
452
+ // that repeat must dedup to the SAME minted id, not mint a fresh one. The
453
+ // PRIOR fix keyed this dedup on "still unresolved" (a call stayed collapsible
454
+ // until its functionResponse landed) — but that collapses a GENUINELY
455
+ // REPEATED invocation (the same name+args called a SECOND time before the
456
+ // first resolves): the second call's tool.start silently vanished, and its
457
+ // later functionResponse then had no pending id left to consume, so it minted
458
+ // a FRESH one — a dangling tool.done with no matching tool.start.
459
+ //
460
+ // The correct dedup scope is the WINDOW, not "resolved-ness": the
461
+ // aggregate-resend window spans this turn's first `partial:true` event to its
462
+ // NEXT `partial:false` event that carries that SAME content, which CLOSES it
463
+ // — the facet's existing partial/aggregate boundary (§8 item 3; see
464
+ // `isAggregate`/`streamedText` in `drive()`). `openWindowCounts` is a per-turn
465
+ // MULTISET of (name,argsJson) -> how many times that content was emitted so
466
+ // far in the CURRENTLY open window. Every `partial:true` occurrence
467
+ // mints+emits and increments the count. The closing `partial:false` event
468
+ // SUPPRESSES up to that many occurrences of the same content (the resend) and
469
+ // mints+emits any EXCESS occurrences fresh — the aggregate is authoritative
470
+ // for the window's full call list, so two truly-parallel identical calls emit
471
+ // twice.
472
+ //
473
+ // Round-3 review finding (regression on this same finding b): the window's
474
+ // lifecycle is scoped PER CONTENT KEY, not per turn. `mintNullIdCallId`
475
+ // clears ONLY the contentKey entry it just fully consumed — it never touches
476
+ // other content keys' entries, and nothing clears the whole turn's map on an
477
+ // unrelated non-partial event (a different tool's call, a text aggregate).
478
+ // The prior "clear the whole per-turn map after any non-partial event"
479
+ // approach wiped a still-in-flight window whenever an unrelated non-partial
480
+ // event landed first, causing that window's TRUE aggregate resend to see no
481
+ // suppress-budget and re-mint+re-emit a duplicate tool.start. Per-contentKey
482
+ // clearing means a repeat invocation with identical content in a LATER window
483
+ // is still never collapsed — once ITS contentKey entry is cleared (by ITS OWN
484
+ // closing event), a further occurrence mints+emits exactly like a first
485
+ // occurrence. A call outside any window (no `partial:true` precursor at all)
486
+ // is never counted either way, so flat standalone repeats always emit too.
487
+ //
488
+ // ── review finding (c): functionResponse correlation ───────────────────────
489
+ // A functionResponse carries the tool NAME, never a position that reliably
490
+ // maps back to its call (SPEC.md:914's `providerCallIndex` is a *re-input*
491
+ // echo concern, not a receive-side correlator). Three cases, by shape:
492
+ // (i) ONE event with MULTIPLE functionResponses: Gemini's parallel-call
493
+ // convention is that a batch of results mirrors its calls' array
494
+ // position — the same rationale `providerCallIndex` records at mint
495
+ // time (§8 item 2). Resolved by a dedicated event-scoped pre-pass in
496
+ // `drive()` that calls `consumeMintedCallId` once per response, IN
497
+ // EVENT ORDER — exactly the positional pairing that convention implies.
498
+ // (ii) a single, standalone functionResponse in its own event: still FIFO
499
+ // per (turnId,name) via `consumeMintedCallId`. Two same-name calls whose
500
+ // responses resolve OUT OF ORDER across separate events are genuinely
501
+ // INDISTINGUISHABLE on this wire — no field ties a response to a
502
+ // specific call beyond the name — so FIFO-by-mint-order is the
503
+ // documented best-available approximation, not a claimed fix.
504
+ // (iii) an ORPHAN response (no pending mint under that name at all) must NOT
505
+ // fabricate a dangling tool.done — the whole functionResponse rides
506
+ // losslessly via `ext.google.unparsed` instead (mirrors the openai
507
+ // `late-*` ext precedents), handled at the `driveAdkPart` call site.
508
+ interface ToolCallMintState {
509
+ nextOrdinal: number;
510
+ /** turnId -> (contentKey -> emitted-count) for the CURRENTLY open resend
511
+ * window. No entry (or an empty map) for a turnId means no window is open
512
+ * for it right now. */
513
+ openWindowCounts: Map<string, Map<string, number>>;
514
+ /** (turnId,name) -> FIFO queue of minted ids awaiting their functionResponse. */
515
+ pendingIdsByName: Map<string, string[]>;
516
+ }
517
+
518
+ function toolCallContentKey(
519
+ turnId: string,
520
+ name: string,
521
+ args: { [k: string]: JsonValue } | undefined
522
+ ): string {
523
+ return `${turnId} ${name} ${JSON.stringify(args ?? {})}`;
524
+ }
525
+
526
+ /** Mint the next per-invoke-ordinal call id — never derived from event position. */
527
+ function mintFreshCallId(mint: ToolCallMintState, turnId: string): string {
528
+ const toolCallId = `${turnId}:call:${mint.nextOrdinal}`;
529
+ mint.nextOrdinal += 1;
530
+ return toolCallId;
531
+ }
532
+
533
+ /** Mint (or, within the still-open resend window's already-emitted budget for
534
+ * this exact content, SUPPRESS) the toolCallId for a null-id functionCall
535
+ * part. `resend:true` means the caller MUST NOT re-emit tool.start/args for
536
+ * this occurrence (§8 item 3 suppression; review finding-b window-scoped
537
+ * multiset dedup — see the file-header doc above for the full rationale). */
538
+ function mintNullIdCallId(
539
+ mint: ToolCallMintState,
540
+ turnId: string,
541
+ name: string,
542
+ args: { [k: string]: JsonValue } | undefined,
543
+ isPartial: boolean
544
+ ): { toolCallId: string; resend: boolean } {
545
+ const contentKey = toolCallContentKey(turnId, name, args);
546
+ if (!isPartial) {
547
+ const windowCounts = mint.openWindowCounts.get(turnId);
548
+ const emitted = windowCounts?.get(contentKey) ?? 0;
549
+ if (emitted > 0) {
550
+ // Round-3 review finding: the window's lifecycle is scoped to THIS
551
+ // content key alone, never the whole turn. Once this occurrence's
552
+ // suppress-budget is fully consumed, delete just this contentKey's
553
+ // entry — an unrelated non-partial event for a DIFFERENT content key
554
+ // (or no null-id calls at all) must never touch it. `drive()` no
555
+ // longer blanket-clears `openWindowCounts` on turn-scope; entries for
556
+ // windows whose aggregate never arrives simply die with the invoke's
557
+ // closure (bounded, per-invoke).
558
+ if (emitted === 1) windowCounts?.delete(contentKey);
559
+ else windowCounts?.set(contentKey, emitted - 1);
560
+ return { toolCallId: "", resend: true };
561
+ }
562
+ // No open window entry for this content, or this content's window budget
563
+ // is already exhausted: either a standalone call (no partial precursor)
564
+ // or an EXCESS occurrence in the aggregate (a genuinely-parallel
565
+ // identical call) — mint+emit fresh.
566
+ }
567
+ const toolCallId = mintFreshCallId(mint, turnId);
568
+ if (isPartial) {
569
+ const windowCounts = mint.openWindowCounts.get(turnId) ?? new Map<string, number>();
570
+ windowCounts.set(contentKey, (windowCounts.get(contentKey) ?? 0) + 1);
571
+ mint.openWindowCounts.set(turnId, windowCounts);
572
+ }
573
+ const nameKey = `${turnId} ${name}`;
574
+ const queue = mint.pendingIdsByName.get(nameKey) ?? [];
575
+ queue.push(toolCallId);
576
+ mint.pendingIdsByName.set(nameKey, queue);
577
+ return { toolCallId, resend: false };
578
+ }
579
+
580
+ /** Correlate a null-id functionResponse to its call: pop the FIFO-oldest
581
+ * unconsumed minted id for this (turnId,name). Called once per response, IN
582
+ * EVENT ORDER, by `drive()`'s pre-pass — for a multi-response event this IS
583
+ * the positional pairing Gemini's parallel-call convention describes
584
+ * (finding c-i); for a lone cross-event response it's the best-available
585
+ * FIFO approximation, since out-of-order same-name responses carry no field
586
+ * that disambiguates them further (finding c-ii). `undefined` means no call
587
+ * is pending under that name — an ORPHAN response (finding c-iii); the
588
+ * caller must NOT mint a fresh id for it. */
589
+ function consumeMintedCallId(
590
+ mint: ToolCallMintState,
591
+ turnId: string,
592
+ name: string
593
+ ): string | undefined {
594
+ const nameKey = `${turnId} ${name}`;
595
+ const queue = mint.pendingIdsByName.get(nameKey);
596
+ if (queue === undefined || queue.length === 0) return undefined;
597
+ return queue.shift();
598
+ }
599
+
600
+ // ─── stateful factory: driveAdkPart ──────────────────────────────────────────
601
+ function driveAdkPart(
602
+ a: StreamAssembler,
603
+ part: AdkPart,
604
+ index: number,
605
+ event: AdkEvent,
606
+ messageId: string,
607
+ turnId: string,
608
+ isPartial: boolean,
609
+ _assembledToolCalls: Set<string>,
610
+ mint: ToolCallMintState,
611
+ nullIdResponseIds: Map<number, string | undefined>,
612
+ citations?: AgCitation[]
613
+ ): string {
614
+ // ── UNMAPPED PART FIELDS (mediaResolution/videoMetadata/toolCall/toolResponse/
615
+ // partMetadata) → provider-raw content.block (fixture-drift ratchet finding,
616
+ // google-adk-ratchet task; Tenet-6; SPEC §8 item 23). These genai `Part`
617
+ // fields have NO route in the kind-specific if-chain below. Checked
618
+ // UNCONDITIONALLY, before that if-chain's early returns, because
619
+ // `videoMetadata` normally rides ALONGSIDE an already-handled `inlineData`/
620
+ // `fileData` part (genai's own doc: "should only be specified while the
621
+ // video data is presented in inline_data or file_data") — a check placed
622
+ // AFTER the if-chain would never see a sibling field on a part that already
623
+ // matched a primary kind and returned. Mirrors `driveAdkTopLevel`'s
624
+ // `unmappedActions`/`unmappedEvent` carry pattern (named-field ledger, not a
625
+ // generic reflection-over-keys catch-all — fixture discipline: type/carry
626
+ // only what is verified on the wire).
627
+ const unmappedPartFields: { [k: string]: JsonValue } = {};
628
+ if (part.mediaResolution !== undefined)
629
+ unmappedPartFields["mediaResolution"] = JsonValue.parse(part.mediaResolution);
630
+ if (part.videoMetadata !== undefined)
631
+ unmappedPartFields["videoMetadata"] = JsonValue.parse(part.videoMetadata);
632
+ if (part.toolCall !== undefined) unmappedPartFields["toolCall"] = JsonValue.parse(part.toolCall);
633
+ if (part.toolResponse !== undefined)
634
+ unmappedPartFields["toolResponse"] = JsonValue.parse(part.toolResponse);
635
+ if (part.partMetadata !== undefined)
636
+ unmappedPartFields["partMetadata"] = JsonValue.parse(part.partMetadata);
637
+ if (Object.keys(unmappedPartFields).length > 0) {
638
+ a.contentBlock(messageId, {
639
+ type: "provider-raw",
640
+ vendor: "google",
641
+ raw: JsonValue.parse(unmappedPartFields),
642
+ });
643
+ }
644
+
645
+ // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
646
+ if (part.thought === true) {
647
+ const id = `reasoning:${index}`;
648
+ a.reasoningStart(id, messageId);
649
+ if (part.text !== undefined && part.text.length > 0) a.reasoningDelta(id, messageId, part.text);
650
+ a.reasoningEnd(id, messageId, { provider: "google" });
651
+ if (part.thoughtSignature !== undefined && part.thoughtSignature.length > 0) {
652
+ a.reasoningOpaque(id, messageId, {
653
+ kind: "signature",
654
+ value: part.thoughtSignature,
655
+ provider: "google",
656
+ });
657
+ }
658
+ return "";
659
+ }
660
+
661
+ // ── TEXT ──
662
+ if (part.text !== undefined) {
663
+ const id = `text:${index}`;
664
+ const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
665
+ // STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
666
+ // event's groundingSupports segments (each already carries its own offsets +
667
+ // sourceIds — see `mapGroundingCitations`) into ONE array attached at
668
+ // text.end — never as per-segment id-less supplement blocks.
669
+ if (signed) {
670
+ // §8.8 — signature rides text.start/end providerMetadata via the sugar path
671
+ // (audit B10/#118).
672
+ const providerMetadata = AgProviderMeta.parse({
673
+ google: { thoughtSignature: part.thoughtSignature },
674
+ });
675
+ a.textStart(id, messageId, { providerMetadata });
676
+ a.textDelta(id, messageId, part.text);
677
+ a.textEnd(id, messageId, { providerMetadata, ...(citations !== undefined ? { citations } : {}) });
678
+ } else {
679
+ a.textStart(id, messageId);
680
+ a.textDelta(id, messageId, part.text);
681
+ a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
682
+ }
683
+ return part.text;
684
+ }
685
+
686
+ // ── FUNCTION CALL → tool.start + tool.args.delta + tool.args.assembled ──
687
+ if (part.functionCall !== undefined) {
688
+ const fc = part.functionCall;
689
+ const realId = fc.id != null && fc.id.length > 0 ? fc.id : null;
690
+ let toolCallId: string;
691
+ if (realId !== null) {
692
+ toolCallId = realId;
693
+ if (_assembledToolCalls.has(toolCallId)) return ""; // dedup the partial:false aggregate re-send
694
+ _assembledToolCalls.add(toolCallId);
695
+ } else {
696
+ // Null id (audit M47): mint a per-invoke-ordinal id, never a per-event
697
+ // positional one. A content-identical occurrence still within the open
698
+ // resend window's emitted budget (the aggregate re-send) is SUPPRESSED
699
+ // — window-scoped multiset dedup, review finding-b (see the
700
+ // `ToolCallMintState` doc above).
701
+ const minted = mintNullIdCallId(mint, turnId, fc.name, fc.args, isPartial);
702
+ if (minted.resend) return ""; // dedup the partial:false aggregate re-send (window-scoped content identity)
703
+ toolCallId = minted.toolCallId;
704
+ }
705
+ const providerCallIndex = realId !== null ? undefined : index;
706
+ const input: JsonValue = JsonValue.parse(fc.args ?? {});
707
+ const longRunning =
708
+ event.longRunningToolIds !== undefined && event.longRunningToolIds.includes(toolCallId)
709
+ ? true
710
+ : undefined;
711
+ a.toolStart({
712
+ toolCallId,
713
+ name: fc.name,
714
+ index,
715
+ longRunning,
716
+ providerMetadata:
717
+ providerCallIndex !== undefined
718
+ ? AgProviderMeta.parse({ google: { providerCallIndex } })
719
+ : undefined,
720
+ });
721
+ a.toolArgsDelta(toolCallId, JSON.stringify(input));
722
+ a.toolArgsAssembled(toolCallId, input, {
723
+ signature:
724
+ part.thoughtSignature !== undefined && part.thoughtSignature.length > 0
725
+ ? part.thoughtSignature
726
+ : undefined,
727
+ });
728
+ return "";
729
+ }
730
+
731
+ // ── FUNCTION RESPONSE → tool.done ──
732
+ if (part.functionResponse !== undefined) {
733
+ const fr = part.functionResponse;
734
+ const realId = fr.id != null && fr.id.length > 0 ? fr.id : null;
735
+ // Null id (audit M47): correlation was already resolved by `drive()`'s
736
+ // event-scoped pre-pass (positional for a multi-response event, FIFO for
737
+ // a lone one — review finding c-i/c-ii; see `consumeMintedCallId` doc).
738
+ const toolCallId = realId ?? nullIdResponseIds.get(index);
739
+ if (toolCallId === undefined) {
740
+ // Orphan response (review finding c-iii): no pending mint exists under
741
+ // this name. Minting a fresh id here would fabricate a dangling
742
+ // tool.done with no matching tool.start — exactly the M47-review bug.
743
+ // Carry the whole functionResponse losslessly instead (mirrors the
744
+ // openai `late-*` ext precedents).
745
+ a.emitExt("google", "unparsed", { functionResponse: JsonValue.parse(fr), turnId });
746
+ return "";
747
+ }
748
+ const outcome: ToolOutcome = fr.response?.["isError"] === true ? "error" : "ok";
749
+ a.toolDone({
750
+ toolCallId,
751
+ content: functionResponseToAgBlocks(fr.name, fr.response),
752
+ outcome,
753
+ turnId,
754
+ providerMetadata:
755
+ fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
756
+ ? AgProviderMeta.parse({ google: { thoughtSignature: fr.thoughtSignature } })
757
+ : undefined,
758
+ });
759
+ return "";
760
+ }
761
+
762
+ // ── inlineData / executableCode / codeExecutionResult / fileData → content.block ──
763
+ if (part.inlineData !== undefined) {
764
+ a.contentBlock(messageId, inlineDataBlock(part.inlineData));
765
+ return "";
766
+ }
767
+ if (part.executableCode !== undefined) {
768
+ a.contentBlock(messageId, {
769
+ type: "code",
770
+ language: codeLanguage(part.executableCode.language),
771
+ code: part.executableCode.code,
772
+ });
773
+ return "";
774
+ }
775
+ if (part.codeExecutionResult !== undefined) {
776
+ a.contentBlock(messageId, {
777
+ type: "code-result",
778
+ outcome: codeOutcome(part.codeExecutionResult.outcome),
779
+ output: part.codeExecutionResult.output ?? "",
780
+ });
781
+ return "";
782
+ }
783
+ if (part.fileData !== undefined) {
784
+ a.contentBlock(messageId, {
785
+ type: "resource-link",
786
+ uri: part.fileData.fileUri,
787
+ mimeType: part.fileData.mimeType,
788
+ });
789
+ return "";
790
+ }
791
+
792
+ return "";
793
+ }
794
+
795
+ /** Append `ask` to the turn's pending-asks list (creating it on first use).
796
+ * Preserves emission order — asks accumulate in the order their originating
797
+ * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
798
+ * `turn.done.outcome.paused.asks[]` (audit M26). */
799
+ function trackPendingAsk(
800
+ pendingAsks: Map<string, AgPausedAsk[]>,
801
+ turnId: string,
802
+ ask: AgPausedAsk
803
+ ): void {
804
+ const existing = pendingAsks.get(turnId);
805
+ if (existing !== undefined) existing.push(ask);
806
+ else pendingAsks.set(turnId, [ask]);
807
+ }
808
+
809
+ function driveAdkTopLevel(
810
+ a: StreamAssembler,
811
+ event: AdkEvent,
812
+ messageId: string,
813
+ turnId: string,
814
+ closedTurns: Set<string>,
815
+ pendingAsks: Map<string, AgPausedAsk[]>
816
+ ): void {
817
+ if (event.inputTranscription?.text !== undefined) {
818
+ a.contentBlock(messageId, {
819
+ type: "text",
820
+ text: event.inputTranscription.text,
821
+ _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
822
+ });
823
+ }
824
+ if (event.outputTranscription?.text !== undefined) {
825
+ a.contentBlock(messageId, {
826
+ type: "text",
827
+ text: event.outputTranscription.text,
828
+ _meta: { "agjson/transcription": { role: "output", kind: "transcription" } },
829
+ });
830
+ }
831
+
832
+ // ── interrupted → turn.abort ──
833
+ // Mark the turn closed in the FACET's own bookkeeping too (audit M21): without
834
+ // this, `maybeCloseTurn`'s is_final_response path or `flush()` would later
835
+ // fabricate a success `turn.done` for a turn that already aborted — the
836
+ // self-contradiction the audit found.
837
+ if (event.interrupted === true) {
838
+ a.emit({ type: "turn.abort", reason: "interrupted" });
839
+ closedTurns.add(turnId);
840
+ }
841
+
842
+ // ── promptFeedback → prompt.blocked ──
843
+ if (event.promptFeedback?.blockReason !== undefined) {
844
+ const reason = mapBlockReason(event.promptFeedback.blockReason);
845
+ const safety =
846
+ event.promptFeedback.safetyRatings !== undefined
847
+ ? event.promptFeedback.safetyRatings
848
+ .filter((r): r is typeof r & { category: string } => r.category !== undefined)
849
+ .map((r) => ({
850
+ category: r.category,
851
+ probability: r.probability,
852
+ score: r.score,
853
+ blocked: r.blocked,
854
+ }))
855
+ : undefined;
856
+ a.emit({ type: "prompt.blocked", reason, ...(safety !== undefined ? { safety } : {}) });
857
+ }
858
+
859
+ // ── groundingMetadata → source + display.required ──────────────────────────
860
+ // groundingSupports (per-segment citations) are handled BEFORE this function
861
+ // runs — collected by `mapGroundingCitations` and attached to the streamed text
862
+ // block's `text.end.citations` in `drive()`/`driveAdkPart` (audit M22: was N
863
+ // id-less per-segment supplement blocks, one per grounding segment).
864
+ if (event.groundingMetadata !== undefined) {
865
+ const gm = event.groundingMetadata;
866
+ if (gm.groundingChunks !== undefined) {
867
+ gm.groundingChunks.forEach((chunk, chunkIndex) => {
868
+ if (chunk.web?.uri !== undefined) {
869
+ a.emit({
870
+ type: "source",
871
+ sourceId: `grounding_${chunkIndex}`,
872
+ source: { url: chunk.web.uri, title: chunk.web.title },
873
+ });
874
+ }
875
+ });
876
+ }
877
+ if (gm.searchEntryPoint?.renderedContent !== undefined) {
878
+ a.emit({
879
+ type: "display.required",
880
+ provider: "google",
881
+ html: gm.searchEntryPoint.renderedContent,
882
+ });
883
+ }
884
+ }
885
+
886
+ // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
887
+ const actions = event.actions;
888
+ if (actions !== undefined) {
889
+ if (actions.transferToAgent !== undefined) {
890
+ a.emit({ type: "handoff", kind: "transfer", toAgentName: actions.transferToAgent });
891
+ }
892
+ if (actions.escalate === true) a.emit({ type: "handoff", kind: "escalate" });
893
+ if (actions.requestedAuthConfigs !== undefined) {
894
+ // ADK dict[str, AuthConfig] keyed by function-call-id. The AuthConfig is a
895
+ // complex framework-specific object (auth-scheme union + credentials) that
896
+ // does not fit the flat AgAuthConfig OAuth projection, so it rides opaque
897
+ // in `metadata` (AgJSON: framework-specifics lossless via metadata; SPEC §8
898
+ // item 12's sanctioned carrier). The SAME ask fields are tracked in
899
+ // `pendingAsks` — if this turn's close-path event turns out to be THIS
900
+ // event (or a later one for the same turnId), `maybeCloseTurn` folds them
901
+ // into `turn.done.outcome.paused.asks[]` instead of fabricating success
902
+ // (audit M26).
903
+ for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
904
+ const ask: AgPausedAsk = {
905
+ askId: `auth_${callId}`,
906
+ kind: "auth",
907
+ toolCallId: callId,
908
+ metadata: { authConfig: JsonValue.parse(authConfig) },
909
+ };
910
+ a.emit({ type: "hitl.ask", ...ask });
911
+ trackPendingAsk(pendingAsks, turnId, ask);
912
+ }
913
+ }
914
+ if (actions.requestedToolConfirmations !== undefined) {
915
+ // ADK dict[str, ToolConfirmation] keyed by function-call-id. `hint` maps to
916
+ // `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
917
+ // 18). Tracked in `pendingAsks` for the same paused-close fold as above.
918
+ for (const [callId, conf] of Object.entries(actions.requestedToolConfirmations)) {
919
+ const metadata: { [k: string]: JsonValue } = {};
920
+ if (conf.confirmed !== undefined) metadata["confirmed"] = conf.confirmed;
921
+ if (conf.payload !== undefined) metadata["payload"] = JsonValue.parse(conf.payload);
922
+ const ask: AgPausedAsk = {
923
+ askId: `approval_${callId}`,
924
+ kind: "approval",
925
+ toolCallId: callId,
926
+ ...(conf.hint !== undefined ? { message: conf.hint } : {}),
927
+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
928
+ };
929
+ a.emit({ type: "hitl.ask", ...ask });
930
+ trackPendingAsk(pendingAsks, turnId, ask);
931
+ }
932
+ }
933
+ if (actions.stateDelta !== undefined)
934
+ a.emit({ type: "state.delta", patch: JsonValue.parse(actions.stateDelta) });
935
+
936
+ const unmappedActions: { [k: string]: JsonValue } = {};
937
+ if (actions.artifactDelta !== undefined)
938
+ unmappedActions["artifactDelta"] = JsonValue.parse(actions.artifactDelta);
939
+ if (actions.renderUiWidgets !== undefined)
940
+ unmappedActions["renderUiWidgets"] = JsonValue.parse(actions.renderUiWidgets);
941
+ if (actions.agentState !== undefined) unmappedActions["agentState"] = actions.agentState;
942
+ if (actions.endOfAgent !== undefined) unmappedActions["endOfAgent"] = actions.endOfAgent;
943
+ if (Object.keys(unmappedActions).length > 0) {
944
+ a.contentBlock(messageId, {
945
+ type: "provider-raw",
946
+ vendor: "google",
947
+ raw: JsonValue.parse(unmappedActions),
948
+ });
949
+ }
950
+ }
951
+
952
+ // ── event-level unmapped (citationMetadata / customMetadata / candidateIndex /
953
+ // branch) → provider-raw ──
954
+ // candidateIndex/branch are fixture-drift ratchet findings (google-adk-ratchet
955
+ // task; SPEC §8 item 23): candidateIndex was entirely absent from the
956
+ // AdkEvent contract; branch was ALREADY typed but never read anywhere in
957
+ // drive()/driveAdkTopLevel. Both are genuinely OPTIONAL on the real
958
+ // @iqai/adk Event class (only set for multi-candidate / multi-agent-branch
959
+ // scenarios), so carrying them opportunistically here matches the
960
+ // citationMetadata/customMetadata precedent.
961
+ //
962
+ // `author`/`timestamp` are ALSO real, currently-unread AdkEvent fields
963
+ // (same manifest inventory) but are DELIBERATELY NOT folded into this bag:
964
+ // unlike the four fields above, both are REQUIRED (non-optional) on the
965
+ // real @iqai/adk `Event` class (`author: string`, `timestamp: number`) —
966
+ // i.e. present on EVERY real event, not an occasional payload. Verified
967
+ // empirically: adding them here fired a provider-raw content.block on
968
+ // every single native event in packages/e2e's captured adk fixtures
969
+ // (author:"spike" is set on all 5 events of both corpus scenarios),
970
+ // breaking the recorded golden `*.agjson.json` snapshots AND the
971
+ // cross-framework convergence assertions (adk's sequence gained
972
+ // content.block noise claude/openai's equivalent streams don't have) —
973
+ // regenerating those cassette fixtures is outside this ratchet's boundary
974
+ // (facet + manifests + script + SPEC §8 only). Disposed honestly as
975
+ // `silently-dropped` in sdk-surface.json rather than landed here; a more
976
+ // precise, non-noisy home (e.g. an agent-identity field on message.start
977
+ // for `author`, or the SPEC.md-sanctioned `_meta.timestamp` bare-key for
978
+ // `timestamp`) is a future spec-process decision, not a mechanical carry.
979
+ const unmappedEvent: { [k: string]: JsonValue } = {};
980
+ if (event.candidateIndex !== undefined) unmappedEvent["candidateIndex"] = event.candidateIndex;
981
+ if (event.branch !== undefined) unmappedEvent["branch"] = event.branch;
982
+ if (event.citationMetadata !== undefined)
983
+ unmappedEvent["citationMetadata"] = JsonValue.parse(event.citationMetadata);
984
+ if (event.customMetadata !== undefined)
985
+ unmappedEvent["customMetadata"] = JsonValue.parse(event.customMetadata);
986
+ if (Object.keys(unmappedEvent).length > 0) {
987
+ a.contentBlock(messageId, {
988
+ type: "provider-raw",
989
+ vendor: "google",
990
+ raw: JsonValue.parse(unmappedEvent),
991
+ });
992
+ }
993
+ }
994
+
995
+ // ─── stateful factory: createAdkNormalizer ────────────────────────────────────
996
+ export function createAdkNormalizer(): Normalizer {
997
+ const a = new StreamAssembler();
998
+ const threadId = "google";
999
+ // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
1000
+ const streamedText = new Map<string, string>();
1001
+ const openTurns = new Set<string>();
1002
+ const closedTurns = new Set<string>();
1003
+ // Per-turn HITL asks emitted by the two `actions.requested*` arms (audit
1004
+ // M26) — populated in emission order by `trackPendingAsk` inside
1005
+ // `driveAdkTopLevel`. Consulted ONLY by `maybeCloseTurn`'s REAL close path
1006
+ // (the is_final_response aggregate); the `flush()` truncation path never
1007
+ // reads it — see the comment there.
1008
+ const pendingAsks = new Map<string, AgPausedAsk[]>();
1009
+ const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
1010
+ // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
1011
+ // content/name correlation maps; lives exactly as long as this Normalizer
1012
+ // instance (one invoke, per §8.0's lifetime rule).
1013
+ const toolCallMint: ToolCallMintState = {
1014
+ nextOrdinal: 0,
1015
+ openWindowCounts: new Map<string, Map<string, number>>(),
1016
+ pendingIdsByName: new Map<string, string[]>(),
1017
+ };
1018
+
1019
+ function ensureOpen(turnId: string): string {
1020
+ const messageId = `msg_${turnId}`;
1021
+ if (!openTurns.has(turnId)) {
1022
+ openTurns.add(turnId);
1023
+ a.openTurn(turnId, threadId);
1024
+ a.openMessage({ id: messageId, role: "assistant", turnId, threadId });
1025
+ }
1026
+ return messageId;
1027
+ }
1028
+
1029
+ function maybeCloseTurn(
1030
+ event: AdkEvent,
1031
+ turnId: string,
1032
+ messageId: string,
1033
+ isPartial: boolean
1034
+ ): void {
1035
+ if (isPartial || closedTurns.has(turnId)) return;
1036
+ const parts = event.content?.parts ?? [];
1037
+ const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
1038
+ const interrupted = event.interrupted === true;
1039
+ const hasCompletion =
1040
+ event.turnComplete === true ||
1041
+ event.finishReason !== undefined ||
1042
+ event.errorCode !== undefined;
1043
+ // is_final_response: a non-partial event with no pending function call and not interrupted.
1044
+ if (hasFunctionCall || interrupted || !hasCompletion) return;
1045
+ closedTurns.add(turnId);
1046
+ a.closeMessage(messageId);
1047
+ if (event.errorCode !== undefined && event.errorMessage !== undefined) {
1048
+ a.closeTurnError(turnId, { message: event.errorMessage, code: event.errorCode });
1049
+ } else {
1050
+ const usage = mapUsage(event.usageMetadata);
1051
+ const safety = mapBlockedSafety(event.safetyRatings);
1052
+ // A turn with pending HITL asks (requestedAuthConfigs /
1053
+ // requestedToolConfirmations, tracked by `trackPendingAsk` above) closes
1054
+ // PAUSED, not success — the asks are real, unresolved requests the
1055
+ // turn is parked on, never a fabricated success (audit M26 / SPEC §8
1056
+ // items 12 + 18). `finishReason` stays the same mapping either way.
1057
+ const asks = pendingAsks.get(turnId);
1058
+ a.closeTurnDone(turnId, {
1059
+ outcome: asks !== undefined && asks.length > 0 ? { type: "paused", asks } : { type: "success" },
1060
+ finishReason: mapFinishReason(event.finishReason ?? event.errorCode),
1061
+ ...(usage !== undefined ? { usage } : {}),
1062
+ ...(safety !== undefined ? { safety } : {}),
1063
+ });
1064
+ }
1065
+ }
1066
+
1067
+ function drive(event: AdkEvent): void {
1068
+ const key = turnKey(event);
1069
+ const turnId = `turn_${key}`;
1070
+ const messageId = ensureOpen(turnId);
1071
+ const parts = event.content?.parts ?? [];
1072
+ const isPartial = event.partial === true;
1073
+
1074
+ // STREAMED-text citations carrier (audit M22): groundingMetadata is
1075
+ // EVENT-level, not per-part. A Gemini grounding response carries the full
1076
+ // grounded answer in a single (non-thought, non-function-call) text part, so
1077
+ // the FIRST such part in this event's `parts[]` is the citation carrier for
1078
+ // ALL of this event's groundingSupports segments — attached at that one
1079
+ // part's text.end below (never a per-segment supplement block).
1080
+ const citations = mapGroundingCitations(event.groundingMetadata);
1081
+ const citedPartIndex =
1082
+ citations !== undefined
1083
+ ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1084
+ : -1;
1085
+
1086
+ // Review finding c-i/c-ii: resolve null-id functionResponse correlation
1087
+ // for the WHOLE event up front, in array order, BEFORE any tool.done is
1088
+ // emitted — Gemini's parallel-call convention is that a batch of results
1089
+ // mirrors its calls' array position (the same rationale `providerCallIndex`
1090
+ // records at mint time, §8 item 2). Doing this as one event-scoped pass
1091
+ // (rather than resolving inline as each part streams past) is what makes a
1092
+ // multi-response event's positional pairing an explicit, testable
1093
+ // guarantee instead of an accident of loop order. A lone response in its
1094
+ // own event is the degenerate one-element case of the same pass.
1095
+ const nullIdResponseIds = new Map<number, string | undefined>();
1096
+ parts.forEach((part, idx) => {
1097
+ const fr = part.functionResponse;
1098
+ if (fr === undefined) return;
1099
+ if (fr.id != null && fr.id.length > 0) return; // real id — resolved directly, not via this map
1100
+ nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
1101
+ });
1102
+
1103
+ // §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
1104
+ const alreadyStreamed = streamedText.get(key) ?? "";
1105
+ const isAggregate = !isPartial && alreadyStreamed.length > 0;
1106
+ const aggregateText = isAggregate
1107
+ ? parts
1108
+ .filter((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1109
+ .map((p) => p.text ?? "")
1110
+ .join("")
1111
+ : "";
1112
+ const suppressAggregateText =
1113
+ isAggregate && aggregateText.length > 0 && alreadyStreamed.startsWith(aggregateText);
1114
+ let residualTail =
1115
+ isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
1116
+ let accumulated = alreadyStreamed;
1117
+
1118
+ parts.forEach((part, index) => {
1119
+ const isAggregateText =
1120
+ isAggregate &&
1121
+ part.thought !== true &&
1122
+ part.functionCall === undefined &&
1123
+ part.text !== undefined;
1124
+ if (isAggregateText) {
1125
+ if (suppressAggregateText) {
1126
+ // NOTE: fully-suppressed aggregate — this event emits NO text.end at all
1127
+ // for this part; its text.end already fired on an earlier PARTIAL event.
1128
+ // Gemini grounding metadata is not documented to land on an intermediate
1129
+ // partial, so this combination is believed unreachable; if it occurs,
1130
+ // citations are dropped rather than force-attached to the wrong
1131
+ // (already-sealed) block.
1132
+ accumulated += part.text ?? "";
1133
+ return;
1134
+ }
1135
+ if (residualTail.length > 0) {
1136
+ const id = `text:${index}`;
1137
+ a.textStart(id, messageId);
1138
+ a.textDelta(id, messageId, residualTail);
1139
+ a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
1140
+ residualTail = "";
1141
+ }
1142
+ accumulated += part.text ?? "";
1143
+ return;
1144
+ }
1145
+ const contributed = driveAdkPart(
1146
+ a,
1147
+ part,
1148
+ index,
1149
+ event,
1150
+ messageId,
1151
+ turnId,
1152
+ isPartial,
1153
+ assembledToolCalls,
1154
+ toolCallMint,
1155
+ nullIdResponseIds,
1156
+ index === citedPartIndex ? citations : undefined
1157
+ );
1158
+ if (isPartial) accumulated += contributed;
1159
+ });
1160
+
1161
+ if (isPartial) streamedText.set(key, accumulated);
1162
+ else if (isAggregate) streamedText.delete(key);
1163
+
1164
+ // Round-3 review finding (regression on finding b): the resend window's
1165
+ // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
1166
+ // (see the `ToolCallMintState` doc above) already clears each null-id
1167
+ // call's own contentKey entry as it's consumed while processing this
1168
+ // event's parts, above. There is deliberately NO blanket
1169
+ // `openWindowCounts.delete(turnId)` here anymore: that used to wipe the
1170
+ // WHOLE turn's window map on ANY non-partial event, including one that
1171
+ // carries no null-id calls for the still-open content key at all (a
1172
+ // different tool's real-id call, a text aggregate) — which silently
1173
+ // dropped a still-in-flight window and made its true aggregate resend
1174
+ // re-mint+re-emit a duplicate tool.start. Entries for windows whose
1175
+ // aggregate never arrives simply die with the invoke's closure — bounded,
1176
+ // per-invoke.
1177
+
1178
+ driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks); // standalone/content arms (Tasks 4–5)
1179
+ maybeCloseTurn(event, turnId, messageId, isPartial);
1180
+ }
1181
+
1182
+ return {
1183
+ push(native: JsonValue): AgEvent[] {
1184
+ if (!isAdkEvent(native)) {
1185
+ a.emitExt("google", "unparsed", { native });
1186
+ return a.drain();
1187
+ }
1188
+ drive(native);
1189
+ return a.drain();
1190
+ },
1191
+ flush(): AgEvent[] {
1192
+ // Dangling open turns (interrupted stream before a final aggregate):
1193
+ // close their message; the ENGINE flush closes the turn itself with
1194
+ // turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
1195
+ // This is deliberately true even when `pendingAsks` holds asks for one
1196
+ // of these turns: a HITL pause that never reached the REAL close path
1197
+ // (the is_final_response aggregate — see `maybeCloseTurn`) is an
1198
+ // INTERRUPTED stream, not a resolved pause. A truncated pause is a
1199
+ // truncation — `pendingAsks` is never consulted here (audit M26).
1200
+ for (const turnId of openTurns) {
1201
+ if (!closedTurns.has(turnId)) {
1202
+ closedTurns.add(turnId);
1203
+ a.closeMessage(`msg_${turnId}`);
1204
+ }
1205
+ }
1206
+ return a.flush();
1207
+ },
1208
+ };
1209
+ }