@paean-ai/adk 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,11 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- import { createPartFromText, FinishReason, GoogleGenAI } from "@google/genai";
6
+ import {
7
+ createPartFromText,
8
+ FinishReason,
9
+ GoogleGenAI
10
+ } from "@google/genai";
7
11
  import { logger } from "../utils/logger.js";
8
12
  import { isGemini3PreviewModel } from "../utils/model_name.js";
9
13
  import { GoogleLLMVariant } from "../utils/variant_utils.js";
@@ -54,11 +58,15 @@ class Gemini extends BaseLlm {
54
58
  if (this.isGemini3Preview && useVertexAI) {
55
59
  const availableApiKey = apiKey || (canReadEnv ? process.env["GOOGLE_GENAI_API_KEY"] || process.env["GEMINI_API_KEY"] : void 0);
56
60
  if (availableApiKey) {
57
- logger.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling.");
61
+ logger.info(
62
+ "Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."
63
+ );
58
64
  useVertexAI = false;
59
65
  this.apiKey = availableApiKey;
60
66
  } else {
61
- logger.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.");
67
+ logger.warn(
68
+ "Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility."
69
+ );
62
70
  }
63
71
  }
64
72
  this.vertexai = useVertexAI;
@@ -98,7 +106,7 @@ class Gemini extends BaseLlm {
98
106
  * @yields LlmResponse: The model response.
99
107
  */
100
108
  async *generateContentAsync(llmRequest, stream = false) {
101
- var _a, _b, _c, _d, _e, _f, _g;
109
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
102
110
  this.preprocessRequest(llmRequest);
103
111
  this.maybeAppendUserContent(llmRequest);
104
112
  logger.info(
@@ -117,6 +125,7 @@ class Gemini extends BaseLlm {
117
125
  config: llmRequest.config
118
126
  });
119
127
  let thoughtText = "";
128
+ let thoughtSignature;
120
129
  let text = "";
121
130
  let usageMetadata;
122
131
  let lastResponse;
@@ -128,6 +137,9 @@ class Gemini extends BaseLlm {
128
137
  if (firstPart == null ? void 0 : firstPart.text) {
129
138
  if ("thought" in firstPart && firstPart.thought) {
130
139
  thoughtText += firstPart.text;
140
+ if ("thoughtSignature" in firstPart && firstPart.thoughtSignature) {
141
+ thoughtSignature = firstPart.thoughtSignature;
142
+ }
131
143
  } else {
132
144
  text += firstPart.text;
133
145
  }
@@ -135,7 +147,11 @@ class Gemini extends BaseLlm {
135
147
  } else if ((thoughtText || text) && (!firstPart || !firstPart.inlineData)) {
136
148
  const parts = [];
137
149
  if (thoughtText) {
138
- parts.push({ text: thoughtText, thought: true });
150
+ const thoughtPart = { text: thoughtText, thought: true };
151
+ if (thoughtSignature) {
152
+ thoughtPart.thoughtSignature = thoughtSignature;
153
+ }
154
+ parts.push(thoughtPart);
139
155
  }
140
156
  if (text) {
141
157
  parts.push(createPartFromText(text));
@@ -150,12 +166,26 @@ class Gemini extends BaseLlm {
150
166
  thoughtText = "";
151
167
  text = "";
152
168
  }
169
+ if (this.isGemini3Preview && thoughtSignature && ((_e = llmResponse.content) == null ? void 0 : _e.parts)) {
170
+ for (const part of llmResponse.content.parts) {
171
+ if (part.functionCall && !part.thoughtSignature) {
172
+ part.thoughtSignature = thoughtSignature;
173
+ }
174
+ }
175
+ }
153
176
  yield llmResponse;
177
+ if ((_g = (_f = llmResponse.content) == null ? void 0 : _f.parts) == null ? void 0 : _g.some((part) => part.functionCall)) {
178
+ thoughtSignature = void 0;
179
+ }
154
180
  }
155
- if ((text || thoughtText) && ((_f = (_e = lastResponse == null ? void 0 : lastResponse.candidates) == null ? void 0 : _e[0]) == null ? void 0 : _f.finishReason) === FinishReason.STOP) {
181
+ if ((text || thoughtText) && ((_i = (_h = lastResponse == null ? void 0 : lastResponse.candidates) == null ? void 0 : _h[0]) == null ? void 0 : _i.finishReason) === FinishReason.STOP) {
156
182
  const parts = [];
157
183
  if (thoughtText) {
158
- parts.push({ text: thoughtText, thought: true });
184
+ const thoughtPart = { text: thoughtText, thought: true };
185
+ if (thoughtSignature) {
186
+ thoughtPart.thoughtSignature = thoughtSignature;
187
+ }
188
+ parts.push(thoughtPart);
159
189
  }
160
190
  if (text) {
161
191
  parts.push({ text });
@@ -170,11 +200,28 @@ class Gemini extends BaseLlm {
170
200
  }
171
201
  } else {
172
202
  const response = await this.apiClient.models.generateContent({
173
- model: (_g = llmRequest.model) != null ? _g : this.model,
203
+ model: (_j = llmRequest.model) != null ? _j : this.model,
174
204
  contents: llmRequest.contents,
175
205
  config: llmRequest.config
176
206
  });
177
- yield createLlmResponse(response);
207
+ const llmResponse = createLlmResponse(response);
208
+ if (this.isGemini3Preview && ((_k = llmResponse.content) == null ? void 0 : _k.parts)) {
209
+ let thoughtSig;
210
+ for (const part of llmResponse.content.parts) {
211
+ if (part.thought && part.thoughtSignature) {
212
+ thoughtSig = part.thoughtSignature;
213
+ break;
214
+ }
215
+ }
216
+ if (thoughtSig) {
217
+ for (const part of llmResponse.content.parts) {
218
+ if (part.functionCall && !part.thoughtSignature) {
219
+ part.thoughtSignature = thoughtSig;
220
+ }
221
+ }
222
+ }
223
+ }
224
+ yield llmResponse;
178
225
  }
179
226
  }
180
227
  get apiClient() {
@@ -199,7 +246,9 @@ class Gemini extends BaseLlm {
199
246
  logger.debug(`Using custom API endpoint: ${this.apiEndpoint}`);
200
247
  if (this.isGemini3Preview) {
201
248
  httpOptions.apiVersion = "";
202
- logger.info(`Gemini 3 preview mode: using direct API path without version prefix`);
249
+ logger.info(
250
+ `Gemini 3 preview mode: using direct API path without version prefix`
251
+ );
203
252
  }
204
253
  }
205
254
  this._apiClient = new GoogleGenAI({
@@ -263,7 +312,9 @@ class Gemini extends BaseLlm {
263
312
  llmRequest.liveConnectConfig.systemInstruction = {
264
313
  role: "system",
265
314
  // TODO - b/425992518: validate type casting works well.
266
- parts: [createPartFromText(llmRequest.config.systemInstruction)]
315
+ parts: [
316
+ createPartFromText(llmRequest.config.systemInstruction)
317
+ ]
267
318
  };
268
319
  }
269
320
  llmRequest.liveConnectConfig.tools = (_c = llmRequest.config) == null ? void 0 : _c.tools;
package/dist/web/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- var fn=Object.defineProperty,dn=Object.defineProperties;var pn=Object.getOwnPropertyDescriptors;var Ct=Object.getOwnPropertySymbols;var mn=Object.prototype.hasOwnProperty,gn=Object.prototype.propertyIsEnumerable;var Le=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var vt=(o,e,t)=>e in o?fn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,x=(o,e)=>{for(var t in e||(e={}))mn.call(e,t)&&vt(o,t,e[t]);if(Ct)for(var t of Ct(e))gn.call(e,t)&&vt(o,t,e[t]);return o},te=(o,e)=>dn(o,pn(e));var u=function(o,e){this[0]=o,this[1]=e},h=(o,e,t)=>{var n=(s,a,c,l)=>{try{var d=t[s](a),f=(a=d.value)instanceof u,g=d.done;Promise.resolve(f?a[0]:a).then(v=>f?n(s==="return"?s:"next",a[1]?{done:v.done,value:v.value}:v,c,l):c({value:v,done:g})).catch(v=>n("throw",v,c,l))}catch(v){l(v)}},r=s=>i[s]=a=>new Promise((c,l)=>n(s,a,c,l)),i={};return t=t.apply(o,e),i[Le("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var E=(o,e,t)=>(e=o[Le("asyncIterator")])?e.call(o):(o=o[Le("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,a,c)=>(i=r.call(o,i),c=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:c}),a)))),t("next"),t("return"),e);import{trace as Tt}from"@opentelemetry/api";function $(o={}){return x({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function yt(o,e){let t=$();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 S(o={}){return te(x({},o),{id:o.id||_e(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||$(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function ne(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:P(o).length===0&&B(o).length===0&&!o.partial&&!xt(o)}function P(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function B(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 xt(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 hn(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 _e(){let o="";for(let e=0;e<8;e++)o+=At[Math.floor(Math.random()*At.length)];return o}var b=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=x(x({},this.delta),e),this.value=x(x({},this.value),e)}toRecord(){return x(x({},this.value),this.delta)}};b.APP_PREFIX="app:",b.USER_PREFIX="user:",b.TEMP_PREFIX="temp:";var _=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 b(this.invocationContext.session.state,{})}};var N=class extends _{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||$(),this._state=new b(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function he(){return typeof window<"u"}var ge="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function oe(){let o="";for(let e=0;e<ge.length;e++){let t=Math.random()*16|0;ge[e]==="x"?o+=t.toString(16):ge[e]==="y"?o+=(t&3|8).toString(16):o+=ge[e]}return o}function Et(o){return he()?window.atob(o):Buffer.from(o,"base64").toString()}var Me=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},q=class{constructor(e){this.invocationCostManager=new Me;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function bt(){return"e-".concat(oe())}var D=class{constructor(e){this.name=Cn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=yn(this),this.beforeAgentCallback=St(e.beforeAgentCallback),this.afterAgentCallback=St(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return h(this,null,function*(){let t=Tt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let a=this.createInvocationContext(e),c=yield new u(this.handleBeforeAgentCallback(a));if(c&&(yield c),a.endInvocation)return;try{for(var n=E(this.runAsyncImpl(a)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let d=i.value;yield d}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a.endInvocation)return;let l=yield new u(this.handleAfterAgentCallback(a));l&&(yield l)}finally{t.end()}})}runLive(e){return h(this,null,function*(){let t=Tt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new q(te(x({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,S({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return S({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new N({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return S({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return S({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error('Agent "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function Cn(o){if(!vn(o))throw new Error('Found invalid agent name: "'.concat(o,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.'));if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function vn(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function yn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function St(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Tn}from"@google/genai";var ue=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(e," requires oauth2 in authCredential."));if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error("Auth Scheme ".concat(e," requires both clientId and clientSecret in authCredential.oauth2."));return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var z=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var V=class extends N{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new ue(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new ue(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new z({hint:e,confirmed:!1,payload:t})}};var It=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(It||{}),re=1;function An(o){re=o}var Be=class{log(e,...t){if(!(e<re))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error("Unsupported log level: ".concat(e))}}debug(...e){re>0||console.debug(Ce(0),...e)}info(...e){re>1||console.info(Ce(1),...e)}warn(...e){re>2||console.warn(Ce(2),...e)}error(...e){re>3||console.error(Ce(3),...e)}},xn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},En={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},bn="\x1B[0m";function Ce(o){return"".concat(En[o],"[ADK ").concat(xn[o],"]:").concat(bn)}var m=new Be;var Ne="adk-",ve="adk_request_credential",ie="adk_request_confirmation",Sn={handleFunctionCallList:ye};function Oe(){return"".concat(Ne).concat(oe())}function Rt(o){let e=P(o);if(e)for(let t of e)t.id||(t.id=Oe())}function wt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ne)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ne)&&(e.functionResponse.id=void 0)}function kt(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 Pt(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:ve,args:{function_call_id:i,auth_config:s},id:Oe()};n.add(a.id),t.push({functionCall:a})}return S({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Lt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=P(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let d=(a=i.find(g=>g.id===c))!=null?a:void 0;if(!d)continue;let f={name:ie,args:{originalFunctionCall:d,toolConfirmation:l},id:Oe()};r.add(f.id),n.push({functionCall:f})}return S({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function In(o,e,t){return m.debug("callToolAsync ".concat(o.name)),await o.runAsync({args:e,toolContext:t})}async function _t({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=P(e);return await ye({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function ye({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var d;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let g;s&&f.id&&(g=s[f.id]);let{tool:v,toolContext:C}=Rn({invocationContext:o,functionCall:f,toolsDict:t,toolConfirmation:g});m.debug("execute_tool ".concat(v.name));let y=(d=f.args)!=null?d:{},p=null,A;if(p=await o.pluginManager.runBeforeToolCallback({tool:v,toolArgs:y,toolContext:C}),p==null){for(let k of n)if(p=await k({tool:v,args:y,context:C}),p)break}if(p==null)try{p=await In(v,y,C)}catch(k){if(k instanceof Error){let M=await o.pluginManager.runOnToolErrorCallback({tool:v,toolArgs:y,toolContext:C,error:k});M?p=M:A=k.message}else A=k}let R=await o.pluginManager.runAfterToolCallback({tool:v,toolArgs:y,toolContext:C,result:p});if(R==null){for(let k of r)if(R=await k({tool:v,args:y,context:C,response:p}),R)break}if(R!=null&&(p=R),v.isLongRunning&&!p)continue;A?p={error:A}:(typeof p!="object"||p==null)&&(p={result:p});let w=S({invocationId:o.invocationId,author:o.agent.name,content:Tn({functionResponse:{id:C.functionCallId,name:v.name,response:p}}),actions:C.actions,branch:o.branch});m.debug("traceToolCall",{tool:v.name,args:y,functionResponseEvent:w.id}),a.push(w)}if(!a.length)return null;let l=wn(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Rn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new V({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function wn(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=yt(n);return S({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Fe=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return h(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as en}from"zod";var Z=class{constructor(){this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var kn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Ae(o){let e=o.match(kn);return e?e[1]:o}function Mt(o){return Ae(o).startsWith("gemini-")}function Bt(o){return Ae(o).startsWith("gemini-1")}function Nt(o){return Ae(o).startsWith("gemini-2")}function Ot(o){let e=Ae(o);return e.startsWith("gemini-3")&&e.includes("preview")}var se=class extends Z{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&Nt(e.model)){e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({codeExecution:{}});return}throw new Error("Gemini code execution tool is not supported for model ".concat(e.model))}};import{Language as Pn,Outcome as Ft}from"@google/genai";function O(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Dt(o,e){var d;if(!((d=o.parts)!=null&&d.length))return"";for(let f=0;f<o.parts.length;f++){let g=o.parts[f];if(g.executableCode&&(f===o.parts.length-1||!o.parts[f+1].codeExecutionResult))return o.parts=o.parts.slice(0,f+1),g.executableCode.code}let t=o.parts.filter(f=>f.text);if(!t.length)return"";let n=O(t[0]),r=t.map(f=>f.text).join("\n"),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[1]).join("|"),a=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(s,")(?<suffix>.*?)$"),"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(o.parts=[],c&&(n.text=c,o.parts.push(n)),o.parts.push(De(l)),l):""}function De(o){return{text:o,executableCode:{code:o,language:Pn.PYTHON}}}function Gt(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:Ft.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push("Code execution result:\n".concat(o.stdout,"\n")),o.outputFiles&&e.push("Saved artifacts:\n"+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:Ft.OUTCOME_OK}}}function $t(o,e,t){var r;if(!((r=o.parts)!=null&&r.length))return;let n=o.parts[o.parts.length-1];n.executableCode?o.parts[o.parts.length-1]={text:e[0]+n.executableCode.code+e[1]}:o.parts.length==1&&n.codeExecutionResult&&(o.parts[o.parts.length-1]={text:t[0]+n.codeExecutionResult.output+t[1]},o.role="user")}var Ge="_code_execution_context",$e="execution_session_id",W="processed_input_files",Q="_code_executor_input_files",Y="_code_executor_error_counts",qe="_code_execution_results",fe=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Ge))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Ge]:O(this.context)}}getExecutionId(){if($e in this.context)return this.context[$e]}setExecutionId(e){this.context[$e]=e}getProcessedFileNames(){return W in this.context?this.context[W]:[]}addProcessedFileNames(e){W in this.context||(this.context[W]=[]),this.context[W].push(...e)}getInputFiles(){return Q in this.sessionState?this.sessionState.get(Q):[]}addInputFiles(e){Q in this.sessionState||this.sessionState.set(Q,[]),this.sessionState.get(Q).push(...e)}clearInputFiles(){Q in this.sessionState&&this.sessionState.set(Q,[]),W in this.context&&(this.context[W]=[])}getErrorCount(e){return Y in this.sessionState&&this.sessionState.get(Y)[e]||0}incrementErrorCount(e){Y in this.sessionState||this.sessionState.set(Y,{}),this.sessionState.get(Y)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(Y in this.sessionState))return;let t=this.sessionState.get(Y);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){qe in this.sessionState||this.sessionState.set(qe,{});let i=this.sessionState.get(qe);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(Ge)||{}}};var Ue="0.2.4";var Ln="google-adk",_n="gl-typescript",Mn="remote_reasoning_engine",Bn="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Nn(){let o="".concat(Ln,"/").concat(Ue);!he()&&process.env[Bn]&&(o="".concat(o,"+").concat(Mn));let e="".concat(_n,"/").concat(he()?window.navigator.userAgent:process.version);return[o,e]}function qt(){return Nn()}var je=Symbol("baseModel");function Ke(o){return typeof o=="object"&&o!==null&&je in o&&o[je]===!0}var Ut;Ut=je;var ae=class{constructor({model:e}){this[Ut]=!0;this.model=e}get trackingHeaders(){let t=qt().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};ae.supportedModels=[];function de(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function jt(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as Vt,FinishReason as Dn,GoogleGenAI as Ze}from"@google/genai";function Kt(){return On("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function On(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var xe=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}]}}}receive(){return h(this,null,function*(){throw new Error("Not Implemented.")})}async close(){this.geminiSession.close()}};function Ve(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 Gn="https://aiplatform.googleapis.com/v1/publishers/google",ce=class extends ae{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=Ot(e);let c=typeof process=="object";this.apiEndpoint=a,!this.apiEndpoint&&c&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&(this.apiEndpoint=Gn,m.info("Using Gemini 3 preview endpoint: ".concat(this.apiEndpoint)));let l=!!n;if(!l&&c){let d=process.env.GOOGLE_GENAI_USE_VERTEXAI;d&&(l=d.toLowerCase()==="true"||d==="1")}if(this.isGemini3Preview&&l){let d=t||(c?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);d?(m.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=d):m.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(c&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),c&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&c&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}generateContentAsync(e,t=!1){return h(this,null,function*(){var n,r,i,s,f,g,v;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=x(x({},e.config.httpOptions.headers),this.trackingHeaders)),t){let C=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),y="",p="",A,R;try{for(var a=E(C),c,l,d;c=!(l=yield new u(a.next())).done;c=!1){let w=l.value;R=w;let k=Ve(w);A=k.usageMetadata;let M=(s=(i=k.content)==null?void 0:i.parts)==null?void 0:s[0];if(M!=null&&M.text)"thought"in M&&M.thought?y+=M.text:p+=M.text,k.partial=!0;else if((y||p)&&(!M||!M.inlineData)){let Pe=[];y&&Pe.push({text:y,thought:!0}),p&&Pe.push(Vt(p)),yield{content:{role:"model",parts:Pe},usageMetadata:k.usageMetadata},y="",p=""}yield k}}catch(l){d=[l]}finally{try{c&&(l=a.return)&&(yield new u(l.call(a)))}finally{if(d)throw d[0]}}if((p||y)&&((g=(f=R==null?void 0:R.candidates)==null?void 0:f[0])==null?void 0:g.finishReason)===Dn.STOP){let w=[];y&&w.push({text:y,thought:!0}),p&&w.push({text:p}),yield{content:{role:"model",parts:w},usageMetadata:A}}}else{let C=yield new u(this.apiClient.models.generateContent({model:(v=e.model)!=null?v:this.model,contents:e.contents,config:e.config}));yield Ve(C)}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=x(x({},this.trackingHeaders),this.headers);if(this.vertexai)this._apiClient=new Ze({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,m.debug("Using custom API endpoint: ".concat(this.apiEndpoint)),this.isGemini3Preview&&(t.apiVersion="",m.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new Ze({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};this.apiEndpoint&&(e.baseUrl=this.apiEndpoint,this.isGemini3Preview&&(e.apiVersion="")),this._liveApiClient=new Ze({apiKey:this.apiKey,httpOptions:e})}return this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[Vt(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new xe(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)Zt(n.inlineData),Zt(n.fileData)}}};ce.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Zt(o){o&&o.displayName&&(o.displayName=void 0)}var ze=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)}},F=class F{static newLlm(e){return new(F.resolve(e))({model:e})}static _register(e,t){F.llmRegistryDict.has(e)&&m.info("Updating LLM class for ".concat(e," from ").concat(F.llmRegistryDict.get(e)," to ").concat(t)),F.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)F._register(t,e)}static resolve(e){let t=F.resolveCache.get(e);if(t)return t;for(let[n,r]of F.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return F.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};F.llmRegistryDict=new Map,F.resolveCache=new ze(32);var le=F;le.register(ce);var G=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=$n(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return Kt()}};function $n(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as qn}from"@google/genai";import{ZodObject as Un}from"zod";import{Type as L}from"@google/genai";import{z as I}from"zod";function zt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function U(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 I.ZodFirstPartyTypeKind.ZodString:n.type=L.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case I.ZodFirstPartyTypeKind.ZodNumber:n.type=L.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=L.INTEGER);return r(n);case I.ZodFirstPartyTypeKind.ZodBoolean:return n.type=L.BOOLEAN,r(n);case I.ZodFirstPartyTypeKind.ZodArray:return n.type=L.ARRAY,n.items=U(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case I.ZodFirstPartyTypeKind.ZodObject:return Ee(o);case I.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=L.STRING;else if(i==="number")n.type=L.NUMBER;else if(i==="boolean")n.type=L.BOOLEAN;else if(e.value===null)n.type=L.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case I.ZodFirstPartyTypeKind.ZodEnum:return n.type=L.STRING,n.enum=e.values,r(n);case I.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=L.STRING,n.enum=Object.values(e.values),r(n);case I.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(U),r(n);case I.ZodFirstPartyTypeKind.ZodOptional:return U(e.innerType);case I.ZodFirstPartyTypeKind.ZodNullable:let s=U(e.innerType);return r(s?x({anyOf:[s,{type:L.NULL}]},t&&{description:t}):x({type:L.NULL},t&&{description:t}));case I.ZodFirstPartyTypeKind.ZodDefault:let a=U(e.innerType);return a&&(a.default=e.defaultValue()),a;case I.ZodFirstPartyTypeKind.ZodBranded:return U(e.type);case I.ZodFirstPartyTypeKind.ZodReadonly:return U(e.innerType);case I.ZodFirstPartyTypeKind.ZodNull:return n.type=L.NULL,r(n);case I.ZodFirstPartyTypeKind.ZodAny:case I.ZodFirstPartyTypeKind.ZodUnknown:return r(x({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function Ee(o){if(o._def.typeName!==I.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=U(a);c&&(t[s]=c);let l=a,d=!1;for(;l._def.typeName===I.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===I.ZodFirstPartyTypeKind.ZodDefault;)d=!0,l=l._def.innerType;d||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==I.ZodFirstPartyTypeKind.ZodNever?i=U(r)||!0:i=o._def.unknownKeys==="passthrough",x({type:L.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function jn(o){return o===void 0?{type:qn.OBJECT,properties:{}}:zt(o)?Ee(o):o}var j=class extends G{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:jn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Un&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var K=class{};function We(o,e,t){var s,a;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||!((a=c.content.parts)!=null&&a.length)||t&&c.branch&&!t.startsWith(c.branch)||Kn(c)||Vn(c)||n.push(Yt(e,c)?Zn(c):c);let r=zn(n);r=Wn(r);let i=[];for(let c of r){let l=O(c.content);wt(l),i.push(l)}return i}function Qt(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Yt(e,r))return We(o.slice(n),e,t)}return[]}function Kn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===ve||((n=r.functionResponse)==null?void 0:n.name)===ve)return!0;return!1}function Vn(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)===ie||((n=r.functionResponse)==null?void 0:n.name)===ie)return!0;return!1}function Yt(o,e){return!!o&&e.author!==o&&e.author!=="user"}function Zn(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:"[".concat(o.author,"] said: ").concat(c.text)});else if(c.functionCall){let l=Wt(c.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(c.functionCall.name,"` with parameters: ").concat(l)})}else if(c.functionResponse){let l=Wt(c.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(c.functionResponse.name,"` returned result: ").concat(l)})}else(a=e.parts)==null||a.push(c);return S({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function Xt(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=S(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 zn(o){if(o.length===0)return o;let e=o[o.length-1],t=B(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=P(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],d=P(l);if(d!=null&&d.length){for(let f of d)if(f.id&&n.has(f.id)){i=c;let g=new Set(d.map(C=>C.id).filter(C=>!!C));if(!Array.from(n).every(C=>g.has(C)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(g).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=g;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],d=B(l);d&&d.some(f=>f.id&&n.has(f.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(Xt(s)),a}function Wn(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=B(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(B(n).length>0)continue;let r=P(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(Xt(a))}}else t.push(n)}return t}function Wt(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function Qe(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),d=l.endsWith("?");if(d&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let g=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!g)throw new Error("Artifact ".concat(f," not found."));return String(g)}if(!Xn(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(d)return"";throw new Error("Context variable not found: `".concat(l,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var Qn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ht(o){return o===""||o===void 0?!1:Qn.test(o)}var Yn=[b.APP_PREFIX,b.USER_PREFIX,b.TEMP_PREFIX];function Xn(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Ht(o):Yn.includes(e[0]+":")?Ht(e[1]):!1}var Ye=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ye||{});function Jt(o={}){return x({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Hn(o.maxLlmCalls||500)},o)}function Hn(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(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 tn="adk_agent_name";async function nn(o,e){return o instanceof G?[o]:await o.getTools(e)}var Xe=class extends K{runAsync(e,t){return h(this,null,function*(){var r;let n=e.agent;n instanceof T&&(t.model=n.canonicalModel.model,t.config=x({},(r=n.generateContentConfig)!=null?r:{}),n.outputSchema&&jt(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))})}},Jn=new Xe,He=class extends K{runAsync(e,t){return h(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),de(t,r)})}},eo=new He,Je=class extends K{runAsync(e,t){return h(this,null,function*(){let n=e.agent;if(!(n instanceof T)||!(n.rootAgent instanceof T))return;let r=n.rootAgent;if(r instanceof T&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new _(e))),a=i;s&&(a=yield new u(Qe(i,new _(e)))),de(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new _(e))),a=i;s&&(a=yield new u(Qe(i,new _(e)))),de(t,[a])}})}},to=new Je,et=class{runAsync(e,t){return h(this,null,function*(){let n=e.agent;!n||!(n instanceof T)||(n.includeContents==="default"?t.contents=We(e.session.events,n.name,e.branch):t.contents=Qt(e.session.events,n.name,e.branch))})}},no=new et,tt=class extends K{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new j({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:en.object({agentName:en.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,n){return h(this,null,function*(){if(!(t.agent instanceof T))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;de(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new V({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof T)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},oo=new tt,nt=class extends K{runAsync(e,t){return h(this,null,function*(){let n=e.agent;if(!(n instanceof T))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let a=r.length-1;a>=0;a--){let c=r[a];if(c.author!=="user")continue;let l=B(c);if(!l)continue;let d=!1;for(let f of l){if(f.name!==ie)continue;d=!0;let g=null;f.response&&Object.keys(f.response).length===1&&"response"in f.response?g=JSON.parse(f.response.response):f.response&&(g=new z({hint:f.response.hint,payload:f.response.payload,confirmed:f.response.confirmed})),f.id&&g&&(i[f.id]=g)}if(d){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=P(c);if(!l)continue;let d={},f={};for(let y of l){if(!y.id||!(y.id in i))continue;let p=y.args;if(!p||!("originalFunctionCall"in p))continue;let A=p.originalFunctionCall;A.id&&(d[A.id]=i[y.id],f[A.id]=A)}if(Object.keys(d).length===0)continue;for(let y=r.length-1;y>s;y--){let p=r[y],A=B(p);if(A){for(let R of A)R.id&&R.id in d&&(delete d[R.id],delete f[R.id]);if(Object.keys(d).length===0)break}}if(Object.keys(d).length===0)continue;let g=yield new u(n.canonicalTools(new _(e))),v=Object.fromEntries(g.map(y=>[y.name,y])),C=yield new u(ye({invocationContext:e,functionCalls:Object.values(f),toolsDict:v,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(d)),toolConfirmationDict:d}));C&&(yield C);return}})}},ro=new nt,ot=class extends K{runAsync(e,t){return h(this,null,function*(){if(e.agent instanceof T&&e.agent.codeExecutor){try{for(var n=E(so(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(e.agent.codeExecutor instanceof Z)for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],l=$t(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},be={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},io="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",rt=class{runAsync(e,t){return h(this,null,function*(){if(!t.partial)try{for(var n=E(ao(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}},ms=new rt;function so(o,e){return h(this,null,function*(){let t=o.agent;if(!(t instanceof T))return;let n=t.codeExecutor;if(!n||!(n instanceof Z))return;if(n instanceof se){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new fe(new b(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=co(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=lo(c);if(!l)return;let d={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},De(l)]};e.contents.push(O(d)),yield S({invocationId:o.invocationId,author:t.name,branch:o.branch,content:d});let f=on(o,r),g=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:g.stdout,resultStderr:g.stderr}),r.addProcessedFileNames([c.name]);let v=yield new u(rn(o,r,g));yield v,e.contents.push(O(v.content))}})}function ao(o,e){return h(this,null,function*(){let t=o.agent;if(!(t instanceof T))return;let n=t.codeExecutor;if(!n||!(n instanceof Z)||!e||!e.content||n instanceof se)return;let r=new fe(new b(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=Dt(i,n.codeBlockDelimiters);if(!s)return;yield S({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=on(o,r),c=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield yield new u(rn(o,r,c)),e.content=null})}function co(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let a=0;a<s.parts.length;a++){let c=s.parts[a],l=(r=c.inlineData)==null?void 0:r.mimeType;if(!l||!c.inlineData||!be[l])continue;let d="data_".concat(i+1,"_").concat(a+1).concat(be[l].extension);c.text="\nAvailable file: `".concat(d,"`\n");let f={name:d,content:Et(c.inlineData.data),mimeType:l};n.has(d)||(o.addInputFiles([f]),t.push(f))}}return t}function on(o,e){var r;let t=o.agent;if(!(t instanceof T)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function rn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[Gt(t)]},r=$({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(o.invocationId):e.resetErrorCount(o.invocationId);for(let i of t.outputFiles){let s=await o.artifactService.saveArtifact({appName:o.appName||"",userId:o.userId||"",sessionId:o.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return S({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function lo(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!be[o.mimeType])return;let t=e(o.name),n=be[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return"\n".concat(io,"\n\n# Load the dataframe.\n").concat(t," = ").concat(n,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var uo=new ot,T=class o extends D{constructor(e){var n,r,i,s,a,c,l,d,f;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(c=e.includeContents)!=null?c:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[Jn,eo,to,ro,no,uo],this.responseProcessors=(d=e.responseProcessors)!=null?d:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((f=this.subAgents)!=null&&f.length)||this.requestProcessors.push(oo),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 ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, subAgents must be empty to disable agent transfer."));if(this.tools&&this.tools.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(Ke(this.model))return this.model;if(typeof this.model=="string"&&this.model)return le.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 ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await nn(n,e);t.push(...r)}return t}static normalizeCallbackArray(e){return e?Array.isArray(e)?e:[e]:[]}get canonicalBeforeModelCallbacks(){return o.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return o.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return o.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return o.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(e){var r,i;if(e.author!==this.name){m.debug("Skipping output save for agent ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){m.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!ne(e)){m.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){m.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){m.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return h(this,null,function*(){for(;;){let s;try{for(var t=E(this.runOneStepAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;s=a,this.maybeSaveOutputToState(a),yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}if(!s||ne(s))break;if(s.partial){m.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return h(this,null,function*(){try{for(var t=E(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return h(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return h(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let p of this.requestProcessors)try{for(var r=E(p.runAsync(e,t)),i,s,a;i=!(s=yield new u(r.next())).done;i=!1){let A=s.value;yield A}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(a)throw a[0]}}for(let p of this.tools){let A=new V({invocationContext:e}),R=yield new u(nn(p,new _(e)));for(let w of R)yield new u(w.processLlmRequest({toolContext:A,llmRequest:t}))}if(e.endInvocation)return;let n=S({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var g=E(this.callLlmAsync(e,t,n)),v,C,y;v=!(C=yield new u(g.next())).done;v=!1){let p=C.value;try{for(var c=E(this.postprocess(e,t,p,n)),l,d,f;l=!(d=yield new u(c.next())).done;l=!1){let A=d.value;n.id=_e(),n.timestamp=new Date().getTime(),yield A}}catch(d){f=[d]}finally{try{l&&(d=c.return)&&(yield new u(d.call(c)))}finally{if(f)throw f[0]}}}}catch(C){y=[C]}finally{try{v&&(C=g.return)&&(yield new u(C.call(g)))}finally{if(y)throw y[0]}}})}postprocess(e,t,n,r){return h(this,null,function*(){var C;for(let w of this.responseProcessors)try{for(var d=E(w.runAsync(e,n)),f,g,v;f=!(g=yield new u(d.next())).done;f=!1){let k=g.value;yield k}}catch(g){v=[g]}finally{try{f&&(g=d.return)&&(yield new u(g.call(d)))}finally{if(v)throw v[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=S(x(x({},r),n));if(i.content){let w=P(i);w!=null&&w.length&&(Rt(i),i.longRunningToolIds=Array.from(kt(w,t.toolsDict)))}if(yield i,!((C=P(i))!=null&&C.length))return;let s=yield new u(_t({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let a=Pt(e,s);a&&(yield a);let c=Lt({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let w=this.getAgentByName(e,l);try{for(var y=E(w.runAsync(e)),p,A,R;p=!(A=yield new u(y.next())).done;p=!1){let k=A.value;yield k}}catch(A){R=[A]}finally{try{p&&(A=y.return)&&(yield new u(A.call(y)))}finally{if(R)throw R[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return h(this,null,function*(){var s,a,c,l,d;let r=yield new u(this.handleBeforeModelCallback(e,t,n));if(r){yield r;return}(s=t.config)!=null||(t.config={}),(c=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[tn]||(t.config.labels[tn]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let y=i.generateContentAsync(t,((d=e.runConfig)==null?void 0:d.streamingMode)==="sse");try{for(var f=E(this.runAndHandleError(y,e,t,n)),g,v,C;g=!(v=yield new u(f.next())).done;g=!1){let p=v.value;let A=yield new u(this.handleAfterModelCallback(e,p,n));yield A!=null?A:p}}catch(v){C=[v]}finally{try{g&&(v=f.return)&&(yield new u(v.call(f)))}finally{if(C)throw C[0]}}}})}async handleBeforeModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runBeforeModelCallback({callbackContext:r,llmRequest:t});if(i)return i;for(let s of this.canonicalBeforeModelCallbacks){let a=await s({context:r,request:t});if(a)return a}}async handleAfterModelCallback(e,t,n){let r=new N({invocationContext:e,eventActions:n.actions}),i=await e.pluginManager.runAfterModelCallback({callbackContext:r,llmResponse:t});if(i)return i;for(let s of this.canonicalAfterModelCallbacks){let a=await s({context:r,response:t});if(a)return a}}runAndHandleError(e,t,n,r){return h(this,null,function*(){try{try{for(var i=E(e),s,a,c;s=!(a=yield new u(i.next())).done;s=!1){let l=a.value;yield l}}catch(a){c=[a]}finally{try{s&&(a=i.return)&&(yield new u(a.call(i)))}finally{if(c)throw c[0]}}}catch(l){let d=new N({invocationContext:t,eventActions:r.actions});if(l instanceof Error){let f=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:d,llmRequest:n,error:l}));if(f)yield f;else{let g=JSON.parse(l.message);yield{errorCode:String(g.error.code),errorMessage:g.error.message}}}else throw m.error("Unknown error during response generation",l),l}})}};var it=class extends D{constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return h(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let a of this.subAgents){let c=!1;try{for(var n=E(a.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let l=i.value;yield l,l.actions.escalate&&(c=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(c)return}t++}})}runLiveImpl(e){return h(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var st=class extends D{runAsyncImpl(e){return h(this,null,function*(){let t=this.subAgents.map(a=>a.runAsync(fo(this,a,e)));try{for(var n=E(po(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return h(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function fo(o,e,t){let n=new q(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function po(o){return h(this,null,function*(){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=yield new u(Promise.race(e.values()));if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}})}var at="task_completed",ct=class extends D{runAsyncImpl(e){return h(this,null,function*(){for(let s of this.subAgents)try{for(var t=E(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return h(this,null,function*(){for(let s of this.subAgents)s instanceof T&&((yield new u(s.canonicalTools(new _(e)))).some(l=>l.name===at)||(s.tools.push(new j({name:at,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(at," function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.")));for(let s of this.subAgents)try{for(var t=E(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var pe=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=Te(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=Te(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="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(t,"/user/"),s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=Te(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=Te(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}};function Te(o,e,t,n){return mo(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function mo(o){return o.startsWith("user:")}var X=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=sn(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=sn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(g=>g.text).filter(g=>!!g).join(" "),d=go(l);if(!d.size)continue;n.some(g=>d.has(g))&&r.memories.push({content:c.content,author:c.author,timestamp:ho(c.timestamp)})}return r}};function sn(o,e){return"".concat(o,"/").concat(e)}function go(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function ho(o){return new Date(o).toISOString()}var H=class{constructor(e){this.name=e}async onUserMessageCallback({invocationContext:e,userMessage:t}){}async beforeRunCallback({invocationContext:e}){}async onEventCallback({invocationContext:e,event:t}){}async afterRunCallback({invocationContext:e}){}async beforeAgentCallback({agent:e,callbackContext:t}){}async afterAgentCallback({agent:e,callbackContext:t}){}async beforeModelCallback({callbackContext:e,llmRequest:t}){}async afterModelCallback({callbackContext:e,llmResponse:t}){}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){}};var lt=class extends H{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((n=e.agent.name)!=null?n:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(ne(t)));let n=P(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=B(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");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: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var me=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),m.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return m.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw 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 cn="adk_request_confirmation",ut="orcas_tool_call_security_check_states",an="This tool call needs external confirmation before completion.",ln=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(ln||{}),Se=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},ft=class extends H{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Se}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:an};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(ut))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(ut))!=null?i:{};r[n]=t,e.state.set(ut,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:an};case"ALLOW":return;default:return}}};function Co(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===cn&&e.push(t.functionCall);return e}var Ie=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(b.TEMP_PREFIX)||(e.state[n]=r)}};function Re(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var J=class extends Ie{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=Re({id:i||oe(),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,O(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=O(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(Re({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{m.warn("Failed to append event to session ".concat(s,": ").concat(l))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(b.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(b.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(b.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(b.USER_PREFIX,"")]=n.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:n}),c.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[b.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[b.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as vo}from"@google/genai";import{trace as yo}from"@opentelemetry/api";var ee=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new me((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return h(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var c;i=Jt(i);let a=yo.getTracer("gcp.vertex.agent").startSpan("invocation");try{let v=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!v)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof T){let A=this.agent.canonicalModel.model;if(!A.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(A," in agent: ").concat(this.agent.name))}let C=new q({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:bt(),agent:this.agent,session:v,userContent:n,runConfig:i,pluginManager:this.pluginManager}),y=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:C}));if(y&&(n=y),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(C.invocationId,v.userId,v.id,n))),yield new u(this.sessionService.appendEvent({session:v,event:S({invocationId:C.invocationId,author:"user",actions:r?$({stateDelta:r}):void 0,content:n})}))}C.agent=this.determineAgentForResumption(v,this.agent);let p=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:C}));if(p){let A=S({invocationId:C.invocationId,author:"model",content:p});yield new u(this.sessionService.appendEvent({session:v,event:A})),yield A}else try{for(var l=E(C.agent.runAsync(C)),d,f,g;d=!(f=yield new u(l.next())).done;d=!1){let A=f.value;A.partial||(yield new u(this.sessionService.appendEvent({session:v,event:A})));let R=yield new u(this.pluginManager.runOnEventCallback({invocationContext:C,event:A}));R?yield R:yield A}}catch(f){g=[f]}finally{try{d&&(f=l.return)&&(yield new u(f.call(l)))}finally{if(g)throw g[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:C}))}finally{a.end()}})}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=vo("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Ao(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){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: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof T)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Ao(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let c=o[a],l=P(c);if(l){for(let d of l)if(d.id===t)return c}}return null}var dt=class extends ee{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new pe,sessionService:new J,memoryService:new X})}};import{Type as ke}from"@google/genai";var we=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(e){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var pt=class extends G{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 T&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:ke.OBJECT,properties:{request:{type:ke.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof T&&this.agent.outputSchema;e.response=t?{type:ke.OBJECT}:{type:ke.STRING}}return e}async runAsync({args:e,toolContext:t}){var C,y;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof T&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new ee({appName:this.agent.name,agent:this.agent,artifactService:new we(t),sessionService:new J,memoryService:new X,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;try{for(var d=E(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),f,g,v;f=!(g=await d.next()).done;f=!1){let p=g.value;p.actions.stateDelta&&t.state.update(p.actions.stateDelta),a=p}}catch(g){v=[g]}finally{try{f&&(g=d.return)&&await g.call(d)}finally{if(v)throw v[0]}}if(!((y=(C=a==null?void 0:a.content)==null?void 0:C.parts)!=null&&y.length))return"";let c=this.agent instanceof T&&this.agent.outputSchema,l=a.content.parts.map(p=>p.text).filter(p=>p).join("\n");return c?JSON.parse(l):l}};var mt=class{constructor(e){this.toolFilter=e}isToolSelected(e,t){return this.toolFilter?typeof this.toolFilter=="function"?this.toolFilter(e,t):Array.isArray(this.toolFilter)?this.toolFilter.includes(e.name):!1:!0}async processLlmRequest(e,t){}};var gt=class extends G{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||[],Bt(t.model)){if(t.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");t.config.tools.push({googleSearchRetrieval:{}});return}if(Mt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},xo=new gt;var un="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",ht=class extends j{constructor(e){super(te(x({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=un:e.description=un.trimStart(),e}};export{pt as AgentTool,D as BaseAgent,ae as BaseLlm,H as BasePlugin,Ie as BaseSessionService,G as BaseTool,mt as BaseToolset,se as BuiltInCodeExecutor,N as CallbackContext,j as FunctionTool,xo as GOOGLE_SEARCH,ce as Gemini,pe as InMemoryArtifactService,X as InMemoryMemoryService,Se as InMemoryPolicyEngine,dt as InMemoryRunner,J as InMemorySessionService,q as InvocationContext,le as LLMRegistry,Fe as LiveRequestQueue,T as LlmAgent,It as LogLevel,lt as LoggingPlugin,ht as LongRunningFunctionTool,it as LoopAgent,st as ParallelAgent,me as PluginManager,ln as PolicyOutcome,cn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,ee as Runner,ft as SecurityPlugin,ct as SequentialAgent,b as State,Ye as StreamingMode,z as ToolConfirmation,V as ToolContext,S as createEvent,$ as createEventActions,Re as createSession,Sn as functionsExportedForTestingOnly,Co as getAskUserConfirmationFunctionCalls,P as getFunctionCalls,B as getFunctionResponses,xt as hasTrailingCodeExecutionResult,Ke as isBaseLlm,ne as isFinalResponse,An as setLogLevel,hn as stringifyContent,Ue as version,Ee as zodObjectToSchema};
7
+ var Cn=Object.defineProperty,vn=Object.defineProperties;var yn=Object.getOwnPropertyDescriptors;var bt=Object.getOwnPropertySymbols;var An=Object.prototype.hasOwnProperty,xn=Object.prototype.propertyIsEnumerable;var Ne=(o,e)=>(e=Symbol[o])?e:Symbol.for("Symbol."+o);var Tt=(o,e,t)=>e in o?Cn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,A=(o,e)=>{for(var t in e||(e={}))An.call(e,t)&&Tt(o,t,e[t]);if(bt)for(var t of bt(e))xn.call(e,t)&&Tt(o,t,e[t]);return o},ie=(o,e)=>vn(o,yn(e));var u=function(o,e){this[0]=o,this[1]=e},g=(o,e,t)=>{var n=(s,a,c,l)=>{try{var f=t[s](a),d=(a=f.value)instanceof u,C=f.done;Promise.resolve(d?a[0]:a).then(y=>d?n(s==="return"?s:"next",a[1]?{done:y.done,value:y.value}:y,c,l):c({value:y,done:C})).catch(y=>n("throw",y,c,l))}catch(y){l(y)}},r=s=>i[s]=a=>new Promise((c,l)=>n(s,a,c,l)),i={};return t=t.apply(o,e),i[Ne("asyncIterator")]=()=>i,r("next"),r("throw"),r("return"),i};var b=(o,e,t)=>(e=o[Ne("asyncIterator")])?e.call(o):(o=o[Ne("iterator")](),e={},t=(n,r)=>(r=o[n])&&(e[n]=i=>new Promise((s,a,c)=>(i=r.call(o,i),c=i.done,Promise.resolve(i.value).then(l=>s({value:l,done:c}),a)))),t("next"),t("return"),e);import{trace as Pt}from"@opentelemetry/api";function U(o={}){return A({stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{}},o)}function St(o,e){let t=U();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 R(o={}){return ie(A({},o),{id:o.id||Oe(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||U(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()})}function se(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:L(o).length===0&&N(o).length===0&&!o.partial&&!Rt(o)}function L(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function N(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function Rt(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function En(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 It="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function Oe(){let o="";for(let e=0;e<8;e++)o+=It[Math.floor(Math.random()*It.length)];return o}var T=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=A(A({},this.delta),e),this.value=A(A({},this.value),e)}toRecord(){return A(A({},this.value),this.delta)}};T.APP_PREFIX="app:",T.USER_PREFIX="user:",T.TEMP_PREFIX="temp:";var M=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new T(this.invocationContext.session.state,{})}};var O=class extends M{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||U(),this._state=new T(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function xe(){return typeof window<"u"}var Ae="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function ae(){let o="";for(let e=0;e<Ae.length;e++){let t=Math.random()*16|0;Ae[e]==="x"?o+=t.toString(16):Ae[e]==="y"?o+=(t&3|8).toString(16):o+=Ae[e]}return o}function wt(o){return xe()?window.atob(o):Buffer.from(o,"base64").toString()}var Fe=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error("Max number of llm calls limit of ".concat(e.maxLlmCalls," exceeded"))}},K=class{constructor(e){this.invocationCostManager=new Fe;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 kt(){return"e-".concat(ae())}var $=class{constructor(e){this.name=bn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Sn(this),this.beforeAgentCallback=Lt(e.beforeAgentCallback),this.afterAgentCallback=Lt(e.afterAgentCallback),this.setParentAgentForSubAgents()}runAsync(e){return g(this,null,function*(){let t=Pt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{let a=this.createInvocationContext(e),c=yield new u(this.handleBeforeAgentCallback(a));if(c&&(yield c),a.endInvocation)return;try{for(var n=b(this.runAsyncImpl(a)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let f=i.value;yield f}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(a.endInvocation)return;let l=yield new u(this.handleAfterAgentCallback(a));l&&(yield l)}finally{t.end()}})}runLive(e){return g(this,null,function*(){let t=Pt.getTracer("gcp.vertex.agent").startSpan("agent_run [".concat(this.name,"]"));try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}})}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new K(ie(A({},e),{agent:this}))}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new O({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,R({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return R({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new O({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return R({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return R({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error('Agent "'.concat(e.name,'" already has a parent agent, current parent: "').concat(e.parentAgent.name,'", trying to add: "').concat(this.name,'"'));e.parentAgent=this}}};function bn(o){if(!Tn(o))throw new Error('Found invalid agent name: "'.concat(o,'". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.'));if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function Tn(o){return new RegExp("^[\\p{ID_Start}$_][\\p{ID_Continue}$_]*$","u").test(o)}function Sn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Lt(o){return o?Array.isArray(o)?o:[o]:[]}import{createUserContent as Pn}from"@google/genai";var me=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error("Auth Scheme ".concat(e," requires authCredential."));if(!this.authConfig.rawAuthCredential.oauth2)throw new Error("Auth Scheme ".concat(e," requires oauth2 in authCredential."));if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error("Auth Scheme ".concat(e," requires both clientId and clientSecret in authCredential.oauth2."));return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var Y=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var W=class extends O{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new me(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new me(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new Y({hint:e,confirmed:!1,payload:t})}};var _t=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(_t||{}),ce=1;function In(o){ce=o}var De=class{log(e,...t){if(!(e<ce))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error("Unsupported log level: ".concat(e))}}debug(...e){ce>0||console.debug(Ee(0),...e)}info(...e){ce>1||console.info(Ee(1),...e)}warn(...e){ce>2||console.warn(Ee(2),...e)}error(...e){ce>3||console.error(Ee(3),...e)}},Rn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},wn={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},kn="\x1B[0m";function Ee(o){return"".concat(wn[o],"[ADK ").concat(Rn[o],"]:").concat(kn)}var m=new De;var Ge="adk-",be="adk_request_credential",le="adk_request_confirmation",Ln={handleFunctionCallList:Te};function $e(){return"".concat(Ge).concat(ae())}function Mt(o){let e=L(o);if(e)for(let t of e)t.id||(t.id=$e())}function Bt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ge)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ge)&&(e.functionResponse.id=void 0)}function Nt(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 Ot(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:be,args:{function_call_id:i,auth_config:s},id:$e()};n.add(a.id),t.push({functionCall:a})}return R({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Ft({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=L(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(C=>C.id===c))!=null?a:void 0;if(!f)continue;let d={name:le,args:{originalFunctionCall:f,toolConfirmation:l},id:$e()};r.add(d.id),n.push({functionCall:d})}return R({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function _n(o,e,t){return m.debug("callToolAsync ".concat(o.name)),await o.runAsync({args:e,toolContext:t})}async function Dt({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=L(e);return await Te({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Te({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(d=>!i||d.id&&i.has(d.id));for(let d of c){let C;s&&d.id&&(C=s[d.id]);let{tool:y,toolContext:h}=Mn({invocationContext:o,functionCall:d,toolsDict:t,toolConfirmation:C});m.debug("execute_tool ".concat(y.name));let x=(f=d.args)!=null?f:{},p=null,v;if(p=await o.pluginManager.runBeforeToolCallback({tool:y,toolArgs:x,toolContext:h}),p==null){for(let S of n)if(p=await S({tool:y,args:x,context:h}),p)break}if(p==null)try{p=await _n(y,x,h)}catch(S){if(S instanceof Error){let P=await o.pluginManager.runOnToolErrorCallback({tool:y,toolArgs:x,toolContext:h,error:S});P?p=P:v=S.message}else v=S}let k=await o.pluginManager.runAfterToolCallback({tool:y,toolArgs:x,toolContext:h,result:p});if(k==null){for(let S of r)if(k=await S({tool:y,args:x,context:h,response:p}),k)break}if(k!=null&&(p=k),y.isLongRunning&&!p)continue;v?p={error:v}:(typeof p!="object"||p==null)&&(p={result:p});let E=R({invocationId:o.invocationId,author:o.agent.name,content:Pn({functionResponse:{id:h.functionCallId,name:y.name,response:p}}),actions:h.actions,branch:o.branch});m.debug("traceToolCall",{tool:y.name,args:x,functionResponseEvent:E.id}),a.push(E)}if(!a.length)return null;let l=Bn(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function Mn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error("Function ".concat(e.name," is not found in the toolsDict."));let r=new W({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Bn(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 R({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var qe=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}[Symbol.asyncIterator](){return g(this,null,function*(){for(;;){let e=yield new u(this.get());if(yield e,e.close)break}})}};import{z as an}from"zod";var Q=class{constructor(){this.optimizeDataFile=!1;this.stateful=!1;this.errorRetryAttempts=2;this.codeBlockDelimiters=[["```tool_code\n","\n```"],["```python\n","\n```"]];this.executionResultDelimiters=["```tool_output\n","\n```"]}};var Nn="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function Se(o){let e=o.match(Nn);return e?e[1]:o}function Gt(o){return Se(o).startsWith("gemini-")}function $t(o){return Se(o).startsWith("gemini-1")}function qt(o){return Se(o).startsWith("gemini-2")}function Ut(o){let e=Se(o);return e.startsWith("gemini-3")&&e.includes("preview")}var ue=class extends Q{executeCode(e){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(e){if(e.model&&qt(e.model)){e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({codeExecution:{}});return}throw new Error("Gemini code execution tool is not supported for model ".concat(e.model))}};import{Language as On,Outcome as jt}from"@google/genai";function F(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Kt(o,e){var f;if(!((f=o.parts)!=null&&f.length))return"";for(let d=0;d<o.parts.length;d++){let C=o.parts[d];if(C.executableCode&&(d===o.parts.length-1||!o.parts[d+1].codeExecutionResult))return o.parts=o.parts.slice(0,d+1),C.executableCode.code}let t=o.parts.filter(d=>d.text);if(!t.length)return"";let n=F(t[0]),r=t.map(d=>d.text).join("\n"),i=e.map(d=>d[0]).join("|"),s=e.map(d=>d[1]).join("|"),a=new RegExp("?<prefix>.*?)(".concat(i,")(?<codeStr>.*?)(").concat(s,")(?<suffix>.*?)$"),"s").exec(r),{prefix:c,codeStr:l}=(a==null?void 0:a.groups)||{};return l?(o.parts=[],c&&(n.text=c,o.parts.push(n)),o.parts.push(Ue(l)),l):""}function Ue(o){return{text:o,executableCode:{code:o,language:On.PYTHON}}}function Vt(o){if(o.stderr)return{text:o.stderr,codeExecutionResult:{outcome:jt.OUTCOME_FAILED}};let e=[];return(o.stdout||!o.outputFiles)&&e.push("Code execution result:\n".concat(o.stdout,"\n")),o.outputFiles&&e.push("Saved artifacts:\n"+o.outputFiles.map(t=>t.name).join(", ")),{text:e.join("\n\n"),codeExecutionResult:{outcome:jt.OUTCOME_OK}}}function Zt(o,e,t){var r;if(!((r=o.parts)!=null&&r.length))return;let n=o.parts[o.parts.length-1];n.executableCode?o.parts[o.parts.length-1]={text:e[0]+n.executableCode.code+e[1]}:o.parts.length==1&&n.codeExecutionResult&&(o.parts[o.parts.length-1]={text:t[0]+n.codeExecutionResult.output+t[1]},o.role="user")}var je="_code_execution_context",Ke="execution_session_id",X="processed_input_files",H="_code_executor_input_files",J="_code_executor_error_counts",Ve="_code_execution_results",ge=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(je))!=null?t:{},this.sessionState=e}getStateDelta(){return{[je]:F(this.context)}}getExecutionId(){if(Ke in this.context)return this.context[Ke]}setExecutionId(e){this.context[Ke]=e}getProcessedFileNames(){return X in this.context?this.context[X]:[]}addProcessedFileNames(e){X in this.context||(this.context[X]=[]),this.context[X].push(...e)}getInputFiles(){return H in this.sessionState?this.sessionState.get(H):[]}addInputFiles(e){H in this.sessionState||this.sessionState.set(H,[]),this.sessionState.get(H).push(...e)}clearInputFiles(){H in this.sessionState&&this.sessionState.set(H,[]),X in this.context&&(this.context[X]=[])}getErrorCount(e){return J in this.sessionState&&this.sessionState.get(J)[e]||0}incrementErrorCount(e){J in this.sessionState||this.sessionState.set(J,{}),this.sessionState.get(J)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(J in this.sessionState))return;let t=this.sessionState.get(J);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:n,resultStderr:r}){Ve in this.sessionState||this.sessionState.set(Ve,{});let i=this.sessionState.get(Ve);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:n,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(e){return this.sessionState.get(je)||{}}};var Ze="0.2.4";var Fn="google-adk",Dn="gl-typescript",Gn="remote_reasoning_engine",$n="GOOGLE_CLOUD_AGENT_ENGINE_ID";function qn(){let o="".concat(Fn,"/").concat(Ze);!xe()&&process.env[$n]&&(o="".concat(o,"+").concat(Gn));let e="".concat(Dn,"/").concat(xe()?window.navigator.userAgent:process.version);return[o,e]}function zt(){return qn()}var ze=Symbol("baseModel");function We(o){return typeof o=="object"&&o!==null&&ze in o&&o[ze]===!0}var Wt;Wt=ze;var fe=class{constructor({model:e}){this[Wt]=!0;this.model=e}get trackingHeaders(){let t=zt().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};fe.supportedModels=[];function he(o,e){o.config||(o.config={});let t=e.join("\n\n");o.config.systemInstruction?o.config.systemInstruction+="\n\n"+t:o.config.systemInstruction=t}function Qt(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as Xt,FinishReason as Kn,GoogleGenAI as Ye}from"@google/genai";function Yt(){return Un("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Un(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(o.toLowerCase())}var Ie=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}]}}}receive(){return g(this,null,function*(){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 Vn="https://aiplatform.googleapis.com/v1/publishers/google",de=class extends fe{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=Ut(e);let c=typeof process=="object";this.apiEndpoint=a,!this.apiEndpoint&&c&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),!this.apiEndpoint&&this.isGemini3Preview&&(this.apiEndpoint=Vn,m.info("Using Gemini 3 preview endpoint: ".concat(this.apiEndpoint)));let l=!!n;if(!l&&c){let f=process.env.GOOGLE_GENAI_USE_VERTEXAI;f&&(l=f.toLowerCase()==="true"||f==="1")}if(this.isGemini3Preview&&l){let f=t||(c?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);f?(m.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),l=!1,this.apiKey=f):m.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=l,this.vertexai){if(c&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),c&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&c&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}generateContentAsync(e,t=!1){return g(this,null,function*(){var n,r,i,s,a,c,l,h,x,p,v;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),m.info("Sending out request, model: ".concat(e.model,", backend: ").concat(this.apiBackend,", stream: ").concat(t)),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers=A(A({},e.config.httpOptions.headers),this.trackingHeaders)),t){let k=yield new u(this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config})),E="",S,P="",xt,ye;try{for(var f=b(k),d,C,y;d=!(C=yield new u(f.next())).done;d=!1){let re=C.value;ye=re;let G=Qe(re);xt=G.usageMetadata;let B=(s=(i=G.content)==null?void 0:i.parts)==null?void 0:s[0];if(B!=null&&B.text)"thought"in B&&B.thought?(E+=B.text,"thoughtSignature"in B&&B.thoughtSignature&&(S=B.thoughtSignature)):P+=B.text,G.partial=!0;else if((E||P)&&(!B||!B.inlineData)){let j=[];if(E){let Et={text:E,thought:!0};S&&(Et.thoughtSignature=S),j.push(Et)}P&&j.push(Xt(P)),yield{content:{role:"model",parts:j},usageMetadata:G.usageMetadata},E="",P=""}if(this.isGemini3Preview&&S&&((a=G.content)!=null&&a.parts))for(let j of G.content.parts)j.functionCall&&!j.thoughtSignature&&(j.thoughtSignature=S);yield G,(l=(c=G.content)==null?void 0:c.parts)!=null&&l.some(j=>j.functionCall)&&(S=void 0)}}catch(C){y=[C]}finally{try{d&&(C=f.return)&&(yield new u(C.call(f)))}finally{if(y)throw y[0]}}if((P||E)&&((x=(h=ye==null?void 0:ye.candidates)==null?void 0:h[0])==null?void 0:x.finishReason)===Kn.STOP){let re=[];if(E){let G={text:E,thought:!0};S&&(G.thoughtSignature=S),re.push(G)}P&&re.push({text:P}),yield{content:{role:"model",parts:re},usageMetadata:xt}}}else{let k=yield new u(this.apiClient.models.generateContent({model:(p=e.model)!=null?p:this.model,contents:e.contents,config:e.config})),E=Qe(k);if(this.isGemini3Preview&&((v=E.content)!=null&&v.parts)){let S;for(let P of E.content.parts)if(P.thought&&P.thoughtSignature){S=P.thoughtSignature;break}if(S)for(let P of E.content.parts)P.functionCall&&!P.thoughtSignature&&(P.thoughtSignature=S)}yield E}})}get apiClient(){if(this._apiClient)return this._apiClient;let e=A(A({},this.trackingHeaders),this.headers);if(this.vertexai)this._apiClient=new Ye({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,m.debug("Using custom API endpoint: ".concat(this.apiEndpoint)),this.isGemini3Preview&&(t.apiVersion="",m.info("Gemini 3 preview mode: using direct API path without version prefix"))),this._apiClient=new Ye({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};this.apiEndpoint&&(e.baseUrl=this.apiEndpoint,this.isGemini3Preview&&(e.apiVersion="")),this._liveApiClient=new Ye({apiKey:this.apiKey,httpOptions:e})}return this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[Xt(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 Ie(t)}preprocessRequest(e){if(this.apiBackend==="GEMINI_API"&&(e.config&&(e.config.labels=void 0),e.contents)){for(let t of e.contents)if(t.parts)for(let n of t.parts)Ht(n.inlineData),Ht(n.fileData)}}};de.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function Ht(o){o&&o.displayName&&(o.displayName=void 0)}var Xe=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)}},D=class D{static newLlm(e){return new(D.resolve(e))({model:e})}static _register(e,t){D.llmRegistryDict.has(e)&&m.info("Updating LLM class for ".concat(e," from ").concat(D.llmRegistryDict.get(e)," to ").concat(t)),D.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)D._register(t,e)}static resolve(e){let t=D.resolveCache.get(e);if(t)return t;for(let[n,r]of D.llmRegistryDict.entries())if(new RegExp("^".concat(n instanceof RegExp?n.source:n,"$"),n instanceof RegExp?n.flags:void 0).test(e))return D.resolveCache.set(e,r),r;throw new Error("Model ".concat(e," not found."))}};D.llmRegistryDict=new Map,D.resolveCache=new Xe(32);var pe=D;pe.register(de);var q=class{constructor(e){var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=Zn(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return Yt()}};function Zn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as zn}from"@google/genai";import{ZodObject as Wn}from"zod";import{Type as _}from"@google/genai";import{z as w}from"zod";function Jt(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function V(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 w.ZodFirstPartyTypeKind.ZodString:n.type=_.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case w.ZodFirstPartyTypeKind.ZodNumber:n.type=_.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=_.INTEGER);return r(n);case w.ZodFirstPartyTypeKind.ZodBoolean:return n.type=_.BOOLEAN,r(n);case w.ZodFirstPartyTypeKind.ZodArray:return n.type=_.ARRAY,n.items=V(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case w.ZodFirstPartyTypeKind.ZodObject:return Re(o);case w.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=_.STRING;else if(i==="number")n.type=_.NUMBER;else if(i==="boolean")n.type=_.BOOLEAN;else if(e.value===null)n.type=_.NULL;else throw new Error("Unsupported ZodLiteral value type: ".concat(i));return r(n);case w.ZodFirstPartyTypeKind.ZodEnum:return n.type=_.STRING,n.enum=e.values,r(n);case w.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=_.STRING,n.enum=Object.values(e.values),r(n);case w.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(V),r(n);case w.ZodFirstPartyTypeKind.ZodOptional:return V(e.innerType);case w.ZodFirstPartyTypeKind.ZodNullable:let s=V(e.innerType);return r(s?A({anyOf:[s,{type:_.NULL}]},t&&{description:t}):A({type:_.NULL},t&&{description:t}));case w.ZodFirstPartyTypeKind.ZodDefault:let a=V(e.innerType);return a&&(a.default=e.defaultValue()),a;case w.ZodFirstPartyTypeKind.ZodBranded:return V(e.type);case w.ZodFirstPartyTypeKind.ZodReadonly:return V(e.innerType);case w.ZodFirstPartyTypeKind.ZodNull:return n.type=_.NULL,r(n);case w.ZodFirstPartyTypeKind.ZodAny:case w.ZodFirstPartyTypeKind.ZodUnknown:return r(A({},t&&{description:t}));default:throw new Error("Unsupported Zod type: ".concat(e.typeName))}}function Re(o){if(o._def.typeName!==w.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=V(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===w.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===w.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==w.ZodFirstPartyTypeKind.ZodNever?i=V(r)||!0:i=o._def.unknownKeys==="passthrough",A({type:_.OBJECT,properties:t,required:n.length>0?n:[]},o._def.description?{description:o._def.description}:{})}function Qn(o){return o===void 0?{type:zn.OBJECT,properties:{}}:Jt(o)?Re(o):o}var Z=class extends q{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:Qn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Wn&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error("Error in tool '".concat(this.name,"': ").concat(n))}}};var z=class{};function He(o,e,t){var s,a;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||!((a=c.content.parts)!=null&&a.length)||t&&c.branch&&!t.startsWith(c.branch)||Yn(c)||Xn(c)||n.push(nn(e,c)?Hn(c):c);let r=Jn(n);r=eo(r);let i=[];for(let c of r){let l=F(c.content);Bt(l),i.push(l)}return i}function tn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||nn(e,r))return He(o.slice(n),e,t)}return[]}function Yn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===be||((n=r.functionResponse)==null?void 0:n.name)===be)return!0;return!1}function Xn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===le||((n=r.functionResponse)==null?void 0:n.name)===le)return!0;return!1}function nn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function Hn(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:"[".concat(o.author,"] said: ").concat(c.text)});else if(c.functionCall){let l=en(c.functionCall.args);(i=e.parts)==null||i.push({text:"[".concat(o.author,"] called tool `").concat(c.functionCall.name,"` with parameters: ").concat(l)})}else if(c.functionResponse){let l=en(c.functionResponse.response);(s=e.parts)==null||s.push({text:"[".concat(o.author,"] tool `").concat(c.functionResponse.name,"` returned result: ").concat(l)})}else(a=e.parts)==null||a.push(c);return R({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function on(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=R(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 Jn(o){if(o.length===0)return o;let e=o[o.length-1],t=N(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=L(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],f=L(l);if(f!=null&&f.length){for(let d of f)if(d.id&&n.has(d.id)){i=c;let C=new Set(f.map(h=>h.id).filter(h=>!!h));if(!Array.from(n).every(h=>C.has(h)))throw new Error("Last response event should only contain the responses for the function calls in the same function call event. Function"+" call ids found : ".concat(Array.from(C).join(", "),", function response")+" ids provided: ".concat(Array.from(n).join(", ")));n=C;break}}}if(i===-1)throw new Error("No function call event found for function responses ids: ".concat(Array.from(n).join(", ")));let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=N(l);f&&f.some(d=>d.id&&n.has(d.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(on(s)),a}function eo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=N(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(N(n).length>0)continue;let r=L(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(on(a))}}else t.push(n)}return t}function en(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch(e){return String(o)}}async function Je(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let d=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let C=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:d});if(!C)throw new Error("Artifact ".concat(d," not found."));return String(C)}if(!oo(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error("Context variable not found: `".concat(l,"`."))}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var to=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function rn(o){return o===""||o===void 0?!1:to.test(o)}var no=[T.APP_PREFIX,T.USER_PREFIX,T.TEMP_PREFIX];function oo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?rn(o):no.includes(e[0]+":")?rn(e[1]):!1}var et=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(et||{});function sn(o={}){return A({saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:ro(o.maxLlmCalls||500)},o)}function ro(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error("maxLlmCalls should be less than ".concat(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 cn="adk_agent_name";async function ln(o,e){return o instanceof q?[o]:await o.getTools(e)}var tt=class extends z{runAsync(e,t){return g(this,null,function*(){var r;let n=e.agent;n instanceof I&&(t.model=n.canonicalModel.model,t.config=A({},(r=n.generateContentConfig)!=null?r:{}),n.outputSchema&&Qt(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))})}},io=new tt,nt=class extends z{runAsync(e,t){return g(this,null,function*(){let n=e.agent,r=['You are an agent. Your internal name is "'.concat(n.name,'".')];n.description&&r.push('The description about you is "'.concat(n.description,'"')),he(t,r)})}},so=new nt,ot=class extends z{runAsync(e,t){return g(this,null,function*(){let n=e.agent;if(!(n instanceof I)||!(n.rootAgent instanceof I))return;let r=n.rootAgent;if(r instanceof I&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=yield new u(r.canonicalGlobalInstruction(new M(e))),a=i;s&&(a=yield new u(Je(i,new M(e)))),he(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=yield new u(n.canonicalInstruction(new M(e))),a=i;s&&(a=yield new u(Je(i,new M(e)))),he(t,[a])}})}},ao=new ot,rt=class{runAsync(e,t){return g(this,null,function*(){let n=e.agent;!n||!(n instanceof I)||(n.includeContents==="default"?t.contents=He(e.session.events,n.name,e.branch):t.contents=tn(e.session.events,n.name,e.branch))})}},co=new rt,it=class extends z{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new Z({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:an.object({agentName:an.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}runAsync(t,n){return g(this,null,function*(){if(!(t.agent instanceof I))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;he(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new W({invocationContext:t});yield new u(this.tool.processLlmRequest({toolContext:i,llmRequest:n}))})}buildTargetAgentsInfo(t){return"\nAgent name: ".concat(t.name,"\nAgent description: ").concat(t.description,"\n")}buildTargetAgentsInstructions(t,n){let r="\nYou have a list of other agents to transfer to:\n\n".concat(n.map(this.buildTargetAgentsInfo).join("\n"),"\n\nIf you are the best to answer the question according to your description, you\ncan answer it.\n\nIf another agent is better for answering the question according to its\ndescription, call `").concat(this.toolName,"` function to transfer the\nquestion to that agent. When transferring, do not generate any text other than\nthe function call.\n");return t.parentAgent&&!t.disallowTransferToParent&&(r+="\nYour parent agent is ".concat(t.parentAgent.name,". If neither the other agents nor\nyou are best for answering the question according to the descriptions, transfer\nto your parent agent.\n")),r}getTransferTargets(t){let n=[];return n.push(...t.subAgents),!t.parentAgent||!(t.parentAgent instanceof I)||(t.disallowTransferToParent||n.push(t.parentAgent),t.disallowTransferToPeers||n.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),n}},lo=new it,st=class extends z{runAsync(e,t){return g(this,null,function*(){let n=e.agent;if(!(n instanceof I))return;let r=e.session.events;if(!r||r.length===0)return;let i={},s=-1;for(let a=r.length-1;a>=0;a--){let c=r[a];if(c.author!=="user")continue;let l=N(c);if(!l)continue;let f=!1;for(let d of l){if(d.name!==le)continue;f=!0;let C=null;d.response&&Object.keys(d.response).length===1&&"response"in d.response?C=JSON.parse(d.response.response):d.response&&(C=new Y({hint:d.response.hint,payload:d.response.payload,confirmed:d.response.confirmed})),d.id&&C&&(i[d.id]=C)}if(f){s=a;break}}if(Object.keys(i).length!==0)for(let a=s-1;a>=0;a--){let c=r[a],l=L(c);if(!l)continue;let f={},d={};for(let x of l){if(!x.id||!(x.id in i))continue;let p=x.args;if(!p||!("originalFunctionCall"in p))continue;let v=p.originalFunctionCall;v.id&&(f[v.id]=i[x.id],d[v.id]=v)}if(Object.keys(f).length===0)continue;for(let x=r.length-1;x>s;x--){let p=r[x],v=N(p);if(v){for(let k of v)k.id&&k.id in f&&(delete f[k.id],delete d[k.id]);if(Object.keys(f).length===0)break}}if(Object.keys(f).length===0)continue;let C=yield new u(n.canonicalTools(new M(e))),y=Object.fromEntries(C.map(x=>[x.name,x])),h=yield new u(Te({invocationContext:e,functionCalls:Object.values(d),toolsDict:y,beforeToolCallbacks:n.canonicalBeforeToolCallbacks,afterToolCallbacks:n.canonicalAfterToolCallbacks,filters:new Set(Object.keys(f)),toolConfirmationDict:f}));h&&(yield h);return}})}},uo=new st,at=class extends z{runAsync(e,t){return g(this,null,function*(){if(e.agent instanceof I&&e.agent.codeExecutor){try{for(var n=b(po(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(e.agent.codeExecutor instanceof Q)for(let a of t.contents){let c=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""],l=Zt(a,c,e.agent.codeExecutor.executionResultDelimiters)}}})}},we={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},fo="\nimport pandas as pd\n\ndef explore_df(df: pd.DataFrame) -> None:\n \"\"\"Prints some information about a pandas DataFrame.\"\"\"\n\n with pd.option_context(\n 'display.max_columns', None, 'display.expand_frame_repr', False\n ):\n # Print the column names to never encounter KeyError when selecting one.\n df_dtypes = df.dtypes\n\n # Obtain information about data types and missing values.\n df_nulls = (len(df) - df.isnull().sum()).apply(\n lambda x: f'{x} / {df.shape[0]} non-null'\n )\n\n # Explore unique total values in columns using `.unique()`.\n df_unique_count = df.apply(lambda x: len(x.unique()))\n\n # Explore unique values in columns using `.unique()`.\n df_unique = df.apply(lambda x: crop(str(list(x.unique()))))\n\n df_info = pd.concat(\n (\n df_dtypes.rename('Dtype'),\n df_nulls.rename('Non-Null Count'),\n df_unique_count.rename('Unique Values Count'),\n df_unique.rename('Unique Values'),\n ),\n axis=1,\n )\n df_info.index.name = 'Columns'\n print(f\"\"\"Total rows: {df.shape[0]}\nTotal columns: {df.shape[1]}\n\n{df_info}\"\"\")\n",ct=class{runAsync(e,t){return g(this,null,function*(){if(!t.partial)try{for(var n=b(mo(e,t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}},As=new ct;function po(o,e){return g(this,null,function*(){let t=o.agent;if(!(t instanceof I))return;let n=t.codeExecutor;if(!n||!(n instanceof Q))return;if(n instanceof ue){n.processLlmRequest(e);return}if(!n.optimizeDataFile)return;let r=new ge(new T(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=go(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=ho(c);if(!l)return;let f={role:"model",parts:[{text:"Processing input file: `".concat(c.name,"`")},Ue(l)]};e.contents.push(F(f)),yield R({invocationId:o.invocationId,author:t.name,branch:o.branch,content:f});let d=un(o,r),C=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:l,inputFiles:[c],executionId:d}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:l,resultStdout:C.stdout,resultStderr:C.stderr}),r.addProcessedFileNames([c.name]);let y=yield new u(fn(o,r,C));yield y,e.contents.push(F(y.content))}})}function mo(o,e){return g(this,null,function*(){let t=o.agent;if(!(t instanceof I))return;let n=t.codeExecutor;if(!n||!(n instanceof Q)||!e||!e.content||n instanceof ue)return;let r=new ge(new T(o.session.state));if(r.getErrorCount(o.invocationId)>=n.errorRetryAttempts)return;let i=e.content,s=Kt(i,n.codeBlockDelimiters);if(!s)return;yield R({invocationId:o.invocationId,author:t.name,branch:o.branch,content:i});let a=un(o,r),c=yield new u(n.executeCode({invocationContext:o,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}}));r.updateCodeExecutionResult({invocationId:o.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield yield new u(fn(o,r,c)),e.content=null})}function go(o,e){var r;let t=o.getInputFiles(),n=new Set(t.map(i=>i.name));for(let i=0;i<e.contents.length;i++){let s=e.contents[i];if(!(s.role!=="user"||!s.parts))for(let a=0;a<s.parts.length;a++){let c=s.parts[a],l=(r=c.inlineData)==null?void 0:r.mimeType;if(!l||!c.inlineData||!we[l])continue;let f="data_".concat(i+1,"_").concat(a+1).concat(we[l].extension);c.text="\nAvailable file: `".concat(f,"`\n");let d={name:f,content:wt(c.inlineData.data),mimeType:l};n.has(f)||(o.addInputFiles([d]),t.push(d))}}return t}function un(o,e){var r;let t=o.agent;if(!(t instanceof I)||!((r=t.codeExecutor)!=null&&r.stateful))return;let n=e.getExecutionId();return n||(n=o.session.id,e.setExecutionId(n)),n}async function fn(o,e,t){if(!o.artifactService)throw new Error("Artifact service is not initialized.");let n={role:"model",parts:[Vt(t)]},r=U({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(o.invocationId):e.resetErrorCount(o.invocationId);for(let i of t.outputFiles){let s=await o.artifactService.saveArtifact({appName:o.appName||"",userId:o.userId||"",sessionId:o.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return R({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:n,actions:r})}function ho(o){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!we[o.mimeType])return;let t=e(o.name),n=we[o.mimeType].loaderCodeTemplate.replace("{filename}",o.name);return"\n".concat(fo,"\n\n# Load the dataframe.\n").concat(t," = ").concat(n,"\n\n# Use `explore_df` to guide my analysis.\nexplore_df(").concat(t,")\n")}var Co=new at,I=class o extends ${constructor(e){var n,r,i,s,a,c,l,f,d;if(super(e),this.model=e.model,this.instruction=(n=e.instruction)!=null?n:"",this.globalInstruction=(r=e.globalInstruction)!=null?r:"",this.tools=(i=e.tools)!=null?i:[],this.generateContentConfig=e.generateContentConfig,this.disallowTransferToParent=(s=e.disallowTransferToParent)!=null?s:!1,this.disallowTransferToPeers=(a=e.disallowTransferToPeers)!=null?a:!1,this.includeContents=(c=e.includeContents)!=null?c:"default",this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputKey=e.outputKey,this.beforeModelCallback=e.beforeModelCallback,this.afterModelCallback=e.afterModelCallback,this.beforeToolCallback=e.beforeToolCallback,this.afterToolCallback=e.afterToolCallback,this.codeExecutor=e.codeExecutor,this.requestProcessors=(l=e.requestProcessors)!=null?l:[io,so,ao,uo,co,Co],this.responseProcessors=(f=e.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((d=this.subAgents)!=null&&d.length)||this.requestProcessors.push(lo),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 ".concat(this.name,": outputSchema cannot co-exist with agent transfer configurations. Setting disallowTransferToParent=true, disallowTransferToPeers=true")),this.disallowTransferToParent=!0,this.disallowTransferToPeers=!0),this.subAgents&&this.subAgents.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, subAgents must be empty to disable agent transfer."));if(this.tools&&this.tools.length>0)throw new Error("Invalid config for agent ".concat(this.name,": if outputSchema is set, tools must be empty"))}}get canonicalModel(){if(We(this.model))return this.model;if(typeof this.model=="string"&&this.model)return pe.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 ".concat(this.name,"."))}async canonicalInstruction(e){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(e),requireStateInjection:!1}}async canonicalGlobalInstruction(e){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(e),requireStateInjection:!1}}async canonicalTools(e){let t=[];for(let n of this.tools){let r=await ln(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 ".concat(this.name,": event authored by ").concat(e.author));return}if(!this.outputKey){m.debug("Skipping output save for agent ".concat(this.name,": outputKey is not set"));return}if(!se(e)){m.debug("Skipping output save for agent ".concat(this.name,": event is not a final response"));return}if(!((i=(r=e.content)==null?void 0:r.parts)!=null&&i.length)){m.debug("Skipping output save for agent ".concat(this.name,": event content is empty"));return}let t=e.content.parts.map(s=>s.text?s.text:"").join(""),n=t;if(this.outputSchema){if(!t.trim())return;try{n=JSON.parse(t)}catch(s){m.error("Error parsing output for agent ".concat(this.name),s)}}e.actions.stateDelta[this.outputKey]=n}runAsyncImpl(e){return g(this,null,function*(){for(;;){let s;try{for(var t=b(this.runOneStepAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;s=a,this.maybeSaveOutputToState(a),yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}if(!s||se(s))break;if(s.partial){m.warn("The last event is partial, which is not expected.");break}}})}runLiveImpl(e){return g(this,null,function*(){try{for(var t=b(this.runLiveFlow(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let s=r.value;this.maybeSaveOutputToState(s),yield s}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}e.endInvocation})}runLiveFlow(e){return g(this,null,function*(){throw yield new u(Promise.resolve()),new Error("LlmAgent.runLiveFlow not implemented")})}runOneStepAsync(e){return g(this,null,function*(){let t={contents:[],toolsDict:{},liveConnectConfig:{}};for(let p of this.requestProcessors)try{for(var r=b(p.runAsync(e,t)),i,s,a;i=!(s=yield new u(r.next())).done;i=!1){let v=s.value;yield v}}catch(s){a=[s]}finally{try{i&&(s=r.return)&&(yield new u(s.call(r)))}finally{if(a)throw a[0]}}for(let p of this.tools){let v=new W({invocationContext:e}),k=yield new u(ln(p,new M(e)));for(let E of k)yield new u(E.processLlmRequest({toolContext:v,llmRequest:t}))}if(e.endInvocation)return;let n=R({invocationId:e.invocationId,author:this.name,branch:e.branch});try{for(var C=b(this.callLlmAsync(e,t,n)),y,h,x;y=!(h=yield new u(C.next())).done;y=!1){let p=h.value;try{for(var c=b(this.postprocess(e,t,p,n)),l,f,d;l=!(f=yield new u(c.next())).done;l=!1){let v=f.value;n.id=Oe(),n.timestamp=new Date().getTime(),yield v}}catch(f){d=[f]}finally{try{l&&(f=c.return)&&(yield new u(f.call(c)))}finally{if(d)throw d[0]}}}}catch(h){x=[h]}finally{try{y&&(h=C.return)&&(yield new u(h.call(C)))}finally{if(x)throw x[0]}}})}postprocess(e,t,n,r){return g(this,null,function*(){var h;for(let E of this.responseProcessors)try{for(var f=b(E.runAsync(e,n)),d,C,y;d=!(C=yield new u(f.next())).done;d=!1){let S=C.value;yield S}}catch(C){y=[C]}finally{try{d&&(C=f.return)&&(yield new u(C.call(f)))}finally{if(y)throw y[0]}}if(!n.content&&!n.errorCode&&!n.interrupted)return;let i=R(A(A({},r),n));if(i.content){let E=L(i);E!=null&&E.length&&(Mt(i),i.longRunningToolIds=Array.from(Nt(E,t.toolsDict)))}if(yield i,!((h=L(i))!=null&&h.length))return;let s=yield new u(Dt({invocationContext:e,functionCallEvent:i,toolsDict:t.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks}));if(!s)return;let a=Ot(e,s);a&&(yield a);let c=Ft({invocationContext:e,functionCallEvent:i,functionResponseEvent:s});c&&(yield c),yield s;let l=s.actions.transferToAgent;if(l){let E=this.getAgentByName(e,l);try{for(var x=b(E.runAsync(e)),p,v,k;p=!(v=yield new u(x.next())).done;p=!1){let S=v.value;yield S}}catch(v){k=[v]}finally{try{p&&(v=x.return)&&(yield new u(v.call(x)))}finally{if(k)throw k[0]}}}})}getAgentByName(e,t){let r=e.agent.rootAgent.findAgent(t);if(!r)throw new Error("Agent ".concat(t," not found in the agent tree."));return r}callLlmAsync(e,t,n){return g(this,null,function*(){var s,a,c,l,f;let r=yield new u(this.handleBeforeModelCallback(e,t,n));if(r){yield r;return}(s=t.config)!=null||(t.config={}),(c=(a=t.config).labels)!=null||(a.labels={}),t.config.labels[cn]||(t.config.labels[cn]=this.name);let i=this.canonicalModel;if((l=e.runConfig)!=null&&l.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{e.incrementLlmCallCount();let x=i.generateContentAsync(t,((f=e.runConfig)==null?void 0:f.streamingMode)==="sse");try{for(var d=b(this.runAndHandleError(x,e,t,n)),C,y,h;C=!(y=yield new u(d.next())).done;C=!1){let p=y.value;let v=yield new u(this.handleAfterModelCallback(e,p,n));yield v!=null?v:p}}catch(y){h=[y]}finally{try{C&&(y=d.return)&&(yield new u(y.call(d)))}finally{if(h)throw h[0]}}}})}async handleBeforeModelCallback(e,t,n){let r=new O({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 O({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}}runAndHandleError(e,t,n,r){return g(this,null,function*(){try{try{for(var i=b(e),s,a,c;s=!(a=yield new u(i.next())).done;s=!1){let l=a.value;yield l}}catch(a){c=[a]}finally{try{s&&(a=i.return)&&(yield new u(a.call(i)))}finally{if(c)throw c[0]}}}catch(l){let f=new O({invocationContext:t,eventActions:r.actions});if(l instanceof Error){let d=yield new u(t.pluginManager.runOnModelErrorCallback({callbackContext:f,llmRequest:n,error:l}));if(d)yield d;else{let C=JSON.parse(l.message);yield{errorCode:String(C.error.code),errorMessage:C.error.message}}}else throw m.error("Unknown error during response generation",l),l}})}};var lt=class extends ${constructor(e){var t;super(e),this.maxIterations=(t=e.maxIterations)!=null?t:Number.MAX_SAFE_INTEGER}runAsyncImpl(e){return g(this,null,function*(){let t=0;for(;t<this.maxIterations;){for(let a of this.subAgents){let c=!1;try{for(var n=b(a.runAsync(e)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let l=i.value;yield l,l.actions.escalate&&(c=!0)}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}if(c)return}t++}})}runLiveImpl(e){return g(this,null,function*(){throw new Error("This is not supported yet for LoopAgent.")})}};var ut=class extends ${runAsyncImpl(e){return g(this,null,function*(){let t=this.subAgents.map(a=>a.runAsync(vo(this,a,e)));try{for(var n=b(yo(t)),r,i,s;r=!(i=yield new u(n.next())).done;r=!1){let a=i.value;yield a}}catch(i){s=[i]}finally{try{r&&(i=n.return)&&(yield new u(i.call(n)))}finally{if(s)throw s[0]}}})}runLiveImpl(e){return g(this,null,function*(){throw new Error("This is not supported yet for ParallelAgent.")})}};function vo(o,e,t){let n=new K(t),r="".concat(o.name,".").concat(e.name);return n.branch=n.branch?"".concat(n.branch,".").concat(r):r,n}function yo(o){return g(this,null,function*(){let e=new Map;for(let[t,n]of o.entries()){let r=n.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:n}=yield new u(Promise.race(e.values()));if(t.done){e.delete(n);continue}yield t.value;let r=o[n].next().then(i=>({result:i,index:n}));e.set(n,r)}})}var ft="task_completed",dt=class extends ${runAsyncImpl(e){return g(this,null,function*(){for(let s of this.subAgents)try{for(var t=b(s.runAsync(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}runLiveImpl(e){return g(this,null,function*(){for(let s of this.subAgents)s instanceof I&&((yield new u(s.canonicalTools(new M(e)))).some(l=>l.name===ft)||(s.tools.push(new Z({name:ft,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),s.instruction+="If you finished the user's request according to its description, call the ".concat(ft," function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.")));for(let s of this.subAgents)try{for(var t=b(s.runLive(e)),n,r,i;n=!(r=yield new u(t.next())).done;n=!1){let a=r.value;yield a}}catch(r){i=[r]}finally{try{n&&(r=t.return)&&(yield new u(r.call(t)))}finally{if(i)throw i[0]}}})}};var Ce=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:n,filename:r,artifact:i}){let s=ke(e,t,n,r);this.artifacts[s]||(this.artifacts[s]=[]);let a=this.artifacts[s].length;return this.artifacts[s].push(i),Promise.resolve(a)}loadArtifact({appName:e,userId:t,sessionId:n,filename:r,version:i}){let s=ke(e,t,n,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i])):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:n}){let r="".concat(e,"/").concat(t,"/").concat(n,"/"),i="".concat(e,"/").concat(t,"/user/"),s=[];for(let a in this.artifacts)if(a.startsWith(r)){let c=a.replace(r,"");s.push(c)}else if(a.startsWith(i)){let c=a.replace(i,"");s.push(c)}return Promise.resolve(s.sort())}deleteArtifact({appName:e,userId:t,sessionId:n,filename:r}){let i=ke(e,t,n,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:n,filename:r}){let i=ke(e,t,n,r),s=this.artifacts[i];if(!s)return Promise.resolve([]);let a=[];for(let c=0;c<s.length;c++)a.push(c);return Promise.resolve(a)}};function ke(o,e,t,n){return Ao(n)?"".concat(o,"/").concat(e,"/user/").concat(n):"".concat(o,"/").concat(e,"/").concat(t,"/").concat(n)}function Ao(o){return o.startsWith("user:")}var ee=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=dn(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(n=>{var r,i,s;return((s=(i=(r=n.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=dn(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let n=e.query.toLowerCase().split(/\s+/),r={memories:[]};for(let a of Object.values(this.sessionEvents[t]))for(let c of a){if(!((s=(i=c.content)==null?void 0:i.parts)!=null&&s.length))continue;let l=c.content.parts.map(C=>C.text).filter(C=>!!C).join(" "),f=xo(l);if(!f.size)continue;n.some(C=>f.has(C))&&r.memories.push({content:c.content,author:c.author,timestamp:Eo(c.timestamp)})}return r}};function dn(o,e){return"".concat(o,"/").concat(e)}function xo(o){return new Set([...o.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function Eo(o){return new Date(o).toISOString()}var te=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 pt=class extends te{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var n;this.log("\u{1F680} USER MESSAGE RECEIVED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Session ID: ".concat(e.session.id)),this.log(" User ID: ".concat(e.userId)),this.log(" App Name: ".concat(e.appName)),this.log(" Root Agent: ".concat((n=e.agent.name)!=null?n:"Unknown")),this.log(" User Content: ".concat(this.formatContent(t))),e.branch&&this.log(" Branch: ".concat(e.branch))}async beforeRunCallback({invocationContext:e}){var t;this.log("\u{1F3C3} INVOCATION STARTING"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Starting Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async onEventCallback({invocationContext:e,event:t}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(" Event ID: ".concat(t.id)),this.log(" Author: ".concat(t.author)),this.log(" Content: ".concat(this.formatContent(t.content))),this.log(" Final Response: ".concat(se(t)));let n=L(t);if(n.length>0){let i=n.map(s=>s.name);this.log(" Function Calls: ".concat(i))}let r=N(t);if(r.length>0){let i=r.map(s=>s.name);this.log(" Function Responses: ".concat(i))}t.longRunningToolIds&&t.longRunningToolIds.length>0&&this.log(" Long Running Tools: ".concat([...t.longRunningToolIds]))}async afterRunCallback({invocationContext:e}){var t;this.log("\u2705 INVOCATION COMPLETED"),this.log(" Invocation ID: ".concat(e.invocationId)),this.log(" Final Agent: ".concat((t=e.agent.name)!=null?t:"Unknown"))}async beforeAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT STARTING"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId)),t.invocationContext.branch&&this.log(" Branch: ".concat(t.invocationContext.branch))}async afterAgentCallback({agent:e,callbackContext:t}){this.log("\u{1F916} AGENT COMPLETED"),this.log(" Agent Name: ".concat(t.agentName)),this.log(" Invocation ID: ".concat(t.invocationId))}async beforeModelCallback({callbackContext:e,llmRequest:t}){var n;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(" Model: ".concat((n=t.model)!=null?n:"default")),this.log(" Agent: ".concat(e.agentName)),t.config&&t.config.systemInstruction){let r=t.config.systemInstruction;r.length>200&&(r=r.substring(0,200)+"..."),this.log(" System Instruction: '".concat(r,"'"))}if(t.toolsDict){let r=Object.keys(t.toolsDict);this.log(" Available Tools: ".concat(r))}}async afterModelCallback({callbackContext:e,llmResponse:t}){this.log("\u{1F9E0} LLM RESPONSE"),this.log(" Agent: ".concat(e.agentName)),t.errorCode?(this.log(" \u274C ERROR - Code: ".concat(t.errorCode)),this.log(" Error Message: ".concat(t.errorMessage))):(this.log(" Content: ".concat(this.formatContent(t.content))),t.partial&&this.log(" Partial: ".concat(t.partial)),t.turnComplete!==void 0&&this.log(" Turn Complete: ".concat(t.turnComplete))),t.usageMetadata&&this.log(" Token Usage - Input: ".concat(t.usageMetadata.promptTokenCount,", Output: ").concat(t.usageMetadata.candidatesTokenCount))}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){this.log("\u{1F527} TOOL STARTING"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t)))}async afterToolCallback({tool:e,toolArgs:t,toolContext:n,result:r}){this.log("\u{1F527} TOOL COMPLETED"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Result: ".concat(this.formatArgs(r)))}async onModelErrorCallback({callbackContext:e,llmRequest:t,error:n}){this.log("\u{1F9E0} LLM ERROR"),this.log(" Agent: ".concat(e.agentName)),this.log(" Error: ".concat(n))}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:n,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(" Tool Name: ".concat(e.name)),this.log(" Agent: ".concat(n.agentName)),this.log(" Function Call ID: ".concat(n.functionCallId)),this.log(" Arguments: ".concat(this.formatArgs(t))),this.log(" Error: ".concat(r))}log(e){let t="\x1B[90m[".concat(this.name,"] ").concat(e,"\x1B[0m");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: '".concat(i,"'"))}else r.functionCall?n.push("function_call: ".concat(r.functionCall.name)):r.functionResponse?n.push("function_response: ".concat(r.functionResponse.name)):r.codeExecutionResult?n.push("code_execution_result"):n.push("other_part");return n.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let n=JSON.stringify(e);return n.length>t&&(n=n.substring(0,t)+"...}"),n}};var ve=class{constructor(e){this.plugins=new Set;if(e)for(let t of e)this.registerPlugin(t)}registerPlugin(e){if(this.plugins.has(e))throw new Error("Plugin '".concat(e.name,"' already registered."));if(Array.from(this.plugins).some(t=>t.name===e.name))throw new Error("Plugin with name '".concat(e.name,"' already registered."));this.plugins.add(e),m.info("Plugin '".concat(e.name,"' registered."))}getPlugin(e){return Array.from(this.plugins).find(t=>t.name===e)}async runCallbacks(e,t,n){for(let r of e)try{let i=await t(r);if(i!==void 0)return m.debug("Plugin '".concat(r.name,"' returned a value for callback '").concat(n,"', exiting early.")),i}catch(i){let s="Error in plugin '".concat(r.name,"' during '").concat(n,"' callback: ").concat(i);throw 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 mn="adk_request_confirmation",mt="orcas_tool_call_security_check_states",pn="This tool call needs external confirmation before completion.",gn=(n=>(n.DENY="DENY",n.CONFIRM="CONFIRM",n.ALLOW="ALLOW",n))(gn||{}),Pe=class{async evaluate(e){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},gt=class extends te{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new Pe}async beforeToolCallback({tool:e,toolArgs:t,toolContext:n}){let r=this.getToolCallCheckState(n);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n});if(r==="CONFIRM"){if(!n.toolConfirmation)return{partial:pn};if(this.setToolCallCheckState(n,n.toolConfirmation),!n.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};n.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(mt))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:n}=e;if(!n)return;let r=(i=e.state.get(mt))!=null?i:{};r[n]=t,e.state.set(mt,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:n}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(n,r.outcome),r.outcome){case"DENY":return{error:"This tool call is rejected by policy engine. Reason: ".concat(r.reason)};case"CONFIRM":return n.requestConfirmation({hint:"Policy engine requires confirmation calling tool: ".concat(e.name,". Reason: ").concat(r.reason)}),{partial:pn};case"ALLOW":return;default:return}}};function bo(o){if(!o.content||!o.content.parts)return[];let e=[];for(let t of o.content.parts)t&&t.functionCall&&t.functionCall.name===mn&&e.push(t.functionCall);return e}var Le=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(T.TEMP_PREFIX)||(e.state[n]=r)}};function _e(o){return{id:o.id,appName:o.appName,userId:o.userId||"",state:o.state||{},events:o.events||[],lastUpdateTime:o.lastUpdateTime||0}}var ne=class extends Le{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}createSession({appName:t,userId:n,state:r,sessionId:i}){let s=_e({id:i||ae(),appName:t,userId:n,state:r,events:[],lastUpdateTime:Date.now()});return this.sessions[t]||(this.sessions[t]={}),this.sessions[t][n]||(this.sessions[t][n]={}),this.sessions[t][n][s.id]=s,Promise.resolve(this.mergeState(t,n,F(s)))}getSession({appName:t,userId:n,sessionId:r,config:i}){if(!this.sessions[t]||!this.sessions[t][n]||!this.sessions[t][n][r])return Promise.resolve(void 0);let s=this.sessions[t][n][r],a=F(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let c=a.events.length-1;for(;c>=0&&!(a.events[c].timestamp<i.afterTimestamp);)c--;c>=0&&(a.events=a.events.slice(c+1))}return Promise.resolve(this.mergeState(t,n,a))}listSessions({appName:t,userId:n}){if(!this.sessions[t]||!this.sessions[t][n])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][n]))r.push(_e({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:n,sessionId:r}){await this.getSession({appName:t,userId:n,sessionId:r})&&delete this.sessions[t][n][r]}async appendEvent({session:t,event:n}){await super.appendEvent({session:t,event:n}),t.lastUpdateTime=n.timestamp;let r=t.appName,i=t.userId,s=t.id,a=l=>{m.warn("Failed to append event to session ".concat(s,": ").concat(l))};if(!this.sessions[r])return a("appName ".concat(r," not in sessions")),n;if(!this.sessions[r][i])return a("userId ".concat(i," not in sessions[appName]")),n;if(!this.sessions[r][i][s])return a("sessionId ".concat(s," not in sessions[appName][userId]")),n;if(n.actions&&n.actions.stateDelta)for(let l of Object.keys(n.actions.stateDelta))l.startsWith(T.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(T.APP_PREFIX,"")]=n.actions.stateDelta[l]),l.startsWith(T.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(T.USER_PREFIX,"")]=n.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:n}),c.lastUpdateTime=n.timestamp,n}mergeState(t,n,r){if(this.appState[t])for(let i of Object.keys(this.appState[t]))r.state[T.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[T.USER_PREFIX+i]=this.userState[t][n][i];return r}};import{createPartFromText as To}from"@google/genai";import{trace as So}from"@opentelemetry/api";var oe=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new ve((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}runAsync(s){return g(this,arguments,function*({userId:e,sessionId:t,newMessage:n,stateDelta:r,runConfig:i}){var c;i=sn(i);let a=So.getTracer("gcp.vertex.agent").startSpan("invocation");try{let y=yield new u(this.sessionService.getSession({appName:this.appName,userId:e,sessionId:t}));if(!y)throw new Error("Session not found: ".concat(t));if(i.supportCfc&&this.agent instanceof I){let v=this.agent.canonicalModel.model;if(!v.startsWith("gemini-2"))throw new Error("CFC is not supported for model: ".concat(v," in agent: ").concat(this.agent.name))}let h=new K({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:kt(),agent:this.agent,session:y,userContent:n,runConfig:i,pluginManager:this.pluginManager}),x=yield new u(this.pluginManager.runOnUserMessageCallback({userMessage:n,invocationContext:h}));if(x&&(n=x),n){if(!((c=n.parts)!=null&&c.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&(yield new u(this.saveArtifacts(h.invocationId,y.userId,y.id,n))),yield new u(this.sessionService.appendEvent({session:y,event:R({invocationId:h.invocationId,author:"user",actions:r?U({stateDelta:r}):void 0,content:n})}))}h.agent=this.determineAgentForResumption(y,this.agent);let p=yield new u(this.pluginManager.runBeforeRunCallback({invocationContext:h}));if(p){let v=R({invocationId:h.invocationId,author:"model",content:p});yield new u(this.sessionService.appendEvent({session:y,event:v})),yield v}else try{for(var l=b(h.agent.runAsync(h)),f,d,C;f=!(d=yield new u(l.next())).done;f=!1){let v=d.value;v.partial||(yield new u(this.sessionService.appendEvent({session:y,event:v})));let k=yield new u(this.pluginManager.runOnEventCallback({invocationContext:h,event:v}));k?yield k:yield v}}catch(d){C=[d]}finally{try{f&&(d=l.return)&&(yield new u(d.call(l)))}finally{if(C)throw C[0]}}yield new u(this.pluginManager.runAfterRunCallback({invocationContext:h}))}finally{a.end()}})}async saveArtifacts(e,t,n,r){var i;if(!(!this.artifactService||!((i=r.parts)!=null&&i.length)))for(let s=0;s<r.parts.length;s++){let a=r.parts[s];if(!a.inlineData)continue;let c="artifact_".concat(e,"_").concat(s);await this.artifactService.saveArtifact({appName:this.appName,userId:t,sessionId:n,filename:c,artifact:a}),r.parts[s]=To("Uploaded file: ".concat(c,". It is saved into artifacts"))}}determineAgentForResumption(e,t){let n=Io(e.events);if(n&&n.author)return t.findAgent(n.author)||t;for(let r=e.events.length-1;r>=0;r--){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: ".concat(i.author,", event id: ").concat(i.id));continue}if(this.isRoutableLlmAgent(s))return s}return t}isRoutableLlmAgent(e){let t=e;for(;t;){if(!(t instanceof I)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function Io(o){var n,r,i,s;if(!o.length)return null;let t=(s=(i=(r=(n=o[o.length-1].content)==null?void 0:n.parts)==null?void 0:r.find(a=>a.functionResponse))==null?void 0:i.functionResponse)==null?void 0:s.id;if(!t)return null;for(let a=o.length-2;a>=0;a--){let c=o[a],l=L(c);if(l){for(let f of l)if(f.id===t)return c}}return null}var ht=class extends oe{constructor({agent:e,appName:t="InMemoryRunner",plugins:n=[]}){super({appName:t,agent:e,plugins:n,artifactService:new Ce,sessionService:new ne,memoryService:new ee})}};import{Type as Be}from"@google/genai";var Me=class{constructor(e){this.toolContext=e;this.invocationContext=e.invocationContext}async saveArtifact(e){return this.toolContext.saveArtifact(e.filename,e.artifact)}async loadArtifact(e){return this.toolContext.loadArtifact(e.filename,e.version)}async listArtifactKeys(e){return this.toolContext.listArtifacts()}async deleteArtifact(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.deleteArtifact(e)}async listVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listVersions(e)}};var Ct=class extends q{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 I&&this.agent.inputSchema?e={name:this.name,description:this.description,parameters:this.agent.inputSchema}:e={name:this.name,description:this.description,parameters:{type:Be.OBJECT,properties:{request:{type:Be.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let t=this.agent instanceof I&&this.agent.outputSchema;e.response=t?{type:Be.OBJECT}:{type:Be.STRING}}return e}async runAsync({args:e,toolContext:t}){var h,x;this.skipSummarization&&(t.actions.skipSummarization=!0);let r={role:"user",parts:[{text:this.agent instanceof I&&this.agent.inputSchema?JSON.stringify(e):e.request}]},i=new oe({appName:this.agent.name,agent:this.agent,artifactService:new Me(t),sessionService:new ne,memoryService:new ee,credentialService:t.invocationContext.credentialService}),s=await i.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:t.state.toRecord()}),a;try{for(var f=b(i.runAsync({userId:s.userId,sessionId:s.id,newMessage:r})),d,C,y;d=!(C=await f.next()).done;d=!1){let p=C.value;p.actions.stateDelta&&t.state.update(p.actions.stateDelta),a=p}}catch(C){y=[C]}finally{try{d&&(C=f.return)&&await C.call(f)}finally{if(y)throw y[0]}}if(!((x=(h=a==null?void 0:a.content)==null?void 0:h.parts)!=null&&x.length))return"";let c=this.agent instanceof I&&this.agent.outputSchema,l=a.content.parts.map(p=>p.text).filter(p=>p).join("\n");return c?JSON.parse(l):l}};var vt=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 yt=class extends q{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||[],$t(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(Gt(t.model)){t.config.tools.push({googleSearch:{}});return}throw new Error("Google search tool is not supported for model ".concat(t.model))}}},Ro=new yt;var hn="\n\nNOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.",At=class extends Z{constructor(e){super(ie(A({},e),{isLongRunning:!0}))}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=hn:e.description=hn.trimStart(),e}};export{Ct as AgentTool,$ as BaseAgent,fe as BaseLlm,te as BasePlugin,Le as BaseSessionService,q as BaseTool,vt as BaseToolset,ue as BuiltInCodeExecutor,O as CallbackContext,Z as FunctionTool,Ro as GOOGLE_SEARCH,de as Gemini,Ce as InMemoryArtifactService,ee as InMemoryMemoryService,Pe as InMemoryPolicyEngine,ht as InMemoryRunner,ne as InMemorySessionService,K as InvocationContext,pe as LLMRegistry,qe as LiveRequestQueue,I as LlmAgent,_t as LogLevel,pt as LoggingPlugin,At as LongRunningFunctionTool,lt as LoopAgent,ut as ParallelAgent,ve as PluginManager,gn as PolicyOutcome,mn as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,oe as Runner,gt as SecurityPlugin,dt as SequentialAgent,T as State,et as StreamingMode,Y as ToolConfirmation,W as ToolContext,R as createEvent,U as createEventActions,_e as createSession,Ln as functionsExportedForTestingOnly,bo as getAskUserConfirmationFunctionCalls,L as getFunctionCalls,N as getFunctionResponses,Rt as hasTrailingCodeExecutionResult,We as isBaseLlm,se as isFinalResponse,In as setLogLevel,En as stringifyContent,Ze as version,Re as zodObjectToSchema};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Google LLC