@silverprotocol/google-adk 0.6.7 → 0.7.1

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,35 @@
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, which this release does not have.
59
+ *
60
+ * NOTE on the Live (bidi) path: a barge-in (`interrupted: true`, from ADK's live
61
+ * aggregator) closes the message, then the turn, as `turn.abort{interrupted}`,
62
+ * after the event's own content, and a turn gets one terminal. That does NOT
63
+ * make a real barge-in session fold. One live session is one ADK invocation,
64
+ * and so one turn here, and ADK delivers the flag first: the interrupted
65
+ * generation's own `usageMetadata` and `turnComplete` follow it, then the
66
+ * reply generation. Those events land in the closed turn until the facet opens
67
+ * a turn per generation, and a reducer parks on them (probe's gemini-3.8-live
68
+ * capture `live-bargein-gemini38live`, @google/adk 2.1.0: the interrupt at
69
+ * native 6, then usage, turnComplete and the reply). A second barge-in, or
70
+ * model content after a completed reply closed the turn (unless
71
+ * `hostCompletion` defers that close), parks the same way. Separately, when
72
+ * text is buffered at the interrupt, ADK yields
73
+ * only the text aggregate, without the flag (utils/live_connection_utils.js,
74
+ * @google/adk 2.1.0), so this facet sees no interrupt and the turn closes at
75
+ * flush as `stream-truncated`.
51
76
  */
52
- import { AgProviderMeta, JsonValue, StreamAssembler, } from "@silverprotocol/core";
77
+ import { AgUsage, AgProviderMeta, JsonValue, StreamAssembler, toJsonValueSafe, withAtomicPush, } from "@silverprotocol/core";
78
+ import { ADK_REQUEST_CREDENTIAL, snakeKey, pickAllowed, scrubStateMap, scrubAdkAuthConfig, scrubbedResponse, carryNodeValue, changedOutputRendering, reduceCarried, scrubCredentialCallArgs, adkAuthConfigView, } from "./auth-objects.js";
79
+ import { isJsonObject, stringMember } from "./json-guards.js";
53
80
  // ─── finishReason → AgFinishReason (spec §4) ──────────────────────────────────
54
81
  // Maps any Gemini/ADK Candidate.finishReason to the neutral AgFinishReason
55
82
  // superset. A bare turnComplete with no reason ⇒ stop.
@@ -109,10 +136,6 @@ export function isLossyFinishReason(reason) {
109
136
  return resolveFinishReason(reason).lossy;
110
137
  }
111
138
  // ─── 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
139
  /** Outer-discriminant guard. ADK events carry an object `content` and/or an `invocationId`. */
117
140
  function isAdkEvent(v) {
118
141
  if (!isJsonObject(v))
@@ -242,16 +265,6 @@ function inlineDataBlock(d) {
242
265
  // (spec §2: video = mediaType video/*). It is still a typed media block.
243
266
  return { type: "file", source, ...(d.displayName !== undefined ? { filename: d.displayName } : {}) };
244
267
  }
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
268
  // A media/code arm missing a member its AgBlock arm REQUIRES rides verbatim in
256
269
  // one provider-raw block keyed by its wire Part field name — the same
257
270
  // `{ <field>: <value> }` shape as `driveAdkPart`'s unmapped-part-fields ledger.
@@ -262,7 +275,7 @@ function carryUnmappableArm(a, messageId, field, arm) {
262
275
  a.contentBlock(messageId, {
263
276
  type: "provider-raw",
264
277
  vendor: "google",
265
- raw: JsonValue.parse({ [field]: arm }),
278
+ raw: reduceCarried(JsonValue.parse({ [field]: arm })),
266
279
  });
267
280
  }
268
281
  // ─── executableCode.language → AgBlock.code.language (spec §2) ────────────────
@@ -300,6 +313,80 @@ function codeOutcome(outcome) {
300
313
  // (a dotless nodeInfo.path); that detail is facet-local, not spec.
301
314
  // The caller closes `paused` on one of these only while an ask is pending.
302
315
  const ADK_REQUEST_INPUT = "adk_request_input";
316
+ const ADK_REQUEST_CONFIRMATION = "adk_request_confirmation";
317
+ /** A member of `v` by camelCase or snake_case name. */
318
+ function memberOf(v, name) {
319
+ if (!isJsonObject(v))
320
+ return undefined;
321
+ if (Object.hasOwn(v, name))
322
+ return v[name];
323
+ const snake = snakeKey(name);
324
+ return Object.hasOwn(v, snake) ? v[snake] : undefined;
325
+ }
326
+ /** The ask a reserved adk_request_* call yields (SPEC §8.0 item 26). */
327
+ function reservedCallAsk(name, callId, args) {
328
+ if (name === ADK_REQUEST_INPUT) {
329
+ const schema = args["response_schema"];
330
+ const message = stringMember(args, "message");
331
+ const payload = args["payload"];
332
+ return {
333
+ ask: {
334
+ askId: callId,
335
+ kind: isJsonObject(schema) ? "form" : "text",
336
+ toolCallId: callId,
337
+ resumeBinding: "id",
338
+ ...(message !== undefined ? { message } : {}),
339
+ ...(isJsonObject(schema) ? { schema } : {}),
340
+ ...(payload !== undefined ? { metadata: { payload } } : {}),
341
+ },
342
+ };
343
+ }
344
+ if (name === ADK_REQUEST_CREDENTIAL) {
345
+ const originalId = stringMember(args, "functionCallId") ?? stringMember(args, "function_call_id");
346
+ const authConfig = memberOf(args, "authConfig") ?? null;
347
+ const message = stringMember(args, "message");
348
+ const view = adkAuthConfigView(authConfig);
349
+ return {
350
+ ask: {
351
+ askId: `auth_${callId}`,
352
+ kind: "auth",
353
+ toolCallId: callId,
354
+ resumeBinding: "id",
355
+ ...(message !== undefined ? { message } : {}),
356
+ ...(view !== undefined ? { authConfig: view } : {}),
357
+ metadata: {
358
+ authConfig: scrubAdkAuthConfig(authConfig),
359
+ ...(originalId !== undefined ? { originalFunctionCallId: originalId } : {}),
360
+ },
361
+ },
362
+ ...(originalId !== undefined ? { originalId } : {}),
363
+ };
364
+ }
365
+ // adk_request_confirmation: args {originalFunctionCall {id, name, args}, toolConfirmation {hint, confirmed, payload}}.
366
+ const originalId = stringMember(memberOf(args, "originalFunctionCall"), "id");
367
+ const confirmation = memberOf(args, "toolConfirmation");
368
+ const hint = stringMember(confirmation, "hint");
369
+ const confirmed = memberOf(confirmation, "confirmed");
370
+ const payload = memberOf(confirmation, "payload");
371
+ const metadata = {};
372
+ if (typeof confirmed === "boolean")
373
+ metadata["confirmed"] = confirmed;
374
+ if (payload !== undefined)
375
+ metadata["payload"] = payload;
376
+ if (originalId !== undefined)
377
+ metadata["originalFunctionCallId"] = originalId;
378
+ return {
379
+ ask: {
380
+ askId: `approval_${callId}`,
381
+ kind: "approval",
382
+ toolCallId: callId,
383
+ resumeBinding: "id",
384
+ ...(hint !== undefined ? { message: hint } : {}),
385
+ ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
386
+ },
387
+ ...(originalId !== undefined ? { originalId } : {}),
388
+ };
389
+ }
303
390
  function isNonEmptyRecord(v) {
304
391
  return isJsonObject(v) && Object.keys(v).length > 0;
305
392
  }
@@ -319,8 +406,75 @@ function isAdkPauseEnd(event) {
319
406
  !path.includes(".") &&
320
407
  (event.longRunningToolIds?.length ?? 0) > 0);
321
408
  }
409
+ /** The event's own turn key: its invocationId, else its id. `undefined` when it
410
+ * has neither; the normalizer then names the turn from its per-instance stem,
411
+ * never a constant that would repeat across the invokes a host folds together. */
322
412
  function turnKey(ev) {
323
- return ev.invocationId && ev.invocationId.length > 0 ? ev.invocationId : ev.id ?? "adk";
413
+ if (ev.invocationId && ev.invocationId.length > 0)
414
+ return ev.invocationId;
415
+ return ev.id !== undefined && ev.id !== null && ev.id.length > 0 ? ev.id : undefined;
416
+ }
417
+ // ─── tool-call positional index (spec §8.2) ───────────────────────────────────
418
+ // Gemini parallel functionCall parts arrive in positional order; when a part's
419
+ // `functionCall.id` is null/absent we synthesize a stable toolCallId AND record
420
+ // the positional index on tool.start/tool-call `providerCallIndex` so re-input can
421
+ // restore name+position correlation when echoing functionResponse parts.
422
+ // ─── functionResponse.response → tool.done outcome (SPEC §8.0 item 25, draft.4) ─
423
+ // adk-10, founder-ruled 2026-09-23 ("Flip on error, approvals kept"). ADK
424
+ // answers a failed tool call with a response carrying Gemini's documented
425
+ // `error` key: an unresolvable tool name (functions.js:264), a thrown tool
426
+ // including a thrown MCP call (functions.js:282), several built-in tools.
427
+ // Rules, in order:
428
+ // 1. MCP CallToolResult `isError: true` → "error" + isError.
429
+ // 2. The call id is named in the SAME event's actions.requestedToolConfirmations
430
+ // or actions.requestedAuthConfigs → "ok": ADK's pause placeholder
431
+ // (function_tool.js:139-141, same event per functions.js:422-431); the
432
+ // pause rides hitl.ask (§8.0 items 12 and 18).
433
+ // 3. A declined approval → "denied", no errorText, no isError: an `error`
434
+ // equal to a rejection literal or starting with the policy-engine prefix,
435
+ // or an error_code/errorCode of CONFIRMATION_REJECTED.
436
+ // 4. An `error` present and not null/false/0/"" → "error" + isError, with
437
+ // errorText when it is a string and errorCode from a string
438
+ // error_code/errorCode.
439
+ // 5. Otherwise "ok" (incl. `{status:"error", …}`, out of scope per item 25).
440
+ // `content` always carries the response verbatim (functionResponseToToolDoneFields).
441
+ // Literals pinned at @google/adk 2.1.0: function_tool.js:144,
442
+ // security_plugin.js:75 and :113, run_skill_inline_script_tool.js:160-163.
443
+ const ADK_REJECTION_ERRORS = new Set([
444
+ "This tool call is rejected.",
445
+ "Tool call rejected from confirmation flow.",
446
+ ]);
447
+ const ADK_POLICY_REJECTION_PREFIX = "This tool call is rejected by policy engine.";
448
+ const ADK_REJECTION_ERROR_CODE = "CONFIRMATION_REJECTED";
449
+ function isAdkPausePlaceholder(toolCallId, actions) {
450
+ const confirmations = actions?.requestedToolConfirmations;
451
+ const auths = actions?.requestedAuthConfigs;
452
+ return ((isJsonObject(confirmations) && Object.hasOwn(confirmations, toolCallId)) ||
453
+ (isJsonObject(auths) && Object.hasOwn(auths, toolCallId)));
454
+ }
455
+ function classifyFunctionResponse(response, toolCallId, actions) {
456
+ if (response === undefined)
457
+ return { outcome: "ok" };
458
+ if (response["isError"] === true)
459
+ return { outcome: "error", isError: true };
460
+ if (isAdkPausePlaceholder(toolCallId, actions))
461
+ return { outcome: "ok" };
462
+ const error = response["error"];
463
+ const code = stringMember(response, "error_code") ?? stringMember(response, "errorCode");
464
+ if (code === ADK_REJECTION_ERROR_CODE ||
465
+ (typeof error === "string" &&
466
+ (ADK_REJECTION_ERRORS.has(error) || error.startsWith(ADK_POLICY_REJECTION_PREFIX)))) {
467
+ return { outcome: "denied" };
468
+ }
469
+ if (error !== undefined && error !== null && error !== false && error !== 0 && error !== "") {
470
+ return {
471
+ outcome: "error",
472
+ isError: true,
473
+ ...(typeof error === "string" ? { errorText: error } : {}),
474
+ ...(code !== undefined ? { errorCode: code } : {}),
475
+ };
476
+ }
477
+ return { outcome: "ok" };
324
478
  }
325
479
  function functionResponseToToolDoneFields(name, response) {
326
480
  if (response === undefined)
@@ -338,7 +492,7 @@ function functionResponseToToolDoneFields(name, response) {
338
492
  }
339
493
  }
340
494
  // Preserve any non-text MCP content part losslessly as a provider-raw block.
341
- out.push({ type: "provider-raw", vendor: "google", raw: part });
495
+ out.push({ type: "provider-raw", vendor: "google", raw: reduceCarried(part) });
342
496
  }
343
497
  const meta = response["_meta"];
344
498
  return {
@@ -441,10 +595,9 @@ function consumeMintedCallId(mint, turnId, name) {
441
595
  return undefined;
442
596
  return queue.shift();
443
597
  }
444
- function mintBlockId(m, turnId, kind) {
445
- const key = `${turnId} ${kind}`;
446
- const n = m.get(key) ?? 0;
447
- m.set(key, n + 1);
598
+ function mintBlockId(m, kind) {
599
+ const n = m.get(kind) ?? 0;
600
+ m.set(kind, n + 1);
448
601
  return `${kind}:${n}`;
449
602
  }
450
603
  function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _assembledToolCalls, mint, nullIdResponseIds, blockIds, citations) {
@@ -490,12 +643,12 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
490
643
  a.contentBlock(messageId, {
491
644
  type: "provider-raw",
492
645
  vendor: "google",
493
- raw: JsonValue.parse(unmappedPartFields),
646
+ raw: reduceCarried(JsonValue.parse(unmappedPartFields)),
494
647
  });
495
648
  }
496
649
  // ── REASONING (thought:true) → reasoning.start/delta/end + opaque signature ──
497
650
  if (part.thought === true) {
498
- const id = mintBlockId(blockIds, turnId, "reasoning");
651
+ const id = mintBlockId(blockIds, "reasoning");
499
652
  a.reasoningStart(id, messageId);
500
653
  // typeof, not `!== undefined`: a JSON-null text is absent (null guard).
501
654
  if (typeof part.text === "string" && part.text.length > 0)
@@ -515,7 +668,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
515
668
  // falls through to the arms below (a functionCall beside it still maps), and
516
669
  // `null` never reaches textDelta or the streamed-text accumulator.
517
670
  if (typeof part.text === "string") {
518
- const id = mintBlockId(blockIds, turnId, "text");
671
+ const id = mintBlockId(blockIds, "text");
519
672
  const signed = part.thoughtSignature !== undefined && part.thoughtSignature.length > 0;
520
673
  // STREAMED-text citations carrier (audit M22): `citations` collects ALL of this
521
674
  // event's groundingSupports segments (each already carries its own offsets +
@@ -617,14 +770,17 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
617
770
  a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
618
771
  return "";
619
772
  }
620
- const outcome = fr.response?.["isError"] === true ? "error" : "ok";
773
+ // A JSON-null response is absent (null guard): it was dereferenced below.
774
+ const response = isJsonObject(fr.response) ? fr.response : undefined;
775
+ // A reserved-credential answer carries the client's credential: its content
776
+ // AND its classification use the allowlisted form (see scrubAdkAuthConfig),
777
+ // so nothing omitted can resurface through errorText.
778
+ const carried = fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : response;
621
779
  a.toolDone({
622
780
  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,
781
+ ...functionResponseToToolDoneFields(fr.name, carried),
782
+ // adk-10 / SPEC §8.0 item 25: see classifyFunctionResponse.
783
+ ...classifyFunctionResponse(carried, toolCallId, event.actions),
628
784
  turnId,
629
785
  providerMetadata: fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
630
786
  ? AgProviderMeta.parse({ google: { thoughtSignature: fr.thoughtSignature } })
@@ -706,7 +862,7 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
706
862
  a.contentBlock(messageId, {
707
863
  type: "provider-raw",
708
864
  vendor: "google",
709
- raw: { fileData: { displayName } },
865
+ raw: reduceCarried({ fileData: { displayName } }),
710
866
  });
711
867
  }
712
868
  }
@@ -717,488 +873,6 @@ function driveAdkPart(a, part, index, event, messageId, turnId, isPartial, _asse
717
873
  }
718
874
  return "";
719
875
  }
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
- }
1202
876
  /** Append `ask` to the turn's pending-asks list (creating it on first use).
1203
877
  * Preserves emission order — asks accumulate in the order their originating
1204
878
  * hitl.ask events were emitted, which `maybeCloseTurn` folds verbatim into
@@ -1210,7 +884,7 @@ function trackPendingAsk(pendingAsks, turnId, ask) {
1210
884
  else
1211
885
  pendingAsks.set(turnId, [ask]);
1212
886
  }
1213
- function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks) {
887
+ function driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved) {
1214
888
  // typeof: a JSON-null transcription text is absent (null guard; it rode the
1215
889
  // text block as `null`, which the schema rejects).
1216
890
  if (typeof event.inputTranscription?.text === "string") {
@@ -1227,15 +901,8 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1227
901
  _meta: { "agjson/transcription": { role: "output", kind: "transcription" } },
1228
902
  });
1229
903
  }
1230
- // ── interrupted → turn.abort ──
1231
- // Mark the turn closed in the FACET's own bookkeeping too (audit M21): without
1232
- // this, `maybeCloseTurn`'s is_final_response path or `flush()` would later
1233
- // fabricate a success `turn.done` for a turn that already aborted — the
1234
- // self-contradiction the audit found.
1235
- if (event.interrupted === true) {
1236
- a.emit({ type: "turn.abort", reason: "interrupted" });
1237
- closedTurns.add(turnId);
1238
- }
904
+ // `interrupted` → turn.abort is closed in drive(), after this event's own
905
+ // content and carries (see closeInterrupted), never here mid-event.
1239
906
  // ── promptFeedback → prompt.blocked ──
1240
907
  if (event.promptFeedback?.blockReason !== undefined) {
1241
908
  const reason = mapBlockReason(event.promptFeedback.blockReason);
@@ -1277,41 +944,41 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1277
944
  });
1278
945
  }
1279
946
  }
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).
947
+ // ── ADK pause family → hitl.ask (SPEC §8.0 item 26, draft.4; R&D item 6) ──
948
+ // An ADK pause is a functionCall named adk_request_input,
949
+ // adk_request_credential or adk_request_confirmation. Each yields ONE ask:
950
+ // toolCallId = the reserved call's id (the id ADK accepts as the answer),
951
+ // resumeBinding "id", and the ORIGINAL tool-call id (when the call names
952
+ // one) in metadata.originalFunctionCallId. When items 12/18 surface the
953
+ // same request (actions keyed by the original id), the reserved call's ask is
954
+ // the one: the original id is recorded, and those loops skip it. On the real
955
+ // engine the reserved call arrives before, or on the same event as, those
956
+ // actions. Deduped by id across the partial/aggregate re-send. The reserved
957
+ // call's own tool.start still opens (suppressing it is an unwalked decision).
1290
958
  if (event.partial !== true) {
1291
959
  for (const part of event.content?.parts ?? []) {
1292
960
  const fc = part.functionCall;
1293
- if (!isJsonObject(fc) || fc["name"] !== ADK_REQUEST_INPUT)
961
+ if (!isJsonObject(fc))
962
+ continue;
963
+ const name = fc["name"];
964
+ if (name !== ADK_REQUEST_INPUT && name !== ADK_REQUEST_CREDENTIAL && name !== ADK_REQUEST_CONFIRMATION)
1294
965
  continue;
1295
966
  const callId = stringMember(fc, "id");
1296
- if (callId === undefined || callId.length === 0 || emittedInputAsks.has(callId))
967
+ if (callId === undefined || callId.length === 0 || reserved.asked.has(callId))
1297
968
  continue;
1298
- emittedInputAsks.add(callId);
969
+ reserved.asked.add(callId);
1299
970
  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
- };
971
+ const { ask, originalId } = reservedCallAsk(name, callId, args);
972
+ if (originalId !== undefined) {
973
+ const originals = reserved.originalsByTurn.get(turnId) ?? new Set();
974
+ originals.add(originalId);
975
+ reserved.originalsByTurn.set(turnId, originals);
976
+ }
1311
977
  a.emit({ type: "hitl.ask", ...ask });
1312
978
  trackPendingAsk(pendingAsks, turnId, ask);
1313
979
  }
1314
980
  }
981
+ const askedOriginals = reserved.originalsByTurn.get(turnId);
1315
982
  // ── actions → handoff / hitl.ask / state.delta / provider-raw bag ──
1316
983
  const actions = event.actions;
1317
984
  if (actions !== undefined) {
@@ -1323,15 +990,18 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1323
990
  if (actions.requestedAuthConfigs !== undefined) {
1324
991
  // ADK dict[str, AuthConfig] keyed by function-call-id (SPEC §8.0 item 12).
1325
992
  // `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).
993
+ // `adkAuthConfigView` (absent when no string scheme exists), and
994
+ // `metadata.authConfig` carries the native AuthConfig through the
995
+ // allowlist (scrubAdkAuthConfig). A request the reserved
996
+ // adk_request_credential call already asked for (item 26) yields no
997
+ // second ask. The SAME ask fields are tracked in `pendingAsks`: if this
998
+ // turn's close-path event turns out to be THIS event (or a later one for
999
+ // the same turnId), `maybeCloseTurn` folds them into
1000
+ // `turn.done.outcome.paused.asks[]` instead of fabricating success
1001
+ // (audit M26).
1334
1002
  for (const [callId, authConfig] of Object.entries(actions.requestedAuthConfigs)) {
1003
+ if (askedOriginals?.has(callId) === true)
1004
+ continue;
1335
1005
  const view = adkAuthConfigView(authConfig);
1336
1006
  const ask = {
1337
1007
  askId: `auth_${callId}`,
@@ -1349,6 +1019,9 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1349
1019
  // `message`; `confirmed`/`payload` ride opaque in `metadata` (SPEC §8 item
1350
1020
  // 18). Tracked in `pendingAsks` for the same paused-close fold as above.
1351
1021
  for (const [callId, conf] of Object.entries(actions.requestedToolConfirmations)) {
1022
+ // Asked already by the reserved adk_request_confirmation call (item 26).
1023
+ if (askedOriginals?.has(callId) === true)
1024
+ continue;
1352
1025
  const metadata = {};
1353
1026
  if (conf.confirmed !== undefined)
1354
1027
  metadata["confirmed"] = conf.confirmed;
@@ -1388,7 +1061,7 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1388
1061
  a.contentBlock(messageId, {
1389
1062
  type: "provider-raw",
1390
1063
  vendor: "google",
1391
- raw: JsonValue.parse(unmappedActions),
1064
+ raw: reduceCarried(JsonValue.parse(unmappedActions)),
1392
1065
  });
1393
1066
  }
1394
1067
  }
@@ -1473,12 +1146,102 @@ function driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks,
1473
1146
  a.contentBlock(messageId, {
1474
1147
  type: "provider-raw",
1475
1148
  vendor: "google",
1476
- raw: JsonValue.parse(unmappedEvent),
1149
+ raw: reduceCarried(JsonValue.parse(unmappedEvent)),
1477
1150
  });
1478
1151
  }
1479
1152
  }
1480
- // ─── stateful factory: createAdkNormalizer ────────────────────────────────────
1481
- function createAdkInner() {
1153
+ /** The facet-local host-completion native (§8.0 host obligation 4). */
1154
+ export const ADK_HOST_COMPLETE_TYPE = "__host_complete__";
1155
+ /**
1156
+ * SPEC §8.0 host obligation 1: when the ADK runtime THROWS instead of ending
1157
+ * the stream (e.g. its LLM-call limit), the host catches it and pushes
1158
+ * `{ type: "__host_error__", code, message, usage?, invocationId? }`. The
1159
+ * open turn closes `turn.error` with that code and message. The shape matches the OpenAI
1160
+ * facet's sentinel. A host may build it from the caught Error itself
1161
+ * (`Object.assign(err, { type: "__host_error__", code })`): the sentinel is
1162
+ * read from the raw native, so the Error's own message is kept.
1163
+ */
1164
+ export const ADK_HOST_ERROR_TYPE = "__host_error__";
1165
+ /** The host-error sentinel, read from the RAW native (an Error's message is
1166
+ * not an own enumerable member, so a JSON copy would lose it). A usage that is
1167
+ * not a valid AgUsage is dropped. Never throws. */
1168
+ function hostErrorOf(raw) {
1169
+ if (raw === null || typeof raw !== "object")
1170
+ return undefined;
1171
+ try {
1172
+ if (Reflect.get(raw, "type") !== ADK_HOST_ERROR_TYPE)
1173
+ return undefined;
1174
+ const code = Reflect.get(raw, "code");
1175
+ const message = Reflect.get(raw, "message");
1176
+ if (typeof code !== "string" || typeof message !== "string")
1177
+ return undefined;
1178
+ const usageRaw = Reflect.get(raw, "usage");
1179
+ const usage = usageRaw === undefined ? undefined : AgUsage.safeParse(toJsonValueSafe(usageRaw));
1180
+ const invocationId = Reflect.get(raw, "invocationId");
1181
+ return {
1182
+ code,
1183
+ message,
1184
+ ...(usage?.success === true ? { usage: usage.data } : {}),
1185
+ ...(typeof invocationId === "string" && invocationId.length > 0 ? { invocationId } : {}),
1186
+ };
1187
+ }
1188
+ catch {
1189
+ return undefined;
1190
+ }
1191
+ }
1192
+ /** Exactly `{ type: "__host_complete__" }` (one key), as recorded by a capture harness. */
1193
+ function isHostCompleteNative(v) {
1194
+ return isJsonObject(v) && v["type"] === ADK_HOST_COMPLETE_TYPE && Object.keys(v).length === 1;
1195
+ }
1196
+ /**
1197
+ * The google-adk Normalizer: the inner, deterministic normalizer below wrapped
1198
+ * in core's withAtomicPush (the fleet guard ruling). Every push() is atomic:
1199
+ * - The native is read once as plain JSON through core's toJsonValueSafe, so a
1200
+ * host may push the live Event objects ADK yields (undefined members, a
1201
+ * Date, an Error, a cycle) and they map exactly like the recorded corpus.
1202
+ * - If mapping one native throws (an event whose envelope is valid but whose
1203
+ * inner members have unexpected types), its partial batch is discarded
1204
+ * without consuming seq, the inner is rebuilt by re-driving every native
1205
+ * accepted so far (the inner never reads the clock or randomness; ids come
1206
+ * from invocationId and per-invoke ordinals, and the one random stem, for a
1207
+ * host error before any event, is drawn outside the inner and kept), and
1208
+ * ONE core `error {message:
1209
+ * "normalizer error", code: <constructor name>}` takes the next seq, with no
1210
+ * payload and no message text.
1211
+ * - flush() is guarded the same way; the wrapper closes what the consumer saw
1212
+ * open itself, without calling the inner again.
1213
+ * So push() never throws (SPEC §8.0), and no facet state believes a turn,
1214
+ * message or block is open that never reached the wire.
1215
+ */
1216
+ export function createAdkNormalizer(options = {}) {
1217
+ // A per-instance id stem, drawn lazily and only on the paths that need it (an
1218
+ // event with neither invocationId nor id; a host error before any event,
1219
+ // with no invocationId on the sentinel). It lives OUTSIDE the inner, so a
1220
+ // rebuild re-drives to the same ids.
1221
+ const stem = {};
1222
+ return withAtomicPush(() => createInnerAdkNormalizer(options, stem));
1223
+ }
1224
+ /** A random per-instance stem; never called while a replay re-drives, since
1225
+ * the stem is drawn once and kept.
1226
+ *
1227
+ * The `Date.now` + `Math.random` fallback runs only when `crypto.randomUUID`
1228
+ * is absent, which cannot happen on Node >= 19 (a global `crypto`). It is the
1229
+ * facet's one read of the clock or a random source, and it is safe for
1230
+ * determinism: the stem is drawn outside the inner, once, and a
1231
+ * withAtomicPush rebuild reuses it, so the corpus legs that poison the clock
1232
+ * and randomness never reach this call. */
1233
+ function drawIdStem() {
1234
+ const cryptoObj = Reflect.get(globalThis, "crypto");
1235
+ const randomUUID = cryptoObj !== undefined && cryptoObj !== null ? Reflect.get(cryptoObj, "randomUUID") : undefined;
1236
+ if (typeof randomUUID === "function") {
1237
+ const id = Reflect.apply(randomUUID, cryptoObj, []);
1238
+ if (typeof id === "string")
1239
+ return id;
1240
+ }
1241
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
1242
+ }
1243
+ function createInnerAdkNormalizer(options, stem) {
1244
+ const hostCompletion = options.hostCompletion === true;
1482
1245
  const a = new StreamAssembler();
1483
1246
  const threadId = "google";
1484
1247
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map):
@@ -1503,8 +1266,19 @@ function createAdkInner() {
1503
1266
  // (the is_final_response aggregate); the `flush()` truncation path never
1504
1267
  // reads it — see the comment there.
1505
1268
  const pendingAsks = new Map();
1506
- // adk_request_input call ids already asked (partial/aggregate re-send dedup).
1507
- const emittedInputAsks = new Set();
1269
+ // Pause-family bookkeeping (item 26): reserved-call ids already asked, and the
1270
+ // original tool-call ids their asks cover, per turn.
1271
+ const reserved = { asked: new Set(), originalsByTurn: new Map() };
1272
+ // Host obligation 4 (opt-in): a success close stashed until the sentinel, and
1273
+ // the non-HITL long-running calls still unanswered, per turn.
1274
+ const deferredClose = new Map();
1275
+ // Live barge-ins (`interrupted: true`, ADK's live aggregator) awaiting their
1276
+ // close. An interrupt on a PARTIAL text event is followed by ADK's full-text
1277
+ // aggregate of the same model turn (utils/live_connection_utils.js:175-178),
1278
+ // so the close waits for the next non-partial event of the turn, or for
1279
+ // flush() / host completion.
1280
+ const interruptPending = new Set();
1281
+ const pendingLongRunning = new Map();
1508
1282
  const assembledToolCalls = new Set(); // FC dedup across partial/aggregate (Task 3)
1509
1283
  // Null-id call mint state (audit M47) — per-invoke ordinal counter + the
1510
1284
  // content/name correlation maps; lives exactly as long as this Normalizer
@@ -1536,7 +1310,7 @@ function createAdkInner() {
1536
1310
  usageByTurn.set(turnId, accumulated);
1537
1311
  const parts = event.content?.parts ?? [];
1538
1312
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
1539
- const interrupted = event.interrupted === true;
1313
+ const interrupted = event.interrupted === true || interruptPending.has(turnId);
1540
1314
  // ── The pause close (R&D item 6, step 1) ──
1541
1315
  // SPEC §7 "the pause is the turn outcome" (SPEC.md:896): while an ask is
1542
1316
  // pending, the event with which ADK ENDS the pause (isAdkPauseEnd) closes
@@ -1575,10 +1349,25 @@ function createAdkInner() {
1575
1349
  // reduce() (INV-MSG, SPEC.md:745/:757). So an event carrying nodeInfo never
1576
1350
  // closes the turn as success. It is a per-EVENT test, never a latch
1577
1351
  // (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.
1352
+ // immediate. A completed workflow closes success only on the host-completion
1353
+ // event (the `hostCompletion` opt-in, §8.0 host obligation 4); without it,
1354
+ // it flushes turn.abort.
1580
1355
  if (errorClose === undefined && event.nodeInfo !== undefined)
1581
1356
  return;
1357
+ // Host obligation 4 (opt-in): a SUCCESS close waits for the host-completion
1358
+ // event, because the run may not be over (a SequentialAgent's next agent,
1359
+ // after-agent callback content). The final response is stashed and closed
1360
+ // unchanged on the sentinel, so a stream ending here is byte-identical.
1361
+ // Error and paused closes stay immediate.
1362
+ if (hostCompletion && errorClose === undefined && !((pendingAsks.get(turnId)?.length ?? 0) > 0)) {
1363
+ deferredClose.set(turnId, event);
1364
+ return;
1365
+ }
1366
+ closeOnFinalResponse(event, turnId, messageId, errorClose);
1367
+ }
1368
+ /** The close on a final response: lossy-finish metadata, message.end, then
1369
+ * turn.error or turn.done (paused when asks are pending, else success). */
1370
+ function closeOnFinalResponse(event, turnId, messageId, errorClose) {
1582
1371
  closedTurns.add(turnId);
1583
1372
  const rawFinish = event.finishReason ?? event.errorCode;
1584
1373
  const finish = resolveFinishReason(rawFinish);
@@ -1621,13 +1410,115 @@ function createAdkInner() {
1621
1410
  a.closeTurnDone(turnId, {
1622
1411
  outcome: paused ? { type: "paused", asks } : { type: "success" },
1623
1412
  finishReason: paused ? "paused" : finish.value,
1413
+ // draft.4 (SPEC.md:941, §10 item 23): a lossy mapping carries the
1414
+ // native value verbatim in turn.done.finishReasonRaw. That is the value
1415
+ // finishReason was mapped from: the wire finishReason, or for an
1416
+ // errorCode-only soft close the errorCode. A paused close's "paused" is
1417
+ // not a fallback, so it takes no companion. message.metadata's
1418
+ // rawFinishReason/rawErrorCode carry stays for one cohort.
1419
+ ...(!paused && rawFinish !== undefined && finish.lossy ? { finishReasonRaw: rawFinish } : {}),
1624
1420
  ...(usage !== undefined ? { usage } : {}),
1625
1421
  ...(safety !== undefined ? { safety } : {}),
1626
1422
  });
1627
1423
  }
1628
1424
  }
1425
+ /** Host obligation 4 bookkeeping: a call named in longRunningToolIds is
1426
+ * pending until its functionResponse arrives. */
1427
+ function trackLongRunning(event, turnId) {
1428
+ const longRunningIds = event.longRunningToolIds ?? [];
1429
+ const pending = pendingLongRunning.get(turnId) ?? new Set();
1430
+ for (const part of event.content?.parts ?? []) {
1431
+ const callId = stringMember(part.functionCall, "id");
1432
+ if (callId !== undefined && longRunningIds.includes(callId))
1433
+ pending.add(callId);
1434
+ const responseId = stringMember(part.functionResponse, "id");
1435
+ if (responseId !== undefined)
1436
+ pending.delete(responseId);
1437
+ }
1438
+ pendingLongRunning.set(turnId, pending);
1439
+ }
1440
+ /** The host-completion event (SPEC §8.0 host obligation 4): the run returned
1441
+ * normally. Each still-open turn closes from push(): paused when an ask is
1442
+ * pending; left to flush() when a non-HITL long-running call is unanswered;
1443
+ * otherwise success (the stashed final response's close, or a plain success
1444
+ * close with the accumulated usage when the run ended on a non-final event,
1445
+ * e.g. a completed Workflow). */
1446
+ function hostComplete() {
1447
+ for (const turnId of openTurns) {
1448
+ if (closedTurns.has(turnId))
1449
+ continue;
1450
+ if (interruptPending.has(turnId)) {
1451
+ closeInterrupted(turnId);
1452
+ continue;
1453
+ }
1454
+ const messageId = `msg_${turnId}`;
1455
+ const asks = pendingAsks.get(turnId);
1456
+ if (asks !== undefined && asks.length > 0) {
1457
+ closedTurns.add(turnId);
1458
+ const usage = mapUsage(usageByTurn.get(turnId));
1459
+ a.closeMessage(messageId);
1460
+ a.closeTurnDone(turnId, {
1461
+ outcome: { type: "paused", asks },
1462
+ finishReason: "paused",
1463
+ ...(usage !== undefined ? { usage } : {}),
1464
+ });
1465
+ continue;
1466
+ }
1467
+ if ((pendingLongRunning.get(turnId)?.size ?? 0) > 0)
1468
+ continue;
1469
+ const stashed = deferredClose.get(turnId);
1470
+ if (stashed !== undefined) {
1471
+ closeOnFinalResponse(stashed, turnId, messageId, undefined);
1472
+ continue;
1473
+ }
1474
+ closedTurns.add(turnId);
1475
+ const usage = mapUsage(usageByTurn.get(turnId));
1476
+ a.closeMessage(messageId);
1477
+ a.closeTurnDone(turnId, {
1478
+ outcome: { type: "success" },
1479
+ finishReason: "stop",
1480
+ ...(usage !== undefined ? { usage } : {}),
1481
+ });
1482
+ }
1483
+ }
1484
+ /** Host obligation 1: close every still-open turn, innermost first, as
1485
+ * turn.error with the sentinel's code and message (and its usage, else the
1486
+ * turn's accumulated usage). A success close stashed for the host-completion
1487
+ * signal never fires, since the turn is now closed: the run did not
1488
+ * complete. With no turn open, a fresh terminal turn carries the error, so
1489
+ * it is never start-less. */
1490
+ let hostErrorTurns = 0;
1491
+ // The first turn key this invoke drove (its ADK invocationId): the stem of a
1492
+ // fresh terminal turn's id, so the id is unique across the invokes a host
1493
+ // folds together, not only within this one.
1494
+ let firstKey;
1495
+ function hostError(err) {
1496
+ let closed = 0;
1497
+ for (const turnId of [...openTurns].reverse()) {
1498
+ if (closedTurns.has(turnId))
1499
+ continue;
1500
+ closedTurns.add(turnId);
1501
+ const usage = err.usage ?? mapUsage(usageByTurn.get(turnId));
1502
+ a.closeMessage(`msg_${turnId}`);
1503
+ a.closeTurnError(turnId, { message: err.message, code: err.code, ...(usage !== undefined ? { usage } : {}) });
1504
+ closed++;
1505
+ }
1506
+ if (closed > 0)
1507
+ return;
1508
+ const base = firstKey ?? err.invocationId ?? (stem.value ??= drawIdStem());
1509
+ const turnId = `turn_${base}_host_error_${hostErrorTurns++}`;
1510
+ const messageId = ensureOpen(turnId);
1511
+ closedTurns.add(turnId);
1512
+ a.closeMessage(messageId);
1513
+ a.closeTurnError(turnId, {
1514
+ message: err.message,
1515
+ code: err.code,
1516
+ ...(err.usage !== undefined ? { usage: err.usage } : {}),
1517
+ });
1518
+ }
1629
1519
  function drive(event) {
1630
- const key = turnKey(event);
1520
+ const key = turnKey(event) ?? `adk_${(stem.value ??= drawIdStem())}`;
1521
+ firstKey ??= key;
1631
1522
  const turnId = `turn_${key}`;
1632
1523
  const messageId = ensureOpen(turnId);
1633
1524
  const parts = event.content?.parts ?? [];
@@ -1705,7 +1596,7 @@ function createAdkInner() {
1705
1596
  return;
1706
1597
  }
1707
1598
  if (residualTail.length > 0) {
1708
- const id = mintBlockId(blockIds, turnId, "text");
1599
+ const id = mintBlockId(blockIds, "text");
1709
1600
  a.textStart(id, messageId);
1710
1601
  a.textDelta(id, messageId, residualTail);
1711
1602
  a.textEnd(id, messageId, index === citedPartIndex && citations !== undefined ? { citations } : undefined);
@@ -1735,13 +1626,51 @@ function createAdkInner() {
1735
1626
  // re-mint+re-emit a duplicate tool.start. Entries for windows whose
1736
1627
  // aggregate never arrives simply die with the invoke's closure — bounded,
1737
1628
  // per-invoke.
1738
- driveAdkTopLevel(a, event, messageId, turnId, closedTurns, pendingAsks, emittedInputAsks); // standalone/content arms (Tasks 4–5)
1629
+ if (!isPartial)
1630
+ trackLongRunning(event, turnId);
1631
+ driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved); // standalone/content arms (Tasks 4–5)
1632
+ // A turn gets ONE terminal: an interrupt on a turn that already closed
1633
+ // (a second barge-in, or one after a success close) adds none.
1634
+ if (event.interrupted === true && !closedTurns.has(turnId))
1635
+ interruptPending.add(turnId);
1739
1636
  maybeCloseTurn(event, turnId, messageId, isPartial);
1637
+ if (!isPartial && interruptPending.has(turnId))
1638
+ closeInterrupted(turnId);
1639
+ }
1640
+ /** interrupted → turn.abort, after the event's own content and carries and
1641
+ * after its message.end (INV-MSG: nothing of the turn follows its terminal).
1642
+ * The turn is marked closed in the facet's own bookkeeping too (audit M21),
1643
+ * so neither maybeCloseTurn nor flush() fabricates a later success. The
1644
+ * message.end carries the turn's accumulated usage, as flush()'s does. */
1645
+ function closeInterrupted(turnId) {
1646
+ interruptPending.delete(turnId);
1647
+ closedTurns.add(turnId);
1648
+ a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
1649
+ a.emit({ type: "turn.abort", turnId, reason: "interrupted" });
1740
1650
  }
1741
1651
  return {
1742
- accept(json) {
1743
- if (json === undefined) {
1744
- a.emitExt("google", "unparsed", { reason: "not-serializable" });
1652
+ push(native) {
1653
+ // withAtomicPush has already read the native as plain JSON (see
1654
+ // createAdkNormalizer). The host-error sentinel is checked first: an
1655
+ // Error-built one keeps its message, because core maps an Error to
1656
+ // {name, message, ...own enumerable}.
1657
+ const json = native;
1658
+ const hostErr = hostErrorOf(json);
1659
+ if (hostErr !== undefined) {
1660
+ // Like the completion sentinel below, a host<->facet contract input
1661
+ // (SPEC §8.0 host obligation 1), not a framework native.
1662
+ hostError(hostErr);
1663
+ return a.drain();
1664
+ }
1665
+ if (isHostCompleteNative(json)) {
1666
+ // The host-completion sentinel is a host<->facet contract input (SPEC
1667
+ // §8.0 host obligation 4), like obligation 1's `__host_error__`: NOT a
1668
+ // framework native. So §8.0's graceful-degradation rule ("MUST NOT
1669
+ // silently drop a native event") does not bind it. With the option OFF
1670
+ // it is ignored by design and never reaches the wire as
1671
+ // ext.google.unparsed.
1672
+ if (hostCompletion)
1673
+ hostComplete();
1745
1674
  return a.drain();
1746
1675
  }
1747
1676
  if (!isAdkEvent(json)) {
@@ -1751,15 +1680,7 @@ function createAdkInner() {
1751
1680
  drive(json);
1752
1681
  return a.drain();
1753
1682
  },
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) {
1683
+ flush() {
1763
1684
  // Dangling open turns (interrupted stream before a final aggregate):
1764
1685
  // close their message; the ENGINE flush closes the turn itself with
1765
1686
  // turn.abort{stream-truncated} per INV-FLUSH — never success (audit M21).
@@ -1772,78 +1693,19 @@ function createAdkInner() {
1772
1693
  // (SPEC.md:779; R&D item 6 step 1), so a flushed turn, e.g. a completed
1773
1694
  // Workflow invoke until the host completion signal exists, still reports
1774
1695
  // 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).
1696
+ // appears only once.
1777
1697
  for (const turnId of openTurns) {
1778
- if (!closedTurns.has(turnId)) {
1779
- closedTurns.add(turnId);
1780
- a.closeMessage(`msg_${turnId}`, bare ? undefined : mapUsage(usageByTurn.get(turnId)));
1698
+ if (closedTurns.has(turnId))
1699
+ continue;
1700
+ if (interruptPending.has(turnId)) {
1701
+ closeInterrupted(turnId);
1702
+ continue;
1781
1703
  }
1704
+ closedTurns.add(turnId);
1705
+ a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
1782
1706
  }
1783
1707
  return a.flush();
1784
1708
  },
1785
1709
  };
1786
1710
  }
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
- }
1849
1711
  //# sourceMappingURL=index.js.map