@google/adk 1.3.0 → 1.4.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 (165) hide show
  1. package/dist/cjs/agents/active_streaming_tool.js +6 -1
  2. package/dist/cjs/agents/context.js +1 -11
  3. package/dist/cjs/agents/functions.js +35 -16
  4. package/dist/cjs/agents/instructions.js +23 -5
  5. package/dist/cjs/agents/invocation_context.js +2 -5
  6. package/dist/cjs/agents/llm_agent.js +8 -6
  7. package/dist/cjs/agents/processors/code_execution_request_processor.js +0 -3
  8. package/dist/cjs/agents/processors/content_processor_utils.js +16 -3
  9. package/dist/cjs/agents/processors/context_compactor_request_processor.js +4 -2
  10. package/dist/cjs/agents/processors/interactions_request_processor.js +63 -0
  11. package/dist/cjs/apps/app.js +79 -0
  12. package/dist/cjs/apps/resumability_config.js +44 -0
  13. package/dist/cjs/artifacts/file_artifact_service.js +14 -1
  14. package/dist/cjs/artifacts/gcs_artifact_service.js +57 -15
  15. package/dist/cjs/artifacts/in_memory_artifact_service.js +5 -1
  16. package/dist/cjs/artifacts/scoped_artifact_service.js +101 -0
  17. package/dist/cjs/artifacts/session_artifact_service.js +27 -0
  18. package/dist/cjs/auth/oauth2/oauth2_discovery.js +17 -5
  19. package/dist/cjs/auth/oauth2/oauth2_utils.js +12 -1
  20. package/dist/cjs/common.js +47 -0
  21. package/dist/cjs/context/agent_controlled_context_compactor.js +109 -0
  22. package/dist/cjs/context/token_based_context_compactor.js +42 -10
  23. package/dist/cjs/context/trajectory_thought_pruning_compactor.js +71 -0
  24. package/dist/cjs/events/event.js +24 -0
  25. package/dist/cjs/models/google_llm.js +25 -10
  26. package/dist/cjs/models/interactions_utils.js +732 -0
  27. package/dist/cjs/plugins/base_plugin.js +1 -0
  28. package/dist/cjs/runner/in_memory_runner.js +13 -2
  29. package/dist/cjs/runner/runner.js +93 -72
  30. package/dist/cjs/sessions/base_session_service.js +6 -1
  31. package/dist/cjs/sessions/database_session_service.js +24 -7
  32. package/dist/cjs/sessions/vertex_ai_session_service.js +19 -4
  33. package/dist/cjs/skills/loader.js +2 -2
  34. package/dist/cjs/tools/base_toolset.js +1 -1
  35. package/dist/cjs/tools/consolidate_context_tool.js +79 -0
  36. package/dist/cjs/tools/forwarding_artifact_service.js +16 -28
  37. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +2 -12
  38. package/dist/cjs/utils/async_hooks_shim.js +52 -0
  39. package/dist/cjs/utils/client_labels.js +41 -3
  40. package/dist/cjs/utils/env_aware_utils.js +10 -1
  41. package/dist/cjs/utils/streaming_utils.js +10 -4
  42. package/dist/cjs/utils/task.js +62 -0
  43. package/dist/cjs/version.js +1 -1
  44. package/dist/esm/agents/active_streaming_tool.js +6 -1
  45. package/dist/esm/agents/context.js +1 -11
  46. package/dist/esm/agents/functions.js +36 -15
  47. package/dist/esm/agents/instructions.js +23 -5
  48. package/dist/esm/agents/invocation_context.js +2 -5
  49. package/dist/esm/agents/llm_agent.js +8 -6
  50. package/dist/esm/agents/processors/code_execution_request_processor.js +0 -3
  51. package/dist/esm/agents/processors/content_processor_utils.js +14 -2
  52. package/dist/esm/agents/processors/context_compactor_request_processor.js +4 -2
  53. package/dist/esm/agents/processors/interactions_request_processor.js +34 -0
  54. package/dist/esm/apps/app.js +49 -0
  55. package/dist/esm/apps/resumability_config.js +16 -0
  56. package/dist/esm/artifacts/file_artifact_service.js +14 -1
  57. package/dist/esm/artifacts/gcs_artifact_service.js +57 -15
  58. package/dist/esm/artifacts/in_memory_artifact_service.js +5 -1
  59. package/dist/esm/artifacts/scoped_artifact_service.js +73 -0
  60. package/dist/esm/artifacts/session_artifact_service.js +7 -0
  61. package/dist/esm/auth/oauth2/oauth2_discovery.js +14 -4
  62. package/dist/esm/auth/oauth2/oauth2_utils.js +12 -1
  63. package/dist/esm/common.js +42 -2
  64. package/dist/esm/context/agent_controlled_context_compactor.js +81 -0
  65. package/dist/esm/context/token_based_context_compactor.js +42 -10
  66. package/dist/esm/context/trajectory_thought_pruning_compactor.js +43 -0
  67. package/dist/esm/events/event.js +22 -0
  68. package/dist/esm/models/google_llm.js +23 -9
  69. package/dist/esm/models/interactions_utils.js +697 -0
  70. package/dist/esm/plugins/base_plugin.js +1 -0
  71. package/dist/esm/runner/in_memory_runner.js +13 -2
  72. package/dist/esm/runner/runner.js +91 -73
  73. package/dist/esm/sessions/base_session_service.js +6 -1
  74. package/dist/esm/sessions/database_session_service.js +24 -7
  75. package/dist/esm/sessions/vertex_ai_session_service.js +17 -3
  76. package/dist/esm/skills/loader.js +2 -2
  77. package/dist/esm/tools/base_toolset.js +1 -1
  78. package/dist/esm/tools/consolidate_context_tool.js +51 -0
  79. package/dist/esm/tools/forwarding_artifact_service.js +16 -28
  80. package/dist/esm/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +2 -12
  81. package/dist/esm/utils/async_hooks_shim.js +24 -0
  82. package/dist/esm/utils/client_labels.js +38 -2
  83. package/dist/esm/utils/env_aware_utils.js +10 -1
  84. package/dist/esm/utils/streaming_utils.js +10 -4
  85. package/dist/esm/utils/task.js +34 -0
  86. package/dist/esm/version.js +1 -1
  87. package/dist/types/agents/active_streaming_tool.d.ts +3 -4
  88. package/dist/types/agents/functions.d.ts +12 -9
  89. package/dist/types/agents/invocation_context.d.ts +7 -3
  90. package/dist/types/agents/processors/content_processor_utils.d.ts +8 -0
  91. package/dist/types/agents/processors/interactions_request_processor.d.ts +17 -0
  92. package/dist/types/apps/app.d.ts +52 -0
  93. package/dist/types/apps/resumability_config.d.ts +27 -0
  94. package/dist/types/artifacts/base_artifact_service.d.ts +6 -36
  95. package/dist/types/artifacts/gcs_artifact_service.d.ts +2 -1
  96. package/dist/types/artifacts/scoped_artifact_service.d.ts +25 -0
  97. package/dist/types/artifacts/session_artifact_service.d.ts +25 -0
  98. package/dist/types/auth/oauth2/oauth2_discovery.d.ts +11 -0
  99. package/dist/types/common.d.ts +20 -3
  100. package/dist/types/context/agent_controlled_context_compactor.d.ts +24 -0
  101. package/dist/types/context/base_context_compactor.d.ts +3 -0
  102. package/dist/types/context/token_based_context_compactor.d.ts +6 -1
  103. package/dist/types/context/trajectory_thought_pruning_compactor.d.ts +27 -0
  104. package/dist/types/events/event.d.ts +8 -0
  105. package/dist/types/models/google_llm.d.ts +15 -1
  106. package/dist/types/models/interactions_utils.d.ts +92 -0
  107. package/dist/types/models/llm_request.d.ts +4 -0
  108. package/dist/types/models/llm_response.d.ts +4 -0
  109. package/dist/types/plugins/base_plugin.d.ts +2 -1
  110. package/dist/types/runner/in_memory_runner.d.ts +7 -1
  111. package/dist/types/runner/runner.d.ts +43 -9
  112. package/dist/types/sessions/base_session_service.d.ts +3 -16
  113. package/dist/types/sessions/session.d.ts +11 -0
  114. package/dist/types/sessions/vertex_ai_session_service.d.ts +9 -1
  115. package/dist/types/tools/consolidate_context_tool.d.ts +19 -0
  116. package/dist/types/tools/forwarding_artifact_service.d.ts +3 -2
  117. package/dist/types/utils/async_hooks_shim.d.ts +10 -0
  118. package/dist/types/utils/client_labels.d.ts +10 -0
  119. package/dist/types/utils/env_aware_utils.d.ts +3 -3
  120. package/dist/types/utils/task.d.ts +24 -0
  121. package/dist/types/version.d.ts +1 -1
  122. package/dist/web/agents/active_streaming_tool.js +6 -1
  123. package/dist/web/agents/context.js +1 -11
  124. package/dist/web/agents/functions.js +36 -15
  125. package/dist/web/agents/instructions.js +23 -5
  126. package/dist/web/agents/invocation_context.js +2 -5
  127. package/dist/web/agents/llm_agent.js +8 -6
  128. package/dist/web/agents/processors/code_execution_request_processor.js +0 -3
  129. package/dist/web/agents/processors/content_processor_utils.js +14 -2
  130. package/dist/web/agents/processors/context_compactor_request_processor.js +4 -2
  131. package/dist/web/agents/processors/interactions_request_processor.js +52 -0
  132. package/dist/web/apps/app.js +49 -0
  133. package/dist/web/apps/resumability_config.js +31 -0
  134. package/dist/web/artifacts/file_artifact_service.js +14 -1
  135. package/dist/web/artifacts/gcs_artifact_service.js +55 -15
  136. package/dist/web/artifacts/in_memory_artifact_service.js +5 -1
  137. package/dist/web/artifacts/scoped_artifact_service.js +86 -0
  138. package/dist/web/artifacts/session_artifact_service.js +7 -0
  139. package/dist/web/auth/oauth2/oauth2_discovery.js +14 -4
  140. package/dist/web/auth/oauth2/oauth2_utils.js +12 -1
  141. package/dist/web/common.js +42 -2
  142. package/dist/web/context/agent_controlled_context_compactor.js +81 -0
  143. package/dist/web/context/token_based_context_compactor.js +42 -10
  144. package/dist/web/context/trajectory_thought_pruning_compactor.js +43 -0
  145. package/dist/web/events/event.js +20 -0
  146. package/dist/web/models/google_llm.js +54 -9
  147. package/dist/web/models/interactions_utils.js +728 -0
  148. package/dist/web/plugins/base_plugin.js +1 -0
  149. package/dist/web/runner/in_memory_runner.js +13 -2
  150. package/dist/web/runner/runner.js +111 -75
  151. package/dist/web/sessions/base_session_service.js +6 -1
  152. package/dist/web/sessions/database_session_service.js +24 -7
  153. package/dist/web/sessions/vertex_ai_session_service.js +17 -3
  154. package/dist/web/skills/loader.js +2 -2
  155. package/dist/web/tools/base_toolset.js +1 -1
  156. package/dist/web/tools/consolidate_context_tool.js +51 -0
  157. package/dist/web/tools/forwarding_artifact_service.js +16 -28
  158. package/dist/web/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +2 -12
  159. package/dist/web/utils/async_hooks_shim.js +24 -0
  160. package/dist/web/utils/client_labels.js +38 -2
  161. package/dist/web/utils/env_aware_utils.js +10 -1
  162. package/dist/web/utils/streaming_utils.js +10 -4
  163. package/dist/web/utils/task.js +34 -0
  164. package/dist/web/version.js +1 -1
  165. package/package.json +2 -2
@@ -14,19 +14,30 @@ class InMemoryRunner extends Runner {
14
14
  * Creates a new InMemoryRunner instance.
15
15
  *
16
16
  * @param params The configuration for the runner.
17
+ * @param params.app An optional application instance to run.
17
18
  * @param params.agent The root agent to run.
18
19
  * @param params.appName The application name. Defaults to `'InMemoryRunner'`.
19
20
  * @param params.plugins An optional list of plugins.
21
+ * @param params.resumabilityConfig An optional resumability configuration.
20
22
  */
21
23
  constructor(params) {
22
- const { agent, appName = "InMemoryRunner", plugins = [] } = params;
24
+ var _a;
25
+ const {
26
+ agent,
27
+ appName = "InMemoryRunner",
28
+ plugins = [],
29
+ app,
30
+ resumabilityConfig
31
+ } = params;
23
32
  super({
33
+ app,
24
34
  appName,
25
35
  agent,
26
36
  plugins,
27
37
  artifactService: new InMemoryArtifactService(),
28
38
  sessionService: new InMemorySessionService(),
29
- memoryService: new InMemoryMemoryService()
39
+ memoryService: new InMemoryMemoryService(),
40
+ resumabilityConfig: (_a = app == null ? void 0 : app.resumabilityConfig) != null ? _a : resumabilityConfig
30
41
  });
31
42
  }
32
43
  }
@@ -8,17 +8,19 @@ const require = topLevelCreateRequire(import.meta.url);
8
8
  var _a;
9
9
  import { createPartFromText } from "@google/genai";
10
10
  import { context, trace } from "@opentelemetry/api";
11
+ import { findMatchingFunctionCall } from "../agents/functions.js";
11
12
  import {
12
13
  InvocationContext,
13
14
  newInvocationContextId
14
15
  } from "../agents/invocation_context.js";
15
16
  import { isLlmAgent } from "../agents/llm_agent.js";
16
17
  import { createRunConfig } from "../agents/run_config.js";
18
+ import { ScopedArtifactService } from "../artifacts/scoped_artifact_service.js";
17
19
  import {
18
20
  BuiltInCodeExecutor,
19
21
  isBuiltInCodeExecutor
20
22
  } from "../code_executors/built_in_code_executor.js";
21
- import { createEvent, getFunctionCalls } from "../events/event.js";
23
+ import { createEvent } from "../events/event.js";
22
24
  import { createEventActions } from "../events/event_actions.js";
23
25
  import { PluginManager } from "../plugins/plugin_manager.js";
24
26
  import {
@@ -41,14 +43,24 @@ class Runner {
41
43
  */
42
44
  constructor(input) {
43
45
  this[_a] = true;
44
- var _a2;
45
- this.appName = input.appName;
46
- this.agent = input.agent;
47
- this.pluginManager = new PluginManager((_a2 = input.plugins) != null ? _a2 : []);
46
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
47
+ const appName = (_b = (_a2 = input.app) == null ? void 0 : _a2.name) != null ? _b : input.appName;
48
+ const agent = (_d = (_c = input.app) == null ? void 0 : _c.rootAgent) != null ? _d : input.agent;
49
+ if (!agent) {
50
+ throw new Error(
51
+ "agent must be provided in runner constructor (or via app.rootAgent)"
52
+ );
53
+ }
54
+ this.appName = appName;
55
+ this.agent = agent;
56
+ const appPlugins = (_f = (_e = input.app) == null ? void 0 : _e.plugins) != null ? _f : [];
57
+ const configPlugins = (_g = input.plugins) != null ? _g : [];
58
+ this.pluginManager = new PluginManager([...appPlugins, ...configPlugins]);
48
59
  this.artifactService = input.artifactService;
49
60
  this.sessionService = input.sessionService;
50
61
  this.memoryService = input.memoryService;
51
62
  this.credentialService = input.credentialService;
63
+ this.resumabilityConfig = (_i = (_h = input.app) == null ? void 0 : _h.resumabilityConfig) != null ? _i : input.resumabilityConfig;
52
64
  }
53
65
  /**
54
66
  * Runs the agent with a new, ephemeral session.
@@ -98,6 +110,9 @@ class Runner {
98
110
  const { userId, sessionId, stateDelta } = params;
99
111
  const runConfig = createRunConfig(params.runConfig);
100
112
  let newMessage = params.newMessage;
113
+ if (newMessage && !newMessage.role) {
114
+ newMessage.role = "user";
115
+ }
101
116
  const span = tracer.startSpan("invocation");
102
117
  const ctx = trace.setSpan(context.active(), span);
103
118
  try {
@@ -117,7 +132,7 @@ class Runner {
117
132
  if (!session) {
118
133
  if (!this.appName) {
119
134
  throw new Error(
120
- `Session lookup failed: appName must be provided in runner constructor`
135
+ `Session lookup failed: appName must be provided in runner constructor (or via app.name)`
121
136
  );
122
137
  }
123
138
  throw new Error(`Session not found: ${sessionId}`);
@@ -134,7 +149,12 @@ class Runner {
134
149
  }
135
150
  }
136
151
  const invocationContext = new InvocationContext({
137
- artifactService: this.artifactService,
152
+ artifactService: this.artifactService ? new ScopedArtifactService(
153
+ this.artifactService,
154
+ this.appName,
155
+ userId,
156
+ sessionId
157
+ ) : void 0,
138
158
  sessionService: this.sessionService,
139
159
  memoryService: this.memoryService,
140
160
  credentialService: this.credentialService,
@@ -261,6 +281,11 @@ class Runner {
261
281
  if (!this.artifactService || !((_a2 = message.parts) == null ? void 0 : _a2.length)) {
262
282
  return;
263
283
  }
284
+ const sessionKey = {
285
+ appName: this.appName,
286
+ userId,
287
+ sessionId
288
+ };
264
289
  for (let i = 0; i < message.parts.length; i++) {
265
290
  const part = message.parts[i];
266
291
  if (!part.inlineData) {
@@ -268,9 +293,7 @@ class Runner {
268
293
  }
269
294
  const fileName = `artifact_${invocationId}_${i}`;
270
295
  await this.artifactService.saveArtifact({
271
- appName: this.appName,
272
- userId,
273
- sessionId,
296
+ ...sessionKey,
274
297
  filename: fileName,
275
298
  artifact: part
276
299
  });
@@ -283,86 +306,78 @@ class Runner {
283
306
  * Determines the next agent to run to continue the session. This is primarily
284
307
  * used for session resumption.
285
308
  */
286
- // TODO - b/425992518: This is where LRO integration should happen.
287
- // Needs clean up before we can generalize it.
309
+ /**
310
+ * Determines the next agent to run to continue the session. This is primarily
311
+ * used for session resumption across tool and LRO boundaries.
312
+ */
288
313
  determineAgentForResumption(session, rootAgent) {
289
- const event = findEventByLastFunctionResponseId(session.events);
290
- if (event && event.author) {
291
- return rootAgent.findAgent(event.author) || rootAgent;
292
- }
293
- for (let i = session.events.length - 1; i >= 0; i--) {
294
- logger.info("event:", JSON.stringify(session.events[i]));
295
- const event2 = session.events[i];
296
- if (event2.author === "user" || !event2.author) {
297
- continue;
298
- }
299
- if (event2.author === rootAgent.name) {
300
- return rootAgent;
301
- }
302
- const agent = rootAgent.findSubAgent(event2.author);
303
- if (!agent) {
304
- logger.warn(
305
- `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
306
- );
307
- continue;
308
- }
309
- if (this.isRoutableLlmAgent(agent)) {
310
- return agent;
311
- }
312
- }
313
- return rootAgent;
314
+ return determineAgentForResumption(
315
+ session,
316
+ rootAgent,
317
+ this.resumabilityConfig
318
+ );
314
319
  }
315
320
  /**
316
321
  * Whether the agent to run can transfer to any other agent in the agent tree.
317
322
  *
318
- * An agent is transferable if:
319
- * - It is an instance of `LlmAgent`.
320
- * - All its ancestors are also transferable (i.e., they have
321
- * `disallowTransferToParent` set to false).
322
- *
323
323
  * @param agentToRun The agent to check for transferability.
324
324
  * @returns True if the agent can transfer, False otherwise.
325
325
  */
326
326
  isRoutableLlmAgent(agentToRun) {
327
- let agent = agentToRun;
328
- while (agent) {
329
- if (!isLlmAgent(agent)) {
330
- return false;
331
- }
332
- if (agent.disallowTransferToParent) {
333
- return false;
334
- }
335
- agent = agent.parentAgent;
336
- }
337
- return true;
327
+ return isRoutableLlmAgent(agentToRun);
338
328
  }
339
329
  // TODO - b/425992518: Implement runLive and related methods.
340
330
  }
341
- function findEventByLastFunctionResponseId(events) {
342
- var _a2, _b, _c, _d;
343
- if (!events.length) {
344
- return null;
345
- }
346
- const lastEvent = events[events.length - 1];
347
- const functionCallId = (_d = (_c = (_b = (_a2 = lastEvent.content) == null ? void 0 : _a2.parts) == null ? void 0 : _b.find(
348
- (part) => part.functionResponse
349
- )) == null ? void 0 : _c.functionResponse) == null ? void 0 : _d.id;
350
- if (!functionCallId) {
351
- return null;
331
+ function determineAgentForResumption(session, rootAgent, resumabilityConfig) {
332
+ const event = findEventByLastFunctionResponseId(session.events);
333
+ const isResumable = Boolean(resumabilityConfig == null ? void 0 : resumabilityConfig.isResumable);
334
+ if (event && event.author && isResumable) {
335
+ const resumedAgent = rootAgent.findAgent(event.author);
336
+ if (resumedAgent) {
337
+ return resumedAgent;
338
+ }
339
+ logger.warn(
340
+ `Function response from an unknown agent: ${event.author}, event id: ${event.id}`
341
+ );
352
342
  }
353
- for (let i = events.length - 2; i >= 0; i--) {
354
- const event = events[i];
355
- const functionCalls = getFunctionCalls(event);
356
- if (!functionCalls) {
343
+ for (let i = session.events.length - 1; i >= 0; i--) {
344
+ logger.debug("event:", JSON.stringify(session.events[i]));
345
+ const event2 = session.events[i];
346
+ if (event2.author === "user" || !event2.author) {
357
347
  continue;
358
348
  }
359
- for (const functionCall of functionCalls) {
360
- if (functionCall.id === functionCallId) {
361
- return event;
362
- }
349
+ if (event2.author === rootAgent.name) {
350
+ return rootAgent;
351
+ }
352
+ const agent = rootAgent.findSubAgent(event2.author);
353
+ if (!agent) {
354
+ logger.warn(
355
+ `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
356
+ );
357
+ continue;
358
+ }
359
+ if (isRoutableLlmAgent(agent)) {
360
+ return agent;
363
361
  }
364
362
  }
365
- return null;
363
+ return rootAgent;
364
+ }
365
+ function isRoutableLlmAgent(agentToRun) {
366
+ let agent = agentToRun;
367
+ while (agent) {
368
+ if (!isLlmAgent(agent)) {
369
+ return false;
370
+ }
371
+ if (agent.disallowTransferToParent) {
372
+ return false;
373
+ }
374
+ agent = agent.parentAgent;
375
+ }
376
+ return true;
377
+ }
378
+ function findEventByLastFunctionResponseId(events) {
379
+ var _a2;
380
+ return (_a2 = findMatchingFunctionCall(events)) != null ? _a2 : null;
366
381
  }
367
382
  function getAllToolsets(agent) {
368
383
  const toolsets = [];
@@ -386,5 +401,8 @@ function getAllToolsets(agent) {
386
401
  }
387
402
  export {
388
403
  Runner,
404
+ determineAgentForResumption,
405
+ findEventByLastFunctionResponseId,
406
+ isRoutableLlmAgent,
389
407
  isRunner
390
408
  };
@@ -40,7 +40,12 @@ class BaseSessionService {
40
40
  }
41
41
  event = trimTempDeltaState(event);
42
42
  this.updateSessionState({ session, event });
43
- session.events.push(event);
43
+ const index = session.events.findIndex((e) => e.id === event.id);
44
+ if (index >= 0) {
45
+ session.events[index] = event;
46
+ } else {
47
+ session.events.push(event);
48
+ }
44
49
  return event;
45
50
  }
46
51
  /**
@@ -371,16 +371,28 @@ class DatabaseSessionService extends BaseSessionService {
371
371
  storageSession.state = { ...storageSession.state, ...sessionDelta };
372
372
  }
373
373
  }
374
- const newStorageEvent = txEm.create(StorageEvent, {
374
+ const existingStorageEvent = await txEm.findOne(StorageEvent, {
375
375
  id: trimmedEvent.id,
376
376
  appName: session.appName,
377
377
  userId: session.userId,
378
- sessionId: session.id,
379
- invocationId: trimmedEvent.invocationId,
380
- timestamp: new Date(trimmedEvent.timestamp),
381
- eventData: trimmedEvent
378
+ sessionId: session.id
382
379
  });
383
- txEm.persist(newStorageEvent);
380
+ if (existingStorageEvent) {
381
+ existingStorageEvent.eventData = trimmedEvent;
382
+ existingStorageEvent.timestamp = new Date(trimmedEvent.timestamp);
383
+ txEm.persist(existingStorageEvent);
384
+ } else {
385
+ const newStorageEvent = txEm.create(StorageEvent, {
386
+ id: trimmedEvent.id,
387
+ appName: session.appName,
388
+ userId: session.userId,
389
+ sessionId: session.id,
390
+ invocationId: trimmedEvent.invocationId,
391
+ timestamp: new Date(trimmedEvent.timestamp),
392
+ eventData: trimmedEvent
393
+ });
394
+ txEm.persist(newStorageEvent);
395
+ }
384
396
  await txEm.commit();
385
397
  storageSession.updateTime = new Date(event.timestamp);
386
398
  const newMergedState = mergeStates(
@@ -389,7 +401,12 @@ class DatabaseSessionService extends BaseSessionService {
389
401
  storageSession.state
390
402
  );
391
403
  session.state = newMergedState;
392
- session.events.push(event);
404
+ const index = session.events.findIndex((e) => e.id === event.id);
405
+ if (index >= 0) {
406
+ session.events[index] = event;
407
+ } else {
408
+ session.events.push(event);
409
+ }
393
410
  session.lastUpdateTime = storageSession.updateTime.getTime();
394
411
  });
395
412
  return event;
@@ -32,6 +32,10 @@ const HTTP_NOT_FOUND = 404;
32
32
  function isVertexAiConnectionString(uri) {
33
33
  return (uri == null ? void 0 : uri.startsWith("vertexai://")) || false;
34
34
  }
35
+ function quoteFilterLiteral(value) {
36
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
37
+ return `"${escaped}"`;
38
+ }
35
39
  let VertexAiSessionService = class extends BaseSessionService {
36
40
  constructor(options) {
37
41
  super();
@@ -199,7 +203,7 @@ let VertexAiSessionService = class extends BaseSessionService {
199
203
  const response = await this.sessions.listInternal({
200
204
  name: `reasoningEngines/${reasoningEngineId}`,
201
205
  config: {
202
- ...userId ? { filter: `user_id="${userId}"` } : {},
206
+ ...userId ? { filter: `user_id=${quoteFilterLiteral(userId)}` } : {},
203
207
  ...pageToken ? { pageToken } : {}
204
208
  }
205
209
  });
@@ -260,10 +264,19 @@ let VertexAiSessionService = class extends BaseSessionService {
260
264
  }
261
265
  async deleteSession({
262
266
  appName,
263
- userId: _userId,
267
+ userId,
264
268
  sessionId
265
269
  }) {
266
270
  const reasoningEngineId = this.getReasoningEngineId(appName);
271
+ const session = await this.getSession({
272
+ appName,
273
+ userId,
274
+ sessionId,
275
+ config: { numRecentEvents: 0 }
276
+ });
277
+ if (!session) {
278
+ return;
279
+ }
267
280
  await this.sessions.delete({
268
281
  name: `reasoningEngines/${reasoningEngineId}/sessions/${sessionId}`
269
282
  });
@@ -401,5 +414,6 @@ function _fromApiEvent(apiEventObj) {
401
414
  }
402
415
  export {
403
416
  VertexAiSessionService,
404
- isVertexAiConnectionString
417
+ isVertexAiConnectionString,
418
+ quoteFilterLiteral
405
419
  };
@@ -84,12 +84,12 @@ function parseSkillMdContent(content) {
84
84
  if (!content.startsWith("---")) {
85
85
  throw new Error("SKILL.md must start with YAML frontmatter (---)");
86
86
  }
87
- const parts = content.split("---", 3);
87
+ const parts = content.split("---");
88
88
  if (parts.length < 3) {
89
89
  throw new Error("SKILL.md frontmatter not properly closed with ---");
90
90
  }
91
91
  const frontmatterStr = parts[1];
92
- const body = parts[2].trim();
92
+ const body = parts.filter((_, i) => i >= 2).join("---").trim();
93
93
  try {
94
94
  const parsed = yaml.load(frontmatterStr);
95
95
  if (typeof parsed !== "object" || parsed === null) {
@@ -25,7 +25,7 @@ class BaseToolset {
25
25
  * @return Whether the tool should be exposed to LLM.
26
26
  */
27
27
  isToolSelected(tool, context) {
28
- if (!this.toolFilter) {
28
+ if (!this.toolFilter || Array.isArray(this.toolFilter) && this.toolFilter.length === 0) {
29
29
  return true;
30
30
  }
31
31
  if (typeof this.toolFilter === "function") {
@@ -0,0 +1,51 @@
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 { Type } from "@google/genai";
9
+ import { BaseTool } from "./base_tool.js";
10
+ class ConsolidateContextTool extends BaseTool {
11
+ constructor() {
12
+ super({
13
+ name: "consolidate_context",
14
+ description: "Requests context consolidation (compaction) to manage history size. Use this when a subtask is complete and you want to summarize progress and clear detailed history."
15
+ });
16
+ }
17
+ _getDeclaration() {
18
+ return {
19
+ name: this.name,
20
+ description: this.description,
21
+ parameters: {
22
+ type: Type.OBJECT,
23
+ properties: {
24
+ detail: {
25
+ type: Type.STRING,
26
+ description: "Optional description of what has been accomplished so far. This detail will be used to guide the summarization of the history."
27
+ }
28
+ }
29
+ }
30
+ };
31
+ }
32
+ async runAsync({
33
+ args,
34
+ toolContext
35
+ }) {
36
+ toolContext.state.set("temp:consolidate_context", true);
37
+ if (args["detail"] !== void 0) {
38
+ toolContext.state.set(
39
+ "temp:consolidate_context_detail",
40
+ args["detail"]
41
+ );
42
+ }
43
+ return {
44
+ status: "success",
45
+ message: "Context consolidation requested."
46
+ };
47
+ }
48
+ }
49
+ export {
50
+ ConsolidateContextTool
51
+ };
@@ -10,48 +10,36 @@ class ForwardingArtifactService {
10
10
  this.toolContext = toolContext;
11
11
  this.invocationContext = toolContext.invocationContext;
12
12
  }
13
- // TODO - b/425992518: Remove unnecessary parameters. We should rethink the
14
- // abstraction layer to make it more clear.
15
13
  async saveArtifact(request) {
16
14
  return this.toolContext.saveArtifact(request.filename, request.artifact);
17
15
  }
18
16
  async loadArtifact(request) {
19
17
  return this.toolContext.loadArtifact(request.filename, request.version);
20
18
  }
21
- async listArtifactKeys() {
19
+ async listArtifactKeys(_request) {
22
20
  return this.toolContext.listArtifacts();
23
21
  }
24
- async deleteArtifact(request) {
25
- if (!this.toolContext.invocationContext.artifactService) {
22
+ getArtifactService() {
23
+ const service = this.invocationContext.artifactService;
24
+ if (!service) {
26
25
  throw new Error("Artifact service is not initialized.");
27
26
  }
28
- return this.toolContext.invocationContext.artifactService.deleteArtifact(
29
- request
30
- );
27
+ return service;
28
+ }
29
+ async deleteArtifact(request) {
30
+ return this.getArtifactService().deleteArtifact(request.filename);
31
31
  }
32
32
  async listVersions(request) {
33
- if (!this.toolContext.invocationContext.artifactService) {
34
- throw new Error("Artifact service is not initialized.");
35
- }
36
- return this.toolContext.invocationContext.artifactService.listVersions(
37
- request
38
- );
33
+ return this.getArtifactService().listVersions(request.filename);
39
34
  }
40
- listArtifactVersions(request) {
41
- if (!this.toolContext.invocationContext.artifactService) {
42
- throw new Error("Artifact service is not initialized.");
43
- }
44
- return this.toolContext.invocationContext.artifactService.listArtifactVersions(
45
- request
46
- );
35
+ async listArtifactVersions(request) {
36
+ return this.getArtifactService().listArtifactVersions(request.filename);
47
37
  }
48
- getArtifactVersion(request) {
49
- if (!this.toolContext.invocationContext.artifactService) {
50
- throw new Error("Artifact service is not initialized.");
51
- }
52
- return this.toolContext.invocationContext.artifactService.getArtifactVersion(
53
- request
54
- );
38
+ async getArtifactVersion(request) {
39
+ return this.getArtifactService().getArtifactVersion({
40
+ filename: request.filename,
41
+ version: request.version
42
+ });
55
43
  }
56
44
  }
57
45
  export {
@@ -27,20 +27,10 @@ class ToolContextCredentialStore {
27
27
  }
28
28
  getCredential(authScheme) {
29
29
  const key = this.getCredentialKey(authScheme);
30
- const state = this.context.state;
31
- if (state) {
32
- const serialized = state[key];
33
- if (serialized) {
34
- return serialized;
35
- }
36
- }
37
- return void 0;
30
+ return this.context.state.get(key);
38
31
  }
39
32
  storeCredential(key, credential) {
40
- const state = this.context.state;
41
- if (state) {
42
- state[key] = credential;
43
- }
33
+ this.context.state.set(key, credential);
44
34
  }
45
35
  }
46
36
  let ToolAuthHandler = class {
@@ -0,0 +1,24 @@
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
+ class AsyncLocalStorage {
9
+ run(store, callback) {
10
+ const previous = this.store;
11
+ this.store = store;
12
+ try {
13
+ return callback();
14
+ } finally {
15
+ this.store = previous;
16
+ }
17
+ }
18
+ getStore() {
19
+ return this.store;
20
+ }
21
+ }
22
+ export {
23
+ AsyncLocalStorage
24
+ };
@@ -5,24 +5,60 @@ const require = topLevelCreateRequire(import.meta.url);
5
5
  * Copyright 2025 Google LLC
6
6
  * SPDX-License-Identifier: Apache-2.0
7
7
  */
8
+ import { AsyncLocalStorage } from "node:async_hooks";
8
9
  import { version } from "../version.js";
9
10
  import { isBrowser } from "./env_aware_utils.js";
10
11
  const ADK_LABEL = "google-adk";
11
12
  const LANGUAGE_LABEL = "gl-typescript";
12
13
  const AGENT_ENGINE_TELEMETRY_TAG = "remote_reasoning_engine";
13
14
  const AGENT_ENGINE_TELEMETRY_ENV_VARIABLE_NAME = "GOOGLE_CLOUD_AGENT_ENGINE_ID";
15
+ const clientLabelLocalStorage = new AsyncLocalStorage();
16
+ const USER_AGENT_PATTERNS = [
17
+ ["Edge", /(?:Edg|Edge|EdgA)\/([0-9.]+)/i],
18
+ ["Firefox", /(?:Firefox|FxiOS)\/([0-9.]+)/i],
19
+ ["Chrome", /(?:Chrome|CriOS)\/([0-9.]+)/i],
20
+ ["Safari", /Version\/([0-9.]+).*Safari/i]
21
+ ];
22
+ function parseUserAgent(userAgent) {
23
+ if (!userAgent) {
24
+ return "Browser";
25
+ }
26
+ for (const [name, regex] of USER_AGENT_PATTERNS) {
27
+ const match = userAgent.match(regex);
28
+ if (match) {
29
+ return `${name}/${match[1]}`;
30
+ }
31
+ }
32
+ return "Browser";
33
+ }
14
34
  function _getDefaultLabels() {
15
35
  let frameworkLabel = `${ADK_LABEL}/${version}`;
16
36
  if (!isBrowser() && process.env[AGENT_ENGINE_TELEMETRY_ENV_VARIABLE_NAME]) {
17
37
  frameworkLabel = `${frameworkLabel}+${AGENT_ENGINE_TELEMETRY_TAG}`;
18
38
  }
19
- const languageLabel = `${LANGUAGE_LABEL}/${isBrowser() ? window.navigator.userAgent : process.version}`;
39
+ const languageLabelDetail = isBrowser() ? (
40
+ // eslint-disable-next-line no-undef
41
+ parseUserAgent(window.navigator.userAgent)
42
+ ) : process.version;
43
+ const languageLabel = `${LANGUAGE_LABEL}/${languageLabelDetail}`;
20
44
  return [frameworkLabel, languageLabel];
21
45
  }
46
+ function runWithClientLabel(clientLabel, callback) {
47
+ if (typeof clientLabel !== "string" || clientLabel.trim() === "") {
48
+ throw new Error("Client label must be a non-empty string.");
49
+ }
50
+ return clientLabelLocalStorage.run(clientLabel, callback);
51
+ }
22
52
  function getClientLabels() {
23
53
  const labels = _getDefaultLabels();
54
+ const contextLabel = clientLabelLocalStorage.getStore();
55
+ if (contextLabel) {
56
+ labels.push(contextLabel);
57
+ }
24
58
  return labels;
25
59
  }
26
60
  export {
27
- getClientLabels
61
+ getClientLabels,
62
+ parseUserAgent,
63
+ runWithClientLabel
28
64
  };
@@ -29,7 +29,16 @@ function randomUUID() {
29
29
  }
30
30
  function base64Encode(data) {
31
31
  if (isBrowser()) {
32
- return window.btoa(data);
32
+ let strData = "";
33
+ if (typeof data === "string") {
34
+ strData = data;
35
+ } else {
36
+ const len = data.byteLength;
37
+ for (let i = 0; i < len; i++) {
38
+ strData += String.fromCharCode(data[i]);
39
+ }
40
+ }
41
+ return window.btoa(strData);
33
42
  }
34
43
  return Buffer.from(data).toString("base64");
35
44
  }