@silverprotocol/google-adk 1.0.0-rc.6 → 1.0.0-rc.8

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
@@ -112,6 +112,7 @@ import {
112
112
  carryNodeValue,
113
113
  changedOutputRendering,
114
114
  reduceCarried,
115
+ reduceCarriedOrThrow,
115
116
  scrubCredentialCallArgs,
116
117
  adkAuthConfigView,
117
118
  } from "./auth-objects.js";
@@ -147,6 +148,17 @@ export interface AdkPart {
147
148
  response?: { [k: string]: JsonValue };
148
149
  id?: string | null;
149
150
  thoughtSignature?: string;
151
+ /** genai `FunctionResponse.parts`: ordered media parts of the result
152
+ * (`FunctionResponsePart`: `inlineData` / `fileData`, each with its own
153
+ * `mediaProcessing` from `@google/genai` 2.32.0). No tool-result channel
154
+ * takes them as they are, so they ride verbatim (functionResponseCarry). */
155
+ parts?: JsonValue[];
156
+ /** genai `FunctionResponseScheduling` (SILENT | WHEN_IDLE | INTERRUPT …),
157
+ * for NON_BLOCKING calls. Rides verbatim (functionResponseCarry). */
158
+ scheduling?: string;
159
+ /** genai `FunctionResponse.willContinue`: more responses follow for a
160
+ * NON_BLOCKING call. Rides verbatim (functionResponseCarry). */
161
+ willContinue?: boolean;
150
162
  };
151
163
  /** Embedded media bytes (base64). Both members are OPTIONAL on the genai
152
164
  * `Blob` type (`data?`/`mimeType?`, doc-"Required" only) — `driveAdkPart`
@@ -938,6 +950,31 @@ function carryUnmappableArm(
938
950
  });
939
951
  }
940
952
 
953
+ // genai `FunctionResponse` members a `tool.done` has no slot for: `parts` (the
954
+ // result's media), `scheduling` and `willContinue` (NON_BLOCKING calls; the
955
+ // spec gives the last two an input-side home only, on an `AgInput` result).
956
+ // On the resolved arm they ride one provider-raw block, keyed by the wire Part
957
+ // field name like `carryUnmappableArm`, with the response's own `name` and
958
+ // `id` (when the native has one) so a reader can tell which call it qualifies.
959
+ // `undefined` when the response has none of them, so such a response maps
960
+ // exactly as before. A reserved-credential answer never takes this carry: its
961
+ // allowlist is the id, the name and the scrubbed response (scrubAdkAuthConfig).
962
+ function functionResponseCarry(fr: NonNullable<AdkPart["functionResponse"]>): JsonValue | undefined {
963
+ if (fr.name === ADK_REQUEST_CREDENTIAL) return undefined;
964
+ const carried: { [k: string]: JsonValue } = {};
965
+ if (fr.parts !== undefined) carried["parts"] = JsonValue.parse(fr.parts);
966
+ if (fr.scheduling !== undefined) carried["scheduling"] = JsonValue.parse(fr.scheduling);
967
+ if (fr.willContinue !== undefined) carried["willContinue"] = JsonValue.parse(fr.willContinue);
968
+ if (Object.keys(carried).length === 0) return undefined;
969
+ return {
970
+ functionResponse: {
971
+ ...(fr.id !== undefined ? { id: JsonValue.parse(fr.id) } : {}),
972
+ name: JsonValue.parse(fr.name),
973
+ ...carried,
974
+ },
975
+ };
976
+ }
977
+
941
978
  // ─── executableCode.language → AgBlock.code.language (spec §2) ────────────────
942
979
  // Gemini ExecutableCode.language is a closed enum (LANGUAGE_UNSPECIFIED|PYTHON);
943
980
  // AgJSON code.language is a free string. Map defensively (spec §2 round-trip note).
@@ -1109,6 +1146,23 @@ function onlyStateChange(ev: AdkEvent): boolean {
1109
1146
  return true;
1110
1147
  }
1111
1148
 
1149
+ /** Whether an event is a state record and nothing else: a non-empty
1150
+ * `actions.stateDelta`, with every other member one the facet maps to
1151
+ * nothing (`branch` aside, which says where the record came from). ADK yields
1152
+ * one at an agent's end (an after-agent callback's state change), which ends
1153
+ * the call before it, and, from `@google/adk` 2.4.0, from inside a model
1154
+ * call: the planning response processor records a planner's state writes as
1155
+ * an event of their own, yielded before the call's next chunk or its repeat
1156
+ * (`dist/esm/agents/processors/nl_planning_processor.js` :77-84). The two
1157
+ * look alike, so the record holds the window and the source's next event
1158
+ * decides (see `heldByStateRecord`). */
1159
+ function stateRecordOnly(ev: AdkEvent): boolean {
1160
+ const delta: unknown = ev.actions?.stateDelta;
1161
+ if (!isJsonObject(delta) || Object.keys(delta).length === 0) return false;
1162
+ const { branch: _branch, ...rest } = ev;
1163
+ return onlyStateChange(rest);
1164
+ }
1165
+
1112
1166
  /** Whether an event carries model output: a part of `model`-role content, or
1113
1167
  * output-transcription text. ADK's function response is `user`-role. */
1114
1168
  function hasModelOutput(ev: AdkEvent): boolean {
@@ -1235,6 +1289,23 @@ function canonicalJson(v: JsonValue): string {
1235
1289
  .join(",")}}`;
1236
1290
  }
1237
1291
 
1292
+ /** An Interactions-route close (`partial: false` and `turnComplete: true`
1293
+ * with an `interactionId`), and what the facet maps of it: the event in sorted-key JSON without `id` and
1294
+ * `timestamp`, the two members it maps to nothing that ADK sets afresh on
1295
+ * every event it yields (NO_EMIT_EVENT_MEMBERS). `undefined` for any other
1296
+ * event. See `lastInteractionsEvent`. */
1297
+ function interactionsClose(native: JsonValue): { interactionId: string; mapped: string } | undefined {
1298
+ // ADK also yields `partial: false` mid-response, with `turnComplete: false`:
1299
+ // each media delta and each finished function call (@google/adk 2.3.0 and
1300
+ // 2.4.0, dist/esm/models/interactions_utils.js :490-498 and :521-526). Those
1301
+ // are not closes, and two equal ones in a row are two parts.
1302
+ if (!isJsonObject(native) || native["partial"] !== false || native["turnComplete"] !== true) return undefined;
1303
+ const interactionId = native["interactionId"];
1304
+ if (typeof interactionId !== "string" || interactionId.length === 0) return undefined;
1305
+ const { id: _id, timestamp: _timestamp, ...mapped } = native;
1306
+ return { interactionId, mapped: canonicalJson(mapped) };
1307
+ }
1308
+
1238
1309
  /** A native member that fits the resource-link block: core's own schema for
1239
1310
  * that member accepts it AND leaves it unchanged, so the block carries it
1240
1311
  * verbatim. `undefined` when it does not fit (it then rides the residual). */
@@ -1900,10 +1971,14 @@ function driveAdkPart(
1900
1971
  // A reserved-credential answer takes the same allowlist here as on the
1901
1972
  // resolved arm below (see scrubAdkAuthConfig): the carry must not
1902
1973
  // bypass it. Only the id, the name and the scrubbed response ride.
1974
+ // Any other orphan rides whole, with each ADK AuthCredential and each
1975
+ // response named adk_request_credential in it, at any depth, reduced in
1976
+ // place to its non-secret members (spec §8.0 item 28 (c), which reaches
1977
+ // the unparsed payload); every other member rides unchanged.
1903
1978
  const carriedResponse: JsonValue =
1904
1979
  fr.name === ADK_REQUEST_CREDENTIAL
1905
1980
  ? (pickAllowed(JsonValue.parse(fr), { id: true, name: true, response: (v) => scrubbedResponse(v) }) ?? {})
1906
- : JsonValue.parse(fr);
1981
+ : reduceCarriedOrThrow(JsonValue.parse(fr));
1907
1982
  a.emitExt("google", "unparsed", { functionResponse: carriedResponse, turnId });
1908
1983
  return "";
1909
1984
  }
@@ -1913,12 +1988,25 @@ function driveAdkPart(
1913
1988
  // AND its classification use the allowlisted form (see scrubAdkAuthConfig),
1914
1989
  // so nothing omitted can resurface through errorText.
1915
1990
  const carried = fr.name === ADK_REQUEST_CREDENTIAL ? scrubbedResponse(fr.response) : response;
1991
+ const unmapped = functionResponseCarry(fr);
1992
+ if (unmapped !== undefined) {
1993
+ a.contentBlock(messageId, { type: "provider-raw", vendor: "google", raw: reduceCarried(unmapped) });
1994
+ }
1995
+ // A result for a call this invoke never opened (spec §5.0 INV-XINV): ADK's
1996
+ // resume processors re-run a call an earlier invoke paused on and yield
1997
+ // its response in the resuming invoke. It lands in its own role:"tool"
1998
+ // message, whose id derives from this invoke's turn as well, so a call id
1999
+ // reused across invokes still names a fresh message. A null-id response
2000
+ // resolves a call minted in this invoke and never takes this path.
2001
+ const resultMessageId =
2002
+ realId !== null && !_assembledToolCalls.has(toolCallId) ? `${turnId}:${toolCallId}:result` : undefined;
1916
2003
  a.toolDone({
1917
2004
  toolCallId,
1918
2005
  ...functionResponseToToolDoneFields(fr.name, carried),
1919
2006
  // SPEC §8.0 item 25: see classifyFunctionResponse.
1920
2007
  ...classifyFunctionResponse(carried, toolCallId, event.actions),
1921
2008
  turnId,
2009
+ ...(resultMessageId !== undefined ? { messageId: resultMessageId } : {}),
1922
2010
  providerMetadata:
1923
2011
  fr.thoughtSignature !== undefined && fr.thoughtSignature.length > 0
1924
2012
  ? AgProviderMeta.parse({ google: { thoughtSignature: fr.thoughtSignature } })
@@ -2721,6 +2809,28 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
2721
2809
  // §8.3 per-instance accumulator (replaces the module-level streamedText Map),
2722
2810
  // keyed by aggregateWindowKey (turn + source):
2723
2811
  const streamedText = new Map<string, string>();
2812
+ // The windows a state record holds (stateRecordOnly): the source's next
2813
+ // event that is neither a chunk, any `partial: false` event (ADK's SSE
2814
+ // aggregator and Live path mark their repeats so) nor another state record
2815
+ // closes the window first, as the call the record followed had ended; any
2816
+ // of those three keeps it open, as the record came from inside the call.
2817
+ const heldByStateRecord = new Set<string>();
2818
+ // Per Interactions response (interactionId): what the facet maps of the
2819
+ // response's last event, when that event was a close (interactionsClose);
2820
+ // no entry after any other event of the response (a chunk, a media delta,
2821
+ // a finished function call). ADK's Interactions converter closes a streamed
2822
+ // response at `interaction.completed` and then again when the stream ends,
2823
+ // each time with every part so far (models/interactions_utils.js), and a
2824
+ // `completed` status update can close it once more. A close that
2825
+ // maps to exactly what the response's previous event mapped to, its `id`
2826
+ // and `timestamp` aside, is that repeat: §8.0 item 3 drops it, and since
2827
+ // nothing of it differs from what the facet already mapped, push() emits
2828
+ // nothing for it (no second rendering, and no new turn after a success
2829
+ // close). Any mapped difference (more text, other parts, usage, a state
2830
+ // change) is a new close and maps as before. The map lives as long as the
2831
+ // normalizer (one per `runAsync()` call) and keeps one entry per response,
2832
+ // media included.
2833
+ const lastInteractionsEvent = new Map<string, string>();
2724
2834
  // Per turn and role: the transcription chunks streamed so far (see driveAdkTopLevel).
2725
2835
  const streamedTranscription = new Map<string, string>();
2726
2836
  // Per turn: the Live usage reports' modality details, one entry per report.
@@ -3211,6 +3321,15 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3211
3321
 
3212
3322
  /** An event's reading against the aggregate windows of a turn (the rules
3213
3323
  * are stated in drive()). */
3324
+ /** Settles the hold a state record put on the event's own window (see
3325
+ * `heldByStateRecord`): a later state record keeps it; any other event
3326
+ * lifts it, and one without a partial flag closes the window first. */
3327
+ function settleStateRecordHold(turnId: string, event: AdkEvent, stateRecord: boolean): void {
3328
+ const key = aggregateWindowKey(turnId, event);
3329
+ if (stateRecord || !heldByStateRecord.delete(key)) return;
3330
+ if (event.partial === undefined) streamedText.delete(key);
3331
+ }
3332
+
3214
3333
  function readWindow(turnId: string, event: AdkEvent, parts: readonly AdkPart[], skipped: ReadonlySet<number>, isPartial: boolean) {
3215
3334
  const isTextPart = (p: AdkPart, idx: number): boolean =>
3216
3335
  !skipped.has(idx) &&
@@ -3299,6 +3418,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3299
3418
  // through its own arm.
3300
3419
  const { parts, origin: nativeIndexOf } = splitPayloadParts(event.content?.parts ?? []);
3301
3420
  const isPartial = event.partial === true;
3421
+ // A state record and nothing else (no content, no partial flag): it holds the window it follows.
3422
+ const stateRecord = stateRecordOnly(event);
3302
3423
  // ADK renders an object `output` as the same event's text part, byte-equal
3303
3424
  // to JSON.stringify(output) (workflow/base_node.js toContent → valueToText).
3304
3425
  // When the node-data reduction changed that output, the rendering would
@@ -3357,7 +3478,8 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3357
3478
  // transcription event, a `partial: false` event whose
3358
3479
  // parts are all non-text (a function call or media before the Interactions
3359
3480
  // route's re-yield), and a function response (progressive SSE runs a tool
3360
- // mid-stream). A text event that closes the window is its re-yield when
3481
+ // mid-stream). A state record (stateRecordOnly) holds it for the source's
3482
+ // next event instead (heldByStateRecord). A text event that closes the window is its re-yield when
3361
3483
  // one text starts with the other (equal; longer by text no chunk streamed,
3362
3484
  // whose tail renders; or shorter, a callback's replacement whose bytes
3363
3485
  // already streamed) or when the streamed text ends with its text (a later
@@ -3375,6 +3497,7 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3375
3497
  // then its status window (snapshotReading), and closes them; and
3376
3498
  // the relaying agent's own failure event ends every relayed window of its
3377
3499
  // author and node path. An empty text part is not text.
3500
+ settleStateRecordHold(turnId, event, stateRecord);
3378
3501
  const {
3379
3502
  isTextPart,
3380
3503
  carriesText,
@@ -3464,7 +3587,9 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3464
3587
  (parts.length > 0 && parts.every((p) => p.functionResponse !== undefined)));
3465
3588
  if (isPartial) streamedText.set(ownKey, accumulated);
3466
3589
  else if (carriesText) for (const key of snapshot !== null ? candidates : [readKey]) streamedText.delete(key);
3467
- else if (!keepsWindowOpen) for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event, relay)]) streamedText.delete(key);
3590
+ else if (stateRecord) {
3591
+ for (const key of candidates) if (streamedText.has(key)) heldByStateRecord.add(key);
3592
+ } else if (!keepsWindowOpen) for (const key of [...candidates, ...relayWindowsEndedBy(streamedText, turnId, event, relay)]) streamedText.delete(key);
3468
3593
 
3469
3594
  // Round-3 review finding (regression on finding b): the resend window's
3470
3595
  // lifecycle is scoped PER CONTENT KEY, never per turn. `mintNullIdCallId`
@@ -3643,9 +3768,20 @@ function createInnerAdkNormalizer(options: AdkNormalizerOptions, invokeStem: str
3643
3768
  omitted = stripped.omitted;
3644
3769
  }
3645
3770
  if (!isAdkEvent(event)) {
3646
- a.emitExt("google", "unparsed", { native: nativeWithCarriedMetadata(event) });
3771
+ // Carried whole, less the metadata entries the facet never carries,
3772
+ // with each ADK AuthCredential and each response named
3773
+ // adk_request_credential in it reduced in place (spec §8.0 item 28
3774
+ // (c), which reaches the unparsed payload): a native ADK did not
3775
+ // shape, such as one serialized from Python, can hold a state entry with
3776
+ // an exchanged token.
3777
+ a.emitExt("google", "unparsed", { native: reduceCarriedOrThrow(nativeWithCarriedMetadata(event)) });
3647
3778
  return a.drain();
3648
3779
  }
3780
+ // An Interactions response's repeated close (see lastInteractionsEvent).
3781
+ const close = interactionsClose(event);
3782
+ if (close !== undefined && lastInteractionsEvent.get(close.interactionId) === close.mapped) return a.drain();
3783
+ if (close !== undefined) lastInteractionsEvent.set(close.interactionId, close.mapped);
3784
+ else if (typeof event.interactionId === "string") lastInteractionsEvent.delete(event.interactionId);
3649
3785
  drive(event, omitted);
3650
3786
  return a.drain();
3651
3787
  },