@google/adk 1.3.0 → 1.5.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 (248) hide show
  1. package/dist/cjs/a2a/agent_to_a2a.js +18 -2
  2. package/dist/cjs/a2a/event_converter_utils.js +8 -4
  3. package/dist/cjs/a2a/metadata_converter_utils.js +1 -1
  4. package/dist/cjs/agents/active_streaming_tool.js +6 -1
  5. package/dist/cjs/agents/base_agent.js +39 -0
  6. package/dist/cjs/agents/context.js +1 -11
  7. package/dist/cjs/agents/functions.js +39 -35
  8. package/dist/cjs/agents/instructions.js +23 -5
  9. package/dist/cjs/agents/invocation_context.js +2 -5
  10. package/dist/cjs/agents/llm_agent.js +10 -7
  11. package/dist/cjs/agents/loop_agent.js +15 -3
  12. package/dist/cjs/agents/processors/code_execution_request_processor.js +0 -3
  13. package/dist/cjs/agents/processors/content_processor_utils.js +18 -4
  14. package/dist/cjs/agents/processors/context_compactor_request_processor.js +4 -2
  15. package/dist/cjs/agents/processors/interactions_request_processor.js +63 -0
  16. package/dist/cjs/agents/routed_agent.js +31 -0
  17. package/dist/cjs/agents/run_config.js +3 -2
  18. package/dist/cjs/apps/app.js +79 -0
  19. package/dist/cjs/apps/resumability_config.js +44 -0
  20. package/dist/cjs/artifacts/file_artifact_service.js +14 -1
  21. package/dist/cjs/artifacts/gcs_artifact_service.js +57 -15
  22. package/dist/cjs/artifacts/in_memory_artifact_service.js +12 -1
  23. package/dist/cjs/artifacts/scoped_artifact_service.js +101 -0
  24. package/dist/cjs/artifacts/session_artifact_service.js +27 -0
  25. package/dist/cjs/auth/oauth2/oauth2_discovery.js +17 -5
  26. package/dist/cjs/auth/oauth2/oauth2_utils.js +12 -1
  27. package/dist/cjs/common.js +76 -0
  28. package/dist/cjs/context/agent_controlled_context_compactor.js +109 -0
  29. package/dist/cjs/context/anchored_context_compactor.js +127 -0
  30. package/dist/cjs/context/compaction_utils.js +52 -0
  31. package/dist/cjs/context/token_based_context_compactor.js +52 -33
  32. package/dist/cjs/context/trajectory_thought_pruning_compactor.js +71 -0
  33. package/dist/cjs/events/compacted_event.js +9 -3
  34. package/dist/cjs/events/event.js +52 -0
  35. package/dist/cjs/index.js +4 -0
  36. package/dist/cjs/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  37. package/dist/cjs/models/google_llm.js +25 -10
  38. package/dist/cjs/models/interactions_utils.js +732 -0
  39. package/dist/cjs/plugins/base_plugin.js +1 -0
  40. package/dist/cjs/plugins/global_instruction_plugin.js +97 -0
  41. package/dist/cjs/runner/in_memory_runner.js +13 -2
  42. package/dist/cjs/runner/runner.js +143 -83
  43. package/dist/cjs/sessions/base_session_service.js +6 -1
  44. package/dist/cjs/sessions/database_session_service.js +24 -7
  45. package/dist/cjs/sessions/vertex_ai_session_service.js +19 -4
  46. package/dist/cjs/skills/loader.js +2 -2
  47. package/dist/cjs/tools/base_toolset.js +1 -1
  48. package/dist/cjs/tools/consolidate_context_tool.js +79 -0
  49. package/dist/cjs/tools/enterprise_web_search_tool.js +81 -0
  50. package/dist/cjs/tools/example_tool.js +68 -0
  51. package/dist/cjs/tools/forwarding_artifact_service.js +16 -28
  52. package/dist/cjs/tools/load_web_page.js +250 -0
  53. package/dist/cjs/tools/mcp/load_mcp_resource_tool.js +140 -0
  54. package/dist/cjs/tools/mcp/mcp_toolset.js +63 -0
  55. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -22
  56. package/dist/cjs/tools/skill/run_skill_inline_script_tool.js +54 -4
  57. package/dist/cjs/tools/skill/skill_toolset.js +4 -2
  58. package/dist/cjs/utils/async_hooks_shim.js +52 -0
  59. package/dist/cjs/utils/branch_trie.js +41 -0
  60. package/dist/cjs/utils/client_labels.js +41 -3
  61. package/dist/cjs/utils/env_aware_utils.js +10 -1
  62. package/dist/cjs/utils/streaming_utils.js +15 -9
  63. package/dist/cjs/utils/task.js +62 -0
  64. package/dist/cjs/version.js +1 -1
  65. package/dist/esm/a2a/agent_to_a2a.js +18 -2
  66. package/dist/esm/a2a/event_converter_utils.js +8 -4
  67. package/dist/esm/a2a/metadata_converter_utils.js +1 -1
  68. package/dist/esm/agents/active_streaming_tool.js +6 -1
  69. package/dist/esm/agents/base_agent.js +39 -0
  70. package/dist/esm/agents/context.js +1 -11
  71. package/dist/esm/agents/functions.js +43 -32
  72. package/dist/esm/agents/instructions.js +23 -5
  73. package/dist/esm/agents/invocation_context.js +2 -5
  74. package/dist/esm/agents/llm_agent.js +12 -9
  75. package/dist/esm/agents/loop_agent.js +15 -3
  76. package/dist/esm/agents/processors/code_execution_request_processor.js +0 -3
  77. package/dist/esm/agents/processors/content_processor_utils.js +16 -3
  78. package/dist/esm/agents/processors/context_compactor_request_processor.js +4 -2
  79. package/dist/esm/agents/processors/interactions_request_processor.js +34 -0
  80. package/dist/esm/agents/routed_agent.js +31 -0
  81. package/dist/esm/agents/run_config.js +3 -2
  82. package/dist/esm/apps/app.js +49 -0
  83. package/dist/esm/apps/resumability_config.js +16 -0
  84. package/dist/esm/artifacts/file_artifact_service.js +14 -1
  85. package/dist/esm/artifacts/gcs_artifact_service.js +57 -15
  86. package/dist/esm/artifacts/in_memory_artifact_service.js +12 -1
  87. package/dist/esm/artifacts/scoped_artifact_service.js +73 -0
  88. package/dist/esm/artifacts/session_artifact_service.js +7 -0
  89. package/dist/esm/auth/oauth2/oauth2_discovery.js +14 -4
  90. package/dist/esm/auth/oauth2/oauth2_utils.js +12 -1
  91. package/dist/esm/common.js +67 -3
  92. package/dist/esm/context/agent_controlled_context_compactor.js +81 -0
  93. package/dist/esm/context/anchored_context_compactor.js +99 -0
  94. package/dist/esm/context/compaction_utils.js +27 -0
  95. package/dist/esm/context/token_based_context_compactor.js +52 -33
  96. package/dist/esm/context/trajectory_thought_pruning_compactor.js +43 -0
  97. package/dist/esm/events/compacted_event.js +7 -2
  98. package/dist/esm/events/event.js +46 -0
  99. package/dist/esm/index.js +6 -1
  100. package/dist/esm/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  101. package/dist/esm/models/google_llm.js +23 -9
  102. package/dist/esm/models/interactions_utils.js +697 -0
  103. package/dist/esm/plugins/base_plugin.js +1 -0
  104. package/dist/esm/plugins/global_instruction_plugin.js +69 -0
  105. package/dist/esm/runner/in_memory_runner.js +13 -2
  106. package/dist/esm/runner/runner.js +141 -84
  107. package/dist/esm/sessions/base_session_service.js +6 -1
  108. package/dist/esm/sessions/database_session_service.js +24 -7
  109. package/dist/esm/sessions/vertex_ai_session_service.js +17 -3
  110. package/dist/esm/skills/loader.js +2 -2
  111. package/dist/esm/tools/base_toolset.js +1 -1
  112. package/dist/esm/tools/consolidate_context_tool.js +51 -0
  113. package/dist/esm/tools/enterprise_web_search_tool.js +55 -0
  114. package/dist/esm/tools/example_tool.js +42 -0
  115. package/dist/esm/tools/forwarding_artifact_service.js +16 -28
  116. package/dist/esm/tools/load_web_page.js +221 -0
  117. package/dist/esm/tools/mcp/load_mcp_resource_tool.js +114 -0
  118. package/dist/esm/tools/mcp/mcp_toolset.js +63 -0
  119. package/dist/esm/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -22
  120. package/dist/esm/tools/skill/run_skill_inline_script_tool.js +53 -4
  121. package/dist/esm/tools/skill/skill_toolset.js +4 -2
  122. package/dist/esm/utils/async_hooks_shim.js +24 -0
  123. package/dist/esm/utils/branch_trie.js +13 -0
  124. package/dist/esm/utils/client_labels.js +38 -2
  125. package/dist/esm/utils/env_aware_utils.js +10 -1
  126. package/dist/esm/utils/streaming_utils.js +11 -5
  127. package/dist/esm/utils/task.js +34 -0
  128. package/dist/esm/version.js +1 -1
  129. package/dist/types/a2a/a2a_remote_agent.d.ts +5 -1
  130. package/dist/types/a2a/agent_to_a2a.d.ts +38 -0
  131. package/dist/types/agents/active_streaming_tool.d.ts +3 -4
  132. package/dist/types/agents/base_agent.d.ts +29 -1
  133. package/dist/types/agents/functions.d.ts +12 -17
  134. package/dist/types/agents/invocation_context.d.ts +7 -3
  135. package/dist/types/agents/llm_agent.d.ts +5 -1
  136. package/dist/types/agents/loop_agent.d.ts +2 -2
  137. package/dist/types/agents/processors/content_processor_utils.d.ts +8 -0
  138. package/dist/types/agents/processors/interactions_request_processor.d.ts +17 -0
  139. package/dist/types/agents/routed_agent.d.ts +24 -1
  140. package/dist/types/agents/run_config.d.ts +1 -1
  141. package/dist/types/apps/app.d.ts +52 -0
  142. package/dist/types/apps/resumability_config.d.ts +27 -0
  143. package/dist/types/artifacts/base_artifact_service.d.ts +6 -36
  144. package/dist/types/artifacts/gcs_artifact_service.d.ts +2 -1
  145. package/dist/types/artifacts/scoped_artifact_service.d.ts +25 -0
  146. package/dist/types/artifacts/session_artifact_service.d.ts +25 -0
  147. package/dist/types/auth/oauth2/oauth2_discovery.d.ts +11 -0
  148. package/dist/types/common.d.ts +29 -5
  149. package/dist/types/context/agent_controlled_context_compactor.d.ts +24 -0
  150. package/dist/types/context/anchored_context_compactor.d.ts +35 -0
  151. package/dist/types/context/base_context_compactor.d.ts +3 -0
  152. package/dist/types/context/compaction_utils.d.ts +15 -0
  153. package/dist/types/context/token_based_context_compactor.d.ts +6 -1
  154. package/dist/types/context/trajectory_thought_pruning_compactor.d.ts +27 -0
  155. package/dist/types/events/compacted_event.d.ts +10 -0
  156. package/dist/types/events/event.d.ts +21 -0
  157. package/dist/types/index.d.ts +3 -2
  158. package/dist/types/models/google_llm.d.ts +15 -1
  159. package/dist/types/models/interactions_utils.d.ts +92 -0
  160. package/dist/types/models/llm_request.d.ts +4 -0
  161. package/dist/types/models/llm_response.d.ts +4 -0
  162. package/dist/types/plugins/base_plugin.d.ts +2 -1
  163. package/dist/types/plugins/global_instruction_plugin.d.ts +38 -0
  164. package/dist/types/runner/in_memory_runner.d.ts +7 -1
  165. package/dist/types/runner/runner.d.ts +44 -10
  166. package/dist/types/sessions/base_session_service.d.ts +3 -16
  167. package/dist/types/sessions/session.d.ts +11 -0
  168. package/dist/types/sessions/vertex_ai_session_service.d.ts +9 -1
  169. package/dist/types/tools/consolidate_context_tool.d.ts +19 -0
  170. package/dist/types/tools/enterprise_web_search_tool.d.ts +26 -0
  171. package/dist/types/tools/example_tool.d.ts +21 -0
  172. package/dist/types/tools/forwarding_artifact_service.d.ts +3 -2
  173. package/dist/types/tools/load_web_page.d.ts +33 -0
  174. package/dist/types/tools/mcp/load_mcp_resource_tool.d.ts +26 -0
  175. package/dist/types/tools/mcp/mcp_toolset.d.ts +27 -0
  176. package/dist/types/tools/skill/run_skill_inline_script_tool.d.ts +25 -0
  177. package/dist/types/tools/skill/skill_toolset.d.ts +9 -0
  178. package/dist/types/utils/async_hooks_shim.d.ts +10 -0
  179. package/dist/types/utils/branch_trie.d.ts +14 -0
  180. package/dist/types/utils/client_labels.d.ts +10 -0
  181. package/dist/types/utils/env_aware_utils.d.ts +3 -3
  182. package/dist/types/utils/task.d.ts +24 -0
  183. package/dist/types/version.d.ts +1 -1
  184. package/dist/web/a2a/agent_to_a2a.js +18 -2
  185. package/dist/web/a2a/event_converter_utils.js +8 -4
  186. package/dist/web/a2a/metadata_converter_utils.js +1 -1
  187. package/dist/web/agents/active_streaming_tool.js +6 -1
  188. package/dist/web/agents/base_agent.js +39 -0
  189. package/dist/web/agents/context.js +1 -11
  190. package/dist/web/agents/functions.js +43 -32
  191. package/dist/web/agents/instructions.js +23 -5
  192. package/dist/web/agents/invocation_context.js +2 -5
  193. package/dist/web/agents/llm_agent.js +12 -9
  194. package/dist/web/agents/loop_agent.js +27 -3
  195. package/dist/web/agents/processors/code_execution_request_processor.js +0 -3
  196. package/dist/web/agents/processors/content_processor_utils.js +16 -3
  197. package/dist/web/agents/processors/context_compactor_request_processor.js +4 -2
  198. package/dist/web/agents/processors/interactions_request_processor.js +52 -0
  199. package/dist/web/agents/routed_agent.js +31 -0
  200. package/dist/web/agents/run_config.js +8 -3
  201. package/dist/web/apps/app.js +49 -0
  202. package/dist/web/apps/resumability_config.js +31 -0
  203. package/dist/web/artifacts/file_artifact_service.js +14 -1
  204. package/dist/web/artifacts/gcs_artifact_service.js +55 -15
  205. package/dist/web/artifacts/in_memory_artifact_service.js +12 -1
  206. package/dist/web/artifacts/scoped_artifact_service.js +86 -0
  207. package/dist/web/artifacts/session_artifact_service.js +7 -0
  208. package/dist/web/auth/oauth2/oauth2_discovery.js +14 -4
  209. package/dist/web/auth/oauth2/oauth2_utils.js +12 -1
  210. package/dist/web/common.js +67 -3
  211. package/dist/web/context/agent_controlled_context_compactor.js +81 -0
  212. package/dist/web/context/anchored_context_compactor.js +117 -0
  213. package/dist/web/context/compaction_utils.js +27 -0
  214. package/dist/web/context/token_based_context_compactor.js +52 -33
  215. package/dist/web/context/trajectory_thought_pruning_compactor.js +43 -0
  216. package/dist/web/events/compacted_event.js +7 -2
  217. package/dist/web/events/event.js +44 -0
  218. package/dist/web/index.js +6 -1
  219. package/dist/web/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  220. package/dist/web/models/google_llm.js +54 -9
  221. package/dist/web/models/interactions_utils.js +728 -0
  222. package/dist/web/plugins/base_plugin.js +1 -0
  223. package/dist/web/plugins/global_instruction_plugin.js +67 -0
  224. package/dist/web/runner/in_memory_runner.js +13 -2
  225. package/dist/web/runner/runner.js +157 -84
  226. package/dist/web/sessions/base_session_service.js +6 -1
  227. package/dist/web/sessions/database_session_service.js +24 -7
  228. package/dist/web/sessions/vertex_ai_session_service.js +17 -3
  229. package/dist/web/skills/loader.js +2 -2
  230. package/dist/web/tools/base_toolset.js +1 -1
  231. package/dist/web/tools/consolidate_context_tool.js +51 -0
  232. package/dist/web/tools/enterprise_web_search_tool.js +55 -0
  233. package/dist/web/tools/example_tool.js +42 -0
  234. package/dist/web/tools/forwarding_artifact_service.js +16 -28
  235. package/dist/web/tools/load_web_page.js +221 -0
  236. package/dist/web/tools/mcp/load_mcp_resource_tool.js +107 -0
  237. package/dist/web/tools/mcp/mcp_toolset.js +63 -0
  238. package/dist/web/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -22
  239. package/dist/web/tools/skill/run_skill_inline_script_tool.js +51 -4
  240. package/dist/web/tools/skill/skill_toolset.js +4 -2
  241. package/dist/web/utils/async_hooks_shim.js +24 -0
  242. package/dist/web/utils/branch_trie.js +13 -0
  243. package/dist/web/utils/client_labels.js +38 -2
  244. package/dist/web/utils/env_aware_utils.js +10 -1
  245. package/dist/web/utils/streaming_utils.js +11 -5
  246. package/dist/web/utils/task.js +34 -0
  247. package/dist/web/version.js +1 -1
  248. package/package.json +2 -2
@@ -45,6 +45,7 @@ var import_experimental = require("../utils/experimental.js");
45
45
  var ContextCompactionTrigger = /* @__PURE__ */ ((ContextCompactionTrigger2) => {
46
46
  ContextCompactionTrigger2["Manual"] = "Manual";
47
47
  ContextCompactionTrigger2["Auto"] = "Auto";
48
+ ContextCompactionTrigger2["AgentControlled"] = "AgentControlled";
48
49
  return ContextCompactionTrigger2;
49
50
  })(ContextCompactionTrigger || {});
50
51
  class BasePlugin {
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var global_instruction_plugin_exports = {};
26
+ __export(global_instruction_plugin_exports, {
27
+ GlobalInstructionPlugin: () => GlobalInstructionPlugin
28
+ });
29
+ module.exports = __toCommonJS(global_instruction_plugin_exports);
30
+ var import_instructions = require("../agents/instructions.js");
31
+ var import_readonly_context = require("../agents/readonly_context.js");
32
+ var import_base_plugin = require("./base_plugin.js");
33
+ /**
34
+ * @license
35
+ * Copyright 2026 Google LLC
36
+ * SPDX-License-Identifier: Apache-2.0
37
+ */
38
+ class GlobalInstructionPlugin extends import_base_plugin.BasePlugin {
39
+ /**
40
+ * Initializes the GlobalInstructionPlugin.
41
+ *
42
+ * @param globalInstruction The instruction to apply globally. Can be a string
43
+ * or an InstructionProvider function that takes ReadonlyContext and
44
+ * returns a string (sync or async).
45
+ * @param name The name of the plugin (defaults to 'global_instruction').
46
+ */
47
+ constructor(globalInstruction, name = "global_instruction") {
48
+ super(name);
49
+ this.globalInstruction = globalInstruction;
50
+ }
51
+ async beforeModelCallback(params) {
52
+ if (!this.globalInstruction) {
53
+ return;
54
+ }
55
+ const readonlyContext = new import_readonly_context.ReadonlyContext(
56
+ params.callbackContext.invocationContext
57
+ );
58
+ const finalGlobalInstruction = await this.resolveGlobalInstruction(readonlyContext);
59
+ if (!finalGlobalInstruction) {
60
+ return;
61
+ }
62
+ if (!params.llmRequest.config) {
63
+ params.llmRequest.config = {};
64
+ }
65
+ const existingInstruction = params.llmRequest.config.systemInstruction;
66
+ if (!existingInstruction || Array.isArray(existingInstruction) && existingInstruction.length === 0) {
67
+ params.llmRequest.config.systemInstruction = finalGlobalInstruction;
68
+ return;
69
+ }
70
+ if (typeof existingInstruction === "string") {
71
+ params.llmRequest.config.systemInstruction = `${finalGlobalInstruction}
72
+
73
+ ${existingInstruction}`;
74
+ } else if (Array.isArray(existingInstruction)) {
75
+ params.llmRequest.config.systemInstruction = [
76
+ finalGlobalInstruction,
77
+ ...existingInstruction
78
+ ];
79
+ } else {
80
+ params.llmRequest.config.systemInstruction = [
81
+ finalGlobalInstruction,
82
+ existingInstruction
83
+ ];
84
+ }
85
+ return;
86
+ }
87
+ async resolveGlobalInstruction(readonlyContext) {
88
+ if (typeof this.globalInstruction === "string") {
89
+ return await (0, import_instructions.injectSessionState)(this.globalInstruction, readonlyContext);
90
+ }
91
+ return await this.globalInstruction(readonlyContext);
92
+ }
93
+ }
94
+ // Annotate the CommonJS export names for ESM import in node:
95
+ 0 && (module.exports = {
96
+ GlobalInstructionPlugin
97
+ });
@@ -41,19 +41,30 @@ class InMemoryRunner extends import_runner.Runner {
41
41
  * Creates a new InMemoryRunner instance.
42
42
  *
43
43
  * @param params The configuration for the runner.
44
+ * @param params.app An optional application instance to run.
44
45
  * @param params.agent The root agent to run.
45
46
  * @param params.appName The application name. Defaults to `'InMemoryRunner'`.
46
47
  * @param params.plugins An optional list of plugins.
48
+ * @param params.resumabilityConfig An optional resumability configuration.
47
49
  */
48
50
  constructor(params) {
49
- const { agent, appName = "InMemoryRunner", plugins = [] } = params;
51
+ var _a;
52
+ const {
53
+ agent,
54
+ appName = "InMemoryRunner",
55
+ plugins = [],
56
+ app,
57
+ resumabilityConfig
58
+ } = params;
50
59
  super({
60
+ app,
51
61
  appName,
52
62
  agent,
53
63
  plugins,
54
64
  artifactService: new import_in_memory_artifact_service.InMemoryArtifactService(),
55
65
  sessionService: new import_in_memory_session_service.InMemorySessionService(),
56
- memoryService: new import_in_memory_memory_service.InMemoryMemoryService()
66
+ memoryService: new import_in_memory_memory_service.InMemoryMemoryService(),
67
+ resumabilityConfig: (_a = app == null ? void 0 : app.resumabilityConfig) != null ? _a : resumabilityConfig
57
68
  });
58
69
  }
59
70
  }
@@ -25,14 +25,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
25
25
  var runner_exports = {};
26
26
  __export(runner_exports, {
27
27
  Runner: () => Runner,
28
+ determineAgentForResumption: () => determineAgentForResumption,
29
+ findEventByLastFunctionResponseId: () => findEventByLastFunctionResponseId,
30
+ isRoutableLlmAgent: () => isRoutableLlmAgent,
28
31
  isRunner: () => isRunner
29
32
  });
30
33
  module.exports = __toCommonJS(runner_exports);
31
34
  var import_genai = require("@google/genai");
32
35
  var import_api = require("@opentelemetry/api");
36
+ var import_functions = require("../agents/functions.js");
33
37
  var import_invocation_context = require("../agents/invocation_context.js");
34
38
  var import_llm_agent = require("../agents/llm_agent.js");
35
39
  var import_run_config = require("../agents/run_config.js");
40
+ var import_scoped_artifact_service = require("../artifacts/scoped_artifact_service.js");
36
41
  var import_built_in_code_executor = require("../code_executors/built_in_code_executor.js");
37
42
  var import_event = require("../events/event.js");
38
43
  var import_event_actions = require("../events/event_actions.js");
@@ -60,14 +65,24 @@ class Runner {
60
65
  */
61
66
  constructor(input) {
62
67
  this[_a] = true;
63
- var _a2;
64
- this.appName = input.appName;
65
- this.agent = input.agent;
66
- this.pluginManager = new import_plugin_manager.PluginManager((_a2 = input.plugins) != null ? _a2 : []);
68
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
69
+ const appName = (_b = (_a2 = input.app) == null ? void 0 : _a2.name) != null ? _b : input.appName;
70
+ const agent = (_d = (_c = input.app) == null ? void 0 : _c.rootAgent) != null ? _d : input.agent;
71
+ if (!agent) {
72
+ throw new Error(
73
+ "agent must be provided in runner constructor (or via app.rootAgent)"
74
+ );
75
+ }
76
+ this.appName = appName;
77
+ this.agent = agent;
78
+ const appPlugins = (_f = (_e = input.app) == null ? void 0 : _e.plugins) != null ? _f : [];
79
+ const configPlugins = (_g = input.plugins) != null ? _g : [];
80
+ this.pluginManager = new import_plugin_manager.PluginManager([...appPlugins, ...configPlugins]);
67
81
  this.artifactService = input.artifactService;
68
82
  this.sessionService = input.sessionService;
69
83
  this.memoryService = input.memoryService;
70
84
  this.credentialService = input.credentialService;
85
+ this.resumabilityConfig = (_i = (_h = input.app) == null ? void 0 : _h.resumabilityConfig) != null ? _i : input.resumabilityConfig;
71
86
  }
72
87
  /**
73
88
  * Runs the agent with a new, ephemeral session.
@@ -117,6 +132,9 @@ class Runner {
117
132
  const { userId, sessionId, stateDelta } = params;
118
133
  const runConfig = (0, import_run_config.createRunConfig)(params.runConfig);
119
134
  let newMessage = params.newMessage;
135
+ if (newMessage && !newMessage.role) {
136
+ newMessage.role = "user";
137
+ }
120
138
  const span = import_tracing.tracer.startSpan("invocation");
121
139
  const ctx = import_api.trace.setSpan(import_api.context.active(), span);
122
140
  try {
@@ -136,7 +154,7 @@ class Runner {
136
154
  if (!session) {
137
155
  if (!this.appName) {
138
156
  throw new Error(
139
- `Session lookup failed: appName must be provided in runner constructor`
157
+ `Session lookup failed: appName must be provided in runner constructor (or via app.name)`
140
158
  );
141
159
  }
142
160
  throw new Error(`Session not found: ${sessionId}`);
@@ -153,7 +171,12 @@ class Runner {
153
171
  }
154
172
  }
155
173
  const invocationContext = new import_invocation_context.InvocationContext({
156
- artifactService: this.artifactService,
174
+ artifactService: this.artifactService ? new import_scoped_artifact_service.ScopedArtifactService(
175
+ this.artifactService,
176
+ this.appName,
177
+ userId,
178
+ sessionId
179
+ ) : void 0,
157
180
  sessionService: this.sessionService,
158
181
  memoryService: this.memoryService,
159
182
  credentialService: this.credentialService,
@@ -180,7 +203,7 @@ class Runner {
180
203
  throw new Error("No parts in the newMessage.");
181
204
  }
182
205
  if (runConfig.saveInputBlobsAsArtifacts) {
183
- await this.saveArtifacts(
206
+ newMessage = await this.saveArtifacts(
184
207
  invocationContext.invocationId,
185
208
  session.userId,
186
209
  session.id,
@@ -268,7 +291,7 @@ class Runner {
268
291
  }
269
292
  /**
270
293
  * Saves artifacts from the message parts and replaces the inline data with
271
- * a file name placeholder.
294
+ * a file name placeholder and optional file reference.
272
295
  *
273
296
  * @param invocationId The current invocation ID.
274
297
  * @param userId The user ID of the session.
@@ -278,110 +301,144 @@ class Runner {
278
301
  async saveArtifacts(invocationId, userId, sessionId, message) {
279
302
  var _a2;
280
303
  if (!this.artifactService || !((_a2 = message.parts) == null ? void 0 : _a2.length)) {
281
- return;
304
+ return message;
282
305
  }
306
+ const sessionKey = {
307
+ appName: this.appName,
308
+ userId,
309
+ sessionId
310
+ };
311
+ const newParts = [];
312
+ let modified = false;
283
313
  for (let i = 0; i < message.parts.length; i++) {
284
314
  const part = message.parts[i];
285
315
  if (!part.inlineData) {
316
+ newParts.push(part);
286
317
  continue;
287
318
  }
288
- const fileName = `artifact_${invocationId}_${i}`;
289
- await this.artifactService.saveArtifact({
290
- appName: this.appName,
291
- userId,
292
- sessionId,
293
- filename: fileName,
294
- artifact: part
295
- });
296
- message.parts[i] = (0, import_genai.createPartFromText)(
297
- `Uploaded file: ${fileName}. It is saved into artifacts`
298
- );
319
+ try {
320
+ const inlineData = part.inlineData;
321
+ const fileName = inlineData.displayName || `artifact_${invocationId}_${i}`;
322
+ const version = await this.artifactService.saveArtifact({
323
+ ...sessionKey,
324
+ filename: fileName,
325
+ artifact: part
326
+ });
327
+ newParts.push((0, import_genai.createPartFromText)(`[Uploaded Artifact: "${fileName}"]`));
328
+ try {
329
+ const artifactVersion = await this.artifactService.getArtifactVersion(
330
+ {
331
+ ...sessionKey,
332
+ filename: fileName,
333
+ version
334
+ }
335
+ );
336
+ if ((artifactVersion == null ? void 0 : artifactVersion.canonicalUri) && /^(gs|https?):/i.test(artifactVersion.canonicalUri)) {
337
+ newParts.push({
338
+ fileData: {
339
+ fileUri: artifactVersion.canonicalUri,
340
+ mimeType: artifactVersion.mimeType || inlineData.mimeType || "",
341
+ displayName: fileName
342
+ }
343
+ });
344
+ }
345
+ } catch (error) {
346
+ import_logger.logger.warn(
347
+ `Failed to resolve artifact version for ${fileName}:`,
348
+ error
349
+ );
350
+ }
351
+ modified = true;
352
+ import_logger.logger.info(`Successfully saved artifact: ${fileName}`);
353
+ } catch (error) {
354
+ import_logger.logger.error(`Failed to save artifact for part ${i}:`, error);
355
+ newParts.push(part);
356
+ }
357
+ }
358
+ if (!modified) {
359
+ return message;
299
360
  }
361
+ return {
362
+ ...message,
363
+ parts: newParts
364
+ };
300
365
  }
301
366
  /**
302
367
  * Determines the next agent to run to continue the session. This is primarily
303
368
  * used for session resumption.
304
369
  */
305
- // TODO - b/425992518: This is where LRO integration should happen.
306
- // Needs clean up before we can generalize it.
370
+ /**
371
+ * Determines the next agent to run to continue the session. This is primarily
372
+ * used for session resumption across tool and LRO boundaries.
373
+ */
307
374
  determineAgentForResumption(session, rootAgent) {
308
- const event = findEventByLastFunctionResponseId(session.events);
309
- if (event && event.author) {
310
- return rootAgent.findAgent(event.author) || rootAgent;
311
- }
312
- for (let i = session.events.length - 1; i >= 0; i--) {
313
- import_logger.logger.info("event:", JSON.stringify(session.events[i]));
314
- const event2 = session.events[i];
315
- if (event2.author === "user" || !event2.author) {
316
- continue;
317
- }
318
- if (event2.author === rootAgent.name) {
319
- return rootAgent;
320
- }
321
- const agent = rootAgent.findSubAgent(event2.author);
322
- if (!agent) {
323
- import_logger.logger.warn(
324
- `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
325
- );
326
- continue;
327
- }
328
- if (this.isRoutableLlmAgent(agent)) {
329
- return agent;
330
- }
331
- }
332
- return rootAgent;
375
+ return determineAgentForResumption(
376
+ session,
377
+ rootAgent,
378
+ this.resumabilityConfig
379
+ );
333
380
  }
334
381
  /**
335
382
  * Whether the agent to run can transfer to any other agent in the agent tree.
336
383
  *
337
- * An agent is transferable if:
338
- * - It is an instance of `LlmAgent`.
339
- * - All its ancestors are also transferable (i.e., they have
340
- * `disallowTransferToParent` set to false).
341
- *
342
384
  * @param agentToRun The agent to check for transferability.
343
385
  * @returns True if the agent can transfer, False otherwise.
344
386
  */
345
387
  isRoutableLlmAgent(agentToRun) {
346
- let agent = agentToRun;
347
- while (agent) {
348
- if (!(0, import_llm_agent.isLlmAgent)(agent)) {
349
- return false;
350
- }
351
- if (agent.disallowTransferToParent) {
352
- return false;
353
- }
354
- agent = agent.parentAgent;
355
- }
356
- return true;
388
+ return isRoutableLlmAgent(agentToRun);
357
389
  }
358
390
  // TODO - b/425992518: Implement runLive and related methods.
359
391
  }
360
- function findEventByLastFunctionResponseId(events) {
361
- var _a2, _b, _c, _d;
362
- if (!events.length) {
363
- return null;
364
- }
365
- const lastEvent = events[events.length - 1];
366
- const functionCallId = (_d = (_c = (_b = (_a2 = lastEvent.content) == null ? void 0 : _a2.parts) == null ? void 0 : _b.find(
367
- (part) => part.functionResponse
368
- )) == null ? void 0 : _c.functionResponse) == null ? void 0 : _d.id;
369
- if (!functionCallId) {
370
- return null;
392
+ function determineAgentForResumption(session, rootAgent, resumabilityConfig) {
393
+ const event = findEventByLastFunctionResponseId(session.events);
394
+ const isResumable = Boolean(resumabilityConfig == null ? void 0 : resumabilityConfig.isResumable);
395
+ if (event && event.author && isResumable) {
396
+ const resumedAgent = rootAgent.findAgent(event.author);
397
+ if (resumedAgent) {
398
+ return resumedAgent;
399
+ }
400
+ import_logger.logger.warn(
401
+ `Function response from an unknown agent: ${event.author}, event id: ${event.id}`
402
+ );
371
403
  }
372
- for (let i = events.length - 2; i >= 0; i--) {
373
- const event = events[i];
374
- const functionCalls = (0, import_event.getFunctionCalls)(event);
375
- if (!functionCalls) {
404
+ for (let i = session.events.length - 1; i >= 0; i--) {
405
+ import_logger.logger.debug("event:", JSON.stringify(session.events[i]));
406
+ const event2 = session.events[i];
407
+ if (event2.author === "user" || !event2.author) {
376
408
  continue;
377
409
  }
378
- for (const functionCall of functionCalls) {
379
- if (functionCall.id === functionCallId) {
380
- return event;
381
- }
410
+ if (event2.author === rootAgent.name) {
411
+ return rootAgent;
412
+ }
413
+ const agent = rootAgent.findSubAgent(event2.author);
414
+ if (!agent) {
415
+ import_logger.logger.warn(
416
+ `Event from an unknown agent: ${event2.author}, event id: ${event2.id}`
417
+ );
418
+ continue;
419
+ }
420
+ if (isRoutableLlmAgent(agent)) {
421
+ return agent;
382
422
  }
383
423
  }
384
- return null;
424
+ return rootAgent;
425
+ }
426
+ function isRoutableLlmAgent(agentToRun) {
427
+ let agent = agentToRun;
428
+ while (agent) {
429
+ if (!(0, import_llm_agent.isLlmAgent)(agent)) {
430
+ return false;
431
+ }
432
+ if (agent.disallowTransferToParent) {
433
+ return false;
434
+ }
435
+ agent = agent.parentAgent;
436
+ }
437
+ return true;
438
+ }
439
+ function findEventByLastFunctionResponseId(events) {
440
+ var _a2;
441
+ return (_a2 = (0, import_functions.findMatchingFunctionCall)(events)) != null ? _a2 : null;
385
442
  }
386
443
  function getAllToolsets(agent) {
387
444
  const toolsets = [];
@@ -406,5 +463,8 @@ function getAllToolsets(agent) {
406
463
  // Annotate the CommonJS export names for ESM import in node:
407
464
  0 && (module.exports = {
408
465
  Runner,
466
+ determineAgentForResumption,
467
+ findEventByLastFunctionResponseId,
468
+ isRoutableLlmAgent,
409
469
  isRunner
410
470
  });
@@ -70,7 +70,12 @@ class BaseSessionService {
70
70
  }
71
71
  event = trimTempDeltaState(event);
72
72
  this.updateSessionState({ session, event });
73
- session.events.push(event);
73
+ const index = session.events.findIndex((e) => e.id === event.id);
74
+ if (index >= 0) {
75
+ session.events[index] = event;
76
+ } else {
77
+ session.events.push(event);
78
+ }
74
79
  return event;
75
80
  }
76
81
  /**
@@ -382,16 +382,28 @@ class DatabaseSessionService extends import_base_session_service.BaseSessionServ
382
382
  storageSession.state = { ...storageSession.state, ...sessionDelta };
383
383
  }
384
384
  }
385
- const newStorageEvent = txEm.create(import_schema.StorageEvent, {
385
+ const existingStorageEvent = await txEm.findOne(import_schema.StorageEvent, {
386
386
  id: trimmedEvent.id,
387
387
  appName: session.appName,
388
388
  userId: session.userId,
389
- sessionId: session.id,
390
- invocationId: trimmedEvent.invocationId,
391
- timestamp: new Date(trimmedEvent.timestamp),
392
- eventData: trimmedEvent
389
+ sessionId: session.id
393
390
  });
394
- txEm.persist(newStorageEvent);
391
+ if (existingStorageEvent) {
392
+ existingStorageEvent.eventData = trimmedEvent;
393
+ existingStorageEvent.timestamp = new Date(trimmedEvent.timestamp);
394
+ txEm.persist(existingStorageEvent);
395
+ } else {
396
+ const newStorageEvent = txEm.create(import_schema.StorageEvent, {
397
+ id: trimmedEvent.id,
398
+ appName: session.appName,
399
+ userId: session.userId,
400
+ sessionId: session.id,
401
+ invocationId: trimmedEvent.invocationId,
402
+ timestamp: new Date(trimmedEvent.timestamp),
403
+ eventData: trimmedEvent
404
+ });
405
+ txEm.persist(newStorageEvent);
406
+ }
395
407
  await txEm.commit();
396
408
  storageSession.updateTime = new Date(event.timestamp);
397
409
  const newMergedState = (0, import_base_session_service.mergeStates)(
@@ -400,7 +412,12 @@ class DatabaseSessionService extends import_base_session_service.BaseSessionServ
400
412
  storageSession.state
401
413
  );
402
414
  session.state = newMergedState;
403
- session.events.push(event);
415
+ const index = session.events.findIndex((e) => e.id === event.id);
416
+ if (index >= 0) {
417
+ session.events[index] = event;
418
+ } else {
419
+ session.events.push(event);
420
+ }
404
421
  session.lastUpdateTime = storageSession.updateTime.getTime();
405
422
  });
406
423
  return event;
@@ -33,7 +33,8 @@ var __decorateClass = (decorators, target, key, kind) => {
33
33
  var vertex_ai_session_service_exports = {};
34
34
  __export(vertex_ai_session_service_exports, {
35
35
  VertexAiSessionService: () => VertexAiSessionService,
36
- isVertexAiConnectionString: () => isVertexAiConnectionString
36
+ isVertexAiConnectionString: () => isVertexAiConnectionString,
37
+ quoteFilterLiteral: () => quoteFilterLiteral
37
38
  });
38
39
  module.exports = __toCommonJS(vertex_ai_session_service_exports);
39
40
  var import_client = require("@google-cloud/vertexai/build/src/genai/client.js");
@@ -55,6 +56,10 @@ const HTTP_NOT_FOUND = 404;
55
56
  function isVertexAiConnectionString(uri) {
56
57
  return (uri == null ? void 0 : uri.startsWith("vertexai://")) || false;
57
58
  }
59
+ function quoteFilterLiteral(value) {
60
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
61
+ return `"${escaped}"`;
62
+ }
58
63
  let VertexAiSessionService = class extends import_base_session_service.BaseSessionService {
59
64
  constructor(options) {
60
65
  super();
@@ -222,7 +227,7 @@ let VertexAiSessionService = class extends import_base_session_service.BaseSessi
222
227
  const response = await this.sessions.listInternal({
223
228
  name: `reasoningEngines/${reasoningEngineId}`,
224
229
  config: {
225
- ...userId ? { filter: `user_id="${userId}"` } : {},
230
+ ...userId ? { filter: `user_id=${quoteFilterLiteral(userId)}` } : {},
226
231
  ...pageToken ? { pageToken } : {}
227
232
  }
228
233
  });
@@ -283,10 +288,19 @@ let VertexAiSessionService = class extends import_base_session_service.BaseSessi
283
288
  }
284
289
  async deleteSession({
285
290
  appName,
286
- userId: _userId,
291
+ userId,
287
292
  sessionId
288
293
  }) {
289
294
  const reasoningEngineId = this.getReasoningEngineId(appName);
295
+ const session = await this.getSession({
296
+ appName,
297
+ userId,
298
+ sessionId,
299
+ config: { numRecentEvents: 0 }
300
+ });
301
+ if (!session) {
302
+ return;
303
+ }
290
304
  await this.sessions.delete({
291
305
  name: `reasoningEngines/${reasoningEngineId}/sessions/${sessionId}`
292
306
  });
@@ -425,5 +439,6 @@ function _fromApiEvent(apiEventObj) {
425
439
  // Annotate the CommonJS export names for ESM import in node:
426
440
  0 && (module.exports = {
427
441
  VertexAiSessionService,
428
- isVertexAiConnectionString
442
+ isVertexAiConnectionString,
443
+ quoteFilterLiteral
429
444
  });
@@ -123,12 +123,12 @@ function parseSkillMdContent(content) {
123
123
  if (!content.startsWith("---")) {
124
124
  throw new Error("SKILL.md must start with YAML frontmatter (---)");
125
125
  }
126
- const parts = content.split("---", 3);
126
+ const parts = content.split("---");
127
127
  if (parts.length < 3) {
128
128
  throw new Error("SKILL.md frontmatter not properly closed with ---");
129
129
  }
130
130
  const frontmatterStr = parts[1];
131
- const body = parts[2].trim();
131
+ const body = parts.filter((_, i) => i >= 2).join("---").trim();
132
132
  try {
133
133
  const parsed = import_js_yaml.default.load(frontmatterStr);
134
134
  if (typeof parsed !== "object" || parsed === null) {
@@ -53,7 +53,7 @@ class BaseToolset {
53
53
  * @return Whether the tool should be exposed to LLM.
54
54
  */
55
55
  isToolSelected(tool, context) {
56
- if (!this.toolFilter) {
56
+ if (!this.toolFilter || Array.isArray(this.toolFilter) && this.toolFilter.length === 0) {
57
57
  return true;
58
58
  }
59
59
  if (typeof this.toolFilter === "function") {