@paean-ai/adk 0.2.19 → 0.2.20

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 (254) hide show
  1. package/dist/cjs/agents/active_streaming_tool.js +44 -0
  2. package/dist/cjs/agents/base_agent.js +245 -0
  3. package/dist/cjs/agents/base_llm_processor.js +44 -0
  4. package/dist/cjs/agents/callback_context.js +98 -0
  5. package/dist/cjs/agents/content_processor_utils.js +311 -0
  6. package/dist/cjs/agents/functions.js +425 -0
  7. package/dist/cjs/agents/instructions.js +110 -0
  8. package/dist/cjs/agents/invocation_context.js +107 -0
  9. package/dist/cjs/agents/live_request_queue.js +136 -0
  10. package/dist/cjs/agents/llm_agent.js +1257 -0
  11. package/dist/cjs/agents/loop_agent.js +68 -0
  12. package/dist/cjs/agents/parallel_agent.js +78 -0
  13. package/dist/cjs/agents/readonly_context.js +68 -0
  14. package/dist/cjs/agents/run_config.js +70 -0
  15. package/dist/cjs/agents/sequential_agent.js +84 -0
  16. package/dist/cjs/agents/transcription_entry.js +27 -0
  17. package/dist/cjs/artifacts/base_artifact_service.js +27 -0
  18. package/dist/cjs/artifacts/gcs_artifact_service.js +140 -0
  19. package/dist/cjs/artifacts/in_memory_artifact_service.js +119 -0
  20. package/dist/cjs/auth/auth_credential.js +46 -0
  21. package/dist/cjs/auth/auth_handler.js +92 -0
  22. package/dist/cjs/auth/auth_schemes.js +62 -0
  23. package/dist/cjs/auth/auth_tool.js +27 -0
  24. package/dist/cjs/auth/credential_service/base_credential_service.js +27 -0
  25. package/dist/cjs/auth/credential_service/in_memory_credential_service.js +63 -0
  26. package/dist/cjs/auth/exchanger/base_credential_exchanger.js +40 -0
  27. package/dist/cjs/auth/exchanger/credential_exchanger_registry.js +59 -0
  28. package/dist/cjs/code_executors/base_code_executor.js +76 -0
  29. package/dist/cjs/code_executors/built_in_code_executor.js +58 -0
  30. package/dist/cjs/code_executors/code_execution_utils.js +142 -0
  31. package/dist/cjs/code_executors/code_executor_context.js +198 -0
  32. package/dist/cjs/common.js +181 -0
  33. package/dist/cjs/events/event.js +119 -0
  34. package/dist/cjs/events/event_actions.js +83 -0
  35. package/dist/cjs/examples/base_example_provider.js +40 -0
  36. package/dist/cjs/examples/example.js +27 -0
  37. package/dist/cjs/examples/example_util.js +107 -0
  38. package/dist/cjs/index.js +12 -12
  39. package/dist/cjs/index.js.map +3 -3
  40. package/dist/cjs/index_web.js +33 -0
  41. package/dist/cjs/memory/base_memory_service.js +27 -0
  42. package/dist/cjs/memory/in_memory_memory_service.js +97 -0
  43. package/dist/cjs/memory/memory_entry.js +27 -0
  44. package/dist/cjs/models/base_llm.js +95 -0
  45. package/dist/cjs/models/base_llm_connection.js +27 -0
  46. package/dist/cjs/models/gemini_llm_connection.js +132 -0
  47. package/dist/cjs/models/google_llm.js +472 -0
  48. package/dist/cjs/models/llm_request.js +82 -0
  49. package/dist/cjs/models/llm_response.js +71 -0
  50. package/dist/cjs/models/registry.js +121 -0
  51. package/dist/cjs/plugins/base_plugin.js +236 -0
  52. package/dist/cjs/plugins/logging_plugin.js +222 -0
  53. package/dist/cjs/plugins/plugin_manager.js +239 -0
  54. package/dist/cjs/plugins/security_plugin.js +153 -0
  55. package/dist/cjs/runner/in_memory_runner.js +58 -0
  56. package/dist/cjs/runner/runner.js +277 -0
  57. package/dist/cjs/sessions/base_session_service.js +71 -0
  58. package/dist/cjs/sessions/in_memory_session_service.js +184 -0
  59. package/dist/cjs/sessions/session.js +48 -0
  60. package/dist/cjs/sessions/state.js +101 -0
  61. package/dist/cjs/telemetry/google_cloud.js +85 -0
  62. package/dist/cjs/telemetry/setup.js +97 -0
  63. package/dist/cjs/telemetry/tracing.js +231 -0
  64. package/dist/cjs/tools/agent_tool.js +134 -0
  65. package/dist/cjs/tools/base_tool.js +107 -0
  66. package/dist/cjs/tools/base_toolset.js +76 -0
  67. package/dist/cjs/tools/forwarding_artifact_service.js +71 -0
  68. package/dist/cjs/tools/function_tool.js +101 -0
  69. package/dist/cjs/tools/google_search_tool.js +77 -0
  70. package/dist/cjs/tools/long_running_tool.js +63 -0
  71. package/dist/cjs/tools/mcp/mcp_session_manager.js +65 -0
  72. package/dist/cjs/tools/mcp/mcp_tool.js +65 -0
  73. package/dist/cjs/tools/mcp/mcp_toolset.js +61 -0
  74. package/dist/cjs/tools/tool_confirmation.js +49 -0
  75. package/dist/cjs/tools/tool_context.js +129 -0
  76. package/dist/cjs/utils/client_labels.js +56 -0
  77. package/dist/cjs/utils/deep_clone.js +44 -0
  78. package/dist/cjs/utils/env_aware_utils.js +83 -0
  79. package/dist/cjs/utils/gemini_schema_util.js +88 -0
  80. package/dist/cjs/utils/logger.js +121 -0
  81. package/dist/cjs/utils/model_name.js +76 -0
  82. package/dist/cjs/utils/simple_zod_to_json.js +191 -0
  83. package/dist/cjs/utils/variant_utils.js +55 -0
  84. package/dist/cjs/version.js +39 -0
  85. package/dist/esm/agents/active_streaming_tool.js +14 -0
  86. package/dist/esm/agents/base_agent.js +214 -0
  87. package/dist/esm/agents/base_llm_processor.js +13 -0
  88. package/dist/esm/agents/callback_context.js +68 -0
  89. package/dist/esm/agents/content_processor_utils.js +280 -0
  90. package/dist/esm/agents/functions.js +384 -0
  91. package/dist/esm/agents/instructions.js +80 -0
  92. package/dist/esm/agents/invocation_context.js +76 -0
  93. package/dist/esm/agents/live_request_queue.js +106 -0
  94. package/dist/esm/agents/llm_agent.js +1225 -0
  95. package/dist/esm/agents/loop_agent.js +38 -0
  96. package/dist/esm/agents/parallel_agent.js +48 -0
  97. package/dist/esm/agents/readonly_context.js +38 -0
  98. package/dist/esm/agents/run_config.js +39 -0
  99. package/dist/esm/agents/sequential_agent.js +54 -0
  100. package/dist/esm/agents/transcription_entry.js +5 -0
  101. package/dist/esm/artifacts/base_artifact_service.js +5 -0
  102. package/dist/esm/artifacts/gcs_artifact_service.js +110 -0
  103. package/dist/esm/artifacts/in_memory_artifact_service.js +89 -0
  104. package/dist/esm/auth/auth_credential.js +16 -0
  105. package/dist/esm/auth/auth_handler.js +62 -0
  106. package/dist/esm/auth/auth_schemes.js +31 -0
  107. package/dist/esm/auth/auth_tool.js +5 -0
  108. package/dist/esm/auth/credential_service/base_credential_service.js +5 -0
  109. package/dist/esm/auth/credential_service/in_memory_credential_service.js +33 -0
  110. package/dist/esm/auth/exchanger/base_credential_exchanger.js +10 -0
  111. package/dist/esm/auth/exchanger/credential_exchanger_registry.js +29 -0
  112. package/dist/esm/code_executors/base_code_executor.js +46 -0
  113. package/dist/esm/code_executors/built_in_code_executor.js +28 -0
  114. package/dist/esm/code_executors/code_execution_utils.js +108 -0
  115. package/dist/esm/code_executors/code_executor_context.js +168 -0
  116. package/dist/esm/common.js +98 -0
  117. package/dist/esm/events/event.js +83 -0
  118. package/dist/esm/events/event_actions.js +52 -0
  119. package/dist/esm/examples/base_example_provider.js +10 -0
  120. package/dist/esm/examples/example.js +5 -0
  121. package/dist/esm/examples/example_util.js +76 -0
  122. package/dist/esm/index.js +12 -12
  123. package/dist/esm/index.js.map +3 -3
  124. package/dist/esm/index_web.js +6 -0
  125. package/dist/esm/memory/base_memory_service.js +5 -0
  126. package/dist/esm/memory/in_memory_memory_service.js +67 -0
  127. package/dist/esm/memory/memory_entry.js +5 -0
  128. package/dist/esm/models/base_llm.js +64 -0
  129. package/dist/esm/models/base_llm_connection.js +5 -0
  130. package/dist/esm/models/gemini_llm_connection.js +102 -0
  131. package/dist/esm/models/google_llm.js +446 -0
  132. package/dist/esm/models/llm_request.js +50 -0
  133. package/dist/esm/models/llm_response.js +41 -0
  134. package/dist/esm/models/registry.js +91 -0
  135. package/dist/esm/plugins/base_plugin.js +206 -0
  136. package/dist/esm/plugins/logging_plugin.js +192 -0
  137. package/dist/esm/plugins/plugin_manager.js +209 -0
  138. package/dist/esm/plugins/security_plugin.js +119 -0
  139. package/dist/esm/runner/in_memory_runner.js +28 -0
  140. package/dist/esm/runner/runner.js +247 -0
  141. package/dist/esm/sessions/base_session_service.js +41 -0
  142. package/dist/esm/sessions/in_memory_session_service.js +154 -0
  143. package/dist/esm/sessions/session.js +18 -0
  144. package/dist/esm/sessions/state.js +71 -0
  145. package/dist/esm/telemetry/google_cloud.js +54 -0
  146. package/dist/esm/telemetry/setup.js +67 -0
  147. package/dist/esm/telemetry/tracing.js +195 -0
  148. package/dist/esm/tools/agent_tool.js +104 -0
  149. package/dist/esm/tools/base_tool.js +77 -0
  150. package/dist/esm/tools/base_toolset.js +46 -0
  151. package/dist/esm/tools/forwarding_artifact_service.js +41 -0
  152. package/dist/esm/tools/function_tool.js +71 -0
  153. package/dist/esm/tools/google_search_tool.js +47 -0
  154. package/dist/esm/tools/long_running_tool.js +33 -0
  155. package/dist/esm/tools/mcp/mcp_session_manager.js +35 -0
  156. package/dist/esm/tools/mcp/mcp_tool.js +35 -0
  157. package/dist/esm/tools/mcp/mcp_toolset.js +31 -0
  158. package/dist/esm/tools/tool_confirmation.js +19 -0
  159. package/dist/esm/tools/tool_context.js +99 -0
  160. package/dist/esm/utils/client_labels.js +26 -0
  161. package/dist/esm/utils/deep_clone.js +14 -0
  162. package/dist/esm/utils/env_aware_utils.js +49 -0
  163. package/dist/esm/utils/gemini_schema_util.js +58 -0
  164. package/dist/esm/utils/logger.js +89 -0
  165. package/dist/esm/utils/model_name.js +41 -0
  166. package/dist/esm/utils/simple_zod_to_json.js +160 -0
  167. package/dist/esm/utils/variant_utils.js +24 -0
  168. package/dist/esm/version.js +9 -0
  169. package/dist/types/models/google_llm.d.ts +0 -7
  170. package/dist/web/agents/active_streaming_tool.js +14 -0
  171. package/dist/web/agents/base_agent.js +265 -0
  172. package/dist/web/agents/base_llm_processor.js +13 -0
  173. package/dist/web/agents/callback_context.js +68 -0
  174. package/dist/web/agents/content_processor_utils.js +280 -0
  175. package/dist/web/agents/functions.js +384 -0
  176. package/dist/web/agents/instructions.js +80 -0
  177. package/dist/web/agents/invocation_context.js +76 -0
  178. package/dist/web/agents/live_request_queue.js +124 -0
  179. package/dist/web/agents/llm_agent.js +1355 -0
  180. package/dist/web/agents/loop_agent.js +71 -0
  181. package/dist/web/agents/parallel_agent.js +83 -0
  182. package/dist/web/agents/readonly_context.js +38 -0
  183. package/dist/web/agents/run_config.js +54 -0
  184. package/dist/web/agents/sequential_agent.js +99 -0
  185. package/dist/web/agents/transcription_entry.js +5 -0
  186. package/dist/web/artifacts/base_artifact_service.js +5 -0
  187. package/dist/web/artifacts/gcs_artifact_service.js +126 -0
  188. package/dist/web/artifacts/in_memory_artifact_service.js +89 -0
  189. package/dist/web/auth/auth_credential.js +16 -0
  190. package/dist/web/auth/auth_handler.js +62 -0
  191. package/dist/web/auth/auth_schemes.js +31 -0
  192. package/dist/web/auth/auth_tool.js +5 -0
  193. package/dist/web/auth/credential_service/base_credential_service.js +5 -0
  194. package/dist/web/auth/credential_service/in_memory_credential_service.js +33 -0
  195. package/dist/web/auth/exchanger/base_credential_exchanger.js +10 -0
  196. package/dist/web/auth/exchanger/credential_exchanger_registry.js +29 -0
  197. package/dist/web/code_executors/base_code_executor.js +46 -0
  198. package/dist/web/code_executors/built_in_code_executor.js +28 -0
  199. package/dist/web/code_executors/code_execution_utils.js +105 -0
  200. package/dist/web/code_executors/code_executor_context.js +168 -0
  201. package/dist/web/common.js +98 -0
  202. package/dist/web/events/event.js +101 -0
  203. package/dist/web/events/event_actions.js +67 -0
  204. package/dist/web/examples/base_example_provider.js +10 -0
  205. package/dist/web/examples/example.js +5 -0
  206. package/dist/web/examples/example_util.js +75 -0
  207. package/dist/web/index.js +1 -1
  208. package/dist/web/index.js.map +3 -3
  209. package/dist/web/index_web.js +6 -0
  210. package/dist/web/memory/base_memory_service.js +5 -0
  211. package/dist/web/memory/in_memory_memory_service.js +67 -0
  212. package/dist/web/memory/memory_entry.js +5 -0
  213. package/dist/web/models/base_llm.js +64 -0
  214. package/dist/web/models/base_llm_connection.js +5 -0
  215. package/dist/web/models/gemini_llm_connection.js +120 -0
  216. package/dist/web/models/google_llm.js +487 -0
  217. package/dist/web/models/llm_request.js +50 -0
  218. package/dist/web/models/llm_response.js +41 -0
  219. package/dist/web/models/registry.js +91 -0
  220. package/dist/web/plugins/base_plugin.js +206 -0
  221. package/dist/web/plugins/logging_plugin.js +192 -0
  222. package/dist/web/plugins/plugin_manager.js +209 -0
  223. package/dist/web/plugins/security_plugin.js +119 -0
  224. package/dist/web/runner/in_memory_runner.js +28 -0
  225. package/dist/web/runner/runner.js +278 -0
  226. package/dist/web/sessions/base_session_service.js +41 -0
  227. package/dist/web/sessions/in_memory_session_service.js +154 -0
  228. package/dist/web/sessions/session.js +18 -0
  229. package/dist/web/sessions/state.js +87 -0
  230. package/dist/web/telemetry/google_cloud.js +54 -0
  231. package/dist/web/telemetry/setup.js +67 -0
  232. package/dist/web/telemetry/tracing.js +210 -0
  233. package/dist/web/tools/agent_tool.js +118 -0
  234. package/dist/web/tools/base_tool.js +77 -0
  235. package/dist/web/tools/base_toolset.js +46 -0
  236. package/dist/web/tools/forwarding_artifact_service.js +41 -0
  237. package/dist/web/tools/function_tool.js +71 -0
  238. package/dist/web/tools/google_search_tool.js +47 -0
  239. package/dist/web/tools/long_running_tool.js +50 -0
  240. package/dist/web/tools/mcp/mcp_session_manager.js +35 -0
  241. package/dist/web/tools/mcp/mcp_tool.js +35 -0
  242. package/dist/web/tools/mcp/mcp_toolset.js +31 -0
  243. package/dist/web/tools/tool_confirmation.js +19 -0
  244. package/dist/web/tools/tool_context.js +99 -0
  245. package/dist/web/utils/client_labels.js +26 -0
  246. package/dist/web/utils/deep_clone.js +14 -0
  247. package/dist/web/utils/env_aware_utils.js +49 -0
  248. package/dist/web/utils/gemini_schema_util.js +58 -0
  249. package/dist/web/utils/logger.js +89 -0
  250. package/dist/web/utils/model_name.js +41 -0
  251. package/dist/web/utils/simple_zod_to_json.js +174 -0
  252. package/dist/web/utils/variant_utils.js +24 -0
  253. package/dist/web/version.js +9 -0
  254. package/package.json +1 -1
@@ -0,0 +1,280 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { createEvent, getFunctionCalls, getFunctionResponses } from "../events/event.js";
7
+ import { deepClone } from "../utils/deep_clone.js";
8
+ import { removeClientFunctionCallId, REQUEST_CONFIRMATION_FUNCTION_CALL_NAME, REQUEST_EUC_FUNCTION_CALL_NAME } from "./functions.js";
9
+ function getContents(events, agentName, currentBranch) {
10
+ var _a, _b;
11
+ const filteredEvents = [];
12
+ for (const event of events) {
13
+ if (!((_a = event.content) == null ? void 0 : _a.role) || !((_b = event.content.parts) == null ? void 0 : _b.length)) {
14
+ continue;
15
+ }
16
+ if (currentBranch && event.branch && !currentBranch.startsWith(event.branch)) {
17
+ continue;
18
+ }
19
+ if (isAuthEvent(event)) {
20
+ continue;
21
+ }
22
+ if (isToolConfirmationEvent(event)) {
23
+ continue;
24
+ }
25
+ filteredEvents.push(
26
+ isEventFromAnotherAgent(agentName, event) ? convertForeignEvent(event) : event
27
+ );
28
+ }
29
+ let resultEvents = rearrangeEventsForLatestFunctionResponse(filteredEvents);
30
+ resultEvents = rearrangeEventsForAsyncFunctionResponsesInHistory(resultEvents);
31
+ const contents = [];
32
+ for (const event of resultEvents) {
33
+ const content = deepClone(event.content);
34
+ removeClientFunctionCallId(content);
35
+ contents.push(content);
36
+ }
37
+ return contents;
38
+ }
39
+ function getCurrentTurnContents(events, agentName, currentBranch) {
40
+ for (let i = events.length - 1; i >= 0; i--) {
41
+ const event = events[i];
42
+ if (event.author === "user" || isEventFromAnotherAgent(agentName, event)) {
43
+ return getContents(events.slice(i), agentName, currentBranch);
44
+ }
45
+ }
46
+ return [];
47
+ }
48
+ function isAuthEvent(event) {
49
+ var _a, _b, _c;
50
+ if (!((_a = event.content) == null ? void 0 : _a.parts)) {
51
+ return false;
52
+ }
53
+ for (const part of event.content.parts) {
54
+ if (((_b = part.functionCall) == null ? void 0 : _b.name) === REQUEST_EUC_FUNCTION_CALL_NAME || ((_c = part.functionResponse) == null ? void 0 : _c.name) === REQUEST_EUC_FUNCTION_CALL_NAME) {
55
+ return true;
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+ function isToolConfirmationEvent(event) {
61
+ var _a, _b, _c;
62
+ if (!((_a = event.content) == null ? void 0 : _a.parts)) {
63
+ return false;
64
+ }
65
+ for (const part of event.content.parts) {
66
+ if (((_b = part.functionCall) == null ? void 0 : _b.name) === REQUEST_CONFIRMATION_FUNCTION_CALL_NAME || ((_c = part.functionResponse) == null ? void 0 : _c.name) === REQUEST_CONFIRMATION_FUNCTION_CALL_NAME) {
67
+ return true;
68
+ }
69
+ }
70
+ return false;
71
+ }
72
+ function isEventFromAnotherAgent(agentName, event) {
73
+ return !!agentName && event.author !== agentName && event.author !== "user";
74
+ }
75
+ function convertForeignEvent(event) {
76
+ var _a, _b, _c, _d, _e, _f;
77
+ if (!((_b = (_a = event.content) == null ? void 0 : _a.parts) == null ? void 0 : _b.length)) {
78
+ return event;
79
+ }
80
+ const content = {
81
+ role: "user",
82
+ parts: [{
83
+ text: "For context:"
84
+ }]
85
+ };
86
+ for (const part of event.content.parts) {
87
+ if (part.text && !part.thought) {
88
+ (_c = content.parts) == null ? void 0 : _c.push({
89
+ text: `[${event.author}] said: ${part.text}`
90
+ });
91
+ } else if (part.functionCall) {
92
+ const argsText = safeStringify(part.functionCall.args);
93
+ (_d = content.parts) == null ? void 0 : _d.push({
94
+ text: `[${event.author}] called tool \`${part.functionCall.name}\` with parameters: ${argsText}`
95
+ });
96
+ } else if (part.functionResponse) {
97
+ const responseText = safeStringify(part.functionResponse.response);
98
+ (_e = content.parts) == null ? void 0 : _e.push({
99
+ text: `[${event.author}] tool \`${part.functionResponse.name}\` returned result: ${responseText}`
100
+ });
101
+ } else {
102
+ (_f = content.parts) == null ? void 0 : _f.push(part);
103
+ }
104
+ }
105
+ return createEvent({
106
+ invocationId: event.invocationId,
107
+ author: "user",
108
+ content,
109
+ branch: event.branch,
110
+ timestamp: event.timestamp
111
+ });
112
+ }
113
+ function mergeFunctionResponseEvents(events) {
114
+ var _a;
115
+ if (events.length === 0) {
116
+ throw new Error("Cannot merge an empty list of events.");
117
+ }
118
+ const mergedEvent = createEvent(events[0]);
119
+ const partsInMergedEvent = ((_a = mergedEvent.content) == null ? void 0 : _a.parts) || [];
120
+ if (partsInMergedEvent.length === 0) {
121
+ throw new Error("There should be at least one function_response part.");
122
+ }
123
+ const partIndicesInMergedEvent = {};
124
+ for (let i = 0; i < partsInMergedEvent.length; i++) {
125
+ const part = partsInMergedEvent[i];
126
+ if (part.functionResponse && part.functionResponse.id) {
127
+ partIndicesInMergedEvent[part.functionResponse.id] = i;
128
+ }
129
+ }
130
+ for (const event of events.slice(1)) {
131
+ if (!event.content || !event.content.parts) {
132
+ throw new Error("There should be at least one function_response part.");
133
+ }
134
+ for (const part of event.content.parts) {
135
+ if (part.functionResponse && part.functionResponse.id) {
136
+ const functionCallId = part.functionResponse.id;
137
+ if (functionCallId in partIndicesInMergedEvent) {
138
+ partsInMergedEvent[partIndicesInMergedEvent[functionCallId]] = part;
139
+ } else {
140
+ partsInMergedEvent.push(part);
141
+ partIndicesInMergedEvent[functionCallId] = partsInMergedEvent.length - 1;
142
+ }
143
+ } else {
144
+ partsInMergedEvent.push(part);
145
+ }
146
+ }
147
+ }
148
+ return mergedEvent;
149
+ }
150
+ function rearrangeEventsForLatestFunctionResponse(events) {
151
+ if (events.length === 0) {
152
+ return events;
153
+ }
154
+ const latestEvent = events[events.length - 1];
155
+ const functionResponses = getFunctionResponses(latestEvent);
156
+ if (!(functionResponses == null ? void 0 : functionResponses.length)) {
157
+ return events;
158
+ }
159
+ let functionResponsesIds = new Set(
160
+ functionResponses.filter((response) => !!response.id).map((response) => response.id)
161
+ );
162
+ const secondLatestEvent = events.at(-2);
163
+ if (secondLatestEvent) {
164
+ const functionCallsFromSecondLatest = getFunctionCalls(secondLatestEvent);
165
+ if (functionCallsFromSecondLatest) {
166
+ for (const functionCall of functionCallsFromSecondLatest) {
167
+ if (functionCall.id && functionResponsesIds.has(functionCall.id)) {
168
+ return events;
169
+ }
170
+ }
171
+ }
172
+ }
173
+ let functionCallEventIdx = -1;
174
+ for (let idx = events.length - 2; idx >= 0; idx--) {
175
+ const event = events[idx];
176
+ const functionCalls = getFunctionCalls(event);
177
+ if (!(functionCalls == null ? void 0 : functionCalls.length)) {
178
+ continue;
179
+ }
180
+ for (const functionCall of functionCalls) {
181
+ if (functionCall.id && functionResponsesIds.has(functionCall.id)) {
182
+ functionCallEventIdx = idx;
183
+ const functionCallIds = new Set(
184
+ functionCalls.map((fc) => fc.id).filter((id) => !!id)
185
+ );
186
+ const isSubset = Array.from(functionResponsesIds).every((id) => functionCallIds.has(id));
187
+ if (!isSubset) {
188
+ throw new Error(
189
+ `Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(functionCallIds).join(", ")}, function response ids provided: ${Array.from(functionResponsesIds).join(", ")}`
190
+ );
191
+ }
192
+ functionResponsesIds = functionCallIds;
193
+ break;
194
+ }
195
+ }
196
+ }
197
+ if (functionCallEventIdx === -1) {
198
+ throw new Error(
199
+ `No function call event found for function responses ids: ${Array.from(
200
+ functionResponsesIds
201
+ ).join(", ")}`
202
+ );
203
+ }
204
+ const functionResponseEvents = [];
205
+ for (let idx = functionCallEventIdx + 1; idx < events.length - 1; idx++) {
206
+ const event = events[idx];
207
+ const responses = getFunctionResponses(event);
208
+ if (responses && responses.some(
209
+ (response) => response.id && functionResponsesIds.has(response.id)
210
+ )) {
211
+ functionResponseEvents.push(event);
212
+ }
213
+ }
214
+ functionResponseEvents.push(events[events.length - 1]);
215
+ const resultEvents = events.slice(0, functionCallEventIdx + 1);
216
+ resultEvents.push(mergeFunctionResponseEvents(functionResponseEvents));
217
+ return resultEvents;
218
+ }
219
+ function rearrangeEventsForAsyncFunctionResponsesInHistory(events) {
220
+ const functionCallIdToResponseEventIndex = /* @__PURE__ */ new Map();
221
+ for (let i = 0; i < events.length; i++) {
222
+ const event = events[i];
223
+ const functionResponses = getFunctionResponses(event);
224
+ if (functionResponses == null ? void 0 : functionResponses.length) {
225
+ for (const functionResponse of functionResponses) {
226
+ if (!functionResponse.id) {
227
+ continue;
228
+ }
229
+ functionCallIdToResponseEventIndex.set(functionResponse.id, i);
230
+ }
231
+ }
232
+ }
233
+ const resultEvents = [];
234
+ for (const event of events) {
235
+ if (getFunctionResponses(event).length > 0) {
236
+ continue;
237
+ }
238
+ const functionCalls = getFunctionCalls(event);
239
+ if (functionCalls == null ? void 0 : functionCalls.length) {
240
+ const functionResponseEventsIndices = /* @__PURE__ */ new Set();
241
+ for (const functionCall of functionCalls) {
242
+ const functionCallId = functionCall.id;
243
+ if (functionCallId && functionCallIdToResponseEventIndex.has(functionCallId)) {
244
+ functionResponseEventsIndices.add(
245
+ functionCallIdToResponseEventIndex.get(functionCallId)
246
+ );
247
+ }
248
+ }
249
+ resultEvents.push(event);
250
+ if (functionResponseEventsIndices.size === 0) {
251
+ continue;
252
+ }
253
+ if (functionResponseEventsIndices.size === 1) {
254
+ const [responseIndex] = [...functionResponseEventsIndices];
255
+ resultEvents.push(events[responseIndex]);
256
+ } else {
257
+ const indicesArray = Array.from(functionResponseEventsIndices).sort((a, b) => a - b);
258
+ const eventsToMerge = indicesArray.map((index) => events[index]);
259
+ resultEvents.push(mergeFunctionResponseEvents(eventsToMerge));
260
+ }
261
+ } else {
262
+ resultEvents.push(event);
263
+ }
264
+ }
265
+ return resultEvents;
266
+ }
267
+ function safeStringify(obj) {
268
+ if (typeof obj === "string") {
269
+ return obj;
270
+ }
271
+ try {
272
+ return JSON.stringify(obj);
273
+ } catch (e) {
274
+ return String(obj);
275
+ }
276
+ }
277
+ export {
278
+ getContents,
279
+ getCurrentTurnContents
280
+ };
@@ -0,0 +1,384 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { createUserContent } from "@google/genai";
7
+ import { createEvent, getFunctionCalls } from "../events/event.js";
8
+ import { mergeEventActions } from "../events/event_actions.js";
9
+ import { ToolContext } from "../tools/tool_context.js";
10
+ import { randomUUID } from "../utils/env_aware_utils.js";
11
+ import { logger } from "../utils/logger.js";
12
+ const AF_FUNCTION_CALL_ID_PREFIX = "adk-";
13
+ const REQUEST_EUC_FUNCTION_CALL_NAME = "adk_request_credential";
14
+ const REQUEST_CONFIRMATION_FUNCTION_CALL_NAME = "adk_request_confirmation";
15
+ const functionsExportedForTestingOnly = {
16
+ handleFunctionCallList
17
+ };
18
+ function generateClientFunctionCallId() {
19
+ return `${AF_FUNCTION_CALL_ID_PREFIX}${randomUUID()}`;
20
+ }
21
+ function populateClientFunctionCallId(modelResponseEvent) {
22
+ const functionCalls = getFunctionCalls(modelResponseEvent);
23
+ if (!functionCalls) {
24
+ return;
25
+ }
26
+ for (const functionCall of functionCalls) {
27
+ if (!functionCall.id) {
28
+ functionCall.id = generateClientFunctionCallId();
29
+ }
30
+ }
31
+ }
32
+ function removeClientFunctionCallId(content) {
33
+ if (content && content.parts) {
34
+ for (const part of content.parts) {
35
+ if (part.functionCall && part.functionCall.id && part.functionCall.id.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
36
+ part.functionCall.id = void 0;
37
+ }
38
+ if (part.functionResponse && part.functionResponse.id && part.functionResponse.id.startsWith(AF_FUNCTION_CALL_ID_PREFIX)) {
39
+ part.functionResponse.id = void 0;
40
+ }
41
+ }
42
+ }
43
+ }
44
+ function resolveToolName(name, toolsDict) {
45
+ if (name in toolsDict) {
46
+ return name;
47
+ }
48
+ const colonIndex = name.indexOf(":");
49
+ if (colonIndex > 0) {
50
+ const baseName = name.substring(0, colonIndex);
51
+ if (baseName in toolsDict) {
52
+ logger.info(
53
+ `Resolved Gemini 3 function name "${name}" to tool "${baseName}"`
54
+ );
55
+ return baseName;
56
+ }
57
+ }
58
+ return void 0;
59
+ }
60
+ function getLongRunningFunctionCalls(functionCalls, toolsDict) {
61
+ const longRunningToolIds = /* @__PURE__ */ new Set();
62
+ for (const functionCall of functionCalls) {
63
+ if (!functionCall.name || !functionCall.id) continue;
64
+ const resolvedName = resolveToolName(functionCall.name, toolsDict);
65
+ if (resolvedName && toolsDict[resolvedName].isLongRunning) {
66
+ longRunningToolIds.add(functionCall.id);
67
+ }
68
+ }
69
+ return longRunningToolIds;
70
+ }
71
+ function generateAuthEvent(invocationContext, functionResponseEvent) {
72
+ var _a;
73
+ if (!((_a = functionResponseEvent.actions) == null ? void 0 : _a.requestedAuthConfigs)) {
74
+ return void 0;
75
+ }
76
+ const parts = [];
77
+ const longRunningToolIds = /* @__PURE__ */ new Set();
78
+ for (const [functionCallId, authConfig] of Object.entries(
79
+ functionResponseEvent.actions.requestedAuthConfigs
80
+ )) {
81
+ const requestEucFunctionCall = {
82
+ name: REQUEST_EUC_FUNCTION_CALL_NAME,
83
+ args: {
84
+ "function_call_id": functionCallId,
85
+ "auth_config": authConfig
86
+ },
87
+ id: generateClientFunctionCallId()
88
+ };
89
+ longRunningToolIds.add(requestEucFunctionCall.id);
90
+ parts.push({ functionCall: requestEucFunctionCall });
91
+ }
92
+ return createEvent({
93
+ invocationId: invocationContext.invocationId,
94
+ author: invocationContext.agent.name,
95
+ branch: invocationContext.branch,
96
+ content: {
97
+ parts,
98
+ role: functionResponseEvent.content.role
99
+ },
100
+ longRunningToolIds: Array.from(longRunningToolIds)
101
+ });
102
+ }
103
+ function generateRequestConfirmationEvent({
104
+ invocationContext,
105
+ functionCallEvent,
106
+ functionResponseEvent
107
+ }) {
108
+ var _a, _b;
109
+ if (!((_a = functionResponseEvent.actions) == null ? void 0 : _a.requestedToolConfirmations)) {
110
+ return;
111
+ }
112
+ const parts = [];
113
+ const longRunningToolIds = /* @__PURE__ */ new Set();
114
+ const functionCalls = getFunctionCalls(functionCallEvent);
115
+ for (const [functionCallId, toolConfirmation] of Object.entries(
116
+ functionResponseEvent.actions.requestedToolConfirmations
117
+ )) {
118
+ const originalFunctionCall = (_b = functionCalls.find((call) => call.id === functionCallId)) != null ? _b : void 0;
119
+ if (!originalFunctionCall) {
120
+ continue;
121
+ }
122
+ const requestConfirmationFunctionCall = {
123
+ name: REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
124
+ args: {
125
+ "originalFunctionCall": originalFunctionCall,
126
+ "toolConfirmation": toolConfirmation
127
+ },
128
+ id: generateClientFunctionCallId()
129
+ };
130
+ longRunningToolIds.add(requestConfirmationFunctionCall.id);
131
+ parts.push({ functionCall: requestConfirmationFunctionCall });
132
+ }
133
+ return createEvent({
134
+ invocationId: invocationContext.invocationId,
135
+ author: invocationContext.agent.name,
136
+ branch: invocationContext.branch,
137
+ content: {
138
+ parts,
139
+ role: functionResponseEvent.content.role
140
+ },
141
+ longRunningToolIds: Array.from(longRunningToolIds)
142
+ });
143
+ }
144
+ async function callToolAsync(tool, args, toolContext) {
145
+ logger.debug(`callToolAsync ${tool.name}`);
146
+ return await tool.runAsync({ args, toolContext });
147
+ }
148
+ async function handleFunctionCallsAsync({
149
+ invocationContext,
150
+ functionCallEvent,
151
+ toolsDict,
152
+ beforeToolCallbacks,
153
+ afterToolCallbacks,
154
+ filters,
155
+ toolConfirmationDict
156
+ }) {
157
+ const functionCalls = getFunctionCalls(functionCallEvent);
158
+ return await handleFunctionCallList({
159
+ invocationContext,
160
+ functionCalls,
161
+ toolsDict,
162
+ beforeToolCallbacks,
163
+ afterToolCallbacks,
164
+ filters,
165
+ toolConfirmationDict
166
+ });
167
+ }
168
+ async function handleFunctionCallList({
169
+ invocationContext,
170
+ functionCalls,
171
+ toolsDict,
172
+ beforeToolCallbacks,
173
+ afterToolCallbacks,
174
+ filters,
175
+ toolConfirmationDict
176
+ }) {
177
+ var _a, _b, _c;
178
+ const functionResponseEvents = [];
179
+ const filteredFunctionCalls = functionCalls.filter((functionCall) => {
180
+ return !filters || functionCall.id && filters.has(functionCall.id);
181
+ });
182
+ for (const functionCall of filteredFunctionCalls) {
183
+ let toolConfirmation = void 0;
184
+ if (toolConfirmationDict && functionCall.id) {
185
+ toolConfirmation = toolConfirmationDict[functionCall.id];
186
+ }
187
+ const toolAndContext = getToolAndContext(
188
+ {
189
+ invocationContext,
190
+ functionCall,
191
+ toolsDict,
192
+ toolConfirmation
193
+ }
194
+ );
195
+ if (!toolAndContext) {
196
+ const availableTools = Object.keys(toolsDict).join(", ");
197
+ logger.warn(
198
+ `Function ${functionCall.name} is not found in the toolsDict. Available tools: [${availableTools}]. Returning error response to LLM.`
199
+ );
200
+ const errorResponseEvent = createEvent({
201
+ invocationId: invocationContext.invocationId,
202
+ author: invocationContext.agent.name,
203
+ content: createUserContent({
204
+ functionResponse: {
205
+ id: functionCall.id || void 0,
206
+ name: (_a = functionCall.name) != null ? _a : "unknown",
207
+ response: {
208
+ error: `Function '${functionCall.name}' is not available. Available tools: [${availableTools}]. Please use one of the available tools instead.`
209
+ }
210
+ }
211
+ }),
212
+ branch: invocationContext.branch
213
+ });
214
+ functionResponseEvents.push(errorResponseEvent);
215
+ continue;
216
+ }
217
+ const { tool, toolContext } = toolAndContext;
218
+ logger.debug(`execute_tool ${tool.name}`);
219
+ const functionArgs = (_b = functionCall.args) != null ? _b : {};
220
+ let functionResponse = null;
221
+ let functionResponseError;
222
+ functionResponse = await invocationContext.pluginManager.runBeforeToolCallback({
223
+ tool,
224
+ toolArgs: functionArgs,
225
+ toolContext
226
+ });
227
+ if (functionResponse == null) {
228
+ for (const callback of beforeToolCallbacks) {
229
+ functionResponse = await callback({
230
+ tool,
231
+ args: functionArgs,
232
+ context: toolContext
233
+ });
234
+ if (functionResponse) {
235
+ break;
236
+ }
237
+ }
238
+ }
239
+ if (functionResponse == null) {
240
+ try {
241
+ functionResponse = await callToolAsync(
242
+ tool,
243
+ functionArgs,
244
+ toolContext
245
+ );
246
+ } catch (e) {
247
+ if (e instanceof Error) {
248
+ const onToolErrorResponse = await invocationContext.pluginManager.runOnToolErrorCallback(
249
+ {
250
+ tool,
251
+ toolArgs: functionArgs,
252
+ toolContext,
253
+ error: e
254
+ }
255
+ );
256
+ if (onToolErrorResponse) {
257
+ functionResponse = onToolErrorResponse;
258
+ } else {
259
+ functionResponseError = e.message;
260
+ }
261
+ } else {
262
+ functionResponseError = e;
263
+ }
264
+ }
265
+ }
266
+ let alteredFunctionResponse = await invocationContext.pluginManager.runAfterToolCallback({
267
+ tool,
268
+ toolArgs: functionArgs,
269
+ toolContext,
270
+ result: functionResponse
271
+ });
272
+ if (alteredFunctionResponse == null) {
273
+ for (const callback of afterToolCallbacks) {
274
+ alteredFunctionResponse = await callback({
275
+ tool,
276
+ args: functionArgs,
277
+ context: toolContext,
278
+ response: functionResponse
279
+ });
280
+ if (alteredFunctionResponse) {
281
+ break;
282
+ }
283
+ }
284
+ }
285
+ if (alteredFunctionResponse != null) {
286
+ functionResponse = alteredFunctionResponse;
287
+ }
288
+ if (tool.isLongRunning && !functionResponse) {
289
+ continue;
290
+ }
291
+ if (functionResponseError) {
292
+ functionResponse = { error: functionResponseError };
293
+ } else if (typeof functionResponse !== "object" || functionResponse == null) {
294
+ functionResponse = { result: functionResponse };
295
+ }
296
+ const functionResponseEvent = createEvent({
297
+ invocationId: invocationContext.invocationId,
298
+ author: invocationContext.agent.name,
299
+ content: createUserContent({
300
+ functionResponse: {
301
+ id: toolContext.functionCallId,
302
+ name: (_c = functionCall.name) != null ? _c : tool.name,
303
+ response: functionResponse
304
+ }
305
+ }),
306
+ actions: toolContext.actions,
307
+ branch: invocationContext.branch
308
+ });
309
+ logger.debug("traceToolCall", {
310
+ tool: tool.name,
311
+ args: functionArgs,
312
+ functionResponseEvent: functionResponseEvent.id
313
+ });
314
+ functionResponseEvents.push(functionResponseEvent);
315
+ }
316
+ if (!functionResponseEvents.length) {
317
+ return null;
318
+ }
319
+ const mergedEvent = mergeParallelFunctionResponseEvents(functionResponseEvents);
320
+ if (functionResponseEvents.length > 1) {
321
+ logger.debug("execute_tool (merged)");
322
+ logger.debug("traceMergedToolCalls", {
323
+ responseEventId: mergedEvent.id,
324
+ functionResponseEvent: mergedEvent.id
325
+ });
326
+ }
327
+ return mergedEvent;
328
+ }
329
+ function getToolAndContext({
330
+ invocationContext,
331
+ functionCall,
332
+ toolsDict,
333
+ toolConfirmation
334
+ }) {
335
+ const resolvedName = functionCall.name ? resolveToolName(functionCall.name, toolsDict) : void 0;
336
+ if (!resolvedName) {
337
+ return null;
338
+ }
339
+ const toolContext = new ToolContext({
340
+ invocationContext,
341
+ functionCallId: functionCall.id || void 0,
342
+ toolConfirmation
343
+ });
344
+ const tool = toolsDict[resolvedName];
345
+ return { tool, toolContext };
346
+ }
347
+ function mergeParallelFunctionResponseEvents(functionResponseEvents) {
348
+ if (!functionResponseEvents.length) {
349
+ throw new Error("No function response events provided.");
350
+ }
351
+ if (functionResponseEvents.length === 1) {
352
+ return functionResponseEvents[0];
353
+ }
354
+ const mergedParts = [];
355
+ for (const event of functionResponseEvents) {
356
+ if (event.content && event.content.parts) {
357
+ mergedParts.push(...event.content.parts);
358
+ }
359
+ }
360
+ const baseEvent = functionResponseEvents[0];
361
+ const actionsList = functionResponseEvents.map((event) => event.actions || {});
362
+ const mergedActions = mergeEventActions(actionsList);
363
+ return createEvent({
364
+ author: baseEvent.author,
365
+ branch: baseEvent.branch,
366
+ content: { role: "user", parts: mergedParts },
367
+ actions: mergedActions,
368
+ timestamp: baseEvent.timestamp
369
+ });
370
+ }
371
+ export {
372
+ REQUEST_CONFIRMATION_FUNCTION_CALL_NAME,
373
+ REQUEST_EUC_FUNCTION_CALL_NAME,
374
+ functionsExportedForTestingOnly,
375
+ generateAuthEvent,
376
+ generateClientFunctionCallId,
377
+ generateRequestConfirmationEvent,
378
+ getLongRunningFunctionCalls,
379
+ handleFunctionCallList,
380
+ handleFunctionCallsAsync,
381
+ mergeParallelFunctionResponseEvents,
382
+ populateClientFunctionCallId,
383
+ removeClientFunctionCallId
384
+ };