@google/adk 0.2.0 → 0.2.2

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