@google/adk 0.2.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/base_agent.js +43 -21
- package/dist/cjs/agents/callback_context.js +4 -1
- package/dist/cjs/agents/content_processor_utils.js +15 -7
- package/dist/cjs/agents/functions.js +79 -29
- package/dist/cjs/agents/llm_agent.js +59 -33
- package/dist/cjs/agents/loop_agent.js +2 -1
- package/dist/cjs/agents/parallel_agent.js +3 -4
- package/dist/cjs/artifacts/gcs_artifact_service.js +28 -20
- package/dist/cjs/artifacts/in_memory_artifact_service.js +18 -4
- package/dist/cjs/auth/auth_handler.js +3 -1
- package/dist/cjs/code_executors/base_code_executor.js +3 -1
- package/dist/cjs/code_executors/built_in_code_executor.js +7 -3
- package/dist/cjs/code_executors/code_executor_context.js +5 -5
- package/dist/cjs/common.js +4 -0
- package/dist/cjs/events/event.js +1 -3
- package/dist/cjs/index.js +19 -19
- package/dist/cjs/index.js.map +4 -4
- package/dist/cjs/memory/in_memory_memory_service.js +3 -1
- package/dist/cjs/models/base_llm.js +8 -4
- package/dist/cjs/models/gemini_llm_connection.js +1 -0
- package/dist/cjs/models/google_llm.js +3 -3
- package/dist/cjs/plugins/base_plugin.js +12 -0
- package/dist/cjs/plugins/logging_plugin.js +50 -13
- package/dist/cjs/plugins/plugin_manager.js +56 -24
- package/dist/cjs/plugins/security_plugin.js +1 -1
- package/dist/cjs/runner/runner.js +110 -95
- package/dist/cjs/sessions/in_memory_session_service.js +38 -14
- package/dist/cjs/telemetry/google_cloud.js +7 -9
- package/dist/cjs/telemetry/setup.js +15 -7
- package/dist/cjs/telemetry/tracing.js +37 -15
- package/dist/cjs/tools/agent_tool.js +8 -4
- package/dist/cjs/tools/base_tool.js +4 -2
- package/dist/cjs/tools/forwarding_artifact_service.js +1 -1
- package/dist/cjs/tools/function_tool.js +1 -2
- package/dist/cjs/tools/google_search_tool.js +1 -2
- package/dist/cjs/tools/mcp/mcp_session_manager.js +16 -10
- package/dist/cjs/tools/mcp/mcp_tool.js +1 -3
- package/dist/cjs/tools/mcp/mcp_toolset.js +1 -1
- package/dist/cjs/utils/env_aware_utils.js +1 -1
- package/dist/cjs/utils/gemini_schema_util.js +9 -4
- package/dist/cjs/utils/logger.js +47 -3
- package/dist/cjs/utils/simple_zod_to_json.js +100 -141
- package/dist/cjs/utils/variant_utils.js +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/agents/base_agent.js +48 -22
- package/dist/esm/agents/callback_context.js +4 -1
- package/dist/esm/agents/content_processor_utils.js +25 -9
- package/dist/esm/agents/functions.js +83 -29
- package/dist/esm/agents/llm_agent.js +63 -33
- package/dist/esm/agents/loop_agent.js +2 -1
- package/dist/esm/agents/parallel_agent.js +3 -4
- package/dist/esm/artifacts/gcs_artifact_service.js +28 -20
- package/dist/esm/artifacts/in_memory_artifact_service.js +18 -4
- package/dist/esm/auth/auth_handler.js +3 -1
- package/dist/esm/code_executors/base_code_executor.js +3 -1
- package/dist/esm/code_executors/built_in_code_executor.js +7 -3
- package/dist/esm/code_executors/code_executor_context.js +5 -5
- package/dist/esm/common.js +3 -1
- package/dist/esm/events/event.js +1 -3
- package/dist/esm/index.js +19 -19
- package/dist/esm/index.js.map +4 -4
- package/dist/esm/memory/in_memory_memory_service.js +3 -1
- package/dist/esm/models/base_llm.js +8 -4
- package/dist/esm/models/gemini_llm_connection.js +1 -0
- package/dist/esm/models/google_llm.js +8 -4
- package/dist/esm/plugins/base_plugin.js +12 -0
- package/dist/esm/plugins/logging_plugin.js +55 -14
- package/dist/esm/plugins/plugin_manager.js +56 -24
- package/dist/esm/plugins/security_plugin.js +1 -1
- package/dist/esm/runner/runner.js +114 -96
- package/dist/esm/sessions/in_memory_session_service.js +41 -15
- package/dist/esm/telemetry/google_cloud.js +7 -9
- package/dist/esm/telemetry/setup.js +23 -9
- package/dist/esm/telemetry/tracing.js +37 -15
- package/dist/esm/tools/agent_tool.js +8 -4
- package/dist/esm/tools/base_tool.js +4 -2
- package/dist/esm/tools/forwarding_artifact_service.js +1 -1
- package/dist/esm/tools/function_tool.js +1 -2
- package/dist/esm/tools/google_search_tool.js +2 -5
- package/dist/esm/tools/long_running_tool.js +3 -1
- package/dist/esm/tools/mcp/mcp_session_manager.js +22 -12
- package/dist/esm/tools/mcp/mcp_tool.js +1 -3
- package/dist/esm/tools/mcp/mcp_toolset.js +1 -1
- package/dist/esm/utils/env_aware_utils.js +1 -1
- package/dist/esm/utils/gemini_schema_util.js +9 -4
- package/dist/esm/utils/logger.js +43 -2
- package/dist/esm/utils/simple_zod_to_json.js +102 -141
- package/dist/esm/utils/variant_utils.js +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/types/agents/base_agent.d.ts +2 -1
- package/dist/types/agents/callback_context.d.ts +1 -1
- package/dist/types/agents/llm_agent.d.ts +1 -1
- package/dist/types/agents/loop_agent.d.ts +1 -1
- package/dist/types/agents/parallel_agent.d.ts +1 -1
- package/dist/types/artifacts/in_memory_artifact_service.d.ts +3 -3
- package/dist/types/code_executors/built_in_code_executor.d.ts +1 -1
- package/dist/types/code_executors/code_executor_context.d.ts +2 -4
- package/dist/types/common.d.ts +2 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/models/base_llm_connection.d.ts +1 -1
- package/dist/types/models/llm_response.d.ts +1 -1
- package/dist/types/plugins/logging_plugin.d.ts +12 -12
- package/dist/types/plugins/plugin_manager.d.ts +12 -12
- package/dist/types/plugins/security_plugin.d.ts +1 -1
- package/dist/types/runner/runner.d.ts +1 -1
- package/dist/types/sessions/in_memory_session_service.d.ts +5 -5
- package/dist/types/telemetry/setup.d.ts +1 -1
- package/dist/types/telemetry/tracing.d.ts +7 -6
- package/dist/types/tools/agent_tool.d.ts +1 -1
- package/dist/types/tools/base_tool.d.ts +1 -1
- package/dist/types/tools/base_toolset.d.ts +2 -1
- package/dist/types/tools/forwarding_artifact_service.d.ts +2 -2
- package/dist/types/tools/function_tool.d.ts +4 -3
- package/dist/types/tools/google_search_tool.d.ts +3 -3
- package/dist/types/tools/mcp/mcp_session_manager.d.ts +10 -3
- package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -2
- package/dist/types/utils/gemini_schema_util.d.ts +4 -12
- package/dist/types/utils/logger.d.ts +11 -10
- package/dist/types/utils/simple_zod_to_json.d.ts +5 -4
- package/dist/types/version.d.ts +1 -1
- package/dist/web/agents/base_agent.js +94 -33
- package/dist/web/agents/callback_context.js +4 -1
- package/dist/web/agents/content_processor_utils.js +25 -9
- package/dist/web/agents/functions.js +83 -29
- package/dist/web/agents/llm_agent.js +117 -54
- package/dist/web/agents/loop_agent.js +2 -1
- package/dist/web/agents/parallel_agent.js +3 -4
- package/dist/web/artifacts/gcs_artifact_service.js +25 -17
- package/dist/web/artifacts/in_memory_artifact_service.js +18 -4
- package/dist/web/auth/auth_handler.js +3 -1
- package/dist/web/code_executors/base_code_executor.js +3 -1
- package/dist/web/code_executors/built_in_code_executor.js +7 -3
- package/dist/web/code_executors/code_executor_context.js +5 -5
- package/dist/web/common.js +3 -1
- package/dist/web/events/event.js +1 -3
- package/dist/web/index.js +1 -1
- package/dist/web/index.js.map +4 -4
- package/dist/web/memory/in_memory_memory_service.js +3 -1
- package/dist/web/models/base_llm.js +8 -4
- package/dist/web/models/gemini_llm_connection.js +1 -0
- package/dist/web/models/google_llm.js +8 -4
- package/dist/web/plugins/base_plugin.js +12 -0
- package/dist/web/plugins/logging_plugin.js +55 -14
- package/dist/web/plugins/plugin_manager.js +56 -24
- package/dist/web/plugins/security_plugin.js +1 -1
- package/dist/web/runner/runner.js +159 -108
- package/dist/web/sessions/in_memory_session_service.js +41 -15
- package/dist/web/telemetry/google_cloud.js +7 -9
- package/dist/web/telemetry/setup.js +23 -9
- package/dist/web/telemetry/tracing.js +37 -15
- package/dist/web/tools/agent_tool.js +8 -4
- package/dist/web/tools/base_tool.js +4 -2
- package/dist/web/tools/forwarding_artifact_service.js +1 -1
- package/dist/web/tools/function_tool.js +1 -2
- package/dist/web/tools/google_search_tool.js +2 -5
- package/dist/web/tools/long_running_tool.js +3 -1
- package/dist/web/tools/mcp/mcp_session_manager.js +22 -12
- package/dist/web/tools/mcp/mcp_tool.js +1 -3
- package/dist/web/tools/mcp/mcp_toolset.js +1 -1
- package/dist/web/utils/env_aware_utils.js +1 -1
- package/dist/web/utils/gemini_schema_util.js +9 -4
- package/dist/web/utils/logger.js +43 -2
- package/dist/web/utils/simple_zod_to_json.js +102 -155
- package/dist/web/utils/variant_utils.js +1 -1
- package/dist/web/version.js +1 -1
- package/package.json +4 -2
package/dist/cjs/index.js
CHANGED
|
@@ -4,23 +4,23 @@
|
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
"use strict";var et=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var Go=Object.getOwnPropertyNames;var $o=Object.prototype.hasOwnProperty;var qo=(o,e)=>{for(var t in e)et(o,t,{get:e[t],enumerable:!0})},Uo=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Go(e))!$o.call(o,r)&&r!==t&&et(o,r,{get:()=>e[r],enumerable:!(n=Do(e,r))||n.enumerable});return o};var jo=o=>Uo(et({},"__esModule",{value:!0}),o);var Vr={};qo(Vr,{ActiveStreamingTool:()=>be,AgentTool:()=>ze,AuthCredentialTypes:()=>Ut,BaseAgent:()=>k,BaseCodeExecutor:()=>oe,BaseExampleProvider:()=>Ue,BaseLlm:()=>X,BaseLlmRequestProcessor:()=>O,BaseLlmResponseProcessor:()=>Ie,BasePlugin:()=>K,BaseSessionService:()=>ve,BaseTool:()=>I,BaseToolset:()=>ce,BuiltInCodeExecutor:()=>ie,CallbackContext:()=>w,FunctionTool:()=>N,GOOGLE_SEARCH:()=>vo,GcsArtifactService:()=>Xt,Gemini:()=>W,GoogleLLMVariant:()=>ge,GoogleSearchTool:()=>Ae,InMemoryArtifactService:()=>se,InMemoryMemoryService:()=>j,InMemoryPolicyEngine:()=>Ce,InMemoryRunner:()=>Ve,InMemorySessionService:()=>V,InvocationContext:()=>B,LLMRegistry:()=>J,LiveRequestQueue:()=>Le,LlmAgent:()=>U,LogLevel:()=>at,LoggingPlugin:()=>je,LongRunningFunctionTool:()=>Ye,LoopAgent:()=>De,MCPSessionManager:()=>Ee,MCPTool:()=>Te,MCPToolset:()=>Qt,ParallelAgent:()=>Ge,PluginManager:()=>ae,PolicyOutcome:()=>Zt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Vt,ReadonlyContext:()=>S,Runner:()=>Z,SecurityPlugin:()=>Ke,SequentialAgent:()=>$e,State:()=>C,StreamingMode:()=>Ne,ToolConfirmation:()=>q,ToolContext:()=>F,createEvent:()=>y,createEventActions:()=>_,createSession:()=>ye,functionsExportedForTestingOnly:()=>fn,getAskUserConfirmationFunctionCalls:()=>fo,getFunctionCalls:()=>T,getFunctionResponses:()=>P,getGcpExporters:()=>jr,getGcpResource:()=>Kr,hasTrailingCodeExecutionResult:()=>tt,isAgentTool:()=>Co,isBaseAgent:()=>cn,isBaseExampleProvider:()=>co,isBaseLlm:()=>Me,isBaseTool:()=>_n,isFinalResponse:()=>z,isFunctionTool:()=>Dn,isGemini2OrAbove:()=>re,isLlmAgent:()=>E,isLoopAgent:()=>eo,isParallelAgent:()=>oo,isSequentialAgent:()=>so,maybeSetOtelProviders:()=>Fr,setLogLevel:()=>ln,stringifyContent:()=>nn,version:()=>Oe,zodObjectToSchema:()=>he});module.exports=jo(Vr);var be=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};var rt=require("@opentelemetry/api");function _(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function en(o,e){let t=_();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function y(o={}){return{...o,id:o.id||nt(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||_(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function z(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:T(o).length===0&&P(o).length===0&&!o.partial&&!tt(o)}function T(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function P(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function tt(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function nn(o){var e;return(e=o.content)!=null&&e.parts?o.content.parts.map(t=>{var n;return(n=t.text)!=null?n:""}).join(""):""}var tn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function nt(){let o="";for(let e=0;e<8;e++)o+=tn[Math.floor(Math.random()*tn.length)];return o}var C=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};C.APP_PREFIX="app:",C.USER_PREFIX="user:",C.TEMP_PREFIX="temp:";var S=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new C(this.invocationContext.session.state,{})}};var w=class extends S{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||_(),this._state=new C(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function Re(){return typeof window<"u"}var Se="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ee(){let o="";for(let e=0;e<Se.length;e++){let t=Math.random()*16|0;Se[e]==="x"?o+=t.toString(16):Se[e]==="y"?o+=(t&3|8).toString(16):o+=Se[e]}return o}function on(o){return Re()?window.atob(o):Buffer.from(o,"base64").toString()}var ot=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},B=class{constructor(e){this.invocationCostManager=new ot;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function rn(){return`e-${ee()}`}var it=Symbol.for("google.adk.baseAgent");function cn(o){return typeof o=="object"&&o!==null&&it in o&&o[it]===!0}var an;an=it;var k=class{constructor(e){this[an]=!0;this.name=Ko(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Zo(this),this.beforeAgentCallback=sn(e.beforeAgentCallback),this.afterAgentCallback=sn(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=rt.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=rt.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new B({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function Ko(o){if(!Vo(o))throw new Error(`Found invalid agent name: "${o}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function Vo(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function Zo(o){for(;o.parentAgent;)o=o.parentAgent;return o}function sn(o){return o?Array.isArray(o)?o:[o]:[]}var O=class{},Ie=class{};var un=require("@google/genai"),lt=require("lodash-es");var ue=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var q=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var F=class extends w{constructor(e){super(e),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new ue(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ue(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new q({hint:e,confirmed:!1,payload:t})}};var at=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(at||{}),te=1;function ln(o){te=o}var st=class{log(e,...t){if(!(e<te))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){te>0||console.debug(Pe(0),...e)}info(...e){te>1||console.info(Pe(1),...e)}warn(...e){te>2||console.warn(Pe(2),...e)}error(...e){te>3||console.error(Pe(3),...e)}},zo={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Yo={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Ho="\x1B[0m";function Pe(o){return`${Yo[o]}[ADK ${zo[o]}]:${Ho}`}var m=new st;var ct="adk-",we="adk_request_credential",ne="adk_request_confirmation",fn={handleFunctionCallList:ke,generateAuthEvent:ft,generateRequestConfirmationEvent:dt};function ut(){return`${ct}${ee()}`}function dn(o){let e=T(o);if(e)for(let t of e)t.id||(t.id=ut())}function pn(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(ct)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(ct)&&(e.functionResponse.id=void 0)}function mn(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function ft(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||(0,lt.isEmpty)(e.actions.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:we,args:{function_call_id:i,auth_config:s},id:ut()};n.add(a.id),t.push({functionCall:a})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function dt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||(0,lt.isEmpty)(t.actions.requestedToolConfirmations))return;let n=[],r=new Set,i=T(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!f)continue;let u={name:ne,args:{originalFunctionCall:f,toolConfirmation:l},id:ut()};r.add(u.id),n.push({functionCall:u})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Qo(o,e,t){return m.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function gn({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=T(e);return await ke({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function ke({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of c){let d;s&&u.id&&(d=s[u.id]);let{tool:p,toolContext:g}=Xo({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});m.debug(`execute_tool ${p.name}`);let v=(f=u.args)!=null?f:{},h=null,x;if(h=await o.pluginManager.runBeforeToolCallback({tool:p,toolArgs:v,toolContext:g}),h==null){for(let $ of n)if(h=await $({tool:p,args:v,context:g}),h)break}if(h==null)try{h=await Qo(p,v,g)}catch($){if($ instanceof Error){let Jt=await o.pluginManager.runOnToolErrorCallback({tool:p,toolArgs:v,toolContext:g,error:$});Jt?h=Jt:x=$.message}else x=$}let R=await o.pluginManager.runAfterToolCallback({tool:p,toolArgs:v,toolContext:g,result:h});if(R==null){for(let $ of r)if(R=await $({tool:p,args:v,context:g,response:h}),R)break}if(R!=null&&(h=R),p.isLongRunning&&!h)continue;x?h={error:x}:(typeof h!="object"||h==null)&&(h={result:h});let Wt=y({invocationId:o.invocationId,author:o.agent.name,content:(0,un.createUserContent)({functionResponse:{id:g.functionCallId,name:p.name,response:h}}),actions:g.actions,branch:o.branch});m.debug("traceToolCall",{tool:p.name,args:v,functionResponseEvent:Wt.id}),a.push(Wt)}if(!a.length)return null;let l=Wo(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Xo({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new F({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Wo(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=en(n);return y({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Le=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var It=require("lodash-es"),Pt=require("zod");var pt=Symbol.for("google.adk.baseCodeExecutor");function _e(o){return typeof o=="object"&&o!==null&&pt in o&&o[pt]===!0}var hn;hn=pt;var oe=class{constructor(){this[hn]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Jo="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function mt(o){let e=o.match(Jo);return e?e[1]:o}function Cn(o){return mt(o).startsWith("gemini-")}function er(o){if(!/^\d+(\.\d+)*$/.test(o))return{valid:!1,major:0,minor:0,patch:0};let e=o.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function vn(o){return mt(o).startsWith("gemini-1")}function re(o){if(!o)return!1;let e=mt(o);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],n=er(t);return n.valid&&n.major>=2}var gt=Symbol.for("google.adk.builtInCodeExecutor");function fe(o){return typeof o=="object"&&o!==null&> in o&&o[gt]===!0}var yn,xn,ie=class extends(xn=oe,yn=gt,xn){constructor(){super(...arguments);this[yn]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&re(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${t.model}`)}};var de=require("@google/genai"),An=require("lodash-es");function En(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let d=o.parts[u];if(d.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),d.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=(0,An.cloneDeep)(t[0]),r=t.map(u=>u.text).join(`
|
|
8
|
-
`),i=e.map(
|
|
9
|
-
${
|
|
10
|
-
`),
|
|
11
|
-
`+
|
|
7
|
+
"use strict";var at=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var rr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var sr=(n,e)=>{for(var t in e)at(n,t,{get:e[t],enumerable:!0})},ar=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rr(e))!ir.call(n,r)&&r!==t&&at(n,r,{get:()=>e[r],enumerable:!(o=or(e,r))||o.enumerable});return n};var cr=n=>ar(at({},"__esModule",{value:!0}),n);var xi={};sr(xi,{ActiveStreamingTool:()=>ke,AgentTool:()=>nt,AuthCredentialTypes:()=>Qt,BaseAgent:()=>I,BaseCodeExecutor:()=>ae,BaseExampleProvider:()=>He,BaseLlm:()=>X,BaseLlmRequestProcessor:()=>k,BaseLlmResponseProcessor:()=>Oe,BasePlugin:()=>z,BaseSessionService:()=>Ee,BaseTool:()=>b,BaseToolset:()=>de,BuiltInCodeExecutor:()=>le,CallbackContext:()=>R,FunctionTool:()=>B,GOOGLE_SEARCH:()=>Do,GcsArtifactService:()=>ct,Gemini:()=>Q,GoogleLLMVariant:()=>Ae,GoogleSearchTool:()=>Se,InMemoryArtifactService:()=>ue,InMemoryMemoryService:()=>U,InMemoryPolicyEngine:()=>ye,InMemoryRunner:()=>et,InMemorySessionService:()=>j,InvocationContext:()=>M,LLMRegistry:()=>ee,LiveRequestQueue:()=>Fe,LlmAgent:()=>q,LogLevel:()=>ht,LoggingPlugin:()=>We,LongRunningFunctionTool:()=>ot,LoopAgent:()=>Ke,MCPSessionManager:()=>Re,MCPTool:()=>Ie,MCPToolset:()=>cn,ParallelAgent:()=>Je,PluginManager:()=>fe,PolicyOutcome:()=>on,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>nn,ReadonlyContext:()=>T,Runner:()=>V,SecurityPlugin:()=>Xe,SequentialAgent:()=>Ye,State:()=>C,StreamingMode:()=>ze,ToolConfirmation:()=>$,ToolContext:()=>F,createEvent:()=>v,createEventActions:()=>P,createSession:()=>Te,functionsExportedForTestingOnly:()=>_n,getAskUserConfirmationFunctionCalls:()=>Oo,getFunctionCalls:()=>E,getFunctionResponses:()=>S,getGcpExporters:()=>di,getGcpResource:()=>pi,getLogger:()=>kn,hasTrailingCodeExecutionResult:()=>lt,isAgentTool:()=>Fo,isBaseAgent:()=>In,isBaseExampleProvider:()=>ko,isBaseLlm:()=>Ge,isBaseTool:()=>Qn,isFinalResponse:()=>K,isFunctionTool:()=>io,isGemini2OrAbove:()=>ce,isLlmAgent:()=>A,isLoopAgent:()=>Eo,isParallelAgent:()=>So,isSequentialAgent:()=>wo,maybeSetOtelProviders:()=>mi,setLogLevel:()=>wn,setLogger:()=>Pn,stringifyContent:()=>mn,version:()=>ne,zodObjectToSchema:()=>Ue});module.exports=cr(xi);var fn=require("@google-cloud/storage"),Pe=require("@google/genai");var ct=class{constructor(e){this.bucket=new fn.Storage().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),o=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(we({...e,version:o}));if(e.artifact.inlineData)return await r.save(JSON.stringify(e.artifact.inlineData.data),{contentType:e.artifact.inlineData.mimeType}),o;if(e.artifact.text)return await r.save(e.artifact.text,{contentType:"text/plain"}),o;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 o=this.bucket.file(we({...e,version:t})),[[r],[i]]=await Promise.all([o.getMetadata(),o.download()]);return r.contentType==="text/plain"?(0,Pe.createPartFromText)(i.toString("utf-8")):(0,Pe.createPartFromBase64)(i.toString("base64"),r.contentType)}async listArtifactKeys(e){let t=[],o=`${e.appName}/${e.userId}/${e.sessionId}/`,r=`${e.appName}/${e.userId}/user/`,[[i],[s]]=await Promise.all([this.bucket.getFiles({prefix:o}),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(o=>this.bucket.file(we({...e,version:o})).delete()))}async listVersions(e){let t=we(e),[o]=await this.bucket.getFiles({prefix:t}),r=[];for(let i of o){let s=i.name.split("/").pop();r.push(parseInt(s,10))}return r}};function we({appName:n,userId:e,sessionId:t,filename:o,version:r}){return o.startsWith("user:")?`${n}/${e}/user/${o}/${r}`:`${n}/${e}/${t}/${o}/${r}`}var ke=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};var re=require("@opentelemetry/api");function P(n={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...n}}function dn(n,e){let t=P();e&&Object.assign(t,e);for(let o of n)o&&(o.stateDelta&&Object.assign(t.stateDelta,o.stateDelta),o.artifactDelta&&Object.assign(t.artifactDelta,o.artifactDelta),o.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,o.requestedAuthConfigs),o.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,o.requestedToolConfirmations),o.skipSummarization!==void 0&&(t.skipSummarization=o.skipSummarization),o.transferToAgent!==void 0&&(t.transferToAgent=o.transferToAgent),o.escalate!==void 0&&(t.escalate=o.escalate));return t}function v(n={}){return{...n,id:n.id||ut(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||P(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()}}function K(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:E(n).length===0&&S(n).length===0&&!n.partial&&!lt(n)}function E(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionCall&&e.push(t.functionCall);return e}function S(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function lt(n){var e;return n.content&&((e=n.content.parts)!=null&&e.length)?n.content.parts[n.content.parts.length-1].codeExecutionResult!==void 0:!1}function mn(n){var e;return(e=n.content)!=null&&e.parts?n.content.parts.map(t=>{var o;return(o=t.text)!=null?o:""}).join(""):""}var pn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function ut(){let n="";for(let e=0;e<8;e++)n+=pn[Math.floor(Math.random()*pn.length)];return n}var _=require("@opentelemetry/api");var ne="0.3.0";var lr="gen_ai.agent.description",ur="gen_ai.agent.name",fr="gen_ai.conversation.id",ft="gen_ai.operation.name",gn="gen_ai.tool.call.id",hn="gen_ai.tool.description",Cn="gen_ai.tool.name",dr="gen_ai.tool.type",O=_.trace.getTracer("gcp.vertex.agent",ne);function pe(n){try{return JSON.stringify(n)}catch{return"<not serializable>"}}function vn({agent:n,invocationContext:e}){let t=_.trace.getActiveSpan();t&&t.setAttributes({[ft]:"invoke_agent",[lr]:n.description,[ur]:n.name,[fr]:e.session.id})}function xn({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=_.trace.getActiveSpan();if(!o)return;o.setAttributes({[ft]:"execute_tool",[hn]:n.description||"",[Cn]:n.name,[dr]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":me()?pe(e):"{}"});let r="<not specified>",i="<not specified>";if((s=t.content)!=null&&s.parts){let l=(a=t.content.parts[0])==null?void 0:a.functionResponse;l!=null&&l.id&&(r=l.id),l!=null&&l.response&&(i=l.response)}(typeof i!="object"||i===null)&&(i={result:i}),o.setAttributes({[gn]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":me()?pe(i):"{}"})}function An({responseEventId:n,functionResponseEvent:e}){let t=_.trace.getActiveSpan();t&&(t.setAttributes({[ft]:"execute_tool",[Cn]:"(merged tools)",[hn]:"(merged tools)",[gn]:n,"gcp.vertex.agent.tool_call_args":"N/A","gcp.vertex.agent.event_id":n,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}"}),t.setAttribute("gcp.vertex.agent.tool_response",me()?pe(e):"{}"))}function yn({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=_.trace.getActiveSpan();if(r&&(r.setAttributes({"gen_ai.system":"gcp.vertex.agent","gen_ai.request.model":t.model,"gcp.vertex.agent.invocation_id":n.invocationId,"gcp.vertex.agent.session_id":n.session.id,"gcp.vertex.agent.event_id":e,"gcp.vertex.agent.llm_request":me()?pe(pr(t)):"{}"}),(i=t.config)!=null&&i.topP&&r.setAttribute("gen_ai.request.top_p",t.config.topP),((s=t.config)==null?void 0:s.maxOutputTokens)!==void 0&&r.setAttribute("gen_ai.request.max_tokens",t.config.maxOutputTokens),r.setAttribute("gcp.vertex.agent.llm_response",me()?pe(o):"{}"),o.usageMetadata&&r.setAttribute("gen_ai.usage.input_tokens",o.usageMetadata.promptTokenCount||0),(a=o.usageMetadata)!=null&&a.candidatesTokenCount&&r.setAttribute("gen_ai.usage.output_tokens",o.usageMetadata.candidatesTokenCount),o.finishReason)){let c=typeof o.finishReason=="string"?o.finishReason.toLowerCase():String(o.finishReason).toLowerCase();r.setAttribute("gen_ai.response.finish_reasons",[c])}}function pr(n){let e={model:n.model,contents:[]};if(n.config){let{responseSchema:t,...o}=n.config;e.config=o}return e.contents=n.contents.map(t=>{var o;return{role:t.role,parts:((o=t.parts)==null?void 0:o.filter(r=>!r.inlineData))||[]}}),e}function En(n,e){return{next:_.context.bind(n,e.next.bind(e)),return:_.context.bind(n,e.return.bind(e)),throw:_.context.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return En(n,e[Symbol.asyncIterator]())}}}function J(n,e,t){let o=t.call(e);return En(n,o)}function me(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var C=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};C.APP_PREFIX="app:",C.USER_PREFIX="user:",C.TEMP_PREFIX="temp:";var T=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new C(this.invocationContext.session.state,{})}};var R=class extends T{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||P(),this._state=new C(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let o=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]=o,o}};function _e(){return typeof window<"u"}var Le="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function oe(){let n="";for(let e=0;e<Le.length;e++){let t=Math.random()*16|0;Le[e]==="x"?n+=t.toString(16):Le[e]==="y"?n+=(t&3|8).toString(16):n+=Le[e]}return n}function Tn(n){return _e()?window.atob(n):Buffer.from(n,"base64").toString()}var dt=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`)}},M=class{constructor(e){this.invocationCostManager=new dt;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 bn(){return`e-${oe()}`}var pt=Symbol.for("google.adk.baseAgent");function In(n){return typeof n=="object"&&n!==null&&pt in n&&n[pt]===!0}var Rn;Rn=pt;var I=class{constructor(e){this[Rn]=!0;this.name=mr(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=Sn(e.beforeAgentCallback),this.afterAgentCallback=Sn(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return hr(this)}async*runAsync(e){let t=O.startSpan(`invoke_agent ${this.name}`),o=re.trace.setSpan(re.context.active(),t);try{yield*J(o,this,async function*(){let r=this.createInvocationContext(e),i=await this.handleBeforeAgentCallback(r);if(i&&(yield i),r.endInvocation)return;vn({agent:this,invocationContext:r});for await(let a of this.runAsyncImpl(r))yield a;if(r.endInvocation)return;let s=await this.handleAfterAgentCallback(r);s&&(yield s)})}finally{t.end()}}async*runLive(e){let t=O.startSpan(`invoke_agent ${this.name}`),o=re.trace.setSpan(re.context.active(),t);try{throw yield*J(o,this,async function*(){}),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 o=t.findAgent(e);if(o)return o}}createInvocationContext(e){return new M({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new R({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,v({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return v({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new R({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return v({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return v({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 mr(n){if(!gr(n))throw new Error(`Found invalid agent name: "${n}". 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(n==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return n}function gr(n){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(n)}function hr(n){for(;n.parentAgent;)n=n.parentAgent;return n}function Sn(n){return n?Array.isArray(n)?n:[n]:[]}var k=class{},Oe=class{};var Ln=require("@google/genai"),vt=require("lodash-es");var ge=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,o;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((o=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&o.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 $=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var F=class extends R{constructor(e){super(e),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new ge(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ge(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 $({hint:e,confirmed:!1,payload:t})}};var ht=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(ht||{}),ie=1;function wn(n){ie=n}var mt=class{log(e,...t){if(!(e<ie))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){ie>0||console.debug(Me(0),...e)}info(...e){ie>1||console.info(Me(1),...e)}warn(...e){ie>2||console.warn(Me(2),...e)}error(...e){ie>3||console.error(Me(3),...e)}},gt=class{log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},Cr={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},vr={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},xr="\x1B[0m";function Me(n){return`${vr[n]}[ADK ${Cr[n]}]:${xr}`}var Y=new mt;function Pn(n){Y=n!=null?n:new gt}function kn(){return Y}var g={log(n,...e){Y.log(n,...e)},debug(...n){Y.debug(...n)},info(...n){Y.info(...n)},warn(...n){Y.warn(...n)},error(...n){Y.error(...n)}};var Ct="adk-",Be="adk_request_credential",se="adk_request_confirmation",_n={handleFunctionCallList:Ne,generateAuthEvent:At,generateRequestConfirmationEvent:yt};function xt(){return`${Ct}${oe()}`}function On(n){let e=E(n);if(e)for(let t of e)t.id||(t.id=xt())}function Mn(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ct)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ct)&&(e.functionResponse.id=void 0)}function Bn(n,e){let t=new Set;for(let o of n)o.name&&o.name in e&&e[o.name].isLongRunning&&o.id&&t.add(o.id);return t}function At(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||(0,vt.isEmpty)(e.actions.requestedAuthConfigs))return;let t=[],o=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:xt()};o.add(a.id),t.push({functionCall:a})}return v({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function yt({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||(0,vt.isEmpty)(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=E(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!u)continue;let f={name:se,args:{originalFunctionCall:u,toolConfirmation:l},id:xt()};r.add(f.id),o.push({functionCall:f})}return v({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:o,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Ar(n,e,t){return O.startActiveSpan(`execute_tool ${n.name}`,async o=>{try{g.debug(`callToolAsync ${n.name}`);let r=await n.runAsync({args:e,toolContext:t});return xn({tool:n,args:e,functionResponseEvent:yr(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function yr(n,e,t,o){let r;typeof e!="object"||e==null?r={result:e}:r=e;let s={role:"user",parts:[{functionResponse:{name:n.name,response:r,id:t.functionCallId}}]};return v({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function Nn({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=E(e);return await Ne({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ne({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let d;s&&f.id&&(d=s[f.id]);let{tool:m,toolContext:p}=Er({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:d});g.debug(`execute_tool ${m.name}`);let x=(u=f.args)!=null?u:{},h=null,y;if(h=await n.pluginManager.runBeforeToolCallback({tool:m,toolArgs:x,toolContext:p}),h==null){for(let G of o)if(h=await G({tool:m,args:x,context:p}),h)break}if(h==null)try{h=await Ar(m,x,p)}catch(G){if(G instanceof Error){let un=await n.pluginManager.runOnToolErrorCallback({tool:m,toolArgs:x,toolContext:p,error:G});un?h=un:y=G.message}else y=G}let N=await n.pluginManager.runAfterToolCallback({tool:m,toolArgs:x,toolContext:p,result:h});if(N==null){for(let G of r)if(N=await G({tool:m,args:x,context:p,response:h}),N)break}if(N!=null&&(h=N),m.isLongRunning&&!h)continue;y?h={error:y}:(typeof h!="object"||h==null)&&(h={result:h});let ln=v({invocationId:n.invocationId,author:n.agent.name,content:(0,Ln.createUserContent)({functionResponse:{id:p.functionCallId,name:m.name,response:h}}),actions:p.actions,branch:n.branch});g.debug("traceToolCall",{tool:m.name,args:x,functionResponseEvent:ln.id}),a.push(ln)}if(!a.length)return null;let l=Tr(a);return a.length>1&&O.startActiveSpan("execute_tool (merged)",f=>{try{g.debug("execute_tool (merged)"),g.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),An({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function Er({invocationContext:n,functionCall:e,toolsDict:t,toolConfirmation:o}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new F({invocationContext:n,functionCallId:e.id||void 0,toolConfirmation:o});return{tool:t[e.name],toolContext:r}}function Tr(n){if(!n.length)throw new Error("No function response events provided.");if(n.length===1)return n[0];let e=[];for(let i of n)i.content&&i.content.parts&&e.push(...i.content.parts);let t=n[0],o=n.map(i=>i.actions||{}),r=dn(o);return v({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(),o=this.queue.shift();t(o)}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 Ve=require("@opentelemetry/api"),Dt=require("lodash-es"),Gt=require("zod");var Et=Symbol.for("google.adk.baseCodeExecutor");function De(n){return typeof n=="object"&&n!==null&&Et in n&&n[Et]===!0}var Fn;Fn=Et;var ae=class{constructor(){this[Fn]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var br="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Tt(n){let e=n.match(br);return e?e[1]:n}function Dn(n){return Tt(n).startsWith("gemini-")}function Sr(n){if(!/^\d+(\.\d+)*$/.test(n))return{valid:!1,major:0,minor:0,patch:0};let e=n.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function Gn(n){return Tt(n).startsWith("gemini-1")}function ce(n){if(!n)return!1;let e=Tt(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Sr(t);return o.valid&&o.major>=2}var bt=Symbol.for("google.adk.builtInCodeExecutor");function he(n){return typeof n=="object"&&n!==null&&bt in n&&n[bt]===!0}var $n,qn,le=class extends(qn=ae,$n=bt,qn){constructor(){super(...arguments);this[$n]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&ce(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${t.model}`)}};var Ce=require("@google/genai"),Un=require("lodash-es");function zn(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let d=n.parts[f];if(d.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),d.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=(0,Un.cloneDeep)(t[0]),r=t.map(f=>f.text).join(`
|
|
8
|
+
`),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[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?(n.parts=[],c&&(o.text=c,n.parts.push(o)),n.parts.push(St(l)),l):""}function St(n){return{text:n,executableCode:{code:n,language:Ce.Language.PYTHON}}}function jn(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:Ce.Outcome.OUTCOME_FAILED}};let e=[];return(n.stdout||!n.outputFiles)&&e.push(`Code execution result:
|
|
9
|
+
${n.stdout}
|
|
10
|
+
`),n.outputFiles&&e.push(`Saved artifacts:
|
|
11
|
+
`+n.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
|
|
12
12
|
|
|
13
|
-
`),codeExecutionResult:{outcome:
|
|
13
|
+
`),codeExecutionResult:{outcome:Ce.Outcome.OUTCOME_OK}}}function Vn(n,e,t){var r;if(!((r=n.parts)!=null&&r.length))return;let o=n.parts[n.parts.length-1];o.executableCode?n.parts[n.parts.length-1]={text:e[0]+o.executableCode.code+e[1]}:n.parts.length==1&&o.codeExecutionResult&&(n.parts[n.parts.length-1]={text:t[0]+o.codeExecutionResult.output+t[1]},n.role="user")}var Kn=require("lodash-es");var Rt="_code_execution_context",It="execution_session_id",Z="processed_input_files",H="_code_executor_input_files",W="_code_executor_error_counts",wt="_code_execution_results",ve=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Rt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Rt]:(0,Kn.cloneDeep)(this.context)}}getExecutionId(){if(It in this.context)return this.context[It]}setExecutionId(e){this.context[It]=e}getProcessedFileNames(){return Z in this.context?this.context[Z]:[]}addProcessedFileNames(e){Z in this.context||(this.context[Z]=[]),this.context[Z].push(...e)}getInputFiles(){return H in this.sessionState?this.sessionState.get(H):[]}addInputFiles(e){H in this.sessionState||this.sessionState.set(H,[]),this.sessionState.get(H).push(...e)}clearInputFiles(){H in this.sessionState&&this.sessionState.set(H,[]),Z in this.context&&(this.context[Z]=[])}getErrorCount(e){return W in this.sessionState&&this.sessionState.get(W)[e]||0}incrementErrorCount(e){W in this.sessionState||this.sessionState.set(W,{}),this.sessionState.get(W)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(W in this.sessionState))return;let t=this.sessionState.get(W);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){wt in this.sessionState||this.sessionState.set(wt,{});let i=this.sessionState.get(wt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(Rt)||{}}};var Rr="google-adk",Ir="gl-typescript",wr="remote_reasoning_engine",Pr="GOOGLE_CLOUD_AGENT_ENGINE_ID";function kr(){let n=`${Rr}/${ne}`;!_e()&&process.env[Pr]&&(n=`${n}+${wr}`);let e=`${Ir}/${_e()?window.navigator.userAgent:process.version}`;return[n,e]}function Jn(){return kr()}var Pt=Symbol.for("google.adk.baseModel");function Ge(n){return typeof n=="object"&&n!==null&&Pt in n&&n[Pt]===!0}var Yn;Yn=Pt;var X=class{constructor({model:e}){this[Yn]=!0;this.model=e}get trackingHeaders(){let t=Jn().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};X.supportedModels=[];function xe(n,e){n.config||(n.config={});let t=e.join(`
|
|
14
14
|
|
|
15
|
-
`);
|
|
15
|
+
`);n.config.systemInstruction?n.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 D=require("@google/genai");var ge=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(ge||{});function wn(){return sr("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function sr(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Be=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(n=>{var r;return n.parts&&((r=n.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):m.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(n=>n.functionResponse).filter(n=>!!n);m.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else m.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){m.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function At(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var W=class extends X{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!n,!this.vertexai&&a){let c=process.env.GOOGLE_GENAI_USE_VERTEXAI;c&&(this.vertexai=c.toLowerCase()==="true"||c==="1")}if(this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,a,c,l;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let f=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),u="",d="",p,g;for await(let v of f){g=v;let h=At(v);p=h.usageMetadata;let x=(s=(i=h.content)==null?void 0:i.parts)==null?void 0:s[0];if(x!=null&&x.text)"thought"in x&&x.thought?u+=x.text:d+=x.text,h.partial=!0;else if((u||d)&&(!x||!x.inlineData)){let R=[];u&&R.push({text:u,thought:!0}),d&&R.push((0,D.createPartFromText)(d)),yield{content:{role:"model",parts:R},usageMetadata:h.usageMetadata},u="",d=""}yield h}if((d||u)&&((c=(a=g==null?void 0:g.candidates)==null?void 0:a[0])==null?void 0:c.finishReason)===D.FinishReason.STOP){let v=[];u&&v.push({text:u,thought:!0}),d&&v.push({text:d}),yield{content:{role:"model",parts:v},usageMetadata:p}}}else{let f=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield At(f)}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};return this.vertexai?this._apiClient=new D.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new D.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new D.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,D.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new Be(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)kn(n.inlineData),kn(n.fileData)}}};W.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function kn(o){o&&o.displayName&&(o.displayName=void 0)}var Et=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},L=class L{static newLlm(e){return new(L.resolve(e))({model:e})}static _register(e,t){L.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${L.llmRegistryDict.get(e)} to ${t}`),L.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)L._register(t,e)}static resolve(e){let t=L.resolveCache.get(e);if(t)return t;for(let[n,r]of L.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return L.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};L.llmRegistryDict=new Map,L.resolveCache=new Et(32);var J=L;J.register(W);var Tt=Symbol.for("google.adk.baseTool");function _n(o){return typeof o=="object"&&o!==null&&Tt in o&&o[Tt]===!0}var Ln;Ln=Tt;var I=class{constructor(e){this[Ln]=!0;var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=ar(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return wn()}};function ar(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var Nn=require("@google/genai"),Fn=require("zod");var b=require("@google/genai"),A=require("zod");function On(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function G(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case A.z.ZodFirstPartyTypeKind.ZodString:n.type=b.Type.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case A.z.ZodFirstPartyTypeKind.ZodNumber:n.type=b.Type.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=b.Type.INTEGER);return r(n);case A.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=b.Type.BOOLEAN,r(n);case A.z.ZodFirstPartyTypeKind.ZodArray:return n.type=b.Type.ARRAY,n.items=G(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case A.z.ZodFirstPartyTypeKind.ZodObject:return he(o);case A.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=b.Type.STRING;else if(i==="number")n.type=b.Type.NUMBER;else if(i==="boolean")n.type=b.Type.BOOLEAN;else if(e.value===null)n.type=b.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case A.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=b.Type.STRING,n.enum=e.values,r(n);case A.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=b.Type.STRING,n.enum=Object.values(e.values),r(n);case A.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(G),r(n);case A.z.ZodFirstPartyTypeKind.ZodOptional:return G(e.innerType);case A.z.ZodFirstPartyTypeKind.ZodNullable:let s=G(e.innerType);return r(s?{anyOf:[s,{type:b.Type.NULL}],...t&&{description:t}}:{type:b.Type.NULL,...t&&{description:t}});case A.z.ZodFirstPartyTypeKind.ZodDefault:let a=G(e.innerType);return a&&(a.default=e.defaultValue()),a;case A.z.ZodFirstPartyTypeKind.ZodBranded:return G(e.type);case A.z.ZodFirstPartyTypeKind.ZodReadonly:return G(e.innerType);case A.z.ZodFirstPartyTypeKind.ZodNull:return n.type=b.Type.NULL,r(n);case A.z.ZodFirstPartyTypeKind.ZodAny:case A.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function he(o){if(o._def.typeName!==A.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=G(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===A.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===A.z.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==A.z.ZodFirstPartyTypeKind.ZodNever?i=G(r)||!0:i=o._def.unknownKeys==="passthrough",{type:b.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function cr(o){return o===void 0?{type:Nn.Type.OBJECT,properties:{}}:On(o)?he(o):o}var bt=Symbol.for("google.adk.functionTool");function Dn(o){return typeof o=="object"&&o!==null&&bt in o&&o[bt]===!0}var Mn,Bn,N=class extends(Bn=I,Mn=bt,Bn){constructor(t){var r;let n=(r=t.name)!=null?r:t.execute.name;if(!n)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:n,description:t.description,isLongRunning:t.isLongRunning});this[Mn]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:cr(this.parameters)}}async runAsync(t){try{let n=t.args;return this.parameters instanceof Fn.ZodObject&&(n=this.parameters.parse(t.args)),await this.execute(n,t.toolContext)}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Error in tool '${this.name}': ${r}`)}}};var $n=require("lodash-es");function St(o,e,t){var s,a,c;let n=[];for(let l of o)!((s=l.content)!=null&&s.role)||((c=(a=l.content.parts)==null?void 0:a[0])==null?void 0:c.text)===""||t&&l.branch&&!t.startsWith(l.branch)||lr(l)||ur(l)||n.push(Un(e,l)?fr(l):l);let r=dr(n);r=pr(r);let i=[];for(let l of r){let f=(0,$n.cloneDeep)(l.content);pn(f),i.push(f)}return i}function qn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Un(e,r))return St(o.slice(n),e,t)}return[]}function lr(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===we||((n=r.functionResponse)==null?void 0:n.name)===we)return!0;return!1}function ur(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===ne||((n=r.functionResponse)==null?void 0:n.name)===ne)return!0;return!1}function Un(o,e){return!!o&&e.author!==o&&e.author!=="user"}function fr(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=Gn(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=Gn(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return y({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function jn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=y(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function dr(o){if(o.length===0)return o;let e=o[o.length-1],t=P(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=T(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],f=T(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=c;let d=new Set(f.map(g=>g.id).filter(g=>!!g));if(!Array.from(n).every(g=>d.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=P(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(jn(s)),a}function pr(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=P(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(P(n).length>0)continue;let r=T(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(jn(a))}}else t.push(n)}return t}function Gn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Rt(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!hr(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var mr=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Kn(o){return o===""||o===void 0?!1:mr.test(o)}var gr=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function hr(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Kn(o):gr.includes(e[0]+":")?Kn(e[1]):!1}var Ne=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ne||{});function Vn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Cr(o.maxLlmCalls||500),...o}}function Cr(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&m.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),o}var Zn="adk_agent_name";async function zn(o,e){return o instanceof I?[o]:await o.getTools(e)}var wt=class extends O{async*runAsync(e,t){var r;let n=e.agent;E(n)&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&Pn(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))}},vr=new wt,kt=class extends O{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),me(t,r)}},yr=new kt,Lt=class extends O{async*runAsync(e,t){let n=e.agent;if(!(n instanceof U)||!(n.rootAgent instanceof U))return;let r=n.rootAgent;if(E(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new S(e)),a=i;s&&(a=await Rt(i,new S(e))),me(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new S(e)),a=i;s&&(a=await Rt(i,new S(e))),me(t,[a])}}},xr=new Lt,_t=class{async*runAsync(e,t){let n=e.agent;!n||!E(n)||(n.includeContents==="default"?t.contents=St(e.session.events,n.name,e.branch):t.contents=qn(e.session.events,n.name,e.branch))}},Ar=new _t,Ot=class extends O{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new N({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:Pt.z.object({agentName:Pt.z.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof U))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;me(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new F({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
17
|
+
`+t:n.config.systemInstruction=t}function Zn(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}var D=require("@google/genai");var Ae=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Ae||{});function Hn(){return Lr("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Lr(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var $e=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(o=>{var r;return o.parts&&((r=o.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):g.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(o=>o.functionResponse).filter(o=>!!o);g.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else g.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){g.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 kt(n){var t;let e=n.usageMetadata;if(n.candidates&&n.candidates.length>0){let o=n.candidates[0];return(t=o.content)!=null&&t.parts&&o.content.parts.length>0?{content:o.content,groundingMetadata:o.groundingMetadata,usageMetadata:e,finishReason:o.finishReason}:{errorCode:o.finishReason,errorMessage:o.finishMessage,usageMetadata:e,finishReason:o.finishReason}}return n.promptFeedback?{errorCode:n.promptFeedback.blockReason,errorMessage:n.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var Q=class extends X{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!o,!this.vertexai&&a){let c=process.env.GOOGLE_GENAI_USE_VERTEXAI;c&&(this.vertexai=c.toLowerCase()==="true"||c==="1")}if(this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var o,r,i,s,a,c,l;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),g.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(o=e.config)!=null&&o.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let u=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),f="",d="",m,p;for await(let x of u){p=x;let h=kt(x);m=h.usageMetadata;let y=(s=(i=h.content)==null?void 0:i.parts)==null?void 0:s[0];if(y!=null&&y.text)"thought"in y&&y.thought?f+=y.text:d+=y.text,h.partial=!0;else if((f||d)&&(!y||!y.inlineData)){let N=[];f&&N.push({text:f,thought:!0}),d&&N.push((0,D.createPartFromText)(d)),yield{content:{role:"model",parts:N},usageMetadata:h.usageMetadata},f="",d=""}yield h}if((d||f)&&((c=(a=p==null?void 0:p.candidates)==null?void 0:a[0])==null?void 0:c.finishReason)===D.FinishReason.STOP){let x=[];f&&x.push({text:f,thought:!0}),d&&x.push({text:d}),yield{content:{role:"model",parts:x},usageMetadata:m}}}else{let u=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield kt(u)}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};return this.vertexai?this._apiClient=new D.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new D.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new D.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),this._liveApiClient}async connect(e){var o,r,i,s;(o=e.liveConnectConfig)!=null&&o.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,D.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new $e(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 o of t.parts)Wn(o.inlineData),Wn(o.fileData)}}};Q.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Wn(n){n&&n.displayName&&(n.displayName=void 0)}var Lt=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 o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},w=class w{static newLlm(e){return new(w.resolve(e))({model:e})}static _register(e,t){w.llmRegistryDict.has(e)&&g.info(`Updating LLM class for ${e} from ${w.llmRegistryDict.get(e)} to ${t}`),w.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)w._register(t,e)}static resolve(e){let t=w.resolveCache.get(e);if(t)return t;for(let[o,r]of w.llmRegistryDict.entries())if(new RegExp(`^${o instanceof RegExp?o.source:o}$`,o instanceof RegExp?o.flags:void 0).test(e))return w.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};w.llmRegistryDict=new Map,w.resolveCache=new Lt(32);var ee=w;ee.register(Q);var _t=Symbol.for("google.adk.baseTool");function Qn(n){return typeof n=="object"&&n!==null&&_t in n&&n[_t]===!0}var Xn;Xn=_t;var b=class{constructor(e){this[Xn]=!0;var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({llmRequest:e}){let t=this._getDeclaration();if(!t)return;e.toolsDict[this.name]=this;let o=_r(e);o?(o.functionDeclarations||(o.functionDeclarations=[]),o.functionDeclarations.push(t)):(e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({functionDeclarations:[t]}))}get apiVariant(){return Hn()}};function _r(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var ro=require("@google/genai");var Ot=require("@google/genai"),eo=require("zod-to-json-schema"),to=require("zod/v4");function Mt(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function Or(n){return Mt(n)&&!("_zod"in n)}function Mr(n){return Mt(n)&&"_zod"in n}function Br(n){var o,r;let e=n;if((o=e._def)!=null&&o.typeName)return e._def.typeName;let t=(r=e._def)==null?void 0:r.type;if(typeof t=="string"&&t)return"Zod"+t.charAt(0).toUpperCase()+t.slice(1)}function qe(n){return Mt(n)&&Br(n)==="ZodObject"}function Ue(n){if(!qe(n))throw new Error("Expected a Zod Object");if(Mr(n))return(0,to.toJSONSchema)(n,{target:"openapi-3.0",io:"input",override:e=>{var o;let{jsonSchema:t}=e;t.additionalProperties!==void 0&&delete t.additionalProperties,t.readOnly!==void 0&&delete t.readOnly,t.maxItems!==void 0&&(t.maxItems=t.maxItems.toString()),(t.format==="email"||t.format==="uuid")&&delete t.pattern,t.minItems!==void 0&&(t.minItems=t.minItems.toString()),t.minLength!==void 0&&(t.minLength=t.minLength.toString()),t.maxLength!==void 0&&(t.maxLength=t.maxLength.toString()),((o=t.enum)==null?void 0:o.length)===1&&t.enum[0]===null&&(t.type=Ot.Type.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(Or(n))return(0,eo.zodToJsonSchema)(n,{target:"openApi3",emailStrategy:"format:email",postProcess:e=>{var t,o,r,i,s,a,c;if(e)return e.additionalProperties!==void 0&&delete e.additionalProperties,e.maxItems!==void 0&&(e.maxItems=(t=e.maxItems)==null?void 0:t.toString()),e.minItems!==void 0&&(e.minItems=(o=e.minItems)==null?void 0:o.toString()),e.minLength!==void 0&&(e.minLength=(r=e.minLength)==null?void 0:r.toString()),e.maxLength!==void 0&&(e.maxLength=(i=e.maxLength)==null?void 0:i.toString()),((s=e.enum)==null?void 0:s.length)===1&&e.enum[0]==="null"&&(e.type=Ot.Type.NULL,delete e.enum),e.type==="integer"&&e.format!=="int64"&&((a=e.minimum)!=null||(e.minimum=Number.MIN_SAFE_INTEGER),(c=e.maximum)!=null||(e.maximum=Number.MAX_SAFE_INTEGER)),e.type!==void 0&&(e.type=e.type.toUpperCase()),e}});throw new Error("Unsupported Zod schema version.")}function Nr(n){return n===void 0?{type:ro.Type.OBJECT,properties:{}}:qe(n)?Ue(n):n}var Bt=Symbol.for("google.adk.functionTool");function io(n){return typeof n=="object"&&n!==null&&Bt in n&&n[Bt]===!0}var no,oo,B=class extends(oo=b,no=Bt,oo){constructor(t){var r;let o=(r=t.name)!=null?r:t.execute.name;if(!o)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:o,description:t.description,isLongRunning:t.isLongRunning});this[no]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:Nr(this.parameters)}}async runAsync(t){try{let o=t.args;return qe(this.parameters)&&(o=this.parameters.parse(t.args)),await this.execute(o,t.toolContext)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error(`Error in tool '${this.name}': ${r}`)}}};var ao=require("lodash-es");function Nt(n,e,t){var s,a,c;let o=[];for(let l of n)!((s=l.content)!=null&&s.role)||((c=(a=l.content.parts)==null?void 0:a[0])==null?void 0:c.text)===""||t&&l.branch&&!t.startsWith(l.branch)||Fr(l)||Dr(l)||o.push(lo(e,l)?Gr(l):l);let r=$r(o);r=qr(r);let i=[];for(let l of r){let u=(0,ao.cloneDeep)(l.content);Mn(u),i.push(u)}return i}function co(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||lo(e,r))return Nt(n.slice(o),e,t)}return[]}function Fr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Be||((o=r.functionResponse)==null?void 0:o.name)===Be)return!0;return!1}function Dr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===se||((o=r.functionResponse)==null?void 0:o.name)===se)return!0;return!1}function lo(n,e){return!!n&&e.author!==n&&e.author!=="user"}function Gr(n){var t,o,r,i,s,a;if(!((o=(t=n.content)==null?void 0:t.parts)!=null&&o.length))return n;let e={role:"user",parts:[{text:"For context:"}]};for(let c of n.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${n.author}] said: ${c.text}`});else if(c.functionCall){let l=so(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${n.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=so(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${n.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return v({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function uo(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=v(n[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 o={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(o[s.functionResponse.id]=i)}for(let i of n.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 o?t[o[a]]=s:(t.push(s),o[a]=t.length-1)}else t.push(s)}return e}function $r(n){if(n.length===0)return n;let e=n[n.length-1],t=S(e);if(!(t!=null&&t.length))return n;let o=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=n.at(-2);if(r){let c=E(r);if(c){for(let l of c)if(l.id&&o.has(l.id))return n}}let i=-1;for(let c=n.length-2;c>=0;c--){let l=n[c],u=E(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let d=new Set(u.map(p=>p.id).filter(p=>!!p));if(!Array.from(o).every(p=>d.has(p)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(o).join(", ")}`);o=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(o).join(", ")}`);let s=[];for(let c=i+1;c<n.length-1;c++){let l=n[c],u=S(l);u&&u.some(f=>f.id&&o.has(f.id))&&s.push(l)}s.push(n[n.length-1]);let a=n.slice(0,i+1);return a.push(uo(s)),a}function qr(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=S(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,o)}let t=[];for(let o of n){if(S(o).length>0)continue;let r=E(o);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(o),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(n[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>n[c]);t.push(uo(a))}}else t.push(o)}return t}function so(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}async function Ft(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!d)throw new Error(`Artifact ${f} not found.`);return String(d)}if(!jr(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(u)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=n.matchAll(r);for(let c of a){i.push(n.slice(s,c.index));let l=await o(c);i.push(l),s=c.index+c[0].length}return i.push(n.slice(s)),i.join("")}var Ur=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function fo(n){return n===""||n===void 0?!1:Ur.test(n)}var zr=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function jr(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?fo(n):zr.includes(e[0]+":")?fo(e[1]):!1}var ze=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(ze||{});function po(n={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Vr(n.maxLlmCalls||500),...n}}function Vr(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return n<=0&&g.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."),n}var mo="adk_agent_name";async function go(n,e){return n instanceof b?[n]:await n.getTools(e)}var $t=class extends k{async*runAsync(e,t){var r;let o=e.agent;A(o)&&(t.model=o.canonicalModel.model,t.config={...(r=o.generateContentConfig)!=null?r:{}},o.outputSchema&&Zn(t,o.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))}},Kr=new $t,qt=class extends k{async*runAsync(e,t){let o=e.agent,r=[`You are an agent. Your internal name is "${o.name}".`];o.description&&r.push(`The description about you is "${o.description}"`),xe(t,r)}},Jr=new qt,Ut=class extends k{async*runAsync(e,t){let o=e.agent;if(!(o instanceof q)||!(o.rootAgent instanceof q))return;let r=o.rootAgent;if(A(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new T(e)),a=i;s&&(a=await Ft(i,new T(e))),xe(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=await o.canonicalInstruction(new T(e)),a=i;s&&(a=await Ft(i,new T(e))),xe(t,[a])}}},Yr=new Ut,zt=class{async*runAsync(e,t){let o=e.agent;!o||!A(o)||(o.includeContents==="default"?t.contents=Nt(e.session.events,o.name,e.branch):t.contents=co(e.session.events,o.name,e.branch))}},Zr=new zt,jt=class extends k{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new B({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:Gt.z.object({agentName:Gt.z.string().describe("the agent name to transfer to.")}),execute:function(t,o){if(!o)throw new Error("toolContext is required.");return o.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,o){if(!(t.agent instanceof q))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;xe(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new F({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:o})}buildTargetAgentsInfo(t){return`
|
|
18
18
|
Agent name: ${t.name}
|
|
19
19
|
Agent description: ${t.description}
|
|
20
|
-
`}buildTargetAgentsInstructions(t,
|
|
20
|
+
`}buildTargetAgentsInstructions(t,o){let r=`
|
|
21
21
|
You have a list of other agents to transfer to:
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${o.map(this.buildTargetAgentsInfo).join(`
|
|
24
24
|
`)}
|
|
25
25
|
|
|
26
26
|
If you are the best to answer the question according to your description, you
|
|
@@ -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
|
|
37
|
+
`),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!A(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},Hr=new jt,Vt=class extends k{async*runAsync(e){let t=e.agent;if(!A(t))return;let o=e.session.events;if(!o||o.length===0)return;let r={},i=-1;for(let s=o.length-1;s>=0;s--){let a=o[s];if(a.author!=="user")continue;let c=S(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==se)continue;l=!0;let f=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?f=JSON.parse(u.response.response):u.response&&(f=new $({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(r[u.id]=f)}if(l){i=s;break}}if(Object.keys(r).length!==0)for(let s=i-1;s>=0;s--){let a=o[s],c=E(a);if(!c)continue;let l={},u={};for(let p of c){if(!p.id||!(p.id in r))continue;let x=p.args;if(!x||!("originalFunctionCall"in x))continue;let h=x.originalFunctionCall;h.id&&(l[h.id]=r[p.id],u[h.id]=h)}if(Object.keys(l).length===0)continue;for(let p=o.length-1;p>i;p--){let x=o[p],h=S(x);if(h){for(let y of h)y.id&&y.id in l&&(delete l[y.id],delete u[y.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=await t.canonicalTools(new T(e)),d=Object.fromEntries(f.map(p=>[p.name,p])),m=await Ne({invocationContext:e,functionCalls:Object.values(u),toolsDict:d,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l});m&&(yield m);return}}},Wr=new Vt,Kt=class extends k{async*runAsync(e,t){if(e.agent instanceof q&&e.agent.codeExecutor){for await(let o of Qr(e,t))yield o;if(De(e.agent.codeExecutor))for(let o of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];Vn(o,r,e.agent.codeExecutor.executionResultDelimiters)}}}},je={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Xr=`
|
|
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
|
-
`,
|
|
75
|
-
Available file: \`${
|
|
76
|
-
`;let
|
|
77
|
-
${
|
|
74
|
+
`,Jt=class{async*runAsync(e,t){if(!t.partial)for await(let o of ei(e,t))yield o}},oc=new Jt;async function*Qr(n,e){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!De(o))return;if(he(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new ve(new C(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=ti(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=ni(c);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},St(l)]};e.contents.push((0,Dt.cloneDeep)(u)),yield v({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=vo(n,r),d=await o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([c.name]);let m=await xo(n,r,d);yield m,e.contents.push((0,Dt.cloneDeep)(m.content))}}async function*ei(n,e){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!De(o)||!e||!e.content||he(o))return;let r=new ve(new C(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=zn(i,o.codeBlockDelimiters);if(!s)return;yield v({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=vo(n,r),c=await o.executeCode({invocationContext:n,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await xo(n,r,c),e.content=void 0}function ti(n,e){var r;let t=n.getInputFiles(),o=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||!je[l])continue;let u=`data_${i+1}_${a+1}${je[l].extension}`;c.text=`
|
|
75
|
+
Available file: \`${u}\`
|
|
76
|
+
`;let f={name:u,content:Tn(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function vo(n,e){var r;let t=n.agent;if(!A(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function xo(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[jn(t)]},r=P({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(n.invocationId):e.resetErrorCount(n.invocationId);for(let i of t.outputFiles){let s=await n.artifactService.saveArtifact({appName:n.appName||"",userId:n.userId||"",sessionId:n.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return v({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function ni(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!je[n.mimeType])return;let t=e(n.name),o=je[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return`
|
|
77
|
+
${Xr}
|
|
78
78
|
|
|
79
79
|
# Load the dataframe.
|
|
80
|
-
${t} = ${
|
|
80
|
+
${t} = ${o}
|
|
81
81
|
|
|
82
82
|
# Use \`explore_df\` to guide my analysis.
|
|
83
83
|
explore_df(${t})
|
|
84
|
-
`}var wr=new Bt,Ft=Symbol.for("google.adk.llmAgent");function E(o){return typeof o=="object"&&o!==null&&Ft in o&&o[Ft]===!0}var Yn,Hn,U=class o extends(Hn=k,Yn=Ft,Hn){constructor(t){var r,i,s,a,c,l,f,u,d;super(t);this[Yn]=!0;if(this.model=t.model,this.instruction=(r=t.instruction)!=null?r:"",this.globalInstruction=(i=t.globalInstruction)!=null?i:"",this.tools=(s=t.tools)!=null?s:[],this.generateContentConfig=t.generateContentConfig,this.disallowTransferToParent=(a=t.disallowTransferToParent)!=null?a:!1,this.disallowTransferToPeers=(c=t.disallowTransferToPeers)!=null?c:!1,this.includeContents=(l=t.includeContents)!=null?l:"default",this.inputSchema=t.inputSchema,this.outputSchema=t.outputSchema,this.outputKey=t.outputKey,this.beforeModelCallback=t.beforeModelCallback,this.afterModelCallback=t.afterModelCallback,this.beforeToolCallback=t.beforeToolCallback,this.afterToolCallback=t.afterToolCallback,this.codeExecutor=t.codeExecutor,this.requestProcessors=(f=t.requestProcessors)!=null?f:[vr,yr,xr,Tr,Ar,wr],this.responseProcessors=(u=t.responseProcessors)!=null?u:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(Er),t.generateContentConfig){if(t.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(t.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(t.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};if(this.outputSchema){if((!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(m.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(Me(this.model))return this.model;if(typeof this.model=="string"&&this.model)return J.newLlm(this.model);let t=this.parentAgent;for(;t;){if(E(t))return t.canonicalModel;t=t.parentAgent}throw new Error(`No model found for ${this.name}.`)}async canonicalInstruction(t){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(t),requireStateInjection:!1}}async canonicalGlobalInstruction(t){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(t),requireStateInjection:!1}}async canonicalTools(t){let n=[];for(let r of this.tools){let i=await zn(r,t);n.push(...i)}return n}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){m.debug(`Skipping output save for agent ${this.name}: event authored by ${t.author}`);return}if(!this.outputKey){m.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!z(t)){m.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){m.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let n=t.content.parts.map(a=>a.text?a.text:"").join(""),r=n;if(this.outputSchema){if(!n.trim())return;try{r=JSON.parse(n)}catch(a){m.error(`Error parsing output for agent ${this.name}`,a)}}t.actions.stateDelta[this.outputKey]=r}async*runAsyncImpl(t){for(;;){let n;for await(let r of this.runOneStepAsync(t))n=r,this.maybeSaveOutputToState(r),yield r;if(!n||z(n))break;if(n.partial){m.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(t){for await(let n of this.runLiveFlow(t))this.maybeSaveOutputToState(n),yield n;t.endInvocation}async*runLiveFlow(t){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(t){let n={contents:[],toolsDict:{},liveConnectConfig:{}};for(let i of this.requestProcessors)for await(let s of i.runAsync(t,n))yield s;for(let i of this.tools){let s=new F({invocationContext:t}),a=await zn(i,new S(t));for(let c of a)await c.processLlmRequest({toolContext:s,llmRequest:n})}if(t.endInvocation)return;let r=y({invocationId:t.invocationId,author:this.name,branch:t.branch});for await(let i of this.callLlmAsync(t,n,r))for await(let s of this.postprocess(t,n,i,r))r.id=nt(),r.timestamp=new Date().getTime(),yield s}async*postprocess(t,n,r,i){var u;for(let d of this.responseProcessors)for await(let p of d.runAsync(t,r))yield p;if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=y({...i,...r});if(s.content){let d=T(s);d!=null&&d.length&&(dn(s),s.longRunningToolIds=Array.from(mn(d,n.toolsDict)))}if(yield s,!((u=T(s))!=null&&u.length))return;let a=await gn({invocationContext:t,functionCallEvent:s,toolsDict:n.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a)return;let c=ft(t,a);c&&(yield c);let l=dt({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});l&&(yield l),yield a;let f=a.actions.transferToAgent;if(f){let d=this.getAgentByName(t,f);for await(let p of d.runAsync(t))yield p}}getAgentByName(t,n){let i=t.agent.rootAgent.findAgent(n);if(!i)throw new Error(`Agent ${n} not found in the agent tree.`);return i}async*callLlmAsync(t,n,r){var a,c,l,f,u;let i=await this.handleBeforeModelCallback(t,n,r);if(i){yield i;return}(a=n.config)!=null||(n.config={}),(l=(c=n.config).labels)!=null||(c.labels={}),n.config.labels[Zn]||(n.config.labels[Zn]=this.name);let s=this.canonicalModel;if((f=t.runConfig)!=null&&f.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let d=s.generateContentAsync(n,((u=t.runConfig)==null?void 0:u.streamingMode)==="sse");for await(let p of this.runAndHandleError(d,t,n,r)){let g=await this.handleAfterModelCallback(t,p,r);yield g!=null?g:p}}}async handleBeforeModelCallback(t,n,r){let i=new w({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:n});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:n});if(c)return c}}async handleAfterModelCallback(t,n,r){let i=new w({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:n});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:n});if(c)return c}}async*runAndHandleError(t,n,r,i){try{for await(let s of t)yield s}catch(s){let a=new w({invocationContext:n,eventActions:i.actions});if(s instanceof Error){let c=await n.pluginManager.runOnModelErrorCallback({callbackContext:a,llmRequest:r,error:s});if(c)yield c;else{let l=JSON.parse(s.message);yield{errorCode:String(l.error.code),errorMessage:l.error.message}}}else throw m.error("Unknown error during response generation",s),s}}};var Dt=Symbol.for("google.adk.loopAgent");function eo(o){return typeof o=="object"&&o!==null&&Dt in o&&o[Dt]===!0}var Wn,Jn,De=class extends(Jn=k,Wn=Dt,Jn){constructor(t){var n;super(t);this[Wn]=!0;this.maxIterations=(n=t.maxIterations)!=null?n:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(t){let n=0;for(;n<this.maxIterations;){for(let r of this.subAgents){let i=!1;for await(let s of r.runAsync(t))yield s,s.actions.escalate&&(i=!0);if(i)return}n++}}async*runLiveImpl(t){throw new Error("This is not supported yet for LoopAgent.")}};var Gt=Symbol.for("google.adk.parallelAgent");function oo(o){return typeof o=="object"&&o!==null&&Gt in o&&o[Gt]===!0}var to,no,Ge=class extends(no=k,to=Gt,no){constructor(){super(...arguments);this[to]=!0}async*runAsyncImpl(t){let n=this.subAgents.map(r=>r.runAsync(kr(this,r,t)));for await(let r of Lr(n))yield r}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function kr(o,e,t){let n=new B(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Lr(o){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=await Promise.race(e.values());if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}}var $t="task_completed",qt=Symbol.for("google.adk.sequentialAgent");function so(o){return typeof o=="object"&&o!==null&&qt in o&&o[qt]===!0}var ro,io,$e=class extends(io=k,ro=qt,io){constructor(){super(...arguments);this[ro]=!0}async*runAsyncImpl(t){for(let n of this.subAgents)for await(let r of n.runAsync(t))yield r}async*runLiveImpl(t){for(let n of this.subAgents)E(n)&&((await n.canonicalTools(new S(t))).some(s=>s.name===$t)||(n.tools.push(new N({name:$t,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),n.instruction+=`If you finished the user's request according to its description, call the ${$t} function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.`));for(let n of this.subAgents)for await(let r of n.runLive(t))yield r}};var se=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=qe(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=qe(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=qe(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=qe(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}};function qe(o,e,t,n){return _r(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function _r(o){return o.startsWith("user:")}var Ut=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(Ut||{});var jt=Symbol.for("google.adk.baseExampleProvider");function co(o){return typeof o=="object"&&o!==null&&jt in o&&o[jt]===!0}var ao;ao=jt;var Ue=class{constructor(){this[ao]=!0}};var j=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=lo(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=lo(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),f=Or(l);if(!f.size)continue;n.some(d=>f.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:Mr(c.timestamp)})}return r}};function lo(o,e){return`${o}/${e}`}function Or(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Mr(o){return new Date(o).toISOString()}var K=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var je=class extends K{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${z(t)}`);let n=T(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=P(t);if(r.length>0){let i=r.map(s=>s.name);this.log(` Function Responses: ${i}`)}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...t.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`),t.invocationContext.branch&&this.log(` Branch: ${t.invocationContext.branch}`)}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(n=t.model)!=null?n:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Result: ${this.formatArgs(r)}`)}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${n}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;m.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let n=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),n.push(`text: '${i}'`)}else r.functionCall?n.push(`function_call: ${r.functionCall.name}`):r.functionResponse?n.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var ae=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),m.info(`Plugin '${e.name}' registered.`)}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return m.debug(`Plugin '${r.name}' returned a value for callback '${n}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${n}' callback: ${i}`;throw m.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,n=>n.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,n=>n.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:n}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:n}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,n=>n.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,n=>n.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}),"onToolErrorCallback")}};var Vt="adk_request_confirmation",Kt="orcas_tool_call_security_check_states",uo="This tool call needs external confirmation before completion.",Zt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Zt||{}),Ce=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Ke=class extends K{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ce}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:uo};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(Kt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Kt))!=null?i:{};r[n]=t,e.state.set(Kt,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:uo};case"ALLOW":return;default:return}}};function fo(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Vt&&e.push(t.functionCall);return e}var zt=require("lodash-es");var ve=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[n,r]of Object.entries(t.actions.stateDelta))n.startsWith(C.TEMP_PREFIX)||(e.state[n]=r)}};function ye(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var V=class extends ve{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=ye({id:i||ee(),appName:t,userId:n,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][n]||(this.sessions[t][n]={}),this.sessions[t][n][s.id]=s,Promise.resolve(this.mergeState(t,n,(0,zt.cloneDeep)(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=(0,zt.cloneDeep)(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(ye({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{m.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(C.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(C.USER_PREFIX,"")]=n.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:n}),c.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[C.USER_PREFIX+i]=this.userState[t][n][i];return r}};var po=require("@google/genai"),mo=require("@opentelemetry/api");var Z=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ae((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync(e){var c;let{userId:t,sessionId:n,stateDelta:r}=e,i=Vn(e.runConfig),s=e.newMessage,a=mo.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let l=await this.sessionService.getSession({appName:this.appName,userId:t,sessionId:n});if(!l)throw this.appName?new Error(`Session not found: ${n}`):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&E(this.agent)){let p=this.agent.canonicalModel.model;if(!re(p))throw new Error(`CFC is not supported for model: ${p} in agent: ${this.agent.name}`);fe(this.agent.codeExecutor)||(this.agent.codeExecutor=new ie)}let f=new B({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:rn(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),u=await this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:f});if(u&&(s=u),s){if(!((c=s.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(f.invocationId,l.userId,l.id,s),await this.sessionService.appendEvent({session:l,event:y({invocationId:f.invocationId,author:"user",actions:r?_({stateDelta:r}):void 0,content:s})})}f.agent=this.determineAgentForResumption(l,this.agent);let d=await this.pluginManager.runBeforeRunCallback({invocationContext:f});if(d){let p=y({invocationId:f.invocationId,author:"model",content:d});await this.sessionService.appendEvent({session:l,event:p}),yield p}else for await(let p of f.agent.runAsync(f)){p.partial||await this.sessionService.appendEvent({session:l,event:p});let g=await this.pluginManager.runOnEventCallback({invocationContext:f,event:p});g?yield g:yield p}await this.pluginManager.runAfterRunCallback({invocationContext:f})}finally{a.end()}}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=(0,po.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Br(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){m.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){m.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!E(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Br(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let c=o[a],l=T(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var Ve=class extends Z{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new se,sessionService:new V,memoryService:new j})}};var xe=require("@google/genai");var Ze=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(e){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var Yt=Symbol.for("google.adk.agentTool");function Co(o){return typeof o=="object"&&o!==null&&Yt in o&&o[Yt]===!0}var go,ho,ze=class extends(ho=I,go=Yt,ho){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[go]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(E(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:xe.Type.OBJECT,properties:{request:{type:xe.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let n=E(this.agent)&&this.agent.outputSchema;t.response=n?{type:xe.Type.OBJECT}:{type:xe.Type.STRING}}return t}async runAsync({args:t,toolContext:n}){var u,d;this.skipSummarization&&(n.actions.skipSummarization=!0);let i={role:"user",parts:[{text:E(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new Z({appName:this.agent.name,agent:this.agent,artifactService:new Ze(n),sessionService:new V,memoryService:new j,credentialService:n.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:n.state.toRecord()}),c;for await(let p of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i}))p.actions.stateDelta&&n.state.update(p.actions.stateDelta),c=p;if(!((d=(u=c==null?void 0:c.content)==null?void 0:u.parts)!=null&&d.length))return"";let l=E(this.agent)&&this.agent.outputSchema,f=c.content.parts.map(p=>p.text).filter(p=>p).join(`
|
|
85
|
-
`);return l?JSON.parse(
|
|
84
|
+
`}var oi=new Kt,Yt=Symbol.for("google.adk.llmAgent");function A(n){return typeof n=="object"&&n!==null&&Yt in n&&n[Yt]===!0}var ho,Co,q=class n extends(Co=I,ho=Yt,Co){constructor(t){var r,i,s,a,c,l,u,f,d;super(t);this[ho]=!0;if(this.model=t.model,this.instruction=(r=t.instruction)!=null?r:"",this.globalInstruction=(i=t.globalInstruction)!=null?i:"",this.tools=(s=t.tools)!=null?s:[],this.generateContentConfig=t.generateContentConfig,this.disallowTransferToParent=(a=t.disallowTransferToParent)!=null?a:!1,this.disallowTransferToPeers=(c=t.disallowTransferToPeers)!=null?c:!1,this.includeContents=(l=t.includeContents)!=null?l:"default",this.inputSchema=t.inputSchema,this.outputSchema=t.outputSchema,this.outputKey=t.outputKey,this.beforeModelCallback=t.beforeModelCallback,this.afterModelCallback=t.afterModelCallback,this.beforeToolCallback=t.beforeToolCallback,this.afterToolCallback=t.afterToolCallback,this.codeExecutor=t.codeExecutor,this.requestProcessors=(u=t.requestProcessors)!=null?u:[Kr,Jr,Yr,Wr,Zr,oi],this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(Hr),t.generateContentConfig){if(t.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(t.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(t.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};if(this.outputSchema){if((!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(g.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(Ge(this.model))return this.model;if(typeof this.model=="string"&&this.model)return ee.newLlm(this.model);let t=this.parentAgent;for(;t;){if(A(t))return t.canonicalModel;t=t.parentAgent}throw new Error(`No model found for ${this.name}.`)}async canonicalInstruction(t){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(t),requireStateInjection:!1}}async canonicalGlobalInstruction(t){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(t),requireStateInjection:!1}}async canonicalTools(t){let o=[];for(let r of this.tools){let i=await go(r,t);o.push(...i)}return o}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return n.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return n.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return n.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return n.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){g.debug(`Skipping output save for agent ${this.name}: event authored by ${t.author}`);return}if(!this.outputKey){g.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!K(t)){g.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){g.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let o=t.content.parts.map(a=>a.text?a.text:"").join(""),r=o;if(this.outputSchema){if(!o.trim())return;try{r=JSON.parse(o)}catch(a){g.error(`Error parsing output for agent ${this.name}`,a)}}t.actions.stateDelta[this.outputKey]=r}async*runAsyncImpl(t){for(;;){let o;for await(let r of this.runOneStepAsync(t))o=r,this.maybeSaveOutputToState(r),yield r;if(!o||K(o))break;if(o.partial){g.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(t){for await(let o of this.runLiveFlow(t))this.maybeSaveOutputToState(o),yield o;t.endInvocation}async*runLiveFlow(t){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(t){let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let a of this.requestProcessors)for await(let c of a.runAsync(t,o))yield c;for(let a of this.tools){let c=new F({invocationContext:t}),l=await go(a,new T(t));for(let u of l)await u.processLlmRequest({toolContext:c,llmRequest:o})}if(t.endInvocation)return;let r=v({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=O.startSpan("call_llm"),s=Ve.trace.setSpan(Ve.context.active(),i);yield*J(s,this,async function*(){for await(let a of this.callLlmAsync(t,o,r))for await(let c of this.postprocess(t,o,a,r))r.id=ut(),r.timestamp=new Date().getTime(),yield c}),i.end()}async*postprocess(t,o,r,i){var f;for(let d of this.responseProcessors)for await(let m of d.runAsync(t,r))yield m;if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=v({...i,...r});if(s.content){let d=E(s);d!=null&&d.length&&(On(s),s.longRunningToolIds=Array.from(Bn(d,o.toolsDict)))}if(yield s,!((f=E(s))!=null&&f.length))return;let a=await Nn({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a)return;let c=At(t,a);c&&(yield c);let l=yt({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});l&&(yield l),yield a;let u=a.actions.transferToAgent;if(u){let d=this.getAgentByName(t,u);for await(let m of d.runAsync(t))yield m}}getAgentByName(t,o){let i=t.agent.rootAgent.findAgent(o);if(!i)throw new Error(`Agent ${o} not found in the agent tree.`);return i}async*callLlmAsync(t,o,r){var a,c,l,u,f;let i=await this.handleBeforeModelCallback(t,o,r);if(i){yield i;return}(a=o.config)!=null||(o.config={}),(l=(c=o.config).labels)!=null||(c.labels={}),o.config.labels[mo]||(o.config.labels[mo]=this.name);let s=this.canonicalModel;if((u=t.runConfig)!=null&&u.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let d=s.generateContentAsync(o,((f=t.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let m of this.runAndHandleError(d,t,o,r)){yn({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:m});let p=await this.handleAfterModelCallback(t,m,r);yield p!=null?p:m}}}async handleBeforeModelCallback(t,o,r){let i=new R({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:o});if(c)return c}}async handleAfterModelCallback(t,o,r){let i=new R({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:o});if(c)return c}}async*runAndHandleError(t,o,r,i){try{for await(let s of t)yield s}catch(s){let a=new R({invocationContext:o,eventActions:i.actions});if(s instanceof Error){let c=await o.pluginManager.runOnModelErrorCallback({callbackContext:a,llmRequest:r,error:s});if(c)yield c;else{let l=JSON.parse(s.message);yield{errorCode:String(l.error.code),errorMessage:l.error.message}}}else throw g.error("Unknown error during response generation",s),s}}};var Zt=Symbol.for("google.adk.loopAgent");function Eo(n){return typeof n=="object"&&n!==null&&Zt in n&&n[Zt]===!0}var Ao,yo,Ke=class extends(yo=I,Ao=Zt,yo){constructor(t){var o;super(t);this[Ao]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(t){let o=0;for(;o<this.maxIterations;){for(let r of this.subAgents){let i=!1;for await(let s of r.runAsync(t))yield s,s.actions.escalate&&(i=!0);if(i)return}o++}}async*runLiveImpl(t){throw new Error("This is not supported yet for LoopAgent.")}};var Ht=Symbol.for("google.adk.parallelAgent");function So(n){return typeof n=="object"&&n!==null&&Ht in n&&n[Ht]===!0}var To,bo,Je=class extends(bo=I,To=Ht,bo){constructor(){super(...arguments);this[To]=!0}async*runAsyncImpl(t){let o=this.subAgents.map(r=>r.runAsync(ri(this,r,t)));for await(let r of ii(o))yield r}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function ri(n,e,t){let o=new M(t),r=`${n.name}.${e.name}`;return o.branch=o.branch?`${o.branch}.${r}`:r,o}async function*ii(n){let e=new Map;for(let[t,o]of n.entries()){let r=o.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:o}=await Promise.race(e.values());if(t.done){e.delete(o);continue}yield t.value;let r=n[o].next().then(i=>({result:i,index:o}));e.set(o,r)}}var Wt="task_completed",Xt=Symbol.for("google.adk.sequentialAgent");function wo(n){return typeof n=="object"&&n!==null&&Xt in n&&n[Xt]===!0}var Ro,Io,Ye=class extends(Io=I,Ro=Xt,Io){constructor(){super(...arguments);this[Ro]=!0}async*runAsyncImpl(t){for(let o of this.subAgents)for await(let r of o.runAsync(t))yield r}async*runLiveImpl(t){for(let o of this.subAgents)A(o)&&((await o.canonicalTools(new T(t))).some(s=>s.name===Wt)||(o.tools.push(new B({name:Wt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),o.instruction+=`If you finished the user's request according to its description, call the ${Wt} 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 o of this.subAgents)for await(let r of o.runLive(t))yield r}};var ue=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:o,filename:r,artifact:i}){let s=Ze(e,t,o,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:o,filename:r,version:i}){let s=Ze(e,t,o,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:o}){let r=`${e}/${t}/${o}/`,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:o,filename:r}){let i=Ze(e,t,o,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=Ze(e,t,o,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(n,e,t,o){return si(o)?`${n}/${e}/user/${o}`:`${n}/${e}/${t}/${o}`}function si(n){return n.startsWith("user:")}var Qt=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(Qt||{});var en=Symbol.for("google.adk.baseExampleProvider");function ko(n){return typeof n=="object"&&n!==null&&en in n&&n[en]===!0}var Po;Po=en;var He=class{constructor(){this[Po]=!0}};var U=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Lo(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(o=>{var r,i,s;return((s=(i=(r=o.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=Lo(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),u=ai(l);if(!u.size)continue;o.some(d=>u.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:ci(c.timestamp)})}return r}};function Lo(n,e){return`${n}/${e}`}function ai(n){return new Set([...n.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function ci(n){return new Date(n).toISOString()}var z=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var We=class extends z{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var o;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: ${(o=e.agent.name)!=null?o:"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({event:e}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${e.id}`),this.log(` Author: ${e.author}`),this.log(` Content: ${this.formatContent(e.content)}`),this.log(` Final Response: ${K(e)}`);let t=E(e);if(t.length>0){let r=t.map(i=>i.name);this.log(` Function Calls: ${r}`)}let o=S(e);if(o.length>0){let r=o.map(i=>i.name);this.log(` Function Responses: ${r}`)}e.longRunningToolIds&&e.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...e.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({callbackContext:e}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${e.agentName}`),this.log(` Invocation ID: ${e.invocationId}`),e.invocationContext.branch&&this.log(` Branch: ${e.invocationContext.branch}`)}async afterAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${e.agentName}`),this.log(` Invocation ID: ${e.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var o;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(o=t.model)!=null?o:"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:o}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${o.agentName}`),this.log(` Function Call ID: ${o.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolContext:t,result:o}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${t.agentName}`),this.log(` Function Call ID: ${t.functionCallId}`),this.log(` Result: ${this.formatArgs(o)}`)}async onModelErrorCallback({callbackContext:e,error:t}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${t}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${o.agentName}`),this.log(` Function Call ID: ${o.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;g.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let o=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),o.push(`text: '${i}'`)}else r.functionCall?o.push(`function_call: ${r.functionCall.name}`):r.functionResponse?o.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?o.push("code_execution_result"):o.push("other_part");return o.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let o=JSON.stringify(e);return o.length>t&&(o=o.substring(0,t)+"...}"),o}};var fe=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),g.info(`Plugin '${e.name}' registered.`)}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,o){for(let r of e)try{let i=await t(r);if(i!==void 0)return g.debug(`Plugin '${r.name}' returned a value for callback '${o}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${o}' callback: ${i}`;throw g.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.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,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:o}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:o}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:o}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:o}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,o=>o.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,o=>o.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}),"onToolErrorCallback")}};var nn="adk_request_confirmation",tn="orcas_tool_call_security_check_states",_o="This tool call needs external confirmation before completion.",on=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(on||{}),ye=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Xe=class extends z{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new ye}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){let r=this.getToolCallCheckState(o);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o});if(r==="CONFIRM"){if(!o.toolConfirmation)return{partial:_o};if(this.setToolCallCheckState(o,o.toolConfirmation),!o.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};o.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(tn))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(tn))!=null?i:{};r[o]=t,e.state.set(tn,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(o,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return o.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:_o};case"ALLOW":return;default:return}}};function Oo(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===nn&&e.push(t.functionCall);return e}var rn=require("lodash-es");var Ee=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[o,r]of Object.entries(t.actions.stateDelta))o.startsWith(C.TEMP_PREFIX)||(e.state[o]=r)}};function Te(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}var j=class extends Ee{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:o,state:r,sessionId:i}){let s=Te({id:i||oe(),appName:t,userId:o,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][o]||(this.sessions[t][o]={}),this.sessions[t][o][s.id]=s,Promise.resolve(this.mergeState(t,o,(0,rn.cloneDeep)(s)))}getSession({appName:t,userId:o,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][o]||!this.sessions[t][o][r])return Promise.resolve(void 0);let s=this.sessions[t][o][r],a=(0,rn.cloneDeep)(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,o,a))}listSessions({appName:t,userId:o}){if(!this.sessions[t]||!this.sessions[t][o])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][o]))r.push(Te({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:o,sessionId:r}){await this.getSession({appName:t,userId:o,sessionId:r})&&delete this.sessions[t][o][r]}async appendEvent({session:t,event:o}){await super.appendEvent({session:t,event:o}),t.lastUpdateTime=o.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{g.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),o;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),o;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),o;if(o.actions&&o.actions.stateDelta)for(let l of Object.keys(o.actions.stateDelta))l.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(C.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(C.USER_PREFIX,"")]=o.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:o}),c.lastUpdateTime=o.timestamp,o}mergeState(t,o,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][o])return r;for(let i of Object.keys(this.userState[t][o]))r.state[C.USER_PREFIX+i]=this.userState[t][o][i];return r}};var Mo=require("@google/genai"),Qe=require("@opentelemetry/api");var V=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new fe((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync(e){let{userId:t,sessionId:o,stateDelta:r}=e,i=po(e.runConfig),s=e.newMessage,a=O.startSpan("invocation"),c=Qe.trace.setSpan(Qe.context.active(),a);try{yield*J(c,this,async function*(){var d;let l=await this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o});if(!l)throw this.appName?new Error(`Session not found: ${o}`):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&A(this.agent)){let m=this.agent.canonicalModel.model;if(!ce(m))throw new Error(`CFC is not supported for model: ${m} in agent: ${this.agent.name}`);he(this.agent.codeExecutor)||(this.agent.codeExecutor=new le)}let u=new M({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:bn(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u});if(f&&(s=f),s){if(!((d=s.parts)!=null&&d.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(u.invocationId,l.userId,l.id,s),await this.sessionService.appendEvent({session:l,event:v({invocationId:u.invocationId,author:"user",actions:r?P({stateDelta:r}):void 0,content:s})})}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let m=await this.pluginManager.runBeforeRunCallback({invocationContext:u});if(m){let p=v({invocationId:u.invocationId,author:"model",content:m});await this.sessionService.appendEvent({session:l,event:p}),yield p}else{for await(let p of u.agent.runAsync(u)){p.partial||await this.sessionService.appendEvent({session:l,event:p});let x=await this.pluginManager.runOnEventCallback({invocationContext:u,event:p});x?yield x:yield p}await this.pluginManager.runAfterRunCallback({invocationContext:u})}}})}finally{a.end()}}async saveArtifacts(e,t,o,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:o,filename:c,artifact:a}),r.parts[s]=(0,Mo.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let o=li(e.events);if(o&&o.author)return t.findAgent(o.author)||t;for(let r=e.events.length-1;r>=0;r--){g.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){g.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(!A(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function li(n){var o,r,i,s;if(!n.length)return null;let t=(s=(i=(r=(o=n[n.length-1].content)==null?void 0:o.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=n.length-2;a>=0;a--){let c=n[a],l=E(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var et=class extends V{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new ue,sessionService:new j,memoryService:new U})}};var be=require("@google/genai");var tt=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(){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 sn=Symbol.for("google.adk.agentTool");function Fo(n){return typeof n=="object"&&n!==null&&sn in n&&n[sn]===!0}var Bo,No,nt=class extends(No=b,Bo=sn,No){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[Bo]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(A(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:be.Type.OBJECT,properties:{request:{type:be.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=A(this.agent)&&this.agent.outputSchema;t.response=o?{type:be.Type.OBJECT}:{type:be.Type.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,d;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:A(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new V({appName:this.agent.name,agent:this.agent,artifactService:new tt(o),sessionService:new j,memoryService:new U,credentialService:o.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:o.state.toRecord()}),c;for await(let m of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i}))m.actions.stateDelta&&o.state.update(m.actions.stateDelta),c=m;if(!((d=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&d.length))return"";let l=A(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(m=>m.text).filter(m=>m).join(`
|
|
85
|
+
`);return l?JSON.parse(u):u}};var de=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 Se=class extends b{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(){return Promise.resolve()}async processLlmRequest({llmRequest:e}){if(e.model){if(e.config=e.config||{},e.config.tools=e.config.tools||[],Gn(e.model)){if(e.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");e.config.tools.push({googleSearchRetrieval:{}});return}if(Dn(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${e.model}`)}}},Do=new Se;var Go=`
|
|
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.`,ot=class extends B{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Go:e.description=Go.trimStart(),e}};var $o=require("@google-cloud/opentelemetry-cloud-monitoring-exporter"),qo=require("@google-cloud/opentelemetry-cloud-trace-exporter"),Uo=require("@opentelemetry/resource-detector-gcp"),zo=require("@opentelemetry/resources"),jo=require("@opentelemetry/sdk-metrics"),Vo=require("@opentelemetry/sdk-trace-base"),Ko=require("google-auth-library");var ui="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function fi(){try{return await new Ko.GoogleAuth().getProjectId()||void 0}catch{return}}async function di(n={}){let{enableTracing:e=!1,enableMetrics:t=!1}=n,o=await fi();return o?{spanProcessors:e?[new Vo.BatchSpanProcessor(new qo.TraceExporter({projectId:o}))]:[],metricReaders:t?[new jo.PeriodicExportingMetricReader({exporter:new $o.MetricExporter({projectId:o}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(g.warn(ui),{})}function pi(){return(0,zo.detectResources)({detectors:[Uo.gcpDetector]})}var rt=require("@opentelemetry/api"),Jo=require("@opentelemetry/api-logs"),Yo=require("@opentelemetry/exporter-logs-otlp-http"),Zo=require("@opentelemetry/exporter-metrics-otlp-http"),Ho=require("@opentelemetry/exporter-trace-otlp-http"),Wo=require("@opentelemetry/resources"),it=require("@opentelemetry/sdk-logs"),st=require("@opentelemetry/sdk-metrics"),Xo=require("@opentelemetry/sdk-trace-base"),Qo=require("@opentelemetry/sdk-trace-node");function mi(n=[],e){let t=e||gi(),o=[...n,Ci()],r=o.flatMap(a=>a.spanProcessors||[]),i=o.flatMap(a=>a.metricReaders||[]),s=o.flatMap(a=>a.logRecordProcessors||[]);if(r.length>0){let a=new Qo.NodeTracerProvider({resource:t,spanProcessors:r});a.register(),rt.trace.setGlobalTracerProvider(a)}if(i.length>0){let a=new st.MeterProvider({readers:i,resource:t});rt.metrics.setGlobalMeterProvider(a)}if(s.length>0){let a=new it.LoggerProvider({resource:t,processors:s});Jo.logs.setGlobalLoggerProvider(a)}}function gi(){return(0,Wo.detectResources)({detectors:[]})}function hi(){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 Ci(n=hi()){let{enableTracing:e,enableMetrics:t,enableLogging:o}=n;return{spanProcessors:e?[new Xo.BatchSpanProcessor(new Ho.OTLPTraceExporter)]:[],metricReaders:t?[new st.PeriodicExportingMetricReader({exporter:new Zo.OTLPMetricExporter})]:[],logRecordProcessors:o?[new it.BatchLogRecordProcessor(new Yo.OTLPLogExporter)]:[]}}var er=require("@modelcontextprotocol/sdk/client/index.js"),tr=require("@modelcontextprotocol/sdk/client/stdio.js"),nr=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Re=class{constructor(e){this.connectionParams=e}async createSession(){var t;let e=new er.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new tr.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":{let o=(t=this.connectionParams.transportOptions)!=null?t:{};!o.requestInit&&this.connectionParams.header!==void 0&&(o.requestInit={headers:this.connectionParams.header}),await e.connect(new nr.StreamableHTTPClientTransport(new URL(this.connectionParams.url),o));break}default:{let o=this.connectionParams;break}}return e}};var L=require("@google/genai"),te=require("zod");var qu=te.z.object({type:te.z.literal("object"),properties:te.z.record(te.z.string(),te.z.unknown()).optional(),required:te.z.string().array().optional()});function vi(n){if(!n)return L.Type.TYPE_UNSPECIFIED;switch(n.toLowerCase()){case"text":case"string":return L.Type.STRING;case"number":return L.Type.NUMBER;case"boolean":return L.Type.BOOLEAN;case"integer":return L.Type.INTEGER;case"array":return L.Type.ARRAY;case"object":return L.Type.OBJECT;default:return L.Type.TYPE_UNSPECIFIED}}function an(n){if(!n)return;function e(t){if(!t.type&&t.anyOf&&Array.isArray(t.anyOf)){let i=t.anyOf.find(s=>{let a=s.type;return a!=="null"&&a!=="NULL"});i&&(t=i)}t.type||(t.properties||t.$ref?t.type="object":t.items&&(t.type="array"));let o=vi(t.type),r={type:o,description:t.description};if(o===L.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 o===L.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(n)}var Ie=class extends b{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){return{name:this.mcpTool.name,description:this.mcpTool.description,parameters:an(this.mcpTool.inputSchema),response:an(this.mcpTool.outputSchema)}}async runAsync(e){let t=await this.mcpSessionManager.createSession(),o={};return o.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(o.params)}};var cn=class extends de{constructor(e,t=[]){super(t),this.mcpSessionManager=new Re(e)}async getTools(){let t=await(await this.mcpSessionManager.createSession()).listTools();g.debug(`number of tools: ${t.tools.length}`);for(let o of t.tools)g.debug(`tool: ${o.name}`);return t.tools.map(o=>new Ie(o,this.mcpSessionManager))}async close(){}};0&&(module.exports={ActiveStreamingTool,AgentTool,AuthCredentialTypes,BaseAgent,BaseCodeExecutor,BaseExampleProvider,BaseLlm,BaseLlmRequestProcessor,BaseLlmResponseProcessor,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,CallbackContext,FunctionTool,GOOGLE_SEARCH,GcsArtifactService,Gemini,GoogleLLMVariant,GoogleSearchTool,InMemoryArtifactService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LLMRegistry,LiveRequestQueue,LlmAgent,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,ParallelAgent,PluginManager,PolicyOutcome,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,ReadonlyContext,Runner,SecurityPlugin,SequentialAgent,State,StreamingMode,ToolConfirmation,ToolContext,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,getLogger,hasTrailingCodeExecutionResult,isAgentTool,isBaseAgent,isBaseExampleProvider,isBaseLlm,isBaseTool,isFinalResponse,isFunctionTool,isGemini2OrAbove,isLlmAgent,isLoopAgent,isParallelAgent,isSequentialAgent,maybeSetOtelProviders,setLogLevel,setLogger,stringifyContent,version,zodObjectToSchema});
|
|
88
88
|
/**
|
|
89
89
|
* @license
|
|
90
90
|
* Copyright 2025 Google LLC
|