@google/adk 0.3.0 → 0.5.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/a2a/a2a_event.js +290 -0
- package/dist/cjs/a2a/event_converter_utils.js +201 -0
- package/dist/cjs/a2a/executor_context.js +53 -0
- package/dist/cjs/a2a/metadata_converter_utils.js +125 -0
- package/dist/cjs/a2a/part_converter_utils.js +212 -0
- package/dist/cjs/agents/active_streaming_tool.js +1 -1
- package/dist/cjs/agents/base_agent.js +6 -6
- package/dist/cjs/agents/content_processor_utils.js +1 -1
- package/dist/cjs/{tools/tool_context.js → agents/context.js} +71 -16
- package/dist/cjs/agents/functions.js +4 -3
- package/dist/cjs/agents/instructions.js +1 -1
- package/dist/cjs/agents/invocation_context.js +1 -1
- package/dist/cjs/agents/live_request_queue.js +1 -1
- package/dist/cjs/agents/llm_agent.js +76 -711
- package/dist/cjs/agents/loop_agent.js +1 -1
- package/dist/cjs/agents/parallel_agent.js +1 -1
- package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +132 -0
- package/dist/cjs/agents/{base_llm_processor.js → processors/base_llm_processor.js} +1 -1
- package/dist/cjs/agents/processors/basic_llm_request_processor.js +68 -0
- package/dist/cjs/agents/processors/code_execution_request_processor.js +389 -0
- package/dist/cjs/agents/processors/content_request_processor.js +66 -0
- package/dist/cjs/agents/processors/identity_llm_request_processor.js +54 -0
- package/dist/cjs/agents/processors/instructions_llm_request_processor.js +85 -0
- package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +165 -0
- package/dist/cjs/agents/readonly_context.js +13 -1
- package/dist/cjs/agents/run_config.js +2 -1
- package/dist/cjs/agents/sequential_agent.js +1 -1
- package/dist/cjs/agents/transcription_entry.js +1 -1
- package/dist/cjs/artifacts/base_artifact_service.js +1 -1
- package/dist/cjs/artifacts/file_artifact_service.js +491 -0
- package/dist/cjs/artifacts/gcs_artifact_service.js +127 -48
- package/dist/cjs/artifacts/in_memory_artifact_service.js +54 -6
- package/dist/cjs/artifacts/registry.js +55 -0
- package/dist/cjs/auth/auth_credential.js +1 -1
- package/dist/cjs/auth/auth_handler.js +1 -1
- package/dist/cjs/auth/auth_schemes.js +1 -1
- package/dist/cjs/auth/auth_tool.js +1 -1
- package/dist/cjs/auth/credential_service/base_credential_service.js +1 -1
- package/dist/cjs/auth/credential_service/in_memory_credential_service.js +1 -1
- package/dist/cjs/auth/exchanger/base_credential_exchanger.js +1 -1
- package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +1 -1
- package/dist/cjs/code_executors/base_code_executor.js +1 -1
- package/dist/cjs/code_executors/built_in_code_executor.js +1 -1
- package/dist/cjs/code_executors/code_execution_utils.js +1 -1
- package/dist/cjs/code_executors/code_executor_context.js +1 -1
- package/dist/cjs/common.js +25 -8
- package/dist/cjs/events/event.js +33 -4
- package/dist/cjs/events/event_actions.js +2 -2
- package/dist/cjs/events/structured_events.js +105 -0
- package/dist/cjs/examples/base_example_provider.js +1 -1
- package/dist/cjs/examples/example.js +1 -1
- package/dist/cjs/examples/example_util.js +1 -1
- package/dist/cjs/index.js +24 -17
- package/dist/cjs/index.js.map +4 -4
- package/dist/cjs/index_web.js +1 -1
- package/dist/cjs/memory/base_memory_service.js +1 -1
- package/dist/cjs/memory/in_memory_memory_service.js +1 -1
- package/dist/cjs/memory/memory_entry.js +1 -1
- package/dist/cjs/models/apigee_llm.js +182 -0
- package/dist/cjs/models/base_llm.js +1 -1
- package/dist/cjs/models/base_llm_connection.js +1 -1
- package/dist/cjs/models/gemini_llm_connection.js +1 -1
- package/dist/cjs/models/google_llm.js +70 -51
- package/dist/cjs/models/llm_request.js +1 -1
- package/dist/cjs/models/llm_response.js +3 -1
- package/dist/cjs/models/registry.js +3 -1
- package/dist/cjs/plugins/base_plugin.js +2 -2
- package/dist/cjs/plugins/logging_plugin.js +1 -1
- package/dist/cjs/plugins/plugin_manager.js +1 -1
- package/dist/cjs/plugins/security_plugin.js +1 -1
- package/dist/cjs/runner/in_memory_runner.js +1 -1
- package/dist/cjs/runner/runner.js +33 -2
- package/dist/cjs/sessions/base_session_service.js +53 -3
- package/dist/cjs/sessions/database_session_service.js +367 -0
- package/dist/cjs/sessions/db/operations.js +126 -0
- package/dist/cjs/sessions/db/schema.js +204 -0
- package/dist/cjs/sessions/in_memory_session_service.js +24 -22
- package/dist/cjs/sessions/registry.js +49 -0
- package/dist/cjs/sessions/session.js +1 -1
- package/dist/cjs/sessions/state.js +1 -1
- package/dist/cjs/telemetry/google_cloud.js +1 -1
- package/dist/cjs/telemetry/setup.js +1 -1
- package/dist/cjs/telemetry/tracing.js +1 -1
- package/dist/cjs/tools/agent_tool.js +1 -1
- package/dist/cjs/tools/base_tool.js +4 -1
- package/dist/cjs/tools/base_toolset.js +14 -4
- package/dist/cjs/tools/exit_loop_tool.js +63 -0
- package/dist/cjs/tools/forwarding_artifact_service.js +17 -1
- package/dist/cjs/tools/function_tool.js +1 -1
- package/dist/cjs/tools/google_search_tool.js +1 -1
- package/dist/cjs/tools/long_running_tool.js +1 -1
- package/dist/cjs/tools/mcp/mcp_session_manager.js +1 -1
- package/dist/cjs/tools/mcp/mcp_tool.js +1 -1
- package/dist/cjs/tools/mcp/mcp_toolset.js +10 -6
- package/dist/cjs/tools/tool_confirmation.js +1 -1
- package/dist/cjs/utils/client_labels.js +1 -1
- package/dist/cjs/utils/env_aware_utils.js +10 -1
- package/dist/cjs/utils/gemini_schema_util.js +1 -1
- package/dist/cjs/utils/logger.js +62 -55
- package/dist/cjs/utils/model_name.js +1 -1
- package/dist/cjs/utils/object_notation_utils.js +78 -0
- package/dist/cjs/utils/simple_zod_to_json.js +1 -1
- package/dist/cjs/utils/variant_utils.js +3 -9
- package/dist/cjs/version.js +2 -2
- package/dist/esm/a2a/a2a_event.js +243 -0
- package/dist/esm/a2a/event_converter_utils.js +187 -0
- package/dist/esm/a2a/executor_context.js +23 -0
- package/dist/esm/a2a/metadata_converter_utils.js +90 -0
- package/dist/esm/a2a/part_converter_utils.js +175 -0
- package/dist/esm/agents/base_agent.js +5 -5
- package/dist/esm/{tools/tool_context.js → agents/context.js} +66 -11
- package/dist/esm/agents/functions.js +3 -2
- package/dist/esm/agents/llm_agent.js +69 -720
- package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +101 -0
- package/dist/esm/agents/processors/basic_llm_request_processor.js +37 -0
- package/dist/esm/agents/processors/code_execution_request_processor.js +363 -0
- package/dist/esm/agents/processors/content_request_processor.js +38 -0
- package/dist/esm/agents/processors/identity_llm_request_processor.js +23 -0
- package/dist/esm/agents/processors/instructions_llm_request_processor.js +54 -0
- package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +140 -0
- package/dist/esm/agents/readonly_context.js +12 -0
- package/dist/esm/agents/run_config.js +1 -0
- package/dist/esm/artifacts/file_artifact_service.js +451 -0
- package/dist/esm/artifacts/gcs_artifact_service.js +126 -47
- package/dist/esm/artifacts/in_memory_artifact_service.js +51 -4
- package/dist/esm/artifacts/registry.js +28 -0
- package/dist/esm/common.js +20 -10
- package/dist/esm/events/event.js +29 -2
- package/dist/esm/events/event_actions.js +1 -1
- package/dist/esm/events/structured_events.js +74 -0
- package/dist/esm/index.js +24 -17
- package/dist/esm/index.js.map +4 -4
- package/dist/esm/models/apigee_llm.js +152 -0
- package/dist/esm/models/google_llm.js +67 -49
- package/dist/esm/models/llm_response.js +2 -0
- package/dist/esm/models/registry.js +2 -0
- package/dist/esm/plugins/base_plugin.js +1 -1
- package/dist/esm/runner/runner.js +32 -1
- package/dist/esm/sessions/base_session_service.js +49 -1
- package/dist/esm/sessions/database_session_service.js +353 -0
- package/dist/esm/sessions/db/operations.js +111 -0
- package/dist/esm/sessions/db/schema.js +172 -0
- package/dist/esm/sessions/in_memory_session_service.js +23 -21
- package/dist/esm/sessions/registry.js +25 -0
- package/dist/esm/tools/base_tool.js +3 -0
- package/dist/esm/tools/base_toolset.js +11 -2
- package/dist/esm/tools/exit_loop_tool.js +32 -0
- package/dist/esm/tools/forwarding_artifact_service.js +16 -0
- package/dist/esm/tools/mcp/mcp_toolset.js +9 -5
- package/dist/esm/utils/env_aware_utils.js +8 -0
- package/dist/esm/utils/logger.js +51 -54
- package/dist/esm/utils/object_notation_utils.js +47 -0
- package/dist/esm/utils/variant_utils.js +1 -7
- package/dist/esm/version.js +1 -1
- package/dist/types/a2a/a2a_event.d.ts +122 -0
- package/dist/types/a2a/event_converter_utils.d.ts +20 -0
- package/dist/types/a2a/executor_context.d.ts +33 -0
- package/dist/types/a2a/metadata_converter_utils.d.ts +62 -0
- package/dist/types/a2a/part_converter_utils.d.ts +48 -0
- package/dist/types/agents/base_agent.d.ts +2 -2
- package/dist/types/{tools/tool_context.d.ts → agents/context.d.ts} +43 -8
- package/dist/types/agents/llm_agent.d.ts +19 -42
- package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +18 -0
- package/dist/types/agents/{base_llm_processor.d.ts → processors/base_llm_processor.d.ts} +4 -4
- package/dist/types/agents/processors/basic_llm_request_processor.d.ts +13 -0
- package/dist/types/agents/processors/code_execution_request_processor.d.ts +34 -0
- package/dist/types/agents/processors/content_request_processor.d.ts +13 -0
- package/dist/types/agents/processors/identity_llm_request_processor.d.ts +13 -0
- package/dist/types/agents/processors/instructions_llm_request_processor.d.ts +16 -0
- package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +13 -0
- package/dist/types/agents/readonly_context.d.ts +8 -0
- package/dist/types/agents/run_config.d.ts +6 -0
- package/dist/types/artifacts/base_artifact_service.d.ts +31 -0
- package/dist/types/artifacts/file_artifact_service.d.ts +43 -0
- package/dist/types/artifacts/gcs_artifact_service.d.ts +3 -1
- package/dist/types/artifacts/in_memory_artifact_service.d.ts +5 -2
- package/dist/types/artifacts/registry.d.ts +7 -0
- package/dist/types/auth/credential_service/base_credential_service.d.ts +3 -3
- package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +3 -3
- package/dist/types/common.d.ts +15 -6
- package/dist/types/events/event.d.ts +15 -1
- package/dist/types/events/event_actions.d.ts +1 -1
- package/dist/types/events/structured_events.d.ts +106 -0
- package/dist/types/index.d.ts +5 -1
- package/dist/types/models/apigee_llm.d.ts +59 -0
- package/dist/types/models/google_llm.d.ts +5 -2
- package/dist/types/models/llm_response.d.ts +5 -1
- package/dist/types/plugins/base_plugin.d.ts +12 -13
- package/dist/types/plugins/logging_plugin.d.ts +9 -10
- package/dist/types/plugins/plugin_manager.d.ts +9 -10
- package/dist/types/plugins/security_plugin.d.ts +2 -2
- package/dist/types/runner/runner.d.ts +15 -0
- package/dist/types/sessions/base_session_service.d.ts +20 -0
- package/dist/types/sessions/database_session_service.d.ts +32 -0
- package/dist/types/sessions/db/operations.d.ts +29 -0
- package/dist/types/sessions/db/schema.d.ts +45 -0
- package/dist/types/sessions/in_memory_session_service.d.ts +4 -1
- package/dist/types/sessions/registry.d.ts +7 -0
- package/dist/types/tools/base_tool.d.ts +3 -3
- package/dist/types/tools/base_toolset.d.ts +12 -3
- package/dist/types/tools/exit_loop_tool.d.ts +24 -0
- package/dist/types/tools/forwarding_artifact_service.d.ts +5 -3
- package/dist/types/tools/function_tool.d.ts +2 -2
- package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -1
- package/dist/types/utils/env_aware_utils.d.ts +7 -0
- package/dist/types/utils/logger.d.ts +5 -9
- package/dist/types/utils/object_notation_utils.d.ts +21 -0
- package/dist/types/version.d.ts +1 -1
- package/dist/web/a2a/a2a_event.js +243 -0
- package/dist/web/a2a/event_converter_utils.js +201 -0
- package/dist/web/a2a/executor_context.js +23 -0
- package/dist/web/a2a/metadata_converter_utils.js +107 -0
- package/dist/web/a2a/part_converter_utils.js +175 -0
- package/dist/web/agents/base_agent.js +5 -5
- package/dist/web/{tools/tool_context.js → agents/context.js} +66 -11
- package/dist/web/agents/functions.js +3 -2
- package/dist/web/agents/llm_agent.js +90 -717
- package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +100 -0
- package/dist/web/agents/processors/basic_llm_request_processor.js +71 -0
- package/dist/web/agents/processors/code_execution_request_processor.js +365 -0
- package/dist/web/agents/processors/content_request_processor.js +56 -0
- package/dist/web/agents/processors/identity_llm_request_processor.js +41 -0
- package/dist/web/agents/processors/instructions_llm_request_processor.js +72 -0
- package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +158 -0
- package/dist/web/agents/readonly_context.js +12 -0
- package/dist/web/agents/run_config.js +2 -1
- package/dist/web/artifacts/file_artifact_service.js +506 -0
- package/dist/web/artifacts/gcs_artifact_service.js +123 -46
- package/dist/web/artifacts/in_memory_artifact_service.js +51 -4
- package/dist/web/artifacts/registry.js +28 -0
- package/dist/web/common.js +20 -10
- package/dist/web/events/event.js +29 -2
- package/dist/web/events/event_actions.js +1 -1
- package/dist/web/events/structured_events.js +74 -0
- package/dist/web/index.js +7 -2
- package/dist/web/index.js.map +4 -4
- package/dist/web/models/apigee_llm.js +219 -0
- package/dist/web/models/google_llm.js +67 -46
- package/dist/web/models/llm_response.js +2 -0
- package/dist/web/models/registry.js +2 -0
- package/dist/web/plugins/base_plugin.js +1 -1
- package/dist/web/runner/runner.js +34 -1
- package/dist/web/sessions/base_session_service.js +49 -1
- package/dist/web/sessions/database_session_service.js +371 -0
- package/dist/web/sessions/db/operations.js +111 -0
- package/dist/web/sessions/db/schema.js +172 -0
- package/dist/web/sessions/in_memory_session_service.js +23 -21
- package/dist/web/sessions/registry.js +25 -0
- package/dist/web/tools/base_tool.js +3 -0
- package/dist/web/tools/base_toolset.js +11 -2
- package/dist/web/tools/exit_loop_tool.js +32 -0
- package/dist/web/tools/forwarding_artifact_service.js +16 -0
- package/dist/web/tools/mcp/mcp_toolset.js +27 -5
- package/dist/web/utils/env_aware_utils.js +8 -0
- package/dist/web/utils/logger.js +51 -54
- package/dist/web/utils/object_notation_utils.js +47 -0
- package/dist/web/utils/variant_utils.js +1 -7
- package/dist/web/version.js +1 -1
- package/package.json +13 -3
- package/dist/cjs/agents/callback_context.js +0 -101
- package/dist/esm/agents/callback_context.js +0 -71
- package/dist/types/agents/callback_context.d.ts +0 -42
- package/dist/web/agents/callback_context.js +0 -71
- /package/dist/esm/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
- /package/dist/web/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
package/dist/cjs/index.js
CHANGED
|
@@ -1,26 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @license
|
|
3
|
-
* Copyright
|
|
3
|
+
* Copyright 2026 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
6
|
|
|
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
|
-
|
|
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(`
|
|
7
|
+
"use strict";var vi=Object.create;var De=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var yi=Object.getPrototypeOf,Ai=Object.prototype.hasOwnProperty;var xi=(n,e)=>{for(var t in e)De(n,t,{get:e[t],enumerable:!0})},Hn=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ci(e))!Ai.call(n,r)&&r!==t&&De(n,r,{get:()=>e[r],enumerable:!(o=Wn(e,r))||o.enumerable});return n};var te=(n,e,t)=>(t=n!=null?vi(yi(n)):{},Hn(e||!n||!n.__esModule?De(t,"default",{value:n,enumerable:!0}):t,n)),Ei=n=>Hn(De({},"__esModule",{value:!0}),n),E=(n,e,t,o)=>{for(var r=o>1?void 0:o?Wn(e,t):e,i=n.length-1,s;i>=0;i--)(s=n[i])&&(r=(o?s(e,t,r):s(r))||r);return o&&r&&De(e,t,r),r};var ks={};xi(ks,{ActiveStreamingTool:()=>rt,AgentTool:()=>Lt,ApigeeLlm:()=>ge,AuthCredentialTypes:()=>Ln,BaseAgent:()=>D,BaseCodeExecutor:()=>Le,BaseExampleProvider:()=>Tt,BaseLlm:()=>me,BaseLlmRequestProcessor:()=>k,BaseLlmResponseProcessor:()=>mt,BasePlugin:()=>ce,BaseSessionService:()=>le,BaseTool:()=>M,BaseToolset:()=>Ne,BuiltInCodeExecutor:()=>ke,Context:()=>_,DatabaseSessionService:()=>Be,EXIT_LOOP:()=>Wr,EventType:()=>_n,ExitLoopTool:()=>Ye,FileArtifactService:()=>Se,FunctionTool:()=>K,GOOGLE_SEARCH:()=>Hr,GcsArtifactService:()=>Re,Gemini:()=>Q,GoogleLLMVariant:()=>Ve,GoogleSearchTool:()=>Je,InMemoryArtifactService:()=>oe,InMemoryMemoryService:()=>ae,InMemoryPolicyEngine:()=>He,InMemoryRunner:()=>It,InMemorySessionService:()=>H,InvocationContext:()=>z,LLMRegistry:()=>se,LiveRequestQueue:()=>ut,LlmAgent:()=>Ct,LogLevel:()=>$t,LoggingPlugin:()=>St,LongRunningFunctionTool:()=>_t,LoopAgent:()=>At,MCPSessionManager:()=>Ze,MCPTool:()=>et,MCPToolset:()=>jn,ParallelAgent:()=>xt,PluginManager:()=>Me,PolicyOutcome:()=>Nn,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Mn,ReadonlyContext:()=>I,Runner:()=>ue,SecurityPlugin:()=>Rt,SequentialAgent:()=>Et,State:()=>v,StreamingMode:()=>vt,ToolConfirmation:()=>re,createEvent:()=>T,createEventActions:()=>G,createSession:()=>Z,functionsExportedForTestingOnly:()=>Io,geminiInitParams:()=>je,getArtifactServiceFromUri:()=>so,getAskUserConfirmationFunctionCalls:()=>Fr,getFunctionCalls:()=>R,getFunctionResponses:()=>B,getGcpExporters:()=>Rs,getGcpResource:()=>bs,getLogger:()=>Yn,getSessionServiceFromUri:()=>Zr,hasTrailingCodeExecutionResult:()=>qt,isAgentTool:()=>jr,isBaseAgent:()=>bo,isBaseExampleProvider:()=>Nr,isBaseLlm:()=>ft,isBaseTool:()=>dt,isBaseToolset:()=>Kr,isFinalResponse:()=>Y,isFunctionTool:()=>Wo,isGemini2OrAbove:()=>_e,isLlmAgent:()=>x,isLoopAgent:()=>br,isParallelAgent:()=>Pr,isSequentialAgent:()=>kr,maybeSetOtelProviders:()=>ws,mergeStates:()=>W,setLogLevel:()=>Jn,setLogger:()=>Xn,stringifyContent:()=>fo,toStructuredEvents:()=>Or,trimTempDeltaState:()=>bt,version:()=>we,zodObjectToSchema:()=>ve});module.exports=Ei(ks);var b=te(require("fs/promises"),1),A=te(require("path"),1),Fe=require("url");var $=te(require("winston"),1);var $t=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))($t||{}),Dt=class{constructor(){this.logLevel=1;this.logger=$.createLogger({levels:{debug:0,info:1,warn:2,error:3},format:$.format.combine($.format.label({label:"ADK"}),$.format(e=>(e.level=e.level.toUpperCase(),e))(),$.format.colorize(),$.format.timestamp(),$.format.printf(e=>`${e.level}: [${e.label}] ${e.timestamp} ${e.message}`)),transports:[new $.transports.Console]})}setLogLevel(e){this.logLevel=e}log(e,...t){this.logLevel>e||this.logger.log(e.toString(),t.join(" "))}debug(...e){this.logLevel>0||this.logger.debug(e.join(" "))}info(...e){this.logLevel>1||this.logger.info(e.join(" "))}warn(...e){this.logLevel>2||this.logger.warn(e.join(" "))}error(...e){this.logLevel>3||this.logger.error(e.join(" "))}},Ft=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},ne=new Dt;function Xn(n){ne=n!=null?n:new Ft}function Yn(){return ne}function Jn(n){m.setLogLevel(n)}var m={setLogLevel(n){ne.setLogLevel(n)},log(n,...e){ne.log(n,...e)},debug(...n){ne.debug(...n)},info(...n){ne.info(...n)},warn(...n){ne.warn(...n)},error(...n){ne.error(...n)}};var nt="user:",Se=class{constructor(e){try{let t=e.startsWith("file://")?(0,Fe.fileURLToPath)(e):e;this.rootDir=A.resolve(t)}catch(t){throw new Error(`Invalid root directory: ${e}`,{cause:t})}}async saveArtifact({userId:e,sessionId:t,filename:o,artifact:r,customMetadata:i}){if(!r.inlineData&&!r.text)throw new Error("Artifact must have either inlineData or text content.");let s=fe(this.rootDir,e,t,o);await b.mkdir(s,{recursive:!0});let a=await Te(s),c=a.length>0?a[a.length-1]+1:0,l=pe(s),u=A.join(l,c.toString());await b.mkdir(u,{recursive:!0});let f=A.basename(s),p=A.join(u,f),d;if(r.inlineData){let h=r.inlineData.data||"";await b.writeFile(p,Buffer.from(h,"base64")),d=r.inlineData.mimeType||"application/octet-stream"}else r.text!==void 0&&await b.writeFile(p,r.text,"utf-8");let g=await Si(this.rootDir,e,t,o,c),y={fileName:o,mimeType:d,version:c,canonicalUri:g,customMetadata:i};return await Ri(A.join(u,"metadata.json"),y),c}async loadArtifact({userId:e,sessionId:t,filename:o,version:r}){try{let i=fe(this.rootDir,e,t,o);try{await b.access(i)}catch(d){m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} not found`,d);return}let s=await Te(i);if(s.length===0)return;let a;if(r===void 0)a=s[s.length-1];else{if(!s.includes(r)){m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} version ${r} not found`);return}a=r}let c=A.join(pe(i),a.toString()),l=A.join(c,"metadata.json"),u=await tt(l),f=A.basename(i),p=A.join(c,f);if(u.canonicalUri){let d=bi(u.canonicalUri);if(d)try{await b.access(d),p=d}catch{m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} missing at ${d}, falling back to content path ${p}`)}}if(u.mimeType)try{let d=await b.readFile(p);return{inlineData:{mimeType:u.mimeType,data:d.toString("base64")}}}catch{m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} missing at ${p}`);return}try{return{text:await b.readFile(p,"utf-8")}}catch{m.warn(`[FileArtifactService] loadArtifact: Text artifact ${o} missing at ${p}`);return}}catch(i){m.error(`[FileArtifactService] loadArtifact: Error loading artifact ${o}`,i);return}}async listArtifactKeys({userId:e,sessionId:t}){let o=new Set,r=eo(this.rootDir,e),i=no(r,t);for await(let a of Gt(i)){let c=await Qn(a);if(c!=null&&c.fileName)o.add(c.fileName);else{let l=A.relative(i,a);o.add(Zn(l))}}let s=to(r);for await(let a of Gt(s)){let c=await Qn(a);if(c!=null&&c.fileName)o.add(c.fileName);else{let l=A.relative(s,a);o.add(`${nt}${Zn(l)}`)}}return Array.from(o).sort()}async deleteArtifact({userId:e,sessionId:t,filename:o}){try{let r=fe(this.rootDir,e,t,o);await b.rm(r,{recursive:!0,force:!0})}catch(r){m.warn(`[FileArtifactService] deleteArtifact: Failed to delete artifact ${o}`,r)}}async listVersions({userId:e,sessionId:t,filename:o}){try{let r=fe(this.rootDir,e,t,o);return await Te(r)}catch(r){return m.warn(`[FileArtifactService] listVersions: Failed to list versions for artifact ${o}`,r),[]}}async listArtifactVersions({userId:e,sessionId:t,filename:o}){try{let r=fe(this.rootDir,e,t,o),i=await Te(r),s=[];for(let a of i){let c=A.join(pe(r),a.toString(),"metadata.json");try{let l=await tt(c);s.push(l)}catch(l){m.warn(`[FileArtifactService] listArtifactVersions: Failed to read artifact version ${a} at ${r}`,l)}}return s}catch(r){return m.warn(`[FileArtifactService] listArtifactVersions: Failed to list artifact versions for userId: ${e} sessionId: ${t} filename: ${o}`,r),[]}}async getArtifactVersion({userId:e,sessionId:t,filename:o,version:r}){try{let i=fe(this.rootDir,e,t,o),s=await Te(i);if(s.length===0)return;let a;if(r===void 0)a=s[s.length-1];else{if(!s.includes(r))return;a=r}let c=A.join(pe(i),a.toString(),"metadata.json");return await tt(c)}catch(i){m.warn(`[FileArtifactService] getArtifactVersion: Failed to get artifact version for userId: ${e} sessionId: ${t} filename: ${o} version: ${r}`,i);return}}};function eo(n,e){return A.join(n,"users",e)}function Ti(n,e){return!n||e.startsWith(nt)}function to(n){return A.join(n,"artifacts")}function no(n,e){return A.join(n,"sessions",e,"artifacts")}function pe(n){return A.join(n,"versions")}function fe(n,e,t,o){let r=eo(n,e),i;if(Ti(t,o))i=to(r);else{if(!t)throw new Error("Session ID must be provided for session-scoped artifacts.");i=no(r,t)}let s=o;if(s.startsWith(nt)&&(s=s.substring(nt.length)),s=s.trim(),A.isAbsolute(s))throw new Error(`Absolute artifact filename ${o} is not permitted.`);let a=A.resolve(i,s),c=A.relative(i,a);if(c.startsWith("..")||A.isAbsolute(c))throw new Error(`Artifact filename ${o} escapes storage directory.`);return c===""||c==="."?A.join(i,"artifact"):a}async function Te(n){let e=pe(n);try{return(await b.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>parseInt(r.name,10)).filter(r=>!isNaN(r)).sort((r,i)=>r-i)}catch(t){return m.warn(`[FileArtifactService] getArtifactVersionsFromDir: Failed to list artifact versions from ${n}`,t),[]}}async function Si(n,e,t,o,r){let i=await fe(n,e,t,o),s=A.basename(i),a=pe(i),c=A.join(a,r.toString(),s);return(0,Fe.pathToFileURL)(c).toString()}async function Ri(n,e){await b.writeFile(n,JSON.stringify(e,null,2),"utf-8")}async function tt(n){let e=await b.readFile(n,"utf-8");return JSON.parse(e)}async function Qn(n){let e=await Te(n);if(e.length===0)return;let t=e[e.length-1],o=A.join(pe(n),t.toString(),"metadata.json");try{return await tt(o)}catch(r){m.warn(`[FileArtifactService] getLatestMetadata: Failed to read metadata from ${o}`,r);return}}async function*Gt(n){try{let e=await b.readdir(n,{withFileTypes:!0});if(e.some(o=>o.isDirectory()&&o.name==="versions")){yield n;return}for(let o of e)if(o.isDirectory()){let r=A.join(n,o.name);for await(let i of Gt(r))yield i}}catch{}}function bi(n){try{return(0,Fe.fileURLToPath)(n)}catch(e){m.warn(`[FileArtifactService] fileUriToPath: Failed to convert file URI to path: ${n}`,e);return}}function Zn(n){return n.split(A.sep).join("/")}var ro=require("@google-cloud/storage"),ot=require("@google/genai");var Re=class{constructor(e){this.bucket=new ro.Storage().bucket(e)}async saveArtifact(e){if(!e.artifact.inlineData&&!e.artifact.text)throw new Error("Artifact must have either inlineData or text content.");let t=await this.listVersions(e),o=t.length>0?Math.max(...t)+1:0,r=this.bucket.file($e({...e,version:o})),i=e.customMetadata||{};return e.artifact.inlineData?(await r.save(Buffer.from(e.artifact.inlineData.data||"","base64"),{contentType:e.artifact.inlineData.mimeType,metadata:i}),o):(await r.save(e.artifact.text,{contentType:"text/plain",metadata:i}),o)}async loadArtifact(e){try{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($e({...e,version:t})),[[r],[i]]=await Promise.all([o.getMetadata(),o.download()]);return r.contentType==="text/plain"?(0,ot.createPartFromText)(i.toString("utf-8")):(0,ot.createPartFromBase64)(i.toString("base64"),r.contentType)}catch(t){m.warn(`[GcsArtifactService] loadArtifact: Failed to load artifact ${e.filename}`,t);return}}async listArtifactKeys(e){let t=`${e.appName}/${e.userId}/${e.sessionId}/`,o=`${e.appName}/${e.userId}/user/`,[[r],[i]]=await Promise.all([this.bucket.getFiles({prefix:t}),this.bucket.getFiles({prefix:o})]);return[...oo(r,t),...oo(i,o,"user:")].sort((s,a)=>s.localeCompare(a))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(o=>this.bucket.file($e({...e,version:o})).delete()))}async listVersions(e){let o=$e(e)+"/",[r]=await this.bucket.getFiles({prefix:o}),i=[];for(let s of r){let a=s.name.split("/").pop(),c=parseInt(a,10);isNaN(c)||i.push(c)}return i.sort((s,a)=>s-a)}async listArtifactVersions(e){let t=await this.listVersions(e),o=[];for(let r of t){let i=await this.getArtifactVersion({...e,version:r});i&&o.push(i)}return o}async getArtifactVersion(e){try{let t=e.version;if(t===void 0){let i=await this.listVersions(e);if(i.length===0)return;t=Math.max(...i)}let o=this.bucket.file($e({...e,version:t})),[r]=await o.getMetadata();return{version:t,mimeType:r.contentType,customMetadata:r.metadata,canonicalUri:o.publicUrl()}}catch(t){m.warn(`[GcsArtifactService] getArtifactVersion: Failed to get artifact version for userId: ${e.userId} sessionId: ${e.sessionId} filename: ${e.filename} version: ${e.version}`,t);return}}};function $e({appName:n,userId:e,sessionId:t,filename:o,version:r}){let i=o.startsWith("user:"),s=i?o.substring(5):o,a=i?`${n}/${e}/user/${s}`:`${n}/${e}/${t}/${s}`;return r!==void 0?`${a}/${r}`:a}function oo(n,e,t=""){let o=new Set;for(let r of n){if(!r.name.startsWith(e))continue;let i=r.name.substring(e.length),s=wi(i);o.add(`${t}${s}`)}return[...o]}function wi(n){let e=n.split("/");return e.length<2?n:e.slice(0,-1).join("/")}function io(n){return n==="memory://"}var oe=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:o,filename:r,artifact:i,customMetadata:s}){if(!i.inlineData&&!i.text)return Promise.reject(new Error("Artifact must have either inlineData or text content."));let a=be(e,t,o,r);this.artifacts[a]||(this.artifacts[a]=[]);let c=this.artifacts[a].length,l={version:c,customMetadata:s};return this.artifacts[a].push({part:i,metadata:l}),Promise.resolve(c)}loadArtifact({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=be(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i].part)):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=be(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=be(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)}listArtifactVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=be(e,t,o,r),s=this.artifacts[i];return s?Promise.resolve(s.map(a=>a.metadata)):Promise.resolve([])}getArtifactVersion({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=be(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),a[i]?Promise.resolve(a[i].metadata):Promise.resolve(void 0)):Promise.resolve(void 0)}};function be(n,e,t,o){return Ii(o)?`${n}/${e}/user/${o}`:`${n}/${e}/${t}/${o}`}function Ii(n){return n.startsWith("user:")}function so(n){if(io(n))return new oe;if(n.startsWith("gs://")){let e=n.split("://")[1];return new Re(e)}if(n.startsWith("file://")){let e=n.split("://")[1];return new Se(e)}throw new Error(`Unsupported artifact service URI: ${n}`)}var rt=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};var Ie=require("@opentelemetry/api");function ao(n,e=[]){return it(n,Pi,"",e)}function co(n,e=[]){return it(n,Li,"",e)}var Pi=n=>n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),Li=n=>n.replace(/[A-Z]/g,e=>"_"+e.toLowerCase());function it(n,e,t="",o=[]){if(Array.isArray(n))return n.map(r=>it(r,e,t,o));if(typeof n=="object"&&n!==null){let r=n,i={};for(let s of Object.keys(r)){let a=e(s),c=t!==""?t+"."+s:s;o.includes(c)?i[a]=r[s]:i[a]=it(r[s],e,c,o)}return i}return n}function G(n={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...n}}function lo(n,e){let t=G();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 T(n={}){return{...n,id:n.id||Ut(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||G(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()}}function Y(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:R(n).length===0&&B(n).length===0&&!n.partial&&!qt(n)}function R(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 B(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 qt(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 fo(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 uo="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Ut(){let n="";for(let e=0;e<8;e++)n+=uo[Math.floor(Math.random()*uo.length)];return n}var _i=["actions.stateDelta","actions.artifactDelta","actions.requestedAuthConfigs","actions.requestedToolConfirmations","actions.customMetadata","content.parts.functionCall.args","content.parts.functionResponse.response"],ki=["actions.state_delta","actions.artifact_delta","actions.requested_auth_configs","actions.requested_tool_confirmations","actions.custom_metadata","content.parts.function_call.args","content.parts.function_response.response"];function Vt(n){return ao(n,ki)}function po(n){return co(n,_i)}var V=require("@opentelemetry/api");var we="0.5.0";var Oi="gen_ai.agent.description",Mi="gen_ai.agent.name",Ni="gen_ai.conversation.id",jt="gen_ai.operation.name",mo="gen_ai.tool.call.id",go="gen_ai.tool.description",ho="gen_ai.tool.name",Bi="gen_ai.tool.type",j=V.trace.getTracer("gcp.vertex.agent",we);function Ge(n){try{return JSON.stringify(n)}catch{return"<not serializable>"}}function vo({agent:n,invocationContext:e}){let t=V.trace.getActiveSpan();t&&t.setAttributes({[jt]:"invoke_agent",[Oi]:n.description,[Mi]:n.name,[Ni]:e.session.id})}function Co({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=V.trace.getActiveSpan();if(!o)return;o.setAttributes({[jt]:"execute_tool",[go]:n.description||"",[ho]:n.name,[Bi]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":qe()?Ge(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({[mo]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":qe()?Ge(i):"{}"})}function yo({responseEventId:n,functionResponseEvent:e}){let t=V.trace.getActiveSpan();t&&(t.setAttributes({[jt]:"execute_tool",[ho]:"(merged tools)",[go]:"(merged tools)",[mo]: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",qe()?Ge(e):"{}"))}function Ao({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=V.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":qe()?Ge(Di(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",qe()?Ge(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 Di(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 xo(n,e){return{next:V.context.bind(n,e.next.bind(e)),return:V.context.bind(n,e.return.bind(e)),throw:V.context.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return xo(n,e[Symbol.asyncIterator]())}}}function de(n,e,t){let o=t.call(e);return xo(n,o)}function qe(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var Ue=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 v=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}}};v.APP_PREFIX="app:",v.USER_PREFIX="user:",v.TEMP_PREFIX="temp:";var re=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var I=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get userId(){return this.invocationContext.userId}get sessionId(){return this.invocationContext.session.id}get agentName(){return this.invocationContext.agent.name}get state(){return new v(this.invocationContext.session.state,{})}};var _=class extends I{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||G(),this._state=new v(e.invocationContext.session.state,this.eventActions.stateDelta),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get state(){return this._state}get actions(){return this.eventActions}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}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 re({hint:e,confirmed:!1,payload:t})}};function q(){return typeof window<"u"}var st="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ie(){let n="";for(let e=0;e<st.length;e++){let t=Math.random()*16|0;st[e]==="x"?n+=t.toString(16):st[e]==="y"?n+=(t&3|8).toString(16):n+=st[e]}return n}function Eo(n){return q()?window.atob(n):Buffer.from(n,"base64").toString()}function at(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var zt=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},z=class{constructor(e){this.invocationCostManager=new zt;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 To(){return`e-${ie()}`}var Kt=Symbol.for("google.adk.baseAgent");function bo(n){return typeof n=="object"&&n!==null&&Kt in n&&n[Kt]===!0}var Ro;Ro=Kt;var D=class{constructor(e){this[Ro]=!0;this.name=Fi(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=So(e.beforeAgentCallback),this.afterAgentCallback=So(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return Gi(this)}async*runAsync(e){let t=j.startSpan(`invoke_agent ${this.name}`),o=Ie.trace.setSpan(Ie.context.active(),t);try{yield*de(o,this,async function*(){let r=this.createInvocationContext(e),i=await this.handleBeforeAgentCallback(r);if(i&&(yield i),r.endInvocation)return;vo({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=j.startSpan(`invoke_agent ${this.name}`),o=Ie.trace.setSpan(Ie.context.active(),t);try{throw yield*de(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 z({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new _({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return T({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new _({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return T({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 Fi(n){if(!$i(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), underscores, and hyphens.`);if(n==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return n}function $i(n){return/^[\p{ID_Start}$_][\p{ID_Continue}$_-]*$/u.test(n)}function Gi(n){for(;n.parentAgent;)n=n.parentAgent;return n}function So(n){return n?Array.isArray(n)?n:[n]:[]}var wo=require("@google/genai"),Ht=require("lodash-es");var Wt="adk-",ct="adk_request_credential",Pe="adk_request_confirmation",Io={handleFunctionCallList:lt,generateAuthEvent:Yt,generateRequestConfirmationEvent:Jt};function Xt(){return`${Wt}${ie()}`}function Po(n){let e=R(n);if(e)for(let t of e)t.id||(t.id=Xt())}function Lo(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Wt)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Wt)&&(e.functionResponse.id=void 0)}function _o(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 Yt(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||(0,Ht.isEmpty)(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:ct,args:{function_call_id:i,auth_config:s},id:Xt()};o.add(a.id),t.push({functionCall:a})}return T({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function Jt({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||(0,Ht.isEmpty)(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=R(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(p=>p.id===c))!=null?a:void 0;if(!u)continue;let f={name:Pe,args:{originalFunctionCall:u,toolConfirmation:l},id:Xt()};r.add(f.id),o.push({functionCall:f})}return T({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:o,role:t.content.role},actions:t.actions,longRunningToolIds:Array.from(r)})}async function qi(n,e,t){return j.startActiveSpan(`execute_tool ${n.name}`,async o=>{try{m.debug(`callToolAsync ${n.name}`);let r=await n.runAsync({args:e,toolContext:t});return Co({tool:n,args:e,functionResponseEvent:Ui(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function Ui(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 T({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function ko({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=R(e);return await lt({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function lt({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 p;s&&f.id&&(p=s[f.id]);let{tool:d,toolContext:g}=Vi({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:p});m.debug(`execute_tool ${d.name}`);let y=(u=f.args)!=null?u:{},h=null,S;if(h=await n.pluginManager.runBeforeToolCallback({tool:d,toolArgs:y,toolContext:g}),h==null){for(let ee of o)if(h=await ee({tool:d,args:y,context:g}),h)break}if(h==null)try{h=await qi(d,y,g)}catch(ee){if(ee instanceof Error){let Kn=await n.pluginManager.runOnToolErrorCallback({tool:d,toolArgs:y,toolContext:g,error:ee});Kn?h=Kn:S=ee.message}else S=ee}let N=await n.pluginManager.runAfterToolCallback({tool:d,toolArgs:y,toolContext:g,result:h});if(N==null){for(let ee of r)if(N=await ee({tool:d,args:y,context:g,response:h}),N)break}if(N!=null&&(h=N),d.isLongRunning&&!h)continue;S?h={error:S}:(typeof h!="object"||h==null)&&(h={result:h});let zn=T({invocationId:n.invocationId,author:n.agent.name,content:(0,wo.createUserContent)({functionResponse:{id:g.functionCallId,name:d.name,response:h}}),actions:g.actions,branch:n.branch});m.debug("traceToolCall",{tool:d.name,args:y,functionResponseEvent:zn.id}),a.push(zn)}if(!a.length)return null;let l=ji(a);return a.length>1&&j.startActiveSpan("execute_tool (merged)",f=>{try{m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),yo({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function Vi({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 _({invocationContext:n,functionCallId:e.id||void 0,toolConfirmation:o});return{tool:t[e.name],toolContext:r}}function ji(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=lo(o);return T({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ut=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 yt=require("@opentelemetry/api");var zi="google-adk",Ki="gl-typescript",Wi="remote_reasoning_engine",Hi="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Xi(){let n=`${zi}/${we}`;!q()&&process.env[Hi]&&(n=`${n}+${Wi}`);let e=`${Ki}/${q()?window.navigator.userAgent:process.version}`;return[n,e]}function Oo(){return Xi()}var Qt=Symbol.for("google.adk.baseModel");function ft(n){return typeof n=="object"&&n!==null&&Qt in n&&n[Qt]===!0}var Mo;Mo=Qt;var me=class{constructor({model:e}){this[Mo]=!0;this.model=e}get trackingHeaders(){let t=Oo().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."}]})}};me.supportedModels=[];var J=require("@google/genai");var Ve=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Ve||{});function No(){return at("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}var pt=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"}):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(o=>o.functionResponse).filter(o=>!!o);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 Zt(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,citationMetadata:o.citationMetadata,usageMetadata:e,finishReason:o.finishReason}:{errorCode:o.finishReason,errorMessage:o.finishMessage,usageMetadata:e,citationMetadata:o.citationMetadata,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 me{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=je({model:e,vertexai:o,project:r,location:i,apiKey:t});if(!a.vertexai&&!a.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.");this.project=a.project,this.location=a.location,this.apiKey=a.apiKey,this.headers=s,this.vertexai=!!a.vertexai}async*generateContentAsync(e,t=!1){var o,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}`),(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="",p="",d,g;for await(let y of u){g=y;let h=Zt(y);d=h.usageMetadata;let S=(s=(i=h.content)==null?void 0:i.parts)==null?void 0:s[0];if(S!=null&&S.text)"thought"in S&&S.thought?f+=S.text:p+=S.text,h.partial=!0;else if((f||p)&&(!S||!S.inlineData)){let N=[];f&&N.push({text:f,thought:!0}),p&&N.push((0,J.createPartFromText)(p)),yield{content:{role:"model",parts:N},usageMetadata:h.usageMetadata},f="",p=""}yield h}if((p||f)&&((c=(a=g==null?void 0:g.candidates)==null?void 0:a[0])==null?void 0:c.finishReason)===J.FinishReason.STOP){let y=[];f&&y.push({text:f,thought:!0}),p&&y.push({text:p}),yield{content:{role:"model",parts:y},usageMetadata:d}}}else{let u=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield Zt(u)}}getHttpOptions(){return{headers:{...this.trackingHeaders,...this.headers}}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new J.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new J.GoogleGenAI({apiKey:this.apiKey,httpOptions:this.getHttpOptions()}),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}getLiveHttpOptions(){return{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new J.GoogleGenAI({apiKey:this.apiKey,httpOptions:this.getLiveHttpOptions()})),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,J.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 pt(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)Bo(o.inlineData),Bo(o.fileData)}}};Q.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Bo(n){n&&n.displayName&&(n.displayName=void 0)}function je({model:n,vertexai:e,project:t,location:o,apiKey:r}){let i={model:n,vertexai:e,project:t,location:o,apiKey:r};if(i.vertexai=!!e,!i.vertexai&&!q()&&(i.vertexai=at("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!q()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!q()&&!i.location&&(i.location=process.env.GOOGLE_CLOUD_LOCATION),!i.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!i.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else!i.apiKey&&!q()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var Do="APIGEE_PROXY_URL",ge=class extends Q{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!$o(e))throw new Error(`Model ${e} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`);if(super({...Yi({model:e,vertexai:r,project:s,location:i,apiKey:o}),headers:a}),this.proxyUrl=t!=null?t:"",!q()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[Do])!=null?c:""),!this.proxyUrl)throw new Error(`Proxy URL must be provided via the constructor or ${Do} environment variable.`)}getHttpOptions(){let e=super.getHttpOptions();return e.baseUrl=this.proxyUrl,e}getLiveHttpOptions(){let e=super.getLiveHttpOptions();return e.baseUrl=this.proxyUrl,e}identifyApiVersion(){let t=(this.model.startsWith("apigee/")?this.model.substring(7):this.model).split("/");return t.length===3?t[1]:t.length===2&&t[0]!="vertex_ai"&&t[0]!="gemini"&&t[0].startsWith("v")?t[0]:this.vertexai?"v1beta1":"v1alpha"}get liveApiVersion(){return this._apigeeLiveApiVersion||(this._apigeeLiveApiVersion=this.identifyApiVersion()),this._apigeeLiveApiVersion}async*generateContentAsync(e,t=!1){var r;let o=(r=e.model)!=null?r:this.model;e.model=Fo(o),yield*super.generateContentAsync(e,t)}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=Fo(t),super.connect(e)}};ge.supportedModels=[/apigee\/.*/];function Yi({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=je({model:n,vertexai:e,project:t,location:o,apiKey:r});return i.vertexai=i.vertexai||((s=i.model)==null?void 0:s.startsWith("apigee/vertex_ai/")),i.vertexai||i.apiKey||(m.warn('No API key provided when using a Gemini model, using a fake key "-".'),i.apiKey="-"),i}function Fo(n){if(!$o(n))throw new Error(`Model ${n} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`);let e=n.split("/");return e[e.length-1]}function $o(n){let e=["vertex_ai","gemini"];if(!n.startsWith("apigee/"))return!1;let t=n.substring(7);if(t.length===0)return!1;let o=t.split("/",-1);return o[o.length-1].length===0?!1:o.length==1?!0:o.length==2?e.includes(o[0])?!0:o[0].startsWith("v"):o.length==3&&e.includes(o[0])?o[1].startsWith("v"):!1}var en=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)}},F=class F{static newLlm(e){return new(F.resolve(e))({model:e})}static _register(e,t){F.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${F.llmRegistryDict.get(e)} to ${t}`),F.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)F._register(t,e)}static resolve(e){let t=F.resolveCache.get(e);if(t)return t;for(let[o,r]of F.llmRegistryDict.entries())if(new RegExp(`^${o instanceof RegExp?o.source:o}$`,o instanceof RegExp?o.flags:void 0).test(e))return F.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};F.llmRegistryDict=new Map,F.resolveCache=new en(32);var se=F;se.register(Q);se.register(ge);var tn=Symbol.for("google.adk.baseTool");function dt(n){return typeof n=="object"&&n!==null&&tn in n&&n[tn]===!0}var Go;Go=tn;var M=class{constructor(e){this[Go]=!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;if(this.name in e.toolsDict)throw new Error(`Duplicate tool name: ${this.name}`);e.toolsDict[this.name]=this;let o=Ji(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 No()}};function Ji(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var nn=require("@google/genai"),qo=require("zod-to-json-schema"),Uo=require("zod/v4");function on(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function Qi(n){return on(n)&&!("_zod"in n)}function Zi(n){return on(n)&&"_zod"in n}function es(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 he(n){return on(n)&&es(n)==="ZodObject"}function ve(n){if(!he(n))throw new Error("Expected a Zod Object");if(Zi(n))return(0,Uo.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=nn.Type.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(Qi(n))return(0,qo.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=nn.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.")}var sn=require("zod");function Ce(n,e){n.config||(n.config={});let t=e.join(`
|
|
14
8
|
|
|
15
9
|
`);n.config.systemInstruction?n.config.systemInstruction+=`
|
|
16
10
|
|
|
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`
|
|
11
|
+
`+t:n.config.systemInstruction=t}function Vo(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}var Ko=require("@google/genai");function ts(n){return n===void 0?{type:Ko.Type.OBJECT,properties:{}}:he(n)?ve(n):n}var rn=Symbol.for("google.adk.functionTool");function Wo(n){return typeof n=="object"&&n!==null&&rn in n&&n[rn]===!0}var jo,zo,K=class extends(zo=M,jo=rn,zo){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[jo]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:ts(this.parameters)}}async runAsync(t){try{let o=t.args;return he(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 k=class{},mt=class{};var an=class extends k{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new K({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:sn.z.object({agentName:sn.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(!x(t.agent))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;Ce(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new _({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:o})}buildTargetAgentsInfo(t){return`
|
|
18
12
|
Agent name: ${t.name}
|
|
19
13
|
Agent description: ${t.description}
|
|
20
14
|
`}buildTargetAgentsInstructions(t,o){let r=`
|
|
21
15
|
You have a list of other agents to transfer to:
|
|
22
16
|
|
|
23
|
-
${o.map(this.buildTargetAgentsInfo).join(`
|
|
17
|
+
${o.map(i=>this.buildTargetAgentsInfo(i)).join(`
|
|
24
18
|
`)}
|
|
25
19
|
|
|
26
20
|
If you are the best to answer the question according to your description, you
|
|
@@ -34,7 +28,13 @@ the function call.
|
|
|
34
28
|
Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
|
|
35
29
|
you are best for answering the question according to the descriptions, transfer
|
|
36
30
|
to your parent agent.
|
|
37
|
-
`),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!
|
|
31
|
+
`),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!x(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},Ho=new an;var cn=class extends k{async*runAsync(e,t){var r;let o=e.agent;x(o)&&(t.model=o.canonicalModel.model,t.config={...(r=o.generateContentConfig)!=null?r:{}},o.outputSchema&&Vo(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))}},Xo=new cn;var hn=require("lodash-es");var ln=Symbol.for("google.adk.baseCodeExecutor");function gt(n){return typeof n=="object"&&n!==null&&ln in n&&n[ln]===!0}var Yo;Yo=ln;var Le=class{constructor(){this[Yo]=!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 ns="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function un(n){let e=n.match(ns);return e?e[1]:n}function Jo(n){return un(n).startsWith("gemini-")}function os(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 Qo(n){return un(n).startsWith("gemini-1")}function _e(n){if(!n)return!1;let e=un(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=os(t);return o.valid&&o.major>=2}var fn=Symbol.for("google.adk.builtInCodeExecutor");function ze(n){return typeof n=="object"&&n!==null&&fn in n&&n[fn]===!0}var Zo,er,ke=class extends(er=Le,Zo=fn,er){constructor(){super(...arguments);this[Zo]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&_e(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 Ke=require("@google/genai"),tr=require("lodash-es");function nr(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let p=n.parts[f];if(p.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),p.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=(0,tr.cloneDeep)(t[0]),r=t.map(f=>f.text).join(`
|
|
32
|
+
`),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(pn(l)),l):""}function pn(n){return{text:n,executableCode:{code:n,language:Ke.Language.PYTHON}}}function or(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:Ke.Outcome.OUTCOME_FAILED}};let e=[];return(n.stdout||!n.outputFiles)&&e.push(`Code execution result:
|
|
33
|
+
${n.stdout}
|
|
34
|
+
`),n.outputFiles&&e.push(`Saved artifacts:
|
|
35
|
+
`+n.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
|
|
36
|
+
|
|
37
|
+
`),codeExecutionResult:{outcome:Ke.Outcome.OUTCOME_OK}}}function rr(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 ir=require("lodash-es");var dn="_code_execution_context",mn="execution_session_id",ye="processed_input_files",Ae="_code_executor_input_files",xe="_code_executor_error_counts",gn="_code_execution_results",We=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(dn))!=null?t:{},this.sessionState=e}getStateDelta(){return{[dn]:(0,ir.cloneDeep)(this.context)}}getExecutionId(){if(mn in this.context)return this.context[mn]}setExecutionId(e){this.context[mn]=e}getProcessedFileNames(){return ye in this.context?this.context[ye]:[]}addProcessedFileNames(e){ye in this.context||(this.context[ye]=[]),this.context[ye].push(...e)}getInputFiles(){return Ae in this.sessionState?this.sessionState.get(Ae):[]}addInputFiles(e){Ae in this.sessionState||this.sessionState.set(Ae,[]),this.sessionState.get(Ae).push(...e)}clearInputFiles(){Ae in this.sessionState&&this.sessionState.set(Ae,[]),ye in this.context&&(this.context[ye]=[])}getErrorCount(e){return xe in this.sessionState&&this.sessionState.get(xe)[e]||0}incrementErrorCount(e){xe in this.sessionState||this.sessionState.set(xe,{}),this.sessionState.get(xe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(xe in this.sessionState))return;let t=this.sessionState.get(xe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){gn in this.sessionState||this.sessionState.set(gn,{});let i=this.sessionState.get(gn);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(dn)||{}}};var vn=class extends k{async*runAsync(e,t){if(x(e.agent)&&e.agent.codeExecutor){for await(let o of is(e,t))yield o;if(gt(e.agent.codeExecutor))for(let o of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];rr(o,r,e.agent.codeExecutor.executionResultDelimiters)}}}},ht={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},rs=`
|
|
38
38
|
import pandas as pd
|
|
39
39
|
|
|
40
40
|
def explore_df(df: pd.DataFrame) -> None:
|
|
@@ -71,23 +71,30 @@ def explore_df(df: pd.DataFrame) -> None:
|
|
|
71
71
|
Total columns: {df.shape[1]}
|
|
72
72
|
|
|
73
73
|
{df_info}""")
|
|
74
|
-
`,
|
|
74
|
+
`,Cn=class{async*runAsync(e,t){if(!t.partial)for await(let o of ss(e,t))yield o}},Al=new Cn;async function*is(n,e){let t=n.agent;if(!x(t))return;let o=t.codeExecutor;if(!o||!gt(o))return;if(ze(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new We(new v(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=as(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=cs(c);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},pn(l)]};e.contents.push((0,hn.cloneDeep)(u)),yield T({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=sr(n,r),p=await o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:p.stdout,resultStderr:p.stderr}),r.addProcessedFileNames([c.name]);let d=await ar(n,r,p);yield d,e.contents.push((0,hn.cloneDeep)(d.content))}}async function*ss(n,e){let t=n.agent;if(!x(t))return;let o=t.codeExecutor;if(!o||!gt(o)||!e||!e.content||ze(o))return;let r=new We(new v(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=nr(i,o.codeBlockDelimiters);if(!s)return;yield T({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=sr(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 ar(n,r,c),e.content=void 0}function as(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||!ht[l])continue;let u=`data_${i+1}_${a+1}${ht[l].extension}`;c.text=`
|
|
75
75
|
Available file: \`${u}\`
|
|
76
|
-
`;let f={name:u,content:
|
|
77
|
-
${
|
|
76
|
+
`;let f={name:u,content:Eo(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function sr(n,e){var r;let t=n.agent;if(!x(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function ar(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[or(t)]},r=G({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 T({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function cs(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!ht[n.mimeType])return;let t=e(n.name),o=ht[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return`
|
|
77
|
+
${rs}
|
|
78
78
|
|
|
79
79
|
# Load the dataframe.
|
|
80
80
|
${t} = ${o}
|
|
81
81
|
|
|
82
82
|
# Use \`explore_df\` to guide my analysis.
|
|
83
83
|
explore_df(${t})
|
|
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
|
|
84
|
+
`}var cr=new vn;var ur=require("lodash-es");function yn(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)||ls(l)||us(l)||o.push(pr(e,l)?fs(l):l);let r=ps(o);r=ds(r);let i=[];for(let l of r){let u=(0,ur.cloneDeep)(l.content);Lo(u),i.push(u)}return i}function fr(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||pr(e,r))return yn(n.slice(o),e,t)}return[]}function ls(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)===ct||((o=r.functionResponse)==null?void 0:o.name)===ct)return!0;return!1}function us(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)===Pe||((o=r.functionResponse)==null?void 0:o.name)===Pe)return!0;return!1}function pr(n,e){return!!n&&e.author!==n&&e.author!=="user"}function fs(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=lr(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=lr(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 T({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function dr(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=T(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 ps(n){if(n.length===0)return n;let e=n[n.length-1],t=B(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=R(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=R(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let p=new Set(u.map(g=>g.id).filter(g=>!!g));if(!Array.from(o).every(g=>p.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(p).join(", ")}, function response ids provided: ${Array.from(o).join(", ")}`);o=p;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=B(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(dr(s)),a}function ds(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=B(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(B(o).length>0)continue;let r=R(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(dr(a))}}else t.push(o)}return t}function lr(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}var An=class{async*runAsync(e,t){let o=e.agent;!o||!x(o)||(o.includeContents==="default"?t.contents=yn(e.session.events,o.name,e.branch):t.contents=fr(e.session.events,o.name,e.branch))}},mr=new An;var xn=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}"`),Ce(t,r)}},gr=new xn;async function En(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 p=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!p)throw new Error(`Artifact ${f} not found.`);return String(p)}if(!hs(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 ms=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function hr(n){return n===""||n===void 0?!1:ms.test(n)}var gs=[v.APP_PREFIX,v.USER_PREFIX,v.TEMP_PREFIX];function hs(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?hr(n):gs.includes(e[0]+":")?hr(e[1]):!1}var Tn=class extends k{async*runAsync(e,t){let o=e.agent;if(!x(o)||!x(o.rootAgent))return;let r=o.rootAgent;if(x(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new I(e)),a=i;s&&(a=await En(i,new I(e))),Ce(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=await o.canonicalInstruction(new I(e)),a=i;s&&(a=await En(i,new I(e))),Ce(t,[a])}}},vr=new Tn;var Sn=class extends k{async*runAsync(e){let t=e.agent;if(!x(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=B(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==Pe)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 re({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=R(a);if(!c)continue;let l={},u={};for(let g of c){if(!g.id||!(g.id in r))continue;let y=g.args;if(!y||!("originalFunctionCall"in y))continue;let h=y.originalFunctionCall;h.id&&(l[h.id]=r[g.id],u[h.id]=h)}if(Object.keys(l).length===0)continue;for(let g=o.length-1;g>i;g--){let y=o[g],h=B(y);if(h){for(let S of h)S.id&&S.id in l&&(delete l[S.id],delete u[S.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=await t.canonicalTools(new I(e)),p=Object.fromEntries(f.map(g=>[g.name,g])),d=await lt({invocationContext:e,functionCalls:Object.values(u),toolsDict:p,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l});d&&(yield d);return}}},Cr=new Sn;var vt=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(vt||{});function yr(n={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:vs(n.maxLlmCalls||500),pauseOnToolCalls:!1,...n}}function vs(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return n<=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."),n}var Ar="adk_agent_name";async function xr(n,e){return dt(n)?[n]:await n.getTools(e)}var Rn=Symbol.for("google.adk.llmAgent");function x(n){return typeof n=="object"&&n!==null&&Rn in n&&n[Rn]===!0}var Er,Tr,Ct=class n extends(Tr=D,Er=Rn,Tr){constructor(t){var r,i,s,a,c,l,u,f,p;super(t);this[Er]=!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=he(t.inputSchema)?ve(t.inputSchema):t.inputSchema,this.outputSchema=he(t.outputSchema)?ve(t.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:[Xo,gr,vr,Cr,mr,cr],this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((p=this.subAgents)!=null&&p.length)||this.requestProcessors.push(Ho),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={};this.outputSchema&&(!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)}get canonicalModel(){if(ft(this.model))return this.model;if(typeof this.model=="string"&&this.model)return se.newLlm(this.model);let t=this.parentAgent;for(;t;){if(x(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 xr(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){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(!Y(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 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){m.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||Y(o))break;if(o.partial){m.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 _({invocationContext:t}),l=await xr(a,new I(t));for(let u of l)await u.processLlmRequest({toolContext:c,llmRequest:o})}if(t.endInvocation)return;let r=T({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=j.startSpan("call_llm"),s=yt.trace.setSpan(yt.context.active(),i);yield*de(s,this,async function*(){let a=async function*(){for await(let c of this.callLlmAsync(t,o,r))for await(let l of this.postprocess(t,o,c,r))r.id=Ut(),r.timestamp=new Date().getTime(),yield l};yield*this.runAndHandleError(a.call(this),t,o,r)}),i.end()}async*postprocess(t,o,r,i){var f,p;for(let d of this.responseProcessors)for await(let g of d.runAsync(t,r))yield g;if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=T({...i,...r});if(s.content){let d=R(s);d!=null&&d.length&&(Po(s),s.longRunningToolIds=Array.from(_o(d,o.toolsDict)))}if(yield s,!((f=R(s))!=null&&f.length))return;if((p=t.runConfig)!=null&&p.pauseOnToolCalls){t.endInvocation=!0;return}let a=await ko({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a)return;let c=Yt(t,a);c&&(yield c);let l=Jt({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let d=this.getAgentByName(t,u);for await(let g of d.runAsync(t))yield g}}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[Ar]||(o.config.labels[Ar]=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 p=s.generateContentAsync(o,((f=t.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let d of p){Ao({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:d});let g=await this.handleAfterModelCallback(t,d,r);yield g!=null?g:d}}}async handleBeforeModelCallback(t,o,r){let i=new _({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 _({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 _({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="UNKNOWN_ERROR",u=s.message;try{let f=JSON.parse(s.message);f!=null&&f.error&&(l=String(f.error.code||"UNKNOWN_ERROR"),u=f.error.message||u)}catch{}i.actions?yield T({invocationId:o.invocationId,author:this.name,errorCode:l,errorMessage:u}):yield{errorCode:l,errorMessage:u}}}else throw m.error("Unknown error during response generation",s),s}}};var bn=Symbol.for("google.adk.loopAgent");function br(n){return typeof n=="object"&&n!==null&&bn in n&&n[bn]===!0}var Sr,Rr,At=class extends(Rr=D,Sr=bn,Rr){constructor(t){var o;super(t);this[Sr]=!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 wn=Symbol.for("google.adk.parallelAgent");function Pr(n){return typeof n=="object"&&n!==null&&wn in n&&n[wn]===!0}var wr,Ir,xt=class extends(Ir=D,wr=wn,Ir){constructor(){super(...arguments);this[wr]=!0}async*runAsyncImpl(t){let o=this.subAgents.map(r=>r.runAsync(Cs(this,r,t)));for await(let r of ys(o))yield r}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function Cs(n,e,t){let o=new z(t),r=`${n.name}.${e.name}`;return o.branch=o.branch?`${o.branch}.${r}`:r,o}async function*ys(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 In="task_completed",Pn=Symbol.for("google.adk.sequentialAgent");function kr(n){return typeof n=="object"&&n!==null&&Pn in n&&n[Pn]===!0}var Lr,_r,Et=class extends(_r=D,Lr=Pn,_r){constructor(){super(...arguments);this[Lr]=!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)x(o)&&((await o.canonicalTools(new I(t))).some(s=>s.name===In)||(o.tools.push(new K({name:In,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 ${In} 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 Ln=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(Ln||{});var Oe=require("lodash-es");var _n=(u=>(u.THOUGHT="thought",u.CONTENT="content",u.TOOL_CALL="tool_call",u.TOOL_RESULT="tool_result",u.CALL_CODE="call_code",u.CODE_RESULT="code_result",u.ERROR="error",u.ACTIVITY="activity",u.TOOL_CONFIRMATION="tool_confirmation",u.FINISHED="finished",u))(_n||{});function Or(n){var t,o;let e=[];if(n.errorCode)return e.push({type:"error",error:new Error(n.errorMessage||n.errorCode)}),e;for(let r of(o=(t=n.content)==null?void 0:t.parts)!=null?o:[])r.functionCall&&!(0,Oe.isEmpty)(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!(0,Oe.isEmpty)(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!(0,Oe.isEmpty)(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!(0,Oe.isEmpty)(r.codeExecutionResult)?e.push({type:"code_result",result:r.codeExecutionResult}):r.text&&(r.thought?e.push({type:"thought",content:r.text}):e.push({type:"content",content:r.text}));return n.actions.requestedToolConfirmations&&!(0,Oe.isEmpty)(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),Y(n)&&e.push({type:"finished",output:void 0}),e}var kn=Symbol.for("google.adk.baseExampleProvider");function Nr(n){return typeof n=="object"&&n!==null&&kn in n&&n[kn]===!0}var Mr;Mr=kn;var Tt=class{constructor(){this[Mr]=!0}};var ae=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Br(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=Br(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(p=>p.text).filter(p=>!!p).join(" "),u=As(l);if(!u.size)continue;o.some(p=>u.has(p))&&r.memories.push({content:c.content,author:c.author,timestamp:xs(c.timestamp)})}return r}};function Br(n,e){return`${n}/${e}`}function As(n){return new Set([...n.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function xs(n){return new Date(n).toISOString()}var ce=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 St=class extends ce{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: ${Y(e)}`);let t=R(e);if(t.length>0){let r=t.map(i=>i.name);this.log(` Function Calls: ${r}`)}let o=B(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`;m.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 Me=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,o){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 '${o}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${o}' callback: ${i}`;throw m.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 Mn="adk_request_confirmation",On="orcas_tool_call_security_check_states",Dr="This tool call needs external confirmation before completion.",Nn=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(Nn||{}),He=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Rt=class extends ce{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new He}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:Dr};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(On))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(On))!=null?i:{};r[o]=t,e.state.set(On,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:Dr};case"ALLOW":return;default:return}}};function Fr(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===Mn&&e.push(t.functionCall);return e}var Bn=require("lodash-es");var $r=require("lodash-es");var le=class{async getOrCreateSession(e){if(!e.sessionId)return this.createSession(e);let t=await this.getSession({appName:e.appName,userId:e.userId,sessionId:e.sessionId});return t||this.createSession(e)}async appendEvent({session:e,event:t}){return t.partial||(t=bt(t),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(v.TEMP_PREFIX)||(e.state[o]=r)}};function bt(n){if(!n.actions||!n.actions.stateDelta)return n;let e=n.actions.stateDelta,t={};for(let[o,r]of Object.entries(e))o.startsWith(v.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function W(n={},e={},t={}){let o=(0,$r.cloneDeep)(t);for(let[r,i]of Object.entries(n))o[v.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[v.USER_PREFIX+r]=i;return o}function Z(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}function Gr(n){return n==="memory://"}var H=class extends le{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}async createSession({appName:t,userId:o,state:r,sessionId:i}){var c;let s=Z({id:i||ie(),appName:t,userId:o,state:r,events:[],lastUpdateTime:Date.now()});this.sessions[t]||(this.sessions[t]={}),this.sessions[t][o]||(this.sessions[t][o]={}),this.sessions[t][o][s.id]=s;let a=(0,Bn.cloneDeep)(s);return a.state=W(this.appState[t],(c=this.userState[t])==null?void 0:c[o],a.state),a}async getSession({appName:t,userId:o,sessionId:r,config:i}){var c;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,Bn.cloneDeep)(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let l=a.events.length-1;for(;l>=0&&!(a.events[l].timestamp<i.afterTimestamp);)l--;l>=0&&(a.events=a.events.slice(l+1))}return a.state=W(this.appState[t],(c=this.userState[t])==null?void 0:c[o],a.state),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(Z({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=>{m.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(v.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(v.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(v.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(v.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}};var qr=require("@google/genai"),wt=require("@opentelemetry/api");var ue=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new Me((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runEphemeral(e){let o=(await this.sessionService.createSession({appName:this.appName,userId:e.userId})).id;try{yield*this.runAsync({userId:e.userId,sessionId:o,newMessage:e.newMessage,stateDelta:e.stateDelta,runConfig:e.runConfig})}finally{await this.sessionService.deleteSession({appName:this.appName,userId:e.userId,sessionId:o})}}async*runAsync(e){let{userId:t,sessionId:o,stateDelta:r}=e,i=yr(e.runConfig),s=e.newMessage,a=j.startSpan("invocation"),c=wt.trace.setSpan(wt.context.active(),a);try{yield*de(c,this,async function*(){var p;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&&x(this.agent)){let d=this.agent.canonicalModel.model;if(!_e(d))throw new Error(`CFC is not supported for model: ${d} in agent: ${this.agent.name}`);ze(this.agent.codeExecutor)||(this.agent.codeExecutor=new ke)}let u=new z({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:To(),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(!((p=s.parts)!=null&&p.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:T({invocationId:u.invocationId,author:"user",actions:r?G({stateDelta:r}):void 0,content:s})})}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let d=await this.pluginManager.runBeforeRunCallback({invocationContext:u});if(d){let g=T({invocationId:u.invocationId,author:"model",content:d});await this.sessionService.appendEvent({session:l,event:g}),yield g}else{for await(let g of u.agent.runAsync(u)){g.partial||await this.sessionService.appendEvent({session:l,event:g});let y=await this.pluginManager.runOnEventCallback({invocationContext:u,event:g});y?yield y:yield g}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,qr.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let o=Es(e.events);if(o&&o.author)return t.findAgent(o.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(!x(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Es(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=R(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var It=class extends ue{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new oe,sessionService:new H,memoryService:new ae})}};var Xe=require("@google/genai");var Pt=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)}listArtifactVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listArtifactVersions(e)}getArtifactVersion(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.getArtifactVersion(e)}};var Dn=Symbol.for("google.adk.agentTool");function jr(n){return typeof n=="object"&&n!==null&&Dn in n&&n[Dn]===!0}var Ur,Vr,Lt=class extends(Vr=M,Ur=Dn,Vr){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[Ur]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(x(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 o=x(this.agent)&&this.agent.outputSchema;t.response=o?{type:Xe.Type.OBJECT}:{type:Xe.Type.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,p;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:x(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new ue({appName:this.agent.name,agent:this.agent,artifactService:new Pt(o),sessionService:new H,memoryService:new ae,credentialService:o.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:o.state.toRecord()}),c;for await(let d of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i}))d.actions.stateDelta&&o.state.update(d.actions.stateDelta),c=d;if(!((p=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&p.length))return"";let l=x(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(d=>d.text).filter(d=>d).join(`
|
|
85
|
+
`);return l?JSON.parse(u):u}};var Fn=Symbol.for("google.adk.baseToolset");function Kr(n){return typeof n=="object"&&n!==null&&Fn in n&&n[Fn]===!0}var zr;zr=Fn;var Ne=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[zr]=!0}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 Ye=class extends M{constructor(){super({name:"exit_loop",description:`Exits the loop.
|
|
86
|
+
|
|
87
|
+
Call this function only when you are instructed to do so.`})}_getDeclaration(){return{name:this.name,description:this.description}}async runAsync({toolContext:e}){return e.actions.escalate=!0,e.actions.skipSummarization=!0,""}},Wr=new Ye;var Je=class extends M{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||[],Qo(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(Jo(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${e.model}`)}}},Hr=new Je;var Xr=`
|
|
86
88
|
|
|
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});
|
|
89
|
+
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,_t=class extends K{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Xr:e.description=Xr.trimStart(),e}};var Ot=require("@mikro-orm/core");var kt=require("@mikro-orm/core");var C=require("@mikro-orm/core");var Gn="schema_version",qn="1",$n=class extends C.JsonType{convertToDatabaseValue(e){return JSON.stringify(po(e))}convertToJSValue(e){return typeof e=="string"?Vt(JSON.parse(e)):Vt(e)}},X=class{};E([(0,C.PrimaryKey)({type:"string"})],X.prototype,"key",2),E([(0,C.Property)({type:"string"})],X.prototype,"value",2),X=E([(0,C.Entity)({tableName:"adk_internal_metadata"})],X);var O=class{constructor(){this.updateTime=new Date}};E([(0,C.PrimaryKey)({type:"string",fieldName:"app_name"})],O.prototype,"appName",2),E([(0,C.Property)({type:"json"})],O.prototype,"state",2),E([(0,C.Property)({type:"datetime",fieldName:"update_time",onCreate:()=>new Date,onUpdate:()=>new Date})],O.prototype,"updateTime",2),O=E([(0,C.Entity)({tableName:"app_states"})],O);C.PrimaryKey.name;var L=class{constructor(){this.updateTime=new Date}};E([(0,C.PrimaryKey)({type:"string",fieldName:"app_name"})],L.prototype,"appName",2),E([(0,C.PrimaryKey)({type:"string",fieldName:"user_id"})],L.prototype,"userId",2),E([(0,C.Property)({type:"json"})],L.prototype,"state",2),E([(0,C.Property)({type:"datetime",fieldName:"update_time",onCreate:()=>new Date,onUpdate:()=>new Date})],L.prototype,"updateTime",2),L=E([(0,C.Entity)({tableName:"user_states"})],L);C.PrimaryKey.name;var w=class{constructor(){this.createTime=new Date;this.updateTime=new Date}};E([(0,C.PrimaryKey)({type:"string"})],w.prototype,"id",2),E([(0,C.PrimaryKey)({type:"string",fieldName:"app_name"})],w.prototype,"appName",2),E([(0,C.PrimaryKey)({type:"string",fieldName:"user_id"})],w.prototype,"userId",2),E([(0,C.Property)({type:"json"})],w.prototype,"state",2),E([(0,C.Property)({type:"datetime",fieldName:"create_time",onCreate:()=>new Date})],w.prototype,"createTime",2),E([(0,C.Property)({type:"datetime",fieldName:"update_time",onCreate:()=>new Date})],w.prototype,"updateTime",2),w=E([(0,C.Entity)({tableName:"sessions"})],w);C.PrimaryKey.name;var P=class{};E([(0,C.PrimaryKey)({type:"string"})],P.prototype,"id",2),E([(0,C.PrimaryKey)({type:"string",fieldName:"app_name"})],P.prototype,"appName",2),E([(0,C.PrimaryKey)({type:"string",fieldName:"user_id"})],P.prototype,"userId",2),E([(0,C.PrimaryKey)({type:"string",fieldName:"session_id"})],P.prototype,"sessionId",2),E([(0,C.Property)({type:"string",fieldName:"invocation_id"})],P.prototype,"invocationId",2),E([(0,C.Property)({type:"datetime"})],P.prototype,"timestamp",2),E([(0,C.Property)({type:$n,fieldName:"event_data"})],P.prototype,"eventData",2),P=E([(0,C.Entity)({tableName:"events"})],P);var Qe=[X,O,L,w,P];async function Un(n){let e;if(n.startsWith("postgres://")||n.startsWith("postgresql://")){let{PostgreSqlDriver:c}=await Promise.resolve().then(()=>te(require("@mikro-orm/postgresql"),1));e=c}else if(n.startsWith("mysql://")){let{MySqlDriver:c}=await Promise.resolve().then(()=>te(require("@mikro-orm/mysql"),1));e=c}else if(n.startsWith("mariadb://")){let{MariaDbDriver:c}=await Promise.resolve().then(()=>te(require("@mikro-orm/mariadb"),1));e=c}else if(n.startsWith("sqlite://")){let{SqliteDriver:c}=await Promise.resolve().then(()=>te(require("@mikro-orm/sqlite"),1));e=c}else if(n.startsWith("mssql://")){let{MsSqlDriver:c}=await Promise.resolve().then(()=>te(require("@mikro-orm/mssql"),1));e=c}else throw new Error(`Unsupported database URI: ${n}`);if(n==="sqlite://:memory:")return{entities:Qe,dbName:":memory:",driver:e};let{host:t,port:o,username:r,password:i,pathname:s}=new URL(n),a=t.split(":")[0];return{entities:Qe,dbName:s.slice(1),host:a,port:o?parseInt(o):void 0,user:r,password:i,driver:e}}async function Yr(n){let e;n instanceof kt.MikroORM?e=n:typeof n=="string"?e=await kt.MikroORM.init(await Un(n)):e=await kt.MikroORM.init(n),await e.schema.ensureDatabase(),await e.schema.updateSchema()}async function Jr(n){let e=n.em.fork(),t=await e.findOne(X,{key:Gn});if(t){if(t.value!==qn)throw new Error(`ADK Database schema version ${t.value} is not compatible.`);return}let o=e.create(X,{key:Gn,value:qn});await e.persist(o).flush()}function Qr(n){return n?n.startsWith("postgres://")||n.startsWith("postgresql://")||n.startsWith("mysql://")||n.startsWith("mariadb://")||n.startsWith("mssql://")||n.startsWith("sqlite://"):!1}var Be=class extends le{constructor(t){super();this.initialized=!1;if(typeof t=="string")this.connectionString=t;else{if(!t.driver)throw new Error("Driver is required when passing options object.");this.options={...t,entities:Qe}}}async init(){this.initialized||(this.connectionString&&(!this.options||!this.options.driver)&&(this.options=await Un(this.connectionString)),this.orm=await Ot.MikroORM.init(this.options),await Yr(this.orm),await Jr(this.orm),this.initialized=!0)}async createSession({appName:t,userId:o,state:r,sessionId:i}){await this.init();let s=this.orm.em.fork(),a=i||ie(),c=new Date;if(await s.findOne(w,{id:a,appName:t,userId:o}))throw new Error(`Session with id ${a} already exists.`);let u=await s.findOne(O,{appName:t});u||(u=s.create(O,{appName:t,state:{},updateTime:c}),s.persist(u));let f=await s.findOne(L,{appName:t,userId:o});f||(f=s.create(L,{appName:t,userId:o,state:{}}),s.persist(f));let p={},d={},g={};if(r)for(let[S,N]of Object.entries(r))S.startsWith(v.APP_PREFIX)?p[S.replace(v.APP_PREFIX,"")]=N:S.startsWith(v.USER_PREFIX)?d[S.replace(v.USER_PREFIX,"")]=N:g[S]=N;Object.keys(p).length>0&&(u.state={...u.state,...p}),Object.keys(d).length>0&&(f.state={...f.state,...d});let y=s.create(w,{id:a,appName:t,userId:o,state:g,createTime:c,updateTime:c});s.persist(y),await s.flush();let h=W(u.state,f.state,g);return Z({id:a,appName:t,userId:o,state:h,events:[],lastUpdateTime:y.createTime.getTime()})}async getSession({appName:t,userId:o,sessionId:r,config:i}){await this.init();let s=this.orm.em.fork(),a=await s.findOne(w,{appName:t,userId:o,id:r});if(!a)return;let c={appName:t,userId:o,sessionId:r};i!=null&&i.afterTimestamp&&(c.timestamp={$gt:new Date(i.afterTimestamp)});let l=await s.find(P,c,{orderBy:{timestamp:"DESC"},limit:i==null?void 0:i.numRecentEvents});l.reverse();let u=await s.findOne(O,{appName:t}),f=await s.findOne(L,{appName:t,userId:o}),p=W((u==null?void 0:u.state)||{},(f==null?void 0:f.state)||{},a.state);return Z({id:r,appName:t,userId:o,state:p,events:l.map(d=>d.eventData),lastUpdateTime:a.updateTime.getTime()})}async listSessions({appName:t,userId:o}){await this.init();let r=this.orm.em.fork(),i={appName:t};o&&(i.userId=o);let s=await r.find(w,i),a=await r.findOne(O,{appName:t}),c=(a==null?void 0:a.state)||{},l={};if(o){let f=await r.findOne(L,{appName:t,userId:o});f&&(l[o]=f.state)}else{let f=await r.find(L,{appName:t});for(let p of f)l[p.userId]=p.state}return{sessions:s.map(f=>{let p=l[f.userId]||{},d=W(c,p,f.state);return Z({id:f.id,appName:f.appName,userId:f.userId,state:d,events:[],lastUpdateTime:f.updateTime.getTime()})})}}async deleteSession({appName:t,userId:o,sessionId:r}){await this.init();let i=this.orm.em.fork();await i.nativeDelete(w,{appName:t,userId:o,id:r}),await i.nativeDelete(P,{appName:t,userId:o,sessionId:r})}async appendEvent({session:t,event:o}){await this.init();let r=this.orm.em.fork();if(o.partial)return o;let i=bt(o);return await r.transactional(async s=>{let a=await s.findOne(w,{appName:t.appName,userId:t.userId,id:t.id},{lockMode:Ot.LockMode.PESSIMISTIC_WRITE});if(!a)throw new Error(`Session ${t.id} not found for appendEvent`);let c=await s.findOne(O,{appName:t.appName});c||(c=s.create(O,{appName:t.appName,state:{},updateTime:new Date}),s.persist(c));let l=await s.findOne(L,{appName:t.appName,userId:t.userId});if(l||(l=s.create(L,{appName:t.appName,userId:t.userId,state:{}}),s.persist(l)),a.updateTime.getTime()>t.lastUpdateTime){let p=await s.find(P,{appName:t.appName,userId:t.userId,sessionId:t.id},{orderBy:{timestamp:"ASC"}}),d=W(c.state,l.state,a.state);t.state=d,t.events=p.map(g=>g.eventData)}if(o.actions&&o.actions.stateDelta){let p={},d={},g={};for(let[y,h]of Object.entries(o.actions.stateDelta))y.startsWith(v.APP_PREFIX)?p[y.replace(v.APP_PREFIX,"")]=h:y.startsWith(v.USER_PREFIX)?d[y.replace(v.USER_PREFIX,"")]=h:g[y]=h;Object.keys(p).length>0&&(c.state={...c.state,...p}),Object.keys(d).length>0&&(l.state={...l.state,...d}),Object.keys(g).length>0&&(a.state={...a.state,...g})}let u=s.create(P,{id:i.id,appName:t.appName,userId:t.userId,sessionId:t.id,invocationId:i.invocationId,timestamp:new Date(i.timestamp),eventData:i});s.persist(u),await s.commit(),a.updateTime=new Date(o.timestamp);let f=W(c.state,l.state,a.state);t.state=f,t.events.push(o),t.lastUpdateTime=a.updateTime.getTime()}),o}};function Zr(n){if(Gr(n))return new H;if(Qr(n))return new Be(n);throw new Error(`Unsupported session service URI: ${n}`)}var ei=require("@google-cloud/opentelemetry-cloud-monitoring-exporter"),ti=require("@google-cloud/opentelemetry-cloud-trace-exporter"),ni=require("@opentelemetry/resource-detector-gcp"),oi=require("@opentelemetry/resources"),ri=require("@opentelemetry/sdk-metrics"),ii=require("@opentelemetry/sdk-trace-base"),si=require("google-auth-library");var Ts="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Ss(){try{return await new si.GoogleAuth().getProjectId()||void 0}catch{return}}async function Rs(n={}){let{enableTracing:e=!1,enableMetrics:t=!1}=n,o=await Ss();return o?{spanProcessors:e?[new ii.BatchSpanProcessor(new ti.TraceExporter({projectId:o}))]:[],metricReaders:t?[new ri.PeriodicExportingMetricReader({exporter:new ei.MetricExporter({projectId:o}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(m.warn(Ts),{})}function bs(){return(0,oi.detectResources)({detectors:[ni.gcpDetector]})}var Mt=require("@opentelemetry/api"),ai=require("@opentelemetry/api-logs"),ci=require("@opentelemetry/exporter-logs-otlp-http"),li=require("@opentelemetry/exporter-metrics-otlp-http"),ui=require("@opentelemetry/exporter-trace-otlp-http"),fi=require("@opentelemetry/resources"),Nt=require("@opentelemetry/sdk-logs"),Bt=require("@opentelemetry/sdk-metrics"),pi=require("@opentelemetry/sdk-trace-base"),di=require("@opentelemetry/sdk-trace-node");function ws(n=[],e){let t=e||Is(),o=[...n,Ls()],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 di.NodeTracerProvider({resource:t,spanProcessors:r});a.register(),Mt.trace.setGlobalTracerProvider(a)}if(i.length>0){let a=new Bt.MeterProvider({readers:i,resource:t});Mt.metrics.setGlobalMeterProvider(a)}if(s.length>0){let a=new Nt.LoggerProvider({resource:t,processors:s});ai.logs.setGlobalLoggerProvider(a)}}function Is(){return(0,fi.detectResources)({detectors:[]})}function Ps(){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 Ls(n=Ps()){let{enableTracing:e,enableMetrics:t,enableLogging:o}=n;return{spanProcessors:e?[new pi.BatchSpanProcessor(new ui.OTLPTraceExporter)]:[],metricReaders:t?[new Bt.PeriodicExportingMetricReader({exporter:new li.OTLPMetricExporter})]:[],logRecordProcessors:o?[new Nt.BatchLogRecordProcessor(new ci.OTLPLogExporter)]:[]}}var mi=require("@modelcontextprotocol/sdk/client/index.js"),gi=require("@modelcontextprotocol/sdk/client/stdio.js"),hi=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Ze=class{constructor(e){this.connectionParams=e}async createSession(){var t;let e=new mi.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new gi.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 hi.StreamableHTTPClientTransport(new URL(this.connectionParams.url),o));break}default:{let o=this.connectionParams;break}}return e}};var U=require("@google/genai"),Ee=require("zod");var Gd=Ee.z.object({type:Ee.z.literal("object"),properties:Ee.z.record(Ee.z.string(),Ee.z.unknown()).optional(),required:Ee.z.string().array().optional()});function _s(n){if(!n)return U.Type.TYPE_UNSPECIFIED;switch(n.toLowerCase()){case"text":case"string":return U.Type.STRING;case"number":return U.Type.NUMBER;case"boolean":return U.Type.BOOLEAN;case"integer":return U.Type.INTEGER;case"array":return U.Type.ARRAY;case"object":return U.Type.OBJECT;default:return U.Type.TYPE_UNSPECIFIED}}function Vn(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=_s(t.type),r={type:o,description:t.description};if(o===U.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===U.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(n)}var et=class extends M{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:Vn(this.mcpTool.inputSchema),response:Vn(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 jn=class extends Ne{constructor(e,t=[],o){super(t,o),this.mcpSessionManager=new Ze(e)}async getTools(){let t=await(await this.mcpSessionManager.createSession()).listTools();m.debug(`number of tools: ${t.tools.length}`);for(let o of t.tools)m.debug(`tool: ${o.name}`);return t.tools.map(o=>{let r={...o,name:this.prefix?`${this.prefix}_${o.name}`:o.name};return new et(r,this.mcpSessionManager)})}async close(){}};0&&(module.exports={ActiveStreamingTool,AgentTool,ApigeeLlm,AuthCredentialTypes,BaseAgent,BaseCodeExecutor,BaseExampleProvider,BaseLlm,BaseLlmRequestProcessor,BaseLlmResponseProcessor,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,Context,DatabaseSessionService,EXIT_LOOP,EventType,ExitLoopTool,FileArtifactService,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,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,geminiInitParams,getArtifactServiceFromUri,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,getLogger,getSessionServiceFromUri,hasTrailingCodeExecutionResult,isAgentTool,isBaseAgent,isBaseExampleProvider,isBaseLlm,isBaseTool,isBaseToolset,isFinalResponse,isFunctionTool,isGemini2OrAbove,isLlmAgent,isLoopAgent,isParallelAgent,isSequentialAgent,maybeSetOtelProviders,mergeStates,setLogLevel,setLogger,stringifyContent,toStructuredEvents,trimTempDeltaState,version,zodObjectToSchema});
|
|
88
90
|
/**
|
|
89
91
|
* @license
|
|
90
92
|
* Copyright 2025 Google LLC
|
|
91
93
|
* SPDX-License-Identifier: Apache-2.0
|
|
92
94
|
*/
|
|
95
|
+
/**
|
|
96
|
+
* @license
|
|
97
|
+
* Copyright 2026 Google LLC
|
|
98
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
99
|
+
*/
|
|
93
100
|
//# sourceMappingURL=index.js.map
|