@google/adk 1.3.0 → 1.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 (248) hide show
  1. package/dist/cjs/a2a/agent_to_a2a.js +18 -2
  2. package/dist/cjs/a2a/event_converter_utils.js +8 -4
  3. package/dist/cjs/a2a/metadata_converter_utils.js +1 -1
  4. package/dist/cjs/agents/active_streaming_tool.js +6 -1
  5. package/dist/cjs/agents/base_agent.js +39 -0
  6. package/dist/cjs/agents/context.js +1 -11
  7. package/dist/cjs/agents/functions.js +39 -35
  8. package/dist/cjs/agents/instructions.js +23 -5
  9. package/dist/cjs/agents/invocation_context.js +2 -5
  10. package/dist/cjs/agents/llm_agent.js +10 -7
  11. package/dist/cjs/agents/loop_agent.js +15 -3
  12. package/dist/cjs/agents/processors/code_execution_request_processor.js +0 -3
  13. package/dist/cjs/agents/processors/content_processor_utils.js +18 -4
  14. package/dist/cjs/agents/processors/context_compactor_request_processor.js +4 -2
  15. package/dist/cjs/agents/processors/interactions_request_processor.js +63 -0
  16. package/dist/cjs/agents/routed_agent.js +31 -0
  17. package/dist/cjs/agents/run_config.js +3 -2
  18. package/dist/cjs/apps/app.js +79 -0
  19. package/dist/cjs/apps/resumability_config.js +44 -0
  20. package/dist/cjs/artifacts/file_artifact_service.js +14 -1
  21. package/dist/cjs/artifacts/gcs_artifact_service.js +57 -15
  22. package/dist/cjs/artifacts/in_memory_artifact_service.js +12 -1
  23. package/dist/cjs/artifacts/scoped_artifact_service.js +101 -0
  24. package/dist/cjs/artifacts/session_artifact_service.js +27 -0
  25. package/dist/cjs/auth/oauth2/oauth2_discovery.js +17 -5
  26. package/dist/cjs/auth/oauth2/oauth2_utils.js +12 -1
  27. package/dist/cjs/common.js +76 -0
  28. package/dist/cjs/context/agent_controlled_context_compactor.js +109 -0
  29. package/dist/cjs/context/anchored_context_compactor.js +127 -0
  30. package/dist/cjs/context/compaction_utils.js +52 -0
  31. package/dist/cjs/context/token_based_context_compactor.js +52 -33
  32. package/dist/cjs/context/trajectory_thought_pruning_compactor.js +71 -0
  33. package/dist/cjs/events/compacted_event.js +9 -3
  34. package/dist/cjs/events/event.js +52 -0
  35. package/dist/cjs/index.js +4 -0
  36. package/dist/cjs/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  37. package/dist/cjs/models/google_llm.js +25 -10
  38. package/dist/cjs/models/interactions_utils.js +732 -0
  39. package/dist/cjs/plugins/base_plugin.js +1 -0
  40. package/dist/cjs/plugins/global_instruction_plugin.js +97 -0
  41. package/dist/cjs/runner/in_memory_runner.js +13 -2
  42. package/dist/cjs/runner/runner.js +143 -83
  43. package/dist/cjs/sessions/base_session_service.js +6 -1
  44. package/dist/cjs/sessions/database_session_service.js +24 -7
  45. package/dist/cjs/sessions/vertex_ai_session_service.js +19 -4
  46. package/dist/cjs/skills/loader.js +2 -2
  47. package/dist/cjs/tools/base_toolset.js +1 -1
  48. package/dist/cjs/tools/consolidate_context_tool.js +79 -0
  49. package/dist/cjs/tools/enterprise_web_search_tool.js +81 -0
  50. package/dist/cjs/tools/example_tool.js +68 -0
  51. package/dist/cjs/tools/forwarding_artifact_service.js +16 -28
  52. package/dist/cjs/tools/load_web_page.js +250 -0
  53. package/dist/cjs/tools/mcp/load_mcp_resource_tool.js +140 -0
  54. package/dist/cjs/tools/mcp/mcp_toolset.js +63 -0
  55. package/dist/cjs/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -22
  56. package/dist/cjs/tools/skill/run_skill_inline_script_tool.js +54 -4
  57. package/dist/cjs/tools/skill/skill_toolset.js +4 -2
  58. package/dist/cjs/utils/async_hooks_shim.js +52 -0
  59. package/dist/cjs/utils/branch_trie.js +41 -0
  60. package/dist/cjs/utils/client_labels.js +41 -3
  61. package/dist/cjs/utils/env_aware_utils.js +10 -1
  62. package/dist/cjs/utils/streaming_utils.js +15 -9
  63. package/dist/cjs/utils/task.js +62 -0
  64. package/dist/cjs/version.js +1 -1
  65. package/dist/esm/a2a/agent_to_a2a.js +18 -2
  66. package/dist/esm/a2a/event_converter_utils.js +8 -4
  67. package/dist/esm/a2a/metadata_converter_utils.js +1 -1
  68. package/dist/esm/agents/active_streaming_tool.js +6 -1
  69. package/dist/esm/agents/base_agent.js +39 -0
  70. package/dist/esm/agents/context.js +1 -11
  71. package/dist/esm/agents/functions.js +43 -32
  72. package/dist/esm/agents/instructions.js +23 -5
  73. package/dist/esm/agents/invocation_context.js +2 -5
  74. package/dist/esm/agents/llm_agent.js +12 -9
  75. package/dist/esm/agents/loop_agent.js +15 -3
  76. package/dist/esm/agents/processors/code_execution_request_processor.js +0 -3
  77. package/dist/esm/agents/processors/content_processor_utils.js +16 -3
  78. package/dist/esm/agents/processors/context_compactor_request_processor.js +4 -2
  79. package/dist/esm/agents/processors/interactions_request_processor.js +34 -0
  80. package/dist/esm/agents/routed_agent.js +31 -0
  81. package/dist/esm/agents/run_config.js +3 -2
  82. package/dist/esm/apps/app.js +49 -0
  83. package/dist/esm/apps/resumability_config.js +16 -0
  84. package/dist/esm/artifacts/file_artifact_service.js +14 -1
  85. package/dist/esm/artifacts/gcs_artifact_service.js +57 -15
  86. package/dist/esm/artifacts/in_memory_artifact_service.js +12 -1
  87. package/dist/esm/artifacts/scoped_artifact_service.js +73 -0
  88. package/dist/esm/artifacts/session_artifact_service.js +7 -0
  89. package/dist/esm/auth/oauth2/oauth2_discovery.js +14 -4
  90. package/dist/esm/auth/oauth2/oauth2_utils.js +12 -1
  91. package/dist/esm/common.js +67 -3
  92. package/dist/esm/context/agent_controlled_context_compactor.js +81 -0
  93. package/dist/esm/context/anchored_context_compactor.js +99 -0
  94. package/dist/esm/context/compaction_utils.js +27 -0
  95. package/dist/esm/context/token_based_context_compactor.js +52 -33
  96. package/dist/esm/context/trajectory_thought_pruning_compactor.js +43 -0
  97. package/dist/esm/events/compacted_event.js +7 -2
  98. package/dist/esm/events/event.js +46 -0
  99. package/dist/esm/index.js +6 -1
  100. package/dist/esm/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  101. package/dist/esm/models/google_llm.js +23 -9
  102. package/dist/esm/models/interactions_utils.js +697 -0
  103. package/dist/esm/plugins/base_plugin.js +1 -0
  104. package/dist/esm/plugins/global_instruction_plugin.js +69 -0
  105. package/dist/esm/runner/in_memory_runner.js +13 -2
  106. package/dist/esm/runner/runner.js +141 -84
  107. package/dist/esm/sessions/base_session_service.js +6 -1
  108. package/dist/esm/sessions/database_session_service.js +24 -7
  109. package/dist/esm/sessions/vertex_ai_session_service.js +17 -3
  110. package/dist/esm/skills/loader.js +2 -2
  111. package/dist/esm/tools/base_toolset.js +1 -1
  112. package/dist/esm/tools/consolidate_context_tool.js +51 -0
  113. package/dist/esm/tools/enterprise_web_search_tool.js +55 -0
  114. package/dist/esm/tools/example_tool.js +42 -0
  115. package/dist/esm/tools/forwarding_artifact_service.js +16 -28
  116. package/dist/esm/tools/load_web_page.js +221 -0
  117. package/dist/esm/tools/mcp/load_mcp_resource_tool.js +114 -0
  118. package/dist/esm/tools/mcp/mcp_toolset.js +63 -0
  119. package/dist/esm/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -22
  120. package/dist/esm/tools/skill/run_skill_inline_script_tool.js +53 -4
  121. package/dist/esm/tools/skill/skill_toolset.js +4 -2
  122. package/dist/esm/utils/async_hooks_shim.js +24 -0
  123. package/dist/esm/utils/branch_trie.js +13 -0
  124. package/dist/esm/utils/client_labels.js +38 -2
  125. package/dist/esm/utils/env_aware_utils.js +10 -1
  126. package/dist/esm/utils/streaming_utils.js +11 -5
  127. package/dist/esm/utils/task.js +34 -0
  128. package/dist/esm/version.js +1 -1
  129. package/dist/types/a2a/a2a_remote_agent.d.ts +5 -1
  130. package/dist/types/a2a/agent_to_a2a.d.ts +38 -0
  131. package/dist/types/agents/active_streaming_tool.d.ts +3 -4
  132. package/dist/types/agents/base_agent.d.ts +29 -1
  133. package/dist/types/agents/functions.d.ts +12 -17
  134. package/dist/types/agents/invocation_context.d.ts +7 -3
  135. package/dist/types/agents/llm_agent.d.ts +5 -1
  136. package/dist/types/agents/loop_agent.d.ts +2 -2
  137. package/dist/types/agents/processors/content_processor_utils.d.ts +8 -0
  138. package/dist/types/agents/processors/interactions_request_processor.d.ts +17 -0
  139. package/dist/types/agents/routed_agent.d.ts +24 -1
  140. package/dist/types/agents/run_config.d.ts +1 -1
  141. package/dist/types/apps/app.d.ts +52 -0
  142. package/dist/types/apps/resumability_config.d.ts +27 -0
  143. package/dist/types/artifacts/base_artifact_service.d.ts +6 -36
  144. package/dist/types/artifacts/gcs_artifact_service.d.ts +2 -1
  145. package/dist/types/artifacts/scoped_artifact_service.d.ts +25 -0
  146. package/dist/types/artifacts/session_artifact_service.d.ts +25 -0
  147. package/dist/types/auth/oauth2/oauth2_discovery.d.ts +11 -0
  148. package/dist/types/common.d.ts +29 -5
  149. package/dist/types/context/agent_controlled_context_compactor.d.ts +24 -0
  150. package/dist/types/context/anchored_context_compactor.d.ts +35 -0
  151. package/dist/types/context/base_context_compactor.d.ts +3 -0
  152. package/dist/types/context/compaction_utils.d.ts +15 -0
  153. package/dist/types/context/token_based_context_compactor.d.ts +6 -1
  154. package/dist/types/context/trajectory_thought_pruning_compactor.d.ts +27 -0
  155. package/dist/types/events/compacted_event.d.ts +10 -0
  156. package/dist/types/events/event.d.ts +21 -0
  157. package/dist/types/index.d.ts +3 -2
  158. package/dist/types/models/google_llm.d.ts +15 -1
  159. package/dist/types/models/interactions_utils.d.ts +92 -0
  160. package/dist/types/models/llm_request.d.ts +4 -0
  161. package/dist/types/models/llm_response.d.ts +4 -0
  162. package/dist/types/plugins/base_plugin.d.ts +2 -1
  163. package/dist/types/plugins/global_instruction_plugin.d.ts +38 -0
  164. package/dist/types/runner/in_memory_runner.d.ts +7 -1
  165. package/dist/types/runner/runner.d.ts +44 -10
  166. package/dist/types/sessions/base_session_service.d.ts +3 -16
  167. package/dist/types/sessions/session.d.ts +11 -0
  168. package/dist/types/sessions/vertex_ai_session_service.d.ts +9 -1
  169. package/dist/types/tools/consolidate_context_tool.d.ts +19 -0
  170. package/dist/types/tools/enterprise_web_search_tool.d.ts +26 -0
  171. package/dist/types/tools/example_tool.d.ts +21 -0
  172. package/dist/types/tools/forwarding_artifact_service.d.ts +3 -2
  173. package/dist/types/tools/load_web_page.d.ts +33 -0
  174. package/dist/types/tools/mcp/load_mcp_resource_tool.d.ts +26 -0
  175. package/dist/types/tools/mcp/mcp_toolset.d.ts +27 -0
  176. package/dist/types/tools/skill/run_skill_inline_script_tool.d.ts +25 -0
  177. package/dist/types/tools/skill/skill_toolset.d.ts +9 -0
  178. package/dist/types/utils/async_hooks_shim.d.ts +10 -0
  179. package/dist/types/utils/branch_trie.d.ts +14 -0
  180. package/dist/types/utils/client_labels.d.ts +10 -0
  181. package/dist/types/utils/env_aware_utils.d.ts +3 -3
  182. package/dist/types/utils/task.d.ts +24 -0
  183. package/dist/types/version.d.ts +1 -1
  184. package/dist/web/a2a/agent_to_a2a.js +18 -2
  185. package/dist/web/a2a/event_converter_utils.js +8 -4
  186. package/dist/web/a2a/metadata_converter_utils.js +1 -1
  187. package/dist/web/agents/active_streaming_tool.js +6 -1
  188. package/dist/web/agents/base_agent.js +39 -0
  189. package/dist/web/agents/context.js +1 -11
  190. package/dist/web/agents/functions.js +43 -32
  191. package/dist/web/agents/instructions.js +23 -5
  192. package/dist/web/agents/invocation_context.js +2 -5
  193. package/dist/web/agents/llm_agent.js +12 -9
  194. package/dist/web/agents/loop_agent.js +27 -3
  195. package/dist/web/agents/processors/code_execution_request_processor.js +0 -3
  196. package/dist/web/agents/processors/content_processor_utils.js +16 -3
  197. package/dist/web/agents/processors/context_compactor_request_processor.js +4 -2
  198. package/dist/web/agents/processors/interactions_request_processor.js +52 -0
  199. package/dist/web/agents/routed_agent.js +31 -0
  200. package/dist/web/agents/run_config.js +8 -3
  201. package/dist/web/apps/app.js +49 -0
  202. package/dist/web/apps/resumability_config.js +31 -0
  203. package/dist/web/artifacts/file_artifact_service.js +14 -1
  204. package/dist/web/artifacts/gcs_artifact_service.js +55 -15
  205. package/dist/web/artifacts/in_memory_artifact_service.js +12 -1
  206. package/dist/web/artifacts/scoped_artifact_service.js +86 -0
  207. package/dist/web/artifacts/session_artifact_service.js +7 -0
  208. package/dist/web/auth/oauth2/oauth2_discovery.js +14 -4
  209. package/dist/web/auth/oauth2/oauth2_utils.js +12 -1
  210. package/dist/web/common.js +67 -3
  211. package/dist/web/context/agent_controlled_context_compactor.js +81 -0
  212. package/dist/web/context/anchored_context_compactor.js +117 -0
  213. package/dist/web/context/compaction_utils.js +27 -0
  214. package/dist/web/context/token_based_context_compactor.js +52 -33
  215. package/dist/web/context/trajectory_thought_pruning_compactor.js +43 -0
  216. package/dist/web/events/compacted_event.js +7 -2
  217. package/dist/web/events/event.js +44 -0
  218. package/dist/web/index.js +6 -1
  219. package/dist/web/integrations/agent_registry/agent_registry_mcp_toolset.js +9 -1
  220. package/dist/web/models/google_llm.js +54 -9
  221. package/dist/web/models/interactions_utils.js +728 -0
  222. package/dist/web/plugins/base_plugin.js +1 -0
  223. package/dist/web/plugins/global_instruction_plugin.js +67 -0
  224. package/dist/web/runner/in_memory_runner.js +13 -2
  225. package/dist/web/runner/runner.js +157 -84
  226. package/dist/web/sessions/base_session_service.js +6 -1
  227. package/dist/web/sessions/database_session_service.js +24 -7
  228. package/dist/web/sessions/vertex_ai_session_service.js +17 -3
  229. package/dist/web/skills/loader.js +2 -2
  230. package/dist/web/tools/base_toolset.js +1 -1
  231. package/dist/web/tools/consolidate_context_tool.js +51 -0
  232. package/dist/web/tools/enterprise_web_search_tool.js +55 -0
  233. package/dist/web/tools/example_tool.js +42 -0
  234. package/dist/web/tools/forwarding_artifact_service.js +16 -28
  235. package/dist/web/tools/load_web_page.js +221 -0
  236. package/dist/web/tools/mcp/load_mcp_resource_tool.js +107 -0
  237. package/dist/web/tools/mcp/mcp_toolset.js +63 -0
  238. package/dist/web/tools/openapi_tool/openapi_spec_parser/tool_auth_handler.js +15 -22
  239. package/dist/web/tools/skill/run_skill_inline_script_tool.js +51 -4
  240. package/dist/web/tools/skill/skill_toolset.js +4 -2
  241. package/dist/web/utils/async_hooks_shim.js +24 -0
  242. package/dist/web/utils/branch_trie.js +13 -0
  243. package/dist/web/utils/client_labels.js +38 -2
  244. package/dist/web/utils/env_aware_utils.js +10 -1
  245. package/dist/web/utils/streaming_utils.js +11 -5
  246. package/dist/web/utils/task.js +34 -0
  247. package/dist/web/version.js +1 -1
  248. package/package.json +2 -2
@@ -0,0 +1,697 @@
1
+ import {createRequire as topLevelCreateRequire} from 'module';
2
+ const require = topLevelCreateRequire(import.meta.url);
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ import {
9
+ Outcome
10
+ } from "@google/genai";
11
+ import { logger } from "../utils/logger.js";
12
+ function getInteractionMediaType(mimeType) {
13
+ switch (mimeType.split("/")[0]) {
14
+ case "image":
15
+ return "image";
16
+ case "audio":
17
+ return "audio";
18
+ case "video":
19
+ return "video";
20
+ default:
21
+ return "document";
22
+ }
23
+ }
24
+ function getLatestUserContents(contents) {
25
+ if (!contents || contents.length === 0) {
26
+ return [];
27
+ }
28
+ const latestUserContents = [];
29
+ for (let i = contents.length - 1; i >= 0; i--) {
30
+ const content = contents[i];
31
+ if (content.role === "user") {
32
+ latestUserContents.unshift(content);
33
+ } else {
34
+ break;
35
+ }
36
+ }
37
+ let hasFunctionResult = false;
38
+ for (const content of latestUserContents) {
39
+ if (content.parts) {
40
+ for (const part of content.parts) {
41
+ if (part.functionResponse !== void 0 && part.functionResponse !== null) {
42
+ hasFunctionResult = true;
43
+ break;
44
+ }
45
+ }
46
+ }
47
+ if (hasFunctionResult) {
48
+ break;
49
+ }
50
+ }
51
+ if (hasFunctionResult && contents.length > latestUserContents.length) {
52
+ const userStartIdx = contents.length - latestUserContents.length;
53
+ if (userStartIdx > 0) {
54
+ const precedingContent = contents[userStartIdx - 1];
55
+ if (precedingContent.role === "model" && precedingContent.parts) {
56
+ for (const part of precedingContent.parts) {
57
+ if (part.functionCall !== void 0 && part.functionCall !== null) {
58
+ return [precedingContent, ...latestUserContents];
59
+ }
60
+ }
61
+ }
62
+ }
63
+ }
64
+ return latestUserContents;
65
+ }
66
+ function convertPartToMediaContent(part) {
67
+ if (part.text !== void 0 && part.text !== null) {
68
+ return { type: "text", text: part.text };
69
+ }
70
+ if (part.inlineData !== void 0 && part.inlineData !== null) {
71
+ const mimeType = part.inlineData.mimeType || "";
72
+ return {
73
+ type: getInteractionMediaType(mimeType),
74
+ data: part.inlineData.data,
75
+ mime_type: mimeType
76
+ };
77
+ }
78
+ if (part.fileData !== void 0 && part.fileData !== null) {
79
+ const mimeType = part.fileData.mimeType || "";
80
+ return {
81
+ type: getInteractionMediaType(mimeType),
82
+ uri: part.fileData.fileUri,
83
+ mime_type: mimeType
84
+ };
85
+ }
86
+ return null;
87
+ }
88
+ function convertContentToSteps(content) {
89
+ const steps = [];
90
+ const role = content.role || "user";
91
+ if (role === "user") {
92
+ const mediaContents = [];
93
+ if (content.parts) {
94
+ for (const part of content.parts) {
95
+ if (part.functionResponse) {
96
+ steps.push({
97
+ type: "function_result",
98
+ call_id: part.functionResponse.id || "",
99
+ name: part.functionResponse.name || "",
100
+ result: part.functionResponse.response
101
+ });
102
+ } else if (part.codeExecutionResult) {
103
+ const isError = part.codeExecutionResult.outcome === Outcome.OUTCOME_FAILED || part.codeExecutionResult.outcome === Outcome.OUTCOME_DEADLINE_EXCEEDED;
104
+ steps.push({
105
+ type: "code_execution_result",
106
+ call_id: "",
107
+ result: part.codeExecutionResult.output || "",
108
+ is_error: isError
109
+ });
110
+ } else {
111
+ const mediaContent = convertPartToMediaContent(part);
112
+ if (mediaContent) {
113
+ mediaContents.push(mediaContent);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ if (mediaContents.length > 0) {
119
+ steps.push({
120
+ type: "user_input",
121
+ content: mediaContents
122
+ });
123
+ }
124
+ } else if (role === "model") {
125
+ const mediaContents = [];
126
+ if (content.parts) {
127
+ for (const part of content.parts) {
128
+ if (part.functionCall) {
129
+ const step = {
130
+ type: "function_call",
131
+ id: part.functionCall.id || "",
132
+ name: part.functionCall.name || "",
133
+ arguments: part.functionCall.args || {}
134
+ };
135
+ if (part.thoughtSignature) {
136
+ step.signature = part.thoughtSignature;
137
+ }
138
+ steps.push(step);
139
+ } else if (part.executableCode) {
140
+ steps.push({
141
+ type: "code_execution_call",
142
+ id: "",
143
+ arguments: {
144
+ code: part.executableCode.code || "",
145
+ language: "python"
146
+ }
147
+ });
148
+ } else if (part.thought) {
149
+ const step = {
150
+ type: "thought"
151
+ };
152
+ if (part.thoughtSignature) {
153
+ step.signature = part.thoughtSignature;
154
+ }
155
+ steps.push(step);
156
+ } else {
157
+ const mediaContent = convertPartToMediaContent(part);
158
+ if (mediaContent) {
159
+ mediaContents.push(mediaContent);
160
+ }
161
+ }
162
+ }
163
+ }
164
+ if (mediaContents.length > 0) {
165
+ steps.push({
166
+ type: "model_output",
167
+ content: mediaContents
168
+ });
169
+ }
170
+ }
171
+ return steps;
172
+ }
173
+ function convertMediaContentToPart(content) {
174
+ if (content.type === "text") {
175
+ return { text: content.text || "" };
176
+ }
177
+ if (content.type === "image" || content.type === "audio" || content.type === "video" || content.type === "document") {
178
+ const media = content;
179
+ if (media.data) {
180
+ return {
181
+ inlineData: {
182
+ data: media.data,
183
+ mimeType: media.mime_type || ""
184
+ }
185
+ };
186
+ } else if (media.uri) {
187
+ return {
188
+ fileData: {
189
+ fileUri: media.uri,
190
+ mimeType: media.mime_type || ""
191
+ }
192
+ };
193
+ }
194
+ }
195
+ return null;
196
+ }
197
+ function convertStepToParts(step) {
198
+ if (!step || !step.type) {
199
+ return [];
200
+ }
201
+ switch (step.type) {
202
+ case "model_output": {
203
+ const modelOutputStep = step;
204
+ const parts = [];
205
+ if (modelOutputStep.content) {
206
+ for (const content of modelOutputStep.content) {
207
+ const part = convertMediaContentToPart(content);
208
+ if (part) {
209
+ parts.push(part);
210
+ }
211
+ }
212
+ }
213
+ return parts;
214
+ }
215
+ case "user_input": {
216
+ const userInputStep = step;
217
+ const parts = [];
218
+ if (userInputStep.content) {
219
+ for (const content of userInputStep.content) {
220
+ const part = convertMediaContentToPart(content);
221
+ if (part) {
222
+ parts.push(part);
223
+ }
224
+ }
225
+ }
226
+ return parts;
227
+ }
228
+ case "function_call": {
229
+ const functionCallStep = step;
230
+ const part = {
231
+ functionCall: {
232
+ id: functionCallStep.id,
233
+ name: functionCallStep.name,
234
+ args: functionCallStep.arguments || {}
235
+ }
236
+ };
237
+ if (functionCallStep.signature) {
238
+ part.thoughtSignature = functionCallStep.signature;
239
+ }
240
+ return [part];
241
+ }
242
+ case "function_result": {
243
+ const functionResultStep = step;
244
+ const result = functionResultStep.result;
245
+ return [
246
+ {
247
+ functionResponse: {
248
+ id: functionResultStep.call_id,
249
+ name: functionResultStep.name || "",
250
+ response: typeof result === "object" && result !== null ? result : { output: result }
251
+ }
252
+ }
253
+ ];
254
+ }
255
+ case "code_execution_call": {
256
+ const codeExecutionCallStep = step;
257
+ const args = codeExecutionCallStep.arguments || {};
258
+ return [
259
+ {
260
+ executableCode: {
261
+ code: args.code || "",
262
+ language: (args.language || "PYTHON").toUpperCase()
263
+ }
264
+ }
265
+ ];
266
+ }
267
+ case "code_execution_result": {
268
+ const codeExecutionResultStep = step;
269
+ return [
270
+ {
271
+ codeExecutionResult: {
272
+ output: codeExecutionResultStep.result || "",
273
+ outcome: codeExecutionResultStep.is_error ? Outcome.OUTCOME_FAILED : Outcome.OUTCOME_OK
274
+ }
275
+ }
276
+ ];
277
+ }
278
+ case "thought": {
279
+ const thoughtStep = step;
280
+ const part = {
281
+ thought: true
282
+ };
283
+ if (thoughtStep.signature) {
284
+ part.thoughtSignature = thoughtStep.signature;
285
+ }
286
+ return [part];
287
+ }
288
+ default:
289
+ return [];
290
+ }
291
+ }
292
+ function convertToolsConfigToInteractionsFormat(config) {
293
+ if (!config.tools) {
294
+ return [];
295
+ }
296
+ const interactionTools = [];
297
+ for (const tool of config.tools) {
298
+ const t = tool;
299
+ if (t.functionDeclarations) {
300
+ for (const funcDecl of t.functionDeclarations) {
301
+ const funcTool = {
302
+ type: "function",
303
+ name: funcDecl.name
304
+ };
305
+ if (funcDecl.description) {
306
+ funcTool.description = funcDecl.description;
307
+ }
308
+ if (funcDecl.parameters) {
309
+ if (funcDecl.parameters.properties) {
310
+ const props = {};
311
+ for (const [k, v] of Object.entries(
312
+ funcDecl.parameters.properties
313
+ )) {
314
+ props[k] = JSON.parse(JSON.stringify(v));
315
+ }
316
+ funcTool.parameters = {
317
+ type: "object",
318
+ properties: props,
319
+ required: funcDecl.parameters.required ? [...funcDecl.parameters.required] : void 0
320
+ };
321
+ }
322
+ } else if (funcDecl.parametersJsonSchema) {
323
+ funcTool.parameters = funcDecl.parametersJsonSchema;
324
+ }
325
+ interactionTools.push(funcTool);
326
+ }
327
+ }
328
+ if (t.googleSearch) {
329
+ interactionTools.push({ type: "google_search" });
330
+ }
331
+ if (t.codeExecution) {
332
+ interactionTools.push({ type: "code_execution" });
333
+ }
334
+ if (t.urlContext) {
335
+ interactionTools.push({ type: "url_context" });
336
+ }
337
+ }
338
+ return interactionTools;
339
+ }
340
+ function findLastPart(parts, predicate) {
341
+ for (let i = parts.length - 1; i >= 0; i--) {
342
+ if (predicate(parts[i])) {
343
+ return parts[i];
344
+ }
345
+ }
346
+ return void 0;
347
+ }
348
+ function getLatestModelParts(steps) {
349
+ if (!steps || steps.length === 0) {
350
+ return [];
351
+ }
352
+ const latestParts = [];
353
+ for (let i = steps.length - 1; i >= 0; i--) {
354
+ const step = steps[i];
355
+ if (step.type === "user_input" || step.type === "function_result" || step.type === "code_execution_result") {
356
+ break;
357
+ }
358
+ const parts = convertStepToParts(step);
359
+ latestParts.unshift(...parts);
360
+ }
361
+ return latestParts;
362
+ }
363
+ function convertInteractionToLlmResponse(interaction) {
364
+ if (interaction.status === "failed") {
365
+ let errorMsg = "Unknown error";
366
+ let errorCode = "UNKNOWN_ERROR";
367
+ if (interaction.error) {
368
+ errorMsg = interaction.error.message || errorMsg;
369
+ errorCode = interaction.error.code || errorCode;
370
+ }
371
+ return {
372
+ errorCode,
373
+ errorMessage: errorMsg,
374
+ interactionId: interaction.id
375
+ };
376
+ }
377
+ const parts = getLatestModelParts(interaction.steps || []);
378
+ let content = void 0;
379
+ if (parts.length > 0) {
380
+ content = { role: "model", parts };
381
+ }
382
+ let usageMetadata = void 0;
383
+ if (interaction.usage) {
384
+ const inputTokens = interaction.usage.total_input_tokens || 0;
385
+ const outputTokens = interaction.usage.total_output_tokens || 0;
386
+ usageMetadata = {
387
+ promptTokenCount: inputTokens,
388
+ candidatesTokenCount: outputTokens,
389
+ totalTokenCount: inputTokens + outputTokens
390
+ };
391
+ }
392
+ let finishReason = void 0;
393
+ if (interaction.status === "completed" || interaction.status === "requires_action") {
394
+ finishReason = "STOP";
395
+ }
396
+ return {
397
+ content,
398
+ usageMetadata,
399
+ finishReason,
400
+ turnComplete: interaction.status === "completed" || interaction.status === "requires_action",
401
+ interactionId: interaction.id
402
+ };
403
+ }
404
+ function convertInteractionEventToLlmResponse(event, aggregatedParts, interactionId) {
405
+ var _a, _b;
406
+ const eventType = event.event_type || event.eventType;
407
+ if (eventType === "step.start") {
408
+ const stepStart = event;
409
+ const step = stepStart.step;
410
+ if (step.type === "function_call") {
411
+ const fcStep = step;
412
+ const part = {
413
+ functionCall: {
414
+ id: fcStep.id,
415
+ name: fcStep.name,
416
+ args: {}
417
+ },
418
+ partMetadata: {
419
+ accumulatedArgs: "",
420
+ isComplete: false
421
+ }
422
+ };
423
+ if (fcStep.signature) {
424
+ part.thoughtSignature = fcStep.signature;
425
+ }
426
+ aggregatedParts.push(part);
427
+ return null;
428
+ }
429
+ if (step.type === "thought") {
430
+ const part = {
431
+ thought: true,
432
+ partMetadata: {
433
+ isComplete: false
434
+ }
435
+ };
436
+ if (step.signature) {
437
+ part.thoughtSignature = step.signature;
438
+ }
439
+ aggregatedParts.push(part);
440
+ return null;
441
+ }
442
+ } else if (eventType === "step.delta") {
443
+ const stepDelta = event;
444
+ const delta = stepDelta.delta;
445
+ if (!delta) {
446
+ return null;
447
+ }
448
+ if (delta.type === "text") {
449
+ const text = delta.text || "";
450
+ if (text) {
451
+ const part = { text };
452
+ aggregatedParts.push(part);
453
+ return {
454
+ content: { role: "model", parts: [part] },
455
+ partial: true,
456
+ turnComplete: false,
457
+ interactionId
458
+ };
459
+ }
460
+ } else if (delta.type === "arguments_delta") {
461
+ const activePart = findLastPart(
462
+ aggregatedParts,
463
+ (p) => !!(p.functionCall && p.partMetadata && !p.partMetadata.isComplete)
464
+ );
465
+ if (activePart && activePart.partMetadata && delta.arguments) {
466
+ activePart.partMetadata.accumulatedArgs = activePart.partMetadata.accumulatedArgs + delta.arguments;
467
+ }
468
+ return null;
469
+ } else if (delta.type === "thought_signature") {
470
+ const activePart = findLastPart(
471
+ aggregatedParts,
472
+ (p) => !!((p.thought || p.functionCall) && p.partMetadata && !p.partMetadata.isComplete)
473
+ );
474
+ if (activePart && delta.signature) {
475
+ activePart.thoughtSignature = delta.signature;
476
+ }
477
+ return null;
478
+ } else if (delta.type === "image" || delta.type === "audio" || delta.type === "video" || delta.type === "document") {
479
+ const part = convertMediaContentToPart(delta);
480
+ if (part) {
481
+ aggregatedParts.push(part);
482
+ return {
483
+ content: { role: "model", parts: [part] },
484
+ partial: false,
485
+ turnComplete: false,
486
+ interactionId
487
+ };
488
+ }
489
+ }
490
+ } else if (eventType === "step.stop") {
491
+ const activePart = findLastPart(
492
+ aggregatedParts,
493
+ (p) => !!(p.partMetadata && !p.partMetadata.isComplete)
494
+ );
495
+ if (activePart && activePart.partMetadata) {
496
+ activePart.partMetadata.isComplete = true;
497
+ if (activePart.functionCall) {
498
+ const accumulatedArgs = activePart.partMetadata.accumulatedArgs;
499
+ try {
500
+ activePart.functionCall.args = accumulatedArgs ? JSON.parse(accumulatedArgs) : {};
501
+ } catch (e) {
502
+ logger.error(
503
+ `Failed to parse accumulated arguments: ${accumulatedArgs}`,
504
+ e
505
+ );
506
+ activePart.functionCall.args = {};
507
+ }
508
+ delete activePart.partMetadata;
509
+ return {
510
+ content: { role: "model", parts: [activePart] },
511
+ partial: false,
512
+ turnComplete: false,
513
+ interactionId
514
+ };
515
+ }
516
+ if (activePart.thought) {
517
+ delete activePart.partMetadata;
518
+ return null;
519
+ }
520
+ }
521
+ } else if (eventType === "interaction.completed") {
522
+ return {
523
+ content: aggregatedParts.length > 0 ? { role: "model", parts: [...aggregatedParts] } : void 0,
524
+ partial: false,
525
+ turnComplete: true,
526
+ finishReason: "STOP",
527
+ interactionId
528
+ };
529
+ } else if (eventType === "interaction.status_update") {
530
+ const statusUpdate = event;
531
+ const status = statusUpdate.status;
532
+ if (status === "completed" || status === "requires_action") {
533
+ return {
534
+ content: aggregatedParts.length > 0 ? { role: "model", parts: [...aggregatedParts] } : void 0,
535
+ partial: false,
536
+ turnComplete: true,
537
+ finishReason: "STOP",
538
+ interactionId
539
+ };
540
+ } else if (status === "failed") {
541
+ const error = statusUpdate.error;
542
+ return {
543
+ errorCode: error ? error.code : "UNKNOWN_ERROR",
544
+ errorMessage: error ? error.message : "Unknown error",
545
+ turnComplete: true,
546
+ interactionId
547
+ };
548
+ }
549
+ } else if (eventType === "error") {
550
+ return {
551
+ errorCode: ((_a = event.error) == null ? void 0 : _a.code) || event.code || "UNKNOWN_ERROR",
552
+ errorMessage: ((_b = event.error) == null ? void 0 : _b.message) || event.message || "Unknown error",
553
+ turnComplete: true,
554
+ interactionId
555
+ };
556
+ }
557
+ return null;
558
+ }
559
+ function buildGenerationConfig(config) {
560
+ const generationConfig = {};
561
+ if (config.temperature !== void 0 && config.temperature !== null) {
562
+ generationConfig["temperature"] = config.temperature;
563
+ }
564
+ if (config.topP !== void 0 && config.topP !== null) {
565
+ generationConfig["top_p"] = config.topP;
566
+ }
567
+ if (config.topK !== void 0 && config.topK !== null) {
568
+ generationConfig["top_k"] = config.topK;
569
+ }
570
+ if (config.maxOutputTokens !== void 0 && config.maxOutputTokens !== null) {
571
+ generationConfig["max_output_tokens"] = config.maxOutputTokens;
572
+ }
573
+ if (config.stopSequences) {
574
+ generationConfig["stop_sequences"] = config.stopSequences;
575
+ }
576
+ if (config.presencePenalty !== void 0 && config.presencePenalty !== null) {
577
+ generationConfig["presence_penalty"] = config.presencePenalty;
578
+ }
579
+ if (config.frequencyPenalty !== void 0 && config.frequencyPenalty !== null) {
580
+ generationConfig["frequency_penalty"] = config.frequencyPenalty;
581
+ }
582
+ return generationConfig;
583
+ }
584
+ function extractSystemInstruction(config) {
585
+ const systemInstruction = config.systemInstruction;
586
+ if (!systemInstruction) {
587
+ return void 0;
588
+ }
589
+ if (typeof systemInstruction === "string") {
590
+ return systemInstruction;
591
+ }
592
+ if (typeof systemInstruction === "object" && "parts" in systemInstruction && Array.isArray(systemInstruction.parts)) {
593
+ const texts = [];
594
+ for (const part of systemInstruction.parts) {
595
+ const p = part;
596
+ if (p.text) {
597
+ texts.push(p.text);
598
+ }
599
+ }
600
+ return texts.length > 0 ? texts.join("\n") : void 0;
601
+ }
602
+ return void 0;
603
+ }
604
+ function extractStreamInteractionId(event) {
605
+ if (event.interaction_id || event.interactionId) {
606
+ return event.interaction_id || event.interactionId;
607
+ }
608
+ if (event.interaction && event.interaction.id) {
609
+ return event.interaction.id;
610
+ }
611
+ if (event.event_type === "interaction" || event.eventType === "interaction") {
612
+ return event.id;
613
+ }
614
+ return void 0;
615
+ }
616
+ async function* generateContentViaInteractions(apiClient, llmRequest, stream) {
617
+ let contents = llmRequest.contents;
618
+ if (llmRequest.previousInteractionId && contents) {
619
+ contents = getLatestUserContents(contents);
620
+ }
621
+ const inputSteps = [];
622
+ if (contents) {
623
+ for (const content of contents) {
624
+ inputSteps.push(...convertContentToSteps(content));
625
+ }
626
+ }
627
+ const interactionTools = convertToolsConfigToInteractionsFormat(
628
+ llmRequest.config || {}
629
+ );
630
+ const systemInstruction = extractSystemInstruction(llmRequest.config || {});
631
+ const generationConfig = buildGenerationConfig(llmRequest.config || {});
632
+ const previousInteractionId = llmRequest.previousInteractionId;
633
+ logger.info(
634
+ `Sending request via interactions API, model: ${llmRequest.model}, stream: ${stream}, previous_interaction_id: ${previousInteractionId}`
635
+ );
636
+ let currentInteractionId = previousInteractionId;
637
+ if (stream) {
638
+ const responses = await apiClient.interactions.create({
639
+ model: llmRequest.model || "gemini-2.5-flash",
640
+ input: inputSteps,
641
+ stream: true,
642
+ system_instruction: systemInstruction,
643
+ tools: interactionTools.length > 0 ? interactionTools : void 0,
644
+ generation_config: Object.keys(generationConfig).length > 0 ? generationConfig : void 0,
645
+ previous_interaction_id: previousInteractionId
646
+ });
647
+ const aggregatedParts = [];
648
+ for await (const event of responses) {
649
+ const sseEvent = event;
650
+ const interactionId = extractStreamInteractionId(sseEvent);
651
+ if (interactionId) {
652
+ currentInteractionId = interactionId;
653
+ }
654
+ const llmResponse = convertInteractionEventToLlmResponse(
655
+ sseEvent,
656
+ aggregatedParts,
657
+ currentInteractionId
658
+ );
659
+ if (llmResponse) {
660
+ yield llmResponse;
661
+ }
662
+ }
663
+ if (aggregatedParts.length > 0) {
664
+ yield {
665
+ content: { role: "model", parts: aggregatedParts },
666
+ partial: false,
667
+ turnComplete: true,
668
+ finishReason: "STOP",
669
+ interactionId: currentInteractionId
670
+ };
671
+ }
672
+ } else {
673
+ const interaction = await apiClient.interactions.create({
674
+ model: llmRequest.model || "gemini-2.5-flash",
675
+ input: inputSteps,
676
+ stream: false,
677
+ system_instruction: systemInstruction,
678
+ tools: interactionTools.length > 0 ? interactionTools : void 0,
679
+ generation_config: Object.keys(generationConfig).length > 0 ? generationConfig : void 0,
680
+ previous_interaction_id: previousInteractionId
681
+ });
682
+ logger.info("Interaction response received from the model.");
683
+ yield convertInteractionToLlmResponse(interaction);
684
+ }
685
+ }
686
+ export {
687
+ buildGenerationConfig,
688
+ convertContentToSteps,
689
+ convertInteractionEventToLlmResponse,
690
+ convertInteractionToLlmResponse,
691
+ convertStepToParts,
692
+ convertToolsConfigToInteractionsFormat,
693
+ extractSystemInstruction,
694
+ generateContentViaInteractions,
695
+ getLatestModelParts,
696
+ getLatestUserContents
697
+ };
@@ -19,6 +19,7 @@ import { experimental } from "../utils/experimental.js";
19
19
  var ContextCompactionTrigger = /* @__PURE__ */ ((ContextCompactionTrigger2) => {
20
20
  ContextCompactionTrigger2["Manual"] = "Manual";
21
21
  ContextCompactionTrigger2["Auto"] = "Auto";
22
+ ContextCompactionTrigger2["AgentControlled"] = "AgentControlled";
22
23
  return ContextCompactionTrigger2;
23
24
  })(ContextCompactionTrigger || {});
24
25
  class BasePlugin {