@warlock.js/ai-google 5.39.1 → 5.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/model.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/model.ts"],"sourcesContent":["import {\n attachCost,\n InvalidRequestError,\n resolveStreamChunks,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type {\n GenerateContentConfig,\n GenerateContentResponse,\n GoogleGenAI,\n GroundingMetadata,\n Part,\n Tool,\n} from \"@google/genai\";\nimport { applyGrounding, groundingMetadata } from \"./utils/grounding\";\nimport { mergeProviderBody } from \"./provider-options\";\nimport type { GoogleModelConfig } from \"./config.type\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n applyGoogleUsage,\n mapFinishReason,\n toGoogleContents,\n toGoogleTools,\n wrapGoogleError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst GOOGLE_WIRE_FORMAT = \"google\";\n\n/**\n * Bucketed `thinkingBudget` (token caps) for the neutral\n * `reasoning.effort` levels when the caller gives no explicit\n * `reasoning.maxTokens`. Gemini 2.5 accepts a positive budget as a cap\n * on the thinking phase; these mirror the spread the OpenAI\n * `reasoning_effort` low/medium/high tiers imply. The installed\n * `@google/genai` `ThinkingConfig` declaration documents that allowed\n * ranges are model-dependent, so retain the existing conservative 24,576\n * cap for the new tiers rather than sending a budget unsupported by Flash.\n */\nconst EFFORT_THINKING_BUDGET: Record<Exclude<ReasoningEffort, \"none\">, number> = {\n minimal: 1024,\n low: 1024,\n medium: 8192,\n high: 24576,\n xhigh: 24576,\n max: 24576,\n};\n\n/**\n * Google Gemini-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the `@google/genai` SDK\n * (`models.generateContent` / `generateContentStream`).\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as per-call defaults.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Gemini shapes (systemInstruction hoisting, `model` role,\n * `functionCall` / `functionResponse` parts, inline image bytes) on\n * the way out, and Gemini's candidate/parts response (text, function\n * calls, finish reason, token usage) back into neutral shapes on the\n * way in.\n * - Does NOT own: dispatching tools, looping, history, retries — those\n * are agent concerns. The model is a per-call protocol adapter.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across calls\"): the `GoogleGenAI` client is reused for the SDK's\n * lifetime.\n *\n * @example\n * import { GoogleGenAI } from \"@google/genai\";\n * const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const model = new GoogleModel(ai, { name: \"gemini-2.5-flash\" });\n *\n * const myAgent = agent({ model, tools: [searchTool] });\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class GoogleModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly ai: GoogleGenAI;\n private readonly config: GoogleModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(ai: GoogleGenAI, config: GoogleModelConfig, provider: string = \"google\") {\n this.ai = ai;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n const multimodal = config.vision ?? inferVisionCapability(config.name);\n\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: multimodal,\n // Every Gemini 2.5 model thinks; older families harmlessly ignore\n // an empty thinking budget. Defaulting `true` lets the agent\n // forward reasoning options; an explicit `false` opts a model out.\n reasoning: config.reasoning ?? true,\n // Gemini reports cache-read hits (`cachedContentTokenCount`) on\n // every call via implicit caching, and accepts explicit context\n // caching. Read-side accounting is always honored.\n promptCaching: true,\n // The multimodal Gemini families that accept images also accept\n // audio and PDF/document parts. Mirror the vision inference unless\n // explicitly overridden.\n audio: config.audio ?? multimodal,\n pdf: config.pdf ?? multimodal,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to\n * `generateContent`, waits for the terminal response, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options`\n * override the instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContent call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let response: GenerateContentResponse;\n\n try {\n response = await this.ai.models.generateContent({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls = this.extractToolCalls(response);\n const finishReason = toolCalls\n ? \"tool_calls\"\n : mapFinishReason(response.candidates?.[0]?.finishReason);\n const usage = this.extractUsage(response);\n const grounding = new Map<number, GroundingMetadata>();\n applyGrounding(usage, grounding, response);\n const providerMetadata = groundingMetadata(grounding);\n attachCost(usage, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContent call succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n ...(providerMetadata ? { providerMetadata } : {}),\n content: response.text ?? \"\",\n finishReason,\n usage,\n toolCalls,\n };\n }\n\n /** Count native input tokens with the same converted content, system and tools. */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const { systemInstruction, contents } = toGoogleContents(messages);\n const config = this.buildConfig(systemInstruction, options);\n if (config.cachedContent !== undefined) {\n throw new InvalidRequestError(\n \"The Google SDK countTokens endpoint cannot count a cachedContent reference.\",\n { reason: \"count-unsupported\" },\n );\n }\n try {\n const response = this.ai.vertexai\n ? await this.ai.models.countTokens({\n model: this.name,\n contents,\n config: {\n ...(config.systemInstruction !== undefined\n ? { systemInstruction: config.systemInstruction }\n : {}),\n ...(config.tools !== undefined ? { tools: config.tools as Tool[] } : {}),\n ...(config.abortSignal ? { abortSignal: config.abortSignal } : {}),\n ...(config.httpOptions ? { httpOptions: config.httpOptions } : {}),\n },\n })\n : await this.countDeveloperTokens(contents, config);\n if (response.totalTokens === undefined)\n throw new InvalidRequestError(\"Google countTokens returned no totalTokens.\");\n return response.totalTokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * REST counts the full generation request, unlike the typed Developer API\n * converter in @google/genai 2.19.0. See https://ai.google.dev/api/tokens.\n * extraBody keeps the SDK's auth, fetch, base URL, retries and cancellation.\n */\n private countDeveloperTokens(\n contents: ReturnType<typeof toGoogleContents>[\"contents\"],\n config: GenerateContentConfig,\n ) {\n config.abortSignal?.throwIfAborted();\n\n const {\n systemInstruction,\n serviceTier,\n tools,\n toolConfig,\n safetySettings,\n cachedContent,\n abortSignal,\n httpOptions,\n ...generationConfig\n } = config;\n // Automatic function calling is SDK-only, never a REST generation field.\n delete generationConfig.automaticFunctionCalling;\n const model = this.name.startsWith(\"models/\") ? this.name : `models/${this.name}`;\n\n return this.ai.models.countTokens({\n model: this.name,\n contents,\n config: {\n abortSignal,\n httpOptions: {\n ...httpOptions,\n extraBody: {\n ...httpOptions?.extraBody,\n // The SDK merges extraBody before JSON serialization. undefined\n // removes its contents field: REST accepts only one input form.\n contents: undefined,\n generateContentRequest: {\n model,\n contents,\n ...(serviceTier !== undefined ? { serviceTier } : {}),\n ...(systemInstruction !== undefined\n ? { systemInstruction: { parts: [{ text: systemInstruction }] } }\n : {}),\n ...(tools !== undefined ? { tools } : {}),\n ...(toolConfig !== undefined ? { toolConfig } : {}),\n ...(safetySettings !== undefined ? { safetySettings } : {}),\n ...(cachedContent !== undefined ? { cachedContent } : {}),\n ...(Object.keys(generationConfig).length > 0 ? { generationConfig } : {}),\n },\n },\n },\n },\n });\n }\n\n /**\n * Incremental streaming completion via `generateContentStream`.\n * Yields neutral `ModelStreamChunk`s — `delta` for text, `tool-call`\n * per function call (Gemini emits a fully-formed call, not partial\n * JSON), and a terminal `done` with the final finish reason + usage.\n *\n * With `options.streamChunks` it also yields `reasoning` for thought\n * parts (only sent when `thinkingConfig.includeThoughts` is on — set it\n * through `providerOptions.google.body`) and `usage` whenever a chunk\n * carries `usageMetadata`. No `tool-args`: calls arrive whole.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContentStream call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let iterable: AsyncGenerator<GenerateContentResponse>;\n\n try {\n iterable = await this.ai.models.generateContentStream({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawFinishReason: string | undefined;\n let sawToolCall = false;\n const usage: Usage = { input: 0, output: 0, total: 0 };\n const want = resolveStreamChunks(options);\n const grounding = new Map<number, GroundingMetadata>();\n\n try {\n for await (const chunk of iterable) {\n applyGrounding(usage, grounding, chunk);\n // Thought parts (`thought: true`, sent when `thinkingConfig.includeThoughts`\n // is on) carry the thought summary in `text`; the SDK's `chunk.text`\n // getter already leaves them out of the answer.\n if (want.reasoning) {\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n if (part.thought === true && typeof part.text === \"string\" && part.text !== \"\") {\n yield { type: \"reasoning\", delta: part.text };\n }\n }\n }\n\n const text = chunk.text;\n\n if (text) {\n yield { type: \"delta\", content: text };\n }\n\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n const toolCall = this.partToToolCall(part);\n\n if (!toolCall) {\n continue;\n }\n\n sawToolCall = true;\n\n yield {\n type: \"tool-call\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input,\n ...(toolCall.providerMetadata ? { providerMetadata: toolCall.providerMetadata } : {}),\n };\n }\n\n const candidateFinish = chunk.candidates?.[0]?.finishReason;\n\n if (candidateFinish) {\n rawFinishReason = candidateFinish;\n }\n\n if (chunk.usageMetadata) {\n applyGoogleUsage(usage, chunk.usageMetadata);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = sawToolCall ? \"tool_calls\" : mapFinishReason(rawFinishReason);\n\n attachCost(usage, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContentStream call succeeded\", {\n finishReason,\n usage,\n });\n\n const providerMetadata = groundingMetadata(grounding);\n yield { type: \"done\", finishReason, usage, ...(providerMetadata ? { providerMetadata } : {}) };\n }\n\n /**\n * Assemble the `GenerateContentConfig` shared by `complete()` and\n * `stream()`: inference params, hoisted system instruction,\n * cancellation signal, and conditional tools + native structured\n * output.\n */\n private buildConfig(\n systemInstruction: string | undefined,\n options: ModelCallOptions | undefined,\n ): GenerateContentConfig {\n const temperature = options?.temperature ?? this.config.temperature;\n const maxOutputTokens = options?.maxTokens ?? this.config.maxTokens;\n\n return mergeProviderBody<GenerateContentConfig>(\n {\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n ...this.buildTools(options),\n ...this.buildStructuredOutput(options?.responseSchema),\n ...this.buildThinking(options?.reasoning),\n },\n options,\n );\n }\n\n /**\n * Translate the neutral `reasoning` option into Gemini's\n * `thinkingConfig`. `reasoning.maxTokens` maps directly to\n * `thinkingBudget` (token cap on the thinking phase); when only\n * `reasoning.effort` is given it is bucketed into a budget. Emitted\n * only when the model is `reasoning`-capable — a `false` capability\n * (config override) drops it so a non-thinking model never receives\n * an unsupported `thinkingConfig`.\n *\n * Gemini's `thinkingBudget` semantics: `0` disables thinking, `-1`\n * lets the model decide automatically. A positive value caps the\n * thinking tokens. The neutral `effort: \"none\"` (\"run without\n * reasoning\") maps to `thinkingBudget: 0`.\n */\n private buildThinking(\n reasoning: ModelCallOptions[\"reasoning\"],\n ): Pick<GenerateContentConfig, \"thinkingConfig\"> {\n if (!reasoning || !this.capabilities.reasoning) {\n return {};\n }\n\n // `effort: \"none\"` = explicit \"run without reasoning\". Gemini disables\n // thinking with `thinkingBudget: 0` (its native off switch), so emit\n // that rather than omitting the config — an omitted config lets a\n // thinking model reason at its default budget.\n if (reasoning.effort === \"none\") {\n return { thinkingConfig: { thinkingBudget: 0 } };\n }\n\n const thinkingBudget =\n reasoning.maxTokens ??\n (reasoning.effort ? EFFORT_THINKING_BUDGET[reasoning.effort] : undefined);\n\n if (thinkingBudget === undefined) {\n return {};\n }\n\n return { thinkingConfig: { thinkingBudget } };\n }\n\n /**\n * Spread-friendly tools fragment. Empty object when no tools were\n * supplied so the caller can unconditionally spread it. Function tools\n * come first; `ai.providerTool({ provider: \"google\" })` definitions\n * (`{ googleSearch: {} }`, `{ codeExecution: {} }`, `{ urlContext: {} }`,\n * …) follow verbatim as their own `Tool` entries. Other providers'\n * definitions are skipped with a warning.\n */\n private buildTools(options: ModelCallOptions | undefined): Pick<GenerateContentConfig, \"tools\"> {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [GOOGLE_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped: Tool[] = [...(toGoogleTools(tools) ?? []), ...(definitions as unknown as Tool[])];\n\n return mapped.length > 0 ? { tools: mapped } : {};\n }\n\n /**\n * Translate the neutral `responseSchema` into Gemini's native JSON\n * structured output (`responseMimeType: \"application/json\"` +\n * `responseJsonSchema`, which takes a raw JSON Schema directly).\n * Emitted only when the model is `structuredOutput`-capable and the\n * schema is an object root — otherwise the agent's soft prompt hint\n * + client-side `validate()` carry shape.\n */\n private buildStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n ): Pick<GenerateContentConfig, \"responseMimeType\" | \"responseJsonSchema\"> {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return {};\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return {};\n }\n\n return {\n responseMimeType: \"application/json\",\n responseJsonSchema: responseSchema,\n };\n }\n\n /**\n * Reshape Gemini's function-call content parts into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no functions so callers can branch on presence.\n *\n * Reads `candidates[0].content.parts` directly rather than the\n * `response.functionCalls` getter: the getter discards the\n * part-level `thoughtSignature`, and Gemini \"thinking\" models 400\n * the follow-up turn if that signature is not echoed back. See\n * `partToToolCall`.\n */\n private extractToolCalls(response: GenerateContentResponse): ModelToolCallRequest[] | undefined {\n const parts = response.candidates?.[0]?.content?.parts ?? [];\n const toolCalls = parts\n .map((part) => this.partToToolCall(part))\n .filter((call): call is ModelToolCallRequest => call !== undefined);\n\n return toolCalls.length > 0 ? toolCalls : undefined;\n }\n\n /**\n * Map a single Gemini `Part` to a neutral `ModelToolCallRequest`,\n * or `undefined` when the part is not a function call. The part's\n * `thoughtSignature` (opaque, set by thinking models) is carried on\n * `providerMetadata` so `toGoogleContents` can replay it on the\n * assistant turn — Gemini rejects the next request without it.\n */\n private partToToolCall(part: Part): ModelToolCallRequest | undefined {\n if (!part.functionCall) {\n return undefined;\n }\n\n const call = part.functionCall;\n\n return {\n // The Gemini Developer API does not assign function-call ids\n // (only Vertex parallel-calling does). Fall back to the function\n // name so the neutral `toolCallId` is non-empty and the echoed\n // `functionResponse.name` resolves — Gemini matches a result to\n // its call by name. See decisions §49.\n id: call.id ?? call.name ?? \"\",\n name: call.name ?? \"\",\n input: (call.args ?? {}) as Record<string, unknown>,\n ...(part.thoughtSignature\n ? { providerMetadata: { thoughtSignature: part.thoughtSignature } }\n : {}),\n };\n }\n\n /**\n * Normalize Gemini's `usageMetadata` into the neutral `Usage` shape\n * via the shared {@link applyGoogleUsage} mapper (the same one the\n * streaming loop and the Gemini image model use). Absent usage\n * collapses to zeros.\n */\n private extractUsage(response: GenerateContentResponse): Usage {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n if (response.usageMetadata) {\n applyGoogleUsage(usage, response.usageMetadata);\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy\n * and emit the standard error log line before it propagates.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapGoogleError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,MAAM,aAAa;;AAGnB,MAAM,qBAAqB;;;;;;;;;;;AAY3B,MAAM,yBAA2E;CAC/E,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,cAAb,MAAkD;CAUhD,AAAO,YAAY,IAAiB,QAA2B,WAAmB,UAAU;gBAF1D;EAGhC,KAAK,KAAK;EACV,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,MAAM,aAAa,OAAO,UAAU,sBAAsB,OAAO,IAAI;EAErE,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB;GAC7C,QAAQ;GAIR,WAAW,OAAO,aAAa;GAI/B,eAAe;GAIf,OAAO,OAAO,SAAS;GACvB,KAAK,OAAO,OAAO;EACrB;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAC7F,KAAK,OAAO,MAAM,YAAY,WAAW,iCAAiC;GACxE,OAAO,KAAK;GACZ,cAAc,SAAS;GACvB,WAAW;GAC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AErD,IAAI,SAAS,eACX,iBAAiB,OAAO,SAAS,aAAa;EAGhD,OAAO;CACT;;;;;CAMA,AAAQ,WAAW,QAAiB;EAClC,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/model.ts"],"sourcesContent":["import {\n attachCost,\n InvalidRequestError,\n resolveStreamChunks,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type {\n GenerateContentConfig,\n GenerateContentResponse,\n GoogleGenAI,\n GroundingMetadata,\n Part,\n Tool,\n} from \"@google/genai\";\nimport { isSearchDefinition, searchBudgetOf } from \"./search-budget\";\nimport { applyGrounding, groundingMetadata } from \"./utils/grounding\";\nimport { mergeProviderBody } from \"./provider-options\";\nimport type { GoogleModelConfig } from \"./config.type\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n applyGoogleUsage,\n mapFinishReason,\n toGoogleContents,\n toGoogleTools,\n wrapGoogleError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst GOOGLE_WIRE_FORMAT = \"google\";\n\n/**\n * Bucketed `thinkingBudget` (token caps) for the neutral\n * `reasoning.effort` levels when the caller gives no explicit\n * `reasoning.maxTokens`. Gemini 2.5 accepts a positive budget as a cap\n * on the thinking phase; these mirror the spread the OpenAI\n * `reasoning_effort` low/medium/high tiers imply. The installed\n * `@google/genai` `ThinkingConfig` declaration documents that allowed\n * ranges are model-dependent, so retain the existing conservative 24,576\n * cap for the new tiers rather than sending a budget unsupported by Flash.\n */\nconst EFFORT_THINKING_BUDGET: Record<Exclude<ReasoningEffort, \"none\">, number> = {\n minimal: 1024,\n low: 1024,\n medium: 8192,\n high: 24576,\n xhigh: 24576,\n max: 24576,\n};\n\n/**\n * Google Gemini-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the `@google/genai` SDK\n * (`models.generateContent` / `generateContentStream`).\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as per-call defaults.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Gemini shapes (systemInstruction hoisting, `model` role,\n * `functionCall` / `functionResponse` parts, inline image bytes) on\n * the way out, and Gemini's candidate/parts response (text, function\n * calls, finish reason, token usage) back into neutral shapes on the\n * way in.\n * - Does NOT own: dispatching tools, looping, history, retries — those\n * are agent concerns. The model is a per-call protocol adapter.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across calls\"): the `GoogleGenAI` client is reused for the SDK's\n * lifetime.\n *\n * @example\n * import { GoogleGenAI } from \"@google/genai\";\n * const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const model = new GoogleModel(ai, { name: \"gemini-2.5-flash\" });\n *\n * const myAgent = agent({ model, tools: [searchTool] });\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class GoogleModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly ai: GoogleGenAI;\n private readonly config: GoogleModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(ai: GoogleGenAI, config: GoogleModelConfig, provider: string = \"google\") {\n this.ai = ai;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n const multimodal = config.vision ?? inferVisionCapability(config.name);\n\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: multimodal,\n // Every Gemini 2.5 model thinks; older families harmlessly ignore\n // an empty thinking budget. Defaulting `true` lets the agent\n // forward reasoning options; an explicit `false` opts a model out.\n reasoning: config.reasoning ?? true,\n // Gemini reports cache-read hits (`cachedContentTokenCount`) on\n // every call via implicit caching, and accepts explicit context\n // caching. Read-side accounting is always honored.\n promptCaching: true,\n // The multimodal Gemini families that accept images also accept\n // audio and PDF/document parts. Mirror the vision inference unless\n // explicitly overridden.\n audio: config.audio ?? multimodal,\n pdf: config.pdf ?? multimodal,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to\n * `generateContent`, waits for the terminal response, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options`\n * override the instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContent call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let response: GenerateContentResponse;\n\n try {\n response = await this.ai.models.generateContent({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls = this.extractToolCalls(response);\n const finishReason = toolCalls\n ? \"tool_calls\"\n : mapFinishReason(response.candidates?.[0]?.finishReason);\n const usage = this.extractUsage(response);\n const grounding = new Map<number, GroundingMetadata>();\n applyGrounding(usage, grounding, response);\n searchBudgetOf(options)?.record(usage.serverToolUse?.webSearchRequests ?? 0);\n const providerMetadata = groundingMetadata(grounding);\n attachCost(usage, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContent call succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n ...(providerMetadata ? { providerMetadata } : {}),\n content: response.text ?? \"\",\n finishReason,\n usage,\n toolCalls,\n };\n }\n\n /** Count native input tokens with the same converted content, system and tools. */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const { systemInstruction, contents } = toGoogleContents(messages);\n const config = this.buildConfig(systemInstruction, options);\n if (config.cachedContent !== undefined) {\n throw new InvalidRequestError(\n \"The Google SDK countTokens endpoint cannot count a cachedContent reference.\",\n { reason: \"count-unsupported\" },\n );\n }\n try {\n const response = this.ai.vertexai\n ? await this.ai.models.countTokens({\n model: this.name,\n contents,\n config: {\n ...(config.systemInstruction !== undefined\n ? { systemInstruction: config.systemInstruction }\n : {}),\n ...(config.tools !== undefined ? { tools: config.tools as Tool[] } : {}),\n ...(config.abortSignal ? { abortSignal: config.abortSignal } : {}),\n ...(config.httpOptions ? { httpOptions: config.httpOptions } : {}),\n },\n })\n : await this.countDeveloperTokens(contents, config);\n if (response.totalTokens === undefined)\n throw new InvalidRequestError(\"Google countTokens returned no totalTokens.\");\n return response.totalTokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * REST counts the full generation request, unlike the typed Developer API\n * converter in @google/genai 2.19.0. See https://ai.google.dev/api/tokens.\n * extraBody keeps the SDK's auth, fetch, base URL, retries and cancellation.\n */\n private countDeveloperTokens(\n contents: ReturnType<typeof toGoogleContents>[\"contents\"],\n config: GenerateContentConfig,\n ) {\n config.abortSignal?.throwIfAborted();\n\n const {\n systemInstruction,\n serviceTier,\n tools,\n toolConfig,\n safetySettings,\n cachedContent,\n abortSignal,\n httpOptions,\n ...generationConfig\n } = config;\n // Automatic function calling is SDK-only, never a REST generation field.\n delete generationConfig.automaticFunctionCalling;\n const model = this.name.startsWith(\"models/\") ? this.name : `models/${this.name}`;\n\n return this.ai.models.countTokens({\n model: this.name,\n contents,\n config: {\n abortSignal,\n httpOptions: {\n ...httpOptions,\n extraBody: {\n ...httpOptions?.extraBody,\n // The SDK merges extraBody before JSON serialization. undefined\n // removes its contents field: REST accepts only one input form.\n contents: undefined,\n generateContentRequest: {\n model,\n contents,\n ...(serviceTier !== undefined ? { serviceTier } : {}),\n ...(systemInstruction !== undefined\n ? { systemInstruction: { parts: [{ text: systemInstruction }] } }\n : {}),\n ...(tools !== undefined ? { tools } : {}),\n ...(toolConfig !== undefined ? { toolConfig } : {}),\n ...(safetySettings !== undefined ? { safetySettings } : {}),\n ...(cachedContent !== undefined ? { cachedContent } : {}),\n ...(Object.keys(generationConfig).length > 0 ? { generationConfig } : {}),\n },\n },\n },\n },\n });\n }\n\n /**\n * Incremental streaming completion via `generateContentStream`.\n * Yields neutral `ModelStreamChunk`s — `delta` for text, `tool-call`\n * per function call (Gemini emits a fully-formed call, not partial\n * JSON), and a terminal `done` with the final finish reason + usage.\n *\n * With `options.streamChunks` it also yields `reasoning` for thought\n * parts (only sent when `thinkingConfig.includeThoughts` is on — set it\n * through `providerOptions.google.body`) and `usage` whenever a chunk\n * carries `usageMetadata`. No `tool-args`: calls arrive whole.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContentStream call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let iterable: AsyncGenerator<GenerateContentResponse>;\n\n try {\n iterable = await this.ai.models.generateContentStream({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawFinishReason: string | undefined;\n let sawToolCall = false;\n const usage: Usage = { input: 0, output: 0, total: 0 };\n const want = resolveStreamChunks(options);\n const grounding = new Map<number, GroundingMetadata>();\n\n try {\n for await (const chunk of iterable) {\n applyGrounding(usage, grounding, chunk);\n // Thought parts (`thought: true`, sent when `thinkingConfig.includeThoughts`\n // is on) carry the thought summary in `text`; the SDK's `chunk.text`\n // getter already leaves them out of the answer.\n if (want.reasoning) {\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n if (part.thought === true && typeof part.text === \"string\" && part.text !== \"\") {\n yield { type: \"reasoning\", delta: part.text };\n }\n }\n }\n\n const text = chunk.text;\n\n if (text) {\n yield { type: \"delta\", content: text };\n }\n\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n const toolCall = this.partToToolCall(part);\n\n if (!toolCall) {\n continue;\n }\n\n sawToolCall = true;\n\n yield {\n type: \"tool-call\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input,\n ...(toolCall.providerMetadata ? { providerMetadata: toolCall.providerMetadata } : {}),\n };\n }\n\n const candidateFinish = chunk.candidates?.[0]?.finishReason;\n\n if (candidateFinish) {\n rawFinishReason = candidateFinish;\n }\n\n if (chunk.usageMetadata) {\n applyGoogleUsage(usage, chunk.usageMetadata);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = sawToolCall ? \"tool_calls\" : mapFinishReason(rawFinishReason);\n\n attachCost(usage, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContentStream call succeeded\", {\n finishReason,\n usage,\n });\n\n searchBudgetOf(options)?.record(usage.serverToolUse?.webSearchRequests ?? 0);\n const providerMetadata = groundingMetadata(grounding);\n yield { type: \"done\", finishReason, usage, ...(providerMetadata ? { providerMetadata } : {}) };\n }\n\n /**\n * Assemble the `GenerateContentConfig` shared by `complete()` and\n * `stream()`: inference params, hoisted system instruction,\n * cancellation signal, and conditional tools + native structured\n * output.\n */\n private buildConfig(\n systemInstruction: string | undefined,\n options: ModelCallOptions | undefined,\n ): GenerateContentConfig {\n const temperature = options?.temperature ?? this.config.temperature;\n const maxOutputTokens = options?.maxTokens ?? this.config.maxTokens;\n\n return mergeProviderBody<GenerateContentConfig>(\n {\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n ...this.buildTools(options),\n ...this.buildStructuredOutput(options?.responseSchema),\n ...this.buildThinking(options?.reasoning),\n },\n options,\n );\n }\n\n /**\n * Translate the neutral `reasoning` option into Gemini's\n * `thinkingConfig`. `reasoning.maxTokens` maps directly to\n * `thinkingBudget` (token cap on the thinking phase); when only\n * `reasoning.effort` is given it is bucketed into a budget. Emitted\n * only when the model is `reasoning`-capable — a `false` capability\n * (config override) drops it so a non-thinking model never receives\n * an unsupported `thinkingConfig`.\n *\n * Gemini's `thinkingBudget` semantics: `0` disables thinking, `-1`\n * lets the model decide automatically. A positive value caps the\n * thinking tokens. The neutral `effort: \"none\"` (\"run without\n * reasoning\") maps to `thinkingBudget: 0`.\n */\n private buildThinking(\n reasoning: ModelCallOptions[\"reasoning\"],\n ): Pick<GenerateContentConfig, \"thinkingConfig\"> {\n if (!reasoning || !this.capabilities.reasoning) {\n return {};\n }\n\n // `effort: \"none\"` = explicit \"run without reasoning\". Gemini disables\n // thinking with `thinkingBudget: 0` (its native off switch), so emit\n // that rather than omitting the config — an omitted config lets a\n // thinking model reason at its default budget.\n if (reasoning.effort === \"none\") {\n return { thinkingConfig: { thinkingBudget: 0 } };\n }\n\n const thinkingBudget =\n reasoning.maxTokens ??\n (reasoning.effort ? EFFORT_THINKING_BUDGET[reasoning.effort] : undefined);\n\n if (thinkingBudget === undefined) {\n return {};\n }\n\n return { thinkingConfig: { thinkingBudget } };\n }\n\n /**\n * Spread-friendly tools fragment. Empty object when no tools were\n * supplied so the caller can unconditionally spread it. Function tools\n * come first; `ai.providerTool({ provider: \"google\" })` definitions\n * (`{ googleSearch: {} }`, `{ codeExecution: {} }`, `{ urlContext: {} }`,\n * …) follow verbatim as their own `Tool` entries. Other providers'\n * definitions are skipped with a warning.\n */\n private buildTools(options: ModelCallOptions | undefined): Pick<GenerateContentConfig, \"tools\"> {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [GOOGLE_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const budget = searchBudgetOf(options);\n // The Gemini API cannot bound searches inside one call, so a spent budget\n // is enforced here by not offering Google Search again.\n const offered =\n budget && budget.remaining <= 0\n ? definitions.filter((definition) => !isSearchDefinition(definition))\n : definitions;\n\n if (offered.length < definitions.length) {\n this.logger.warn(\n LOG_MODULE,\n \"search-budget\",\n \"Google Search budget is spent; calling without the search tool\",\n { model: this.name, max: budget?.max, used: budget?.used },\n );\n }\n\n const mapped: Tool[] = [...(toGoogleTools(tools) ?? []), ...(offered as unknown as Tool[])];\n\n return mapped.length > 0 ? { tools: mapped } : {};\n }\n\n /**\n * Translate the neutral `responseSchema` into Gemini's native JSON\n * structured output (`responseMimeType: \"application/json\"` +\n * `responseJsonSchema`, which takes a raw JSON Schema directly).\n * Emitted only when the model is `structuredOutput`-capable and the\n * schema is an object root — otherwise the agent's soft prompt hint\n * + client-side `validate()` carry shape.\n */\n private buildStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n ): Pick<GenerateContentConfig, \"responseMimeType\" | \"responseJsonSchema\"> {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return {};\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return {};\n }\n\n return {\n responseMimeType: \"application/json\",\n responseJsonSchema: responseSchema,\n };\n }\n\n /**\n * Reshape Gemini's function-call content parts into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no functions so callers can branch on presence.\n *\n * Reads `candidates[0].content.parts` directly rather than the\n * `response.functionCalls` getter: the getter discards the\n * part-level `thoughtSignature`, and Gemini \"thinking\" models 400\n * the follow-up turn if that signature is not echoed back. See\n * `partToToolCall`.\n */\n private extractToolCalls(response: GenerateContentResponse): ModelToolCallRequest[] | undefined {\n const parts = response.candidates?.[0]?.content?.parts ?? [];\n const toolCalls = parts\n .map((part) => this.partToToolCall(part))\n .filter((call): call is ModelToolCallRequest => call !== undefined);\n\n return toolCalls.length > 0 ? toolCalls : undefined;\n }\n\n /**\n * Map a single Gemini `Part` to a neutral `ModelToolCallRequest`,\n * or `undefined` when the part is not a function call. The part's\n * `thoughtSignature` (opaque, set by thinking models) is carried on\n * `providerMetadata` so `toGoogleContents` can replay it on the\n * assistant turn — Gemini rejects the next request without it.\n */\n private partToToolCall(part: Part): ModelToolCallRequest | undefined {\n if (!part.functionCall) {\n return undefined;\n }\n\n const call = part.functionCall;\n\n return {\n // The Gemini Developer API does not assign function-call ids\n // (only Vertex parallel-calling does). Fall back to the function\n // name so the neutral `toolCallId` is non-empty and the echoed\n // `functionResponse.name` resolves — Gemini matches a result to\n // its call by name. See decisions §49.\n id: call.id ?? call.name ?? \"\",\n name: call.name ?? \"\",\n input: (call.args ?? {}) as Record<string, unknown>,\n ...(part.thoughtSignature\n ? { providerMetadata: { thoughtSignature: part.thoughtSignature } }\n : {}),\n };\n }\n\n /**\n * Normalize Gemini's `usageMetadata` into the neutral `Usage` shape\n * via the shared {@link applyGoogleUsage} mapper (the same one the\n * streaming loop and the Gemini image model use). Absent usage\n * collapses to zeros.\n */\n private extractUsage(response: GenerateContentResponse): Usage {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n if (response.usageMetadata) {\n applyGoogleUsage(usage, response.usageMetadata);\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy\n * and emit the standard error log line before it propagates.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapGoogleError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsCA,MAAM,aAAa;;AAGnB,MAAM,qBAAqB;;;;;;;;;;;AAY3B,MAAM,yBAA2E;CAC/E,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,cAA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ai";
2
3
  //#region ../../packages/ai-google/src/provider-options.d.ts
3
4
  /** Adapter-only fields merged after the neutral request parameters. */
4
5
  export type GoogleCallOptions = {
5
6
  body?: Record<string, unknown>;
7
+ /**
8
+ * Bound Google Search across the calls of one run. See
9
+ * `googleSearchBudget()`: the Gemini API has no per-request limit, so this
10
+ * stops offering the search tool once the allowance is spent.
11
+ */
12
+ search?: {
13
+ budget?: GoogleSearchBudget;
14
+ };
6
15
  };
7
16
  //#endregion
8
17
  //# sourceMappingURL=provider-options.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-options.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"mappings":";;;YAGY;EAAsB,OAAO"}
1
+ {"version":3,"file":"provider-options.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"mappings":";;;;YAIY;EACV,OAAO;;;;;;EAMP;IAAW,SAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"provider-options.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"sourcesContent":["import { InvalidRequestError, type ModelCallOptions } from \"@warlock.js/ai\";\n\n/** Adapter-only fields merged after the neutral request parameters. */\nexport type GoogleCallOptions = { body?: Record<string, unknown> };\n\nconst RESERVED_FIELDS = new Set([\"systemInstruction\", \"tools\", \"abortSignal\", \"httpOptions\"]);\n\nexport function mergeProviderBody<T extends object>(\n built: T,\n options: ModelCallOptions | undefined,\n): T {\n const provider = options?.providerOptions?.google as GoogleCallOptions | undefined;\n const body = provider?.body ?? {};\n const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.google.body cannot set ${reserved.join(\", \")}: use the call's messages, tools and model options.`,\n { context: { fields: reserved } },\n );\n }\n const defaults = built as Record<string, unknown>;\n const overrides = Object.fromEntries(\n Object.entries(body).map(([key, value]) => {\n const previous = defaults[key];\n return [\n key,\n isPlainObject(previous) && isPlainObject(value) ? { ...previous, ...value } : value,\n ];\n }),\n );\n return { ...built, ...overrides };\n}\n\n/** Merge only plain objects; arrays, null and provider scalar values replace the field. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;AAKA,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAqB;CAAS;CAAe;AAAa,CAAC;AAE5F,SAAgB,kBACd,OACA,SACG;CAEH,MAAM,QADW,SAAS,iBAAiB,OACtB,EAAE,QAAQ,CAAC;CAChC,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,QAAQ,gBAAgB,IAAI,GAAG,CAAC;CAC3E,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,oBACR,0CAA0C,SAAS,KAAK,IAAI,EAAE,sDAC9D,EAAE,SAAS,EAAE,QAAQ,SAAS,EAAE,CAClC;CAEF,MAAM,WAAW;CACjB,MAAM,YAAY,OAAO,YACvB,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;EACzC,MAAM,WAAW,SAAS;EAC1B,OAAO,CACL,KACA,cAAc,QAAQ,KAAK,cAAc,KAAK,IAAI;GAAE,GAAG;GAAU,GAAG;EAAM,IAAI,KAChF;CACF,CAAC,CACH;CACA,OAAO;EAAE,GAAG;EAAO,GAAG;CAAU;AAClC;;AAGA,SAAS,cAAc,OAAkD;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD"}
1
+ {"version":3,"file":"provider-options.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"sourcesContent":["import type { GoogleSearchBudget } from \"./search-budget\";\nimport { InvalidRequestError, type ModelCallOptions } from \"@warlock.js/ai\";\n\n/** Adapter-only fields merged after the neutral request parameters. */\nexport type GoogleCallOptions = {\n body?: Record<string, unknown>;\n /**\n * Bound Google Search across the calls of one run. See\n * `googleSearchBudget()`: the Gemini API has no per-request limit, so this\n * stops offering the search tool once the allowance is spent.\n */\n search?: { budget?: GoogleSearchBudget };\n};\n\nconst RESERVED_FIELDS = new Set([\"systemInstruction\", \"tools\", \"abortSignal\", \"httpOptions\"]);\n\nexport function mergeProviderBody<T extends object>(\n built: T,\n options: ModelCallOptions | undefined,\n): T {\n const provider = options?.providerOptions?.google as GoogleCallOptions | undefined;\n const body = provider?.body ?? {};\n const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.google.body cannot set ${reserved.join(\", \")}: use the call's messages, tools and model options.`,\n { context: { fields: reserved } },\n );\n }\n const defaults = built as Record<string, unknown>;\n const overrides = Object.fromEntries(\n Object.entries(body).map(([key, value]) => {\n const previous = defaults[key];\n return [\n key,\n isPlainObject(previous) && isPlainObject(value) ? { ...previous, ...value } : value,\n ];\n }),\n );\n return { ...built, ...overrides };\n}\n\n/** Merge only plain objects; arrays, null and provider scalar values replace the field. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;AAcA,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAqB;CAAS;CAAe;AAAa,CAAC;AAE5F,SAAgB,kBACd,OACA,SACG;CAEH,MAAM,QADW,SAAS,iBAAiB,OACtB,EAAE,QAAQ,CAAC;CAChC,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,QAAQ,gBAAgB,IAAI,GAAG,CAAC;CAC3E,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,oBACR,0CAA0C,SAAS,KAAK,IAAI,EAAE,sDAC9D,EAAE,SAAS,EAAE,QAAQ,SAAS,EAAE,CAClC;CAEF,MAAM,WAAW;CACjB,MAAM,YAAY,OAAO,YACvB,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;EACzC,MAAM,WAAW,SAAS;EAC1B,OAAO,CACL,KACA,cAAc,QAAQ,KAAK,cAAc,KAAK,IAAI;GAAE,GAAG;GAAU,GAAG;EAAM,IAAI,KAChF;CACF,CAAC,CACH;CACA,OAAO;EAAE,GAAG;EAAO,GAAG;CAAU;AAClC;;AAGA,SAAS,cAAc,OAAkD;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD"}
package/esm/sdk.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { GoogleEmbedderConfig, GoogleImageConfig, GoogleModelConfig, GoogleSDKConfig } from "./config.type.mjs";
2
- import { EmbedderContract, ImageModelContract, ModelContract, SDKAdapterContract } from "@warlock.js/ai";
2
+ import { EmbedderContract, ImageModelContract, ListModelsOptions, ModelContract, ModelInfo, SDKAdapterContract } from "@warlock.js/ai";
3
3
  //#region ../../packages/ai-google/src/sdk.d.ts
4
4
  /**
5
5
  * Google Gemini-backed implementation of `SDKAdapterContract`.
@@ -80,6 +80,20 @@ export declare class GoogleSDK implements SDKAdapterContract {
80
80
  * const { data } = await ai.image({ model: gemini, prompt: "a red bicycle" });
81
81
  */
82
82
  image(config: GoogleImageConfig): ImageModelContract;
83
+ /**
84
+ * List the models this key or project can use, live from the Gemini API
85
+ * `models.list` endpoint, mapped to {@link ModelInfo}. Follows pagination to
86
+ * the end. `kind` comes from the model's `supportedActions`:
87
+ * `generateContent` is `"chat"` (unless the id is an image or audio
88
+ * model), `embedContent` is `"embedding"`, `predict` / `predictLongRunning`
89
+ * is `"image"`. Google reports no creation date, so `created` is left out.
90
+ * Failures are thrown as the adapter's usual provider errors.
91
+ *
92
+ * @example
93
+ * const models = await google.models();
94
+ * const chat = models.filter((model) => model.kind === "chat");
95
+ */
96
+ models(options?: ListModelsOptions): Promise<ModelInfo[]>;
83
97
  }
84
98
  //#endregion
85
99
  //# sourceMappingURL=sdk.d.mts.map
package/esm/sdk.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;qBA+Ea,qBAAqB;mBACf;mBACA;mBACA;EAEjB,YAAmB,QAAQ;;;;;;;;;;;EAkBpB,MAAM,QAAQ,oBAAoB;;;;;;;EAe5B,MAAM,cAAc,kBAAkB;;;;;;;;EAW5C,SAAS,QAAQ,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;EA2BxC,MAAM,QAAQ,oBAAoB"}
1
+ {"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmFa,qBAAqB;mBACf;mBACA;mBACA;EAEjB,YAAmB,QAAQ;;;;;;;;;;;EAkBpB,MAAM,QAAQ,oBAAoB;;;;;;;EAe5B,MAAM,cAAc,kBAAkB;;;;;;;;EAW5C,SAAS,QAAQ,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;EA2BxC,MAAM,QAAQ,oBAAoB;;;;;;;;;;;;;;EAyB5B,OAAO,UAAU,oBAAoB,QAAQ"}
package/esm/sdk.mjs CHANGED
@@ -1,10 +1,12 @@
1
+ import { wrapGoogleError } from "./utils/wrap-google-error.mjs";
2
+ import "./utils/index.mjs";
1
3
  import { GoogleEmbedder } from "./embedder.mjs";
2
4
  import { GeminiImageModel } from "./gemini-image.mjs";
3
5
  import { GoogleImageModel } from "./image.mjs";
4
6
  import { googlePricingFor } from "./known-pricing.mjs";
5
7
  import { GoogleModel } from "./model.mjs";
6
8
  import { GoogleGenAI } from "@google/genai";
7
- import { approximateTokenCount } from "@warlock.js/ai";
9
+ import { approximateTokenCount, inferModelKind } from "@warlock.js/ai";
8
10
 
9
11
  //#region ../../packages/ai-google/src/sdk.ts
10
12
  /**
@@ -137,7 +139,55 @@ var GoogleSDK = class {
137
139
  if (usesGeminiImageTransport(config.name)) return new GeminiImageModel(this.ai, resolvedConfig, this.provider);
138
140
  return new GoogleImageModel(this.ai, resolvedConfig, this.provider);
139
141
  }
142
+ /**
143
+ * List the models this key or project can use, live from the Gemini API
144
+ * `models.list` endpoint, mapped to {@link ModelInfo}. Follows pagination to
145
+ * the end. `kind` comes from the model's `supportedActions`:
146
+ * `generateContent` is `"chat"` (unless the id is an image or audio
147
+ * model), `embedContent` is `"embedding"`, `predict` / `predictLongRunning`
148
+ * is `"image"`. Google reports no creation date, so `created` is left out.
149
+ * Failures are thrown as the adapter's usual provider errors.
150
+ *
151
+ * @example
152
+ * const models = await google.models();
153
+ * const chat = models.filter((model) => model.kind === "chat");
154
+ */
155
+ async models(options) {
156
+ const found = /* @__PURE__ */ new Map();
157
+ try {
158
+ const pager = await this.ai.models.list({ config: {
159
+ pageSize: 1e3,
160
+ ...options?.signal ? { abortSignal: options.signal } : {}
161
+ } });
162
+ for await (const entry of pager) {
163
+ const rawName = entry.name;
164
+ if (typeof rawName !== "string" || rawName === "") continue;
165
+ const id = rawName.replace(/^(?:publishers\/[^/]+\/)?models\//u, "");
166
+ const actions = entry.supportedActions ?? [];
167
+ found.set(id, {
168
+ id,
169
+ label: entry.displayName || id,
170
+ provider: this.provider,
171
+ kind: kindOfActions(actions, id),
172
+ ...entry.inputTokenLimit ? { contextWindow: entry.inputTokenLimit } : {},
173
+ ...entry.outputTokenLimit ? { maxOutputTokens: entry.outputTokenLimit } : {},
174
+ ...entry.description ? { description: entry.description } : {}
175
+ });
176
+ }
177
+ } catch (thrown) {
178
+ throw wrapGoogleError(thrown);
179
+ }
180
+ return [...found.values()];
181
+ }
140
182
  };
183
+ /** Map Gemini `supportedActions` to a {@link ModelKind}; fall back to the id when none are listed. */
184
+ function kindOfActions(actions, id) {
185
+ const inferred = inferModelKind(id);
186
+ if (actions.includes("embedContent") || actions.includes("batchEmbedContents")) return "embedding";
187
+ if (actions.includes("predict") || actions.includes("predictLongRunning")) return inferred === "audio" ? "audio" : "image";
188
+ if (actions.includes("generateContent")) return inferred === "embedding" || inferred === "moderation" ? "other" : inferred;
189
+ return actions.length === 0 ? inferred : "other";
190
+ }
141
191
 
142
192
  //#endregion
143
193
  export { GoogleSDK };
package/esm/sdk.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"sourcesContent":["import { GoogleGenAI } from \"@google/genai\";\nimport type {\n EmbedderContract,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n} from \"@warlock.js/ai\";\nimport { approximateTokenCount } from \"@warlock.js/ai\";\nimport type {\n GoogleEmbedderConfig,\n GoogleImageConfig,\n GoogleModelConfig,\n GoogleSDKConfig,\n} from \"./config.type\";\nimport { GoogleEmbedder } from \"./embedder\";\nimport { GeminiImageModel } from \"./gemini-image\";\nimport { GoogleImageModel } from \"./image\";\nimport { googlePricingFor } from \"./known-pricing\";\nimport { GoogleModel } from \"./model\";\n\n/**\n * Pick the transport for an image model id.\n *\n * `ai.models.generateImages` calls `{model}:predict`, and a `gemini-`\n * id sent there comes back `404 … is not supported for predict`\n * (observed verbatim from Google). `generateContent` is what the SDK\n * itself points `generateImages` users at — its deprecation notice\n * reads \"Please use the generateContent method with image models\n * instead\" — so the id has to choose the transport.\n *\n * Runs in this package establish where a `gemini-` id is ACCEPTED, not\n * what it returns: on this transport such an id got as far as a quota\n * error (HTTP 429) instead of the 404. That an image\n * comes back end-to-end once billing is enabled is reported by the\n * maintainer from a locally linked build, not measured here. Whether\n * these models report token usage is still unknown.\n *\n * This is ROUTING, not validation — no id is refused here. An id this\n * function does not recognize takes the `generateImages` route, the\n * only route that existed before Gemini image support landed, so every\n * id that reached Google before still reaches Google the same way and\n * still fails (or succeeds) at the provider.\n *\n * A leading `models/` resource prefix is tolerated, matching the id\n * shapes `inferVisionCapability` already accepts\n * (`models/gemini-1.5-flash-001`).\n */\nfunction usesGeminiImageTransport(name: string): boolean {\n return name\n .toLowerCase()\n .replace(/^models\\//, \"\")\n .startsWith(\"gemini-\");\n}\n\n/**\n * Google Gemini-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for Gemini models via the\n * `@google/genai` SDK. A single `GoogleSDK` holds one live\n * `GoogleGenAI` client, shared by every `ModelContract` /\n * `EmbedderContract` it produces. Construct one SDK per\n * account/project and reuse it everywhere.\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client (auth, Vertex vs Gemini\n * API) and its lifetime. Factory for `GoogleModel` /\n * `GoogleEmbedder` instances sharing that client.\n * - Does NOT own: anything per-call — those live in `GoogleModel` /\n * `GoogleEmbedder` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"), fronted by FP usage like the other adapters.\n *\n * @example\n * const google = new GoogleSDK({ apiKey: process.env.GEMINI_API_KEY! });\n * const model = google.model({ name: \"gemini-2.5-flash\", temperature: 0.7 });\n * const embedder = google.embedder({ name: \"gemini-embedding-001\" });\n */\nexport class GoogleSDK implements SDKAdapterContract {\n private readonly ai: GoogleGenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: GoogleSDKConfig) {\n const { provider, pricing, ...clientOptions } = config;\n\n this.ai = new GoogleGenAI(clientOptions);\n this.provider = provider ?? \"google\";\n this.pricing = pricing;\n }\n\n /**\n * Build a `GoogleModel` bound to this SDK's client. Each call\n * returns a fresh instance; all instances share the underlying\n * `GoogleGenAI` client. The SDK's `provider` label is forwarded.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise the\n * built-in list price (`GOOGLE_MODEL_PRICING`); otherwise `undefined`\n * (no cost computed).\n */\n public model(config: GoogleModelConfig): ModelContract {\n const resolvedPricing =\n config.pricing ?? this.pricing?.[config.name] ?? googlePricingFor(config.name);\n const resolvedConfig: GoogleModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new GoogleModel(this.ai, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate. Uses the character-heuristic\n * (`approximateTokenCount`) from the core package — Gemini's\n * `countTokens` is a network round-trip; `count()` is intentionally\n * offline. Good for budgeting/quota guards, not billing.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build a `GoogleEmbedder` bound to this SDK's client.\n *\n * @example\n * const embedder = google.embedder({ name: \"gemini-embedding-001\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: GoogleEmbedderConfig): EmbedderContract {\n return new GoogleEmbedder(this.ai, config, this.provider);\n }\n\n /**\n * Build an image model bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` decides the transport\n * (see {@link usesGeminiImageTransport}) — a `gemini-` id gets the\n * `generateContent` implementation, everything else the Imagen\n * `generateImages` one. No id is rejected locally either way, so an\n * unsupported model fails at Google, not here.\n *\n * The two differ in what usage they can report, which is what the\n * caller must price for: the Imagen path always returns a zero token\n * `Usage` (Imagen reports none — price with `{ perImage }`), while the\n * Gemini path passes through whatever `usageMetadata` Google attaches\n * (price with `{ input, output }` when tokens come back).\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined`.\n *\n * @example\n * const imagen = google.image({ name: \"imagen-4.0-generate-001\" });\n * const gemini = google.image({ name: \"gemini-3.1-flash-lite-image\" });\n * const { data } = await ai.image({ model: gemini, prompt: \"a red bicycle\" });\n */\n public image(config: GoogleImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: GoogleImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (usesGeminiImageTransport(config.name)) {\n return new GeminiImageModel(this.ai, resolvedConfig, this.provider);\n }\n\n return new GoogleImageModel(this.ai, resolvedConfig, this.provider);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAS,yBAAyB,MAAuB;CACvD,OAAO,KACJ,YAAY,CAAC,CACb,QAAQ,aAAa,EAAE,CAAC,CACxB,WAAW,SAAS;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,YAAb,MAAqD;CAKnD,AAAO,YAAY,QAAyB;EAC1C,MAAM,EAAE,UAAU,SAAS,GAAG,kBAAkB;EAEhD,KAAK,KAAK,IAAI,YAAY,aAAa;EACvC,KAAK,WAAW,YAAY;EAC5B,KAAK,UAAU;CACjB;;;;;;;;;;;CAYA,AAAO,MAAM,QAA0C;EACrD,MAAM,kBACJ,OAAO,WAAW,KAAK,UAAU,OAAO,SAAS,iBAAiB,OAAO,IAAI;EAC/E,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,OAAO,IAAI,YAAY,KAAK,IAAI,gBAAgB,KAAK,QAAQ;CAC/D;;;;;;;CAQA,MAAa,MAAM,MAAc,QAAkC;EACjE,OAAO,sBAAsB,IAAI;CACnC;;;;;;;;CASA,AAAO,SAAS,QAAgD;EAC9D,OAAO,IAAI,eAAe,KAAK,IAAI,QAAQ,KAAK,QAAQ;CAC1D;;;;;;;;;;;;;;;;;;;;;;;;CAyBA,AAAO,MAAM,QAA+C;EAC1D,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,IAAI,yBAAyB,OAAO,IAAI,GACtC,OAAO,IAAI,iBAAiB,KAAK,IAAI,gBAAgB,KAAK,QAAQ;EAGpE,OAAO,IAAI,iBAAiB,KAAK,IAAI,gBAAgB,KAAK,QAAQ;CACpE;AACF"}
1
+ {"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"sourcesContent":["import { GoogleGenAI } from \"@google/genai\";\nimport type {\n EmbedderContract,\n ListModelsOptions,\n ModelInfo,\n ModelKind,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n} from \"@warlock.js/ai\";\nimport { approximateTokenCount, inferModelKind } from \"@warlock.js/ai\";\nimport type {\n GoogleEmbedderConfig,\n GoogleImageConfig,\n GoogleModelConfig,\n GoogleSDKConfig,\n} from \"./config.type\";\nimport { GoogleEmbedder } from \"./embedder\";\nimport { GeminiImageModel } from \"./gemini-image\";\nimport { GoogleImageModel } from \"./image\";\nimport { googlePricingFor } from \"./known-pricing\";\nimport { GoogleModel } from \"./model\";\nimport { wrapGoogleError } from \"./utils\";\n\n/**\n * Pick the transport for an image model id.\n *\n * `ai.models.generateImages` calls `{model}:predict`, and a `gemini-`\n * id sent there comes back `404 … is not supported for predict`\n * (observed verbatim from Google). `generateContent` is what the SDK\n * itself points `generateImages` users at — its deprecation notice\n * reads \"Please use the generateContent method with image models\n * instead\" — so the id has to choose the transport.\n *\n * Runs in this package establish where a `gemini-` id is ACCEPTED, not\n * what it returns: on this transport such an id got as far as a quota\n * error (HTTP 429) instead of the 404. That an image\n * comes back end-to-end once billing is enabled is reported by the\n * maintainer from a locally linked build, not measured here. Whether\n * these models report token usage is still unknown.\n *\n * This is ROUTING, not validation — no id is refused here. An id this\n * function does not recognize takes the `generateImages` route, the\n * only route that existed before Gemini image support landed, so every\n * id that reached Google before still reaches Google the same way and\n * still fails (or succeeds) at the provider.\n *\n * A leading `models/` resource prefix is tolerated, matching the id\n * shapes `inferVisionCapability` already accepts\n * (`models/gemini-1.5-flash-001`).\n */\nfunction usesGeminiImageTransport(name: string): boolean {\n return name\n .toLowerCase()\n .replace(/^models\\//, \"\")\n .startsWith(\"gemini-\");\n}\n\n/**\n * Google Gemini-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for Gemini models via the\n * `@google/genai` SDK. A single `GoogleSDK` holds one live\n * `GoogleGenAI` client, shared by every `ModelContract` /\n * `EmbedderContract` it produces. Construct one SDK per\n * account/project and reuse it everywhere.\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client (auth, Vertex vs Gemini\n * API) and its lifetime. Factory for `GoogleModel` /\n * `GoogleEmbedder` instances sharing that client.\n * - Does NOT own: anything per-call — those live in `GoogleModel` /\n * `GoogleEmbedder` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"), fronted by FP usage like the other adapters.\n *\n * @example\n * const google = new GoogleSDK({ apiKey: process.env.GEMINI_API_KEY! });\n * const model = google.model({ name: \"gemini-2.5-flash\", temperature: 0.7 });\n * const embedder = google.embedder({ name: \"gemini-embedding-001\" });\n */\nexport class GoogleSDK implements SDKAdapterContract {\n private readonly ai: GoogleGenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: GoogleSDKConfig) {\n const { provider, pricing, ...clientOptions } = config;\n\n this.ai = new GoogleGenAI(clientOptions);\n this.provider = provider ?? \"google\";\n this.pricing = pricing;\n }\n\n /**\n * Build a `GoogleModel` bound to this SDK's client. Each call\n * returns a fresh instance; all instances share the underlying\n * `GoogleGenAI` client. The SDK's `provider` label is forwarded.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise the\n * built-in list price (`GOOGLE_MODEL_PRICING`); otherwise `undefined`\n * (no cost computed).\n */\n public model(config: GoogleModelConfig): ModelContract {\n const resolvedPricing =\n config.pricing ?? this.pricing?.[config.name] ?? googlePricingFor(config.name);\n const resolvedConfig: GoogleModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new GoogleModel(this.ai, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate. Uses the character-heuristic\n * (`approximateTokenCount`) from the core package — Gemini's\n * `countTokens` is a network round-trip; `count()` is intentionally\n * offline. Good for budgeting/quota guards, not billing.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build a `GoogleEmbedder` bound to this SDK's client.\n *\n * @example\n * const embedder = google.embedder({ name: \"gemini-embedding-001\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: GoogleEmbedderConfig): EmbedderContract {\n return new GoogleEmbedder(this.ai, config, this.provider);\n }\n\n /**\n * Build an image model bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` decides the transport\n * (see {@link usesGeminiImageTransport}) — a `gemini-` id gets the\n * `generateContent` implementation, everything else the Imagen\n * `generateImages` one. No id is rejected locally either way, so an\n * unsupported model fails at Google, not here.\n *\n * The two differ in what usage they can report, which is what the\n * caller must price for: the Imagen path always returns a zero token\n * `Usage` (Imagen reports none — price with `{ perImage }`), while the\n * Gemini path passes through whatever `usageMetadata` Google attaches\n * (price with `{ input, output }` when tokens come back).\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined`.\n *\n * @example\n * const imagen = google.image({ name: \"imagen-4.0-generate-001\" });\n * const gemini = google.image({ name: \"gemini-3.1-flash-lite-image\" });\n * const { data } = await ai.image({ model: gemini, prompt: \"a red bicycle\" });\n */\n public image(config: GoogleImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: GoogleImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (usesGeminiImageTransport(config.name)) {\n return new GeminiImageModel(this.ai, resolvedConfig, this.provider);\n }\n\n return new GoogleImageModel(this.ai, resolvedConfig, this.provider);\n }\n\n /**\n * List the models this key or project can use, live from the Gemini API\n * `models.list` endpoint, mapped to {@link ModelInfo}. Follows pagination to\n * the end. `kind` comes from the model's `supportedActions`:\n * `generateContent` is `\"chat\"` (unless the id is an image or audio\n * model), `embedContent` is `\"embedding\"`, `predict` / `predictLongRunning`\n * is `\"image\"`. Google reports no creation date, so `created` is left out.\n * Failures are thrown as the adapter's usual provider errors.\n *\n * @example\n * const models = await google.models();\n * const chat = models.filter((model) => model.kind === \"chat\");\n */\n public async models(options?: ListModelsOptions): Promise<ModelInfo[]> {\n const found = new Map<string, ModelInfo>();\n\n try {\n const pager = await this.ai.models.list({\n config: {\n pageSize: 1000,\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n },\n });\n\n for await (const entry of pager) {\n const rawName = entry.name;\n\n if (typeof rawName !== \"string\" || rawName === \"\") {\n continue;\n }\n\n const id = rawName.replace(/^(?:publishers\\/[^/]+\\/)?models\\//u, \"\");\n const actions = entry.supportedActions ?? [];\n\n found.set(id, {\n id,\n label: entry.displayName || id,\n provider: this.provider,\n kind: kindOfActions(actions, id),\n ...(entry.inputTokenLimit ? { contextWindow: entry.inputTokenLimit } : {}),\n ...(entry.outputTokenLimit ? { maxOutputTokens: entry.outputTokenLimit } : {}),\n ...(entry.description ? { description: entry.description } : {}),\n });\n }\n } catch (thrown) {\n throw wrapGoogleError(thrown);\n }\n\n return [...found.values()];\n }\n}\n\n/** Map Gemini `supportedActions` to a {@link ModelKind}; fall back to the id when none are listed. */\nfunction kindOfActions(actions: string[], id: string): ModelKind {\n const inferred = inferModelKind(id);\n\n if (actions.includes(\"embedContent\") || actions.includes(\"batchEmbedContents\")) {\n return \"embedding\";\n }\n\n if (actions.includes(\"predict\") || actions.includes(\"predictLongRunning\")) {\n return inferred === \"audio\" ? \"audio\" : \"image\";\n }\n\n if (actions.includes(\"generateContent\")) {\n return inferred === \"embedding\" || inferred === \"moderation\" ? \"other\" : inferred;\n }\n\n return actions.length === 0 ? inferred : \"other\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAS,yBAAyB,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UAAU;IACV,GAAI,SAAS,SAAS,EAAE,aAAa,QAAQ,OAAO,IAAI,CAAC;GAC3D,EACF,CAAC;GAED,WAAW,MAAM,SAAS,OAAO;IAC/B,MAAM,UAAU,MAAM;IAEtB,IAAI,OAAO,YAAY,YAAY,YAAY,IAC7C;IAGF,MAAM,KAAK,QAAQ,QAAQ,sCAAsC,EAAE;IACnE,MAAM,UAAU,MAAM,oBAAoB,CAAC;IAE3C,MAAM,IAAI,IAAI;KACZ;KACA,OAAO,MAAM,eAAe;KAC5B,UAAU,KAAK;KACf,MAAM,cAAc,SAAS,EAAE;KAC/B,GAAI,MAAM,kBAAkB,EAAE,eAAe,MAAM,gBAAgB,IAAI,CAAC;KACxE,GAAI,MAAM,mBAAmB,EAAE,iBAAiB,MAAM,iBAAiB,IAAI,CAAC;KAC5E,GAAI,MAAM,cAAc,EAAE,aAAa,MAAM,YAAY,IAAI,CAAC;IAChE,CAAC;GACH;EACF,SAAS,QAAQ;GACf,MAAM,gBAAgB,MAAM;EAC9B;EAEA,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC;CAC3B;AACF;;AAGA,SAAS,cAAc,SAAmB,IAAuB;CAC/D,MAAM,WAAW,eAAe,EAAE;CAElC,IAAI,QAAQ,SAAS,cAAc,KAAK,QAAQ,SAAS,oBAAoB,GAC3E,OAAO;CAGT,IAAI,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS,oBAAoB,GACtE,OAAO,aAAa,UAAU,UAAU;CAG1C,IAAI,QAAQ,SAAS,iBAAiB,GACpC,OAAO,aAAa,eAAe,aAAa,eAAe,UAAU;CAG3E,OAAO,QAAQ,WAAW,IAAI,WAAW;AAC3C"}
@@ -0,0 +1,42 @@
1
+ import "@warlock.js/ai";
2
+ //#region ../../packages/ai-google/src/search-budget.d.ts
3
+ /**
4
+ * A running allowance of Google Search queries, shared by the model calls of
5
+ * one run. Create it with {@link googleSearchBudget} and pass it as
6
+ * `providerOptions.google.search.budget` on every call of that run.
7
+ */
8
+ export type GoogleSearchBudget = {
9
+ /** The allowance the budget was created with. */
10
+ readonly max: number;
11
+ /** Unique search queries the provider reported so far. */
12
+ readonly used: number;
13
+ /** `max - used`, never below zero. */
14
+ readonly remaining: number;
15
+ /** Add queries the provider reported for one finished call. */
16
+ record(queries: number): void;
17
+ };
18
+ /**
19
+ * Bound Google Search grounding across the model calls of one run.
20
+ *
21
+ * The Gemini API has no per-request search limit: `{ googleSearch: {} }` takes
22
+ * no `max_uses`, and the model decides how many queries one `generateContent`
23
+ * call runs. What the adapter can enforce is the number of queries across
24
+ * calls: after each call it adds the queries Google reported
25
+ * (`groundingMetadata.webSearchQueries`, counted the way Gemini 3 bills them,
26
+ * unique and non-empty) to the budget, and once the budget is spent it stops
27
+ * sending the `googleSearch` tool, so later calls run without search. One
28
+ * call that is already running can still overshoot the budget by the queries
29
+ * it makes itself.
30
+ *
31
+ * @example
32
+ * const budget = googleSearchBudget(3);
33
+ * const search = ai.providerTool({ provider: "google", definition: { googleSearch: {} } });
34
+ * await model.complete(messages, {
35
+ * tools: [search],
36
+ * providerOptions: { google: { search: { budget } } },
37
+ * });
38
+ * budget.used; // queries spent so far
39
+ */
40
+ export declare function googleSearchBudget(maxQueries: number): GoogleSearchBudget;
41
+ //#endregion
42
+ //# sourceMappingURL=search-budget.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-budget.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/search-budget.ts"],"mappings":";;;;;;;YAWY;;WAED;;WAEA;;WAEA;;EAET,OAAO;;;;;;;;;;;;;;;;;;;;;;;;wBAyBO,mBAAmB,qBAAqB"}
@@ -0,0 +1,56 @@
1
+ import { InvalidRequestError } from "@warlock.js/ai";
2
+
3
+ //#region ../../packages/ai-google/src/search-budget.ts
4
+ /**
5
+ * Bound Google Search grounding across the model calls of one run.
6
+ *
7
+ * The Gemini API has no per-request search limit: `{ googleSearch: {} }` takes
8
+ * no `max_uses`, and the model decides how many queries one `generateContent`
9
+ * call runs. What the adapter can enforce is the number of queries across
10
+ * calls: after each call it adds the queries Google reported
11
+ * (`groundingMetadata.webSearchQueries`, counted the way Gemini 3 bills them,
12
+ * unique and non-empty) to the budget, and once the budget is spent it stops
13
+ * sending the `googleSearch` tool, so later calls run without search. One
14
+ * call that is already running can still overshoot the budget by the queries
15
+ * it makes itself.
16
+ *
17
+ * @example
18
+ * const budget = googleSearchBudget(3);
19
+ * const search = ai.providerTool({ provider: "google", definition: { googleSearch: {} } });
20
+ * await model.complete(messages, {
21
+ * tools: [search],
22
+ * providerOptions: { google: { search: { budget } } },
23
+ * });
24
+ * budget.used; // queries spent so far
25
+ */
26
+ function googleSearchBudget(maxQueries) {
27
+ if (!Number.isInteger(maxQueries) || maxQueries < 0) throw new InvalidRequestError(`googleSearchBudget(maxQueries) needs a non-negative integer, got ${String(maxQueries)}.`);
28
+ let used = 0;
29
+ return {
30
+ max: maxQueries,
31
+ get used() {
32
+ return used;
33
+ },
34
+ get remaining() {
35
+ return Math.max(0, maxQueries - used);
36
+ },
37
+ record(queries) {
38
+ if (Number.isFinite(queries) && queries > 0) used += queries;
39
+ }
40
+ };
41
+ }
42
+ /** The budget on a call, validated; `undefined` when the call sets none. */
43
+ function searchBudgetOf(options) {
44
+ const budget = ((options?.providerOptions?.google)?.search)?.budget;
45
+ if (budget === void 0) return;
46
+ if (typeof budget !== "object" || budget === null || typeof budget.record !== "function" || typeof budget.remaining !== "number") throw new InvalidRequestError("providerOptions.google.search.budget must come from googleSearchBudget(maxQueries).");
47
+ return budget;
48
+ }
49
+ /** `true` for a Gemini tool entry that runs Google Search grounding. */
50
+ function isSearchDefinition(definition) {
51
+ return "googleSearch" in definition || "googleSearchRetrieval" in definition;
52
+ }
53
+
54
+ //#endregion
55
+ export { googleSearchBudget, isSearchDefinition, searchBudgetOf };
56
+ //# sourceMappingURL=search-budget.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-budget.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/search-budget.ts"],"sourcesContent":["import {\n InvalidRequestError,\n type ModelCallOptions,\n type ProviderToolDefinition,\n} from \"@warlock.js/ai\";\n\n/**\n * A running allowance of Google Search queries, shared by the model calls of\n * one run. Create it with {@link googleSearchBudget} and pass it as\n * `providerOptions.google.search.budget` on every call of that run.\n */\nexport type GoogleSearchBudget = {\n /** The allowance the budget was created with. */\n readonly max: number;\n /** Unique search queries the provider reported so far. */\n readonly used: number;\n /** `max - used`, never below zero. */\n readonly remaining: number;\n /** Add queries the provider reported for one finished call. */\n record(queries: number): void;\n};\n\n/**\n * Bound Google Search grounding across the model calls of one run.\n *\n * The Gemini API has no per-request search limit: `{ googleSearch: {} }` takes\n * no `max_uses`, and the model decides how many queries one `generateContent`\n * call runs. What the adapter can enforce is the number of queries across\n * calls: after each call it adds the queries Google reported\n * (`groundingMetadata.webSearchQueries`, counted the way Gemini 3 bills them,\n * unique and non-empty) to the budget, and once the budget is spent it stops\n * sending the `googleSearch` tool, so later calls run without search. One\n * call that is already running can still overshoot the budget by the queries\n * it makes itself.\n *\n * @example\n * const budget = googleSearchBudget(3);\n * const search = ai.providerTool({ provider: \"google\", definition: { googleSearch: {} } });\n * await model.complete(messages, {\n * tools: [search],\n * providerOptions: { google: { search: { budget } } },\n * });\n * budget.used; // queries spent so far\n */\nexport function googleSearchBudget(maxQueries: number): GoogleSearchBudget {\n if (!Number.isInteger(maxQueries) || maxQueries < 0) {\n throw new InvalidRequestError(\n `googleSearchBudget(maxQueries) needs a non-negative integer, got ${String(maxQueries)}.`,\n );\n }\n\n let used = 0;\n\n return {\n max: maxQueries,\n get used() {\n return used;\n },\n get remaining() {\n return Math.max(0, maxQueries - used);\n },\n record(queries) {\n if (Number.isFinite(queries) && queries > 0) {\n used += queries;\n }\n },\n };\n}\n\n/** The budget on a call, validated; `undefined` when the call sets none. */\nexport function searchBudgetOf(\n options: ModelCallOptions | undefined,\n): GoogleSearchBudget | undefined {\n const search = (options?.providerOptions?.google as { search?: { budget?: unknown } } | undefined)\n ?.search;\n const budget = search?.budget;\n\n if (budget === undefined) {\n return undefined;\n }\n\n if (\n typeof budget !== \"object\" ||\n budget === null ||\n typeof (budget as GoogleSearchBudget).record !== \"function\" ||\n typeof (budget as GoogleSearchBudget).remaining !== \"number\"\n ) {\n throw new InvalidRequestError(\n \"providerOptions.google.search.budget must come from googleSearchBudget(maxQueries).\",\n );\n }\n\n return budget as GoogleSearchBudget;\n}\n\n/** `true` for a Gemini tool entry that runs Google Search grounding. */\nexport function isSearchDefinition(definition: ProviderToolDefinition[\"definition\"]): boolean {\n return \"googleSearch\" in definition || \"googleSearchRetrieval\" in definition;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,mBAAmB,YAAwC;CACzE,IAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAa,GAChD,MAAM,IAAI,oBACR,oEAAoE,OAAO,UAAU,EAAE,EACzF;CAGF,IAAI,OAAO;CAEX,OAAO;EACL,KAAK;EACL,IAAI,OAAO;GACT,OAAO;EACT;EACA,IAAI,YAAY;GACd,OAAO,KAAK,IAAI,GAAG,aAAa,IAAI;EACtC;EACA,OAAO,SAAS;GACd,IAAI,OAAO,SAAS,OAAO,KAAK,UAAU,GACxC,QAAQ;EAEZ;CACF;AACF;;AAGA,SAAgB,eACd,SACgC;CAGhC,MAAM,WAFU,SAAS,iBAAiB,OAAM,EAC5C,OACiB,EAAE;CAEvB,IAAI,WAAW,QACb;CAGF,IACE,OAAO,WAAW,YAClB,WAAW,QACX,OAAQ,OAA8B,WAAW,cACjD,OAAQ,OAA8B,cAAc,UAEpD,MAAM,IAAI,oBACR,qFACF;CAGF,OAAO;AACT;;AAGA,SAAgB,mBAAmB,YAA2D;CAC5F,OAAO,kBAAkB,cAAc,2BAA2B;AACpE"}
package/llms-full.txt CHANGED
@@ -370,4 +370,12 @@ console.log(response.usage.serverToolUse?.webSearchRequests);
370
370
  console.log(response.providerMetadata);
371
371
  ```
372
372
 
373
+ ## Bounding Google Search
374
+
375
+ The Gemini API has no per-request search limit. `googleSearchBudget(max)` plus `providerOptions: { google: { search: { budget } } }` bounds searches across the calls of one run: the adapter adds each call's unique `webSearchQueries` to the budget and stops sending `googleSearch` once it is spent. A call already running can still overshoot. `googleSearchBudget(0)` disables search for that run.
376
+
377
+ ## List models
378
+
379
+ `await google.models()` returns `ModelInfo[]` (id without `models/`, `label`, `kind` from `supportedActions`, `contextWindow`, `maxOutputTokens`, `description`; no `created`).
380
+
373
381
 
package/package.json CHANGED
@@ -15,13 +15,13 @@
15
15
  "directory": "packages/ai-google"
16
16
  },
17
17
  "peerDependencies": {
18
- "@warlock.js/ai": "5.39.1"
18
+ "@warlock.js/ai": "5.40.0"
19
19
  },
20
20
  "dependencies": {
21
21
  "@google/genai": "^2.17.1",
22
- "@warlock.js/logger": "5.39.1"
22
+ "@warlock.js/logger": "5.40.0"
23
23
  },
24
- "version": "5.39.1",
24
+ "version": "5.40.0",
25
25
  "main": "./cjs/index.cjs",
26
26
  "module": "./esm/index.mjs",
27
27
  "types": "./esm/index.d.mts",
package/skills/SKILL.md CHANGED
@@ -361,3 +361,11 @@ const response = await model.complete(messages, {
361
361
  console.log(response.usage.serverToolUse?.webSearchRequests);
362
362
  console.log(response.providerMetadata);
363
363
  ```
364
+
365
+ ## Bounding Google Search
366
+
367
+ The Gemini API has no per-request search limit. `googleSearchBudget(max)` plus `providerOptions: { google: { search: { budget } } }` bounds searches across the calls of one run: the adapter adds each call's unique `webSearchQueries` to the budget and stops sending `googleSearch` once it is spent. A call already running can still overshoot. `googleSearchBudget(0)` disables search for that run.
368
+
369
+ ## List models
370
+
371
+ `await google.models()` returns `ModelInfo[]` (id without `models/`, `label`, `kind` from `supportedActions`, `contextWindow`, `maxOutputTokens`, `description`; no `created`).