@silverprotocol/google-adk 0.6.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -48,8 +48,18 @@
48
48
  * surface. The Python ADK uses the snake_case aliases (`turn_complete`,
49
49
  * `function_call`); a runtime adapter would map those before this seam. This
50
50
  * fixture contract is the camelCase wire projection.
51
+ *
52
+ * NOTE on turn ids across invokes: google-adk derives turn ids from ADK's
53
+ * `invocationId`, which ADK-JS mints fresh on every `runAsync` (including a
54
+ * resume), so they don't repeat across the invokes of a fold. ADK-Python's
55
+ * resumable resume reuses `invocation_id`, and this facet also accepts events
56
+ * serialized from Python: fed that resume, it would repeat `turn_${invocationId}`
57
+ * (and the message id derived from it) across the fold. Supporting that path
58
+ * needs a per-invoke stem; it is queued, not part of this release.
51
59
  */
52
- import { AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
60
+ import { AgUsage, AgProviderMeta, JsonValue, StreamAssembler, toJsonValueSafe, withAtomicPush, } from "@silverprotocol/core";
61
+ import { ADK_REQUEST_CREDENTIAL, snakeKey, pickAllowed, scrubStateMap, scrubAdkAuthConfig, scrubbedResponse, carryNodeValue, changedOutputRendering, reduceCarried, scrubCredentialCallArgs, adkAuthConfigView, } from "./auth-objects.js";
62
+ import { isJsonObject, stringMember } from "./json-guards.js";
53
63
  // ─── finishReason → AgFinishReason (spec §4) ──────────────────────────────────
54
64
  // Maps any Gemini/ADK Candidate.finishReason to the neutral AgFinishReason
55
65
  // superset. A bare turnComplete with no reason ⇒ stop.
@@ -109,10 +119,6 @@ export function isLossyFinishReason(reason) {
109
119
  return resolveFinishReason(reason).lossy;
110
120
  }
111
121
  // ─── stateful factory helpers ─────────────────────────────────────────────────
112
- /** True for a non-null, non-array plain JSON object (guard idiom from the OpenAI facet). */
113
- function isJsonObject(v) {
114
- return typeof v === "object" && v !== null && !Array.isArray(v);
115
- }
116
122
  /** Outer-discriminant guard. ADK events carry an object `content` and/or an `invocationId`. */
117
123
  function isAdkEvent(v) {
118
124
  if (!isJsonObject(v))
@@ -242,16 +248,6 @@ function inlineDataBlock(d) {
242
248
  // (spec §2: video = mediaType video/*). It is still a typed media block.
243
249
  return { type: "file", source, ...(d.displayName !== undefined ? { filename: d.displayName } : {}) };
244
250
  }
245
- // ─── genai-optional arm members (adk-13 hardening) ───────────────────────────
246
- // A Part arm's member when it is a string, else undefined. Read through
247
- // `unknown` + `isJsonObject` so a JSON-null arm (a snake_case serializer that
248
- // keeps None) is guarded too, never dereferenced.
249
- function stringMember(arm, key) {
250
- if (!isJsonObject(arm))
251
- return undefined;
252
- const v = arm[key];
253
- return typeof v === "string" ? v : undefined;
254
- }
255
251
  // A media/code arm missing a member its AgBlock arm REQUIRES rides verbatim in
256
252
  // one provider-raw block keyed by its wire Part field name — the same
257
253
  // `{ <field>: <value> }` shape as `driveAdkPart`'s unmapped-part-fields ledger.
@@ -262,7 +258,7 @@ function carryUnmappableArm(a, messageId, field, arm) {
262
258
  a.contentBlock(messageId, {
263
259
  type: "provider-raw",
264
260
  vendor: "google",
265
- raw: JsonValue.parse({ [field]: arm }),
261
+ raw: reduceCarried(JsonValue.parse({ [field]: arm })),
266
262
  });
267
263
  }
268
264
  // ─── executableCode.language → AgBlock.code.language (spec §2) ────────────────
@@ -300,6 +296,80 @@ function codeOutcome(outcome) {
300
296
  // (a dotless nodeInfo.path); that detail is facet-local, not spec.
301
297
  // The caller closes `paused` on one of these only while an ask is pending.
302
298
  const ADK_REQUEST_INPUT = "adk_request_input";
299
+ const ADK_REQUEST_CONFIRMATION = "adk_request_confirmation";
300
+ /** A member of `v` by camelCase or snake_case name. */
301
+ function memberOf(v, name) {
302
+ if (!isJsonObject(v))
303
+ return undefined;
304
+ if (Object.hasOwn(v, name))
305
+ return v[name];
306
+ const snake = snakeKey(name);
307
+ return Object.hasOwn(v, snake) ? v[snake] : undefined;
308
+ }
309
+ /** The ask a reserved adk_request_* call yields (SPEC §8.0 item 26). */
310
+ function reservedCallAsk(name, callId, args) {
311
+ if (name === ADK_REQUEST_INPUT) {
312
+ const schema = args["response_schema"];
313
+ const message = stringMember(args, "message");
314
+ const payload = args["payload"];
315
+ return {
316
+ ask: {
317
+ askId: callId,
318
+ kind: isJsonObject(schema) ? "form" : "text",
319
+ toolCallId: callId,
320
+ resumeBinding: "id",
321
+ ...(message !== undefined ? { message } : {}),
322
+ ...(isJsonObject(schema) ? { schema } : {}),
323
+ ...(payload !== undefined ? { metadata: { payload } } : {}),
324
+ },
325
+ };
326
+ }
327
+ if (name === ADK_REQUEST_CREDENTIAL) {
328
+ const originalId = stringMember(args, "functionCallId") ?? stringMember(args, "function_call_id");
329
+ const authConfig = memberOf(args, "authConfig") ?? null;
330
+ const message = stringMember(args, "message");
331
+ const view = adkAuthConfigView(authConfig);
332
+ return {
333
+ ask: {
334
+ askId: `auth_${callId}`,
335
+ kind: "auth",
336
+ toolCallId: callId,
337
+ resumeBinding: "id",
338
+ ...(message !== undefined ? { message } : {}),
339
+ ...(view !== undefined ? { authConfig: view } : {}),
340
+ metadata: {
341
+ authConfig: scrubAdkAuthConfig(authConfig),
342
+ ...(originalId !== undefined ? { originalFunctionCallId: originalId } : {}),
343
+ },
344
+ },
345
+ ...(originalId !== undefined ? { originalId } : {}),
346
+ };
347
+ }
348
+ // adk_request_confirmation: args {originalFunctionCall {id, name, args}, toolConfirmation {hint, confirmed, payload}}.
349
+ const originalId = stringMember(memberOf(args, "originalFunctionCall"), "id");
350
+ const confirmation = memberOf(args, "toolConfirmation");
351
+ const hint = stringMember(confirmation, "hint");
352
+ const confirmed = memberOf(confirmation, "confirmed");
353
+ const payload = memberOf(confirmation, "payload");
354
+ const metadata = {};
355
+ if (typeof confirmed === "boolean")
356
+ metadata["confirmed"] = confirmed;
357
+ if (payload !== undefined)
358
+ metadata["payload"] = payload;
359
+ if (originalId !== undefined)
360
+ metadata["originalFunctionCallId"] = originalId;
361
+ return {
362
+ ask: {
363
+ askId: `approval_${callId}`,
364
+ kind: "approval",
365
+ toolCallId: callId,
366
+ resumeBinding: "id",
367
+ ...(hint !== undefined ? { message: hint } : {}),
368
+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
369
+ },
370
+ ...(originalId !== undefined ? { originalId } : {}),
371
+ };
372
+ }
303
373
  function isNonEmptyRecord(v) {
304
374
  return isJsonObject(v) && Object.keys(v).length > 0;
305
375
  }
@@ -319,8 +389,75 @@ function isAdkPauseEnd(event) {
319
389
  !path.includes(".") &&
320
390
  (event.longRunningToolIds?.length ?? 0) > 0);
321
391
  }
392
+ /** The event's own turn key: its invocationId, else its id. `undefined` when it
393
+ * has neither; the normalizer then names the turn from its per-instance stem,
394
+ * never a constant that would repeat across the invokes a host folds together. */
322
395
  function turnKey(ev) {
323
- return ev.invocationId && ev.invocationId.length > 0 ? ev.invocationId : ev.id ?? "adk";
396
+ if (ev.invocationId && ev.invocationId.length > 0)
397
+ return ev.invocationId;
398
+ return ev.id !== undefined && ev.id !== null && ev.id.length > 0 ? ev.id : undefined;
399
+ }
400
+ // ─── tool-call positional index (spec §8.2) ───────────────────────────────────
401
+ // Gemini parallel functionCall parts arrive in positional order; when a part's
402
+ // `functionCall.id` is null/absent we synthesize a stable toolCallId AND record
403
+ // the positional index on tool.start/tool-call `providerCallIndex` so re-input can
404
+ // restore name+position correlation when echoing functionResponse parts.
405
+ // ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
406
+ // adk-10, founder-ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
407
+ // answers a failed tool call with a response carrying Gemini's documented
408
+ // `error` key: an unresolvable tool name (functions.js:264), a thrown tool
409
+ // including a thrown MCP call (functions.js:282), several built-in tools.
410
+ // Rules, in order:
411
+ // 1. MCP CallToolResult `isError: true` → "error" + isError.
412
+ // 2. The call id is named in the SAME event's actions.requestedToolConfirmations
413
+ // or actions.requestedAuthConfigs → "ok": ADK's pause placeholder
414
+ // (function_tool.js:139-141, same event per functions.js:422-431); the
415
+ // pause rides hitl.ask (§8.0 items 12 and 18).
416
+ // 3. A declined approval → "denied", no errorText, no isError: an `error`
417
+ // equal to a rejection literal or starting with the policy-engine prefix,
418
+ // or an error_code/errorCode of CONFIRMATION_REJECTED.
419
+ // 4. An `error` present and not null/false/0/"" → "error" + isError, with
420
+ // errorText when it is a string and errorCode from a string
421
+ // error_code/errorCode.
422
+ // 5. Otherwise "ok" (incl. `{status:"error", …}`, out of scope per item 25).
423
+ // `content` always carries the response verbatim (functionResponseToToolDoneFields).
424
+ // Literals pinned at @google/adk 2.1.0: function_tool.js:144,
425
+ // security_plugin.js:75 and :113, run_skill_inline_script_tool.js:160-163.
426
+ const ADK_REJECTION_ERRORS = new Set([
427
+ "This tool call is rejected.",
428
+ "Tool call rejected from confirmation flow.",
429
+ ]);
430
+ const ADK_POLICY_REJECTION_PREFIX = "This tool call is rejected by policy engine.";
431
+ const ADK_REJECTION_ERROR_CODE = "CONFIRMATION_REJECTED";
432
+ function isAdkPausePlaceholder(toolCallId, actions) {
433
+ const confirmations = actions?.requestedToolConfirmations;
434
+ const auths = actions?.requestedAuthConfigs;
435
+ return ((isJsonObject(confirmations) && Object.hasOwn(confirmations, toolCallId)) ||
436
+ (isJsonObject(auths) && Object.hasOwn(auths, toolCallId)));
437
+ }
438
+ function classifyFunctionResponse(response, toolCallId, actions) {
439
+ if (response === undefined)
440
+ return { outcome: "ok" };
441
+ if (response["isError"] === true)
442
+ return { outcome: "error", isError: true };
443
+ if (isAdkPausePlaceholder(toolCallId, actions))
444
+ return { outcome: "ok" };
445
+ const error = response["error"];
446
+ const code = stringMember(response, "error_code") ?? stringMember(response, "errorCode");
447
+ if (code === ADK_REJECTION_ERROR_CODE ||
448
+ (typeof error === "string" &&
449
+ (ADK_REJECTION_ERRORS.has(error) || error.startsWith(ADK_POLICY_REJECTION_PREFIX)))) {
450
+ return { outcome: "denied" };
451
+ }
452
+ if (error !== undefined && error !== null && error !== false && error !== 0 && error !== "") {
453
+ return {
454
+ outcome: "error",
455
+ isError: true,
456
+ ...(typeof error === "string" ? { errorText: error } : {}),
457
+ ...(code !== undefined ? { errorCode: code } : {}),
458
+ };
459
+ }
460
+ return { outcome: "ok" };
324
461
  }
325
462
  function functionResponseToToolDoneFields(name, response) {
326
463
  if (response === undefined)
@@ -338,7 +475,7 @@ function functionResponseToToolDoneFields(name, response) {
338
475
  }
339
476
  }
340
477
  // Preserve any non-text MCP content part losslessly as a provider-raw block.
341
- out.push({ type: "provider-raw", vendor: "google", raw: part });
478
+ out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
342
479
  }
343
480
  const meta = response["_meta"];
344
481
  return {
@@ -441,10 +578,9 @@ function consumeMintedCallId(mint, turnId, name) {
441
578
  return undefined;
442
579
  return queue.shift();
443
580
  }
444
- function mintBlockId(m, turnId, kind) {
445
- const key = `${turnId} ${kind}`;
446
- const n = m.get(key) ?? 0;
447
- m.set(key, n + 1);
581
+ function mintBlockId(m, kind) {
582
+ const n = m.get(kind) ?? 0;
583
+ m.set(kind, n + 1);
448
584
  return `${kind}:${n}`;
449
585
  }
450
586
  function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
@@ -490,12 +626,12 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
490
626
  a.contentBlock(messageId, {
491
627
  type: "provider-raw",
492
628
  vendor: "google",
493
- raw: JsonValue.parse(unmappedPartFields),
629
+ raw: reduceCarried(JsonValue.parse(unmappedPartFields)),
494
630
  });
495
631
  }
496
632
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
497
633
  if (part.thought === true) {
498
- const id = mintBlockId(blockIds, turnId, "reasoning");
634
+ const id = mintBlockId(blockIds, "reasoning");
499
635
  a.reasoningStart(id, messageId);
500
636
  // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
501
637
  if (typeof part.text === "string" && part.text.length > 0)
@@ -515,7 +651,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
515
651
  // falls through to the arms below (a functionCall beside it still maps), and
516
652
  // `null` never reaches textDelta or the streamed-text accumulator.
517
653
  if (typeof part.text === "string") {
518
- const id = mintBlockId(blockIds, turnId, "text");
654
+ const id = mintBlockId(blockIds, "text");
519
655
  const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
520
656
  // STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
521
657
  // event's groundingSupports segments (each already carries its own offsets +
@@ -617,14 +753,17 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
617
753
  a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
618
754
  return "";
619
755
  }
620
- const outcome = fr.response?.["isError"] === true ? "error" : "ok";
756
+ // A JSON-null response is absent (null guard): it was dereferenced below.
757
+ const response = isJsonObject(fr.response) ? fr.response : undefined;
758
+ // A reserved-credential answer carries the client's credential: its content
759
+ // AND its classification use the allowlisted form (see scrubAdkAuthConfig),
760
+ // so nothing omitted can resurface through errorText.
761
+ const carried = fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : response;
621
762
  a.toolDone({
622
763
  toolCallId,
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),
627
- outcome,
764
+ ...functionResponseToToolDoneFields(fr.name, carried),
765
+ // adk-10 / SPEC §8.0 item 25: see classifyFunctionResponse.
766
+ ...classifyFunctionResponse(carried, toolCallId, event.actions),
628
767
  turnId,
629
768
  providerMetadata: fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
630
769
  ? AgProviderMeta.parse({ google: { thoughtSignature: fr.thoughtSignature } })
@@ -706,7 +845,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
706
845
  a.contentBlock(messageId, {
707
846
  type: "provider-raw",
708
847
  vendor: "google",
709
- raw: { fileData: { displayName } },
848
+ raw: reduceCarried({ fileData: { displayName } }),
710
849
  });
711
850
  }
712
851
  }
@@ -717,305 +856,6 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
717
856
  }
718
857
  return "";
719
858
  }
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
- }
1019
859
  /** Append `ask` to the turn's pending-asks list (creating it on first use).
1020
860
  * Preserves emission order — asks accumulate in the order their originating
1021
861
  * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
@@ -1027,7 +867,7 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
1027
867
  else
1028
868
  pendingAsks.set(turnId, [ask]);
1029
869
  }
1030
- function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks) {
870
+ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, reserved) {
1031
871
  // typeof: a JSON-null transcription text is absent (null guard; it rode the
1032
872
  // text block as `null`, which the schema rejects).
1033
873
  if (typeof event.inputTranscription?.text === "string") {
@@ -1094,41 +934,41 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1094
934
  });
1095
935
  }
1096
936
  }
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).
937
+ // ── ADK pause family → hitl.ask (SPEC §8.0 item 26, draft.4; R&D item 6) ──
938
+ // An ADK pause is a functionCall named adk_request_input,
939
+ // adk_request_credential or adk_request_confirmation. Each yields ONE ask:
940
+ // toolCallId = the reserved call's id (the id ADK accepts as the answer),
941
+ // resumeBinding "id", and the ORIGINAL tool-call id (when the call names
942
+ // one) in metadata.originalFunctionCallId. When items 12/18 surface the
943
+ // same request (actions keyed by the original id), the reserved call's ask is
944
+ // the one: the original id is recorded, and those loops skip it. On the real
945
+ // engine the reserved call arrives before, or on the same event as, those
946
+ // actions. Deduped by id across the partial/aggregate re-send. The reserved
947
+ // call's own tool.start still opens (suppressing it is an unwalked decision).
1107
948
  if (event.partial !== true) {
1108
949
  for (const part of event.content?.parts ?? []) {
1109
950
  const fc = part.functionCall;
1110
- if (!isJsonObject(fc) || fc["name"] !== ADK_REQUEST_INPUT)
951
+ if (!isJsonObject(fc))
952
+ continue;
953
+ const name = fc["name"];
954
+ if (name !== ADK_REQUEST_INPUT && name !== ADK_REQUEST_CREDENTIAL && name !== ADK_REQUEST_CONFIRMATION)
1111
955
  continue;
1112
956
  const callId = stringMember(fc, "id");
1113
- if (callId === undefined || callId.length === 0 || emittedInputAsks.has(callId))
957
+ if (callId === undefined || callId.length === 0 || reserved.asked.has(callId))
1114
958
  continue;
1115
- emittedInputAsks.add(callId);
959
+ reserved.asked.add(callId);
1116
960
  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
- };
961
+ const { ask, originalId } = reservedCallAsk(name, callId, args);
962
+ if (originalId !== undefined) {
963
+ const originals = reserved.originalsByTurn.get(turnId) ?? new Set();
964
+ originals.add(originalId);
965
+ reserved.originalsByTurn.set(turnId, originals);
966
+ }
1128
967
  a.emit({ type: "hitl.ask", ...ask });
1129
968
  trackPendingAsk(pendingAsks, turnId, ask);
1130
969
  }
1131
970
  }
971
+ const askedOriginals = reserved.originalsByTurn.get(turnId);
1132
972
  // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
1133
973
  const actions = event.actions;
1134
974
  if (actions !== undefined) {
@@ -1140,15 +980,18 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1140
980
  if (actions.requestedAuthConfigs !== undefined) {
1141
981
  // ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
1142
982
  // `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).
983
+ // `adkAuthConfigView` (absent when no string scheme exists), and
984
+ // `metadata.authConfig` carries the native AuthConfig through the
985
+ // allowlist (scrubAdkAuthConfig). A request the reserved
986
+ // adk_request_credential call already asked for (item 26) yields no
987
+ // second ask. The SAME ask fields are tracked in `pendingAsks`: if this
988
+ // turn's close-path event turns out to be THIS event (or a later one for
989
+ // the same turnId), `maybeCloseTurn` folds them into
990
+ // `turn.done.outcome.paused.asks[]` instead of fabricating success
991
+ // (audit M26).
1151
992
  for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
993
+ if (askedOriginals?.has(callId) === true)
994
+ continue;
1152
995
  const view = adkAuthConfigView(authConfig);
1153
996
  const ask = {
1154
997
  askId: `auth_${callId}`,
@@ -1166,6 +1009,9 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1166
1009
  // `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
1167
1010
  // 18). Tracked in `pendingAsks` for the same paused-close fold as above.
1168
1011
  for (const [callId, conf] of Object.entries(actions.requestedToolConfirmations)) {
1012
+ // Asked already by the reserved adk_request_confirmation call (item 26).
1013
+ if (askedOriginals?.has(callId) === true)
1014
+ continue;
1169
1015
  const metadata = {};
1170
1016
  if (conf.confirmed !== undefined)
1171
1017
  metadata["confirmed"] = conf.confirmed;
@@ -1194,15 +1040,18 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1194
1040
  // agentState is an OBJECT on the official 2.0.0 EventActions (a
1195
1041
  // resumable-checkpoint snapshot, e.g. `{ input }`), a string on the older
1196
1042
  // hand-typed contract — JsonValue.parse at the boundary carries either.
1197
- if (actions.agentState !== undefined)
1198
- unmappedActions["agentState"] = JsonValue.parse(actions.agentState);
1043
+ if (actions.agentState !== undefined) {
1044
+ const carried = carryNodeValue(actions.agentState);
1045
+ if (carried !== undefined)
1046
+ unmappedActions["agentState"] = carried.value;
1047
+ }
1199
1048
  if (actions.endOfAgent !== undefined)
1200
1049
  unmappedActions["endOfAgent"] = actions.endOfAgent;
1201
1050
  if (Object.keys(unmappedActions).length > 0) {
1202
1051
  a.contentBlock(messageId, {
1203
1052
  type: "provider-raw",
1204
1053
  vendor: "google",
1205
- raw: JsonValue.parse(unmappedActions),
1054
+ raw: reduceCarried(JsonValue.parse(unmappedActions)),
1206
1055
  });
1207
1056
  }
1208
1057
  }
@@ -1268,8 +1117,11 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1268
1117
  // throughout (`route` may legitimately be `false`/`0`; `output` may be any
1269
1118
  // JSON value incl. null); `nodeInfo` rides as a WHOLE object. `nodeInfo` is
1270
1119
  // also READ by maybeCloseTurn's per-event gate and by isAdkPauseEnd.
1271
- if (event.output !== undefined)
1272
- unmappedEvent["output"] = JsonValue.parse(event.output);
1120
+ if (event.output !== undefined) {
1121
+ const carried = carryNodeValue(event.output);
1122
+ if (carried !== undefined)
1123
+ unmappedEvent["output"] = carried.value;
1124
+ }
1273
1125
  if (event.route !== undefined)
1274
1126
  unmappedEvent["route"] = JsonValue.parse(event.route);
1275
1127
  if (event.nodeInfo !== undefined)
@@ -1284,12 +1136,102 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1284
1136
  a.contentBlock(messageId, {
1285
1137
  type: "provider-raw",
1286
1138
  vendor: "google",
1287
- raw: JsonValue.parse(unmappedEvent),
1139
+ raw: reduceCarried(JsonValue.parse(unmappedEvent)),
1288
1140
  });
1289
1141
  }
1290
1142
  }
1291
- // ─── stateful factory: createAdkNormalizer ────────────────────────────────────
1292
- export function createAdkNormalizer() {
1143
+ /** The facet-local host-completion native (§8.0 host obligation 4). */
1144
+ export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
1145
+ /**
1146
+ * SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
1147
+ * the stream (e.g. its LLM-call limit), the host catches it and pushes
1148
+ * `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
1149
+ * open turn closes `turn.error` with that code and message. The shape matches the OpenAI
1150
+ * facet's sentinel. A host may build it from the caught Error itself
1151
+ * (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
1152
+ * read from the raw native, so the Error's own message is kept.
1153
+ */
1154
+ export const ADK_HOST_ERROR_TYPE = "__host_error__";
1155
+ /** The host-error sentinel, read from the RAW native (an Error's message is
1156
+ * not an own enumerable member, so a JSON copy would lose it). A usage that is
1157
+ * not a valid AgUsage is dropped. Never throws. */
1158
+ function hostErrorOf(raw) {
1159
+ if (raw === null || typeof raw !== "object")
1160
+ return undefined;
1161
+ try {
1162
+ if (Reflect.get(raw, "type") !== ADK_HOST_ERROR_TYPE)
1163
+ return undefined;
1164
+ const code = Reflect.get(raw, "code");
1165
+ const message = Reflect.get(raw, "message");
1166
+ if (typeof code !== "string" || typeof message !== "string")
1167
+ return undefined;
1168
+ const usageRaw = Reflect.get(raw, "usage");
1169
+ const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
1170
+ const invocationId = Reflect.get(raw, "invocationId");
1171
+ return {
1172
+ code,
1173
+ message,
1174
+ ...(usage?.success === true ? { usage: usage.data } : {}),
1175
+ ...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
1176
+ };
1177
+ }
1178
+ catch {
1179
+ return undefined;
1180
+ }
1181
+ }
1182
+ /** Exactly `{ type: "__host_complete__" }` (one key), as recorded by a capture harness. */
1183
+ function isHostCompleteNative(v) {
1184
+ return isJsonObject(v) && v["type"] === ADK_HOST_COMPLETE_TYPE && Object.keys(v).length === 1;
1185
+ }
1186
+ /**
1187
+ * The google-adk Normalizer: the inner, deterministic normalizer below wrapped
1188
+ * in core's withAtomicPush (the fleet guard ruling). Every push() is atomic:
1189
+ * - The native is read once as plain JSON through core's toJsonValueSafe, so a
1190
+ * host may push the live Event objects ADK yields (undefined members, a
1191
+ * Date, an Error, a cycle) and they map exactly like the recorded corpus.
1192
+ * - If mapping one native throws (an event whose envelope is valid but whose
1193
+ * inner members have unexpected types), its partial batch is discarded
1194
+ * without consuming seq, the inner is rebuilt by re-driving every native
1195
+ * accepted so far (the inner never reads the clock or randomness; ids come
1196
+ * from invocationId and per-invoke ordinals, and the one random stem, for a
1197
+ * host error before any event, is drawn outside the inner and kept), and
1198
+ * ONE core `error {message:
1199
+ * "normalizer error", code: <constructor name>}` takes the next seq, with no
1200
+ * payload and no message text.
1201
+ * - flush() is guarded the same way; the wrapper closes what the consumer saw
1202
+ * open itself, without calling the inner again.
1203
+ * So push() never throws (SPEC §8.0), and no facet state believes a turn,
1204
+ * message or block is open that never reached the wire.
1205
+ */
1206
+ export function createAdkNormalizer(options = {}) {
1207
+ // A per-instance id stem, drawn lazily and only on the paths that need it (an
1208
+ // event with neither invocationId nor id; a host error before any event,
1209
+ // with no invocationId on the sentinel). It lives OUTSIDE the inner, so a
1210
+ // rebuild re-drives to the same ids.
1211
+ const stem = {};
1212
+ return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
1213
+ }
1214
+ /** A random per-instance stem; never called while a replay re-drives, since
1215
+ * the stem is drawn once and kept.
1216
+ *
1217
+ * The `Date.now` + `Math.random` fallback runs only when `crypto.randomUUID`
1218
+ * is absent, which cannot happen on Node >= 19 (a global `crypto`). It is the
1219
+ * facet's one read of the clock or a random source, and it is safe for
1220
+ * determinism: the stem is drawn outside the inner, once, and a
1221
+ * withAtomicPush rebuild reuses it, so the corpus legs that poison the clock
1222
+ * and randomness never reach this call. */
1223
+ function drawIdStem() {
1224
+ const cryptoObj = Reflect.get(globalThis, "crypto");
1225
+ const randomUUID = cryptoObj !== undefined && cryptoObj !== null ? Reflect.get(cryptoObj, "randomUUID") : undefined;
1226
+ if (typeof randomUUID === "function") {
1227
+ const id = Reflect.apply(randomUUID, cryptoObj, []);
1228
+ if (typeof id === "string")
1229
+ return id;
1230
+ }
1231
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1232
+ }
1233
+ function createInnerAdkNormalizer(options, stem) {
1234
+ const hostCompletion = options.hostCompletion === true;
1293
1235
  const a = new StreamAssembler();
1294
1236
  const threadId = "google";
1295
1237
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
@@ -1314,8 +1256,13 @@ export function createAdkNormalizer() {
1314
1256
  // (the is_final_response aggregate); the `flush()` truncation path never
1315
1257
  // reads it — see the comment there.
1316
1258
  const pendingAsks = new Map();
1317
- // adk_request_input call ids already asked (partial/aggregate re-send dedup).
1318
- const emittedInputAsks = new Set();
1259
+ // Pause-family bookkeeping (item 26): reserved-call ids already asked, and the
1260
+ // original tool-call ids their asks cover, per turn.
1261
+ const reserved = { asked: new Set(), originalsByTurn: new Map() };
1262
+ // Host obligation 4 (opt-in): a success close stashed until the sentinel, and
1263
+ // the non-HITL long-running calls still unanswered, per turn.
1264
+ const deferredClose = new Map();
1265
+ const pendingLongRunning = new Map();
1319
1266
  const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
1320
1267
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
1321
1268
  // content/name correlation maps; lives exactly as long as this Normalizer
@@ -1386,10 +1333,25 @@ export function createAdkNormalizer() {
1386
1333
  // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1387
1334
  // closes the turn as success. It is a per-EVENT test, never a latch
1388
1335
  // (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.
1336
+ // immediate. A completed workflow closes success only on the host-completion
1337
+ // event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
1338
+ // it flushes turn.abort.
1391
1339
  if (errorClose === undefined && event.nodeInfo !== undefined)
1392
1340
  return;
1341
+ // Host obligation 4 (opt-in): a SUCCESS close waits for the host-completion
1342
+ // event, because the run may not be over (a SequentialAgent's next agent,
1343
+ // after-agent callback content). The final response is stashed and closed
1344
+ // unchanged on the sentinel, so a stream ending here is byte-identical.
1345
+ // Error and paused closes stay immediate.
1346
+ if (hostCompletion && errorClose === undefined && !((pendingAsks.get(turnId)?.length ?? 0) > 0)) {
1347
+ deferredClose.set(turnId, event);
1348
+ return;
1349
+ }
1350
+ closeOnFinalResponse(event, turnId, messageId, errorClose);
1351
+ }
1352
+ /** The close on a final response: lossy-finish metadata, message.end, then
1353
+ * turn.error or turn.done (paused when asks are pending, else success). */
1354
+ function closeOnFinalResponse(event, turnId, messageId, errorClose) {
1393
1355
  closedTurns.add(turnId);
1394
1356
  const rawFinish = event.finishReason ?? event.errorCode;
1395
1357
  const finish = resolveFinishReason(rawFinish);
@@ -1432,17 +1394,128 @@ export function createAdkNormalizer() {
1432
1394
  a.closeTurnDone(turnId, {
1433
1395
  outcome: paused ? { type: "paused", asks } : { type: "success" },
1434
1396
  finishReason: paused ? "paused" : finish.value,
1397
+ // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
1398
+ // native value verbatim in turn.done.finishReasonRaw. That is the value
1399
+ // finishReason was mapped from: the wire finishReason, or for an
1400
+ // errorCode-only soft close the errorCode. A paused close's "paused" is
1401
+ // not a fallback, so it takes no companion. message.metadata's
1402
+ // rawFinishReason/rawErrorCode carry stays for one cohort.
1403
+ ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
1435
1404
  ...(usage !== undefined ? { usage } : {}),
1436
1405
  ...(safety !== undefined ? { safety } : {}),
1437
1406
  });
1438
1407
  }
1439
1408
  }
1409
+ /** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
1410
+ * pending until its functionResponse arrives. */
1411
+ function trackLongRunning(event, turnId) {
1412
+ const longRunningIds = event.longRunningToolIds ?? [];
1413
+ const pending = pendingLongRunning.get(turnId) ?? new Set();
1414
+ for (const part of event.content?.parts ?? []) {
1415
+ const callId = stringMember(part.functionCall, "id");
1416
+ if (callId !== undefined && longRunningIds.includes(callId))
1417
+ pending.add(callId);
1418
+ const responseId = stringMember(part.functionResponse, "id");
1419
+ if (responseId !== undefined)
1420
+ pending.delete(responseId);
1421
+ }
1422
+ pendingLongRunning.set(turnId, pending);
1423
+ }
1424
+ /** The host-completion event (SPEC §8.0 host obligation 4): the run returned
1425
+ * normally. Each still-open turn closes from push(): paused when an ask is
1426
+ * pending; left to flush() when a non-HITL long-running call is unanswered;
1427
+ * otherwise success (the stashed final response's close, or a plain success
1428
+ * close with the accumulated usage when the run ended on a non-final event,
1429
+ * e.g. a completed Workflow). */
1430
+ function hostComplete() {
1431
+ for (const turnId of openTurns) {
1432
+ if (closedTurns.has(turnId))
1433
+ continue;
1434
+ const messageId = `msg_${turnId}`;
1435
+ const asks = pendingAsks.get(turnId);
1436
+ if (asks !== undefined && asks.length > 0) {
1437
+ closedTurns.add(turnId);
1438
+ const usage = mapUsage(usageByTurn.get(turnId));
1439
+ a.closeMessage(messageId);
1440
+ a.closeTurnDone(turnId, {
1441
+ outcome: { type: "paused", asks },
1442
+ finishReason: "paused",
1443
+ ...(usage !== undefined ? { usage } : {}),
1444
+ });
1445
+ continue;
1446
+ }
1447
+ if ((pendingLongRunning.get(turnId)?.size ?? 0) > 0)
1448
+ continue;
1449
+ const stashed = deferredClose.get(turnId);
1450
+ if (stashed !== undefined) {
1451
+ closeOnFinalResponse(stashed, turnId, messageId, undefined);
1452
+ continue;
1453
+ }
1454
+ closedTurns.add(turnId);
1455
+ const usage = mapUsage(usageByTurn.get(turnId));
1456
+ a.closeMessage(messageId);
1457
+ a.closeTurnDone(turnId, {
1458
+ outcome: { type: "success" },
1459
+ finishReason: "stop",
1460
+ ...(usage !== undefined ? { usage } : {}),
1461
+ });
1462
+ }
1463
+ }
1464
+ /** Host obligation 1: close every still-open turn, innermost first, as
1465
+ * turn.error with the sentinel's code and message (and its usage, else the
1466
+ * turn's accumulated usage). A success close stashed for the host-completion
1467
+ * signal never fires, since the turn is now closed: the run did not
1468
+ * complete. With no turn open, a fresh terminal turn carries the error, so
1469
+ * it is never start-less. */
1470
+ let hostErrorTurns = 0;
1471
+ // The first turn key this invoke drove (its ADK invocationId): the stem of a
1472
+ // fresh terminal turn's id, so the id is unique across the invokes a host
1473
+ // folds together, not only within this one.
1474
+ let firstKey;
1475
+ function hostError(err) {
1476
+ let closed = 0;
1477
+ for (const turnId of [...openTurns].reverse()) {
1478
+ if (closedTurns.has(turnId))
1479
+ continue;
1480
+ closedTurns.add(turnId);
1481
+ const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
1482
+ a.closeMessage(`msg_${turnId}`);
1483
+ a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
1484
+ closed++;
1485
+ }
1486
+ if (closed > 0)
1487
+ return;
1488
+ const base = firstKey ?? err.invocationId ?? (stem.value ??= drawIdStem());
1489
+ const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
1490
+ const messageId = ensureOpen(turnId);
1491
+ closedTurns.add(turnId);
1492
+ a.closeMessage(messageId);
1493
+ a.closeTurnError(turnId, {
1494
+ message: err.message,
1495
+ code: err.code,
1496
+ ...(err.usage !== undefined ? { usage: err.usage } : {}),
1497
+ });
1498
+ }
1440
1499
  function drive(event) {
1441
- const key = turnKey(event);
1500
+ const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
1501
+ firstKey ??= key;
1442
1502
  const turnId = `turn_${key}`;
1443
1503
  const messageId = ensureOpen(turnId);
1444
1504
  const parts = event.content?.parts ?? [];
1445
1505
  const isPartial = event.partial === true;
1506
+ // ADK renders an object `output` as the same event's text part, byte-equal
1507
+ // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
1508
+ // When the node-data reduction changed that output, the rendering would
1509
+ // repeat what the reduction removed, so that one part is skipped here and
1510
+ // in the aggregate below. Nothing else matches: not a string output, not
1511
+ // a substring, not model text.
1512
+ const renderedOutput = changedOutputRendering(event.output);
1513
+ const skipped = new Set();
1514
+ if (renderedOutput !== undefined)
1515
+ parts.forEach((p, idx) => {
1516
+ if (p.thought !== true && typeof p.text === "string" && p.text === renderedOutput)
1517
+ skipped.add(idx);
1518
+ });
1446
1519
  // STREAMED-text citations carrier (audit M22): groundingMetadata is
1447
1520
  // EVENT-level, not per-part. A Gemini grounding response carries the full
1448
1521
  // grounded answer in a single (non-thought, non-function-call) text part, so
@@ -1451,7 +1524,7 @@ export function createAdkNormalizer() {
1451
1524
  // part's text.end below (never a per-segment supplement block).
1452
1525
  const citations = mapGroundingCitations(event.groundingMetadata);
1453
1526
  const citedPartIndex = citations !== undefined
1454
- ? parts.findIndex((p) => p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1527
+ ? parts.findIndex((p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1455
1528
  : -1;
1456
1529
  // Review finding c-i/c-ii: resolve null-id functionResponse correlation
1457
1530
  // for the WHOLE event up front, in array order, BEFORE any tool.done is
@@ -1477,7 +1550,7 @@ export function createAdkNormalizer() {
1477
1550
  const isAggregate = !isPartial && alreadyStreamed.length > 0;
1478
1551
  const aggregateText = isAggregate
1479
1552
  ? parts
1480
- .filter((p) => p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1553
+ .filter((p, idx) => !skipped.has(idx) && p.thought !== true && p.functionCall === undefined && typeof p.text === "string")
1481
1554
  .map((p) => p.text ?? "")
1482
1555
  .join("")
1483
1556
  : "";
@@ -1485,6 +1558,8 @@ export function createAdkNormalizer() {
1485
1558
  let residualTail = isAggregate && !suppressAggregateText ? aggregateText.slice(alreadyStreamed.length) : "";
1486
1559
  let accumulated = alreadyStreamed;
1487
1560
  parts.forEach((part, index) => {
1561
+ if (skipped.has(index))
1562
+ return;
1488
1563
  const isAggregateText = isAggregate &&
1489
1564
  part.thought !== true &&
1490
1565
  part.functionCall === undefined &&
@@ -1501,7 +1576,7 @@ export function createAdkNormalizer() {
1501
1576
  return;
1502
1577
  }
1503
1578
  if (residualTail.length > 0) {
1504
- const id = mintBlockId(blockIds, turnId, "text");
1579
+ const id = mintBlockId(blockIds, "text");
1505
1580
  a.textStart(id, messageId);
1506
1581
  a.textDelta(id, messageId, residualTail);
1507
1582
  a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
@@ -1531,16 +1606,41 @@ export function createAdkNormalizer() {
1531
1606
  // re-mint+re-emit a duplicate tool.start. Entries for windows whose
1532
1607
  // aggregate never arrives simply die with the invoke's closure — bounded,
1533
1608
  // per-invoke.
1534
- driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks); // standalone/content arms (Tasks 4–5)
1609
+ if (!isPartial)
1610
+ trackLongRunning(event, turnId);
1611
+ driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
1535
1612
  maybeCloseTurn(event, turnId, messageId, isPartial);
1536
1613
  }
1537
1614
  return {
1538
1615
  push(native) {
1539
- if (!isAdkEvent(native)) {
1540
- a.emitExt("google", "unparsed", { native });
1616
+ // withAtomicPush has already read the native as plain JSON (see
1617
+ // createAdkNormalizer). The host-error sentinel is checked first: an
1618
+ // Error-built one keeps its message, because core maps an Error to
1619
+ // {name, message, ...own enumerable}.
1620
+ const json = native;
1621
+ const hostErr = hostErrorOf(json);
1622
+ if (hostErr !== undefined) {
1623
+ // Like the completion sentinel below, a host<->facet contract input
1624
+ // (SPEC §8.0 host obligation 1), not a framework native.
1625
+ hostError(hostErr);
1626
+ return a.drain();
1627
+ }
1628
+ if (isHostCompleteNative(json)) {
1629
+ // The host-completion sentinel is a host<->facet contract input (SPEC
1630
+ // §8.0 host obligation 4), like obligation 1's `__host_error__`: NOT a
1631
+ // framework native. So §8.0's graceful-degradation rule ("MUST NOT
1632
+ // silently drop a native event") does not bind it. With the option OFF
1633
+ // it is ignored by design and never reaches the wire as
1634
+ // ext.google.unparsed.
1635
+ if (hostCompletion)
1636
+ hostComplete();
1637
+ return a.drain();
1638
+ }
1639
+ if (!isAdkEvent(json)) {
1640
+ a.emitExt("google", "unparsed", { native: json });
1541
1641
  return a.drain();
1542
1642
  }
1543
- drive(native);
1643
+ drive(json);
1544
1644
  return a.drain();
1545
1645
  },
1546
1646
  flush() {