@google/adk 0.4.0 → 0.5.0

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 (132) hide show
  1. package/dist/cjs/a2a/a2a_event.js +290 -0
  2. package/dist/cjs/a2a/event_converter_utils.js +201 -0
  3. package/dist/cjs/a2a/executor_context.js +53 -0
  4. package/dist/cjs/a2a/metadata_converter_utils.js +125 -0
  5. package/dist/cjs/a2a/part_converter_utils.js +23 -21
  6. package/dist/cjs/agents/base_agent.js +3 -3
  7. package/dist/cjs/{tools/tool_context.js → agents/context.js} +70 -15
  8. package/dist/cjs/agents/functions.js +2 -2
  9. package/dist/cjs/agents/llm_agent.js +21 -674
  10. package/dist/cjs/agents/processors/agent_transfer_llm_request_processor.js +132 -0
  11. package/dist/cjs/agents/processors/basic_llm_request_processor.js +68 -0
  12. package/dist/cjs/agents/processors/code_execution_request_processor.js +389 -0
  13. package/dist/cjs/agents/processors/content_request_processor.js +66 -0
  14. package/dist/cjs/agents/processors/identity_llm_request_processor.js +54 -0
  15. package/dist/cjs/agents/processors/instructions_llm_request_processor.js +85 -0
  16. package/dist/cjs/agents/processors/request_confirmation_llm_request_processor.js +165 -0
  17. package/dist/cjs/common.js +11 -7
  18. package/dist/cjs/index.js +89 -53
  19. package/dist/cjs/index.js.map +7 -0
  20. package/dist/cjs/models/llm_response.js +2 -0
  21. package/dist/cjs/plugins/base_plugin.js +1 -1
  22. package/dist/cjs/runner/runner.js +1 -1
  23. package/dist/cjs/sessions/database_session_service.js +4 -1
  24. package/dist/cjs/sessions/db/operations.js +24 -12
  25. package/dist/cjs/tools/base_tool.js +3 -0
  26. package/dist/cjs/tools/base_toolset.js +13 -3
  27. package/dist/cjs/tools/exit_loop_tool.js +63 -0
  28. package/dist/cjs/tools/mcp/mcp_toolset.js +9 -5
  29. package/dist/cjs/utils/logger.js +61 -54
  30. package/dist/cjs/version.js +1 -1
  31. package/dist/esm/a2a/a2a_event.js +243 -0
  32. package/dist/esm/a2a/event_converter_utils.js +187 -0
  33. package/dist/esm/a2a/executor_context.js +23 -0
  34. package/dist/esm/a2a/metadata_converter_utils.js +90 -0
  35. package/dist/esm/a2a/part_converter_utils.js +25 -21
  36. package/dist/esm/agents/base_agent.js +3 -3
  37. package/dist/esm/{tools/tool_context.js → agents/context.js} +66 -11
  38. package/dist/esm/agents/functions.js +2 -2
  39. package/dist/esm/agents/llm_agent.js +14 -683
  40. package/dist/esm/agents/processors/agent_transfer_llm_request_processor.js +101 -0
  41. package/dist/esm/agents/processors/basic_llm_request_processor.js +37 -0
  42. package/dist/esm/agents/processors/code_execution_request_processor.js +363 -0
  43. package/dist/esm/agents/processors/content_request_processor.js +38 -0
  44. package/dist/esm/agents/processors/identity_llm_request_processor.js +23 -0
  45. package/dist/esm/agents/processors/instructions_llm_request_processor.js +54 -0
  46. package/dist/esm/agents/processors/request_confirmation_llm_request_processor.js +140 -0
  47. package/dist/esm/common.js +11 -9
  48. package/dist/esm/index.js +95 -18
  49. package/dist/esm/index.js.map +7 -0
  50. package/dist/esm/models/llm_response.js +2 -0
  51. package/dist/esm/plugins/base_plugin.js +1 -1
  52. package/dist/esm/runner/runner.js +1 -1
  53. package/dist/esm/sessions/database_session_service.js +4 -1
  54. package/dist/esm/sessions/db/operations.js +31 -7
  55. package/dist/esm/tools/base_tool.js +3 -0
  56. package/dist/esm/tools/base_toolset.js +11 -2
  57. package/dist/esm/tools/exit_loop_tool.js +32 -0
  58. package/dist/esm/tools/mcp/mcp_toolset.js +9 -5
  59. package/dist/esm/utils/logger.js +51 -54
  60. package/dist/esm/version.js +1 -1
  61. package/dist/types/a2a/a2a_event.d.ts +122 -0
  62. package/dist/types/a2a/event_converter_utils.d.ts +20 -0
  63. package/dist/types/a2a/executor_context.d.ts +33 -0
  64. package/dist/types/a2a/metadata_converter_utils.d.ts +62 -0
  65. package/dist/types/a2a/part_converter_utils.d.ts +4 -3
  66. package/dist/types/agents/base_agent.d.ts +2 -2
  67. package/dist/types/{tools/tool_context.d.ts → agents/context.d.ts} +43 -8
  68. package/dist/types/agents/llm_agent.d.ts +8 -31
  69. package/dist/types/agents/processors/agent_transfer_llm_request_processor.d.ts +18 -0
  70. package/dist/types/agents/{base_llm_processor.d.ts → processors/base_llm_processor.d.ts} +4 -4
  71. package/dist/types/agents/processors/basic_llm_request_processor.d.ts +13 -0
  72. package/dist/types/agents/processors/code_execution_request_processor.d.ts +34 -0
  73. package/dist/types/agents/processors/content_request_processor.d.ts +13 -0
  74. package/dist/types/agents/processors/identity_llm_request_processor.d.ts +13 -0
  75. package/dist/types/agents/processors/instructions_llm_request_processor.d.ts +16 -0
  76. package/dist/types/agents/processors/request_confirmation_llm_request_processor.d.ts +13 -0
  77. package/dist/types/auth/credential_service/base_credential_service.d.ts +3 -3
  78. package/dist/types/auth/credential_service/in_memory_credential_service.d.ts +3 -3
  79. package/dist/types/common.d.ts +4 -4
  80. package/dist/types/models/llm_response.d.ts +5 -1
  81. package/dist/types/plugins/base_plugin.d.ts +12 -13
  82. package/dist/types/plugins/logging_plugin.d.ts +9 -10
  83. package/dist/types/plugins/plugin_manager.d.ts +9 -10
  84. package/dist/types/plugins/security_plugin.d.ts +2 -2
  85. package/dist/types/sessions/database_session_service.d.ts +2 -1
  86. package/dist/types/sessions/db/operations.d.ts +1 -1
  87. package/dist/types/tools/base_tool.d.ts +3 -3
  88. package/dist/types/tools/base_toolset.d.ts +12 -3
  89. package/dist/types/tools/exit_loop_tool.d.ts +24 -0
  90. package/dist/types/tools/forwarding_artifact_service.d.ts +2 -2
  91. package/dist/types/tools/function_tool.d.ts +2 -2
  92. package/dist/types/tools/mcp/mcp_toolset.d.ts +1 -1
  93. package/dist/types/utils/logger.d.ts +5 -9
  94. package/dist/types/version.d.ts +1 -1
  95. package/dist/web/a2a/a2a_event.js +243 -0
  96. package/dist/web/a2a/event_converter_utils.js +201 -0
  97. package/dist/web/a2a/executor_context.js +23 -0
  98. package/dist/web/a2a/metadata_converter_utils.js +107 -0
  99. package/dist/web/a2a/part_converter_utils.js +25 -21
  100. package/dist/web/agents/base_agent.js +3 -3
  101. package/dist/web/{tools/tool_context.js → agents/context.js} +66 -11
  102. package/dist/web/agents/functions.js +2 -2
  103. package/dist/web/agents/llm_agent.js +14 -661
  104. package/dist/web/agents/processors/agent_transfer_llm_request_processor.js +100 -0
  105. package/dist/web/agents/processors/basic_llm_request_processor.js +71 -0
  106. package/dist/web/agents/processors/code_execution_request_processor.js +365 -0
  107. package/dist/web/agents/processors/content_request_processor.js +56 -0
  108. package/dist/web/agents/processors/identity_llm_request_processor.js +41 -0
  109. package/dist/web/agents/processors/instructions_llm_request_processor.js +72 -0
  110. package/dist/web/agents/processors/request_confirmation_llm_request_processor.js +158 -0
  111. package/dist/web/common.js +11 -9
  112. package/dist/web/index.js +13 -18
  113. package/dist/web/index.js.map +7 -0
  114. package/dist/web/models/llm_response.js +2 -0
  115. package/dist/web/plugins/base_plugin.js +1 -1
  116. package/dist/web/runner/runner.js +1 -1
  117. package/dist/web/sessions/database_session_service.js +4 -1
  118. package/dist/web/sessions/db/operations.js +31 -7
  119. package/dist/web/tools/base_tool.js +3 -0
  120. package/dist/web/tools/base_toolset.js +11 -2
  121. package/dist/web/tools/exit_loop_tool.js +32 -0
  122. package/dist/web/tools/mcp/mcp_toolset.js +27 -5
  123. package/dist/web/utils/logger.js +51 -54
  124. package/dist/web/version.js +1 -1
  125. package/package.json +3 -2
  126. package/dist/cjs/agents/callback_context.js +0 -101
  127. package/dist/esm/agents/callback_context.js +0 -71
  128. package/dist/types/agents/callback_context.d.ts +0 -42
  129. package/dist/web/agents/callback_context.js +0 -71
  130. /package/dist/cjs/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
  131. /package/dist/esm/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
  132. /package/dist/web/agents/{base_llm_processor.js → processors/base_llm_processor.js} +0 -0
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import {
7
+ getFunctionCalls,
8
+ getFunctionResponses
9
+ } from "../../events/event.js";
10
+ import { ToolConfirmation } from "../../tools/tool_confirmation.js";
11
+ import {
12
+ REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
13
+ handleFunctionCallList
14
+ } from "../functions.js";
15
+ import { isLlmAgent } from "../llm_agent.js";
16
+ import { ReadonlyContext } from "../readonly_context.js";
17
+ import { BaseLlmRequestProcessor } from "./base_llm_processor.js";
18
+ class RequestConfirmationLlmRequestProcessor extends BaseLlmRequestProcessor {
19
+ /** Handles tool confirmation information to build the LLM request. */
20
+ async *runAsync(invocationContext) {
21
+ const agent = invocationContext.agent;
22
+ if (!isLlmAgent(agent)) {
23
+ return;
24
+ }
25
+ const events = invocationContext.session.events;
26
+ if (!events || events.length === 0) {
27
+ return;
28
+ }
29
+ const requestConfirmationFunctionResponses = {};
30
+ let confirmationEventIndex = -1;
31
+ for (let i = events.length - 1; i >= 0; i--) {
32
+ const event = events[i];
33
+ if (event.author !== "user") {
34
+ continue;
35
+ }
36
+ const responses = getFunctionResponses(event);
37
+ if (!responses) {
38
+ continue;
39
+ }
40
+ let foundConfirmation = false;
41
+ for (const functionResponse of responses) {
42
+ if (functionResponse.name !== REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
43
+ continue;
44
+ }
45
+ foundConfirmation = true;
46
+ let toolConfirmation = null;
47
+ if (functionResponse.response && Object.keys(functionResponse.response).length === 1 && "response" in functionResponse.response) {
48
+ toolConfirmation = JSON.parse(
49
+ functionResponse.response["response"]
50
+ );
51
+ } else if (functionResponse.response) {
52
+ toolConfirmation = new ToolConfirmation({
53
+ hint: functionResponse.response["hint"],
54
+ payload: functionResponse.response["payload"],
55
+ confirmed: functionResponse.response["confirmed"]
56
+ });
57
+ }
58
+ if (functionResponse.id && toolConfirmation) {
59
+ requestConfirmationFunctionResponses[functionResponse.id] = toolConfirmation;
60
+ }
61
+ }
62
+ if (foundConfirmation) {
63
+ confirmationEventIndex = i;
64
+ break;
65
+ }
66
+ }
67
+ if (Object.keys(requestConfirmationFunctionResponses).length === 0) {
68
+ return;
69
+ }
70
+ for (let i = confirmationEventIndex - 1; i >= 0; i--) {
71
+ const event = events[i];
72
+ const functionCalls = getFunctionCalls(event);
73
+ if (!functionCalls) {
74
+ continue;
75
+ }
76
+ const toolsToResumeWithConfirmation = {};
77
+ const toolsToResumeWithArgs = {};
78
+ for (const functionCall of functionCalls) {
79
+ if (!functionCall.id || !(functionCall.id in requestConfirmationFunctionResponses)) {
80
+ continue;
81
+ }
82
+ const args = functionCall.args;
83
+ if (!args || !("originalFunctionCall" in args)) {
84
+ continue;
85
+ }
86
+ const originalFunctionCall = args["originalFunctionCall"];
87
+ if (originalFunctionCall.id) {
88
+ toolsToResumeWithConfirmation[originalFunctionCall.id] = requestConfirmationFunctionResponses[functionCall.id];
89
+ toolsToResumeWithArgs[originalFunctionCall.id] = originalFunctionCall;
90
+ }
91
+ }
92
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
93
+ continue;
94
+ }
95
+ for (let j = events.length - 1; j > confirmationEventIndex; j--) {
96
+ const eventToCheck = events[j];
97
+ const functionResponses = getFunctionResponses(eventToCheck);
98
+ if (!functionResponses) {
99
+ continue;
100
+ }
101
+ for (const fr of functionResponses) {
102
+ if (fr.id && fr.id in toolsToResumeWithConfirmation) {
103
+ delete toolsToResumeWithConfirmation[fr.id];
104
+ delete toolsToResumeWithArgs[fr.id];
105
+ }
106
+ }
107
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
108
+ break;
109
+ }
110
+ }
111
+ if (Object.keys(toolsToResumeWithConfirmation).length === 0) {
112
+ continue;
113
+ }
114
+ const toolsList = await agent.canonicalTools(
115
+ new ReadonlyContext(invocationContext)
116
+ );
117
+ const toolsDict = Object.fromEntries(
118
+ toolsList.map((tool) => [tool.name, tool])
119
+ );
120
+ const functionResponseEvent = await handleFunctionCallList({
121
+ invocationContext,
122
+ functionCalls: Object.values(toolsToResumeWithArgs),
123
+ toolsDict,
124
+ beforeToolCallbacks: agent.canonicalBeforeToolCallbacks,
125
+ afterToolCallbacks: agent.canonicalAfterToolCallbacks,
126
+ filters: new Set(Object.keys(toolsToResumeWithConfirmation)),
127
+ toolConfirmationDict: toolsToResumeWithConfirmation
128
+ });
129
+ if (functionResponseEvent) {
130
+ yield functionResponseEvent;
131
+ }
132
+ return;
133
+ }
134
+ }
135
+ }
136
+ const REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR = new RequestConfirmationLlmRequestProcessor();
137
+ export {
138
+ REQUEST_CONFIRMATION_LLM_REQUEST_PROCESSOR,
139
+ RequestConfirmationLlmRequestProcessor
140
+ };
@@ -5,17 +5,17 @@
5
5
  */
6
6
  import { ActiveStreamingTool } from "./agents/active_streaming_tool.js";
7
7
  import { BaseAgent, isBaseAgent } from "./agents/base_agent.js";
8
- import {
9
- BaseLlmRequestProcessor,
10
- BaseLlmResponseProcessor
11
- } from "./agents/base_llm_processor.js";
12
- import { CallbackContext } from "./agents/callback_context.js";
8
+ import { Context } from "./agents/context.js";
13
9
  import { functionsExportedForTestingOnly } from "./agents/functions.js";
14
10
  import { InvocationContext } from "./agents/invocation_context.js";
15
11
  import { LiveRequestQueue } from "./agents/live_request_queue.js";
16
12
  import { LlmAgent, isLlmAgent } from "./agents/llm_agent.js";
17
13
  import { LoopAgent, isLoopAgent } from "./agents/loop_agent.js";
18
14
  import { ParallelAgent, isParallelAgent } from "./agents/parallel_agent.js";
15
+ import {
16
+ BaseLlmRequestProcessor,
17
+ BaseLlmResponseProcessor
18
+ } from "./agents/processors/base_llm_processor.js";
19
19
  import { ReadonlyContext } from "./agents/readonly_context.js";
20
20
  import { StreamingMode } from "./agents/run_config.js";
21
21
  import { SequentialAgent, isSequentialAgent } from "./agents/sequential_agent.js";
@@ -60,12 +60,12 @@ import { createSession } from "./sessions/session.js";
60
60
  import { State } from "./sessions/state.js";
61
61
  import { AgentTool, isAgentTool } from "./tools/agent_tool.js";
62
62
  import { BaseTool, isBaseTool } from "./tools/base_tool.js";
63
- import { BaseToolset } from "./tools/base_toolset.js";
63
+ import { BaseToolset, isBaseToolset } from "./tools/base_toolset.js";
64
+ import { EXIT_LOOP, ExitLoopTool } from "./tools/exit_loop_tool.js";
64
65
  import { FunctionTool, isFunctionTool } from "./tools/function_tool.js";
65
66
  import { GOOGLE_SEARCH, GoogleSearchTool } from "./tools/google_search_tool.js";
66
67
  import { LongRunningFunctionTool } from "./tools/long_running_tool.js";
67
68
  import { ToolConfirmation } from "./tools/tool_confirmation.js";
68
- import { ToolContext } from "./tools/tool_context.js";
69
69
  import { LogLevel, getLogger, setLogLevel, setLogger } from "./utils/logger.js";
70
70
  import { isGemini2OrAbove } from "./utils/model_name.js";
71
71
  import { zodObjectToSchema } from "./utils/simple_zod_to_json.js";
@@ -91,8 +91,10 @@ export {
91
91
  BaseTool,
92
92
  BaseToolset,
93
93
  BuiltInCodeExecutor,
94
- CallbackContext,
94
+ Context,
95
+ EXIT_LOOP,
95
96
  EventType,
97
+ ExitLoopTool,
96
98
  FunctionTool,
97
99
  GOOGLE_SEARCH,
98
100
  Gemini,
@@ -122,7 +124,6 @@ export {
122
124
  State,
123
125
  StreamingMode,
124
126
  ToolConfirmation,
125
- ToolContext,
126
127
  createEvent,
127
128
  createEventActions,
128
129
  createSession,
@@ -138,6 +139,7 @@ export {
138
139
  isBaseExampleProvider,
139
140
  isBaseLlm,
140
141
  isBaseTool,
142
+ isBaseToolset,
141
143
  isFinalResponse,
142
144
  isFunctionTool,
143
145
  isGemini2OrAbove,
package/dist/esm/index.js CHANGED
@@ -1,23 +1,100 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ var Tr=Object.create;var ut=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var Sr=Object.getOwnPropertyNames;var Rr=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var Se=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var wr=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sr(e))!br.call(n,r)&&r!==t&&ut(n,r,{get:()=>e[r],enumerable:!(o=Pn(e,r))||o.enumerable});return n};var Re=(n,e,t)=>(t=n!=null?Tr(Rr(n)):{},wr(e||!n||!n.__esModule?ut(t,"default",{value:n,enumerable:!0}):t,n));var x=(n,e,t,o)=>{for(var r=o>1?void 0:o?Pn(e,t):e,i=n.length-1,s;i>=0;i--)(s=n[i])&&(r=(o?s(e,t,r):s(r))||r);return o&&r&&ut(e,t,r),r};import*as S from"fs/promises";import*as y from"path";import{fileURLToPath as On,pathToFileURL as _r}from"url";import*as F from"winston";var Ln=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(Ln||{}),ft=class{constructor(){this.logLevel=1;this.logger=F.createLogger({levels:{debug:0,info:1,warn:2,error:3},format:F.format.combine(F.format.label({label:"ADK"}),F.format(e=>(e.level=e.level.toUpperCase(),e))(),F.format.colorize(),F.format.timestamp(),F.format.printf(e=>`${e.level}: [${e.label}] ${e.timestamp} ${e.message}`)),transports:[new F.transports.Console]})}setLogLevel(e){this.logLevel=e}log(e,...t){this.logLevel>e||this.logger.log(e.toString(),t.join(" "))}debug(...e){this.logLevel>0||this.logger.debug(e.join(" "))}info(...e){this.logLevel>1||this.logger.info(e.join(" "))}warn(...e){this.logLevel>2||this.logger.warn(e.join(" "))}error(...e){this.logLevel>3||this.logger.error(e.join(" "))}},pt=class{setLogLevel(e){}log(e,...t){}debug(...e){}info(...e){}warn(...e){}error(...e){}},J=new ft;function Ir(n){J=n!=null?n:new pt}function Pr(){return J}function Lr(n){m.setLogLevel(n)}var m={setLogLevel(n){J.setLogLevel(n)},log(n,...e){J.log(n,...e)},debug(...n){J.debug(...n)},info(...n){J.info(...n)},warn(...n){J.warn(...n)},error(...n){J.error(...n)}};var Ke="user:",be=class{constructor(e){try{let t=e.startsWith("file://")?On(e):e;this.rootDir=y.resolve(t)}catch(t){throw new Error(`Invalid root directory: ${e}`,{cause:t})}}async saveArtifact({userId:e,sessionId:t,filename:o,artifact:r,customMetadata:i}){if(!r.inlineData&&!r.text)throw new Error("Artifact must have either inlineData or text content.");let s=ne(this.rootDir,e,t,o);await S.mkdir(s,{recursive:!0});let a=await ve(s),c=a.length>0?a[a.length-1]+1:0,l=oe(s),u=y.join(l,c.toString());await S.mkdir(u,{recursive:!0});let f=y.basename(s),p=y.join(u,f),d;if(r.inlineData){let h=r.inlineData.data||"";await S.writeFile(p,Buffer.from(h,"base64")),d=r.inlineData.mimeType||"application/octet-stream"}else r.text!==void 0&&await S.writeFile(p,r.text,"utf-8");let g=await Or(this.rootDir,e,t,o,c),C={fileName:o,mimeType:d,version:c,canonicalUri:g,customMetadata:i};return await Mr(y.join(u,"metadata.json"),C),c}async loadArtifact({userId:e,sessionId:t,filename:o,version:r}){try{let i=ne(this.rootDir,e,t,o);try{await S.access(i)}catch(d){m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} not found`,d);return}let s=await ve(i);if(s.length===0)return;let a;if(r===void 0)a=s[s.length-1];else{if(!s.includes(r)){m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} version ${r} not found`);return}a=r}let c=y.join(oe(i),a.toString()),l=y.join(c,"metadata.json"),u=await ze(l),f=y.basename(i),p=y.join(c,f);if(u.canonicalUri){let d=Nr(u.canonicalUri);if(d)try{await S.access(d),p=d}catch{m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} missing at ${d}, falling back to content path ${p}`)}}if(u.mimeType)try{let d=await S.readFile(p);return{inlineData:{mimeType:u.mimeType,data:d.toString("base64")}}}catch{m.warn(`[FileArtifactService] loadArtifact: Artifact ${o} missing at ${p}`);return}try{return{text:await S.readFile(p,"utf-8")}}catch{m.warn(`[FileArtifactService] loadArtifact: Text artifact ${o} missing at ${p}`);return}}catch(i){m.error(`[FileArtifactService] loadArtifact: Error loading artifact ${o}`,i);return}}async listArtifactKeys({userId:e,sessionId:t}){let o=new Set,r=Mn(this.rootDir,e),i=Bn(r,t);for await(let a of dt(i)){let c=await _n(a);if(c!=null&&c.fileName)o.add(c.fileName);else{let l=y.relative(i,a);o.add(kn(l))}}let s=Nn(r);for await(let a of dt(s)){let c=await _n(a);if(c!=null&&c.fileName)o.add(c.fileName);else{let l=y.relative(s,a);o.add(`${Ke}${kn(l)}`)}}return Array.from(o).sort()}async deleteArtifact({userId:e,sessionId:t,filename:o}){try{let r=ne(this.rootDir,e,t,o);await S.rm(r,{recursive:!0,force:!0})}catch(r){m.warn(`[FileArtifactService] deleteArtifact: Failed to delete artifact ${o}`,r)}}async listVersions({userId:e,sessionId:t,filename:o}){try{let r=ne(this.rootDir,e,t,o);return await ve(r)}catch(r){return m.warn(`[FileArtifactService] listVersions: Failed to list versions for artifact ${o}`,r),[]}}async listArtifactVersions({userId:e,sessionId:t,filename:o}){try{let r=ne(this.rootDir,e,t,o),i=await ve(r),s=[];for(let a of i){let c=y.join(oe(r),a.toString(),"metadata.json");try{let l=await ze(c);s.push(l)}catch(l){m.warn(`[FileArtifactService] listArtifactVersions: Failed to read artifact version ${a} at ${r}`,l)}}return s}catch(r){return m.warn(`[FileArtifactService] listArtifactVersions: Failed to list artifact versions for userId: ${e} sessionId: ${t} filename: ${o}`,r),[]}}async getArtifactVersion({userId:e,sessionId:t,filename:o,version:r}){try{let i=ne(this.rootDir,e,t,o),s=await ve(i);if(s.length===0)return;let a;if(r===void 0)a=s[s.length-1];else{if(!s.includes(r))return;a=r}let c=y.join(oe(i),a.toString(),"metadata.json");return await ze(c)}catch(i){m.warn(`[FileArtifactService] getArtifactVersion: Failed to get artifact version for userId: ${e} sessionId: ${t} filename: ${o} version: ${r}`,i);return}}};function Mn(n,e){return y.join(n,"users",e)}function kr(n,e){return!n||e.startsWith(Ke)}function Nn(n){return y.join(n,"artifacts")}function Bn(n,e){return y.join(n,"sessions",e,"artifacts")}function oe(n){return y.join(n,"versions")}function ne(n,e,t,o){let r=Mn(n,e),i;if(kr(t,o))i=Nn(r);else{if(!t)throw new Error("Session ID must be provided for session-scoped artifacts.");i=Bn(r,t)}let s=o;if(s.startsWith(Ke)&&(s=s.substring(Ke.length)),s=s.trim(),y.isAbsolute(s))throw new Error(`Absolute artifact filename ${o} is not permitted.`);let a=y.resolve(i,s),c=y.relative(i,a);if(c.startsWith("..")||y.isAbsolute(c))throw new Error(`Artifact filename ${o} escapes storage directory.`);return c===""||c==="."?y.join(i,"artifact"):a}async function ve(n){let e=oe(n);try{return(await S.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>parseInt(r.name,10)).filter(r=>!isNaN(r)).sort((r,i)=>r-i)}catch(t){return m.warn(`[FileArtifactService] getArtifactVersionsFromDir: Failed to list artifact versions from ${n}`,t),[]}}async function Or(n,e,t,o,r){let i=await ne(n,e,t,o),s=y.basename(i),a=oe(i),c=y.join(a,r.toString(),s);return _r(c).toString()}async function Mr(n,e){await S.writeFile(n,JSON.stringify(e,null,2),"utf-8")}async function ze(n){let e=await S.readFile(n,"utf-8");return JSON.parse(e)}async function _n(n){let e=await ve(n);if(e.length===0)return;let t=e[e.length-1],o=y.join(oe(n),t.toString(),"metadata.json");try{return await ze(o)}catch(r){m.warn(`[FileArtifactService] getLatestMetadata: Failed to read metadata from ${o}`,r);return}}async function*dt(n){try{let e=await S.readdir(n,{withFileTypes:!0});if(e.some(o=>o.isDirectory()&&o.name==="versions")){yield n;return}for(let o of e)if(o.isDirectory()){let r=y.join(n,o.name);for await(let i of dt(r))yield i}}catch{}}function Nr(n){try{return On(n)}catch(e){m.warn(`[FileArtifactService] fileUriToPath: Failed to convert file URI to path: ${n}`,e);return}}function kn(n){return n.split(y.sep).join("/")}import{Storage as Br}from"@google-cloud/storage";import{createPartFromBase64 as Dr,createPartFromText as Fr}from"@google/genai";var Ie=class{constructor(e){this.bucket=new Br().bucket(e)}async saveArtifact(e){if(!e.artifact.inlineData&&!e.artifact.text)throw new Error("Artifact must have either inlineData or text content.");let t=await this.listVersions(e),o=t.length>0?Math.max(...t)+1:0,r=this.bucket.file(we({...e,version:o})),i=e.customMetadata||{};return e.artifact.inlineData?(await r.save(Buffer.from(e.artifact.inlineData.data||"","base64"),{contentType:e.artifact.inlineData.mimeType,metadata:i}),o):(await r.save(e.artifact.text,{contentType:"text/plain",metadata:i}),o)}async loadArtifact(e){try{let t=e.version;if(t===void 0){let s=await this.listVersions(e);if(s.length===0)return;t=Math.max(...s)}let o=this.bucket.file(we({...e,version:t})),[[r],[i]]=await Promise.all([o.getMetadata(),o.download()]);return r.contentType==="text/plain"?Fr(i.toString("utf-8")):Dr(i.toString("base64"),r.contentType)}catch(t){m.warn(`[GcsArtifactService] loadArtifact: Failed to load artifact ${e.filename}`,t);return}}async listArtifactKeys(e){let t=`${e.appName}/${e.userId}/${e.sessionId}/`,o=`${e.appName}/${e.userId}/user/`,[[r],[i]]=await Promise.all([this.bucket.getFiles({prefix:t}),this.bucket.getFiles({prefix:o})]);return[...Dn(r,t),...Dn(i,o,"user:")].sort((s,a)=>s.localeCompare(a))}async deleteArtifact(e){let t=await this.listVersions(e);await Promise.all(t.map(o=>this.bucket.file(we({...e,version:o})).delete()))}async listVersions(e){let o=we(e)+"/",[r]=await this.bucket.getFiles({prefix:o}),i=[];for(let s of r){let a=s.name.split("/").pop(),c=parseInt(a,10);isNaN(c)||i.push(c)}return i.sort((s,a)=>s-a)}async listArtifactVersions(e){let t=await this.listVersions(e),o=[];for(let r of t){let i=await this.getArtifactVersion({...e,version:r});i&&o.push(i)}return o}async getArtifactVersion(e){try{let t=e.version;if(t===void 0){let i=await this.listVersions(e);if(i.length===0)return;t=Math.max(...i)}let o=this.bucket.file(we({...e,version:t})),[r]=await o.getMetadata();return{version:t,mimeType:r.contentType,customMetadata:r.metadata,canonicalUri:o.publicUrl()}}catch(t){m.warn(`[GcsArtifactService] getArtifactVersion: Failed to get artifact version for userId: ${e.userId} sessionId: ${e.sessionId} filename: ${e.filename} version: ${e.version}`,t);return}}};function we({appName:n,userId:e,sessionId:t,filename:o,version:r}){let i=o.startsWith("user:"),s=i?o.substring(5):o,a=i?`${n}/${e}/user/${s}`:`${n}/${e}/${t}/${s}`;return r!==void 0?`${a}/${r}`:a}function Dn(n,e,t=""){let o=new Set;for(let r of n){if(!r.name.startsWith(e))continue;let i=r.name.substring(e.length),s=$r(i);o.add(`${t}${s}`)}return[...o]}function $r(n){let e=n.split("/");return e.length<2?n:e.slice(0,-1).join("/")}function Fn(n){return n==="memory://"}var re=class{constructor(){this.artifacts={}}saveArtifact({appName:e,userId:t,sessionId:o,filename:r,artifact:i,customMetadata:s}){if(!i.inlineData&&!i.text)return Promise.reject(new Error("Artifact must have either inlineData or text content."));let a=Ce(e,t,o,r);this.artifacts[a]||(this.artifacts[a]=[]);let c=this.artifacts[a].length,l={version:c,customMetadata:s};return this.artifacts[a].push({part:i,metadata:l}),Promise.resolve(c)}loadArtifact({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=Ce(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),Promise.resolve(a[i].part)):Promise.resolve(void 0)}listArtifactKeys({appName:e,userId:t,sessionId:o}){let r=`${e}/${t}/${o}/`,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:o,filename:r}){let i=Ce(e,t,o,r);return this.artifacts[i]&&delete this.artifacts[i],Promise.resolve()}listVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=Ce(e,t,o,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)}listArtifactVersions({appName:e,userId:t,sessionId:o,filename:r}){let i=Ce(e,t,o,r),s=this.artifacts[i];return s?Promise.resolve(s.map(a=>a.metadata)):Promise.resolve([])}getArtifactVersion({appName:e,userId:t,sessionId:o,filename:r,version:i}){let s=Ce(e,t,o,r),a=this.artifacts[s];return a?(i===void 0&&(i=a.length-1),a[i]?Promise.resolve(a[i].metadata):Promise.resolve(void 0)):Promise.resolve(void 0)}};function Ce(n,e,t,o){return Gr(o)?`${n}/${e}/user/${o}`:`${n}/${e}/${t}/${o}`}function Gr(n){return n.startsWith("user:")}function qr(n){if(Fn(n))return new re;if(n.startsWith("gs://")){let e=n.split("://")[1];return new Ie(e)}if(n.startsWith("file://")){let e=n.split("://")[1];return new be(e)}throw new Error(`Unsupported artifact service URI: ${n}`)}var mt=class{constructor(e={}){this.task=e.task,this.stream=e.stream}};import{context as to,trace as no}from"@opentelemetry/api";function $n(n,e=[]){return We(n,Ur,"",e)}function Gn(n,e=[]){return We(n,Vr,"",e)}var Ur=n=>n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),Vr=n=>n.replace(/[A-Z]/g,e=>"_"+e.toLowerCase());function We(n,e,t="",o=[]){if(Array.isArray(n))return n.map(r=>We(r,e,t,o));if(typeof n=="object"&&n!==null){let r=n,i={};for(let s of Object.keys(r)){let a=e(s),c=t!==""?t+"."+s:s;o.includes(c)?i[a]=r[s]:i[a]=We(r[s],e,c,o)}return i}return n}function U(n={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...n}}function qn(n,e){let t=U();e&&Object.assign(t,e);for(let o of n)o&&(o.stateDelta&&Object.assign(t.stateDelta,o.stateDelta),o.artifactDelta&&Object.assign(t.artifactDelta,o.artifactDelta),o.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,o.requestedAuthConfigs),o.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,o.requestedToolConfirmations),o.skipSummarization!==void 0&&(t.skipSummarization=o.skipSummarization),o.transferToAgent!==void 0&&(t.transferToAgent=o.transferToAgent),o.escalate!==void 0&&(t.escalate=o.escalate));return t}function E(n={}){return{...n,id:n.id||gt(),invocationId:n.invocationId||"",author:n.author,actions:n.actions||U(),longRunningToolIds:n.longRunningToolIds||[],branch:n.branch,timestamp:n.timestamp||Date.now()}}function Q(n){return n.actions.skipSummarization||n.longRunningToolIds&&n.longRunningToolIds.length>0?!0:R(n).length===0&&B(n).length===0&&!n.partial&&!Vn(n)}function R(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionCall&&e.push(t.functionCall);return e}function B(n){let e=[];if(n.content&&n.content.parts)for(let t of n.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function Vn(n){var e;return n.content&&((e=n.content.parts)!=null&&e.length)?n.content.parts[n.content.parts.length-1].codeExecutionResult!==void 0:!1}function jr(n){var e;return(e=n.content)!=null&&e.parts?n.content.parts.map(t=>{var o;return(o=t.text)!=null?o:""}).join(""):""}var Un="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function gt(){let n="";for(let e=0;e<8;e++)n+=Un[Math.floor(Math.random()*Un.length)];return n}var zr=["actions.stateDelta","actions.artifactDelta","actions.requestedAuthConfigs","actions.requestedToolConfirmations","actions.customMetadata","content.parts.functionCall.args","content.parts.functionResponse.response"],Kr=["actions.state_delta","actions.artifact_delta","actions.requested_auth_configs","actions.requested_tool_confirmations","actions.custom_metadata","content.parts.function_call.args","content.parts.function_response.response"];function ht(n){return $n(n,Kr)}function jn(n){return Gn(n,zr)}import{context as vt,trace as ke}from"@opentelemetry/api";var Pe="0.5.0";var Wr="gen_ai.agent.description",Hr="gen_ai.agent.name",Xr="gen_ai.conversation.id",Ct="gen_ai.operation.name",zn="gen_ai.tool.call.id",Kn="gen_ai.tool.description",Wn="gen_ai.tool.name",Yr="gen_ai.tool.type",V=ke.getTracer("gcp.vertex.agent",Pe);function Le(n){try{return JSON.stringify(n)}catch{return"<not serializable>"}}function Hn({agent:n,invocationContext:e}){let t=ke.getActiveSpan();t&&t.setAttributes({[Ct]:"invoke_agent",[Wr]:n.description,[Hr]:n.name,[Xr]:e.session.id})}function Xn({tool:n,args:e,functionResponseEvent:t}){var s,a;let o=ke.getActiveSpan();if(!o)return;o.setAttributes({[Ct]:"execute_tool",[Kn]:n.description||"",[Wn]:n.name,[Yr]:n.constructor.name,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}","gcp.vertex.agent.tool_call_args":_e()?Le(e):"{}"});let r="<not specified>",i="<not specified>";if((s=t.content)!=null&&s.parts){let l=(a=t.content.parts[0])==null?void 0:a.functionResponse;l!=null&&l.id&&(r=l.id),l!=null&&l.response&&(i=l.response)}(typeof i!="object"||i===null)&&(i={result:i}),o.setAttributes({[zn]:r,"gcp.vertex.agent.event_id":t.id,"gcp.vertex.agent.tool_response":_e()?Le(i):"{}"})}function Yn({responseEventId:n,functionResponseEvent:e}){let t=ke.getActiveSpan();t&&(t.setAttributes({[Ct]:"execute_tool",[Wn]:"(merged tools)",[Kn]:"(merged tools)",[zn]:n,"gcp.vertex.agent.tool_call_args":"N/A","gcp.vertex.agent.event_id":n,"gcp.vertex.agent.llm_request":"{}","gcp.vertex.agent.llm_response":"{}"}),t.setAttribute("gcp.vertex.agent.tool_response",_e()?Le(e):"{}"))}function Jn({invocationContext:n,eventId:e,llmRequest:t,llmResponse:o}){var i,s,a;let r=ke.getActiveSpan();if(r&&(r.setAttributes({"gen_ai.system":"gcp.vertex.agent","gen_ai.request.model":t.model,"gcp.vertex.agent.invocation_id":n.invocationId,"gcp.vertex.agent.session_id":n.session.id,"gcp.vertex.agent.event_id":e,"gcp.vertex.agent.llm_request":_e()?Le(Jr(t)):"{}"}),(i=t.config)!=null&&i.topP&&r.setAttribute("gen_ai.request.top_p",t.config.topP),((s=t.config)==null?void 0:s.maxOutputTokens)!==void 0&&r.setAttribute("gen_ai.request.max_tokens",t.config.maxOutputTokens),r.setAttribute("gcp.vertex.agent.llm_response",_e()?Le(o):"{}"),o.usageMetadata&&r.setAttribute("gen_ai.usage.input_tokens",o.usageMetadata.promptTokenCount||0),(a=o.usageMetadata)!=null&&a.candidatesTokenCount&&r.setAttribute("gen_ai.usage.output_tokens",o.usageMetadata.candidatesTokenCount),o.finishReason)){let c=typeof o.finishReason=="string"?o.finishReason.toLowerCase():String(o.finishReason).toLowerCase();r.setAttribute("gen_ai.response.finish_reasons",[c])}}function Jr(n){let e={model:n.model,contents:[]};if(n.config){let{responseSchema:t,...o}=n.config;e.config=o}return e.contents=n.contents.map(t=>{var o;return{role:t.role,parts:((o=t.parts)==null?void 0:o.filter(r=>!r.inlineData))||[]}}),e}function Qn(n,e){return{next:vt.bind(n,e.next.bind(e)),return:vt.bind(n,e.return.bind(e)),throw:vt.bind(n,e.throw.bind(e)),[Symbol.asyncIterator](){return Qn(n,e[Symbol.asyncIterator]())}}}function ie(n,e,t){let o=t.call(e);return Qn(n,o)}function _e(){let n=process.env.ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS||"true";return n==="true"||n==="1"}var Oe=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,o;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((o=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&o.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 v=class{constructor(e={},t={}){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};v.APP_PREFIX="app:",v.USER_PREFIX="user:",v.TEMP_PREFIX="temp:";var se=class{constructor({hint:e,confirmed:t,payload:o}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=o}};var P=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get userId(){return this.invocationContext.userId}get sessionId(){return this.invocationContext.session.id}get agentName(){return this.invocationContext.agent.name}get state(){return new v(this.invocationContext.session.state,{})}};var L=class extends P{constructor(e){super(e.invocationContext),this.eventActions=e.eventActions||U(),this._state=new v(e.invocationContext.session.state,this.eventActions.stateDelta),this.functionCallId=e.functionCallId,this.toolConfirmation=e.toolConfirmation}get state(){return this._state}get actions(){return this.eventActions}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 o=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]=o,o}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 se({hint:e,confirmed:!1,payload:t})}};function $(){return typeof window<"u"}var He="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function Z(){let n="";for(let e=0;e<He.length;e++){let t=Math.random()*16|0;He[e]==="x"?n+=t.toString(16):He[e]==="y"?n+=(t&3|8).toString(16):n+=He[e]}return n}function Zn(n){return $()?window.atob(n):Buffer.from(n,"base64").toString()}function Xe(n){if(!process.env)return!1;let e=(process.env[n]||"").toLowerCase();return["true","1"].includes(e)}var yt=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`)}},K=class{constructor(e){this.invocationCostManager=new yt;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 eo(){return`e-${Z()}`}var At=Symbol.for("google.adk.baseAgent");function Qr(n){return typeof n=="object"&&n!==null&&At in n&&n[At]===!0}var ro;ro=At;var G=class{constructor(e){this[ro]=!0;this.name=Zr(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.beforeAgentCallback=oo(e.beforeAgentCallback),this.afterAgentCallback=oo(e.afterAgentCallback),this.setParentAgentForSubAgents()}get rootAgent(){return ti(this)}async*runAsync(e){let t=V.startSpan(`invoke_agent ${this.name}`),o=no.setSpan(to.active(),t);try{yield*ie(o,this,async function*(){let r=this.createInvocationContext(e),i=await this.handleBeforeAgentCallback(r);if(i&&(yield i),r.endInvocation)return;Hn({agent:this,invocationContext:r});for await(let a of this.runAsyncImpl(r))yield a;if(r.endInvocation)return;let s=await this.handleAfterAgentCallback(r);s&&(yield s)})}finally{t.end()}}async*runLive(e){let t=V.startSpan(`invoke_agent ${this.name}`),o=no.setSpan(to.active(),t);try{throw yield*ie(o,this,async function*(){}),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 o=t.findAgent(e);if(o)return o}}createInvocationContext(e){return new K({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new L({invocationContext:e});for(let o of this.beforeAgentCallback){let r=await o(t);if(r)return e.endInvocation=!0,E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new L({invocationContext:e});for(let o of this.afterAgentCallback){let r=await o(t);if(r)return E({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return E({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 Zr(n){if(!ei(n))throw new Error(`Found invalid agent name: "${n}". 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), underscores, and hyphens.`);if(n==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return n}function ei(n){return/^[\p{ID_Start}$_][\p{ID_Continue}$_-]*$/u.test(n)}function ti(n){for(;n.parentAgent;)n=n.parentAgent;return n}function oo(n){return n?Array.isArray(n)?n:[n]:[]}import{createUserContent as ni}from"@google/genai";import{isEmpty as io}from"lodash-es";var xt="adk-",Ye="adk_request_credential",ye="adk_request_confirmation",oi={handleFunctionCallList:Je,generateAuthEvent:Tt,generateRequestConfirmationEvent:St};function Et(){return`${xt}${Z()}`}function so(n){let e=R(n);if(e)for(let t of e)t.id||(t.id=Et())}function ao(n){if(n&&n.parts)for(let e of n.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(xt)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(xt)&&(e.functionResponse.id=void 0)}function co(n,e){let t=new Set;for(let o of n)o.name&&o.name in e&&e[o.name].isLongRunning&&o.id&&t.add(o.id);return t}function Tt(n,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs)||io(e.actions.requestedAuthConfigs))return;let t=[],o=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:Ye,args:{function_call_id:i,auth_config:s},id:Et()};o.add(a.id),t.push({functionCall:a})}return E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(o)})}function St({invocationContext:n,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations)||io(t.actions.requestedToolConfirmations))return;let o=[],r=new Set,i=R(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let u=(a=i.find(p=>p.id===c))!=null?a:void 0;if(!u)continue;let f={name:ye,args:{originalFunctionCall:u,toolConfirmation:l},id:Et()};r.add(f.id),o.push({functionCall:f})}return E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:{parts:o,role:t.content.role},actions:t.actions,longRunningToolIds:Array.from(r)})}async function ri(n,e,t){return V.startActiveSpan(`execute_tool ${n.name}`,async o=>{try{m.debug(`callToolAsync ${n.name}`);let r=await n.runAsync({args:e,toolContext:t});return Xn({tool:n,args:e,functionResponseEvent:ii(n,r,t,t.invocationContext)}),r}finally{o.end()}})}function ii(n,e,t,o){let r;typeof e!="object"||e==null?r={result:e}:r=e;let s={role:"user",parts:[{functionResponse:{name:n.name,response:r,id:t.functionCallId}}]};return E({invocationId:o.invocationId,author:o.agent.name,content:s,actions:t.actions,branch:o.branch})}async function lo({invocationContext:n,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=R(e);return await Je({invocationContext:n,functionCalls:a,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function Je({invocationContext:n,functionCalls:e,toolsDict:t,beforeToolCallbacks:o,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var u;let a=[],c=e.filter(f=>!i||f.id&&i.has(f.id));for(let f of c){let p;s&&f.id&&(p=s[f.id]);let{tool:d,toolContext:g}=si({invocationContext:n,functionCall:f,toolsDict:t,toolConfirmation:p});m.debug(`execute_tool ${d.name}`);let C=(u=f.args)!=null?u:{},h=null,T;if(h=await n.pluginManager.runBeforeToolCallback({tool:d,toolArgs:C,toolContext:g}),h==null){for(let Y of o)if(h=await Y({tool:d,args:C,context:g}),h)break}if(h==null)try{h=await ri(d,C,g)}catch(Y){if(Y instanceof Error){let In=await n.pluginManager.runOnToolErrorCallback({tool:d,toolArgs:C,toolContext:g,error:Y});In?h=In:T=Y.message}else T=Y}let M=await n.pluginManager.runAfterToolCallback({tool:d,toolArgs:C,toolContext:g,result:h});if(M==null){for(let Y of r)if(M=await Y({tool:d,args:C,context:g,response:h}),M)break}if(M!=null&&(h=M),d.isLongRunning&&!h)continue;T?h={error:T}:(typeof h!="object"||h==null)&&(h={result:h});let wn=E({invocationId:n.invocationId,author:n.agent.name,content:ni({functionResponse:{id:g.functionCallId,name:d.name,response:h}}),actions:g.actions,branch:n.branch});m.debug("traceToolCall",{tool:d.name,args:C,functionResponseEvent:wn.id}),a.push(wn)}if(!a.length)return null;let l=ai(a);return a.length>1&&V.startActiveSpan("execute_tool (merged)",f=>{try{m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id}),Yn({responseEventId:l.id,functionResponseEvent:l})}finally{f.end()}}),l}function si({invocationContext:n,functionCall:e,toolsDict:t,toolConfirmation:o}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new L({invocationContext:n,functionCallId:e.id||void 0,toolConfirmation:o});return{tool:t[e.name],toolContext:r}}function ai(n){if(!n.length)throw new Error("No function response events provided.");if(n.length===1)return n[0];let e=[];for(let i of n)i.content&&i.content.parts&&e.push(...i.content.parts);let t=n[0],o=n.map(i=>i.actions||{}),r=qn(o);return E({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Rt=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(),o=this.queue.shift();t(o)}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{context as ji,trace as zi}from"@opentelemetry/api";var ci="google-adk",li="gl-typescript",ui="remote_reasoning_engine",fi="GOOGLE_CLOUD_AGENT_ENGINE_ID";function pi(){let n=`${ci}/${Pe}`;!$()&&process.env[fi]&&(n=`${n}+${ui}`);let e=`${li}/${$()?window.navigator.userAgent:process.version}`;return[n,e]}function uo(){return pi()}var bt=Symbol.for("google.adk.baseModel");function wt(n){return typeof n=="object"&&n!==null&&bt in n&&n[bt]===!0}var fo;fo=bt;var Ae=class{constructor({model:e}){this[fo]=!0;this.model=e}get trackingHeaders(){let t=uo().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};Ae.supportedModels=[];import{createPartFromText as mo,FinishReason as di,GoogleGenAI as Pt}from"@google/genai";var Qe=(t=>(t.VERTEX_AI="VERTEX_AI",t.GEMINI_API="GEMINI_API",t))(Qe||{});function po(){return Xe("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}var Ze=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(o=>{var r;return o.parts&&((r=o.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(o=>o.functionResponse).filter(o=>!!o);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 It(n){var t;let e=n.usageMetadata;if(n.candidates&&n.candidates.length>0){let o=n.candidates[0];return(t=o.content)!=null&&t.parts&&o.content.parts.length>0?{content:o.content,groundingMetadata:o.groundingMetadata,citationMetadata:o.citationMetadata,usageMetadata:e,finishReason:o.finishReason}:{errorCode:o.finishReason,errorMessage:o.finishMessage,usageMetadata:e,citationMetadata:o.citationMetadata,finishReason:o.finishReason}}return n.promptFeedback?{errorCode:n.promptFeedback.blockReason,errorMessage:n.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var ee=class extends Ae{constructor({model:e,apiKey:t,vertexai:o,project:r,location:i,headers:s}){e||(e="gemini-2.5-flash"),super({model:e});let a=et({model:e,vertexai:o,project:r,location:i,apiKey:t});if(!a.vertexai&&!a.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.");this.project=a.project,this.location=a.location,this.apiKey=a.apiKey,this.headers=s,this.vertexai=!!a.vertexai}async*generateContentAsync(e,t=!1){var o,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}`),(o=e.config)!=null&&o.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let u=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),f="",p="",d,g;for await(let C of u){g=C;let h=It(C);d=h.usageMetadata;let T=(s=(i=h.content)==null?void 0:i.parts)==null?void 0:s[0];if(T!=null&&T.text)"thought"in T&&T.thought?f+=T.text:p+=T.text,h.partial=!0;else if((f||p)&&(!T||!T.inlineData)){let M=[];f&&M.push({text:f,thought:!0}),p&&M.push(mo(p)),yield{content:{role:"model",parts:M},usageMetadata:h.usageMetadata},f="",p=""}yield h}if((p||f)&&((c=(a=g==null?void 0:g.candidates)==null?void 0:a[0])==null?void 0:c.finishReason)===di.STOP){let C=[];f&&C.push({text:f,thought:!0}),p&&C.push({text:p}),yield{content:{role:"model",parts:C},usageMetadata:d}}}else{let u=await this.apiClient.models.generateContent({model:(l=e.model)!=null?l:this.model,contents:e.contents,config:e.config});yield It(u)}}getHttpOptions(){return{headers:{...this.trackingHeaders,...this.headers}}}get apiClient(){return this._apiClient?this._apiClient:(this.vertexai?this._apiClient=new Pt({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:this.getHttpOptions()}):this._apiClient=new Pt({apiKey:this.apiKey,httpOptions:this.getHttpOptions()}),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}getLiveHttpOptions(){return{headers:this.trackingHeaders,apiVersion:this.liveApiVersion}}get liveApiClient(){return this._liveApiClient||(this._liveApiClient=new Pt({apiKey:this.apiKey,httpOptions:this.getLiveHttpOptions()})),this._liveApiClient}async connect(e){var o,r,i,s;(o=e.liveConnectConfig)!=null&&o.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:[mo(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 Ze(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 o of t.parts)go(o.inlineData),go(o.fileData)}}};ee.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function go(n){n&&n.displayName&&(n.displayName=void 0)}function et({model:n,vertexai:e,project:t,location:o,apiKey:r}){let i={model:n,vertexai:e,project:t,location:o,apiKey:r};if(i.vertexai=!!e,!i.vertexai&&!$()&&(i.vertexai=Xe("GOOGLE_GENAI_USE_VERTEXAI")),i.vertexai){if(!$()&&!i.project&&(i.project=process.env.GOOGLE_CLOUD_PROJECT),!$()&&!i.location&&(i.location=process.env.GOOGLE_CLOUD_LOCATION),!i.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!i.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else!i.apiKey&&!$()&&(i.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY);return i}var ho="APIGEE_PROXY_URL",xe=class extends ee{constructor({model:e,proxyUrl:t,apiKey:o,vertexai:r,location:i,project:s,headers:a}){var c;if(!Co(e))throw new Error(`Model ${e} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`);if(super({...mi({model:e,vertexai:r,project:s,location:i,apiKey:o}),headers:a}),this.proxyUrl=t!=null?t:"",!$()&&!this.proxyUrl&&(this.proxyUrl=(c=process.env[ho])!=null?c:""),!this.proxyUrl)throw new Error(`Proxy URL must be provided via the constructor or ${ho} environment variable.`)}getHttpOptions(){let e=super.getHttpOptions();return e.baseUrl=this.proxyUrl,e}getLiveHttpOptions(){let e=super.getLiveHttpOptions();return e.baseUrl=this.proxyUrl,e}identifyApiVersion(){let t=(this.model.startsWith("apigee/")?this.model.substring(7):this.model).split("/");return t.length===3?t[1]:t.length===2&&t[0]!="vertex_ai"&&t[0]!="gemini"&&t[0].startsWith("v")?t[0]:this.vertexai?"v1beta1":"v1alpha"}get liveApiVersion(){return this._apigeeLiveApiVersion||(this._apigeeLiveApiVersion=this.identifyApiVersion()),this._apigeeLiveApiVersion}async*generateContentAsync(e,t=!1){var r;let o=(r=e.model)!=null?r:this.model;e.model=vo(o),yield*super.generateContentAsync(e,t)}async connect(e){var o;let t=(o=e.model)!=null?o:this.model;return e.model=vo(t),super.connect(e)}};xe.supportedModels=[/apigee\/.*/];function mi({model:n,vertexai:e,project:t,location:o,apiKey:r}){var s;let i=et({model:n,vertexai:e,project:t,location:o,apiKey:r});return i.vertexai=i.vertexai||((s=i.model)==null?void 0:s.startsWith("apigee/vertex_ai/")),i.vertexai||i.apiKey||(m.warn('No API key provided when using a Gemini model, using a fake key "-".'),i.apiKey="-"),i}function vo(n){if(!Co(n))throw new Error(`Model ${n} is not a valid Apigee model, expected apigee/[<provider>/][<version>/]<model_id>`);let e=n.split("/");return e[e.length-1]}function Co(n){let e=["vertex_ai","gemini"];if(!n.startsWith("apigee/"))return!1;let t=n.substring(7);if(t.length===0)return!1;let o=t.split("/",-1);return o[o.length-1].length===0?!1:o.length==1?!0:o.length==2?e.includes(o[0])?!0:o[0].startsWith("v"):o.length==3&&e.includes(o[0])?o[1].startsWith("v"):!1}var Lt=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 o=this.cache.keys().next().value;o!==void 0&&this.cache.delete(o)}this.cache.set(e,t)}},D=class D{static newLlm(e){return new(D.resolve(e))({model:e})}static _register(e,t){D.llmRegistryDict.has(e)&&m.info(`Updating LLM class for ${e} from ${D.llmRegistryDict.get(e)} to ${t}`),D.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)D._register(t,e)}static resolve(e){let t=D.resolveCache.get(e);if(t)return t;for(let[o,r]of D.llmRegistryDict.entries())if(new RegExp(`^${o instanceof RegExp?o.source:o}$`,o instanceof RegExp?o.flags:void 0).test(e))return D.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};D.llmRegistryDict=new Map,D.resolveCache=new Lt(32);var ae=D;ae.register(ee);ae.register(xe);var _t=Symbol.for("google.adk.baseTool");function kt(n){return typeof n=="object"&&n!==null&&_t in n&&n[_t]===!0}var yo;yo=_t;var N=class{constructor(e){this[yo]=!0;var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({llmRequest:e}){let t=this._getDeclaration();if(!t)return;if(this.name in e.toolsDict)throw new Error(`Duplicate tool name: ${this.name}`);e.toolsDict[this.name]=this;let o=gi(e);o?(o.functionDeclarations||(o.functionDeclarations=[]),o.functionDeclarations.push(t)):(e.config=e.config||{},e.config.tools=e.config.tools||[],e.config.tools.push({functionDeclarations:[t]}))}get apiVariant(){return po()}};function gi(n){var e;return(((e=n.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Ao}from"@google/genai";import{zodToJsonSchema as hi}from"zod-to-json-schema";import{toJSONSchema as vi}from"zod/v4";function Ot(n){return n!==null&&typeof n=="object"&&"parse"in n&&typeof n.parse=="function"&&"safeParse"in n&&typeof n.safeParse=="function"}function Ci(n){return Ot(n)&&!("_zod"in n)}function yi(n){return Ot(n)&&"_zod"in n}function Ai(n){var o,r;let e=n;if((o=e._def)!=null&&o.typeName)return e._def.typeName;let t=(r=e._def)==null?void 0:r.type;if(typeof t=="string"&&t)return"Zod"+t.charAt(0).toUpperCase()+t.slice(1)}function ce(n){return Ot(n)&&Ai(n)==="ZodObject"}function Ee(n){if(!ce(n))throw new Error("Expected a Zod Object");if(yi(n))return vi(n,{target:"openapi-3.0",io:"input",override:e=>{var o;let{jsonSchema:t}=e;t.additionalProperties!==void 0&&delete t.additionalProperties,t.readOnly!==void 0&&delete t.readOnly,t.maxItems!==void 0&&(t.maxItems=t.maxItems.toString()),(t.format==="email"||t.format==="uuid")&&delete t.pattern,t.minItems!==void 0&&(t.minItems=t.minItems.toString()),t.minLength!==void 0&&(t.minLength=t.minLength.toString()),t.maxLength!==void 0&&(t.maxLength=t.maxLength.toString()),((o=t.enum)==null?void 0:o.length)===1&&t.enum[0]===null&&(t.type=Ao.NULL,delete t.enum),t.type!==void 0&&(t.type=t.type.toUpperCase())}});if(Ci(n))return hi(n,{target:"openApi3",emailStrategy:"format:email",postProcess:e=>{var t,o,r,i,s,a,c;if(e)return e.additionalProperties!==void 0&&delete e.additionalProperties,e.maxItems!==void 0&&(e.maxItems=(t=e.maxItems)==null?void 0:t.toString()),e.minItems!==void 0&&(e.minItems=(o=e.minItems)==null?void 0:o.toString()),e.minLength!==void 0&&(e.minLength=(r=e.minLength)==null?void 0:r.toString()),e.maxLength!==void 0&&(e.maxLength=(i=e.maxLength)==null?void 0:i.toString()),((s=e.enum)==null?void 0:s.length)===1&&e.enum[0]==="null"&&(e.type=Ao.NULL,delete e.enum),e.type==="integer"&&e.format!=="int64"&&((a=e.minimum)!=null||(e.minimum=Number.MIN_SAFE_INTEGER),(c=e.maximum)!=null||(e.maximum=Number.MAX_SAFE_INTEGER)),e.type!==void 0&&(e.type=e.type.toUpperCase()),e}});throw new Error("Unsupported Zod schema version.")}import{z as So}from"zod";function le(n,e){n.config||(n.config={});let t=e.join(`
8
+
9
+ `);n.config.systemInstruction?n.config.systemInstruction+=`
10
+
11
+ `+t:n.config.systemInstruction=t}function xo(n,e){n.config||(n.config={}),n.config.responseSchema=e,n.config.responseMimeType="application/json"}import{Type as xi}from"@google/genai";function Ei(n){return n===void 0?{type:xi.OBJECT,properties:{}}:ce(n)?Ee(n):n}var Mt=Symbol.for("google.adk.functionTool");function Ti(n){return typeof n=="object"&&n!==null&&Mt in n&&n[Mt]===!0}var Eo,To,W=class extends(To=N,Eo=Mt,To){constructor(t){var r;let o=(r=t.name)!=null?r:t.execute.name;if(!o)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:o,description:t.description,isLongRunning:t.isLongRunning});this[Eo]=!0;this.execute=t.execute,this.parameters=t.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:Ei(this.parameters)}}async runAsync(t){try{let o=t.args;return ce(this.parameters)&&(o=this.parameters.parse(t.args)),await this.execute(o,t.toolContext)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error(`Error in tool '${this.name}': ${r}`)}}};var _=class{},Nt=class{};var Bt=class extends _{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new W({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:So.object({agentName:So.string().describe("the agent name to transfer to.")}),execute:function(t,o){if(!o)throw new Error("toolContext is required.");return o.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,o){if(!A(t.agent))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;le(o,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new L({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:o})}buildTargetAgentsInfo(t){return`
12
+ Agent name: ${t.name}
13
+ Agent description: ${t.description}
14
+ `}buildTargetAgentsInstructions(t,o){let r=`
15
+ You have a list of other agents to transfer to:
16
+
17
+ ${o.map(i=>this.buildTargetAgentsInfo(i)).join(`
18
+ `)}
19
+
20
+ If you are the best to answer the question according to your description, you
21
+ can answer it.
22
+
23
+ If another agent is better for answering the question according to its
24
+ description, call \`${this.toolName}\` function to transfer the
25
+ question to that agent. When transferring, do not generate any text other than
26
+ the function call.
27
+ `;return t.parentAgent&&!t.disallowTransferToParent&&(r+=`
28
+ Your parent agent is ${t.parentAgent.name}. If neither the other agents nor
29
+ you are best for answering the question according to the descriptions, transfer
30
+ to your parent agent.
31
+ `),r}getTransferTargets(t){let o=[];return o.push(...t.subAgents),!t.parentAgent||!A(t.parentAgent)||(t.disallowTransferToParent||o.push(t.parentAgent),t.disallowTransferToPeers||o.push(...t.parentAgent.subAgents.filter(r=>r.name!==t.name))),o}},Ro=new Bt;var Dt=class extends _{async*runAsync(e,t){var r;let o=e.agent;A(o)&&(t.model=o.canonicalModel.model,t.config={...(r=o.generateContentConfig)!=null?r:{}},o.outputSchema&&xo(t,o.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))}},bo=new Dt;import{cloneDeep as Bo}from"lodash-es";var Ft=Symbol.for("google.adk.baseCodeExecutor");function tt(n){return typeof n=="object"&&n!==null&&Ft in n&&n[Ft]===!0}var wo;wo=Ft;var Me=class{constructor(){this[wo]=!0;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 Si="^projects/[^/]+/locations/[^/]+/publishers/[^/]+/models/(.+)$";function $t(n){let e=n.match(Si);return e?e[1]:n}function Io(n){return $t(n).startsWith("gemini-")}function Ri(n){if(!/^\d+(\.\d+)*$/.test(n))return{valid:!1,major:0,minor:0,patch:0};let e=n.split(".").map(t=>parseInt(t,10));return{valid:!0,major:e[0],minor:e.length>1?e[1]:0,patch:e.length>2?e[2]:0}}function Po(n){return $t(n).startsWith("gemini-1")}function Ne(n){if(!n)return!1;let e=$t(n);if(!e.startsWith("gemini-"))return!1;let t=e.slice(7).split("-",1)[0],o=Ri(t);return o.valid&&o.major>=2}var Gt=Symbol.for("google.adk.builtInCodeExecutor");function De(n){return typeof n=="object"&&n!==null&&Gt in n&&n[Gt]===!0}var Lo,_o,Be=class extends(_o=Me,Lo=Gt,_o){constructor(){super(...arguments);this[Lo]=!0}executeCode(t){return Promise.resolve({stdout:"",stderr:"",outputFiles:[]})}processLlmRequest(t){if(t.model&&Ne(t.model)){t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({codeExecution:{}});return}throw new Error(`Gemini code execution tool is not supported for model ${t.model}`)}};import{Language as bi,Outcome as ko}from"@google/genai";import{cloneDeep as wi}from"lodash-es";function Oo(n,e){var u;if(!((u=n.parts)!=null&&u.length))return"";for(let f=0;f<n.parts.length;f++){let p=n.parts[f];if(p.executableCode&&(f===n.parts.length-1||!n.parts[f+1].codeExecutionResult))return n.parts=n.parts.slice(0,f+1),p.executableCode.code}let t=n.parts.filter(f=>f.text);if(!t.length)return"";let o=wi(t[0]),r=t.map(f=>f.text).join(`
32
+ `),i=e.map(f=>f[0]).join("|"),s=e.map(f=>f[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?(n.parts=[],c&&(o.text=c,n.parts.push(o)),n.parts.push(qt(l)),l):""}function qt(n){return{text:n,executableCode:{code:n,language:bi.PYTHON}}}function Mo(n){if(n.stderr)return{text:n.stderr,codeExecutionResult:{outcome:ko.OUTCOME_FAILED}};let e=[];return(n.stdout||!n.outputFiles)&&e.push(`Code execution result:
33
+ ${n.stdout}
34
+ `),n.outputFiles&&e.push(`Saved artifacts:
35
+ `+n.outputFiles.map(t=>t.name).join(", ")),{text:e.join(`
36
+
37
+ `),codeExecutionResult:{outcome:ko.OUTCOME_OK}}}function No(n,e,t){var r;if(!((r=n.parts)!=null&&r.length))return;let o=n.parts[n.parts.length-1];o.executableCode?n.parts[n.parts.length-1]={text:e[0]+o.executableCode.code+e[1]}:n.parts.length==1&&o.codeExecutionResult&&(n.parts[n.parts.length-1]={text:t[0]+o.codeExecutionResult.output+t[1]},n.role="user")}import{cloneDeep as Ii}from"lodash-es";var Ut="_code_execution_context",Vt="execution_session_id",ue="processed_input_files",fe="_code_executor_input_files",pe="_code_executor_error_counts",jt="_code_execution_results",Fe=class{constructor(e){this.sessionState=e;var t;this.context=(t=e.get(Ut))!=null?t:{},this.sessionState=e}getStateDelta(){return{[Ut]:Ii(this.context)}}getExecutionId(){if(Vt in this.context)return this.context[Vt]}setExecutionId(e){this.context[Vt]=e}getProcessedFileNames(){return ue in this.context?this.context[ue]:[]}addProcessedFileNames(e){ue in this.context||(this.context[ue]=[]),this.context[ue].push(...e)}getInputFiles(){return fe in this.sessionState?this.sessionState.get(fe):[]}addInputFiles(e){fe in this.sessionState||this.sessionState.set(fe,[]),this.sessionState.get(fe).push(...e)}clearInputFiles(){fe in this.sessionState&&this.sessionState.set(fe,[]),ue in this.context&&(this.context[ue]=[])}getErrorCount(e){return pe in this.sessionState&&this.sessionState.get(pe)[e]||0}incrementErrorCount(e){pe in this.sessionState||this.sessionState.set(pe,{}),this.sessionState.get(pe)[e]=this.getErrorCount(e)+1}resetErrorCount(e){if(!(pe in this.sessionState))return;let t=this.sessionState.get(pe);e in t&&delete t[e]}updateCodeExecutionResult({invocationId:e,code:t,resultStdout:o,resultStderr:r}){jt in this.sessionState||this.sessionState.set(jt,{});let i=this.sessionState.get(jt);e in i||(i[e]=[]),i[e].push({code:t,resultStdout:o,resultStderr:r,timestamp:Date.now()})}getCodeExecutionContext(){return this.sessionState.get(Ut)||{}}};var zt=class extends _{async*runAsync(e,t){if(A(e.agent)&&e.agent.codeExecutor){for await(let o of Li(e,t))yield o;if(tt(e.agent.codeExecutor))for(let o of t.contents){let r=e.agent.codeExecutor.codeBlockDelimiters.length?e.agent.codeExecutor.codeBlockDelimiters[0]:["",""];No(o,r,e.agent.codeExecutor.executionResultDelimiters)}}}},nt={"text/csv":{extension:".csv",loaderCodeTemplate:"pd.read_csv('{filename}')"}},Pi=`
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]}
72
+
73
+ {df_info}""")
74
+ `,Kt=class{async*runAsync(e,t){if(!t.partial)for await(let o of _i(e,t))yield o}},Hl=new Kt;async function*Li(n,e){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!tt(o))return;if(De(o)){o.processLlmRequest(e);return}if(!o.optimizeDataFile)return;let r=new Fe(new v(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=ki(r,e),s=new Set(r.getProcessedFileNames()),a=i.filter(c=>!s.has(c.name));for(let c of a){let l=Oi(c);if(!l)return;let u={role:"model",parts:[{text:`Processing input file: \`${c.name}\``},qt(l)]};e.contents.push(Bo(u)),yield E({invocationId:n.invocationId,author:t.name,branch:n.branch,content:u});let f=Do(n,r),p=await o.executeCode({invocationContext:n,codeExecutionInput:{code:l,inputFiles:[c],executionId:f}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:l,resultStdout:p.stdout,resultStderr:p.stderr}),r.addProcessedFileNames([c.name]);let d=await Fo(n,r,p);yield d,e.contents.push(Bo(d.content))}}async function*_i(n,e){let t=n.agent;if(!A(t))return;let o=t.codeExecutor;if(!o||!tt(o)||!e||!e.content||De(o))return;let r=new Fe(new v(n.session.state));if(r.getErrorCount(n.invocationId)>=o.errorRetryAttempts)return;let i=e.content,s=Oo(i,o.codeBlockDelimiters);if(!s)return;yield E({invocationId:n.invocationId,author:t.name,branch:n.branch,content:i});let a=Do(n,r),c=await o.executeCode({invocationContext:n,codeExecutionInput:{code:s,inputFiles:r.getInputFiles(),executionId:a}});r.updateCodeExecutionResult({invocationId:n.invocationId,code:s,resultStdout:c.stdout,resultStderr:c.stderr}),yield await Fo(n,r,c),e.content=void 0}function ki(n,e){var r;let t=n.getInputFiles(),o=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||!nt[l])continue;let u=`data_${i+1}_${a+1}${nt[l].extension}`;c.text=`
75
+ Available file: \`${u}\`
76
+ `;let f={name:u,content:Zn(c.inlineData.data),mimeType:l};o.has(u)||(n.addInputFiles([f]),t.push(f))}}return t}function Do(n,e){var r;let t=n.agent;if(!A(t)||!((r=t.codeExecutor)!=null&&r.stateful))return;let o=e.getExecutionId();return o||(o=n.session.id,e.setExecutionId(o)),o}async function Fo(n,e,t){if(!n.artifactService)throw new Error("Artifact service is not initialized.");let o={role:"model",parts:[Mo(t)]},r=U({stateDelta:e.getStateDelta()});t.stderr?e.incrementErrorCount(n.invocationId):e.resetErrorCount(n.invocationId);for(let i of t.outputFiles){let s=await n.artifactService.saveArtifact({appName:n.appName||"",userId:n.userId||"",sessionId:n.session.id,filename:i.name,artifact:{inlineData:{data:i.content,mimeType:i.mimeType}}});r.artifactDelta[i.name]=s}return E({invocationId:n.invocationId,author:n.agent.name,branch:n.branch,content:o,actions:r})}function Oi(n){function e(r){let[i]=r.split("."),s=i.replace(/[^a-zA-Z0-9_]/g,"_");return/^\d/.test(s)&&(s="_"+s),s}if(!nt[n.mimeType])return;let t=e(n.name),o=nt[n.mimeType].loaderCodeTemplate.replace("{filename}",n.name);return`
77
+ ${Pi}
78
+
79
+ # Load the dataframe.
80
+ ${t} = ${o}
81
+
82
+ # Use \`explore_df\` to guide my analysis.
83
+ explore_df(${t})
84
+ `}var $o=new zt;import{cloneDeep as Mi}from"lodash-es";function Wt(n,e,t){var s,a,c;let o=[];for(let l of n)!((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)||Ni(l)||Bi(l)||o.push(Uo(e,l)?Di(l):l);let r=Fi(o);r=$i(r);let i=[];for(let l of r){let u=Mi(l.content);ao(u),i.push(u)}return i}function qo(n,e,t){for(let o=n.length-1;o>=0;o--){let r=n[o];if(r.author==="user"||Uo(e,r))return Wt(n.slice(o),e,t)}return[]}function Ni(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Ye||((o=r.functionResponse)==null?void 0:o.name)===Ye)return!0;return!1}function Bi(n){var e,t,o;if(!((e=n.content)!=null&&e.parts))return!1;for(let r of n.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===ye||((o=r.functionResponse)==null?void 0:o.name)===ye)return!0;return!1}function Uo(n,e){return!!n&&e.author!==n&&e.author!=="user"}function Di(n){var t,o,r,i,s,a;if(!((o=(t=n.content)==null?void 0:t.parts)!=null&&o.length))return n;let e={role:"user",parts:[{text:"For context:"}]};for(let c of n.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${n.author}] said: ${c.text}`});else if(c.functionCall){let l=Go(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${n.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=Go(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${n.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return E({invocationId:n.invocationId,author:"user",content:e,branch:n.branch,timestamp:n.timestamp})}function Vo(n){var r;if(n.length===0)throw new Error("Cannot merge an empty list of events.");let e=E(n[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 o={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(o[s.functionResponse.id]=i)}for(let i of n.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 o?t[o[a]]=s:(t.push(s),o[a]=t.length-1)}else t.push(s)}return e}function Fi(n){if(n.length===0)return n;let e=n[n.length-1],t=B(e);if(!(t!=null&&t.length))return n;let o=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=n.at(-2);if(r){let c=R(r);if(c){for(let l of c)if(l.id&&o.has(l.id))return n}}let i=-1;for(let c=n.length-2;c>=0;c--){let l=n[c],u=R(l);if(u!=null&&u.length){for(let f of u)if(f.id&&o.has(f.id)){i=c;let p=new Set(u.map(g=>g.id).filter(g=>!!g));if(!Array.from(o).every(g=>p.has(g)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(p).join(", ")}, function response ids provided: ${Array.from(o).join(", ")}`);o=p;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(o).join(", ")}`);let s=[];for(let c=i+1;c<n.length-1;c++){let l=n[c],u=B(l);u&&u.some(f=>f.id&&o.has(f.id))&&s.push(l)}s.push(n[n.length-1]);let a=n.slice(0,i+1);return a.push(Vo(s)),a}function $i(n){let e=new Map;for(let o=0;o<n.length;o++){let r=n[o],i=B(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,o)}let t=[];for(let o of n){if(B(o).length>0)continue;let r=R(o);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(o),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(n[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>n[c]);t.push(Vo(a))}}else t.push(o)}return t}function Go(n){if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}var Ht=class{async*runAsync(e,t){let o=e.agent;!o||!A(o)||(o.includeContents==="default"?t.contents=Wt(e.session.events,o.name,e.branch):t.contents=qo(e.session.events,o.name,e.branch))}},jo=new Ht;var Xt=class extends _{async*runAsync(e,t){let o=e.agent,r=[`You are an agent. Your internal name is "${o.name}".`];o.description&&r.push(`The description about you is "${o.description}"`),le(t,r)}},zo=new Xt;async function Yt(n,e){let t=e.invocationContext;async function o(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),u=l.endsWith("?");if(u&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let f=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let p=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:f});if(!p)throw new Error(`Artifact ${f} not found.`);return String(p)}if(!Ui(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(u)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=n.matchAll(r);for(let c of a){i.push(n.slice(s,c.index));let l=await o(c);i.push(l),s=c.index+c[0].length}return i.push(n.slice(s)),i.join("")}var Gi=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ko(n){return n===""||n===void 0?!1:Gi.test(n)}var qi=[v.APP_PREFIX,v.USER_PREFIX,v.TEMP_PREFIX];function Ui(n){let e=n.split(":");return e.length===0||e.length>2?!1:e.length===1?Ko(n):qi.includes(e[0]+":")?Ko(e[1]):!1}var Jt=class extends _{async*runAsync(e,t){let o=e.agent;if(!A(o)||!A(o.rootAgent))return;let r=o.rootAgent;if(A(r)&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new P(e)),a=i;s&&(a=await Yt(i,new P(e))),le(t,[a])}if(o.instruction){let{instruction:i,requireStateInjection:s}=await o.canonicalInstruction(new P(e)),a=i;s&&(a=await Yt(i,new P(e))),le(t,[a])}}},Wo=new Jt;var Qt=class extends _{async*runAsync(e){let t=e.agent;if(!A(t))return;let o=e.session.events;if(!o||o.length===0)return;let r={},i=-1;for(let s=o.length-1;s>=0;s--){let a=o[s];if(a.author!=="user")continue;let c=B(a);if(!c)continue;let l=!1;for(let u of c){if(u.name!==ye)continue;l=!0;let f=null;u.response&&Object.keys(u.response).length===1&&"response"in u.response?f=JSON.parse(u.response.response):u.response&&(f=new se({hint:u.response.hint,payload:u.response.payload,confirmed:u.response.confirmed})),u.id&&f&&(r[u.id]=f)}if(l){i=s;break}}if(Object.keys(r).length!==0)for(let s=i-1;s>=0;s--){let a=o[s],c=R(a);if(!c)continue;let l={},u={};for(let g of c){if(!g.id||!(g.id in r))continue;let C=g.args;if(!C||!("originalFunctionCall"in C))continue;let h=C.originalFunctionCall;h.id&&(l[h.id]=r[g.id],u[h.id]=h)}if(Object.keys(l).length===0)continue;for(let g=o.length-1;g>i;g--){let C=o[g],h=B(C);if(h){for(let T of h)T.id&&T.id in l&&(delete l[T.id],delete u[T.id]);if(Object.keys(l).length===0)break}}if(Object.keys(l).length===0)continue;let f=await t.canonicalTools(new P(e)),p=Object.fromEntries(f.map(g=>[g.name,g])),d=await Je({invocationContext:e,functionCalls:Object.values(u),toolsDict:p,beforeToolCallbacks:t.canonicalBeforeToolCallbacks,afterToolCallbacks:t.canonicalAfterToolCallbacks,filters:new Set(Object.keys(l)),toolConfirmationDict:l});d&&(yield d);return}}},Ho=new Qt;var Zt=(o=>(o.NONE="none",o.SSE="sse",o.BIDI="bidi",o))(Zt||{});function Xo(n={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Vi(n.maxLlmCalls||500),pauseOnToolCalls:!1,...n}}function Vi(n){if(n>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return n<=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."),n}var Yo="adk_agent_name";async function Jo(n,e){return kt(n)?[n]:await n.getTools(e)}var en=Symbol.for("google.adk.llmAgent");function A(n){return typeof n=="object"&&n!==null&&en in n&&n[en]===!0}var Qo,Zo,tn=class n extends(Zo=G,Qo=en,Zo){constructor(t){var r,i,s,a,c,l,u,f,p;super(t);this[Qo]=!0;if(this.model=t.model,this.instruction=(r=t.instruction)!=null?r:"",this.globalInstruction=(i=t.globalInstruction)!=null?i:"",this.tools=(s=t.tools)!=null?s:[],this.generateContentConfig=t.generateContentConfig,this.disallowTransferToParent=(a=t.disallowTransferToParent)!=null?a:!1,this.disallowTransferToPeers=(c=t.disallowTransferToPeers)!=null?c:!1,this.includeContents=(l=t.includeContents)!=null?l:"default",this.inputSchema=ce(t.inputSchema)?Ee(t.inputSchema):t.inputSchema,this.outputSchema=ce(t.outputSchema)?Ee(t.outputSchema):t.outputSchema,this.outputKey=t.outputKey,this.beforeModelCallback=t.beforeModelCallback,this.afterModelCallback=t.afterModelCallback,this.beforeToolCallback=t.beforeToolCallback,this.afterToolCallback=t.afterToolCallback,this.codeExecutor=t.codeExecutor,this.requestProcessors=(u=t.requestProcessors)!=null?u:[bo,zo,Wo,Ho,jo,$o],this.responseProcessors=(f=t.responseProcessors)!=null?f:[],this.disallowTransferToParent&&this.disallowTransferToPeers&&!((p=this.subAgents)!=null&&p.length)||this.requestProcessors.push(Ro),t.generateContentConfig){if(t.generateContentConfig.tools)throw new Error("All tools must be set via LlmAgent.tools.");if(t.generateContentConfig.systemInstruction)throw new Error("System instruction must be set via LlmAgent.instruction.");if(t.generateContentConfig.responseSchema)throw new Error("Response schema must be set via LlmAgent.output_schema.")}else this.generateContentConfig={};this.outputSchema&&(!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)}get canonicalModel(){if(wt(this.model))return this.model;if(typeof this.model=="string"&&this.model)return ae.newLlm(this.model);let t=this.parentAgent;for(;t;){if(A(t))return t.canonicalModel;t=t.parentAgent}throw new Error(`No model found for ${this.name}.`)}async canonicalInstruction(t){return typeof this.instruction=="string"?{instruction:this.instruction,requireStateInjection:!0}:{instruction:await this.instruction(t),requireStateInjection:!1}}async canonicalGlobalInstruction(t){return typeof this.globalInstruction=="string"?{instruction:this.globalInstruction,requireStateInjection:!0}:{instruction:await this.globalInstruction(t),requireStateInjection:!1}}async canonicalTools(t){let o=[];for(let r of this.tools){let i=await Jo(r,t);o.push(...i)}return o}static normalizeCallbackArray(t){return t?Array.isArray(t)?t:[t]:[]}get canonicalBeforeModelCallbacks(){return n.normalizeCallbackArray(this.beforeModelCallback)}get canonicalAfterModelCallbacks(){return n.normalizeCallbackArray(this.afterModelCallback)}get canonicalBeforeToolCallbacks(){return n.normalizeCallbackArray(this.beforeToolCallback)}get canonicalAfterToolCallbacks(){return n.normalizeCallbackArray(this.afterToolCallback)}maybeSaveOutputToState(t){var i,s;if(t.author!==this.name){m.debug(`Skipping output save for agent ${this.name}: event authored by ${t.author}`);return}if(!this.outputKey){m.debug(`Skipping output save for agent ${this.name}: outputKey is not set`);return}if(!Q(t)){m.debug(`Skipping output save for agent ${this.name}: event is not a final response`);return}if(!((s=(i=t.content)==null?void 0:i.parts)!=null&&s.length)){m.debug(`Skipping output save for agent ${this.name}: event content is empty`);return}let o=t.content.parts.map(a=>a.text?a.text:"").join(""),r=o;if(this.outputSchema){if(!o.trim())return;try{r=JSON.parse(o)}catch(a){m.error(`Error parsing output for agent ${this.name}`,a)}}t.actions.stateDelta[this.outputKey]=r}async*runAsyncImpl(t){for(;;){let o;for await(let r of this.runOneStepAsync(t))o=r,this.maybeSaveOutputToState(r),yield r;if(!o||Q(o))break;if(o.partial){m.warn("The last event is partial, which is not expected.");break}}}async*runLiveImpl(t){for await(let o of this.runLiveFlow(t))this.maybeSaveOutputToState(o),yield o;t.endInvocation}async*runLiveFlow(t){throw await Promise.resolve(),new Error("LlmAgent.runLiveFlow not implemented")}async*runOneStepAsync(t){let o={contents:[],toolsDict:{},liveConnectConfig:{}};for(let a of this.requestProcessors)for await(let c of a.runAsync(t,o))yield c;for(let a of this.tools){let c=new L({invocationContext:t}),l=await Jo(a,new P(t));for(let u of l)await u.processLlmRequest({toolContext:c,llmRequest:o})}if(t.endInvocation)return;let r=E({invocationId:t.invocationId,author:this.name,branch:t.branch}),i=V.startSpan("call_llm"),s=zi.setSpan(ji.active(),i);yield*ie(s,this,async function*(){let a=async function*(){for await(let c of this.callLlmAsync(t,o,r))for await(let l of this.postprocess(t,o,c,r))r.id=gt(),r.timestamp=new Date().getTime(),yield l};yield*this.runAndHandleError(a.call(this),t,o,r)}),i.end()}async*postprocess(t,o,r,i){var f,p;for(let d of this.responseProcessors)for await(let g of d.runAsync(t,r))yield g;if(!r.content&&!r.errorCode&&!r.interrupted)return;let s=E({...i,...r});if(s.content){let d=R(s);d!=null&&d.length&&(so(s),s.longRunningToolIds=Array.from(co(d,o.toolsDict)))}if(yield s,!((f=R(s))!=null&&f.length))return;if((p=t.runConfig)!=null&&p.pauseOnToolCalls){t.endInvocation=!0;return}let a=await lo({invocationContext:t,functionCallEvent:s,toolsDict:o.toolsDict,beforeToolCallbacks:this.canonicalBeforeToolCallbacks,afterToolCallbacks:this.canonicalAfterToolCallbacks});if(!a)return;let c=Tt(t,a);c&&(yield c);let l=St({invocationContext:t,functionCallEvent:s,functionResponseEvent:a});if(l){yield l,t.endInvocation=!0;return}yield a;let u=a.actions.transferToAgent;if(u){let d=this.getAgentByName(t,u);for await(let g of d.runAsync(t))yield g}}getAgentByName(t,o){let i=t.agent.rootAgent.findAgent(o);if(!i)throw new Error(`Agent ${o} not found in the agent tree.`);return i}async*callLlmAsync(t,o,r){var a,c,l,u,f;let i=await this.handleBeforeModelCallback(t,o,r);if(i){yield i;return}(a=o.config)!=null||(o.config={}),(l=(c=o.config).labels)!=null||(c.labels={}),o.config.labels[Yo]||(o.config.labels[Yo]=this.name);let s=this.canonicalModel;if((u=t.runConfig)!=null&&u.supportCfc)throw new Error("CFC is not yet supported in callLlmAsync");{t.incrementLlmCallCount();let p=s.generateContentAsync(o,((f=t.runConfig)==null?void 0:f.streamingMode)==="sse");for await(let d of p){Jn({invocationContext:t,eventId:r.id,llmRequest:o,llmResponse:d});let g=await this.handleAfterModelCallback(t,d,r);yield g!=null?g:d}}}async handleBeforeModelCallback(t,o,r){let i=new L({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runBeforeModelCallback({callbackContext:i,llmRequest:o});if(s)return s;for(let a of this.canonicalBeforeModelCallbacks){let c=await a({context:i,request:o});if(c)return c}}async handleAfterModelCallback(t,o,r){let i=new L({invocationContext:t,eventActions:r.actions}),s=await t.pluginManager.runAfterModelCallback({callbackContext:i,llmResponse:o});if(s)return s;for(let a of this.canonicalAfterModelCallbacks){let c=await a({context:i,response:o});if(c)return c}}async*runAndHandleError(t,o,r,i){try{for await(let s of t)yield s}catch(s){let a=new L({invocationContext:o,eventActions:i.actions});if(s instanceof Error){let c=await o.pluginManager.runOnModelErrorCallback({callbackContext:a,llmRequest:r,error:s});if(c)yield c;else{let l="UNKNOWN_ERROR",u=s.message;try{let f=JSON.parse(s.message);f!=null&&f.error&&(l=String(f.error.code||"UNKNOWN_ERROR"),u=f.error.message||u)}catch{}i.actions?yield E({invocationId:o.invocationId,author:this.name,errorCode:l,errorMessage:u}):yield{errorCode:l,errorMessage:u}}}else throw m.error("Unknown error during response generation",s),s}}};var nn=Symbol.for("google.adk.loopAgent");function Ki(n){return typeof n=="object"&&n!==null&&nn in n&&n[nn]===!0}var er,tr,on=class extends(tr=G,er=nn,tr){constructor(t){var o;super(t);this[er]=!0;this.maxIterations=(o=t.maxIterations)!=null?o:Number.MAX_SAFE_INTEGER}async*runAsyncImpl(t){let o=0;for(;o<this.maxIterations;){for(let r of this.subAgents){let i=!1;for await(let s of r.runAsync(t))yield s,s.actions.escalate&&(i=!0);if(i)return}o++}}async*runLiveImpl(t){throw new Error("This is not supported yet for LoopAgent.")}};var rn=Symbol.for("google.adk.parallelAgent");function Wi(n){return typeof n=="object"&&n!==null&&rn in n&&n[rn]===!0}var nr,or,sn=class extends(or=G,nr=rn,or){constructor(){super(...arguments);this[nr]=!0}async*runAsyncImpl(t){let o=this.subAgents.map(r=>r.runAsync(Hi(this,r,t)));for await(let r of Xi(o))yield r}async*runLiveImpl(t){throw new Error("This is not supported yet for ParallelAgent.")}};function Hi(n,e,t){let o=new K(t),r=`${n.name}.${e.name}`;return o.branch=o.branch?`${o.branch}.${r}`:r,o}async function*Xi(n){let e=new Map;for(let[t,o]of n.entries()){let r=o.next().then(i=>({result:i,index:t}));e.set(t,r)}for(;e.size>0;){let{result:t,index:o}=await Promise.race(e.values());if(t.done){e.delete(o);continue}yield t.value;let r=n[o].next().then(i=>({result:i,index:o}));e.set(o,r)}}var an="task_completed",cn=Symbol.for("google.adk.sequentialAgent");function Yi(n){return typeof n=="object"&&n!==null&&cn in n&&n[cn]===!0}var rr,ir,ln=class extends(ir=G,rr=cn,ir){constructor(){super(...arguments);this[rr]=!0}async*runAsyncImpl(t){for(let o of this.subAgents)for await(let r of o.runAsync(t))yield r}async*runLiveImpl(t){for(let o of this.subAgents)A(o)&&((await o.canonicalTools(new P(t))).some(s=>s.name===an)||(o.tools.push(new W({name:an,description:"Signals that the model has successfully completed the user's question or task.",execute:()=>"Task completion signaled."})),o.instruction+=`If you finished the user's request according to its description, call the ${an} 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 o of this.subAgents)for await(let r of o.runLive(t))yield r}};var sr=(i=>(i.API_KEY="apiKey",i.HTTP="http",i.OAUTH2="oauth2",i.OPEN_ID_CONNECT="openIdConnect",i.SERVICE_ACCOUNT="serviceAccount",i))(sr||{});import{isEmpty as $e}from"lodash-es";var ar=(u=>(u.THOUGHT="thought",u.CONTENT="content",u.TOOL_CALL="tool_call",u.TOOL_RESULT="tool_result",u.CALL_CODE="call_code",u.CODE_RESULT="code_result",u.ERROR="error",u.ACTIVITY="activity",u.TOOL_CONFIRMATION="tool_confirmation",u.FINISHED="finished",u))(ar||{});function Ji(n){var t,o;let e=[];if(n.errorCode)return e.push({type:"error",error:new Error(n.errorMessage||n.errorCode)}),e;for(let r of(o=(t=n.content)==null?void 0:t.parts)!=null?o:[])r.functionCall&&!$e(r.functionCall)?e.push({type:"tool_call",call:r.functionCall}):r.functionResponse&&!$e(r.functionResponse)?e.push({type:"tool_result",result:r.functionResponse}):r.executableCode&&!$e(r.executableCode)?e.push({type:"call_code",code:r.executableCode}):r.codeExecutionResult&&!$e(r.codeExecutionResult)?e.push({type:"code_result",result:r.codeExecutionResult}):r.text&&(r.thought?e.push({type:"thought",content:r.text}):e.push({type:"content",content:r.text}));return n.actions.requestedToolConfirmations&&!$e(n.actions.requestedToolConfirmations)&&e.push({type:"tool_confirmation",confirmations:n.actions.requestedToolConfirmations}),Q(n)&&e.push({type:"finished",output:void 0}),e}var un=Symbol.for("google.adk.baseExampleProvider");function Qi(n){return typeof n=="object"&&n!==null&&un in n&&n[un]===!0}var cr;cr=un;var fn=class{constructor(){this[cr]=!0}};var de=class{constructor(){this.memories=[];this.sessionEvents={}}async addSessionToMemory(e){let t=lr(e.appName,e.userId);this.sessionEvents[t]||(this.sessionEvents[t]={}),this.sessionEvents[t][e.id]=e.events.filter(o=>{var r,i,s;return((s=(i=(r=o.content)==null?void 0:r.parts)==null?void 0:i.length)!=null?s:0)>0})}async searchMemory(e){var i,s;let t=lr(e.appName,e.userId);if(!this.sessionEvents[t])return Promise.resolve({memories:[]});let o=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(p=>p.text).filter(p=>!!p).join(" "),u=Zi(l);if(!u.size)continue;o.some(p=>u.has(p))&&r.memories.push({content:c.content,author:c.author,timestamp:es(c.timestamp)})}return r}};function lr(n,e){return`${n}/${e}`}function Zi(n){return new Set([...n.matchAll(/[A-Za-z]+/)].map(e=>e[0].toLowerCase()))}function es(n){return new Date(n).toISOString()}var me=class{constructor(e){this.name=e}async onUserMessageCallback(e){}async beforeRunCallback(e){}async onEventCallback(e){}async afterRunCallback(e){}async beforeAgentCallback(e){}async afterAgentCallback(e){}async beforeModelCallback(e){}async afterModelCallback(e){}async onModelErrorCallback(e){}async beforeToolCallback(e){}async afterToolCallback(e){}async onToolErrorCallback(e){}};var pn=class extends me{constructor(e="logging_plugin"){super(e)}async onUserMessageCallback({invocationContext:e,userMessage:t}){var o;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: ${(o=e.agent.name)!=null?o:"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({event:e}){this.log("\u{1F4E2} EVENT YIELDED"),this.log(` Event ID: ${e.id}`),this.log(` Author: ${e.author}`),this.log(` Content: ${this.formatContent(e.content)}`),this.log(` Final Response: ${Q(e)}`);let t=R(e);if(t.length>0){let r=t.map(i=>i.name);this.log(` Function Calls: ${r}`)}let o=B(e);if(o.length>0){let r=o.map(i=>i.name);this.log(` Function Responses: ${r}`)}e.longRunningToolIds&&e.longRunningToolIds.length>0&&this.log(` Long Running Tools: ${[...e.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({callbackContext:e}){this.log("\u{1F916} AGENT STARTING"),this.log(` Agent Name: ${e.agentName}`),this.log(` Invocation ID: ${e.invocationId}`),e.invocationContext.branch&&this.log(` Branch: ${e.invocationContext.branch}`)}async afterAgentCallback({callbackContext:e}){this.log("\u{1F916} AGENT COMPLETED"),this.log(` Agent Name: ${e.agentName}`),this.log(` Invocation ID: ${e.invocationId}`)}async beforeModelCallback({callbackContext:e,llmRequest:t}){var o;if(this.log("\u{1F9E0} LLM REQUEST"),this.log(` Model: ${(o=t.model)!=null?o:"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:o}){this.log("\u{1F527} TOOL STARTING"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${o.agentName}`),this.log(` Function Call ID: ${o.functionCallId}`),this.log(` Arguments: ${this.formatArgs(t)}`)}async afterToolCallback({tool:e,toolContext:t,result:o}){this.log("\u{1F527} TOOL COMPLETED"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${t.agentName}`),this.log(` Function Call ID: ${t.functionCallId}`),this.log(` Result: ${this.formatArgs(o)}`)}async onModelErrorCallback({callbackContext:e,error:t}){this.log("\u{1F9E0} LLM ERROR"),this.log(` Agent: ${e.agentName}`),this.log(` Error: ${t}`)}async onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){this.log("\u{1F527} TOOL ERROR"),this.log(` Tool Name: ${e.name}`),this.log(` Agent: ${o.agentName}`),this.log(` Function Call ID: ${o.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 o=[];for(let r of e.parts)if(r.text){let i=r.text.trim();i.length>t&&(i=i.substring(0,t)+"..."),o.push(`text: '${i}'`)}else r.functionCall?o.push(`function_call: ${r.functionCall.name}`):r.functionResponse?o.push(`function_response: ${r.functionResponse.name}`):r.codeExecutionResult?o.push("code_execution_result"):o.push("other_part");return o.join(" | ")}formatArgs(e,t=300){if(!e)return"{}";let o=JSON.stringify(e);return o.length>t&&(o=o.substring(0,t)+"...}"),o}};var Ge=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,o){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 '${o}', exiting early.`),i}catch(i){let s=`Error in plugin '${r.name}' during '${o}' callback: ${i}`;throw m.error(s),new Error(s)}}async runOnUserMessageCallback({userMessage:e,invocationContext:t}){return await this.runCallbacks(this.plugins,o=>o.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,o=>o.onEventCallback({invocationContext:e,event:t}),"onEventCallback")}async runBeforeAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.beforeAgentCallback({agent:e,callbackContext:t}),"beforeAgentCallback")}async runAfterAgentCallback({agent:e,callbackContext:t}){return await this.runCallbacks(this.plugins,o=>o.afterAgentCallback({agent:e,callbackContext:t}),"afterAgentCallback")}async runBeforeToolCallback({tool:e,toolArgs:t,toolContext:o}){return await this.runCallbacks(this.plugins,r=>r.beforeToolCallback({tool:e,toolArgs:t,toolContext:o}),"beforeToolCallback")}async runAfterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}){return await this.runCallbacks(this.plugins,i=>i.afterToolCallback({tool:e,toolArgs:t,toolContext:o,result:r}),"afterToolCallback")}async runOnModelErrorCallback({callbackContext:e,llmRequest:t,error:o}){return await this.runCallbacks(this.plugins,r=>r.onModelErrorCallback({callbackContext:e,llmRequest:t,error:o}),"onModelErrorCallback")}async runBeforeModelCallback({callbackContext:e,llmRequest:t}){return await this.runCallbacks(this.plugins,o=>o.beforeModelCallback({callbackContext:e,llmRequest:t}),"beforeModelCallback")}async runAfterModelCallback({callbackContext:e,llmResponse:t}){return await this.runCallbacks(this.plugins,o=>o.afterModelCallback({callbackContext:e,llmResponse:t}),"afterModelCallback")}async runOnToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}){return await this.runCallbacks(this.plugins,i=>i.onToolErrorCallback({tool:e,toolArgs:t,toolContext:o,error:r}),"onToolErrorCallback")}};var fr="adk_request_confirmation",dn="orcas_tool_call_security_check_states",ur="This tool call needs external confirmation before completion.",pr=(o=>(o.DENY="DENY",o.CONFIRM="CONFIRM",o.ALLOW="ALLOW",o))(pr||{}),ot=class{async evaluate(){return Promise.resolve({outcome:"ALLOW",reason:"For prototyping purpose, all tool calls are allowed."})}},mn=class extends me{constructor(e){var t;super("security_plugin"),this.policyEngine=(t=e==null?void 0:e.policyEngine)!=null?t:new ot}async beforeToolCallback({tool:e,toolArgs:t,toolContext:o}){let r=this.getToolCallCheckState(o);if(!r)return this.checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o});if(r==="CONFIRM"){if(!o.toolConfirmation)return{partial:ur};if(this.setToolCallCheckState(o,o.toolConfirmation),!o.toolConfirmation.confirmed)return{error:"Tool call rejected from confirmation flow."};o.toolConfirmation=void 0}}getToolCallCheckState(e){var r;let{functionCallId:t}=e;return t?((r=e.state.get(dn))!=null?r:{})[t]:void 0}setToolCallCheckState(e,t){var i;let{functionCallId:o}=e;if(!o)return;let r=(i=e.state.get(dn))!=null?i:{};r[o]=t,e.state.set(dn,r)}async checkToolCallPolicy({tool:e,toolArgs:t,toolContext:o}){let r=await this.policyEngine.evaluate({tool:e,toolArgs:t});switch(this.setToolCallCheckState(o,r.outcome),r.outcome){case"DENY":return{error:`This tool call is rejected by policy engine. Reason: ${r.reason}`};case"CONFIRM":return o.requestConfirmation({hint:`Policy engine requires confirmation calling tool: ${e.name}. Reason: ${r.reason}`}),{partial:ur};case"ALLOW":return;default:return}}};function ts(n){if(!n.content||!n.content.parts)return[];let e=[];for(let t of n.content.parts)t&&t.functionCall&&t.functionCall.name===fr&&e.push(t.functionCall);return e}import{cloneDeep as dr}from"lodash-es";import{cloneDeep as ns}from"lodash-es";var ge=class{async getOrCreateSession(e){if(!e.sessionId)return this.createSession(e);let t=await this.getSession({appName:e.appName,userId:e.userId,sessionId:e.sessionId});return t||this.createSession(e)}async appendEvent({session:e,event:t}){return t.partial||(t=gn(t),this.updateSessionState({session:e,event:t}),e.events.push(t)),t}updateSessionState({session:e,event:t}){if(!(!t.actions||!t.actions.stateDelta))for(let[o,r]of Object.entries(t.actions.stateDelta))o.startsWith(v.TEMP_PREFIX)||(e.state[o]=r)}};function gn(n){if(!n.actions||!n.actions.stateDelta)return n;let e=n.actions.stateDelta,t={};for(let[o,r]of Object.entries(e))o.startsWith(v.TEMP_PREFIX)||(t[o]=r);return n.actions.stateDelta=t,n}function H(n={},e={},t={}){let o=ns(t);for(let[r,i]of Object.entries(n))o[v.APP_PREFIX+r]=i;for(let[r,i]of Object.entries(e))o[v.USER_PREFIX+r]=i;return o}function te(n){return{id:n.id,appName:n.appName,userId:n.userId||"",state:n.state||{},events:n.events||[],lastUpdateTime:n.lastUpdateTime||0}}function mr(n){return n==="memory://"}var X=class extends ge{constructor(){super(...arguments);this.sessions={};this.userState={};this.appState={}}async createSession({appName:t,userId:o,state:r,sessionId:i}){var c;let s=te({id:i||Z(),appName:t,userId:o,state:r,events:[],lastUpdateTime:Date.now()});this.sessions[t]||(this.sessions[t]={}),this.sessions[t][o]||(this.sessions[t][o]={}),this.sessions[t][o][s.id]=s;let a=dr(s);return a.state=H(this.appState[t],(c=this.userState[t])==null?void 0:c[o],a.state),a}async getSession({appName:t,userId:o,sessionId:r,config:i}){var c;if(!this.sessions[t]||!this.sessions[t][o]||!this.sessions[t][o][r])return Promise.resolve(void 0);let s=this.sessions[t][o][r],a=dr(s);if(i&&(i.numRecentEvents&&(a.events=a.events.slice(-i.numRecentEvents)),i.afterTimestamp)){let l=a.events.length-1;for(;l>=0&&!(a.events[l].timestamp<i.afterTimestamp);)l--;l>=0&&(a.events=a.events.slice(l+1))}return a.state=H(this.appState[t],(c=this.userState[t])==null?void 0:c[o],a.state),a}listSessions({appName:t,userId:o}){if(!this.sessions[t]||!this.sessions[t][o])return Promise.resolve({sessions:[]});let r=[];for(let i of Object.values(this.sessions[t][o]))r.push(te({id:i.id,appName:i.appName,userId:i.userId,state:{},events:[],lastUpdateTime:i.lastUpdateTime}));return Promise.resolve({sessions:r})}async deleteSession({appName:t,userId:o,sessionId:r}){await this.getSession({appName:t,userId:o,sessionId:r})&&delete this.sessions[t][o][r]}async appendEvent({session:t,event:o}){await super.appendEvent({session:t,event:o}),t.lastUpdateTime=o.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`),o;if(!this.sessions[r][i])return a(`userId ${i} not in sessions[appName]`),o;if(!this.sessions[r][i][s])return a(`sessionId ${s} not in sessions[appName][userId]`),o;if(o.actions&&o.actions.stateDelta)for(let l of Object.keys(o.actions.stateDelta))l.startsWith(v.APP_PREFIX)&&(this.appState[r]=this.appState[r]||{},this.appState[r][l.replace(v.APP_PREFIX,"")]=o.actions.stateDelta[l]),l.startsWith(v.USER_PREFIX)&&(this.userState[r]=this.userState[r]||{},this.userState[r][i]=this.userState[r][i]||{},this.userState[r][i][l.replace(v.USER_PREFIX,"")]=o.actions.stateDelta[l]);let c=this.sessions[r][i][s];return await super.appendEvent({session:c,event:o}),c.lastUpdateTime=o.timestamp,o}};import{createPartFromText as os}from"@google/genai";import{context as rs,trace as is}from"@opentelemetry/api";var he=class{constructor(e){var t;this.appName=e.appName,this.agent=e.agent,this.pluginManager=new Ge((t=e.plugins)!=null?t:[]),this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.credentialService=e.credentialService}async*runEphemeral(e){let o=(await this.sessionService.createSession({appName:this.appName,userId:e.userId})).id;try{yield*this.runAsync({userId:e.userId,sessionId:o,newMessage:e.newMessage,stateDelta:e.stateDelta,runConfig:e.runConfig})}finally{await this.sessionService.deleteSession({appName:this.appName,userId:e.userId,sessionId:o})}}async*runAsync(e){let{userId:t,sessionId:o,stateDelta:r}=e,i=Xo(e.runConfig),s=e.newMessage,a=V.startSpan("invocation"),c=is.setSpan(rs.active(),a);try{yield*ie(c,this,async function*(){var p;let l=await this.sessionService.getSession({appName:this.appName,userId:t,sessionId:o});if(!l)throw this.appName?new Error(`Session not found: ${o}`):new Error("Session lookup failed: appName must be provided in runner constructor");if(i.supportCfc&&A(this.agent)){let d=this.agent.canonicalModel.model;if(!Ne(d))throw new Error(`CFC is not supported for model: ${d} in agent: ${this.agent.name}`);De(this.agent.codeExecutor)||(this.agent.codeExecutor=new Be)}let u=new K({artifactService:this.artifactService,sessionService:this.sessionService,memoryService:this.memoryService,credentialService:this.credentialService,invocationId:eo(),agent:this.agent,session:l,userContent:s,runConfig:i,pluginManager:this.pluginManager}),f=await this.pluginManager.runOnUserMessageCallback({userMessage:s,invocationContext:u});if(f&&(s=f),s){if(!((p=s.parts)!=null&&p.length))throw new Error("No parts in the newMessage.");i.saveInputBlobsAsArtifacts&&await this.saveArtifacts(u.invocationId,l.userId,l.id,s),await this.sessionService.appendEvent({session:l,event:E({invocationId:u.invocationId,author:"user",actions:r?U({stateDelta:r}):void 0,content:s})})}if(u.agent=this.determineAgentForResumption(l,this.agent),s){let d=await this.pluginManager.runBeforeRunCallback({invocationContext:u});if(d){let g=E({invocationId:u.invocationId,author:"model",content:d});await this.sessionService.appendEvent({session:l,event:g}),yield g}else{for await(let g of u.agent.runAsync(u)){g.partial||await this.sessionService.appendEvent({session:l,event:g});let C=await this.pluginManager.runOnEventCallback({invocationContext:u,event:g});C?yield C:yield g}await this.pluginManager.runAfterRunCallback({invocationContext:u})}}})}finally{a.end()}}async saveArtifacts(e,t,o,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:o,filename:c,artifact:a}),r.parts[s]=os(`Uploaded file: ${c}. It is saved into artifacts`)}}determineAgentForResumption(e,t){let o=ss(e.events);if(o&&o.author)return t.findAgent(o.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(!A(t)||t.disallowTransferToParent)return!1;t=t.parentAgent}return!0}};function ss(n){var o,r,i,s;if(!n.length)return null;let t=(s=(i=(r=(o=n[n.length-1].content)==null?void 0:o.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=n.length-2;a>=0;a--){let c=n[a],l=R(c);if(l){for(let u of l)if(u.id===t)return c}}return null}var hn=class extends he{constructor({agent:e,appName:t="InMemoryRunner",plugins:o=[]}){super({appName:t,agent:e,plugins:o,artifactService:new re,sessionService:new X,memoryService:new de})}};import{Type as it}from"@google/genai";var rt=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(){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)}listArtifactVersions(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.listArtifactVersions(e)}getArtifactVersion(e){if(!this.toolContext.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.toolContext.invocationContext.artifactService.getArtifactVersion(e)}};var vn=Symbol.for("google.adk.agentTool");function as(n){return typeof n=="object"&&n!==null&&vn in n&&n[vn]===!0}var gr,hr,Cn=class extends(hr=N,gr=vn,hr){constructor(t){super({name:t.agent.name,description:t.agent.description||""});this[gr]=!0;this.agent=t.agent,this.skipSummarization=t.skipSummarization||!1}_getDeclaration(){let t;if(A(this.agent)&&this.agent.inputSchema?t={name:this.name,description:this.description,parameters:this.agent.inputSchema}:t={name:this.name,description:this.description,parameters:{type:it.OBJECT,properties:{request:{type:it.STRING}},required:["request"]}},this.apiVariant!=="GEMINI_API"){let o=A(this.agent)&&this.agent.outputSchema;t.response=o?{type:it.OBJECT}:{type:it.STRING}}return t}async runAsync({args:t,toolContext:o}){var f,p;this.skipSummarization&&(o.actions.skipSummarization=!0);let i={role:"user",parts:[{text:A(this.agent)&&this.agent.inputSchema?JSON.stringify(t):t.request}]},s=new he({appName:this.agent.name,agent:this.agent,artifactService:new rt(o),sessionService:new X,memoryService:new de,credentialService:o.invocationContext.credentialService}),a=await s.sessionService.createSession({appName:this.agent.name,userId:"tmp_user",state:o.state.toRecord()}),c;for await(let d of s.runAsync({userId:a.userId,sessionId:a.id,newMessage:i}))d.actions.stateDelta&&o.state.update(d.actions.stateDelta),c=d;if(!((p=(f=c==null?void 0:c.content)==null?void 0:f.parts)!=null&&p.length))return"";let l=A(this.agent)&&this.agent.outputSchema,u=c.content.parts.map(d=>d.text).filter(d=>d).join(`
85
+ `);return l?JSON.parse(u):u}};var yn=Symbol.for("google.adk.baseToolset");function cs(n){return typeof n=="object"&&n!==null&&yn in n&&n[yn]===!0}var vr;vr=yn;var qe=class{constructor(e,t){this.toolFilter=e;this.prefix=t;this[vr]=!0}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 st=class extends N{constructor(){super({name:"exit_loop",description:`Exits the loop.
86
+
87
+ Call this function only when you are instructed to do so.`})}_getDeclaration(){return{name:this.name,description:this.description}}async runAsync({toolContext:e}){return e.actions.escalate=!0,e.actions.skipSummarization=!0,""}},ls=new st;var at=class extends N{constructor(){super({name:"google_search",description:"Google Search Tool"})}runAsync(){return Promise.resolve()}async processLlmRequest({llmRequest:e}){if(e.model){if(e.config=e.config||{},e.config.tools=e.config.tools||[],Po(e.model)){if(e.config.tools.length>0)throw new Error("Google search tool can not be used with other tools in Gemini 1.x.");e.config.tools.push({googleSearchRetrieval:{}});return}if(Io(e.model)){e.config.tools.push({googleSearch:{}});return}throw new Error(`Google search tool is not supported for model ${e.model}`)}}},us=new at;var Cr=`
88
+
89
+ NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.`,An=class extends W{constructor(e){super({...e,isLongRunning:!0})}_getDeclaration(){let e=super._getDeclaration();return e.description?e.description+=Cr:e.description=Cr.trimStart(),e}};import{LockMode as ps,MikroORM as ds}from"@mikro-orm/core";import{MikroORM as Sn}from"@mikro-orm/core";import{Entity as Ue,JsonType as fs,PrimaryKey as O,Property as q}from"@mikro-orm/core";var En="schema_version",Tn="1",xn=class extends fs{convertToDatabaseValue(e){return JSON.stringify(jn(e))}convertToJSValue(e){return typeof e=="string"?ht(JSON.parse(e)):ht(e)}},j=class{};x([O({type:"string"})],j.prototype,"key",2),x([q({type:"string"})],j.prototype,"value",2),j=x([Ue({tableName:"adk_internal_metadata"})],j);var k=class{constructor(){this.updateTime=new Date}};x([O({type:"string",fieldName:"app_name"})],k.prototype,"appName",2),x([q({type:"json"})],k.prototype,"state",2),x([q({type:"datetime",fieldName:"update_time",onCreate:()=>new Date,onUpdate:()=>new Date})],k.prototype,"updateTime",2),k=x([Ue({tableName:"app_states"})],k);O.name;var I=class{constructor(){this.updateTime=new Date}};x([O({type:"string",fieldName:"app_name"})],I.prototype,"appName",2),x([O({type:"string",fieldName:"user_id"})],I.prototype,"userId",2),x([q({type:"json"})],I.prototype,"state",2),x([q({type:"datetime",fieldName:"update_time",onCreate:()=>new Date,onUpdate:()=>new Date})],I.prototype,"updateTime",2),I=x([Ue({tableName:"user_states"})],I);O.name;var b=class{constructor(){this.createTime=new Date;this.updateTime=new Date}};x([O({type:"string"})],b.prototype,"id",2),x([O({type:"string",fieldName:"app_name"})],b.prototype,"appName",2),x([O({type:"string",fieldName:"user_id"})],b.prototype,"userId",2),x([q({type:"json"})],b.prototype,"state",2),x([q({type:"datetime",fieldName:"create_time",onCreate:()=>new Date})],b.prototype,"createTime",2),x([q({type:"datetime",fieldName:"update_time",onCreate:()=>new Date})],b.prototype,"updateTime",2),b=x([Ue({tableName:"sessions"})],b);O.name;var w=class{};x([O({type:"string"})],w.prototype,"id",2),x([O({type:"string",fieldName:"app_name"})],w.prototype,"appName",2),x([O({type:"string",fieldName:"user_id"})],w.prototype,"userId",2),x([O({type:"string",fieldName:"session_id"})],w.prototype,"sessionId",2),x([q({type:"string",fieldName:"invocation_id"})],w.prototype,"invocationId",2),x([q({type:"datetime"})],w.prototype,"timestamp",2),x([q({type:xn,fieldName:"event_data"})],w.prototype,"eventData",2),w=x([Ue({tableName:"events"})],w);var Ve=[j,k,I,b,w];async function Rn(n){let e;if(n.startsWith("postgres://")||n.startsWith("postgresql://")){let{PostgreSqlDriver:c}=await Promise.resolve().then(()=>Re(Se("@mikro-orm/postgresql"),1));e=c}else if(n.startsWith("mysql://")){let{MySqlDriver:c}=await Promise.resolve().then(()=>Re(Se("@mikro-orm/mysql"),1));e=c}else if(n.startsWith("mariadb://")){let{MariaDbDriver:c}=await Promise.resolve().then(()=>Re(Se("@mikro-orm/mariadb"),1));e=c}else if(n.startsWith("sqlite://")){let{SqliteDriver:c}=await Promise.resolve().then(()=>Re(Se("@mikro-orm/sqlite"),1));e=c}else if(n.startsWith("mssql://")){let{MsSqlDriver:c}=await Promise.resolve().then(()=>Re(Se("@mikro-orm/mssql"),1));e=c}else throw new Error(`Unsupported database URI: ${n}`);if(n==="sqlite://:memory:")return{entities:Ve,dbName:":memory:",driver:e};let{host:t,port:o,username:r,password:i,pathname:s}=new URL(n),a=t.split(":")[0];return{entities:Ve,dbName:s.slice(1),host:a,port:o?parseInt(o):void 0,user:r,password:i,driver:e}}async function yr(n){let e;n instanceof Sn?e=n:typeof n=="string"?e=await Sn.init(await Rn(n)):e=await Sn.init(n),await e.schema.ensureDatabase(),await e.schema.updateSchema()}async function Ar(n){let e=n.em.fork(),t=await e.findOne(j,{key:En});if(t){if(t.value!==Tn)throw new Error(`ADK Database schema version ${t.value} is not compatible.`);return}let o=e.create(j,{key:En,value:Tn});await e.persist(o).flush()}function xr(n){return n?n.startsWith("postgres://")||n.startsWith("postgresql://")||n.startsWith("mysql://")||n.startsWith("mariadb://")||n.startsWith("mssql://")||n.startsWith("sqlite://"):!1}var je=class extends ge{constructor(t){super();this.initialized=!1;if(typeof t=="string")this.connectionString=t;else{if(!t.driver)throw new Error("Driver is required when passing options object.");this.options={...t,entities:Ve}}}async init(){this.initialized||(this.connectionString&&(!this.options||!this.options.driver)&&(this.options=await Rn(this.connectionString)),this.orm=await ds.init(this.options),await yr(this.orm),await Ar(this.orm),this.initialized=!0)}async createSession({appName:t,userId:o,state:r,sessionId:i}){await this.init();let s=this.orm.em.fork(),a=i||Z(),c=new Date;if(await s.findOne(b,{id:a,appName:t,userId:o}))throw new Error(`Session with id ${a} already exists.`);let u=await s.findOne(k,{appName:t});u||(u=s.create(k,{appName:t,state:{},updateTime:c}),s.persist(u));let f=await s.findOne(I,{appName:t,userId:o});f||(f=s.create(I,{appName:t,userId:o,state:{}}),s.persist(f));let p={},d={},g={};if(r)for(let[T,M]of Object.entries(r))T.startsWith(v.APP_PREFIX)?p[T.replace(v.APP_PREFIX,"")]=M:T.startsWith(v.USER_PREFIX)?d[T.replace(v.USER_PREFIX,"")]=M:g[T]=M;Object.keys(p).length>0&&(u.state={...u.state,...p}),Object.keys(d).length>0&&(f.state={...f.state,...d});let C=s.create(b,{id:a,appName:t,userId:o,state:g,createTime:c,updateTime:c});s.persist(C),await s.flush();let h=H(u.state,f.state,g);return te({id:a,appName:t,userId:o,state:h,events:[],lastUpdateTime:C.createTime.getTime()})}async getSession({appName:t,userId:o,sessionId:r,config:i}){await this.init();let s=this.orm.em.fork(),a=await s.findOne(b,{appName:t,userId:o,id:r});if(!a)return;let c={appName:t,userId:o,sessionId:r};i!=null&&i.afterTimestamp&&(c.timestamp={$gt:new Date(i.afterTimestamp)});let l=await s.find(w,c,{orderBy:{timestamp:"DESC"},limit:i==null?void 0:i.numRecentEvents});l.reverse();let u=await s.findOne(k,{appName:t}),f=await s.findOne(I,{appName:t,userId:o}),p=H((u==null?void 0:u.state)||{},(f==null?void 0:f.state)||{},a.state);return te({id:r,appName:t,userId:o,state:p,events:l.map(d=>d.eventData),lastUpdateTime:a.updateTime.getTime()})}async listSessions({appName:t,userId:o}){await this.init();let r=this.orm.em.fork(),i={appName:t};o&&(i.userId=o);let s=await r.find(b,i),a=await r.findOne(k,{appName:t}),c=(a==null?void 0:a.state)||{},l={};if(o){let f=await r.findOne(I,{appName:t,userId:o});f&&(l[o]=f.state)}else{let f=await r.find(I,{appName:t});for(let p of f)l[p.userId]=p.state}return{sessions:s.map(f=>{let p=l[f.userId]||{},d=H(c,p,f.state);return te({id:f.id,appName:f.appName,userId:f.userId,state:d,events:[],lastUpdateTime:f.updateTime.getTime()})})}}async deleteSession({appName:t,userId:o,sessionId:r}){await this.init();let i=this.orm.em.fork();await i.nativeDelete(b,{appName:t,userId:o,id:r}),await i.nativeDelete(w,{appName:t,userId:o,sessionId:r})}async appendEvent({session:t,event:o}){await this.init();let r=this.orm.em.fork();if(o.partial)return o;let i=gn(o);return await r.transactional(async s=>{let a=await s.findOne(b,{appName:t.appName,userId:t.userId,id:t.id},{lockMode:ps.PESSIMISTIC_WRITE});if(!a)throw new Error(`Session ${t.id} not found for appendEvent`);let c=await s.findOne(k,{appName:t.appName});c||(c=s.create(k,{appName:t.appName,state:{},updateTime:new Date}),s.persist(c));let l=await s.findOne(I,{appName:t.appName,userId:t.userId});if(l||(l=s.create(I,{appName:t.appName,userId:t.userId,state:{}}),s.persist(l)),a.updateTime.getTime()>t.lastUpdateTime){let p=await s.find(w,{appName:t.appName,userId:t.userId,sessionId:t.id},{orderBy:{timestamp:"ASC"}}),d=H(c.state,l.state,a.state);t.state=d,t.events=p.map(g=>g.eventData)}if(o.actions&&o.actions.stateDelta){let p={},d={},g={};for(let[C,h]of Object.entries(o.actions.stateDelta))C.startsWith(v.APP_PREFIX)?p[C.replace(v.APP_PREFIX,"")]=h:C.startsWith(v.USER_PREFIX)?d[C.replace(v.USER_PREFIX,"")]=h:g[C]=h;Object.keys(p).length>0&&(c.state={...c.state,...p}),Object.keys(d).length>0&&(l.state={...l.state,...d}),Object.keys(g).length>0&&(a.state={...a.state,...g})}let u=s.create(w,{id:i.id,appName:t.appName,userId:t.userId,sessionId:t.id,invocationId:i.invocationId,timestamp:new Date(i.timestamp),eventData:i});s.persist(u),await s.commit(),a.updateTime=new Date(o.timestamp);let f=H(c.state,l.state,a.state);t.state=f,t.events.push(o),t.lastUpdateTime=a.updateTime.getTime()}),o}};function ms(n){if(mr(n))return new X;if(xr(n))return new je(n);throw new Error(`Unsupported session service URI: ${n}`)}import{MetricExporter as gs}from"@google-cloud/opentelemetry-cloud-monitoring-exporter";import{TraceExporter as hs}from"@google-cloud/opentelemetry-cloud-trace-exporter";import{gcpDetector as vs}from"@opentelemetry/resource-detector-gcp";import{detectResources as Cs}from"@opentelemetry/resources";import{PeriodicExportingMetricReader as ys}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as As}from"@opentelemetry/sdk-trace-base";import{GoogleAuth as xs}from"google-auth-library";var Es="Cannot determine GCP Project. OTel GCP Exporters cannot be set up. Please make sure to log into correct GCP Project.";async function Ts(){try{return await new xs().getProjectId()||void 0}catch{return}}async function Em(n={}){let{enableTracing:e=!1,enableMetrics:t=!1}=n,o=await Ts();return o?{spanProcessors:e?[new As(new hs({projectId:o}))]:[],metricReaders:t?[new ys({exporter:new gs({projectId:o}),exportIntervalMillis:5e3})]:[],logRecordProcessors:[]}:(m.warn(Es),{})}function Tm(){return Cs({detectors:[vs]})}import{metrics as Ss,trace as Rs}from"@opentelemetry/api";import{logs as bs}from"@opentelemetry/api-logs";import{OTLPLogExporter as ws}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as Is}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as Ps}from"@opentelemetry/exporter-trace-otlp-http";import{detectResources as Ls}from"@opentelemetry/resources";import{BatchLogRecordProcessor as _s,LoggerProvider as ks}from"@opentelemetry/sdk-logs";import{MeterProvider as Os,PeriodicExportingMetricReader as Ms}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as Ns}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as Bs}from"@opentelemetry/sdk-trace-node";function $m(n=[],e){let t=e||Ds(),o=[...n,$s()],r=o.flatMap(a=>a.spanProcessors||[]),i=o.flatMap(a=>a.metricReaders||[]),s=o.flatMap(a=>a.logRecordProcessors||[]);if(r.length>0){let a=new Bs({resource:t,spanProcessors:r});a.register(),Rs.setGlobalTracerProvider(a)}if(i.length>0){let a=new Os({readers:i,resource:t});Ss.setGlobalMeterProvider(a)}if(s.length>0){let a=new ks({resource:t,processors:s});bs.setGlobalLoggerProvider(a)}}function Ds(){return Ls({detectors:[]})}function Fs(){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 $s(n=Fs()){let{enableTracing:e,enableMetrics:t,enableLogging:o}=n;return{spanProcessors:e?[new Ns(new Ps)]:[],metricReaders:t?[new Ms({exporter:new Is})]:[],logRecordProcessors:o?[new _s(new ws)]:[]}}import{Client as Gs}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as qs}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Us}from"@modelcontextprotocol/sdk/client/streamableHttp.js";var ct=class{constructor(e){this.connectionParams=e}async createSession(){var t;let e=new Gs({name:"MCPClient",version:"1.0.0"});switch(this.connectionParams.type){case"StdioConnectionParams":await e.connect(new qs(this.connectionParams.serverParams));break;case"StreamableHTTPConnectionParams":{let o=(t=this.connectionParams.transportOptions)!=null?t:{};!o.requestInit&&this.connectionParams.header!==void 0&&(o.requestInit={headers:this.connectionParams.header}),await e.connect(new Us(new URL(this.connectionParams.url),o));break}default:{let o=this.connectionParams;break}}return e}};import{Type as z}from"@google/genai";import{z as Te}from"zod";var Ym=Te.object({type:Te.literal("object"),properties:Te.record(Te.string(),Te.unknown()).optional(),required:Te.string().array().optional()});function Vs(n){if(!n)return z.TYPE_UNSPECIFIED;switch(n.toLowerCase()){case"text":case"string":return z.STRING;case"number":return z.NUMBER;case"boolean":return z.BOOLEAN;case"integer":return z.INTEGER;case"array":return z.ARRAY;case"object":return z.OBJECT;default:return z.TYPE_UNSPECIFIED}}function bn(n){if(!n)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 o=Vs(t.type),r={type:o,description:t.description};if(o===z.OBJECT){if(r.properties={},t.properties)for(let i in t.properties)r.properties[i]=e(t.properties[i]);r.required=t.required}else o===z.ARRAY&&t.items&&(r.items=e(t.items));return r}return e(n)}var lt=class extends N{constructor(e,t){super({name:e.name,description:e.description||""}),this.mcpTool=e,this.mcpSessionManager=t}_getDeclaration(){return{name:this.mcpTool.name,description:this.mcpTool.description,parameters:bn(this.mcpTool.inputSchema),response:bn(this.mcpTool.outputSchema)}}async runAsync(e){let t=await this.mcpSessionManager.createSession(),o={};return o.params={name:this.mcpTool.name,arguments:e.args},await t.callTool(o.params)}};var Er=class extends qe{constructor(e,t=[],o){super(t,o),this.mcpSessionManager=new ct(e)}async getTools(){let t=await(await this.mcpSessionManager.createSession()).listTools();m.debug(`number of tools: ${t.tools.length}`);for(let o of t.tools)m.debug(`tool: ${o.name}`);return t.tools.map(o=>{let r={...o,name:this.prefix?`${this.prefix}_${o.name}`:o.name};return new lt(r,this.mcpSessionManager)})}async close(){}};export{mt as ActiveStreamingTool,Cn as AgentTool,xe as ApigeeLlm,sr as AuthCredentialTypes,G as BaseAgent,Me as BaseCodeExecutor,fn as BaseExampleProvider,Ae as BaseLlm,_ as BaseLlmRequestProcessor,Nt as BaseLlmResponseProcessor,me as BasePlugin,ge as BaseSessionService,N as BaseTool,qe as BaseToolset,Be as BuiltInCodeExecutor,L as Context,je as DatabaseSessionService,ls as EXIT_LOOP,ar as EventType,st as ExitLoopTool,be as FileArtifactService,W as FunctionTool,us as GOOGLE_SEARCH,Ie as GcsArtifactService,ee as Gemini,Qe as GoogleLLMVariant,at as GoogleSearchTool,re as InMemoryArtifactService,de as InMemoryMemoryService,ot as InMemoryPolicyEngine,hn as InMemoryRunner,X as InMemorySessionService,K as InvocationContext,ae as LLMRegistry,Rt as LiveRequestQueue,tn as LlmAgent,Ln as LogLevel,pn as LoggingPlugin,An as LongRunningFunctionTool,on as LoopAgent,ct as MCPSessionManager,lt as MCPTool,Er as MCPToolset,sn as ParallelAgent,Ge as PluginManager,pr as PolicyOutcome,fr as REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,P as ReadonlyContext,he as Runner,mn as SecurityPlugin,ln as SequentialAgent,v as State,Zt as StreamingMode,se as ToolConfirmation,E as createEvent,U as createEventActions,te as createSession,oi as functionsExportedForTestingOnly,et as geminiInitParams,qr as getArtifactServiceFromUri,ts as getAskUserConfirmationFunctionCalls,R as getFunctionCalls,B as getFunctionResponses,Em as getGcpExporters,Tm as getGcpResource,Pr as getLogger,ms as getSessionServiceFromUri,Vn as hasTrailingCodeExecutionResult,as as isAgentTool,Qr as isBaseAgent,Qi as isBaseExampleProvider,wt as isBaseLlm,kt as isBaseTool,cs as isBaseToolset,Q as isFinalResponse,Ti as isFunctionTool,Ne as isGemini2OrAbove,A as isLlmAgent,Ki as isLoopAgent,Wi as isParallelAgent,Yi as isSequentialAgent,$m as maybeSetOtelProviders,H as mergeStates,Lr as setLogLevel,Ir as setLogger,jr as stringifyContent,Ji as toStructuredEvents,gn as trimTempDeltaState,Pe as version,Ee as zodObjectToSchema};
1
90
  /**
2
91
  * @license
3
92
  * Copyright 2025 Google LLC
4
93
  * SPDX-License-Identifier: Apache-2.0
5
94
  */
6
- import { FileArtifactService } from "./artifacts/file_artifact_service.js";
7
- import { GcsArtifactService } from "./artifacts/gcs_artifact_service.js";
8
- import { getArtifactServiceFromUri } from "./artifacts/registry.js";
9
- export * from "./common.js";
10
- import { DatabaseSessionService } from "./sessions/database_session_service.js";
11
- import { getSessionServiceFromUri } from "./sessions/registry.js";
12
- export * from "./telemetry/google_cloud.js";
13
- export * from "./telemetry/setup.js";
14
- export * from "./tools/mcp/mcp_session_manager.js";
15
- export * from "./tools/mcp/mcp_tool.js";
16
- export * from "./tools/mcp/mcp_toolset.js";
17
- export {
18
- DatabaseSessionService,
19
- FileArtifactService,
20
- GcsArtifactService,
21
- getArtifactServiceFromUri,
22
- getSessionServiceFromUri
23
- };
95
+ /**
96
+ * @license
97
+ * Copyright 2026 Google LLC
98
+ * SPDX-License-Identifier: Apache-2.0
99
+ */
100
+ //# sourceMappingURL=index.js.map