@paean-ai/adk 0.2.26 → 0.2.28

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.
@@ -454,6 +454,7 @@ class Gemini extends BaseLlm {
454
454
  return new GeminiLlmConnection(liveSession);
455
455
  }
456
456
  preprocessRequest(llmRequest) {
457
+ var _a;
457
458
  if (this.apiBackend === GoogleLLMVariant.GEMINI_API) {
458
459
  if (llmRequest.config) {
459
460
  llmRequest.config.labels = void 0;
@@ -467,6 +468,22 @@ class Gemini extends BaseLlm {
467
468
  }
468
469
  }
469
470
  }
471
+ if (((_a = llmRequest.config) == null ? void 0 : _a.tools) && llmRequest.config.tools.length > 1) {
472
+ const hasBuiltInSearch = llmRequest.config.tools.some(
473
+ (t) => "googleSearch" in t || "googleSearchRetrieval" in t
474
+ );
475
+ const hasFunctionDeclarations = llmRequest.config.tools.some(
476
+ (t) => "functionDeclarations" in t
477
+ );
478
+ if (hasBuiltInSearch && hasFunctionDeclarations) {
479
+ logger.warn(
480
+ "Gemini API (AI Studio) does not support combining built-in search tools with custom function declarations. Removing built-in search tool from this request."
481
+ );
482
+ llmRequest.config.tools = llmRequest.config.tools.filter(
483
+ (t) => !("googleSearch" in t) && !("googleSearchRetrieval" in t)
484
+ );
485
+ }
486
+ }
470
487
  }
471
488
  }
472
489
  }
@@ -16,7 +16,7 @@ function getBooleanEnvVar(envVar) {
16
16
  return false;
17
17
  }
18
18
  const envVarValue = (process.env[envVar] || "").toLowerCase();
19
- return ["true", "1"].includes(envVar.toLowerCase());
19
+ return ["true", "1"].includes(envVarValue);
20
20
  }
21
21
  export {
22
22
  GoogleLLMVariant,
@@ -453,6 +453,9 @@ function runPreProcessor(invocationContext, llmRequest) {
453
453
  }
454
454
  const codeExecutorContext = new CodeExecutorContext(new State(invocationContext.session.state));
455
455
  if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
456
+ logger.warn(
457
+ "[CodeExecutor] Pre-processor skipped: error count exceeded max retry attempts (".concat(codeExecutor.errorRetryAttempts, ") for invocation ").concat(invocationContext.invocationId)
458
+ );
456
459
  return;
457
460
  }
458
461
  const allInputFiles = extractAndReplaceInlineFiles(codeExecutorContext, llmRequest);
@@ -521,6 +524,9 @@ function runPostProcessor(invocationContext, llmResponse) {
521
524
  }
522
525
  const codeExecutorContext = new CodeExecutorContext(new State(invocationContext.session.state));
523
526
  if (codeExecutorContext.getErrorCount(invocationContext.invocationId) >= codeExecutor.errorRetryAttempts) {
527
+ logger.warn(
528
+ "[CodeExecutor] Post-processor skipped: error count exceeded max retry attempts (".concat(codeExecutor.errorRetryAttempts, ") for invocation ").concat(invocationContext.invocationId)
529
+ );
524
530
  return;
525
531
  }
526
532
  const responseContent = llmResponse.content;
package/dist/web/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- var wn=Object.defineProperty,Ln=Object.defineProperties;var kn=Object.getOwnPropertyDescriptors;var Mt=Object.getOwnPropertySymbols;var Pn=Object.prototype.hasOwnProperty,_n=Object.prototype.propertyIsEnumerable;var Ze=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var Nt=(o,e,t)=>e in o?wn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,E=(o,e)=>{for(var t in e||(e={}))Pn.call(e,t)&&Nt(o,t,e[t]);if(Mt)for(var t of Mt(e))_n.call(e,t)&&Nt(o,t,e[t]);return o},he=(o,e)=>Ln(o,kn(e));var u=function(o,e){this[0]=o,this[1]=e},v=(o,e,t)=>{var n=(s,c,a,l)=>{try{var d=t[s](c),f=(c=d.value)instanceof u,g=d.done;Promise.resolve(f?c[0]:c).then(h=>f?n(s==="return"?s:"next",c[1]?{done:h.done,value:h.value}:h,a,l):a({value:h,done:g})).catch(h=>n("throw",h,a,l))}catch(h){l(h)}},r=s=>i[s]=c=>new Promise((a,l)=>n(s,c,a,l)),i={};return t=t.apply(o,e),i[Ze("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var b=(o,e,t)=>(e=o[Ze("asyncIterator")])?e.call(o):(o=o[Ze("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,c,a)=>(i=r.call(o,i),a=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:a}),c)))),t("next"),t("return"),e);import{trace as Gt}from"@opentelemetry/api";function J(o={}){return E({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function Ot(o,e){let t=J();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 L(o={}){return he(E({},o),{id:o.id||ze(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||J(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function Ce(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:N(o).length===0&&z(o).length===0&&!o.partial&&!Ft(o)}function N(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 z(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 Ft(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 Mn(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 Bt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function ze(){let o="";for(let e=0;e<8;e++)o+=Bt[Math.floor(Math.random()*Bt.length)];return o}var R=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=E(E({},this.delta),e),this.value=E(E({},this.value),e)}toRecord(){return E(E({},this.value),this.delta)}};R.APP_PREFIX="app:",R.USER_PREFIX="user:",R.TEMP_PREFIX="temp:";var V=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 R(this.invocationContext.session.state,{})}};var W=class extends V{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||J(),this._state=new R(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 _e(){return typeof window<"u"}var Pe="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ve(){let o="";for(let e=0;e<Pe.length;e++){let t=Math.random()*16|0;Pe[e]==="x"?o+=t.toString(16):Pe[e]==="y"?o+=(t&3|8).toString(16):o+=Pe[e]}return o}function $t(o){return _e()?window.atob(o):Buffer.from(o,"base64").toString()}var We=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},te=class{constructor(e){this.invocationCostManager=new We;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-".concat(ve())}var Q=class{constructor(e){this.name=Nn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Bn(this),this.beforeAgentCallback=qt(e.beforeAgentCallback),this.afterAgentCallback=qt(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return v(this,null,function*(){let t=Gt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let c=this.createInvocationContext(e),a=yield new u(this.handleBeforeAgentCallback(c));if(a&&(yield a),c.endInvocation)return;try{for(var n=b(this.runAsyncImpl(c)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let d=i.value;yield d}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(c.endInvocation)return;let l=yield new u(this.handleAfterAgentCallback(c));l&&(yield l)}finally{t.end()}})}runLive(e){return v(this,null,function*(){let t=Gt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new te(he(E({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new W({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,L({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return L({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new W({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return L({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return L({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error('Agent "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function Nn(o){if(!On(o))throw new Error('Found invalid agent name: "'.concat(o,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.'));if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function On(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function Bn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function qt(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Kt}from"@google/genai";var Re=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(e," requires oauth2 in authCredential."));if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error("Auth Scheme ".concat(e," requires both clientId and clientSecret in authCredential.oauth2."));return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var ce=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var ie=class extends W{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Re(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Re(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new ce({hint:e,confirmed:!1,payload:t})}};var Ut=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Ut||{}),ye=1;function Fn(o){ye=o}var Ye=class{log(e,...t){if(!(e<ye))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error("Unsupported log level: ".concat(e))}}debug(...e){ye>0||console.debug(Me(0),...e)}info(...e){ye>1||console.info(Me(1),...e)}warn(...e){ye>2||console.warn(Me(2),...e)}error(...e){ye>3||console.error(Me(3),...e)}},$n={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Dn={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Gn="\x1B[0m";function Me(o){return"".concat(Dn[o],"[ADK ").concat($n[o],"]:").concat(Gn)}var p=new Ye;var Xe="adk-",Ne="adk_request_credential",Ee="adk_request_confirmation",qn={handleFunctionCallList:Oe};function Qe(){return"".concat(Xe).concat(ve())}function jt(o){let e=N(o);if(e)for(let t of e)t.id||(t.id=Qe())}function Vt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Xe)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Xe)&&(e.functionResponse.id=void 0)}function Zt(o,e){if(o in e)return o;let t=o.indexOf(":");if(t>0){let n=o.substring(0,t);if(n in e)return p.info('Resolved Gemini 3 function name "'.concat(o,'" to tool "').concat(n,'"')),n}}function zt(o,e){let t=new Set;for(let n of o){if(!n.name||!n.id)continue;let r=Zt(n.name,e);r&&e[r].isLongRunning&&t.add(n.id)}return t}function Wt(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:Ne,args:{function_call_id:i,auth_config:s},id:Qe()};n.add(c.id),t.push({functionCall:c})}if(t.length!==0)return L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Yt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=N(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let d=(c=i.find(g=>g.id===a))!=null?c:void 0;if(!d)continue;let f={name:Ee,args:{originalFunctionCall:d,toolConfirmation:l},id:Qe()};r.add(f.id),n.push({functionCall:f})}if(n.length!==0)return L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Un(o,e,t){return p.debug("callToolAsync ".concat(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 c=N(e);return await Oe({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Oe({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var d,f,g;let c=[],a=e.filter(h=>!i||h.id&&i.has(h.id));for(let h of a){let y;s&&h.id&&(y=s[h.id]);let I=Kn({invocationContext:o,functionCall:h,toolsDict:t,toolConfirmation:y});if(!I){let D=h.args?JSON.stringify(h.args).substring(0,300):"(none)";p.warn('Function "'.concat(h.name,'" not found in toolsDict ')+"(".concat(Object.keys(t).length," tools registered). ")+"Args: ".concat(D));let ae=L({invocationId:o.invocationId,author:o.agent.name,content:Kt({functionResponse:{id:h.id||void 0,name:(d=h.name)!=null?d:"unknown",response:{error:"Function '".concat(h.name,"' is not available. ")+"Please use a different approach or pick from the tools already declared in your configuration."}}}),branch:o.branch});c.push(ae);continue}let{tool:C,toolContext:m}=I;p.debug("execute_tool ".concat(C.name));let S=(f=h.args)!=null?f:{},A=null,j;if(A=await o.pluginManager.runBeforeToolCallback({tool:C,toolArgs:S,toolContext:m}),A==null){for(let D of n)if(A=await D({tool:C,args:S,context:m}),A)break}if(A==null)try{A=await Un(C,S,m)}catch(D){let ae=JSON.stringify(S).substring(0,500);if(p.error('Tool execution error: "'.concat(C.name,'" threw ').concat(D instanceof Error?D.message:String(D),". Args: ").concat(ae)),D instanceof Error){let P=await o.pluginManager.runOnToolErrorCallback({tool:C,toolArgs:S,toolContext:m,error:D});P?A=P:j=D.message}else j=D}let w=await o.pluginManager.runAfterToolCallback({tool:C,toolArgs:S,toolContext:m,result:A});if(w==null){for(let D of r)if(w=await D({tool:C,args:S,context:m,response:A}),w)break}if(w!=null&&(A=w),C.isLongRunning&&!A)continue;j?A={error:j}:(typeof A!="object"||A==null)&&(A={result:A});let K=L({invocationId:o.invocationId,author:o.agent.name,content:Kt({functionResponse:{id:m.functionCallId,name:(g=h.name)!=null?g:C.name,response:A}}),actions:m.actions,branch:o.branch});p.debug("traceToolCall",{tool:C.name,args:S,functionResponseEvent:K.id}),c.push(K)}if(!c.length)return null;let l=jn(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Kn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){let r=e.name?Zt(e.name,t):void 0;if(!r)return null;let i=new ie({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[r],toolContext:i}}function jn(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 L({invocationId:t.invocationId,author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var He=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return v(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as vn}from"zod";var se=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 Vn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Be(o){let e=o.match(Vn);return e?e[1]:o}function Qt(o){return Be(o).startsWith("gemini-")}function Ht(o){return Be(o).startsWith("gemini-1")}function Jt(o){return Be(o).startsWith("gemini-2")}function en(o){let e=Be(o);return e.startsWith("gemini-3")&&e.includes("preview")}var Ae=class extends se{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Jt(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 ".concat(e.model))}};import{Language as Zn,Outcome as tn}from"@google/genai";function Y(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 f=0;f<o.parts.length;f++){let g=o.parts[f];if(g.executableCode&&(f===o.parts.length-1||!o.parts[f+1].codeExecutionResult))return o.parts=o.parts.slice(0,f+1),g.executableCode.code}let t=o.parts.filter(f=>f.text);if(!t.length)return"";let n=Y(t[0]),r=t.map(f=>f.text).join("\n"),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),c=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(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(Je(l)),l):""}function Je(o){return{text:o,executableCode:{code:o,language:Zn.PYTHON}}}function on(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:tn.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push("Code execution result:\n".concat(o.stdout,"\n")),o.outputFiles&&e.push("Saved artifacts:\n"+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:tn.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 et="_code_execution_context",tt="execution_session_id",le="processed_input_files",ue="_code_executor_input_files",fe="_code_executor_error_counts",nt="_code_execution_results",Ie=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(et))!=null?t:{},this.sessionState=e}getStateDelta(){return{[et]:Y(this.context)}}getExecutionId(){if(tt in this.context)return this.context[tt]}setExecutionId(e){this.context[tt]=e}getProcessedFileNames(){return le in this.context?this.context[le]:[]}addProcessedFileNames(e){le in this.context||(this.context[le]=[]),this.context[le].push(...e)}getInputFiles(){return ue in this.sessionState?this.sessionState.get(ue):[]}addInputFiles(e){ue in this.sessionState||this.sessionState.set(ue,[]),this.sessionState.get(ue).push(...e)}clearInputFiles(){ue in this.sessionState&&this.sessionState.set(ue,[]),le in this.context&&(this.context[le]=[])}getErrorCount(e){return fe in this.sessionState&&this.sessionState.get(fe)[e]||0}incrementErrorCount(e){fe in this.sessionState||this.sessionState.set(fe,{}),this.sessionState.get(fe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(fe in this.sessionState))return;let t=this.sessionState.get(fe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){nt in this.sessionState||this.sessionState.set(nt,{});let i=this.sessionState.get(nt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(et)||{}}};var ot="0.2.4";var zn="google-adk",Wn="gl-typescript",Yn="remote_reasoning_engine",Xn="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Qn(){let o="".concat(zn,"/").concat(ot);!_e()&&process.env[Xn]&&(o="".concat(o,"+").concat(Yn));let e="".concat(Wn,"/").concat(_e()?window.navigator.userAgent:process.version);return[o,e]}function sn(){return Qn()}var rt=Symbol("baseModel");function it(o){return typeof o=="object"&&o!==null&&rt in o&&o[rt]===!0}var an;an=rt;var xe=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."}]})}};xe.supportedModels=[];function we(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function cn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as at,FinishReason as to,GoogleGenAI as ct}from"@google/genai";function ln(){return Hn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Hn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Fe=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}]}}}receive(){return v(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};import{FinishReason as Jn}from"@google/genai";function st(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}:n.finishReason===Jn.STOP?{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 no="https://aiplatform.googleapis.com/v1/publishers/google",be=class extends xe{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=en(e);let a=typeof process=="object",l=a?process.env.AI_STUDIO_API_KEY:void 0,d=!!l;this.apiEndpoint=c,!this.apiEndpoint&&a&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&!d&&(this.apiEndpoint=no,p.info("Using Gemini 3 preview endpoint: ".concat(this.apiEndpoint)));let f=!!n;if(!f&&a){let g=process.env.GOOGLE_GENAI_USE_VERTEXAI;g&&(f=g.toLowerCase()==="true"||g==="1")}if(d&&(f&&p.info("AI_STUDIO_API_KEY set \u2014 overriding Vertex AI mode to use AI Studio (generativelanguage.googleapis.com)"),f=!1,this.apiKey=l),this.isGemini3Preview&&f){let g=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);g?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),f=!1,this.apiKey=g):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=f,this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}generateContentAsync(e,t=!1){return v(this,null,function*(){var n,r,i,s,c,a,l,d,f,g,h,y,A,j,w,K,D;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=E(E({},e.config.httpOptions.headers),this.trackingHeaders)),t){let ae=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),P="",_,T="",O,F,G=null;try{for(var I=b(ae),C,m,S;C=!(m=yield new u(I.next())).done;C=!1){let ee=m.value;F=ee;let x=st(ee);O=x.usageMetadata;let Z=(s=(i=x.content)==null?void 0:i.parts)==null?void 0:s[0],Te=(a=(c=x.content)==null?void 0:c.parts)==null?void 0:a.some(q=>q.functionCall);if(this.isGemini3Preview&&((l=x.content)!=null&&l.parts)){for(let q of x.content.parts)if(q.thoughtSignature&&!_){_=q.thoughtSignature,p.debug("[Gemini3] Captured thoughtSignature (length: ".concat(_.length,")"));break}}if(Z!=null&&Z.text)"thought"in Z&&Z.thought?(P+=Z.text,"thoughtSignature"in Z&&Z.thoughtSignature&&(_=Z.thoughtSignature)):T+=Z.text,Te||(x.partial=!0),this.isGemini3Preview&&Te&&(P="",_=void 0,T="");else if((P||T)&&(!Z||!Z.inlineData))if(this.isGemini3Preview&&Te&&x.content){let q=[];if(P){let $={text:P,thought:!0};_&&($.thoughtSignature=_),q.push($)}if(T&&q.push(at(T)),!P&&_){for(let $ of x.content.parts||[])if($.functionCall&&!$.thoughtSignature){$.thoughtSignature=_;break}}x.content.parts=[...q,...x.content.parts||[]],P="",_=void 0,T=""}else{let q=[];if(P){let $={text:P,thought:!0};_&&($.thoughtSignature=_),q.push($)}T&&q.push(at(T)),yield{content:{role:"model",parts:q},usageMetadata:x.usageMetadata},P="",_=void 0,T=""}if(this.isGemini3Preview&&Te&&((d=x.content)!=null&&d.parts)&&!x.content.parts.some($=>$.thoughtSignature)&&_){for(let $ of x.content.parts)if($.functionCall){$.thoughtSignature=_;break}}if(Te){if(G&&((f=G.content)!=null&&f.parts)){let q=(((g=x.content)==null?void 0:g.parts)||[]).filter($=>$.functionCall||$.thoughtSignature);G.content.parts.push(...q),G.usageMetadata=x.usageMetadata}else G=x;continue}if(G){if(!((y=(h=x.content)==null?void 0:h.parts)!=null&&y.length))continue;yield G,G=null}yield x}}catch(m){S=[m]}finally{try{C&&(m=I.return)&&(yield new u(m.call(I)))}finally{if(S)throw S[0]}}if(G){if(this.isGemini3Preview&&((A=G.content)!=null&&A.parts)){let ee=G.content.parts.filter(x=>x.thoughtSignature).length;if(ee===0&&_){for(let x of G.content.parts)if(x.functionCall){x.thoughtSignature=_;break}}else ee===0&&p.warn("[Gemini3] No thoughtSignature on merged function call parts \u2014 may cause 400 on next request")}yield G,G=null}if((T||P)&&((w=(j=F==null?void 0:F.candidates)==null?void 0:j[0])==null?void 0:w.finishReason)===to.STOP){let ee=[];if(P){let x={text:P,thought:!0};_&&(x.thoughtSignature=_),ee.push(x)}T&&ee.push({text:T}),yield{content:{role:"model",parts:ee},usageMetadata:O}}}else{let ae=yield new u(this.apiClient.models.generateContent({model:(K=e.model)!=null?K:this.model,contents:e.contents,config:e.config})),P=st(ae);if(this.isGemini3Preview&&((D=P.content)!=null&&D.parts)){let _,T=!1;for(let F of P.content.parts)if(F.thoughtSignature){_=F.thoughtSignature,F.thought&&(T=!0);break}if(_&&!T){for(let F of P.content.parts)if(F.functionCall&&!F.thoughtSignature){F.thoughtSignature=_;break}}P.content.parts.some(F=>F.functionCall)&&P.content.parts.filter(G=>G.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield P}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=E(E({},this.trackingHeaders),this.headers);if(this.vertexai)this._apiClient=new ct({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: ".concat(this.apiEndpoint)),this.isGemini3Preview&&(t.apiVersion="",p.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new ct({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 ct({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:[at(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 Fe(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)}}};be.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function un(o){o&&o.displayName&&(o.displayName=void 0)}var lt=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)}},X=class X{static newLlm(e){return new(X.resolve(e))({model:e})}static _register(e,t){X.llmRegistryDict.has(e)&&p.info("Updating LLM class for ".concat(e," from ").concat(X.llmRegistryDict.get(e)," to ").concat(t)),X.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)X._register(t,e)}static resolve(e){let t=X.resolveCache.get(e);if(t)return t;for(let[n,r]of X.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return X.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};X.llmRegistryDict=new Map,X.resolveCache=new lt(32);var Se=X;Se.register(be);var H=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=oo(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 oo(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as ro}from"@google/genai";import{ZodObject as io}from"zod";import{Type as U}from"@google/genai";import{z as M}from"zod";function fn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function ne(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 M.ZodFirstPartyTypeKind.ZodString:n.type=U.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 M.ZodFirstPartyTypeKind.ZodNumber:n.type=U.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=U.INTEGER);return r(n);case M.ZodFirstPartyTypeKind.ZodBoolean:return n.type=U.BOOLEAN,r(n);case M.ZodFirstPartyTypeKind.ZodArray:return n.type=U.ARRAY,n.items=ne(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case M.ZodFirstPartyTypeKind.ZodObject:return $e(o);case M.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=U.STRING;else if(i==="number")n.type=U.NUMBER;else if(i==="boolean")n.type=U.BOOLEAN;else if(e.value===null)n.type=U.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case M.ZodFirstPartyTypeKind.ZodEnum:return n.type=U.STRING,n.enum=e.values,r(n);case M.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=U.STRING,n.enum=Object.values(e.values),r(n);case M.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(ne),r(n);case M.ZodFirstPartyTypeKind.ZodOptional:return ne(e.innerType);case M.ZodFirstPartyTypeKind.ZodNullable:let s=ne(e.innerType);return r(s?E({anyOf:[s,{type:U.NULL}]},t&&{description:t}):E({type:U.NULL},t&&{description:t}));case M.ZodFirstPartyTypeKind.ZodDefault:let c=ne(e.innerType);return c&&(c.default=e.defaultValue()),c;case M.ZodFirstPartyTypeKind.ZodBranded:return ne(e.type);case M.ZodFirstPartyTypeKind.ZodReadonly:return ne(e.innerType);case M.ZodFirstPartyTypeKind.ZodNull:return n.type=U.NULL,r(n);case M.ZodFirstPartyTypeKind.ZodAny:case M.ZodFirstPartyTypeKind.ZodUnknown:return r(E({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function $e(o){if(o._def.typeName!==M.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let c=e[s],a=ne(c);a&&(t[s]=a);let l=c,d=!1;for(;l._def.typeName===M.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===M.ZodFirstPartyTypeKind.ZodDefault;)d=!0,l=l._def.innerType;d||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==M.ZodFirstPartyTypeKind.ZodNever?i=ne(r)||!0:i=o._def.unknownKeys==="passthrough",E({type:U.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function so(o){return o===void 0?{type:ro.OBJECT,properties:{}}:fn(o)?$e(o):o}var oe=class extends H{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:so(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof io&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var re=class{};function ut(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)||ao(a)||co(a)||n.push(gn(e,a)?lo(a):a);let r=uo(n);r=fo(r);let i=[];for(let a of r){let l=Y(a.content);Vt(l),i.push(l)}return i}function pn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||gn(e,r))return ut(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)===Ne||((n=r.functionResponse)==null?void 0:n.name)===Ne)return!0;return!1}function co(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)===Ee||((n=r.functionResponse)==null?void 0:n.name)===Ee)return!0;return!1}function gn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function lo(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:"[".concat(o.author,"] said: ").concat(a.text)});else if(a.functionCall){let l=dn(a.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(a.functionCall.name,"` with parameters: ").concat(l)})}else if(a.functionResponse){let l=dn(a.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(a.functionResponse.name,"` returned result: ").concat(l)})}else(c=e.parts)==null||c.push(a);return L({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=L(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 uo(o){if(o.length===0)return o;let e=o[o.length-1],t=z(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=N(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],d=N(l);if(d!=null&&d.length){for(let f of d)if(f.id&&n.has(f.id)){i=a;let g=new Set(d.map(y=>y.id).filter(y=>!!y));if(!Array.from(n).every(y=>g.has(y)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(g).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=g;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let a=i+1;a<o.length-1;a++){let l=o[a],d=z(l);d&&d.some(f=>f.id&&n.has(f.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(mn(s)),c}function fo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=z(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(z(n).length>0)continue;let r=N(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 dn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function ft(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),d=l.endsWith("?");if(d&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let g=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!g)throw new Error("Artifact ".concat(f," not found."));return String(g)}if(!mo(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(d)return"";throw new Error("Context variable not found: `".concat(l,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,c=o.matchAll(r);for(let a of c){i.push(o.slice(s,a.index));let l=await n(a);i.push(l),s=a.index+a[0].length}return i.push(o.slice(s)),i.join("")}var po=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function hn(o){return o===""||o===void 0?!1:po.test(o)}var go=[R.APP_PREFIX,R.USER_PREFIX,R.TEMP_PREFIX];function mo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?hn(o):go.includes(e[0]+":")?hn(e[1]):!1}var dt=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(dt||{});function Cn(o={}){return E({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ho(o.maxLlmCalls||500)},o)}function ho(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(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 yn="adk_agent_name";async function En(o,e){return o instanceof H?[o]:await o.getTools(e)}var pt=class extends re{runAsync(e,t){return v(this,null,function*(){var r;let n=e.agent;n instanceof k&&(t.model=n.canonicalModel.model,t.config=E({},(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))})}},Co=new pt,gt=class extends re{runAsync(e,t){return v(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),we(t,r)})}},vo=new gt,mt=class extends re{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof k)||!(n.rootAgent instanceof k))return;let r=n.rootAgent;if(r instanceof k&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new V(e))),c=i;s&&(c=yield new u(ft(i,new V(e)))),we(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new V(e))),c=i;s&&(c=yield new u(ft(i,new V(e)))),we(t,[c])}})}},yo=new mt,ht=class{runAsync(e,t){return v(this,null,function*(){let n=e.agent;!n||!(n instanceof k)||(n.includeContents==="default"?t.contents=ut(e.session.events,n.name,e.branch):t.contents=pn(e.session.events,n.name,e.branch))})}},Eo=new ht,Ct=class extends re{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new oe({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:vn.object({agentName:vn.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,n){return v(this,null,function*(){if(!(t.agent instanceof k))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;we(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new ie({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof k)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},Ao=new Ct,vt=class extends re{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof k))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=z(a);if(!l)continue;let d=!1;for(let f of l){if(f.name!==Ee)continue;d=!0;let g=null;f.response&&Object.keys(f.response).length===1&&"response"in f.response?g=JSON.parse(f.response.response):f.response&&(g=new ce({hint:f.response.hint,payload:f.response.payload,confirmed:f.response.confirmed})),f.id&&g&&(i[f.id]=g)}if(d){s=c;break}}if(Object.keys(i).length!==0)for(let c=s-1;c>=0;c--){let a=r[c],l=N(a);if(!l)continue;let d={},f={};for(let I of l){if(!I.id||!(I.id in i))continue;let C=I.args;if(!C||!("originalFunctionCall"in C))continue;let m=C.originalFunctionCall;m.id&&(d[m.id]=i[I.id],f[m.id]=m)}if(Object.keys(d).length===0)continue;for(let I=r.length-1;I>s;I--){let C=r[I],m=z(C);if(m){for(let S of m)S.id&&S.id in d&&(delete d[S.id],delete f[S.id]);if(Object.keys(d).length===0)break}}if(Object.keys(d).length===0)continue;let g=yield new u(n.canonicalTools(new V(e))),h=Object.fromEntries(g.map(I=>[I.name,I])),y=yield new u(Oe({invocationContext:e,functionCalls:Object.values(f),toolsDict:h,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(d)),toolConfirmationDict:d}));y&&(yield y);return}})}},xo=new vt,yt=class extends re{runAsync(e,t){return v(this,null,function*(){if(e.agent instanceof k&&e.agent.codeExecutor){try{for(var n=b(So(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(e.agent.codeExecutor instanceof se)for(let c of t.contents){let a=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],l=rn(c,a,e.agent.codeExecutor.executionResultDelimiters)}}})}},De={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},bo="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",Et=class{runAsync(e,t){return v(this,null,function*(){if(!t.partial)try{for(var n=b(To(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}},$s=new Et;function So(o,e){return v(this,null,function*(){let t=o.agent;if(!(t instanceof k))return;let n=t.codeExecutor;if(!n||!(n instanceof se))return;if(n instanceof Ae){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new Ie(new R(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=Ro(r,e),s=new Set(r.getProcessedFileNames()),c=i.filter(a=>!s.has(a.name));for(let a of c){let l=Io(a);if(!l)return;let d={role:"model",parts:[{text:"Processing input file: `".concat(a.name,"`")},Je(l)]};e.contents.push(Y(d)),yield L({invocationId:o.invocationId,author:t.name,branch:o.branch,content:d});let f=An(o,r),g=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[a],executionId:f}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:g.stdout,resultStderr:g.stderr}),r.addProcessedFileNames([a.name]);let h=yield new u(xn(o,r,g));yield h,e.contents.push(Y(h.content))}})}function To(o,e){return v(this,null,function*(){let t=o.agent;if(!(t instanceof k))return;let n=t.codeExecutor;if(!n||!(n instanceof se)||!e||!e.content||n instanceof Ae)return;let r=new Ie(new R(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=nn(i,n.codeBlockDelimiters);if(!s)return;yield L({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let c=An(o,r),a=yield new u(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 yield new u(xn(o,r,a)),e.content=null})}function Ro(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let c=0;c<s.parts.length;c++){let a=s.parts[c],l=(r=a.inlineData)==null?void 0:r.mimeType;if(!l||!a.inlineData||!De[l])continue;let d="data_".concat(i+1,"_").concat(c+1).concat(De[l].extension);a.text="\nAvailable file: `".concat(d,"`\n");let f={name:d,content:$t(a.inlineData.data),mimeType:l};n.has(d)||(o.addInputFiles([f]),t.push(f))}}return t}function An(o,e){var r;let t=o.agent;if(!(t instanceof k)||!((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:[on(t)]},r=J({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 L({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Io(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"\n".concat(bo,"\n\n# Load the dataframe.\n").concat(t," = ").concat(n,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var wo=new yt,B=class B extends Q{constructor(e){var n,r,i,s,c,a,l,d,f;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(c=e.disallowTransferToPeers)!=null?c:!1,this.includeContents=(a=e.includeContents)!=null?a:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[Co,vo,yo,xo,Eo,wo],this.responseProcessors=(d=e.responseProcessors)!=null?d:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((f=this.subAgents)!=null&&f.length)||this.requestProcessors.push(Ao),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 ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, subAgents must be empty to disable agent transfer."));if(this.tools&&this.tools.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(it(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 B)return e.canonicalModel;e=e.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await En(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return B.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return B.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return B.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return B.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){p.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!Ce(e)){p.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){p.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return v(this,null,function*(){var c,a;let t=0;for(;;){let l;try{for(var n=b(this.runOneStepAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let d=i.value;l=d,this.maybeSaveOutputToState(d),yield d}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(!l)break;if(l.errorCode&&!((a=(c=l.content)==null?void 0:c.parts)!=null&&a.length)){if(t++,t<=B.MAX_AGENT_LOOP_ERROR_RETRIES){p.warn("[runAsyncImpl] Error event (".concat(l.errorCode,": ").concat(l.errorMessage||"no message","), ")+"retrying agent loop (".concat(t,"/").concat(B.MAX_AGENT_LOOP_ERROR_RETRIES,")"));continue}p.error("[runAsyncImpl] Max agent-loop error retries exhausted for "+"".concat(l.errorCode,": ").concat(l.errorMessage||"no message"));break}if(t=0,Ce(l))break;if(l.partial){p.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return v(this,null,function*(){try{for(var t=b(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return v(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return v(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let C of this.requestProcessors)try{for(var r=b(C.runAsync(e,t)),i,s,c;i=!(s=yield new u(r.next())).done;i=!1){let m=s.value;yield m}}catch(s){c=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(c)throw c[0]}}for(let C of this.tools){let m=new ie({invocationContext:e}),S=yield new u(En(C,new V(e)));for(let A of S)yield new u(A.processLlmRequest({toolContext:m,llmRequest:t}))}if(e.endInvocation)return;let n=L({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var g=b(this.callLlmAsync(e,t,n)),h,y,I;h=!(y=yield new u(g.next())).done;h=!1){let C=y.value;try{try{for(var a=b(this.postprocess(e,t,C,n)),l,d,f;l=!(d=yield new u(a.next())).done;l=!1){let m=d.value;n.id=ze(),n.timestamp=new Date().getTime(),yield m}}catch(d){f=[d]}finally{try{l&&(d=a.return)&&(yield new u(d.call(a)))}finally{if(f)throw f[0]}}}catch(m){let S=m instanceof Error?m.message:String(m);p.error("Postprocess error: ".concat(S)),yield L({invocationId:e.invocationId,author:this.name,branch:e.branch,errorCode:"POSTPROCESS_ERROR",errorMessage:S})}}}catch(y){I=[y]}finally{try{h&&(y=g.return)&&(yield new u(y.call(g)))}finally{if(I)throw I[0]}}})}postprocess(e,t,n,r){return v(this,null,function*(){var y,I,C,m,S,A,j,w,K;for(let T of this.responseProcessors)try{for(var d=b(T.runAsync(e,n)),f,g,h;f=!(g=yield new u(d.next())).done;f=!1){let O=g.value;yield O}}catch(g){h=[g]}finally{try{f&&(g=d.return)&&(yield new u(g.call(d)))}finally{if(h)throw h[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;if(n.content&&!n.errorCode){if(!n.content.parts||n.content.parts.length===0){p.debug("[postprocess] Skipping LLM response with no parts (role=".concat(n.content.role,")"));return}if(n.content.parts.every(O=>!(O.functionCall||O.functionResponse||O.executableCode||O.codeExecutionResult||O.inlineData||O.fileData||"text"in O&&typeof O.text=="string"&&O.text.length>0))){p.debug("[postprocess] Skipping empty-content LLM response (".concat(n.content.parts.length," empty parts)"));return}}let i=L(E(E({},r),n));if(i.content){let T=N(i);T!=null&&T.length&&(jt(i),i.longRunningToolIds=Array.from(zt(T,t.toolsDict)),(y=i.content.parts)!=null&&y.some(F=>F.thoughtSignature)||p.warn("[postprocess] Function calls (".concat(T.length,") without thoughtSignature")))}if(p.debug("[postprocess] Yielding mergedEvent: role=".concat((I=i.content)==null?void 0:I.role,", parts=").concat((m=(C=i.content)==null?void 0:C.parts)==null?void 0:m.length,", ")+"hasFCs=".concat(((S=N(i))==null?void 0:S.length)||0,", partial=").concat(i.partial)),yield i,!((A=N(i))!=null&&A.length))return;let s=yield new u(Xt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let c=Wt(e,s);c&&(yield c);let a=Yt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),p.debug("[postprocess] Yielding functionResponseEvent: role=".concat((j=s.content)==null?void 0:j.role,", parts=").concat((K=(w=s.content)==null?void 0:w.parts)==null?void 0:K.length)),yield s;let l=s.actions.transferToAgent;if(l){let T=this.getAgentByName(e,l);try{for(var D=b(T.runAsync(e)),ae,P,_;ae=!(P=yield new u(D.next())).done;ae=!1){let O=P.value;yield O}}catch(P){_=[P]}finally{try{ae&&(P=D.return)&&(yield new u(P.call(D)))}finally{if(_)throw _[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return v(this,null,function*(){var s,c,a,l,d;let r=yield new u(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[yn]||(t.config.labels[yn]=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 I=((d=e.runConfig)==null?void 0:d.streamingMode)==="sse",C=B.LLM_TRANSIENT_ERROR_MAX_RETRIES;for(let m=0;m<=C;m++){if(m>0){let w=Math.min(B.LLM_TRANSIENT_ERROR_BASE_DELAY_MS*Math.pow(2,m-1),B.LLM_TRANSIENT_ERROR_MAX_DELAY_MS);p.warn("[callLlmAsync] Retrying LLM call after transient error "+"(attempt ".concat(m+1,"/").concat(C+1,"), waiting ").concat(w,"ms")),yield new u(new Promise(K=>setTimeout(K,w)))}let S=i.generateContentAsync(t,I),A=!1,j=!1;try{for(var f=b(this.runAndHandleError(S,e,t,n)),g,h,y;g=!(h=yield new u(f.next())).done;g=!1){let w=h.value;if(w.content&&(j=!0),w.errorCode&&B.LLM_RETRYABLE_ERROR_CODES.has(w.errorCode)&&!j&&m<C){A=!0,p.warn("[callLlmAsync] Transient LLM error: ".concat(w.errorCode)+"".concat(w.errorMessage?": "+w.errorMessage:"",", ")+"finishReason: ".concat(w.finishReason||"none",", ")+"usage: ".concat(JSON.stringify(w.usageMetadata)));break}let K=yield new u(this.handleAfterModelCallback(e,w,n));yield K!=null?K:w}}catch(h){y=[h]}finally{try{g&&(h=f.return)&&(yield new u(h.call(f)))}finally{if(y)throw y[0]}}if(!A)return}}})}async handleBeforeModelCallback(e,t,n){let r=new W({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 W({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}}runAndHandleError(e,t,n,r){return v(this,null,function*(){try{try{for(var i=b(e),s,c,a;s=!(c=yield new u(i.next())).done;s=!1){let l=c.value;yield l}}catch(c){a=[c]}finally{try{s&&(c=i.return)&&(yield new u(c.call(i)))}finally{if(a)throw a[0]}}}catch(l){let d=new W({invocationContext:t,eventActions:r.actions});if(l instanceof Error){let f=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:d,llmRequest:n,error:l}));if(f)yield f;else try{let g=JSON.parse(l.message);yield{errorCode:String(g.error.code),errorMessage:g.error.message}}catch(g){p.warn("LLM error message is not valid JSON, using raw message: ".concat(l.message.substring(0,200))),yield{errorCode:"UNKNOWN_ERROR",errorMessage:l.message}}}else throw p.error("Unknown error during response generation",l),l}})}};B.MAX_AGENT_LOOP_ERROR_RETRIES=2,B.LLM_TRANSIENT_ERROR_MAX_RETRIES=2,B.LLM_TRANSIENT_ERROR_BASE_DELAY_MS=1e3,B.LLM_TRANSIENT_ERROR_MAX_DELAY_MS=4e3,B.LLM_RETRYABLE_ERROR_CODES=new Set(["UNKNOWN_ERROR","UNEXPECTED_TOOL_CALL","MALFORMED_FUNCTION_CALL"]);var k=B;var At=class extends Q{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return v(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let c of this.subAgents){let a=!1;try{for(var n=b(c.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let l=i.value;yield l,l.actions.escalate&&(a=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a)return}t++}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var xt=class extends Q{runAsyncImpl(e){return v(this,null,function*(){let t=this.subAgents.map(c=>c.runAsync(Lo(this,c,e)));try{for(var n=b(ko(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function Lo(o,e,t){let n=new te(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function ko(o){return v(this,null,function*(){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=yield new u(Promise.race(e.values()));if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}})}var bt="task_completed",St=class extends Q{runAsyncImpl(e){return v(this,null,function*(){for(let s of this.subAgents)try{for(var t=b(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let c=r.value;yield c}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return v(this,null,function*(){for(let s of this.subAgents)s instanceof k&&((yield new u(s.canonicalTools(new V(e)))).some(l=>l.name===bt)||(s.tools.push(new oe({name:bt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(bt," function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.")));for(let s of this.subAgents)try{for(var t=b(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let c=r.value;yield c}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var Le=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=Ge(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let 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=Ge(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="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(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=Ge(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=Ge(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let c=[];for(let a=0;a<s.length;a++)c.push(a);return Promise.resolve(c)}};function Ge(o,e,t,n){return Po(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function Po(o){return o.startsWith("user:")}var de=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=bn(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=bn(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(g=>g.text).filter(g=>!!g).join(" "),d=_o(l);if(!d.size)continue;n.some(g=>d.has(g))&&r.memories.push({content:a.content,author:a.author,timestamp:Mo(a.timestamp)})}return r}};function bn(o,e){return"".concat(o,"/").concat(e)}function _o(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Mo(o){return new Date(o).toISOString()}var pe=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 Tt=class extends pe{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((n=e.agent.name)!=null?n:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(Ce(t)));let n=N(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=z(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");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: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var ke=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),p.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return p.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw 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 Tn="adk_request_confirmation",Rt="orcas_tool_call_security_check_states",Sn="This tool call needs external confirmation before completion.",Rn=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Rn||{}),qe=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},It=class extends pe{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new qe}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(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: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Sn};case"ALLOW":return;default:return}}};function No(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Tn&&e.push(t.functionCall);return e}var Ue=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(R.TEMP_PREFIX)||(e.state[n]=r)}};function Ke(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var ge=class extends Ue{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Ke({id:i||ve(),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,Y(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=Y(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(Ke({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 ".concat(s,": ").concat(l))};if(!this.sessions[r])return c("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return c("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return c("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(R.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(R.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(R.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(R.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[R.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[R.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as Oo}from"@google/genai";import{trace as Bo}from"@opentelemetry/api";var me=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ke((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return v(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var a;i=Cn(i);let c=Bo.getTracer("gcp.vertex.agent").startSpan("invocation");try{let h=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!h)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof k){let m=this.agent.canonicalModel.model;if(!m.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(m," in agent: ").concat(this.agent.name))}let y=new te({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Dt(),agent:this.agent,session:h,userContent:n,runConfig:i,pluginManager:this.pluginManager}),I=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:y}));if(I&&(n=I),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(y.invocationId,h.userId,h.id,n))),yield new u(this.sessionService.appendEvent({session:h,event:L({invocationId:y.invocationId,author:"user",actions:r?J({stateDelta:r}):void 0,content:n})}))}y.agent=this.determineAgentForResumption(h,this.agent);let C=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:y}));if(C){let m=L({invocationId:y.invocationId,author:"model",content:C});yield new u(this.sessionService.appendEvent({session:h,event:m})),yield m}else try{for(var l=b(y.agent.runAsync(y)),d,f,g;d=!(f=yield new u(l.next())).done;d=!1){let m=f.value;m.partial||(yield new u(this.sessionService.appendEvent({session:h,event:m})));let S=yield new u(this.pluginManager.runOnEventCallback({invocationContext:y,event:m}));S?yield S:yield m}}catch(f){g=[f]}finally{try{d&&(f=l.return)&&(yield new u(f.call(l)))}finally{if(g)throw g[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:y}))}finally{c.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_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:a,artifact:c}),r.parts[s]=Oo("Uploaded file: ".concat(a,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Fo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.debug("event[".concat(r,"]: author=").concat(e.events[r].author,", id=").concat(e.events[r].id));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){p.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof k)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Fo(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=N(a);if(l){for(let d of l)if(d.id===t)return a}}return null}var wt=class extends me{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new Le,sessionService:new ge,memoryService:new de})}};import{Type as Ve}from"@google/genai";var je=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 Lt=class extends H{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 k&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Ve.OBJECT,properties:{request:{type:Ve.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof k&&this.agent.outputSchema;e.response=t?{type:Ve.OBJECT}:{type:Ve.STRING}}return e}async runAsync({args:e,toolContext:t}){var y,I;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof k&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new me({appName:this.agent.name,agent:this.agent,artifactService:new je(t),sessionService:new ge,memoryService:new de,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),c;try{for(var d=b(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),f,g,h;f=!(g=await d.next()).done;f=!1){let C=g.value;C.actions.stateDelta&&t.state.update(C.actions.stateDelta),c=C}}catch(g){h=[g]}finally{try{f&&(g=d.return)&&await g.call(d)}finally{if(h)throw h[0]}}if(!((I=(y=c==null?void 0:c.content)==null?void 0:y.parts)!=null&&I.length))return"";let a=this.agent instanceof k&&this.agent.outputSchema,l=c.content.parts.map(C=>C.text).filter(C=>C).join("\n");return a?JSON.parse(l):l}};var kt=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 Pt=class extends H{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.toolsDict[this.name]=this,t.config=t.config||{},t.config.tools=t.config.tools||[],Ht(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(Qt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},$o=new Pt;var In="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",_t=class extends oe{constructor(e){super(he(E({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=In:e.description=In.trimStart(),e}};export{Lt as AgentTool,Q as BaseAgent,xe as BaseLlm,pe as BasePlugin,Ue as BaseSessionService,H as BaseTool,kt as BaseToolset,Ae as BuiltInCodeExecutor,W as CallbackContext,oe as FunctionTool,$o as GOOGLE_SEARCH,be as Gemini,Le as InMemoryArtifactService,de as InMemoryMemoryService,qe as InMemoryPolicyEngine,wt as InMemoryRunner,ge as InMemorySessionService,te as InvocationContext,Se as LLMRegistry,He as LiveRequestQueue,k as LlmAgent,Ut as LogLevel,Tt as LoggingPlugin,_t as LongRunningFunctionTool,At as LoopAgent,xt as ParallelAgent,ke as PluginManager,Rn as PolicyOutcome,Tn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,me as Runner,It as SecurityPlugin,St as SequentialAgent,R as State,dt as StreamingMode,ce as ToolConfirmation,ie as ToolContext,L as createEvent,J as createEventActions,Ke as createSession,qn as functionsExportedForTestingOnly,No as getAskUserConfirmationFunctionCalls,N as getFunctionCalls,z as getFunctionResponses,Ft as hasTrailingCodeExecutionResult,it as isBaseLlm,Ce as isFinalResponse,Fn as setLogLevel,Mn as stringifyContent,ot as version,$e as zodObjectToSchema};
7
+ var wn=Object.defineProperty,Pn=Object.defineProperties;var kn=Object.getOwnPropertyDescriptors;var Mt=Object.getOwnPropertySymbols;var Ln=Object.prototype.hasOwnProperty,_n=Object.prototype.propertyIsEnumerable;var Ze=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var Nt=(o,e,t)=>e in o?wn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,E=(o,e)=>{for(var t in e||(e={}))Ln.call(e,t)&&Nt(o,t,e[t]);if(Mt)for(var t of Mt(e))_n.call(e,t)&&Nt(o,t,e[t]);return o},he=(o,e)=>Pn(o,kn(e));var u=function(o,e){this[0]=o,this[1]=e},v=(o,e,t)=>{var n=(s,c,a,l)=>{try{var d=t[s](c),f=(c=d.value)instanceof u,g=d.done;Promise.resolve(f?c[0]:c).then(h=>f?n(s==="return"?s:"next",c[1]?{done:h.done,value:h.value}:h,a,l):a({value:h,done:g})).catch(h=>n("throw",h,a,l))}catch(h){l(h)}},r=s=>i[s]=c=>new Promise((a,l)=>n(s,c,a,l)),i={};return t=t.apply(o,e),i[Ze("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var b=(o,e,t)=>(e=o[Ze("asyncIterator")])?e.call(o):(o=o[Ze("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,c,a)=>(i=r.call(o,i),a=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:a}),c)))),t("next"),t("return"),e);import{trace as Gt}from"@opentelemetry/api";function J(o={}){return E({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function Ot(o,e){let t=J();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 P(o={}){return he(E({},o),{id:o.id||ze(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||J(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function Ce(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:N(o).length===0&&z(o).length===0&&!o.partial&&!Ft(o)}function N(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 z(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 Ft(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 Mn(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 Bt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function ze(){let o="";for(let e=0;e<8;e++)o+=Bt[Math.floor(Math.random()*Bt.length)];return o}var R=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=E(E({},this.delta),e),this.value=E(E({},this.value),e)}toRecord(){return E(E({},this.value),this.delta)}};R.APP_PREFIX="app:",R.USER_PREFIX="user:",R.TEMP_PREFIX="temp:";var V=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 R(this.invocationContext.session.state,{})}};var W=class extends V{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||J(),this._state=new R(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 _e(){return typeof window<"u"}var Le="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ve(){let o="";for(let e=0;e<Le.length;e++){let t=Math.random()*16|0;Le[e]==="x"?o+=t.toString(16):Le[e]==="y"?o+=(t&3|8).toString(16):o+=Le[e]}return o}function $t(o){return _e()?window.atob(o):Buffer.from(o,"base64").toString()}var We=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},te=class{constructor(e){this.invocationCostManager=new We;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-".concat(ve())}var Q=class{constructor(e){this.name=Nn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Bn(this),this.beforeAgentCallback=qt(e.beforeAgentCallback),this.afterAgentCallback=qt(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return v(this,null,function*(){let t=Gt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let c=this.createInvocationContext(e),a=yield new u(this.handleBeforeAgentCallback(c));if(a&&(yield a),c.endInvocation)return;try{for(var n=b(this.runAsyncImpl(c)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let d=i.value;yield d}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(c.endInvocation)return;let l=yield new u(this.handleAfterAgentCallback(c));l&&(yield l)}finally{t.end()}})}runLive(e){return v(this,null,function*(){let t=Gt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new te(he(E({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new W({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,P({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return P({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new W({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return P({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return P({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error('Agent "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function Nn(o){if(!On(o))throw new Error('Found invalid agent name: "'.concat(o,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.'));if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function On(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function Bn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function qt(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Kt}from"@google/genai";var Re=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(e," requires oauth2 in authCredential."));if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error("Auth Scheme ".concat(e," requires both clientId and clientSecret in authCredential.oauth2."));return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var ce=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var ie=class extends W{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new Re(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new Re(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new ce({hint:e,confirmed:!1,payload:t})}};var Ut=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Ut||{}),ye=1;function Fn(o){ye=o}var Ye=class{log(e,...t){if(!(e<ye))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error("Unsupported log level: ".concat(e))}}debug(...e){ye>0||console.debug(Me(0),...e)}info(...e){ye>1||console.info(Me(1),...e)}warn(...e){ye>2||console.warn(Me(2),...e)}error(...e){ye>3||console.error(Me(3),...e)}},$n={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Dn={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Gn="\x1B[0m";function Me(o){return"".concat(Dn[o],"[ADK ").concat($n[o],"]:").concat(Gn)}var p=new Ye;var Xe="adk-",Ne="adk_request_credential",Ee="adk_request_confirmation",qn={handleFunctionCallList:Oe};function Qe(){return"".concat(Xe).concat(ve())}function jt(o){let e=N(o);if(e)for(let t of e)t.id||(t.id=Qe())}function Vt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Xe)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Xe)&&(e.functionResponse.id=void 0)}function Zt(o,e){if(o in e)return o;let t=o.indexOf(":");if(t>0){let n=o.substring(0,t);if(n in e)return p.info('Resolved Gemini 3 function name "'.concat(o,'" to tool "').concat(n,'"')),n}}function zt(o,e){let t=new Set;for(let n of o){if(!n.name||!n.id)continue;let r=Zt(n.name,e);r&&e[r].isLongRunning&&t.add(n.id)}return t}function Wt(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:Ne,args:{function_call_id:i,auth_config:s},id:Qe()};n.add(c.id),t.push({functionCall:c})}if(t.length!==0)return P({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Yt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=N(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let d=(c=i.find(g=>g.id===a))!=null?c:void 0;if(!d)continue;let f={name:Ee,args:{originalFunctionCall:d,toolConfirmation:l},id:Qe()};r.add(f.id),n.push({functionCall:f})}if(n.length!==0)return P({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function Un(o,e,t){return p.debug("callToolAsync ".concat(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 c=N(e);return await Oe({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Oe({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var d,f,g;let c=[],a=e.filter(h=>!i||h.id&&i.has(h.id));for(let h of a){let y;s&&h.id&&(y=s[h.id]);let I=Kn({invocationContext:o,functionCall:h,toolsDict:t,toolConfirmation:y});if(!I){let D=h.args?JSON.stringify(h.args).substring(0,300):"(none)";p.warn('Function "'.concat(h.name,'" not found in toolsDict ')+"(".concat(Object.keys(t).length," tools registered). ")+"Args: ".concat(D));let ae=P({invocationId:o.invocationId,author:o.agent.name,content:Kt({functionResponse:{id:h.id||void 0,name:(d=h.name)!=null?d:"unknown",response:{error:"Function '".concat(h.name,"' is not available. ")+"Please use a different approach or pick from the tools already declared in your configuration."}}}),branch:o.branch});c.push(ae);continue}let{tool:C,toolContext:m}=I;p.debug("execute_tool ".concat(C.name));let S=(f=h.args)!=null?f:{},A=null,j;if(A=await o.pluginManager.runBeforeToolCallback({tool:C,toolArgs:S,toolContext:m}),A==null){for(let D of n)if(A=await D({tool:C,args:S,context:m}),A)break}if(A==null)try{A=await Un(C,S,m)}catch(D){let ae=JSON.stringify(S).substring(0,500);if(p.error('Tool execution error: "'.concat(C.name,'" threw ').concat(D instanceof Error?D.message:String(D),". Args: ").concat(ae)),D instanceof Error){let L=await o.pluginManager.runOnToolErrorCallback({tool:C,toolArgs:S,toolContext:m,error:D});L?A=L:j=D.message}else j=D}let w=await o.pluginManager.runAfterToolCallback({tool:C,toolArgs:S,toolContext:m,result:A});if(w==null){for(let D of r)if(w=await D({tool:C,args:S,context:m,response:A}),w)break}if(w!=null&&(A=w),C.isLongRunning&&!A)continue;j?A={error:j}:(typeof A!="object"||A==null)&&(A={result:A});let K=P({invocationId:o.invocationId,author:o.agent.name,content:Kt({functionResponse:{id:m.functionCallId,name:(g=h.name)!=null?g:C.name,response:A}}),actions:m.actions,branch:o.branch});p.debug("traceToolCall",{tool:C.name,args:S,functionResponseEvent:K.id}),c.push(K)}if(!c.length)return null;let l=jn(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Kn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){let r=e.name?Zt(e.name,t):void 0;if(!r)return null;let i=new ie({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[r],toolContext:i}}function jn(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 P({invocationId:t.invocationId,author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var He=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return v(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as vn}from"zod";var se=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 Vn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Be(o){let e=o.match(Vn);return e?e[1]:o}function Qt(o){return Be(o).startsWith("gemini-")}function Ht(o){return Be(o).startsWith("gemini-1")}function Jt(o){return Be(o).startsWith("gemini-2")}function en(o){let e=Be(o);return e.startsWith("gemini-3")&&e.includes("preview")}var Ae=class extends se{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Jt(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 ".concat(e.model))}};import{Language as Zn,Outcome as tn}from"@google/genai";function Y(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 f=0;f<o.parts.length;f++){let g=o.parts[f];if(g.executableCode&&(f===o.parts.length-1||!o.parts[f+1].codeExecutionResult))return o.parts=o.parts.slice(0,f+1),g.executableCode.code}let t=o.parts.filter(f=>f.text);if(!t.length)return"";let n=Y(t[0]),r=t.map(f=>f.text).join("\n"),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),c=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(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(Je(l)),l):""}function Je(o){return{text:o,executableCode:{code:o,language:Zn.PYTHON}}}function on(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:tn.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push("Code execution result:\n".concat(o.stdout,"\n")),o.outputFiles&&e.push("Saved artifacts:\n"+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:tn.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 et="_code_execution_context",tt="execution_session_id",le="processed_input_files",ue="_code_executor_input_files",fe="_code_executor_error_counts",nt="_code_execution_results",Ie=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(et))!=null?t:{},this.sessionState=e}getStateDelta(){return{[et]:Y(this.context)}}getExecutionId(){if(tt in this.context)return this.context[tt]}setExecutionId(e){this.context[tt]=e}getProcessedFileNames(){return le in this.context?this.context[le]:[]}addProcessedFileNames(e){le in this.context||(this.context[le]=[]),this.context[le].push(...e)}getInputFiles(){return ue in this.sessionState?this.sessionState.get(ue):[]}addInputFiles(e){ue in this.sessionState||this.sessionState.set(ue,[]),this.sessionState.get(ue).push(...e)}clearInputFiles(){ue in this.sessionState&&this.sessionState.set(ue,[]),le in this.context&&(this.context[le]=[])}getErrorCount(e){return fe in this.sessionState&&this.sessionState.get(fe)[e]||0}incrementErrorCount(e){fe in this.sessionState||this.sessionState.set(fe,{}),this.sessionState.get(fe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(fe in this.sessionState))return;let t=this.sessionState.get(fe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){nt in this.sessionState||this.sessionState.set(nt,{});let i=this.sessionState.get(nt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(et)||{}}};var ot="0.2.4";var zn="google-adk",Wn="gl-typescript",Yn="remote_reasoning_engine",Xn="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Qn(){let o="".concat(zn,"/").concat(ot);!_e()&&process.env[Xn]&&(o="".concat(o,"+").concat(Yn));let e="".concat(Wn,"/").concat(_e()?window.navigator.userAgent:process.version);return[o,e]}function sn(){return Qn()}var rt=Symbol("baseModel");function it(o){return typeof o=="object"&&o!==null&&rt in o&&o[rt]===!0}var an;an=rt;var xe=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."}]})}};xe.supportedModels=[];function we(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function cn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as at,FinishReason as to,GoogleGenAI as ct}from"@google/genai";function ln(){return Hn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Hn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(e)}var Fe=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}]}}}receive(){return v(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};import{FinishReason as Jn}from"@google/genai";function st(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}:n.finishReason===Jn.STOP?{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 no="https://aiplatform.googleapis.com/v1/publishers/google",be=class extends xe{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=en(e);let a=typeof process=="object",l=a?process.env.AI_STUDIO_API_KEY:void 0,d=!!l;this.apiEndpoint=c,!this.apiEndpoint&&a&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&!d&&(this.apiEndpoint=no,p.info("Using Gemini 3 preview endpoint: ".concat(this.apiEndpoint)));let f=!!n;if(!f&&a){let g=process.env.GOOGLE_GENAI_USE_VERTEXAI;g&&(f=g.toLowerCase()==="true"||g==="1")}if(d&&(f&&p.info("AI_STUDIO_API_KEY set \u2014 overriding Vertex AI mode to use AI Studio (generativelanguage.googleapis.com)"),f=!1,this.apiKey=l),this.isGemini3Preview&&f){let g=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);g?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),f=!1,this.apiKey=g):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=f,this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}generateContentAsync(e,t=!1){return v(this,null,function*(){var n,r,i,s,c,a,l,d,f,g,h,y,A,j,w,K,D;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=E(E({},e.config.httpOptions.headers),this.trackingHeaders)),t){let ae=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),L="",_,T="",O,F,G=null;try{for(var I=b(ae),C,m,S;C=!(m=yield new u(I.next())).done;C=!1){let ee=m.value;F=ee;let x=st(ee);O=x.usageMetadata;let Z=(s=(i=x.content)==null?void 0:i.parts)==null?void 0:s[0],Te=(a=(c=x.content)==null?void 0:c.parts)==null?void 0:a.some(q=>q.functionCall);if(this.isGemini3Preview&&((l=x.content)!=null&&l.parts)){for(let q of x.content.parts)if(q.thoughtSignature&&!_){_=q.thoughtSignature,p.debug("[Gemini3] Captured thoughtSignature (length: ".concat(_.length,")"));break}}if(Z!=null&&Z.text)"thought"in Z&&Z.thought?(L+=Z.text,"thoughtSignature"in Z&&Z.thoughtSignature&&(_=Z.thoughtSignature)):T+=Z.text,Te||(x.partial=!0),this.isGemini3Preview&&Te&&(L="",_=void 0,T="");else if((L||T)&&(!Z||!Z.inlineData))if(this.isGemini3Preview&&Te&&x.content){let q=[];if(L){let $={text:L,thought:!0};_&&($.thoughtSignature=_),q.push($)}if(T&&q.push(at(T)),!L&&_){for(let $ of x.content.parts||[])if($.functionCall&&!$.thoughtSignature){$.thoughtSignature=_;break}}x.content.parts=[...q,...x.content.parts||[]],L="",_=void 0,T=""}else{let q=[];if(L){let $={text:L,thought:!0};_&&($.thoughtSignature=_),q.push($)}T&&q.push(at(T)),yield{content:{role:"model",parts:q},usageMetadata:x.usageMetadata},L="",_=void 0,T=""}if(this.isGemini3Preview&&Te&&((d=x.content)!=null&&d.parts)&&!x.content.parts.some($=>$.thoughtSignature)&&_){for(let $ of x.content.parts)if($.functionCall){$.thoughtSignature=_;break}}if(Te){if(G&&((f=G.content)!=null&&f.parts)){let q=(((g=x.content)==null?void 0:g.parts)||[]).filter($=>$.functionCall||$.thoughtSignature);G.content.parts.push(...q),G.usageMetadata=x.usageMetadata}else G=x;continue}if(G){if(!((y=(h=x.content)==null?void 0:h.parts)!=null&&y.length))continue;yield G,G=null}yield x}}catch(m){S=[m]}finally{try{C&&(m=I.return)&&(yield new u(m.call(I)))}finally{if(S)throw S[0]}}if(G){if(this.isGemini3Preview&&((A=G.content)!=null&&A.parts)){let ee=G.content.parts.filter(x=>x.thoughtSignature).length;if(ee===0&&_){for(let x of G.content.parts)if(x.functionCall){x.thoughtSignature=_;break}}else ee===0&&p.warn("[Gemini3] No thoughtSignature on merged function call parts \u2014 may cause 400 on next request")}yield G,G=null}if((T||L)&&((w=(j=F==null?void 0:F.candidates)==null?void 0:j[0])==null?void 0:w.finishReason)===to.STOP){let ee=[];if(L){let x={text:L,thought:!0};_&&(x.thoughtSignature=_),ee.push(x)}T&&ee.push({text:T}),yield{content:{role:"model",parts:ee},usageMetadata:O}}}else{let ae=yield new u(this.apiClient.models.generateContent({model:(K=e.model)!=null?K:this.model,contents:e.contents,config:e.config})),L=st(ae);if(this.isGemini3Preview&&((D=L.content)!=null&&D.parts)){let _,T=!1;for(let F of L.content.parts)if(F.thoughtSignature){_=F.thoughtSignature,F.thought&&(T=!0);break}if(_&&!T){for(let F of L.content.parts)if(F.functionCall&&!F.thoughtSignature){F.thoughtSignature=_;break}}L.content.parts.some(F=>F.functionCall)&&L.content.parts.filter(G=>G.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield L}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=E(E({},this.trackingHeaders),this.headers);if(this.vertexai)this._apiClient=new ct({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: ".concat(this.apiEndpoint)),this.isGemini3Preview&&(t.apiVersion="",p.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new ct({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 ct({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:[at(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 Fe(t)}preprocessRequest(e){var t;if(this.apiBackend==="GEMINI_API"){if(e.config&&(e.config.labels=void 0),e.contents){for(let n of e.contents)if(n.parts)for(let r of n.parts)un(r.inlineData),un(r.fileData)}if((t=e.config)!=null&&t.tools&&e.config.tools.length>1){let n=e.config.tools.some(i=>"googleSearch"in i||"googleSearchRetrieval"in i),r=e.config.tools.some(i=>"functionDeclarations"in i);n&&r&&(p.warn("Gemini API (AI Studio) does not support combining built-in search tools with custom function declarations. Removing built-in search tool from this request."),e.config.tools=e.config.tools.filter(i=>!("googleSearch"in i)&&!("googleSearchRetrieval"in i)))}}}};be.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function un(o){o&&o.displayName&&(o.displayName=void 0)}var lt=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)}},X=class X{static newLlm(e){return new(X.resolve(e))({model:e})}static _register(e,t){X.llmRegistryDict.has(e)&&p.info("Updating LLM class for ".concat(e," from ").concat(X.llmRegistryDict.get(e)," to ").concat(t)),X.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)X._register(t,e)}static resolve(e){let t=X.resolveCache.get(e);if(t)return t;for(let[n,r]of X.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return X.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};X.llmRegistryDict=new Map,X.resolveCache=new lt(32);var Se=X;Se.register(be);var H=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=oo(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 oo(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as ro}from"@google/genai";import{ZodObject as io}from"zod";import{Type as U}from"@google/genai";import{z as M}from"zod";function fn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function ne(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 M.ZodFirstPartyTypeKind.ZodString:n.type=U.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 M.ZodFirstPartyTypeKind.ZodNumber:n.type=U.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=U.INTEGER);return r(n);case M.ZodFirstPartyTypeKind.ZodBoolean:return n.type=U.BOOLEAN,r(n);case M.ZodFirstPartyTypeKind.ZodArray:return n.type=U.ARRAY,n.items=ne(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case M.ZodFirstPartyTypeKind.ZodObject:return $e(o);case M.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=U.STRING;else if(i==="number")n.type=U.NUMBER;else if(i==="boolean")n.type=U.BOOLEAN;else if(e.value===null)n.type=U.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case M.ZodFirstPartyTypeKind.ZodEnum:return n.type=U.STRING,n.enum=e.values,r(n);case M.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=U.STRING,n.enum=Object.values(e.values),r(n);case M.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(ne),r(n);case M.ZodFirstPartyTypeKind.ZodOptional:return ne(e.innerType);case M.ZodFirstPartyTypeKind.ZodNullable:let s=ne(e.innerType);return r(s?E({anyOf:[s,{type:U.NULL}]},t&&{description:t}):E({type:U.NULL},t&&{description:t}));case M.ZodFirstPartyTypeKind.ZodDefault:let c=ne(e.innerType);return c&&(c.default=e.defaultValue()),c;case M.ZodFirstPartyTypeKind.ZodBranded:return ne(e.type);case M.ZodFirstPartyTypeKind.ZodReadonly:return ne(e.innerType);case M.ZodFirstPartyTypeKind.ZodNull:return n.type=U.NULL,r(n);case M.ZodFirstPartyTypeKind.ZodAny:case M.ZodFirstPartyTypeKind.ZodUnknown:return r(E({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function $e(o){if(o._def.typeName!==M.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let c=e[s],a=ne(c);a&&(t[s]=a);let l=c,d=!1;for(;l._def.typeName===M.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===M.ZodFirstPartyTypeKind.ZodDefault;)d=!0,l=l._def.innerType;d||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==M.ZodFirstPartyTypeKind.ZodNever?i=ne(r)||!0:i=o._def.unknownKeys==="passthrough",E({type:U.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function so(o){return o===void 0?{type:ro.OBJECT,properties:{}}:fn(o)?$e(o):o}var oe=class extends H{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:so(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof io&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var re=class{};function ut(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)||ao(a)||co(a)||n.push(gn(e,a)?lo(a):a);let r=uo(n);r=fo(r);let i=[];for(let a of r){let l=Y(a.content);Vt(l),i.push(l)}return i}function pn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||gn(e,r))return ut(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)===Ne||((n=r.functionResponse)==null?void 0:n.name)===Ne)return!0;return!1}function co(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)===Ee||((n=r.functionResponse)==null?void 0:n.name)===Ee)return!0;return!1}function gn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function lo(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:"[".concat(o.author,"] said: ").concat(a.text)});else if(a.functionCall){let l=dn(a.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(a.functionCall.name,"` with parameters: ").concat(l)})}else if(a.functionResponse){let l=dn(a.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(a.functionResponse.name,"` returned result: ").concat(l)})}else(c=e.parts)==null||c.push(a);return P({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=P(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 uo(o){if(o.length===0)return o;let e=o[o.length-1],t=z(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=N(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],d=N(l);if(d!=null&&d.length){for(let f of d)if(f.id&&n.has(f.id)){i=a;let g=new Set(d.map(y=>y.id).filter(y=>!!y));if(!Array.from(n).every(y=>g.has(y)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(g).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=g;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let a=i+1;a<o.length-1;a++){let l=o[a],d=z(l);d&&d.some(f=>f.id&&n.has(f.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(mn(s)),c}function fo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=z(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(z(n).length>0)continue;let r=N(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 dn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function ft(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),d=l.endsWith("?");if(d&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let g=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!g)throw new Error("Artifact ".concat(f," not found."));return String(g)}if(!mo(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(d)return"";throw new Error("Context variable not found: `".concat(l,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,c=o.matchAll(r);for(let a of c){i.push(o.slice(s,a.index));let l=await n(a);i.push(l),s=a.index+a[0].length}return i.push(o.slice(s)),i.join("")}var po=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function hn(o){return o===""||o===void 0?!1:po.test(o)}var go=[R.APP_PREFIX,R.USER_PREFIX,R.TEMP_PREFIX];function mo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?hn(o):go.includes(e[0]+":")?hn(e[1]):!1}var dt=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(dt||{});function Cn(o={}){return E({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ho(o.maxLlmCalls||500)},o)}function ho(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(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 yn="adk_agent_name";async function En(o,e){return o instanceof H?[o]:await o.getTools(e)}var pt=class extends re{runAsync(e,t){return v(this,null,function*(){var r;let n=e.agent;n instanceof k&&(t.model=n.canonicalModel.model,t.config=E({},(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))})}},Co=new pt,gt=class extends re{runAsync(e,t){return v(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),we(t,r)})}},vo=new gt,mt=class extends re{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof k)||!(n.rootAgent instanceof k))return;let r=n.rootAgent;if(r instanceof k&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new V(e))),c=i;s&&(c=yield new u(ft(i,new V(e)))),we(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new V(e))),c=i;s&&(c=yield new u(ft(i,new V(e)))),we(t,[c])}})}},yo=new mt,ht=class{runAsync(e,t){return v(this,null,function*(){let n=e.agent;!n||!(n instanceof k)||(n.includeContents==="default"?t.contents=ut(e.session.events,n.name,e.branch):t.contents=pn(e.session.events,n.name,e.branch))})}},Eo=new ht,Ct=class extends re{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new oe({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:vn.object({agentName:vn.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,n){return v(this,null,function*(){if(!(t.agent instanceof k))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;we(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new ie({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof k)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},Ao=new Ct,vt=class extends re{runAsync(e,t){return v(this,null,function*(){let n=e.agent;if(!(n instanceof k))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=z(a);if(!l)continue;let d=!1;for(let f of l){if(f.name!==Ee)continue;d=!0;let g=null;f.response&&Object.keys(f.response).length===1&&"response"in f.response?g=JSON.parse(f.response.response):f.response&&(g=new ce({hint:f.response.hint,payload:f.response.payload,confirmed:f.response.confirmed})),f.id&&g&&(i[f.id]=g)}if(d){s=c;break}}if(Object.keys(i).length!==0)for(let c=s-1;c>=0;c--){let a=r[c],l=N(a);if(!l)continue;let d={},f={};for(let I of l){if(!I.id||!(I.id in i))continue;let C=I.args;if(!C||!("originalFunctionCall"in C))continue;let m=C.originalFunctionCall;m.id&&(d[m.id]=i[I.id],f[m.id]=m)}if(Object.keys(d).length===0)continue;for(let I=r.length-1;I>s;I--){let C=r[I],m=z(C);if(m){for(let S of m)S.id&&S.id in d&&(delete d[S.id],delete f[S.id]);if(Object.keys(d).length===0)break}}if(Object.keys(d).length===0)continue;let g=yield new u(n.canonicalTools(new V(e))),h=Object.fromEntries(g.map(I=>[I.name,I])),y=yield new u(Oe({invocationContext:e,functionCalls:Object.values(f),toolsDict:h,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(d)),toolConfirmationDict:d}));y&&(yield y);return}})}},xo=new vt,yt=class extends re{runAsync(e,t){return v(this,null,function*(){if(e.agent instanceof k&&e.agent.codeExecutor){try{for(var n=b(So(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(e.agent.codeExecutor instanceof se)for(let c of t.contents){let a=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],l=rn(c,a,e.agent.codeExecutor.executionResultDelimiters)}}})}},De={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},bo="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",Et=class{runAsync(e,t){return v(this,null,function*(){if(!t.partial)try{for(var n=b(To(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}},$s=new Et;function So(o,e){return v(this,null,function*(){let t=o.agent;if(!(t instanceof k))return;let n=t.codeExecutor;if(!n||!(n instanceof se))return;if(n instanceof Ae){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new Ie(new R(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts){p.warn("[CodeExecutor] Pre-processor skipped: error count exceeded max retry attempts (".concat(n.errorRetryAttempts,") for invocation ").concat(o.invocationId));return}let i=Ro(r,e),s=new Set(r.getProcessedFileNames()),c=i.filter(a=>!s.has(a.name));for(let a of c){let l=Io(a);if(!l)return;let d={role:"model",parts:[{text:"Processing input file: `".concat(a.name,"`")},Je(l)]};e.contents.push(Y(d)),yield P({invocationId:o.invocationId,author:t.name,branch:o.branch,content:d});let f=An(o,r),g=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[a],executionId:f}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:g.stdout,resultStderr:g.stderr}),r.addProcessedFileNames([a.name]);let h=yield new u(xn(o,r,g));yield h,e.contents.push(Y(h.content))}})}function To(o,e){return v(this,null,function*(){let t=o.agent;if(!(t instanceof k))return;let n=t.codeExecutor;if(!n||!(n instanceof se)||!e||!e.content||n instanceof Ae)return;let r=new Ie(new R(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts){p.warn("[CodeExecutor] Post-processor skipped: error count exceeded max retry attempts (".concat(n.errorRetryAttempts,") for invocation ").concat(o.invocationId));return}let i=e.content,s=nn(i,n.codeBlockDelimiters);if(!s)return;yield P({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let c=An(o,r),a=yield new u(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 yield new u(xn(o,r,a)),e.content=null})}function Ro(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let c=0;c<s.parts.length;c++){let a=s.parts[c],l=(r=a.inlineData)==null?void 0:r.mimeType;if(!l||!a.inlineData||!De[l])continue;let d="data_".concat(i+1,"_").concat(c+1).concat(De[l].extension);a.text="\nAvailable file: `".concat(d,"`\n");let f={name:d,content:$t(a.inlineData.data),mimeType:l};n.has(d)||(o.addInputFiles([f]),t.push(f))}}return t}function An(o,e){var r;let t=o.agent;if(!(t instanceof k)||!((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:[on(t)]},r=J({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 P({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function Io(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"\n".concat(bo,"\n\n# Load the dataframe.\n").concat(t," = ").concat(n,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var wo=new yt,B=class B extends Q{constructor(e){var n,r,i,s,c,a,l,d,f;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(c=e.disallowTransferToPeers)!=null?c:!1,this.includeContents=(a=e.includeContents)!=null?a:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[Co,vo,yo,xo,Eo,wo],this.responseProcessors=(d=e.responseProcessors)!=null?d:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((f=this.subAgents)!=null&&f.length)||this.requestProcessors.push(Ao),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 ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, subAgents must be empty to disable agent transfer."));if(this.tools&&this.tools.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(it(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 B)return e.canonicalModel;e=e.parentAgent}throw new Error("No model found for ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await En(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return B.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return B.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return B.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return B.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){p.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!Ce(e)){p.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){p.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return v(this,null,function*(){var c,a;let t=0;for(;;){let l;try{for(var n=b(this.runOneStepAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let d=i.value;l=d,this.maybeSaveOutputToState(d),yield d}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(!l)break;if(l.errorCode&&!((a=(c=l.content)==null?void 0:c.parts)!=null&&a.length)){if(t++,t<=B.MAX_AGENT_LOOP_ERROR_RETRIES){p.warn("[runAsyncImpl] Error event (".concat(l.errorCode,": ").concat(l.errorMessage||"no message","), ")+"retrying agent loop (".concat(t,"/").concat(B.MAX_AGENT_LOOP_ERROR_RETRIES,")"));continue}p.error("[runAsyncImpl] Max agent-loop error retries exhausted for "+"".concat(l.errorCode,": ").concat(l.errorMessage||"no message"));break}if(t=0,Ce(l))break;if(l.partial){p.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return v(this,null,function*(){try{for(var t=b(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return v(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return v(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let C of this.requestProcessors)try{for(var r=b(C.runAsync(e,t)),i,s,c;i=!(s=yield new u(r.next())).done;i=!1){let m=s.value;yield m}}catch(s){c=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(c)throw c[0]}}for(let C of this.tools){let m=new ie({invocationContext:e}),S=yield new u(En(C,new V(e)));for(let A of S)yield new u(A.processLlmRequest({toolContext:m,llmRequest:t}))}if(e.endInvocation)return;let n=P({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var g=b(this.callLlmAsync(e,t,n)),h,y,I;h=!(y=yield new u(g.next())).done;h=!1){let C=y.value;try{try{for(var a=b(this.postprocess(e,t,C,n)),l,d,f;l=!(d=yield new u(a.next())).done;l=!1){let m=d.value;n.id=ze(),n.timestamp=new Date().getTime(),yield m}}catch(d){f=[d]}finally{try{l&&(d=a.return)&&(yield new u(d.call(a)))}finally{if(f)throw f[0]}}}catch(m){let S=m instanceof Error?m.message:String(m);p.error("Postprocess error: ".concat(S)),yield P({invocationId:e.invocationId,author:this.name,branch:e.branch,errorCode:"POSTPROCESS_ERROR",errorMessage:S})}}}catch(y){I=[y]}finally{try{h&&(y=g.return)&&(yield new u(y.call(g)))}finally{if(I)throw I[0]}}})}postprocess(e,t,n,r){return v(this,null,function*(){var y,I,C,m,S,A,j,w,K;for(let T of this.responseProcessors)try{for(var d=b(T.runAsync(e,n)),f,g,h;f=!(g=yield new u(d.next())).done;f=!1){let O=g.value;yield O}}catch(g){h=[g]}finally{try{f&&(g=d.return)&&(yield new u(g.call(d)))}finally{if(h)throw h[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;if(n.content&&!n.errorCode){if(!n.content.parts||n.content.parts.length===0){p.debug("[postprocess] Skipping LLM response with no parts (role=".concat(n.content.role,")"));return}if(n.content.parts.every(O=>!(O.functionCall||O.functionResponse||O.executableCode||O.codeExecutionResult||O.inlineData||O.fileData||"text"in O&&typeof O.text=="string"&&O.text.length>0))){p.debug("[postprocess] Skipping empty-content LLM response (".concat(n.content.parts.length," empty parts)"));return}}let i=P(E(E({},r),n));if(i.content){let T=N(i);T!=null&&T.length&&(jt(i),i.longRunningToolIds=Array.from(zt(T,t.toolsDict)),(y=i.content.parts)!=null&&y.some(F=>F.thoughtSignature)||p.warn("[postprocess] Function calls (".concat(T.length,") without thoughtSignature")))}if(p.debug("[postprocess] Yielding mergedEvent: role=".concat((I=i.content)==null?void 0:I.role,", parts=").concat((m=(C=i.content)==null?void 0:C.parts)==null?void 0:m.length,", ")+"hasFCs=".concat(((S=N(i))==null?void 0:S.length)||0,", partial=").concat(i.partial)),yield i,!((A=N(i))!=null&&A.length))return;let s=yield new u(Xt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let c=Wt(e,s);c&&(yield c);let a=Yt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),p.debug("[postprocess] Yielding functionResponseEvent: role=".concat((j=s.content)==null?void 0:j.role,", parts=").concat((K=(w=s.content)==null?void 0:w.parts)==null?void 0:K.length)),yield s;let l=s.actions.transferToAgent;if(l){let T=this.getAgentByName(e,l);try{for(var D=b(T.runAsync(e)),ae,L,_;ae=!(L=yield new u(D.next())).done;ae=!1){let O=L.value;yield O}}catch(L){_=[L]}finally{try{ae&&(L=D.return)&&(yield new u(L.call(D)))}finally{if(_)throw _[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return v(this,null,function*(){var s,c,a,l,d;let r=yield new u(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[yn]||(t.config.labels[yn]=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 I=((d=e.runConfig)==null?void 0:d.streamingMode)==="sse",C=B.LLM_TRANSIENT_ERROR_MAX_RETRIES;for(let m=0;m<=C;m++){if(m>0){let w=Math.min(B.LLM_TRANSIENT_ERROR_BASE_DELAY_MS*Math.pow(2,m-1),B.LLM_TRANSIENT_ERROR_MAX_DELAY_MS);p.warn("[callLlmAsync] Retrying LLM call after transient error "+"(attempt ".concat(m+1,"/").concat(C+1,"), waiting ").concat(w,"ms")),yield new u(new Promise(K=>setTimeout(K,w)))}let S=i.generateContentAsync(t,I),A=!1,j=!1;try{for(var f=b(this.runAndHandleError(S,e,t,n)),g,h,y;g=!(h=yield new u(f.next())).done;g=!1){let w=h.value;if(w.content&&(j=!0),w.errorCode&&B.LLM_RETRYABLE_ERROR_CODES.has(w.errorCode)&&!j&&m<C){A=!0,p.warn("[callLlmAsync] Transient LLM error: ".concat(w.errorCode)+"".concat(w.errorMessage?": "+w.errorMessage:"",", ")+"finishReason: ".concat(w.finishReason||"none",", ")+"usage: ".concat(JSON.stringify(w.usageMetadata)));break}let K=yield new u(this.handleAfterModelCallback(e,w,n));yield K!=null?K:w}}catch(h){y=[h]}finally{try{g&&(h=f.return)&&(yield new u(h.call(f)))}finally{if(y)throw y[0]}}if(!A)return}}})}async handleBeforeModelCallback(e,t,n){let r=new W({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 W({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}}runAndHandleError(e,t,n,r){return v(this,null,function*(){try{try{for(var i=b(e),s,c,a;s=!(c=yield new u(i.next())).done;s=!1){let l=c.value;yield l}}catch(c){a=[c]}finally{try{s&&(c=i.return)&&(yield new u(c.call(i)))}finally{if(a)throw a[0]}}}catch(l){let d=new W({invocationContext:t,eventActions:r.actions});if(l instanceof Error){let f=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:d,llmRequest:n,error:l}));if(f)yield f;else try{let g=JSON.parse(l.message);yield{errorCode:String(g.error.code),errorMessage:g.error.message}}catch(g){p.warn("LLM error message is not valid JSON, using raw message: ".concat(l.message.substring(0,200))),yield{errorCode:"UNKNOWN_ERROR",errorMessage:l.message}}}else throw p.error("Unknown error during response generation",l),l}})}};B.MAX_AGENT_LOOP_ERROR_RETRIES=2,B.LLM_TRANSIENT_ERROR_MAX_RETRIES=2,B.LLM_TRANSIENT_ERROR_BASE_DELAY_MS=1e3,B.LLM_TRANSIENT_ERROR_MAX_DELAY_MS=4e3,B.LLM_RETRYABLE_ERROR_CODES=new Set(["UNKNOWN_ERROR","UNEXPECTED_TOOL_CALL","MALFORMED_FUNCTION_CALL"]);var k=B;var At=class extends Q{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return v(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let c of this.subAgents){let a=!1;try{for(var n=b(c.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let l=i.value;yield l,l.actions.escalate&&(a=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a)return}t++}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var xt=class extends Q{runAsyncImpl(e){return v(this,null,function*(){let t=this.subAgents.map(c=>c.runAsync(Po(this,c,e)));try{for(var n=b(ko(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let c=i.value;yield c}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return v(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function Po(o,e,t){let n=new te(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function ko(o){return v(this,null,function*(){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=yield new u(Promise.race(e.values()));if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}})}var bt="task_completed",St=class extends Q{runAsyncImpl(e){return v(this,null,function*(){for(let s of this.subAgents)try{for(var t=b(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let c=r.value;yield c}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return v(this,null,function*(){for(let s of this.subAgents)s instanceof k&&((yield new u(s.canonicalTools(new V(e)))).some(l=>l.name===bt)||(s.tools.push(new oe({name:bt,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(bt," function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.")));for(let s of this.subAgents)try{for(var t=b(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let c=r.value;yield c}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var Pe=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=Ge(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let 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=Ge(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="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(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=Ge(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=Ge(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let c=[];for(let a=0;a<s.length;a++)c.push(a);return Promise.resolve(c)}};function Ge(o,e,t,n){return Lo(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function Lo(o){return o.startsWith("user:")}var de=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=bn(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=bn(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(g=>g.text).filter(g=>!!g).join(" "),d=_o(l);if(!d.size)continue;n.some(g=>d.has(g))&&r.memories.push({content:a.content,author:a.author,timestamp:Mo(a.timestamp)})}return r}};function bn(o,e){return"".concat(o,"/").concat(e)}function _o(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Mo(o){return new Date(o).toISOString()}var pe=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 Tt=class extends pe{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((n=e.agent.name)!=null?n:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(Ce(t)));let n=N(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=z(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");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: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var ke=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),p.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return p.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw 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 Tn="adk_request_confirmation",Rt="orcas_tool_call_security_check_states",Sn="This tool call needs external confirmation before completion.",Rn=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(Rn||{}),qe=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},It=class extends pe{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new qe}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(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: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:Sn};case"ALLOW":return;default:return}}};function No(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===Tn&&e.push(t.functionCall);return e}var Ue=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(R.TEMP_PREFIX)||(e.state[n]=r)}};function Ke(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var ge=class extends Ue{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Ke({id:i||ve(),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,Y(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=Y(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(Ke({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 ".concat(s,": ").concat(l))};if(!this.sessions[r])return c("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return c("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return c("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(R.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(R.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(R.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(R.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[R.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[R.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as Oo}from"@google/genai";import{trace as Bo}from"@opentelemetry/api";var me=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ke((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return v(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var a;i=Cn(i);let c=Bo.getTracer("gcp.vertex.agent").startSpan("invocation");try{let h=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!h)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof k){let m=this.agent.canonicalModel.model;if(!m.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(m," in agent: ").concat(this.agent.name))}let y=new te({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:Dt(),agent:this.agent,session:h,userContent:n,runConfig:i,pluginManager:this.pluginManager}),I=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:y}));if(I&&(n=I),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(y.invocationId,h.userId,h.id,n))),yield new u(this.sessionService.appendEvent({session:h,event:P({invocationId:y.invocationId,author:"user",actions:r?J({stateDelta:r}):void 0,content:n})}))}y.agent=this.determineAgentForResumption(h,this.agent);let C=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:y}));if(C){let m=P({invocationId:y.invocationId,author:"model",content:C});yield new u(this.sessionService.appendEvent({session:h,event:m})),yield m}else try{for(var l=b(y.agent.runAsync(y)),d,f,g;d=!(f=yield new u(l.next())).done;d=!1){let m=f.value;m.partial||(yield new u(this.sessionService.appendEvent({session:h,event:m})));let S=yield new u(this.pluginManager.runOnEventCallback({invocationContext:y,event:m}));S?yield S:yield m}}catch(f){g=[f]}finally{try{d&&(f=l.return)&&(yield new u(f.call(l)))}finally{if(g)throw g[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:y}))}finally{c.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_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:a,artifact:c}),r.parts[s]=Oo("Uploaded file: ".concat(a,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Fo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.debug("event[".concat(r,"]: author=").concat(e.events[r].author,", id=").concat(e.events[r].id));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){p.warn("Event from an unknown agent: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof k)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Fo(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=N(a);if(l){for(let d of l)if(d.id===t)return a}}return null}var wt=class extends me{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new Pe,sessionService:new ge,memoryService:new de})}};import{Type as Ve}from"@google/genai";var je=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 Pt=class extends H{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 k&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Ve.OBJECT,properties:{request:{type:Ve.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof k&&this.agent.outputSchema;e.response=t?{type:Ve.OBJECT}:{type:Ve.STRING}}return e}async runAsync({args:e,toolContext:t}){var y,I;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof k&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new me({appName:this.agent.name,agent:this.agent,artifactService:new je(t),sessionService:new ge,memoryService:new de,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),c;try{for(var d=b(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),f,g,h;f=!(g=await d.next()).done;f=!1){let C=g.value;C.actions.stateDelta&&t.state.update(C.actions.stateDelta),c=C}}catch(g){h=[g]}finally{try{f&&(g=d.return)&&await g.call(d)}finally{if(h)throw h[0]}}if(!((I=(y=c==null?void 0:c.content)==null?void 0:y.parts)!=null&&I.length))return"";let a=this.agent instanceof k&&this.agent.outputSchema,l=c.content.parts.map(C=>C.text).filter(C=>C).join("\n");return a?JSON.parse(l):l}};var kt=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 Lt=class extends H{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.toolsDict[this.name]=this,t.config=t.config||{},t.config.tools=t.config.tools||[],Ht(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(Qt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},$o=new Lt;var In="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",_t=class extends oe{constructor(e){super(he(E({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=In:e.description=In.trimStart(),e}};export{Pt as AgentTool,Q as BaseAgent,xe as BaseLlm,pe as BasePlugin,Ue as BaseSessionService,H as BaseTool,kt as BaseToolset,Ae as BuiltInCodeExecutor,W as CallbackContext,oe as FunctionTool,$o as GOOGLE_SEARCH,be as Gemini,Pe as InMemoryArtifactService,de as InMemoryMemoryService,qe as InMemoryPolicyEngine,wt as InMemoryRunner,ge as InMemorySessionService,te as InvocationContext,Se as LLMRegistry,He as LiveRequestQueue,k as LlmAgent,Ut as LogLevel,Tt as LoggingPlugin,_t as LongRunningFunctionTool,At as LoopAgent,xt as ParallelAgent,ke as PluginManager,Rn as PolicyOutcome,Tn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,me as Runner,It as SecurityPlugin,St as SequentialAgent,R as State,dt as StreamingMode,ce as ToolConfirmation,ie as ToolContext,P as createEvent,J as createEventActions,Ke as createSession,qn as functionsExportedForTestingOnly,No as getAskUserConfirmationFunctionCalls,N as getFunctionCalls,z as getFunctionResponses,Ft as hasTrailingCodeExecutionResult,it as isBaseLlm,Ce as isFinalResponse,Fn as setLogLevel,Mn as stringifyContent,ot as version,$e as zodObjectToSchema};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Google LLC