experimental-ash 0.61.0 → 0.63.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/CHANGELOG.md +72 -0
- package/dist/docs/public/advanced/hooks.mdx +8 -2
- package/dist/docs/public/advanced/runs-and-streaming.md +6 -3
- package/dist/docs/public/advanced/typescript-api.md +32 -0
- package/dist/docs/public/channels/custom.mdx +23 -0
- package/dist/docs/public/frontend/README.md +8 -4
- package/dist/docs/public/frontend/meta.json +9 -1
- package/dist/docs/public/frontend/nextjs.md +4 -4
- package/dist/docs/public/frontend/nuxt.md +168 -0
- package/dist/docs/public/frontend/sveltekit.md +177 -0
- package/dist/docs/public/frontend/use-ash-agent-svelte.md +185 -0
- package/dist/docs/public/frontend/use-ash-agent-vue.md +236 -0
- package/dist/docs/public/frontend/use-ash-agent.md +14 -14
- package/dist/docs/public/getting-started.mdx +2 -0
- package/dist/skills/ash-add-agent/SKILL.md +29 -17
- package/dist/skills/ash-add-next/SKILL.md +58 -8
- package/dist/src/channel/websocket-upgrade-server.d.ts +26 -0
- package/dist/src/channel/websocket-upgrade-server.js +1 -0
- package/dist/src/chunks/use-ash-agent-BQJLh7KU.js +1224 -0
- package/dist/src/chunks/use-ash-agent-CRWVA4i-.js +1192 -0
- package/dist/src/client/ash-agent-store.d.ts +61 -0
- package/dist/src/client/ash-agent-store.js +2 -0
- package/dist/src/client/index.d.ts +2 -0
- package/dist/src/client/index.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +9 -9
- package/dist/src/compiled/@ai-sdk/anthropic/_provider-utils.d.ts +1 -1
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +3 -3
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +52 -2
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +32 -2
- package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/provider/index.d.ts +507 -1
- package/dist/src/compiled/@chat-adapter/slack/index.js +25 -25
- package/dist/src/compiled/@workflow/core/events-consumer.d.ts +8 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +1 -0
- package/dist/src/compiled/@workflow/core/runtime.js +29 -29
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
- package/dist/src/compiled/@workflow/errors/index.d.ts +14 -0
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/queue.d.ts +8 -0
- package/dist/src/compiled/_chunks/workflow/{dist-Chj-QcBs.js → dist-gEXVSMPU.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-zpK2YVVA.js +3 -0
- package/dist/src/compiled/_chunks/workflow/resume-hook-BFK9mgsb.js +12 -0
- package/dist/src/compiled/_chunks/workflow/{sleep-Bg0t23kF.js → sleep-CeJckNg2.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{symbols-u476uwyR.js → symbols-BWCAoPHE.js} +1 -1
- package/dist/src/compiler/manifest.d.ts +12 -0
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-connection.d.ts +10 -2
- package/dist/src/compiler/normalize-connection.js +1 -1
- package/dist/src/execution/sandbox/bindings/local.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/internal/application/package.d.ts +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.d.ts +9 -0
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
- package/dist/src/internal/nitro/host/channel-routes.js +2 -2
- package/dist/src/internal/vercel-agent-summary.d.ts +6 -4
- package/dist/src/internal/workflow-bundle/ash-service-route-output.js +11 -1
- package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
- package/dist/src/public/channels/auth.d.ts +1 -1
- package/dist/src/public/channels/index.d.ts +1 -0
- package/dist/src/public/channels/index.js +1 -1
- package/dist/src/public/connections/index.d.ts +3 -2
- package/dist/src/public/connections/index.js +1 -1
- package/dist/src/public/definitions/connections/mcp.d.ts +4 -12
- package/dist/src/public/definitions/connections/mcp.js +1 -1
- package/dist/src/public/definitions/connections/openapi.d.ts +100 -0
- package/dist/src/public/definitions/connections/openapi.js +1 -0
- package/dist/src/public/definitions/connections/protocol.d.ts +12 -0
- package/dist/src/public/definitions/connections/protocol.js +1 -0
- package/dist/src/public/next/index.d.ts +6 -6
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/{vercel-json.d.ts → vercel-output-config.d.ts} +3 -3
- package/dist/src/public/next/vercel-output-config.js +1 -0
- package/dist/src/public/nuxt/dev-server.d.ts +24 -0
- package/dist/src/public/nuxt/dev-server.js +1 -0
- package/dist/src/public/nuxt/index.d.ts +1 -0
- package/dist/src/public/nuxt/index.js +1 -0
- package/dist/src/public/nuxt/module.d.ts +31 -0
- package/dist/src/public/nuxt/module.js +1 -0
- package/dist/src/public/nuxt/routing.d.ts +55 -0
- package/dist/src/public/nuxt/routing.js +1 -0
- package/dist/src/public/nuxt/vercel-json.d.ts +17 -0
- package/dist/src/public/{next → nuxt}/vercel-json.js +1 -1
- package/dist/src/public/sveltekit/dev-server.d.ts +24 -0
- package/dist/src/public/sveltekit/dev-server.js +1 -0
- package/dist/src/public/sveltekit/index.d.ts +39 -0
- package/dist/src/public/sveltekit/index.js +1 -0
- package/dist/src/public/sveltekit/routing.d.ts +32 -0
- package/dist/src/public/sveltekit/routing.js +1 -0
- package/dist/src/public/sveltekit/vercel-json.d.ts +17 -0
- package/dist/src/public/sveltekit/vercel-json.js +1 -0
- package/dist/src/react/use-ash-agent.d.ts +5 -27
- package/dist/src/react/use-ash-agent.js +1 -2
- package/dist/src/runtime/connections/openapi-client.d.ts +43 -0
- package/dist/src/runtime/connections/openapi-client.js +1 -0
- package/dist/src/runtime/connections/openapi-operations.d.ts +30 -0
- package/dist/src/runtime/connections/openapi-operations.js +1 -0
- package/dist/src/runtime/connections/openapi-schema.d.ts +39 -0
- package/dist/src/runtime/connections/openapi-schema.js +1 -0
- package/dist/src/runtime/connections/openapi-security.d.ts +41 -0
- package/dist/src/runtime/connections/openapi-security.js +1 -0
- package/dist/src/runtime/connections/openapi-spec.d.ts +20 -0
- package/dist/src/runtime/connections/openapi-spec.js +1 -0
- package/dist/src/runtime/connections/registry.d.ts +5 -7
- package/dist/src/runtime/connections/registry.js +1 -1
- package/dist/src/runtime/connections/types.d.ts +23 -0
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/types.d.ts +15 -1
- package/dist/src/shared/sandbox-session.d.ts +1 -1
- package/dist/src/shared/vercel-output-directory.d.ts +2 -0
- package/dist/src/shared/vercel-output-directory.js +1 -0
- package/dist/src/svelte/index.d.ts +3 -0
- package/dist/src/svelte/index.js +3 -0
- package/dist/src/svelte/use-ash-agent.d.ts +80 -0
- package/dist/src/svelte/use-ash-agent.js +3 -0
- package/dist/src/vue/index.d.ts +3 -0
- package/dist/src/vue/index.js +3 -0
- package/dist/src/vue/use-ash-agent.d.ts +78 -0
- package/dist/src/vue/use-ash-agent.js +3 -0
- package/package.json +59 -14
- package/dist/src/compiled/_chunks/workflow/dist-C4EHshZE.js +0 -3
- package/dist/src/compiled/_chunks/workflow/resume-hook-BlALLgSA.js +0 -12
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _ai_sdk_provider_utils from './_provider-utils.js';
|
|
2
2
|
import { InferSchema, FetchFunction } from './_provider-utils.js';
|
|
3
|
-
import { ProviderV4, LanguageModelV4, ImageModelV4, EmbeddingModelV4, Experimental_VideoModelV4, FilesV4 } from '#compiled/@ai-sdk/provider/index.js';
|
|
3
|
+
import { ProviderV4, LanguageModelV4, ImageModelV4, EmbeddingModelV4, Experimental_VideoModelV4, SpeechModelV4, FilesV4, Experimental_RealtimeFactoryV4, Experimental_RealtimeModelV4, Experimental_RealtimeModelV4ClientSecretOptions, Experimental_RealtimeModelV4ClientSecretResult, Experimental_RealtimeModelV4ServerEvent, Experimental_RealtimeModelV4ClientEvent, Experimental_RealtimeModelV4SessionConfig } from '#compiled/@ai-sdk/provider/index.js';
|
|
4
4
|
|
|
5
5
|
declare const googleErrorDataSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
6
6
|
error: {
|
|
@@ -265,6 +265,21 @@ type GoogleVideoModelOptions = {
|
|
|
265
265
|
|
|
266
266
|
type GoogleVideoModelId = 'veo-3.1-fast-generate-preview' | 'veo-3.1-generate-preview' | 'veo-3.1-generate' | 'veo-3.1-lite-generate-preview' | 'veo-3.0-generate-001' | 'veo-3.0-fast-generate-001' | 'veo-2.0-generate-001' | (string & {});
|
|
267
267
|
|
|
268
|
+
type GoogleSpeechModelId = 'gemini-2.5-flash-preview-tts' | 'gemini-2.5-pro-preview-tts' | 'gemini-3.1-flash-tts-preview' | (string & {});
|
|
269
|
+
declare const googleSpeechProviderOptionsSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
270
|
+
multiSpeakerVoiceConfig?: {
|
|
271
|
+
speakerVoiceConfigs: {
|
|
272
|
+
speaker: string;
|
|
273
|
+
voiceConfig: {
|
|
274
|
+
prebuiltVoiceConfig: {
|
|
275
|
+
voiceName: string;
|
|
276
|
+
};
|
|
277
|
+
};
|
|
278
|
+
}[];
|
|
279
|
+
} | undefined;
|
|
280
|
+
}>;
|
|
281
|
+
type GoogleSpeechModelOptions = InferSchema<typeof googleSpeechProviderOptionsSchema>;
|
|
282
|
+
|
|
268
283
|
type GoogleFilesUploadOptions = {
|
|
269
284
|
displayName?: string | null;
|
|
270
285
|
pollIntervalMs?: number | null;
|
|
@@ -517,6 +532,14 @@ interface GoogleProvider extends ProviderV4 {
|
|
|
517
532
|
* Creates a model for video generation.
|
|
518
533
|
*/
|
|
519
534
|
videoModel(modelId: GoogleVideoModelId): Experimental_VideoModelV4;
|
|
535
|
+
/**
|
|
536
|
+
* Creates a model for speech generation (text-to-speech).
|
|
537
|
+
*/
|
|
538
|
+
speech(modelId: GoogleSpeechModelId): SpeechModelV4;
|
|
539
|
+
/**
|
|
540
|
+
* Creates a model for speech generation (text-to-speech).
|
|
541
|
+
*/
|
|
542
|
+
speechModel(modelId: GoogleSpeechModelId): SpeechModelV4;
|
|
520
543
|
files(): FilesV4;
|
|
521
544
|
/**
|
|
522
545
|
* Creates a language model targeting the Gemini Interactions API
|
|
@@ -531,6 +554,7 @@ interface GoogleProvider extends ProviderV4 {
|
|
|
531
554
|
} | {
|
|
532
555
|
managedAgent: string;
|
|
533
556
|
}): LanguageModelV4;
|
|
557
|
+
experimental_realtime: Experimental_RealtimeFactoryV4;
|
|
534
558
|
tools: typeof googleTools;
|
|
535
559
|
}
|
|
536
560
|
interface GoogleProviderSettings {
|
|
@@ -572,6 +596,32 @@ declare function createGoogle(options?: GoogleProviderSettings): GoogleProvider;
|
|
|
572
596
|
*/
|
|
573
597
|
declare const google: GoogleProvider;
|
|
574
598
|
|
|
599
|
+
type GoogleRealtimeModelConfig = {
|
|
600
|
+
provider: string;
|
|
601
|
+
baseURL: string;
|
|
602
|
+
headers: () => Record<string, string | undefined>;
|
|
603
|
+
fetch?: FetchFunction;
|
|
604
|
+
};
|
|
605
|
+
declare class GoogleRealtimeModel implements Experimental_RealtimeModelV4 {
|
|
606
|
+
readonly specificationVersion: "v4";
|
|
607
|
+
readonly provider: string;
|
|
608
|
+
readonly modelId: string;
|
|
609
|
+
private readonly config;
|
|
610
|
+
private readonly mapper;
|
|
611
|
+
constructor(modelId: string, config: GoogleRealtimeModelConfig);
|
|
612
|
+
doCreateClientSecret(options: Experimental_RealtimeModelV4ClientSecretOptions): Promise<Experimental_RealtimeModelV4ClientSecretResult>;
|
|
613
|
+
getWebSocketConfig(options: {
|
|
614
|
+
token: string;
|
|
615
|
+
url: string;
|
|
616
|
+
}): {
|
|
617
|
+
url: string;
|
|
618
|
+
protocols?: string[];
|
|
619
|
+
};
|
|
620
|
+
parseServerEvent(raw: unknown): Experimental_RealtimeModelV4ServerEvent | Experimental_RealtimeModelV4ServerEvent[];
|
|
621
|
+
serializeClientEvent(event: Experimental_RealtimeModelV4ClientEvent): ReturnType<Experimental_RealtimeModelV4['serializeClientEvent']>;
|
|
622
|
+
buildSessionConfig(config: Experimental_RealtimeModelV4SessionConfig): Record<string, unknown>;
|
|
623
|
+
}
|
|
624
|
+
|
|
575
625
|
declare const VERSION: string;
|
|
576
626
|
|
|
577
|
-
export { type GoogleEmbeddingModelOptions, type GoogleErrorData, type GoogleFilesUploadOptions, type GoogleEmbeddingModelOptions as GoogleGenerativeAIEmbeddingProviderOptions, type GoogleImageModelOptions as GoogleGenerativeAIImageProviderOptions, type GoogleProvider as GoogleGenerativeAIProvider, type GoogleProviderMetadata as GoogleGenerativeAIProviderMetadata, type GoogleLanguageModelOptions as GoogleGenerativeAIProviderOptions, type GoogleProviderSettings as GoogleGenerativeAIProviderSettings, type GoogleVideoModelId as GoogleGenerativeAIVideoModelId, type GoogleVideoModelOptions as GoogleGenerativeAIVideoProviderOptions, type GoogleImageModelOptions, type GoogleInteractionsAgentName, type GoogleInteractionsModelId, type GoogleInteractionsProviderMetadata, type GoogleLanguageModelInteractionsOptions, type GoogleLanguageModelOptions, type GoogleProvider, type GoogleProviderMetadata, type GoogleProviderSettings, type GoogleVideoModelId, type GoogleVideoModelOptions, VERSION, createGoogle, createGoogle as createGoogleGenerativeAI, google };
|
|
627
|
+
export { GoogleRealtimeModel as Experimental_GoogleRealtimeModel, type GoogleRealtimeModelConfig as Experimental_GoogleRealtimeModelConfig, type GoogleEmbeddingModelOptions, type GoogleErrorData, type GoogleFilesUploadOptions, type GoogleEmbeddingModelOptions as GoogleGenerativeAIEmbeddingProviderOptions, type GoogleImageModelOptions as GoogleGenerativeAIImageProviderOptions, type GoogleProvider as GoogleGenerativeAIProvider, type GoogleProviderMetadata as GoogleGenerativeAIProviderMetadata, type GoogleLanguageModelOptions as GoogleGenerativeAIProviderOptions, type GoogleProviderSettings as GoogleGenerativeAIProviderSettings, type GoogleVideoModelId as GoogleGenerativeAIVideoModelId, type GoogleVideoModelOptions as GoogleGenerativeAIVideoProviderOptions, type GoogleImageModelOptions, type GoogleInteractionsAgentName, type GoogleInteractionsModelId, type GoogleInteractionsProviderMetadata, type GoogleLanguageModelInteractionsOptions, type GoogleLanguageModelOptions, type GoogleProvider, type GoogleProviderMetadata, type GoogleProviderSettings, type GoogleSpeechModelId, type GoogleSpeechModelOptions, type GoogleVideoModelId, type GoogleVideoModelOptions, VERSION, createGoogle, createGoogle as createGoogleGenerativeAI, google };
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-DWOIBELG.js";import{A as p,B as m,C as h,E as g,
|
|
2
|
-
`):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function
|
|
1
|
+
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-DWOIBELG.js";import{A as p,B as m,C as h,E as g,H as _,I as v,J as y,M as b,N as x,R as S,S as C,T as w,V as T,W as E,X as D,Y as O,Z as k,_ as A,a as ee,b as j,c as te,d as ne,f as M,h as N,i as re,k as P,o as F,q as ie,r as I,u as L,w as R,x as z,z as B}from"../../_chunks/workflow/dist-gEXVSMPU.js";var ae=`4.0.0-canary.79`,V=ne({errorSchema:P(()=>O(s({error:s({code:d().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),oe=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})}),s({fileData:s({fileUri:o(),mimeType:o()})})]),se=P(()=>O(s({outputDimensionality:d().optional(),taskType:f([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(oe).min(1).nullable()).optional()}))),ce=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[k](e){return E({modelId:e.modelId,config:e.config})}static[D](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await v({provider:`google`,providerOptions:i,schema:se});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=I(this.config.headers?await B(this.config.headers):void 0,n),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],n=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:c,value:l,rawValue:u}=await S({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:V,successfulResponseHandler:M(ue),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await S({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:V,successfulResponseHandler:M(le),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},le=P(()=>O(s({embeddings:i(s({values:i(d())}))}))),ue=P(()=>O(s({embedding:s({values:i(d())})})));function de(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.promptTokenCount??0,n=e.candidatesTokenCount??0,r=e.cachedContentTokenCount??0,i=e.thoughtsTokenCount??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n+i,text:n,reasoning:i},raw:e}}function H(e,t=!0){if(e==null)return;if(fe(e))return t?void 0:typeof e==`object`&&e.description?{type:`object`,description:e.description}:{type:`object`};if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:n,description:r,required:i,properties:a,items:o,allOf:s,anyOf:c,oneOf:l,format:u,const:d,minLength:f,enum:p}=e,m={};if(r&&(m.description=r),i&&(m.required=i),u&&(m.format=u),d!==void 0&&(m.enum=[d]),n)if(Array.isArray(n)){let e=n.includes(`null`),t=n.filter(e=>e!==`null`);t.length===0?m.type=`null`:(m.anyOf=t.map(e=>({type:e})),e&&(m.nullable=!0))}else m.type=n;if(p!==void 0&&(m.enum=p),a!=null&&(m.properties=Object.entries(a).reduce((e,[t,n])=>(e[t]=H(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>H(e,!1)):H(o,!1)),s&&(m.allOf=s.map(e=>H(e,!1))),c)if(c.some(e=>typeof e==`object`&&e?.type===`null`)){let e=c.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=H(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>H(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>H(e,!1));return l&&(m.oneOf=l.map(e=>H(e,!1))),f!==void 0&&(m.minLength=f),m}function fe(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var pe=`skip_thought_signature_validator`,me=/^data:([^;,]+);base64,(.+)$/s;function he(e){let t=me.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function ge(e){let t=he(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function _e(e,t,n,r){let i=[],a=[];for(let e of n)switch(e.type){case`text`:a.push(e.text);break;case`file`:if(e.data.type===`data`)i.push({inlineData:{mimeType:m({part:e}),data:F(e.data.data)}});else if(e.data.type===`url`){let t=ge(e.data.url.toString());t==null?a.push(JSON.stringify(e)):i.push(t)}else a.push(JSON.stringify(e));break;default:a.push(JSON.stringify(e));break}e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:a.length>0?a.join(`
|
|
2
|
+
`):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function ve(e,t,n,r){for(let i of n)switch(i.type){case`text`:e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:i.text}}});break;case`file`:i.data.type===`data`&&h(i.mediaType)===`image`?e.push({inlineData:{mimeType:m({part:i}),data:F(i.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function ye(e,t){let r=[],i=[],a=!0,o=t?.isGemmaModel??!1,s=t?.isGemini3Model??!1,c=t?.onWarning,l=t?.providerOptionsNames??[`google`],u=!l.includes(`google`),d=t?.supportsFunctionResponseParts??!0,f=!1,p=[],h=e=>(p.push(e),f=!0,pe),_=e=>{for(let t of l){let n=e.providerOptions?.[t];if(n!=null)return n}return u?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:m({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(u)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:m({part:t}),fileUri:T({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:g(t.mediaType)?t.mediaType:`text/plain`,data:F(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:m({part:t}),data:F(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{let t=_(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:F(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(u)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:T({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:g(e.mediaType)?e.mediaType:`text/plain`,data:F(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:F(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType),a=r??(s?h(e.toolName):void 0);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:n},thoughtSignature:a}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:a}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=_(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?d?_e(e,t.toolName,o.value,t.toolCallId):ve(e,t.toolName,o.value,t.toolCallId):e.push({functionResponse:{...t.toolCallId==null?{}:{id:t.toolCallId},name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
3
3
|
|
|
4
4
|
`);i[0].parts.unshift({text:e+`
|
|
5
5
|
|
|
6
|
-
`})}if(f&&c!=null){let e=Array.from(new Set(p));c({type:`other`,message:`Replayed ${p.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${e.map(e=>`\`${e}\``).join(`, `)}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function ve(e){return e.includes(`/`)?e:`models/${e}`}var ye=P(()=>D(s({responseModalities:i(f([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:d().optional(),includeThoughts:r().optional(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:f([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:f([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).optional(),imageSize:f([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:d(),longitude:d()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:f([`standard`,`flex`,`priority`]).optional(),sharedRequestType:f([`priority`,`flex`,`standard`]).optional(),requestType:f([`shared`]).optional()})));function be({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var xe=class{constructor(){this.accumulatedArgs={},this.jsonText=``,this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t=``;for(let n of e){let e=n.jsonPath.replace(/^\$\./,``);if(!e)continue;let r=Se(e),i=Ce(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);we(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Te(n);a!=null&&(we(this.accumulatedArgs,r,a.value),t+=this.emitNavigationTo(r,n,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs);return{finalJSON:e,closingDelta:e.slice(this.jsonText.length)}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:``,isArray:!1,childCount:0}),`{`):``}emitNavigationTo(e,t,n){let r=``;this.stringOpen&&=(r+=`"`,!1),r+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],o=this.findCommonStackDepth(i);return r+=this.closeDownTo(o),r+=this.openDownTo(i,a),r+=this.emitLeaf(a,t,n),r}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let r=0;r<t&&this.pathStack[r+1].segment===e[r];r++)n++;return n+1}closeDownTo(e){let t=``;for(;this.pathStack.length>e;){let e=this.pathStack.pop();t+=e.isArray?`]`:`}`}return t}openDownTo(e,t){let n=``,r=this.pathStack.length-1;for(let i=r;i<e.length;i++){let r=e[i],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(n+=`,`),a.childCount++,typeof r==`string`&&(n+=`${JSON.stringify(r)}:`);let o=typeof(i+1<e.length?e[i+1]:t)==`number`;n+=o?`[`:`{`,this.pathStack.push({segment:r,isArray:o,childCount:0})}return n}emitLeaf(e,t,n){let r=``,i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(r+=`,`),i.childCount++,typeof e==`string`&&(r+=`${JSON.stringify(e)}:`),t.stringValue!=null&&t.willContinue?(r+=n.slice(0,-1),this.stringOpen=!0):r+=n,r}};function Se(e){let t=[];for(let n of e.split(`.`)){let e=n.indexOf(`[`);if(e===-1)t.push(n);else{e>0&&t.push(n.slice(0,e));for(let e of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(e[1],10))}}return t}function Ce(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function we(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];r[n]??(r[n]=typeof i==`number`?[]:{}),r=r[n]}r[t[t.length-1]]=n}function Te(e){let t=e.stringValue??e.numberValue??e.boolValue;if(t!=null)return{value:t,json:JSON.stringify(t)};if(`nullValue`in e)return{value:null,json:`null`}}function Ee({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`other`}}var De=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??A}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:m=!1}={}){let h=[],g=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],v;for(let e of g)if(v=await _({provider:e,providerOptions:p,schema:ye}),v!=null)break;v==null&&!g.includes(`google`)&&(v=await _({provider:`google`,providerOptions:p,schema:ye}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&h.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),v?.streamFunctionCallArguments&&!y&&h.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),v?.serviceTier&&y&&h.push({type:`other`,message:`'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo`}),(v?.sharedRequestType||v?.requestType)&&!y&&h.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let b=y&&(v?.sharedRequestType||v?.requestType)?{...v.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":v.sharedRequestType},...v.requestType&&{"X-Vertex-AI-LLM-Request-Type":v.requestType}}:void 0,x=y?void 0:v?.serviceTier,S=this.modelId.toLowerCase().startsWith(`gemma-`),C=/^gemini-3[.-]/.test(this.modelId),{contents:w,systemInstruction:T}=_e(e,{isGemmaModel:S,isGemini3Model:C,onWarning:e=>h.push(e),providerOptionsNames:g,supportsFunctionResponseParts:C}),{tools:E,toolConfig:D,toolWarnings:O}=be({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),k=je({reasoning:f,modelId:this.modelId,warnings:h}),ee=v?.thinkingConfig||k?{...k,...v?.thinkingConfig}:void 0,A=m&&y?v?.streamFunctionCallArguments??!1:void 0,j=D||A||v?.retrievalConfig?{...D,...A&&{functionCallingConfig:{...D?.functionCallingConfig,streamFunctionCallArguments:!0}},...v?.retrievalConfig&&{retrievalConfig:v.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(v?.structuredOutputs??!0)?H(c.schema):void 0,...v?.audioTimestamp&&{audioTimestamp:v.audioTimestamp},responseModalities:v?.responseModalities,thinkingConfig:ee,...v?.mediaResolution&&{mediaResolution:v.mediaResolution},...v?.imageConfig&&{imageConfig:v.imageConfig}},contents:w,systemInstruction:S?void 0:T,safetySettings:v?.safetySettings,tools:E,toolConfig:j,cachedContent:v?.cachedContent,labels:v?.labels,serviceTier:x},warnings:[...h,...O],providerOptionsNames:g,extraHeaders:b}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=I(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c,rawValue:l}=await x({url:`${this.config.baseURL}/${ve(this.modelId)}:generateContent`,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:M(Ve),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c.candidates[0],d=[],f=u.content?.parts??[],p=c.usageMetadata,m,h;for(let e of f)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();m=t,d.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)d.push({type:`tool-result`,toolCallId:m,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),m=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&d.length>0){let e=d[d.length-1];e.providerMetadata=t}}else d.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)d.push({type:`tool-call`,toolCallId:e.functionCall.id??this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;d.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?a({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();h=t,d.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):a({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=h??e.toolResponse.id??this.config.generateId();d.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):a({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),h=void 0}let g=Pe({groundingMetadata:u.groundingMetadata,generateId:this.config.generateId})??[];for(let e of g)d.push(e);return{content:d,finishReason:{unified:Ee({finishReason:u.finishReason,hasToolCalls:d.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:u.finishReason??void 0},usage:le(p),warnings:n,providerMetadata:a({promptFeedback:c.promptFeedback??null,groundingMetadata:u.groundingMetadata??null,urlContextMetadata:u.urlContextMetadata??null,safetyRatings:u.safetyRatings??null,usageMetadata:p??null,finishMessage:u.finishMessage??null,serviceTier:p?.serviceTier??null}),request:{body:t},response:{headers:s,body:l}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e,{isStreaming:!0}),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=I(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c}=await x({url:`${this.config.baseURL}/${ve(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:L(He),abortSignal:e.abortSignal,fetch:this.config.fetch}),l={unified:`other`,raw:void 0},u,d,f=null,p=null,m=this.config.generateId,h=!1,g=null,_=null,v=0,y=new Set,b,S,C=[],w=e=>{let t=C.pop();if(t==null)return;let{finalJSON:n,closingDelta:r}=t.accumulator.finalize();r.length>0&&e.enqueue({type:`tool-input-delta`,id:t.toolCallId,delta:r,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-input-end`,id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-call`,toolCallId:t.toolCallId,toolName:t.toolName,input:n,providerMetadata:t.providerMetadata}),h=!0};return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(u=i);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(f=o.groundingMetadata),o.urlContextMetadata!=null&&(p=o.urlContextMetadata);let c=Pe({groundingMetadata:o.groundingMetadata,generateId:m});if(c!=null)for(let e of c)e.sourceType===`url`&&!y.has(e.url)&&(y.add(e.url),n.enqueue(e));if(s!=null){let e=s.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=m();b=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=b;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),b=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&g!==null&&n.enqueue({type:`text-delta`,id:g,delta:``,providerMetadata:e}):t.thought===!0?(g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_===null&&(_=String(v++),n.enqueue({type:`reasoning-start`,id:_,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:_,delta:t.text,providerMetadata:e})):(_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null),g===null&&(g=String(v++),n.enqueue({type:`text-start`,id:g,providerMetadata:e})),n.enqueue({type:`text-delta`,id:g,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null);let e=t.thought===!0,r=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;n.enqueue({type:e?`reasoning-file`:`file`,mediaType:t.inlineData.mimeType,data:{type:`data`,data:t.inlineData.data},providerMetadata:r})}else if(`toolCall`in t&&t.toolCall){let e=t.toolCall.id??m();S=e;let r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});n.enqueue({type:`tool-call`,toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:r})}else if(`toolResponse`in t&&t.toolResponse){let e=S??t.toolResponse.id??m(),r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});n.enqueue({type:`tool-result`,toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:r}),S=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,i=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=t.functionCall.name!=null&&t.functionCall.args!=null&&t.functionCall.partialArgs==null,s=t.functionCall.name!=null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue!==!0;if(r){if(t.functionCall.name!=null){let r=t.functionCall.id??m(),i=new xe;if(C.push({toolCallId:r,toolName:t.functionCall.name,accumulator:i,providerMetadata:e}),n.enqueue({type:`tool-input-start`,id:r,toolName:t.functionCall.name,providerMetadata:e}),t.functionCall.partialArgs!=null){let a=t.functionCall.partialArgs,{textDelta:o}=i.processPartialArgs(a);o.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:o,providerMetadata:e}),t.functionCall.willContinue!==!0&&a.every(e=>e.willContinue!==!0)&&w(n)}}else if(t.functionCall.partialArgs!=null&&C.length>0){let r=C[C.length-1],i=t.functionCall.partialArgs,{textDelta:a}=r.accumulator.processPartialArgs(i);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:a,providerMetadata:e}),t.functionCall.willContinue!==!0&&i.every(e=>e.willContinue!==!0)&&w(n)}}else if(i&&C.length>0)w(n);else if(o){let r=t.functionCall.id??m(),i=t.functionCall.name,a=typeof t.functionCall.args==`string`?t.functionCall.args:JSON.stringify(t.functionCall.args??{});n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:a,providerMetadata:e}),h=!0}else if(s){let r=t.functionCall.id??m(),i=t.functionCall.name;n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:`{}`,providerMetadata:e}),h=!0}}}o.finishReason!=null&&(l={unified:Ee({finishReason:o.finishReason,hasToolCalls:h}),raw:o.finishReason},d=a({promptFeedback:r.promptFeedback??null,groundingMetadata:f,urlContextMetadata:p,safetyRatings:o.safetyRatings??null,usageMetadata:i??null,finishMessage:o.finishMessage??null,serviceTier:u?.serviceTier??null}))},flush(e){g!==null&&e.enqueue({type:`text-end`,id:g}),_!==null&&e.enqueue({type:`reasoning-end`,id:_}),e.enqueue({type:`finish`,finishReason:l,usage:le(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function Oe(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function ke(){return 65536}function Ae(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function je({reasoning:e,modelId:t,warnings:n}){if(C(e))return Oe(t)&&!t.includes(`gemini-3-pro-image`)?Me({reasoning:e,warnings:n}):Ne({reasoning:e,modelId:t,warnings:n})}function Me({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=b({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Ne({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=y({reasoning:e,maxOutputTokens:ke(),maxReasoningBudget:Ae(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function Pe({groundingMetadata:e,generateId:t}){if(!e?.groundingChunks)return;let n=[];for(let r of e.groundingChunks)if(r.web!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.web.uri,title:r.web.title??void 0});else if(r.image!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.image.sourceUri,title:r.image.title??void 0});else if(r.retrievedContext!=null){let e=r.retrievedContext.uri,i=r.retrievedContext.fileSearchStore;if(e&&(e.startsWith(`http://`)||e.startsWith(`https://`)))n.push({type:`source`,sourceType:`url`,id:t(),url:e,title:r.retrievedContext.title??void 0});else if(e){let i=r.retrievedContext.title??`Unknown Document`,a=`application/octet-stream`,o;e.endsWith(`.pdf`)?(a=`application/pdf`,o=e.split(`/`).pop()):e.endsWith(`.txt`)?(a=`text/plain`,o=e.split(`/`).pop()):e.endsWith(`.docx`)?(a=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,o=e.split(`/`).pop()):e.endsWith(`.doc`)?(a=`application/msword`,o=e.split(`/`).pop()):(e.match(/\.(md|markdown)$/)&&(a=`text/markdown`),o=e.split(`/`).pop()),n.push({type:`source`,sourceType:`document`,id:t(),mediaType:a,title:i,filename:o})}else if(i){let e=r.retrievedContext.title??`Unknown Document`;n.push({type:`source`,sourceType:`document`,id:t(),mediaType:`application/octet-stream`,title:e,filename:i.split(`/`).pop()})}}else r.maps!=null&&r.maps.uri&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.maps.uri,title:r.maps.title??void 0});return n.length>0?n:void 0}var Fe=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:d().nullish(),endIndex:d().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(d()).nullish(),supportChunkIndices:i(d()).nullish(),confidenceScores:i(d()).nullish(),confidenceScore:i(d()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:d()}),s({})]).nullish()}),Ie=s({jsonPath:o(),stringValue:o().nullish(),numberValue:d().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),Le=()=>s({parts:i(c([s({functionCall:s({id:o().nullish(),name:o().nullish(),args:l().nullish(),partialArgs:i(Ie).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),U=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:d().nullish(),severity:o().nullish(),severityScore:d().nullish(),blocked:r().nullish()}),Re=i(s({modality:o(),tokenCount:d()})).nullish(),ze=s({cachedContentTokenCount:d().nullish(),thoughtsTokenCount:d().nullish(),promptTokenCount:d().nullish(),candidatesTokenCount:d().nullish(),totalTokenCount:d().nullish(),trafficType:o().nullish(),serviceTier:o().nullish(),promptTokensDetails:Re,candidatesTokensDetails:Re}),Be=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),Ve=P(()=>D(s({candidates:i(s({content:Le().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Fe().nullish(),urlContextMetadata:Be().nullish()})),usageMetadata:ze.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(U()).nullish()}).nullish()}))),He=P(()=>D(s({candidates:i(s({content:Le().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(U()).nullish(),groundingMetadata:Fe().nullish(),urlContextMetadata:Be().nullish()})).nullish(),usageMetadata:ze.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(U()).nullish()}).nullish()}))),Ue=N({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),We=N({id:`google.enterprise_web_search`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:d().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().describe(`Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.`).optional()}).passthrough();var Ge=N({id:`google.file_search`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),Ke=N({id:`google.google_maps`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),qe=s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough(),Je={googleSearch:N({id:`google.google_search`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),enterpriseWebSearch:We,googleMaps:Ke,urlContext:N({id:`google.url_context`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))}),fileSearch:Ge,codeExecution:Ue,vertexRagStore:N({id:`google.vertex_rag_store`,inputSchema:P(()=>D(s({}))),outputSchema:P(()=>D(s({})))})},Ye=P(()=>D(s({personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:f([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish(),googleSearch:qe.optional()}))),Xe=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?Ze(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return Ze(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.length>0)throw Error(`Google Gemini API does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);if(d!=null)throw Error(`Google Gemini API does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await _({provider:`google`,providerOptions:s,schema:Ye}),m=((t=this.config._internal)?.currentDate)?.call(t)??new Date,h={sampleCount:r};if(a!=null&&(h.aspectRatio=a),p){let{googleSearch:e,...t}=p;e!=null&&f.push({type:`unsupported`,feature:`googleSearch`,details:`Google Search grounding is only supported on Gemini image models.`}),Object.assign(h,t)}let g={instances:[{prompt:n}],parameters:h},{responseHeaders:v,value:y}=await x({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:I(this.config.headers?await B(this.config.headers):void 0,c),body:g,failedResponseHandler:V,successfulResponseHandler:M(Qe),abortSignal:l,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:y.predictions.map(()=>({}))}},response:{timestamp:m,modelId:this.modelId,headers:v}}}async doGenerateGemini(e){var t;let{prompt:n,n:r,size:i,aspectRatio:a,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(d!=null)throw Error(`Gemini image models do not support mask-based image editing.`);if(r!=null&&r>1)throw Error(`Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let p=[];if(n!=null&&p.push({type:`text`,text:n}),u!=null&&u.length>0)for(let e of u)e.type===`url`?p.push({type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}):p.push({type:`file`,data:{type:`data`,data:typeof e.data==`string`?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let m=[{role:`user`,content:p}],h=await _({provider:`google`,providerOptions:s,schema:Ye}),{googleSearch:g,...v}=s?.google??{},y=await new De(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??A}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,...v}},tools:h?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:h.googleSearch}],headers:c,abortSignal:l}),b=((t=this.config._internal)?.currentDate)?.call(t)??new Date,x=[];for(let e of y.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&x.push(F(e.data.data));return{images:x,warnings:f,providerMetadata:{google:{...y.providerMetadata?.google??{},images:x.map(()=>({}))}},response:{timestamp:b,modelId:this.modelId,headers:y.response?.headers},usage:y.usage?{inputTokens:y.usage.inputTokens.total,outputTokens:y.usage.outputTokens.total,totalTokens:(y.usage.inputTokens.total??0)+(y.usage.outputTokens.total??0)}:void 0}}};function Ze(e){return e.startsWith(`gemini-`)}var Qe=P(()=>D(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),$e=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await _({provider:`google`,providerOptions:t.providerOptions,schema:tt}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=ee(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,h=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-h>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await k(p);let{value:t}=await z({url:`${this.config.baseURL}/${f.name}`,headers:I(r),successfulResponseHandler:M(et),failedResponseHandler:V,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},et=P(()=>D(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),tt=P(()=>D(s({displayName:o().nullish(),pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish()}).passthrough())),nt=P(()=>D(s({pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish(),personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),rt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await _({provider:`google`,providerOptions:t.providerOptions,schema:nt}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:j(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await x({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:I(await B(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:M(it),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),m=l,h;for(;!m.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await k(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await z({url:`${this.config.baseURL}/${u}`,headers:I(await B(this.config.headers),t.headers),successfulResponseHandler:M(it),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch});m=n,h=r}if(m.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${m.error.message}`});let g=m.response;if(!g?.generateVideoResponse?.generatedSamples||g.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(m)}`});let v=[],y=[],b=(await B(this.config.headers))?.[`x-goog-api-key`];for(let e of g.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=b?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${b}`:e.video.uri;v.push({type:`url`,url:t,mediaType:`video/mp4`}),y.push({uri:e.video.uri})}if(v.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:v,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:h},providerMetadata:{google:{videos:y}}}}},it=s({name:o().nullish(),done:r().nullish(),error:s({code:d().nullish(),message:o(),status:o().nullish()}).nullish(),response:s({generateVideoResponse:s({generatedSamples:i(s({video:s({uri:o().nullish()}).nullish()})).nullish()}).nullish()}).nullish()});function W(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.total_input_tokens??0,n=e.total_output_tokens??0,r=e.total_thought_tokens??0,i=e.total_cached_tokens??0;return{inputTokens:{total:e.total_input_tokens??void 0,noCache:e.total_input_tokens==null?void 0:t-i,cacheRead:e.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:e.total_output_tokens==null&&e.total_thought_tokens==null?void 0:n+r,text:e.total_output_tokens??void 0,reasoning:e.total_thought_tokens??void 0},raw:e}}var at={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function ot(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(at))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function st(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function ct({annotation:e,generateId:t}){switch(e.type){case`url_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.title==null?{}:{title:n.title}}}case`file_citation`:{let n=e,r=n.url??n.document_uri??n.file_name;if(r==null||r.length===0)return;if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`source`,sourceType:`url`,id:t(),url:r,...n.file_name==null?{}:{title:n.file_name}};let i=n.file_name??st(r),a=ot(r);return{type:`source`,sourceType:`document`,id:t(),mediaType:a,title:n.file_name??i??r,...i==null?{}:{filename:i}}}case`place_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.name==null?{}:{title:n.name}}}default:return}}function lt({block:e,generateId:t}){let n=[];switch(e.type){case`url_context_result`:{let r=e.result??[];for(let e of r)e?.url==null||e.url.length===0||e.status!=null&&e.status!==`success`||n.push({type:`source`,sourceType:`url`,id:t(),url:e.url});break}case`google_search_result`:{let r=e.result??[];for(let e of r){let r=e?.url;r==null||r.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r,...e.title==null?{}:{title:e.title}})}break}case`google_maps_result`:{let r=e.result??[];for(let e of r)for(let r of e.places??[])r.url==null||r.url.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r.url,...r.name==null?{}:{title:r.name}});break}case`file_search_result`:{let r=e.result??[];for(let e of r){if(typeof e!=`object`||!e)continue;let r=e,i=r.url??r.document_uri??r.file_name;if(i==null||i.length===0)continue;if(i.startsWith(`http://`)||i.startsWith(`https://`)){n.push({type:`source`,sourceType:`url`,id:t(),url:i,...r.title==null?{}:{title:r.title}});continue}let a=r.file_name??st(i),o=ot(i);n.push({type:`source`,sourceType:`document`,id:t(),mediaType:o,title:r.title??r.file_name??a??i,...a==null?{}:{filename:a}})}break}default:break}return n}function G({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=ct({annotation:i,generateId:t});if(e==null)continue;let a=e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`;n.has(a)||(n.add(a),r.push(e))}return r}function K({status:e,hasFunctionCall:t}){switch(e){case`completed`:return t?`tool-calls`:`stop`;case`requires_action`:return`tool-calls`;case`failed`:return`error`;case`incomplete`:return`length`;case`cancelled`:return`other`;default:return`other`}}var ut=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),dt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function ft(e){return e.replace(/_call$/,``)}function pt(e){return e.replace(/_result$/,``)}function mt({warnings:e,generateId:t,includeRawChunks:n,serviceTier:r}){let i,a,o=r,s,c=!1,l=new Map,u=new Set;function d(e){return e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`}return new TransformStream({start(t){t.enqueue({type:`stream-start`,warnings:e})},transform(e,r){if(n&&r.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){s=`failed`,r.enqueue({type:`error`,error:e.error});return}let f=e.value,p=f.event_type;switch(p){case`interaction.created`:{let e=f.interaction;i=e?.id!=null&&e.id.length>0?e.id:void 0;let t=e?.created,n;if(typeof t==`string`){let e=new Date(t);Number.isNaN(e.getTime())||(n=e)}r.enqueue({type:`response-metadata`,...i==null?{}:{id:i},modelId:e?.model,...n?{timestamp:n}:{}});break}case`step.start`:{let e=f,n=e.step,a=e.index,o=`${i??`interaction`}:${a}`,s=n?.type;if(s===`model_output`){let e=n?.content?.[0];if(e?.type===`text`){l.set(a,{kind:`text`,id:o,emittedSourceKeys:new Set}),r.enqueue({type:`text-start`,id:o});let n=G({annotations:e.annotations,generateId:t});for(let e of n){let t=d(e);u.has(t)||(u.add(t),r.enqueue(e))}}else e?.type===`image`?l.set(a,{kind:`image`,id:o,...e.data==null?{}:{data:e.data},...e.mime_type==null?{}:{mimeType:e.mime_type},...e.uri==null?{}:{uri:e.uri}}):l.set(a,{kind:`pending_model_output`,id:o})}else if(s===`thought`){let e=n?.signature;if(l.set(a,{kind:`reasoning`,id:o,...e==null?{}:{signature:e}}),r.enqueue({type:`reasoning-start`,id:o}),Array.isArray(n?.summary))for(let e of n.summary)e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:o,delta:e.text})}else if(s===`function_call`){let e=n?.id??o,t=n?.name??`unknown`;c=!0;let i={kind:`function_call`,id:o,toolCallId:e,toolName:t,argumentsAccum:``,...n?.signature==null?{}:{signature:n.signature}};l.set(a,i),r.enqueue({type:`tool-input-start`,id:e,toolName:t})}else if(s!=null&&ut.has(s)){let e=s===`mcp_server_tool_call`?n?.name??`mcp_server_tool`:ft(s),t={kind:`builtin_tool_call`,id:o,blockType:s,toolCallId:n?.id??o,toolName:e,arguments:n?.arguments??{},callEmitted:!1};l.set(a,t)}else if(s!=null&&dt.has(s)){let e=s===`mcp_server_tool_result`?n?.name??`mcp_server_tool`:pt(s),t={kind:`builtin_tool_result`,id:o,blockType:s,callId:n?.call_id??o,toolName:e,result:n?.result??null,...n?.is_error==null?{}:{isError:n.is_error},resultEmitted:!1};l.set(a,t)}else l.set(a,{kind:`unknown`,id:o});break}case`step.delta`:{let e=f,n=l.get(e.index);if(n==null)break;let a=e.delta?.type;if(n.kind===`pending_model_output`&&(a===`text`||a===`text_annotation`||a===`text_annotation_delta`)){let t={kind:`text`,id:n.id,emittedSourceKeys:new Set};l.set(e.index,t),n=t,r.enqueue({type:`text-start`,id:t.id})}if(a===`image`&&(n.kind===`pending_model_output`||n.kind===`text`||n.kind===`image`)){let t=e.delta,a={};i!=null&&(a.interactionId=i);let o=Object.keys(a).length>0?{google:a}:void 0;t?.data!=null&&t.data.length>0?r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`data`,data:t.data},...o?{providerMetadata:o}:{}}):t?.uri!=null&&t.uri.length>0&&r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`url`,url:new URL(t.uri)},...o?{providerMetadata:o}:{}}),n.kind===`image`&&(n.data=void 0,n.uri=void 0);break}let o=e.delta;if(n.kind===`text`&&o?.type===`text`){let e=o.text??``;e.length>0&&r.enqueue({type:`text-delta`,id:n.id,delta:e})}else if(n.kind===`text`&&(o?.type===`text_annotation`||o?.type===`text_annotation_delta`)){let e=G({annotations:o.annotations,generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),n.emittedSourceKeys.add(e),r.enqueue(t))}}else if(n.kind===`image`&&o?.type===`image`)o.data!=null&&(n.data=o.data),o.mime_type!=null&&(n.mimeType=o.mime_type),o.uri!=null&&(n.uri=o.uri);else if(n.kind===`reasoning`){if(o?.type===`thought_summary`){let e=o.content;e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:n.id,delta:e.text})}else if(o?.type===`thought_signature`){let e=o.signature;e!=null&&(n.signature=e)}}else if(n.kind===`function_call`&&o?.type===`arguments_delta`){let e=typeof o.arguments==`string`?o.arguments:``;e.length>0&&(n.argumentsAccum+=e,r.enqueue({type:`tool-input-delta`,id:n.toolCallId,delta:e})),o.id!=null&&(n.toolCallId=o.id),o.signature!=null&&(n.signature=o.signature),c=!0}else n.kind===`builtin_tool_call`&&o?.type===n.blockType?(o.id!=null&&(n.toolCallId=o.id),o.arguments!=null&&typeof o.arguments==`object`&&(n.arguments=o.arguments),o.name!=null&&n.blockType===`mcp_server_tool_call`&&(n.toolName=o.name)):n.kind===`builtin_tool_result`&&o?.type===n.blockType&&(o.call_id!=null&&(n.callId=o.call_id),o.result!==void 0&&(n.result=o.result),o.is_error!=null&&(n.isError=o.is_error),o.name!=null&&n.blockType===`mcp_server_tool_result`&&(n.toolName=o.name));break}case`step.stop`:{let e=f,n=l.get(e.index);if(n==null)break;if(n.kind===`text`){let e=i==null?void 0:{google:{interactionId:i}};r.enqueue({type:`text-end`,id:n.id,...e?{providerMetadata:e}:{}})}else if(n.kind===`reasoning`){let e={};n.signature!=null&&(e.signature=n.signature),i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;r.enqueue({type:`reasoning-end`,id:n.id,...t?{providerMetadata:t}:{}})}else if(n.kind===`image`){let e={};i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;n.data!=null&&n.data.length>0?r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`data`,data:n.data},...t?{providerMetadata:t}:{}}):n.uri!=null&&n.uri.length>0&&r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`url`,url:new URL(n.uri)},...t?{providerMetadata:t}:{}})}else if(n.kind===`function_call`){let e=n.argumentsAccum.length>0?n.argumentsAccum:`{}`;r.enqueue({type:`tool-input-end`,id:n.toolCallId});let t={};n.signature!=null&&(t.signature=n.signature),i!=null&&(t.interactionId=i);let a=Object.keys(t).length>0?{google:t}:void 0;r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:e,...a?{providerMetadata:a}:{}})}else if(n.kind===`builtin_tool_call`&&!n.callEmitted)r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:JSON.stringify(n.arguments??{}),providerExecuted:!0}),n.callEmitted=!0;else if(n.kind===`builtin_tool_result`&&!n.resultEmitted){r.enqueue({type:`tool-result`,toolCallId:n.callId,toolName:n.toolName,result:n.result??null}),n.resultEmitted=!0;let e=lt({block:{type:n.blockType,call_id:n.callId,result:n.result},generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),r.enqueue(t))}}l.delete(e.index);break}case`interaction.status_update`:case`interaction.in_progress`:case`interaction.requires_action`:{let e=f;s=e.status==null?p===`interaction.requires_action`?`requires_action`:`in_progress`:e.status;break}case`interaction.completed`:{let e=f.interaction;e?.id!=null&&e.id.length>0&&(i=e.id),e?.status!=null&&(s=e.status),e?.usage!=null&&(a=e.usage),e?.service_tier!=null&&(o=e.service_tier);break}case`error`:{let e=f;s=`failed`;let t=e.error??{message:`Unknown interaction error`};r.enqueue({type:`error`,error:t});break}default:break}},flush(e){let t={unified:K({status:s,hasFunctionCall:c}),raw:s},n={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o}}};e.enqueue({type:`finish`,finishReason:t,usage:W(a),providerMetadata:n})}})}function ht({prompt:e,previousInteractionId:t,store:n,mediaResolution:r}){let i=[],a=t!=null&&n===!1,o=t!=null&&n!==!1;a&&i.push({type:`other`,message:`google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted.`});let s=o?_t({prompt:e,previousInteractionId:t}):e,c=[],l=[];for(let e of s)switch(e.role){case`system`:c.push(e.content);break;case`user`:{let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`file`){let e=gt({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=xt(t);n.length>0&&l.push({type:`user_input`,content:n});break}case`assistant`:{let t=[],n=()=>{t.length>0&&(l.push({type:`model_output`,content:t}),t=[])};for(let a of e.content)if(a.type===`text`)t.push({type:`text`,text:a.text});else if(a.type===`reasoning`){n();let e=a.providerOptions?.google?.signature;l.push({type:`thought`,...e==null?{}:{signature:e},summary:a.text.length>0?[{type:`text`,text:a.text}]:void 0})}else if(a.type===`file`){let e=gt({part:a,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(a.type===`tool-call`){n();let e=a.providerOptions?.google?.signature,t=typeof a.input==`string`?vt(a.input):a.input??{};l.push({type:`function_call`,id:a.toolCallId,name:a.toolName,arguments:t,...e==null?{}:{signature:e}})}else i.push({type:`other`,message:`google.interactions: unsupported assistant content part type "${a.type}"; part dropped.`});n();break}case`tool`:{let t=[];for(let n of e.content){if(n.type!==`tool-result`){i.push({type:`other`,message:`google.interactions: unsupported tool message part type "${n.type}"; part dropped.`});continue}let e=yt({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:n.providerOptions?.google?.signature,warnings:i});t.push(e)}t.length>0&&l.push({type:`user_input`,content:t});break}}return{input:l,systemInstruction:c.length>0?c.join(`
|
|
6
|
+
`})}if(f&&c!=null){let e=Array.from(new Set(p));c({type:`other`,message:`Replayed ${p.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${e.map(e=>`\`${e}\``).join(`, `)}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function U(e){return e.includes(`/`)?e:`models/${e}`}var be=P(()=>O(s({responseModalities:i(f([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:d().optional(),includeThoughts:r().optional(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:f([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:f([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).optional(),imageSize:f([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:d(),longitude:d()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:f([`standard`,`flex`,`priority`]).optional(),sharedRequestType:f([`priority`,`flex`,`standard`]).optional(),requestType:f([`shared`]).optional()})));function xe({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:H(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var Se=class{constructor(){this.accumulatedArgs={},this.jsonText=``,this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t=``;for(let n of e){let e=n.jsonPath.replace(/^\$\./,``);if(!e)continue;let r=Ce(e),i=we(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);Te(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Ee(n);a!=null&&(Te(this.accumulatedArgs,r,a.value),t+=this.emitNavigationTo(r,n,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs);return{finalJSON:e,closingDelta:e.slice(this.jsonText.length)}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:``,isArray:!1,childCount:0}),`{`):``}emitNavigationTo(e,t,n){let r=``;this.stringOpen&&=(r+=`"`,!1),r+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],o=this.findCommonStackDepth(i);return r+=this.closeDownTo(o),r+=this.openDownTo(i,a),r+=this.emitLeaf(a,t,n),r}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let r=0;r<t&&this.pathStack[r+1].segment===e[r];r++)n++;return n+1}closeDownTo(e){let t=``;for(;this.pathStack.length>e;){let e=this.pathStack.pop();t+=e.isArray?`]`:`}`}return t}openDownTo(e,t){let n=``,r=this.pathStack.length-1;for(let i=r;i<e.length;i++){let r=e[i],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(n+=`,`),a.childCount++,typeof r==`string`&&(n+=`${JSON.stringify(r)}:`);let o=typeof(i+1<e.length?e[i+1]:t)==`number`;n+=o?`[`:`{`,this.pathStack.push({segment:r,isArray:o,childCount:0})}return n}emitLeaf(e,t,n){let r=``,i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(r+=`,`),i.childCount++,typeof e==`string`&&(r+=`${JSON.stringify(e)}:`),t.stringValue!=null&&t.willContinue?(r+=n.slice(0,-1),this.stringOpen=!0):r+=n,r}};function Ce(e){let t=[];for(let n of e.split(`.`)){let e=n.indexOf(`[`);if(e===-1)t.push(n);else{e>0&&t.push(n.slice(0,e));for(let e of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(e[1],10))}}return t}function we(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Te(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];r[n]??(r[n]=typeof i==`number`?[]:{}),r=r[n]}r[t[t.length-1]]=n}function Ee(e){let t=e.stringValue??e.numberValue??e.boolValue;if(t!=null)return{value:t,json:JSON.stringify(t)};if(`nullValue`in e)return{value:null,json:`null`}}function De({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`other`}}var Oe=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??j}static[k](e){return E({modelId:e.modelId,config:e.config})}static[D](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:m=!1}={}){let h=[],g=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],_;for(let e of g)if(_=await v({provider:e,providerOptions:p,schema:be}),_!=null)break;_==null&&!g.includes(`google`)&&(_=await v({provider:`google`,providerOptions:p,schema:be}));let y=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!y&&h.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),_?.streamFunctionCallArguments&&!y&&h.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),_?.serviceTier&&y&&h.push({type:`other`,message:`'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo`}),(_?.sharedRequestType||_?.requestType)&&!y&&h.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let b=y&&(_?.sharedRequestType||_?.requestType)?{..._.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":_.sharedRequestType},..._.requestType&&{"X-Vertex-AI-LLM-Request-Type":_.requestType}}:void 0,x=y?void 0:_?.serviceTier,S=this.modelId.toLowerCase().startsWith(`gemma-`),C=/^gemini-3[.-]/.test(this.modelId),{contents:w,systemInstruction:T}=ye(e,{isGemmaModel:S,isGemini3Model:C,onWarning:e=>h.push(e),providerOptionsNames:g,supportsFunctionResponseParts:C}),{tools:E,toolConfig:D,toolWarnings:O}=xe({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:y}),k=Me({reasoning:f,modelId:this.modelId,warnings:h}),A=_?.thinkingConfig||k?{...k,..._?.thinkingConfig}:void 0,ee=m&&y?_?.streamFunctionCallArguments??!1:void 0,j=D||ee||_?.retrievalConfig?{...D,...ee&&{functionCallingConfig:{...D?.functionCallingConfig,streamFunctionCallArguments:!0}},..._?.retrievalConfig&&{retrievalConfig:_.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(_?.structuredOutputs??!0)?H(c.schema):void 0,..._?.audioTimestamp&&{audioTimestamp:_.audioTimestamp},responseModalities:_?.responseModalities,thinkingConfig:A,..._?.mediaResolution&&{mediaResolution:_.mediaResolution},..._?.imageConfig&&{imageConfig:_.imageConfig}},contents:w,systemInstruction:S?void 0:T,safetySettings:_?.safetySettings,tools:E,toolConfig:j,cachedContent:_?.cachedContent,labels:_?.labels,serviceTier:x},warnings:[...h,...O],providerOptionsNames:g,extraHeaders:b}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=I(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c,rawValue:l}=await S({url:`${this.config.baseURL}/${U(this.modelId)}:generateContent`,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:M(He),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c.candidates[0],d=[],f=u.content?.parts??[],p=c.usageMetadata,m,h;for(let e of f)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();m=t,d.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)d.push({type:`tool-result`,toolCallId:m,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),m=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&d.length>0){let e=d[d.length-1];e.providerMetadata=t}}else d.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)d.push({type:`tool-call`,toolCallId:e.functionCall.id??this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;d.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?a({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();h=t,d.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):a({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=h??e.toolResponse.id??this.config.generateId();d.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):a({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),h=void 0}let g=Fe({groundingMetadata:u.groundingMetadata,generateId:this.config.generateId})??[];for(let e of g)d.push(e);return{content:d,finishReason:{unified:De({finishReason:u.finishReason,hasToolCalls:d.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:u.finishReason??void 0},usage:de(p),warnings:n,providerMetadata:a({promptFeedback:c.promptFeedback??null,groundingMetadata:u.groundingMetadata??null,urlContextMetadata:u.urlContextMetadata??null,safetyRatings:u.safetyRatings??null,usageMetadata:p??null,finishMessage:u.finishMessage??null,serviceTier:p?.serviceTier??null}),request:{body:t},response:{headers:s,body:l}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e,{isStreaming:!0}),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=I(this.config.headers?await B(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c}=await S({url:`${this.config.baseURL}/${U(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:L(Ue),abortSignal:e.abortSignal,fetch:this.config.fetch}),l={unified:`other`,raw:void 0},u,d,f=null,p=null,m=this.config.generateId,h=!1,g=null,_=null,v=0,y=new Set,b,x,C=[],w=e=>{let t=C.pop();if(t==null)return;let{finalJSON:n,closingDelta:r}=t.accumulator.finalize();r.length>0&&e.enqueue({type:`tool-input-delta`,id:t.toolCallId,delta:r,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-input-end`,id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-call`,toolCallId:t.toolCallId,toolName:t.toolName,input:n,providerMetadata:t.providerMetadata}),h=!0};return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(u=i);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(f=o.groundingMetadata),o.urlContextMetadata!=null&&(p=o.urlContextMetadata);let c=Fe({groundingMetadata:o.groundingMetadata,generateId:m});if(c!=null)for(let e of c)e.sourceType===`url`&&!y.has(e.url)&&(y.add(e.url),n.enqueue(e));if(s!=null){let e=s.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=m();b=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=b;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),b=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&g!==null&&n.enqueue({type:`text-delta`,id:g,delta:``,providerMetadata:e}):t.thought===!0?(g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_===null&&(_=String(v++),n.enqueue({type:`reasoning-start`,id:_,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:_,delta:t.text,providerMetadata:e})):(_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null),g===null&&(g=String(v++),n.enqueue({type:`text-start`,id:g,providerMetadata:e})),n.enqueue({type:`text-delta`,id:g,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){g!==null&&(n.enqueue({type:`text-end`,id:g}),g=null),_!==null&&(n.enqueue({type:`reasoning-end`,id:_}),_=null);let e=t.thought===!0,r=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;n.enqueue({type:e?`reasoning-file`:`file`,mediaType:t.inlineData.mimeType,data:{type:`data`,data:t.inlineData.data},providerMetadata:r})}else if(`toolCall`in t&&t.toolCall){let e=t.toolCall.id??m();x=e;let r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});n.enqueue({type:`tool-call`,toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:r})}else if(`toolResponse`in t&&t.toolResponse){let e=x??t.toolResponse.id??m(),r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});n.enqueue({type:`tool-result`,toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:r}),x=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,i=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=t.functionCall.name!=null&&t.functionCall.args!=null&&t.functionCall.partialArgs==null,s=t.functionCall.name!=null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue!==!0;if(r){if(t.functionCall.name!=null){let r=t.functionCall.id??m(),i=new Se;if(C.push({toolCallId:r,toolName:t.functionCall.name,accumulator:i,providerMetadata:e}),n.enqueue({type:`tool-input-start`,id:r,toolName:t.functionCall.name,providerMetadata:e}),t.functionCall.partialArgs!=null){let a=t.functionCall.partialArgs,{textDelta:o}=i.processPartialArgs(a);o.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:o,providerMetadata:e}),t.functionCall.willContinue!==!0&&a.every(e=>e.willContinue!==!0)&&w(n)}}else if(t.functionCall.partialArgs!=null&&C.length>0){let r=C[C.length-1],i=t.functionCall.partialArgs,{textDelta:a}=r.accumulator.processPartialArgs(i);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:a,providerMetadata:e}),t.functionCall.willContinue!==!0&&i.every(e=>e.willContinue!==!0)&&w(n)}}else if(i&&C.length>0)w(n);else if(o){let r=t.functionCall.id??m(),i=t.functionCall.name,a=typeof t.functionCall.args==`string`?t.functionCall.args:JSON.stringify(t.functionCall.args??{});n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:a,providerMetadata:e}),h=!0}else if(s){let r=t.functionCall.id??m(),i=t.functionCall.name;n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:`{}`,providerMetadata:e}),h=!0}}}o.finishReason!=null&&(l={unified:De({finishReason:o.finishReason,hasToolCalls:h}),raw:o.finishReason},d=a({promptFeedback:r.promptFeedback??null,groundingMetadata:f,urlContextMetadata:p,safetyRatings:o.safetyRatings??null,usageMetadata:i??null,finishMessage:o.finishMessage??null,serviceTier:u?.serviceTier??null}))},flush(e){g!==null&&e.enqueue({type:`text-end`,id:g}),_!==null&&e.enqueue({type:`reasoning-end`,id:_}),e.enqueue({type:`finish`,finishReason:l,usage:de(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function ke(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function Ae(){return 65536}function je(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function Me({reasoning:e,modelId:t,warnings:n}){if(w(e))return ke(t)&&!t.includes(`gemini-3-pro-image`)?Ne({reasoning:e,warnings:n}):Pe({reasoning:e,modelId:t,warnings:n})}function Ne({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=x({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Pe({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=b({reasoning:e,maxOutputTokens:Ae(),maxReasoningBudget:je(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function Fe({groundingMetadata:e,generateId:t}){if(!e?.groundingChunks)return;let n=[];for(let r of e.groundingChunks)if(r.web!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.web.uri,title:r.web.title??void 0});else if(r.image!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.image.sourceUri,title:r.image.title??void 0});else if(r.retrievedContext!=null){let e=r.retrievedContext.uri,i=r.retrievedContext.fileSearchStore;if(e&&(e.startsWith(`http://`)||e.startsWith(`https://`)))n.push({type:`source`,sourceType:`url`,id:t(),url:e,title:r.retrievedContext.title??void 0});else if(e){let i=r.retrievedContext.title??`Unknown Document`,a=`application/octet-stream`,o;e.endsWith(`.pdf`)?(a=`application/pdf`,o=e.split(`/`).pop()):e.endsWith(`.txt`)?(a=`text/plain`,o=e.split(`/`).pop()):e.endsWith(`.docx`)?(a=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,o=e.split(`/`).pop()):e.endsWith(`.doc`)?(a=`application/msword`,o=e.split(`/`).pop()):(e.match(/\.(md|markdown)$/)&&(a=`text/markdown`),o=e.split(`/`).pop()),n.push({type:`source`,sourceType:`document`,id:t(),mediaType:a,title:i,filename:o})}else if(i){let e=r.retrievedContext.title??`Unknown Document`;n.push({type:`source`,sourceType:`document`,id:t(),mediaType:`application/octet-stream`,title:e,filename:i.split(`/`).pop()})}}else r.maps!=null&&r.maps.uri&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.maps.uri,title:r.maps.title??void 0});return n.length>0?n:void 0}var Ie=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:d().nullish(),endIndex:d().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(d()).nullish(),supportChunkIndices:i(d()).nullish(),confidenceScores:i(d()).nullish(),confidenceScore:i(d()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:d()}),s({})]).nullish()}),Le=s({jsonPath:o(),stringValue:o().nullish(),numberValue:d().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),Re=()=>s({parts:i(c([s({functionCall:s({id:o().nullish(),name:o().nullish(),args:l().nullish(),partialArgs:i(Le).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),W=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:d().nullish(),severity:o().nullish(),severityScore:d().nullish(),blocked:r().nullish()}),ze=i(s({modality:o(),tokenCount:d()})).nullish(),Be=s({cachedContentTokenCount:d().nullish(),thoughtsTokenCount:d().nullish(),promptTokenCount:d().nullish(),candidatesTokenCount:d().nullish(),totalTokenCount:d().nullish(),trafficType:o().nullish(),serviceTier:o().nullish(),promptTokensDetails:ze,candidatesTokensDetails:ze}),Ve=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),He=P(()=>O(s({candidates:i(s({content:Re().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(W()).nullish(),groundingMetadata:Ie().nullish(),urlContextMetadata:Ve().nullish()})),usageMetadata:Be.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(W()).nullish()}).nullish()}))),Ue=P(()=>O(s({candidates:i(s({content:Re().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(W()).nullish(),groundingMetadata:Ie().nullish(),urlContextMetadata:Ve().nullish()})).nullish(),usageMetadata:Be.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(W()).nullish()}).nullish()}))),We=N({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),Ge=N({id:`google.enterprise_web_search`,inputSchema:P(()=>O(s({}))),outputSchema:P(()=>O(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:d().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().describe(`Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.`).optional()}).passthrough();var Ke=N({id:`google.file_search`,inputSchema:P(()=>O(s({}))),outputSchema:P(()=>O(s({})))}),qe=N({id:`google.google_maps`,inputSchema:P(()=>O(s({}))),outputSchema:P(()=>O(s({})))}),Je=s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough(),Ye={googleSearch:N({id:`google.google_search`,inputSchema:P(()=>O(s({}))),outputSchema:P(()=>O(s({})))}),enterpriseWebSearch:Ge,googleMaps:qe,urlContext:N({id:`google.url_context`,inputSchema:P(()=>O(s({}))),outputSchema:P(()=>O(s({})))}),fileSearch:Ke,codeExecution:We,vertexRagStore:N({id:`google.vertex_rag_store`,inputSchema:P(()=>O(s({}))),outputSchema:P(()=>O(s({})))})},Xe=P(()=>O(s({personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:f([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish(),googleSearch:Je.optional()}))),Ze=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[k](e){return E({modelId:e.modelId,config:e.config})}static[D](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?Qe(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return Qe(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.length>0)throw Error(`Google Gemini API does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);if(d!=null)throw Error(`Google Gemini API does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await v({provider:`google`,providerOptions:s,schema:Xe}),m=((t=this.config._internal)?.currentDate)?.call(t)??new Date,h={sampleCount:r};if(a!=null&&(h.aspectRatio=a),p){let{googleSearch:e,...t}=p;e!=null&&f.push({type:`unsupported`,feature:`googleSearch`,details:`Google Search grounding is only supported on Gemini image models.`}),Object.assign(h,t)}let g={instances:[{prompt:n}],parameters:h},{responseHeaders:_,value:y}=await S({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:I(this.config.headers?await B(this.config.headers):void 0,c),body:g,failedResponseHandler:V,successfulResponseHandler:M($e),abortSignal:l,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:y.predictions.map(()=>({}))}},response:{timestamp:m,modelId:this.modelId,headers:_}}}async doGenerateGemini(e){var t;let{prompt:n,n:r,size:i,aspectRatio:a,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(d!=null)throw Error(`Gemini image models do not support mask-based image editing.`);if(r!=null&&r>1)throw Error(`Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let p=[];if(n!=null&&p.push({type:`text`,text:n}),u!=null&&u.length>0)for(let e of u)e.type===`url`?p.push({type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}):p.push({type:`file`,data:{type:`data`,data:typeof e.data==`string`?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let m=[{role:`user`,content:p}],h=await v({provider:`google`,providerOptions:s,schema:Xe}),{googleSearch:g,..._}=s?.google??{},y=await new Oe(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??j}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,..._}},tools:h?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:h.googleSearch}],headers:c,abortSignal:l}),b=((t=this.config._internal)?.currentDate)?.call(t)??new Date,x=[];for(let e of y.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&x.push(F(e.data.data));return{images:x,warnings:f,providerMetadata:{google:{...y.providerMetadata?.google??{},images:x.map(()=>({}))}},response:{timestamp:b,modelId:this.modelId,headers:y.response?.headers},usage:y.usage?{inputTokens:y.usage.inputTokens.total,outputTokens:y.usage.outputTokens.total,totalTokens:(y.usage.inputTokens.total??0)+(y.usage.outputTokens.total??0)}:void 0}}};function Qe(e){return e.startsWith(`gemini-`)}var $e=P(()=>O(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),et=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await v({provider:`google`,providerOptions:t.providerOptions,schema:nt}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=ee(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,h=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-h>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await A(p);let{value:t}=await z({url:`${this.config.baseURL}/${f.name}`,headers:I(r),successfulResponseHandler:M(tt),failedResponseHandler:V,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},tt=P(()=>O(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),nt=P(()=>O(s({displayName:o().nullish(),pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish()}).passthrough())),rt=P(()=>O(s({pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish(),personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),it=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await v({provider:`google`,providerOptions:t.providerOptions,schema:rt}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:te(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await S({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:I(await B(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:M(at),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),m=l,h;for(;!m.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await A(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await z({url:`${this.config.baseURL}/${u}`,headers:I(await B(this.config.headers),t.headers),successfulResponseHandler:M(at),failedResponseHandler:V,abortSignal:t.abortSignal,fetch:this.config.fetch});m=n,h=r}if(m.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${m.error.message}`});let g=m.response;if(!g?.generateVideoResponse?.generatedSamples||g.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(m)}`});let _=[],y=[],b=(await B(this.config.headers))?.[`x-goog-api-key`];for(let e of g.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=b?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${b}`:e.video.uri;_.push({type:`url`,url:t,mediaType:`video/mp4`}),y.push({uri:e.video.uri})}if(_.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No valid videos in response`});return{videos:_,warnings:i,response:{timestamp:r,modelId:this.modelId,headers:h},providerMetadata:{google:{videos:y}}}}},at=s({name:o().nullish(),done:r().nullish(),error:s({code:d().nullish(),message:o(),status:o().nullish()}).nullish(),response:s({generateVideoResponse:s({generatedSamples:i(s({video:s({uri:o().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),ot=P(()=>O(s({candidates:i(s({content:s({parts:i(s({inlineData:s({mimeType:o().nullish(),data:o().nullish()}).nullish()})).nullish()}).nullish()})).nullish()}))),st=s({prebuiltVoiceConfig:s({voiceName:o()})}),ct=P(()=>O(s({multiSpeakerVoiceConfig:s({speakerVoiceConfigs:i(s({speaker:o(),voiceConfig:st}))}).optional()}))),lt=`Kore`,ut=24e3,dt=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[k](e){return E({modelId:e.modelId,config:e.config})}static[D](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({text:e,voice:t=lt,outputFormat:n,instructions:r,speed:i,language:a,providerOptions:o}){let s=[],c=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],l;for(let e of c)if(l=await v({provider:e,providerOptions:o,schema:ct}),l!=null)break;l==null&&!c.includes(`google`)&&(l=await v({provider:`google`,providerOptions:o,schema:ct}));let u=l?.multiSpeakerVoiceConfig,d=u?{multiSpeakerVoiceConfig:u}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}},f=e;r!=null&&(u?s.push({type:`unsupported`,feature:`instructions`,details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."}):f=`${r}: ${e}`),i!=null&&s.push({type:`unsupported`,feature:`speed`,details:"Google Gemini TTS models do not support the `speed` option. It was ignored."}),a!=null&&s.push({type:`unsupported`,feature:`language`,details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let p=`wav`;return n===`pcm`?p=`pcm`:n!=null&&n!==`wav`&&s.push({type:`unsupported`,feature:`outputFormat`,details:`Unsupported output format: ${n}. Using wav instead.`}),{requestBody:{contents:[{role:`user`,parts:[{text:f}]}],generationConfig:{responseModalities:[`AUDIO`],speechConfig:d}},warnings:s,outputFormat:p}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i,outputFormat:a}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:c}=await S({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:I(this.config.headers?await B(this.config.headers):void 0,e.headers),body:r,failedResponseHandler:V,successfulResponseHandler:M(ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),l,u;for(let e of o.candidates??[]){for(let t of e.content?.parts??[])if(t.inlineData?.data){l=t.inlineData.data,u=t.inlineData.mimeType??void 0;break}if(l!=null)break}let d=ft(u)??ut,f=l==null?new Uint8Array:re(l),p=a===`pcm`||f.length===0?f:pt(f,d);return a===`pcm`&&f.length>0&&i.push({type:`unsupported`,feature:`outputFormat`,details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${d} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`}),{audio:p,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:s,body:c},providerMetadata:{google:{sampleRate:d,mimeType:u??null}}}}};function ft(e){if(e==null)return;let t=/rate=(\d+)/.exec(e);return t?Number.parseInt(t[1],10):void 0}function pt(e,t){let n=t*2,r=e.length,i=new ArrayBuffer(44+r),a=new DataView(i);G(a,0,`RIFF`),a.setUint32(4,36+r,!0),G(a,8,`WAVE`),G(a,12,`fmt `),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,n,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),G(a,36,`data`),a.setUint32(40,r,!0);let o=new Uint8Array(i);return o.set(e,44),o}function G(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function K(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.total_input_tokens??0,n=e.total_output_tokens??0,r=e.total_thought_tokens??0,i=e.total_cached_tokens??0;return{inputTokens:{total:e.total_input_tokens??void 0,noCache:e.total_input_tokens==null?void 0:t-i,cacheRead:e.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:e.total_output_tokens==null&&e.total_thought_tokens==null?void 0:n+r,text:e.total_output_tokens??void 0,reasoning:e.total_thought_tokens??void 0},raw:e}}var mt={pdf:`application/pdf`,txt:`text/plain`,md:`text/markdown`,markdown:`text/markdown`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};function ht(e){let t=e.toLowerCase();for(let[e,n]of Object.entries(mt))if(t.endsWith(`.${e}`))return n;return`application/octet-stream`}function gt(e){let t=e.split(`/`),n=t[t.length-1];return n&&n.length>0?n:void 0}function _t({annotation:e,generateId:t}){switch(e.type){case`url_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.title==null?{}:{title:n.title}}}case`file_citation`:{let n=e,r=n.url??n.document_uri??n.file_name;if(r==null||r.length===0)return;if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`source`,sourceType:`url`,id:t(),url:r,...n.file_name==null?{}:{title:n.file_name}};let i=n.file_name??gt(r),a=ht(r);return{type:`source`,sourceType:`document`,id:t(),mediaType:a,title:n.file_name??i??r,...i==null?{}:{filename:i}}}case`place_citation`:{let n=e;return n.url==null||n.url.length===0?void 0:{type:`source`,sourceType:`url`,id:t(),url:n.url,...n.name==null?{}:{title:n.name}}}default:return}}function vt({block:e,generateId:t}){let n=[];switch(e.type){case`url_context_result`:{let r=e.result??[];for(let e of r)e?.url==null||e.url.length===0||e.status!=null&&e.status!==`success`||n.push({type:`source`,sourceType:`url`,id:t(),url:e.url});break}case`google_search_result`:{let r=e.result??[];for(let e of r){let r=e?.url;r==null||r.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r,...e.title==null?{}:{title:e.title}})}break}case`google_maps_result`:{let r=e.result??[];for(let e of r)for(let r of e.places??[])r.url==null||r.url.length===0||n.push({type:`source`,sourceType:`url`,id:t(),url:r.url,...r.name==null?{}:{title:r.name}});break}case`file_search_result`:{let r=e.result??[];for(let e of r){if(typeof e!=`object`||!e)continue;let r=e,i=r.url??r.document_uri??r.file_name;if(i==null||i.length===0)continue;if(i.startsWith(`http://`)||i.startsWith(`https://`)){n.push({type:`source`,sourceType:`url`,id:t(),url:i,...r.title==null?{}:{title:r.title}});continue}let a=r.file_name??gt(i),o=ht(i);n.push({type:`source`,sourceType:`document`,id:t(),mediaType:o,title:r.title??r.file_name??a??i,...a==null?{}:{filename:a}})}break}default:break}return n}function q({annotations:e,generateId:t}){if(e==null)return[];let n=new Set,r=[];for(let i of e){let e=_t({annotation:i,generateId:t});if(e==null)continue;let a=e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`;n.has(a)||(n.add(a),r.push(e))}return r}function J({status:e,hasFunctionCall:t}){switch(e){case`completed`:return t?`tool-calls`:`stop`;case`requires_action`:return`tool-calls`;case`failed`:return`error`;case`incomplete`:return`length`;case`cancelled`:return`other`;default:return`other`}}var yt=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),bt=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function xt(e){return e.replace(/_call$/,``)}function St(e){return e.replace(/_result$/,``)}function Ct({warnings:e,generateId:t,includeRawChunks:n,serviceTier:r}){let i,a,o=r,s,c=!1,l=new Map,u=new Set;function d(e){return e.sourceType===`url`?`url:${e.url}`:`doc:${e.filename??e.title}`}return new TransformStream({start(t){t.enqueue({type:`stream-start`,warnings:e})},transform(e,r){if(n&&r.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){s=`failed`,r.enqueue({type:`error`,error:e.error});return}let f=e.value,p=f.event_type;switch(p){case`interaction.created`:{let e=f.interaction;i=e?.id!=null&&e.id.length>0?e.id:void 0;let t=e?.created,n;if(typeof t==`string`){let e=new Date(t);Number.isNaN(e.getTime())||(n=e)}r.enqueue({type:`response-metadata`,...i==null?{}:{id:i},modelId:e?.model,...n?{timestamp:n}:{}});break}case`step.start`:{let e=f,n=e.step,a=e.index,o=`${i??`interaction`}:${a}`,s=n?.type;if(s===`model_output`){let e=n?.content?.[0];if(e?.type===`text`){l.set(a,{kind:`text`,id:o,emittedSourceKeys:new Set}),r.enqueue({type:`text-start`,id:o});let n=q({annotations:e.annotations,generateId:t});for(let e of n){let t=d(e);u.has(t)||(u.add(t),r.enqueue(e))}}else e?.type===`image`?l.set(a,{kind:`image`,id:o,...e.data==null?{}:{data:e.data},...e.mime_type==null?{}:{mimeType:e.mime_type},...e.uri==null?{}:{uri:e.uri}}):l.set(a,{kind:`pending_model_output`,id:o})}else if(s===`thought`){let e=n?.signature;if(l.set(a,{kind:`reasoning`,id:o,...e==null?{}:{signature:e}}),r.enqueue({type:`reasoning-start`,id:o}),Array.isArray(n?.summary))for(let e of n.summary)e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:o,delta:e.text})}else if(s===`function_call`){let e=n?.id??o,t=n?.name??`unknown`;c=!0;let i={kind:`function_call`,id:o,toolCallId:e,toolName:t,argumentsAccum:``,...n?.signature==null?{}:{signature:n.signature}};l.set(a,i),r.enqueue({type:`tool-input-start`,id:e,toolName:t})}else if(s!=null&&yt.has(s)){let e=s===`mcp_server_tool_call`?n?.name??`mcp_server_tool`:xt(s),t={kind:`builtin_tool_call`,id:o,blockType:s,toolCallId:n?.id??o,toolName:e,arguments:n?.arguments??{},callEmitted:!1};l.set(a,t)}else if(s!=null&&bt.has(s)){let e=s===`mcp_server_tool_result`?n?.name??`mcp_server_tool`:St(s),t={kind:`builtin_tool_result`,id:o,blockType:s,callId:n?.call_id??o,toolName:e,result:n?.result??null,...n?.is_error==null?{}:{isError:n.is_error},resultEmitted:!1};l.set(a,t)}else l.set(a,{kind:`unknown`,id:o});break}case`step.delta`:{let e=f,n=l.get(e.index);if(n==null)break;let a=e.delta?.type;if(n.kind===`pending_model_output`&&(a===`text`||a===`text_annotation`||a===`text_annotation_delta`)){let t={kind:`text`,id:n.id,emittedSourceKeys:new Set};l.set(e.index,t),n=t,r.enqueue({type:`text-start`,id:t.id})}if(a===`image`&&(n.kind===`pending_model_output`||n.kind===`text`||n.kind===`image`)){let t=e.delta,a={};i!=null&&(a.interactionId=i);let o=Object.keys(a).length>0?{google:a}:void 0;t?.data!=null&&t.data.length>0?r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`data`,data:t.data},...o?{providerMetadata:o}:{}}):t?.uri!=null&&t.uri.length>0&&r.enqueue({type:`file`,mediaType:t.mime_type??`image/png`,data:{type:`url`,url:new URL(t.uri)},...o?{providerMetadata:o}:{}}),n.kind===`image`&&(n.data=void 0,n.uri=void 0);break}let o=e.delta;if(n.kind===`text`&&o?.type===`text`){let e=o.text??``;e.length>0&&r.enqueue({type:`text-delta`,id:n.id,delta:e})}else if(n.kind===`text`&&(o?.type===`text_annotation`||o?.type===`text_annotation_delta`)){let e=q({annotations:o.annotations,generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),n.emittedSourceKeys.add(e),r.enqueue(t))}}else if(n.kind===`image`&&o?.type===`image`)o.data!=null&&(n.data=o.data),o.mime_type!=null&&(n.mimeType=o.mime_type),o.uri!=null&&(n.uri=o.uri);else if(n.kind===`reasoning`){if(o?.type===`thought_summary`){let e=o.content;e?.type===`text`&&typeof e.text==`string`&&r.enqueue({type:`reasoning-delta`,id:n.id,delta:e.text})}else if(o?.type===`thought_signature`){let e=o.signature;e!=null&&(n.signature=e)}}else if(n.kind===`function_call`&&o?.type===`arguments_delta`){let e=typeof o.arguments==`string`?o.arguments:``;e.length>0&&(n.argumentsAccum+=e,r.enqueue({type:`tool-input-delta`,id:n.toolCallId,delta:e})),o.id!=null&&(n.toolCallId=o.id),o.signature!=null&&(n.signature=o.signature),c=!0}else n.kind===`builtin_tool_call`&&o?.type===n.blockType?(o.id!=null&&(n.toolCallId=o.id),o.arguments!=null&&typeof o.arguments==`object`&&(n.arguments=o.arguments),o.name!=null&&n.blockType===`mcp_server_tool_call`&&(n.toolName=o.name)):n.kind===`builtin_tool_result`&&o?.type===n.blockType&&(o.call_id!=null&&(n.callId=o.call_id),o.result!==void 0&&(n.result=o.result),o.is_error!=null&&(n.isError=o.is_error),o.name!=null&&n.blockType===`mcp_server_tool_result`&&(n.toolName=o.name));break}case`step.stop`:{let e=f,n=l.get(e.index);if(n==null)break;if(n.kind===`text`){let e=i==null?void 0:{google:{interactionId:i}};r.enqueue({type:`text-end`,id:n.id,...e?{providerMetadata:e}:{}})}else if(n.kind===`reasoning`){let e={};n.signature!=null&&(e.signature=n.signature),i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;r.enqueue({type:`reasoning-end`,id:n.id,...t?{providerMetadata:t}:{}})}else if(n.kind===`image`){let e={};i!=null&&(e.interactionId=i);let t=Object.keys(e).length>0?{google:e}:void 0;n.data!=null&&n.data.length>0?r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`data`,data:n.data},...t?{providerMetadata:t}:{}}):n.uri!=null&&n.uri.length>0&&r.enqueue({type:`file`,mediaType:n.mimeType??`image/png`,data:{type:`url`,url:new URL(n.uri)},...t?{providerMetadata:t}:{}})}else if(n.kind===`function_call`){let e=n.argumentsAccum.length>0?n.argumentsAccum:`{}`;r.enqueue({type:`tool-input-end`,id:n.toolCallId});let t={};n.signature!=null&&(t.signature=n.signature),i!=null&&(t.interactionId=i);let a=Object.keys(t).length>0?{google:t}:void 0;r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:e,...a?{providerMetadata:a}:{}})}else if(n.kind===`builtin_tool_call`&&!n.callEmitted)r.enqueue({type:`tool-call`,toolCallId:n.toolCallId,toolName:n.toolName,input:JSON.stringify(n.arguments??{}),providerExecuted:!0}),n.callEmitted=!0;else if(n.kind===`builtin_tool_result`&&!n.resultEmitted){r.enqueue({type:`tool-result`,toolCallId:n.callId,toolName:n.toolName,result:n.result??null}),n.resultEmitted=!0;let e=vt({block:{type:n.blockType,call_id:n.callId,result:n.result},generateId:t});for(let t of e){let e=d(t);u.has(e)||(u.add(e),r.enqueue(t))}}l.delete(e.index);break}case`interaction.status_update`:case`interaction.in_progress`:case`interaction.requires_action`:{let e=f;s=e.status==null?p===`interaction.requires_action`?`requires_action`:`in_progress`:e.status;break}case`interaction.completed`:{let e=f.interaction;e?.id!=null&&e.id.length>0&&(i=e.id),e?.status!=null&&(s=e.status),e?.usage!=null&&(a=e.usage),e?.service_tier!=null&&(o=e.service_tier);break}case`error`:{let e=f;s=`failed`;let t=e.error??{message:`Unknown interaction error`};r.enqueue({type:`error`,error:t});break}default:break}},flush(e){let t={unified:J({status:s,hasFunctionCall:c}),raw:s},n={google:{...i==null?{}:{interactionId:i},...o==null?{}:{serviceTier:o}}};e.enqueue({type:`finish`,finishReason:t,usage:K(a),providerMetadata:n})}})}function wt({prompt:e,previousInteractionId:t,store:n,mediaResolution:r}){let i=[],a=t!=null&&n===!1,o=t!=null&&n!==!1;a&&i.push({type:`other`,message:`google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted.`});let s=o?Et({prompt:e,previousInteractionId:t}):e,c=[],l=[];for(let e of s)switch(e.role){case`system`:c.push(e.content);break;case`user`:{let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`file`){let e=Tt({part:n,warnings:i,mediaResolution:r});e!=null&&t.push(e)}let n=At(t);n.length>0&&l.push({type:`user_input`,content:n});break}case`assistant`:{let t=[],n=()=>{t.length>0&&(l.push({type:`model_output`,content:t}),t=[])};for(let a of e.content)if(a.type===`text`)t.push({type:`text`,text:a.text});else if(a.type===`reasoning`){n();let e=a.providerOptions?.google?.signature;l.push({type:`thought`,...e==null?{}:{signature:e},summary:a.text.length>0?[{type:`text`,text:a.text}]:void 0})}else if(a.type===`file`){let e=Tt({part:a,warnings:i,mediaResolution:r});e!=null&&t.push(e)}else if(a.type===`tool-call`){n();let e=a.providerOptions?.google?.signature,t=typeof a.input==`string`?Dt(a.input):a.input??{};l.push({type:`function_call`,id:a.toolCallId,name:a.toolName,arguments:t,...e==null?{}:{signature:e}})}else i.push({type:`other`,message:`google.interactions: unsupported assistant content part type "${a.type}"; part dropped.`});n();break}case`tool`:{let t=[];for(let n of e.content){if(n.type!==`tool-result`){i.push({type:`other`,message:`google.interactions: unsupported tool message part type "${n.type}"; part dropped.`});continue}let e=Ot({toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,signature:n.providerOptions?.google?.signature,warnings:i});t.push(e)}t.length>0&&l.push({type:`user_input`,content:t});break}}return{input:l,systemInstruction:c.length>0?c.join(`
|
|
7
7
|
|
|
8
|
-
`):void 0,warnings:i}}function
|
|
8
|
+
`):void 0,warnings:i}}function Tt({part:e,warnings:t,mediaResolution:n}){if(e.data.type===`text`)return{type:`text`,text:e.data.text};let r=h(e.mediaType),i;switch(r){case`image`:i=`image`;break;case`audio`:i=`audio`;break;case`video`:i=`video`;break;case`application`:i=`document`;break;default:i=void 0}if(i==null){t.push({type:`other`,message:`google.interactions: unsupported file media type "${e.mediaType}"; part dropped.`});return}let a=n!=null&&(i===`image`||i===`video`)?{resolution:n}:{};switch(e.data.type){case`data`:{let t=m({part:e});return{type:i,data:F(e.data.data),mime_type:t,...a}}case`url`:return{type:i,uri:e.data.url.toString(),...g(e.mediaType)?{mime_type:e.mediaType}:{},...a};case`reference`:{let t=T({reference:e.data.reference,provider:`google`});return{type:i,uri:t,...g(e.mediaType)?{mime_type:e.mediaType}:{},...a}}}}function Et({prompt:e,previousInteractionId:t}){let n=[],r=new Set;for(let i of e){if(i.role===`assistant`){if(i.content.some(e=>e.providerOptions?.google?.interactionId===t)){for(let e of i.content)e.type===`tool-call`&&r.add(e.toolCallId);continue}n.push(i);continue}if(i.role===`tool`){let e=i.content.filter(e=>e.type===`tool-result`?!r.has(e.toolCallId):!0);if(e.length===0)continue;n.push({...i,content:e});continue}n.push(i)}return n}function Dt(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{value:t}}catch{return{value:e}}}function Ot({toolCallId:e,toolName:t,output:n,signature:r,warnings:i}){let a={type:`function_result`,call_id:e,name:t,...r==null?{}:{signature:r}};switch(n.type){case`text`:return{...a,result:n.value};case`json`:return{...a,result:JSON.stringify(n.value)};case`error-text`:return{...a,is_error:!0,result:n.value};case`error-json`:return{...a,is_error:!0,result:JSON.stringify(n.value)};case`execution-denied`:return{...a,is_error:!0,result:n.reason??`Tool execution denied by user.`};case`content`:{let e=[];for(let t of n.value)if(t.type===`text`)e.push({type:`text`,text:t.text});else if(t.type===`file`){if(h(t.mediaType)!==`image`){i.push({type:`other`,message:`google.interactions: tool-result file with mediaType "${t.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}let n=kt({part:t,warnings:i});n!=null&&e.push(n)}else i.push({type:`other`,message:`google.interactions: tool-result content part type "${t.type}" is not supported; part dropped.`});return{...a,result:e}}}}function kt({part:e,warnings:t}){switch(e.data.type){case`data`:{let t=g(e.mediaType)?e.mediaType:m({part:{type:`file`,mediaType:e.mediaType,data:e.data}});return{type:`image`,data:F(e.data.data),mime_type:t}}case`url`:return{type:`image`,uri:e.data.url.toString(),...g(e.mediaType)?{mime_type:e.mediaType}:{}};case`reference`:return{type:`image`,uri:T({reference:e.data.reference,provider:`google`}),...g(e.mediaType)?{mime_type:e.mediaType}:{}};case`text`:t.push({type:`other`,message:'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'});return}}function At(e){if(e.length<2)return e;let t=[];for(let n of e){let e=t[t.length-1];if(n.type===`text`&&e!=null&&e.type===`text`&&e.annotations==null&&n.annotations==null){let r={type:`text`,text:`${e.text}
|
|
9
9
|
|
|
10
|
-
${n.text}`};t[t.length-1]=r;continue}t.push(n)}return t}var
|
|
11
|
-
`);r.push({type:`reasoning`,text:t,...Y({signature:e.signature,interactionId:n})});break}case`function_call`:{i=!0;let e=a;r.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.arguments??{}),...Y({signature:e.signature,interactionId:n})});break}default:if(Mt.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:Pt(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id??t(),toolName:i,input:o,providerExecuted:!0})}else if(Nt.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:Ft(e);r.push({type:`tool-result`,toolCallId:n.call_id??t(),toolName:i,result:n.result??null});let o=lt({block:a,generateId:t});for(let e of o)r.push(e)}break}}return{content:r,hasFunctionCall:i}}var It=()=>globalThis.fetch;async function Lt({baseURL:e,interactionId:t,headers:n,fetch:r=It()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:ne(I({"Content-Type":`application/json`},n),S()),body:`{}`});try{await e.text()}catch{}}catch{}}var Rt=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function Z(e){return e!=null&&Rt.has(e)}var zt=1e3,Bt=1e4,Vt=1800*1e3;async function Ht({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,initialDelayMs:a=zt,maxDelayMs:o=Bt,timeoutMs:s=Vt}){if(t==null||t.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let c=Date.now(),l=a,u=`${e}/interactions/${encodeURIComponent(t)}`,d=()=>Lt({baseURL:e,interactionId:t,headers:n,fetch:r});try{for(;;){if(i?.aborted)throw await d(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-c>s)throw Error(`google.interactions: timed out polling interaction ${t} after ${s}ms.`);await k(l,{abortSignal:i});let{value:e,rawValue:a,responseHeaders:f}=await z({url:u,headers:n,failedResponseHandler:V,successfulResponseHandler:M(J),abortSignal:i,fetch:r});if(Z(e.status))return{response:e,rawResponse:a,responseHeaders:f};l=Math.min(l*2,o)}}catch(e){throw R(e)&&await d(),e}}function Ut({tools:e,toolChoice:t}){let n=[],r=e?.length?e:void 0;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let e of r){if(e.type===`function`){i.push({type:`function`,name:e.name,description:e.description??``,parameters:e.inputSchema});continue}if(e.type===`provider`){let t=e.args??{};switch(e.id){case`google.google_search`:{let e=t.searchTypes,n;if(typeof e==`object`&&e){let t=[];e.webSearch!=null&&t.push(`web_search`),e.imageSearch!=null&&t.push(`image_search`),t.length>0&&(n=t)}i.push({type:`google_search`,...n==null?{}:{search_types:n}});break}case`google.code_execution`:i.push({type:`code_execution`});break;case`google.url_context`:i.push({type:`url_context`});break;case`google.file_search`:i.push({type:`file_search`,...t.fileSearchStoreNames==null?{}:{file_search_store_names:t.fileSearchStoreNames},...t.topK==null?{}:{top_k:t.topK},...t.metadataFilter==null?{}:{metadata_filter:t.metadataFilter}});break;case`google.google_maps`:i.push({type:`google_maps`,...t.latitude==null?{}:{latitude:t.latitude},...t.longitude==null?{}:{longitude:t.longitude},...t.enableWidget==null?{}:{enable_widget:t.enableWidget}});break;case`google.computer_use`:i.push({type:`computer_use`,environment:t.environment??`browser`,...t.excludedPredefinedFunctions==null?{}:{excludedPredefinedFunctions:t.excludedPredefinedFunctions}});break;case`google.mcp_server`:i.push({type:`mcp_server`,...t.name==null?{}:{name:t.name},...t.url==null?{}:{url:t.url},...t.headers==null?{}:{headers:t.headers},...t.allowedTools==null?{}:{allowed_tools:t.allowedTools}});break;case`google.retrieval`:{let e=t.vertexAiSearchConfig??void 0;i.push({type:`retrieval`,...t.retrievalTypes==null?{retrieval_types:[`vertex_ai_search`]}:{retrieval_types:t.retrievalTypes},...e==null?{}:{vertex_ai_search_config:e}});break}default:n.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`provider-defined tool ${e.id} is not supported by google.interactions; tool dropped.`});break}continue}n.push({type:`unsupported`,feature:`tool of type ${e.type}`,details:`Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped.`})}let a=i.some(e=>e.type===`function`),o;if(t!=null&&a)switch(t.type){case`auto`:o=`auto`;break;case`required`:o=`any`;break;case`none`:o=`none`;break;case`tool`:o={allowed_tools:{mode:`validated`,tools:[t.toolName]}};break}return{tools:i.length>0?i:void 0,toolChoice:o,toolWarnings:n}}var Wt=3,Gt=500;function Kt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,maxRetries:a=Wt,retryDelayMs:o=Gt}){if(t.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let s={...n,accept:`text/event-stream`},c,l=!1,u=0,d=!1,f,p=new AbortController,m=()=>p.abort();i!=null&&(i.aborted?p.abort():i.addEventListener(`abort`,m,{once:!0}));let h=p.signal;function g(){let n=`${e}/interactions/${encodeURIComponent(t)}`,r=new URLSearchParams({stream:`true`});return c!=null&&r.set(`last_event_id`,c),`${n}?${r.toString()}`}async function _(){let{value:e}=await z({url:g(),headers:s,failedResponseHandler:V,successfulResponseHandler:L(At),abortSignal:h,fetch:r});return e.getReader()}return new ReadableStream({async start(s){try{for(;!l&&!h.aborted;){if(f==null)try{f=await _(),d=!1}catch(e){if(R(e)||h.aborted){s.error(e);return}if(u++,u>=a){s.error(e);return}await k(o*u,{abortSignal:h});continue}try{let{done:e,value:t}=await f.read();if(e){if(f=void 0,l)break;if(d)u=0;else{if(u++,u>=a){s.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await k(o*u,{abortSignal:h})}continue}if(d=!0,t.success){let e=t.value;typeof e.event_id==`string`&&e.event_id.length>0&&(c=e.event_id),(e.event_type===`interaction.completed`||e.event_type===`error`)&&(l=!0)}s.enqueue(t)}catch(e){if(R(e)||h.aborted){s.error(e);return}if(f=void 0,u++,u>=a){s.error(e);return}await k(o*u,{abortSignal:h})}}s.close()}catch(e){s.error(e)}finally{i?.removeEventListener(`abort`,m),f?.cancel().catch(()=>{}),f=void 0,h.aborted&&!l&&await Lt({baseURL:e,interactionId:t,headers:n,fetch:r})}},cancel(){p.abort(),f?.cancel().catch(()=>{}),f=void 0}})}function qt({response:e,warnings:t,generateId:n,includeRawChunks:r,headerServiceTier:i}){return new ReadableStream({start(a){a.enqueue({type:`stream-start`,warnings:t});let o=typeof e.id==`string`&&e.id.length>0?e.id:void 0,s,c=e.created;if(typeof c==`string`){let e=new Date(c);Number.isNaN(e.getTime())||(s=e)}a.enqueue({type:`response-metadata`,...o==null?{}:{id:o},modelId:e.model??void 0,...s?{timestamp:s}:{}}),r&&a.enqueue({type:`raw`,rawValue:e});let{content:l,hasFunctionCall:u}=X({steps:e.steps??null,generateId:n,interactionId:o}),d=0,f=()=>`${o??`agent`}:${d++}`;for(let e of l)switch(e.type){case`text`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`text-start`,id:t}),e.text.length>0&&a.enqueue({type:`text-delta`,id:t,delta:e.text}),a.enqueue({type:`text-end`,id:t,...n?{providerMetadata:n}:{}});break}case`reasoning`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`reasoning-start`,id:t}),e.text.length>0&&a.enqueue({type:`reasoning-delta`,id:t,delta:e.text}),a.enqueue({type:`reasoning-end`,id:t,...n?{providerMetadata:n}:{}});break}case`tool-call`:{let t=e.providerMetadata;a.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{}}),a.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.input}),a.enqueue({type:`tool-input-end`,id:e.toolCallId}),a.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...t?{providerMetadata:t}:{}});break}case`tool-result`:a.enqueue({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result});break;case`source`:case`file`:a.enqueue(e);break;default:break}let p=e.service_tier??i,m={unified:K({status:e.status,hasFunctionCall:u}),raw:e.status},h={google:{...o==null?{}:{interactionId:o},...p==null?{}:{serviceTier:p}}};a.enqueue({type:`finish`,finishReason:m,usage:W(e.usage),providerMetadata:h}),a.close()}})}var Jt=class e{constructor(e,t){this.specificationVersion=`v4`,typeof e==`string`?(this.modelId=e,this.agent=void 0):`managedAgent`in e?(this.modelId=e.managedAgent,this.agent=e.managedAgent):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[O](e){return{...T({modelId:e.modelId,config:e.config}),agent:e.agent}}static[E](t){return new e(t.agent==null?t.modelId:{agent:t.agent},t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){let t=[],n=await _({provider:`google`,providerOptions:e.providerOptions,schema:jt}),r=this.agent!=null,i=e.tools!=null&&e.tools.length>0,a,o;if(i&&r)t.push({type:`other`,message:`google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body.`});else if(i){let n=Ut({tools:e.tools,toolChoice:e.toolChoice});a=n.tools,o=n.toolChoice,t.push(...n.toolWarnings)}let s=[];if(e.responseFormat?.type===`json`)if(r)t.push({type:`other`,message:`google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored.`});else{let t={type:`text`,mime_type:`application/json`,...e.responseFormat.schema==null?{}:{schema:e.responseFormat.schema}};s.push(t)}if(n?.responseFormat!=null)for(let e of n.responseFormat)e.type===`text`?s.push(Q({type:`text`,mime_type:e.mimeType??void 0,schema:e.schema??void 0})):e.type===`image`?s.push(Q({type:`image`,mime_type:e.mimeType??void 0,aspect_ratio:e.aspectRatio??void 0,image_size:e.imageSize??void 0})):e.type===`audio`&&s.push(Q({type:`audio`,mime_type:e.mimeType??void 0}));let{input:c,systemInstruction:l,warnings:u}=ht({prompt:e.prompt,previousInteractionId:n?.previousInteractionId??void 0,store:n?.store??void 0,mediaResolution:n?.mediaResolution??void 0});t.push(...u);let d=l,f=n?.systemInstruction??void 0;d!=null&&f!=null?t.push({type:`other`,message:`google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message.`}):d==null&&f!=null&&(d=f);let p;if(r){let r=[];e.temperature!=null&&r.push(`temperature`),e.topP!=null&&r.push(`topP`),e.seed!=null&&r.push(`seed`),e.stopSequences!=null&&e.stopSequences.length>0&&r.push(`stopSequences`),e.maxOutputTokens!=null&&r.push(`maxOutputTokens`),n?.thinkingLevel!=null&&r.push(`thinkingLevel`),n?.thinkingSummaries!=null&&r.push(`thinkingSummaries`),n?.imageConfig!=null&&r.push(`imageConfig`),r.length>0&&t.push({type:`other`,message:`google.interactions: ${r.join(`, `)} ${r.length===1?`is`:`are`} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),p=void 0}else if(p=Q({temperature:e.temperature??void 0,top_p:e.topP??void 0,seed:e.seed??void 0,stop_sequences:e.stopSequences!=null&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:e.maxOutputTokens??void 0,thinking_level:n?.thinkingLevel??void 0,thinking_summaries:n?.thinkingSummaries??void 0,tool_choice:o}),n?.imageConfig!=null){let e=s.some(e=>e.type===`image`);t.push({type:`other`,message:e?`google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.`:`google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.`}),e||s.push({type:`image`,mime_type:`image/png`,...n.imageConfig.aspectRatio==null?{}:{aspect_ratio:n.imageConfig.aspectRatio},...n.imageConfig.imageSize==null?{}:{image_size:n.imageConfig.imageSize}})}let m;if(r&&n?.agentConfig!=null){let e=n.agentConfig;e.type===`deep-research`?m=Q({type:`deep-research`,thinking_summaries:e.thinkingSummaries??void 0,visualization:e.visualization??void 0,collaborative_planning:e.collaborativePlanning??void 0}):e.type===`dynamic`&&(m={type:`dynamic`})}let h;if(n?.environment!=null)if(!r)t.push({type:`other`,message:`google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body.`});else if(typeof n.environment==`string`)h=n.environment;else{let e=n.environment,t=e.sources?.map(e=>e.type===`inline`?{type:`inline`,content:e.content,target:e.target}:Q({type:e.type,source:e.source,target:e.target??void 0})),r;e.network===`disabled`?r=`disabled`:e.network!=null&&(r={allowlist:e.network.allowlist.map(e=>Q({domain:e.domain,transform:e.transform??void 0}))}),h=Q({type:`remote`,sources:t!=null&&t.length>0?t:void 0,network:r})}return{args:Q({...r?{agent:this.agent}:{model:this.modelId},input:c,system_instruction:d,tools:a,response_format:s.length>0?s:void 0,response_modalities:n?.responseModalities==null?void 0:n.responseModalities,previous_interaction_id:n?.previousInteractionId??void 0,service_tier:n?.serviceTier??void 0,store:n?.store??void 0,generation_config:p!=null&&Object.keys(p).length>0?p:void 0,agent_config:m,environment:h,background:n?.background??void 0}),warnings:t,isAgent:r,isBackground:n?.background===!0,pollingTimeoutMs:n?.pollingTimeoutMs??void 0}}async doGenerate(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=I(Yt,this.config.headers?await B(this.config.headers):void 0,e.headers),{responseHeaders:s,value:c,rawValue:l}=await x({url:a,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:M(J),abortSignal:e.abortSignal,fetch:this.config.fetch});if(r&&!Z(c.status)){let t=await Ht({baseURL:this.config.baseURL,interactionId:c.id,headers:o,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:i});c=t.response,l=t.rawResponse,s=t.responseHeaders??s}let u=typeof c.id==`string`&&c.id.length>0?c.id:void 0,{content:d,hasFunctionCall:f}=X({steps:c.steps??null,generateId:this.config.generateId??A,interactionId:u}),p={unified:K({status:c.status,hasFunctionCall:f}),raw:c.status},m=c.service_tier??s?.[`x-gemini-service-tier`]??void 0,h={google:{...u==null?{}:{interactionId:u},...m==null?{}:{serviceTier:m}}},g;if(typeof c.created==`string`){let e=new Date(c.created);Number.isNaN(e.getTime())||(g=e)}return{content:d,finishReason:p,usage:W(c.usage),warnings:n,providerMetadata:h,request:{body:t},response:{headers:s,body:l,...u==null?{}:{id:u},...g?{timestamp:g}:{},modelId:c.model??void 0}}}async doStream(e){let{args:t,warnings:n,isBackground:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=I(Yt,this.config.headers?await B(this.config.headers):void 0,e.headers);if(r)return this.doStreamBackground({args:t,warnings:n,url:a,mergedHeaders:o,options:e,pollingTimeoutMs:i});let s={...t,stream:!0},{responseHeaders:c,value:l}=await x({url:a,headers:o,body:s,failedResponseHandler:V,successfulResponseHandler:L(At),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c?.[`x-gemini-service-tier`],d=mt({warnings:n,generateId:this.config.generateId??A,includeRawChunks:e.includeRawChunks,serviceTier:u});return{stream:l.pipeThrough(d),request:{body:s},response:{headers:c}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:r,options:i,pollingTimeoutMs:a}){let{responseHeaders:o,value:s}=await x({url:n,headers:r,body:e,failedResponseHandler:V,successfulResponseHandler:M(J),abortSignal:i.abortSignal,fetch:this.config.fetch}),c=s.id;if(c==null||c.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let l=o?.[`x-gemini-service-tier`];if(Z(s.status))return{stream:qt({response:s,warnings:t,generateId:this.config.generateId??A,includeRawChunks:i.includeRawChunks,headerServiceTier:l}),request:{body:e},response:{headers:o}};let u=Kt({baseURL:this.config.baseURL,interactionId:c,headers:r,fetch:this.config.fetch,abortSignal:i.abortSignal}),d=mt({warnings:t,generateId:this.config.generateId??A,includeRawChunks:i.includeRawChunks,serviceTier:l});return{stream:u.pipeThrough(d),request:{body:e},response:{headers:o}}}},Yt={"Api-Revision":`2026-05-20`};function Q(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function $(e={}){let t=v(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>ne({"x-goog-api-key":p({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${re}`),i=i=>new De(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??A,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),a=i=>new oe(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new Xe(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new $e({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new rt(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??A}),l=i=>new Jt(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??A,fetch:e.fetch}),u=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return u.specificationVersion=`v4`,u.languageModel=i,u.chat=i,u.generativeAI=i,u.embedding=a,u.embeddingModel=a,u.textEmbedding=a,u.textEmbeddingModel=a,u.image=o,u.imageModel=o,u.video=c,u.videoModel=c,u.files=s,u.interactions=l,u.tools=Je,u}var Xt=$();export{re as VERSION,$ as createGoogle,$ as createGoogleGenerativeAI,Xt as google};
|
|
10
|
+
${n.text}`};t[t.length-1]=r;continue}t.push(n)}return t}var Y=()=>s({modality:o().nullish(),tokens:d().nullish()}).loose(),jt=()=>s({total_input_tokens:d().nullish(),total_output_tokens:d().nullish(),total_thought_tokens:d().nullish(),total_cached_tokens:d().nullish(),total_tool_use_tokens:d().nullish(),total_tokens:d().nullish(),input_tokens_by_modality:i(Y()).nullish(),output_tokens_by_modality:i(Y()).nullish(),cached_tokens_by_modality:i(Y()).nullish(),tool_use_tokens_by_modality:i(Y()).nullish(),grounding_tool_count:i(s({type:o().nullish(),count:d().nullish()}).loose()).nullish()}).loose(),Mt=()=>f([`in_progress`,`requires_action`,`completed`,`failed`,`cancelled`,`incomplete`]),Nt=()=>c([s({type:u(`url_citation`),url:o().nullish(),title:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:u(`file_citation`),file_name:o().nullish(),document_uri:o().nullish(),url:o().nullish(),page_number:d().nullish(),media_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish(),custom_metadata:a(o(),l()).nullish()}).loose(),s({type:u(`place_citation`),name:o().nullish(),url:o().nullish(),place_id:o().nullish(),start_index:d().nullish(),end_index:d().nullish()}).loose(),s({type:o()}).loose()]),Pt=()=>s({type:o(),text:o().nullish(),data:o().nullish(),mime_type:o().nullish()}).loose(),Ft=()=>c([s({type:u(`text`),text:o(),annotations:i(Nt()).nullish()}).loose(),s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),s({type:o()}).loose()]),It=[`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`],Lt=[`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`],Rt=()=>c([s({type:u(`user_input`),content:i(Ft()).nullish()}).loose(),s({type:u(`model_output`),content:i(Ft()).nullish()}).loose(),s({type:u(`function_call`),id:o(),name:o(),arguments:a(o(),l()).nullish(),signature:o().nullish()}).loose(),s({type:u(`thought`),signature:o().nullish(),summary:i(Pt()).nullish()}).loose(),s({type:f(It),id:o(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f(Lt),call_id:o(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]),X=P(()=>O(s({id:o().nullish(),created:o().nullish(),updated:o().nullish(),status:Mt(),model:o().nullish(),agent:o().nullish(),steps:i(Rt()).nullish(),usage:jt().nullish(),service_tier:o().nullish(),previous_interaction_id:o().nullish(),response_modalities:i(o()).nullish()}).loose())),zt=P(()=>O((()=>{let e=Mt(),t=Nt(),n=Pt(),p=s({event_type:u(`interaction.created`),event_id:o().nullish(),interaction:s({id:o().nullish(),created:o().nullish(),model:o().nullish(),agent:o().nullish(),status:e.nullish()}).loose()}).loose(),m=s({event_type:u(`step.start`),event_id:o().nullish(),index:d(),step:Rt()}).loose(),h=s({type:u(`text`),text:o()}).loose(),g=s({type:u(`thought_summary`),content:n.nullish()}).loose(),_=s({type:u(`thought_signature`),signature:o().nullish()}).loose(),v=s({type:u(`arguments_delta`),arguments:o().nullish(),id:o().nullish(),signature:o().nullish()}).loose(),y=s({type:f([`text_annotation_delta`,`text_annotation`]),annotations:i(t).nullish()}).loose(),b=c([h,s({type:u(`image`),data:o().nullish(),mime_type:o().nullish(),resolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),uri:o().nullish()}).loose(),g,_,v,y,s({type:f(It),id:o().nullish(),arguments:a(o(),l()).nullish(),name:o().nullish(),server_name:o().nullish(),search_type:o().nullish(),signature:o().nullish()}).loose(),s({type:f(Lt),call_id:o().nullish(),result:l().nullish(),is_error:r().nullish(),name:o().nullish(),server_name:o().nullish(),signature:o().nullish()}).loose(),s({type:o()}).loose()]);return c([p,m,s({event_type:u(`step.delta`),event_id:o().nullish(),index:d(),delta:b}).loose(),s({event_type:u(`step.stop`),event_id:o().nullish(),index:d()}).loose(),s({event_type:u(`interaction.status_update`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.in_progress`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.requires_action`),event_id:o().nullish(),interaction_id:o().nullish(),status:e.nullish()}).loose(),s({event_type:u(`interaction.completed`),event_id:o().nullish(),interaction:s({id:o().nullish(),status:e.nullish(),usage:jt().nullish(),service_tier:o().nullish()}).loose()}).loose(),s({event_type:u(`error`),event_id:o().nullish(),error:s({code:o().nullish(),message:o().nullish()}).loose().nullish()}).loose(),s({event_type:o()}).loose()])})())),Bt=P(()=>O(s({previousInteractionId:o().nullish(),store:r().nullish(),agent:o().nullish(),agentConfig:c([s({type:u(`dynamic`)}).loose(),s({type:u(`deep-research`),thinkingSummaries:f([`auto`,`none`]).nullish(),visualization:f([`off`,`auto`]).nullish(),collaborativePlanning:r().nullish()})]).nullish(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).nullish(),thinkingSummaries:f([`auto`,`none`]).nullish(),responseFormat:i(c([s({type:u(`text`),mimeType:o().nullish(),schema:l().nullish()}).loose(),s({type:u(`image`),mimeType:o().nullish(),aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).nullish(),imageSize:f([`1K`,`2K`,`4K`,`512`]).nullish()}).loose(),s({type:u(`audio`),mimeType:o().nullish()}).loose()])).nullish(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).nullish(),imageSize:f([`1K`,`2K`,`4K`,`512`]).nullish()}).nullish(),mediaResolution:f([`low`,`medium`,`high`,`ultra_high`]).nullish(),responseModalities:i(f([`text`,`image`,`audio`,`video`,`document`])).nullish(),serviceTier:f([`flex`,`standard`,`priority`]).nullish(),systemInstruction:o().nullish(),signature:o().nullish(),interactionId:o().nullish(),pollingTimeoutMs:d().int().positive().nullish(),background:r().nullish(),environment:c([o(),s({type:u(`remote`),sources:i(c([s({type:u(`gcs`),source:o(),target:o().nullish()}),s({type:u(`repository`),source:o(),target:o().nullish()}),s({type:u(`inline`),content:o(),target:o()})])).nullish(),network:c([u(`disabled`),s({allowlist:i(s({domain:o(),transform:i(a(o(),o())).nullish()}))})]).nullish()})]).nullish()})));function Z({signature:e,interactionId:t}){let n={};return e!=null&&(n.signature=e),t!=null&&(n.interactionId=t),Object.keys(n).length>0?{providerMetadata:{google:n}}:{}}var Vt=new Set([`google_search_call`,`code_execution_call`,`url_context_call`,`file_search_call`,`google_maps_call`,`mcp_server_tool_call`]),Ht=new Set([`google_search_result`,`code_execution_result`,`url_context_result`,`file_search_result`,`google_maps_result`,`mcp_server_tool_result`]);function Ut(e){return e.replace(/_call$/,``)}function Wt(e){return e.replace(/_result$/,``)}function Gt({steps:e,generateId:t,interactionId:n}){let r=[],i=!1;if(e==null)return{content:r,hasFunctionCall:i};for(let a of e){if(typeof a!=`object`||!a)continue;let e=a.type;if(typeof e==`string`)switch(e){case`user_input`:break;case`model_output`:{let e=a.content??[];for(let i of e){if(typeof i!=`object`||!i)continue;let e=i.type;if(e===`text`){let e=i.text??``,a=i.annotations;r.push({type:`text`,text:e,...Z({interactionId:n})});let o=q({annotations:a,generateId:t});for(let e of o)r.push(e)}else if(e===`image`){let e=i;e.data!=null&&e.data.length>0?r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`data`,data:e.data},...Z({interactionId:n})}):e.uri!=null&&e.uri.length>0&&r.push({type:`file`,mediaType:e.mime_type??`image/png`,data:{type:`url`,url:new URL(e.uri)},...Z({interactionId:n})})}}break}case`thought`:{let e=a,t=(Array.isArray(e.summary)?e.summary:[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
11
|
+
`);r.push({type:`reasoning`,text:t,...Z({signature:e.signature,interactionId:n})});break}case`function_call`:{i=!0;let e=a;r.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.arguments??{}),...Z({signature:e.signature,interactionId:n})});break}default:if(Vt.has(e)){let n=a,i=e===`mcp_server_tool_call`?n.name??`mcp_server_tool`:Ut(e),o=JSON.stringify(n.arguments??{});r.push({type:`tool-call`,toolCallId:n.id??t(),toolName:i,input:o,providerExecuted:!0})}else if(Ht.has(e)){let n=a,i=e===`mcp_server_tool_result`?n.name??`mcp_server_tool`:Wt(e);r.push({type:`tool-result`,toolCallId:n.call_id??t(),toolName:i,result:n.result??null});let o=vt({block:a,generateId:t});for(let e of o)r.push(e)}break}}return{content:r,hasFunctionCall:i}}var Kt=()=>globalThis.fetch;async function qt({baseURL:e,interactionId:t,headers:n,fetch:r=Kt()}){if(t==null||t.length===0)return;let i=`${e}/interactions/${encodeURIComponent(t)}/cancel`;try{let e=await r(i,{method:`POST`,headers:ie(I({"Content-Type":`application/json`},n),C()),body:`{}`});try{await e.text()}catch{}}catch{}}var Jt=new Set([`completed`,`failed`,`cancelled`,`incomplete`]);function Q(e){return e!=null&&Jt.has(e)}var Yt=1e3,Xt=1e4,Zt=1800*1e3;async function Qt({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,initialDelayMs:a=Yt,maxDelayMs:o=Xt,timeoutMs:s=Zt}){if(t==null||t.length===0)throw Error(`google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.`);let c=Date.now(),l=a,u=`${e}/interactions/${encodeURIComponent(t)}`,d=()=>qt({baseURL:e,interactionId:t,headers:n,fetch:r});try{for(;;){if(i?.aborted)throw await d(),new DOMException(`Polling was aborted`,`AbortError`);if(Date.now()-c>s)throw Error(`google.interactions: timed out polling interaction ${t} after ${s}ms.`);await A(l,{abortSignal:i});let{value:e,rawValue:a,responseHeaders:f}=await z({url:u,headers:n,failedResponseHandler:V,successfulResponseHandler:M(X),abortSignal:i,fetch:r});if(Q(e.status))return{response:e,rawResponse:a,responseHeaders:f};l=Math.min(l*2,o)}}catch(e){throw R(e)&&await d(),e}}function $t({tools:e,toolChoice:t}){let n=[],r=e?.length?e:void 0;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let e of r){if(e.type===`function`){i.push({type:`function`,name:e.name,description:e.description??``,parameters:e.inputSchema});continue}if(e.type===`provider`){let t=e.args??{};switch(e.id){case`google.google_search`:{let e=t.searchTypes,n;if(typeof e==`object`&&e){let t=[];e.webSearch!=null&&t.push(`web_search`),e.imageSearch!=null&&t.push(`image_search`),t.length>0&&(n=t)}i.push({type:`google_search`,...n==null?{}:{search_types:n}});break}case`google.code_execution`:i.push({type:`code_execution`});break;case`google.url_context`:i.push({type:`url_context`});break;case`google.file_search`:i.push({type:`file_search`,...t.fileSearchStoreNames==null?{}:{file_search_store_names:t.fileSearchStoreNames},...t.topK==null?{}:{top_k:t.topK},...t.metadataFilter==null?{}:{metadata_filter:t.metadataFilter}});break;case`google.google_maps`:i.push({type:`google_maps`,...t.latitude==null?{}:{latitude:t.latitude},...t.longitude==null?{}:{longitude:t.longitude},...t.enableWidget==null?{}:{enable_widget:t.enableWidget}});break;case`google.computer_use`:i.push({type:`computer_use`,environment:t.environment??`browser`,...t.excludedPredefinedFunctions==null?{}:{excludedPredefinedFunctions:t.excludedPredefinedFunctions}});break;case`google.mcp_server`:i.push({type:`mcp_server`,...t.name==null?{}:{name:t.name},...t.url==null?{}:{url:t.url},...t.headers==null?{}:{headers:t.headers},...t.allowedTools==null?{}:{allowed_tools:t.allowedTools}});break;case`google.retrieval`:{let e=t.vertexAiSearchConfig??void 0;i.push({type:`retrieval`,...t.retrievalTypes==null?{retrieval_types:[`vertex_ai_search`]}:{retrieval_types:t.retrievalTypes},...e==null?{}:{vertex_ai_search_config:e}});break}default:n.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`provider-defined tool ${e.id} is not supported by google.interactions; tool dropped.`});break}continue}n.push({type:`unsupported`,feature:`tool of type ${e.type}`,details:`Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped.`})}let a=i.some(e=>e.type===`function`),o;if(t!=null&&a)switch(t.type){case`auto`:o=`auto`;break;case`required`:o=`any`;break;case`none`:o=`none`;break;case`tool`:o={allowed_tools:{mode:`validated`,tools:[t.toolName]}};break}return{tools:i.length>0?i:void 0,toolChoice:o,toolWarnings:n}}var en=3,tn=500;function nn({baseURL:e,interactionId:t,headers:n,fetch:r,abortSignal:i,maxRetries:a=en,retryDelayMs:o=tn}){if(t.length===0)throw Error(`google.interactions: cannot stream a background interaction without an id.`);let s={...n,accept:`text/event-stream`},c,l=!1,u=0,d=!1,f,p=new AbortController,m=()=>p.abort();i!=null&&(i.aborted?p.abort():i.addEventListener(`abort`,m,{once:!0}));let h=p.signal;function g(){let n=`${e}/interactions/${encodeURIComponent(t)}`,r=new URLSearchParams({stream:`true`});return c!=null&&r.set(`last_event_id`,c),`${n}?${r.toString()}`}async function _(){let{value:e}=await z({url:g(),headers:s,failedResponseHandler:V,successfulResponseHandler:L(zt),abortSignal:h,fetch:r});return e.getReader()}return new ReadableStream({async start(s){try{for(;!l&&!h.aborted;){if(f==null)try{f=await _(),d=!1}catch(e){if(R(e)||h.aborted){s.error(e);return}if(u++,u>=a){s.error(e);return}await A(o*u,{abortSignal:h});continue}try{let{done:e,value:t}=await f.read();if(e){if(f=void 0,l)break;if(d)u=0;else{if(u++,u>=a){s.error(Error(`google.interactions: SSE stream closed without producing any events.`));return}await A(o*u,{abortSignal:h})}continue}if(d=!0,t.success){let e=t.value;typeof e.event_id==`string`&&e.event_id.length>0&&(c=e.event_id),(e.event_type===`interaction.completed`||e.event_type===`error`)&&(l=!0)}s.enqueue(t)}catch(e){if(R(e)||h.aborted){s.error(e);return}if(f=void 0,u++,u>=a){s.error(e);return}await A(o*u,{abortSignal:h})}}s.close()}catch(e){s.error(e)}finally{i?.removeEventListener(`abort`,m),f?.cancel().catch(()=>{}),f=void 0,h.aborted&&!l&&await qt({baseURL:e,interactionId:t,headers:n,fetch:r})}},cancel(){p.abort(),f?.cancel().catch(()=>{}),f=void 0}})}function rn({response:e,warnings:t,generateId:n,includeRawChunks:r,headerServiceTier:i}){return new ReadableStream({start(a){a.enqueue({type:`stream-start`,warnings:t});let o=typeof e.id==`string`&&e.id.length>0?e.id:void 0,s,c=e.created;if(typeof c==`string`){let e=new Date(c);Number.isNaN(e.getTime())||(s=e)}a.enqueue({type:`response-metadata`,...o==null?{}:{id:o},modelId:e.model??void 0,...s?{timestamp:s}:{}}),r&&a.enqueue({type:`raw`,rawValue:e});let{content:l,hasFunctionCall:u}=Gt({steps:e.steps??null,generateId:n,interactionId:o}),d=0,f=()=>`${o??`agent`}:${d++}`;for(let e of l)switch(e.type){case`text`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`text-start`,id:t}),e.text.length>0&&a.enqueue({type:`text-delta`,id:t,delta:e.text}),a.enqueue({type:`text-end`,id:t,...n?{providerMetadata:n}:{}});break}case`reasoning`:{let t=f(),n=e.providerMetadata;a.enqueue({type:`reasoning-start`,id:t}),e.text.length>0&&a.enqueue({type:`reasoning-delta`,id:t,delta:e.text}),a.enqueue({type:`reasoning-end`,id:t,...n?{providerMetadata:n}:{}});break}case`tool-call`:{let t=e.providerMetadata;a.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{}}),a.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.input}),a.enqueue({type:`tool-input-end`,id:e.toolCallId}),a.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...t?{providerMetadata:t}:{}});break}case`tool-result`:a.enqueue({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result});break;case`source`:case`file`:a.enqueue(e);break;default:break}let p=e.service_tier??i,m={unified:J({status:e.status,hasFunctionCall:u}),raw:e.status},h={google:{...o==null?{}:{interactionId:o},...p==null?{}:{serviceTier:p}}};a.enqueue({type:`finish`,finishReason:m,usage:K(e.usage),providerMetadata:h}),a.close()}})}var an=class e{constructor(e,t){this.specificationVersion=`v4`,typeof e==`string`?(this.modelId=e,this.agent=void 0):`managedAgent`in e?(this.modelId=e.managedAgent,this.agent=e.managedAgent):(this.modelId=e.agent,this.agent=e.agent),this.config=t}static[k](e){return{...E({modelId:e.modelId,config:e.config}),agent:e.agent}}static[D](t){return new e(t.agent==null?t.modelId:{agent:t.agent},t.config)}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(e){let t=[],n=await v({provider:`google`,providerOptions:e.providerOptions,schema:Bt}),r=this.agent!=null,i=e.tools!=null&&e.tools.length>0,a,o;if(i&&r)t.push({type:`other`,message:`google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body.`});else if(i){let n=$t({tools:e.tools,toolChoice:e.toolChoice});a=n.tools,o=n.toolChoice,t.push(...n.toolWarnings)}let s=[];if(e.responseFormat?.type===`json`)if(r)t.push({type:`other`,message:`google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored.`});else{let t={type:`text`,mime_type:`application/json`,...e.responseFormat.schema==null?{}:{schema:e.responseFormat.schema}};s.push(t)}if(n?.responseFormat!=null)for(let e of n.responseFormat)e.type===`text`?s.push($({type:`text`,mime_type:e.mimeType??void 0,schema:e.schema??void 0})):e.type===`image`?s.push($({type:`image`,mime_type:e.mimeType??void 0,aspect_ratio:e.aspectRatio??void 0,image_size:e.imageSize??void 0})):e.type===`audio`&&s.push($({type:`audio`,mime_type:e.mimeType??void 0}));let{input:c,systemInstruction:l,warnings:u}=wt({prompt:e.prompt,previousInteractionId:n?.previousInteractionId??void 0,store:n?.store??void 0,mediaResolution:n?.mediaResolution??void 0});t.push(...u);let d=l,f=n?.systemInstruction??void 0;d!=null&&f!=null?t.push({type:`other`,message:`google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message.`}):d==null&&f!=null&&(d=f);let p;if(r){let r=[];e.temperature!=null&&r.push(`temperature`),e.topP!=null&&r.push(`topP`),e.seed!=null&&r.push(`seed`),e.stopSequences!=null&&e.stopSequences.length>0&&r.push(`stopSequences`),e.maxOutputTokens!=null&&r.push(`maxOutputTokens`),n?.thinkingLevel!=null&&r.push(`thinkingLevel`),n?.thinkingSummaries!=null&&r.push(`thinkingSummaries`),n?.imageConfig!=null&&r.push(`imageConfig`),r.length>0&&t.push({type:`other`,message:`google.interactions: ${r.join(`, `)} ${r.length===1?`is`:`are`} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),p=void 0}else if(p=$({temperature:e.temperature??void 0,top_p:e.topP??void 0,seed:e.seed??void 0,stop_sequences:e.stopSequences!=null&&e.stopSequences.length>0?e.stopSequences:void 0,max_output_tokens:e.maxOutputTokens??void 0,thinking_level:n?.thinkingLevel??void 0,thinking_summaries:n?.thinkingSummaries??void 0,tool_choice:o}),n?.imageConfig!=null){let e=s.some(e=>e.type===`image`);t.push({type:`other`,message:e?`google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.`:`google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.`}),e||s.push({type:`image`,mime_type:`image/png`,...n.imageConfig.aspectRatio==null?{}:{aspect_ratio:n.imageConfig.aspectRatio},...n.imageConfig.imageSize==null?{}:{image_size:n.imageConfig.imageSize}})}let m;if(r&&n?.agentConfig!=null){let e=n.agentConfig;e.type===`deep-research`?m=$({type:`deep-research`,thinking_summaries:e.thinkingSummaries??void 0,visualization:e.visualization??void 0,collaborative_planning:e.collaborativePlanning??void 0}):e.type===`dynamic`&&(m={type:`dynamic`})}let h;if(n?.environment!=null)if(!r)t.push({type:`other`,message:`google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body.`});else if(typeof n.environment==`string`)h=n.environment;else{let e=n.environment,t=e.sources?.map(e=>e.type===`inline`?{type:`inline`,content:e.content,target:e.target}:$({type:e.type,source:e.source,target:e.target??void 0})),r;e.network===`disabled`?r=`disabled`:e.network!=null&&(r={allowlist:e.network.allowlist.map(e=>$({domain:e.domain,transform:e.transform??void 0}))}),h=$({type:`remote`,sources:t!=null&&t.length>0?t:void 0,network:r})}return{args:$({...r?{agent:this.agent}:{model:this.modelId},input:c,system_instruction:d,tools:a,response_format:s.length>0?s:void 0,response_modalities:n?.responseModalities==null?void 0:n.responseModalities,previous_interaction_id:n?.previousInteractionId??void 0,service_tier:n?.serviceTier??void 0,store:n?.store??void 0,generation_config:p!=null&&Object.keys(p).length>0?p:void 0,agent_config:m,environment:h,background:n?.background??void 0}),warnings:t,isAgent:r,isBackground:n?.background===!0,pollingTimeoutMs:n?.pollingTimeoutMs??void 0}}async doGenerate(e){let{args:t,warnings:n,isAgent:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=I(on,this.config.headers?await B(this.config.headers):void 0,e.headers),{responseHeaders:s,value:c,rawValue:l}=await S({url:a,headers:o,body:t,failedResponseHandler:V,successfulResponseHandler:M(X),abortSignal:e.abortSignal,fetch:this.config.fetch});if(r&&!Q(c.status)){let t=await Qt({baseURL:this.config.baseURL,interactionId:c.id,headers:o,fetch:this.config.fetch,abortSignal:e.abortSignal,timeoutMs:i});c=t.response,l=t.rawResponse,s=t.responseHeaders??s}let u=typeof c.id==`string`&&c.id.length>0?c.id:void 0,{content:d,hasFunctionCall:f}=Gt({steps:c.steps??null,generateId:this.config.generateId??j,interactionId:u}),p={unified:J({status:c.status,hasFunctionCall:f}),raw:c.status},m=c.service_tier??s?.[`x-gemini-service-tier`]??void 0,h={google:{...u==null?{}:{interactionId:u},...m==null?{}:{serviceTier:m}}},g;if(typeof c.created==`string`){let e=new Date(c.created);Number.isNaN(e.getTime())||(g=e)}return{content:d,finishReason:p,usage:K(c.usage),warnings:n,providerMetadata:h,request:{body:t},response:{headers:s,body:l,...u==null?{}:{id:u},...g?{timestamp:g}:{},modelId:c.model??void 0}}}async doStream(e){let{args:t,warnings:n,isBackground:r,pollingTimeoutMs:i}=await this.getArgs(e),a=`${this.config.baseURL}/interactions`,o=I(on,this.config.headers?await B(this.config.headers):void 0,e.headers);if(r)return this.doStreamBackground({args:t,warnings:n,url:a,mergedHeaders:o,options:e,pollingTimeoutMs:i});let s={...t,stream:!0},{responseHeaders:c,value:l}=await S({url:a,headers:o,body:s,failedResponseHandler:V,successfulResponseHandler:L(zt),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c?.[`x-gemini-service-tier`],d=Ct({warnings:n,generateId:this.config.generateId??j,includeRawChunks:e.includeRawChunks,serviceTier:u});return{stream:l.pipeThrough(d),request:{body:s},response:{headers:c}}}async doStreamBackground({args:e,warnings:t,url:n,mergedHeaders:r,options:i,pollingTimeoutMs:a}){let{responseHeaders:o,value:s}=await S({url:n,headers:r,body:e,failedResponseHandler:V,successfulResponseHandler:M(X),abortSignal:i.abortSignal,fetch:this.config.fetch}),c=s.id;if(c==null||c.length===0)throw Error(`google.interactions: background POST response did not include an interaction id; cannot stream the result.`);let l=o?.[`x-gemini-service-tier`];if(Q(s.status))return{stream:rn({response:s,warnings:t,generateId:this.config.generateId??j,includeRawChunks:i.includeRawChunks,headerServiceTier:l}),request:{body:e},response:{headers:o}};let u=nn({baseURL:this.config.baseURL,interactionId:c,headers:r,fetch:this.config.fetch,abortSignal:i.abortSignal}),d=Ct({warnings:t,generateId:this.config.generateId??j,includeRawChunks:i.includeRawChunks,serviceTier:l});return{stream:u.pipeThrough(d),request:{body:e},response:{headers:o}}}},on={"Api-Revision":`2026-05-20`};function $(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var sn=class{constructor(){this.turnCounter=0,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,this.turnClosed=!1,this.inputAudioRate=16e3}get responseId(){return`google-resp-${this.turnCounter}`}get itemId(){return`google-item-${this.turnCounter}`}beginTurnIfClosed(){this.turnClosed&&=(this.turnCounter++,this.hasAudio=!1,this.hasText=!1,this.hasTranscript=!1,!1)}parseServerEvent(e){let t=e;return t.setupComplete==null?t.toolCall==null?t.toolCallCancellation==null?t.serverContent==null?t.inputTranscription?.text==null?{type:`custom`,rawType:String(Object.keys(t)[0]),raw:e}:{type:`input-transcription-completed`,itemId:`google-input-${this.turnCounter}`,transcript:t.inputTranscription.text,raw:e}:this.parseServerContent(t.serverContent,e):{type:`custom`,rawType:`toolCallCancellation`,raw:e}:(this.beginTurnIfClosed(),(t.toolCall.functionCalls??[]).flatMap(t=>{let n=JSON.stringify(t.args??{});return[{type:`function-call-arguments-delta`,responseId:this.responseId,itemId:this.itemId,callId:t.id,delta:n,raw:e},{type:`function-call-arguments-done`,responseId:this.responseId,itemId:this.itemId,callId:t.id,name:t.name,arguments:n,raw:e}]})):{type:`session-created`,raw:e}}parseServerContent(e,t){let n=[];if(e.interrupted&&n.push({type:`speech-started`,raw:t}),e.modelTurn?.parts){this.beginTurnIfClosed();for(let r of e.modelTurn.parts)r.inlineData?.data&&(this.hasAudio=!0,n.push({type:`audio-delta`,responseId:this.responseId,itemId:this.itemId,delta:r.inlineData.data,raw:t})),r.text&&(this.hasText=!0,n.push({type:`text-delta`,responseId:this.responseId,itemId:this.itemId,delta:r.text,raw:t}))}return e.outputTranscription?.text&&(this.hasTranscript=!0,n.push({type:`audio-transcript-delta`,responseId:this.responseId,itemId:this.itemId,delta:e.outputTranscription.text,raw:t})),e.inputTranscription?.text&&n.push({type:`input-transcription-completed`,itemId:`google-input-${this.turnCounter}`,transcript:e.inputTranscription.text,raw:t}),e.turnComplete&&(this.hasAudio&&n.push({type:`audio-done`,responseId:this.responseId,itemId:this.itemId,raw:t}),this.hasText&&n.push({type:`text-done`,responseId:this.responseId,itemId:this.itemId,raw:t}),this.hasTranscript&&n.push({type:`audio-transcript-done`,responseId:this.responseId,itemId:this.itemId,raw:t}),n.push({type:`response-done`,responseId:this.responseId,status:`completed`,raw:t}),this.turnClosed=!0),n.length===0?{type:`custom`,rawType:`serverContent`,raw:t}:n.length===1?n[0]:n}serializeClientEvent(e,t){switch(e.type){case`session-update`:return e.config.inputAudioFormat?.rate!=null&&(this.inputAudioRate=e.config.inputAudioFormat.rate),{setup:ln(e.config,t)};case`input-audio-append`:return{realtimeInput:{audio:{data:e.audio,mimeType:`audio/pcm;rate=${this.inputAudioRate}`}}};case`input-audio-commit`:case`input-audio-clear`:case`response-create`:case`response-cancel`:case`conversation-item-truncate`:return null;case`conversation-item-create`:{let t=e.item;switch(t.type){case`text-message`:return{realtimeInput:{text:t.text}};case`function-call-output`:return cn(t);case`audio-message`:return null}break}}return null}};async function cn(e){let t=await _({text:e.output}),n=t.success?t.value:{};return{toolResponse:{functionResponses:[{id:e.callId,name:e.name,response:n}]}}}function ln(e,t){let n={model:U(t)},r={};return e?.outputModalities==null?r.responseModalities=[`AUDIO`]:r.responseModalities=e.outputModalities.map(e=>e.toUpperCase()),e?.voice!=null&&(r.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.voice}}}),n.generationConfig=r,e?.instructions!=null&&(n.systemInstruction={parts:[{text:e.instructions}]}),e?.tools!=null&&e.tools.length>0&&(n.tools=[{functionDeclarations:e.tools.map(e=>({name:e.name,description:e.description,parameters:H(e.parameters)}))}]),e?.inputAudioTranscription!=null&&(n.inputAudioTranscription={}),e?.outputAudioTranscription!=null&&(n.outputAudioTranscription={}),e?.providerOptions!=null&&Object.assign(n,e.providerOptions),n}var un=`google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained`;function dn(e){let t=new URL(e),n=t.pathname.split(`/`),r=n.at(-1);return(r===`v1beta`||r===`v1alpha`)&&(n.pop(),t.pathname=n.join(`/`)||`/`),t}function fn(e){let t=dn(e);return t.pathname=`${t.pathname.replace(/\/$/,``)}/v1alpha/auth_tokens`,t.toString()}function pn(e){let t=dn(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=`${t.pathname.replace(/\/$/,``)}/ws/${un}`,t.toString()}var mn=class{constructor(e,t){this.specificationVersion=`v4`,this.mapper=new sn,this.modelId=e,this.provider=t.provider,this.config=t}async doCreateClientSecret(e){let t=this.config.fetch??fetch,n=this.config.headers()[`x-goog-api-key`];if(!n)throw Error(`Google Generative AI API key is required for realtime token creation.`);let r=Date.now(),i=(e.expiresAfterSeconds??60)*1e3,a=new Date(r+i).toISOString(),o=new Date(r+i+1800*1e3).toISOString(),s=ln(e.sessionConfig,this.modelId),c=await t(`${fn(this.config.baseURL)}?key=${encodeURIComponent(n)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({uses:0,expireTime:o,newSessionExpireTime:a,bidiGenerateContentSetup:s})});if(!c.ok){let e=await c.text();throw Error(`Google realtime auth token request failed: ${c.status} ${e}`)}let l=await c.json();return{token:l.name,url:pn(this.config.baseURL),expiresAt:l.expireTime?Math.floor(new Date(l.expireTime).getTime()/1e3):void 0}}getWebSocketConfig(e){return{url:`${e.url}?access_token=${encodeURIComponent(e.token)}`}}parseServerEvent(e){return this.mapper.parseServerEvent(e)}serializeClientEvent(e){return this.mapper.serializeClientEvent(e,this.modelId)}buildSessionConfig(e){return ln(e,this.modelId)}};function hn(e={}){let t=y(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=e.name??`google.generative-ai`,r=()=>ie({"x-goog-api-key":p({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${ae}`),i=i=>new Oe(i,{provider:n,baseURL:t,headers:r,generateId:e.generateId??j,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),a=i=>new ce(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),o=(i,a={})=>new Ze(i,a,{provider:n,baseURL:t,headers:r,fetch:e.fetch}),s=()=>new et({provider:n,baseURL:t,headers:r,fetch:e.fetch}),c=i=>new it(i,{provider:n,baseURL:t,headers:r,fetch:e.fetch,generateId:e.generateId??j}),l=i=>new mn(i,{provider:`${n}.realtime`,baseURL:t,headers:r,fetch:e.fetch}),u=i=>new dt(i,{provider:`${n}.speech`,baseURL:t,headers:r,fetch:e.fetch}),d=Object.assign(e=>l(e),{getToken:async e=>{let t=await l(e.model).doCreateClientSecret({sessionConfig:e.sessionConfig,expiresAfterSeconds:e.expiresAfterSeconds});return{token:t.token,url:t.url,expiresAt:t.expiresAt}}}),f=i=>new an(i,{provider:`${n}.interactions`,baseURL:t,headers:r,generateId:e.generateId??j,fetch:e.fetch}),m=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return m.specificationVersion=`v4`,m.languageModel=i,m.chat=i,m.generativeAI=i,m.embedding=a,m.embeddingModel=a,m.textEmbedding=a,m.textEmbeddingModel=a,m.image=o,m.imageModel=o,m.video=c,m.videoModel=c,m.experimental_realtime=d,m.files=s,m.speech=u,m.speechModel=u,m.interactions=f,m.tools=Ye,m}var gn=hn();export{mn as Experimental_GoogleRealtimeModel,ae as VERSION,hn as createGoogle,hn as createGoogleGenerativeAI,gn as google};
|