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