@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
@@ -7,7 +7,11 @@ const require = topLevelCreateRequire(import.meta.url);
7
7
  */
8
8
  import { createUserContent } from "@google/genai";
9
9
  import { isEmpty } from "lodash-es";
10
- import { createEvent, getFunctionCalls } from "../events/event.js";
10
+ import {
11
+ createEvent,
12
+ getFunctionCalls,
13
+ getFunctionResponses
14
+ } from "../events/event.js";
11
15
  import { mergeEventActions } from "../events/event_actions.js";
12
16
  import { randomUUID } from "../utils/env_aware_utils.js";
13
17
  import { logger } from "../utils/logger.js";
@@ -39,18 +43,6 @@ function populateClientFunctionCallId(modelResponseEvent) {
39
43
  }
40
44
  }
41
45
  }
42
- function removeClientFunctionCallId(content) {
43
- if (content && content.parts) {
44
- for (const part of content.parts) {
45
- if (part.functionCall && part.functionCall.id && part.functionCall.id.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
46
- part.functionCall.id = void 0;
47
- }
48
- if (part.functionResponse && part.functionResponse.id && part.functionResponse.id.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
49
- part.functionResponse.id = void 0;
50
- }
51
- }
52
- }
53
- }
54
46
  function getLongRunningFunctionCalls(functionCalls, toolsDict) {
55
47
  const longRunningToolIds = /* @__PURE__ */ new Set();
56
48
  for (const functionCall of functionCalls) {
@@ -393,9 +385,39 @@ function mergeParallelFunctionResponseEvents(functionResponseEvents) {
393
385
  timestamp: baseEvent.timestamp
394
386
  });
395
387
  }
388
+ function findEventByFunctionCallId(events, functionCallId, endIndex = events.length) {
389
+ for (let i = endIndex - 1; i >= 0; i--) {
390
+ const event = events[i];
391
+ const functionCalls = getFunctionCalls(event);
392
+ for (const functionCall of functionCalls) {
393
+ if (functionCall.id === functionCallId) {
394
+ return event;
395
+ }
396
+ }
397
+ }
398
+ return void 0;
399
+ }
400
+ function findMatchingFunctionCall(events) {
401
+ if (!events.length) {
402
+ return void 0;
403
+ }
404
+ const lastEvent = events[events.length - 1];
405
+ const functionResponses = getFunctionResponses(lastEvent);
406
+ if (!functionResponses.length || !functionResponses[0].id) {
407
+ return void 0;
408
+ }
409
+ return findEventByFunctionCallId(
410
+ events,
411
+ functionResponses[0].id,
412
+ events.length - 1
413
+ );
414
+ }
396
415
  export {
416
+ AF_FUNCTION_CALL_ID_PREFIX,
397
417
  REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
398
418
  REQUEST_EUC_FUNCTION_CALL_NAME,
419
+ findEventByFunctionCallId,
420
+ findMatchingFunctionCall,
399
421
  functionsExportedForTestingOnly,
400
422
  generateAuthEvent,
401
423
  generateClientFunctionCallId,
@@ -404,6 +426,5 @@ export {
404
426
  handleFunctionCallList,
405
427
  handleFunctionCallsAsync,
406
428
  mergeParallelFunctionResponseEvents,
407
- populateClientFunctionCallId,
408
- removeClientFunctionCallId
429
+ populateClientFunctionCallId
409
430
  };
@@ -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 ${fileName} not found.`);
30
- }
31
- return String(artifact);
24
+ throw new Error(`Artifact ${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: \`${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: ${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: \`${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.
@@ -7,10 +7,12 @@ const require = topLevelCreateRequire(import.meta.url);
7
7
  */
8
8
  var _a, _b;
9
9
  import { context, trace } from "@opentelemetry/api";
10
+ import { FunctionTool } from "../tools/function_tool.js";
10
11
  import {
11
12
  createEvent,
12
13
  createNewEventId,
13
14
  getFunctionCalls,
15
+ getFunctionResponses,
14
16
  isFinalResponse
15
17
  } from "../events/event.js";
16
18
  import { isBaseLlm } from "../models/base_llm.js";
@@ -32,6 +34,7 @@ import {
32
34
  handleFunctionCallsAsync,
33
35
  populateClientFunctionCallId
34
36
  } from "./functions.js";
37
+ import { AUTH_PREPROCESSOR } from "../auth/auth_preprocessor.js";
35
38
  import { AGENT_TRANSFER_LLM_REQUEST_PROCESSOR } from "./processors/agent_transfer_llm_request_processor.js";
36
39
  import { BASIC_LLM_REQUEST_PROCESSOR } from "./processors/basic_llm_request_processor.js";
37
40
  import { CODE_EXECUTION_REQUEST_PROCESSOR } from "./processors/code_execution_request_processor.js";
@@ -39,6 +42,7 @@ import { CONTENT_REQUEST_PROCESSOR } from "./processors/content_request_processo
39
42
  import { ContextCompactorRequestProcessor } from "./processors/context_compactor_request_processor.js";
40
43
  import { IDENTITY_LLM_REQUEST_PROCESSOR } from "./processors/identity_llm_request_processor.js";
41
44
  import { INSTRUCTIONS_LLM_REQUEST_PROCESSOR } from "./processors/instructions_llm_request_processor.js";
45
+ import { INTERACTIONS_REQUEST_PROCESSOR } from "./processors/interactions_request_processor.js";
42
46
  import { REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR } from "./processors/request_confirmation_llm_request_processor.js";
43
47
  import { TOOL_FILTER_REQUEST_PROCESSOR } from "./processors/tool_filter_request_processor.js";
44
48
  import { ReadonlyContext } from "./readonly_context.js";
@@ -78,10 +82,12 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
78
82
  this.codeExecutor = config.codeExecutor;
79
83
  this.requestProcessors = (_g = config.requestProcessors) != null ? _g : [
80
84
  BASIC_LLM_REQUEST_PROCESSOR,
85
+ AUTH_PREPROCESSOR,
81
86
  IDENTITY_LLM_REQUEST_PROCESSOR,
82
87
  INSTRUCTIONS_LLM_REQUEST_PROCESSOR,
83
88
  REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
84
89
  CONTENT_REQUEST_PROCESSOR,
90
+ INTERACTIONS_REQUEST_PROCESSOR,
85
91
  CODE_EXECUTION_REQUEST_PROCESSOR,
86
92
  TOOL_FILTER_REQUEST_PROCESSOR
87
93
  ];
@@ -303,18 +309,26 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
303
309
  event.actions.stateDelta[this.outputKey] = result;
304
310
  }
305
311
  async *runAsyncImpl(context2) {
306
- var _a2;
312
+ var _a2, _b2;
307
313
  while (true) {
308
314
  let lastEvent = void 0;
315
+ let stepHadToolCalls = false;
309
316
  for await (const event of this.runOneStepAsync(context2)) {
310
317
  if ((_a2 = context2.abortSignal) == null ? void 0 : _a2.aborted) {
311
318
  return;
312
319
  }
313
320
  lastEvent = event;
321
+ if (getFunctionCalls(event).length > 0 || getFunctionResponses(event).length > 0) {
322
+ stepHadToolCalls = true;
323
+ }
314
324
  this.maybeSaveOutputToState(event);
315
325
  yield event;
316
326
  }
317
- if (!lastEvent || isFinalResponse(lastEvent)) {
327
+ if (!lastEvent) {
328
+ break;
329
+ }
330
+ const isEmptyMetadataEvent = lastEvent.author === this.name && !lastEvent.partial && (!((_b2 = lastEvent.content) == null ? void 0 : _b2.parts) || lastEvent.content.parts.length === 0);
331
+ if (isFinalResponse(lastEvent) && !(isEmptyMetadataEvent && stepHadToolCalls)) {
318
332
  break;
319
333
  }
320
334
  if (lastEvent.partial) {
@@ -339,6 +353,20 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
339
353
  // --------------------------------------------------------------------------
340
354
  // #START LlmFlow Logic
341
355
  // --------------------------------------------------------------------------
356
+ /**
357
+ * Runs the bidirectional (live) flow for this agent.
358
+ *
359
+ * Establishes a live connection to the model, drains the invocation's
360
+ * `liveRequestQueue` into the connection on a parallel task, and yields
361
+ * events derived from server messages until the queue closes, the model
362
+ * finishes, or an agent transfer occurs.
363
+ *
364
+ * If the live connection drops (network failure, server `goAway`) and a
365
+ * session resumption handle has been observed, the flow transparently
366
+ * reconnects using that handle up to {@link MAX_LIVE_RECONNECT_ATTEMPTS}
367
+ * times. Subsequent reconnects skip `sendHistory` because the server
368
+ * already holds the conversation state associated with the handle.
369
+ */
342
370
  // eslint-disable-next-line require-yield
343
371
  async *runLiveFlow(_invocationContext) {
344
372
  await Promise.resolve();
@@ -362,13 +390,28 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
362
390
  yield event;
363
391
  }
364
392
  }
365
- for (const toolUnion of this.tools) {
393
+ const allTools = [...this.tools];
394
+ if (this.outputSchema && allTools.length > 0) {
395
+ const setModelResponseTool = new FunctionTool({
396
+ name: "set_model_response",
397
+ 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.",
398
+ parameters: this.outputSchema,
399
+ execute: async (args, toolContext) => {
400
+ if (toolContext) {
401
+ toolContext.actions.skipSummarization = true;
402
+ }
403
+ return JSON.stringify(args);
404
+ }
405
+ });
406
+ allTools.push(setModelResponseTool);
407
+ }
408
+ for (const toolUnion of allTools) {
366
409
  const toolContext = new Context({ invocationContext });
367
410
  const tools = (await convertToolUnionToTools(
368
411
  toolUnion,
369
412
  new ReadonlyContext(invocationContext)
370
413
  )).filter((tool) => {
371
- return !llmRequest.allowedTools || llmRequest.allowedTools.includes(tool.name);
414
+ return !llmRequest.allowedTools || llmRequest.allowedTools.includes(tool.name) || tool.name === "set_model_response";
372
415
  });
373
416
  for (const tool of tools) {
374
417
  await tool.processLlmRequest({ toolContext, llmRequest });
@@ -427,7 +470,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
427
470
  span.end();
428
471
  }
429
472
  async *postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
430
- var _a2, _b2, _c, _d, _e;
473
+ var _a2, _b2, _c, _d, _e, _f;
431
474
  for (const processor of this.responseProcessors) {
432
475
  for await (const event of processor.runAsync(
433
476
  invocationContext,
@@ -439,7 +482,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
439
482
  yield event;
440
483
  }
441
484
  }
442
- if (!llmResponse.content && !llmResponse.errorCode && !llmResponse.interrupted) {
485
+ if ((!llmResponse.content || ((_b2 = llmResponse.content.parts) == null ? void 0 : _b2.length) === 0) && !llmResponse.errorCode && !llmResponse.interrupted) {
443
486
  return;
444
487
  }
445
488
  const mergedEvent = createEvent({
@@ -448,7 +491,14 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
448
491
  });
449
492
  if (mergedEvent.content) {
450
493
  const functionCalls = getFunctionCalls(mergedEvent);
451
- if (functionCalls == null ? void 0 : functionCalls.length) {
494
+ const setModelResponseCall = functionCalls.find(
495
+ (call) => call.name === "set_model_response"
496
+ );
497
+ if (setModelResponseCall) {
498
+ const args = setModelResponseCall.args;
499
+ mergedEvent.content.parts = [{ text: JSON.stringify(args) }];
500
+ mergedEvent.actions.skipSummarization = true;
501
+ } else if (functionCalls && functionCalls.length) {
452
502
  populateClientFunctionCallId(mergedEvent);
453
503
  mergedEvent.longRunningToolIds = Array.from(
454
504
  getLongRunningFunctionCalls(functionCalls, llmRequest.toolsDict)
@@ -456,10 +506,10 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
456
506
  }
457
507
  }
458
508
  yield mergedEvent;
459
- if (!((_b2 = getFunctionCalls(mergedEvent)) == null ? void 0 : _b2.length)) {
509
+ if (!((_c = getFunctionCalls(mergedEvent)) == null ? void 0 : _c.length)) {
460
510
  return;
461
511
  }
462
- if ((_c = invocationContext.runConfig) == null ? void 0 : _c.pauseOnToolCalls) {
512
+ if ((_d = invocationContext.runConfig) == null ? void 0 : _d.pauseOnToolCalls) {
463
513
  invocationContext.endInvocation = true;
464
514
  return;
465
515
  }
@@ -470,7 +520,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
470
520
  beforeToolCallbacks: this.canonicalBeforeToolCallbacks,
471
521
  afterToolCallbacks: this.canonicalAfterToolCallbacks
472
522
  });
473
- if (!functionResponseEvent || ((_d = invocationContext.abortSignal) == null ? void 0 : _d.aborted)) {
523
+ if (!functionResponseEvent || ((_e = invocationContext.abortSignal) == null ? void 0 : _e.aborted)) {
474
524
  return;
475
525
  }
476
526
  const authEvent = generateAuthEvent(
@@ -495,7 +545,7 @@ class LlmAgent extends (_b = BaseAgent, _a = LLM_AGENT_SIGNATURE_SYMBOL, _b) {
495
545
  if (nextAgentName) {
496
546
  const nextAgent = this.getAgentByName(invocationContext, nextAgentName);
497
547
  for await (const event of nextAgent.runAsync(invocationContext)) {
498
- if ((_e = invocationContext.abortSignal) == null ? void 0 : _e.aborted) {
548
+ if ((_f = invocationContext.abortSignal) == null ? void 0 : _f.aborted) {
499
549
  return;
500
550
  }
501
551
  yield event;
@@ -30,6 +30,13 @@ class AgentTransferLlmRequestProcessor extends BaseLlmRequestProcessor {
30
30
  }
31
31
  });
32
32
  }
33
+ /**
34
+ * Appends transfer instructions and registers the `transfer_to_agent` tool
35
+ * when the agent has reachable transfer targets.
36
+ *
37
+ * @param invocationContext - The current invocation context.
38
+ * @param llmRequest - The request to augment with transfer instructions and the transfer tool.
39
+ */
33
40
  // eslint-disable-next-line require-yield
34
41
  async *runAsync(invocationContext, llmRequest) {
35
42
  if (!isLlmAgent(invocationContext.agent)) {
@@ -9,6 +9,13 @@ import { setOutputSchema } from "../../models/llm_request.js";
9
9
  import { isLlmAgent } from "../llm_agent.js";
10
10
  import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
11
11
  class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
12
+ /**
13
+ * Populates model name, generation config, output schema, and live connect
14
+ * settings on the request from the agent and run config.
15
+ *
16
+ * @param invocationContext - The current invocation context.
17
+ * @param llmRequest - The request object to populate in place.
18
+ */
12
19
  // eslint-disable-next-line require-yield
13
20
  async *runAsync(invocationContext, llmRequest) {
14
21
  var _a;
@@ -18,7 +25,7 @@ class BasicLlmRequestProcessor extends BaseLlmRequestProcessor {
18
25
  }
19
26
  llmRequest.model = agent.canonicalModel.model;
20
27
  llmRequest.config = { ...(_a = agent.generateContentConfig) != null ? _a : {} };
21
- if (agent.outputSchema) {
28
+ if (agent.outputSchema && (!agent.tools || agent.tools.length === 0)) {
22
29
  setOutputSchema(llmRequest, agent.outputSchema);
23
30
  }
24
31
  if (invocationContext.runConfig) {
@@ -317,9 +317,6 @@ async function postProcessCodeExecutionResult(invocationContext, codeExecutorCon
317
317
  }
318
318
  for (const outputFile of codeExecutionResult.outputFiles) {
319
319
  const version = await invocationContext.artifactService.saveArtifact({
320
- appName: invocationContext.appName || "",
321
- userId: invocationContext.userId || "",
322
- sessionId: invocationContext.session.id,
323
320
  filename: outputFile.name,
324
321
  artifact: {
325
322
  inlineData: { data: outputFile.content, mimeType: outputFile.mimeType }
@@ -16,10 +16,21 @@ import {
16
16
  getFunctionResponses
17
17
  } from "../../events/event.js";
18
18
  import {
19
- removeClientFunctionCallId,
19
+ AF_FUNCTION_CALL_ID_PREFIX,
20
20
  REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
21
21
  REQUEST_EUC_FUNCTION_CALL_NAME
22
22
  } from "../functions.js";
23
+ function removeClientFunctionCallId(content) {
24
+ var _a, _b, _c, _d, _e;
25
+ for (const part of (_a = content == null ? void 0 : content.parts) != null ? _a : []) {
26
+ if ((_c = (_b = part.functionCall) == null ? void 0 : _b.id) == null ? void 0 : _c.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
27
+ part.functionCall.id = void 0;
28
+ }
29
+ if ((_e = (_d = part.functionResponse) == null ? void 0 : _d.id) == null ? void 0 : _e.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
30
+ part.functionResponse.id = void 0;
31
+ }
32
+ }
33
+ }
23
34
  function getContents(events, agentName, currentBranch) {
24
35
  var _a, _b, _c;
25
36
  const filteredEvents = [];
@@ -109,17 +120,19 @@ function convertForeignEvent(event) {
109
120
  text: `[${event.author}] said: ${part.text}`
110
121
  });
111
122
  } else if (part.functionCall) {
112
- const argsText = safeStringify(part.functionCall.args);
113
123
  (_d = content.parts) == null ? void 0 : _d.push({
114
- text: `[${event.author}] called tool \`${part.functionCall.name}\` with parameters: ${argsText}`
124
+ text: `[${event.author}] called tool \`${part.functionCall.name}\` with parameters: ${safeStringify(
125
+ part.functionCall.args
126
+ )}`
115
127
  });
116
128
  } else if (part.functionResponse) {
117
- const responseText = safeStringify(part.functionResponse.response);
118
129
  (_e = content.parts) == null ? void 0 : _e.push({
119
- text: `[${event.author}] tool \`${part.functionResponse.name}\` returned result: ${responseText}`
130
+ text: `[${event.author}] tool \`${part.functionResponse.name}\` returned result: ${safeStringify(
131
+ part.functionResponse.response
132
+ )}`
120
133
  });
121
134
  } else {
122
- (_f = content.parts) == null ? void 0 : _f.push(part);
135
+ (_f = content.parts) == null ? void 0 : _f.push(cloneDeep(part));
123
136
  }
124
137
  }
125
138
  return createEvent({
@@ -135,9 +148,12 @@ function mergeFunctionResponseEvents(events) {
135
148
  if (events.length === 0) {
136
149
  throw new Error("Cannot merge an empty list of events.");
137
150
  }
138
- const mergedEvent = createEvent(events[0]);
139
- const partsInMergedEvent = ((_a = mergedEvent.content) == null ? void 0 : _a.parts) || [];
140
- if (partsInMergedEvent.length === 0) {
151
+ const mergedEvent = createEvent({
152
+ ...events[0],
153
+ content: events[0].content ? cloneDeep(events[0].content) : void 0
154
+ });
155
+ const partsInMergedEvent = (_a = mergedEvent.content) == null ? void 0 : _a.parts;
156
+ if (!partsInMergedEvent || partsInMergedEvent.length === 0) {
141
157
  throw new Error("There should be at least one function_response part.");
142
158
  }
143
159
  const partIndicesInMergedEvent = {};
@@ -152,16 +168,17 @@ function mergeFunctionResponseEvents(events) {
152
168
  throw new Error("There should be at least one function_response part.");
153
169
  }
154
170
  for (const part of event.content.parts) {
155
- if (part.functionResponse && part.functionResponse.id) {
156
- const functionCallId = part.functionResponse.id;
171
+ const clonedPart = cloneDeep(part);
172
+ if (clonedPart.functionResponse && clonedPart.functionResponse.id) {
173
+ const functionCallId = clonedPart.functionResponse.id;
157
174
  if (functionCallId in partIndicesInMergedEvent) {
158
- partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = part;
175
+ partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = clonedPart;
159
176
  } else {
160
- partsInMergedEvent.push(part);
177
+ partsInMergedEvent.push(clonedPart);
161
178
  partIndicesInMergedEvent[functionCallId] = partsInMergedEvent.length - 1;
162
179
  }
163
180
  } else {
164
- partsInMergedEvent.push(part);
181
+ partsInMergedEvent.push(clonedPart);
165
182
  }
166
183
  }
167
184
  }
@@ -176,7 +193,7 @@ function rearrangeEventsForLatestFunctionResponse(events) {
176
193
  if (!(functionResponses == null ? void 0 : functionResponses.length)) {
177
194
  return events;
178
195
  }
179
- let functionResponsesIds = new Set(
196
+ const functionResponsesIds = new Set(
180
197
  functionResponses.filter((response) => !!response.id).map((response) => response.id)
181
198
  );
182
199
  const secondLatestEvent = events.at(-2);
@@ -190,16 +207,16 @@ function rearrangeEventsForLatestFunctionResponse(events) {
190
207
  }
191
208
  }
192
209
  }
193
- let functionCallEventIdx = -1;
210
+ let match;
194
211
  for (let idx = events.length - 2; idx >= 0; idx--) {
195
212
  const event = events[idx];
196
213
  const functionCalls = getFunctionCalls(event);
197
214
  if (!(functionCalls == null ? void 0 : functionCalls.length)) {
198
215
  continue;
199
216
  }
217
+ let matchedInEvent = false;
200
218
  for (const functionCall of functionCalls) {
201
219
  if (functionCall.id && functionResponsesIds.has(functionCall.id)) {
202
- functionCallEventIdx = idx;
203
220
  const functionCallIds = new Set(
204
221
  functionCalls.map((fc) => fc.id).filter((id) => !!id)
205
222
  );
@@ -213,12 +230,16 @@ function rearrangeEventsForLatestFunctionResponse(events) {
213
230
  )}, function response ids provided: ${Array.from(functionResponsesIds).join(", ")}`
214
231
  );
215
232
  }
216
- functionResponsesIds = functionCallIds;
233
+ match = { eventIdx: idx, responseIds: functionCallIds };
234
+ matchedInEvent = true;
217
235
  break;
218
236
  }
219
237
  }
238
+ if (matchedInEvent) {
239
+ break;
240
+ }
220
241
  }
221
- if (functionCallEventIdx === -1) {
242
+ if (!match) {
222
243
  throw new Error(
223
244
  `No function call event found for function responses ids: ${Array.from(
224
245
  functionResponsesIds
@@ -226,17 +247,18 @@ function rearrangeEventsForLatestFunctionResponse(events) {
226
247
  );
227
248
  }
228
249
  const functionResponseEvents = [];
229
- for (let idx = functionCallEventIdx + 1; idx < events.length - 1; idx++) {
250
+ const activeResponses = match.responseIds;
251
+ for (let idx = match.eventIdx + 1; idx < events.length - 1; idx++) {
230
252
  const event = events[idx];
231
253
  const responses = getFunctionResponses(event);
232
254
  if (responses && responses.some(
233
- (response) => response.id && functionResponsesIds.has(response.id)
255
+ (response) => response.id && activeResponses.has(response.id)
234
256
  )) {
235
257
  functionResponseEvents.push(event);
236
258
  }
237
259
  }
238
260
  functionResponseEvents.push(events[events.length - 1]);
239
- const resultEvents = events.slice(0, functionCallEventIdx + 1);
261
+ const resultEvents = events.slice(0, match.eventIdx + 1);
240
262
  resultEvents.push(mergeFunctionResponseEvents(functionResponseEvents));
241
263
  return resultEvents;
242
264
  }
@@ -275,7 +297,7 @@ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
275
297
  continue;
276
298
  }
277
299
  if (functionResponseEventsIndices.size === 1) {
278
- const [responseIndex] = [...functionResponseEventsIndices];
300
+ const [responseIndex] = Array.from(functionResponseEventsIndices);
279
301
  resultEvents.push(events[responseIndex]);
280
302
  } else {
281
303
  const indicesArray = Array.from(functionResponseEventsIndices).sort(
@@ -315,5 +337,7 @@ ${event.compactedContent}`
315
337
  }
316
338
  export {
317
339
  getContents,
318
- getCurrentTurnContents
340
+ getCurrentTurnContents,
341
+ mergeFunctionResponseEvents,
342
+ removeClientFunctionCallId
319
343
  };
@@ -12,6 +12,13 @@ import {
12
12
  getCurrentTurnContents
13
13
  } from "./content_processor_utils.js";
14
14
  class ContentRequestProcessor {
15
+ /**
16
+ * Fills {@link LlmRequest.contents} based on the session event history and
17
+ * agent configuration.
18
+ *
19
+ * @param invocationContext - The current invocation context.
20
+ * @param llmRequest - The request whose contents field will be populated.
21
+ */
15
22
  // eslint-disable-next-line require-yield
16
23
  async *runAsync(invocationContext, llmRequest) {
17
24
  const agent = invocationContext.agent;