@paean-ai/adk 0.2.9 → 0.2.11

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.
@@ -30,6 +30,7 @@ __export(content_processor_utils_exports, {
30
30
  module.exports = __toCommonJS(content_processor_utils_exports);
31
31
  var import_event = require("../events/event.js");
32
32
  var import_deep_clone = require("../utils/deep_clone.js");
33
+ var import_logger = require("../utils/logger.js");
33
34
  var import_functions = require("./functions.js");
34
35
  /**
35
36
  * @license
@@ -37,7 +38,7 @@ var import_functions = require("./functions.js");
37
38
  * SPDX-License-Identifier: Apache-2.0
38
39
  */
39
40
  function getContents(events, agentName, currentBranch) {
40
- var _a, _b;
41
+ var _a, _b, _c, _d, _e, _f;
41
42
  const filteredEvents = [];
42
43
  for (const event of events) {
43
44
  if (!((_a = event.content) == null ? void 0 : _a.role) || !((_b = event.content.parts) == null ? void 0 : _b.length)) {
@@ -64,6 +65,30 @@ function getContents(events, agentName, currentBranch) {
64
65
  (0, import_functions.removeClientFunctionCallId)(content);
65
66
  contents.push(content);
66
67
  }
68
+ import_logger.logger.debug(`[getContents] Preparing ${contents.length} content blocks for LLM request`);
69
+ for (let i = 0; i < contents.length; i++) {
70
+ const content = contents[i];
71
+ const hasFunctionCalls = (_c = content.parts) == null ? void 0 : _c.some((p) => p.functionCall);
72
+ const hasThoughtSignature = (_d = content.parts) == null ? void 0 : _d.some((p) => p.thoughtSignature);
73
+ const hasThought = (_e = content.parts) == null ? void 0 : _e.some((p) => p.thought);
74
+ if (hasFunctionCalls) {
75
+ import_logger.logger.debug(
76
+ `[getContents] Content block ${i + 1}: role=${content.role}, hasFunctionCalls=true, hasThought=${hasThought}, hasSignature=${hasThoughtSignature}`
77
+ );
78
+ for (let j = 0; j < (((_f = content.parts) == null ? void 0 : _f.length) || 0); j++) {
79
+ const part = content.parts[j];
80
+ if (part.functionCall) {
81
+ import_logger.logger.debug(
82
+ `[getContents] Part ${j}: functionCall=${part.functionCall.name}, hasSignature=${!!part.thoughtSignature}`
83
+ );
84
+ } else if (part.thought) {
85
+ import_logger.logger.debug(
86
+ `[getContents] Part ${j}: thought=true, hasSignature=${!!part.thoughtSignature}`
87
+ );
88
+ }
89
+ }
90
+ }
91
+ }
67
92
  return contents;
68
93
  }
69
94
  function getCurrentTurnContents(events, agentName, currentBranch) {
@@ -993,7 +993,7 @@ class LlmAgent extends import_base_agent.BaseAgent {
993
993
  }
994
994
  }
995
995
  async *postprocess(invocationContext, llmRequest, llmResponse, modelResponseEvent) {
996
- var _a;
996
+ var _a, _b, _c, _d, _e;
997
997
  for (const processor of this.responseProcessors) {
998
998
  for await (const event of processor.runAsync(invocationContext, llmResponse)) {
999
999
  yield event;
@@ -1013,10 +1013,25 @@ class LlmAgent extends import_base_agent.BaseAgent {
1013
1013
  mergedEvent.longRunningToolIds = Array.from(
1014
1014
  (0, import_functions.getLongRunningFunctionCalls)(functionCalls, llmRequest.toolsDict)
1015
1015
  );
1016
+ const hasThought = (_a = mergedEvent.content.parts) == null ? void 0 : _a.some((p) => p.thought);
1017
+ const hasSignature = (_b = mergedEvent.content.parts) == null ? void 0 : _b.some(
1018
+ (p) => p.thoughtSignature
1019
+ );
1020
+ import_logger.logger.debug(
1021
+ `[postprocess] Function call event: ${functionCalls.length} calls, hasThought=${hasThought}, hasSignature=${hasSignature}`
1022
+ );
1023
+ for (let i = 0; i < (((_c = mergedEvent.content.parts) == null ? void 0 : _c.length) || 0); i++) {
1024
+ const part = mergedEvent.content.parts[i];
1025
+ if (part.functionCall || part.thought) {
1026
+ import_logger.logger.debug(
1027
+ `[postprocess] Part ${i}: thought=${!!part.thought}, functionCall=${((_d = part.functionCall) == null ? void 0 : _d.name) || "none"}, hasSignature=${!!part.thoughtSignature}`
1028
+ );
1029
+ }
1030
+ }
1016
1031
  }
1017
1032
  }
1018
1033
  yield mergedEvent;
1019
- if (!((_a = (0, import_event.getFunctionCalls)(mergedEvent)) == null ? void 0 : _a.length)) {
1034
+ if (!((_e = (0, import_event.getFunctionCalls)(mergedEvent)) == null ? void 0 : _e.length)) {
1020
1035
  return;
1021
1036
  }
1022
1037
  const functionResponseEvent = await (0, import_functions.handleFunctionCallsAsync)({
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 He=Object.defineProperty;var Zn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Wn=Object.prototype.hasOwnProperty;var Yn=(o,e)=>{for(var t in e)He(o,t,{get:e[t],enumerable:!0})},Qn=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zn(e))!Wn.call(o,r)&&r!==t&&He(o,r,{get:()=>e[r],enumerable:!(n=Zn(e,r))||n.enumerable});return o};var Xn=o=>Qn(He({},"__esModule",{value:!0}),o);var tr={};Yn(tr,{AgentTool:()=>Ve,BaseAgent:()=>O,BaseLlm:()=>re,BasePlugin:()=>Y,BaseSessionService:()=>xe,BaseTool:()=>I,BaseToolset:()=>de,BuiltInCodeExecutor:()=>ee,CallbackContext:()=>_,FunctionTool:()=>$,GOOGLE_SEARCH:()=>Rn,GcsArtifactService:()=>_t,Gemini:()=>ie,InMemoryArtifactService:()=>ue,InMemoryMemoryService:()=>W,InMemoryPolicyEngine:()=>ye,InMemoryRunner:()=>je,InMemorySessionService:()=>Q,InvocationContext:()=>D,LLMRegistry:()=>se,LiveRequestQueue:()=>ke,LlmAgent:()=>y,LogLevel:()=>rt,LoggingPlugin:()=>qe,LongRunningFunctionTool:()=>Ze,LoopAgent:()=>Fe,MCPSessionManager:()=>be,MCPTool:()=>Te,MCPToolset:()=>Lt,ParallelAgent:()=>De,PluginManager:()=>fe,PolicyOutcome:()=>Pt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>It,Runner:()=>X,SecurityPlugin:()=>Ue,SequentialAgent:()=>Ge,State:()=>C,StreamingMode:()=>Ne,ToolConfirmation:()=>Z,ToolContext:()=>j,createEvent:()=>x,createEventActions:()=>F,createSession:()=>Ee,functionsExportedForTestingOnly:()=>Ut,getAskUserConfirmationFunctionCalls:()=>bn,getFunctionCalls:()=>b,getFunctionResponses:()=>k,getGcpExporters:()=>Jo,getGcpResource:()=>er,hasTrailingCodeExecutionResult:()=>Je,isBaseLlm:()=>Me,isFinalResponse:()=>J,maybeSetOtelProviders:()=>zo,setLogLevel:()=>$t,stringifyContent:()=>Bt,version:()=>_e,zodObjectToSchema:()=>ve});module.exports=Xn(tr);var nt=require("@opentelemetry/api");function F(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function Ot(o,e){let t=F();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 x(o={}){return{...o,id:o.id||et(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||F(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function J(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:b(o).length===0&&k(o).length===0&&!o.partial&&!Je(o)}function b(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 k(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 Je(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 Bt(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 Nt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function et(){let o="";for(let e=0;e<8;e++)o+=Nt[Math.floor(Math.random()*Nt.length)];return o}var C=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}}};C.APP_PREFIX="app:",C.USER_PREFIX="user:",C.TEMP_PREFIX="temp:";var L=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 C(this.invocationContext.session.state,{})}};var _=class extends L{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||F(),this._state=new C(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 Re(){return typeof window<"u"}var Se="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ae(){let o="";for(let e=0;e<Se.length;e++){let t=Math.random()*16|0;Se[e]==="x"?o+=t.toString(16):Se[e]==="y"?o+=(t&3|8).toString(16):o+=Se[e]}return o}function Ft(o){return Re()?window.atob(o):Buffer.from(o,"base64").toString()}var tt=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`)}},D=class{constructor(e){this.invocationCostManager=new tt;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 Dt(){return`e-${ae()}`}var O=class{constructor(e){this.name=Hn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=eo(this),this.beforeAgentCallback=Gt(e.beforeAgentCallback),this.afterAgentCallback=Gt(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=nt.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=nt.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 D({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new _({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,x({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return x({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new _({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return x({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return x({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function Hn(o){if(!Jn(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 Jn(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function eo(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Gt(o){return o?Array.isArray(o)?o:[o]:[]}var qt=require("@google/genai");var me=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 Z=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var j=class extends _{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 me(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new me(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 Z({hint:e,confirmed:!1,payload:t})}};var rt=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(rt||{}),ce=1;function $t(o){ce=o}var ot=class{log(e,...t){if(!(e<ce))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){ce>0||console.debug(Ie(0),...e)}info(...e){ce>1||console.info(Ie(1),...e)}warn(...e){ce>2||console.warn(Ie(2),...e)}error(...e){ce>3||console.error(Ie(3),...e)}},to={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},no={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},oo="\x1B[0m";function Ie(o){return`${no[o]}[ADK ${to[o]}]:${oo}`}var p=new ot;var it="adk-",Pe="adk_request_credential",le="adk_request_confirmation",Ut={handleFunctionCallList:we};function st(){return`${it}${ae()}`}function jt(o){let e=b(o);if(e)for(let t of e)t.id||(t.id=st())}function Kt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(it)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(it)&&(e.functionResponse.id=void 0)}function Vt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function Zt(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:Pe,args:{function_call_id:i,auth_config:s},id:st()};n.add(c.id),t.push({functionCall:c})}return x({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function zt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=b(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(c=i.find(d=>d.id===a))!=null?c:void 0;if(!f)continue;let u={name:le,args:{originalFunctionCall:f,toolConfirmation:l},id:st()};r.add(u.id),n.push({functionCall:u})}return x({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function ro(o,e,t){return p.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function Wt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let c=b(e);return await we({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function we({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let c=[],a=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of a){let d;s&&u.id&&(d=s[u.id]);let{tool:v,toolContext:A}=io({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});p.debug(`execute_tool ${v.name}`);let g=(f=u.args)!=null?f:{},m=null,h;if(m=await o.pluginManager.runBeforeToolCallback({tool:v,toolArgs:g,toolContext:A}),m==null){for(let R of n)if(m=await R({tool:v,args:g,context:A}),m)break}if(m==null)try{m=await ro(v,g,A)}catch(R){if(R instanceof Error){let T=await o.pluginManager.runOnToolErrorCallback({tool:v,toolArgs:g,toolContext:A,error:R});T?m=T:h=R.message}else h=R}let P=await o.pluginManager.runAfterToolCallback({tool:v,toolArgs:g,toolContext:A,result:m});if(P==null){for(let R of r)if(P=await R({tool:v,args:g,context:A,response:m}),P)break}if(P!=null&&(m=P),v.isLongRunning&&!m)continue;h?m={error:h}:(typeof m!="object"||m==null)&&(m={result:m});let H=x({invocationId:o.invocationId,author:o.agent.name,content:(0,qt.createUserContent)({functionResponse:{id:A.functionCallId,name:v.name,response:m}}),actions:A.actions,branch:o.branch});p.debug("traceToolCall",{tool:v.name,args:g,functionResponseEvent:H.id}),c.push(H)}if(!c.length)return null;let l=so(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function io({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new j({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function so(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=Ot(n);return x({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ke=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var ht=require("zod");var z=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 ao="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Le(o){let e=o.match(ao);return e?e[1]:o}function Yt(o){return Le(o).startsWith("gemini-")}function Qt(o){return Le(o).startsWith("gemini-1")}function Xt(o){return Le(o).startsWith("gemini-2")}function Ht(o){let e=Le(o);return e.startsWith("gemini-3")&&e.includes("preview")}var ee=class extends z{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Xt(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 ge=require("@google/genai");function N(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Jt(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let d=o.parts[u];if(d.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),d.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=N(t[0]),r=t.map(u=>u.text).join(`
8
- `),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[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(at(l)),l):""}function at(o){return{text:o,executableCode:{code:o,language:ge.Language.PYTHON}}}function en(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:ge.Outcome.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push(`Code execution result:
7
+ "use strict";var nt=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var Xn=Object.prototype.hasOwnProperty;var Hn=(o,e)=>{for(var t in e)nt(o,t,{get:e[t],enumerable:!0})},Jn=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qn(e))!Xn.call(o,r)&&r!==t&&nt(o,r,{get:()=>e[r],enumerable:!(n=Yn(e,r))||n.enumerable});return o};var eo=o=>Jn(nt({},"__esModule",{value:!0}),o);var rr={};Hn(rr,{AgentTool:()=>Ye,BaseAgent:()=>F,BaseLlm:()=>se,BasePlugin:()=>H,BaseSessionService:()=>be,BaseTool:()=>L,BaseToolset:()=>ge,BuiltInCodeExecutor:()=>ne,CallbackContext:()=>N,FunctionTool:()=>j,GOOGLE_SEARCH:()=>wn,GcsArtifactService:()=>Bt,Gemini:()=>ae,InMemoryArtifactService:()=>pe,InMemoryMemoryService:()=>X,InMemoryPolicyEngine:()=>Ae,InMemoryRunner:()=>ze,InMemorySessionService:()=>J,InvocationContext:()=>q,LLMRegistry:()=>ce,LiveRequestQueue:()=>Oe,LlmAgent:()=>x,LogLevel:()=>ct,LoggingPlugin:()=>Ve,LongRunningFunctionTool:()=>Qe,LoopAgent:()=>qe,MCPSessionManager:()=>Re,MCPTool:()=>Ie,MCPToolset:()=>Nt,ParallelAgent:()=>Ue,PluginManager:()=>me,PolicyOutcome:()=>_t,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>Lt,Runner:()=>ee,SecurityPlugin:()=>Ze,SequentialAgent:()=>je,State:()=>y,StreamingMode:()=>Ge,ToolConfirmation:()=>Y,ToolContext:()=>V,createEvent:()=>b,createEventActions:()=>D,createSession:()=>Te,functionsExportedForTestingOnly:()=>Vt,getAskUserConfirmationFunctionCalls:()=>Rn,getFunctionCalls:()=>P,getFunctionResponses:()=>M,getGcpExporters:()=>nr,getGcpResource:()=>or,hasTrailingCodeExecutionResult:()=>ot,isBaseLlm:()=>Fe,isFinalResponse:()=>te,maybeSetOtelProviders:()=>Qo,setLogLevel:()=>jt,stringifyContent:()=>Gt,version:()=>Be,zodObjectToSchema:()=>Ee});module.exports=eo(rr);var st=require("@opentelemetry/api");function D(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function Ft(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 b(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 te(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:P(o).length===0&&M(o).length===0&&!o.partial&&!ot(o)}function P(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 M(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 Gt(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 $t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function rt(){let o="";for(let e=0;e<8;e++)o+=$t[Math.floor(Math.random()*$t.length)];return o}var y=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}}};y.APP_PREFIX="app:",y.USER_PREFIX="user:",y.TEMP_PREFIX="temp:";var O=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 y(this.invocationContext.session.state,{})}};var N=class extends O{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||D(),this._state=new y(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 ke(){return typeof window<"u"}var we="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ue(){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 Dt(o){return ke()?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`)}},q=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 qt(){return`e-${ue()}`}var F=class{constructor(e){this.name=to(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=oo(this),this.beforeAgentCallback=Ut(e.beforeAgentCallback),this.afterAgentCallback=Ut(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 q({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({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 to(o){if(!no(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 no(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function oo(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Ut(o){return o?Array.isArray(o)?o:[o]:[]}var Kt=require("@google/genai");var Ce=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 Y=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var V=class extends N{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Ce(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Ce(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 Y({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||{}),fe=1;function jt(o){fe=o}var at=class{log(e,...t){if(!(e<fe))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){fe>0||console.debug(Le(0),...e)}info(...e){fe>1||console.info(Le(1),...e)}warn(...e){fe>2||console.warn(Le(2),...e)}error(...e){fe>3||console.error(Le(3),...e)}},ro={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},io={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},so="\x1B[0m";function Le(o){return`${io[o]}[ADK ${ro[o]}]:${so}`}var p=new at;var lt="adk-",_e="adk_request_credential",de="adk_request_confirmation",Vt={handleFunctionCallList:Me};function ut(){return`${lt}${ue()}`}function Zt(o){let e=P(o);if(e)for(let t of e)t.id||(t.id=ut())}function zt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(lt)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(lt)&&(e.functionResponse.id=void 0)}function Wt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function Yt(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:_e,args:{function_call_id:i,auth_config:s},id:ut()};n.add(a.id),t.push({functionCall:a})}return b({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,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=P(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let d=(a=i.find(f=>f.id===c))!=null?a:void 0;if(!d)continue;let u={name:de,args:{originalFunctionCall:d,toolConfirmation:l},id:ut()};r.add(u.id),n.push({functionCall:u})}return b({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function ao(o,e,t){return p.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function Xt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=P(e);return await Me({invocationContext:o,functionCalls:a,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 d;let a=[],c=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of c){let f;s&&u.id&&(f=s[u.id]);let{tool:h,toolContext:E}=co({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:f});p.debug(`execute_tool ${h.name}`);let v=(d=u.args)!=null?d:{},C=null,g;if(C=await o.pluginManager.runBeforeToolCallback({tool:h,toolArgs:v,toolContext:E}),C==null){for(let T of n)if(C=await T({tool:h,args:v,context:E}),C)break}if(C==null)try{C=await ao(h,v,E)}catch(T){if(T instanceof Error){let w=await o.pluginManager.runOnToolErrorCallback({tool:h,toolArgs:v,toolContext:E,error:T});w?C=w:g=T.message}else g=T}let m=await o.pluginManager.runAfterToolCallback({tool:h,toolArgs:v,toolContext:E,result:C});if(m==null){for(let T of r)if(m=await T({tool:h,args:v,context:E,response:C}),m)break}if(m!=null&&(C=m),h.isLongRunning&&!C)continue;g?C={error:g}:(typeof C!="object"||C==null)&&(C={result:C});let A=b({invocationId:o.invocationId,author:o.agent.name,content:(0,Kt.createUserContent)({functionResponse:{id:E.functionCallId,name:h.name,response:C}}),actions:E.actions,branch:o.branch});p.debug("traceToolCall",{tool:h.name,args:v,functionResponseEvent:A.id}),a.push(A)}if(!a.length)return null;let l=lo(a);return a.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function co({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new V({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function lo(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=Ft(n);return b({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 uo="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ne(o){let e=o.match(uo);return e?e[1]:o}function Ht(o){return Ne(o).startsWith("gemini-")}function Jt(o){return Ne(o).startsWith("gemini-1")}function en(o){return Ne(o).startsWith("gemini-2")}function tn(o){let e=Ne(o);return e.startsWith("gemini-3")&&e.includes("preview")}var ne=class extends Q{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&en(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 ve=require("@google/genai");function $(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function nn(o,e){var d;if(!((d=o.parts)!=null&&d.length))return"";for(let u=0;u<o.parts.length;u++){let f=o.parts[u];if(f.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),f.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=$(t[0]),r=t.map(u=>u.text).join(`
8
+ `),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[1]).join("|"),a=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(o.parts=[],c&&(n.text=c,o.parts.push(n)),o.parts.push(ft(l)),l):""}function ft(o){return{text:o,executableCode:{code:o,language:ve.Language.PYTHON}}}function on(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:ve.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:ge.Outcome.OUTCOME_OK}}}function tn(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 ct="_code_execution_context",lt="execution_session_id",te="processed_input_files",ne="_code_executor_input_files",oe="_code_executor_error_counts",ut="_code_execution_results",he=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(ct))!=null?t:{},this.sessionState=e}getStateDelta(){return{[ct]:N(this.context)}}getExecutionId(){if(lt in this.context)return this.context[lt]}setExecutionId(e){this.context[lt]=e}getProcessedFileNames(){return te in this.context?this.context[te]:[]}addProcessedFileNames(e){te in this.context||(this.context[te]=[]),this.context[te].push(...e)}getInputFiles(){return ne in this.sessionState?this.sessionState.get(ne):[]}addInputFiles(e){ne in this.sessionState||this.sessionState.set(ne,[]),this.sessionState.get(ne).push(...e)}clearInputFiles(){ne in this.sessionState&&this.sessionState.set(ne,[]),te in this.context&&(this.context[te]=[])}getErrorCount(e){return oe in this.sessionState&&this.sessionState.get(oe)[e]||0}incrementErrorCount(e){oe in this.sessionState||this.sessionState.set(oe,{}),this.sessionState.get(oe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(oe in this.sessionState))return;let t=this.sessionState.get(oe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){ut in this.sessionState||this.sessionState.set(ut,{});let i=this.sessionState.get(ut);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(ct)||{}}};var _e="0.2.4";var co="google-adk",lo="gl-typescript",uo="remote_reasoning_engine",fo="GOOGLE_CLOUD_AGENT_ENGINE_ID";function po(){let o=`${co}/${_e}`;!Re()&&process.env[fo]&&(o=`${o}+${uo}`);let e=`${lo}/${Re()?window.navigator.userAgent:process.version}`;return[o,e]}function nn(){return po()}var ft=Symbol("baseModel");function Me(o){return typeof o=="object"&&o!==null&&ft in o&&o[ft]===!0}var on;on=ft;var re=class{constructor({model:e}){this[on]=!0;this.model=e}get trackingHeaders(){let t=nn().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."}]})}};re.supportedModels=[];function Ce(o,e){o.config||(o.config={});let t=e.join(`
13
+ `),codeExecutionResult:{outcome:ve.Outcome.OUTCOME_OK}}}function rn(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 dt="_code_execution_context",pt="execution_session_id",oe="processed_input_files",re="_code_executor_input_files",ie="_code_executor_error_counts",mt="_code_execution_results",ye=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(dt))!=null?t:{},this.sessionState=e}getStateDelta(){return{[dt]:$(this.context)}}getExecutionId(){if(pt in this.context)return this.context[pt]}setExecutionId(e){this.context[pt]=e}getProcessedFileNames(){return oe in this.context?this.context[oe]:[]}addProcessedFileNames(e){oe in this.context||(this.context[oe]=[]),this.context[oe].push(...e)}getInputFiles(){return re in this.sessionState?this.sessionState.get(re):[]}addInputFiles(e){re in this.sessionState||this.sessionState.set(re,[]),this.sessionState.get(re).push(...e)}clearInputFiles(){re in this.sessionState&&this.sessionState.set(re,[]),oe in this.context&&(this.context[oe]=[])}getErrorCount(e){return ie in this.sessionState&&this.sessionState.get(ie)[e]||0}incrementErrorCount(e){ie in this.sessionState||this.sessionState.set(ie,{}),this.sessionState.get(ie)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(ie in this.sessionState))return;let t=this.sessionState.get(ie);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){mt in this.sessionState||this.sessionState.set(mt,{});let i=this.sessionState.get(mt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(dt)||{}}};var Be="0.2.4";var fo="google-adk",po="gl-typescript",mo="remote_reasoning_engine",go="GOOGLE_CLOUD_AGENT_ENGINE_ID";function ho(){let o=`${fo}/${Be}`;!ke()&&process.env[go]&&(o=`${o}+${mo}`);let e=`${po}/${ke()?window.navigator.userAgent:process.version}`;return[o,e]}function sn(){return ho()}var gt=Symbol("baseModel");function Fe(o){return typeof o=="object"&&o!==null&&gt in o&&o[gt]===!0}var an;an=gt;var se=class{constructor({model:e}){this[an]=!0;this.model=e}get trackingHeaders(){let t=sn().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};se.supportedModels=[];function xe(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 rn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var G=require("@google/genai");function sn(){return mo("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function mo(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Oe=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 dt(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 ho="https://aiplatform.googleapis.com/v1/publishers/google",ie=class extends re{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=Ht(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=ho,p.info(`Using Gemini 3 preview endpoint: ${this.apiEndpoint}`));let l=!!n;if(!l&&a){let f=process.env.GOOGLE_GENAI_USE_VERTEXAI;f&&(l=f.toLowerCase()==="true"||f==="1")}if(this.isGemini3Preview&&l){let f=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);f?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):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,f,u,d,v;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 A=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),g="",m,h="",P,H;for await(let R of A){H=R;let T=dt(R);P=T.usageMetadata;let M=(s=(i=T.content)==null?void 0:i.parts)==null?void 0:s[0],Mt=(a=(c=T.content)==null?void 0:c.parts)==null?void 0:a.some(w=>w.functionCall);if(M!=null&&M.text)"thought"in M&&M.thought?(g+=M.text,"thoughtSignature"in M&&M.thoughtSignature&&(m=M.thoughtSignature)):h+=M.text,T.partial=!0;else if((g||h)&&(!M||!M.inlineData))if(this.isGemini3Preview&&Mt&&T.content){let w=[];if(g){let U={text:g,thought:!0};m&&(U.thoughtSignature=m),w.push(U)}h&&w.push((0,G.createPartFromText)(h));for(let U of T.content.parts||[])U.functionCall&&!U.thoughtSignature&&(U.thoughtSignature=m);T.content.parts=[...w,...T.content.parts||[]],g="",m=void 0,h=""}else{let w=[];if(g){let U={text:g,thought:!0};m&&(U.thoughtSignature=m),w.push(U)}h&&w.push((0,G.createPartFromText)(h)),yield{content:{role:"model",parts:w},usageMetadata:T.usageMetadata},g="",m=void 0,h=""}if(this.isGemini3Preview&&m&&((l=T.content)!=null&&l.parts))for(let w of T.content.parts)w.functionCall&&!w.thoughtSignature&&(w.thoughtSignature=m);yield T,Mt&&(m=void 0)}if((h||g)&&((u=(f=H==null?void 0:H.candidates)==null?void 0:f[0])==null?void 0:u.finishReason)===G.FinishReason.STOP){let R=[];if(g){let T={text:g,thought:!0};m&&(T.thoughtSignature=m),R.push(T)}h&&R.push({text:h}),yield{content:{role:"model",parts:R},usageMetadata:P}}}else{let A=await this.apiClient.models.generateContent({model:(d=e.model)!=null?d:this.model,contents:e.contents,config:e.config}),g=dt(A);if(this.isGemini3Preview&&((v=g.content)!=null&&v.parts)){let m;for(let h of g.content.parts)if(h.thought&&h.thoughtSignature){m=h.thoughtSignature;break}if(m)for(let h of g.content.parts)h.functionCall&&!h.thoughtSignature&&(h.thoughtSignature=m)}yield g}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new G.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 G.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 G.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,G.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 Oe(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)an(n.inlineData),an(n.fileData)}}};ie.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function an(o){o&&o.displayName&&(o.displayName=void 0)}var pt=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)}},B=class B{static newLlm(e){return new(B.resolve(e))({model:e})}static _register(e,t){B.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${B.llmRegistryDict.get(e)} to ${t}`),B.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)B._register(t,e)}static resolve(e){let t=B.resolveCache.get(e);if(t)return t;for(let[n,r]of B.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return B.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};B.llmRegistryDict=new Map,B.resolveCache=new pt(32);var se=B;se.register(ie);var I=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=Co(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 sn()}};function Co(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var ln=require("@google/genai"),un=require("zod");var S=require("@google/genai"),E=require("zod");function cn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function K(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 E.z.ZodFirstPartyTypeKind.ZodString:n.type=S.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 E.z.ZodFirstPartyTypeKind.ZodNumber:n.type=S.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=S.Type.INTEGER);return r(n);case E.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=S.Type.BOOLEAN,r(n);case E.z.ZodFirstPartyTypeKind.ZodArray:return n.type=S.Type.ARRAY,n.items=K(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case E.z.ZodFirstPartyTypeKind.ZodObject:return ve(o);case E.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=S.Type.STRING;else if(i==="number")n.type=S.Type.NUMBER;else if(i==="boolean")n.type=S.Type.BOOLEAN;else if(e.value===null)n.type=S.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case E.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=S.Type.STRING,n.enum=e.values,r(n);case E.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=S.Type.STRING,n.enum=Object.values(e.values),r(n);case E.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(K),r(n);case E.z.ZodFirstPartyTypeKind.ZodOptional:return K(e.innerType);case E.z.ZodFirstPartyTypeKind.ZodNullable:let s=K(e.innerType);return r(s?{anyOf:[s,{type:S.Type.NULL}],...t&&{description:t}}:{type:S.Type.NULL,...t&&{description:t}});case E.z.ZodFirstPartyTypeKind.ZodDefault:let c=K(e.innerType);return c&&(c.default=e.defaultValue()),c;case E.z.ZodFirstPartyTypeKind.ZodBranded:return K(e.type);case E.z.ZodFirstPartyTypeKind.ZodReadonly:return K(e.innerType);case E.z.ZodFirstPartyTypeKind.ZodNull:return n.type=S.Type.NULL,r(n);case E.z.ZodFirstPartyTypeKind.ZodAny:case E.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function ve(o){if(o._def.typeName!==E.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=K(c);a&&(t[s]=a);let l=c,f=!1;for(;l._def.typeName===E.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===E.z.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==E.z.ZodFirstPartyTypeKind.ZodNever?i=K(r)||!0:i=o._def.unknownKeys==="passthrough",{type:S.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function vo(o){return o===void 0?{type:ln.Type.OBJECT,properties:{}}:cn(o)?ve(o):o}var $=class extends I{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:vo(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof un.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 V=class{};function mt(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)||yo(a)||xo(a)||n.push(pn(e,a)?Eo(a):a);let r=Ao(n);r=bo(r);let i=[];for(let a of r){let l=N(a.content);Kt(l),i.push(l)}return i}function dn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||pn(e,r))return mt(o.slice(n),e,t)}return[]}function yo(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 xo(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)===le||((n=r.functionResponse)==null?void 0:n.name)===le)return!0;return!1}function pn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function Eo(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=fn(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=fn(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 x({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function mn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=x(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 Ao(o){if(o.length===0)return o;let e=o[o.length-1],t=k(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=b(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],f=b(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=a;let d=new Set(f.map(A=>A.id).filter(A=>!!A));if(!Array.from(n).every(A=>d.has(A)))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],f=k(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(mn(s)),c}function bo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=k(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(k(n).length>0)continue;let r=b(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(mn(c))}}else t.push(n)}return t}function fn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function gt(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=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:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!Ro(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(f)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 To=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function gn(o){return o===""||o===void 0?!1:To.test(o)}var So=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function Ro(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?gn(o):So.includes(e[0]+":")?gn(e[1]):!1}var Ne=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ne||{});function hn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Io(o.maxLlmCalls||500),...o}}function Io(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 Cn="adk_agent_name";async function vn(o,e){return o instanceof I?[o]:await o.getTools(e)}var Ct=class extends V{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&&rn(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))}},Po=new Ct,vt=class extends V{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}"`),Ce(t,r)}},wo=new vt,yt=class extends V{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 L(e)),c=i;s&&(c=await gt(i,new L(e))),Ce(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new L(e)),c=i;s&&(c=await gt(i,new L(e))),Ce(t,[c])}}},ko=new yt,xt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof y)||(n.includeContents==="default"?t.contents=mt(e.session.events,n.name,e.branch):t.contents=dn(e.session.events,n.name,e.branch))}},Lo=new xt,Et=class extends V{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new $({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:ht.z.object({agentName:ht.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;Ce(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new j({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
17
+ `+t:o.config.systemInstruction=t}function cn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var U=require("@google/genai");function ln(){return Co("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Co(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 ht(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",ae=class extends se{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=tn(e);let c=typeof process=="object";this.apiEndpoint=a,!this.apiEndpoint&&c&&(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&&c){let d=process.env.GOOGLE_GENAI_USE_VERTEXAI;d&&(l=d.toLowerCase()==="true"||d==="1")}if(this.isGemini3Preview&&l){let d=t||(c?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);d?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=d):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(c&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),c&&!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&&c&&(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,a,c,l,d,u,f,h,E,v;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 C=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),g="",m,A="",T,w;for await(let le of C){w=le;let R=ht(le);T=R.usageMetadata;let B=(s=(i=R.content)==null?void 0:i.parts)==null?void 0:s[0],Pe=(c=(a=R.content)==null?void 0:a.parts)==null?void 0:c.some(_=>_.functionCall);if(this.isGemini3Preview&&((l=R.content)!=null&&l.parts)){for(let _ of R.content.parts)if(_.thoughtSignature&&!m){m=_.thoughtSignature,p.debug("[Gemini3] Captured thoughtSignature from response part");break}}if(B!=null&&B.text)"thought"in B&&B.thought?(g+=B.text,"thoughtSignature"in B&&B.thoughtSignature&&(m=B.thoughtSignature,p.debug("[Gemini3] Captured thoughtSignature from thought part"))):A+=B.text,R.partial=!0,this.isGemini3Preview&&Pe&&(p.debug("[Gemini3] Chunk has both thought and function calls - clearing accumulated text"),g="",m=void 0,A="");else if((g||A)&&(!B||!B.inlineData))if(this.isGemini3Preview&&Pe&&R.content){p.debug(`[Gemini3] Merging thought with function calls. Has signature: ${!!m}`);let _=[];if(g){let I={text:g,thought:!0};m&&(I.thoughtSignature=m),_.push(I),p.debug(`[Gemini3] Created thought part with signature: ${!!m}`)}if(A&&_.push((0,U.createPartFromText)(A)),!g&&m){let I=!1;for(let W of R.content.parts||[])W.functionCall&&!I&&(W.thoughtSignature||(W.thoughtSignature=m,p.debug(`[Gemini3] Applied signature to first function call: ${W.functionCall.name}`)),I=!0)}R.content.parts=[..._,...R.content.parts||[]],p.debug(`[Gemini3] Final merged content has ${R.content.parts.length} parts`);for(let I=0;I<R.content.parts.length;I++){let W=R.content.parts[I];p.debug(`[Gemini3] Part ${I}: thought=${!!W.thought}, functionCall=${!!W.functionCall}, hasSignature=${!!W.thoughtSignature}`)}g="",m=void 0,A=""}else{let _=[];if(g){let I={text:g,thought:!0};m&&(I.thoughtSignature=m),_.push(I)}A&&_.push((0,U.createPartFromText)(A)),yield{content:{role:"model",parts:_},usageMetadata:R.usageMetadata},g="",m=void 0,A=""}if(this.isGemini3Preview&&Pe&&((d=R.content)!=null&&d.parts)&&!R.content.parts.some(I=>I.thoughtSignature)&&m){for(let I of R.content.parts)if(I.functionCall){I.thoughtSignature=m,p.debug(`[Gemini3] Applied cached signature to first function call: ${I.functionCall.name}`);break}}yield R,Pe&&(m=void 0)}if((A||g)&&((f=(u=w==null?void 0:w.candidates)==null?void 0:u[0])==null?void 0:f.finishReason)===U.FinishReason.STOP){let le=[];if(g){let R={text:g,thought:!0};m&&(R.thoughtSignature=m),le.push(R)}A&&le.push({text:A}),yield{content:{role:"model",parts:le},usageMetadata:T}}}else{let C=await this.apiClient.models.generateContent({model:(h=e.model)!=null?h:this.model,contents:e.contents,config:e.config}),g=ht(C);if(this.isGemini3Preview&&((E=g.content)!=null&&E.parts)){let m,A=!1;for(let T of g.content.parts)if(T.thoughtSignature){m=T.thoughtSignature,T.thought&&(A=!0);break}if(p.debug(`[Gemini3] Non-streaming response: hasSignature=${!!m}, hasThoughtPart=${A}`),m&&!A){let T=!1;for(let w of g.content.parts)w.functionCall&&(!T&&!w.thoughtSignature&&(w.thoughtSignature=m,p.debug(`[Gemini3] Applied signature to first function call: ${w.functionCall.name}`)),T=!0)}for(let T=0;T<g.content.parts.length;T++){let w=g.content.parts[T];p.debug(`[Gemini3] Response Part ${T}: thought=${!!w.thought}, functionCall=${((v=w.functionCall)==null?void 0:v.name)||"none"}, hasSignature=${!!w.thoughtSignature}`)}}yield g}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new U.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 U.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 U.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,U.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)un(n.inlineData),un(n.fileData)}}};ae.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function un(o){o&&o.displayName&&(o.displayName=void 0)}var Ct=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let 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 Ct(32);var ce=G;ce.register(ae);var L=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 ln()}};function xo(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var dn=require("@google/genai"),pn=require("zod");var k=require("@google/genai"),S=require("zod");function fn(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 S.z.ZodFirstPartyTypeKind.ZodString:n.type=k.Type.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case S.z.ZodFirstPartyTypeKind.ZodNumber:n.type=k.Type.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=k.Type.INTEGER);return r(n);case S.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=k.Type.BOOLEAN,r(n);case S.z.ZodFirstPartyTypeKind.ZodArray:return n.type=k.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 S.z.ZodFirstPartyTypeKind.ZodObject:return Ee(o);case S.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=k.Type.STRING;else if(i==="number")n.type=k.Type.NUMBER;else if(i==="boolean")n.type=k.Type.BOOLEAN;else if(e.value===null)n.type=k.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case S.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=k.Type.STRING,n.enum=e.values,r(n);case S.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=k.Type.STRING,n.enum=Object.values(e.values),r(n);case S.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(Z),r(n);case S.z.ZodFirstPartyTypeKind.ZodOptional:return Z(e.innerType);case S.z.ZodFirstPartyTypeKind.ZodNullable:let s=Z(e.innerType);return r(s?{anyOf:[s,{type:k.Type.NULL}],...t&&{description:t}}:{type:k.Type.NULL,...t&&{description:t}});case S.z.ZodFirstPartyTypeKind.ZodDefault:let a=Z(e.innerType);return a&&(a.default=e.defaultValue()),a;case S.z.ZodFirstPartyTypeKind.ZodBranded:return Z(e.type);case S.z.ZodFirstPartyTypeKind.ZodReadonly:return Z(e.innerType);case S.z.ZodFirstPartyTypeKind.ZodNull:return n.type=k.Type.NULL,r(n);case S.z.ZodFirstPartyTypeKind.ZodAny:case S.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Ee(o){if(o._def.typeName!==S.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=Z(a);c&&(t[s]=c);let l=a,d=!1;for(;l._def.typeName===S.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===S.z.ZodFirstPartyTypeKind.ZodDefault;)d=!0,l=l._def.innerType;d||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==S.z.ZodFirstPartyTypeKind.ZodNever?i=Z(r)||!0:i=o._def.unknownKeys==="passthrough",{type:k.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Eo(o){return o===void 0?{type:dn.Type.OBJECT,properties:{}}:fn(o)?Ee(o):o}var j=class extends L{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:Eo(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof pn.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 z=class{};function vt(o,e,t){var s,a,c,l,d,u;let n=[];for(let f of o)!((s=f.content)!=null&&s.role)||!((a=f.content.parts)!=null&&a.length)||t&&f.branch&&!t.startsWith(f.branch)||Ao(f)||bo(f)||n.push(hn(e,f)?To(f):f);let r=So(n);r=Ro(r);let i=[];for(let f of r){let h=$(f.content);zt(h),i.push(h)}p.debug(`[getContents] Preparing ${i.length} content blocks for LLM request`);for(let f=0;f<i.length;f++){let h=i[f],E=(c=h.parts)==null?void 0:c.some(g=>g.functionCall),v=(l=h.parts)==null?void 0:l.some(g=>g.thoughtSignature),C=(d=h.parts)==null?void 0:d.some(g=>g.thought);if(E){p.debug(`[getContents] Content block ${f+1}: role=${h.role}, hasFunctionCalls=true, hasThought=${C}, hasSignature=${v}`);for(let g=0;g<(((u=h.parts)==null?void 0:u.length)||0);g++){let m=h.parts[g];m.functionCall?p.debug(`[getContents] Part ${g}: functionCall=${m.functionCall.name}, hasSignature=${!!m.thoughtSignature}`):m.thought&&p.debug(`[getContents] Part ${g}: thought=true, hasSignature=${!!m.thoughtSignature}`)}}}return i}function gn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||hn(e,r))return vt(o.slice(n),e,t)}return[]}function Ao(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 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)===de||((n=r.functionResponse)==null?void 0:n.name)===de)return!0;return!1}function hn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function To(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=mn(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=mn(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return b({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function Cn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=b(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function So(o){if(o.length===0)return o;let e=o[o.length-1],t=M(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=P(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],d=P(l);if(d!=null&&d.length){for(let u of d)if(u.id&&n.has(u.id)){i=c;let f=new Set(d.map(E=>E.id).filter(E=>!!E));if(!Array.from(n).every(E=>f.has(E)))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(f).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=f;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],d=M(l);d&&d.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(Cn(s)),a}function Ro(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=M(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(M(n).length>0)continue;let r=P(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(Cn(a))}}else t.push(n)}return t}function mn(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(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),d=l.endsWith("?");if(d&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let f=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!f)throw new Error(`Artifact ${u} not found.`);return String(f)}if(!wo(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(d)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var Io=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function vn(o){return o===""||o===void 0?!1:Io.test(o)}var Po=[y.APP_PREFIX,y.USER_PREFIX,y.TEMP_PREFIX];function wo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?vn(o):Po.includes(e[0]+":")?vn(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 xn="adk_agent_name";async function En(o,e){return o instanceof L?[o]:await o.getTools(e)}var Et=class extends z{async*runAsync(e,t){var r;let n=e.agent;n instanceof x&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&cn(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))}},Lo=new Et,At=class extends z{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)}},_o=new At,bt=class extends z{async*runAsync(e,t){let n=e.agent;if(!(n instanceof x)||!(n.rootAgent instanceof x))return;let r=n.rootAgent;if(r instanceof x&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new O(e)),a=i;s&&(a=await yt(i,new O(e))),xe(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new O(e)),a=i;s&&(a=await yt(i,new O(e))),xe(t,[a])}}},Mo=new bt,Tt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof x)||(n.includeContents==="default"?t.contents=vt(e.session.events,n.name,e.branch):t.contents=gn(e.session.events,n.name,e.branch))}},Oo=new Tt,St=class extends z{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new j({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 x))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;xe(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new V({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 y)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},_o=new Et,At=class extends V{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=k(a);if(!l)continue;let f=!1;for(let u of l){if(u.name!==le)continue;f=!0;let d=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?d=JSON.parse(u.response.response):u.response&&(d=new Z({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&d&&(i[u.id]=d)}if(f){s=c;break}}if(Object.keys(i).length!==0)for(let c=s-1;c>=0;c--){let a=r[c],l=b(a);if(!l)continue;let f={},u={};for(let g of l){if(!g.id||!(g.id in i))continue;let m=g.args;if(!m||!("originalFunctionCall"in m))continue;let h=m.originalFunctionCall;h.id&&(f[h.id]=i[g.id],u[h.id]=h)}if(Object.keys(f).length===0)continue;for(let g=r.length-1;g>s;g--){let m=r[g],h=k(m);if(h){for(let P of h)P.id&&P.id in f&&(delete f[P.id],delete u[P.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let d=await n.canonicalTools(new L(e)),v=Object.fromEntries(d.map(g=>[g.name,g])),A=await we({invocationContext:e,functionCalls:Object.values(u),toolsDict:v,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f});A&&(yield A);return}}},Mo=new At,bt=class extends V{async*runAsync(e,t){if(e.agent instanceof y&&e.agent.codeExecutor){for await(let n of No(e,t))yield n;if(e.agent.codeExecutor instanceof z)for(let n of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],i=tn(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},Be={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Oo=`
37
+ `),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof x)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},No=new St,Rt=class extends z{async*runAsync(e,t){let n=e.agent;if(!(n instanceof x))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let a=r.length-1;a>=0;a--){let c=r[a];if(c.author!=="user")continue;let l=M(c);if(!l)continue;let d=!1;for(let u of l){if(u.name!==de)continue;d=!0;let f=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?f=JSON.parse(u.response.response):u.response&&(f=new Y({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(i[u.id]=f)}if(d){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=P(c);if(!l)continue;let d={},u={};for(let v of l){if(!v.id||!(v.id in i))continue;let C=v.args;if(!C||!("originalFunctionCall"in C))continue;let g=C.originalFunctionCall;g.id&&(d[g.id]=i[v.id],u[g.id]=g)}if(Object.keys(d).length===0)continue;for(let v=r.length-1;v>s;v--){let C=r[v],g=M(C);if(g){for(let m of g)m.id&&m.id in d&&(delete d[m.id],delete u[m.id]);if(Object.keys(d).length===0)break}}if(Object.keys(d).length===0)continue;let f=await n.canonicalTools(new O(e)),h=Object.fromEntries(f.map(v=>[v.name,v])),E=await Me({invocationContext:e,functionCalls:Object.values(u),toolsDict:h,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(d)),toolConfirmationDict:d});E&&(yield E);return}}},Bo=new Rt,It=class extends z{async*runAsync(e,t){if(e.agent instanceof x&&e.agent.codeExecutor){for await(let n of $o(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=rn(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},De={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Fo=`
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
- `,Tt=class{async*runAsync(e,t){if(!t.partial)for await(let n of Bo(e,t))yield n}},ks=new Tt;async function*No(o,e){let t=o.agent;if(!(t instanceof y))return;let n=t.codeExecutor;if(!n||!(n instanceof z))return;if(n instanceof ee){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new he(new C(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=Fo(r,e),s=new Set(r.getProcessedFileNames()),c=i.filter(a=>!s.has(a.name));for(let a of c){let l=Do(a);if(!l)return;let f={role:"model",parts:[{text:`Processing input file: \`${a.name}\``},at(l)]};e.contents.push(N(f)),yield x({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let u=yn(o,r),d=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[a],executionId:u}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([a.name]);let v=await xn(o,r,d);yield v,e.contents.push(N(v.content))}}async function*Bo(o,e){let t=o.agent;if(!(t instanceof y))return;let n=t.codeExecutor;if(!n||!(n instanceof z)||!e||!e.content||n instanceof ee)return;let r=new he(new C(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=Jt(i,n.codeBlockDelimiters);if(!s)return;yield x({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let c=yn(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 xn(o,r,a),e.content=null}function Fo(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||!Be[l])continue;let f=`data_${i+1}_${c+1}${Be[l].extension}`;a.text=`
75
- Available file: \`${f}\`
76
- `;let u={name:f,content:Ft(a.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([u]),t.push(u))}}return t}function yn(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 xn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[en(t)]},r=F({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 x({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Do(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!Be[o.mimeType])return;let t=e(o.name),n=Be[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return`
77
- ${Oo}
74
+ `,Pt=class{async*runAsync(e,t){if(!t.partial)for await(let n of Go(e,t))yield n}},Os=new Pt;async function*$o(o,e){let t=o.agent;if(!(t instanceof x))return;let n=t.codeExecutor;if(!n||!(n instanceof Q))return;if(n instanceof ne){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new ye(new y(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=Do(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=qo(c);if(!l)return;let d={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},ft(l)]};e.contents.push($(d)),yield b({invocationId:o.invocationId,author:t.name,branch:o.branch,content:d});let u=An(o,r),f=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:u}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:f.stdout,resultStderr:f.stderr}),r.addProcessedFileNames([c.name]);let h=await bn(o,r,f);yield h,e.contents.push($(h.content))}}async function*Go(o,e){let t=o.agent;if(!(t instanceof x))return;let n=t.codeExecutor;if(!n||!(n instanceof Q)||!e||!e.content||n instanceof ne)return;let r=new ye(new y(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=nn(i,n.codeBlockDelimiters);if(!s)return;yield b({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=An(o,r),c=await n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await bn(o,r,c),e.content=null}function Do(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 a=0;a<s.parts.length;a++){let c=s.parts[a],l=(r=c.inlineData)==null?void 0:r.mimeType;if(!l||!c.inlineData||!De[l])continue;let d=`data_${i+1}_${a+1}${De[l].extension}`;c.text=`
75
+ Available file: \`${d}\`
76
+ `;let u={name:d,content:Dt(c.inlineData.data),mimeType:l};n.has(d)||(o.addInputFiles([u]),t.push(u))}}return t}function An(o,e){var r;let t=o.agent;if(!(t instanceof x)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function bn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[on(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 b({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function qo(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
+ ${Fo}
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 Go=new bt,y=class o extends O{constructor(e){var n,r,i,s,c,a,l,f,u;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:[Po,wo,ko,Mo,Lo,Go],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(_o),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(Me(this.model))return this.model;if(typeof this.model=="string"&&this.model)return se.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error(`No model found for ${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 vn(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){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(!J(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||J(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 j({invocationContext:e}),s=await vn(r,new L(e));for(let c of s)await c.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=x({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=et(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var f;for(let u of this.responseProcessors)for await(let d of u.runAsync(e,n))yield d;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=x({...r,...n});if(i.content){let u=b(i);u!=null&&u.length&&(jt(i),i.longRunningToolIds=Array.from(Vt(u,t.toolsDict)))}if(yield i,!((f=b(i))!=null&&f.length))return;let s=await Wt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let c=Zt(e,s);c&&(yield c);let a=zt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),yield s;let l=s.actions.transferToAgent;if(l){let u=this.getAgentByName(e,l);for await(let d of u.runAsync(e))yield d}}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,f;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[Cn]||(t.config.labels[Cn]=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 u=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let d of this.runAndHandleError(u,e,t,n)){let v=await this.handleAfterModelCallback(e,d,n);yield v!=null?v:d}}}async handleBeforeModelCallback(e,t,n){let r=new _({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 _({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 _({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{let a=JSON.parse(i.message);yield{errorCode:String(a.error.code),errorMessage:a.error.message}}}else throw p.error("Unknown error during response generation",i),i}}};var Fe=class extends O{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 De=class extends O{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync($o(this,n,e)));for await(let n of qo(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function $o(o,e,t){let n=new D(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*qo(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 St="task_completed",Ge=class extends O{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 L(e))).some(i=>i.name===St)||(t.tools.push(new $({name:St,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 ${St} 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 ue=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=$e(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=$e(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=$e(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=$e(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 $e(o,e,t,n){return Uo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Uo(o){return o.startsWith("user:")}var W=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=En(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=En(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(" "),f=jo(l);if(!f.size)continue;n.some(d=>f.has(d))&&r.memories.push({content:a.content,author:a.author,timestamp:Ko(a.timestamp)})}return r}};function En(o,e){return`${o}/${e}`}function jo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Ko(o){return new Date(o).toISOString()}var Y=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 qe=class extends Y{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: ${J(t)}`);let n=b(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=k(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 fe=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 It="adk_request_confirmation",Rt="orcas_tool_call_security_check_states",An="This tool call needs external confirmation before completion.",Pt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Pt||{}),ye=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Ue=class extends Y{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new ye}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:An};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(Rt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Rt))!=null?i:{};r[n]=t,e.state.set(Rt,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:An};case"ALLOW":return;default:return}}};function bn(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===It&&e.push(t.functionCall);return e}var xe=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(C.TEMP_PREFIX)||(e.state[n]=r)}};function Ee(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var Q=class extends xe{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Ee({id:i||ae(),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,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=N(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(Ee({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(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(C.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(C.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[C.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[C.USER_PREFIX+i]=this.userState[t][n][i];return r}};var Tn=require("@google/genai"),Sn=require("@opentelemetry/api");var X=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new fe((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=hn(i);let s=Sn.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 D({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Dt(),agent:this.agent,session:a,userContent:n,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(f&&(n=f),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:x({invocationId:l.invocationId,author:"user",actions:r?F({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(a,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(u){let d=x({invocationId:l.invocationId,author:"model",content:u});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 v=await this.pluginManager.runOnEventCallback({invocationContext:l,event:d});v?yield v: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,Tn.createPartFromText)(`Uploaded file: ${a}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Vo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){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 Vo(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=b(a);if(l){for(let f of l)if(f.id===t)return a}}return null}var je=class extends X{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new ue,sessionService:new Q,memoryService:new W})}};var Ae=require("@google/genai");var Ke=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(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 Ve=class extends I{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:Ae.Type.OBJECT,properties:{request:{type:Ae.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof y&&this.agent.outputSchema;e.response=t?{type:Ae.Type.OBJECT}:{type:Ae.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var f,u;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 X({appName:this.agent.name,agent:this.agent,artifactService:new Ke(t),sessionService:new Q,memoryService:new W,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(!((u=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&u.length))return"";let a=this.agent instanceof y&&this.agent.outputSchema,l=c.content.parts.map(d=>d.text).filter(d=>d).join(`
85
- `);return a?JSON.parse(l):l}};var de=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 wt=class extends I{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.config=t.config||{},t.config.tools=t.config.tools||[],Qt(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(Yt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},Rn=new wt;var In=`
84
+ `}var Uo=new It,x=class o extends F{constructor(e){var n,r,i,s,a,c,l,d,u;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(c=e.includeContents)!=null?c:"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:[Lo,_o,Mo,Bo,Oo,Uo],this.responseProcessors=(d=e.responseProcessors)!=null?d:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(No),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 ce.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error(`No model found for ${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 En(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){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(!te(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||te(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 V({invocationContext:e}),s=await En(r,new O(e));for(let a of s)await a.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=b({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=rt(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var d,u,f,h,E;for(let v of this.responseProcessors)for await(let C of v.runAsync(e,n))yield C;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=b({...r,...n});if(i.content){let v=P(i);if(v!=null&&v.length){Zt(i),i.longRunningToolIds=Array.from(Wt(v,t.toolsDict));let C=(d=i.content.parts)==null?void 0:d.some(m=>m.thought),g=(u=i.content.parts)==null?void 0:u.some(m=>m.thoughtSignature);p.debug(`[postprocess] Function call event: ${v.length} calls, hasThought=${C}, hasSignature=${g}`);for(let m=0;m<(((f=i.content.parts)==null?void 0:f.length)||0);m++){let A=i.content.parts[m];(A.functionCall||A.thought)&&p.debug(`[postprocess] Part ${m}: thought=${!!A.thought}, functionCall=${((h=A.functionCall)==null?void 0:h.name)||"none"}, hasSignature=${!!A.thoughtSignature}`)}}}if(yield i,!((E=P(i))!=null&&E.length))return;let s=await Xt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let a=Yt(e,s);a&&(yield a);let c=Qt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let v=this.getAgentByName(e,l);for await(let C of v.runAsync(e))yield C}}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,a,c,l,d;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(c=(a=t.config).labels)!=null||(a.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 u=i.generateContentAsync(t,((d=e.runConfig)==null?void 0:d.streamingMode)==="sse");for await(let f of this.runAndHandleError(u,e,t,n)){let h=await this.handleAfterModelCallback(e,f,n);yield h!=null?h:f}}}async handleBeforeModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let a=await s({context:r,request:t});if(a)return a}}async handleAfterModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let a=await s({context:r,response:t});if(a)return a}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new N({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let a=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(a)yield a;else{let c=JSON.parse(i.message);yield{errorCode:String(c.error.code),errorMessage:c.error.message}}}else throw p.error("Unknown error during response generation",i),i}}};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(jo(this,n,e)));for await(let n of Ko(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function jo(o,e,t){let n=new q(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*Ko(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 wt="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 x&&((await t.canonicalTools(new O(e))).some(i=>i.name===wt)||(t.tools.push(new j({name:wt,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 ${wt} 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 pe=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 a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=Ke(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId: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 a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}};function Ke(o,e,t,n){return Vo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Vo(o){return o.startsWith("user:")}var X=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Tn(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=Tn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(f=>f.text).filter(f=>!!f).join(" "),d=Zo(l);if(!d.size)continue;n.some(f=>d.has(f))&&r.memories.push({content:c.content,author:c.author,timestamp:zo(c.timestamp)})}return r}};function Tn(o,e){return`${o}/${e}`}function Zo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function zo(o){return new Date(o).toISOString()}var H=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 H{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: ${te(t)}`);let n=P(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=M(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 me=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 Lt="adk_request_confirmation",kt="orcas_tool_call_security_check_states",Sn="This tool call needs external confirmation before completion.",_t=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(_t||{}),Ae=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Ze=class extends H{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ae}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 Rn(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Lt&&e.push(t.functionCall);return e}var be=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(y.TEMP_PREFIX)||(e.state[n]=r)}};function Te(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var J=class extends be{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Te({id:i||ue(),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],a=$(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(Te({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{p.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`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(y.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(y.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(y.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(y.USER_PREFIX,"")]=n.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:n}),c.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[y.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[y.USER_PREFIX+i]=this.userState[t][n][i];return r}};var In=require("@google/genai"),Pn=require("@opentelemetry/api");var ee=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new me((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 a;i=yn(i);let s=Pn.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let c=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!c)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof x){let f=this.agent.canonicalModel.model;if(!f.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${f} in agent: ${this.agent.name}`)}let l=new q({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:qt(),agent:this.agent,session:c,userContent:n,runConfig:i,pluginManager:this.pluginManager}),d=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(d&&(n=d),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,c.userId,c.id,n),await this.sessionService.appendEvent({session:c,event:b({invocationId:l.invocationId,author:"user",actions:r?D({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(c,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(u){let f=b({invocationId:l.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:c,event:f}),yield f}else for await(let f of l.agent.runAsync(l)){f.partial||await this.sessionService.appendEvent({session:c,event:f});let h=await this.pluginManager.runOnEventCallback({invocationContext:l,event:f});h?yield h:yield f}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 a=r.parts[s];if(!a.inlineData)continue;let c=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=(0,In.createPartFromText)(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Wo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){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 x)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Wo(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let c=o[a],l=P(c);if(l){for(let d of l)if(d.id===t)return c}}return null}var ze=class extends ee{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new pe,sessionService:new J,memoryService:new X})}};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 L{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 x&&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 x&&this.agent.outputSchema;e.response=t?{type:Se.Type.OBJECT}:{type:Se.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var d,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof x&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new ee({appName:this.agent.name,agent:this.agent,artifactService:new We(t),sessionService:new J,memoryService:new X,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;for await(let f of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))f.actions.stateDelta&&t.state.update(f.actions.stateDelta),a=f;if(!((u=(d=a==null?void 0:a.content)==null?void 0:d.parts)!=null&&u.length))return"";let c=this.agent instanceof x&&this.agent.outputSchema,l=a.content.parts.map(f=>f.text).filter(f=>f).join(`
85
+ `);return c?JSON.parse(l):l}};var ge=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 Mt=class extends L{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.config=t.config||{},t.config.tools=t.config.tools||[],Jt(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(Ht(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},wn=new Mt;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.`,Ze=class extends ${constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=In:e.description=In.trimStart(),e}};var Pn=require("@modelcontextprotocol/sdk/client/index.js"),wn=require("@modelcontextprotocol/sdk/client/stdio.js"),kn=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var be=class{constructor(e){this.connectionParams=e}async createSession(){let e=new Pn.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new wn.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new kn.StreamableHTTPClientTransport(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};var q=require("@google/genai"),pe=require("zod");var Yc=pe.z.object({type:pe.z.literal("object"),properties:pe.z.record(pe.z.unknown()).optional(),required:pe.z.string().array().optional()});function Zo(o){switch(o.toLowerCase()){case"text":case"string":return q.Type.STRING;case"number":return q.Type.NUMBER;case"boolean":return q.Type.BOOLEAN;case"integer":return q.Type.INTEGER;case"array":return q.Type.ARRAY;case"object":return q.Type.OBJECT;default:return q.Type.TYPE_UNSPECIFIED}}function kt(o){if(!o)return;function e(t){let n=Zo(t.type),r={type:n,description:t.description};if(n===q.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===q.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var Te=class extends I{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:kt(this.mcpTool.inputSchema),response:kt(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 Lt=class extends de{constructor(e,t=[]){super(t),this.mcpSessionManager=new be(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 Te(r,this.mcpSessionManager))}async close(){}};var Ln=require("@google-cloud/storage"),We=require("@google/genai");var _t=class{constructor(e){this.bucket=new Ln.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(ze({...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(ze({...e,version:t})),[[r],[i]]=await Promise.all([n.getMetadata(),n.download()]);return r.contentType==="text/plain"?(0,We.createPartFromText)(i.toString("utf-8")):(0,We.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(ze({...e,version:n})).delete()))}async listVersions(e){let t=ze(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 ze({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 Ye=require("@opentelemetry/api"),_n=require("@opentelemetry/api-logs"),Qe=require("@opentelemetry/sdk-logs"),Xe=require("@opentelemetry/sdk-metrics"),Mn=require("@opentelemetry/resources"),On=require("@opentelemetry/sdk-trace-base"),Nn=require("@opentelemetry/sdk-trace-node"),Bn=require("@opentelemetry/exporter-trace-otlp-http"),Fn=require("@opentelemetry/exporter-metrics-otlp-http"),Dn=require("@opentelemetry/exporter-logs-otlp-http");function zo(o=[],e){let t=e||Wo(),n=[...o,Qo()],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 Nn.NodeTracerProvider({resource:t,spanProcessors:r});c.register(),Ye.trace.setGlobalTracerProvider(c)}if(i.length>0){let c=new Xe.MeterProvider({readers:i,resource:t});Ye.metrics.setGlobalMeterProvider(c)}if(s.length>0){let c=new Qe.LoggerProvider({resource:t,processors:s});_n.logs.setGlobalLoggerProvider(c)}}function Wo(){return(0,Mn.detectResources)({detectors:[]})}function Yo(){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 Qo(o=Yo()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new On.BatchSpanProcessor(new Bn.OTLPTraceExporter)]:[],metricReaders:t?[new Xe.PeriodicExportingMetricReader({exporter:new Fn.OTLPMetricExporter})]:[],logRecordProcessors:n?[new Qe.BatchLogRecordProcessor(new Dn.OTLPLogExporter)]:[]}}var Gn=require("google-auth-library"),$n=require("@opentelemetry/sdk-metrics"),qn=require("@opentelemetry/resources"),Un=require("@opentelemetry/resource-detector-gcp"),jn=require("@google-cloud/opentelemetry-cloud-trace-exporter"),Kn=require("@opentelemetry/sdk-trace-base"),Vn=require("@google-cloud/opentelemetry-cloud-monitoring-exporter");var Xo="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Ho(){try{return await new Gn.GoogleAuth().getProjectId()||void 0}catch{return}}async function Jo(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await Ho();return n?{spanProcessors:e?[new Kn.BatchSpanProcessor(new jn.TraceExporter({projectId:n}))]:[],metricReaders:t?[new $n.PeriodicExportingMetricReader({exporter:new Vn.MetricExporter({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(p.warn(Xo),{})}function er(){return(0,qn.detectResources)({detectors:[Un.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.`,Qe=class extends j{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=kn:e.description=kn.trimStart(),e}};var Ln=require("@modelcontextprotocol/sdk/client/index.js"),_n=require("@modelcontextprotocol/sdk/client/stdio.js"),Mn=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var Re=class{constructor(e){this.connectionParams=e}async createSession(){let e=new Ln.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new _n.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new Mn.StreamableHTTPClientTransport(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};var K=require("@google/genai"),he=require("zod");var Jc=he.z.object({type:he.z.literal("object"),properties:he.z.record(he.z.unknown()).optional(),required:he.z.string().array().optional()});function Yo(o){switch(o.toLowerCase()){case"text":case"string":return K.Type.STRING;case"number":return K.Type.NUMBER;case"boolean":return K.Type.BOOLEAN;case"integer":return K.Type.INTEGER;case"array":return K.Type.ARRAY;case"object":return K.Type.OBJECT;default:return K.Type.TYPE_UNSPECIFIED}}function Ot(o){if(!o)return;function e(t){let n=Yo(t.type),r={type:n,description:t.description};if(n===K.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===K.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var Ie=class extends L{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:Ot(this.mcpTool.inputSchema),response:Ot(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 Nt=class extends ge{constructor(e,t=[]){super(t),this.mcpSessionManager=new Re(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 Ie(r,this.mcpSessionManager))}async close(){}};var On=require("@google-cloud/storage"),He=require("@google/genai");var Bt=class{constructor(e){this.bucket=new On.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(Xe({...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(Xe({...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 a of i)t.push(a.name.split("/").pop());for(let a of s)t.push(a.name.split("/").pop());return t.sort((a,c)=>a.localeCompare(c))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(n=>this.bucket.file(Xe({...e,version:n})).delete()))}async listVersions(e){let t=Xe(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 Xe({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"),Nn=require("@opentelemetry/api-logs"),et=require("@opentelemetry/sdk-logs"),tt=require("@opentelemetry/sdk-metrics"),Bn=require("@opentelemetry/resources"),Fn=require("@opentelemetry/sdk-trace-base"),$n=require("@opentelemetry/sdk-trace-node"),Gn=require("@opentelemetry/exporter-trace-otlp-http"),Dn=require("@opentelemetry/exporter-metrics-otlp-http"),qn=require("@opentelemetry/exporter-logs-otlp-http");function Qo(o=[],e){let t=e||Xo(),n=[...o,Jo()],r=n.flatMap(a=>a.spanProcessors||[]),i=n.flatMap(a=>a.metricReaders||[]),s=n.flatMap(a=>a.logRecordProcessors||[]);if(r.length>0){let a=new $n.NodeTracerProvider({resource:t,spanProcessors:r});a.register(),Je.trace.setGlobalTracerProvider(a)}if(i.length>0){let a=new tt.MeterProvider({readers:i,resource:t});Je.metrics.setGlobalMeterProvider(a)}if(s.length>0){let a=new et.LoggerProvider({resource:t,processors:s});Nn.logs.setGlobalLoggerProvider(a)}}function Xo(){return(0,Bn.detectResources)({detectors:[]})}function Ho(){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 Jo(o=Ho()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new Fn.BatchSpanProcessor(new Gn.OTLPTraceExporter)]:[],metricReaders:t?[new tt.PeriodicExportingMetricReader({exporter:new Dn.OTLPMetricExporter})]:[],logRecordProcessors:n?[new et.BatchLogRecordProcessor(new qn.OTLPLogExporter)]:[]}}var Un=require("google-auth-library"),jn=require("@opentelemetry/sdk-metrics"),Kn=require("@opentelemetry/resources"),Vn=require("@opentelemetry/resource-detector-gcp"),Zn=require("@google-cloud/opentelemetry-cloud-trace-exporter"),zn=require("@opentelemetry/sdk-trace-base"),Wn=require("@google-cloud/opentelemetry-cloud-monitoring-exporter");var er="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function tr(){try{return await new Un.GoogleAuth().getProjectId()||void 0}catch{return}}async function nr(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await tr();return n?{spanProcessors:e?[new zn.BatchSpanProcessor(new Zn.TraceExporter({projectId:n}))]:[],metricReaders:t?[new jn.PeriodicExportingMetricReader({exporter:new Wn.MetricExporter({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(p.warn(er),{})}function or(){return(0,Kn.detectResources)({detectors:[Vn.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