@silverprotocol/google-adk 0.6.5 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,488 @@ 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, a tool's credential request inside an LlmAgent):
746
+ // the credential resume rebuilds the request
747
+ // server-side from the session's own reserved call (auth_preprocessor.js
748
+ // requestedAuthConfigs) and takes only the auth code / response URI from the
749
+ // client's answer (credential_response_binding.js bindCredential; the raw
750
+ // credential is restored from the request). An oauth2/OIDC request always
751
+ // carries a generated authUri (auth_handler.js generateAuthRequest). So what
752
+ // the allowlist omits is never needed to answer the ask.
753
+ const ADK_REQUEST_CREDENTIAL = "adk_request_credential";
754
+ function snakeKey(k) {
755
+ return k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
756
+ }
757
+ /** Copy only the allowlisted members of `v` (camel or snake spelling), each
758
+ * either verbatim (`true`) or through its nested allowlist. */
759
+ function pickAllowed(v, spec) {
760
+ if (!isJsonObject(v))
761
+ return undefined;
762
+ const out = {};
763
+ for (const [name, rule] of Object.entries(spec)) {
764
+ for (const key of name === snakeKey(name) ? [name] : [name, snakeKey(name)]) {
765
+ if (!Object.hasOwn(v, key))
766
+ continue;
767
+ const member = v[key];
768
+ if (member === undefined)
769
+ continue;
770
+ const kept = rule === true ? member : rule(member);
771
+ if (kept !== undefined)
772
+ out[key] = kept;
773
+ }
774
+ }
775
+ return out;
776
+ }
777
+ const OAUTH2_ALLOW = {
778
+ clientId: true,
779
+ authUri: true,
780
+ redirectUri: true,
781
+ scopes: true,
782
+ codeChallengeMethod: true,
783
+ tokenEndpointAuthMethod: true,
784
+ expiresAt: true,
785
+ expiresIn: true,
786
+ audience: true,
787
+ };
788
+ const SERVICE_ACCOUNT_ALLOW = {
789
+ scopes: true,
790
+ useDefaultCredential: true,
791
+ useIdToken: true,
792
+ audience: true,
793
+ serviceAccountCredential: (v) => pickAllowed(v, { projectId: true, clientEmail: true, tokenUri: true, universeDomain: true }),
794
+ };
795
+ const AUTH_CREDENTIAL_ALLOW = {
796
+ authType: true,
797
+ resourceRef: true,
798
+ oauth2: (v) => pickAllowed(v, OAUTH2_ALLOW),
799
+ serviceAccount: (v) => pickAllowed(v, SERVICE_ACCOUNT_ALLOW),
800
+ };
801
+ // The security scheme, member by member: an OpenAPI 3.0 SecuritySchemeObject
802
+ // (openapi-types 12.1.3 OpenAPIV3: http, apiKey, oauth2 and openIdConnect,
803
+ // the type @google/adk 2.1.0's auth_schemes.d.ts names) or ADK's
804
+ // OpenIdConnectWithConfig. Every leaf is a string, a string list or a map of
805
+ // strings, and only those survive. A scheme member no type declares (a vendor
806
+ // extension, a stray field) never rides.
807
+ const schemeString = (v) => (typeof v === "string" ? v : undefined);
808
+ const schemeStringList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
809
+ /** A map this facet rebuilds from native entries never carries an own
810
+ * `__proto__` key (SPEC §13.7): JsonValue.parse drops one, and
811
+ * Object.fromEntries would re-create it as an own property. */
812
+ function isReservedMapKey(k) {
813
+ return k === "__proto__";
814
+ }
815
+ /** OAuth2 flow scopes are a map of scope name -> description; OIDC config
816
+ * scopes are a list. Either keeps only its string entries. */
817
+ const schemeScopes = (v) => Array.isArray(v)
818
+ ? schemeStringList(v)
819
+ : isJsonObject(v)
820
+ ? Object.fromEntries(Object.entries(v).filter((e) => !isReservedMapKey(e[0]) && typeof e[1] === "string"))
821
+ : undefined;
822
+ const OAUTH2_FLOW_ALLOW = {
823
+ authorizationUrl: schemeString,
824
+ tokenUrl: schemeString,
825
+ refreshUrl: schemeString,
826
+ scopes: schemeScopes,
827
+ };
828
+ const AUTH_SCHEME_ALLOW = {
829
+ type: schemeString,
830
+ description: schemeString,
831
+ // http
832
+ scheme: schemeString,
833
+ bearerFormat: schemeString,
834
+ // apiKey (the header/query parameter's name and location, never its value)
835
+ name: schemeString,
836
+ in: schemeString,
837
+ // oauth2 (flows.password is the password-GRANT flow: a tokenUrl and scopes)
838
+ flows: (v) => pickAllowed(v, {
839
+ implicit: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
840
+ password: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
841
+ clientCredentials: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
842
+ authorizationCode: (f) => pickAllowed(f, OAUTH2_FLOW_ALLOW),
843
+ }),
844
+ // openIdConnect
845
+ openIdConnectUrl: schemeString,
846
+ // OpenIdConnectWithConfig
847
+ authorizationEndpoint: schemeString,
848
+ tokenEndpoint: schemeString,
849
+ userinfoEndpoint: schemeString,
850
+ revocationEndpoint: schemeString,
851
+ tokenEndpointAuthMethodsSupported: schemeStringList,
852
+ grantTypesSupported: schemeStringList,
853
+ scopes: schemeScopes,
854
+ };
855
+ const AUTH_CONFIG_ALLOW = {
856
+ authScheme: (v) => pickAllowed(v, AUTH_SCHEME_ALLOW),
857
+ credentialKey: true,
858
+ rawAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
859
+ exchangedAuthCredential: (v) => pickAllowed(v, AUTH_CREDENTIAL_ALLOW),
860
+ };
861
+ // ─── shared state (state.delta) ──────────────────────────────────────────────
862
+ // ADK itself writes an exchanged AuthCredential into the event's
863
+ // actions.stateDelta on two paths (@google/adk 2.1.0):
864
+ // - a Runner configured with SessionStateCredentialService saves it under the
865
+ // bare credentialKey (session_state_credential_service.js; ToolContext's
866
+ // State writes value AND delta, agents/context.js:37-39, sessions/state.js:97-102);
867
+ // - a Workflow FunctionNode whose auth step runs again on resume stores it
868
+ // under "temp:" + credentialKey (auth_handler.js:35-38, :47), and function_node.js
869
+ // copies every new delta entry into the event it yields (:93-127). A Runner
870
+ // removes "temp:" entries from a non-partial event as it appends it to the
871
+ // session, before yielding it; a partial event, or an event read before
872
+ // that append, still carries them.
873
+ // ADK treats any value under the key as a stored credential
874
+ // (hitl_utils.js:131-133), so the entry is omitted whole: a redacted value left
875
+ // behind would read as a credential. Every "temp:" entry is omitted too
876
+ // (invocation-scoped by ADK's contract). Every other entry rides unchanged.
877
+ const ADK_TEMP_STATE_PREFIX = "temp:";
878
+ const AUTH_CREDENTIAL_TYPES = new Set(["apiKey", "http", "oauth2", "openIdConnect", "serviceAccount"]);
879
+ // resourceRef (auth_credential.d.ts:244) names a stored credential: ADK's
880
+ // presence readers treat an object holding it as a held credential.
881
+ const AUTH_CREDENTIAL_MEMBERS = [
882
+ "apiKey",
883
+ "api_key",
884
+ "http",
885
+ "oauth2",
886
+ "serviceAccount",
887
+ "service_account",
888
+ "resourceRef",
889
+ "resource_ref",
890
+ ];
891
+ function isObjectRecord(v) {
892
+ return v !== null && typeof v === "object" && !Array.isArray(v);
893
+ }
894
+ /** An ADK AuthCredential: `authType` (either spelling) is one of ADK's
895
+ * credential types (auth_credential.d.ts) and a credential member is present
896
+ * and non-null. */
897
+ function isAuthCredentialObject(v) {
898
+ const typed = ["authType", "auth_type"].some((k) => {
899
+ const t = Object.hasOwn(v, k) ? v[k] : undefined;
900
+ return typeof t === "string" && AUTH_CREDENTIAL_TYPES.has(t);
901
+ });
902
+ return typed && AUTH_CREDENTIAL_MEMBERS.some((m) => Object.hasOwn(v, m) && v[m] !== null && v[m] !== undefined);
903
+ }
904
+ /** Whether `v` is, or holds at any depth (arrays included), an ADK
905
+ * AuthCredential. Iterative and cycle-safe over the raw native value; a value
906
+ * that cannot be walked counts as holding one, so this never throws. */
907
+ function holdsAuthCredential(v) {
908
+ return holdsObject(v, isAuthCredentialObject);
909
+ }
910
+ /** Whether `v` is, or holds at any depth (arrays included), an object `match`
911
+ * accepts. Iterative and cycle-safe over the raw native value; a value that
912
+ * cannot be walked counts as holding one, so this never throws. */
913
+ function holdsObject(v, match) {
914
+ try {
915
+ const seen = new Set();
916
+ const stack = [v];
917
+ while (stack.length > 0) {
918
+ const x = stack.pop();
919
+ if (x === null || typeof x !== "object" || seen.has(x))
920
+ continue;
921
+ seen.add(x);
922
+ if (Array.isArray(x)) {
923
+ for (const y of x)
924
+ stack.push(y);
925
+ }
926
+ else if (isObjectRecord(x)) {
927
+ if (match(x))
928
+ return true;
929
+ for (const k of Object.keys(x))
930
+ stack.push(x[k]);
931
+ }
932
+ }
933
+ return false;
934
+ }
935
+ catch {
936
+ return true;
937
+ }
938
+ }
939
+ /** The state map ADK yields, minus its "temp:" entries and every entry that
940
+ * holds an ADK AuthCredential, in the original key order. A map with none of
941
+ * those is carried exactly as before. When entries were omitted, a remaining
942
+ * entry that is not JSON is dropped rather than thrown on, since a throw would
943
+ * hand the raw native event to the host's error path. A value that is not a
944
+ * map is carried as before, or as {} if it holds a credential. */
945
+ // From push(), an entry whose value is not JSON (ADK allows state.set(k,
946
+ // undefined)) never reaches here: the entry conversion drops it, as JSON
947
+ // serialization does. Under a per-key fold the fold then keeps its prior value
948
+ // for that key while ADK holds undefined (read as absent), which is accepted
949
+ // residue.
950
+ function scrubStateMap(raw) {
951
+ if (!isObjectRecord(raw))
952
+ return holdsAuthCredential(raw) ? {} : JsonValue.parse(raw);
953
+ const keys = Object.keys(raw);
954
+ const omitted = keys.map((k) => k.startsWith(ADK_TEMP_STATE_PREFIX) || holdsAuthCredential(raw[k]));
955
+ if (!omitted.includes(true))
956
+ return JsonValue.parse(raw);
957
+ const kept = [];
958
+ keys.forEach((k, i) => {
959
+ if (omitted[i] === true || isReservedMapKey(k))
960
+ return;
961
+ const parsed = JsonValue.safeParse(raw[k]);
962
+ if (parsed.success)
963
+ kept.push([k, parsed.data]);
964
+ });
965
+ return Object.fromEntries(kept);
966
+ }
967
+ /** The ADK AuthConfig reduced to its non-secret members ({} for a non-object). */
968
+ function scrubAdkAuthConfig(native) {
969
+ return pickAllowed(native, AUTH_CONFIG_ALLOW) ?? {};
970
+ }
971
+ /** A reserved-credential functionResponse (the client's answer) scrubbed the
972
+ * same way; undefined when the response is not an object. */
973
+ function scrubbedResponse(response) {
974
+ if (!isJsonObject(response))
975
+ return undefined;
976
+ const scrubbed = scrubAdkAuthConfig(response);
977
+ return isJsonObject(scrubbed) ? scrubbed : undefined;
978
+ }
979
+ // ─── provider-raw carries of node data ───────────────────────────────────────
980
+ // A Workflow event's `output` and `actions.agentState` ride verbatim in
981
+ // provider-raw. Inside them, each ADK AuthCredential (detected as for shared
982
+ // state) is reduced to its allowlisted members, and each response named
983
+ // adk_request_credential (matched by that name at any depth, never by id)
984
+ // keeps only its id, its name and the reserved-credential answer's
985
+ // allowlisted response, so an untyped reply becomes {}. Every other member
986
+ // rides unchanged. A value with neither is parsed exactly as before; a value
987
+ // that cannot be walked or reduced is omitted, never thrown on.
988
+ /** The native as plain JSON, converted node by node with JSON semantics: an
989
+ * Error becomes {name, message, ...its own enumerable members} without its
990
+ * stack, an undefined, function or symbol member is dropped (null inside an array), a
991
+ * non-finite number becomes null, a value with toJSON (a Date) is read
992
+ * through it, a BigInt becomes its decimal string, a node that repeats one of
993
+ * its own ancestors becomes "[Circular]", and a member whose read throws is
994
+ * dropped. Shared references that are not cycles are copied, as
995
+ * JSON.stringify copies them. A JSON native comes back structurally identical,
996
+ * own keys and their order included. `undefined` when nothing serializable
997
+ * remains, or the value is too deep to walk. Never throws. */
998
+ function asWireJson(native) {
999
+ const ancestors = new Set();
1000
+ const convert = (v, key) => {
1001
+ if (v === null || typeof v === "string" || typeof v === "boolean")
1002
+ return v;
1003
+ if (typeof v === "number")
1004
+ return Number.isFinite(v) ? v : null;
1005
+ if (typeof v === "bigint")
1006
+ return v.toString();
1007
+ if (typeof v !== "object")
1008
+ return undefined;
1009
+ if (ancestors.has(v))
1010
+ return "[Circular]";
1011
+ let toJSON;
1012
+ try {
1013
+ toJSON = Reflect.get(v, "toJSON");
1014
+ }
1015
+ catch {
1016
+ return undefined;
1017
+ }
1018
+ if (typeof toJSON === "function") {
1019
+ let replaced;
1020
+ try {
1021
+ replaced = Reflect.apply(toJSON, v, [key]);
1022
+ }
1023
+ catch {
1024
+ return undefined;
1025
+ }
1026
+ if (replaced !== v) {
1027
+ ancestors.add(v);
1028
+ try {
1029
+ return convert(replaced, key);
1030
+ }
1031
+ finally {
1032
+ ancestors.delete(v);
1033
+ }
1034
+ }
1035
+ }
1036
+ ancestors.add(v);
1037
+ try {
1038
+ if (Array.isArray(v))
1039
+ return v.map((x, i) => convert(x, String(i)) ?? null);
1040
+ const out = {};
1041
+ if (v instanceof Error) {
1042
+ // An Error's name and message are not own enumerable members, so JSON
1043
+ // would drop them; they are read explicitly. Its stack never rides.
1044
+ for (const k of ["name", "message"]) {
1045
+ let member;
1046
+ try {
1047
+ member = Reflect.get(v, k);
1048
+ }
1049
+ catch {
1050
+ continue;
1051
+ }
1052
+ const converted = convert(member, k);
1053
+ if (converted !== undefined)
1054
+ Object.defineProperty(out, k, { value: converted, enumerable: true, writable: true, configurable: true });
1055
+ }
1056
+ }
1057
+ for (const k of Object.keys(v)) {
1058
+ if (k === "stack" && v instanceof Error)
1059
+ continue;
1060
+ let member;
1061
+ try {
1062
+ member = Reflect.get(v, k);
1063
+ }
1064
+ catch {
1065
+ continue;
1066
+ }
1067
+ const converted = convert(member, k);
1068
+ // defineProperty keeps an own key exactly as JSON.parse would create it.
1069
+ if (converted !== undefined)
1070
+ Object.defineProperty(out, k, { value: converted, enumerable: true, writable: true, configurable: true });
1071
+ }
1072
+ return out;
1073
+ }
1074
+ finally {
1075
+ ancestors.delete(v);
1076
+ }
1077
+ };
1078
+ try {
1079
+ return convert(native, "");
1080
+ }
1081
+ catch {
1082
+ return undefined;
1083
+ }
1084
+ }
1085
+ /** A response named adk_request_credential (a functionResponse object). */
1086
+ function isCredentialRequestResponse(v) {
1087
+ return v["name"] === ADK_REQUEST_CREDENTIAL && Object.hasOwn(v, "name") && Object.hasOwn(v, "response");
1088
+ }
1089
+ /** One JSON value with every credential object and credential-request
1090
+ * response reduced (see above); recursion stops at a reduced unit. */
1091
+ function reduceCredentialCarry(v) {
1092
+ if (Array.isArray(v))
1093
+ return v.map(reduceCredentialCarry);
1094
+ if (!isJsonObject(v))
1095
+ return v;
1096
+ if (isAuthCredentialObject(v))
1097
+ return pickAllowed(v, AUTH_CREDENTIAL_ALLOW) ?? {};
1098
+ if (isCredentialRequestResponse(v))
1099
+ return pickAllowed(v, { id: true, name: true, response: (r) => scrubbedResponse(r) }) ?? {};
1100
+ return Object.fromEntries(Object.entries(v)
1101
+ .filter(([k]) => !isReservedMapKey(k))
1102
+ .map(([k, x]) => [k, reduceCredentialCarry(x)]));
1103
+ }
1104
+ /** JSON with object keys in sorted order: "did the reduction change it"
1105
+ * compares members, not the order an allowlist writes them in. */
1106
+ function canonicalJson(v) {
1107
+ if (Array.isArray(v))
1108
+ return `[${v.map(canonicalJson).join(",")}]`;
1109
+ if (!isJsonObject(v))
1110
+ return JSON.stringify(v);
1111
+ return `{${Object.keys(v)
1112
+ .sort()
1113
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k] ?? null)}`)
1114
+ .join(",")}}`;
1115
+ }
1116
+ /** A node-data value for a provider-raw carry. `changed` says whether the
1117
+ * reduction altered it; `undefined` omits the unit. */
1118
+ function carryNodeValue(raw) {
1119
+ if (!holdsAuthCredential(raw) && !holdsObject(raw, isCredentialRequestResponse))
1120
+ return { value: JsonValue.parse(raw), changed: false };
1121
+ try {
1122
+ const before = JsonValue.parse(JSON.parse(JSON.stringify(raw)));
1123
+ const value = reduceCredentialCarry(before);
1124
+ return { value, changed: canonicalJson(value) !== canonicalJson(before) };
1125
+ }
1126
+ catch {
1127
+ return undefined;
1128
+ }
1129
+ }
1130
+ /** JSON.stringify of a raw `output` whose node-data reduction changed or
1131
+ * omitted it: the text ADK renders from that output. `undefined` otherwise
1132
+ * (including a string output, which ADK renders as itself). */
1133
+ function changedOutputRendering(output) {
1134
+ if (output === undefined || output === null || typeof output !== "object")
1135
+ return undefined;
1136
+ // Detection first, so an output holding neither is never parsed here.
1137
+ if (!holdsAuthCredential(output) && !holdsObject(output, isCredentialRequestResponse))
1138
+ return undefined;
1139
+ const carried = carryNodeValue(output);
1140
+ if (carried !== undefined && !carried.changed)
1141
+ return undefined;
1142
+ try {
1143
+ const rendered = JSON.stringify(output);
1144
+ return typeof rendered === "string" ? rendered : undefined;
1145
+ }
1146
+ catch {
1147
+ return undefined;
1148
+ }
1149
+ }
1150
+ /** The reserved credential call's args: its id, its message and the scrubbed
1151
+ * AuthConfig. Nothing else is forwarded. */
1152
+ function scrubCredentialCallArgs(args) {
1153
+ return (pickAllowed(args, {
1154
+ functionCallId: true,
1155
+ message: true,
1156
+ authConfig: (v) => scrubAdkAuthConfig(v),
1157
+ }) ?? {});
1158
+ }
1159
+ function adkAuthConfigView(native) {
1160
+ if (!isJsonObject(native))
1161
+ return undefined;
1162
+ const authScheme = native["authScheme"];
1163
+ const scheme = stringMember(authScheme, "type");
1164
+ if (scheme === undefined || !isJsonObject(authScheme))
1165
+ return undefined;
1166
+ let authorizationUrl;
1167
+ let tokenUrl;
1168
+ let scopes;
1169
+ if ("authorizationEndpoint" in authScheme) {
1170
+ authorizationUrl = stringMember(authScheme, "authorizationEndpoint");
1171
+ tokenUrl = stringMember(authScheme, "tokenEndpoint");
1172
+ const s = authScheme["scopes"];
1173
+ if (Array.isArray(s))
1174
+ scopes = s.filter((x) => typeof x === "string");
1175
+ }
1176
+ else if (scheme === "oauth2") {
1177
+ const flows = authScheme["flows"];
1178
+ const flow = isJsonObject(flows)
1179
+ ? [flows["implicit"], flows["authorizationCode"], flows["clientCredentials"], flows["password"]].find(isJsonObject)
1180
+ : undefined;
1181
+ if (flow !== undefined) {
1182
+ authorizationUrl = stringMember(flow, "authorizationUrl");
1183
+ tokenUrl = stringMember(flow, "tokenUrl");
1184
+ const s = flow["scopes"];
1185
+ if (isJsonObject(s))
1186
+ scopes = Object.keys(s);
1187
+ }
1188
+ }
1189
+ const raw = native["rawAuthCredential"];
1190
+ const oauth2 = isJsonObject(raw) ? raw["oauth2"] : undefined;
1191
+ const clientId = stringMember(oauth2, "clientId");
1192
+ const audience = stringMember(oauth2, "audience");
1193
+ return {
1194
+ scheme,
1195
+ ...(scopes !== undefined ? { scopes } : {}),
1196
+ ...(authorizationUrl !== undefined ? { authorizationUrl } : {}),
1197
+ ...(tokenUrl !== undefined ? { tokenUrl } : {}),
1198
+ ...(clientId !== undefined ? { clientId } : {}),
1199
+ ...(audience !== undefined ? { audience } : {}),
1200
+ };
1201
+ }
623
1202
  /** Append `ask` to the turn's pending-asks list (creating it on first use).
624
1203
  * Preserves emission order — asks accumulate in the order their originating
625
1204
  * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
@@ -631,15 +1210,17 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
631
1210
  else
632
1211
  pendingAsks.set(turnId, [ask]);
633
1212
  }
634
- function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks) {
635
- if (event.inputTranscription?.text !== undefined) {
1213
+ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks) {
1214
+ // typeof: a JSON-null transcription text is absent (null guard; it rode the
1215
+ // text block as `null`, which the schema rejects).
1216
+ if (typeof event.inputTranscription?.text === "string") {
636
1217
  a.contentBlock(messageId, {
637
1218
  type: "text",
638
1219
  text: event.inputTranscription.text,
639
1220
  _meta: { "agjson/transcription": { role: "input", kind: "transcription" } },
640
1221
  });
641
1222
  }
642
- if (event.outputTranscription?.text !== undefined) {
1223
+ if (typeof event.outputTranscription?.text === "string") {
643
1224
  a.contentBlock(messageId, {
644
1225
  type: "text",
645
1226
  text: event.outputTranscription.text,
@@ -696,6 +1277,41 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
696
1277
  });
697
1278
  }
698
1279
  }
1280
+ // ── ADK request-input pause → hitl.ask text|form (R&D item 6, step 1) ──
1281
+ // `adk_request_input` is ADK's reserved input-pause call: a workflow
1282
+ // `RequestInput` (args {interruptId, payload, message, response_schema}) or
1283
+ // the `requestInputTool` (args {message, response_schema?}). askId =
1284
+ // toolCallId = the call's id, the id ADK answers with. It is form when
1285
+ // response_schema is a non-null object, else text; payload rides metadata.
1286
+ // Tracked pending, so the pause-ending event closes the turn `paused`
1287
+ // (maybeCloseTurn). Deduped by id across the partial/aggregate re-send. The
1288
+ // call's own tool.start still opens (whether to suppress reserved calls is an
1289
+ // open step-2 decision).
1290
+ if (event.partial !== true) {
1291
+ for (const part of event.content?.parts ?? []) {
1292
+ const fc = part.functionCall;
1293
+ if (!isJsonObject(fc) || fc["name"] !== ADK_REQUEST_INPUT)
1294
+ continue;
1295
+ const callId = stringMember(fc, "id");
1296
+ if (callId === undefined || callId.length === 0 || emittedInputAsks.has(callId))
1297
+ continue;
1298
+ emittedInputAsks.add(callId);
1299
+ const args = isJsonObject(fc["args"]) ? fc["args"] : {};
1300
+ const schema = args["response_schema"];
1301
+ const message = stringMember(args, "message");
1302
+ const payload = args["payload"];
1303
+ const ask = {
1304
+ askId: callId,
1305
+ kind: isJsonObject(schema) ? "form" : "text",
1306
+ toolCallId: callId,
1307
+ ...(message !== undefined ? { message } : {}),
1308
+ ...(isJsonObject(schema) ? { schema } : {}),
1309
+ ...(payload !== undefined ? { metadata: { payload } } : {}),
1310
+ };
1311
+ a.emit({ type: "hitl.ask", ...ask });
1312
+ trackPendingAsk(pendingAsks, turnId, ask);
1313
+ }
1314
+ }
699
1315
  // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
700
1316
  const actions = event.actions;
701
1317
  if (actions !== undefined) {
@@ -705,21 +1321,24 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
705
1321
  if (actions.escalate === true)
706
1322
  a.emit({ type: "handoff", kind: "escalate" });
707
1323
  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).
1324
+ // ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
1325
+ // `authConfig` is the flat AgAuthConfig VIEW derived by
1326
+ // `adkAuthConfigView` (absent when no string scheme exists). The native
1327
+ // AuthConfig rides WHOLE and verbatim in `metadata.authConfig`, the
1328
+ // item's sanctioned carrier, so the ask stays lossless and the mapped
1329
+ // values may appear twice (sp-protocol confirmed 2026-09-23). The SAME
1330
+ // ask fields are tracked in `pendingAsks`: if this turn's close-path
1331
+ // event turns out to be THIS event (or a later one for the same turnId),
1332
+ // `maybeCloseTurn` folds them into `turn.done.outcome.paused.asks[]`
1333
+ // instead of fabricating success (audit M26).
717
1334
  for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
1335
+ const view = adkAuthConfigView(authConfig);
718
1336
  const ask = {
719
1337
  askId: `auth_${callId}`,
720
1338
  kind: "auth",
721
1339
  toolCallId: callId,
722
- metadata: { authConfig: JsonValue.parse(authConfig) },
1340
+ ...(view !== undefined ? { authConfig: view } : {}),
1341
+ metadata: { authConfig: scrubAdkAuthConfig(JsonValue.parse(authConfig)) },
723
1342
  };
724
1343
  a.emit({ type: "hitl.ask", ...ask });
725
1344
  trackPendingAsk(pendingAsks, turnId, ask);
@@ -746,8 +1365,10 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
746
1365
  trackPendingAsk(pendingAsks, turnId, ask);
747
1366
  }
748
1367
  }
1368
+ // One state.delta per native state change, partial events included; see
1369
+ // scrubStateMap for the entries it omits ({} when none remain).
749
1370
  if (actions.stateDelta !== undefined)
750
- a.emit({ type: "state.delta", patch: JsonValue.parse(actions.stateDelta) });
1371
+ a.emit({ type: "state.delta", patch: scrubStateMap(actions.stateDelta) });
751
1372
  const unmappedActions = {};
752
1373
  if (actions.artifactDelta !== undefined)
753
1374
  unmappedActions["artifactDelta"] = JsonValue.parse(actions.artifactDelta);
@@ -756,8 +1377,11 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
756
1377
  // agentState is an OBJECT on the official 2.0.0 EventActions (a
757
1378
  // resumable-checkpoint snapshot, e.g. `{ input }`), a string on the older
758
1379
  // hand-typed contract — JsonValue.parse at the boundary carries either.
759
- if (actions.agentState !== undefined)
760
- unmappedActions["agentState"] = JsonValue.parse(actions.agentState);
1380
+ if (actions.agentState !== undefined) {
1381
+ const carried = carryNodeValue(actions.agentState);
1382
+ if (carried !== undefined)
1383
+ unmappedActions["agentState"] = carried.value;
1384
+ }
761
1385
  if (actions.endOfAgent !== undefined)
762
1386
  unmappedActions["endOfAgent"] = actions.endOfAgent;
763
1387
  if (Object.keys(unmappedActions).length > 0) {
@@ -823,14 +1447,18 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
823
1447
  if (event.isScratchpad !== undefined)
824
1448
  unmappedEvent["isScratchpad"] = event.isScratchpad;
825
1449
  // 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.
832
- if (event.output !== undefined)
833
- unmappedEvent["output"] = JsonValue.parse(event.output);
1450
+ // stamped only by dist/esm/workflow/* (and round-tripped by the Vertex
1451
+ // session service); a plain LlmAgent runAsync stream carries it only via a
1452
+ // NodeTool. It fires on every Workflow invoke (the e2e workflow capture
1453
+ // agent, observed offline on the real 2.1.0 engine). Present-checks
1454
+ // throughout (`route` may legitimately be `false`/`0`; `output` may be any
1455
+ // JSON value incl. null); `nodeInfo` rides as a WHOLE object. `nodeInfo` is
1456
+ // also READ by maybeCloseTurn's per-event gate and by isAdkPauseEnd.
1457
+ if (event.output !== undefined) {
1458
+ const carried = carryNodeValue(event.output);
1459
+ if (carried !== undefined)
1460
+ unmappedEvent["output"] = carried.value;
1461
+ }
834
1462
  if (event.route !== undefined)
835
1463
  unmappedEvent["route"] = JsonValue.parse(event.route);
836
1464
  if (event.nodeInfo !== undefined)
@@ -850,7 +1478,7 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks)
850
1478
  }
851
1479
  }
852
1480
  // ─── stateful factory: createAdkNormalizer ────────────────────────────────────
853
- export function createAdkNormalizer() {
1481
+ function createAdkInner() {
854
1482
  const a = new StreamAssembler();
855
1483
  const threadId = "google";
856
1484
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
@@ -875,10 +1503,14 @@ export function createAdkNormalizer() {
875
1503
  // (the is_final_response aggregate); the `flush()` truncation path never
876
1504
  // reads it — see the comment there.
877
1505
  const pendingAsks = new Map();
1506
+ // adk_request_input call ids already asked (partial/aggregate re-send dedup).
1507
+ const emittedInputAsks = new Set();
878
1508
  const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
879
1509
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
880
1510
  // content/name correlation maps; lives exactly as long as this Normalizer
881
1511
  // instance (one invoke, per §8.0's lifetime rule).
1512
+ // Per-turn, per-kind block ordinals (INV-BLOCK); lives as long as the invoke.
1513
+ const blockIds = new Map();
882
1514
  const toolCallMint = {
883
1515
  nextOrdinal: 0,
884
1516
  openWindowCounts: new Map(),
@@ -905,19 +1537,49 @@ export function createAdkNormalizer() {
905
1537
  const parts = event.content?.parts ?? [];
906
1538
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
907
1539
  const interrupted = event.interrupted === true;
1540
+ // ── The pause close (R&D item 6, step 1) ──
1541
+ // SPEC §7 "the pause is the turn outcome" (SPEC.md:896): while an ask is
1542
+ // pending, the event with which ADK ENDS the pause (isAdkPauseEnd) closes
1543
+ // the turn `paused` from push(), with finishReason "paused". This runs
1544
+ // before the functionCall early-return, because the confirmation-request
1545
+ // event carries a (reserved) call. Items 12/18 now close on the real wire;
1546
+ // before, their close never fired and the turn flushed as an abort.
1547
+ const pending = pendingAsks.get(turnId);
1548
+ if (!interrupted && pending !== undefined && pending.length > 0 && isAdkPauseEnd(event)) {
1549
+ closedTurns.add(turnId);
1550
+ const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
1551
+ a.closeMessage(messageId);
1552
+ a.closeTurnDone(turnId, {
1553
+ outcome: { type: "paused", asks: pending },
1554
+ finishReason: "paused",
1555
+ ...(usage !== undefined ? { usage } : {}),
1556
+ });
1557
+ return;
1558
+ }
908
1559
  const hasCompletion = event.turnComplete === true ||
909
1560
  event.finishReason !== undefined ||
910
1561
  event.errorCode !== undefined;
911
1562
  // is_final_response: a non-partial event with no pending function call and not interrupted.
912
1563
  if (hasFunctionCall || interrupted || !hasCompletion)
913
1564
  return;
914
- closedTurns.add(turnId);
915
1565
  // The error-close predicate, spelled ONCE: both errorCode AND errorMessage
916
1566
  // present ⇒ turn.error (values captured here so the close below needs no
917
1567
  // re-narrowing).
918
1568
  const errorClose = event.errorCode !== undefined && event.errorMessage !== undefined
919
1569
  ? { code: event.errorCode, message: event.errorMessage }
920
1570
  : undefined;
1571
+ // ── The nodeInfo gate (R&D item 6, step 1) ──
1572
+ // ADK's final-response rule is PER AGENT. On a Workflow invoke a node's
1573
+ // final text (nodeInfo present) is mid-invocation: closing the invocation
1574
+ // turn on it put the workflow's later events after the terminal and parked
1575
+ // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1576
+ // closes the turn as success. It is a per-EVENT test, never a latch
1577
+ // (NodeTool puts nodeInfo into plain runs too). Error closes stay
1578
+ // immediate. A completed workflow therefore flushes turn.abort until a host
1579
+ // completion signal exists (step 2): a documented known gap.
1580
+ if (errorClose === undefined && event.nodeInfo !== undefined)
1581
+ return;
1582
+ closedTurns.add(turnId);
921
1583
  const rawFinish = event.finishReason ?? event.errorCode;
922
1584
  const finish = resolveFinishReason(rawFinish);
923
1585
  // Lossy finish mappings (resolveFinishReason's lossy arms) land the wire
@@ -948,14 +1610,17 @@ export function createAdkNormalizer() {
948
1610
  const usage = mapUsage(usageByTurn.get(turnId) ?? event.usageMetadata);
949
1611
  const safety = mapBlockedSafety(event.safetyRatings);
950
1612
  // 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.
1613
+ // requestedToolConfirmations / adk_request_input, tracked by
1614
+ // `trackPendingAsk` above) closes PAUSED, not success: the asks are real,
1615
+ // unresolved requests the turn is parked on, never a fabricated success
1616
+ // (audit M26 / SPEC §8 items 12 + 18). A paused close carries
1617
+ // finishReason "paused" (the HITL value, R&D item 6 step 1), the same as
1618
+ // the pause-end close above.
955
1619
  const asks = pendingAsks.get(turnId);
1620
+ const paused = asks !== undefined && asks.length > 0;
956
1621
  a.closeTurnDone(turnId, {
957
- outcome: asks !== undefined && asks.length > 0 ? { type: "paused", asks } : { type: "success" },
958
- finishReason: finish.value,
1622
+ outcome: paused ? { type: "paused", asks } : { type: "success" },
1623
+ finishReason: paused ? "paused" : finish.value,
959
1624
  ...(usage !== undefined ? { usage } : {}),
960
1625
  ...(safety !== undefined ? { safety } : {}),
961
1626
  });
@@ -967,6 +1632,19 @@ export function createAdkNormalizer() {
967
1632
  const messageId = ensureOpen(turnId);
968
1633
  const parts = event.content?.parts ?? [];
969
1634
  const isPartial = event.partial === true;
1635
+ // ADK renders an object `output` as the same event's text part, byte-equal
1636
+ // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
1637
+ // When the node-data reduction changed that output, the rendering would
1638
+ // repeat what the reduction removed, so that one part is skipped here and
1639
+ // in the aggregate below. Nothing else matches: not a string output, not
1640
+ // a substring, not model text.
1641
+ const renderedOutput = changedOutputRendering(event.output);
1642
+ const skipped = new Set();
1643
+ if (renderedOutput !== undefined)
1644
+ parts.forEach((p, idx) => {
1645
+ if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput)
1646
+ skipped.add(idx);
1647
+ });
970
1648
  // STREAMED-text citations carrier (audit M22): groundingMetadata is
971
1649
  // EVENT-level, not per-part. A Gemini grounding response carries the full
972
1650
  // grounded answer in a single (non-thought, non-function-call) text part, so
@@ -975,7 +1653,7 @@ export function createAdkNormalizer() {
975
1653
  // part's text.end below (never a per-segment supplement block).
976
1654
  const citations = mapGroundingCitations(event.groundingMetadata);
977
1655
  const citedPartIndex = citations !== undefined
978
- ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1656
+ ? parts.findIndex((p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
979
1657
  : -1;
980
1658
  // Review finding c-i/c-ii: resolve null-id functionResponse correlation
981
1659
  // for the WHOLE event up front, in array order, BEFORE any tool.done is
@@ -989,7 +1667,8 @@ export function createAdkNormalizer() {
989
1667
  const nullIdResponseIds = new Map();
990
1668
  parts.forEach((part, idx) => {
991
1669
  const fr = part.functionResponse;
992
- if (fr === undefined)
1670
+ // A JSON-null arm is carried by driveAdkPart; never dereference it here.
1671
+ if (fr === undefined || !isJsonObject(fr))
993
1672
  return;
994
1673
  if (fr.id != null && fr.id.length > 0)
995
1674
  return; // real id — resolved directly, not via this map
@@ -1000,7 +1679,7 @@ export function createAdkNormalizer() {
1000
1679
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
1001
1680
  const aggregateText = isAggregate
1002
1681
  ? parts
1003
- .filter((p) => p.thought !== true && p.functionCall === undefined && p.text !== undefined)
1682
+ .filter((p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1004
1683
  .map((p) => p.text ?? "")
1005
1684
  .join("")
1006
1685
  : "";
@@ -1008,10 +1687,12 @@ export function createAdkNormalizer() {
1008
1687
  let residualTail = isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
1009
1688
  let accumulated = alreadyStreamed;
1010
1689
  parts.forEach((part, index) => {
1690
+ if (skipped.has(index))
1691
+ return;
1011
1692
  const isAggregateText = isAggregate &&
1012
1693
  part.thought !== true &&
1013
1694
  part.functionCall === undefined &&
1014
- part.text !== undefined;
1695
+ typeof part.text === "string";
1015
1696
  if (isAggregateText) {
1016
1697
  if (suppressAggregateText) {
1017
1698
  // NOTE: fully-suppressed aggregate — this event emits NO text.end at all
@@ -1024,7 +1705,7 @@ export function createAdkNormalizer() {
1024
1705
  return;
1025
1706
  }
1026
1707
  if (residualTail.length > 0) {
1027
- const id = `text:${index}`;
1708
+ const id = mintBlockId(blockIds, turnId, "text");
1028
1709
  a.textStart(id, messageId);
1029
1710
  a.textDelta(id, messageId, residualTail);
1030
1711
  a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
@@ -1033,7 +1714,7 @@ export function createAdkNormalizer() {
1033
1714
  accumulated += part.text ?? "";
1034
1715
  return;
1035
1716
  }
1036
- const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, index === citedPartIndex ? citations : undefined);
1717
+ const contributed = driveAdkPart(a, part, index, event, messageId, turnId, isPartial, assembledToolCalls, toolCallMint, nullIdResponseIds, blockIds, index === citedPartIndex ? citations : undefined);
1037
1718
  if (isPartial)
1038
1719
  accumulated += contributed;
1039
1720
  });
@@ -1054,19 +1735,31 @@ export function createAdkNormalizer() {
1054
1735
  // re-mint+re-emit a duplicate tool.start. Entries for windows whose
1055
1736
  // aggregate never arrives simply die with the invoke's closure — bounded,
1056
1737
  // per-invoke.
1057
- driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks); // standalone/content arms (Tasks 4–5)
1738
+ driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks); // standalone/content arms (Tasks 4–5)
1058
1739
  maybeCloseTurn(event, turnId, messageId, isPartial);
1059
1740
  }
1060
1741
  return {
1061
- push(native) {
1062
- if (!isAdkEvent(native)) {
1063
- a.emitExt("google", "unparsed", { native });
1742
+ accept(json) {
1743
+ if (json === undefined) {
1744
+ a.emitExt("google", "unparsed", { reason: "not-serializable" });
1745
+ return a.drain();
1746
+ }
1747
+ if (!isAdkEvent(json)) {
1748
+ a.emitExt("google", "unparsed", { native: json });
1064
1749
  return a.drain();
1065
1750
  }
1066
- drive(native);
1751
+ drive(json);
1067
1752
  return a.drain();
1068
1753
  },
1069
- flush() {
1754
+ reportError(e) {
1755
+ // A non-terminal core `error` whose code is only the thrown value's
1756
+ // constructor name (e.g. "TypeError"), with a fixed message and no
1757
+ // payload, so nothing from the native reaches it.
1758
+ const code = e instanceof Error ? e.constructor.name : typeof e;
1759
+ a.emit({ type: "error", message: "normalizer error", code });
1760
+ return a.drain();
1761
+ },
1762
+ flush(bare) {
1070
1763
  // Dangling open turns (interrupted stream before a final aggregate):
1071
1764
  // close their message; the ENGINE flush closes the turn itself with
1072
1765
  // turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
@@ -1075,14 +1768,82 @@ export function createAdkNormalizer() {
1075
1768
  // (the is_final_response aggregate — see `maybeCloseTurn`) is an
1076
1769
  // INTERRUPTED stream, not a resolved pause. A truncated pause is a
1077
1770
  // truncation — `pendingAsks` is never consulted here (audit M26).
1771
+ // The synthetic message.end carries the turn's accumulated usage
1772
+ // (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
1773
+ // Workflow invoke until the host completion signal exists, still reports
1774
+ // the tokens it spent. There is never a turn.done here, so the usage
1775
+ // appears only once. `bare` closes without the usage (the last-resort
1776
+ // path, when reading it failed).
1078
1777
  for (const turnId of openTurns) {
1079
1778
  if (!closedTurns.has(turnId)) {
1080
1779
  closedTurns.add(turnId);
1081
- a.closeMessage(`msg_${turnId}`);
1780
+ a.closeMessage(`msg_${turnId}`, bare ? undefined : mapUsage(usageByTurn.get(turnId)));
1082
1781
  }
1083
1782
  }
1084
1783
  return a.flush();
1085
1784
  },
1086
1785
  };
1087
1786
  }
1787
+ /**
1788
+ * The google-adk Normalizer. push() is atomic and never throws (SPEC §8.0):
1789
+ * the native is read once as plain JSON (asWireJson), then mapped. If mapping
1790
+ * throws (an event whose envelope is valid but whose inner members have
1791
+ * unexpected types), the partial batch is discarded, consuming no seq; the
1792
+ * facet is rebuilt by re-driving, silently, every native accepted so far (it
1793
+ * is deterministic: no clock, no randomness, ids from invocationId and
1794
+ * per-invoke ordinals); and one core `error` event is emitted at the next seq.
1795
+ * flush() is guarded the same way and then closes what is open without usage.
1796
+ * Costs: the journal holds a copy of every accepted native for the invoke's
1797
+ * life, and each failure re-drives the accepted prefix.
1798
+ */
1799
+ export function createAdkNormalizer() {
1800
+ let inner = createAdkInner();
1801
+ const journal = [];
1802
+ const rebuild = () => {
1803
+ inner = createAdkInner();
1804
+ try {
1805
+ for (const entry of journal)
1806
+ inner.accept(entry);
1807
+ }
1808
+ catch {
1809
+ // Unreachable: each entry was accepted before by an identical facet.
1810
+ }
1811
+ };
1812
+ return {
1813
+ push(native) {
1814
+ // A host may push the live object ADK yields (the README's usage), and
1815
+ // that can hold undefined members, a Date or another non-JSON value. The
1816
+ // native is read once as plain JSON (see asWireJson), so nothing below
1817
+ // parses a non-JSON value. A native that cannot be serialized at all is
1818
+ // reported without its content.
1819
+ const json = asWireJson(native);
1820
+ // The journal keeps its own copy, taken before mapping, so nothing the
1821
+ // mapping or the host does to the value can change a later re-drive.
1822
+ const entry = json === undefined ? undefined : copyJson(json);
1823
+ try {
1824
+ const out = inner.accept(json);
1825
+ journal.push(entry);
1826
+ return out;
1827
+ }
1828
+ catch (e) {
1829
+ rebuild();
1830
+ return inner.reportError(e);
1831
+ }
1832
+ },
1833
+ flush() {
1834
+ try {
1835
+ return inner.flush(false);
1836
+ }
1837
+ catch (e) {
1838
+ rebuild();
1839
+ return [...inner.reportError(e), ...inner.flush(true)];
1840
+ }
1841
+ },
1842
+ };
1843
+ }
1844
+ /** A deep copy of a plain JSON value. */
1845
+ function copyJson(v) {
1846
+ const copy = JSON.parse(JSON.stringify(v));
1847
+ return copy;
1848
+ }
1088
1849
  //# sourceMappingURL=index.js.map