@silverprotocol/google-adk 0.6.5 → 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/dist/index.js CHANGED
@@ -228,13 +228,19 @@ function mapBlockReason(reason) {
228
228
  // is the only source kind Gemini inlineData carries (Blob = {mimeType, data}).
229
229
  function inlineDataBlock(d) {
230
230
  const source = { type: "base64", mediaType: d.mimeType, data: d.data };
231
+ // genai 2.24.0 Blob.displayName: the file arm's own `filename` (SPEC §2) is
232
+ // its home; image/audio have no name slot, so it rides providerMetadata.
233
+ // Absent ⇒ byte-identical.
234
+ const named = d.displayName !== undefined
235
+ ? { providerMetadata: AgProviderMeta.parse({ google: { displayName: d.displayName } }) }
236
+ : {};
231
237
  if (d.mimeType.startsWith("image/"))
232
- return { type: "image", source };
238
+ return { type: "image", source, ...named };
233
239
  if (d.mimeType.startsWith("audio/"))
234
- return { type: "audio", source };
240
+ return { type: "audio", source, ...named };
235
241
  // Everything else (video/*, application/*, text/*, …) rides the file arm
236
242
  // (spec §2: video = mediaType video/*). It is still a typed media block.
237
- return { type: "file", source };
243
+ return { type: "file", source, ...(d.displayName !== undefined ? { filename: d.displayName } : {}) };
238
244
  }
239
245
  // ─── genai-optional arm members (adk-13 hardening) ───────────────────────────
240
246
  // A Part arm's member when it is a string, else undefined. Read through
@@ -249,6 +255,9 @@ function stringMember(arm, key) {
249
255
  // A media/code arm missing a member its AgBlock arm REQUIRES rides verbatim in
250
256
  // one provider-raw block keyed by its wire Part field name — the same
251
257
  // `{ <field>: <value> }` shape as `driveAdkPart`'s unmapped-part-fields ledger.
258
+ // A JSON-null arm (a snake_case serializer that keeps None) rides the same way
259
+ // for every object arm, the tool arms included (null guard): it is carried,
260
+ // never dereferenced.
252
261
  function carryUnmappableArm(a, messageId, field, arm) {
253
262
  a.contentBlock(messageId, {
254
263
  type: "provider-raw",
@@ -276,6 +285,40 @@ function codeOutcome(outcome) {
276
285
  return "failed";
277
286
  }
278
287
  }
288
+ // ─── ADK pause family: the event with which ADK ENDS a pause (R&D item 6) ────
289
+ // Package rd-06 (sp-protocol bar wf_6973f170-9d0), step 1. Observed on the
290
+ // real @google/adk 2.1.0 engine (offline, stub model), each pause's LAST event:
291
+ // - requireConfirmation: the confirmation-request event, which carries
292
+ // actions.requestedToolConfirmations (plus a user-role adk_request_confirmation
293
+ // call);
294
+ // - credential: the tool's functionResponse carrying actions.requestedAuthConfigs,
295
+ // AFTER the adk_request_credential call (closing on that call would put the
296
+ // response after the terminal and park);
297
+ // - requestInputTool: the content-less skipSummarization event after the call;
298
+ // - a Workflow root pause: the root's own content-less input record, which
299
+ // carries longRunningToolIds. The root is identified by adk-js path grammar
300
+ // (a dotless nodeInfo.path); that detail is facet-local, not spec.
301
+ // The caller closes `paused` on one of these only while an ask is pending.
302
+ const ADK_REQUEST_INPUT = "adk_request_input";
303
+ function isNonEmptyRecord(v) {
304
+ return isJsonObject(v) && Object.keys(v).length > 0;
305
+ }
306
+ function isAdkPauseEnd(event) {
307
+ const actions = event.actions;
308
+ if (isNonEmptyRecord(actions?.requestedToolConfirmations))
309
+ return true;
310
+ if (isNonEmptyRecord(actions?.requestedAuthConfigs))
311
+ return true;
312
+ const contentless = (event.content?.parts ?? []).length === 0;
313
+ if (contentless && actions?.skipSummarization === true)
314
+ return true;
315
+ const path = event.nodeInfo?.path;
316
+ return (contentless &&
317
+ typeof path === "string" &&
318
+ path.length > 0 &&
319
+ !path.includes(".") &&
320
+ (event.longRunningToolIds?.length ?? 0) > 0);
321
+ }
279
322
  function turnKey(ev) {
280
323
  return ev.invocationId && ev.invocationId.length > 0 ? ev.invocationId : ev.id ?? "adk";
281
324
  }
@@ -398,8 +441,13 @@ function consumeMintedCallId(mint, turnId, name) {
398
441
  return undefined;
399
442
  return queue.shift();
400
443
  }
401
- // ─── stateful factory: driveAdkPart ──────────────────────────────────────────
402
- function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, citations) {
444
+ function mintBlockId(m, turnId, kind) {
445
+ const key = `${turnId} ${kind}`;
446
+ const n = m.get(key) ?? 0;
447
+ m.set(key, n + 1);
448
+ return `${kind}:${n}`;
449
+ }
450
+ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
403
451
  // ── UNMAPPED PART FIELDS (mediaResolution/videoMetadata/toolCall/toolResponse/
404
452
  // partMetadata/audioTranscription/mediaProcessing/speechMetadata) → provider-raw content.block
405
453
  // (fixture-drift ratchet finding, google-adk-ratchet task; Tenet-6; SPEC §8 item 23). These
@@ -447,9 +495,10 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
447
495
  }
448
496
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
449
497
  if (part.thought === true) {
450
- const id = `reasoning:${index}`;
498
+ const id = mintBlockId(blockIds, turnId, "reasoning");
451
499
  a.reasoningStart(id, messageId);
452
- if (part.text !== undefined && part.text.length > 0)
500
+ // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
501
+ if (typeof part.text === "string" && part.text.length > 0)
453
502
  a.reasoningDelta(id, messageId, part.text);
454
503
  a.reasoningEnd(id, messageId, { provider: "google" });
455
504
  if (part.thoughtSignature !== undefined && part.thoughtSignature.length > 0) {
@@ -462,8 +511,11 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
462
511
  return "";
463
512
  }
464
513
  // ── TEXT ──
465
- if (part.text !== undefined) {
466
- const id = `text:${index}`;
514
+ // A JSON-null text is ABSENT (null guard): it is not a text arm, so the part
515
+ // falls through to the arms below (a functionCall beside it still maps), and
516
+ // `null` never reaches textDelta or the streamed-text accumulator.
517
+ if (typeof part.text === "string") {
518
+ const id = mintBlockId(blockIds, turnId, "text");
467
519
  const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
468
520
  // STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
469
521
  // event's groundingSupports segments (each already carries its own offsets +
@@ -488,6 +540,10 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
488
540
  }
489
541
  // ── FUNCTION CALL → tool.start + tool.args.delta + tool.args.assembled ──
490
542
  if (part.functionCall !== undefined) {
543
+ if (!isJsonObject(part.functionCall)) {
544
+ carryUnmappableArm(a, messageId, "functionCall", part.functionCall);
545
+ return "";
546
+ }
491
547
  const fc = part.functionCall;
492
548
  const realId = fc.id != null && fc.id.length > 0 ? fc.id : null;
493
549
  let toolCallId;
@@ -509,7 +565,11 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
509
565
  toolCallId = minted.toolCallId;
510
566
  }
511
567
  const providerCallIndex = realId !== null ? undefined : index;
512
- const input = JsonValue.parse(fc.args ?? {});
568
+ // The reserved credential call's args carry the whole ADK AuthConfig: scrub
569
+ // them to the allowlist (see scrubAdkAuthConfig) before they reach
570
+ // tool.args.* and the folded tool-call block.
571
+ const rawInput = JsonValue.parse(fc.args ?? {});
572
+ const input = fc.name === ADK_REQUEST_CREDENTIAL ? scrubCredentialCallArgs(rawInput) : rawInput;
513
573
  const longRunning = event.longRunningToolIds !== undefined && event.longRunningToolIds.includes(toolCallId)
514
574
  ? true
515
575
  : undefined;
@@ -532,6 +592,10 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
532
592
  }
533
593
  // ── FUNCTION RESPONSE → tool.done ──
534
594
  if (part.functionResponse !== undefined) {
595
+ if (!isJsonObject(part.functionResponse)) {
596
+ carryUnmappableArm(a, messageId, "functionResponse", part.functionResponse);
597
+ return "";
598
+ }
535
599
  const fr = part.functionResponse;
536
600
  const realId = fr.id != null && fr.id.length > 0 ? fr.id : null;
537
601
  // Null id (audit M47): correlation was already resolved by `drive()`'s
@@ -544,13 +608,22 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
544
608
  // tool.done with no matching tool.start — exactly the M47-review bug.
545
609
  // Carry the whole functionResponse losslessly instead (mirrors the
546
610
  // openai `late-*` ext precedents).
547
- a.emitExt("google", "unparsed", { functionResponse: JsonValue.parse(fr), turnId });
611
+ // A reserved-credential answer takes the same allowlist here as on the
612
+ // resolved arm below (see scrubAdkAuthConfig): the carry must not
613
+ // bypass it. Only the id, the name and the scrubbed response ride.
614
+ const carriedResponse = fr.name === ADK_REQUEST_CREDENTIAL
615
+ ? (pickAllowed(JsonValue.parse(fr), { id: true, name: true, response: (v) => scrubbedResponse(v) }) ?? {})
616
+ : JsonValue.parse(fr);
617
+ a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
548
618
  return "";
549
619
  }
550
620
  const outcome = fr.response?.["isError"] === true ? "error" : "ok";
551
621
  a.toolDone({
552
622
  toolCallId,
553
- ...functionResponseToToolDoneFields(fr.name, fr.response),
623
+ // A JSON-null response is absent (null guard): it was dereferenced below.
624
+ // A reserved-credential answer carries the client's credential: scrub it
625
+ // to the allowlist like the request.
626
+ ...functionResponseToToolDoneFields(fr.name, fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : isJsonObject(fr.response) ? fr.response : undefined),
554
627
  outcome,
555
628
  turnId,
556
629
  providerMetadata: fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
@@ -569,13 +642,14 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
569
642
  // `mimeType.startsWith`), so the arm rides VERBATIM via
570
643
  // `carryUnmappableArm`'s provider-raw block instead — lossless, never a
571
644
  // fabricated value. Branch order is unchanged: the carry fires exactly
572
- // where the arm would otherwise have mapped. codeExecutionResult already
573
- // defaults both of its optional members, so it needs no guard.
645
+ // where the arm would otherwise have mapped. codeExecutionResult defaults
646
+ // both of its optional members, so only a JSON-null arm needs the carry.
574
647
  if (part.inlineData !== undefined) {
575
648
  const mimeType = stringMember(part.inlineData, "mimeType");
576
649
  const data = stringMember(part.inlineData, "data");
577
650
  if (mimeType !== undefined && data !== undefined) {
578
- a.contentBlock(messageId, inlineDataBlock({ mimeType, data }));
651
+ const displayName = stringMember(part.inlineData, "displayName");
652
+ a.contentBlock(messageId, inlineDataBlock({ mimeType, data, ...(displayName !== undefined ? { displayName } : {}) }));
579
653
  }
580
654
  else {
581
655
  carryUnmappableArm(a, messageId, "inlineData", part.inlineData);
@@ -587,7 +661,9 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
587
661
  if (code !== undefined) {
588
662
  a.contentBlock(messageId, {
589
663
  type: "code",
590
- language: codeLanguage(part.executableCode.language),
664
+ // stringMember: a JSON-null language is absent → "python" (null guard;
665
+ // it was `null.toLowerCase()`).
666
+ language: codeLanguage(stringMember(part.executableCode, "language")),
591
667
  code,
592
668
  });
593
669
  }
@@ -597,11 +673,18 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
597
673
  return "";
598
674
  }
599
675
  if (part.codeExecutionResult !== undefined) {
600
- a.contentBlock(messageId, {
601
- type: "code-result",
602
- outcome: codeOutcome(part.codeExecutionResult.outcome),
603
- output: part.codeExecutionResult.output ?? "",
604
- });
676
+ // Null guard: a JSON-null arm rides provider-raw (it was dereferenced);
677
+ // a null or non-string member is absent and takes its existing default.
678
+ if (isJsonObject(part.codeExecutionResult)) {
679
+ a.contentBlock(messageId, {
680
+ type: "code-result",
681
+ outcome: codeOutcome(stringMember(part.codeExecutionResult, "outcome")),
682
+ output: stringMember(part.codeExecutionResult, "output") ?? "",
683
+ });
684
+ }
685
+ else {
686
+ carryUnmappableArm(a, messageId, "codeExecutionResult", part.codeExecutionResult);
687
+ }
605
688
  return "";
606
689
  }
607
690
  if (part.fileData !== undefined) {
@@ -610,8 +693,22 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
610
693
  a.contentBlock(messageId, {
611
694
  type: "resource-link",
612
695
  uri: fileUri,
613
- mimeType: part.fileData.mimeType,
696
+ // stringMember: a JSON-null mimeType is absent (null guard; it rode
697
+ // the block as `null`, which the schema rejects).
698
+ mimeType: stringMember(part.fileData, "mimeType"),
614
699
  });
700
+ // genai 2.24.0 FileData.displayName: resource-link has no name slot
701
+ // (SPEC §2), so it rides a sibling provider-raw keyed by the wire path.
702
+ // Absent ⇒ byte-identical. (Spec R&D item 5 would map it to an MCP
703
+ // `name` if protocol adds one.)
704
+ const displayName = stringMember(part.fileData, "displayName");
705
+ if (displayName !== undefined) {
706
+ a.contentBlock(messageId, {
707
+ type: "provider-raw",
708
+ vendor: "google",
709
+ raw: { fileData: { displayName } },
710
+ });
711
+ }
615
712
  }
616
713
  else {
617
714
  carryUnmappableArm(a, messageId, "fileData", part.fileData);
@@ -620,6 +717,305 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
620
717
  }
621
718
  return "";
622
719
  }
720
+ // ─── ADK AuthConfig → flat AgAuthConfig view (SPEC §8.0 item 12) ─────────────
721
+ // ADK's AuthConfig (@google/adk 2.1.0 dist/types/auth/auth_tool.d.ts:12-42) is
722
+ // `{ authScheme, rawAuthCredential?, exchangedAuthCredential?, credentialKey }`,
723
+ // with authScheme an OpenAPI v3 SecuritySchemeObject or OIDC-with-config
724
+ // (auth_schemes.d.ts:12, :25). The view maps ONLY what has a native value:
725
+ // - scheme ← authScheme.type, verbatim; no string type → no view at all (the
726
+ // field is required and never invented);
727
+ // - authorizationUrl / tokenUrl / scopes follow ADK's own derivation
728
+ // (dist/esm/auth/auth_handler.js:112-128): OIDC-with-config's
729
+ // authorizationEndpoint / tokenEndpoint / scopes; for oauth2, the first
730
+ // present flow of implicit > authorizationCode > clientCredentials >
731
+ // password, with scopes = the keys of its OpenAPI scopes map;
732
+ // - clientId / audience ← rawAuthCredential.oauth2 (auth_credential.d.ts:35-62).
733
+ // credentialKey, secrets and exchange state never enter the view.
734
+ // ─── ADK auth objects: carry only members known to be non-secret ─────────────
735
+ // An ADK AuthConfig, and the credential objects inside it, can hold credential
736
+ // material. Anything the facet forwards is persisted by hosts (hitl.ask →
737
+ // turn.done paused asks[]; tool-call blocks). So every carrier of an ADK auth
738
+ // object is an ALLOWLIST: a member is forwarded only when it is known to be
739
+ // non-secret, and every other member, at any depth, is omitted. The list is
740
+ // checked against @google/adk 2.1.0 dist/types/auth/auth_tool.d.ts and
741
+ // auth_credential.d.ts. Keys match in camelCase or snake_case (the reserved
742
+ // call's args arrive snake_case at the top level); a kept key keeps its wire
743
+ // spelling.
744
+ //
745
+ // Resume safety (ADK 2.1.0): the credential resume rebuilds the request
746
+ // server-side from the session's own reserved call (auth_preprocessor.js
747
+ // requestedAuthConfigs) and takes only the auth code / response URI from the
748
+ // client's answer (credential_response_binding.js bindCredential; the raw
749
+ // credential is restored from the request). An oauth2/OIDC request always
750
+ // carries a generated authUri (auth_handler.js generateAuthRequest). So what
751
+ // the allowlist omits is never needed to answer the ask.
752
+ const ADK_REQUEST_CREDENTIAL = "adk_request_credential";
753
+ function snakeKey(k) {
754
+ return k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
755
+ }
756
+ /** Copy only the allowlisted members of `v` (camel or snake spelling), each
757
+ * either verbatim (`true`) or through its nested allowlist. */
758
+ function pickAllowed(v, spec) {
759
+ if (!isJsonObject(v))
760
+ return undefined;
761
+ const out = {};
762
+ for (const [name, rule] of Object.entries(spec)) {
763
+ for (const key of name === snakeKey(name) ? [name] : [name, snakeKey(name)]) {
764
+ if (!Object.hasOwn(v, key))
765
+ continue;
766
+ const member = v[key];
767
+ if (member === undefined)
768
+ continue;
769
+ const kept = rule === true ? member : rule(member);
770
+ if (kept !== undefined)
771
+ out[key] = kept;
772
+ }
773
+ }
774
+ return out;
775
+ }
776
+ const OAUTH2_ALLOW = {
777
+ clientId: true,
778
+ authUri: true,
779
+ redirectUri: true,
780
+ scopes: true,
781
+ codeChallengeMethod: true,
782
+ tokenEndpointAuthMethod: true,
783
+ expiresAt: true,
784
+ expiresIn: true,
785
+ audience: true,
786
+ };
787
+ const SERVICE_ACCOUNT_ALLOW = {
788
+ scopes: true,
789
+ useDefaultCredential: true,
790
+ useIdToken: true,
791
+ audience: true,
792
+ serviceAccountCredential: (v) => pickAllowed(v, { projectId: true, clientEmail: true, tokenUri: true, universeDomain: true }),
793
+ };
794
+ const AUTH_CREDENTIAL_ALLOW = {
795
+ authType: true,
796
+ resourceRef: true,
797
+ oauth2: (v) => pickAllowed(v, OAUTH2_ALLOW),
798
+ serviceAccount: (v) => pickAllowed(v, SERVICE_ACCOUNT_ALLOW),
799
+ };
800
+ // The security scheme, member by member: an OpenAPI 3.0 SecuritySchemeObject
801
+ // (openapi-types 12.1.3 OpenAPIV3: http, apiKey, oauth2 and openIdConnect,
802
+ // the type @google/adk 2.1.0's auth_schemes.d.ts names) or ADK's
803
+ // OpenIdConnectWithConfig. Every leaf is a string, a string list or a map of
804
+ // strings, and only those survive. A scheme member no type declares (a vendor
805
+ // extension, a stray field) never rides.
806
+ const schemeString = (v) => (typeof v === "string" ? v : undefined);
807
+ const schemeStringList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
808
+ /** A map this facet rebuilds from native entries never carries an own
809
+ * `__proto__` key (SPEC §13.7): JsonValue.parse drops one, and
810
+ * Object.fromEntries would re-create it as an own property. */
811
+ function isReservedMapKey(k) {
812
+ return k === "__proto__";
813
+ }
814
+ /** OAuth2 flow scopes are a map of scope name -> description; OIDC config
815
+ * scopes are a list. Either keeps only its string entries. */
816
+ const schemeScopes = (v) => Array.isArray(v)
817
+ ? schemeStringList(v)
818
+ : isJsonObject(v)
819
+ ? Object.fromEntries(Object.entries(v).filter((e) => !isReservedMapKey(e[0]) && typeof e[1] === "string"))
820
+ : undefined;
821
+ const OAUTH2_FLOW_ALLOW = {
822
+ authorizationUrl: schemeString,
823
+ tokenUrl: schemeString,
824
+ refreshUrl: schemeString,
825
+ scopes: schemeScopes,
826
+ };
827
+ const AUTH_SCHEME_ALLOW = {
828
+ type: schemeString,
829
+ description: schemeString,
830
+ // http
831
+ scheme: schemeString,
832
+ bearerFormat: schemeString,
833
+ // apiKey (the header/query parameter's name and location, never its value)
834
+ name: schemeString,
835
+ in: schemeString,
836
+ // oauth2 (flows.password is the password-GRANT flow: a tokenUrl and scopes)
837
+ flows: (v) => pickAllowed(v, {
838
+ implicit: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
839
+ password: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
840
+ clientCredentials: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
841
+ authorizationCode: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
842
+ }),
843
+ // openIdConnect
844
+ openIdConnectUrl: schemeString,
845
+ // OpenIdConnectWithConfig
846
+ authorizationEndpoint: schemeString,
847
+ tokenEndpoint: schemeString,
848
+ userinfoEndpoint: schemeString,
849
+ revocationEndpoint: schemeString,
850
+ tokenEndpointAuthMethodsSupported: schemeStringList,
851
+ grantTypesSupported: schemeStringList,
852
+ scopes: schemeScopes,
853
+ };
854
+ const AUTH_CONFIG_ALLOW = {
855
+ authScheme: (v) => pickAllowed(v, AUTH_SCHEME_ALLOW),
856
+ credentialKey: true,
857
+ rawAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
858
+ exchangedAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
859
+ };
860
+ // ─── shared state (state.delta) ──────────────────────────────────────────────
861
+ // ADK itself writes an exchanged AuthCredential into the event's
862
+ // actions.stateDelta on two paths (@google/adk 2.1.0):
863
+ // - a Runner configured with SessionStateCredentialService saves it under the
864
+ // bare credentialKey (session_state_credential_service.js; ToolContext's
865
+ // State writes value AND delta, agents/context.js:37-39, sessions/state.js:97-102);
866
+ // - the Workflow plane's FunctionNode auth resume stores it under
867
+ // "temp:" + credentialKey (auth_handler.js:35-38, :47), and function_node.js
868
+ // copies every new delta entry into the event it yields (:93-127). A Runner
869
+ // removes "temp:" entries from a non-partial event as it appends it to the
870
+ // session, before yielding it; a partial event, or an event read before
871
+ // that append, still carries them.
872
+ // ADK treats any value under the key as a stored credential
873
+ // (hitl_utils.js:131-133), so the entry is omitted whole: a redacted value left
874
+ // behind would read as a credential. Every "temp:" entry is omitted too
875
+ // (invocation-scoped by ADK's contract). Every other entry rides unchanged.
876
+ const ADK_TEMP_STATE_PREFIX = "temp:";
877
+ const AUTH_CREDENTIAL_TYPES = new Set(["apiKey", "http", "oauth2", "openIdConnect", "serviceAccount"]);
878
+ // resourceRef (auth_credential.d.ts:244) names a stored credential: ADK's
879
+ // presence readers treat an object holding it as a held credential.
880
+ const AUTH_CREDENTIAL_MEMBERS = [
881
+ "apiKey",
882
+ "api_key",
883
+ "http",
884
+ "oauth2",
885
+ "serviceAccount",
886
+ "service_account",
887
+ "resourceRef",
888
+ "resource_ref",
889
+ ];
890
+ function isObjectRecord(v) {
891
+ return v !== null && typeof v === "object" && !Array.isArray(v);
892
+ }
893
+ /** An ADK AuthCredential: `authType` (either spelling) is one of ADK's
894
+ * credential types (auth_credential.d.ts) and a credential member is present
895
+ * and non-null. */
896
+ function isAuthCredentialObject(v) {
897
+ const typed = ["authType", "auth_type"].some((k) => {
898
+ const t = Object.hasOwn(v, k) ? v[k] : undefined;
899
+ return typeof t === "string" && AUTH_CREDENTIAL_TYPES.has(t);
900
+ });
901
+ return typed && AUTH_CREDENTIAL_MEMBERS.some((m) => Object.hasOwn(v, m) && v[m] !== null && v[m] !== undefined);
902
+ }
903
+ /** Whether `v` is, or holds at any depth (arrays included), an ADK
904
+ * AuthCredential. Iterative and cycle-safe over the raw native value; a value
905
+ * that cannot be walked counts as holding one, so this never throws. */
906
+ function holdsAuthCredential(v) {
907
+ try {
908
+ const seen = new Set();
909
+ const stack = [v];
910
+ while (stack.length > 0) {
911
+ const x = stack.pop();
912
+ if (x === null || typeof x !== "object" || seen.has(x))
913
+ continue;
914
+ seen.add(x);
915
+ if (Array.isArray(x)) {
916
+ for (const y of x)
917
+ stack.push(y);
918
+ }
919
+ else if (isObjectRecord(x)) {
920
+ if (isAuthCredentialObject(x))
921
+ return true;
922
+ for (const k of Object.keys(x))
923
+ stack.push(x[k]);
924
+ }
925
+ }
926
+ return false;
927
+ }
928
+ catch {
929
+ return true;
930
+ }
931
+ }
932
+ /** The state map ADK yields, minus its "temp:" entries and every entry that
933
+ * holds an ADK AuthCredential, in the original key order. A map with none of
934
+ * those is carried exactly as before. When entries were omitted, a remaining
935
+ * entry that is not JSON is dropped rather than thrown on, since a throw would
936
+ * hand the raw native event to the host's error path. A value that is not a
937
+ * map is carried as before, or as {} if it holds a credential. */
938
+ function scrubStateMap(raw) {
939
+ if (!isObjectRecord(raw))
940
+ return holdsAuthCredential(raw) ? {} : JsonValue.parse(raw);
941
+ const keys = Object.keys(raw);
942
+ const omitted = keys.map((k) => k.startsWith(ADK_TEMP_STATE_PREFIX) || holdsAuthCredential(raw[k]));
943
+ if (!omitted.includes(true))
944
+ return JsonValue.parse(raw);
945
+ const kept = [];
946
+ keys.forEach((k, i) => {
947
+ if (omitted[i] === true || isReservedMapKey(k))
948
+ return;
949
+ const parsed = JsonValue.safeParse(raw[k]);
950
+ if (parsed.success)
951
+ kept.push([k, parsed.data]);
952
+ });
953
+ return Object.fromEntries(kept);
954
+ }
955
+ /** The ADK AuthConfig reduced to its non-secret members ({} for a non-object). */
956
+ function scrubAdkAuthConfig(native) {
957
+ return pickAllowed(native, AUTH_CONFIG_ALLOW) ?? {};
958
+ }
959
+ /** A reserved-credential functionResponse (the client's answer) scrubbed the
960
+ * same way; undefined when the response is not an object. */
961
+ function scrubbedResponse(response) {
962
+ if (!isJsonObject(response))
963
+ return undefined;
964
+ const scrubbed = scrubAdkAuthConfig(response);
965
+ return isJsonObject(scrubbed) ? scrubbed : undefined;
966
+ }
967
+ /** The reserved credential call's args: its id, its message and the scrubbed
968
+ * AuthConfig. Nothing else is forwarded. */
969
+ function scrubCredentialCallArgs(args) {
970
+ return (pickAllowed(args, {
971
+ functionCallId: true,
972
+ message: true,
973
+ authConfig: (v) => scrubAdkAuthConfig(v),
974
+ }) ?? {});
975
+ }
976
+ function adkAuthConfigView(native) {
977
+ if (!isJsonObject(native))
978
+ return undefined;
979
+ const authScheme = native["authScheme"];
980
+ const scheme = stringMember(authScheme, "type");
981
+ if (scheme === undefined || !isJsonObject(authScheme))
982
+ return undefined;
983
+ let authorizationUrl;
984
+ let tokenUrl;
985
+ let scopes;
986
+ if ("authorizationEndpoint" in authScheme) {
987
+ authorizationUrl = stringMember(authScheme, "authorizationEndpoint");
988
+ tokenUrl = stringMember(authScheme, "tokenEndpoint");
989
+ const s = authScheme["scopes"];
990
+ if (Array.isArray(s))
991
+ scopes = s.filter((x) => typeof x === "string");
992
+ }
993
+ else if (scheme === "oauth2") {
994
+ const flows = authScheme["flows"];
995
+ const flow = isJsonObject(flows)
996
+ ? [flows["implicit"], flows["authorizationCode"], flows["clientCredentials"], flows["password"]].find(isJsonObject)
997
+ : undefined;
998
+ if (flow !== undefined) {
999
+ authorizationUrl = stringMember(flow, "authorizationUrl");
1000
+ tokenUrl = stringMember(flow, "tokenUrl");
1001
+ const s = flow["scopes"];
1002
+ if (isJsonObject(s))
1003
+ scopes = Object.keys(s);
1004
+ }
1005
+ }
1006
+ const raw = native["rawAuthCredential"];
1007
+ const oauth2 = isJsonObject(raw) ? raw["oauth2"] : undefined;
1008
+ const clientId = stringMember(oauth2, "clientId");
1009
+ const audience = stringMember(oauth2, "audience");
1010
+ return {
1011
+ scheme,
1012
+ ...(scopes !== undefined ? { scopes } : {}),
1013
+ ...(authorizationUrl !== undefined ? { authorizationUrl } : {}),
1014
+ ...(tokenUrl !== undefined ? { tokenUrl } : {}),
1015
+ ...(clientId !== undefined ? { clientId } : {}),
1016
+ ...(audience !== undefined ? { audience } : {}),
1017
+ };
1018
+ }
623
1019
  /** Append `ask` to the turn's pending-asks list (creating it on first use).
624
1020
  * Preserves emission order — asks accumulate in the order their originating
625
1021
  * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
@@ -631,15 +1027,17 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
631
1027
  else
632
1028
  pendingAsks.set(turnId, [ask]);
633
1029
  }
634
- function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks) {
635
- if (event.inputTranscription?.text !== undefined) {
1030
+ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks) {
1031
+ // typeof: a JSON-null transcription text is absent (null guard; it rode the
1032
+ // text block as `null`, which the schema rejects).
1033
+ if (typeof event.inputTranscription?.text === "string") {
636
1034
  a.contentBlock(messageId, {
637
1035
  type: "text",
638
1036
  text: event.inputTranscription.text,
639
1037
  _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
640
1038
  });
641
1039
  }
642
- if (event.outputTranscription?.text !== undefined) {
1040
+ if (typeof event.outputTranscription?.text === "string") {
643
1041
  a.contentBlock(messageId, {
644
1042
  type: "text",
645
1043
  text: event.outputTranscription.text,
@@ -696,6 +1094,41 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
696
1094
  });
697
1095
  }
698
1096
  }
1097
+ // ── ADK request-input pause → hitl.ask text|form (R&D item 6, step 1) ──
1098
+ // `adk_request_input` is ADK's reserved input-pause call: a workflow
1099
+ // `RequestInput` (args {interruptId, payload, message, response_schema}) or
1100
+ // the `requestInputTool` (args {message, response_schema?}). askId =
1101
+ // toolCallId = the call's id, the id ADK answers with. It is form when
1102
+ // response_schema is a non-null object, else text; payload rides metadata.
1103
+ // Tracked pending, so the pause-ending event closes the turn `paused`
1104
+ // (maybeCloseTurn). Deduped by id across the partial/aggregate re-send. The
1105
+ // call's own tool.start still opens (whether to suppress reserved calls is an
1106
+ // open step-2 decision).
1107
+ if (event.partial !== true) {
1108
+ for (const part of event.content?.parts ?? []) {
1109
+ const fc = part.functionCall;
1110
+ if (!isJsonObject(fc) || fc["name"] !== ADK_REQUEST_INPUT)
1111
+ continue;
1112
+ const callId = stringMember(fc, "id");
1113
+ if (callId === undefined || callId.length === 0 || emittedInputAsks.has(callId))
1114
+ continue;
1115
+ emittedInputAsks.add(callId);
1116
+ const args = isJsonObject(fc["args"]) ? fc["args"] : {};
1117
+ const schema = args["response_schema"];
1118
+ const message = stringMember(args, "message");
1119
+ const payload = args["payload"];
1120
+ const ask = {
1121
+ askId: callId,
1122
+ kind: isJsonObject(schema) ? "form" : "text",
1123
+ toolCallId: callId,
1124
+ ...(message !== undefined ? { message } : {}),
1125
+ ...(isJsonObject(schema) ? { schema } : {}),
1126
+ ...(payload !== undefined ? { metadata: { payload } } : {}),
1127
+ };
1128
+ a.emit({ type: "hitl.ask", ...ask });
1129
+ trackPendingAsk(pendingAsks, turnId, ask);
1130
+ }
1131
+ }
699
1132
  // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
700
1133
  const actions = event.actions;
701
1134
  if (actions !== undefined) {
@@ -705,21 +1138,24 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
705
1138
  if (actions.escalate === true)
706
1139
  a.emit({ type: "handoff", kind: "escalate" });
707
1140
  if (actions.requestedAuthConfigs !== undefined) {
708
- // ADK dict[str, AuthConfig] keyed by function-call-id. The AuthConfig is a
709
- // complex framework-specific object (auth-scheme union + credentials) that
710
- // does not fit the flat AgAuthConfig OAuth projection, so it rides opaque
711
- // in `metadata` (AgJSON: framework-specifics lossless via metadata; SPEC §8
712
- // item 12's sanctioned carrier). The SAME ask fields are tracked in
713
- // `pendingAsks` — if this turn's close-path event turns out to be THIS
714
- // event (or a later one for the same turnId), `maybeCloseTurn` folds them
715
- // into `turn.done.outcome.paused.asks[]` instead of fabricating success
716
- // (audit M26).
1141
+ // ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
1142
+ // `authConfig` is the flat AgAuthConfig VIEW derived by
1143
+ // `adkAuthConfigView` (absent when no string scheme exists). The native
1144
+ // AuthConfig rides WHOLE and verbatim in `metadata.authConfig`, the
1145
+ // item's sanctioned carrier, so the ask stays lossless and the mapped
1146
+ // values may appear twice (sp-protocol confirmed 2026-09-23). The SAME
1147
+ // ask fields are tracked in `pendingAsks`: if this turn's close-path
1148
+ // event turns out to be THIS event (or a later one for the same turnId),
1149
+ // `maybeCloseTurn` folds them into `turn.done.outcome.paused.asks[]`
1150
+ // instead of fabricating success (audit M26).
717
1151
  for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
1152
+ const view = adkAuthConfigView(authConfig);
718
1153
  const ask = {
719
1154
  askId: `auth_${callId}`,
720
1155
  kind: "auth",
721
1156
  toolCallId: callId,
722
- metadata: { authConfig: JsonValue.parse(authConfig) },
1157
+ ...(view !== undefined ? { authConfig: view } : {}),
1158
+ metadata: { authConfig: scrubAdkAuthConfig(JsonValue.parse(authConfig)) },
723
1159
  };
724
1160
  a.emit({ type: "hitl.ask", ...ask });
725
1161
  trackPendingAsk(pendingAsks, turnId, ask);
@@ -746,8 +1182,10 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
746
1182
  trackPendingAsk(pendingAsks, turnId, ask);
747
1183
  }
748
1184
  }
1185
+ // One state.delta per native state change, partial events included; see
1186
+ // scrubStateMap for the entries it omits ({} when none remain).
749
1187
  if (actions.stateDelta !== undefined)
750
- a.emit({ type: "state.delta", patch: JsonValue.parse(actions.stateDelta) });
1188
+ a.emit({ type: "state.delta", patch: scrubStateMap(actions.stateDelta) });
751
1189
  const unmappedActions = {};
752
1190
  if (actions.artifactDelta !== undefined)
753
1191
  unmappedActions["artifactDelta"] = JsonValue.parse(actions.artifactDelta);
@@ -823,12 +1261,13 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
823
1261
  if (event.isScratchpad !== undefined)
824
1262
  unmappedEvent["isScratchpad"] = event.isScratchpad;
825
1263
  // Workflow-plane quartet (2.0.0 peer bump; see the AdkEvent field docs):
826
- // stamped only by dist/esm/workflow/* and round-tripped by the Vertex
827
- // session service — never on a plain LlmAgent runAsync stream, so this is
828
- // the same never-fires-on-captured-wire tolerance class as the
829
- // CompactedEvent projection above. Present-checks throughout (`route` may
830
- // legitimately be `false`/`0`; `output` may be any JSON value incl. null);
831
- // `nodeInfo` rides as a WHOLE object.
1264
+ // stamped only by dist/esm/workflow/* (and round-tripped by the Vertex
1265
+ // session service); a plain LlmAgent runAsync stream carries it only via a
1266
+ // NodeTool. It fires on every Workflow invoke (the e2e workflow capture
1267
+ // agent, observed offline on the real 2.1.0 engine). Present-checks
1268
+ // throughout (`route` may legitimately be `false`/`0`; `output` may be any
1269
+ // JSON value incl. null); `nodeInfo` rides as a WHOLE object. `nodeInfo` is
1270
+ // also READ by maybeCloseTurn's per-event gate and by isAdkPauseEnd.
832
1271
  if (event.output !== undefined)
833
1272
  unmappedEvent["output"] = JsonValue.parse(event.output);
834
1273
  if (event.route !== undefined)
@@ -875,10 +1314,14 @@ export function createAdkNormalizer() {
875
1314
  // (the is_final_response aggregate); the `flush()` truncation path never
876
1315
  // reads it — see the comment there.
877
1316
  const pendingAsks = new Map();
1317
+ // adk_request_input call ids already asked (partial/aggregate re-send dedup).
1318
+ const emittedInputAsks = new Set();
878
1319
  const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
879
1320
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
880
1321
  // content/name correlation maps; lives exactly as long as this Normalizer
881
1322
  // instance (one invoke, per §8.0's lifetime rule).
1323
+ // Per-turn, per-kind block ordinals (INV-BLOCK); lives as long as the invoke.
1324
+ const blockIds = new Map();
882
1325
  const toolCallMint = {
883
1326
  nextOrdinal: 0,
884
1327
  openWindowCounts: new Map(),
@@ -905,19 +1348,49 @@ export function createAdkNormalizer() {
905
1348
  const parts = event.content?.parts ?? [];
906
1349
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
907
1350
  const interrupted = event.interrupted === true;
1351
+ // ── The pause close (R&D item 6, step 1) ──
1352
+ // SPEC §7 "the pause is the turn outcome" (SPEC.md:896): while an ask is
1353
+ // pending, the event with which ADK ENDS the pause (isAdkPauseEnd) closes
1354
+ // the turn `paused` from push(), with finishReason "paused". This runs
1355
+ // before the functionCall early-return, because the confirmation-request
1356
+ // event carries a (reserved) call. Items 12/18 now close on the real wire;
1357
+ // before, their close never fired and the turn flushed as an abort.
1358
+ const pending = pendingAsks.get(turnId);
1359
+ if (!interrupted && pending !== undefined && pending.length > 0 && isAdkPauseEnd(event)) {
1360
+ closedTurns.add(turnId);
1361
+ const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1362
+ a.closeMessage(messageId);
1363
+ a.closeTurnDone(turnId, {
1364
+ outcome: { type: "paused", asks: pending },
1365
+ finishReason: "paused",
1366
+ ...(usage !== undefined ? { usage } : {}),
1367
+ });
1368
+ return;
1369
+ }
908
1370
  const hasCompletion = event.turnComplete === true ||
909
1371
  event.finishReason !== undefined ||
910
1372
  event.errorCode !== undefined;
911
1373
  // is_final_response: a non-partial event with no pending function call and not interrupted.
912
1374
  if (hasFunctionCall || interrupted || !hasCompletion)
913
1375
  return;
914
- closedTurns.add(turnId);
915
1376
  // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
916
1377
  // present ⇒ turn.error (values captured here so the close below needs no
917
1378
  // re-narrowing).
918
1379
  const errorClose = event.errorCode !== undefined && event.errorMessage !== undefined
919
1380
  ? { code: event.errorCode, message: event.errorMessage }
920
1381
  : undefined;
1382
+ // ── The nodeInfo gate (R&D item 6, step 1) ──
1383
+ // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
1384
+ // final text (nodeInfo present) is mid-invocation: closing the invocation
1385
+ // turn on it put the workflow's later events after the terminal and parked
1386
+ // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1387
+ // closes the turn as success. It is a per-EVENT test, never a latch
1388
+ // (NodeTool puts nodeInfo into plain runs too). Error closes stay
1389
+ // immediate. A completed workflow therefore flushes turn.abort until a host
1390
+ // completion signal exists (step 2): a documented known gap.
1391
+ if (errorClose === undefined && event.nodeInfo !== undefined)
1392
+ return;
1393
+ closedTurns.add(turnId);
921
1394
  const rawFinish = event.finishReason ?? event.errorCode;
922
1395
  const finish = resolveFinishReason(rawFinish);
923
1396
  // Lossy finish mappings (resolveFinishReason's lossy arms) land the wire
@@ -948,14 +1421,17 @@ export function createAdkNormalizer() {
948
1421
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
949
1422
  const safety = mapBlockedSafety(event.safetyRatings);
950
1423
  // A turn with pending HITL asks (requestedAuthConfigs /
951
- // requestedToolConfirmations, tracked by `trackPendingAsk` above) closes
952
- // PAUSED, not success — the asks are real, unresolved requests the
953
- // turn is parked on, never a fabricated success (audit M26 / SPEC §8
954
- // items 12 + 18). `finishReason` stays the same mapping either way.
1424
+ // requestedToolConfirmations / adk_request_input, tracked by
1425
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
1426
+ // unresolved requests the turn is parked on, never a fabricated success
1427
+ // (audit M26 / SPEC §8 items 12 + 18). A paused close carries
1428
+ // finishReason "paused" (the HITL value, R&D item 6 step 1), the same as
1429
+ // the pause-end close above.
955
1430
  const asks = pendingAsks.get(turnId);
1431
+ const paused = asks !== undefined && asks.length > 0;
956
1432
  a.closeTurnDone(turnId, {
957
- outcome: asks !== undefined && asks.length > 0 ? { type: "paused", asks } : { type: "success" },
958
- finishReason: finish.value,
1433
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
1434
+ finishReason: paused ? "paused" : finish.value,
959
1435
  ...(usage !== undefined ? { usage } : {}),
960
1436
  ...(safety !== undefined ? { safety } : {}),
961
1437
  });
@@ -975,7 +1451,7 @@ export function createAdkNormalizer() {
975
1451
  // part's text.end below (never a per-segment supplement block).
976
1452
  const citations = mapGroundingCitations(event.groundingMetadata);
977
1453
  const citedPartIndex = citations !== undefined
978
- ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1454
+ ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
979
1455
  : -1;
980
1456
  // Review finding c-i/c-ii: resolve null-id functionResponse correlation
981
1457
  // for the WHOLE event up front, in array order, BEFORE any tool.done is
@@ -989,7 +1465,8 @@ export function createAdkNormalizer() {
989
1465
  const nullIdResponseIds = new Map();
990
1466
  parts.forEach((part, idx) => {
991
1467
  const fr = part.functionResponse;
992
- if (fr === undefined)
1468
+ // A JSON-null arm is carried by driveAdkPart; never dereference it here.
1469
+ if (fr === undefined || !isJsonObject(fr))
993
1470
  return;
994
1471
  if (fr.id != null && fr.id.length > 0)
995
1472
  return; // real id — resolved directly, not via this map
@@ -1000,7 +1477,7 @@ export function createAdkNormalizer() {
1000
1477
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
1001
1478
  const aggregateText = isAggregate
1002
1479
  ? parts
1003
- .filter((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1480
+ .filter((p) => p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1004
1481
  .map((p) => p.text ?? "")
1005
1482
  .join("")
1006
1483
  : "";
@@ -1011,7 +1488,7 @@ export function createAdkNormalizer() {
1011
1488
  const isAggregateText = isAggregate &&
1012
1489
  part.thought !== true &&
1013
1490
  part.functionCall === undefined &&
1014
- part.text !== undefined;
1491
+ typeof part.text === "string";
1015
1492
  if (isAggregateText) {
1016
1493
  if (suppressAggregateText) {
1017
1494
  // NOTE: fully-suppressed aggregate — this event emits NO text.end at all
@@ -1024,7 +1501,7 @@ export function createAdkNormalizer() {
1024
1501
  return;
1025
1502
  }
1026
1503
  if (residualTail.length > 0) {
1027
- const id = `text:${index}`;
1504
+ const id = mintBlockId(blockIds, turnId, "text");
1028
1505
  a.textStart(id, messageId);
1029
1506
  a.textDelta(id, messageId, residualTail);
1030
1507
  a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
@@ -1033,7 +1510,7 @@ export function createAdkNormalizer() {
1033
1510
  accumulated += part.text ?? "";
1034
1511
  return;
1035
1512
  }
1036
- const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, index === citedPartIndex ? citations : undefined);
1513
+ const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, blockIds, index === citedPartIndex ? citations : undefined);
1037
1514
  if (isPartial)
1038
1515
  accumulated += contributed;
1039
1516
  });
@@ -1054,7 +1531,7 @@ export function createAdkNormalizer() {
1054
1531
  // re-mint+re-emit a duplicate tool.start. Entries for windows whose
1055
1532
  // aggregate never arrives simply die with the invoke's closure — bounded,
1056
1533
  // per-invoke.
1057
- driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks); // standalone/content arms (Tasks 4–5)
1534
+ driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks); // standalone/content arms (Tasks 4–5)
1058
1535
  maybeCloseTurn(event, turnId, messageId, isPartial);
1059
1536
  }
1060
1537
  return {
@@ -1075,10 +1552,15 @@ export function createAdkNormalizer() {
1075
1552
  // (the is_final_response aggregate — see `maybeCloseTurn`) is an
1076
1553
  // INTERRUPTED stream, not a resolved pause. A truncated pause is a
1077
1554
  // truncation — `pendingAsks` is never consulted here (audit M26).
1555
+ // The synthetic message.end carries the turn's accumulated usage
1556
+ // (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
1557
+ // Workflow invoke until the host completion signal exists, still reports
1558
+ // the tokens it spent. There is never a turn.done here, so the usage
1559
+ // appears only once.
1078
1560
  for (const turnId of openTurns) {
1079
1561
  if (!closedTurns.has(turnId)) {
1080
1562
  closedTurns.add(turnId);
1081
- a.closeMessage(`msg_${turnId}`);
1563
+ a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
1082
1564
  }
1083
1565
  }
1084
1566
  return a.flush();