@google/adk 1.2.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 (294) hide show
  1. package/dist/cjs/agents/active_streaming_tool.js +6 -1
  2. package/dist/cjs/agents/base_agent.js +19 -1
  3. package/dist/cjs/agents/context.js +1 -11
  4. package/dist/cjs/agents/functions.js +35 -16
  5. package/dist/cjs/agents/instructions.js +99 -33
  6. package/dist/cjs/agents/invocation_context.js +2 -6
  7. package/dist/cjs/agents/llm_agent.js +60 -11
  8. package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +7 -0
  9. package/dist/cjs/agents/processors/basic_llm_request_processor.js +8 -1
  10. package/dist/cjs/agents/processors/code_execution_request_processor.js +0 -3
  11. package/dist/cjs/agents/processors/content_processor_utils.js +51 -25
  12. package/dist/cjs/agents/processors/content_request_processor.js +7 -0
  13. package/dist/cjs/agents/processors/context_compactor_request_processor.js +16 -2
  14. package/dist/cjs/agents/processors/identity_llm_request_processor.js +7 -0
  15. package/dist/cjs/agents/processors/instructions_llm_request_processor.js +5 -0
  16. package/dist/cjs/agents/processors/interactions_request_processor.js +63 -0
  17. package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +9 -1
  18. package/dist/cjs/agents/processors/tool_filter_request_processor.js +7 -1
  19. package/dist/cjs/apps/app.js +79 -0
  20. package/dist/cjs/apps/resumability_config.js +44 -0
  21. package/dist/cjs/artifacts/file_artifact_service.js +14 -1
  22. package/dist/cjs/artifacts/gcs_artifact_service.js +57 -15
  23. package/dist/cjs/artifacts/in_memory_artifact_service.js +5 -1
  24. package/dist/cjs/artifacts/scoped_artifact_service.js +101 -0
  25. package/dist/cjs/artifacts/session_artifact_service.js +27 -0
  26. package/dist/cjs/auth/auth_preprocessor.js +12 -10
  27. package/dist/cjs/auth/oauth2/oauth2_discovery.js +17 -5
  28. package/dist/cjs/auth/oauth2/oauth2_utils.js +12 -1
  29. package/dist/cjs/code_executors/code_executor_context.js +7 -7
  30. package/dist/cjs/common.js +86 -0
  31. package/dist/cjs/context/agent_controlled_context_compactor.js +109 -0
  32. package/dist/cjs/context/summarizers/llm_summarizer.js +11 -0
  33. package/dist/cjs/context/token_based_context_compactor.js +43 -11
  34. package/dist/cjs/context/trajectory_thought_pruning_compactor.js +71 -0
  35. package/dist/cjs/events/event.js +25 -1
  36. package/dist/cjs/integrations/agent_registry/agent_registry_mcp_toolset.js +21 -2
  37. package/dist/cjs/models/gemini_llm_connection.js +62 -19
  38. package/dist/cjs/models/google_llm.js +51 -18
  39. package/dist/cjs/models/interactions_utils.js +732 -0
  40. package/dist/cjs/plugins/base_plugin.js +1 -0
  41. package/dist/cjs/plugins/security_plugin.js +16 -0
  42. package/dist/cjs/runner/in_memory_runner.js +13 -2
  43. package/dist/cjs/runner/runner.js +93 -72
  44. package/dist/cjs/sessions/base_session_service.js +19 -3
  45. package/dist/cjs/sessions/database_session_service.js +26 -9
  46. package/dist/cjs/sessions/db/schema.js +45 -10
  47. package/dist/cjs/sessions/in_memory_session_service.js +2 -1
  48. package/dist/cjs/sessions/vertex_ai_session_service.js +21 -5
  49. package/dist/cjs/skills/gcp_skill_registry.js +104 -0
  50. package/dist/cjs/skills/loader.js +67 -2
  51. package/dist/cjs/skills/skill_registry.js +27 -0
  52. package/dist/cjs/tools/base_toolset.js +1 -1
  53. package/dist/cjs/tools/consolidate_context_tool.js +79 -0
  54. package/dist/cjs/tools/forwarding_artifact_service.js +16 -28
  55. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.js +232 -0
  56. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/operation_parser.js +224 -0
  57. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +117 -0
  58. package/dist/cjs/tools/openapi_tool/openapi_toolset.js +133 -0
  59. package/dist/cjs/tools/openapi_tool/rest_api_tool.js +256 -0
  60. package/dist/cjs/tools/skill/load_skill_resource_tool.js +25 -3
  61. package/dist/cjs/tools/skill/load_skill_tool.js +12 -1
  62. package/dist/cjs/tools/skill/run_skill_script_tool.js +12 -1
  63. package/dist/cjs/tools/skill/search_skills_tool.js +108 -0
  64. package/dist/cjs/tools/skill/skill_toolset.js +40 -5
  65. package/dist/cjs/utils/async_hooks_shim.js +52 -0
  66. package/dist/cjs/utils/async_queue.js +88 -0
  67. package/dist/cjs/utils/case_utils.js +53 -0
  68. package/dist/cjs/utils/client_labels.js +41 -3
  69. package/dist/cjs/utils/env_aware_utils.js +14 -1
  70. package/dist/cjs/utils/live_connection_utils.js +284 -0
  71. package/dist/cjs/utils/model_name.js +9 -0
  72. package/dist/cjs/utils/streaming_utils.js +18 -11
  73. package/dist/cjs/utils/task.js +62 -0
  74. package/dist/cjs/version.js +1 -1
  75. package/dist/esm/agents/active_streaming_tool.js +6 -1
  76. package/dist/esm/agents/base_agent.js +19 -1
  77. package/dist/esm/agents/context.js +1 -11
  78. package/dist/esm/agents/functions.js +36 -15
  79. package/dist/esm/agents/instructions.js +99 -33
  80. package/dist/esm/agents/invocation_context.js +2 -6
  81. package/dist/esm/agents/llm_agent.js +61 -11
  82. package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +7 -0
  83. package/dist/esm/agents/processors/basic_llm_request_processor.js +8 -1
  84. package/dist/esm/agents/processors/code_execution_request_processor.js +0 -3
  85. package/dist/esm/agents/processors/content_processor_utils.js +48 -24
  86. package/dist/esm/agents/processors/content_request_processor.js +7 -0
  87. package/dist/esm/agents/processors/context_compactor_request_processor.js +16 -2
  88. package/dist/esm/agents/processors/identity_llm_request_processor.js +7 -0
  89. package/dist/esm/agents/processors/instructions_llm_request_processor.js +5 -0
  90. package/dist/esm/agents/processors/interactions_request_processor.js +34 -0
  91. package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +9 -1
  92. package/dist/esm/agents/processors/tool_filter_request_processor.js +7 -1
  93. package/dist/esm/apps/app.js +49 -0
  94. package/dist/esm/apps/resumability_config.js +16 -0
  95. package/dist/esm/artifacts/file_artifact_service.js +14 -1
  96. package/dist/esm/artifacts/gcs_artifact_service.js +57 -15
  97. package/dist/esm/artifacts/in_memory_artifact_service.js +5 -1
  98. package/dist/esm/artifacts/scoped_artifact_service.js +73 -0
  99. package/dist/esm/artifacts/session_artifact_service.js +7 -0
  100. package/dist/esm/auth/auth_preprocessor.js +12 -10
  101. package/dist/esm/auth/oauth2/oauth2_discovery.js +14 -4
  102. package/dist/esm/auth/oauth2/oauth2_utils.js +12 -1
  103. package/dist/esm/code_executors/code_executor_context.js +7 -7
  104. package/dist/esm/common.js +75 -3
  105. package/dist/esm/context/agent_controlled_context_compactor.js +81 -0
  106. package/dist/esm/context/summarizers/llm_summarizer.js +11 -0
  107. package/dist/esm/context/token_based_context_compactor.js +43 -11
  108. package/dist/esm/context/trajectory_thought_pruning_compactor.js +43 -0
  109. package/dist/esm/events/event.js +23 -1
  110. package/dist/esm/integrations/agent_registry/agent_registry_mcp_toolset.js +21 -2
  111. package/dist/esm/models/gemini_llm_connection.js +62 -19
  112. package/dist/esm/models/google_llm.js +49 -17
  113. package/dist/esm/models/interactions_utils.js +697 -0
  114. package/dist/esm/plugins/base_plugin.js +1 -0
  115. package/dist/esm/plugins/security_plugin.js +16 -0
  116. package/dist/esm/runner/in_memory_runner.js +13 -2
  117. package/dist/esm/runner/runner.js +91 -73
  118. package/dist/esm/sessions/base_session_service.js +17 -2
  119. package/dist/esm/sessions/database_session_service.js +26 -9
  120. package/dist/esm/sessions/db/schema.js +44 -10
  121. package/dist/esm/sessions/in_memory_session_service.js +4 -2
  122. package/dist/esm/sessions/vertex_ai_session_service.js +21 -5
  123. package/dist/esm/skills/gcp_skill_registry.js +78 -0
  124. package/dist/esm/skills/loader.js +66 -2
  125. package/dist/esm/skills/skill_registry.js +7 -0
  126. package/dist/esm/tools/base_toolset.js +1 -1
  127. package/dist/esm/tools/consolidate_context_tool.js +51 -0
  128. package/dist/esm/tools/forwarding_artifact_service.js +16 -28
  129. package/dist/esm/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.js +206 -0
  130. package/dist/esm/tools/openapi_tool/openapi_spec_parser/operation_parser.js +198 -0
  131. package/dist/esm/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +91 -0
  132. package/dist/esm/tools/openapi_tool/openapi_toolset.js +97 -0
  133. package/dist/esm/tools/openapi_tool/rest_api_tool.js +229 -0
  134. package/dist/esm/tools/skill/load_skill_resource_tool.js +25 -3
  135. package/dist/esm/tools/skill/load_skill_tool.js +12 -1
  136. package/dist/esm/tools/skill/run_skill_script_tool.js +12 -1
  137. package/dist/esm/tools/skill/search_skills_tool.js +82 -0
  138. package/dist/esm/tools/skill/skill_toolset.js +40 -5
  139. package/dist/esm/utils/async_hooks_shim.js +24 -0
  140. package/dist/esm/utils/async_queue.js +60 -0
  141. package/dist/esm/utils/case_utils.js +25 -0
  142. package/dist/esm/utils/client_labels.js +38 -2
  143. package/dist/esm/utils/env_aware_utils.js +14 -1
  144. package/dist/esm/utils/live_connection_utils.js +256 -0
  145. package/dist/esm/utils/model_name.js +8 -0
  146. package/dist/esm/utils/streaming_utils.js +18 -11
  147. package/dist/esm/utils/task.js +34 -0
  148. package/dist/esm/version.js +1 -1
  149. package/dist/types/a2a/a2a_remote_agent_utils.d.ts +29 -4
  150. package/dist/types/a2a/event_converter_utils.d.ts +14 -1
  151. package/dist/types/a2a/metadata_converter_utils.d.ts +18 -0
  152. package/dist/types/a2a/part_converter_utils.d.ts +51 -6
  153. package/dist/types/agents/active_streaming_tool.d.ts +3 -4
  154. package/dist/types/agents/functions.d.ts +12 -9
  155. package/dist/types/agents/invocation_context.d.ts +7 -12
  156. package/dist/types/agents/llm_agent.d.ts +14 -0
  157. package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +14 -0
  158. package/dist/types/agents/processors/basic_llm_request_processor.d.ts +7 -0
  159. package/dist/types/agents/processors/content_processor_utils.d.ts +34 -0
  160. package/dist/types/agents/processors/content_request_processor.d.ts +16 -0
  161. package/dist/types/agents/processors/context_compactor_request_processor.d.ts +12 -0
  162. package/dist/types/agents/processors/identity_llm_request_processor.d.ts +7 -0
  163. package/dist/types/agents/processors/interactions_request_processor.d.ts +17 -0
  164. package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +9 -1
  165. package/dist/types/agents/processors/tool_filter_request_processor.d.ts +12 -1
  166. package/dist/types/apps/app.d.ts +52 -0
  167. package/dist/types/apps/resumability_config.d.ts +27 -0
  168. package/dist/types/artifacts/base_artifact_service.d.ts +6 -36
  169. package/dist/types/artifacts/gcs_artifact_service.d.ts +2 -1
  170. package/dist/types/artifacts/scoped_artifact_service.d.ts +25 -0
  171. package/dist/types/artifacts/session_artifact_service.d.ts +25 -0
  172. package/dist/types/auth/oauth2/oauth2_discovery.d.ts +11 -0
  173. package/dist/types/common.d.ts +35 -4
  174. package/dist/types/context/agent_controlled_context_compactor.d.ts +24 -0
  175. package/dist/types/context/base_context_compactor.d.ts +3 -0
  176. package/dist/types/context/summarizers/llm_summarizer.d.ts +17 -0
  177. package/dist/types/context/token_based_context_compactor.d.ts +6 -1
  178. package/dist/types/context/trajectory_thought_pruning_compactor.d.ts +27 -0
  179. package/dist/types/events/event.d.ts +8 -0
  180. package/dist/types/events/event_actions.d.ts +1 -2
  181. package/dist/types/integrations/agent_registry/agent_registry_mcp_toolset.d.ts +21 -2
  182. package/dist/types/models/base_llm_connection.d.ts +10 -0
  183. package/dist/types/models/gemini_llm_connection.d.ts +15 -4
  184. package/dist/types/models/google_llm.d.ts +15 -1
  185. package/dist/types/models/interactions_utils.d.ts +92 -0
  186. package/dist/types/models/llm_request.d.ts +4 -0
  187. package/dist/types/models/llm_response.d.ts +14 -1
  188. package/dist/types/plugins/base_plugin.d.ts +2 -1
  189. package/dist/types/plugins/security_plugin.d.ts +30 -0
  190. package/dist/types/runner/in_memory_runner.d.ts +7 -1
  191. package/dist/types/runner/runner.d.ts +43 -9
  192. package/dist/types/sessions/base_session_service.d.ts +7 -16
  193. package/dist/types/sessions/db/schema.d.ts +1 -0
  194. package/dist/types/sessions/session.d.ts +11 -0
  195. package/dist/types/sessions/vertex_ai_session_service.d.ts +9 -1
  196. package/dist/types/skills/gcp_skill_registry.d.ts +24 -0
  197. package/dist/types/skills/loader.d.ts +7 -0
  198. package/dist/types/skills/skill.d.ts +1 -1
  199. package/dist/types/skills/skill_registry.d.ts +29 -0
  200. package/dist/types/tools/consolidate_context_tool.d.ts +19 -0
  201. package/dist/types/tools/forwarding_artifact_service.d.ts +3 -2
  202. package/dist/types/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.d.ts +34 -0
  203. package/dist/types/tools/openapi_tool/openapi_spec_parser/operation_parser.d.ts +59 -0
  204. package/dist/types/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.d.ts +23 -0
  205. package/dist/types/tools/openapi_tool/openapi_toolset.d.ts +27 -0
  206. package/dist/types/tools/openapi_tool/rest_api_tool.d.ts +50 -0
  207. package/dist/types/tools/skill/load_skill_resource_tool.d.ts +1 -1
  208. package/dist/types/tools/skill/search_skills_tool.d.ts +14 -0
  209. package/dist/types/tools/skill/skill_toolset.d.ts +5 -0
  210. package/dist/types/utils/async_hooks_shim.d.ts +10 -0
  211. package/dist/types/utils/async_queue.d.ts +18 -0
  212. package/dist/types/utils/case_utils.d.ts +12 -0
  213. package/dist/types/utils/client_labels.d.ts +10 -0
  214. package/dist/types/utils/env_aware_utils.d.ts +3 -3
  215. package/dist/types/utils/live_connection_utils.d.ts +30 -0
  216. package/dist/types/utils/model_name.d.ts +7 -0
  217. package/dist/types/utils/streaming_utils.d.ts +0 -1
  218. package/dist/types/utils/task.d.ts +24 -0
  219. package/dist/types/version.d.ts +1 -1
  220. package/dist/web/agents/active_streaming_tool.js +6 -1
  221. package/dist/web/agents/base_agent.js +31 -1
  222. package/dist/web/agents/context.js +1 -11
  223. package/dist/web/agents/functions.js +36 -15
  224. package/dist/web/agents/instructions.js +99 -33
  225. package/dist/web/agents/invocation_context.js +2 -6
  226. package/dist/web/agents/llm_agent.js +61 -11
  227. package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +7 -0
  228. package/dist/web/agents/processors/basic_llm_request_processor.js +8 -1
  229. package/dist/web/agents/processors/code_execution_request_processor.js +0 -3
  230. package/dist/web/agents/processors/content_processor_utils.js +66 -24
  231. package/dist/web/agents/processors/content_request_processor.js +7 -0
  232. package/dist/web/agents/processors/context_compactor_request_processor.js +16 -2
  233. package/dist/web/agents/processors/identity_llm_request_processor.js +7 -0
  234. package/dist/web/agents/processors/instructions_llm_request_processor.js +5 -0
  235. package/dist/web/agents/processors/interactions_request_processor.js +52 -0
  236. package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +9 -1
  237. package/dist/web/agents/processors/tool_filter_request_processor.js +7 -1
  238. package/dist/web/apps/app.js +49 -0
  239. package/dist/web/apps/resumability_config.js +31 -0
  240. package/dist/web/artifacts/file_artifact_service.js +14 -1
  241. package/dist/web/artifacts/gcs_artifact_service.js +55 -15
  242. package/dist/web/artifacts/in_memory_artifact_service.js +5 -1
  243. package/dist/web/artifacts/scoped_artifact_service.js +86 -0
  244. package/dist/web/artifacts/session_artifact_service.js +7 -0
  245. package/dist/web/auth/auth_preprocessor.js +12 -10
  246. package/dist/web/auth/oauth2/oauth2_discovery.js +14 -4
  247. package/dist/web/auth/oauth2/oauth2_utils.js +12 -1
  248. package/dist/web/code_executors/code_executor_context.js +7 -7
  249. package/dist/web/common.js +75 -3
  250. package/dist/web/context/agent_controlled_context_compactor.js +81 -0
  251. package/dist/web/context/summarizers/llm_summarizer.js +11 -0
  252. package/dist/web/context/token_based_context_compactor.js +43 -11
  253. package/dist/web/context/trajectory_thought_pruning_compactor.js +43 -0
  254. package/dist/web/events/event.js +21 -1
  255. package/dist/web/integrations/agent_registry/agent_registry_mcp_toolset.js +21 -2
  256. package/dist/web/models/gemini_llm_connection.js +75 -19
  257. package/dist/web/models/google_llm.js +80 -17
  258. package/dist/web/models/interactions_utils.js +728 -0
  259. package/dist/web/plugins/base_plugin.js +1 -0
  260. package/dist/web/plugins/security_plugin.js +16 -0
  261. package/dist/web/runner/in_memory_runner.js +13 -2
  262. package/dist/web/runner/runner.js +111 -75
  263. package/dist/web/sessions/base_session_service.js +17 -2
  264. package/dist/web/sessions/database_session_service.js +26 -9
  265. package/dist/web/sessions/db/schema.js +44 -10
  266. package/dist/web/sessions/in_memory_session_service.js +4 -2
  267. package/dist/web/sessions/vertex_ai_session_service.js +21 -5
  268. package/dist/web/skills/gcp_skill_registry.js +78 -0
  269. package/dist/web/skills/loader.js +66 -2
  270. package/dist/web/skills/skill_registry.js +7 -0
  271. package/dist/web/tools/base_toolset.js +1 -1
  272. package/dist/web/tools/consolidate_context_tool.js +51 -0
  273. package/dist/web/tools/forwarding_artifact_service.js +16 -28
  274. package/dist/web/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.js +221 -0
  275. package/dist/web/tools/openapi_tool/openapi_spec_parser/operation_parser.js +198 -0
  276. package/dist/web/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +91 -0
  277. package/dist/web/tools/openapi_tool/openapi_toolset.js +97 -0
  278. package/dist/web/tools/openapi_tool/rest_api_tool.js +229 -0
  279. package/dist/web/tools/skill/load_skill_resource_tool.js +25 -3
  280. package/dist/web/tools/skill/load_skill_tool.js +12 -1
  281. package/dist/web/tools/skill/run_skill_script_tool.js +12 -1
  282. package/dist/web/tools/skill/search_skills_tool.js +82 -0
  283. package/dist/web/tools/skill/skill_toolset.js +40 -5
  284. package/dist/web/utils/async_hooks_shim.js +24 -0
  285. package/dist/web/utils/async_queue.js +60 -0
  286. package/dist/web/utils/case_utils.js +25 -0
  287. package/dist/web/utils/client_labels.js +38 -2
  288. package/dist/web/utils/env_aware_utils.js +14 -1
  289. package/dist/web/utils/live_connection_utils.js +254 -0
  290. package/dist/web/utils/model_name.js +8 -0
  291. package/dist/web/utils/streaming_utils.js +18 -11
  292. package/dist/web/utils/task.js +34 -0
  293. package/dist/web/version.js +1 -1
  294. package/package.json +4 -2
@@ -6,50 +6,116 @@ const require = topLevelCreateRequire(import.meta.url);
6
6
  * SPDX-License-Identifier: Apache-2.0
7
7
  */
8
8
  import { State } from "../sessions/state.js";
9
- async function injectSessionState(template, readonlyContext) {
9
+ const ARTIFACT_PREFIX = "artifact.";
10
+ async function resolveKey(key, isOptional, rawMatch, readonlyContext) {
10
11
  const invocationContext = readonlyContext.invocationContext;
11
- async function replaceMatchedKeyWithItsValue(match) {
12
- let key = match[0].replace(/^\{+/, "").replace(/\}+$/, "").trim();
13
- const isOptional = key.endsWith("?");
14
- if (isOptional) {
15
- key = key.slice(0, -1);
12
+ if (key.startsWith(ARTIFACT_PREFIX)) {
13
+ const fileName = key.substring(ARTIFACT_PREFIX.length);
14
+ if (invocationContext.artifactService === void 0) {
15
+ throw new Error("Artifact service is not initialized.");
16
16
  }
17
- if (key.startsWith("artifact.")) {
18
- const fileName = key.substring("artifact.".length);
19
- if (invocationContext.artifactService === void 0) {
20
- throw new Error("Artifact service is not initialized.");
17
+ const artifact = await invocationContext.artifactService.loadArtifact({
18
+ filename: fileName
19
+ });
20
+ if (!artifact) {
21
+ if (isOptional) {
22
+ return "";
21
23
  }
22
- const artifact = await invocationContext.artifactService.loadArtifact({
23
- appName: invocationContext.session.appName,
24
- userId: invocationContext.session.userId,
25
- sessionId: invocationContext.session.id,
26
- filename: fileName
27
- });
28
- if (!artifact) {
29
- throw new Error("Artifact ".concat(fileName, " not found."));
30
- }
31
- return String(artifact);
24
+ throw new Error("Artifact ".concat(fileName, " not found."));
32
25
  }
33
- if (!isValidStateName(key)) {
34
- return match[0];
26
+ return formatValue(artifact, true);
27
+ }
28
+ if (!isValidStateName(key)) {
29
+ return rawMatch;
30
+ }
31
+ if (key in invocationContext.session.state) {
32
+ return formatValue(invocationContext.session.state[key], false);
33
+ }
34
+ if (isOptional) {
35
+ return "";
36
+ }
37
+ throw new Error("Context variable not found: `".concat(key, "`."));
38
+ }
39
+ function formatValue(value, isArtifact = false) {
40
+ if (typeof value === "string") {
41
+ return value;
42
+ }
43
+ if (typeof value === "object" && value !== null) {
44
+ if (isArtifact && "text" in value && typeof value.text === "string") {
45
+ return value.text;
35
46
  }
36
- if (key in invocationContext.session.state) {
37
- return String(invocationContext.session.state[key]);
47
+ try {
48
+ const json = JSON.stringify(value);
49
+ if (json !== void 0) {
50
+ return json;
51
+ }
52
+ } catch (e) {
53
+ throw new Error(
54
+ "Failed to serialize value for instruction template: ".concat(e instanceof Error ? e.message : String(e))
55
+ );
38
56
  }
57
+ }
58
+ return String(value);
59
+ }
60
+ async function injectSessionState(template, readonlyContext) {
61
+ const pattern = /\{+[^{}]*}+/g;
62
+ const matches = Array.from(template.matchAll(pattern));
63
+ if (matches.length === 0) {
64
+ return template;
65
+ }
66
+ const parsedMatches = matches.map((match) => {
67
+ const raw = match[0];
68
+ let key = raw.replace(/^\{+/, "").replace(/\}+$/, "").trim();
69
+ const isOptional = key.endsWith("?");
39
70
  if (isOptional) {
40
- return "";
71
+ key = key.slice(0, -1);
72
+ }
73
+ const isValid = key.startsWith(ARTIFACT_PREFIX) || isValidStateName(key);
74
+ return {
75
+ raw,
76
+ key,
77
+ isOptional,
78
+ isValid,
79
+ index: match.index
80
+ };
81
+ });
82
+ const uniqueKeys = /* @__PURE__ */ new Map();
83
+ for (const pm of parsedMatches) {
84
+ if (!pm.isValid) {
85
+ continue;
86
+ }
87
+ const existing = uniqueKeys.get(pm.key);
88
+ if (existing) {
89
+ if (existing.isOptional && !pm.isOptional) {
90
+ existing.isOptional = false;
91
+ }
92
+ } else {
93
+ uniqueKeys.set(pm.key, {
94
+ key: pm.key,
95
+ isOptional: pm.isOptional,
96
+ raw: pm.raw
97
+ });
41
98
  }
42
- throw new Error("Context variable not found: `".concat(key, "`."));
43
99
  }
44
- const pattern = /\{+[^{}]*}+/g;
100
+ const resolutions = /* @__PURE__ */ new Map();
101
+ for (const info of uniqueKeys.values()) {
102
+ resolutions.set(
103
+ info.key,
104
+ resolveKey(info.key, info.isOptional, info.raw, readonlyContext)
105
+ );
106
+ }
107
+ await Promise.all(resolutions.values());
45
108
  const result = [];
46
109
  let lastEnd = 0;
47
- const matches = template.matchAll(pattern);
48
- for (const match of matches) {
49
- result.push(template.slice(lastEnd, match.index));
50
- const replacement = await replaceMatchedKeyWithItsValue(match);
51
- result.push(replacement);
52
- lastEnd = match.index + match[0].length;
110
+ for (const pm of parsedMatches) {
111
+ result.push(template.slice(lastEnd, pm.index));
112
+ if (pm.isValid) {
113
+ const replacement = await resolutions.get(pm.key);
114
+ result.push(replacement);
115
+ } else {
116
+ result.push(pm.raw);
117
+ }
118
+ lastEnd = pm.index + pm.raw.length;
53
119
  }
54
120
  result.push(template.slice(lastEnd));
55
121
  return result.join("");
@@ -30,11 +30,7 @@ class InvocationContext {
30
30
  * @param params The parameters for creating an invocation context.
31
31
  */
32
32
  constructor(params) {
33
- /**
34
- * A container to keep track of different kinds of costs incurred as a part of
35
- * this invocation.
36
- */
37
- this.invocationCostManager = new InvocationCostManager();
33
+ var _a;
38
34
  this.artifactService = params.artifactService;
39
35
  this.sessionService = params.sessionService;
40
36
  this.memoryService = params.memoryService;
@@ -46,10 +42,10 @@ class InvocationContext {
46
42
  this.endInvocation = params.endInvocation || false;
47
43
  this.transcriptionCache = params.transcriptionCache;
48
44
  this.runConfig = params.runConfig;
49
- this.liveRequestQueue = params.liveRequestQueue;
50
45
  this.activeStreamingTools = params.activeStreamingTools;
51
46
  this.pluginManager = params.pluginManager;
52
47
  this.abortSignal = params.abortSignal;
48
+ this.invocationCostManager = (_a = params.invocationCostManager) != null ? _a : new InvocationCostManager();
53
49
  }
54
50
  /**
55
51
  * The app name of the current session.
@@ -71,10 +71,12 @@ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")])
71
71
  */
72
72
  var _a, _b;
73
73
  import { context, trace } from "@opentelemetry/api";
74
+ import { FunctionTool } from "../tools/function_tool.js";
74
75
  import {
75
76
  createEvent,
76
77
  createNewEventId,
77
78
  getFunctionCalls,
79
+ getFunctionResponses,
78
80
  isFinalResponse
79
81
  } from "../events/event.js";
80
82
  import { isBaseLlm } from "../models/base_llm.js";
@@ -96,6 +98,7 @@ import {
96
98
  handleFunctionCallsAsync,
97
99
  populateClientFunctionCallId
98
100
  } from "./functions.js";
101
+ import { AUTH_PREPROCESSOR } from "../auth/auth_preprocessor.js";
99
102
  import { AGENT_TRANSFER_LLM_REQUEST_PROCESSOR } from "./processors/agent_transfer_llm_request_processor.js";
100
103
  import { BASIC_LLM_REQUEST_PROCESSOR } from "./processors/basic_llm_request_processor.js";
101
104
  import { CODE_EXECUTION_REQUEST_PROCESSOR } from "./processors/code_execution_request_processor.js";
@@ -103,6 +106,7 @@ import { CONTENT_REQUEST_PROCESSOR } from "./processors/content_request_processo
103
106
  import { ContextCompactorRequestProcessor } from "./processors/context_compactor_request_processor.js";
104
107
  import { IDENTITY_LLM_REQUEST_PROCESSOR } from "./processors/identity_llm_request_processor.js";
105
108
  import { INSTRUCTIONS_LLM_REQUEST_PROCESSOR } from "./processors/instructions_llm_request_processor.js";
109
+ import { INTERACTIONS_REQUEST_PROCESSOR } from "./processors/interactions_request_processor.js";
106
110
  import { REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR } from "./processors/request_confirmation_llm_request_processor.js";
107
111
  import { TOOL_FILTER_REQUEST_PROCESSOR } from "./processors/tool_filter_request_processor.js";
108
112
  import { ReadonlyContext } from "./readonly_context.js";
@@ -142,10 +146,12 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
142
146
  this.codeExecutor = config.codeExecutor;
143
147
  this.requestProcessors = (_g = config.requestProcessors) != null ? _g : [
144
148
  BASIC_LLM_REQUEST_PROCESSOR,
149
+ AUTH_PREPROCESSOR,
145
150
  IDENTITY_LLM_REQUEST_PROCESSOR,
146
151
  INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
147
152
  REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
148
153
  CONTENT_REQUEST_PROCESSOR,
154
+ INTERACTIONS_REQUEST_PROCESSOR,
149
155
  CODE_EXECUTION_REQUEST_PROCESSOR,
150
156
  TOOL_FILTER_REQUEST_PROCESSOR
151
157
  ];
@@ -368,9 +374,10 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
368
374
  }
369
375
  runAsyncImpl(context2) {
370
376
  return __asyncGenerator(this, null, function* () {
371
- var _a2;
377
+ var _a2, _b2;
372
378
  while (true) {
373
379
  let lastEvent = void 0;
380
+ let stepHadToolCalls = false;
374
381
  try {
375
382
  for (var iter = __forAwait(this.runOneStepAsync(context2)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
376
383
  const event = temp.value;
@@ -378,6 +385,9 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
378
385
  return;
379
386
  }
380
387
  lastEvent = event;
388
+ if (getFunctionCalls(event).length > 0 || getFunctionResponses(event).length > 0) {
389
+ stepHadToolCalls = true;
390
+ }
381
391
  this.maybeSaveOutputToState(event);
382
392
  yield event;
383
393
  }
@@ -391,7 +401,11 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
391
401
  throw error[0];
392
402
  }
393
403
  }
394
- if (!lastEvent || isFinalResponse(lastEvent)) {
404
+ if (!lastEvent) {
405
+ break;
406
+ }
407
+ const isEmptyMetadataEvent = lastEvent.author === this.name && !lastEvent.partial && (!((_b2 = lastEvent.content) == null ? void 0 : _b2.parts) || lastEvent.content.parts.length === 0);
408
+ if (isFinalResponse(lastEvent) && !(isEmptyMetadataEvent && stepHadToolCalls)) {
395
409
  break;
396
410
  }
397
411
  if (lastEvent.partial) {
@@ -431,6 +445,20 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
431
445
  // --------------------------------------------------------------------------
432
446
  // #START LlmFlow Logic
433
447
  // --------------------------------------------------------------------------
448
+ /**
449
+ * Runs the bidirectional (live) flow for this agent.
450
+ *
451
+ * Establishes a live connection to the model, drains the invocation's
452
+ * `liveRequestQueue` into the connection on a parallel task, and yields
453
+ * events derived from server messages until the queue closes, the model
454
+ * finishes, or an agent transfer occurs.
455
+ *
456
+ * If the live connection drops (network failure, server `goAway`) and a
457
+ * session resumption handle has been observed, the flow transparently
458
+ * reconnects using that handle up to {@link MAX_LIVE_RECONNECT_ATTEMPTS}
459
+ * times. Subsequent reconnects skip `sendHistory` because the server
460
+ * already holds the conversation state associated with the handle.
461
+ */
434
462
  // eslint-disable-next-line require-yield
435
463
  runLiveFlow(_invocationContext) {
436
464
  return __asyncGenerator(this, null, function* () {
@@ -469,13 +497,28 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
469
497
  }
470
498
  }
471
499
  }
472
- for (const toolUnion of this.tools) {
500
+ const allTools = [...this.tools];
501
+ if (this.outputSchema && allTools.length > 0) {
502
+ const setModelResponseTool = new FunctionTool({
503
+ name: "set_model_response",
504
+ description: "Call this tool to submit your final response conforming to the output schema. Use this tool only when you have collected all the information and are ready to return the final answer.",
505
+ parameters: this.outputSchema,
506
+ execute: async (args, toolContext) => {
507
+ if (toolContext) {
508
+ toolContext.actions.skipSummarization = true;
509
+ }
510
+ return JSON.stringify(args);
511
+ }
512
+ });
513
+ allTools.push(setModelResponseTool);
514
+ }
515
+ for (const toolUnion of allTools) {
473
516
  const toolContext = new Context({ invocationContext });
474
517
  const tools = (yield new __await(convertToolUnionToTools(
475
518
  toolUnion,
476
519
  new ReadonlyContext(invocationContext)
477
520
  ))).filter((tool) => {
478
- return !llmRequest.allowedTools || llmRequest.allowedTools.includes(tool.name);
521
+ return !llmRequest.allowedTools || llmRequest.allowedTools.includes(tool.name) || tool.name === "set_model_response";
479
522
  });
480
523
  for (const tool of tools) {
481
524
  yield new __await(tool.processLlmRequest({ toolContext, llmRequest }));
@@ -564,7 +607,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
564
607
  }
565
608
  postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
566
609
  return __asyncGenerator(this, null, function* () {
567
- var _a2, _b2, _c, _d, _e;
610
+ var _a2, _b2, _c, _d, _e, _f;
568
611
  for (const processor of this.responseProcessors) {
569
612
  try {
570
613
  for (var iter = __forAwait(processor.runAsync(
@@ -588,13 +631,20 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
588
631
  }
589
632
  }
590
633
  }
591
- if (!llmResponse.content && !llmResponse.errorCode && !llmResponse.interrupted) {
634
+ if ((!llmResponse.content || ((_b2 = llmResponse.content.parts) == null ? void 0 : _b2.length) === 0) && !llmResponse.errorCode && !llmResponse.interrupted) {
592
635
  return;
593
636
  }
594
637
  const mergedEvent = createEvent(__spreadValues(__spreadValues({}, modelResponseEvent), llmResponse));
595
638
  if (mergedEvent.content) {
596
639
  const functionCalls = getFunctionCalls(mergedEvent);
597
- if (functionCalls == null ? void 0 : functionCalls.length) {
640
+ const setModelResponseCall = functionCalls.find(
641
+ (call) => call.name === "set_model_response"
642
+ );
643
+ if (setModelResponseCall) {
644
+ const args = setModelResponseCall.args;
645
+ mergedEvent.content.parts = [{ text: JSON.stringify(args) }];
646
+ mergedEvent.actions.skipSummarization = true;
647
+ } else if (functionCalls && functionCalls.length) {
598
648
  populateClientFunctionCallId(mergedEvent);
599
649
  mergedEvent.longRunningToolIds = Array.from(
600
650
  getLongRunningFunctionCalls(functionCalls, llmRequest.toolsDict)
@@ -602,10 +652,10 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
602
652
  }
603
653
  }
604
654
  yield mergedEvent;
605
- if (!((_b2 = getFunctionCalls(mergedEvent)) == null ? void 0 : _b2.length)) {
655
+ if (!((_c = getFunctionCalls(mergedEvent)) == null ? void 0 : _c.length)) {
606
656
  return;
607
657
  }
608
- if ((_c = invocationContext.runConfig) == null ? void 0 : _c.pauseOnToolCalls) {
658
+ if ((_d = invocationContext.runConfig) == null ? void 0 : _d.pauseOnToolCalls) {
609
659
  invocationContext.endInvocation = true;
610
660
  return;
611
661
  }
@@ -616,7 +666,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
616
666
  beforeToolCallbacks: this.canonicalBeforeToolCallbacks,
617
667
  afterToolCallbacks: this.canonicalAfterToolCallbacks
618
668
  }));
619
- if (!functionResponseEvent || ((_d = invocationContext.abortSignal) == null ? void 0 : _d.aborted)) {
669
+ if (!functionResponseEvent || ((_e = invocationContext.abortSignal) == null ? void 0 : _e.aborted)) {
620
670
  return;
621
671
  }
622
672
  const authEvent = generateAuthEvent(
@@ -643,7 +693,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
643
693
  try {
644
694
  for (var iter2 = __forAwait(nextAgent.runAsync(invocationContext)), more2, temp2, error2; more2 = !(temp2 = yield new __await(iter2.next())).done; more2 = false) {
645
695
  const event = temp2.value;
646
- if ((_e = invocationContext.abortSignal) == null ? void 0 : _e.aborted) {
696
+ if ((_f = invocationContext.abortSignal) == null ? void 0 : _f.aborted) {
647
697
  return;
648
698
  }
649
699
  yield event;
@@ -46,6 +46,13 @@ class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
46
46
  }
47
47
  });
48
48
  }
49
+ /**
50
+ * Appends transfer instructions and registers the `transfer_to_agent` tool
51
+ * when the agent has reachable transfer targets.
52
+ *
53
+ * @param invocationContext - The current invocation context.
54
+ * @param llmRequest - The request to augment with transfer instructions and the transfer tool.
55
+ */
49
56
  // eslint-disable-next-line require-yield
50
57
  runAsync(invocationContext, llmRequest) {
51
58
  return __asyncGenerator(this, null, function* () {
@@ -41,6 +41,13 @@ import { setOutputSchema } from "../../models/llm_request.js";
41
41
  import { isLlmAgent } from "../llm_agent.js";
42
42
  import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
43
43
  class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
44
+ /**
45
+ * Populates model name, generation config, output schema, and live connect
46
+ * settings on the request from the agent and run config.
47
+ *
48
+ * @param invocationContext - The current invocation context.
49
+ * @param llmRequest - The request object to populate in place.
50
+ */
44
51
  // eslint-disable-next-line require-yield
45
52
  runAsync(invocationContext, llmRequest) {
46
53
  return __asyncGenerator(this, null, function* () {
@@ -51,7 +58,7 @@ class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
51
58
  }
52
59
  llmRequest.model = agent.canonicalModel.model;
53
60
  llmRequest.config = __spreadValues({}, (_a = agent.generateContentConfig) != null ? _a : {});
54
- if (agent.outputSchema) {
61
+ if (agent.outputSchema && (!agent.tools || agent.tools.length === 0)) {
55
62
  setOutputSchema(llmRequest, agent.outputSchema);
56
63
  }
57
64
  if (invocationContext.runConfig) {
@@ -327,9 +327,6 @@ async function postProcessCodeExecutionResult(invocationContext, codeExecutorCon
327
327
  }
328
328
  for (const outputFile of codeExecutionResult.outputFiles) {
329
329
  const version = await invocationContext.artifactService.saveArtifact({
330
- appName: invocationContext.appName || "",
331
- userId: invocationContext.userId || "",
332
- sessionId: invocationContext.session.id,
333
330
  filename: outputFile.name,
334
331
  artifact: {
335
332
  inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
@@ -1,5 +1,24 @@
1
1
  import {createRequire as topLevelCreateRequire} from 'module';
2
2
  const require = topLevelCreateRequire(import.meta.url);
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __spreadValues = (a, b) => {
11
+ for (var prop in b || (b = {}))
12
+ if (__hasOwnProp.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ if (__getOwnPropSymbols)
15
+ for (var prop of __getOwnPropSymbols(b)) {
16
+ if (__propIsEnum.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ }
19
+ return a;
20
+ };
21
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3
22
  /**
4
23
  * @license
5
24
  * Copyright 2025 Google LLC
@@ -16,10 +35,21 @@ import {
16
35
  getFunctionResponses
17
36
  } from "../../events/event.js";
18
37
  import {
19
- removeClientFunctionCallId,
38
+ AF_FUNCTION_CALL_ID_PREFIX,
20
39
  REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
21
40
  REQUEST_EUC_FUNCTION_CALL_NAME
22
41
  } from "../functions.js";
42
+ function removeClientFunctionCallId(content) {
43
+ var _a, _b, _c, _d, _e;
44
+ for (const part of (_a = content == null ? void 0 : content.parts) != null ? _a : []) {
45
+ if ((_c = (_b = part.functionCall) == null ? void 0 : _b.id) == null ? void 0 : _c.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
46
+ part.functionCall.id = void 0;
47
+ }
48
+ if ((_e = (_d = part.functionResponse) == null ? void 0 : _d.id) == null ? void 0 : _e.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
49
+ part.functionResponse.id = void 0;
50
+ }
51
+ }
52
+ }
23
53
  function getContents(events, agentName, currentBranch) {
24
54
  var _a, _b, _c;
25
55
  const filteredEvents = [];
@@ -109,17 +139,19 @@ function convertForeignEvent(event) {
109
139
  text: "[".concat(event.author, "] said: ").concat(part.text)
110
140
  });
111
141
  } else if (part.functionCall) {
112
- const argsText = safeStringify(part.functionCall.args);
113
142
  (_d = content.parts) == null ? void 0 : _d.push({
114
- text: "[".concat(event.author, "] called tool `").concat(part.functionCall.name, "` with parameters: ").concat(argsText)
143
+ text: "[".concat(event.author, "] called tool `").concat(part.functionCall.name, "` with parameters: ").concat(safeStringify(
144
+ part.functionCall.args
145
+ ))
115
146
  });
116
147
  } else if (part.functionResponse) {
117
- const responseText = safeStringify(part.functionResponse.response);
118
148
  (_e = content.parts) == null ? void 0 : _e.push({
119
- text: "[".concat(event.author, "] tool `").concat(part.functionResponse.name, "` returned result: ").concat(responseText)
149
+ text: "[".concat(event.author, "] tool `").concat(part.functionResponse.name, "` returned result: ").concat(safeStringify(
150
+ part.functionResponse.response
151
+ ))
120
152
  });
121
153
  } else {
122
- (_f = content.parts) == null ? void 0 : _f.push(part);
154
+ (_f = content.parts) == null ? void 0 : _f.push(cloneDeep(part));
123
155
  }
124
156
  }
125
157
  return createEvent({
@@ -135,9 +167,11 @@ function mergeFunctionResponseEvents(events) {
135
167
  if (events.length === 0) {
136
168
  throw new Error("Cannot merge an empty list of events.");
137
169
  }
138
- const mergedEvent = createEvent(events[0]);
139
- const partsInMergedEvent = ((_a = mergedEvent.content) == null ? void 0 : _a.parts) || [];
140
- if (partsInMergedEvent.length === 0) {
170
+ const mergedEvent = createEvent(__spreadProps(__spreadValues({}, events[0]), {
171
+ content: events[0].content ? cloneDeep(events[0].content) : void 0
172
+ }));
173
+ const partsInMergedEvent = (_a = mergedEvent.content) == null ? void 0 : _a.parts;
174
+ if (!partsInMergedEvent || partsInMergedEvent.length === 0) {
141
175
  throw new Error("There should be at least one function_response part.");
142
176
  }
143
177
  const partIndicesInMergedEvent = {};
@@ -152,16 +186,17 @@ function mergeFunctionResponseEvents(events) {
152
186
  throw new Error("There should be at least one function_response part.");
153
187
  }
154
188
  for (const part of event.content.parts) {
155
- if (part.functionResponse && part.functionResponse.id) {
156
- const functionCallId = part.functionResponse.id;
189
+ const clonedPart = cloneDeep(part);
190
+ if (clonedPart.functionResponse && clonedPart.functionResponse.id) {
191
+ const functionCallId = clonedPart.functionResponse.id;
157
192
  if (functionCallId in partIndicesInMergedEvent) {
158
- partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = part;
193
+ partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = clonedPart;
159
194
  } else {
160
- partsInMergedEvent.push(part);
195
+ partsInMergedEvent.push(clonedPart);
161
196
  partIndicesInMergedEvent[functionCallId] = partsInMergedEvent.length - 1;
162
197
  }
163
198
  } else {
164
- partsInMergedEvent.push(part);
199
+ partsInMergedEvent.push(clonedPart);
165
200
  }
166
201
  }
167
202
  }
@@ -176,7 +211,7 @@ function rearrangeEventsForLatestFunctionResponse(events) {
176
211
  if (!(functionResponses == null ? void 0 : functionResponses.length)) {
177
212
  return events;
178
213
  }
179
- let functionResponsesIds = new Set(
214
+ const functionResponsesIds = new Set(
180
215
  functionResponses.filter((response) => !!response.id).map((response) => response.id)
181
216
  );
182
217
  const secondLatestEvent = events.at(-2);
@@ -190,16 +225,16 @@ function rearrangeEventsForLatestFunctionResponse(events) {
190
225
  }
191
226
  }
192
227
  }
193
- let functionCallEventIdx = -1;
228
+ let match;
194
229
  for (let idx = events.length - 2; idx >= 0; idx--) {
195
230
  const event = events[idx];
196
231
  const functionCalls = getFunctionCalls(event);
197
232
  if (!(functionCalls == null ? void 0 : functionCalls.length)) {
198
233
  continue;
199
234
  }
235
+ let matchedInEvent = false;
200
236
  for (const functionCall of functionCalls) {
201
237
  if (functionCall.id && functionResponsesIds.has(functionCall.id)) {
202
- functionCallEventIdx = idx;
203
238
  const functionCallIds = new Set(
204
239
  functionCalls.map((fc) => fc.id).filter((id) => !!id)
205
240
  );
@@ -213,12 +248,16 @@ function rearrangeEventsForLatestFunctionResponse(events) {
213
248
  ), ", function response") + " ids provided: ".concat(Array.from(functionResponsesIds).join(", "))
214
249
  );
215
250
  }
216
- functionResponsesIds = functionCallIds;
251
+ match = { eventIdx: idx, responseIds: functionCallIds };
252
+ matchedInEvent = true;
217
253
  break;
218
254
  }
219
255
  }
256
+ if (matchedInEvent) {
257
+ break;
258
+ }
220
259
  }
221
- if (functionCallEventIdx === -1) {
260
+ if (!match) {
222
261
  throw new Error(
223
262
  "No function call event found for function responses ids: ".concat(Array.from(
224
263
  functionResponsesIds
@@ -226,17 +265,18 @@ function rearrangeEventsForLatestFunctionResponse(events) {
226
265
  );
227
266
  }
228
267
  const functionResponseEvents = [];
229
- for (let idx = functionCallEventIdx + 1; idx < events.length - 1; idx++) {
268
+ const activeResponses = match.responseIds;
269
+ for (let idx = match.eventIdx + 1; idx < events.length - 1; idx++) {
230
270
  const event = events[idx];
231
271
  const responses = getFunctionResponses(event);
232
272
  if (responses && responses.some(
233
- (response) => response.id && functionResponsesIds.has(response.id)
273
+ (response) => response.id && activeResponses.has(response.id)
234
274
  )) {
235
275
  functionResponseEvents.push(event);
236
276
  }
237
277
  }
238
278
  functionResponseEvents.push(events[events.length - 1]);
239
- const resultEvents = events.slice(0, functionCallEventIdx + 1);
279
+ const resultEvents = events.slice(0, match.eventIdx + 1);
240
280
  resultEvents.push(mergeFunctionResponseEvents(functionResponseEvents));
241
281
  return resultEvents;
242
282
  }
@@ -275,7 +315,7 @@ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
275
315
  continue;
276
316
  }
277
317
  if (functionResponseEventsIndices.size === 1) {
278
- const [responseIndex] = [...functionResponseEventsIndices];
318
+ const [responseIndex] = Array.from(functionResponseEventsIndices);
279
319
  resultEvents.push(events[responseIndex]);
280
320
  } else {
281
321
  const indicesArray = Array.from(functionResponseEventsIndices).sort(
@@ -314,5 +354,7 @@ function convertCompactedEvent(event) {
314
354
  }
315
355
  export {
316
356
  getContents,
317
- getCurrentTurnContents
357
+ getCurrentTurnContents,
358
+ mergeFunctionResponseEvents,
359
+ removeClientFunctionCallId
318
360
  };
@@ -28,6 +28,13 @@ import {
28
28
  getCurrentTurnContents
29
29
  } from "./content_processor_utils.js";
30
30
  class ContentRequestProcessor {
31
+ /**
32
+ * Fills {@link LlmRequest.contents} based on the session event history and
33
+ * agent configuration.
34
+ *
35
+ * @param invocationContext - The current invocation context.
36
+ * @param llmRequest - The request whose contents field will be populated.
37
+ */
31
38
  // eslint-disable-next-line require-yield
32
39
  runAsync(invocationContext, llmRequest) {
33
40
  return __asyncGenerator(this, null, function* () {
@@ -23,25 +23,39 @@ var __asyncGenerator = (__this, __arguments, generator) => {
23
23
  */
24
24
  import { ContextCompactionTrigger } from "../../plugins/base_plugin.js";
25
25
  class ContextCompactorRequestProcessor {
26
+ /**
27
+ * @param compactors - Ordered list of compactors to evaluate; the first one
28
+ * that reports it should compact will perform the compaction.
29
+ */
26
30
  constructor(compactors) {
27
31
  this.compactors = compactors;
28
32
  }
33
+ /**
34
+ * Evaluates compactors in priority order. The first compactor that indicates
35
+ * it should compact will compact the session history, fire plugin hooks, and
36
+ * yield any newly generated events. Iteration stops after one compaction.
37
+ *
38
+ * @param invocationContext - The current invocation context.
39
+ * @param _llmRequest - Unused; present to satisfy the {@link BaseLlmRequestProcessor} interface.
40
+ */
29
41
  runAsync(invocationContext, _llmRequest) {
30
42
  return __asyncGenerator(this, null, function* () {
43
+ var _a;
31
44
  for (const compactor of this.compactors) {
32
45
  const shouldCompact = yield new __await(Promise.resolve(
33
46
  compactor.shouldCompact(invocationContext)
34
47
  ));
35
48
  if (shouldCompact) {
49
+ const trigger = (_a = compactor.trigger) != null ? _a : ContextCompactionTrigger.Auto;
36
50
  yield new __await(invocationContext.pluginManager.runBeforeContextCompaction({
37
51
  invocationContext,
38
- trigger: ContextCompactionTrigger.Auto
52
+ trigger
39
53
  }));
40
54
  const oldEvents = new Set(invocationContext.session.events);
41
55
  yield new __await(Promise.resolve(compactor.compact(invocationContext)));
42
56
  yield new __await(invocationContext.pluginManager.runAfterContextCompaction({
43
57
  invocationContext,
44
- trigger: ContextCompactionTrigger.Auto
58
+ trigger
45
59
  }));
46
60
  const newEvents = invocationContext.session.events.filter(
47
61
  (e) => !oldEvents.has(e)