@silverprotocol/google-adk 0.6.7 → 0.7.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 +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 +70 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +509 -647
- 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 +579 -657
- package/src/json-guards.ts +20 -0
package/src/index.ts
CHANGED
|
@@ -48,6 +48,31 @@
|
|
|
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, which this release does not have.
|
|
59
|
+
*
|
|
60
|
+
* NOTE on the Live (bidi) path: a barge-in (`interrupted: true`, from ADK's live
|
|
61
|
+
* aggregator) closes the message, then the turn, as `turn.abort{interrupted}`,
|
|
62
|
+
* after the event's own content, and a turn gets one terminal. That does NOT
|
|
63
|
+
* make a real barge-in session fold. One live session is one ADK invocation,
|
|
64
|
+
* and so one turn here, and ADK delivers the flag first: the interrupted
|
|
65
|
+
* generation's own `usageMetadata` and `turnComplete` follow it, then the
|
|
66
|
+
* reply generation. Those events land in the closed turn until the facet opens
|
|
67
|
+
* a turn per generation, and a reducer parks on them (probe's gemini-3.8-live
|
|
68
|
+
* capture `live-bargein-gemini38live`, @google/adk 2.1.0: the interrupt at
|
|
69
|
+
* native 6, then usage, turnComplete and the reply). A second barge-in, or
|
|
70
|
+
* model content after a completed reply closed the turn (unless
|
|
71
|
+
* `hostCompletion` defers that close), parks the same way. Separately, when
|
|
72
|
+
* text is buffered at the interrupt, ADK yields
|
|
73
|
+
* only the text aggregate, without the flag (utils/live_connection_utils.js,
|
|
74
|
+
* @google/adk 2.1.0), so this facet sees no interrupt and the turn closes at
|
|
75
|
+
* flush as `stream-truncated`.
|
|
51
76
|
*/
|
|
52
77
|
import {
|
|
53
78
|
type AgEvent,
|
|
@@ -58,13 +83,29 @@ import {
|
|
|
58
83
|
type AgMeta,
|
|
59
84
|
type AgPausedAsk,
|
|
60
85
|
type AgSafety,
|
|
61
|
-
|
|
86
|
+
AgUsage,
|
|
62
87
|
AgProviderMeta,
|
|
63
88
|
JsonValue,
|
|
64
89
|
type Normalizer,
|
|
65
90
|
StreamAssembler,
|
|
66
91
|
type ToolOutcome,
|
|
92
|
+
toJsonValueSafe,
|
|
93
|
+
withAtomicPush,
|
|
67
94
|
} from "@silverprotocol/core";
|
|
95
|
+
import {
|
|
96
|
+
ADK_REQUEST_CREDENTIAL,
|
|
97
|
+
snakeKey,
|
|
98
|
+
pickAllowed,
|
|
99
|
+
scrubStateMap,
|
|
100
|
+
scrubAdkAuthConfig,
|
|
101
|
+
scrubbedResponse,
|
|
102
|
+
carryNodeValue,
|
|
103
|
+
changedOutputRendering,
|
|
104
|
+
reduceCarried,
|
|
105
|
+
scrubCredentialCallArgs,
|
|
106
|
+
adkAuthConfigView,
|
|
107
|
+
} from "./auth-objects.js";
|
|
108
|
+
import { isJsonObject, stringMember } from "./json-guards.js";
|
|
68
109
|
|
|
69
110
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
70
111
|
// AdkEvent — the HAND-DEFINED fixture contract (a faithful PROJECTION of the
|
|
@@ -447,10 +488,6 @@ export function isLossyFinishReason(reason: string): boolean {
|
|
|
447
488
|
|
|
448
489
|
// ─── stateful factory helpers ─────────────────────────────────────────────────
|
|
449
490
|
|
|
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
491
|
|
|
455
492
|
/** Outer-discriminant guard. ADK events carry an object `content` and/or an `invocationId`. */
|
|
456
493
|
function isAdkEvent(v: unknown): v is AdkEvent {
|
|
@@ -589,15 +626,6 @@ function inlineDataBlock(d: { mimeType: string; data: string; displayName?: stri
|
|
|
589
626
|
return { type: "file", source, ...(d.displayName !== undefined ? { filename: d.displayName } : {}) };
|
|
590
627
|
}
|
|
591
628
|
|
|
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
629
|
|
|
602
630
|
// A media/code arm missing a member its AgBlock arm REQUIRES rides verbatim in
|
|
603
631
|
// one provider-raw block keyed by its wire Part field name — the same
|
|
@@ -620,7 +648,7 @@ function carryUnmappableArm(
|
|
|
620
648
|
a.contentBlock(messageId, {
|
|
621
649
|
type: "provider-raw",
|
|
622
650
|
vendor: "google",
|
|
623
|
-
raw: JsonValue.parse({ [field]: arm }),
|
|
651
|
+
raw: reduceCarried(JsonValue.parse({ [field]: arm })),
|
|
624
652
|
});
|
|
625
653
|
}
|
|
626
654
|
|
|
@@ -660,6 +688,87 @@ function codeOutcome(outcome: string | undefined): "ok" | "failed" | "deadline_e
|
|
|
660
688
|
// (a dotless nodeInfo.path); that detail is facet-local, not spec.
|
|
661
689
|
// The caller closes `paused` on one of these only while an ask is pending.
|
|
662
690
|
const ADK_REQUEST_INPUT = "adk_request_input";
|
|
691
|
+
const ADK_REQUEST_CONFIRMATION = "adk_request_confirmation";
|
|
692
|
+
|
|
693
|
+
/** Per-normalizer pause-family bookkeeping (item 26): reserved-call ids already
|
|
694
|
+
* asked, and per turn the ORIGINAL tool-call ids those asks cover (so items
|
|
695
|
+
* 12/18 yield no second ask for them). */
|
|
696
|
+
type ReservedAskState = { asked: Set<string>; originalsByTurn: Map<string, Set<string>> };
|
|
697
|
+
|
|
698
|
+
/** A member of `v` by camelCase or snake_case name. */
|
|
699
|
+
function memberOf(v: JsonValue | undefined, name: string): JsonValue | undefined {
|
|
700
|
+
if (!isJsonObject(v)) return undefined;
|
|
701
|
+
if (Object.hasOwn(v, name)) return v[name];
|
|
702
|
+
const snake = snakeKey(name);
|
|
703
|
+
return Object.hasOwn(v, snake) ? v[snake] : undefined;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** The ask a reserved adk_request_* call yields (SPEC §8.0 item 26). */
|
|
707
|
+
function reservedCallAsk(
|
|
708
|
+
name: string,
|
|
709
|
+
callId: string,
|
|
710
|
+
args: { readonly [k: string]: JsonValue },
|
|
711
|
+
): { ask: AgPausedAsk; originalId?: string } {
|
|
712
|
+
if (name === ADK_REQUEST_INPUT) {
|
|
713
|
+
const schema = args["response_schema"];
|
|
714
|
+
const message = stringMember(args, "message");
|
|
715
|
+
const payload = args["payload"];
|
|
716
|
+
return {
|
|
717
|
+
ask: {
|
|
718
|
+
askId: callId,
|
|
719
|
+
kind: isJsonObject(schema) ? "form" : "text",
|
|
720
|
+
toolCallId: callId,
|
|
721
|
+
resumeBinding: "id",
|
|
722
|
+
...(message !== undefined ? { message } : {}),
|
|
723
|
+
...(isJsonObject(schema) ? { schema } : {}),
|
|
724
|
+
...(payload !== undefined ? { metadata: { payload } } : {}),
|
|
725
|
+
},
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
if (name === ADK_REQUEST_CREDENTIAL) {
|
|
729
|
+
const originalId =
|
|
730
|
+
stringMember(args, "functionCallId") ?? stringMember(args, "function_call_id");
|
|
731
|
+
const authConfig = memberOf(args, "authConfig") ?? null;
|
|
732
|
+
const message = stringMember(args, "message");
|
|
733
|
+
const view = adkAuthConfigView(authConfig);
|
|
734
|
+
return {
|
|
735
|
+
ask: {
|
|
736
|
+
askId: `auth_${callId}`,
|
|
737
|
+
kind: "auth",
|
|
738
|
+
toolCallId: callId,
|
|
739
|
+
resumeBinding: "id",
|
|
740
|
+
...(message !== undefined ? { message } : {}),
|
|
741
|
+
...(view !== undefined ? { authConfig: view } : {}),
|
|
742
|
+
metadata: {
|
|
743
|
+
authConfig: scrubAdkAuthConfig(authConfig),
|
|
744
|
+
...(originalId !== undefined ? { originalFunctionCallId: originalId } : {}),
|
|
745
|
+
},
|
|
746
|
+
},
|
|
747
|
+
...(originalId !== undefined ? { originalId } : {}),
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
// adk_request_confirmation: args {originalFunctionCall {id, name, args}, toolConfirmation {hint, confirmed, payload}}.
|
|
751
|
+
const originalId = stringMember(memberOf(args, "originalFunctionCall"), "id");
|
|
752
|
+
const confirmation = memberOf(args, "toolConfirmation");
|
|
753
|
+
const hint = stringMember(confirmation, "hint");
|
|
754
|
+
const confirmed = memberOf(confirmation, "confirmed");
|
|
755
|
+
const payload = memberOf(confirmation, "payload");
|
|
756
|
+
const metadata: { [k: string]: JsonValue } = {};
|
|
757
|
+
if (typeof confirmed === "boolean") metadata["confirmed"] = confirmed;
|
|
758
|
+
if (payload !== undefined) metadata["payload"] = payload;
|
|
759
|
+
if (originalId !== undefined) metadata["originalFunctionCallId"] = originalId;
|
|
760
|
+
return {
|
|
761
|
+
ask: {
|
|
762
|
+
askId: `approval_${callId}`,
|
|
763
|
+
kind: "approval",
|
|
764
|
+
toolCallId: callId,
|
|
765
|
+
resumeBinding: "id",
|
|
766
|
+
...(hint !== undefined ? { message: hint } : {}),
|
|
767
|
+
...(Object.keys(metadata).length > 0 ? { metadata } : {}),
|
|
768
|
+
},
|
|
769
|
+
...(originalId !== undefined ? { originalId } : {}),
|
|
770
|
+
};
|
|
771
|
+
}
|
|
663
772
|
|
|
664
773
|
function isNonEmptyRecord(v: unknown): boolean {
|
|
665
774
|
return isJsonObject(v) && Object.keys(v).length > 0;
|
|
@@ -681,8 +790,12 @@ function isAdkPauseEnd(event: AdkEvent): boolean {
|
|
|
681
790
|
);
|
|
682
791
|
}
|
|
683
792
|
|
|
684
|
-
|
|
685
|
-
|
|
793
|
+
/** The event's own turn key: its invocationId, else its id. `undefined` when it
|
|
794
|
+
* has neither; the normalizer then names the turn from its per-instance stem,
|
|
795
|
+
* never a constant that would repeat across the invokes a host folds together. */
|
|
796
|
+
function turnKey(ev: AdkEvent): string | undefined {
|
|
797
|
+
if (ev.invocationId && ev.invocationId.length > 0) return ev.invocationId;
|
|
798
|
+
return ev.id !== undefined && ev.id !== null && ev.id.length > 0 ? ev.id : undefined;
|
|
686
799
|
}
|
|
687
800
|
|
|
688
801
|
// ─── tool-call positional index (spec §8.2) ───────────────────────────────────
|
|
@@ -691,6 +804,78 @@ function turnKey(ev: AdkEvent): string {
|
|
|
691
804
|
// the positional index on tool.start/tool-call `providerCallIndex` so re-input can
|
|
692
805
|
// restore name+position correlation when echoing functionResponse parts.
|
|
693
806
|
|
|
807
|
+
// ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
|
|
808
|
+
// adk-10, founder-ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
|
|
809
|
+
// answers a failed tool call with a response carrying Gemini's documented
|
|
810
|
+
// `error` key: an unresolvable tool name (functions.js:264), a thrown tool
|
|
811
|
+
// including a thrown MCP call (functions.js:282), several built-in tools.
|
|
812
|
+
// Rules, in order:
|
|
813
|
+
// 1. MCP CallToolResult `isError: true` → "error" + isError.
|
|
814
|
+
// 2. The call id is named in the SAME event's actions.requestedToolConfirmations
|
|
815
|
+
// or actions.requestedAuthConfigs → "ok": ADK's pause placeholder
|
|
816
|
+
// (function_tool.js:139-141, same event per functions.js:422-431); the
|
|
817
|
+
// pause rides hitl.ask (§8.0 items 12 and 18).
|
|
818
|
+
// 3. A declined approval → "denied", no errorText, no isError: an `error`
|
|
819
|
+
// equal to a rejection literal or starting with the policy-engine prefix,
|
|
820
|
+
// or an error_code/errorCode of CONFIRMATION_REJECTED.
|
|
821
|
+
// 4. An `error` present and not null/false/0/"" → "error" + isError, with
|
|
822
|
+
// errorText when it is a string and errorCode from a string
|
|
823
|
+
// error_code/errorCode.
|
|
824
|
+
// 5. Otherwise "ok" (incl. `{status:"error", …}`, out of scope per item 25).
|
|
825
|
+
// `content` always carries the response verbatim (functionResponseToToolDoneFields).
|
|
826
|
+
// Literals pinned at @google/adk 2.1.0: function_tool.js:144,
|
|
827
|
+
// security_plugin.js:75 and :113, run_skill_inline_script_tool.js:160-163.
|
|
828
|
+
const ADK_REJECTION_ERRORS: ReadonlySet<string> = new Set([
|
|
829
|
+
"This tool call is rejected.",
|
|
830
|
+
"Tool call rejected from confirmation flow.",
|
|
831
|
+
]);
|
|
832
|
+
const ADK_POLICY_REJECTION_PREFIX = "This tool call is rejected by policy engine.";
|
|
833
|
+
const ADK_REJECTION_ERROR_CODE = "CONFIRMATION_REJECTED";
|
|
834
|
+
|
|
835
|
+
type ToolResultClassification = {
|
|
836
|
+
outcome: ToolOutcome;
|
|
837
|
+
isError?: true;
|
|
838
|
+
errorText?: string;
|
|
839
|
+
errorCode?: string;
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
function isAdkPausePlaceholder(toolCallId: string, actions: AdkEvent["actions"]): boolean {
|
|
843
|
+
const confirmations = actions?.requestedToolConfirmations;
|
|
844
|
+
const auths = actions?.requestedAuthConfigs;
|
|
845
|
+
return (
|
|
846
|
+
(isJsonObject(confirmations) && Object.hasOwn(confirmations, toolCallId)) ||
|
|
847
|
+
(isJsonObject(auths) && Object.hasOwn(auths, toolCallId))
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function classifyFunctionResponse(
|
|
852
|
+
response: { readonly [k: string]: JsonValue } | undefined,
|
|
853
|
+
toolCallId: string,
|
|
854
|
+
actions: AdkEvent["actions"],
|
|
855
|
+
): ToolResultClassification {
|
|
856
|
+
if (response === undefined) return { outcome: "ok" };
|
|
857
|
+
if (response["isError"] === true) return { outcome: "error", isError: true };
|
|
858
|
+
if (isAdkPausePlaceholder(toolCallId, actions)) return { outcome: "ok" };
|
|
859
|
+
const error = response["error"];
|
|
860
|
+
const code = stringMember(response, "error_code") ?? stringMember(response, "errorCode");
|
|
861
|
+
if (
|
|
862
|
+
code === ADK_REJECTION_ERROR_CODE ||
|
|
863
|
+
(typeof error === "string" &&
|
|
864
|
+
(ADK_REJECTION_ERRORS.has(error) || error.startsWith(ADK_POLICY_REJECTION_PREFIX)))
|
|
865
|
+
) {
|
|
866
|
+
return { outcome: "denied" };
|
|
867
|
+
}
|
|
868
|
+
if (error !== undefined && error !== null && error !== false && error !== 0 && error !== "") {
|
|
869
|
+
return {
|
|
870
|
+
outcome: "error",
|
|
871
|
+
isError: true,
|
|
872
|
+
...(typeof error === "string" ? { errorText: error } : {}),
|
|
873
|
+
...(code !== undefined ? { errorCode: code } : {}),
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
return { outcome: "ok" };
|
|
877
|
+
}
|
|
878
|
+
|
|
694
879
|
// ─── functionResponse.response → tool.done channels (spec §2/§2.1, MCP shape) ──
|
|
695
880
|
// The Gemini functionResponse.response is a JSON OBJECT (the function result).
|
|
696
881
|
// Preserve its shape: an MCP-style { content: AgBlock[] } passes through as the
|
|
@@ -729,7 +914,7 @@ function functionResponseToToolDoneFields(
|
|
|
729
914
|
}
|
|
730
915
|
}
|
|
731
916
|
// Preserve any non-text MCP content part losslessly as a provider-raw block.
|
|
732
|
-
out.push({ type: "provider-raw", vendor: "google", raw: part });
|
|
917
|
+
out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
|
|
733
918
|
}
|
|
734
919
|
const meta = response["_meta"];
|
|
735
920
|
return {
|
|
@@ -931,20 +1116,24 @@ function consumeMintedCallId(
|
|
|
931
1116
|
}
|
|
932
1117
|
|
|
933
1118
|
// ─── stateful factory: driveAdkPart ──────────────────────────────────────────
|
|
934
|
-
// ─── block ids: a per-
|
|
1119
|
+
// ─── block ids: a per-INVOKE ordinal per kind (SPEC.md INV-BLOCK) ────────────
|
|
935
1120
|
// Streaming block ids MUST be unique within a fold, and identity MUST never
|
|
936
1121
|
// derive solely from a per-event positional index. ADK/Gemini parts carry no
|
|
937
1122
|
// 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
|
-
|
|
1123
|
+
// blocks across the WHOLE normalizer (one invoke, §8.0 obligation 3). The id
|
|
1124
|
+
// carries no turnId, so the counter must not reset per turn. A per-turn count
|
|
1125
|
+
// re-opened text:0 in a second turn of the same invoke (a workflow-node turn
|
|
1126
|
+
// then a plain turn), and the draft.4 reducer parks on that (rd-14 P14:
|
|
1127
|
+
// invoke-scoped INV-BLOCK, reset at the seq-0 restart). The old
|
|
1128
|
+
// `${kind}:${partIndex}` repeated across events: two thought events in one
|
|
1129
|
+
// invoke both opened reasoning:0 (thinking-gemini37/38, R&D item 14
|
|
1130
|
+
// prerequisite). A one-turn invoke's ids are unchanged, and every committed
|
|
1131
|
+
// adk golden is a one-turn invoke.
|
|
1132
|
+
type BlockIdMint = Map<"text" | "reasoning", number>;
|
|
1133
|
+
|
|
1134
|
+
function mintBlockId(m: BlockIdMint, kind: "text" | "reasoning"): string {
|
|
1135
|
+
const n = m.get(kind) ?? 0;
|
|
1136
|
+
m.set(kind, n + 1);
|
|
948
1137
|
return `${kind}:${n}`;
|
|
949
1138
|
}
|
|
950
1139
|
|
|
@@ -1003,13 +1192,13 @@ function driveAdkPart(
|
|
|
1003
1192
|
a.contentBlock(messageId, {
|
|
1004
1193
|
type: "provider-raw",
|
|
1005
1194
|
vendor: "google",
|
|
1006
|
-
raw: JsonValue.parse(unmappedPartFields),
|
|
1195
|
+
raw: reduceCarried(JsonValue.parse(unmappedPartFields)),
|
|
1007
1196
|
});
|
|
1008
1197
|
}
|
|
1009
1198
|
|
|
1010
1199
|
// ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
|
|
1011
1200
|
if (part.thought === true) {
|
|
1012
|
-
const id = mintBlockId(blockIds,
|
|
1201
|
+
const id = mintBlockId(blockIds, "reasoning");
|
|
1013
1202
|
a.reasoningStart(id, messageId);
|
|
1014
1203
|
// typeof, not `!== undefined`: a JSON-null text is absent (null guard).
|
|
1015
1204
|
if (typeof part.text === "string" && part.text.length > 0) a.reasoningDelta(id, messageId, part.text);
|
|
@@ -1029,7 +1218,7 @@ function driveAdkPart(
|
|
|
1029
1218
|
// falls through to the arms below (a functionCall beside it still maps), and
|
|
1030
1219
|
// `null` never reaches textDelta or the streamed-text accumulator.
|
|
1031
1220
|
if (typeof part.text === "string") {
|
|
1032
|
-
const id = mintBlockId(blockIds,
|
|
1221
|
+
const id = mintBlockId(blockIds, "text");
|
|
1033
1222
|
const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
|
|
1034
1223
|
// STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
|
|
1035
1224
|
// event's groundingSupports segments (each already carries its own offsets +
|
|
@@ -1133,17 +1322,17 @@ function driveAdkPart(
|
|
|
1133
1322
|
a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
|
|
1134
1323
|
return "";
|
|
1135
1324
|
}
|
|
1136
|
-
|
|
1325
|
+
// A JSON-null response is absent (null guard): it was dereferenced below.
|
|
1326
|
+
const response = isJsonObject(fr.response) ? fr.response : undefined;
|
|
1327
|
+
// A reserved-credential answer carries the client's credential: its content
|
|
1328
|
+
// AND its classification use the allowlisted form (see scrubAdkAuthConfig),
|
|
1329
|
+
// so nothing omitted can resurface through errorText.
|
|
1330
|
+
const carried = fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : response;
|
|
1137
1331
|
a.toolDone({
|
|
1138
1332
|
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,
|
|
1333
|
+
...functionResponseToToolDoneFields(fr.name, carried),
|
|
1334
|
+
// adk-10 / SPEC §8.0 item 25: see classifyFunctionResponse.
|
|
1335
|
+
...classifyFunctionResponse(carried, toolCallId, event.actions),
|
|
1147
1336
|
turnId,
|
|
1148
1337
|
providerMetadata:
|
|
1149
1338
|
fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
|
|
@@ -1227,7 +1416,7 @@ function driveAdkPart(
|
|
|
1227
1416
|
a.contentBlock(messageId, {
|
|
1228
1417
|
type: "provider-raw",
|
|
1229
1418
|
vendor: "google",
|
|
1230
|
-
raw: { fileData: { displayName } },
|
|
1419
|
+
raw: reduceCarried({ fileData: { displayName } }),
|
|
1231
1420
|
});
|
|
1232
1421
|
}
|
|
1233
1422
|
} else {
|
|
@@ -1239,478 +1428,6 @@ function driveAdkPart(
|
|
|
1239
1428
|
return "";
|
|
1240
1429
|
}
|
|
1241
1430
|
|
|
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, a tool's credential request inside an LlmAgent):
|
|
1268
|
-
// the credential resume rebuilds the request
|
|
1269
|
-
// server-side from the session's own reserved call (auth_preprocessor.js
|
|
1270
|
-
// requestedAuthConfigs) and takes only the auth code / response URI from the
|
|
1271
|
-
// client's answer (credential_response_binding.js bindCredential; the raw
|
|
1272
|
-
// credential is restored from the request). An oauth2/OIDC request always
|
|
1273
|
-
// carries a generated authUri (auth_handler.js generateAuthRequest). So what
|
|
1274
|
-
// the allowlist omits is never needed to answer the ask.
|
|
1275
|
-
const ADK_REQUEST_CREDENTIAL = "adk_request_credential";
|
|
1276
|
-
|
|
1277
|
-
type AllowSpec = { [key: string]: true | ((v: JsonValue) => JsonValue | undefined) };
|
|
1278
|
-
|
|
1279
|
-
function snakeKey(k: string): string {
|
|
1280
|
-
return k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
1281
|
-
}
|
|
1282
|
-
|
|
1283
|
-
/** Copy only the allowlisted members of `v` (camel or snake spelling), each
|
|
1284
|
-
* either verbatim (`true`) or through its nested allowlist. */
|
|
1285
|
-
function pickAllowed(v: JsonValue | undefined, spec: AllowSpec): JsonValue | undefined {
|
|
1286
|
-
if (!isJsonObject(v)) return undefined;
|
|
1287
|
-
const out: { [k: string]: JsonValue } = {};
|
|
1288
|
-
for (const [name, rule] of Object.entries(spec)) {
|
|
1289
|
-
for (const key of name === snakeKey(name) ? [name] : [name, snakeKey(name)]) {
|
|
1290
|
-
if (!Object.hasOwn(v, key)) continue;
|
|
1291
|
-
const member = v[key];
|
|
1292
|
-
if (member === undefined) continue;
|
|
1293
|
-
const kept = rule === true ? member : rule(member);
|
|
1294
|
-
if (kept !== undefined) out[key] = kept;
|
|
1295
|
-
}
|
|
1296
|
-
}
|
|
1297
|
-
return out;
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
const OAUTH2_ALLOW: AllowSpec = {
|
|
1301
|
-
clientId: true,
|
|
1302
|
-
authUri: true,
|
|
1303
|
-
redirectUri: true,
|
|
1304
|
-
scopes: true,
|
|
1305
|
-
codeChallengeMethod: true,
|
|
1306
|
-
tokenEndpointAuthMethod: true,
|
|
1307
|
-
expiresAt: true,
|
|
1308
|
-
expiresIn: true,
|
|
1309
|
-
audience: true,
|
|
1310
|
-
};
|
|
1311
|
-
const SERVICE_ACCOUNT_ALLOW: AllowSpec = {
|
|
1312
|
-
scopes: true,
|
|
1313
|
-
useDefaultCredential: true,
|
|
1314
|
-
useIdToken: true,
|
|
1315
|
-
audience: true,
|
|
1316
|
-
serviceAccountCredential: (v) =>
|
|
1317
|
-
pickAllowed(v, { projectId: true, clientEmail: true, tokenUri: true, universeDomain: true }),
|
|
1318
|
-
};
|
|
1319
|
-
const AUTH_CREDENTIAL_ALLOW: AllowSpec = {
|
|
1320
|
-
authType: true,
|
|
1321
|
-
resourceRef: true,
|
|
1322
|
-
oauth2: (v) => pickAllowed(v, OAUTH2_ALLOW),
|
|
1323
|
-
serviceAccount: (v) => pickAllowed(v, SERVICE_ACCOUNT_ALLOW),
|
|
1324
|
-
};
|
|
1325
|
-
// The security scheme, member by member: an OpenAPI 3.0 SecuritySchemeObject
|
|
1326
|
-
// (openapi-types 12.1.3 OpenAPIV3: http, apiKey, oauth2 and openIdConnect,
|
|
1327
|
-
// the type @google/adk 2.1.0's auth_schemes.d.ts names) or ADK's
|
|
1328
|
-
// OpenIdConnectWithConfig. Every leaf is a string, a string list or a map of
|
|
1329
|
-
// strings, and only those survive. A scheme member no type declares (a vendor
|
|
1330
|
-
// extension, a stray field) never rides.
|
|
1331
|
-
const schemeString = (v: JsonValue): JsonValue | undefined => (typeof v === "string" ? v : undefined);
|
|
1332
|
-
const schemeStringList = (v: JsonValue): JsonValue | undefined =>
|
|
1333
|
-
Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
|
|
1334
|
-
/** A map this facet rebuilds from native entries never carries an own
|
|
1335
|
-
* `__proto__` key (SPEC §13.7): JsonValue.parse drops one, and
|
|
1336
|
-
* Object.fromEntries would re-create it as an own property. */
|
|
1337
|
-
function isReservedMapKey(k: string): boolean {
|
|
1338
|
-
return k === "__proto__";
|
|
1339
|
-
}
|
|
1340
|
-
/** OAuth2 flow scopes are a map of scope name -> description; OIDC config
|
|
1341
|
-
* scopes are a list. Either keeps only its string entries. */
|
|
1342
|
-
const schemeScopes = (v: JsonValue): JsonValue | undefined =>
|
|
1343
|
-
Array.isArray(v)
|
|
1344
|
-
? schemeStringList(v)
|
|
1345
|
-
: isJsonObject(v)
|
|
1346
|
-
? Object.fromEntries(
|
|
1347
|
-
Object.entries(v).filter((e): e is [string, string] => !isReservedMapKey(e[0]) && typeof e[1] === "string"),
|
|
1348
|
-
)
|
|
1349
|
-
: undefined;
|
|
1350
|
-
const OAUTH2_FLOW_ALLOW: AllowSpec = {
|
|
1351
|
-
authorizationUrl: schemeString,
|
|
1352
|
-
tokenUrl: schemeString,
|
|
1353
|
-
refreshUrl: schemeString,
|
|
1354
|
-
scopes: schemeScopes,
|
|
1355
|
-
};
|
|
1356
|
-
const AUTH_SCHEME_ALLOW: AllowSpec = {
|
|
1357
|
-
type: schemeString,
|
|
1358
|
-
description: schemeString,
|
|
1359
|
-
// http
|
|
1360
|
-
scheme: schemeString,
|
|
1361
|
-
bearerFormat: schemeString,
|
|
1362
|
-
// apiKey (the header/query parameter's name and location, never its value)
|
|
1363
|
-
name: schemeString,
|
|
1364
|
-
in: schemeString,
|
|
1365
|
-
// oauth2 (flows.password is the password-GRANT flow: a tokenUrl and scopes)
|
|
1366
|
-
flows: (v) =>
|
|
1367
|
-
pickAllowed(v, {
|
|
1368
|
-
implicit: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1369
|
-
password: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1370
|
-
clientCredentials: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1371
|
-
authorizationCode: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
|
|
1372
|
-
}),
|
|
1373
|
-
// openIdConnect
|
|
1374
|
-
openIdConnectUrl: schemeString,
|
|
1375
|
-
// OpenIdConnectWithConfig
|
|
1376
|
-
authorizationEndpoint: schemeString,
|
|
1377
|
-
tokenEndpoint: schemeString,
|
|
1378
|
-
userinfoEndpoint: schemeString,
|
|
1379
|
-
revocationEndpoint: schemeString,
|
|
1380
|
-
tokenEndpointAuthMethodsSupported: schemeStringList,
|
|
1381
|
-
grantTypesSupported: schemeStringList,
|
|
1382
|
-
scopes: schemeScopes,
|
|
1383
|
-
};
|
|
1384
|
-
const AUTH_CONFIG_ALLOW: AllowSpec = {
|
|
1385
|
-
authScheme: (v) => pickAllowed(v, AUTH_SCHEME_ALLOW),
|
|
1386
|
-
credentialKey: true,
|
|
1387
|
-
rawAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
|
|
1388
|
-
exchangedAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
|
|
1389
|
-
};
|
|
1390
|
-
|
|
1391
|
-
// ─── shared state (state.delta) ──────────────────────────────────────────────
|
|
1392
|
-
// ADK itself writes an exchanged AuthCredential into the event's
|
|
1393
|
-
// actions.stateDelta on two paths (@google/adk 2.1.0):
|
|
1394
|
-
// - a Runner configured with SessionStateCredentialService saves it under the
|
|
1395
|
-
// bare credentialKey (session_state_credential_service.js; ToolContext's
|
|
1396
|
-
// State writes value AND delta, agents/context.js:37-39, sessions/state.js:97-102);
|
|
1397
|
-
// - a Workflow FunctionNode whose auth step runs again on resume stores it
|
|
1398
|
-
// under "temp:" + credentialKey (auth_handler.js:35-38, :47), and function_node.js
|
|
1399
|
-
// copies every new delta entry into the event it yields (:93-127). A Runner
|
|
1400
|
-
// removes "temp:" entries from a non-partial event as it appends it to the
|
|
1401
|
-
// session, before yielding it; a partial event, or an event read before
|
|
1402
|
-
// that append, still carries them.
|
|
1403
|
-
// ADK treats any value under the key as a stored credential
|
|
1404
|
-
// (hitl_utils.js:131-133), so the entry is omitted whole: a redacted value left
|
|
1405
|
-
// behind would read as a credential. Every "temp:" entry is omitted too
|
|
1406
|
-
// (invocation-scoped by ADK's contract). Every other entry rides unchanged.
|
|
1407
|
-
const ADK_TEMP_STATE_PREFIX = "temp:";
|
|
1408
|
-
const AUTH_CREDENTIAL_TYPES: ReadonlySet<string> = new Set(["apiKey", "http", "oauth2", "openIdConnect", "serviceAccount"]);
|
|
1409
|
-
// resourceRef (auth_credential.d.ts:244) names a stored credential: ADK's
|
|
1410
|
-
// presence readers treat an object holding it as a held credential.
|
|
1411
|
-
const AUTH_CREDENTIAL_MEMBERS = [
|
|
1412
|
-
"apiKey",
|
|
1413
|
-
"api_key",
|
|
1414
|
-
"http",
|
|
1415
|
-
"oauth2",
|
|
1416
|
-
"serviceAccount",
|
|
1417
|
-
"service_account",
|
|
1418
|
-
"resourceRef",
|
|
1419
|
-
"resource_ref",
|
|
1420
|
-
] as const;
|
|
1421
|
-
|
|
1422
|
-
function isObjectRecord(v: unknown): v is { readonly [k: string]: unknown } {
|
|
1423
|
-
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
1424
|
-
}
|
|
1425
|
-
|
|
1426
|
-
/** An ADK AuthCredential: `authType` (either spelling) is one of ADK's
|
|
1427
|
-
* credential types (auth_credential.d.ts) and a credential member is present
|
|
1428
|
-
* and non-null. */
|
|
1429
|
-
function isAuthCredentialObject(v: { readonly [k: string]: unknown }): boolean {
|
|
1430
|
-
const typed = ["authType", "auth_type"].some((k) => {
|
|
1431
|
-
const t = Object.hasOwn(v, k) ? v[k] : undefined;
|
|
1432
|
-
return typeof t === "string" && AUTH_CREDENTIAL_TYPES.has(t);
|
|
1433
|
-
});
|
|
1434
|
-
return typed && AUTH_CREDENTIAL_MEMBERS.some((m) => Object.hasOwn(v, m) && v[m] !== null && v[m] !== undefined);
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
/** Whether `v` is, or holds at any depth (arrays included), an ADK
|
|
1438
|
-
* AuthCredential. Iterative and cycle-safe over the raw native value; a value
|
|
1439
|
-
* that cannot be walked counts as holding one, so this never throws. */
|
|
1440
|
-
function holdsAuthCredential(v: unknown): boolean {
|
|
1441
|
-
return holdsObject(v, isAuthCredentialObject);
|
|
1442
|
-
}
|
|
1443
|
-
|
|
1444
|
-
/** Whether `v` is, or holds at any depth (arrays included), an object `match`
|
|
1445
|
-
* accepts. Iterative and cycle-safe over the raw native value; a value that
|
|
1446
|
-
* cannot be walked counts as holding one, so this never throws. */
|
|
1447
|
-
function holdsObject(v: unknown, match: (o: { readonly [k: string]: unknown }) => boolean): boolean {
|
|
1448
|
-
try {
|
|
1449
|
-
const seen = new Set<object>();
|
|
1450
|
-
const stack: unknown[] = [v];
|
|
1451
|
-
while (stack.length > 0) {
|
|
1452
|
-
const x = stack.pop();
|
|
1453
|
-
if (x === null || typeof x !== "object" || seen.has(x)) continue;
|
|
1454
|
-
seen.add(x);
|
|
1455
|
-
if (Array.isArray(x)) {
|
|
1456
|
-
for (const y of x) stack.push(y);
|
|
1457
|
-
} else if (isObjectRecord(x)) {
|
|
1458
|
-
if (match(x)) return true;
|
|
1459
|
-
for (const k of Object.keys(x)) stack.push(x[k]);
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
return false;
|
|
1463
|
-
} catch {
|
|
1464
|
-
return true;
|
|
1465
|
-
}
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
/** The state map ADK yields, minus its "temp:" entries and every entry that
|
|
1469
|
-
* holds an ADK AuthCredential, in the original key order. A map with none of
|
|
1470
|
-
* those is carried exactly as before. When entries were omitted, a remaining
|
|
1471
|
-
* entry that is not JSON is dropped rather than thrown on, since a throw would
|
|
1472
|
-
* hand the raw native event to the host's error path. A value that is not a
|
|
1473
|
-
* map is carried as before, or as {} if it holds a credential. */
|
|
1474
|
-
// From push(), an entry whose value is not JSON (ADK allows state.set(k,
|
|
1475
|
-
// undefined)) never reaches here: the entry conversion drops it, as JSON
|
|
1476
|
-
// serialization does. Under a per-key fold the fold then keeps its prior value
|
|
1477
|
-
// for that key while ADK holds undefined (read as absent), which is accepted
|
|
1478
|
-
// residue.
|
|
1479
|
-
function scrubStateMap(raw: unknown): JsonValue {
|
|
1480
|
-
if (!isObjectRecord(raw)) return holdsAuthCredential(raw) ? {} : JsonValue.parse(raw);
|
|
1481
|
-
const keys = Object.keys(raw);
|
|
1482
|
-
const omitted = keys.map((k) => k.startsWith(ADK_TEMP_STATE_PREFIX) || holdsAuthCredential(raw[k]));
|
|
1483
|
-
if (!omitted.includes(true)) return JsonValue.parse(raw);
|
|
1484
|
-
const kept: [string, JsonValue][] = [];
|
|
1485
|
-
keys.forEach((k, i) => {
|
|
1486
|
-
if (omitted[i] === true || isReservedMapKey(k)) return;
|
|
1487
|
-
const parsed = JsonValue.safeParse(raw[k]);
|
|
1488
|
-
if (parsed.success) kept.push([k, parsed.data]);
|
|
1489
|
-
});
|
|
1490
|
-
return Object.fromEntries(kept);
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
/** The ADK AuthConfig reduced to its non-secret members ({} for a non-object). */
|
|
1494
|
-
function scrubAdkAuthConfig(native: JsonValue): JsonValue {
|
|
1495
|
-
return pickAllowed(native, AUTH_CONFIG_ALLOW) ?? {};
|
|
1496
|
-
}
|
|
1497
|
-
|
|
1498
|
-
/** A reserved-credential functionResponse (the client's answer) scrubbed the
|
|
1499
|
-
* same way; undefined when the response is not an object. */
|
|
1500
|
-
function scrubbedResponse(response: unknown): { readonly [k: string]: JsonValue } | undefined {
|
|
1501
|
-
if (!isJsonObject(response)) return undefined;
|
|
1502
|
-
const scrubbed = scrubAdkAuthConfig(response);
|
|
1503
|
-
return isJsonObject(scrubbed) ? scrubbed : undefined;
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
// ─── provider-raw carries of node data ───────────────────────────────────────
|
|
1507
|
-
// A Workflow event's `output` and `actions.agentState` ride verbatim in
|
|
1508
|
-
// provider-raw. Inside them, each ADK AuthCredential (detected as for shared
|
|
1509
|
-
// state) is reduced to its allowlisted members, and each response named
|
|
1510
|
-
// adk_request_credential (matched by that name at any depth, never by id)
|
|
1511
|
-
// keeps only its id, its name and the reserved-credential answer's
|
|
1512
|
-
// allowlisted response, so an untyped reply becomes {}. Every other member
|
|
1513
|
-
// rides unchanged. A value with neither is parsed exactly as before; a value
|
|
1514
|
-
// that cannot be walked or reduced is omitted, never thrown on.
|
|
1515
|
-
|
|
1516
|
-
/** The native as plain JSON, converted node by node with JSON semantics: an
|
|
1517
|
-
* Error becomes {name, message, ...its own enumerable members} without its
|
|
1518
|
-
* stack, an undefined, function or symbol member is dropped (null inside an array), a
|
|
1519
|
-
* non-finite number becomes null, a value with toJSON (a Date) is read
|
|
1520
|
-
* through it, a BigInt becomes its decimal string, a node that repeats one of
|
|
1521
|
-
* its own ancestors becomes "[Circular]", and a member whose read throws is
|
|
1522
|
-
* dropped. Shared references that are not cycles are copied, as
|
|
1523
|
-
* JSON.stringify copies them. A JSON native comes back structurally identical,
|
|
1524
|
-
* own keys and their order included. `undefined` when nothing serializable
|
|
1525
|
-
* remains, or the value is too deep to walk. Never throws. */
|
|
1526
|
-
function asWireJson(native: unknown): JsonValue | undefined {
|
|
1527
|
-
const ancestors = new Set<object>();
|
|
1528
|
-
const convert = (v: unknown, key: string): JsonValue | undefined => {
|
|
1529
|
-
if (v === null || typeof v === "string" || typeof v === "boolean") return v;
|
|
1530
|
-
if (typeof v === "number") return Number.isFinite(v) ? v : null;
|
|
1531
|
-
if (typeof v === "bigint") return v.toString();
|
|
1532
|
-
if (typeof v !== "object") return undefined;
|
|
1533
|
-
if (ancestors.has(v)) return "[Circular]";
|
|
1534
|
-
let toJSON: unknown;
|
|
1535
|
-
try {
|
|
1536
|
-
toJSON = Reflect.get(v, "toJSON");
|
|
1537
|
-
} catch {
|
|
1538
|
-
return undefined;
|
|
1539
|
-
}
|
|
1540
|
-
if (typeof toJSON === "function") {
|
|
1541
|
-
let replaced: unknown;
|
|
1542
|
-
try {
|
|
1543
|
-
replaced = Reflect.apply(toJSON, v, [key]);
|
|
1544
|
-
} catch {
|
|
1545
|
-
return undefined;
|
|
1546
|
-
}
|
|
1547
|
-
if (replaced !== v) {
|
|
1548
|
-
ancestors.add(v);
|
|
1549
|
-
try {
|
|
1550
|
-
return convert(replaced, key);
|
|
1551
|
-
} finally {
|
|
1552
|
-
ancestors.delete(v);
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
ancestors.add(v);
|
|
1557
|
-
try {
|
|
1558
|
-
if (Array.isArray(v)) return v.map((x, i) => convert(x, String(i)) ?? null);
|
|
1559
|
-
const out: { [k: string]: JsonValue } = {};
|
|
1560
|
-
if (v instanceof Error) {
|
|
1561
|
-
// An Error's name and message are not own enumerable members, so JSON
|
|
1562
|
-
// would drop them; they are read explicitly. Its stack never rides.
|
|
1563
|
-
for (const k of ["name", "message"]) {
|
|
1564
|
-
let member: unknown;
|
|
1565
|
-
try {
|
|
1566
|
-
member = Reflect.get(v, k);
|
|
1567
|
-
} catch {
|
|
1568
|
-
continue;
|
|
1569
|
-
}
|
|
1570
|
-
const converted = convert(member, k);
|
|
1571
|
-
if (converted !== undefined)
|
|
1572
|
-
Object.defineProperty(out, k, { value: converted, enumerable: true, writable: true, configurable: true });
|
|
1573
|
-
}
|
|
1574
|
-
}
|
|
1575
|
-
for (const k of Object.keys(v)) {
|
|
1576
|
-
if (k === "stack" && v instanceof Error) continue;
|
|
1577
|
-
let member: unknown;
|
|
1578
|
-
try {
|
|
1579
|
-
member = Reflect.get(v, k);
|
|
1580
|
-
} catch {
|
|
1581
|
-
continue;
|
|
1582
|
-
}
|
|
1583
|
-
const converted = convert(member, k);
|
|
1584
|
-
// defineProperty keeps an own key exactly as JSON.parse would create it.
|
|
1585
|
-
if (converted !== undefined)
|
|
1586
|
-
Object.defineProperty(out, k, { value: converted, enumerable: true, writable: true, configurable: true });
|
|
1587
|
-
}
|
|
1588
|
-
return out;
|
|
1589
|
-
} finally {
|
|
1590
|
-
ancestors.delete(v);
|
|
1591
|
-
}
|
|
1592
|
-
};
|
|
1593
|
-
try {
|
|
1594
|
-
return convert(native, "");
|
|
1595
|
-
} catch {
|
|
1596
|
-
return undefined;
|
|
1597
|
-
}
|
|
1598
|
-
}
|
|
1599
|
-
|
|
1600
|
-
/** A response named adk_request_credential (a functionResponse object). */
|
|
1601
|
-
function isCredentialRequestResponse(v: { readonly [k: string]: unknown }): boolean {
|
|
1602
|
-
return v["name"] === ADK_REQUEST_CREDENTIAL && Object.hasOwn(v, "name") && Object.hasOwn(v, "response");
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
/** One JSON value with every credential object and credential-request
|
|
1606
|
-
* response reduced (see above); recursion stops at a reduced unit. */
|
|
1607
|
-
function reduceCredentialCarry(v: JsonValue): JsonValue {
|
|
1608
|
-
if (Array.isArray(v)) return v.map(reduceCredentialCarry);
|
|
1609
|
-
if (!isJsonObject(v)) return v;
|
|
1610
|
-
if (isAuthCredentialObject(v)) return pickAllowed(v, AUTH_CREDENTIAL_ALLOW) ?? {};
|
|
1611
|
-
if (isCredentialRequestResponse(v))
|
|
1612
|
-
return pickAllowed(v, { id: true, name: true, response: (r) => scrubbedResponse(r) }) ?? {};
|
|
1613
|
-
return Object.fromEntries(
|
|
1614
|
-
Object.entries(v)
|
|
1615
|
-
.filter(([k]) => !isReservedMapKey(k))
|
|
1616
|
-
.map(([k, x]): [string, JsonValue] => [k, reduceCredentialCarry(x)]),
|
|
1617
|
-
);
|
|
1618
|
-
}
|
|
1619
|
-
|
|
1620
|
-
/** JSON with object keys in sorted order: "did the reduction change it"
|
|
1621
|
-
* compares members, not the order an allowlist writes them in. */
|
|
1622
|
-
function canonicalJson(v: JsonValue): string {
|
|
1623
|
-
if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;
|
|
1624
|
-
if (!isJsonObject(v)) return JSON.stringify(v);
|
|
1625
|
-
return `{${Object.keys(v)
|
|
1626
|
-
.sort()
|
|
1627
|
-
.map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
|
|
1628
|
-
.join(",")}}`;
|
|
1629
|
-
}
|
|
1630
|
-
|
|
1631
|
-
/** A node-data value for a provider-raw carry. `changed` says whether the
|
|
1632
|
-
* reduction altered it; `undefined` omits the unit. */
|
|
1633
|
-
function carryNodeValue(raw: unknown): { value: JsonValue; changed: boolean } | undefined {
|
|
1634
|
-
if (!holdsAuthCredential(raw) && !holdsObject(raw, isCredentialRequestResponse))
|
|
1635
|
-
return { value: JsonValue.parse(raw), changed: false };
|
|
1636
|
-
try {
|
|
1637
|
-
const before = JsonValue.parse(JSON.parse(JSON.stringify(raw)));
|
|
1638
|
-
const value = reduceCredentialCarry(before);
|
|
1639
|
-
return { value, changed: canonicalJson(value) !== canonicalJson(before) };
|
|
1640
|
-
} catch {
|
|
1641
|
-
return undefined;
|
|
1642
|
-
}
|
|
1643
|
-
}
|
|
1644
|
-
|
|
1645
|
-
/** JSON.stringify of a raw `output` whose node-data reduction changed or
|
|
1646
|
-
* omitted it: the text ADK renders from that output. `undefined` otherwise
|
|
1647
|
-
* (including a string output, which ADK renders as itself). */
|
|
1648
|
-
function changedOutputRendering(output: unknown): string | undefined {
|
|
1649
|
-
if (output === undefined || output === null || typeof output !== "object") return undefined;
|
|
1650
|
-
// Detection first, so an output holding neither is never parsed here.
|
|
1651
|
-
if (!holdsAuthCredential(output) && !holdsObject(output, isCredentialRequestResponse)) return undefined;
|
|
1652
|
-
const carried = carryNodeValue(output);
|
|
1653
|
-
if (carried !== undefined && !carried.changed) return undefined;
|
|
1654
|
-
try {
|
|
1655
|
-
const rendered: unknown = JSON.stringify(output);
|
|
1656
|
-
return typeof rendered === "string" ? rendered : undefined;
|
|
1657
|
-
} catch {
|
|
1658
|
-
return undefined;
|
|
1659
|
-
}
|
|
1660
|
-
}
|
|
1661
|
-
|
|
1662
|
-
/** The reserved credential call's args: its id, its message and the scrubbed
|
|
1663
|
-
* AuthConfig. Nothing else is forwarded. */
|
|
1664
|
-
function scrubCredentialCallArgs(args: JsonValue): JsonValue {
|
|
1665
|
-
return (
|
|
1666
|
-
pickAllowed(args, {
|
|
1667
|
-
functionCallId: true,
|
|
1668
|
-
message: true,
|
|
1669
|
-
authConfig: (v) => scrubAdkAuthConfig(v),
|
|
1670
|
-
}) ?? {}
|
|
1671
|
-
);
|
|
1672
|
-
}
|
|
1673
|
-
|
|
1674
|
-
function adkAuthConfigView(native: JsonValue): AgAuthConfig | undefined {
|
|
1675
|
-
if (!isJsonObject(native)) return undefined;
|
|
1676
|
-
const authScheme = native["authScheme"];
|
|
1677
|
-
const scheme = stringMember(authScheme, "type");
|
|
1678
|
-
if (scheme === undefined || !isJsonObject(authScheme)) return undefined;
|
|
1679
|
-
let authorizationUrl: string | undefined;
|
|
1680
|
-
let tokenUrl: string | undefined;
|
|
1681
|
-
let scopes: string[] | undefined;
|
|
1682
|
-
if ("authorizationEndpoint" in authScheme) {
|
|
1683
|
-
authorizationUrl = stringMember(authScheme, "authorizationEndpoint");
|
|
1684
|
-
tokenUrl = stringMember(authScheme, "tokenEndpoint");
|
|
1685
|
-
const s = authScheme["scopes"];
|
|
1686
|
-
if (Array.isArray(s)) scopes = s.filter((x): x is string => typeof x === "string");
|
|
1687
|
-
} else if (scheme === "oauth2") {
|
|
1688
|
-
const flows = authScheme["flows"];
|
|
1689
|
-
const flow = isJsonObject(flows)
|
|
1690
|
-
? [flows["implicit"], flows["authorizationCode"], flows["clientCredentials"], flows["password"]].find(
|
|
1691
|
-
isJsonObject,
|
|
1692
|
-
)
|
|
1693
|
-
: undefined;
|
|
1694
|
-
if (flow !== undefined) {
|
|
1695
|
-
authorizationUrl = stringMember(flow, "authorizationUrl");
|
|
1696
|
-
tokenUrl = stringMember(flow, "tokenUrl");
|
|
1697
|
-
const s = flow["scopes"];
|
|
1698
|
-
if (isJsonObject(s)) scopes = Object.keys(s);
|
|
1699
|
-
}
|
|
1700
|
-
}
|
|
1701
|
-
const raw = native["rawAuthCredential"];
|
|
1702
|
-
const oauth2 = isJsonObject(raw) ? raw["oauth2"] : undefined;
|
|
1703
|
-
const clientId = stringMember(oauth2, "clientId");
|
|
1704
|
-
const audience = stringMember(oauth2, "audience");
|
|
1705
|
-
return {
|
|
1706
|
-
scheme,
|
|
1707
|
-
...(scopes !== undefined ? { scopes } : {}),
|
|
1708
|
-
...(authorizationUrl !== undefined ? { authorizationUrl } : {}),
|
|
1709
|
-
...(tokenUrl !== undefined ? { tokenUrl } : {}),
|
|
1710
|
-
...(clientId !== undefined ? { clientId } : {}),
|
|
1711
|
-
...(audience !== undefined ? { audience } : {}),
|
|
1712
|
-
};
|
|
1713
|
-
}
|
|
1714
1431
|
|
|
1715
1432
|
/** Append `ask` to the turn's pending-asks list (creating it on first use).
|
|
1716
1433
|
* Preserves emission order — asks accumulate in the order their originating
|
|
@@ -1731,9 +1448,8 @@ function driveAdkTopLevel(
|
|
|
1731
1448
|
event: AdkEvent,
|
|
1732
1449
|
messageId: string,
|
|
1733
1450
|
turnId: string,
|
|
1734
|
-
closedTurns: Set<string>,
|
|
1735
1451
|
pendingAsks: Map<string, AgPausedAsk[]>,
|
|
1736
|
-
|
|
1452
|
+
reserved: ReservedAskState
|
|
1737
1453
|
): void {
|
|
1738
1454
|
// typeof: a JSON-null transcription text is absent (null guard; it rode the
|
|
1739
1455
|
// text block as `null`, which the schema rejects).
|
|
@@ -1752,15 +1468,8 @@ function driveAdkTopLevel(
|
|
|
1752
1468
|
});
|
|
1753
1469
|
}
|
|
1754
1470
|
|
|
1755
|
-
//
|
|
1756
|
-
//
|
|
1757
|
-
// this, `maybeCloseTurn`'s is_final_response path or `flush()` would later
|
|
1758
|
-
// fabricate a success `turn.done` for a turn that already aborted — the
|
|
1759
|
-
// self-contradiction the audit found.
|
|
1760
|
-
if (event.interrupted === true) {
|
|
1761
|
-
a.emit({ type: "turn.abort", reason: "interrupted" });
|
|
1762
|
-
closedTurns.add(turnId);
|
|
1763
|
-
}
|
|
1471
|
+
// `interrupted` → turn.abort is closed in drive(), after this event's own
|
|
1472
|
+
// content and carries (see closeInterrupted), never here mid-event.
|
|
1764
1473
|
|
|
1765
1474
|
// ── promptFeedback → prompt.blocked ──
|
|
1766
1475
|
if (event.promptFeedback?.blockReason !== undefined) {
|
|
@@ -1806,39 +1515,39 @@ function driveAdkTopLevel(
|
|
|
1806
1515
|
}
|
|
1807
1516
|
}
|
|
1808
1517
|
|
|
1809
|
-
// ── ADK
|
|
1810
|
-
//
|
|
1811
|
-
//
|
|
1812
|
-
// the
|
|
1813
|
-
//
|
|
1814
|
-
//
|
|
1815
|
-
//
|
|
1816
|
-
//
|
|
1817
|
-
//
|
|
1818
|
-
//
|
|
1518
|
+
// ── ADK pause family → hitl.ask (SPEC §8.0 item 26, draft.4; R&D item 6) ──
|
|
1519
|
+
// An ADK pause is a functionCall named adk_request_input,
|
|
1520
|
+
// adk_request_credential or adk_request_confirmation. Each yields ONE ask:
|
|
1521
|
+
// toolCallId = the reserved call's id (the id ADK accepts as the answer),
|
|
1522
|
+
// resumeBinding "id", and the ORIGINAL tool-call id (when the call names
|
|
1523
|
+
// one) in metadata.originalFunctionCallId. When items 12/18 surface the
|
|
1524
|
+
// same request (actions keyed by the original id), the reserved call's ask is
|
|
1525
|
+
// the one: the original id is recorded, and those loops skip it. On the real
|
|
1526
|
+
// engine the reserved call arrives before, or on the same event as, those
|
|
1527
|
+
// actions. Deduped by id across the partial/aggregate re-send. The reserved
|
|
1528
|
+
// call's own tool.start still opens (suppressing it is an unwalked decision).
|
|
1819
1529
|
if (event.partial !== true) {
|
|
1820
1530
|
for (const part of event.content?.parts ?? []) {
|
|
1821
1531
|
const fc = part.functionCall;
|
|
1822
|
-
if (!isJsonObject(fc)
|
|
1532
|
+
if (!isJsonObject(fc)) continue;
|
|
1533
|
+
const name = fc["name"];
|
|
1534
|
+
if (name !== ADK_REQUEST_INPUT && name !== ADK_REQUEST_CREDENTIAL && name !== ADK_REQUEST_CONFIRMATION)
|
|
1535
|
+
continue;
|
|
1823
1536
|
const callId = stringMember(fc, "id");
|
|
1824
|
-
if (callId === undefined || callId.length === 0 ||
|
|
1825
|
-
|
|
1537
|
+
if (callId === undefined || callId.length === 0 || reserved.asked.has(callId)) continue;
|
|
1538
|
+
reserved.asked.add(callId);
|
|
1826
1539
|
const args = isJsonObject(fc["args"]) ? fc["args"] : {};
|
|
1827
|
-
const
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
toolCallId: callId,
|
|
1834
|
-
...(message !== undefined ? { message } : {}),
|
|
1835
|
-
...(isJsonObject(schema) ? { schema } : {}),
|
|
1836
|
-
...(payload !== undefined ? { metadata: { payload } } : {}),
|
|
1837
|
-
};
|
|
1540
|
+
const { ask, originalId } = reservedCallAsk(name, callId, args);
|
|
1541
|
+
if (originalId !== undefined) {
|
|
1542
|
+
const originals = reserved.originalsByTurn.get(turnId) ?? new Set<string>();
|
|
1543
|
+
originals.add(originalId);
|
|
1544
|
+
reserved.originalsByTurn.set(turnId, originals);
|
|
1545
|
+
}
|
|
1838
1546
|
a.emit({ type: "hitl.ask", ...ask });
|
|
1839
1547
|
trackPendingAsk(pendingAsks, turnId, ask);
|
|
1840
1548
|
}
|
|
1841
1549
|
}
|
|
1550
|
+
const askedOriginals = reserved.originalsByTurn.get(turnId);
|
|
1842
1551
|
|
|
1843
1552
|
// ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
|
|
1844
1553
|
const actions = event.actions;
|
|
@@ -1850,15 +1559,17 @@ function driveAdkTopLevel(
|
|
|
1850
1559
|
if (actions.requestedAuthConfigs !== undefined) {
|
|
1851
1560
|
// ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
|
|
1852
1561
|
// `authConfig` is the flat AgAuthConfig VIEW derived by
|
|
1853
|
-
// `adkAuthConfigView` (absent when no string scheme exists)
|
|
1854
|
-
//
|
|
1855
|
-
//
|
|
1856
|
-
//
|
|
1857
|
-
// ask fields are tracked in `pendingAsks`: if this
|
|
1858
|
-
// event turns out to be THIS event (or a later one for
|
|
1859
|
-
// `maybeCloseTurn` folds them into
|
|
1860
|
-
// instead of fabricating success
|
|
1562
|
+
// `adkAuthConfigView` (absent when no string scheme exists), and
|
|
1563
|
+
// `metadata.authConfig` carries the native AuthConfig through the
|
|
1564
|
+
// allowlist (scrubAdkAuthConfig). A request the reserved
|
|
1565
|
+
// adk_request_credential call already asked for (item 26) yields no
|
|
1566
|
+
// second ask. The SAME ask fields are tracked in `pendingAsks`: if this
|
|
1567
|
+
// turn's close-path event turns out to be THIS event (or a later one for
|
|
1568
|
+
// the same turnId), `maybeCloseTurn` folds them into
|
|
1569
|
+
// `turn.done.outcome.paused.asks[]` instead of fabricating success
|
|
1570
|
+
// (audit M26).
|
|
1861
1571
|
for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
|
|
1572
|
+
if (askedOriginals?.has(callId) === true) continue;
|
|
1862
1573
|
const view = adkAuthConfigView(authConfig);
|
|
1863
1574
|
const ask: AgPausedAsk = {
|
|
1864
1575
|
askId: `auth_${callId}`,
|
|
@@ -1876,6 +1587,8 @@ function driveAdkTopLevel(
|
|
|
1876
1587
|
// `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
|
|
1877
1588
|
// 18). Tracked in `pendingAsks` for the same paused-close fold as above.
|
|
1878
1589
|
for (const [callId, conf] of Object.entries(actions.requestedToolConfirmations)) {
|
|
1590
|
+
// Asked already by the reserved adk_request_confirmation call (item 26).
|
|
1591
|
+
if (askedOriginals?.has(callId) === true) continue;
|
|
1879
1592
|
const metadata: { [k: string]: JsonValue } = {};
|
|
1880
1593
|
if (conf.confirmed !== undefined) metadata["confirmed"] = conf.confirmed;
|
|
1881
1594
|
if (conf.payload !== undefined) metadata["payload"] = JsonValue.parse(conf.payload);
|
|
@@ -1912,7 +1625,7 @@ function driveAdkTopLevel(
|
|
|
1912
1625
|
a.contentBlock(messageId, {
|
|
1913
1626
|
type: "provider-raw",
|
|
1914
1627
|
vendor: "google",
|
|
1915
|
-
raw: JsonValue.parse(unmappedActions),
|
|
1628
|
+
raw: reduceCarried(JsonValue.parse(unmappedActions)),
|
|
1916
1629
|
});
|
|
1917
1630
|
}
|
|
1918
1631
|
}
|
|
@@ -1987,13 +1700,134 @@ function driveAdkTopLevel(
|
|
|
1987
1700
|
a.contentBlock(messageId, {
|
|
1988
1701
|
type: "provider-raw",
|
|
1989
1702
|
vendor: "google",
|
|
1990
|
-
raw: JsonValue.parse(unmappedEvent),
|
|
1703
|
+
raw: reduceCarried(JsonValue.parse(unmappedEvent)),
|
|
1991
1704
|
});
|
|
1992
1705
|
}
|
|
1993
1706
|
}
|
|
1994
1707
|
|
|
1995
1708
|
// ─── stateful factory: createAdkNormalizer ────────────────────────────────────
|
|
1996
|
-
|
|
1709
|
+
/** Options for {@link createAdkNormalizer}. */
|
|
1710
|
+
export interface AdkNormalizerOptions {
|
|
1711
|
+
/**
|
|
1712
|
+
* Opt in to SPEC §8.0 host obligation 4 (draft.4): the host feeds
|
|
1713
|
+
* `{ type: "__host_complete__" }` after the ADK run returned NORMALLY (never
|
|
1714
|
+
* after a cancel, an abort signal or a thrown error), before `flush()`.
|
|
1715
|
+
* Then a success close waits for that event (so a Workflow, a
|
|
1716
|
+
* SequentialAgent or after-agent callback content can follow a node's final
|
|
1717
|
+
* text), and on it each still-open turn closes: `paused` if an ask is
|
|
1718
|
+
* pending, left to `flush()` if a non-HITL long-running call is unanswered,
|
|
1719
|
+
* else `success`. Default off: the step-1 behaviour.
|
|
1720
|
+
*/
|
|
1721
|
+
hostCompletion?: boolean;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/** The facet-local host-completion native (§8.0 host obligation 4). */
|
|
1725
|
+
export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
|
|
1726
|
+
|
|
1727
|
+
/**
|
|
1728
|
+
* SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
|
|
1729
|
+
* the stream (e.g. its LLM-call limit), the host catches it and pushes
|
|
1730
|
+
* `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
|
|
1731
|
+
* open turn closes `turn.error` with that code and message. The shape matches the OpenAI
|
|
1732
|
+
* facet's sentinel. A host may build it from the caught Error itself
|
|
1733
|
+
* (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
|
|
1734
|
+
* read from the raw native, so the Error's own message is kept.
|
|
1735
|
+
*/
|
|
1736
|
+
export const ADK_HOST_ERROR_TYPE = "__host_error__";
|
|
1737
|
+
|
|
1738
|
+
interface AdkHostError {
|
|
1739
|
+
code: string;
|
|
1740
|
+
message: string;
|
|
1741
|
+
usage?: AgUsage;
|
|
1742
|
+
/** The invoke's ADK invocationId, when the host has it: used to name a
|
|
1743
|
+
* fresh terminal turn if the error arrives before any event. */
|
|
1744
|
+
invocationId?: string;
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
/** The host-error sentinel, read from the RAW native (an Error's message is
|
|
1748
|
+
* not an own enumerable member, so a JSON copy would lose it). A usage that is
|
|
1749
|
+
* not a valid AgUsage is dropped. Never throws. */
|
|
1750
|
+
function hostErrorOf(raw: unknown): AdkHostError | undefined {
|
|
1751
|
+
if (raw === null || typeof raw !== "object") return undefined;
|
|
1752
|
+
try {
|
|
1753
|
+
if (Reflect.get(raw, "type") !== ADK_HOST_ERROR_TYPE) return undefined;
|
|
1754
|
+
const code: unknown = Reflect.get(raw, "code");
|
|
1755
|
+
const message: unknown = Reflect.get(raw, "message");
|
|
1756
|
+
if (typeof code !== "string" || typeof message !== "string") return undefined;
|
|
1757
|
+
const usageRaw: unknown = Reflect.get(raw, "usage");
|
|
1758
|
+
const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
|
|
1759
|
+
const invocationId: unknown = Reflect.get(raw, "invocationId");
|
|
1760
|
+
return {
|
|
1761
|
+
code,
|
|
1762
|
+
message,
|
|
1763
|
+
...(usage?.success === true ? { usage: usage.data } : {}),
|
|
1764
|
+
...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
|
|
1765
|
+
};
|
|
1766
|
+
} catch {
|
|
1767
|
+
return undefined;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
/** Exactly `{ type: "__host_complete__" }` (one key), as recorded by a capture harness. */
|
|
1772
|
+
function isHostCompleteNative(v: JsonValue): boolean {
|
|
1773
|
+
return isJsonObject(v) && v["type"] === ADK_HOST_COMPLETE_TYPE && Object.keys(v).length === 1;
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
/**
|
|
1777
|
+
* The google-adk Normalizer: the inner, deterministic normalizer below wrapped
|
|
1778
|
+
* in core's withAtomicPush (the fleet guard ruling). Every push() is atomic:
|
|
1779
|
+
* - The native is read once as plain JSON through core's toJsonValueSafe, so a
|
|
1780
|
+
* host may push the live Event objects ADK yields (undefined members, a
|
|
1781
|
+
* Date, an Error, a cycle) and they map exactly like the recorded corpus.
|
|
1782
|
+
* - If mapping one native throws (an event whose envelope is valid but whose
|
|
1783
|
+
* inner members have unexpected types), its partial batch is discarded
|
|
1784
|
+
* without consuming seq, the inner is rebuilt by re-driving every native
|
|
1785
|
+
* accepted so far (the inner never reads the clock or randomness; ids come
|
|
1786
|
+
* from invocationId and per-invoke ordinals, and the one random stem, for a
|
|
1787
|
+
* host error before any event, is drawn outside the inner and kept), and
|
|
1788
|
+
* ONE core `error {message:
|
|
1789
|
+
* "normalizer error", code: <constructor name>}` takes the next seq, with no
|
|
1790
|
+
* payload and no message text.
|
|
1791
|
+
* - flush() is guarded the same way; the wrapper closes what the consumer saw
|
|
1792
|
+
* open itself, without calling the inner again.
|
|
1793
|
+
* So push() never throws (SPEC §8.0), and no facet state believes a turn,
|
|
1794
|
+
* message or block is open that never reached the wire.
|
|
1795
|
+
*/
|
|
1796
|
+
export function createAdkNormalizer(options: AdkNormalizerOptions = {}): Normalizer {
|
|
1797
|
+
// A per-instance id stem, drawn lazily and only on the paths that need it (an
|
|
1798
|
+
// event with neither invocationId nor id; a host error before any event,
|
|
1799
|
+
// with no invocationId on the sentinel). It lives OUTSIDE the inner, so a
|
|
1800
|
+
// rebuild re-drives to the same ids.
|
|
1801
|
+
const stem: IdStem = {};
|
|
1802
|
+
return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
/** Holds the lazily drawn per-instance id stem across inner rebuilds. */
|
|
1806
|
+
interface IdStem {
|
|
1807
|
+
value?: string;
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
/** A random per-instance stem; never called while a replay re-drives, since
|
|
1811
|
+
* the stem is drawn once and kept.
|
|
1812
|
+
*
|
|
1813
|
+
* The `Date.now` + `Math.random` fallback runs only when `crypto.randomUUID`
|
|
1814
|
+
* is absent, which cannot happen on Node >= 19 (a global `crypto`). It is the
|
|
1815
|
+
* facet's one read of the clock or a random source, and it is safe for
|
|
1816
|
+
* determinism: the stem is drawn outside the inner, once, and a
|
|
1817
|
+
* withAtomicPush rebuild reuses it, so the corpus legs that poison the clock
|
|
1818
|
+
* and randomness never reach this call. */
|
|
1819
|
+
function drawIdStem(): string {
|
|
1820
|
+
const cryptoObj: unknown = Reflect.get(globalThis, "crypto");
|
|
1821
|
+
const randomUUID: unknown = cryptoObj !== undefined && cryptoObj !== null ? Reflect.get(cryptoObj, "randomUUID") : undefined;
|
|
1822
|
+
if (typeof randomUUID === "function") {
|
|
1823
|
+
const id: unknown = Reflect.apply(randomUUID, cryptoObj, []);
|
|
1824
|
+
if (typeof id === "string") return id;
|
|
1825
|
+
}
|
|
1826
|
+
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
function createInnerAdkNormalizer(options: AdkNormalizerOptions, stem: IdStem): Normalizer {
|
|
1830
|
+
const hostCompletion = options.hostCompletion === true;
|
|
1997
1831
|
const a = new StreamAssembler();
|
|
1998
1832
|
const threadId = "google";
|
|
1999
1833
|
// §8.3 per-instance accumulator (replaces the module-level streamedText Map):
|
|
@@ -2018,8 +1852,19 @@ function createAdkInner(): AdkInner {
|
|
|
2018
1852
|
// (the is_final_response aggregate); the `flush()` truncation path never
|
|
2019
1853
|
// reads it — see the comment there.
|
|
2020
1854
|
const pendingAsks = new Map<string, AgPausedAsk[]>();
|
|
2021
|
-
//
|
|
2022
|
-
|
|
1855
|
+
// Pause-family bookkeeping (item 26): reserved-call ids already asked, and the
|
|
1856
|
+
// original tool-call ids their asks cover, per turn.
|
|
1857
|
+
const reserved: ReservedAskState = { asked: new Set(), originalsByTurn: new Map() };
|
|
1858
|
+
// Host obligation 4 (opt-in): a success close stashed until the sentinel, and
|
|
1859
|
+
// the non-HITL long-running calls still unanswered, per turn.
|
|
1860
|
+
const deferredClose = new Map<string, AdkEvent>();
|
|
1861
|
+
// Live barge-ins (`interrupted: true`, ADK's live aggregator) awaiting their
|
|
1862
|
+
// close. An interrupt on a PARTIAL text event is followed by ADK's full-text
|
|
1863
|
+
// aggregate of the same model turn (utils/live_connection_utils.js:175-178),
|
|
1864
|
+
// so the close waits for the next non-partial event of the turn, or for
|
|
1865
|
+
// flush() / host completion.
|
|
1866
|
+
const interruptPending = new Set<string>();
|
|
1867
|
+
const pendingLongRunning = new Map<string, Set<string>>();
|
|
2023
1868
|
const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
|
|
2024
1869
|
// Null-id call mint state (audit M47) — per-invoke ordinal counter + the
|
|
2025
1870
|
// content/name correlation maps; lives exactly as long as this Normalizer
|
|
@@ -2056,7 +1901,7 @@ function createAdkInner(): AdkInner {
|
|
|
2056
1901
|
if (accumulated !== undefined) usageByTurn.set(turnId, accumulated);
|
|
2057
1902
|
const parts = event.content?.parts ?? [];
|
|
2058
1903
|
const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
|
|
2059
|
-
const interrupted = event.interrupted === true;
|
|
1904
|
+
const interrupted = event.interrupted === true || interruptPending.has(turnId);
|
|
2060
1905
|
// ── The pause close (R&D item 6, step 1) ──
|
|
2061
1906
|
// SPEC §7 "the pause is the turn outcome" (SPEC.md:896): while an ask is
|
|
2062
1907
|
// pending, the event with which ADK ENDS the pause (isAdkPauseEnd) closes
|
|
@@ -2096,9 +1941,30 @@ function createAdkInner(): AdkInner {
|
|
|
2096
1941
|
// reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
|
|
2097
1942
|
// closes the turn as success. It is a per-EVENT test, never a latch
|
|
2098
1943
|
// (NodeTool puts nodeInfo into plain runs too). Error closes stay
|
|
2099
|
-
// immediate. A completed workflow
|
|
2100
|
-
//
|
|
1944
|
+
// immediate. A completed workflow closes success only on the host-completion
|
|
1945
|
+
// event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
|
|
1946
|
+
// it flushes turn.abort.
|
|
2101
1947
|
if (errorClose === undefined && event.nodeInfo !== undefined) return;
|
|
1948
|
+
// Host obligation 4 (opt-in): a SUCCESS close waits for the host-completion
|
|
1949
|
+
// event, because the run may not be over (a SequentialAgent's next agent,
|
|
1950
|
+
// after-agent callback content). The final response is stashed and closed
|
|
1951
|
+
// unchanged on the sentinel, so a stream ending here is byte-identical.
|
|
1952
|
+
// Error and paused closes stay immediate.
|
|
1953
|
+
if (hostCompletion && errorClose === undefined && !((pendingAsks.get(turnId)?.length ?? 0) > 0)) {
|
|
1954
|
+
deferredClose.set(turnId, event);
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
closeOnFinalResponse(event, turnId, messageId, errorClose);
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
/** The close on a final response: lossy-finish metadata, message.end, then
|
|
1961
|
+
* turn.error or turn.done (paused when asks are pending, else success). */
|
|
1962
|
+
function closeOnFinalResponse(
|
|
1963
|
+
event: AdkEvent,
|
|
1964
|
+
turnId: string,
|
|
1965
|
+
messageId: string,
|
|
1966
|
+
errorClose: { code: string; message: string } | undefined,
|
|
1967
|
+
): void {
|
|
2102
1968
|
closedTurns.add(turnId);
|
|
2103
1969
|
const rawFinish = event.finishReason ?? event.errorCode;
|
|
2104
1970
|
const finish = resolveFinishReason(rawFinish);
|
|
@@ -2140,14 +2006,113 @@ function createAdkInner(): AdkInner {
|
|
|
2140
2006
|
a.closeTurnDone(turnId, {
|
|
2141
2007
|
outcome: paused ? { type: "paused", asks } : { type: "success" },
|
|
2142
2008
|
finishReason: paused ? "paused" : finish.value,
|
|
2009
|
+
// draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
|
|
2010
|
+
// native value verbatim in turn.done.finishReasonRaw. That is the value
|
|
2011
|
+
// finishReason was mapped from: the wire finishReason, or for an
|
|
2012
|
+
// errorCode-only soft close the errorCode. A paused close's "paused" is
|
|
2013
|
+
// not a fallback, so it takes no companion. message.metadata's
|
|
2014
|
+
// rawFinishReason/rawErrorCode carry stays for one cohort.
|
|
2015
|
+
...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
|
|
2143
2016
|
...(usage !== undefined ? { usage } : {}),
|
|
2144
2017
|
...(safety !== undefined ? { safety } : {}),
|
|
2145
2018
|
});
|
|
2146
2019
|
}
|
|
2147
2020
|
}
|
|
2148
2021
|
|
|
2022
|
+
/** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
|
|
2023
|
+
* pending until its functionResponse arrives. */
|
|
2024
|
+
function trackLongRunning(event: AdkEvent, turnId: string): void {
|
|
2025
|
+
const longRunningIds = event.longRunningToolIds ?? [];
|
|
2026
|
+
const pending = pendingLongRunning.get(turnId) ?? new Set<string>();
|
|
2027
|
+
for (const part of event.content?.parts ?? []) {
|
|
2028
|
+
const callId = stringMember(part.functionCall, "id");
|
|
2029
|
+
if (callId !== undefined && longRunningIds.includes(callId)) pending.add(callId);
|
|
2030
|
+
const responseId = stringMember(part.functionResponse, "id");
|
|
2031
|
+
if (responseId !== undefined) pending.delete(responseId);
|
|
2032
|
+
}
|
|
2033
|
+
pendingLongRunning.set(turnId, pending);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
/** The host-completion event (SPEC §8.0 host obligation 4): the run returned
|
|
2037
|
+
* normally. Each still-open turn closes from push(): paused when an ask is
|
|
2038
|
+
* pending; left to flush() when a non-HITL long-running call is unanswered;
|
|
2039
|
+
* otherwise success (the stashed final response's close, or a plain success
|
|
2040
|
+
* close with the accumulated usage when the run ended on a non-final event,
|
|
2041
|
+
* e.g. a completed Workflow). */
|
|
2042
|
+
function hostComplete(): void {
|
|
2043
|
+
for (const turnId of openTurns) {
|
|
2044
|
+
if (closedTurns.has(turnId)) continue;
|
|
2045
|
+
if (interruptPending.has(turnId)) {
|
|
2046
|
+
closeInterrupted(turnId);
|
|
2047
|
+
continue;
|
|
2048
|
+
}
|
|
2049
|
+
const messageId = `msg_${turnId}`;
|
|
2050
|
+
const asks = pendingAsks.get(turnId);
|
|
2051
|
+
if (asks !== undefined && asks.length > 0) {
|
|
2052
|
+
closedTurns.add(turnId);
|
|
2053
|
+
const usage = mapUsage(usageByTurn.get(turnId));
|
|
2054
|
+
a.closeMessage(messageId);
|
|
2055
|
+
a.closeTurnDone(turnId, {
|
|
2056
|
+
outcome: { type: "paused", asks },
|
|
2057
|
+
finishReason: "paused",
|
|
2058
|
+
...(usage !== undefined ? { usage } : {}),
|
|
2059
|
+
});
|
|
2060
|
+
continue;
|
|
2061
|
+
}
|
|
2062
|
+
if ((pendingLongRunning.get(turnId)?.size ?? 0) > 0) continue;
|
|
2063
|
+
const stashed = deferredClose.get(turnId);
|
|
2064
|
+
if (stashed !== undefined) {
|
|
2065
|
+
closeOnFinalResponse(stashed, turnId, messageId, undefined);
|
|
2066
|
+
continue;
|
|
2067
|
+
}
|
|
2068
|
+
closedTurns.add(turnId);
|
|
2069
|
+
const usage = mapUsage(usageByTurn.get(turnId));
|
|
2070
|
+
a.closeMessage(messageId);
|
|
2071
|
+
a.closeTurnDone(turnId, {
|
|
2072
|
+
outcome: { type: "success" },
|
|
2073
|
+
finishReason: "stop",
|
|
2074
|
+
...(usage !== undefined ? { usage } : {}),
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
/** Host obligation 1: close every still-open turn, innermost first, as
|
|
2080
|
+
* turn.error with the sentinel's code and message (and its usage, else the
|
|
2081
|
+
* turn's accumulated usage). A success close stashed for the host-completion
|
|
2082
|
+
* signal never fires, since the turn is now closed: the run did not
|
|
2083
|
+
* complete. With no turn open, a fresh terminal turn carries the error, so
|
|
2084
|
+
* it is never start-less. */
|
|
2085
|
+
let hostErrorTurns = 0;
|
|
2086
|
+
// The first turn key this invoke drove (its ADK invocationId): the stem of a
|
|
2087
|
+
// fresh terminal turn's id, so the id is unique across the invokes a host
|
|
2088
|
+
// folds together, not only within this one.
|
|
2089
|
+
let firstKey: string | undefined;
|
|
2090
|
+
function hostError(err: AdkHostError): void {
|
|
2091
|
+
let closed = 0;
|
|
2092
|
+
for (const turnId of [...openTurns].reverse()) {
|
|
2093
|
+
if (closedTurns.has(turnId)) continue;
|
|
2094
|
+
closedTurns.add(turnId);
|
|
2095
|
+
const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
|
|
2096
|
+
a.closeMessage(`msg_${turnId}`);
|
|
2097
|
+
a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
|
|
2098
|
+
closed++;
|
|
2099
|
+
}
|
|
2100
|
+
if (closed > 0) return;
|
|
2101
|
+
const base = firstKey ?? err.invocationId ?? (stem.value ??= drawIdStem());
|
|
2102
|
+
const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
|
|
2103
|
+
const messageId = ensureOpen(turnId);
|
|
2104
|
+
closedTurns.add(turnId);
|
|
2105
|
+
a.closeMessage(messageId);
|
|
2106
|
+
a.closeTurnError(turnId, {
|
|
2107
|
+
message: err.message,
|
|
2108
|
+
code: err.code,
|
|
2109
|
+
...(err.usage !== undefined ? { usage: err.usage } : {}),
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2149
2113
|
function drive(event: AdkEvent): void {
|
|
2150
|
-
const key = turnKey(event)
|
|
2114
|
+
const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
|
|
2115
|
+
firstKey ??= key;
|
|
2151
2116
|
const turnId = `turn_${key}`;
|
|
2152
2117
|
const messageId = ensureOpen(turnId);
|
|
2153
2118
|
const parts = event.content?.parts ?? [];
|
|
@@ -2233,7 +2198,7 @@ function createAdkInner(): AdkInner {
|
|
|
2233
2198
|
return;
|
|
2234
2199
|
}
|
|
2235
2200
|
if (residualTail.length > 0) {
|
|
2236
|
-
const id = mintBlockId(blockIds,
|
|
2201
|
+
const id = mintBlockId(blockIds, "text");
|
|
2237
2202
|
a.textStart(id, messageId);
|
|
2238
2203
|
a.textDelta(id, messageId, residualTail);
|
|
2239
2204
|
a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
|
|
@@ -2276,14 +2241,49 @@ function createAdkInner(): AdkInner {
|
|
|
2276
2241
|
// aggregate never arrives simply die with the invoke's closure — bounded,
|
|
2277
2242
|
// per-invoke.
|
|
2278
2243
|
|
|
2279
|
-
|
|
2244
|
+
if (!isPartial) trackLongRunning(event, turnId);
|
|
2245
|
+
driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
|
|
2246
|
+
// A turn gets ONE terminal: an interrupt on a turn that already closed
|
|
2247
|
+
// (a second barge-in, or one after a success close) adds none.
|
|
2248
|
+
if (event.interrupted === true && !closedTurns.has(turnId)) interruptPending.add(turnId);
|
|
2280
2249
|
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
2250
|
+
if (!isPartial && interruptPending.has(turnId)) closeInterrupted(turnId);
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
/** interrupted → turn.abort, after the event's own content and carries and
|
|
2254
|
+
* after its message.end (INV-MSG: nothing of the turn follows its terminal).
|
|
2255
|
+
* The turn is marked closed in the facet's own bookkeeping too (audit M21),
|
|
2256
|
+
* so neither maybeCloseTurn nor flush() fabricates a later success. The
|
|
2257
|
+
* message.end carries the turn's accumulated usage, as flush()'s does. */
|
|
2258
|
+
function closeInterrupted(turnId: string): void {
|
|
2259
|
+
interruptPending.delete(turnId);
|
|
2260
|
+
closedTurns.add(turnId);
|
|
2261
|
+
a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
|
|
2262
|
+
a.emit({ type: "turn.abort", turnId, reason: "interrupted" });
|
|
2281
2263
|
}
|
|
2282
2264
|
|
|
2283
2265
|
return {
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2266
|
+
push(native: JsonValue): AgEvent[] {
|
|
2267
|
+
// withAtomicPush has already read the native as plain JSON (see
|
|
2268
|
+
// createAdkNormalizer). The host-error sentinel is checked first: an
|
|
2269
|
+
// Error-built one keeps its message, because core maps an Error to
|
|
2270
|
+
// {name, message, ...own enumerable}.
|
|
2271
|
+
const json = native;
|
|
2272
|
+
const hostErr = hostErrorOf(json);
|
|
2273
|
+
if (hostErr !== undefined) {
|
|
2274
|
+
// Like the completion sentinel below, a host<->facet contract input
|
|
2275
|
+
// (SPEC §8.0 host obligation 1), not a framework native.
|
|
2276
|
+
hostError(hostErr);
|
|
2277
|
+
return a.drain();
|
|
2278
|
+
}
|
|
2279
|
+
if (isHostCompleteNative(json)) {
|
|
2280
|
+
// The host-completion sentinel is a host<->facet contract input (SPEC
|
|
2281
|
+
// §8.0 host obligation 4), like obligation 1's `__host_error__`: NOT a
|
|
2282
|
+
// framework native. So §8.0's graceful-degradation rule ("MUST NOT
|
|
2283
|
+
// silently drop a native event") does not bind it. With the option OFF
|
|
2284
|
+
// it is ignored by design and never reaches the wire as
|
|
2285
|
+
// ext.google.unparsed.
|
|
2286
|
+
if (hostCompletion) hostComplete();
|
|
2287
2287
|
return a.drain();
|
|
2288
2288
|
}
|
|
2289
2289
|
if (!isAdkEvent(json)) {
|
|
@@ -2293,15 +2293,7 @@ function createAdkInner(): AdkInner {
|
|
|
2293
2293
|
drive(json);
|
|
2294
2294
|
return a.drain();
|
|
2295
2295
|
},
|
|
2296
|
-
|
|
2297
|
-
// A non-terminal core `error` whose code is only the thrown value's
|
|
2298
|
-
// constructor name (e.g. "TypeError"), with a fixed message and no
|
|
2299
|
-
// payload, so nothing from the native reaches it.
|
|
2300
|
-
const code = e instanceof Error ? e.constructor.name : typeof e;
|
|
2301
|
-
a.emit({ type: "error", message: "normalizer error", code });
|
|
2302
|
-
return a.drain();
|
|
2303
|
-
},
|
|
2304
|
-
flush(bare: boolean): AgEvent[] {
|
|
2296
|
+
flush(): AgEvent[] {
|
|
2305
2297
|
// Dangling open turns (interrupted stream before a final aggregate):
|
|
2306
2298
|
// close their message; the ENGINE flush closes the turn itself with
|
|
2307
2299
|
// turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
|
|
@@ -2314,87 +2306,17 @@ function createAdkInner(): AdkInner {
|
|
|
2314
2306
|
// (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
|
|
2315
2307
|
// Workflow invoke until the host completion signal exists, still reports
|
|
2316
2308
|
// the tokens it spent. There is never a turn.done here, so the usage
|
|
2317
|
-
// appears only once.
|
|
2318
|
-
// path, when reading it failed).
|
|
2309
|
+
// appears only once.
|
|
2319
2310
|
for (const turnId of openTurns) {
|
|
2320
|
-
if (
|
|
2321
|
-
|
|
2322
|
-
|
|
2311
|
+
if (closedTurns.has(turnId)) continue;
|
|
2312
|
+
if (interruptPending.has(turnId)) {
|
|
2313
|
+
closeInterrupted(turnId);
|
|
2314
|
+
continue;
|
|
2323
2315
|
}
|
|
2316
|
+
closedTurns.add(turnId);
|
|
2317
|
+
a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
|
|
2324
2318
|
}
|
|
2325
2319
|
return a.flush();
|
|
2326
2320
|
},
|
|
2327
2321
|
};
|
|
2328
2322
|
}
|
|
2329
|
-
|
|
2330
|
-
/** One invoke's facet state and assembler; driven only through
|
|
2331
|
-
* createAdkNormalizer, which keeps push() atomic. */
|
|
2332
|
-
interface AdkInner {
|
|
2333
|
-
/** Map one entry-converted native (`undefined`: nothing serializable).
|
|
2334
|
-
* May throw on an event whose inner members have unexpected types. */
|
|
2335
|
-
accept(json: JsonValue | undefined): AgEvent[];
|
|
2336
|
-
/** The last-resort report, at the next seq. */
|
|
2337
|
-
reportError(e: unknown): AgEvent[];
|
|
2338
|
-
/** End of stream; `bare` closes open messages without their usage. */
|
|
2339
|
-
flush(bare: boolean): AgEvent[];
|
|
2340
|
-
}
|
|
2341
|
-
|
|
2342
|
-
/**
|
|
2343
|
-
* The google-adk Normalizer. push() is atomic and never throws (SPEC §8.0):
|
|
2344
|
-
* the native is read once as plain JSON (asWireJson), then mapped. If mapping
|
|
2345
|
-
* throws (an event whose envelope is valid but whose inner members have
|
|
2346
|
-
* unexpected types), the partial batch is discarded, consuming no seq; the
|
|
2347
|
-
* facet is rebuilt by re-driving, silently, every native accepted so far (it
|
|
2348
|
-
* is deterministic: no clock, no randomness, ids from invocationId and
|
|
2349
|
-
* per-invoke ordinals); and one core `error` event is emitted at the next seq.
|
|
2350
|
-
* flush() is guarded the same way and then closes what is open without usage.
|
|
2351
|
-
* Costs: the journal holds a copy of every accepted native for the invoke's
|
|
2352
|
-
* life, and each failure re-drives the accepted prefix.
|
|
2353
|
-
*/
|
|
2354
|
-
export function createAdkNormalizer(): Normalizer {
|
|
2355
|
-
let inner = createAdkInner();
|
|
2356
|
-
const journal: (JsonValue | undefined)[] = [];
|
|
2357
|
-
const rebuild = (): void => {
|
|
2358
|
-
inner = createAdkInner();
|
|
2359
|
-
try {
|
|
2360
|
-
for (const entry of journal) inner.accept(entry);
|
|
2361
|
-
} catch {
|
|
2362
|
-
// Unreachable: each entry was accepted before by an identical facet.
|
|
2363
|
-
}
|
|
2364
|
-
};
|
|
2365
|
-
return {
|
|
2366
|
-
push(native: JsonValue): AgEvent[] {
|
|
2367
|
-
// A host may push the live object ADK yields (the README's usage), and
|
|
2368
|
-
// that can hold undefined members, a Date or another non-JSON value. The
|
|
2369
|
-
// native is read once as plain JSON (see asWireJson), so nothing below
|
|
2370
|
-
// parses a non-JSON value. A native that cannot be serialized at all is
|
|
2371
|
-
// reported without its content.
|
|
2372
|
-
const json = asWireJson(native);
|
|
2373
|
-
// The journal keeps its own copy, taken before mapping, so nothing the
|
|
2374
|
-
// mapping or the host does to the value can change a later re-drive.
|
|
2375
|
-
const entry = json === undefined ? undefined : copyJson(json);
|
|
2376
|
-
try {
|
|
2377
|
-
const out = inner.accept(json);
|
|
2378
|
-
journal.push(entry);
|
|
2379
|
-
return out;
|
|
2380
|
-
} catch (e) {
|
|
2381
|
-
rebuild();
|
|
2382
|
-
return inner.reportError(e);
|
|
2383
|
-
}
|
|
2384
|
-
},
|
|
2385
|
-
flush(): AgEvent[] {
|
|
2386
|
-
try {
|
|
2387
|
-
return inner.flush(false);
|
|
2388
|
-
} catch (e) {
|
|
2389
|
-
rebuild();
|
|
2390
|
-
return [...inner.reportError(e), ...inner.flush(true)];
|
|
2391
|
-
}
|
|
2392
|
-
},
|
|
2393
|
-
};
|
|
2394
|
-
}
|
|
2395
|
-
|
|
2396
|
-
/** A deep copy of a plain JSON value. */
|
|
2397
|
-
function copyJson(v: JsonValue): JsonValue {
|
|
2398
|
-
const copy: JsonValue = JSON.parse(JSON.stringify(v));
|
|
2399
|
-
return copy;
|
|
2400
|
-
}
|