@google/adk 0.2.0 → 0.2.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.
@@ -3,7 +3,7 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- const version = "0.2.0";
6
+ const version = "0.2.1";
7
7
  export {
8
8
  version
9
9
  };
@@ -3,4 +3,4 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- export declare const version = "0.2.0";
6
+ export declare const version = "0.2.1";
package/dist/web/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- var Dt=Object.defineProperty,Gt=Object.defineProperties;var qt=Object.getOwnPropertyDescriptors;var tt=Object.getOwnPropertySymbols;var Ut=Object.prototype.hasOwnProperty,jt=Object.prototype.propertyIsEnumerable;var xe=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var nt=(o,e,t)=>e in o?Dt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,b=(o,e)=>{for(var t in e||(e={}))Ut.call(e,t)&&nt(o,t,e[t]);if(tt)for(var t of tt(e))jt.call(e,t)&&nt(o,t,e[t]);return o},Y=(o,e)=>Gt(o,qt(e));var u=function(o,e){this[0]=o,this[1]=e},v=(o,e,t)=>{var n=(s,a,l,c)=>{try{var f=t[s](a),m=(a=f.value)instanceof u,A=f.done;Promise.resolve(m?a[0]:a).then(y=>m?n(s==="return"?s:"next",a[1]?{done:y.done,value:y.value}:y,l,c):l({value:y,done:A})).catch(y=>n("throw",y,l,c))}catch(y){c(y)}},r=s=>i[s]=a=>new Promise((l,c)=>n(s,a,l,c)),i={};return t=t.apply(o,e),i[xe("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var x=(o,e,t)=>(e=o[xe("asyncIterator")])?e.call(o):(o=o[xe("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,a,l)=>(i=r.call(o,i),l=i.done,Promise.resolve(i.value).then(c=>s({value:c,done:l}),a)))),t("next"),t("return"),e);import{trace as at}from"@opentelemetry/api";function U(o={}){return b({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function ot(o,e){let t=U();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function w(o={}){return Y(b({},o),{id:o.id||Ee(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||U(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function H(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:L(o).length===0&&_(o).length===0&&!o.partial&&!it(o)}function L(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function _(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function it(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function Kt(o){var e;return(e=o.content)!=null&&e.parts?o.content.parts.map(t=>{var n;return(n=t.text)!=null?n:""}).join(""):""}var rt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Ee(){let o="";for(let e=0;e<8;e++)o+=rt[Math.floor(Math.random()*rt.length)];return o}var E=class{constructor(e,t){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta=b(b({},this.delta),e),this.value=b(b({},this.value),e)}toRecord(){return b(b({},this.value),this.delta)}};E.APP_PREFIX="app:",E.USER_PREFIX="user:",E.TEMP_PREFIX="temp:";var B=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new E(this.invocationContext.session.state,{})}};var N=class extends B{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||U(),this._state=new E(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function Te(){return typeof window<"u"}var ce="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function J(){let o="";for(let e=0;e<ce.length;e++){let t=Math.random()*16|0;ce[e]==="x"?o+=t.toString(16):ce[e]==="y"?o+=(t&3|8).toString(16):o+=ce[e]}return o}var Se=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"))}},D=class{constructor(e){this.invocationCostManager=new Se;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 st(){return"e-".concat(J())}var F=class{constructor(e){this.name=Zt(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=zt(this),this.beforeAgentCallback=lt(e.beforeAgentCallback),this.afterAgentCallback=lt(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return v(this,null,function*(){let t=at.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let a=this.createInvocationContext(e),l=yield new u(this.handleBeforeAgentCallback(a));if(l&&(yield l),a.endInvocation)return;try{for(var n=x(this.runAsyncImpl(a)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let f=i.value;yield f}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a.endInvocation)return;let c=yield new u(this.handleAfterAgentCallback(a));c&&(yield c)}finally{t.end()}})}runLive(e){return v(this,null,function*(){let t=at.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new D(Y(b({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,w({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return w({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return w({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return w({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 Zt(o){if(!Vt(o))throw new Error('Found invalid agent name: "'.concat(o,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.'));if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function Vt(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function zt(o){for(;o.parentAgent;)o=o.parentAgent;return o}function lt(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Ht}from"@google/genai";var re=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".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 V=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var j=class extends N{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new re(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new re(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 V({hint:e,confirmed:!1,payload:t})}};var ct=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(ct||{}),ee=1;function Wt(o){ee=o}var Re=class{log(e,...t){if(!(e<ee))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error("Unsupported log level: ".concat(e))}}debug(...e){ee>0||console.debug(ue(0),...e)}info(...e){ee>1||console.info(ue(1),...e)}warn(...e){ee>2||console.warn(ue(2),...e)}error(...e){ee>3||console.error(ue(3),...e)}},Qt={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Xt={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Yt="\x1B[0m";function ue(o){return"".concat(Xt[o],"[ADK ").concat(Qt[o],"]:").concat(Yt)}var g=new Re;var Ie="adk-",fe="adk_request_credential",te="adk_request_confirmation",Jt={handleFunctionCallList:de};function we(){return"".concat(Ie).concat(J())}function ut(o){let e=L(o);if(e)for(let t of e)t.id||(t.id=we())}function ft(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ie)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ie)&&(e.functionResponse.id=void 0)}function dt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function mt(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:fe,args:{function_call_id:i,auth_config:s},id:we()};n.add(a.id),t.push({functionCall:a})}return w({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function pt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=L(e);for(let[l,c]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(A=>A.id===l))!=null?a:void 0;if(!f)continue;let m={name:te,args:{originalFunctionCall:f,toolConfirmation:c},id:we()};r.add(m.id),n.push({functionCall:m})}return w({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function en(o,e,t){return g.debug("callToolAsync ".concat(o.name)),await o.runAsync({args:e,toolContext:t})}async function gt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=L(e);return await de({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function de({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],l=e.filter(m=>!i||m.id&&i.has(m.id));for(let m of l){let A;s&&m.id&&(A=s[m.id]);let{tool:y,toolContext:p}=tn({invocationContext:o,functionCall:m,toolsDict:t,toolConfirmation:A});g.debug("execute_tool ".concat(y.name));let h=(f=m.args)!=null?f:{},d=null,C;if(d=await o.pluginManager.runBeforeToolCallback({tool:y,toolArgs:h,toolContext:p}),d==null){for(let k of n)if(d=await k({tool:y,args:h,context:p}),d)break}if(d==null)try{d=await en(y,h,p)}catch(k){if(k instanceof Error){let M=await o.pluginManager.runOnToolErrorCallback({tool:y,toolArgs:h,toolContext:p,error:k});M?d=M:C=k.message}else C=k}let R=await o.pluginManager.runAfterToolCallback({tool:y,toolArgs:h,toolContext:p,result:d});if(R==null){for(let k of r)if(R=await k({tool:y,args:h,context:p,response:d}),R)break}if(R!=null&&(d=R),y.isLongRunning&&!d)continue;C?d={error:C}:(typeof d!="object"||d==null)&&(d={result:d});let I=w({invocationId:o.invocationId,author:o.agent.name,content:Ht({functionResponse:{id:p.functionCallId,name:y.name,response:d}}),actions:p.actions,branch:o.branch});g.debug("traceToolCall",{tool:y.name,args:h,functionResponseEvent:I.id}),a.push(I)}if(!a.length)return null;let c=nn(a);return a.length>1&&(g.debug("execute_tool (merged)"),g.debug("traceMergedToolCalls",{responseEventId:c.id,functionResponseEvent:c.id})),c}function tn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new j({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function nn(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=ot(n);return w({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ke=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return v(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as wt}from"zod";var Le="0.2.0";var on="google-adk",rn="gl-typescript",sn="remote_reasoning_engine",an="GOOGLE_CLOUD_AGENT_ENGINE_ID";function ln(){let o="".concat(on,"/").concat(Le);!Te()&&process.env[an]&&(o="".concat(o,"+").concat(sn));let e="".concat(rn,"/").concat(Te()?window.navigator.userAgent:process.version);return[o,e]}function ht(){return ln()}var K=class{constructor({model:e}){this.model=e}get trackingHeaders(){let t=ht().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."}]})}};K.supportedModels=[];function ie(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function Ct(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as yt,FinishReason as fn,GoogleGenAI as Be}from"@google/genai";function vt(){return cn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function cn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var me=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(n=>{var r;return n.parts&&((r=n.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):g.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(n=>n.functionResponse).filter(n=>!!n);g.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else g.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){g.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return v(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function Pe(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var ne=class extends K{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!n,!this.vertexai&&a){let l=process.env.GOOGLE_GENAI_USE_VERTEXAI;l&&(this.vertexai=l.toLowerCase()==="true"||l==="1")}if(this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}generateContentAsync(e,t=!1){return v(this,null,function*(){var n,r,i,s,m,A,y;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),g.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=b(b({},e.config.httpOptions.headers),this.trackingHeaders)),t){let p=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),h="",d="",C,R;try{for(var a=x(p),l,c,f;l=!(c=yield new u(a.next())).done;l=!1){let I=c.value;R=I;let k=Pe(I);C=k.usageMetadata;let M=(s=(i=k.content)==null?void 0:i.parts)==null?void 0:s[0];if(M!=null&&M.text)"thought"in M&&M.thought?h+=M.text:d+=M.text,k.partial=!0;else if((h||d)&&(!M||!M.inlineData)){let be=[];h&&be.push({text:h,thought:!0}),d&&be.push(yt(d)),yield{content:{role:"model",parts:be},usageMetadata:k.usageMetadata},h="",d=""}yield k}}catch(c){f=[c]}finally{try{l&&(c=a.return)&&(yield new u(c.call(a)))}finally{if(f)throw f[0]}}if((d||h)&&((A=(m=R==null?void 0:R.candidates)==null?void 0:m[0])==null?void 0:A.finishReason)===fn.STOP){let I=[];h&&I.push({text:h,thought:!0}),d&&I.push({text:d}),yield{content:{role:"model",parts:I},usageMetadata:C}}}else{let p=yield new u(this.apiClient.models.generateContent({model:(y=e.model)!=null?y:this.model,contents:e.contents,config:e.config}));yield Pe(p)}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=b(b({},this.trackingHeaders),this.headers);return this.vertexai?this._apiClient=new Be({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new Be({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new Be({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[yt(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 me(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)At(n.inlineData),At(n.fileData)}}};ne.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function At(o){o&&o.displayName&&(o.displayName=void 0)}var Me=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},O=class O{static newLlm(e){return new(O.resolve(e))({model:e})}static _register(e,t){O.llmRegistryDict.has(e)&&g.info("Updating LLM class for ".concat(e," from ").concat(O.llmRegistryDict.get(e)," to ").concat(t)),O.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)O._register(t,e)}static resolve(e){let t=O.resolveCache.get(e);if(t)return t;for(let[n,r]of O.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return O.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};O.llmRegistryDict=new Map,O.resolveCache=new Me(32);var oe=O;oe.register(ne);var $=class{constructor(e){var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=dn(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return vt()}};function dn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as mn}from"@google/genai";import{ZodObject as pn}from"zod";import{Type as P}from"@google/genai";import{z as T}from"zod";function bt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function G(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case T.ZodFirstPartyTypeKind.ZodString:n.type=P.STRING;for(let l of e.checks||[])l.kind==="min"?n.minLength=l.value.toString():l.kind==="max"?n.maxLength=l.value.toString():l.kind==="email"?n.format="email":l.kind==="uuid"?n.format="uuid":l.kind==="url"?n.format="uri":l.kind==="regex"&&(n.pattern=l.regex.source);return r(n);case T.ZodFirstPartyTypeKind.ZodNumber:n.type=P.NUMBER;for(let l of e.checks||[])l.kind==="min"?n.minimum=l.value:l.kind==="max"?n.maximum=l.value:l.kind==="int"&&(n.type=P.INTEGER);return r(n);case T.ZodFirstPartyTypeKind.ZodBoolean:return n.type=P.BOOLEAN,r(n);case T.ZodFirstPartyTypeKind.ZodArray:return n.type=P.ARRAY,n.items=G(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case T.ZodFirstPartyTypeKind.ZodObject:return pe(o);case T.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=P.STRING;else if(i==="number")n.type=P.NUMBER;else if(i==="boolean")n.type=P.BOOLEAN;else if(e.value===null)n.type=P.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case T.ZodFirstPartyTypeKind.ZodEnum:return n.type=P.STRING,n.enum=e.values,r(n);case T.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=P.STRING,n.enum=Object.values(e.values),r(n);case T.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(G),r(n);case T.ZodFirstPartyTypeKind.ZodOptional:return G(e.innerType);case T.ZodFirstPartyTypeKind.ZodNullable:let s=G(e.innerType);return r(s?b({anyOf:[s,{type:P.NULL}]},t&&{description:t}):b({type:P.NULL},t&&{description:t}));case T.ZodFirstPartyTypeKind.ZodDefault:let a=G(e.innerType);return a&&(a.default=e.defaultValue()),a;case T.ZodFirstPartyTypeKind.ZodBranded:return G(e.type);case T.ZodFirstPartyTypeKind.ZodReadonly:return G(e.innerType);case T.ZodFirstPartyTypeKind.ZodNull:return n.type=P.NULL,r(n);case T.ZodFirstPartyTypeKind.ZodAny:case T.ZodFirstPartyTypeKind.ZodUnknown:return r(b({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function pe(o){if(o._def.typeName!==T.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],l=G(a);l&&(t[s]=l);let c=a,f=!1;for(;c._def.typeName===T.ZodFirstPartyTypeKind.ZodOptional||c._def.typeName===T.ZodFirstPartyTypeKind.ZodDefault;)f=!0,c=c._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==T.ZodFirstPartyTypeKind.ZodNever?i=G(r)||!0:i=o._def.unknownKeys==="passthrough",b({type:P.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function gn(o){return o===void 0?{type:mn.OBJECT,properties:{}}:bt(o)?pe(o):o}var q=class extends ${constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:gn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof pn&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var Z=class{};function se(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function _e(o,e,t){var s,a,l;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||((l=(a=c.content.parts)==null?void 0:a[0])==null?void 0:l.text)===""||t&&c.branch&&!t.startsWith(c.branch)||hn(c)||Cn(c)||n.push(Tt(e,c)?vn(c):c);let r=yn(n);r=An(r);let i=[];for(let c of r){let f=se(c.content);ft(f),i.push(f)}return i}function Et(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Tt(e,r))return _e(o.slice(n),e,t)}return[]}function hn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===fe||((n=r.functionResponse)==null?void 0:n.name)===fe)return!0;return!1}function Cn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===te||((n=r.functionResponse)==null?void 0:n.name)===te)return!0;return!1}function Tt(o,e){return!!o&&e.author!==o&&e.author!=="user"}function vn(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let l of o.content.parts)if(l.text&&!l.thought)(r=e.parts)==null||r.push({text:"[".concat(o.author,"] said: ").concat(l.text)});else if(l.functionCall){let c=xt(l.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(l.functionCall.name,"` with parameters: ").concat(c)})}else if(l.functionResponse){let c=xt(l.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(l.functionResponse.name,"` returned result: ").concat(c)})}else(a=e.parts)==null||a.push(l);return w({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function St(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=w(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function yn(o){if(o.length===0)return o;let e=o[o.length-1],t=_(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(l=>!!l.id).map(l=>l.id)),r=o.at(-2);if(r){let l=L(r);if(l){for(let c of l)if(c.id&&n.has(c.id))return o}}let i=-1;for(let l=o.length-2;l>=0;l--){let c=o[l],f=L(c);if(f!=null&&f.length){for(let m of f)if(m.id&&n.has(m.id)){i=l;let A=new Set(f.map(p=>p.id).filter(p=>!!p));if(!Array.from(n).every(p=>A.has(p)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(A).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=A;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let l=i+1;l<o.length-1;l++){let c=o[l],f=_(c);f&&f.some(m=>m.id&&n.has(m.id))&&s.push(c)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(St(s)),a}function An(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=_(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(_(n).length>0)continue;let r=L(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((l,c)=>l-c).map(l=>o[l]);t.push(St(a))}}else t.push(n)}return t}function xt(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function Ne(o,e){let t=e.invocationContext;async function n(l){let c=l[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=c.endsWith("?");if(f&&(c=c.slice(0,-1)),c.startsWith("artifact.")){let m=c.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let A=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:m});if(!A)throw new Error("Artifact ".concat(m," not found."));return String(A)}if(!En(c))return l[0];if(c in t.session.state)return String(t.session.state[c]);if(f)return"";throw new Error("Context variable not found: `".concat(c,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let l of a){i.push(o.slice(s,l.index));let c=await n(l);i.push(c),s=l.index+l[0].length}return i.push(o.slice(s)),i.join("")}var bn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Rt(o){return o===""||o===void 0?!1:bn.test(o)}var xn=[E.APP_PREFIX,E.USER_PREFIX,E.TEMP_PREFIX];function En(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Rt(o):xn.includes(e[0]+":")?Rt(e[1]):!1}var Oe=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Oe||{});function It(o={}){return b({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Tn(o.maxLlmCalls||500)},o)}function Tn(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return o<=0&&g.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),o}var kt="adk_agent_name";async function Lt(o,e){return o instanceof $?[o]:await o.getTools(e)}var Fe=class extends Z{runAsync(e,t){return v(this,null,function*(){var r;let n=e.agent;n instanceof S&&(t.model=n.canonicalModel.model,t.config=b({},(r=n.generateContentConfig)!=null?r:{}),n.outputSchema&&Ct(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},Sn=new Fe,$e=class extends Z{runAsync(e,t){return v(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),ie(t,r)})}},Rn=new $e,De=class extends Z{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof S)||!(n.rootAgent instanceof S))return;let r=n.rootAgent;if(r instanceof S&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new B(e))),a=i;s&&(a=yield new u(Ne(i,new B(e)))),ie(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new B(e))),a=i;s&&(a=yield new u(Ne(i,new B(e)))),ie(t,[a])}})}},In=new De,Ge=class{runAsync(e,t){return v(this,null,function*(){let n=e.agent;!n||!(n instanceof S)||(n.includeContents==="default"?t.contents=_e(e.session.events,n.name,e.branch):t.contents=Et(e.session.events,n.name,e.branch))})}},wn=new Ge,qe=class extends Z{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new q({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:wt.object({agentName:wt.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,n){return v(this,null,function*(){if(!(t.agent instanceof S))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;ie(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new j({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).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 n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof S)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},kn=new qe,Ue=class extends Z{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof S))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let a=r.length-1;a>=0;a--){let l=r[a];if(l.author!=="user")continue;let c=_(l);if(!c)continue;let f=!1;for(let m of c){if(m.name!==te)continue;f=!0;let A=null;m.response&&Object.keys(m.response).length===1&&"response"in m.response?A=JSON.parse(m.response.response):m.response&&(A=new V({hint:m.response.hint,payload:m.response.payload,confirmed:m.response.confirmed})),m.id&&A&&(i[m.id]=A)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let l=r[a],c=L(l);if(!c)continue;let f={},m={};for(let h of c){if(!h.id||!(h.id in i))continue;let d=h.args;if(!d||!("originalFunctionCall"in d))continue;let C=d.originalFunctionCall;C.id&&(f[C.id]=i[h.id],m[C.id]=C)}if(Object.keys(f).length===0)continue;for(let h=r.length-1;h>s;h--){let d=r[h],C=_(d);if(C){for(let R of C)R.id&&R.id in f&&(delete f[R.id],delete m[R.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let A=yield new u(n.canonicalTools(new B(e))),y=Object.fromEntries(A.map(h=>[h.name,h])),p=yield new u(de({invocationContext:e,functionCalls:Object.values(m),toolsDict:y,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f}));p&&(yield p);return}})}},Ln=new Ue,S=class o extends F{constructor(e){var n,r,i,s,a,l,c,f,m;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(l=e.includeContents)!=null?l:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.requestProcessors=(c=e.requestProcessors)!=null?c:[Sn,Rn,In,Ln,wn],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((m=this.subAgents)!=null&&m.length)||this.requestProcessors.push(kn),e.generateContentConfig){if(e.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(e.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(e.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};if(this.outputSchema){if((!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(g.warn("Invalid config for agent ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, subAgents must be empty to disable agent transfer."));if(this.tools&&this.tools.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(this.model instanceof K)return this.model;if(typeof this.model=="string"&&this.model)return oe.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await Lt(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){g.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){g.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!H(e)){g.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){g.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){g.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return v(this,null,function*(){for(;;){let s;try{for(var t=x(this.runOneStepAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;s=a,this.maybeSaveOutputToState(a),yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}if(!s||H(s))break;if(s.partial){g.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return v(this,null,function*(){try{for(var t=x(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return v(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return v(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let d of this.requestProcessors)try{for(var r=x(d.runAsync(e,t)),i,s,a;i=!(s=yield new u(r.next())).done;i=!1){let C=s.value;yield C}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(a)throw a[0]}}for(let d of this.tools){let C=new j({invocationContext:e}),R=yield new u(Lt(d,new B(e)));for(let I of R)yield new u(I.processLlmRequest({toolContext:C,llmRequest:t}))}if(e.endInvocation)return;let n=w({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var A=x(this.callLlmAsync(e,t,n)),y,p,h;y=!(p=yield new u(A.next())).done;y=!1){let d=p.value;try{for(var l=x(this.postprocess(e,t,d,n)),c,f,m;c=!(f=yield new u(l.next())).done;c=!1){let C=f.value;n.id=Ee(),n.timestamp=new Date().getTime(),yield C}}catch(f){m=[f]}finally{try{c&&(f=l.return)&&(yield new u(f.call(l)))}finally{if(m)throw m[0]}}}}catch(p){h=[p]}finally{try{y&&(p=A.return)&&(yield new u(p.call(A)))}finally{if(h)throw h[0]}}})}postprocess(e,t,n,r){return v(this,null,function*(){var p;for(let I of this.responseProcessors)try{for(var f=x(I.runAsync(e,n)),m,A,y;m=!(A=yield new u(f.next())).done;m=!1){let k=A.value;yield k}}catch(A){y=[A]}finally{try{m&&(A=f.return)&&(yield new u(A.call(f)))}finally{if(y)throw y[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=w(b(b({},r),n));if(i.content){let I=L(i);I!=null&&I.length&&(ut(i),i.longRunningToolIds=Array.from(dt(I,t.toolsDict)))}if(yield i,!((p=L(i))!=null&&p.length))return;let s=yield new u(gt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let a=mt(e,s);a&&(yield a);let l=pt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});l&&(yield l),yield s;let c=s.actions.transferToAgent;if(c){let I=this.getAgentByName(e,c);try{for(var h=x(I.runAsync(e)),d,C,R;d=!(C=yield new u(h.next())).done;d=!1){let k=C.value;yield k}}catch(C){R=[C]}finally{try{d&&(C=h.return)&&(yield new u(C.call(h)))}finally{if(R)throw R[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return v(this,null,function*(){var s,a,l,c,f;let r=yield new u(this.handleBeforeModelCallback(e,t,n));if(r){yield r;return}(s=t.config)!=null||(t.config={}),(l=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[kt]||(t.config.labels[kt]=this.name);let i=this.canonicalModel;if((c=e.runConfig)!=null&&c.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let h=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");try{for(var m=x(this.runAndHandleError(h,e,t,n)),A,y,p;A=!(y=yield new u(m.next())).done;A=!1){let d=y.value;let C=yield new u(this.handleAfterModelCallback(e,d,n));yield C!=null?C:d}}catch(y){p=[y]}finally{try{A&&(y=m.return)&&(yield new u(y.call(m)))}finally{if(p)throw p[0]}}}})}async handleBeforeModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let a=await s({context:r,request:t});if(a)return a}}async handleAfterModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let a=await s({context:r,response:t});if(a)return a}}runAndHandleError(e,t,n,r){return v(this,null,function*(){try{try{for(var i=x(e),s,a,l;s=!(a=yield new u(i.next())).done;s=!1){let c=a.value;yield c}}catch(a){l=[a]}finally{try{s&&(a=i.return)&&(yield new u(a.call(i)))}finally{if(l)throw l[0]}}}catch(c){let f=new N({invocationContext:t,eventActions:r.actions});if(c instanceof Error){let m=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:n,error:c}));if(m)yield m;else{let A=JSON.parse(c.message);yield{errorCode:String(A.error.code),errorMessage:A.error.message}}}else throw g.error("Unknown error during response generation",c),c}})}};var je=class extends F{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return v(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let a of this.subAgents){let l=!1;try{for(var n=x(a.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c,c.actions.escalate&&(l=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(l)return}t++}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var Ke=class extends F{runAsyncImpl(e){return v(this,null,function*(){let t=this.subAgents.map(a=>a.runAsync(Pn(this,a,e)));try{for(var n=x(Bn(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function Pn(o,e,t){let n=new D(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function Bn(o){return v(this,null,function*(){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=yield new u(Promise.race(e.values()));if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}})}var Ze="task_completed",Ve=class extends F{runAsyncImpl(e){return v(this,null,function*(){for(let s of this.subAgents)try{for(var t=x(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return v(this,null,function*(){for(let s of this.subAgents)s instanceof S&&((yield new u(s.canonicalTools(new B(e)))).some(c=>c.name===Ze)||(s.tools.push(new q({name:Ze,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(Ze," 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 s of this.subAgents)try{for(var t=x(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var ae=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=ge(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=ge(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(t,"/user/"),s=[];for(let a in this.artifacts)if(a.startsWith(r)){let l=a.replace(r,"");s.push(l)}else if(a.startsWith(i)){let l=a.replace(i,"");s.push(l)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=ge(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=ge(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let l=0;l<s.length;l++)a.push(l);return Promise.resolve(a)}};function ge(o,e,t,n){return Mn(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function Mn(o){return o.startsWith("user:")}var z=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Pt(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=Pt(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let l of a){if(!((s=(i=l.content)==null?void 0:i.parts)!=null&&s.length))continue;let c=l.content.parts.map(A=>A.text).filter(A=>!!A).join(" "),f=_n(c);if(!f.size)continue;n.some(A=>f.has(A))&&r.memories.push({content:l.content,author:l.author,timestamp:Nn(l.timestamp)})}return r}};function Pt(o,e){return"".concat(o,"/").concat(e)}function _n(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Nn(o){return new Date(o).toISOString()}var W=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var ze=class extends W{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".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((n=e.agent.name)!=null?n:"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({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(H(t)));let n=L(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=_(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.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({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"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:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");g.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let n=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),n.push("text: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var le=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),g.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return g.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw g.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,n=>n.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,n=>n.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:n}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:n}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,n=>n.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,n=>n.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}),"onToolErrorCallback")}};var Mt="adk_request_confirmation",We="orcas_tool_call_security_check_states",Bt="This tool call needs external confirmation before completion.",_t=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(_t||{}),he=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Qe=class extends W{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new he}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:Bt};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(We))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(We))!=null?i:{};r[n]=t,e.state.set(We,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Bt};case"ALLOW":return;default:return}}};function On(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Mt&&e.push(t.functionCall);return e}var Ce=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[n,r]of Object.entries(t.actions.stateDelta))n.startsWith(E.TEMP_PREFIX)||(e.state[n]=r)}};function ve(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var Q=class extends Ce{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=ve({id:i||J(),appName:t,userId:n,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][n]||(this.sessions[t][n]={}),this.sessions[t][n][s.id]=s,Promise.resolve(this.mergeState(t,n,se(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=se(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 Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(ve({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=c=>{g.warn("Failed to append event to session ".concat(s,": ").concat(c))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let c of Object.keys(n.actions.stateDelta))c.startsWith(E.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][c.replace(E.APP_PREFIX,"")]=n.actions.stateDelta[c]),c.startsWith(E.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][c.replace(E.USER_PREFIX,"")]=n.actions.stateDelta[c]);let l=this.sessions[r][i][s];return await super.appendEvent({session:l,event:n}),l.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[E.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[E.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as Fn}from"@google/genai";import{trace as $n}from"@opentelemetry/api";var X=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new le((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return v(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var l;i=It(i);let a=$n.getTracer("gcp.vertex.agent").startSpan("invocation");try{let y=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!y)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof S){let C=this.agent.canonicalModel.model;if(!C.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(C," in agent: ").concat(this.agent.name))}let p=new D({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:st(),agent:this.agent,session:y,userContent:n,runConfig:i,pluginManager:this.pluginManager}),h=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:p}));if(h&&(n=h),n){if(!((l=n.parts)!=null&&l.length))throw new Error("No parts in the new_message.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(p.invocationId,y.userId,y.id,n))),yield new u(this.sessionService.appendEvent({session:y,event:w({invocationId:p.invocationId,author:"user",actions:r?U({stateDelta:r}):void 0,content:n})}))}p.agent=this.determineAgentForResumption(y,this.agent);let d=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:p}));if(d){let C=w({invocationId:p.invocationId,author:"model",content:d});yield new u(this.sessionService.appendEvent({session:y,event:C})),yield C}else try{for(var c=x(p.agent.runAsync(p)),f,m,A;f=!(m=yield new u(c.next())).done;f=!1){let C=m.value;C.partial||(yield new u(this.sessionService.appendEvent({session:y,event:C})));let R=yield new u(this.pluginManager.runOnEventCallback({invocationContext:p,event:C}));R?yield R:yield C}}catch(m){A=[m]}finally{try{f&&(m=c.return)&&(yield new u(m.call(c)))}finally{if(A)throw A[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:p}))}finally{a.end()}})}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let l="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:l,artifact:a}),r.parts[s]=Fn("Uploaded file: ".concat(l,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Dn(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){g.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){g.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof S)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Dn(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let l=o[a],c=L(l);if(c){for(let f of c)if(f.id===t)return l}}return null}var Xe=class extends X{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new ae,sessionService:new Q,memoryService:new z})}};import{Type as Ae}from"@google/genai";var ye=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(e){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var Ye=class extends ${constructor(e){super({name:e.agent.name,description:e.agent.description||""}),this.agent=e.agent,this.skipSummarization=e.skipSummarization||!1}_getDeclaration(){let e;if(this.agent instanceof S&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Ae.OBJECT,properties:{request:{type:Ae.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof S&&this.agent.outputSchema;e.response=t?{type:Ae.OBJECT}:{type:Ae.STRING}}return e}async runAsync({args:e,toolContext:t}){var p,h;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof S&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new X({appName:this.agent.name,agent:this.agent,artifactService:new ye(t),sessionService:new Q,memoryService:new z,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;try{for(var f=x(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),m,A,y;m=!(A=await f.next()).done;m=!1){let d=A.value;d.actions.stateDelta&&t.state.update(d.actions.stateDelta),a=d}}catch(A){y=[A]}finally{try{m&&(A=f.return)&&await A.call(f)}finally{if(y)throw y[0]}}if(!((h=(p=a==null?void 0:a.content)==null?void 0:p.parts)!=null&&h.length))return"";let l=this.agent instanceof S&&this.agent.outputSchema,c=a.content.parts.map(d=>d.text).filter(d=>d).join("\n");return l?JSON.parse(c):c}};var He=class{constructor(e){this.toolFilter=e}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var Gn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Nt(o){let e=o.match(Gn);return e?e[1]:o}function Ot(o){return Nt(o).startsWith("gemini-")}function Ft(o){return Nt(o).startsWith("gemini-1")}var Je=class extends ${constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.config=t.config||{},t.config.tools=t.config.tools||[],Ft(t.model)){if(t.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");t.config.tools.push({googleSearchRetrieval:{}});return}if(Ot(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},qn=new Je;var $t="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",et=class extends q{constructor(e){super(Y(b({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=$t:e.description=$t.trimStart(),e}};export{Ye as AgentTool,F as BaseAgent,K as BaseLlm,W as BasePlugin,Ce as BaseSessionService,$ as BaseTool,He as BaseToolset,N as CallbackContext,q as FunctionTool,qn as GOOGLE_SEARCH,ne as Gemini,ae as InMemoryArtifactService,z as InMemoryMemoryService,he as InMemoryPolicyEngine,Xe as InMemoryRunner,Q as InMemorySessionService,D as InvocationContext,oe as LLMRegistry,ke as LiveRequestQueue,S as LlmAgent,ct as LogLevel,ze as LoggingPlugin,et as LongRunningFunctionTool,je as LoopAgent,Ke as ParallelAgent,le as PluginManager,_t as PolicyOutcome,Mt as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,X as Runner,Qe as SecurityPlugin,Ve as SequentialAgent,E as State,Oe as StreamingMode,V as ToolConfirmation,j as ToolContext,w as createEvent,U as createEventActions,ve as createSession,Jt as functionsExportedForTestingOnly,On as getAskUserConfirmationFunctionCalls,L as getFunctionCalls,_ as getFunctionResponses,it as hasTrailingCodeExecutionResult,H as isFinalResponse,Wt as setLogLevel,Kt as stringifyContent,Le as version,pe as zodObjectToSchema};
7
+ var Dt=Object.defineProperty,Gt=Object.defineProperties;var qt=Object.getOwnPropertyDescriptors;var tt=Object.getOwnPropertySymbols;var Ut=Object.prototype.hasOwnProperty,jt=Object.prototype.propertyIsEnumerable;var xe=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var nt=(o,e,t)=>e in o?Dt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,b=(o,e)=>{for(var t in e||(e={}))Ut.call(e,t)&&nt(o,t,e[t]);if(tt)for(var t of tt(e))jt.call(e,t)&&nt(o,t,e[t]);return o},Y=(o,e)=>Gt(o,qt(e));var u=function(o,e){this[0]=o,this[1]=e},v=(o,e,t)=>{var n=(s,a,l,c)=>{try{var f=t[s](a),m=(a=f.value)instanceof u,A=f.done;Promise.resolve(m?a[0]:a).then(y=>m?n(s==="return"?s:"next",a[1]?{done:y.done,value:y.value}:y,l,c):l({value:y,done:A})).catch(y=>n("throw",y,l,c))}catch(y){c(y)}},r=s=>i[s]=a=>new Promise((l,c)=>n(s,a,l,c)),i={};return t=t.apply(o,e),i[xe("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var x=(o,e,t)=>(e=o[xe("asyncIterator")])?e.call(o):(o=o[xe("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,a,l)=>(i=r.call(o,i),l=i.done,Promise.resolve(i.value).then(c=>s({value:c,done:l}),a)))),t("next"),t("return"),e);import{trace as at}from"@opentelemetry/api";function U(o={}){return b({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function ot(o,e){let t=U();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function w(o={}){return Y(b({},o),{id:o.id||Ee(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||U(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function H(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:L(o).length===0&&_(o).length===0&&!o.partial&&!it(o)}function L(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function _(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function it(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function Kt(o){var e;return(e=o.content)!=null&&e.parts?o.content.parts.map(t=>{var n;return(n=t.text)!=null?n:""}).join(""):""}var rt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Ee(){let o="";for(let e=0;e<8;e++)o+=rt[Math.floor(Math.random()*rt.length)];return o}var E=class{constructor(e,t){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta=b(b({},this.delta),e),this.value=b(b({},this.value),e)}toRecord(){return b(b({},this.value),this.delta)}};E.APP_PREFIX="app:",E.USER_PREFIX="user:",E.TEMP_PREFIX="temp:";var B=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new E(this.invocationContext.session.state,{})}};var N=class extends B{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||U(),this._state=new E(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function Te(){return typeof window<"u"}var ce="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function J(){let o="";for(let e=0;e<ce.length;e++){let t=Math.random()*16|0;ce[e]==="x"?o+=t.toString(16):ce[e]==="y"?o+=(t&3|8).toString(16):o+=ce[e]}return o}var Se=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"))}},D=class{constructor(e){this.invocationCostManager=new Se;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 st(){return"e-".concat(J())}var F=class{constructor(e){this.name=Zt(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=zt(this),this.beforeAgentCallback=lt(e.beforeAgentCallback),this.afterAgentCallback=lt(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return v(this,null,function*(){let t=at.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let a=this.createInvocationContext(e),l=yield new u(this.handleBeforeAgentCallback(a));if(l&&(yield l),a.endInvocation)return;try{for(var n=x(this.runAsyncImpl(a)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let f=i.value;yield f}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a.endInvocation)return;let c=yield new u(this.handleAfterAgentCallback(a));c&&(yield c)}finally{t.end()}})}runLive(e){return v(this,null,function*(){let t=at.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new D(Y(b({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,w({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return w({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return w({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return w({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 Zt(o){if(!Vt(o))throw new Error('Found invalid agent name: "'.concat(o,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.'));if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function Vt(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function zt(o){for(;o.parentAgent;)o=o.parentAgent;return o}function lt(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Ht}from"@google/genai";var re=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".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 V=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var j=class extends N{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new re(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new re(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 V({hint:e,confirmed:!1,payload:t})}};var ct=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(ct||{}),ee=1;function Wt(o){ee=o}var Re=class{log(e,...t){if(!(e<ee))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error("Unsupported log level: ".concat(e))}}debug(...e){ee>0||console.debug(ue(0),...e)}info(...e){ee>1||console.info(ue(1),...e)}warn(...e){ee>2||console.warn(ue(2),...e)}error(...e){ee>3||console.error(ue(3),...e)}},Qt={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Xt={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Yt="\x1B[0m";function ue(o){return"".concat(Xt[o],"[ADK ").concat(Qt[o],"]:").concat(Yt)}var g=new Re;var Ie="adk-",fe="adk_request_credential",te="adk_request_confirmation",Jt={handleFunctionCallList:de};function we(){return"".concat(Ie).concat(J())}function ut(o){let e=L(o);if(e)for(let t of e)t.id||(t.id=we())}function ft(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ie)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ie)&&(e.functionResponse.id=void 0)}function dt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function mt(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:fe,args:{function_call_id:i,auth_config:s},id:we()};n.add(a.id),t.push({functionCall:a})}return w({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function pt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=L(e);for(let[l,c]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(A=>A.id===l))!=null?a:void 0;if(!f)continue;let m={name:te,args:{originalFunctionCall:f,toolConfirmation:c},id:we()};r.add(m.id),n.push({functionCall:m})}return w({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function en(o,e,t){return g.debug("callToolAsync ".concat(o.name)),await o.runAsync({args:e,toolContext:t})}async function gt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=L(e);return await de({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function de({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],l=e.filter(m=>!i||m.id&&i.has(m.id));for(let m of l){let A;s&&m.id&&(A=s[m.id]);let{tool:y,toolContext:p}=tn({invocationContext:o,functionCall:m,toolsDict:t,toolConfirmation:A});g.debug("execute_tool ".concat(y.name));let h=(f=m.args)!=null?f:{},d=null,C;if(d=await o.pluginManager.runBeforeToolCallback({tool:y,toolArgs:h,toolContext:p}),d==null){for(let k of n)if(d=await k({tool:y,args:h,context:p}),d)break}if(d==null)try{d=await en(y,h,p)}catch(k){if(k instanceof Error){let M=await o.pluginManager.runOnToolErrorCallback({tool:y,toolArgs:h,toolContext:p,error:k});M?d=M:C=k.message}else C=k}let R=await o.pluginManager.runAfterToolCallback({tool:y,toolArgs:h,toolContext:p,result:d});if(R==null){for(let k of r)if(R=await k({tool:y,args:h,context:p,response:d}),R)break}if(R!=null&&(d=R),y.isLongRunning&&!d)continue;C?d={error:C}:(typeof d!="object"||d==null)&&(d={result:d});let I=w({invocationId:o.invocationId,author:o.agent.name,content:Ht({functionResponse:{id:p.functionCallId,name:y.name,response:d}}),actions:p.actions,branch:o.branch});g.debug("traceToolCall",{tool:y.name,args:h,functionResponseEvent:I.id}),a.push(I)}if(!a.length)return null;let c=nn(a);return a.length>1&&(g.debug("execute_tool (merged)"),g.debug("traceMergedToolCalls",{responseEventId:c.id,functionResponseEvent:c.id})),c}function tn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new j({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function nn(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=ot(n);return w({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ke=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return v(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as wt}from"zod";var Le="0.2.1";var on="google-adk",rn="gl-typescript",sn="remote_reasoning_engine",an="GOOGLE_CLOUD_AGENT_ENGINE_ID";function ln(){let o="".concat(on,"/").concat(Le);!Te()&&process.env[an]&&(o="".concat(o,"+").concat(sn));let e="".concat(rn,"/").concat(Te()?window.navigator.userAgent:process.version);return[o,e]}function ht(){return ln()}var K=class{constructor({model:e}){this.model=e}get trackingHeaders(){let t=ht().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."}]})}};K.supportedModels=[];function ie(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function Ct(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as yt,FinishReason as fn,GoogleGenAI as Be}from"@google/genai";function vt(){return cn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function cn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var me=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(n=>{var r;return n.parts&&((r=n.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):g.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(n=>n.functionResponse).filter(n=>!!n);g.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else g.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){g.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}receive(){return v(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function Pe(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var ne=class extends K{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!n,!this.vertexai&&a){let l=process.env.GOOGLE_GENAI_USE_VERTEXAI;l&&(this.vertexai=l.toLowerCase()==="true"||l==="1")}if(this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}generateContentAsync(e,t=!1){return v(this,null,function*(){var n,r,i,s,m,A,y;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),g.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=b(b({},e.config.httpOptions.headers),this.trackingHeaders)),t){let p=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),h="",d="",C,R;try{for(var a=x(p),l,c,f;l=!(c=yield new u(a.next())).done;l=!1){let I=c.value;R=I;let k=Pe(I);C=k.usageMetadata;let M=(s=(i=k.content)==null?void 0:i.parts)==null?void 0:s[0];if(M!=null&&M.text)"thought"in M&&M.thought?h+=M.text:d+=M.text,k.partial=!0;else if((h||d)&&(!M||!M.inlineData)){let be=[];h&&be.push({text:h,thought:!0}),d&&be.push(yt(d)),yield{content:{role:"model",parts:be},usageMetadata:k.usageMetadata},h="",d=""}yield k}}catch(c){f=[c]}finally{try{l&&(c=a.return)&&(yield new u(c.call(a)))}finally{if(f)throw f[0]}}if((d||h)&&((A=(m=R==null?void 0:R.candidates)==null?void 0:m[0])==null?void 0:A.finishReason)===fn.STOP){let I=[];h&&I.push({text:h,thought:!0}),d&&I.push({text:d}),yield{content:{role:"model",parts:I},usageMetadata:C}}}else{let p=yield new u(this.apiClient.models.generateContent({model:(y=e.model)!=null?y:this.model,contents:e.contents,config:e.config}));yield Pe(p)}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=b(b({},this.trackingHeaders),this.headers);return this.vertexai?this._apiClient=new Be({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new Be({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new Be({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[yt(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 me(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)At(n.inlineData),At(n.fileData)}}};ne.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function At(o){o&&o.displayName&&(o.displayName=void 0)}var Me=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},O=class O{static newLlm(e){return new(O.resolve(e))({model:e})}static _register(e,t){O.llmRegistryDict.has(e)&&g.info("Updating LLM class for ".concat(e," from ").concat(O.llmRegistryDict.get(e)," to ").concat(t)),O.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)O._register(t,e)}static resolve(e){let t=O.resolveCache.get(e);if(t)return t;for(let[n,r]of O.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return O.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};O.llmRegistryDict=new Map,O.resolveCache=new Me(32);var oe=O;oe.register(ne);var $=class{constructor(e){var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=dn(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return vt()}};function dn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as mn}from"@google/genai";import{ZodObject as pn}from"zod";import{Type as P}from"@google/genai";import{z as T}from"zod";function bt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function G(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case T.ZodFirstPartyTypeKind.ZodString:n.type=P.STRING;for(let l of e.checks||[])l.kind==="min"?n.minLength=l.value.toString():l.kind==="max"?n.maxLength=l.value.toString():l.kind==="email"?n.format="email":l.kind==="uuid"?n.format="uuid":l.kind==="url"?n.format="uri":l.kind==="regex"&&(n.pattern=l.regex.source);return r(n);case T.ZodFirstPartyTypeKind.ZodNumber:n.type=P.NUMBER;for(let l of e.checks||[])l.kind==="min"?n.minimum=l.value:l.kind==="max"?n.maximum=l.value:l.kind==="int"&&(n.type=P.INTEGER);return r(n);case T.ZodFirstPartyTypeKind.ZodBoolean:return n.type=P.BOOLEAN,r(n);case T.ZodFirstPartyTypeKind.ZodArray:return n.type=P.ARRAY,n.items=G(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case T.ZodFirstPartyTypeKind.ZodObject:return pe(o);case T.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=P.STRING;else if(i==="number")n.type=P.NUMBER;else if(i==="boolean")n.type=P.BOOLEAN;else if(e.value===null)n.type=P.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case T.ZodFirstPartyTypeKind.ZodEnum:return n.type=P.STRING,n.enum=e.values,r(n);case T.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=P.STRING,n.enum=Object.values(e.values),r(n);case T.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(G),r(n);case T.ZodFirstPartyTypeKind.ZodOptional:return G(e.innerType);case T.ZodFirstPartyTypeKind.ZodNullable:let s=G(e.innerType);return r(s?b({anyOf:[s,{type:P.NULL}]},t&&{description:t}):b({type:P.NULL},t&&{description:t}));case T.ZodFirstPartyTypeKind.ZodDefault:let a=G(e.innerType);return a&&(a.default=e.defaultValue()),a;case T.ZodFirstPartyTypeKind.ZodBranded:return G(e.type);case T.ZodFirstPartyTypeKind.ZodReadonly:return G(e.innerType);case T.ZodFirstPartyTypeKind.ZodNull:return n.type=P.NULL,r(n);case T.ZodFirstPartyTypeKind.ZodAny:case T.ZodFirstPartyTypeKind.ZodUnknown:return r(b({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function pe(o){if(o._def.typeName!==T.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],l=G(a);l&&(t[s]=l);let c=a,f=!1;for(;c._def.typeName===T.ZodFirstPartyTypeKind.ZodOptional||c._def.typeName===T.ZodFirstPartyTypeKind.ZodDefault;)f=!0,c=c._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==T.ZodFirstPartyTypeKind.ZodNever?i=G(r)||!0:i=o._def.unknownKeys==="passthrough",b({type:P.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function gn(o){return o===void 0?{type:mn.OBJECT,properties:{}}:bt(o)?pe(o):o}var q=class extends ${constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:gn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof pn&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var Z=class{};function se(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function _e(o,e,t){var s,a,l;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||((l=(a=c.content.parts)==null?void 0:a[0])==null?void 0:l.text)===""||t&&c.branch&&!t.startsWith(c.branch)||hn(c)||Cn(c)||n.push(Tt(e,c)?vn(c):c);let r=yn(n);r=An(r);let i=[];for(let c of r){let f=se(c.content);ft(f),i.push(f)}return i}function Et(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Tt(e,r))return _e(o.slice(n),e,t)}return[]}function hn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===fe||((n=r.functionResponse)==null?void 0:n.name)===fe)return!0;return!1}function Cn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===te||((n=r.functionResponse)==null?void 0:n.name)===te)return!0;return!1}function Tt(o,e){return!!o&&e.author!==o&&e.author!=="user"}function vn(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let l of o.content.parts)if(l.text&&!l.thought)(r=e.parts)==null||r.push({text:"[".concat(o.author,"] said: ").concat(l.text)});else if(l.functionCall){let c=xt(l.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(l.functionCall.name,"` with parameters: ").concat(c)})}else if(l.functionResponse){let c=xt(l.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(l.functionResponse.name,"` returned result: ").concat(c)})}else(a=e.parts)==null||a.push(l);return w({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function St(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=w(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function yn(o){if(o.length===0)return o;let e=o[o.length-1],t=_(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(l=>!!l.id).map(l=>l.id)),r=o.at(-2);if(r){let l=L(r);if(l){for(let c of l)if(c.id&&n.has(c.id))return o}}let i=-1;for(let l=o.length-2;l>=0;l--){let c=o[l],f=L(c);if(f!=null&&f.length){for(let m of f)if(m.id&&n.has(m.id)){i=l;let A=new Set(f.map(p=>p.id).filter(p=>!!p));if(!Array.from(n).every(p=>A.has(p)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(A).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=A;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let l=i+1;l<o.length-1;l++){let c=o[l],f=_(c);f&&f.some(m=>m.id&&n.has(m.id))&&s.push(c)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(St(s)),a}function An(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=_(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(_(n).length>0)continue;let r=L(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((l,c)=>l-c).map(l=>o[l]);t.push(St(a))}}else t.push(n)}return t}function xt(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function Ne(o,e){let t=e.invocationContext;async function n(l){let c=l[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=c.endsWith("?");if(f&&(c=c.slice(0,-1)),c.startsWith("artifact.")){let m=c.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let A=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:m});if(!A)throw new Error("Artifact ".concat(m," not found."));return String(A)}if(!En(c))return l[0];if(c in t.session.state)return String(t.session.state[c]);if(f)return"";throw new Error("Context variable not found: `".concat(c,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let l of a){i.push(o.slice(s,l.index));let c=await n(l);i.push(c),s=l.index+l[0].length}return i.push(o.slice(s)),i.join("")}var bn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Rt(o){return o===""||o===void 0?!1:bn.test(o)}var xn=[E.APP_PREFIX,E.USER_PREFIX,E.TEMP_PREFIX];function En(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Rt(o):xn.includes(e[0]+":")?Rt(e[1]):!1}var Oe=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Oe||{});function It(o={}){return b({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Tn(o.maxLlmCalls||500)},o)}function Tn(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(Number.MAX_SAFE_INTEGER,"."));return o<=0&&g.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),o}var kt="adk_agent_name";async function Lt(o,e){return o instanceof $?[o]:await o.getTools(e)}var Fe=class extends Z{runAsync(e,t){return v(this,null,function*(){var r;let n=e.agent;n instanceof S&&(t.model=n.canonicalModel.model,t.config=b({},(r=n.generateContentConfig)!=null?r:{}),n.outputSchema&&Ct(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},Sn=new Fe,$e=class extends Z{runAsync(e,t){return v(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),ie(t,r)})}},Rn=new $e,De=class extends Z{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof S)||!(n.rootAgent instanceof S))return;let r=n.rootAgent;if(r instanceof S&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new B(e))),a=i;s&&(a=yield new u(Ne(i,new B(e)))),ie(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new B(e))),a=i;s&&(a=yield new u(Ne(i,new B(e)))),ie(t,[a])}})}},In=new De,Ge=class{runAsync(e,t){return v(this,null,function*(){let n=e.agent;!n||!(n instanceof S)||(n.includeContents==="default"?t.contents=_e(e.session.events,n.name,e.branch):t.contents=Et(e.session.events,n.name,e.branch))})}},wn=new Ge,qe=class extends Z{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new q({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:wt.object({agentName:wt.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,n){return v(this,null,function*(){if(!(t.agent instanceof S))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;ie(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new j({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).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 n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof S)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},kn=new qe,Ue=class extends Z{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof S))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let a=r.length-1;a>=0;a--){let l=r[a];if(l.author!=="user")continue;let c=_(l);if(!c)continue;let f=!1;for(let m of c){if(m.name!==te)continue;f=!0;let A=null;m.response&&Object.keys(m.response).length===1&&"response"in m.response?A=JSON.parse(m.response.response):m.response&&(A=new V({hint:m.response.hint,payload:m.response.payload,confirmed:m.response.confirmed})),m.id&&A&&(i[m.id]=A)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let l=r[a],c=L(l);if(!c)continue;let f={},m={};for(let h of c){if(!h.id||!(h.id in i))continue;let d=h.args;if(!d||!("originalFunctionCall"in d))continue;let C=d.originalFunctionCall;C.id&&(f[C.id]=i[h.id],m[C.id]=C)}if(Object.keys(f).length===0)continue;for(let h=r.length-1;h>s;h--){let d=r[h],C=_(d);if(C){for(let R of C)R.id&&R.id in f&&(delete f[R.id],delete m[R.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let A=yield new u(n.canonicalTools(new B(e))),y=Object.fromEntries(A.map(h=>[h.name,h])),p=yield new u(de({invocationContext:e,functionCalls:Object.values(m),toolsDict:y,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f}));p&&(yield p);return}})}},Ln=new Ue,S=class o extends F{constructor(e){var n,r,i,s,a,l,c,f,m;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(l=e.includeContents)!=null?l:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.requestProcessors=(c=e.requestProcessors)!=null?c:[Sn,Rn,In,Ln,wn],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((m=this.subAgents)!=null&&m.length)||this.requestProcessors.push(kn),e.generateContentConfig){if(e.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(e.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(e.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};if(this.outputSchema){if((!this.disallowTransferToParent||!this.disallowTransferToPeers)&&(g.warn("Invalid config for agent ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, subAgents must be empty to disable agent transfer."));if(this.tools&&this.tools.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(this.model instanceof K)return this.model;if(typeof this.model=="string"&&this.model)return oe.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await Lt(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){g.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){g.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!H(e)){g.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){g.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){g.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return v(this,null,function*(){for(;;){let s;try{for(var t=x(this.runOneStepAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;s=a,this.maybeSaveOutputToState(a),yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}if(!s||H(s))break;if(s.partial){g.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return v(this,null,function*(){try{for(var t=x(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return v(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return v(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let d of this.requestProcessors)try{for(var r=x(d.runAsync(e,t)),i,s,a;i=!(s=yield new u(r.next())).done;i=!1){let C=s.value;yield C}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(a)throw a[0]}}for(let d of this.tools){let C=new j({invocationContext:e}),R=yield new u(Lt(d,new B(e)));for(let I of R)yield new u(I.processLlmRequest({toolContext:C,llmRequest:t}))}if(e.endInvocation)return;let n=w({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var A=x(this.callLlmAsync(e,t,n)),y,p,h;y=!(p=yield new u(A.next())).done;y=!1){let d=p.value;try{for(var l=x(this.postprocess(e,t,d,n)),c,f,m;c=!(f=yield new u(l.next())).done;c=!1){let C=f.value;n.id=Ee(),n.timestamp=new Date().getTime(),yield C}}catch(f){m=[f]}finally{try{c&&(f=l.return)&&(yield new u(f.call(l)))}finally{if(m)throw m[0]}}}}catch(p){h=[p]}finally{try{y&&(p=A.return)&&(yield new u(p.call(A)))}finally{if(h)throw h[0]}}})}postprocess(e,t,n,r){return v(this,null,function*(){var p;for(let I of this.responseProcessors)try{for(var f=x(I.runAsync(e,n)),m,A,y;m=!(A=yield new u(f.next())).done;m=!1){let k=A.value;yield k}}catch(A){y=[A]}finally{try{m&&(A=f.return)&&(yield new u(A.call(f)))}finally{if(y)throw y[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=w(b(b({},r),n));if(i.content){let I=L(i);I!=null&&I.length&&(ut(i),i.longRunningToolIds=Array.from(dt(I,t.toolsDict)))}if(yield i,!((p=L(i))!=null&&p.length))return;let s=yield new u(gt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let a=mt(e,s);a&&(yield a);let l=pt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});l&&(yield l),yield s;let c=s.actions.transferToAgent;if(c){let I=this.getAgentByName(e,c);try{for(var h=x(I.runAsync(e)),d,C,R;d=!(C=yield new u(h.next())).done;d=!1){let k=C.value;yield k}}catch(C){R=[C]}finally{try{d&&(C=h.return)&&(yield new u(C.call(h)))}finally{if(R)throw R[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return v(this,null,function*(){var s,a,l,c,f;let r=yield new u(this.handleBeforeModelCallback(e,t,n));if(r){yield r;return}(s=t.config)!=null||(t.config={}),(l=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[kt]||(t.config.labels[kt]=this.name);let i=this.canonicalModel;if((c=e.runConfig)!=null&&c.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let h=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");try{for(var m=x(this.runAndHandleError(h,e,t,n)),A,y,p;A=!(y=yield new u(m.next())).done;A=!1){let d=y.value;let C=yield new u(this.handleAfterModelCallback(e,d,n));yield C!=null?C:d}}catch(y){p=[y]}finally{try{A&&(y=m.return)&&(yield new u(y.call(m)))}finally{if(p)throw p[0]}}}})}async handleBeforeModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let a=await s({context:r,request:t});if(a)return a}}async handleAfterModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let a=await s({context:r,response:t});if(a)return a}}runAndHandleError(e,t,n,r){return v(this,null,function*(){try{try{for(var i=x(e),s,a,l;s=!(a=yield new u(i.next())).done;s=!1){let c=a.value;yield c}}catch(a){l=[a]}finally{try{s&&(a=i.return)&&(yield new u(a.call(i)))}finally{if(l)throw l[0]}}}catch(c){let f=new N({invocationContext:t,eventActions:r.actions});if(c instanceof Error){let m=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:n,error:c}));if(m)yield m;else{let A=JSON.parse(c.message);yield{errorCode:String(A.error.code),errorMessage:A.error.message}}}else throw g.error("Unknown error during response generation",c),c}})}};var je=class extends F{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return v(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let a of this.subAgents){let l=!1;try{for(var n=x(a.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c,c.actions.escalate&&(l=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(l)return}t++}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var Ke=class extends F{runAsyncImpl(e){return v(this,null,function*(){let t=this.subAgents.map(a=>a.runAsync(Pn(this,a,e)));try{for(var n=x(Bn(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function Pn(o,e,t){let n=new D(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function Bn(o){return v(this,null,function*(){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=yield new u(Promise.race(e.values()));if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}})}var Ze="task_completed",Ve=class extends F{runAsyncImpl(e){return v(this,null,function*(){for(let s of this.subAgents)try{for(var t=x(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return v(this,null,function*(){for(let s of this.subAgents)s instanceof S&&((yield new u(s.canonicalTools(new B(e)))).some(c=>c.name===Ze)||(s.tools.push(new q({name:Ze,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(Ze," 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 s of this.subAgents)try{for(var t=x(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var ae=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=ge(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=ge(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(t,"/user/"),s=[];for(let a in this.artifacts)if(a.startsWith(r)){let l=a.replace(r,"");s.push(l)}else if(a.startsWith(i)){let l=a.replace(i,"");s.push(l)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=ge(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=ge(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let l=0;l<s.length;l++)a.push(l);return Promise.resolve(a)}};function ge(o,e,t,n){return Mn(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function Mn(o){return o.startsWith("user:")}var z=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Pt(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=Pt(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let l of a){if(!((s=(i=l.content)==null?void 0:i.parts)!=null&&s.length))continue;let c=l.content.parts.map(A=>A.text).filter(A=>!!A).join(" "),f=_n(c);if(!f.size)continue;n.some(A=>f.has(A))&&r.memories.push({content:l.content,author:l.author,timestamp:Nn(l.timestamp)})}return r}};function Pt(o,e){return"".concat(o,"/").concat(e)}function _n(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Nn(o){return new Date(o).toISOString()}var W=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var ze=class extends W{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".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((n=e.agent.name)!=null?n:"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({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(H(t)));let n=L(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=_(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.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({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"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:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");g.info(t)}formatContent(e,t=200){if(!e||!e.parts)return"None";let n=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),n.push("text: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var le=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),g.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return g.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw g.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,n=>n.onUserMessageCallback({userMessage:e,invocationContext:t}),"onUserMessageCallback")}async runBeforeRunCallback({invocationContext:e}){return await this.runCallbacks(this.plugins,t=>t.beforeRunCallback({invocationContext:e}),"beforeRunCallback")}async runAfterRunCallback({invocationContext:e}){await this.runCallbacks(this.plugins,t=>t.afterRunCallback({invocationContext:e}),"afterRunCallback")}async runOnEventCallback({invocationContext:e,event:t}){return await this.runCallbacks(this.plugins,n=>n.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,n=>n.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:n}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:n}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,n=>n.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,n=>n.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}),"onToolErrorCallback")}};var Mt="adk_request_confirmation",We="orcas_tool_call_security_check_states",Bt="This tool call needs external confirmation before completion.",_t=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(_t||{}),he=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Qe=class extends W{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new he}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:Bt};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(We))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(We))!=null?i:{};r[n]=t,e.state.set(We,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Bt};case"ALLOW":return;default:return}}};function On(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Mt&&e.push(t.functionCall);return e}var Ce=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[n,r]of Object.entries(t.actions.stateDelta))n.startsWith(E.TEMP_PREFIX)||(e.state[n]=r)}};function ve(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var Q=class extends Ce{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=ve({id:i||J(),appName:t,userId:n,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][n]||(this.sessions[t][n]={}),this.sessions[t][n][s.id]=s,Promise.resolve(this.mergeState(t,n,se(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=se(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 Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(ve({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=c=>{g.warn("Failed to append event to session ".concat(s,": ").concat(c))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let c of Object.keys(n.actions.stateDelta))c.startsWith(E.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][c.replace(E.APP_PREFIX,"")]=n.actions.stateDelta[c]),c.startsWith(E.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][c.replace(E.USER_PREFIX,"")]=n.actions.stateDelta[c]);let l=this.sessions[r][i][s];return await super.appendEvent({session:l,event:n}),l.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[E.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[E.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as Fn}from"@google/genai";import{trace as $n}from"@opentelemetry/api";var X=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new le((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return v(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var l;i=It(i);let a=$n.getTracer("gcp.vertex.agent").startSpan("invocation");try{let y=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!y)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof S){let C=this.agent.canonicalModel.model;if(!C.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(C," in agent: ").concat(this.agent.name))}let p=new D({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:st(),agent:this.agent,session:y,userContent:n,runConfig:i,pluginManager:this.pluginManager}),h=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:p}));if(h&&(n=h),n){if(!((l=n.parts)!=null&&l.length))throw new Error("No parts in the new_message.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(p.invocationId,y.userId,y.id,n))),yield new u(this.sessionService.appendEvent({session:y,event:w({invocationId:p.invocationId,author:"user",actions:r?U({stateDelta:r}):void 0,content:n})}))}p.agent=this.determineAgentForResumption(y,this.agent);let d=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:p}));if(d){let C=w({invocationId:p.invocationId,author:"model",content:d});yield new u(this.sessionService.appendEvent({session:y,event:C})),yield C}else try{for(var c=x(p.agent.runAsync(p)),f,m,A;f=!(m=yield new u(c.next())).done;f=!1){let C=m.value;C.partial||(yield new u(this.sessionService.appendEvent({session:y,event:C})));let R=yield new u(this.pluginManager.runOnEventCallback({invocationContext:p,event:C}));R?yield R:yield C}}catch(m){A=[m]}finally{try{f&&(m=c.return)&&(yield new u(m.call(c)))}finally{if(A)throw A[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:p}))}finally{a.end()}})}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let l="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:l,artifact:a}),r.parts[s]=Fn("Uploaded file: ".concat(l,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Dn(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){g.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){g.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof S)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Dn(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let l=o[a],c=L(l);if(c){for(let f of c)if(f.id===t)return l}}return null}var Xe=class extends X{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new ae,sessionService:new Q,memoryService:new z})}};import{Type as Ae}from"@google/genai";var ye=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(e){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var Ye=class extends ${constructor(e){super({name:e.agent.name,description:e.agent.description||""}),this.agent=e.agent,this.skipSummarization=e.skipSummarization||!1}_getDeclaration(){let e;if(this.agent instanceof S&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Ae.OBJECT,properties:{request:{type:Ae.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof S&&this.agent.outputSchema;e.response=t?{type:Ae.OBJECT}:{type:Ae.STRING}}return e}async runAsync({args:e,toolContext:t}){var p,h;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof S&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new X({appName:this.agent.name,agent:this.agent,artifactService:new ye(t),sessionService:new Q,memoryService:new z,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;try{for(var f=x(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),m,A,y;m=!(A=await f.next()).done;m=!1){let d=A.value;d.actions.stateDelta&&t.state.update(d.actions.stateDelta),a=d}}catch(A){y=[A]}finally{try{m&&(A=f.return)&&await A.call(f)}finally{if(y)throw y[0]}}if(!((h=(p=a==null?void 0:a.content)==null?void 0:p.parts)!=null&&h.length))return"";let l=this.agent instanceof S&&this.agent.outputSchema,c=a.content.parts.map(d=>d.text).filter(d=>d).join("\n");return l?JSON.parse(c):c}};var He=class{constructor(e){this.toolFilter=e}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var Gn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Nt(o){let e=o.match(Gn);return e?e[1]:o}function Ot(o){return Nt(o).startsWith("gemini-")}function Ft(o){return Nt(o).startsWith("gemini-1")}var Je=class extends ${constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.config=t.config||{},t.config.tools=t.config.tools||[],Ft(t.model)){if(t.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");t.config.tools.push({googleSearchRetrieval:{}});return}if(Ot(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},qn=new Je;var $t="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",et=class extends q{constructor(e){super(Y(b({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=$t:e.description=$t.trimStart(),e}};export{Ye as AgentTool,F as BaseAgent,K as BaseLlm,W as BasePlugin,Ce as BaseSessionService,$ as BaseTool,He as BaseToolset,N as CallbackContext,q as FunctionTool,qn as GOOGLE_SEARCH,ne as Gemini,ae as InMemoryArtifactService,z as InMemoryMemoryService,he as InMemoryPolicyEngine,Xe as InMemoryRunner,Q as InMemorySessionService,D as InvocationContext,oe as LLMRegistry,ke as LiveRequestQueue,S as LlmAgent,ct as LogLevel,ze as LoggingPlugin,et as LongRunningFunctionTool,je as LoopAgent,Ke as ParallelAgent,le as PluginManager,_t as PolicyOutcome,Mt as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,X as Runner,Qe as SecurityPlugin,Ve as SequentialAgent,E as State,Oe as StreamingMode,V as ToolConfirmation,j as ToolContext,w as createEvent,U as createEventActions,ve as createSession,Jt as functionsExportedForTestingOnly,On as getAskUserConfirmationFunctionCalls,L as getFunctionCalls,_ as getFunctionResponses,it as hasTrailingCodeExecutionResult,H as isFinalResponse,Wt as setLogLevel,Kt as stringifyContent,Le as version,pe as zodObjectToSchema};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Google LLC