@silverprotocol/google-adk 0.6.5 → 0.6.7

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/src/index.ts CHANGED
@@ -52,6 +52,7 @@
52
52
  import {
53
53
  type AgEvent,
54
54
  type AgBlock,
55
+ type AgAuthConfig,
55
56
  type AgCitation,
56
57
  type AgFinishReason,
57
58
  type AgMeta,
@@ -95,8 +96,11 @@ export interface AdkPart {
95
96
  /** Embedded media bytes (base64). Both members are OPTIONAL on the genai
96
97
  * `Blob` type (`data?`/`mimeType?`, doc-"Required" only) — `driveAdkPart`
97
98
  * typeof-guards them and carries a Blob missing either via provider-raw
98
- * rather than crash on `mimeType.startsWith` or emit a `data`-less source. */
99
- inlineData?: { mimeType?: string; data?: string };
99
+ * rather than crash on `mimeType.startsWith` or emit a `data`-less source.
100
+ * `displayName?` (genai 2.24.0 drops "not supported in Gemini API" from its
101
+ * doc): → `file.filename`, or `providerMetadata.google.displayName` on an
102
+ * image/audio block, which has no name slot. */
103
+ inlineData?: { mimeType?: string; data?: string; displayName?: string };
100
104
  /** Model-generated code (the Code Execution tool). `code` is OPTIONAL on
101
105
  * the genai `ExecutableCode` type (upstream adk #868 fixed the same
102
106
  * assumption) — a code-less part rides provider-raw, never a `code` block
@@ -106,8 +110,10 @@ export interface AdkPart {
106
110
  codeExecutionResult?: { outcome?: string; output?: string };
107
111
  /** A reference to an uploaded file (passed through opaquely). `fileUri` is
108
112
  * OPTIONAL on the genai `FileData` type — a uri-less part rides
109
- * provider-raw, never a schema-invalid `resource-link`. */
110
- fileData?: { mimeType?: string; fileUri?: string };
113
+ * provider-raw, never a schema-invalid `resource-link`. `displayName?`
114
+ * (genai 2.24.0): `resource-link` has no name slot (SPEC §2), so it rides a
115
+ * sibling provider-raw `{ fileData: { displayName } }`. */
116
+ fileData?: { mimeType?: string; fileUri?: string; displayName?: string };
111
117
  /** Media resolution hint for the input media (fixture-drift ratchet finding,
112
118
  * google-adk-ratchet task) — carried opaquely via `driveAdkPart`'s
113
119
  * unmapped-part-fields provider-raw block; never interpreted. */
@@ -567,13 +573,20 @@ function mapBlockReason(reason: string): "safety" | "blocklist" | "prohibited" |
567
573
  // ─── inlineData.mimeType → AgBlock type (spec §2) ─────────────────────────────
568
574
  // Route a Gemini Blob by its MIME type to the matching AgBlock media arm. base64
569
575
  // is the only source kind Gemini inlineData carries (Blob = {mimeType, data}).
570
- function inlineDataBlock(d: { mimeType: string; data: string }): AgBlock {
576
+ function inlineDataBlock(d: { mimeType: string; data: string; displayName?: string }): AgBlock {
571
577
  const source = { type: "base64", mediaType: d.mimeType, data: d.data } as const;
572
- if (d.mimeType.startsWith("image/")) return { type: "image", source };
573
- if (d.mimeType.startsWith("audio/")) return { type: "audio", source };
578
+ // genai 2.24.0 Blob.displayName: the file arm's own `filename` (SPEC §2) is
579
+ // its home; image/audio have no name slot, so it rides providerMetadata.
580
+ // Absent ⇒ byte-identical.
581
+ const named =
582
+ d.displayName !== undefined
583
+ ? { providerMetadata: AgProviderMeta.parse({ google: { displayName: d.displayName } }) }
584
+ : {};
585
+ if (d.mimeType.startsWith("image/")) return { type: "image", source, ...named };
586
+ if (d.mimeType.startsWith("audio/")) return { type: "audio", source, ...named };
574
587
  // Everything else (video/*, application/*, text/*, …) rides the file arm
575
588
  // (spec §2: video = mediaType video/*). It is still a typed media block.
576
- return { type: "file", source };
589
+ return { type: "file", source, ...(d.displayName !== undefined ? { filename: d.displayName } : {}) };
577
590
  }
578
591
 
579
592
  // ─── genai-optional arm members (adk-13 hardening) ───────────────────────────
@@ -589,10 +602,19 @@ function stringMember(arm: unknown, key: string): string | undefined {
589
602
  // A media/code arm missing a member its AgBlock arm REQUIRES rides verbatim in
590
603
  // one provider-raw block keyed by its wire Part field name — the same
591
604
  // `{ <field>: <value> }` shape as `driveAdkPart`'s unmapped-part-fields ledger.
605
+ // A JSON-null arm (a snake_case serializer that keeps None) rides the same way
606
+ // for every object arm, the tool arms included (null guard): it is carried,
607
+ // never dereferenced.
592
608
  function carryUnmappableArm(
593
609
  a: StreamAssembler,
594
610
  messageId: string,
595
- field: "inlineData" | "executableCode" | "fileData",
611
+ field:
612
+ | "inlineData"
613
+ | "executableCode"
614
+ | "codeExecutionResult"
615
+ | "fileData"
616
+ | "functionCall"
617
+ | "functionResponse",
596
618
  arm: unknown,
597
619
  ): void {
598
620
  a.contentBlock(messageId, {
@@ -623,6 +645,42 @@ function codeOutcome(outcome: string | undefined): "ok" | "failed" | "deadline_e
623
645
  }
624
646
  }
625
647
 
648
+ // ─── ADK pause family: the event with which ADK ENDS a pause (R&D item 6) ────
649
+ // Package rd-06 (sp-protocol bar wf_6973f170-9d0), step 1. Observed on the
650
+ // real @google/adk 2.1.0 engine (offline, stub model), each pause's LAST event:
651
+ // - requireConfirmation: the confirmation-request event, which carries
652
+ // actions.requestedToolConfirmations (plus a user-role adk_request_confirmation
653
+ // call);
654
+ // - credential: the tool's functionResponse carrying actions.requestedAuthConfigs,
655
+ // AFTER the adk_request_credential call (closing on that call would put the
656
+ // response after the terminal and park);
657
+ // - requestInputTool: the content-less skipSummarization event after the call;
658
+ // - a Workflow root pause: the root's own content-less input record, which
659
+ // carries longRunningToolIds. The root is identified by adk-js path grammar
660
+ // (a dotless nodeInfo.path); that detail is facet-local, not spec.
661
+ // The caller closes `paused` on one of these only while an ask is pending.
662
+ const ADK_REQUEST_INPUT = "adk_request_input";
663
+
664
+ function isNonEmptyRecord(v: unknown): boolean {
665
+ return isJsonObject(v) && Object.keys(v).length > 0;
666
+ }
667
+
668
+ function isAdkPauseEnd(event: AdkEvent): boolean {
669
+ const actions = event.actions;
670
+ if (isNonEmptyRecord(actions?.requestedToolConfirmations)) return true;
671
+ if (isNonEmptyRecord(actions?.requestedAuthConfigs)) return true;
672
+ const contentless = (event.content?.parts ?? []).length === 0;
673
+ if (contentless && actions?.skipSummarization === true) return true;
674
+ const path = event.nodeInfo?.path;
675
+ return (
676
+ contentless &&
677
+ typeof path === "string" &&
678
+ path.length > 0 &&
679
+ !path.includes(".") &&
680
+ (event.longRunningToolIds?.length ?? 0) > 0
681
+ );
682
+ }
683
+
626
684
  function turnKey(ev: AdkEvent): string {
627
685
  return ev.invocationId && ev.invocationId.length > 0 ? ev.invocationId : ev.id ?? "adk";
628
686
  }
@@ -873,6 +931,23 @@ function consumeMintedCallId(
873
931
  }
874
932
 
875
933
  // ─── stateful factory: driveAdkPart ──────────────────────────────────────────
934
+ // ─── block ids: a per-turn ordinal per kind (SPEC.md:747, INV-BLOCK) ─────────
935
+ // Streaming block ids MUST be unique within a fold, and identity MUST never
936
+ // derive solely from a per-event positional index. ADK/Gemini parts carry no
937
+ // block id, so the facet mints `${kind}:${n}`, where n counts that kind's
938
+ // blocks in the turn. The old `${kind}:${partIndex}` repeated across events:
939
+ // two thought events in one invoke both opened reasoning:0 (thinking-gemini37/38,
940
+ // R&D item 14 prerequisite). The first block of each kind keeps its old id, so
941
+ // only streams that repeated an id, or put text after a thought, change.
942
+ type BlockIdMint = Map<string, number>;
943
+
944
+ function mintBlockId(m: BlockIdMint, turnId: string, kind: "text" | "reasoning"): string {
945
+ const key = `${turnId} ${kind}`;
946
+ const n = m.get(key) ?? 0;
947
+ m.set(key, n + 1);
948
+ return `${kind}:${n}`;
949
+ }
950
+
876
951
  function driveAdkPart(
877
952
  a: StreamAssembler,
878
953
  part: AdkPart,
@@ -884,6 +959,7 @@ function driveAdkPart(
884
959
  _assembledToolCalls: Set<string>,
885
960
  mint: ToolCallMintState,
886
961
  nullIdResponseIds: Map<number, string | undefined>,
962
+ blockIds: BlockIdMint,
887
963
  citations?: AgCitation[]
888
964
  ): string {
889
965
  // ── UNMAPPED PART FIELDS (mediaResolution/videoMetadata/toolCall/toolResponse/
@@ -933,9 +1009,10 @@ function driveAdkPart(
933
1009
 
934
1010
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
935
1011
  if (part.thought === true) {
936
- const id = `reasoning:${index}`;
1012
+ const id = mintBlockId(blockIds, turnId, "reasoning");
937
1013
  a.reasoningStart(id, messageId);
938
- if (part.text !== undefined && part.text.length > 0) a.reasoningDelta(id, messageId, part.text);
1014
+ // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
1015
+ if (typeof part.text === "string" && part.text.length > 0) a.reasoningDelta(id, messageId, part.text);
939
1016
  a.reasoningEnd(id, messageId, { provider: "google" });
940
1017
  if (part.thoughtSignature !== undefined && part.thoughtSignature.length > 0) {
941
1018
  a.reasoningOpaque(id, messageId, {
@@ -948,8 +1025,11 @@ function driveAdkPart(
948
1025
  }
949
1026
 
950
1027
  // ── TEXT ──
951
- if (part.text !== undefined) {
952
- const id = `text:${index}`;
1028
+ // A JSON-null text is ABSENT (null guard): it is not a text arm, so the part
1029
+ // falls through to the arms below (a functionCall beside it still maps), and
1030
+ // `null` never reaches textDelta or the streamed-text accumulator.
1031
+ if (typeof part.text === "string") {
1032
+ const id = mintBlockId(blockIds, turnId, "text");
953
1033
  const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
954
1034
  // STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
955
1035
  // event's groundingSupports segments (each already carries its own offsets +
@@ -974,6 +1054,10 @@ function driveAdkPart(
974
1054
 
975
1055
  // ── FUNCTION CALL → tool.start + tool.args.delta + tool.args.assembled ──
976
1056
  if (part.functionCall !== undefined) {
1057
+ if (!isJsonObject(part.functionCall)) {
1058
+ carryUnmappableArm(a, messageId, "functionCall", part.functionCall);
1059
+ return "";
1060
+ }
977
1061
  const fc = part.functionCall;
978
1062
  const realId = fc.id != null && fc.id.length > 0 ? fc.id : null;
979
1063
  let toolCallId: string;
@@ -992,7 +1076,11 @@ function driveAdkPart(
992
1076
  toolCallId = minted.toolCallId;
993
1077
  }
994
1078
  const providerCallIndex = realId !== null ? undefined : index;
995
- const input: JsonValue = JsonValue.parse(fc.args ?? {});
1079
+ // The reserved credential call's args carry the whole ADK AuthConfig: scrub
1080
+ // them to the allowlist (see scrubAdkAuthConfig) before they reach
1081
+ // tool.args.* and the folded tool-call block.
1082
+ const rawInput: JsonValue = JsonValue.parse(fc.args ?? {});
1083
+ const input: JsonValue = fc.name === ADK_REQUEST_CREDENTIAL ? scrubCredentialCallArgs(rawInput) : rawInput;
996
1084
  const longRunning =
997
1085
  event.longRunningToolIds !== undefined && event.longRunningToolIds.includes(toolCallId)
998
1086
  ? true
@@ -1019,6 +1107,10 @@ function driveAdkPart(
1019
1107
 
1020
1108
  // ── FUNCTION RESPONSE → tool.done ──
1021
1109
  if (part.functionResponse !== undefined) {
1110
+ if (!isJsonObject(part.functionResponse)) {
1111
+ carryUnmappableArm(a, messageId, "functionResponse", part.functionResponse);
1112
+ return "";
1113
+ }
1022
1114
  const fr = part.functionResponse;
1023
1115
  const realId = fr.id != null && fr.id.length > 0 ? fr.id : null;
1024
1116
  // Null id (audit M47): correlation was already resolved by `drive()`'s
@@ -1031,13 +1123,26 @@ function driveAdkPart(
1031
1123
  // tool.done with no matching tool.start — exactly the M47-review bug.
1032
1124
  // Carry the whole functionResponse losslessly instead (mirrors the
1033
1125
  // openai `late-*` ext precedents).
1034
- a.emitExt("google", "unparsed", { functionResponse: JsonValue.parse(fr), turnId });
1126
+ // A reserved-credential answer takes the same allowlist here as on the
1127
+ // resolved arm below (see scrubAdkAuthConfig): the carry must not
1128
+ // bypass it. Only the id, the name and the scrubbed response ride.
1129
+ const carriedResponse: JsonValue =
1130
+ fr.name === ADK_REQUEST_CREDENTIAL
1131
+ ? (pickAllowed(JsonValue.parse(fr), { id: true, name: true, response: (v) => scrubbedResponse(v) }) ?? {})
1132
+ : JsonValue.parse(fr);
1133
+ a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
1035
1134
  return "";
1036
1135
  }
1037
1136
  const outcome: ToolOutcome = fr.response?.["isError"] === true ? "error" : "ok";
1038
1137
  a.toolDone({
1039
1138
  toolCallId,
1040
- ...functionResponseToToolDoneFields(fr.name, fr.response),
1139
+ // A JSON-null response is absent (null guard): it was dereferenced below.
1140
+ // A reserved-credential answer carries the client's credential: scrub it
1141
+ // to the allowlist like the request.
1142
+ ...functionResponseToToolDoneFields(
1143
+ fr.name,
1144
+ fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : isJsonObject(fr.response) ? fr.response : undefined,
1145
+ ),
1041
1146
  outcome,
1042
1147
  turnId,
1043
1148
  providerMetadata:
@@ -1058,13 +1163,17 @@ function driveAdkPart(
1058
1163
  // `mimeType.startsWith`), so the arm rides VERBATIM via
1059
1164
  // `carryUnmappableArm`'s provider-raw block instead — lossless, never a
1060
1165
  // fabricated value. Branch order is unchanged: the carry fires exactly
1061
- // where the arm would otherwise have mapped. codeExecutionResult already
1062
- // defaults both of its optional members, so it needs no guard.
1166
+ // where the arm would otherwise have mapped. codeExecutionResult defaults
1167
+ // both of its optional members, so only a JSON-null arm needs the carry.
1063
1168
  if (part.inlineData !== undefined) {
1064
1169
  const mimeType = stringMember(part.inlineData, "mimeType");
1065
1170
  const data = stringMember(part.inlineData, "data");
1066
1171
  if (mimeType !== undefined && data !== undefined) {
1067
- a.contentBlock(messageId, inlineDataBlock({ mimeType, data }));
1172
+ const displayName = stringMember(part.inlineData, "displayName");
1173
+ a.contentBlock(
1174
+ messageId,
1175
+ inlineDataBlock({ mimeType, data, ...(displayName !== undefined ? { displayName } : {}) }),
1176
+ );
1068
1177
  } else {
1069
1178
  carryUnmappableArm(a, messageId, "inlineData", part.inlineData);
1070
1179
  }
@@ -1075,7 +1184,9 @@ function driveAdkPart(
1075
1184
  if (code !== undefined) {
1076
1185
  a.contentBlock(messageId, {
1077
1186
  type: "code",
1078
- language: codeLanguage(part.executableCode.language),
1187
+ // stringMember: a JSON-null language is absent → "python" (null guard;
1188
+ // it was `null.toLowerCase()`).
1189
+ language: codeLanguage(stringMember(part.executableCode, "language")),
1079
1190
  code,
1080
1191
  });
1081
1192
  } else {
@@ -1084,11 +1195,17 @@ function driveAdkPart(
1084
1195
  return "";
1085
1196
  }
1086
1197
  if (part.codeExecutionResult !== undefined) {
1087
- a.contentBlock(messageId, {
1088
- type: "code-result",
1089
- outcome: codeOutcome(part.codeExecutionResult.outcome),
1090
- output: part.codeExecutionResult.output ?? "",
1091
- });
1198
+ // Null guard: a JSON-null arm rides provider-raw (it was dereferenced);
1199
+ // a null or non-string member is absent and takes its existing default.
1200
+ if (isJsonObject(part.codeExecutionResult)) {
1201
+ a.contentBlock(messageId, {
1202
+ type: "code-result",
1203
+ outcome: codeOutcome(stringMember(part.codeExecutionResult, "outcome")),
1204
+ output: stringMember(part.codeExecutionResult, "output") ?? "",
1205
+ });
1206
+ } else {
1207
+ carryUnmappableArm(a, messageId, "codeExecutionResult", part.codeExecutionResult);
1208
+ }
1092
1209
  return "";
1093
1210
  }
1094
1211
  if (part.fileData !== undefined) {
@@ -1097,8 +1214,22 @@ function driveAdkPart(
1097
1214
  a.contentBlock(messageId, {
1098
1215
  type: "resource-link",
1099
1216
  uri: fileUri,
1100
- mimeType: part.fileData.mimeType,
1217
+ // stringMember: a JSON-null mimeType is absent (null guard; it rode
1218
+ // the block as `null`, which the schema rejects).
1219
+ mimeType: stringMember(part.fileData, "mimeType"),
1101
1220
  });
1221
+ // genai 2.24.0 FileData.displayName: resource-link has no name slot
1222
+ // (SPEC §2), so it rides a sibling provider-raw keyed by the wire path.
1223
+ // Absent ⇒ byte-identical. (Spec R&D item 5 would map it to an MCP
1224
+ // `name` if protocol adds one.)
1225
+ const displayName = stringMember(part.fileData, "displayName");
1226
+ if (displayName !== undefined) {
1227
+ a.contentBlock(messageId, {
1228
+ type: "provider-raw",
1229
+ vendor: "google",
1230
+ raw: { fileData: { displayName } },
1231
+ });
1232
+ }
1102
1233
  } else {
1103
1234
  carryUnmappableArm(a, messageId, "fileData", part.fileData);
1104
1235
  }
@@ -1108,6 +1239,479 @@ function driveAdkPart(
1108
1239
  return "";
1109
1240
  }
1110
1241
 
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
+
1111
1715
  /** Append `ask` to the turn's pending-asks list (creating it on first use).
1112
1716
  * Preserves emission order — asks accumulate in the order their originating
1113
1717
  * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
@@ -1128,16 +1732,19 @@ function driveAdkTopLevel(
1128
1732
  messageId: string,
1129
1733
  turnId: string,
1130
1734
  closedTurns: Set<string>,
1131
- pendingAsks: Map<string, AgPausedAsk[]>
1735
+ pendingAsks: Map<string, AgPausedAsk[]>,
1736
+ emittedInputAsks: Set<string>
1132
1737
  ): void {
1133
- if (event.inputTranscription?.text !== undefined) {
1738
+ // typeof: a JSON-null transcription text is absent (null guard; it rode the
1739
+ // text block as `null`, which the schema rejects).
1740
+ if (typeof event.inputTranscription?.text === "string") {
1134
1741
  a.contentBlock(messageId, {
1135
1742
  type: "text",
1136
1743
  text: event.inputTranscription.text,
1137
1744
  _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
1138
1745
  });
1139
1746
  }
1140
- if (event.outputTranscription?.text !== undefined) {
1747
+ if (typeof event.outputTranscription?.text === "string") {
1141
1748
  a.contentBlock(messageId, {
1142
1749
  type: "text",
1143
1750
  text: event.outputTranscription.text,
@@ -1199,6 +1806,40 @@ function driveAdkTopLevel(
1199
1806
  }
1200
1807
  }
1201
1808
 
1809
+ // ── ADK request-input pause → hitl.ask text|form (R&D item 6, step 1) ──
1810
+ // `adk_request_input` is ADK's reserved input-pause call: a workflow
1811
+ // `RequestInput` (args {interruptId, payload, message, response_schema}) or
1812
+ // the `requestInputTool` (args {message, response_schema?}). askId =
1813
+ // toolCallId = the call's id, the id ADK answers with. It is form when
1814
+ // response_schema is a non-null object, else text; payload rides metadata.
1815
+ // Tracked pending, so the pause-ending event closes the turn `paused`
1816
+ // (maybeCloseTurn). Deduped by id across the partial/aggregate re-send. The
1817
+ // call's own tool.start still opens (whether to suppress reserved calls is an
1818
+ // open step-2 decision).
1819
+ if (event.partial !== true) {
1820
+ for (const part of event.content?.parts ?? []) {
1821
+ const fc = part.functionCall;
1822
+ if (!isJsonObject(fc) || fc["name"] !== ADK_REQUEST_INPUT) continue;
1823
+ const callId = stringMember(fc, "id");
1824
+ if (callId === undefined || callId.length === 0 || emittedInputAsks.has(callId)) continue;
1825
+ emittedInputAsks.add(callId);
1826
+ const args = isJsonObject(fc["args"]) ? fc["args"] : {};
1827
+ const schema = args["response_schema"];
1828
+ const message = stringMember(args, "message");
1829
+ const payload = args["payload"];
1830
+ const ask: AgPausedAsk = {
1831
+ askId: callId,
1832
+ kind: isJsonObject(schema) ? "form" : "text",
1833
+ toolCallId: callId,
1834
+ ...(message !== undefined ? { message } : {}),
1835
+ ...(isJsonObject(schema) ? { schema } : {}),
1836
+ ...(payload !== undefined ? { metadata: { payload } } : {}),
1837
+ };
1838
+ a.emit({ type: "hitl.ask", ...ask });
1839
+ trackPendingAsk(pendingAsks, turnId, ask);
1840
+ }
1841
+ }
1842
+
1202
1843
  // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
1203
1844
  const actions = event.actions;
1204
1845
  if (actions !== undefined) {
@@ -1207,21 +1848,24 @@ function driveAdkTopLevel(
1207
1848
  }
1208
1849
  if (actions.escalate === true) a.emit({ type: "handoff", kind: "escalate" });
1209
1850
  if (actions.requestedAuthConfigs !== undefined) {
1210
- // ADK dict[str, AuthConfig] keyed by function-call-id. The AuthConfig is a
1211
- // complex framework-specific object (auth-scheme union + credentials) that
1212
- // does not fit the flat AgAuthConfig OAuth projection, so it rides opaque
1213
- // in `metadata` (AgJSON: framework-specifics lossless via metadata; SPEC §8
1214
- // item 12's sanctioned carrier). The SAME ask fields are tracked in
1215
- // `pendingAsks` — if this turn's close-path event turns out to be THIS
1216
- // event (or a later one for the same turnId), `maybeCloseTurn` folds them
1217
- // into `turn.done.outcome.paused.asks[]` instead of fabricating success
1218
- // (audit M26).
1851
+ // ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
1852
+ // `authConfig` is the flat AgAuthConfig VIEW derived by
1853
+ // `adkAuthConfigView` (absent when no string scheme exists). The native
1854
+ // AuthConfig rides WHOLE and verbatim in `metadata.authConfig`, the
1855
+ // item's sanctioned carrier, so the ask stays lossless and the mapped
1856
+ // values may appear twice (sp-protocol confirmed 2026-09-23). The SAME
1857
+ // ask fields are tracked in `pendingAsks`: if this turn's close-path
1858
+ // event turns out to be THIS event (or a later one for the same turnId),
1859
+ // `maybeCloseTurn` folds them into `turn.done.outcome.paused.asks[]`
1860
+ // instead of fabricating success (audit M26).
1219
1861
  for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
1862
+ const view = adkAuthConfigView(authConfig);
1220
1863
  const ask: AgPausedAsk = {
1221
1864
  askId: `auth_${callId}`,
1222
1865
  kind: "auth",
1223
1866
  toolCallId: callId,
1224
- metadata: { authConfig: JsonValue.parse(authConfig) },
1867
+ ...(view !== undefined ? { authConfig: view } : {}),
1868
+ metadata: { authConfig: scrubAdkAuthConfig(JsonValue.parse(authConfig)) },
1225
1869
  };
1226
1870
  a.emit({ type: "hitl.ask", ...ask });
1227
1871
  trackPendingAsk(pendingAsks, turnId, ask);
@@ -1246,8 +1890,10 @@ function driveAdkTopLevel(
1246
1890
  trackPendingAsk(pendingAsks, turnId, ask);
1247
1891
  }
1248
1892
  }
1893
+ // One state.delta per native state change, partial events included; see
1894
+ // scrubStateMap for the entries it omits ({} when none remain).
1249
1895
  if (actions.stateDelta !== undefined)
1250
- a.emit({ type: "state.delta", patch: JsonValue.parse(actions.stateDelta) });
1896
+ a.emit({ type: "state.delta", patch: scrubStateMap(actions.stateDelta) });
1251
1897
 
1252
1898
  const unmappedActions: { [k: string]: JsonValue } = {};
1253
1899
  if (actions.artifactDelta !== undefined)
@@ -1257,8 +1903,10 @@ function driveAdkTopLevel(
1257
1903
  // agentState is an OBJECT on the official 2.0.0 EventActions (a
1258
1904
  // resumable-checkpoint snapshot, e.g. `{ input }`), a string on the older
1259
1905
  // hand-typed contract — JsonValue.parse at the boundary carries either.
1260
- if (actions.agentState !== undefined)
1261
- unmappedActions["agentState"] = JsonValue.parse(actions.agentState);
1906
+ if (actions.agentState !== undefined) {
1907
+ const carried = carryNodeValue(actions.agentState);
1908
+ if (carried !== undefined) unmappedActions["agentState"] = carried.value;
1909
+ }
1262
1910
  if (actions.endOfAgent !== undefined) unmappedActions["endOfAgent"] = actions.endOfAgent;
1263
1911
  if (Object.keys(unmappedActions).length > 0) {
1264
1912
  a.contentBlock(messageId, {
@@ -1316,13 +1964,17 @@ function driveAdkTopLevel(
1316
1964
  unmappedEvent["compactedContent"] = event.compactedContent;
1317
1965
  if (event.isScratchpad !== undefined) unmappedEvent["isScratchpad"] = event.isScratchpad;
1318
1966
  // Workflow-plane quartet (2.0.0 peer bump; see the AdkEvent field docs):
1319
- // stamped only by dist/esm/workflow/* and round-tripped by the Vertex
1320
- // session service — never on a plain LlmAgent runAsync stream, so this is
1321
- // the same never-fires-on-captured-wire tolerance class as the
1322
- // CompactedEvent projection above. Present-checks throughout (`route` may
1323
- // legitimately be `false`/`0`; `output` may be any JSON value incl. null);
1324
- // `nodeInfo` rides as a WHOLE object.
1325
- if (event.output !== undefined) unmappedEvent["output"] = JsonValue.parse(event.output);
1967
+ // stamped only by dist/esm/workflow/* (and round-tripped by the Vertex
1968
+ // session service); a plain LlmAgent runAsync stream carries it only via a
1969
+ // NodeTool. It fires on every Workflow invoke (the e2e workflow capture
1970
+ // agent, observed offline on the real 2.1.0 engine). Present-checks
1971
+ // throughout (`route` may legitimately be `false`/`0`; `output` may be any
1972
+ // JSON value incl. null); `nodeInfo` rides as a WHOLE object. `nodeInfo` is
1973
+ // also READ by maybeCloseTurn's per-event gate and by isAdkPauseEnd.
1974
+ if (event.output !== undefined) {
1975
+ const carried = carryNodeValue(event.output);
1976
+ if (carried !== undefined) unmappedEvent["output"] = carried.value;
1977
+ }
1326
1978
  if (event.route !== undefined) unmappedEvent["route"] = JsonValue.parse(event.route);
1327
1979
  if (event.nodeInfo !== undefined) unmappedEvent["nodeInfo"] = JsonValue.parse(event.nodeInfo);
1328
1980
  if (event.isolationScope !== undefined)
@@ -1341,7 +1993,7 @@ function driveAdkTopLevel(
1341
1993
  }
1342
1994
 
1343
1995
  // ─── stateful factory: createAdkNormalizer ────────────────────────────────────
1344
- export function createAdkNormalizer(): Normalizer {
1996
+ function createAdkInner(): AdkInner {
1345
1997
  const a = new StreamAssembler();
1346
1998
  const threadId = "google";
1347
1999
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
@@ -1366,10 +2018,14 @@ export function createAdkNormalizer(): Normalizer {
1366
2018
  // (the is_final_response aggregate); the `flush()` truncation path never
1367
2019
  // reads it — see the comment there.
1368
2020
  const pendingAsks = new Map<string, AgPausedAsk[]>();
2021
+ // adk_request_input call ids already asked (partial/aggregate re-send dedup).
2022
+ const emittedInputAsks = new Set<string>();
1369
2023
  const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
1370
2024
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
1371
2025
  // content/name correlation maps; lives exactly as long as this Normalizer
1372
2026
  // instance (one invoke, per §8.0's lifetime rule).
2027
+ // Per-turn, per-kind block ordinals (INV-BLOCK); lives as long as the invoke.
2028
+ const blockIds: BlockIdMint = new Map();
1373
2029
  const toolCallMint: ToolCallMintState = {
1374
2030
  nextOrdinal: 0,
1375
2031
  openWindowCounts: new Map<string, Map<string, number>>(),
@@ -1401,13 +2057,31 @@ export function createAdkNormalizer(): Normalizer {
1401
2057
  const parts = event.content?.parts ?? [];
1402
2058
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
1403
2059
  const interrupted = event.interrupted === true;
2060
+ // ── The pause close (R&D item 6, step 1) ──
2061
+ // SPEC §7 "the pause is the turn outcome" (SPEC.md:896): while an ask is
2062
+ // pending, the event with which ADK ENDS the pause (isAdkPauseEnd) closes
2063
+ // the turn `paused` from push(), with finishReason "paused". This runs
2064
+ // before the functionCall early-return, because the confirmation-request
2065
+ // event carries a (reserved) call. Items 12/18 now close on the real wire;
2066
+ // before, their close never fired and the turn flushed as an abort.
2067
+ const pending = pendingAsks.get(turnId);
2068
+ if (!interrupted && pending !== undefined && pending.length > 0 && isAdkPauseEnd(event)) {
2069
+ closedTurns.add(turnId);
2070
+ const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
2071
+ a.closeMessage(messageId);
2072
+ a.closeTurnDone(turnId, {
2073
+ outcome: { type: "paused", asks: pending },
2074
+ finishReason: "paused",
2075
+ ...(usage !== undefined ? { usage } : {}),
2076
+ });
2077
+ return;
2078
+ }
1404
2079
  const hasCompletion =
1405
2080
  event.turnComplete === true ||
1406
2081
  event.finishReason !== undefined ||
1407
2082
  event.errorCode !== undefined;
1408
2083
  // is_final_response: a non-partial event with no pending function call and not interrupted.
1409
2084
  if (hasFunctionCall || interrupted || !hasCompletion) return;
1410
- closedTurns.add(turnId);
1411
2085
  // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
1412
2086
  // present ⇒ turn.error (values captured here so the close below needs no
1413
2087
  // re-narrowing).
@@ -1415,6 +2089,17 @@ export function createAdkNormalizer(): Normalizer {
1415
2089
  event.errorCode !== undefined && event.errorMessage !== undefined
1416
2090
  ? { code: event.errorCode, message: event.errorMessage }
1417
2091
  : undefined;
2092
+ // ── The nodeInfo gate (R&D item 6, step 1) ──
2093
+ // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
2094
+ // final text (nodeInfo present) is mid-invocation: closing the invocation
2095
+ // turn on it put the workflow's later events after the terminal and parked
2096
+ // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
2097
+ // closes the turn as success. It is a per-EVENT test, never a latch
2098
+ // (NodeTool puts nodeInfo into plain runs too). Error closes stay
2099
+ // immediate. A completed workflow therefore flushes turn.abort until a host
2100
+ // completion signal exists (step 2): a documented known gap.
2101
+ if (errorClose === undefined && event.nodeInfo !== undefined) return;
2102
+ closedTurns.add(turnId);
1418
2103
  const rawFinish = event.finishReason ?? event.errorCode;
1419
2104
  const finish = resolveFinishReason(rawFinish);
1420
2105
  // Lossy finish mappings (resolveFinishReason's lossy arms) land the wire
@@ -1444,14 +2129,17 @@ export function createAdkNormalizer(): Normalizer {
1444
2129
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1445
2130
  const safety = mapBlockedSafety(event.safetyRatings);
1446
2131
  // A turn with pending HITL asks (requestedAuthConfigs /
1447
- // requestedToolConfirmations, tracked by `trackPendingAsk` above) closes
1448
- // PAUSED, not success — the asks are real, unresolved requests the
1449
- // turn is parked on, never a fabricated success (audit M26 / SPEC §8
1450
- // items 12 + 18). `finishReason` stays the same mapping either way.
2132
+ // requestedToolConfirmations / adk_request_input, tracked by
2133
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
2134
+ // unresolved requests the turn is parked on, never a fabricated success
2135
+ // (audit M26 / SPEC §8 items 12 + 18). A paused close carries
2136
+ // finishReason "paused" (the HITL value, R&D item 6 step 1), the same as
2137
+ // the pause-end close above.
1451
2138
  const asks = pendingAsks.get(turnId);
2139
+ const paused = asks !== undefined && asks.length > 0;
1452
2140
  a.closeTurnDone(turnId, {
1453
- outcome: asks !== undefined && asks.length > 0 ? { type: "paused", asks } : { type: "success" },
1454
- finishReason: finish.value,
2141
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
2142
+ finishReason: paused ? "paused" : finish.value,
1455
2143
  ...(usage !== undefined ? { usage } : {}),
1456
2144
  ...(safety !== undefined ? { safety } : {}),
1457
2145
  });
@@ -1464,6 +2152,18 @@ export function createAdkNormalizer(): Normalizer {
1464
2152
  const messageId = ensureOpen(turnId);
1465
2153
  const parts = event.content?.parts ?? [];
1466
2154
  const isPartial = event.partial === true;
2155
+ // ADK renders an object `output` as the same event's text part, byte-equal
2156
+ // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
2157
+ // When the node-data reduction changed that output, the rendering would
2158
+ // repeat what the reduction removed, so that one part is skipped here and
2159
+ // in the aggregate below. Nothing else matches: not a string output, not
2160
+ // a substring, not model text.
2161
+ const renderedOutput = changedOutputRendering(event.output);
2162
+ const skipped = new Set<number>();
2163
+ if (renderedOutput !== undefined)
2164
+ parts.forEach((p, idx) => {
2165
+ if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput) skipped.add(idx);
2166
+ });
1467
2167
 
1468
2168
  // STREAMED-text citations carrier (audit M22): groundingMetadata is
1469
2169
  // EVENT-level, not per-part. A Gemini grounding response carries the full
@@ -1474,7 +2174,9 @@ export function createAdkNormalizer(): Normalizer {
1474
2174
  const citations = mapGroundingCitations(event.groundingMetadata);
1475
2175
  const citedPartIndex =
1476
2176
  citations !== undefined
1477
- ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
2177
+ ? parts.findIndex(
2178
+ (p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string",
2179
+ )
1478
2180
  : -1;
1479
2181
 
1480
2182
  // Review finding c-i/c-ii: resolve null-id functionResponse correlation
@@ -1489,7 +2191,8 @@ export function createAdkNormalizer(): Normalizer {
1489
2191
  const nullIdResponseIds = new Map<number, string | undefined>();
1490
2192
  parts.forEach((part, idx) => {
1491
2193
  const fr = part.functionResponse;
1492
- if (fr === undefined) return;
2194
+ // A JSON-null arm is carried by driveAdkPart; never dereference it here.
2195
+ if (fr === undefined || !isJsonObject(fr)) return;
1493
2196
  if (fr.id != null && fr.id.length > 0) return; // real id — resolved directly, not via this map
1494
2197
  nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
1495
2198
  });
@@ -1499,7 +2202,9 @@ export function createAdkNormalizer(): Normalizer {
1499
2202
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
1500
2203
  const aggregateText = isAggregate
1501
2204
  ? parts
1502
- .filter((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
2205
+ .filter(
2206
+ (p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string",
2207
+ )
1503
2208
  .map((p) => p.text ?? "")
1504
2209
  .join("")
1505
2210
  : "";
@@ -1510,11 +2215,12 @@ export function createAdkNormalizer(): Normalizer {
1510
2215
  let accumulated = alreadyStreamed;
1511
2216
 
1512
2217
  parts.forEach((part, index) => {
2218
+ if (skipped.has(index)) return;
1513
2219
  const isAggregateText =
1514
2220
  isAggregate &&
1515
2221
  part.thought !== true &&
1516
2222
  part.functionCall === undefined &&
1517
- part.text !== undefined;
2223
+ typeof part.text === "string";
1518
2224
  if (isAggregateText) {
1519
2225
  if (suppressAggregateText) {
1520
2226
  // NOTE: fully-suppressed aggregate — this event emits NO text.end at all
@@ -1527,7 +2233,7 @@ export function createAdkNormalizer(): Normalizer {
1527
2233
  return;
1528
2234
  }
1529
2235
  if (residualTail.length > 0) {
1530
- const id = `text:${index}`;
2236
+ const id = mintBlockId(blockIds, turnId, "text");
1531
2237
  a.textStart(id, messageId);
1532
2238
  a.textDelta(id, messageId, residualTail);
1533
2239
  a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
@@ -1547,6 +2253,7 @@ export function createAdkNormalizer(): Normalizer {
1547
2253
  assembledToolCalls,
1548
2254
  toolCallMint,
1549
2255
  nullIdResponseIds,
2256
+ blockIds,
1550
2257
  index === citedPartIndex ? citations : undefined
1551
2258
  );
1552
2259
  if (isPartial) accumulated += contributed;
@@ -1569,20 +2276,32 @@ export function createAdkNormalizer(): Normalizer {
1569
2276
  // aggregate never arrives simply die with the invoke's closure — bounded,
1570
2277
  // per-invoke.
1571
2278
 
1572
- driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks); // standalone/content arms (Tasks 4–5)
2279
+ driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks); // standalone/content arms (Tasks 4–5)
1573
2280
  maybeCloseTurn(event, turnId, messageId, isPartial);
1574
2281
  }
1575
2282
 
1576
2283
  return {
1577
- push(native: JsonValue): AgEvent[] {
1578
- if (!isAdkEvent(native)) {
1579
- a.emitExt("google", "unparsed", { native });
2284
+ accept(json: JsonValue | undefined): AgEvent[] {
2285
+ if (json === undefined) {
2286
+ a.emitExt("google", "unparsed", { reason: "not-serializable" });
1580
2287
  return a.drain();
1581
2288
  }
1582
- drive(native);
2289
+ if (!isAdkEvent(json)) {
2290
+ a.emitExt("google", "unparsed", { native: json });
2291
+ return a.drain();
2292
+ }
2293
+ drive(json);
1583
2294
  return a.drain();
1584
2295
  },
1585
- flush(): AgEvent[] {
2296
+ reportError(e: unknown): AgEvent[] {
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[] {
1586
2305
  // Dangling open turns (interrupted stream before a final aggregate):
1587
2306
  // close their message; the ENGINE flush closes the turn itself with
1588
2307
  // turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
@@ -1591,13 +2310,91 @@ export function createAdkNormalizer(): Normalizer {
1591
2310
  // (the is_final_response aggregate — see `maybeCloseTurn`) is an
1592
2311
  // INTERRUPTED stream, not a resolved pause. A truncated pause is a
1593
2312
  // truncation — `pendingAsks` is never consulted here (audit M26).
2313
+ // The synthetic message.end carries the turn's accumulated usage
2314
+ // (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
2315
+ // Workflow invoke until the host completion signal exists, still reports
2316
+ // the tokens it spent. There is never a turn.done here, so the usage
2317
+ // appears only once. `bare` closes without the usage (the last-resort
2318
+ // path, when reading it failed).
1594
2319
  for (const turnId of openTurns) {
1595
2320
  if (!closedTurns.has(turnId)) {
1596
2321
  closedTurns.add(turnId);
1597
- a.closeMessage(`msg_${turnId}`);
2322
+ a.closeMessage(`msg_${turnId}`, bare ? undefined : mapUsage(usageByTurn.get(turnId)));
1598
2323
  }
1599
2324
  }
1600
2325
  return a.flush();
1601
2326
  },
1602
2327
  };
1603
2328
  }
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
+ }