@google/adk 0.2.5 → 0.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 (264) hide show
  1. package/dist/cjs/a2a/part_converter_utils.js +210 -0
  2. package/dist/cjs/agents/active_streaming_tool.js +1 -1
  3. package/dist/cjs/agents/base_agent.js +46 -24
  4. package/dist/cjs/agents/base_llm_processor.js +1 -1
  5. package/dist/cjs/agents/callback_context.js +5 -2
  6. package/dist/cjs/agents/content_processor_utils.js +16 -8
  7. package/dist/cjs/agents/functions.js +81 -30
  8. package/dist/cjs/agents/instructions.js +1 -1
  9. package/dist/cjs/agents/invocation_context.js +1 -1
  10. package/dist/cjs/agents/live_request_queue.js +1 -1
  11. package/dist/cjs/agents/llm_agent.js +106 -62
  12. package/dist/cjs/agents/loop_agent.js +3 -2
  13. package/dist/cjs/agents/parallel_agent.js +4 -5
  14. package/dist/cjs/agents/readonly_context.js +13 -1
  15. package/dist/cjs/agents/run_config.js +2 -1
  16. package/dist/cjs/agents/sequential_agent.js +1 -1
  17. package/dist/cjs/agents/transcription_entry.js +1 -1
  18. package/dist/cjs/artifacts/base_artifact_service.js +1 -1
  19. package/dist/cjs/artifacts/file_artifact_service.js +491 -0
  20. package/dist/cjs/artifacts/gcs_artifact_service.js +145 -58
  21. package/dist/cjs/artifacts/in_memory_artifact_service.js +72 -10
  22. package/dist/cjs/artifacts/registry.js +55 -0
  23. package/dist/cjs/auth/auth_credential.js +1 -1
  24. package/dist/cjs/auth/auth_handler.js +4 -2
  25. package/dist/cjs/auth/auth_schemes.js +1 -1
  26. package/dist/cjs/auth/auth_tool.js +1 -1
  27. package/dist/cjs/auth/credential_service/base_credential_service.js +1 -1
  28. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +1 -1
  29. package/dist/cjs/auth/exchanger/base_credential_exchanger.js +1 -1
  30. package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +1 -1
  31. package/dist/cjs/code_executors/base_code_executor.js +4 -2
  32. package/dist/cjs/code_executors/built_in_code_executor.js +8 -4
  33. package/dist/cjs/code_executors/code_execution_utils.js +1 -1
  34. package/dist/cjs/code_executors/code_executor_context.js +6 -6
  35. package/dist/cjs/common.js +18 -1
  36. package/dist/cjs/events/event.js +34 -7
  37. package/dist/cjs/events/event_actions.js +2 -2
  38. package/dist/cjs/events/structured_events.js +105 -0
  39. package/dist/cjs/examples/base_example_provider.js +1 -1
  40. package/dist/cjs/examples/example.js +1 -1
  41. package/dist/cjs/examples/example_util.js +1 -1
  42. package/dist/cjs/index.js +54 -83
  43. package/dist/cjs/index_web.js +1 -1
  44. package/dist/cjs/memory/base_memory_service.js +1 -1
  45. package/dist/cjs/memory/in_memory_memory_service.js +4 -2
  46. package/dist/cjs/memory/memory_entry.js +1 -1
  47. package/dist/cjs/models/apigee_llm.js +182 -0
  48. package/dist/cjs/models/base_llm.js +9 -5
  49. package/dist/cjs/models/base_llm_connection.js +1 -1
  50. package/dist/cjs/models/gemini_llm_connection.js +2 -1
  51. package/dist/cjs/models/google_llm.js +73 -54
  52. package/dist/cjs/models/llm_request.js +1 -1
  53. package/dist/cjs/models/llm_response.js +1 -1
  54. package/dist/cjs/models/registry.js +3 -1
  55. package/dist/cjs/plugins/base_plugin.js +13 -1
  56. package/dist/cjs/plugins/logging_plugin.js +51 -14
  57. package/dist/cjs/plugins/plugin_manager.js +57 -25
  58. package/dist/cjs/plugins/security_plugin.js +2 -2
  59. package/dist/cjs/runner/in_memory_runner.js +1 -1
  60. package/dist/cjs/runner/runner.js +142 -96
  61. package/dist/cjs/sessions/base_session_service.js +53 -3
  62. package/dist/cjs/sessions/database_session_service.js +364 -0
  63. package/dist/cjs/sessions/db/operations.js +114 -0
  64. package/dist/cjs/sessions/db/schema.js +204 -0
  65. package/dist/cjs/sessions/in_memory_session_service.js +60 -34
  66. package/dist/cjs/sessions/registry.js +49 -0
  67. package/dist/cjs/sessions/session.js +1 -1
  68. package/dist/cjs/sessions/state.js +1 -1
  69. package/dist/cjs/telemetry/google_cloud.js +8 -10
  70. package/dist/cjs/telemetry/setup.js +16 -8
  71. package/dist/cjs/telemetry/tracing.js +38 -16
  72. package/dist/cjs/tools/agent_tool.js +9 -5
  73. package/dist/cjs/tools/base_tool.js +5 -3
  74. package/dist/cjs/tools/base_toolset.js +1 -1
  75. package/dist/cjs/tools/forwarding_artifact_service.js +18 -2
  76. package/dist/cjs/tools/function_tool.js +2 -3
  77. package/dist/cjs/tools/google_search_tool.js +2 -3
  78. package/dist/cjs/tools/long_running_tool.js +1 -1
  79. package/dist/cjs/tools/mcp/mcp_session_manager.js +17 -11
  80. package/dist/cjs/tools/mcp/mcp_tool.js +2 -4
  81. package/dist/cjs/tools/mcp/mcp_toolset.js +2 -2
  82. package/dist/cjs/tools/tool_confirmation.js +1 -1
  83. package/dist/cjs/tools/tool_context.js +1 -1
  84. package/dist/cjs/utils/client_labels.js +1 -1
  85. package/dist/cjs/utils/env_aware_utils.js +11 -2
  86. package/dist/cjs/utils/gemini_schema_util.js +10 -5
  87. package/dist/cjs/utils/logger.js +48 -4
  88. package/dist/cjs/utils/model_name.js +1 -1
  89. package/dist/cjs/utils/object_notation_utils.js +78 -0
  90. package/dist/cjs/utils/simple_zod_to_json.js +101 -142
  91. package/dist/cjs/utils/variant_utils.js +3 -9
  92. package/dist/cjs/version.js +2 -2
  93. package/dist/esm/a2a/part_converter_utils.js +171 -0
  94. package/dist/esm/agents/base_agent.js +50 -24
  95. package/dist/esm/agents/callback_context.js +4 -1
  96. package/dist/esm/agents/content_processor_utils.js +25 -9
  97. package/dist/esm/agents/functions.js +84 -29
  98. package/dist/esm/agents/llm_agent.js +110 -62
  99. package/dist/esm/agents/loop_agent.js +2 -1
  100. package/dist/esm/agents/parallel_agent.js +3 -4
  101. package/dist/esm/agents/readonly_context.js +12 -0
  102. package/dist/esm/agents/run_config.js +1 -0
  103. package/dist/esm/artifacts/file_artifact_service.js +451 -0
  104. package/dist/esm/artifacts/gcs_artifact_service.js +144 -57
  105. package/dist/esm/artifacts/in_memory_artifact_service.js +69 -8
  106. package/dist/esm/artifacts/registry.js +28 -0
  107. package/dist/esm/auth/auth_handler.js +3 -1
  108. package/dist/esm/code_executors/base_code_executor.js +3 -1
  109. package/dist/esm/code_executors/built_in_code_executor.js +7 -3
  110. package/dist/esm/code_executors/code_executor_context.js +5 -5
  111. package/dist/esm/common.js +12 -2
  112. package/dist/esm/events/event.js +30 -5
  113. package/dist/esm/events/event_actions.js +1 -1
  114. package/dist/esm/events/structured_events.js +74 -0
  115. package/dist/esm/index.js +18 -88
  116. package/dist/esm/memory/in_memory_memory_service.js +3 -1
  117. package/dist/esm/models/apigee_llm.js +152 -0
  118. package/dist/esm/models/base_llm.js +8 -4
  119. package/dist/esm/models/gemini_llm_connection.js +1 -0
  120. package/dist/esm/models/google_llm.js +75 -53
  121. package/dist/esm/models/registry.js +2 -0
  122. package/dist/esm/plugins/base_plugin.js +12 -0
  123. package/dist/esm/plugins/logging_plugin.js +55 -14
  124. package/dist/esm/plugins/plugin_manager.js +56 -24
  125. package/dist/esm/plugins/security_plugin.js +1 -1
  126. package/dist/esm/runner/runner.js +145 -96
  127. package/dist/esm/sessions/base_session_service.js +49 -1
  128. package/dist/esm/sessions/database_session_service.js +350 -0
  129. package/dist/esm/sessions/db/operations.js +87 -0
  130. package/dist/esm/sessions/db/schema.js +172 -0
  131. package/dist/esm/sessions/in_memory_session_service.js +61 -33
  132. package/dist/esm/sessions/registry.js +25 -0
  133. package/dist/esm/telemetry/google_cloud.js +7 -9
  134. package/dist/esm/telemetry/setup.js +23 -9
  135. package/dist/esm/telemetry/tracing.js +37 -15
  136. package/dist/esm/tools/agent_tool.js +8 -4
  137. package/dist/esm/tools/base_tool.js +4 -2
  138. package/dist/esm/tools/forwarding_artifact_service.js +17 -1
  139. package/dist/esm/tools/function_tool.js +1 -2
  140. package/dist/esm/tools/google_search_tool.js +2 -5
  141. package/dist/esm/tools/long_running_tool.js +3 -1
  142. package/dist/esm/tools/mcp/mcp_session_manager.js +22 -12
  143. package/dist/esm/tools/mcp/mcp_tool.js +1 -3
  144. package/dist/esm/tools/mcp/mcp_toolset.js +1 -1
  145. package/dist/esm/utils/env_aware_utils.js +9 -1
  146. package/dist/esm/utils/gemini_schema_util.js +9 -4
  147. package/dist/esm/utils/logger.js +43 -2
  148. package/dist/esm/utils/object_notation_utils.js +47 -0
  149. package/dist/esm/utils/simple_zod_to_json.js +102 -141
  150. package/dist/esm/utils/variant_utils.js +1 -7
  151. package/dist/esm/version.js +1 -1
  152. package/dist/types/a2a/part_converter_utils.d.ts +47 -0
  153. package/dist/types/agents/base_agent.d.ts +2 -1
  154. package/dist/types/agents/callback_context.d.ts +1 -1
  155. package/dist/types/agents/llm_agent.d.ts +12 -12
  156. package/dist/types/agents/loop_agent.d.ts +1 -1
  157. package/dist/types/agents/parallel_agent.d.ts +1 -1
  158. package/dist/types/agents/readonly_context.d.ts +8 -0
  159. package/dist/types/agents/run_config.d.ts +6 -0
  160. package/dist/types/artifacts/base_artifact_service.d.ts +31 -0
  161. package/dist/types/artifacts/file_artifact_service.d.ts +43 -0
  162. package/dist/types/artifacts/gcs_artifact_service.d.ts +3 -1
  163. package/dist/types/artifacts/in_memory_artifact_service.d.ts +8 -5
  164. package/dist/types/artifacts/registry.d.ts +7 -0
  165. package/dist/types/code_executors/built_in_code_executor.d.ts +1 -1
  166. package/dist/types/code_executors/code_executor_context.d.ts +2 -4
  167. package/dist/types/common.d.ts +13 -3
  168. package/dist/types/events/event.d.ts +15 -1
  169. package/dist/types/events/event_actions.d.ts +1 -1
  170. package/dist/types/events/structured_events.d.ts +106 -0
  171. package/dist/types/index.d.ts +7 -3
  172. package/dist/types/models/apigee_llm.d.ts +59 -0
  173. package/dist/types/models/base_llm_connection.d.ts +1 -1
  174. package/dist/types/models/google_llm.d.ts +5 -2
  175. package/dist/types/models/llm_response.d.ts +1 -1
  176. package/dist/types/plugins/logging_plugin.d.ts +12 -12
  177. package/dist/types/plugins/plugin_manager.d.ts +12 -12
  178. package/dist/types/plugins/security_plugin.d.ts +1 -1
  179. package/dist/types/runner/runner.d.ts +16 -1
  180. package/dist/types/sessions/base_session_service.d.ts +20 -0
  181. package/dist/types/sessions/database_session_service.d.ts +31 -0
  182. package/dist/types/sessions/db/operations.d.ts +29 -0
  183. package/dist/types/sessions/db/schema.d.ts +45 -0
  184. package/dist/types/sessions/in_memory_session_service.d.ts +9 -6
  185. package/dist/types/sessions/registry.d.ts +7 -0
  186. package/dist/types/telemetry/setup.d.ts +1 -1
  187. package/dist/types/telemetry/tracing.d.ts +7 -6
  188. package/dist/types/tools/agent_tool.d.ts +1 -1
  189. package/dist/types/tools/base_tool.d.ts +1 -1
  190. package/dist/types/tools/base_toolset.d.ts +2 -1
  191. package/dist/types/tools/forwarding_artifact_service.d.ts +4 -2
  192. package/dist/types/tools/function_tool.d.ts +4 -3
  193. package/dist/types/tools/google_search_tool.d.ts +3 -3
  194. package/dist/types/tools/mcp/mcp_session_manager.d.ts +10 -3
  195. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -2
  196. package/dist/types/utils/env_aware_utils.d.ts +7 -0
  197. package/dist/types/utils/gemini_schema_util.d.ts +4 -12
  198. package/dist/types/utils/logger.d.ts +11 -10
  199. package/dist/types/utils/object_notation_utils.d.ts +21 -0
  200. package/dist/types/utils/simple_zod_to_json.d.ts +5 -4
  201. package/dist/types/version.d.ts +1 -1
  202. package/dist/web/a2a/part_converter_utils.js +171 -0
  203. package/dist/web/agents/base_agent.js +96 -35
  204. package/dist/web/agents/callback_context.js +4 -1
  205. package/dist/web/agents/content_processor_utils.js +25 -9
  206. package/dist/web/agents/functions.js +84 -29
  207. package/dist/web/agents/llm_agent.js +166 -83
  208. package/dist/web/agents/loop_agent.js +2 -1
  209. package/dist/web/agents/parallel_agent.js +3 -4
  210. package/dist/web/agents/readonly_context.js +12 -0
  211. package/dist/web/agents/run_config.js +2 -1
  212. package/dist/web/artifacts/file_artifact_service.js +506 -0
  213. package/dist/web/artifacts/gcs_artifact_service.js +139 -54
  214. package/dist/web/artifacts/in_memory_artifact_service.js +69 -8
  215. package/dist/web/artifacts/registry.js +28 -0
  216. package/dist/web/auth/auth_handler.js +3 -1
  217. package/dist/web/code_executors/base_code_executor.js +3 -1
  218. package/dist/web/code_executors/built_in_code_executor.js +7 -3
  219. package/dist/web/code_executors/code_executor_context.js +5 -5
  220. package/dist/web/common.js +12 -2
  221. package/dist/web/events/event.js +30 -5
  222. package/dist/web/events/event_actions.js +1 -1
  223. package/dist/web/events/structured_events.js +74 -0
  224. package/dist/web/index.js +18 -8
  225. package/dist/web/memory/in_memory_memory_service.js +3 -1
  226. package/dist/web/models/apigee_llm.js +219 -0
  227. package/dist/web/models/base_llm.js +8 -4
  228. package/dist/web/models/gemini_llm_connection.js +1 -0
  229. package/dist/web/models/google_llm.js +75 -50
  230. package/dist/web/models/registry.js +2 -0
  231. package/dist/web/plugins/base_plugin.js +12 -0
  232. package/dist/web/plugins/logging_plugin.js +55 -14
  233. package/dist/web/plugins/plugin_manager.js +56 -24
  234. package/dist/web/plugins/security_plugin.js +1 -1
  235. package/dist/web/runner/runner.js +192 -108
  236. package/dist/web/sessions/base_session_service.js +49 -1
  237. package/dist/web/sessions/database_session_service.js +368 -0
  238. package/dist/web/sessions/db/operations.js +87 -0
  239. package/dist/web/sessions/db/schema.js +172 -0
  240. package/dist/web/sessions/in_memory_session_service.js +61 -33
  241. package/dist/web/sessions/registry.js +25 -0
  242. package/dist/web/telemetry/google_cloud.js +7 -9
  243. package/dist/web/telemetry/setup.js +23 -9
  244. package/dist/web/telemetry/tracing.js +37 -15
  245. package/dist/web/tools/agent_tool.js +8 -4
  246. package/dist/web/tools/base_tool.js +4 -2
  247. package/dist/web/tools/forwarding_artifact_service.js +17 -1
  248. package/dist/web/tools/function_tool.js +1 -2
  249. package/dist/web/tools/google_search_tool.js +2 -5
  250. package/dist/web/tools/long_running_tool.js +3 -1
  251. package/dist/web/tools/mcp/mcp_session_manager.js +22 -12
  252. package/dist/web/tools/mcp/mcp_tool.js +1 -3
  253. package/dist/web/tools/mcp/mcp_toolset.js +1 -1
  254. package/dist/web/utils/env_aware_utils.js +9 -1
  255. package/dist/web/utils/gemini_schema_util.js +9 -4
  256. package/dist/web/utils/logger.js +43 -2
  257. package/dist/web/utils/object_notation_utils.js +47 -0
  258. package/dist/web/utils/simple_zod_to_json.js +102 -155
  259. package/dist/web/utils/variant_utils.js +1 -7
  260. package/dist/web/version.js +1 -1
  261. package/package.json +16 -5
  262. package/dist/cjs/index.js.map +0 -7
  263. package/dist/esm/index.js.map +0 -7
  264. package/dist/web/index.js.map +0 -7
package/dist/cjs/index.js CHANGED
@@ -1,93 +1,64 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- "use strict";var et=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var Go=Object.getOwnPropertyNames;var $o=Object.prototype.hasOwnProperty;var qo=(o,e)=>{for(var t in e)et(o,t,{get:e[t],enumerable:!0})},Uo=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Go(e))!$o.call(o,r)&&r!==t&&et(o,r,{get:()=>e[r],enumerable:!(n=Do(e,r))||n.enumerable});return o};var jo=o=>Uo(et({},"__esModule",{value:!0}),o);var Vr={};qo(Vr,{ActiveStreamingTool:()=>be,AgentTool:()=>ze,AuthCredentialTypes:()=>Ut,BaseAgent:()=>k,BaseCodeExecutor:()=>oe,BaseExampleProvider:()=>Ue,BaseLlm:()=>X,BaseLlmRequestProcessor:()=>O,BaseLlmResponseProcessor:()=>Ie,BasePlugin:()=>K,BaseSessionService:()=>ve,BaseTool:()=>I,BaseToolset:()=>ce,BuiltInCodeExecutor:()=>ie,CallbackContext:()=>w,FunctionTool:()=>N,GOOGLE_SEARCH:()=>vo,GcsArtifactService:()=>Xt,Gemini:()=>W,GoogleLLMVariant:()=>ge,GoogleSearchTool:()=>Ae,InMemoryArtifactService:()=>se,InMemoryMemoryService:()=>j,InMemoryPolicyEngine:()=>Ce,InMemoryRunner:()=>Ve,InMemorySessionService:()=>V,InvocationContext:()=>B,LLMRegistry:()=>J,LiveRequestQueue:()=>Le,LlmAgent:()=>U,LogLevel:()=>at,LoggingPlugin:()=>je,LongRunningFunctionTool:()=>Ye,LoopAgent:()=>De,MCPSessionManager:()=>Ee,MCPTool:()=>Te,MCPToolset:()=>Qt,ParallelAgent:()=>Ge,PluginManager:()=>ae,PolicyOutcome:()=>Zt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Vt,ReadonlyContext:()=>S,Runner:()=>Z,SecurityPlugin:()=>Ke,SequentialAgent:()=>$e,State:()=>C,StreamingMode:()=>Ne,ToolConfirmation:()=>q,ToolContext:()=>F,createEvent:()=>y,createEventActions:()=>_,createSession:()=>ye,functionsExportedForTestingOnly:()=>fn,getAskUserConfirmationFunctionCalls:()=>fo,getFunctionCalls:()=>T,getFunctionResponses:()=>P,getGcpExporters:()=>jr,getGcpResource:()=>Kr,hasTrailingCodeExecutionResult:()=>tt,isAgentTool:()=>Co,isBaseAgent:()=>cn,isBaseExampleProvider:()=>co,isBaseLlm:()=>Me,isBaseTool:()=>_n,isFinalResponse:()=>z,isFunctionTool:()=>Dn,isGemini2OrAbove:()=>re,isLlmAgent:()=>E,isLoopAgent:()=>eo,isParallelAgent:()=>oo,isSequentialAgent:()=>so,maybeSetOtelProviders:()=>Fr,setLogLevel:()=>ln,stringifyContent:()=>nn,version:()=>Oe,zodObjectToSchema:()=>he});module.exports=jo(Vr);var be=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};var rt=require("@opentelemetry/api");function _(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function en(o,e){let t=_();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function y(o={}){return{...o,id:o.id||nt(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||_(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function z(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:T(o).length===0&&P(o).length===0&&!o.partial&&!tt(o)}function T(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function P(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function tt(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function nn(o){var e;return(e=o.content)!=null&&e.parts?o.content.parts.map(t=>{var n;return(n=t.text)!=null?n:""}).join(""):""}var tn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function nt(){let o="";for(let e=0;e<8;e++)o+=tn[Math.floor(Math.random()*tn.length)];return o}var C=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};C.APP_PREFIX="app:",C.USER_PREFIX="user:",C.TEMP_PREFIX="temp:";var S=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new C(this.invocationContext.session.state,{})}};var w=class extends S{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||_(),this._state=new C(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function Re(){return typeof window<"u"}var Se="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ee(){let o="";for(let e=0;e<Se.length;e++){let t=Math.random()*16|0;Se[e]==="x"?o+=t.toString(16):Se[e]==="y"?o+=(t&3|8).toString(16):o+=Se[e]}return o}function on(o){return Re()?window.atob(o):Buffer.from(o,"base64").toString()}var ot=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},B=class{constructor(e){this.invocationCostManager=new ot;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function rn(){return`e-${ee()}`}var it=Symbol.for("google.adk.baseAgent");function cn(o){return typeof o=="object"&&o!==null&&it in o&&o[it]===!0}var an;an=it;var k=class{constructor(e){this[an]=!0;this.name=Ko(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Zo(this),this.beforeAgentCallback=sn(e.beforeAgentCallback),this.afterAgentCallback=sn(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=rt.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=rt.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new B({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function Ko(o){if(!Vo(o))throw new Error(`Found invalid agent name: "${o}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function Vo(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function Zo(o){for(;o.parentAgent;)o=o.parentAgent;return o}function sn(o){return o?Array.isArray(o)?o:[o]:[]}var O=class{},Ie=class{};var un=require("@google/genai"),lt=require("lodash-es");var ue=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var q=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var F=class extends w{constructor(e){super(e),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new ue(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ue(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new q({hint:e,confirmed:!1,payload:t})}};var at=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(at||{}),te=1;function ln(o){te=o}var st=class{log(e,...t){if(!(e<te))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){te>0||console.debug(Pe(0),...e)}info(...e){te>1||console.info(Pe(1),...e)}warn(...e){te>2||console.warn(Pe(2),...e)}error(...e){te>3||console.error(Pe(3),...e)}},zo={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Yo={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Ho="\x1B[0m";function Pe(o){return`${Yo[o]}[ADK ${zo[o]}]:${Ho}`}var m=new st;var ct="adk-",we="adk_request_credential",ne="adk_request_confirmation",fn={handleFunctionCallList:ke,generateAuthEvent:ft,generateRequestConfirmationEvent:dt};function ut(){return`${ct}${ee()}`}function dn(o){let e=T(o);if(e)for(let t of e)t.id||(t.id=ut())}function pn(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(ct)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(ct)&&(e.functionResponse.id=void 0)}function mn(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function ft(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||(0,lt.isEmpty)(e.actions.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:we,args:{function_call_id:i,auth_config:s},id:ut()};n.add(a.id),t.push({functionCall:a})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function dt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||(0,lt.isEmpty)(t.actions.requestedToolConfirmations))return;let n=[],r=new Set,i=T(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!f)continue;let u={name:ne,args:{originalFunctionCall:f,toolConfirmation:l},id:ut()};r.add(u.id),n.push({functionCall:u})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Qo(o,e,t){return m.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function gn({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=T(e);return await ke({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function ke({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of c){let d;s&&u.id&&(d=s[u.id]);let{tool:p,toolContext:g}=Xo({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});m.debug(`execute_tool ${p.name}`);let v=(f=u.args)!=null?f:{},h=null,x;if(h=await o.pluginManager.runBeforeToolCallback({tool:p,toolArgs:v,toolContext:g}),h==null){for(let $ of n)if(h=await $({tool:p,args:v,context:g}),h)break}if(h==null)try{h=await Qo(p,v,g)}catch($){if($ instanceof Error){let Jt=await o.pluginManager.runOnToolErrorCallback({tool:p,toolArgs:v,toolContext:g,error:$});Jt?h=Jt:x=$.message}else x=$}let R=await o.pluginManager.runAfterToolCallback({tool:p,toolArgs:v,toolContext:g,result:h});if(R==null){for(let $ of r)if(R=await $({tool:p,args:v,context:g,response:h}),R)break}if(R!=null&&(h=R),p.isLongRunning&&!h)continue;x?h={error:x}:(typeof h!="object"||h==null)&&(h={result:h});let Wt=y({invocationId:o.invocationId,author:o.agent.name,content:(0,un.createUserContent)({functionResponse:{id:g.functionCallId,name:p.name,response:h}}),actions:g.actions,branch:o.branch});m.debug("traceToolCall",{tool:p.name,args:v,functionResponseEvent:Wt.id}),a.push(Wt)}if(!a.length)return null;let l=Wo(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Xo({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new F({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Wo(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=en(n);return y({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Le=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var It=require("lodash-es"),Pt=require("zod");var pt=Symbol.for("google.adk.baseCodeExecutor");function _e(o){return typeof o=="object"&&o!==null&&pt in o&&o[pt]===!0}var hn;hn=pt;var oe=class{constructor(){this[hn]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Jo="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function mt(o){let e=o.match(Jo);return e?e[1]:o}function Cn(o){return mt(o).startsWith("gemini-")}function er(o){if(!/^\d+(\.\d+)*$/.test(o))return{valid:!1,major:0,minor:0,patch:0};let e=o.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function vn(o){return mt(o).startsWith("gemini-1")}function re(o){if(!o)return!1;let e=mt(o);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],n=er(t);return n.valid&&n.major>=2}var gt=Symbol.for("google.adk.builtInCodeExecutor");function fe(o){return typeof o=="object"&&o!==null&&gt in o&&o[gt]===!0}var yn,xn,ie=class extends(xn=oe,yn=gt,xn){constructor(){super(...arguments);this[yn]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&re(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${t.model}`)}};var de=require("@google/genai"),An=require("lodash-es");function En(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let d=o.parts[u];if(d.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),d.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=(0,An.cloneDeep)(t[0]),r=t.map(u=>u.text).join(`
8
- `),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[1]).join("|"),a=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(o.parts=[],c&&(n.text=c,o.parts.push(n)),o.parts.push(ht(l)),l):""}function ht(o){return{text:o,executableCode:{code:o,language:de.Language.PYTHON}}}function Tn(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:de.Outcome.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push(`Code execution result:
9
- ${o.stdout}
10
- `),o.outputFiles&&e.push(`Saved artifacts:
11
- `+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
12
-
13
- `),codeExecutionResult:{outcome:de.Outcome.OUTCOME_OK}}}function bn(o,e,t){var r;if(!((r=o.parts)!=null&&r.length))return;let n=o.parts[o.parts.length-1];n.executableCode?o.parts[o.parts.length-1]={text:e[0]+n.executableCode.code+e[1]}:o.parts.length==1&&n.codeExecutionResult&&(o.parts[o.parts.length-1]={text:t[0]+n.codeExecutionResult.output+t[1]},o.role="user")}var Sn=require("lodash-es");var Ct="_code_execution_context",vt="execution_session_id",Y="processed_input_files",H="_code_executor_input_files",Q="_code_executor_error_counts",yt="_code_execution_results",pe=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Ct))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Ct]:(0,Sn.cloneDeep)(this.context)}}getExecutionId(){if(vt in this.context)return this.context[vt]}setExecutionId(e){this.context[vt]=e}getProcessedFileNames(){return Y in this.context?this.context[Y]:[]}addProcessedFileNames(e){Y in this.context||(this.context[Y]=[]),this.context[Y].push(...e)}getInputFiles(){return H in this.sessionState?this.sessionState.get(H):[]}addInputFiles(e){H in this.sessionState||this.sessionState.set(H,[]),this.sessionState.get(H).push(...e)}clearInputFiles(){H in this.sessionState&&this.sessionState.set(H,[]),Y in this.context&&(this.context[Y]=[])}getErrorCount(e){return Q in this.sessionState&&this.sessionState.get(Q)[e]||0}incrementErrorCount(e){Q in this.sessionState||this.sessionState.set(Q,{}),this.sessionState.get(Q)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(Q in this.sessionState))return;let t=this.sessionState.get(Q);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){yt in this.sessionState||this.sessionState.set(yt,{});let i=this.sessionState.get(yt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(Ct)||{}}};var Oe="0.2.5";var tr="google-adk",nr="gl-typescript",or="remote_reasoning_engine",rr="GOOGLE_CLOUD_AGENT_ENGINE_ID";function ir(){let o=`${tr}/${Oe}`;!Re()&&process.env[rr]&&(o=`${o}+${or}`);let e=`${nr}/${Re()?window.navigator.userAgent:process.version}`;return[o,e]}function Rn(){return ir()}var xt=Symbol.for("google.adk.baseModel");function Me(o){return typeof o=="object"&&o!==null&&xt in o&&o[xt]===!0}var In;In=xt;var X=class{constructor({model:e}){this[In]=!0;this.model=e}get trackingHeaders(){let t=Rn().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};X.supportedModels=[];function me(o,e){o.config||(o.config={});let t=e.join(`
14
-
15
- `);o.config.systemInstruction?o.config.systemInstruction+=`
16
-
17
- `+t:o.config.systemInstruction=t}function Pn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var D=require("@google/genai");var ge=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(ge||{});function wn(){return sr("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function sr(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Be=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(n=>{var r;return n.parts&&((r=n.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):m.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(n=>n.functionResponse).filter(n=>!!n);m.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else m.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){m.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function At(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var W=class extends X{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!n,!this.vertexai&&a){let c=process.env.GOOGLE_GENAI_USE_VERTEXAI;c&&(this.vertexai=c.toLowerCase()==="true"||c==="1")}if(this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,a,c,l;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let f=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),u="",d="",p,g;for await(let v of f){g=v;let h=At(v);p=h.usageMetadata;let x=(s=(i=h.content)==null?void 0:i.parts)==null?void 0:s[0];if(x!=null&&x.text)"thought"in x&&x.thought?u+=x.text:d+=x.text,h.partial=!0;else if((u||d)&&(!x||!x.inlineData)){let R=[];u&&R.push({text:u,thought:!0}),d&&R.push((0,D.createPartFromText)(d)),yield{content:{role:"model",parts:R},usageMetadata:h.usageMetadata},u="",d=""}yield h}if((d||u)&&((c=(a=g==null?void 0:g.candidates)==null?void 0:a[0])==null?void 0:c.finishReason)===D.FinishReason.STOP){let v=[];u&&v.push({text:u,thought:!0}),d&&v.push({text:d}),yield{content:{role:"model",parts:v},usageMetadata:p}}}else{let f=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield At(f)}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};return this.vertexai?this._apiClient=new D.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new D.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new D.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,D.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new Be(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)kn(n.inlineData),kn(n.fileData)}}};W.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function kn(o){o&&o.displayName&&(o.displayName=void 0)}var Et=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},L=class L{static newLlm(e){return new(L.resolve(e))({model:e})}static _register(e,t){L.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${L.llmRegistryDict.get(e)} to ${t}`),L.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)L._register(t,e)}static resolve(e){let t=L.resolveCache.get(e);if(t)return t;for(let[n,r]of L.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return L.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};L.llmRegistryDict=new Map,L.resolveCache=new Et(32);var J=L;J.register(W);var Tt=Symbol.for("google.adk.baseTool");function _n(o){return typeof o=="object"&&o!==null&&Tt in o&&o[Tt]===!0}var Ln;Ln=Tt;var I=class{constructor(e){this[Ln]=!0;var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=ar(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return wn()}};function ar(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var Nn=require("@google/genai"),Fn=require("zod");var b=require("@google/genai"),A=require("zod");function On(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function G(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case A.z.ZodFirstPartyTypeKind.ZodString:n.type=b.Type.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case A.z.ZodFirstPartyTypeKind.ZodNumber:n.type=b.Type.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=b.Type.INTEGER);return r(n);case A.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=b.Type.BOOLEAN,r(n);case A.z.ZodFirstPartyTypeKind.ZodArray:return n.type=b.Type.ARRAY,n.items=G(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case A.z.ZodFirstPartyTypeKind.ZodObject:return he(o);case A.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=b.Type.STRING;else if(i==="number")n.type=b.Type.NUMBER;else if(i==="boolean")n.type=b.Type.BOOLEAN;else if(e.value===null)n.type=b.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case A.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=b.Type.STRING,n.enum=e.values,r(n);case A.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=b.Type.STRING,n.enum=Object.values(e.values),r(n);case A.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(G),r(n);case A.z.ZodFirstPartyTypeKind.ZodOptional:return G(e.innerType);case A.z.ZodFirstPartyTypeKind.ZodNullable:let s=G(e.innerType);return r(s?{anyOf:[s,{type:b.Type.NULL}],...t&&{description:t}}:{type:b.Type.NULL,...t&&{description:t}});case A.z.ZodFirstPartyTypeKind.ZodDefault:let a=G(e.innerType);return a&&(a.default=e.defaultValue()),a;case A.z.ZodFirstPartyTypeKind.ZodBranded:return G(e.type);case A.z.ZodFirstPartyTypeKind.ZodReadonly:return G(e.innerType);case A.z.ZodFirstPartyTypeKind.ZodNull:return n.type=b.Type.NULL,r(n);case A.z.ZodFirstPartyTypeKind.ZodAny:case A.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function he(o){if(o._def.typeName!==A.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=G(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===A.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===A.z.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==A.z.ZodFirstPartyTypeKind.ZodNever?i=G(r)||!0:i=o._def.unknownKeys==="passthrough",{type:b.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function cr(o){return o===void 0?{type:Nn.Type.OBJECT,properties:{}}:On(o)?he(o):o}var bt=Symbol.for("google.adk.functionTool");function Dn(o){return typeof o=="object"&&o!==null&&bt in o&&o[bt]===!0}var Mn,Bn,N=class extends(Bn=I,Mn=bt,Bn){constructor(t){var r;let n=(r=t.name)!=null?r:t.execute.name;if(!n)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:n,description:t.description,isLongRunning:t.isLongRunning});this[Mn]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:cr(this.parameters)}}async runAsync(t){try{let n=t.args;return this.parameters instanceof Fn.ZodObject&&(n=this.parameters.parse(t.args)),await this.execute(n,t.toolContext)}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Error in tool '${this.name}': ${r}`)}}};var $n=require("lodash-es");function St(o,e,t){var s,a,c;let n=[];for(let l of o)!((s=l.content)!=null&&s.role)||((c=(a=l.content.parts)==null?void 0:a[0])==null?void 0:c.text)===""||t&&l.branch&&!t.startsWith(l.branch)||lr(l)||ur(l)||n.push(Un(e,l)?fr(l):l);let r=dr(n);r=pr(r);let i=[];for(let l of r){let f=(0,$n.cloneDeep)(l.content);pn(f),i.push(f)}return i}function qn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Un(e,r))return St(o.slice(n),e,t)}return[]}function lr(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===we||((n=r.functionResponse)==null?void 0:n.name)===we)return!0;return!1}function ur(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===ne||((n=r.functionResponse)==null?void 0:n.name)===ne)return!0;return!1}function Un(o,e){return!!o&&e.author!==o&&e.author!=="user"}function fr(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=Gn(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=Gn(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return y({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function jn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=y(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function dr(o){if(o.length===0)return o;let e=o[o.length-1],t=P(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=T(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],f=T(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=c;let d=new Set(f.map(g=>g.id).filter(g=>!!g));if(!Array.from(n).every(g=>d.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=P(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(jn(s)),a}function pr(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=P(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(P(n).length>0)continue;let r=T(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(jn(a))}}else t.push(n)}return t}function Gn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Rt(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!hr(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var mr=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Kn(o){return o===""||o===void 0?!1:mr.test(o)}var gr=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function hr(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Kn(o):gr.includes(e[0]+":")?Kn(e[1]):!1}var Ne=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ne||{});function Vn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Cr(o.maxLlmCalls||500),...o}}function Cr(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&m.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),o}var Zn="adk_agent_name";async function zn(o,e){return o instanceof I?[o]:await o.getTools(e)}var wt=class extends O{async*runAsync(e,t){var r;let n=e.agent;E(n)&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&Pn(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))}},vr=new wt,kt=class extends O{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),me(t,r)}},yr=new kt,Lt=class extends O{async*runAsync(e,t){let n=e.agent;if(!(n instanceof U)||!(n.rootAgent instanceof U))return;let r=n.rootAgent;if(E(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new S(e)),a=i;s&&(a=await Rt(i,new S(e))),me(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new S(e)),a=i;s&&(a=await Rt(i,new S(e))),me(t,[a])}}},xr=new Lt,_t=class{async*runAsync(e,t){let n=e.agent;!n||!E(n)||(n.includeContents==="default"?t.contents=St(e.session.events,n.name,e.branch):t.contents=qn(e.session.events,n.name,e.branch))}},Ar=new _t,Ot=class extends O{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new N({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:Pt.z.object({agentName:Pt.z.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof U))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;me(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new F({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
18
- Agent name: ${t.name}
19
- Agent description: ${t.description}
20
- `}buildTargetAgentsInstructions(t,n){let r=`
21
- You have a list of other agents to transfer to:
22
-
23
- ${n.map(this.buildTargetAgentsInfo).join(`
24
- `)}
25
-
26
- If you are the best to answer the question according to your description, you
27
- can answer it.
28
-
29
- If another agent is better for answering the question according to its
30
- description, call \`${this.toolName}\` function to transfer the
31
- question to that agent. When transferring, do not generate any text other than
32
- the function call.
33
- `;return t.parentAgent&&!t.disallowTransferToParent&&(r+=`
34
- Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
35
- you are best for answering the question according to the descriptions, transfer
36
- to your parent agent.
37
- `),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!E(t.parentAgent)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},Er=new Ot,Mt=class extends O{async*runAsync(e,t){let n=e.agent;if(!E(n))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let a=r.length-1;a>=0;a--){let c=r[a];if(c.author!=="user")continue;let l=P(c);if(!l)continue;let f=!1;for(let u of l){if(u.name!==ne)continue;f=!0;let d=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?d=JSON.parse(u.response.response):u.response&&(d=new q({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&d&&(i[u.id]=d)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=T(c);if(!l)continue;let f={},u={};for(let v of l){if(!v.id||!(v.id in i))continue;let h=v.args;if(!h||!("originalFunctionCall"in h))continue;let x=h.originalFunctionCall;x.id&&(f[x.id]=i[v.id],u[x.id]=x)}if(Object.keys(f).length===0)continue;for(let v=r.length-1;v>s;v--){let h=r[v],x=P(h);if(x){for(let R of x)R.id&&R.id in f&&(delete f[R.id],delete u[R.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let d=await n.canonicalTools(new S(e)),p=Object.fromEntries(d.map(v=>[v.name,v])),g=await ke({invocationContext:e,functionCalls:Object.values(u),toolsDict:p,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f});g&&(yield g);return}}},Tr=new Mt,Bt=class extends O{async*runAsync(e,t){if(e.agent instanceof U&&e.agent.codeExecutor){for await(let n of Sr(e,t))yield n;if(_e(e.agent.codeExecutor))for(let n of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],i=bn(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},Fe={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},br=`
38
- import pandas as pd
39
-
40
- def explore_df(df: pd.DataFrame) -> None:
41
- """Prints some information about a pandas DataFrame."""
42
-
43
- with pd.option_context(
44
- 'display.max_columns', None, 'display.expand_frame_repr', False
45
- ):
46
- # Print the column names to never encounter KeyError when selecting one.
47
- df_dtypes = df.dtypes
48
-
49
- # Obtain information about data types and missing values.
50
- df_nulls = (len(df) - df.isnull().sum()).apply(
51
- lambda x: f'{x} / {df.shape[0]} non-null'
52
- )
53
-
54
- # Explore unique total values in columns using \`.unique()\`.
55
- df_unique_count = df.apply(lambda x: len(x.unique()))
56
-
57
- # Explore unique values in columns using \`.unique()\`.
58
- df_unique = df.apply(lambda x: crop(str(list(x.unique()))))
59
-
60
- df_info = pd.concat(
61
- (
62
- df_dtypes.rename('Dtype'),
63
- df_nulls.rename('Non-Null Count'),
64
- df_unique_count.rename('Unique Values Count'),
65
- df_unique.rename('Unique Values'),
66
- ),
67
- axis=1,
68
- )
69
- df_info.index.name = 'Columns'
70
- print(f"""Total rows: {df.shape[0]}
71
- Total columns: {df.shape[1]}
72
-
73
- {df_info}""")
74
- `,Nt=class{async*runAsync(e,t){if(!t.partial)for await(let n of Rr(e,t))yield n}},ga=new Nt;async function*Sr(o,e){let t=o.agent;if(!E(t))return;let n=t.codeExecutor;if(!n||!_e(n))return;if(fe(n)){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new pe(new C(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=Ir(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=Pr(c);if(!l)return;let f={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},ht(l)]};e.contents.push((0,It.cloneDeep)(f)),yield y({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let u=Qn(o,r),d=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:u}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([c.name]);let p=await Xn(o,r,d);yield p,e.contents.push((0,It.cloneDeep)(p.content))}}async function*Rr(o,e){let t=o.agent;if(!E(t))return;let n=t.codeExecutor;if(!n||!_e(n)||!e||!e.content||fe(n))return;let r=new pe(new C(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=En(i,n.codeBlockDelimiters);if(!s)return;yield y({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=Qn(o,r),c=await n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await Xn(o,r,c),e.content=null}function Ir(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let a=0;a<s.parts.length;a++){let c=s.parts[a],l=(r=c.inlineData)==null?void 0:r.mimeType;if(!l||!c.inlineData||!Fe[l])continue;let f=`data_${i+1}_${a+1}${Fe[l].extension}`;c.text=`
75
- Available file: \`${f}\`
76
- `;let u={name:f,content:on(c.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([u]),t.push(u))}}return t}function Qn(o,e){var r;let t=o.agent;if(!E(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function Xn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[Tn(t)]},r=_({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(o.invocationId):e.resetErrorCount(o.invocationId);for(let i of t.outputFiles){let s=await o.artifactService.saveArtifact({appName:o.appName||"",userId:o.userId||"",sessionId:o.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Pr(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Fe[o.mimeType])return;let t=e(o.name),n=Fe[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return`
77
- ${br}
78
-
79
- # Load the dataframe.
80
- ${t} = ${n}
81
-
82
- # Use \`explore_df\` to guide my analysis.
83
- explore_df(${t})
84
- `}var wr=new Bt,Ft=Symbol.for("google.adk.llmAgent");function E(o){return typeof o=="object"&&o!==null&&Ft in o&&o[Ft]===!0}var Yn,Hn,U=class o extends(Hn=k,Yn=Ft,Hn){constructor(t){var r,i,s,a,c,l,f,u,d;super(t);this[Yn]=!0;if(this.model=t.model,this.instruction=(r=t.instruction)!=null?r:"",this.globalInstruction=(i=t.globalInstruction)!=null?i:"",this.tools=(s=t.tools)!=null?s:[],this.generateContentConfig=t.generateContentConfig,this.disallowTransferToParent=(a=t.disallowTransferToParent)!=null?a:!1,this.disallowTransferToPeers=(c=t.disallowTransferToPeers)!=null?c:!1,this.includeContents=(l=t.includeContents)!=null?l:"default",this.inputSchema=t.inputSchema,this.outputSchema=t.outputSchema,this.outputKey=t.outputKey,this.beforeModelCallback=t.beforeModelCallback,this.afterModelCallback=t.afterModelCallback,this.beforeToolCallback=t.beforeToolCallback,this.afterToolCallback=t.afterToolCallback,this.codeExecutor=t.codeExecutor,this.requestProcessors=(f=t.requestProcessors)!=null?f:[vr,yr,xr,Tr,Ar,wr],this.responseProcessors=(u=t.responseProcessors)!=null?u:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(Er),t.generateContentConfig){if(t.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(t.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(t.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};if(this.outputSchema){if((!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(m.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(Me(this.model))return this.model;if(typeof this.model=="string"&&this.model)return J.newLlm(this.model);let t=this.parentAgent;for(;t;){if(E(t))return t.canonicalModel;t=t.parentAgent}throw new Error(`No model found for ${this.name}.`)}async canonicalInstruction(t){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(t),requireStateInjection:!1}}async canonicalGlobalInstruction(t){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(t),requireStateInjection:!1}}async canonicalTools(t){let n=[];for(let r of this.tools){let i=await zn(r,t);n.push(...i)}return n}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){m.debug(`Skipping output save for agent ${this.name}: event authored by ${t.author}`);return}if(!this.outputKey){m.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!z(t)){m.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){m.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let n=t.content.parts.map(a=>a.text?a.text:"").join(""),r=n;if(this.outputSchema){if(!n.trim())return;try{r=JSON.parse(n)}catch(a){m.error(`Error parsing output for agent ${this.name}`,a)}}t.actions.stateDelta[this.outputKey]=r}async*runAsyncImpl(t){for(;;){let n;for await(let r of this.runOneStepAsync(t))n=r,this.maybeSaveOutputToState(r),yield r;if(!n||z(n))break;if(n.partial){m.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(t){for await(let n of this.runLiveFlow(t))this.maybeSaveOutputToState(n),yield n;t.endInvocation}async*runLiveFlow(t){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(t){let n={contents:[],toolsDict:{},liveConnectConfig:{}};for(let i of this.requestProcessors)for await(let s of i.runAsync(t,n))yield s;for(let i of this.tools){let s=new F({invocationContext:t}),a=await zn(i,new S(t));for(let c of a)await c.processLlmRequest({toolContext:s,llmRequest:n})}if(t.endInvocation)return;let r=y({invocationId:t.invocationId,author:this.name,branch:t.branch});for await(let i of this.callLlmAsync(t,n,r))for await(let s of this.postprocess(t,n,i,r))r.id=nt(),r.timestamp=new Date().getTime(),yield s}async*postprocess(t,n,r,i){var u;for(let d of this.responseProcessors)for await(let p of d.runAsync(t,r))yield p;if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=y({...i,...r});if(s.content){let d=T(s);d!=null&&d.length&&(dn(s),s.longRunningToolIds=Array.from(mn(d,n.toolsDict)))}if(yield s,!((u=T(s))!=null&&u.length))return;let a=await gn({invocationContext:t,functionCallEvent:s,toolsDict:n.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a)return;let c=ft(t,a);c&&(yield c);let l=dt({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});l&&(yield l),yield a;let f=a.actions.transferToAgent;if(f){let d=this.getAgentByName(t,f);for await(let p of d.runAsync(t))yield p}}getAgentByName(t,n){let i=t.agent.rootAgent.findAgent(n);if(!i)throw new Error(`Agent ${n} not found in the agent tree.`);return i}async*callLlmAsync(t,n,r){var a,c,l,f,u;let i=await this.handleBeforeModelCallback(t,n,r);if(i){yield i;return}(a=n.config)!=null||(n.config={}),(l=(c=n.config).labels)!=null||(c.labels={}),n.config.labels[Zn]||(n.config.labels[Zn]=this.name);let s=this.canonicalModel;if((f=t.runConfig)!=null&&f.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let d=s.generateContentAsync(n,((u=t.runConfig)==null?void 0:u.streamingMode)==="sse");for await(let p of this.runAndHandleError(d,t,n,r)){let g=await this.handleAfterModelCallback(t,p,r);yield g!=null?g:p}}}async handleBeforeModelCallback(t,n,r){let i=new w({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:n});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:n});if(c)return c}}async handleAfterModelCallback(t,n,r){let i=new w({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:n});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:n});if(c)return c}}async*runAndHandleError(t,n,r,i){try{for await(let s of t)yield s}catch(s){let a=new w({invocationContext:n,eventActions:i.actions});if(s instanceof Error){let c=await n.pluginManager.runOnModelErrorCallback({callbackContext:a,llmRequest:r,error:s});if(c)yield c;else{let l=JSON.parse(s.message);yield{errorCode:String(l.error.code),errorMessage:l.error.message}}}else throw m.error("Unknown error during response generation",s),s}}};var Dt=Symbol.for("google.adk.loopAgent");function eo(o){return typeof o=="object"&&o!==null&&Dt in o&&o[Dt]===!0}var Wn,Jn,De=class extends(Jn=k,Wn=Dt,Jn){constructor(t){var n;super(t);this[Wn]=!0;this.maxIterations=(n=t.maxIterations)!=null?n:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(t){let n=0;for(;n<this.maxIterations;){for(let r of this.subAgents){let i=!1;for await(let s of r.runAsync(t))yield s,s.actions.escalate&&(i=!0);if(i)return}n++}}async*runLiveImpl(t){throw new Error("This is not supported yet for LoopAgent.")}};var Gt=Symbol.for("google.adk.parallelAgent");function oo(o){return typeof o=="object"&&o!==null&&Gt in o&&o[Gt]===!0}var to,no,Ge=class extends(no=k,to=Gt,no){constructor(){super(...arguments);this[to]=!0}async*runAsyncImpl(t){let n=this.subAgents.map(r=>r.runAsync(kr(this,r,t)));for await(let r of Lr(n))yield r}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function kr(o,e,t){let n=new B(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Lr(o){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=await Promise.race(e.values());if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}}var $t="task_completed",qt=Symbol.for("google.adk.sequentialAgent");function so(o){return typeof o=="object"&&o!==null&&qt in o&&o[qt]===!0}var ro,io,$e=class extends(io=k,ro=qt,io){constructor(){super(...arguments);this[ro]=!0}async*runAsyncImpl(t){for(let n of this.subAgents)for await(let r of n.runAsync(t))yield r}async*runLiveImpl(t){for(let n of this.subAgents)E(n)&&((await n.canonicalTools(new S(t))).some(s=>s.name===$t)||(n.tools.push(new N({name:$t,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),n.instruction+=`If you finished the user's request according to its description, call the ${$t} function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.`));for(let n of this.subAgents)for await(let r of n.runLive(t))yield r}};var se=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=qe(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=qe(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=qe(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=qe(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}};function qe(o,e,t,n){return _r(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function _r(o){return o.startsWith("user:")}var Ut=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(Ut||{});var jt=Symbol.for("google.adk.baseExampleProvider");function co(o){return typeof o=="object"&&o!==null&&jt in o&&o[jt]===!0}var ao;ao=jt;var Ue=class{constructor(){this[ao]=!0}};var j=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=lo(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=lo(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),f=Or(l);if(!f.size)continue;n.some(d=>f.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:Mr(c.timestamp)})}return r}};function lo(o,e){return`${o}/${e}`}function Or(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Mr(o){return new Date(o).toISOString()}var K=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var je=class extends K{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${z(t)}`);let n=T(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=P(t);if(r.length>0){let i=r.map(s=>s.name);this.log(` Function Responses: ${i}`)}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...t.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`),t.invocationContext.branch&&this.log(` Branch: ${t.invocationContext.branch}`)}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(n=t.model)!=null?n:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Result: ${this.formatArgs(r)}`)}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${n}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;m.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let n=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),n.push(`text: '${i}'`)}else r.functionCall?n.push(`function_call: ${r.functionCall.name}`):r.functionResponse?n.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var ae=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),m.info(`Plugin '${e.name}' registered.`)}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return m.debug(`Plugin '${r.name}' returned a value for callback '${n}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${n}' callback: ${i}`;throw m.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,n=>n.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,n=>n.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:n}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:n}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,n=>n.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,n=>n.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}),"onToolErrorCallback")}};var Vt="adk_request_confirmation",Kt="orcas_tool_call_security_check_states",uo="This tool call needs external confirmation before completion.",Zt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Zt||{}),Ce=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Ke=class extends K{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ce}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:uo};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(Kt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Kt))!=null?i:{};r[n]=t,e.state.set(Kt,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:uo};case"ALLOW":return;default:return}}};function fo(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Vt&&e.push(t.functionCall);return e}var zt=require("lodash-es");var ve=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[n,r]of Object.entries(t.actions.stateDelta))n.startsWith(C.TEMP_PREFIX)||(e.state[n]=r)}};function ye(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var V=class extends ve{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=ye({id:i||ee(),appName:t,userId:n,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][n]||(this.sessions[t][n]={}),this.sessions[t][n][s.id]=s,Promise.resolve(this.mergeState(t,n,(0,zt.cloneDeep)(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=(0,zt.cloneDeep)(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(ye({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{m.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(C.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(C.USER_PREFIX,"")]=n.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:n}),c.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[C.USER_PREFIX+i]=this.userState[t][n][i];return r}};var po=require("@google/genai"),mo=require("@opentelemetry/api");var Z=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ae((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync(e){var c;let{userId:t,sessionId:n,stateDelta:r}=e,i=Vn(e.runConfig),s=e.newMessage,a=mo.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let l=await this.sessionService.getSession({appName:this.appName,userId:t,sessionId:n});if(!l)throw this.appName?new Error(`Session not found: ${n}`):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&E(this.agent)){let p=this.agent.canonicalModel.model;if(!re(p))throw new Error(`CFC is not supported for model: ${p} in agent: ${this.agent.name}`);fe(this.agent.codeExecutor)||(this.agent.codeExecutor=new ie)}let f=new B({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:rn(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),u=await this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:f});if(u&&(s=u),s){if(!((c=s.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(f.invocationId,l.userId,l.id,s),await this.sessionService.appendEvent({session:l,event:y({invocationId:f.invocationId,author:"user",actions:r?_({stateDelta:r}):void 0,content:s})})}f.agent=this.determineAgentForResumption(l,this.agent);let d=await this.pluginManager.runBeforeRunCallback({invocationContext:f});if(d){let p=y({invocationId:f.invocationId,author:"model",content:d});await this.sessionService.appendEvent({session:l,event:p}),yield p}else for await(let p of f.agent.runAsync(f)){p.partial||await this.sessionService.appendEvent({session:l,event:p});let g=await this.pluginManager.runOnEventCallback({invocationContext:f,event:p});g?yield g:yield p}await this.pluginManager.runAfterRunCallback({invocationContext:f})}finally{a.end()}}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=(0,po.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Br(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){m.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){m.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!E(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Br(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let c=o[a],l=T(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var Ve=class extends Z{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new se,sessionService:new V,memoryService:new j})}};var xe=require("@google/genai");var Ze=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(e){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var Yt=Symbol.for("google.adk.agentTool");function Co(o){return typeof o=="object"&&o!==null&&Yt in o&&o[Yt]===!0}var go,ho,ze=class extends(ho=I,go=Yt,ho){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[go]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(E(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:xe.Type.OBJECT,properties:{request:{type:xe.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let n=E(this.agent)&&this.agent.outputSchema;t.response=n?{type:xe.Type.OBJECT}:{type:xe.Type.STRING}}return t}async runAsync({args:t,toolContext:n}){var u,d;this.skipSummarization&&(n.actions.skipSummarization=!0);let i={role:"user",parts:[{text:E(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new Z({appName:this.agent.name,agent:this.agent,artifactService:new Ze(n),sessionService:new V,memoryService:new j,credentialService:n.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:n.state.toRecord()}),c;for await(let p of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i}))p.actions.stateDelta&&n.state.update(p.actions.stateDelta),c=p;if(!((d=(u=c==null?void 0:c.content)==null?void 0:u.parts)!=null&&d.length))return"";let l=E(this.agent)&&this.agent.outputSchema,f=c.content.parts.map(p=>p.text).filter(p=>p).join(`
85
- `);return l?JSON.parse(f):f}};var ce=class{constructor(e){this.toolFilter=e}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var Ae=class extends I{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.config=t.config||{},t.config.tools=t.config.tools||[],vn(t.model)){if(t.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");t.config.tools.push({googleSearchRetrieval:{}});return}if(Cn(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},vo=new Ae;var yo=`
86
-
87
- NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,Ye=class extends N{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=yo:e.description=yo.trimStart(),e}};var xo=require("@modelcontextprotocol/sdk/client/index.js"),Ao=require("@modelcontextprotocol/sdk/client/stdio.js"),Eo=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Ee=class{constructor(e){this.connectionParams=e}async createSession(){let e=new xo.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new Ao.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":let t=this.connectionParams.header?{requestInit:{headers:this.connectionParams.header}}:void 0;await e.connect(new Eo.StreamableHTTPClientTransport(new URL(this.connectionParams.url),t));break;default:let n=this.connectionParams;break}return e}};var M=require("@google/genai"),le=require("zod");var Vl=le.z.object({type:le.z.literal("object"),properties:le.z.record(le.z.unknown()).optional(),required:le.z.string().array().optional()});function Nr(o){if(!o)return M.Type.TYPE_UNSPECIFIED;switch(o.toLowerCase()){case"text":case"string":return M.Type.STRING;case"number":return M.Type.NUMBER;case"boolean":return M.Type.BOOLEAN;case"integer":return M.Type.INTEGER;case"array":return M.Type.ARRAY;case"object":return M.Type.OBJECT;default:return M.Type.TYPE_UNSPECIFIED}}function Ht(o){if(!o)return;function e(t){if(!t.type&&t.anyOf&&Array.isArray(t.anyOf)){let i=t.anyOf.find(s=>{let a=s.type;return a!=="null"&&a!=="NULL"});i&&(t=i)}t.type||(t.properties||t.$ref?t.type="object":t.items&&(t.type="array"));let n=Nr(t.type),r={type:n,description:t.description};if(n===M.Type.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else n===M.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var Te=class extends I{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){let e;return e={name:this.mcpTool.name,description:this.mcpTool.description,parameters:Ht(this.mcpTool.inputSchema),response:Ht(this.mcpTool.outputSchema)},e}async runAsync(e){let t=await this.mcpSessionManager.createSession(),n={};return n.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(n.params)}};var Qt=class extends ce{constructor(e,t=[]){super(t),this.mcpSessionManager=new Ee(e)}async getTools(e){let n=await(await this.mcpSessionManager.createSession()).listTools();m.debug(`number of tools: ${n.tools.length}`);for(let r of n.tools)m.debug(`tool: ${r.name}`);return n.tools.map(r=>new Te(r,this.mcpSessionManager))}async close(){}};var To=require("@google-cloud/storage"),Qe=require("@google/genai");var Xt=class{constructor(e){this.bucket=new To.Storage().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),n=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(He({...e,version:n}));if(e.artifact.inlineData)return await r.save(JSON.stringify(e.artifact.inlineData.data),{contentType:e.artifact.inlineData.mimeType}),n;if(e.artifact.text)return await r.save(e.artifact.text,{contentType:"text/plain"}),n;throw new Error("Artifact must have either inlineData or text.")}async loadArtifact(e){let t=e.version;if(t===void 0){let s=await this.listVersions(e);if(s.length===0)return;t=Math.max(...s)}let n=this.bucket.file(He({...e,version:t})),[[r],[i]]=await Promise.all([n.getMetadata(),n.download()]);return r.contentType==="text/plain"?(0,Qe.createPartFromText)(i.toString("utf-8")):(0,Qe.createPartFromBase64)(i.toString("base64"),r.contentType)}async listArtifactKeys(e){let t=[],n=`${e.appName}/${e.userId}/${e.sessionId}/`,r=`${e.appName}/${e.userId}/user/`,[[i],[s]]=await Promise.all([this.bucket.getFiles({prefix:n}),this.bucket.getFiles({prefix:r})]);for(let a of i)t.push(a.name.split("/").pop());for(let a of s)t.push(a.name.split("/").pop());return t.sort((a,c)=>a.localeCompare(c))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(n=>this.bucket.file(He({...e,version:n})).delete()))}async listVersions(e){let t=He(e),[n]=await this.bucket.getFiles({prefix:t}),r=[];for(let i of n){let s=i.name.split("/").pop();r.push(parseInt(s,10))}return r}};function He({appName:o,userId:e,sessionId:t,filename:n,version:r}){return n.startsWith("user:")?`${o}/${e}/user/${n}/${r}`:`${o}/${e}/${t}/${n}/${r}`}var Xe=require("@opentelemetry/api"),bo=require("@opentelemetry/api-logs"),We=require("@opentelemetry/sdk-logs"),Je=require("@opentelemetry/sdk-metrics"),So=require("@opentelemetry/resources"),Ro=require("@opentelemetry/sdk-trace-base"),Io=require("@opentelemetry/sdk-trace-node"),Po=require("@opentelemetry/exporter-trace-otlp-http"),wo=require("@opentelemetry/exporter-metrics-otlp-http"),ko=require("@opentelemetry/exporter-logs-otlp-http");function Fr(o=[],e){let t=e||Dr(),n=[...o,$r()],r=n.flatMap(a=>a.spanProcessors||[]),i=n.flatMap(a=>a.metricReaders||[]),s=n.flatMap(a=>a.logRecordProcessors||[]);if(r.length>0){let a=new Io.NodeTracerProvider({resource:t,spanProcessors:r});a.register(),Xe.trace.setGlobalTracerProvider(a)}if(i.length>0){let a=new Je.MeterProvider({readers:i,resource:t});Xe.metrics.setGlobalMeterProvider(a)}if(s.length>0){let a=new We.LoggerProvider({resource:t,processors:s});bo.logs.setGlobalLoggerProvider(a)}}function Dr(){return(0,So.detectResources)({detectors:[]})}function Gr(){return{enableTracing:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),enableMetrics:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT),enableLogging:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)}}function $r(o=Gr()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new Ro.BatchSpanProcessor(new Po.OTLPTraceExporter)]:[],metricReaders:t?[new Je.PeriodicExportingMetricReader({exporter:new wo.OTLPMetricExporter})]:[],logRecordProcessors:n?[new We.BatchLogRecordProcessor(new ko.OTLPLogExporter)]:[]}}var Lo=require("google-auth-library"),_o=require("@opentelemetry/sdk-metrics"),Oo=require("@opentelemetry/resources"),Mo=require("@opentelemetry/resource-detector-gcp"),Bo=require("@google-cloud/opentelemetry-cloud-trace-exporter"),No=require("@opentelemetry/sdk-trace-base"),Fo=require("@google-cloud/opentelemetry-cloud-monitoring-exporter");var qr="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Ur(){try{return await new Lo.GoogleAuth().getProjectId()||void 0}catch{return}}async function jr(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await Ur();return n?{spanProcessors:e?[new No.BatchSpanProcessor(new Bo.TraceExporter({projectId:n}))]:[],metricReaders:t?[new _o.PeriodicExportingMetricReader({exporter:new Fo.MetricExporter({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(m.warn(qr),{})}function Kr(){return(0,Oo.detectResources)({detectors:[Mo.gcpDetector]})}0&&(module.exports={ActiveStreamingTool,AgentTool,AuthCredentialTypes,BaseAgent,BaseCodeExecutor,BaseExampleProvider,BaseLlm,BaseLlmRequestProcessor,BaseLlmResponseProcessor,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,CallbackContext,FunctionTool,GOOGLE_SEARCH,GcsArtifactService,Gemini,GoogleLLMVariant,GoogleSearchTool,InMemoryArtifactService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LLMRegistry,LiveRequestQueue,LlmAgent,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,ParallelAgent,PluginManager,PolicyOutcome,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,ReadonlyContext,Runner,SecurityPlugin,SequentialAgent,State,StreamingMode,ToolConfirmation,ToolContext,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,hasTrailingCodeExecutionResult,isAgentTool,isBaseAgent,isBaseExampleProvider,isBaseLlm,isBaseTool,isFinalResponse,isFunctionTool,isGemini2OrAbove,isLlmAgent,isLoopAgent,isParallelAgent,isSequentialAgent,maybeSetOtelProviders,setLogLevel,stringifyContent,version,zodObjectToSchema});
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var index_exports = {};
27
+ __export(index_exports, {
28
+ DatabaseSessionService: () => import_database_session_service.DatabaseSessionService,
29
+ FileArtifactService: () => import_file_artifact_service.FileArtifactService,
30
+ GcsArtifactService: () => import_gcs_artifact_service.GcsArtifactService,
31
+ getArtifactServiceFromUri: () => import_registry.getArtifactServiceFromUri,
32
+ getSessionServiceFromUri: () => import_registry2.getSessionServiceFromUri
33
+ });
34
+ module.exports = __toCommonJS(index_exports);
35
+ var import_file_artifact_service = require("./artifacts/file_artifact_service.js");
36
+ var import_gcs_artifact_service = require("./artifacts/gcs_artifact_service.js");
37
+ var import_registry = require("./artifacts/registry.js");
38
+ __reExport(index_exports, require("./common.js"), module.exports);
39
+ var import_database_session_service = require("./sessions/database_session_service.js");
40
+ var import_registry2 = require("./sessions/registry.js");
41
+ __reExport(index_exports, require("./telemetry/google_cloud.js"), module.exports);
42
+ __reExport(index_exports, require("./telemetry/setup.js"), module.exports);
43
+ __reExport(index_exports, require("./tools/mcp/mcp_session_manager.js"), module.exports);
44
+ __reExport(index_exports, require("./tools/mcp/mcp_tool.js"), module.exports);
45
+ __reExport(index_exports, require("./tools/mcp/mcp_toolset.js"), module.exports);
88
46
  /**
89
47
  * @license
90
48
  * Copyright 2025 Google LLC
91
49
  * SPDX-License-Identifier: Apache-2.0
92
50
  */
93
- //# sourceMappingURL=index.js.map
51
+ // Annotate the CommonJS export names for ESM import in node:
52
+ 0 && (module.exports = {
53
+ DatabaseSessionService,
54
+ FileArtifactService,
55
+ GcsArtifactService,
56
+ getArtifactServiceFromUri,
57
+ getSessionServiceFromUri,
58
+ ...require("./common.js"),
59
+ ...require("./telemetry/google_cloud.js"),
60
+ ...require("./telemetry/setup.js"),
61
+ ...require("./tools/mcp/mcp_session_manager.js"),
62
+ ...require("./tools/mcp/mcp_tool.js"),
63
+ ...require("./tools/mcp/mcp_toolset.js")
64
+ });
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
@@ -67,7 +67,9 @@ class InMemoryMemoryService {
67
67
  if (!wordsInEvent.size) {
68
68
  continue;
69
69
  }
70
- const matchQuery = wordsInQuery.some((queryWord) => wordsInEvent.has(queryWord));
70
+ const matchQuery = wordsInQuery.some(
71
+ (queryWord) => wordsInEvent.has(queryWord)
72
+ );
71
73
  if (matchQuery) {
72
74
  response.memories.push({
73
75
  content: event.content,
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ "use strict";
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+ var apigee_llm_exports = {};
26
+ __export(apigee_llm_exports, {
27
+ ApigeeLlm: () => ApigeeLlm
28
+ });
29
+ module.exports = __toCommonJS(apigee_llm_exports);
30
+ var import_env_aware_utils = require("../utils/env_aware_utils.js");
31
+ var import_logger = require("../utils/logger.js");
32
+ var import_google_llm = require("./google_llm.js");
33
+ /**
34
+ * @license
35
+ * Copyright 2026 Google LLC
36
+ * SPDX-License-Identifier: Apache-2.0
37
+ */
38
+ const APIGEE_PROXY_URL_ENV_VARIABLE_NAME = "APIGEE_PROXY_URL";
39
+ class ApigeeLlm extends import_google_llm.Gemini {
40
+ constructor({
41
+ model,
42
+ proxyUrl,
43
+ apiKey,
44
+ vertexai,
45
+ location,
46
+ project,
47
+ headers
48
+ }) {
49
+ var _a;
50
+ if (!validateModel(model)) {
51
+ throw new Error(
52
+ `Model ${model} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`
53
+ );
54
+ }
55
+ super({
56
+ ...apigeeToGeminiInitParams({ model, vertexai, project, location, apiKey }),
57
+ headers
58
+ });
59
+ this.proxyUrl = proxyUrl != null ? proxyUrl : "";
60
+ if (!(0, import_env_aware_utils.isBrowser)() && !this.proxyUrl) {
61
+ this.proxyUrl = (_a = process.env[APIGEE_PROXY_URL_ENV_VARIABLE_NAME]) != null ? _a : "";
62
+ }
63
+ if (!this.proxyUrl) {
64
+ throw new Error(
65
+ `Proxy URL must be provided via the constructor or ${APIGEE_PROXY_URL_ENV_VARIABLE_NAME} environment variable.`
66
+ );
67
+ }
68
+ }
69
+ getHttpOptions() {
70
+ const opts = super.getHttpOptions();
71
+ opts.baseUrl = this.proxyUrl;
72
+ return opts;
73
+ }
74
+ getLiveHttpOptions() {
75
+ const opts = super.getLiveHttpOptions();
76
+ opts.baseUrl = this.proxyUrl;
77
+ return opts;
78
+ }
79
+ identifyApiVersion() {
80
+ const modelTrimmed = this.model.startsWith("apigee/") ? this.model.substring("apigee/".length) : this.model;
81
+ const components = modelTrimmed.split("/");
82
+ if (components.length === 3) {
83
+ return components[1];
84
+ }
85
+ if (components.length === 2) {
86
+ if (components[0] != "vertex_ai" && components[0] != "gemini" && components[0].startsWith("v")) {
87
+ return components[0];
88
+ }
89
+ }
90
+ return this.vertexai ? "v1beta1" : "v1alpha";
91
+ }
92
+ get liveApiVersion() {
93
+ if (!this._apigeeLiveApiVersion) {
94
+ this._apigeeLiveApiVersion = this.identifyApiVersion();
95
+ }
96
+ return this._apigeeLiveApiVersion;
97
+ }
98
+ async *generateContentAsync(llmRequest, stream = false) {
99
+ var _a;
100
+ const modelToUse = (_a = llmRequest.model) != null ? _a : this.model;
101
+ llmRequest.model = getModelId(modelToUse);
102
+ yield* super.generateContentAsync(llmRequest, stream);
103
+ }
104
+ async connect(llmRequest) {
105
+ var _a;
106
+ const modelToUse = (_a = llmRequest.model) != null ? _a : this.model;
107
+ llmRequest.model = getModelId(modelToUse);
108
+ return super.connect(llmRequest);
109
+ }
110
+ }
111
+ /**
112
+ * A list of model name patterns that are supported by this LLM.
113
+ *
114
+ * @returns A list of supported models.
115
+ */
116
+ ApigeeLlm.supportedModels = [
117
+ /apigee\/.*/
118
+ ];
119
+ function apigeeToGeminiInitParams({
120
+ model,
121
+ vertexai,
122
+ project,
123
+ location,
124
+ apiKey
125
+ }) {
126
+ var _a;
127
+ const params = (0, import_google_llm.geminiInitParams)({ model, vertexai, project, location, apiKey });
128
+ params.vertexai = params.vertexai || ((_a = params.model) == null ? void 0 : _a.startsWith("apigee/vertex_ai/"));
129
+ if (params.vertexai) {
130
+ return params;
131
+ }
132
+ if (!params.apiKey) {
133
+ import_logger.logger.warn(
134
+ `No API key provided when using a Gemini model, using a fake key "-".`
135
+ );
136
+ params.apiKey = "-";
137
+ }
138
+ return params;
139
+ }
140
+ function getModelId(model) {
141
+ if (!validateModel(model)) {
142
+ throw new Error(
143
+ `Model ${model} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`
144
+ );
145
+ }
146
+ const components = model.split("/");
147
+ return components[components.length - 1];
148
+ }
149
+ function validateModel(model) {
150
+ const validProviders = ["vertex_ai", "gemini"];
151
+ if (!model.startsWith("apigee/")) {
152
+ return false;
153
+ }
154
+ const modelPart = model.substring("apigee/".length);
155
+ if (modelPart.length === 0) {
156
+ return false;
157
+ }
158
+ const components = modelPart.split("/", -1);
159
+ if (components[components.length - 1].length === 0) {
160
+ return false;
161
+ }
162
+ if (components.length == 1) {
163
+ return true;
164
+ }
165
+ if (components.length == 2) {
166
+ if (validProviders.includes(components[0])) {
167
+ return true;
168
+ }
169
+ return components[0].startsWith("v");
170
+ }
171
+ if (components.length == 3) {
172
+ if (!validProviders.includes(components[0])) {
173
+ return false;
174
+ }
175
+ return components[1].startsWith("v");
176
+ }
177
+ return false;
178
+ }
179
+ // Annotate the CommonJS export names for ESM import in node:
180
+ 0 && (module.exports = {
181
+ ApigeeLlm
182
+ });
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
@@ -73,16 +73,20 @@ class BaseLlm {
73
73
  llmRequest.contents.push({
74
74
  role: "user",
75
75
  parts: [
76
- { text: "Handle the requests as specified in the System Instruction." }
76
+ {
77
+ text: "Handle the requests as specified in the System Instruction."
78
+ }
77
79
  ]
78
80
  });
79
81
  }
80
82
  if (((_a2 = llmRequest.contents[llmRequest.contents.length - 1]) == null ? void 0 : _a2.role) !== "user") {
81
83
  llmRequest.contents.push({
82
84
  role: "user",
83
- parts: [{
84
- text: "Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."
85
- }]
85
+ parts: [
86
+ {
87
+ text: "Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."
88
+ }
89
+ ]
86
90
  });
87
91
  }
88
92
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @license
3
- * Copyright 2025 Google LLC
3
+ * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6