@softactivate/adk 1.1.0 → 1.2.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.
Files changed (141) hide show
  1. package/dist/cjs/agents/functions.js +4 -0
  2. package/dist/cjs/auth/oauth2/oauth2_discovery.js +26 -2
  3. package/dist/cjs/code_executors/agent_engine_sandbox_code_executor.js +305 -0
  4. package/dist/cjs/code_executors/code_execution_utils.js +1 -1
  5. package/dist/cjs/common.js +3 -0
  6. package/dist/cjs/events/event.js +2 -0
  7. package/dist/cjs/index.js +14 -0
  8. package/dist/cjs/integrations/agent_registry/agent_registry.js +362 -0
  9. package/dist/cjs/integrations/agent_registry/agent_registry_mcp_toolset.js +103 -0
  10. package/dist/cjs/integrations/agent_registry/helpers.js +57 -0
  11. package/dist/cjs/integrations/agent_registry/types.js +50 -0
  12. package/dist/cjs/memory/vertex_ai_memory_bank_service.js +496 -0
  13. package/dist/cjs/runner/in_memory_runner.js +10 -5
  14. package/dist/cjs/runner/runner.js +32 -2
  15. package/dist/cjs/sessions/database_session_service.js +49 -3
  16. package/dist/cjs/sessions/in_memory_session_service.js +70 -14
  17. package/dist/cjs/sessions/registry.js +4 -0
  18. package/dist/cjs/sessions/vertex_ai_session_service.js +428 -0
  19. package/dist/cjs/tools/agent_tool.js +17 -8
  20. package/dist/cjs/tools/exit_loop_tool.js +9 -0
  21. package/dist/cjs/tools/function_tool.js +7 -2
  22. package/dist/cjs/tools/long_running_tool.js +2 -1
  23. package/dist/cjs/tools/mcp/mcp_session_manager.js +11 -0
  24. package/dist/cjs/tools/mcp/mcp_tool.js +10 -7
  25. package/dist/cjs/tools/mcp/mcp_toolset.js +10 -2
  26. package/dist/cjs/tools/openapi_tool/auth/auth_helpers.js +78 -0
  27. package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +84 -0
  28. package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +133 -0
  29. package/dist/cjs/tools/skill/load_skill_resource_tool.js +2 -25
  30. package/dist/cjs/utils/file_utils.js +28 -0
  31. package/dist/cjs/utils/gemini_schema_util.js +18 -0
  32. package/dist/cjs/utils/partial_copy.js +51 -0
  33. package/dist/cjs/utils/streaming_utils.js +167 -118
  34. package/dist/cjs/utils/vertex_ai_utils.js +50 -0
  35. package/dist/cjs/version.js +1 -1
  36. package/dist/esm/agents/functions.js +4 -0
  37. package/dist/esm/auth/oauth2/oauth2_discovery.js +26 -2
  38. package/dist/esm/code_executors/agent_engine_sandbox_code_executor.js +281 -0
  39. package/dist/esm/code_executors/code_execution_utils.js +1 -1
  40. package/dist/esm/common.js +2 -0
  41. package/dist/esm/events/event.js +2 -0
  42. package/dist/esm/index.js +11 -0
  43. package/dist/esm/integrations/agent_registry/agent_registry.js +333 -0
  44. package/dist/esm/integrations/agent_registry/agent_registry_mcp_toolset.js +77 -0
  45. package/dist/esm/integrations/agent_registry/helpers.js +28 -0
  46. package/dist/esm/integrations/agent_registry/types.js +20 -0
  47. package/dist/esm/memory/vertex_ai_memory_bank_service.js +468 -0
  48. package/dist/esm/runner/in_memory_runner.js +10 -5
  49. package/dist/esm/runner/runner.js +32 -2
  50. package/dist/esm/sessions/database_session_service.js +49 -3
  51. package/dist/esm/sessions/in_memory_session_service.js +70 -14
  52. package/dist/esm/sessions/registry.js +7 -0
  53. package/dist/esm/sessions/vertex_ai_session_service.js +403 -0
  54. package/dist/esm/tools/agent_tool.js +17 -8
  55. package/dist/esm/tools/exit_loop_tool.js +9 -0
  56. package/dist/esm/tools/function_tool.js +7 -2
  57. package/dist/esm/tools/long_running_tool.js +2 -1
  58. package/dist/esm/tools/mcp/mcp_session_manager.js +11 -0
  59. package/dist/esm/tools/mcp/mcp_tool.js +10 -7
  60. package/dist/esm/tools/mcp/mcp_toolset.js +10 -2
  61. package/dist/esm/tools/openapi_tool/auth/auth_helpers.js +48 -0
  62. package/dist/esm/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +60 -0
  63. package/dist/esm/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +111 -0
  64. package/dist/esm/tools/skill/load_skill_resource_tool.js +1 -24
  65. package/dist/esm/utils/file_utils.js +26 -0
  66. package/dist/esm/utils/gemini_schema_util.js +18 -0
  67. package/dist/esm/utils/partial_copy.js +23 -0
  68. package/dist/esm/utils/streaming_utils.js +165 -117
  69. package/dist/esm/utils/vertex_ai_utils.js +22 -0
  70. package/dist/esm/version.js +1 -1
  71. package/dist/types/a2a/a2a_remote_agent.d.ts +14 -0
  72. package/dist/types/agents/processors/base_llm_processor.d.ts +12 -4
  73. package/dist/types/agents/processors/basic_llm_request_processor.d.ts +5 -0
  74. package/dist/types/agents/processors/identity_llm_request_processor.d.ts +4 -0
  75. package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +5 -0
  76. package/dist/types/agents/run_config.d.ts +15 -0
  77. package/dist/types/code_executors/agent_engine_sandbox_code_executor.d.ts +51 -0
  78. package/dist/types/common.d.ts +2 -0
  79. package/dist/types/events/event_actions.d.ts +24 -6
  80. package/dist/types/events/structured_events.d.ts +13 -0
  81. package/dist/types/examples/example_util.d.ts +25 -0
  82. package/dist/types/index.d.ts +6 -0
  83. package/dist/types/integrations/agent_registry/agent_registry.d.ts +94 -0
  84. package/dist/types/integrations/agent_registry/agent_registry_mcp_toolset.d.ts +43 -0
  85. package/dist/types/integrations/agent_registry/helpers.d.ts +7 -0
  86. package/dist/types/integrations/agent_registry/types.d.ts +101 -0
  87. package/dist/types/memory/vertex_ai_memory_bank_service.d.ts +52 -0
  88. package/dist/types/runner/in_memory_runner.d.ts +28 -1
  89. package/dist/types/runner/runner.d.ts +47 -0
  90. package/dist/types/sessions/base_session_service.d.ts +18 -0
  91. package/dist/types/sessions/database_session_service.d.ts +1 -1
  92. package/dist/types/sessions/in_memory_session_service.d.ts +1 -1
  93. package/dist/types/sessions/vertex_ai_session_service.d.ts +37 -0
  94. package/dist/types/tools/exit_loop_tool.d.ts +9 -0
  95. package/dist/types/tools/function_tool.d.ts +22 -2
  96. package/dist/types/tools/long_running_tool.d.ts +11 -1
  97. package/dist/types/tools/mcp/mcp_session_manager.d.ts +3 -0
  98. package/dist/types/tools/openapi_tool/auth/auth_helpers.d.ts +25 -0
  99. package/dist/types/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.d.ts +20 -0
  100. package/dist/types/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.d.ts +20 -0
  101. package/dist/types/utils/file_utils.d.ts +2 -0
  102. package/dist/types/utils/partial_copy.d.ts +13 -0
  103. package/dist/types/utils/streaming_utils.d.ts +8 -17
  104. package/dist/types/utils/vertex_ai_utils.d.ts +14 -0
  105. package/dist/types/version.d.ts +1 -1
  106. package/dist/web/agents/functions.js +4 -0
  107. package/dist/web/auth/oauth2/oauth2_discovery.js +26 -2
  108. package/dist/web/code_executors/agent_engine_sandbox_code_executor.js +281 -0
  109. package/dist/web/code_executors/code_execution_utils.js +1 -1
  110. package/dist/web/common.js +2 -0
  111. package/dist/web/events/event.js +2 -0
  112. package/dist/web/index.js +11 -0
  113. package/dist/web/integrations/agent_registry/agent_registry.js +333 -0
  114. package/dist/web/integrations/agent_registry/agent_registry_mcp_toolset.js +90 -0
  115. package/dist/web/integrations/agent_registry/helpers.js +28 -0
  116. package/dist/web/integrations/agent_registry/types.js +20 -0
  117. package/dist/web/memory/vertex_ai_memory_bank_service.js +475 -0
  118. package/dist/web/runner/in_memory_runner.js +10 -5
  119. package/dist/web/runner/runner.js +32 -2
  120. package/dist/web/sessions/database_session_service.js +49 -3
  121. package/dist/web/sessions/in_memory_session_service.js +70 -14
  122. package/dist/web/sessions/registry.js +7 -0
  123. package/dist/web/sessions/vertex_ai_session_service.js +414 -0
  124. package/dist/web/tools/agent_tool.js +17 -8
  125. package/dist/web/tools/exit_loop_tool.js +9 -0
  126. package/dist/web/tools/function_tool.js +7 -2
  127. package/dist/web/tools/long_running_tool.js +2 -1
  128. package/dist/web/tools/mcp/mcp_session_manager.js +11 -0
  129. package/dist/web/tools/mcp/mcp_tool.js +10 -7
  130. package/dist/web/tools/mcp/mcp_toolset.js +10 -2
  131. package/dist/web/tools/openapi_tool/auth/auth_helpers.js +48 -0
  132. package/dist/web/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +60 -0
  133. package/dist/web/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +111 -0
  134. package/dist/web/tools/skill/load_skill_resource_tool.js +1 -24
  135. package/dist/web/utils/file_utils.js +26 -0
  136. package/dist/web/utils/gemini_schema_util.js +18 -0
  137. package/dist/web/utils/partial_copy.js +23 -0
  138. package/dist/web/utils/streaming_utils.js +218 -117
  139. package/dist/web/utils/vertex_ai_utils.js +22 -0
  140. package/dist/web/version.js +1 -1
  141. package/package.json +2 -1
@@ -0,0 +1,475 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ /**
20
+ * @license
21
+ * Copyright 2026 Google LLC
22
+ * SPDX-License-Identifier: Apache-2.0
23
+ */
24
+ import { Client } from "@google-cloud/vertexai";
25
+ import { createUserContent } from "@google/genai";
26
+ import { logger } from "../utils/logger.js";
27
+ import { getExpressModeApiKey } from "../utils/vertex_ai_utils.js";
28
+ const GENERATE_MEMORIES_KNOWN_FIELDS = [
29
+ "disableConsolidation",
30
+ "waitForCompletion",
31
+ "revisionLabels",
32
+ "revisionExpireTime",
33
+ "revisionTtl",
34
+ "disableMemoryRevisions",
35
+ "metadataMergeStrategy",
36
+ "allowedTopics"
37
+ ];
38
+ const CREATE_MEMORY_KNOWN_FIELDS = [
39
+ "displayName",
40
+ "description",
41
+ "waitForCompletion",
42
+ "ttl",
43
+ "expireTime",
44
+ "revisionExpireTime",
45
+ "revisionTtl",
46
+ "disableMemoryRevisions",
47
+ "topics",
48
+ "memoryId"
49
+ ];
50
+ const ENABLE_CONSOLIDATION_KEY = "enable_consolidation";
51
+ const MAX_DIRECT_MEMORIES_PER_GENERATE_CALL = 5;
52
+ function shouldFilterOutEvent(content) {
53
+ return !((content == null ? void 0 : content.parts) || []).some(
54
+ (p) => p.text || p.inlineData || p.fileData
55
+ );
56
+ }
57
+ function toVertexMetadataValue(key, value) {
58
+ if (typeof value === "boolean") {
59
+ return { boolValue: value };
60
+ }
61
+ if (typeof value === "number") {
62
+ return { doubleValue: value };
63
+ }
64
+ if (typeof value === "string") {
65
+ return { stringValue: value };
66
+ }
67
+ if (value instanceof Date) {
68
+ return { timestampValue: value.toISOString() };
69
+ }
70
+ if (typeof value === "object" && value !== null) {
71
+ const v = value;
72
+ if (v.boolValue !== void 0 || v.doubleValue !== void 0 || v.stringValue !== void 0 || v.timestampValue !== void 0) {
73
+ return v;
74
+ }
75
+ return { stringValue: JSON.stringify(value) };
76
+ }
77
+ if (value === null || value === void 0) {
78
+ logger.warn(
79
+ "Ignoring custom metadata key ".concat(key, " because its value is null or undefined.")
80
+ );
81
+ return void 0;
82
+ }
83
+ return { stringValue: String(value) };
84
+ }
85
+ class VertexAiMemoryBankService {
86
+ constructor(options) {
87
+ if (!options.agentEngineId) {
88
+ throw new Error(
89
+ "agentEngineId is required for VertexAiMemoryBankService."
90
+ );
91
+ }
92
+ this.projectId = options.projectId;
93
+ this.location = options.location;
94
+ this.agentEngineId = options.agentEngineId;
95
+ this.expressModeApiKey = getExpressModeApiKey(
96
+ options.projectId,
97
+ options.location,
98
+ options.expressModeApiKey
99
+ );
100
+ if (options.agentEngineId.includes("/")) {
101
+ logger.warn(
102
+ "agentEngineId appears to be a full resource path: '".concat(options.agentEngineId, "'. ") + "Expected just the ID (e.g., '456'). Extract the ID using: agentEngine.apiResource.name.split('/').pop()"
103
+ );
104
+ }
105
+ if (options.client) {
106
+ this.memories = options.client.agentEnginesInternal.memories;
107
+ } else {
108
+ const client = new Client({
109
+ project: this.projectId,
110
+ location: this.location
111
+ });
112
+ this.memories = client.agentEnginesInternal.memories;
113
+ }
114
+ }
115
+ async addSessionToMemory(session) {
116
+ await this.addEventsToMemoryFromEvents({
117
+ appName: session.appName,
118
+ userId: session.userId,
119
+ eventsToProcess: session.events
120
+ });
121
+ }
122
+ /**
123
+ * Adds events to Vertex AI Memory Bank via memories.generate.
124
+ */
125
+ async addEventsToMemory(request) {
126
+ await this.addEventsToMemoryFromEvents({
127
+ appName: request.appName,
128
+ userId: request.userId,
129
+ eventsToProcess: request.events,
130
+ customMetadata: request.customMetadata
131
+ });
132
+ }
133
+ /**
134
+ * Adds explicit memory items using Vertex Memory Bank.
135
+ */
136
+ async addMemory(request) {
137
+ if (isConsolidationEnabled(request.customMetadata)) {
138
+ return this.addMemoriesViaGenerateDirectMemoriesSource(request);
139
+ }
140
+ await this.addMemoriesViaCreate(request);
141
+ }
142
+ async searchMemory(request) {
143
+ const params = {
144
+ name: "reasoningEngines/".concat(this.agentEngineId),
145
+ scope: {
146
+ app_name: request.appName,
147
+ user_id: request.userId
148
+ },
149
+ similaritySearchParams: {
150
+ searchQuery: request.query
151
+ }
152
+ };
153
+ const retrievedMemoriesResponse = await this.memories.retrieveInternal(params);
154
+ logger.debug("Search memory response received.");
155
+ const memoryEvents = [];
156
+ const retrievedMemories = retrievedMemoriesResponse.retrievedMemories || [];
157
+ for (const retrievedMemory of retrievedMemories) {
158
+ logger.debug("Retrieved memory: ".concat(JSON.stringify(retrievedMemory)));
159
+ if (retrievedMemory.memory && retrievedMemory.memory.fact) {
160
+ const content = createUserContent(retrievedMemory.memory.fact);
161
+ memoryEvents.push({
162
+ author: "user",
163
+ content,
164
+ timestamp: retrievedMemory.memory.updateTime
165
+ });
166
+ }
167
+ }
168
+ return { memories: memoryEvents };
169
+ }
170
+ async addEventsToMemoryFromEvents(request) {
171
+ const directEvents = [];
172
+ for (const event of request.eventsToProcess) {
173
+ if (shouldFilterOutEvent(event.content)) {
174
+ continue;
175
+ }
176
+ directEvents.push({
177
+ content: JSON.parse(JSON.stringify(event.content))
178
+ });
179
+ }
180
+ if (directEvents.length > 0) {
181
+ const config = buildGenerateMemoriesConfig(request.customMetadata);
182
+ const params = {
183
+ name: "reasoningEngines/".concat(this.agentEngineId),
184
+ directContentsSource: { events: directEvents },
185
+ scope: {
186
+ app_name: request.appName,
187
+ user_id: request.userId
188
+ },
189
+ config
190
+ };
191
+ const operation = await this.memories.generateInternal(params);
192
+ logger.debug("Generate memory response received.");
193
+ logger.debug("Generate memory response: ".concat(JSON.stringify(operation)));
194
+ } else {
195
+ logger.info("No events to add to memory.");
196
+ }
197
+ }
198
+ async addMemoriesViaCreate(request) {
199
+ const validatedMemories = normalizeMemoriesForCreate(request.memories);
200
+ for (let index = 0; index < validatedMemories.length; index++) {
201
+ const memory = validatedMemories[index];
202
+ const memoryFact = memoryEntryToFact(memory, index);
203
+ const memoryMetadata = mergeCustomMetadataForMemory({
204
+ customMetadata: request.customMetadata,
205
+ memory
206
+ });
207
+ const memoryRevisionLabels = revisionLabelsForMemory(memory);
208
+ const config = buildCreateMemoryConfig({
209
+ customMetadata: memoryMetadata,
210
+ memoryRevisionLabels
211
+ });
212
+ const params = {
213
+ name: "reasoningEngines/".concat(this.agentEngineId),
214
+ fact: memoryFact,
215
+ scope: {
216
+ app_name: request.appName,
217
+ user_id: request.userId
218
+ },
219
+ config
220
+ };
221
+ const operation = await this.memories.createInternal(params);
222
+ logger.info("Create memory response received.");
223
+ logger.debug("Create memory response: ".concat(JSON.stringify(operation)));
224
+ }
225
+ }
226
+ async addMemoriesViaGenerateDirectMemoriesSource(request) {
227
+ const validatedMemories = normalizeMemoriesForCreate(request.memories);
228
+ const memoryTexts = validatedMemories.map(
229
+ (m, i) => memoryEntryToFact(m, i)
230
+ );
231
+ const config = buildGenerateMemoriesConfig(request.customMetadata);
232
+ const memoryBatches = iterMemoryBatches(memoryTexts);
233
+ for (const memoryBatch of memoryBatches) {
234
+ const params = {
235
+ name: "reasoningEngines/".concat(this.agentEngineId),
236
+ directMemoriesSource: {
237
+ directMemories: memoryBatch.map((fact) => ({ fact }))
238
+ },
239
+ scope: {
240
+ app_name: request.appName,
241
+ user_id: request.userId
242
+ },
243
+ config
244
+ };
245
+ const operation = await this.memories.generateInternal(params);
246
+ logger.info("Generate direct memory response received.");
247
+ logger.debug(
248
+ "Generate direct memory response: ".concat(JSON.stringify(operation))
249
+ );
250
+ }
251
+ }
252
+ }
253
+ function buildCreateMemoryConfig(params) {
254
+ const config = { waitForCompletion: false };
255
+ if (params.customMetadata) {
256
+ logger.debug(
257
+ "Memory creation metadata: ".concat(JSON.stringify(params.customMetadata))
258
+ );
259
+ }
260
+ const metadataByKey = {};
261
+ const customRevisionLabels = {};
262
+ for (const [key, value] of Object.entries(params.customMetadata || {})) {
263
+ if (key === ENABLE_CONSOLIDATION_KEY) {
264
+ continue;
265
+ }
266
+ if (key === "metadata") {
267
+ if (value === null || value === void 0) continue;
268
+ if (typeof value === "object" && !Array.isArray(value)) {
269
+ config["metadata"] = buildVertexMetadata(
270
+ value
271
+ );
272
+ } else {
273
+ logger.warn(
274
+ 'Ignoring metadata because customMetadata["metadata"] is not an object.'
275
+ );
276
+ }
277
+ continue;
278
+ }
279
+ if (key === "revisionLabels") {
280
+ if (value === null || value === void 0) continue;
281
+ const extractedLabels = extractRevisionLabels(
282
+ value,
283
+ 'customMetadata["revisionLabels"]'
284
+ );
285
+ if (extractedLabels) {
286
+ Object.assign(customRevisionLabels, extractedLabels);
287
+ }
288
+ continue;
289
+ }
290
+ if (CREATE_MEMORY_KNOWN_FIELDS.includes(key)) {
291
+ if (value !== null && value !== void 0) {
292
+ config[key] = value;
293
+ }
294
+ } else {
295
+ metadataByKey[key] = value;
296
+ }
297
+ }
298
+ if (Object.keys(metadataByKey).length > 0) {
299
+ const existingMetadata = config["metadata"];
300
+ if (!existingMetadata) {
301
+ config["metadata"] = buildVertexMetadata(metadataByKey);
302
+ } else {
303
+ config["metadata"] = __spreadValues(__spreadValues({}, existingMetadata), buildVertexMetadata(metadataByKey));
304
+ }
305
+ }
306
+ const revisionLabels = __spreadValues(__spreadValues({}, customRevisionLabels), params.memoryRevisionLabels);
307
+ if (Object.keys(revisionLabels).length > 0) {
308
+ config["revisionLabels"] = revisionLabels;
309
+ }
310
+ return config;
311
+ }
312
+ function extractRevisionLabels(value, source) {
313
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
314
+ logger.warn("Ignoring ".concat(source, " because it is not an object."));
315
+ return void 0;
316
+ }
317
+ const revisionLabels = {};
318
+ for (const [key, labelValue] of Object.entries(value)) {
319
+ if (typeof labelValue !== "string") {
320
+ logger.warn(
321
+ "Ignoring revision label ".concat(key, " from ").concat(source, " because its value is not a string.")
322
+ );
323
+ continue;
324
+ }
325
+ revisionLabels[key] = labelValue;
326
+ }
327
+ if (Object.keys(revisionLabels).length === 0) {
328
+ return void 0;
329
+ }
330
+ return revisionLabels;
331
+ }
332
+ function buildVertexMetadata(metadataByKey) {
333
+ const vertexMetadata = {};
334
+ for (const [key, value] of Object.entries(metadataByKey)) {
335
+ const convertedValue = toVertexMetadataValue(key, value);
336
+ if (convertedValue !== void 0) {
337
+ vertexMetadata[key] = convertedValue;
338
+ }
339
+ }
340
+ return vertexMetadata;
341
+ }
342
+ function buildGenerateMemoriesConfig(customMetadata) {
343
+ const config = { waitForCompletion: false };
344
+ if (!customMetadata) {
345
+ return config;
346
+ }
347
+ logger.debug("Memory generation metadata: ".concat(JSON.stringify(customMetadata)));
348
+ const metadataByKey = {};
349
+ for (const [key, value] of Object.entries(customMetadata)) {
350
+ if (key === ENABLE_CONSOLIDATION_KEY) {
351
+ continue;
352
+ }
353
+ if (key === "ttl") {
354
+ if (value === null || value === void 0) continue;
355
+ if (customMetadata["revisionTtl"] === void 0) {
356
+ config["revisionTtl"] = value;
357
+ }
358
+ continue;
359
+ }
360
+ if (key === "metadata") {
361
+ if (value === null || value === void 0) continue;
362
+ if (typeof value === "object" && !Array.isArray(value)) {
363
+ config["metadata"] = buildVertexMetadata(
364
+ value
365
+ );
366
+ } else {
367
+ logger.warn(
368
+ 'Ignoring metadata because customMetadata["metadata"] is not an object.'
369
+ );
370
+ }
371
+ continue;
372
+ }
373
+ if (GENERATE_MEMORIES_KNOWN_FIELDS.includes(key)) {
374
+ if (value !== null && value !== void 0) {
375
+ config[key] = value;
376
+ }
377
+ } else {
378
+ metadataByKey[key] = value;
379
+ }
380
+ }
381
+ if (Object.keys(metadataByKey).length > 0) {
382
+ const existingMetadata = config["metadata"];
383
+ if (!existingMetadata) {
384
+ config["metadata"] = buildVertexMetadata(metadataByKey);
385
+ } else {
386
+ config["metadata"] = __spreadValues(__spreadValues({}, existingMetadata), buildVertexMetadata(metadataByKey));
387
+ }
388
+ }
389
+ return config;
390
+ }
391
+ function normalizeMemoriesForCreate(memories) {
392
+ if (!Array.isArray(memories)) {
393
+ throw new TypeError("memories must be a sequence of memory items.");
394
+ }
395
+ if (memories.length === 0) {
396
+ throw new Error("memories must contain at least one entry.");
397
+ }
398
+ return memories;
399
+ }
400
+ function memoryEntryToFact(memory, index) {
401
+ const textParts = [];
402
+ if (memory.content && memory.content.parts) {
403
+ for (const part of memory.content.parts) {
404
+ if (part.inlineData || part.fileData) {
405
+ throw new Error(
406
+ "memories[".concat(index, "] must include text only; inlineData and fileData are not supported.")
407
+ );
408
+ }
409
+ if (part.text) {
410
+ const strippedText = part.text.trim();
411
+ if (strippedText) {
412
+ textParts.push(strippedText);
413
+ }
414
+ }
415
+ }
416
+ }
417
+ if (textParts.length === 0) {
418
+ throw new Error("memories[".concat(index, "] must include non-whitespace text."));
419
+ }
420
+ return textParts.join("\n");
421
+ }
422
+ function mergeCustomMetadataForMemory(params) {
423
+ const mergedMetadata = {};
424
+ if (params.customMetadata) {
425
+ Object.assign(mergedMetadata, params.customMetadata);
426
+ }
427
+ const memoryWithMetadata = params.memory;
428
+ if (memoryWithMetadata.customMetadata) {
429
+ Object.assign(mergedMetadata, memoryWithMetadata.customMetadata);
430
+ }
431
+ if (Object.keys(mergedMetadata).length === 0) {
432
+ return void 0;
433
+ }
434
+ return mergedMetadata;
435
+ }
436
+ function revisionLabelsForMemory(memory) {
437
+ const revisionLabels = {};
438
+ if (memory.author) {
439
+ revisionLabels["author"] = memory.author;
440
+ }
441
+ if (memory.timestamp) {
442
+ revisionLabels["timestamp"] = memory.timestamp;
443
+ }
444
+ if (Object.keys(revisionLabels).length === 0) {
445
+ return void 0;
446
+ }
447
+ return revisionLabels;
448
+ }
449
+ function isConsolidationEnabled(customMetadata) {
450
+ if (!customMetadata) {
451
+ return false;
452
+ }
453
+ const enableConsolidation = customMetadata[ENABLE_CONSOLIDATION_KEY];
454
+ if (enableConsolidation === void 0) {
455
+ return false;
456
+ }
457
+ if (typeof enableConsolidation !== "boolean") {
458
+ throw new TypeError(
459
+ 'customMetadata["'.concat(ENABLE_CONSOLIDATION_KEY, '"] must be a bool.')
460
+ );
461
+ }
462
+ return enableConsolidation;
463
+ }
464
+ function iterMemoryBatches(memories) {
465
+ const memoryBatches = [];
466
+ for (let index = 0; index < memories.length; index += MAX_DIRECT_MEMORIES_PER_GENERATE_CALL) {
467
+ memoryBatches.push(
468
+ memories.slice(index, index + MAX_DIRECT_MEMORIES_PER_GENERATE_CALL)
469
+ );
470
+ }
471
+ return memoryBatches;
472
+ }
473
+ export {
474
+ VertexAiMemoryBankService
475
+ };
@@ -10,11 +10,16 @@ import { InMemoryMemoryService } from "../memory/in_memory_memory_service.js";
10
10
  import { InMemorySessionService } from "../sessions/in_memory_session_service.js";
11
11
  import { Runner } from "./runner.js";
12
12
  class InMemoryRunner extends Runner {
13
- constructor({
14
- agent,
15
- appName = "InMemoryRunner",
16
- plugins = []
17
- }) {
13
+ /**
14
+ * Creates a new InMemoryRunner instance.
15
+ *
16
+ * @param params The configuration for the runner.
17
+ * @param params.agent The root agent to run.
18
+ * @param params.appName The application name. Defaults to `'InMemoryRunner'`.
19
+ * @param params.plugins An optional list of plugins.
20
+ */
21
+ constructor(params) {
22
+ const { agent, appName = "InMemoryRunner", plugins = [] } = params;
18
23
  super({
19
24
  appName,
20
25
  agent,
@@ -73,6 +73,7 @@ import {
73
73
  runAsyncGeneratorWithOtelContext,
74
74
  tracer
75
75
  } from "../telemetry/tracing.js";
76
+ import { isBaseToolset } from "../tools/base_toolset.js";
76
77
  import { logger } from "../utils/logger.js";
77
78
  import { isGemini2OrAbove } from "../utils/model_name.js";
78
79
  const RUNNER_SIGNATURE_SYMBOL = Symbol.for("google.adk.runner");
@@ -81,6 +82,11 @@ function isRunner(obj) {
81
82
  }
82
83
  _a = RUNNER_SIGNATURE_SYMBOL;
83
84
  class Runner {
85
+ /**
86
+ * Creates a new Runner instance.
87
+ *
88
+ * @param input The configuration for the runner.
89
+ */
84
90
  constructor(input) {
85
91
  this[_a] = true;
86
92
  var _a2;
@@ -114,7 +120,8 @@ class Runner {
114
120
  sessionId,
115
121
  newMessage: params.newMessage,
116
122
  stateDelta: params.stateDelta,
117
- runConfig: params.runConfig
123
+ runConfig: params.runConfig,
124
+ customMetadata: params.customMetadata
118
125
  }));
119
126
  } finally {
120
127
  yield new __await(this.sessionService.deleteSession({
@@ -222,7 +229,8 @@ class Runner {
222
229
  invocationId: invocationContext.invocationId,
223
230
  author: "user",
224
231
  actions: stateDelta ? createEventActions({ stateDelta }) : void 0,
225
- content: newMessage
232
+ content: newMessage,
233
+ customMetadata: params.customMetadata
226
234
  })
227
235
  }));
228
236
  if ((_e = params.abortSignal) == null ? void 0 : _e.aborted) {
@@ -300,6 +308,8 @@ class Runner {
300
308
  ));
301
309
  } finally {
302
310
  span.end();
311
+ const toolsets = getAllToolsets(this.agent);
312
+ yield new __await(Promise.allSettled(toolsets.map((t) => t.close())));
303
313
  }
304
314
  });
305
315
  }
@@ -420,6 +430,26 @@ function findEventByLastFunctionResponseId(events) {
420
430
  }
421
431
  return null;
422
432
  }
433
+ function getAllToolsets(agent) {
434
+ const toolsets = [];
435
+ const visited = /* @__PURE__ */ new Set();
436
+ function traverse(curr) {
437
+ if (visited.has(curr)) return;
438
+ visited.add(curr);
439
+ if (isLlmAgent(curr)) {
440
+ for (const tool of curr.tools) {
441
+ if (isBaseToolset(tool)) {
442
+ toolsets.push(tool);
443
+ }
444
+ }
445
+ }
446
+ for (const sub of curr.subAgents) {
447
+ traverse(sub);
448
+ }
449
+ }
450
+ traverse(agent);
451
+ return toolsets;
452
+ }
423
453
  export {
424
454
  Runner,
425
455
  isRunner
@@ -211,7 +211,11 @@ class DatabaseSessionService extends BaseSessionService {
211
211
  }
212
212
  async listSessions({
213
213
  appName,
214
- userId
214
+ userId,
215
+ limit,
216
+ offset,
217
+ page,
218
+ order
215
219
  }) {
216
220
  await this.init();
217
221
  const em = this.orm.em.fork();
@@ -219,7 +223,49 @@ class DatabaseSessionService extends BaseSessionService {
219
223
  if (userId) {
220
224
  where.userId = userId;
221
225
  }
222
- const storageSessions = await em.find(StorageSession, where);
226
+ const orderBy = order === "asc" ? { updateTime: "ASC", id: "ASC" } : order === "desc" ? { updateTime: "DESC", id: "ASC" } : void 0;
227
+ let storageSessions;
228
+ let paginationMeta;
229
+ if (limit !== void 0) {
230
+ const totalItems = await em.count(StorageSession, where);
231
+ const totalPages = limit === 0 ? 0 : Math.ceil(totalItems / limit);
232
+ let effectiveOffset;
233
+ let effectivePage;
234
+ if (page !== void 0) {
235
+ effectiveOffset = (page - 1) * limit;
236
+ effectivePage = page;
237
+ } else {
238
+ effectiveOffset = offset != null ? offset : 0;
239
+ effectivePage = limit === 0 ? 1 : Math.floor(effectiveOffset / limit) + 1;
240
+ }
241
+ storageSessions = await em.find(StorageSession, where, {
242
+ orderBy,
243
+ limit,
244
+ offset: effectiveOffset
245
+ });
246
+ paginationMeta = { page: effectivePage, limit, totalItems, totalPages };
247
+ } else if (offset) {
248
+ const totalItems = await em.count(StorageSession, where);
249
+ storageSessions = await em.find(StorageSession, where, {
250
+ orderBy,
251
+ offset
252
+ });
253
+ paginationMeta = {
254
+ page: 1,
255
+ limit: totalItems,
256
+ totalItems,
257
+ totalPages: totalItems === 0 ? 0 : 1
258
+ };
259
+ } else {
260
+ storageSessions = await em.find(StorageSession, where, { orderBy });
261
+ const totalItems = storageSessions.length;
262
+ paginationMeta = {
263
+ page: 1,
264
+ limit: totalItems,
265
+ totalItems,
266
+ totalPages: totalItems === 0 ? 0 : 1
267
+ };
268
+ }
223
269
  const appStateModel = await em.findOne(StorageAppState, { appName });
224
270
  const appState = (appStateModel == null ? void 0 : appStateModel.state) || {};
225
271
  const userStateMap = {};
@@ -244,7 +290,7 @@ class DatabaseSessionService extends BaseSessionService {
244
290
  lastUpdateTime: ss.updateTime.getTime()
245
291
  });
246
292
  });
247
- return { sessions };
293
+ return __spreadValues({ sessions }, paginationMeta);
248
294
  }
249
295
  async deleteSession({
250
296
  appName,