@silverprotocol/google-adk 0.6.6 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/dist/auth-objects.d.ts +56 -0
- package/dist/auth-objects.d.ts.map +1 -0
- package/dist/auth-objects.js +405 -0
- package/dist/auth-objects.js.map +1 -0
- package/dist/index.d.ts +55 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +484 -384
- package/dist/index.js.map +1 -1
- package/dist/json-guards.d.ts +11 -0
- package/dist/json-guards.d.ts.map +1 -0
- package/dist/json-guards.js +15 -0
- package/dist/json-guards.js.map +1 -0
- package/package.json +2 -2
- package/src/auth-objects.ts +407 -0
- package/src/index.ts +556 -396
- package/src/json-guards.ts +20 -0
package/src/index.ts
CHANGED
|
@@ -48,6 +48,14 @@
|
|
|
48
48
|
* surface. The Python ADK uses the snake_case aliases (`turn_complete`,
|
|
49
49
|
* `function_call`); a runtime adapter would map those before this seam. This
|
|
50
50
|
* fixture contract is the camelCase wire projection.
|
|
51
|
+
*
|
|
52
|
+
* NOTE on turn ids across invokes: google-adk derives turn ids from ADK's
|
|
53
|
+
* `invocationId`, which ADK-JS mints fresh on every `runAsync` (including a
|
|
54
|
+
* resume), so they don't repeat across the invokes of a fold. ADK-Python's
|
|
55
|
+
* resumable resume reuses `invocation_id`, and this facet also accepts events
|
|
56
|
+
* serialized from Python: fed that resume, it would repeat `turn_${invocationId}`
|
|
57
|
+
* (and the message id derived from it) across the fold. Supporting that path
|
|
58
|
+
* needs a per-invoke stem; it is queued, not part of this release.
|
|
51
59
|
*/
|
|
52
60
|
import {
|
|
53
61
|
type AgEvent,
|
|
@@ -58,13 +66,29 @@ import {
|
|
|
58
66
|
type AgMeta,
|
|
59
67
|
type AgPausedAsk,
|
|
60
68
|
type AgSafety,
|
|
61
|
-
|
|
69
|
+
AgUsage,
|
|
62
70
|
AgProviderMeta,
|
|
63
71
|
JsonValue,
|
|
64
72
|
type Normalizer,
|
|
65
73
|
StreamAssembler,
|
|
66
74
|
type ToolOutcome,
|
|
75
|
+
toJsonValueSafe,
|
|
76
|
+
withAtomicPush,
|
|
67
77
|
} from "@silverprotocol/core";
|
|
78
|
+
import {
|
|
79
|
+
ADK_REQUEST_CREDENTIAL,
|
|
80
|
+
snakeKey,
|
|
81
|
+
pickAllowed,
|
|
82
|
+
scrubStateMap,
|
|
83
|
+
scrubAdkAuthConfig,
|
|
84
|
+
scrubbedResponse,
|
|
85
|
+
carryNodeValue,
|
|
86
|
+
changedOutputRendering,
|
|
87
|
+
reduceCarried,
|
|
88
|
+
scrubCredentialCallArgs,
|
|
89
|
+
adkAuthConfigView,
|
|
90
|
+
} from "./auth-objects.js";
|
|
91
|
+
import { isJsonObject, stringMember } from "./json-guards.js";
|
|
68
92
|
|
|
69
93
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
70
94
|
// AdkEvent — the HAND-DEFINED fixture contract (a faithful PROJECTION of the
|
|
@@ -447,10 +471,6 @@ export function isLossyFinishReason(reason: string): boolean {
|
|
|
447
471
|
|
|
448
472
|
// ─── stateful factory helpers ─────────────────────────────────────────────────
|
|
449
473
|
|
|
450
|
-
/** True for a non-null, non-array plain JSON object (guard idiom from the OpenAI facet). */
|
|
451
|
-
function isJsonObject(v: unknown): v is { readonly [k: string]: JsonValue } {
|
|
452
|
-
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
453
|
-
}
|
|
454
474
|
|
|
455
475
|
/** Outer-discriminant guard. ADK events carry an object `content` and/or an `invocationId`. */
|
|
456
476
|
function isAdkEvent(v: unknown): v is AdkEvent {
|
|
@@ -589,15 +609,6 @@ function inlineDataBlock(d: { mimeType: string; data: string; displayName?: stri
|
|
|
589
609
|
return { type: "file", source, ...(d.displayName !== undefined ? { filename: d.displayName } : {}) };
|
|
590
610
|
}
|
|
591
611
|
|
|
592
|
-
// ─── genai-optional arm members (adk-13 hardening) ───────────────────────────
|
|
593
|
-
// A Part arm's member when it is a string, else undefined. Read through
|
|
594
|
-
// `unknown` + `isJsonObject` so a JSON-null arm (a snake_case serializer that
|
|
595
|
-
// keeps None) is guarded too, never dereferenced.
|
|
596
|
-
function stringMember(arm: unknown, key: string): string | undefined {
|
|
597
|
-
if (!isJsonObject(arm)) return undefined;
|
|
598
|
-
const v = arm[key];
|
|
599
|
-
return typeof v === "string" ? v : undefined;
|
|
600
|
-
}
|
|
601
612
|
|
|
602
613
|
// A media/code arm missing a member its AgBlock arm REQUIRES rides verbatim in
|
|
603
614
|
// one provider-raw block keyed by its wire Part field name — the same
|
|
@@ -620,7 +631,7 @@ function carryUnmappableArm(
|
|
|
620
631
|
a.contentBlock(messageId, {
|
|
621
632
|
type: "provider-raw",
|
|
622
633
|
vendor: "google",
|
|
623
|
-
raw: JsonValue.parse({ [field]: arm }),
|
|
634
|
+
raw: reduceCarried(JsonValue.parse({ [field]: arm })),
|
|
624
635
|
});
|
|
625
636
|
}
|
|
626
637
|
|
|
@@ -660,6 +671,87 @@ function codeOutcome(outcome: string | undefined): "ok" | "failed" | "deadline_e
|
|
|
660
671
|
// (a dotless nodeInfo.path); that detail is facet-local, not spec.
|
|
661
672
|
// The caller closes `paused` on one of these only while an ask is pending.
|
|
662
673
|
const ADK_REQUEST_INPUT = "adk_request_input";
|
|
674
|
+
const ADK_REQUEST_CONFIRMATION = "adk_request_confirmation";
|
|
675
|
+
|
|
676
|
+
/** Per-normalizer pause-family bookkeeping (item 26): reserved-call ids already
|
|
677
|
+
* asked, and per turn the ORIGINAL tool-call ids those asks cover (so items
|
|
678
|
+
* 12/18 yield no second ask for them). */
|
|
679
|
+
type ReservedAskState = { asked: Set<string>; originalsByTurn: Map<string, Set<string>> };
|
|
680
|
+
|
|
681
|
+
/** A member of `v` by camelCase or snake_case name. */
|
|
682
|
+
function memberOf(v: JsonValue | undefined, name: string): JsonValue | undefined {
|
|
683
|
+
if (!isJsonObject(v)) return undefined;
|
|
684
|
+
if (Object.hasOwn(v, name)) return v[name];
|
|
685
|
+
const snake = snakeKey(name);
|
|
686
|
+
return Object.hasOwn(v, snake) ? v[snake] : undefined;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** The ask a reserved adk_request_* call yields (SPEC §8.0 item 26). */
|
|
690
|
+
function reservedCallAsk(
|
|
691
|
+
name: string,
|
|
692
|
+
callId: string,
|
|
693
|
+
args: { readonly [k: string]: JsonValue },
|
|
694
|
+
): { ask: AgPausedAsk; originalId?: string } {
|
|
695
|
+
if (name === ADK_REQUEST_INPUT) {
|
|
696
|
+
const schema = args["response_schema"];
|
|
697
|
+
const message = stringMember(args, "message");
|
|
698
|
+
const payload = args["payload"];
|
|
699
|
+
return {
|
|
700
|
+
ask: {
|
|
701
|
+
askId: callId,
|
|
702
|
+
kind: isJsonObject(schema) ? "form" : "text",
|
|
703
|
+
toolCallId: callId,
|
|
704
|
+
resumeBinding: "id",
|
|
705
|
+
...(message !== undefined ? { message } : {}),
|
|
706
|
+
...(isJsonObject(schema) ? { schema } : {}),
|
|
707
|
+
...(payload !== undefined ? { metadata: { payload } } : {}),
|
|
708
|
+
},
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
if (name === ADK_REQUEST_CREDENTIAL) {
|
|
712
|
+
const originalId =
|
|
713
|
+
stringMember(args, "functionCallId") ?? stringMember(args, "function_call_id");
|
|
714
|
+
const authConfig = memberOf(args, "authConfig") ?? null;
|
|
715
|
+
const message = stringMember(args, "message");
|
|
716
|
+
const view = adkAuthConfigView(authConfig);
|
|
717
|
+
return {
|
|
718
|
+
ask: {
|
|
719
|
+
askId: `auth_${callId}`,
|
|
720
|
+
kind: "auth",
|
|
721
|
+
toolCallId: callId,
|
|
722
|
+
resumeBinding: "id",
|
|
723
|
+
...(message !== undefined ? { message } : {}),
|
|
724
|
+
...(view !== undefined ? { authConfig: view } : {}),
|
|
725
|
+
metadata: {
|
|
726
|
+
authConfig: scrubAdkAuthConfig(authConfig),
|
|
727
|
+
...(originalId !== undefined ? { originalFunctionCallId: originalId } : {}),
|
|
728
|
+
},
|
|
729
|
+
},
|
|
730
|
+
...(originalId !== undefined ? { originalId } : {}),
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
// adk_request_confirmation: args {originalFunctionCall {id, name, args}, toolConfirmation {hint, confirmed, payload}}.
|
|
734
|
+
const originalId = stringMember(memberOf(args, "originalFunctionCall"), "id");
|
|
735
|
+
const confirmation = memberOf(args, "toolConfirmation");
|
|
736
|
+
const hint = stringMember(confirmation, "hint");
|
|
737
|
+
const confirmed = memberOf(confirmation, "confirmed");
|
|
738
|
+
const payload = memberOf(confirmation, "payload");
|
|
739
|
+
const metadata: { [k: string]: JsonValue } = {};
|
|
740
|
+
if (typeof confirmed === "boolean") metadata["confirmed"] = confirmed;
|
|
741
|
+
if (payload !== undefined) metadata["payload"] = payload;
|
|
742
|
+
if (originalId !== undefined) metadata["originalFunctionCallId"] = originalId;
|
|
743
|
+
return {
|
|
744
|
+
ask: {
|
|
745
|
+
askId: `approval_${callId}`,
|
|
746
|
+
kind: "approval",
|
|
747
|
+
toolCallId: callId,
|
|
748
|
+
resumeBinding: "id",
|
|
749
|
+
...(hint !== undefined ? { message: hint } : {}),
|
|
750
|
+
...(Object.keys(metadata).length > 0 ? { metadata } : {}),
|
|
751
|
+
},
|
|
752
|
+
...(originalId !== undefined ? { originalId } : {}),
|
|
753
|
+
};
|
|
754
|
+
}
|
|
663
755
|
|
|
664
756
|
function isNonEmptyRecord(v: unknown): boolean {
|
|
665
757
|
return isJsonObject(v) && Object.keys(v).length > 0;
|
|
@@ -681,8 +773,12 @@ function isAdkPauseEnd(event: AdkEvent): boolean {
|
|
|
681
773
|
);
|
|
682
774
|
}
|
|
683
775
|
|
|
684
|
-
|
|
685
|
-
|
|
776
|
+
/** The event's own turn key: its invocationId, else its id. `undefined` when it
|
|
777
|
+
* has neither; the normalizer then names the turn from its per-instance stem,
|
|
778
|
+
* never a constant that would repeat across the invokes a host folds together. */
|
|
779
|
+
function turnKey(ev: AdkEvent): string | undefined {
|
|
780
|
+
if (ev.invocationId && ev.invocationId.length > 0) return ev.invocationId;
|
|
781
|
+
return ev.id !== undefined && ev.id !== null && ev.id.length > 0 ? ev.id : undefined;
|
|
686
782
|
}
|
|
687
783
|
|
|
688
784
|
// ─── tool-call positional index (spec §8.2) ───────────────────────────────────
|
|
@@ -691,6 +787,78 @@ function turnKey(ev: AdkEvent): string {
|
|
|
691
787
|
// the positional index on tool.start/tool-call `providerCallIndex` so re-input can
|
|
692
788
|
// restore name+position correlation when echoing functionResponse parts.
|
|
693
789
|
|
|
790
|
+
// ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
|
|
791
|
+
// adk-10, founder-ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
|
|
792
|
+
// answers a failed tool call with a response carrying Gemini's documented
|
|
793
|
+
// `error` key: an unresolvable tool name (functions.js:264), a thrown tool
|
|
794
|
+
// including a thrown MCP call (functions.js:282), several built-in tools.
|
|
795
|
+
// Rules, in order:
|
|
796
|
+
// 1. MCP CallToolResult `isError: true` → "error" + isError.
|
|
797
|
+
// 2. The call id is named in the SAME event's actions.requestedToolConfirmations
|
|
798
|
+
// or actions.requestedAuthConfigs → "ok": ADK's pause placeholder
|
|
799
|
+
// (function_tool.js:139-141, same event per functions.js:422-431); the
|
|
800
|
+
// pause rides hitl.ask (§8.0 items 12 and 18).
|
|
801
|
+
// 3. A declined approval → "denied", no errorText, no isError: an `error`
|
|
802
|
+
// equal to a rejection literal or starting with the policy-engine prefix,
|
|
803
|
+
// or an error_code/errorCode of CONFIRMATION_REJECTED.
|
|
804
|
+
// 4. An `error` present and not null/false/0/"" → "error" + isError, with
|
|
805
|
+
// errorText when it is a string and errorCode from a string
|
|
806
|
+
// error_code/errorCode.
|
|
807
|
+
// 5. Otherwise "ok" (incl. `{status:"error", …}`, out of scope per item 25).
|
|
808
|
+
// `content` always carries the response verbatim (functionResponseToToolDoneFields).
|
|
809
|
+
// Literals pinned at @google/adk 2.1.0: function_tool.js:144,
|
|
810
|
+
// security_plugin.js:75 and :113, run_skill_inline_script_tool.js:160-163.
|
|
811
|
+
const ADK_REJECTION_ERRORS: ReadonlySet<string> = new Set([
|
|
812
|
+
"This tool call is rejected.",
|
|
813
|
+
"Tool call rejected from confirmation flow.",
|
|
814
|
+
]);
|
|
815
|
+
const ADK_POLICY_REJECTION_PREFIX = "This tool call is rejected by policy engine.";
|
|
816
|
+
const ADK_REJECTION_ERROR_CODE = "CONFIRMATION_REJECTED";
|
|
817
|
+
|
|
818
|
+
type ToolResultClassification = {
|
|
819
|
+
outcome: ToolOutcome;
|
|
820
|
+
isError?: true;
|
|
821
|
+
errorText?: string;
|
|
822
|
+
errorCode?: string;
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
function isAdkPausePlaceholder(toolCallId: string, actions: AdkEvent["actions"]): boolean {
|
|
826
|
+
const confirmations = actions?.requestedToolConfirmations;
|
|
827
|
+
const auths = actions?.requestedAuthConfigs;
|
|
828
|
+
return (
|
|
829
|
+
(isJsonObject(confirmations) && Object.hasOwn(confirmations, toolCallId)) ||
|
|
830
|
+
(isJsonObject(auths) && Object.hasOwn(auths, toolCallId))
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function classifyFunctionResponse(
|
|
835
|
+
response: { readonly [k: string]: JsonValue } | undefined,
|
|
836
|
+
toolCallId: string,
|
|
837
|
+
actions: AdkEvent["actions"],
|
|
838
|
+
): ToolResultClassification {
|
|
839
|
+
if (response === undefined) return { outcome: "ok" };
|
|
840
|
+
if (response["isError"] === true) return { outcome: "error", isError: true };
|
|
841
|
+
if (isAdkPausePlaceholder(toolCallId, actions)) return { outcome: "ok" };
|
|
842
|
+
const error = response["error"];
|
|
843
|
+
const code = stringMember(response, "error_code") ?? stringMember(response, "errorCode");
|
|
844
|
+
if (
|
|
845
|
+
code === ADK_REJECTION_ERROR_CODE ||
|
|
846
|
+
(typeof error === "string" &&
|
|
847
|
+
(ADK_REJECTION_ERRORS.has(error) || error.startsWith(ADK_POLICY_REJECTION_PREFIX)))
|
|
848
|
+
) {
|
|
849
|
+
return { outcome: "denied" };
|
|
850
|
+
}
|
|
851
|
+
if (error !== undefined && error !== null && error !== false && error !== 0 && error !== "") {
|
|
852
|
+
return {
|
|
853
|
+
outcome: "error",
|
|
854
|
+
isError: true,
|
|
855
|
+
...(typeof error === "string" ? { errorText: error } : {}),
|
|
856
|
+
...(code !== undefined ? { errorCode: code } : {}),
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
return { outcome: "ok" };
|
|
860
|
+
}
|
|
861
|
+
|
|
694
862
|
// ─── functionResponse.response → tool.done channels (spec §2/§2.1, MCP shape) ──
|
|
695
863
|
// The Gemini functionResponse.response is a JSON OBJECT (the function result).
|
|
696
864
|
// Preserve its shape: an MCP-style { content: AgBlock[] } passes through as the
|
|
@@ -729,7 +897,7 @@ function functionResponseToToolDoneFields(
|
|
|
729
897
|
}
|
|
730
898
|
}
|
|
731
899
|
// Preserve any non-text MCP content part losslessly as a provider-raw block.
|
|
732
|
-
out.push({ type: "provider-raw", vendor: "google", raw: part });
|
|
900
|
+
out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
|
|
733
901
|
}
|
|
734
902
|
const meta = response["_meta"];
|
|
735
903
|
return {
|
|
@@ -931,20 +1099,24 @@ function consumeMintedCallId(
|
|
|
931
1099
|
}
|
|
932
1100
|
|
|
933
1101
|
// ─── stateful factory: driveAdkPart ──────────────────────────────────────────
|
|
934
|
-
// ─── block ids: a per-
|
|
1102
|
+
// ─── block ids: a per-INVOKE ordinal per kind (SPEC.md INV-BLOCK) ────────────
|
|
935
1103
|
// Streaming block ids MUST be unique within a fold, and identity MUST never
|
|
936
1104
|
// derive solely from a per-event positional index. ADK/Gemini parts carry no
|
|
937
1105
|
// block id, so the facet mints `${kind}:${n}`, where n counts that kind's
|
|
938
|
-
// blocks
|
|
939
|
-
//
|
|
940
|
-
//
|
|
941
|
-
//
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1106
|
+
// blocks across the WHOLE normalizer (one invoke, §8.0 obligation 3). The id
|
|
1107
|
+
// carries no turnId, so the counter must not reset per turn. A per-turn count
|
|
1108
|
+
// re-opened text:0 in a second turn of the same invoke (a workflow-node turn
|
|
1109
|
+
// then a plain turn), and the draft.4 reducer parks on that (rd-14 P14:
|
|
1110
|
+
// invoke-scoped INV-BLOCK, reset at the seq-0 restart). The old
|
|
1111
|
+
// `${kind}:${partIndex}` repeated across events: two thought events in one
|
|
1112
|
+
// invoke both opened reasoning:0 (thinking-gemini37/38, R&D item 14
|
|
1113
|
+
// prerequisite). A one-turn invoke's ids are unchanged, and every committed
|
|
1114
|
+
// adk golden is a one-turn invoke.
|
|
1115
|
+
type BlockIdMint = Map<"text" | "reasoning", number>;
|
|
1116
|
+
|
|
1117
|
+
function mintBlockId(m: BlockIdMint, kind: "text" | "reasoning"): string {
|
|
1118
|
+
const n = m.get(kind) ?? 0;
|
|
1119
|
+
m.set(kind, n + 1);
|
|
948
1120
|
return `${kind}:${n}`;
|
|
949
1121
|
}
|
|
950
1122
|
|
|
@@ -1003,13 +1175,13 @@ function driveAdkPart(
|
|
|
1003
1175
|
a.contentBlock(messageId, {
|
|
1004
1176
|
type: "provider-raw",
|
|
1005
1177
|
vendor: "google",
|
|
1006
|
-
raw: JsonValue.parse(unmappedPartFields),
|
|
1178
|
+
raw: reduceCarried(JsonValue.parse(unmappedPartFields)),
|
|
1007
1179
|
});
|
|
1008
1180
|
}
|
|
1009
1181
|
|
|
1010
1182
|
// ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
|
|
1011
1183
|
if (part.thought === true) {
|
|
1012
|
-
const id = mintBlockId(blockIds,
|
|
1184
|
+
const id = mintBlockId(blockIds, "reasoning");
|
|
1013
1185
|
a.reasoningStart(id, messageId);
|
|
1014
1186
|
// typeof, not `!== undefined`: a JSON-null text is absent (null guard).
|
|
1015
1187
|
if (typeof part.text === "string" && part.text.length > 0) a.reasoningDelta(id, messageId, part.text);
|
|
@@ -1029,7 +1201,7 @@ function driveAdkPart(
|
|
|
1029
1201
|
// falls through to the arms below (a functionCall beside it still maps), and
|
|
1030
1202
|
// `null` never reaches textDelta or the streamed-text accumulator.
|
|
1031
1203
|
if (typeof part.text === "string") {
|
|
1032
|
-
const id = mintBlockId(blockIds,
|
|
1204
|
+
const id = mintBlockId(blockIds, "text");
|
|
1033
1205
|
const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
|
|
1034
1206
|
// STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
|
|
1035
1207
|
// event's groundingSupports segments (each already carries its own offsets +
|
|
@@ -1133,17 +1305,17 @@ function driveAdkPart(
|
|
|
1133
1305
|
a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
|
|
1134
1306
|
return "";
|
|
1135
1307
|
}
|
|
1136
|
-
|
|
1308
|
+
// A JSON-null response is absent (null guard): it was dereferenced below.
|
|
1309
|
+
const response = isJsonObject(fr.response) ? fr.response : undefined;
|
|
1310
|
+
// A reserved-credential answer carries the client's credential: its content
|
|
1311
|
+
// AND its classification use the allowlisted form (see scrubAdkAuthConfig),
|
|
1312
|
+
// so nothing omitted can resurface through errorText.
|
|
1313
|
+
const carried = fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : response;
|
|
1137
1314
|
a.toolDone({
|
|
1138
1315
|
toolCallId,
|
|
1139
|
-
|
|
1140
|
-
//
|
|
1141
|
-
|
|
1142
|
-
...functionResponseToToolDoneFields(
|
|
1143
|
-
fr.name,
|
|
1144
|
-
fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : isJsonObject(fr.response) ? fr.response : undefined,
|
|
1145
|
-
),
|
|
1146
|
-
outcome,
|
|
1316
|
+
...functionResponseToToolDoneFields(fr.name, carried),
|
|
1317
|
+
// adk-10 / SPEC §8.0 item 25: see classifyFunctionResponse.
|
|
1318
|
+
...classifyFunctionResponse(carried, toolCallId, event.actions),
|
|
1147
1319
|
turnId,
|
|
1148
1320
|
providerMetadata:
|
|
1149
1321
|
fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
|
|
@@ -1227,7 +1399,7 @@ function driveAdkPart(
|
|
|
1227
1399
|
a.contentBlock(messageId, {
|
|
1228
1400
|
type: "provider-raw",
|
|
1229
1401
|
vendor: "google",
|
|
1230
|
-
raw: { fileData: { displayName } },
|
|
1402
|
+
raw: reduceCarried({ fileData: { displayName } }),
|
|
1231
1403
|
});
|
|
1232
1404
|
}
|
|
1233
1405
|
} else {
|
|
@@ -1239,309 +1411,6 @@ function driveAdkPart(
|
|
|
1239
1411
|
return "";
|
|
1240
1412
|
}
|
|
1241
1413
|
|
|
1242
|
-
// ─── ADK AuthConfig → flat AgAuthConfig view (SPEC §8.0 item 12) ─────────────
|
|
1243
|
-
// ADK's AuthConfig (@google/adk 2.1.0 dist/types/auth/auth_tool.d.ts:12-42) is
|
|
1244
|
-
// `{ authScheme, rawAuthCredential?, exchangedAuthCredential?, credentialKey }`,
|
|
1245
|
-
// with authScheme an OpenAPI v3 SecuritySchemeObject or OIDC-with-config
|
|
1246
|
-
// (auth_schemes.d.ts:12, :25). The view maps ONLY what has a native value:
|
|
1247
|
-
// - scheme ← authScheme.type, verbatim; no string type → no view at all (the
|
|
1248
|
-
// field is required and never invented);
|
|
1249
|
-
// - authorizationUrl / tokenUrl / scopes follow ADK's own derivation
|
|
1250
|
-
// (dist/esm/auth/auth_handler.js:112-128): OIDC-with-config's
|
|
1251
|
-
// authorizationEndpoint / tokenEndpoint / scopes; for oauth2, the first
|
|
1252
|
-
// present flow of implicit > authorizationCode > clientCredentials >
|
|
1253
|
-
// password, with scopes = the keys of its OpenAPI scopes map;
|
|
1254
|
-
// - clientId / audience ← rawAuthCredential.oauth2 (auth_credential.d.ts:35-62).
|
|
1255
|
-
// credentialKey, secrets and exchange state never enter the view.
|
|
1256
|
-
// ─── ADK auth objects: carry only members known to be non-secret ─────────────
|
|
1257
|
-
// An ADK AuthConfig, and the credential objects inside it, can hold credential
|
|
1258
|
-
// material. Anything the facet forwards is persisted by hosts (hitl.ask →
|
|
1259
|
-
// turn.done paused asks[]; tool-call blocks). So every carrier of an ADK auth
|
|
1260
|
-
// object is an ALLOWLIST: a member is forwarded only when it is known to be
|
|
1261
|
-
// non-secret, and every other member, at any depth, is omitted. The list is
|
|
1262
|
-
// checked against @google/adk 2.1.0 dist/types/auth/auth_tool.d.ts and
|
|
1263
|
-
// auth_credential.d.ts. Keys match in camelCase or snake_case (the reserved
|
|
1264
|
-
// call's args arrive snake_case at the top level); a kept key keeps its wire
|
|
1265
|
-
// spelling.
|
|
1266
|
-
//
|
|
1267
|
-
// Resume safety (ADK 2.1.0): the credential resume rebuilds the request
|
|
1268
|
-
// server-side from the session's own reserved call (auth_preprocessor.js
|
|
1269
|
-
// requestedAuthConfigs) and takes only the auth code / response URI from the
|
|
1270
|
-
// client's answer (credential_response_binding.js bindCredential; the raw
|
|
1271
|
-
// credential is restored from the request). An oauth2/OIDC request always
|
|
1272
|
-
// carries a generated authUri (auth_handler.js generateAuthRequest). So what
|
|
1273
|
-
// the allowlist omits is never needed to answer the ask.
|
|
1274
|
-
const ADK_REQUEST_CREDENTIAL = "adk_request_credential";
|
|
1275
|
-
|
|
1276
|
-
type AllowSpec = { [key: string]: true | ((v: JsonValue) => JsonValue | undefined) };
|
|
1277
|
-
|
|
1278
|
-
function snakeKey(k: string): string {
|
|
1279
|
-
return k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
|
-
/** Copy only the allowlisted members of `v` (camel or snake spelling), each
|
|
1283
|
-
* either verbatim (`true`) or through its nested allowlist. */
|
|
1284
|
-
function pickAllowed(v: JsonValue | undefined, spec: AllowSpec): JsonValue | undefined {
|
|
1285
|
-
if (!isJsonObject(v)) return undefined;
|
|
1286
|
-
const out: { [k: string]: JsonValue } = {};
|
|
1287
|
-
for (const [name, rule] of Object.entries(spec)) {
|
|
1288
|
-
for (const key of name === snakeKey(name) ? [name] : [name, snakeKey(name)]) {
|
|
1289
|
-
if (!Object.hasOwn(v, key)) continue;
|
|
1290
|
-
const member = v[key];
|
|
1291
|
-
if (member === undefined) continue;
|
|
1292
|
-
const kept = rule === true ? member : rule(member);
|
|
1293
|
-
if (kept !== undefined) out[key] = kept;
|
|
1294
|
-
}
|
|
1295
|
-
}
|
|
1296
|
-
return out;
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
const OAUTH2_ALLOW: AllowSpec = {
|
|
1300
|
-
clientId: true,
|
|
1301
|
-
authUri: true,
|
|
1302
|
-
redirectUri: true,
|
|
1303
|
-
scopes: true,
|
|
1304
|
-
codeChallengeMethod: true,
|
|
1305
|
-
tokenEndpointAuthMethod: true,
|
|
1306
|
-
expiresAt: true,
|
|
1307
|
-
expiresIn: true,
|
|
1308
|
-
audience: true,
|
|
1309
|
-
};
|
|
1310
|
-
const SERVICE_ACCOUNT_ALLOW: AllowSpec = {
|
|
1311
|
-
scopes: true,
|
|
1312
|
-
useDefaultCredential: true,
|
|
1313
|
-
useIdToken: true,
|
|
1314
|
-
audience: true,
|
|
1315
|
-
serviceAccountCredential: (v) =>
|
|
1316
|
-
pickAllowed(v, { projectId: true, clientEmail: true, tokenUri: true, universeDomain: true }),
|
|
1317
|
-
};
|
|
1318
|
-
const AUTH_CREDENTIAL_ALLOW: AllowSpec = {
|
|
1319
|
-
authType: true,
|
|
1320
|
-
resourceRef: true,
|
|
1321
|
-
oauth2: (v) => pickAllowed(v, OAUTH2_ALLOW),
|
|
1322
|
-
serviceAccount: (v) => pickAllowed(v, SERVICE_ACCOUNT_ALLOW),
|
|
1323
|
-
};
|
|
1324
|
-
// The security scheme, member by member: an OpenAPI 3.0 SecuritySchemeObject
|
|
1325
|
-
// (openapi-types 12.1.3 OpenAPIV3: http, apiKey, oauth2 and openIdConnect,
|
|
1326
|
-
// the type @google/adk 2.1.0's auth_schemes.d.ts names) or ADK's
|
|
1327
|
-
// OpenIdConnectWithConfig. Every leaf is a string, a string list or a map of
|
|
1328
|
-
// strings, and only those survive. A scheme member no type declares (a vendor
|
|
1329
|
-
// extension, a stray field) never rides.
|
|
1330
|
-
const schemeString = (v: JsonValue): JsonValue | undefined => (typeof v === "string" ? v : undefined);
|
|
1331
|
-
const schemeStringList = (v: JsonValue): JsonValue | undefined =>
|
|
1332
|
-
Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
|
|
1333
|
-
/** A map this facet rebuilds from native entries never carries an own
|
|
1334
|
-
* `__proto__` key (SPEC §13.7): JsonValue.parse drops one, and
|
|
1335
|
-
* Object.fromEntries would re-create it as an own property. */
|
|
1336
|
-
function isReservedMapKey(k: string): boolean {
|
|
1337
|
-
return k === "__proto__";
|
|
1338
|
-
}
|
|
1339
|
-
/** OAuth2 flow scopes are a map of scope name -> description; OIDC config
|
|
1340
|
-
* scopes are a list. Either keeps only its string entries. */
|
|
1341
|
-
const schemeScopes = (v: JsonValue): JsonValue | undefined =>
|
|
1342
|
-
Array.isArray(v)
|
|
1343
|
-
? schemeStringList(v)
|
|
1344
|
-
: isJsonObject(v)
|
|
1345
|
-
? Object.fromEntries(
|
|
1346
|
-
Object.entries(v).filter((e): e is [string, string] => !isReservedMapKey(e[0]) && typeof e[1] === "string"),
|
|
1347
|
-
)
|
|
1348
|
-
: undefined;
|
|
1349
|
-
const OAUTH2_FLOW_ALLOW: AllowSpec = {
|
|
1350
|
-
authorizationUrl: schemeString,
|
|
1351
|
-
tokenUrl: schemeString,
|
|
1352
|
-
refreshUrl: schemeString,
|
|
1353
|
-
scopes: schemeScopes,
|
|
1354
|
-
};
|
|
1355
|
-
const AUTH_SCHEME_ALLOW: AllowSpec = {
|
|
1356
|
-
type: schemeString,
|
|
1357
|
-
description: schemeString,
|
|
1358
|
-
// http
|
|
1359
|
-
scheme: schemeString,
|
|
1360
|
-
bearerFormat: schemeString,
|
|
1361
|
-
// apiKey (the header/query parameter's name and location, never its value)
|
|
1362
|
-
name: schemeString,
|
|
1363
|
-
in: schemeString,
|
|
1364
|
-
// oauth2 (flows.password is the password-GRANT flow: a tokenUrl and scopes)
|
|
1365
|
-
flows: (v) =>
|
|
1366
|
-
pickAllowed(v, {
|
|
1367
|
-
implicit: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1368
|
-
password: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1369
|
-
clientCredentials: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1370
|
-
authorizationCode: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1371
|
-
}),
|
|
1372
|
-
// openIdConnect
|
|
1373
|
-
openIdConnectUrl: schemeString,
|
|
1374
|
-
// OpenIdConnectWithConfig
|
|
1375
|
-
authorizationEndpoint: schemeString,
|
|
1376
|
-
tokenEndpoint: schemeString,
|
|
1377
|
-
userinfoEndpoint: schemeString,
|
|
1378
|
-
revocationEndpoint: schemeString,
|
|
1379
|
-
tokenEndpointAuthMethodsSupported: schemeStringList,
|
|
1380
|
-
grantTypesSupported: schemeStringList,
|
|
1381
|
-
scopes: schemeScopes,
|
|
1382
|
-
};
|
|
1383
|
-
const AUTH_CONFIG_ALLOW: AllowSpec = {
|
|
1384
|
-
authScheme: (v) => pickAllowed(v, AUTH_SCHEME_ALLOW),
|
|
1385
|
-
credentialKey: true,
|
|
1386
|
-
rawAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
|
|
1387
|
-
exchangedAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
|
|
1388
|
-
};
|
|
1389
|
-
|
|
1390
|
-
// ─── shared state (state.delta) ──────────────────────────────────────────────
|
|
1391
|
-
// ADK itself writes an exchanged AuthCredential into the event's
|
|
1392
|
-
// actions.stateDelta on two paths (@google/adk 2.1.0):
|
|
1393
|
-
// - a Runner configured with SessionStateCredentialService saves it under the
|
|
1394
|
-
// bare credentialKey (session_state_credential_service.js; ToolContext's
|
|
1395
|
-
// State writes value AND delta, agents/context.js:37-39, sessions/state.js:97-102);
|
|
1396
|
-
// - the Workflow plane's FunctionNode auth resume stores it under
|
|
1397
|
-
// "temp:" + credentialKey (auth_handler.js:35-38, :47), and function_node.js
|
|
1398
|
-
// copies every new delta entry into the event it yields (:93-127). A Runner
|
|
1399
|
-
// removes "temp:" entries from a non-partial event as it appends it to the
|
|
1400
|
-
// session, before yielding it; a partial event, or an event read before
|
|
1401
|
-
// that append, still carries them.
|
|
1402
|
-
// ADK treats any value under the key as a stored credential
|
|
1403
|
-
// (hitl_utils.js:131-133), so the entry is omitted whole: a redacted value left
|
|
1404
|
-
// behind would read as a credential. Every "temp:" entry is omitted too
|
|
1405
|
-
// (invocation-scoped by ADK's contract). Every other entry rides unchanged.
|
|
1406
|
-
const ADK_TEMP_STATE_PREFIX = "temp:";
|
|
1407
|
-
const AUTH_CREDENTIAL_TYPES: ReadonlySet<string> = new Set(["apiKey", "http", "oauth2", "openIdConnect", "serviceAccount"]);
|
|
1408
|
-
// resourceRef (auth_credential.d.ts:244) names a stored credential: ADK's
|
|
1409
|
-
// presence readers treat an object holding it as a held credential.
|
|
1410
|
-
const AUTH_CREDENTIAL_MEMBERS = [
|
|
1411
|
-
"apiKey",
|
|
1412
|
-
"api_key",
|
|
1413
|
-
"http",
|
|
1414
|
-
"oauth2",
|
|
1415
|
-
"serviceAccount",
|
|
1416
|
-
"service_account",
|
|
1417
|
-
"resourceRef",
|
|
1418
|
-
"resource_ref",
|
|
1419
|
-
] as const;
|
|
1420
|
-
|
|
1421
|
-
function isObjectRecord(v: unknown): v is { readonly [k: string]: unknown } {
|
|
1422
|
-
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
/** An ADK AuthCredential: `authType` (either spelling) is one of ADK's
|
|
1426
|
-
* credential types (auth_credential.d.ts) and a credential member is present
|
|
1427
|
-
* and non-null. */
|
|
1428
|
-
function isAuthCredentialObject(v: { readonly [k: string]: unknown }): boolean {
|
|
1429
|
-
const typed = ["authType", "auth_type"].some((k) => {
|
|
1430
|
-
const t = Object.hasOwn(v, k) ? v[k] : undefined;
|
|
1431
|
-
return typeof t === "string" && AUTH_CREDENTIAL_TYPES.has(t);
|
|
1432
|
-
});
|
|
1433
|
-
return typed && AUTH_CREDENTIAL_MEMBERS.some((m) => Object.hasOwn(v, m) && v[m] !== null && v[m] !== undefined);
|
|
1434
|
-
}
|
|
1435
|
-
|
|
1436
|
-
/** Whether `v` is, or holds at any depth (arrays included), an ADK
|
|
1437
|
-
* AuthCredential. Iterative and cycle-safe over the raw native value; a value
|
|
1438
|
-
* that cannot be walked counts as holding one, so this never throws. */
|
|
1439
|
-
function holdsAuthCredential(v: unknown): boolean {
|
|
1440
|
-
try {
|
|
1441
|
-
const seen = new Set<object>();
|
|
1442
|
-
const stack: unknown[] = [v];
|
|
1443
|
-
while (stack.length > 0) {
|
|
1444
|
-
const x = stack.pop();
|
|
1445
|
-
if (x === null || typeof x !== "object" || seen.has(x)) continue;
|
|
1446
|
-
seen.add(x);
|
|
1447
|
-
if (Array.isArray(x)) {
|
|
1448
|
-
for (const y of x) stack.push(y);
|
|
1449
|
-
} else if (isObjectRecord(x)) {
|
|
1450
|
-
if (isAuthCredentialObject(x)) return true;
|
|
1451
|
-
for (const k of Object.keys(x)) stack.push(x[k]);
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
return false;
|
|
1455
|
-
} catch {
|
|
1456
|
-
return true;
|
|
1457
|
-
}
|
|
1458
|
-
}
|
|
1459
|
-
|
|
1460
|
-
/** The state map ADK yields, minus its "temp:" entries and every entry that
|
|
1461
|
-
* holds an ADK AuthCredential, in the original key order. A map with none of
|
|
1462
|
-
* those is carried exactly as before. When entries were omitted, a remaining
|
|
1463
|
-
* entry that is not JSON is dropped rather than thrown on, since a throw would
|
|
1464
|
-
* hand the raw native event to the host's error path. A value that is not a
|
|
1465
|
-
* map is carried as before, or as {} if it holds a credential. */
|
|
1466
|
-
function scrubStateMap(raw: unknown): JsonValue {
|
|
1467
|
-
if (!isObjectRecord(raw)) return holdsAuthCredential(raw) ? {} : JsonValue.parse(raw);
|
|
1468
|
-
const keys = Object.keys(raw);
|
|
1469
|
-
const omitted = keys.map((k) => k.startsWith(ADK_TEMP_STATE_PREFIX) || holdsAuthCredential(raw[k]));
|
|
1470
|
-
if (!omitted.includes(true)) return JsonValue.parse(raw);
|
|
1471
|
-
const kept: [string, JsonValue][] = [];
|
|
1472
|
-
keys.forEach((k, i) => {
|
|
1473
|
-
if (omitted[i] === true || isReservedMapKey(k)) return;
|
|
1474
|
-
const parsed = JsonValue.safeParse(raw[k]);
|
|
1475
|
-
if (parsed.success) kept.push([k, parsed.data]);
|
|
1476
|
-
});
|
|
1477
|
-
return Object.fromEntries(kept);
|
|
1478
|
-
}
|
|
1479
|
-
|
|
1480
|
-
/** The ADK AuthConfig reduced to its non-secret members ({} for a non-object). */
|
|
1481
|
-
function scrubAdkAuthConfig(native: JsonValue): JsonValue {
|
|
1482
|
-
return pickAllowed(native, AUTH_CONFIG_ALLOW) ?? {};
|
|
1483
|
-
}
|
|
1484
|
-
|
|
1485
|
-
/** A reserved-credential functionResponse (the client's answer) scrubbed the
|
|
1486
|
-
* same way; undefined when the response is not an object. */
|
|
1487
|
-
function scrubbedResponse(response: unknown): { readonly [k: string]: JsonValue } | undefined {
|
|
1488
|
-
if (!isJsonObject(response)) return undefined;
|
|
1489
|
-
const scrubbed = scrubAdkAuthConfig(response);
|
|
1490
|
-
return isJsonObject(scrubbed) ? scrubbed : undefined;
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
/** The reserved credential call's args: its id, its message and the scrubbed
|
|
1494
|
-
* AuthConfig. Nothing else is forwarded. */
|
|
1495
|
-
function scrubCredentialCallArgs(args: JsonValue): JsonValue {
|
|
1496
|
-
return (
|
|
1497
|
-
pickAllowed(args, {
|
|
1498
|
-
functionCallId: true,
|
|
1499
|
-
message: true,
|
|
1500
|
-
authConfig: (v) => scrubAdkAuthConfig(v),
|
|
1501
|
-
}) ?? {}
|
|
1502
|
-
);
|
|
1503
|
-
}
|
|
1504
|
-
|
|
1505
|
-
function adkAuthConfigView(native: JsonValue): AgAuthConfig | undefined {
|
|
1506
|
-
if (!isJsonObject(native)) return undefined;
|
|
1507
|
-
const authScheme = native["authScheme"];
|
|
1508
|
-
const scheme = stringMember(authScheme, "type");
|
|
1509
|
-
if (scheme === undefined || !isJsonObject(authScheme)) return undefined;
|
|
1510
|
-
let authorizationUrl: string | undefined;
|
|
1511
|
-
let tokenUrl: string | undefined;
|
|
1512
|
-
let scopes: string[] | undefined;
|
|
1513
|
-
if ("authorizationEndpoint" in authScheme) {
|
|
1514
|
-
authorizationUrl = stringMember(authScheme, "authorizationEndpoint");
|
|
1515
|
-
tokenUrl = stringMember(authScheme, "tokenEndpoint");
|
|
1516
|
-
const s = authScheme["scopes"];
|
|
1517
|
-
if (Array.isArray(s)) scopes = s.filter((x): x is string => typeof x === "string");
|
|
1518
|
-
} else if (scheme === "oauth2") {
|
|
1519
|
-
const flows = authScheme["flows"];
|
|
1520
|
-
const flow = isJsonObject(flows)
|
|
1521
|
-
? [flows["implicit"], flows["authorizationCode"], flows["clientCredentials"], flows["password"]].find(
|
|
1522
|
-
isJsonObject,
|
|
1523
|
-
)
|
|
1524
|
-
: undefined;
|
|
1525
|
-
if (flow !== undefined) {
|
|
1526
|
-
authorizationUrl = stringMember(flow, "authorizationUrl");
|
|
1527
|
-
tokenUrl = stringMember(flow, "tokenUrl");
|
|
1528
|
-
const s = flow["scopes"];
|
|
1529
|
-
if (isJsonObject(s)) scopes = Object.keys(s);
|
|
1530
|
-
}
|
|
1531
|
-
}
|
|
1532
|
-
const raw = native["rawAuthCredential"];
|
|
1533
|
-
const oauth2 = isJsonObject(raw) ? raw["oauth2"] : undefined;
|
|
1534
|
-
const clientId = stringMember(oauth2, "clientId");
|
|
1535
|
-
const audience = stringMember(oauth2, "audience");
|
|
1536
|
-
return {
|
|
1537
|
-
scheme,
|
|
1538
|
-
...(scopes !== undefined ? { scopes } : {}),
|
|
1539
|
-
...(authorizationUrl !== undefined ? { authorizationUrl } : {}),
|
|
1540
|
-
...(tokenUrl !== undefined ? { tokenUrl } : {}),
|
|
1541
|
-
...(clientId !== undefined ? { clientId } : {}),
|
|
1542
|
-
...(audience !== undefined ? { audience } : {}),
|
|
1543
|
-
};
|
|
1544
|
-
}
|
|
1545
1414
|
|
|
1546
1415
|
/** Append `ask` to the turn's pending-asks list (creating it on first use).
|
|
1547
1416
|
* Preserves emission order — asks accumulate in the order their originating
|
|
@@ -1564,7 +1433,7 @@ function driveAdkTopLevel(
|
|
|
1564
1433
|
turnId: string,
|
|
1565
1434
|
closedTurns: Set<string>,
|
|
1566
1435
|
pendingAsks: Map<string, AgPausedAsk[]>,
|
|
1567
|
-
|
|
1436
|
+
reserved: ReservedAskState
|
|
1568
1437
|
): void {
|
|
1569
1438
|
// typeof: a JSON-null transcription text is absent (null guard; it rode the
|
|
1570
1439
|
// text block as `null`, which the schema rejects).
|
|
@@ -1637,39 +1506,39 @@ function driveAdkTopLevel(
|
|
|
1637
1506
|
}
|
|
1638
1507
|
}
|
|
1639
1508
|
|
|
1640
|
-
// ── ADK
|
|
1641
|
-
//
|
|
1642
|
-
//
|
|
1643
|
-
// the
|
|
1644
|
-
//
|
|
1645
|
-
//
|
|
1646
|
-
//
|
|
1647
|
-
//
|
|
1648
|
-
//
|
|
1649
|
-
//
|
|
1509
|
+
// ── ADK pause family → hitl.ask (SPEC §8.0 item 26, draft.4; R&D item 6) ──
|
|
1510
|
+
// An ADK pause is a functionCall named adk_request_input,
|
|
1511
|
+
// adk_request_credential or adk_request_confirmation. Each yields ONE ask:
|
|
1512
|
+
// toolCallId = the reserved call's id (the id ADK accepts as the answer),
|
|
1513
|
+
// resumeBinding "id", and the ORIGINAL tool-call id (when the call names
|
|
1514
|
+
// one) in metadata.originalFunctionCallId. When items 12/18 surface the
|
|
1515
|
+
// same request (actions keyed by the original id), the reserved call's ask is
|
|
1516
|
+
// the one: the original id is recorded, and those loops skip it. On the real
|
|
1517
|
+
// engine the reserved call arrives before, or on the same event as, those
|
|
1518
|
+
// actions. Deduped by id across the partial/aggregate re-send. The reserved
|
|
1519
|
+
// call's own tool.start still opens (suppressing it is an unwalked decision).
|
|
1650
1520
|
if (event.partial !== true) {
|
|
1651
1521
|
for (const part of event.content?.parts ?? []) {
|
|
1652
1522
|
const fc = part.functionCall;
|
|
1653
|
-
if (!isJsonObject(fc)
|
|
1523
|
+
if (!isJsonObject(fc)) continue;
|
|
1524
|
+
const name = fc["name"];
|
|
1525
|
+
if (name !== ADK_REQUEST_INPUT && name !== ADK_REQUEST_CREDENTIAL && name !== ADK_REQUEST_CONFIRMATION)
|
|
1526
|
+
continue;
|
|
1654
1527
|
const callId = stringMember(fc, "id");
|
|
1655
|
-
if (callId === undefined || callId.length === 0 ||
|
|
1656
|
-
|
|
1528
|
+
if (callId === undefined || callId.length === 0 || reserved.asked.has(callId)) continue;
|
|
1529
|
+
reserved.asked.add(callId);
|
|
1657
1530
|
const args = isJsonObject(fc["args"]) ? fc["args"] : {};
|
|
1658
|
-
const
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
toolCallId: callId,
|
|
1665
|
-
...(message !== undefined ? { message } : {}),
|
|
1666
|
-
...(isJsonObject(schema) ? { schema } : {}),
|
|
1667
|
-
...(payload !== undefined ? { metadata: { payload } } : {}),
|
|
1668
|
-
};
|
|
1531
|
+
const { ask, originalId } = reservedCallAsk(name, callId, args);
|
|
1532
|
+
if (originalId !== undefined) {
|
|
1533
|
+
const originals = reserved.originalsByTurn.get(turnId) ?? new Set<string>();
|
|
1534
|
+
originals.add(originalId);
|
|
1535
|
+
reserved.originalsByTurn.set(turnId, originals);
|
|
1536
|
+
}
|
|
1669
1537
|
a.emit({ type: "hitl.ask", ...ask });
|
|
1670
1538
|
trackPendingAsk(pendingAsks, turnId, ask);
|
|
1671
1539
|
}
|
|
1672
1540
|
}
|
|
1541
|
+
const askedOriginals = reserved.originalsByTurn.get(turnId);
|
|
1673
1542
|
|
|
1674
1543
|
// ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
|
|
1675
1544
|
const actions = event.actions;
|
|
@@ -1681,15 +1550,17 @@ function driveAdkTopLevel(
|
|
|
1681
1550
|
if (actions.requestedAuthConfigs !== undefined) {
|
|
1682
1551
|
// ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
|
|
1683
1552
|
// `authConfig` is the flat AgAuthConfig VIEW derived by
|
|
1684
|
-
// `adkAuthConfigView` (absent when no string scheme exists)
|
|
1685
|
-
//
|
|
1686
|
-
//
|
|
1687
|
-
//
|
|
1688
|
-
// ask fields are tracked in `pendingAsks`: if this
|
|
1689
|
-
// event turns out to be THIS event (or a later one for
|
|
1690
|
-
// `maybeCloseTurn` folds them into
|
|
1691
|
-
// instead of fabricating success
|
|
1553
|
+
// `adkAuthConfigView` (absent when no string scheme exists), and
|
|
1554
|
+
// `metadata.authConfig` carries the native AuthConfig through the
|
|
1555
|
+
// allowlist (scrubAdkAuthConfig). A request the reserved
|
|
1556
|
+
// adk_request_credential call already asked for (item 26) yields no
|
|
1557
|
+
// second ask. The SAME ask fields are tracked in `pendingAsks`: if this
|
|
1558
|
+
// turn's close-path event turns out to be THIS event (or a later one for
|
|
1559
|
+
// the same turnId), `maybeCloseTurn` folds them into
|
|
1560
|
+
// `turn.done.outcome.paused.asks[]` instead of fabricating success
|
|
1561
|
+
// (audit M26).
|
|
1692
1562
|
for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
|
|
1563
|
+
if (askedOriginals?.has(callId) === true) continue;
|
|
1693
1564
|
const view = adkAuthConfigView(authConfig);
|
|
1694
1565
|
const ask: AgPausedAsk = {
|
|
1695
1566
|
askId: `auth_${callId}`,
|
|
@@ -1707,6 +1578,8 @@ function driveAdkTopLevel(
|
|
|
1707
1578
|
// `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
|
|
1708
1579
|
// 18). Tracked in `pendingAsks` for the same paused-close fold as above.
|
|
1709
1580
|
for (const [callId, conf] of Object.entries(actions.requestedToolConfirmations)) {
|
|
1581
|
+
// Asked already by the reserved adk_request_confirmation call (item 26).
|
|
1582
|
+
if (askedOriginals?.has(callId) === true) continue;
|
|
1710
1583
|
const metadata: { [k: string]: JsonValue } = {};
|
|
1711
1584
|
if (conf.confirmed !== undefined) metadata["confirmed"] = conf.confirmed;
|
|
1712
1585
|
if (conf.payload !== undefined) metadata["payload"] = JsonValue.parse(conf.payload);
|
|
@@ -1734,14 +1607,16 @@ function driveAdkTopLevel(
|
|
|
1734
1607
|
// agentState is an OBJECT on the official 2.0.0 EventActions (a
|
|
1735
1608
|
// resumable-checkpoint snapshot, e.g. `{ input }`), a string on the older
|
|
1736
1609
|
// hand-typed contract — JsonValue.parse at the boundary carries either.
|
|
1737
|
-
if (actions.agentState !== undefined)
|
|
1738
|
-
|
|
1610
|
+
if (actions.agentState !== undefined) {
|
|
1611
|
+
const carried = carryNodeValue(actions.agentState);
|
|
1612
|
+
if (carried !== undefined) unmappedActions["agentState"] = carried.value;
|
|
1613
|
+
}
|
|
1739
1614
|
if (actions.endOfAgent !== undefined) unmappedActions["endOfAgent"] = actions.endOfAgent;
|
|
1740
1615
|
if (Object.keys(unmappedActions).length > 0) {
|
|
1741
1616
|
a.contentBlock(messageId, {
|
|
1742
1617
|
type: "provider-raw",
|
|
1743
1618
|
vendor: "google",
|
|
1744
|
-
raw: JsonValue.parse(unmappedActions),
|
|
1619
|
+
raw: reduceCarried(JsonValue.parse(unmappedActions)),
|
|
1745
1620
|
});
|
|
1746
1621
|
}
|
|
1747
1622
|
}
|
|
@@ -1800,7 +1675,10 @@ function driveAdkTopLevel(
|
|
|
1800
1675
|
// throughout (`route` may legitimately be `false`/`0`; `output` may be any
|
|
1801
1676
|
// JSON value incl. null); `nodeInfo` rides as a WHOLE object. `nodeInfo` is
|
|
1802
1677
|
// also READ by maybeCloseTurn's per-event gate and by isAdkPauseEnd.
|
|
1803
|
-
if (event.output !== undefined)
|
|
1678
|
+
if (event.output !== undefined) {
|
|
1679
|
+
const carried = carryNodeValue(event.output);
|
|
1680
|
+
if (carried !== undefined) unmappedEvent["output"] = carried.value;
|
|
1681
|
+
}
|
|
1804
1682
|
if (event.route !== undefined) unmappedEvent["route"] = JsonValue.parse(event.route);
|
|
1805
1683
|
if (event.nodeInfo !== undefined) unmappedEvent["nodeInfo"] = JsonValue.parse(event.nodeInfo);
|
|
1806
1684
|
if (event.isolationScope !== undefined)
|
|
@@ -1813,13 +1691,134 @@ function driveAdkTopLevel(
|
|
|
1813
1691
|
a.contentBlock(messageId, {
|
|
1814
1692
|
type: "provider-raw",
|
|
1815
1693
|
vendor: "google",
|
|
1816
|
-
raw: JsonValue.parse(unmappedEvent),
|
|
1694
|
+
raw: reduceCarried(JsonValue.parse(unmappedEvent)),
|
|
1817
1695
|
});
|
|
1818
1696
|
}
|
|
1819
1697
|
}
|
|
1820
1698
|
|
|
1821
1699
|
// ─── stateful factory: createAdkNormalizer ────────────────────────────────────
|
|
1822
|
-
|
|
1700
|
+
/** Options for {@link createAdkNormalizer}. */
|
|
1701
|
+
export interface AdkNormalizerOptions {
|
|
1702
|
+
/**
|
|
1703
|
+
* Opt in to SPEC §8.0 host obligation 4 (draft.4): the host feeds
|
|
1704
|
+
* `{ type: "__host_complete__" }` after the ADK run returned NORMALLY (never
|
|
1705
|
+
* after a cancel, an abort signal or a thrown error), before `flush()`.
|
|
1706
|
+
* Then a success close waits for that event (so a Workflow, a
|
|
1707
|
+
* SequentialAgent or after-agent callback content can follow a node's final
|
|
1708
|
+
* text), and on it each still-open turn closes: `paused` if an ask is
|
|
1709
|
+
* pending, left to `flush()` if a non-HITL long-running call is unanswered,
|
|
1710
|
+
* else `success`. Default off: the step-1 behaviour.
|
|
1711
|
+
*/
|
|
1712
|
+
hostCompletion?: boolean;
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
/** The facet-local host-completion native (§8.0 host obligation 4). */
|
|
1716
|
+
export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
|
|
1717
|
+
|
|
1718
|
+
/**
|
|
1719
|
+
* SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
|
|
1720
|
+
* the stream (e.g. its LLM-call limit), the host catches it and pushes
|
|
1721
|
+
* `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
|
|
1722
|
+
* open turn closes `turn.error` with that code and message. The shape matches the OpenAI
|
|
1723
|
+
* facet's sentinel. A host may build it from the caught Error itself
|
|
1724
|
+
* (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
|
|
1725
|
+
* read from the raw native, so the Error's own message is kept.
|
|
1726
|
+
*/
|
|
1727
|
+
export const ADK_HOST_ERROR_TYPE = "__host_error__";
|
|
1728
|
+
|
|
1729
|
+
interface AdkHostError {
|
|
1730
|
+
code: string;
|
|
1731
|
+
message: string;
|
|
1732
|
+
usage?: AgUsage;
|
|
1733
|
+
/** The invoke's ADK invocationId, when the host has it: used to name a
|
|
1734
|
+
* fresh terminal turn if the error arrives before any event. */
|
|
1735
|
+
invocationId?: string;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/** The host-error sentinel, read from the RAW native (an Error's message is
|
|
1739
|
+
* not an own enumerable member, so a JSON copy would lose it). A usage that is
|
|
1740
|
+
* not a valid AgUsage is dropped. Never throws. */
|
|
1741
|
+
function hostErrorOf(raw: unknown): AdkHostError | undefined {
|
|
1742
|
+
if (raw === null || typeof raw !== "object") return undefined;
|
|
1743
|
+
try {
|
|
1744
|
+
if (Reflect.get(raw, "type") !== ADK_HOST_ERROR_TYPE) return undefined;
|
|
1745
|
+
const code: unknown = Reflect.get(raw, "code");
|
|
1746
|
+
const message: unknown = Reflect.get(raw, "message");
|
|
1747
|
+
if (typeof code !== "string" || typeof message !== "string") return undefined;
|
|
1748
|
+
const usageRaw: unknown = Reflect.get(raw, "usage");
|
|
1749
|
+
const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
|
|
1750
|
+
const invocationId: unknown = Reflect.get(raw, "invocationId");
|
|
1751
|
+
return {
|
|
1752
|
+
code,
|
|
1753
|
+
message,
|
|
1754
|
+
...(usage?.success === true ? { usage: usage.data } : {}),
|
|
1755
|
+
...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
|
|
1756
|
+
};
|
|
1757
|
+
} catch {
|
|
1758
|
+
return undefined;
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
/** Exactly `{ type: "__host_complete__" }` (one key), as recorded by a capture harness. */
|
|
1763
|
+
function isHostCompleteNative(v: JsonValue): boolean {
|
|
1764
|
+
return isJsonObject(v) && v["type"] === ADK_HOST_COMPLETE_TYPE && Object.keys(v).length === 1;
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
/**
|
|
1768
|
+
* The google-adk Normalizer: the inner, deterministic normalizer below wrapped
|
|
1769
|
+
* in core's withAtomicPush (the fleet guard ruling). Every push() is atomic:
|
|
1770
|
+
* - The native is read once as plain JSON through core's toJsonValueSafe, so a
|
|
1771
|
+
* host may push the live Event objects ADK yields (undefined members, a
|
|
1772
|
+
* Date, an Error, a cycle) and they map exactly like the recorded corpus.
|
|
1773
|
+
* - If mapping one native throws (an event whose envelope is valid but whose
|
|
1774
|
+
* inner members have unexpected types), its partial batch is discarded
|
|
1775
|
+
* without consuming seq, the inner is rebuilt by re-driving every native
|
|
1776
|
+
* accepted so far (the inner never reads the clock or randomness; ids come
|
|
1777
|
+
* from invocationId and per-invoke ordinals, and the one random stem, for a
|
|
1778
|
+
* host error before any event, is drawn outside the inner and kept), and
|
|
1779
|
+
* ONE core `error {message:
|
|
1780
|
+
* "normalizer error", code: <constructor name>}` takes the next seq, with no
|
|
1781
|
+
* payload and no message text.
|
|
1782
|
+
* - flush() is guarded the same way; the wrapper closes what the consumer saw
|
|
1783
|
+
* open itself, without calling the inner again.
|
|
1784
|
+
* So push() never throws (SPEC §8.0), and no facet state believes a turn,
|
|
1785
|
+
* message or block is open that never reached the wire.
|
|
1786
|
+
*/
|
|
1787
|
+
export function createAdkNormalizer(options: AdkNormalizerOptions = {}): Normalizer {
|
|
1788
|
+
// A per-instance id stem, drawn lazily and only on the paths that need it (an
|
|
1789
|
+
// event with neither invocationId nor id; a host error before any event,
|
|
1790
|
+
// with no invocationId on the sentinel). It lives OUTSIDE the inner, so a
|
|
1791
|
+
// rebuild re-drives to the same ids.
|
|
1792
|
+
const stem: IdStem = {};
|
|
1793
|
+
return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
/** Holds the lazily drawn per-instance id stem across inner rebuilds. */
|
|
1797
|
+
interface IdStem {
|
|
1798
|
+
value?: string;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/** A random per-instance stem; never called while a replay re-drives, since
|
|
1802
|
+
* the stem is drawn once and kept.
|
|
1803
|
+
*
|
|
1804
|
+
* The `Date.now` + `Math.random` fallback runs only when `crypto.randomUUID`
|
|
1805
|
+
* is absent, which cannot happen on Node >= 19 (a global `crypto`). It is the
|
|
1806
|
+
* facet's one read of the clock or a random source, and it is safe for
|
|
1807
|
+
* determinism: the stem is drawn outside the inner, once, and a
|
|
1808
|
+
* withAtomicPush rebuild reuses it, so the corpus legs that poison the clock
|
|
1809
|
+
* and randomness never reach this call. */
|
|
1810
|
+
function drawIdStem(): string {
|
|
1811
|
+
const cryptoObj: unknown = Reflect.get(globalThis, "crypto");
|
|
1812
|
+
const randomUUID: unknown = cryptoObj !== undefined && cryptoObj !== null ? Reflect.get(cryptoObj, "randomUUID") : undefined;
|
|
1813
|
+
if (typeof randomUUID === "function") {
|
|
1814
|
+
const id: unknown = Reflect.apply(randomUUID, cryptoObj, []);
|
|
1815
|
+
if (typeof id === "string") return id;
|
|
1816
|
+
}
|
|
1817
|
+
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem): Normalizer {
|
|
1821
|
+
const hostCompletion = options.hostCompletion === true;
|
|
1823
1822
|
const a = new StreamAssembler();
|
|
1824
1823
|
const threadId = "google";
|
|
1825
1824
|
// §8.3 per-instance accumulator (replaces the module-level streamedText Map):
|
|
@@ -1844,8 +1843,13 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
1844
1843
|
// (the is_final_response aggregate); the `flush()` truncation path never
|
|
1845
1844
|
// reads it — see the comment there.
|
|
1846
1845
|
const pendingAsks = new Map<string, AgPausedAsk[]>();
|
|
1847
|
-
//
|
|
1848
|
-
|
|
1846
|
+
// Pause-family bookkeeping (item 26): reserved-call ids already asked, and the
|
|
1847
|
+
// original tool-call ids their asks cover, per turn.
|
|
1848
|
+
const reserved: ReservedAskState = { asked: new Set(), originalsByTurn: new Map() };
|
|
1849
|
+
// Host obligation 4 (opt-in): a success close stashed until the sentinel, and
|
|
1850
|
+
// the non-HITL long-running calls still unanswered, per turn.
|
|
1851
|
+
const deferredClose = new Map<string, AdkEvent>();
|
|
1852
|
+
const pendingLongRunning = new Map<string, Set<string>>();
|
|
1849
1853
|
const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
|
|
1850
1854
|
// Null-id call mint state (audit M47) — per-invoke ordinal counter + the
|
|
1851
1855
|
// content/name correlation maps; lives exactly as long as this Normalizer
|
|
@@ -1922,9 +1926,30 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
1922
1926
|
// reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
|
|
1923
1927
|
// closes the turn as success. It is a per-EVENT test, never a latch
|
|
1924
1928
|
// (NodeTool puts nodeInfo into plain runs too). Error closes stay
|
|
1925
|
-
// immediate. A completed workflow
|
|
1926
|
-
//
|
|
1929
|
+
// immediate. A completed workflow closes success only on the host-completion
|
|
1930
|
+
// event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
|
|
1931
|
+
// it flushes turn.abort.
|
|
1927
1932
|
if (errorClose === undefined && event.nodeInfo !== undefined) return;
|
|
1933
|
+
// Host obligation 4 (opt-in): a SUCCESS close waits for the host-completion
|
|
1934
|
+
// event, because the run may not be over (a SequentialAgent's next agent,
|
|
1935
|
+
// after-agent callback content). The final response is stashed and closed
|
|
1936
|
+
// unchanged on the sentinel, so a stream ending here is byte-identical.
|
|
1937
|
+
// Error and paused closes stay immediate.
|
|
1938
|
+
if (hostCompletion && errorClose === undefined && !((pendingAsks.get(turnId)?.length ?? 0) > 0)) {
|
|
1939
|
+
deferredClose.set(turnId, event);
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
closeOnFinalResponse(event, turnId, messageId, errorClose);
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
/** The close on a final response: lossy-finish metadata, message.end, then
|
|
1946
|
+
* turn.error or turn.done (paused when asks are pending, else success). */
|
|
1947
|
+
function closeOnFinalResponse(
|
|
1948
|
+
event: AdkEvent,
|
|
1949
|
+
turnId: string,
|
|
1950
|
+
messageId: string,
|
|
1951
|
+
errorClose: { code: string; message: string } | undefined,
|
|
1952
|
+
): void {
|
|
1928
1953
|
closedTurns.add(turnId);
|
|
1929
1954
|
const rawFinish = event.finishReason ?? event.errorCode;
|
|
1930
1955
|
const finish = resolveFinishReason(rawFinish);
|
|
@@ -1966,18 +1991,125 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
1966
1991
|
a.closeTurnDone(turnId, {
|
|
1967
1992
|
outcome: paused ? { type: "paused", asks } : { type: "success" },
|
|
1968
1993
|
finishReason: paused ? "paused" : finish.value,
|
|
1994
|
+
// draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
|
|
1995
|
+
// native value verbatim in turn.done.finishReasonRaw. That is the value
|
|
1996
|
+
// finishReason was mapped from: the wire finishReason, or for an
|
|
1997
|
+
// errorCode-only soft close the errorCode. A paused close's "paused" is
|
|
1998
|
+
// not a fallback, so it takes no companion. message.metadata's
|
|
1999
|
+
// rawFinishReason/rawErrorCode carry stays for one cohort.
|
|
2000
|
+
...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
|
|
1969
2001
|
...(usage !== undefined ? { usage } : {}),
|
|
1970
2002
|
...(safety !== undefined ? { safety } : {}),
|
|
1971
2003
|
});
|
|
1972
2004
|
}
|
|
1973
2005
|
}
|
|
1974
2006
|
|
|
2007
|
+
/** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
|
|
2008
|
+
* pending until its functionResponse arrives. */
|
|
2009
|
+
function trackLongRunning(event: AdkEvent, turnId: string): void {
|
|
2010
|
+
const longRunningIds = event.longRunningToolIds ?? [];
|
|
2011
|
+
const pending = pendingLongRunning.get(turnId) ?? new Set<string>();
|
|
2012
|
+
for (const part of event.content?.parts ?? []) {
|
|
2013
|
+
const callId = stringMember(part.functionCall, "id");
|
|
2014
|
+
if (callId !== undefined && longRunningIds.includes(callId)) pending.add(callId);
|
|
2015
|
+
const responseId = stringMember(part.functionResponse, "id");
|
|
2016
|
+
if (responseId !== undefined) pending.delete(responseId);
|
|
2017
|
+
}
|
|
2018
|
+
pendingLongRunning.set(turnId, pending);
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
/** The host-completion event (SPEC §8.0 host obligation 4): the run returned
|
|
2022
|
+
* normally. Each still-open turn closes from push(): paused when an ask is
|
|
2023
|
+
* pending; left to flush() when a non-HITL long-running call is unanswered;
|
|
2024
|
+
* otherwise success (the stashed final response's close, or a plain success
|
|
2025
|
+
* close with the accumulated usage when the run ended on a non-final event,
|
|
2026
|
+
* e.g. a completed Workflow). */
|
|
2027
|
+
function hostComplete(): void {
|
|
2028
|
+
for (const turnId of openTurns) {
|
|
2029
|
+
if (closedTurns.has(turnId)) continue;
|
|
2030
|
+
const messageId = `msg_${turnId}`;
|
|
2031
|
+
const asks = pendingAsks.get(turnId);
|
|
2032
|
+
if (asks !== undefined && asks.length > 0) {
|
|
2033
|
+
closedTurns.add(turnId);
|
|
2034
|
+
const usage = mapUsage(usageByTurn.get(turnId));
|
|
2035
|
+
a.closeMessage(messageId);
|
|
2036
|
+
a.closeTurnDone(turnId, {
|
|
2037
|
+
outcome: { type: "paused", asks },
|
|
2038
|
+
finishReason: "paused",
|
|
2039
|
+
...(usage !== undefined ? { usage } : {}),
|
|
2040
|
+
});
|
|
2041
|
+
continue;
|
|
2042
|
+
}
|
|
2043
|
+
if ((pendingLongRunning.get(turnId)?.size ?? 0) > 0) continue;
|
|
2044
|
+
const stashed = deferredClose.get(turnId);
|
|
2045
|
+
if (stashed !== undefined) {
|
|
2046
|
+
closeOnFinalResponse(stashed, turnId, messageId, undefined);
|
|
2047
|
+
continue;
|
|
2048
|
+
}
|
|
2049
|
+
closedTurns.add(turnId);
|
|
2050
|
+
const usage = mapUsage(usageByTurn.get(turnId));
|
|
2051
|
+
a.closeMessage(messageId);
|
|
2052
|
+
a.closeTurnDone(turnId, {
|
|
2053
|
+
outcome: { type: "success" },
|
|
2054
|
+
finishReason: "stop",
|
|
2055
|
+
...(usage !== undefined ? { usage } : {}),
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
/** Host obligation 1: close every still-open turn, innermost first, as
|
|
2061
|
+
* turn.error with the sentinel's code and message (and its usage, else the
|
|
2062
|
+
* turn's accumulated usage). A success close stashed for the host-completion
|
|
2063
|
+
* signal never fires, since the turn is now closed: the run did not
|
|
2064
|
+
* complete. With no turn open, a fresh terminal turn carries the error, so
|
|
2065
|
+
* it is never start-less. */
|
|
2066
|
+
let hostErrorTurns = 0;
|
|
2067
|
+
// The first turn key this invoke drove (its ADK invocationId): the stem of a
|
|
2068
|
+
// fresh terminal turn's id, so the id is unique across the invokes a host
|
|
2069
|
+
// folds together, not only within this one.
|
|
2070
|
+
let firstKey: string | undefined;
|
|
2071
|
+
function hostError(err: AdkHostError): void {
|
|
2072
|
+
let closed = 0;
|
|
2073
|
+
for (const turnId of [...openTurns].reverse()) {
|
|
2074
|
+
if (closedTurns.has(turnId)) continue;
|
|
2075
|
+
closedTurns.add(turnId);
|
|
2076
|
+
const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
|
|
2077
|
+
a.closeMessage(`msg_${turnId}`);
|
|
2078
|
+
a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
|
|
2079
|
+
closed++;
|
|
2080
|
+
}
|
|
2081
|
+
if (closed > 0) return;
|
|
2082
|
+
const base = firstKey ?? err.invocationId ?? (stem.value ??= drawIdStem());
|
|
2083
|
+
const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
|
|
2084
|
+
const messageId = ensureOpen(turnId);
|
|
2085
|
+
closedTurns.add(turnId);
|
|
2086
|
+
a.closeMessage(messageId);
|
|
2087
|
+
a.closeTurnError(turnId, {
|
|
2088
|
+
message: err.message,
|
|
2089
|
+
code: err.code,
|
|
2090
|
+
...(err.usage !== undefined ? { usage: err.usage } : {}),
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
|
|
1975
2094
|
function drive(event: AdkEvent): void {
|
|
1976
|
-
const key = turnKey(event)
|
|
2095
|
+
const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
|
|
2096
|
+
firstKey ??= key;
|
|
1977
2097
|
const turnId = `turn_${key}`;
|
|
1978
2098
|
const messageId = ensureOpen(turnId);
|
|
1979
2099
|
const parts = event.content?.parts ?? [];
|
|
1980
2100
|
const isPartial = event.partial === true;
|
|
2101
|
+
// ADK renders an object `output` as the same event's text part, byte-equal
|
|
2102
|
+
// to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
|
|
2103
|
+
// When the node-data reduction changed that output, the rendering would
|
|
2104
|
+
// repeat what the reduction removed, so that one part is skipped here and
|
|
2105
|
+
// in the aggregate below. Nothing else matches: not a string output, not
|
|
2106
|
+
// a substring, not model text.
|
|
2107
|
+
const renderedOutput = changedOutputRendering(event.output);
|
|
2108
|
+
const skipped = new Set<number>();
|
|
2109
|
+
if (renderedOutput !== undefined)
|
|
2110
|
+
parts.forEach((p, idx) => {
|
|
2111
|
+
if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput) skipped.add(idx);
|
|
2112
|
+
});
|
|
1981
2113
|
|
|
1982
2114
|
// STREAMED-text citations carrier (audit M22): groundingMetadata is
|
|
1983
2115
|
// EVENT-level, not per-part. A Gemini grounding response carries the full
|
|
@@ -1988,7 +2120,9 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
1988
2120
|
const citations = mapGroundingCitations(event.groundingMetadata);
|
|
1989
2121
|
const citedPartIndex =
|
|
1990
2122
|
citations !== undefined
|
|
1991
|
-
? parts.findIndex(
|
|
2123
|
+
? parts.findIndex(
|
|
2124
|
+
(p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string",
|
|
2125
|
+
)
|
|
1992
2126
|
: -1;
|
|
1993
2127
|
|
|
1994
2128
|
// Review finding c-i/c-ii: resolve null-id functionResponse correlation
|
|
@@ -2014,7 +2148,9 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
2014
2148
|
const isAggregate = !isPartial && alreadyStreamed.length > 0;
|
|
2015
2149
|
const aggregateText = isAggregate
|
|
2016
2150
|
? parts
|
|
2017
|
-
.filter(
|
|
2151
|
+
.filter(
|
|
2152
|
+
(p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string",
|
|
2153
|
+
)
|
|
2018
2154
|
.map((p) => p.text ?? "")
|
|
2019
2155
|
.join("")
|
|
2020
2156
|
: "";
|
|
@@ -2025,6 +2161,7 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
2025
2161
|
let accumulated = alreadyStreamed;
|
|
2026
2162
|
|
|
2027
2163
|
parts.forEach((part, index) => {
|
|
2164
|
+
if (skipped.has(index)) return;
|
|
2028
2165
|
const isAggregateText =
|
|
2029
2166
|
isAggregate &&
|
|
2030
2167
|
part.thought !== true &&
|
|
@@ -2042,7 +2179,7 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
2042
2179
|
return;
|
|
2043
2180
|
}
|
|
2044
2181
|
if (residualTail.length > 0) {
|
|
2045
|
-
const id = mintBlockId(blockIds,
|
|
2182
|
+
const id = mintBlockId(blockIds, "text");
|
|
2046
2183
|
a.textStart(id, messageId);
|
|
2047
2184
|
a.textDelta(id, messageId, residualTail);
|
|
2048
2185
|
a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
|
|
@@ -2085,17 +2222,40 @@ export function createAdkNormalizer(): Normalizer {
|
|
|
2085
2222
|
// aggregate never arrives simply die with the invoke's closure — bounded,
|
|
2086
2223
|
// per-invoke.
|
|
2087
2224
|
|
|
2088
|
-
|
|
2225
|
+
if (!isPartial) trackLongRunning(event, turnId);
|
|
2226
|
+
driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
|
|
2089
2227
|
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
2090
2228
|
}
|
|
2091
2229
|
|
|
2092
2230
|
return {
|
|
2093
2231
|
push(native: JsonValue): AgEvent[] {
|
|
2094
|
-
|
|
2095
|
-
|
|
2232
|
+
// withAtomicPush has already read the native as plain JSON (see
|
|
2233
|
+
// createAdkNormalizer). The host-error sentinel is checked first: an
|
|
2234
|
+
// Error-built one keeps its message, because core maps an Error to
|
|
2235
|
+
// {name, message, ...own enumerable}.
|
|
2236
|
+
const json = native;
|
|
2237
|
+
const hostErr = hostErrorOf(json);
|
|
2238
|
+
if (hostErr !== undefined) {
|
|
2239
|
+
// Like the completion sentinel below, a host<->facet contract input
|
|
2240
|
+
// (SPEC §8.0 host obligation 1), not a framework native.
|
|
2241
|
+
hostError(hostErr);
|
|
2242
|
+
return a.drain();
|
|
2243
|
+
}
|
|
2244
|
+
if (isHostCompleteNative(json)) {
|
|
2245
|
+
// The host-completion sentinel is a host<->facet contract input (SPEC
|
|
2246
|
+
// §8.0 host obligation 4), like obligation 1's `__host_error__`: NOT a
|
|
2247
|
+
// framework native. So §8.0's graceful-degradation rule ("MUST NOT
|
|
2248
|
+
// silently drop a native event") does not bind it. With the option OFF
|
|
2249
|
+
// it is ignored by design and never reaches the wire as
|
|
2250
|
+
// ext.google.unparsed.
|
|
2251
|
+
if (hostCompletion) hostComplete();
|
|
2252
|
+
return a.drain();
|
|
2253
|
+
}
|
|
2254
|
+
if (!isAdkEvent(json)) {
|
|
2255
|
+
a.emitExt("google", "unparsed", { native: json });
|
|
2096
2256
|
return a.drain();
|
|
2097
2257
|
}
|
|
2098
|
-
drive(
|
|
2258
|
+
drive(json);
|
|
2099
2259
|
return a.drain();
|
|
2100
2260
|
},
|
|
2101
2261
|
flush(): AgEvent[] {
|