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