@google/adk 0.2.4 → 0.3.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 (191) hide show
  1. package/dist/cjs/agents/base_agent.js +52 -24
  2. package/dist/cjs/agents/callback_context.js +4 -1
  3. package/dist/cjs/agents/content_processor_utils.js +15 -7
  4. package/dist/cjs/agents/functions.js +79 -29
  5. package/dist/cjs/agents/invocation_context.js +3 -1
  6. package/dist/cjs/agents/llm_agent.js +188 -108
  7. package/dist/cjs/agents/loop_agent.js +18 -6
  8. package/dist/cjs/agents/parallel_agent.js +20 -7
  9. package/dist/cjs/agents/readonly_context.js +4 -1
  10. package/dist/cjs/agents/sequential_agent.js +34 -12
  11. package/dist/cjs/artifacts/gcs_artifact_service.js +28 -20
  12. package/dist/cjs/artifacts/in_memory_artifact_service.js +18 -4
  13. package/dist/cjs/auth/auth_handler.js +3 -1
  14. package/dist/cjs/code_executors/base_code_executor.js +14 -2
  15. package/dist/cjs/code_executors/built_in_code_executor.js +21 -5
  16. package/dist/cjs/code_executors/code_executor_context.js +5 -5
  17. package/dist/cjs/common.js +45 -0
  18. package/dist/cjs/events/event.js +1 -3
  19. package/dist/cjs/examples/base_example_provider.js +18 -2
  20. package/dist/cjs/examples/example_util.js +1 -1
  21. package/dist/cjs/index.js +19 -19
  22. package/dist/cjs/index.js.map +4 -4
  23. package/dist/cjs/memory/in_memory_memory_service.js +3 -1
  24. package/dist/cjs/models/base_llm.js +8 -4
  25. package/dist/cjs/models/gemini_llm_connection.js +1 -0
  26. package/dist/cjs/models/google_llm.js +3 -3
  27. package/dist/cjs/plugins/base_plugin.js +71 -49
  28. package/dist/cjs/plugins/logging_plugin.js +50 -13
  29. package/dist/cjs/plugins/plugin_manager.js +56 -24
  30. package/dist/cjs/plugins/security_plugin.js +5 -2
  31. package/dist/cjs/runner/runner.js +126 -101
  32. package/dist/cjs/sessions/in_memory_session_service.js +38 -14
  33. package/dist/cjs/telemetry/google_cloud.js +7 -9
  34. package/dist/cjs/telemetry/setup.js +15 -7
  35. package/dist/cjs/telemetry/tracing.js +37 -15
  36. package/dist/cjs/tools/agent_tool.js +26 -13
  37. package/dist/cjs/tools/base_tool.js +19 -7
  38. package/dist/cjs/tools/forwarding_artifact_service.js +1 -1
  39. package/dist/cjs/tools/function_tool.js +15 -7
  40. package/dist/cjs/tools/google_search_tool.js +8 -4
  41. package/dist/cjs/tools/mcp/mcp_session_manager.js +16 -10
  42. package/dist/cjs/tools/mcp/mcp_tool.js +1 -3
  43. package/dist/cjs/tools/mcp/mcp_toolset.js +1 -1
  44. package/dist/cjs/tools/tool_context.js +4 -9
  45. package/dist/cjs/utils/env_aware_utils.js +1 -1
  46. package/dist/cjs/utils/gemini_schema_util.js +10 -4
  47. package/dist/cjs/utils/logger.js +47 -3
  48. package/dist/cjs/utils/simple_zod_to_json.js +100 -141
  49. package/dist/cjs/utils/variant_utils.js +1 -1
  50. package/dist/cjs/version.js +1 -1
  51. package/dist/esm/agents/base_agent.js +57 -25
  52. package/dist/esm/agents/callback_context.js +4 -1
  53. package/dist/esm/agents/content_processor_utils.js +25 -9
  54. package/dist/esm/agents/functions.js +83 -29
  55. package/dist/esm/agents/invocation_context.js +3 -1
  56. package/dist/esm/agents/llm_agent.js +228 -116
  57. package/dist/esm/agents/loop_agent.js +16 -5
  58. package/dist/esm/agents/parallel_agent.js +18 -6
  59. package/dist/esm/agents/readonly_context.js +4 -1
  60. package/dist/esm/agents/sequential_agent.js +33 -12
  61. package/dist/esm/artifacts/gcs_artifact_service.js +28 -20
  62. package/dist/esm/artifacts/in_memory_artifact_service.js +18 -4
  63. package/dist/esm/auth/auth_handler.js +3 -1
  64. package/dist/esm/code_executors/base_code_executor.js +12 -1
  65. package/dist/esm/code_executors/built_in_code_executor.js +19 -4
  66. package/dist/esm/code_executors/code_executor_context.js +5 -5
  67. package/dist/esm/common.js +56 -11
  68. package/dist/esm/events/event.js +1 -3
  69. package/dist/esm/examples/base_example_provider.js +16 -1
  70. package/dist/esm/examples/example_util.js +4 -2
  71. package/dist/esm/index.js +19 -19
  72. package/dist/esm/index.js.map +4 -4
  73. package/dist/esm/memory/in_memory_memory_service.js +3 -1
  74. package/dist/esm/models/base_llm.js +8 -4
  75. package/dist/esm/models/gemini_llm_connection.js +1 -0
  76. package/dist/esm/models/google_llm.js +8 -4
  77. package/dist/esm/plugins/base_plugin.js +71 -49
  78. package/dist/esm/plugins/logging_plugin.js +55 -14
  79. package/dist/esm/plugins/plugin_manager.js +56 -24
  80. package/dist/esm/plugins/security_plugin.js +5 -2
  81. package/dist/esm/runner/runner.js +139 -105
  82. package/dist/esm/sessions/in_memory_session_service.js +41 -15
  83. package/dist/esm/telemetry/google_cloud.js +7 -9
  84. package/dist/esm/telemetry/setup.js +23 -9
  85. package/dist/esm/telemetry/tracing.js +37 -15
  86. package/dist/esm/tools/agent_tool.js +25 -13
  87. package/dist/esm/tools/base_tool.js +17 -6
  88. package/dist/esm/tools/forwarding_artifact_service.js +1 -1
  89. package/dist/esm/tools/function_tool.js +13 -8
  90. package/dist/esm/tools/google_search_tool.js +6 -3
  91. package/dist/esm/tools/long_running_tool.js +3 -1
  92. package/dist/esm/tools/mcp/mcp_session_manager.js +22 -12
  93. package/dist/esm/tools/mcp/mcp_tool.js +1 -3
  94. package/dist/esm/tools/mcp/mcp_toolset.js +1 -1
  95. package/dist/esm/tools/tool_context.js +4 -9
  96. package/dist/esm/utils/env_aware_utils.js +1 -1
  97. package/dist/esm/utils/gemini_schema_util.js +10 -4
  98. package/dist/esm/utils/logger.js +43 -2
  99. package/dist/esm/utils/simple_zod_to_json.js +102 -141
  100. package/dist/esm/utils/variant_utils.js +1 -1
  101. package/dist/esm/version.js +1 -1
  102. package/dist/types/agents/base_agent.d.ts +16 -4
  103. package/dist/types/agents/callback_context.d.ts +1 -1
  104. package/dist/types/agents/invocation_context.d.ts +4 -2
  105. package/dist/types/agents/llm_agent.d.ts +43 -31
  106. package/dist/types/agents/loop_agent.d.ts +17 -1
  107. package/dist/types/agents/parallel_agent.d.ts +17 -1
  108. package/dist/types/agents/sequential_agent.d.ts +17 -1
  109. package/dist/types/artifacts/in_memory_artifact_service.d.ts +3 -3
  110. package/dist/types/auth/auth_schemes.d.ts +5 -2
  111. package/dist/types/code_executors/base_code_executor.d.ts +14 -0
  112. package/dist/types/code_executors/built_in_code_executor.d.ts +20 -1
  113. package/dist/types/code_executors/code_executor_context.d.ts +2 -4
  114. package/dist/types/common.d.ts +40 -15
  115. package/dist/types/examples/base_example_provider.d.ts +16 -0
  116. package/dist/types/index.d.ts +3 -3
  117. package/dist/types/models/base_llm_connection.d.ts +1 -1
  118. package/dist/types/models/llm_response.d.ts +1 -1
  119. package/dist/types/plugins/base_plugin.d.ts +50 -40
  120. package/dist/types/plugins/logging_plugin.d.ts +12 -12
  121. package/dist/types/plugins/plugin_manager.d.ts +12 -12
  122. package/dist/types/plugins/security_plugin.d.ts +1 -1
  123. package/dist/types/runner/runner.d.ts +18 -10
  124. package/dist/types/sessions/in_memory_session_service.d.ts +5 -5
  125. package/dist/types/telemetry/setup.d.ts +1 -1
  126. package/dist/types/telemetry/tracing.d.ts +7 -6
  127. package/dist/types/tools/agent_tool.d.ts +15 -1
  128. package/dist/types/tools/base_tool.d.ts +15 -1
  129. package/dist/types/tools/base_toolset.d.ts +2 -1
  130. package/dist/types/tools/forwarding_artifact_service.d.ts +2 -2
  131. package/dist/types/tools/function_tool.d.ts +18 -4
  132. package/dist/types/tools/google_search_tool.d.ts +5 -6
  133. package/dist/types/tools/mcp/mcp_session_manager.d.ts +10 -3
  134. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -2
  135. package/dist/types/tools/tool_context.d.ts +1 -1
  136. package/dist/types/utils/gemini_schema_util.d.ts +4 -12
  137. package/dist/types/utils/logger.d.ts +11 -10
  138. package/dist/types/utils/simple_zod_to_json.d.ts +5 -4
  139. package/dist/types/version.d.ts +1 -1
  140. package/dist/web/agents/base_agent.js +103 -36
  141. package/dist/web/agents/callback_context.js +4 -1
  142. package/dist/web/agents/content_processor_utils.js +25 -9
  143. package/dist/web/agents/functions.js +83 -29
  144. package/dist/web/agents/invocation_context.js +3 -1
  145. package/dist/web/agents/llm_agent.js +282 -137
  146. package/dist/web/agents/loop_agent.js +16 -5
  147. package/dist/web/agents/parallel_agent.js +18 -6
  148. package/dist/web/agents/readonly_context.js +4 -1
  149. package/dist/web/agents/sequential_agent.js +33 -12
  150. package/dist/web/artifacts/gcs_artifact_service.js +25 -17
  151. package/dist/web/artifacts/in_memory_artifact_service.js +18 -4
  152. package/dist/web/auth/auth_handler.js +3 -1
  153. package/dist/web/code_executors/base_code_executor.js +12 -1
  154. package/dist/web/code_executors/built_in_code_executor.js +19 -4
  155. package/dist/web/code_executors/code_executor_context.js +5 -5
  156. package/dist/web/common.js +56 -11
  157. package/dist/web/events/event.js +1 -3
  158. package/dist/web/examples/base_example_provider.js +16 -1
  159. package/dist/web/examples/example_util.js +4 -2
  160. package/dist/web/index.js +1 -1
  161. package/dist/web/index.js.map +4 -4
  162. package/dist/web/memory/in_memory_memory_service.js +3 -1
  163. package/dist/web/models/base_llm.js +8 -4
  164. package/dist/web/models/gemini_llm_connection.js +1 -0
  165. package/dist/web/models/google_llm.js +8 -4
  166. package/dist/web/plugins/base_plugin.js +71 -49
  167. package/dist/web/plugins/logging_plugin.js +55 -14
  168. package/dist/web/plugins/plugin_manager.js +56 -24
  169. package/dist/web/plugins/security_plugin.js +5 -2
  170. package/dist/web/runner/runner.js +186 -119
  171. package/dist/web/sessions/in_memory_session_service.js +41 -15
  172. package/dist/web/telemetry/google_cloud.js +7 -9
  173. package/dist/web/telemetry/setup.js +23 -9
  174. package/dist/web/telemetry/tracing.js +37 -15
  175. package/dist/web/tools/agent_tool.js +25 -13
  176. package/dist/web/tools/base_tool.js +17 -6
  177. package/dist/web/tools/forwarding_artifact_service.js +1 -1
  178. package/dist/web/tools/function_tool.js +13 -8
  179. package/dist/web/tools/google_search_tool.js +6 -3
  180. package/dist/web/tools/long_running_tool.js +3 -1
  181. package/dist/web/tools/mcp/mcp_session_manager.js +22 -12
  182. package/dist/web/tools/mcp/mcp_tool.js +1 -3
  183. package/dist/web/tools/mcp/mcp_toolset.js +1 -1
  184. package/dist/web/tools/tool_context.js +4 -9
  185. package/dist/web/utils/env_aware_utils.js +1 -1
  186. package/dist/web/utils/gemini_schema_util.js +10 -4
  187. package/dist/web/utils/logger.js +43 -2
  188. package/dist/web/utils/simple_zod_to_json.js +102 -155
  189. package/dist/web/utils/variant_utils.js +1 -1
  190. package/dist/web/version.js +1 -1
  191. package/package.json +5 -3
@@ -36,6 +36,7 @@ var import_built_in_code_executor = require("../code_executors/built_in_code_exe
36
36
  var import_event = require("../events/event.js");
37
37
  var import_event_actions = require("../events/event_actions.js");
38
38
  var import_plugin_manager = require("../plugins/plugin_manager.js");
39
+ var import_tracing = require("../telemetry/tracing.js");
39
40
  var import_logger = require("../utils/logger.js");
40
41
  var import_model_name = require("../utils/model_name.js");
41
42
  /**
@@ -58,112 +59,132 @@ class Runner {
58
59
  * Runs the agent with the given message, and returns an async generator of
59
60
  * events.
60
61
  *
61
- * @param userId The user ID of the session.
62
- * @param sessionId The session ID of the session.
63
- * @param newMessage A new message to append to the session.
64
- * @param stateDelta An optional state delta to apply to the session.
65
- * @param runConfig The run config for the agent.
62
+ * @param params.userId The user ID of the session.
63
+ * @param params.sessionId The session ID of the session.
64
+ * @param params.newMessage A new message to append to the session.
65
+ * @param params.stateDelta An optional state delta to apply to the session.
66
+ * @param params.runConfig The run config for the agent.
66
67
  * @yields The events generated by the agent.
67
68
  */
68
69
  // TODO - b/425992518: user, sessionId, and runConfig can be internalized.
69
- async *runAsync({
70
- userId,
71
- sessionId,
72
- newMessage,
73
- stateDelta,
74
- runConfig
75
- }) {
76
- var _a;
77
- runConfig = (0, import_run_config.createRunConfig)(runConfig);
78
- const span = import_api.trace.getTracer("gcp.vertex.agent").startSpan("invocation");
70
+ async *runAsync(params) {
71
+ const { userId, sessionId, stateDelta } = params;
72
+ const runConfig = (0, import_run_config.createRunConfig)(params.runConfig);
73
+ let newMessage = params.newMessage;
74
+ const span = import_tracing.tracer.startSpan("invocation");
75
+ const ctx = import_api.trace.setSpan(import_api.context.active(), span);
79
76
  try {
80
- const session = await this.sessionService.getSession({ appName: this.appName, userId, sessionId });
81
- if (!session) {
82
- if (!this.appName) {
83
- throw new Error(
84
- `Session lookup failed: appName must be provided in runner constructor`
85
- );
86
- }
87
- throw new Error(`Session not found: ${sessionId}`);
88
- }
89
- if (runConfig.supportCfc && this.agent instanceof import_llm_agent.LlmAgent) {
90
- const modelName = this.agent.canonicalModel.model;
91
- if (!(0, import_model_name.isGemini2OrAbove)(modelName)) {
92
- throw new Error(`CFC is not supported for model: ${modelName} in agent: ${this.agent.name}`);
93
- }
94
- if (!(this.agent.codeExecutor instanceof import_built_in_code_executor.BuiltInCodeExecutor)) {
95
- this.agent.codeExecutor = new import_built_in_code_executor.BuiltInCodeExecutor();
96
- }
97
- }
98
- const invocationContext = new import_invocation_context.InvocationContext({
99
- artifactService: this.artifactService,
100
- sessionService: this.sessionService,
101
- memoryService: this.memoryService,
102
- credentialService: this.credentialService,
103
- invocationId: (0, import_invocation_context.newInvocationContextId)(),
104
- agent: this.agent,
105
- session,
106
- userContent: newMessage,
107
- runConfig,
108
- pluginManager: this.pluginManager
109
- });
110
- const pluginUserMessage = await this.pluginManager.runOnUserMessageCallback({
111
- userMessage: newMessage,
112
- invocationContext
113
- });
114
- if (pluginUserMessage) {
115
- newMessage = pluginUserMessage;
116
- }
117
- if (newMessage) {
118
- if (!((_a = newMessage.parts) == null ? void 0 : _a.length)) {
119
- throw new Error("No parts in the newMessage.");
120
- }
121
- if (runConfig.saveInputBlobsAsArtifacts) {
122
- await this.saveArtifacts(
123
- invocationContext.invocationId,
124
- session.userId,
125
- session.id,
126
- newMessage
127
- );
128
- }
129
- await this.sessionService.appendEvent({
130
- session,
131
- event: (0, import_event.createEvent)({
132
- invocationId: invocationContext.invocationId,
133
- author: "user",
134
- actions: stateDelta ? (0, import_event_actions.createEventActions)({ stateDelta }) : void 0,
135
- content: newMessage
136
- })
137
- });
138
- }
139
- invocationContext.agent = this.determineAgentForResumption(session, this.agent);
140
- const beforeRunCallbackResponse = await this.pluginManager.runBeforeRunCallback({ invocationContext });
141
- if (beforeRunCallbackResponse) {
142
- const earlyExitEvent = (0, import_event.createEvent)({
143
- invocationId: invocationContext.invocationId,
144
- author: "model",
145
- content: beforeRunCallbackResponse
146
- });
147
- await this.sessionService.appendEvent({ session, event: earlyExitEvent });
148
- yield earlyExitEvent;
149
- } else {
150
- for await (const event of invocationContext.agent.runAsync(
151
- invocationContext
152
- )) {
153
- if (!event.partial) {
154
- await this.sessionService.appendEvent({ session, event });
77
+ yield* (0, import_tracing.runAsyncGeneratorWithOtelContext)(
78
+ ctx,
79
+ this,
80
+ async function* () {
81
+ var _a;
82
+ const session = await this.sessionService.getSession({
83
+ appName: this.appName,
84
+ userId,
85
+ sessionId
86
+ });
87
+ if (!session) {
88
+ if (!this.appName) {
89
+ throw new Error(
90
+ `Session lookup failed: appName must be provided in runner constructor`
91
+ );
92
+ }
93
+ throw new Error(`Session not found: ${sessionId}`);
155
94
  }
156
- const modifiedEvent = await this.pluginManager.runOnEventCallback(
157
- { invocationContext, event }
95
+ if (runConfig.supportCfc && (0, import_llm_agent.isLlmAgent)(this.agent)) {
96
+ const modelName = this.agent.canonicalModel.model;
97
+ if (!(0, import_model_name.isGemini2OrAbove)(modelName)) {
98
+ throw new Error(
99
+ `CFC is not supported for model: ${modelName} in agent: ${this.agent.name}`
100
+ );
101
+ }
102
+ if (!(0, import_built_in_code_executor.isBuiltInCodeExecutor)(this.agent.codeExecutor)) {
103
+ this.agent.codeExecutor = new import_built_in_code_executor.BuiltInCodeExecutor();
104
+ }
105
+ }
106
+ const invocationContext = new import_invocation_context.InvocationContext({
107
+ artifactService: this.artifactService,
108
+ sessionService: this.sessionService,
109
+ memoryService: this.memoryService,
110
+ credentialService: this.credentialService,
111
+ invocationId: (0, import_invocation_context.newInvocationContextId)(),
112
+ agent: this.agent,
113
+ session,
114
+ userContent: newMessage,
115
+ runConfig,
116
+ pluginManager: this.pluginManager
117
+ });
118
+ const pluginUserMessage = await this.pluginManager.runOnUserMessageCallback({
119
+ userMessage: newMessage,
120
+ invocationContext
121
+ });
122
+ if (pluginUserMessage) {
123
+ newMessage = pluginUserMessage;
124
+ }
125
+ if (newMessage) {
126
+ if (!((_a = newMessage.parts) == null ? void 0 : _a.length)) {
127
+ throw new Error("No parts in the newMessage.");
128
+ }
129
+ if (runConfig.saveInputBlobsAsArtifacts) {
130
+ await this.saveArtifacts(
131
+ invocationContext.invocationId,
132
+ session.userId,
133
+ session.id,
134
+ newMessage
135
+ );
136
+ }
137
+ await this.sessionService.appendEvent({
138
+ session,
139
+ event: (0, import_event.createEvent)({
140
+ invocationId: invocationContext.invocationId,
141
+ author: "user",
142
+ actions: stateDelta ? (0, import_event_actions.createEventActions)({ stateDelta }) : void 0,
143
+ content: newMessage
144
+ })
145
+ });
146
+ }
147
+ invocationContext.agent = this.determineAgentForResumption(
148
+ session,
149
+ this.agent
158
150
  );
159
- if (modifiedEvent) {
160
- yield modifiedEvent;
161
- } else {
162
- yield event;
151
+ if (newMessage) {
152
+ const beforeRunCallbackResponse = await this.pluginManager.runBeforeRunCallback({
153
+ invocationContext
154
+ });
155
+ if (beforeRunCallbackResponse) {
156
+ const earlyExitEvent = (0, import_event.createEvent)({
157
+ invocationId: invocationContext.invocationId,
158
+ author: "model",
159
+ content: beforeRunCallbackResponse
160
+ });
161
+ await this.sessionService.appendEvent({
162
+ session,
163
+ event: earlyExitEvent
164
+ });
165
+ yield earlyExitEvent;
166
+ } else {
167
+ for await (const event of invocationContext.agent.runAsync(
168
+ invocationContext
169
+ )) {
170
+ if (!event.partial) {
171
+ await this.sessionService.appendEvent({ session, event });
172
+ }
173
+ const modifiedEvent = await this.pluginManager.runOnEventCallback({
174
+ invocationContext,
175
+ event
176
+ });
177
+ if (modifiedEvent) {
178
+ yield modifiedEvent;
179
+ } else {
180
+ yield event;
181
+ }
182
+ }
183
+ await this.pluginManager.runAfterRunCallback({ invocationContext });
184
+ }
163
185
  }
164
186
  }
165
- }
166
- await this.pluginManager.runAfterRunCallback({ invocationContext });
187
+ );
167
188
  } finally {
168
189
  span.end();
169
190
  }
@@ -222,7 +243,9 @@ class Runner {
222
243
  }
223
244
  const agent = rootAgent.findSubAgent(event2.author);
224
245
  if (!agent) {
225
- import_logger.logger.warn(`Event from an unknown agent: ${event2.author}, event id: ${event2.id}`);
246
+ import_logger.logger.warn(
247
+ `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
248
+ );
226
249
  continue;
227
250
  }
228
251
  if (this.isRoutableLlmAgent(agent)) {
@@ -245,7 +268,7 @@ class Runner {
245
268
  isRoutableLlmAgent(agentToRun) {
246
269
  let agent = agentToRun;
247
270
  while (agent) {
248
- if (!(agent instanceof import_llm_agent.LlmAgent)) {
271
+ if (!(0, import_llm_agent.isLlmAgent)(agent)) {
249
272
  return false;
250
273
  }
251
274
  if (agent.disallowTransferToParent) {
@@ -263,7 +286,9 @@ function findEventByLastFunctionResponseId(events) {
263
286
  return null;
264
287
  }
265
288
  const lastEvent = events[events.length - 1];
266
- const functionCallId = (_d = (_c = (_b = (_a = lastEvent.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.find((part) => part.functionResponse)) == null ? void 0 : _c.functionResponse) == null ? void 0 : _d.id;
289
+ const functionCallId = (_d = (_c = (_b = (_a = lastEvent.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.find(
290
+ (part) => part.functionResponse
291
+ )) == null ? void 0 : _c.functionResponse) == null ? void 0 : _d.id;
267
292
  if (!functionCallId) {
268
293
  return null;
269
294
  }
@@ -55,7 +55,12 @@ class InMemorySessionService extends import_base_session_service.BaseSessionServ
55
55
  */
56
56
  this.appState = {};
57
57
  }
58
- createSession({ appName, userId, state, sessionId }) {
58
+ createSession({
59
+ appName,
60
+ userId,
61
+ state,
62
+ sessionId
63
+ }) {
59
64
  const session = (0, import_session.createSession)({
60
65
  id: sessionId || (0, import_env_aware_utils.randomUUID)(),
61
66
  appName,
@@ -75,7 +80,12 @@ class InMemorySessionService extends import_base_session_service.BaseSessionServ
75
80
  this.mergeState(appName, userId, (0, import_lodash_es.cloneDeep)(session))
76
81
  );
77
82
  }
78
- getSession({ appName, userId, sessionId, config }) {
83
+ getSession({
84
+ appName,
85
+ userId,
86
+ sessionId,
87
+ config
88
+ }) {
79
89
  if (!this.sessions[appName] || !this.sessions[appName][userId] || !this.sessions[appName][userId][sessionId]) {
80
90
  return Promise.resolve(void 0);
81
91
  }
@@ -83,7 +93,9 @@ class InMemorySessionService extends import_base_session_service.BaseSessionServ
83
93
  const copiedSession = (0, import_lodash_es.cloneDeep)(session);
84
94
  if (config) {
85
95
  if (config.numRecentEvents) {
86
- copiedSession.events = copiedSession.events.slice(-config.numRecentEvents);
96
+ copiedSession.events = copiedSession.events.slice(
97
+ -config.numRecentEvents
98
+ );
87
99
  }
88
100
  if (config.afterTimestamp) {
89
101
  let i = copiedSession.events.length - 1;
@@ -100,31 +112,43 @@ class InMemorySessionService extends import_base_session_service.BaseSessionServ
100
112
  }
101
113
  return Promise.resolve(this.mergeState(appName, userId, copiedSession));
102
114
  }
103
- listSessions({ appName, userId }) {
115
+ listSessions({
116
+ appName,
117
+ userId
118
+ }) {
104
119
  if (!this.sessions[appName] || !this.sessions[appName][userId]) {
105
120
  return Promise.resolve({ sessions: [] });
106
121
  }
107
122
  const sessionsWithoutEvents = [];
108
123
  for (const session of Object.values(this.sessions[appName][userId])) {
109
- sessionsWithoutEvents.push((0, import_session.createSession)({
110
- id: session.id,
111
- appName: session.appName,
112
- userId: session.userId,
113
- state: {},
114
- events: [],
115
- lastUpdateTime: session.lastUpdateTime
116
- }));
124
+ sessionsWithoutEvents.push(
125
+ (0, import_session.createSession)({
126
+ id: session.id,
127
+ appName: session.appName,
128
+ userId: session.userId,
129
+ state: {},
130
+ events: [],
131
+ lastUpdateTime: session.lastUpdateTime
132
+ })
133
+ );
117
134
  }
118
135
  return Promise.resolve({ sessions: sessionsWithoutEvents });
119
136
  }
120
- async deleteSession({ appName, userId, sessionId }) {
137
+ async deleteSession({
138
+ appName,
139
+ userId,
140
+ sessionId
141
+ }) {
121
142
  const session = await this.getSession({ appName, userId, sessionId });
122
143
  if (!session) {
123
144
  return;
124
145
  }
125
146
  delete this.sessions[appName][userId][sessionId];
126
147
  }
127
- async appendEvent({ session, event }) {
148
+ async appendEvent({
149
+ session,
150
+ event
151
+ }) {
128
152
  await super.appendEvent({ session, event });
129
153
  session.lastUpdateTime = event.timestamp;
130
154
  const appName = session.appName;
@@ -28,13 +28,13 @@ __export(google_cloud_exports, {
28
28
  getGcpResource: () => getGcpResource
29
29
  });
30
30
  module.exports = __toCommonJS(google_cloud_exports);
31
- var import_google_auth_library = require("google-auth-library");
32
- var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
33
- var import_resources = require("@opentelemetry/resources");
34
- var import_resource_detector_gcp = require("@opentelemetry/resource-detector-gcp");
31
+ var import_opentelemetry_cloud_monitoring_exporter = require("@google-cloud/opentelemetry-cloud-monitoring-exporter");
35
32
  var import_opentelemetry_cloud_trace_exporter = require("@google-cloud/opentelemetry-cloud-trace-exporter");
33
+ var import_resource_detector_gcp = require("@opentelemetry/resource-detector-gcp");
34
+ var import_resources = require("@opentelemetry/resources");
35
+ var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
36
36
  var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
37
- var import_opentelemetry_cloud_monitoring_exporter = require("@google-cloud/opentelemetry-cloud-monitoring-exporter");
37
+ var import_google_auth_library = require("google-auth-library");
38
38
  var import_logger = require("../utils/logger.js");
39
39
  /**
40
40
  * @license
@@ -47,7 +47,7 @@ async function getGcpProjectId() {
47
47
  const auth = new import_google_auth_library.GoogleAuth();
48
48
  const projectId = await auth.getProjectId();
49
49
  return projectId || void 0;
50
- } catch (error) {
50
+ } catch (_e) {
51
51
  return void 0;
52
52
  }
53
53
  }
@@ -63,9 +63,7 @@ async function getGcpExporters(config = {}) {
63
63
  return {};
64
64
  }
65
65
  return {
66
- spanProcessors: enableTracing ? [
67
- new import_sdk_trace_base.BatchSpanProcessor(new import_opentelemetry_cloud_trace_exporter.TraceExporter({ projectId }))
68
- ] : [],
66
+ spanProcessors: enableTracing ? [new import_sdk_trace_base.BatchSpanProcessor(new import_opentelemetry_cloud_trace_exporter.TraceExporter({ projectId }))] : [],
69
67
  metricReaders: enableMetrics ? [
70
68
  new import_sdk_metrics.PeriodicExportingMetricReader({
71
69
  exporter: new import_opentelemetry_cloud_monitoring_exporter.MetricExporter({ projectId }),
@@ -29,14 +29,14 @@ __export(setup_exports, {
29
29
  module.exports = __toCommonJS(setup_exports);
30
30
  var import_api = require("@opentelemetry/api");
31
31
  var import_api_logs = require("@opentelemetry/api-logs");
32
+ var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
33
+ var import_exporter_metrics_otlp_http = require("@opentelemetry/exporter-metrics-otlp-http");
34
+ var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
35
+ var import_resources = require("@opentelemetry/resources");
32
36
  var import_sdk_logs = require("@opentelemetry/sdk-logs");
33
37
  var import_sdk_metrics = require("@opentelemetry/sdk-metrics");
34
- var import_resources = require("@opentelemetry/resources");
35
38
  var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
36
39
  var import_sdk_trace_node = require("@opentelemetry/sdk-trace-node");
37
- var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
38
- var import_exporter_metrics_otlp_http = require("@opentelemetry/exporter-metrics-otlp-http");
39
- var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-http");
40
40
  /**
41
41
  * @license
42
42
  * Copyright 2025 Google LLC
@@ -45,9 +45,13 @@ var import_exporter_logs_otlp_http = require("@opentelemetry/exporter-logs-otlp-
45
45
  function maybeSetOtelProviders(otelHooksToSetup = [], otelResource) {
46
46
  const resource = otelResource || getOtelResource();
47
47
  const allHooks = [...otelHooksToSetup, getOtelExporters()];
48
- const spanProcessors = allHooks.flatMap((hooks) => hooks.spanProcessors || []);
48
+ const spanProcessors = allHooks.flatMap(
49
+ (hooks) => hooks.spanProcessors || []
50
+ );
49
51
  const metricReaders = allHooks.flatMap((hooks) => hooks.metricReaders || []);
50
- const logRecordProcessors = allHooks.flatMap((hooks) => hooks.logRecordProcessors || []);
52
+ const logRecordProcessors = allHooks.flatMap(
53
+ (hooks) => hooks.logRecordProcessors || []
54
+ );
51
55
  if (spanProcessors.length > 0) {
52
56
  const tracerProvider = new import_sdk_trace_node.NodeTracerProvider({
53
57
  resource,
@@ -87,7 +91,11 @@ function getOtelExporters(config = getOtelExportersConfig()) {
87
91
  const { enableTracing, enableMetrics, enableLogging } = config;
88
92
  return {
89
93
  spanProcessors: enableTracing ? [new import_sdk_trace_base.BatchSpanProcessor(new import_exporter_trace_otlp_http.OTLPTraceExporter())] : [],
90
- metricReaders: enableMetrics ? [new import_sdk_metrics.PeriodicExportingMetricReader({ exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter() })] : [],
94
+ metricReaders: enableMetrics ? [
95
+ new import_sdk_metrics.PeriodicExportingMetricReader({
96
+ exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter()
97
+ })
98
+ ] : [],
91
99
  logRecordProcessors: enableLogging ? [new import_sdk_logs.BatchLogRecordProcessor(new import_exporter_logs_otlp_http.OTLPLogExporter())] : []
92
100
  };
93
101
  }
@@ -24,7 +24,7 @@ var __copyProps = (to, from, except, desc) => {
24
24
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
25
  var tracing_exports = {};
26
26
  __export(tracing_exports, {
27
- bindAsyncGenerator: () => bindAsyncGenerator,
27
+ runAsyncGeneratorWithOtelContext: () => runAsyncGeneratorWithOtelContext,
28
28
  traceAgentInvocation: () => traceAgentInvocation,
29
29
  traceCallLlm: () => traceCallLlm,
30
30
  traceMergedToolCalls: () => traceMergedToolCalls,
@@ -48,14 +48,11 @@ const GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id";
48
48
  const GEN_AI_TOOL_DESCRIPTION = "gen_ai.tool.description";
49
49
  const GEN_AI_TOOL_NAME = "gen_ai.tool.name";
50
50
  const GEN_AI_TOOL_TYPE = "gen_ai.tool.type";
51
- const tracer = import_api.trace.getTracer(
52
- "gcp.vertex.agent",
53
- import_version.version
54
- );
51
+ const tracer = import_api.trace.getTracer("gcp.vertex.agent", import_version.version);
55
52
  function safeJsonSerialize(obj) {
56
53
  try {
57
54
  return JSON.stringify(obj);
58
- } catch (error) {
55
+ } catch (_e) {
59
56
  return "<not serializable>";
60
57
  }
61
58
  }
@@ -132,7 +129,10 @@ function traceMergedToolCalls({
132
129
  "gcp.vertex.agent.llm_request": "{}",
133
130
  "gcp.vertex.agent.llm_response": "{}"
134
131
  });
135
- span.setAttribute("gcp.vertex.agent.tool_response", shouldAddRequestResponseToSpans() ? safeJsonSerialize(functionResponseEvent) : "{}");
132
+ span.setAttribute(
133
+ "gcp.vertex.agent.tool_response",
134
+ shouldAddRequestResponseToSpans() ? safeJsonSerialize(functionResponseEvent) : "{}"
135
+ );
136
136
  }
137
137
  function traceCallLlm({
138
138
  invocationContext,
@@ -156,14 +156,26 @@ function traceCallLlm({
156
156
  span.setAttribute("gen_ai.request.top_p", llmRequest.config.topP);
157
157
  }
158
158
  if (((_b = llmRequest.config) == null ? void 0 : _b.maxOutputTokens) !== void 0) {
159
- span.setAttribute("gen_ai.request.max_tokens", llmRequest.config.maxOutputTokens);
159
+ span.setAttribute(
160
+ "gen_ai.request.max_tokens",
161
+ llmRequest.config.maxOutputTokens
162
+ );
160
163
  }
161
- span.setAttribute("gcp.vertex.agent.llm_response", shouldAddRequestResponseToSpans() ? safeJsonSerialize(llmResponse) : "{}");
164
+ span.setAttribute(
165
+ "gcp.vertex.agent.llm_response",
166
+ shouldAddRequestResponseToSpans() ? safeJsonSerialize(llmResponse) : "{}"
167
+ );
162
168
  if (llmResponse.usageMetadata) {
163
- span.setAttribute("gen_ai.usage.input_tokens", llmResponse.usageMetadata.promptTokenCount || 0);
169
+ span.setAttribute(
170
+ "gen_ai.usage.input_tokens",
171
+ llmResponse.usageMetadata.promptTokenCount || 0
172
+ );
164
173
  }
165
174
  if ((_c = llmResponse.usageMetadata) == null ? void 0 : _c.candidatesTokenCount) {
166
- span.setAttribute("gen_ai.usage.output_tokens", llmResponse.usageMetadata.candidatesTokenCount);
175
+ span.setAttribute(
176
+ "gen_ai.usage.output_tokens",
177
+ llmResponse.usageMetadata.candidatesTokenCount
178
+ );
167
179
  }
168
180
  if (llmResponse.finishReason) {
169
181
  const finishReasonValue = typeof llmResponse.finishReason === "string" ? llmResponse.finishReason.toLowerCase() : String(llmResponse.finishReason).toLowerCase();
@@ -181,7 +193,10 @@ function traceSendData({
181
193
  "gcp.vertex.agent.invocation_id": invocationContext.invocationId,
182
194
  "gcp.vertex.agent.event_id": eventId
183
195
  });
184
- span.setAttribute("gcp.vertex.agent.data", shouldAddRequestResponseToSpans() ? safeJsonSerialize(data) : "{}");
196
+ span.setAttribute(
197
+ "gcp.vertex.agent.data",
198
+ shouldAddRequestResponseToSpans() ? safeJsonSerialize(data) : "{}"
199
+ );
185
200
  }
186
201
  function buildLlmRequestForTrace(llmRequest) {
187
202
  const result = {
@@ -201,7 +216,7 @@ function buildLlmRequestForTrace(llmRequest) {
201
216
  });
202
217
  return result;
203
218
  }
204
- function bindAsyncGenerator(ctx, generator) {
219
+ function bindOtelContextToAsyncGenerator(ctx, generator) {
205
220
  return {
206
221
  // Bind the next() method to execute within the provided context
207
222
  next: import_api.context.bind(ctx, generator.next.bind(generator)),
@@ -211,17 +226,24 @@ function bindAsyncGenerator(ctx, generator) {
211
226
  throw: import_api.context.bind(ctx, generator.throw.bind(generator)),
212
227
  // Ensure the async iterator symbol also returns a context-bound generator
213
228
  [Symbol.asyncIterator]() {
214
- return bindAsyncGenerator(ctx, generator[Symbol.asyncIterator]());
229
+ return bindOtelContextToAsyncGenerator(
230
+ ctx,
231
+ generator[Symbol.asyncIterator]()
232
+ );
215
233
  }
216
234
  };
217
235
  }
236
+ function runAsyncGeneratorWithOtelContext(otelContext, generatorFnContext, generatorFn) {
237
+ const generator = generatorFn.call(generatorFnContext);
238
+ return bindOtelContextToAsyncGenerator(otelContext, generator);
239
+ }
218
240
  function shouldAddRequestResponseToSpans() {
219
241
  const envValue = process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS || "true";
220
242
  return envValue === "true" || envValue === "1";
221
243
  }
222
244
  // Annotate the CommonJS export names for ESM import in node:
223
245
  0 && (module.exports = {
224
- bindAsyncGenerator,
246
+ runAsyncGeneratorWithOtelContext,
225
247
  traceAgentInvocation,
226
248
  traceCallLlm,
227
249
  traceMergedToolCalls,
@@ -24,7 +24,8 @@ var __copyProps = (to, from, except, desc) => {
24
24
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
25
  var agent_tool_exports = {};
26
26
  __export(agent_tool_exports, {
27
- AgentTool: () => AgentTool
27
+ AgentTool: () => AgentTool,
28
+ isAgentTool: () => isAgentTool
28
29
  });
29
30
  module.exports = __toCommonJS(agent_tool_exports);
30
31
  var import_genai = require("@google/genai");
@@ -40,17 +41,25 @@ var import_forwarding_artifact_service = require("./forwarding_artifact_service.
40
41
  * Copyright 2025 Google LLC
41
42
  * SPDX-License-Identifier: Apache-2.0
42
43
  */
43
- class AgentTool extends import_base_tool.BaseTool {
44
+ var _a, _b;
45
+ const AGENT_TOOL_SIGNATURE_SYMBOL = Symbol.for("google.adk.agentTool");
46
+ function isAgentTool(obj) {
47
+ return typeof obj === "object" && obj !== null && AGENT_TOOL_SIGNATURE_SYMBOL in obj && obj[AGENT_TOOL_SIGNATURE_SYMBOL] === true;
48
+ }
49
+ class AgentTool extends (_b = import_base_tool.BaseTool, _a = AGENT_TOOL_SIGNATURE_SYMBOL, _b) {
44
50
  constructor(config) {
45
- super(
46
- { name: config.agent.name, description: config.agent.description || "" }
47
- );
51
+ super({
52
+ name: config.agent.name,
53
+ description: config.agent.description || ""
54
+ });
55
+ /** A unique symbol to identify ADK agent tool class. */
56
+ this[_a] = true;
48
57
  this.agent = config.agent;
49
58
  this.skipSummarization = config.skipSummarization || false;
50
59
  }
51
60
  _getDeclaration() {
52
61
  let declaration;
53
- if (this.agent instanceof import_llm_agent.LlmAgent && this.agent.inputSchema) {
62
+ if ((0, import_llm_agent.isLlmAgent)(this.agent) && this.agent.inputSchema) {
54
63
  declaration = {
55
64
  name: this.name,
56
65
  description: this.description,
@@ -75,17 +84,20 @@ class AgentTool extends import_base_tool.BaseTool {
75
84
  };
76
85
  }
77
86
  if (this.apiVariant !== import_variant_utils.GoogleLLMVariant.GEMINI_API) {
78
- const hasOutputSchema = this.agent instanceof import_llm_agent.LlmAgent && this.agent.outputSchema;
87
+ const hasOutputSchema = (0, import_llm_agent.isLlmAgent)(this.agent) && this.agent.outputSchema;
79
88
  declaration.response = hasOutputSchema ? { type: import_genai.Type.OBJECT } : { type: import_genai.Type.STRING };
80
89
  }
81
90
  return declaration;
82
91
  }
83
- async runAsync({ args, toolContext }) {
84
- var _a, _b;
92
+ async runAsync({
93
+ args,
94
+ toolContext
95
+ }) {
96
+ var _a2, _b2;
85
97
  if (this.skipSummarization) {
86
98
  toolContext.actions.skipSummarization = true;
87
99
  }
88
- const hasInputSchema = this.agent instanceof import_llm_agent.LlmAgent && this.agent.inputSchema;
100
+ const hasInputSchema = (0, import_llm_agent.isLlmAgent)(this.agent) && this.agent.inputSchema;
89
101
  const content = {
90
102
  role: "user",
91
103
  parts: [
@@ -120,15 +132,16 @@ class AgentTool extends import_base_tool.BaseTool {
120
132
  }
121
133
  lastEvent = event;
122
134
  }
123
- if (!((_b = (_a = lastEvent == null ? void 0 : lastEvent.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
135
+ if (!((_b2 = (_a2 = lastEvent == null ? void 0 : lastEvent.content) == null ? void 0 : _a2.parts) == null ? void 0 : _b2.length)) {
124
136
  return "";
125
137
  }
126
- const hasOutputSchema = this.agent instanceof import_llm_agent.LlmAgent && this.agent.outputSchema;
138
+ const hasOutputSchema = (0, import_llm_agent.isLlmAgent)(this.agent) && this.agent.outputSchema;
127
139
  const mergedText = lastEvent.content.parts.map((part) => part.text).filter((text) => text).join("\n");
128
140
  return hasOutputSchema ? JSON.parse(mergedText) : mergedText;
129
141
  }
130
142
  }
131
143
  // Annotate the CommonJS export names for ESM import in node:
132
144
  0 && (module.exports = {
133
- AgentTool
145
+ AgentTool,
146
+ isAgentTool
134
147
  });