@tanstack/ai-gemini 0.11.0 → 0.12.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.
@@ -0,0 +1,907 @@
1
+ import { EventType } from "@tanstack/ai";
2
+ import { BaseTextAdapter } from "@tanstack/ai/adapters";
3
+ import { createGeminiClient, generateId, getGeminiApiKeyFromEnv } from "../../utils/client.js";
4
+ class GeminiTextInteractionsAdapter extends BaseTextAdapter {
5
+ kind = "text";
6
+ name = "gemini-text-interactions";
7
+ client;
8
+ // Tracks the most recent server-assigned interaction id per threadId
9
+ // so the adapter can chain follow-up calls on the same thread without
10
+ // the caller having to thread the id manually. Two callers rely on
11
+ // this:
12
+ // 1. The agent loop's tool-call iterations (each iteration is a new
13
+ // `chatStream` call with accumulated tool messages).
14
+ // 2. The agentic-structured composition: a `chatStream` run followed
15
+ // by `structuredOutput` on the accumulated messages.
16
+ // Cross-request chaining is the caller's job via
17
+ // `modelOptions.previous_interaction_id`. To keep stale ids from
18
+ // chaining a brand-new turn, `chatStream` evicts at the START when
19
+ // the caller signals fresh-turn intent (no caller-provided id AND a
20
+ // single user message — anything else is a follow-up). Errors evict
21
+ // immediately so a failed turn never chains into the next one.
22
+ interactionIdByThread = /* @__PURE__ */ new Map();
23
+ constructor(config, model) {
24
+ super({}, model);
25
+ this.client = createGeminiClient(config);
26
+ }
27
+ async *chatStream(options) {
28
+ const runId = options.runId ?? generateId(this.name);
29
+ const threadId = options.threadId ?? generateId(this.name);
30
+ const timestamp = Date.now();
31
+ const { logger } = options;
32
+ if (!options.modelOptions?.previous_interaction_id && options.messages.length === 1 && options.messages[0]?.role === "user") {
33
+ this.interactionIdByThread.delete(threadId);
34
+ }
35
+ const effectivePreviousInteractionId = options.modelOptions?.previous_interaction_id ?? this.interactionIdByThread.get(threadId);
36
+ let sawTerminalEvent = false;
37
+ let completedTryBlock = false;
38
+ try {
39
+ const request = buildInteractionsRequest({
40
+ ...options,
41
+ modelOptions: {
42
+ ...options.modelOptions,
43
+ previous_interaction_id: effectivePreviousInteractionId
44
+ }
45
+ });
46
+ logger.request(
47
+ `activity=chat provider=gemini-text-interactions model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,
48
+ {
49
+ provider: "gemini-text-interactions",
50
+ model: this.model,
51
+ request
52
+ }
53
+ );
54
+ const stream = await this.client.interactions.create(
55
+ { ...request, stream: true },
56
+ { signal: options.abortController?.signal }
57
+ );
58
+ for await (const chunk of translateInteractionEvents(
59
+ stream,
60
+ options.model,
61
+ runId,
62
+ threadId,
63
+ options.parentRunId,
64
+ timestamp,
65
+ this.name,
66
+ logger
67
+ )) {
68
+ if (chunk.type === EventType.CUSTOM && chunk.name === "gemini.interactionId") {
69
+ const value = chunk.value;
70
+ this.interactionIdByThread.set(threadId, value.interactionId);
71
+ }
72
+ if (chunk.type === EventType.RUN_FINISHED) {
73
+ sawTerminalEvent = true;
74
+ } else if (chunk.type === EventType.RUN_ERROR) {
75
+ sawTerminalEvent = true;
76
+ this.interactionIdByThread.delete(threadId);
77
+ }
78
+ yield chunk;
79
+ }
80
+ if (!sawTerminalEvent) {
81
+ this.interactionIdByThread.delete(threadId);
82
+ const message = "Gemini Interactions stream ended without a terminal event (no interaction.complete or error)";
83
+ logger.errors("gemini-text-interactions.chatStream truncated", {
84
+ source: "gemini-text-interactions.chatStream",
85
+ runId,
86
+ threadId
87
+ });
88
+ yield {
89
+ type: EventType.RUN_ERROR,
90
+ runId,
91
+ model: options.model,
92
+ timestamp,
93
+ message,
94
+ error: { message }
95
+ };
96
+ }
97
+ completedTryBlock = true;
98
+ } catch (error) {
99
+ this.interactionIdByThread.delete(threadId);
100
+ const message = error instanceof Error ? error.message : "An unknown error occurred during the interactions stream.";
101
+ logger.errors("gemini-text-interactions.chatStream fatal", {
102
+ error,
103
+ source: "gemini-text-interactions.chatStream"
104
+ });
105
+ yield {
106
+ type: EventType.RUN_ERROR,
107
+ runId,
108
+ model: options.model,
109
+ timestamp,
110
+ message,
111
+ error: { message }
112
+ };
113
+ } finally {
114
+ if (!completedTryBlock) {
115
+ this.interactionIdByThread.delete(threadId);
116
+ }
117
+ }
118
+ }
119
+ async structuredOutput(options) {
120
+ const { chatOptions, outputSchema } = options;
121
+ const { logger } = chatOptions;
122
+ const threadId = chatOptions.threadId;
123
+ const effectivePreviousInteractionId = chatOptions.modelOptions?.previous_interaction_id ?? (threadId ? this.interactionIdByThread.get(threadId) : void 0);
124
+ const baseRequest = buildInteractionsRequest({
125
+ ...chatOptions,
126
+ modelOptions: {
127
+ ...chatOptions.modelOptions,
128
+ previous_interaction_id: effectivePreviousInteractionId
129
+ }
130
+ });
131
+ const request = {
132
+ ...baseRequest,
133
+ response_mime_type: "application/json",
134
+ response_format: outputSchema
135
+ };
136
+ try {
137
+ logger.request(
138
+ `activity=chat provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,
139
+ {
140
+ provider: "gemini-text-interactions",
141
+ model: this.model,
142
+ request
143
+ }
144
+ );
145
+ const result = await this.client.interactions.create(
146
+ request,
147
+ { signal: chatOptions.abortController?.signal }
148
+ );
149
+ const rawText = extractTextFromInteraction(result);
150
+ if (!rawText) {
151
+ throw new Error(
152
+ `Gemini Interactions returned no text output for structured-output request (status: ${result.status}). The model may have produced only tool calls or non-text content.`
153
+ );
154
+ }
155
+ let parsed;
156
+ try {
157
+ parsed = JSON.parse(rawText);
158
+ } catch {
159
+ throw new Error(
160
+ `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? "..." : ""}`
161
+ );
162
+ }
163
+ return { data: parsed, rawText };
164
+ } catch (error) {
165
+ logger.errors("gemini-text-interactions.structuredOutput fatal", {
166
+ error,
167
+ source: "gemini-text-interactions.structuredOutput"
168
+ });
169
+ throw new Error(
170
+ error instanceof Error ? error.message : "An unknown error occurred during structured output generation.",
171
+ { cause: error }
172
+ );
173
+ }
174
+ }
175
+ }
176
+ function createGeminiTextInteractions(model, apiKey, config) {
177
+ return new GeminiTextInteractionsAdapter({ apiKey, ...config }, model);
178
+ }
179
+ function geminiTextInteractions(model, config) {
180
+ const apiKey = getGeminiApiKeyFromEnv();
181
+ return createGeminiTextInteractions(model, apiKey, config);
182
+ }
183
+ function buildInteractionsRequest(options) {
184
+ const modelOpts = options.modelOptions;
185
+ const systemInstruction = modelOpts?.system_instruction ?? options.systemPrompts?.join("\n");
186
+ const generationConfig = {
187
+ ...modelOpts?.generation_config
188
+ };
189
+ if (options.temperature !== void 0) {
190
+ generationConfig.temperature = options.temperature;
191
+ }
192
+ if (options.topP !== void 0) {
193
+ generationConfig.top_p = options.topP;
194
+ }
195
+ if (options.maxTokens !== void 0) {
196
+ generationConfig.max_output_tokens = options.maxTokens;
197
+ }
198
+ const hasGenerationConfig = Object.keys(generationConfig).length > 0;
199
+ const input = convertMessagesToInteractionsInput(
200
+ options.messages,
201
+ modelOpts?.previous_interaction_id !== void 0
202
+ );
203
+ return {
204
+ model: options.model,
205
+ input,
206
+ previous_interaction_id: modelOpts?.previous_interaction_id,
207
+ system_instruction: systemInstruction,
208
+ tools: convertToolsToInteractionsFormat(options.tools),
209
+ generation_config: hasGenerationConfig ? generationConfig : void 0,
210
+ store: modelOpts?.store,
211
+ background: modelOpts?.background,
212
+ response_modalities: modelOpts?.response_modalities,
213
+ response_format: modelOpts?.response_format,
214
+ response_mime_type: modelOpts?.response_mime_type
215
+ };
216
+ }
217
+ function convertMessagesToInteractionsInput(messages, hasPreviousInteraction) {
218
+ const toolCallIdToName = /* @__PURE__ */ new Map();
219
+ for (const msg of messages) {
220
+ if (msg.role === "assistant" && msg.toolCalls) {
221
+ for (const tc of msg.toolCalls) {
222
+ toolCallIdToName.set(tc.id, tc.function.name);
223
+ }
224
+ }
225
+ }
226
+ const source = hasPreviousInteraction ? messagesAfterLastAssistant(messages) : messages;
227
+ if (hasPreviousInteraction && source.length === 0) {
228
+ throw new Error(
229
+ "Gemini Interactions adapter: modelOptions.previous_interaction_id was provided but no new messages were found after the last assistant turn. Append at least one user or tool message before chaining."
230
+ );
231
+ }
232
+ if (!hasPreviousInteraction) {
233
+ const [only, ...rest] = source;
234
+ if (!only) {
235
+ throw new Error("Gemini Interactions adapter: no messages to send.");
236
+ }
237
+ if (rest.length > 0) {
238
+ throw new Error(
239
+ 'Gemini Interactions adapter: cannot send prior conversation history on a fresh interaction. Either set modelOptions.previous_interaction_id to chain prior turns server-side, or trim the message list to a single new user turn. See docs/adapters/gemini.md ("Wiring with useChat") for the canonical client/server pattern.'
240
+ );
241
+ }
242
+ if (only.role !== "user") {
243
+ throw new Error(
244
+ `Gemini Interactions adapter: the first message of a fresh interaction must be a user turn (got role="${only.role}"). Set modelOptions.previous_interaction_id to continue an existing interaction.`
245
+ );
246
+ }
247
+ const content = messageToContentBlocks(only);
248
+ if (content.length === 0) {
249
+ throw new Error(
250
+ "Gemini Interactions adapter: the user message produced no content blocks to send."
251
+ );
252
+ }
253
+ return [{ type: "user_input", content }];
254
+ }
255
+ const steps = [];
256
+ for (const msg of source) {
257
+ if (msg.role === "tool" && msg.toolCallId) {
258
+ const result = serializeToolResultContent(msg.content);
259
+ steps.push({
260
+ type: "function_result",
261
+ call_id: msg.toolCallId,
262
+ name: toolCallIdToName.get(msg.toolCallId),
263
+ result
264
+ });
265
+ } else if (msg.role === "user") {
266
+ const content = messageToContentBlocks(msg);
267
+ if (content.length > 0) {
268
+ steps.push({ type: "user_input", content });
269
+ }
270
+ }
271
+ }
272
+ if (steps.length === 0) {
273
+ throw new Error(
274
+ "Gemini Interactions adapter: messages after the last assistant turn produced no steps to send."
275
+ );
276
+ }
277
+ return steps;
278
+ }
279
+ function serializeToolResultContent(content) {
280
+ if (typeof content === "string") return content;
281
+ if (content === null || content === void 0) {
282
+ throw new Error(
283
+ "Gemini Interactions adapter: tool message has no content. The Interactions API requires a string `result` on function_result steps — return a string from your tool implementation (encode JSON/multimodal output yourself)."
284
+ );
285
+ }
286
+ throw new Error(
287
+ "Gemini Interactions adapter: tool message content must be a string (got an array of content parts). The Interactions API requires a string `result` on function_result steps — stringify multimodal tool output before returning it from your tool."
288
+ );
289
+ }
290
+ function messageToContentBlocks(msg) {
291
+ const blocks = [];
292
+ if (Array.isArray(msg.content)) {
293
+ for (const part of msg.content) {
294
+ blocks.push(contentPartToBlock(part));
295
+ }
296
+ } else if (typeof msg.content === "string" && msg.content && msg.role !== "tool") {
297
+ blocks.push({ type: "text", text: msg.content });
298
+ }
299
+ return blocks;
300
+ }
301
+ function messagesAfterLastAssistant(messages) {
302
+ for (let i = messages.length - 1; i >= 0; i--) {
303
+ if (messages[i]?.role === "assistant") {
304
+ return messages.slice(i + 1);
305
+ }
306
+ }
307
+ return messages;
308
+ }
309
+ function safeParseToolArguments(raw, logger) {
310
+ if (!raw) return {};
311
+ try {
312
+ const parsed = JSON.parse(raw);
313
+ return parsed && typeof parsed === "object" ? parsed : {};
314
+ } catch (error) {
315
+ logger.errors(
316
+ "gemini-text-interactions.safeParseToolArguments parse failed",
317
+ {
318
+ error,
319
+ raw,
320
+ source: "gemini-text-interactions.chatStream"
321
+ }
322
+ );
323
+ return {};
324
+ }
325
+ }
326
+ const IMAGE_MIME_TYPES = [
327
+ "image/png",
328
+ "image/jpeg",
329
+ "image/webp",
330
+ "image/heic",
331
+ "image/heif"
332
+ ];
333
+ const AUDIO_MIME_TYPES = [
334
+ "audio/wav",
335
+ "audio/mp3",
336
+ "audio/aiff",
337
+ "audio/aac",
338
+ "audio/ogg",
339
+ "audio/flac"
340
+ ];
341
+ const VIDEO_MIME_TYPES = [
342
+ "video/mp4",
343
+ "video/mpeg",
344
+ "video/mpg",
345
+ "video/mov",
346
+ "video/avi",
347
+ "video/x-flv",
348
+ "video/webm",
349
+ "video/wmv",
350
+ "video/3gpp"
351
+ ];
352
+ const DOCUMENT_MIME_TYPES = [
353
+ "application/pdf"
354
+ ];
355
+ function validateMime(allowed, value, kind) {
356
+ if (value === void 0) return void 0;
357
+ if (allowed.includes(value)) {
358
+ return value;
359
+ }
360
+ throw new Error(
361
+ `Unsupported ${kind} mime type "${value}" for the Gemini Interactions API. Allowed: ${allowed.join(", ")}.`
362
+ );
363
+ }
364
+ function contentPartToBlock(part) {
365
+ if (part.type === "text") {
366
+ return { type: "text", text: part.content };
367
+ }
368
+ const isData = part.source.type === "data";
369
+ switch (part.type) {
370
+ case "image": {
371
+ const mime_type = validateMime(
372
+ IMAGE_MIME_TYPES,
373
+ part.source.mimeType,
374
+ "image"
375
+ );
376
+ return isData ? { type: "image", data: part.source.value, mime_type } : { type: "image", uri: part.source.value, mime_type };
377
+ }
378
+ case "audio": {
379
+ const mime_type = validateMime(
380
+ AUDIO_MIME_TYPES,
381
+ part.source.mimeType,
382
+ "audio"
383
+ );
384
+ return isData ? { type: "audio", data: part.source.value, mime_type } : { type: "audio", uri: part.source.value, mime_type };
385
+ }
386
+ case "video": {
387
+ const mime_type = validateMime(
388
+ VIDEO_MIME_TYPES,
389
+ part.source.mimeType,
390
+ "video"
391
+ );
392
+ return isData ? { type: "video", data: part.source.value, mime_type } : { type: "video", uri: part.source.value, mime_type };
393
+ }
394
+ case "document": {
395
+ const mime_type = validateMime(
396
+ DOCUMENT_MIME_TYPES,
397
+ part.source.mimeType,
398
+ "document"
399
+ );
400
+ return isData ? { type: "document", data: part.source.value, mime_type } : { type: "document", uri: part.source.value, mime_type };
401
+ }
402
+ }
403
+ }
404
+ function convertToolsToInteractionsFormat(tools) {
405
+ if (!tools || tools.length === 0) return void 0;
406
+ const result = [];
407
+ for (const tool of tools) {
408
+ switch (tool.name) {
409
+ case "google_search": {
410
+ const metadata = tool.metadata ?? {};
411
+ result.push({
412
+ type: "google_search",
413
+ ...metadata.search_types ? { search_types: metadata.search_types } : {}
414
+ });
415
+ break;
416
+ }
417
+ case "code_execution": {
418
+ result.push({ type: "code_execution" });
419
+ break;
420
+ }
421
+ case "url_context": {
422
+ result.push({ type: "url_context" });
423
+ break;
424
+ }
425
+ case "file_search": {
426
+ const metadata = tool.metadata ?? {};
427
+ result.push({
428
+ type: "file_search",
429
+ ...metadata.fileSearchStoreNames ? { file_search_store_names: metadata.fileSearchStoreNames } : {},
430
+ ...metadata.topK !== void 0 ? { top_k: metadata.topK } : {},
431
+ ...metadata.metadataFilter !== void 0 ? { metadata_filter: metadata.metadataFilter } : {}
432
+ });
433
+ break;
434
+ }
435
+ case "computer_use": {
436
+ const metadata = tool.metadata ?? {};
437
+ if (metadata.environment && metadata.environment !== "browser") {
438
+ throw new Error(
439
+ `computer_use environment "${metadata.environment}" is not supported on the Gemini Interactions API. Only "browser" is accepted.`
440
+ );
441
+ }
442
+ result.push({
443
+ type: "computer_use",
444
+ ...metadata.environment ? { environment: metadata.environment } : {},
445
+ ...metadata.excludedPredefinedFunctions ? {
446
+ excludedPredefinedFunctions: metadata.excludedPredefinedFunctions
447
+ } : {}
448
+ });
449
+ break;
450
+ }
451
+ case "google_search_retrieval":
452
+ throw new Error(
453
+ "`google_search_retrieval` is not supported on the Gemini Interactions API. Use `googleSearchTool()` (`google_search`) with `geminiTextInteractions()`, or call `geminiText()` for the legacy retrieval tool."
454
+ );
455
+ case "google_maps":
456
+ throw new Error(
457
+ "`google_maps` is not yet supported on the Gemini Interactions API. Use `geminiText()` for Google Maps grounding."
458
+ );
459
+ case "mcp_server":
460
+ throw new Error(
461
+ "`mcp_server` is not yet supported on the `geminiTextInteractions()` adapter."
462
+ );
463
+ default: {
464
+ if (!tool.description) {
465
+ throw new Error(
466
+ `Tool ${tool.name} requires a description for the Gemini Interactions adapter`
467
+ );
468
+ }
469
+ result.push({
470
+ type: "function",
471
+ name: tool.name,
472
+ description: tool.description,
473
+ parameters: sanitizeToolParameters(
474
+ tool.inputSchema ?? { type: "object", properties: {} }
475
+ )
476
+ });
477
+ }
478
+ }
479
+ }
480
+ return result;
481
+ }
482
+ function statusToFinishReason(status, sawFunctionCall) {
483
+ if (status === "requires_action") return "tool_calls";
484
+ if (status === "incomplete") return "length";
485
+ if (sawFunctionCall) return "tool_calls";
486
+ return "stop";
487
+ }
488
+ function statusIsError(status) {
489
+ return status === "failed" || status === "cancelled";
490
+ }
491
+ async function* translateInteractionEvents(stream, model, runId, threadId, parentRunId, timestamp, adapterName, logger) {
492
+ const messageId = generateId(adapterName);
493
+ let hasEmittedRunStarted = false;
494
+ let hasEmittedTextMessageStart = false;
495
+ let textAccumulated = "";
496
+ let interactionId;
497
+ let sawFunctionCall = false;
498
+ const toolCalls = /* @__PURE__ */ new Map();
499
+ let nextToolIndex = 0;
500
+ let thinkingStepId = null;
501
+ let thinkingAccumulated = "";
502
+ let reasoningMessageId = null;
503
+ let hasClosedReasoning = false;
504
+ const closeReasoningIfNeeded = function* () {
505
+ if (reasoningMessageId && !hasClosedReasoning) {
506
+ hasClosedReasoning = true;
507
+ yield {
508
+ type: EventType.REASONING_MESSAGE_END,
509
+ messageId: reasoningMessageId,
510
+ model,
511
+ timestamp
512
+ };
513
+ yield {
514
+ type: EventType.REASONING_END,
515
+ messageId: reasoningMessageId,
516
+ model,
517
+ timestamp
518
+ };
519
+ thinkingStepId = null;
520
+ reasoningMessageId = null;
521
+ hasClosedReasoning = false;
522
+ }
523
+ };
524
+ const closeOpenState = function* () {
525
+ yield* closeReasoningIfNeeded();
526
+ for (const [toolCallId, state] of toolCalls) {
527
+ if (state.ended) continue;
528
+ state.ended = true;
529
+ yield {
530
+ type: EventType.TOOL_CALL_END,
531
+ toolCallId,
532
+ toolName: state.name,
533
+ model,
534
+ timestamp,
535
+ input: state.args
536
+ };
537
+ }
538
+ if (hasEmittedTextMessageStart) {
539
+ hasEmittedTextMessageStart = false;
540
+ yield {
541
+ type: EventType.TEXT_MESSAGE_END,
542
+ messageId,
543
+ model,
544
+ timestamp
545
+ };
546
+ }
547
+ };
548
+ const emitRunStartedIfNeeded = function* () {
549
+ if (!hasEmittedRunStarted) {
550
+ hasEmittedRunStarted = true;
551
+ yield {
552
+ type: EventType.RUN_STARTED,
553
+ runId,
554
+ threadId,
555
+ model,
556
+ timestamp,
557
+ parentRunId
558
+ };
559
+ }
560
+ };
561
+ for await (const event of stream) {
562
+ logger.provider(`provider=gemini-text-interactions`, { event });
563
+ switch (event.event_type) {
564
+ case "interaction.start": {
565
+ interactionId = event.interaction.id;
566
+ yield* emitRunStartedIfNeeded();
567
+ break;
568
+ }
569
+ case "content.start": {
570
+ yield* emitRunStartedIfNeeded();
571
+ break;
572
+ }
573
+ case "content.delta": {
574
+ yield* emitRunStartedIfNeeded();
575
+ const delta = event.delta;
576
+ switch (delta.type) {
577
+ case "text": {
578
+ yield* closeReasoningIfNeeded();
579
+ if (!hasEmittedTextMessageStart) {
580
+ hasEmittedTextMessageStart = true;
581
+ yield {
582
+ type: EventType.TEXT_MESSAGE_START,
583
+ messageId,
584
+ model,
585
+ timestamp,
586
+ role: "assistant"
587
+ };
588
+ }
589
+ textAccumulated += delta.text;
590
+ yield {
591
+ type: EventType.TEXT_MESSAGE_CONTENT,
592
+ messageId,
593
+ model,
594
+ timestamp,
595
+ delta: delta.text,
596
+ content: textAccumulated
597
+ };
598
+ break;
599
+ }
600
+ case "function_call": {
601
+ yield* closeReasoningIfNeeded();
602
+ sawFunctionCall = true;
603
+ const toolCallId = delta.id;
604
+ const deltaArgs = typeof delta.arguments === "string" ? safeParseToolArguments(delta.arguments, logger) : delta.arguments;
605
+ let state = toolCalls.get(toolCallId);
606
+ if (!state) {
607
+ state = {
608
+ name: delta.name,
609
+ args: { ...deltaArgs },
610
+ index: nextToolIndex++,
611
+ started: false,
612
+ ended: false
613
+ };
614
+ toolCalls.set(toolCallId, state);
615
+ } else {
616
+ state.args = { ...state.args, ...deltaArgs };
617
+ if (delta.name) state.name = delta.name;
618
+ }
619
+ if (!state.started) {
620
+ state.started = true;
621
+ yield {
622
+ type: EventType.TOOL_CALL_START,
623
+ toolCallId,
624
+ toolCallName: state.name,
625
+ toolName: state.name,
626
+ model,
627
+ timestamp,
628
+ index: state.index
629
+ };
630
+ }
631
+ yield {
632
+ type: EventType.TOOL_CALL_ARGS,
633
+ toolCallId,
634
+ model,
635
+ timestamp,
636
+ delta: JSON.stringify(deltaArgs),
637
+ args: JSON.stringify(state.args)
638
+ };
639
+ break;
640
+ }
641
+ case "google_search_call": {
642
+ yield* closeReasoningIfNeeded();
643
+ yield {
644
+ type: EventType.CUSTOM,
645
+ name: "gemini.googleSearchCall",
646
+ value: delta,
647
+ model,
648
+ timestamp
649
+ };
650
+ break;
651
+ }
652
+ case "google_search_result": {
653
+ yield* closeReasoningIfNeeded();
654
+ yield {
655
+ type: EventType.CUSTOM,
656
+ name: "gemini.googleSearchResult",
657
+ value: delta,
658
+ model,
659
+ timestamp
660
+ };
661
+ break;
662
+ }
663
+ case "code_execution_call": {
664
+ yield* closeReasoningIfNeeded();
665
+ yield {
666
+ type: EventType.CUSTOM,
667
+ name: "gemini.codeExecutionCall",
668
+ value: delta,
669
+ model,
670
+ timestamp
671
+ };
672
+ break;
673
+ }
674
+ case "code_execution_result": {
675
+ yield* closeReasoningIfNeeded();
676
+ yield {
677
+ type: EventType.CUSTOM,
678
+ name: "gemini.codeExecutionResult",
679
+ value: delta,
680
+ model,
681
+ timestamp
682
+ };
683
+ break;
684
+ }
685
+ case "url_context_call": {
686
+ yield* closeReasoningIfNeeded();
687
+ yield {
688
+ type: EventType.CUSTOM,
689
+ name: "gemini.urlContextCall",
690
+ value: delta,
691
+ model,
692
+ timestamp
693
+ };
694
+ break;
695
+ }
696
+ case "url_context_result": {
697
+ yield* closeReasoningIfNeeded();
698
+ yield {
699
+ type: EventType.CUSTOM,
700
+ name: "gemini.urlContextResult",
701
+ value: delta,
702
+ model,
703
+ timestamp
704
+ };
705
+ break;
706
+ }
707
+ case "file_search_call": {
708
+ yield* closeReasoningIfNeeded();
709
+ yield {
710
+ type: EventType.CUSTOM,
711
+ name: "gemini.fileSearchCall",
712
+ value: delta,
713
+ model,
714
+ timestamp
715
+ };
716
+ break;
717
+ }
718
+ case "file_search_result": {
719
+ yield* closeReasoningIfNeeded();
720
+ yield {
721
+ type: EventType.CUSTOM,
722
+ name: "gemini.fileSearchResult",
723
+ value: delta,
724
+ model,
725
+ timestamp
726
+ };
727
+ break;
728
+ }
729
+ case "thought_summary": {
730
+ const thoughtText = delta.content && "text" in delta.content ? delta.content.text : "";
731
+ if (!thoughtText) break;
732
+ if (thinkingStepId === null || reasoningMessageId === null) {
733
+ thinkingStepId = generateId(adapterName);
734
+ reasoningMessageId = generateId(adapterName);
735
+ yield {
736
+ type: EventType.REASONING_START,
737
+ messageId: reasoningMessageId,
738
+ model,
739
+ timestamp
740
+ };
741
+ yield {
742
+ type: EventType.REASONING_MESSAGE_START,
743
+ messageId: reasoningMessageId,
744
+ role: "reasoning",
745
+ model,
746
+ timestamp
747
+ };
748
+ yield {
749
+ type: EventType.STEP_STARTED,
750
+ stepName: thinkingStepId,
751
+ stepId: thinkingStepId,
752
+ model,
753
+ timestamp,
754
+ stepType: "thinking"
755
+ };
756
+ }
757
+ thinkingAccumulated += thoughtText;
758
+ yield {
759
+ type: EventType.REASONING_MESSAGE_CONTENT,
760
+ messageId: reasoningMessageId,
761
+ delta: thoughtText,
762
+ model,
763
+ timestamp
764
+ };
765
+ yield {
766
+ type: EventType.STEP_FINISHED,
767
+ stepName: thinkingStepId,
768
+ stepId: thinkingStepId,
769
+ model,
770
+ timestamp,
771
+ delta: thoughtText,
772
+ content: thinkingAccumulated
773
+ };
774
+ break;
775
+ }
776
+ // The following delta types are valid per the SDK type union
777
+ // but aren't yet translated by this adapter (output modalities
778
+ // text-only adapter shouldn't see, response-side function_result
779
+ // / mcp_server_*, thought_signature). Falling through to the
780
+ // observability default so SDK drift is visible.
781
+ case "image":
782
+ case "audio":
783
+ case "video":
784
+ case "document":
785
+ case "function_result":
786
+ case "mcp_server_tool_call":
787
+ case "mcp_server_tool_result":
788
+ case "thought_signature":
789
+ default:
790
+ logger.provider(
791
+ `gemini-text-interactions unhandled content.delta type`,
792
+ { delta }
793
+ );
794
+ break;
795
+ }
796
+ break;
797
+ }
798
+ case "content.stop":
799
+ case "interaction.status_update": {
800
+ break;
801
+ }
802
+ case "interaction.complete": {
803
+ if (event.interaction.id) {
804
+ interactionId = event.interaction.id;
805
+ }
806
+ yield* closeOpenState();
807
+ const status = event.interaction.status;
808
+ if (statusIsError(status)) {
809
+ const message = `Gemini Interactions ${status}: the interaction ended without a usable response.`;
810
+ logger.errors(
811
+ "gemini-text-interactions.translateInteractionEvents non-success status",
812
+ {
813
+ source: "gemini-text-interactions.chatStream",
814
+ status,
815
+ interactionId
816
+ }
817
+ );
818
+ yield {
819
+ type: EventType.RUN_ERROR,
820
+ runId,
821
+ model,
822
+ timestamp,
823
+ message,
824
+ code: status,
825
+ error: { message, code: status }
826
+ };
827
+ return;
828
+ }
829
+ const usage = event.interaction.usage;
830
+ const finishReason = statusToFinishReason(status, sawFunctionCall);
831
+ if (interactionId) {
832
+ yield {
833
+ type: EventType.CUSTOM,
834
+ name: "gemini.interactionId",
835
+ value: { interactionId },
836
+ model,
837
+ timestamp
838
+ };
839
+ }
840
+ yield {
841
+ type: EventType.RUN_FINISHED,
842
+ runId,
843
+ threadId,
844
+ model,
845
+ timestamp,
846
+ finishReason,
847
+ usage: usage ? {
848
+ promptTokens: usage.total_input_tokens ?? 0,
849
+ completionTokens: usage.total_output_tokens ?? 0,
850
+ totalTokens: usage.total_tokens ?? 0
851
+ } : void 0
852
+ };
853
+ return;
854
+ }
855
+ case "error": {
856
+ yield* closeOpenState();
857
+ const rawMessage = event.error?.message;
858
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : `Gemini Interactions error (no message): ${JSON.stringify(event.error ?? {})}`;
859
+ const rawCode = event.error?.code;
860
+ const code = typeof rawCode === "string" || typeof rawCode === "number" ? String(rawCode) : void 0;
861
+ yield {
862
+ type: EventType.RUN_ERROR,
863
+ runId,
864
+ model,
865
+ timestamp,
866
+ message,
867
+ code,
868
+ error: { message, code }
869
+ };
870
+ return;
871
+ }
872
+ default:
873
+ logger.provider(`gemini-text-interactions unhandled event_type`, {
874
+ event
875
+ });
876
+ break;
877
+ }
878
+ }
879
+ yield* closeOpenState();
880
+ }
881
+ function extractTextFromInteraction(interaction) {
882
+ let text = "";
883
+ for (const output of interaction.outputs ?? []) {
884
+ if (output.type === "text") {
885
+ text += output.text;
886
+ }
887
+ }
888
+ return text;
889
+ }
890
+ function sanitizeToolParameters(schema) {
891
+ if (!schema || typeof schema !== "object") return schema;
892
+ if (Array.isArray(schema)) return schema.map(sanitizeToolParameters);
893
+ const out = {};
894
+ for (const [key, value] of Object.entries(schema)) {
895
+ if (key === "required" && Array.isArray(value) && value.length === 0) {
896
+ continue;
897
+ }
898
+ out[key] = sanitizeToolParameters(value);
899
+ }
900
+ return out;
901
+ }
902
+ export {
903
+ GeminiTextInteractionsAdapter,
904
+ createGeminiTextInteractions,
905
+ geminiTextInteractions
906
+ };
907
+ //# sourceMappingURL=adapter.js.map