@silverprotocol/google-adk 0.12.4 → 1.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -7
- package/dist/index.d.ts +29 -28
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +938 -124
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +973 -130
package/src/index.ts
CHANGED
|
@@ -75,11 +75,11 @@
|
|
|
75
75
|
* the model's reply share one turn: ADK yields the call generation's
|
|
76
76
|
* turnComplete after the function response and before the reply (a
|
|
77
77
|
* gemini-3.8-live capture `live-tool-gemini38live`), so a turnComplete with no
|
|
78
|
-
* model output since the last function response does not close the turn.
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
78
|
+
* model output since the last function response does not close the turn. A
|
|
79
|
+
* generation that follows a completed generation opens the next turn
|
|
80
|
+
* (liveTurnFor), and an `{interrupted}` that follows a completed generation
|
|
81
|
+
* interrupts the next one, which closes `turn.abort{interrupted}`. One limit
|
|
82
|
+
* remains. When text is buffered at the interrupt, ADK yields only the text
|
|
83
83
|
* aggregate, without the flag (utils/live_connection_utils.js), so this facet
|
|
84
84
|
* sees no interrupt and the turn closes at flush as `stream-truncated`.
|
|
85
85
|
*/
|
|
@@ -258,8 +258,11 @@ export interface AdkEvent {
|
|
|
258
258
|
finishReason?: string;
|
|
259
259
|
/** Provider error code (Gemini block reason) — surfaces a non-STOP finish. */
|
|
260
260
|
errorCode?: string;
|
|
261
|
-
/** Free-text error message accompanying errorCode for hard errors.
|
|
262
|
-
* errorCode AND errorMessage
|
|
261
|
+
/** Free-text error message accompanying errorCode for hard errors. An event
|
|
262
|
+
* with BOTH errorCode AND errorMessage is an in-band invocation error: the
|
|
263
|
+
* facet emits a non-terminal `error` event when it arrives, and the
|
|
264
|
+
* invocation's turn closes with turn.error at the invocation's end (spec
|
|
265
|
+
* §8.0 item 35). */
|
|
263
266
|
errorMessage?: string;
|
|
264
267
|
/** Event id (stable per ADK event). */
|
|
265
268
|
id?: string;
|
|
@@ -482,6 +485,8 @@ function resolveFinishReason(reason: string | undefined | null): {
|
|
|
482
485
|
case "PROHIBITED_CONTENT":
|
|
483
486
|
case "SPII":
|
|
484
487
|
case "IMAGE_SAFETY":
|
|
488
|
+
case "IMAGE_PROHIBITED_CONTENT":
|
|
489
|
+
case "IMAGE_RECITATION":
|
|
485
490
|
return { value: "safety_blocked", lossy: false };
|
|
486
491
|
case "MALFORMED_FUNCTION_CALL":
|
|
487
492
|
return { value: "malformed_tool_call", lossy: false };
|
|
@@ -734,6 +739,53 @@ const USAGE_SUM_FIELDS = [
|
|
|
734
739
|
"responseTokenCount",
|
|
735
740
|
] as const;
|
|
736
741
|
|
|
742
|
+
/** The per-kind count members of AgUsage, which sumUsage sums with an absent
|
|
743
|
+
* count read as 0. */
|
|
744
|
+
const USAGE_COUNTS = [
|
|
745
|
+
"inputTokens",
|
|
746
|
+
"outputTokens",
|
|
747
|
+
"cacheReadTokens",
|
|
748
|
+
"cacheWriteTokens",
|
|
749
|
+
"reasoningTokens",
|
|
750
|
+
"toolUseInputTokens",
|
|
751
|
+
"serverToolRequests",
|
|
752
|
+
] as const;
|
|
753
|
+
|
|
754
|
+
/** The aggregate members of AgUsage, which sumUsage sums only when both
|
|
755
|
+
* records carry them: a total or a cost one record lacks would understate
|
|
756
|
+
* the sum (spec §4: totals are copied, never computed). */
|
|
757
|
+
const USAGE_AGGREGATES = ["totalTokens", "totalTokensRaw", "costUsd"] as const;
|
|
758
|
+
|
|
759
|
+
/** The field-wise sum of two usage records: each per-kind count present in
|
|
760
|
+
* either is summed (an absent count is 0), each aggregate only when both
|
|
761
|
+
* carry it (otherwise it is omitted), per model too; every other member is
|
|
762
|
+
* the first record's, else the second's. Either absent returns the other. */
|
|
763
|
+
function sumUsage(a: AgUsage | undefined, b: AgUsage | undefined): AgUsage | undefined {
|
|
764
|
+
if (a === undefined) return b;
|
|
765
|
+
if (b === undefined) return a;
|
|
766
|
+
const out: AgUsage = { ...b, ...a };
|
|
767
|
+
for (const key of USAGE_COUNTS) {
|
|
768
|
+
const x = a[key];
|
|
769
|
+
const y = b[key];
|
|
770
|
+
if (x !== undefined || y !== undefined) out[key] = (x ?? 0) + (y ?? 0);
|
|
771
|
+
}
|
|
772
|
+
for (const key of USAGE_AGGREGATES) {
|
|
773
|
+
const x = a[key];
|
|
774
|
+
const y = b[key];
|
|
775
|
+
if (x !== undefined && y !== undefined) out[key] = x + y;
|
|
776
|
+
else delete out[key];
|
|
777
|
+
}
|
|
778
|
+
if (a.byModel !== undefined || b.byModel !== undefined) {
|
|
779
|
+
const byModel: { [model: string]: AgUsage } = {};
|
|
780
|
+
for (const model of new Set([...Object.keys(a.byModel ?? {}), ...Object.keys(b.byModel ?? {})])) {
|
|
781
|
+
const sum = sumUsage(a.byModel?.[model], b.byModel?.[model]);
|
|
782
|
+
if (sum !== undefined) byModel[model] = sum;
|
|
783
|
+
}
|
|
784
|
+
out.byModel = byModel;
|
|
785
|
+
}
|
|
786
|
+
return out;
|
|
787
|
+
}
|
|
788
|
+
|
|
737
789
|
/** Fold one event's usageMetadata into a turn's running accumulator
|
|
738
790
|
* (field-wise sum; absent fields stay absent so mapUsage's presence checks
|
|
739
791
|
* keep working). Returns the accumulator (creating it on first use). */
|
|
@@ -766,6 +818,51 @@ function mapBlockedSafety(ratings: AdkEvent["safetyRatings"]): AgSafety[] | unde
|
|
|
766
818
|
return out.length > 0 ? out : undefined;
|
|
767
819
|
}
|
|
768
820
|
|
|
821
|
+
// ─── ADK's prompt-block event (errorCode) → prompt.blocked (spec §4) ─────────
|
|
822
|
+
/**
|
|
823
|
+
* The errorCode values that mark an ADK event as a blocked prompt: genai
|
|
824
|
+
* 2.24.0's `BlockedReason` values and the Gemini API's spelling of the
|
|
825
|
+
* unspecified one. In StreamingMode NONE, @google/adk 2.1.0's
|
|
826
|
+
* `createLlmResponse` (models/llm_response.js) turns a blocked prompt into an
|
|
827
|
+
* event whose errorCode is the block reason, with no finishReason, no content
|
|
828
|
+
* and no safety ratings. Exported so the e2e suite's genai pin test
|
|
829
|
+
* (e2e/src/adk-prompt-block-reasons.pin.test.ts) can hold it against genai's
|
|
830
|
+
* own `BlockedReason`. It restates the peer's native values, so it changes
|
|
831
|
+
* when they do.
|
|
832
|
+
*
|
|
833
|
+
* @beta
|
|
834
|
+
*/
|
|
835
|
+
export const ADK_PROMPT_BLOCK_REASONS: readonly string[] = [
|
|
836
|
+
"BLOCKED_REASON_UNSPECIFIED",
|
|
837
|
+
"SAFETY",
|
|
838
|
+
"OTHER",
|
|
839
|
+
"BLOCKLIST",
|
|
840
|
+
"PROHIBITED_CONTENT",
|
|
841
|
+
"IMAGE_SAFETY",
|
|
842
|
+
"MODEL_ARMOR",
|
|
843
|
+
"JAILBREAK",
|
|
844
|
+
"BLOCK_REASON_UNSPECIFIED",
|
|
845
|
+
];
|
|
846
|
+
const PROMPT_BLOCK_REASONS: ReadonlySet<string> = new Set(ADK_PROMPT_BLOCK_REASONS);
|
|
847
|
+
|
|
848
|
+
/** The block reason when an event is an ADK prompt block (a treated errorCode,
|
|
849
|
+
* no finishReason, which a response-level block keeps beside errorCode, no
|
|
850
|
+
* content parts, and not relayed), else undefined. ADK's A2A relay marks each
|
|
851
|
+
* event it forwards with an a2a:response entry in customMetadata and drops the
|
|
852
|
+
* finishReason, so a relayed prompt block and a relayed response-level block
|
|
853
|
+
* with the same code arrive alike: no relayed event is read as a prompt block. */
|
|
854
|
+
function adkPromptBlockReason(event: AdkEvent): string | undefined {
|
|
855
|
+
const code: unknown = event.errorCode;
|
|
856
|
+
const relayed = isJsonObject(event.customMetadata) && Object.hasOwn(event.customMetadata, "a2a:response");
|
|
857
|
+
return typeof code === "string" &&
|
|
858
|
+
PROMPT_BLOCK_REASONS.has(code) &&
|
|
859
|
+
event.finishReason === undefined &&
|
|
860
|
+
(event.content?.parts ?? []).length === 0 &&
|
|
861
|
+
!relayed
|
|
862
|
+
? code
|
|
863
|
+
: undefined;
|
|
864
|
+
}
|
|
865
|
+
|
|
769
866
|
// ─── promptFeedback.blockReason → prompt.blocked reason (spec §4) ────────────
|
|
770
867
|
// Maps Gemini blockReason to the AgJSON prompt.blocked reason enum.
|
|
771
868
|
function mapBlockReason(reason: string): "safety" | "blocklist" | "prohibited" | "other" {
|
|
@@ -970,6 +1067,33 @@ function hasLiveContent(ev: AdkEvent): boolean {
|
|
|
970
1067
|
return (ev.content?.parts?.length ?? 0) > 0 || ev.inputTranscription !== undefined || ev.outputTranscription !== undefined;
|
|
971
1068
|
}
|
|
972
1069
|
|
|
1070
|
+
// Members of an ADK event that the facet maps to nothing, with the values
|
|
1071
|
+
// ADK gives them by default; a member's other value, or any other member,
|
|
1072
|
+
// maps to something. The `actions` members are listed below.
|
|
1073
|
+
const NO_EMIT_EVENT_MEMBERS: ReadonlySet<string> = new Set(["invocationId", "author", "id", "timestamp"]);
|
|
1074
|
+
const NO_EMIT_ACTION_MEMBERS: ReadonlySet<string> = new Set(["artifactDelta", "requestedAuthConfigs", "requestedToolConfirmations"]);
|
|
1075
|
+
|
|
1076
|
+
function isEmptyObject(v: unknown): boolean {
|
|
1077
|
+
return isJsonObject(v) && Object.keys(v).length === 0;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/** Whether all an event maps to is the state.delta of its stateDelta (or
|
|
1081
|
+
* nothing): every member is one the facet maps to nothing, holding ADK's
|
|
1082
|
+
* default value, but for `actions.stateDelta`. */
|
|
1083
|
+
function onlyStateChange(ev: AdkEvent): boolean {
|
|
1084
|
+
for (const [key, value] of Object.entries(ev)) {
|
|
1085
|
+
if (value === undefined || NO_EMIT_EVENT_MEMBERS.has(key)) continue;
|
|
1086
|
+
if (key === "longRunningToolIds" && Array.isArray(value) && value.length === 0) continue;
|
|
1087
|
+
if (key !== "actions" || !isJsonObject(value)) return false;
|
|
1088
|
+
for (const [action, member] of Object.entries(value)) {
|
|
1089
|
+
if (member === undefined || action === "stateDelta") continue;
|
|
1090
|
+
if (action === "escalate" && member === false) continue;
|
|
1091
|
+
if (!NO_EMIT_ACTION_MEMBERS.has(action) || !isEmptyObject(member)) return false;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return true;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
973
1097
|
/** Whether an event carries model output: a part of `model`-role content, or
|
|
974
1098
|
* output-transcription text. ADK's function response is `user`-role. */
|
|
975
1099
|
function hasModelOutput(ev: AdkEvent): boolean {
|
|
@@ -1219,17 +1343,104 @@ function mapGroundingCitations(
|
|
|
1219
1343
|
gm: AdkEvent["groundingMetadata"]
|
|
1220
1344
|
): AgCitation[] | undefined {
|
|
1221
1345
|
if (gm?.groundingSupports === undefined || gm.groundingSupports.length === 0) return undefined;
|
|
1222
|
-
return gm.groundingSupports.map((support): AgCitation =>
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1346
|
+
return gm.groundingSupports.map((support: unknown): AgCitation => {
|
|
1347
|
+
// genai types these members (numbers, a string, number lists). A value of
|
|
1348
|
+
// another type has no AgCitation home: the citation takes the member's
|
|
1349
|
+
// default (0, "", []) or, for the optional scores, omits it, and the
|
|
1350
|
+
// event-level carry holds the native value verbatim
|
|
1351
|
+
// (groundingSupportsCarry). Nothing is filtered: ADK pairs each score with
|
|
1352
|
+
// the chunk index at the same position.
|
|
1353
|
+
const read = readSupport(support);
|
|
1354
|
+
return {
|
|
1355
|
+
kind: "offset",
|
|
1356
|
+
unit: "byte",
|
|
1357
|
+
startIndex: read.startIndex ?? 0,
|
|
1358
|
+
endIndex: read.endIndex ?? 0,
|
|
1359
|
+
bounds: "[start,end)",
|
|
1360
|
+
sourceIds: (read.chunkIndices ?? []).map((i) => `grounding_${i}`),
|
|
1361
|
+
...(read.scores !== undefined ? { confidenceScores: read.scores } : {}),
|
|
1362
|
+
citedText: read.text ?? "",
|
|
1363
|
+
indexFrame: "response",
|
|
1364
|
+
};
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/** One grounding support's members as AgCitation takes them. An absent or
|
|
1369
|
+
* JSON-null member reads as its default; a member of another type reads as undefined, and its
|
|
1370
|
+
* native value is named in `unmapped`. */
|
|
1371
|
+
function readSupport(support: unknown): {
|
|
1372
|
+
startIndex: number | undefined;
|
|
1373
|
+
endIndex: number | undefined;
|
|
1374
|
+
text: string | undefined;
|
|
1375
|
+
chunkIndices: number[] | undefined;
|
|
1376
|
+
scores: number[] | undefined;
|
|
1377
|
+
unmapped: { [k: string]: JsonValue };
|
|
1378
|
+
} {
|
|
1379
|
+
const unmapped: { [k: string]: JsonValue } = {};
|
|
1380
|
+
const member = (key: string): unknown => (isJsonObject(support) ? support[key] : undefined);
|
|
1381
|
+
const segment = member("segment");
|
|
1382
|
+
const seg = (key: string): unknown => (isJsonObject(segment) ? segment[key] : undefined);
|
|
1383
|
+
const startRaw = seg("startIndex");
|
|
1384
|
+
const endRaw = seg("endIndex");
|
|
1385
|
+
const textRaw = seg("text");
|
|
1386
|
+
const startIndex = startRaw === undefined || startRaw === null ? 0 : finiteNumber(startRaw);
|
|
1387
|
+
const endIndex = endRaw === undefined || endRaw === null ? 0 : finiteNumber(endRaw);
|
|
1388
|
+
const text = textRaw === undefined || textRaw === null ? "" : typeof textRaw === "string" ? textRaw : undefined;
|
|
1389
|
+
const segmentMapped = (segment === undefined || segment === null || isJsonObject(segment)) && startIndex !== undefined && endIndex !== undefined && text !== undefined;
|
|
1390
|
+
if (!segmentMapped) unmapped["segment"] = JsonValue.parse(segment);
|
|
1391
|
+
const indicesRaw = member("groundingChunkIndices");
|
|
1392
|
+
const chunkIndices = indicesRaw === undefined || indicesRaw === null ? [] : chunkIndexList(indicesRaw);
|
|
1393
|
+
if (chunkIndices === undefined) unmapped["groundingChunkIndices"] = JsonValue.parse(indicesRaw);
|
|
1394
|
+
const scoresRaw = member("confidenceScores");
|
|
1395
|
+
const scores = scoresRaw === undefined || scoresRaw === null ? [] : finiteScores(scoresRaw);
|
|
1396
|
+
if (scores === undefined) unmapped["confidenceScores"] = JsonValue.parse(scoresRaw);
|
|
1397
|
+
return { startIndex, endIndex, text, chunkIndices, scores, unmapped };
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/** The value when it is a finite number, else undefined. */
|
|
1401
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
1402
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
/** The value when it is a list of finite numbers, else undefined. */
|
|
1406
|
+
function finiteScores(value: unknown): number[] | undefined {
|
|
1407
|
+
if (!Array.isArray(value)) return undefined;
|
|
1408
|
+
const scores: number[] = [];
|
|
1409
|
+
for (const score of value) {
|
|
1410
|
+
const n = finiteNumber(score);
|
|
1411
|
+
if (n === undefined) return undefined;
|
|
1412
|
+
scores.push(n);
|
|
1413
|
+
}
|
|
1414
|
+
return scores;
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
/** The value when it is a list of chunk indexes (non-negative integers), else
|
|
1418
|
+
* undefined. */
|
|
1419
|
+
function chunkIndexList(value: unknown): number[] | undefined {
|
|
1420
|
+
if (!Array.isArray(value)) return undefined;
|
|
1421
|
+
const indices: number[] = [];
|
|
1422
|
+
for (const index of value) {
|
|
1423
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return undefined;
|
|
1424
|
+
indices.push(index);
|
|
1425
|
+
}
|
|
1426
|
+
return indices;
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
/** The grounding supports' members that mapGroundingCitations could not map,
|
|
1430
|
+
* verbatim at their native path: one entry per support, in order, holding
|
|
1431
|
+
* those members (the whole `segment` when one of its members did not map)
|
|
1432
|
+
* and nothing for a support that mapped whole. Undefined when every support
|
|
1433
|
+
* mapped. */
|
|
1434
|
+
function groundingSupportsCarry(gm: AdkEvent["groundingMetadata"]): JsonValue | undefined {
|
|
1435
|
+
const supports: unknown = gm?.groundingSupports;
|
|
1436
|
+
if (!Array.isArray(supports)) return undefined;
|
|
1437
|
+
let any = false;
|
|
1438
|
+
const entries = supports.map((support: unknown): JsonValue => {
|
|
1439
|
+
const { unmapped } = readSupport(support);
|
|
1440
|
+
if (Object.keys(unmapped).length > 0) any = true;
|
|
1441
|
+
return unmapped;
|
|
1442
|
+
});
|
|
1443
|
+
return any ? { groundingSupports: entries } : undefined;
|
|
1233
1444
|
}
|
|
1234
1445
|
|
|
1235
1446
|
// ─── null-id call mint state (audit M47; window/correlation redesign — review
|
|
@@ -1416,10 +1627,80 @@ function mintBlockId(m: BlockIdMint, kind: "text" | "reasoning"): string {
|
|
|
1416
1627
|
return `${kind}:${n}`;
|
|
1417
1628
|
}
|
|
1418
1629
|
|
|
1630
|
+
/** Whether a part carries a member one of driveAdkPart's non-text arms maps:
|
|
1631
|
+
* a call, a result, inline or file data, or code or its result. */
|
|
1632
|
+
function carriesPayload(part: AdkPart): boolean {
|
|
1633
|
+
return (
|
|
1634
|
+
part.functionCall !== undefined ||
|
|
1635
|
+
part.functionResponse !== undefined ||
|
|
1636
|
+
part.inlineData !== undefined ||
|
|
1637
|
+
part.fileData !== undefined ||
|
|
1638
|
+
part.executableCode !== undefined ||
|
|
1639
|
+
part.codeExecutionResult !== undefined
|
|
1640
|
+
);
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
/** An event's parts with each part that holds text beside a payload member,
|
|
1644
|
+
* or two or more payload members, split into one part per payload member in
|
|
1645
|
+
* driveAdkPart's arm order, after a part holding its text (a genai Part holds
|
|
1646
|
+
* one kind of data, so such a part is malformed; every arm returns, and each
|
|
1647
|
+
* arm after the first would never map). The first part keeps the text, the
|
|
1648
|
+
* thought signature and every unmapped member (they are carried once); each
|
|
1649
|
+
* payload part holds its member alone, marked as thought when the original
|
|
1650
|
+
* part was. So the parts map as the same event with the split parts would
|
|
1651
|
+
* (but for the positions below): the text in its text or reasoning block,
|
|
1652
|
+
* and each payload member through its own arm, credential scrubs included
|
|
1653
|
+
* (SPEC.md §8.0, graceful degradation: no native value is dropped
|
|
1654
|
+
* silently). Any other part is
|
|
1655
|
+
* unchanged, and an event with no such part keeps its array. `origin` holds,
|
|
1656
|
+
* for each resulting part, the index of the native part it came from: a
|
|
1657
|
+
* null-id call's providerCallIndex and tool.start's `index` record that
|
|
1658
|
+
* original position (SPEC.md §8.0 item 2), never the split one. */
|
|
1659
|
+
function splitPayloadParts(parts: readonly AdkPart[]): { parts: readonly AdkPart[]; origin: readonly number[] } {
|
|
1660
|
+
if (!parts.some((p) => payloadCount(p) > (typeof p.text === "string" ? 0 : 1))) return { parts, origin: parts.map((_, i) => i) };
|
|
1661
|
+
const out: AdkPart[] = [];
|
|
1662
|
+
const origin: number[] = [];
|
|
1663
|
+
for (const [nativeIndex, part] of parts.entries()) {
|
|
1664
|
+
const textual = typeof part.text === "string";
|
|
1665
|
+
if (payloadCount(part) <= (textual ? 0 : 1)) {
|
|
1666
|
+
out.push(part);
|
|
1667
|
+
origin.push(nativeIndex);
|
|
1668
|
+
continue;
|
|
1669
|
+
}
|
|
1670
|
+
const { functionCall, functionResponse, inlineData, executableCode, codeExecutionResult, fileData, ...rest } = part;
|
|
1671
|
+
const mark: AdkPart = part.thought === true ? { thought: true } : {};
|
|
1672
|
+
const halves: AdkPart[] = [];
|
|
1673
|
+
if (functionCall !== undefined) halves.push({ functionCall, ...mark });
|
|
1674
|
+
if (functionResponse !== undefined) halves.push({ functionResponse, ...mark });
|
|
1675
|
+
if (inlineData !== undefined) halves.push({ inlineData, ...mark });
|
|
1676
|
+
if (executableCode !== undefined) halves.push({ executableCode, ...mark });
|
|
1677
|
+
if (codeExecutionResult !== undefined) halves.push({ codeExecutionResult, ...mark });
|
|
1678
|
+
if (fileData !== undefined) halves.push({ fileData, ...mark });
|
|
1679
|
+
const [first, ...others] = halves;
|
|
1680
|
+
const split: AdkPart[] = textual || first === undefined ? [rest, ...halves] : [{ ...rest, ...first }, ...others];
|
|
1681
|
+
out.push(...split);
|
|
1682
|
+
for (let k = 0; k < split.length; k++) origin.push(nativeIndex);
|
|
1683
|
+
}
|
|
1684
|
+
return { parts: out, origin };
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
/** How many of driveAdkPart's payload members a part holds. */
|
|
1688
|
+
function payloadCount(part: AdkPart): number {
|
|
1689
|
+
let n = 0;
|
|
1690
|
+
if (part.functionCall !== undefined) n++;
|
|
1691
|
+
if (part.functionResponse !== undefined) n++;
|
|
1692
|
+
if (part.inlineData !== undefined) n++;
|
|
1693
|
+
if (part.executableCode !== undefined) n++;
|
|
1694
|
+
if (part.codeExecutionResult !== undefined) n++;
|
|
1695
|
+
if (part.fileData !== undefined) n++;
|
|
1696
|
+
return n;
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1419
1699
|
function driveAdkPart(
|
|
1420
1700
|
a: StreamAssembler,
|
|
1421
1701
|
part: AdkPart,
|
|
1422
1702
|
index: number,
|
|
1703
|
+
nativeIndex: number,
|
|
1423
1704
|
event: AdkEvent,
|
|
1424
1705
|
messageId: string,
|
|
1425
1706
|
turnId: string,
|
|
@@ -1467,6 +1748,15 @@ function driveAdkPart(
|
|
|
1467
1748
|
unmappedPartFields["mediaProcessing"] = JsonValue.parse(part.mediaProcessing);
|
|
1468
1749
|
if (part.speechMetadata !== undefined)
|
|
1469
1750
|
unmappedPartFields["speechMetadata"] = JsonValue.parse(part.speechMetadata);
|
|
1751
|
+
// A part marked as thought that carries no text but a call, a result or
|
|
1752
|
+
// media (ADK-Python's A2A relay marks every part it converts from a remote
|
|
1753
|
+
// agent's in-progress status as thought) maps through that
|
|
1754
|
+
// payload's arm below, as it would unmarked, and not as an empty reasoning
|
|
1755
|
+
// block. Its `thought` flag, which no event of those arms holds, rides this
|
|
1756
|
+
// carry (SPEC.md §8.0, graceful degradation: no native value is dropped
|
|
1757
|
+
// silently).
|
|
1758
|
+
const thoughtPayload = part.thought === true && typeof part.text !== "string" && carriesPayload(part);
|
|
1759
|
+
if (thoughtPayload) unmappedPartFields["thought"] = true;
|
|
1470
1760
|
if (Object.keys(unmappedPartFields).length > 0) {
|
|
1471
1761
|
a.contentBlock(messageId, {
|
|
1472
1762
|
type: "provider-raw",
|
|
@@ -1476,7 +1766,7 @@ function driveAdkPart(
|
|
|
1476
1766
|
}
|
|
1477
1767
|
|
|
1478
1768
|
// ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
|
|
1479
|
-
if (part.thought === true) {
|
|
1769
|
+
if (part.thought === true && !thoughtPayload) {
|
|
1480
1770
|
const id = mintBlockId(blockIds, "reasoning");
|
|
1481
1771
|
a.reasoningStart(id, messageId);
|
|
1482
1772
|
// typeof, not `!== undefined`: a JSON-null text is absent (null guard).
|
|
@@ -1543,7 +1833,8 @@ function driveAdkPart(
|
|
|
1543
1833
|
if (minted.resend) return ""; // dedup the partial:false aggregate re-send (window-scoped content identity)
|
|
1544
1834
|
toolCallId = minted.toolCallId;
|
|
1545
1835
|
}
|
|
1546
|
-
|
|
1836
|
+
// The native part's position, not the split one (see splitPayloadParts).
|
|
1837
|
+
const providerCallIndex = realId !== null ? undefined : nativeIndex;
|
|
1547
1838
|
// The reserved credential call's args carry the whole ADK AuthConfig: scrub
|
|
1548
1839
|
// them to the allowlist (see scrubAdkAuthConfig) before they reach
|
|
1549
1840
|
// tool.args.* and the folded tool-call block.
|
|
@@ -1556,7 +1847,7 @@ function driveAdkPart(
|
|
|
1556
1847
|
a.toolStart({
|
|
1557
1848
|
toolCallId,
|
|
1558
1849
|
name: fc.name,
|
|
1559
|
-
index,
|
|
1850
|
+
index: nativeIndex,
|
|
1560
1851
|
longRunning,
|
|
1561
1852
|
providerMetadata:
|
|
1562
1853
|
providerCallIndex !== undefined
|
|
@@ -1729,7 +2020,8 @@ function driveAdkTopLevel(
|
|
|
1729
2020
|
turnId: string,
|
|
1730
2021
|
pendingAsks: Map<string, AgPausedAsk[]>,
|
|
1731
2022
|
reserved: ReservedAskState,
|
|
1732
|
-
streamedTranscription: Map<string, string
|
|
2023
|
+
streamedTranscription: Map<string, string>,
|
|
2024
|
+
turnClosed: boolean
|
|
1733
2025
|
): void {
|
|
1734
2026
|
// Transcriptions (Live): ADK streams chunks (`finished: false`), then yields
|
|
1735
2027
|
// a `finished: true` transcription whose text is the chunks joined
|
|
@@ -1764,8 +2056,16 @@ function driveAdkTopLevel(
|
|
|
1764
2056
|
// `interrupted` → turn.abort is closed in drive(), after this event's own
|
|
1765
2057
|
// content and carries (see closeInterrupted), never here mid-event.
|
|
1766
2058
|
|
|
1767
|
-
// ──
|
|
1768
|
-
|
|
2059
|
+
// ── prompt block → prompt.blocked: one record per block event while the turn
|
|
2060
|
+
// is open, never after its terminal. A record runs before the close logic, so
|
|
2061
|
+
// it precedes the terminal the same event may bring; the terminal itself is
|
|
2062
|
+
// unchanged. An event carrying promptFeedback is recorded from it (a
|
|
2063
|
+
// dual-shape event records once); otherwise ADK's own shape records: a treated
|
|
2064
|
+
// errorCode with no finishReason and no content (adkPromptBlockReason), reason
|
|
2065
|
+
// mapped as below and no safety, since that event carries no ratings.
|
|
2066
|
+
if (turnClosed) {
|
|
2067
|
+
// no record after the turn's terminal
|
|
2068
|
+
} else if (event.promptFeedback?.blockReason !== undefined) {
|
|
1769
2069
|
const blockReason = event.promptFeedback.blockReason;
|
|
1770
2070
|
const reason = mapBlockReason(blockReason);
|
|
1771
2071
|
const safety =
|
|
@@ -1781,16 +2081,21 @@ function driveAdkTopLevel(
|
|
|
1781
2081
|
: undefined;
|
|
1782
2082
|
// draft.8 (§4): an unmapped block reason (reason "other") carries the
|
|
1783
2083
|
// native value verbatim in reasonRaw; a mapped reason carries none, as a
|
|
1784
|
-
// lossless finishReason takes no finishReasonRaw
|
|
1785
|
-
// @google/adk 2.1.0
|
|
1786
|
-
//
|
|
1787
|
-
// (models/llm_response.js), so this arm serves events built elsewhere.
|
|
2084
|
+
// lossless finishReason takes no finishReasonRaw. No ADK-built event
|
|
2085
|
+
// carries promptFeedback at @google/adk 2.1.0, so this arm serves events
|
|
2086
|
+
// built elsewhere; ADK's own shape is the branch below.
|
|
1788
2087
|
a.emit({
|
|
1789
2088
|
type: "prompt.blocked",
|
|
1790
2089
|
reason,
|
|
1791
2090
|
...(reason === "other" ? { reasonRaw: blockReason } : {}),
|
|
1792
2091
|
...(safety !== undefined ? { safety } : {}),
|
|
1793
2092
|
});
|
|
2093
|
+
} else {
|
|
2094
|
+
const blockReason = adkPromptBlockReason(event);
|
|
2095
|
+
if (blockReason !== undefined) {
|
|
2096
|
+
const reason = mapBlockReason(blockReason);
|
|
2097
|
+
a.emit({ type: "prompt.blocked", reason, ...(reason === "other" ? { reasonRaw: blockReason } : {}) });
|
|
2098
|
+
}
|
|
1794
2099
|
}
|
|
1795
2100
|
|
|
1796
2101
|
// ── groundingMetadata → source + display.required ──────────────────────────
|
|
@@ -1955,8 +2260,10 @@ function driveAdkTopLevel(
|
|
|
1955
2260
|
// absent from `@iqai/adk`'s surface, closed by the same opportunistic-carry
|
|
1956
2261
|
// precedent (absent from all recorded fixtures — no golden-snapshot impact).
|
|
1957
2262
|
//
|
|
1958
|
-
// `author`/`timestamp` are ALSO real
|
|
1959
|
-
//
|
|
2263
|
+
// `author`/`timestamp` are ALSO real AdkEvent fields (same manifest
|
|
2264
|
+
// inventory) but are DELIBERATELY NOT folded into this bag (`author` is read
|
|
2265
|
+
// only by the aggregate window: its key, aggregateWindowKey, and the
|
|
2266
|
+
// same-author lookup in windowCandidates).
|
|
1960
2267
|
// On the official `@google/adk` 1.3.0 `Event` interface `timestamp: number`
|
|
1961
2268
|
// is REQUIRED and `author?: string` is optional in the TYPE — but the
|
|
1962
2269
|
// runner sets author on every event it appends in practice, so the
|
|
@@ -2006,10 +2313,25 @@ function driveAdkTopLevel(
|
|
|
2006
2313
|
unmappedEvent["isolationScope"] = JsonValue.parse(event.isolationScope);
|
|
2007
2314
|
if (event.citationMetadata !== undefined)
|
|
2008
2315
|
unmappedEvent["citationMetadata"] = JsonValue.parse(event.citationMetadata);
|
|
2316
|
+
const groundingSupports = groundingSupportsCarry(event.groundingMetadata);
|
|
2317
|
+
if (groundingSupports !== undefined) unmappedEvent["groundingMetadata"] = groundingSupports;
|
|
2009
2318
|
if (event.customMetadata !== undefined) {
|
|
2010
2319
|
const kept = withoutRelayBookkeeping(JsonValue.parse(event.customMetadata));
|
|
2011
2320
|
if (kept !== undefined) unmappedEvent["customMetadata"] = kept;
|
|
2012
2321
|
}
|
|
2322
|
+
// An error message without an error code (ADK's A2A relay reports its own
|
|
2323
|
+
// failure so, and a remote executor's that it passes on) is not an in-band
|
|
2324
|
+
// invocation error (spec §8.0 item 35), which maps the code and message as a
|
|
2325
|
+
// pair; its message, and a code that is not a string, ride here verbatim
|
|
2326
|
+
// (spec §8.0 graceful degradation and item 23).
|
|
2327
|
+
if (inBandErrorOf(event) === undefined) {
|
|
2328
|
+
const message: unknown = event.errorMessage;
|
|
2329
|
+
const code: unknown = event.errorCode;
|
|
2330
|
+
if (message !== undefined && message !== null) {
|
|
2331
|
+
if (code !== undefined && code !== null) unmappedEvent["errorCode"] = JsonValue.parse(code);
|
|
2332
|
+
unmappedEvent["errorMessage"] = JsonValue.parse(message);
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2013
2335
|
if (Object.keys(unmappedEvent).length > 0) {
|
|
2014
2336
|
a.contentBlock(messageId, {
|
|
2015
2337
|
type: "provider-raw",
|
|
@@ -2071,7 +2393,11 @@ export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
|
|
|
2071
2393
|
* SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
|
|
2072
2394
|
* the stream (e.g. its LLM-call limit), the host catches it and pushes
|
|
2073
2395
|
* `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
|
|
2074
|
-
* open turn closes `turn.error` with that code and message
|
|
2396
|
+
* open turn closes `turn.error` with that code and message and the turn's
|
|
2397
|
+
* usage plus `usage`, which covers only work the stream did not report (so
|
|
2398
|
+
* a host passes the usage of unreported work, never a total); a turn whose
|
|
2399
|
+
* pause was signalled closes paused first, and the error then closes on a
|
|
2400
|
+
* new top-level turn (spec §8.0 item 26). The shape matches the OpenAI
|
|
2075
2401
|
* facet's sentinel. A host may build it from the caught Error itself
|
|
2076
2402
|
* (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
|
|
2077
2403
|
* read from the raw native, so the Error's own message is kept.
|
|
@@ -2131,6 +2457,209 @@ function isHostCompleteNative(v: JsonValue): boolean {
|
|
|
2131
2457
|
* So push() never throws (SPEC §8.0), and no facet state believes a turn,
|
|
2132
2458
|
* message or block is open that never reached the wire.
|
|
2133
2459
|
*/
|
|
2460
|
+
// ─── ADK in-band invocation errors (spec §8.0 item 35) ───────────────────────
|
|
2461
|
+
// ADK yields an in-band invocation error (errorCode AND errorMessage) without
|
|
2462
|
+
// ending the invocation: a SequentialAgent runs its next sub-agent, a Workflow
|
|
2463
|
+
// node retries, a callback or a further model round follows. So the turn never
|
|
2464
|
+
// closes on one: the push() that receives it emits the non-terminal `error`
|
|
2465
|
+
// event, and the invocation's turn closes with one turn.error at the
|
|
2466
|
+
// invocation's end (the host-completion event, a host-terminal event or
|
|
2467
|
+
// flush()), never as success.
|
|
2468
|
+
|
|
2469
|
+
/** Spec §8.0 item 35: an in-band invocation error carries both errorCode and
|
|
2470
|
+
* errorMessage. */
|
|
2471
|
+
function inBandErrorOf(event: AdkEvent): { code: string; message: string } | undefined {
|
|
2472
|
+
const code: unknown = event.errorCode;
|
|
2473
|
+
const message: unknown = event.errorMessage;
|
|
2474
|
+
return typeof code === "string" && typeof message === "string" ? { code, message } : undefined;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
/** The previous event of one source, for item 35's SSE repeat: whether it
|
|
2478
|
+
* carried `partial: false`, the in-band error it carried, its usage report,
|
|
2479
|
+
* and the slot that report took among the turn's counted reports (absent when
|
|
2480
|
+
* it was not counted). */
|
|
2481
|
+
interface PreviousSourceEvent {
|
|
2482
|
+
partialFalse: boolean;
|
|
2483
|
+
error: { code: string; message: string } | undefined;
|
|
2484
|
+
usage: NonNullable<AdkEvent["usageMetadata"]> | undefined;
|
|
2485
|
+
usageSlot: number | undefined;
|
|
2486
|
+
}
|
|
2487
|
+
|
|
2488
|
+
/** An in-band invocation error seen on one source, for item 35's relay
|
|
2489
|
+
* repeat: its code and message, and its usage report and `a2a:task_id`
|
|
2490
|
+
* entry as sorted-key JSON ("" when absent). */
|
|
2491
|
+
interface InBandErrorRecord {
|
|
2492
|
+
code: string;
|
|
2493
|
+
message: string;
|
|
2494
|
+
usage: string;
|
|
2495
|
+
taskId: string;
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
/** The record item 35's relay repeat compares for one in-band error. */
|
|
2499
|
+
function inBandErrorRecord(event: AdkEvent, error: { code: string; message: string }): InBandErrorRecord {
|
|
2500
|
+
const metadata: unknown = event.customMetadata;
|
|
2501
|
+
return {
|
|
2502
|
+
code: error.code,
|
|
2503
|
+
message: error.message,
|
|
2504
|
+
usage: event.usageMetadata !== undefined ? canonicalJson(JsonValue.parse(event.usageMetadata)) : "",
|
|
2505
|
+
taskId: isJsonObject(metadata) && Object.hasOwn(metadata, "a2a:task_id") ? canonicalJson(metadata["a2a:task_id"] ?? null) : "",
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
2508
|
+
|
|
2509
|
+
/** Item 35's relay repeat: `RemoteA2AAgent` stamps an `a2a:request` entry on
|
|
2510
|
+
* each relayed event that carries `turnComplete: true`, and at @google/adk
|
|
2511
|
+
* 2.1.0 it reports a remote failure that carries no content only in that
|
|
2512
|
+
* closing event, so one failure can reach the facet twice. The closing event
|
|
2513
|
+
* repeats an earlier in-band error of the same source when the code, message
|
|
2514
|
+
* and usage report are equal (an absent report matches only an absent one)
|
|
2515
|
+
* and both carry the same `a2a:task_id` entry, present on both. */
|
|
2516
|
+
function isRelayRepeat(event: AdkEvent, record: InBandErrorRecord, earlier: readonly InBandErrorRecord[]): boolean {
|
|
2517
|
+
const metadata: unknown = event.customMetadata;
|
|
2518
|
+
if (event.turnComplete !== true || !isJsonObject(metadata) || !Object.hasOwn(metadata, "a2a:request")) return false;
|
|
2519
|
+
if (record.taskId === "") return false;
|
|
2520
|
+
return earlier.some(
|
|
2521
|
+
(e) => e.taskId === record.taskId && e.code === record.code && e.message === record.message && e.usage === record.usage,
|
|
2522
|
+
);
|
|
2523
|
+
}
|
|
2524
|
+
|
|
2525
|
+
/** The aggregate window's key: the turn plus the event's source (author,
|
|
2526
|
+
* branch and node path). A missing or non-string value is its own key, never
|
|
2527
|
+
* equal to an empty string. */
|
|
2528
|
+
function aggregateWindowKey(turnId: string, event: AdkEvent, stream: string | null = relayStreamOf(event)): string {
|
|
2529
|
+
const author: unknown = event.author;
|
|
2530
|
+
const branch: unknown = event.branch;
|
|
2531
|
+
const path: unknown = event.nodeInfo?.path;
|
|
2532
|
+
return JSON.stringify([
|
|
2533
|
+
turnId,
|
|
2534
|
+
typeof author === "string" ? author : null,
|
|
2535
|
+
typeof branch === "string" ? branch : null,
|
|
2536
|
+
typeof path === "string" ? path : null,
|
|
2537
|
+
stream,
|
|
2538
|
+
]);
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2541
|
+
/** What a relayed event is, read from the native relay record ADK's
|
|
2542
|
+
* RemoteA2AAgent attaches: its A2A task (the `a2a:task_id` entry, null when
|
|
2543
|
+
* the reply carried none) and its stream, one artifact's chunks and their
|
|
2544
|
+
* aggregate (`artifact:<id>`), the status messages (`status`), or a Task or
|
|
2545
|
+
* Message that restates the task (`snapshot`). null for an event that is not
|
|
2546
|
+
* relayed. */
|
|
2547
|
+
function relayOf(event: AdkEvent): { task: string | null; stream: string } | null {
|
|
2548
|
+
const metadata: unknown = event.customMetadata;
|
|
2549
|
+
if (!isJsonObject(metadata)) return null;
|
|
2550
|
+
const response: unknown = metadata["a2a:response"];
|
|
2551
|
+
if (!isJsonObject(response)) return null;
|
|
2552
|
+
const taskId: unknown = metadata["a2a:task_id"];
|
|
2553
|
+
const task = typeof taskId === "string" ? taskId : null;
|
|
2554
|
+
const kind: unknown = response["kind"];
|
|
2555
|
+
const artifact: unknown = response["artifact"];
|
|
2556
|
+
if (kind === "artifact-update" && isJsonObject(artifact) && typeof artifact["artifactId"] === "string")
|
|
2557
|
+
return { task, stream: `artifact:${artifact["artifactId"]}` };
|
|
2558
|
+
if (kind === "status-update") return { task, stream: "status" };
|
|
2559
|
+
if (kind === "task" || kind === "message") return { task, stream: "snapshot" };
|
|
2560
|
+
return null;
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
/** The window-key part of a relayed stream: the task and the stream, so a new
|
|
2564
|
+
* relay pass (a new A2A task) never reads the windows of an earlier one. */
|
|
2565
|
+
function relayStreamKey(task: string | null, stream: string): string {
|
|
2566
|
+
return JSON.stringify([task, stream]);
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
/** The A2A stream a relayed event belongs to, scoped by its task; null for
|
|
2570
|
+
* every event that is not relayed. */
|
|
2571
|
+
function relayStreamOf(event: AdkEvent): string | null {
|
|
2572
|
+
const relay = relayOf(event);
|
|
2573
|
+
return relay === null ? null : relayStreamKey(relay.task, relay.stream);
|
|
2574
|
+
}
|
|
2575
|
+
|
|
2576
|
+
/** The open windows a non-partial event reads and closes: the one under its
|
|
2577
|
+
* own key; else, for an event without a branch, every open window of the
|
|
2578
|
+
* same turn, author and node path. */
|
|
2579
|
+
function windowCandidates(windows: ReadonlyMap<string, string>, turnId: string, event: AdkEvent): string[] {
|
|
2580
|
+
const own = aggregateWindowKey(turnId, event);
|
|
2581
|
+
if (windows.has(own)) return [own];
|
|
2582
|
+
// A relayed artifact with no chunks of its own can repeat the status text
|
|
2583
|
+
// of its own task (a peer that sends its answer as status messages, then
|
|
2584
|
+
// the same text as its final artifact).
|
|
2585
|
+
const relay = relayOf(event);
|
|
2586
|
+
if (relay !== null && relay.stream.startsWith("artifact:")) {
|
|
2587
|
+
const status = aggregateWindowKey(turnId, event, relayStreamKey(relay.task, "status"));
|
|
2588
|
+
if (windows.has(status)) return [status];
|
|
2589
|
+
}
|
|
2590
|
+
if (typeof event.branch === "string") return [];
|
|
2591
|
+
const wantStream = relayStreamOf(event);
|
|
2592
|
+
return sourceWindows(windows, turnId, event, true)
|
|
2593
|
+
.filter(([, stream]) => stream === wantStream)
|
|
2594
|
+
.map(([key]) => key);
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
/** The open windows of the source of an event, as [key, stream] pairs: the
|
|
2598
|
+
* same turn, author and node path, and the same branch unless anyBranch. */
|
|
2599
|
+
function sourceWindows(windows: ReadonlyMap<string, string>, turnId: string, event: AdkEvent, anyBranch: boolean): Array<[string, unknown]> {
|
|
2600
|
+
const author: unknown = event.author;
|
|
2601
|
+
const branch: unknown = event.branch;
|
|
2602
|
+
const path: unknown = event.nodeInfo?.path;
|
|
2603
|
+
const wantAuthor = typeof author === "string" ? author : null;
|
|
2604
|
+
const wantBranch = typeof branch === "string" ? branch : null;
|
|
2605
|
+
const wantPath = typeof path === "string" ? path : null;
|
|
2606
|
+
const out: Array<[string, unknown]> = [];
|
|
2607
|
+
for (const key of windows.keys()) {
|
|
2608
|
+
const parsed: unknown = JSON.parse(key);
|
|
2609
|
+
if (
|
|
2610
|
+
Array.isArray(parsed) &&
|
|
2611
|
+
parsed[0] === turnId &&
|
|
2612
|
+
parsed[1] === wantAuthor &&
|
|
2613
|
+
(anyBranch || parsed[2] === wantBranch) &&
|
|
2614
|
+
parsed[3] === wantPath
|
|
2615
|
+
)
|
|
2616
|
+
out.push([key, parsed[4]]);
|
|
2617
|
+
}
|
|
2618
|
+
return out;
|
|
2619
|
+
}
|
|
2620
|
+
|
|
2621
|
+
/** The windows a relayed Task or Message restates: its task's open artifact
|
|
2622
|
+
* windows, in the order they opened, and its task's status window. */
|
|
2623
|
+
function snapshotWindows(
|
|
2624
|
+
windows: ReadonlyMap<string, string>,
|
|
2625
|
+
turnId: string,
|
|
2626
|
+
event: AdkEvent,
|
|
2627
|
+
task: string | null,
|
|
2628
|
+
): { artifacts: string[]; status: string[] } {
|
|
2629
|
+
const own = sourceWindows(windows, turnId, event, false);
|
|
2630
|
+
const artifacts = own.filter(([, stream]) => {
|
|
2631
|
+
if (typeof stream !== "string") return false;
|
|
2632
|
+
const parsed: unknown = JSON.parse(stream);
|
|
2633
|
+
return Array.isArray(parsed) && parsed[0] === task && typeof parsed[1] === "string" && parsed[1].startsWith("artifact:");
|
|
2634
|
+
});
|
|
2635
|
+
const status = relayStreamKey(task, "status");
|
|
2636
|
+
return { artifacts: artifacts.map(([key]) => key), status: own.filter(([, stream]) => stream === status).map(([key]) => key) };
|
|
2637
|
+
}
|
|
2638
|
+
|
|
2639
|
+
/** The streamed text a relayed Task or Message is read against. ADK renders a
|
|
2640
|
+
* Task as its artifacts' parts, then its status message's (taskToAdkEvent), so
|
|
2641
|
+
* the snapshot is matched in that order: against the artifacts and the status
|
|
2642
|
+
* text together (a task still in the state it streamed), else the artifacts
|
|
2643
|
+
* alone (its status message is new, and renders), else the status text alone.
|
|
2644
|
+
* The first reading the snapshot repeats is taken; with none, the first. */
|
|
2645
|
+
function snapshotReading(artifactText: string, statusText: string, text: string): string {
|
|
2646
|
+
const readings = [artifactText + statusText, artifactText, statusText].filter((r) => r.length > 0);
|
|
2647
|
+
const repeats = (r: string) => text.startsWith(r) || r.startsWith(text) || r.endsWith(text);
|
|
2648
|
+
return readings.find(repeats) ?? readings[0] ?? "";
|
|
2649
|
+
}
|
|
2650
|
+
|
|
2651
|
+
/** The relay windows an event of the relaying agent ends without being
|
|
2652
|
+
* relayed itself: ADK's RemoteA2AAgent reports a failed request with an
|
|
2653
|
+
* event of its own (errorMessage, turnComplete, no relay record), which ends
|
|
2654
|
+
* every relayed stream of that author and node path. */
|
|
2655
|
+
function relayWindowsEndedBy(windows: ReadonlyMap<string, string>, turnId: string, event: AdkEvent): string[] {
|
|
2656
|
+
if (relayOf(event) !== null) return [];
|
|
2657
|
+
if (event.errorMessage === undefined && event.turnComplete !== true) return [];
|
|
2658
|
+
return sourceWindows(windows, turnId, event, true)
|
|
2659
|
+
.filter(([, stream]) => stream !== null)
|
|
2660
|
+
.map(([key]) => key);
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2134
2663
|
export function createAdkNormalizer(options: AdkNormalizerOptions = {}): Normalizer {
|
|
2135
2664
|
// The per-invoke id stem, drawn ONCE here, OUTSIDE the inner, so a rebuild
|
|
2136
2665
|
// re-drives to the same ids and no push() reads randomness.
|
|
@@ -2150,7 +2679,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2150
2679
|
const hostCompletion = options.hostCompletion === true;
|
|
2151
2680
|
const a = new StreamAssembler();
|
|
2152
2681
|
const threadId = options.threadId ?? "google";
|
|
2153
|
-
// §8.3 per-instance accumulator (replaces the module-level streamedText Map)
|
|
2682
|
+
// §8.3 per-instance accumulator (replaces the module-level streamedText Map),
|
|
2683
|
+
// keyed by aggregateWindowKey (turn + source):
|
|
2154
2684
|
const streamedText = new Map<string, string>();
|
|
2155
2685
|
// Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
|
|
2156
2686
|
const streamedTranscription = new Map<string, string>();
|
|
@@ -2170,6 +2700,18 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2170
2700
|
// double-render quirk applies to usage too), so counting non-partial
|
|
2171
2701
|
// events counts each round exactly once.
|
|
2172
2702
|
const usageByTurn = new Map<string, NonNullable<AdkEvent["usageMetadata"]>>();
|
|
2703
|
+
// The usage reports summed into usageByTurn, in order, so the report that an
|
|
2704
|
+
// in-band error's repeat supersedes can be replaced (spec §8.0 item 35).
|
|
2705
|
+
const usageReportsByTurn = new Map<string, Array<NonNullable<AdkEvent["usageMetadata"]>>>();
|
|
2706
|
+
// Spec §8.0 item 35: per turn, the invocation's first in-band invocation
|
|
2707
|
+
// error (errorCode AND errorMessage). The turn never closes on one, never
|
|
2708
|
+
// closes as success after one, and closes with one turn.error at the
|
|
2709
|
+
// invocation's end.
|
|
2710
|
+
const firstInBandError = new Map<string, { code: string; message: string }>();
|
|
2711
|
+
// Per turn and source (author, branch, node path): the previous event, for
|
|
2712
|
+
// item 35's SSE repeat, and the in-band errors seen, for its relay repeat.
|
|
2713
|
+
const previousBySource = new Map<string, PreviousSourceEvent>();
|
|
2714
|
+
const inBandErrorsBySource = new Map<string, InBandErrorRecord[]>();
|
|
2173
2715
|
// Per-turn HITL asks emitted by the two `actions.requested*` arms (audit
|
|
2174
2716
|
// M26) — populated in emission order by `trackPendingAsk` inside
|
|
2175
2717
|
// `driveAdkTopLevel`. Consulted ONLY by `maybeCloseTurn`'s REAL close path
|
|
@@ -2197,6 +2739,16 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2197
2739
|
// opens a new turn, `<turn>_g<n>`, instead of landing in the closed one.
|
|
2198
2740
|
const generationOf = new Map<string, number>();
|
|
2199
2741
|
const interruptClosed = new Set<string>();
|
|
2742
|
+
// Per turn key: whether the previous event carried both turnComplete and
|
|
2743
|
+
// interrupted, the message after which ADK re-yields a bare {interrupted}.
|
|
2744
|
+
const previousBothFlags = new Map<string, boolean>();
|
|
2745
|
+
// Turns a final response closed as success before the invocation ended
|
|
2746
|
+
// (without the host-completion event only). ADK keeps running after such a
|
|
2747
|
+
// final (a SequentialAgent's next sub-agent, a LoopAgent's next iteration),
|
|
2748
|
+
// and content that follows opens the next generation of the turn rather
|
|
2749
|
+
// than landing after its terminal (spec §8.0: framework content that
|
|
2750
|
+
// arrives after a terminal opens a new turn).
|
|
2751
|
+
const successClosed = new Set<string>();
|
|
2200
2752
|
// Turns whose last function response has no model output after it yet. On
|
|
2201
2753
|
// the Live path the model always answers a tool result with a reply
|
|
2202
2754
|
// generation, and ADK can yield the call generation's turnComplete between
|
|
@@ -2236,11 +2788,6 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2236
2788
|
isPartial: boolean
|
|
2237
2789
|
): void {
|
|
2238
2790
|
if (isPartial || closedTurns.has(turnId)) return;
|
|
2239
|
-
// Every non-partial event contributes its per-round usage to the turn's
|
|
2240
|
-
// accumulator — including functionCall rounds, which never close the
|
|
2241
|
-
// turn themselves (see the usageByTurn doc above).
|
|
2242
|
-
const accumulated = accumulateUsage(usageByTurn.get(turnId), event.usageMetadata);
|
|
2243
|
-
if (accumulated !== undefined) usageByTurn.set(turnId, accumulated);
|
|
2244
2791
|
const parts = event.content?.parts ?? [];
|
|
2245
2792
|
const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
|
|
2246
2793
|
const interrupted = event.interrupted === true || interruptPending.has(turnId);
|
|
@@ -2274,36 +2821,47 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2274
2821
|
// A bare Live turnComplete between a function response and the model's
|
|
2275
2822
|
// reply ends the call generation, not the turn (see awaitingReply).
|
|
2276
2823
|
if (event.finishReason === undefined && event.errorCode === undefined && awaitingReply.has(turnId)) return;
|
|
2277
|
-
//
|
|
2278
|
-
//
|
|
2279
|
-
//
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2824
|
+
// Spec §8.0 item 35: an in-band invocation error never closes the turn
|
|
2825
|
+
// (recordErrorAndUsage emitted its `error` event), and once the invocation
|
|
2826
|
+
// met one, no final response closes it either: the invocation's end does
|
|
2827
|
+
// (hostComplete, hostError, flush). A final response while an ask is
|
|
2828
|
+
// pending still signals the pause (item 26).
|
|
2829
|
+
if (inBandErrorOf(event) !== undefined) return;
|
|
2830
|
+
if (firstInBandError.has(turnId)) {
|
|
2831
|
+
if ((pendingAsks.get(turnId)?.length ?? 0) > 0) deferredClose.set(turnId, event);
|
|
2832
|
+
return;
|
|
2833
|
+
}
|
|
2284
2834
|
// ── The nodeInfo gate (R&D item 6, step 1) ──
|
|
2285
2835
|
// ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
|
|
2286
2836
|
// final text (nodeInfo present) is mid-invocation: closing the invocation
|
|
2287
2837
|
// turn on it put the workflow's later events after the terminal and parked
|
|
2288
2838
|
// reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
|
|
2289
2839
|
// closes the turn as success. It is a per-EVENT test, never a latch
|
|
2290
|
-
// (NodeTool puts nodeInfo into plain runs too).
|
|
2291
|
-
//
|
|
2292
|
-
//
|
|
2293
|
-
|
|
2294
|
-
if (errorClose === undefined && event.nodeInfo !== undefined) return;
|
|
2840
|
+
// (NodeTool puts nodeInfo into plain runs too). A completed workflow closes
|
|
2841
|
+
// success only on the host-completion event (the `hostCompletion` opt-in,
|
|
2842
|
+
// §8.0 host obligation 4); without it, it flushes turn.abort.
|
|
2843
|
+
if (event.nodeInfo !== undefined) return;
|
|
2295
2844
|
// Host obligation 4 (opt-in): a success close waits for the
|
|
2296
2845
|
// host-completion event, because the run may not be over (a
|
|
2297
2846
|
// SequentialAgent's next agent, after-agent callback content). A close
|
|
2298
2847
|
// while an ask is pending waits on every host (item 26: the invocation's
|
|
2299
2848
|
// end, the host-completion event or flush()), because the model may run
|
|
2300
2849
|
// again after a pause. The final response is stashed and closed unchanged,
|
|
2301
|
-
// so a stream ending here is byte-identical.
|
|
2302
|
-
if (
|
|
2850
|
+
// so a stream ending here is byte-identical.
|
|
2851
|
+
if (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0) {
|
|
2303
2852
|
deferredClose.set(turnId, event);
|
|
2304
2853
|
return;
|
|
2305
2854
|
}
|
|
2306
|
-
|
|
2855
|
+
// ── The branch gate ──
|
|
2856
|
+
// A final response that carries a `branch` (a ParallelAgent's sub-agent)
|
|
2857
|
+
// ends that branch, not the invocation: ADK runs the other branches after
|
|
2858
|
+
// it, so closing the turn on it put their events after the terminal and
|
|
2859
|
+
// parked reduce() (INV-TURN). Without the host-completion event such a
|
|
2860
|
+
// turn closes at flush(), as a completed Workflow does.
|
|
2861
|
+
if (typeof event.branch === "string") return;
|
|
2862
|
+
// No ask is pending here, so this close is a success.
|
|
2863
|
+
successClosed.add(turnId);
|
|
2864
|
+
closeOnFinalResponse(event, turnId, messageId);
|
|
2307
2865
|
}
|
|
2308
2866
|
|
|
2309
2867
|
/** The paused close at the invocation's end. A final response stashed while
|
|
@@ -2312,7 +2870,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2312
2870
|
function closePaused(turnId: string, messageId: string, asks: AgPausedAsk[]): void {
|
|
2313
2871
|
const stashed = deferredClose.get(turnId);
|
|
2314
2872
|
if (stashed !== undefined) {
|
|
2315
|
-
closeOnFinalResponse(stashed, turnId, messageId
|
|
2873
|
+
closeOnFinalResponse(stashed, turnId, messageId);
|
|
2316
2874
|
return;
|
|
2317
2875
|
}
|
|
2318
2876
|
closedTurns.add(turnId);
|
|
@@ -2326,13 +2884,9 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2326
2884
|
}
|
|
2327
2885
|
|
|
2328
2886
|
/** The close on a final response: lossy-finish metadata, message.end, then
|
|
2329
|
-
* turn.
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
turnId: string,
|
|
2333
|
-
messageId: string,
|
|
2334
|
-
errorClose: { code: string; message: string } | undefined,
|
|
2335
|
-
): void {
|
|
2887
|
+
* turn.done (paused when asks are pending, else success). An in-band
|
|
2888
|
+
* invocation error never reaches it (spec §8.0 item 35). */
|
|
2889
|
+
function closeOnFinalResponse(event: AdkEvent, turnId: string, messageId: string): void {
|
|
2336
2890
|
closedTurns.add(turnId);
|
|
2337
2891
|
const rawFinish = event.finishReason ?? event.errorCode;
|
|
2338
2892
|
const finish = resolveFinishReason(rawFinish);
|
|
@@ -2345,9 +2899,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2345
2899
|
// `rawErrorCode`, never fabricated as a finishReason. Lossy-only (unlike
|
|
2346
2900
|
// vercel-ai's unconditional carry) so no recorded cassette — all STOP
|
|
2347
2901
|
// closes — gains noise. Runs exactly once per turn (real-close path,
|
|
2348
|
-
// closedTurns-guarded), never on partials
|
|
2349
|
-
|
|
2350
|
-
if (errorClose === undefined && rawFinish !== undefined && finish.lossy) {
|
|
2902
|
+
// closedTurns-guarded), never on partials.
|
|
2903
|
+
if (rawFinish !== undefined && finish.lossy) {
|
|
2351
2904
|
a.emit({
|
|
2352
2905
|
type: "message.metadata",
|
|
2353
2906
|
messageId,
|
|
@@ -2357,40 +2910,134 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2357
2910
|
});
|
|
2358
2911
|
}
|
|
2359
2912
|
a.closeMessage(messageId);
|
|
2360
|
-
// The turn's accrued usage rides its terminal
|
|
2361
|
-
// turn.error.usage mirrors turn.done), as the host-error close does.
|
|
2913
|
+
// The turn's accrued usage rides its terminal.
|
|
2362
2914
|
const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2915
|
+
// SPEC §4's safety_blocked conformance note: a safety_blocked close
|
|
2916
|
+
// carries safety[].category so the collapsed reason stays recoverable. A
|
|
2917
|
+
// blocked rating names it; when no rating does (ADK 2.1.0 delivers none on
|
|
2918
|
+
// a real block), the native value finishReason was mapped from is the
|
|
2919
|
+
// category, as a block.
|
|
2920
|
+
const rated = mapBlockedSafety(event.safetyRatings);
|
|
2921
|
+
const safety =
|
|
2922
|
+
rated === undefined && finish.value === "safety_blocked" && rawFinish !== undefined
|
|
2923
|
+
? [{ category: rawFinish, blocked: true }]
|
|
2924
|
+
: rated;
|
|
2925
|
+
// A turn with pending HITL asks (requestedAuthConfigs /
|
|
2926
|
+
// requestedToolConfirmations / adk_request_input, tracked by
|
|
2927
|
+
// `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
|
|
2928
|
+
// unresolved requests the turn is parked on, never a fabricated success
|
|
2929
|
+
// (SPEC §8 items 12 + 18). A paused close carries finishReason "paused"
|
|
2930
|
+
// (the HITL value), the same as the pause-end close above.
|
|
2931
|
+
const asks = pendingAsks.get(turnId);
|
|
2932
|
+
const paused = asks !== undefined && asks.length > 0;
|
|
2933
|
+
a.closeTurnDone(turnId, {
|
|
2934
|
+
outcome: paused ? { type: "paused", asks } : { type: "success" },
|
|
2935
|
+
finishReason: paused ? "paused" : finish.value,
|
|
2936
|
+
// draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
|
|
2937
|
+
// native value verbatim in turn.done.finishReasonRaw. That is the value
|
|
2938
|
+
// finishReason was mapped from: the wire finishReason, or for an
|
|
2939
|
+
// errorCode-only soft close the errorCode. A paused close's "paused" is
|
|
2940
|
+
// not a fallback, so it takes no companion. message.metadata's
|
|
2941
|
+
// rawFinishReason/rawErrorCode carry stays for one cohort.
|
|
2942
|
+
...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
|
|
2943
|
+
...(usage !== undefined ? { usage } : {}),
|
|
2944
|
+
...(safety !== undefined ? { safety } : {}),
|
|
2945
|
+
});
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
/** Count one usage report toward the turn's usage; returns its slot. */
|
|
2949
|
+
function countUsage(turnId: string, usage: NonNullable<AdkEvent["usageMetadata"]>): number {
|
|
2950
|
+
const reports = usageReportsByTurn.get(turnId) ?? [];
|
|
2951
|
+
reports.push(usage);
|
|
2952
|
+
usageReportsByTurn.set(turnId, reports);
|
|
2953
|
+
const accumulated = accumulateUsage(usageByTurn.get(turnId), usage);
|
|
2954
|
+
if (accumulated !== undefined) usageByTurn.set(turnId, accumulated);
|
|
2955
|
+
return reports.length - 1;
|
|
2956
|
+
}
|
|
2957
|
+
|
|
2958
|
+
/** Replace the report in one slot and re-sum the turn's usage. */
|
|
2959
|
+
function replaceUsage(turnId: string, slot: number, usage: NonNullable<AdkEvent["usageMetadata"]>): void {
|
|
2960
|
+
const reports = usageReportsByTurn.get(turnId);
|
|
2961
|
+
if (reports === undefined || slot >= reports.length) return;
|
|
2962
|
+
reports[slot] = usage;
|
|
2963
|
+
let sum: NonNullable<AdkEvent["usageMetadata"]> | undefined;
|
|
2964
|
+
for (const report of reports) sum = accumulateUsage(sum, report);
|
|
2965
|
+
if (sum !== undefined) usageByTurn.set(turnId, sum);
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
/** Spec §8.0 item 35 when the event arrives, and the event's usage count.
|
|
2969
|
+
* Every non-partial event of an open turn counts its usage report once,
|
|
2970
|
+
* functionCall rounds included (see the usageByTurn doc above). An in-band
|
|
2971
|
+
* invocation error that repeats an earlier one yields no `error` event: the
|
|
2972
|
+
* SSE aggregate that repeats the previous in-band error of its source as the
|
|
2973
|
+
* model call's stream closes (its report replaces the one it repeats, so
|
|
2974
|
+
* the call counts once, from the later report), and the relay's closing
|
|
2975
|
+
* event (it adds no usage). Any other in-band error emits `error` from this
|
|
2976
|
+
* push and, when it is the invocation's first, latches it. */
|
|
2977
|
+
function recordErrorAndUsage(event: AdkEvent, turnId: string, isPartial: boolean): void {
|
|
2978
|
+
const sourceKey = aggregateWindowKey(turnId, event, null);
|
|
2979
|
+
const previous = previousBySource.get(sourceKey);
|
|
2980
|
+
const error = inBandErrorOf(event);
|
|
2981
|
+
const counting = !isPartial && !closedTurns.has(turnId);
|
|
2982
|
+
let usageSlot: number | undefined;
|
|
2983
|
+
if (error === undefined) {
|
|
2984
|
+
if (counting && event.usageMetadata !== undefined) usageSlot = countUsage(turnId, event.usageMetadata);
|
|
2369
2985
|
} else {
|
|
2370
|
-
const
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2986
|
+
const record = inBandErrorRecord(event, error);
|
|
2987
|
+
const earlier = inBandErrorsBySource.get(sourceKey) ?? [];
|
|
2988
|
+
const repeatsPrevious =
|
|
2989
|
+
event.partial === false &&
|
|
2990
|
+
previous !== undefined &&
|
|
2991
|
+
!previous.partialFalse &&
|
|
2992
|
+
previous.error !== undefined &&
|
|
2993
|
+
previous.error.code === error.code &&
|
|
2994
|
+
previous.error.message === error.message;
|
|
2995
|
+
if (repeatsPrevious) {
|
|
2996
|
+
const later = event.usageMetadata ?? previous.usage;
|
|
2997
|
+
if (counting && later !== undefined) {
|
|
2998
|
+
if (previous.usageSlot !== undefined) {
|
|
2999
|
+
replaceUsage(turnId, previous.usageSlot, later);
|
|
3000
|
+
usageSlot = previous.usageSlot;
|
|
3001
|
+
} else {
|
|
3002
|
+
usageSlot = countUsage(turnId, later);
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
} else if (!isRelayRepeat(event, record, earlier)) {
|
|
3006
|
+
a.emit({ type: "error", turnId, code: error.code, message: error.message });
|
|
3007
|
+
if (!firstInBandError.has(turnId)) firstInBandError.set(turnId, error);
|
|
3008
|
+
if (counting && event.usageMetadata !== undefined) usageSlot = countUsage(turnId, event.usageMetadata);
|
|
3009
|
+
}
|
|
3010
|
+
inBandErrorsBySource.set(sourceKey, [...earlier, record]);
|
|
2393
3011
|
}
|
|
3012
|
+
previousBySource.set(sourceKey, { partialFalse: event.partial === false, error, usage: event.usageMetadata, usageSlot });
|
|
3013
|
+
}
|
|
3014
|
+
|
|
3015
|
+
/** Item 26's pause signal: an ask is pending and the stream showed the
|
|
3016
|
+
* pause's end (its pause-end event, or a final response while the ask was
|
|
3017
|
+
* pending). An in-band invocation error is never one. */
|
|
3018
|
+
function pauseSignalled(turnId: string): boolean {
|
|
3019
|
+
return (pendingAsks.get(turnId)?.length ?? 0) > 0 && (pauseEnded.has(turnId) || deferredClose.has(turnId));
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
/** Spec §8.0 item 35 at the invocation's end: the one turn.error of a turn
|
|
3023
|
+
* whose invocation met an invocation error, with the given code and message
|
|
3024
|
+
* and the turn's accumulated usage. */
|
|
3025
|
+
function closeInvocationError(turnId: string, error: { code: string; message: string }, usage: AgUsage | undefined): void {
|
|
3026
|
+
closedTurns.add(turnId);
|
|
3027
|
+
a.closeMessage(`msg_${turnId}`);
|
|
3028
|
+
a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
/** Spec §8.0 item 26 with an invocation error: after the paused close, the
|
|
3032
|
+
* error closes on a new top-level turn of the invocation, which carries one
|
|
3033
|
+
* assistant message with no content; its turn.error carries only usage a
|
|
3034
|
+
* host-terminal event reports. */
|
|
3035
|
+
function closeErrorTurn(pausedTurnId: string, error: { code: string; message: string }, usage: AgUsage | undefined): void {
|
|
3036
|
+
const turnId = `${pausedTurnId}_error`;
|
|
3037
|
+
const messageId = ensureOpen(turnId);
|
|
3038
|
+
closedTurns.add(turnId);
|
|
3039
|
+
a.closeMessage(messageId);
|
|
3040
|
+
a.closeTurnError(turnId, { message: error.message, code: error.code, ...(usage !== undefined ? { usage } : {}) });
|
|
2394
3041
|
}
|
|
2395
3042
|
|
|
2396
3043
|
/** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
|
|
@@ -2414,7 +3061,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2414
3061
|
* close with the accumulated usage when the run ended on a non-final event,
|
|
2415
3062
|
* e.g. a completed Workflow). */
|
|
2416
3063
|
function hostComplete(): void {
|
|
2417
|
-
for (const turnId of openTurns) {
|
|
3064
|
+
for (const turnId of [...openTurns]) {
|
|
2418
3065
|
if (closedTurns.has(turnId)) continue;
|
|
2419
3066
|
if (interruptPending.has(turnId)) {
|
|
2420
3067
|
closeInterrupted(turnId);
|
|
@@ -2422,6 +3069,19 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2422
3069
|
}
|
|
2423
3070
|
const messageId = `msg_${turnId}`;
|
|
2424
3071
|
const asks = pendingAsks.get(turnId);
|
|
3072
|
+
// Spec §8.0 items 26 and 35: an invocation that met an in-band error
|
|
3073
|
+
// never closes as success. A signalled pause closes paused, and the
|
|
3074
|
+
// error follows on its own turn; otherwise the turn closes turn.error.
|
|
3075
|
+
const error = firstInBandError.get(turnId);
|
|
3076
|
+
if (error !== undefined) {
|
|
3077
|
+
if (asks !== undefined && pauseSignalled(turnId)) {
|
|
3078
|
+
closePaused(turnId, messageId, asks);
|
|
3079
|
+
closeErrorTurn(turnId, error, undefined);
|
|
3080
|
+
} else {
|
|
3081
|
+
closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
|
|
3082
|
+
}
|
|
3083
|
+
continue;
|
|
3084
|
+
}
|
|
2425
3085
|
if (asks !== undefined && asks.length > 0) {
|
|
2426
3086
|
closePaused(turnId, messageId, asks);
|
|
2427
3087
|
continue;
|
|
@@ -2429,7 +3089,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2429
3089
|
if ((pendingLongRunning.get(turnId)?.size ?? 0) > 0) continue;
|
|
2430
3090
|
const stashed = deferredClose.get(turnId);
|
|
2431
3091
|
if (stashed !== undefined) {
|
|
2432
|
-
closeOnFinalResponse(stashed, turnId, messageId
|
|
3092
|
+
closeOnFinalResponse(stashed, turnId, messageId);
|
|
2433
3093
|
continue;
|
|
2434
3094
|
}
|
|
2435
3095
|
closedTurns.add(turnId);
|
|
@@ -2454,8 +3114,21 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2454
3114
|
let closed = 0;
|
|
2455
3115
|
for (const turnId of [...openTurns].reverse()) {
|
|
2456
3116
|
if (closedTurns.has(turnId)) continue;
|
|
3117
|
+
// A signalled pause on a turn with no interruption closes paused first,
|
|
3118
|
+
// then the error closes on a new top-level turn (spec §8.0 host
|
|
3119
|
+
// obligation 1 and item 26).
|
|
3120
|
+
const asks = pendingAsks.get(turnId);
|
|
3121
|
+
if (asks !== undefined && pauseSignalled(turnId) && !interruptPending.has(turnId)) {
|
|
3122
|
+
closePaused(turnId, `msg_${turnId}`, asks);
|
|
3123
|
+
closeErrorTurn(turnId, { code: err.code, message: err.message }, err.usage);
|
|
3124
|
+
closed++;
|
|
3125
|
+
continue;
|
|
3126
|
+
}
|
|
2457
3127
|
closedTurns.add(turnId);
|
|
2458
|
-
|
|
3128
|
+
// The turn closes with the host's code and message and its accumulated
|
|
3129
|
+
// usage plus any usage the host reports, which covers only work the
|
|
3130
|
+
// stream did not report (spec §8.0 host obligation 1 and item 35).
|
|
3131
|
+
const usage = sumUsage(mapUsage(usageByTurn.get(turnId)), err.usage);
|
|
2459
3132
|
a.closeMessage(`msg_${turnId}`);
|
|
2460
3133
|
a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
|
|
2461
3134
|
closed++;
|
|
@@ -2472,19 +3145,106 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2472
3145
|
});
|
|
2473
3146
|
}
|
|
2474
3147
|
|
|
3148
|
+
/** The part indexes whose text repeats a changed output rendering (see
|
|
3149
|
+
* drive()): skipped here and in the aggregate. */
|
|
3150
|
+
function skippedParts(event: AdkEvent, parts: readonly AdkPart[]): Set<number> {
|
|
3151
|
+
const renderedOutput = changedOutputRendering(event.output);
|
|
3152
|
+
const skipped = new Set<number>();
|
|
3153
|
+
if (renderedOutput !== undefined)
|
|
3154
|
+
parts.forEach((p, idx) => {
|
|
3155
|
+
if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput) skipped.add(idx);
|
|
3156
|
+
});
|
|
3157
|
+
return skipped;
|
|
3158
|
+
}
|
|
3159
|
+
|
|
3160
|
+
/** An event's reading against the aggregate windows of a turn (the rules
|
|
3161
|
+
* are stated in drive()). */
|
|
3162
|
+
function readWindow(turnId: string, event: AdkEvent, parts: readonly AdkPart[], skipped: ReadonlySet<number>, isPartial: boolean) {
|
|
3163
|
+
const isTextPart = (p: AdkPart, idx: number): boolean =>
|
|
3164
|
+
!skipped.has(idx) &&
|
|
3165
|
+
p.thought !== true &&
|
|
3166
|
+
p.functionCall === undefined &&
|
|
3167
|
+
typeof p.text === "string" &&
|
|
3168
|
+
p.text.length > 0;
|
|
3169
|
+
const carriesText = parts.some(isTextPart);
|
|
3170
|
+
const ownKey = aggregateWindowKey(turnId, event);
|
|
3171
|
+
const relay = relayOf(event);
|
|
3172
|
+
const snapshot = !isPartial && relay !== null && relay.stream === "snapshot" ? relay : null;
|
|
3173
|
+
const restated = snapshot !== null ? snapshotWindows(streamedText, turnId, event, snapshot.task) : null;
|
|
3174
|
+
const candidates = isPartial
|
|
3175
|
+
? []
|
|
3176
|
+
: restated !== null
|
|
3177
|
+
? [...restated.artifacts, ...restated.status]
|
|
3178
|
+
: windowCandidates(streamedText, turnId, event);
|
|
3179
|
+
const [onlyCandidate] = candidates;
|
|
3180
|
+
const readKey = !isPartial && candidates.length === 1 && onlyCandidate !== undefined ? onlyCandidate : ownKey;
|
|
3181
|
+
const alreadyStreamed = isPartial
|
|
3182
|
+
? (streamedText.get(ownKey) ?? "")
|
|
3183
|
+
: restated !== null
|
|
3184
|
+
? snapshotReading(
|
|
3185
|
+
restated.artifacts.map((key) => streamedText.get(key) ?? "").join(""),
|
|
3186
|
+
restated.status.map((key) => streamedText.get(key) ?? "").join(""),
|
|
3187
|
+
parts
|
|
3188
|
+
.filter(isTextPart)
|
|
3189
|
+
.map((p) => p.text ?? "")
|
|
3190
|
+
.join(""),
|
|
3191
|
+
)
|
|
3192
|
+
: candidates.length === 1
|
|
3193
|
+
? (streamedText.get(readKey) ?? "")
|
|
3194
|
+
: "";
|
|
3195
|
+
const matchesWindow = !isPartial && alreadyStreamed.length > 0 && carriesText;
|
|
3196
|
+
const eventText = matchesWindow
|
|
3197
|
+
? parts
|
|
3198
|
+
.filter(isTextPart)
|
|
3199
|
+
.map((p) => p.text ?? "")
|
|
3200
|
+
.join("")
|
|
3201
|
+
: "";
|
|
3202
|
+
const suffixRepeat = matchesWindow && alreadyStreamed.endsWith(eventText);
|
|
3203
|
+
const isAggregate =
|
|
3204
|
+
matchesWindow &&
|
|
3205
|
+
(eventText.startsWith(alreadyStreamed) || alreadyStreamed.startsWith(eventText) || suffixRepeat);
|
|
3206
|
+
const aggregateText = isAggregate ? eventText : "";
|
|
3207
|
+
const suppressAggregateText =
|
|
3208
|
+
isAggregate && aggregateText.length > 0 && (alreadyStreamed.startsWith(aggregateText) || suffixRepeat);
|
|
3209
|
+
return { isTextPart, carriesText, ownKey, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText };
|
|
3210
|
+
}
|
|
3211
|
+
|
|
3212
|
+
/** Whether an event after a success close only repeats the closed turn's
|
|
3213
|
+
* streamed text: ADK's aggregate after a message-less block chunk closed
|
|
3214
|
+
* the turn. It stays on that turn, where the window suppresses it, rather
|
|
3215
|
+
* than opening a new one. */
|
|
3216
|
+
function repeatsClosedTurn(turnId: string, event: AdkEvent): boolean {
|
|
3217
|
+
if (event.partial === true) return false;
|
|
3218
|
+
const { parts } = splitPayloadParts(event.content?.parts ?? []);
|
|
3219
|
+
if (parts.length === 0) return false;
|
|
3220
|
+
const skipped = skippedParts(event, parts);
|
|
3221
|
+
const reading = readWindow(turnId, event, parts, skipped, false);
|
|
3222
|
+
return (
|
|
3223
|
+
reading.suppressAggregateText &&
|
|
3224
|
+
parts.every((p, idx) => skipped.has(idx) || reading.isTextPart(p, idx) || (p.thought !== true && p.text === ""))
|
|
3225
|
+
);
|
|
3226
|
+
}
|
|
3227
|
+
|
|
2475
3228
|
function drive(event: AdkEvent, relayEchoOmitted = 0): void {
|
|
2476
|
-
const turnId = liveTurnFor(event);
|
|
3229
|
+
const turnId = liveTurnFor(event, relayEchoOmitted > 0);
|
|
2477
3230
|
// ADK re-yields a bare `{interrupted}` after a message that carried both
|
|
2478
3231
|
// turnComplete and interrupted (utils/live_connection_utils.js, @google/adk
|
|
2479
3232
|
// 2.1.0). For a generation the barge-in already closed, it adds nothing:
|
|
2480
3233
|
// no new turn and no second terminal, so the facet emits nothing for it.
|
|
3234
|
+
// An event push() removed parts from is not that re-yield even when
|
|
3235
|
+
// nothing is left of it: its marker needs a turn, so it opens the next
|
|
3236
|
+
// generation as an event with content would.
|
|
2481
3237
|
if (turnId === undefined) return;
|
|
2482
3238
|
const messageId = ensureOpen(turnId);
|
|
2483
3239
|
// A relayed repeat of the forwarded request whose parts push() removed:
|
|
2484
3240
|
// one content-free marker, after the opening of the turn the event maps
|
|
2485
3241
|
// into.
|
|
2486
3242
|
if (relayEchoOmitted > 0) a.emitExt("google", "relay-echo-omitted", { parts: relayEchoOmitted });
|
|
2487
|
-
|
|
3243
|
+
// A part holding text beside a payload member, or two payload members, is
|
|
3244
|
+
// split before any reader below classifies it (see splitPayloadParts), so
|
|
3245
|
+
// its text joins the aggregate as text does and each payload member maps
|
|
3246
|
+
// through its own arm.
|
|
3247
|
+
const { parts, origin: nativeIndexOf } = splitPayloadParts(event.content?.parts ?? []);
|
|
2488
3248
|
const isPartial = event.partial === true;
|
|
2489
3249
|
// ADK renders an object `output` as the same event's text part, byte-equal
|
|
2490
3250
|
// to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
|
|
@@ -2492,12 +3252,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2492
3252
|
// repeat what the reduction removed, so that one part is skipped here and
|
|
2493
3253
|
// in the aggregate below. Nothing else matches: not a string output, not
|
|
2494
3254
|
// a substring, not model text.
|
|
2495
|
-
const
|
|
2496
|
-
const skipped = new Set<number>();
|
|
2497
|
-
if (renderedOutput !== undefined)
|
|
2498
|
-
parts.forEach((p, idx) => {
|
|
2499
|
-
if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput) skipped.add(idx);
|
|
2500
|
-
});
|
|
3255
|
+
const skipped = skippedParts(event, parts);
|
|
2501
3256
|
|
|
2502
3257
|
// STREAMED-text citations carrier (audit M22): groundingMetadata is
|
|
2503
3258
|
// EVENT-level, not per-part. A Gemini grounding response carries the full
|
|
@@ -2531,19 +3286,54 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2531
3286
|
nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
|
|
2532
3287
|
});
|
|
2533
3288
|
|
|
2534
|
-
// §8.3 —
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
3289
|
+
// §8.3 — the aggregate suppression (§8.0 item 3). ADK re-yields a model
|
|
3290
|
+
// call's streamed text as one `partial: false` event: when the call closes,
|
|
3291
|
+
// in SSE before a non-text part in the same stream, and on the Live path
|
|
3292
|
+
// before a tool call, on a switch between thought and text, and on a
|
|
3293
|
+
// barge-in. The window holding the
|
|
3294
|
+
// text streamed so far is keyed per turn AND per source (author, branch,
|
|
3295
|
+
// node path, and for an event ADK's A2A relay forwards, the relayed stream:
|
|
3296
|
+
// one artifact, or the status messages; an absent value is its own key), so
|
|
3297
|
+
// interleaved streams never share one. Every non-partial event of the
|
|
3298
|
+
// source closes it, except the ones ADK yields between a call's chunks and
|
|
3299
|
+
// its re-yield, none of which carries text: a block chunk (no content, a
|
|
3300
|
+
// finishReason), a Live usage report or grounding record (no content and
|
|
3301
|
+
// nothing else a closing record carries: no errorCode, errorMessage,
|
|
3302
|
+
// finishReason, turnComplete, session-resumption update, goAway or state or
|
|
3303
|
+
// artifact delta, and for the usage report no interruption), a
|
|
3304
|
+
// transcription event, a `partial: false` event whose
|
|
3305
|
+
// parts are all non-text (a function call or media before the Interactions
|
|
3306
|
+
// route's re-yield), and a function response (progressive SSE runs a tool
|
|
3307
|
+
// mid-stream). A text event that closes the window is its re-yield when
|
|
3308
|
+
// one text starts with the other (equal; longer by text no chunk streamed,
|
|
3309
|
+
// whose tail renders; or shorter, a callback's replacement whose bytes
|
|
3310
|
+
// already streamed) or when the streamed text ends with its text (a later
|
|
3311
|
+
// call's re-yield after a call whose close never arrived, or ADK's
|
|
3312
|
+
// structured-output rewrite); any other text renders in full. An event
|
|
3313
|
+
// without a branch that finds no window under its own key (ADK's A2A relay
|
|
3314
|
+
// rebuilds its re-yield without one, and a failed call's in-band error
|
|
3315
|
+
// carries none) reads the open windows of the same turn, author and node
|
|
3316
|
+
// path: a re-yield matches only when exactly one is open, and a text-less
|
|
3317
|
+
// event that ends the match ends them all (a text with two or more
|
|
3318
|
+
// candidates closes none). A relayed stream is scoped by its A2A task. A
|
|
3319
|
+
// relayed artifact with no window of its own reads its task's status
|
|
3320
|
+
// window; a relayed Task or Message restates its task, so it is read, in
|
|
3321
|
+
// the order ADK renders a Task, against that task's artifact windows and
|
|
3322
|
+
// then its status window (snapshotReading), and closes them; and
|
|
3323
|
+
// the relaying agent's own failure event ends every relayed window of its
|
|
3324
|
+
// author and node path. An empty text part is not text.
|
|
3325
|
+
const {
|
|
3326
|
+
isTextPart,
|
|
3327
|
+
carriesText,
|
|
3328
|
+
ownKey,
|
|
3329
|
+
snapshot,
|
|
3330
|
+
candidates,
|
|
3331
|
+
readKey,
|
|
3332
|
+
alreadyStreamed,
|
|
3333
|
+
isAggregate,
|
|
3334
|
+
aggregateText,
|
|
3335
|
+
suppressAggregateText,
|
|
3336
|
+
} = readWindow(turnId, event, parts, skipped, isPartial);
|
|
2547
3337
|
let residualTail =
|
|
2548
3338
|
isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
|
|
2549
3339
|
let accumulated = alreadyStreamed;
|
|
@@ -2580,6 +3370,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2580
3370
|
a,
|
|
2581
3371
|
part,
|
|
2582
3372
|
index,
|
|
3373
|
+
nativeIndexOf[index] ?? index,
|
|
2583
3374
|
event,
|
|
2584
3375
|
messageId,
|
|
2585
3376
|
turnId,
|
|
@@ -2593,8 +3384,32 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2593
3384
|
if (isPartial) accumulated += contributed;
|
|
2594
3385
|
});
|
|
2595
3386
|
|
|
2596
|
-
|
|
2597
|
-
|
|
3387
|
+
const stateDelta: unknown = event.actions?.stateDelta;
|
|
3388
|
+
const artifactDelta: unknown = event.actions?.artifactDelta;
|
|
3389
|
+
// Two records ADK's Live aggregator yields on their own between a call's
|
|
3390
|
+
// chunks and its repeat: its usage report, and the grounding metadata of
|
|
3391
|
+
// a message with no parts (a barge-in's among them). One that also carries
|
|
3392
|
+
// anything that ends a call is neither, and closes the window.
|
|
3393
|
+
const endsNoCall =
|
|
3394
|
+
event.errorCode === undefined &&
|
|
3395
|
+
event.errorMessage === undefined &&
|
|
3396
|
+
event.turnComplete !== true &&
|
|
3397
|
+
!Object.hasOwn(event, "liveSessionResumptionUpdate") &&
|
|
3398
|
+
!Object.hasOwn(event, "goAway") &&
|
|
3399
|
+
!(isJsonObject(stateDelta) && Object.keys(stateDelta).length > 0) &&
|
|
3400
|
+
!(isJsonObject(artifactDelta) && Object.keys(artifactDelta).length > 0);
|
|
3401
|
+
const usageReportOnly = endsNoCall && event.interrupted !== true && event.usageMetadata?.responseTokenCount !== undefined;
|
|
3402
|
+
const groundingOnly = endsNoCall && event.groundingMetadata !== undefined;
|
|
3403
|
+
const keepsWindowOpen =
|
|
3404
|
+
!carriesText &&
|
|
3405
|
+
((event.partial === undefined && parts.length === 0 && (event.finishReason !== undefined || usageReportOnly || groundingOnly)) ||
|
|
3406
|
+
event.inputTranscription !== undefined ||
|
|
3407
|
+
event.outputTranscription !== undefined ||
|
|
3408
|
+
(event.partial === false && parts.length > 0) ||
|
|
3409
|
+
(parts.length > 0 && parts.every((p) => p.functionResponse !== undefined)));
|
|
3410
|
+
if (isPartial) streamedText.set(ownKey, accumulated);
|
|
3411
|
+
else if (carriesText) for (const key of snapshot !== null ? candidates : [readKey]) streamedText.delete(key);
|
|
3412
|
+
else if (!keepsWindowOpen) for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event)]) streamedText.delete(key);
|
|
2598
3413
|
|
|
2599
3414
|
// Round-3 review finding (regression on finding b): the resend window's
|
|
2600
3415
|
// lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
|
|
@@ -2611,13 +3426,14 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2611
3426
|
// per-invoke.
|
|
2612
3427
|
|
|
2613
3428
|
if (!isPartial) trackLongRunning(event, turnId);
|
|
2614
|
-
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription); // standalone
|
|
3429
|
+
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, closedTurns.has(turnId)); // standalone and content arms
|
|
2615
3430
|
// A turn gets ONE terminal: an interrupt on a turn that already closed
|
|
2616
3431
|
// (a second barge-in, or one after a success close) adds none.
|
|
2617
3432
|
if (event.interrupted === true && !closedTurns.has(turnId)) interruptPending.add(turnId);
|
|
2618
3433
|
carryLiveUsageDetails(event, turnId, messageId, isPartial);
|
|
2619
3434
|
if (parts.some((p) => p.functionResponse !== undefined)) awaitingReply.add(turnId);
|
|
2620
3435
|
else if (hasModelOutput(event)) awaitingReply.delete(turnId);
|
|
3436
|
+
recordErrorAndUsage(event, turnId, isPartial);
|
|
2621
3437
|
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
2622
3438
|
// The interrupted generation closes on its own turnComplete (its trailing
|
|
2623
3439
|
// usageMetadata arrives before it), or at flush() / host completion.
|
|
@@ -2647,15 +3463,33 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2647
3463
|
|
|
2648
3464
|
/** The turn an event belongs to: `turn_<stem>_<key>` (or `turn_<stem>` with no
|
|
2649
3465
|
* key), with `_g<n>` for the n-th generation after a barge-in closed the
|
|
2650
|
-
* previous one. `undefined` for ADK's bare `{interrupted}` re-yield
|
|
2651
|
-
*
|
|
2652
|
-
|
|
3466
|
+
* previous one. `undefined` for ADK's bare `{interrupted}` re-yield: the one
|
|
3467
|
+
* that directly follows a message carrying both turnComplete and
|
|
3468
|
+
* interrupted (utils/live_connection_utils.js yields that message's final
|
|
3469
|
+
* response, then the bare flag). Any other bare `{interrupted}` after a
|
|
3470
|
+
* barge-in closed the generation interrupts the next one. */
|
|
3471
|
+
function liveTurnFor(event: AdkEvent, omittedParts = false): string | undefined {
|
|
2653
3472
|
const key = turnKey(event);
|
|
2654
3473
|
const base = key !== undefined ? `turn_${invokeStem}_${key}` : `turn_${invokeStem}`;
|
|
3474
|
+
const reyield = previousBothFlags.get(base) === true;
|
|
3475
|
+
previousBothFlags.set(base, event.turnComplete === true && event.interrupted === true);
|
|
2655
3476
|
const g = generationOf.get(base) ?? 0;
|
|
2656
3477
|
const current = g === 0 ? base : `${base}_g${g}`;
|
|
2657
|
-
|
|
2658
|
-
|
|
3478
|
+
// Any event after a success close opens the next generation, so no
|
|
3479
|
+
// message or block event names the closed turn (SPEC :959): content, a
|
|
3480
|
+
// usage report, a carry, an interruption. An `{interrupted}` after a
|
|
3481
|
+
// success close interrupts the next generation, which then closes
|
|
3482
|
+
// turn.abort interrupted; ADK's bare re-yield after a message carrying
|
|
3483
|
+
// both flags follows an interrupt close, handled below. Two stay: an event
|
|
3484
|
+
// whose only mapping is the state.delta of its stateDelta (shared state,
|
|
3485
|
+
// not the turn's content), and an aggregate that only repeats the closed
|
|
3486
|
+
// turn's streamed text (the window suppresses it).
|
|
3487
|
+
const afterSuccess =
|
|
3488
|
+
successClosed.has(current) &&
|
|
3489
|
+
!onlyStateChange(event) &&
|
|
3490
|
+
!repeatsClosedTurn(current, event);
|
|
3491
|
+
if (!interruptClosed.has(current) && !afterSuccess) return current;
|
|
3492
|
+
if (!afterSuccess && reyield && event.interrupted === true && !hasLiveContent(event) && !omittedParts) return undefined;
|
|
2659
3493
|
generationOf.set(base, g + 1);
|
|
2660
3494
|
return `${base}_g${g + 1}`;
|
|
2661
3495
|
}
|
|
@@ -2730,7 +3564,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2730
3564
|
// Workflow invoke until the host completion signal exists, still reports
|
|
2731
3565
|
// the tokens it spent. There is never a turn.done here, so the usage
|
|
2732
3566
|
// appears only once.
|
|
2733
|
-
for (const turnId of openTurns) {
|
|
3567
|
+
for (const turnId of [...openTurns]) {
|
|
2734
3568
|
if (closedTurns.has(turnId)) continue;
|
|
2735
3569
|
if (interruptPending.has(turnId)) {
|
|
2736
3570
|
closeInterrupted(turnId);
|
|
@@ -2738,11 +3572,20 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
|
|
|
2738
3572
|
}
|
|
2739
3573
|
// A pause the stream saw end (its pause-end event, or a final response
|
|
2740
3574
|
// while an ask was pending) is a resolved pause, not a truncation: it
|
|
2741
|
-
// closes paused here (SPEC §8.0 item 26)
|
|
2742
|
-
//
|
|
3575
|
+
// closes paused here (SPEC §8.0 item 26), and an in-band error of its
|
|
3576
|
+
// invocation then closes on its own turn. Asks with neither stay a
|
|
3577
|
+
// truncation, as above, unless the invocation met an in-band error:
|
|
3578
|
+
// that turn, like any other of such an invocation, closes turn.error
|
|
3579
|
+
// (spec §8.0 item 35, INV-FLUSH (2)).
|
|
2743
3580
|
const asks = pendingAsks.get(turnId);
|
|
2744
|
-
|
|
3581
|
+
const error = firstInBandError.get(turnId);
|
|
3582
|
+
if (asks !== undefined && pauseSignalled(turnId)) {
|
|
2745
3583
|
closePaused(turnId, `msg_${turnId}`, asks);
|
|
3584
|
+
if (error !== undefined) closeErrorTurn(turnId, error, undefined);
|
|
3585
|
+
continue;
|
|
3586
|
+
}
|
|
3587
|
+
if (error !== undefined) {
|
|
3588
|
+
closeInvocationError(turnId, error, mapUsage(usageByTurn.get(turnId)));
|
|
2746
3589
|
continue;
|
|
2747
3590
|
}
|
|
2748
3591
|
closedTurns.add(turnId);
|