@paean-ai/adk 0.2.6 → 0.2.8
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/index.js +11 -11
- package/dist/cjs/index.js.map +3 -3
- package/dist/cjs/models/google_llm.js +57 -10
- package/dist/esm/index.js +11 -11
- package/dist/esm/index.js.map +3 -3
- package/dist/esm/models/google_llm.js +62 -11
- package/dist/web/index.js +1 -1
- package/dist/web/index.js.map +3 -3
- package/dist/web/models/google_llm.js +62 -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 Et}from"@opentelemetry/api";function M(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function ht(o,e){let t=M();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function y(o={}){return{...o,id:o.id||we(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||M(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function Q(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:b(o).length===0&&P(o).length===0&&!o.partial&&!vt(o)}function b(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function P(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 vt(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 un(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 Ct="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function we(){let o="";for(let e=0;e<8;e++)o+=Ct[Math.floor(Math.random()*Ct.length)];return o}var C=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};C.APP_PREFIX="app:",C.USER_PREFIX="user:",C.TEMP_PREFIX="temp:";var R=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new C(this.invocationContext.session.state,{})}};var w=class extends R{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||M(),this._state=new C(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function de(){return typeof window<"u"}var fe="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function X(){let o="";for(let e=0;e<fe.length;e++){let t=Math.random()*16|0;fe[e]==="x"?o+=t.toString(16):fe[e]==="y"?o+=(t&3|8).toString(16):o+=fe[e]}return o}function yt(o){return de()?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`)}},O=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 xt(){return`e-${X()}`}var _=class{constructor(e){this.name=fn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=pn(this),this.beforeAgentCallback=At(e.beforeAgentCallback),this.afterAgentCallback=At(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=Et.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=Et.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 O({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return y({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return y({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function fn(o){if(!dn(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 dn(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function pn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function At(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as vn}from"@google/genai";var re=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${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 U=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var $=class extends w{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new re(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new re(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new U({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||{}),H=1;function mn(o){H=o}var Le=class{log(e,...t){if(!(e<H))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){H>0||console.debug(pe(0),...e)}info(...e){H>1||console.info(pe(1),...e)}warn(...e){H>2||console.warn(pe(2),...e)}error(...e){H>3||console.error(pe(3),...e)}},gn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},hn={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Cn="\x1B[0m";function pe(o){return`${hn[o]}[ADK ${gn[o]}]:${Cn}`}var p=new Le;var _e="adk-",me="adk_request_credential",J="adk_request_confirmation",yn={handleFunctionCallList:ge};function Me(){return`${_e}${X()}`}function Tt(o){let e=b(o);if(e)for(let t of e)t.id||(t.id=Me())}function St(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(_e)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(_e)&&(e.functionResponse.id=void 0)}function Rt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function It(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:me,args:{function_call_id:i,auth_config:s},id:Me()};n.add(c.id),t.push({functionCall:c})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Pt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=b(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(c=i.find(d=>d.id===a))!=null?c:void 0;if(!f)continue;let u={name:J,args:{originalFunctionCall:f,toolConfirmation:l},id:Me()};r.add(u.id),n.push({functionCall:u})}return y({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function xn(o,e,t){return p.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function wt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let c=b(e);return await ge({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function ge({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let c=[],a=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of a){let d;s&&u.id&&(d=s[u.id]);let{tool:g,toolContext:x}=En({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});p.debug(`execute_tool ${g.name}`);let h=(f=u.args)!=null?f:{},m=null,E;if(m=await o.pluginManager.runBeforeToolCallback({tool:g,toolArgs:h,toolContext:x}),m==null){for(let G of n)if(m=await G({tool:g,args:h,context:x}),m)break}if(m==null)try{m=await xn(g,h,x)}catch(G){if(G instanceof Error){let gt=await o.pluginManager.runOnToolErrorCallback({tool:g,toolArgs:h,toolContext:x,error:G});gt?m=gt:E=G.message}else E=G}let S=await o.pluginManager.runAfterToolCallback({tool:g,toolArgs:h,toolContext:x,result:m});if(S==null){for(let G of r)if(S=await G({tool:g,args:h,context:x,response:m}),S)break}if(S!=null&&(m=S),g.isLongRunning&&!m)continue;E?m={error:E}:(typeof m!="object"||m==null)&&(m={result:m});let mt=y({invocationId:o.invocationId,author:o.agent.name,content:vn({functionResponse:{id:x.functionCallId,name:g.name,response:m}}),actions:x.actions,branch:o.branch});p.debug("traceToolCall",{tool:g.name,args:h,functionResponseEvent:mt.id}),c.push(mt)}if(!c.length)return null;let l=An(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function En({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new $({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function An(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=ht(n);return y({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Oe=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};import{z as Xt}from"zod";var q=class{constructor(){this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var bn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function he(o){let e=o.match(bn);return e?e[1]:o}function kt(o){return he(o).startsWith("gemini-")}function Lt(o){return he(o).startsWith("gemini-1")}function _t(o){return he(o).startsWith("gemini-2")}function Mt(o){let e=he(o);return e.startsWith("gemini-3")&&e.includes("preview")}var ee=class extends q{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&_t(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 Tn,Outcome as Ot}from"@google/genai";function k(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Nt(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let d=o.parts[u];if(d.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),d.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=k(t[0]),r=t.map(u=>u.text).join(`
|
|
8
|
-
`),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[1]).join("|"),c=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:a,codeStr:l}=(c==null?void 0:c.groups)||{};return l?(o.parts=[],a&&(n.text=a,o.parts.push(n)),o.parts.push(
|
|
7
|
+
import{trace as Tt}from"@opentelemetry/api";function B(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function yt(o,e){let t=B();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||Me(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||B(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function ee(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:b(o).length===0&&L(o).length===0&&!o.partial&&!Et(o)}function b(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function L(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 Et(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 pn(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 xt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Me(){let o="";for(let e=0;e<8;e++)o+=xt[Math.floor(Math.random()*xt.length)];return o}var v=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};v.APP_PREFIX="app:",v.USER_PREFIX="user:",v.TEMP_PREFIX="temp:";var P=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new v(this.invocationContext.session.state,{})}};var _=class extends P{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||B(),this._state=new v(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function he(){return typeof window<"u"}var ge="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function te(){let o="";for(let e=0;e<ge.length;e++){let t=Math.random()*16|0;ge[e]==="x"?o+=t.toString(16):ge[e]==="y"?o+=(t&3|8).toString(16):o+=ge[e]}return o}function At(o){return he()?window.atob(o):Buffer.from(o,"base64").toString()}var Oe=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},D=class{constructor(e){this.invocationCostManager=new Oe;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 bt(){return`e-${te()}`}var N=class{constructor(e){this.name=mn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=hn(this),this.beforeAgentCallback=St(e.beforeAgentCallback),this.afterAgentCallback=St(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=Tt.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=Tt.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new D({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new _({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,x({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return x({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new _({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return x({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return x({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function mn(o){if(!gn(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 gn(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function hn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function St(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as En}from"@google/genai";var ce=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var Z=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var j=class extends _{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new ce(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ce(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new Z({hint:e,confirmed:!1,payload:t})}};var Rt=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Rt||{}),ne=1;function Cn(o){ne=o}var Ne=class{log(e,...t){if(!(e<ne))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){ne>0||console.debug(Ce(0),...e)}info(...e){ne>1||console.info(Ce(1),...e)}warn(...e){ne>2||console.warn(Ce(2),...e)}error(...e){ne>3||console.error(Ce(3),...e)}},vn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},yn={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},xn="\x1B[0m";function Ce(o){return`${yn[o]}[ADK ${vn[o]}]:${xn}`}var p=new Ne;var Be="adk-",ve="adk_request_credential",oe="adk_request_confirmation",An={handleFunctionCallList:ye};function Fe(){return`${Be}${te()}`}function It(o){let e=b(o);if(e)for(let t of e)t.id||(t.id=Fe())}function Pt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Be)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Be)&&(e.functionResponse.id=void 0)}function wt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function kt(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:ve,args:{function_call_id:i,auth_config:s},id:Fe()};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 Lt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,c;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=b(e);for(let[a,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(c=i.find(d=>d.id===a))!=null?c:void 0;if(!f)continue;let u={name:oe,args:{originalFunctionCall:f,toolConfirmation:l},id:Fe()};r.add(u.id),n.push({functionCall:u})}return x({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function bn(o,e,t){return p.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function _t({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let c=b(e);return await ye({invocationContext:o,functionCalls:c,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function ye({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let c=[],a=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of a){let d;s&&u.id&&(d=s[u.id]);let{tool:C,toolContext:E}=Tn({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});p.debug(`execute_tool ${C.name}`);let g=(f=u.args)!=null?f:{},m=null,h;if(m=await o.pluginManager.runBeforeToolCallback({tool:C,toolArgs:g,toolContext:E}),m==null){for(let T of n)if(m=await T({tool:C,args:g,context:E}),m)break}if(m==null)try{m=await bn(C,g,E)}catch(T){if(T instanceof Error){let R=await o.pluginManager.runOnToolErrorCallback({tool:C,toolArgs:g,toolContext:E,error:T});R?m=R:h=T.message}else h=T}let I=await o.pluginManager.runAfterToolCallback({tool:C,toolArgs:g,toolContext:E,result:m});if(I==null){for(let T of r)if(I=await T({tool:C,args:g,context:E,response:m}),I)break}if(I!=null&&(m=I),C.isLongRunning&&!m)continue;h?m={error:h}:(typeof m!="object"||m==null)&&(m={result:m});let V=x({invocationId:o.invocationId,author:o.agent.name,content:En({functionResponse:{id:E.functionCallId,name:C.name,response:m}}),actions:E.actions,branch:o.branch});p.debug("traceToolCall",{tool:C.name,args:g,functionResponseEvent:V.id}),c.push(V)}if(!c.length)return null;let l=Sn(c);return c.length>1&&(p.debug("execute_tool (merged)"),p.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Tn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new j({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Sn(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=yt(n);return x({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var De=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 en}from"zod";var K=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 Rn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function xe(o){let e=o.match(Rn);return e?e[1]:o}function Mt(o){return xe(o).startsWith("gemini-")}function Ot(o){return xe(o).startsWith("gemini-1")}function Nt(o){return xe(o).startsWith("gemini-2")}function Bt(o){let e=xe(o);return e.startsWith("gemini-3")&&e.includes("preview")}var re=class extends K{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Nt(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 In,Outcome as Ft}from"@google/genai";function M(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Dt(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let u=0;u<o.parts.length;u++){let d=o.parts[u];if(d.executableCode&&(u===o.parts.length-1||!o.parts[u+1].codeExecutionResult))return o.parts=o.parts.slice(0,u+1),d.executableCode.code}let t=o.parts.filter(u=>u.text);if(!t.length)return"";let n=M(t[0]),r=t.map(u=>u.text).join(`
|
|
8
|
+
`),i=e.map(u=>u[0]).join("|"),s=e.map(u=>u[1]).join("|"),c=new RegExp(`?<prefix>.*?)(${i})(?<codeStr>.*?)(${s})(?<suffix>.*?)$`,"s").exec(r),{prefix:a,codeStr:l}=(c==null?void 0:c.groups)||{};return l?(o.parts=[],a&&(n.text=a,o.parts.push(n)),o.parts.push(Ge(l)),l):""}function Ge(o){return{text:o,executableCode:{code:o,language:In.PYTHON}}}function Gt(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:Ft.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:Ft.OUTCOME_OK}}}function $t(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 $e="_code_execution_context",qe="execution_session_id",z="processed_input_files",W="_code_executor_input_files",Y="_code_executor_error_counts",Ue="_code_execution_results",le=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get($e))!=null?t:{},this.sessionState=e}getStateDelta(){return{[$e]:M(this.context)}}getExecutionId(){if(qe in this.context)return this.context[qe]}setExecutionId(e){this.context[qe]=e}getProcessedFileNames(){return z in this.context?this.context[z]:[]}addProcessedFileNames(e){z in this.context||(this.context[z]=[]),this.context[z].push(...e)}getInputFiles(){return W in this.sessionState?this.sessionState.get(W):[]}addInputFiles(e){W in this.sessionState||this.sessionState.set(W,[]),this.sessionState.get(W).push(...e)}clearInputFiles(){W in this.sessionState&&this.sessionState.set(W,[]),z in this.context&&(this.context[z]=[])}getErrorCount(e){return Y in this.sessionState&&this.sessionState.get(Y)[e]||0}incrementErrorCount(e){Y in this.sessionState||this.sessionState.set(Y,{}),this.sessionState.get(Y)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(Y in this.sessionState))return;let t=this.sessionState.get(Y);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){Ue in this.sessionState||this.sessionState.set(Ue,{});let i=this.sessionState.get(Ue);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get($e)||{}}};var je="0.2.4";var Pn="google-adk",wn="gl-typescript",kn="remote_reasoning_engine",Ln="GOOGLE_CLOUD_AGENT_ENGINE_ID";function _n(){let o=`${Pn}/${je}`;!he()&&process.env[Ln]&&(o=`${o}+${kn}`);let e=`${wn}/${he()?window.navigator.userAgent:process.version}`;return[o,e]}function qt(){return _n()}var Ke=Symbol("baseModel");function Ve(o){return typeof o=="object"&&o!==null&&Ke in o&&o[Ke]===!0}var Ut;Ut=Ke;var ie=class{constructor({model:e}){this[Ut]=!0;this.model=e}get trackingHeaders(){let t=qt().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."}]})}};ie.supportedModels=[];function ue(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 $t(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as Ut,FinishReason as _n,GoogleGenAI as je}from"@google/genai";function qt(){return kn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function kn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Ce=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 Ue(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 Mn="https://aiplatform.googleapis.com/v1/publishers/google",ne=class extends te{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=Mt(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=Mn,p.info(`Using Gemini 3 preview endpoint: ${this.apiEndpoint}`));let l=!!n;if(!l&&a){let f=process.env.GOOGLE_GENAI_USE_VERTEXAI;f&&(l=f.toLowerCase()==="true"||f==="1")}if(this.isGemini3Preview&&l){let f=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);f?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,c,a,l;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 f=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),u="",d="",g,x;for await(let h of f){x=h;let m=Ue(h);g=m.usageMetadata;let E=(s=(i=m.content)==null?void 0:i.parts)==null?void 0:s[0];if(E!=null&&E.text)"thought"in E&&E.thought?u+=E.text:d+=E.text,m.partial=!0;else if((u||d)&&(!E||!E.inlineData)){let S=[];u&&S.push({text:u,thought:!0}),d&&S.push(Ut(d)),yield{content:{role:"model",parts:S},usageMetadata:m.usageMetadata},u="",d=""}yield m}if((d||u)&&((a=(c=x==null?void 0:x.candidates)==null?void 0:c[0])==null?void 0:a.finishReason)===_n.STOP){let h=[];u&&h.push({text:u,thought:!0}),d&&h.push({text:d}),yield{content:{role:"model",parts:h},usageMetadata:g}}}else{let f=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield Ue(f)}}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:[Ut(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 Ce(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)jt(n.inlineData),jt(n.fileData)}}};ne.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function jt(o){o&&o.displayName&&(o.displayName=void 0)}var Ke=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)}},L=class L{static newLlm(e){return new(L.resolve(e))({model:e})}static _register(e,t){L.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${L.llmRegistryDict.get(e)} to ${t}`),L.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)L._register(t,e)}static resolve(e){let t=L.resolveCache.get(e);if(t)return t;for(let[n,r]of L.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return L.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};L.llmRegistryDict=new Map,L.resolveCache=new Ke(32);var oe=L;oe.register(ne);var I=class{constructor(e){var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=On(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 On(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Nn}from"@google/genai";import{ZodObject as Bn}from"zod";import{Type as T}from"@google/genai";import{z as A}from"zod";function Kt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function N(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 A.ZodFirstPartyTypeKind.ZodString:n.type=T.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 A.ZodFirstPartyTypeKind.ZodNumber:n.type=T.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=T.INTEGER);return r(n);case A.ZodFirstPartyTypeKind.ZodBoolean:return n.type=T.BOOLEAN,r(n);case A.ZodFirstPartyTypeKind.ZodArray:return n.type=T.ARRAY,n.items=N(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case A.ZodFirstPartyTypeKind.ZodObject:return ve(o);case A.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=T.STRING;else if(i==="number")n.type=T.NUMBER;else if(i==="boolean")n.type=T.BOOLEAN;else if(e.value===null)n.type=T.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case A.ZodFirstPartyTypeKind.ZodEnum:return n.type=T.STRING,n.enum=e.values,r(n);case A.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=T.STRING,n.enum=Object.values(e.values),r(n);case A.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(N),r(n);case A.ZodFirstPartyTypeKind.ZodOptional:return N(e.innerType);case A.ZodFirstPartyTypeKind.ZodNullable:let s=N(e.innerType);return r(s?{anyOf:[s,{type:T.NULL}],...t&&{description:t}}:{type:T.NULL,...t&&{description:t}});case A.ZodFirstPartyTypeKind.ZodDefault:let c=N(e.innerType);return c&&(c.default=e.defaultValue()),c;case A.ZodFirstPartyTypeKind.ZodBranded:return N(e.type);case A.ZodFirstPartyTypeKind.ZodReadonly:return N(e.innerType);case A.ZodFirstPartyTypeKind.ZodNull:return n.type=T.NULL,r(n);case A.ZodFirstPartyTypeKind.ZodAny:case A.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function ve(o){if(o._def.typeName!==A.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let c=e[s],a=N(c);a&&(t[s]=a);let l=c,f=!1;for(;l._def.typeName===A.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===A.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==A.ZodFirstPartyTypeKind.ZodNever?i=N(r)||!0:i=o._def.unknownKeys==="passthrough",{type:T.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Fn(o){return o===void 0?{type:Nn.OBJECT,properties:{}}:Kt(o)?ve(o):o}var B=class extends I{constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:Fn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Bn&&(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 F=class{};function Ve(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)||Dn(a)||Gn(a)||n.push(zt(e,a)?$n(a):a);let r=qn(n);r=Un(r);let i=[];for(let a of r){let l=k(a.content);St(l),i.push(l)}return i}function Zt(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||zt(e,r))return Ve(o.slice(n),e,t)}return[]}function Dn(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)===me||((n=r.functionResponse)==null?void 0:n.name)===me)return!0;return!1}function Gn(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)===J||((n=r.functionResponse)==null?void 0:n.name)===J)return!0;return!1}function zt(o,e){return!!o&&e.author!==o&&e.author!=="user"}function $n(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=Vt(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=Vt(a.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${a.functionResponse.name}\` returned result: ${l}`})}else(c=e.parts)==null||c.push(a);return y({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function Wt(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=y(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let c=s.functionResponse.id;c in n?t[n[c]]=s:(t.push(s),n[c]=t.length-1)}else t.push(s)}return e}function qn(o){if(o.length===0)return o;let e=o[o.length-1],t=P(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(a=>!!a.id).map(a=>a.id)),r=o.at(-2);if(r){let a=b(r);if(a){for(let l of a)if(l.id&&n.has(l.id))return o}}let i=-1;for(let a=o.length-2;a>=0;a--){let l=o[a],f=b(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=a;let d=new Set(f.map(x=>x.id).filter(x=>!!x));if(!Array.from(n).every(x=>d.has(x)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let a=i+1;a<o.length-1;a++){let l=o[a],f=P(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(Wt(s)),c}function Un(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=P(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(P(n).length>0)continue;let r=b(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let c=s.id;c&&e.has(c)&&i.add(e.get(c))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let c=Array.from(i).sort((a,l)=>a-l).map(a=>o[a]);t.push(Wt(c))}}else t.push(n)}return t}function Vt(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Ze(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!Vn(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,c=o.matchAll(r);for(let a of c){i.push(o.slice(s,a.index));let l=await n(a);i.push(l),s=a.index+a[0].length}return i.push(o.slice(s)),i.join("")}var jn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Yt(o){return o===""||o===void 0?!1:jn.test(o)}var Kn=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function Vn(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Yt(o):Kn.includes(e[0]+":")?Yt(e[1]):!1}var ze=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(ze||{});function Qt(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Zn(o.maxLlmCalls||500),...o}}function Zn(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 Ht="adk_agent_name";async function Jt(o,e){return o instanceof I?[o]:await o.getTools(e)}var We=class extends F{async*runAsync(e,t){var r;let n=e.agent;n instanceof v&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&$t(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))}},zn=new We,Ye=class extends F{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}"`),se(t,r)}},Wn=new Ye,Qe=class extends F{async*runAsync(e,t){let n=e.agent;if(!(n instanceof v)||!(n.rootAgent instanceof v))return;let r=n.rootAgent;if(r instanceof v&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new R(e)),c=i;s&&(c=await Ze(i,new R(e))),se(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new R(e)),c=i;s&&(c=await Ze(i,new R(e))),se(t,[c])}}},Yn=new Qe,Xe=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof v)||(n.includeContents==="default"?t.contents=Ve(e.session.events,n.name,e.branch):t.contents=Zt(e.session.events,n.name,e.branch))}},Qn=new Xe,He=class extends F{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new B({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:Xt.object({agentName:Xt.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 v))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;se(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new $({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
17
|
+
`+t:o.config.systemInstruction=t}function jt(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as Vt,FinishReason as Nn,GoogleGenAI as ze}from"@google/genai";function Kt(){return Mn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Mn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Ee=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 Ze(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 Bn="https://aiplatform.googleapis.com/v1/publishers/google",se=class extends ie{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=Bt(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=Bn,p.info(`Using Gemini 3 preview endpoint: ${this.apiEndpoint}`));let l=!!n;if(!l&&a){let f=process.env.GOOGLE_GENAI_USE_VERTEXAI;f&&(l=f.toLowerCase()==="true"||f==="1")}if(this.isGemini3Preview&&l){let f=t||(a?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);f?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(a&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),a&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&a&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,c,a,l,f,u,d,C;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 E=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),g="",m,h="",I,V;for await(let T of E){V=T;let R=Ze(T);I=R.usageMetadata;let k=(s=(i=R.content)==null?void 0:i.parts)==null?void 0:s[0];if(k!=null&&k.text)"thought"in k&&k.thought?(g+=k.text,"thoughtSignature"in k&&k.thoughtSignature&&(m=k.thoughtSignature)):h+=k.text,R.partial=!0;else if((g||h)&&(!k||!k.inlineData)){let F=[];if(g){let vt={text:g,thought:!0};m&&(vt.thoughtSignature=m),F.push(vt)}h&&F.push(Vt(h)),yield{content:{role:"model",parts:F},usageMetadata:R.usageMetadata},g="",h=""}if(this.isGemini3Preview&&m&&((c=R.content)!=null&&c.parts))for(let F of R.content.parts)F.functionCall&&!F.thoughtSignature&&(F.thoughtSignature=m);yield R,(l=(a=R.content)==null?void 0:a.parts)!=null&&l.some(F=>F.functionCall)&&(m=void 0)}if((h||g)&&((u=(f=V==null?void 0:V.candidates)==null?void 0:f[0])==null?void 0:u.finishReason)===Nn.STOP){let T=[];if(g){let R={text:g,thought:!0};m&&(R.thoughtSignature=m),T.push(R)}h&&T.push({text:h}),yield{content:{role:"model",parts:T},usageMetadata:I}}}else{let E=await this.apiClient.models.generateContent({model:(d=e.model)!=null?d:this.model,contents:e.contents,config:e.config}),g=Ze(E);if(this.isGemini3Preview&&((C=g.content)!=null&&C.parts)){let m;for(let h of g.content.parts)if(h.thought&&h.thoughtSignature){m=h.thoughtSignature;break}if(m)for(let h of g.content.parts)h.functionCall&&!h.thoughtSignature&&(h.thoughtSignature=m)}yield g}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new ze({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 ze({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 ze({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:[Vt(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 Ee(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)Zt(n.inlineData),Zt(n.fileData)}}};se.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Zt(o){o&&o.displayName&&(o.displayName=void 0)}var We=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},O=class O{static newLlm(e){return new(O.resolve(e))({model:e})}static _register(e,t){O.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${O.llmRegistryDict.get(e)} to ${t}`),O.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)O._register(t,e)}static resolve(e){let t=O.resolveCache.get(e);if(t)return t;for(let[n,r]of O.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return O.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};O.llmRegistryDict=new Map,O.resolveCache=new We(32);var ae=O;ae.register(se);var w=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=Fn(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 Kt()}};function Fn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Dn}from"@google/genai";import{ZodObject as Gn}from"zod";import{Type as S}from"@google/genai";import{z as A}from"zod";function zt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function G(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case A.ZodFirstPartyTypeKind.ZodString:n.type=S.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 A.ZodFirstPartyTypeKind.ZodNumber:n.type=S.NUMBER;for(let a of e.checks||[])a.kind==="min"?n.minimum=a.value:a.kind==="max"?n.maximum=a.value:a.kind==="int"&&(n.type=S.INTEGER);return r(n);case A.ZodFirstPartyTypeKind.ZodBoolean:return n.type=S.BOOLEAN,r(n);case A.ZodFirstPartyTypeKind.ZodArray:return n.type=S.ARRAY,n.items=G(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case A.ZodFirstPartyTypeKind.ZodObject:return Ae(o);case A.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=S.STRING;else if(i==="number")n.type=S.NUMBER;else if(i==="boolean")n.type=S.BOOLEAN;else if(e.value===null)n.type=S.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case A.ZodFirstPartyTypeKind.ZodEnum:return n.type=S.STRING,n.enum=e.values,r(n);case A.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=S.STRING,n.enum=Object.values(e.values),r(n);case A.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(G),r(n);case A.ZodFirstPartyTypeKind.ZodOptional:return G(e.innerType);case A.ZodFirstPartyTypeKind.ZodNullable:let s=G(e.innerType);return r(s?{anyOf:[s,{type:S.NULL}],...t&&{description:t}}:{type:S.NULL,...t&&{description:t}});case A.ZodFirstPartyTypeKind.ZodDefault:let c=G(e.innerType);return c&&(c.default=e.defaultValue()),c;case A.ZodFirstPartyTypeKind.ZodBranded:return G(e.type);case A.ZodFirstPartyTypeKind.ZodReadonly:return G(e.innerType);case A.ZodFirstPartyTypeKind.ZodNull:return n.type=S.NULL,r(n);case A.ZodFirstPartyTypeKind.ZodAny:case A.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Ae(o){if(o._def.typeName!==A.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let c=e[s],a=G(c);a&&(t[s]=a);let l=c,f=!1;for(;l._def.typeName===A.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===A.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==A.ZodFirstPartyTypeKind.ZodNever?i=G(r)||!0:i=o._def.unknownKeys==="passthrough",{type:S.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function $n(o){return o===void 0?{type:Dn.OBJECT,properties:{}}:zt(o)?Ae(o):o}var $=class extends w{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:$n(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Gn&&(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 q=class{};function Ye(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)||Un(a)||n.push(Qt(e,a)?jn(a):a);let r=Kn(n);r=Vn(r);let i=[];for(let a of r){let l=M(a.content);Pt(l),i.push(l)}return i}function Yt(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Qt(e,r))return Ye(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)===ve||((n=r.functionResponse)==null?void 0:n.name)===ve)return!0;return!1}function Un(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)===oe||((n=r.functionResponse)==null?void 0:n.name)===oe)return!0;return!1}function Qt(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=Wt(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=Wt(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 Xt(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 Kn(o){if(o.length===0)return o;let e=o[o.length-1],t=L(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(a=>!!a.id).map(a=>a.id)),r=o.at(-2);if(r){let a=b(r);if(a){for(let l of a)if(l.id&&n.has(l.id))return o}}let i=-1;for(let a=o.length-2;a>=0;a--){let l=o[a],f=b(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=a;let d=new Set(f.map(E=>E.id).filter(E=>!!E));if(!Array.from(n).every(E=>d.has(E)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let a=i+1;a<o.length-1;a++){let l=o[a],f=L(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let c=o.slice(0,i+1);return c.push(Xt(s)),c}function Vn(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=L(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(L(n).length>0)continue;let r=b(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let c=s.id;c&&e.has(c)&&i.add(e.get(c))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let c=Array.from(i).sort((a,l)=>a-l).map(a=>o[a]);t.push(Xt(c))}}else t.push(n)}return t}function Wt(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Qe(o,e){let t=e.invocationContext;async function n(a){let l=a[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!Wn(l))return a[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,c=o.matchAll(r);for(let a of c){i.push(o.slice(s,a.index));let l=await n(a);i.push(l),s=a.index+a[0].length}return i.push(o.slice(s)),i.join("")}var Zn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ht(o){return o===""||o===void 0?!1:Zn.test(o)}var zn=[v.APP_PREFIX,v.USER_PREFIX,v.TEMP_PREFIX];function Wn(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Ht(o):zn.includes(e[0]+":")?Ht(e[1]):!1}var Xe=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Xe||{});function Jt(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Yn(o.maxLlmCalls||500),...o}}function Yn(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 tn="adk_agent_name";async function nn(o,e){return o instanceof w?[o]:await o.getTools(e)}var He=class extends q{async*runAsync(e,t){var r;let n=e.agent;n instanceof y&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&jt(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))}},Qn=new He,Je=class extends q{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}"`),ue(t,r)}},Xn=new Je,et=class extends q{async*runAsync(e,t){let n=e.agent;if(!(n instanceof y)||!(n.rootAgent instanceof y))return;let r=n.rootAgent;if(r instanceof y&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new P(e)),c=i;s&&(c=await Qe(i,new P(e))),ue(t,[c])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new P(e)),c=i;s&&(c=await Qe(i,new P(e))),ue(t,[c])}}},Hn=new et,tt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof y)||(n.includeContents==="default"?t.contents=Ye(e.session.events,n.name,e.branch):t.contents=Yt(e.session.events,n.name,e.branch))}},Jn=new tt,nt=class extends q{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new $({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:en.object({agentName:en.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof y))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;ue(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new j({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 y)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},eo=new nt,ot=class extends q{async*runAsync(e,t){let n=e.agent;if(!(n instanceof y))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let c=r.length-1;c>=0;c--){let a=r[c];if(a.author!=="user")continue;let l=L(a);if(!l)continue;let f=!1;for(let u of l){if(u.name!==oe)continue;f=!0;let d=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?d=JSON.parse(u.response.response):u.response&&(d=new Z({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&d&&(i[u.id]=d)}if(f){s=c;break}}if(Object.keys(i).length!==0)for(let c=s-1;c>=0;c--){let a=r[c],l=b(a);if(!l)continue;let f={},u={};for(let g of l){if(!g.id||!(g.id in i))continue;let m=g.args;if(!m||!("originalFunctionCall"in m))continue;let h=m.originalFunctionCall;h.id&&(f[h.id]=i[g.id],u[h.id]=h)}if(Object.keys(f).length===0)continue;for(let g=r.length-1;g>s;g--){let m=r[g],h=L(m);if(h){for(let I of h)I.id&&I.id in f&&(delete f[I.id],delete u[I.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let d=await n.canonicalTools(new P(e)),C=Object.fromEntries(d.map(g=>[g.name,g])),E=await ye({invocationContext:e,functionCalls:Object.values(u),toolsDict:C,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f});E&&(yield E);return}}},to=new ot,rt=class extends q{async*runAsync(e,t){if(e.agent instanceof y&&e.agent.codeExecutor){for await(let n of oo(e,t))yield n;if(e.agent.codeExecutor instanceof K)for(let n of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],i=$t(n,r,e.agent.codeExecutor.executionResultDelimiters)}}}},be={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},no=`
|
|
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
|
+
`,it=class{async*runAsync(e,t){if(!t.partial)for await(let n of ro(e,t))yield n}},Ms=new it;async function*oo(o,e){let t=o.agent;if(!(t instanceof y))return;let n=t.codeExecutor;if(!n||!(n instanceof K))return;if(n instanceof re){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new le(new v(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=io(r,e),s=new Set(r.getProcessedFileNames()),c=i.filter(a=>!s.has(a.name));for(let a of c){let l=so(a);if(!l)return;let f={role:"model",parts:[{text:`Processing input file: \`${a.name}\``},Ge(l)]};e.contents.push(M(f)),yield x({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let u=on(o,r),d=await n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[a],executionId:u}});r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:d.stdout,resultStderr:d.stderr}),r.addProcessedFileNames([a.name]);let C=await rn(o,r,d);yield C,e.contents.push(M(C.content))}}async function*ro(o,e){let t=o.agent;if(!(t instanceof y))return;let n=t.codeExecutor;if(!n||!(n instanceof K)||!e||!e.content||n instanceof re)return;let r=new le(new v(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=Dt(i,n.codeBlockDelimiters);if(!s)return;yield x({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let c=on(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 rn(o,r,a),e.content=null}function io(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let c=0;c<s.parts.length;c++){let a=s.parts[c],l=(r=a.inlineData)==null?void 0:r.mimeType;if(!l||!a.inlineData||!be[l])continue;let f=`data_${i+1}_${c+1}${be[l].extension}`;a.text=`
|
|
75
75
|
Available file: \`${f}\`
|
|
76
|
-
`;let u={name:f,content:
|
|
77
|
-
${
|
|
76
|
+
`;let u={name:f,content:At(a.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([u]),t.push(u))}}return t}function on(o,e){var r;let t=o.agent;if(!(t instanceof y)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function rn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[Gt(t)]},r=B({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(o.invocationId):e.resetErrorCount(o.invocationId);for(let i of t.outputFiles){let s=await o.artifactService.saveArtifact({appName:o.appName||"",userId:o.userId||"",sessionId:o.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return x({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function so(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!be[o.mimeType])return;let t=e(o.name),n=be[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return`
|
|
77
|
+
${no}
|
|
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 ro=new et,v=class o extends _{constructor(e){var n,r,i,s,c,a,l,f,u;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(c=e.disallowTransferToPeers)!=null?c:!1,this.includeContents=(a=e.includeContents)!=null?a:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[zn,Wn,Yn,Hn,Qn,ro],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(Xn),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(qe(this.model))return this.model;if(typeof this.model=="string"&&this.model)return oe.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error(`No model found for ${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 Jt(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){p.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!Q(e)){p.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){p.error(`Error parsing output for agent ${this.name}`,s)}}e.actions.stateDelta[this.outputKey]=n}async*runAsyncImpl(e){for(;;){let t;for await(let n of this.runOneStepAsync(e))t=n,this.maybeSaveOutputToState(n),yield n;if(!t||Q(t))break;if(t.partial){p.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(e){for await(let t of this.runLiveFlow(e))this.maybeSaveOutputToState(t),yield t;e.endInvocation}async*runLiveFlow(e){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(e){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let r of this.requestProcessors)for await(let i of r.runAsync(e,t))yield i;for(let r of this.tools){let i=new $({invocationContext:e}),s=await Jt(r,new R(e));for(let c of s)await c.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=y({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=we(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var f;for(let u of this.responseProcessors)for await(let d of u.runAsync(e,n))yield d;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=y({...r,...n});if(i.content){let u=b(i);u!=null&&u.length&&(Tt(i),i.longRunningToolIds=Array.from(Rt(u,t.toolsDict)))}if(yield i,!((f=b(i))!=null&&f.length))return;let s=await wt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let c=It(e,s);c&&(yield c);let a=Pt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),yield s;let l=s.actions.transferToAgent;if(l){let u=this.getAgentByName(e,l);for await(let d of u.runAsync(e))yield d}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,c,a,l,f;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(a=(c=t.config).labels)!=null||(c.labels={}),t.config.labels[Ht]||(t.config.labels[Ht]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let u=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let d of this.runAndHandleError(u,e,t,n)){let g=await this.handleAfterModelCallback(e,d,n);yield g!=null?g:d}}}async handleBeforeModelCallback(e,t,n){let r=new w({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let c=await s({context:r,request:t});if(c)return c}}async handleAfterModelCallback(e,t,n){let r=new w({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let c=await s({context:r,response:t});if(c)return c}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new w({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let c=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(c)yield c;else{let a=JSON.parse(i.message);yield{errorCode:String(a.error.code),errorMessage:a.error.message}}}else throw p.error("Unknown error during response generation",i),i}}};var nt=class extends _{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 ot=class extends _{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(io(this,n,e)));for await(let n of so(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function io(o,e,t){let n=new O(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*so(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 rt="task_completed",it=class extends _{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 v&&((await t.canonicalTools(new R(e))).some(i=>i.name===rt)||(t.tools.push(new B({name:rt,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 ${rt} 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 ae=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=xe(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=xe(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=xe(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=xe(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 xe(o,e,t,n){return ao(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function ao(o){return o.startsWith("user:")}var Z=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=nn(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=nn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let c of Object.values(this.sessionEvents[t]))for(let a of c){if(!((s=(i=a.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=a.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),f=co(l);if(!f.size)continue;n.some(d=>f.has(d))&&r.memories.push({content:a.content,author:a.author,timestamp:lo(a.timestamp)})}return r}};function nn(o,e){return`${o}/${e}`}function co(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function lo(o){return new Date(o).toISOString()}var z=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 st=class extends z{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: ${Q(t)}`);let n=b(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=P(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 rn="adk_request_confirmation",at="orcas_tool_call_security_check_states",on="This tool call needs external confirmation before completion.",sn=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(sn||{}),Ee=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},ct=class extends z{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Ee}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:on};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:on};case"ALLOW":return;default:return}}};function uo(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===rn&&e.push(t.functionCall);return e}var Ae=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[n,r]of Object.entries(t.actions.stateDelta))n.startsWith(C.TEMP_PREFIX)||(e.state[n]=r)}};function be(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var W=class extends Ae{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=be({id:i||X(),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,k(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=k(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(be({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,c=l=>{p.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return c(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return c(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return c(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(C.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(C.USER_PREFIX,"")]=n.actions.stateDelta[l]);let a=this.sessions[r][i][s];return await super.appendEvent({session:a,event:n}),a.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[C.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as fo}from"@google/genai";import{trace as po}from"@opentelemetry/api";var Y=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=Qt(i);let s=po.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 v){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 O({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:xt(),agent:this.agent,session:a,userContent:n,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(f&&(n=f),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,a.userId,a.id,n),await this.sessionService.appendEvent({session:a,event:y({invocationId:l.invocationId,author:"user",actions:r?M({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(a,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(u){let d=y({invocationId:l.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:a,event:d}),yield d}else for await(let d of l.agent.runAsync(l)){d.partial||await this.sessionService.appendEvent({session:a,event:d});let g=await this.pluginManager.runOnEventCallback({invocationContext:l,event:d});g?yield g: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]=fo(`Uploaded file: ${a}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=mo(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){p.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof v)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function mo(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(c=>c.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let c=o.length-2;c>=0;c--){let a=o[c],l=b(a);if(l){for(let f of l)if(f.id===t)return a}}return null}var lt=class extends Y{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new ae,sessionService:new W,memoryService:new Z})}};import{Type as Se}from"@google/genai";var Te=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 ut=class extends I{constructor(e){super({name:e.agent.name,description:e.agent.description||""}),this.agent=e.agent,this.skipSummarization=e.skipSummarization||!1}_getDeclaration(){let e;if(this.agent instanceof v&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Se.OBJECT,properties:{request:{type:Se.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof v&&this.agent.outputSchema;e.response=t?{type:Se.OBJECT}:{type:Se.STRING}}return e}async runAsync({args:e,toolContext:t}){var f,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof v&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new Y({appName:this.agent.name,agent:this.agent,artifactService:new Te(t),sessionService:new W,memoryService:new Z,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),c;for await(let d of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))d.actions.stateDelta&&t.state.update(d.actions.stateDelta),c=d;if(!((u=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&u.length))return"";let a=this.agent instanceof v&&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 ao=new rt,y=class o extends N{constructor(e){var n,r,i,s,c,a,l,f,u;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(c=e.disallowTransferToPeers)!=null?c:!1,this.includeContents=(a=e.includeContents)!=null?a:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[Qn,Xn,Hn,to,Jn,ao],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(eo),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(Ve(this.model))return this.model;if(typeof this.model=="string"&&this.model)return ae.newLlm(this.model);let e=this.parentAgent;for(;e;){if(e instanceof o)return e.canonicalModel;e=e.parentAgent}throw new Error(`No model found for ${this.name}.`)}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await nn(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){p.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){p.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!ee(e)){p.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){p.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){p.error(`Error parsing output for agent ${this.name}`,s)}}e.actions.stateDelta[this.outputKey]=n}async*runAsyncImpl(e){for(;;){let t;for await(let n of this.runOneStepAsync(e))t=n,this.maybeSaveOutputToState(n),yield n;if(!t||ee(t))break;if(t.partial){p.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(e){for await(let t of this.runLiveFlow(e))this.maybeSaveOutputToState(t),yield t;e.endInvocation}async*runLiveFlow(e){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(e){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let r of this.requestProcessors)for await(let i of r.runAsync(e,t))yield i;for(let r of this.tools){let i=new j({invocationContext:e}),s=await nn(r,new P(e));for(let c of s)await c.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=x({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=Me(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var f;for(let u of this.responseProcessors)for await(let d of u.runAsync(e,n))yield d;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=x({...r,...n});if(i.content){let u=b(i);u!=null&&u.length&&(It(i),i.longRunningToolIds=Array.from(wt(u,t.toolsDict)))}if(yield i,!((f=b(i))!=null&&f.length))return;let s=await _t({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let c=kt(e,s);c&&(yield c);let a=Lt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});a&&(yield a),yield s;let l=s.actions.transferToAgent;if(l){let u=this.getAgentByName(e,l);for await(let d of u.runAsync(e))yield d}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,c,a,l,f;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(a=(c=t.config).labels)!=null||(c.labels={}),t.config.labels[tn]||(t.config.labels[tn]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let u=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let d of this.runAndHandleError(u,e,t,n)){let C=await this.handleAfterModelCallback(e,d,n);yield C!=null?C:d}}}async handleBeforeModelCallback(e,t,n){let r=new _({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let c=await s({context:r,request:t});if(c)return c}}async handleAfterModelCallback(e,t,n){let r=new _({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let c=await s({context:r,response:t});if(c)return c}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new _({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let c=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(c)yield c;else{let a=JSON.parse(i.message);yield{errorCode:String(a.error.code),errorMessage:a.error.message}}}else throw p.error("Unknown error during response generation",i),i}}};var st=class extends N{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 at=class extends N{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(co(this,n,e)));for await(let n of lo(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function co(o,e,t){let n=new D(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*lo(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 ct="task_completed",lt=class extends N{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof y&&((await t.canonicalTools(new P(e))).some(i=>i.name===ct)||(t.tools.push(new $({name:ct,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 ${ct} 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 fe=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=Te(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=Te(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=Te(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=Te(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 Te(o,e,t,n){return uo(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function uo(o){return o.startsWith("user:")}var Q=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=sn(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=sn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let c of Object.values(this.sessionEvents[t]))for(let a of c){if(!((s=(i=a.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=a.content.parts.map(d=>d.text).filter(d=>!!d).join(" "),f=fo(l);if(!f.size)continue;n.some(d=>f.has(d))&&r.memories.push({content:a.content,author:a.author,timestamp:po(a.timestamp)})}return r}};function sn(o,e){return`${o}/${e}`}function fo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function po(o){return new Date(o).toISOString()}var X=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 ut=class extends X{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: ${ee(t)}`);let n=b(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=L(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 de=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 cn="adk_request_confirmation",ft="orcas_tool_call_security_check_states",an="This tool call needs external confirmation before completion.",ln=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(ln||{}),Se=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},dt=class extends X{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Se}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:an};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(ft))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(ft))!=null?i:{};r[n]=t,e.state.set(ft,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return n.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:an};case"ALLOW":return;default:return}}};function mo(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===cn&&e.push(t.functionCall);return e}var Re=class{async appendEvent({session:e,event:t}){return t.partial||(this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[n,r]of Object.entries(t.actions.stateDelta))n.startsWith(v.TEMP_PREFIX)||(e.state[n]=r)}};function Ie(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var H=class extends Re{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Ie({id:i||te(),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,M(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=M(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(Ie({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,c=l=>{p.warn(`Failed to append event to session ${s}: ${l}`)};if(!this.sessions[r])return c(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return c(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return c(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(v.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(v.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(v.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(v.USER_PREFIX,"")]=n.actions.stateDelta[l]);let a=this.sessions[r][i][s];return await super.appendEvent({session:a,event:n}),a.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[v.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[v.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as go}from"@google/genai";import{trace as ho}from"@opentelemetry/api";var J=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new de((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=Jt(i);let s=ho.getTracer("gcp.vertex.agent").startSpan("invocation");try{let a=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!a)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof y){let d=this.agent.canonicalModel.model;if(!d.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${d} in agent: ${this.agent.name}`)}let l=new D({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:bt(),agent:this.agent,session:a,userContent:n,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:l});if(f&&(n=f),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(l.invocationId,a.userId,a.id,n),await this.sessionService.appendEvent({session:a,event:x({invocationId:l.invocationId,author:"user",actions:r?B({stateDelta:r}):void 0,content:n})})}l.agent=this.determineAgentForResumption(a,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:l});if(u){let d=x({invocationId:l.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:a,event:d}),yield d}else for await(let d of l.agent.runAsync(l)){d.partial||await this.sessionService.appendEvent({session:a,event:d});let C=await this.pluginManager.runOnEventCallback({invocationContext:l,event:d});C?yield C: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]=go(`Uploaded file: ${a}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Co(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){p.info("event: ",JSON.stringify(e.events[r]));let i=e.events[r];if(i.author==="user"||!i.author)continue;if(i.author===t.name)return t;let s=t.findSubAgent(i.author);if(!s){p.warn(`Event from an unknown agent: ${i.author}, event id: ${i.id}`);continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof y)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Co(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(c=>c.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let c=o.length-2;c>=0;c--){let a=o[c],l=b(a);if(l){for(let f of l)if(f.id===t)return a}}return null}var pt=class extends J{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new fe,sessionService:new H,memoryService:new Q})}};import{Type as we}from"@google/genai";var Pe=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 mt=class extends w{constructor(e){super({name:e.agent.name,description:e.agent.description||""}),this.agent=e.agent,this.skipSummarization=e.skipSummarization||!1}_getDeclaration(){let e;if(this.agent instanceof y&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:we.OBJECT,properties:{request:{type:we.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof y&&this.agent.outputSchema;e.response=t?{type:we.OBJECT}:{type:we.STRING}}return e}async runAsync({args:e,toolContext:t}){var f,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof y&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new J({appName:this.agent.name,agent:this.agent,artifactService:new Pe(t),sessionService:new H,memoryService:new Q,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),c;for await(let d of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))d.actions.stateDelta&&t.state.update(d.actions.stateDelta),c=d;if(!((u=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&u.length))return"";let a=this.agent instanceof y&&this.agent.outputSchema,l=c.content.parts.map(d=>d.text).filter(d=>d).join(`
|
|
85
|
+
`);return a?JSON.parse(l):l}};var pe=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 gt=class extends w{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(e){return Promise.resolve()}async processLlmRequest({toolContext:e,llmRequest:t}){if(t.model){if(t.config=t.config||{},t.config.tools=t.config.tools||[],Ot(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(Mt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},vo=new gt;var un=`
|
|
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.`,ht=class extends ${constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=un:e.description=un.trimStart(),e}};import{Client as yo}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as xo}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Eo}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var ke=class{constructor(e){this.connectionParams=e}async createSession(){let e=new yo({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new xo(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new Eo(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};import{Type as U}from"@google/genai";import{z as me}from"zod";var sl=me.object({type:me.literal("object"),properties:me.record(me.unknown()).optional(),required:me.string().array().optional()});function Ao(o){switch(o.toLowerCase()){case"text":case"string":return U.STRING;case"number":return U.NUMBER;case"boolean":return U.BOOLEAN;case"integer":return U.INTEGER;case"array":return U.ARRAY;case"object":return U.OBJECT;default:return U.TYPE_UNSPECIFIED}}function Ct(o){if(!o)return;function e(t){let n=Ao(t.type),r={type:n,description:t.description};if(n===U.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===U.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var Le=class extends w{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:Ct(this.mcpTool.inputSchema),response:Ct(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 fn=class extends pe{constructor(e,t=[]){super(t),this.mcpSessionManager=new ke(e)}async getTools(e){let n=await(await this.mcpSessionManager.createSession()).listTools();p.debug(`number of tools: ${n.tools.length}`);for(let r of n.tools)p.debug(`tool: ${r.name}`);return n.tools.map(r=>new Le(r,this.mcpSessionManager))}async close(){}};import{Storage as bo}from"@google-cloud/storage";import{createPartFromBase64 as To,createPartFromText as So}from"@google/genai";var dn=class{constructor(e){this.bucket=new bo().bucket(e)}async saveArtifact(e){let t=await this.listVersions(e),n=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(_e({...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(_e({...e,version:t})),[[r],[i]]=await Promise.all([n.getMetadata(),n.download()]);return r.contentType==="text/plain"?So(i.toString("utf-8")):To(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(_e({...e,version:n})).delete()))}async listVersions(e){let t=_e(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 _e({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 Ro,metrics as Io}from"@opentelemetry/api";import{logs as Po}from"@opentelemetry/api-logs";import{LoggerProvider as wo,BatchLogRecordProcessor as ko}from"@opentelemetry/sdk-logs";import{MeterProvider as Lo,PeriodicExportingMetricReader as _o}from"@opentelemetry/sdk-metrics";import{detectResources as Mo}from"@opentelemetry/resources";import{BatchSpanProcessor as Oo}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as No}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Bo}from"@opentelemetry/exporter-trace-otlp-http";import{OTLPMetricExporter as Fo}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPLogExporter as Do}from"@opentelemetry/exporter-logs-otlp-http";function Dl(o=[],e){let t=e||Go(),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 No({resource:t,spanProcessors:r});c.register(),Ro.setGlobalTracerProvider(c)}if(i.length>0){let c=new Lo({readers:i,resource:t});Io.setGlobalMeterProvider(c)}if(s.length>0){let c=new wo({resource:t,processors:s});Po.setGlobalLoggerProvider(c)}}function Go(){return Mo({detectors:[]})}function $o(){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=$o()){let{enableTracing:e,enableMetrics:t,enableLogging:n}=o;return{spanProcessors:e?[new Oo(new Bo)]:[],metricReaders:t?[new _o({exporter:new Fo})]:[],logRecordProcessors:n?[new ko(new Do)]:[]}}import{GoogleAuth as Uo}from"google-auth-library";import{PeriodicExportingMetricReader as jo}from"@opentelemetry/sdk-metrics";import{detectResources as Ko}from"@opentelemetry/resources";import{gcpDetector as Vo}from"@opentelemetry/resource-detector-gcp";import{TraceExporter as Zo}from"@google-cloud/opentelemetry-cloud-trace-exporter";import{BatchSpanProcessor as zo}from"@opentelemetry/sdk-trace-base";import{MetricExporter as Wo}from"@google-cloud/opentelemetry-cloud-monitoring-exporter";var Yo="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Qo(){try{return await new Uo().getProjectId()||void 0}catch{return}}async function Yl(o={}){let{enableTracing:e=!1,enableMetrics:t=!1}=o,n=await Qo();return n?{spanProcessors:e?[new zo(new Zo({projectId:n}))]:[],metricReaders:t?[new jo({exporter:new Wo({projectId:n}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(p.warn(Yo),{})}function Ql(){return Ko({detectors:[Vo]})}export{mt as AgentTool,N as BaseAgent,ie as BaseLlm,X as BasePlugin,Re as BaseSessionService,w as BaseTool,pe as BaseToolset,re as BuiltInCodeExecutor,_ as CallbackContext,$ as FunctionTool,vo as GOOGLE_SEARCH,dn as GcsArtifactService,se as Gemini,fe as InMemoryArtifactService,Q as InMemoryMemoryService,Se as InMemoryPolicyEngine,pt as InMemoryRunner,H as InMemorySessionService,D as InvocationContext,ae as LLMRegistry,De as LiveRequestQueue,y as LlmAgent,Rt as LogLevel,ut as LoggingPlugin,ht as LongRunningFunctionTool,st as LoopAgent,ke as MCPSessionManager,Le as MCPTool,fn as MCPToolset,at as ParallelAgent,de as PluginManager,ln as PolicyOutcome,cn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,J as Runner,dt as SecurityPlugin,lt as SequentialAgent,v as State,Xe as StreamingMode,Z as ToolConfirmation,j as ToolContext,x as createEvent,B as createEventActions,Ie as createSession,An as functionsExportedForTestingOnly,mo as getAskUserConfirmationFunctionCalls,b as getFunctionCalls,L as getFunctionResponses,Yl as getGcpExporters,Ql as getGcpResource,Et as hasTrailingCodeExecutionResult,Ve as isBaseLlm,ee as isFinalResponse,Dl as maybeSetOtelProviders,Cn as setLogLevel,pn as stringifyContent,je as version,Ae as zodObjectToSchema};
|
|
88
88
|
/**
|
|
89
89
|
* @license
|
|
90
90
|
* Copyright 2025 Google LLC
|