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