@silverprotocol/google-adk 0.6.4 → 0.6.6

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,310 @@ 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): the credential resume rebuilds the request
1268
+ // server-side from the session's own reserved call (auth_preprocessor.js
1269
+ // requestedAuthConfigs) and takes only the auth code / response URI from the
1270
+ // client's answer (credential_response_binding.js bindCredential; the raw
1271
+ // credential is restored from the request). An oauth2/OIDC request always
1272
+ // carries a generated authUri (auth_handler.js generateAuthRequest). So what
1273
+ // the allowlist omits is never needed to answer the ask.
1274
+ const ADK_REQUEST_CREDENTIAL = "adk_request_credential";
1275
+
1276
+ type AllowSpec = { [key: string]: true | ((v: JsonValue) => JsonValue | undefined) };
1277
+
1278
+ function snakeKey(k: string): string {
1279
+ return k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
1280
+ }
1281
+
1282
+ /** Copy only the allowlisted members of `v` (camel or snake spelling), each
1283
+ * either verbatim (`true`) or through its nested allowlist. */
1284
+ function pickAllowed(v: JsonValue | undefined, spec: AllowSpec): JsonValue | undefined {
1285
+ if (!isJsonObject(v)) return undefined;
1286
+ const out: { [k: string]: JsonValue } = {};
1287
+ for (const [name, rule] of Object.entries(spec)) {
1288
+ for (const key of name === snakeKey(name) ? [name] : [name, snakeKey(name)]) {
1289
+ if (!Object.hasOwn(v, key)) continue;
1290
+ const member = v[key];
1291
+ if (member === undefined) continue;
1292
+ const kept = rule === true ? member : rule(member);
1293
+ if (kept !== undefined) out[key] = kept;
1294
+ }
1295
+ }
1296
+ return out;
1297
+ }
1298
+
1299
+ const OAUTH2_ALLOW: AllowSpec = {
1300
+ clientId: true,
1301
+ authUri: true,
1302
+ redirectUri: true,
1303
+ scopes: true,
1304
+ codeChallengeMethod: true,
1305
+ tokenEndpointAuthMethod: true,
1306
+ expiresAt: true,
1307
+ expiresIn: true,
1308
+ audience: true,
1309
+ };
1310
+ const SERVICE_ACCOUNT_ALLOW: AllowSpec = {
1311
+ scopes: true,
1312
+ useDefaultCredential: true,
1313
+ useIdToken: true,
1314
+ audience: true,
1315
+ serviceAccountCredential: (v) =>
1316
+ pickAllowed(v, { projectId: true, clientEmail: true, tokenUri: true, universeDomain: true }),
1317
+ };
1318
+ const AUTH_CREDENTIAL_ALLOW: AllowSpec = {
1319
+ authType: true,
1320
+ resourceRef: true,
1321
+ oauth2: (v) => pickAllowed(v, OAUTH2_ALLOW),
1322
+ serviceAccount: (v) => pickAllowed(v, SERVICE_ACCOUNT_ALLOW),
1323
+ };
1324
+ // The security scheme, member by member: an OpenAPI 3.0 SecuritySchemeObject
1325
+ // (openapi-types 12.1.3 OpenAPIV3: http, apiKey, oauth2 and openIdConnect,
1326
+ // the type @google/adk 2.1.0's auth_schemes.d.ts names) or ADK's
1327
+ // OpenIdConnectWithConfig. Every leaf is a string, a string list or a map of
1328
+ // strings, and only those survive. A scheme member no type declares (a vendor
1329
+ // extension, a stray field) never rides.
1330
+ const schemeString = (v: JsonValue): JsonValue | undefined => (typeof v === "string" ? v : undefined);
1331
+ const schemeStringList = (v: JsonValue): JsonValue | undefined =>
1332
+ Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
1333
+ /** A map this facet rebuilds from native entries never carries an own
1334
+ * `__proto__` key (SPEC §13.7): JsonValue.parse drops one, and
1335
+ * Object.fromEntries would re-create it as an own property. */
1336
+ function isReservedMapKey(k: string): boolean {
1337
+ return k === "__proto__";
1338
+ }
1339
+ /** OAuth2 flow scopes are a map of scope name -> description; OIDC config
1340
+ * scopes are a list. Either keeps only its string entries. */
1341
+ const schemeScopes = (v: JsonValue): JsonValue | undefined =>
1342
+ Array.isArray(v)
1343
+ ? schemeStringList(v)
1344
+ : isJsonObject(v)
1345
+ ? Object.fromEntries(
1346
+ Object.entries(v).filter((e): e is [string, string] => !isReservedMapKey(e[0]) && typeof e[1] === "string"),
1347
+ )
1348
+ : undefined;
1349
+ const OAUTH2_FLOW_ALLOW: AllowSpec = {
1350
+ authorizationUrl: schemeString,
1351
+ tokenUrl: schemeString,
1352
+ refreshUrl: schemeString,
1353
+ scopes: schemeScopes,
1354
+ };
1355
+ const AUTH_SCHEME_ALLOW: AllowSpec = {
1356
+ type: schemeString,
1357
+ description: schemeString,
1358
+ // http
1359
+ scheme: schemeString,
1360
+ bearerFormat: schemeString,
1361
+ // apiKey (the header/query parameter's name and location, never its value)
1362
+ name: schemeString,
1363
+ in: schemeString,
1364
+ // oauth2 (flows.password is the password-GRANT flow: a tokenUrl and scopes)
1365
+ flows: (v) =>
1366
+ pickAllowed(v, {
1367
+ implicit: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
1368
+ password: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
1369
+ clientCredentials: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
1370
+ authorizationCode: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
1371
+ }),
1372
+ // openIdConnect
1373
+ openIdConnectUrl: schemeString,
1374
+ // OpenIdConnectWithConfig
1375
+ authorizationEndpoint: schemeString,
1376
+ tokenEndpoint: schemeString,
1377
+ userinfoEndpoint: schemeString,
1378
+ revocationEndpoint: schemeString,
1379
+ tokenEndpointAuthMethodsSupported: schemeStringList,
1380
+ grantTypesSupported: schemeStringList,
1381
+ scopes: schemeScopes,
1382
+ };
1383
+ const AUTH_CONFIG_ALLOW: AllowSpec = {
1384
+ authScheme: (v) => pickAllowed(v, AUTH_SCHEME_ALLOW),
1385
+ credentialKey: true,
1386
+ rawAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
1387
+ exchangedAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
1388
+ };
1389
+
1390
+ // ─── shared state (state.delta) ──────────────────────────────────────────────
1391
+ // ADK itself writes an exchanged AuthCredential into the event's
1392
+ // actions.stateDelta on two paths (@google/adk 2.1.0):
1393
+ // - a Runner configured with SessionStateCredentialService saves it under the
1394
+ // bare credentialKey (session_state_credential_service.js; ToolContext's
1395
+ // State writes value AND delta, agents/context.js:37-39, sessions/state.js:97-102);
1396
+ // - the Workflow plane's FunctionNode auth resume stores it under
1397
+ // "temp:" + credentialKey (auth_handler.js:35-38, :47), and function_node.js
1398
+ // copies every new delta entry into the event it yields (:93-127). A Runner
1399
+ // removes "temp:" entries from a non-partial event as it appends it to the
1400
+ // session, before yielding it; a partial event, or an event read before
1401
+ // that append, still carries them.
1402
+ // ADK treats any value under the key as a stored credential
1403
+ // (hitl_utils.js:131-133), so the entry is omitted whole: a redacted value left
1404
+ // behind would read as a credential. Every "temp:" entry is omitted too
1405
+ // (invocation-scoped by ADK's contract). Every other entry rides unchanged.
1406
+ const ADK_TEMP_STATE_PREFIX = "temp:";
1407
+ const AUTH_CREDENTIAL_TYPES: ReadonlySet<string> = new Set(["apiKey", "http", "oauth2", "openIdConnect", "serviceAccount"]);
1408
+ // resourceRef (auth_credential.d.ts:244) names a stored credential: ADK's
1409
+ // presence readers treat an object holding it as a held credential.
1410
+ const AUTH_CREDENTIAL_MEMBERS = [
1411
+ "apiKey",
1412
+ "api_key",
1413
+ "http",
1414
+ "oauth2",
1415
+ "serviceAccount",
1416
+ "service_account",
1417
+ "resourceRef",
1418
+ "resource_ref",
1419
+ ] as const;
1420
+
1421
+ function isObjectRecord(v: unknown): v is { readonly [k: string]: unknown } {
1422
+ return v !== null && typeof v === "object" && !Array.isArray(v);
1423
+ }
1424
+
1425
+ /** An ADK AuthCredential: `authType` (either spelling) is one of ADK's
1426
+ * credential types (auth_credential.d.ts) and a credential member is present
1427
+ * and non-null. */
1428
+ function isAuthCredentialObject(v: { readonly [k: string]: unknown }): boolean {
1429
+ const typed = ["authType", "auth_type"].some((k) => {
1430
+ const t = Object.hasOwn(v, k) ? v[k] : undefined;
1431
+ return typeof t === "string" && AUTH_CREDENTIAL_TYPES.has(t);
1432
+ });
1433
+ return typed && AUTH_CREDENTIAL_MEMBERS.some((m) => Object.hasOwn(v, m) && v[m] !== null && v[m] !== undefined);
1434
+ }
1435
+
1436
+ /** Whether `v` is, or holds at any depth (arrays included), an ADK
1437
+ * AuthCredential. Iterative and cycle-safe over the raw native value; a value
1438
+ * that cannot be walked counts as holding one, so this never throws. */
1439
+ function holdsAuthCredential(v: unknown): boolean {
1440
+ try {
1441
+ const seen = new Set<object>();
1442
+ const stack: unknown[] = [v];
1443
+ while (stack.length > 0) {
1444
+ const x = stack.pop();
1445
+ if (x === null || typeof x !== "object" || seen.has(x)) continue;
1446
+ seen.add(x);
1447
+ if (Array.isArray(x)) {
1448
+ for (const y of x) stack.push(y);
1449
+ } else if (isObjectRecord(x)) {
1450
+ if (isAuthCredentialObject(x)) return true;
1451
+ for (const k of Object.keys(x)) stack.push(x[k]);
1452
+ }
1453
+ }
1454
+ return false;
1455
+ } catch {
1456
+ return true;
1457
+ }
1458
+ }
1459
+
1460
+ /** The state map ADK yields, minus its "temp:" entries and every entry that
1461
+ * holds an ADK AuthCredential, in the original key order. A map with none of
1462
+ * those is carried exactly as before. When entries were omitted, a remaining
1463
+ * entry that is not JSON is dropped rather than thrown on, since a throw would
1464
+ * hand the raw native event to the host's error path. A value that is not a
1465
+ * map is carried as before, or as {} if it holds a credential. */
1466
+ function scrubStateMap(raw: unknown): JsonValue {
1467
+ if (!isObjectRecord(raw)) return holdsAuthCredential(raw) ? {} : JsonValue.parse(raw);
1468
+ const keys = Object.keys(raw);
1469
+ const omitted = keys.map((k) => k.startsWith(ADK_TEMP_STATE_PREFIX) || holdsAuthCredential(raw[k]));
1470
+ if (!omitted.includes(true)) return JsonValue.parse(raw);
1471
+ const kept: [string, JsonValue][] = [];
1472
+ keys.forEach((k, i) => {
1473
+ if (omitted[i] === true || isReservedMapKey(k)) return;
1474
+ const parsed = JsonValue.safeParse(raw[k]);
1475
+ if (parsed.success) kept.push([k, parsed.data]);
1476
+ });
1477
+ return Object.fromEntries(kept);
1478
+ }
1479
+
1480
+ /** The ADK AuthConfig reduced to its non-secret members ({} for a non-object). */
1481
+ function scrubAdkAuthConfig(native: JsonValue): JsonValue {
1482
+ return pickAllowed(native, AUTH_CONFIG_ALLOW) ?? {};
1483
+ }
1484
+
1485
+ /** A reserved-credential functionResponse (the client's answer) scrubbed the
1486
+ * same way; undefined when the response is not an object. */
1487
+ function scrubbedResponse(response: unknown): { readonly [k: string]: JsonValue } | undefined {
1488
+ if (!isJsonObject(response)) return undefined;
1489
+ const scrubbed = scrubAdkAuthConfig(response);
1490
+ return isJsonObject(scrubbed) ? scrubbed : undefined;
1491
+ }
1492
+
1493
+ /** The reserved credential call's args: its id, its message and the scrubbed
1494
+ * AuthConfig. Nothing else is forwarded. */
1495
+ function scrubCredentialCallArgs(args: JsonValue): JsonValue {
1496
+ return (
1497
+ pickAllowed(args, {
1498
+ functionCallId: true,
1499
+ message: true,
1500
+ authConfig: (v) => scrubAdkAuthConfig(v),
1501
+ }) ?? {}
1502
+ );
1503
+ }
1504
+
1505
+ function adkAuthConfigView(native: JsonValue): AgAuthConfig | undefined {
1506
+ if (!isJsonObject(native)) return undefined;
1507
+ const authScheme = native["authScheme"];
1508
+ const scheme = stringMember(authScheme, "type");
1509
+ if (scheme === undefined || !isJsonObject(authScheme)) return undefined;
1510
+ let authorizationUrl: string | undefined;
1511
+ let tokenUrl: string | undefined;
1512
+ let scopes: string[] | undefined;
1513
+ if ("authorizationEndpoint" in authScheme) {
1514
+ authorizationUrl = stringMember(authScheme, "authorizationEndpoint");
1515
+ tokenUrl = stringMember(authScheme, "tokenEndpoint");
1516
+ const s = authScheme["scopes"];
1517
+ if (Array.isArray(s)) scopes = s.filter((x): x is string => typeof x === "string");
1518
+ } else if (scheme === "oauth2") {
1519
+ const flows = authScheme["flows"];
1520
+ const flow = isJsonObject(flows)
1521
+ ? [flows["implicit"], flows["authorizationCode"], flows["clientCredentials"], flows["password"]].find(
1522
+ isJsonObject,
1523
+ )
1524
+ : undefined;
1525
+ if (flow !== undefined) {
1526
+ authorizationUrl = stringMember(flow, "authorizationUrl");
1527
+ tokenUrl = stringMember(flow, "tokenUrl");
1528
+ const s = flow["scopes"];
1529
+ if (isJsonObject(s)) scopes = Object.keys(s);
1530
+ }
1531
+ }
1532
+ const raw = native["rawAuthCredential"];
1533
+ const oauth2 = isJsonObject(raw) ? raw["oauth2"] : undefined;
1534
+ const clientId = stringMember(oauth2, "clientId");
1535
+ const audience = stringMember(oauth2, "audience");
1536
+ return {
1537
+ scheme,
1538
+ ...(scopes !== undefined ? { scopes } : {}),
1539
+ ...(authorizationUrl !== undefined ? { authorizationUrl } : {}),
1540
+ ...(tokenUrl !== undefined ? { tokenUrl } : {}),
1541
+ ...(clientId !== undefined ? { clientId } : {}),
1542
+ ...(audience !== undefined ? { audience } : {}),
1543
+ };
1544
+ }
1545
+
1111
1546
  /** Append `ask` to the turn's pending-asks list (creating it on first use).
1112
1547
  * Preserves emission order — asks accumulate in the order their originating
1113
1548
  * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
@@ -1128,16 +1563,19 @@ function driveAdkTopLevel(
1128
1563
  messageId: string,
1129
1564
  turnId: string,
1130
1565
  closedTurns: Set<string>,
1131
- pendingAsks: Map<string, AgPausedAsk[]>
1566
+ pendingAsks: Map<string, AgPausedAsk[]>,
1567
+ emittedInputAsks: Set<string>
1132
1568
  ): void {
1133
- if (event.inputTranscription?.text !== undefined) {
1569
+ // typeof: a JSON-null transcription text is absent (null guard; it rode the
1570
+ // text block as `null`, which the schema rejects).
1571
+ if (typeof event.inputTranscription?.text === "string") {
1134
1572
  a.contentBlock(messageId, {
1135
1573
  type: "text",
1136
1574
  text: event.inputTranscription.text,
1137
1575
  _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
1138
1576
  });
1139
1577
  }
1140
- if (event.outputTranscription?.text !== undefined) {
1578
+ if (typeof event.outputTranscription?.text === "string") {
1141
1579
  a.contentBlock(messageId, {
1142
1580
  type: "text",
1143
1581
  text: event.outputTranscription.text,
@@ -1199,6 +1637,40 @@ function driveAdkTopLevel(
1199
1637
  }
1200
1638
  }
1201
1639
 
1640
+ // ── ADK request-input pause → hitl.ask text|form (R&D item 6, step 1) ──
1641
+ // `adk_request_input` is ADK's reserved input-pause call: a workflow
1642
+ // `RequestInput` (args {interruptId, payload, message, response_schema}) or
1643
+ // the `requestInputTool` (args {message, response_schema?}). askId =
1644
+ // toolCallId = the call's id, the id ADK answers with. It is form when
1645
+ // response_schema is a non-null object, else text; payload rides metadata.
1646
+ // Tracked pending, so the pause-ending event closes the turn `paused`
1647
+ // (maybeCloseTurn). Deduped by id across the partial/aggregate re-send. The
1648
+ // call's own tool.start still opens (whether to suppress reserved calls is an
1649
+ // open step-2 decision).
1650
+ if (event.partial !== true) {
1651
+ for (const part of event.content?.parts ?? []) {
1652
+ const fc = part.functionCall;
1653
+ if (!isJsonObject(fc) || fc["name"] !== ADK_REQUEST_INPUT) continue;
1654
+ const callId = stringMember(fc, "id");
1655
+ if (callId === undefined || callId.length === 0 || emittedInputAsks.has(callId)) continue;
1656
+ emittedInputAsks.add(callId);
1657
+ const args = isJsonObject(fc["args"]) ? fc["args"] : {};
1658
+ const schema = args["response_schema"];
1659
+ const message = stringMember(args, "message");
1660
+ const payload = args["payload"];
1661
+ const ask: AgPausedAsk = {
1662
+ askId: callId,
1663
+ kind: isJsonObject(schema) ? "form" : "text",
1664
+ toolCallId: callId,
1665
+ ...(message !== undefined ? { message } : {}),
1666
+ ...(isJsonObject(schema) ? { schema } : {}),
1667
+ ...(payload !== undefined ? { metadata: { payload } } : {}),
1668
+ };
1669
+ a.emit({ type: "hitl.ask", ...ask });
1670
+ trackPendingAsk(pendingAsks, turnId, ask);
1671
+ }
1672
+ }
1673
+
1202
1674
  // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
1203
1675
  const actions = event.actions;
1204
1676
  if (actions !== undefined) {
@@ -1207,21 +1679,24 @@ function driveAdkTopLevel(
1207
1679
  }
1208
1680
  if (actions.escalate === true) a.emit({ type: "handoff", kind: "escalate" });
1209
1681
  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).
1682
+ // ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
1683
+ // `authConfig` is the flat AgAuthConfig VIEW derived by
1684
+ // `adkAuthConfigView` (absent when no string scheme exists). The native
1685
+ // AuthConfig rides WHOLE and verbatim in `metadata.authConfig`, the
1686
+ // item's sanctioned carrier, so the ask stays lossless and the mapped
1687
+ // values may appear twice (sp-protocol confirmed 2026-09-23). The SAME
1688
+ // ask fields are tracked in `pendingAsks`: if this turn's close-path
1689
+ // event turns out to be THIS event (or a later one for the same turnId),
1690
+ // `maybeCloseTurn` folds them into `turn.done.outcome.paused.asks[]`
1691
+ // instead of fabricating success (audit M26).
1219
1692
  for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
1693
+ const view = adkAuthConfigView(authConfig);
1220
1694
  const ask: AgPausedAsk = {
1221
1695
  askId: `auth_${callId}`,
1222
1696
  kind: "auth",
1223
1697
  toolCallId: callId,
1224
- metadata: { authConfig: JsonValue.parse(authConfig) },
1698
+ ...(view !== undefined ? { authConfig: view } : {}),
1699
+ metadata: { authConfig: scrubAdkAuthConfig(JsonValue.parse(authConfig)) },
1225
1700
  };
1226
1701
  a.emit({ type: "hitl.ask", ...ask });
1227
1702
  trackPendingAsk(pendingAsks, turnId, ask);
@@ -1246,8 +1721,10 @@ function driveAdkTopLevel(
1246
1721
  trackPendingAsk(pendingAsks, turnId, ask);
1247
1722
  }
1248
1723
  }
1724
+ // One state.delta per native state change, partial events included; see
1725
+ // scrubStateMap for the entries it omits ({} when none remain).
1249
1726
  if (actions.stateDelta !== undefined)
1250
- a.emit({ type: "state.delta", patch: JsonValue.parse(actions.stateDelta) });
1727
+ a.emit({ type: "state.delta", patch: scrubStateMap(actions.stateDelta) });
1251
1728
 
1252
1729
  const unmappedActions: { [k: string]: JsonValue } = {};
1253
1730
  if (actions.artifactDelta !== undefined)
@@ -1316,12 +1793,13 @@ function driveAdkTopLevel(
1316
1793
  unmappedEvent["compactedContent"] = event.compactedContent;
1317
1794
  if (event.isScratchpad !== undefined) unmappedEvent["isScratchpad"] = event.isScratchpad;
1318
1795
  // 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.
1796
+ // stamped only by dist/esm/workflow/* (and round-tripped by the Vertex
1797
+ // session service); a plain LlmAgent runAsync stream carries it only via a
1798
+ // NodeTool. It fires on every Workflow invoke (the e2e workflow capture
1799
+ // agent, observed offline on the real 2.1.0 engine). Present-checks
1800
+ // throughout (`route` may legitimately be `false`/`0`; `output` may be any
1801
+ // JSON value incl. null); `nodeInfo` rides as a WHOLE object. `nodeInfo` is
1802
+ // also READ by maybeCloseTurn's per-event gate and by isAdkPauseEnd.
1325
1803
  if (event.output !== undefined) unmappedEvent["output"] = JsonValue.parse(event.output);
1326
1804
  if (event.route !== undefined) unmappedEvent["route"] = JsonValue.parse(event.route);
1327
1805
  if (event.nodeInfo !== undefined) unmappedEvent["nodeInfo"] = JsonValue.parse(event.nodeInfo);
@@ -1366,10 +1844,14 @@ export function createAdkNormalizer(): Normalizer {
1366
1844
  // (the is_final_response aggregate); the `flush()` truncation path never
1367
1845
  // reads it — see the comment there.
1368
1846
  const pendingAsks = new Map<string, AgPausedAsk[]>();
1847
+ // adk_request_input call ids already asked (partial/aggregate re-send dedup).
1848
+ const emittedInputAsks = new Set<string>();
1369
1849
  const assembledToolCalls = new Set<string>(); // FC dedup across partial/aggregate (Task 3)
1370
1850
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
1371
1851
  // content/name correlation maps; lives exactly as long as this Normalizer
1372
1852
  // instance (one invoke, per §8.0's lifetime rule).
1853
+ // Per-turn, per-kind block ordinals (INV-BLOCK); lives as long as the invoke.
1854
+ const blockIds: BlockIdMint = new Map();
1373
1855
  const toolCallMint: ToolCallMintState = {
1374
1856
  nextOrdinal: 0,
1375
1857
  openWindowCounts: new Map<string, Map<string, number>>(),
@@ -1401,13 +1883,31 @@ export function createAdkNormalizer(): Normalizer {
1401
1883
  const parts = event.content?.parts ?? [];
1402
1884
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
1403
1885
  const interrupted = event.interrupted === true;
1886
+ // ── The pause close (R&D item 6, step 1) ──
1887
+ // SPEC §7 "the pause is the turn outcome" (SPEC.md:896): while an ask is
1888
+ // pending, the event with which ADK ENDS the pause (isAdkPauseEnd) closes
1889
+ // the turn `paused` from push(), with finishReason "paused". This runs
1890
+ // before the functionCall early-return, because the confirmation-request
1891
+ // event carries a (reserved) call. Items 12/18 now close on the real wire;
1892
+ // before, their close never fired and the turn flushed as an abort.
1893
+ const pending = pendingAsks.get(turnId);
1894
+ if (!interrupted && pending !== undefined && pending.length > 0 && isAdkPauseEnd(event)) {
1895
+ closedTurns.add(turnId);
1896
+ const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1897
+ a.closeMessage(messageId);
1898
+ a.closeTurnDone(turnId, {
1899
+ outcome: { type: "paused", asks: pending },
1900
+ finishReason: "paused",
1901
+ ...(usage !== undefined ? { usage } : {}),
1902
+ });
1903
+ return;
1904
+ }
1404
1905
  const hasCompletion =
1405
1906
  event.turnComplete === true ||
1406
1907
  event.finishReason !== undefined ||
1407
1908
  event.errorCode !== undefined;
1408
1909
  // is_final_response: a non-partial event with no pending function call and not interrupted.
1409
1910
  if (hasFunctionCall || interrupted || !hasCompletion) return;
1410
- closedTurns.add(turnId);
1411
1911
  // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
1412
1912
  // present ⇒ turn.error (values captured here so the close below needs no
1413
1913
  // re-narrowing).
@@ -1415,6 +1915,17 @@ export function createAdkNormalizer(): Normalizer {
1415
1915
  event.errorCode !== undefined && event.errorMessage !== undefined
1416
1916
  ? { code: event.errorCode, message: event.errorMessage }
1417
1917
  : undefined;
1918
+ // ── The nodeInfo gate (R&D item 6, step 1) ──
1919
+ // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
1920
+ // final text (nodeInfo present) is mid-invocation: closing the invocation
1921
+ // turn on it put the workflow's later events after the terminal and parked
1922
+ // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1923
+ // closes the turn as success. It is a per-EVENT test, never a latch
1924
+ // (NodeTool puts nodeInfo into plain runs too). Error closes stay
1925
+ // immediate. A completed workflow therefore flushes turn.abort until a host
1926
+ // completion signal exists (step 2): a documented known gap.
1927
+ if (errorClose === undefined && event.nodeInfo !== undefined) return;
1928
+ closedTurns.add(turnId);
1418
1929
  const rawFinish = event.finishReason ?? event.errorCode;
1419
1930
  const finish = resolveFinishReason(rawFinish);
1420
1931
  // Lossy finish mappings (resolveFinishReason's lossy arms) land the wire
@@ -1444,14 +1955,17 @@ export function createAdkNormalizer(): Normalizer {
1444
1955
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1445
1956
  const safety = mapBlockedSafety(event.safetyRatings);
1446
1957
  // 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.
1958
+ // requestedToolConfirmations / adk_request_input, tracked by
1959
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
1960
+ // unresolved requests the turn is parked on, never a fabricated success
1961
+ // (audit M26 / SPEC §8 items 12 + 18). A paused close carries
1962
+ // finishReason "paused" (the HITL value, R&D item 6 step 1), the same as
1963
+ // the pause-end close above.
1451
1964
  const asks = pendingAsks.get(turnId);
1965
+ const paused = asks !== undefined && asks.length > 0;
1452
1966
  a.closeTurnDone(turnId, {
1453
- outcome: asks !== undefined && asks.length > 0 ? { type: "paused", asks } : { type: "success" },
1454
- finishReason: finish.value,
1967
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
1968
+ finishReason: paused ? "paused" : finish.value,
1455
1969
  ...(usage !== undefined ? { usage } : {}),
1456
1970
  ...(safety !== undefined ? { safety } : {}),
1457
1971
  });
@@ -1474,7 +1988,7 @@ export function createAdkNormalizer(): Normalizer {
1474
1988
  const citations = mapGroundingCitations(event.groundingMetadata);
1475
1989
  const citedPartIndex =
1476
1990
  citations !== undefined
1477
- ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1991
+ ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1478
1992
  : -1;
1479
1993
 
1480
1994
  // Review finding c-i/c-ii: resolve null-id functionResponse correlation
@@ -1489,7 +2003,8 @@ export function createAdkNormalizer(): Normalizer {
1489
2003
  const nullIdResponseIds = new Map<number, string | undefined>();
1490
2004
  parts.forEach((part, idx) => {
1491
2005
  const fr = part.functionResponse;
1492
- if (fr === undefined) return;
2006
+ // A JSON-null arm is carried by driveAdkPart; never dereference it here.
2007
+ if (fr === undefined || !isJsonObject(fr)) return;
1493
2008
  if (fr.id != null && fr.id.length > 0) return; // real id — resolved directly, not via this map
1494
2009
  nullIdResponseIds.set(idx, consumeMintedCallId(toolCallMint, turnId, fr.name));
1495
2010
  });
@@ -1499,7 +2014,7 @@ export function createAdkNormalizer(): Normalizer {
1499
2014
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
1500
2015
  const aggregateText = isAggregate
1501
2016
  ? parts
1502
- .filter((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
2017
+ .filter((p) => p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1503
2018
  .map((p) => p.text ?? "")
1504
2019
  .join("")
1505
2020
  : "";
@@ -1514,7 +2029,7 @@ export function createAdkNormalizer(): Normalizer {
1514
2029
  isAggregate &&
1515
2030
  part.thought !== true &&
1516
2031
  part.functionCall === undefined &&
1517
- part.text !== undefined;
2032
+ typeof part.text === "string";
1518
2033
  if (isAggregateText) {
1519
2034
  if (suppressAggregateText) {
1520
2035
  // NOTE: fully-suppressed aggregate — this event emits NO text.end at all
@@ -1527,7 +2042,7 @@ export function createAdkNormalizer(): Normalizer {
1527
2042
  return;
1528
2043
  }
1529
2044
  if (residualTail.length > 0) {
1530
- const id = `text:${index}`;
2045
+ const id = mintBlockId(blockIds, turnId, "text");
1531
2046
  a.textStart(id, messageId);
1532
2047
  a.textDelta(id, messageId, residualTail);
1533
2048
  a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
@@ -1547,6 +2062,7 @@ export function createAdkNormalizer(): Normalizer {
1547
2062
  assembledToolCalls,
1548
2063
  toolCallMint,
1549
2064
  nullIdResponseIds,
2065
+ blockIds,
1550
2066
  index === citedPartIndex ? citations : undefined
1551
2067
  );
1552
2068
  if (isPartial) accumulated += contributed;
@@ -1569,7 +2085,7 @@ export function createAdkNormalizer(): Normalizer {
1569
2085
  // aggregate never arrives simply die with the invoke's closure — bounded,
1570
2086
  // per-invoke.
1571
2087
 
1572
- driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks); // standalone/content arms (Tasks 4–5)
2088
+ driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks); // standalone/content arms (Tasks 4–5)
1573
2089
  maybeCloseTurn(event, turnId, messageId, isPartial);
1574
2090
  }
1575
2091
 
@@ -1591,10 +2107,15 @@ export function createAdkNormalizer(): Normalizer {
1591
2107
  // (the is_final_response aggregate — see `maybeCloseTurn`) is an
1592
2108
  // INTERRUPTED stream, not a resolved pause. A truncated pause is a
1593
2109
  // truncation — `pendingAsks` is never consulted here (audit M26).
2110
+ // The synthetic message.end carries the turn's accumulated usage
2111
+ // (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
2112
+ // Workflow invoke until the host completion signal exists, still reports
2113
+ // the tokens it spent. There is never a turn.done here, so the usage
2114
+ // appears only once.
1594
2115
  for (const turnId of openTurns) {
1595
2116
  if (!closedTurns.has(turnId)) {
1596
2117
  closedTurns.add(turnId);
1597
- a.closeMessage(`msg_${turnId}`);
2118
+ a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
1598
2119
  }
1599
2120
  }
1600
2121
  return a.flush();