@google/adk 0.6.0 → 0.6.1

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/web/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- var Qo=Object.defineProperty,Jo=Object.defineProperties;var Xo=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var dn=Object.prototype.hasOwnProperty,gn=Object.prototype.propertyIsEnumerable;var le=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),er=n=>{throw TypeError(n)};var pn=(n,e,t)=>e in n?Qo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,T=(n,e)=>{for(var t in e||(e={}))dn.call(e,t)&&pn(n,t,e[t]);if(ke)for(var t of ke(e))gn.call(e,t)&&pn(n,t,e[t]);return n},z=(n,e)=>Jo(n,Xo(e));var hn=(n,e)=>{var t={};for(var o in n)dn.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&ke)for(var o of ke(n))e.indexOf(o)<0&&gn.call(n,o)&&(t[o]=n[o]);return t};var m=function(n,e){this[0]=n,this[1]=e},p=(n,e,t)=>{var o=(s,a,c,l)=>{try{var u=t[s](a),f=(a=u.value)instanceof m,d=u.done;Promise.resolve(f?a[0]:a).then(g=>f?o(s==="return"?s:"next",a[1]?{done:g.done,value:g.value}:g,c,l):c({value:g,done:d})).catch(g=>o("throw",g,c,l))}catch(g){l(g)}},r=s=>i[s]=a=>new Promise((c,l)=>o(s,a,c,l)),i={};return t=t.apply(n,e),i[le("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i},q=n=>{var e=n[le("asyncIterator")],t=!1,o,r={};return e==null?(e=n[le("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 m(new Promise(a=>{var c=e[i](s);c instanceof Object||er("Object expected"),a(c)}),1)}}),r[le("iterator")]=()=>r,o("next"),"throw"in e?o("throw"):r.throw=i=>{throw i},"return"in e&&o("return"),r},y=(n,e,t)=>(e=n[le("asyncIterator")])?e.call(n):(n=n[le("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 Xe=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};import{context as _n,trace as Pn}from"@opentelemetry/api";function V(n={}){return T({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},n)}function Cn(n,e){let t=V();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 E(n={}){return z(T({},n),{id:n.id||et(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||V(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()})}function H(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:_(n).length===0&&N(n).length===0&&!n.partial&&!xn(n)}function _(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionCall&&e.push(t.functionCall);return e}function N(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 xn(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 Ce(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 vn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function et(){let n="";for(let e=0;e<8;e++)n+=vn[Math.floor(Math.random()*vn.length)];return n}import{context as tt,trace as Ee}from"@opentelemetry/api";var ve="0.6.0";var tr="gen_ai.agent.description",nr="gen_ai.agent.name",or="gen_ai.conversation.id",nt="gen_ai.operation.name",yn="gen_ai.tool.call.id",En="gen_ai.tool.description",An="gen_ai.tool.name",rr="gen_ai.tool.type",j=Ee.getTracer("gcp.vertex.agent",ve);function xe(n){try{return JSON.stringify(n)}catch(e){return"<not serializable>"}}function Tn({agent:n,invocationContext:e}){let t=Ee.getActiveSpan();t&&t.setAttributes({[nt]:"invoke_agent",[tr]:n.description,[nr]:n.name,[or]:e.session.id})}function Sn({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=Ee.getActiveSpan();if(!o)return;o.setAttributes({[nt]:"execute_tool",[En]:n.description||"",[An]:n.name,[rr]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":ye()?xe(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({[yn]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":ye()?xe(i):"{}"})}function Rn({responseEventId:n,functionResponseEvent:e}){let t=Ee.getActiveSpan();t&&(t.setAttributes({[nt]:"execute_tool",[An]:"(merged tools)",[En]:"(merged tools)",[yn]: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",ye()?xe(e):"{}"))}function bn({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=Ee.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":ye()?xe(ir(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",ye()?xe(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 ir(n){let e={model:n.model,contents:[]};if(n.config){let t=n.config,{responseSchema:o}=t,r=hn(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 In(n,e){return{next:tt.bind(n,e.next.bind(e)),return:tt.bind(n,e.return.bind(e)),throw:tt.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return In(n,e[Symbol.asyncIterator]())}}}function J(n,e,t){let o=t.call(e);return In(n,o)}function ye(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var Ae=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,o;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((o=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&o.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".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(){return this.authConfig.rawAuthCredential}};var S=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 T(T({},this.value),this.delta)}};S.APP_PREFIX="app:",S.USER_PREFIX="user:",S.TEMP_PREFIX="temp:";var X=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var k=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 S(this.invocationContext.session.state,{})}};var O=class extends k{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||V(),this._state=new S(e.invocationContext.session.state,this.eventActions.stateDelta),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get state(){return this._state}get actions(){return this.eventActions}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let o=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=o,o}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Ae(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ae(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new X({hint:e,confirmed:!1,payload:t})}};function G(){return typeof window<"u"}var Oe="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ue(){let n="";for(let e=0;e<Oe.length;e++){let t=Math.random()*16|0;Oe[e]==="x"?n+=t.toString(16):Oe[e]==="y"?n+=(t&3|8).toString(16):n+=Oe[e]}return n}function wn(n){return G()?window.atob(n):Buffer.from(n,"base64").toString()}function Me(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var ot=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},K=class{constructor(e){this.invocationCostManager=new ot;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function Ln(){return"e-".concat(ue())}var rt=Symbol.for("google.adk.baseAgent");function sr(n){return typeof n=="object"&&n!==null&&rt in n&&n[rt]===!0}var On;On=rt;var $=class{constructor(e){this[On]=!0;this.name=ar(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=kn(e.beforeAgentCallback),this.afterAgentCallback=kn(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return lr(this)}runAsync(e){return p(this,null,function*(){let t=j.startSpan("invoke_agent ".concat(this.name)),o=Pn.setSpan(_n.active(),t);try{yield*q(J(o,this,function(){return p(this,null,function*(){let r=this.createInvocationContext(e),i=yield new m(this.handleBeforeAgentCallback(r));if(i&&(yield i),r.endInvocation)return;Tn({agent:this,invocationContext:r});try{for(var a=y(this.runAsyncImpl(r)),c,l,u;c=!(l=yield new m(a.next())).done;c=!1){let f=l.value;yield f}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new m(l.call(a)))}finally{if(u)throw u[0]}}if(r.endInvocation)return;let s=yield new m(this.handleAfterAgentCallback(r));s&&(yield s)})}))}finally{t.end()}})}runLive(e){return p(this,null,function*(){let t=j.startSpan("invoke_agent ".concat(this.name)),o=Pn.setSpan(_n.active(),t);try{throw yield*q(J(o,this,function(){return p(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 K(z(T({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new O({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new O({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({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 ar(n){if(!cr(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 cr(n){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_-]*$","u").test(n)}function lr(n){for(;n.parentAgent;)n=n.parentAgent;return n}function kn(n){return n?Array.isArray(n)?n:[n]:[]}import{createUserContent as mr}from"@google/genai";import{isEmpty as Bn}from"lodash-es";import*as U from"winston";var Mn=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Mn||{}),it=class{constructor(){this.logLevel=1;this.logger=U.createLogger({levels:{debug:0,info:1,warn:2,error:3},level:"error",format:U.format.combine(U.format.label({label:"ADK"}),U.format(e=>(e.level=e.level.toUpperCase(),e))(),U.format.colorize(),U.format.timestamp(),U.format.printf(e=>"".concat(e.level,": [").concat(e.label,"] ").concat(e.timestamp," ").concat(e.message))),transports:[new U.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(" "))}},st=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},W=new it;function ur(n){W=n!=null?n:new st}function at(){return W}function fr(n){C.setLogLevel(n)}var C={setLogLevel(n){W.setLogLevel(n)},log(n,...e){W.log(n,...e)},debug(...n){W.debug(...n)},info(...n){W.info(...n)},warn(...n){W.warn(...n)},error(...n){W.error(...n)}};var ct="adk-",Be="adk_request_credential",fe="adk_request_confirmation",pr={handleFunctionCallList:Ne,generateAuthEvent:ut,generateRequestConfirmationEvent:ft};function lt(){return"".concat(ct).concat(ue())}function Nn(n){let e=_(n);if(e)for(let t of e)t.id||(t.id=lt())}function Fn(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(ct)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(ct)&&(e.functionResponse.id=void 0)}function Dn(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 ut(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||Bn(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:Be,args:{function_call_id:i,auth_config:s},id:lt()};o.add(a.id),t.push({functionCall:a})}return E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function ft({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||Bn(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=_(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!u)continue;let f={name:fe,args:{originalFunctionCall:u,toolConfirmation:l},id:lt()};r.add(f.id),o.push({functionCall:f})}return E({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 dr(n,e,t){return j.startActiveSpan("execute_tool ".concat(n.name),async o=>{try{C.debug("callToolAsync ".concat(n.name));let r=await n.runAsync({args:e,toolContext:t});return Sn({tool:n,args:e,functionResponseEvent:gr(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function gr(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 E({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function qn({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=_(e);return await Ne({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ne({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let d;s&&f.id&&(d=s[f.id]);let{tool:g,toolContext:h}=hr({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:d});C.debug("execute_tool ".concat(g.name));let x=(u=f.args)!=null?u:{},v=null,R;if(v=await n.pluginManager.runBeforeToolCallback({tool:g,toolArgs:x,toolContext:h}),v==null){for(let I of o)if(v=await I({tool:g,args:x,context:h}),v)break}if(v==null)try{v=await dr(g,x,h)}catch(I){if(I instanceof Error){let w=await n.pluginManager.runOnToolErrorCallback({tool:g,toolArgs:x,toolContext:h,error:I});w?v=w:R=I.message}else R=I}let b=await n.pluginManager.runAfterToolCallback({tool:g,toolArgs:x,toolContext:h,result:v});if(b==null){for(let I of r)if(b=await I({tool:g,args:x,context:h,response:v}),b)break}if(b!=null&&(v=b),g.isLongRunning&&!v)continue;R?v={error:R}:(typeof v!="object"||v==null)&&(v={result:v});let L=E({invocationId:n.invocationId,author:n.agent.name,content:mr({functionResponse:{id:h.functionCallId,name:g.name,response:v}}),actions:h.actions,branch:n.branch});C.debug("traceToolCall",{tool:g.name,args:x,functionResponseEvent:L.id}),a.push(L)}if(!a.length)return null;let l=Cr(a);return a.length>1&&j.startActiveSpan("execute_tool (merged)",f=>{try{C.debug("execute_tool (merged)"),C.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),Rn({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function hr({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 Cr(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=Cn(o);return E({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var mt=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 p(this,null,function*(){for(;;){let e=yield new m(this.get());if(yield e,e.close)break}})}};import{context as ni,trace as oi}from"@opentelemetry/api";var vr="google-adk",xr="gl-typescript",yr="remote_reasoning_engine",Er="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Ar(){let n="".concat(vr,"/").concat(ve);!G()&&process.env[Er]&&(n="".concat(n,"+").concat(yr));let e="".concat(xr,"/").concat(G()?window.navigator.userAgent:process.version);return[n,e]}function Gn(){return Ar()}var pt=Symbol.for("google.adk.baseModel");function dt(n){return typeof n=="object"&&n!==null&&pt in n&&n[pt]===!0}var $n;$n=pt;var me=class{constructor({model:e}){this[$n]=!0;this.model=e}get trackingHeaders(){let t=Gn().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};me.supportedModels=[];import{createPartFromText as zn,FinishReason as Tr,GoogleGenAI as ht}from"@google/genai";var Fe=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Fe||{});function Un(){return Me("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}var De=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"}):C.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);C.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else C.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){C.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return p(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function gt(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 Z=class extends me{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=qe({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){return p(this,null,function*(){var o,r,i,s,f,d,g;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),C.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(o=e.config)!=null&&o.httpOptions&&(e.config.httpOptions.headers=T(T({},e.config.httpOptions.headers),this.trackingHeaders)),t){let h=yield new m(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),x="",v="",R,b;try{for(var a=y(h),c,l,u;c=!(l=yield new m(a.next())).done;c=!1){let L=l.value;b=L;let I=gt(L);R=I.usageMetadata;let w=(s=(i=I.content)==null?void 0:i.parts)==null?void 0:s[0];if(w!=null&&w.text)"thought"in w&&w.thought?x+=w.text:v+=w.text,I.partial=!0;else if((x||v)&&(!w||!w.inlineData)){let Q=[];x&&Q.push({text:x,thought:!0}),v&&Q.push(zn(v)),yield{content:{role:"model",parts:Q},usageMetadata:I.usageMetadata},x="",v=""}yield I}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new m(l.call(a)))}finally{if(u)throw u[0]}}if((v||x)&&((d=(f=b==null?void 0:b.candidates)==null?void 0:f[0])==null?void 0:d.finishReason)===Tr.STOP){let L=[];x&&L.push({text:x,thought:!0}),v&&L.push({text:v}),yield{content:{role:"model",parts:L},usageMetadata:R}}}else{let h=yield new m(this.apiClient.models.generateContent({model:(g=e.model)!=null?g:this.model,contents:e.contents,config:e.config}));yield gt(h)}})}getHttpOptions(){return{headers:T(T({},this.trackingHeaders),this.headers)}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new ht({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new ht({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 ht({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:[zn(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 De(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)Vn(o.inlineData),Vn(o.fileData)}}};Z.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Vn(n){n&&n.displayName&&(n.displayName=void 0)}function qe({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&&!G()&&(i.vertexai=Me("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!G()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!G()&&!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&&!G()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var jn="APIGEE_PROXY_URL",pe=class extends Z{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!Yn(e))throw new Error("Model ".concat(e," is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>"));if(super(z(T({},Sr({model:e,vertexai:r,project:s,location:i,apiKey:o})),{headers:a})),this.proxyUrl=t!=null?t:"",!G()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[jn])!=null?c:""),!this.proxyUrl)throw new Error("Proxy URL must be provided via the constructor or ".concat(jn," 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){return p(this,null,function*(){var r;let o=(r=e.model)!=null?r:this.model;e.model=Kn(o),yield*q(super.generateContentAsync(e,t))})}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=Kn(t),super.connect(e)}};pe.supportedModels=[/apigee\/.*/];function Sr({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=qe({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||(C.warn('No API key provided when using a Gemini model, using a fake key "-".'),i.apiKey="-"),i}function Kn(n){if(!Yn(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 Yn(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 Ct=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},F=class F{static newLlm(e){return new(F.resolve(e))({model:e})}static _register(e,t){F.llmRegistryDict.has(e)&&C.info("Updating LLM class for ".concat(e," from ").concat(F.llmRegistryDict.get(e)," to ").concat(t)),F.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)F._register(t,e)}static resolve(e){let t=F.resolveCache.get(e);if(t)return t;for(let[o,r]of F.llmRegistryDict.entries())if(new RegExp("^".concat(o instanceof RegExp?o.source:o,"$"),o instanceof RegExp?o.flags:void 0).test(e))return F.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};F.llmRegistryDict=new Map,F.resolveCache=new Ct(32);var ee=F;ee.register(Z);ee.register(pe);var vt=Symbol.for("google.adk.baseTool");function xt(n){return typeof n=="object"&&n!==null&&vt in n&&n[vt]===!0}var Hn;Hn=vt;var P=class{constructor(e){this[Hn]=!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=Rr(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 Un()}};function Rr(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Wn}from"@google/genai";import{zodToJsonSchema as br}from"zod-to-json-schema";import{toJSONSchema as Ir}from"zod/v4";function yt(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function wr(n){return yt(n)&&!("_zod"in n)}function Lr(n){return yt(n)&&"_zod"in n}function _r(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 te(n){return yt(n)&&_r(n)==="ZodObject"}function de(n){if(!te(n))throw new Error("Expected a Zod Object");if(Lr(n))return Ir(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=Wn.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(wr(n))return br(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=Wn.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 Xn}from"zod";function B(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 Zn(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}import{Type as Pr}from"@google/genai";function kr(n){return n===void 0?{type:Pr.OBJECT,properties:{}}:te(n)?de(n):n}var Et=Symbol.for("google.adk.functionTool");function Or(n){return typeof n=="object"&&n!==null&&Et in n&&n[Et]===!0}var Qn,Jn,Y=class extends(Jn=P,Qn=Et,Jn){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[Qn]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:kr(this.parameters)}}async runAsync(t){try{let o=t.args;return te(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 M=class{},At=class{};var Tt=class extends M{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new Y({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:Xn.object({agentName:Xn.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 p(this,null,function*(){if(!A(t.agent))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;B(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new O({invocationContext:t});yield new m(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||!A(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},eo=new Tt;var St=class extends M{runAsync(e,t){return p(this,null,function*(){var r;let o=e.agent;A(o)&&(t.model=o.canonicalModel.model,t.config=T({},(r=o.generateContentConfig)!=null?r:{}),o.outputSchema&&Zn(t,o.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},to=new St;import{cloneDeep as fo}from"lodash-es";var Rt=Symbol.for("google.adk.baseCodeExecutor");function Ge(n){return typeof n=="object"&&n!==null&&Rt in n&&n[Rt]===!0}var no;no=Rt;var Te=class{constructor(){this[no]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Mr="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function bt(n){let e=n.match(Mr);return e?e[1]:n}function oo(n){return bt(n).startsWith("gemini-")}function Br(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 ro(n){return bt(n).startsWith("gemini-1")}function Se(n){if(!n)return!1;let e=bt(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Br(t);return o.valid&&o.major>=2}var It=Symbol.for("google.adk.builtInCodeExecutor");function be(n){return typeof n=="object"&&n!==null&&It in n&&n[It]===!0}var io,so,Re=class extends(so=Te,io=It,so){constructor(){super(...arguments);this[io]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&Se(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 Nr,Outcome as ao}from"@google/genai";import{cloneDeep as Fr}from"lodash-es";function co(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let d=n.parts[f];if(d.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),d.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=Fr(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(wt(l)),l):""}function wt(n){return{text:n,executableCode:{code:n,language:Nr.PYTHON}}}function lo(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:ao.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:ao.OUTCOME_OK}}}function uo(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 Dr}from"lodash-es";var Lt="_code_execution_context",_t="execution_session_id",ne="processed_input_files",oe="_code_executor_input_files",re="_code_executor_error_counts",Pt="_code_execution_results",Ie=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Lt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Lt]:Dr(this.context)}}getExecutionId(){if(_t in this.context)return this.context[_t]}setExecutionId(e){this.context[_t]=e}getProcessedFileNames(){return ne in this.context?this.context[ne]:[]}addProcessedFileNames(e){ne in this.context||(this.context[ne]=[]),this.context[ne].push(...e)}getInputFiles(){return oe in this.sessionState?this.sessionState.get(oe):[]}addInputFiles(e){oe in this.sessionState||this.sessionState.set(oe,[]),this.sessionState.get(oe).push(...e)}clearInputFiles(){oe in this.sessionState&&this.sessionState.set(oe,[]),ne in this.context&&(this.context[ne]=[])}getErrorCount(e){return re in this.sessionState&&this.sessionState.get(re)[e]||0}incrementErrorCount(e){re in this.sessionState||this.sessionState.set(re,{}),this.sessionState.get(re)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(re in this.sessionState))return;let t=this.sessionState.get(re);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){Pt in this.sessionState||this.sessionState.set(Pt,{});let i=this.sessionState.get(Pt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(Lt)||{}}};var kt=class extends M{runAsync(e,t){return p(this,null,function*(){if(A(e.agent)&&e.agent.codeExecutor){try{for(var o=y(Gr(e,t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}if(Ge(e.agent.codeExecutor))for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];uo(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},$e={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},qr="\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",Ot=class{runAsync(e,t){return p(this,null,function*(){if(!t.partial)try{for(var o=y($r(e,t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}})}},$c=new Ot;function Gr(n,e){return p(this,null,function*(){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!Ge(o))return;if(be(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new Ie(new S(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=Ur(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=zr(c);if(!l)return;let u={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},wt(l)]};e.contents.push(fo(u)),yield E({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=mo(n,r),d=yield new m(o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([c.name]);let g=yield new m(po(n,r,d));yield g,e.contents.push(fo(g.content))}})}function $r(n,e){return p(this,null,function*(){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!Ge(o)||!e||!e.content||be(o))return;let r=new Ie(new S(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=co(i,o.codeBlockDelimiters);if(!s)return;yield E({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=mo(n,r),c=yield new m(o.executeCode({invocationContext:n,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield yield new m(po(n,r,c)),e.content=void 0})}function Ur(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||!$e[l])continue;let u="data_".concat(i+1,"_").concat(a+1).concat($e[l].extension);c.text="\nAvailable file: `".concat(u,"`\n");let f={name:u,content:wn(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function mo(n,e){var r;let t=n.agent;if(!A(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function po(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[lo(t)]},r=V({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 E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function zr(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!$e[n.mimeType])return;let t=e(n.name),o=$e[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return"\n".concat(qr,"\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 go=new kt;function D(n){return"isCompacted"in n&&n.isCompacted===!0}function ho(n={}){return z(T({},E(n)),{isCompacted:n.isCompacted||!0,startTime:n.startTime,endTime:n.endTime,compactedContent:n.compactedContent})}import{createUserContent as Vr}from"@google/genai";import{cloneDeep as jr}from"lodash-es";function Mt(n,e,t){var s,a,c;let o=[];for(let l of n){if(D(l)){o.push(Qr(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)||Kr(l)||Yr(l)||o.push(xo(e,l)?Hr(l):l)}let r=Wr(o);r=Zr(r);let i=[];for(let l of r){let u=jr(l.content);Fn(u),i.push(u)}return i}function vo(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||xo(e,r))return Mt(n.slice(o),e,t)}return[]}function Kr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Be||((o=r.functionResponse)==null?void 0:o.name)===Be)return!0;return!1}function Yr(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)===fe||((o=r.functionResponse)==null?void 0:o.name)===fe)return!0;return!1}function xo(n,e){return!!n&&e.author!==n&&e.author!=="user"}function Hr(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=Co(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=Co(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 E({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function yo(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=E(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 Wr(n){if(n.length===0)return n;let e=n[n.length-1],t=N(e);if(!(t!=null&&t.length))return n;let o=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=n.at(-2);if(r){let c=_(r);if(c){for(let l of c)if(l.id&&o.has(l.id))return n}}let i=-1;for(let c=n.length-2;c>=0;c--){let l=n[c],u=_(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let d=new Set(u.map(h=>h.id).filter(h=>!!h));if(!Array.from(o).every(h=>d.has(h)))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(d).join(", "),", function response")+" ids provided: ".concat(Array.from(o).join(", ")));o=d;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=N(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(yo(s)),a}function Zr(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=N(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(N(o).length>0)continue;let r=_(o);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(o),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(n[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>n[c]);t.push(yo(a))}}else t.push(o)}return t}function Co(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch(e){return String(n)}}function Qr(n){let e=Vr("[Previous Context Summary]:\n".concat(n.compactedContent));return E({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}var Ue=class{runAsync(e,t){return p(this,null,function*(){let o=e.agent;if(!o||!A(o))return;let r=e.session.events,i=r.filter(D),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||D(c)||c.timestamp<=s.endTime));r=[s,...a]}o.includeContents==="default"?t.contents=Mt(r,o.name,e.branch):t.contents=vo(r,o.name,e.branch)})}},ze=new Ue;var ge=class{constructor(e){this.compactors=e}runAsync(e,t){return p(this,null,function*(){for(let o of this.compactors)if(yield new m(Promise.resolve(o.shouldCompact(e)))){let i=new Set(e.session.events);yield new m(Promise.resolve(o.compact(e)));let s=e.session.events.filter(a=>!i.has(a));for(let a of s)yield a;return}})}};var Bt=class extends M{runAsync(e,t){return p(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,'"')),B(t,r)})}},Eo=new Bt;async function Nt(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!d)throw new Error("Artifact ".concat(f," not found."));return String(d)}if(!ei(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 Jr=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ao(n){return n===""||n===void 0?!1:Jr.test(n)}var Xr=[S.APP_PREFIX,S.USER_PREFIX,S.TEMP_PREFIX];function ei(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?Ao(n):Xr.includes(e[0]+":")?Ao(e[1]):!1}var Ft=class extends M{runAsync(e,t){return p(this,null,function*(){let o=e.agent;if(!A(o))return;let r=o.rootAgent;if(A(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new m(r.canonicalGlobalInstruction(new k(e))),a=i;s&&(a=yield new m(Nt(i,new k(e)))),B(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=yield new m(o.canonicalInstruction(new k(e))),a=i;s&&(a=yield new m(Nt(i,new k(e)))),B(t,[a])}})}},To=new Ft;var Dt=class extends M{runAsync(e){return p(this,null,function*(){let t=e.agent;if(!A(t))return;let o=e.session.events;if(!o||o.length===0)return;let r={},i=-1;for(let s=o.length-1;s>=0;s--){let a=o[s];if(a.author!=="user")continue;let c=N(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==fe)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 X({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(r[u.id]=f)}if(l){i=s;break}}if(Object.keys(r).length!==0)for(let s=i-1;s>=0;s--){let a=o[s],c=_(a);if(!c)continue;let l={},u={};for(let h of c){if(!h.id||!(h.id in r))continue;let x=h.args;if(!x||!("originalFunctionCall"in x))continue;let v=x.originalFunctionCall;v.id&&(l[v.id]=r[h.id],u[v.id]=v)}if(Object.keys(l).length===0)continue;for(let h=o.length-1;h>i;h--){let x=o[h],v=N(x);if(v){for(let R of v)R.id&&R.id in l&&(delete l[R.id],delete u[R.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=yield new m(t.canonicalTools(new k(e))),d=Object.fromEntries(f.map(h=>[h.name,h])),g=yield new m(Ne({invocationContext:e,functionCalls:Object.values(u),toolsDict:d,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l}));g&&(yield g);return}})}},So=new Dt;var qt=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(qt||{});function Ro(n={}){return T({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ti(n.maxLlmCalls||500),pauseOnToolCalls:!1},n)}function ti(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return n<=0&&C.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 bo="adk_agent_name";async function Io(n,e){return xt(n)?[n]:await n.getTools(e)}var Gt=Symbol.for("google.adk.llmAgent");function A(n){return typeof n=="object"&&n!==null&&Gt in n&&n[Gt]===!0}var wo,Lo,$t=class n extends(Lo=$,wo=Gt,Lo){constructor(t){var r,i,s,a,c,l,u,f,d;super(t);this[wo]=!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=te(t.inputSchema)?de(t.inputSchema):t.inputSchema,this.outputSchema=te(t.outputSchema)?de(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:[to,Eo,To,So,ze,go],!t.requestProcessors&&t.contextCompactors&&t.contextCompactors.length>0){let g=this.requestProcessors.indexOf(ze);g!==-1?this.requestProcessors.splice(g,0,new ge(t.contextCompactors)):this.requestProcessors.push(new ge(t.contextCompactors))}if(this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(eo),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)&&(C.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(dt(this.model))return this.model;if(typeof this.model=="string"&&this.model)return ee.newLlm(this.model);let t=this.parentAgent;for(;t;){if(A(t))return t.canonicalModel;t=t.parentAgent}throw new Error("No model found for ".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 Io(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){C.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(t.author));return}if(!this.outputKey){C.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!H(t)){C.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)){C.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){C.error("Error parsing output for agent ".concat(this.name),a)}}t.actions.stateDelta[this.outputKey]=r}runAsyncImpl(t){return p(this,null,function*(){for(;;){let a;try{for(var o=y(this.runOneStepAsync(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let c=i.value;a=c,this.maybeSaveOutputToState(c),yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}if(!a||H(a))break;if(a.partial){C.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(t){return p(this,null,function*(){try{for(var o=y(this.runLiveFlow(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let a=i.value;this.maybeSaveOutputToState(a),yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}t.endInvocation})}runLiveFlow(t){return p(this,null,function*(){throw yield new m(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(t){return p(this,null,function*(){let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let f of this.requestProcessors)try{for(var a=y(f.runAsync(t,o)),c,l,u;c=!(l=yield new m(a.next())).done;c=!1){let d=l.value;yield d}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new m(l.call(a)))}finally{if(u)throw u[0]}}for(let f of this.tools){let d=new O({invocationContext:t}),g=yield new m(Io(f,new k(t)));for(let h of g)yield new m(h.processLlmRequest({toolContext:d,llmRequest:o}))}if(t.endInvocation)return;let r=E({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=j.startSpan("call_llm"),s=oi.setSpan(ni.active(),i);yield*q(J(s,this,function(){return p(this,null,function*(){let f=function(){return p(this,null,function*(){try{for(var v=y(this.callLlmAsync(t,o,r)),R,b,L;R=!(b=yield new m(v.next())).done;R=!1){let I=b.value;try{for(var d=y(this.postprocess(t,o,I,r)),g,h,x;g=!(h=yield new m(d.next())).done;g=!1){let w=h.value;r.id=et(),r.timestamp=new Date().getTime(),yield w}}catch(h){x=[h]}finally{try{g&&(h=d.return)&&(yield new m(h.call(d)))}finally{if(x)throw x[0]}}}}catch(b){L=[b]}finally{try{R&&(b=v.return)&&(yield new m(b.call(v)))}finally{if(L)throw L[0]}}})};yield*q(this.runAndHandleError(f.call(this),t,o,r))})})),i.end()})}postprocess(t,o,r,i){return p(this,null,function*(){var x,v;for(let w of this.responseProcessors)try{for(var f=y(w.runAsync(t,r)),d,g,h;d=!(g=yield new m(f.next())).done;d=!1){let Q=g.value;yield Q}}catch(g){h=[g]}finally{try{d&&(g=f.return)&&(yield new m(g.call(f)))}finally{if(h)throw h[0]}}if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=E(T(T({},i),r));if(s.content){let w=_(s);w!=null&&w.length&&(Nn(s),s.longRunningToolIds=Array.from(Dn(w,o.toolsDict)))}if(yield s,!((x=_(s))!=null&&x.length))return;if((v=t.runConfig)!=null&&v.pauseOnToolCalls){t.endInvocation=!0;return}let a=yield new m(qn({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!a)return;let c=ut(t,a);c&&(yield c);let l=ft({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let w=this.getAgentByName(t,u);try{for(var R=y(w.runAsync(t)),b,L,I;b=!(L=yield new m(R.next())).done;b=!1){let Q=L.value;yield Q}}catch(L){I=[L]}finally{try{b&&(L=R.return)&&(yield new m(L.call(R)))}finally{if(I)throw I[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 p(this,null,function*(){var a,c,l,u,f;let i=yield new m(this.handleBeforeModelCallback(t,o,r));if(i){yield i;return}(a=o.config)!=null||(o.config={}),(l=(c=o.config).labels)!=null||(c.labels={}),o.config.labels[bo]||(o.config.labels[bo]=this.name);let s=this.canonicalModel;if((u=t.runConfig)!=null&&u.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let v=s.generateContentAsync(o,((f=t.runConfig)==null?void 0:f.streamingMode)==="sse");try{for(var d=y(v),g,h,x;g=!(h=yield new m(d.next())).done;g=!1){let R=h.value;bn({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:R});let b=yield new m(this.handleAfterModelCallback(t,R,r));yield b!=null?b:R}}catch(h){x=[h]}finally{try{g&&(h=d.return)&&(yield new m(h.call(d)))}finally{if(x)throw x[0]}}}})}async handleBeforeModelCallback(t,o,r){let i=new O({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:o});if(c)return c}}async handleAfterModelCallback(t,o,r){let i=new O({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:o});if(c)return c}}runAndHandleError(t,o,r,i){return p(this,null,function*(){try{try{for(var s=y(t),a,c,l;a=!(c=yield new m(s.next())).done;a=!1){let u=c.value;yield u}}catch(c){l=[c]}finally{try{a&&(c=s.return)&&(yield new m(c.call(s)))}finally{if(l)throw l[0]}}}catch(u){let f=new O({invocationContext:o,eventActions:i.actions});if(u instanceof Error){let d=yield new m(o.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:r,error:u}));if(d)yield d;else{let g="UNKNOWN_ERROR",h=u.message;try{let x=JSON.parse(u.message);x!=null&&x.error&&(g=String(x.error.code||"UNKNOWN_ERROR"),h=x.error.message||h)}catch(x){}i.actions?yield E({invocationId:o.invocationId,author:this.name,errorCode:g,errorMessage:h}):yield{errorCode:g,errorMessage:h}}}else throw C.error("Unknown error during response generation",u),u}})}};var Ut=Symbol.for("google.adk.loopAgent");function ri(n){return typeof n=="object"&&n!==null&&Ut in n&&n[Ut]===!0}var _o,Po,zt=class extends(Po=$,_o=Ut,Po){constructor(t){var o;super(t);this[_o]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}runAsyncImpl(t){return p(this,null,function*(){let o=0;for(;o<this.maxIterations;){for(let c of this.subAgents){let l=!1;try{for(var r=y(c.runAsync(t)),i,s,a;i=!(s=yield new m(r.next())).done;i=!1){let u=s.value;yield u,u.actions.escalate&&(l=!0)}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new m(s.call(r)))}finally{if(a)throw a[0]}}if(l)return}o++}})}runLiveImpl(t){return p(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var Vt=Symbol.for("google.adk.parallelAgent");function ii(n){return typeof n=="object"&&n!==null&&Vt in n&&n[Vt]===!0}var ko,Oo,jt=class extends(Oo=$,ko=Vt,Oo){constructor(){super(...arguments);this[ko]=!0}runAsyncImpl(t){return p(this,null,function*(){let o=this.subAgents.map(c=>c.runAsync(si(this,c,t)));try{for(var r=y(ai(o)),i,s,a;i=!(s=yield new m(r.next())).done;i=!1){let c=s.value;yield c}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new m(s.call(r)))}finally{if(a)throw a[0]}}})}runLiveImpl(t){return p(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function si(n,e,t){let o=new K(t),r="".concat(n.name,".").concat(e.name);return o.branch=o.branch?"".concat(o.branch,".").concat(r):r,o}function ai(n){return p(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 m(Promise.race(e.values()));if(t.done){e.delete(o);continue}yield t.value;let r=n[o].next().then(i=>({result:i,index:o}));e.set(o,r)}})}var Kt="task_completed",Yt=Symbol.for("google.adk.sequentialAgent");function ci(n){return typeof n=="object"&&n!==null&&Yt in n&&n[Yt]===!0}var Mo,Bo,Ht=class extends(Bo=$,Mo=Yt,Bo){constructor(){super(...arguments);this[Mo]=!0}runAsyncImpl(t){return p(this,null,function*(){for(let a of this.subAgents)try{for(var o=y(a.runAsync(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}})}runLiveImpl(t){return p(this,null,function*(){for(let a of this.subAgents)A(a)&&((yield new m(a.canonicalTools(new k(t)))).some(u=>u.name===Kt)||(a.tools.push(new Y({name:Kt,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(Kt," 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=y(a.runLive(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}})}};var we=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=he(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=he(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=he(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=he(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=he(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=he(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 he(n,e,t,o){return li(o)?"".concat(n,"/").concat(e,"/user/").concat(o):"".concat(n,"/").concat(e,"/").concat(t,"/").concat(o)}function li(n){return n.startsWith("user:")}var No=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(No||{});var ui="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.",Wt=class{constructor(e){this.llm=e.llm,this.prompt=e.prompt||ui}async summarize(e){var u,f,d,g,h,x;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 I=0;I<e.length;I++)r+="[Event ".concat(I+1," - Author: ").concat(e[I].author,"]\n"),r+="".concat(Ce(e[I]),"\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||!((d=(f=(u=l.value.content)==null?void 0:u.parts)==null?void 0:f[0])!=null&&d.text))throw new Error("LLM failed to return a valid summary.");c+=l.value.content.parts[0].text;try{for(var v=y(a),R,b,L;R=!(b=await v.next()).done;R=!1){let I=b.value;(x=(h=(g=I.content)==null?void 0:g.parts)==null?void 0:h[0])!=null&&x.text&&(c+=I.content.parts[0].text)}}catch(b){L=[b]}finally{try{R&&(b=v.return)&&await b.call(v)}finally{if(L)throw L[0]}}return ho({author:"system",content:{role:"model",parts:[{text:c}]},startTime:t,endTime:o,compactedContent:c})}};var Zt=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];D(i)&&(!t||i.endTime>t.endTime)&&(t=i)}if(!t)return e;let o=e.filter(r=>!D(r)&&r.timestamp>t.endTime);return[t,...o]}shouldCompact(e){let t=e.session.events,o=this.getActiveEvents(t);if(o.filter(s=>!D(s)).length<=this.eventRetentionSize)return!1;let i=0;for(let s of o)i+=fi(s);return i>this.tokenThreshold}async compact(e){let t=e.session.events,o=this.getActiveEvents(t),r=o.filter(u=>!D(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(pi(u)&&mi(f))i--;else break}if(i===0)return;let s=r.slice(0,i),a=o.find(D),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 fi(n){var t;if(((t=n.usageMetadata)==null?void 0:t.promptTokenCount)!==void 0)return n.usageMetadata.promptTokenCount;let e=Ce(n);return Math.ceil(e.length/4)}function mi(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionCall!==void 0))}function pi(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionResponse!==void 0))}var Qt=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 Le}from"lodash-es";var Fo=(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))(Fo||{});function di(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&&!Le(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!Le(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!Le(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!Le(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&&!Le(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),H(n)&&e.push({type:"finished",output:void 0}),e}var Jt=Symbol.for("google.adk.baseExampleProvider");function gi(n){return typeof n=="object"&&n!==null&&Jt in n&&n[Jt]===!0}var Do;Do=Jt;var Xt=class{constructor(){this[Do]=!0}};var ie=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=qo(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=qo(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),u=hi(l);if(!u.size)continue;o.some(d=>u.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:Ci(c.timestamp)})}return r}};function qo(n,e){return"".concat(n,"/").concat(e)}function hi(n){return new Set([...n.matchAll(/[A-Za-z]+/g)].map(e=>e[0].toLowerCase()))}function Ci(n){return new Date(n).toISOString()}var se=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var en=class extends se{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(H(e)));let t=_(e);if(t.length>0){let r=t.map(i=>i.name);this.log(" Function Calls: ".concat(r))}let o=N(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");C.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 _e=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),C.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 C.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 C.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:o}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:o}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:o}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:o}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,o=>o.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,o=>o.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}),"onToolErrorCallback")}};var $o="adk_request_confirmation",tn="orcas_tool_call_security_check_states",Go="This tool call needs external confirmation before completion.",Uo=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(Uo||{}),Ve=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},nn=class extends se{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ve}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:Go};if(this.setToolCallCheckState(o,o.toolConfirmation),!o.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};o.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(tn))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(tn))!=null?i:{};r[o]=t,e.state.set(tn,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(o,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return o.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Go};case"ALLOW":return;default:return}}};function vi(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===$o&&e.push(t.functionCall);return e}import{cloneDeep as zo}from"lodash-es";import{cloneDeep as xi}from"lodash-es";var Pe=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=yi(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(S.TEMP_PREFIX)||(e.state[o]=r)}};function yi(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(S.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function on(n={},e={},t={}){let o=xi(t);for(let[r,i]of Object.entries(n))o[S.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[S.USER_PREFIX+r]=i;return o}function je(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}var ae=class extends Pe{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}async createSession({appName:t,userId:o,state:r,sessionId:i}){var c;let s=je({id:i||ue(),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=zo(s);return a.state=on(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=zo(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=on(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(je({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=>{C.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(S.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(S.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(S.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(S.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 Ei}from"@google/genai";import{context as Ai,trace as Ti}from"@opentelemetry/api";var rn=Symbol.for("google.adk.runner");function Si(n){return typeof n=="object"&&n!==null&&rn in n&&n[rn]===!0}var Vo;Vo=rn;var ce=class{constructor(e){this[Vo]=!0;var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new _e((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runEphemeral(e){return p(this,null,function*(){let o=(yield new m(this.sessionService.createSession({appName:this.appName,userId:e.userId}))).id;try{yield*q(this.runAsync({userId:e.userId,sessionId:o,newMessage:e.newMessage,stateDelta:e.stateDelta,runConfig:e.runConfig}))}finally{yield new m(this.sessionService.deleteSession({appName:this.appName,userId:e.userId,sessionId:o}))}})}runAsync(e){return p(this,null,function*(){let{userId:t,sessionId:o,stateDelta:r}=e,i=Ro(e.runConfig),s=e.newMessage,a=j.startSpan("invocation"),c=Ti.setSpan(Ai.active(),a);try{yield*q(J(c,this,function(){return p(this,null,function*(){var d;let l=yield new m(this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o}));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&&A(this.agent)){let R=this.agent.canonicalModel.model;if(!Se(R))throw new Error("CFC is not supported for model: ".concat(R," in agent: ").concat(this.agent.name));be(this.agent.codeExecutor)||(this.agent.codeExecutor=new Re)}let u=new K({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Ln(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),f=yield new m(this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u}));if(f&&(s=f),s){if(!((d=s.parts)!=null&&d.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new m(this.saveArtifacts(u.invocationId,l.userId,l.id,s))),yield new m(this.sessionService.appendEvent({session:l,event:E({invocationId:u.invocationId,author:"user",actions:r?V({stateDelta:r}):void 0,content:s})}))}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let R=yield new m(this.pluginManager.runBeforeRunCallback({invocationContext:u}));if(R){let b=E({invocationId:u.invocationId,author:"model",content:R});yield new m(this.sessionService.appendEvent({session:l,event:b})),yield b}else{try{for(var g=y(u.agent.runAsync(u)),h,x,v;h=!(x=yield new m(g.next())).done;h=!1){let b=x.value;b.partial||(yield new m(this.sessionService.appendEvent({session:l,event:b})));let L=yield new m(this.pluginManager.runOnEventCallback({invocationContext:u,event:b}));L?yield L:yield b}}catch(x){v=[x]}finally{try{h&&(x=g.return)&&(yield new m(x.call(g)))}finally{if(v)throw v[0]}}yield new m(this.pluginManager.runAfterRunCallback({invocationContext:u}))}}})}))}finally{a.end()}})}async saveArtifacts(e,t,o,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:o,filename:c,artifact:a}),r.parts[s]=Ei("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let o=Ri(e.events);if(o&&o.author)return t.findAgent(o.author)||t;for(let r=e.events.length-1;r>=0;r--){C.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){C.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(!A(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Ri(n){var o,r,i,s;if(!n.length)return null;let t=(s=(i=(r=(o=n[n.length-1].content)==null?void 0:o.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=n.length-2;a>=0;a--){let c=n[a],l=_(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var sn=class extends ce{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new we,sessionService:new ae,memoryService:new ie})}};import{Type as Ye}from"@google/genai";var Ke=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 an=Symbol.for("google.adk.agentTool");function bi(n){return typeof n=="object"&&n!==null&&an in n&&n[an]===!0}var jo,Ko,cn=class extends(Ko=P,jo=an,Ko){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[jo]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(A(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:Ye.OBJECT,properties:{request:{type:Ye.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=A(this.agent)&&this.agent.outputSchema;t.response=o?{type:Ye.OBJECT}:{type:Ye.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,d,R,b;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:A(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new ce({appName:this.agent.name,agent:this.agent,artifactService:new Ke(o),sessionService:(f=o.invocationContext.sessionService)!=null?f:new ae,memoryService:(d=o.invocationContext.memoryService)!=null?d:new ie,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()}),c;try{for(var g=y(s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i})),h,x,v;h=!(x=await g.next()).done;h=!1){let L=x.value;L.actions.stateDelta&&o.state.update(L.actions.stateDelta),c=L}}catch(x){v=[x]}finally{try{h&&(x=g.return)&&await x.call(g)}finally{if(v)throw v[0]}}if(!((b=(R=c==null?void 0:c.content)==null?void 0:R.parts)!=null&&b.length))return"";let l=A(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(L=>L.text).filter(L=>L).join("\n");return l?JSON.parse(u):u}};var ln=Symbol.for("google.adk.baseToolset");function Ii(n){return typeof n=="object"&&n!==null&&ln in n&&n[ln]===!0}var Yo;Yo=ln;var un=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[Yo]=!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 He=class extends P{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,""}},wi=new He;var We=class extends P{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||[],ro(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(oo(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(e.model))}}},Li=new We;import{Type as fn}from"@google/genai";var _i=at(),Pi=["image/","audio/","video/"],ki=new Set(["application/pdf"]),Oi=new Set(["application/csv","application/json","application/xml"]);function Ho(n){if(n)return n.split(";")[0].trim()}function Mi(n){let e=Ho(n);return e?Pi.some(t=>e.startsWith(t))||ki.has(e):!1}function Bi(n,e){let t=n.inlineData;if(!t||Mi(t.mimeType))return n;let o=Ho(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/")||Oi.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 Ze=class extends P{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:fn.OBJECT,properties:{artifact_names:{type:fn.ARRAY,items:{type:fn.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;B(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 g="user:".concat(u);f=await e.loadArtifact(g)}if(!f){_i.warn('Artifact "'.concat(u,'" not found, skipping'));continue}let d=Bi(f,u);t.contents.push({role:"user",parts:[{text:"Artifact ".concat(u," is:")},d]})}}}}}},Ni=new Ze;import{Type as Wo}from"@google/genai";var Qe=class extends P{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:Wo.OBJECT,properties:{query:{type:Wo.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&&B(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."])}},Fi=new Qe;var Zo="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",mn=class extends Y{constructor(e){super(z(T({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Zo:e.description=Zo.trimStart(),e}};var Je=class extends P{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){C.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 d=f.timestamp?"Time: ".concat(f.timestamp):"";d&&i.push(d);let g=(u=(l=f.content.parts)==null?void 0:l.map(h=>{var x;return(x=h.text)!=null?x:""}).join(" "))!=null?u:"";g&&i.push(f.author?"".concat(f.author,": ").concat(g):g)}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");B(e.llmRequest,[a])}},Di=new Je;export{Xe as ActiveStreamingTool,cn as AgentTool,pe as ApigeeLlm,No as AuthCredentialTypes,$ as BaseAgent,Te as BaseCodeExecutor,Xt as BaseExampleProvider,me as BaseLlm,M as BaseLlmRequestProcessor,At as BaseLlmResponseProcessor,se as BasePlugin,Pe as BaseSessionService,P as BaseTool,un as BaseToolset,Re as BuiltInCodeExecutor,ze as CONTENT_REQUEST_PROCESSOR,Ue as ContentRequestProcessor,O as Context,ge as ContextCompactorRequestProcessor,wi as EXIT_LOOP,Fo as EventType,He as ExitLoopTool,Y as FunctionTool,Li as GOOGLE_SEARCH,Z as Gemini,Fe as GoogleLLMVariant,We as GoogleSearchTool,we as InMemoryArtifactService,ie as InMemoryMemoryService,Ve as InMemoryPolicyEngine,sn as InMemoryRunner,ae as InMemorySessionService,K as InvocationContext,ee as LLMRegistry,Ni as LOAD_ARTIFACTS,Fi as LOAD_MEMORY,mt as LiveRequestQueue,$t as LlmAgent,Wt as LlmSummarizer,Ze as LoadArtifactsTool,Qe as LoadMemoryTool,Mn as LogLevel,en as LoggingPlugin,mn as LongRunningFunctionTool,zt as LoopAgent,Di as PRELOAD_MEMORY,jt as ParallelAgent,_e as PluginManager,Uo as PolicyOutcome,Je as PreloadMemoryTool,$o as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,k as ReadonlyContext,ce as Runner,nn as SecurityPlugin,Ht as SequentialAgent,S as State,qt as StreamingMode,Zt as TokenBasedContextCompactor,X as ToolConfirmation,Qt as TruncatingContextCompactor,E as createEvent,V as createEventActions,je as createSession,pr as functionsExportedForTestingOnly,qe as geminiInitParams,vi as getAskUserConfirmationFunctionCalls,_ as getFunctionCalls,N as getFunctionResponses,at as getLogger,xn as hasTrailingCodeExecutionResult,bi as isAgentTool,sr as isBaseAgent,gi as isBaseExampleProvider,dt as isBaseLlm,xt as isBaseTool,Ii as isBaseToolset,D as isCompactedEvent,H as isFinalResponse,Or as isFunctionTool,Se as isGemini2OrAbove,A as isLlmAgent,ri as isLoopAgent,ii as isParallelAgent,Si as isRunner,ci as isSequentialAgent,on as mergeStates,fr as setLogLevel,ur as setLogger,Ce as stringifyContent,di as toStructuredEvents,yi as trimTempDeltaState,ve as version,de as zodObjectToSchema};
7
+ var Qo=Object.defineProperty,Jo=Object.defineProperties;var Xo=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var dn=Object.prototype.hasOwnProperty,gn=Object.prototype.propertyIsEnumerable;var le=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),er=n=>{throw TypeError(n)};var pn=(n,e,t)=>e in n?Qo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,T=(n,e)=>{for(var t in e||(e={}))dn.call(e,t)&&pn(n,t,e[t]);if(ke)for(var t of ke(e))gn.call(e,t)&&pn(n,t,e[t]);return n},z=(n,e)=>Jo(n,Xo(e));var hn=(n,e)=>{var t={};for(var o in n)dn.call(n,o)&&e.indexOf(o)<0&&(t[o]=n[o]);if(n!=null&&ke)for(var o of ke(n))e.indexOf(o)<0&&gn.call(n,o)&&(t[o]=n[o]);return t};var m=function(n,e){this[0]=n,this[1]=e},p=(n,e,t)=>{var o=(s,a,c,l)=>{try{var u=t[s](a),f=(a=u.value)instanceof m,d=u.done;Promise.resolve(f?a[0]:a).then(g=>f?o(s==="return"?s:"next",a[1]?{done:g.done,value:g.value}:g,c,l):c({value:g,done:d})).catch(g=>o("throw",g,c,l))}catch(g){l(g)}},r=s=>i[s]=a=>new Promise((c,l)=>o(s,a,c,l)),i={};return t=t.apply(n,e),i[le("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i},q=n=>{var e=n[le("asyncIterator")],t=!1,o,r={};return e==null?(e=n[le("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 m(new Promise(a=>{var c=e[i](s);c instanceof Object||er("Object expected"),a(c)}),1)}}),r[le("iterator")]=()=>r,o("next"),"throw"in e?o("throw"):r.throw=i=>{throw i},"return"in e&&o("return"),r},y=(n,e,t)=>(e=n[le("asyncIterator")])?e.call(n):(n=n[le("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 Xe=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};import{context as _n,trace as Pn}from"@opentelemetry/api";function V(n={}){return T({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},n)}function Cn(n,e){let t=V();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 E(n={}){return z(T({},n),{id:n.id||et(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||V(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()})}function H(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:_(n).length===0&&N(n).length===0&&!n.partial&&!xn(n)}function _(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionCall&&e.push(t.functionCall);return e}function N(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 xn(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 Ce(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 vn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function et(){let n="";for(let e=0;e<8;e++)n+=vn[Math.floor(Math.random()*vn.length)];return n}import{context as tt,trace as Ee}from"@opentelemetry/api";var ve="0.6.1";var tr="gen_ai.agent.description",nr="gen_ai.agent.name",or="gen_ai.conversation.id",nt="gen_ai.operation.name",yn="gen_ai.tool.call.id",En="gen_ai.tool.description",An="gen_ai.tool.name",rr="gen_ai.tool.type",j=Ee.getTracer("gcp.vertex.agent",ve);function xe(n){try{return JSON.stringify(n)}catch(e){return"<not serializable>"}}function Tn({agent:n,invocationContext:e}){let t=Ee.getActiveSpan();t&&t.setAttributes({[nt]:"invoke_agent",[tr]:n.description,[nr]:n.name,[or]:e.session.id})}function Sn({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=Ee.getActiveSpan();if(!o)return;o.setAttributes({[nt]:"execute_tool",[En]:n.description||"",[An]:n.name,[rr]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":ye()?xe(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({[yn]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":ye()?xe(i):"{}"})}function Rn({responseEventId:n,functionResponseEvent:e}){let t=Ee.getActiveSpan();t&&(t.setAttributes({[nt]:"execute_tool",[An]:"(merged tools)",[En]:"(merged tools)",[yn]: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",ye()?xe(e):"{}"))}function bn({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=Ee.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":ye()?xe(ir(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",ye()?xe(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 ir(n){let e={model:n.model,contents:[]};if(n.config){let t=n.config,{responseSchema:o}=t,r=hn(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 In(n,e){return{next:tt.bind(n,e.next.bind(e)),return:tt.bind(n,e.return.bind(e)),throw:tt.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return In(n,e[Symbol.asyncIterator]())}}}function J(n,e,t){let o=t.call(e);return In(n,o)}function ye(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var Ae=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,o;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((o=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&o.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".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(){return this.authConfig.rawAuthCredential}};var S=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 T(T({},this.value),this.delta)}};S.APP_PREFIX="app:",S.USER_PREFIX="user:",S.TEMP_PREFIX="temp:";var X=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var k=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 S(this.invocationContext.session.state,{})}};var O=class extends k{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||V(),this._state=new S(e.invocationContext.session.state,this.eventActions.stateDelta),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get state(){return this._state}get actions(){return this.eventActions}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let o=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=o,o}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Ae(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ae(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new X({hint:e,confirmed:!1,payload:t})}};function G(){return typeof window<"u"}var Oe="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ue(){let n="";for(let e=0;e<Oe.length;e++){let t=Math.random()*16|0;Oe[e]==="x"?n+=t.toString(16):Oe[e]==="y"?n+=(t&3|8).toString(16):n+=Oe[e]}return n}function wn(n){return G()?window.atob(n):Buffer.from(n,"base64").toString()}function Me(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var ot=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},K=class{constructor(e){this.invocationCostManager=new ot;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function Ln(){return"e-".concat(ue())}var rt=Symbol.for("google.adk.baseAgent");function sr(n){return typeof n=="object"&&n!==null&&rt in n&&n[rt]===!0}var On;On=rt;var $=class{constructor(e){this[On]=!0;this.name=ar(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=kn(e.beforeAgentCallback),this.afterAgentCallback=kn(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return lr(this)}runAsync(e){return p(this,null,function*(){let t=j.startSpan("invoke_agent ".concat(this.name)),o=Pn.setSpan(_n.active(),t);try{yield*q(J(o,this,function(){return p(this,null,function*(){let r=this.createInvocationContext(e),i=yield new m(this.handleBeforeAgentCallback(r));if(i&&(yield i),r.endInvocation)return;Tn({agent:this,invocationContext:r});try{for(var a=y(this.runAsyncImpl(r)),c,l,u;c=!(l=yield new m(a.next())).done;c=!1){let f=l.value;yield f}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new m(l.call(a)))}finally{if(u)throw u[0]}}if(r.endInvocation)return;let s=yield new m(this.handleAfterAgentCallback(r));s&&(yield s)})}))}finally{t.end()}})}runLive(e){return p(this,null,function*(){let t=j.startSpan("invoke_agent ".concat(this.name)),o=Pn.setSpan(_n.active(),t);try{throw yield*q(J(o,this,function(){return p(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 K(z(T({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new O({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new O({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({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 ar(n){if(!cr(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 cr(n){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_-]*$","u").test(n)}function lr(n){for(;n.parentAgent;)n=n.parentAgent;return n}function kn(n){return n?Array.isArray(n)?n:[n]:[]}import{createUserContent as mr}from"@google/genai";import{isEmpty as Bn}from"lodash-es";import*as U from"winston";var Mn=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Mn||{}),it=class{constructor(){this.logLevel=1;this.logger=U.createLogger({levels:{debug:0,info:1,warn:2,error:3},level:"error",format:U.format.combine(U.format.label({label:"ADK"}),U.format(e=>(e.level=e.level.toUpperCase(),e))(),U.format.colorize(),U.format.timestamp(),U.format.printf(e=>"".concat(e.level,": [").concat(e.label,"] ").concat(e.timestamp," ").concat(e.message))),transports:[new U.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(" "))}},st=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},W=new it;function ur(n){W=n!=null?n:new st}function at(){return W}function fr(n){C.setLogLevel(n)}var C={setLogLevel(n){W.setLogLevel(n)},log(n,...e){W.log(n,...e)},debug(...n){W.debug(...n)},info(...n){W.info(...n)},warn(...n){W.warn(...n)},error(...n){W.error(...n)}};var ct="adk-",Be="adk_request_credential",fe="adk_request_confirmation",pr={handleFunctionCallList:Ne,generateAuthEvent:ut,generateRequestConfirmationEvent:ft};function lt(){return"".concat(ct).concat(ue())}function Nn(n){let e=_(n);if(e)for(let t of e)t.id||(t.id=lt())}function Fn(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(ct)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(ct)&&(e.functionResponse.id=void 0)}function Dn(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 ut(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||Bn(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:Be,args:{function_call_id:i,auth_config:s},id:lt()};o.add(a.id),t.push({functionCall:a})}return E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function ft({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||Bn(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=_(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!u)continue;let f={name:fe,args:{originalFunctionCall:u,toolConfirmation:l},id:lt()};r.add(f.id),o.push({functionCall:f})}return E({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 dr(n,e,t){return j.startActiveSpan("execute_tool ".concat(n.name),async o=>{try{C.debug("callToolAsync ".concat(n.name));let r=await n.runAsync({args:e,toolContext:t});return Sn({tool:n,args:e,functionResponseEvent:gr(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function gr(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 E({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function qn({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=_(e);return await Ne({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ne({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let d;s&&f.id&&(d=s[f.id]);let{tool:g,toolContext:h}=hr({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:d});C.debug("execute_tool ".concat(g.name));let x=(u=f.args)!=null?u:{},v=null,R;if(v=await n.pluginManager.runBeforeToolCallback({tool:g,toolArgs:x,toolContext:h}),v==null){for(let I of o)if(v=await I({tool:g,args:x,context:h}),v)break}if(v==null)try{v=await dr(g,x,h)}catch(I){if(I instanceof Error){let w=await n.pluginManager.runOnToolErrorCallback({tool:g,toolArgs:x,toolContext:h,error:I});w?v=w:R=I.message}else R=I}let b=await n.pluginManager.runAfterToolCallback({tool:g,toolArgs:x,toolContext:h,result:v});if(b==null){for(let I of r)if(b=await I({tool:g,args:x,context:h,response:v}),b)break}if(b!=null&&(v=b),g.isLongRunning&&!v)continue;R?v={error:R}:(typeof v!="object"||v==null)&&(v={result:v});let L=E({invocationId:n.invocationId,author:n.agent.name,content:mr({functionResponse:{id:h.functionCallId,name:g.name,response:v}}),actions:h.actions,branch:n.branch});C.debug("traceToolCall",{tool:g.name,args:x,functionResponseEvent:L.id}),a.push(L)}if(!a.length)return null;let l=Cr(a);return a.length>1&&j.startActiveSpan("execute_tool (merged)",f=>{try{C.debug("execute_tool (merged)"),C.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),Rn({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function hr({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 Cr(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=Cn(o);return E({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var mt=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 p(this,null,function*(){for(;;){let e=yield new m(this.get());if(yield e,e.close)break}})}};import{context as ni,trace as oi}from"@opentelemetry/api";var vr="google-adk",xr="gl-typescript",yr="remote_reasoning_engine",Er="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Ar(){let n="".concat(vr,"/").concat(ve);!G()&&process.env[Er]&&(n="".concat(n,"+").concat(yr));let e="".concat(xr,"/").concat(G()?window.navigator.userAgent:process.version);return[n,e]}function Gn(){return Ar()}var pt=Symbol.for("google.adk.baseModel");function dt(n){return typeof n=="object"&&n!==null&&pt in n&&n[pt]===!0}var $n;$n=pt;var me=class{constructor({model:e}){this[$n]=!0;this.model=e}get trackingHeaders(){let t=Gn().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};me.supportedModels=[];import{createPartFromText as zn,FinishReason as Tr,GoogleGenAI as ht}from"@google/genai";var Fe=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Fe||{});function Un(){return Me("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}var De=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"}):C.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);C.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else C.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){C.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return p(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function gt(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 Z=class extends me{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=qe({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){return p(this,null,function*(){var o,r,i,s,f,d,g;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),C.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(o=e.config)!=null&&o.httpOptions&&(e.config.httpOptions.headers=T(T({},e.config.httpOptions.headers),this.trackingHeaders)),t){let h=yield new m(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),x="",v="",R,b;try{for(var a=y(h),c,l,u;c=!(l=yield new m(a.next())).done;c=!1){let L=l.value;b=L;let I=gt(L);R=I.usageMetadata;let w=(s=(i=I.content)==null?void 0:i.parts)==null?void 0:s[0];if(w!=null&&w.text)"thought"in w&&w.thought?x+=w.text:v+=w.text,I.partial=!0;else if((x||v)&&(!w||!w.inlineData)){let Q=[];x&&Q.push({text:x,thought:!0}),v&&Q.push(zn(v)),yield{content:{role:"model",parts:Q},usageMetadata:I.usageMetadata},x="",v=""}yield I}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new m(l.call(a)))}finally{if(u)throw u[0]}}if((v||x)&&((d=(f=b==null?void 0:b.candidates)==null?void 0:f[0])==null?void 0:d.finishReason)===Tr.STOP){let L=[];x&&L.push({text:x,thought:!0}),v&&L.push({text:v}),yield{content:{role:"model",parts:L},usageMetadata:R}}}else{let h=yield new m(this.apiClient.models.generateContent({model:(g=e.model)!=null?g:this.model,contents:e.contents,config:e.config}));yield gt(h)}})}getHttpOptions(){return{headers:T(T({},this.trackingHeaders),this.headers)}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new ht({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new ht({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 ht({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:[zn(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 De(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)Vn(o.inlineData),Vn(o.fileData)}}};Z.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Vn(n){n&&n.displayName&&(n.displayName=void 0)}function qe({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&&!G()&&(i.vertexai=Me("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!G()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!G()&&!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&&!G()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var jn="APIGEE_PROXY_URL",pe=class extends Z{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!Yn(e))throw new Error("Model ".concat(e," is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>"));if(super(z(T({},Sr({model:e,vertexai:r,project:s,location:i,apiKey:o})),{headers:a})),this.proxyUrl=t!=null?t:"",!G()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[jn])!=null?c:""),!this.proxyUrl)throw new Error("Proxy URL must be provided via the constructor or ".concat(jn," 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){return p(this,null,function*(){var r;let o=(r=e.model)!=null?r:this.model;e.model=Kn(o),yield*q(super.generateContentAsync(e,t))})}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=Kn(t),super.connect(e)}};pe.supportedModels=[/apigee\/.*/];function Sr({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=qe({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||(C.warn('No API key provided when using a Gemini model, using a fake key "-".'),i.apiKey="-"),i}function Kn(n){if(!Yn(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 Yn(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 Ct=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},F=class F{static newLlm(e){return new(F.resolve(e))({model:e})}static _register(e,t){F.llmRegistryDict.has(e)&&C.info("Updating LLM class for ".concat(e," from ").concat(F.llmRegistryDict.get(e)," to ").concat(t)),F.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)F._register(t,e)}static resolve(e){let t=F.resolveCache.get(e);if(t)return t;for(let[o,r]of F.llmRegistryDict.entries())if(new RegExp("^".concat(o instanceof RegExp?o.source:o,"$"),o instanceof RegExp?o.flags:void 0).test(e))return F.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};F.llmRegistryDict=new Map,F.resolveCache=new Ct(32);var ee=F;ee.register(Z);ee.register(pe);var vt=Symbol.for("google.adk.baseTool");function xt(n){return typeof n=="object"&&n!==null&&vt in n&&n[vt]===!0}var Hn;Hn=vt;var P=class{constructor(e){this[Hn]=!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=Rr(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 Un()}};function Rr(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Wn}from"@google/genai";import{zodToJsonSchema as br}from"zod-to-json-schema";import{toJSONSchema as Ir}from"zod/v4";function yt(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function wr(n){return yt(n)&&!("_zod"in n)}function Lr(n){return yt(n)&&"_zod"in n}function _r(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 te(n){return yt(n)&&_r(n)==="ZodObject"}function de(n){if(!te(n))throw new Error("Expected a Zod Object");if(Lr(n))return Ir(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=Wn.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(wr(n))return br(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=Wn.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 Xn}from"zod";function B(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 Zn(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}import{Type as Pr}from"@google/genai";function kr(n){return n===void 0?{type:Pr.OBJECT,properties:{}}:te(n)?de(n):n}var Et=Symbol.for("google.adk.functionTool");function Or(n){return typeof n=="object"&&n!==null&&Et in n&&n[Et]===!0}var Qn,Jn,Y=class extends(Jn=P,Qn=Et,Jn){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[Qn]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:kr(this.parameters)}}async runAsync(t){try{let o=t.args;return te(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 M=class{},At=class{};var Tt=class extends M{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new Y({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:Xn.object({agentName:Xn.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 p(this,null,function*(){if(!A(t.agent))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;B(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new O({invocationContext:t});yield new m(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||!A(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},eo=new Tt;var St=class extends M{runAsync(e,t){return p(this,null,function*(){var r;let o=e.agent;A(o)&&(t.model=o.canonicalModel.model,t.config=T({},(r=o.generateContentConfig)!=null?r:{}),o.outputSchema&&Zn(t,o.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},to=new St;import{cloneDeep as fo}from"lodash-es";var Rt=Symbol.for("google.adk.baseCodeExecutor");function Ge(n){return typeof n=="object"&&n!==null&&Rt in n&&n[Rt]===!0}var no;no=Rt;var Te=class{constructor(){this[no]=!0;this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Mr="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function bt(n){let e=n.match(Mr);return e?e[1]:n}function oo(n){return bt(n).startsWith("gemini-")}function Br(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 ro(n){return bt(n).startsWith("gemini-1")}function Se(n){if(!n)return!1;let e=bt(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Br(t);return o.valid&&o.major>=2}var It=Symbol.for("google.adk.builtInCodeExecutor");function be(n){return typeof n=="object"&&n!==null&&It in n&&n[It]===!0}var io,so,Re=class extends(so=Te,io=It,so){constructor(){super(...arguments);this[io]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&Se(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 Nr,Outcome as ao}from"@google/genai";import{cloneDeep as Fr}from"lodash-es";function co(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let d=n.parts[f];if(d.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),d.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=Fr(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(wt(l)),l):""}function wt(n){return{text:n,executableCode:{code:n,language:Nr.PYTHON}}}function lo(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:ao.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:ao.OUTCOME_OK}}}function uo(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 Dr}from"lodash-es";var Lt="_code_execution_context",_t="execution_session_id",ne="processed_input_files",oe="_code_executor_input_files",re="_code_executor_error_counts",Pt="_code_execution_results",Ie=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Lt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Lt]:Dr(this.context)}}getExecutionId(){if(_t in this.context)return this.context[_t]}setExecutionId(e){this.context[_t]=e}getProcessedFileNames(){return ne in this.context?this.context[ne]:[]}addProcessedFileNames(e){ne in this.context||(this.context[ne]=[]),this.context[ne].push(...e)}getInputFiles(){return oe in this.sessionState?this.sessionState.get(oe):[]}addInputFiles(e){oe in this.sessionState||this.sessionState.set(oe,[]),this.sessionState.get(oe).push(...e)}clearInputFiles(){oe in this.sessionState&&this.sessionState.set(oe,[]),ne in this.context&&(this.context[ne]=[])}getErrorCount(e){return re in this.sessionState&&this.sessionState.get(re)[e]||0}incrementErrorCount(e){re in this.sessionState||this.sessionState.set(re,{}),this.sessionState.get(re)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(re in this.sessionState))return;let t=this.sessionState.get(re);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){Pt in this.sessionState||this.sessionState.set(Pt,{});let i=this.sessionState.get(Pt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(Lt)||{}}};var kt=class extends M{runAsync(e,t){return p(this,null,function*(){if(A(e.agent)&&e.agent.codeExecutor){try{for(var o=y(Gr(e,t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}if(Ge(e.agent.codeExecutor))for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];uo(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},$e={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},qr="\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",Ot=class{runAsync(e,t){return p(this,null,function*(){if(!t.partial)try{for(var o=y($r(e,t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}})}},$c=new Ot;function Gr(n,e){return p(this,null,function*(){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!Ge(o))return;if(be(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new Ie(new S(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=Ur(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=zr(c);if(!l)return;let u={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},wt(l)]};e.contents.push(fo(u)),yield E({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=mo(n,r),d=yield new m(o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([c.name]);let g=yield new m(po(n,r,d));yield g,e.contents.push(fo(g.content))}})}function $r(n,e){return p(this,null,function*(){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!Ge(o)||!e||!e.content||be(o))return;let r=new Ie(new S(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=co(i,o.codeBlockDelimiters);if(!s)return;yield E({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=mo(n,r),c=yield new m(o.executeCode({invocationContext:n,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}}));r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield yield new m(po(n,r,c)),e.content=void 0})}function Ur(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||!$e[l])continue;let u="data_".concat(i+1,"_").concat(a+1).concat($e[l].extension);c.text="\nAvailable file: `".concat(u,"`\n");let f={name:u,content:wn(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function mo(n,e){var r;let t=n.agent;if(!A(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function po(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[lo(t)]},r=V({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 E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function zr(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!$e[n.mimeType])return;let t=e(n.name),o=$e[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return"\n".concat(qr,"\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 go=new kt;function D(n){return"isCompacted"in n&&n.isCompacted===!0}function ho(n={}){return z(T({},E(n)),{isCompacted:n.isCompacted||!0,startTime:n.startTime,endTime:n.endTime,compactedContent:n.compactedContent})}import{createUserContent as Vr}from"@google/genai";import{cloneDeep as jr}from"lodash-es";function Mt(n,e,t){var s,a,c;let o=[];for(let l of n){if(D(l)){o.push(Qr(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)||Kr(l)||Yr(l)||o.push(xo(e,l)?Hr(l):l)}let r=Wr(o);r=Zr(r);let i=[];for(let l of r){let u=jr(l.content);Fn(u),i.push(u)}return i}function vo(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||xo(e,r))return Mt(n.slice(o),e,t)}return[]}function Kr(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Be||((o=r.functionResponse)==null?void 0:o.name)===Be)return!0;return!1}function Yr(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)===fe||((o=r.functionResponse)==null?void 0:o.name)===fe)return!0;return!1}function xo(n,e){return!!n&&e.author!==n&&e.author!=="user"}function Hr(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=Co(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=Co(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 E({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function yo(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=E(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 Wr(n){if(n.length===0)return n;let e=n[n.length-1],t=N(e);if(!(t!=null&&t.length))return n;let o=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=n.at(-2);if(r){let c=_(r);if(c){for(let l of c)if(l.id&&o.has(l.id))return n}}let i=-1;for(let c=n.length-2;c>=0;c--){let l=n[c],u=_(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let d=new Set(u.map(h=>h.id).filter(h=>!!h));if(!Array.from(o).every(h=>d.has(h)))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(d).join(", "),", function response")+" ids provided: ".concat(Array.from(o).join(", ")));o=d;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=N(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(yo(s)),a}function Zr(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=N(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(N(o).length>0)continue;let r=_(o);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(o),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(n[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>n[c]);t.push(yo(a))}}else t.push(o)}return t}function Co(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch(e){return String(n)}}function Qr(n){let e=Vr("[Previous Context Summary]:\n".concat(n.compactedContent));return E({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}var Ue=class{runAsync(e,t){return p(this,null,function*(){let o=e.agent;if(!o||!A(o))return;let r=e.session.events,i=r.filter(D),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||D(c)||c.timestamp<=s.endTime));r=[s,...a]}o.includeContents==="default"?t.contents=Mt(r,o.name,e.branch):t.contents=vo(r,o.name,e.branch)})}},ze=new Ue;var ge=class{constructor(e){this.compactors=e}runAsync(e,t){return p(this,null,function*(){for(let o of this.compactors)if(yield new m(Promise.resolve(o.shouldCompact(e)))){let i=new Set(e.session.events);yield new m(Promise.resolve(o.compact(e)));let s=e.session.events.filter(a=>!i.has(a));for(let a of s)yield a;return}})}};var Bt=class extends M{runAsync(e,t){return p(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,'"')),B(t,r)})}},Eo=new Bt;async function Nt(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!d)throw new Error("Artifact ".concat(f," not found."));return String(d)}if(!ei(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 Jr=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ao(n){return n===""||n===void 0?!1:Jr.test(n)}var Xr=[S.APP_PREFIX,S.USER_PREFIX,S.TEMP_PREFIX];function ei(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?Ao(n):Xr.includes(e[0]+":")?Ao(e[1]):!1}var Ft=class extends M{runAsync(e,t){return p(this,null,function*(){let o=e.agent;if(!A(o))return;let r=o.rootAgent;if(A(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new m(r.canonicalGlobalInstruction(new k(e))),a=i;s&&(a=yield new m(Nt(i,new k(e)))),B(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=yield new m(o.canonicalInstruction(new k(e))),a=i;s&&(a=yield new m(Nt(i,new k(e)))),B(t,[a])}})}},To=new Ft;var Dt=class extends M{runAsync(e){return p(this,null,function*(){let t=e.agent;if(!A(t))return;let o=e.session.events;if(!o||o.length===0)return;let r={},i=-1;for(let s=o.length-1;s>=0;s--){let a=o[s];if(a.author!=="user")continue;let c=N(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==fe)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 X({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(r[u.id]=f)}if(l){i=s;break}}if(Object.keys(r).length!==0)for(let s=i-1;s>=0;s--){let a=o[s],c=_(a);if(!c)continue;let l={},u={};for(let h of c){if(!h.id||!(h.id in r))continue;let x=h.args;if(!x||!("originalFunctionCall"in x))continue;let v=x.originalFunctionCall;v.id&&(l[v.id]=r[h.id],u[v.id]=v)}if(Object.keys(l).length===0)continue;for(let h=o.length-1;h>i;h--){let x=o[h],v=N(x);if(v){for(let R of v)R.id&&R.id in l&&(delete l[R.id],delete u[R.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=yield new m(t.canonicalTools(new k(e))),d=Object.fromEntries(f.map(h=>[h.name,h])),g=yield new m(Ne({invocationContext:e,functionCalls:Object.values(u),toolsDict:d,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l}));g&&(yield g);return}})}},So=new Dt;var qt=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(qt||{});function Ro(n={}){return T({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ti(n.maxLlmCalls||500),pauseOnToolCalls:!1},n)}function ti(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return n<=0&&C.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 bo="adk_agent_name";async function Io(n,e){return xt(n)?[n]:await n.getTools(e)}var Gt=Symbol.for("google.adk.llmAgent");function A(n){return typeof n=="object"&&n!==null&&Gt in n&&n[Gt]===!0}var wo,Lo,$t=class n extends(Lo=$,wo=Gt,Lo){constructor(t){var r,i,s,a,c,l,u,f,d;super(t);this[wo]=!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=te(t.inputSchema)?de(t.inputSchema):t.inputSchema,this.outputSchema=te(t.outputSchema)?de(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:[to,Eo,To,So,ze,go],!t.requestProcessors&&t.contextCompactors&&t.contextCompactors.length>0){let g=this.requestProcessors.indexOf(ze);g!==-1?this.requestProcessors.splice(g,0,new ge(t.contextCompactors)):this.requestProcessors.push(new ge(t.contextCompactors))}if(this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(eo),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)&&(C.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(dt(this.model))return this.model;if(typeof this.model=="string"&&this.model)return ee.newLlm(this.model);let t=this.parentAgent;for(;t;){if(A(t))return t.canonicalModel;t=t.parentAgent}throw new Error("No model found for ".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 Io(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){C.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(t.author));return}if(!this.outputKey){C.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!H(t)){C.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)){C.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){C.error("Error parsing output for agent ".concat(this.name),a)}}t.actions.stateDelta[this.outputKey]=r}runAsyncImpl(t){return p(this,null,function*(){for(;;){let a;try{for(var o=y(this.runOneStepAsync(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let c=i.value;a=c,this.maybeSaveOutputToState(c),yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}if(!a||H(a))break;if(a.partial){C.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(t){return p(this,null,function*(){try{for(var o=y(this.runLiveFlow(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let a=i.value;this.maybeSaveOutputToState(a),yield a}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}t.endInvocation})}runLiveFlow(t){return p(this,null,function*(){throw yield new m(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(t){return p(this,null,function*(){let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let f of this.requestProcessors)try{for(var a=y(f.runAsync(t,o)),c,l,u;c=!(l=yield new m(a.next())).done;c=!1){let d=l.value;yield d}}catch(l){u=[l]}finally{try{c&&(l=a.return)&&(yield new m(l.call(a)))}finally{if(u)throw u[0]}}for(let f of this.tools){let d=new O({invocationContext:t}),g=yield new m(Io(f,new k(t)));for(let h of g)yield new m(h.processLlmRequest({toolContext:d,llmRequest:o}))}if(t.endInvocation)return;let r=E({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=j.startSpan("call_llm"),s=oi.setSpan(ni.active(),i);yield*q(J(s,this,function(){return p(this,null,function*(){let f=function(){return p(this,null,function*(){try{for(var v=y(this.callLlmAsync(t,o,r)),R,b,L;R=!(b=yield new m(v.next())).done;R=!1){let I=b.value;try{for(var d=y(this.postprocess(t,o,I,r)),g,h,x;g=!(h=yield new m(d.next())).done;g=!1){let w=h.value;r.id=et(),r.timestamp=new Date().getTime(),yield w}}catch(h){x=[h]}finally{try{g&&(h=d.return)&&(yield new m(h.call(d)))}finally{if(x)throw x[0]}}}}catch(b){L=[b]}finally{try{R&&(b=v.return)&&(yield new m(b.call(v)))}finally{if(L)throw L[0]}}})};yield*q(this.runAndHandleError(f.call(this),t,o,r))})})),i.end()})}postprocess(t,o,r,i){return p(this,null,function*(){var x,v;for(let w of this.responseProcessors)try{for(var f=y(w.runAsync(t,r)),d,g,h;d=!(g=yield new m(f.next())).done;d=!1){let Q=g.value;yield Q}}catch(g){h=[g]}finally{try{d&&(g=f.return)&&(yield new m(g.call(f)))}finally{if(h)throw h[0]}}if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=E(T(T({},i),r));if(s.content){let w=_(s);w!=null&&w.length&&(Nn(s),s.longRunningToolIds=Array.from(Dn(w,o.toolsDict)))}if(yield s,!((x=_(s))!=null&&x.length))return;if((v=t.runConfig)!=null&&v.pauseOnToolCalls){t.endInvocation=!0;return}let a=yield new m(qn({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!a)return;let c=ut(t,a);c&&(yield c);let l=ft({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let w=this.getAgentByName(t,u);try{for(var R=y(w.runAsync(t)),b,L,I;b=!(L=yield new m(R.next())).done;b=!1){let Q=L.value;yield Q}}catch(L){I=[L]}finally{try{b&&(L=R.return)&&(yield new m(L.call(R)))}finally{if(I)throw I[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 p(this,null,function*(){var a,c,l,u,f;let i=yield new m(this.handleBeforeModelCallback(t,o,r));if(i){yield i;return}(a=o.config)!=null||(o.config={}),(l=(c=o.config).labels)!=null||(c.labels={}),o.config.labels[bo]||(o.config.labels[bo]=this.name);let s=this.canonicalModel;if((u=t.runConfig)!=null&&u.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let v=s.generateContentAsync(o,((f=t.runConfig)==null?void 0:f.streamingMode)==="sse");try{for(var d=y(v),g,h,x;g=!(h=yield new m(d.next())).done;g=!1){let R=h.value;bn({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:R});let b=yield new m(this.handleAfterModelCallback(t,R,r));yield b!=null?b:R}}catch(h){x=[h]}finally{try{g&&(h=d.return)&&(yield new m(h.call(d)))}finally{if(x)throw x[0]}}}})}async handleBeforeModelCallback(t,o,r){let i=new O({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:o});if(c)return c}}async handleAfterModelCallback(t,o,r){let i=new O({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:o});if(c)return c}}runAndHandleError(t,o,r,i){return p(this,null,function*(){try{try{for(var s=y(t),a,c,l;a=!(c=yield new m(s.next())).done;a=!1){let u=c.value;yield u}}catch(c){l=[c]}finally{try{a&&(c=s.return)&&(yield new m(c.call(s)))}finally{if(l)throw l[0]}}}catch(u){let f=new O({invocationContext:o,eventActions:i.actions});if(u instanceof Error){let d=yield new m(o.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:r,error:u}));if(d)yield d;else{let g="UNKNOWN_ERROR",h=u.message;try{let x=JSON.parse(u.message);x!=null&&x.error&&(g=String(x.error.code||"UNKNOWN_ERROR"),h=x.error.message||h)}catch(x){}i.actions?yield E({invocationId:o.invocationId,author:this.name,errorCode:g,errorMessage:h}):yield{errorCode:g,errorMessage:h}}}else throw C.error("Unknown error during response generation",u),u}})}};var Ut=Symbol.for("google.adk.loopAgent");function ri(n){return typeof n=="object"&&n!==null&&Ut in n&&n[Ut]===!0}var _o,Po,zt=class extends(Po=$,_o=Ut,Po){constructor(t){var o;super(t);this[_o]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}runAsyncImpl(t){return p(this,null,function*(){let o=0;for(;o<this.maxIterations;){for(let c of this.subAgents){let l=!1;try{for(var r=y(c.runAsync(t)),i,s,a;i=!(s=yield new m(r.next())).done;i=!1){let u=s.value;yield u,u.actions.escalate&&(l=!0)}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new m(s.call(r)))}finally{if(a)throw a[0]}}if(l)return}o++}})}runLiveImpl(t){return p(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var Vt=Symbol.for("google.adk.parallelAgent");function ii(n){return typeof n=="object"&&n!==null&&Vt in n&&n[Vt]===!0}var ko,Oo,jt=class extends(Oo=$,ko=Vt,Oo){constructor(){super(...arguments);this[ko]=!0}runAsyncImpl(t){return p(this,null,function*(){let o=this.subAgents.map(c=>c.runAsync(si(this,c,t)));try{for(var r=y(ai(o)),i,s,a;i=!(s=yield new m(r.next())).done;i=!1){let c=s.value;yield c}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new m(s.call(r)))}finally{if(a)throw a[0]}}})}runLiveImpl(t){return p(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function si(n,e,t){let o=new K(t),r="".concat(n.name,".").concat(e.name);return o.branch=o.branch?"".concat(o.branch,".").concat(r):r,o}function ai(n){return p(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 m(Promise.race(e.values()));if(t.done){e.delete(o);continue}yield t.value;let r=n[o].next().then(i=>({result:i,index:o}));e.set(o,r)}})}var Kt="task_completed",Yt=Symbol.for("google.adk.sequentialAgent");function ci(n){return typeof n=="object"&&n!==null&&Yt in n&&n[Yt]===!0}var Mo,Bo,Ht=class extends(Bo=$,Mo=Yt,Bo){constructor(){super(...arguments);this[Mo]=!0}runAsyncImpl(t){return p(this,null,function*(){for(let a of this.subAgents)try{for(var o=y(a.runAsync(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}})}runLiveImpl(t){return p(this,null,function*(){for(let a of this.subAgents)A(a)&&((yield new m(a.canonicalTools(new k(t)))).some(u=>u.name===Kt)||(a.tools.push(new Y({name:Kt,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(Kt," 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=y(a.runLive(t)),r,i,s;r=!(i=yield new m(o.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=o.return)&&(yield new m(i.call(o)))}finally{if(s)throw s[0]}}})}};var we=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=he(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=he(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=he(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=he(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=he(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=he(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 he(n,e,t,o){return li(o)?"".concat(n,"/").concat(e,"/user/").concat(o):"".concat(n,"/").concat(e,"/").concat(t,"/").concat(o)}function li(n){return n.startsWith("user:")}var No=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(No||{});var ui="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.",Wt=class{constructor(e){this.llm=e.llm,this.prompt=e.prompt||ui}async summarize(e){var u,f,d,g,h,x;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 I=0;I<e.length;I++)r+="[Event ".concat(I+1," - Author: ").concat(e[I].author,"]\n"),r+="".concat(Ce(e[I]),"\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||!((d=(f=(u=l.value.content)==null?void 0:u.parts)==null?void 0:f[0])!=null&&d.text))throw new Error("LLM failed to return a valid summary.");c+=l.value.content.parts[0].text;try{for(var v=y(a),R,b,L;R=!(b=await v.next()).done;R=!1){let I=b.value;(x=(h=(g=I.content)==null?void 0:g.parts)==null?void 0:h[0])!=null&&x.text&&(c+=I.content.parts[0].text)}}catch(b){L=[b]}finally{try{R&&(b=v.return)&&await b.call(v)}finally{if(L)throw L[0]}}return ho({author:"system",content:{role:"model",parts:[{text:c}]},startTime:t,endTime:o,compactedContent:c})}};var Zt=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];D(i)&&(!t||i.endTime>t.endTime)&&(t=i)}if(!t)return e;let o=e.filter(r=>!D(r)&&r.timestamp>t.endTime);return[t,...o]}shouldCompact(e){let t=e.session.events,o=this.getActiveEvents(t);if(o.filter(s=>!D(s)).length<=this.eventRetentionSize)return!1;let i=0;for(let s of o)i+=fi(s);return i>this.tokenThreshold}async compact(e){let t=e.session.events,o=this.getActiveEvents(t),r=o.filter(u=>!D(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(pi(u)&&mi(f))i--;else break}if(i===0)return;let s=r.slice(0,i),a=o.find(D),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 fi(n){var t;if(((t=n.usageMetadata)==null?void 0:t.promptTokenCount)!==void 0)return n.usageMetadata.promptTokenCount;let e=Ce(n);return Math.ceil(e.length/4)}function mi(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionCall!==void 0))}function pi(n){var e,t;return!!((t=(e=n.content)==null?void 0:e.parts)!=null&&t.some(o=>o.functionResponse!==void 0))}var Qt=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 Le}from"lodash-es";var Fo=(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))(Fo||{});function di(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&&!Le(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!Le(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!Le(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!Le(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&&!Le(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),H(n)&&e.push({type:"finished",output:void 0}),e}var Jt=Symbol.for("google.adk.baseExampleProvider");function gi(n){return typeof n=="object"&&n!==null&&Jt in n&&n[Jt]===!0}var Do;Do=Jt;var Xt=class{constructor(){this[Do]=!0}};var ie=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=qo(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=qo(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),u=hi(l);if(!u.size)continue;o.some(d=>u.has(d))&&r.memories.push({content:c.content,author:c.author,timestamp:Ci(c.timestamp)})}return r}};function qo(n,e){return"".concat(n,"/").concat(e)}function hi(n){return new Set([...n.matchAll(/[A-Za-z]+/g)].map(e=>e[0].toLowerCase()))}function Ci(n){return new Date(n).toISOString()}var se=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var en=class extends se{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(H(e)));let t=_(e);if(t.length>0){let r=t.map(i=>i.name);this.log(" Function Calls: ".concat(r))}let o=N(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");C.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 _e=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),C.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 C.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 C.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:o}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:o}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:o}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:o}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,o=>o.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,o=>o.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}),"onToolErrorCallback")}};var $o="adk_request_confirmation",tn="orcas_tool_call_security_check_states",Go="This tool call needs external confirmation before completion.",Uo=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(Uo||{}),Ve=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},nn=class extends se{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ve}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:Go};if(this.setToolCallCheckState(o,o.toolConfirmation),!o.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};o.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(tn))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(tn))!=null?i:{};r[o]=t,e.state.set(tn,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(o,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return o.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Go};case"ALLOW":return;default:return}}};function vi(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===$o&&e.push(t.functionCall);return e}import{cloneDeep as zo}from"lodash-es";import{cloneDeep as xi}from"lodash-es";var Pe=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=yi(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(S.TEMP_PREFIX)||(e.state[o]=r)}};function yi(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(S.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function on(n={},e={},t={}){let o=xi(t);for(let[r,i]of Object.entries(n))o[S.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[S.USER_PREFIX+r]=i;return o}function je(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}var ae=class extends Pe{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}async createSession({appName:t,userId:o,state:r,sessionId:i}){var c;let s=je({id:i||ue(),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=zo(s);return a.state=on(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=zo(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=on(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(je({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=>{C.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(S.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(S.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(S.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(S.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 Ei}from"@google/genai";import{context as Ai,trace as Ti}from"@opentelemetry/api";var rn=Symbol.for("google.adk.runner");function Si(n){return typeof n=="object"&&n!==null&&rn in n&&n[rn]===!0}var Vo;Vo=rn;var ce=class{constructor(e){this[Vo]=!0;var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new _e((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runEphemeral(e){return p(this,null,function*(){let o=(yield new m(this.sessionService.createSession({appName:this.appName,userId:e.userId}))).id;try{yield*q(this.runAsync({userId:e.userId,sessionId:o,newMessage:e.newMessage,stateDelta:e.stateDelta,runConfig:e.runConfig}))}finally{yield new m(this.sessionService.deleteSession({appName:this.appName,userId:e.userId,sessionId:o}))}})}runAsync(e){return p(this,null,function*(){let{userId:t,sessionId:o,stateDelta:r}=e,i=Ro(e.runConfig),s=e.newMessage,a=j.startSpan("invocation"),c=Ti.setSpan(Ai.active(),a);try{yield*q(J(c,this,function(){return p(this,null,function*(){var d;let l=yield new m(this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o}));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&&A(this.agent)){let R=this.agent.canonicalModel.model;if(!Se(R))throw new Error("CFC is not supported for model: ".concat(R," in agent: ").concat(this.agent.name));be(this.agent.codeExecutor)||(this.agent.codeExecutor=new Re)}let u=new K({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Ln(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),f=yield new m(this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u}));if(f&&(s=f),s){if(!((d=s.parts)!=null&&d.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new m(this.saveArtifacts(u.invocationId,l.userId,l.id,s))),yield new m(this.sessionService.appendEvent({session:l,event:E({invocationId:u.invocationId,author:"user",actions:r?V({stateDelta:r}):void 0,content:s})}))}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let R=yield new m(this.pluginManager.runBeforeRunCallback({invocationContext:u}));if(R){let b=E({invocationId:u.invocationId,author:"model",content:R});yield new m(this.sessionService.appendEvent({session:l,event:b})),yield b}else{try{for(var g=y(u.agent.runAsync(u)),h,x,v;h=!(x=yield new m(g.next())).done;h=!1){let b=x.value;b.partial||(yield new m(this.sessionService.appendEvent({session:l,event:b})));let L=yield new m(this.pluginManager.runOnEventCallback({invocationContext:u,event:b}));L?yield L:yield b}}catch(x){v=[x]}finally{try{h&&(x=g.return)&&(yield new m(x.call(g)))}finally{if(v)throw v[0]}}yield new m(this.pluginManager.runAfterRunCallback({invocationContext:u}))}}})}))}finally{a.end()}})}async saveArtifacts(e,t,o,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:o,filename:c,artifact:a}),r.parts[s]=Ei("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let o=Ri(e.events);if(o&&o.author)return t.findAgent(o.author)||t;for(let r=e.events.length-1;r>=0;r--){C.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){C.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(!A(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Ri(n){var o,r,i,s;if(!n.length)return null;let t=(s=(i=(r=(o=n[n.length-1].content)==null?void 0:o.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=n.length-2;a>=0;a--){let c=n[a],l=_(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var sn=class extends ce{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new we,sessionService:new ae,memoryService:new ie})}};import{Type as Ye}from"@google/genai";var Ke=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 an=Symbol.for("google.adk.agentTool");function bi(n){return typeof n=="object"&&n!==null&&an in n&&n[an]===!0}var jo,Ko,cn=class extends(Ko=P,jo=an,Ko){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[jo]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(A(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:Ye.OBJECT,properties:{request:{type:Ye.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=A(this.agent)&&this.agent.outputSchema;t.response=o?{type:Ye.OBJECT}:{type:Ye.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,d,R,b;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:A(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new ce({appName:this.agent.name,agent:this.agent,artifactService:new Ke(o),sessionService:(f=o.invocationContext.sessionService)!=null?f:new ae,memoryService:(d=o.invocationContext.memoryService)!=null?d:new ie,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()}),c;try{for(var g=y(s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i})),h,x,v;h=!(x=await g.next()).done;h=!1){let L=x.value;L.actions.stateDelta&&o.state.update(L.actions.stateDelta),c=L}}catch(x){v=[x]}finally{try{h&&(x=g.return)&&await x.call(g)}finally{if(v)throw v[0]}}if(!((b=(R=c==null?void 0:c.content)==null?void 0:R.parts)!=null&&b.length))return"";let l=A(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(L=>L.text).filter(L=>L).join("\n");return l?JSON.parse(u):u}};var ln=Symbol.for("google.adk.baseToolset");function Ii(n){return typeof n=="object"&&n!==null&&ln in n&&n[ln]===!0}var Yo;Yo=ln;var un=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[Yo]=!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 He=class extends P{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,""}},wi=new He;var We=class extends P{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||[],ro(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(oo(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(e.model))}}},Li=new We;import{Type as fn}from"@google/genai";var _i=at(),Pi=["image/","audio/","video/"],ki=new Set(["application/pdf"]),Oi=new Set(["application/csv","application/json","application/xml"]);function Ho(n){if(n)return n.split(";")[0].trim()}function Mi(n){let e=Ho(n);return e?Pi.some(t=>e.startsWith(t))||ki.has(e):!1}function Bi(n,e){let t=n.inlineData;if(!t||Mi(t.mimeType))return n;let o=Ho(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/")||Oi.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 Ze=class extends P{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:fn.OBJECT,properties:{artifact_names:{type:fn.ARRAY,items:{type:fn.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;B(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 g="user:".concat(u);f=await e.loadArtifact(g)}if(!f){_i.warn('Artifact "'.concat(u,'" not found, skipping'));continue}let d=Bi(f,u);t.contents.push({role:"user",parts:[{text:"Artifact ".concat(u," is:")},d]})}}}}}},Ni=new Ze;import{Type as Wo}from"@google/genai";var Qe=class extends P{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:Wo.OBJECT,properties:{query:{type:Wo.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&&B(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."])}},Fi=new Qe;var Zo="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",mn=class extends Y{constructor(e){super(z(T({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Zo:e.description=Zo.trimStart(),e}};var Je=class extends P{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){C.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 d=f.timestamp?"Time: ".concat(f.timestamp):"";d&&i.push(d);let g=(u=(l=f.content.parts)==null?void 0:l.map(h=>{var x;return(x=h.text)!=null?x:""}).join(" "))!=null?u:"";g&&i.push(f.author?"".concat(f.author,": ").concat(g):g)}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");B(e.llmRequest,[a])}},Di=new Je;export{Xe as ActiveStreamingTool,cn as AgentTool,pe as ApigeeLlm,No as AuthCredentialTypes,$ as BaseAgent,Te as BaseCodeExecutor,Xt as BaseExampleProvider,me as BaseLlm,M as BaseLlmRequestProcessor,At as BaseLlmResponseProcessor,se as BasePlugin,Pe as BaseSessionService,P as BaseTool,un as BaseToolset,Re as BuiltInCodeExecutor,ze as CONTENT_REQUEST_PROCESSOR,Ue as ContentRequestProcessor,O as Context,ge as ContextCompactorRequestProcessor,wi as EXIT_LOOP,Fo as EventType,He as ExitLoopTool,Y as FunctionTool,Li as GOOGLE_SEARCH,Z as Gemini,Fe as GoogleLLMVariant,We as GoogleSearchTool,we as InMemoryArtifactService,ie as InMemoryMemoryService,Ve as InMemoryPolicyEngine,sn as InMemoryRunner,ae as InMemorySessionService,K as InvocationContext,ee as LLMRegistry,Ni as LOAD_ARTIFACTS,Fi as LOAD_MEMORY,mt as LiveRequestQueue,$t as LlmAgent,Wt as LlmSummarizer,Ze as LoadArtifactsTool,Qe as LoadMemoryTool,Mn as LogLevel,en as LoggingPlugin,mn as LongRunningFunctionTool,zt as LoopAgent,Di as PRELOAD_MEMORY,jt as ParallelAgent,_e as PluginManager,Uo as PolicyOutcome,Je as PreloadMemoryTool,$o as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,k as ReadonlyContext,ce as Runner,nn as SecurityPlugin,Ht as SequentialAgent,S as State,qt as StreamingMode,Zt as TokenBasedContextCompactor,X as ToolConfirmation,Qt as TruncatingContextCompactor,E as createEvent,V as createEventActions,je as createSession,pr as functionsExportedForTestingOnly,qe as geminiInitParams,vi as getAskUserConfirmationFunctionCalls,_ as getFunctionCalls,N as getFunctionResponses,at as getLogger,xn as hasTrailingCodeExecutionResult,bi as isAgentTool,sr as isBaseAgent,gi as isBaseExampleProvider,dt as isBaseLlm,xt as isBaseTool,Ii as isBaseToolset,D as isCompactedEvent,H as isFinalResponse,Or as isFunctionTool,Se as isGemini2OrAbove,A as isLlmAgent,ri as isLoopAgent,ii as isParallelAgent,Si as isRunner,ci as isSequentialAgent,on as mergeStates,fr as setLogLevel,ur as setLogger,Ce as stringifyContent,di as toStructuredEvents,yi as trimTempDeltaState,ve as version,de as zodObjectToSchema};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Google LLC