@google/adk 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/cjs/a2a/event_converter_utils.js +5 -1
  2. package/dist/cjs/a2a/metadata_converter_utils.js +2 -1
  3. package/dist/cjs/common.js +18 -0
  4. package/dist/cjs/events/abort_events.js +135 -0
  5. package/dist/cjs/events/internal_metadata.js +131 -0
  6. package/dist/cjs/models/gemini_continuation.js +232 -0
  7. package/dist/cjs/plugins/debug_logging_plugin.js +653 -0
  8. package/dist/cjs/plugins/plugin_manager.js +1 -1
  9. package/dist/cjs/plugins/tool_call_integrity_plugin.js +364 -0
  10. package/dist/cjs/runner/runner.js +17 -3
  11. package/dist/cjs/version.js +1 -1
  12. package/dist/esm/a2a/event_converter_utils.js +5 -1
  13. package/dist/esm/a2a/metadata_converter_utils.js +2 -1
  14. package/dist/esm/common.js +20 -0
  15. package/dist/esm/events/abort_events.js +110 -0
  16. package/dist/esm/events/internal_metadata.js +97 -0
  17. package/dist/esm/models/gemini_continuation.js +205 -0
  18. package/dist/esm/plugins/debug_logging_plugin.js +615 -0
  19. package/dist/esm/plugins/plugin_manager.js +1 -1
  20. package/dist/esm/plugins/tool_call_integrity_plugin.js +339 -0
  21. package/dist/esm/runner/runner.js +20 -3
  22. package/dist/esm/version.js +1 -1
  23. package/dist/types/common.d.ts +3 -0
  24. package/dist/types/events/abort_events.d.ts +43 -0
  25. package/dist/types/events/internal_metadata.d.ts +78 -0
  26. package/dist/types/models/gemini_continuation.d.ts +59 -0
  27. package/dist/types/plugins/debug_logging_plugin.d.ts +157 -0
  28. package/dist/types/plugins/tool_call_integrity_plugin.d.ts +116 -0
  29. package/dist/types/version.d.ts +1 -1
  30. package/dist/web/index_web.js +59 -59
  31. package/dist/web/index_web.js.map +4 -4
  32. package/package.json +1 -1
@@ -32,6 +32,7 @@ module.exports = __toCommonJS(event_converter_utils_exports);
32
32
  var import_genai = require("@google/genai");
33
33
  var import_event = require("../events/event.js");
34
34
  var import_event_actions = require("../events/event_actions.js");
35
+ var import_internal_metadata = require("../events/internal_metadata.js");
35
36
  var import_env_aware_utils = require("../utils/env_aware_utils.js");
36
37
  var import_a2a_event = require("./a2a_event.js");
37
38
  var import_metadata_converter_utils = require("./metadata_converter_utils.js");
@@ -201,7 +202,10 @@ function createAdkEventFromMetadata(a2aEvent) {
201
202
  citationMetadata: metadata[import_metadata_converter_utils.A2AMetadataKeys.CITATION_METADATA],
202
203
  groundingMetadata: metadata[import_metadata_converter_utils.A2AMetadataKeys.GROUNDING_METADATA],
203
204
  usageMetadata: metadata[import_metadata_converter_utils.A2AMetadataKeys.USAGE_METADATA],
204
- customMetadata: metadata[import_metadata_converter_utils.A2AMetadataKeys.CUSTOM_METADATA],
205
+ // A remote peer cannot set ADK-internal keys on the events we emit for it.
206
+ customMetadata: (0, import_internal_metadata.withoutInternalMetadata)(
207
+ metadata[import_metadata_converter_utils.A2AMetadataKeys.CUSTOM_METADATA]
208
+ ),
205
209
  // Only fields in PEER_SETTABLE_ACTION_FIELDS may be restored from
206
210
  // metadata a remote A2A peer controls. Every other action field either
207
211
  // mutates the caller's own session or drives the caller's own control
@@ -33,6 +33,7 @@ __export(metadata_converter_utils_exports, {
33
33
  getAdkEventMetadata: () => getAdkEventMetadata
34
34
  });
35
35
  module.exports = __toCommonJS(metadata_converter_utils_exports);
36
+ var import_internal_metadata = require("../events/internal_metadata.js");
36
37
  var import_a2a_event = require("./a2a_event.js");
37
38
  /**
38
39
  * @license
@@ -95,7 +96,7 @@ function getA2AEventMetadata(adkEvent, {
95
96
  [A2AMetadataKeys.CITATION_METADATA]: adkEvent.citationMetadata,
96
97
  [A2AMetadataKeys.GROUNDING_METADATA]: adkEvent.groundingMetadata,
97
98
  [A2AMetadataKeys.USAGE_METADATA]: adkEvent.usageMetadata,
98
- [A2AMetadataKeys.CUSTOM_METADATA]: adkEvent.customMetadata,
99
+ [A2AMetadataKeys.CUSTOM_METADATA]: (0, import_internal_metadata.publicMetadata)(adkEvent.customMetadata),
99
100
  [A2AMetadataKeys.PARTIAL]: adkEvent.partial,
100
101
  [A2AMetadataKeys.IS_LONG_RUNNING]: (adkEvent.longRunningToolIds || []).length > 0
101
102
  };
@@ -96,6 +96,7 @@ __export(common_exports, {
96
96
  GoogleSearchTool: () => import_google_search_tool.GoogleSearchTool,
97
97
  Graph: () => import_workflow.Graph,
98
98
  INTERACTIONS_REQUEST_PROCESSOR: () => import_interactions_request_processor.INTERACTIONS_REQUEST_PROCESSOR,
99
+ INTERNAL_METADATA_PREFIX: () => import_internal_metadata.INTERNAL_METADATA_PREFIX,
99
100
  InMemoryArtifactService: () => import_in_memory_artifact_service.InMemoryArtifactService,
100
101
  InMemoryCredentialService: () => import_in_memory_credential_service.InMemoryCredentialService,
101
102
  InMemoryMemoryService: () => import_in_memory_memory_service.InMemoryMemoryService,
@@ -144,6 +145,7 @@ __export(common_exports, {
144
145
  REQUEST_CREDENTIAL_FUNCTION_CALL_NAME: () => import_functions.REQUEST_CREDENTIAL_FUNCTION_CALL_NAME,
145
146
  REQUEST_INPUT_FUNCTION_CALL_NAME: () => import_functions.REQUEST_INPUT_FUNCTION_CALL_NAME,
146
147
  RESERVED_TOOL_CALL_ERROR_TYPE: () => import_reflect_retry_model_plugin.RESERVED_TOOL_CALL_ERROR_TYPE,
148
+ RESTORED_EVENT_KEY: () => import_internal_metadata.RESTORED_EVENT_KEY,
147
149
  ReadonlyContext: () => import_readonly_context.ReadonlyContext,
148
150
  ReflectAndRetryModelPlugin: () => import_reflect_retry_model_plugin.ReflectAndRetryModelPlugin,
149
151
  ReflectAndRetryToolPlugin: () => import_reflect_retry_tool_plugin.ReflectAndRetryToolPlugin,
@@ -164,6 +166,8 @@ __export(common_exports, {
164
166
  StreamingMode: () => import_run_config.StreamingMode,
165
167
  Task: () => import_task.Task,
166
168
  TokenBasedContextCompactor: () => import_token_based_context_compactor.TokenBasedContextCompactor,
169
+ ToolCallIntegrityError: () => import_tool_call_integrity_plugin.ToolCallIntegrityError,
170
+ ToolCallIntegrityPlugin: () => import_tool_call_integrity_plugin.ToolCallIntegrityPlugin,
167
171
  ToolConfirmation: () => import_tool_confirmation.ToolConfirmation,
168
172
  ToolContext: () => import_tool_context.ToolContext,
169
173
  ToolErrorType: () => import_tool_execution_error.ToolErrorType,
@@ -247,11 +251,15 @@ __export(common_exports, {
247
251
  isWebMCPSupported: () => import_webmcp_types.isWebMCPSupported,
248
252
  isWorkflow: () => import_workflow.isWorkflow,
249
253
  logger: () => import_logger.logger,
254
+ markRestored: () => import_internal_metadata.markRestored,
250
255
  node: () => import_workflow.node,
251
256
  normalizeRetryExceptions: () => import_workflow.normalizeRetryExceptions,
252
257
  populateClientFunctionCallId: () => import_event.populateClientFunctionCallId,
253
258
  prepareRetryConfig: () => import_workflow.prepareRetryConfig,
254
259
  pruneThoughts: () => import_event.pruneThoughts,
260
+ publicEvent: () => import_internal_metadata.publicEvent,
261
+ publicMetadata: () => import_internal_metadata.publicMetadata,
262
+ publicSession: () => import_internal_metadata.publicSession,
255
263
  renameReservedKeywords: () => import_case_utils.renameReservedKeywords,
256
264
  requestInputTool: () => import_request_input_tool.requestInputTool,
257
265
  requireAgent: () => import_invocation_context.requireAgent,
@@ -322,6 +330,7 @@ var import_tool_execution_error = require("./errors/tool_execution_error.js");
322
330
  var import_compacted_event = require("./events/compacted_event.js");
323
331
  var import_event = require("./events/event.js");
324
332
  var import_event_actions = require("./events/event_actions.js");
333
+ var import_internal_metadata = require("./events/internal_metadata.js");
325
334
  var import_structured_events = require("./events/structured_events.js");
326
335
  var import_base_example_provider = require("./examples/base_example_provider.js");
327
336
  var import_example = require("./examples/example.js");
@@ -343,6 +352,7 @@ var import_plugin_manager = require("./plugins/plugin_manager.js");
343
352
  var import_reflect_retry_model_plugin = require("./plugins/reflect_retry_model_plugin.js");
344
353
  var import_reflect_retry_tool_plugin = require("./plugins/reflect_retry_tool_plugin.js");
345
354
  var import_security_plugin = require("./plugins/security_plugin.js");
355
+ var import_tool_call_integrity_plugin = require("./plugins/tool_call_integrity_plugin.js");
346
356
  var import_in_memory_runner = require("./runner/in_memory_runner.js");
347
357
  var import_runner = require("./runner/runner.js");
348
358
  var import_base_session_service = require("./sessions/base_session_service.js");
@@ -480,6 +490,7 @@ __reExport(common_exports, require("./tools/base_tool.js"), module.exports);
480
490
  GoogleSearchTool,
481
491
  Graph,
482
492
  INTERACTIONS_REQUEST_PROCESSOR,
493
+ INTERNAL_METADATA_PREFIX,
483
494
  InMemoryArtifactService,
484
495
  InMemoryCredentialService,
485
496
  InMemoryMemoryService,
@@ -528,6 +539,7 @@ __reExport(common_exports, require("./tools/base_tool.js"), module.exports);
528
539
  REQUEST_CREDENTIAL_FUNCTION_CALL_NAME,
529
540
  REQUEST_INPUT_FUNCTION_CALL_NAME,
530
541
  RESERVED_TOOL_CALL_ERROR_TYPE,
542
+ RESTORED_EVENT_KEY,
531
543
  ReadonlyContext,
532
544
  ReflectAndRetryModelPlugin,
533
545
  ReflectAndRetryToolPlugin,
@@ -548,6 +560,8 @@ __reExport(common_exports, require("./tools/base_tool.js"), module.exports);
548
560
  StreamingMode,
549
561
  Task,
550
562
  TokenBasedContextCompactor,
563
+ ToolCallIntegrityError,
564
+ ToolCallIntegrityPlugin,
551
565
  ToolConfirmation,
552
566
  ToolContext,
553
567
  ToolErrorType,
@@ -631,11 +645,15 @@ __reExport(common_exports, require("./tools/base_tool.js"), module.exports);
631
645
  isWebMCPSupported,
632
646
  isWorkflow,
633
647
  logger,
648
+ markRestored,
634
649
  node,
635
650
  normalizeRetryExceptions,
636
651
  populateClientFunctionCallId,
637
652
  prepareRetryConfig,
638
653
  pruneThoughts,
654
+ publicEvent,
655
+ publicMetadata,
656
+ publicSession,
639
657
  renameReservedKeywords,
640
658
  requestInputTool,
641
659
  requireAgent,
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var abort_events_exports = {};
27
+ __export(abort_events_exports, {
28
+ ABORT_MESSAGE: () => ABORT_MESSAGE,
29
+ INVOCATION_ABORTED: () => INVOCATION_ABORTED,
30
+ buildAbortEvents: () => buildAbortEvents,
31
+ isAbortEvent: () => isAbortEvent
32
+ });
33
+ module.exports = __toCommonJS(abort_events_exports);
34
+ var import_event = require("./event.js");
35
+ /**
36
+ * @license
37
+ * Copyright 2026 Google LLC
38
+ * SPDX-License-Identifier: Apache-2.0
39
+ */
40
+ const INVOCATION_ABORTED = "INVOCATION_ABORTED";
41
+ const ABORT_MESSAGE = "Invocation was aborted by client.";
42
+ function isAbortEvent(event) {
43
+ return event.errorCode === INVOCATION_ABORTED;
44
+ }
45
+ __name(isAbortEvent, "isAbortEvent");
46
+ function isPausedTaskReply(event) {
47
+ return Boolean(event.isolationScope) && event.author !== "user" && (0, import_event.isFinalResponse)(event);
48
+ }
49
+ __name(isPausedTaskReply, "isPausedTaskReply");
50
+ function buildAbortEvents({
51
+ events,
52
+ invocationId,
53
+ rootAgentName,
54
+ branch
55
+ }) {
56
+ var _a, _b;
57
+ const invocationEvents = events.filter(
58
+ (e) => e.invocationId === invocationId
59
+ );
60
+ if (invocationEvents.length > 0 && isPausedTaskReply(invocationEvents[invocationEvents.length - 1])) {
61
+ return [];
62
+ }
63
+ const answeredCallIds = /* @__PURE__ */ new Set();
64
+ for (const event of invocationEvents) {
65
+ for (const fr of (0, import_event.getFunctionResponses)(event)) {
66
+ if (fr.id) {
67
+ answeredCallIds.add(fr.id);
68
+ }
69
+ }
70
+ }
71
+ const groupedCalls = /* @__PURE__ */ new Map();
72
+ for (const event of invocationEvents) {
73
+ for (const fc of (0, import_event.getFunctionCalls)(event)) {
74
+ if (!fc.id || answeredCallIds.has(fc.id)) {
75
+ continue;
76
+ }
77
+ const callBranch = event.branch || branch;
78
+ const key = JSON.stringify([
79
+ (_a = event.author) != null ? _a : null,
80
+ callBranch != null ? callBranch : null,
81
+ (_b = event.isolationScope) != null ? _b : null
82
+ ]);
83
+ let group = groupedCalls.get(key);
84
+ if (!group) {
85
+ group = {
86
+ author: event.author,
87
+ branch: callBranch,
88
+ isolationScope: event.isolationScope,
89
+ calls: []
90
+ };
91
+ groupedCalls.set(key, group);
92
+ }
93
+ group.calls.push(fc);
94
+ }
95
+ }
96
+ if (groupedCalls.size === 0) {
97
+ return [
98
+ (0, import_event.createEvent)({
99
+ invocationId,
100
+ author: rootAgentName,
101
+ branch,
102
+ errorCode: INVOCATION_ABORTED,
103
+ errorMessage: ABORT_MESSAGE
104
+ })
105
+ ];
106
+ }
107
+ return [...groupedCalls.values()].map(
108
+ (group) => (0, import_event.createEvent)({
109
+ invocationId,
110
+ author: group.author,
111
+ branch: group.branch,
112
+ isolationScope: group.isolationScope,
113
+ content: {
114
+ role: "user",
115
+ parts: group.calls.map((fc) => ({
116
+ functionResponse: {
117
+ id: fc.id,
118
+ name: fc.name,
119
+ response: { error: ABORT_MESSAGE }
120
+ }
121
+ }))
122
+ },
123
+ errorCode: INVOCATION_ABORTED,
124
+ errorMessage: ABORT_MESSAGE
125
+ })
126
+ );
127
+ }
128
+ __name(buildAbortEvents, "buildAbortEvents");
129
+ // Annotate the CommonJS export names for ESM import in node:
130
+ 0 && (module.exports = {
131
+ ABORT_MESSAGE,
132
+ INVOCATION_ABORTED,
133
+ buildAbortEvents,
134
+ isAbortEvent
135
+ });
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var internal_metadata_exports = {};
27
+ __export(internal_metadata_exports, {
28
+ INTERNAL_METADATA_PREFIX: () => INTERNAL_METADATA_PREFIX,
29
+ RESTORED_EVENT_KEY: () => RESTORED_EVENT_KEY,
30
+ internalMetadata: () => internalMetadata,
31
+ markRestored: () => markRestored,
32
+ publicEvent: () => publicEvent,
33
+ publicMetadata: () => publicMetadata,
34
+ publicSession: () => publicSession,
35
+ withoutInternalMetadata: () => withoutInternalMetadata
36
+ });
37
+ module.exports = __toCommonJS(internal_metadata_exports);
38
+ var import_logger = require("../utils/logger.js");
39
+ /**
40
+ * @license
41
+ * Copyright 2026 Google LLC
42
+ * SPDX-License-Identifier: Apache-2.0
43
+ */
44
+ const INTERNAL_METADATA_PREFIX = "__adk_internal_";
45
+ const RESTORED_EVENT_KEY = `${INTERNAL_METADATA_PREFIX}restored_event`;
46
+ function isMetadataObject(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+ __name(isMetadataObject, "isMetadataObject");
50
+ function isInternalKey(key) {
51
+ return key.startsWith(INTERNAL_METADATA_PREFIX);
52
+ }
53
+ __name(isInternalKey, "isInternalKey");
54
+ function dropInternalKeys(metadata) {
55
+ return Object.fromEntries(
56
+ Object.entries(metadata).filter(([key]) => !isInternalKey(key))
57
+ );
58
+ }
59
+ __name(dropInternalKeys, "dropInternalKeys");
60
+ function hasInternalKeys(metadata) {
61
+ return isMetadataObject(metadata) && Object.keys(metadata).some(isInternalKey);
62
+ }
63
+ __name(hasInternalKeys, "hasInternalKeys");
64
+ function withoutInternalMetadata(metadata) {
65
+ if (!isMetadataObject(metadata)) {
66
+ return metadata;
67
+ }
68
+ const kept = dropInternalKeys(metadata);
69
+ const dropped = Object.keys(metadata).filter(isInternalKey);
70
+ if (dropped.length > 0) {
71
+ import_logger.logger.debug(
72
+ `Dropping ADK-internal customMetadata keys: ${JSON.stringify(dropped.sort())}`
73
+ );
74
+ }
75
+ return kept;
76
+ }
77
+ __name(withoutInternalMetadata, "withoutInternalMetadata");
78
+ function publicMetadata(metadata) {
79
+ if (!isMetadataObject(metadata)) {
80
+ return metadata;
81
+ }
82
+ const kept = dropInternalKeys(metadata);
83
+ return Object.keys(kept).length > 0 ? kept : void 0;
84
+ }
85
+ __name(publicMetadata, "publicMetadata");
86
+ function internalMetadata(metadata) {
87
+ if (!isMetadataObject(metadata)) {
88
+ return {};
89
+ }
90
+ return Object.fromEntries(
91
+ Object.entries(metadata).filter(([key]) => isInternalKey(key))
92
+ );
93
+ }
94
+ __name(internalMetadata, "internalMetadata");
95
+ function markRestored(event) {
96
+ var _a;
97
+ event.customMetadata = {
98
+ ...(_a = withoutInternalMetadata(event.customMetadata)) != null ? _a : {},
99
+ [RESTORED_EVENT_KEY]: true
100
+ };
101
+ return event;
102
+ }
103
+ __name(markRestored, "markRestored");
104
+ function publicEvent(event) {
105
+ if (!hasInternalKeys(event.customMetadata)) {
106
+ return event;
107
+ }
108
+ return { ...event, customMetadata: publicMetadata(event.customMetadata) };
109
+ }
110
+ __name(publicEvent, "publicEvent");
111
+ function publicSession(session) {
112
+ var _a;
113
+ const events = (_a = session.events) != null ? _a : [];
114
+ const publicEvents = events.map((event) => publicEvent(event));
115
+ if (publicEvents.every((event, i) => event === events[i])) {
116
+ return session;
117
+ }
118
+ return { ...session, events: publicEvents };
119
+ }
120
+ __name(publicSession, "publicSession");
121
+ // Annotate the CommonJS export names for ESM import in node:
122
+ 0 && (module.exports = {
123
+ INTERNAL_METADATA_PREFIX,
124
+ RESTORED_EVENT_KEY,
125
+ internalMetadata,
126
+ markRestored,
127
+ publicEvent,
128
+ publicMetadata,
129
+ publicSession,
130
+ withoutInternalMetadata
131
+ });
@@ -0,0 +1,232 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var gemini_continuation_exports = {};
27
+ __export(gemini_continuation_exports, {
28
+ GeminiContinuation: () => GeminiContinuation,
29
+ MAX_RESUMES: () => MAX_RESUMES,
30
+ resumeToken: () => resumeToken
31
+ });
32
+ module.exports = __toCommonJS(gemini_continuation_exports);
33
+ var import_genai = require("@google/genai");
34
+ var import_content_processor_utils = require("../agents/processors/content_processor_utils.js");
35
+ var import_logger = require("../utils/logger.js");
36
+ var import_llm_response = require("./llm_response.js");
37
+ /**
38
+ * @license
39
+ * Copyright 2026 Google LLC
40
+ * SPDX-License-Identifier: Apache-2.0
41
+ */
42
+ const MAX_RESUMES = 256;
43
+ function resumeToken(response) {
44
+ var _a;
45
+ const candidate = (_a = response.candidates) == null ? void 0 : _a[0];
46
+ if ((candidate == null ? void 0 : candidate.finishReason) !== import_genai.FinishReason.CONTINUATION) {
47
+ return void 0;
48
+ }
49
+ if (!candidate.continuationToken) {
50
+ import_logger.logger.warn(
51
+ "The model paused the generation for continuation, but the response carries no continuation token, so the partial output is returned."
52
+ );
53
+ return void 0;
54
+ }
55
+ return candidate.continuationToken;
56
+ }
57
+ __name(resumeToken, "resumeToken");
58
+ const _GeminiContinuation = class _GeminiContinuation {
59
+ constructor(contents, config) {
60
+ this.config = config;
61
+ this.parts = [];
62
+ this.resumes = 0;
63
+ this.contents = [...contents];
64
+ }
65
+ /**
66
+ * Adds one request's output to the generation: its parts to the content and
67
+ * its usage to the total.
68
+ */
69
+ addOutput(newParts, newUsage) {
70
+ this.usage = addUsage(this.usage, newUsage);
71
+ this.appendParts(newParts);
72
+ }
73
+ /**
74
+ * Returns the request that resumes the generation after a request that
75
+ * ended with `nextToken`. Returns undefined if the request did not pause,
76
+ * returned the previous token again, or the generation was already resumed
77
+ * {@link MAX_RESUMES} times.
78
+ */
79
+ resumeRequest(nextToken) {
80
+ if (nextToken === void 0) {
81
+ return void 0;
82
+ }
83
+ if (!this.willResume(nextToken)) {
84
+ if (nextToken === this.token) {
85
+ import_logger.logger.warn(
86
+ "The model returned the same continuation token twice; returning the output generated so far."
87
+ );
88
+ } else {
89
+ import_logger.logger.warn(
90
+ `The model paused the generation ${MAX_RESUMES} times; returning the output generated so far.`
91
+ );
92
+ }
93
+ return void 0;
94
+ }
95
+ this.token = nextToken;
96
+ this.resumes++;
97
+ import_logger.logger.debug("The model paused the generation; resuming it.");
98
+ return this.buildResumeRequest(nextToken);
99
+ }
100
+ /** Returns `response` with the content and usage of all requests, if resumed. */
101
+ complete(response) {
102
+ var _a;
103
+ if (!this.resumed) {
104
+ return (0, import_llm_response.createLlmResponse)(response);
105
+ }
106
+ const candidate = (_a = response.candidates) == null ? void 0 : _a[0];
107
+ return (0, import_llm_response.createLlmResponse)({
108
+ ...response,
109
+ usageMetadata: this.usage,
110
+ candidates: candidate && this.parts.length > 0 ? [{ ...candidate, content: this.content() }] : response.candidates
111
+ });
112
+ }
113
+ /**
114
+ * Returns the final streamed `response`, with usage summed across all
115
+ * requests if resumed.
116
+ */
117
+ withSummedUsage(response) {
118
+ return this.resumed ? { ...response, usageMetadata: this.usage } : response;
119
+ }
120
+ /** Returns whether a request that ended with `nextToken` is resumed. */
121
+ willResume(nextToken) {
122
+ return nextToken !== this.token && this.resumes < MAX_RESUMES;
123
+ }
124
+ /** Whether the generation took more than one request. */
125
+ get resumed() {
126
+ return this.token !== void 0;
127
+ }
128
+ content() {
129
+ return { role: "model", parts: [...this.parts] };
130
+ }
131
+ buildResumeRequest(nextToken) {
132
+ const contents = [...this.contents];
133
+ if (this.parts.length > 0) {
134
+ const content = structuredClone(this.content());
135
+ (0, import_content_processor_utils.removeClientFunctionCallId)(content);
136
+ contents.push(content);
137
+ }
138
+ return {
139
+ contents,
140
+ config: { ...this.config, continuationToken: nextToken }
141
+ };
142
+ }
143
+ /** Appends `newParts`, joining text as the streaming aggregator does. */
144
+ appendParts(newParts) {
145
+ for (const part of newParts) {
146
+ const last = this.parts.length - 1;
147
+ const previous = last >= 0 ? this.parts[last] : void 0;
148
+ if (previous && canJoin(previous, part)) {
149
+ const joined = { text: previous.text + part.text };
150
+ if (previous.thought !== void 0) {
151
+ joined.thought = previous.thought;
152
+ }
153
+ const signature = previous.thoughtSignature || part.thoughtSignature;
154
+ if (signature !== void 0) {
155
+ joined.thoughtSignature = signature;
156
+ }
157
+ this.parts[last] = joined;
158
+ } else {
159
+ this.parts.push(part);
160
+ }
161
+ }
162
+ }
163
+ };
164
+ __name(_GeminiContinuation, "GeminiContinuation");
165
+ let GeminiContinuation = _GeminiContinuation;
166
+ function canJoin(first, second) {
167
+ var _a, _b;
168
+ return isText(first) && isText(second) && ((_a = first.thought) != null ? _a : false) === ((_b = second.thought) != null ? _b : false);
169
+ }
170
+ __name(canJoin, "canJoin");
171
+ function isText(part) {
172
+ if (!part.text) {
173
+ return false;
174
+ }
175
+ return Object.entries(part).every(
176
+ ([key, value]) => value === void 0 || key === "text" || key === "thought" || key === "thoughtSignature"
177
+ );
178
+ }
179
+ __name(isText, "isText");
180
+ const COUNT_FIELDS = [
181
+ "promptTokenCount",
182
+ "candidatesTokenCount",
183
+ "totalTokenCount",
184
+ "cachedContentTokenCount",
185
+ "thoughtsTokenCount",
186
+ "toolUsePromptTokenCount"
187
+ ];
188
+ const MODALITY_FIELDS = [
189
+ "promptTokensDetails",
190
+ "candidatesTokensDetails",
191
+ "cacheTokensDetails",
192
+ "toolUsePromptTokensDetails"
193
+ ];
194
+ function addUsage(total, next) {
195
+ var _a, _b;
196
+ if (!total || !next) {
197
+ return total != null ? total : next;
198
+ }
199
+ const combined = { ...next };
200
+ for (const field of COUNT_FIELDS) {
201
+ if (total[field] !== void 0 || next[field] !== void 0) {
202
+ combined[field] = ((_a = total[field]) != null ? _a : 0) + ((_b = next[field]) != null ? _b : 0);
203
+ }
204
+ }
205
+ for (const field of MODALITY_FIELDS) {
206
+ if (total[field] !== void 0 || next[field] !== void 0) {
207
+ combined[field] = addModalityCounts(total[field], next[field]);
208
+ }
209
+ }
210
+ return combined;
211
+ }
212
+ __name(addUsage, "addUsage");
213
+ function addModalityCounts(first, second) {
214
+ var _a, _b;
215
+ const totals = /* @__PURE__ */ new Map();
216
+ for (const count of [...first != null ? first : [], ...second != null ? second : []]) {
217
+ totals.set(
218
+ count.modality,
219
+ ((_a = totals.get(count.modality)) != null ? _a : 0) + ((_b = count.tokenCount) != null ? _b : 0)
220
+ );
221
+ }
222
+ return [...totals].map(
223
+ ([modality, tokenCount]) => modality === void 0 ? { tokenCount } : { modality, tokenCount }
224
+ );
225
+ }
226
+ __name(addModalityCounts, "addModalityCounts");
227
+ // Annotate the CommonJS export names for ESM import in node:
228
+ 0 && (module.exports = {
229
+ GeminiContinuation,
230
+ MAX_RESUMES,
231
+ resumeToken
232
+ });