@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,77 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ import { BaseToolset } from "../../tools/base_toolset.js";
9
+ import {
10
+ MCPSessionManager
11
+ } from "../../tools/mcp/mcp_session_manager.js";
12
+ import { MCPTool } from "../../tools/mcp/mcp_tool.js";
13
+ import { GCP_MCP_SERVER_DESTINATION_ID } from "./types.js";
14
+ class AgentRegistrySingleMCPToolset extends BaseToolset {
15
+ constructor(options) {
16
+ super(options.toolFilter || [], options.prefix);
17
+ this.destinationResourceId = options.destinationResourceId;
18
+ this.connectionParams = options.connectionParams;
19
+ this.headerProvider = options.headerProvider;
20
+ this.authScheme = options.authScheme;
21
+ this.authCredential = options.authCredential;
22
+ }
23
+ /**
24
+ * Connects to the underlying MCP server, retrieves tool definitions, prefixes tool names,
25
+ * and injects destination telemetry metadata.
26
+ */
27
+ async getTools(context) {
28
+ var _a, _b, _c;
29
+ const headers = {};
30
+ if (this.headerProvider) {
31
+ const providerHeaders = await this.headerProvider(context);
32
+ Object.assign(headers, providerHeaders);
33
+ }
34
+ const connectionParamsCopy = {
35
+ ...this.connectionParams,
36
+ transportOptions: {
37
+ ...this.connectionParams.transportOptions,
38
+ requestInit: {
39
+ ...(_a = this.connectionParams.transportOptions) == null ? void 0 : _a.requestInit,
40
+ headers: {
41
+ ...(_c = (_b = this.connectionParams.transportOptions) == null ? void 0 : _b.requestInit) == null ? void 0 : _c.headers,
42
+ ...headers
43
+ }
44
+ }
45
+ }
46
+ };
47
+ const sessionManager = new MCPSessionManager(connectionParamsCopy);
48
+ const session = await sessionManager.createSession();
49
+ const listResult = await session.listTools();
50
+ const tools = listResult.tools.map((tool) => {
51
+ const prefixedName = this.prefix ? `${this.prefix}_${tool.name}` : tool.name;
52
+ const mcpTool = new MCPTool(
53
+ { ...tool, name: prefixedName },
54
+ sessionManager,
55
+ tool.name
56
+ );
57
+ const toolWithMetadata = mcpTool;
58
+ if (this.destinationResourceId) {
59
+ if (!toolWithMetadata.customMetadata) {
60
+ toolWithMetadata.customMetadata = {};
61
+ }
62
+ toolWithMetadata.customMetadata[GCP_MCP_SERVER_DESTINATION_ID] = this.destinationResourceId;
63
+ }
64
+ return mcpTool;
65
+ });
66
+ const filter = this.toolFilter;
67
+ if (!filter || Array.isArray(filter) && filter.length === 0) {
68
+ return tools;
69
+ }
70
+ return tools.filter((t) => this.isToolSelected(t, context));
71
+ }
72
+ async close() {
73
+ }
74
+ }
75
+ export {
76
+ AgentRegistrySingleMCPToolset
77
+ };
@@ -0,0 +1,28 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ function isGoogleApi(url) {
9
+ try {
10
+ const parsed = new URL(url);
11
+ return parsed.hostname === "googleapis.com" || parsed.hostname.endsWith(".googleapis.com");
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+ function cleanName(name) {
17
+ let clean = name.replace(/[^a-zA-Z0-9_]/g, "_");
18
+ clean = clean.replace(/_+/g, "_");
19
+ clean = clean.replace(/^_+|_+$/g, "");
20
+ if (clean && !/^[a-zA-Z_]/.test(clean)) {
21
+ clean = "_" + clean;
22
+ }
23
+ return clean;
24
+ }
25
+ export {
26
+ cleanName,
27
+ isGoogleApi
28
+ };
@@ -0,0 +1,20 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ const AGENT_REGISTRY_BASE_URL = "https://agentregistry.googleapis.com/v1alpha";
9
+ const GCP_MCP_SERVER_DESTINATION_ID = "gcp.mcp.server.destination.id";
10
+ var ProtocolType = /* @__PURE__ */ ((ProtocolType2) => {
11
+ ProtocolType2["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
12
+ ProtocolType2["A2A_AGENT"] = "A2A_AGENT";
13
+ ProtocolType2["CUSTOM"] = "CUSTOM";
14
+ return ProtocolType2;
15
+ })(ProtocolType || {});
16
+ export {
17
+ AGENT_REGISTRY_BASE_URL,
18
+ GCP_MCP_SERVER_DESTINATION_ID,
19
+ ProtocolType
20
+ };
@@ -0,0 +1,468 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ import { Client } from "@google-cloud/vertexai";
9
+ import { createUserContent } from "@google/genai";
10
+ import { logger } from "../utils/logger.js";
11
+ import { getExpressModeApiKey } from "../utils/vertex_ai_utils.js";
12
+ const GENERATE_MEMORIES_KNOWN_FIELDS = [
13
+ "disableConsolidation",
14
+ "waitForCompletion",
15
+ "revisionLabels",
16
+ "revisionExpireTime",
17
+ "revisionTtl",
18
+ "disableMemoryRevisions",
19
+ "metadataMergeStrategy",
20
+ "allowedTopics"
21
+ ];
22
+ const CREATE_MEMORY_KNOWN_FIELDS = [
23
+ "displayName",
24
+ "description",
25
+ "waitForCompletion",
26
+ "ttl",
27
+ "expireTime",
28
+ "revisionExpireTime",
29
+ "revisionTtl",
30
+ "disableMemoryRevisions",
31
+ "topics",
32
+ "memoryId"
33
+ ];
34
+ const ENABLE_CONSOLIDATION_KEY = "enable_consolidation";
35
+ const MAX_DIRECT_MEMORIES_PER_GENERATE_CALL = 5;
36
+ function shouldFilterOutEvent(content) {
37
+ return !((content == null ? void 0 : content.parts) || []).some(
38
+ (p) => p.text || p.inlineData || p.fileData
39
+ );
40
+ }
41
+ function toVertexMetadataValue(key, value) {
42
+ if (typeof value === "boolean") {
43
+ return { boolValue: value };
44
+ }
45
+ if (typeof value === "number") {
46
+ return { doubleValue: value };
47
+ }
48
+ if (typeof value === "string") {
49
+ return { stringValue: value };
50
+ }
51
+ if (value instanceof Date) {
52
+ return { timestampValue: value.toISOString() };
53
+ }
54
+ if (typeof value === "object" && value !== null) {
55
+ const v = value;
56
+ if (v.boolValue !== void 0 || v.doubleValue !== void 0 || v.stringValue !== void 0 || v.timestampValue !== void 0) {
57
+ return v;
58
+ }
59
+ return { stringValue: JSON.stringify(value) };
60
+ }
61
+ if (value === null || value === void 0) {
62
+ logger.warn(
63
+ `Ignoring custom metadata key ${key} because its value is null or undefined.`
64
+ );
65
+ return void 0;
66
+ }
67
+ return { stringValue: String(value) };
68
+ }
69
+ class VertexAiMemoryBankService {
70
+ constructor(options) {
71
+ if (!options.agentEngineId) {
72
+ throw new Error(
73
+ "agentEngineId is required for VertexAiMemoryBankService."
74
+ );
75
+ }
76
+ this.projectId = options.projectId;
77
+ this.location = options.location;
78
+ this.agentEngineId = options.agentEngineId;
79
+ this.expressModeApiKey = getExpressModeApiKey(
80
+ options.projectId,
81
+ options.location,
82
+ options.expressModeApiKey
83
+ );
84
+ if (options.agentEngineId.includes("/")) {
85
+ logger.warn(
86
+ `agentEngineId appears to be a full resource path: '${options.agentEngineId}'. Expected just the ID (e.g., '456'). Extract the ID using: agentEngine.apiResource.name.split('/').pop()`
87
+ );
88
+ }
89
+ if (options.client) {
90
+ this.memories = options.client.agentEnginesInternal.memories;
91
+ } else {
92
+ const client = new Client({
93
+ project: this.projectId,
94
+ location: this.location
95
+ });
96
+ this.memories = client.agentEnginesInternal.memories;
97
+ }
98
+ }
99
+ async addSessionToMemory(session) {
100
+ await this.addEventsToMemoryFromEvents({
101
+ appName: session.appName,
102
+ userId: session.userId,
103
+ eventsToProcess: session.events
104
+ });
105
+ }
106
+ /**
107
+ * Adds events to Vertex AI Memory Bank via memories.generate.
108
+ */
109
+ async addEventsToMemory(request) {
110
+ await this.addEventsToMemoryFromEvents({
111
+ appName: request.appName,
112
+ userId: request.userId,
113
+ eventsToProcess: request.events,
114
+ customMetadata: request.customMetadata
115
+ });
116
+ }
117
+ /**
118
+ * Adds explicit memory items using Vertex Memory Bank.
119
+ */
120
+ async addMemory(request) {
121
+ if (isConsolidationEnabled(request.customMetadata)) {
122
+ return this.addMemoriesViaGenerateDirectMemoriesSource(request);
123
+ }
124
+ await this.addMemoriesViaCreate(request);
125
+ }
126
+ async searchMemory(request) {
127
+ const params = {
128
+ name: `reasoningEngines/${this.agentEngineId}`,
129
+ scope: {
130
+ app_name: request.appName,
131
+ user_id: request.userId
132
+ },
133
+ similaritySearchParams: {
134
+ searchQuery: request.query
135
+ }
136
+ };
137
+ const retrievedMemoriesResponse = await this.memories.retrieveInternal(params);
138
+ logger.debug("Search memory response received.");
139
+ const memoryEvents = [];
140
+ const retrievedMemories = retrievedMemoriesResponse.retrievedMemories || [];
141
+ for (const retrievedMemory of retrievedMemories) {
142
+ logger.debug(`Retrieved memory: ${JSON.stringify(retrievedMemory)}`);
143
+ if (retrievedMemory.memory && retrievedMemory.memory.fact) {
144
+ const content = createUserContent(retrievedMemory.memory.fact);
145
+ memoryEvents.push({
146
+ author: "user",
147
+ content,
148
+ timestamp: retrievedMemory.memory.updateTime
149
+ });
150
+ }
151
+ }
152
+ return { memories: memoryEvents };
153
+ }
154
+ async addEventsToMemoryFromEvents(request) {
155
+ const directEvents = [];
156
+ for (const event of request.eventsToProcess) {
157
+ if (shouldFilterOutEvent(event.content)) {
158
+ continue;
159
+ }
160
+ directEvents.push({
161
+ content: JSON.parse(JSON.stringify(event.content))
162
+ });
163
+ }
164
+ if (directEvents.length > 0) {
165
+ const config = buildGenerateMemoriesConfig(request.customMetadata);
166
+ const params = {
167
+ name: `reasoningEngines/${this.agentEngineId}`,
168
+ directContentsSource: { events: directEvents },
169
+ scope: {
170
+ app_name: request.appName,
171
+ user_id: request.userId
172
+ },
173
+ config
174
+ };
175
+ const operation = await this.memories.generateInternal(params);
176
+ logger.debug("Generate memory response received.");
177
+ logger.debug(`Generate memory response: ${JSON.stringify(operation)}`);
178
+ } else {
179
+ logger.info("No events to add to memory.");
180
+ }
181
+ }
182
+ async addMemoriesViaCreate(request) {
183
+ const validatedMemories = normalizeMemoriesForCreate(request.memories);
184
+ for (let index = 0; index < validatedMemories.length; index++) {
185
+ const memory = validatedMemories[index];
186
+ const memoryFact = memoryEntryToFact(memory, index);
187
+ const memoryMetadata = mergeCustomMetadataForMemory({
188
+ customMetadata: request.customMetadata,
189
+ memory
190
+ });
191
+ const memoryRevisionLabels = revisionLabelsForMemory(memory);
192
+ const config = buildCreateMemoryConfig({
193
+ customMetadata: memoryMetadata,
194
+ memoryRevisionLabels
195
+ });
196
+ const params = {
197
+ name: `reasoningEngines/${this.agentEngineId}`,
198
+ fact: memoryFact,
199
+ scope: {
200
+ app_name: request.appName,
201
+ user_id: request.userId
202
+ },
203
+ config
204
+ };
205
+ const operation = await this.memories.createInternal(params);
206
+ logger.info("Create memory response received.");
207
+ logger.debug(`Create memory response: ${JSON.stringify(operation)}`);
208
+ }
209
+ }
210
+ async addMemoriesViaGenerateDirectMemoriesSource(request) {
211
+ const validatedMemories = normalizeMemoriesForCreate(request.memories);
212
+ const memoryTexts = validatedMemories.map(
213
+ (m, i) => memoryEntryToFact(m, i)
214
+ );
215
+ const config = buildGenerateMemoriesConfig(request.customMetadata);
216
+ const memoryBatches = iterMemoryBatches(memoryTexts);
217
+ for (const memoryBatch of memoryBatches) {
218
+ const params = {
219
+ name: `reasoningEngines/${this.agentEngineId}`,
220
+ directMemoriesSource: {
221
+ directMemories: memoryBatch.map((fact) => ({ fact }))
222
+ },
223
+ scope: {
224
+ app_name: request.appName,
225
+ user_id: request.userId
226
+ },
227
+ config
228
+ };
229
+ const operation = await this.memories.generateInternal(params);
230
+ logger.info("Generate direct memory response received.");
231
+ logger.debug(
232
+ `Generate direct memory response: ${JSON.stringify(operation)}`
233
+ );
234
+ }
235
+ }
236
+ }
237
+ function buildCreateMemoryConfig(params) {
238
+ const config = { waitForCompletion: false };
239
+ if (params.customMetadata) {
240
+ logger.debug(
241
+ `Memory creation metadata: ${JSON.stringify(params.customMetadata)}`
242
+ );
243
+ }
244
+ const metadataByKey = {};
245
+ const customRevisionLabels = {};
246
+ for (const [key, value] of Object.entries(params.customMetadata || {})) {
247
+ if (key === ENABLE_CONSOLIDATION_KEY) {
248
+ continue;
249
+ }
250
+ if (key === "metadata") {
251
+ if (value === null || value === void 0) continue;
252
+ if (typeof value === "object" && !Array.isArray(value)) {
253
+ config["metadata"] = buildVertexMetadata(
254
+ value
255
+ );
256
+ } else {
257
+ logger.warn(
258
+ 'Ignoring metadata because customMetadata["metadata"] is not an object.'
259
+ );
260
+ }
261
+ continue;
262
+ }
263
+ if (key === "revisionLabels") {
264
+ if (value === null || value === void 0) continue;
265
+ const extractedLabels = extractRevisionLabels(
266
+ value,
267
+ 'customMetadata["revisionLabels"]'
268
+ );
269
+ if (extractedLabels) {
270
+ Object.assign(customRevisionLabels, extractedLabels);
271
+ }
272
+ continue;
273
+ }
274
+ if (CREATE_MEMORY_KNOWN_FIELDS.includes(key)) {
275
+ if (value !== null && value !== void 0) {
276
+ config[key] = value;
277
+ }
278
+ } else {
279
+ metadataByKey[key] = value;
280
+ }
281
+ }
282
+ if (Object.keys(metadataByKey).length > 0) {
283
+ const existingMetadata = config["metadata"];
284
+ if (!existingMetadata) {
285
+ config["metadata"] = buildVertexMetadata(metadataByKey);
286
+ } else {
287
+ config["metadata"] = {
288
+ ...existingMetadata,
289
+ ...buildVertexMetadata(metadataByKey)
290
+ };
291
+ }
292
+ }
293
+ const revisionLabels = {
294
+ ...customRevisionLabels,
295
+ ...params.memoryRevisionLabels
296
+ };
297
+ if (Object.keys(revisionLabels).length > 0) {
298
+ config["revisionLabels"] = revisionLabels;
299
+ }
300
+ return config;
301
+ }
302
+ function extractRevisionLabels(value, source) {
303
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
304
+ logger.warn(`Ignoring ${source} because it is not an object.`);
305
+ return void 0;
306
+ }
307
+ const revisionLabels = {};
308
+ for (const [key, labelValue] of Object.entries(value)) {
309
+ if (typeof labelValue !== "string") {
310
+ logger.warn(
311
+ `Ignoring revision label ${key} from ${source} because its value is not a string.`
312
+ );
313
+ continue;
314
+ }
315
+ revisionLabels[key] = labelValue;
316
+ }
317
+ if (Object.keys(revisionLabels).length === 0) {
318
+ return void 0;
319
+ }
320
+ return revisionLabels;
321
+ }
322
+ function buildVertexMetadata(metadataByKey) {
323
+ const vertexMetadata = {};
324
+ for (const [key, value] of Object.entries(metadataByKey)) {
325
+ const convertedValue = toVertexMetadataValue(key, value);
326
+ if (convertedValue !== void 0) {
327
+ vertexMetadata[key] = convertedValue;
328
+ }
329
+ }
330
+ return vertexMetadata;
331
+ }
332
+ function buildGenerateMemoriesConfig(customMetadata) {
333
+ const config = { waitForCompletion: false };
334
+ if (!customMetadata) {
335
+ return config;
336
+ }
337
+ logger.debug(`Memory generation metadata: ${JSON.stringify(customMetadata)}`);
338
+ const metadataByKey = {};
339
+ for (const [key, value] of Object.entries(customMetadata)) {
340
+ if (key === ENABLE_CONSOLIDATION_KEY) {
341
+ continue;
342
+ }
343
+ if (key === "ttl") {
344
+ if (value === null || value === void 0) continue;
345
+ if (customMetadata["revisionTtl"] === void 0) {
346
+ config["revisionTtl"] = value;
347
+ }
348
+ continue;
349
+ }
350
+ if (key === "metadata") {
351
+ if (value === null || value === void 0) continue;
352
+ if (typeof value === "object" && !Array.isArray(value)) {
353
+ config["metadata"] = buildVertexMetadata(
354
+ value
355
+ );
356
+ } else {
357
+ logger.warn(
358
+ 'Ignoring metadata because customMetadata["metadata"] is not an object.'
359
+ );
360
+ }
361
+ continue;
362
+ }
363
+ if (GENERATE_MEMORIES_KNOWN_FIELDS.includes(key)) {
364
+ if (value !== null && value !== void 0) {
365
+ config[key] = value;
366
+ }
367
+ } else {
368
+ metadataByKey[key] = value;
369
+ }
370
+ }
371
+ if (Object.keys(metadataByKey).length > 0) {
372
+ const existingMetadata = config["metadata"];
373
+ if (!existingMetadata) {
374
+ config["metadata"] = buildVertexMetadata(metadataByKey);
375
+ } else {
376
+ config["metadata"] = {
377
+ ...existingMetadata,
378
+ ...buildVertexMetadata(metadataByKey)
379
+ };
380
+ }
381
+ }
382
+ return config;
383
+ }
384
+ function normalizeMemoriesForCreate(memories) {
385
+ if (!Array.isArray(memories)) {
386
+ throw new TypeError("memories must be a sequence of memory items.");
387
+ }
388
+ if (memories.length === 0) {
389
+ throw new Error("memories must contain at least one entry.");
390
+ }
391
+ return memories;
392
+ }
393
+ function memoryEntryToFact(memory, index) {
394
+ const textParts = [];
395
+ if (memory.content && memory.content.parts) {
396
+ for (const part of memory.content.parts) {
397
+ if (part.inlineData || part.fileData) {
398
+ throw new Error(
399
+ `memories[${index}] must include text only; inlineData and fileData are not supported.`
400
+ );
401
+ }
402
+ if (part.text) {
403
+ const strippedText = part.text.trim();
404
+ if (strippedText) {
405
+ textParts.push(strippedText);
406
+ }
407
+ }
408
+ }
409
+ }
410
+ if (textParts.length === 0) {
411
+ throw new Error(`memories[${index}] must include non-whitespace text.`);
412
+ }
413
+ return textParts.join("\n");
414
+ }
415
+ function mergeCustomMetadataForMemory(params) {
416
+ const mergedMetadata = {};
417
+ if (params.customMetadata) {
418
+ Object.assign(mergedMetadata, params.customMetadata);
419
+ }
420
+ const memoryWithMetadata = params.memory;
421
+ if (memoryWithMetadata.customMetadata) {
422
+ Object.assign(mergedMetadata, memoryWithMetadata.customMetadata);
423
+ }
424
+ if (Object.keys(mergedMetadata).length === 0) {
425
+ return void 0;
426
+ }
427
+ return mergedMetadata;
428
+ }
429
+ function revisionLabelsForMemory(memory) {
430
+ const revisionLabels = {};
431
+ if (memory.author) {
432
+ revisionLabels["author"] = memory.author;
433
+ }
434
+ if (memory.timestamp) {
435
+ revisionLabels["timestamp"] = memory.timestamp;
436
+ }
437
+ if (Object.keys(revisionLabels).length === 0) {
438
+ return void 0;
439
+ }
440
+ return revisionLabels;
441
+ }
442
+ function isConsolidationEnabled(customMetadata) {
443
+ if (!customMetadata) {
444
+ return false;
445
+ }
446
+ const enableConsolidation = customMetadata[ENABLE_CONSOLIDATION_KEY];
447
+ if (enableConsolidation === void 0) {
448
+ return false;
449
+ }
450
+ if (typeof enableConsolidation !== "boolean") {
451
+ throw new TypeError(
452
+ `customMetadata["${ENABLE_CONSOLIDATION_KEY}"] must be a bool.`
453
+ );
454
+ }
455
+ return enableConsolidation;
456
+ }
457
+ function iterMemoryBatches(memories) {
458
+ const memoryBatches = [];
459
+ for (let index = 0; index < memories.length; index += MAX_DIRECT_MEMORIES_PER_GENERATE_CALL) {
460
+ memoryBatches.push(
461
+ memories.slice(index, index + MAX_DIRECT_MEMORIES_PER_GENERATE_CALL)
462
+ );
463
+ }
464
+ return memoryBatches;
465
+ }
466
+ export {
467
+ VertexAiMemoryBankService
468
+ };
@@ -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,
@@ -25,6 +25,7 @@ import {
25
25
  runAsyncGeneratorWithOtelContext,
26
26
  tracer
27
27
  } from "../telemetry/tracing.js";
28
+ import { isBaseToolset } from "../tools/base_toolset.js";
28
29
  import { logger } from "../utils/logger.js";
29
30
  import { isGemini2OrAbove } from "../utils/model_name.js";
30
31
  const RUNNER_SIGNATURE_SYMBOL = Symbol.for("google.adk.runner");
@@ -33,6 +34,11 @@ function isRunner(obj) {
33
34
  }
34
35
  _a = RUNNER_SIGNATURE_SYMBOL;
35
36
  class Runner {
37
+ /**
38
+ * Creates a new Runner instance.
39
+ *
40
+ * @param input The configuration for the runner.
41
+ */
36
42
  constructor(input) {
37
43
  this[_a] = true;
38
44
  var _a2;
@@ -65,7 +71,8 @@ class Runner {
65
71
  sessionId,
66
72
  newMessage: params.newMessage,
67
73
  stateDelta: params.stateDelta,
68
- runConfig: params.runConfig
74
+ runConfig: params.runConfig,
75
+ customMetadata: params.customMetadata
69
76
  });
70
77
  } finally {
71
78
  await this.sessionService.deleteSession({
@@ -170,7 +177,8 @@ class Runner {
170
177
  invocationId: invocationContext.invocationId,
171
178
  author: "user",
172
179
  actions: stateDelta ? createEventActions({ stateDelta }) : void 0,
173
- content: newMessage
180
+ content: newMessage,
181
+ customMetadata: params.customMetadata
174
182
  })
175
183
  });
176
184
  if ((_e = params.abortSignal) == null ? void 0 : _e.aborted) {
@@ -235,6 +243,8 @@ class Runner {
235
243
  );
236
244
  } finally {
237
245
  span.end();
246
+ const toolsets = getAllToolsets(this.agent);
247
+ await Promise.allSettled(toolsets.map((t) => t.close()));
238
248
  }
239
249
  }
240
250
  /**
@@ -354,6 +364,26 @@ function findEventByLastFunctionResponseId(events) {
354
364
  }
355
365
  return null;
356
366
  }
367
+ function getAllToolsets(agent) {
368
+ const toolsets = [];
369
+ const visited = /* @__PURE__ */ new Set();
370
+ function traverse(curr) {
371
+ if (visited.has(curr)) return;
372
+ visited.add(curr);
373
+ if (isLlmAgent(curr)) {
374
+ for (const tool of curr.tools) {
375
+ if (isBaseToolset(tool)) {
376
+ toolsets.push(tool);
377
+ }
378
+ }
379
+ }
380
+ for (const sub of curr.subAgents) {
381
+ traverse(sub);
382
+ }
383
+ }
384
+ traverse(agent);
385
+ return toolsets;
386
+ }
357
387
  export {
358
388
  Runner,
359
389
  isRunner