@google/adk 0.1.0 → 0.1.1
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/common.js +5 -0
- package/dist/cjs/events/event.js +14 -2
- package/dist/cjs/index.js +5 -5
- package/dist/cjs/index.js.map +3 -3
- package/dist/esm/common.js +4 -1
- package/dist/esm/events/event.js +12 -1
- package/dist/esm/index.js +5 -5
- package/dist/esm/index.js.map +3 -3
- package/dist/types/common.d.ts +3 -1
- package/dist/types/events/event.d.ts +7 -0
- package/dist/web/common.js +4 -1
- package/dist/web/events/event.js +12 -1
- package/dist/web/index.js +1 -1
- package/dist/web/index.js.map +3 -3
- package/package.json +2 -13
package/dist/cjs/common.js
CHANGED
|
@@ -34,6 +34,7 @@ __export(common_exports, {
|
|
|
34
34
|
CallbackContext: () => import_callback_context.CallbackContext,
|
|
35
35
|
FunctionTool: () => import_function_tool.FunctionTool,
|
|
36
36
|
GOOGLE_SEARCH: () => import_google_search_tool.GOOGLE_SEARCH,
|
|
37
|
+
Gemini: () => import_google_llm.Gemini,
|
|
37
38
|
InMemoryArtifactService: () => import_in_memory_artifact_service.InMemoryArtifactService,
|
|
38
39
|
InMemoryMemoryService: () => import_in_memory_memory_service.InMemoryMemoryService,
|
|
39
40
|
InMemoryPolicyEngine: () => import_security_plugin.InMemoryPolicyEngine,
|
|
@@ -66,6 +67,7 @@ __export(common_exports, {
|
|
|
66
67
|
hasTrailingCodeExecutionResult: () => import_event.hasTrailingCodeExecutionResult,
|
|
67
68
|
isFinalResponse: () => import_event.isFinalResponse,
|
|
68
69
|
setLogLevel: () => import_logger.setLogLevel,
|
|
70
|
+
stringifyContent: () => import_event.stringifyContent,
|
|
69
71
|
zodObjectToSchema: () => import_simple_zod_to_json.zodObjectToSchema
|
|
70
72
|
});
|
|
71
73
|
module.exports = __toCommonJS(common_exports);
|
|
@@ -83,6 +85,7 @@ var import_in_memory_artifact_service = require("./artifacts/in_memory_artifact_
|
|
|
83
85
|
var import_event = require("./events/event.js");
|
|
84
86
|
var import_in_memory_memory_service = require("./memory/in_memory_memory_service.js");
|
|
85
87
|
var import_base_llm = require("./models/base_llm.js");
|
|
88
|
+
var import_google_llm = require("./models/google_llm.js");
|
|
86
89
|
var import_base_plugin = require("./plugins/base_plugin.js");
|
|
87
90
|
var import_logging_plugin = require("./plugins/logging_plugin.js");
|
|
88
91
|
var import_plugin_manager = require("./plugins/plugin_manager.js");
|
|
@@ -121,6 +124,7 @@ __reExport(common_exports, require("./tools/base_tool.js"), module.exports);
|
|
|
121
124
|
CallbackContext,
|
|
122
125
|
FunctionTool,
|
|
123
126
|
GOOGLE_SEARCH,
|
|
127
|
+
Gemini,
|
|
124
128
|
InMemoryArtifactService,
|
|
125
129
|
InMemoryMemoryService,
|
|
126
130
|
InMemoryPolicyEngine,
|
|
@@ -153,6 +157,7 @@ __reExport(common_exports, require("./tools/base_tool.js"), module.exports);
|
|
|
153
157
|
hasTrailingCodeExecutionResult,
|
|
154
158
|
isFinalResponse,
|
|
155
159
|
setLogLevel,
|
|
160
|
+
stringifyContent,
|
|
156
161
|
zodObjectToSchema,
|
|
157
162
|
...require("./artifacts/base_artifact_service.js"),
|
|
158
163
|
...require("./memory/base_memory_service.js"),
|
package/dist/cjs/events/event.js
CHANGED
|
@@ -29,7 +29,8 @@ __export(event_exports, {
|
|
|
29
29
|
getFunctionCalls: () => getFunctionCalls,
|
|
30
30
|
getFunctionResponses: () => getFunctionResponses,
|
|
31
31
|
hasTrailingCodeExecutionResult: () => hasTrailingCodeExecutionResult,
|
|
32
|
-
isFinalResponse: () => isFinalResponse
|
|
32
|
+
isFinalResponse: () => isFinalResponse,
|
|
33
|
+
stringifyContent: () => stringifyContent
|
|
33
34
|
});
|
|
34
35
|
module.exports = __toCommonJS(event_exports);
|
|
35
36
|
var import_event_actions = require("./event_actions.js");
|
|
@@ -86,6 +87,16 @@ function hasTrailingCodeExecutionResult(event) {
|
|
|
86
87
|
}
|
|
87
88
|
return false;
|
|
88
89
|
}
|
|
90
|
+
function stringifyContent(event) {
|
|
91
|
+
var _a;
|
|
92
|
+
if (!((_a = event.content) == null ? void 0 : _a.parts)) {
|
|
93
|
+
return "";
|
|
94
|
+
}
|
|
95
|
+
return event.content.parts.map((part) => {
|
|
96
|
+
var _a2;
|
|
97
|
+
return (_a2 = part.text) != null ? _a2 : "";
|
|
98
|
+
}).join("");
|
|
99
|
+
}
|
|
89
100
|
const ASCII_LETTERS_AND_NUMBERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
90
101
|
function createNewEventId() {
|
|
91
102
|
let id = "";
|
|
@@ -103,5 +114,6 @@ function createNewEventId() {
|
|
|
103
114
|
getFunctionCalls,
|
|
104
115
|
getFunctionResponses,
|
|
105
116
|
hasTrailingCodeExecutionResult,
|
|
106
|
-
isFinalResponse
|
|
117
|
+
isFinalResponse,
|
|
118
|
+
stringifyContent
|
|
107
119
|
});
|
package/dist/cjs/index.js
CHANGED
|
@@ -4,11 +4,11 @@
|
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
"use strict";var Pe=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Vt=Object.prototype.hasOwnProperty;var zt=(o,e)=>{for(var t in e)Pe(o,t,{get:e[t],enumerable:!0})},Wt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zt(e))!Vt.call(o,r)&&r!==t&&Pe(o,r,{get:()=>e[r],enumerable:!(n=Kt(e,r))||n.enumerable});return o};var Qt=o=>Wt(Pe({},"__esModule",{value:!0}),o);var _n={};zt(_n,{AgentTool:()=>we,BaseAgent:()=>k,BaseLlm:()=>_,BasePlugin:()=>j,BaseSessionService:()=>ce,BaseTool:()=>S,BaseToolset:()=>ee,CallbackContext:()=>w,FunctionTool:()=>B,GOOGLE_SEARCH:()=>Dt,InMemoryArtifactService:()=>Y,InMemoryMemoryService:()=>U,InMemoryPolicyEngine:()=>le,InMemoryRunner:()=>Re,InMemorySessionService:()=>K,InvocationContext:()=>M,LiveRequestQueue:()=>ve,LlmAgent:()=>y,LogLevel:()=>Fe,LoggingPlugin:()=>Ee,LongRunningFunctionTool:()=>ke,LoopAgent:()=>Ae,MCPSessionManager:()=>de,MCPTool:()=>me,MCPToolset:()=>rt,ParallelAgent:()=>be,PluginManager:()=>J,PolicyOutcome:()=>tt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>et,RunConfig:()=>X,Runner:()=>Z,SecurityPlugin:()=>Se,SequentialAgent:()=>Te,StreamingMode:()=>Xe,ToolConfirmation:()=>q,ToolContext:()=>O,createEvent:()=>b,createSession:()=>ue,functionsExportedForTestingOnly:()=>ft,getAskUserConfirmationFunctionCalls:()=>Bt,getFunctionCalls:()=>x,getFunctionResponses:()=>R,hasTrailingCodeExecutionResult:()=>Le,isFinalResponse:()=>z,setLogLevel:()=>ut,zodObjectToSchema:()=>se});module.exports=Qt(_n);var Oe=require("@opentelemetry/api");function V(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function st(o,e){let t=V();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function b(o={}){return{...o,id:o.id||Me(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||V(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function z(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:x(o).length===0&&R(o).length===0&&!o.partial&&!Le(o)}function x(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 R(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 Le(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}var at="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Me(){let o="";for(let e=0;e<8;e++)o+=at[Math.floor(Math.random()*at.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 I=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 I{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||V(),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 Be(){return typeof window<"u"}var pe="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function W(){let o="";for(let e=0;e<pe.length;e++){let t=Math.random()*16|0;pe[e]==="x"?o+=t.toString(16):pe[e]==="y"?o+=(t&3|8).toString(16):o+=pe[e]}return o}var Ne=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`)}},M=class{constructor(e){this.invocationCostManager=new Ne;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 lt(){return`e-${W()}`}var k=class{constructor(e){this.name=Ht(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Yt(this),this.beforeAgentCallback=ct(e.beforeAgentCallback),this.afterAgentCallback=ct(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=Oe.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=Oe.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new M({...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,b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function Ht(o){if(!Xt(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 Xt(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function Yt(o){for(;o.parentAgent;)o=o.parentAgent;return o}function ct(o){return o?Array.isArray(o)?o:[o]:[]}var ne=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 q=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var O=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 ne(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ne(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 q({hint:e,confirmed:!1,payload:t})}};var Fe=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Fe||{}),Q=1;function ut(o){Q=o}var _e=class{log(e,...t){if(!(e<Q))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){Q>0||console.debug(ge(0),...e)}info(...e){Q>1||console.info(ge(1),...e)}warn(...e){Q>2||console.warn(ge(2),...e)}error(...e){Q>3||console.error(ge(3),...e)}},Jt={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},en={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},tn="\x1B[0m";function ge(o){return`${en[o]}[ADK ${Jt[o]}]:${tn}`}var m=new _e;var $e="adk-",he="adk_request_credential",H="adk_request_confirmation",ft={handleFunctionCallList:Ce};function De(){return`${$e}${W()}`}function dt(o){let e=x(o);if(e)for(let t of e)t.id||(t.id=De())}function mt(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 pt(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 gt(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:he,args:{function_call_id:i,auth_config:s},id:De()};n.add(a.id),t.push({functionCall:a})}return b({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function ht({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=x(e);for(let[l,c]of Object.entries(t.actions.requestedToolConfirmations)){let d=(a=i.find(f=>f.id===l))!=null?a:void 0;if(!d)continue;let u={name:H,args:{originalFunctionCall:d,toolConfirmation:c},id:De()};r.add(u.id),n.push({functionCall:u})}return b({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function nn(o,e,t){return m.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}function on(o,e,t,n){let r=e;(typeof e!="object"||e==null)&&(r={result:e});let s={role:"user",parts:[{functionResponse:{name:o.name,response:r,id:t.functionCallId}}]};return b({invocationId:n.invocationId,author:n.agent.name,content:s,actions:t.actions,branch:n.branch})}async function Ct({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=x(e);return await Ce({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ce({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var d;let a=[],l=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of l){let f;s&&u.id&&(f=s[u.id]);let{tool:T,toolContext:A}=rn({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:f});m.debug(`execute_tool ${T.name}`);let p=(d=u.args)!=null?d:{},g=null;if(g=await o.pluginManager.runBeforeToolCallback({tool:T,toolArgs:p,toolContext:A}),g==null){for(let D of n)if(g=await D({tool:T,args:p,context:A}),g)break}if(g==null)try{g=await nn(T,p,A)}catch(D){if(D instanceof Error){let it=await o.pluginManager.runOnToolErrorCallback({tool:T,toolArgs:p,toolContext:A,error:D});it&&(g=it)}else throw m.error("Unknown error on tool execution type",D),D}let h=await o.pluginManager.runAfterToolCallback({tool:T,toolArgs:p,toolContext:A,result:g});if(h==null){for(let D of r)if(h=await D({tool:T,args:p,context:A,response:g}),h)break}if(h!=null&&(g=h),T.isLongRunning&&!g)continue;let L=on(T,g,A,o);m.debug("traceToolCall",{tool:T.name,args:p,functionResponseEvent:L.id}),a.push(L)}if(!a.length)return null;let c=sn(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:c.id,functionResponseEvent:c.id})),c}function rn({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 O({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=st(n);return b({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ve=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var Ke=require("zod");var _=class{constructor(e){this.model=e}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."}]})}};_.supportedModels=[];function oe(o,e){o.config||(o.config={});let t=e.join(`
|
|
7
|
+
"use strict";var Pe=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var zt=Object.prototype.hasOwnProperty;var Wt=(o,e)=>{for(var t in e)Pe(o,t,{get:e[t],enumerable:!0})},Qt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vt(e))!zt.call(o,r)&&r!==t&&Pe(o,r,{get:()=>e[r],enumerable:!(n=Zt(e,r))||n.enumerable});return o};var Ht=o=>Qt(Pe({},"__esModule",{value:!0}),o);var Fn={};Wt(Fn,{AgentTool:()=>we,BaseAgent:()=>k,BaseLlm:()=>O,BasePlugin:()=>j,BaseSessionService:()=>ce,BaseTool:()=>S,BaseToolset:()=>te,CallbackContext:()=>w,FunctionTool:()=>B,GOOGLE_SEARCH:()=>qt,Gemini:()=>W,InMemoryArtifactService:()=>J,InMemoryMemoryService:()=>U,InMemoryPolicyEngine:()=>le,InMemoryRunner:()=>Re,InMemorySessionService:()=>K,InvocationContext:()=>M,LiveRequestQueue:()=>ve,LlmAgent:()=>y,LogLevel:()=>Fe,LoggingPlugin:()=>Ee,LongRunningFunctionTool:()=>ke,LoopAgent:()=>Ae,MCPSessionManager:()=>de,MCPTool:()=>me,MCPToolset:()=>rt,ParallelAgent:()=>be,PluginManager:()=>ee,PolicyOutcome:()=>tt,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>et,RunConfig:()=>Y,Runner:()=>Z,SecurityPlugin:()=>Se,SequentialAgent:()=>Te,StreamingMode:()=>Xe,ToolConfirmation:()=>q,ToolContext:()=>N,createEvent:()=>b,createSession:()=>ue,functionsExportedForTestingOnly:()=>dt,getAskUserConfirmationFunctionCalls:()=>_t,getFunctionCalls:()=>x,getFunctionResponses:()=>R,hasTrailingCodeExecutionResult:()=>Le,isFinalResponse:()=>z,setLogLevel:()=>ft,stringifyContent:()=>lt,zodObjectToSchema:()=>se});module.exports=Ht(Fn);var Ne=require("@opentelemetry/api");function V(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function st(o,e){let t=V();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function b(o={}){return{...o,id:o.id||Me(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||V(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function z(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:x(o).length===0&&R(o).length===0&&!o.partial&&!Le(o)}function x(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 R(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 Le(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 lt(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 at="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Me(){let o="";for(let e=0;e<8;e++)o+=at[Math.floor(Math.random()*at.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 I=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 I{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||V(),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 Be(){return typeof window<"u"}var pe="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function Q(){let o="";for(let e=0;e<pe.length;e++){let t=Math.random()*16|0;pe[e]==="x"?o+=t.toString(16):pe[e]==="y"?o+=(t&3|8).toString(16):o+=pe[e]}return o}var _e=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`)}},M=class{constructor(e){this.invocationCostManager=new _e;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 ct(){return`e-${Q()}`}var k=class{constructor(e){this.name=Xt(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Jt(this),this.beforeAgentCallback=ut(e.beforeAgentCallback),this.afterAgentCallback=ut(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=Ne.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=Ne.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new M({...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,b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return b({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return b({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function Xt(o){if(!Yt(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 Yt(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function Jt(o){for(;o.parentAgent;)o=o.parentAgent;return o}function ut(o){return o?Array.isArray(o)?o:[o]:[]}var oe=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 q=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var N=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 oe(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new oe(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 q({hint:e,confirmed:!1,payload:t})}};var Fe=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Fe||{}),H=1;function ft(o){H=o}var Oe=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(ge(0),...e)}info(...e){H>1||console.info(ge(1),...e)}warn(...e){H>2||console.warn(ge(2),...e)}error(...e){H>3||console.error(ge(3),...e)}},en={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},tn={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},nn="\x1B[0m";function ge(o){return`${tn[o]}[ADK ${en[o]}]:${nn}`}var m=new Oe;var $e="adk-",he="adk_request_credential",X="adk_request_confirmation",dt={handleFunctionCallList:Ce};function De(){return`${$e}${Q()}`}function mt(o){let e=x(o);if(e)for(let t of e)t.id||(t.id=De())}function pt(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 gt(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 ht(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:he,args:{function_call_id:i,auth_config:s},id:De()};n.add(a.id),t.push({functionCall:a})}return b({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Ct({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=x(e);for(let[l,c]of Object.entries(t.actions.requestedToolConfirmations)){let d=(a=i.find(f=>f.id===l))!=null?a:void 0;if(!d)continue;let u={name:X,args:{originalFunctionCall:d,toolConfirmation:c},id:De()};r.add(u.id),n.push({functionCall:u})}return b({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function on(o,e,t){return m.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}function rn(o,e,t,n){let r=e;(typeof e!="object"||e==null)&&(r={result:e});let s={role:"user",parts:[{functionResponse:{name:o.name,response:r,id:t.functionCallId}}]};return b({invocationId:n.invocationId,author:n.agent.name,content:s,actions:t.actions,branch:n.branch})}async function vt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=x(e);return await Ce({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Ce({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var d;let a=[],l=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of l){let f;s&&u.id&&(f=s[u.id]);let{tool:T,toolContext:A}=sn({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:f});m.debug(`execute_tool ${T.name}`);let p=(d=u.args)!=null?d:{},g=null;if(g=await o.pluginManager.runBeforeToolCallback({tool:T,toolArgs:p,toolContext:A}),g==null){for(let D of n)if(g=await D({tool:T,args:p,context:A}),g)break}if(g==null)try{g=await on(T,p,A)}catch(D){if(D instanceof Error){let it=await o.pluginManager.runOnToolErrorCallback({tool:T,toolArgs:p,toolContext:A,error:D});it&&(g=it)}else throw m.error("Unknown error on tool execution type",D),D}let h=await o.pluginManager.runAfterToolCallback({tool:T,toolArgs:p,toolContext:A,result:g});if(h==null){for(let D of r)if(h=await D({tool:T,args:p,context:A,response:g}),h)break}if(h!=null&&(g=h),T.isLongRunning&&!g)continue;let L=rn(T,g,A,o);m.debug("traceToolCall",{tool:T.name,args:p,functionResponseEvent:L.id}),a.push(L)}if(!a.length)return null;let c=an(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:c.id,functionResponseEvent:c.id})),c}function sn({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 N({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=st(n);return b({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var ve=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var Ke=require("zod");var O=class{constructor(e){this.model=e}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."}]})}};O.supportedModels=[];function re(o,e){o.config||(o.config={});let t=e.join(`
|
|
8
8
|
|
|
9
9
|
`);o.config.systemInstruction?o.config.systemInstruction+=`
|
|
10
10
|
|
|
11
|
-
`+t:o.config.systemInstruction=t}function vt(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var F=require("@google/genai");function yt(){return an("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function an(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var At="0.1.0";var ye=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"}):m.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);m.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else m.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){m.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function qe(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var cn="remote_reasoning_engine",un="GOOGLE_CLOUD_AGENT_ENGINE_ID",re=class extends _{constructor({model:e="gemini-2.5-flash",apiKey:t,vertexai:n,project:r,location:i,headers:s}={}){super(e),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!n,!this.vertexai&&a){let l=process.env.GOOGLE_GENAI_USE_VERTEXAI;l&&(this.vertexai=l.toLowerCase()==="true"||l==="1")}if(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,a,l,c;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.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 d=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),u="",f="",T,A;for await(let p of d){A=p;let g=qe(p);T=g.usageMetadata;let h=(s=(i=g.content)==null?void 0:i.parts)==null?void 0:s[0];if(h!=null&&h.text)"thought"in h&&h.thought?u+=h.text:f+=h.text,g.partial=!0;else if((u||f)&&(!h||!h.inlineData)){let L=[];u&&L.push({text:u,thought:!0}),f&&L.push((0,F.createPartFromText)(f)),yield{content:{role:"model",parts:L},usageMetadata:g.usageMetadata},u="",f=""}yield g}if((f||u)&&((l=(a=A==null?void 0:A.candidates)==null?void 0:a[0])==null?void 0:l.finishReason)===F.FinishReason.STOP){let p=[];u&&p.push({text:u,thought:!0}),f&&p.push({text:f}),yield{content:{role:"model",parts:p},usageMetadata:T}}}else{let d=await this.apiClient.models.generateContent({model:(c=e.model)!=null?c:this.model,contents:e.contents,config:e.config});yield qe(d)}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};return this.vertexai?this._apiClient=new F.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new F.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get trackingHeaders(){if(!this._trackingHeaders){let e=`google-adk/${At}`;!Be()&&process.env[un]&&(e=`${e}+${cn}`);let t=`gl-typescript/${Be()?window.navigator.userAgent:process.version}`,n=`${e} ${t}`;this._trackingHeaders={"x-goog-api-client":n,"user-agent":n}}return this._trackingHeaders}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new F.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),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.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,F.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new ye(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)bt(n.inlineData),bt(n.fileData)}}};re.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function bt(o){o&&o.displayName&&(o.displayName=void 0)}var Ge=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)}},P=class P{static newLlm(e){return new(P.resolve(e))(e)}static _register(e,t){P.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${P.llmRegistryDict.get(e)} to ${t}`),P.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)P._register(t,e)}static resolve(e){let t=P.resolveCache.get(e);if(t)return t;for(let[n,r]of P.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return P.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};P.llmRegistryDict=new Map,P.resolveCache=new Ge(32);var ie=P;ie.register(re);var S=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 yt()}};function fn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var xt=require("@google/genai"),Et=require("zod");var E=require("@google/genai"),v=require("zod");function Tt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function $(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 v.z.ZodFirstPartyTypeKind.ZodString:n.type=E.Type.STRING;for(let l of e.checks||[])l.kind==="min"?n.minLength=l.value.toString():l.kind==="max"?n.maxLength=l.value.toString():l.kind==="email"?n.format="email":l.kind==="uuid"?n.format="uuid":l.kind==="url"?n.format="uri":l.kind==="regex"&&(n.pattern=l.regex.source);return r(n);case v.z.ZodFirstPartyTypeKind.ZodNumber:n.type=E.Type.NUMBER;for(let l of e.checks||[])l.kind==="min"?n.minimum=l.value:l.kind==="max"?n.maximum=l.value:l.kind==="int"&&(n.type=E.Type.INTEGER);return r(n);case v.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=E.Type.BOOLEAN,r(n);case v.z.ZodFirstPartyTypeKind.ZodArray:return n.type=E.Type.ARRAY,n.items=$(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case v.z.ZodFirstPartyTypeKind.ZodObject:return se(o);case v.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=E.Type.STRING;else if(i==="number")n.type=E.Type.NUMBER;else if(i==="boolean")n.type=E.Type.BOOLEAN;else if(e.value===null)n.type=E.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case v.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=E.Type.STRING,n.enum=e.values,r(n);case v.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=E.Type.STRING,n.enum=Object.values(e.values),r(n);case v.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map($),r(n);case v.z.ZodFirstPartyTypeKind.ZodOptional:return $(e.innerType);case v.z.ZodFirstPartyTypeKind.ZodNullable:let s=$(e.innerType);return r(s?{anyOf:[s,{type:E.Type.NULL}],...t&&{description:t}}:{type:E.Type.NULL,...t&&{description:t}});case v.z.ZodFirstPartyTypeKind.ZodDefault:let a=$(e.innerType);return a&&(a.default=e.defaultValue()),a;case v.z.ZodFirstPartyTypeKind.ZodBranded:return $(e.type);case v.z.ZodFirstPartyTypeKind.ZodReadonly:return $(e.innerType);case v.z.ZodFirstPartyTypeKind.ZodNull:return n.type=E.Type.NULL,r(n);case v.z.ZodFirstPartyTypeKind.ZodAny:case v.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function se(o){if(o._def.typeName!==v.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],l=$(a);l&&(t[s]=l);let c=a,d=!1;for(;c._def.typeName===v.z.ZodFirstPartyTypeKind.ZodOptional||c._def.typeName===v.z.ZodFirstPartyTypeKind.ZodDefault;)d=!0,c=c._def.innerType;d||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==v.z.ZodFirstPartyTypeKind.ZodNever?i=$(r)||!0:i=o._def.unknownKeys==="passthrough",{type:E.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function dn(o){return o===void 0?{type:xt.Type.OBJECT,properties:{}}:Tt(o)?se(o):o}var B=class extends S{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:dn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Et.ZodObject&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`Error in tool '${this.name}': ${n}`)}}};var G=class{};function ae(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ue(o,e,t){var s,a,l;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||((l=(a=c.content.parts)==null?void 0:a[0])==null?void 0:l.text)===""||t&&c.branch&&!t.startsWith(c.branch)||mn(c)||pn(c)||n.push(Rt(e,c)?gn(c):c);let r=hn(n);r=Cn(r);let i=[];for(let c of r){let d=ae(c.content);mt(d),i.push(d)}return i}function St(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Rt(e,r))return Ue(o.slice(n),e,t)}return[]}function mn(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)===he||((n=r.functionResponse)==null?void 0:n.name)===he)return!0;return!1}function pn(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)===H||((n=r.functionResponse)==null?void 0:n.name)===H)return!0;return!1}function Rt(o,e){return!!o&&e.author!==o&&e.author!=="user"}function gn(o){var t,n,r,i,s;if(!((t=o.content)!=null&&t.parts))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let a of o.content.parts)a.text&&!a.thought?(n=e.parts)==null||n.push({text:`[${o.author}] said: ${a.text}`}):a.functionCall?(r=e.parts)==null||r.push({text:`[${o.author}] called tool \`${a.functionCall.name}\` with parameters: ${a.functionCall.args}`}):a.functionResponse?(i=e.parts)==null||i.push({text:`[${o.author}] tool \`${a.functionResponse.name}\` returned result: ${a.functionResponse.response}`}):(s=e.parts)==null||s.push(a);return b({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function It(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=b(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function hn(o){if(o.length===0)return o;let e=o[o.length-1],t=R(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(l=>!!l.id).map(l=>l.id)),r=o.at(-2);if(r){let l=x(r);if(l){for(let c of l)if(c.id&&n.has(c.id))return o}}let i=-1;for(let l=o.length-2;l>=0;l--){let c=o[l],d=x(c);if(d!=null&&d.length){for(let u of d)if(u.id&&n.has(u.id)){i=l;let f=new Set(d.map(A=>A.id).filter(A=>!!A));if(!Array.from(n).every(A=>f.has(A)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(f).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=f;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let l=i+1;l<o.length-1;l++){let c=o[l],d=R(c);d&&d.some(u=>u.id&&n.has(u.id))&&s.push(c)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(It(s)),a}function Cn(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=R(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(R(n).length>0)continue;let r=x(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((l,c)=>l-c).map(l=>o[l]);t.push(It(a))}}else t.push(n)}return t}async function je(o,e){let t=e.invocationContext;async function n(l){let c=l[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),d=c.endsWith("?");if(d&&(c=c.slice(0,-1)),c.startsWith("artifact.")){let u=c.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let f=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!f)throw new Error(`Artifact ${u} not found.`);return String(f)}if(!An(c))return l[0];if(c in t.session.state)return String(t.session.state[c]);if(d)return"";throw new Error(`Context variable not found: \`${c}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let l of a){i.push(o.slice(s,l.index));let c=await n(l);i.push(c),s=l.index+l[0].length}return i.push(o.slice(s)),i.join("")}var vn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function wt(o){return o===""||o===void 0?!1:vn.test(o)}var yn=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function An(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?wt(o):yn.includes(e[0]+":")?wt(e[1]):!1}var kt="adk_agent_name";async function Pt(o,e){return o instanceof S?[o]:await o.getTools(e)}var Ze=class extends G{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&&vt(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))}},bn=new Ze,Ve=class extends G{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}"`),oe(t,r)}},Tn=new Ve,ze=class extends G{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 I(e)),a=i;s&&(a=await je(i,new I(e))),oe(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new I(e)),a=i;s&&(a=await je(i,new I(e))),oe(t,[a])}}},xn=new ze,We=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof y)||(n.includeContents==="default"?t.contents=Ue(e.session.events,n.name,e.branch):t.contents=St(e.session.events,n.name,e.branch))}},En=new We,Qe=class extends G{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:Ke.z.object({agentName:Ke.z.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");n.actions.transferToAgent=t.agentName}})}async*runAsync(t,n){if(!(t.agent instanceof y))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;oe(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new O({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
11
|
+
`+t:o.config.systemInstruction=t}function yt(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var F=require("@google/genai");function At(){return ln("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function ln(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var bt="0.1.0";var ye=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"}):m.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);m.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else m.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){m.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};function qe(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var un="remote_reasoning_engine",fn="GOOGLE_CLOUD_AGENT_ENGINE_ID",W=class extends O{constructor({model:e="gemini-2.5-flash",apiKey:t,vertexai:n,project:r,location:i,headers:s}={}){super(e),this.project=r,this.location=i,this.apiKey=t,this.headers=s;let a=typeof process=="object";if(this.vertexai=!!n,!this.vertexai&&a){let l=process.env.GOOGLE_GENAI_USE_VERTEXAI;l&&(this.vertexai=l.toLowerCase()==="true"||l==="1")}if(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,a,l,c;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.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 d=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),u="",f="",T,A;for await(let p of d){A=p;let g=qe(p);T=g.usageMetadata;let h=(s=(i=g.content)==null?void 0:i.parts)==null?void 0:s[0];if(h!=null&&h.text)"thought"in h&&h.thought?u+=h.text:f+=h.text,g.partial=!0;else if((u||f)&&(!h||!h.inlineData)){let L=[];u&&L.push({text:u,thought:!0}),f&&L.push((0,F.createPartFromText)(f)),yield{content:{role:"model",parts:L},usageMetadata:g.usageMetadata},u="",f=""}yield g}if((f||u)&&((l=(a=A==null?void 0:A.candidates)==null?void 0:a[0])==null?void 0:l.finishReason)===F.FinishReason.STOP){let p=[];u&&p.push({text:u,thought:!0}),f&&p.push({text:f}),yield{content:{role:"model",parts:p},usageMetadata:T}}}else{let d=await this.apiClient.models.generateContent({model:(c=e.model)!=null?c:this.model,contents:e.contents,config:e.config});yield qe(d)}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};return this.vertexai?this._apiClient=new F.GoogleGenAI({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}}):this._apiClient=new F.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:e}}),this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get trackingHeaders(){if(!this._trackingHeaders){let e=`google-adk/${bt}`;!Be()&&process.env[fn]&&(e=`${e}+${un}`);let t=`gl-typescript/${Be()?window.navigator.userAgent:process.version}`,n=`${e} ${t}`;this._trackingHeaders={"x-goog-api-client":n,"user-agent":n}}return this._trackingHeaders}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new F.GoogleGenAI({apiKey:this.apiKey,httpOptions:{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}})),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.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[(0,F.createPartFromText)(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new ye(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)Tt(n.inlineData),Tt(n.fileData)}}};W.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Tt(o){o&&o.displayName&&(o.displayName=void 0)}var Ge=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)}},P=class P{static newLlm(e){return new(P.resolve(e))(e)}static _register(e,t){P.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${P.llmRegistryDict.get(e)} to ${t}`),P.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)P._register(t,e)}static resolve(e){let t=P.resolveCache.get(e);if(t)return t;for(let[n,r]of P.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return P.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};P.llmRegistryDict=new Map,P.resolveCache=new Ge(32);var ie=P;ie.register(W);var S=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=dn(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 At()}};function dn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var Et=require("@google/genai"),St=require("zod");var E=require("@google/genai"),v=require("zod");function xt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function $(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 v.z.ZodFirstPartyTypeKind.ZodString:n.type=E.Type.STRING;for(let l of e.checks||[])l.kind==="min"?n.minLength=l.value.toString():l.kind==="max"?n.maxLength=l.value.toString():l.kind==="email"?n.format="email":l.kind==="uuid"?n.format="uuid":l.kind==="url"?n.format="uri":l.kind==="regex"&&(n.pattern=l.regex.source);return r(n);case v.z.ZodFirstPartyTypeKind.ZodNumber:n.type=E.Type.NUMBER;for(let l of e.checks||[])l.kind==="min"?n.minimum=l.value:l.kind==="max"?n.maximum=l.value:l.kind==="int"&&(n.type=E.Type.INTEGER);return r(n);case v.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=E.Type.BOOLEAN,r(n);case v.z.ZodFirstPartyTypeKind.ZodArray:return n.type=E.Type.ARRAY,n.items=$(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case v.z.ZodFirstPartyTypeKind.ZodObject:return se(o);case v.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=E.Type.STRING;else if(i==="number")n.type=E.Type.NUMBER;else if(i==="boolean")n.type=E.Type.BOOLEAN;else if(e.value===null)n.type=E.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case v.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=E.Type.STRING,n.enum=e.values,r(n);case v.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=E.Type.STRING,n.enum=Object.values(e.values),r(n);case v.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map($),r(n);case v.z.ZodFirstPartyTypeKind.ZodOptional:return $(e.innerType);case v.z.ZodFirstPartyTypeKind.ZodNullable:let s=$(e.innerType);return r(s?{anyOf:[s,{type:E.Type.NULL}],...t&&{description:t}}:{type:E.Type.NULL,...t&&{description:t}});case v.z.ZodFirstPartyTypeKind.ZodDefault:let a=$(e.innerType);return a&&(a.default=e.defaultValue()),a;case v.z.ZodFirstPartyTypeKind.ZodBranded:return $(e.type);case v.z.ZodFirstPartyTypeKind.ZodReadonly:return $(e.innerType);case v.z.ZodFirstPartyTypeKind.ZodNull:return n.type=E.Type.NULL,r(n);case v.z.ZodFirstPartyTypeKind.ZodAny:case v.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function se(o){if(o._def.typeName!==v.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],l=$(a);l&&(t[s]=l);let c=a,d=!1;for(;c._def.typeName===v.z.ZodFirstPartyTypeKind.ZodOptional||c._def.typeName===v.z.ZodFirstPartyTypeKind.ZodDefault;)d=!0,c=c._def.innerType;d||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==v.z.ZodFirstPartyTypeKind.ZodNever?i=$(r)||!0:i=o._def.unknownKeys==="passthrough",{type:E.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function mn(o){return o===void 0?{type:Et.Type.OBJECT,properties:{}}:xt(o)?se(o):o}var B=class extends S{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:mn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof St.ZodObject&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`Error in tool '${this.name}': ${n}`)}}};var G=class{};function ae(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ue(o,e,t){var s,a,l;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||((l=(a=c.content.parts)==null?void 0:a[0])==null?void 0:l.text)===""||t&&c.branch&&!t.startsWith(c.branch)||pn(c)||gn(c)||n.push(It(e,c)?hn(c):c);let r=Cn(n);r=vn(r);let i=[];for(let c of r){let d=ae(c.content);pt(d),i.push(d)}return i}function Rt(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||It(e,r))return Ue(o.slice(n),e,t)}return[]}function pn(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)===he||((n=r.functionResponse)==null?void 0:n.name)===he)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)===X||((n=r.functionResponse)==null?void 0:n.name)===X)return!0;return!1}function It(o,e){return!!o&&e.author!==o&&e.author!=="user"}function hn(o){var t,n,r,i,s;if(!((t=o.content)!=null&&t.parts))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let a of o.content.parts)a.text&&!a.thought?(n=e.parts)==null||n.push({text:`[${o.author}] said: ${a.text}`}):a.functionCall?(r=e.parts)==null||r.push({text:`[${o.author}] called tool \`${a.functionCall.name}\` with parameters: ${a.functionCall.args}`}):a.functionResponse?(i=e.parts)==null||i.push({text:`[${o.author}] tool \`${a.functionResponse.name}\` returned result: ${a.functionResponse.response}`}):(s=e.parts)==null||s.push(a);return b({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=b(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function Cn(o){if(o.length===0)return o;let e=o[o.length-1],t=R(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(l=>!!l.id).map(l=>l.id)),r=o.at(-2);if(r){let l=x(r);if(l){for(let c of l)if(c.id&&n.has(c.id))return o}}let i=-1;for(let l=o.length-2;l>=0;l--){let c=o[l],d=x(c);if(d!=null&&d.length){for(let u of d)if(u.id&&n.has(u.id)){i=l;let f=new Set(d.map(A=>A.id).filter(A=>!!A));if(!Array.from(n).every(A=>f.has(A)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(f).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=f;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let l=i+1;l<o.length-1;l++){let c=o[l],d=R(c);d&&d.some(u=>u.id&&n.has(u.id))&&s.push(c)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(wt(s)),a}function vn(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=R(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(R(n).length>0)continue;let r=x(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((l,c)=>l-c).map(l=>o[l]);t.push(wt(a))}}else t.push(n)}return t}async function je(o,e){let t=e.invocationContext;async function n(l){let c=l[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),d=c.endsWith("?");if(d&&(c=c.slice(0,-1)),c.startsWith("artifact.")){let u=c.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let f=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!f)throw new Error(`Artifact ${u} not found.`);return String(f)}if(!bn(c))return l[0];if(c in t.session.state)return String(t.session.state[c]);if(d)return"";throw new Error(`Context variable not found: \`${c}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let l of a){i.push(o.slice(s,l.index));let c=await n(l);i.push(c),s=l.index+l[0].length}return i.push(o.slice(s)),i.join("")}var yn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function kt(o){return o===""||o===void 0?!1:yn.test(o)}var An=[C.APP_PREFIX,C.USER_PREFIX,C.TEMP_PREFIX];function bn(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?kt(o):An.includes(e[0]+":")?kt(e[1]):!1}var Pt="adk_agent_name";async function Lt(o,e){return o instanceof S?[o]:await o.getTools(e)}var Ze=class extends G{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&&yt(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))}},Tn=new Ze,Ve=class extends G{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}"`),re(t,r)}},xn=new Ve,ze=class extends G{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 I(e)),a=i;s&&(a=await je(i,new I(e))),re(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new I(e)),a=i;s&&(a=await je(i,new I(e))),re(t,[a])}}},En=new ze,We=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof y)||(n.includeContents==="default"?t.contents=Ue(e.session.events,n.name,e.branch):t.contents=Rt(e.session.events,n.name,e.branch))}},Sn=new We,Qe=class extends G{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:Ke.z.object({agentName:Ke.z.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");n.actions.transferToAgent=t.agentName}})}async*runAsync(t,n){if(!(t.agent instanceof y))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;re(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new N({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
12
12
|
Agent name: ${t.name}
|
|
13
13
|
Agent description: ${t.description}
|
|
14
14
|
`}buildTargetAgentsInstructions(t,n){let r=`
|
|
@@ -28,10 +28,10 @@ the function call.
|
|
|
28
28
|
Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
|
|
29
29
|
you are best for answering the question according to the descriptions, transfer
|
|
30
30
|
to your parent agent.
|
|
31
|
-
`),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}},Sn=new Qe,He=class extends G{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 a=r.length-1;a>=0;a--){let l=r[a];if(l.author!=="user")continue;let c=R(l);if(!c)continue;let d=!1;for(let u of c){if(u.name!==H)continue;d=!0;let f=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?f=JSON.parse(u.response.response):u.response&&(f=new q({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(i[u.id]=f)}if(d){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let l=r[a],c=x(l);if(!c)continue;let d={},u={};for(let p of c){if(!p.id||!(p.id in i))continue;let g=p.args;if(!g||!("originalFunctionCall"in g))continue;let h=g.originalFunctionCall;h.id&&(d[h.id]=i[p.id],u[h.id]=h)}if(Object.keys(d).length===0)continue;for(let p=r.length-1;p>s;p--){let g=r[p],h=R(g);if(h){for(let L of h)L.id&&L.id in d&&(delete d[L.id],delete u[L.id]);if(Object.keys(d).length===0)break}}if(Object.keys(d).length===0)continue;let f=await n.canonicalTools(new I(e)),T=Object.fromEntries(f.map(p=>[p.name,p])),A=await Ce({invocationContext:e,functionCalls:Object.values(u),toolsDict:T,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(d)),toolConfirmationDict:d});A&&(yield A);return}}},Rn=new He,y=class o extends k{constructor(e){var n,r,i,s,a,l,c,d,u;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(l=e.includeContents)!=null?l:"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.requestProcessors=(c=e.requestProcessors)!=null?c:[bn,Tn,xn,Rn,En],this.responseProcessors=(d=e.responseProcessors)!=null?d:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(Sn),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)&&(m.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(this.model instanceof _)return this.model;if(typeof this.model=="string"&&this.model)return ie.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 Pt(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){m.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){m.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!z(e)){m.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)){m.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){m.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||z(t))break;if(t.partial){m.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 O({invocationContext:e}),s=await Pt(r,new I(e));for(let a of s)await a.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=b({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=Me(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var d;for(let u of this.responseProcessors)for await(let f of u.runAsync(e,n))yield f;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=b({...r,...n});if(i.content){let u=x(i);u!=null&&u.length&&(dt(i),i.longRunningToolIds=Array.from(pt(u,t.toolsDict)))}if(yield i,!((d=x(i))!=null&&d.length))return;let s=await Ct({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let a=gt(e,s);a&&(yield a);let l=ht({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});l&&(yield l),yield s;let c=s.actions.transferToAgent;if(c){let u=this.getAgentByName(e,c);for await(let f of u.runAsync(e))yield f}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,a,l,c;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(l=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[kt]||(t.config.labels[kt]=this.name);let i=this.canonicalModel;if((c=e.runConfig)!=null&&c.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let d=i.generateContentAsync(t);for await(let u of this.runAndHandleError(d,e,t,n)){let f=await this.handleAfterModelCallback(e,u,n);yield f!=null?f:u}}}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 a=await s({context:r,request:t});if(a)return a}}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 a=await s({context:r,response:t});if(a)return a}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new w({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let a=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(a)yield a;else{let l=JSON.parse(i.message);yield{errorCode:String(l.error.code),errorMessage:l.error.message}}}else throw m.error("Unknown error during response generation",i),i}}};var Ae=class extends k{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(e){let t=0;for(;t<this.maxIterations;){for(let n of this.subAgents){let r=!1;for await(let i of n.runAsync(e))yield i,i.actions.escalate&&(r=!0);if(r)return}t++}}async*runLiveImpl(e){throw new Error("This is not supported yet for LoopAgent.")}};var be=class extends k{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(In(this,n,e)));for await(let n of wn(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function In(o,e,t){let n=new M(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*wn(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 Xe=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Xe||{}),X=class{constructor(e={}){this.speechConfig=e.speechConfig,this.responseModalities=e.responseModalities,this.saveInputBlobsAsArtifacts=e.saveInputBlobsAsArtifacts||!1,this.supportCfc=e.supportCfc||!1,this.streamingMode=e.streamingMode||"none",this.outputAudioTranscription=e.outputAudioTranscription,this.inputAudioTranscription=e.inputAudioTranscription,this.enableAffectiveDialog=e.enableAffectiveDialog||!1,this.realtimeInputConfig=e.realtimeInputConfig,this.maxLlmCalls=kn(e.maxLlmCalls||500)}};function kn(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&m.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 Ye="task_completed",Te=class extends k{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof y&&((await t.canonicalTools(new I(e))).some(i=>i.name===Ye)||(t.tools.push(new B({name:Ye,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 ${Ye} 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 Y=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 a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=xe(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let l=a.replace(r,"");s.push(l)}else if(a.startsWith(i)){let l=a.replace(i,"");s.push(l)}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 a=[];for(let l=0;l<s.length;l++)a.push(l);return Promise.resolve(a)}};function xe(o,e,t,n){return Pn(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Pn(o){return o.startsWith("user:")}var U=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Lt(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=Lt(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let l of a){if(!((s=(i=l.content)==null?void 0:i.parts)!=null&&s.length))continue;let c=l.content.parts.map(f=>f.text).filter(f=>!!f).join(" "),d=Ln(c);if(!d.size)continue;n.some(f=>d.has(f))&&r.memories.push({content:l.content,author:l.author,timestamp:Mn(l.timestamp)})}return r}};function Lt(o,e){return`${o}/${e}`}function Ln(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Mn(o){return new Date(o).toISOString()}var j=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var Ee=class extends j{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${z(t)}`);let n=x(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=R(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`;m.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 J=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),m.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 m.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 m.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 et="adk_request_confirmation",Je="orcas_tool_call_security_check_states",Mt="This tool call needs external confirmation before completion.",tt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(tt||{}),le=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Se=class extends j{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new le}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:Mt};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(Je))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Je))!=null?i:{};r[n]=t,e.state.set(Je,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:Mt};case"ALLOW":return;default:return}}};function Bt(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===et&&e.push(t.functionCall);return e}var ce=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 ue(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var K=class extends ce{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=ue({id:i||W(),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,ae(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=ae(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let l=a.events.length-1;for(;l>=0&&!(a.events[l].timestamp<i.afterTimestamp);)l--;l>=0&&(a.events=a.events.slice(l+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(ue({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=c=>{m.warn(`Failed to append event to session ${s}: ${c}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let c of Object.keys(n.actions.stateDelta))c.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][c.replace(C.APP_PREFIX,"")]=n.actions.stateDelta[c]),c.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][c.replace(C.USER_PREFIX,"")]=n.actions.stateDelta[c]);let l=this.sessions[r][i][s];return await super.appendEvent({session:l,event:n}),l.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[C.USER_PREFIX+i]=this.userState[t][n][i];return r}};var Nt=require("@google/genai"),Ot=require("@opentelemetry/api");var Z=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new J((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=new X}){var a;let s=Ot.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let l=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!l)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof y){let f=this.agent.canonicalModel.model;if(!f.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${f} in agent: ${this.agent.name}`)}let c=new M({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:lt(),agent:this.agent,session:l,userContent:n,runConfig:i,pluginManager:this.pluginManager}),d=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:c});if(d&&(n=d),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the new_message.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(c.invocationId,l.userId,l.id,n),await this.sessionService.appendEvent({session:l,event:b({invocationId:c.invocationId,author:"user",actions:r?V({stateDelta:r}):void 0,content:n})})}c.agent=this.determineAgentForResumption(l,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:c});if(u){let f=b({invocationId:c.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:l,event:f}),yield f}else for await(let f of c.agent.runAsync(c)){f.partial||await this.sessionService.appendEvent({session:l,event:f});let T=await this.pluginManager.runOnEventCallback({invocationContext:c,event:f});T?yield T:yield f}await this.pluginManager.runAfterRunCallback({invocationContext:c})}finally{s.end()}}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let l=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:l,artifact:a}),r.parts[s]=(0,Nt.createPartFromText)(`Uploaded file: ${l}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=Bn(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){m.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){m.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 Bn(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let l=o[a],c=x(l);if(c){for(let d of c)if(d.id===t)return l}}return null}var Re=class extends Z{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new Y,sessionService:new K,memoryService:new U})}};var fe=require("@google/genai");var Ie=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 we=class extends S{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:fe.Type.OBJECT,properties:{request:{type:fe.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof y&&this.agent.outputSchema;e.response=t?{type:fe.Type.OBJECT}:{type:fe.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var d,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof y&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new Z({appName:this.agent.name,agent:this.agent,artifactService:new Ie(t),sessionService:new K,memoryService:new U,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;for await(let f of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))f.actions.stateDelta&&t.state.update(f.actions.stateDelta),a=f;if(!((u=(d=a==null?void 0:a.content)==null?void 0:d.parts)!=null&&u.length))return"";let l=this.agent instanceof y&&this.agent.outputSchema,c=a.content.parts.map(f=>f.text).filter(f=>f).join(`
|
|
32
|
-
`);return l?JSON.parse(c):c}};var
|
|
31
|
+
`),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}},Rn=new Qe,He=class extends G{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 a=r.length-1;a>=0;a--){let l=r[a];if(l.author!=="user")continue;let c=R(l);if(!c)continue;let d=!1;for(let u of c){if(u.name!==X)continue;d=!0;let f=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?f=JSON.parse(u.response.response):u.response&&(f=new q({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(i[u.id]=f)}if(d){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let l=r[a],c=x(l);if(!c)continue;let d={},u={};for(let p of c){if(!p.id||!(p.id in i))continue;let g=p.args;if(!g||!("originalFunctionCall"in g))continue;let h=g.originalFunctionCall;h.id&&(d[h.id]=i[p.id],u[h.id]=h)}if(Object.keys(d).length===0)continue;for(let p=r.length-1;p>s;p--){let g=r[p],h=R(g);if(h){for(let L of h)L.id&&L.id in d&&(delete d[L.id],delete u[L.id]);if(Object.keys(d).length===0)break}}if(Object.keys(d).length===0)continue;let f=await n.canonicalTools(new I(e)),T=Object.fromEntries(f.map(p=>[p.name,p])),A=await Ce({invocationContext:e,functionCalls:Object.values(u),toolsDict:T,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(d)),toolConfirmationDict:d});A&&(yield A);return}}},In=new He,y=class o extends k{constructor(e){var n,r,i,s,a,l,c,d,u;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(l=e.includeContents)!=null?l:"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.requestProcessors=(c=e.requestProcessors)!=null?c:[Tn,xn,En,In,Sn],this.responseProcessors=(d=e.responseProcessors)!=null?d:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((u=this.subAgents)!=null&&u.length)||this.requestProcessors.push(Rn),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)&&(m.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(this.model instanceof O)return this.model;if(typeof this.model=="string"&&this.model)return ie.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 Lt(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){m.debug(`Skipping output save for agent ${this.name}: event authored by ${e.author}`);return}if(!this.outputKey){m.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!z(e)){m.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)){m.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){m.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||z(t))break;if(t.partial){m.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 N({invocationContext:e}),s=await Lt(r,new I(e));for(let a of s)await a.processLlmRequest({toolContext:i,llmRequest:t})}if(e.endInvocation)return;let n=b({invocationId:e.invocationId,author:this.name,branch:e.branch});for await(let r of this.callLlmAsync(e,t,n))for await(let i of this.postprocess(e,t,r,n))n.id=Me(),n.timestamp=new Date().getTime(),yield i}async*postprocess(e,t,n,r){var d;for(let u of this.responseProcessors)for await(let f of u.runAsync(e,n))yield f;if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=b({...r,...n});if(i.content){let u=x(i);u!=null&&u.length&&(mt(i),i.longRunningToolIds=Array.from(gt(u,t.toolsDict)))}if(yield i,!((d=x(i))!=null&&d.length))return;let s=await vt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!s)return;let a=ht(e,s);a&&(yield a);let l=Ct({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});l&&(yield l),yield s;let c=s.actions.transferToAgent;if(c){let u=this.getAgentByName(e,c);for await(let f of u.runAsync(e))yield f}}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error(`Agent ${t} not found in the agent tree.`);return r}async*callLlmAsync(e,t,n){var s,a,l,c;let r=await this.handleBeforeModelCallback(e,t,n);if(r){yield r;return}(s=t.config)!=null||(t.config={}),(l=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[Pt]||(t.config.labels[Pt]=this.name);let i=this.canonicalModel;if((c=e.runConfig)!=null&&c.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let d=i.generateContentAsync(t);for await(let u of this.runAndHandleError(d,e,t,n)){let f=await this.handleAfterModelCallback(e,u,n);yield f!=null?f:u}}}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 a=await s({context:r,request:t});if(a)return a}}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 a=await s({context:r,response:t});if(a)return a}}async*runAndHandleError(e,t,n,r){try{for await(let i of e)yield i}catch(i){let s=new w({invocationContext:t,eventActions:r.actions});if(i instanceof Error){let a=await t.pluginManager.runOnModelErrorCallback({callbackContext:s,llmRequest:n,error:i});if(a)yield a;else{let l=JSON.parse(i.message);yield{errorCode:String(l.error.code),errorMessage:l.error.message}}}else throw m.error("Unknown error during response generation",i),i}}};var Ae=class extends k{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(e){let t=0;for(;t<this.maxIterations;){for(let n of this.subAgents){let r=!1;for await(let i of n.runAsync(e))yield i,i.actions.escalate&&(r=!0);if(r)return}t++}}async*runLiveImpl(e){throw new Error("This is not supported yet for LoopAgent.")}};var be=class extends k{async*runAsyncImpl(e){let t=this.subAgents.map(n=>n.runAsync(wn(this,n,e)));for await(let n of kn(t))yield n}async*runLiveImpl(e){throw new Error("This is not supported yet for ParallelAgent.")}};function wn(o,e,t){let n=new M(t),r=`${o.name}.${e.name}`;return n.branch=n.branch?`${n.branch}.${r}`:r,n}async function*kn(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 Xe=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Xe||{}),Y=class{constructor(e={}){this.speechConfig=e.speechConfig,this.responseModalities=e.responseModalities,this.saveInputBlobsAsArtifacts=e.saveInputBlobsAsArtifacts||!1,this.supportCfc=e.supportCfc||!1,this.streamingMode=e.streamingMode||"none",this.outputAudioTranscription=e.outputAudioTranscription,this.inputAudioTranscription=e.inputAudioTranscription,this.enableAffectiveDialog=e.enableAffectiveDialog||!1,this.realtimeInputConfig=e.realtimeInputConfig,this.maxLlmCalls=Pn(e.maxLlmCalls||500)}};function Pn(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&m.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 Ye="task_completed",Te=class extends k{async*runAsyncImpl(e){for(let t of this.subAgents)for await(let n of t.runAsync(e))yield n}async*runLiveImpl(e){for(let t of this.subAgents)t instanceof y&&((await t.canonicalTools(new I(e))).some(i=>i.name===Ye)||(t.tools.push(new B({name:Ye,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 ${Ye} 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 J=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 a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=xe(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r=`${e}/${t}/${n}/`,i=`${e}/${t}/user/`,s=[];for(let a in this.artifacts)if(a.startsWith(r)){let l=a.replace(r,"");s.push(l)}else if(a.startsWith(i)){let l=a.replace(i,"");s.push(l)}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 a=[];for(let l=0;l<s.length;l++)a.push(l);return Promise.resolve(a)}};function xe(o,e,t,n){return Ln(n)?`${o}/${e}/user/${n}`:`${o}/${e}/${t}/${n}`}function Ln(o){return o.startsWith("user:")}var U=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=Mt(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=Mt(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let l of a){if(!((s=(i=l.content)==null?void 0:i.parts)!=null&&s.length))continue;let c=l.content.parts.map(f=>f.text).filter(f=>!!f).join(" "),d=Mn(c);if(!d.size)continue;n.some(f=>d.has(f))&&r.memories.push({content:l.content,author:l.author,timestamp:Bn(l.timestamp)})}return r}};function Mt(o,e){return`${o}/${e}`}function Mn(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Bn(o){return new Date(o).toISOString()}var j=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var Ee=class extends j{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Session ID: ${e.session.id}`),this.log(` User ID: ${e.userId}`),this.log(` App Name: ${e.appName}`),this.log(` Root Agent: ${(n=e.agent.name)!=null?n:"Unknown"}`),this.log(` User Content: ${this.formatContent(t)}`),e.branch&&this.log(` Branch: ${e.branch}`)}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(` Invocation ID: ${e.invocationId}`),this.log(` Starting Agent: ${(t=e.agent.name)!=null?t:"Unknown"}`)}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${t.id}`),this.log(` Author: ${t.author}`),this.log(` Content: ${this.formatContent(t.content)}`),this.log(` Final Response: ${z(t)}`);let n=x(t);if(n.length>0){let i=n.map(s=>s.name);this.log(` Function Calls: ${i}`)}let r=R(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`;m.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 ee=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),m.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 m.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 m.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 et="adk_request_confirmation",Je="orcas_tool_call_security_check_states",Bt="This tool call needs external confirmation before completion.",tt=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(tt||{}),le=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},Se=class extends j{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new le}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:Bt};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(Je))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(Je))!=null?i:{};r[n]=t,e.state.set(Je,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:Bt};case"ALLOW":return;default:return}}};function _t(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===et&&e.push(t.functionCall);return e}var ce=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 ue(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var K=class extends ce{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=ue({id:i||Q(),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,ae(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=ae(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let l=a.events.length-1;for(;l>=0&&!(a.events[l].timestamp<i.afterTimestamp);)l--;l>=0&&(a.events=a.events.slice(l+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(ue({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=c=>{m.warn(`Failed to append event to session ${s}: ${c}`)};if(!this.sessions[r])return a(`appName ${r} not in sessions`),n;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),n;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),n;if(n.actions&&n.actions.stateDelta)for(let c of Object.keys(n.actions.stateDelta))c.startsWith(C.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][c.replace(C.APP_PREFIX,"")]=n.actions.stateDelta[c]),c.startsWith(C.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][c.replace(C.USER_PREFIX,"")]=n.actions.stateDelta[c]);let l=this.sessions[r][i][s];return await super.appendEvent({session:l,event:n}),l.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[C.APP_PREFIX+i]=this.appState[t][i];if(!this.userState[t]||!this.userState[t][n])return r;for(let i of Object.keys(this.userState[t][n]))r.state[C.USER_PREFIX+i]=this.userState[t][n][i];return r}};var Nt=require("@google/genai"),Ot=require("@opentelemetry/api");var Z=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ee((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=new Y}){var a;let s=Ot.trace.getTracer("gcp.vertex.agent").startSpan("invocation");try{let l=await this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t});if(!l)throw new Error(`Session not found: ${t}`);if(i.supportCfc&&this.agent instanceof y){let f=this.agent.canonicalModel.model;if(!f.startsWith("gemini-2"))throw new Error(`CFC is not supported for model: ${f} in agent: ${this.agent.name}`)}let c=new M({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:ct(),agent:this.agent,session:l,userContent:n,runConfig:i,pluginManager:this.pluginManager}),d=await this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:c});if(d&&(n=d),n){if(!((a=n.parts)!=null&&a.length))throw new Error("No parts in the new_message.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(c.invocationId,l.userId,l.id,n),await this.sessionService.appendEvent({session:l,event:b({invocationId:c.invocationId,author:"user",actions:r?V({stateDelta:r}):void 0,content:n})})}c.agent=this.determineAgentForResumption(l,this.agent);let u=await this.pluginManager.runBeforeRunCallback({invocationContext:c});if(u){let f=b({invocationId:c.invocationId,author:"model",content:u});await this.sessionService.appendEvent({session:l,event:f}),yield f}else for await(let f of c.agent.runAsync(c)){f.partial||await this.sessionService.appendEvent({session:l,event:f});let T=await this.pluginManager.runOnEventCallback({invocationContext:c,event:f});T?yield T:yield f}await this.pluginManager.runAfterRunCallback({invocationContext:c})}finally{s.end()}}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let l=`artifact_${e}_${s}`;await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:l,artifact:a}),r.parts[s]=(0,Nt.createPartFromText)(`Uploaded file: ${l}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let n=_n(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){m.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){m.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 _n(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let l=o[a],c=x(l);if(c){for(let d of c)if(d.id===t)return l}}return null}var Re=class extends Z{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new J,sessionService:new K,memoryService:new U})}};var fe=require("@google/genai");var Ie=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 we=class extends S{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:fe.Type.OBJECT,properties:{request:{type:fe.Type.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof y&&this.agent.outputSchema;e.response=t?{type:fe.Type.OBJECT}:{type:fe.Type.STRING}}return e}async runAsync({args:e,toolContext:t}){var d,u;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof y&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new Z({appName:this.agent.name,agent:this.agent,artifactService:new Ie(t),sessionService:new K,memoryService:new U,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;for await(let f of i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r}))f.actions.stateDelta&&t.state.update(f.actions.stateDelta),a=f;if(!((u=(d=a==null?void 0:a.content)==null?void 0:d.parts)!=null&&u.length))return"";let l=this.agent instanceof y&&this.agent.outputSchema,c=a.content.parts.map(f=>f.text).filter(f=>f).join(`
|
|
32
|
+
`);return l?JSON.parse(c):c}};var te=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 Nn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ft(o){let e=o.match(Nn);return e?e[1]:o}function $t(o){return Ft(o).startsWith("gemini-")}function Dt(o){return Ft(o).startsWith("gemini-1")}var nt=class extends S{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||[],Dt(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($t(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${t.model}`)}}},qt=new nt;var Gt=`
|
|
33
33
|
|
|
34
|
-
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,ke=class extends B{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=
|
|
34
|
+
NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,ke=class extends B{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Gt:e.description=Gt.trimStart(),e}};var Ut=require("@modelcontextprotocol/sdk/client/index.js"),jt=require("@modelcontextprotocol/sdk/client/stdio.js"),Kt=require("@modelcontextprotocol/sdk/client/streamableHttp.js");var de=class{constructor(e){this.connectionParams=e}async createSession(){let e=new Ut.Client({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new jt.StdioClientTransport(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":await e.connect(new Kt.StreamableHTTPClientTransport(new URL(this.connectionParams.url)));break;default:let t=this.connectionParams;break}return e}};var _=require("@google/genai"),ne=require("zod");var zs=ne.z.object({type:ne.z.literal("object"),properties:ne.z.record(ne.z.unknown()).optional(),required:ne.z.string().array().optional()});function On(o){switch(o.toLowerCase()){case"text":case"string":return _.Type.STRING;case"number":return _.Type.NUMBER;case"boolean":return _.Type.BOOLEAN;case"integer":return _.Type.INTEGER;case"array":return _.Type.ARRAY;case"object":return _.Type.OBJECT;default:return _.Type.TYPE_UNSPECIFIED}}function ot(o){if(!o)return;function e(t){let n=On(t.type),r={type:n,description:t.description};if(n===_.Type.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else n===_.Type.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(o)}var me=class extends S{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){let e;return e={name:this.mcpTool.name,description:this.mcpTool.description,parameters:ot(this.mcpTool.inputSchema),response:ot(this.mcpTool.outputSchema)},e}async runAsync(e){let t=await this.mcpSessionManager.createSession(),n={};return n.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(n.params)}};var rt=class extends te{constructor(e,t=[]){super(t),this.mcpSessionManager=new de(e)}async getTools(e){let n=await(await this.mcpSessionManager.createSession()).listTools();m.debug(`number of tools: ${n.tools.length}`);for(let r of n.tools)m.debug(`tool: ${r.name}`);return n.tools.map(r=>new me(r,this.mcpSessionManager))}async close(){}};0&&(module.exports={AgentTool,BaseAgent,BaseLlm,BasePlugin,BaseSessionService,BaseTool,BaseToolset,CallbackContext,FunctionTool,GOOGLE_SEARCH,Gemini,InMemoryArtifactService,InMemoryMemoryService,InMemoryPolicyEngine,InMemoryRunner,InMemorySessionService,InvocationContext,LiveRequestQueue,LlmAgent,LogLevel,LoggingPlugin,LongRunningFunctionTool,LoopAgent,MCPSessionManager,MCPTool,MCPToolset,ParallelAgent,PluginManager,PolicyOutcome,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,RunConfig,Runner,SecurityPlugin,SequentialAgent,StreamingMode,ToolConfirmation,ToolContext,createEvent,createSession,functionsExportedForTestingOnly,getAskUserConfirmationFunctionCalls,getFunctionCalls,getFunctionResponses,hasTrailingCodeExecutionResult,isFinalResponse,setLogLevel,stringifyContent,zodObjectToSchema});
|
|
35
35
|
/**
|
|
36
36
|
* @license
|
|
37
37
|
* Copyright 2025 Google LLC
|