@google/adk 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/functions.js +4 -0
- package/dist/cjs/auth/oauth2/oauth2_discovery.js +26 -2
- package/dist/cjs/code_executors/agent_engine_sandbox_code_executor.js +305 -0
- package/dist/cjs/code_executors/code_execution_utils.js +1 -1
- package/dist/cjs/common.js +19 -0
- package/dist/cjs/events/event.js +3 -1
- package/dist/cjs/index.js +97 -125
- package/dist/cjs/integrations/agent_registry/agent_registry.js +362 -0
- package/dist/cjs/integrations/agent_registry/agent_registry_mcp_toolset.js +103 -0
- package/dist/cjs/integrations/agent_registry/helpers.js +57 -0
- package/dist/cjs/integrations/agent_registry/types.js +50 -0
- package/dist/cjs/memory/vertex_ai_memory_bank_service.js +496 -0
- package/dist/cjs/runner/in_memory_runner.js +10 -5
- package/dist/cjs/runner/runner.js +32 -2
- package/dist/cjs/sessions/database_session_service.js +49 -3
- package/dist/cjs/sessions/in_memory_session_service.js +70 -14
- package/dist/cjs/sessions/registry.js +4 -0
- package/dist/cjs/sessions/vertex_ai_session_service.js +428 -0
- package/dist/cjs/tools/agent_tool.js +11 -6
- package/dist/cjs/tools/exit_loop_tool.js +9 -0
- package/dist/cjs/tools/function_tool.js +7 -2
- package/dist/cjs/tools/google_maps_grounding_tool.js +80 -0
- package/dist/cjs/tools/long_running_tool.js +2 -1
- package/dist/cjs/tools/mcp/mcp_session_manager.js +11 -0
- package/dist/cjs/tools/mcp/mcp_tool.js +12 -7
- package/dist/cjs/tools/mcp/mcp_toolset.js +27 -4
- package/dist/cjs/tools/openapi_tool/auth/auth_helpers.js +78 -0
- package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +84 -0
- package/dist/cjs/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +133 -0
- package/dist/cjs/tools/skill/load_skill_resource_tool.js +2 -25
- package/dist/cjs/tools/url_context_tool.js +73 -0
- package/dist/cjs/tools/vertex_ai_search_tool.js +127 -0
- package/dist/cjs/tools/vertex_rag_retrieval_tool.js +64 -0
- package/dist/cjs/utils/file_utils.js +28 -0
- package/dist/cjs/utils/gemini_schema_util.js +18 -0
- package/dist/cjs/utils/model_name.js +8 -2
- package/dist/cjs/utils/partial_copy.js +51 -0
- package/dist/cjs/utils/streaming_utils.js +167 -121
- package/dist/cjs/utils/vertex_ai_utils.js +50 -0
- package/dist/cjs/version.js +1 -1
- package/dist/esm/agents/functions.js +4 -0
- package/dist/esm/auth/oauth2/oauth2_discovery.js +26 -2
- package/dist/esm/code_executors/agent_engine_sandbox_code_executor.js +281 -0
- package/dist/esm/code_executors/code_execution_utils.js +1 -1
- package/dist/esm/common.js +15 -0
- package/dist/esm/events/event.js +3 -1
- package/dist/esm/index.js +54 -130
- package/dist/esm/integrations/agent_registry/agent_registry.js +333 -0
- package/dist/esm/integrations/agent_registry/agent_registry_mcp_toolset.js +77 -0
- package/dist/esm/integrations/agent_registry/helpers.js +28 -0
- package/dist/esm/integrations/agent_registry/types.js +20 -0
- package/dist/esm/memory/vertex_ai_memory_bank_service.js +468 -0
- package/dist/esm/runner/in_memory_runner.js +10 -5
- package/dist/esm/runner/runner.js +32 -2
- package/dist/esm/sessions/database_session_service.js +49 -3
- package/dist/esm/sessions/in_memory_session_service.js +70 -14
- package/dist/esm/sessions/registry.js +7 -0
- package/dist/esm/sessions/vertex_ai_session_service.js +403 -0
- package/dist/esm/tools/agent_tool.js +11 -6
- package/dist/esm/tools/exit_loop_tool.js +9 -0
- package/dist/esm/tools/function_tool.js +7 -2
- package/dist/esm/tools/google_maps_grounding_tool.js +54 -0
- package/dist/esm/tools/long_running_tool.js +2 -1
- package/dist/esm/tools/mcp/mcp_session_manager.js +11 -0
- package/dist/esm/tools/mcp/mcp_tool.js +12 -7
- package/dist/esm/tools/mcp/mcp_toolset.js +27 -4
- package/dist/esm/tools/openapi_tool/auth/auth_helpers.js +48 -0
- package/dist/esm/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +60 -0
- package/dist/esm/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +111 -0
- package/dist/esm/tools/skill/load_skill_resource_tool.js +1 -24
- package/dist/esm/tools/url_context_tool.js +44 -0
- package/dist/esm/tools/vertex_ai_search_tool.js +103 -0
- package/dist/esm/tools/vertex_rag_retrieval_tool.js +36 -0
- package/dist/esm/utils/file_utils.js +26 -0
- package/dist/esm/utils/gemini_schema_util.js +18 -0
- package/dist/esm/utils/model_name.js +6 -1
- package/dist/esm/utils/partial_copy.js +23 -0
- package/dist/esm/utils/streaming_utils.js +165 -120
- package/dist/esm/utils/vertex_ai_utils.js +22 -0
- package/dist/esm/version.js +1 -1
- package/dist/types/a2a/a2a_remote_agent.d.ts +14 -0
- package/dist/types/agents/processors/base_llm_processor.d.ts +12 -4
- package/dist/types/agents/processors/basic_llm_request_processor.d.ts +5 -0
- package/dist/types/agents/processors/identity_llm_request_processor.d.ts +4 -0
- package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +5 -0
- package/dist/types/agents/run_config.d.ts +15 -0
- package/dist/types/code_executors/agent_engine_sandbox_code_executor.d.ts +51 -0
- package/dist/types/common.d.ts +7 -0
- package/dist/types/events/event_actions.d.ts +24 -6
- package/dist/types/events/structured_events.d.ts +13 -0
- package/dist/types/examples/example_util.d.ts +25 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/integrations/agent_registry/agent_registry.d.ts +94 -0
- package/dist/types/integrations/agent_registry/agent_registry_mcp_toolset.d.ts +43 -0
- package/dist/types/integrations/agent_registry/helpers.d.ts +7 -0
- package/dist/types/integrations/agent_registry/types.d.ts +101 -0
- package/dist/types/memory/vertex_ai_memory_bank_service.d.ts +52 -0
- package/dist/types/runner/in_memory_runner.d.ts +28 -1
- package/dist/types/runner/runner.d.ts +47 -0
- package/dist/types/sessions/base_session_service.d.ts +18 -0
- package/dist/types/sessions/database_session_service.d.ts +1 -1
- package/dist/types/sessions/in_memory_session_service.d.ts +1 -1
- package/dist/types/sessions/vertex_ai_session_service.d.ts +37 -0
- package/dist/types/tools/exit_loop_tool.d.ts +9 -0
- package/dist/types/tools/function_tool.d.ts +22 -2
- package/dist/types/tools/google_maps_grounding_tool.d.ts +22 -0
- package/dist/types/tools/long_running_tool.d.ts +11 -1
- package/dist/types/tools/mcp/mcp_session_manager.d.ts +3 -0
- package/dist/types/tools/mcp/mcp_tool.d.ts +7 -1
- package/dist/types/tools/mcp/mcp_toolset.d.ts +7 -1
- package/dist/types/tools/openapi_tool/auth/auth_helpers.d.ts +25 -0
- package/dist/types/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.d.ts +20 -0
- package/dist/types/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.d.ts +20 -0
- package/dist/types/tools/url_context_tool.d.ts +17 -0
- package/dist/types/tools/vertex_ai_search_tool.d.ts +55 -0
- package/dist/types/tools/vertex_rag_retrieval_tool.d.ts +42 -0
- package/dist/types/utils/file_utils.d.ts +2 -0
- package/dist/types/utils/model_name.d.ts +4 -0
- package/dist/types/utils/partial_copy.d.ts +13 -0
- package/dist/types/utils/streaming_utils.d.ts +8 -17
- package/dist/types/utils/vertex_ai_utils.d.ts +14 -0
- package/dist/types/version.d.ts +1 -1
- package/dist/web/agents/functions.js +4 -0
- package/dist/web/auth/oauth2/oauth2_discovery.js +26 -2
- package/dist/web/code_executors/agent_engine_sandbox_code_executor.js +281 -0
- package/dist/web/code_executors/code_execution_utils.js +1 -1
- package/dist/web/common.js +15 -0
- package/dist/web/events/event.js +3 -1
- package/dist/web/index.js +54 -12
- package/dist/web/integrations/agent_registry/agent_registry.js +333 -0
- package/dist/web/integrations/agent_registry/agent_registry_mcp_toolset.js +90 -0
- package/dist/web/integrations/agent_registry/helpers.js +28 -0
- package/dist/web/integrations/agent_registry/types.js +20 -0
- package/dist/web/memory/vertex_ai_memory_bank_service.js +475 -0
- package/dist/web/runner/in_memory_runner.js +10 -5
- package/dist/web/runner/runner.js +32 -2
- package/dist/web/sessions/database_session_service.js +49 -3
- package/dist/web/sessions/in_memory_session_service.js +70 -14
- package/dist/web/sessions/registry.js +7 -0
- package/dist/web/sessions/vertex_ai_session_service.js +414 -0
- package/dist/web/tools/agent_tool.js +11 -6
- package/dist/web/tools/exit_loop_tool.js +9 -0
- package/dist/web/tools/function_tool.js +7 -2
- package/dist/web/tools/google_maps_grounding_tool.js +54 -0
- package/dist/web/tools/long_running_tool.js +2 -1
- package/dist/web/tools/mcp/mcp_session_manager.js +11 -0
- package/dist/web/tools/mcp/mcp_tool.js +12 -7
- package/dist/web/tools/mcp/mcp_toolset.js +27 -4
- package/dist/web/tools/openapi_tool/auth/auth_helpers.js +48 -0
- package/dist/web/tools/openapi_tool/auth/credential_exchangers/auto_auth_credential_exchanger.js +60 -0
- package/dist/web/tools/openapi_tool/auth/credential_exchangers/service_account_exchanger.js +111 -0
- package/dist/web/tools/skill/load_skill_resource_tool.js +1 -24
- package/dist/web/tools/url_context_tool.js +44 -0
- package/dist/web/tools/vertex_ai_search_tool.js +103 -0
- package/dist/web/tools/vertex_rag_retrieval_tool.js +36 -0
- package/dist/web/utils/file_utils.js +26 -0
- package/dist/web/utils/gemini_schema_util.js +18 -0
- package/dist/web/utils/model_name.js +6 -1
- package/dist/web/utils/partial_copy.js +23 -0
- package/dist/web/utils/streaming_utils.js +219 -121
- package/dist/web/utils/vertex_ai_utils.js +22 -0
- package/dist/web/version.js +1 -1
- package/package.json +3 -2
- package/dist/cjs/index.js.map +0 -7
- package/dist/esm/index.js.map +0 -7
- package/dist/web/index.js.map +0 -7
package/dist/cjs/index.js
CHANGED
|
@@ -4,133 +4,105 @@
|
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
"use strict";var gc=Object.create;var _t=Object.defineProperty;var Yr=Object.getOwnPropertyDescriptor;var hc=Object.getOwnPropertyNames;var Cc=Object.getPrototypeOf,vc=Object.prototype.hasOwnProperty;var Ac=(n,e)=>{for(var t in e)_t(n,t,{get:e[t],enumerable:!0})},Jr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hc(e))!vc.call(n,r)&&r!==t&&_t(n,r,{get:()=>e[r],enumerable:!(o=Yr(e,r))||o.enumerable});return n};var P=(n,e,t)=>(t=n!=null?gc(Cc(n)):{},Jr(e||!n||!n.__esModule?_t(t,"default",{value:n,enumerable:!0}):t,n)),Ec=n=>Jr(_t({},"__esModule",{value:!0}),n),v=(n,e,t,o)=>{for(var r=o>1?void 0:o?Yr(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&&_t(e,t,r),r};var $u={};Ac($u,{A2AAgentExecutor:()=>ht,AGENT_CARD_PATH:()=>wr.AGENT_CARD_PATH,ActiveStreamingTool:()=>eo,Agent:()=>Kt,AgentTool:()=>Co,AgentTransferLlmRequestProcessor:()=>qt,ApigeeLlm:()=>We,AuthCredentialTypes:()=>no,AuthHandler:()=>Ve,AuthProviderRegistry:()=>oo,BaseAgent:()=>q,BaseCodeExecutor:()=>Pe,BaseExampleProvider:()=>fo,BaseLlm:()=>ve,BaseLlmRequestProcessor:()=>B,BaseLlmResponseProcessor:()=>In,BasePlugin:()=>ie,BaseSessionService:()=>Le,BaseTool:()=>w,BaseToolset:()=>xe,BuiltInCodeExecutor:()=>mt,CONTENT_REQUEST_PROCESSOR:()=>Wt,CodeExecutionLanguage:()=>ye,ContentRequestProcessor:()=>zt,Context:()=>F,ContextCompactionTrigger:()=>Ln,ContextCompactorRequestProcessor:()=>Qe,CredentialExchangeError:()=>V,CredentialRefresherRegistry:()=>ao,DatabaseSessionService:()=>bt,EXIT_LOOP:()=>Pa,EventType:()=>_r,ExitLoopTool:()=>en,FeatureName:()=>Ho,FeatureStage:()=>qi,FileArtifactService:()=>vt,FileContentEncoding:()=>kn,FunctionTool:()=>fe,GOOGLE_SEARCH:()=>_a,GcsArtifactService:()=>At,Gemini:()=>Ee,GoogleLLMVariant:()=>Dt,GoogleSearchTool:()=>tn,InMemoryArtifactService:()=>Oe,InMemoryCredentialService:()=>ro,InMemoryMemoryService:()=>Ne,InMemoryPolicyEngine:()=>Qt,InMemoryRunner:()=>go,InMemorySessionService:()=>Z,InvocationContext:()=>J,LLMRegistry:()=>ke,LOAD_ARTIFACTS:()=>Oa,LOAD_MEMORY:()=>Ma,ListSkillsTool:()=>Fe,LiveRequestQueue:()=>to,LlmAgent:()=>Kt,LlmSummarizer:()=>co,LoadArtifactsTool:()=>nn,LoadMemoryTool:()=>on,LoadSkillResourceTool:()=>Be,LoadSkillTool:()=>De,LogLevel:()=>Lo,LoggingPlugin:()=>po,LongRunningFunctionTool:()=>Ao,LoopAgent:()=>Mn,MCPSessionManager:()=>cn,MCPTool:()=>ln,MCPToolset:()=>Hr,OAuth2CredentialExchanger:()=>ct,OAuth2DiscoveryManager:()=>so,OAuthGrantType:()=>pn,PRELOAD_MEMORY:()=>Fa,ParallelAgent:()=>Nn,PluginManager:()=>gt,PolicyOutcome:()=>Nr,PreloadMemoryTool:()=>rn,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Mr,ReadonlyContext:()=>b,RemoteA2AAgent:()=>qn,RoutedAgent:()=>St,RoutedLlm:()=>wt,RunSkillInlineScriptTool:()=>Ue,RunSkillScriptTool:()=>$e,Runner:()=>de,SecurityPlugin:()=>mo,SequentialAgent:()=>Fn,SessionStateCredentialService:()=>io,SkillToolset:()=>It,State:()=>T,StreamingMode:()=>Ht,TokenBasedContextCompactor:()=>lo,ToolConfirmation:()=>we,TruncatingContextCompactor:()=>uo,UnsafeLocalCodeExecutor:()=>Qn,createEvent:()=>x,createEventActions:()=>j,createSession:()=>Te,functionsExportedForTestingOnly:()=>Ni,geminiInitParams:()=>$t,getA2AAgentCard:()=>Un,getArtifactServiceFromUri:()=>ma,getAskUserConfirmationFunctionCalls:()=>wa,getFeatureConfig:()=>Tn,getFunctionCalls:()=>_,getFunctionResponses:()=>Y,getGcpExporters:()=>Ou,getGcpResource:()=>Mu,getLogger:()=>dn,getSessionServiceFromUri:()=>za,hasTrailingCodeExecutionResult:()=>wo,isAgentTool:()=>ka,isBaseAgent:()=>vi,isBaseExampleProvider:()=>Ta,isBaseLlm:()=>En,isBaseTool:()=>dt,isBaseToolset:()=>Bn,isCompactedEvent:()=>X,isFeatureEnabled:()=>Ko,isFinalResponse:()=>he,isFunctionTool:()=>es,isGemini2OrAbove:()=>pt,isLlmAgent:()=>y,isLoopAgent:()=>Ze,isParallelAgent:()=>et,isRoutedAgent:()=>Aa,isRunner:()=>jn,isSequentialAgent:()=>tt,loadAllSkillsInDir:()=>Ja,loadSkillFromDir:()=>zr,maybeSetOtelProviders:()=>Nu,mergeStates:()=>pe,overrideFeatureEnabled:()=>nl,registerFeature:()=>tl,setLogLevel:()=>di,setLogger:()=>fi,stringifyContent:()=>st,toA2a:()=>oa,toStructuredEvents:()=>ya,trimTempDeltaState:()=>Vn,validateSkillDir:()=>Ka,version:()=>at,withTemporaryFeatureOverride:()=>ol,zodObjectToSchema:()=>Ke});module.exports=Ec($u);var wr=require("@a2a-js/sdk"),Hs=require("@a2a-js/sdk/client");var lt=require("@opentelemetry/api");function Xr(n,e=[]){return un(n,yc,"",e)}function Qr(n,e=[]){return un(n,xc,"",e)}var yc=n=>n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),xc=n=>n.replace(/[A-Z]/g,e=>"_"+e.toLowerCase());function un(n,e,t="",o=[]){if(Array.isArray(n))return n.map(r=>un(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]=un(r[s],e,c,o)}return i}return n}function j(n={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...n}}function Zr(n,e){let t=j();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 x(n={}){return{...n,id:n.id||Io(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||j(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()}}function he(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:_(n).length===0&&Y(n).length===0&&!n.partial&&!wo(n)}function _(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 Y(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 wo(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 st(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 ei="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Io(){let n="";for(let e=0;e<8;e++)n+=ei[Math.floor(Math.random()*ei.length)];return n}var Tc=["actions.stateDelta","actions.artifactDelta","actions.requestedAuthConfigs","actions.requestedToolConfirmations","actions.customMetadata","content.parts.functionCall.args","content.parts.functionResponse.response"],Sc=["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 bo(n){return Xr(n,Sc)}function ti(n){return Qr(n,Tc)}var ae=require("@opentelemetry/api");var at="1.0.0";var Rc="gen_ai.agent.description",wc="gen_ai.agent.name",Ic="gen_ai.conversation.id",ko="gen_ai.operation.name",ni="gen_ai.tool.call.id",oi="gen_ai.tool.description",ri="gen_ai.tool.name",bc="gen_ai.tool.type",ce=ae.trace.getTracer("gcp.vertex.agent",at);function Lt(n){try{return JSON.stringify(n)}catch{return"<not serializable>"}}function ii({agent:n,invocationContext:e}){let t=ae.trace.getActiveSpan();t&&t.setAttributes({[ko]:"invoke_agent",[Rc]:n.description,[wc]:n.name,[Ic]:e.session.id})}function si({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=ae.trace.getActiveSpan();if(!o)return;o.setAttributes({[ko]:"execute_tool",[oi]:n.description||"",[ri]:n.name,[bc]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":Ot()?Lt(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({[ni]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":Ot()?Lt(i):"{}"})}function ai({responseEventId:n,functionResponseEvent:e}){let t=ae.trace.getActiveSpan();t&&(t.setAttributes({[ko]:"execute_tool",[ri]:"(merged tools)",[oi]:"(merged tools)",[ni]: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",Ot()?Lt(e):"{}"))}function ci({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=ae.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":Ot()?Lt(kc(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",Ot()?Lt(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 kc(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 li(n,e){return{next:ae.context.bind(n,e.next.bind(e)),return:ae.context.bind(n,e.return.bind(e)),throw:ae.context.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return li(n,e[Symbol.asyncIterator]())}}}function Ge(n,e,t){let o=t.call(e);return li(n,o)}function Ot(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}function oe(){return typeof window<"u"}var fn="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function k(){let n="";for(let e=0;e<fn.length;e++){let t=Math.random()*16|0;fn[e]==="x"?n+=t.toString(16):fn[e]==="y"?n+=(t&3|8).toString(16):n+=fn[e]}return n}function ui(n){return oe()?window.atob(n):Buffer.from(n,"base64").toString()}function je(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var re=P(require("winston"),1);var Lo=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Lo||{}),Po=class{constructor(){this.logLevel=1;this.logger=re.createLogger({levels:{debug:0,info:1,warn:2,error:3},level:"error",format:re.format.combine(re.format.label({label:"ADK"}),re.format(e=>(e.level=e.level.toUpperCase(),e))(),re.format.colorize(),re.format.timestamp(),re.format.printf(e=>`${e.level}: [${e.label}] ${e.timestamp} ${e.message}`)),transports:[new re.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(" "))}},_o=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},Re=new Po;function fi(n){Re=n!=null?n:new _o}function dn(){return Re}function di(n){m.setLogLevel(n)}var m={setLogLevel(n){Re.setLogLevel(n)},log(n,...e){Re.log(n,...e)},debug(...n){Re.debug(...n)},info(...n){Re.info(...n)},warn(...n){Re.warn(...n)},error(...n){Re.error(...n)}};var pn=(r=>(r.CLIENT_CREDENTIALS="client_credentials",r.AUTHORIZATION_CODE="authorization_code",r.IMPLICIT="implicit",r.PASSWORD="password",r))(pn||{});function pi(n){if(n.clientCredentials)return"client_credentials";if(n.authorizationCode)return"authorization_code";if(n.implicit)return"implicit";if(n.password)return"password"}var V=class extends Error{};function Oo(n){if(n.type==="openIdConnect"&&n.tokenEndpoint)return n.tokenEndpoint;if(n.type==="oauth2"&&n.flows){let e=n.flows,t=e.authorizationCode||e.clientCredentials||e.password||e.implicit;if(t&&"tokenUrl"in t)return t.tokenUrl}}async function Mo(n,e){try{let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!t.ok)throw new Error(`Token request failed with status ${t.status}`);let o=await t.json();return{accessToken:o.access_token,refreshToken:o.refresh_token,idToken:o.id_token,expiresIn:o.expires_in,expiresAt:o.expires_in?Date.now()+o.expires_in*1e3:void 0}}catch(t){throw m.error(`Failed to fetch OAuth2 tokens: ${t}`),t}}function mi(n){try{return new URL(n).searchParams.get("code")||void 0}catch(e){m.warn(`Failed to parse authorization URI ${n}: ${e}`);return}}function No(n){let e=new URLSearchParams;return e.set("grant_type",n.grantType),e.set("client_id",n.clientId),e.set("client_secret",n.clientSecret),n.grantType==="authorization_code"?(e.set("code",n.code),n.redirectUri&&e.set("redirect_uri",n.redirectUri),n.codeVerifier&&e.set("code_verifier",n.codeVerifier)):n.grantType==="refresh_token"&&e.set("refresh_token",n.refreshToken),e}var ct=class{async exchange({authCredential:e,authScheme:t}){var r;if(!t)throw new V("authScheme is required for OAuth2 credential exchange");if((r=e.oauth2)!=null&&r.accessToken)return{credential:e,wasExchanged:!1};let o=Pc(t);return o==="client_credentials"?_c({authCredential:e,authScheme:t}):o==="authorization_code"?Lc({authCredential:e,authScheme:t}):(m.warn(`Unsupported OAuth2 grant type: ${o}`),{credential:e,wasExchanged:!1})}};function Pc(n){var e;if("flows"in n&&n.flows)return pi(n.flows);if(n.grantTypesSupported)return(e=n.grantTypesSupported)!=null&&e.includes("client_credentials")?"client_credentials":"authorization_code"}async function _c({authCredential:n,authScheme:e}){var r,i;let t=Oo(e);if(!t)throw new V("Token endpoint not found in auth scheme.");if(!((r=n.oauth2)!=null&&r.clientId)||!((i=n.oauth2)!=null&&i.clientSecret))throw new V("clientId and clientSecret are required for client credentials exchange.");let o=No({grantType:"client_credentials",clientId:n.oauth2.clientId,clientSecret:n.oauth2.clientSecret});try{let s=await Mo(t,o);return{credential:{...n,oauth2:{...n.oauth2,...s}},wasExchanged:!0}}catch(s){throw new V(`Failed to exchange tokens: ${s instanceof Error?s.message:String(s)}`)}}async function Lc({authCredential:n,authScheme:e}){var i,s,a,c;let t=Oo(e);if(!t)throw new V("Token endpoint not found in auth scheme.");if(!((i=n.oauth2)!=null&&i.clientId)||!((s=n.oauth2)!=null&&s.clientSecret)||!((a=n.oauth2)!=null&&a.authCode)&&!((c=n.oauth2)!=null&&c.authResponseUri))throw new V("clientId, clientSecret, and either authCode or authResponseUri are required for authorization code exchange.");let o=n.oauth2.authCode;if(!o&&n.oauth2.authResponseUri&&(o=mi(n.oauth2.authResponseUri)),n.oauth2.authResponseUri&&n.oauth2.state)try{let u=new URL(n.oauth2.authResponseUri).searchParams.get("state")||void 0;if(n.oauth2.state!==u)throw new V("State mismatch detected. Potential CSRF attack.")}catch(l){throw new V(`Failed to parse authResponseUri for state validation: ${l instanceof Error?l.message:String(l)}`)}if(!o)throw new V("Authorization code not found in auth response.");let r=No({grantType:"authorization_code",clientId:n.oauth2.clientId,clientSecret:n.oauth2.clientSecret,code:o,redirectUri:n.oauth2.redirectUri,codeVerifier:n.oauth2.codeVerifier});try{let l=await Mo(t,r);return{credential:{...n,oauth2:{...n.oauth2,...l}},wasExchanged:!0}}catch(l){throw new V(`Failed to exchange tokens: ${l instanceof Error?l.message:String(l)}`)}}var Ve=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}async parseAndStoreAuthResponse(e){let t="temp:"+this.authConfig.credentialKey,o=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(o)){e.set(t,this.authConfig.exchangedAuthCredential);return}if(this.authConfig.exchangedAuthCredential){let i=await new ct().exchange({authCredential:this.authConfig.exchangedAuthCredential,authScheme:this.authConfig.authScheme});e.set(t,i.credential)}}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(){let e=this.authConfig.authScheme,t=this.authConfig.rawAuthCredential;if(!t||!t.oauth2)return t;let o="",r=[];if("authorizationEndpoint"in e)o=e.authorizationEndpoint,r=e.scopes||[];else if(e.type==="oauth2"&&e.flows){let c=e.flows,l=c.implicit||c.authorizationCode||c.clientCredentials||c.password;l&&("authorizationUrl"in l&&l.authorizationUrl?o=l.authorizationUrl:"tokenUrl"in l&&l.tokenUrl&&(o=l.tokenUrl),l.scopes&&(r=Object.keys(l.scopes)))}if(!o)throw new Error("Authorization endpoint not configured in auth scheme.");let i=k(),s=new URL(o);return s.searchParams.set("client_id",t.oauth2.clientId||""),s.searchParams.set("redirect_uri",t.oauth2.redirectUri||""),s.searchParams.set("response_type","code"),s.searchParams.set("scope",r.join(" ")),s.searchParams.set("state",i),s.searchParams.set("access_type","offline"),s.searchParams.set("prompt","consent"),{...t,oauth2:{...t.oauth2,authUri:s.toString(),state:i}}}};var T=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){Object.assign(this.delta,e),Object.assign(this.value,e)}toRecord(){return{...this.value,...this.delta}}};T.APP_PREFIX="app:",T.USER_PREFIX="user:",T.TEMP_PREFIX="temp:";var we=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var b=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 T(this.invocationContext.session.state,{})}};var F=class extends b{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||j(),this._state=new T(e.invocationContext.session.state,this.eventActions.stateDelta),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation,this.abortSignal=e.invocationContext.abortSignal}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 Ve(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ve(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 we({hint:e,confirmed:!1,payload:t})}};var Fo=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`)}},J=class{constructor(e){this.invocationCostManager=new Fo;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,this.abortSignal=e.abortSignal}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function gi(){return`e-${k()}`}var Bo=Symbol.for("google.adk.baseAgent");function vi(n){return typeof n=="object"&&n!==null&&Bo in n&&n[Bo]===!0}var Ci;Ci=Bo;var q=class{constructor(e){this[Ci]=!0;this.name=Oc(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=hi(e.beforeAgentCallback),this.afterAgentCallback=hi(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return Nc(this)}async*runAsync(e){let t=ce.startSpan(`invoke_agent ${this.name}`),o=lt.trace.setSpan(lt.context.active(),t);try{yield*Ge(o,this,async function*(){var a,c;let r=this.createInvocationContext(e),i=await this.handleBeforeAgentCallback(r);if(i&&(yield i),r.endInvocation||(a=e.abortSignal)!=null&&a.aborted)return;ii({agent:this,invocationContext:r});for await(let l of this.runAsyncImpl(r))yield l;if(r.endInvocation||(c=e.abortSignal)!=null&&c.aborted)return;let s=await this.handleAfterAgentCallback(r);s&&(yield s)})}finally{t.end()}}async*runLive(e){let t=ce.startSpan(`invoke_agent ${this.name}`),o=lt.trace.setSpan(lt.context.active(),t);try{throw yield*Ge(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 J({...e,agent:this})}async handleBeforeAgentCallback(e){var o;if(this.beforeAgentCallback.length===0)return;let t=new F({invocationContext:e});for(let r of this.beforeAgentCallback){let i=await r(t);if((o=e.abortSignal)!=null&&o.aborted)return;if(i)return e.endInvocation=!0,x({invocationId:e.invocationId,author:this.name,branch:e.branch,content:i,actions:t.eventActions})}if(t.state.hasDelta())return x({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){var o;if(this.afterAgentCallback.length===0)return;let t=new F({invocationContext:e});for(let r of this.afterAgentCallback){let i=await r(t);if((o=e.abortSignal)!=null&&o.aborted)return;if(i)return x({invocationId:e.invocationId,author:this.name,branch:e.branch,content:i,actions:t.eventActions})}if(t.state.hasDelta())return x({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 Oc(n){if(!Mc(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 Mc(n){return/^[\p{ID_Start}$_][\p{ID_Continue}$_-]*$/u.test(n)}function Nc(n){for(;n.parentAgent;)n=n.parentAgent;return n}function hi(n){return n?Array.isArray(n)?n:[n]:[]}function Ie(n){return(n==null?void 0:n.kind)==="status-update"}function Mt(n){return(n==null?void 0:n.kind)==="artifact-update"}function Do(n){return(n==null?void 0:n.kind)==="message"}function le(n){return(n==null?void 0:n.kind)==="task"}function mn(n){return Mt(n)?n.artifact.metadata||{}:Ie(n)||le(n)||Do(n)?n.metadata||{}:{}}function gn(n){return(Ie(n)||le(n))&&n.status.state==="failed"}function Ai(n){return(Ie(n)||le(n))&&["completed","failed","canceled","rejected"].includes(n.status.state)}function hn(n){return(Ie(n)||le(n))&&n.status.state==="input-required"}function Uo(n){var t;if(!gn(n))return;let e=((t=n.status.message)==null?void 0:t.parts)||[];if(e.length!==0&&e[0].kind==="text")return e[0].text}function Ei({contextId:n,message:e,taskId:t,metadata:o}){return{kind:"task",id:t||k(),contextId:n,history:[e],status:{state:"submitted",timestamp:new Date().toISOString()},metadata:o}}function yi({taskId:n,contextId:e,message:t,metadata:o}){return{kind:"status-update",taskId:n,contextId:e,final:!1,status:{state:"working",message:t,timestamp:new Date().toISOString()},metadata:o}}function xi({taskId:n,contextId:e,metadata:t}){return{kind:"status-update",taskId:n,contextId:e,final:!0,status:{state:"completed",timestamp:new Date().toISOString()},metadata:t}}function Ti({taskId:n,contextId:e,artifactId:t,parts:o=[],metadata:r,append:i,lastChunk:s}){return{kind:"artifact-update",taskId:n,contextId:e,append:i,lastChunk:s,artifact:{artifactId:t||k(),parts:o},metadata:r}}function Cn({taskId:n,contextId:e,error:t,metadata:o}){return{kind:"status-update",taskId:n,contextId:e,final:!0,status:{state:"failed",message:{kind:"message",messageId:k(),role:"agent",taskId:n,contextId:e,parts:[{kind:"text",text:t.message}]},timestamp:new Date().toISOString()},metadata:o}}function Si({taskId:n,contextId:e,parts:t,metadata:o}){return{kind:"status-update",taskId:n,contextId:e,final:!0,status:{state:"input-required",message:{kind:"message",messageId:k(),role:"agent",taskId:n,contextId:e,parts:t},timestamp:new Date().toISOString()},metadata:o}}function Ri({taskId:n,contextId:e,parts:t,metadata:o}){return{kind:"status-update",taskId:n,contextId:e,final:!0,status:{state:"input-required",message:{kind:"message",messageId:k(),role:"agent",taskId:n,contextId:e,parts:t},timestamp:new Date().toISOString()},metadata:o}}var Ii=require("@google/genai");var O="adk_",wi="a2a:",E=(I=>(I.APP_NAME=`${O}app_name`,I.USER_ID=`${O}user_id`,I.SESSION_ID=`${O}session_id`,I.INVOCATION_ID=`${O}invocation_id`,I.AUTHOR=`${O}author`,I.BRANCH=`${O}branch`,I.DATA_PART_TYPE=`${O}type`,I.PARTIAL=`${O}partial`,I.ESCALATE=`${O}escalate`,I.TRANSFER_TO_AGENT=`${O}transfer_to_agent`,I.IS_LONG_RUNNING=`${O}is_long_running`,I.THOUGHT=`${O}thought`,I.ERROR_CODE=`${O}error_code`,I.ERROR_MESSAGE=`${O}error_message`,I.CITATION_METADATA=`${O}citation_metadata`,I.GROUNDING_METADATA=`${O}grounding_metadata`,I.USAGE_METADATA=`${O}usage_metadata`,I.CUSTOM_METADATA=`${O}custom_metadata`,I.VIDEO_METADATA=`${O}video_metadata`,I))(E||{}),Nt=(t=>(t.TASK_ID=`${wi}task_id`,t.CONTEXT_ID=`${wi}context_id`,t))(Nt||{});function Ft(n,{appName:e,userId:t,sessionId:o}){return{...Bt(n.actions),...be({appName:e,userId:t,sessionId:o}),[E.INVOCATION_ID]:n.invocationId,[E.AUTHOR]:n.author,[E.BRANCH]:n.branch,[E.ERROR_CODE]:n.errorMessage,[E.ERROR_MESSAGE]:n.errorMessage,[E.CITATION_METADATA]:n.citationMetadata,[E.GROUNDING_METADATA]:n.groundingMetadata,[E.USAGE_METADATA]:n.usageMetadata,[E.CUSTOM_METADATA]:n.customMetadata,[E.PARTIAL]:n.partial,[E.IS_LONG_RUNNING]:(n.longRunningToolIds||[]).length>0}}function be({appName:n,userId:e,sessionId:t}){return{[E.APP_NAME]:n,[E.USER_ID]:e,[E.SESSION_ID]:t}}function Bt(n){return{[E.ESCALATE]:n.escalate,[E.TRANSFER_TO_AGENT]:n.transferToAgent}}var vn=class{constructor(e){this.request=e;this.aggregations=new Map;this.aggregationOrder=[]}aggregatePartial(e,t,o){if(mn(t)[E.PARTIAL])return[o];if(Ie(t)&&t.final){let a=[];for(let c of this.aggregationOrder){let l=this.aggregations.get(c);l&&a.push(this.buildNonPartialAggregation(e,l))}return this.aggregations.clear(),this.aggregationOrder=[],[...a,o]}if(le(t))return this.aggregations.clear(),this.aggregationOrder=[],[o];if(!Mt(t))return[o];let i=t.artifact.artifactId;if(!t.append&&(this.removeAggregation(i),t.lastChunk))return o.partial=!1,[o];let s=this.aggregations.get(i);return s?(this.aggregationOrder=this.aggregationOrder.filter(a=>a!==i),this.aggregationOrder.push(i)):(s={aggregatedText:"",aggregatedThoughts:"",parts:[]},this.aggregations.set(i,s),this.aggregationOrder.push(i)),this.updateAggregation(s,o),t.lastChunk?(this.removeAggregation(i),[o,this.buildNonPartialAggregation(e,s)]):[o]}removeAggregation(e){this.aggregations.delete(e),this.aggregationOrder=this.aggregationOrder.filter(t=>t!==e)}updateAggregation(e,t){var r;let o=((r=t.content)==null?void 0:r.parts)||[];for(let i of o)i.text&&i.text!==""?i.thought?e.aggregatedThoughts+=i.text:e.aggregatedText+=i.text:(this.promoteTextBlocksToParts(e),e.parts.push(i));t.citationMetadata&&(e.citations||(e.citations={citations:[]}),e.citations.citations||(e.citations.citations=[]),e.citations.citations.push(...t.citationMetadata.citations||[])),t.customMetadata&&(e.customMeta||(e.customMeta={}),Object.assign(e.customMeta,t.customMetadata)),t.groundingMetadata&&(e.grounding=t.groundingMetadata),t.usageMetadata&&(e.usage=t.usageMetadata)}buildNonPartialAggregation(e,t){return this.promoteTextBlocksToParts(t),x({author:e.agent.name,invocationId:e.invocationId,content:t.parts.length>0?(0,Ii.createModelContent)([...t.parts]):void 0,customMetadata:t.customMeta,groundingMetadata:t.grounding,citationMetadata:t.citations,usageMetadata:t.usage,turnComplete:!1,partial:!1})}promoteTextBlocksToParts(e){e.aggregatedThoughts!==""&&(e.parts.push({thought:!0,text:e.aggregatedThoughts}),e.aggregatedThoughts=""),e.aggregatedText!==""&&(e.parts.push({text:e.aggregatedText}),e.aggregatedText="")}updateCustomMetadata(e,t){let o={};if(this.request&&e.turnComplete&&(o.request=this.request),t&&(o.response=t,le(t)?(t.id&&(o.task_id=t.id),t.contextId&&(o.context_id=t.contextId)):t.taskId&&(o.task_id=t.taskId,t.contextId&&(o.context_id=t.contextId))),Object.keys(o).length!==0){e.customMetadata||(e.customMetadata={});for(let[r,i]of Object.entries(o))i!=null&&(e.customMetadata[`a2a:${r}`]=i)}}};var An=require("@google/genai");function Ce(n=[],e=[]){return n.map(t=>Fc(t,e))}function Fc(n,e){return n.text!==void 0&&n.text!==null?Bc(n):n.inlineData||n.fileData?Dc(n):Uc(n,e)}function Bc(n){let e={kind:"text",text:n.text||""};return n.thought&&(e.metadata={[E.THOUGHT]:!0}),e}function Dc(n){let e={};if(n.videoMetadata&&(e[E.VIDEO_METADATA]=n.videoMetadata),n.fileData)return{kind:"file",file:{uri:n.fileData.fileUri||"",mimeType:n.fileData.mimeType},metadata:e};if(n.inlineData)return{kind:"file",file:{bytes:n.inlineData.data||"",mimeType:n.inlineData.mimeType},metadata:e};throw new Error(`Not a file part: ${JSON.stringify(n)}`)}function Uc(n,e=[]){let t,o;if(n.functionCall)t="function_call",o=n.functionCall;else if(n.functionResponse)t="function_response",o=n.functionResponse;else if(n.executableCode)t="executable_code",o=n.executableCode;else if(n.codeExecutionResult)t="code_execution_result",o=n.codeExecutionResult;else return{kind:"data",data:{},metadata:{}};let r={[E.DATA_PART_TYPE]:t};return n.functionCall&&n.functionCall.id&&e.includes(n.functionCall.id)&&(r[E.IS_LONG_RUNNING]=!0),n.functionResponse&&n.functionResponse.id&&e.includes(n.functionResponse.id)&&(r[E.IS_LONG_RUNNING]=!0),{kind:"data",data:o,metadata:r}}function bi(n){let e=ue(n.parts);return n.role==="user"?(0,An.createUserContent)(e):(0,An.createModelContent)(e)}function ue(n){return n.map(e=>$o(e))}function $o(n){if(n.kind==="text")return $c(n);if(n.kind==="file")return qc(n);if(n.kind==="data")return Gc(n);throw new Error(`Unknown part kind: ${JSON.stringify(n)}`)}function $c(n){var e;return{text:n.text,thought:!!((e=n.metadata)!=null&&e[E.THOUGHT])}}function qc(n){var t;let e={};if((t=n.metadata)!=null&&t[E.VIDEO_METADATA]&&(e.videoMetadata=n.metadata[E.VIDEO_METADATA]),"bytes"in n.file)return e.inlineData={data:n.file.bytes,mimeType:n.file.mimeType||""},e;if("uri"in n.file)return e.fileData={fileUri:n.file.uri,mimeType:n.file.mimeType||""},e;throw new Error(`Not a file part: ${JSON.stringify(n)}`)}function Gc(n){var o;if(!n.data)throw new Error(`No data in part: ${JSON.stringify(n)}`);let e=n.data,t=(o=n.metadata)==null?void 0:o[E.DATA_PART_TYPE];return t==="function_call"?{functionCall:e}:t==="function_response"?{functionResponse:e}:t==="executable_code"?{executableCode:e}:t==="code_execution_result"?{codeExecutionResult:e}:{text:JSON.stringify(n.data)}}function ki(n,e){let t=n.events;if(e<0||e>=t.length)return;let o=t[e];if(o.author!=="user")return;let r=Vc(o);if(r)for(let i=e-1;i>=0;i--){let s=t[i];if(!jc(s,r))continue;let a=s.customMetadata||{},c=a[Nt.TASK_ID]||"",l=a[Nt.CONTEXT_ID]||"";return{response:o,taskId:c,contextId:l}}}function jc(n,e){return!n||!n.content||!n.content.parts?!1:n.content.parts.some(t=>t.functionCall&&t.functionCall.id===e)}function Vc(n){var t;if(!n||!n.content||!n.content.parts)return;let e=n.content.parts.find(o=>o.functionResponse);return(t=e==null?void 0:e.functionResponse)==null?void 0:t.id}function Pi(n,e){let t=e.events,o,r=-1;for(let s=t.length-1;s>=0;s--){let a=t[s];if(a.author===n.agent.name){r=s,o=(a.customMetadata||{})[Nt.CONTEXT_ID];break}}let i=[];for(let s=r+1;s<t.length;s++){let a=t[s];if(a.author!=="user"&&a.author!==n.agent.name&&(a=zc(n,a)),!a.content||!a.content.parts||a.content.parts.length===0)continue;let c=Ce(a.content.parts,a.longRunningToolIds);i.push(...c)}return{parts:i,contextId:o}}function zc(n,e){let t=x({author:"user",invocationId:n.invocationId});if(!e.content||!e.content.parts)return t;let o=[{text:"For context:"}];for(let r of e.content.parts)if(!r.thought)if(r.text)o.push({text:`[${e.author}] said: ${r.text}`});else if(r.functionCall){let i=r.functionCall;o.push({text:`[${e.author}] called tool ${i.name} with parameters: ${JSON.stringify(i.args)}`})}else if(r.functionResponse){let i=r.functionResponse;o.push({text:`[${e.author}] ${i.name} tool returned result: ${JSON.stringify(i.response)}`})}else o.push(r);return o.length>1&&(t.content={role:"user",parts:o}),t}var js=require("@a2a-js/sdk/client"),Vs=P(require("fs/promises"),1);var On=require("@opentelemetry/api");var Wc="google-adk",Hc="gl-typescript",Kc="remote_reasoning_engine",Yc="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Jc(){let n=`${Wc}/${at}`;!oe()&&process.env[Yc]&&(n=`${n}+${Kc}`);let e=`${Hc}/${oe()?window.navigator.userAgent:process.version}`;return[n,e]}function _i(){return Jc()}var qo=Symbol.for("google.adk.baseModel");function En(n){return typeof n=="object"&&n!==null&&qo in n&&n[qo]===!0}var Li;Li=qo;var ve=class{constructor({model:e}){this[Li]=!0;this.model=e}get trackingHeaders(){let t=_i().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."}]})}};ve.supportedModels=[];var ft=require("@google/genai");var Dt=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Dt||{});function Oi(){return je("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}var Ut=require("@google/genai"),Yo=require("jsonpath-plus");var Mi=require("@google/genai"),jo=require("lodash-es");var Go="adk-",yn="adk_request_credential",ut="adk_request_confirmation",Ni={handleFunctionCallList:xn,generateAuthEvent:Vo,generateRequestConfirmationEvent:zo};function ze(){return`${Go}${k()}`}function Fi(n){let e=_(n);if(e)for(let t of e)t.id||(t.id=ze())}function Bi(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Go)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Go)&&(e.functionResponse.id=void 0)}function Di(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 Vo(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||(0,jo.isEmpty)(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:yn,args:{function_call_id:i,auth_config:s},id:ze()};o.add(a.id),t.push({functionCall:a})}return x({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function zo({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||(0,jo.isEmpty)(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=_(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:ut,args:{originalFunctionCall:u,toolConfirmation:l},id:ze()};r.add(f.id),o.push({functionCall:f})}return x({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 Xc(n,e,t){return ce.startActiveSpan(`execute_tool ${n.name}`,async o=>{try{m.debug(`callToolAsync ${n.name}`);let r=await n.runAsync({args:e,toolContext:t});return si({tool:n,args:e,functionResponseEvent:Qc(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function Qc(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 x({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function Ui({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=_(e);return await xn({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function xn({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:p,toolContext:g}=Zc({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:d});m.debug(`execute_tool ${p.name}`);let C=(u=f.args)!=null?u:{},h=null,A;if(h=await n.pluginManager.runBeforeToolCallback({tool:p,toolArgs:C,toolContext:g}),h==null){for(let K of o)if(h=await K({tool:p,args:C,context:g}),h)break}if(h==null)try{h=await Xc(p,C,g)}catch(K){if(K instanceof Error){let kt=await n.pluginManager.runOnToolErrorCallback({tool:p,toolArgs:C,toolContext:g,error:K});kt?h=kt:A=K.message}else A=K}let H=await n.pluginManager.runAfterToolCallback({tool:p,toolArgs:C,toolContext:g,result:h});if(H==null){for(let K of r)if(H=await K({tool:p,args:C,context:g,response:h}),H)break}if(H!=null&&(h=H),p.isLongRunning&&!h)continue;A?h={error:A}:(typeof h!="object"||h==null)&&(h={result:h});let I=x({invocationId:n.invocationId,author:n.agent.name,content:(0,Mi.createUserContent)({functionResponse:{id:g.functionCallId,name:p.name,response:h}}),actions:g.actions,branch:n.branch});m.debug("traceToolCall",{tool:p.name,args:C,functionResponseEvent:I.id}),a.push(I)}if(!a.length)return null;let l=el(a);return a.length>1&&ce.startActiveSpan("execute_tool (merged)",f=>{try{m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),ai({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function Zc({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 el(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=Zr(o);return x({invocationId:t.invocationId,author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Ho=(e=>(e.PROGRESSIVE_SSE_STREAMING="PROGRESSIVE_SSE_STREAMING",e))(Ho||{}),qi=(o=>(o.WIP="wip",o.EXPERIMENTAL="experimental",o.STABLE="stable",o))(qi||{}),Gi={PROGRESSIVE_SSE_STREAMING:{stage:"experimental",defaultOn:!1}},$i=new Set,Ae={};function Tn(n){return Gi[n]}function tl(n,e){Gi[n]=e}function nl(n,e){if(!Tn(n))throw new Error(`Feature ${n} is not registered.`);e===void 0?delete Ae[n]:Ae[n]=e}function Ko(n){let e=Tn(n);if(!e)throw new Error(`Feature ${n} is not registered.`);if(n in Ae){let r=Ae[n];return r&&e.stage!=="stable"&&Wo(n,e.stage),r}let t=`ADK_ENABLE_${n}`,o=`ADK_DISABLE_${n}`;return je(t)?(e.stage!=="stable"&&Wo(n,e.stage),!0):je(o)?!1:(e.stage!=="stable"&&e.defaultOn&&Wo(n,e.stage),e.defaultOn)}function Wo(n,e){$i.has(n)||($i.add(n),m.warn(`[${e.toUpperCase()}] feature ${n} is enabled.`))}async function ol(n,e,t){if(!Tn(n))throw new Error(`Feature ${n} is not registered.`);let r=n in Ae,i=Ae[n];Ae[n]=e;try{return await t()}finally{r?Ae[n]=i:delete Ae[n]}}function Sn(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 Rn=class{constructor(e=Ko("PROGRESSIVE_SSE_STREAMING")){this.isProgressiveMode=e;this.text="";this.thoughtText="";this.partsSequence=[];this.currentTextBuffer="";this.currentFcArgs={}}flushTextBufferToSequence(){this.currentTextBuffer&&(this.currentTextIsThought?this.partsSequence.push({text:this.currentTextBuffer,thought:!0}):this.partsSequence.push({text:this.currentTextBuffer}),this.currentTextBuffer="",this.currentTextIsThought=void 0)}getValueFromPartialArg(e,t){let o=null,r=!1,i=e.stringValue,s=e.numberValue,a=e.boolValue,c=e.nullValue;if(i!==void 0){let l=i;r=!0;let u=Yo.JSONPath.toPathArray(t).filter(d=>d!=="$"&&d!=="$["),f=this.currentFcArgs;for(let d of u)if(f&&typeof f=="object"&&d in f)f=f[d];else{f=void 0;break}typeof f=="string"?o=f+l:o=l}else s!==void 0?(o=s,r=!0):a!==void 0?(o=a,r=!0):c!==void 0&&(o=null,r=!0);return[o,r]}setValueByJsonPath(e,t){let o=Yo.JSONPath.toPathArray(e).filter(i=>i!=="$"&&i!=="$["),r=this.currentFcArgs;for(let i=0;i<o.length-1;i++){let s=o[i];s in r||(r[s]={}),r=r[s]}o.length>0&&(r[o[o.length-1]]=t)}flushFunctionCallToSequence(){var e;if(this.currentFcName){let t={functionCall:{name:this.currentFcName,args:JSON.parse(JSON.stringify(this.currentFcArgs)),id:(e=this.currentFcId)!=null?e:ze()}};this.currentThoughtSignature&&(t.thoughtSignature=this.currentThoughtSignature.toString()),this.partsSequence.push(t),this.currentFcName=void 0,this.currentFcArgs={},this.currentFcId=void 0,this.currentThoughtSignature=void 0}}processStreamingFunctionCall(e){e.name&&(this.currentFcName=e.name),e.id&&(this.currentFcId=e.id);for(let t of e.partialArgs||[]){let o=t.jsonPath;if(!o)continue;let[r,i]=this.getValueFromPartialArg(t,o);i&&this.setValueByJsonPath(o,r)}e.willContinue||(this.flushTextBufferToSequence(),this.flushFunctionCallToSequence())}processFunctionCallPart(e){let t=e.functionCall;t&&(e.thoughtSignature?this.lastThoughtSignature=e.thoughtSignature:this.lastThoughtSignature&&(e.thoughtSignature=this.lastThoughtSignature.toString()),t.partialArgs||t.willContinue?(!t.id&&!this.currentFcId&&(t.id=ze()),e.thoughtSignature&&!this.currentThoughtSignature&&(this.currentThoughtSignature=e.thoughtSignature),this.processStreamingFunctionCall(t)):t.name&&(t.id||(t.id=ze()),this.flushTextBufferToSequence(),this.partsSequence.push(e)))}async*processResponse(e){var o,r,i;this.response=e;let t=Sn(e);if(this.usageMetadata=t.usageMetadata,t.groundingMetadata&&(this.groundingMetadata=t.groundingMetadata),t.citationMetadata&&(this.citationMetadata=t.citationMetadata),t.finishReason&&(this.finishReason=t.finishReason),t.content&&t.content.parts)for(let s of t.content.parts)s.thoughtSignature?this.lastThoughtSignature=s.thoughtSignature:s.functionCall&&this.lastThoughtSignature&&(s.thoughtSignature=this.lastThoughtSignature.toString());if(this.isProgressiveMode){if(t.content&&t.content.parts)for(let s of t.content.parts)if(s.text){let a=(o=s.thought)!=null?o:!1;this.currentTextBuffer&&a!==this.currentTextIsThought&&this.flushTextBufferToSequence(),this.currentTextBuffer||(this.currentTextIsThought=a),this.currentTextBuffer+=s.text}else s.functionCall?this.processFunctionCallPart(s):(this.flushTextBufferToSequence(),this.partsSequence.push(s));t.partial=!0,yield t;return}if(t.content&&t.content.parts&&typeof((r=t.content.parts[0])==null?void 0:r.text)=="string"){let s=t.content.parts[0],a=s.text||"";s.thought?this.thoughtText+=a:this.text+=a,t.partial=!0}else if((this.thoughtText||this.text)&&(!t.content||!t.content.parts||!((i=t.content.parts[0])!=null&&i.inlineData))){let s=[];this.thoughtText&&s.push({text:this.thoughtText,thought:!0}),this.text&&s.push({text:this.text}),yield{content:{role:"model",parts:s},usageMetadata:t.usageMetadata,partial:!1},this.thoughtText="",this.text=""}yield t}close(){var e,t;if(!(!((e=this.response)!=null&&e.candidates)||this.response.candidates.length===0)){if(this.isProgressiveMode){this.flushTextBufferToSequence(),this.flushFunctionCallToSequence();let o=this.partsSequence;if(o.length===0)return;let r=this.response.candidates[0],i=(t=this.finishReason)!=null?t:r.finishReason;return{content:{role:"model",parts:o},groundingMetadata:this.groundingMetadata,citationMetadata:this.citationMetadata,errorCode:i===Ut.FinishReason.STOP?void 0:i,errorMessage:i===Ut.FinishReason.STOP?void 0:r.finishMessage,usageMetadata:this.usageMetadata,finishReason:i,partial:!1}}if((this.text||this.thoughtText)&&this.response.candidates&&this.response.candidates.length>0){let o=[];this.thoughtText&&o.push({text:this.thoughtText,thought:!0}),this.text&&o.push({text:this.text});let r=this.response.candidates[0],i=r.finishReason;return{content:{role:"model",parts:o},groundingMetadata:this.groundingMetadata,citationMetadata:this.citationMetadata,errorCode:i===Ut.FinishReason.STOP?void 0:i,errorMessage:i===Ut.FinishReason.STOP?void 0:r.finishMessage,usageMetadata:this.usageMetadata,finishReason:i,partial:!1}}}}};var wn=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()}};var Ee=class extends ve{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=$t({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,o){var r,i,s;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.info(`Sending out request, model: ${(r=e.model)!=null?r:this.model}, backend: ${this.apiBackend}, stream: ${t}`),e.config||(e.config={}),e.config.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),o&&(e.config.abortSignal=o),t){let a=await this.apiClient.models.generateContentStream({model:(i=e.model)!=null?i:this.model,contents:e.contents,config:e.config}),c=new Rn;for await(let u of a)for await(let f of c.processResponse(u))yield f;let l=c.close();l&&(yield l)}else{let a=await this.apiClient.models.generateContent({model:(s=e.model)!=null?s:this.model,contents:e.contents,config:e.config});yield Sn(a)}}getHttpOptions(){return{headers:{...this.trackingHeaders,...this.headers}}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new ft.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new ft.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 ft.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,ft.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 wn(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)ji(o.inlineData),ji(o.fileData)}}};Ee.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function ji(n){n&&n.displayName&&(n.displayName=void 0)}function $t({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&&!oe()&&(i.vertexai=je("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!oe()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!oe()&&!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&&!oe()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var Vi="APIGEE_PROXY_URL",We=class extends Ee{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!Wi(e))throw new Error(`Model ${e} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`);if(super({...rl({model:e,vertexai:r,project:s,location:i,apiKey:o}),headers:a}),this.proxyUrl=t!=null?t:"",!oe()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[Vi])!=null?c:""),!this.proxyUrl)throw new Error(`Proxy URL must be provided via the constructor or ${Vi} 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,o){var i;let r=(i=e.model)!=null?i:this.model;e.model=zi(r),yield*super.generateContentAsync(e,t,o)}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=zi(t),super.connect(e)}};We.supportedModels=[/apigee\/.*/];function rl({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=$t({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 zi(n){if(!Wi(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 Wi(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 Jo=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)}},Q=class Q{static newLlm(e){return new(Q.resolve(e))({model:e})}static _register(e,t){Q.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${Q.llmRegistryDict.get(e)} to ${t}`),Q.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)Q._register(t,e)}static resolve(e){let t=Q.resolveCache.get(e);if(t)return t;for(let[o,r]of Q.llmRegistryDict.entries())if(new RegExp(`^${o instanceof RegExp?o.source:o}$`,o instanceof RegExp?o.flags:void 0).test(e))return Q.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};Q.llmRegistryDict=new Map,Q.resolveCache=new Jo(32);var ke=Q;ke.register(Ee);ke.register(We);var Xo=Symbol.for("google.adk.baseTool");function dt(n){return typeof n=="object"&&n!==null&&Xo in n&&n[Xo]===!0}var Hi;Hi=Xo;var w=class{constructor(e){this[Hi]=!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=il(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 Oi()}};function il(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var Qo=require("@google/genai"),Ki=require("zod-to-json-schema"),Yi=require("zod/v4");function Zo(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function sl(n){return Zo(n)&&!("_zod"in n)}function al(n){return Zo(n)&&"_zod"in n}function cl(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 Zo(n)&&cl(n)==="ZodObject"}function Ke(n){if(!He(n))throw new Error("Expected a Zod Object");if(al(n))return(0,Yi.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=Qo.Type.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(sl(n))return(0,Ki.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=Qo.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 tr=require("zod");function z(n,e){n.config||(n.config={});let t=e.join(`
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
`,dr=class{async*runAsync(e,t){if(!t.partial)for await(let o of ml(e,t))yield o}},Am=new dr;async function*pl(n,e){let t=n.agent;if(!y(t))return;let o=t.codeExecutor;if(!o||!bn(o))return;if(Gt(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new Vt(new T(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=gl(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=hl(c);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},sr(l)]};e.contents.push((0,ur.cloneDeep)(u)),yield x({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=ps(n,r),d=await o.executeCode({invocationContext:n,codeExecutionInput:{code:l,language:"python",inputFiles:[c],executionId:f}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([c.name]);let p=await ms(n,r,d);yield p,e.contents.push((0,ur.cloneDeep)(p.content))}}async function*ml(n,e){let t=n.agent;if(!y(t))return;let o=t.codeExecutor;if(!o||!bn(o)||!e||!e.content||Gt(o))return;let r=new Vt(new T(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=ls(i,o.codeBlockDelimiters);if(!s)return;yield x({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=ps(n,r),c=await o.executeCode({invocationContext:n,codeExecutionInput:{code:s,language:"python",inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await ms(n,r,c),e.content=void 0}function gl(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||!Pn[l])continue;let u=`data_${i+1}_${a+1}${Pn[l].extension}`;c.text=`
|
|
75
|
-
Available file: \`${u}\`
|
|
76
|
-
`;let f={name:u,content:ui(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function ps(n,e){var r;let t=n.agent;if(!y(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function ms(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[us(t)]},r=j({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 x({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function hl(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Pn[n.mimeType])return;let t=e(n.name),o=Pn[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return`
|
|
77
|
-
${dl}
|
|
78
|
-
|
|
79
|
-
# Load the dataframe.
|
|
80
|
-
${t} = ${o}
|
|
81
|
-
|
|
82
|
-
# Use \`explore_df\` to guide my analysis.
|
|
83
|
-
explore_df(${t})
|
|
84
|
-
`}var gs=new fr;function X(n){return"isCompacted"in n&&n.isCompacted===!0}function hs(n={}){return{...x(n),isCompacted:n.isCompacted||!0,startTime:n.startTime,endTime:n.endTime,compactedContent:n.compactedContent}}var vs=require("@google/genai"),As=require("lodash-es");function pr(n,e,t){var s,a,c;let o=[];for(let l of n){if(X(l)){o.push(xl(l));continue}!((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)||Cl(l)||vl(l)||o.push(ys(e,l)?Al(l):l)}let r=El(o);r=yl(r);let i=[];for(let l of r){let u=(0,As.cloneDeep)(l.content);Bi(u),i.push(u)}return i}function Es(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||ys(e,r))return pr(n.slice(o),e,t)}return[]}function Cl(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)===yn||((o=r.functionResponse)==null?void 0:o.name)===yn)return!0;return!1}function vl(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)===ut||((o=r.functionResponse)==null?void 0:o.name)===ut)return!0;return!1}function ys(n,e){return!!n&&e.author!==n&&e.author!=="user"}function Al(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=Cs(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=Cs(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 x({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function xs(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=x(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 El(n){if(n.length===0)return n;let e=n[n.length-1],t=Y(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);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=_(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(g=>g.id).filter(g=>!!g));if(!Array.from(o).every(g=>d.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(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=Y(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(xs(s)),a}function yl(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=Y(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(Y(o).length>0)continue;let 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(xs(a))}}else t.push(o)}return t}function Cs(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}function xl(n){let e=(0,vs.createUserContent)(`[Previous Context Summary]:
|
|
85
|
-
${n.compactedContent}`);return x({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}var zt=class{async*runAsync(e,t){let o=e.agent;if(!o||!y(o))return;let r=e.session.events,i=r.filter(X),s=i.length>0?i.reduce((a,c)=>c.endTime>a.endTime?c:a):void 0;if(s){let a=r.filter(c=>!(c===s||X(c)||c.timestamp<=s.endTime));r=[s,...a]}o.includeContents==="default"?t.contents=pr(r,o.name,e.branch):t.contents=Es(r,o.name,e.branch)}},Wt=new zt;var _n=new Set;function L(n,e,t){if(e===void 0){let o=n.name;return class extends n{constructor(...i){_n.has(o)||(m.warn(`Class ${o} is experimental and may change in the future.`),_n.add(o)),super(...i)}}}if(e!==void 0&&t!==void 0){let o=typeof n=="function"?n.name:n.constructor.name,r=String(e),i=`${o}.${r}`,s=t.value;return t.value=function(...a){return _n.has(i)||(m.warn(`Method ${i} is experimental and may change in the future.`),_n.add(i)),s.apply(this,a)},t}throw new Error("Invalid decorator usage")}var Ln=(t=>(t.Manual="Manual",t.Auto="Auto",t))(Ln||{}),ie=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 beforeToolSelection(e){}async beforeContextCompaction(e){}async afterContextCompaction(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};v([L],ie.prototype,"beforeToolSelection",1),v([L],ie.prototype,"beforeContextCompaction",1),v([L],ie.prototype,"afterContextCompaction",1);var Qe=class{constructor(e){this.compactors=e}async*runAsync(e,t){for(let o of this.compactors)if(await Promise.resolve(o.shouldCompact(e))){await e.pluginManager.runBeforeContextCompaction({invocationContext:e,trigger:"Auto"});let i=new Set(e.session.events);await Promise.resolve(o.compact(e)),await e.pluginManager.runAfterContextCompaction({invocationContext:e,trigger:"Auto"});let s=e.session.events.filter(a=>!i.has(a));for(let a of s)yield a;return}}};var mr=class extends B{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}"`),z(t,r)}},Ts=new mr;async function gr(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(!Rl(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 Tl=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ss(n){return n===""||n===void 0?!1:Tl.test(n)}var Sl=[T.APP_PREFIX,T.USER_PREFIX,T.TEMP_PREFIX];function Rl(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?Ss(n):Sl.includes(e[0]+":")?Ss(e[1]):!1}var hr=class extends B{async*runAsync(e,t){let o=e.agent;if(!y(o))return;let r=o.rootAgent;if(y(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new b(e)),a=i;s&&(a=await gr(i,new b(e))),z(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=await o.canonicalInstruction(new b(e)),a=i;s&&(a=await gr(i,new b(e))),z(t,[a])}}},Rs=new hr;var Cr=class extends B{async*runAsync(e){let t=e.agent;if(!y(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=Y(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==ut)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 we({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=_(a);if(!c)continue;let l={},u={};for(let g of c){if(!g.id||!(g.id in r))continue;let C=g.args;if(!C||!("originalFunctionCall"in C))continue;let h=C.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 C=o[g],h=Y(C);if(h){for(let A of h)A.id&&A.id in l&&(delete l[A.id],delete u[A.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=await t.canonicalTools(new b(e)),d=Object.fromEntries(f.map(g=>[g.name,g])),p=await xn({invocationContext:e,functionCalls:Object.values(u),toolsDict:d,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l});p&&(yield p);return}}},ws=new Cr;var vr=class extends B{async*runAsync(e,t){let o=e.agent;if(!y(o))return;let r=await o.canonicalTools(new b(e));if(r.length===0)return;let i={};for(let c of r)i[c.name]=c;let s=new F({invocationContext:e}),a=await e.pluginManager.runBeforeToolSelection({callbackContext:s,tools:i});a!==void 0&&(t.allowedTools=Object.keys(a))}},Is=new vr;var Ht=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(Ht||{});function bs(n={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:wl(n.maxLlmCalls||500),pauseOnToolCalls:!1,...n}}function wl(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 ks="adk_agent_name";async function Ps(n,e){return dt(n)?[n]:await n.getTools(e)}var Ar=Symbol.for("google.adk.llmAgent");function y(n){return typeof n=="object"&&n!==null&&Ar in n&&n[Ar]===!0}var _s,Ls,Kt=class n extends(Ls=q,_s=Ar,Ls){constructor(t){var r,i,s,a,c,l,u,f,d;super(t);this[_s]=!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)?Ke(t.inputSchema):t.inputSchema,this.outputSchema=He(t.outputSchema)?Ke(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:[ns,Ts,Rs,ws,Wt,gs,Is],!t.requestProcessors&&t.contextCompactors&&t.contextCompactors.length>0){let p=this.requestProcessors.indexOf(Wt);p!==-1?this.requestProcessors.splice(p,0,new Qe(t.contextCompactors)):this.requestProcessors.push(new Qe(t.contextCompactors))}if(this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(ts),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(En(this.model))return this.model;if(typeof this.model=="string"&&this.model)return ke.newLlm(this.model);let t=this.parentAgent;for(;t;){if(y(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 Ps(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(!he(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){var o;for(;;){let r;for await(let i of this.runOneStepAsync(t)){if((o=t.abortSignal)!=null&&o.aborted)return;r=i,this.maybeSaveOutputToState(i),yield i}if(!r||he(r))break;if(r.partial){m.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(t){var o;for await(let r of this.runLiveFlow(t)){if((o=t.abortSignal)!=null&&o.aborted)return;this.maybeSaveOutputToState(r),yield r}t.endInvocation}async*runLiveFlow(t){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(t){var a,c,l;let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let u of this.requestProcessors)for await(let f of u.runAsync(t,o)){if((a=t.abortSignal)!=null&&a.aborted)return;yield f}for(let u of this.tools){let f=new F({invocationContext:t}),d=(await Ps(u,new b(t))).filter(p=>!o.allowedTools||o.allowedTools.includes(p.name));for(let p of d)if(await p.processLlmRequest({toolContext:f,llmRequest:o}),(c=t.abortSignal)!=null&&c.aborted)return}if(t.endInvocation||(l=t.abortSignal)!=null&&l.aborted)return;let r=x({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=ce.startSpan("call_llm"),s=On.trace.setSpan(On.context.active(),i);yield*Ge(s,this,async function*(){let u=async function*(){var f,d;for await(let p of this.callLlmAsync(t,o,r)){if((f=t.abortSignal)!=null&&f.aborted)return;for await(let g of this.postprocess(t,o,p,r)){if((d=t.abortSignal)!=null&&d.aborted)return;r.id=Io(),r.timestamp=new Date().getTime(),yield g}}};yield*this.runAndHandleError(u.call(this),t,o,r)}),i.end()}async*postprocess(t,o,r,i){var f,d,p,g,C;for(let h of this.responseProcessors)for await(let A of h.runAsync(t,r)){if((f=t.abortSignal)!=null&&f.aborted)return;yield A}if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=x({...i,...r});if(s.content){let h=_(s);h!=null&&h.length&&(Fi(s),s.longRunningToolIds=Array.from(Di(h,o.toolsDict)))}if(yield s,!((d=_(s))!=null&&d.length))return;if((p=t.runConfig)!=null&&p.pauseOnToolCalls){t.endInvocation=!0;return}let a=await Ui({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a||(g=t.abortSignal)!=null&&g.aborted)return;let c=Vo(t,a);c&&(yield c);let l=zo({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let h=this.getAgentByName(t,u);for await(let A of h.runAsync(t)){if((C=t.abortSignal)!=null&&C.aborted)return;yield A}}}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,d,p,g;let i=await this.handleBeforeModelCallback(t,o,r);if((a=t.abortSignal)!=null&&a.aborted)return;if(i){yield i;return}(c=o.config)!=null||(o.config={}),(u=(l=o.config).labels)!=null||(l.labels={}),o.config.labels[ks]||(o.config.labels[ks]=this.name);let s=this.canonicalModel;if((f=t.runConfig)!=null&&f.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let C=s.generateContentAsync(o,((d=t.runConfig)==null?void 0:d.streamingMode)==="sse",t.abortSignal);for await(let h of C){if(ci({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:h}),(p=t.abortSignal)!=null&&p.aborted)return;let A=await this.handleAfterModelCallback(t,h,r);if((g=t.abortSignal)!=null&&g.aborted)return;yield A!=null?A:h}}}async handleBeforeModelCallback(t,o,r){var a,c;let i=new F({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(!((a=t.abortSignal)!=null&&a.aborted)){if(s)return s;for(let l of this.canonicalBeforeModelCallbacks){let u=await l({context:i,request:o});if((c=t.abortSignal)!=null&&c.aborted)return;if(u)return u}}}async handleAfterModelCallback(t,o,r){var a;let i=new F({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let c of this.canonicalAfterModelCallbacks){let l=await c({context:i,response:o});if((a=t.abortSignal)!=null&&a.aborted)return;if(l)return l}}async*runAndHandleError(t,o,r,i){var s;try{for await(let a of t){if((s=o.abortSignal)!=null&&s.aborted)return;yield a}}catch(a){let c=new F({invocationContext:o,eventActions:i.actions});if(a instanceof Error){let l=await o.pluginManager.runOnModelErrorCallback({callbackContext:c,llmRequest:r,error:a});if(l)yield l;else{let u="UNKNOWN_ERROR",f=a.message;try{let d=JSON.parse(a.message);d!=null&&d.error&&(u=String(d.error.code||"UNKNOWN_ERROR"),f=d.error.message||f)}catch{}i.actions?yield x({invocationId:o.invocationId,author:this.name,errorCode:u,errorMessage:f}):yield{errorCode:u,errorMessage:f}}}else throw m.error("Unknown error during response generation",a),a}}};var Er=Symbol.for("google.adk.loopAgent");function Ze(n){return typeof n=="object"&&n!==null&&Er in n&&n[Er]===!0}var Os,Ms,Mn=class extends(Ms=q,Os=Er,Ms){constructor(t){var o;super(t);this[Os]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(t){var r;let o=0;for(;o<this.maxIterations;){for(let i of this.subAgents){let s=!1;for await(let a of i.runAsync(t)){if((r=t.abortSignal)!=null&&r.aborted)return;yield a,a.actions.escalate&&(s=!0)}if(s)return}o++}}async*runLiveImpl(t){throw new Error("This is not supported yet for LoopAgent.")}};var yr=Symbol.for("google.adk.parallelAgent");function et(n){return typeof n=="object"&&n!==null&&yr in n&&n[yr]===!0}var Ns,Fs,Nn=class extends(Fs=q,Ns=yr,Fs){constructor(){super(...arguments);this[Ns]=!0}async*runAsyncImpl(t){var r;let o=this.subAgents.map(i=>i.runAsync(Il(this,i,t)));for await(let i of bl(o)){if((r=t.abortSignal)!=null&&r.aborted)return;yield i}}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function Il(n,e,t){let o=new J(t),r=`${n.name}.${e.name}`;return o.branch=o.branch?`${o.branch}.${r}`:r,o}async function*bl(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 xr="task_completed",Tr=Symbol.for("google.adk.sequentialAgent");function tt(n){return typeof n=="object"&&n!==null&&Tr in n&&n[Tr]===!0}var Bs,Ds,Fn=class extends(Ds=q,Bs=Tr,Ds){constructor(){super(...arguments);this[Bs]=!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)y(o)&&((await o.canonicalTools(new b(t))).some(s=>s.name===xr)||(o.tools.push(new fe({name:xr,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 ${xr} 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 Sr=Symbol.for("google.adk.baseToolset");function Bn(n){return typeof n=="object"&&n!==null&&Sr in n&&n[Sr]===!0}var Us;Us=Sr;var xe=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[Us]=!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){}};async function Dn(n){if(typeof n=="object")return n;let e=n;if(e.startsWith("http://")||e.startsWith("https://"))return await new js.DefaultAgentCardResolver().resolve(e);try{let t=await Vs.readFile(e,"utf-8");return JSON.parse(t)}catch(t){throw new Error(`Failed to read agent card from file ${e}: ${t.message}`)}}async function Un(n,e){return{name:n.name,description:n.description||"",protocolVersion:"0.3.0",version:"1.0.0",skills:await kl(n),url:e[0].url,preferredTransport:e[0].transport,capabilities:{extensions:[],stateTransitionHistory:!1,pushNotifications:!1,streaming:!0},defaultInputModes:["text"],defaultOutputModes:["text"],additionalInterfaces:e}}async function kl(n){let[e,t]=await Promise.all([zs(n),Pl(n)]);return[...e,...t]}async function zs(n){return y(n)?_l(n):Ll(n)}async function Pl(n){let e=n.subAgents,t=[];for(let o of e){let r=await zs(o);for(let i of r){let s={id:`${o.name}_${i.id}`,name:`${o.name}: ${i.name}`,description:i.description,tags:[`sub_agent:${o.name}`,...i.tags]};t.push(s)}}return t}async function _l(n){let e=[{id:n.name,name:"model",description:await Bl(n),tags:["llm"]}];if(n.tools&&n.tools.length>0){for(let t of n.tools)if(dt(t))e.push($s(n.name,t));else if(Bn(t)){let o=await t.getTools();for(let r of o)e.push($s(n.name,r))}}return e}function $s(n,e){let t=e.description;return t||(t=`Tool: ${e.name}`),{id:`${n}-${e.name}`,name:e.name,description:t,tags:["llm","tools"]}}function Ll(n){let e=[{id:n.name,name:Dl(n),description:Ol(n),tags:[Gs(n)]}],t=n.subAgents;if(t.length>0){let o=t.map(r=>r.description||"No description");e.push({id:`${n.name}-sub-agents`,name:"sub-agents",description:`Orchestrates: ${o.join("; ")}`,tags:[Gs(n),"orchestration"]})}return e}function Ol(n){let e=[];return n.description&&e.push(n.description),n.subAgents.length>0&&(Ze(n)?e.push(Fl(n)):et(n)?e.push(Nl(n)):tt(n)&&e.push(Ml(n))),e.length>0?e.join(" "):Ws(n)}function Ml(n){let e=n.subAgents,t=[];return e.forEach((o,r)=>{let i=o.description;i||(i=`execute the ${o.name} agent`),r===0?t.push(`First, this agent will ${i}.`):r===e.length-1?t.push(`Finally, this agent will ${i}.`):t.push(`Then, this agent will ${i}.`)}),t.join(" ")}function Nl(n){let e=n.subAgents,t=[];return e.forEach((o,r)=>{let i=o.description;i||(i=`execute the ${o.name} agent`),r===0?t.push(`This agent will ${i}`):r===e.length-1?t.push(`and ${i}`):t.push(`, ${i}`)}),`${t.join(" ")} simultaneously.`}function Fl(n){let e=n.maxIterations,t="unlimited";typeof e=="number"&&e<Number.MAX_SAFE_INTEGER&&(t=e.toString());let o=n.subAgents,r=[];return o.forEach((i,s)=>{let a=i.description;a||(a=`execute the ${i.name} agent`),s===0?r.push(`This agent will ${a}`):s===o.length-1?r.push(`and ${a}`):r.push(`, ${a}`)}),`${r.join(" ")} in a loop (max ${t} iterations).`}async function Bl(n){let e=[];if(n.description&&e.push(n.description),n.instruction){let o;if(typeof n.instruction=="function"){let r=new b(new J({agent:n}));try{o=await n.instruction(r)}catch(i){m.warn("Failed to resolve dynamic instruction for AgentCard",i),o=""}}else o=n.instruction;o&&e.push(qs(o))}let t=n.rootAgent;if(y(t)&&t.globalInstruction){let o;if(typeof t.globalInstruction=="function"){let r=new b(new J({agent:n}));try{o=await t.globalInstruction(r)}catch(i){m.warn("Failed to resolve dynamic global instruction for AgentCard",i),o=""}}else o=t.globalInstruction;o&&e.push(qs(o))}return e.length>0?e.join(" "):Ws(n)}function qs(n){let e=[{original:"you were",target:"I was"},{original:"you are",target:"I am"},{original:"you're",target:"I am"},{original:"you've",target:"I have"},{original:"yours",target:"mine"},{original:"your",target:"my"},{original:"you",target:"I"}],t=n;for(let o of e){let r=new RegExp(`\\b${o.original}\\b`,"gi");t=t.replace(r,o.target)}return t}function Ws(n){return Ze(n)?"A loop workflow agent":tt(n)?"A sequential workflow agent":et(n)?"A parallel workflow agent":y(n)?"An LLM-based agent":"A custom agent"}function Gs(n){return Ze(n)?"loop_workflow":tt(n)?"sequential_workflow":et(n)?"parallel_workflow":y(n)?"llm_agent":"custom_agent"}function Dl(n){return y(n)?"model":Ul(n)?"workflow":"custom"}function Ul(n){return Ze(n)||tt(n)||et(n)}var _e=require("@google/genai");function Rr(n,e,t){if(Do(n))return ql(n,e,t);if(le(n))return zl(n,e,t);if(Mt(n))return Gl(n,e,t);if(Ie(n))return n.final?jl(n,e,t):Vl(n,e,t)}function ql(n,e,t,o){let r=ue(n.parts);return{...Yt(o||n),invocationId:e,author:n.role==="user"?"user":t,content:n.role==="user"?(0,_e.createUserContent)(r):(0,_e.createModelContent)(r),turnComplete:!0,partial:!1}}function Gl(n,e,t){var i;let o=((i=n.artifact)==null?void 0:i.parts)||[];if(o.length===0)return;let r=!!mn(n)[E.PARTIAL]||n.append||!n.lastChunk;return{...Yt(n),invocationId:e,author:t,content:(0,_e.createModelContent)(ue(o)),longRunningToolIds:$n(o),partial:r}}function jl(n,e,t){var a;let o=((a=n.status.message)==null?void 0:a.parts)||[];if(o.length===0)return;let r=ue(o),i=gn(n),s=!i&&r.length>0;return{...Yt(n),invocationId:e,author:t,errorMessage:i?Uo(n):void 0,content:s?(0,_e.createModelContent)(r):void 0,longRunningToolIds:$n(o),turnComplete:!0}}function Vl(n,e,t){let o=n.status.message;if(!o)return;let r=ue(o.parts);return{...Yt(n),invocationId:e,author:t,content:(0,_e.createModelContent)(r),turnComplete:!1,partial:!0}}function zl(n,e,t){var a,c;let o=[],r=[];if(n.artifacts){for(let l of n.artifacts)if(((a=l.parts)==null?void 0:a.length)>0){let u=ue(l.parts);o.push(...u),r.push(...$n(l.parts))}}if((c=n.status)!=null&&c.message){let l=n.status.message.parts,u=ue(l);o.push(...u),r.push(...$n(l))}let i=Ai(n)||hn(n),s=gn(n);if(!(o.length===0&&!i))return{...Yt(n),invocationId:e,author:t,content:s?void 0:(0,_e.createModelContent)(o),errorMessage:s?Uo(n):void 0,longRunningToolIds:r,turnComplete:i}}function Yt(n){let e=n.metadata||{};return x({branch:e[E.BRANCH],author:e[E.AUTHOR],partial:e[E.PARTIAL],errorCode:e[E.ERROR_CODE],errorMessage:e[E.ERROR_MESSAGE],citationMetadata:e[E.CITATION_METADATA],groundingMetadata:e[E.GROUNDING_METADATA],usageMetadata:e[E.USAGE_METADATA],customMetadata:e[E.CUSTOM_METADATA],actions:j({escalate:!!e[E.ESCALATE],transferToAgent:e[E.TRANSFER_TO_AGENT]})})}function $n(n){let e=[];for(let t of n)if(t.metadata&&t.metadata[E.IS_LONG_RUNNING]){let o=$o(t);o.functionCall&&o.functionCall.id&&e.push(o.functionCall.id)}return e}var qn=class extends q{constructor(t){super(t);this.a2aConfig=t;this.isInitialized=!1;if(!t.agentCard&&!t.client)throw new Error("Either AgentCard or Client must be provided")}async init(){if(!this.isInitialized){if(this.a2aConfig.client&&(this.client=this.a2aConfig.client),this.a2aConfig.agentCard&&(this.card=await Dn(this.a2aConfig.agentCard),!this.client)){let t=this.a2aConfig.clientFactory||new Hs.ClientFactory;this.client=await t.createFromAgentCard(this.card)}this.isInitialized=!0}}async*runAsyncImpl(t){var o,r;await this.init();try{let i=t.session.events;if(i.length===0)throw new Error("No events in session to send");let s=ki(t.session,i.length-1),a,c,l;if(s){let g=s.response;a=Ce(((o=g.content)==null?void 0:o.parts)||[],g.longRunningToolIds),c=s.taskId,l=s.contextId}else{let g=Pi(t,t.session);a=g.parts,l=g.contextId}let u={kind:"message",messageId:k(),role:"user",parts:a,metadata:be({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id})};c&&(u.taskId=c),l&&(u.contextId=l);let f={message:u,configuration:this.a2aConfig.messageSendConfig},d=new vn(f);if(this.a2aConfig.beforeRequestCallbacks)for(let g of this.a2aConfig.beforeRequestCallbacks)await g(t,f);if(this.card?((r=this.card.capabilities)==null?void 0:r.streaming)!==!1:!0)for await(let g of this.client.sendMessageStream(f)){if(this.a2aConfig.afterRequestCallbacks)for(let A of this.a2aConfig.afterRequestCallbacks)await A(t,g);let C=Rr(g,t.invocationId,this.name);if(!C)continue;d.updateCustomMetadata(C,g);let h=d.aggregatePartial(t,g,C);for(let A of h)yield A}else{let g=await this.client.sendMessage(f);if(this.a2aConfig.afterRequestCallbacks)for(let h of this.a2aConfig.afterRequestCallbacks)await h(t,g);let C=Rr(g,t.invocationId,this.name);C&&(d.updateCustomMetadata(C,g),yield C)}}catch(i){let s=i;m.error(`A2ARemoteAgent ${this.name} failed:`,s),yield x({author:this.name,invocationId:t.invocationId,errorMessage:s.message,turnComplete:!0})}}runLiveImpl(t){throw new Error("Live mode is not supported in A2ARemoteAgent yet.")}};var Ys=require("@google/genai"),Gn=require("@opentelemetry/api");var gt=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 runBeforeToolSelection({callbackContext:e,tools:t}){return await this.runCallbacks(this.plugins,o=>o.beforeToolSelection({callbackContext:e,tools:t}),"beforeToolSelection")}async runBeforeContextCompaction({invocationContext:e,trigger:t}){await this.runCallbacks(this.plugins,o=>o.beforeContextCompaction({invocationContext:e,trigger:t}),"beforeContextCompaction")}async runAfterContextCompaction({invocationContext:e,trigger:t}){await this.runCallbacks(this.plugins,o=>o.afterContextCompaction({invocationContext:e,trigger:t}),"afterContextCompaction")}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 Ir=Symbol.for("google.adk.runner");function jn(n){return typeof n=="object"&&n!==null&&Ir in n&&n[Ir]===!0}var Ks;Ks=Ir;var de=class{constructor(e){this[Ks]=!0;var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new gt((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=bs(e.runConfig),s=e.newMessage,a=ce.startSpan("invocation"),c=Gn.trace.setSpan(Gn.context.active(),a);try{yield*Ge(c,this,async function*(){var d,p,g,C,h,A,H,I,K,kt;let l=await this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o});if((d=e.abortSignal)!=null&&d.aborted)return;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&&y(this.agent)){let Pt=this.agent.canonicalModel.model;if(!pt(Pt))throw new Error(`CFC is not supported for model: ${Pt} in agent: ${this.agent.name}`);Gt(this.agent.codeExecutor)||(this.agent.codeExecutor=new mt)}let u=new J({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:gi(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager,abortSignal:e.abortSignal}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u});if(!((p=e.abortSignal)!=null&&p.aborted)){if(f&&(s=f),s){if(!((g=s.parts)!=null&&g.length))throw new Error("No parts in the newMessage.");if(i.saveInputBlobsAsArtifacts&&(await this.saveArtifacts(u.invocationId,l.userId,l.id,s),(C=e.abortSignal)!=null&&C.aborted)||(await this.sessionService.appendEvent({session:l,event:x({invocationId:u.invocationId,author:"user",actions:r?j({stateDelta:r}):void 0,content:s})}),(h=e.abortSignal)!=null&&h.aborted))return}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let Pt=await this.pluginManager.runBeforeRunCallback({invocationContext:u});if((A=e.abortSignal)!=null&&A.aborted)return;if(Pt){let qe=x({invocationId:u.invocationId,author:"model",content:Pt});if(await this.sessionService.appendEvent({session:l,event:qe}),(H=e.abortSignal)!=null&&H.aborted)return;yield qe}else{for await(let qe of u.agent.runAsync(u)){if((I=e.abortSignal)!=null&&I.aborted)return;qe.partial||await this.sessionService.appendEvent({session:l,event:qe});let Kr=await this.pluginManager.runOnEventCallback({invocationContext:u,event:qe});if((K=e.abortSignal)!=null&&K.aborted)return;Kr?yield Kr:yield qe}if(await this.pluginManager.runAfterRunCallback({invocationContext:u}),(kt=e.abortSignal)!=null&&kt.aborted)return}}}})}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,Ys.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let o=Wl(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(!y(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Wl(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=_(c);if(l){for(let u of l)if(u.id===t)return c}}return null}function Js(n,e){var r,i;let t=j();for(let s of n){if(s.errorCode||s.errorMessage)return Cn({taskId:e.requestContext.taskId,contextId:e.requestContext.contextId,error:new Error(s.errorMessage||s.errorCode),metadata:{...Ft(s,e),...Bt(t)}});t.escalate=t.escalate||((r=s.actions)==null?void 0:r.escalate),(i=s.actions)!=null&&i.transferToAgent&&(t.transferToAgent=s.actions.transferToAgent)}let o=Hl(n,e);return o?{...o,metadata:{...o.metadata,...Bt(t)}}:xi({taskId:e.requestContext.taskId,contextId:e.requestContext.contextId,metadata:{...be(e),...Bt(t)}})}function Hl(n,e){var r,i;let t=[],o=new Set;for(let s of n)if((i=(r=s.content)==null?void 0:r.parts)!=null&&i.length)for(let a of s.content.parts){let c=Kl(a,s.longRunningToolIds,t);!c||o.has(c)||(t.push(a),o.add(c))}if(t.length>0)return Si({taskId:e.requestContext.taskId,contextId:e.requestContext.contextId,parts:Ce(t,[...o]),metadata:be(e)})}function Kl(n,e=[],t=[]){var i,s,a;let o=(i=n.functionCall)==null?void 0:i.id,r=(s=n.functionResponse)==null?void 0:s.id;if(!(!o&&!r)){if(o&&e.includes(o))return o;if(r&&e.includes(r))return r;for(let c of t)if(((a=c.functionCall)==null?void 0:a.id)===r)return r}}function Xs(n,e){var r;if(!n||!hn(n)||!n.status.message)return;let t=n.status.message,o=ue(t.parts);for(let i of o){let s=(r=i.functionCall)==null?void 0:r.id;if(!s)continue;if(!((e==null?void 0:e.parts)||[]).some(c=>{var l;return((l=c.functionResponse)==null?void 0:l.id)===s}))return Ri({taskId:n.id,contextId:n.contextId,parts:[...t.parts.filter(c=>{var l;return!((l=c.metadata)!=null&&l.validation_error)}),{kind:"text",text:`No input provided for function call id ${s}`,metadata:{validation_error:!0}}]})}}function Qs({session:n,userContent:e,requestContext:t}){return{userId:n.userId,sessionId:n.id,appName:n.appName,readonlyState:n.state,events:n.events,userContent:e,requestContext:t}}var ht=class{constructor(e){this.config=e;this.agentPartialArtifactIdsMap={}}async execute(e,t){var u,f;let o=e.userMessage;if(!o)throw new Error("message not provided");let r=`A2A_USER_${e.contextId}`,i=e.contextId,s=bi(o),a=await Zs(this.config.runner),c=await Yl(r,i,a.sessionService,a.appName),l=Qs({session:c,userContent:s,requestContext:e});try{if(this.config.beforeExecuteCallback&&await this.config.beforeExecuteCallback(e),e.task){let p=Xs(e.task,s);if(p){await this.publishFinalTaskStatus({executorContext:l,eventBus:t,event:p});return}}e.task||t.publish(Ei({taskId:e.taskId,contextId:e.contextId,message:o})),t.publish(yi({taskId:e.taskId,contextId:e.contextId}));let d=[];for await(let p of a.runAsync({userId:r,sessionId:i,newMessage:s,runConfig:this.config.runConfig})){d.push(p);let g=this.convertAdkEventToA2AEvent(p,l);g&&(await((f=(u=this.config).afterEventCallback)==null?void 0:f.call(u,l,p,g)),t.publish(g))}await this.publishFinalTaskStatus({executorContext:l,eventBus:t,event:Js(d,l)})}catch(d){let p=d;await this.publishFinalTaskStatus({executorContext:l,eventBus:t,error:p,event:Cn({taskId:e.taskId,contextId:e.contextId,error:new Error(`Agent run failed: ${p.message}`),metadata:be(l)})})}}async cancelTask(e){throw new Error("Task cancellation is not supported yet.")}convertAdkEventToA2AEvent(e,t){var s;let o=Ce((s=e.content)==null?void 0:s.parts,e.longRunningToolIds);if(o.length===0)return;let r=this.agentPartialArtifactIdsMap[e.author]||k(),i=Ti({taskId:t.requestContext.taskId,contextId:t.requestContext.contextId,artifactId:r,parts:o,metadata:Ft(e,t),append:e.partial,lastChunk:!e.partial});return e.partial?this.agentPartialArtifactIdsMap[e.author]=r:delete this.agentPartialArtifactIdsMap[e.author],i}async publishFinalTaskStatus({executorContext:e,eventBus:t,event:o,error:r}){var i,s;try{await((s=(i=this.config).afterExecuteCallback)==null?void 0:s.call(i,e,o,r))}catch(a){m.error("Error in afterExecuteCallback:",a)}t.publish(o)}};async function Yl(n,e,t,o){let r=await t.getSession({appName:o,userId:n,sessionId:e});return r||t.createSession({appName:o,userId:n,sessionId:e})}async function Zs(n){if(typeof n=="function"){let e=await n();return Zs(e)}return jn(n)?n:new de(n)}var na=require("@a2a-js/sdk"),Wn=require("@a2a-js/sdk/server"),Se=require("@a2a-js/sdk/server/express"),zn=P(require("express"),1);var br=require("lodash-es");var ea=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=Vn(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(T.TEMP_PREFIX)||(e.state[o]=r)}};function Vn(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(T.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function pe(n={},e={},t={}){let o=(0,ea.cloneDeep)(t);for(let[r,i]of Object.entries(n))o[T.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[T.USER_PREFIX+r]=i;return o}function Te(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}function ta(n){return n==="memory://"}var Z=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=Te({id:i||k(),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,br.cloneDeep)(s);return a.state=pe(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,br.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=pe(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(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=>{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(T.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(T.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(T.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(T.USER_PREFIX,"")]=o.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:o}),c.lastUpdateTime=o.timestamp,o}};async function oa(n,e={}){var f,d,p,g;let t=(f=e.host)!=null?f:"localhost",o=(d=e.port)!=null?d:8e3,r=(p=e.protocol)!=null?p:"http",i=e.basePath||"",s=`${r}://${t}:${o}${i}`,a=e.agentCard?await Dn(e.agentCard):await Un(n,[{url:`${s}/jsonrpc`,transport:"JSONRPC"},{url:`${s}/rest`,transport:"HTTP+JSON"}]),c=new ht({runner:e.runner||{agent:n,appName:n.name,sessionService:e.sessionService||new Z,memoryService:e.memoryService,artifactService:e.artifactService},runConfig:{streamingMode:"sse"}}),l=new Wn.DefaultRequestHandler(a,new Wn.InMemoryTaskStore,c),u=(g=e.app)!=null?g:(0,zn.default)();return e.app||(u.use(zn.default.urlencoded({limit:"50mb",extended:!0})),u.use(zn.default.json({limit:"50mb"}))),u.use(`${i}/${na.AGENT_CARD_PATH}`,(0,Se.agentCardHandler)({agentCardProvider:l})),u.use(`${i}/rest`,(0,Se.restHandler)({requestHandler:l,userBuilder:Se.UserBuilder.noAuthentication})),u.use(`${i}/jsonrpc`,(0,Se.jsonRpcHandler)({requestHandler:l,userBuilder:Se.UserBuilder.noAuthentication})),u}var M=P(require("fs/promises"),1),S=P(require("path"),1),Jt=require("url");var Kn="user:",vt=class{constructor(e){try{let t=e.startsWith("file://")?(0,Jt.fileURLToPath)(e):e;this.rootDir=S.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=nt(this.rootDir,e,t,o);await M.mkdir(s,{recursive:!0});let a=await Ct(s),c=a.length>0?a[a.length-1]+1:0,l=ot(s),u=S.join(l,c.toString());await M.mkdir(u,{recursive:!0});let f=S.basename(s),d=S.join(u,f),p;if(r.inlineData){let h=r.inlineData.data||"";await M.writeFile(d,Buffer.from(h,"base64")),p=r.inlineData.mimeType||"application/octet-stream"}else r.text!==void 0&&await M.writeFile(d,r.text,"utf-8");let g=await Ql(this.rootDir,e,t,o,c),C={fileName:o,mimeType:p,version:c,canonicalUri:g,customMetadata:i};return await Zl(S.join(u,"metadata.json"),C),c}async loadArtifact({userId:e,sessionId:t,filename:o,version:r}){try{let i=nt(this.rootDir,e,t,o);try{await M.access(i)}catch(p){m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} not found`,p);return}let s=await Ct(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=S.join(ot(i),a.toString()),l=S.join(c,"metadata.json"),u=await Hn(l),f=S.basename(i),d=S.join(c,f);if(u.canonicalUri){let p=eu(u.canonicalUri);if(p)try{await M.access(p),d=p}catch{m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} missing at ${p}, falling back to content path ${d}`)}}if(u.mimeType)try{let p=await M.readFile(d);return{inlineData:{mimeType:u.mimeType,data:p.toString("base64")}}}catch{m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} missing at ${d}`);return}try{return{text:await M.readFile(d,"utf-8")}}catch{m.warn(`[FileArtifactService] loadArtifact: Text artifact ${o} missing at ${d}`);return}}catch(i){m.error(`[FileArtifactService] loadArtifact: Error loading artifact ${o}`,i);return}}async listArtifactKeys({userId:e,sessionId:t}){let o=new Set,r=ca(this.rootDir,e),i=ua(r,t);for await(let a of kr(i)){let c=await ra(a);if(c!=null&&c.fileName)o.add(c.fileName);else{let l=S.relative(i,a);o.add(ia(l))}}let s=la(r);for await(let a of kr(s)){let c=await ra(a);if(c!=null&&c.fileName)o.add(c.fileName);else{let l=S.relative(s,a);o.add(`${Kn}${ia(l)}`)}}return Array.from(o).sort()}async deleteArtifact({userId:e,sessionId:t,filename:o}){try{let r=nt(this.rootDir,e,t,o);await M.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=nt(this.rootDir,e,t,o);return await Ct(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=nt(this.rootDir,e,t,o),i=await Ct(r),s=[];for(let a of i){let c=S.join(ot(r),a.toString(),"metadata.json");try{let l=await Hn(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=nt(this.rootDir,e,t,o),s=await Ct(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=S.join(ot(i),a.toString(),"metadata.json");return await Hn(c)}catch(i){m.warn(`[FileArtifactService] getArtifactVersion: Failed to get artifact version for userId: ${e} sessionId: ${t} filename: ${o} version: ${r}`,i);return}}},Jl=/^[a-zA-Z0-9_@-][a-zA-Z0-9_.@-]{0,255}$/;function sa(n,e){if(!n||!Jl.test(n))throw new Error(`[FileArtifactService] Invalid ${e}: value contains disallowed characters.`)}function aa(n,e,t){let o=S.resolve(e),r=S.resolve(n);if(!r.startsWith(o+S.sep)&&r!==o)throw new Error(`[FileArtifactService] ${t} escapes storage root. Resolved: ${r}, Root: ${o}`)}function ca(n,e){sa(e,"userId");let t=S.join(n,"users",e);return aa(t,n,"userRoot"),t}function Xl(n,e){return!n||e.startsWith(Kn)}function la(n){return S.join(n,"artifacts")}function ua(n,e){sa(e,"sessionId");let t=S.join(n,"sessions",e,"artifacts");return aa(t,n,"sessionArtifactsDir"),t}function ot(n){return S.join(n,"versions")}function nt(n,e,t,o){let r=ca(n,e),i;if(Xl(t,o))i=la(r);else{if(!t)throw new Error("Session ID must be provided for session-scoped artifacts.");i=ua(r,t)}let s=o;if(s.startsWith(Kn)&&(s=s.substring(Kn.length)),s=s.trim(),S.isAbsolute(s))throw new Error(`Absolute artifact filename ${o} is not permitted.`);let a=S.resolve(i,s),c=S.relative(i,a);if(c.startsWith("..")||S.isAbsolute(c))throw new Error(`Artifact filename ${o} escapes storage directory.`);return c===""||c==="."?S.join(i,"artifact"):a}async function Ct(n){let e=ot(n);try{return(await M.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 Ql(n,e,t,o,r){let i=await nt(n,e,t,o),s=S.basename(i),a=ot(i),c=S.join(a,r.toString(),s);return(0,Jt.pathToFileURL)(c).toString()}async function Zl(n,e){await M.writeFile(n,JSON.stringify(e,null,2),"utf-8")}async function Hn(n){let e=await M.readFile(n,"utf-8");return JSON.parse(e)}async function ra(n){let e=await Ct(n);if(e.length===0)return;let t=e[e.length-1],o=S.join(ot(n),t.toString(),"metadata.json");try{return await Hn(o)}catch(r){m.warn(`[FileArtifactService] getLatestMetadata: Failed to read metadata from ${o}`,r);return}}async function*kr(n){try{let e=await M.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=S.join(n,o.name);for await(let i of kr(r))yield i}}catch{}}function eu(n){try{return(0,Jt.fileURLToPath)(n)}catch(e){m.warn(`[FileArtifactService] fileUriToPath: Failed to convert file URI to path: ${n}`,e);return}}function ia(n){return n.split(S.sep).join("/")}var da=require("@google-cloud/storage"),Yn=require("@google/genai");var At=class{constructor(e){this.bucket=new da.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(Xt({...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(Xt({...e,version:t})),[[r],[i]]=await Promise.all([o.getMetadata(),o.download()]);return r.contentType==="text/plain"?(0,Yn.createPartFromText)(i.toString("utf-8")):(0,Yn.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[...fa(r,t),...fa(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(Xt({...e,version:o})).delete()))}async listVersions(e){let o=Xt(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(Xt({...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 Xt({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 fa(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=tu(i);o.add(`${t}${s}`)}return[...o]}function tu(n){let e=n.split("/");return e.length<2?n:e.slice(0,-1).join("/")}function pa(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=Et(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=Et(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=Et(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=Et(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=Et(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=Et(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 Et(n,e,t,o){return nu(o)?`${n}/${e}/user/${o}`:`${n}/${e}/${t}/${o}`}function nu(n){return n.startsWith("user:")}function ma(n){if(pa(n))return new Oe;if(n.startsWith("gs://")){let e=n.split("://")[1];return new At(e)}if(n.startsWith("file://")){let e=n.split("://")[1];return new vt(e)}throw new Error(`Unsupported artifact service URI: ${n}`)}var ha=require("child_process"),ee=P(require("fs/promises"),1),Zn=P(require("os"),1),Me=P(require("path"),1);var ou={".js":{mimeType:"text/javascript",encoding:"utf-8"},".py":{mimeType:"text/x-python",encoding:"utf-8"},".md":{mimeType:"text/markdown",encoding:"utf-8"},".txt":{mimeType:"text/plain",encoding:"utf-8"},".html":{mimeType:"text/html",encoding:"utf-8"},".css":{mimeType:"text/css",encoding:"utf-8"},".json":{mimeType:"application/json",encoding:"utf-8"},".csv":{mimeType:"text/csv",encoding:"utf-8"},".svg":{mimeType:"image/svg+xml",encoding:"utf-8"},".xml":{mimeType:"application/xml",encoding:"utf-8"},".yaml":{mimeType:"text/yaml",encoding:"utf-8"},".yml":{mimeType:"text/yaml",encoding:"utf-8"},".png":{mimeType:"image/png",encoding:"base64"},".jpg":{mimeType:"image/jpeg",encoding:"base64"},".jpeg":{mimeType:"image/jpeg",encoding:"base64"},".pdf":{mimeType:"application/pdf",encoding:"base64"}},ru={".js":"javascript",".ts":"typescript",".py":"python",".bat":"cmd",".cmd":"cmd",".ps1":"powershell",".sh":"shell"};function Jn(n){return ou[n.toLowerCase()]||{mimeType:"application/octet-stream",encoding:"base64"}}function ga(n){return ru[n.toLowerCase()]||"unspecified"}var yt=P(require("fs/promises"),1),G=P(require("path"),1);async function xt(n,e=process.cwd()){let t=G.resolve(e),o=[];for(let r of n){let i=G.resolve(e,r.name);if(!i.startsWith(t))throw new Error(`Path traversal detected: ${r.name} resolves outside of ${e}`);let s=G.extname(i),a=G.dirname(i),c=G.basename(i,s),l=i,u=2;for(;;)try{await yt.access(l);let f=`${c}_${u}${s}`;l=G.join(a,f);let d=G.dirname(r.name);r.name=d==="."?f:G.join(d,f),u++}catch{break}if(!l.startsWith(t))throw new Error(`Path traversal detected: ${r.name} resolves outside of ${e}`);await yt.mkdir(G.dirname(l),{recursive:!0}),await yt.writeFile(l,Buffer.from(r.content,r.contentEncoding)),o.push({...r,name:G.relative(e,l)})}return o}var Xn=Zn.platform()==="win32";async function iu(n,e,t){let o=Me.join(Zn.tmpdir(),"adk_js_unsafe_code_executor",Date.now().toString()+"_"+Math.random().toString(36).slice(2));await ee.mkdir(o,{recursive:!0});let r=su(e,t)||".js",i=Me.join(o,`script${r}`);return await ee.writeFile(i,n),{filePath:i,tempDir:o}}function su(n,e){if(n==="javascript")return".js";if(n==="python")return".py";if(n==="powershell")return".ps1";if(n==="cmd")return".bat";if(n==="shell")return Xn?e&&e.toLowerCase().includes("cmd")?".bat":".ps1":".sh"}var Qn=class extends Pe{constructor(e={}){var t,o,r,i;super(),this.timeoutSeconds=(t=e.timeoutSeconds)!=null?t:30,this.nodeCommandPath=(o=e.commandPath)!=null?o:process.execPath,this.pythonCommandPath=(r=e.pythonCommandPath)!=null?r:Xn?"python":"python3",this.shellCommandPath=(i=e.shellCommandPath)!=null?i:Xn?"powershell":"bash",this.stateful=!1,this.optimizeDataFile=!1}async executeCode(e){var i;let{code:t,language:o}=e.codeExecutionInput;if(!["javascript","python","shell","cmd","powershell"].includes(o))return{stdout:"",stderr:`Unsupported language: ${o}`,outputFiles:[]};m.warn(`
|
|
86
|
-
====================================================================================
|
|
87
|
-
\u26A0\uFE0F DANGER: UnsafeLocalCodeExecutor is executing code locally on this host machine!
|
|
88
|
-
This component provides NO sandboxing or container isolation. Arbitrary shell/script
|
|
89
|
-
commands generated by AI or untrusted sources could lead to serious security risks.
|
|
90
|
-
====================================================================================
|
|
91
|
-
`);let r;try{let s=await iu(t,o,this.shellCommandPath),a=s.filePath;r=s.tempDir,e.codeExecutionInput.inputFiles&&await xt(e.codeExecutionInput.inputFiles,r);let c=this.nodeCommandPath,l=[a];if(o==="python"?c=this.pythonCommandPath:o==="shell"?(c=this.shellCommandPath,this.shellCommandPath.toLowerCase().includes("powershell")?l=["-NoLogo","-ExecutionPolicy","Bypass","-File",a]:this.shellCommandPath.toLowerCase().includes("cmd")&&(l=["/c",a])):o==="powershell"?(c=Xn?"powershell":"pwsh",l=["-NoLogo","-ExecutionPolicy","Bypass","-File",a]):o==="cmd"&&(c="cmd.exe",l=["/c",a]),e.codeExecutionInput.args)if(Array.isArray(e.codeExecutionInput.args))l.push(...e.codeExecutionInput.args);else for(let[d,p]of Object.entries(e.codeExecutionInput.args))l.push(`--${d}`,String(p));let u=await new Promise(d=>{let p=(0,ha.spawn)(c,l,{timeout:this.timeoutSeconds*1e3,killSignal:"SIGKILL",cwd:r}),g="",C="";p.stdout&&p.stdout.on("data",h=>{g+=h.toString()}),p.stderr&&p.stderr.on("data",h=>{C+=h.toString()}),p.on("error",h=>{C+=`Process error: ${h.message}
|
|
92
|
-
`}),p.on("close",(h,A)=>{A==="SIGKILL"||A==="SIGTERM"?C+=`
|
|
93
|
-
Code execution timed out after ${this.timeoutSeconds} seconds.`:h!==0&&h!==null&&(C||(C=`Exit code ${h}`)),d({stdout:g,stderr:C,exitCode:h})})}),f=[];try{let d=await ee.readdir(r,{recursive:!0});for(let p of d){let g=Me.join(r,p);if(!(await ee.lstat(g)).isFile()||p===Me.basename(a)||((i=e.codeExecutionInput.inputFiles)==null?void 0:i.some(K=>K.name===p)))continue;let A=await ee.readFile(g),{mimeType:H,encoding:I}=Jn(Me.extname(p));f.push({name:p,content:A.toString(I),contentEncoding:I,mimeType:H})}}catch(d){m.error(`Error scanning output files: ${d}`)}return{stdout:u.stdout,stderr:u.stderr,outputFiles:f}}finally{r&&await ee.rm(r,{recursive:!0,force:!0})}}};var eo=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};var to=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}}};async function*Tt(n,e,t,o){let r=await t(n,e);if(!r)throw new Error("Initial routing failed, no item selected.");let i=r;m.debug(`Router selected initial key: ${i}`);let s=n[i];if(!s)throw new Error(`Item not found for key: ${i}`);let a=new Set([i]);for(;;){let c=o(s),l=!1;try{if(au(c)){for await(let f of c)yield f,l=!0;return}yield await c;return}catch(u){if(l)throw u;{let f=await t(n,e,{failedKeys:a,lastError:u});if(m.debug(`Router selected next key: ${f}`),f===void 0||a.has(f))throw u;if(i=f,s=n[i],!s)throw new Error(`Item not found for key: ${i}`);a.add(i)}}}}function au(n){return typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function"}var Pr=Symbol.for("google.adk.routedAgent");function Aa(n){return typeof n=="object"&&n!==null&&Pr in n&&n[Pr]===!0}var Ca,va,St=class extends(va=q,Ca=Pr,va){constructor(t){let o=Array.isArray(t.agents)?t.agents:Object.values(t.agents);super({...t,subAgents:o});this[Ca]=!0;Array.isArray(t.agents)?this.agents=Object.fromEntries(t.agents.map(r=>[r.name,r])):this.agents=t.agents,this.router=t.router}async*runAsyncImpl(t){yield*Tt(this.agents,t,this.router,o=>o.runAsync(t))}async*runLiveImpl(t){yield*Tt(this.agents,t,this.router,o=>o.runLive(t))}};St=v([L],St);var no=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(no||{});var oo=class{constructor(){this.providers=new Map}register(e,t){this.providers.set(e,t)}getProvider(e){return this.providers.get(e.type)}};var ro=class{constructor(){this.credentials={}}loadCredential(e,t){let o=this.getBucketForCurrentContext(t);return Promise.resolve(o[e.credentialKey])}async saveCredential(e,t){let o=this.getBucketForCurrentContext(t);e.exchangedAuthCredential&&(o[e.credentialKey]=e.exchangedAuthCredential)}getBucketForCurrentContext(e){let{appName:t,userId:o}=e.invocationContext.session;return this.credentials[t]||(this.credentials[t]={}),this.credentials[t][o]||(this.credentials[t][o]={}),this.credentials[t][o]}};var io=class{loadCredential(e,t){return Promise.resolve(t.state.get(e.credentialKey))}async saveCredential(e,t){e.exchangedAuthCredential&&t.state.set(e.credentialKey,e.exchangedAuthCredential)}};var te=require("zod");var cu=te.z.object({issuer:te.z.string(),authorization_endpoint:te.z.string(),token_endpoint:te.z.string(),scopes_supported:te.z.array(te.z.string()).optional(),registration_endpoint:te.z.string().optional()}),lu=te.z.object({resource:te.z.string(),authorization_servers:te.z.array(te.z.string()).default([])}),so=class{async discoverAuthServerMetadata(e){if(!Ea(e))return;let t,o;try{let i=new URL(e);t=`${i.protocol}//${i.host}`,o=i.pathname}catch(i){m.warn(`Failed to parse issuerUrl ${e}: ${i}`);return}let r=[];o&&o!=="/"?r.push(`${t}/.well-known/oauth-authorization-server${o}`,`${t}/.well-known/openid-configuration${o}`,`${t}${o}/.well-known/openid-configuration`):r.push(`${t}/.well-known/oauth-authorization-server`,`${t}/.well-known/openid-configuration`);for(let i of r)try{let s=await fetch(i,{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)continue;let a=await s.json(),c=cu.parse(a);if(c.issuer.replace(/\/$/,"")===e.replace(/\/$/,""))return c;m.warn(`Issuer in metadata ${c.issuer} does not match issuerUrl ${e}`)}catch(s){m.debug(`Failed to fetch metadata from ${i}: ${s}`)}}async discoverResourceMetadata(e){if(!Ea(e))return;let t,o;try{let i=new URL(e);t=`${i.protocol}//${i.host}`,o=i.pathname}catch(i){m.warn(`Failed to parse resourceUrl ${e}: ${i}`);return}let r;o&&o!=="/"?r=`${t}/.well-known/oauth-protected-resource${o}`:r=`${t}/.well-known/oauth-protected-resource`;try{let i=await fetch(r,{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)return;let s=await i.json(),a=lu.parse(s);if(a.resource.replace(/\/$/,"")===e.replace(/\/$/,""))return a;m.warn(`Resource in metadata ${a.resource} does not match resourceUrl ${e}`)}catch(i){m.debug(`Failed to fetch metadata from ${r}: ${i}`)}}};function Ea(n){try{let e=new URL(n);if(e.protocol!=="https:")return m.warn(`Unsafe protocol for discovery URL: ${e.protocol}`),!1;let t=e.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.startsWith("10.")||t.startsWith("192.168.")||t.startsWith("169.254."))return m.warn(`Unsafe host for discovery URL: ${t}`),!1;let o=t.match(/^172\.(\d+)\./);if(o){let r=parseInt(o[1],10);if(r>=16&&r<=31)return m.warn(`Unsafe host for discovery URL: ${t}`),!1}return!0}catch(e){return m.warn(`Failed to parse URL for validation ${n}: ${e}`),!1}}var ao=class{constructor(){this.refreshers={apiKey:void 0,http:void 0,oauth2:void 0,openIdConnect:void 0,serviceAccount:void 0}}register(e,t){this.refreshers[e]=t}getRefresher(e){return this.refreshers[e]}};var uu="The following is a conversation history between a user and an AI agent. Please summarize the conversation, focusing on key information and decisions made, as well as any unresolved questions or tasks. The summary should be concise and capture the essence of the interaction.",co=class{constructor(e){this.llm=e.llm,this.prompt=e.prompt||uu}async summarize(e){var u,f,d,p,g,C;if(e.length===0)throw new Error("Cannot summarize an empty list of events.");let t=e[0].timestamp,o=e[e.length-1].timestamp,r="";for(let h=0;h<e.length;h++)r+=`[Event ${h+1} - Author: ${e[h].author}]
|
|
94
|
-
`,r+=`${st(e[h])}
|
|
95
|
-
|
|
96
|
-
`;let s={contents:[{role:"user",parts:[{text:`${this.prompt}
|
|
97
|
-
|
|
98
|
-
${r}`}]}],toolsDict:{},liveConnectConfig:{}},a=this.llm.generateContentAsync(s,!1),c="",l=await a.next();if(l.done||!((d=(f=(u=l.value.content)==null?void 0:u.parts)==null?void 0:f[0])!=null&&d.text))throw new Error("LLM failed to return a valid summary.");c+=l.value.content.parts[0].text;for await(let h of a)(C=(g=(p=h.content)==null?void 0:p.parts)==null?void 0:g[0])!=null&&C.text&&(c+=h.content.parts[0].text);return hs({author:"system",content:{role:"model",parts:[{text:c}]},startTime:t,endTime:o,compactedContent:c})}};var lo=class{constructor(e){this.tokenThreshold=e.tokenThreshold,this.eventRetentionSize=e.eventRetentionSize,this.summarizer=e.summarizer}getActiveEvents(e){let t;for(let r=e.length-1;r>=0;r--){let i=e[r];X(i)&&(!t||i.endTime>t.endTime)&&(t=i)}if(!t)return e;let o=e.filter(r=>!X(r)&&r.timestamp>t.endTime);return[t,...o]}shouldCompact(e){let t=e.session.events,o=this.getActiveEvents(t);if(o.filter(s=>!X(s)).length<=this.eventRetentionSize)return!1;let i=0;for(let s of o)i+=fu(s);return i>this.tokenThreshold}async compact(e){let t=e.session.events,o=this.getActiveEvents(t),r=o.filter(u=>!X(u));if(r.length<=this.eventRetentionSize)return;let i=Math.max(0,r.length-this.eventRetentionSize);for(;i>0;){let u=r[i],f=r[i-1];if(pu(u)&&du(f))i--;else break}if(i===0)return;let s=r.slice(0,i),a=o.find(X),c=a?[a,...s]:s,l=await this.summarizer.summarize(c);l.actions||(l.actions={stateDelta:{},artifactDelta:{},requestedAuthConfigs:[],requestedToolConfirmations:{}}),e.session.events.push(l)}};function fu(n){var t;if(((t=n.usageMetadata)==null?void 0:t.promptTokenCount)!==void 0)return n.usageMetadata.promptTokenCount;let e=st(n);return Math.ceil(e.length/4)}function du(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionCall!==void 0))}function pu(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionResponse!==void 0))}var uo=class{constructor(e){var t;this.threshold=e.threshold,this.preserveLeadingEvents=(t=e.preserveLeadingEvents)!=null?t:0}shouldCompact(e){return e.session.events.length>this.threshold+Math.max(0,this.preserveLeadingEvents)}compact(e){let t=e.session.events,o=t.length-this.threshold-Math.max(0,this.preserveLeadingEvents);if(o<=0)return;let r=Math.max(0,this.preserveLeadingEvents);t.splice(r,o)}};var Rt=require("lodash-es");var _r=(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))(_r||{});function ya(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,Rt.isEmpty)(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!(0,Rt.isEmpty)(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!(0,Rt.isEmpty)(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!(0,Rt.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,Rt.isEmpty)(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),he(n)&&e.push({type:"finished",output:void 0}),e}var Lr=Symbol.for("google.adk.baseExampleProvider");function Ta(n){return typeof n=="object"&&n!==null&&Lr in n&&n[Lr]===!0}var xa;xa=Lr;var fo=class{constructor(){this[xa]=!0}};var Ne=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Sa(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=Sa(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=mu(l);if(!u.size)continue;o.some(d=>u.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:gu(c.timestamp)})}return r}};function Sa(n,e){return`${n}/${e}`}function mu(n){return new Set([...n.matchAll(/[A-Za-z]+/g)].map(e=>e[0].toLowerCase()))}function gu(n){return new Date(n).toISOString()}var wt=class extends ve{constructor({models:e,router:t,modelName:o="routed-llm"}){let r=Array.isArray(e)?Object.fromEntries(e.map(a=>[a.model,a])):e,s=`RoutedLlm[${Object.entries(r).map(([a,c])=>`${a} (${c.model})`).join(", ")}]`;super({model:o==="routed-llm"?s:o}),this.models=r,this.router=t}async*generateContentAsync(e,t){m.info(`Routing request via ${this.model}`),yield*Tt(this.models,e,this.router,o=>o.generateContentAsync(e,t))}async connect(e){let o=await Tt(this.models,e,this.router,r=>r.connect(e)).next();if(o.done||o.value===void 0)throw new Error("Failed to establish connection: No connection yielded.");return o.value}};wt=v([L],wt);var po=class extends ie{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: ${he(e)}`);let t=_(e);if(t.length>0){let r=t.map(i=>i.name);this.log(` Function Calls: ${r}`)}let o=Y(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 Mr="adk_request_confirmation",Or="orcas_tool_call_security_check_states",Ra="This tool call needs external confirmation before completion.",Nr=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(Nr||{}),Qt=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},mo=class extends ie{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Qt}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:Ra};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(Or))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(Or))!=null?i:{};r[o]=t,e.state.set(Or,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:Ra};case"ALLOW":return;default:return}}};function wa(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===Mr&&e.push(t.functionCall);return e}var go=class extends de{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new Oe,sessionService:new Z,memoryService:new Ne})}};var Zt=require("@google/genai");var ho=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 Fr=Symbol.for("google.adk.agentTool");function ka(n){return typeof n=="object"&&n!==null&&Fr in n&&n[Fr]===!0}var Ia,ba,Co=class extends(ba=w,Ia=Fr,ba){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[Ia]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(y(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:Zt.Type.OBJECT,properties:{request:{type:Zt.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=y(this.agent)&&this.agent.outputSchema;t.response=o?{type:Zt.Type.OBJECT}:{type:Zt.Type.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,d,p,g,C,h;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:y(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new de({appName:this.agent.name,agent:this.agent,artifactService:new ho(o),sessionService:(f=o.invocationContext.sessionService)!=null?f:new Z,memoryService:(d=o.invocationContext.memoryService)!=null?d:new Ne,credentialService:o.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:o.invocationContext.userId,sessionId:o.invocationContext.session.id,state:o.state.toRecord()});if((p=o.abortSignal)!=null&&p.aborted)return"";let c;for await(let A of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i,abortSignal:o.abortSignal})){if((g=o.abortSignal)!=null&&g.aborted)return;A.actions.stateDelta&&o.state.update(A.actions.stateDelta),c=A}if(!((h=(C=c==null?void 0:c.content)==null?void 0:C.parts)!=null&&h.length))return"";let l=y(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(A=>A.text).filter(A=>A).join(`
|
|
99
|
-
`);return l?JSON.parse(u):u}};var en=class extends w{constructor(){super({name:"exit_loop",description:`Exits the loop.
|
|
100
|
-
|
|
101
|
-
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,""}},Pa=new en;var tn=class extends w{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||[],is(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(rs(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${e.model}`)}}},_a=new tn;var vo=require("@google/genai");var hu=dn(),Cu=["image/","audio/","video/"],vu=new Set(["application/pdf"]),Au=new Set(["application/csv","application/json","application/xml"]);function La(n){if(n)return n.split(";")[0].trim()}function Eu(n){let e=La(n);return e?Cu.some(t=>e.startsWith(t))||vu.has(e):!1}function yu(n,e){let t=n.inlineData;if(!t||Eu(t.mimeType))return n;let o=La(t.mimeType)||"application/octet-stream",r=t.data;if(!r)return{text:`[Artifact: ${e}, type: ${o}. No inline data was provided.]`};let i=o.startsWith("text/")||Au.has(o),s=Buffer.from(r,"base64");if(i)try{return{text:s.toString("utf8")}}catch{}let a=s.length/1024;return{text:`[Binary artifact: ${e}, type: ${o}, size: ${a.toFixed(1)} KB. Content cannot be displayed inline.]`}}var nn=class extends w{constructor(){super({name:"load_artifacts",description:`Loads artifacts into the session for this request.
|
|
102
|
-
|
|
103
|
-
NOTE: Call when you need access to artifacts (for example, uploads saved by the web UI).`})}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:vo.Type.OBJECT,properties:{artifact_names:{type:vo.Type.ARRAY,items:{type:vo.Type.STRING},description:"The names of the artifacts to load."}}}}}async runAsync({args:e}){return{artifact_names:e.artifact_names||[],status:"artifact contents temporarily inserted and removed. to access these artifacts, call load_artifacts tool again."}}async processLlmRequest(e){await super.processLlmRequest(e),await this.appendArtifactsToLlmRequest(e.toolContext,e.llmRequest)}async appendArtifactsToLlmRequest(e,t){if(!e.invocationContext.artifactService)return;let o=await e.listArtifacts();if(!o||o.length===0)return;z(t,[`You have a list of artifacts:
|
|
104
|
-
${JSON.stringify(o)}
|
|
105
|
-
|
|
106
|
-
When the user asks questions about any of the artifacts, you should call the
|
|
107
|
-
\`load_artifacts\` function to load the artifact. Always call load_artifacts
|
|
108
|
-
before answering questions related to the artifacts, regardless of whether the
|
|
109
|
-
artifacts have been loaded before. Do not depend on prior answers about the
|
|
110
|
-
artifacts.`]);let r=t.contents;if(r&&r.length>0){let i=r[r.length-1];if(i.role==="user"&&i.parts&&i.parts.length>0){let a=i.parts[0].functionResponse;if(a&&a.name==="load_artifacts"){let l=(a.response||{}).artifact_names||[];for(let u of l){let f=await e.loadArtifact(u);if(!f&&!u.startsWith("user:")){let p=`user:${u}`;f=await e.loadArtifact(p)}if(!f){hu.warn(`Artifact "${u}" not found, skipping`);continue}let d=yu(f,u);t.contents.push({role:"user",parts:[{text:`Artifact ${u} is:`},d]})}}}}}},Oa=new nn;var Br=require("@google/genai");var on=class extends w{constructor(){super({name:"load_memory",description:`Loads the memory for the current user.
|
|
111
|
-
|
|
112
|
-
NOTE: Currently this tool only uses text part from the memory.`})}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:Br.Type.OBJECT,properties:{query:{type:Br.Type.STRING,description:"The query to load the memory for."}},required:["query"]}}}async runAsync({args:e,toolContext:t}){try{let o=e.query;if(!t.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return{memories:(await t.searchMemory(o)).memories.map(i=>{var s,a;return{content:(a=(s=i.content.parts)==null?void 0:s.map(c=>{var l;return(l=c.text)!=null?l:""}).join(" "))!=null?a:"",author:i.author,timestamp:i.timestamp}})}}catch(o){throw console.error("ERROR in LoadMemoryTool runAsync:",o),o}}async processLlmRequest(e){await super.processLlmRequest(e),e.toolContext.invocationContext.memoryService&&z(e.llmRequest,[`You have memory. You can use it to answer questions. If any questions need
|
|
113
|
-
you to look up the memory, you should call load_memory function with a query.`])}},Ma=new on;var Na=`
|
|
114
|
-
|
|
115
|
-
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,Ao=class extends fe{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Na:e.description=Na.trimStart(),e}};var rn=class extends w{constructor(){super({name:"preload_memory",description:"preload_memory"})}async runAsync({args:e,toolContext:t}){throw new Error("PreloadMemoryTool should not be called by model")}async processLlmRequest(e){var c,l,u;await super.processLlmRequest(e);let t=e.toolContext.userContent;if(!t||!t.parts||!((c=t.parts[0])!=null&&c.text))return;let o=t.parts[0].text,r;try{if(!e.toolContext.invocationContext.memoryService)return;r=await e.toolContext.searchMemory(o)}catch{m.warn(`Failed to preload memory for query: ${o}`);return}if(!r.memories||r.memories.length===0)return;let i=[];for(let f of r.memories){let d=f.timestamp?`Time: ${f.timestamp}`:"";d&&i.push(d);let p=(u=(l=f.content.parts)==null?void 0:l.map(g=>{var C;return(C=g.text)!=null?C:""}).join(" "))!=null?u:"";p&&i.push(f.author?`${f.author}: ${p}`:p)}if(i.length===0)return;let a=`The following content is from your previous conversations with the user.
|
|
116
|
-
They may be useful for answering the user's current query.
|
|
117
|
-
<PAST_CONVERSATIONS>
|
|
118
|
-
${i.join(`
|
|
119
|
-
`)}
|
|
120
|
-
</PAST_CONVERSATIONS>
|
|
121
|
-
`;z(e.llmRequest,[a])}},Fa=new rn;var Da=require("@google/genai");function Ba(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Eo(n){if(!n||n.length===0)return`<available_skills>
|
|
122
|
-
</available_skills>`;let e=["<available_skills>"];for(let t of n){let o="frontmatter"in t?t.frontmatter:t;e.push(" <skill>"),e.push(` <name>${Ba(o.name)}</name>`),e.push(` <description>${Ba(o.description)}</description>`),e.push(" </skill>")}return e.push("</available_skills>"),e.join(`
|
|
123
|
-
`)}var Fe=class extends w{constructor(t){super({name:"list_skills",description:"Lists all available skills with their names and descriptions."});this.toolset=t}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:Da.Type.OBJECT,properties:{}}}}async runAsync(t){let o=Object.values(this.toolset.skills);return Eo(o)}};Fe=v([L],Fe);var yo=require("@google/genai"),$a=P(require("path"),1);var Ua="Binary file detected. The content has been injected into the conversation history for you to analyze.",xu={pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",csv:"text/csv",json:"application/json",xml:"application/xml",sh:"text/x-shellscript",bash:"text/x-shellscript",py:"text/x-python",js:"text/javascript",cjs:"text/javascript",mjs:"text/javascript",ts:"text/javascript",cts:"text/javascript",mts:"text/javascript"};function Tu(n){var t;let e=((t=n.split(".").pop())==null?void 0:t.toLowerCase())||"";return xu[e]||"application/octet-stream"}var Be=class extends w{constructor(t){super({name:"load_skill_resource",description:"Loads a resource file (from references/, assets/, or scripts/) from within a skill."});this.toolset=t}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:yo.Type.OBJECT,properties:{skill_name:{type:yo.Type.STRING,description:"The name of the skill."},path:{type:yo.Type.STRING,description:"The relative path to the resource (e.g., 'references/my_doc.md', 'assets/template.txt', or 'scripts/setup.sh')."}},required:["skill_name","path"]}}}async runAsync({args:t}){var c,l,u;let o=t.skill_name,r=t.path;if(!o)return{error:"Skill name is required.",error_code:"MISSING_SKILL_NAME"};if(!r)return{error:"Resource path is required.",error_code:"MISSING_RESOURCE_PATH"};r=$a.default.posix.normalize(r);let i=this.toolset.getSkill(o);if(!i)return{error:`Skill '${o}' not found.`,error_code:"SKILL_NOT_FOUND"};let s,a=i.resources||{};if(r.startsWith("references/")){let f=r.substring(11);s=(c=a.references)==null?void 0:c[f]}else if(r.startsWith("assets/")){let f=r.substring(7);s=(l=a.assets)==null?void 0:l[f]}else if(r.startsWith("scripts/")){let f=r.substring(8),d=(u=a.scripts)==null?void 0:u[f];d&&(s=d.src)}else return{error:"Path must start with 'references/', 'assets/', or 'scripts/'.",error_code:"INVALID_RESOURCE_PATH"};return s===void 0?{error:`Resource '${r}' not found in skill '${o}'.`,error_code:"RESOURCE_NOT_FOUND"}:Buffer.isBuffer(s)?{skill_name:o,path:r,status:Ua}:{skill_name:o,path:r,content:s}}async processLlmRequest(t){var i,s;await super.processLlmRequest(t);let o=t.llmRequest;if(!o.contents||o.contents.length===0)return;let r=o.contents[o.contents.length-1];if(!(r.role!=="user"||!r.parts)){for(let a of r.parts)if(a.functionResponse&&a.functionResponse.name===this.name){let c=a.functionResponse.response||{};if(c.status===Ua){let l=c.skill_name,u=c.path,f=this.toolset.getSkill(l);if(!f)continue;let d=f.resources||{},p;if(u.startsWith("references/")?p=(i=d.references)==null?void 0:i[u.substring(11)]:u.startsWith("assets/")&&(p=(s=d.assets)==null?void 0:s[u.substring(7)]),Buffer.isBuffer(p)){let g=Tu(u);o.contents.push({role:"user",parts:[{text:`The content of binary file '${u}' is:`},{inlineData:{data:p.toString("base64"),mimeType:g}}]})}}}}}};Be=v([L],Be);var Dr=require("@google/genai");var De=class extends w{constructor(t){super({name:"load_skill",description:"Loads the SKILL.md instructions for a given skill."});this.toolset=t}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:Dr.Type.OBJECT,properties:{name:{type:Dr.Type.STRING,description:"The name of the skill to load."}},required:["name"]}}}async runAsync({args:t,toolContext:o}){let r=t.name;if(!r)return{error:"Skill name is required.",error_code:"MISSING_SKILL_NAME"};let i=this.toolset.getSkill(r);if(!i)return{error:`Skill '${r}' not found.`,error_code:"SKILL_NOT_FOUND"};let a=`_adk_activated_skill_${o.invocationContext.agent.name}`,c=o.state.get(a)||[];return c.includes(r)||o.state.set(a,[...c,r]),{skill_name:r,instructions:i.instructions,frontmatter:i.frontmatter,resources:i.resources}}};De=v([L],De);var rt=require("@google/genai");var Ue=class extends w{constructor(t){super({name:"run_skill_inline_script",description:"Executes an inline script provided directly in the request."});this.toolset=t}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:rt.Type.OBJECT,properties:{script_content:{type:rt.Type.STRING,description:"The content of the script to execute."},language:{type:rt.Type.STRING,description:"The language/type of the script.",enum:Object.values(ye).filter(t=>t!=="unspecified")},args:{anyOf:[{type:rt.Type.OBJECT},{type:rt.Type.ARRAY,items:{type:rt.Type.STRING}}],description:"Optional arguments to pass to the script as key-value pairs or an array of strings."}},required:["script_content","language"]}}}async runAsync({args:t,toolContext:o}){var c;let r=t.script_content,i=t.language,s=t.args;if(!r)return{error:"Script content is required.",errorCode:"MISSING_SCRIPT_CONTENT"};if(!i)return{error:"Language is required.",errorCode:"MISSING_LANGUAGE"};let a=(c=this.toolset)==null?void 0:c.codeExecutor;if(!a){let l=o.invocationContext.agent;y(l)&&(a=l.codeExecutor)}if(!a)return{error:"No code executor configured.",errorCode:"NO_CODE_EXECUTOR"};try{let l=await a.executeCode({invocationContext:o.invocationContext,codeExecutionInput:{code:r,inputFiles:[],language:i,args:s}});return l.outputFiles=await xt(l.outputFiles),l}catch(l){return{error:`Failed to execute inline script: ${l.message}`,errorCode:"EXECUTION_ERROR"}}}};Ue=v([L],Ue);var sn=require("@google/genai"),Ur=P(require("path"),1);var $e=class extends w{constructor(t){super({name:"run_skill_script",description:"Executes a script from a skill's scripts/ directory."});this.toolset=t}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:sn.Type.OBJECT,properties:{skill_name:{type:sn.Type.STRING,description:"The name of the skill."},script_path:{type:sn.Type.STRING,description:"The relative path to the script (e.g., 'scripts/setup.js')."},args:{type:sn.Type.OBJECT,description:"Optional arguments to pass to the script as key-value pairs."}},required:["skill_name","script_path"]}}}async runAsync({args:t,toolContext:o}){var f,d,p,g;let r=t.skill_name,i=t.script_path,s=t.args||{};if(!r)return{error:"Skill name is required.",errorCode:"MISSING_SKILL_NAME"};if(!i)return{error:"Script path is required.",errorCode:"MISSING_SCRIPT_PATH"};let a=this.toolset.getSkill(r);if(!a)return{error:`Skill '${r}' not found.`,errorCode:"SKILL_NOT_FOUND"};let c=i.startsWith("scripts/")?i.substring(8):i,l=(d=(f=a.resources)==null?void 0:f.scripts)==null?void 0:d[c];if(l||(l=(g=(p=a.resources)==null?void 0:p.scripts)==null?void 0:g[i]),!l)return{error:`Script '${i}' not found in skill '${r}'.`,errorCode:"SCRIPT_NOT_FOUND"};let u=this.toolset.codeExecutor;if(!u){let C=o.invocationContext.agent;y(C)&&(u=C.codeExecutor)}if(!u)return{error:"No code executor configured.",errorCode:"NO_CODE_EXECUTOR"};try{let C=ga(Ur.extname(i)),h=await u.executeCode({invocationContext:o.invocationContext,codeExecutionInput:{code:Su(i,C),inputFiles:Ru(a),language:C,args:s}});return h.outputFiles=await xt(h.outputFiles),h}catch(C){return{error:`Failed to execute script '${i}': ${C.message}`,errorCode:"EXECUTION_ERROR"}}}};$e=v([L],$e);function Su(n,e){switch(e){case"javascript":return`require('./${n}');`;case"typescript":return`require('ts-node/register');
|
|
124
|
-
require('./${n}');`;case"python":return`import runpy
|
|
125
|
-
runpy.run_path('./${n}', run_name='__main__')`;case"shell":return`source ./${n} "$@"`;case"powershell":return`& .\\${n.replace(/\//g,"\\\\")} $args`;case"cmd":return`call .\\${n.replace(/\//g,"\\\\")} %*`;default:throw new Error(`Unsupported wrapper language: ${e}`)}}function Ru(n){var t,o,r;let e=[];for(let i of["references","assets","scripts"]){let s=(o=(t=n.resources)==null?void 0:t[i])!=null?o:{};for(let a of Object.keys(s)){let c=(r=s[a])!=null?r:void 0;if(c===void 0)continue;let l;if(typeof c=="string"||Buffer.isBuffer(c)?l=c:typeof c=="object"&&c!==null&&"src"in c&&typeof c.src=="string"&&(l=c.src),l===void 0)continue;let u=Ur.extname(a).toLowerCase(),{encoding:f,mimeType:d}=Jn(u);e.push({name:`${i}/${a}`,content:Buffer.from(l).toString(f),contentEncoding:f,mimeType:d})}}return e}var wu="You can use specialized 'skills' to help you with complex tasks. You MUST use the skill tools to interact with these skills.\n\nSkills are folders of instructions and resources that extend your capabilities for specialized tasks. Each skill folder contains:\n- **SKILL.md** (required): The main instruction file with skill metadata and detailed markdown instructions.\n- **references/** (Optional): Additional documentation or examples for skill usage.\n- **assets/** (Optional): Templates, scripts or other resources used by the skill.\n- **scripts/** (Optional): Executable scripts that can be run via bash.\n\nThis is very important:\n\n1. If a skill seems relevant to the current user query, you MUST use the `load_skill` tool with `name=\"<SKILL_NAME>\"` to read its full instructions before proceeding.\n2. Once you have read the instructions, follow them exactly as documented before replying to the user. For example, If the instruction lists multiple steps, please make sure you complete all of them in order.\n3. The `load_skill_resource` tool is for viewing files within a skill's directory (e.g., `references/*`, `assets/*`, `scripts/*`). Do NOT use other tools to access these files.\n4. Use `run_skill_script` to run scripts from a skill's `scripts/` directory. Use `load_skill_resource` to view script content first if needed.\n",It=class extends xe{constructor(t,o={}){super([],"adk_skill_toolset");this.toolCache=new Map;this.skills=Array.isArray(t)?Object.fromEntries(t.map(r=>[r.frontmatter.name,r])):t,this.codeExecutor=o.codeExecutor,this.additionalTools=o.additionalTools||[],this.tools=[new Fe(this),new De(this),new Be(this),new $e(this),new Ue(this)]}async getTools(t){let o=await this.resolveAdditionalTools(t);return[...this.tools,...o]}async close(){}getSkill(t){return this.skills[t]}async processLlmRequest(t,o){await super.processLlmRequest(t,o);let r=Object.values(this.skills),i=Eo(r);z(o,[wu,i])}async resolveAdditionalTools(t){if(!t)return[];let o=t.agentName,r=`_adk_activated_skill_${o}`,i=t.state.get(r)||[];if(i.length===0)return[];let s=`${o}:${i.join(",")}`;if(this.toolCache.has(s))return this.toolCache.get(s);let a=new Set;for(let f of i){let d=this.skills[f];if(d&&d.frontmatter.metadata){let p=d.frontmatter.metadata.adk_additional_tools;p&&p.forEach(g=>a.add(g))}}if(a.size===0)return this.toolCache.set(s,[]),[];let c={};for(let f of this.additionalTools)if(f instanceof w){if(c[f.name])throw new Error(`Duplicate tool name: ${f.name}`);c[f.name]=f}else if(f instanceof xe){let d=await f.getTools(t);for(let p of d){if(c[p.name])throw new Error(`Duplicate tool name: ${p.name}`);c[p.name]=p}}let l=[],u=new Set(this.tools.map(f=>f.name));for(let f of a)if(c[f]){let d=c[f];u.has(d.name)||(l.push(d),u.add(d.name))}return this.toolCache.set(s,l),l}};It=v([L],It);var xo=require("@mikro-orm/core");var R=require("@mikro-orm/core");var qr="schema_version",Gr="1",$r=class extends R.JsonType{convertToDatabaseValue(e){return JSON.stringify(ti(e))}convertToJSValue(e){return typeof e=="string"?bo(JSON.parse(e)):bo(e)}},me=class{};v([(0,R.PrimaryKey)({type:"string"})],me.prototype,"key",2),v([(0,R.Property)({type:"string"})],me.prototype,"value",2),me=v([(0,R.Entity)({tableName:"adk_internal_metadata"})],me);var W=class{constructor(){this.updateTime=new Date}};v([(0,R.PrimaryKey)({type:"string",fieldName:"app_name"})],W.prototype,"appName",2),v([(0,R.Property)({type:"json"})],W.prototype,"state",2),v([(0,R.Property)({type:"datetime",fieldName:"update_time",onCreate:()=>new Date,onUpdate:()=>new Date})],W.prototype,"updateTime",2),W=v([(0,R.Entity)({tableName:"app_states"})],W);R.PrimaryKey.name;var $=class{constructor(){this.updateTime=new Date}};v([(0,R.PrimaryKey)({type:"string",fieldName:"app_name"})],$.prototype,"appName",2),v([(0,R.PrimaryKey)({type:"string",fieldName:"user_id"})],$.prototype,"userId",2),v([(0,R.Property)({type:"json"})],$.prototype,"state",2),v([(0,R.Property)({type:"datetime",fieldName:"update_time",onCreate:()=>new Date,onUpdate:()=>new Date})],$.prototype,"updateTime",2),$=v([(0,R.Entity)({tableName:"user_states"})],$);R.PrimaryKey.name;var D=class{constructor(){this.createTime=new Date;this.updateTime=new Date}};v([(0,R.PrimaryKey)({type:"string"})],D.prototype,"id",2),v([(0,R.PrimaryKey)({type:"string",fieldName:"app_name"})],D.prototype,"appName",2),v([(0,R.PrimaryKey)({type:"string",fieldName:"user_id"})],D.prototype,"userId",2),v([(0,R.Property)({type:"json"})],D.prototype,"state",2),v([(0,R.Property)({type:"datetime",fieldName:"create_time",onCreate:()=>new Date})],D.prototype,"createTime",2),v([(0,R.Property)({type:"datetime",fieldName:"update_time",onCreate:()=>new Date})],D.prototype,"updateTime",2),D=v([(0,R.Entity)({tableName:"sessions"})],D);R.PrimaryKey.name;var U=class{};v([(0,R.PrimaryKey)({type:"string"})],U.prototype,"id",2),v([(0,R.PrimaryKey)({type:"string",fieldName:"app_name"})],U.prototype,"appName",2),v([(0,R.PrimaryKey)({type:"string",fieldName:"user_id"})],U.prototype,"userId",2),v([(0,R.PrimaryKey)({type:"string",fieldName:"session_id"})],U.prototype,"sessionId",2),v([(0,R.Property)({type:"string",fieldName:"invocation_id"})],U.prototype,"invocationId",2),v([(0,R.Property)({type:"datetime"})],U.prototype,"timestamp",2),v([(0,R.Property)({type:$r,fieldName:"event_data"})],U.prototype,"eventData",2),U=v([(0,R.Entity)({tableName:"events"})],U);var an=[me,W,$,D,U];async function qa(n){let e;if(n.startsWith("postgres://")||n.startsWith("postgresql://")){let{PostgreSqlDriver:t}=await Promise.resolve().then(()=>P(require("@mikro-orm/postgresql"),1));e=t}else if(n.startsWith("mysql://")){let{MySqlDriver:t}=await Promise.resolve().then(()=>P(require("@mikro-orm/mysql"),1));e=t}else if(n.startsWith("mariadb://")){let{MariaDbDriver:t}=await Promise.resolve().then(()=>P(require("@mikro-orm/mariadb"),1));e=t}else if(n.startsWith("sqlite://")){let{SqliteDriver:t}=await Promise.resolve().then(()=>P(require("@mikro-orm/sqlite"),1));e=t}else if(n.startsWith("mssql://")){let{MsSqlDriver:t}=await Promise.resolve().then(()=>P(require("@mikro-orm/mssql"),1));e=t}else throw new Error(`Unsupported database URI: ${n}`);return n.startsWith("sqlite://")?{entities:an,dbName:n==="sqlite://:memory:"?":memory:":n.substring(9),driver:e}:{entities:an,clientUrl:n,driver:e}}async function Ga(n){await n.schema.ensureDatabase(),await n.schema.updateSchema({safe:!0})}async function ja(n){let e=n.em.fork(),t=await e.findOne(me,{key:qr});if(t){if(t.value!==Gr)throw new Error(`ADK Database schema version ${t.value} is not compatible.`);return}let o=e.create(me,{key:qr,value:Gr});await e.persist(o).flush()}function Va(n){return n?n.startsWith("postgres://")||n.startsWith("postgresql://")||n.startsWith("mysql://")||n.startsWith("mariadb://")||n.startsWith("mssql://")||n.startsWith("sqlite://"):!1}var bt=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:an}}}async init(){this.initialized||(this.connectionString&&(!this.options||!this.options.driver)&&(this.options=await qa(this.connectionString)),this.orm=await xo.MikroORM.init(this.options),await Ga(this.orm),await ja(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||k(),c=new Date;if(await s.findOne(D,{id:a,appName:t,userId:o}))throw new Error(`Session with id ${a} already exists.`);let u=await s.findOne(W,{appName:t});u||(u=s.create(W,{appName:t,state:{},updateTime:c}),s.persist(u));let f=await s.findOne($,{appName:t,userId:o});f||(f=s.create($,{appName:t,userId:o,state:{}}),s.persist(f));let d={},p={},g={};if(r)for(let[A,H]of Object.entries(r))A.startsWith(T.APP_PREFIX)?d[A.replace(T.APP_PREFIX,"")]=H:A.startsWith(T.USER_PREFIX)?p[A.replace(T.USER_PREFIX,"")]=H:g[A]=H;Object.keys(d).length>0&&(u.state={...u.state,...d}),Object.keys(p).length>0&&(f.state={...f.state,...p});let C=s.create(D,{id:a,appName:t,userId:o,state:g,createTime:c,updateTime:c});s.persist(C),await s.flush();let h=pe(u.state,f.state,g);return Te({id:a,appName:t,userId:o,state:h,events:[],lastUpdateTime:C.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(D,{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(U,c,{orderBy:{timestamp:"DESC"},limit:i==null?void 0:i.numRecentEvents});l.reverse();let u=await s.findOne(W,{appName:t}),f=await s.findOne($,{appName:t,userId:o}),d=pe((u==null?void 0:u.state)||{},(f==null?void 0:f.state)||{},a.state);return Te({id:r,appName:t,userId:o,state:d,events:l.map(p=>p.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(D,i),a=await r.findOne(W,{appName:t}),c=(a==null?void 0:a.state)||{},l={};if(o){let f=await r.findOne($,{appName:t,userId:o});f&&(l[o]=f.state)}else{let f=await r.find($,{appName:t});for(let d of f)l[d.userId]=d.state}return{sessions:s.map(f=>{let d=l[f.userId]||{},p=pe(c,d,f.state);return Te({id:f.id,appName:f.appName,userId:f.userId,state:p,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(D,{appName:t,userId:o,id:r}),await i.nativeDelete(U,{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=Vn(o);return await r.transactional(async s=>{let a=await s.findOne(D,{appName:t.appName,userId:t.userId,id:t.id},{lockMode:xo.LockMode.PESSIMISTIC_WRITE});if(!a)throw new Error(`Session ${t.id} not found for appendEvent`);let c=await s.findOne(W,{appName:t.appName});c||(c=s.create(W,{appName:t.appName,state:{},updateTime:new Date}),s.persist(c));let l=await s.findOne($,{appName:t.appName,userId:t.userId});if(l||(l=s.create($,{appName:t.appName,userId:t.userId,state:{}}),s.persist(l)),a.updateTime.getTime()>t.lastUpdateTime){let d=await s.find(U,{appName:t.appName,userId:t.userId,sessionId:t.id},{orderBy:{timestamp:"ASC"}}),p=pe(c.state,l.state,a.state);t.state=p,t.events=d.map(g=>g.eventData)}if(o.actions&&o.actions.stateDelta){let d={},p={},g={};for(let[C,h]of Object.entries(o.actions.stateDelta))C.startsWith(T.APP_PREFIX)?d[C.replace(T.APP_PREFIX,"")]=h:C.startsWith(T.USER_PREFIX)?p[C.replace(T.USER_PREFIX,"")]=h:g[C]=h;Object.keys(d).length>0&&(c.state={...c.state,...d}),Object.keys(p).length>0&&(l.state={...l.state,...p}),Object.keys(g).length>0&&(a.state={...a.state,...g})}let u=s.create(U,{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=pe(c.state,l.state,a.state);t.state=f,t.events.push(o),t.lastUpdateTime=a.updateTime.getTime()}),o}};function za(n){if(ta(n))return new Z;if(Va(n))return new bt(n);throw new Error(`Unsupported session service URI: ${n}`)}var Wa=P(require("js-yaml"),1),ge=P(require("fs/promises"),1),N=P(require("path"),1);var se=require("zod");var Iu=/^([a-z0-9]+(-[a-z0-9]+)*|[a-z0-9]+(_[a-z0-9]+)*)$/,jr=se.z.preprocess(n=>{if(typeof n=="object"&&n!==null){let e=n;if("allowed-tools"in e&&!("allowedTools"in e))return{...e,allowedTools:e["allowed-tools"]}}return n},se.z.object({name:se.z.string().regex(Iu,{message:"name must be lowercase kebab-case (a-z, 0-9, hyphens) or snake_case (a-z, 0-9, underscores), with no leading, trailing, or consecutive delimiters. Mixing hyphens and underscores is not allowed."}).max(64),description:se.z.string().min(1).max(1024),license:se.z.string().optional(),compatibility:se.z.string().max(500).optional(),"allowed-tools":se.z.string().optional(),metadata:se.z.record(se.z.string(),se.z.any()).default({}).refine(n=>"adk_additional_tools"in n?Array.isArray(n.adk_additional_tools)&&n.adk_additional_tools.every(e=>typeof e=="string"):!0,{message:"adk_additional_tools must be a list of strings"})}).loose());var bu=new Set(["name","description","license","allowed-tools","metadata","compatibility"]),Ha=new Set(["__pycache__",".pytest_cache",".mypy_cache",".ruff_cache","node_modules","coverage","venv",".venv","env",".env",".git",".vscode",".idea"]),ku=new Set([".pyc",".pyo",".pyd",".tsbuildinfo",".DS_Store"]);async function Vr(n){let e={};async function t(o){let r=await ge.readdir(o,{withFileTypes:!0});for(let i of r){let s=N.join(o,i.name);if(i.isDirectory()){if(Ha.has(i.name))continue;await t(s)}else if(i.isFile()){let a=N.relative(n,s);if(ku.has(N.extname(i.name)))continue;let c=await ge.readFile(s);try{e[a]=c.toString("utf-8")}catch{e[a]=c}}}}try{(await ge.stat(n)).isDirectory()&&await t(n)}catch(o){m.warn(`Failed to load directory '${n}': ${o.message}`)}return e}function Pu(n){if(!n.startsWith("---"))throw new Error("SKILL.md must start with YAML frontmatter (---)");let e=n.split("---",3);if(e.length<3)throw new Error("SKILL.md frontmatter not properly closed with ---");let t=e[1],o=e[2].trim();try{let r=Wa.default.load(t);if(typeof r!="object"||r===null)throw new Error("SKILL.md frontmatter must be a YAML mapping");return{frontmatter:jr.parse(r),body:o}}catch(r){throw new Error(`Invalid YAML in frontmatter: ${r.message}`)}}async function zr(n){let e=N.resolve(n),t=await Ya(n),o=N.join(e,"references"),r=N.join(e,"assets"),i=N.join(e,"scripts"),[s,a,c]=await Promise.all([Vr(o),Vr(r),Vr(i)]),l={};for(let[f,d]of Object.entries(c))typeof d=="string"&&(l[f]={src:d});return{...t,resources:{references:s,assets:a,scripts:l}}}async function Ka(n){let e=[],t=N.resolve(n),o;try{o=await Ya(t)}catch(r){return[r.message]}try{let i=Object.keys(o.frontmatter).filter(a=>!bu.has(a));i.length>0&&e.push(`Unknown frontmatter fields: [${i.sort().join(", ")}]`);let s=N.basename(t);s!==o.frontmatter.name&&e.push(`Skill name '${o.frontmatter.name}' does not match directory name '${s}'.`)}catch(r){e.push(r.message)}return e}async function Ya(n){let e=N.resolve(n),t="",o="";try{let c=await ge.readdir(e,{withFileTypes:!0});for(let l of c)if(l.isFile()&&l.name.toLowerCase()==="skill.md"){let u=N.join(e,l.name);try{o=await ge.readFile(u,"utf-8"),t=u;break}catch{}}}catch(c){m.warn(`Failed to load directory '${n}': ${c.message}`)}if(!t)throw new Error(`SKILL.md (or any case variation like skill.md) not found in '${n}'.`);let{frontmatter:r,body:i}=Pu(o),s=jr.parse(r),a=N.basename(e);if(a!==s.name)throw new Error(`Skill name '${s.name}' does not match directory name '${a}'.`);return{frontmatter:s,instructions:i}}async function Ja(n){let e=N.resolve(n),t={};async function o(r){let i;try{i=await ge.readdir(r,{withFileTypes:!0})}catch{return}let s=!1;if(r!==e){for(let a of i)if(a.isFile()&&a.name.toLowerCase()==="skill.md"){s=!0;break}}if(s)try{let a=await zr(r);t[a.frontmatter.name]=a}catch(a){m.warn(`Skipping invalid skill in '${r}':`,a)}else for(let a of i)if(a.isDirectory()){if(Ha.has(a.name))continue;await o(N.join(r,a.name))}}try{await ge.readdir(e),await o(e)}catch(r){m.warn(`Skills base path '${n}' is not a directory.`,r)}return t}var Xa=require("@google-cloud/opentelemetry-cloud-monitoring-exporter"),Qa=require("@google-cloud/opentelemetry-cloud-trace-exporter"),Za=require("@opentelemetry/resource-detector-gcp"),ec=require("@opentelemetry/resources"),tc=require("@opentelemetry/sdk-metrics"),nc=require("@opentelemetry/sdk-trace-base"),oc=require("google-auth-library");var _u="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Lu(){try{return await new oc.GoogleAuth().getProjectId()||void 0}catch{return}}async function Ou(n={}){let{enableTracing:e=!1,enableMetrics:t=!1}=n,o=await Lu();return o?{spanProcessors:e?[new nc.BatchSpanProcessor(new Qa.TraceExporter({projectId:o}))]:[],metricReaders:t?[new tc.PeriodicExportingMetricReader({exporter:new Xa.MetricExporter({projectId:o}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(m.warn(_u),{})}function Mu(){return(0,ec.detectResources)({detectors:[Za.gcpDetector]})}var To=require("@opentelemetry/api"),rc=require("@opentelemetry/api-logs"),ic=require("@opentelemetry/exporter-logs-otlp-http"),sc=require("@opentelemetry/exporter-metrics-otlp-http"),ac=require("@opentelemetry/exporter-trace-otlp-http"),cc=require("@opentelemetry/resources"),So=require("@opentelemetry/sdk-logs"),Ro=require("@opentelemetry/sdk-metrics"),lc=require("@opentelemetry/sdk-trace-base"),uc=require("@opentelemetry/sdk-trace-node");function Nu(n=[],e){let t=e||Fu(),o=[...n,Du()],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 uc.NodeTracerProvider({resource:t,spanProcessors:r});a.register(),To.trace.setGlobalTracerProvider(a)}if(i.length>0){let a=new Ro.MeterProvider({readers:i,resource:t});To.metrics.setGlobalMeterProvider(a)}if(s.length>0){let a=new So.LoggerProvider({resource:t,processors:s});rc.logs.setGlobalLoggerProvider(a)}}function Fu(){return(0,cc.detectResources)({detectors:[]})}function Bu(){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 Du(n=Bu()){let{enableTracing:e,enableMetrics:t,enableLogging:o}=n;return{spanProcessors:e?[new lc.BatchSpanProcessor(new ac.OTLPTraceExporter)]:[],metricReaders:t?[new Ro.PeriodicExportingMetricReader({exporter:new sc.OTLPMetricExporter})]:[],logRecordProcessors:o?[new So.BatchLogRecordProcessor(new ic.OTLPLogExporter)]:[]}}var fc=require("@modelcontextprotocol/sdk/client/index.js"),dc=require("@modelcontextprotocol/sdk/client/stdio.js"),pc=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var cn=class{constructor(e){this.connectionParams=e}async createSession(){var t;let e=new fc.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new dc.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 pc.StreamableHTTPClientTransport(new URL(this.connectionParams.url),o));break}default:{let o=this.connectionParams;break}}return e}};var ne=require("@google/genai"),it=require("zod");var bT=it.z.object({type:it.z.literal("object"),properties:it.z.record(it.z.string(),it.z.unknown()).optional(),required:it.z.string().array().optional()});function Uu(n){if(!n)return ne.Type.TYPE_UNSPECIFIED;switch(n.toLowerCase()){case"text":case"string":return ne.Type.STRING;case"number":return ne.Type.NUMBER;case"boolean":return ne.Type.BOOLEAN;case"integer":return ne.Type.INTEGER;case"array":return ne.Type.ARRAY;case"object":return ne.Type.OBJECT;case"null":return ne.Type.NULL;default:return ne.Type.TYPE_UNSPECIFIED}}var mc=n=>{var e,t;return typeof n=="string"?n.toLowerCase():(t=(e=n==null?void 0:n.type)==null?void 0:e.toLowerCase)==null?void 0:t.call(e)};function Wr(n){if(!n)return;function e(t){var c;let o=(c=t.anyOf)!=null?c:t.type,r=!1,i;if(Array.isArray(o)){if(i=o.filter(l=>mc(l)!=="null"),r=o.some(l=>mc(l)==="null"),i.length===1){let l=i[0];if(typeof l=="object")t=l;else{let{type:u,anyOf:f,...d}=t;t={...d,type:l}}}else if(i.length===0&&r){let{type:l,anyOf:u,...f}=t;t={...f,type:"null"}}else if(typeof t.anyOf>"u"){let l=t.type.map(d=>({type:d})),{type:u,...f}=t;t={...f,anyOf:l}}}t.type||(t.properties||t.$ref?t.type="object":t.items?t.type="array":r&&(t.type="null"));let s=Uu(t.type),a={};if(t.anyOf?a.anyOf=t.anyOf.map(l=>e(l)):a.type=s,t.description&&(a.description=t.description),r&&t.type!=="null"&&(a.nullable=!0),s===ne.Type.OBJECT){if(a.properties={},t.properties)for(let l in t.properties)a.properties[l]=e(t.properties[l]);t.required&&(a.required=t.required)}else s===ne.Type.ARRAY&&t.items&&(a.items=e(t.items));return a}return e(n)}var ln=class extends w{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:Wr(this.mcpTool.inputSchema),response:Wr(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,void 0,{signal:e.toolContext.abortSignal})}};var Hr=class extends xe{constructor(e,t=[],o){super(t,o),this.mcpSessionManager=new cn(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 ln(r,this.mcpSessionManager)})}async close(){}};0&&(module.exports={A2AAgentExecutor,AGENT_CARD_PATH,ActiveStreamingTool,Agent,AgentTool,AgentTransferLlmRequestProcessor,ApigeeLlm,AuthCredentialTypes,AuthHandler,AuthProviderRegistry,BaseAgent,BaseCodeExecutor,BaseExampleProvider,BaseLlm,BaseLlmRequestProcessor,BaseLlmResponseProcessor,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,CONTENT_REQUEST_PROCESSOR,CodeExecutionLanguage,ContentRequestProcessor,Context,ContextCompactionTrigger,ContextCompactorRequestProcessor,CredentialExchangeError,CredentialRefresherRegistry,DatabaseSessionService,EXIT_LOOP,EventType,ExitLoopTool,FeatureName,FeatureStage,FileArtifactService,FileContentEncoding,FunctionTool,GOOGLE_SEARCH,GcsArtifactService,Gemini,GoogleLLMVariant,GoogleSearchTool,InMemoryArtifactService,InMemoryCredentialService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LLMRegistry,LOAD_ARTIFACTS,LOAD_MEMORY,ListSkillsTool,LiveRequestQueue,LlmAgent,LlmSummarizer,LoadArtifactsTool,LoadMemoryTool,LoadSkillResourceTool,LoadSkillTool,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,OAuth2CredentialExchanger,OAuth2DiscoveryManager,OAuthGrantType,PRELOAD_MEMORY,ParallelAgent,PluginManager,PolicyOutcome,PreloadMemoryTool,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,ReadonlyContext,RemoteA2AAgent,RoutedAgent,RoutedLlm,RunSkillInlineScriptTool,RunSkillScriptTool,Runner,SecurityPlugin,SequentialAgent,SessionStateCredentialService,SkillToolset,State,StreamingMode,TokenBasedContextCompactor,ToolConfirmation,TruncatingContextCompactor,UnsafeLocalCodeExecutor,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,geminiInitParams,getA2AAgentCard,getArtifactServiceFromUri,getAskUserConfirmationFunctionCalls,getFeatureConfig,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,getLogger,getSessionServiceFromUri,hasTrailingCodeExecutionResult,isAgentTool,isBaseAgent,isBaseExampleProvider,isBaseLlm,isBaseTool,isBaseToolset,isCompactedEvent,isFeatureEnabled,isFinalResponse,isFunctionTool,isGemini2OrAbove,isLlmAgent,isLoopAgent,isParallelAgent,isRoutedAgent,isRunner,isSequentialAgent,loadAllSkillsInDir,loadSkillFromDir,maybeSetOtelProviders,mergeStates,overrideFeatureEnabled,registerFeature,setLogLevel,setLogger,stringifyContent,toA2a,toStructuredEvents,trimTempDeltaState,validateSkillDir,version,withTemporaryFeatureOverride,zodObjectToSchema});
|
|
126
|
-
/**
|
|
127
|
-
* @license
|
|
128
|
-
* Copyright 2026 Google LLC
|
|
129
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
130
|
-
*/
|
|
7
|
+
"use strict";
|
|
8
|
+
var __defProp = Object.defineProperty;
|
|
9
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
10
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
11
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
var __copyProps = (to, from, except, desc) => {
|
|
17
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
18
|
+
for (let key of __getOwnPropNames(from))
|
|
19
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
20
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
21
|
+
}
|
|
22
|
+
return to;
|
|
23
|
+
};
|
|
24
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
25
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
26
|
+
var index_exports = {};
|
|
27
|
+
__export(index_exports, {
|
|
28
|
+
A2AAgentExecutor: () => import_agent_executor.A2AAgentExecutor,
|
|
29
|
+
AGENT_CARD_PATH: () => import_a2a_remote_agent.AGENT_CARD_PATH,
|
|
30
|
+
AgentEngineSandboxCodeExecutor: () => import_agent_engine_sandbox_code_executor.AgentEngineSandboxCodeExecutor,
|
|
31
|
+
CodeExecutionLanguage: () => import_code_execution_utils.CodeExecutionLanguage,
|
|
32
|
+
DatabaseSessionService: () => import_database_session_service.DatabaseSessionService,
|
|
33
|
+
FileArtifactService: () => import_file_artifact_service.FileArtifactService,
|
|
34
|
+
GcsArtifactService: () => import_gcs_artifact_service.GcsArtifactService,
|
|
35
|
+
InvocationContext: () => import_invocation_context.InvocationContext,
|
|
36
|
+
RemoteA2AAgent: () => import_a2a_remote_agent.RemoteA2AAgent,
|
|
37
|
+
RunSkillInlineScriptTool: () => import_run_skill_inline_script_tool.RunSkillInlineScriptTool,
|
|
38
|
+
RunSkillScriptTool: () => import_run_skill_script_tool.RunSkillScriptTool,
|
|
39
|
+
UnsafeLocalCodeExecutor: () => import_unsafe_local_code_executor.UnsafeLocalCodeExecutor,
|
|
40
|
+
VertexAiSessionService: () => import_vertex_ai_session_service.VertexAiSessionService,
|
|
41
|
+
getA2AAgentCard: () => import_agent_card.getA2AAgentCard,
|
|
42
|
+
getArtifactServiceFromUri: () => import_registry.getArtifactServiceFromUri,
|
|
43
|
+
getSessionServiceFromUri: () => import_registry2.getSessionServiceFromUri,
|
|
44
|
+
loadAllSkillsInDir: () => import_loader.loadAllSkillsInDir,
|
|
45
|
+
loadSkillFromDir: () => import_loader.loadSkillFromDir,
|
|
46
|
+
toA2a: () => import_agent_to_a2a.toA2a,
|
|
47
|
+
validateSkillDir: () => import_loader.validateSkillDir
|
|
48
|
+
});
|
|
49
|
+
module.exports = __toCommonJS(index_exports);
|
|
50
|
+
var import_a2a_remote_agent = require("./a2a/a2a_remote_agent.js");
|
|
51
|
+
var import_agent_card = require("./a2a/agent_card.js");
|
|
52
|
+
var import_agent_executor = require("./a2a/agent_executor.js");
|
|
53
|
+
var import_agent_to_a2a = require("./a2a/agent_to_a2a.js");
|
|
54
|
+
var import_invocation_context = require("./agents/invocation_context.js");
|
|
55
|
+
var import_file_artifact_service = require("./artifacts/file_artifact_service.js");
|
|
56
|
+
var import_gcs_artifact_service = require("./artifacts/gcs_artifact_service.js");
|
|
57
|
+
var import_registry = require("./artifacts/registry.js");
|
|
58
|
+
var import_agent_engine_sandbox_code_executor = require("./code_executors/agent_engine_sandbox_code_executor.js");
|
|
59
|
+
var import_code_execution_utils = require("./code_executors/code_execution_utils.js");
|
|
60
|
+
var import_unsafe_local_code_executor = require("./code_executors/unsafe_local_code_executor.js");
|
|
61
|
+
__reExport(index_exports, require("./common.js"), module.exports);
|
|
62
|
+
var import_database_session_service = require("./sessions/database_session_service.js");
|
|
63
|
+
var import_registry2 = require("./sessions/registry.js");
|
|
64
|
+
var import_vertex_ai_session_service = require("./sessions/vertex_ai_session_service.js");
|
|
65
|
+
var import_loader = require("./skills/loader.js");
|
|
66
|
+
var import_run_skill_inline_script_tool = require("./tools/skill/run_skill_inline_script_tool.js");
|
|
67
|
+
var import_run_skill_script_tool = require("./tools/skill/run_skill_script_tool.js");
|
|
68
|
+
__reExport(index_exports, require("./integrations/agent_registry/agent_registry.js"), module.exports);
|
|
69
|
+
__reExport(index_exports, require("./telemetry/google_cloud.js"), module.exports);
|
|
70
|
+
__reExport(index_exports, require("./telemetry/setup.js"), module.exports);
|
|
71
|
+
__reExport(index_exports, require("./tools/mcp/mcp_session_manager.js"), module.exports);
|
|
72
|
+
__reExport(index_exports, require("./tools/mcp/mcp_tool.js"), module.exports);
|
|
73
|
+
__reExport(index_exports, require("./tools/mcp/mcp_toolset.js"), module.exports);
|
|
131
74
|
/**
|
|
132
75
|
* @license
|
|
133
76
|
* Copyright 2025 Google LLC
|
|
134
77
|
* SPDX-License-Identifier: Apache-2.0
|
|
135
78
|
*/
|
|
136
|
-
|
|
79
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
80
|
+
0 && (module.exports = {
|
|
81
|
+
A2AAgentExecutor,
|
|
82
|
+
AGENT_CARD_PATH,
|
|
83
|
+
AgentEngineSandboxCodeExecutor,
|
|
84
|
+
CodeExecutionLanguage,
|
|
85
|
+
DatabaseSessionService,
|
|
86
|
+
FileArtifactService,
|
|
87
|
+
GcsArtifactService,
|
|
88
|
+
InvocationContext,
|
|
89
|
+
RemoteA2AAgent,
|
|
90
|
+
RunSkillInlineScriptTool,
|
|
91
|
+
RunSkillScriptTool,
|
|
92
|
+
UnsafeLocalCodeExecutor,
|
|
93
|
+
VertexAiSessionService,
|
|
94
|
+
getA2AAgentCard,
|
|
95
|
+
getArtifactServiceFromUri,
|
|
96
|
+
getSessionServiceFromUri,
|
|
97
|
+
loadAllSkillsInDir,
|
|
98
|
+
loadSkillFromDir,
|
|
99
|
+
toA2a,
|
|
100
|
+
validateSkillDir,
|
|
101
|
+
...require("./common.js"),
|
|
102
|
+
...require("./integrations/agent_registry/agent_registry.js"),
|
|
103
|
+
...require("./telemetry/google_cloud.js"),
|
|
104
|
+
...require("./telemetry/setup.js"),
|
|
105
|
+
...require("./tools/mcp/mcp_session_manager.js"),
|
|
106
|
+
...require("./tools/mcp/mcp_tool.js"),
|
|
107
|
+
...require("./tools/mcp/mcp_toolset.js")
|
|
108
|
+
});
|