@paean-ai/adk 0.2.13 → 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.
- package/dist/cjs/index.js +11 -11
- package/dist/cjs/index.js.map +3 -3
- package/dist/esm/index.js +11 -11
- package/dist/esm/index.js.map +3 -3
- package/dist/types/agents/llm_agent.d.ts +4 -0
- package/dist/web/index.js +1 -1
- package/dist/web/index.js.map +3 -3
- package/package.json +3 -3
- package/dist/cjs/agents/active_streaming_tool.js +0 -44
- package/dist/cjs/agents/base_agent.js +0 -245
- package/dist/cjs/agents/base_llm_processor.js +0 -44
- package/dist/cjs/agents/callback_context.js +0 -98
- package/dist/cjs/agents/content_processor_utils.js +0 -346
- package/dist/cjs/agents/functions.js +0 -385
- package/dist/cjs/agents/instructions.js +0 -110
- package/dist/cjs/agents/invocation_context.js +0 -107
- package/dist/cjs/agents/live_request_queue.js +0 -136
- package/dist/cjs/agents/llm_agent.js +0 -1212
- package/dist/cjs/agents/loop_agent.js +0 -68
- package/dist/cjs/agents/parallel_agent.js +0 -78
- package/dist/cjs/agents/readonly_context.js +0 -68
- package/dist/cjs/agents/run_config.js +0 -70
- package/dist/cjs/agents/sequential_agent.js +0 -84
- package/dist/cjs/agents/transcription_entry.js +0 -27
- package/dist/cjs/artifacts/base_artifact_service.js +0 -27
- package/dist/cjs/artifacts/gcs_artifact_service.js +0 -140
- package/dist/cjs/artifacts/in_memory_artifact_service.js +0 -119
- package/dist/cjs/auth/auth_credential.js +0 -46
- package/dist/cjs/auth/auth_handler.js +0 -92
- package/dist/cjs/auth/auth_schemes.js +0 -62
- package/dist/cjs/auth/auth_tool.js +0 -27
- package/dist/cjs/auth/credential_service/base_credential_service.js +0 -27
- package/dist/cjs/auth/credential_service/in_memory_credential_service.js +0 -63
- package/dist/cjs/auth/exchanger/base_credential_exchanger.js +0 -40
- package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +0 -59
- package/dist/cjs/code_executors/base_code_executor.js +0 -76
- package/dist/cjs/code_executors/built_in_code_executor.js +0 -58
- package/dist/cjs/code_executors/code_execution_utils.js +0 -142
- package/dist/cjs/code_executors/code_executor_context.js +0 -198
- package/dist/cjs/common.js +0 -181
- package/dist/cjs/events/event.js +0 -119
- package/dist/cjs/events/event_actions.js +0 -83
- package/dist/cjs/examples/base_example_provider.js +0 -40
- package/dist/cjs/examples/example.js +0 -27
- package/dist/cjs/examples/example_util.js +0 -107
- package/dist/cjs/index_web.js +0 -33
- package/dist/cjs/memory/base_memory_service.js +0 -27
- package/dist/cjs/memory/in_memory_memory_service.js +0 -97
- package/dist/cjs/memory/memory_entry.js +0 -27
- package/dist/cjs/models/base_llm.js +0 -95
- package/dist/cjs/models/base_llm_connection.js +0 -27
- package/dist/cjs/models/gemini_llm_connection.js +0 -132
- package/dist/cjs/models/google_llm.js +0 -559
- package/dist/cjs/models/llm_request.js +0 -82
- package/dist/cjs/models/llm_response.js +0 -71
- package/dist/cjs/models/registry.js +0 -121
- package/dist/cjs/plugins/base_plugin.js +0 -236
- package/dist/cjs/plugins/logging_plugin.js +0 -222
- package/dist/cjs/plugins/plugin_manager.js +0 -239
- package/dist/cjs/plugins/security_plugin.js +0 -153
- package/dist/cjs/runner/in_memory_runner.js +0 -58
- package/dist/cjs/runner/runner.js +0 -277
- package/dist/cjs/sessions/base_session_service.js +0 -71
- package/dist/cjs/sessions/in_memory_session_service.js +0 -184
- package/dist/cjs/sessions/session.js +0 -48
- package/dist/cjs/sessions/state.js +0 -101
- package/dist/cjs/telemetry/google_cloud.js +0 -85
- package/dist/cjs/telemetry/setup.js +0 -97
- package/dist/cjs/telemetry/tracing.js +0 -231
- package/dist/cjs/tools/agent_tool.js +0 -134
- package/dist/cjs/tools/base_tool.js +0 -107
- package/dist/cjs/tools/base_toolset.js +0 -76
- package/dist/cjs/tools/forwarding_artifact_service.js +0 -71
- package/dist/cjs/tools/function_tool.js +0 -101
- package/dist/cjs/tools/google_search_tool.js +0 -76
- package/dist/cjs/tools/long_running_tool.js +0 -63
- package/dist/cjs/tools/mcp/mcp_session_manager.js +0 -65
- package/dist/cjs/tools/mcp/mcp_tool.js +0 -65
- package/dist/cjs/tools/mcp/mcp_toolset.js +0 -61
- package/dist/cjs/tools/tool_confirmation.js +0 -49
- package/dist/cjs/tools/tool_context.js +0 -129
- package/dist/cjs/utils/client_labels.js +0 -56
- package/dist/cjs/utils/deep_clone.js +0 -44
- package/dist/cjs/utils/env_aware_utils.js +0 -83
- package/dist/cjs/utils/gemini_schema_util.js +0 -88
- package/dist/cjs/utils/logger.js +0 -121
- package/dist/cjs/utils/model_name.js +0 -76
- package/dist/cjs/utils/simple_zod_to_json.js +0 -191
- package/dist/cjs/utils/variant_utils.js +0 -55
- package/dist/cjs/version.js +0 -39
- package/dist/esm/agents/active_streaming_tool.js +0 -14
- package/dist/esm/agents/base_agent.js +0 -214
- package/dist/esm/agents/base_llm_processor.js +0 -13
- package/dist/esm/agents/callback_context.js +0 -68
- package/dist/esm/agents/content_processor_utils.js +0 -315
- package/dist/esm/agents/functions.js +0 -344
- package/dist/esm/agents/instructions.js +0 -80
- package/dist/esm/agents/invocation_context.js +0 -76
- package/dist/esm/agents/live_request_queue.js +0 -106
- package/dist/esm/agents/llm_agent.js +0 -1180
- package/dist/esm/agents/loop_agent.js +0 -38
- package/dist/esm/agents/parallel_agent.js +0 -48
- package/dist/esm/agents/readonly_context.js +0 -38
- package/dist/esm/agents/run_config.js +0 -39
- package/dist/esm/agents/sequential_agent.js +0 -54
- package/dist/esm/agents/transcription_entry.js +0 -5
- package/dist/esm/artifacts/base_artifact_service.js +0 -5
- package/dist/esm/artifacts/gcs_artifact_service.js +0 -110
- package/dist/esm/artifacts/in_memory_artifact_service.js +0 -89
- package/dist/esm/auth/auth_credential.js +0 -16
- package/dist/esm/auth/auth_handler.js +0 -62
- package/dist/esm/auth/auth_schemes.js +0 -31
- package/dist/esm/auth/auth_tool.js +0 -5
- package/dist/esm/auth/credential_service/base_credential_service.js +0 -5
- package/dist/esm/auth/credential_service/in_memory_credential_service.js +0 -33
- package/dist/esm/auth/exchanger/base_credential_exchanger.js +0 -10
- package/dist/esm/auth/exchanger/credential_exchanger_registry.js +0 -29
- package/dist/esm/code_executors/base_code_executor.js +0 -46
- package/dist/esm/code_executors/built_in_code_executor.js +0 -28
- package/dist/esm/code_executors/code_execution_utils.js +0 -108
- package/dist/esm/code_executors/code_executor_context.js +0 -168
- package/dist/esm/common.js +0 -98
- package/dist/esm/events/event.js +0 -83
- package/dist/esm/events/event_actions.js +0 -52
- package/dist/esm/examples/base_example_provider.js +0 -10
- package/dist/esm/examples/example.js +0 -5
- package/dist/esm/examples/example_util.js +0 -76
- package/dist/esm/index_web.js +0 -6
- package/dist/esm/memory/base_memory_service.js +0 -5
- package/dist/esm/memory/in_memory_memory_service.js +0 -67
- package/dist/esm/memory/memory_entry.js +0 -5
- package/dist/esm/models/base_llm.js +0 -64
- package/dist/esm/models/base_llm_connection.js +0 -5
- package/dist/esm/models/gemini_llm_connection.js +0 -102
- package/dist/esm/models/google_llm.js +0 -533
- package/dist/esm/models/llm_request.js +0 -50
- package/dist/esm/models/llm_response.js +0 -41
- package/dist/esm/models/registry.js +0 -91
- package/dist/esm/plugins/base_plugin.js +0 -206
- package/dist/esm/plugins/logging_plugin.js +0 -192
- package/dist/esm/plugins/plugin_manager.js +0 -209
- package/dist/esm/plugins/security_plugin.js +0 -119
- package/dist/esm/runner/in_memory_runner.js +0 -28
- package/dist/esm/runner/runner.js +0 -247
- package/dist/esm/sessions/base_session_service.js +0 -41
- package/dist/esm/sessions/in_memory_session_service.js +0 -154
- package/dist/esm/sessions/session.js +0 -18
- package/dist/esm/sessions/state.js +0 -71
- package/dist/esm/telemetry/google_cloud.js +0 -54
- package/dist/esm/telemetry/setup.js +0 -67
- package/dist/esm/telemetry/tracing.js +0 -195
- package/dist/esm/tools/agent_tool.js +0 -104
- package/dist/esm/tools/base_tool.js +0 -77
- package/dist/esm/tools/base_toolset.js +0 -46
- package/dist/esm/tools/forwarding_artifact_service.js +0 -41
- package/dist/esm/tools/function_tool.js +0 -71
- package/dist/esm/tools/google_search_tool.js +0 -46
- package/dist/esm/tools/long_running_tool.js +0 -33
- package/dist/esm/tools/mcp/mcp_session_manager.js +0 -35
- package/dist/esm/tools/mcp/mcp_tool.js +0 -35
- package/dist/esm/tools/mcp/mcp_toolset.js +0 -31
- package/dist/esm/tools/tool_confirmation.js +0 -19
- package/dist/esm/tools/tool_context.js +0 -99
- package/dist/esm/utils/client_labels.js +0 -26
- package/dist/esm/utils/deep_clone.js +0 -14
- package/dist/esm/utils/env_aware_utils.js +0 -49
- package/dist/esm/utils/gemini_schema_util.js +0 -58
- package/dist/esm/utils/logger.js +0 -89
- package/dist/esm/utils/model_name.js +0 -41
- package/dist/esm/utils/simple_zod_to_json.js +0 -160
- package/dist/esm/utils/variant_utils.js +0 -24
- package/dist/esm/version.js +0 -9
- package/dist/web/agents/active_streaming_tool.js +0 -14
- package/dist/web/agents/base_agent.js +0 -265
- package/dist/web/agents/base_llm_processor.js +0 -13
- package/dist/web/agents/callback_context.js +0 -68
- package/dist/web/agents/content_processor_utils.js +0 -315
- package/dist/web/agents/functions.js +0 -344
- package/dist/web/agents/instructions.js +0 -80
- package/dist/web/agents/invocation_context.js +0 -76
- package/dist/web/agents/live_request_queue.js +0 -124
- package/dist/web/agents/llm_agent.js +0 -1310
- package/dist/web/agents/loop_agent.js +0 -71
- package/dist/web/agents/parallel_agent.js +0 -83
- package/dist/web/agents/readonly_context.js +0 -38
- package/dist/web/agents/run_config.js +0 -54
- package/dist/web/agents/sequential_agent.js +0 -99
- package/dist/web/agents/transcription_entry.js +0 -5
- package/dist/web/artifacts/base_artifact_service.js +0 -5
- package/dist/web/artifacts/gcs_artifact_service.js +0 -126
- package/dist/web/artifacts/in_memory_artifact_service.js +0 -89
- package/dist/web/auth/auth_credential.js +0 -16
- package/dist/web/auth/auth_handler.js +0 -62
- package/dist/web/auth/auth_schemes.js +0 -31
- package/dist/web/auth/auth_tool.js +0 -5
- package/dist/web/auth/credential_service/base_credential_service.js +0 -5
- package/dist/web/auth/credential_service/in_memory_credential_service.js +0 -33
- package/dist/web/auth/exchanger/base_credential_exchanger.js +0 -10
- package/dist/web/auth/exchanger/credential_exchanger_registry.js +0 -29
- package/dist/web/code_executors/base_code_executor.js +0 -46
- package/dist/web/code_executors/built_in_code_executor.js +0 -28
- package/dist/web/code_executors/code_execution_utils.js +0 -105
- package/dist/web/code_executors/code_executor_context.js +0 -168
- package/dist/web/common.js +0 -98
- package/dist/web/events/event.js +0 -101
- package/dist/web/events/event_actions.js +0 -67
- package/dist/web/examples/base_example_provider.js +0 -10
- package/dist/web/examples/example.js +0 -5
- package/dist/web/examples/example_util.js +0 -75
- package/dist/web/index_web.js +0 -6
- package/dist/web/memory/base_memory_service.js +0 -5
- package/dist/web/memory/in_memory_memory_service.js +0 -67
- package/dist/web/memory/memory_entry.js +0 -5
- package/dist/web/models/base_llm.js +0 -64
- package/dist/web/models/base_llm_connection.js +0 -5
- package/dist/web/models/gemini_llm_connection.js +0 -120
- package/dist/web/models/google_llm.js +0 -574
- package/dist/web/models/llm_request.js +0 -50
- package/dist/web/models/llm_response.js +0 -41
- package/dist/web/models/registry.js +0 -91
- package/dist/web/plugins/base_plugin.js +0 -206
- package/dist/web/plugins/logging_plugin.js +0 -192
- package/dist/web/plugins/plugin_manager.js +0 -209
- package/dist/web/plugins/security_plugin.js +0 -119
- package/dist/web/runner/in_memory_runner.js +0 -28
- package/dist/web/runner/runner.js +0 -278
- package/dist/web/sessions/base_session_service.js +0 -41
- package/dist/web/sessions/in_memory_session_service.js +0 -154
- package/dist/web/sessions/session.js +0 -18
- package/dist/web/sessions/state.js +0 -87
- package/dist/web/telemetry/google_cloud.js +0 -54
- package/dist/web/telemetry/setup.js +0 -67
- package/dist/web/telemetry/tracing.js +0 -210
- package/dist/web/tools/agent_tool.js +0 -118
- package/dist/web/tools/base_tool.js +0 -77
- package/dist/web/tools/base_toolset.js +0 -46
- package/dist/web/tools/forwarding_artifact_service.js +0 -41
- package/dist/web/tools/function_tool.js +0 -71
- package/dist/web/tools/google_search_tool.js +0 -46
- package/dist/web/tools/long_running_tool.js +0 -50
- package/dist/web/tools/mcp/mcp_session_manager.js +0 -35
- package/dist/web/tools/mcp/mcp_tool.js +0 -35
- package/dist/web/tools/mcp/mcp_toolset.js +0 -31
- package/dist/web/tools/tool_confirmation.js +0 -19
- package/dist/web/tools/tool_context.js +0 -99
- package/dist/web/utils/client_labels.js +0 -26
- package/dist/web/utils/deep_clone.js +0 -14
- package/dist/web/utils/env_aware_utils.js +0 -49
- package/dist/web/utils/gemini_schema_util.js +0 -58
- package/dist/web/utils/logger.js +0 -89
- package/dist/web/utils/model_name.js +0 -41
- package/dist/web/utils/simple_zod_to_json.js +0 -174
- package/dist/web/utils/variant_utils.js +0 -24
- package/dist/web/version.js +0 -9
package/dist/cjs/index.js
CHANGED
|
@@ -4,17 +4,17 @@
|
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
"use strict";var at=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var no=Object.prototype.hasOwnProperty;var oo=(o,e)=>{for(var t in e)at(o,t,{get:e[t],enumerable:!0})},ro=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of to(e))!no.call(o,r)&&r!==t&&at(o,r,{get:()=>e[r],enumerable:!(n=eo(e,r))||n.enumerable});return o};var io=o=>ro(at({},"__esModule",{value:!0}),o);var lr={};oo(lr,{AgentTool:()=>Xe,BaseAgent:()=>U,BaseLlm:()=>ue,BasePlugin:()=>ne,BaseSessionService:()=>Re,BaseTool:()=>B,BaseToolset:()=>ve,BuiltInCodeExecutor:()=>se,CallbackContext:()=>D,FunctionTool:()=>z,GOOGLE_SEARCH:()=>Nn,GcsArtifactService:()=>qt,Gemini:()=>fe,InMemoryArtifactService:()=>he,InMemoryMemoryService:()=>te,InMemoryPolicyEngine:()=>Se,InMemoryRunner:()=>Ye,InMemorySessionService:()=>oe,InvocationContext:()=>Z,LLMRegistry:()=>de,LiveRequestQueue:()=>Fe,LlmAgent:()=>A,LogLevel:()=>pt,LoggingPlugin:()=>ze,LongRunningFunctionTool:()=>Je,LoopAgent:()=>Ke,MCPSessionManager:()=>we,MCPTool:()=>ke,MCPToolset:()=>Dt,ParallelAgent:()=>Ve,PluginManager:()=>Ce,PolicyOutcome:()=>Ft,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Bt,Runner:()=>re,SecurityPlugin:()=>He,SequentialAgent:()=>Ze,State:()=>E,StreamingMode:()=>Ue,ToolConfirmation:()=>J,ToolContext:()=>Y,createEvent:()=>S,createEventActions:()=>V,createSession:()=>Ie,functionsExportedForTestingOnly:()=>Yt,getAskUserConfirmationFunctionCalls:()=>Ln,getFunctionCalls:()=>w,getFunctionResponses:()=>$,getGcpExporters:()=>ar,getGcpResource:()=>cr,hasTrailingCodeExecutionResult:()=>ct,isBaseLlm:()=>De,isFinalResponse:()=>ie,maybeSetOtelProviders:()=>tr,setLogLevel:()=>zt,stringifyContent:()=>Kt,version:()=>Ge,zodObjectToSchema:()=>Te});module.exports=io(lr);var ft=require("@opentelemetry/api");function V(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function Ut(o,e){let t=V();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 S(o={}){return{...o,id:o.id||lt(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||V(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function ie(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:w(o).length===0&&$(o).length===0&&!o.partial&&!ct(o)}function w(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 $(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 ct(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 Kt(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 jt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function lt(){let o="";for(let e=0;e<8;e++)o+=jt[Math.floor(Math.random()*jt.length)];return o}var E=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};E.APP_PREFIX="app:",E.USER_PREFIX="user:",E.TEMP_PREFIX="temp:";var G=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 E(this.invocationContext.session.state,{})}};var D=class extends G{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||V(),this._state=new E(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 Me(){return typeof window<"u"}var _e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function pe(){let o="";for(let e=0;e<_e.length;e++){let t=Math.random()*16|0;_e[e]==="x"?o+=t.toString(16):_e[e]==="y"?o+=(t&3|8).toString(16):o+=_e[e]}return o}function Vt(o){return Me()?window.atob(o):Buffer.from(o,"base64").toString()}var ut=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},Z=class{constructor(e){this.invocationCostManager=new ut;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 Zt(){return`e-${pe()}`}var U=class{constructor(e){this.name=so(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=co(this),this.beforeAgentCallback=Wt(e.beforeAgentCallback),this.afterAgentCallback=Wt(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=ft.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=ft.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new Z({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new D({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,S({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return S({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new D({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return S({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return S({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function so(o){if(!ao(o))throw new Error(`Found invalid agent name: "${o}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function ao(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function co(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Wt(o){return o?Array.isArray(o)?o:[o]:[]}var Ht=require("@google/genai");var xe=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var J=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var Y=class extends D{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 xe(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new xe(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 J({hint:e,confirmed:!1,payload:t})}};var pt=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(pt||{}),me=1;function zt(o){me=o}var dt=class{log(e,...t){if(!(e<me))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){me>0||console.debug(Ne(0),...e)}info(...e){me>1||console.info(Ne(1),...e)}warn(...e){me>2||console.warn(Ne(2),...e)}error(...e){me>3||console.error(Ne(3),...e)}},lo={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},uo={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},fo="\x1B[0m";function Ne(o){return`${uo[o]}[ADK ${lo[o]}]:${fo}`}var d=new dt;var mt="adk-",Oe="adk_request_credential",ge="adk_request_confirmation",Yt={handleFunctionCallList:Be};function gt(){return`${mt}${pe()}`}function Qt(o){let e=w(o);if(e)for(let t of e)t.id||(t.id=gt())}function Xt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(mt)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(mt)&&(e.functionResponse.id=void 0)}function Jt(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 en(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:Oe,args:{function_call_id:i,auth_config:s},id:gt()};n.add(a.id),t.push({functionCall:a})}return S({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function tn({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=w(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(p=>p.id===c))!=null?a:void 0;if(!f)continue;let u={name:ge,args:{originalFunctionCall:f,toolConfirmation:l},id:gt()};r.add(u.id),n.push({functionCall:u})}return S({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function po(o,e,t){return d.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function nn({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=w(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(u=>!i||u.id&&i.has(u.id));for(let u of c){let p;s&&u.id&&(p=s[u.id]);let{tool:y,toolContext:g}=mo({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:p});d.debug(`execute_tool ${y.name}`);let m=(f=u.args)!=null?f:{},C=null,P;if(C=await o.pluginManager.runBeforeToolCallback({tool:y,toolArgs:m,toolContext:g}),C==null){for(let h of n)if(C=await h({tool:y,args:m,context:g}),C)break}if(C==null)try{C=await po(y,m,g)}catch(h){if(h instanceof Error){let v=await o.pluginManager.runOnToolErrorCallback({tool:y,toolArgs:m,toolContext:g,error:h});v?C=v:P=h.message}else P=h}let b=await o.pluginManager.runAfterToolCallback({tool:y,toolArgs:m,toolContext:g,result:C});if(b==null){for(let h of r)if(b=await h({tool:y,args:m,context:g,response:C}),b)break}if(b!=null&&(C=b),y.isLongRunning&&!C)continue;P?C={error:P}:(typeof C!="object"||C==null)&&(C={result:C});let T=S({invocationId:o.invocationId,author:o.agent.name,content:(0,Ht.createUserContent)({functionResponse:{id:g.functionCallId,name:y.name,response:C}}),actions:g.actions,branch:o.branch});d.debug("traceToolCall",{tool:y.name,args:m,functionResponseEvent:T.id}),a.push(T)}if(!a.length)return null;let l=go(a);return a.length>1&&(d.debug("execute_tool (merged)"),d.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function mo({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new Y({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function go(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=Ut(n);return S({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Fe=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var St=require("zod");var ee=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 ho="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function $e(o){let e=o.match(ho);return e?e[1]:o}function on(o){return $e(o).startsWith("gemini-")}function rn(o){return $e(o).startsWith("gemini-1")}function sn(o){return $e(o).startsWith("gemini-2")}function an(o){let e=$e(o);return e.startsWith("gemini-3")&&e.includes("preview")}var se=class extends ee{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&sn(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 ${e.model}`)}};var Ee=require("@google/genai");function j(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function cn(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let p=o.parts[u];if(p.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),p.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=j(t[0]),r=t.map(u=>u.text).join(`
|
|
8
|
-
`),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[1]).join("|"),a=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(o.parts=[],c&&(n.text=c,o.parts.push(n)),o.parts.push(
|
|
7
|
+
"use strict";var ct=Object.defineProperty;var to=Object.getOwnPropertyDescriptor;var no=Object.getOwnPropertyNames;var oo=Object.prototype.hasOwnProperty;var ro=(o,e)=>{for(var t in e)ct(o,t,{get:e[t],enumerable:!0})},io=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of no(e))!oo.call(o,r)&&r!==t&&ct(o,r,{get:()=>e[r],enumerable:!(n=to(e,r))||n.enumerable});return o};var so=o=>io(ct({},"__esModule",{value:!0}),o);var ur={};ro(ur,{AgentTool:()=>Je,BaseAgent:()=>j,BaseLlm:()=>fe,BasePlugin:()=>oe,BaseSessionService:()=>Ie,BaseTool:()=>F,BaseToolset:()=>ye,BuiltInCodeExecutor:()=>ae,CallbackContext:()=>q,FunctionTool:()=>Y,GOOGLE_SEARCH:()=>On,GcsArtifactService:()=>Ut,Gemini:()=>de,InMemoryArtifactService:()=>Ce,InMemoryMemoryService:()=>ne,InMemoryPolicyEngine:()=>Re,InMemoryRunner:()=>Xe,InMemorySessionService:()=>re,InvocationContext:()=>W,LLMRegistry:()=>pe,LiveRequestQueue:()=>$e,LlmAgent:()=>b,LogLevel:()=>mt,LoggingPlugin:()=>Ye,LongRunningFunctionTool:()=>et,LoopAgent:()=>Ve,MCPSessionManager:()=>Le,MCPTool:()=>ke,MCPToolset:()=>qt,ParallelAgent:()=>Ze,PluginManager:()=>ve,PolicyOutcome:()=>$t,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Ft,Runner:()=>ie,SecurityPlugin:()=>He,SequentialAgent:()=>We,State:()=>T,StreamingMode:()=>je,ToolConfirmation:()=>ee,ToolContext:()=>X,createEvent:()=>R,createEventActions:()=>Z,createSession:()=>Pe,functionsExportedForTestingOnly:()=>Xt,getAskUserConfirmationFunctionCalls:()=>_n,getFunctionCalls:()=>w,getFunctionResponses:()=>G,getGcpExporters:()=>cr,getGcpResource:()=>lr,hasTrailingCodeExecutionResult:()=>lt,isBaseLlm:()=>qe,isFinalResponse:()=>se,maybeSetOtelProviders:()=>nr,setLogLevel:()=>Yt,stringifyContent:()=>Vt,version:()=>De,zodObjectToSchema:()=>Se});module.exports=so(ur);var dt=require("@opentelemetry/api");function Z(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function jt(o,e){let t=Z();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 R(o={}){return{...o,id:o.id||ut(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||Z(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function se(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:w(o).length===0&&G(o).length===0&&!o.partial&&!lt(o)}function w(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 G(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 lt(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 Vt(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 Kt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function ut(){let o="";for(let e=0;e<8;e++)o+=Kt[Math.floor(Math.random()*Kt.length)];return o}var T=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};T.APP_PREFIX="app:",T.USER_PREFIX="user:",T.TEMP_PREFIX="temp:";var D=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 T(this.invocationContext.session.state,{})}};var q=class extends D{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||Z(),this._state=new T(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 Ne(){return typeof window<"u"}var Me="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function me(){let o="";for(let e=0;e<Me.length;e++){let t=Math.random()*16|0;Me[e]==="x"?o+=t.toString(16):Me[e]==="y"?o+=(t&3|8).toString(16):o+=Me[e]}return o}function Zt(o){return Ne()?window.atob(o):Buffer.from(o,"base64").toString()}var ft=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},W=class{constructor(e){this.invocationCostManager=new ft;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 Wt(){return`e-${me()}`}var j=class{constructor(e){this.name=ao(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=lo(this),this.beforeAgentCallback=zt(e.beforeAgentCallback),this.afterAgentCallback=zt(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=dt.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=dt.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new W({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new q({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,R({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return R({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new q({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return R({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return R({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function ao(o){if(!co(o))throw new Error(`Found invalid agent name: "${o}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function co(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function lo(o){for(;o.parentAgent;)o=o.parentAgent;return o}function zt(o){return o?Array.isArray(o)?o:[o]:[]}var Ht=require("@google/genai");var Ae=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var ee=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var X=class extends q{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 Ae(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ae(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 ee({hint:e,confirmed:!1,payload:t})}};var mt=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(mt||{}),ge=1;function Yt(o){ge=o}var pt=class{log(e,...t){if(!(e<ge))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){ge>0||console.debug(Oe(0),...e)}info(...e){ge>1||console.info(Oe(1),...e)}warn(...e){ge>2||console.warn(Oe(2),...e)}error(...e){ge>3||console.error(Oe(3),...e)}},uo={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},fo={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},po="\x1B[0m";function Oe(o){return`${fo[o]}[ADK ${uo[o]}]:${po}`}var d=new pt;var gt="adk-",Be="adk_request_credential",he="adk_request_confirmation",Xt={handleFunctionCallList:Fe};function ht(){return`${gt}${me()}`}function Qt(o){let e=w(o);if(e)for(let t of e)t.id||(t.id=ht())}function Jt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(gt)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(gt)&&(e.functionResponse.id=void 0)}function en(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 tn(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:Be,args:{function_call_id:i,auth_config:s},id:ht()};n.add(a.id),t.push({functionCall:a})}return R({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function nn({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=w(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(p=>p.id===c))!=null?a:void 0;if(!f)continue;let u={name:he,args:{originalFunctionCall:f,toolConfirmation:l},id:ht()};r.add(u.id),n.push({functionCall:u})}return R({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function mo(o,e,t){return d.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function on({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=w(e);return await Fe({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Fe({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of c){let p;s&&u.id&&(p=s[u.id]);let{tool:v,toolContext:g}=go({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:p});d.debug(`execute_tool ${v.name}`);let m=(f=u.args)!=null?f:{},C=null,E;if(C=await o.pluginManager.runBeforeToolCallback({tool:v,toolArgs:m,toolContext:g}),C==null){for(let h of n)if(C=await h({tool:v,args:m,context:g}),C)break}if(C==null)try{C=await mo(v,m,g)}catch(h){if(h instanceof Error){let y=await o.pluginManager.runOnToolErrorCallback({tool:v,toolArgs:m,toolContext:g,error:h});y?C=y:E=h.message}else E=h}let A=await o.pluginManager.runAfterToolCallback({tool:v,toolArgs:m,toolContext:g,result:C});if(A==null){for(let h of r)if(A=await h({tool:v,args:m,context:g,response:C}),A)break}if(A!=null&&(C=A),v.isLongRunning&&!C)continue;E?C={error:E}:(typeof C!="object"||C==null)&&(C={result:C});let S=R({invocationId:o.invocationId,author:o.agent.name,content:(0,Ht.createUserContent)({functionResponse:{id:g.functionCallId,name:v.name,response:C}}),actions:g.actions,branch:o.branch});d.debug("traceToolCall",{tool:v.name,args:m,functionResponseEvent:S.id}),a.push(S)}if(!a.length)return null;let l=ho(a);return a.length>1&&(d.debug("execute_tool (merged)"),d.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function go({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new X({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function ho(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=jt(n);return R({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var $e=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var Rt=require("zod");var te=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 Co="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ge(o){let e=o.match(Co);return e?e[1]:o}function rn(o){return Ge(o).startsWith("gemini-")}function sn(o){return Ge(o).startsWith("gemini-1")}function an(o){return Ge(o).startsWith("gemini-2")}function cn(o){let e=Ge(o);return e.startsWith("gemini-3")&&e.includes("preview")}var ae=class extends te{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&an(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 ${e.model}`)}};var xe=require("@google/genai");function K(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function ln(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let p=o.parts[u];if(p.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),p.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=K(t[0]),r=t.map(u=>u.text).join(`
|
|
8
|
+
`),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[1]).join("|"),a=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(o.parts=[],c&&(n.text=c,o.parts.push(n)),o.parts.push(Ct(l)),l):""}function Ct(o){return{text:o,executableCode:{code:o,language:xe.Language.PYTHON}}}function un(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:xe.Outcome.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push(`Code execution result:
|
|
9
9
|
${o.stdout}
|
|
10
10
|
`),o.outputFiles&&e.push(`Saved artifacts:
|
|
11
11
|
`+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
|
|
12
12
|
|
|
13
|
-
`),codeExecutionResult:{outcome:
|
|
13
|
+
`),codeExecutionResult:{outcome:xe.Outcome.OUTCOME_OK}}}function fn(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 vt="_code_execution_context",yt="execution_session_id",ce="processed_input_files",le="_code_executor_input_files",ue="_code_executor_error_counts",Et="_code_execution_results",Te=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(vt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[vt]:K(this.context)}}getExecutionId(){if(yt in this.context)return this.context[yt]}setExecutionId(e){this.context[yt]=e}getProcessedFileNames(){return ce in this.context?this.context[ce]:[]}addProcessedFileNames(e){ce in this.context||(this.context[ce]=[]),this.context[ce].push(...e)}getInputFiles(){return le in this.sessionState?this.sessionState.get(le):[]}addInputFiles(e){le in this.sessionState||this.sessionState.set(le,[]),this.sessionState.get(le).push(...e)}clearInputFiles(){le in this.sessionState&&this.sessionState.set(le,[]),ce in this.context&&(this.context[ce]=[])}getErrorCount(e){return ue in this.sessionState&&this.sessionState.get(ue)[e]||0}incrementErrorCount(e){ue in this.sessionState||this.sessionState.set(ue,{}),this.sessionState.get(ue)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(ue in this.sessionState))return;let t=this.sessionState.get(ue);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){Et in this.sessionState||this.sessionState.set(Et,{});let i=this.sessionState.get(Et);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(vt)||{}}};var De="0.2.4";var vo="google-adk",yo="gl-typescript",Eo="remote_reasoning_engine",Ao="GOOGLE_CLOUD_AGENT_ENGINE_ID";function xo(){let o=`${vo}/${De}`;!Ne()&&process.env[Ao]&&(o=`${o}+${Eo}`);let e=`${yo}/${Ne()?window.navigator.userAgent:process.version}`;return[o,e]}function dn(){return xo()}var At=Symbol("baseModel");function qe(o){return typeof o=="object"&&o!==null&&At in o&&o[At]===!0}var pn;pn=At;var fe=class{constructor({model:e}){this[pn]=!0;this.model=e}get trackingHeaders(){let t=dn().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."}]})}};fe.supportedModels=[];function be(o,e){o.config||(o.config={});let t=e.join(`
|
|
14
14
|
|
|
15
15
|
`);o.config.systemInstruction?o.config.systemInstruction+=`
|
|
16
16
|
|
|
17
|
-
`+t:o.config.systemInstruction=t}function pn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var W=require("@google/genai");function mn(){return Ao("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Ao(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var qe=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"}):d.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);d.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else d.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){d.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function Et(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",fe=class extends ue{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=an(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,d.info(`Using Gemini 3 preview endpoint: ${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?(d.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):d.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.")}async*generateContentAsync(e,t=!1){var n,r,i,s,a,c,l,f,u,p,y,g,m,C,P,b;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),d.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let T=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),h="",v,_="",it,k;this.isGemini3Preview&&this.cachedThoughtSignature&&d.info(`[Gemini3] Starting new request with CACHED thoughtSignature (length: ${this.cachedThoughtSignature.length})`);for await(let R of T){k=R;let x=Et(R);it=x.usageMetadata;let q=(s=(i=x.content)==null?void 0:i.parts)==null?void 0:s[0],st=(c=(a=x.content)==null?void 0:a.parts)==null?void 0:c.some(N=>N.functionCall);if(this.isGemini3Preview&&((l=x.content)!=null&&l.parts)){for(let N of x.content.parts)if(N.thoughtSignature&&!v){v=N.thoughtSignature,this.cachedThoughtSignature=v,d.info(`[Gemini3] Captured and CACHED thoughtSignature from response part (length: ${v.length})`);break}}if(q!=null&&q.text){if("thought"in q&&q.thought?(h+=q.text,"thoughtSignature"in q&&q.thoughtSignature&&(v=q.thoughtSignature,this.cachedThoughtSignature=v,d.info(`[Gemini3] Captured and CACHED thoughtSignature from thought part (length: ${v.length})`))):_+=q.text,x.partial=!0,this.isGemini3Preview&&st){let N=(u=(f=x.content)==null?void 0:f.parts)==null?void 0:u.some(L=>L.thoughtSignature);d.info(`[Gemini3] Chunk has thought AND function calls. Response has signature: ${N}`),h="",v=void 0,_=""}}else if((h||_)&&(!q||!q.inlineData))if(this.isGemini3Preview&&st&&x.content){d.info(`[Gemini3] Merging thought with function calls. Has accumulated signature: ${!!v}`);let N=[];if(h){let L={text:h,thought:!0};v&&(L.thoughtSignature=v),N.push(L),d.info(`[Gemini3] Created thought part with signature: ${!!v}`)}if(_&&N.push((0,W.createPartFromText)(_)),!h&&v){let L=!1;for(let F of x.content.parts||[])F.functionCall&&!L&&(F.thoughtSignature||(F.thoughtSignature=v,d.info(`[Gemini3] Applied accumulated signature to first function call: ${F.functionCall.name}`)),L=!0)}x.content.parts=[...N,...x.content.parts||[]],d.info(`[Gemini3] Final merged content has ${x.content.parts.length} parts`);for(let L=0;L<x.content.parts.length;L++){let F=x.content.parts[L];d.info(`[Gemini3] Part ${L}: thought=${!!F.thought}, functionCall=${((p=F.functionCall)==null?void 0:p.name)||"none"}, hasSignature=${!!F.thoughtSignature}`)}h="",v=void 0,_=""}else{let N=[];if(h){let L={text:h,thought:!0};v&&(L.thoughtSignature=v),N.push(L)}_&&N.push((0,W.createPartFromText)(_)),yield{content:{role:"model",parts:N},usageMetadata:x.usageMetadata},h="",v=void 0,_=""}if(this.isGemini3Preview&&st&&((y=x.content)!=null&&y.parts)){if(!x.content.parts.some(O=>O.thoughtSignature)&&v){for(let O of x.content.parts)if(O.functionCall){O.thoughtSignature=v,d.info(`[Gemini3] Applied cached signature to first function call: ${O.functionCall.name}`);break}}let L=x.content.parts.filter(O=>O.functionCall).map(O=>O.functionCall.name),F=x.content.parts.filter(O=>O.thoughtSignature).length;if(F===0){let O=v||this.cachedThoughtSignature;if(O){for(let Le of x.content.parts)if(Le.functionCall&&!Le.thoughtSignature){Le.thoughtSignature=O,d.info(`[Gemini3] Applied CACHED signature to function call: ${Le.functionCall.name} (API didn't return new signature, using ${v?"local":"class-level"} cache)`),F=1;break}}}d.info(`[Gemini3] Yielding function call response: calls=[${L.join(", ")}], partsWithSignature=${F}`),F===0&&d.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}yield x}if((_||h)&&((m=(g=k==null?void 0:k.candidates)==null?void 0:g[0])==null?void 0:m.finishReason)===W.FinishReason.STOP){let R=[];if(h){let x={text:h,thought:!0};v&&(x.thoughtSignature=v),R.push(x)}_&&R.push({text:_}),yield{content:{role:"model",parts:R},usageMetadata:it}}}else{let T=await this.apiClient.models.generateContent({model:(C=e.model)!=null?C:this.model,contents:e.contents,config:e.config}),h=Et(T);if(this.isGemini3Preview&&((P=h.content)!=null&&P.parts)){let v,_=!1;for(let k of h.content.parts)if(k.thoughtSignature){v=k.thoughtSignature,this.cachedThoughtSignature=v,k.thought&&(_=!0);break}if(d.info(`[Gemini3] Non-streaming response: hasSignature=${!!v}, hasThoughtPart=${_}, hasCachedSig=${!!this.cachedThoughtSignature}`),v&&!_){let k=!1;for(let R of h.content.parts)R.functionCall&&(!k&&!R.thoughtSignature&&(R.thoughtSignature=v,d.info(`[Gemini3] Applied signature to first function call: ${R.functionCall.name}`)),k=!0)}if(h.content.parts.some(k=>k.functionCall)){let k=h.content.parts.filter(R=>R.thoughtSignature).length;if(k===0&&this.cachedThoughtSignature){for(let R of h.content.parts)if(R.functionCall&&!R.thoughtSignature){R.thoughtSignature=this.cachedThoughtSignature,d.info(`[Gemini3] Applied CACHED signature to function call: ${R.functionCall.name} (API didn't return new signature)`),k=1;break}}for(let R=0;R<h.content.parts.length;R++){let x=h.content.parts[R];d.info(`[Gemini3] Response Part ${R}: thought=${!!x.thought}, functionCall=${((b=x.functionCall)==null?void 0:b.name)||"none"}, hasSignature=${!!x.thoughtSignature}`)}k===0&&d.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}}yield h}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new W.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,d.debug(`Using custom API endpoint: ${this.apiEndpoint}`),this.isGemini3Preview&&(t.apiVersion="",d.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new W.GoogleGenAI({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 W.GoogleGenAI({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:[(0,W.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new qe(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)gn(n.inlineData),gn(n.fileData)}}};fe.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function gn(o){o&&o.displayName&&(o.displayName=void 0)}var At=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)}},K=class K{static newLlm(e){return new(K.resolve(e))({model:e})}static _register(e,t){K.llmRegistryDict.has(e)&&d.info(`Updating LLM class for ${e} from ${K.llmRegistryDict.get(e)} to ${t}`),K.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)K._register(t,e)}static resolve(e){let t=K.resolveCache.get(e);if(t)return t;for(let[n,r]of K.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return K.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};K.llmRegistryDict=new Map,K.resolveCache=new At(32);var de=K;de.register(fe);var B=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=So(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 mn()}};function So(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var Cn=require("@google/genai"),vn=require("zod");var M=require("@google/genai"),I=require("zod");function hn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function Q(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 I.z.ZodFirstPartyTypeKind.ZodString:n.type=M.Type.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case I.z.ZodFirstPartyTypeKind.ZodNumber:n.type=M.Type.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=M.Type.INTEGER);return r(n);case I.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=M.Type.BOOLEAN,r(n);case I.z.ZodFirstPartyTypeKind.ZodArray:return n.type=M.Type.ARRAY,n.items=Q(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case I.z.ZodFirstPartyTypeKind.ZodObject:return Te(o);case I.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=M.Type.STRING;else if(i==="number")n.type=M.Type.NUMBER;else if(i==="boolean")n.type=M.Type.BOOLEAN;else if(e.value===null)n.type=M.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case I.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=M.Type.STRING,n.enum=e.values,r(n);case I.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=M.Type.STRING,n.enum=Object.values(e.values),r(n);case I.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(Q),r(n);case I.z.ZodFirstPartyTypeKind.ZodOptional:return Q(e.innerType);case I.z.ZodFirstPartyTypeKind.ZodNullable:let s=Q(e.innerType);return r(s?{anyOf:[s,{type:M.Type.NULL}],...t&&{description:t}}:{type:M.Type.NULL,...t&&{description:t}});case I.z.ZodFirstPartyTypeKind.ZodDefault:let a=Q(e.innerType);return a&&(a.default=e.defaultValue()),a;case I.z.ZodFirstPartyTypeKind.ZodBranded:return Q(e.type);case I.z.ZodFirstPartyTypeKind.ZodReadonly:return Q(e.innerType);case I.z.ZodFirstPartyTypeKind.ZodNull:return n.type=M.Type.NULL,r(n);case I.z.ZodFirstPartyTypeKind.ZodAny:case I.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Te(o){if(o._def.typeName!==I.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=Q(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===I.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===I.z.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==I.z.ZodFirstPartyTypeKind.ZodNever?i=Q(r)||!0:i=o._def.unknownKeys==="passthrough",{type:M.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Ro(o){return o===void 0?{type:Cn.Type.OBJECT,properties:{}}:hn(o)?Te(o):o}var z=class extends B{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 vn.ZodObject&&(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 '${this.name}': ${n}`)}}};var X=class{};function bt(o,e,t){var c,l,f,u,p,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)||Io(g)||Po(g)||n.push(En(e,g)?wo(g):g);let r=ko(n);r=Lo(r);let i=[];for(let g of r){let m=j(g.content);Xt(m),i.push(m)}let s=!1,a=-1;for(let g=0;g<i.length;g++){let m=i[g],C=(f=m.parts)==null?void 0:f.some(T=>T.functionCall),P=(u=m.parts)==null?void 0:u.some(T=>T.thoughtSignature),b=(p=m.parts)==null?void 0:p.some(T=>T.thought);if(C){d.info(`[getContents] Content block ${g+1}/${i.length}: role=${m.role}, hasFunctionCalls=true, hasThought=${b}, hasSignature=${P}`),!P&&m.role==="model"&&(s=!0,a=g+1);for(let T=0;T<(((y=m.parts)==null?void 0:y.length)||0);T++){let h=m.parts[T];h.functionCall?d.info(`[getContents] Part ${T}: functionCall=${h.functionCall.name}, hasSignature=${!!h.thoughtSignature}`):h.thought&&d.info(`[getContents] Part ${T}: thought=true, hasSignature=${!!h.thoughtSignature}`)}}}return s&&d.warn(`[getContents] WARNING: Content block ${a} has model function calls but NO thoughtSignature! This will likely cause a 400 error from Gemini 3 API.`),i}function xn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||En(e,r))return bt(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)===Oe||((n=r.functionResponse)==null?void 0:n.name)===Oe)return!0;return!1}function Po(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)===ge||((n=r.functionResponse)==null?void 0:n.name)===ge)return!0;return!1}function En(o,e){return!!o&&e.author!==o&&e.author!=="user"}function wo(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=yn(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=yn(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return S({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function An(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=S(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 ko(o){if(o.length===0)return o;let e=o[o.length-1],t=$(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=w(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=w(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=c;let p=new Set(f.map(g=>g.id).filter(g=>!!g));if(!Array.from(n).every(g=>p.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(p).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=p;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=$(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(An(s)),a}function Lo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=$(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($(n).length>0)continue;let r=w(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(An(a))}}else t.push(n)}return t}function yn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Tt(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let p=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!p)throw new Error(`Artifact ${u} not found.`);return String(p)}if(!No(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var _o=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function bn(o){return o===""||o===void 0?!1:_o.test(o)}var Mo=[E.APP_PREFIX,E.USER_PREFIX,E.TEMP_PREFIX];function No(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?bn(o):Mo.includes(e[0]+":")?bn(e[1]):!1}var Ue=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ue||{});function Tn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Oo(o.maxLlmCalls||500),...o}}function Oo(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&d.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 Sn="adk_agent_name";async function Rn(o,e){return o instanceof B?[o]:await o.getTools(e)}var Rt=class extends X{async*runAsync(e,t){var r;let n=e.agent;n instanceof A&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&pn(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))}},Bo=new Rt,It=class extends X{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),be(t,r)}},Fo=new It,Pt=class extends X{async*runAsync(e,t){let n=e.agent;if(!(n instanceof A)||!(n.rootAgent instanceof A))return;let r=n.rootAgent;if(r instanceof A&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new G(e)),a=i;s&&(a=await Tt(i,new G(e))),be(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new G(e)),a=i;s&&(a=await Tt(i,new G(e))),be(t,[a])}}},$o=new Pt,wt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof A)||(n.includeContents==="default"?t.contents=bt(e.session.events,n.name,e.branch):t.contents=xn(e.session.events,n.name,e.branch))}},Go=new wt,kt=class extends X{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new z({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:St.z.object({agentName:St.z.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof A))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;be(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new Y({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
17
|
+
`+t:o.config.systemInstruction=t}function mn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var z=require("@google/genai");function gn(){return To("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function To(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Ue=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"}):d.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);d.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else d.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){d.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function xt(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 So="https://aiplatform.googleapis.com/v1/publishers/google",de=class extends fe{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=cn(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=So,d.info(`Using Gemini 3 preview endpoint: ${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?(d.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):d.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.")}async*generateContentAsync(e,t=!1){var n,r,i,s,a,c,l,f,u,p,v,g,m,C,E,A;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),d.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let S=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),h="",y,_="",st,L;this.isGemini3Preview&&this.cachedThoughtSignature&&d.info(`[Gemini3] Starting new request with CACHED thoughtSignature (length: ${this.cachedThoughtSignature.length})`);for await(let I of S){L=I;let x=xt(I);st=x.usageMetadata;let U=(s=(i=x.content)==null?void 0:i.parts)==null?void 0:s[0],at=(c=(a=x.content)==null?void 0:a.parts)==null?void 0:c.some(N=>N.functionCall);if(this.isGemini3Preview&&((l=x.content)!=null&&l.parts)){for(let N of x.content.parts)if(N.thoughtSignature&&!y){y=N.thoughtSignature,this.cachedThoughtSignature=y,d.info(`[Gemini3] Captured and CACHED thoughtSignature from response part (length: ${y.length})`);break}}if(U!=null&&U.text){if("thought"in U&&U.thought?(h+=U.text,"thoughtSignature"in U&&U.thoughtSignature&&(y=U.thoughtSignature,this.cachedThoughtSignature=y,d.info(`[Gemini3] Captured and CACHED thoughtSignature from thought part (length: ${y.length})`))):_+=U.text,x.partial=!0,this.isGemini3Preview&&at){let N=(u=(f=x.content)==null?void 0:f.parts)==null?void 0:u.some(k=>k.thoughtSignature);d.info(`[Gemini3] Chunk has thought AND function calls. Response has signature: ${N}`),h="",y=void 0,_=""}}else if((h||_)&&(!U||!U.inlineData))if(this.isGemini3Preview&&at&&x.content){d.info(`[Gemini3] Merging thought with function calls. Has accumulated signature: ${!!y}`);let N=[];if(h){let k={text:h,thought:!0};y&&(k.thoughtSignature=y),N.push(k),d.info(`[Gemini3] Created thought part with signature: ${!!y}`)}if(_&&N.push((0,z.createPartFromText)(_)),!h&&y){let k=!1;for(let $ of x.content.parts||[])$.functionCall&&!k&&($.thoughtSignature||($.thoughtSignature=y,d.info(`[Gemini3] Applied accumulated signature to first function call: ${$.functionCall.name}`)),k=!0)}x.content.parts=[...N,...x.content.parts||[]],d.info(`[Gemini3] Final merged content has ${x.content.parts.length} parts`);for(let k=0;k<x.content.parts.length;k++){let $=x.content.parts[k];d.info(`[Gemini3] Part ${k}: thought=${!!$.thought}, functionCall=${((p=$.functionCall)==null?void 0:p.name)||"none"}, hasSignature=${!!$.thoughtSignature}`)}h="",y=void 0,_=""}else{let N=[];if(h){let k={text:h,thought:!0};y&&(k.thoughtSignature=y),N.push(k)}_&&N.push((0,z.createPartFromText)(_)),yield{content:{role:"model",parts:N},usageMetadata:x.usageMetadata},h="",y=void 0,_=""}if(this.isGemini3Preview&&at&&((v=x.content)!=null&&v.parts)){if(!x.content.parts.some(B=>B.thoughtSignature)&&y){for(let B of x.content.parts)if(B.functionCall){B.thoughtSignature=y,d.info(`[Gemini3] Applied cached signature to first function call: ${B.functionCall.name}`);break}}let k=x.content.parts.filter(B=>B.functionCall).map(B=>B.functionCall.name),$=x.content.parts.filter(B=>B.thoughtSignature).length;if($===0){let B=y||this.cachedThoughtSignature;if(B){for(let _e of x.content.parts)if(_e.functionCall&&!_e.thoughtSignature){_e.thoughtSignature=B,d.info(`[Gemini3] Applied CACHED signature to function call: ${_e.functionCall.name} (API didn't return new signature, using ${y?"local":"class-level"} cache)`),$=1;break}}}d.info(`[Gemini3] Yielding function call response: calls=[${k.join(", ")}], partsWithSignature=${$}`),$===0&&d.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}yield x}if((_||h)&&((m=(g=L==null?void 0:L.candidates)==null?void 0:g[0])==null?void 0:m.finishReason)===z.FinishReason.STOP){let I=[];if(h){let x={text:h,thought:!0};y&&(x.thoughtSignature=y),I.push(x)}_&&I.push({text:_}),yield{content:{role:"model",parts:I},usageMetadata:st}}}else{let S=await this.apiClient.models.generateContent({model:(C=e.model)!=null?C:this.model,contents:e.contents,config:e.config}),h=xt(S);if(this.isGemini3Preview&&((E=h.content)!=null&&E.parts)){let y,_=!1;for(let L of h.content.parts)if(L.thoughtSignature){y=L.thoughtSignature,this.cachedThoughtSignature=y,L.thought&&(_=!0);break}if(d.info(`[Gemini3] Non-streaming response: hasSignature=${!!y}, hasThoughtPart=${_}, hasCachedSig=${!!this.cachedThoughtSignature}`),y&&!_){let L=!1;for(let I of h.content.parts)I.functionCall&&(!L&&!I.thoughtSignature&&(I.thoughtSignature=y,d.info(`[Gemini3] Applied signature to first function call: ${I.functionCall.name}`)),L=!0)}if(h.content.parts.some(L=>L.functionCall)){let L=h.content.parts.filter(I=>I.thoughtSignature).length;if(L===0&&this.cachedThoughtSignature){for(let I of h.content.parts)if(I.functionCall&&!I.thoughtSignature){I.thoughtSignature=this.cachedThoughtSignature,d.info(`[Gemini3] Applied CACHED signature to function call: ${I.functionCall.name} (API didn't return new signature)`),L=1;break}}for(let I=0;I<h.content.parts.length;I++){let x=h.content.parts[I];d.info(`[Gemini3] Response Part ${I}: thought=${!!x.thought}, functionCall=${((A=x.functionCall)==null?void 0:A.name)||"none"}, hasSignature=${!!x.thoughtSignature}`)}L===0&&d.warn("[Gemini3] WARNING: No thoughtSignature found and no cached signature available! This may cause 400 errors on next request.")}}yield h}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new z.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,d.debug(`Using custom API endpoint: ${this.apiEndpoint}`),this.isGemini3Preview&&(t.apiVersion="",d.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new z.GoogleGenAI({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 z.GoogleGenAI({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:[(0,z.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new Ue(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)hn(n.inlineData),hn(n.fileData)}}};de.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function hn(o){o&&o.displayName&&(o.displayName=void 0)}var Tt=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)}},V=class V{static newLlm(e){return new(V.resolve(e))({model:e})}static _register(e,t){V.llmRegistryDict.has(e)&&d.info(`Updating LLM class for ${e} from ${V.llmRegistryDict.get(e)} to ${t}`),V.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)V._register(t,e)}static resolve(e){let t=V.resolveCache.get(e);if(t)return t;for(let[n,r]of V.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return V.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};V.llmRegistryDict=new Map,V.resolveCache=new Tt(32);var pe=V;pe.register(de);var F=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=Ro(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 gn()}};function Ro(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var vn=require("@google/genai"),yn=require("zod");var M=require("@google/genai"),P=require("zod");function Cn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function Q(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 P.z.ZodFirstPartyTypeKind.ZodString:n.type=M.Type.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case P.z.ZodFirstPartyTypeKind.ZodNumber:n.type=M.Type.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=M.Type.INTEGER);return r(n);case P.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=M.Type.BOOLEAN,r(n);case P.z.ZodFirstPartyTypeKind.ZodArray:return n.type=M.Type.ARRAY,n.items=Q(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case P.z.ZodFirstPartyTypeKind.ZodObject:return Se(o);case P.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=M.Type.STRING;else if(i==="number")n.type=M.Type.NUMBER;else if(i==="boolean")n.type=M.Type.BOOLEAN;else if(e.value===null)n.type=M.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case P.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=M.Type.STRING,n.enum=e.values,r(n);case P.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=M.Type.STRING,n.enum=Object.values(e.values),r(n);case P.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(Q),r(n);case P.z.ZodFirstPartyTypeKind.ZodOptional:return Q(e.innerType);case P.z.ZodFirstPartyTypeKind.ZodNullable:let s=Q(e.innerType);return r(s?{anyOf:[s,{type:M.Type.NULL}],...t&&{description:t}}:{type:M.Type.NULL,...t&&{description:t}});case P.z.ZodFirstPartyTypeKind.ZodDefault:let a=Q(e.innerType);return a&&(a.default=e.defaultValue()),a;case P.z.ZodFirstPartyTypeKind.ZodBranded:return Q(e.type);case P.z.ZodFirstPartyTypeKind.ZodReadonly:return Q(e.innerType);case P.z.ZodFirstPartyTypeKind.ZodNull:return n.type=M.Type.NULL,r(n);case P.z.ZodFirstPartyTypeKind.ZodAny:case P.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Se(o){if(o._def.typeName!==P.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=Q(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===P.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===P.z.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==P.z.ZodFirstPartyTypeKind.ZodNever?i=Q(r)||!0:i=o._def.unknownKeys==="passthrough",{type:M.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Io(o){return o===void 0?{type:vn.Type.OBJECT,properties:{}}:Cn(o)?Se(o):o}var Y=class extends F{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 yn.ZodObject&&(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 '${this.name}': ${n}`)}}};var J=class{};function bt(o,e,t){var c,l,f,u,p,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)||Po(g)||wo(g)||n.push(xn(e,g)?Lo(g):g);let r=ko(n);r=_o(r);let i=[];for(let g of r){let m=K(g.content);Jt(m),i.push(m)}let s=!1,a=-1;for(let g=0;g<i.length;g++){let m=i[g],C=(f=m.parts)==null?void 0:f.some(S=>S.functionCall),E=(u=m.parts)==null?void 0:u.some(S=>S.thoughtSignature),A=(p=m.parts)==null?void 0:p.some(S=>S.thought);if(C){d.info(`[getContents] Content block ${g+1}/${i.length}: role=${m.role}, hasFunctionCalls=true, hasThought=${A}, hasSignature=${E}`),!E&&m.role==="model"&&(s=!0,a=g+1);for(let S=0;S<(((v=m.parts)==null?void 0:v.length)||0);S++){let h=m.parts[S];h.functionCall?d.info(`[getContents] Part ${S}: functionCall=${h.functionCall.name}, hasSignature=${!!h.thoughtSignature}`):h.thought&&d.info(`[getContents] Part ${S}: thought=true, hasSignature=${!!h.thoughtSignature}`)}}}return s&&d.warn(`[getContents] WARNING: Content block ${a} has model function calls but NO thoughtSignature! This will likely cause a 400 error from Gemini 3 API.`),i}function An(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||xn(e,r))return bt(o.slice(n),e,t)}return[]}function Po(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)===Be||((n=r.functionResponse)==null?void 0:n.name)===Be)return!0;return!1}function wo(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)===he||((n=r.functionResponse)==null?void 0:n.name)===he)return!0;return!1}function xn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function Lo(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=En(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=En(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return R({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function Tn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=R(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 ko(o){if(o.length===0)return o;let e=o[o.length-1],t=G(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=w(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=w(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=c;let p=new Set(f.map(g=>g.id).filter(g=>!!g));if(!Array.from(n).every(g=>p.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(p).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=p;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=G(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(Tn(s)),a}function _o(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=G(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(G(n).length>0)continue;let r=w(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(Tn(a))}}else t.push(n)}return t}function En(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function St(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let p=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!p)throw new Error(`Artifact ${u} not found.`);return String(p)}if(!Oo(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var Mo=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function bn(o){return o===""||o===void 0?!1:Mo.test(o)}var No=[T.APP_PREFIX,T.USER_PREFIX,T.TEMP_PREFIX];function Oo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?bn(o):No.includes(e[0]+":")?bn(e[1]):!1}var je=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(je||{});function Sn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Bo(o.maxLlmCalls||500),...o}}function Bo(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&d.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 Rn="adk_agent_name";async function In(o,e){return o instanceof F?[o]:await o.getTools(e)}var It=class extends J{async*runAsync(e,t){var r;let n=e.agent;n instanceof b&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&mn(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))}},Fo=new It,Pt=class extends J{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),be(t,r)}},$o=new Pt,wt=class extends J{async*runAsync(e,t){let n=e.agent;if(!(n instanceof b)||!(n.rootAgent instanceof b))return;let r=n.rootAgent;if(r instanceof b&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new D(e)),a=i;s&&(a=await St(i,new D(e))),be(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new D(e)),a=i;s&&(a=await St(i,new D(e))),be(t,[a])}}},Go=new wt,Lt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof b)||(n.includeContents==="default"?t.contents=bt(e.session.events,n.name,e.branch):t.contents=An(e.session.events,n.name,e.branch))}},Do=new Lt,kt=class extends J{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new Y({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:Rt.z.object({agentName:Rt.z.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof b))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;be(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new X({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
18
18
|
Agent name: ${t.name}
|
|
19
19
|
Agent description: ${t.description}
|
|
20
20
|
`}buildTargetAgentsInstructions(t,n){let r=`
|
|
@@ -34,7 +34,7 @@ the function call.
|
|
|
34
34
|
Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
|
|
35
35
|
you are best for answering the question according to the descriptions, transfer
|
|
36
36
|
to your parent agent.
|
|
37
|
-
`),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof
|
|
37
|
+
`),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof b)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},qo=new kt,_t=class extends J{async*runAsync(e,t){let n=e.agent;if(!(n instanceof b))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=G(c);if(!l)continue;let f=!1;for(let u of l){if(u.name!==he)continue;f=!0;let p=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?p=JSON.parse(u.response.response):u.response&&(p=new ee({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&p&&(i[u.id]=p)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=w(c);if(!l)continue;let f={},u={};for(let m of l){if(!m.id||!(m.id in i))continue;let C=m.args;if(!C||!("originalFunctionCall"in C))continue;let E=C.originalFunctionCall;E.id&&(f[E.id]=i[m.id],u[E.id]=E)}if(Object.keys(f).length===0)continue;for(let m=r.length-1;m>s;m--){let C=r[m],E=G(C);if(E){for(let A of E)A.id&&A.id in f&&(delete f[A.id],delete u[A.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let p=await n.canonicalTools(new D(e)),v=Object.fromEntries(p.map(m=>[m.name,m])),g=await Fe({invocationContext:e,functionCalls:Object.values(u),toolsDict:v,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f});g&&(yield g);return}}},Uo=new _t,Mt=class extends J{async*runAsync(e,t){if(e.agent instanceof b&&e.agent.codeExecutor){for await(let n of Ko(e,t))yield n;if(e.agent.codeExecutor instanceof te)for(let n of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],i=fn(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},Ke={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},jo=`
|
|
38
38
|
import pandas as pd
|
|
39
39
|
|
|
40
40
|
def explore_df(df: pd.DataFrame) -> None:
|
|
@@ -71,20 +71,20 @@ def explore_df(df: pd.DataFrame) -> None:
|
|
|
71
71
|
Total columns: {df.shape[1]}
|
|
72
72
|
|
|
73
73
|
{df_info}""")
|
|
74
|
-
`,
|
|
74
|
+
`,Nt=class{async*runAsync(e,t){if(!t.partial)for await(let n of Vo(e,t))yield n}},Ds=new Nt;async function*Ko(o,e){let t=o.agent;if(!(t instanceof b))return;let n=t.codeExecutor;if(!n||!(n instanceof te))return;if(n instanceof ae){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new Te(new T(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=Zo(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=Wo(c);if(!l)return;let f={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},Ct(l)]};e.contents.push(K(f)),yield R({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let u=Pn(o,r),p=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:u}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:p.stdout,resultStderr:p.stderr}),r.addProcessedFileNames([c.name]);let v=await wn(o,r,p);yield v,e.contents.push(K(v.content))}}async function*Vo(o,e){let t=o.agent;if(!(t instanceof b))return;let n=t.codeExecutor;if(!n||!(n instanceof te)||!e||!e.content||n instanceof ae)return;let r=new Te(new T(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=ln(i,n.codeBlockDelimiters);if(!s)return;yield R({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=Pn(o,r),c=await n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await wn(o,r,c),e.content=null}function Zo(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||!Ke[l])continue;let f=`data_${i+1}_${a+1}${Ke[l].extension}`;c.text=`
|
|
75
75
|
Available file: \`${f}\`
|
|
76
|
-
`;let u={name:f,content:
|
|
77
|
-
${
|
|
76
|
+
`;let u={name:f,content:Zt(c.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([u]),t.push(u))}}return t}function Pn(o,e){var r;let t=o.agent;if(!(t instanceof b)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function wn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[un(t)]},r=Z({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 R({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Wo(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Ke[o.mimeType])return;let t=e(o.name),n=Ke[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return`
|
|
77
|
+
${jo}
|
|
78
78
|
|
|
79
79
|
# Load the dataframe.
|
|
80
80
|
${t} = ${n}
|
|
81
81
|
|
|
82
82
|
# Use \`explore_df\` to guide my analysis.
|
|
83
83
|
explore_df(${t})
|
|
84
|
-
`}var Wo=new _t,A=class o extends U{constructor(e){var n,r,i,s,a,c,l,f,u;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:[Bo,Fo,$o,qo,Go,Wo],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(Do),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)&&(d.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(De(this.model))return this.model;if(typeof this.model=="string"&&this.model)return de.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 ${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 Rn(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){d.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){d.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!ie(e)){d.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){d.debug(`Skipping output save for agent ${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){d.error(`Error parsing output for agent ${this.name}`,s)}}e.actions.stateDelta[this.outputKey]=n}async*runAsyncImpl(e){for(;;){let t;for await(let n of this.runOneStepAsync(e))t=n,this.maybeSaveOutputToState(n),yield n;if(!t||ie(t))break;if(t.partial){d.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(e){for await(let t of this.runLiveFlow(e))this.maybeSaveOutputToState(t),yield t;e.endInvocation}async*runLiveFlow(e){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(e){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let r of this.requestProcessors)for await(let i of r.runAsync(e,t))yield i;for(let r of this.tools){let i=new Y({invocationContext:e}),s=await Rn(r,new G(e));for(let a of s)await a.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=S({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=lt(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var f,u,p,y,g;for(let m of this.responseProcessors)for await(let C of m.runAsync(e,n))yield C;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=S({...r,...n});if(i.content){let m=w(i);if(m!=null&&m.length){Qt(i),i.longRunningToolIds=Array.from(Jt(m,t.toolsDict));let C=(f=i.content.parts)==null?void 0:f.some(b=>b.thought),P=(u=i.content.parts)==null?void 0:u.some(b=>b.thoughtSignature);d.info(`[postprocess] Function call event: ${m.length} calls, hasThought=${C}, hasSignature=${P}`);for(let b=0;b<(((p=i.content.parts)==null?void 0:p.length)||0);b++){let T=i.content.parts[b];(T.functionCall||T.thought)&&d.info(`[postprocess] Part ${b}: thought=${!!T.thought}, functionCall=${((y=T.functionCall)==null?void 0:y.name)||"none"}, hasSignature=${!!T.thoughtSignature}`)}P||d.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,!((g=w(i))!=null&&g.length))return;let s=await nn({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let a=en(e,s);a&&(yield a);let c=tn({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let m=this.getAgentByName(e,l);for await(let C of m.runAsync(e))yield C}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,a,c,l,f;let r=await 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[Sn]||(t.config.labels[Sn]=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 u=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let p of this.runAndHandleError(u,e,t,n)){let y=await this.handleAfterModelCallback(e,p,n);yield y!=null?y:p}}}async handleBeforeModelCallback(e,t,n){let r=new D({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 D({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}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new D({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let a=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(a)yield a;else{let c=JSON.parse(i.message);yield{errorCode:String(c.error.code),errorMessage:c.error.message}}}else throw d.error("Unknown error during response generation",i),i}}};var Ke=class extends U{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(e){let t=0;for(;t<this.maxIterations;){for(let n of this.subAgents){let r=!1;for await(let i of n.runAsync(e))yield i,i.actions.escalate&&(r=!0);if(r)return}t++}}async*runLiveImpl(e){throw new Error("This is not supported yet for LoopAgent.")}};var Ve=class extends U{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(zo(this,n,e)));for await(let n of Ho(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function zo(o,e,t){let n=new Z(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Ho(o){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=await Promise.race(e.values());if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}}var Nt="task_completed",Ze=class extends U{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof A&&((await t.canonicalTools(new G(e))).some(i=>i.name===Nt)||(t.tools.push(new z({name:Nt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),t.instruction+=`If you finished the user's request according to its description, call the ${Nt} 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 t of this.subAgents)for await(let n of t.runLive(e))yield n}};var he=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=We(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=We(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=We(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=We(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 We(o,e,t,n){return Yo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Yo(o){return o.startsWith("user:")}var te=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=wn(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=wn(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(p=>p.text).filter(p=>!!p).join(" "),f=Qo(l);if(!f.size)continue;n.some(p=>f.has(p))&&r.memories.push({content:c.content,author:c.author,timestamp:Xo(c.timestamp)})}return r}};function wn(o,e){return`${o}/${e}`}function Qo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Xo(o){return new Date(o).toISOString()}var ne=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 ze=class extends ne{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${ie(t)}`);let n=w(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=$(t);if(r.length>0){let i=r.map(s=>s.name);this.log(` Function Responses: ${i}`)}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...t.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`),t.invocationContext.branch&&this.log(` Branch: ${t.invocationContext.branch}`)}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(n=t.model)!=null?n:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Result: ${this.formatArgs(r)}`)}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${n}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;d.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let n=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),n.push(`text: '${i}'`)}else r.functionCall?n.push(`function_call: ${r.functionCall.name}`):r.functionResponse?n.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var Ce=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),d.info(`Plugin '${e.name}' registered.`)}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return d.debug(`Plugin '${r.name}' returned a value for callback '${n}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${n}' callback: ${i}`;throw d.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 Bt="adk_request_confirmation",Ot="orcas_tool_call_security_check_states",kn="This tool call needs external confirmation before completion.",Ft=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Ft||{}),Se=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},He=class extends ne{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Se}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:kn};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(Ot))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Ot))!=null?i:{};r[n]=t,e.state.set(Ot,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:kn};case"ALLOW":return;default:return}}};function Ln(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Bt&&e.push(t.functionCall);return e}var Re=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(E.TEMP_PREFIX)||(e.state[n]=r)}};function Ie(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var oe=class extends Re{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Ie({id:i||pe(),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,j(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=j(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(Ie({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=>{d.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(E.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(E.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(E.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(E.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[E.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[E.USER_PREFIX+i]=this.userState[t][n][i];return r}};var _n=require("@google/genai"),Mn=require("@opentelemetry/api");var re=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new Ce((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var a;i=Tn(i);let s=Mn.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let c=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!c)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof A){let p=this.agent.canonicalModel.model;if(!p.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${p} in agent: ${this.agent.name}`)}let l=new Z({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Zt(),agent:this.agent,session:c,userContent:n,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(f&&(n=f),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,c.userId,c.id,n),await this.sessionService.appendEvent({session:c,event:S({invocationId:l.invocationId,author:"user",actions:r?V({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(c,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(u){let p=S({invocationId:l.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:c,event:p}),yield p}else for await(let p of l.agent.runAsync(l)){p.partial||await this.sessionService.appendEvent({session:c,event:p});let y=await this.pluginManager.runOnEventCallback({invocationContext:l,event:p});y?yield y:yield p}await this.pluginManager.runAfterRunCallback({invocationContext:l})}finally{s.end()}}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=(0,_n.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Jo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){d.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){d.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof A)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Jo(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=w(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var Ye=class extends re{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new he,sessionService:new oe,memoryService:new te})}};var Pe=require("@google/genai");var Qe=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 Xe=class extends B{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 A&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Pe.Type.OBJECT,properties:{request:{type:Pe.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof A&&this.agent.outputSchema;e.response=t?{type:Pe.Type.OBJECT}:{type:Pe.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var f,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof A&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new re({appName:this.agent.name,agent:this.agent,artifactService:new Qe(t),sessionService:new oe,memoryService:new te,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;for await(let p of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))p.actions.stateDelta&&t.state.update(p.actions.stateDelta),a=p;if(!((u=(f=a==null?void 0:a.content)==null?void 0:f.parts)!=null&&u.length))return"";let c=this.agent instanceof A&&this.agent.outputSchema,l=a.content.parts.map(p=>p.text).filter(p=>p).join(`
|
|
85
|
-
`);return c?JSON.parse(l):l}};var
|
|
84
|
+
`}var zo=new Mt,O=class O extends j{constructor(e){var n,r,i,s,a,c,l,f,u;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:[Fo,$o,Go,Uo,Do,zo],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(qo),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)&&(d.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(qe(this.model))return this.model;if(typeof this.model=="string"&&this.model)return pe.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 ${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 In(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){d.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){d.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!se(e)){d.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){d.debug(`Skipping output save for agent ${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){d.error(`Error parsing output for agent ${this.name}`,s)}}e.actions.stateDelta[this.outputKey]=n}async*runAsyncImpl(e){for(;;){let t;for await(let n of this.runOneStepAsync(e))t=n,this.maybeSaveOutputToState(n),yield n;if(!t||se(t))break;if(t.partial){d.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(e){for await(let t of this.runLiveFlow(e))this.maybeSaveOutputToState(t),yield t;e.endInvocation}async*runLiveFlow(e){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(e){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let r of this.requestProcessors)for await(let i of r.runAsync(e,t))yield i;for(let r of this.tools){let i=new X({invocationContext:e}),s=await In(r,new D(e));for(let a of s)await a.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=R({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=ut(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var f,u,p,v,g;for(let m of this.responseProcessors)for await(let C of m.runAsync(e,n))yield C;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=R({...r,...n});if(i.content){let m=w(i);if(m!=null&&m.length){Qt(i),i.longRunningToolIds=Array.from(en(m,t.toolsDict));let C=(f=i.content.parts)==null?void 0:f.some(A=>A.thought),E=(u=i.content.parts)==null?void 0:u.some(A=>A.thoughtSignature);d.info(`[postprocess] Function call event: ${m.length} calls, hasThought=${C}, hasSignature=${E}`);for(let A=0;A<(((p=i.content.parts)==null?void 0:p.length)||0);A++){let S=i.content.parts[A];(S.functionCall||S.thought)&&d.info(`[postprocess] Part ${A}: thought=${!!S.thought}, functionCall=${((v=S.functionCall)==null?void 0:v.name)||"none"}, hasSignature=${!!S.thoughtSignature}`)}E||d.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,!((g=w(i))!=null&&g.length))return;let s=await on({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let a=tn(e,s);a&&(yield a);let c=nn({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let m=this.getAgentByName(e,l);for await(let C of m.runAsync(e))yield C}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,a,c,l,f;let r=await 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[Rn]||(t.config.labels[Rn]=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 u=((f=e.runConfig)==null?void 0:f.streamingMode)==="sse",p=O.LLM_TRANSIENT_ERROR_MAX_RETRIES;for(let v=0;v<=p;v++){if(v>0){let E=Math.min(O.LLM_TRANSIENT_ERROR_BASE_DELAY_MS*Math.pow(2,v-1),O.LLM_TRANSIENT_ERROR_MAX_DELAY_MS);d.warn(`[callLlmAsync] Retrying LLM call after transient error (attempt ${v+1}/${p+1}), waiting ${E}ms`),await new Promise(A=>setTimeout(A,E))}let g=i.generateContentAsync(t,u),m=!1,C=!1;for await(let E of this.runAndHandleError(g,e,t,n)){if(E.content&&(C=!0),E.errorCode&&O.LLM_RETRYABLE_ERROR_CODES.has(E.errorCode)&&!C&&v<p){m=!0,d.warn(`[callLlmAsync] Transient LLM error: ${E.errorCode}, usage: ${JSON.stringify(E.usageMetadata)}`);break}let A=await this.handleAfterModelCallback(e,E,n);yield A!=null?A:E}if(!m)return}}}async handleBeforeModelCallback(e,t,n){let r=new q({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 q({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}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new q({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let a=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(a)yield a;else{let c=JSON.parse(i.message);yield{errorCode:String(c.error.code),errorMessage:c.error.message}}}else throw d.error("Unknown error during response generation",i),i}}};O.LLM_TRANSIENT_ERROR_MAX_RETRIES=2,O.LLM_TRANSIENT_ERROR_BASE_DELAY_MS=1e3,O.LLM_TRANSIENT_ERROR_MAX_DELAY_MS=4e3,O.LLM_RETRYABLE_ERROR_CODES=new Set(["UNKNOWN_ERROR"]);var b=O;var Ve=class extends j{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(e){let t=0;for(;t<this.maxIterations;){for(let n of this.subAgents){let r=!1;for await(let i of n.runAsync(e))yield i,i.actions.escalate&&(r=!0);if(r)return}t++}}async*runLiveImpl(e){throw new Error("This is not supported yet for LoopAgent.")}};var Ze=class extends j{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(Yo(this,n,e)));for await(let n of Ho(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function Yo(o,e,t){let n=new W(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Ho(o){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=await Promise.race(e.values());if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}}var Ot="task_completed",We=class extends j{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof b&&((await t.canonicalTools(new D(e))).some(i=>i.name===Ot)||(t.tools.push(new Y({name:Ot,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),t.instruction+=`If you finished the user's request according to its description, call the ${Ot} 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 t of this.subAgents)for await(let n of t.runLive(e))yield n}};var Ce=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=ze(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=ze(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=ze(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=ze(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 ze(o,e,t,n){return Xo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Xo(o){return o.startsWith("user:")}var ne=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Ln(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=Ln(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(p=>p.text).filter(p=>!!p).join(" "),f=Qo(l);if(!f.size)continue;n.some(p=>f.has(p))&&r.memories.push({content:c.content,author:c.author,timestamp:Jo(c.timestamp)})}return r}};function Ln(o,e){return`${o}/${e}`}function Qo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Jo(o){return new Date(o).toISOString()}var oe=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 Ye=class extends oe{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${se(t)}`);let n=w(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=G(t);if(r.length>0){let i=r.map(s=>s.name);this.log(` Function Responses: ${i}`)}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...t.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`),t.invocationContext.branch&&this.log(` Branch: ${t.invocationContext.branch}`)}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(n=t.model)!=null?n:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Result: ${this.formatArgs(r)}`)}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${n}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;d.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let n=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),n.push(`text: '${i}'`)}else r.functionCall?n.push(`function_call: ${r.functionCall.name}`):r.functionResponse?n.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var ve=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),d.info(`Plugin '${e.name}' registered.`)}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return d.debug(`Plugin '${r.name}' returned a value for callback '${n}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${n}' callback: ${i}`;throw d.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 Ft="adk_request_confirmation",Bt="orcas_tool_call_security_check_states",kn="This tool call needs external confirmation before completion.",$t=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))($t||{}),Re=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},He=class extends oe{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Re}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:kn};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(Bt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Bt))!=null?i:{};r[n]=t,e.state.set(Bt,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:kn};case"ALLOW":return;default:return}}};function _n(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Ft&&e.push(t.functionCall);return e}var Ie=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(T.TEMP_PREFIX)||(e.state[n]=r)}};function Pe(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var re=class extends Ie{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Pe({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,K(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=K(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(Pe({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=>{d.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(T.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(T.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(T.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(T.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[T.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[T.USER_PREFIX+i]=this.userState[t][n][i];return r}};var Mn=require("@google/genai"),Nn=require("@opentelemetry/api");var ie=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ve((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var a;i=Sn(i);let s=Nn.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let c=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!c)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof b){let p=this.agent.canonicalModel.model;if(!p.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${p} in agent: ${this.agent.name}`)}let l=new W({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Wt(),agent:this.agent,session:c,userContent:n,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(f&&(n=f),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,c.userId,c.id,n),await this.sessionService.appendEvent({session:c,event:R({invocationId:l.invocationId,author:"user",actions:r?Z({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(c,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(u){let p=R({invocationId:l.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:c,event:p}),yield p}else for await(let p of l.agent.runAsync(l)){p.partial||await this.sessionService.appendEvent({session:c,event:p});let v=await this.pluginManager.runOnEventCallback({invocationContext:l,event:p});v?yield v:yield p}await this.pluginManager.runAfterRunCallback({invocationContext:l})}finally{s.end()}}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=(0,Mn.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=er(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){d.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){d.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof b)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function er(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=w(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var Xe=class extends ie{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new Ce,sessionService:new re,memoryService:new ne})}};var we=require("@google/genai");var Qe=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 Je=class extends F{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 b&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:we.Type.OBJECT,properties:{request:{type:we.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof b&&this.agent.outputSchema;e.response=t?{type:we.Type.OBJECT}:{type:we.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var f,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof b&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new ie({appName:this.agent.name,agent:this.agent,artifactService:new Qe(t),sessionService:new re,memoryService:new ne,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;for await(let p of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))p.actions.stateDelta&&t.state.update(p.actions.stateDelta),a=p;if(!((u=(f=a==null?void 0:a.content)==null?void 0:f.parts)!=null&&u.length))return"";let c=this.agent instanceof b&&this.agent.outputSchema,l=a.content.parts.map(p=>p.text).filter(p=>p).join(`
|
|
85
|
+
`);return c?JSON.parse(l):l}};var ye=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 Gt=class extends F{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||[],sn(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(rn(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},On=new Gt;var Bn=`
|
|
86
86
|
|
|
87
|
-
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,
|
|
87
|
+
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,et=class extends Y{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Bn:e.description=Bn.trimStart(),e}};var Fn=require("@modelcontextprotocol/sdk/client/index.js"),$n=require("@modelcontextprotocol/sdk/client/stdio.js"),Gn=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Le=class{constructor(e){this.connectionParams=e}async createSession(){let e=new Fn.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new $n.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new Gn.StreamableHTTPClientTransport(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};var H=require("@google/genai"),Ee=require("zod");var il=Ee.z.object({type:Ee.z.literal("object"),properties:Ee.z.record(Ee.z.unknown()).optional(),required:Ee.z.string().array().optional()});function tr(o){switch(o.toLowerCase()){case"text":case"string":return H.Type.STRING;case"number":return H.Type.NUMBER;case"boolean":return H.Type.BOOLEAN;case"integer":return H.Type.INTEGER;case"array":return H.Type.ARRAY;case"object":return H.Type.OBJECT;default:return H.Type.TYPE_UNSPECIFIED}}function Dt(o){if(!o)return;function e(t){let n=tr(t.type),r={type:n,description:t.description};if(n===H.Type.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else n===H.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var ke=class extends F{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){let e;return e={name:this.mcpTool.name,description:this.mcpTool.description,parameters:Dt(this.mcpTool.inputSchema),response:Dt(this.mcpTool.outputSchema)},e}async runAsync(e){let t=await this.mcpSessionManager.createSession(),n={};return n.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(n.params)}};var qt=class extends ye{constructor(e,t=[]){super(t),this.mcpSessionManager=new Le(e)}async getTools(e){let n=await(await this.mcpSessionManager.createSession()).listTools();d.debug(`number of tools: ${n.tools.length}`);for(let r of n.tools)d.debug(`tool: ${r.name}`);return n.tools.map(r=>new ke(r,this.mcpSessionManager))}async close(){}};var Dn=require("@google-cloud/storage"),nt=require("@google/genai");var Ut=class{constructor(e){this.bucket=new Dn.Storage().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),n=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(tt({...e,version:n}));if(e.artifact.inlineData)return await r.save(JSON.stringify(e.artifact.inlineData.data),{contentType:e.artifact.inlineData.mimeType}),n;if(e.artifact.text)return await r.save(e.artifact.text,{contentType:"text/plain"}),n;throw new Error("Artifact must have either inlineData or text.")}async loadArtifact(e){let t=e.version;if(t===void 0){let s=await this.listVersions(e);if(s.length===0)return;t=Math.max(...s)}let n=this.bucket.file(tt({...e,version:t})),[[r],[i]]=await Promise.all([n.getMetadata(),n.download()]);return r.contentType==="text/plain"?(0,nt.createPartFromText)(i.toString("utf-8")):(0,nt.createPartFromBase64)(i.toString("base64"),r.contentType)}async listArtifactKeys(e){let t=[],n=`${e.appName}/${e.userId}/${e.sessionId}/`,r=`${e.appName}/${e.userId}/user/`,[[i],[s]]=await Promise.all([this.bucket.getFiles({prefix:n}),this.bucket.getFiles({prefix:r})]);for(let a of i)t.push(a.name.split("/").pop());for(let a of s)t.push(a.name.split("/").pop());return t.sort((a,c)=>a.localeCompare(c))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(n=>this.bucket.file(tt({...e,version:n})).delete()))}async listVersions(e){let t=tt(e),[n]=await this.bucket.getFiles({prefix:t}),r=[];for(let i of n){let s=i.name.split("/").pop();r.push(parseInt(s,10))}return r}};function tt({appName:o,userId:e,sessionId:t,filename:n,version:r}){return n.startsWith("user:")?`${o}/${e}/user/${n}/${r}`:`${o}/${e}/${t}/${n}/${r}`}var ot=require("@opentelemetry/api"),qn=require("@opentelemetry/api-logs"),rt=require("@opentelemetry/sdk-logs"),it=require("@opentelemetry/sdk-metrics"),Un=require("@opentelemetry/resources"),jn=require("@opentelemetry/sdk-trace-base"),Kn=require("@opentelemetry/sdk-trace-node"),Vn=require("@opentelemetry/exporter-trace-otlp-http"),Zn=require("@opentelemetry/exporter-metrics-otlp-http"),Wn=require("@opentelemetry/exporter-logs-otlp-http");function nr(o=[],e){let t=e||or(),n=[...o,ir()],r=n.flatMap(a=>a.spanProcessors||[]),i=n.flatMap(a=>a.metricReaders||[]),s=n.flatMap(a=>a.logRecordProcessors||[]);if(r.length>0){let a=new Kn.NodeTracerProvider({resource:t,spanProcessors:r});a.register(),ot.trace.setGlobalTracerProvider(a)}if(i.length>0){let a=new it.MeterProvider({readers:i,resource:t});ot.metrics.setGlobalMeterProvider(a)}if(s.length>0){let a=new rt.LoggerProvider({resource:t,processors:s});qn.logs.setGlobalLoggerProvider(a)}}function or(){return(0,Un.detectResources)({detectors:[]})}function rr(){return{enableTracing:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),enableMetrics:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT),enableLogging:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)}}function ir(o=rr()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new jn.BatchSpanProcessor(new Vn.OTLPTraceExporter)]:[],metricReaders:t?[new it.PeriodicExportingMetricReader({exporter:new Zn.OTLPMetricExporter})]:[],logRecordProcessors:n?[new rt.BatchLogRecordProcessor(new Wn.OTLPLogExporter)]:[]}}var zn=require("google-auth-library"),Yn=require("@opentelemetry/sdk-metrics"),Hn=require("@opentelemetry/resources"),Xn=require("@opentelemetry/resource-detector-gcp"),Qn=require("@google-cloud/opentelemetry-cloud-trace-exporter"),Jn=require("@opentelemetry/sdk-trace-base"),eo=require("@google-cloud/opentelemetry-cloud-monitoring-exporter");var sr="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function ar(){try{return await new zn.GoogleAuth().getProjectId()||void 0}catch{return}}async function cr(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await ar();return n?{spanProcessors:e?[new Jn.BatchSpanProcessor(new Qn.TraceExporter({projectId:n}))]:[],metricReaders:t?[new Yn.PeriodicExportingMetricReader({exporter:new eo.MetricExporter({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(d.warn(sr),{})}function lr(){return(0,Hn.detectResources)({detectors:[Xn.gcpDetector]})}0&&(module.exports={AgentTool,BaseAgent,BaseLlm,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,CallbackContext,FunctionTool,GOOGLE_SEARCH,GcsArtifactService,Gemini,InMemoryArtifactService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LLMRegistry,LiveRequestQueue,LlmAgent,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,ParallelAgent,PluginManager,PolicyOutcome,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,Runner,SecurityPlugin,SequentialAgent,State,StreamingMode,ToolConfirmation,ToolContext,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,hasTrailingCodeExecutionResult,isBaseLlm,isFinalResponse,maybeSetOtelProviders,setLogLevel,stringifyContent,version,zodObjectToSchema});
|
|
88
88
|
/**
|
|
89
89
|
* @license
|
|
90
90
|
* Copyright 2025 Google LLC
|