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