@tanstack/ai-gemini 0.32.1 → 0.33.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/experimental/text-interactions/adapter.ts"],"sourcesContent":["import { EventType } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { parse as parsePartialJSON } from 'partial-json'\nimport {\n createGeminiClient,\n generateId,\n getGeminiApiKeyFromEnv,\n} from '../../utils/client'\nimport {\n getGeminiProviderToolKind,\n getGeminiProviderToolMetadata,\n} from '../../tools/gemini-provider-tool'\nimport { assertUniqueToolNames } from '@tanstack/ai/adapter-internals'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n GeminiChatModelProviderOptionsByName,\n GeminiChatModelToolCapabilitiesByName,\n GeminiModelInputModalitiesByName,\n GeminiModels,\n} from '../../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { GoogleGenAI, Interactions } from '@google/genai'\nimport type {\n ContentPart,\n Modality,\n ModelMessage,\n AdapterYieldChunk,\n TextOptions,\n Tool,\n} from '@tanstack/ai'\n\nimport type {\n GeminiInteractionsCustomEvent,\n GeminiInteractionsCustomEventValue,\n GeminiInteractionsStream,\n} from './events'\nimport type { ExternalTextInteractionsProviderOptions } from './provider-options'\nimport type { GeminiMessageMetadataByModality } from '../../message-types'\nimport type { GeminiClientConfig } from '../../utils/client'\n\ntype Interaction = Interactions.Interaction\ntype InteractionSSEEvent = Interactions.InteractionSSEEvent\n\nexport type GeminiTextInteractionsConfig = GeminiClientConfig\n\nexport type GeminiTextInteractionsProviderOptions =\n ExternalTextInteractionsProviderOptions\n\ntype InteractionsTool = NonNullable<\n Interactions.CreateModelInteractionParamsStreaming['tools']\n>[number]\n\ntype ContentBlock = Interactions.Content\n\n// The Interactions API takes `input` as a list of *Steps* (not a list of\n// content blocks, and not a list of `Turn`s — the SDK's type union is\n// misleading on both counts). The live API enforces the Step envelope —\n// raw content arrays produce `invalid_request` / \"value at top-level\n// must be a list\". The wire discriminator is snake_case\n// (`user_input` / `function_result`); see\n// https://ai.google.dev/api/interactions-api for the full Step union.\ntype UserInputStep = {\n type: 'user_input'\n content: Array<ContentBlock>\n}\ntype FunctionResultStep = {\n type: 'function_result'\n call_id: string\n name?: string\n result: string\n}\ntype InteractionsStep = UserInputStep | FunctionResultStep\ntype InteractionsRequestInput = Array<InteractionsStep>\n\n// Concrete wire shape we send to `client.interactions.create`. The SDK's\n// own param union types `input` as `string | Content[] | Turn[] | ...`\n// which is wrong for the live API (see the InteractionsRequestInput\n// comment above), so we type `input` ourselves and cast just once at the\n// SDK boundary instead of casting every field through.\ntype GeminiInteractionsRequestBody = Omit<\n Interactions.CreateModelInteractionParamsStreaming,\n 'input' | 'stream'\n> & {\n input: InteractionsRequestInput\n stream?: boolean\n}\n\ntype ToolCallState = {\n name: string\n // Accumulated args as a parsed object. Kept here in object form so a\n // garbled delta can't corrupt previously-merged fragments (the prior\n // string-then-reparse pipeline replaced the whole accumulator on any\n // parse failure). Stringified only when emitting AG-UI events.\n args: Record<string, unknown>\n index: number\n started: boolean\n ended: boolean\n}\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model. Reuses the chat-model\n * options map from `model-meta.ts` so a model's allowed thinking levels are\n * declared once: the Interactions API takes the same levels as\n * `generateContent` but lowercased (`low`, not `LOW`). Models whose chat\n * options carry no `thinkingConfig` resolve to `never`, so `thinking_level`\n * can't be set on them. Everything else falls through to the flat SDK shape.\n */\ntype InteractionsThinkingLevel<TModel> =\n TModel extends keyof GeminiChatModelProviderOptionsByName\n ? GeminiChatModelProviderOptionsByName[TModel] extends {\n thinkingConfig?: { thinkingLevel?: infer L extends string }\n }\n ? Lowercase<L>\n : never\n : never\n\ntype ResolveProviderOptions<TModel extends GeminiModels> = Omit<\n GeminiTextInteractionsProviderOptions,\n 'generation_config'\n> & {\n generation_config?: Omit<\n NonNullable<GeminiTextInteractionsProviderOptions['generation_config']>,\n 'thinking_level'\n > & { thinking_level?: InteractionsThinkingLevel<TModel> }\n}\n\n/**\n * Resolve input modalities for a specific model. Reuses the chat-model\n * modality map from `model-meta.ts`: passing a `document` content block\n * to a model that doesn't support it is a compile error, matching the\n * sibling `GeminiTextAdapter`.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof GeminiModelInputModalitiesByName\n ? GeminiModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'audio', 'video', 'document']\n\n/**\n * Resolve tool capabilities for a specific model. Reuses the chat-model\n * capability map: `google_maps` / `google_search_retrieval` are rejected at\n * runtime by `convertToolsToInteractionsFormat`, but per-model gating happens\n * here at compile time.\n */\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof GeminiChatModelToolCapabilitiesByName\n ? NonNullable<GeminiChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n/**\n * Tree-shakeable adapter for Gemini's stateful Interactions API. Routes\n * through `client.interactions.create` and surfaces the server-assigned\n * `interactionId` via an AG-UI `CUSTOM` event with\n * `name: 'gemini.interactionId'` emitted just before `RUN_FINISHED`; pass\n * that id back on the next turn via `modelOptions.previous_interaction_id`\n * to continue the conversation without resending history.\n *\n * The Interactions API does NOT support stateless multi-turn replay —\n * passing more than one message in `messages` without a\n * `previous_interaction_id` throws. For a chat UI that maintains local\n * history (e.g. `useChat`), see the \"Wiring with `useChat`\" section of\n * `docs/adapters/gemini.md` for the canonical client/server pattern.\n *\n * Supports user-defined function tools and the built-in tools\n * `google_search`, `code_execution`, `url_context`, `file_search`, and\n * `computer_use`. Built-in tool *activity* for the four search/exec\n * variants is surfaced via `CUSTOM` events\n * (`gemini.googleSearchCall` / `gemini.googleSearchResult` and the\n * corresponding per-tool variants) carrying the raw Interactions delta;\n * see {@link GeminiInteractionsCustomEvent}. `computer_use` is accepted\n * in the request but the Interactions API does not currently stream\n * per-delta CUSTOM events for it. The `google_search_retrieval` and\n * `google_maps` provider-tool factories are not supported on this adapter and\n * throw a targeted error. There is no Gemini `mcp_server` factory, so a tool\n * merely *named* `mcp_server` is an ordinary function and is sent as a function\n * declaration like any other.\n *\n * @experimental Interactions API is in Beta per Google; shapes may change.\n * @see https://ai.google.dev/gemini-api/docs/interactions\n */\nexport class GeminiTextInteractionsAdapter<\n TModel extends GeminiModels,\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n GeminiMessageMetadataByModality,\n TToolCapabilities\n> {\n override readonly kind = 'text' as const\n override readonly name = 'gemini-text-interactions' as const\n\n private readonly client: GoogleGenAI\n // Tracks the most recent server-assigned interaction id per threadId\n // so the adapter can chain follow-up calls on the same thread without\n // the caller having to thread the id manually. Two callers rely on\n // this:\n // 1. The agent loop's tool-call iterations (each iteration is a new\n // `chatStream` call with accumulated tool messages).\n // 2. The agentic-structured composition: a `chatStream` run followed\n // by `structuredOutput` on the accumulated messages.\n // Cross-request chaining is the caller's job via\n // `modelOptions.previous_interaction_id`. To keep stale ids from\n // chaining a brand-new turn, `chatStream` evicts at the START when\n // the caller signals fresh-turn intent (no caller-provided id AND a\n // single user message — anything else is a follow-up). Errors evict\n // immediately so a failed turn never chains into the next one.\n private readonly interactionIdByThread = new Map<string, string>()\n\n constructor(config: GeminiTextInteractionsConfig, model: TModel) {\n super({}, model)\n this.client = createGeminiClient(config)\n }\n\n async *chatStream(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const runId = options.runId ?? generateId(this.name)\n const threadId = options.threadId ?? generateId(this.name)\n const timestamp = Date.now()\n const { logger } = options\n\n // Fresh-turn intent: caller didn't thread an id AND only a single\n // user message is queued. Drop any stale captured id so we don't\n // silently chain off a prior turn the caller doesn't know about.\n // Multi-message inputs are follow-ups (agent-loop iteration or\n // structuredOutput composition) and keep the Map entry.\n if (\n !options.modelOptions?.previous_interaction_id &&\n options.messages.length === 1 &&\n options.messages[0]?.role === 'user'\n ) {\n this.interactionIdByThread.delete(threadId)\n }\n\n // Resolve `previous_interaction_id`. Caller-provided wins; otherwise\n // fall back to the id we captured during a prior iteration of this\n // same agent-loop run (matched by threadId).\n const effectivePreviousInteractionId =\n options.modelOptions?.previous_interaction_id ??\n this.interactionIdByThread.get(threadId)\n\n let sawTerminalEvent = false\n // Sentinel for the `.return()` abandonment path. Set to `true` only at\n // the bottom of the `try` block — so a consumer-initiated close (via\n // upstream `break` or abort) leaves it `false`, distinguishing\n // abandonment from normal completion. This is the only signal that\n // catches abandonment AFTER a `RUN_FINISHED(tool_calls)`, where\n // `sawTerminalEvent` is `true` but the in-loop deliberately kept the\n // map entry for an agent-loop iteration that will now never run.\n let completedTryBlock = false\n try {\n const request = buildInteractionsRequest({\n ...options,\n modelOptions: {\n ...options.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const stream = (await this.client.interactions.create(\n { ...request, stream: true } as GeminiInteractionsRequestBody &\n Parameters<typeof this.client.interactions.create>[0],\n { signal: abortSignalFromOptions(options) },\n )) as AsyncIterable<InteractionSSEEvent>\n\n for await (const chunk of translateInteractionEvents(\n stream,\n options.model,\n runId,\n threadId,\n options.parentRunId,\n timestamp,\n this.name,\n logger,\n )) {\n // Capture the server-assigned id so the next agent-loop\n // iteration on this thread can chain off it. The CUSTOM event\n // is also yielded downstream as usual — callers consume it via\n // `onCustomEvent` for cross-request chaining.\n //\n // The yield type can't be narrowed to GeminiInteractionsStream\n // here without fighting zod-passthrough variance (StreamChunk's\n // CustomEvent variant carries `[k: string]: unknown`), so we\n // narrow via the literal `name` and trust the typed\n // construction inside `translateInteractionEvents`.\n if (\n chunk.type === EventType.CUSTOM &&\n chunk.name === 'gemini.interactionId'\n ) {\n const value =\n chunk.value as GeminiInteractionsCustomEventValue<'gemini.interactionId'>\n this.interactionIdByThread.set(threadId, value.interactionId)\n }\n if (chunk.type === EventType.RUN_FINISHED) {\n sawTerminalEvent = true\n // Keep the captured id for follow-ups (next agent-loop\n // iteration OR a structuredOutput call composing this turn).\n // The next *fresh* chatStream call evicts at the top via the\n // fresh-turn guard.\n } else if (chunk.type === EventType.RUN_ERROR) {\n sawTerminalEvent = true\n this.interactionIdByThread.delete(threadId)\n }\n yield chunk\n }\n\n if (!sawTerminalEvent) {\n // SDK stream ended without either `interaction.complete` or\n // `error` — surface the truncation rather than silently leaving\n // downstream consumers waiting on a `RUN_FINISHED` that will\n // never come.\n this.interactionIdByThread.delete(threadId)\n const message =\n 'Gemini Interactions stream ended without a terminal event (no interaction.complete or error)'\n logger.errors('gemini-text-interactions.chatStream truncated', {\n source: 'gemini-text-interactions.chatStream',\n runId,\n threadId,\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n }\n completedTryBlock = true\n } catch (error) {\n this.interactionIdByThread.delete(threadId)\n const message =\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during the interactions stream.'\n logger.errors('gemini-text-interactions.chatStream fatal', {\n error,\n source: 'gemini-text-interactions.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n } finally {\n // Abandonment cleanup — consumer `.return()` (upstream `break` /\n // abort) bypasses both the truncation guard and the catch handler.\n // `completedTryBlock` is the sentinel that distinguishes natural\n // completion from abandonment; on abandonment we evict so a stale\n // id from a half-finished turn can't chain into a follow-up. The\n // catch handler also lands here with the flag false; its explicit\n // delete is harmless to repeat.\n if (!completedTryBlock) {\n this.interactionIdByThread.delete(threadId)\n }\n }\n }\n\n async structuredOutput(\n options: StructuredOutputOptions<GeminiTextInteractionsProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n const threadId = chatOptions.threadId\n\n // Mirror the chatStream fallback: the agentic-structured flow runs\n // the chat loop first and then calls structuredOutput with the\n // accumulated `messages`. If any tool ran during the loop, the\n // messages include assistant/tool turns; without a chained\n // previous_interaction_id those would throw \"cannot send prior\n // conversation history on a fresh interaction\".\n const effectivePreviousInteractionId =\n chatOptions.modelOptions?.previous_interaction_id ??\n (threadId ? this.interactionIdByThread.get(threadId) : undefined)\n\n const baseRequest = buildInteractionsRequest({\n ...chatOptions,\n modelOptions: {\n ...chatOptions.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n\n // SDK 2.x: `response_mime_type` has been removed and `response_format`\n // is now polymorphic — each entry has a `type` discriminator and the\n // mime type lives inside the entry. See:\n // https://ai.google.dev/gemini-api/docs/interactions-breaking-changes-may-2026\n const request: GeminiInteractionsRequestBody = {\n ...baseRequest,\n response_format: {\n type: 'text',\n mime_type: 'application/json',\n schema: outputSchema,\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const result = (await this.client.interactions.create(\n request as Parameters<typeof this.client.interactions.create>[0],\n { signal: abortSignalFromOptions(chatOptions) },\n )) as Interaction\n\n const rawText = extractTextFromInteraction(result)\n\n if (!rawText) {\n throw new Error(\n `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.`,\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(jsonContentParseError(rawText, 'structured output'))\n }\n\n return { data: parsed, rawText }\n } catch (error) {\n logger.errors('gemini-text-interactions.structuredOutput fatal', {\n error,\n source: 'gemini-text-interactions.structuredOutput',\n })\n // Preserve the original error as `cause` so the stack trace and any\n // SDK-attached status/code/headers survive for Sentry dedup.\n throw new Error(\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during structured output generation.',\n { cause: error },\n )\n }\n }\n\n async *structuredOutputStream(\n options: StructuredOutputOptions<GeminiTextInteractionsProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const { chatOptions, outputSchema } = options\n const runId = chatOptions.runId ?? generateId(this.name)\n const threadId = chatOptions.threadId ?? generateId(this.name)\n const timestamp = Date.now()\n const effectivePreviousInteractionId =\n chatOptions.modelOptions?.previous_interaction_id ??\n this.interactionIdByThread.get(threadId)\n const baseRequest = buildInteractionsRequest({\n ...chatOptions,\n modelOptions: {\n ...chatOptions.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n const request: GeminiInteractionsRequestBody = {\n ...baseRequest,\n stream: true,\n response_format: {\n type: 'text',\n mime_type: 'application/json',\n schema: outputSchema,\n },\n }\n\n try {\n chatOptions.logger.request(\n `activity=structuredOutputStream provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length}`,\n { provider: this.name, model: this.model, request },\n )\n const stream = (await this.client.interactions.create(\n request as GeminiInteractionsRequestBody &\n Parameters<typeof this.client.interactions.create>[0],\n { signal: abortSignalFromOptions(chatOptions) },\n )) as AsyncIterable<InteractionSSEEvent>\n\n let rawText = ''\n let finished:\n | Extract<AdapterYieldChunk, { type: typeof EventType.RUN_FINISHED }>\n | undefined\n let failed = false\n for await (const chunk of translateInteractionEvents(\n stream,\n chatOptions.model,\n runId,\n threadId,\n chatOptions.parentRunId,\n timestamp,\n this.name,\n chatOptions.logger,\n )) {\n if (chunk.type === EventType.TEXT_MESSAGE_CONTENT)\n rawText += chunk.delta\n if (\n chunk.type === EventType.CUSTOM &&\n chunk.name === 'gemini.interactionId'\n ) {\n const value =\n chunk.value as GeminiInteractionsCustomEventValue<'gemini.interactionId'>\n this.interactionIdByThread.set(threadId, value.interactionId)\n }\n if (chunk.type === EventType.RUN_ERROR) failed = true\n if (chunk.type === EventType.RUN_FINISHED) finished = chunk\n else yield chunk\n }\n\n if (failed) return\n if (!finished) {\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n 'Gemini Interactions structured-output stream ended without a terminal event',\n 'truncated-stream',\n )\n return\n }\n if (!rawText) {\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n 'Gemini Interactions structured-output stream contained no content',\n 'empty-response',\n )\n return\n }\n let object: unknown\n try {\n object = JSON.parse(rawText)\n } catch {\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n jsonContentParseError(\n rawText,\n 'Gemini Interactions structured-output stream',\n ),\n 'parse-error',\n )\n return\n }\n yield {\n type: EventType.CUSTOM,\n name: 'structured-output.complete',\n value: { object, raw: rawText },\n model: chatOptions.model,\n timestamp: Date.now(),\n }\n yield { ...finished, timestamp: Date.now() }\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during structured output streaming.'\n chatOptions.logger.errors(\n 'gemini-text-interactions.structuredOutputStream fatal',\n { error, source: 'gemini-text-interactions.structuredOutputStream' },\n )\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n message,\n 'provider-error',\n )\n }\n }\n}\n\nfunction abortSignalFromOptions(\n options: Pick<\n TextOptions<GeminiTextInteractionsProviderOptions>,\n 'request' | 'abortController'\n >,\n) {\n return options.request?.signal ?? options.abortController?.signal\n}\n\nfunction jsonContentParseError(rawText: string, label: string) {\n const snippet = rawText.slice(0, 200)\n const ellipsis = rawText.length > 200 ? '...' : ''\n return `Failed to parse ${label} as JSON. Content: ${snippet}${ellipsis}`\n}\n\nfunction interactionsStructuredStreamError(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n runId: string,\n message: string,\n code: string,\n): Extract<AdapterYieldChunk, { type: typeof EventType.RUN_ERROR }> {\n return {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp: Date.now(),\n message,\n code,\n error: { message, code },\n }\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function createGeminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n apiKey: string,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n return new GeminiTextInteractionsAdapter({ apiKey, ...config }, model)\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function geminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n const apiKey = getGeminiApiKeyFromEnv()\n return createGeminiTextInteractions(model, apiKey, config)\n}\n\nfunction buildInteractionsRequest(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n): GeminiInteractionsRequestBody {\n const modelOpts = options.modelOptions\n\n const systemInstruction =\n modelOpts?.system_instruction ?? options.systemPrompts?.join('\\n')\n\n const generationConfig: Interactions.GenerationConfig = {\n ...modelOpts?.generation_config,\n }\n\n const hasGenerationConfig = Object.keys(generationConfig).length > 0\n\n const input = convertMessagesToInteractionsInput(\n options.messages,\n modelOpts?.previous_interaction_id !== undefined,\n )\n\n return {\n model: options.model,\n input,\n previous_interaction_id: modelOpts?.previous_interaction_id,\n system_instruction: systemInstruction,\n tools: convertToolsToInteractionsFormat(options.tools),\n generation_config: hasGenerationConfig ? generationConfig : undefined,\n store: modelOpts?.store,\n background: modelOpts?.background,\n response_modalities: modelOpts?.response_modalities,\n response_format: modelOpts?.response_format,\n }\n}\n\n// Google's Interactions API takes `input` as `Array<Step>`. Each Step\n// is `{type: 'user_input' | 'function_result' | ..., ...}` — content\n// blocks (text/image/etc.) live nested inside a Step's `content` array,\n// they are NOT valid at the top level. Sending raw `Array<Content>`\n// produces `invalid_request` / \"value at top-level must be a list\",\n// because the API is looking for a Step list at the top level and\n// gets content objects instead. The SDK's type union\n// (`string | Array<Content> | Array<Turn> | ...`) is misleading; see\n// https://ai.google.dev/api/interactions-api for the real Step union.\n//\n// When `hasPreviousInteraction` is true the server holds the transcript\n// up through the last assistant turn, so we only send the steps that\n// come after it (a new `user_input`, one or more `function_result`s\n// continuing a tool call, etc.). Otherwise the conversation is fresh\n// and only the latest user turn is supported — multi-turn replay\n// without `previous_interaction_id` is not part of the API contract.\nfunction convertMessagesToInteractionsInput(\n messages: Array<ModelMessage>,\n hasPreviousInteraction: boolean,\n): InteractionsRequestInput {\n const toolCallIdToName = new Map<string, string>()\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.toolCalls) {\n for (const tc of msg.toolCalls) {\n toolCallIdToName.set(tc.id, tc.function.name)\n }\n }\n }\n\n const source = hasPreviousInteraction\n ? messagesAfterLastAssistant(messages)\n : messages\n\n if (hasPreviousInteraction && source.length === 0) {\n throw new Error(\n '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.',\n )\n }\n\n if (!hasPreviousInteraction) {\n const [only, ...rest] = source\n if (!only) {\n throw new Error('Gemini Interactions adapter: no messages to send.')\n }\n if (rest.length > 0) {\n throw new Error(\n '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.',\n )\n }\n if (only.role !== 'user') {\n throw new Error(\n `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.`,\n )\n }\n const content = messageToContentBlocks(only)\n if (content.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: the user message produced no content blocks to send.',\n )\n }\n return [{ type: 'user_input', content }]\n }\n\n // Chained path: each post-assistant message becomes one Step. A user\n // reply maps to `user_input`; a tool reply maps to `function_result`.\n // Assistant turns shouldn't appear here (sliced off above) — if one\n // somehow does we skip it rather than letting it shape the wire.\n const steps: Array<InteractionsStep> = []\n for (const msg of source) {\n if (msg.role === 'tool' && msg.toolCallId) {\n const result = serializeToolResultContent(msg.content)\n steps.push({\n type: 'function_result',\n call_id: msg.toolCallId,\n name: toolCallIdToName.get(msg.toolCallId),\n result,\n })\n } else if (msg.role === 'user') {\n const content = messageToContentBlocks(msg)\n if (content.length > 0) {\n steps.push({ type: 'user_input', content })\n }\n }\n }\n if (steps.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: messages after the last assistant turn produced no steps to send.',\n )\n }\n return steps\n}\n\n// The Interactions API's `function_result.result` field is a string. We\n// fail loudly on non-string tool content rather than silently coercing\n// to `''` — silent coercion meant the model lost the entire tool\n// output for callers that returned content as an array (e.g. image +\n// text) or `null`. If you need to send structured tool output, encode\n// it yourself before passing.\nfunction serializeToolResultContent(\n content: ModelMessage['content'] | undefined,\n): string {\n if (typeof content === 'string') return content\n if (content === null || content === undefined) {\n throw new Error(\n '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).',\n )\n }\n throw new Error(\n '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.',\n )\n}\n\n// Extracts the content blocks (text / image / audio / video / document)\n// from a single message. Tool calls and tool results live one level up\n// as Steps, not as content, so they are NOT emitted here.\nfunction messageToContentBlocks(msg: ModelMessage): Array<ContentBlock> {\n const blocks: Array<ContentBlock> = []\n\n if (Array.isArray(msg.content)) {\n for (const part of msg.content) {\n blocks.push(contentPartToBlock(part))\n }\n } else if (\n typeof msg.content === 'string' &&\n msg.content &&\n msg.role !== 'tool'\n ) {\n blocks.push({ type: 'text', text: msg.content })\n }\n\n return blocks\n}\n\nfunction messagesAfterLastAssistant(\n messages: Array<ModelMessage>,\n): Array<ModelMessage> {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === 'assistant') {\n return messages.slice(i + 1)\n }\n }\n return messages\n}\n\n// Leniently parse the *accumulated* streamed tool-call argument buffer.\n// Streamed `arguments_delta` fragments are individually incomplete JSON, so\n// a strict `JSON.parse` would throw (and log noise) on every fragment until\n// the final one. `partial-json` recovers a best-effort object from a\n// truncated buffer instead. Returns `undefined` when nothing usable could be\n// parsed, so callers can keep the last good value rather than clobber\n// previously-merged args with `{}`.\nfunction parsePartialToolArguments(\n raw: string,\n): Record<string, unknown> | undefined {\n if (!raw) return undefined\n try {\n const parsed = parsePartialJSON(raw)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n// `satisfies` pins these arrays to the SDK's narrow mime-type unions: if\n// Google removes a format the build breaks, and if they add one ours keeps\n// working (we just won't accept the new one until added here).\nconst IMAGE_MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/heic',\n 'image/heif',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.ImageContent['mime_type']>\n>\n\nconst AUDIO_MIME_TYPES = [\n 'audio/wav',\n 'audio/mp3',\n 'audio/aiff',\n 'audio/aac',\n 'audio/ogg',\n 'audio/flac',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.AudioContent['mime_type']>\n>\n\nconst VIDEO_MIME_TYPES = [\n 'video/mp4',\n 'video/mpeg',\n 'video/mpg',\n 'video/mov',\n 'video/avi',\n 'video/x-flv',\n 'video/webm',\n 'video/wmv',\n 'video/3gpp',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.VideoContent['mime_type']>\n>\n\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.DocumentContent['mime_type']>\n>\n\nfunction validateMime<T extends string>(\n allowed: ReadonlyArray<T>,\n value: string | undefined,\n kind: string,\n): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as ReadonlyArray<string>).includes(value)) {\n return value as T\n }\n throw new Error(\n `Unsupported ${kind} mime type \"${value}\" for the Gemini Interactions API. Allowed: ${allowed.join(', ')}.`,\n )\n}\n\nfunction contentPartToBlock(part: ContentPart): ContentBlock {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n const isData = part.source.type === 'data'\n switch (part.type) {\n case 'image': {\n const mime_type = validateMime(\n IMAGE_MIME_TYPES,\n part.source.mimeType,\n 'image',\n )\n return isData\n ? { type: 'image', data: part.source.value, mime_type }\n : { type: 'image', uri: part.source.value, mime_type }\n }\n case 'audio': {\n const mime_type = validateMime(\n AUDIO_MIME_TYPES,\n part.source.mimeType,\n 'audio',\n )\n return isData\n ? { type: 'audio', data: part.source.value, mime_type }\n : { type: 'audio', uri: part.source.value, mime_type }\n }\n case 'video': {\n const mime_type = validateMime(\n VIDEO_MIME_TYPES,\n part.source.mimeType,\n 'video',\n )\n return isData\n ? { type: 'video', data: part.source.value, mime_type }\n : { type: 'video', uri: part.source.value, mime_type }\n }\n case 'document': {\n const mime_type = validateMime(\n DOCUMENT_MIME_TYPES,\n part.source.mimeType,\n 'document',\n )\n return isData\n ? { type: 'document', data: part.source.value, mime_type }\n : { type: 'document', uri: part.source.value, mime_type }\n }\n }\n}\n\n// Built-in Gemini tools use snake_case field names in the Interactions API\n// that differ from the camelCase fields used on `client.models.generateContent`\n// (e.g. `fileSearchStoreNames` vs `file_search_store_names`). Translate\n// explicitly so callers keep using the same tool factories across adapters.\nfunction convertToolsToInteractionsFormat<TTool extends Tool>(\n tools: Array<TTool> | undefined,\n): Array<InteractionsTool> | undefined {\n if (!tools || tools.length === 0) return undefined\n assertUniqueToolNames(tools)\n\n const result: Array<InteractionsTool> = []\n\n for (const tool of tools) {\n switch (getGeminiProviderToolKind(tool)) {\n case 'google_search': {\n const metadata = (getGeminiProviderToolMetadata(tool) ?? {}) as {\n searchTypes?: {\n webSearch?: unknown\n imageSearch?: unknown\n }\n }\n const searchTypes: Array<'web_search' | 'image_search'> = []\n if (metadata.searchTypes?.webSearch !== undefined) {\n searchTypes.push('web_search')\n }\n if (metadata.searchTypes?.imageSearch !== undefined) {\n searchTypes.push('image_search')\n }\n result.push({\n type: 'google_search',\n ...(searchTypes.length > 0 ? { search_types: searchTypes } : {}),\n })\n break\n }\n case 'code_execution': {\n result.push({ type: 'code_execution' })\n break\n }\n case 'url_context': {\n result.push({ type: 'url_context' })\n break\n }\n case 'file_search': {\n const metadata = (getGeminiProviderToolMetadata(tool) ?? {}) as {\n fileSearchStoreNames?: Array<string>\n topK?: number\n metadataFilter?: string\n }\n result.push({\n type: 'file_search',\n ...(metadata.fileSearchStoreNames\n ? { file_search_store_names: metadata.fileSearchStoreNames }\n : {}),\n ...(metadata.topK !== undefined ? { top_k: metadata.topK } : {}),\n ...(metadata.metadataFilter !== undefined\n ? { metadata_filter: metadata.metadataFilter }\n : {}),\n })\n break\n }\n case 'computer_use': {\n const metadata = (getGeminiProviderToolMetadata(tool) ?? {}) as {\n environment?: string\n excludedPredefinedFunctions?: Array<string>\n }\n if (metadata.environment && metadata.environment !== 'browser') {\n throw new Error(\n `computer_use environment \"${metadata.environment}\" is not supported on the Gemini Interactions API. Only \"browser\" is accepted.`,\n )\n }\n result.push({\n type: 'computer_use',\n ...(metadata.environment\n ? { environment: metadata.environment as 'browser' }\n : {}),\n ...(metadata.excludedPredefinedFunctions\n ? {\n excludedPredefinedFunctions:\n metadata.excludedPredefinedFunctions,\n }\n : {}),\n })\n break\n }\n case 'google_search_retrieval':\n throw new Error(\n '`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.',\n )\n case 'google_maps':\n throw new Error(\n '`google_maps` is not yet supported on the Gemini Interactions API. Use `geminiText()` for Google Maps grounding.',\n )\n case undefined: {\n if (!tool.description) {\n throw new Error(\n `Tool ${tool.name} requires a description for the Gemini Interactions adapter`,\n )\n }\n result.push({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: sanitizeToolParameters(\n tool.inputSchema ?? { type: 'object', properties: {} },\n ),\n })\n }\n }\n }\n\n return result\n}\n\n// Map of API-level status values onto the AG-UI `finishReason` field.\n// `requires_action` is the Interactions API's signal that the model\n// produced one or more function calls and is waiting for results — we\n// always map that to 'tool_calls' regardless of whether deltas were\n// observed (a function_call may have arrived in a single delta with no\n// other content). `incomplete` is the truncation signal (max_tokens\n// exceeded etc.) — map to 'length'. `completed` is normal stop.\nfunction statusToFinishReason(\n status: Interaction['status'] | undefined,\n sawFunctionCall: boolean,\n): 'stop' | 'length' | 'tool_calls' | null {\n if (status === 'requires_action') return 'tool_calls'\n if (status === 'incomplete') return 'length'\n if (sawFunctionCall) return 'tool_calls'\n return 'stop'\n}\n\n// Statuses that mean the interaction did not produce a usable result.\n// `failed`/`cancelled` map to RUN_ERROR. `incomplete` is the model\n// hitting a stop condition (max_tokens etc.) and is reported via\n// `finishReason: 'length'` on RUN_FINISHED so callers can decide how to\n// react without it looking like a hard error.\nfunction statusIsError(\n status: Interaction['status'] | undefined,\n): status is 'failed' | 'cancelled' {\n return status === 'failed' || status === 'cancelled'\n}\n\nasync function* translateInteractionEvents(\n stream: AsyncIterable<InteractionSSEEvent>,\n model: string,\n runId: string,\n threadId: string,\n parentRunId: string | undefined,\n timestamp: number,\n adapterName: string,\n logger: InternalLogger,\n): AsyncIterable<AdapterYieldChunk> {\n const messageId = generateId(adapterName)\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let textAccumulated = ''\n let interactionId: string | undefined\n let sawFunctionCall = false\n const toolCalls = new Map<string, ToolCallState>()\n let nextToolIndex = 0\n let thinkingStepId: string | null = null\n let thinkingAccumulated = ''\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n // SDK 2.x routes events by step `index`, not by content id. We need to\n // map the index of an in-flight `function_call` step back to the tool\n // call id so subsequent `step.delta` (arguments_delta) and `step.stop`\n // events can update / close the right TOOL_CALL_*.\n const indexToToolCallId = new Map<number, string>()\n // Function-call arguments now stream as partial JSON fragments\n // (`StepDelta.ArgumentsDelta.arguments`) rather than as pre-parsed\n // object deltas. Buffer the raw strings per tool call so we can\n // attempt one JSON parse per delta and recover gracefully if the\n // fragment isn't yet syntactically complete.\n const argStringByToolCallId = new Map<string, string>()\n\n const closeReasoningIfNeeded = function* (): Generator<AdapterYieldChunk> {\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n // Reset so that a later `thought_summary` delta (the API\n // interleaves text → thought → text on some models) opens a\n // fresh reasoning block instead of re-using an already-ended\n // messageId, which would violate AG-UI ordering.\n thinkingStepId = null\n reasoningMessageId = null\n hasClosedReasoning = false\n }\n }\n\n // Seals any in-flight messages and tool calls. Called both on the\n // normal terminal path (`interaction.complete`) and on the error path\n // (`error` SSE event + premature EOF) so the StreamProcessor never\n // sees orphan TEXT_MESSAGE_START / TOOL_CALL_START / REASONING_*\n // events on RUN_ERROR.\n const closeOpenState = function* (): Generator<AdapterYieldChunk> {\n yield* closeReasoningIfNeeded()\n for (const [toolCallId, state] of toolCalls) {\n if (state.ended) continue\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n if (hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = false\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp,\n }\n }\n }\n\n const emitRunStartedIfNeeded = function* (): Generator<AdapterYieldChunk> {\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp,\n parentRunId,\n }\n }\n }\n\n for await (const event of stream) {\n logger.provider(`provider=gemini-text-interactions`, { event })\n switch (event.event_type) {\n case 'interaction.created': {\n interactionId = event.interaction.id\n yield* emitRunStartedIfNeeded()\n break\n }\n\n case 'step.start': {\n yield* emitRunStartedIfNeeded()\n const step = event.step\n const index = event.index\n switch (step.type) {\n case 'function_call': {\n yield* closeReasoningIfNeeded()\n sawFunctionCall = true\n const toolCallId = step.id\n indexToToolCallId.set(index, toolCallId)\n // `step.arguments` is required on FunctionCallStep but may\n // be an empty `{}` placeholder when streaming, where the\n // real args arrive as `arguments_delta` events. Treat both\n // uniformly: stash whatever we got, stringify once.\n const initialArgs = step.arguments\n const state: ToolCallState = {\n name: step.name,\n args: { ...initialArgs },\n index: nextToolIndex++,\n started: true,\n ended: false,\n }\n toolCalls.set(toolCallId, state)\n argStringByToolCallId.set(\n toolCallId,\n Object.keys(initialArgs).length > 0\n ? JSON.stringify(initialArgs)\n : '',\n )\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: state.name,\n toolName: state.name,\n // Bind the tool call to the same assistant message id the\n // eventual TEXT_MESSAGE_START uses so the message id stays\n // stable when a function_call arrives before any text (#477).\n parentMessageId: messageId,\n model,\n timestamp,\n index: state.index,\n }\n if (Object.keys(initialArgs).length > 0) {\n const argsJson = JSON.stringify(initialArgs)\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: argsJson,\n args: argsJson,\n }\n }\n break\n }\n case 'thought': {\n // Open the reasoning block lazily — content lands here via\n // `step.delta { thought_summary }` events. If the server\n // ships a non-empty `summary` array up-front (rare, unary\n // responses), surface it immediately.\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n for (const part of step.summary ?? []) {\n if (part.type !== 'text' || !part.text) continue\n thinkingAccumulated += part.text\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: part.text,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: part.text,\n content: thinkingAccumulated,\n }\n }\n break\n }\n case 'model_output': {\n yield* closeReasoningIfNeeded()\n // Some servers ship an initial `content` array on\n // `step.start` (notably non-streaming and ahead-of-stream\n // unary completions). Treat any prefilled text content the\n // same way a `text` step.delta would.\n for (const part of step.content ?? []) {\n if (part.type !== 'text' || !part.text) continue\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += part.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: part.text,\n content: textAccumulated,\n }\n }\n break\n }\n case 'google_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'google_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n // Unhandled step types (user_input on GET timelines,\n // mcp_server_*, google_maps_*, function_result) fall through\n // to the observability default so SDK drift is visible.\n case 'user_input':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(`gemini-text-interactions unhandled step.start`, {\n step,\n })\n break\n }\n break\n }\n\n case 'step.delta': {\n yield* emitRunStartedIfNeeded()\n const delta = event.delta\n const index = event.index\n switch (delta.type) {\n case 'text': {\n yield* closeReasoningIfNeeded()\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += delta.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: delta.text,\n content: textAccumulated,\n }\n break\n }\n case 'arguments_delta': {\n // Streamed function-call arguments. Identity (id, name) was\n // delivered on the matching `step.start` and recorded in\n // indexToToolCallId.\n const toolCallId = indexToToolCallId.get(index)\n if (!toolCallId) {\n logger.provider(\n `gemini-text-interactions arguments_delta for unknown step index`,\n { index, delta },\n )\n break\n }\n const state = toolCalls.get(toolCallId)\n if (!state) break\n const fragment = delta.arguments ?? ''\n const buffer =\n (argStringByToolCallId.get(toolCallId) ?? '') + fragment\n argStringByToolCallId.set(toolCallId, buffer)\n // Parse the accumulated buffer leniently: streamed arg fragments\n // are individually incomplete JSON, so use a partial-JSON parser\n // that tolerates truncation rather than logging a parse error per\n // fragment. Only overwrite `state.args` when we actually recovered\n // an object, so a momentarily-unparseable fragment can't reset\n // previously-merged args back to `{}`.\n const parsed = parsePartialToolArguments(buffer)\n if (parsed) state.args = parsed\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: fragment,\n args: buffer,\n }\n break\n }\n case 'thought_summary': {\n const thoughtText =\n delta.content && 'text' in delta.content ? delta.content.text : ''\n if (!thoughtText) break\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n thinkingAccumulated += thoughtText\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: thoughtText,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: thoughtText,\n content: thinkingAccumulated,\n }\n break\n }\n // The remaining StepDelta variants (image/audio/video/document\n // for output modalities a text adapter shouldn't see, tool\n // call/result deltas which are surfaced via step.start in this\n // adapter, thought_signature, annotation deltas, mcp/google\n // maps variants) fall through to the observability default.\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n case 'thought_signature':\n case 'text_annotation_delta':\n case 'code_execution_call':\n case 'code_execution_result':\n case 'url_context_call':\n case 'url_context_result':\n case 'google_search_call':\n case 'google_search_result':\n case 'file_search_call':\n case 'file_search_result':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(\n `gemini-text-interactions unhandled step.delta type`,\n { delta },\n )\n break\n }\n break\n }\n\n case 'step.stop': {\n // Close any open function_call so downstream consumers get the\n // matching TOOL_CALL_END once the arguments are complete. Other\n // step types don't carry adapter-level open state.\n const toolCallId = indexToToolCallId.get(event.index)\n if (toolCallId) {\n const state = toolCalls.get(toolCallId)\n if (state && !state.ended) {\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n indexToToolCallId.delete(event.index)\n }\n break\n }\n\n case 'interaction.status_update': {\n break\n }\n\n case 'interaction.completed': {\n if (event.interaction.id) {\n interactionId = event.interaction.id\n }\n\n yield* closeOpenState()\n\n const status = event.interaction.status\n if (statusIsError(status)) {\n const message = `Gemini Interactions ${status}: the interaction ended without a usable response.`\n logger.errors(\n 'gemini-text-interactions.translateInteractionEvents non-success status',\n {\n source: 'gemini-text-interactions.chatStream',\n status,\n interactionId,\n },\n )\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code: status,\n error: { message, code: status },\n }\n return\n }\n\n const usage = event.interaction.usage\n const finishReason = statusToFinishReason(status, sawFunctionCall)\n\n if (interactionId) {\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.interactionId',\n value: { interactionId },\n model,\n timestamp,\n }\n }\n\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp,\n finishReason,\n usage: usage\n ? {\n promptTokens: usage.total_input_tokens ?? 0,\n completionTokens: usage.total_output_tokens ?? 0,\n totalTokens: usage.total_tokens ?? 0,\n }\n : undefined,\n }\n return\n }\n\n case 'error': {\n // Close any in-flight TEXT_MESSAGE_START / TOOL_CALL_START /\n // REASONING_* so downstream consumers don't see orphan open\n // state after RUN_ERROR.\n yield* closeOpenState()\n const rawMessage = event.error?.message\n const message =\n typeof rawMessage === 'string' && rawMessage.length > 0\n ? rawMessage\n : `Gemini Interactions error (no message): ${JSON.stringify(event.error ?? {})}`\n const rawCode = event.error?.code\n const code =\n typeof rawCode === 'string' || typeof rawCode === 'number'\n ? String(rawCode)\n : undefined\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code,\n error: { message, code },\n }\n return\n }\n\n default:\n logger.provider(`gemini-text-interactions unhandled event_type`, {\n event,\n })\n break\n }\n }\n\n // Stream ended without `interaction.complete` or `error` (both `return`\n // out of the loop). Seal any in-flight TEXT/TOOL/REASONING blocks here\n // so the truncation-fallback RUN_ERROR yielded by `chatStream` doesn't\n // leave orphan `*_START` events open downstream.\n yield* closeOpenState()\n}\n\nfunction extractTextFromInteraction(interaction: Interaction): string {\n // SDK 2.x: the response carries a `steps` array; `output_text` is a\n // convenience the SDK derives from the last model output. Prefer the\n // SDK sugar when it's populated, then fall back to walking\n // model_output steps for adapters / responses that don't get the\n // sugar (e.g. older SDK builds).\n if (typeof interaction.output_text === 'string' && interaction.output_text) {\n return interaction.output_text\n }\n let text = ''\n for (const step of interaction.steps ?? []) {\n if (step.type !== 'model_output' || !step.content) continue\n for (const part of step.content) {\n if (part.type === 'text') {\n text += part.text\n }\n }\n }\n return text\n}\n\n// The live Interactions API rejects tool parameter schemas that contain\n// an empty `required: []` array with the misleading top-level error\n// `\"value at top-level must be a list\"`. Empty `properties: {}` and\n// `parameters: {}` are both fine — only the empty `required` array is\n// poison. The Zod -> JSON Schema converter (and many hand-written\n// schemas) emit `required: []` whenever a tool has zero required\n// parameters, so we strip those instances recursively before sending.\n// Non-empty `required` arrays are passed through unchanged.\nfunction sanitizeToolParameters(schema: unknown): unknown {\n if (!schema || typeof schema !== 'object') return schema\n if (Array.isArray(schema)) return schema.map(sanitizeToolParameters)\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'required' && Array.isArray(value) && value.length === 0) {\n continue\n }\n out[key] = sanitizeToolParameters(value)\n }\n return out\n}\n\n// Re-export the stream type so consumers can import it alongside the\n// adapter from a single path: `import type { GeminiInteractionsStream }\n// from '@tanstack/ai-gemini/experimental'`.\nexport type { GeminiInteractionsStream }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0LA,IAAa,gCAAb,cAOU,gBAMR;CACA,OAAyB;CACzB,OAAyB;CAEzB;CAeA,wCAAyC,IAAI,IAAoB;CAEjE,YAAY,QAAsC,OAAe;EAC/D,MAAM,CAAC,GAAG,KAAK;EACf,KAAK,SAAS,mBAAmB,MAAM;CACzC;CAEA,OAAO,WACL,SACkC;EAClC,MAAM,QAAQ,QAAQ,SAAS,WAAW,KAAK,IAAI;EACnD,MAAM,WAAW,QAAQ,YAAY,WAAW,KAAK,IAAI;EACzD,MAAM,YAAY,KAAK,IAAI;EAC3B,MAAM,EAAE,WAAW;EAOnB,IACE,CAAC,QAAQ,cAAc,2BACvB,QAAQ,SAAS,WAAW,KAC5B,QAAQ,SAAS,EAAE,EAAE,SAAS,QAE9B,KAAK,sBAAsB,OAAO,QAAQ;EAM5C,MAAM,iCACJ,QAAQ,cAAc,2BACtB,KAAK,sBAAsB,IAAI,QAAQ;EAEzC,IAAI,mBAAmB;EAQvB,IAAI,oBAAoB;EACxB,IAAI;GACF,MAAM,UAAU,yBAAyB;IACvC,GAAG;IACH,cAAc;KACZ,GAAG,QAAQ;KACX,yBAAyB;IAC3B;GACF,CAAC;GACD,OAAO,QACL,yDAAyD,KAAK,MAAM,YAAY,QAAQ,SAAS,OAAO,SAAS,QAAQ,OAAO,UAAU,EAAE,eAC5I;IACE,UAAU;IACV,OAAO,KAAK;IACZ;GACF,CACF;GACA,MAAM,SAAU,MAAM,KAAK,OAAO,aAAa,OAC7C;IAAE,GAAG;IAAS,QAAQ;GAAK,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UAAU,OAAO,WAAW,UAAU,OAAO;CAClD,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO,OAAO,IAAI,sBAAsB;CACnE,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,QAAQ,cAAc,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,GACjE;EAEF,IAAI,OAAO,uBAAuB,KAAK;CACzC;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/experimental/text-interactions/adapter.ts"],"sourcesContent":["import { EventType, fileReferenceFor, isFileSource } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { parse as parsePartialJSON } from 'partial-json'\nimport {\n createGeminiClient,\n generateId,\n getGeminiApiKeyFromEnv,\n} from '../../utils/client'\nimport {\n getGeminiProviderToolKind,\n getGeminiProviderToolMetadata,\n} from '../../tools/gemini-provider-tool'\nimport { assertUniqueToolNames } from '@tanstack/ai/adapter-internals'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n GeminiChatModelProviderOptionsByName,\n GeminiChatModelToolCapabilitiesByName,\n GeminiModelInputModalitiesByName,\n GeminiModels,\n} from '../../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { GoogleGenAI, Interactions } from '@google/genai'\nimport type {\n ContentPart,\n Modality,\n ModelMessage,\n AdapterYieldChunk,\n TextOptions,\n Tool,\n} from '@tanstack/ai'\n\nimport type {\n GeminiInteractionsCustomEvent,\n GeminiInteractionsCustomEventValue,\n GeminiInteractionsStream,\n} from './events'\nimport type { ExternalTextInteractionsProviderOptions } from './provider-options'\nimport type { GeminiMessageMetadataByModality } from '../../message-types'\nimport type { GeminiClientConfig } from '../../utils/client'\n\ntype Interaction = Interactions.Interaction\ntype InteractionSSEEvent = Interactions.InteractionSSEEvent\n\nexport type GeminiTextInteractionsConfig = GeminiClientConfig\n\nexport type GeminiTextInteractionsProviderOptions =\n ExternalTextInteractionsProviderOptions\n\ntype InteractionsTool = NonNullable<\n Interactions.CreateModelInteractionParamsStreaming['tools']\n>[number]\n\ntype ContentBlock = Interactions.Content\n\n// The Interactions API takes `input` as a list of *Steps* (not a list of\n// content blocks, and not a list of `Turn`s — the SDK's type union is\n// misleading on both counts). The live API enforces the Step envelope —\n// raw content arrays produce `invalid_request` / \"value at top-level\n// must be a list\". The wire discriminator is snake_case\n// (`user_input` / `function_result`); see\n// https://ai.google.dev/api/interactions-api for the full Step union.\ntype UserInputStep = {\n type: 'user_input'\n content: Array<ContentBlock>\n}\ntype FunctionResultStep = {\n type: 'function_result'\n call_id: string\n name?: string\n result: string\n}\ntype InteractionsStep = UserInputStep | FunctionResultStep\ntype InteractionsRequestInput = Array<InteractionsStep>\n\n// Concrete wire shape we send to `client.interactions.create`. The SDK's\n// own param union types `input` as `string | Content[] | Turn[] | ...`\n// which is wrong for the live API (see the InteractionsRequestInput\n// comment above), so we type `input` ourselves and cast just once at the\n// SDK boundary instead of casting every field through.\ntype GeminiInteractionsRequestBody = Omit<\n Interactions.CreateModelInteractionParamsStreaming,\n 'input' | 'stream'\n> & {\n input: InteractionsRequestInput\n stream?: boolean\n}\n\ntype ToolCallState = {\n name: string\n // Accumulated args as a parsed object. Kept here in object form so a\n // garbled delta can't corrupt previously-merged fragments (the prior\n // string-then-reparse pipeline replaced the whole accumulator on any\n // parse failure). Stringified only when emitting AG-UI events.\n args: Record<string, unknown>\n index: number\n started: boolean\n ended: boolean\n}\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model. Reuses the chat-model\n * options map from `model-meta.ts` so a model's allowed thinking levels are\n * declared once: the Interactions API takes the same levels as\n * `generateContent` but lowercased (`low`, not `LOW`). Models whose chat\n * options carry no `thinkingConfig` resolve to `never`, so `thinking_level`\n * can't be set on them. Everything else falls through to the flat SDK shape.\n */\ntype InteractionsThinkingLevel<TModel> =\n TModel extends keyof GeminiChatModelProviderOptionsByName\n ? GeminiChatModelProviderOptionsByName[TModel] extends {\n thinkingConfig?: { thinkingLevel?: infer L extends string }\n }\n ? Lowercase<L>\n : never\n : never\n\ntype ResolveProviderOptions<TModel extends GeminiModels> = Omit<\n GeminiTextInteractionsProviderOptions,\n 'generation_config'\n> & {\n generation_config?: Omit<\n NonNullable<GeminiTextInteractionsProviderOptions['generation_config']>,\n 'thinking_level'\n > & { thinking_level?: InteractionsThinkingLevel<TModel> }\n}\n\n/**\n * Resolve input modalities for a specific model. Reuses the chat-model\n * modality map from `model-meta.ts`: passing a `document` content block\n * to a model that doesn't support it is a compile error, matching the\n * sibling `GeminiTextAdapter`.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof GeminiModelInputModalitiesByName\n ? GeminiModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'audio', 'video', 'document']\n\n/**\n * Resolve tool capabilities for a specific model. Reuses the chat-model\n * capability map: `google_maps` / `google_search_retrieval` are rejected at\n * runtime by `convertToolsToInteractionsFormat`, but per-model gating happens\n * here at compile time.\n */\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof GeminiChatModelToolCapabilitiesByName\n ? NonNullable<GeminiChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n/**\n * Tree-shakeable adapter for Gemini's stateful Interactions API. Routes\n * through `client.interactions.create` and surfaces the server-assigned\n * `interactionId` via an AG-UI `CUSTOM` event with\n * `name: 'gemini.interactionId'` emitted just before `RUN_FINISHED`; pass\n * that id back on the next turn via `modelOptions.previous_interaction_id`\n * to continue the conversation without resending history.\n *\n * The Interactions API does NOT support stateless multi-turn replay —\n * passing more than one message in `messages` without a\n * `previous_interaction_id` throws. For a chat UI that maintains local\n * history (e.g. `useChat`), see the \"Wiring with `useChat`\" section of\n * `docs/adapters/gemini.md` for the canonical client/server pattern.\n *\n * Supports user-defined function tools and the built-in tools\n * `google_search`, `code_execution`, `url_context`, `file_search`, and\n * `computer_use`. Built-in tool *activity* for the four search/exec\n * variants is surfaced via `CUSTOM` events\n * (`gemini.googleSearchCall` / `gemini.googleSearchResult` and the\n * corresponding per-tool variants) carrying the raw Interactions delta;\n * see {@link GeminiInteractionsCustomEvent}. `computer_use` is accepted\n * in the request but the Interactions API does not currently stream\n * per-delta CUSTOM events for it. The `google_search_retrieval` and\n * `google_maps` provider-tool factories are not supported on this adapter and\n * throw a targeted error. There is no Gemini `mcp_server` factory, so a tool\n * merely *named* `mcp_server` is an ordinary function and is sent as a function\n * declaration like any other.\n *\n * @experimental Interactions API is in Beta per Google; shapes may change.\n * @see https://ai.google.dev/gemini-api/docs/interactions\n */\nexport class GeminiTextInteractionsAdapter<\n TModel extends GeminiModels,\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n GeminiMessageMetadataByModality,\n TToolCapabilities\n> {\n override readonly kind = 'text' as const\n override readonly name = 'gemini-text-interactions' as const\n // Consumes Gemini Files API references (geminiFiles()) as content `uri`s.\n override readonly supportsFileSources = true\n\n private readonly client: GoogleGenAI\n // Tracks the most recent server-assigned interaction id per threadId\n // so the adapter can chain follow-up calls on the same thread without\n // the caller having to thread the id manually. Two callers rely on\n // this:\n // 1. The agent loop's tool-call iterations (each iteration is a new\n // `chatStream` call with accumulated tool messages).\n // 2. The agentic-structured composition: a `chatStream` run followed\n // by `structuredOutput` on the accumulated messages.\n // Cross-request chaining is the caller's job via\n // `modelOptions.previous_interaction_id`. To keep stale ids from\n // chaining a brand-new turn, `chatStream` evicts at the START when\n // the caller signals fresh-turn intent (no caller-provided id AND a\n // single user message — anything else is a follow-up). Errors evict\n // immediately so a failed turn never chains into the next one.\n private readonly interactionIdByThread = new Map<string, string>()\n\n constructor(config: GeminiTextInteractionsConfig, model: TModel) {\n super({}, model)\n this.client = createGeminiClient(config)\n }\n\n async *chatStream(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const runId = options.runId ?? generateId(this.name)\n const threadId = options.threadId ?? generateId(this.name)\n const timestamp = Date.now()\n const { logger } = options\n\n // Fresh-turn intent: caller didn't thread an id AND only a single\n // user message is queued. Drop any stale captured id so we don't\n // silently chain off a prior turn the caller doesn't know about.\n // Multi-message inputs are follow-ups (agent-loop iteration or\n // structuredOutput composition) and keep the Map entry.\n if (\n !options.modelOptions?.previous_interaction_id &&\n options.messages.length === 1 &&\n options.messages[0]?.role === 'user'\n ) {\n this.interactionIdByThread.delete(threadId)\n }\n\n // Resolve `previous_interaction_id`. Caller-provided wins; otherwise\n // fall back to the id we captured during a prior iteration of this\n // same agent-loop run (matched by threadId).\n const effectivePreviousInteractionId =\n options.modelOptions?.previous_interaction_id ??\n this.interactionIdByThread.get(threadId)\n\n let sawTerminalEvent = false\n // Sentinel for the `.return()` abandonment path. Set to `true` only at\n // the bottom of the `try` block — so a consumer-initiated close (via\n // upstream `break` or abort) leaves it `false`, distinguishing\n // abandonment from normal completion. This is the only signal that\n // catches abandonment AFTER a `RUN_FINISHED(tool_calls)`, where\n // `sawTerminalEvent` is `true` but the in-loop deliberately kept the\n // map entry for an agent-loop iteration that will now never run.\n let completedTryBlock = false\n try {\n const request = buildInteractionsRequest({\n ...options,\n modelOptions: {\n ...options.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const stream = (await this.client.interactions.create(\n { ...request, stream: true } as GeminiInteractionsRequestBody &\n Parameters<typeof this.client.interactions.create>[0],\n { signal: abortSignalFromOptions(options) },\n )) as AsyncIterable<InteractionSSEEvent>\n\n for await (const chunk of translateInteractionEvents(\n stream,\n options.model,\n runId,\n threadId,\n options.parentRunId,\n timestamp,\n this.name,\n logger,\n )) {\n // Capture the server-assigned id so the next agent-loop\n // iteration on this thread can chain off it. The CUSTOM event\n // is also yielded downstream as usual — callers consume it via\n // `onCustomEvent` for cross-request chaining.\n //\n // The yield type can't be narrowed to GeminiInteractionsStream\n // here without fighting zod-passthrough variance (StreamChunk's\n // CustomEvent variant carries `[k: string]: unknown`), so we\n // narrow via the literal `name` and trust the typed\n // construction inside `translateInteractionEvents`.\n if (\n chunk.type === EventType.CUSTOM &&\n chunk.name === 'gemini.interactionId'\n ) {\n const value =\n chunk.value as GeminiInteractionsCustomEventValue<'gemini.interactionId'>\n this.interactionIdByThread.set(threadId, value.interactionId)\n }\n if (chunk.type === EventType.RUN_FINISHED) {\n sawTerminalEvent = true\n // Keep the captured id for follow-ups (next agent-loop\n // iteration OR a structuredOutput call composing this turn).\n // The next *fresh* chatStream call evicts at the top via the\n // fresh-turn guard.\n } else if (chunk.type === EventType.RUN_ERROR) {\n sawTerminalEvent = true\n this.interactionIdByThread.delete(threadId)\n }\n yield chunk\n }\n\n if (!sawTerminalEvent) {\n // SDK stream ended without either `interaction.complete` or\n // `error` — surface the truncation rather than silently leaving\n // downstream consumers waiting on a `RUN_FINISHED` that will\n // never come.\n this.interactionIdByThread.delete(threadId)\n const message =\n 'Gemini Interactions stream ended without a terminal event (no interaction.complete or error)'\n logger.errors('gemini-text-interactions.chatStream truncated', {\n source: 'gemini-text-interactions.chatStream',\n runId,\n threadId,\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n }\n completedTryBlock = true\n } catch (error) {\n this.interactionIdByThread.delete(threadId)\n const message =\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during the interactions stream.'\n logger.errors('gemini-text-interactions.chatStream fatal', {\n error,\n source: 'gemini-text-interactions.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n } finally {\n // Abandonment cleanup — consumer `.return()` (upstream `break` /\n // abort) bypasses both the truncation guard and the catch handler.\n // `completedTryBlock` is the sentinel that distinguishes natural\n // completion from abandonment; on abandonment we evict so a stale\n // id from a half-finished turn can't chain into a follow-up. The\n // catch handler also lands here with the flag false; its explicit\n // delete is harmless to repeat.\n if (!completedTryBlock) {\n this.interactionIdByThread.delete(threadId)\n }\n }\n }\n\n async structuredOutput(\n options: StructuredOutputOptions<GeminiTextInteractionsProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n const threadId = chatOptions.threadId\n\n // Mirror the chatStream fallback: the agentic-structured flow runs\n // the chat loop first and then calls structuredOutput with the\n // accumulated `messages`. If any tool ran during the loop, the\n // messages include assistant/tool turns; without a chained\n // previous_interaction_id those would throw \"cannot send prior\n // conversation history on a fresh interaction\".\n const effectivePreviousInteractionId =\n chatOptions.modelOptions?.previous_interaction_id ??\n (threadId ? this.interactionIdByThread.get(threadId) : undefined)\n\n const baseRequest = buildInteractionsRequest({\n ...chatOptions,\n modelOptions: {\n ...chatOptions.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n\n // SDK 2.x: `response_mime_type` has been removed and `response_format`\n // is now polymorphic — each entry has a `type` discriminator and the\n // mime type lives inside the entry. See:\n // https://ai.google.dev/gemini-api/docs/interactions-breaking-changes-may-2026\n const request: GeminiInteractionsRequestBody = {\n ...baseRequest,\n response_format: {\n type: 'text',\n mime_type: 'application/json',\n schema: outputSchema,\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const result = (await this.client.interactions.create(\n request as Parameters<typeof this.client.interactions.create>[0],\n { signal: abortSignalFromOptions(chatOptions) },\n )) as Interaction\n\n const rawText = extractTextFromInteraction(result)\n\n if (!rawText) {\n throw new Error(\n `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.`,\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(jsonContentParseError(rawText, 'structured output'))\n }\n\n return { data: parsed, rawText }\n } catch (error) {\n logger.errors('gemini-text-interactions.structuredOutput fatal', {\n error,\n source: 'gemini-text-interactions.structuredOutput',\n })\n // Preserve the original error as `cause` so the stack trace and any\n // SDK-attached status/code/headers survive for Sentry dedup.\n throw new Error(\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during structured output generation.',\n { cause: error },\n )\n }\n }\n\n async *structuredOutputStream(\n options: StructuredOutputOptions<GeminiTextInteractionsProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const { chatOptions, outputSchema } = options\n const runId = chatOptions.runId ?? generateId(this.name)\n const threadId = chatOptions.threadId ?? generateId(this.name)\n const timestamp = Date.now()\n const effectivePreviousInteractionId =\n chatOptions.modelOptions?.previous_interaction_id ??\n this.interactionIdByThread.get(threadId)\n const baseRequest = buildInteractionsRequest({\n ...chatOptions,\n modelOptions: {\n ...chatOptions.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n const request: GeminiInteractionsRequestBody = {\n ...baseRequest,\n stream: true,\n response_format: {\n type: 'text',\n mime_type: 'application/json',\n schema: outputSchema,\n },\n }\n\n try {\n chatOptions.logger.request(\n `activity=structuredOutputStream provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length}`,\n { provider: this.name, model: this.model, request },\n )\n const stream = (await this.client.interactions.create(\n request as GeminiInteractionsRequestBody &\n Parameters<typeof this.client.interactions.create>[0],\n { signal: abortSignalFromOptions(chatOptions) },\n )) as AsyncIterable<InteractionSSEEvent>\n\n let rawText = ''\n let finished:\n | Extract<AdapterYieldChunk, { type: typeof EventType.RUN_FINISHED }>\n | undefined\n let failed = false\n for await (const chunk of translateInteractionEvents(\n stream,\n chatOptions.model,\n runId,\n threadId,\n chatOptions.parentRunId,\n timestamp,\n this.name,\n chatOptions.logger,\n )) {\n if (chunk.type === EventType.TEXT_MESSAGE_CONTENT)\n rawText += chunk.delta\n if (\n chunk.type === EventType.CUSTOM &&\n chunk.name === 'gemini.interactionId'\n ) {\n const value =\n chunk.value as GeminiInteractionsCustomEventValue<'gemini.interactionId'>\n this.interactionIdByThread.set(threadId, value.interactionId)\n }\n if (chunk.type === EventType.RUN_ERROR) failed = true\n if (chunk.type === EventType.RUN_FINISHED) finished = chunk\n else yield chunk\n }\n\n if (failed) return\n if (!finished) {\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n 'Gemini Interactions structured-output stream ended without a terminal event',\n 'truncated-stream',\n )\n return\n }\n if (!rawText) {\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n 'Gemini Interactions structured-output stream contained no content',\n 'empty-response',\n )\n return\n }\n let object: unknown\n try {\n object = JSON.parse(rawText)\n } catch {\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n jsonContentParseError(\n rawText,\n 'Gemini Interactions structured-output stream',\n ),\n 'parse-error',\n )\n return\n }\n yield {\n type: EventType.CUSTOM,\n name: 'structured-output.complete',\n value: { object, raw: rawText },\n model: chatOptions.model,\n timestamp: Date.now(),\n }\n yield { ...finished, timestamp: Date.now() }\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during structured output streaming.'\n chatOptions.logger.errors(\n 'gemini-text-interactions.structuredOutputStream fatal',\n { error, source: 'gemini-text-interactions.structuredOutputStream' },\n )\n yield interactionsStructuredStreamError(\n chatOptions,\n runId,\n message,\n 'provider-error',\n )\n }\n }\n}\n\nfunction abortSignalFromOptions(\n options: Pick<\n TextOptions<GeminiTextInteractionsProviderOptions>,\n 'request' | 'abortController'\n >,\n) {\n return options.request?.signal ?? options.abortController?.signal\n}\n\nfunction jsonContentParseError(rawText: string, label: string) {\n const snippet = rawText.slice(0, 200)\n const ellipsis = rawText.length > 200 ? '...' : ''\n return `Failed to parse ${label} as JSON. Content: ${snippet}${ellipsis}`\n}\n\nfunction interactionsStructuredStreamError(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n runId: string,\n message: string,\n code: string,\n): Extract<AdapterYieldChunk, { type: typeof EventType.RUN_ERROR }> {\n return {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp: Date.now(),\n message,\n code,\n error: { message, code },\n }\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function createGeminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n apiKey: string,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n return new GeminiTextInteractionsAdapter({ apiKey, ...config }, model)\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function geminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions<TModel>,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n const apiKey = getGeminiApiKeyFromEnv()\n return createGeminiTextInteractions(model, apiKey, config)\n}\n\nfunction buildInteractionsRequest(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n): GeminiInteractionsRequestBody {\n const modelOpts = options.modelOptions\n\n const systemInstruction =\n modelOpts?.system_instruction ?? options.systemPrompts?.join('\\n')\n\n const generationConfig: Interactions.GenerationConfig = {\n ...modelOpts?.generation_config,\n }\n\n const hasGenerationConfig = Object.keys(generationConfig).length > 0\n\n const input = convertMessagesToInteractionsInput(\n options.messages,\n modelOpts?.previous_interaction_id !== undefined,\n )\n\n return {\n model: options.model,\n input,\n previous_interaction_id: modelOpts?.previous_interaction_id,\n system_instruction: systemInstruction,\n tools: convertToolsToInteractionsFormat(options.tools),\n generation_config: hasGenerationConfig ? generationConfig : undefined,\n store: modelOpts?.store,\n background: modelOpts?.background,\n response_modalities: modelOpts?.response_modalities,\n response_format: modelOpts?.response_format,\n }\n}\n\n// Google's Interactions API takes `input` as `Array<Step>`. Each Step\n// is `{type: 'user_input' | 'function_result' | ..., ...}` — content\n// blocks (text/image/etc.) live nested inside a Step's `content` array,\n// they are NOT valid at the top level. Sending raw `Array<Content>`\n// produces `invalid_request` / \"value at top-level must be a list\",\n// because the API is looking for a Step list at the top level and\n// gets content objects instead. The SDK's type union\n// (`string | Array<Content> | Array<Turn> | ...`) is misleading; see\n// https://ai.google.dev/api/interactions-api for the real Step union.\n//\n// When `hasPreviousInteraction` is true the server holds the transcript\n// up through the last assistant turn, so we only send the steps that\n// come after it (a new `user_input`, one or more `function_result`s\n// continuing a tool call, etc.). Otherwise the conversation is fresh\n// and only the latest user turn is supported — multi-turn replay\n// without `previous_interaction_id` is not part of the API contract.\nfunction convertMessagesToInteractionsInput(\n messages: Array<ModelMessage>,\n hasPreviousInteraction: boolean,\n): InteractionsRequestInput {\n const toolCallIdToName = new Map<string, string>()\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.toolCalls) {\n for (const tc of msg.toolCalls) {\n toolCallIdToName.set(tc.id, tc.function.name)\n }\n }\n }\n\n const source = hasPreviousInteraction\n ? messagesAfterLastAssistant(messages)\n : messages\n\n if (hasPreviousInteraction && source.length === 0) {\n throw new Error(\n '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.',\n )\n }\n\n if (!hasPreviousInteraction) {\n const [only, ...rest] = source\n if (!only) {\n throw new Error('Gemini Interactions adapter: no messages to send.')\n }\n if (rest.length > 0) {\n throw new Error(\n '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.',\n )\n }\n if (only.role !== 'user') {\n throw new Error(\n `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.`,\n )\n }\n const content = messageToContentBlocks(only)\n if (content.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: the user message produced no content blocks to send.',\n )\n }\n return [{ type: 'user_input', content }]\n }\n\n // Chained path: each post-assistant message becomes one Step. A user\n // reply maps to `user_input`; a tool reply maps to `function_result`.\n // Assistant turns shouldn't appear here (sliced off above) — if one\n // somehow does we skip it rather than letting it shape the wire.\n const steps: Array<InteractionsStep> = []\n for (const msg of source) {\n if (msg.role === 'tool' && msg.toolCallId) {\n const result = serializeToolResultContent(msg.content)\n steps.push({\n type: 'function_result',\n call_id: msg.toolCallId,\n name: toolCallIdToName.get(msg.toolCallId),\n result,\n })\n } else if (msg.role === 'user') {\n const content = messageToContentBlocks(msg)\n if (content.length > 0) {\n steps.push({ type: 'user_input', content })\n }\n }\n }\n if (steps.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: messages after the last assistant turn produced no steps to send.',\n )\n }\n return steps\n}\n\n// The Interactions API's `function_result.result` field is a string. We\n// fail loudly on non-string tool content rather than silently coercing\n// to `''` — silent coercion meant the model lost the entire tool\n// output for callers that returned content as an array (e.g. image +\n// text) or `null`. If you need to send structured tool output, encode\n// it yourself before passing.\nfunction serializeToolResultContent(\n content: ModelMessage['content'] | undefined,\n): string {\n if (typeof content === 'string') return content\n if (content === null || content === undefined) {\n throw new Error(\n '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).',\n )\n }\n throw new Error(\n '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.',\n )\n}\n\n// Extracts the content blocks (text / image / audio / video / document)\n// from a single message. Tool calls and tool results live one level up\n// as Steps, not as content, so they are NOT emitted here.\nfunction messageToContentBlocks(msg: ModelMessage): Array<ContentBlock> {\n const blocks: Array<ContentBlock> = []\n\n if (Array.isArray(msg.content)) {\n for (const part of msg.content) {\n blocks.push(contentPartToBlock(part))\n }\n } else if (\n typeof msg.content === 'string' &&\n msg.content &&\n msg.role !== 'tool'\n ) {\n blocks.push({ type: 'text', text: msg.content })\n }\n\n return blocks\n}\n\nfunction messagesAfterLastAssistant(\n messages: Array<ModelMessage>,\n): Array<ModelMessage> {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === 'assistant') {\n return messages.slice(i + 1)\n }\n }\n return messages\n}\n\n// Leniently parse the *accumulated* streamed tool-call argument buffer.\n// Streamed `arguments_delta` fragments are individually incomplete JSON, so\n// a strict `JSON.parse` would throw (and log noise) on every fragment until\n// the final one. `partial-json` recovers a best-effort object from a\n// truncated buffer instead. Returns `undefined` when nothing usable could be\n// parsed, so callers can keep the last good value rather than clobber\n// previously-merged args with `{}`.\nfunction parsePartialToolArguments(\n raw: string,\n): Record<string, unknown> | undefined {\n if (!raw) return undefined\n try {\n const parsed = parsePartialJSON(raw)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n// `satisfies` pins these arrays to the SDK's narrow mime-type unions: if\n// Google removes a format the build breaks, and if they add one ours keeps\n// working (we just won't accept the new one until added here).\nconst IMAGE_MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/heic',\n 'image/heif',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.ImageContent['mime_type']>\n>\n\nconst AUDIO_MIME_TYPES = [\n 'audio/wav',\n 'audio/mp3',\n 'audio/aiff',\n 'audio/aac',\n 'audio/ogg',\n 'audio/flac',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.AudioContent['mime_type']>\n>\n\nconst VIDEO_MIME_TYPES = [\n 'video/mp4',\n 'video/mpeg',\n 'video/mpg',\n 'video/mov',\n 'video/avi',\n 'video/x-flv',\n 'video/webm',\n 'video/wmv',\n 'video/3gpp',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.VideoContent['mime_type']>\n>\n\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.DocumentContent['mime_type']>\n>\n\nfunction validateMime<T extends string>(\n allowed: ReadonlyArray<T>,\n value: string | undefined,\n kind: string,\n): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as ReadonlyArray<string>).includes(value)) {\n return value as T\n }\n throw new Error(\n `Unsupported ${kind} mime type \"${value}\" for the Gemini Interactions API. Allowed: ${allowed.join(', ')}.`,\n )\n}\n\nfunction contentPartToBlock(part: ContentPart): ContentBlock {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n // A Gemini Files API handle maps to the `uri` field (isData stays false),\n // same as a public URL. `fileReferenceFor` checks the issuer against\n // 'gemini', the name geminiFiles() stamps on its handles, not this\n // adapter's own name.\n const sourceValue = isFileSource(part.source)\n ? fileReferenceFor(part.source, 'gemini')\n : part.source.value\n const isData = part.source.type === 'data'\n switch (part.type) {\n case 'image': {\n const mime_type = validateMime(\n IMAGE_MIME_TYPES,\n part.source.mimeType,\n 'image',\n )\n return isData\n ? { type: 'image', data: sourceValue, mime_type }\n : { type: 'image', uri: sourceValue, mime_type }\n }\n case 'audio': {\n const mime_type = validateMime(\n AUDIO_MIME_TYPES,\n part.source.mimeType,\n 'audio',\n )\n return isData\n ? { type: 'audio', data: sourceValue, mime_type }\n : { type: 'audio', uri: sourceValue, mime_type }\n }\n case 'video': {\n const mime_type = validateMime(\n VIDEO_MIME_TYPES,\n part.source.mimeType,\n 'video',\n )\n return isData\n ? { type: 'video', data: sourceValue, mime_type }\n : { type: 'video', uri: sourceValue, mime_type }\n }\n case 'document': {\n const mime_type = validateMime(\n DOCUMENT_MIME_TYPES,\n part.source.mimeType,\n 'document',\n )\n return isData\n ? { type: 'document', data: sourceValue, mime_type }\n : { type: 'document', uri: sourceValue, mime_type }\n }\n }\n}\n\n// Built-in Gemini tools use snake_case field names in the Interactions API\n// that differ from the camelCase fields used on `client.models.generateContent`\n// (e.g. `fileSearchStoreNames` vs `file_search_store_names`). Translate\n// explicitly so callers keep using the same tool factories across adapters.\nfunction convertToolsToInteractionsFormat<TTool extends Tool>(\n tools: Array<TTool> | undefined,\n): Array<InteractionsTool> | undefined {\n if (!tools || tools.length === 0) return undefined\n assertUniqueToolNames(tools)\n\n const result: Array<InteractionsTool> = []\n\n for (const tool of tools) {\n switch (getGeminiProviderToolKind(tool)) {\n case 'google_search': {\n const metadata = (getGeminiProviderToolMetadata(tool) ?? {}) as {\n searchTypes?: {\n webSearch?: unknown\n imageSearch?: unknown\n }\n }\n const searchTypes: Array<'web_search' | 'image_search'> = []\n if (metadata.searchTypes?.webSearch !== undefined) {\n searchTypes.push('web_search')\n }\n if (metadata.searchTypes?.imageSearch !== undefined) {\n searchTypes.push('image_search')\n }\n result.push({\n type: 'google_search',\n ...(searchTypes.length > 0 ? { search_types: searchTypes } : {}),\n })\n break\n }\n case 'code_execution': {\n result.push({ type: 'code_execution' })\n break\n }\n case 'url_context': {\n result.push({ type: 'url_context' })\n break\n }\n case 'file_search': {\n const metadata = (getGeminiProviderToolMetadata(tool) ?? {}) as {\n fileSearchStoreNames?: Array<string>\n topK?: number\n metadataFilter?: string\n }\n result.push({\n type: 'file_search',\n ...(metadata.fileSearchStoreNames\n ? { file_search_store_names: metadata.fileSearchStoreNames }\n : {}),\n ...(metadata.topK !== undefined ? { top_k: metadata.topK } : {}),\n ...(metadata.metadataFilter !== undefined\n ? { metadata_filter: metadata.metadataFilter }\n : {}),\n })\n break\n }\n case 'computer_use': {\n const metadata = (getGeminiProviderToolMetadata(tool) ?? {}) as {\n environment?: string\n excludedPredefinedFunctions?: Array<string>\n }\n if (metadata.environment && metadata.environment !== 'browser') {\n throw new Error(\n `computer_use environment \"${metadata.environment}\" is not supported on the Gemini Interactions API. Only \"browser\" is accepted.`,\n )\n }\n result.push({\n type: 'computer_use',\n ...(metadata.environment\n ? { environment: metadata.environment as 'browser' }\n : {}),\n ...(metadata.excludedPredefinedFunctions\n ? {\n excludedPredefinedFunctions:\n metadata.excludedPredefinedFunctions,\n }\n : {}),\n })\n break\n }\n case 'google_search_retrieval':\n throw new Error(\n '`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.',\n )\n case 'google_maps':\n throw new Error(\n '`google_maps` is not yet supported on the Gemini Interactions API. Use `geminiText()` for Google Maps grounding.',\n )\n case undefined: {\n if (!tool.description) {\n throw new Error(\n `Tool ${tool.name} requires a description for the Gemini Interactions adapter`,\n )\n }\n result.push({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: sanitizeToolParameters(\n tool.inputSchema ?? { type: 'object', properties: {} },\n ),\n })\n }\n }\n }\n\n return result\n}\n\n// Map of API-level status values onto the AG-UI `finishReason` field.\n// `requires_action` is the Interactions API's signal that the model\n// produced one or more function calls and is waiting for results — we\n// always map that to 'tool_calls' regardless of whether deltas were\n// observed (a function_call may have arrived in a single delta with no\n// other content). `incomplete` is the truncation signal (max_tokens\n// exceeded etc.) — map to 'length'. `completed` is normal stop.\nfunction statusToFinishReason(\n status: Interaction['status'] | undefined,\n sawFunctionCall: boolean,\n): 'stop' | 'length' | 'tool_calls' | null {\n if (status === 'requires_action') return 'tool_calls'\n if (status === 'incomplete') return 'length'\n if (sawFunctionCall) return 'tool_calls'\n return 'stop'\n}\n\n// Statuses that mean the interaction did not produce a usable result.\n// `failed`/`cancelled` map to RUN_ERROR. `incomplete` is the model\n// hitting a stop condition (max_tokens etc.) and is reported via\n// `finishReason: 'length'` on RUN_FINISHED so callers can decide how to\n// react without it looking like a hard error.\nfunction statusIsError(\n status: Interaction['status'] | undefined,\n): status is 'failed' | 'cancelled' {\n return status === 'failed' || status === 'cancelled'\n}\n\nasync function* translateInteractionEvents(\n stream: AsyncIterable<InteractionSSEEvent>,\n model: string,\n runId: string,\n threadId: string,\n parentRunId: string | undefined,\n timestamp: number,\n adapterName: string,\n logger: InternalLogger,\n): AsyncIterable<AdapterYieldChunk> {\n const messageId = generateId(adapterName)\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let textAccumulated = ''\n let interactionId: string | undefined\n let sawFunctionCall = false\n const toolCalls = new Map<string, ToolCallState>()\n let nextToolIndex = 0\n let thinkingStepId: string | null = null\n let thinkingAccumulated = ''\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n // SDK 2.x routes events by step `index`, not by content id. We need to\n // map the index of an in-flight `function_call` step back to the tool\n // call id so subsequent `step.delta` (arguments_delta) and `step.stop`\n // events can update / close the right TOOL_CALL_*.\n const indexToToolCallId = new Map<number, string>()\n // Function-call arguments now stream as partial JSON fragments\n // (`StepDelta.ArgumentsDelta.arguments`) rather than as pre-parsed\n // object deltas. Buffer the raw strings per tool call so we can\n // attempt one JSON parse per delta and recover gracefully if the\n // fragment isn't yet syntactically complete.\n const argStringByToolCallId = new Map<string, string>()\n\n const closeReasoningIfNeeded = function* (): Generator<AdapterYieldChunk> {\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n // Reset so that a later `thought_summary` delta (the API\n // interleaves text → thought → text on some models) opens a\n // fresh reasoning block instead of re-using an already-ended\n // messageId, which would violate AG-UI ordering.\n thinkingStepId = null\n reasoningMessageId = null\n hasClosedReasoning = false\n }\n }\n\n // Seals any in-flight messages and tool calls. Called both on the\n // normal terminal path (`interaction.complete`) and on the error path\n // (`error` SSE event + premature EOF) so the StreamProcessor never\n // sees orphan TEXT_MESSAGE_START / TOOL_CALL_START / REASONING_*\n // events on RUN_ERROR.\n const closeOpenState = function* (): Generator<AdapterYieldChunk> {\n yield* closeReasoningIfNeeded()\n for (const [toolCallId, state] of toolCalls) {\n if (state.ended) continue\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n if (hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = false\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp,\n }\n }\n }\n\n const emitRunStartedIfNeeded = function* (): Generator<AdapterYieldChunk> {\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp,\n parentRunId,\n }\n }\n }\n\n for await (const event of stream) {\n logger.provider(`provider=gemini-text-interactions`, { event })\n switch (event.event_type) {\n case 'interaction.created': {\n interactionId = event.interaction.id\n yield* emitRunStartedIfNeeded()\n break\n }\n\n case 'step.start': {\n yield* emitRunStartedIfNeeded()\n const step = event.step\n const index = event.index\n switch (step.type) {\n case 'function_call': {\n yield* closeReasoningIfNeeded()\n sawFunctionCall = true\n const toolCallId = step.id\n indexToToolCallId.set(index, toolCallId)\n // `step.arguments` is required on FunctionCallStep but may\n // be an empty `{}` placeholder when streaming, where the\n // real args arrive as `arguments_delta` events. Treat both\n // uniformly: stash whatever we got, stringify once.\n const initialArgs = step.arguments\n const state: ToolCallState = {\n name: step.name,\n args: { ...initialArgs },\n index: nextToolIndex++,\n started: true,\n ended: false,\n }\n toolCalls.set(toolCallId, state)\n argStringByToolCallId.set(\n toolCallId,\n Object.keys(initialArgs).length > 0\n ? JSON.stringify(initialArgs)\n : '',\n )\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: state.name,\n toolName: state.name,\n // Bind the tool call to the same assistant message id the\n // eventual TEXT_MESSAGE_START uses so the message id stays\n // stable when a function_call arrives before any text (#477).\n parentMessageId: messageId,\n model,\n timestamp,\n index: state.index,\n }\n if (Object.keys(initialArgs).length > 0) {\n const argsJson = JSON.stringify(initialArgs)\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: argsJson,\n args: argsJson,\n }\n }\n break\n }\n case 'thought': {\n // Open the reasoning block lazily — content lands here via\n // `step.delta { thought_summary }` events. If the server\n // ships a non-empty `summary` array up-front (rare, unary\n // responses), surface it immediately.\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n for (const part of step.summary ?? []) {\n if (part.type !== 'text' || !part.text) continue\n thinkingAccumulated += part.text\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: part.text,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: part.text,\n content: thinkingAccumulated,\n }\n }\n break\n }\n case 'model_output': {\n yield* closeReasoningIfNeeded()\n // Some servers ship an initial `content` array on\n // `step.start` (notably non-streaming and ahead-of-stream\n // unary completions). Treat any prefilled text content the\n // same way a `text` step.delta would.\n for (const part of step.content ?? []) {\n if (part.type !== 'text' || !part.text) continue\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += part.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: part.text,\n content: textAccumulated,\n }\n }\n break\n }\n case 'google_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'google_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n // Unhandled step types (user_input on GET timelines,\n // mcp_server_*, google_maps_*, function_result) fall through\n // to the observability default so SDK drift is visible.\n case 'user_input':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(`gemini-text-interactions unhandled step.start`, {\n step,\n })\n break\n }\n break\n }\n\n case 'step.delta': {\n yield* emitRunStartedIfNeeded()\n const delta = event.delta\n const index = event.index\n switch (delta.type) {\n case 'text': {\n yield* closeReasoningIfNeeded()\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += delta.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: delta.text,\n content: textAccumulated,\n }\n break\n }\n case 'arguments_delta': {\n // Streamed function-call arguments. Identity (id, name) was\n // delivered on the matching `step.start` and recorded in\n // indexToToolCallId.\n const toolCallId = indexToToolCallId.get(index)\n if (!toolCallId) {\n logger.provider(\n `gemini-text-interactions arguments_delta for unknown step index`,\n { index, delta },\n )\n break\n }\n const state = toolCalls.get(toolCallId)\n if (!state) break\n const fragment = delta.arguments ?? ''\n const buffer =\n (argStringByToolCallId.get(toolCallId) ?? '') + fragment\n argStringByToolCallId.set(toolCallId, buffer)\n // Parse the accumulated buffer leniently: streamed arg fragments\n // are individually incomplete JSON, so use a partial-JSON parser\n // that tolerates truncation rather than logging a parse error per\n // fragment. Only overwrite `state.args` when we actually recovered\n // an object, so a momentarily-unparseable fragment can't reset\n // previously-merged args back to `{}`.\n const parsed = parsePartialToolArguments(buffer)\n if (parsed) state.args = parsed\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: fragment,\n args: buffer,\n }\n break\n }\n case 'thought_summary': {\n const thoughtText =\n delta.content && 'text' in delta.content ? delta.content.text : ''\n if (!thoughtText) break\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n thinkingAccumulated += thoughtText\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: thoughtText,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: thoughtText,\n content: thinkingAccumulated,\n }\n break\n }\n // The remaining StepDelta variants (image/audio/video/document\n // for output modalities a text adapter shouldn't see, tool\n // call/result deltas which are surfaced via step.start in this\n // adapter, thought_signature, annotation deltas, mcp/google\n // maps variants) fall through to the observability default.\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n case 'thought_signature':\n case 'text_annotation_delta':\n case 'code_execution_call':\n case 'code_execution_result':\n case 'url_context_call':\n case 'url_context_result':\n case 'google_search_call':\n case 'google_search_result':\n case 'file_search_call':\n case 'file_search_result':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(\n `gemini-text-interactions unhandled step.delta type`,\n { delta },\n )\n break\n }\n break\n }\n\n case 'step.stop': {\n // Close any open function_call so downstream consumers get the\n // matching TOOL_CALL_END once the arguments are complete. Other\n // step types don't carry adapter-level open state.\n const toolCallId = indexToToolCallId.get(event.index)\n if (toolCallId) {\n const state = toolCalls.get(toolCallId)\n if (state && !state.ended) {\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n indexToToolCallId.delete(event.index)\n }\n break\n }\n\n case 'interaction.status_update': {\n break\n }\n\n case 'interaction.completed': {\n if (event.interaction.id) {\n interactionId = event.interaction.id\n }\n\n yield* closeOpenState()\n\n const status = event.interaction.status\n if (statusIsError(status)) {\n const message = `Gemini Interactions ${status}: the interaction ended without a usable response.`\n logger.errors(\n 'gemini-text-interactions.translateInteractionEvents non-success status',\n {\n source: 'gemini-text-interactions.chatStream',\n status,\n interactionId,\n },\n )\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code: status,\n error: { message, code: status },\n }\n return\n }\n\n const usage = event.interaction.usage\n const finishReason = statusToFinishReason(status, sawFunctionCall)\n\n if (interactionId) {\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.interactionId',\n value: { interactionId },\n model,\n timestamp,\n }\n }\n\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp,\n finishReason,\n usage: usage\n ? {\n promptTokens: usage.total_input_tokens ?? 0,\n completionTokens: usage.total_output_tokens ?? 0,\n totalTokens: usage.total_tokens ?? 0,\n }\n : undefined,\n }\n return\n }\n\n case 'error': {\n // Close any in-flight TEXT_MESSAGE_START / TOOL_CALL_START /\n // REASONING_* so downstream consumers don't see orphan open\n // state after RUN_ERROR.\n yield* closeOpenState()\n const rawMessage = event.error?.message\n const message =\n typeof rawMessage === 'string' && rawMessage.length > 0\n ? rawMessage\n : `Gemini Interactions error (no message): ${JSON.stringify(event.error ?? {})}`\n const rawCode = event.error?.code\n const code =\n typeof rawCode === 'string' || typeof rawCode === 'number'\n ? String(rawCode)\n : undefined\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code,\n error: { message, code },\n }\n return\n }\n\n default:\n logger.provider(`gemini-text-interactions unhandled event_type`, {\n event,\n })\n break\n }\n }\n\n // Stream ended without `interaction.complete` or `error` (both `return`\n // out of the loop). Seal any in-flight TEXT/TOOL/REASONING blocks here\n // so the truncation-fallback RUN_ERROR yielded by `chatStream` doesn't\n // leave orphan `*_START` events open downstream.\n yield* closeOpenState()\n}\n\nfunction extractTextFromInteraction(interaction: Interaction): string {\n // SDK 2.x: the response carries a `steps` array; `output_text` is a\n // convenience the SDK derives from the last model output. Prefer the\n // SDK sugar when it's populated, then fall back to walking\n // model_output steps for adapters / responses that don't get the\n // sugar (e.g. older SDK builds).\n if (typeof interaction.output_text === 'string' && interaction.output_text) {\n return interaction.output_text\n }\n let text = ''\n for (const step of interaction.steps ?? []) {\n if (step.type !== 'model_output' || !step.content) continue\n for (const part of step.content) {\n if (part.type === 'text') {\n text += part.text\n }\n }\n }\n return text\n}\n\n// The live Interactions API rejects tool parameter schemas that contain\n// an empty `required: []` array with the misleading top-level error\n// `\"value at top-level must be a list\"`. Empty `properties: {}` and\n// `parameters: {}` are both fine — only the empty `required` array is\n// poison. The Zod -> JSON Schema converter (and many hand-written\n// schemas) emit `required: []` whenever a tool has zero required\n// parameters, so we strip those instances recursively before sending.\n// Non-empty `required` arrays are passed through unchanged.\nfunction sanitizeToolParameters(schema: unknown): unknown {\n if (!schema || typeof schema !== 'object') return schema\n if (Array.isArray(schema)) return schema.map(sanitizeToolParameters)\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'required' && Array.isArray(value) && value.length === 0) {\n continue\n }\n out[key] = sanitizeToolParameters(value)\n }\n return out\n}\n\n// Re-export the stream type so consumers can import it alongside the\n// adapter from a single path: `import type { GeminiInteractionsStream }\n// from '@tanstack/ai-gemini/experimental'`.\nexport type { GeminiInteractionsStream }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0LA,IAAa,gCAAb,cAOU,gBAMR;CACA,OAAyB;CACzB,OAAyB;CAEzB,sBAAwC;CAExC;CAeA,wCAAyC,IAAI,IAAoB;CAEjE,YAAY,QAAsC,OAAe;EAC/D,MAAM,CAAC,GAAG,KAAK;EACf,KAAK,SAAS,mBAAmB,MAAM;CACzC;CAEA,OAAO,WACL,SACkC;EAClC,MAAM,QAAQ,QAAQ,SAAS,WAAW,KAAK,IAAI;EACnD,MAAM,WAAW,QAAQ,YAAY,WAAW,KAAK,IAAI;EACzD,MAAM,YAAY,KAAK,IAAI;EAC3B,MAAM,EAAE,WAAW;EAOnB,IACE,CAAC,QAAQ,cAAc,2BACvB,QAAQ,SAAS,WAAW,KAC5B,QAAQ,SAAS,EAAE,EAAE,SAAS,QAE9B,KAAK,sBAAsB,OAAO,QAAQ;EAM5C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A,SACE,OAAO,SAAS,iDAAiD,EAC/D,MACF,CAAC;EAEL;CACF;CAMA,OAAO,eAAe;AACxB;AAEA,SAAS,2BAA2B,aAAkC;CAMpE,IAAI,OAAO,YAAY,gBAAgB,YAAY,YAAY,aAC7D,OAAO,YAAY;CAErB,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,YAAY,SAAS,CAAC,GAAG;EAC1C,IAAI,KAAK,SAAS,kBAAkB,CAAC,KAAK,SAAS;EACnD,KAAK,MAAM,QAAQ,KAAK,SACtB,IAAI,KAAK,SAAS,QAChB,QAAQ,KAAK;CAGnB;CACA,OAAO;AACT;AAUA,SAAS,uBAAuB,QAA0B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO;CAClD,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO,OAAO,IAAI,sBAAsB;CACnE,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,QAAQ,cAAc,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,GACjE;EAEF,IAAI,OAAO,uBAAuB,KAAK;CACzC;CACA,OAAO;AACT"}
@@ -1,5 +1,6 @@
1
1
  export { GeminiTextAdapter, createGeminiChat, geminiText, type GeminiTextConfig, type GeminiTextProviderOptions, } from './adapters/text.js';
2
2
  export { createGeminiSummarize, geminiSummarize, type GeminiSummarizeConfig, type GeminiSummarizeModel, } from './adapters/summarize.js';
3
+ export { GeminiFilesAdapter, createGeminiFiles, geminiFiles, type GeminiFilesConfig, } from './adapters/files.js';
3
4
  export { GeminiImageAdapter, createGeminiImage, geminiImage, type GeminiImageConfig, } from './adapters/image.js';
4
5
  export type { GeminiImageProviderOptions, GeminiNativeImageConfig, GeminiNativeImageProviderOptions, GeminiAnyImageProviderOptions, GeminiImageModelProviderOptionsByName, GeminiAspectRatio, GeminiImageModelSizeByName, GeminiStandardImageAspectRatio, GeminiExtendedImageAspectRatio, Gemini31FlashImageSize, Gemini31FlashLiteImageSize, Gemini3ProImageSize, Gemini25FlashImageSize, GeminiNativeImageSize, PersonGeneration, SafetyFilterLevel, ImagePromptLanguage, SafetySetting, ThinkingConfig, ImageConfig, ContentUnion, } from './image/image-provider-options.js';
5
6
  export { HarmBlockThreshold, HarmCategory } from '@google/genai';
package/dist/esm/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { GEMINI_AUDIO_MODELS, GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS, GEMINI_EMBEDDING_MODELS, GEMINI_IMAGE_MODELS, GEMINI_INTERACTIONS_VIDEO_MODELS, GEMINI_MODELS, GEMINI_TTS_MODELS, GEMINI_TTS_VOICES, GEMINI_VIDEO_MODELS } from "./model-meta.js";
2
2
  import { GeminiTextAdapter, createGeminiChat, geminiText } from "./adapters/text.js";
3
3
  import { createGeminiSummarize, geminiSummarize } from "./adapters/summarize.js";
4
+ import { GeminiFilesAdapter, createGeminiFiles, geminiFiles } from "./adapters/files.js";
4
5
  import { GEMINI_NATIVE_IMAGE_MODELS, isGeminiNativeImageModel } from "./image/image-provider-options.js";
5
6
  import { GeminiImageAdapter, createGeminiImage, geminiImage } from "./adapters/image.js";
6
7
  import { geminiVideoPart, uploadGeminiFile } from "./files/index.js";
@@ -13,4 +14,4 @@ import { geminiRealtimeToken } from "./realtime/token.js";
13
14
  import { geminiRealtime } from "./realtime/adapter.js";
14
15
  import "./realtime/index.js";
15
16
  import { HarmBlockThreshold, HarmCategory } from "@google/genai";
16
- export { GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS, GEMINI_EMBEDDING_MODELS, GEMINI_MODELS, GEMINI_NATIVE_IMAGE_MODELS, GEMINI_VIDEO_DURATIONS, GeminiAudioAdapter, GEMINI_AUDIO_MODELS as GeminiAudioModels, GeminiEmbeddingAdapter, GeminiImageAdapter, GEMINI_IMAGE_MODELS as GeminiImageModels, GEMINI_INTERACTIONS_VIDEO_MODELS as GeminiInteractionsVideoModels, GeminiTTSAdapter, GEMINI_TTS_MODELS as GeminiTTSModels, GEMINI_TTS_VOICES as GeminiTTSVoices, GeminiTextAdapter, GEMINI_MODELS as GeminiTextModels, GeminiVideoAdapter, GEMINI_VIDEO_MODELS as GeminiVideoModels, HarmBlockThreshold, HarmCategory, createGeminiAudio, createGeminiChat, createGeminiEmbedding, createGeminiImage, createGeminiSpeech, createGeminiSummarize, createGeminiVideo, geminiAudio, geminiEmbedding, geminiImage, geminiRealtime, geminiRealtimeToken, geminiSpeech, geminiSummarize, geminiText, geminiVideo, geminiVideoPart, getGeminiVideoDurationOptions, isGeminiNativeImageModel, isInteractionsVideoModel, parseGeminiOmniVideoSize, uploadGeminiFile };
17
+ export { GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS, GEMINI_EMBEDDING_MODELS, GEMINI_MODELS, GEMINI_NATIVE_IMAGE_MODELS, GEMINI_VIDEO_DURATIONS, GeminiAudioAdapter, GEMINI_AUDIO_MODELS as GeminiAudioModels, GeminiEmbeddingAdapter, GeminiFilesAdapter, GeminiImageAdapter, GEMINI_IMAGE_MODELS as GeminiImageModels, GEMINI_INTERACTIONS_VIDEO_MODELS as GeminiInteractionsVideoModels, GeminiTTSAdapter, GEMINI_TTS_MODELS as GeminiTTSModels, GEMINI_TTS_VOICES as GeminiTTSVoices, GeminiTextAdapter, GEMINI_MODELS as GeminiTextModels, GeminiVideoAdapter, GEMINI_VIDEO_MODELS as GeminiVideoModels, HarmBlockThreshold, HarmCategory, createGeminiAudio, createGeminiChat, createGeminiEmbedding, createGeminiFiles, createGeminiImage, createGeminiSpeech, createGeminiSummarize, createGeminiVideo, geminiAudio, geminiEmbedding, geminiFiles, geminiImage, geminiRealtime, geminiRealtimeToken, geminiSpeech, geminiSummarize, geminiText, geminiVideo, geminiVideoPart, getGeminiVideoDurationOptions, isGeminiNativeImageModel, isInteractionsVideoModel, parseGeminiOmniVideoSize, uploadGeminiFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-gemini",
3
- "version": "0.32.1",
3
+ "version": "0.33.1",
4
4
  "description": "Google Gemini adapter for TanStack AI chat, images, speech, audio generation, and structured outputs.",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -63,13 +63,13 @@
63
63
  "@tanstack/ai-utils": "^0.4.1"
64
64
  },
65
65
  "peerDependencies": {
66
- "@tanstack/ai": "^0.59.0"
66
+ "@tanstack/ai": "^0.61.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@vitest/coverage-v8": "4.1.10",
70
70
  "vite": "^8.2.1",
71
71
  "zod": "^4.2.0",
72
- "@tanstack/ai": "0.59.0"
72
+ "@tanstack/ai": "0.61.0"
73
73
  },
74
74
  "scripts": {
75
75
  "build": "vite build",
@@ -0,0 +1,84 @@
1
+ import {
2
+ BaseFilesAdapter,
3
+ normalizeFileUploadInput,
4
+ } from '@tanstack/ai/adapters'
5
+ import { createGeminiClient, getGeminiApiKeyFromEnv } from '../utils/client'
6
+ import type { File as GeminiFile, GoogleGenAI } from '@google/genai'
7
+ import type { FileHandle, FileUploadInput } from '@tanstack/ai/adapters'
8
+ import type { GeminiClientConfig } from '../utils/client'
9
+
10
+ export interface GeminiFilesConfig extends GeminiClientConfig {}
11
+
12
+ /**
13
+ * Gemini Files adapter — uploads media to the Gemini Files API and references
14
+ * it by its file URI. Pair with `geminiText()` / `geminiImage()`: reference the
15
+ * returned handle via `fileSourceFromHandle(handle)`, which uses the handle URI
16
+ * (Gemini fetches it server-side as `fileData.fileUri`).
17
+ */
18
+ export class GeminiFilesAdapter extends BaseFilesAdapter<'gemini'> {
19
+ readonly name = 'gemini' as const
20
+ private readonly client: GoogleGenAI
21
+
22
+ constructor(config: GeminiFilesConfig) {
23
+ super()
24
+ this.client = createGeminiClient(config)
25
+ }
26
+
27
+ async upload(input: FileUploadInput): Promise<FileHandle<'gemini'>> {
28
+ const { blob, mimeType } = normalizeFileUploadInput(input)
29
+ const file = await this.client.files.upload({
30
+ file: blob,
31
+ ...(mimeType ? { config: { mimeType } } : {}),
32
+ })
33
+ return toFileHandle(file)
34
+ }
35
+
36
+ async get(id: string): Promise<FileHandle<'gemini'>> {
37
+ return toFileHandle(await this.client.files.get({ name: id }))
38
+ }
39
+
40
+ async delete(id: string): Promise<void> {
41
+ await this.client.files.delete({ name: id })
42
+ }
43
+ }
44
+
45
+ function toFileHandle(file: GeminiFile): FileHandle<'gemini'> {
46
+ // `name` (e.g. "files/abc-123") is the lifecycle id; `uri` is the URL Gemini
47
+ // fetches when the handle is referenced in a message.
48
+ if (!file.name) {
49
+ throw new Error('gemini: files.upload returned a file without a name')
50
+ }
51
+ const expiresAt = file.expirationTime
52
+ ? Date.parse(file.expirationTime)
53
+ : undefined
54
+ return {
55
+ id: file.name,
56
+ provider: 'gemini',
57
+ ...(file.uri ? { uri: file.uri } : {}),
58
+ ...(file.mimeType ? { mimeType: file.mimeType } : {}),
59
+ ...(file.sizeBytes ? { sizeBytes: Number(file.sizeBytes) } : {}),
60
+ ...(expiresAt !== undefined && !Number.isNaN(expiresAt)
61
+ ? { expiresAt }
62
+ : {}),
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Create a Gemini Files adapter with an explicit API key.
68
+ */
69
+ export function createGeminiFiles(
70
+ apiKey: string,
71
+ config?: Omit<GeminiFilesConfig, 'apiKey'>,
72
+ ): GeminiFilesAdapter {
73
+ return new GeminiFilesAdapter({ ...config, apiKey })
74
+ }
75
+
76
+ /**
77
+ * Create a Gemini Files adapter, reading the API key from `GOOGLE_API_KEY` /
78
+ * `GEMINI_API_KEY`.
79
+ */
80
+ export function geminiFiles(
81
+ config?: Omit<GeminiFilesConfig, 'apiKey'>,
82
+ ): GeminiFilesAdapter {
83
+ return createGeminiFiles(getGeminiApiKeyFromEnv(), config)
84
+ }
@@ -1,4 +1,8 @@
1
- import { resolveMediaPrompt } from '@tanstack/ai'
1
+ import {
2
+ fileReferenceFor,
3
+ isFileSource,
4
+ resolveMediaPrompt,
5
+ } from '@tanstack/ai'
2
6
  import { BaseImageAdapter } from '@tanstack/ai/adapters'
3
7
  import {
4
8
  createGeminiClient,
@@ -75,6 +79,8 @@ export class GeminiImageAdapter<
75
79
  > {
76
80
  override readonly kind = 'image' as const
77
81
  readonly name = 'gemini' as const
82
+ // Consumes Gemini Files API references (geminiFiles()) as fileData.fileUri.
83
+ override readonly supportsFileSources = true
78
84
 
79
85
  // Type-only property - never assigned at runtime
80
86
  declare '~types': {
@@ -270,10 +276,14 @@ export class GeminiImageAdapter<
270
276
  // `fileData` and Gemini fetches them server-side — same as the chat
271
277
  // adapter. Fetching locally and inlining as base64 double-buffers the
272
278
  // image and OOMs on memory-constrained runtimes (e.g. Cloudflare
273
- // Workers).
279
+ // Workers). A file source's handle is the file URI (throws when another
280
+ // provider issued it).
281
+ const fileUri = isFileSource(part.source)
282
+ ? fileReferenceFor(part.source, this.name)
283
+ : part.source.value
274
284
  return {
275
285
  fileData: {
276
- fileUri: part.source.value,
286
+ fileUri,
277
287
  mimeType: part.source.mimeType ?? 'image/jpeg',
278
288
  },
279
289
  }