@paean-ai/adk 0.2.14 → 0.2.15

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 (254) hide show
  1. package/dist/cjs/index.js +11 -11
  2. package/dist/cjs/index.js.map +3 -3
  3. package/dist/esm/index.js +11 -11
  4. package/dist/esm/index.js.map +3 -3
  5. package/dist/types/agents/llm_agent.d.ts +4 -0
  6. package/dist/web/index.js +1 -1
  7. package/dist/web/index.js.map +3 -3
  8. package/package.json +1 -1
  9. package/dist/cjs/agents/active_streaming_tool.js +0 -44
  10. package/dist/cjs/agents/base_agent.js +0 -245
  11. package/dist/cjs/agents/base_llm_processor.js +0 -44
  12. package/dist/cjs/agents/callback_context.js +0 -98
  13. package/dist/cjs/agents/content_processor_utils.js +0 -346
  14. package/dist/cjs/agents/functions.js +0 -385
  15. package/dist/cjs/agents/instructions.js +0 -110
  16. package/dist/cjs/agents/invocation_context.js +0 -107
  17. package/dist/cjs/agents/live_request_queue.js +0 -136
  18. package/dist/cjs/agents/llm_agent.js +0 -1212
  19. package/dist/cjs/agents/loop_agent.js +0 -68
  20. package/dist/cjs/agents/parallel_agent.js +0 -78
  21. package/dist/cjs/agents/readonly_context.js +0 -68
  22. package/dist/cjs/agents/run_config.js +0 -70
  23. package/dist/cjs/agents/sequential_agent.js +0 -84
  24. package/dist/cjs/agents/transcription_entry.js +0 -27
  25. package/dist/cjs/artifacts/base_artifact_service.js +0 -27
  26. package/dist/cjs/artifacts/gcs_artifact_service.js +0 -140
  27. package/dist/cjs/artifacts/in_memory_artifact_service.js +0 -119
  28. package/dist/cjs/auth/auth_credential.js +0 -46
  29. package/dist/cjs/auth/auth_handler.js +0 -92
  30. package/dist/cjs/auth/auth_schemes.js +0 -62
  31. package/dist/cjs/auth/auth_tool.js +0 -27
  32. package/dist/cjs/auth/credential_service/base_credential_service.js +0 -27
  33. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +0 -63
  34. package/dist/cjs/auth/exchanger/base_credential_exchanger.js +0 -40
  35. package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +0 -59
  36. package/dist/cjs/code_executors/base_code_executor.js +0 -76
  37. package/dist/cjs/code_executors/built_in_code_executor.js +0 -58
  38. package/dist/cjs/code_executors/code_execution_utils.js +0 -142
  39. package/dist/cjs/code_executors/code_executor_context.js +0 -198
  40. package/dist/cjs/common.js +0 -181
  41. package/dist/cjs/events/event.js +0 -119
  42. package/dist/cjs/events/event_actions.js +0 -83
  43. package/dist/cjs/examples/base_example_provider.js +0 -40
  44. package/dist/cjs/examples/example.js +0 -27
  45. package/dist/cjs/examples/example_util.js +0 -107
  46. package/dist/cjs/index_web.js +0 -33
  47. package/dist/cjs/memory/base_memory_service.js +0 -27
  48. package/dist/cjs/memory/in_memory_memory_service.js +0 -97
  49. package/dist/cjs/memory/memory_entry.js +0 -27
  50. package/dist/cjs/models/base_llm.js +0 -95
  51. package/dist/cjs/models/base_llm_connection.js +0 -27
  52. package/dist/cjs/models/gemini_llm_connection.js +0 -132
  53. package/dist/cjs/models/google_llm.js +0 -559
  54. package/dist/cjs/models/llm_request.js +0 -82
  55. package/dist/cjs/models/llm_response.js +0 -71
  56. package/dist/cjs/models/registry.js +0 -121
  57. package/dist/cjs/plugins/base_plugin.js +0 -236
  58. package/dist/cjs/plugins/logging_plugin.js +0 -222
  59. package/dist/cjs/plugins/plugin_manager.js +0 -239
  60. package/dist/cjs/plugins/security_plugin.js +0 -153
  61. package/dist/cjs/runner/in_memory_runner.js +0 -58
  62. package/dist/cjs/runner/runner.js +0 -277
  63. package/dist/cjs/sessions/base_session_service.js +0 -71
  64. package/dist/cjs/sessions/in_memory_session_service.js +0 -184
  65. package/dist/cjs/sessions/session.js +0 -48
  66. package/dist/cjs/sessions/state.js +0 -101
  67. package/dist/cjs/telemetry/google_cloud.js +0 -85
  68. package/dist/cjs/telemetry/setup.js +0 -97
  69. package/dist/cjs/telemetry/tracing.js +0 -231
  70. package/dist/cjs/tools/agent_tool.js +0 -134
  71. package/dist/cjs/tools/base_tool.js +0 -107
  72. package/dist/cjs/tools/base_toolset.js +0 -76
  73. package/dist/cjs/tools/forwarding_artifact_service.js +0 -71
  74. package/dist/cjs/tools/function_tool.js +0 -101
  75. package/dist/cjs/tools/google_search_tool.js +0 -76
  76. package/dist/cjs/tools/long_running_tool.js +0 -63
  77. package/dist/cjs/tools/mcp/mcp_session_manager.js +0 -65
  78. package/dist/cjs/tools/mcp/mcp_tool.js +0 -65
  79. package/dist/cjs/tools/mcp/mcp_toolset.js +0 -61
  80. package/dist/cjs/tools/tool_confirmation.js +0 -49
  81. package/dist/cjs/tools/tool_context.js +0 -129
  82. package/dist/cjs/utils/client_labels.js +0 -56
  83. package/dist/cjs/utils/deep_clone.js +0 -44
  84. package/dist/cjs/utils/env_aware_utils.js +0 -83
  85. package/dist/cjs/utils/gemini_schema_util.js +0 -88
  86. package/dist/cjs/utils/logger.js +0 -121
  87. package/dist/cjs/utils/model_name.js +0 -76
  88. package/dist/cjs/utils/simple_zod_to_json.js +0 -191
  89. package/dist/cjs/utils/variant_utils.js +0 -55
  90. package/dist/cjs/version.js +0 -39
  91. package/dist/esm/agents/active_streaming_tool.js +0 -14
  92. package/dist/esm/agents/base_agent.js +0 -214
  93. package/dist/esm/agents/base_llm_processor.js +0 -13
  94. package/dist/esm/agents/callback_context.js +0 -68
  95. package/dist/esm/agents/content_processor_utils.js +0 -315
  96. package/dist/esm/agents/functions.js +0 -344
  97. package/dist/esm/agents/instructions.js +0 -80
  98. package/dist/esm/agents/invocation_context.js +0 -76
  99. package/dist/esm/agents/live_request_queue.js +0 -106
  100. package/dist/esm/agents/llm_agent.js +0 -1180
  101. package/dist/esm/agents/loop_agent.js +0 -38
  102. package/dist/esm/agents/parallel_agent.js +0 -48
  103. package/dist/esm/agents/readonly_context.js +0 -38
  104. package/dist/esm/agents/run_config.js +0 -39
  105. package/dist/esm/agents/sequential_agent.js +0 -54
  106. package/dist/esm/agents/transcription_entry.js +0 -5
  107. package/dist/esm/artifacts/base_artifact_service.js +0 -5
  108. package/dist/esm/artifacts/gcs_artifact_service.js +0 -110
  109. package/dist/esm/artifacts/in_memory_artifact_service.js +0 -89
  110. package/dist/esm/auth/auth_credential.js +0 -16
  111. package/dist/esm/auth/auth_handler.js +0 -62
  112. package/dist/esm/auth/auth_schemes.js +0 -31
  113. package/dist/esm/auth/auth_tool.js +0 -5
  114. package/dist/esm/auth/credential_service/base_credential_service.js +0 -5
  115. package/dist/esm/auth/credential_service/in_memory_credential_service.js +0 -33
  116. package/dist/esm/auth/exchanger/base_credential_exchanger.js +0 -10
  117. package/dist/esm/auth/exchanger/credential_exchanger_registry.js +0 -29
  118. package/dist/esm/code_executors/base_code_executor.js +0 -46
  119. package/dist/esm/code_executors/built_in_code_executor.js +0 -28
  120. package/dist/esm/code_executors/code_execution_utils.js +0 -108
  121. package/dist/esm/code_executors/code_executor_context.js +0 -168
  122. package/dist/esm/common.js +0 -98
  123. package/dist/esm/events/event.js +0 -83
  124. package/dist/esm/events/event_actions.js +0 -52
  125. package/dist/esm/examples/base_example_provider.js +0 -10
  126. package/dist/esm/examples/example.js +0 -5
  127. package/dist/esm/examples/example_util.js +0 -76
  128. package/dist/esm/index_web.js +0 -6
  129. package/dist/esm/memory/base_memory_service.js +0 -5
  130. package/dist/esm/memory/in_memory_memory_service.js +0 -67
  131. package/dist/esm/memory/memory_entry.js +0 -5
  132. package/dist/esm/models/base_llm.js +0 -64
  133. package/dist/esm/models/base_llm_connection.js +0 -5
  134. package/dist/esm/models/gemini_llm_connection.js +0 -102
  135. package/dist/esm/models/google_llm.js +0 -533
  136. package/dist/esm/models/llm_request.js +0 -50
  137. package/dist/esm/models/llm_response.js +0 -41
  138. package/dist/esm/models/registry.js +0 -91
  139. package/dist/esm/plugins/base_plugin.js +0 -206
  140. package/dist/esm/plugins/logging_plugin.js +0 -192
  141. package/dist/esm/plugins/plugin_manager.js +0 -209
  142. package/dist/esm/plugins/security_plugin.js +0 -119
  143. package/dist/esm/runner/in_memory_runner.js +0 -28
  144. package/dist/esm/runner/runner.js +0 -247
  145. package/dist/esm/sessions/base_session_service.js +0 -41
  146. package/dist/esm/sessions/in_memory_session_service.js +0 -154
  147. package/dist/esm/sessions/session.js +0 -18
  148. package/dist/esm/sessions/state.js +0 -71
  149. package/dist/esm/telemetry/google_cloud.js +0 -54
  150. package/dist/esm/telemetry/setup.js +0 -67
  151. package/dist/esm/telemetry/tracing.js +0 -195
  152. package/dist/esm/tools/agent_tool.js +0 -104
  153. package/dist/esm/tools/base_tool.js +0 -77
  154. package/dist/esm/tools/base_toolset.js +0 -46
  155. package/dist/esm/tools/forwarding_artifact_service.js +0 -41
  156. package/dist/esm/tools/function_tool.js +0 -71
  157. package/dist/esm/tools/google_search_tool.js +0 -46
  158. package/dist/esm/tools/long_running_tool.js +0 -33
  159. package/dist/esm/tools/mcp/mcp_session_manager.js +0 -35
  160. package/dist/esm/tools/mcp/mcp_tool.js +0 -35
  161. package/dist/esm/tools/mcp/mcp_toolset.js +0 -31
  162. package/dist/esm/tools/tool_confirmation.js +0 -19
  163. package/dist/esm/tools/tool_context.js +0 -99
  164. package/dist/esm/utils/client_labels.js +0 -26
  165. package/dist/esm/utils/deep_clone.js +0 -14
  166. package/dist/esm/utils/env_aware_utils.js +0 -49
  167. package/dist/esm/utils/gemini_schema_util.js +0 -58
  168. package/dist/esm/utils/logger.js +0 -89
  169. package/dist/esm/utils/model_name.js +0 -41
  170. package/dist/esm/utils/simple_zod_to_json.js +0 -160
  171. package/dist/esm/utils/variant_utils.js +0 -24
  172. package/dist/esm/version.js +0 -9
  173. package/dist/web/agents/active_streaming_tool.js +0 -14
  174. package/dist/web/agents/base_agent.js +0 -265
  175. package/dist/web/agents/base_llm_processor.js +0 -13
  176. package/dist/web/agents/callback_context.js +0 -68
  177. package/dist/web/agents/content_processor_utils.js +0 -315
  178. package/dist/web/agents/functions.js +0 -344
  179. package/dist/web/agents/instructions.js +0 -80
  180. package/dist/web/agents/invocation_context.js +0 -76
  181. package/dist/web/agents/live_request_queue.js +0 -124
  182. package/dist/web/agents/llm_agent.js +0 -1310
  183. package/dist/web/agents/loop_agent.js +0 -71
  184. package/dist/web/agents/parallel_agent.js +0 -83
  185. package/dist/web/agents/readonly_context.js +0 -38
  186. package/dist/web/agents/run_config.js +0 -54
  187. package/dist/web/agents/sequential_agent.js +0 -99
  188. package/dist/web/agents/transcription_entry.js +0 -5
  189. package/dist/web/artifacts/base_artifact_service.js +0 -5
  190. package/dist/web/artifacts/gcs_artifact_service.js +0 -126
  191. package/dist/web/artifacts/in_memory_artifact_service.js +0 -89
  192. package/dist/web/auth/auth_credential.js +0 -16
  193. package/dist/web/auth/auth_handler.js +0 -62
  194. package/dist/web/auth/auth_schemes.js +0 -31
  195. package/dist/web/auth/auth_tool.js +0 -5
  196. package/dist/web/auth/credential_service/base_credential_service.js +0 -5
  197. package/dist/web/auth/credential_service/in_memory_credential_service.js +0 -33
  198. package/dist/web/auth/exchanger/base_credential_exchanger.js +0 -10
  199. package/dist/web/auth/exchanger/credential_exchanger_registry.js +0 -29
  200. package/dist/web/code_executors/base_code_executor.js +0 -46
  201. package/dist/web/code_executors/built_in_code_executor.js +0 -28
  202. package/dist/web/code_executors/code_execution_utils.js +0 -105
  203. package/dist/web/code_executors/code_executor_context.js +0 -168
  204. package/dist/web/common.js +0 -98
  205. package/dist/web/events/event.js +0 -101
  206. package/dist/web/events/event_actions.js +0 -67
  207. package/dist/web/examples/base_example_provider.js +0 -10
  208. package/dist/web/examples/example.js +0 -5
  209. package/dist/web/examples/example_util.js +0 -75
  210. package/dist/web/index_web.js +0 -6
  211. package/dist/web/memory/base_memory_service.js +0 -5
  212. package/dist/web/memory/in_memory_memory_service.js +0 -67
  213. package/dist/web/memory/memory_entry.js +0 -5
  214. package/dist/web/models/base_llm.js +0 -64
  215. package/dist/web/models/base_llm_connection.js +0 -5
  216. package/dist/web/models/gemini_llm_connection.js +0 -120
  217. package/dist/web/models/google_llm.js +0 -574
  218. package/dist/web/models/llm_request.js +0 -50
  219. package/dist/web/models/llm_response.js +0 -41
  220. package/dist/web/models/registry.js +0 -91
  221. package/dist/web/plugins/base_plugin.js +0 -206
  222. package/dist/web/plugins/logging_plugin.js +0 -192
  223. package/dist/web/plugins/plugin_manager.js +0 -209
  224. package/dist/web/plugins/security_plugin.js +0 -119
  225. package/dist/web/runner/in_memory_runner.js +0 -28
  226. package/dist/web/runner/runner.js +0 -278
  227. package/dist/web/sessions/base_session_service.js +0 -41
  228. package/dist/web/sessions/in_memory_session_service.js +0 -154
  229. package/dist/web/sessions/session.js +0 -18
  230. package/dist/web/sessions/state.js +0 -87
  231. package/dist/web/telemetry/google_cloud.js +0 -54
  232. package/dist/web/telemetry/setup.js +0 -67
  233. package/dist/web/telemetry/tracing.js +0 -210
  234. package/dist/web/tools/agent_tool.js +0 -118
  235. package/dist/web/tools/base_tool.js +0 -77
  236. package/dist/web/tools/base_toolset.js +0 -46
  237. package/dist/web/tools/forwarding_artifact_service.js +0 -41
  238. package/dist/web/tools/function_tool.js +0 -71
  239. package/dist/web/tools/google_search_tool.js +0 -46
  240. package/dist/web/tools/long_running_tool.js +0 -50
  241. package/dist/web/tools/mcp/mcp_session_manager.js +0 -35
  242. package/dist/web/tools/mcp/mcp_tool.js +0 -35
  243. package/dist/web/tools/mcp/mcp_toolset.js +0 -31
  244. package/dist/web/tools/tool_confirmation.js +0 -19
  245. package/dist/web/tools/tool_context.js +0 -99
  246. package/dist/web/utils/client_labels.js +0 -26
  247. package/dist/web/utils/deep_clone.js +0 -14
  248. package/dist/web/utils/env_aware_utils.js +0 -49
  249. package/dist/web/utils/gemini_schema_util.js +0 -58
  250. package/dist/web/utils/logger.js +0 -89
  251. package/dist/web/utils/model_name.js +0 -41
  252. package/dist/web/utils/simple_zod_to_json.js +0 -174
  253. package/dist/web/utils/variant_utils.js +0 -24
  254. package/dist/web/version.js +0 -9
@@ -348,6 +348,10 @@ export declare class LlmAgent extends BaseAgent {
348
348
  * @throws Error if the agent is not found.
349
349
  */
350
350
  private getAgentByName;
351
+ private static readonly LLM_TRANSIENT_ERROR_MAX_RETRIES;
352
+ private static readonly LLM_TRANSIENT_ERROR_BASE_DELAY_MS;
353
+ private static readonly LLM_TRANSIENT_ERROR_MAX_DELAY_MS;
354
+ private static readonly LLM_RETRYABLE_ERROR_CODES;
351
355
  private callLlmAsync;
352
356
  private handleBeforeModelCallback;
353
357
  private handleAfterModelCallback;
package/dist/web/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- var In=Object.defineProperty,Rn=Object.defineProperties;var wn=Object.getOwnPropertyDescriptors;var Nt=Object.getOwnPropertySymbols;var kn=Object.prototype.hasOwnProperty,Pn=Object.prototype.propertyIsEnumerable;var Ve=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var Mt=(o,e,t)=>e in o?In(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,x=(o,e)=>{for(var t in e||(e={}))kn.call(e,t)&&Mt(o,t,e[t]);if(Nt)for(var t of Nt(e))Pn.call(e,t)&&Mt(o,t,e[t]);return o},pe=(o,e)=>Rn(o,wn(e));var u=function(o,e){this[0]=o,this[1]=e},A=(o,e,t)=>{var n=(s,a,c,l)=>{try{var f=t[s](a),d=(a=f.value)instanceof u,h=f.done;Promise.resolve(d?a[0]:a).then(v=>d?n(s==="return"?s:"next",a[1]?{done:v.done,value:v.value}:v,c,l):c({value:v,done:h})).catch(v=>n("throw",v,c,l))}catch(v){l(v)}},r=s=>i[s]=a=>new Promise((c,l)=>n(s,a,c,l)),i={};return t=t.apply(o,e),i[Ve("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var T=(o,e,t)=>(e=o[Ve("asyncIterator")])?e.call(o):(o=o[Ve("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,a,c)=>(i=r.call(o,i),c=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:c}),a)))),t("next"),t("return"),e);import{trace as Dt}from"@opentelemetry/api";function H(o={}){return x({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function Bt(o,e){let t=H();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 L(o={}){return pe(x({},o),{id:o.id||Ze(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||H(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function ge(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:M(o).length===0&&V(o).length===0&&!o.partial&&!Ot(o)}function M(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 V(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 Ot(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 Ln(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 Ft="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Ze(){let o="";for(let e=0;e<8;e++)o+=Ft[Math.floor(Math.random()*Ft.length)];return o}var I=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=x(x({},this.delta),e),this.value=x(x({},this.value),e)}toRecord(){return x(x({},this.value),this.delta)}};I.APP_PREFIX="app:",I.USER_PREFIX="user:",I.TEMP_PREFIX="temp:";var j=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 I(this.invocationContext.session.state,{})}};var Z=class extends j{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||H(),this._state=new I(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 Pe(){return typeof window<"u"}var ke="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function me(){let o="";for(let e=0;e<ke.length;e++){let t=Math.random()*16|0;ke[e]==="x"?o+=t.toString(16):ke[e]==="y"?o+=(t&3|8).toString(16):o+=ke[e]}return o}function $t(o){return Pe()?window.atob(o):Buffer.from(o,"base64").toString()}var We=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 ".concat(e.maxLlmCalls," exceeded"))}},J=class{constructor(e){this.invocationCostManager=new We;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 Gt(){return"e-".concat(me())}var Q=class{constructor(e){this.name=_n(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Mn(this),this.beforeAgentCallback=qt(e.beforeAgentCallback),this.afterAgentCallback=qt(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return A(this,null,function*(){let t=Dt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let a=this.createInvocationContext(e),c=yield new u(this.handleBeforeAgentCallback(a));if(c&&(yield c),a.endInvocation)return;try{for(var n=T(this.runAsyncImpl(a)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let f=i.value;yield f}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a.endInvocation)return;let l=yield new u(this.handleAfterAgentCallback(a));l&&(yield l)}finally{t.end()}})}runLive(e){return A(this,null,function*(){let t=Dt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(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 J(pe(x({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new Z({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,L({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return L({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new Z({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return L({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return L({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 "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function _n(o){if(!Nn(o))throw new Error('Found invalid agent name: "'.concat(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 Nn(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function Mn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function qt(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Gn}from"@google/genai";var be=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 ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(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 ".concat(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 ie=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var oe=class extends Z{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new be(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new be(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 ie({hint:e,confirmed:!1,payload:t})}};var Ut=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Ut||{}),he=1;function Bn(o){he=o}var ze=class{log(e,...t){if(!(e<he))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: ".concat(e))}}debug(...e){he>0||console.debug(Le(0),...e)}info(...e){he>1||console.info(Le(1),...e)}warn(...e){he>2||console.warn(Le(2),...e)}error(...e){he>3||console.error(Le(3),...e)}},Fn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},On={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},$n="\x1B[0m";function Le(o){return"".concat(On[o],"[ADK ").concat(Fn[o],"]:").concat($n)}var p=new ze;var Qe="adk-",_e="adk_request_credential",Ce="adk_request_confirmation",Dn={handleFunctionCallList:Ne};function Ye(){return"".concat(Qe).concat(me())}function jt(o){let e=M(o);if(e)for(let t of e)t.id||(t.id=Ye())}function Kt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Qe)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Qe)&&(e.functionResponse.id=void 0)}function Vt(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 Zt(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:_e,args:{function_call_id:i,auth_config:s},id:Ye()};n.add(a.id),t.push({functionCall:a})}return L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Wt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=M(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(h=>h.id===c))!=null?a:void 0;if(!f)continue;let d={name:Ce,args:{originalFunctionCall:f,toolConfirmation:l},id:Ye()};r.add(d.id),n.push({functionCall:d})}return L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function qn(o,e,t){return p.debug("callToolAsync ".concat(o.name)),await o.runAsync({args:e,toolContext:t})}async function zt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=M(e);return await Ne({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ne({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(d=>!i||d.id&&i.has(d.id));for(let d of c){let h;s&&d.id&&(h=s[d.id]);let{tool:v,toolContext:g}=Un({invocationContext:o,functionCall:d,toolsDict:t,toolConfirmation:h});p.debug("execute_tool ".concat(v.name));let C=(f=d.args)!=null?f:{},m=null,y;if(m=await o.pluginManager.runBeforeToolCallback({tool:v,toolArgs:C,toolContext:g}),m==null){for(let B of n)if(m=await B({tool:v,args:C,context:g}),m)break}if(m==null)try{m=await qn(v,C,g)}catch(B){if(B instanceof Error){let xe=await o.pluginManager.runOnToolErrorCallback({tool:v,toolArgs:C,toolContext:g,error:B});xe?m=xe:y=B.message}else y=B}let k=await o.pluginManager.runAfterToolCallback({tool:v,toolArgs:C,toolContext:g,result:m});if(k==null){for(let B of r)if(k=await B({tool:v,args:C,context:g,response:m}),k)break}if(k!=null&&(m=k),v.isLongRunning&&!m)continue;y?m={error:y}:(typeof m!="object"||m==null)&&(m={result:m});let N=L({invocationId:o.invocationId,author:o.agent.name,content:Gn({functionResponse:{id:g.functionCallId,name:v.name,response:m}}),actions:g.actions,branch:o.branch});p.debug("traceToolCall",{tool:v.name,args:C,functionResponseEvent:N.id}),a.push(N)}if(!a.length)return null;let l=jn(a);return a.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Un({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new oe({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function jn(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=Bt(n);return L({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var He=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:{}})}[Symbol.asyncIterator](){return A(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as hn}from"zod";var re=class{constructor(){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 Kn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Me(o){let e=o.match(Kn);return e?e[1]:o}function Qt(o){return Me(o).startsWith("gemini-")}function Yt(o){return Me(o).startsWith("gemini-1")}function Ht(o){return Me(o).startsWith("gemini-2")}function Xt(o){let e=Me(o);return e.startsWith("gemini-3")&&e.includes("preview")}var ve=class extends re{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Ht(e.model)){e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({codeExecution:{}});return}throw new Error("Gemini code execution tool is not supported for model ".concat(e.model))}};import{Language as Vn,Outcome as Jt}from"@google/genai";function W(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function en(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let d=0;d<o.parts.length;d++){let h=o.parts[d];if(h.executableCode&&(d===o.parts.length-1||!o.parts[d+1].codeExecutionResult))return o.parts=o.parts.slice(0,d+1),h.executableCode.code}let t=o.parts.filter(d=>d.text);if(!t.length)return"";let n=W(t[0]),r=t.map(d=>d.text).join("\n"),i=e.map(d=>d[0]).join("|"),s=e.map(d=>d[1]).join("|"),a=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(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(Xe(l)),l):""}function Xe(o){return{text:o,executableCode:{code:o,language:Vn.PYTHON}}}function tn(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:Jt.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push("Code execution result:\n".concat(o.stdout,"\n")),o.outputFiles&&e.push("Saved artifacts:\n"+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:Jt.OUTCOME_OK}}}function nn(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 Je="_code_execution_context",et="execution_session_id",se="processed_input_files",ae="_code_executor_input_files",ce="_code_executor_error_counts",tt="_code_execution_results",Se=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Je))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Je]:W(this.context)}}getExecutionId(){if(et in this.context)return this.context[et]}setExecutionId(e){this.context[et]=e}getProcessedFileNames(){return se in this.context?this.context[se]:[]}addProcessedFileNames(e){se in this.context||(this.context[se]=[]),this.context[se].push(...e)}getInputFiles(){return ae in this.sessionState?this.sessionState.get(ae):[]}addInputFiles(e){ae in this.sessionState||this.sessionState.set(ae,[]),this.sessionState.get(ae).push(...e)}clearInputFiles(){ae in this.sessionState&&this.sessionState.set(ae,[]),se in this.context&&(this.context[se]=[])}getErrorCount(e){return ce in this.sessionState&&this.sessionState.get(ce)[e]||0}incrementErrorCount(e){ce in this.sessionState||this.sessionState.set(ce,{}),this.sessionState.get(ce)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(ce in this.sessionState))return;let t=this.sessionState.get(ce);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){tt in this.sessionState||this.sessionState.set(tt,{});let i=this.sessionState.get(tt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(Je)||{}}};var nt="0.2.4";var Zn="google-adk",Wn="gl-typescript",zn="remote_reasoning_engine",Qn="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Yn(){let o="".concat(Zn,"/").concat(nt);!Pe()&&process.env[Qn]&&(o="".concat(o,"+").concat(zn));let e="".concat(Wn,"/").concat(Pe()?window.navigator.userAgent:process.version);return[o,e]}function on(){return Yn()}var ot=Symbol("baseModel");function rt(o){return typeof o=="object"&&o!==null&&ot in o&&o[ot]===!0}var rn;rn=ot;var ye=class{constructor({model:e}){this[rn]=!0;this.model=e}get trackingHeaders(){let t=on().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."}]})}};ye.supportedModels=[];function Te(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function sn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as st,FinishReason as Jn,GoogleGenAI as at}from"@google/genai";function an(){return Hn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Hn(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"}):p.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);p.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else p.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){p.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return A(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function it(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 eo="https://aiplatform.googleapis.com/v1/publishers/google",Ae=class extends ye{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=Xt(e);let c=typeof process=="object";this.apiEndpoint=a,!this.apiEndpoint&&c&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&(this.apiEndpoint=eo,p.info("Using Gemini 3 preview endpoint: ".concat(this.apiEndpoint)));let l=!!n;if(!l&&c){let f=process.env.GOOGLE_GENAI_USE_VERTEXAI;f&&(l=f.toLowerCase()==="true"||f==="1")}if(this.isGemini3Preview&&l){let f=t||(c?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);f?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(c&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),c&&!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&&c&&(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.")}generateContentAsync(e,t=!1){return A(this,null,function*(){var n,r,i,s,a,c,l,f,d,h,v,k,N,B,xe,_t;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=x(x({},e.config.httpOptions.headers),this.trackingHeaders)),t){let q=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),b="",E,R="",X,F;this.isGemini3Preview&&this.cachedThoughtSignature&&p.info("[Gemini3] Starting new request with CACHED thoughtSignature (length: ".concat(this.cachedThoughtSignature.length,")"));try{for(var g=T(q),C,m,y;C=!(m=yield new u(g.next())).done;C=!1){let P=m.value;F=P;let S=it(P);X=S.usageMetadata;let K=(s=(i=S.content)==null?void 0:i.parts)==null?void 0:s[0],Ke=(c=(a=S.content)==null?void 0:a.parts)==null?void 0:c.some($=>$.functionCall);if(this.isGemini3Preview&&((l=S.content)!=null&&l.parts)){for(let $ of S.content.parts)if($.thoughtSignature&&!E){E=$.thoughtSignature,this.cachedThoughtSignature=E,p.info("[Gemini3] Captured and CACHED thoughtSignature from response part (length: ".concat(E.length,")"));break}}if(K!=null&&K.text){if("thought"in K&&K.thought?(b+=K.text,"thoughtSignature"in K&&K.thoughtSignature&&(E=K.thoughtSignature,this.cachedThoughtSignature=E,p.info("[Gemini3] Captured and CACHED thoughtSignature from thought part (length: ".concat(E.length,")")))):R+=K.text,S.partial=!0,this.isGemini3Preview&&Ke){let $=(d=(f=S.content)==null?void 0:f.parts)==null?void 0:d.some(O=>O.thoughtSignature);p.info("[Gemini3] Chunk has thought AND function calls. Response has signature: ".concat($)),b="",E=void 0,R=""}}else if((b||R)&&(!K||!K.inlineData))if(this.isGemini3Preview&&Ke&&S.content){p.info("[Gemini3] Merging thought with function calls. Has accumulated signature: ".concat(!!E));let $=[];if(b){let O={text:b,thought:!0};E&&(O.thoughtSignature=E),$.push(O),p.info("[Gemini3] Created thought part with signature: ".concat(!!E))}if(R&&$.push(st(R)),!b&&E){let O=!1;for(let U of S.content.parts||[])U.functionCall&&!O&&(U.thoughtSignature||(U.thoughtSignature=E,p.info("[Gemini3] Applied accumulated signature to first function call: ".concat(U.functionCall.name))),O=!0)}S.content.parts=[...$,...S.content.parts||[]],p.info("[Gemini3] Final merged content has ".concat(S.content.parts.length," parts"));for(let O=0;O<S.content.parts.length;O++){let U=S.content.parts[O];p.info("[Gemini3] Part ".concat(O,": thought=").concat(!!U.thought,", functionCall=").concat(((h=U.functionCall)==null?void 0:h.name)||"none",", hasSignature=").concat(!!U.thoughtSignature))}b="",E=void 0,R=""}else{let $=[];if(b){let O={text:b,thought:!0};E&&(O.thoughtSignature=E),$.push(O)}R&&$.push(st(R)),yield{content:{role:"model",parts:$},usageMetadata:S.usageMetadata},b="",E=void 0,R=""}if(this.isGemini3Preview&&Ke&&((v=S.content)!=null&&v.parts)){if(!S.content.parts.some(D=>D.thoughtSignature)&&E){for(let D of S.content.parts)if(D.functionCall){D.thoughtSignature=E,p.info("[Gemini3] Applied cached signature to first function call: ".concat(D.functionCall.name));break}}let O=S.content.parts.filter(D=>D.functionCall).map(D=>D.functionCall.name),U=S.content.parts.filter(D=>D.thoughtSignature).length;if(U===0){let D=E||this.cachedThoughtSignature;if(D){for(let we of S.content.parts)if(we.functionCall&&!we.thoughtSignature){we.thoughtSignature=D,p.info("[Gemini3] Applied CACHED signature to function call: ".concat(we.functionCall.name," (API didn't return new signature, using ").concat(E?"local":"class-level"," cache)")),U=1;break}}}p.info("[Gemini3] Yielding function call response: calls=[".concat(O.join(", "),"], partsWithSignature=").concat(U)),U===0&&p.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}yield S}}catch(m){y=[m]}finally{try{C&&(m=g.return)&&(yield new u(m.call(g)))}finally{if(y)throw y[0]}}if((R||b)&&((N=(k=F==null?void 0:F.candidates)==null?void 0:k[0])==null?void 0:N.finishReason)===Jn.STOP){let P=[];if(b){let S={text:b,thought:!0};E&&(S.thoughtSignature=E),P.push(S)}R&&P.push({text:R}),yield{content:{role:"model",parts:P},usageMetadata:X}}}else{let q=yield new u(this.apiClient.models.generateContent({model:(B=e.model)!=null?B:this.model,contents:e.contents,config:e.config})),b=it(q);if(this.isGemini3Preview&&((xe=b.content)!=null&&xe.parts)){let E,R=!1;for(let F of b.content.parts)if(F.thoughtSignature){E=F.thoughtSignature,this.cachedThoughtSignature=E,F.thought&&(R=!0);break}if(p.info("[Gemini3] Non-streaming response: hasSignature=".concat(!!E,", hasThoughtPart=").concat(R,", hasCachedSig=").concat(!!this.cachedThoughtSignature)),E&&!R){let F=!1;for(let P of b.content.parts)P.functionCall&&(!F&&!P.thoughtSignature&&(P.thoughtSignature=E,p.info("[Gemini3] Applied signature to first function call: ".concat(P.functionCall.name))),F=!0)}if(b.content.parts.some(F=>F.functionCall)){let F=b.content.parts.filter(P=>P.thoughtSignature).length;if(F===0&&this.cachedThoughtSignature){for(let P of b.content.parts)if(P.functionCall&&!P.thoughtSignature){P.thoughtSignature=this.cachedThoughtSignature,p.info("[Gemini3] Applied CACHED signature to function call: ".concat(P.functionCall.name," (API didn't return new signature)")),F=1;break}}for(let P=0;P<b.content.parts.length;P++){let S=b.content.parts[P];p.info("[Gemini3] Response Part ".concat(P,": thought=").concat(!!S.thought,", functionCall=").concat(((_t=S.functionCall)==null?void 0:_t.name)||"none",", hasSignature=").concat(!!S.thoughtSignature))}F===0&&p.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}}yield b}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=x(x({},this.trackingHeaders),this.headers);if(this.vertexai)this._apiClient=new at({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,p.debug("Using custom API endpoint: ".concat(this.apiEndpoint)),this.isGemini3Preview&&(t.apiVersion="",p.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new at({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return 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(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};this.apiEndpoint&&(e.baseUrl=this.apiEndpoint,this.isGemini3Preview&&(e.apiVersion="")),this._liveApiClient=new at({apiKey:this.apiKey,httpOptions:e})}return 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.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[st(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)cn(n.inlineData),cn(n.fileData)}}};Ae.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function cn(o){o&&o.displayName&&(o.displayName=void 0)}var ct=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)}},z=class z{static newLlm(e){return new(z.resolve(e))({model:e})}static _register(e,t){z.llmRegistryDict.has(e)&&p.info("Updating LLM class for ".concat(e," from ").concat(z.llmRegistryDict.get(e)," to ").concat(t)),z.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)z._register(t,e)}static resolve(e){let t=z.resolveCache.get(e);if(t)return t;for(let[n,r]of z.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return z.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};z.llmRegistryDict=new Map,z.resolveCache=new ct(32);var Ee=z;Ee.register(Ae);var Y=class{constructor(e){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=to(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 an()}};function to(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as no}from"@google/genai";import{ZodObject as oo}from"zod";import{Type as G}from"@google/genai";import{z as _}from"zod";function ln(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function ee(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 _.ZodFirstPartyTypeKind.ZodString:n.type=G.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 _.ZodFirstPartyTypeKind.ZodNumber:n.type=G.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=G.INTEGER);return r(n);case _.ZodFirstPartyTypeKind.ZodBoolean:return n.type=G.BOOLEAN,r(n);case _.ZodFirstPartyTypeKind.ZodArray:return n.type=G.ARRAY,n.items=ee(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case _.ZodFirstPartyTypeKind.ZodObject:return Fe(o);case _.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=G.STRING;else if(i==="number")n.type=G.NUMBER;else if(i==="boolean")n.type=G.BOOLEAN;else if(e.value===null)n.type=G.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case _.ZodFirstPartyTypeKind.ZodEnum:return n.type=G.STRING,n.enum=e.values,r(n);case _.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=G.STRING,n.enum=Object.values(e.values),r(n);case _.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(ee),r(n);case _.ZodFirstPartyTypeKind.ZodOptional:return ee(e.innerType);case _.ZodFirstPartyTypeKind.ZodNullable:let s=ee(e.innerType);return r(s?x({anyOf:[s,{type:G.NULL}]},t&&{description:t}):x({type:G.NULL},t&&{description:t}));case _.ZodFirstPartyTypeKind.ZodDefault:let a=ee(e.innerType);return a&&(a.default=e.defaultValue()),a;case _.ZodFirstPartyTypeKind.ZodBranded:return ee(e.type);case _.ZodFirstPartyTypeKind.ZodReadonly:return ee(e.innerType);case _.ZodFirstPartyTypeKind.ZodNull:return n.type=G.NULL,r(n);case _.ZodFirstPartyTypeKind.ZodAny:case _.ZodFirstPartyTypeKind.ZodUnknown:return r(x({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function Fe(o){if(o._def.typeName!==_.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=ee(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===_.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===_.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==_.ZodFirstPartyTypeKind.ZodNever?i=ee(r)||!0:i=o._def.unknownKeys==="passthrough",x({type:G.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function ro(o){return o===void 0?{type:no.OBJECT,properties:{}}:ln(o)?Fe(o):o}var te=class extends Y{constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:ro(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof oo&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var ne=class{};function lt(o,e,t){var c,l,f,d,h,v;let n=[];for(let g of o)!((c=g.content)!=null&&c.role)||!((l=g.content.parts)!=null&&l.length)||t&&g.branch&&!t.startsWith(g.branch)||io(g)||so(g)||n.push(dn(e,g)?ao(g):g);let r=co(n);r=lo(r);let i=[];for(let g of r){let C=W(g.content);Kt(C),i.push(C)}let s=!1,a=-1;for(let g=0;g<i.length;g++){let C=i[g],m=(f=C.parts)==null?void 0:f.some(N=>N.functionCall),y=(d=C.parts)==null?void 0:d.some(N=>N.thoughtSignature),k=(h=C.parts)==null?void 0:h.some(N=>N.thought);if(m){p.info("[getContents] Content block ".concat(g+1,"/").concat(i.length,": role=").concat(C.role,", ")+"hasFunctionCalls=true, hasThought=".concat(k,", hasSignature=").concat(y)),!y&&C.role==="model"&&(s=!0,a=g+1);for(let N=0;N<(((v=C.parts)==null?void 0:v.length)||0);N++){let B=C.parts[N];B.functionCall?p.info("[getContents] Part ".concat(N,": functionCall=").concat(B.functionCall.name,", ")+"hasSignature=".concat(!!B.thoughtSignature)):B.thought&&p.info("[getContents] Part ".concat(N,": thought=true, hasSignature=").concat(!!B.thoughtSignature))}}}return s&&p.warn("[getContents] WARNING: Content block ".concat(a," has model function calls but NO thoughtSignature! ")+"This will likely cause a 400 error from Gemini 3 API."),i}function fn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||dn(e,r))return lt(o.slice(n),e,t)}return[]}function io(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)===_e||((n=r.functionResponse)==null?void 0:n.name)===_e)return!0;return!1}function so(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)===Ce||((n=r.functionResponse)==null?void 0:n.name)===Ce)return!0;return!1}function dn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function ao(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:"[".concat(o.author,"] said: ").concat(c.text)});else if(c.functionCall){let l=un(c.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(c.functionCall.name,"` with parameters: ").concat(l)})}else if(c.functionResponse){let l=un(c.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(c.functionResponse.name,"` returned result: ").concat(l)})}else(a=e.parts)==null||a.push(c);return L({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function pn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=L(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 co(o){if(o.length===0)return o;let e=o[o.length-1],t=V(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=M(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=M(l);if(f!=null&&f.length){for(let d of f)if(d.id&&n.has(d.id)){i=c;let h=new Set(f.map(g=>g.id).filter(g=>!!g));if(!Array.from(n).every(g=>h.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 : ".concat(Array.from(h).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=h;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=V(l);f&&f.some(d=>d.id&&n.has(d.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(pn(s)),a}function lo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=V(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(V(n).length>0)continue;let r=M(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(pn(a))}}else t.push(n)}return t}function un(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function ut(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 d=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let h=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:d});if(!h)throw new Error("Artifact ".concat(d," not found."));return String(h)}if(!po(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: `".concat(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 uo=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function gn(o){return o===""||o===void 0?!1:uo.test(o)}var fo=[I.APP_PREFIX,I.USER_PREFIX,I.TEMP_PREFIX];function po(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?gn(o):fo.includes(e[0]+":")?gn(e[1]):!1}var ft=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(ft||{});function mn(o={}){return x({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:go(o.maxLlmCalls||500)},o)}function go(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return o<=0&&p.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 Cn="adk_agent_name";async function vn(o,e){return o instanceof Y?[o]:await o.getTools(e)}var dt=class extends ne{runAsync(e,t){return A(this,null,function*(){var r;let n=e.agent;n instanceof w&&(t.model=n.canonicalModel.model,t.config=x({},(r=n.generateContentConfig)!=null?r:{}),n.outputSchema&&sn(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))})}},mo=new dt,pt=class extends ne{runAsync(e,t){return A(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),Te(t,r)})}},ho=new pt,gt=class extends ne{runAsync(e,t){return A(this,null,function*(){let n=e.agent;if(!(n instanceof w)||!(n.rootAgent instanceof w))return;let r=n.rootAgent;if(r instanceof w&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new j(e))),a=i;s&&(a=yield new u(ut(i,new j(e)))),Te(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new j(e))),a=i;s&&(a=yield new u(ut(i,new j(e)))),Te(t,[a])}})}},Co=new gt,mt=class{runAsync(e,t){return A(this,null,function*(){let n=e.agent;!n||!(n instanceof w)||(n.includeContents==="default"?t.contents=lt(e.session.events,n.name,e.branch):t.contents=fn(e.session.events,n.name,e.branch))})}},vo=new mt,ht=class extends ne{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new te({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:hn.object({agentName:hn.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"}})}runAsync(t,n){return A(this,null,function*(){if(!(t.agent instanceof w))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;Te(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new oe({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof w)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},yo=new ht,Ct=class extends ne{runAsync(e,t){return A(this,null,function*(){let n=e.agent;if(!(n instanceof w))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=V(c);if(!l)continue;let f=!1;for(let d of l){if(d.name!==Ce)continue;f=!0;let h=null;d.response&&Object.keys(d.response).length===1&&"response"in d.response?h=JSON.parse(d.response.response):d.response&&(h=new ie({hint:d.response.hint,payload:d.response.payload,confirmed:d.response.confirmed})),d.id&&h&&(i[d.id]=h)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=M(c);if(!l)continue;let f={},d={};for(let C of l){if(!C.id||!(C.id in i))continue;let m=C.args;if(!m||!("originalFunctionCall"in m))continue;let y=m.originalFunctionCall;y.id&&(f[y.id]=i[C.id],d[y.id]=y)}if(Object.keys(f).length===0)continue;for(let C=r.length-1;C>s;C--){let m=r[C],y=V(m);if(y){for(let k of y)k.id&&k.id in f&&(delete f[k.id],delete d[k.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let h=yield new u(n.canonicalTools(new j(e))),v=Object.fromEntries(h.map(C=>[C.name,C])),g=yield new u(Ne({invocationContext:e,functionCalls:Object.values(d),toolsDict:v,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f}));g&&(yield g);return}})}},Ao=new Ct,vt=class extends ne{runAsync(e,t){return A(this,null,function*(){if(e.agent instanceof w&&e.agent.codeExecutor){try{for(var n=T(xo(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(e.agent.codeExecutor instanceof re)for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],l=nn(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},Oe={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Eo="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",yt=class{runAsync(e,t){return A(this,null,function*(){if(!t.partial)try{for(var n=T(bo(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}},Ps=new yt;function xo(o,e){return A(this,null,function*(){let t=o.agent;if(!(t instanceof w))return;let n=t.codeExecutor;if(!n||!(n instanceof re))return;if(n instanceof ve){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new Se(new I(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=So(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=To(c);if(!l)return;let f={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},Xe(l)]};e.contents.push(W(f)),yield L({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let d=yn(o,r),h=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:d}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:h.stdout,resultStderr:h.stderr}),r.addProcessedFileNames([c.name]);let v=yield new u(An(o,r,h));yield v,e.contents.push(W(v.content))}})}function bo(o,e){return A(this,null,function*(){let t=o.agent;if(!(t instanceof w))return;let n=t.codeExecutor;if(!n||!(n instanceof re)||!e||!e.content||n instanceof ve)return;let r=new Se(new I(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=en(i,n.codeBlockDelimiters);if(!s)return;yield L({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=yn(o,r),c=yield new u(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 yield new u(An(o,r,c)),e.content=null})}function So(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||!Oe[l])continue;let f="data_".concat(i+1,"_").concat(a+1).concat(Oe[l].extension);c.text="\nAvailable file: `".concat(f,"`\n");let d={name:f,content:$t(c.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([d]),t.push(d))}}return t}function yn(o,e){var r;let t=o.agent;if(!(t instanceof w)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function An(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[tn(t)]},r=H({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 L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function To(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Oe[o.mimeType])return;let t=e(o.name),n=Oe[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return"\n".concat(Eo,"\n\n# Load the dataframe.\n").concat(t," = ").concat(n,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var Io=new vt,w=class o extends Q{constructor(e){var n,r,i,s,a,c,l,f,d;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(c=e.includeContents)!=null?c:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[mo,ho,Co,Ao,vo,Io],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(yo),e.generateContentConfig){if(e.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(e.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(e.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)&&(p.warn("Invalid config for agent ".concat(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 ".concat(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 ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(rt(this.model))return this.model;if(typeof this.model=="string"&&this.model)return Ee.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await vn(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}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(e){var r,i;if(e.author!==this.name){p.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){p.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!ge(e)){p.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){p.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return A(this,null,function*(){for(;;){let s;try{for(var t=T(this.runOneStepAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;s=a,this.maybeSaveOutputToState(a),yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}if(!s||ge(s))break;if(s.partial){p.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return A(this,null,function*(){try{for(var t=T(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return A(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return A(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let m of this.requestProcessors)try{for(var r=T(m.runAsync(e,t)),i,s,a;i=!(s=yield new u(r.next())).done;i=!1){let y=s.value;yield y}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(a)throw a[0]}}for(let m of this.tools){let y=new oe({invocationContext:e}),k=yield new u(vn(m,new j(e)));for(let N of k)yield new u(N.processLlmRequest({toolContext:y,llmRequest:t}))}if(e.endInvocation)return;let n=L({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var h=T(this.callLlmAsync(e,t,n)),v,g,C;v=!(g=yield new u(h.next())).done;v=!1){let m=g.value;try{for(var c=T(this.postprocess(e,t,m,n)),l,f,d;l=!(f=yield new u(c.next())).done;l=!1){let y=f.value;n.id=Ze(),n.timestamp=new Date().getTime(),yield y}}catch(f){d=[f]}finally{try{l&&(f=c.return)&&(yield new u(f.call(c)))}finally{if(d)throw d[0]}}}}catch(g){C=[g]}finally{try{v&&(g=h.return)&&(yield new u(g.call(h)))}finally{if(C)throw C[0]}}})}postprocess(e,t,n,r){return A(this,null,function*(){var g,C,m,y,k;for(let q of this.responseProcessors)try{for(var f=T(q.runAsync(e,n)),d,h,v;d=!(h=yield new u(f.next())).done;d=!1){let b=h.value;yield b}}catch(h){v=[h]}finally{try{d&&(h=f.return)&&(yield new u(h.call(f)))}finally{if(v)throw v[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=L(x(x({},r),n));if(i.content){let q=M(i);if(q!=null&&q.length){jt(i),i.longRunningToolIds=Array.from(Vt(q,t.toolsDict));let b=(g=i.content.parts)==null?void 0:g.some(R=>R.thought),E=(C=i.content.parts)==null?void 0:C.some(R=>R.thoughtSignature);p.info("[postprocess] Function call event: ".concat(q.length," calls, ")+"hasThought=".concat(b,", hasSignature=").concat(E));for(let R=0;R<(((m=i.content.parts)==null?void 0:m.length)||0);R++){let X=i.content.parts[R];(X.functionCall||X.thought)&&p.info("[postprocess] Part ".concat(R,": thought=").concat(!!X.thought,", ")+"functionCall=".concat(((y=X.functionCall)==null?void 0:y.name)||"none",", ")+"hasSignature=".concat(!!X.thoughtSignature))}E||p.warn("[postprocess] WARNING: Event has function calls but NO thoughtSignature! This will cause 400 errors when this content is sent back to Gemini 3.")}}if(yield i,!((k=M(i))!=null&&k.length))return;let s=yield new u(zt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let a=Zt(e,s);a&&(yield a);let c=Wt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let q=this.getAgentByName(e,l);try{for(var N=T(q.runAsync(e)),B,xe,_t;B=!(xe=yield new u(N.next())).done;B=!1){let b=xe.value;yield b}}catch(xe){_t=[xe]}finally{try{B&&(xe=N.return)&&(yield new u(xe.call(N)))}finally{if(_t)throw _t[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return A(this,null,function*(){var s,a,c,l,f;let r=yield new u(this.handleBeforeModelCallback(e,t,n));if(r){yield r;return}(s=t.config)!=null||(t.config={}),(c=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[Cn]||(t.config.labels[Cn]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let C=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");try{for(var d=T(this.runAndHandleError(C,e,t,n)),h,v,g;h=!(v=yield new u(d.next())).done;h=!1){let m=v.value;let y=yield new u(this.handleAfterModelCallback(e,m,n));yield y!=null?y:m}}catch(v){g=[v]}finally{try{h&&(v=d.return)&&(yield new u(v.call(d)))}finally{if(g)throw g[0]}}}})}async handleBeforeModelCallback(e,t,n){let r=new Z({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let a=await s({context:r,request:t});if(a)return a}}async handleAfterModelCallback(e,t,n){let r=new Z({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let a=await s({context:r,response:t});if(a)return a}}runAndHandleError(e,t,n,r){return A(this,null,function*(){try{try{for(var i=T(e),s,a,c;s=!(a=yield new u(i.next())).done;s=!1){let l=a.value;yield l}}catch(a){c=[a]}finally{try{s&&(a=i.return)&&(yield new u(a.call(i)))}finally{if(c)throw c[0]}}}catch(l){let f=new Z({invocationContext:t,eventActions:r.actions});if(l instanceof Error){let d=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:n,error:l}));if(d)yield d;else{let h=JSON.parse(l.message);yield{errorCode:String(h.error.code),errorMessage:h.error.message}}}else throw p.error("Unknown error during response generation",l),l}})}};var At=class extends Q{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return A(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let a of this.subAgents){let c=!1;try{for(var n=T(a.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let l=i.value;yield l,l.actions.escalate&&(c=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(c)return}t++}})}runLiveImpl(e){return A(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var Et=class extends Q{runAsyncImpl(e){return A(this,null,function*(){let t=this.subAgents.map(a=>a.runAsync(Ro(this,a,e)));try{for(var n=T(wo(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return A(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function Ro(o,e,t){let n=new J(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function wo(o){return A(this,null,function*(){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}=yield new u(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 xt="task_completed",bt=class extends Q{runAsyncImpl(e){return A(this,null,function*(){for(let s of this.subAgents)try{for(var t=T(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return A(this,null,function*(){for(let s of this.subAgents)s instanceof w&&((yield new u(s.canonicalTools(new j(e)))).some(l=>l.name===xt)||(s.tools.push(new te({name:xt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(xt," 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 s of this.subAgents)try{for(var t=T(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var Ie=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=$e(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=$e(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="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(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=$e(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=$e(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 $e(o,e,t,n){return ko(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function ko(o){return o.startsWith("user:")}var le=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=En(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=En(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(h=>h.text).filter(h=>!!h).join(" "),f=Po(l);if(!f.size)continue;n.some(h=>f.has(h))&&r.memories.push({content:c.content,author:c.author,timestamp:Lo(c.timestamp)})}return r}};function En(o,e){return"".concat(o,"/").concat(e)}function Po(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Lo(o){return new Date(o).toISOString()}var ue=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var St=class extends ue{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: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((n=e.agent.name)!=null?n:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(ge(t)));let n=M(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=V(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");p.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: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(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 Re=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 '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),p.info("Plugin '".concat(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 p.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw p.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 bn="adk_request_confirmation",Tt="orcas_tool_call_security_check_states",xn="This tool call needs external confirmation before completion.",Sn=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Sn||{}),Ge=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},It=class extends ue{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ge}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:xn};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(Tt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Tt))!=null?i:{};r[n]=t,e.state.set(Tt,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: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:xn};case"ALLOW":return;default:return}}};function _o(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===bn&&e.push(t.functionCall);return e}var De=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(I.TEMP_PREFIX)||(e.state[n]=r)}};function qe(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var fe=class extends De{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=qe({id:i||me(),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,W(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=W(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(qe({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=>{p.warn("Failed to append event to session ".concat(s,": ").concat(l))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(I.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(I.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(I.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(I.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[I.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[I.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as No}from"@google/genai";import{trace as Mo}from"@opentelemetry/api";var de=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new Re((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return A(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var c;i=mn(i);let a=Mo.getTracer("gcp.vertex.agent").startSpan("invocation");try{let v=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!v)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof w){let y=this.agent.canonicalModel.model;if(!y.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(y," in agent: ").concat(this.agent.name))}let g=new J({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Gt(),agent:this.agent,session:v,userContent:n,runConfig:i,pluginManager:this.pluginManager}),C=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:g}));if(C&&(n=C),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(g.invocationId,v.userId,v.id,n))),yield new u(this.sessionService.appendEvent({session:v,event:L({invocationId:g.invocationId,author:"user",actions:r?H({stateDelta:r}):void 0,content:n})}))}g.agent=this.determineAgentForResumption(v,this.agent);let m=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:g}));if(m){let y=L({invocationId:g.invocationId,author:"model",content:m});yield new u(this.sessionService.appendEvent({session:v,event:y})),yield y}else try{for(var l=T(g.agent.runAsync(g)),f,d,h;f=!(d=yield new u(l.next())).done;f=!1){let y=d.value;y.partial||(yield new u(this.sessionService.appendEvent({session:v,event:y})));let k=yield new u(this.pluginManager.runOnEventCallback({invocationContext:g,event:y}));k?yield k:yield y}}catch(d){h=[d]}finally{try{f&&(d=l.return)&&(yield new u(d.call(l)))}finally{if(h)throw h[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:g}))}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_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=No("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Bo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.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){p.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof w)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Bo(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=M(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var Rt=class extends de{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new Ie,sessionService:new fe,memoryService:new le})}};import{Type as je}from"@google/genai";var Ue=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 wt=class extends Y{constructor(e){super({name:e.agent.name,description:e.agent.description||""}),this.agent=e.agent,this.skipSummarization=e.skipSummarization||!1}_getDeclaration(){let e;if(this.agent instanceof w&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:je.OBJECT,properties:{request:{type:je.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof w&&this.agent.outputSchema;e.response=t?{type:je.OBJECT}:{type:je.STRING}}return e}async runAsync({args:e,toolContext:t}){var g,C;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof w&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new de({appName:this.agent.name,agent:this.agent,artifactService:new Ue(t),sessionService:new fe,memoryService:new le,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;try{for(var f=T(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),d,h,v;d=!(h=await f.next()).done;d=!1){let m=h.value;m.actions.stateDelta&&t.state.update(m.actions.stateDelta),a=m}}catch(h){v=[h]}finally{try{d&&(h=f.return)&&await h.call(f)}finally{if(v)throw v[0]}}if(!((C=(g=a==null?void 0:a.content)==null?void 0:g.parts)!=null&&C.length))return"";let c=this.agent instanceof w&&this.agent.outputSchema,l=a.content.parts.map(m=>m.text).filter(m=>m).join("\n");return c?JSON.parse(l):l}};var kt=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 Pt=class extends Y{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||[],Yt(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(Qt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},Fo=new Pt;var Tn="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",Lt=class extends te{constructor(e){super(pe(x({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Tn:e.description=Tn.trimStart(),e}};export{wt as AgentTool,Q as BaseAgent,ye as BaseLlm,ue as BasePlugin,De as BaseSessionService,Y as BaseTool,kt as BaseToolset,ve as BuiltInCodeExecutor,Z as CallbackContext,te as FunctionTool,Fo as GOOGLE_SEARCH,Ae as Gemini,Ie as InMemoryArtifactService,le as InMemoryMemoryService,Ge as InMemoryPolicyEngine,Rt as InMemoryRunner,fe as InMemorySessionService,J as InvocationContext,Ee as LLMRegistry,He as LiveRequestQueue,w as LlmAgent,Ut as LogLevel,St as LoggingPlugin,Lt as LongRunningFunctionTool,At as LoopAgent,Et as ParallelAgent,Re as PluginManager,Sn as PolicyOutcome,bn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,de as Runner,It as SecurityPlugin,bt as SequentialAgent,I as State,ft as StreamingMode,ie as ToolConfirmation,oe as ToolContext,L as createEvent,H as createEventActions,qe as createSession,Dn as functionsExportedForTestingOnly,_o as getAskUserConfirmationFunctionCalls,M as getFunctionCalls,V as getFunctionResponses,Ot as hasTrailingCodeExecutionResult,rt as isBaseLlm,ge as isFinalResponse,Bn as setLogLevel,Ln as stringifyContent,nt as version,Fe as zodObjectToSchema};
7
+ var In=Object.defineProperty,wn=Object.defineProperties;var kn=Object.getOwnPropertyDescriptors;var Mt=Object.getOwnPropertySymbols;var Pn=Object.prototype.hasOwnProperty,Ln=Object.prototype.propertyIsEnumerable;var We=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var Bt=(o,e,t)=>e in o?In(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,x=(o,e)=>{for(var t in e||(e={}))Pn.call(e,t)&&Bt(o,t,e[t]);if(Mt)for(var t of Mt(e))Ln.call(e,t)&&Bt(o,t,e[t]);return o},he=(o,e)=>wn(o,kn(e));var u=function(o,e){this[0]=o,this[1]=e},A=(o,e,t)=>{var n=(s,a,c,l)=>{try{var f=t[s](a),d=(a=f.value)instanceof u,h=f.done;Promise.resolve(d?a[0]:a).then(y=>d?n(s==="return"?s:"next",a[1]?{done:y.done,value:y.value}:y,c,l):c({value:y,done:h})).catch(y=>n("throw",y,c,l))}catch(y){l(y)}},r=s=>i[s]=a=>new Promise((c,l)=>n(s,a,c,l)),i={};return t=t.apply(o,e),i[We("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var T=(o,e,t)=>(e=o[We("asyncIterator")])?e.call(o):(o=o[We("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,a,c)=>(i=r.call(o,i),c=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:c}),a)))),t("next"),t("return"),e);import{trace as qt}from"@opentelemetry/api";function J(o={}){return x({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function Ot(o,e){let t=J();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 L(o={}){return he(x({},o),{id:o.id||ze(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||J(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function Ce(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:B(o).length===0&&W(o).length===0&&!o.partial&&!$t(o)}function B(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 W(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 $t(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 _n(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 Ft="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function ze(){let o="";for(let e=0;e<8;e++)o+=Ft[Math.floor(Math.random()*Ft.length)];return o}var R=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=x(x({},this.delta),e),this.value=x(x({},this.value),e)}toRecord(){return x(x({},this.value),this.delta)}};R.APP_PREFIX="app:",R.USER_PREFIX="user:",R.TEMP_PREFIX="temp:";var V=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 R(this.invocationContext.session.state,{})}};var z=class extends V{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||J(),this._state=new R(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 _e(){return typeof window<"u"}var Le="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ve(){let o="";for(let e=0;e<Le.length;e++){let t=Math.random()*16|0;Le[e]==="x"?o+=t.toString(16):Le[e]==="y"?o+=(t&3|8).toString(16):o+=Le[e]}return o}function Gt(o){return _e()?window.atob(o):Buffer.from(o,"base64").toString()}var Ye=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 ".concat(e.maxLlmCalls," exceeded"))}},te=class{constructor(e){this.invocationCostManager=new Ye;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 Dt(){return"e-".concat(ve())}var X=class{constructor(e){this.name=Nn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Bn(this),this.beforeAgentCallback=Ut(e.beforeAgentCallback),this.afterAgentCallback=Ut(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return A(this,null,function*(){let t=qt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let a=this.createInvocationContext(e),c=yield new u(this.handleBeforeAgentCallback(a));if(c&&(yield c),a.endInvocation)return;try{for(var n=T(this.runAsyncImpl(a)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let f=i.value;yield f}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a.endInvocation)return;let l=yield new u(this.handleAfterAgentCallback(a));l&&(yield l)}finally{t.end()}})}runLive(e){return A(this,null,function*(){let t=qt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(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 te(he(x({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new z({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,L({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return L({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new z({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return L({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return L({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 "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function Nn(o){if(!Mn(o))throw new Error('Found invalid agent name: "'.concat(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 Mn(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function Bn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Ut(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Dn}from"@google/genai";var Te=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 ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(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 ".concat(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 ce=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var se=class extends z{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Te(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Te(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 ce({hint:e,confirmed:!1,payload:t})}};var jt=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(jt||{}),ye=1;function On(o){ye=o}var Qe=class{log(e,...t){if(!(e<ye))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: ".concat(e))}}debug(...e){ye>0||console.debug(Ne(0),...e)}info(...e){ye>1||console.info(Ne(1),...e)}warn(...e){ye>2||console.warn(Ne(2),...e)}error(...e){ye>3||console.error(Ne(3),...e)}},Fn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},$n={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Gn="\x1B[0m";function Ne(o){return"".concat($n[o],"[ADK ").concat(Fn[o],"]:").concat(Gn)}var p=new Qe;var Xe="adk-",Me="adk_request_credential",Ae="adk_request_confirmation",qn={handleFunctionCallList:Be};function He(){return"".concat(Xe).concat(ve())}function Kt(o){let e=B(o);if(e)for(let t of e)t.id||(t.id=He())}function Vt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Xe)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Xe)&&(e.functionResponse.id=void 0)}function Zt(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 Wt(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:Me,args:{function_call_id:i,auth_config:s},id:He()};n.add(a.id),t.push({functionCall:a})}return L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function zt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=B(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(h=>h.id===c))!=null?a:void 0;if(!f)continue;let d={name:Ae,args:{originalFunctionCall:f,toolConfirmation:l},id:He()};r.add(d.id),n.push({functionCall:d})}return L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Un(o,e,t){return p.debug("callToolAsync ".concat(o.name)),await o.runAsync({args:e,toolContext:t})}async function Yt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=B(e);return await Be({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Be({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(d=>!i||d.id&&i.has(d.id));for(let d of c){let h;s&&d.id&&(h=s[d.id]);let{tool:y,toolContext:g}=jn({invocationContext:o,functionCall:d,toolsDict:t,toolConfirmation:h});p.debug("execute_tool ".concat(y.name));let v=(f=d.args)!=null?f:{},m=null,C;if(m=await o.pluginManager.runBeforeToolCallback({tool:y,toolArgs:v,toolContext:g}),m==null){for(let M of n)if(m=await M({tool:y,args:v,context:g}),m)break}if(m==null)try{m=await Un(y,v,g)}catch(M){if(M instanceof Error){let $=await o.pluginManager.runOnToolErrorCallback({tool:y,toolArgs:v,toolContext:g,error:M});$?m=$:C=M.message}else C=M}let I=await o.pluginManager.runAfterToolCallback({tool:y,toolArgs:v,toolContext:g,result:m});if(I==null){for(let M of r)if(I=await M({tool:y,args:v,context:g,response:m}),I)break}if(I!=null&&(m=I),y.isLongRunning&&!m)continue;C?m={error:C}:(typeof m!="object"||m==null)&&(m={result:m});let _=L({invocationId:o.invocationId,author:o.agent.name,content:Dn({functionResponse:{id:g.functionCallId,name:y.name,response:m}}),actions:g.actions,branch:o.branch});p.debug("traceToolCall",{tool:y.name,args:v,functionResponseEvent:_.id}),a.push(_)}if(!a.length)return null;let l=Kn(a);return a.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function jn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new se({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Kn(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=Ot(n);return L({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Je=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:{}})}[Symbol.asyncIterator](){return A(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as Cn}from"zod";var ae=class{constructor(){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 Vn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Oe(o){let e=o.match(Vn);return e?e[1]:o}function Qt(o){return Oe(o).startsWith("gemini-")}function Xt(o){return Oe(o).startsWith("gemini-1")}function Ht(o){return Oe(o).startsWith("gemini-2")}function Jt(o){let e=Oe(o);return e.startsWith("gemini-3")&&e.includes("preview")}var Ee=class extends ae{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Ht(e.model)){e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({codeExecution:{}});return}throw new Error("Gemini code execution tool is not supported for model ".concat(e.model))}};import{Language as Zn,Outcome as en}from"@google/genai";function Y(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function tn(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let d=0;d<o.parts.length;d++){let h=o.parts[d];if(h.executableCode&&(d===o.parts.length-1||!o.parts[d+1].codeExecutionResult))return o.parts=o.parts.slice(0,d+1),h.executableCode.code}let t=o.parts.filter(d=>d.text);if(!t.length)return"";let n=Y(t[0]),r=t.map(d=>d.text).join("\n"),i=e.map(d=>d[0]).join("|"),s=e.map(d=>d[1]).join("|"),a=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(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(et(l)),l):""}function et(o){return{text:o,executableCode:{code:o,language:Zn.PYTHON}}}function nn(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:en.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push("Code execution result:\n".concat(o.stdout,"\n")),o.outputFiles&&e.push("Saved artifacts:\n"+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:en.OUTCOME_OK}}}function on(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 tt="_code_execution_context",nt="execution_session_id",le="processed_input_files",ue="_code_executor_input_files",fe="_code_executor_error_counts",ot="_code_execution_results",Re=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(tt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[tt]:Y(this.context)}}getExecutionId(){if(nt in this.context)return this.context[nt]}setExecutionId(e){this.context[nt]=e}getProcessedFileNames(){return le in this.context?this.context[le]:[]}addProcessedFileNames(e){le in this.context||(this.context[le]=[]),this.context[le].push(...e)}getInputFiles(){return ue in this.sessionState?this.sessionState.get(ue):[]}addInputFiles(e){ue in this.sessionState||this.sessionState.set(ue,[]),this.sessionState.get(ue).push(...e)}clearInputFiles(){ue in this.sessionState&&this.sessionState.set(ue,[]),le in this.context&&(this.context[le]=[])}getErrorCount(e){return fe in this.sessionState&&this.sessionState.get(fe)[e]||0}incrementErrorCount(e){fe in this.sessionState||this.sessionState.set(fe,{}),this.sessionState.get(fe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(fe in this.sessionState))return;let t=this.sessionState.get(fe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){ot in this.sessionState||this.sessionState.set(ot,{});let i=this.sessionState.get(ot);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(tt)||{}}};var rt="0.2.4";var Wn="google-adk",zn="gl-typescript",Yn="remote_reasoning_engine",Qn="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Xn(){let o="".concat(Wn,"/").concat(rt);!_e()&&process.env[Qn]&&(o="".concat(o,"+").concat(Yn));let e="".concat(zn,"/").concat(_e()?window.navigator.userAgent:process.version);return[o,e]}function rn(){return Xn()}var it=Symbol("baseModel");function st(o){return typeof o=="object"&&o!==null&&it in o&&o[it]===!0}var sn;sn=it;var xe=class{constructor({model:e}){this[sn]=!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."}]})}};xe.supportedModels=[];function Ie(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function an(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as ct,FinishReason as eo,GoogleGenAI as lt}from"@google/genai";function cn(){return Hn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Hn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Fe=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"}):p.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);p.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else p.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){p.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return A(this,null,function*(){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 to="https://aiplatform.googleapis.com/v1/publishers/google",be=class extends xe{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=Jt(e);let c=typeof process=="object";this.apiEndpoint=a,!this.apiEndpoint&&c&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&(this.apiEndpoint=to,p.info("Using Gemini 3 preview endpoint: ".concat(this.apiEndpoint)));let l=!!n;if(!l&&c){let f=process.env.GOOGLE_GENAI_USE_VERTEXAI;f&&(l=f.toLowerCase()==="true"||f==="1")}if(this.isGemini3Preview&&l){let f=t||(c?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);f?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(c&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),c&&!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&&c&&(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.")}generateContentAsync(e,t=!1){return A(this,null,function*(){var n,r,i,s,a,c,l,f,d,h,y,I,_,M,$,ie;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=x(x({},e.config.httpOptions.headers),this.trackingHeaders)),t){let j=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),b="",E,w="",ee,O;this.isGemini3Preview&&this.cachedThoughtSignature&&p.info("[Gemini3] Starting new request with CACHED thoughtSignature (length: ".concat(this.cachedThoughtSignature.length,")"));try{for(var g=T(j),v,m,C;v=!(m=yield new u(g.next())).done;v=!1){let P=m.value;O=P;let S=at(P);ee=S.usageMetadata;let Z=(s=(i=S.content)==null?void 0:i.parts)==null?void 0:s[0],Ze=(c=(a=S.content)==null?void 0:a.parts)==null?void 0:c.some(G=>G.functionCall);if(this.isGemini3Preview&&((l=S.content)!=null&&l.parts)){for(let G of S.content.parts)if(G.thoughtSignature&&!E){E=G.thoughtSignature,this.cachedThoughtSignature=E,p.info("[Gemini3] Captured and CACHED thoughtSignature from response part (length: ".concat(E.length,")"));break}}if(Z!=null&&Z.text){if("thought"in Z&&Z.thought?(b+=Z.text,"thoughtSignature"in Z&&Z.thoughtSignature&&(E=Z.thoughtSignature,this.cachedThoughtSignature=E,p.info("[Gemini3] Captured and CACHED thoughtSignature from thought part (length: ".concat(E.length,")")))):w+=Z.text,S.partial=!0,this.isGemini3Preview&&Ze){let G=(d=(f=S.content)==null?void 0:f.parts)==null?void 0:d.some(F=>F.thoughtSignature);p.info("[Gemini3] Chunk has thought AND function calls. Response has signature: ".concat(G)),b="",E=void 0,w=""}}else if((b||w)&&(!Z||!Z.inlineData))if(this.isGemini3Preview&&Ze&&S.content){p.info("[Gemini3] Merging thought with function calls. Has accumulated signature: ".concat(!!E));let G=[];if(b){let F={text:b,thought:!0};E&&(F.thoughtSignature=E),G.push(F),p.info("[Gemini3] Created thought part with signature: ".concat(!!E))}if(w&&G.push(ct(w)),!b&&E){let F=!1;for(let K of S.content.parts||[])K.functionCall&&!F&&(K.thoughtSignature||(K.thoughtSignature=E,p.info("[Gemini3] Applied accumulated signature to first function call: ".concat(K.functionCall.name))),F=!0)}S.content.parts=[...G,...S.content.parts||[]],p.info("[Gemini3] Final merged content has ".concat(S.content.parts.length," parts"));for(let F=0;F<S.content.parts.length;F++){let K=S.content.parts[F];p.info("[Gemini3] Part ".concat(F,": thought=").concat(!!K.thought,", functionCall=").concat(((h=K.functionCall)==null?void 0:h.name)||"none",", hasSignature=").concat(!!K.thoughtSignature))}b="",E=void 0,w=""}else{let G=[];if(b){let F={text:b,thought:!0};E&&(F.thoughtSignature=E),G.push(F)}w&&G.push(ct(w)),yield{content:{role:"model",parts:G},usageMetadata:S.usageMetadata},b="",E=void 0,w=""}if(this.isGemini3Preview&&Ze&&((y=S.content)!=null&&y.parts)){if(!S.content.parts.some(U=>U.thoughtSignature)&&E){for(let U of S.content.parts)if(U.functionCall){U.thoughtSignature=E,p.info("[Gemini3] Applied cached signature to first function call: ".concat(U.functionCall.name));break}}let F=S.content.parts.filter(U=>U.functionCall).map(U=>U.functionCall.name),K=S.content.parts.filter(U=>U.thoughtSignature).length;if(K===0){let U=E||this.cachedThoughtSignature;if(U){for(let Pe of S.content.parts)if(Pe.functionCall&&!Pe.thoughtSignature){Pe.thoughtSignature=U,p.info("[Gemini3] Applied CACHED signature to function call: ".concat(Pe.functionCall.name," (API didn't return new signature, using ").concat(E?"local":"class-level"," cache)")),K=1;break}}}p.info("[Gemini3] Yielding function call response: calls=[".concat(F.join(", "),"], partsWithSignature=").concat(K)),K===0&&p.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}yield S}}catch(m){C=[m]}finally{try{v&&(m=g.return)&&(yield new u(m.call(g)))}finally{if(C)throw C[0]}}if((w||b)&&((_=(I=O==null?void 0:O.candidates)==null?void 0:I[0])==null?void 0:_.finishReason)===eo.STOP){let P=[];if(b){let S={text:b,thought:!0};E&&(S.thoughtSignature=E),P.push(S)}w&&P.push({text:w}),yield{content:{role:"model",parts:P},usageMetadata:ee}}}else{let j=yield new u(this.apiClient.models.generateContent({model:(M=e.model)!=null?M:this.model,contents:e.contents,config:e.config})),b=at(j);if(this.isGemini3Preview&&(($=b.content)!=null&&$.parts)){let E,w=!1;for(let O of b.content.parts)if(O.thoughtSignature){E=O.thoughtSignature,this.cachedThoughtSignature=E,O.thought&&(w=!0);break}if(p.info("[Gemini3] Non-streaming response: hasSignature=".concat(!!E,", hasThoughtPart=").concat(w,", hasCachedSig=").concat(!!this.cachedThoughtSignature)),E&&!w){let O=!1;for(let P of b.content.parts)P.functionCall&&(!O&&!P.thoughtSignature&&(P.thoughtSignature=E,p.info("[Gemini3] Applied signature to first function call: ".concat(P.functionCall.name))),O=!0)}if(b.content.parts.some(O=>O.functionCall)){let O=b.content.parts.filter(P=>P.thoughtSignature).length;if(O===0&&this.cachedThoughtSignature){for(let P of b.content.parts)if(P.functionCall&&!P.thoughtSignature){P.thoughtSignature=this.cachedThoughtSignature,p.info("[Gemini3] Applied CACHED signature to function call: ".concat(P.functionCall.name," (API didn't return new signature)")),O=1;break}}for(let P=0;P<b.content.parts.length;P++){let S=b.content.parts[P];p.info("[Gemini3] Response Part ".concat(P,": thought=").concat(!!S.thought,", functionCall=").concat(((ie=S.functionCall)==null?void 0:ie.name)||"none",", hasSignature=").concat(!!S.thoughtSignature))}O===0&&p.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}}yield b}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=x(x({},this.trackingHeaders),this.headers);if(this.vertexai)this._apiClient=new lt({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,p.debug("Using custom API endpoint: ".concat(this.apiEndpoint)),this.isGemini3Preview&&(t.apiVersion="",p.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new lt({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return 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(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};this.apiEndpoint&&(e.baseUrl=this.apiEndpoint,this.isGemini3Preview&&(e.apiVersion="")),this._liveApiClient=new lt({apiKey:this.apiKey,httpOptions:e})}return 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.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[ct(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 Fe(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)ln(n.inlineData),ln(n.fileData)}}};be.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function ln(o){o&&o.displayName&&(o.displayName=void 0)}var ut=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)}},Q=class Q{static newLlm(e){return new(Q.resolve(e))({model:e})}static _register(e,t){Q.llmRegistryDict.has(e)&&p.info("Updating LLM class for ".concat(e," from ").concat(Q.llmRegistryDict.get(e)," to ").concat(t)),Q.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)Q._register(t,e)}static resolve(e){let t=Q.resolveCache.get(e);if(t)return t;for(let[n,r]of Q.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return Q.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};Q.llmRegistryDict=new Map,Q.resolveCache=new ut(32);var Se=Q;Se.register(be);var H=class{constructor(e){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=no(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 cn()}};function no(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as oo}from"@google/genai";import{ZodObject as ro}from"zod";import{Type as D}from"@google/genai";import{z as N}from"zod";function un(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function ne(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 N.ZodFirstPartyTypeKind.ZodString:n.type=D.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 N.ZodFirstPartyTypeKind.ZodNumber:n.type=D.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=D.INTEGER);return r(n);case N.ZodFirstPartyTypeKind.ZodBoolean:return n.type=D.BOOLEAN,r(n);case N.ZodFirstPartyTypeKind.ZodArray:return n.type=D.ARRAY,n.items=ne(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case N.ZodFirstPartyTypeKind.ZodObject:return $e(o);case N.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=D.STRING;else if(i==="number")n.type=D.NUMBER;else if(i==="boolean")n.type=D.BOOLEAN;else if(e.value===null)n.type=D.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case N.ZodFirstPartyTypeKind.ZodEnum:return n.type=D.STRING,n.enum=e.values,r(n);case N.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=D.STRING,n.enum=Object.values(e.values),r(n);case N.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(ne),r(n);case N.ZodFirstPartyTypeKind.ZodOptional:return ne(e.innerType);case N.ZodFirstPartyTypeKind.ZodNullable:let s=ne(e.innerType);return r(s?x({anyOf:[s,{type:D.NULL}]},t&&{description:t}):x({type:D.NULL},t&&{description:t}));case N.ZodFirstPartyTypeKind.ZodDefault:let a=ne(e.innerType);return a&&(a.default=e.defaultValue()),a;case N.ZodFirstPartyTypeKind.ZodBranded:return ne(e.type);case N.ZodFirstPartyTypeKind.ZodReadonly:return ne(e.innerType);case N.ZodFirstPartyTypeKind.ZodNull:return n.type=D.NULL,r(n);case N.ZodFirstPartyTypeKind.ZodAny:case N.ZodFirstPartyTypeKind.ZodUnknown:return r(x({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function $e(o){if(o._def.typeName!==N.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=ne(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===N.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===N.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==N.ZodFirstPartyTypeKind.ZodNever?i=ne(r)||!0:i=o._def.unknownKeys==="passthrough",x({type:D.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function io(o){return o===void 0?{type:oo.OBJECT,properties:{}}:un(o)?$e(o):o}var oe=class extends H{constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:io(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof ro&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var re=class{};function ft(o,e,t){var c,l,f,d,h,y;let n=[];for(let g of o)!((c=g.content)!=null&&c.role)||!((l=g.content.parts)!=null&&l.length)||t&&g.branch&&!t.startsWith(g.branch)||so(g)||ao(g)||n.push(pn(e,g)?co(g):g);let r=lo(n);r=uo(r);let i=[];for(let g of r){let v=Y(g.content);Vt(v),i.push(v)}let s=!1,a=-1;for(let g=0;g<i.length;g++){let v=i[g],m=(f=v.parts)==null?void 0:f.some(_=>_.functionCall),C=(d=v.parts)==null?void 0:d.some(_=>_.thoughtSignature),I=(h=v.parts)==null?void 0:h.some(_=>_.thought);if(m){p.info("[getContents] Content block ".concat(g+1,"/").concat(i.length,": role=").concat(v.role,", ")+"hasFunctionCalls=true, hasThought=".concat(I,", hasSignature=").concat(C)),!C&&v.role==="model"&&(s=!0,a=g+1);for(let _=0;_<(((y=v.parts)==null?void 0:y.length)||0);_++){let M=v.parts[_];M.functionCall?p.info("[getContents] Part ".concat(_,": functionCall=").concat(M.functionCall.name,", ")+"hasSignature=".concat(!!M.thoughtSignature)):M.thought&&p.info("[getContents] Part ".concat(_,": thought=true, hasSignature=").concat(!!M.thoughtSignature))}}}return s&&p.warn("[getContents] WARNING: Content block ".concat(a," has model function calls but NO thoughtSignature! ")+"This will likely cause a 400 error from Gemini 3 API."),i}function dn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||pn(e,r))return ft(o.slice(n),e,t)}return[]}function so(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)===Me||((n=r.functionResponse)==null?void 0:n.name)===Me)return!0;return!1}function ao(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)===Ae||((n=r.functionResponse)==null?void 0:n.name)===Ae)return!0;return!1}function pn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function co(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:"[".concat(o.author,"] said: ").concat(c.text)});else if(c.functionCall){let l=fn(c.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(c.functionCall.name,"` with parameters: ").concat(l)})}else if(c.functionResponse){let l=fn(c.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(c.functionResponse.name,"` returned result: ").concat(l)})}else(a=e.parts)==null||a.push(c);return L({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function gn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=L(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 lo(o){if(o.length===0)return o;let e=o[o.length-1],t=W(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=B(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=B(l);if(f!=null&&f.length){for(let d of f)if(d.id&&n.has(d.id)){i=c;let h=new Set(f.map(g=>g.id).filter(g=>!!g));if(!Array.from(n).every(g=>h.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 : ".concat(Array.from(h).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=h;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=W(l);f&&f.some(d=>d.id&&n.has(d.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(gn(s)),a}function uo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=W(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(W(n).length>0)continue;let r=B(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(gn(a))}}else t.push(n)}return t}function fn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function dt(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 d=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let h=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:d});if(!h)throw new Error("Artifact ".concat(d," not found."));return String(h)}if(!go(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: `".concat(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 fo=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function mn(o){return o===""||o===void 0?!1:fo.test(o)}var po=[R.APP_PREFIX,R.USER_PREFIX,R.TEMP_PREFIX];function go(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?mn(o):po.includes(e[0]+":")?mn(e[1]):!1}var pt=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(pt||{});function hn(o={}){return x({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:mo(o.maxLlmCalls||500)},o)}function mo(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return o<=0&&p.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 vn="adk_agent_name";async function yn(o,e){return o instanceof H?[o]:await o.getTools(e)}var gt=class extends re{runAsync(e,t){return A(this,null,function*(){var r;let n=e.agent;n instanceof k&&(t.model=n.canonicalModel.model,t.config=x({},(r=n.generateContentConfig)!=null?r:{}),n.outputSchema&&an(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))})}},ho=new gt,mt=class extends re{runAsync(e,t){return A(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),Ie(t,r)})}},Co=new mt,ht=class extends re{runAsync(e,t){return A(this,null,function*(){let n=e.agent;if(!(n instanceof k)||!(n.rootAgent instanceof k))return;let r=n.rootAgent;if(r instanceof k&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new V(e))),a=i;s&&(a=yield new u(dt(i,new V(e)))),Ie(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new V(e))),a=i;s&&(a=yield new u(dt(i,new V(e)))),Ie(t,[a])}})}},vo=new ht,Ct=class{runAsync(e,t){return A(this,null,function*(){let n=e.agent;!n||!(n instanceof k)||(n.includeContents==="default"?t.contents=ft(e.session.events,n.name,e.branch):t.contents=dn(e.session.events,n.name,e.branch))})}},yo=new Ct,vt=class extends re{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new oe({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:Cn.object({agentName:Cn.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"}})}runAsync(t,n){return A(this,null,function*(){if(!(t.agent instanceof k))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;Ie(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new se({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof k)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},Ao=new vt,yt=class extends re{runAsync(e,t){return A(this,null,function*(){let n=e.agent;if(!(n instanceof k))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=W(c);if(!l)continue;let f=!1;for(let d of l){if(d.name!==Ae)continue;f=!0;let h=null;d.response&&Object.keys(d.response).length===1&&"response"in d.response?h=JSON.parse(d.response.response):d.response&&(h=new ce({hint:d.response.hint,payload:d.response.payload,confirmed:d.response.confirmed})),d.id&&h&&(i[d.id]=h)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=B(c);if(!l)continue;let f={},d={};for(let v of l){if(!v.id||!(v.id in i))continue;let m=v.args;if(!m||!("originalFunctionCall"in m))continue;let C=m.originalFunctionCall;C.id&&(f[C.id]=i[v.id],d[C.id]=C)}if(Object.keys(f).length===0)continue;for(let v=r.length-1;v>s;v--){let m=r[v],C=W(m);if(C){for(let I of C)I.id&&I.id in f&&(delete f[I.id],delete d[I.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let h=yield new u(n.canonicalTools(new V(e))),y=Object.fromEntries(h.map(v=>[v.name,v])),g=yield new u(Be({invocationContext:e,functionCalls:Object.values(d),toolsDict:y,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f}));g&&(yield g);return}})}},Eo=new yt,At=class extends re{runAsync(e,t){return A(this,null,function*(){if(e.agent instanceof k&&e.agent.codeExecutor){try{for(var n=T(bo(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(e.agent.codeExecutor instanceof ae)for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],l=on(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},Ge={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},xo="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",Et=class{runAsync(e,t){return A(this,null,function*(){if(!t.partial)try{for(var n=T(So(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}},Ls=new Et;function bo(o,e){return A(this,null,function*(){let t=o.agent;if(!(t instanceof k))return;let n=t.codeExecutor;if(!n||!(n instanceof ae))return;if(n instanceof Ee){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new Re(new R(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=To(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=Ro(c);if(!l)return;let f={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},et(l)]};e.contents.push(Y(f)),yield L({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let d=An(o,r),h=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:d}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:h.stdout,resultStderr:h.stderr}),r.addProcessedFileNames([c.name]);let y=yield new u(En(o,r,h));yield y,e.contents.push(Y(y.content))}})}function So(o,e){return A(this,null,function*(){let t=o.agent;if(!(t instanceof k))return;let n=t.codeExecutor;if(!n||!(n instanceof ae)||!e||!e.content||n instanceof Ee)return;let r=new Re(new R(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=tn(i,n.codeBlockDelimiters);if(!s)return;yield L({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=An(o,r),c=yield new u(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 yield new u(En(o,r,c)),e.content=null})}function To(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||!Ge[l])continue;let f="data_".concat(i+1,"_").concat(a+1).concat(Ge[l].extension);c.text="\nAvailable file: `".concat(f,"`\n");let d={name:f,content:Gt(c.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([d]),t.push(d))}}return t}function An(o,e){var r;let t=o.agent;if(!(t instanceof k)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function En(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[nn(t)]},r=J({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 L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Ro(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Ge[o.mimeType])return;let t=e(o.name),n=Ge[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return"\n".concat(xo,"\n\n# Load the dataframe.\n").concat(t," = ").concat(n,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var Io=new At,q=class q extends X{constructor(e){var n,r,i,s,a,c,l,f,d;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(c=e.includeContents)!=null?c:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[ho,Co,vo,Eo,yo,Io],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(Ao),e.generateContentConfig){if(e.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(e.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(e.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)&&(p.warn("Invalid config for agent ".concat(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 ".concat(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 ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(st(this.model))return this.model;if(typeof this.model=="string"&&this.model)return Se.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof q)return e.canonicalModel;e=e.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await yn(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return q.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return q.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return q.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return q.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){p.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!Ce(e)){p.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){p.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return A(this,null,function*(){for(;;){let s;try{for(var t=T(this.runOneStepAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;s=a,this.maybeSaveOutputToState(a),yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}if(!s||Ce(s))break;if(s.partial){p.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return A(this,null,function*(){try{for(var t=T(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return A(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return A(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let m of this.requestProcessors)try{for(var r=T(m.runAsync(e,t)),i,s,a;i=!(s=yield new u(r.next())).done;i=!1){let C=s.value;yield C}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(a)throw a[0]}}for(let m of this.tools){let C=new se({invocationContext:e}),I=yield new u(yn(m,new V(e)));for(let _ of I)yield new u(_.processLlmRequest({toolContext:C,llmRequest:t}))}if(e.endInvocation)return;let n=L({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var h=T(this.callLlmAsync(e,t,n)),y,g,v;y=!(g=yield new u(h.next())).done;y=!1){let m=g.value;try{for(var c=T(this.postprocess(e,t,m,n)),l,f,d;l=!(f=yield new u(c.next())).done;l=!1){let C=f.value;n.id=ze(),n.timestamp=new Date().getTime(),yield C}}catch(f){d=[f]}finally{try{l&&(f=c.return)&&(yield new u(f.call(c)))}finally{if(d)throw d[0]}}}}catch(g){v=[g]}finally{try{y&&(g=h.return)&&(yield new u(g.call(h)))}finally{if(v)throw v[0]}}})}postprocess(e,t,n,r){return A(this,null,function*(){var g,v,m,C,I;for(let j of this.responseProcessors)try{for(var f=T(j.runAsync(e,n)),d,h,y;d=!(h=yield new u(f.next())).done;d=!1){let b=h.value;yield b}}catch(h){y=[h]}finally{try{d&&(h=f.return)&&(yield new u(h.call(f)))}finally{if(y)throw y[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=L(x(x({},r),n));if(i.content){let j=B(i);if(j!=null&&j.length){Kt(i),i.longRunningToolIds=Array.from(Zt(j,t.toolsDict));let b=(g=i.content.parts)==null?void 0:g.some(w=>w.thought),E=(v=i.content.parts)==null?void 0:v.some(w=>w.thoughtSignature);p.info("[postprocess] Function call event: ".concat(j.length," calls, ")+"hasThought=".concat(b,", hasSignature=").concat(E));for(let w=0;w<(((m=i.content.parts)==null?void 0:m.length)||0);w++){let ee=i.content.parts[w];(ee.functionCall||ee.thought)&&p.info("[postprocess] Part ".concat(w,": thought=").concat(!!ee.thought,", ")+"functionCall=".concat(((C=ee.functionCall)==null?void 0:C.name)||"none",", ")+"hasSignature=".concat(!!ee.thoughtSignature))}E||p.warn("[postprocess] WARNING: Event has function calls but NO thoughtSignature! This will cause 400 errors when this content is sent back to Gemini 3.")}}if(yield i,!((I=B(i))!=null&&I.length))return;let s=yield new u(Yt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let a=Wt(e,s);a&&(yield a);let c=zt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let j=this.getAgentByName(e,l);try{for(var _=T(j.runAsync(e)),M,$,ie;M=!($=yield new u(_.next())).done;M=!1){let b=$.value;yield b}}catch($){ie=[$]}finally{try{M&&($=_.return)&&(yield new u($.call(_)))}finally{if(ie)throw ie[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return A(this,null,function*(){var s,a,c,l,f;let r=yield new u(this.handleBeforeModelCallback(e,t,n));if(r){yield r;return}(s=t.config)!=null||(t.config={}),(c=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[vn]||(t.config.labels[vn]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let v=((f=e.runConfig)==null?void 0:f.streamingMode)==="sse",m=q.LLM_TRANSIENT_ERROR_MAX_RETRIES;for(let C=0;C<=m;C++){if(C>0){let $=Math.min(q.LLM_TRANSIENT_ERROR_BASE_DELAY_MS*Math.pow(2,C-1),q.LLM_TRANSIENT_ERROR_MAX_DELAY_MS);p.warn("[callLlmAsync] Retrying LLM call after transient error "+"(attempt ".concat(C+1,"/").concat(m+1,"), waiting ").concat($,"ms")),yield new u(new Promise(ie=>setTimeout(ie,$)))}let I=i.generateContentAsync(t,v),_=!1,M=!1;try{for(var d=T(this.runAndHandleError(I,e,t,n)),h,y,g;h=!(y=yield new u(d.next())).done;h=!1){let $=y.value;if($.content&&(M=!0),$.errorCode&&q.LLM_RETRYABLE_ERROR_CODES.has($.errorCode)&&!M&&C<m){_=!0,p.warn("[callLlmAsync] Transient LLM error: ".concat($.errorCode,", ")+"usage: ".concat(JSON.stringify($.usageMetadata)));break}let ie=yield new u(this.handleAfterModelCallback(e,$,n));yield ie!=null?ie:$}}catch(y){g=[y]}finally{try{h&&(y=d.return)&&(yield new u(y.call(d)))}finally{if(g)throw g[0]}}if(!_)return}}})}async handleBeforeModelCallback(e,t,n){let r=new z({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let a=await s({context:r,request:t});if(a)return a}}async handleAfterModelCallback(e,t,n){let r=new z({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let a=await s({context:r,response:t});if(a)return a}}runAndHandleError(e,t,n,r){return A(this,null,function*(){try{try{for(var i=T(e),s,a,c;s=!(a=yield new u(i.next())).done;s=!1){let l=a.value;yield l}}catch(a){c=[a]}finally{try{s&&(a=i.return)&&(yield new u(a.call(i)))}finally{if(c)throw c[0]}}}catch(l){let f=new z({invocationContext:t,eventActions:r.actions});if(l instanceof Error){let d=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:n,error:l}));if(d)yield d;else{let h=JSON.parse(l.message);yield{errorCode:String(h.error.code),errorMessage:h.error.message}}}else throw p.error("Unknown error during response generation",l),l}})}};q.LLM_TRANSIENT_ERROR_MAX_RETRIES=2,q.LLM_TRANSIENT_ERROR_BASE_DELAY_MS=1e3,q.LLM_TRANSIENT_ERROR_MAX_DELAY_MS=4e3,q.LLM_RETRYABLE_ERROR_CODES=new Set(["UNKNOWN_ERROR"]);var k=q;var xt=class extends X{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return A(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let a of this.subAgents){let c=!1;try{for(var n=T(a.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let l=i.value;yield l,l.actions.escalate&&(c=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(c)return}t++}})}runLiveImpl(e){return A(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var bt=class extends X{runAsyncImpl(e){return A(this,null,function*(){let t=this.subAgents.map(a=>a.runAsync(wo(this,a,e)));try{for(var n=T(ko(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return A(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function wo(o,e,t){let n=new te(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function ko(o){return A(this,null,function*(){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}=yield new u(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 St="task_completed",Tt=class extends X{runAsyncImpl(e){return A(this,null,function*(){for(let s of this.subAgents)try{for(var t=T(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return A(this,null,function*(){for(let s of this.subAgents)s instanceof k&&((yield new u(s.canonicalTools(new V(e)))).some(l=>l.name===St)||(s.tools.push(new oe({name:St,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(St," 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 s of this.subAgents)try{for(var t=T(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var we=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=De(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=De(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="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(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=De(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=De(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 De(o,e,t,n){return Po(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function Po(o){return o.startsWith("user:")}var de=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=xn(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=xn(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(h=>h.text).filter(h=>!!h).join(" "),f=Lo(l);if(!f.size)continue;n.some(h=>f.has(h))&&r.memories.push({content:c.content,author:c.author,timestamp:_o(c.timestamp)})}return r}};function xn(o,e){return"".concat(o,"/").concat(e)}function Lo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function _o(o){return new Date(o).toISOString()}var pe=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var Rt=class extends pe{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: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((n=e.agent.name)!=null?n:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(Ce(t)));let n=B(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=W(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");p.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: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(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 ke=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 '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),p.info("Plugin '".concat(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 p.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw p.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 Sn="adk_request_confirmation",It="orcas_tool_call_security_check_states",bn="This tool call needs external confirmation before completion.",Tn=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Tn||{}),qe=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},wt=class extends pe{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new qe}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:bn};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(It))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(It))!=null?i:{};r[n]=t,e.state.set(It,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: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:bn};case"ALLOW":return;default:return}}};function No(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Sn&&e.push(t.functionCall);return e}var Ue=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(R.TEMP_PREFIX)||(e.state[n]=r)}};function je(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var ge=class extends Ue{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=je({id:i||ve(),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,Y(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=Y(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(je({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=>{p.warn("Failed to append event to session ".concat(s,": ").concat(l))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(R.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(R.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(R.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(R.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[R.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[R.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as Mo}from"@google/genai";import{trace as Bo}from"@opentelemetry/api";var me=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ke((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return A(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var c;i=hn(i);let a=Bo.getTracer("gcp.vertex.agent").startSpan("invocation");try{let y=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!y)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof k){let C=this.agent.canonicalModel.model;if(!C.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(C," in agent: ").concat(this.agent.name))}let g=new te({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Dt(),agent:this.agent,session:y,userContent:n,runConfig:i,pluginManager:this.pluginManager}),v=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:g}));if(v&&(n=v),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(g.invocationId,y.userId,y.id,n))),yield new u(this.sessionService.appendEvent({session:y,event:L({invocationId:g.invocationId,author:"user",actions:r?J({stateDelta:r}):void 0,content:n})}))}g.agent=this.determineAgentForResumption(y,this.agent);let m=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:g}));if(m){let C=L({invocationId:g.invocationId,author:"model",content:m});yield new u(this.sessionService.appendEvent({session:y,event:C})),yield C}else try{for(var l=T(g.agent.runAsync(g)),f,d,h;f=!(d=yield new u(l.next())).done;f=!1){let C=d.value;C.partial||(yield new u(this.sessionService.appendEvent({session:y,event:C})));let I=yield new u(this.pluginManager.runOnEventCallback({invocationContext:g,event:C}));I?yield I:yield C}}catch(d){h=[d]}finally{try{f&&(d=l.return)&&(yield new u(d.call(l)))}finally{if(h)throw h[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:g}))}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_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=Mo("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Oo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.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){p.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof k)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Oo(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=B(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var kt=class extends me{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new we,sessionService:new ge,memoryService:new de})}};import{Type as Ve}from"@google/genai";var Ke=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 Pt=class extends H{constructor(e){super({name:e.agent.name,description:e.agent.description||""}),this.agent=e.agent,this.skipSummarization=e.skipSummarization||!1}_getDeclaration(){let e;if(this.agent instanceof k&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Ve.OBJECT,properties:{request:{type:Ve.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof k&&this.agent.outputSchema;e.response=t?{type:Ve.OBJECT}:{type:Ve.STRING}}return e}async runAsync({args:e,toolContext:t}){var g,v;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof k&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new me({appName:this.agent.name,agent:this.agent,artifactService:new Ke(t),sessionService:new ge,memoryService:new de,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;try{for(var f=T(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),d,h,y;d=!(h=await f.next()).done;d=!1){let m=h.value;m.actions.stateDelta&&t.state.update(m.actions.stateDelta),a=m}}catch(h){y=[h]}finally{try{d&&(h=f.return)&&await h.call(f)}finally{if(y)throw y[0]}}if(!((v=(g=a==null?void 0:a.content)==null?void 0:g.parts)!=null&&v.length))return"";let c=this.agent instanceof k&&this.agent.outputSchema,l=a.content.parts.map(m=>m.text).filter(m=>m).join("\n");return c?JSON.parse(l):l}};var Lt=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 _t=class extends H{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||[],Xt(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(Qt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},Fo=new _t;var Rn="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",Nt=class extends oe{constructor(e){super(he(x({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Rn:e.description=Rn.trimStart(),e}};export{Pt as AgentTool,X as BaseAgent,xe as BaseLlm,pe as BasePlugin,Ue as BaseSessionService,H as BaseTool,Lt as BaseToolset,Ee as BuiltInCodeExecutor,z as CallbackContext,oe as FunctionTool,Fo as GOOGLE_SEARCH,be as Gemini,we as InMemoryArtifactService,de as InMemoryMemoryService,qe as InMemoryPolicyEngine,kt as InMemoryRunner,ge as InMemorySessionService,te as InvocationContext,Se as LLMRegistry,Je as LiveRequestQueue,k as LlmAgent,jt as LogLevel,Rt as LoggingPlugin,Nt as LongRunningFunctionTool,xt as LoopAgent,bt as ParallelAgent,ke as PluginManager,Tn as PolicyOutcome,Sn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,me as Runner,wt as SecurityPlugin,Tt as SequentialAgent,R as State,pt as StreamingMode,ce as ToolConfirmation,se as ToolContext,L as createEvent,J as createEventActions,je as createSession,qn as functionsExportedForTestingOnly,No as getAskUserConfirmationFunctionCalls,B as getFunctionCalls,W as getFunctionResponses,$t as hasTrailingCodeExecutionResult,st as isBaseLlm,Ce as isFinalResponse,On as setLogLevel,_n as stringifyContent,rt as version,$e as zodObjectToSchema};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Google LLC