@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
@@ -104,25 +104,81 @@ class InMemorySessionService extends BaseSessionService {
104
104
  }
105
105
  listSessions({
106
106
  appName,
107
- userId
107
+ userId,
108
+ limit,
109
+ offset,
110
+ page,
111
+ order
108
112
  }) {
109
113
  if (!this.sessions[appName] || !this.sessions[appName][userId]) {
110
- return Promise.resolve({ sessions: [] });
114
+ if (limit !== void 0) {
115
+ const effectiveOffset2 = page !== void 0 ? (page - 1) * limit : offset != null ? offset : 0;
116
+ const effectivePage2 = page !== void 0 ? page : limit === 0 ? 1 : Math.floor(effectiveOffset2 / limit) + 1;
117
+ return Promise.resolve({
118
+ sessions: [],
119
+ page: effectivePage2,
120
+ limit,
121
+ totalItems: 0,
122
+ totalPages: 0
123
+ });
124
+ }
125
+ return Promise.resolve({
126
+ sessions: [],
127
+ page: 1,
128
+ limit: 0,
129
+ totalItems: 0,
130
+ totalPages: 0
131
+ });
111
132
  }
112
- const sessionsWithoutEvents = [];
113
- for (const session of Object.values(this.sessions[appName][userId])) {
114
- sessionsWithoutEvents.push(
115
- createSession({
116
- id: session.id,
117
- appName: session.appName,
118
- userId: session.userId,
119
- state: {},
120
- events: [],
121
- lastUpdateTime: session.lastUpdateTime
122
- })
133
+ const all = Object.values(this.sessions[appName][userId]).map(
134
+ (session) => createSession({
135
+ id: session.id,
136
+ appName: session.appName,
137
+ userId: session.userId,
138
+ state: {},
139
+ events: [],
140
+ lastUpdateTime: session.lastUpdateTime
141
+ })
142
+ );
143
+ if (order === "asc") {
144
+ all.sort(
145
+ (a, b) => a.lastUpdateTime - b.lastUpdateTime || a.id.localeCompare(b.id)
146
+ );
147
+ } else if (order === "desc") {
148
+ all.sort(
149
+ (a, b) => b.lastUpdateTime - a.lastUpdateTime || a.id.localeCompare(b.id)
123
150
  );
124
151
  }
125
- return Promise.resolve({ sessions: sessionsWithoutEvents });
152
+ if (limit === void 0) {
153
+ const totalItems2 = all.length;
154
+ const sliced = offset ? all.slice(offset) : all;
155
+ return Promise.resolve({
156
+ sessions: sliced,
157
+ page: 1,
158
+ limit: totalItems2,
159
+ totalItems: totalItems2,
160
+ totalPages: totalItems2 === 0 ? 0 : 1
161
+ });
162
+ }
163
+ const totalItems = all.length;
164
+ const totalPages = limit === 0 ? 0 : Math.ceil(totalItems / limit);
165
+ let effectiveOffset;
166
+ let effectivePage;
167
+ if (page !== void 0) {
168
+ effectiveOffset = (page - 1) * limit;
169
+ effectivePage = page;
170
+ } else {
171
+ effectiveOffset = offset != null ? offset : 0;
172
+ effectivePage = limit === 0 ? 1 : Math.floor(effectiveOffset / limit) + 1;
173
+ }
174
+ const paginated = all.slice(effectiveOffset, effectiveOffset + limit);
175
+ return Promise.resolve({
176
+ sessions: paginated,
177
+ page: effectivePage,
178
+ limit,
179
+ totalItems,
180
+ totalPages
181
+ });
126
182
  }
127
183
  async deleteSession({
128
184
  appName,
@@ -13,6 +13,10 @@ import {
13
13
  InMemorySessionService,
14
14
  isInMemoryConnectionString
15
15
  } from "./in_memory_session_service.js";
16
+ import {
17
+ VertexAiSessionService,
18
+ isVertexAiConnectionString
19
+ } from "./vertex_ai_session_service.js";
16
20
  function getSessionServiceFromUri(uri) {
17
21
  if (isInMemoryConnectionString(uri)) {
18
22
  return new InMemorySessionService();
@@ -20,6 +24,9 @@ function getSessionServiceFromUri(uri) {
20
24
  if (isDatabaseConnectionString(uri)) {
21
25
  return new DatabaseSessionService(uri);
22
26
  }
27
+ if (isVertexAiConnectionString(uri)) {
28
+ return new VertexAiSessionService({});
29
+ }
23
30
  throw new Error("Unsupported session service URI: ".concat(uri));
24
31
  }
25
32
  export {
@@ -0,0 +1,414 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __decorateClass = (decorators, target, key, kind) => {
24
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
25
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
26
+ if (decorator = decorators[i])
27
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
28
+ if (kind && result) __defProp(target, key, result);
29
+ return result;
30
+ };
31
+ /**
32
+ * @license
33
+ * Copyright 2026 Google LLC
34
+ * SPDX-License-Identifier: Apache-2.0
35
+ */
36
+ import { Client } from "@google-cloud/vertexai/build/src/genai/client.js";
37
+ import { isCompactedEvent } from "../events/compacted_event.js";
38
+ import { experimental } from "../utils/experimental.js";
39
+ import { logger } from "../utils/logger.js";
40
+ import { getExpressModeApiKey } from "../utils/vertex_ai_utils.js";
41
+ import { partialCopy } from "../utils/partial_copy.js";
42
+ import {
43
+ BaseSessionService
44
+ } from "./base_session_service.js";
45
+ import { createSession } from "./session.js";
46
+ const DEFAULT_MAX_ATTEMPTS = 30;
47
+ const GRPC_NOT_FOUND = 5;
48
+ const HTTP_NOT_FOUND = 404;
49
+ function isVertexAiConnectionString(uri) {
50
+ return (uri == null ? void 0 : uri.startsWith("vertexai://")) || false;
51
+ }
52
+ let VertexAiSessionService = class extends BaseSessionService {
53
+ constructor(options) {
54
+ super();
55
+ this.agentEngineId = options.agentEngineId;
56
+ this.projectId = options.projectId;
57
+ this.location = options.location;
58
+ this.expressModeApiKey = getExpressModeApiKey(
59
+ this.projectId,
60
+ this.location,
61
+ options.expressModeApiKey
62
+ );
63
+ if (!options.sessions) {
64
+ if (!this.expressModeApiKey && (!this.projectId || !this.location)) {
65
+ throw new Error(
66
+ "Either (Project ID and Location) or an expressModeApiKey is required."
67
+ );
68
+ }
69
+ }
70
+ if (options.sessions) {
71
+ this.sessions = options.sessions;
72
+ } else {
73
+ const client = new Client({
74
+ project: this.projectId,
75
+ location: this.location
76
+ });
77
+ this.sessions = client.agentEnginesInternal.sessions;
78
+ }
79
+ }
80
+ getReasoningEngineId(appName) {
81
+ if (this.agentEngineId) {
82
+ return this.agentEngineId;
83
+ }
84
+ if (/^\d+$/.test(appName)) {
85
+ return appName;
86
+ }
87
+ const pattern = /^projects\/([a-zA-Z0-9-_]+)\/locations\/([a-zA-Z0-9-_]+)\/reasoningEngines\/(\d+)$/;
88
+ const match = appName.match(pattern);
89
+ if (!match) {
90
+ throw new Error(
91
+ "App name ".concat(appName, " is not valid. It should either be the full ReasoningEngine resource name, or the reasoning engine id.")
92
+ );
93
+ }
94
+ return match[3];
95
+ }
96
+ async createSession({
97
+ appName,
98
+ userId,
99
+ state,
100
+ sessionId
101
+ }) {
102
+ var _a;
103
+ const reasoningEngineId = this.getReasoningEngineId(appName);
104
+ let apiResponse = await this.sessions.createInternal({
105
+ name: "reasoningEngines/".concat(reasoningEngineId),
106
+ userId,
107
+ config: __spreadValues(__spreadValues({}, state ? { sessionState: state } : {}), sessionId ? { sessionId } : {})
108
+ });
109
+ const operationName = apiResponse.name;
110
+ let attempts = 0;
111
+ while (!apiResponse.done && attempts < DEFAULT_MAX_ATTEMPTS) {
112
+ const [nextResponse] = await Promise.all([
113
+ this.sessions.getSessionOperationInternal({
114
+ operationName
115
+ }),
116
+ new Promise((resolve) => setTimeout(resolve, 1e3))
117
+ ]);
118
+ apiResponse = nextResponse;
119
+ attempts++;
120
+ }
121
+ if (!apiResponse.done) {
122
+ throw new Error(
123
+ "Session creation operation ".concat(operationName, " did not complete in time.")
124
+ );
125
+ }
126
+ const getSessionResponse = apiResponse.response;
127
+ const id = ((_a = getSessionResponse.name) == null ? void 0 : _a.split("/").pop()) || "";
128
+ return createSession({
129
+ id,
130
+ appName,
131
+ userId,
132
+ state: getSessionResponse.sessionState,
133
+ events: [],
134
+ lastUpdateTime: getSessionResponse.updateTime ? Date.parse(getSessionResponse.updateTime) : Date.now()
135
+ });
136
+ }
137
+ async getSession({
138
+ appName,
139
+ userId,
140
+ sessionId,
141
+ config
142
+ }) {
143
+ const reasoningEngineId = this.getReasoningEngineId(appName);
144
+ const sessionResourceName = "reasoningEngines/".concat(reasoningEngineId, "/sessions/").concat(sessionId);
145
+ try {
146
+ let getSessionResponse;
147
+ let eventsIterator = [];
148
+ if (config && config.numRecentEvents === 0) {
149
+ getSessionResponse = await this.sessions.get({
150
+ name: sessionResourceName
151
+ });
152
+ } else {
153
+ const listConfig = {};
154
+ if (config && config.afterTimestamp) {
155
+ listConfig.filter = 'timestamp>="'.concat(new Date(
156
+ config.afterTimestamp
157
+ ).toISOString(), '"');
158
+ }
159
+ const [sessionRes, eventsRes] = await Promise.all([
160
+ this.sessions.get({ name: sessionResourceName }),
161
+ this.sessions.events.listInternal({
162
+ name: sessionResourceName,
163
+ config: listConfig
164
+ })
165
+ ]);
166
+ getSessionResponse = sessionRes;
167
+ eventsIterator = eventsRes.sessionEvents || [];
168
+ }
169
+ const sessionObj = getSessionResponse;
170
+ if (sessionObj.userId !== userId) {
171
+ throw new Error(
172
+ "Session ".concat(sessionId, " does not belong to user ").concat(userId, ".")
173
+ );
174
+ }
175
+ const session = createSession({
176
+ id: sessionId,
177
+ appName,
178
+ userId,
179
+ state: sessionObj.sessionState,
180
+ events: [],
181
+ lastUpdateTime: sessionObj.updateTime ? Date.parse(sessionObj.updateTime) : Date.now()
182
+ });
183
+ for (const event of eventsIterator) {
184
+ session.events.push(_fromApiEvent(event));
185
+ }
186
+ if (config && config.numRecentEvents) {
187
+ session.events = session.events.slice(-config.numRecentEvents);
188
+ }
189
+ return session;
190
+ } catch (error) {
191
+ const err = error;
192
+ if (err.code === GRPC_NOT_FOUND || err.code === HTTP_NOT_FOUND) {
193
+ return void 0;
194
+ }
195
+ logger.error("Error getting session from Vertex AI: ".concat(err.message));
196
+ throw error;
197
+ }
198
+ }
199
+ async listSessions({
200
+ appName,
201
+ userId,
202
+ limit,
203
+ offset,
204
+ page,
205
+ order
206
+ }) {
207
+ var _a;
208
+ const reasoningEngineId = this.getReasoningEngineId(appName);
209
+ const adkSessions = [];
210
+ let pageToken = void 0;
211
+ do {
212
+ const response = await this.sessions.listInternal({
213
+ name: "reasoningEngines/".concat(reasoningEngineId),
214
+ config: __spreadValues(__spreadValues({}, userId ? { filter: 'user_id="'.concat(userId, '"') } : {}), pageToken ? { pageToken } : {})
215
+ });
216
+ const sessions = response.sessions || [];
217
+ for (const sessionObj of sessions) {
218
+ const id = ((_a = sessionObj.name) == null ? void 0 : _a.split("/").pop()) || "";
219
+ adkSessions.push(
220
+ createSession({
221
+ id,
222
+ appName,
223
+ userId: sessionObj.userId,
224
+ state: sessionObj.sessionState,
225
+ events: [],
226
+ lastUpdateTime: sessionObj.updateTime ? new Date(sessionObj.updateTime).getTime() : Date.now()
227
+ })
228
+ );
229
+ }
230
+ pageToken = response.nextPageToken;
231
+ } while (pageToken);
232
+ if (order === "asc") {
233
+ adkSessions.sort(
234
+ (a, b) => a.lastUpdateTime - b.lastUpdateTime || a.id.localeCompare(b.id)
235
+ );
236
+ } else if (order === "desc") {
237
+ adkSessions.sort(
238
+ (a, b) => b.lastUpdateTime - a.lastUpdateTime || a.id.localeCompare(b.id)
239
+ );
240
+ }
241
+ if (limit === void 0) {
242
+ const totalItems2 = adkSessions.length;
243
+ const sliced = offset ? adkSessions.slice(offset) : adkSessions;
244
+ return {
245
+ sessions: sliced,
246
+ page: 1,
247
+ limit: totalItems2,
248
+ totalItems: totalItems2,
249
+ totalPages: totalItems2 === 0 ? 0 : 1
250
+ };
251
+ }
252
+ const totalItems = adkSessions.length;
253
+ const totalPages = limit === 0 ? 0 : Math.ceil(totalItems / limit);
254
+ let effectiveOffset;
255
+ let effectivePage;
256
+ if (page !== void 0) {
257
+ effectiveOffset = (page - 1) * limit;
258
+ effectivePage = page;
259
+ } else {
260
+ effectiveOffset = offset != null ? offset : 0;
261
+ effectivePage = limit === 0 ? 1 : Math.floor(effectiveOffset / limit) + 1;
262
+ }
263
+ return {
264
+ sessions: adkSessions.slice(effectiveOffset, effectiveOffset + limit),
265
+ page: effectivePage,
266
+ limit,
267
+ totalItems,
268
+ totalPages
269
+ };
270
+ }
271
+ async deleteSession({
272
+ appName,
273
+ userId: _userId,
274
+ sessionId
275
+ }) {
276
+ const reasoningEngineId = this.getReasoningEngineId(appName);
277
+ await this.sessions.delete({
278
+ name: "reasoningEngines/".concat(reasoningEngineId, "/sessions/").concat(sessionId)
279
+ });
280
+ }
281
+ async appendEvent({
282
+ session,
283
+ event
284
+ }) {
285
+ await super.appendEvent({ session, event });
286
+ session.lastUpdateTime = event.timestamp;
287
+ const reasoningEngineId = this.getReasoningEngineId(session.appName);
288
+ const customMetadata = __spreadValues({}, event.customMetadata);
289
+ if (isCompactedEvent(event)) {
290
+ customMetadata._compaction = {
291
+ startTime: event.startTime,
292
+ endTime: event.endTime,
293
+ compactedContent: event.compactedContent
294
+ };
295
+ }
296
+ if (event.usageMetadata) {
297
+ customMetadata._usage_metadata = event.usageMetadata;
298
+ }
299
+ const config = partialCopy(event, [
300
+ "content",
301
+ "actions",
302
+ "errorCode",
303
+ "errorMessage"
304
+ ]);
305
+ config.eventMetadata = __spreadProps(__spreadValues({}, partialCopy(event, [
306
+ "partial",
307
+ "turnComplete",
308
+ "interrupted",
309
+ "branch",
310
+ "longRunningToolIds",
311
+ "groundingMetadata"
312
+ ])), {
313
+ customMetadata: Object.keys(customMetadata).length > 0 ? customMetadata : void 0
314
+ });
315
+ config.rawEvent = JSON.parse(JSON.stringify(event));
316
+ const params = {
317
+ name: "reasoningEngines/".concat(reasoningEngineId, "/sessions/").concat(session.id),
318
+ author: event.author || "user",
319
+ invocationId: event.invocationId || "inv-".concat(Date.now()),
320
+ timestamp: new Date(event.timestamp).toISOString(),
321
+ config
322
+ };
323
+ try {
324
+ await this.sessions.events.append(params);
325
+ } catch (error) {
326
+ logger.warn(
327
+ "Failed to append event with rawEvent, falling back...",
328
+ error
329
+ );
330
+ delete config.rawEvent;
331
+ await this.sessions.events.append({
332
+ name: "reasoningEngines/".concat(reasoningEngineId, "/sessions/").concat(session.id),
333
+ author: event.author || "user",
334
+ invocationId: event.invocationId || "inv-".concat(Date.now()),
335
+ timestamp: new Date(event.timestamp).toISOString(),
336
+ config
337
+ });
338
+ }
339
+ return event;
340
+ }
341
+ };
342
+ VertexAiSessionService = __decorateClass([
343
+ experimental
344
+ ], VertexAiSessionService);
345
+ function _fromApiEvent(apiEventObj) {
346
+ var _a, _b, _c;
347
+ const rawEvent = apiEventObj.rawEvent;
348
+ if (rawEvent) {
349
+ const event2 = JSON.parse(JSON.stringify(rawEvent));
350
+ event2.id = ((_a = apiEventObj.name) == null ? void 0 : _a.split("/").pop()) || "";
351
+ event2.invocationId = apiEventObj.invocationId || "";
352
+ event2.author = apiEventObj.author;
353
+ if (apiEventObj.timestamp) {
354
+ event2.timestamp = new Date(apiEventObj.timestamp).getTime();
355
+ }
356
+ return event2;
357
+ }
358
+ const actions = apiEventObj.actions || {};
359
+ const eventMetadata = apiEventObj.eventMetadata || {};
360
+ let customMetadata = eventMetadata.customMetadata;
361
+ let compactionData = null;
362
+ let usageMetadataData = null;
363
+ if (customMetadata) {
364
+ if (customMetadata._compaction) {
365
+ compactionData = customMetadata._compaction;
366
+ delete customMetadata._compaction;
367
+ }
368
+ if (customMetadata._usage_metadata) {
369
+ usageMetadataData = customMetadata._usage_metadata;
370
+ delete customMetadata._usage_metadata;
371
+ }
372
+ if (Object.keys(customMetadata).length === 0) {
373
+ customMetadata = void 0;
374
+ }
375
+ }
376
+ const eventActions = {
377
+ stateDelta: actions["stateDelta"] || {},
378
+ artifactDelta: actions["artifactDelta"] || {},
379
+ requestedAuthConfigs: actions.requestedAuthConfigs || {},
380
+ requestedToolConfirmations: actions["requestedToolConfirmations"] || {},
381
+ skipSummarization: actions["skipSummarization"],
382
+ transferToAgent: actions["transferAgent"],
383
+ escalate: actions["escalate"],
384
+ compaction: compactionData || void 0
385
+ };
386
+ const event = {
387
+ id: ((_b = apiEventObj.name) == null ? void 0 : _b.split("/").pop()) || "",
388
+ invocationId: apiEventObj.invocationId || "",
389
+ author: apiEventObj.author,
390
+ actions: eventActions,
391
+ content: apiEventObj.content,
392
+ timestamp: apiEventObj.timestamp ? new Date(apiEventObj.timestamp).getTime() : Date.now(),
393
+ errorCode: (_c = apiEventObj.errorCode) == null ? void 0 : _c.toString(),
394
+ errorMessage: apiEventObj.errorMessage,
395
+ partial: eventMetadata["partial"],
396
+ turnComplete: eventMetadata["turnComplete"],
397
+ interrupted: eventMetadata["interrupted"],
398
+ branch: eventMetadata["branch"],
399
+ customMetadata,
400
+ longRunningToolIds: eventMetadata["longRunningToolIds"],
401
+ usageMetadata: usageMetadataData
402
+ };
403
+ if (compactionData) {
404
+ event.isCompacted = true;
405
+ event.startTime = compactionData.startTime;
406
+ event.endTime = compactionData.endTime;
407
+ event.compactedContent = compactionData.compactedContent;
408
+ }
409
+ return event;
410
+ }
411
+ export {
412
+ VertexAiSessionService,
413
+ isVertexAiConnectionString
414
+ };
@@ -29,6 +29,7 @@ import { InMemoryMemoryService } from "../memory/in_memory_memory_service.js";
29
29
  import { Runner } from "../runner/runner.js";
30
30
  import { InMemorySessionService } from "../sessions/in_memory_session_service.js";
31
31
  import { GoogleLLMVariant } from "../utils/variant_utils.js";
32
+ import { State } from "../sessions/state.js";
32
33
  import { BaseTool } from "./base_tool.js";
33
34
  import { ForwardingArtifactService } from "./forwarding_artifact_service.js";
34
35
  const AGENT_TOOL_SIGNATURE_SYMBOL = Symbol.for("google.adk.agentTool");
@@ -139,9 +140,6 @@ class AgentTool extends (_b = BaseTool, _a = AGENT_TOOL_SIGNATURE_SYMBOL, _b) {
139
140
  toolContext
140
141
  }) {
141
142
  var _a2, _b2;
142
- if (this.skipSummarization) {
143
- toolContext.actions.skipSummarization = true;
144
- }
145
143
  const { runner, content, sessionUserId, sessionId } = await this.setupRunnerAndSession({ args, toolContext });
146
144
  if ((_a2 = toolContext.abortSignal) == null ? void 0 : _a2.aborted) {
147
145
  return "";
@@ -160,7 +158,14 @@ class AgentTool extends (_b = BaseTool, _a = AGENT_TOOL_SIGNATURE_SYMBOL, _b) {
160
158
  return;
161
159
  }
162
160
  if (event.actions.stateDelta) {
163
- toolContext.state.update(event.actions.stateDelta);
161
+ const filteredDelta = Object.fromEntries(
162
+ Object.entries(event.actions.stateDelta).filter(
163
+ ([key]) => !key.startsWith(State.TEMP_PREFIX)
164
+ )
165
+ );
166
+ if (Object.keys(filteredDelta).length > 0) {
167
+ toolContext.state.update(filteredDelta);
168
+ }
164
169
  }
165
170
  lastEvent = event;
166
171
  }
@@ -190,9 +195,6 @@ class AgentTool extends (_b = BaseTool, _a = AGENT_TOOL_SIGNATURE_SYMBOL, _b) {
190
195
  toolContext
191
196
  }) {
192
197
  var _a2, _b2;
193
- if (this.skipSummarization) {
194
- toolContext.actions.skipSummarization = true;
195
- }
196
198
  const { runner, content, sessionUserId, sessionId } = yield new __await(this.setupRunnerAndSession({ args, toolContext }));
197
199
  if ((_a2 = toolContext.abortSignal) == null ? void 0 : _a2.aborted) {
198
200
  return;
@@ -210,7 +212,14 @@ class AgentTool extends (_b = BaseTool, _a = AGENT_TOOL_SIGNATURE_SYMBOL, _b) {
210
212
  return;
211
213
  }
212
214
  if (event.actions.stateDelta) {
213
- toolContext.state.update(event.actions.stateDelta);
215
+ const filteredDelta = Object.fromEntries(
216
+ Object.entries(event.actions.stateDelta).filter(
217
+ ([key]) => !key.startsWith(State.TEMP_PREFIX)
218
+ )
219
+ );
220
+ if (Object.keys(filteredDelta).length > 0) {
221
+ toolContext.state.update(filteredDelta);
222
+ }
214
223
  }
215
224
  yield event;
216
225
  }
@@ -7,18 +7,27 @@ const require = topLevelCreateRequire(import.meta.url);
7
7
  */
8
8
  import { BaseTool } from "./base_tool.js";
9
9
  class ExitLoopTool extends BaseTool {
10
+ /** Creates an ExitLoopTool with its fixed name and description. */
10
11
  constructor() {
11
12
  super({
12
13
  name: "exit_loop",
13
14
  description: "Exits the loop.\n\nCall this function only when you are instructed to do so."
14
15
  });
15
16
  }
17
+ /** Returns the function declaration for this tool. */
16
18
  _getDeclaration() {
17
19
  return {
18
20
  name: this.name,
19
21
  description: this.description
20
22
  };
21
23
  }
24
+ /**
25
+ * Sets `escalate` and `skipSummarization` on the event actions, signalling
26
+ * the {@link LoopAgent} to stop iterating.
27
+ *
28
+ * @param request The tool request containing the current tool context.
29
+ * @returns An empty string response.
30
+ */
22
31
  async runAsync({
23
32
  toolContext
24
33
  }) {
@@ -46,7 +46,8 @@ class FunctionTool extends (_b = BaseTool, _a = FUNCTION_TOOL_SIGNATURE_SYMBOL,
46
46
  this.parameters = options.parameters;
47
47
  }
48
48
  /**
49
- * Provide a schema for the function.
49
+ * Returns the function declaration derived from the tool's name, description,
50
+ * and parameter schema.
50
51
  */
51
52
  _getDeclaration() {
52
53
  return {
@@ -56,7 +57,11 @@ class FunctionTool extends (_b = BaseTool, _a = FUNCTION_TOOL_SIGNATURE_SYMBOL,
56
57
  };
57
58
  }
58
59
  /**
59
- * Logic for running the tool.
60
+ * Validates the model-provided arguments against the parameter schema and
61
+ * invokes the user-defined `execute` function.
62
+ *
63
+ * @param req The tool request containing arguments and tool context.
64
+ * @returns A promise resolving to the function's return value.
60
65
  */
61
66
  async runAsync(req) {
62
67
  try {
@@ -37,7 +37,8 @@ class LongRunningFunctionTool extends FunctionTool {
37
37
  super(__spreadProps(__spreadValues({}, options), { isLongRunning: true }));
38
38
  }
39
39
  /**
40
- * Provide a schema for the function.
40
+ * Returns the function declaration with an appended instruction warning the
41
+ * model not to re-invoke the tool while it is still running.
41
42
  */
42
43
  _getDeclaration() {
43
44
  const declaration = super._getDeclaration();
@@ -14,6 +14,7 @@ import {
14
14
  } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
15
15
  class MCPSessionManager {
16
16
  constructor(connectionParams) {
17
+ this.activeSessions = /* @__PURE__ */ new Set();
17
18
  this.connectionParams = connectionParams;
18
19
  }
19
20
  async createSession() {
@@ -45,8 +46,18 @@ class MCPSessionManager {
45
46
  break;
46
47
  }
47
48
  }
49
+ this.activeSessions.add(client);
48
50
  return client;
49
51
  }
52
+ async closeSession(client) {
53
+ if (this.activeSessions.has(client)) {
54
+ this.activeSessions.delete(client);
55
+ await client.close();
56
+ }
57
+ }
58
+ getActiveSessions() {
59
+ return Array.from(this.activeSessions);
60
+ }
50
61
  }
51
62
  export {
52
63
  MCPSessionManager