@silverprotocol/google-adk 0.6.7 → 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 +53 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +456 -635
- 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 +528 -644
- 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,478 +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, 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
1414
|
|
|
1715
1415
|
/** Append `ask` to the turn's pending-asks list (creating it on first use).
|
|
1716
1416
|
* Preserves emission order — asks accumulate in the order their originating
|
|
@@ -1733,7 +1433,7 @@ function driveAdkTopLevel(
|
|
|
1733
1433
|
turnId: string,
|
|
1734
1434
|
closedTurns: Set<string>,
|
|
1735
1435
|
pendingAsks: Map<string, AgPausedAsk[]>,
|
|
1736
|
-
|
|
1436
|
+
reserved: ReservedAskState
|
|
1737
1437
|
): void {
|
|
1738
1438
|
// typeof: a JSON-null transcription text is absent (null guard; it rode the
|
|
1739
1439
|
// text block as `null`, which the schema rejects).
|
|
@@ -1806,39 +1506,39 @@ function driveAdkTopLevel(
|
|
|
1806
1506
|
}
|
|
1807
1507
|
}
|
|
1808
1508
|
|
|
1809
|
-
// ── ADK
|
|
1810
|
-
//
|
|
1811
|
-
//
|
|
1812
|
-
// the
|
|
1813
|
-
//
|
|
1814
|
-
//
|
|
1815
|
-
//
|
|
1816
|
-
//
|
|
1817
|
-
//
|
|
1818
|
-
//
|
|
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).
|
|
1819
1520
|
if (event.partial !== true) {
|
|
1820
1521
|
for (const part of event.content?.parts ?? []) {
|
|
1821
1522
|
const fc = part.functionCall;
|
|
1822
|
-
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;
|
|
1823
1527
|
const callId = stringMember(fc, "id");
|
|
1824
|
-
if (callId === undefined || callId.length === 0 ||
|
|
1825
|
-
|
|
1528
|
+
if (callId === undefined || callId.length === 0 || reserved.asked.has(callId)) continue;
|
|
1529
|
+
reserved.asked.add(callId);
|
|
1826
1530
|
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
|
-
};
|
|
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
|
+
}
|
|
1838
1537
|
a.emit({ type: "hitl.ask", ...ask });
|
|
1839
1538
|
trackPendingAsk(pendingAsks, turnId, ask);
|
|
1840
1539
|
}
|
|
1841
1540
|
}
|
|
1541
|
+
const askedOriginals = reserved.originalsByTurn.get(turnId);
|
|
1842
1542
|
|
|
1843
1543
|
// ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
|
|
1844
1544
|
const actions = event.actions;
|
|
@@ -1850,15 +1550,17 @@ function driveAdkTopLevel(
|
|
|
1850
1550
|
if (actions.requestedAuthConfigs !== undefined) {
|
|
1851
1551
|
// ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
|
|
1852
1552
|
// `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
|
|
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).
|
|
1861
1562
|
for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
|
|
1563
|
+
if (askedOriginals?.has(callId) === true) continue;
|
|
1862
1564
|
const view = adkAuthConfigView(authConfig);
|
|
1863
1565
|
const ask: AgPausedAsk = {
|
|
1864
1566
|
askId: `auth_${callId}`,
|
|
@@ -1876,6 +1578,8 @@ function driveAdkTopLevel(
|
|
|
1876
1578
|
// `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
|
|
1877
1579
|
// 18). Tracked in `pendingAsks` for the same paused-close fold as above.
|
|
1878
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;
|
|
1879
1583
|
const metadata: { [k: string]: JsonValue } = {};
|
|
1880
1584
|
if (conf.confirmed !== undefined) metadata["confirmed"] = conf.confirmed;
|
|
1881
1585
|
if (conf.payload !== undefined) metadata["payload"] = JsonValue.parse(conf.payload);
|
|
@@ -1912,7 +1616,7 @@ function driveAdkTopLevel(
|
|
|
1912
1616
|
a.contentBlock(messageId, {
|
|
1913
1617
|
type: "provider-raw",
|
|
1914
1618
|
vendor: "google",
|
|
1915
|
-
raw: JsonValue.parse(unmappedActions),
|
|
1619
|
+
raw: reduceCarried(JsonValue.parse(unmappedActions)),
|
|
1916
1620
|
});
|
|
1917
1621
|
}
|
|
1918
1622
|
}
|
|
@@ -1987,13 +1691,134 @@ function driveAdkTopLevel(
|
|
|
1987
1691
|
a.contentBlock(messageId, {
|
|
1988
1692
|
type: "provider-raw",
|
|
1989
1693
|
vendor: "google",
|
|
1990
|
-
raw: JsonValue.parse(unmappedEvent),
|
|
1694
|
+
raw: reduceCarried(JsonValue.parse(unmappedEvent)),
|
|
1991
1695
|
});
|
|
1992
1696
|
}
|
|
1993
1697
|
}
|
|
1994
1698
|
|
|
1995
1699
|
// ─── stateful factory: createAdkNormalizer ────────────────────────────────────
|
|
1996
|
-
|
|
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;
|
|
1997
1822
|
const a = new StreamAssembler();
|
|
1998
1823
|
const threadId = "google";
|
|
1999
1824
|
// §8.3 per-instance accumulator (replaces the module-level streamedText Map):
|
|
@@ -2018,8 +1843,13 @@ function createAdkInner(): AdkInner {
|
|
|
2018
1843
|
// (the is_final_response aggregate); the `flush()` truncation path never
|
|
2019
1844
|
// reads it — see the comment there.
|
|
2020
1845
|
const pendingAsks = new Map<string, AgPausedAsk[]>();
|
|
2021
|
-
//
|
|
2022
|
-
|
|
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>>();
|
|
2023
1853
|
const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
|
|
2024
1854
|
// Null-id call mint state (audit M47) — per-invoke ordinal counter + the
|
|
2025
1855
|
// content/name correlation maps; lives exactly as long as this Normalizer
|
|
@@ -2096,9 +1926,30 @@ function createAdkInner(): AdkInner {
|
|
|
2096
1926
|
// reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
|
|
2097
1927
|
// closes the turn as success. It is a per-EVENT test, never a latch
|
|
2098
1928
|
// (NodeTool puts nodeInfo into plain runs too). Error closes stay
|
|
2099
|
-
// immediate. A completed workflow
|
|
2100
|
-
//
|
|
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.
|
|
2101
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 {
|
|
2102
1953
|
closedTurns.add(turnId);
|
|
2103
1954
|
const rawFinish = event.finishReason ?? event.errorCode;
|
|
2104
1955
|
const finish = resolveFinishReason(rawFinish);
|
|
@@ -2140,14 +1991,109 @@ function createAdkInner(): AdkInner {
|
|
|
2140
1991
|
a.closeTurnDone(turnId, {
|
|
2141
1992
|
outcome: paused ? { type: "paused", asks } : { type: "success" },
|
|
2142
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 } : {}),
|
|
2143
2001
|
...(usage !== undefined ? { usage } : {}),
|
|
2144
2002
|
...(safety !== undefined ? { safety } : {}),
|
|
2145
2003
|
});
|
|
2146
2004
|
}
|
|
2147
2005
|
}
|
|
2148
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
|
+
|
|
2149
2094
|
function drive(event: AdkEvent): void {
|
|
2150
|
-
const key = turnKey(event)
|
|
2095
|
+
const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
|
|
2096
|
+
firstKey ??= key;
|
|
2151
2097
|
const turnId = `turn_${key}`;
|
|
2152
2098
|
const messageId = ensureOpen(turnId);
|
|
2153
2099
|
const parts = event.content?.parts ?? [];
|
|
@@ -2233,7 +2179,7 @@ function createAdkInner(): AdkInner {
|
|
|
2233
2179
|
return;
|
|
2234
2180
|
}
|
|
2235
2181
|
if (residualTail.length > 0) {
|
|
2236
|
-
const id = mintBlockId(blockIds,
|
|
2182
|
+
const id = mintBlockId(blockIds, "text");
|
|
2237
2183
|
a.textStart(id, messageId);
|
|
2238
2184
|
a.textDelta(id, messageId, residualTail);
|
|
2239
2185
|
a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
|
|
@@ -2276,14 +2222,33 @@ function createAdkInner(): AdkInner {
|
|
|
2276
2222
|
// aggregate never arrives simply die with the invoke's closure — bounded,
|
|
2277
2223
|
// per-invoke.
|
|
2278
2224
|
|
|
2279
|
-
|
|
2225
|
+
if (!isPartial) trackLongRunning(event, turnId);
|
|
2226
|
+
driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
|
|
2280
2227
|
maybeCloseTurn(event, turnId, messageId, isPartial);
|
|
2281
2228
|
}
|
|
2282
2229
|
|
|
2283
2230
|
return {
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2231
|
+
push(native: JsonValue): AgEvent[] {
|
|
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();
|
|
2287
2252
|
return a.drain();
|
|
2288
2253
|
}
|
|
2289
2254
|
if (!isAdkEvent(json)) {
|
|
@@ -2293,15 +2258,7 @@ function createAdkInner(): AdkInner {
|
|
|
2293
2258
|
drive(json);
|
|
2294
2259
|
return a.drain();
|
|
2295
2260
|
},
|
|
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[] {
|
|
2261
|
+
flush(): AgEvent[] {
|
|
2305
2262
|
// Dangling open turns (interrupted stream before a final aggregate):
|
|
2306
2263
|
// close their message; the ENGINE flush closes the turn itself with
|
|
2307
2264
|
// turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
|
|
@@ -2314,87 +2271,14 @@ function createAdkInner(): AdkInner {
|
|
|
2314
2271
|
// (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
|
|
2315
2272
|
// Workflow invoke until the host completion signal exists, still reports
|
|
2316
2273
|
// the tokens it spent. There is never a turn.done here, so the usage
|
|
2317
|
-
// appears only once.
|
|
2318
|
-
// path, when reading it failed).
|
|
2274
|
+
// appears only once.
|
|
2319
2275
|
for (const turnId of openTurns) {
|
|
2320
2276
|
if (!closedTurns.has(turnId)) {
|
|
2321
2277
|
closedTurns.add(turnId);
|
|
2322
|
-
a.closeMessage(`msg_${turnId}`,
|
|
2278
|
+
a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
|
|
2323
2279
|
}
|
|
2324
2280
|
}
|
|
2325
2281
|
return a.flush();
|
|
2326
2282
|
},
|
|
2327
2283
|
};
|
|
2328
2284
|
}
|
|
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
|
-
}
|