@paean-ai/adk 0.2.20 → 0.2.21

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.
@@ -914,6 +914,8 @@ const _LlmAgent = class _LlmAgent extends import_base_agent.BaseAgent {
914
914
  event.actions.stateDelta[this.outputKey] = result;
915
915
  }
916
916
  async *runAsyncImpl(context) {
917
+ var _a, _b;
918
+ let consecutiveErrors = 0;
917
919
  while (true) {
918
920
  let lastEvent = void 0;
919
921
  for await (const event of this.runOneStepAsync(context)) {
@@ -921,7 +923,24 @@ const _LlmAgent = class _LlmAgent extends import_base_agent.BaseAgent {
921
923
  this.maybeSaveOutputToState(event);
922
924
  yield event;
923
925
  }
924
- if (!lastEvent || (0, import_event.isFinalResponse)(lastEvent)) {
926
+ if (!lastEvent) {
927
+ break;
928
+ }
929
+ if (lastEvent.errorCode && !((_b = (_a = lastEvent.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
930
+ consecutiveErrors++;
931
+ if (consecutiveErrors <= _LlmAgent.MAX_AGENT_LOOP_ERROR_RETRIES) {
932
+ import_logger.logger.warn(
933
+ `[runAsyncImpl] Error event (${lastEvent.errorCode}), retrying agent loop (${consecutiveErrors}/${_LlmAgent.MAX_AGENT_LOOP_ERROR_RETRIES})`
934
+ );
935
+ continue;
936
+ }
937
+ import_logger.logger.error(
938
+ `[runAsyncImpl] Max agent-loop error retries exhausted for ${lastEvent.errorCode}`
939
+ );
940
+ break;
941
+ }
942
+ consecutiveErrors = 0;
943
+ if ((0, import_event.isFinalResponse)(lastEvent)) {
925
944
  break;
926
945
  }
927
946
  if (lastEvent.partial) {
@@ -1242,11 +1261,14 @@ const _LlmAgent = class _LlmAgent extends import_base_agent.BaseAgent {
1242
1261
  // - code_executor
1243
1262
  // - configurable agents by yaml config
1244
1263
  };
1264
+ _LlmAgent.MAX_AGENT_LOOP_ERROR_RETRIES = 2;
1245
1265
  _LlmAgent.LLM_TRANSIENT_ERROR_MAX_RETRIES = 2;
1246
1266
  _LlmAgent.LLM_TRANSIENT_ERROR_BASE_DELAY_MS = 1e3;
1247
1267
  _LlmAgent.LLM_TRANSIENT_ERROR_MAX_DELAY_MS = 4e3;
1248
1268
  _LlmAgent.LLM_RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
1249
- "UNKNOWN_ERROR"
1269
+ "UNKNOWN_ERROR",
1270
+ "UNEXPECTED_TOOL_CALL",
1271
+ "MALFORMED_FUNCTION_CALL"
1250
1272
  ]);
1251
1273
  let LlmAgent = _LlmAgent;
1252
1274
  // Annotate the CommonJS export names for ESM import in node:
package/dist/cjs/index.js CHANGED
@@ -4,17 +4,17 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- "use strict";var nt=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var Hn=Object.prototype.hasOwnProperty;var Jn=(o,e)=>{for(var t in e)nt(o,t,{get:e[t],enumerable:!0})},eo=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qn(e))!Hn.call(o,r)&&r!==t&&nt(o,r,{get:()=>e[r],enumerable:!(n=Xn(e,r))||n.enumerable});return o};var to=o=>eo(nt({},"__esModule",{value:!0}),o);var ir={};Jn(ir,{AgentTool:()=>Ye,BaseAgent:()=>F,BaseLlm:()=>ae,BasePlugin:()=>J,BaseSessionService:()=>Te,BaseTool:()=>_,BaseToolset:()=>he,BuiltInCodeExecutor:()=>oe,CallbackContext:()=>B,FunctionTool:()=>K,GOOGLE_SEARCH:()=>Ln,GcsArtifactService:()=>Ft,Gemini:()=>ce,InMemoryArtifactService:()=>me,InMemoryMemoryService:()=>H,InMemoryPolicyEngine:()=>be,InMemoryRunner:()=>ze,InMemorySessionService:()=>ee,InvocationContext:()=>U,LLMRegistry:()=>le,LiveRequestQueue:()=>Oe,LlmAgent:()=>E,LogLevel:()=>ct,LoggingPlugin:()=>Ve,LongRunningFunctionTool:()=>Xe,LoopAgent:()=>qe,MCPSessionManager:()=>Ie,MCPTool:()=>Pe,MCPToolset:()=>Bt,ParallelAgent:()=>Ue,PluginManager:()=>ge,PolicyOutcome:()=>Mt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>_t,Runner:()=>te,SecurityPlugin:()=>Ze,SequentialAgent:()=>je,State:()=>v,StreamingMode:()=>Ge,ToolConfirmation:()=>X,ToolContext:()=>Z,createEvent:()=>y,createEventActions:()=>$,createSession:()=>Se,functionsExportedForTestingOnly:()=>Vt,getAskUserConfirmationFunctionCalls:()=>In,getFunctionCalls:()=>I,getFunctionResponses:()=>O,getGcpExporters:()=>or,getGcpResource:()=>rr,hasTrailingCodeExecutionResult:()=>ot,isBaseLlm:()=>Fe,isFinalResponse:()=>ne,maybeSetOtelProviders:()=>Qo,setLogLevel:()=>Kt,stringifyContent:()=>$t,version:()=>Be,zodObjectToSchema:()=>Ae});module.exports=to(ir);var st=require("@opentelemetry/api");function $(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function Dt(o,e){let t=$();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 y(o={}){return{...o,id:o.id||rt(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||$(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function ne(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:I(o).length===0&&O(o).length===0&&!o.partial&&!ot(o)}function I(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(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 ot(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 $t(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 Gt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function rt(){let o="";for(let e=0;e<8;e++)o+=Gt[Math.floor(Math.random()*Gt.length)];return o}var v=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};v.APP_PREFIX="app:",v.USER_PREFIX="user:",v.TEMP_PREFIX="temp:";var N=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 v(this.invocationContext.session.state,{})}};var B=class extends N{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||$(),this._state=new v(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 Le(){return typeof window<"u"}var we="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function fe(){let o="";for(let e=0;e<we.length;e++){let t=Math.random()*16|0;we[e]==="x"?o+=t.toString(16):we[e]==="y"?o+=(t&3|8).toString(16):o+=we[e]}return o}function qt(o){return Le()?window.atob(o):Buffer.from(o,"base64").toString()}var it=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},U=class{constructor(e){this.invocationCostManager=new it;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 Ut(){return`e-${fe()}`}var F=class{constructor(e){this.name=no(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=ro(this),this.beforeAgentCallback=jt(e.beforeAgentCallback),this.afterAgentCallback=jt(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=st.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=st.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${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 U({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new B({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new B({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function no(o){if(!oo(o))throw new Error(`Found invalid agent name: "${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 oo(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function ro(o){for(;o.parentAgent;)o=o.parentAgent;return o}function jt(o){return o?Array.isArray(o)?o:[o]:[]}var lt=require("@google/genai");var ve=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 ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var X=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var Z=class extends B{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 ve(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ve(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new X({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||{}),de=1;function Kt(o){de=o}var at=class{log(e,...t){if(!(e<de))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){de>0||console.debug(ke(0),...e)}info(...e){de>1||console.info(ke(1),...e)}warn(...e){de>2||console.warn(ke(2),...e)}error(...e){de>3||console.error(ke(3),...e)}},io={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},so={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},ao="\x1B[0m";function ke(o){return`${so[o]}[ADK ${io[o]}]:${ao}`}var p=new at;var ut="adk-",_e="adk_request_credential",pe="adk_request_confirmation",Vt={handleFunctionCallList:Me};function ft(){return`${ut}${fe()}`}function Zt(o){let e=I(o);if(e)for(let t of e)t.id||(t.id=ft())}function zt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(ut)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(ut)&&(e.functionResponse.id=void 0)}function Wt(o,e){if(o in e)return o;let t=o.indexOf(":");if(t>0){let n=o.substring(0,t);if(n in e)return p.info(`Resolved Gemini 3 function name "${o}" to tool "${n}"`),n}}function Yt(o,e){let t=new Set;for(let n of o){if(!n.name||!n.id)continue;let r=Wt(n.name,e);r&&e[r].isLongRunning&&t.add(n.id)}return t}function Xt(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 c={name:_e,args:{function_call_id:i,auth_config:s},id:ft()};n.add(c.id),t.push({functionCall:c})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Qt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=I(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(c=i.find(d=>d.id===a))!=null?c:void 0;if(!u)continue;let f={name:pe,args:{originalFunctionCall:u,toolConfirmation:l},id:ft()};r.add(f.id),n.push({functionCall:f})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function co(o,e,t){return p.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function Ht({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let c=I(e);return await Me({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Me({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u,f,d;let c=[],a=e.filter(h=>!i||h.id&&i.has(h.id));for(let h of a){let P;s&&h.id&&(P=s[h.id]);let T=lo({invocationContext:o,functionCall:h,toolsDict:t,toolConfirmation:P});if(!T){let x=Object.keys(t).join(", ");p.warn(`Function ${h.name} is not found in the toolsDict. Available tools: [${x}]. Returning error response to LLM.`);let Y=y({invocationId:o.invocationId,author:o.agent.name,content:(0,lt.createUserContent)({functionResponse:{id:h.id||void 0,name:(u=h.name)!=null?u:"unknown",response:{error:`Function '${h.name}' is not available. Available tools: [${x}]. Please use one of the available tools instead.`}}}),branch:o.branch});c.push(Y);continue}let{tool:g,toolContext:m}=T;p.debug(`execute_tool ${g.name}`);let C=(f=h.args)!=null?f:{},S=null,R;if(S=await o.pluginManager.runBeforeToolCallback({tool:g,toolArgs:C,toolContext:m}),S==null){for(let x of n)if(S=await x({tool:g,args:C,context:m}),S)break}if(S==null)try{S=await co(g,C,m)}catch(x){if(x instanceof Error){let Y=await o.pluginManager.runOnToolErrorCallback({tool:g,toolArgs:C,toolContext:m,error:x});Y?S=Y:R=x.message}else R=x}let k=await o.pluginManager.runAfterToolCallback({tool:g,toolArgs:C,toolContext:m,result:S});if(k==null){for(let x of r)if(k=await x({tool:g,args:C,context:m,response:S}),k)break}if(k!=null&&(S=k),g.isLongRunning&&!S)continue;R?S={error:R}:(typeof S!="object"||S==null)&&(S={result:S});let A=y({invocationId:o.invocationId,author:o.agent.name,content:(0,lt.createUserContent)({functionResponse:{id:m.functionCallId,name:(d=h.name)!=null?d:g.name,response:S}}),actions:m.actions,branch:o.branch});p.debug("traceToolCall",{tool:g.name,args:C,functionResponseEvent:A.id}),c.push(A)}if(!c.length)return null;let l=uo(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function lo({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){let r=e.name?Wt(e.name,t):void 0;if(!r)return null;let i=new Z({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[r],toolContext:i}}function uo(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=Dt(n);return y({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Oe=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:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var xt=require("zod");var Q=class{constructor(){this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var fo="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ne(o){let e=o.match(fo);return e?e[1]:o}function Jt(o){return Ne(o).startsWith("gemini-")}function en(o){return Ne(o).startsWith("gemini-1")}function tn(o){return Ne(o).startsWith("gemini-2")}function nn(o){let e=Ne(o);return e.startsWith("gemini-3")&&e.includes("preview")}var oe=class extends Q{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&tn(e.model)){e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${e.model}`)}};var ye=require("@google/genai");function D(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function on(o,e){var u;if(!((u=o.parts)!=null&&u.length))return"";for(let f=0;f<o.parts.length;f++){let d=o.parts[f];if(d.executableCode&&(f===o.parts.length-1||!o.parts[f+1].codeExecutionResult))return o.parts=o.parts.slice(0,f+1),d.executableCode.code}let t=o.parts.filter(f=>f.text);if(!t.length)return"";let n=D(t[0]),r=t.map(f=>f.text).join(`
8
- `),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),c=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:a,codeStr:l}=(c==null?void 0:c.groups)||{};return l?(o.parts=[],a&&(n.text=a,o.parts.push(n)),o.parts.push(dt(l)),l):""}function dt(o){return{text:o,executableCode:{code:o,language:ye.Language.PYTHON}}}function rn(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:ye.Outcome.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push(`Code execution result:
7
+ "use strict";var nt=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var Hn=Object.prototype.hasOwnProperty;var Jn=(o,e)=>{for(var t in e)nt(o,t,{get:e[t],enumerable:!0})},eo=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qn(e))!Hn.call(o,r)&&r!==t&&nt(o,r,{get:()=>e[r],enumerable:!(n=Xn(e,r))||n.enumerable});return o};var to=o=>eo(nt({},"__esModule",{value:!0}),o);var ir={};Jn(ir,{AgentTool:()=>Ye,BaseAgent:()=>F,BaseLlm:()=>ae,BasePlugin:()=>J,BaseSessionService:()=>Te,BaseTool:()=>_,BaseToolset:()=>he,BuiltInCodeExecutor:()=>oe,CallbackContext:()=>B,FunctionTool:()=>K,GOOGLE_SEARCH:()=>Ln,GcsArtifactService:()=>Ft,Gemini:()=>ce,InMemoryArtifactService:()=>me,InMemoryMemoryService:()=>H,InMemoryPolicyEngine:()=>be,InMemoryRunner:()=>ze,InMemorySessionService:()=>ee,InvocationContext:()=>U,LLMRegistry:()=>le,LiveRequestQueue:()=>Oe,LlmAgent:()=>y,LogLevel:()=>ct,LoggingPlugin:()=>Ve,LongRunningFunctionTool:()=>Xe,LoopAgent:()=>qe,MCPSessionManager:()=>Ie,MCPTool:()=>Pe,MCPToolset:()=>Bt,ParallelAgent:()=>Ue,PluginManager:()=>ge,PolicyOutcome:()=>Mt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>_t,Runner:()=>te,SecurityPlugin:()=>Ze,SequentialAgent:()=>je,State:()=>v,StreamingMode:()=>Ge,ToolConfirmation:()=>X,ToolContext:()=>Z,createEvent:()=>E,createEventActions:()=>D,createSession:()=>Re,functionsExportedForTestingOnly:()=>Vt,getAskUserConfirmationFunctionCalls:()=>In,getFunctionCalls:()=>I,getFunctionResponses:()=>O,getGcpExporters:()=>or,getGcpResource:()=>rr,hasTrailingCodeExecutionResult:()=>ot,isBaseLlm:()=>Fe,isFinalResponse:()=>ne,maybeSetOtelProviders:()=>Qo,setLogLevel:()=>Kt,stringifyContent:()=>Dt,version:()=>Be,zodObjectToSchema:()=>xe});module.exports=to(ir);var st=require("@opentelemetry/api");function D(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function $t(o,e){let t=D();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 E(o={}){return{...o,id:o.id||rt(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||D(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function ne(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:I(o).length===0&&O(o).length===0&&!o.partial&&!ot(o)}function I(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(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 ot(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 Dt(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 Gt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function rt(){let o="";for(let e=0;e<8;e++)o+=Gt[Math.floor(Math.random()*Gt.length)];return o}var v=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};v.APP_PREFIX="app:",v.USER_PREFIX="user:",v.TEMP_PREFIX="temp:";var N=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 v(this.invocationContext.session.state,{})}};var B=class extends N{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||D(),this._state=new v(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 Le(){return typeof window<"u"}var we="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function fe(){let o="";for(let e=0;e<we.length;e++){let t=Math.random()*16|0;we[e]==="x"?o+=t.toString(16):we[e]==="y"?o+=(t&3|8).toString(16):o+=we[e]}return o}function qt(o){return Le()?window.atob(o):Buffer.from(o,"base64").toString()}var it=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},U=class{constructor(e){this.invocationCostManager=new it;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 Ut(){return`e-${fe()}`}var F=class{constructor(e){this.name=no(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=ro(this),this.beforeAgentCallback=jt(e.beforeAgentCallback),this.afterAgentCallback=jt(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=st.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=st.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${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 U({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new B({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new B({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function no(o){if(!oo(o))throw new Error(`Found invalid agent name: "${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 oo(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function ro(o){for(;o.parentAgent;)o=o.parentAgent;return o}function jt(o){return o?Array.isArray(o)?o:[o]:[]}var lt=require("@google/genai");var ve=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 ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var X=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var Z=class extends B{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 ve(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ve(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new X({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||{}),de=1;function Kt(o){de=o}var at=class{log(e,...t){if(!(e<de))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){de>0||console.debug(ke(0),...e)}info(...e){de>1||console.info(ke(1),...e)}warn(...e){de>2||console.warn(ke(2),...e)}error(...e){de>3||console.error(ke(3),...e)}},io={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},so={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},ao="\x1B[0m";function ke(o){return`${so[o]}[ADK ${io[o]}]:${ao}`}var p=new at;var ut="adk-",_e="adk_request_credential",pe="adk_request_confirmation",Vt={handleFunctionCallList:Me};function ft(){return`${ut}${fe()}`}function Zt(o){let e=I(o);if(e)for(let t of e)t.id||(t.id=ft())}function zt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(ut)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(ut)&&(e.functionResponse.id=void 0)}function Wt(o,e){if(o in e)return o;let t=o.indexOf(":");if(t>0){let n=o.substring(0,t);if(n in e)return p.info(`Resolved Gemini 3 function name "${o}" to tool "${n}"`),n}}function Yt(o,e){let t=new Set;for(let n of o){if(!n.name||!n.id)continue;let r=Wt(n.name,e);r&&e[r].isLongRunning&&t.add(n.id)}return t}function Xt(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 c={name:_e,args:{function_call_id:i,auth_config:s},id:ft()};n.add(c.id),t.push({functionCall:c})}return E({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Qt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=I(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(c=i.find(d=>d.id===a))!=null?c:void 0;if(!u)continue;let f={name:pe,args:{originalFunctionCall:u,toolConfirmation:l},id:ft()};r.add(f.id),n.push({functionCall:f})}return E({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function co(o,e,t){return p.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function Ht({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let c=I(e);return await Me({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Me({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u,f,d;let c=[],a=e.filter(h=>!i||h.id&&i.has(h.id));for(let h of a){let P;s&&h.id&&(P=s[h.id]);let T=lo({invocationContext:o,functionCall:h,toolsDict:t,toolConfirmation:P});if(!T){let A=Object.keys(t).join(", ");p.warn(`Function ${h.name} is not found in the toolsDict. Available tools: [${A}]. Returning error response to LLM.`);let Y=E({invocationId:o.invocationId,author:o.agent.name,content:(0,lt.createUserContent)({functionResponse:{id:h.id||void 0,name:(u=h.name)!=null?u:"unknown",response:{error:`Function '${h.name}' is not available. Available tools: [${A}]. Please use one of the available tools instead.`}}}),branch:o.branch});c.push(Y);continue}let{tool:g,toolContext:m}=T;p.debug(`execute_tool ${g.name}`);let C=(f=h.args)!=null?f:{},R=null,S;if(R=await o.pluginManager.runBeforeToolCallback({tool:g,toolArgs:C,toolContext:m}),R==null){for(let A of n)if(R=await A({tool:g,args:C,context:m}),R)break}if(R==null)try{R=await co(g,C,m)}catch(A){if(A instanceof Error){let Y=await o.pluginManager.runOnToolErrorCallback({tool:g,toolArgs:C,toolContext:m,error:A});Y?R=Y:S=A.message}else S=A}let k=await o.pluginManager.runAfterToolCallback({tool:g,toolArgs:C,toolContext:m,result:R});if(k==null){for(let A of r)if(k=await A({tool:g,args:C,context:m,response:R}),k)break}if(k!=null&&(R=k),g.isLongRunning&&!R)continue;S?R={error:S}:(typeof R!="object"||R==null)&&(R={result:R});let x=E({invocationId:o.invocationId,author:o.agent.name,content:(0,lt.createUserContent)({functionResponse:{id:m.functionCallId,name:(d=h.name)!=null?d:g.name,response:R}}),actions:m.actions,branch:o.branch});p.debug("traceToolCall",{tool:g.name,args:C,functionResponseEvent:x.id}),c.push(x)}if(!c.length)return null;let l=uo(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function lo({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){let r=e.name?Wt(e.name,t):void 0;if(!r)return null;let i=new Z({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[r],toolContext:i}}function uo(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=$t(n);return E({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Oe=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:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var At=require("zod");var Q=class{constructor(){this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var fo="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ne(o){let e=o.match(fo);return e?e[1]:o}function Jt(o){return Ne(o).startsWith("gemini-")}function en(o){return Ne(o).startsWith("gemini-1")}function tn(o){return Ne(o).startsWith("gemini-2")}function nn(o){let e=Ne(o);return e.startsWith("gemini-3")&&e.includes("preview")}var oe=class extends Q{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&tn(e.model)){e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${e.model}`)}};var Ee=require("@google/genai");function $(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function on(o,e){var u;if(!((u=o.parts)!=null&&u.length))return"";for(let f=0;f<o.parts.length;f++){let d=o.parts[f];if(d.executableCode&&(f===o.parts.length-1||!o.parts[f+1].codeExecutionResult))return o.parts=o.parts.slice(0,f+1),d.executableCode.code}let t=o.parts.filter(f=>f.text);if(!t.length)return"";let n=$(t[0]),r=t.map(f=>f.text).join(`
8
+ `),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),c=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:a,codeStr:l}=(c==null?void 0:c.groups)||{};return l?(o.parts=[],a&&(n.text=a,o.parts.push(n)),o.parts.push(dt(l)),l):""}function dt(o){return{text:o,executableCode:{code:o,language:Ee.Language.PYTHON}}}function rn(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:Ee.Outcome.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push(`Code execution result:
9
9
  ${o.stdout}
10
10
  `),o.outputFiles&&e.push(`Saved artifacts:
11
11
  `+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
12
12
 
13
- `),codeExecutionResult:{outcome:ye.Outcome.OUTCOME_OK}}}function sn(o,e,t){var r;if(!((r=o.parts)!=null&&r.length))return;let n=o.parts[o.parts.length-1];n.executableCode?o.parts[o.parts.length-1]={text:e[0]+n.executableCode.code+e[1]}:o.parts.length==1&&n.codeExecutionResult&&(o.parts[o.parts.length-1]={text:t[0]+n.codeExecutionResult.output+t[1]},o.role="user")}var pt="_code_execution_context",mt="execution_session_id",re="processed_input_files",ie="_code_executor_input_files",se="_code_executor_error_counts",gt="_code_execution_results",Ee=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(pt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[pt]:D(this.context)}}getExecutionId(){if(mt in this.context)return this.context[mt]}setExecutionId(e){this.context[mt]=e}getProcessedFileNames(){return re in this.context?this.context[re]:[]}addProcessedFileNames(e){re in this.context||(this.context[re]=[]),this.context[re].push(...e)}getInputFiles(){return ie in this.sessionState?this.sessionState.get(ie):[]}addInputFiles(e){ie in this.sessionState||this.sessionState.set(ie,[]),this.sessionState.get(ie).push(...e)}clearInputFiles(){ie in this.sessionState&&this.sessionState.set(ie,[]),re in this.context&&(this.context[re]=[])}getErrorCount(e){return se in this.sessionState&&this.sessionState.get(se)[e]||0}incrementErrorCount(e){se in this.sessionState||this.sessionState.set(se,{}),this.sessionState.get(se)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(se in this.sessionState))return;let t=this.sessionState.get(se);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){gt in this.sessionState||this.sessionState.set(gt,{});let i=this.sessionState.get(gt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(pt)||{}}};var Be="0.2.4";var po="google-adk",mo="gl-typescript",go="remote_reasoning_engine",ho="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Co(){let o=`${po}/${Be}`;!Le()&&process.env[ho]&&(o=`${o}+${go}`);let e=`${mo}/${Le()?window.navigator.userAgent:process.version}`;return[o,e]}function an(){return Co()}var ht=Symbol("baseModel");function Fe(o){return typeof o=="object"&&o!==null&&ht in o&&o[ht]===!0}var cn;cn=ht;var ae=class{constructor({model:e}){this[cn]=!0;this.model=e}get trackingHeaders(){let t=an().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."}]})}};ae.supportedModels=[];function xe(o,e){o.config||(o.config={});let t=e.join(`
13
+ `),codeExecutionResult:{outcome:Ee.Outcome.OUTCOME_OK}}}function sn(o,e,t){var r;if(!((r=o.parts)!=null&&r.length))return;let n=o.parts[o.parts.length-1];n.executableCode?o.parts[o.parts.length-1]={text:e[0]+n.executableCode.code+e[1]}:o.parts.length==1&&n.codeExecutionResult&&(o.parts[o.parts.length-1]={text:t[0]+n.codeExecutionResult.output+t[1]},o.role="user")}var pt="_code_execution_context",mt="execution_session_id",re="processed_input_files",ie="_code_executor_input_files",se="_code_executor_error_counts",gt="_code_execution_results",ye=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(pt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[pt]:$(this.context)}}getExecutionId(){if(mt in this.context)return this.context[mt]}setExecutionId(e){this.context[mt]=e}getProcessedFileNames(){return re in this.context?this.context[re]:[]}addProcessedFileNames(e){re in this.context||(this.context[re]=[]),this.context[re].push(...e)}getInputFiles(){return ie in this.sessionState?this.sessionState.get(ie):[]}addInputFiles(e){ie in this.sessionState||this.sessionState.set(ie,[]),this.sessionState.get(ie).push(...e)}clearInputFiles(){ie in this.sessionState&&this.sessionState.set(ie,[]),re in this.context&&(this.context[re]=[])}getErrorCount(e){return se in this.sessionState&&this.sessionState.get(se)[e]||0}incrementErrorCount(e){se in this.sessionState||this.sessionState.set(se,{}),this.sessionState.get(se)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(se in this.sessionState))return;let t=this.sessionState.get(se);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){gt in this.sessionState||this.sessionState.set(gt,{});let i=this.sessionState.get(gt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(pt)||{}}};var Be="0.2.4";var po="google-adk",mo="gl-typescript",go="remote_reasoning_engine",ho="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Co(){let o=`${po}/${Be}`;!Le()&&process.env[ho]&&(o=`${o}+${go}`);let e=`${mo}/${Le()?window.navigator.userAgent:process.version}`;return[o,e]}function an(){return Co()}var ht=Symbol("baseModel");function Fe(o){return typeof o=="object"&&o!==null&&ht in o&&o[ht]===!0}var cn;cn=ht;var ae=class{constructor({model:e}){this[cn]=!0;this.model=e}get trackingHeaders(){let t=an().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."}]})}};ae.supportedModels=[];function Ae(o,e){o.config||(o.config={});let t=e.join(`
14
14
 
15
15
  `);o.config.systemInstruction?o.config.systemInstruction+=`
16
16
 
17
- `+t:o.config.systemInstruction=t}function ln(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var j=require("@google/genai");function un(){return vo("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function vo(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var De=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"}):p.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);p.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else p.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){p.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function Ct(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 Eo="https://aiplatform.googleapis.com/v1/publishers/google",ce=class extends ae{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:c}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=nn(e);let a=typeof process=="object";this.apiEndpoint=c,!this.apiEndpoint&&a&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&(this.apiEndpoint=Eo,p.info(`Using Gemini 3 preview endpoint: ${this.apiEndpoint}`));let l=!!n;if(!l&&a){let u=process.env.GOOGLE_GENAI_USE_VERTEXAI;u&&(l=u.toLowerCase()==="true"||u==="1")}if(this.isGemini3Preview&&l){let u=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);u?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=u):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,c,a,l,u,f,d,h,P;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let T=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),g="",m,C="",S,R;for await(let k of T){R=k;let A=Ct(k);S=A.usageMetadata;let x=(s=(i=A.content)==null?void 0:i.parts)==null?void 0:s[0],Y=(a=(c=A.content)==null?void 0:c.parts)==null?void 0:a.some(M=>M.functionCall);if(this.isGemini3Preview&&((l=A.content)!=null&&l.parts)){for(let M of A.content.parts)if(M.thoughtSignature&&!m){m=M.thoughtSignature,p.debug(`[Gemini3] Captured thoughtSignature (length: ${m.length})`);break}}if(x!=null&&x.text)"thought"in x&&x.thought?(g+=x.text,"thoughtSignature"in x&&x.thoughtSignature&&(m=x.thoughtSignature)):C+=x.text,A.partial=!0,this.isGemini3Preview&&Y&&(g="",m=void 0,C="");else if((g||C)&&(!x||!x.inlineData))if(this.isGemini3Preview&&Y&&A.content){let M=[];if(g){let q={text:g,thought:!0};m&&(q.thoughtSignature=m),M.push(q)}if(C&&M.push((0,j.createPartFromText)(C)),!g&&m){for(let q of A.content.parts||[])if(q.functionCall&&!q.thoughtSignature){q.thoughtSignature=m;break}}A.content.parts=[...M,...A.content.parts||[]],g="",m=void 0,C=""}else{let M=[];if(g){let q={text:g,thought:!0};m&&(q.thoughtSignature=m),M.push(q)}C&&M.push((0,j.createPartFromText)(C)),yield{content:{role:"model",parts:M},usageMetadata:A.usageMetadata},g="",m=void 0,C=""}if(this.isGemini3Preview&&Y&&((u=A.content)!=null&&u.parts)){if(!A.content.parts.some(ue=>ue.thoughtSignature)&&m){for(let ue of A.content.parts)if(ue.functionCall){ue.thoughtSignature=m;break}}A.content.parts.filter(ue=>ue.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield A}if((C||g)&&((d=(f=R==null?void 0:R.candidates)==null?void 0:f[0])==null?void 0:d.finishReason)===j.FinishReason.STOP){let k=[];if(g){let A={text:g,thought:!0};m&&(A.thoughtSignature=m),k.push(A)}C&&k.push({text:C}),yield{content:{role:"model",parts:k},usageMetadata:S}}}else{let T=await this.apiClient.models.generateContent({model:(h=e.model)!=null?h:this.model,contents:e.contents,config:e.config}),g=Ct(T);if(this.isGemini3Preview&&((P=g.content)!=null&&P.parts)){let m,C=!1;for(let R of g.content.parts)if(R.thoughtSignature){m=R.thoughtSignature,R.thought&&(C=!0);break}if(m&&!C){for(let R of g.content.parts)if(R.functionCall&&!R.thoughtSignature){R.thoughtSignature=m;break}}g.content.parts.some(R=>R.functionCall)&&g.content.parts.filter(k=>k.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield g}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new j.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,p.debug(`Using custom API endpoint: ${this.apiEndpoint}`),this.isGemini3Preview&&(t.apiVersion="",p.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new j.GoogleGenAI({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return 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(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};this.apiEndpoint&&(e.baseUrl=this.apiEndpoint,this.isGemini3Preview&&(e.apiVersion="")),this._liveApiClient=new j.GoogleGenAI({apiKey:this.apiKey,httpOptions:e})}return 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.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,j.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new De(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)fn(n.inlineData),fn(n.fileData)}}};ce.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function fn(o){o&&o.displayName&&(o.displayName=void 0)}var vt=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)}},G=class G{static newLlm(e){return new(G.resolve(e))({model:e})}static _register(e,t){G.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${G.llmRegistryDict.get(e)} to ${t}`),G.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)G._register(t,e)}static resolve(e){let t=G.resolveCache.get(e);if(t)return t;for(let[n,r]of G.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return G.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};G.llmRegistryDict=new Map,G.resolveCache=new vt(32);var le=G;le.register(ce);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=xo(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 un()}};function xo(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var pn=require("@google/genai"),mn=require("zod");var w=require("@google/genai"),b=require("zod");function dn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function z(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 b.z.ZodFirstPartyTypeKind.ZodString:n.type=w.Type.STRING;for(let a of e.checks||[])a.kind==="min"?n.minLength=a.value.toString():a.kind==="max"?n.maxLength=a.value.toString():a.kind==="email"?n.format="email":a.kind==="uuid"?n.format="uuid":a.kind==="url"?n.format="uri":a.kind==="regex"&&(n.pattern=a.regex.source);return r(n);case b.z.ZodFirstPartyTypeKind.ZodNumber:n.type=w.Type.NUMBER;for(let a of e.checks||[])a.kind==="min"?n.minimum=a.value:a.kind==="max"?n.maximum=a.value:a.kind==="int"&&(n.type=w.Type.INTEGER);return r(n);case b.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=w.Type.BOOLEAN,r(n);case b.z.ZodFirstPartyTypeKind.ZodArray:return n.type=w.Type.ARRAY,n.items=z(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case b.z.ZodFirstPartyTypeKind.ZodObject:return Ae(o);case b.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=w.Type.STRING;else if(i==="number")n.type=w.Type.NUMBER;else if(i==="boolean")n.type=w.Type.BOOLEAN;else if(e.value===null)n.type=w.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case b.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=w.Type.STRING,n.enum=e.values,r(n);case b.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=w.Type.STRING,n.enum=Object.values(e.values),r(n);case b.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(z),r(n);case b.z.ZodFirstPartyTypeKind.ZodOptional:return z(e.innerType);case b.z.ZodFirstPartyTypeKind.ZodNullable:let s=z(e.innerType);return r(s?{anyOf:[s,{type:w.Type.NULL}],...t&&{description:t}}:{type:w.Type.NULL,...t&&{description:t}});case b.z.ZodFirstPartyTypeKind.ZodDefault:let c=z(e.innerType);return c&&(c.default=e.defaultValue()),c;case b.z.ZodFirstPartyTypeKind.ZodBranded:return z(e.type);case b.z.ZodFirstPartyTypeKind.ZodReadonly:return z(e.innerType);case b.z.ZodFirstPartyTypeKind.ZodNull:return n.type=w.Type.NULL,r(n);case b.z.ZodFirstPartyTypeKind.ZodAny:case b.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Ae(o){if(o._def.typeName!==b.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let c=e[s],a=z(c);a&&(t[s]=a);let l=c,u=!1;for(;l._def.typeName===b.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===b.z.ZodFirstPartyTypeKind.ZodDefault;)u=!0,l=l._def.innerType;u||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==b.z.ZodFirstPartyTypeKind.ZodNever?i=z(r)||!0:i=o._def.unknownKeys==="passthrough",{type:w.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Ao(o){return o===void 0?{type:pn.Type.OBJECT,properties:{}}:dn(o)?Ae(o):o}var K=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:Ao(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof mn.ZodObject&&(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 '${this.name}': ${n}`)}}};var W=class{};function yt(o,e,t){var s,c;let n=[];for(let a of o)!((s=a.content)!=null&&s.role)||!((c=a.content.parts)!=null&&c.length)||t&&a.branch&&!t.startsWith(a.branch)||bo(a)||To(a)||n.push(Cn(e,a)?So(a):a);let r=Ro(n);r=Io(r);let i=[];for(let a of r){let l=D(a.content);zt(l),i.push(l)}return i}function hn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Cn(e,r))return yt(o.slice(n),e,t)}return[]}function bo(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)===_e||((n=r.functionResponse)==null?void 0:n.name)===_e)return!0;return!1}function To(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)===pe||((n=r.functionResponse)==null?void 0:n.name)===pe)return!0;return!1}function Cn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function So(o){var t,n,r,i,s,c;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 a of o.content.parts)if(a.text&&!a.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${a.text}`});else if(a.functionCall){let l=gn(a.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${a.functionCall.name}\` with parameters: ${l}`})}else if(a.functionResponse){let l=gn(a.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${a.functionResponse.name}\` returned result: ${l}`})}else(c=e.parts)==null||c.push(a);return y({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function vn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=y(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 c=s.functionResponse.id;c in n?t[n[c]]=s:(t.push(s),n[c]=t.length-1)}else t.push(s)}return e}function Ro(o){if(o.length===0)return o;let e=o[o.length-1],t=O(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(a=>!!a.id).map(a=>a.id)),r=o.at(-2);if(r){let a=I(r);if(a){for(let l of a)if(l.id&&n.has(l.id))return o}}let i=-1;for(let a=o.length-2;a>=0;a--){let l=o[a],u=I(l);if(u!=null&&u.length){for(let f of u)if(f.id&&n.has(f.id)){i=a;let d=new Set(u.map(P=>P.id).filter(P=>!!P));if(!Array.from(n).every(P=>d.has(P)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let a=i+1;a<o.length-1;a++){let l=o[a],u=O(l);u&&u.some(f=>f.id&&n.has(f.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(vn(s)),c}function Io(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=O(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(O(n).length>0)continue;let r=I(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let c=s.id;c&&e.has(c)&&i.add(e.get(c))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let c=Array.from(i).sort((a,l)=>a-l).map(a=>o[a]);t.push(vn(c))}}else t.push(n)}return t}function gn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Et(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!d)throw new Error(`Artifact ${f} not found.`);return String(d)}if(!Lo(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(u)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,c=o.matchAll(r);for(let a of c){i.push(o.slice(s,a.index));let l=await n(a);i.push(l),s=a.index+a[0].length}return i.push(o.slice(s)),i.join("")}var Po=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function yn(o){return o===""||o===void 0?!1:Po.test(o)}var wo=[v.APP_PREFIX,v.USER_PREFIX,v.TEMP_PREFIX];function Lo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?yn(o):wo.includes(e[0]+":")?yn(e[1]):!1}var Ge=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ge||{});function En(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ko(o.maxLlmCalls||500),...o}}function ko(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&p.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 xn="adk_agent_name";async function An(o,e){return o instanceof _?[o]:await o.getTools(e)}var At=class extends W{async*runAsync(e,t){var r;let n=e.agent;n instanceof E&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&ln(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))}},_o=new At,bt=class extends W{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),xe(t,r)}},Mo=new bt,Tt=class extends W{async*runAsync(e,t){let n=e.agent;if(!(n instanceof E)||!(n.rootAgent instanceof E))return;let r=n.rootAgent;if(r instanceof E&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new N(e)),c=i;s&&(c=await Et(i,new N(e))),xe(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new N(e)),c=i;s&&(c=await Et(i,new N(e))),xe(t,[c])}}},Oo=new Tt,St=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof E)||(n.includeContents==="default"?t.contents=yt(e.session.events,n.name,e.branch):t.contents=hn(e.session.events,n.name,e.branch))}},No=new St,Rt=class extends W{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new K({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:xt.z.object({agentName:xt.z.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"}})}async*runAsync(t,n){if(!(t.agent instanceof E))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;xe(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new Z({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
17
+ `+t:o.config.systemInstruction=t}function ln(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var j=require("@google/genai");function un(){return vo("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function vo(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var $e=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"}):p.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);p.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else p.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){p.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function Ct(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 yo="https://aiplatform.googleapis.com/v1/publishers/google",ce=class extends ae{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:c}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=nn(e);let a=typeof process=="object";this.apiEndpoint=c,!this.apiEndpoint&&a&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&(this.apiEndpoint=yo,p.info(`Using Gemini 3 preview endpoint: ${this.apiEndpoint}`));let l=!!n;if(!l&&a){let u=process.env.GOOGLE_GENAI_USE_VERTEXAI;u&&(l=u.toLowerCase()==="true"||u==="1")}if(this.isGemini3Preview&&l){let u=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);u?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=u):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,c,a,l,u,f,d,h,P;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let T=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),g="",m,C="",R,S;for await(let k of T){S=k;let x=Ct(k);R=x.usageMetadata;let A=(s=(i=x.content)==null?void 0:i.parts)==null?void 0:s[0],Y=(a=(c=x.content)==null?void 0:c.parts)==null?void 0:a.some(M=>M.functionCall);if(this.isGemini3Preview&&((l=x.content)!=null&&l.parts)){for(let M of x.content.parts)if(M.thoughtSignature&&!m){m=M.thoughtSignature,p.debug(`[Gemini3] Captured thoughtSignature (length: ${m.length})`);break}}if(A!=null&&A.text)"thought"in A&&A.thought?(g+=A.text,"thoughtSignature"in A&&A.thoughtSignature&&(m=A.thoughtSignature)):C+=A.text,x.partial=!0,this.isGemini3Preview&&Y&&(g="",m=void 0,C="");else if((g||C)&&(!A||!A.inlineData))if(this.isGemini3Preview&&Y&&x.content){let M=[];if(g){let q={text:g,thought:!0};m&&(q.thoughtSignature=m),M.push(q)}if(C&&M.push((0,j.createPartFromText)(C)),!g&&m){for(let q of x.content.parts||[])if(q.functionCall&&!q.thoughtSignature){q.thoughtSignature=m;break}}x.content.parts=[...M,...x.content.parts||[]],g="",m=void 0,C=""}else{let M=[];if(g){let q={text:g,thought:!0};m&&(q.thoughtSignature=m),M.push(q)}C&&M.push((0,j.createPartFromText)(C)),yield{content:{role:"model",parts:M},usageMetadata:x.usageMetadata},g="",m=void 0,C=""}if(this.isGemini3Preview&&Y&&((u=x.content)!=null&&u.parts)){if(!x.content.parts.some(ue=>ue.thoughtSignature)&&m){for(let ue of x.content.parts)if(ue.functionCall){ue.thoughtSignature=m;break}}x.content.parts.filter(ue=>ue.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield x}if((C||g)&&((d=(f=S==null?void 0:S.candidates)==null?void 0:f[0])==null?void 0:d.finishReason)===j.FinishReason.STOP){let k=[];if(g){let x={text:g,thought:!0};m&&(x.thoughtSignature=m),k.push(x)}C&&k.push({text:C}),yield{content:{role:"model",parts:k},usageMetadata:R}}}else{let T=await this.apiClient.models.generateContent({model:(h=e.model)!=null?h:this.model,contents:e.contents,config:e.config}),g=Ct(T);if(this.isGemini3Preview&&((P=g.content)!=null&&P.parts)){let m,C=!1;for(let S of g.content.parts)if(S.thoughtSignature){m=S.thoughtSignature,S.thought&&(C=!0);break}if(m&&!C){for(let S of g.content.parts)if(S.functionCall&&!S.thoughtSignature){S.thoughtSignature=m;break}}g.content.parts.some(S=>S.functionCall)&&g.content.parts.filter(k=>k.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield g}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new j.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,p.debug(`Using custom API endpoint: ${this.apiEndpoint}`),this.isGemini3Preview&&(t.apiVersion="",p.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new j.GoogleGenAI({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return 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(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};this.apiEndpoint&&(e.baseUrl=this.apiEndpoint,this.isGemini3Preview&&(e.apiVersion="")),this._liveApiClient=new j.GoogleGenAI({apiKey:this.apiKey,httpOptions:e})}return 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.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,j.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new $e(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)fn(n.inlineData),fn(n.fileData)}}};ce.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function fn(o){o&&o.displayName&&(o.displayName=void 0)}var vt=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)}},G=class G{static newLlm(e){return new(G.resolve(e))({model:e})}static _register(e,t){G.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${G.llmRegistryDict.get(e)} to ${t}`),G.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)G._register(t,e)}static resolve(e){let t=G.resolveCache.get(e);if(t)return t;for(let[n,r]of G.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return G.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};G.llmRegistryDict=new Map,G.resolveCache=new vt(32);var le=G;le.register(ce);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=Ao(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 un()}};function Ao(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var pn=require("@google/genai"),mn=require("zod");var L=require("@google/genai"),b=require("zod");function dn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function z(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 b.z.ZodFirstPartyTypeKind.ZodString:n.type=L.Type.STRING;for(let a of e.checks||[])a.kind==="min"?n.minLength=a.value.toString():a.kind==="max"?n.maxLength=a.value.toString():a.kind==="email"?n.format="email":a.kind==="uuid"?n.format="uuid":a.kind==="url"?n.format="uri":a.kind==="regex"&&(n.pattern=a.regex.source);return r(n);case b.z.ZodFirstPartyTypeKind.ZodNumber:n.type=L.Type.NUMBER;for(let a of e.checks||[])a.kind==="min"?n.minimum=a.value:a.kind==="max"?n.maximum=a.value:a.kind==="int"&&(n.type=L.Type.INTEGER);return r(n);case b.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=L.Type.BOOLEAN,r(n);case b.z.ZodFirstPartyTypeKind.ZodArray:return n.type=L.Type.ARRAY,n.items=z(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case b.z.ZodFirstPartyTypeKind.ZodObject:return xe(o);case b.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=L.Type.STRING;else if(i==="number")n.type=L.Type.NUMBER;else if(i==="boolean")n.type=L.Type.BOOLEAN;else if(e.value===null)n.type=L.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case b.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=L.Type.STRING,n.enum=e.values,r(n);case b.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=L.Type.STRING,n.enum=Object.values(e.values),r(n);case b.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(z),r(n);case b.z.ZodFirstPartyTypeKind.ZodOptional:return z(e.innerType);case b.z.ZodFirstPartyTypeKind.ZodNullable:let s=z(e.innerType);return r(s?{anyOf:[s,{type:L.Type.NULL}],...t&&{description:t}}:{type:L.Type.NULL,...t&&{description:t}});case b.z.ZodFirstPartyTypeKind.ZodDefault:let c=z(e.innerType);return c&&(c.default=e.defaultValue()),c;case b.z.ZodFirstPartyTypeKind.ZodBranded:return z(e.type);case b.z.ZodFirstPartyTypeKind.ZodReadonly:return z(e.innerType);case b.z.ZodFirstPartyTypeKind.ZodNull:return n.type=L.Type.NULL,r(n);case b.z.ZodFirstPartyTypeKind.ZodAny:case b.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function xe(o){if(o._def.typeName!==b.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let c=e[s],a=z(c);a&&(t[s]=a);let l=c,u=!1;for(;l._def.typeName===b.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===b.z.ZodFirstPartyTypeKind.ZodDefault;)u=!0,l=l._def.innerType;u||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==b.z.ZodFirstPartyTypeKind.ZodNever?i=z(r)||!0:i=o._def.unknownKeys==="passthrough",{type:L.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function xo(o){return o===void 0?{type:pn.Type.OBJECT,properties:{}}:dn(o)?xe(o):o}var K=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:xo(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof mn.ZodObject&&(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 '${this.name}': ${n}`)}}};var W=class{};function Et(o,e,t){var s,c;let n=[];for(let a of o)!((s=a.content)!=null&&s.role)||!((c=a.content.parts)!=null&&c.length)||t&&a.branch&&!t.startsWith(a.branch)||bo(a)||To(a)||n.push(Cn(e,a)?Ro(a):a);let r=So(n);r=Io(r);let i=[];for(let a of r){let l=$(a.content);zt(l),i.push(l)}return i}function hn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Cn(e,r))return Et(o.slice(n),e,t)}return[]}function bo(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)===_e||((n=r.functionResponse)==null?void 0:n.name)===_e)return!0;return!1}function To(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)===pe||((n=r.functionResponse)==null?void 0:n.name)===pe)return!0;return!1}function Cn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function Ro(o){var t,n,r,i,s,c;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 a of o.content.parts)if(a.text&&!a.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${a.text}`});else if(a.functionCall){let l=gn(a.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${a.functionCall.name}\` with parameters: ${l}`})}else if(a.functionResponse){let l=gn(a.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${a.functionResponse.name}\` returned result: ${l}`})}else(c=e.parts)==null||c.push(a);return E({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function vn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=E(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 c=s.functionResponse.id;c in n?t[n[c]]=s:(t.push(s),n[c]=t.length-1)}else t.push(s)}return e}function So(o){if(o.length===0)return o;let e=o[o.length-1],t=O(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(a=>!!a.id).map(a=>a.id)),r=o.at(-2);if(r){let a=I(r);if(a){for(let l of a)if(l.id&&n.has(l.id))return o}}let i=-1;for(let a=o.length-2;a>=0;a--){let l=o[a],u=I(l);if(u!=null&&u.length){for(let f of u)if(f.id&&n.has(f.id)){i=a;let d=new Set(u.map(P=>P.id).filter(P=>!!P));if(!Array.from(n).every(P=>d.has(P)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let a=i+1;a<o.length-1;a++){let l=o[a],u=O(l);u&&u.some(f=>f.id&&n.has(f.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(vn(s)),c}function Io(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=O(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(O(n).length>0)continue;let r=I(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let c=s.id;c&&e.has(c)&&i.add(e.get(c))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let c=Array.from(i).sort((a,l)=>a-l).map(a=>o[a]);t.push(vn(c))}}else t.push(n)}return t}function gn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function yt(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!d)throw new Error(`Artifact ${f} not found.`);return String(d)}if(!Lo(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(u)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,c=o.matchAll(r);for(let a of c){i.push(o.slice(s,a.index));let l=await n(a);i.push(l),s=a.index+a[0].length}return i.push(o.slice(s)),i.join("")}var Po=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function En(o){return o===""||o===void 0?!1:Po.test(o)}var wo=[v.APP_PREFIX,v.USER_PREFIX,v.TEMP_PREFIX];function Lo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?En(o):wo.includes(e[0]+":")?En(e[1]):!1}var Ge=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ge||{});function yn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ko(o.maxLlmCalls||500),...o}}function ko(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&p.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 An="adk_agent_name";async function xn(o,e){return o instanceof _?[o]:await o.getTools(e)}var xt=class extends W{async*runAsync(e,t){var r;let n=e.agent;n instanceof y&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&ln(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))}},_o=new xt,bt=class extends W{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),Ae(t,r)}},Mo=new bt,Tt=class extends W{async*runAsync(e,t){let n=e.agent;if(!(n instanceof y)||!(n.rootAgent instanceof y))return;let r=n.rootAgent;if(r instanceof y&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new N(e)),c=i;s&&(c=await yt(i,new N(e))),Ae(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new N(e)),c=i;s&&(c=await yt(i,new N(e))),Ae(t,[c])}}},Oo=new Tt,Rt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof y)||(n.includeContents==="default"?t.contents=Et(e.session.events,n.name,e.branch):t.contents=hn(e.session.events,n.name,e.branch))}},No=new Rt,St=class extends W{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new K({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:At.z.object({agentName:At.z.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"}})}async*runAsync(t,n){if(!(t.agent instanceof y))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;Ae(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new Z({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
18
18
  Agent name: ${t.name}
19
19
  Agent description: ${t.description}
20
20
  `}buildTargetAgentsInstructions(t,n){let r=`
@@ -34,7 +34,7 @@ the function call.
34
34
  Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
35
35
  you are best for answering the question according to the descriptions, transfer
36
36
  to your parent agent.
37
- `),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof E)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},Bo=new Rt,It=class extends W{async*runAsync(e,t){let n=e.agent;if(!(n instanceof E))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let c=r.length-1;c>=0;c--){let a=r[c];if(a.author!=="user")continue;let l=O(a);if(!l)continue;let u=!1;for(let f of l){if(f.name!==pe)continue;u=!0;let d=null;f.response&&Object.keys(f.response).length===1&&"response"in f.response?d=JSON.parse(f.response.response):f.response&&(d=new X({hint:f.response.hint,payload:f.response.payload,confirmed:f.response.confirmed})),f.id&&d&&(i[f.id]=d)}if(u){s=c;break}}if(Object.keys(i).length!==0)for(let c=s-1;c>=0;c--){let a=r[c],l=I(a);if(!l)continue;let u={},f={};for(let T of l){if(!T.id||!(T.id in i))continue;let g=T.args;if(!g||!("originalFunctionCall"in g))continue;let m=g.originalFunctionCall;m.id&&(u[m.id]=i[T.id],f[m.id]=m)}if(Object.keys(u).length===0)continue;for(let T=r.length-1;T>s;T--){let g=r[T],m=O(g);if(m){for(let C of m)C.id&&C.id in u&&(delete u[C.id],delete f[C.id]);if(Object.keys(u).length===0)break}}if(Object.keys(u).length===0)continue;let d=await n.canonicalTools(new N(e)),h=Object.fromEntries(d.map(T=>[T.name,T])),P=await Me({invocationContext:e,functionCalls:Object.values(f),toolsDict:h,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(u)),toolConfirmationDict:u});P&&(yield P);return}}},Fo=new It,Pt=class extends W{async*runAsync(e,t){if(e.agent instanceof E&&e.agent.codeExecutor){for await(let n of Go(e,t))yield n;if(e.agent.codeExecutor instanceof Q)for(let n of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],i=sn(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},$e={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Do=`
37
+ `),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof y)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},Bo=new St,It=class extends W{async*runAsync(e,t){let n=e.agent;if(!(n instanceof y))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let c=r.length-1;c>=0;c--){let a=r[c];if(a.author!=="user")continue;let l=O(a);if(!l)continue;let u=!1;for(let f of l){if(f.name!==pe)continue;u=!0;let d=null;f.response&&Object.keys(f.response).length===1&&"response"in f.response?d=JSON.parse(f.response.response):f.response&&(d=new X({hint:f.response.hint,payload:f.response.payload,confirmed:f.response.confirmed})),f.id&&d&&(i[f.id]=d)}if(u){s=c;break}}if(Object.keys(i).length!==0)for(let c=s-1;c>=0;c--){let a=r[c],l=I(a);if(!l)continue;let u={},f={};for(let T of l){if(!T.id||!(T.id in i))continue;let g=T.args;if(!g||!("originalFunctionCall"in g))continue;let m=g.originalFunctionCall;m.id&&(u[m.id]=i[T.id],f[m.id]=m)}if(Object.keys(u).length===0)continue;for(let T=r.length-1;T>s;T--){let g=r[T],m=O(g);if(m){for(let C of m)C.id&&C.id in u&&(delete u[C.id],delete f[C.id]);if(Object.keys(u).length===0)break}}if(Object.keys(u).length===0)continue;let d=await n.canonicalTools(new N(e)),h=Object.fromEntries(d.map(T=>[T.name,T])),P=await Me({invocationContext:e,functionCalls:Object.values(f),toolsDict:h,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(u)),toolConfirmationDict:u});P&&(yield P);return}}},Fo=new It,Pt=class extends W{async*runAsync(e,t){if(e.agent instanceof y&&e.agent.codeExecutor){for await(let n of Go(e,t))yield n;if(e.agent.codeExecutor instanceof Q)for(let n of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],i=sn(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},De={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},$o=`
38
38
  import pandas as pd
39
39
 
40
40
  def explore_df(df: pd.DataFrame) -> None:
@@ -71,20 +71,20 @@ def explore_df(df: pd.DataFrame) -> None:
71
71
  Total columns: {df.shape[1]}
72
72
 
73
73
  {df_info}""")
74
- `,wt=class{async*runAsync(e,t){if(!t.partial)for await(let n of $o(e,t))yield n}},Os=new wt;async function*Go(o,e){let t=o.agent;if(!(t instanceof E))return;let n=t.codeExecutor;if(!n||!(n instanceof Q))return;if(n instanceof oe){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new Ee(new v(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=qo(r,e),s=new Set(r.getProcessedFileNames()),c=i.filter(a=>!s.has(a.name));for(let a of c){let l=Uo(a);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${a.name}\``},dt(l)]};e.contents.push(D(u)),yield y({invocationId:o.invocationId,author:t.name,branch:o.branch,content:u});let f=bn(o,r),d=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[a],executionId:f}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([a.name]);let h=await Tn(o,r,d);yield h,e.contents.push(D(h.content))}}async function*$o(o,e){let t=o.agent;if(!(t instanceof E))return;let n=t.codeExecutor;if(!n||!(n instanceof Q)||!e||!e.content||n instanceof oe)return;let r=new Ee(new v(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=on(i,n.codeBlockDelimiters);if(!s)return;yield y({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let c=bn(o,r),a=await n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:c}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:a.stdout,resultStderr:a.stderr}),yield await Tn(o,r,a),e.content=null}function qo(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let c=0;c<s.parts.length;c++){let a=s.parts[c],l=(r=a.inlineData)==null?void 0:r.mimeType;if(!l||!a.inlineData||!$e[l])continue;let u=`data_${i+1}_${c+1}${$e[l].extension}`;a.text=`
74
+ `,wt=class{async*runAsync(e,t){if(!t.partial)for await(let n of Do(e,t))yield n}},Os=new wt;async function*Go(o,e){let t=o.agent;if(!(t instanceof y))return;let n=t.codeExecutor;if(!n||!(n instanceof Q))return;if(n instanceof oe){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new ye(new v(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=qo(r,e),s=new Set(r.getProcessedFileNames()),c=i.filter(a=>!s.has(a.name));for(let a of c){let l=Uo(a);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${a.name}\``},dt(l)]};e.contents.push($(u)),yield E({invocationId:o.invocationId,author:t.name,branch:o.branch,content:u});let f=bn(o,r),d=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[a],executionId:f}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([a.name]);let h=await Tn(o,r,d);yield h,e.contents.push($(h.content))}}async function*Do(o,e){let t=o.agent;if(!(t instanceof y))return;let n=t.codeExecutor;if(!n||!(n instanceof Q)||!e||!e.content||n instanceof oe)return;let r=new ye(new v(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=on(i,n.codeBlockDelimiters);if(!s)return;yield E({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let c=bn(o,r),a=await n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:c}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:a.stdout,resultStderr:a.stderr}),yield await Tn(o,r,a),e.content=null}function qo(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let c=0;c<s.parts.length;c++){let a=s.parts[c],l=(r=a.inlineData)==null?void 0:r.mimeType;if(!l||!a.inlineData||!De[l])continue;let u=`data_${i+1}_${c+1}${De[l].extension}`;a.text=`
75
75
  Available file: \`${u}\`
76
- `;let f={name:u,content:qt(a.inlineData.data),mimeType:l};n.has(u)||(o.addInputFiles([f]),t.push(f))}}return t}function bn(o,e){var r;let t=o.agent;if(!(t instanceof E)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function Tn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[rn(t)]},r=$({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(o.invocationId):e.resetErrorCount(o.invocationId);for(let i of t.outputFiles){let s=await o.artifactService.saveArtifact({appName:o.appName||"",userId:o.userId||"",sessionId:o.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Uo(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!$e[o.mimeType])return;let t=e(o.name),n=$e[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return`
77
- ${Do}
76
+ `;let f={name:u,content:qt(a.inlineData.data),mimeType:l};n.has(u)||(o.addInputFiles([f]),t.push(f))}}return t}function bn(o,e){var r;let t=o.agent;if(!(t instanceof y)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function Tn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[rn(t)]},r=D({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(o.invocationId):e.resetErrorCount(o.invocationId);for(let i of t.outputFiles){let s=await o.artifactService.saveArtifact({appName:o.appName||"",userId:o.userId||"",sessionId:o.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return E({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Uo(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!De[o.mimeType])return;let t=e(o.name),n=De[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return`
77
+ ${$o}
78
78
 
79
79
  # Load the dataframe.
80
80
  ${t} = ${n}
81
81
 
82
82
  # Use \`explore_df\` to guide my analysis.
83
83
  explore_df(${t})
84
- `}var jo=new Pt,L=class L extends F{constructor(e){var n,r,i,s,c,a,l,u,f;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=(c=e.disallowTransferToPeers)!=null?c:!1,this.includeContents=(a=e.includeContents)!=null?a:"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.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[_o,Mo,Oo,Fo,No,jo],this.responseProcessors=(u=e.responseProcessors)!=null?u:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((f=this.subAgents)!=null&&f.length)||this.requestProcessors.push(Bo),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)&&(p.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(Fe(this.model))return this.model;if(typeof this.model=="string"&&this.model)return le.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof L)return e.canonicalModel;e=e.parentAgent}throw new Error(`No model found for ${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 An(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return L.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return L.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return L.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return L.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){p.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!ne(e)){p.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug(`Skipping output save for agent ${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){p.error(`Error parsing output for agent ${this.name}`,s)}}e.actions.stateDelta[this.outputKey]=n}async*runAsyncImpl(e){for(;;){let t;for await(let n of this.runOneStepAsync(e))t=n,this.maybeSaveOutputToState(n),yield n;if(!t||ne(t))break;if(t.partial){p.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(e){for await(let t of this.runLiveFlow(e))this.maybeSaveOutputToState(t),yield t;e.endInvocation}async*runLiveFlow(e){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(e){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let r of this.requestProcessors)for await(let i of r.runAsync(e,t))yield i;for(let r of this.tools){let i=new Z({invocationContext:e}),s=await An(r,new N(e));for(let c of s)await c.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=y({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))try{for await(let i of this.postprocess(e,t,r,n))n.id=rt(),n.timestamp=new Date().getTime(),yield i}catch(i){let s=i instanceof Error?i.message:String(i);p.error(`Postprocess error: ${s}`),yield y({invocationId:e.invocationId,author:this.name,branch:e.branch,errorCode:"POSTPROCESS_ERROR",errorMessage:s})}}async*postprocess(e,t,n,r){var u,f;for(let d of this.responseProcessors)for await(let h of d.runAsync(e,n))yield h;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=y({...r,...n});if(i.content){let d=I(i);d!=null&&d.length&&(Zt(i),i.longRunningToolIds=Array.from(Yt(d,t.toolsDict)),(u=i.content.parts)!=null&&u.some(P=>P.thoughtSignature)||p.warn(`[postprocess] Function calls (${d.length}) without thoughtSignature`))}if(yield i,!((f=I(i))!=null&&f.length))return;let s=await Ht({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let c=Xt(e,s);c&&(yield c);let a=Qt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),yield s;let l=s.actions.transferToAgent;if(l){let d=this.getAgentByName(e,l);for await(let h of d.runAsync(e))yield h}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,c,a,l,u;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(a=(c=t.config).labels)!=null||(c.labels={}),t.config.labels[xn]||(t.config.labels[xn]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let f=((u=e.runConfig)==null?void 0:u.streamingMode)==="sse",d=L.LLM_TRANSIENT_ERROR_MAX_RETRIES;for(let h=0;h<=d;h++){if(h>0){let m=Math.min(L.LLM_TRANSIENT_ERROR_BASE_DELAY_MS*Math.pow(2,h-1),L.LLM_TRANSIENT_ERROR_MAX_DELAY_MS);p.warn(`[callLlmAsync] Retrying LLM call after transient error (attempt ${h+1}/${d+1}), waiting ${m}ms`),await new Promise(C=>setTimeout(C,m))}let P=i.generateContentAsync(t,f),T=!1,g=!1;for await(let m of this.runAndHandleError(P,e,t,n)){if(m.content&&(g=!0),m.errorCode&&L.LLM_RETRYABLE_ERROR_CODES.has(m.errorCode)&&!g&&h<d){T=!0,p.warn(`[callLlmAsync] Transient LLM error: ${m.errorCode}, usage: ${JSON.stringify(m.usageMetadata)}`);break}let C=await this.handleAfterModelCallback(e,m,n);yield C!=null?C:m}if(!T)return}}}async handleBeforeModelCallback(e,t,n){let r=new B({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 c=await s({context:r,request:t});if(c)return c}}async handleAfterModelCallback(e,t,n){let r=new B({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 c=await s({context:r,response:t});if(c)return c}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new B({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let c=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(c)yield c;else try{let a=JSON.parse(i.message);yield{errorCode:String(a.error.code),errorMessage:a.error.message}}catch{p.warn(`LLM error message is not valid JSON, using raw message: ${i.message.substring(0,200)}`),yield{errorCode:"UNKNOWN_ERROR",errorMessage:i.message}}}else throw p.error("Unknown error during response generation",i),i}}};L.LLM_TRANSIENT_ERROR_MAX_RETRIES=2,L.LLM_TRANSIENT_ERROR_BASE_DELAY_MS=1e3,L.LLM_TRANSIENT_ERROR_MAX_DELAY_MS=4e3,L.LLM_RETRYABLE_ERROR_CODES=new Set(["UNKNOWN_ERROR"]);var E=L;var qe=class extends F{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(e){let t=0;for(;t<this.maxIterations;){for(let n of this.subAgents){let r=!1;for await(let i of n.runAsync(e))yield i,i.actions.escalate&&(r=!0);if(r)return}t++}}async*runLiveImpl(e){throw new Error("This is not supported yet for LoopAgent.")}};var Ue=class extends F{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(Ko(this,n,e)));for await(let n of Vo(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function Ko(o,e,t){let n=new U(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Vo(o){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}=await 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 Lt="task_completed",je=class extends F{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof E&&((await t.canonicalTools(new N(e))).some(i=>i.name===Lt)||(t.tools.push(new K({name:Lt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),t.instruction+=`If you finished the user's request according to its description, call the ${Lt} 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 t of this.subAgents)for await(let n of t.runLive(e))yield n}};var me=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=Ke(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let c=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(c)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=Ke(e,t,n,r),c=this.artifacts[s];return c?(i===void 0&&(i=c.length-1),Promise.resolve(c[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let c in this.artifacts)if(c.startsWith(r)){let a=c.replace(r,"");s.push(a)}else if(c.startsWith(i)){let a=c.replace(i,"");s.push(a)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=Ke(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=Ke(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let c=[];for(let a=0;a<s.length;a++)c.push(a);return Promise.resolve(c)}};function Ke(o,e,t,n){return Zo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Zo(o){return o.startsWith("user:")}var H=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Sn(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=Sn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let c of Object.values(this.sessionEvents[t]))for(let a of c){if(!((s=(i=a.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=a.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),u=zo(l);if(!u.size)continue;n.some(d=>u.has(d))&&r.memories.push({content:a.content,author:a.author,timestamp:Wo(a.timestamp)})}return r}};function Sn(o,e){return`${o}/${e}`}function zo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Wo(o){return new Date(o).toISOString()}var J=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 Ve=class extends J{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: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${ne(t)}`);let n=I(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=O(t);if(r.length>0){let i=r.map(s=>s.name);this.log(` Function Responses: ${i}`)}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...t.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`),t.invocationContext.branch&&this.log(` Branch: ${t.invocationContext.branch}`)}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(n=t.model)!=null?n:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Result: ${this.formatArgs(r)}`)}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${n}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;p.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: '${i}'`)}else r.functionCall?n.push(`function_call: ${r.functionCall.name}`):r.functionResponse?n.push(`function_response: ${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 ge=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),p.info(`Plugin '${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 p.debug(`Plugin '${r.name}' returned a value for callback '${n}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${n}' callback: ${i}`;throw p.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 _t="adk_request_confirmation",kt="orcas_tool_call_security_check_states",Rn="This tool call needs external confirmation before completion.",Mt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Mt||{}),be=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Ze=class extends J{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new be}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:Rn};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(kt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(kt))!=null?i:{};r[n]=t,e.state.set(kt,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: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:Rn};case"ALLOW":return;default:return}}};function In(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===_t&&e.push(t.functionCall);return e}var Te=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(v.TEMP_PREFIX)||(e.state[n]=r)}};function Se(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var ee=class extends Te{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Se({id:i||fe(),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,D(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],c=D(s);if(i&&(i.numRecentEvents&&(c.events=c.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let a=c.events.length-1;for(;a>=0&&!(c.events[a].timestamp<i.afterTimestamp);)a--;a>=0&&(c.events=c.events.slice(a+1))}return Promise.resolve(this.mergeState(t,n,c))}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(Se({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,c=l=>{p.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return c(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return c(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return c(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(v.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(v.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(v.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(v.USER_PREFIX,"")]=n.actions.stateDelta[l]);let a=this.sessions[r][i][s];return await super.appendEvent({session:a,event:n}),a.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[v.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[v.USER_PREFIX+i]=this.userState[t][n][i];return r}};var Pn=require("@google/genai"),wn=require("@opentelemetry/api");var te=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ge((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var c;i=En(i);let s=wn.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let a=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!a)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof E){let d=this.agent.canonicalModel.model;if(!d.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${d} in agent: ${this.agent.name}`)}let l=new U({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Ut(),agent:this.agent,session:a,userContent:n,runConfig:i,pluginManager:this.pluginManager}),u=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(u&&(n=u),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,a.userId,a.id,n),await this.sessionService.appendEvent({session:a,event:y({invocationId:l.invocationId,author:"user",actions:r?$({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(a,this.agent);let f=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(f){let d=y({invocationId:l.invocationId,author:"model",content:f});await this.sessionService.appendEvent({session:a,event:d}),yield d}else for await(let d of l.agent.runAsync(l)){d.partial||await this.sessionService.appendEvent({session:a,event:d});let h=await this.pluginManager.runOnEventCallback({invocationContext:l,event:d});h?yield h:yield d}await this.pluginManager.runAfterRunCallback({invocationContext:l})}finally{s.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 c=r.parts[s];if(!c.inlineData)continue;let a=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:a,artifact:c}),r.parts[s]=(0,Pn.createPartFromText)(`Uploaded file: ${a}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Yo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.debug(`event[${r}]: author=${e.events[r].author}, id=${e.events[r].id}`);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){p.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof E)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Yo(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(c=>c.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let c=o.length-2;c>=0;c--){let a=o[c],l=I(a);if(l){for(let u of l)if(u.id===t)return a}}return null}var ze=class extends te{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new me,sessionService:new ee,memoryService:new H})}};var Re=require("@google/genai");var We=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 E&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Re.Type.OBJECT,properties:{request:{type:Re.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof E&&this.agent.outputSchema;e.response=t?{type:Re.Type.OBJECT}:{type:Re.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var u,f;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof E&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new te({appName:this.agent.name,agent:this.agent,artifactService:new We(t),sessionService:new ee,memoryService:new H,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),c;for await(let d of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))d.actions.stateDelta&&t.state.update(d.actions.stateDelta),c=d;if(!((f=(u=c==null?void 0:c.content)==null?void 0:u.parts)!=null&&f.length))return"";let a=this.agent instanceof E&&this.agent.outputSchema,l=c.content.parts.map(d=>d.text).filter(d=>d).join(`
84
+ `}var jo=new Pt,w=class w extends F{constructor(e){var n,r,i,s,c,a,l,u,f;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=(c=e.disallowTransferToPeers)!=null?c:!1,this.includeContents=(a=e.includeContents)!=null?a:"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.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[_o,Mo,Oo,Fo,No,jo],this.responseProcessors=(u=e.responseProcessors)!=null?u:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((f=this.subAgents)!=null&&f.length)||this.requestProcessors.push(Bo),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)&&(p.warn(`Invalid config for agent ${this.name}: outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true`),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, subAgents must be empty to disable agent transfer.`);if(this.tools&&this.tools.length>0)throw new Error(`Invalid config for agent ${this.name}: if outputSchema is set, tools must be empty`)}}get canonicalModel(){if(Fe(this.model))return this.model;if(typeof this.model=="string"&&this.model)return le.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof w)return e.canonicalModel;e=e.parentAgent}throw new Error(`No model found for ${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 xn(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return w.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return w.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return w.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return w.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){p.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!ne(e)){p.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug(`Skipping output save for agent ${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){p.error(`Error parsing output for agent ${this.name}`,s)}}e.actions.stateDelta[this.outputKey]=n}async*runAsyncImpl(e){var n,r;let t=0;for(;;){let i;for await(let s of this.runOneStepAsync(e))i=s,this.maybeSaveOutputToState(s),yield s;if(!i)break;if(i.errorCode&&!((r=(n=i.content)==null?void 0:n.parts)!=null&&r.length)){if(t++,t<=w.MAX_AGENT_LOOP_ERROR_RETRIES){p.warn(`[runAsyncImpl] Error event (${i.errorCode}), retrying agent loop (${t}/${w.MAX_AGENT_LOOP_ERROR_RETRIES})`);continue}p.error(`[runAsyncImpl] Max agent-loop error retries exhausted for ${i.errorCode}`);break}if(t=0,ne(i))break;if(i.partial){p.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(e){for await(let t of this.runLiveFlow(e))this.maybeSaveOutputToState(t),yield t;e.endInvocation}async*runLiveFlow(e){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(e){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let r of this.requestProcessors)for await(let i of r.runAsync(e,t))yield i;for(let r of this.tools){let i=new Z({invocationContext:e}),s=await xn(r,new N(e));for(let c of s)await c.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=E({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))try{for await(let i of this.postprocess(e,t,r,n))n.id=rt(),n.timestamp=new Date().getTime(),yield i}catch(i){let s=i instanceof Error?i.message:String(i);p.error(`Postprocess error: ${s}`),yield E({invocationId:e.invocationId,author:this.name,branch:e.branch,errorCode:"POSTPROCESS_ERROR",errorMessage:s})}}async*postprocess(e,t,n,r){var u,f;for(let d of this.responseProcessors)for await(let h of d.runAsync(e,n))yield h;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=E({...r,...n});if(i.content){let d=I(i);d!=null&&d.length&&(Zt(i),i.longRunningToolIds=Array.from(Yt(d,t.toolsDict)),(u=i.content.parts)!=null&&u.some(P=>P.thoughtSignature)||p.warn(`[postprocess] Function calls (${d.length}) without thoughtSignature`))}if(yield i,!((f=I(i))!=null&&f.length))return;let s=await Ht({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let c=Xt(e,s);c&&(yield c);let a=Qt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),yield s;let l=s.actions.transferToAgent;if(l){let d=this.getAgentByName(e,l);for await(let h of d.runAsync(e))yield h}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,c,a,l,u;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(a=(c=t.config).labels)!=null||(c.labels={}),t.config.labels[An]||(t.config.labels[An]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let f=((u=e.runConfig)==null?void 0:u.streamingMode)==="sse",d=w.LLM_TRANSIENT_ERROR_MAX_RETRIES;for(let h=0;h<=d;h++){if(h>0){let m=Math.min(w.LLM_TRANSIENT_ERROR_BASE_DELAY_MS*Math.pow(2,h-1),w.LLM_TRANSIENT_ERROR_MAX_DELAY_MS);p.warn(`[callLlmAsync] Retrying LLM call after transient error (attempt ${h+1}/${d+1}), waiting ${m}ms`),await new Promise(C=>setTimeout(C,m))}let P=i.generateContentAsync(t,f),T=!1,g=!1;for await(let m of this.runAndHandleError(P,e,t,n)){if(m.content&&(g=!0),m.errorCode&&w.LLM_RETRYABLE_ERROR_CODES.has(m.errorCode)&&!g&&h<d){T=!0,p.warn(`[callLlmAsync] Transient LLM error: ${m.errorCode}, usage: ${JSON.stringify(m.usageMetadata)}`);break}let C=await this.handleAfterModelCallback(e,m,n);yield C!=null?C:m}if(!T)return}}}async handleBeforeModelCallback(e,t,n){let r=new B({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 c=await s({context:r,request:t});if(c)return c}}async handleAfterModelCallback(e,t,n){let r=new B({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 c=await s({context:r,response:t});if(c)return c}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new B({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let c=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(c)yield c;else try{let a=JSON.parse(i.message);yield{errorCode:String(a.error.code),errorMessage:a.error.message}}catch{p.warn(`LLM error message is not valid JSON, using raw message: ${i.message.substring(0,200)}`),yield{errorCode:"UNKNOWN_ERROR",errorMessage:i.message}}}else throw p.error("Unknown error during response generation",i),i}}};w.MAX_AGENT_LOOP_ERROR_RETRIES=2,w.LLM_TRANSIENT_ERROR_MAX_RETRIES=2,w.LLM_TRANSIENT_ERROR_BASE_DELAY_MS=1e3,w.LLM_TRANSIENT_ERROR_MAX_DELAY_MS=4e3,w.LLM_RETRYABLE_ERROR_CODES=new Set(["UNKNOWN_ERROR","UNEXPECTED_TOOL_CALL","MALFORMED_FUNCTION_CALL"]);var y=w;var qe=class extends F{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(e){let t=0;for(;t<this.maxIterations;){for(let n of this.subAgents){let r=!1;for await(let i of n.runAsync(e))yield i,i.actions.escalate&&(r=!0);if(r)return}t++}}async*runLiveImpl(e){throw new Error("This is not supported yet for LoopAgent.")}};var Ue=class extends F{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(Ko(this,n,e)));for await(let n of Vo(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function Ko(o,e,t){let n=new U(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Vo(o){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}=await 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 Lt="task_completed",je=class extends F{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof y&&((await t.canonicalTools(new N(e))).some(i=>i.name===Lt)||(t.tools.push(new K({name:Lt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),t.instruction+=`If you finished the user's request according to its description, call the ${Lt} 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 t of this.subAgents)for await(let n of t.runLive(e))yield n}};var me=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=Ke(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let c=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(c)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=Ke(e,t,n,r),c=this.artifacts[s];return c?(i===void 0&&(i=c.length-1),Promise.resolve(c[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let c in this.artifacts)if(c.startsWith(r)){let a=c.replace(r,"");s.push(a)}else if(c.startsWith(i)){let a=c.replace(i,"");s.push(a)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=Ke(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=Ke(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let c=[];for(let a=0;a<s.length;a++)c.push(a);return Promise.resolve(c)}};function Ke(o,e,t,n){return Zo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Zo(o){return o.startsWith("user:")}var H=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Rn(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=Rn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let c of Object.values(this.sessionEvents[t]))for(let a of c){if(!((s=(i=a.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=a.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),u=zo(l);if(!u.size)continue;n.some(d=>u.has(d))&&r.memories.push({content:a.content,author:a.author,timestamp:Wo(a.timestamp)})}return r}};function Rn(o,e){return`${o}/${e}`}function zo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Wo(o){return new Date(o).toISOString()}var J=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 Ve=class extends J{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: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${ne(t)}`);let n=I(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=O(t);if(r.length>0){let i=r.map(s=>s.name);this.log(` Function Responses: ${i}`)}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...t.longRunningToolIds]}`)}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Final Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`),t.invocationContext.branch&&this.log(` Branch: ${t.invocationContext.branch}`)}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${t.agentName}`),this.log(` Invocation ID: ${t.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(n=t.model)!=null?n:"default"}`),this.log(` Agent: ${e.agentName}`),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(` System Instruction: '${r}'`)}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(` Available Tools: ${r}`)}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(` Agent: ${e.agentName}`),t.errorCode?(this.log(` \u274C ERROR - Code: ${t.errorCode}`),this.log(` Error Message: ${t.errorMessage}`)):(this.log(` Content: ${this.formatContent(t.content)}`),t.partial&&this.log(` Partial: ${t.partial}`),t.turnComplete!==void 0&&this.log(` Turn Complete: ${t.turnComplete}`)),t.usageMetadata&&this.log(` Token Usage - Input: ${t.usageMetadata.promptTokenCount}, Output: ${t.usageMetadata.candidatesTokenCount}`)}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Result: ${this.formatArgs(r)}`)}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${n}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${n.agentName}`),this.log(` Function Call ID: ${n.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`),this.log(` Error: ${r}`)}log(e){let t=`\x1B[90m[${this.name}] ${e}\x1B[0m`;p.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: '${i}'`)}else r.functionCall?n.push(`function_call: ${r.functionCall.name}`):r.functionResponse?n.push(`function_response: ${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 ge=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error(`Plugin '${e.name}' already registered.`);if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error(`Plugin with name '${e.name}' already registered.`);this.plugins.add(e),p.info(`Plugin '${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 p.debug(`Plugin '${r.name}' returned a value for callback '${n}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${n}' callback: ${i}`;throw p.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 _t="adk_request_confirmation",kt="orcas_tool_call_security_check_states",Sn="This tool call needs external confirmation before completion.",Mt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Mt||{}),be=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Ze=class extends J{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new be}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:Sn};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(kt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(kt))!=null?i:{};r[n]=t,e.state.set(kt,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: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:Sn};case"ALLOW":return;default:return}}};function In(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===_t&&e.push(t.functionCall);return e}var Te=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(v.TEMP_PREFIX)||(e.state[n]=r)}};function Re(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var ee=class extends Te{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Re({id:i||fe(),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,$(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],c=$(s);if(i&&(i.numRecentEvents&&(c.events=c.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let a=c.events.length-1;for(;a>=0&&!(c.events[a].timestamp<i.afterTimestamp);)a--;a>=0&&(c.events=c.events.slice(a+1))}return Promise.resolve(this.mergeState(t,n,c))}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(Re({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,c=l=>{p.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return c(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return c(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return c(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(v.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(v.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(v.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(v.USER_PREFIX,"")]=n.actions.stateDelta[l]);let a=this.sessions[r][i][s];return await super.appendEvent({session:a,event:n}),a.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[v.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[v.USER_PREFIX+i]=this.userState[t][n][i];return r}};var Pn=require("@google/genai"),wn=require("@opentelemetry/api");var te=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ge((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runAsync({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var c;i=yn(i);let s=wn.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let a=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!a)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof y){let d=this.agent.canonicalModel.model;if(!d.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${d} in agent: ${this.agent.name}`)}let l=new U({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Ut(),agent:this.agent,session:a,userContent:n,runConfig:i,pluginManager:this.pluginManager}),u=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(u&&(n=u),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,a.userId,a.id,n),await this.sessionService.appendEvent({session:a,event:E({invocationId:l.invocationId,author:"user",actions:r?D({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(a,this.agent);let f=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(f){let d=E({invocationId:l.invocationId,author:"model",content:f});await this.sessionService.appendEvent({session:a,event:d}),yield d}else for await(let d of l.agent.runAsync(l)){d.partial||await this.sessionService.appendEvent({session:a,event:d});let h=await this.pluginManager.runOnEventCallback({invocationContext:l,event:d});h?yield h:yield d}await this.pluginManager.runAfterRunCallback({invocationContext:l})}finally{s.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 c=r.parts[s];if(!c.inlineData)continue;let a=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:a,artifact:c}),r.parts[s]=(0,Pn.createPartFromText)(`Uploaded file: ${a}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Yo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.debug(`event[${r}]: author=${e.events[r].author}, id=${e.events[r].id}`);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){p.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof y)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Yo(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(c=>c.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let c=o.length-2;c>=0;c--){let a=o[c],l=I(a);if(l){for(let u of l)if(u.id===t)return a}}return null}var ze=class extends te{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new me,sessionService:new ee,memoryService:new H})}};var Se=require("@google/genai");var We=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 y&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Se.Type.OBJECT,properties:{request:{type:Se.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof y&&this.agent.outputSchema;e.response=t?{type:Se.Type.OBJECT}:{type:Se.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var u,f;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof y&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new te({appName:this.agent.name,agent:this.agent,artifactService:new We(t),sessionService:new ee,memoryService:new H,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),c;for await(let d of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))d.actions.stateDelta&&t.state.update(d.actions.stateDelta),c=d;if(!((f=(u=c==null?void 0:c.content)==null?void 0:u.parts)!=null&&f.length))return"";let a=this.agent instanceof y&&this.agent.outputSchema,l=c.content.parts.map(d=>d.text).filter(d=>d).join(`
85
85
  `);return a?JSON.parse(l):l}};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 Ot=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.toolsDict[this.name]=this,t.config=t.config||{},t.config.tools=t.config.tools||[],en(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(Jt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},Ln=new Ot;var kn=`
86
86
 
87
- NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,Xe=class extends K{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=kn:e.description=kn.trimStart(),e}};var _n=require("@modelcontextprotocol/sdk/client/index.js"),Mn=require("@modelcontextprotocol/sdk/client/stdio.js"),On=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Ie=class{constructor(e){this.connectionParams=e}async createSession(){let e=new _n.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new Mn.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new On.StreamableHTTPClientTransport(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};var V=require("@google/genai"),Ce=require("zod");var Jc=Ce.z.object({type:Ce.z.literal("object"),properties:Ce.z.record(Ce.z.unknown()).optional(),required:Ce.z.string().array().optional()});function Xo(o){switch(o.toLowerCase()){case"text":case"string":return V.Type.STRING;case"number":return V.Type.NUMBER;case"boolean":return V.Type.BOOLEAN;case"integer":return V.Type.INTEGER;case"array":return V.Type.ARRAY;case"object":return V.Type.OBJECT;default:return V.Type.TYPE_UNSPECIFIED}}function Nt(o){if(!o)return;function e(t){let n=Xo(t.type),r={type:n,description:t.description};if(n===V.Type.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else n===V.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var Pe=class extends _{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){let e;return e={name:this.mcpTool.name,description:this.mcpTool.description,parameters:Nt(this.mcpTool.inputSchema),response:Nt(this.mcpTool.outputSchema)},e}async runAsync(e){let t=await this.mcpSessionManager.createSession(),n={};return n.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(n.params)}};var Bt=class extends he{constructor(e,t=[]){super(t),this.mcpSessionManager=new Ie(e)}async getTools(e){let n=await(await this.mcpSessionManager.createSession()).listTools();p.debug(`number of tools: ${n.tools.length}`);for(let r of n.tools)p.debug(`tool: ${r.name}`);return n.tools.map(r=>new Pe(r,this.mcpSessionManager))}async close(){}};var Nn=require("@google-cloud/storage"),He=require("@google/genai");var Ft=class{constructor(e){this.bucket=new Nn.Storage().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),n=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(Qe({...e,version:n}));if(e.artifact.inlineData)return await r.save(JSON.stringify(e.artifact.inlineData.data),{contentType:e.artifact.inlineData.mimeType}),n;if(e.artifact.text)return await r.save(e.artifact.text,{contentType:"text/plain"}),n;throw new Error("Artifact must have either inlineData or text.")}async loadArtifact(e){let t=e.version;if(t===void 0){let s=await this.listVersions(e);if(s.length===0)return;t=Math.max(...s)}let n=this.bucket.file(Qe({...e,version:t})),[[r],[i]]=await Promise.all([n.getMetadata(),n.download()]);return r.contentType==="text/plain"?(0,He.createPartFromText)(i.toString("utf-8")):(0,He.createPartFromBase64)(i.toString("base64"),r.contentType)}async listArtifactKeys(e){let t=[],n=`${e.appName}/${e.userId}/${e.sessionId}/`,r=`${e.appName}/${e.userId}/user/`,[[i],[s]]=await Promise.all([this.bucket.getFiles({prefix:n}),this.bucket.getFiles({prefix:r})]);for(let c of i)t.push(c.name.split("/").pop());for(let c of s)t.push(c.name.split("/").pop());return t.sort((c,a)=>c.localeCompare(a))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(n=>this.bucket.file(Qe({...e,version:n})).delete()))}async listVersions(e){let t=Qe(e),[n]=await this.bucket.getFiles({prefix:t}),r=[];for(let i of n){let s=i.name.split("/").pop();r.push(parseInt(s,10))}return r}};function Qe({appName:o,userId:e,sessionId:t,filename:n,version:r}){return n.startsWith("user:")?`${o}/${e}/user/${n}/${r}`:`${o}/${e}/${t}/${n}/${r}`}var Je=require("@opentelemetry/api"),Bn=require("@opentelemetry/api-logs"),et=require("@opentelemetry/sdk-logs"),tt=require("@opentelemetry/sdk-metrics"),Fn=require("@opentelemetry/resources"),Dn=require("@opentelemetry/sdk-trace-base"),Gn=require("@opentelemetry/sdk-trace-node"),$n=require("@opentelemetry/exporter-trace-otlp-http"),qn=require("@opentelemetry/exporter-metrics-otlp-http"),Un=require("@opentelemetry/exporter-logs-otlp-http");function Qo(o=[],e){let t=e||Ho(),n=[...o,er()],r=n.flatMap(c=>c.spanProcessors||[]),i=n.flatMap(c=>c.metricReaders||[]),s=n.flatMap(c=>c.logRecordProcessors||[]);if(r.length>0){let c=new Gn.NodeTracerProvider({resource:t,spanProcessors:r});c.register(),Je.trace.setGlobalTracerProvider(c)}if(i.length>0){let c=new tt.MeterProvider({readers:i,resource:t});Je.metrics.setGlobalMeterProvider(c)}if(s.length>0){let c=new et.LoggerProvider({resource:t,processors:s});Bn.logs.setGlobalLoggerProvider(c)}}function Ho(){return(0,Fn.detectResources)({detectors:[]})}function Jo(){return{enableTracing:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),enableMetrics:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT),enableLogging:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)}}function er(o=Jo()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new Dn.BatchSpanProcessor(new $n.OTLPTraceExporter)]:[],metricReaders:t?[new tt.PeriodicExportingMetricReader({exporter:new qn.OTLPMetricExporter})]:[],logRecordProcessors:n?[new et.BatchLogRecordProcessor(new Un.OTLPLogExporter)]:[]}}var jn=require("google-auth-library"),Kn=require("@opentelemetry/sdk-metrics"),Vn=require("@opentelemetry/resources"),Zn=require("@opentelemetry/resource-detector-gcp"),zn=require("@google-cloud/opentelemetry-cloud-trace-exporter"),Wn=require("@opentelemetry/sdk-trace-base"),Yn=require("@google-cloud/opentelemetry-cloud-monitoring-exporter");var tr="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function nr(){try{return await new jn.GoogleAuth().getProjectId()||void 0}catch{return}}async function or(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await nr();return n?{spanProcessors:e?[new Wn.BatchSpanProcessor(new zn.TraceExporter({projectId:n}))]:[],metricReaders:t?[new Kn.PeriodicExportingMetricReader({exporter:new Yn.MetricExporter({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(p.warn(tr),{})}function rr(){return(0,Vn.detectResources)({detectors:[Zn.gcpDetector]})}0&&(module.exports={AgentTool,BaseAgent,BaseLlm,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,CallbackContext,FunctionTool,GOOGLE_SEARCH,GcsArtifactService,Gemini,InMemoryArtifactService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LLMRegistry,LiveRequestQueue,LlmAgent,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,ParallelAgent,PluginManager,PolicyOutcome,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,Runner,SecurityPlugin,SequentialAgent,State,StreamingMode,ToolConfirmation,ToolContext,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,hasTrailingCodeExecutionResult,isBaseLlm,isFinalResponse,maybeSetOtelProviders,setLogLevel,stringifyContent,version,zodObjectToSchema});
87
+ NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,Xe=class extends K{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=kn:e.description=kn.trimStart(),e}};var _n=require("@modelcontextprotocol/sdk/client/index.js"),Mn=require("@modelcontextprotocol/sdk/client/stdio.js"),On=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Ie=class{constructor(e){this.connectionParams=e}async createSession(){let e=new _n.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new Mn.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new On.StreamableHTTPClientTransport(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};var V=require("@google/genai"),Ce=require("zod");var Jc=Ce.z.object({type:Ce.z.literal("object"),properties:Ce.z.record(Ce.z.unknown()).optional(),required:Ce.z.string().array().optional()});function Xo(o){switch(o.toLowerCase()){case"text":case"string":return V.Type.STRING;case"number":return V.Type.NUMBER;case"boolean":return V.Type.BOOLEAN;case"integer":return V.Type.INTEGER;case"array":return V.Type.ARRAY;case"object":return V.Type.OBJECT;default:return V.Type.TYPE_UNSPECIFIED}}function Nt(o){if(!o)return;function e(t){let n=Xo(t.type),r={type:n,description:t.description};if(n===V.Type.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else n===V.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var Pe=class extends _{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){let e;return e={name:this.mcpTool.name,description:this.mcpTool.description,parameters:Nt(this.mcpTool.inputSchema),response:Nt(this.mcpTool.outputSchema)},e}async runAsync(e){let t=await this.mcpSessionManager.createSession(),n={};return n.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(n.params)}};var Bt=class extends he{constructor(e,t=[]){super(t),this.mcpSessionManager=new Ie(e)}async getTools(e){let n=await(await this.mcpSessionManager.createSession()).listTools();p.debug(`number of tools: ${n.tools.length}`);for(let r of n.tools)p.debug(`tool: ${r.name}`);return n.tools.map(r=>new Pe(r,this.mcpSessionManager))}async close(){}};var Nn=require("@google-cloud/storage"),He=require("@google/genai");var Ft=class{constructor(e){this.bucket=new Nn.Storage().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),n=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(Qe({...e,version:n}));if(e.artifact.inlineData)return await r.save(JSON.stringify(e.artifact.inlineData.data),{contentType:e.artifact.inlineData.mimeType}),n;if(e.artifact.text)return await r.save(e.artifact.text,{contentType:"text/plain"}),n;throw new Error("Artifact must have either inlineData or text.")}async loadArtifact(e){let t=e.version;if(t===void 0){let s=await this.listVersions(e);if(s.length===0)return;t=Math.max(...s)}let n=this.bucket.file(Qe({...e,version:t})),[[r],[i]]=await Promise.all([n.getMetadata(),n.download()]);return r.contentType==="text/plain"?(0,He.createPartFromText)(i.toString("utf-8")):(0,He.createPartFromBase64)(i.toString("base64"),r.contentType)}async listArtifactKeys(e){let t=[],n=`${e.appName}/${e.userId}/${e.sessionId}/`,r=`${e.appName}/${e.userId}/user/`,[[i],[s]]=await Promise.all([this.bucket.getFiles({prefix:n}),this.bucket.getFiles({prefix:r})]);for(let c of i)t.push(c.name.split("/").pop());for(let c of s)t.push(c.name.split("/").pop());return t.sort((c,a)=>c.localeCompare(a))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(n=>this.bucket.file(Qe({...e,version:n})).delete()))}async listVersions(e){let t=Qe(e),[n]=await this.bucket.getFiles({prefix:t}),r=[];for(let i of n){let s=i.name.split("/").pop();r.push(parseInt(s,10))}return r}};function Qe({appName:o,userId:e,sessionId:t,filename:n,version:r}){return n.startsWith("user:")?`${o}/${e}/user/${n}/${r}`:`${o}/${e}/${t}/${n}/${r}`}var Je=require("@opentelemetry/api"),Bn=require("@opentelemetry/api-logs"),et=require("@opentelemetry/sdk-logs"),tt=require("@opentelemetry/sdk-metrics"),Fn=require("@opentelemetry/resources"),$n=require("@opentelemetry/sdk-trace-base"),Gn=require("@opentelemetry/sdk-trace-node"),Dn=require("@opentelemetry/exporter-trace-otlp-http"),qn=require("@opentelemetry/exporter-metrics-otlp-http"),Un=require("@opentelemetry/exporter-logs-otlp-http");function Qo(o=[],e){let t=e||Ho(),n=[...o,er()],r=n.flatMap(c=>c.spanProcessors||[]),i=n.flatMap(c=>c.metricReaders||[]),s=n.flatMap(c=>c.logRecordProcessors||[]);if(r.length>0){let c=new Gn.NodeTracerProvider({resource:t,spanProcessors:r});c.register(),Je.trace.setGlobalTracerProvider(c)}if(i.length>0){let c=new tt.MeterProvider({readers:i,resource:t});Je.metrics.setGlobalMeterProvider(c)}if(s.length>0){let c=new et.LoggerProvider({resource:t,processors:s});Bn.logs.setGlobalLoggerProvider(c)}}function Ho(){return(0,Fn.detectResources)({detectors:[]})}function Jo(){return{enableTracing:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT),enableMetrics:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT),enableLogging:!!(process.env.OTEL_EXPORTER_OTLP_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)}}function er(o=Jo()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new $n.BatchSpanProcessor(new Dn.OTLPTraceExporter)]:[],metricReaders:t?[new tt.PeriodicExportingMetricReader({exporter:new qn.OTLPMetricExporter})]:[],logRecordProcessors:n?[new et.BatchLogRecordProcessor(new Un.OTLPLogExporter)]:[]}}var jn=require("google-auth-library"),Kn=require("@opentelemetry/sdk-metrics"),Vn=require("@opentelemetry/resources"),Zn=require("@opentelemetry/resource-detector-gcp"),zn=require("@google-cloud/opentelemetry-cloud-trace-exporter"),Wn=require("@opentelemetry/sdk-trace-base"),Yn=require("@google-cloud/opentelemetry-cloud-monitoring-exporter");var tr="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function nr(){try{return await new jn.GoogleAuth().getProjectId()||void 0}catch{return}}async function or(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await nr();return n?{spanProcessors:e?[new Wn.BatchSpanProcessor(new zn.TraceExporter({projectId:n}))]:[],metricReaders:t?[new Kn.PeriodicExportingMetricReader({exporter:new Yn.MetricExporter({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(p.warn(tr),{})}function rr(){return(0,Vn.detectResources)({detectors:[Zn.gcpDetector]})}0&&(module.exports={AgentTool,BaseAgent,BaseLlm,BasePlugin,BaseSessionService,BaseTool,BaseToolset,BuiltInCodeExecutor,CallbackContext,FunctionTool,GOOGLE_SEARCH,GcsArtifactService,Gemini,InMemoryArtifactService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LLMRegistry,LiveRequestQueue,LlmAgent,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,ParallelAgent,PluginManager,PolicyOutcome,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,Runner,SecurityPlugin,SequentialAgent,State,StreamingMode,ToolConfirmation,ToolContext,createEvent,createEventActions,createSession,functionsExportedForTestingOnly,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,getGcpExporters,getGcpResource,hasTrailingCodeExecutionResult,isBaseLlm,isFinalResponse,maybeSetOtelProviders,setLogLevel,stringifyContent,version,zodObjectToSchema});
88
88
  /**
89
89
  * @license
90
90
  * Copyright 2025 Google LLC