@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/LICENSE +21 -0
- package/README.md +32 -0
- package/dist/index.d.ts +283 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +851 -0
- package/dist/index.js.map +1 -0
- package/package.json +49 -0
- package/src/index.ts +1209 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,851 @@
|
|
|
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 { AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
|
|
53
|
+
// ─── finishReason → AgFinishReason (spec §4) ──────────────────────────────────
|
|
54
|
+
// Maps any Gemini/ADK Candidate.finishReason to the neutral AgFinishReason
|
|
55
|
+
// superset. A bare turnComplete with no reason ⇒ stop.
|
|
56
|
+
export function mapFinishReason(reason) {
|
|
57
|
+
switch (reason) {
|
|
58
|
+
case undefined:
|
|
59
|
+
case null:
|
|
60
|
+
case "":
|
|
61
|
+
case "STOP":
|
|
62
|
+
case "FINISH_REASON_STOP":
|
|
63
|
+
return "stop";
|
|
64
|
+
case "MAX_TOKENS":
|
|
65
|
+
return "token_limit";
|
|
66
|
+
case "SAFETY":
|
|
67
|
+
case "RECITATION":
|
|
68
|
+
case "BLOCKLIST":
|
|
69
|
+
case "PROHIBITED_CONTENT":
|
|
70
|
+
case "SPII":
|
|
71
|
+
case "IMAGE_SAFETY":
|
|
72
|
+
return "safety_blocked";
|
|
73
|
+
case "MALFORMED_FUNCTION_CALL":
|
|
74
|
+
return "malformed_tool_call";
|
|
75
|
+
case "OTHER":
|
|
76
|
+
return "other";
|
|
77
|
+
default:
|
|
78
|
+
return "unknown";
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// ─── stateful factory helpers ─────────────────────────────────────────────────
|
|
82
|
+
/** True for a non-null, non-array plain JSON object (guard idiom from the OpenAI facet). */
|
|
83
|
+
function isJsonObject(v) {
|
|
84
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
85
|
+
}
|
|
86
|
+
/** Outer-discriminant guard. ADK events carry an object `content` and/or an `invocationId`. */
|
|
87
|
+
function isAdkEvent(v) {
|
|
88
|
+
if (!isJsonObject(v))
|
|
89
|
+
return false;
|
|
90
|
+
return isJsonObject(v["content"]) || typeof v["invocationId"] === "string";
|
|
91
|
+
}
|
|
92
|
+
/** ADK usageMetadata → neutral AgUsage (cumulative:false). Extracted from the legacy turn.done arm. */
|
|
93
|
+
function mapUsage(um) {
|
|
94
|
+
if (um === undefined)
|
|
95
|
+
return undefined;
|
|
96
|
+
return {
|
|
97
|
+
...(um.promptTokenCount !== undefined ? { inputTokens: um.promptTokenCount } : {}),
|
|
98
|
+
...(um.candidatesTokenCount !== undefined ? { outputTokens: um.candidatesTokenCount } : {}),
|
|
99
|
+
...(um.totalTokenCount !== undefined ? { totalTokens: um.totalTokenCount } : {}),
|
|
100
|
+
...(um.cachedContentTokenCount !== undefined
|
|
101
|
+
? { cacheReadTokens: um.cachedContentTokenCount }
|
|
102
|
+
: {}),
|
|
103
|
+
...(um.thoughtsTokenCount !== undefined ? { reasoningTokens: um.thoughtsTokenCount } : {}),
|
|
104
|
+
...(um.toolUsePromptTokenCount !== undefined
|
|
105
|
+
? { toolUseInputTokens: um.toolUsePromptTokenCount }
|
|
106
|
+
: {}),
|
|
107
|
+
cumulative: false,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** ADK blocked safetyRatings → neutral AgSafety[]. Extracted from the legacy turn.done arm. */
|
|
111
|
+
function mapBlockedSafety(ratings) {
|
|
112
|
+
if (ratings === undefined)
|
|
113
|
+
return undefined;
|
|
114
|
+
const out = ratings
|
|
115
|
+
.filter((r) => r.blocked === true && r.category !== undefined)
|
|
116
|
+
.map((r) => ({
|
|
117
|
+
category: r.category,
|
|
118
|
+
probability: r.probability,
|
|
119
|
+
score: r.score,
|
|
120
|
+
blocked: r.blocked,
|
|
121
|
+
}));
|
|
122
|
+
return out.length > 0 ? out : undefined;
|
|
123
|
+
}
|
|
124
|
+
// ─── promptFeedback.blockReason → prompt.blocked reason (spec §4) ────────────
|
|
125
|
+
// Maps Gemini blockReason to the AgJSON prompt.blocked reason enum.
|
|
126
|
+
function mapBlockReason(reason) {
|
|
127
|
+
switch (reason) {
|
|
128
|
+
case "SAFETY":
|
|
129
|
+
return "safety";
|
|
130
|
+
case "BLOCKLIST":
|
|
131
|
+
return "blocklist";
|
|
132
|
+
case "PROHIBITED_CONTENT":
|
|
133
|
+
return "prohibited";
|
|
134
|
+
default:
|
|
135
|
+
return "other";
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// ─── inlineData.mimeType → AgBlock type (spec §2) ─────────────────────────────
|
|
139
|
+
// Route a Gemini Blob by its MIME type to the matching AgBlock media arm. base64
|
|
140
|
+
// is the only source kind Gemini inlineData carries (Blob = {mimeType, data}).
|
|
141
|
+
function inlineDataBlock(d) {
|
|
142
|
+
const source = { type: "base64", mediaType: d.mimeType, data: d.data };
|
|
143
|
+
if (d.mimeType.startsWith("image/"))
|
|
144
|
+
return { type: "image", source };
|
|
145
|
+
if (d.mimeType.startsWith("audio/"))
|
|
146
|
+
return { type: "audio", source };
|
|
147
|
+
// Everything else (video/*, application/*, text/*, …) rides the file arm
|
|
148
|
+
// (spec §2: video = mediaType video/*). It is still a typed media block.
|
|
149
|
+
return { type: "file", source };
|
|
150
|
+
}
|
|
151
|
+
// ─── executableCode.language → AgBlock.code.language (spec §2) ────────────────
|
|
152
|
+
// Gemini ExecutableCode.language is a closed enum (LANGUAGE_UNSPECIFIED|PYTHON);
|
|
153
|
+
// AgJSON code.language is a free string. Map defensively (spec §2 round-trip note).
|
|
154
|
+
function codeLanguage(lang) {
|
|
155
|
+
if (lang === undefined || lang === "LANGUAGE_UNSPECIFIED" || lang === "")
|
|
156
|
+
return "python";
|
|
157
|
+
return lang.toLowerCase();
|
|
158
|
+
}
|
|
159
|
+
// ─── codeExecutionResult.outcome → code-result.outcome (spec §2) ──────────────
|
|
160
|
+
function codeOutcome(outcome) {
|
|
161
|
+
switch (outcome) {
|
|
162
|
+
case "OUTCOME_OK":
|
|
163
|
+
return "ok";
|
|
164
|
+
case "OUTCOME_DEADLINE_EXCEEDED":
|
|
165
|
+
return "deadline_exceeded";
|
|
166
|
+
default:
|
|
167
|
+
// OUTCOME_FAILED / OUTCOME_UNSPECIFIED / unknown → failed.
|
|
168
|
+
return "failed";
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function turnKey(ev) {
|
|
172
|
+
return ev.invocationId && ev.invocationId.length > 0 ? ev.invocationId : ev.id ?? "adk";
|
|
173
|
+
}
|
|
174
|
+
// ─── tool-call positional index (spec §8.2) ───────────────────────────────────
|
|
175
|
+
// Gemini parallel functionCall parts arrive in positional order; when a part's
|
|
176
|
+
// `functionCall.id` is null/absent we synthesize a stable toolCallId AND record
|
|
177
|
+
// the positional index on tool.start/tool-call `providerCallIndex` so re-input can
|
|
178
|
+
// restore name+position correlation when echoing functionResponse parts.
|
|
179
|
+
// ─── functionResponse.response → AgBlock[] (spec §2, MCP resource shape) ──────
|
|
180
|
+
// The Gemini functionResponse.response is a JSON OBJECT (the function result).
|
|
181
|
+
// Preserve its shape: an MCP-style { content: AgBlock[] } passes through as the
|
|
182
|
+
// model-facing content blocks; otherwise the whole object rides a single `data`
|
|
183
|
+
// block (typed, addressable by the function name) so nothing is dropped.
|
|
184
|
+
function functionResponseToAgBlocks(name, response) {
|
|
185
|
+
if (response === undefined)
|
|
186
|
+
return [];
|
|
187
|
+
// MCP resource shape: a `content` array of MCP content blocks (text/image/…).
|
|
188
|
+
const content = response["content"];
|
|
189
|
+
if (Array.isArray(content)) {
|
|
190
|
+
const out = [];
|
|
191
|
+
for (const part of content) {
|
|
192
|
+
if (part !== null && typeof part === "object" && !Array.isArray(part)) {
|
|
193
|
+
const t = part["type"];
|
|
194
|
+
if (t === "text" && typeof part["text"] === "string") {
|
|
195
|
+
out.push({ type: "text", text: part["text"] });
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// Preserve any non-text MCP content part losslessly as a provider-raw block.
|
|
200
|
+
out.push({ type: "provider-raw", vendor: "google", raw: part });
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
// Non-MCP plain object result → a typed `data` block keyed by the tool name.
|
|
205
|
+
return [{ type: "data", name, data: response }];
|
|
206
|
+
}
|
|
207
|
+
// ─── groundingMetadata.groundingSupports → ONE citations[] (audit M22) ────────
|
|
208
|
+
// Each `groundingSupports` entry is a distinct SEGMENT of the SAME grounded text
|
|
209
|
+
// output (its own offsets + sourceIds, self-contained), so collecting them into
|
|
210
|
+
// one array — attached to the ONE streamed text block's `text.end` — is correct:
|
|
211
|
+
// no per-segment supplement block, no duplicate-fold.
|
|
212
|
+
function mapGroundingCitations(gm) {
|
|
213
|
+
if (gm?.groundingSupports === undefined || gm.groundingSupports.length === 0)
|
|
214
|
+
return undefined;
|
|
215
|
+
return gm.groundingSupports.map((support) => ({
|
|
216
|
+
kind: "offset",
|
|
217
|
+
unit: "byte",
|
|
218
|
+
startIndex: support.segment?.startIndex ?? 0,
|
|
219
|
+
endIndex: support.segment?.endIndex ?? 0,
|
|
220
|
+
bounds: "[start,end)",
|
|
221
|
+
sourceIds: support.groundingChunkIndices?.map((i) => `grounding_${i}`) ?? [],
|
|
222
|
+
confidenceScores: support.confidenceScores ?? [],
|
|
223
|
+
citedText: support.segment?.text ?? "",
|
|
224
|
+
indexFrame: "response",
|
|
225
|
+
}));
|
|
226
|
+
}
|
|
227
|
+
function toolCallContentKey(turnId, name, args) {
|
|
228
|
+
return `${turnId} ${name} ${JSON.stringify(args ?? {})}`;
|
|
229
|
+
}
|
|
230
|
+
/** Mint the next per-invoke-ordinal call id — never derived from event position. */
|
|
231
|
+
function mintFreshCallId(mint, turnId) {
|
|
232
|
+
const toolCallId = `${turnId}:call:${mint.nextOrdinal}`;
|
|
233
|
+
mint.nextOrdinal += 1;
|
|
234
|
+
return toolCallId;
|
|
235
|
+
}
|
|
236
|
+
/** Mint (or, within the still-open resend window's already-emitted budget for
|
|
237
|
+
* this exact content, SUPPRESS) the toolCallId for a null-id functionCall
|
|
238
|
+
* part. `resend:true` means the caller MUST NOT re-emit tool.start/args for
|
|
239
|
+
* this occurrence (§8 item 3 suppression; review finding-b window-scoped
|
|
240
|
+
* multiset dedup — see the file-header doc above for the full rationale). */
|
|
241
|
+
function mintNullIdCallId(mint, turnId, name, args, isPartial) {
|
|
242
|
+
const contentKey = toolCallContentKey(turnId, name, args);
|
|
243
|
+
if (!isPartial) {
|
|
244
|
+
const windowCounts = mint.openWindowCounts.get(turnId);
|
|
245
|
+
const emitted = windowCounts?.get(contentKey) ?? 0;
|
|
246
|
+
if (emitted > 0) {
|
|
247
|
+
// Round-3 review finding: the window's lifecycle is scoped to THIS
|
|
248
|
+
// content key alone, never the whole turn. Once this occurrence's
|
|
249
|
+
// suppress-budget is fully consumed, delete just this contentKey's
|
|
250
|
+
// entry — an unrelated non-partial event for a DIFFERENT content key
|
|
251
|
+
// (or no null-id calls at all) must never touch it. `drive()` no
|
|
252
|
+
// longer blanket-clears `openWindowCounts` on turn-scope; entries for
|
|
253
|
+
// windows whose aggregate never arrives simply die with the invoke's
|
|
254
|
+
// closure (bounded, per-invoke).
|
|
255
|
+
if (emitted === 1)
|
|
256
|
+
windowCounts?.delete(contentKey);
|
|
257
|
+
else
|
|
258
|
+
windowCounts?.set(contentKey, emitted - 1);
|
|
259
|
+
return { toolCallId: "", resend: true };
|
|
260
|
+
}
|
|
261
|
+
// No open window entry for this content, or this content's window budget
|
|
262
|
+
// is already exhausted: either a standalone call (no partial precursor)
|
|
263
|
+
// or an EXCESS occurrence in the aggregate (a genuinely-parallel
|
|
264
|
+
// identical call) — mint+emit fresh.
|
|
265
|
+
}
|
|
266
|
+
const toolCallId = mintFreshCallId(mint, turnId);
|
|
267
|
+
if (isPartial) {
|
|
268
|
+
const windowCounts = mint.openWindowCounts.get(turnId) ?? new Map();
|
|
269
|
+
windowCounts.set(contentKey, (windowCounts.get(contentKey) ?? 0) + 1);
|
|
270
|
+
mint.openWindowCounts.set(turnId, windowCounts);
|
|
271
|
+
}
|
|
272
|
+
const nameKey = `${turnId} ${name}`;
|
|
273
|
+
const queue = mint.pendingIdsByName.get(nameKey) ?? [];
|
|
274
|
+
queue.push(toolCallId);
|
|
275
|
+
mint.pendingIdsByName.set(nameKey, queue);
|
|
276
|
+
return { toolCallId, resend: false };
|
|
277
|
+
}
|
|
278
|
+
/** Correlate a null-id functionResponse to its call: pop the FIFO-oldest
|
|
279
|
+
* unconsumed minted id for this (turnId,name). Called once per response, IN
|
|
280
|
+
* EVENT ORDER, by `drive()`'s pre-pass — for a multi-response event this IS
|
|
281
|
+
* the positional pairing Gemini's parallel-call convention describes
|
|
282
|
+
* (finding c-i); for a lone cross-event response it's the best-available
|
|
283
|
+
* FIFO approximation, since out-of-order same-name responses carry no field
|
|
284
|
+
* that disambiguates them further (finding c-ii). `undefined` means no call
|
|
285
|
+
* is pending under that name — an ORPHAN response (finding c-iii); the
|
|
286
|
+
* caller must NOT mint a fresh id for it. */
|
|
287
|
+
function consumeMintedCallId(mint, turnId, name) {
|
|
288
|
+
const nameKey = `${turnId} ${name}`;
|
|
289
|
+
const queue = mint.pendingIdsByName.get(nameKey);
|
|
290
|
+
if (queue === undefined || queue.length === 0)
|
|
291
|
+
return undefined;
|
|
292
|
+
return queue.shift();
|
|
293
|
+
}
|
|
294
|
+
// ─── stateful factory: driveAdkPart ──────────────────────────────────────────
|
|
295
|
+
function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, citations) {
|
|
296
|
+
// ── UNMAPPED PART FIELDS (mediaResolution/videoMetadata/toolCall/toolResponse/
|
|
297
|
+
// partMetadata) → provider-raw content.block (fixture-drift ratchet finding,
|
|
298
|
+
// google-adk-ratchet task; Tenet-6; SPEC §8 item 23). These genai `Part`
|
|
299
|
+
// fields have NO route in the kind-specific if-chain below. Checked
|
|
300
|
+
// UNCONDITIONALLY, before that if-chain's early returns, because
|
|
301
|
+
// `videoMetadata` normally rides ALONGSIDE an already-handled `inlineData`/
|
|
302
|
+
// `fileData` part (genai's own doc: "should only be specified while the
|
|
303
|
+
// video data is presented in inline_data or file_data") — a check placed
|
|
304
|
+
// AFTER the if-chain would never see a sibling field on a part that already
|
|
305
|
+
// matched a primary kind and returned. Mirrors `driveAdkTopLevel`'s
|
|
306
|
+
// `unmappedActions`/`unmappedEvent` carry pattern (named-field ledger, not a
|
|
307
|
+
// generic reflection-over-keys catch-all — fixture discipline: type/carry
|
|
308
|
+
// only what is verified on the wire).
|
|
309
|
+
const unmappedPartFields = {};
|
|
310
|
+
if (part.mediaResolution !== undefined)
|
|
311
|
+
unmappedPartFields["mediaResolution"] = JsonValue.parse(part.mediaResolution);
|
|
312
|
+
if (part.videoMetadata !== undefined)
|
|
313
|
+
unmappedPartFields["videoMetadata"] = JsonValue.parse(part.videoMetadata);
|
|
314
|
+
if (part.toolCall !== undefined)
|
|
315
|
+
unmappedPartFields["toolCall"] = JsonValue.parse(part.toolCall);
|
|
316
|
+
if (part.toolResponse !== undefined)
|
|
317
|
+
unmappedPartFields["toolResponse"] = JsonValue.parse(part.toolResponse);
|
|
318
|
+
if (part.partMetadata !== undefined)
|
|
319
|
+
unmappedPartFields["partMetadata"] = JsonValue.parse(part.partMetadata);
|
|
320
|
+
if (Object.keys(unmappedPartFields).length > 0) {
|
|
321
|
+
a.contentBlock(messageId, {
|
|
322
|
+
type: "provider-raw",
|
|
323
|
+
vendor: "google",
|
|
324
|
+
raw: JsonValue.parse(unmappedPartFields),
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
// ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
|
|
328
|
+
if (part.thought === true) {
|
|
329
|
+
const id = `reasoning:${index}`;
|
|
330
|
+
a.reasoningStart(id, messageId);
|
|
331
|
+
if (part.text !== undefined && part.text.length > 0)
|
|
332
|
+
a.reasoningDelta(id, messageId, part.text);
|
|
333
|
+
a.reasoningEnd(id, messageId, { provider: "google" });
|
|
334
|
+
if (part.thoughtSignature !== undefined && part.thoughtSignature.length > 0) {
|
|
335
|
+
a.reasoningOpaque(id, messageId, {
|
|
336
|
+
kind: "signature",
|
|
337
|
+
value: part.thoughtSignature,
|
|
338
|
+
provider: "google",
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
return "";
|
|
342
|
+
}
|
|
343
|
+
// ── TEXT ──
|
|
344
|
+
if (part.text !== undefined) {
|
|
345
|
+
const id = `text:${index}`;
|
|
346
|
+
const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
|
|
347
|
+
// STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
|
|
348
|
+
// event's groundingSupports segments (each already carries its own offsets +
|
|
349
|
+
// sourceIds — see `mapGroundingCitations`) into ONE array attached at
|
|
350
|
+
// text.end — never as per-segment id-less supplement blocks.
|
|
351
|
+
if (signed) {
|
|
352
|
+
// §8.8 — signature rides text.start/end providerMetadata via the sugar path
|
|
353
|
+
// (audit B10/#118).
|
|
354
|
+
const providerMetadata = AgProviderMeta.parse({
|
|
355
|
+
google: { thoughtSignature: part.thoughtSignature },
|
|
356
|
+
});
|
|
357
|
+
a.textStart(id, messageId, { providerMetadata });
|
|
358
|
+
a.textDelta(id, messageId, part.text);
|
|
359
|
+
a.textEnd(id, messageId, { providerMetadata, ...(citations !== undefined ? { citations } : {}) });
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
a.textStart(id, messageId);
|
|
363
|
+
a.textDelta(id, messageId, part.text);
|
|
364
|
+
a.textEnd(id, messageId, citations !== undefined ? { citations } : undefined);
|
|
365
|
+
}
|
|
366
|
+
return part.text;
|
|
367
|
+
}
|
|
368
|
+
// ── FUNCTION CALL → tool.start + tool.args.delta + tool.args.assembled ──
|
|
369
|
+
if (part.functionCall !== undefined) {
|
|
370
|
+
const fc = part.functionCall;
|
|
371
|
+
const realId = fc.id != null && fc.id.length > 0 ? fc.id : null;
|
|
372
|
+
let toolCallId;
|
|
373
|
+
if (realId !== null) {
|
|
374
|
+
toolCallId = realId;
|
|
375
|
+
if (_assembledToolCalls.has(toolCallId))
|
|
376
|
+
return ""; // dedup the partial:false aggregate re-send
|
|
377
|
+
_assembledToolCalls.add(toolCallId);
|
|
378
|
+
}
|
|
379
|
+
else {
|
|
380
|
+
// Null id (audit M47): mint a per-invoke-ordinal id, never a per-event
|
|
381
|
+
// positional one. A content-identical occurrence still within the open
|
|
382
|
+
// resend window's emitted budget (the aggregate re-send) is SUPPRESSED
|
|
383
|
+
// — window-scoped multiset dedup, review finding-b (see the
|
|
384
|
+
// `ToolCallMintState` doc above).
|
|
385
|
+
const minted = mintNullIdCallId(mint, turnId, fc.name, fc.args, isPartial);
|
|
386
|
+
if (minted.resend)
|
|
387
|
+
return ""; // dedup the partial:false aggregate re-send (window-scoped content identity)
|
|
388
|
+
toolCallId = minted.toolCallId;
|
|
389
|
+
}
|
|
390
|
+
const providerCallIndex = realId !== null ? undefined : index;
|
|
391
|
+
const input = JsonValue.parse(fc.args ?? {});
|
|
392
|
+
const longRunning = event.longRunningToolIds !== undefined && event.longRunningToolIds.includes(toolCallId)
|
|
393
|
+
? true
|
|
394
|
+
: undefined;
|
|
395
|
+
a.toolStart({
|
|
396
|
+
toolCallId,
|
|
397
|
+
name: fc.name,
|
|
398
|
+
index,
|
|
399
|
+
longRunning,
|
|
400
|
+
providerMetadata: providerCallIndex !== undefined
|
|
401
|
+
? AgProviderMeta.parse({ google: { providerCallIndex } })
|
|
402
|
+
: undefined,
|
|
403
|
+
});
|
|
404
|
+
a.toolArgsDelta(toolCallId, JSON.stringify(input));
|
|
405
|
+
a.toolArgsAssembled(toolCallId, input, {
|
|
406
|
+
signature: part.thoughtSignature !== undefined && part.thoughtSignature.length > 0
|
|
407
|
+
? part.thoughtSignature
|
|
408
|
+
: undefined,
|
|
409
|
+
});
|
|
410
|
+
return "";
|
|
411
|
+
}
|
|
412
|
+
// ── FUNCTION RESPONSE → tool.done ──
|
|
413
|
+
if (part.functionResponse !== undefined) {
|
|
414
|
+
const fr = part.functionResponse;
|
|
415
|
+
const realId = fr.id != null && fr.id.length > 0 ? fr.id : null;
|
|
416
|
+
// Null id (audit M47): correlation was already resolved by `drive()`'s
|
|
417
|
+
// event-scoped pre-pass (positional for a multi-response event, FIFO for
|
|
418
|
+
// a lone one — review finding c-i/c-ii; see `consumeMintedCallId` doc).
|
|
419
|
+
const toolCallId = realId ?? nullIdResponseIds.get(index);
|
|
420
|
+
if (toolCallId === undefined) {
|
|
421
|
+
// Orphan response (review finding c-iii): no pending mint exists under
|
|
422
|
+
// this name. Minting a fresh id here would fabricate a dangling
|
|
423
|
+
// tool.done with no matching tool.start — exactly the M47-review bug.
|
|
424
|
+
// Carry the whole functionResponse losslessly instead (mirrors the
|
|
425
|
+
// openai `late-*` ext precedents).
|
|
426
|
+
a.emitExt("google", "unparsed", { functionResponse: JsonValue.parse(fr), turnId });
|
|
427
|
+
return "";
|
|
428
|
+
}
|
|
429
|
+
const outcome = fr.response?.["isError"] === true ? "error" : "ok";
|
|
430
|
+
a.toolDone({
|
|
431
|
+
toolCallId,
|
|
432
|
+
content: functionResponseToAgBlocks(fr.name, fr.response),
|
|
433
|
+
outcome,
|
|
434
|
+
turnId,
|
|
435
|
+
providerMetadata: fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
|
|
436
|
+
? AgProviderMeta.parse({ google: { thoughtSignature: fr.thoughtSignature } })
|
|
437
|
+
: undefined,
|
|
438
|
+
});
|
|
439
|
+
return "";
|
|
440
|
+
}
|
|
441
|
+
// ── inlineData / executableCode / codeExecutionResult / fileData → content.block ──
|
|
442
|
+
if (part.inlineData !== undefined) {
|
|
443
|
+
a.contentBlock(messageId, inlineDataBlock(part.inlineData));
|
|
444
|
+
return "";
|
|
445
|
+
}
|
|
446
|
+
if (part.executableCode !== undefined) {
|
|
447
|
+
a.contentBlock(messageId, {
|
|
448
|
+
type: "code",
|
|
449
|
+
language: codeLanguage(part.executableCode.language),
|
|
450
|
+
code: part.executableCode.code,
|
|
451
|
+
});
|
|
452
|
+
return "";
|
|
453
|
+
}
|
|
454
|
+
if (part.codeExecutionResult !== undefined) {
|
|
455
|
+
a.contentBlock(messageId, {
|
|
456
|
+
type: "code-result",
|
|
457
|
+
outcome: codeOutcome(part.codeExecutionResult.outcome),
|
|
458
|
+
output: part.codeExecutionResult.output ?? "",
|
|
459
|
+
});
|
|
460
|
+
return "";
|
|
461
|
+
}
|
|
462
|
+
if (part.fileData !== undefined) {
|
|
463
|
+
a.contentBlock(messageId, {
|
|
464
|
+
type: "resource-link",
|
|
465
|
+
uri: part.fileData.fileUri,
|
|
466
|
+
mimeType: part.fileData.mimeType,
|
|
467
|
+
});
|
|
468
|
+
return "";
|
|
469
|
+
}
|
|
470
|
+
return "";
|
|
471
|
+
}
|
|
472
|
+
/** Append `ask` to the turn's pending-asks list (creating it on first use).
|
|
473
|
+
* Preserves emission order — asks accumulate in the order their originating
|
|
474
|
+
* hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
|
|
475
|
+
* `turn.done.outcome.paused.asks[]` (audit M26). */
|
|
476
|
+
function trackPendingAsk(pendingAsks, turnId, ask) {
|
|
477
|
+
const existing = pendingAsks.get(turnId);
|
|
478
|
+
if (existing !== undefined)
|
|
479
|
+
existing.push(ask);
|
|
480
|
+
else
|
|
481
|
+
pendingAsks.set(turnId, [ask]);
|
|
482
|
+
}
|
|
483
|
+
function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks) {
|
|
484
|
+
if (event.inputTranscription?.text !== undefined) {
|
|
485
|
+
a.contentBlock(messageId, {
|
|
486
|
+
type: "text",
|
|
487
|
+
text: event.inputTranscription.text,
|
|
488
|
+
_meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
if (event.outputTranscription?.text !== undefined) {
|
|
492
|
+
a.contentBlock(messageId, {
|
|
493
|
+
type: "text",
|
|
494
|
+
text: event.outputTranscription.text,
|
|
495
|
+
_meta: { "agjson/transcription": { role: "output", kind: "transcription" } },
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
// ── interrupted → turn.abort ──
|
|
499
|
+
// Mark the turn closed in the FACET's own bookkeeping too (audit M21): without
|
|
500
|
+
// this, `maybeCloseTurn`'s is_final_response path or `flush()` would later
|
|
501
|
+
// fabricate a success `turn.done` for a turn that already aborted — the
|
|
502
|
+
// self-contradiction the audit found.
|
|
503
|
+
if (event.interrupted === true) {
|
|
504
|
+
a.emit({ type: "turn.abort", reason: "interrupted" });
|
|
505
|
+
closedTurns.add(turnId);
|
|
506
|
+
}
|
|
507
|
+
// ── promptFeedback → prompt.blocked ──
|
|
508
|
+
if (event.promptFeedback?.blockReason !== undefined) {
|
|
509
|
+
const reason = mapBlockReason(event.promptFeedback.blockReason);
|
|
510
|
+
const safety = event.promptFeedback.safetyRatings !== undefined
|
|
511
|
+
? event.promptFeedback.safetyRatings
|
|
512
|
+
.filter((r) => r.category !== undefined)
|
|
513
|
+
.map((r) => ({
|
|
514
|
+
category: r.category,
|
|
515
|
+
probability: r.probability,
|
|
516
|
+
score: r.score,
|
|
517
|
+
blocked: r.blocked,
|
|
518
|
+
}))
|
|
519
|
+
: undefined;
|
|
520
|
+
a.emit({ type: "prompt.blocked", reason, ...(safety !== undefined ? { safety } : {}) });
|
|
521
|
+
}
|
|
522
|
+
// ── groundingMetadata → source + display.required ──────────────────────────
|
|
523
|
+
// groundingSupports (per-segment citations) are handled BEFORE this function
|
|
524
|
+
// runs — collected by `mapGroundingCitations` and attached to the streamed text
|
|
525
|
+
// block's `text.end.citations` in `drive()`/`driveAdkPart` (audit M22: was N
|
|
526
|
+
// id-less per-segment supplement blocks, one per grounding segment).
|
|
527
|
+
if (event.groundingMetadata !== undefined) {
|
|
528
|
+
const gm = event.groundingMetadata;
|
|
529
|
+
if (gm.groundingChunks !== undefined) {
|
|
530
|
+
gm.groundingChunks.forEach((chunk, chunkIndex) => {
|
|
531
|
+
if (chunk.web?.uri !== undefined) {
|
|
532
|
+
a.emit({
|
|
533
|
+
type: "source",
|
|
534
|
+
sourceId: `grounding_${chunkIndex}`,
|
|
535
|
+
source: { url: chunk.web.uri, title: chunk.web.title },
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
if (gm.searchEntryPoint?.renderedContent !== undefined) {
|
|
541
|
+
a.emit({
|
|
542
|
+
type: "display.required",
|
|
543
|
+
provider: "google",
|
|
544
|
+
html: gm.searchEntryPoint.renderedContent,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
|
|
549
|
+
const actions = event.actions;
|
|
550
|
+
if (actions !== undefined) {
|
|
551
|
+
if (actions.transferToAgent !== undefined) {
|
|
552
|
+
a.emit({ type: "handoff", kind: "transfer", toAgentName: actions.transferToAgent });
|
|
553
|
+
}
|
|
554
|
+
if (actions.escalate === true)
|
|
555
|
+
a.emit({ type: "handoff", kind: "escalate" });
|
|
556
|
+
if (actions.requestedAuthConfigs !== undefined) {
|
|
557
|
+
// ADK dict[str, AuthConfig] keyed by function-call-id. The AuthConfig is a
|
|
558
|
+
// complex framework-specific object (auth-scheme union + credentials) that
|
|
559
|
+
// does not fit the flat AgAuthConfig OAuth projection, so it rides opaque
|
|
560
|
+
// in `metadata` (AgJSON: framework-specifics lossless via metadata; SPEC §8
|
|
561
|
+
// item 12's sanctioned carrier). The SAME ask fields are tracked in
|
|
562
|
+
// `pendingAsks` — if this turn's close-path event turns out to be THIS
|
|
563
|
+
// event (or a later one for the same turnId), `maybeCloseTurn` folds them
|
|
564
|
+
// into `turn.done.outcome.paused.asks[]` instead of fabricating success
|
|
565
|
+
// (audit M26).
|
|
566
|
+
for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
|
|
567
|
+
const ask = {
|
|
568
|
+
askId: `auth_${callId}`,
|
|
569
|
+
kind: "auth",
|
|
570
|
+
toolCallId: callId,
|
|
571
|
+
metadata: { authConfig: JsonValue.parse(authConfig) },
|
|
572
|
+
};
|
|
573
|
+
a.emit({ type: "hitl.ask", ...ask });
|
|
574
|
+
trackPendingAsk(pendingAsks, turnId, ask);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (actions.requestedToolConfirmations !== undefined) {
|
|
578
|
+
// ADK dict[str, ToolConfirmation] keyed by function-call-id. `hint` maps to
|
|
579
|
+
// `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
|
|
580
|
+
// 18). Tracked in `pendingAsks` for the same paused-close fold as above.
|
|
581
|
+
for (const [callId, conf] of Object.entries(actions.requestedToolConfirmations)) {
|
|
582
|
+
const metadata = {};
|
|
583
|
+
if (conf.confirmed !== undefined)
|
|
584
|
+
metadata["confirmed"] = conf.confirmed;
|
|
585
|
+
if (conf.payload !== undefined)
|
|
586
|
+
metadata["payload"] = JsonValue.parse(conf.payload);
|
|
587
|
+
const ask = {
|
|
588
|
+
askId: `approval_${callId}`,
|
|
589
|
+
kind: "approval",
|
|
590
|
+
toolCallId: callId,
|
|
591
|
+
...(conf.hint !== undefined ? { message: conf.hint } : {}),
|
|
592
|
+
...(Object.keys(metadata).length > 0 ? { metadata } : {}),
|
|
593
|
+
};
|
|
594
|
+
a.emit({ type: "hitl.ask", ...ask });
|
|
595
|
+
trackPendingAsk(pendingAsks, turnId, ask);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (actions.stateDelta !== undefined)
|
|
599
|
+
a.emit({ type: "state.delta", patch: JsonValue.parse(actions.stateDelta) });
|
|
600
|
+
const unmappedActions = {};
|
|
601
|
+
if (actions.artifactDelta !== undefined)
|
|
602
|
+
unmappedActions["artifactDelta"] = JsonValue.parse(actions.artifactDelta);
|
|
603
|
+
if (actions.renderUiWidgets !== undefined)
|
|
604
|
+
unmappedActions["renderUiWidgets"] = JsonValue.parse(actions.renderUiWidgets);
|
|
605
|
+
if (actions.agentState !== undefined)
|
|
606
|
+
unmappedActions["agentState"] = actions.agentState;
|
|
607
|
+
if (actions.endOfAgent !== undefined)
|
|
608
|
+
unmappedActions["endOfAgent"] = actions.endOfAgent;
|
|
609
|
+
if (Object.keys(unmappedActions).length > 0) {
|
|
610
|
+
a.contentBlock(messageId, {
|
|
611
|
+
type: "provider-raw",
|
|
612
|
+
vendor: "google",
|
|
613
|
+
raw: JsonValue.parse(unmappedActions),
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
// ── event-level unmapped (citationMetadata / customMetadata / candidateIndex /
|
|
618
|
+
// branch) → provider-raw ──
|
|
619
|
+
// candidateIndex/branch are fixture-drift ratchet findings (google-adk-ratchet
|
|
620
|
+
// task; SPEC §8 item 23): candidateIndex was entirely absent from the
|
|
621
|
+
// AdkEvent contract; branch was ALREADY typed but never read anywhere in
|
|
622
|
+
// drive()/driveAdkTopLevel. Both are genuinely OPTIONAL on the real
|
|
623
|
+
// @iqai/adk Event class (only set for multi-candidate / multi-agent-branch
|
|
624
|
+
// scenarios), so carrying them opportunistically here matches the
|
|
625
|
+
// citationMetadata/customMetadata precedent.
|
|
626
|
+
//
|
|
627
|
+
// `author`/`timestamp` are ALSO real, currently-unread AdkEvent fields
|
|
628
|
+
// (same manifest inventory) but are DELIBERATELY NOT folded into this bag:
|
|
629
|
+
// unlike the four fields above, both are REQUIRED (non-optional) on the
|
|
630
|
+
// real @iqai/adk `Event` class (`author: string`, `timestamp: number`) —
|
|
631
|
+
// i.e. present on EVERY real event, not an occasional payload. Verified
|
|
632
|
+
// empirically: adding them here fired a provider-raw content.block on
|
|
633
|
+
// every single native event in packages/e2e's captured adk fixtures
|
|
634
|
+
// (author:"spike" is set on all 5 events of both corpus scenarios),
|
|
635
|
+
// breaking the recorded golden `*.agjson.json` snapshots AND the
|
|
636
|
+
// cross-framework convergence assertions (adk's sequence gained
|
|
637
|
+
// content.block noise claude/openai's equivalent streams don't have) —
|
|
638
|
+
// regenerating those cassette fixtures is outside this ratchet's boundary
|
|
639
|
+
// (facet + manifests + script + SPEC §8 only). Disposed honestly as
|
|
640
|
+
// `silently-dropped` in sdk-surface.json rather than landed here; a more
|
|
641
|
+
// precise, non-noisy home (e.g. an agent-identity field on message.start
|
|
642
|
+
// for `author`, or the SPEC.md-sanctioned `_meta.timestamp` bare-key for
|
|
643
|
+
// `timestamp`) is a future spec-process decision, not a mechanical carry.
|
|
644
|
+
const unmappedEvent = {};
|
|
645
|
+
if (event.candidateIndex !== undefined)
|
|
646
|
+
unmappedEvent["candidateIndex"] = event.candidateIndex;
|
|
647
|
+
if (event.branch !== undefined)
|
|
648
|
+
unmappedEvent["branch"] = event.branch;
|
|
649
|
+
if (event.citationMetadata !== undefined)
|
|
650
|
+
unmappedEvent["citationMetadata"] = JsonValue.parse(event.citationMetadata);
|
|
651
|
+
if (event.customMetadata !== undefined)
|
|
652
|
+
unmappedEvent["customMetadata"] = JsonValue.parse(event.customMetadata);
|
|
653
|
+
if (Object.keys(unmappedEvent).length > 0) {
|
|
654
|
+
a.contentBlock(messageId, {
|
|
655
|
+
type: "provider-raw",
|
|
656
|
+
vendor: "google",
|
|
657
|
+
raw: JsonValue.parse(unmappedEvent),
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
// ─── stateful factory: createAdkNormalizer ────────────────────────────────────
|
|
662
|
+
export function createAdkNormalizer() {
|
|
663
|
+
const a = new StreamAssembler();
|
|
664
|
+
const threadId = "google";
|
|
665
|
+
// §8.3 per-instance accumulator (replaces the module-level streamedText Map):
|
|
666
|
+
const streamedText = new Map();
|
|
667
|
+
const openTurns = new Set();
|
|
668
|
+
const closedTurns = new Set();
|
|
669
|
+
// Per-turn HITL asks emitted by the two `actions.requested*` arms (audit
|
|
670
|
+
// M26) — populated in emission order by `trackPendingAsk` inside
|
|
671
|
+
// `driveAdkTopLevel`. Consulted ONLY by `maybeCloseTurn`'s REAL close path
|
|
672
|
+
// (the is_final_response aggregate); the `flush()` truncation path never
|
|
673
|
+
// reads it — see the comment there.
|
|
674
|
+
const pendingAsks = new Map();
|
|
675
|
+
const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
|
|
676
|
+
// Null-id call mint state (audit M47) — per-invoke ordinal counter + the
|
|
677
|
+
// content/name correlation maps; lives exactly as long as this Normalizer
|
|
678
|
+
// instance (one invoke, per §8.0's lifetime rule).
|
|
679
|
+
const toolCallMint = {
|
|
680
|
+
nextOrdinal: 0,
|
|
681
|
+
openWindowCounts: new Map(),
|
|
682
|
+
pendingIdsByName: new Map(),
|
|
683
|
+
};
|
|
684
|
+
function ensureOpen(turnId) {
|
|
685
|
+
const messageId = `msg_${turnId}`;
|
|
686
|
+
if (!openTurns.has(turnId)) {
|
|
687
|
+
openTurns.add(turnId);
|
|
688
|
+
a.openTurn(turnId, threadId);
|
|
689
|
+
a.openMessage({ id: messageId, role: "assistant", turnId, threadId });
|
|
690
|
+
}
|
|
691
|
+
return messageId;
|
|
692
|
+
}
|
|
693
|
+
function maybeCloseTurn(event, turnId, messageId, isPartial) {
|
|
694
|
+
if (isPartial || closedTurns.has(turnId))
|
|
695
|
+
return;
|
|
696
|
+
const parts = event.content?.parts ?? [];
|
|
697
|
+
const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
|
|
698
|
+
const interrupted = event.interrupted === true;
|
|
699
|
+
const hasCompletion = event.turnComplete === true ||
|
|
700
|
+
event.finishReason !== undefined ||
|
|
701
|
+
event.errorCode !== undefined;
|
|
702
|
+
// is_final_response: a non-partial event with no pending function call and not interrupted.
|
|
703
|
+
if (hasFunctionCall || interrupted || !hasCompletion)
|
|
704
|
+
return;
|
|
705
|
+
closedTurns.add(turnId);
|
|
706
|
+
a.closeMessage(messageId);
|
|
707
|
+
if (event.errorCode !== undefined && event.errorMessage !== undefined) {
|
|
708
|
+
a.closeTurnError(turnId, { message: event.errorMessage, code: event.errorCode });
|
|
709
|
+
}
|
|
710
|
+
else {
|
|
711
|
+
const usage = mapUsage(event.usageMetadata);
|
|
712
|
+
const safety = mapBlockedSafety(event.safetyRatings);
|
|
713
|
+
// A turn with pending HITL asks (requestedAuthConfigs /
|
|
714
|
+
// requestedToolConfirmations, tracked by `trackPendingAsk` above) closes
|
|
715
|
+
// PAUSED, not success — the asks are real, unresolved requests the
|
|
716
|
+
// turn is parked on, never a fabricated success (audit M26 / SPEC §8
|
|
717
|
+
// items 12 + 18). `finishReason` stays the same mapping either way.
|
|
718
|
+
const asks = pendingAsks.get(turnId);
|
|
719
|
+
a.closeTurnDone(turnId, {
|
|
720
|
+
outcome: asks !== undefined && asks.length > 0 ? { type: "paused", asks } : { type: "success" },
|
|
721
|
+
finishReason: mapFinishReason(event.finishReason ?? event.errorCode),
|
|
722
|
+
...(usage !== undefined ? { usage } : {}),
|
|
723
|
+
...(safety !== undefined ? { safety } : {}),
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
function drive(event) {
|
|
728
|
+
const key = turnKey(event);
|
|
729
|
+
const turnId = `turn_${key}`;
|
|
730
|
+
const messageId = ensureOpen(turnId);
|
|
731
|
+
const parts = event.content?.parts ?? [];
|
|
732
|
+
const isPartial = event.partial === true;
|
|
733
|
+
// STREAMED-text citations carrier (audit M22): groundingMetadata is
|
|
734
|
+
// EVENT-level, not per-part. A Gemini grounding response carries the full
|
|
735
|
+
// grounded answer in a single (non-thought, non-function-call) text part, so
|
|
736
|
+
// the FIRST such part in this event's `parts[]` is the citation carrier for
|
|
737
|
+
// ALL of this event's groundingSupports segments — attached at that one
|
|
738
|
+
// part's text.end below (never a per-segment supplement block).
|
|
739
|
+
const citations = mapGroundingCitations(event.groundingMetadata);
|
|
740
|
+
const citedPartIndex = citations !== undefined
|
|
741
|
+
? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
|
|
742
|
+
: -1;
|
|
743
|
+
// Review finding c-i/c-ii: resolve null-id functionResponse correlation
|
|
744
|
+
// for the WHOLE event up front, in array order, BEFORE any tool.done is
|
|
745
|
+
// emitted — Gemini's parallel-call convention is that a batch of results
|
|
746
|
+
// mirrors its calls' array position (the same rationale `providerCallIndex`
|
|
747
|
+
// records at mint time, §8 item 2). Doing this as one event-scoped pass
|
|
748
|
+
// (rather than resolving inline as each part streams past) is what makes a
|
|
749
|
+
// multi-response event's positional pairing an explicit, testable
|
|
750
|
+
// guarantee instead of an accident of loop order. A lone response in its
|
|
751
|
+
// own event is the degenerate one-element case of the same pass.
|
|
752
|
+
const nullIdResponseIds = new Map();
|
|
753
|
+
parts.forEach((part, idx) => {
|
|
754
|
+
const fr = part.functionResponse;
|
|
755
|
+
if (fr === undefined)
|
|
756
|
+
return;
|
|
757
|
+
if (fr.id != null && fr.id.length > 0)
|
|
758
|
+
return; // real id — resolved directly, not via this map
|
|
759
|
+
nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
|
|
760
|
+
});
|
|
761
|
+
// §8.3 — verbatim port of the legacy suppression, with e.push(...) → a.<primitive>.
|
|
762
|
+
const alreadyStreamed = streamedText.get(key) ?? "";
|
|
763
|
+
const isAggregate = !isPartial && alreadyStreamed.length > 0;
|
|
764
|
+
const aggregateText = isAggregate
|
|
765
|
+
? parts
|
|
766
|
+
.filter((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
|
|
767
|
+
.map((p) => p.text ?? "")
|
|
768
|
+
.join("")
|
|
769
|
+
: "";
|
|
770
|
+
const suppressAggregateText = isAggregate && aggregateText.length > 0 && alreadyStreamed.startsWith(aggregateText);
|
|
771
|
+
let residualTail = isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
|
|
772
|
+
let accumulated = alreadyStreamed;
|
|
773
|
+
parts.forEach((part, index) => {
|
|
774
|
+
const isAggregateText = isAggregate &&
|
|
775
|
+
part.thought !== true &&
|
|
776
|
+
part.functionCall === undefined &&
|
|
777
|
+
part.text !== undefined;
|
|
778
|
+
if (isAggregateText) {
|
|
779
|
+
if (suppressAggregateText) {
|
|
780
|
+
// NOTE: fully-suppressed aggregate — this event emits NO text.end at all
|
|
781
|
+
// for this part; its text.end already fired on an earlier PARTIAL event.
|
|
782
|
+
// Gemini grounding metadata is not documented to land on an intermediate
|
|
783
|
+
// partial, so this combination is believed unreachable; if it occurs,
|
|
784
|
+
// citations are dropped rather than force-attached to the wrong
|
|
785
|
+
// (already-sealed) block.
|
|
786
|
+
accumulated += part.text ?? "";
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
if (residualTail.length > 0) {
|
|
790
|
+
const id = `text:${index}`;
|
|
791
|
+
a.textStart(id, messageId);
|
|
792
|
+
a.textDelta(id, messageId, residualTail);
|
|
793
|
+
a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
|
|
794
|
+
residualTail = "";
|
|
795
|
+
}
|
|
796
|
+
accumulated += part.text ?? "";
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, index === citedPartIndex ? citations : undefined);
|
|
800
|
+
if (isPartial)
|
|
801
|
+
accumulated += contributed;
|
|
802
|
+
});
|
|
803
|
+
if (isPartial)
|
|
804
|
+
streamedText.set(key, accumulated);
|
|
805
|
+
else if (isAggregate)
|
|
806
|
+
streamedText.delete(key);
|
|
807
|
+
// Round-3 review finding (regression on finding b): the resend window's
|
|
808
|
+
// lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
|
|
809
|
+
// (see the `ToolCallMintState` doc above) already clears each null-id
|
|
810
|
+
// call's own contentKey entry as it's consumed while processing this
|
|
811
|
+
// event's parts, above. There is deliberately NO blanket
|
|
812
|
+
// `openWindowCounts.delete(turnId)` here anymore: that used to wipe the
|
|
813
|
+
// WHOLE turn's window map on ANY non-partial event, including one that
|
|
814
|
+
// carries no null-id calls for the still-open content key at all (a
|
|
815
|
+
// different tool's real-id call, a text aggregate) — which silently
|
|
816
|
+
// dropped a still-in-flight window and made its true aggregate resend
|
|
817
|
+
// re-mint+re-emit a duplicate tool.start. Entries for windows whose
|
|
818
|
+
// aggregate never arrives simply die with the invoke's closure — bounded,
|
|
819
|
+
// per-invoke.
|
|
820
|
+
driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks); // standalone/content arms (Tasks 4–5)
|
|
821
|
+
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
822
|
+
}
|
|
823
|
+
return {
|
|
824
|
+
push(native) {
|
|
825
|
+
if (!isAdkEvent(native)) {
|
|
826
|
+
a.emitExt("google", "unparsed", { native });
|
|
827
|
+
return a.drain();
|
|
828
|
+
}
|
|
829
|
+
drive(native);
|
|
830
|
+
return a.drain();
|
|
831
|
+
},
|
|
832
|
+
flush() {
|
|
833
|
+
// Dangling open turns (interrupted stream before a final aggregate):
|
|
834
|
+
// close their message; the ENGINE flush closes the turn itself with
|
|
835
|
+
// turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
|
|
836
|
+
// This is deliberately true even when `pendingAsks` holds asks for one
|
|
837
|
+
// of these turns: a HITL pause that never reached the REAL close path
|
|
838
|
+
// (the is_final_response aggregate — see `maybeCloseTurn`) is an
|
|
839
|
+
// INTERRUPTED stream, not a resolved pause. A truncated pause is a
|
|
840
|
+
// truncation — `pendingAsks` is never consulted here (audit M26).
|
|
841
|
+
for (const turnId of openTurns) {
|
|
842
|
+
if (!closedTurns.has(turnId)) {
|
|
843
|
+
closedTurns.add(turnId);
|
|
844
|
+
a.closeMessage(`msg_${turnId}`);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
return a.flush();
|
|
848
|
+
},
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
//# sourceMappingURL=index.js.map
|