@silverprotocol/google-adk 1.0.0-rc.1 → 1.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -523,32 +523,47 @@ export function isLossyFinishReason(reason: string): boolean {
523
523
  // ─── stateful factory helpers ─────────────────────────────────────────────────
524
524
 
525
525
 
526
- // ─── the A2A relay's bookkeeping entries in customMetadata ───────────────────
527
- // ADK's RemoteA2AAgent writes up to four bookkeeping entries into the
528
- // customMetadata of the events it relays: its send request, the peer's raw A2A
529
- // event and their task and context ids. They are the relay's own bookkeeping,
530
- // not event data, and the facet does not carry them, wherever customMetadata
531
- // is carried (the provider-raw carry and the ext.google.unparsed native, where
532
- // an event serialized from Python spells it custom_metadata). Every other
533
- // entry, including one a remote agent wrote, rides unchanged.
526
+ // ─── customMetadata entries the facet does not carry ─────────────────────────
527
+ // Two kinds of customMetadata entry are not event data, and the facet does not
528
+ // carry them, wherever customMetadata is carried (the provider-raw carry and
529
+ // the ext.google.unparsed native, where an event serialized from Python spells
530
+ // it custom_metadata):
531
+ // - ADK's RemoteA2AAgent writes up to four bookkeeping entries into the
532
+ // customMetadata of the events it relays: its send request, the peer's raw
533
+ // A2A event and their task and context ids.
534
+ // - ADK reserves the entries whose name begins with `__adk_internal_` for its
535
+ // own components (events/internal_metadata.js, @google/adk 2.2.1): callers
536
+ // cannot set them, and ADK removes them from the API responses, saved
537
+ // session files and A2A messages it produces. At that version they hold a
538
+ // tool-call integrity stamp and a restored-history marker (SPEC §8.0 item
539
+ // 38).
540
+ // Only top-level entries are matched. Every other entry, including one a
541
+ // remote agent wrote and a value nested below a carried entry, rides
542
+ // unchanged.
534
543
  const RELAY_BOOKKEEPING_KEYS: ReadonlySet<string> = new Set(["a2a:request", "a2a:response", "a2a:task_id", "a2a:context_id"]);
544
+ const ADK_INTERNAL_METADATA_PREFIX = "__adk_internal_";
535
545
 
536
- /** A customMetadata value without the relay's bookkeeping entries, as a new
537
- * value; the argument is not changed. A value holding none of them, or one
538
- * that is not an object, is returned as it is; undefined when the entries
539
- * were all it held. */
540
- function withoutRelayBookkeeping(value: JsonValue): JsonValue | undefined {
541
- if (!isJsonObject(value) || !Object.keys(value).some((k) => RELAY_BOOKKEEPING_KEYS.has(k))) return value;
542
- const kept = Object.entries(value).filter(([k]) => !RELAY_BOOKKEEPING_KEYS.has(k));
546
+ /** Whether a top-level customMetadata entry is one the facet does not carry. */
547
+ function isUncarriedMetadataKey(key: string): boolean {
548
+ return RELAY_BOOKKEEPING_KEYS.has(key) || key.startsWith(ADK_INTERNAL_METADATA_PREFIX);
549
+ }
550
+
551
+ /** A customMetadata value without the entries the facet does not carry, as a
552
+ * new value; the argument is not changed. A value holding none of them, or
553
+ * one that is not an object, is returned as it is; undefined when those
554
+ * entries were all it held. */
555
+ function carriedMetadata(value: JsonValue): JsonValue | undefined {
556
+ if (!isJsonObject(value) || !Object.keys(value).some(isUncarriedMetadataKey)) return value;
557
+ const kept = Object.entries(value).filter(([k]) => !isUncarriedMetadataKey(k));
543
558
  return kept.length > 0 ? Object.fromEntries(kept) : undefined;
544
559
  }
545
560
 
546
561
  /** A native with its customMetadata, or the custom_metadata of an event
547
- * serialized from Python, reduced as by withoutRelayBookkeeping and dropped
548
- * when nothing is left, as a new value; every other member is unchanged, and
549
- * the argument is not changed. The new value's members are defined, never
562
+ * serialized from Python, reduced as by carriedMetadata and dropped when
563
+ * nothing is left, as a new value; every other member is unchanged, and the
564
+ * argument is not changed. The new value's members are defined, never
550
565
  * assigned, and one named __proto__ is not copied (SPEC §13.7). */
551
- function nativeWithoutRelayBookkeeping(native: JsonValue): JsonValue {
566
+ function nativeWithCarriedMetadata(native: JsonValue): JsonValue {
552
567
  if (!isJsonObject(native)) return native;
553
568
  let changed = false;
554
569
  const out: Array<[string, JsonValue]> = [];
@@ -558,7 +573,7 @@ function nativeWithoutRelayBookkeeping(native: JsonValue): JsonValue {
558
573
  out.push([key, value]);
559
574
  continue;
560
575
  }
561
- const kept = withoutRelayBookkeeping(value);
576
+ const kept = carriedMetadata(value);
562
577
  if (kept !== value) changed = true;
563
578
  if (kept !== undefined) out.push([key, kept]);
564
579
  }
@@ -2316,7 +2331,7 @@ function driveAdkTopLevel(
2316
2331
  const groundingSupports = groundingSupportsCarry(event.groundingMetadata);
2317
2332
  if (groundingSupports !== undefined) unmappedEvent["groundingMetadata"] = groundingSupports;
2318
2333
  if (event.customMetadata !== undefined) {
2319
- const kept = withoutRelayBookkeeping(JsonValue.parse(event.customMetadata));
2334
+ const kept = carriedMetadata(JsonValue.parse(event.customMetadata));
2320
2335
  if (kept !== undefined) unmappedEvent["customMetadata"] = kept;
2321
2336
  }
2322
2337
  // An error message without an error code (ADK's A2A relay reports its own
@@ -2466,9 +2481,22 @@ function isHostCompleteNative(v: JsonValue): boolean {
2466
2481
  // invocation's end (the host-completion event, a host-terminal event or
2467
2482
  // flush()), never as success.
2468
2483
 
2484
+ /** The `errorCode` of the seal `@google/adk` (2.3.0, `runAsync`) appends when
2485
+ * a client abort ends the invocation (events/abort_events.js, read by ADK's
2486
+ * own `isAbortEvent` on this value alone). */
2487
+ const ADK_ABORT_SEAL_CODE = "INVOCATION_ABORTED";
2488
+
2489
+ /** Spec §8.0 item 35: the client-abort seal is keyed on its `errorCode` value
2490
+ * alone, never on content or author (a seal with no call to answer carries
2491
+ * no content). It is outside item 35. */
2492
+ function isAbortSeal(event: AdkEvent): boolean {
2493
+ return event.errorCode === ADK_ABORT_SEAL_CODE;
2494
+ }
2495
+
2469
2496
  /** Spec §8.0 item 35: an in-band invocation error carries both errorCode and
2470
- * errorMessage. */
2497
+ * errorMessage. The client-abort seal is not one. */
2471
2498
  function inBandErrorOf(event: AdkEvent): { code: string; message: string } | undefined {
2499
+ if (isAbortSeal(event)) return undefined;
2472
2500
  const code: unknown = event.errorCode;
2473
2501
  const message: unknown = event.errorMessage;
2474
2502
  return typeof code === "string" && typeof message === "string" ? { code, message } : undefined;
@@ -2575,20 +2603,26 @@ function relayStreamOf(event: AdkEvent): string | null {
2575
2603
 
2576
2604
  /** The open windows a non-partial event reads and closes: the one under its
2577
2605
  * own key; else, for an event without a branch, every open window of the
2578
- * same turn, author and node path. */
2579
- function windowCandidates(windows: ReadonlyMap<string, string>, turnId: string, event: AdkEvent): string[] {
2580
- const own = aggregateWindowKey(turnId, event);
2606
+ * same turn, author and node path. `own`, `relay` and `wantStream` are the
2607
+ * event's own window key, relay record and relay stream, read once by the
2608
+ * caller. */
2609
+ function windowCandidates(
2610
+ windows: ReadonlyMap<string, string>,
2611
+ turnId: string,
2612
+ event: AdkEvent,
2613
+ own: string,
2614
+ relay: { task: string | null; stream: string } | null,
2615
+ wantStream: string | null,
2616
+ ): string[] {
2581
2617
  if (windows.has(own)) return [own];
2582
2618
  // A relayed artifact with no chunks of its own can repeat the status text
2583
2619
  // of its own task (a peer that sends its answer as status messages, then
2584
2620
  // the same text as its final artifact).
2585
- const relay = relayOf(event);
2586
2621
  if (relay !== null && relay.stream.startsWith("artifact:")) {
2587
2622
  const status = aggregateWindowKey(turnId, event, relayStreamKey(relay.task, "status"));
2588
2623
  if (windows.has(status)) return [status];
2589
2624
  }
2590
2625
  if (typeof event.branch === "string") return [];
2591
- const wantStream = relayStreamOf(event);
2592
2626
  return sourceWindows(windows, turnId, event, true)
2593
2627
  .filter(([, stream]) => stream === wantStream)
2594
2628
  .map(([key]) => key);
@@ -2652,8 +2686,13 @@ function snapshotReading(artifactText: string, statusText: string, text: string)
2652
2686
  * relayed itself: ADK's RemoteA2AAgent reports a failed request with an
2653
2687
  * event of its own (errorMessage, turnComplete, no relay record), which ends
2654
2688
  * every relayed stream of that author and node path. */
2655
- function relayWindowsEndedBy(windows: ReadonlyMap<string, string>, turnId: string, event: AdkEvent): string[] {
2656
- if (relayOf(event) !== null) return [];
2689
+ function relayWindowsEndedBy(
2690
+ windows: ReadonlyMap<string, string>,
2691
+ turnId: string,
2692
+ event: AdkEvent,
2693
+ relay: { task: string | null; stream: string } | null,
2694
+ ): string[] {
2695
+ if (relay !== null) return [];
2657
2696
  if (event.errorMessage === undefined && event.turnComplete !== true) return [];
2658
2697
  return sourceWindows(windows, turnId, event, true)
2659
2698
  .filter(([, stream]) => stream !== null)
@@ -2724,6 +2763,14 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2724
2763
  // Host obligation 4 (opt-in): a success close stashed until the sentinel, and
2725
2764
  // the non-HITL long-running calls still unanswered, per turn.
2726
2765
  const deferredClose = new Map<string, AdkEvent>();
2766
+ // Per turn: a final response of a pausing agent (the author of a pending
2767
+ // ask's event) arrived while that ask was pending, one of item 26's pause
2768
+ // signals. A final stashed before any ask is not one, and neither is another
2769
+ // agent's final, which only follows the signal.
2770
+ const finalWhileAsking = new Set<string>();
2771
+ const askingAuthors = new Map<string, Set<string | undefined>>();
2772
+ const finalOfPausingAgent = (turnId: string, event: AdkEvent): boolean =>
2773
+ (pendingAsks.get(turnId)?.length ?? 0) > 0 && askingAuthors.get(turnId)?.has(event.author) === true;
2727
2774
  // Live barge-ins (`interrupted: true`, ADK's live aggregator) awaiting their
2728
2775
  // close. An interrupt on a PARTIAL text event is followed by ADK's full-text
2729
2776
  // aggregate of the same model turn (utils/live_connection_utils.js:175-178),
@@ -2788,6 +2835,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2788
2835
  isPartial: boolean
2789
2836
  ): void {
2790
2837
  if (isPartial || closedTurns.has(turnId)) return;
2838
+ // The client-abort seal closes the turn in drive() (closeCancelled), never here.
2839
+ if (isAbortSeal(event)) return;
2791
2840
  const parts = event.content?.parts ?? [];
2792
2841
  const hasFunctionCall = parts.some((p) => p.functionCall !== undefined);
2793
2842
  const interrupted = event.interrupted === true || interruptPending.has(turnId);
@@ -2828,7 +2877,10 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2828
2877
  // pending still signals the pause (item 26).
2829
2878
  if (inBandErrorOf(event) !== undefined) return;
2830
2879
  if (firstInBandError.has(turnId)) {
2831
- if ((pendingAsks.get(turnId)?.length ?? 0) > 0) deferredClose.set(turnId, event);
2880
+ if ((pendingAsks.get(turnId)?.length ?? 0) > 0) {
2881
+ deferredClose.set(turnId, event);
2882
+ if (finalOfPausingAgent(turnId, event)) finalWhileAsking.add(turnId);
2883
+ }
2832
2884
  return;
2833
2885
  }
2834
2886
  // ── The nodeInfo gate (R&D item 6, step 1) ──
@@ -2850,6 +2902,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2850
2902
  // so a stream ending here is byte-identical.
2851
2903
  if (hostCompletion || (pendingAsks.get(turnId)?.length ?? 0) > 0) {
2852
2904
  deferredClose.set(turnId, event);
2905
+ if (finalOfPausingAgent(turnId, event)) finalWhileAsking.add(turnId);
2853
2906
  return;
2854
2907
  }
2855
2908
  // ── The branch gate ──
@@ -2974,8 +3027,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2974
3027
  * the call counts once, from the later report), and the relay's closing
2975
3028
  * event (it adds no usage). Any other in-band error emits `error` from this
2976
3029
  * push and, when it is the invocation's first, latches it. */
2977
- function recordErrorAndUsage(event: AdkEvent, turnId: string, isPartial: boolean): void {
2978
- const sourceKey = aggregateWindowKey(turnId, event, null);
3030
+ function recordErrorAndUsage(event: AdkEvent, turnId: string, isPartial: boolean, sourceKey: string): void {
2979
3031
  const previous = previousBySource.get(sourceKey);
2980
3032
  const error = inBandErrorOf(event);
2981
3033
  const counting = !isPartial && !closedTurns.has(turnId);
@@ -3016,7 +3068,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3016
3068
  * pause's end (its pause-end event, or a final response while the ask was
3017
3069
  * pending). An in-band invocation error is never one. */
3018
3070
  function pauseSignalled(turnId: string): boolean {
3019
- return (pendingAsks.get(turnId)?.length ?? 0) > 0 && (pauseEnded.has(turnId) || deferredClose.has(turnId));
3071
+ return (pendingAsks.get(turnId)?.length ?? 0) > 0 && (pauseEnded.has(turnId) || finalWhileAsking.has(turnId));
3020
3072
  }
3021
3073
 
3022
3074
  /** Spec §8.0 item 35 at the invocation's end: the one turn.error of a turn
@@ -3167,15 +3219,16 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3167
3219
  typeof p.text === "string" &&
3168
3220
  p.text.length > 0;
3169
3221
  const carriesText = parts.some(isTextPart);
3170
- const ownKey = aggregateWindowKey(turnId, event);
3171
3222
  const relay = relayOf(event);
3223
+ const relayStream = relay === null ? null : relayStreamKey(relay.task, relay.stream);
3224
+ const ownKey = aggregateWindowKey(turnId, event, relayStream);
3172
3225
  const snapshot = !isPartial && relay !== null && relay.stream === "snapshot" ? relay : null;
3173
3226
  const restated = snapshot !== null ? snapshotWindows(streamedText, turnId, event, snapshot.task) : null;
3174
3227
  const candidates = isPartial
3175
3228
  ? []
3176
3229
  : restated !== null
3177
3230
  ? [...restated.artifacts, ...restated.status]
3178
- : windowCandidates(streamedText, turnId, event);
3231
+ : windowCandidates(streamedText, turnId, event, ownKey, relay, relayStream);
3179
3232
  const [onlyCandidate] = candidates;
3180
3233
  const readKey = !isPartial && candidates.length === 1 && onlyCandidate !== undefined ? onlyCandidate : ownKey;
3181
3234
  const alreadyStreamed = isPartial
@@ -3206,7 +3259,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3206
3259
  const aggregateText = isAggregate ? eventText : "";
3207
3260
  const suppressAggregateText =
3208
3261
  isAggregate && aggregateText.length > 0 && (alreadyStreamed.startsWith(aggregateText) || suffixRepeat);
3209
- return { isTextPart, carriesText, ownKey, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText };
3262
+ return { isTextPart, carriesText, ownKey, relay, relayStream, snapshot, candidates, readKey, alreadyStreamed, isAggregate, aggregateText, suppressAggregateText };
3210
3263
  }
3211
3264
 
3212
3265
  /** Whether an event after a success close only repeats the closed turn's
@@ -3326,6 +3379,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3326
3379
  isTextPart,
3327
3380
  carriesText,
3328
3381
  ownKey,
3382
+ relay,
3383
+ relayStream,
3329
3384
  snapshot,
3330
3385
  candidates,
3331
3386
  readKey,
@@ -3409,7 +3464,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3409
3464
  (parts.length > 0 && parts.every((p) => p.functionResponse !== undefined)));
3410
3465
  if (isPartial) streamedText.set(ownKey, accumulated);
3411
3466
  else if (carriesText) for (const key of snapshot !== null ? candidates : [readKey]) streamedText.delete(key);
3412
- else if (!keepsWindowOpen) for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event)]) streamedText.delete(key);
3467
+ else if (!keepsWindowOpen) for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event, relay)]) streamedText.delete(key);
3413
3468
 
3414
3469
  // Round-3 review finding (regression on finding b): the resend window's
3415
3470
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
@@ -3426,15 +3481,31 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3426
3481
  // per-invoke.
3427
3482
 
3428
3483
  if (!isPartial) trackLongRunning(event, turnId);
3484
+ const asksBefore = pendingAsks.get(turnId)?.length ?? 0;
3429
3485
  driveAdkTopLevel(a, event, messageId, turnId, pendingAsks, reserved, streamedTranscription, closedTurns.has(turnId)); // standalone and content arms
3486
+ if ((pendingAsks.get(turnId)?.length ?? 0) > asksBefore) {
3487
+ const authors = askingAuthors.get(turnId) ?? new Set<string | undefined>();
3488
+ authors.add(event.author);
3489
+ askingAuthors.set(turnId, authors);
3490
+ }
3491
+ // Spec §8.0 item 26: an ask is pending only while its adk_request_* call
3492
+ // has no functionResponse in a non-partial event of the invocation. One
3493
+ // that answers it (the client-abort seal answers every unanswered call)
3494
+ // ends the ask, and a turn holding no pending ask does not close paused.
3495
+ if (!isPartial) pruneAnsweredAsks(turnId, parts);
3430
3496
  // A turn gets ONE terminal: an interrupt on a turn that already closed
3431
3497
  // (a second barge-in, or one after a success close) adds none.
3432
3498
  if (event.interrupted === true && !closedTurns.has(turnId)) interruptPending.add(turnId);
3433
3499
  carryLiveUsageDetails(event, turnId, messageId, isPartial);
3434
3500
  if (parts.some((p) => p.functionResponse !== undefined)) awaitingReply.add(turnId);
3435
3501
  else if (hasModelOutput(event)) awaitingReply.delete(turnId);
3436
- recordErrorAndUsage(event, turnId, isPartial);
3502
+ // A non-relayed event's own window key is its source key.
3503
+ recordErrorAndUsage(event, turnId, isPartial, relayStream === null ? ownKey : aggregateWindowKey(turnId, event, null));
3437
3504
  maybeCloseTurn(event, turnId, messageId, isPartial);
3505
+ // Spec §8.0 item 35: the client-abort seal is the invocation's native
3506
+ // terminal. Its functionResponse parts closed their calls above (item 25);
3507
+ // it closes the turn now, from this push().
3508
+ if (!isPartial && isAbortSeal(event) && !closedTurns.has(turnId)) closeCancelled(turnId);
3438
3509
  // The interrupted generation closes on its own turnComplete (its trailing
3439
3510
  // usageMetadata arrives before it), or at flush() / host completion.
3440
3511
  if (!isPartial && event.turnComplete === true && interruptPending.has(turnId)) closeInterrupted(turnId);
@@ -3499,6 +3570,34 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3499
3570
  * The turn is marked closed in the facet's own bookkeeping too (audit M21),
3500
3571
  * so neither maybeCloseTurn nor flush() fabricates a later success. The
3501
3572
  * message.end carries the turn's accumulated usage, as flush()'s does. */
3573
+ /** Drop each pending ask of the turn whose adk_request_* call one of these
3574
+ * parts answers (spec §8.0 item 26). */
3575
+ function pruneAnsweredAsks(turnId: string, parts: readonly AdkPart[]): void {
3576
+ const asks = pendingAsks.get(turnId);
3577
+ if (asks === undefined) return;
3578
+ const answered = new Set<string>();
3579
+ for (const p of parts) {
3580
+ const id: unknown = p.functionResponse?.id;
3581
+ if (typeof id === "string") answered.add(id);
3582
+ }
3583
+ if (answered.size === 0) return;
3584
+ const left = asks.filter((ask) => ask.toolCallId === undefined || !answered.has(ask.toolCallId));
3585
+ if (left.length === asks.length) return;
3586
+ if (left.length > 0) pendingAsks.set(turnId, left);
3587
+ else pendingAsks.delete(turnId);
3588
+ }
3589
+
3590
+ /** Spec §8.0 item 35: the client-abort seal closes the invocation's turn with
3591
+ * one turn.abort, reason "cancelled", and no `error` or `turn.error`. As for
3592
+ * an interruption (item 17), the message.end before it carries the turn's
3593
+ * accumulated usage, and the turn is marked closed, so neither the
3594
+ * host-completion event nor flush() adds a terminal. */
3595
+ function closeCancelled(turnId: string): void {
3596
+ closedTurns.add(turnId);
3597
+ a.closeMessage(`msg_${turnId}`, mapUsage(usageByTurn.get(turnId)));
3598
+ a.emit({ type: "turn.abort", turnId, reason: "cancelled" });
3599
+ }
3600
+
3502
3601
  function closeInterrupted(turnId: string): void {
3503
3602
  interruptPending.delete(turnId);
3504
3603
  interruptClosed.add(turnId);
@@ -3544,7 +3643,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3544
3643
  omitted = stripped.omitted;
3545
3644
  }
3546
3645
  if (!isAdkEvent(event)) {
3547
- a.emitExt("google", "unparsed", { native: nativeWithoutRelayBookkeeping(event) });
3646
+ a.emitExt("google", "unparsed", { native: nativeWithCarriedMetadata(event) });
3548
3647
  return a.drain();
3549
3648
  }
3550
3649
  drive(event, omitted);