@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/web/index.js
CHANGED
|
@@ -1,19 +1,61 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2026 Google LLC
|
|
4
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
-
*/
|
|
6
1
|
import {createRequire as topLevelCreateRequire} from 'module';
|
|
7
2
|
const require = topLevelCreateRequire(import.meta.url);
|
|
8
|
-
var ao=Object.defineProperty,ii=Object.defineProperties,si=Object.getOwnPropertyDescriptor,ai=Object.getOwnPropertyDescriptors;var ot=Object.getOwnPropertySymbols;var co=Object.prototype.hasOwnProperty,lo=Object.prototype.propertyIsEnumerable;var be=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),ci=n=>{throw TypeError(n)};var so=(n,e,t)=>e in n?ao(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,x=(n,e)=>{for(var t in e||(e={}))co.call(e,t)&&so(n,t,e[t]);if(ot)for(var t of ot(e))lo.call(e,t)&&so(n,t,e[t]);return n},w=(n,e)=>ii(n,ai(e));var uo=(n,e)=>{var t={};for(var o in n)co.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&ot)for(var o of ot(n))e.indexOf(o)<0&&lo.call(n,o)&&(t[o]=n[o]);return t};var _=(n,e,t,o)=>{for(var r=o>1?void 0:o?si(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&&ao(e,t,r),r};var d=function(n,e){this[0]=n,this[1]=e},h=(n,e,t)=>{var o=(s,a,c,l)=>{try{var u=t[s](a),f=(a=u.value)instanceof d,p=u.done;Promise.resolve(f?a[0]:a).then(m=>f?o(s==="return"?s:"next",a[1]?{done:m.done,value:m.value}:m,c,l):c({value:m,done:p})).catch(m=>o("throw",m,c,l))}catch(m){l(m)}},r=s=>i[s]=a=>new Promise((c,l)=>o(s,a,c,l)),i={};return t=t.apply(n,e),i[be("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i},M=n=>{var e=n[be("asyncIterator")],t=!1,o,r={};return e==null?(e=n[be("iterator")](),o=i=>r[i]=s=>e[i](s)):(e=e.call(n),o=i=>r[i]=s=>{if(t){if(t=!1,i==="throw")throw s;return s}return t=!0,{done:!1,value:new d(new Promise(a=>{var c=e[i](s);c instanceof Object||ci("Object expected"),a(c)}),1)}}),r[be("iterator")]=()=>r,o("next"),"throw"in e?o("throw"):r.throw=i=>{throw i},"return"in e&&o("return"),r},A=(n,e,t)=>(e=n[be("asyncIterator")])?e.call(n):(n=n[be("iterator")](),e={},t=(o,r)=>(r=n[o])&&(e[o]=i=>new Promise((s,a,c)=>(i=r.call(n,i),c=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:c}),a)))),t("next"),t("return"),e);var Pt=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};import{context as wo,trace as _o}from"@opentelemetry/api";function H(n={}){return x({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},n)}function fo(n,e){let t=H();e&&Object.assign(t,e);for(let o of n)o&&(o.stateDelta&&Object.assign(t.stateDelta,o.stateDelta),o.artifactDelta&&Object.assign(t.artifactDelta,o.artifactDelta),o.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,o.requestedAuthConfigs),o.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,o.requestedToolConfirmations),o.skipSummarization!==void 0&&(t.skipSummarization=o.skipSummarization),o.transferToAgent!==void 0&&(t.transferToAgent=o.transferToAgent),o.escalate!==void 0&&(t.escalate=o.escalate));return t}function T(n={}){return w(x({},n),{id:n.id||Ot(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||H(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()})}function oe(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:L(n).length===0&&z(n).length===0&&!n.partial&&!mo(n)}function L(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 z(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 mo(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 $e(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 po="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Ot(){let n="";for(let e=0;e<8;e++)n+=po[Math.floor(Math.random()*po.length)];return n}import{context as Bt,trace as ze}from"@opentelemetry/api";var qe="1.0.0";var li="gen_ai.agent.description",ui="gen_ai.agent.name",fi="gen_ai.conversation.id",Mt="gen_ai.operation.name",go="gen_ai.tool.call.id",ho="gen_ai.tool.description",Co="gen_ai.tool.name",di="gen_ai.tool.type",J=ze.getTracer("gcp.vertex.agent",qe);function Ue(n){try{return JSON.stringify(n)}catch(e){return"<not serializable>"}}function vo({agent:n,invocationContext:e}){let t=ze.getActiveSpan();t&&t.setAttributes({[Mt]:"invoke_agent",[li]:n.description,[ui]:n.name,[fi]:e.session.id})}function yo({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=ze.getActiveSpan();if(!o)return;o.setAttributes({[Mt]:"execute_tool",[ho]:n.description||"",[Co]:n.name,[di]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":Ge()?Ue(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({[go]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":Ge()?Ue(i):"{}"})}function xo({responseEventId:n,functionResponseEvent:e}){let t=ze.getActiveSpan();t&&(t.setAttributes({[Mt]:"execute_tool",[Co]:"(merged tools)",[ho]:"(merged tools)",[go]: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",Ge()?Ue(e):"{}"))}function Eo({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=ze.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":Ge()?Ue(pi(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",Ge()?Ue(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 pi(n){let e={model:n.model,contents:[]};if(n.config){let t=n.config,{responseSchema:o}=t,r=uo(t,["responseSchema"]);e.config=r}return e.contents=n.contents.map(o=>{var r;return{role:o.role,parts:((r=o.parts)==null?void 0:r.filter(i=>!i.inlineData))||[]}}),e}function Ao(n,e){return{next:Bt.bind(n,e.next.bind(e)),return:Bt.bind(n,e.return.bind(e)),throw:Bt.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return Ao(n,e[Symbol.asyncIterator]())}}}function ue(n,e,t){let o=t.call(e);return Ao(n,o)}function Ge(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}function K(){return typeof window<"u"}var rt="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function re(){let n="";for(let e=0;e<rt.length;e++){let t=Math.random()*16|0;rt[e]==="x"?n+=t.toString(16):rt[e]==="y"?n+=(t&3|8).toString(16):n+=rt[e]}return n}function To(n){return K()?window.atob(n):Buffer.from(n,"base64").toString()}function fe(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}import*as W from"winston";var So=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(So||{}),Nt=class{constructor(){this.logLevel=1;this.logger=W.createLogger({levels:{debug:0,info:1,warn:2,error:3},level:"error",format:W.format.combine(W.format.label({label:"ADK"}),W.format(e=>(e.level=e.level.toUpperCase(),e))(),W.format.colorize(),W.format.timestamp(),W.format.printf(e=>"".concat(e.level,": [").concat(e.label,"] ").concat(e.timestamp," ").concat(e.message))),transports:[new W.transports.Console]})}setLogLevel(e){this.logLevel=e}log(e,...t){this.logLevel>e||this.logger.log(e.toString(),t.join(" "))}debug(...e){this.logLevel>0||this.logger.debug(e.join(" "))}info(...e){this.logLevel>1||this.logger.info(e.join(" "))}warn(...e){this.logLevel>2||this.logger.warn(e.join(" "))}error(...e){this.logLevel>3||this.logger.error(e.join(" "))}},Ft=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},ie=new Nt;function mi(n){ie=n!=null?n:new Ft}function Dt(){return ie}function gi(n){g.setLogLevel(n)}var g={setLogLevel(n){ie.setLogLevel(n)},log(n,...e){ie.log(n,...e)},debug(...n){ie.debug(...n)},info(...n){ie.info(...n)},warn(...n){ie.warn(...n)},error(...n){ie.error(...n)}};var $t=(r=>(r.CLIENT_CREDENTIALS="client_credentials",r.AUTHORIZATION_CODE="authorization_code",r.IMPLICIT="implicit",r.PASSWORD="password",r))($t||{});function Ro(n){if(n.clientCredentials)return"client_credentials";if(n.authorizationCode)return"authorization_code";if(n.implicit)return"implicit";if(n.password)return"password"}var q=class extends Error{};function qt(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 Ut(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 ".concat(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 g.error("Failed to fetch OAuth2 tokens: ".concat(t)),t}}function bo(n){try{return new URL(n).searchParams.get("code")||void 0}catch(e){g.warn("Failed to parse authorization URI ".concat(n,": ").concat(e));return}}function Gt(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 je=class{async exchange({authCredential:e,authScheme:t}){var r;if(!t)throw new q("authScheme is required for OAuth2 credential exchange");if((r=e.oauth2)!=null&&r.accessToken)return{credential:e,wasExchanged:!1};let o=hi(t);return o==="client_credentials"?Ci({authCredential:e,authScheme:t}):o==="authorization_code"?vi({authCredential:e,authScheme:t}):(g.warn("Unsupported OAuth2 grant type: ".concat(o)),{credential:e,wasExchanged:!1})}};function hi(n){var e;if("flows"in n&&n.flows)return Ro(n.flows);if(n.grantTypesSupported)return(e=n.grantTypesSupported)!=null&&e.includes("client_credentials")?"client_credentials":"authorization_code"}async function Ci({authCredential:n,authScheme:e}){var r,i;let t=qt(e);if(!t)throw new q("Token endpoint not found in auth scheme.");if(!((r=n.oauth2)!=null&&r.clientId)||!((i=n.oauth2)!=null&&i.clientSecret))throw new q("clientId and clientSecret are required for client credentials exchange.");let o=Gt({grantType:"client_credentials",clientId:n.oauth2.clientId,clientSecret:n.oauth2.clientSecret});try{let s=await Ut(t,o);return{credential:w(x({},n),{oauth2:x(x({},n.oauth2),s)}),wasExchanged:!0}}catch(s){throw new q("Failed to exchange tokens: ".concat(s instanceof Error?s.message:String(s)))}}async function vi({authCredential:n,authScheme:e}){var i,s,a,c;let t=qt(e);if(!t)throw new q("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 q("clientId, clientSecret, and either authCode or authResponseUri are required for authorization code exchange.");let o=n.oauth2.authCode;if(!o&&n.oauth2.authResponseUri&&(o=bo(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 q("State mismatch detected. Potential CSRF attack.")}catch(l){throw new q("Failed to parse authResponseUri for state validation: ".concat(l instanceof Error?l.message:String(l)))}if(!o)throw new q("Authorization code not found in auth response.");let r=Gt({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 Ut(t,r);return{credential:w(x({},n),{oauth2:x(x({},n.oauth2),l)}),wasExchanged:!0}}catch(l){throw new q("Failed to exchange tokens: ".concat(l instanceof Error?l.message:String(l)))}}var Ie=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 je().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 ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(e," requires oauth2 in authCredential."));if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error("Auth Scheme ".concat(e," requires both clientId and clientSecret in authCredential.oauth2."));return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){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=re(),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"),w(x({},t),{oauth2:w(x({},t.oauth2),{authUri:s.toString(),state:i})})}};var b=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 x(x({},this.value),this.delta)}};b.APP_PREFIX="app:",b.USER_PREFIX="user:",b.TEMP_PREFIX="temp:";var de=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var P=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 b(this.invocationContext.session.state,{})}};var O=class extends P{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||H(),this._state=new b(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 Ie(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ie(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 de({hint:e,confirmed:!1,payload:t})}};var zt=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},Z=class{constructor(e){this.invocationCostManager=new zt;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager,this.abortSignal=e.abortSignal}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function Io(){return"e-".concat(re())}var jt=Symbol.for("google.adk.baseAgent");function yi(n){return typeof n=="object"&&n!==null&&jt in n&&n[jt]===!0}var Lo;Lo=jt;var G=class{constructor(e){this[Lo]=!0;this.name=xi(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=ko(e.beforeAgentCallback),this.afterAgentCallback=ko(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return Ai(this)}runAsync(e){return h(this,null,function*(){let t=J.startSpan("invoke_agent ".concat(this.name)),o=_o.setSpan(wo.active(),t);try{yield*M(ue(o,this,function(){return h(this,null,function*(){var a,p;let r=this.createInvocationContext(e),i=yield new d(this.handleBeforeAgentCallback(r));if(i&&(yield i),r.endInvocation||(a=e.abortSignal)!=null&&a.aborted)return;vo({agent:this,invocationContext:r});try{for(var c=A(this.runAsyncImpl(r)),l,u,f;l=!(u=yield new d(c.next())).done;l=!1){let m=u.value;yield m}}catch(u){f=[u]}finally{try{l&&(u=c.return)&&(yield new d(u.call(c)))}finally{if(f)throw f[0]}}if(r.endInvocation||(p=e.abortSignal)!=null&&p.aborted)return;let s=yield new d(this.handleAfterAgentCallback(r));s&&(yield s)})}))}finally{t.end()}})}runLive(e){return h(this,null,function*(){let t=J.startSpan("invoke_agent ".concat(this.name)),o=_o.setSpan(wo.active(),t);try{throw yield*M(ue(o,this,function(){return h(this,null,function*(){})})),new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let o=t.findAgent(e);if(o)return o}}createInvocationContext(e){return new Z(w(x({},e),{agent:this}))}async handleBeforeAgentCallback(e){var o;if(this.beforeAgentCallback.length===0)return;let t=new O({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,T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:i,actions:t.eventActions})}if(t.state.hasDelta())return T({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 O({invocationContext:e});for(let r of this.afterAgentCallback){let i=await r(t);if((o=e.abortSignal)!=null&&o.aborted)return;if(i)return T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:i,actions:t.eventActions})}if(t.state.hasDelta())return T({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error('Agent "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function xi(n){if(!Ei(n))throw new Error('Found invalid agent name: "'.concat(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 Ei(n){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_-]*$","u").test(n)}function Ai(n){for(;n.parentAgent;)n=n.parentAgent;return n}function ko(n){return n?Array.isArray(n)?n:[n]:[]}import{createUserContent as Ti}from"@google/genai";import{isEmpty as Po}from"lodash-es";var Vt="adk-",it="adk_request_credential",we="adk_request_confirmation",Si={handleFunctionCallList:st,generateAuthEvent:Kt,generateRequestConfirmationEvent:Wt};function pe(){return"".concat(Vt).concat(re())}function Oo(n){let e=L(n);if(e)for(let t of e)t.id||(t.id=pe())}function Bo(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Vt)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Vt)&&(e.functionResponse.id=void 0)}function Mo(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 Kt(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||Po(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:it,args:{function_call_id:i,auth_config:s},id:pe()};o.add(a.id),t.push({functionCall:a})}return T({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function Wt({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||Po(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=L(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(p=>p.id===c))!=null?a:void 0;if(!u)continue;let f={name:we,args:{originalFunctionCall:u,toolConfirmation:l},id:pe()};r.add(f.id),o.push({functionCall:f})}return T({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:o,role:t.content.role},actions:t.actions,longRunningToolIds:Array.from(r)})}async function Ri(n,e,t){return J.startActiveSpan("execute_tool ".concat(n.name),async o=>{try{g.debug("callToolAsync ".concat(n.name));let r=await n.runAsync({args:e,toolContext:t});return yo({tool:n,args:e,functionResponseEvent:bi(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function bi(n,e,t,o){let r;typeof e!="object"||e==null?r={result:e}:r=e;let s={role:"user",parts:[{functionResponse:{name:n.name,response:r,id:t.functionCallId}}]};return T({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function No({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=L(e);return await st({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function st({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let p;s&&f.id&&(p=s[f.id]);let{tool:m,toolContext:C}=Ii({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:p});g.debug("execute_tool ".concat(m.name));let v=(u=f.args)!=null?u:{},y=null,I;if(y=await n.pluginManager.runBeforeToolCallback({tool:m,toolArgs:v,toolContext:C}),y==null){for(let R of o)if(y=await R({tool:m,args:v,context:C}),y)break}if(y==null)try{y=await Ri(m,v,C)}catch(R){if(R instanceof Error){let $=await n.pluginManager.runOnToolErrorCallback({tool:m,toolArgs:v,toolContext:C,error:R});$?y=$:I=R.message}else I=R}let U=await n.pluginManager.runAfterToolCallback({tool:m,toolArgs:v,toolContext:C,result:y});if(U==null){for(let R of r)if(U=await R({tool:m,args:v,context:C,response:y}),U)break}if(U!=null&&(y=U),m.isLongRunning&&!y)continue;I?y={error:I}:(typeof y!="object"||y==null)&&(y={result:y});let F=T({invocationId:n.invocationId,author:n.agent.name,content:Ti({functionResponse:{id:C.functionCallId,name:m.name,response:y}}),actions:C.actions,branch:n.branch});g.debug("traceToolCall",{tool:m.name,args:v,functionResponseEvent:F.id}),a.push(F)}if(!a.length)return null;let l=wi(a);return a.length>1&&J.startActiveSpan("execute_tool (merged)",f=>{try{g.debug("execute_tool (merged)"),g.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),xo({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function Ii({invocationContext:n,functionCall:e,toolsDict:t,toolConfirmation:o}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new O({invocationContext:n,functionCallId:e.id||void 0,toolConfirmation:o});return{tool:t[e.name],toolContext:r}}function wi(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=fo(o);return T({invocationId:t.invocationId,author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Yt=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:{}})}[Symbol.asyncIterator](){return h(this,null,function*(){for(;;){let e=yield new d(this.get());if(yield e,e.close)break}})}};import{context as ms,trace as gs}from"@opentelemetry/api";var _i="google-adk",ki="gl-typescript",Li="remote_reasoning_engine",Pi="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Oi(){let n="".concat(_i,"/").concat(qe);!K()&&process.env[Pi]&&(n="".concat(n,"+").concat(Li));let e="".concat(ki,"/").concat(K()?window.navigator.userAgent:process.version);return[n,e]}function Fo(){return Oi()}var Ht=Symbol.for("google.adk.baseModel");function Jt(n){return typeof n=="object"&&n!==null&&Ht in n&&n[Ht]===!0}var Do;Do=Ht;var se=class{constructor({model:e}){this[Do]=!0;this.model=e}get trackingHeaders(){let t=Fo().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."}]})}};se.supportedModels=[];import{createPartFromText as Mi,GoogleGenAI as Qt}from"@google/genai";var at=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(at||{});function $o(){return fe("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}import{FinishReason as lt}from"@google/genai";import{JSONPath as jo}from"jsonpath-plus";var Uo=(e=>(e.PROGRESSIVE_SSE_STREAMING="PROGRESSIVE_SSE_STREAMING",e))(Uo||{}),Bi=(o=>(o.WIP="wip",o.EXPERIMENTAL="experimental",o.STABLE="stable",o))(Bi||{}),Go={PROGRESSIVE_SSE_STREAMING:{stage:"experimental",defaultOn:!1}},qo=new Set,Q={};function Zt(n){return Go[n]}function qc(n,e){Go[n]=e}function Uc(n,e){if(!Zt(n))throw new Error("Feature ".concat(n," is not registered."));e===void 0?delete Q[n]:Q[n]=e}function zo(n){let e=Zt(n);if(!e)throw new Error("Feature ".concat(n," is not registered."));if(n in Q){let r=Q[n];return r&&e.stage!=="stable"&&Xt(n,e.stage),r}let t="ADK_ENABLE_".concat(n),o="ADK_DISABLE_".concat(n);return fe(t)?(e.stage!=="stable"&&Xt(n,e.stage),!0):fe(o)?!1:(e.stage!=="stable"&&e.defaultOn&&Xt(n,e.stage),e.defaultOn)}function Xt(n,e){qo.has(n)||(qo.add(n),g.warn("[".concat(e.toUpperCase(),"] feature ").concat(n," is enabled.")))}async function Gc(n,e,t){if(!Zt(n))throw new Error("Feature ".concat(n," is not registered."));let r=n in Q,i=Q[n];Q[n]=e;try{return await t()}finally{r?Q[n]=i:delete Q[n]}}function ct(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 ut=class{constructor(e=zo("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=jo.toPathArray(t).filter(p=>p!=="$"&&p!=="$["),f=this.currentFcArgs;for(let p of u)if(f&&typeof f=="object"&&p in f)f=f[p];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=jo.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:pe()}};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=pe()),e.thoughtSignature&&!this.currentThoughtSignature&&(this.currentThoughtSignature=e.thoughtSignature),this.processStreamingFunctionCall(t)):t.name&&(t.id||(t.id=pe()),this.flushTextBufferToSequence(),this.partsSequence.push(e)))}processResponse(e){return h(this,null,function*(){var o,r,i;this.response=e;let t=ct(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===lt.STOP?void 0:i,errorMessage:i===lt.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===lt.STOP?void 0:i,errorMessage:i===lt.STOP?void 0:r.finishMessage,usageMetadata:this.usageMetadata,finishReason:i,partial:!1}}}}};var ft=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(o=>{var r;return o.parts&&((r=o.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):g.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(o=>o.functionResponse).filter(o=>!!o);g.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else g.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){g.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return h(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};var ae=class extends se{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=dt({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}generateContentAsync(e,t=!1,o){return h(this,null,function*(){var r,i,C;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),g.info("Sending out request, model: ".concat((r=e.model)!=null?r:this.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),e.config||(e.config={}),e.config.httpOptions&&(e.config.httpOptions.headers=x(x({},e.config.httpOptions.headers),this.trackingHeaders)),o&&(e.config.abortSignal=o),t){let v=yield new d(this.apiClient.models.generateContentStream({model:(i=e.model)!=null?i:this.model,contents:e.contents,config:e.config})),y=new ut;try{for(var u=A(v),f,p,m;f=!(p=yield new d(u.next())).done;f=!1){let U=p.value;try{for(var s=A(y.processResponse(U)),a,c,l;a=!(c=yield new d(s.next())).done;a=!1){let F=c.value;yield F}}catch(c){l=[c]}finally{try{a&&(c=s.return)&&(yield new d(c.call(s)))}finally{if(l)throw l[0]}}}}catch(p){m=[p]}finally{try{f&&(p=u.return)&&(yield new d(p.call(u)))}finally{if(m)throw m[0]}}let I=y.close();I&&(yield I)}else{let v=yield new d(this.apiClient.models.generateContent({model:(C=e.model)!=null?C:this.model,contents:e.contents,config:e.config}));yield ct(v)}})}getHttpOptions(){return{headers:x(x({},this.trackingHeaders),this.headers)}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new Qt({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new Qt({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 Qt({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:[Mi(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 ft(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)Vo(o.inlineData),Vo(o.fileData)}}};ae.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Vo(n){n&&n.displayName&&(n.displayName=void 0)}function dt({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&&!K()&&(i.vertexai=fe("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!K()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!K()&&!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&&!K()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var Ko="APIGEE_PROXY_URL",_e=class extends ae{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!Yo(e))throw new Error("Model ".concat(e," is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>"));if(super(w(x({},Ni({model:e,vertexai:r,project:s,location:i,apiKey:o})),{headers:a})),this.proxyUrl=t!=null?t:"",!K()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[Ko])!=null?c:""),!this.proxyUrl)throw new Error("Proxy URL must be provided via the constructor or ".concat(Ko," 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}generateContentAsync(e,t=!1,o){return h(this,null,function*(){var i;let r=(i=e.model)!=null?i:this.model;e.model=Wo(r),yield*M(super.generateContentAsync(e,t,o))})}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=Wo(t),super.connect(e)}};_e.supportedModels=[/apigee\/.*/];function Ni({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=dt({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||(g.warn('No API key provided when using a Gemini model, using a fake key "-".'),i.apiKey="-"),i}function Wo(n){if(!Yo(n))throw new Error("Model ".concat(n," is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>"));let e=n.split("/");return e[e.length-1]}function Yo(n){let e=["vertex_ai","gemini"];if(!n.startsWith("apigee/"))return!1;let t=n.substring(7);if(t.length===0)return!1;let o=t.split("/",-1);return o[o.length-1].length===0?!1:o.length==1?!0:o.length==2?e.includes(o[0])?!0:o[0].startsWith("v"):o.length==3&&e.includes(o[0])?o[1].startsWith("v"):!1}var en=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},j=class j{static newLlm(e){return new(j.resolve(e))({model:e})}static _register(e,t){j.llmRegistryDict.has(e)&&g.info("Updating LLM class for ".concat(e," from ").concat(j.llmRegistryDict.get(e)," to ").concat(t)),j.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)j._register(t,e)}static resolve(e){let t=j.resolveCache.get(e);if(t)return t;for(let[o,r]of j.llmRegistryDict.entries())if(new RegExp("^".concat(o instanceof RegExp?o.source:o,"$"),o instanceof RegExp?o.flags:void 0).test(e))return j.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};j.llmRegistryDict=new Map,j.resolveCache=new en(32);var me=j;me.register(ae);me.register(_e);var tn=Symbol.for("google.adk.baseTool");function nn(n){return typeof n=="object"&&n!==null&&tn in n&&n[tn]===!0}var Ho;Ho=tn;var S=class{constructor(e){this[Ho]=!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: ".concat(this.name));e.toolsDict[this.name]=this;let o=Fi(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 $o()}};function Fi(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Jo}from"@google/genai";import{zodToJsonSchema as Di}from"zod-to-json-schema";import{toJSONSchema as $i}from"zod/v4";function on(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function qi(n){return on(n)&&!("_zod"in n)}function Ui(n){return on(n)&&"_zod"in n}function Gi(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 ge(n){return on(n)&&Gi(n)==="ZodObject"}function ke(n){if(!ge(n))throw new Error("Expected a Zod Object");if(Ui(n))return $i(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=Jo.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(qi(n))return Di(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=Jo.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.")}import{z as er}from"zod";function D(n,e){n.config||(n.config={});let t=e.join("\n\n");n.config.systemInstruction?n.config.systemInstruction+="\n\n"+t:n.config.systemInstruction=t}function Xo(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}import{Type as zi}from"@google/genai";function ji(n){return n===void 0?{type:zi.OBJECT,properties:{}}:ge(n)?ke(n):n}var rn=Symbol.for("google.adk.functionTool");function Vi(n){return typeof n=="object"&&n!==null&&rn in n&&n[rn]===!0}var Zo,Qo,ee=class extends(Qo=S,Zo=rn,Qo){constructor(t){var r;let o=(r=t.name)!=null?r:t.execute.name;if(!o)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:o,description:t.description,isLongRunning:t.isLongRunning});this[Zo]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:ji(this.parameters)}}async runAsync(t){try{let o=t.args;return ge(this.parameters)&&(o=this.parameters.parse(t.args)),await this.execute(o,t.toolContext)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error("Error in tool '".concat(this.name,"': ").concat(r))}}};var B=class{},sn=class{};var pt=class extends B{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new ee({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:er.object({agentName:er.string().describe("the agent name to transfer to.")}),execute:function(t,o){if(!o)throw new Error("toolContext is required.");return o.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,o){return h(this,null,function*(){if(!E(t.agent))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;D(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new O({invocationContext:t});yield new d(this.tool.processLlmRequest({toolContext:i,llmRequest:o}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,o){let r="\nYou have a list of other agents to transfer to:\n\n".concat(o.map(i=>this.buildTargetAgentsInfo(i)).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!E(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},tr=new pt;var an=class extends B{runAsync(e,t){return h(this,null,function*(){var r;let o=e.agent;E(o)&&(t.model=o.canonicalModel.model,t.config=x({},(r=o.generateContentConfig)!=null?r:{}),o.outputSchema&&Xo(t,o.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},nr=new an;import{cloneDeep as dr}from"lodash-es";var cn=Symbol.for("google.adk.baseCodeExecutor");function mt(n){return typeof n=="object"&&n!==null&&cn in n&&n[cn]===!0}var or;or=cn;var Ve=class{constructor(){this[or]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"],["```javascript\n","\n```"],["```typescript\n","\n```"],["```bash\n","\n```"],["```sh\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Ki="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function ln(n){let e=n.match(Ki);return e?e[1]:n}function rr(n){return ln(n).startsWith("gemini-")}function Wi(n){if(!/^\d+(\.\d+)*$/.test(n))return{valid:!1,major:0,minor:0,patch:0};let e=n.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function ir(n){return ln(n).startsWith("gemini-1")}function Ke(n){if(!n)return!1;let e=ln(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Wi(t);return o.valid&&o.major>=2}var un=Symbol.for("google.adk.builtInCodeExecutor");function Ye(n){return typeof n=="object"&&n!==null&&un in n&&n[un]===!0}var sr,ar,We=class extends(ar=Ve,sr=un,ar){constructor(){super(...arguments);this[sr]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&Ke(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error("Gemini code execution tool is not supported for model ".concat(t.model))}};import{Language as Yi,Outcome as cr}from"@google/genai";import{cloneDeep as Hi}from"lodash-es";var fn=(t=>(t.UTF8="utf-8",t.BASE64="base64",t))(fn||{}),he=(a=>(a.UNSPECIFIED="unspecified",a.PYTHON="python",a.JAVASCRIPT="javascript",a.TYPESCRIPT="typescript",a.SHELL="shell",a.POWERSHELL="powershell",a.WINDOWS_CMD="cmd",a))(he||{});function lr(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let p=n.parts[f];if(p.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),p.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=Hi(t[0]),r=t.map(f=>f.text).join("\n"),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),a=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(s,")(?<suffix>.*?)$"),"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(n.parts=[],c&&(o.text=c,n.parts.push(o)),n.parts.push(dn(l)),l):""}function dn(n){return{text:n,executableCode:{code:n,language:Yi.PYTHON}}}function ur(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:cr.OUTCOME_FAILED}};let e=[];return(n.stdout||!n.outputFiles)&&e.push("Code execution result:\n".concat(n.stdout,"\n")),n.outputFiles&&e.push("Saved artifacts:\n"+n.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:cr.OUTCOME_OK}}}function fr(n,e,t){var r;if(!((r=n.parts)!=null&&r.length))return;let o=n.parts[n.parts.length-1];o.executableCode?n.parts[n.parts.length-1]={text:e[0]+o.executableCode.code+e[1]}:n.parts.length==1&&o.codeExecutionResult&&(n.parts[n.parts.length-1]={text:t[0]+o.codeExecutionResult.output+t[1]},n.role="user")}import{cloneDeep as Ji}from"lodash-es";var pn="_code_execution_context",mn="execution_session_id",Ce="processed_input_files",ve="_code_executor_input_files",ye="_code_executor_error_counts",gn="_code_execution_results",He=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(pn))!=null?t:{},this.sessionState=e}getStateDelta(){return{[pn]:Ji(this.context)}}getExecutionId(){if(mn in this.context)return this.context[mn]}setExecutionId(e){this.context[mn]=e}getProcessedFileNames(){return Ce in this.context?this.context[Ce]:[]}addProcessedFileNames(e){Ce in this.context||(this.context[Ce]=[]),this.context[Ce].push(...e)}getInputFiles(){return ve in this.sessionState?this.sessionState.get(ve):[]}addInputFiles(e){ve in this.sessionState||this.sessionState.set(ve,[]),this.sessionState.get(ve).push(...e)}clearInputFiles(){ve in this.sessionState&&this.sessionState.set(ve,[]),Ce in this.context&&(this.context[Ce]=[])}getErrorCount(e){return ye in this.sessionState&&this.sessionState.get(ye)[e]||0}incrementErrorCount(e){ye in this.sessionState||this.sessionState.set(ye,{}),this.sessionState.get(ye)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(ye in this.sessionState))return;let t=this.sessionState.get(ye);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){gn in this.sessionState||this.sessionState.set(gn,{});let i=this.sessionState.get(gn);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(pn)||{}}};var hn=class extends B{runAsync(e,t){return h(this,null,function*(){if(E(e.agent)&&e.agent.codeExecutor){try{for(var o=A(Zi(e,t)),r,i,s;r=!(i=yield new d(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new d(i.call(o)))}finally{if(s)throw s[0]}}if(mt(e.agent.codeExecutor))for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];fr(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},gt={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Xi="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",Cn=class{runAsync(e,t){return h(this,null,function*(){if(!t.partial)try{for(var o=A(Qi(e,t)),r,i,s;r=!(i=yield new d(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new d(i.call(o)))}finally{if(s)throw s[0]}}})}},Hu=new Cn;function Zi(n,e){return h(this,null,function*(){let t=n.agent;if(!E(t))return;let o=t.codeExecutor;if(!o||!mt(o))return;if(Ye(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new He(new b(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=es(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=ts(c);if(!l)return;let u={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},dn(l)]};e.contents.push(dr(u)),yield T({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=pr(n,r),p=yield new d(o.executeCode({invocationContext:n,codeExecutionInput:{code:l,language:"python",inputFiles:[c],executionId:f}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:p.stdout,resultStderr:p.stderr}),r.addProcessedFileNames([c.name]);let m=yield new d(mr(n,r,p));yield m,e.contents.push(dr(m.content))}})}function Qi(n,e){return h(this,null,function*(){let t=n.agent;if(!E(t))return;let o=t.codeExecutor;if(!o||!mt(o)||!e||!e.content||Ye(o))return;let r=new He(new b(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=lr(i,o.codeBlockDelimiters);if(!s)return;yield T({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=pr(n,r),c=yield new d(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 yield new d(mr(n,r,c)),e.content=void 0})}function es(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||!gt[l])continue;let u="data_".concat(i+1,"_").concat(a+1).concat(gt[l].extension);c.text="\nAvailable file: `".concat(u,"`\n");let f={name:u,content:To(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function pr(n,e){var r;let t=n.agent;if(!E(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function mr(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[ur(t)]},r=H({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(n.invocationId):e.resetErrorCount(n.invocationId);for(let i of t.outputFiles){let s=await n.artifactService.saveArtifact({appName:n.appName||"",userId:n.userId||"",sessionId:n.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return T({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function ts(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!gt[n.mimeType])return;let t=e(n.name),o=gt[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return"\n".concat(Xi,"\n\n# Load the dataframe.\n").concat(t," = ").concat(o,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var gr=new hn;function V(n){return"isCompacted"in n&&n.isCompacted===!0}function hr(n={}){return w(x({},T(n)),{isCompacted:n.isCompacted||!0,startTime:n.startTime,endTime:n.endTime,compactedContent:n.compactedContent})}import{createUserContent as ns}from"@google/genai";import{cloneDeep as os}from"lodash-es";function vn(n,e,t){var s,a,c;let o=[];for(let l of n){if(V(l)){o.push(ls(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)||rs(l)||is(l)||o.push(yr(e,l)?ss(l):l)}let r=as(o);r=cs(r);let i=[];for(let l of r){let u=os(l.content);Bo(u),i.push(u)}return i}function vr(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||yr(e,r))return vn(n.slice(o),e,t)}return[]}function rs(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)===it||((o=r.functionResponse)==null?void 0:o.name)===it)return!0;return!1}function is(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)===we||((o=r.functionResponse)==null?void 0:o.name)===we)return!0;return!1}function yr(n,e){return!!n&&e.author!==n&&e.author!=="user"}function ss(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:"[".concat(n.author,"] said: ").concat(c.text)});else if(c.functionCall){let l=Cr(c.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(n.author,"] called tool `").concat(c.functionCall.name,"` with parameters: ").concat(l)})}else if(c.functionResponse){let l=Cr(c.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(n.author,"] tool `").concat(c.functionResponse.name,"` returned result: ").concat(l)})}else(a=e.parts)==null||a.push(c);return T({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function xr(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=T(n[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let o={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(o[s.functionResponse.id]=i)}for(let i of n.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in o?t[o[a]]=s:(t.push(s),o[a]=t.length-1)}else t.push(s)}return e}function as(n){if(n.length===0)return n;let e=n[n.length-1],t=z(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=L(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(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let p=new Set(u.map(C=>C.id).filter(C=>!!C));if(!Array.from(o).every(C=>p.has(C)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(p).join(", "),", function response")+" ids provided: ".concat(Array.from(o).join(", ")));o=p;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(o).join(", ")));let s=[];for(let c=i+1;c<n.length-1;c++){let l=n[c],u=z(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(xr(s)),a}function cs(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=z(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(z(o).length>0)continue;let r=L(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(xr(a))}}else t.push(o)}return t}function Cr(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch(e){return String(n)}}function ls(n){let e=ns("[Previous Context Summary]:\n".concat(n.compactedContent));return T({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}var ht=class{runAsync(e,t){return h(this,null,function*(){let o=e.agent;if(!o||!E(o))return;let r=e.session.events,i=r.filter(V),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||V(c)||c.timestamp<=s.endTime));r=[s,...a]}o.includeContents==="default"?t.contents=vn(r,o.name,e.branch):t.contents=vr(r,o.name,e.branch)})}},Ct=new ht;var vt=new Set;function k(n,e,t){if(e===void 0){let o=n.name;return class extends n{constructor(...i){vt.has(o)||(g.warn("Class ".concat(o," is experimental and may change in the future.")),vt.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="".concat(o,".").concat(r),s=t.value;return t.value=function(...a){return vt.has(i)||(g.warn("Method ".concat(i," is experimental and may change in the future.")),vt.add(i)),s.apply(this,a)},t}throw new Error("Invalid decorator usage")}var yn=(t=>(t.Manual="Manual",t.Auto="Auto",t))(yn||{}),X=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){}};_([k],X.prototype,"beforeToolSelection",1),_([k],X.prototype,"beforeContextCompaction",1),_([k],X.prototype,"afterContextCompaction",1);var Le=class{constructor(e){this.compactors=e}runAsync(e,t){return h(this,null,function*(){for(let o of this.compactors)if(yield new d(Promise.resolve(o.shouldCompact(e)))){yield new d(e.pluginManager.runBeforeContextCompaction({invocationContext:e,trigger:"Auto"}));let i=new Set(e.session.events);yield new d(Promise.resolve(o.compact(e))),yield new d(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 xn=class extends B{runAsync(e,t){return h(this,null,function*(){let o=e.agent,r=['You are an agent. Your internal name is "'.concat(o.name,'".')];o.description&&r.push('The description about you is "'.concat(o.description,'"')),D(t,r)})}},Er=new xn;async function En(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let p=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!p)throw new Error("Artifact ".concat(f," not found."));return String(p)}if(!ds(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: `".concat(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 us=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ar(n){return n===""||n===void 0?!1:us.test(n)}var fs=[b.APP_PREFIX,b.USER_PREFIX,b.TEMP_PREFIX];function ds(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?Ar(n):fs.includes(e[0]+":")?Ar(e[1]):!1}var An=class extends B{runAsync(e,t){return h(this,null,function*(){let o=e.agent;if(!E(o))return;let r=o.rootAgent;if(E(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new d(r.canonicalGlobalInstruction(new P(e))),a=i;s&&(a=yield new d(En(i,new P(e)))),D(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=yield new d(o.canonicalInstruction(new P(e))),a=i;s&&(a=yield new d(En(i,new P(e)))),D(t,[a])}})}},Tr=new An;var Tn=class extends B{runAsync(e){return h(this,null,function*(){let t=e.agent;if(!E(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=z(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==we)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 de({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=L(a);if(!c)continue;let l={},u={};for(let C of c){if(!C.id||!(C.id in r))continue;let v=C.args;if(!v||!("originalFunctionCall"in v))continue;let y=v.originalFunctionCall;y.id&&(l[y.id]=r[C.id],u[y.id]=y)}if(Object.keys(l).length===0)continue;for(let C=o.length-1;C>i;C--){let v=o[C],y=z(v);if(y){for(let I of y)I.id&&I.id in l&&(delete l[I.id],delete u[I.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=yield new d(t.canonicalTools(new P(e))),p=Object.fromEntries(f.map(C=>[C.name,C])),m=yield new d(st({invocationContext:e,functionCalls:Object.values(u),toolsDict:p,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l}));m&&(yield m);return}})}},Sr=new Tn;var Sn=class extends B{runAsync(e,t){return h(this,null,function*(){let o=e.agent;if(!E(o))return;let r=yield new d(o.canonicalTools(new P(e)));if(r.length===0)return;let i={};for(let c of r)i[c.name]=c;let s=new O({invocationContext:e}),a=yield new d(e.pluginManager.runBeforeToolSelection({callbackContext:s,tools:i}));a!==void 0&&(t.allowedTools=Object.keys(a))})}},Rr=new Sn;var Rn=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(Rn||{});function br(n={}){return x({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ps(n.maxLlmCalls||500),pauseOnToolCalls:!1},n)}function ps(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return n<=0&&g.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),n}var Ir="adk_agent_name";async function wr(n,e){return nn(n)?[n]:await n.getTools(e)}var bn=Symbol.for("google.adk.llmAgent");function E(n){return typeof n=="object"&&n!==null&&bn in n&&n[bn]===!0}var _r,kr,yt=class n extends(kr=G,_r=bn,kr){constructor(t){var r,i,s,a,c,l,u,f,p;super(t);this[_r]=!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=ge(t.inputSchema)?ke(t.inputSchema):t.inputSchema,this.outputSchema=ge(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:[nr,Er,Tr,Sr,Ct,gr,Rr],!t.requestProcessors&&t.contextCompactors&&t.contextCompactors.length>0){let m=this.requestProcessors.indexOf(Ct);m!==-1?this.requestProcessors.splice(m,0,new Le(t.contextCompactors)):this.requestProcessors.push(new Le(t.contextCompactors))}if(this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((p=this.subAgents)!=null&&p.length)||this.requestProcessors.push(tr),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)&&(g.warn("Invalid config for agent ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0)}get canonicalModel(){if(Jt(this.model))return this.model;if(typeof this.model=="string"&&this.model)return me.newLlm(this.model);let t=this.parentAgent;for(;t;){if(E(t))return t.canonicalModel;t=t.parentAgent}throw new Error("No model found for ".concat(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 wr(r,t);o.push(...i)}return o}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return n.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return n.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return n.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return n.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){g.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(t.author));return}if(!this.outputKey){g.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!oe(t)){g.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){g.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let o=t.content.parts.map(a=>a.text?a.text:"").join(""),r=o;if(this.outputSchema){if(!o.trim())return;try{r=JSON.parse(o)}catch(a){g.error("Error parsing output for agent ".concat(this.name),a)}}t.actions.stateDelta[this.outputKey]=r}runAsyncImpl(t){return h(this,null,function*(){var o;for(;;){let c;try{for(var r=A(this.runOneStepAsync(t)),i,s,a;i=!(s=yield new d(r.next())).done;i=!1){let l=s.value;if((o=t.abortSignal)!=null&&o.aborted)return;c=l,this.maybeSaveOutputToState(l),yield l}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new d(s.call(r)))}finally{if(a)throw a[0]}}if(!c||oe(c))break;if(c.partial){g.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(t){return h(this,null,function*(){var o;try{for(var r=A(this.runLiveFlow(t)),i,s,a;i=!(s=yield new d(r.next())).done;i=!1){let c=s.value;if((o=t.abortSignal)!=null&&o.aborted)return;this.maybeSaveOutputToState(c),yield c}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new d(s.call(r)))}finally{if(a)throw a[0]}}t.endInvocation})}runLiveFlow(t){return h(this,null,function*(){throw yield new d(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(t){return h(this,null,function*(){var a,p,m;let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let C of this.requestProcessors)try{for(var c=A(C.runAsync(t,o)),l,u,f;l=!(u=yield new d(c.next())).done;l=!1){let v=u.value;if((a=t.abortSignal)!=null&&a.aborted)return;yield v}}catch(u){f=[u]}finally{try{l&&(u=c.return)&&(yield new d(u.call(c)))}finally{if(f)throw f[0]}}for(let C of this.tools){let v=new O({invocationContext:t}),y=(yield new d(wr(C,new P(t)))).filter(I=>!o.allowedTools||o.allowedTools.includes(I.name));for(let I of y)if(yield new d(I.processLlmRequest({toolContext:v,llmRequest:o})),(p=t.abortSignal)!=null&&p.aborted)return}if(t.endInvocation||(m=t.abortSignal)!=null&&m.aborted)return;let r=T({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=J.startSpan("call_llm"),s=gs.setSpan(ms.active(),i);yield*M(ue(s,this,function(){return h(this,null,function*(){let C=function(){return h(this,null,function*(){var v,y;try{for(var $=A(this.callLlmAsync(t,o,r)),dv,pv,te;dv=!(pv=yield new d($.next())).done;dv=!1){let ne=pv.value;if((v=t.abortSignal)!=null&&v.aborted)return;try{for(var I=A(this.postprocess(t,o,ne,r)),U,F,R;U=!(F=yield new d(I.next())).done;U=!1){let ce=F.value;if((y=t.abortSignal)!=null&&y.aborted)return;r.id=Ot(),r.timestamp=new Date().getTime(),yield ce}}catch(F){R=[F]}finally{try{U&&(F=I.return)&&(yield new d(F.call(I)))}finally{if(R)throw R[0]}}}}catch(pv){te=[pv]}finally{try{dv&&(pv=$.return)&&(yield new d(pv.call($)))}finally{if(te)throw te[0]}}})};yield*M(this.runAndHandleError(C.call(this),t,o,r))})})),i.end()})}postprocess(t,o,r,i){return h(this,null,function*(){var f,y,I,U,F;for(let te of this.responseProcessors)try{for(var p=A(te.runAsync(t,r)),m,C,v;m=!(C=yield new d(p.next())).done;m=!1){let ne=C.value;if((f=t.abortSignal)!=null&&f.aborted)return;yield ne}}catch(C){v=[C]}finally{try{m&&(C=p.return)&&(yield new d(C.call(p)))}finally{if(v)throw v[0]}}if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=T(x(x({},i),r));if(s.content){let te=L(s);te!=null&&te.length&&(Oo(s),s.longRunningToolIds=Array.from(Mo(te,o.toolsDict)))}if(yield s,!((y=L(s))!=null&&y.length))return;if((I=t.runConfig)!=null&&I.pauseOnToolCalls){t.endInvocation=!0;return}let a=yield new d(No({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!a||(U=t.abortSignal)!=null&&U.aborted)return;let c=Kt(t,a);c&&(yield c);let l=Wt({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let te=this.getAgentByName(t,u);try{for(var R=A(te.runAsync(t)),$,dv,pv;$=!(dv=yield new d(R.next())).done;$=!1){let ne=dv.value;if((F=t.abortSignal)!=null&&F.aborted)return;yield ne}}catch(dv){pv=[dv]}finally{try{$&&(dv=R.return)&&(yield new d(dv.call(R)))}finally{if(pv)throw pv[0]}}}})}getAgentByName(t,o){let i=t.agent.rootAgent.findAgent(o);if(!i)throw new Error("Agent ".concat(o," not found in the agent tree."));return i}callLlmAsync(t,o,r){return h(this,null,function*(){var a,c,l,u,f,p,m,C;let i=yield new d(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[Ir]||(o.config.labels[Ir]=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 F=s.generateContentAsync(o,((p=t.runConfig)==null?void 0:p.streamingMode)==="sse",t.abortSignal);try{for(var v=A(F),y,I,U;y=!(I=yield new d(v.next())).done;y=!1){let R=I.value;if(Eo({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:R}),(m=t.abortSignal)!=null&&m.aborted)return;let $=yield new d(this.handleAfterModelCallback(t,R,r));if((C=t.abortSignal)!=null&&C.aborted)return;yield $!=null?$:R}}catch(I){U=[I]}finally{try{y&&(I=v.return)&&(yield new d(I.call(v)))}finally{if(U)throw U[0]}}}})}async handleBeforeModelCallback(t,o,r){var a,c;let i=new O({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 O({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}}runAndHandleError(t,o,r,i){return h(this,null,function*(){var s;try{try{for(var a=A(t),c,l,u;c=!(l=yield new d(a.next())).done;c=!1){let f=l.value;if((s=o.abortSignal)!=null&&s.aborted)return;yield f}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new d(l.call(a)))}finally{if(u)throw u[0]}}}catch(f){let p=new O({invocationContext:o,eventActions:i.actions});if(f instanceof Error){let m=yield new d(o.pluginManager.runOnModelErrorCallback({callbackContext:p,llmRequest:r,error:f}));if(m)yield m;else{let C="UNKNOWN_ERROR",v=f.message;try{let y=JSON.parse(f.message);y!=null&&y.error&&(C=String(y.error.code||"UNKNOWN_ERROR"),v=y.error.message||v)}catch(y){}i.actions?yield T({invocationId:o.invocationId,author:this.name,errorCode:C,errorMessage:v}):yield{errorCode:C,errorMessage:v}}}else throw g.error("Unknown error during response generation",f),f}})}};var In=Symbol.for("google.adk.loopAgent");function hs(n){return typeof n=="object"&&n!==null&&In in n&&n[In]===!0}var Lr,Pr,wn=class extends(Pr=G,Lr=In,Pr){constructor(t){var o;super(t);this[Lr]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}runAsyncImpl(t){return h(this,null,function*(){var r;let o=0;for(;o<this.maxIterations;){for(let l of this.subAgents){let u=!1;try{for(var i=A(l.runAsync(t)),s,a,c;s=!(a=yield new d(i.next())).done;s=!1){let f=a.value;if((r=t.abortSignal)!=null&&r.aborted)return;yield f,f.actions.escalate&&(u=!0)}}catch(a){c=[a]}finally{try{s&&(a=i.return)&&(yield new d(a.call(i)))}finally{if(c)throw c[0]}}if(u)return}o++}})}runLiveImpl(t){return h(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var _n=Symbol.for("google.adk.parallelAgent");function Cs(n){return typeof n=="object"&&n!==null&&_n in n&&n[_n]===!0}var Or,Br,kn=class extends(Br=G,Or=_n,Br){constructor(){super(...arguments);this[Or]=!0}runAsyncImpl(t){return h(this,null,function*(){var r;let o=this.subAgents.map(l=>l.runAsync(vs(this,l,t)));try{for(var i=A(ys(o)),s,a,c;s=!(a=yield new d(i.next())).done;s=!1){let l=a.value;if((r=t.abortSignal)!=null&&r.aborted)return;yield l}}catch(a){c=[a]}finally{try{s&&(a=i.return)&&(yield new d(a.call(i)))}finally{if(c)throw c[0]}}})}runLiveImpl(t){return h(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function vs(n,e,t){let o=new Z(t),r="".concat(n.name,".").concat(e.name);return o.branch=o.branch?"".concat(o.branch,".").concat(r):r,o}function ys(n){return h(this,null,function*(){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}=yield new d(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)}})}function Pe(n,e,t,o){return h(this,null,function*(){let r=yield new d(t(n,e));if(!r)throw new Error("Initial routing failed, no item selected.");let i=r;g.debug("Router selected initial key: ".concat(i));let s=n[i];if(!s)throw new Error("Item not found for key: ".concat(i));let a=new Set([i]);for(;;){let p=o(s),m=!1;try{if(xs(p)){try{for(var c=A(p),l,u,f;l=!(u=yield new d(c.next())).done;l=!1){let v=u.value;yield v,m=!0}}catch(u){f=[u]}finally{try{l&&(u=c.return)&&(yield new d(u.call(c)))}finally{if(f)throw f[0]}}return}yield yield new d(p);return}catch(C){if(m)throw C;{let v=yield new d(t(n,e,{failedKeys:a,lastError:C}));if(g.debug("Router selected next key: ".concat(v)),v===void 0||a.has(v))throw C;if(i=v,s=n[i],!s)throw new Error("Item not found for key: ".concat(i));a.add(i)}}}})}function xs(n){return typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function"}var Ln=Symbol.for("google.adk.routedAgent");function Es(n){return typeof n=="object"&&n!==null&&Ln in n&&n[Ln]===!0}var Mr,Nr,Je=class extends(Nr=G,Mr=Ln,Nr){constructor(t){let o=Array.isArray(t.agents)?t.agents:Object.values(t.agents);super(w(x({},t),{subAgents:o}));this[Mr]=!0;Array.isArray(t.agents)?this.agents=Object.fromEntries(t.agents.map(r=>[r.name,r])):this.agents=t.agents,this.router=t.router}runAsyncImpl(t){return h(this,null,function*(){yield*M(Pe(this.agents,t,this.router,o=>o.runAsync(t)))})}runLiveImpl(t){return h(this,null,function*(){yield*M(Pe(this.agents,t,this.router,o=>o.runLive(t)))})}};Je=_([k],Je);var Pn="task_completed",On=Symbol.for("google.adk.sequentialAgent");function As(n){return typeof n=="object"&&n!==null&&On in n&&n[On]===!0}var Fr,Dr,Bn=class extends(Dr=G,Fr=On,Dr){constructor(){super(...arguments);this[Fr]=!0}runAsyncImpl(t){return h(this,null,function*(){for(let a of this.subAgents)try{for(var o=A(a.runAsync(t)),r,i,s;r=!(i=yield new d(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new d(i.call(o)))}finally{if(s)throw s[0]}}})}runLiveImpl(t){return h(this,null,function*(){for(let a of this.subAgents)E(a)&&((yield new d(a.canonicalTools(new P(t)))).some(u=>u.name===Pn)||(a.tools.push(new ee({name:Pn,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),a.instruction+="If you finished the user's request according to its description, call the ".concat(Pn," 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 a of this.subAgents)try{for(var o=A(a.runLive(t)),r,i,s;r=!(i=yield new d(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new d(i.call(o)))}finally{if(s)throw s[0]}}})}};var Xe=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=Oe(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=Oe(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="".concat(e,"/").concat(t,"/").concat(o,"/"),i="".concat(e,"/").concat(t,"/user/"),s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:o,filename:r}){let i=Oe(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=Oe(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=Oe(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=Oe(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 Oe(n,e,t,o){return Ts(o)?"".concat(n,"/").concat(e,"/user/").concat(o):"".concat(n,"/").concat(e,"/").concat(t,"/").concat(o)}function Ts(n){return n.startsWith("user:")}var Mn=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(Mn||{});var Nn=class{constructor(){this.providers=new Map}register(e,t){this.providers.set(e,t)}getProvider(e){return this.providers.get(e.type)}};var Fn=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 Dn=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)}};import{z as Y}from"zod";var Ss=Y.object({issuer:Y.string(),authorization_endpoint:Y.string(),token_endpoint:Y.string(),scopes_supported:Y.array(Y.string()).optional(),registration_endpoint:Y.string().optional()}),Rs=Y.object({resource:Y.string(),authorization_servers:Y.array(Y.string()).default([])}),$n=class{async discoverAuthServerMetadata(e){if(!$r(e))return;let t,o;try{let i=new URL(e);t="".concat(i.protocol,"//").concat(i.host),o=i.pathname}catch(i){g.warn("Failed to parse issuerUrl ".concat(e,": ").concat(i));return}let r=[];o&&o!=="/"?r.push("".concat(t,"/.well-known/oauth-authorization-server").concat(o),"".concat(t,"/.well-known/openid-configuration").concat(o),"".concat(t).concat(o,"/.well-known/openid-configuration")):r.push("".concat(t,"/.well-known/oauth-authorization-server"),"".concat(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=Ss.parse(a);if(c.issuer.replace(/\/$/,"")===e.replace(/\/$/,""))return c;g.warn("Issuer in metadata ".concat(c.issuer," does not match issuerUrl ").concat(e))}catch(s){g.debug("Failed to fetch metadata from ".concat(i,": ").concat(s))}}async discoverResourceMetadata(e){if(!$r(e))return;let t,o;try{let i=new URL(e);t="".concat(i.protocol,"//").concat(i.host),o=i.pathname}catch(i){g.warn("Failed to parse resourceUrl ".concat(e,": ").concat(i));return}let r;o&&o!=="/"?r="".concat(t,"/.well-known/oauth-protected-resource").concat(o):r="".concat(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=Rs.parse(s);if(a.resource.replace(/\/$/,"")===e.replace(/\/$/,""))return a;g.warn("Resource in metadata ".concat(a.resource," does not match resourceUrl ").concat(e))}catch(i){g.debug("Failed to fetch metadata from ".concat(r,": ").concat(i))}}};function $r(n){try{let e=new URL(n);if(e.protocol!=="https:")return g.warn("Unsafe protocol for discovery URL: ".concat(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 g.warn("Unsafe host for discovery URL: ".concat(t)),!1;let o=t.match(/^172\.(\d+)\./);if(o){let r=parseInt(o[1],10);if(r>=16&&r<=31)return g.warn("Unsafe host for discovery URL: ".concat(t)),!1}return!0}catch(e){return g.warn("Failed to parse URL for validation ".concat(n,": ").concat(e)),!1}}var qn=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 bs="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.",Un=class{constructor(e){this.llm=e.llm,this.prompt=e.prompt||bs}async summarize(e){var u,f,p,m,C,v;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 R=0;R<e.length;R++)r+="[Event ".concat(R+1," - Author: ").concat(e[R].author,"]\n"),r+="".concat($e(e[R]),"\n\n");let s={contents:[{role:"user",parts:[{text:"".concat(this.prompt,"\n\n").concat(r)}]}],toolsDict:{},liveConnectConfig:{}},a=this.llm.generateContentAsync(s,!1),c="",l=await a.next();if(l.done||!((p=(f=(u=l.value.content)==null?void 0:u.parts)==null?void 0:f[0])!=null&&p.text))throw new Error("LLM failed to return a valid summary.");c+=l.value.content.parts[0].text;try{for(var y=A(a),I,U,F;I=!(U=await y.next()).done;I=!1){let R=U.value;(v=(C=(m=R.content)==null?void 0:m.parts)==null?void 0:C[0])!=null&&v.text&&(c+=R.content.parts[0].text)}}catch(U){F=[U]}finally{try{I&&(U=y.return)&&await U.call(y)}finally{if(F)throw F[0]}}return hr({author:"system",content:{role:"model",parts:[{text:c}]},startTime:t,endTime:o,compactedContent:c})}};var Gn=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];V(i)&&(!t||i.endTime>t.endTime)&&(t=i)}if(!t)return e;let o=e.filter(r=>!V(r)&&r.timestamp>t.endTime);return[t,...o]}shouldCompact(e){let t=e.session.events,o=this.getActiveEvents(t);if(o.filter(s=>!V(s)).length<=this.eventRetentionSize)return!1;let i=0;for(let s of o)i+=Is(s);return i>this.tokenThreshold}async compact(e){let t=e.session.events,o=this.getActiveEvents(t),r=o.filter(u=>!V(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(_s(u)&&ws(f))i--;else break}if(i===0)return;let s=r.slice(0,i),a=o.find(V),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 Is(n){var t;if(((t=n.usageMetadata)==null?void 0:t.promptTokenCount)!==void 0)return n.usageMetadata.promptTokenCount;let e=$e(n);return Math.ceil(e.length/4)}function ws(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionCall!==void 0))}function _s(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionResponse!==void 0))}var zn=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)}};import{isEmpty as Ze}from"lodash-es";var qr=(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))(qr||{});function ks(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&&!Ze(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!Ze(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!Ze(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!Ze(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&&!Ze(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),oe(n)&&e.push({type:"finished",output:void 0}),e}var jn=Symbol.for("google.adk.baseExampleProvider");function Ls(n){return typeof n=="object"&&n!==null&&jn in n&&n[jn]===!0}var Ur;Ur=jn;var Vn=class{constructor(){this[Ur]=!0}};var xe=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Gr(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=Gr(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(p=>p.text).filter(p=>!!p).join(" "),u=Ps(l);if(!u.size)continue;o.some(p=>u.has(p))&&r.memories.push({content:c.content,author:c.author,timestamp:Os(c.timestamp)})}return r}};function Gr(n,e){return"".concat(n,"/").concat(e)}function Ps(n){return new Set([...n.matchAll(/[A-Za-z]+/g)].map(e=>e[0].toLowerCase()))}function Os(n){return new Date(n).toISOString()}var Qe=class extends se{constructor({models:e,router:t,modelName:o="routed-llm"}){let r=Array.isArray(e)?Object.fromEntries(e.map(a=>[a.model,a])):e,i=Object.entries(r).map(([a,c])=>"".concat(a," (").concat(c.model,")")),s="RoutedLlm[".concat(i.join(", "),"]");super({model:o==="routed-llm"?s:o}),this.models=r,this.router=t}generateContentAsync(e,t){return h(this,null,function*(){g.info("Routing request via ".concat(this.model)),yield*M(Pe(this.models,e,this.router,o=>o.generateContentAsync(e,t)))})}async connect(e){let o=await Pe(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}};Qe=_([k],Qe);var Kn=class extends X{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: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((o=e.agent.name)!=null?o:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({event:e}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(e.id)),this.log(" Author: ".concat(e.author)),this.log(" Content: ".concat(this.formatContent(e.content))),this.log(" Final Response: ".concat(oe(e)));let t=L(e);if(t.length>0){let r=t.map(i=>i.name);this.log(" Function Calls: ".concat(r))}let o=z(e);if(o.length>0){let r=o.map(i=>i.name);this.log(" Function Responses: ".concat(r))}e.longRunningToolIds&&e.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...e.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(e.agentName)),this.log(" Invocation ID: ".concat(e.invocationId)),e.invocationContext.branch&&this.log(" Branch: ".concat(e.invocationContext.branch))}async afterAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(e.agentName)),this.log(" Invocation ID: ".concat(e.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var o;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((o=t.model)!=null?o:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(o.agentName)),this.log(" Function Call ID: ".concat(o.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolContext:t,result:o}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(t.agentName)),this.log(" Function Call ID: ".concat(t.functionCallId)),this.log(" Result: ".concat(this.formatArgs(o)))}async onModelErrorCallback({callbackContext:e,error:t}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(t))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(o.agentName)),this.log(" Function Call ID: ".concat(o.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");g.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let o=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),o.push("text: '".concat(i,"'"))}else r.functionCall?o.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?o.push("function_response: ".concat(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 et=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),g.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,o){for(let r of e)try{let i=await t(r);if(i!==void 0)return g.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(o,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(o,"' callback: ").concat(i);throw g.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async 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 jr="adk_request_confirmation",Wn="orcas_tool_call_security_check_states",zr="This tool call needs external confirmation before completion.",Vr=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(Vr||{}),xt=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Yn=class extends X{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new xt}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:zr};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(Wn))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(Wn))!=null?i:{};r[o]=t,e.state.set(Wn,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: ".concat(r.reason)};case"CONFIRM":return o.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:zr};case"ALLOW":return;default:return}}};function Bs(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===jr&&e.push(t.functionCall);return e}import{cloneDeep as Kr}from"lodash-es";import{cloneDeep as Ms}from"lodash-es";var tt=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=Ns(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(b.TEMP_PREFIX)||(e.state[o]=r)}};function Ns(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(b.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function Hn(n={},e={},t={}){let o=Ms(t);for(let[r,i]of Object.entries(n))o[b.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[b.USER_PREFIX+r]=i;return o}function Et(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}var Ee=class extends tt{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}async createSession({appName:t,userId:o,state:r,sessionId:i}){var c;let s=Et({id:i||re(),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=Kr(s);return a.state=Hn(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=Kr(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=Hn(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(Et({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:o,sessionId:r}){await this.getSession({appName:t,userId:o,sessionId:r})&&delete this.sessions[t][o][r]}async appendEvent({session:t,event:o}){await super.appendEvent({session:t,event:o}),t.lastUpdateTime=o.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{g.warn("Failed to append event to session ".concat(s,": ").concat(l))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),o;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),o;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),o;if(o.actions&&o.actions.stateDelta)for(let l of Object.keys(o.actions.stateDelta))l.startsWith(b.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(b.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(b.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(b.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}};import{createPartFromText as Fs}from"@google/genai";import{context as Ds,trace as $s}from"@opentelemetry/api";var Jn=Symbol.for("google.adk.runner");function qs(n){return typeof n=="object"&&n!==null&&Jn in n&&n[Jn]===!0}var Wr;Wr=Jn;var Ae=class{constructor(e){this[Wr]=!0;var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new et((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runEphemeral(e){return h(this,null,function*(){let o=(yield new d(this.sessionService.createSession({appName:this.appName,userId:e.userId}))).id;try{yield*M(this.runAsync({userId:e.userId,sessionId:o,newMessage:e.newMessage,stateDelta:e.stateDelta,runConfig:e.runConfig}))}finally{yield new d(this.sessionService.deleteSession({appName:this.appName,userId:e.userId,sessionId:o}))}})}runAsync(e){return h(this,null,function*(){let{userId:t,sessionId:o,stateDelta:r}=e,i=br(e.runConfig),s=e.newMessage,a=J.startSpan("invocation"),c=$s.setSpan(Ds.active(),a);try{yield*M(ue(c,this,function(){return h(this,null,function*(){var p,m,C,v,y,I,U,F,R,ne;let l=yield new d(this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o}));if((p=e.abortSignal)!=null&&p.aborted)return;if(!l)throw this.appName?new Error("Session not found: ".concat(o)):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&E(this.agent)){let ce=this.agent.canonicalModel.model;if(!Ke(ce))throw new Error("CFC is not supported for model: ".concat(ce," in agent: ").concat(this.agent.name));Ye(this.agent.codeExecutor)||(this.agent.codeExecutor=new We)}let u=new Z({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Io(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager,abortSignal:e.abortSignal}),f=yield new d(this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u}));if(!((m=e.abortSignal)!=null&&m.aborted)){if(f&&(s=f),s){if(!((C=s.parts)!=null&&C.length))throw new Error("No parts in the newMessage.");if(i.saveInputBlobsAsArtifacts&&(yield new d(this.saveArtifacts(u.invocationId,l.userId,l.id,s)),(v=e.abortSignal)!=null&&v.aborted)||(yield new d(this.sessionService.appendEvent({session:l,event:T({invocationId:u.invocationId,author:"user",actions:r?H({stateDelta:r}):void 0,content:s})})),(y=e.abortSignal)!=null&&y.aborted))return}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let ce=yield new d(this.pluginManager.runBeforeRunCallback({invocationContext:u}));if((I=e.abortSignal)!=null&&I.aborted)return;if(ce){let le=T({invocationId:u.invocationId,author:"model",content:ce});if(yield new d(this.sessionService.appendEvent({session:l,event:le})),(U=e.abortSignal)!=null&&U.aborted)return;yield le}else{try{for(var $=A(u.agent.runAsync(u)),dv,pv,te;dv=!(pv=yield new d($.next())).done;dv=!1){let le=pv.value;if((F=e.abortSignal)!=null&&F.aborted)return;le.partial||(yield new d(this.sessionService.appendEvent({session:l,event:le})));let io=yield new d(this.pluginManager.runOnEventCallback({invocationContext:u,event:le}));if((R=e.abortSignal)!=null&&R.aborted)return;io?yield io:yield le}}catch(pv){te=[pv]}finally{try{dv&&(pv=$.return)&&(yield new d(pv.call($)))}finally{if(te)throw te[0]}}if(yield new d(this.pluginManager.runAfterRunCallback({invocationContext:u})),(ne=e.abortSignal)!=null&&ne.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_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:o,filename:c,artifact:a}),r.parts[s]=Fs("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let o=Us(e.events);if(o&&o.author)return t.findAgent(o.author)||t;for(let r=e.events.length-1;r>=0;r--){g.info("event:",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){g.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!E(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Us(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=L(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var Xn=class extends Ae{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new Xe,sessionService:new Ee,memoryService:new xe})}};import{Type as Tt}from"@google/genai";var At=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 Zn=Symbol.for("google.adk.agentTool");function Gs(n){return typeof n=="object"&&n!==null&&Zn in n&&n[Zn]===!0}var Yr,Hr,Qn=class extends(Hr=S,Yr=Zn,Hr){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[Yr]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(E(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:Tt.OBJECT,properties:{request:{type:Tt.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=E(this.agent)&&this.agent.outputSchema;t.response=o?{type:Tt.OBJECT}:{type:Tt.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,p,m,C,F,R;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:E(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new Ae({appName:this.agent.name,agent:this.agent,artifactService:new At(o),sessionService:(f=o.invocationContext.sessionService)!=null?f:new Ee,memoryService:(p=o.invocationContext.memoryService)!=null?p:new xe,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((m=o.abortSignal)!=null&&m.aborted)return"";let c;try{for(var v=A(s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i,abortSignal:o.abortSignal})),y,I,U;y=!(I=await v.next()).done;y=!1){let $=I.value;if((C=o.abortSignal)!=null&&C.aborted)return;$.actions.stateDelta&&o.state.update($.actions.stateDelta),c=$}}catch(I){U=[I]}finally{try{y&&(I=v.return)&&await I.call(v)}finally{if(U)throw U[0]}}if(!((R=(F=c==null?void 0:c.content)==null?void 0:F.parts)!=null&&R.length))return"";let l=E(this.agent)&&this.agent.outputSchema,u=c.content.parts.map($=>$.text).filter($=>$).join("\n");return l?JSON.parse(u):u}};var eo=Symbol.for("google.adk.baseToolset");function zs(n){return typeof n=="object"&&n!==null&&eo in n&&n[eo]===!0}var Jr;Jr=eo;var Be=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[Jr]=!0}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var St=class extends S{constructor(){super({name:"exit_loop",description:"Exits the loop.\n\nCall 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,""}},js=new St;var Rt=class extends S{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||[],ir(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(rr(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(e.model))}}},Vs=new Rt;import{Type as to}from"@google/genai";var Ks=Dt(),Ws=["image/","audio/","video/"],Ys=new Set(["application/pdf"]),Hs=new Set(["application/csv","application/json","application/xml"]);function Xr(n){if(n)return n.split(";")[0].trim()}function Js(n){let e=Xr(n);return e?Ws.some(t=>e.startsWith(t))||Ys.has(e):!1}function Xs(n,e){let t=n.inlineData;if(!t||Js(t.mimeType))return n;let o=Xr(t.mimeType)||"application/octet-stream",r=t.data;if(!r)return{text:"[Artifact: ".concat(e,", type: ").concat(o,". No inline data was provided.]")};let i=o.startsWith("text/")||Hs.has(o),s=Buffer.from(r,"base64");if(i)try{return{text:s.toString("utf8")}}catch(c){}let a=s.length/1024;return{text:"[Binary artifact: ".concat(e,", type: ").concat(o,", size: ").concat(a.toFixed(1)," KB. Content cannot be displayed inline.]")}}var bt=class extends S{constructor(){super({name:"load_artifacts",description:"Loads artifacts into the session for this request.\n\nNOTE: 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:to.OBJECT,properties:{artifact_names:{type:to.ARRAY,items:{type:to.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;D(t,["You have a list of artifacts:\n ".concat(JSON.stringify(o),"\n\n When the user asks questions about any of the artifacts, you should call the\n `load_artifacts` function to load the artifact. Always call load_artifacts\n before answering questions related to the artifacts, regardless of whether the\n artifacts have been loaded before. Do not depend on prior answers about the\n 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 m="user:".concat(u);f=await e.loadArtifact(m)}if(!f){Ks.warn('Artifact "'.concat(u,'" not found, skipping'));continue}let p=Xs(f,u);t.contents.push({role:"user",parts:[{text:"Artifact ".concat(u," is:")},p]})}}}}}},Zs=new bt;import{Type as Zr}from"@google/genai";var It=class extends S{constructor(){super({name:"load_memory",description:"Loads the memory for the current user.\n\nNOTE: Currently this tool only uses text part from the memory."})}_getDeclaration(){return{name:this.name,description:this.description,parameters:{type:Zr.OBJECT,properties:{query:{type:Zr.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&&D(e.llmRequest,["You have memory. You can use it to answer questions. If any questions need\nyou to look up the memory, you should call load_memory function with a query."])}},Qs=new It;var Qr="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",no=class extends ee{constructor(e){super(w(x({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Qr:e.description=Qr.trimStart(),e}};var wt=class extends S{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(f){g.warn("Failed to preload memory for query: ".concat(o));return}if(!r.memories||r.memories.length===0)return;let i=[];for(let f of r.memories){let p=f.timestamp?"Time: ".concat(f.timestamp):"";p&&i.push(p);let m=(u=(l=f.content.parts)==null?void 0:l.map(C=>{var v;return(v=C.text)!=null?v:""}).join(" "))!=null?u:"";m&&i.push(f.author?"".concat(f.author,": ").concat(m):m)}if(i.length===0)return;let s=i.join("\n"),a="The following content is from your previous conversations with the user.\nThey may be useful for answering the user's current query.\n<PAST_CONVERSATIONS>\n".concat(s,"\n</PAST_CONVERSATIONS>\n");D(e.llmRequest,[a])}},ea=new wt;import{Type as ta}from"@google/genai";function ei(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function _t(n){if(!n||n.length===0)return"<available_skills>\n</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>".concat(ei(o.name),"</name>")),e.push(" <description>".concat(ei(o.description),"</description>")),e.push(" </skill>")}return e.push("</available_skills>"),e.join("\n")}var Te=class extends S{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:ta.OBJECT,properties:{}}}}async runAsync(t){let o=Object.values(this.toolset.skills);return _t(o)}};Te=_([k],Te);import{Type as oo}from"@google/genai";import na from"node:path";var ti="Binary file detected. The content has been injected into the conversation history for you to analyze.",oa={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 ra(n){var t;let e=((t=n.split(".").pop())==null?void 0:t.toLowerCase())||"";return oa[e]||"application/octet-stream"}var Se=class extends S{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:oo.OBJECT,properties:{skill_name:{type:oo.STRING,description:"The name of the skill."},path:{type:oo.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=na.posix.normalize(r);let i=this.toolset.getSkill(o);if(!i)return{error:"Skill '".concat(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),p=(u=a.scripts)==null?void 0:u[f];p&&(s=p.src)}else return{error:"Path must start with 'references/', 'assets/', or 'scripts/'.",error_code:"INVALID_RESOURCE_PATH"};return s===void 0?{error:"Resource '".concat(r,"' not found in skill '").concat(o,"'."),error_code:"RESOURCE_NOT_FOUND"}:Buffer.isBuffer(s)?{skill_name:o,path:r,status:ti}:{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===ti){let l=c.skill_name,u=c.path,f=this.toolset.getSkill(l);if(!f)continue;let p=f.resources||{},m;if(u.startsWith("references/")?m=(i=p.references)==null?void 0:i[u.substring(11)]:u.startsWith("assets/")&&(m=(s=p.assets)==null?void 0:s[u.substring(7)]),Buffer.isBuffer(m)){let C=ra(u);o.contents.push({role:"user",parts:[{text:"The content of binary file '".concat(u,"' is:")},{inlineData:{data:m.toString("base64"),mimeType:C}}]})}}}}}};Se=_([k],Se);import{Type as ni}from"@google/genai";var Re=class extends S{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:ni.OBJECT,properties:{name:{type:ni.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 '".concat(r,"' not found."),error_code:"SKILL_NOT_FOUND"};let s=o.invocationContext.agent.name,a="_adk_activated_skill_".concat(s),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}}};Re=_([k],Re);import{Type as Ne}from"@google/genai";import*as Me from"node:fs/promises";import*as N from"node:path";async function kt(n,e=process.cwd()){let t=N.resolve(e),o=[];for(let r of n){let i=N.resolve(e,r.name);if(!i.startsWith(t))throw new Error("Path traversal detected: ".concat(r.name," resolves outside of ").concat(e));let s=N.extname(i),a=N.dirname(i),c=N.basename(i,s),l=i,u=2;for(;;)try{await Me.access(l);let f="".concat(c,"_").concat(u).concat(s);l=N.join(a,f);let p=N.dirname(r.name);r.name=p==="."?f:N.join(p,f),u++}catch(f){break}if(!l.startsWith(t))throw new Error("Path traversal detected: ".concat(r.name," resolves outside of ").concat(e));await Me.mkdir(N.dirname(l),{recursive:!0}),await Me.writeFile(l,Buffer.from(r.content,r.contentEncoding)),o.push(w(x({},r),{name:N.relative(e,l)}))}return o}var Fe=class extends S{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:Ne.OBJECT,properties:{script_content:{type:Ne.STRING,description:"The content of the script to execute."},language:{type:Ne.STRING,description:"The language/type of the script.",enum:Object.values(he).filter(t=>t!=="unspecified")},args:{anyOf:[{type:Ne.OBJECT},{type:Ne.ARRAY,items:{type:Ne.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;E(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 kt(l.outputFiles),l}catch(l){return{error:"Failed to execute inline script: ".concat(l.message),errorCode:"EXECUTION_ERROR"}}}};Fe=_([k],Fe);import{Type as Lt}from"@google/genai";import*as ro from"node:path";var ia={".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"}},sa={".js":"javascript",".ts":"typescript",".py":"python",".bat":"cmd",".cmd":"cmd",".ps1":"powershell",".sh":"shell"};function oi(n){return ia[n.toLowerCase()]||{mimeType:"application/octet-stream",encoding:"base64"}}function ri(n){return sa[n.toLowerCase()]||"unspecified"}var De=class extends S{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:Lt.OBJECT,properties:{skill_name:{type:Lt.STRING,description:"The name of the skill."},script_path:{type:Lt.STRING,description:"The relative path to the script (e.g., 'scripts/setup.js')."},args:{type:Lt.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,p,m,C;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 '".concat(r,"' not found."),errorCode:"SKILL_NOT_FOUND"};let c=i.startsWith("scripts/")?i.substring(8):i,l=(p=(f=a.resources)==null?void 0:f.scripts)==null?void 0:p[c];if(l||(l=(C=(m=a.resources)==null?void 0:m.scripts)==null?void 0:C[i]),!l)return{error:"Script '".concat(i,"' not found in skill '").concat(r,"'."),errorCode:"SCRIPT_NOT_FOUND"};let u=this.toolset.codeExecutor;if(!u){let v=o.invocationContext.agent;E(v)&&(u=v.codeExecutor)}if(!u)return{error:"No code executor configured.",errorCode:"NO_CODE_EXECUTOR"};try{let v=ri(ro.extname(i)),y=await u.executeCode({invocationContext:o.invocationContext,codeExecutionInput:{code:aa(i,v),inputFiles:ca(a),language:v,args:s}});return y.outputFiles=await kt(y.outputFiles),y}catch(v){return{error:"Failed to execute script '".concat(i,"': ").concat(v.message),errorCode:"EXECUTION_ERROR"}}}};De=_([k],De);function aa(n,e){switch(e){case"javascript":return"require('./".concat(n,"');");case"typescript":return"require('ts-node/register');\nrequire('./".concat(n,"');");case"python":return"import runpy\nrunpy.run_path('./".concat(n,"', run_name='__main__')");case"shell":return"source ./".concat(n,' "$@"');case"powershell":return"& .\\".concat(n.replace(/\//g,"\\\\")," $args");case"cmd":return"call .\\".concat(n.replace(/\//g,"\\\\")," %*");default:throw new Error("Unsupported wrapper language: ".concat(e))}}function ca(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=ro.extname(a).toLowerCase(),{encoding:f,mimeType:p}=oi(u);e.push({name:"".concat(i,"/").concat(a),content:Buffer.from(l).toString(f),contentEncoding:f,mimeType:p})}}return e}var la="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",nt=class extends Be{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 Te(this),new Re(this),new Se(this),new De(this),new Fe(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=_t(r);D(o,[la,i])}async resolveAdditionalTools(t){if(!t)return[];let o=t.agentName,r="_adk_activated_skill_".concat(o),i=t.state.get(r)||[];if(i.length===0)return[];let s="".concat(o,":").concat(i.join(","));if(this.toolCache.has(s))return this.toolCache.get(s);let a=new Set;for(let f of i){let p=this.skills[f];if(p&&p.frontmatter.metadata){let m=p.frontmatter.metadata.adk_additional_tools;m&&m.forEach(C=>a.add(C))}}if(a.size===0)return this.toolCache.set(s,[]),[];let c={};for(let f of this.additionalTools)if(f instanceof S){if(c[f.name])throw new Error("Duplicate tool name: ".concat(f.name));c[f.name]=f}else if(f instanceof Be){let p=await f.getTools(t);for(let m of p){if(c[m.name])throw new Error("Duplicate tool name: ".concat(m.name));c[m.name]=m}}let l=[],u=new Set(this.tools.map(f=>f.name));for(let f of a)if(c[f]){let p=c[f];u.has(p.name)||(l.push(p),u.add(p.name))}return this.toolCache.set(s,l),l}};nt=_([k],nt);export{Pt as ActiveStreamingTool,yt as Agent,Qn as AgentTool,pt as AgentTransferLlmRequestProcessor,_e as ApigeeLlm,Mn as AuthCredentialTypes,Ie as AuthHandler,Nn as AuthProviderRegistry,G as BaseAgent,Ve as BaseCodeExecutor,Vn as BaseExampleProvider,se as BaseLlm,B as BaseLlmRequestProcessor,sn as BaseLlmResponseProcessor,X as BasePlugin,tt as BaseSessionService,S as BaseTool,Be as BaseToolset,We as BuiltInCodeExecutor,Ct as CONTENT_REQUEST_PROCESSOR,he as CodeExecutionLanguage,ht as ContentRequestProcessor,O as Context,yn as ContextCompactionTrigger,Le as ContextCompactorRequestProcessor,q as CredentialExchangeError,qn as CredentialRefresherRegistry,js as EXIT_LOOP,qr as EventType,St as ExitLoopTool,Uo as FeatureName,Bi as FeatureStage,fn as FileContentEncoding,ee as FunctionTool,Vs as GOOGLE_SEARCH,ae as Gemini,at as GoogleLLMVariant,Rt as GoogleSearchTool,Xe as InMemoryArtifactService,Fn as InMemoryCredentialService,xe as InMemoryMemoryService,xt as InMemoryPolicyEngine,Xn as InMemoryRunner,Ee as InMemorySessionService,Z as InvocationContext,me as LLMRegistry,Zs as LOAD_ARTIFACTS,Qs as LOAD_MEMORY,Te as ListSkillsTool,Yt as LiveRequestQueue,yt as LlmAgent,Un as LlmSummarizer,bt as LoadArtifactsTool,It as LoadMemoryTool,Se as LoadSkillResourceTool,Re as LoadSkillTool,So as LogLevel,Kn as LoggingPlugin,no as LongRunningFunctionTool,wn as LoopAgent,je as OAuth2CredentialExchanger,$n as OAuth2DiscoveryManager,$t as OAuthGrantType,ea as PRELOAD_MEMORY,kn as ParallelAgent,et as PluginManager,Vr as PolicyOutcome,wt as PreloadMemoryTool,jr as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,P as ReadonlyContext,Je as RoutedAgent,Qe as RoutedLlm,Ae as Runner,Yn as SecurityPlugin,Bn as SequentialAgent,Dn as SessionStateCredentialService,nt as SkillToolset,b as State,Rn as StreamingMode,Gn as TokenBasedContextCompactor,de as ToolConfirmation,zn as TruncatingContextCompactor,T as createEvent,H as createEventActions,Et as createSession,Si as functionsExportedForTestingOnly,dt as geminiInitParams,Bs as getAskUserConfirmationFunctionCalls,Zt as getFeatureConfig,L as getFunctionCalls,z as getFunctionResponses,Dt as getLogger,mo as hasTrailingCodeExecutionResult,Gs as isAgentTool,yi as isBaseAgent,Ls as isBaseExampleProvider,Jt as isBaseLlm,nn as isBaseTool,zs as isBaseToolset,V as isCompactedEvent,zo as isFeatureEnabled,oe as isFinalResponse,Vi as isFunctionTool,Ke as isGemini2OrAbove,E as isLlmAgent,hs as isLoopAgent,Cs as isParallelAgent,Es as isRoutedAgent,qs as isRunner,As as isSequentialAgent,Hn as mergeStates,Uc as overrideFeatureEnabled,qc as registerFeature,gi as setLogLevel,mi as setLogger,$e as stringifyContent,ks as toStructuredEvents,Ns as trimTempDeltaState,qe as version,Gc as withTemporaryFeatureOverride,ke as zodObjectToSchema};
|
|
9
3
|
/**
|
|
10
4
|
* @license
|
|
11
5
|
* Copyright 2025 Google LLC
|
|
12
6
|
* SPDX-License-Identifier: Apache-2.0
|
|
13
7
|
*/
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
8
|
+
import { AGENT_CARD_PATH, RemoteA2AAgent } from "./a2a/a2a_remote_agent.js";
|
|
9
|
+
import { getA2AAgentCard } from "./a2a/agent_card.js";
|
|
10
|
+
import { A2AAgentExecutor } from "./a2a/agent_executor.js";
|
|
11
|
+
import { toA2a } from "./a2a/agent_to_a2a.js";
|
|
12
|
+
import { InvocationContext } from "./agents/invocation_context.js";
|
|
13
|
+
import { FileArtifactService } from "./artifacts/file_artifact_service.js";
|
|
14
|
+
import { GcsArtifactService } from "./artifacts/gcs_artifact_service.js";
|
|
15
|
+
import { getArtifactServiceFromUri } from "./artifacts/registry.js";
|
|
16
|
+
import {
|
|
17
|
+
AgentEngineSandboxCodeExecutor
|
|
18
|
+
} from "./code_executors/agent_engine_sandbox_code_executor.js";
|
|
19
|
+
import { CodeExecutionLanguage } from "./code_executors/code_execution_utils.js";
|
|
20
|
+
import {
|
|
21
|
+
UnsafeLocalCodeExecutor
|
|
22
|
+
} from "./code_executors/unsafe_local_code_executor.js";
|
|
23
|
+
export * from "./common.js";
|
|
24
|
+
import { DatabaseSessionService } from "./sessions/database_session_service.js";
|
|
25
|
+
import { getSessionServiceFromUri } from "./sessions/registry.js";
|
|
26
|
+
import { VertexAiSessionService } from "./sessions/vertex_ai_session_service.js";
|
|
27
|
+
import {
|
|
28
|
+
loadAllSkillsInDir,
|
|
29
|
+
loadSkillFromDir,
|
|
30
|
+
validateSkillDir
|
|
31
|
+
} from "./skills/loader.js";
|
|
32
|
+
import { RunSkillInlineScriptTool } from "./tools/skill/run_skill_inline_script_tool.js";
|
|
33
|
+
import { RunSkillScriptTool } from "./tools/skill/run_skill_script_tool.js";
|
|
34
|
+
export * from "./integrations/agent_registry/agent_registry.js";
|
|
35
|
+
export * from "./telemetry/google_cloud.js";
|
|
36
|
+
export * from "./telemetry/setup.js";
|
|
37
|
+
export * from "./tools/mcp/mcp_session_manager.js";
|
|
38
|
+
export * from "./tools/mcp/mcp_tool.js";
|
|
39
|
+
export * from "./tools/mcp/mcp_toolset.js";
|
|
40
|
+
export {
|
|
41
|
+
A2AAgentExecutor,
|
|
42
|
+
AGENT_CARD_PATH,
|
|
43
|
+
AgentEngineSandboxCodeExecutor,
|
|
44
|
+
CodeExecutionLanguage,
|
|
45
|
+
DatabaseSessionService,
|
|
46
|
+
FileArtifactService,
|
|
47
|
+
GcsArtifactService,
|
|
48
|
+
InvocationContext,
|
|
49
|
+
RemoteA2AAgent,
|
|
50
|
+
RunSkillInlineScriptTool,
|
|
51
|
+
RunSkillScriptTool,
|
|
52
|
+
UnsafeLocalCodeExecutor,
|
|
53
|
+
VertexAiSessionService,
|
|
54
|
+
getA2AAgentCard,
|
|
55
|
+
getArtifactServiceFromUri,
|
|
56
|
+
getSessionServiceFromUri,
|
|
57
|
+
loadAllSkillsInDir,
|
|
58
|
+
loadSkillFromDir,
|
|
59
|
+
toA2a,
|
|
60
|
+
validateSkillDir
|
|
61
|
+
};
|