@ai-sdk/google 3.0.67 → 3.0.68

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/dist/index.js CHANGED
@@ -27,10 +27,10 @@ __export(index_exports, {
27
27
  module.exports = __toCommonJS(index_exports);
28
28
 
29
29
  // src/google-provider.ts
30
- var import_provider_utils16 = require("@ai-sdk/provider-utils");
30
+ var import_provider_utils21 = require("@ai-sdk/provider-utils");
31
31
 
32
32
  // src/version.ts
33
- var VERSION = true ? "3.0.67" : "0.0.0-test";
33
+ var VERSION = true ? "3.0.68" : "0.0.0-test";
34
34
 
35
35
  // src/google-generative-ai-embedding-model.ts
36
36
  var import_provider = require("@ai-sdk/provider");
@@ -2995,55 +2995,2375 @@ var googleVideoModelOptionsSchema = (0, import_provider_utils15.lazySchema)(
2995
2995
  )
2996
2996
  );
2997
2997
 
2998
- // src/google-provider.ts
2999
- function createGoogleGenerativeAI(options = {}) {
3000
- var _a, _b;
3001
- const baseURL = (_a = (0, import_provider_utils16.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
3002
- const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
3003
- const getHeaders = () => (0, import_provider_utils16.withUserAgentSuffix)(
3004
- {
3005
- "x-goog-api-key": (0, import_provider_utils16.loadApiKey)({
3006
- apiKey: options.apiKey,
3007
- environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
3008
- description: "Google Generative AI"
3009
- }),
3010
- ...options.headers
2998
+ // src/interactions/google-interactions-language-model.ts
2999
+ var import_provider_utils20 = require("@ai-sdk/provider-utils");
3000
+
3001
+ // src/interactions/convert-google-interactions-usage.ts
3002
+ function convertGoogleInteractionsUsage(usage) {
3003
+ var _a, _b, _c, _d, _e, _f, _g, _h;
3004
+ if (usage == null) {
3005
+ return {
3006
+ inputTokens: {
3007
+ total: void 0,
3008
+ noCache: void 0,
3009
+ cacheRead: void 0,
3010
+ cacheWrite: void 0
3011
+ },
3012
+ outputTokens: {
3013
+ total: void 0,
3014
+ text: void 0,
3015
+ reasoning: void 0
3016
+ },
3017
+ raw: void 0
3018
+ };
3019
+ }
3020
+ const totalInput = (_a = usage.total_input_tokens) != null ? _a : 0;
3021
+ const totalOutput = (_b = usage.total_output_tokens) != null ? _b : 0;
3022
+ const totalThought = (_c = usage.total_thought_tokens) != null ? _c : 0;
3023
+ const totalCached = (_d = usage.total_cached_tokens) != null ? _d : 0;
3024
+ return {
3025
+ inputTokens: {
3026
+ total: (_e = usage.total_input_tokens) != null ? _e : void 0,
3027
+ noCache: usage.total_input_tokens == null ? void 0 : totalInput - totalCached,
3028
+ cacheRead: (_f = usage.total_cached_tokens) != null ? _f : void 0,
3029
+ cacheWrite: void 0
3011
3030
  },
3012
- `ai-sdk/google/${VERSION}`
3013
- );
3014
- const createChatModel = (modelId) => {
3015
- var _a2;
3016
- return new GoogleGenerativeAILanguageModel(modelId, {
3017
- provider: providerName,
3018
- baseURL,
3019
- headers: getHeaders,
3020
- generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils16.generateId,
3021
- supportedUrls: () => ({
3022
- "*": [
3023
- // Google Generative Language "files" endpoint
3024
- // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
3025
- new RegExp(`^${baseURL}/files/.*$`),
3026
- // YouTube URLs (public or unlisted videos)
3027
- new RegExp(
3028
- `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
3029
- ),
3030
- new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
3031
- ]
3032
- }),
3033
- fetch: options.fetch
3034
- });
3031
+ outputTokens: {
3032
+ total: usage.total_output_tokens == null && usage.total_thought_tokens == null ? void 0 : totalOutput + totalThought,
3033
+ text: (_g = usage.total_output_tokens) != null ? _g : void 0,
3034
+ reasoning: (_h = usage.total_thought_tokens) != null ? _h : void 0
3035
+ },
3036
+ raw: usage
3035
3037
  };
3036
- const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
3037
- provider: providerName,
3038
- baseURL,
3039
- headers: getHeaders,
3040
- fetch: options.fetch
3038
+ }
3039
+
3040
+ // src/interactions/extract-google-interactions-sources.ts
3041
+ var KNOWN_DOC_EXTENSIONS = {
3042
+ pdf: "application/pdf",
3043
+ txt: "text/plain",
3044
+ md: "text/markdown",
3045
+ markdown: "text/markdown",
3046
+ doc: "application/msword",
3047
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
3048
+ };
3049
+ function inferDocMediaType(uriOrName) {
3050
+ const lower = uriOrName.toLowerCase();
3051
+ for (const [ext, media] of Object.entries(KNOWN_DOC_EXTENSIONS)) {
3052
+ if (lower.endsWith(`.${ext}`)) return media;
3053
+ }
3054
+ return "application/octet-stream";
3055
+ }
3056
+ function basename(uriOrName) {
3057
+ const parts = uriOrName.split("/");
3058
+ const last = parts[parts.length - 1];
3059
+ return last && last.length > 0 ? last : void 0;
3060
+ }
3061
+ function annotationToSource({
3062
+ annotation,
3063
+ generateId: generateId3
3064
+ }) {
3065
+ var _a, _b, _c, _d, _e;
3066
+ switch (annotation.type) {
3067
+ case "url_citation": {
3068
+ const a = annotation;
3069
+ if (a.url == null || a.url.length === 0) return void 0;
3070
+ return {
3071
+ type: "source",
3072
+ sourceType: "url",
3073
+ id: generateId3(),
3074
+ url: a.url,
3075
+ ...a.title != null ? { title: a.title } : {}
3076
+ };
3077
+ }
3078
+ case "file_citation": {
3079
+ const a = annotation;
3080
+ const uri = (_b = (_a = a.document_uri) != null ? _a : a.source) != null ? _b : a.file_name;
3081
+ if (uri == null || uri.length === 0) return void 0;
3082
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
3083
+ return {
3084
+ type: "source",
3085
+ sourceType: "url",
3086
+ id: generateId3(),
3087
+ url: uri,
3088
+ ...a.file_name != null ? { title: a.file_name } : {}
3089
+ };
3090
+ }
3091
+ const filename = (_c = a.file_name) != null ? _c : basename(uri);
3092
+ const mediaType = inferDocMediaType(uri);
3093
+ return {
3094
+ type: "source",
3095
+ sourceType: "document",
3096
+ id: generateId3(),
3097
+ mediaType,
3098
+ title: (_e = (_d = a.file_name) != null ? _d : filename) != null ? _e : uri,
3099
+ ...filename != null ? { filename } : {}
3100
+ };
3101
+ }
3102
+ case "place_citation": {
3103
+ const a = annotation;
3104
+ if (a.url == null || a.url.length === 0) return void 0;
3105
+ return {
3106
+ type: "source",
3107
+ sourceType: "url",
3108
+ id: generateId3(),
3109
+ url: a.url,
3110
+ ...a.name != null ? { title: a.name } : {}
3111
+ };
3112
+ }
3113
+ default:
3114
+ return void 0;
3115
+ }
3116
+ }
3117
+ function builtinToolResultToSources({
3118
+ block,
3119
+ generateId: generateId3
3120
+ }) {
3121
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
3122
+ const sources = [];
3123
+ switch (block.type) {
3124
+ case "url_context_result": {
3125
+ const result = (_a = block.result) != null ? _a : [];
3126
+ for (const entry of result) {
3127
+ if ((entry == null ? void 0 : entry.url) == null || entry.url.length === 0) continue;
3128
+ if (entry.status != null && entry.status !== "success") continue;
3129
+ sources.push({
3130
+ type: "source",
3131
+ sourceType: "url",
3132
+ id: generateId3(),
3133
+ url: entry.url
3134
+ });
3135
+ }
3136
+ break;
3137
+ }
3138
+ case "google_search_result": {
3139
+ const result = (_b = block.result) != null ? _b : [];
3140
+ for (const entry of result) {
3141
+ const url = entry == null ? void 0 : entry.url;
3142
+ if (url == null || url.length === 0) continue;
3143
+ sources.push({
3144
+ type: "source",
3145
+ sourceType: "url",
3146
+ id: generateId3(),
3147
+ url,
3148
+ ...entry.title != null ? { title: entry.title } : {}
3149
+ });
3150
+ }
3151
+ break;
3152
+ }
3153
+ case "google_maps_result": {
3154
+ const result = (_c = block.result) != null ? _c : [];
3155
+ for (const entry of result) {
3156
+ for (const place of (_d = entry.places) != null ? _d : []) {
3157
+ if (place.url == null || place.url.length === 0) continue;
3158
+ sources.push({
3159
+ type: "source",
3160
+ sourceType: "url",
3161
+ id: generateId3(),
3162
+ url: place.url,
3163
+ ...place.name != null ? { title: place.name } : {}
3164
+ });
3165
+ }
3166
+ }
3167
+ break;
3168
+ }
3169
+ case "file_search_result": {
3170
+ const result = (_e = block.result) != null ? _e : [];
3171
+ for (const raw of result) {
3172
+ if (raw == null || typeof raw !== "object") continue;
3173
+ const entry = raw;
3174
+ const uri = (_g = (_f = entry.document_uri) != null ? _f : entry.source) != null ? _g : entry.file_name;
3175
+ if (uri == null || uri.length === 0) continue;
3176
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
3177
+ sources.push({
3178
+ type: "source",
3179
+ sourceType: "url",
3180
+ id: generateId3(),
3181
+ url: uri,
3182
+ ...entry.title != null ? { title: entry.title } : {}
3183
+ });
3184
+ continue;
3185
+ }
3186
+ const filename = (_h = entry.file_name) != null ? _h : basename(uri);
3187
+ const mediaType = inferDocMediaType(uri);
3188
+ sources.push({
3189
+ type: "source",
3190
+ sourceType: "document",
3191
+ id: generateId3(),
3192
+ mediaType,
3193
+ title: (_k = (_j = (_i = entry.title) != null ? _i : entry.file_name) != null ? _j : filename) != null ? _k : uri,
3194
+ ...filename != null ? { filename } : {}
3195
+ });
3196
+ }
3197
+ break;
3198
+ }
3199
+ default:
3200
+ break;
3201
+ }
3202
+ return sources;
3203
+ }
3204
+ function annotationsToSources({
3205
+ annotations,
3206
+ generateId: generateId3
3207
+ }) {
3208
+ var _a;
3209
+ if (annotations == null) return [];
3210
+ const seen = /* @__PURE__ */ new Set();
3211
+ const sources = [];
3212
+ for (const annotation of annotations) {
3213
+ const source = annotationToSource({ annotation, generateId: generateId3 });
3214
+ if (source == null) continue;
3215
+ const key = source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a = source.filename) != null ? _a : source.title}`;
3216
+ if (seen.has(key)) continue;
3217
+ seen.add(key);
3218
+ sources.push(source);
3219
+ }
3220
+ return sources;
3221
+ }
3222
+
3223
+ // src/interactions/map-google-interactions-finish-reason.ts
3224
+ function mapGoogleInteractionsFinishReason({
3225
+ status,
3226
+ hasFunctionCall
3227
+ }) {
3228
+ switch (status) {
3229
+ case "completed":
3230
+ return hasFunctionCall ? "tool-calls" : "stop";
3231
+ case "requires_action":
3232
+ return "tool-calls";
3233
+ case "failed":
3234
+ return "error";
3235
+ case "incomplete":
3236
+ return "length";
3237
+ case "cancelled":
3238
+ return "other";
3239
+ case "in_progress":
3240
+ default:
3241
+ return "other";
3242
+ }
3243
+ }
3244
+
3245
+ // src/interactions/build-google-interactions-stream-transform.ts
3246
+ var BUILTIN_TOOL_CALL_TYPES = /* @__PURE__ */ new Set([
3247
+ "google_search_call",
3248
+ "code_execution_call",
3249
+ "url_context_call",
3250
+ "file_search_call",
3251
+ "google_maps_call",
3252
+ "mcp_server_tool_call"
3253
+ ]);
3254
+ var BUILTIN_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([
3255
+ "google_search_result",
3256
+ "code_execution_result",
3257
+ "url_context_result",
3258
+ "file_search_result",
3259
+ "google_maps_result",
3260
+ "mcp_server_tool_result"
3261
+ ]);
3262
+ function builtinToolNameFromCallType(type) {
3263
+ return type.replace(/_call$/, "");
3264
+ }
3265
+ function builtinToolNameFromResultType(type) {
3266
+ return type.replace(/_result$/, "");
3267
+ }
3268
+ function buildGoogleInteractionsStreamTransform({
3269
+ warnings,
3270
+ generateId: generateId3,
3271
+ includeRawChunks,
3272
+ serviceTier: headerServiceTier
3273
+ }) {
3274
+ let interactionId;
3275
+ let usage;
3276
+ let serviceTier = headerServiceTier;
3277
+ let finishStatus;
3278
+ let hasFunctionCall = false;
3279
+ const openBlocks = /* @__PURE__ */ new Map();
3280
+ const emittedSourceKeys = /* @__PURE__ */ new Set();
3281
+ function sourceKey(source) {
3282
+ var _a;
3283
+ return source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a = source.filename) != null ? _a : source.title}`;
3284
+ }
3285
+ return new TransformStream({
3286
+ start(controller) {
3287
+ controller.enqueue({ type: "stream-start", warnings });
3288
+ },
3289
+ transform(chunk, controller) {
3290
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
3291
+ if (includeRawChunks) {
3292
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3293
+ }
3294
+ if (!chunk.success) {
3295
+ finishStatus = "failed";
3296
+ controller.enqueue({ type: "error", error: chunk.error });
3297
+ return;
3298
+ }
3299
+ const value = chunk.value;
3300
+ const eventType = value.event_type;
3301
+ switch (eventType) {
3302
+ case "interaction.start": {
3303
+ const event = value;
3304
+ const interaction = event.interaction;
3305
+ interactionId = (interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0 ? interaction.id : void 0;
3306
+ const created = interaction == null ? void 0 : interaction.created;
3307
+ let timestamp;
3308
+ if (typeof created === "string") {
3309
+ const parsed = new Date(created);
3310
+ if (!Number.isNaN(parsed.getTime())) {
3311
+ timestamp = parsed;
3312
+ }
3313
+ }
3314
+ controller.enqueue({
3315
+ type: "response-metadata",
3316
+ ...interactionId != null ? { id: interactionId } : {},
3317
+ modelId: interaction == null ? void 0 : interaction.model,
3318
+ ...timestamp ? { timestamp } : {}
3319
+ });
3320
+ break;
3321
+ }
3322
+ case "content.start": {
3323
+ const event = value;
3324
+ const block = event.content;
3325
+ const index = event.index;
3326
+ const blockId = `${interactionId != null ? interactionId : "interaction"}:${index}`;
3327
+ if ((block == null ? void 0 : block.type) === "text") {
3328
+ openBlocks.set(index, {
3329
+ kind: "text",
3330
+ id: blockId,
3331
+ emittedSourceKeys: /* @__PURE__ */ new Set()
3332
+ });
3333
+ controller.enqueue({ type: "text-start", id: blockId });
3334
+ const initialSources = annotationsToSources({
3335
+ annotations: block.annotations,
3336
+ generateId: generateId3
3337
+ });
3338
+ for (const source of initialSources) {
3339
+ const key = sourceKey(source);
3340
+ if (emittedSourceKeys.has(key)) continue;
3341
+ emittedSourceKeys.add(key);
3342
+ controller.enqueue(source);
3343
+ }
3344
+ } else if ((block == null ? void 0 : block.type) === "image") {
3345
+ const img = block;
3346
+ openBlocks.set(index, {
3347
+ kind: "image",
3348
+ id: blockId,
3349
+ ...img.data != null ? { data: img.data } : {},
3350
+ ...img.mime_type != null ? { mimeType: img.mime_type } : {},
3351
+ ...img.uri != null ? { uri: img.uri } : {}
3352
+ });
3353
+ } else if ((block == null ? void 0 : block.type) === "thought") {
3354
+ const signature = block.signature;
3355
+ openBlocks.set(index, {
3356
+ kind: "reasoning",
3357
+ id: blockId,
3358
+ ...signature != null ? { signature } : {}
3359
+ });
3360
+ controller.enqueue({ type: "reasoning-start", id: blockId });
3361
+ } else if ((block == null ? void 0 : block.type) === "function_call") {
3362
+ const fc = block;
3363
+ const toolCallId = (_a = fc.id) != null ? _a : blockId;
3364
+ hasFunctionCall = true;
3365
+ const state = {
3366
+ kind: "function_call",
3367
+ id: blockId,
3368
+ toolCallId,
3369
+ toolName: fc.name,
3370
+ arguments: (_b = fc.arguments) != null ? _b : {},
3371
+ ...fc.signature != null ? { signature: fc.signature } : {},
3372
+ startEmitted: false
3373
+ };
3374
+ openBlocks.set(index, state);
3375
+ if (state.toolName != null) {
3376
+ controller.enqueue({
3377
+ type: "tool-input-start",
3378
+ id: toolCallId,
3379
+ toolName: state.toolName
3380
+ });
3381
+ state.startEmitted = true;
3382
+ }
3383
+ } else if ((block == null ? void 0 : block.type) != null && BUILTIN_TOOL_CALL_TYPES.has(block.type)) {
3384
+ const toolName = block.type === "mcp_server_tool_call" ? (_c = block.name) != null ? _c : "mcp_server_tool" : builtinToolNameFromCallType(block.type);
3385
+ const toolCallId = (_d = block.id) != null ? _d : blockId;
3386
+ const state = {
3387
+ kind: "builtin_tool_call",
3388
+ id: blockId,
3389
+ blockType: block.type,
3390
+ toolCallId,
3391
+ toolName,
3392
+ arguments: (_e = block.arguments) != null ? _e : {},
3393
+ callEmitted: false
3394
+ };
3395
+ openBlocks.set(index, state);
3396
+ } else if ((block == null ? void 0 : block.type) != null && BUILTIN_TOOL_RESULT_TYPES.has(block.type)) {
3397
+ const toolName = block.type === "mcp_server_tool_result" ? (_f = block.name) != null ? _f : "mcp_server_tool" : builtinToolNameFromResultType(block.type);
3398
+ const callId = (_g = block.call_id) != null ? _g : blockId;
3399
+ const state = {
3400
+ kind: "builtin_tool_result",
3401
+ id: blockId,
3402
+ blockType: block.type,
3403
+ callId,
3404
+ toolName,
3405
+ result: (_h = block.result) != null ? _h : null,
3406
+ ...block.is_error != null ? { isError: block.is_error } : {},
3407
+ resultEmitted: false
3408
+ };
3409
+ openBlocks.set(index, state);
3410
+ } else {
3411
+ openBlocks.set(index, { kind: "unknown", id: blockId });
3412
+ }
3413
+ break;
3414
+ }
3415
+ case "content.delta": {
3416
+ const event = value;
3417
+ const open = openBlocks.get(event.index);
3418
+ if (open == null) break;
3419
+ const delta = event.delta;
3420
+ if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text") {
3421
+ const text = (_i = delta.text) != null ? _i : "";
3422
+ if (text.length > 0) {
3423
+ controller.enqueue({
3424
+ type: "text-delta",
3425
+ id: open.id,
3426
+ delta: text
3427
+ });
3428
+ }
3429
+ } else if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text_annotation") {
3430
+ const sources = annotationsToSources({
3431
+ annotations: delta.annotations,
3432
+ generateId: generateId3
3433
+ });
3434
+ for (const source of sources) {
3435
+ const key = sourceKey(source);
3436
+ if (emittedSourceKeys.has(key)) continue;
3437
+ emittedSourceKeys.add(key);
3438
+ open.emittedSourceKeys.add(key);
3439
+ controller.enqueue(source);
3440
+ }
3441
+ } else if (open.kind === "image" && (delta == null ? void 0 : delta.type) === "image") {
3442
+ if (delta.data != null) open.data = delta.data;
3443
+ if (delta.mime_type != null) open.mimeType = delta.mime_type;
3444
+ if (delta.uri != null) open.uri = delta.uri;
3445
+ } else if (open.kind === "reasoning") {
3446
+ if ((delta == null ? void 0 : delta.type) === "thought_summary") {
3447
+ const item = delta.content;
3448
+ if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") {
3449
+ controller.enqueue({
3450
+ type: "reasoning-delta",
3451
+ id: open.id,
3452
+ delta: item.text
3453
+ });
3454
+ }
3455
+ } else if ((delta == null ? void 0 : delta.type) === "thought_signature") {
3456
+ const signature = delta.signature;
3457
+ if (signature != null) {
3458
+ open.signature = signature;
3459
+ }
3460
+ }
3461
+ } else if (open.kind === "function_call" && (delta == null ? void 0 : delta.type) === "function_call") {
3462
+ if (delta.id != null) {
3463
+ open.toolCallId = delta.id;
3464
+ }
3465
+ if (delta.name != null) {
3466
+ open.toolName = delta.name;
3467
+ }
3468
+ if (delta.arguments != null) {
3469
+ open.arguments = delta.arguments;
3470
+ }
3471
+ if (delta.signature != null) {
3472
+ open.signature = delta.signature;
3473
+ }
3474
+ if (!open.startEmitted && open.toolName != null) {
3475
+ controller.enqueue({
3476
+ type: "tool-input-start",
3477
+ id: open.toolCallId,
3478
+ toolName: open.toolName
3479
+ });
3480
+ open.startEmitted = true;
3481
+ }
3482
+ hasFunctionCall = true;
3483
+ } else if (open.kind === "builtin_tool_call" && (delta == null ? void 0 : delta.type) === open.blockType) {
3484
+ if (delta.id != null) open.toolCallId = delta.id;
3485
+ if (delta.arguments != null) open.arguments = delta.arguments;
3486
+ if (delta.name != null && open.blockType === "mcp_server_tool_call") {
3487
+ open.toolName = delta.name;
3488
+ }
3489
+ } else if (open.kind === "builtin_tool_result" && (delta == null ? void 0 : delta.type) === open.blockType) {
3490
+ if (delta.call_id != null) open.callId = delta.call_id;
3491
+ if (delta.result !== void 0) open.result = delta.result;
3492
+ if (delta.is_error != null) open.isError = delta.is_error;
3493
+ if (delta.name != null && open.blockType === "mcp_server_tool_result") {
3494
+ open.toolName = delta.name;
3495
+ }
3496
+ }
3497
+ break;
3498
+ }
3499
+ case "content.stop": {
3500
+ const event = value;
3501
+ const open = openBlocks.get(event.index);
3502
+ if (open == null) break;
3503
+ if (open.kind === "text") {
3504
+ const textProviderMetadata = interactionId != null ? { google: { interactionId } } : void 0;
3505
+ controller.enqueue({
3506
+ type: "text-end",
3507
+ id: open.id,
3508
+ ...textProviderMetadata ? { providerMetadata: textProviderMetadata } : {}
3509
+ });
3510
+ } else if (open.kind === "reasoning") {
3511
+ const google2 = {};
3512
+ if (open.signature != null) google2.signature = open.signature;
3513
+ if (interactionId != null) google2.interactionId = interactionId;
3514
+ const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
3515
+ controller.enqueue({
3516
+ type: "reasoning-end",
3517
+ id: open.id,
3518
+ ...providerMetadata ? { providerMetadata } : {}
3519
+ });
3520
+ } else if (open.kind === "image") {
3521
+ const google2 = {};
3522
+ if (interactionId != null) google2.interactionId = interactionId;
3523
+ const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
3524
+ if (open.data != null && open.data.length > 0) {
3525
+ controller.enqueue({
3526
+ type: "file",
3527
+ mediaType: (_j = open.mimeType) != null ? _j : "image/png",
3528
+ data: open.data,
3529
+ ...providerMetadata ? { providerMetadata } : {}
3530
+ });
3531
+ } else if (open.uri != null && open.uri.length > 0) {
3532
+ const uriProviderMetadata = {
3533
+ google: {
3534
+ ...interactionId != null ? { interactionId } : {},
3535
+ imageUri: open.uri
3536
+ }
3537
+ };
3538
+ controller.enqueue({
3539
+ type: "file",
3540
+ mediaType: (_k = open.mimeType) != null ? _k : "image/png",
3541
+ data: "",
3542
+ providerMetadata: uriProviderMetadata
3543
+ });
3544
+ }
3545
+ } else if (open.kind === "function_call") {
3546
+ const toolName = (_l = open.toolName) != null ? _l : "unknown";
3547
+ const argsJson = JSON.stringify((_m = open.arguments) != null ? _m : {});
3548
+ if (!open.startEmitted) {
3549
+ controller.enqueue({
3550
+ type: "tool-input-start",
3551
+ id: open.toolCallId,
3552
+ toolName
3553
+ });
3554
+ }
3555
+ controller.enqueue({
3556
+ type: "tool-input-delta",
3557
+ id: open.toolCallId,
3558
+ delta: argsJson
3559
+ });
3560
+ controller.enqueue({
3561
+ type: "tool-input-end",
3562
+ id: open.toolCallId
3563
+ });
3564
+ const google2 = {};
3565
+ if (open.signature != null) google2.signature = open.signature;
3566
+ if (interactionId != null) google2.interactionId = interactionId;
3567
+ const providerMetadata = Object.keys(google2).length > 0 ? { google: google2 } : void 0;
3568
+ controller.enqueue({
3569
+ type: "tool-call",
3570
+ toolCallId: open.toolCallId,
3571
+ toolName,
3572
+ input: argsJson,
3573
+ ...providerMetadata ? { providerMetadata } : {}
3574
+ });
3575
+ } else if (open.kind === "builtin_tool_call" && !open.callEmitted) {
3576
+ controller.enqueue({
3577
+ type: "tool-call",
3578
+ toolCallId: open.toolCallId,
3579
+ toolName: open.toolName,
3580
+ input: JSON.stringify((_n = open.arguments) != null ? _n : {}),
3581
+ providerExecuted: true
3582
+ });
3583
+ open.callEmitted = true;
3584
+ } else if (open.kind === "builtin_tool_result" && !open.resultEmitted) {
3585
+ controller.enqueue({
3586
+ type: "tool-result",
3587
+ toolCallId: open.callId,
3588
+ toolName: open.toolName,
3589
+ result: (_o = open.result) != null ? _o : null
3590
+ });
3591
+ open.resultEmitted = true;
3592
+ const sources = builtinToolResultToSources({
3593
+ block: {
3594
+ type: open.blockType,
3595
+ call_id: open.callId,
3596
+ result: open.result
3597
+ },
3598
+ generateId: generateId3
3599
+ });
3600
+ for (const source of sources) {
3601
+ const key = sourceKey(source);
3602
+ if (emittedSourceKeys.has(key)) continue;
3603
+ emittedSourceKeys.add(key);
3604
+ controller.enqueue(source);
3605
+ }
3606
+ }
3607
+ openBlocks.delete(event.index);
3608
+ break;
3609
+ }
3610
+ case "interaction.status_update": {
3611
+ const event = value;
3612
+ finishStatus = event.status;
3613
+ break;
3614
+ }
3615
+ case "interaction.complete": {
3616
+ const event = value;
3617
+ const interaction = event.interaction;
3618
+ if ((interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0) {
3619
+ interactionId = interaction.id;
3620
+ }
3621
+ if ((interaction == null ? void 0 : interaction.status) != null) {
3622
+ finishStatus = interaction.status;
3623
+ }
3624
+ if ((interaction == null ? void 0 : interaction.usage) != null) {
3625
+ usage = interaction.usage;
3626
+ }
3627
+ if ((interaction == null ? void 0 : interaction.service_tier) != null) {
3628
+ serviceTier = interaction.service_tier;
3629
+ }
3630
+ break;
3631
+ }
3632
+ case "error": {
3633
+ const event = value;
3634
+ finishStatus = "failed";
3635
+ const errorPayload = (_p = event.error) != null ? _p : {
3636
+ message: "Unknown interaction error"
3637
+ };
3638
+ controller.enqueue({ type: "error", error: errorPayload });
3639
+ break;
3640
+ }
3641
+ default:
3642
+ break;
3643
+ }
3644
+ },
3645
+ flush(controller) {
3646
+ const finishReason = {
3647
+ unified: mapGoogleInteractionsFinishReason({
3648
+ status: finishStatus,
3649
+ hasFunctionCall
3650
+ }),
3651
+ raw: finishStatus
3652
+ };
3653
+ const providerMetadata = {
3654
+ google: {
3655
+ ...interactionId != null ? { interactionId } : {},
3656
+ ...serviceTier != null ? { serviceTier } : {}
3657
+ }
3658
+ };
3659
+ controller.enqueue({
3660
+ type: "finish",
3661
+ finishReason,
3662
+ usage: convertGoogleInteractionsUsage(usage),
3663
+ providerMetadata
3664
+ });
3665
+ }
3041
3666
  });
3042
- const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
3043
- provider: providerName,
3044
- baseURL,
3045
- headers: getHeaders,
3046
- fetch: options.fetch
3667
+ }
3668
+
3669
+ // src/interactions/convert-to-google-interactions-input.ts
3670
+ var import_provider_utils16 = require("@ai-sdk/provider-utils");
3671
+ function getTopLevelMediaType(mediaType) {
3672
+ const slashIndex = mediaType.indexOf("/");
3673
+ return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);
3674
+ }
3675
+ function isFullMediaType(mediaType) {
3676
+ const slashIndex = mediaType.indexOf("/");
3677
+ if (slashIndex === -1) {
3678
+ return false;
3679
+ }
3680
+ const subtype = mediaType.substring(slashIndex + 1);
3681
+ return subtype.length > 0 && subtype !== "*";
3682
+ }
3683
+ function convertToGoogleInteractionsInput({
3684
+ prompt,
3685
+ previousInteractionId,
3686
+ store,
3687
+ mediaResolution
3688
+ }) {
3689
+ var _a, _b, _c, _d, _e, _f, _g;
3690
+ const warnings = [];
3691
+ const incoherentCombo = previousInteractionId != null && store === false;
3692
+ const shouldCompact = previousInteractionId != null && store !== false;
3693
+ if (incoherentCombo) {
3694
+ warnings.push({
3695
+ type: "other",
3696
+ 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."
3697
+ });
3698
+ }
3699
+ const compactedPrompt = shouldCompact ? compactPromptForPreviousInteraction({
3700
+ prompt,
3701
+ previousInteractionId
3702
+ }) : prompt;
3703
+ const systemTexts = [];
3704
+ const turns = [];
3705
+ for (const message of compactedPrompt) {
3706
+ switch (message.role) {
3707
+ case "system": {
3708
+ systemTexts.push(message.content);
3709
+ break;
3710
+ }
3711
+ case "user": {
3712
+ const content = [];
3713
+ for (const part of message.content) {
3714
+ if (part.type === "text") {
3715
+ const block = {
3716
+ type: "text",
3717
+ text: part.text
3718
+ };
3719
+ content.push(block);
3720
+ } else if (part.type === "file") {
3721
+ const fileBlock = convertFilePartToContent({
3722
+ part,
3723
+ warnings,
3724
+ mediaResolution
3725
+ });
3726
+ if (fileBlock != null) {
3727
+ content.push(fileBlock);
3728
+ }
3729
+ }
3730
+ }
3731
+ const merged = mergeAdjacentTextContent(content);
3732
+ if (merged.length > 0) {
3733
+ turns.push({ role: "user", content: merged });
3734
+ }
3735
+ break;
3736
+ }
3737
+ case "assistant": {
3738
+ const content = [];
3739
+ for (const part of message.content) {
3740
+ if (part.type === "text") {
3741
+ content.push({ type: "text", text: part.text });
3742
+ } else if (part.type === "reasoning") {
3743
+ const signature = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.signature;
3744
+ content.push({
3745
+ type: "thought",
3746
+ ...signature != null ? { signature } : {},
3747
+ summary: part.text.length > 0 ? [{ type: "text", text: part.text }] : void 0
3748
+ });
3749
+ } else if (part.type === "tool-call") {
3750
+ const signature = (_d = (_c = part.providerOptions) == null ? void 0 : _c.google) == null ? void 0 : _d.signature;
3751
+ const args = typeof part.input === "string" ? safeParseToolArgs(part.input) : (_e = part.input) != null ? _e : {};
3752
+ content.push({
3753
+ type: "function_call",
3754
+ id: part.toolCallId,
3755
+ name: part.toolName,
3756
+ arguments: args,
3757
+ ...signature != null ? { signature } : {}
3758
+ });
3759
+ } else {
3760
+ warnings.push({
3761
+ type: "other",
3762
+ message: `google.interactions: unsupported assistant content part type "${part.type}"; part dropped.`
3763
+ });
3764
+ }
3765
+ }
3766
+ if (content.length > 0) {
3767
+ turns.push({ role: "model", content });
3768
+ }
3769
+ break;
3770
+ }
3771
+ case "tool": {
3772
+ const content = [];
3773
+ for (const part of message.content) {
3774
+ if (part.type !== "tool-result") {
3775
+ warnings.push({
3776
+ type: "other",
3777
+ message: `google.interactions: unsupported tool message part type "${part.type}"; part dropped.`
3778
+ });
3779
+ continue;
3780
+ }
3781
+ const block = convertToolResultPart({
3782
+ toolCallId: part.toolCallId,
3783
+ toolName: part.toolName,
3784
+ output: part.output,
3785
+ signature: (_g = (_f = part.providerOptions) == null ? void 0 : _f.google) == null ? void 0 : _g.signature,
3786
+ warnings
3787
+ });
3788
+ content.push(block);
3789
+ }
3790
+ if (content.length > 0) {
3791
+ turns.push({ role: "user", content });
3792
+ }
3793
+ break;
3794
+ }
3795
+ }
3796
+ }
3797
+ const systemInstruction = systemTexts.length > 0 ? systemTexts.join("\n\n") : void 0;
3798
+ let input;
3799
+ if (turns.length === 0) {
3800
+ input = "";
3801
+ } else if (turns.length === 1 && turns[0].role === "user" && Array.isArray(turns[0].content)) {
3802
+ input = turns[0].content;
3803
+ } else {
3804
+ input = turns;
3805
+ }
3806
+ return { input, systemInstruction, warnings };
3807
+ }
3808
+ function convertFilePartToContent({
3809
+ part,
3810
+ warnings,
3811
+ mediaResolution
3812
+ }) {
3813
+ const topLevel = getTopLevelMediaType(part.mediaType);
3814
+ let kind;
3815
+ switch (topLevel) {
3816
+ case "image":
3817
+ kind = "image";
3818
+ break;
3819
+ case "audio":
3820
+ kind = "audio";
3821
+ break;
3822
+ case "video":
3823
+ kind = "video";
3824
+ break;
3825
+ case "application":
3826
+ kind = "document";
3827
+ break;
3828
+ default:
3829
+ kind = void 0;
3830
+ }
3831
+ if (kind == null) {
3832
+ warnings.push({
3833
+ type: "other",
3834
+ message: `google.interactions: unsupported file media type "${part.mediaType}"; part dropped.`
3835
+ });
3836
+ return void 0;
3837
+ }
3838
+ const resolutionField = mediaResolution != null && (kind === "image" || kind === "video") ? { resolution: mediaResolution } : {};
3839
+ if (part.data instanceof URL) {
3840
+ return {
3841
+ type: kind,
3842
+ uri: part.data.toString(),
3843
+ ...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {},
3844
+ ...resolutionField
3845
+ };
3846
+ }
3847
+ if (!isFullMediaType(part.mediaType)) {
3848
+ warnings.push({
3849
+ type: "other",
3850
+ message: `google.interactions: inline file data requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.`
3851
+ });
3852
+ return void 0;
3853
+ }
3854
+ return {
3855
+ type: kind,
3856
+ data: (0, import_provider_utils16.convertToBase64)(part.data),
3857
+ mime_type: part.mediaType,
3858
+ ...resolutionField
3859
+ };
3860
+ }
3861
+ function compactPromptForPreviousInteraction({
3862
+ prompt,
3863
+ previousInteractionId
3864
+ }) {
3865
+ const out = [];
3866
+ const droppedToolCallIds = /* @__PURE__ */ new Set();
3867
+ for (const message of prompt) {
3868
+ if (message.role === "assistant") {
3869
+ const matchesLinkedInteraction = message.content.some((part) => {
3870
+ var _a, _b;
3871
+ const partInteractionId = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.interactionId;
3872
+ return partInteractionId === previousInteractionId;
3873
+ });
3874
+ if (matchesLinkedInteraction) {
3875
+ for (const part of message.content) {
3876
+ if (part.type === "tool-call") {
3877
+ droppedToolCallIds.add(part.toolCallId);
3878
+ }
3879
+ }
3880
+ continue;
3881
+ }
3882
+ out.push(message);
3883
+ continue;
3884
+ }
3885
+ if (message.role === "tool") {
3886
+ const remaining = message.content.filter((part) => {
3887
+ if (part.type !== "tool-result") {
3888
+ return true;
3889
+ }
3890
+ return !droppedToolCallIds.has(part.toolCallId);
3891
+ });
3892
+ if (remaining.length === 0) {
3893
+ continue;
3894
+ }
3895
+ out.push({
3896
+ ...message,
3897
+ content: remaining
3898
+ });
3899
+ continue;
3900
+ }
3901
+ out.push(message);
3902
+ }
3903
+ return out;
3904
+ }
3905
+ function safeParseToolArgs(input) {
3906
+ try {
3907
+ const parsed = JSON.parse(input);
3908
+ if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) {
3909
+ return parsed;
3910
+ }
3911
+ return { value: parsed };
3912
+ } catch (e) {
3913
+ return { value: input };
3914
+ }
3915
+ }
3916
+ function convertToolResultPart({
3917
+ toolCallId,
3918
+ toolName,
3919
+ output,
3920
+ signature,
3921
+ warnings
3922
+ }) {
3923
+ var _a;
3924
+ const base = {
3925
+ type: "function_result",
3926
+ call_id: toolCallId,
3927
+ name: toolName,
3928
+ ...signature != null ? { signature } : {}
3929
+ };
3930
+ switch (output.type) {
3931
+ case "text":
3932
+ return { ...base, result: output.value };
3933
+ case "json":
3934
+ return { ...base, result: JSON.stringify(output.value) };
3935
+ case "error-text":
3936
+ return { ...base, is_error: true, result: output.value };
3937
+ case "error-json":
3938
+ return { ...base, is_error: true, result: JSON.stringify(output.value) };
3939
+ case "execution-denied":
3940
+ return {
3941
+ ...base,
3942
+ is_error: true,
3943
+ result: (_a = output.reason) != null ? _a : "Tool execution denied by user."
3944
+ };
3945
+ case "content": {
3946
+ const blocks = [];
3947
+ for (const item of output.value) {
3948
+ if (item.type === "text") {
3949
+ blocks.push({ type: "text", text: item.text });
3950
+ } else if (item.type === "image-data") {
3951
+ const imageBlock = filePartToImageBlock({
3952
+ part: {
3953
+ type: "file",
3954
+ mediaType: item.mediaType,
3955
+ data: item.data
3956
+ },
3957
+ warnings
3958
+ });
3959
+ if (imageBlock != null) {
3960
+ blocks.push(imageBlock);
3961
+ }
3962
+ } else if (item.type === "image-url") {
3963
+ const imageBlock = filePartToImageBlock({
3964
+ part: {
3965
+ type: "file",
3966
+ mediaType: "image/*",
3967
+ data: new URL(item.url)
3968
+ },
3969
+ warnings
3970
+ });
3971
+ if (imageBlock != null) {
3972
+ blocks.push(imageBlock);
3973
+ }
3974
+ } else if (item.type === "file-data" || item.type === "file-url") {
3975
+ const mediaType = item.type === "file-data" ? item.mediaType : "application/*";
3976
+ const topLevel = getTopLevelMediaType(mediaType);
3977
+ if (topLevel !== "image") {
3978
+ warnings.push({
3979
+ type: "other",
3980
+ message: `google.interactions: tool-result file with mediaType "${mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`
3981
+ });
3982
+ continue;
3983
+ }
3984
+ const imageBlock = filePartToImageBlock({
3985
+ part: item.type === "file-data" ? {
3986
+ type: "file",
3987
+ mediaType: item.mediaType,
3988
+ data: item.data
3989
+ } : {
3990
+ type: "file",
3991
+ mediaType,
3992
+ data: new URL(item.url)
3993
+ },
3994
+ warnings
3995
+ });
3996
+ if (imageBlock != null) {
3997
+ blocks.push(imageBlock);
3998
+ }
3999
+ } else {
4000
+ warnings.push({
4001
+ type: "other",
4002
+ message: `google.interactions: tool-result content part type "${item.type}" is not supported; part dropped.`
4003
+ });
4004
+ }
4005
+ }
4006
+ return { ...base, result: blocks };
4007
+ }
4008
+ }
4009
+ }
4010
+ function filePartToImageBlock({
4011
+ part,
4012
+ warnings
4013
+ }) {
4014
+ if (part.data instanceof URL) {
4015
+ return {
4016
+ type: "image",
4017
+ uri: part.data.toString(),
4018
+ ...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {}
4019
+ };
4020
+ }
4021
+ if (!isFullMediaType(part.mediaType)) {
4022
+ warnings.push({
4023
+ type: "other",
4024
+ message: `google.interactions: tool-result image part requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.`
4025
+ });
4026
+ return void 0;
4027
+ }
4028
+ return {
4029
+ type: "image",
4030
+ data: (0, import_provider_utils16.convertToBase64)(part.data),
4031
+ mime_type: part.mediaType
4032
+ };
4033
+ }
4034
+ function mergeAdjacentTextContent(content) {
4035
+ if (content.length < 2) {
4036
+ return content;
4037
+ }
4038
+ const result = [];
4039
+ for (const block of content) {
4040
+ const last = result[result.length - 1];
4041
+ if (block.type === "text" && last != null && last.type === "text" && last.annotations == null && block.annotations == null) {
4042
+ const merged = {
4043
+ type: "text",
4044
+ text: `${last.text}
4045
+
4046
+ ${block.text}`
4047
+ };
4048
+ result[result.length - 1] = merged;
4049
+ continue;
4050
+ }
4051
+ result.push(block);
4052
+ }
4053
+ return result;
4054
+ }
4055
+
4056
+ // src/interactions/google-interactions-api.ts
4057
+ var import_provider_utils17 = require("@ai-sdk/provider-utils");
4058
+ var import_v415 = require("zod/v4");
4059
+ var tokenByModalitySchema = () => import_v415.z.object({
4060
+ modality: import_v415.z.string().nullish(),
4061
+ tokens: import_v415.z.number().nullish()
4062
+ }).loose();
4063
+ var usageSchema2 = () => import_v415.z.object({
4064
+ total_input_tokens: import_v415.z.number().nullish(),
4065
+ total_output_tokens: import_v415.z.number().nullish(),
4066
+ total_thought_tokens: import_v415.z.number().nullish(),
4067
+ total_cached_tokens: import_v415.z.number().nullish(),
4068
+ total_tool_use_tokens: import_v415.z.number().nullish(),
4069
+ total_tokens: import_v415.z.number().nullish(),
4070
+ input_tokens_by_modality: import_v415.z.array(tokenByModalitySchema()).nullish(),
4071
+ output_tokens_by_modality: import_v415.z.array(tokenByModalitySchema()).nullish(),
4072
+ cached_tokens_by_modality: import_v415.z.array(tokenByModalitySchema()).nullish(),
4073
+ tool_use_tokens_by_modality: import_v415.z.array(tokenByModalitySchema()).nullish(),
4074
+ grounding_tool_count: import_v415.z.array(
4075
+ import_v415.z.object({
4076
+ type: import_v415.z.string().nullish(),
4077
+ count: import_v415.z.number().nullish()
4078
+ }).loose()
4079
+ ).nullish()
4080
+ }).loose();
4081
+ var interactionStatusSchema = () => import_v415.z.enum([
4082
+ "in_progress",
4083
+ "requires_action",
4084
+ "completed",
4085
+ "failed",
4086
+ "cancelled",
4087
+ "incomplete"
4088
+ ]);
4089
+ var annotationSchema = () => {
4090
+ const urlCitation = import_v415.z.object({
4091
+ type: import_v415.z.literal("url_citation"),
4092
+ url: import_v415.z.string().nullish(),
4093
+ title: import_v415.z.string().nullish(),
4094
+ start_index: import_v415.z.number().nullish(),
4095
+ end_index: import_v415.z.number().nullish()
4096
+ }).loose();
4097
+ const fileCitation = import_v415.z.object({
4098
+ type: import_v415.z.literal("file_citation"),
4099
+ file_name: import_v415.z.string().nullish(),
4100
+ document_uri: import_v415.z.string().nullish(),
4101
+ source: import_v415.z.string().nullish(),
4102
+ page_number: import_v415.z.number().nullish(),
4103
+ media_id: import_v415.z.string().nullish(),
4104
+ start_index: import_v415.z.number().nullish(),
4105
+ end_index: import_v415.z.number().nullish(),
4106
+ custom_metadata: import_v415.z.record(import_v415.z.string(), import_v415.z.unknown()).nullish()
4107
+ }).loose();
4108
+ const placeCitation = import_v415.z.object({
4109
+ type: import_v415.z.literal("place_citation"),
4110
+ name: import_v415.z.string().nullish(),
4111
+ url: import_v415.z.string().nullish(),
4112
+ place_id: import_v415.z.string().nullish(),
4113
+ start_index: import_v415.z.number().nullish(),
4114
+ end_index: import_v415.z.number().nullish()
4115
+ }).loose();
4116
+ return import_v415.z.union([
4117
+ urlCitation,
4118
+ fileCitation,
4119
+ placeCitation,
4120
+ import_v415.z.object({ type: import_v415.z.string() }).loose()
4121
+ ]);
4122
+ };
4123
+ var thoughtSummaryItemSchema = () => import_v415.z.object({
4124
+ type: import_v415.z.string(),
4125
+ text: import_v415.z.string().nullish(),
4126
+ data: import_v415.z.string().nullish(),
4127
+ mime_type: import_v415.z.string().nullish()
4128
+ }).loose();
4129
+ var contentBlockSchema = () => {
4130
+ const textContent = import_v415.z.object({
4131
+ type: import_v415.z.literal("text"),
4132
+ text: import_v415.z.string(),
4133
+ annotations: import_v415.z.array(annotationSchema()).nullish()
4134
+ }).loose();
4135
+ const thoughtContent = import_v415.z.object({
4136
+ type: import_v415.z.literal("thought"),
4137
+ signature: import_v415.z.string().nullish(),
4138
+ summary: import_v415.z.array(thoughtSummaryItemSchema()).nullish()
4139
+ }).loose();
4140
+ const functionCallContent = import_v415.z.object({
4141
+ type: import_v415.z.literal("function_call"),
4142
+ id: import_v415.z.string(),
4143
+ name: import_v415.z.string(),
4144
+ arguments: import_v415.z.record(import_v415.z.string(), import_v415.z.unknown()).nullish(),
4145
+ signature: import_v415.z.string().nullish()
4146
+ }).loose();
4147
+ const imageContent = import_v415.z.object({
4148
+ type: import_v415.z.literal("image"),
4149
+ data: import_v415.z.string().nullish(),
4150
+ mime_type: import_v415.z.string().nullish(),
4151
+ resolution: import_v415.z.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4152
+ uri: import_v415.z.string().nullish()
4153
+ }).loose();
4154
+ const builtinToolCall = import_v415.z.object({
4155
+ type: import_v415.z.enum([
4156
+ "google_search_call",
4157
+ "code_execution_call",
4158
+ "url_context_call",
4159
+ "file_search_call",
4160
+ "google_maps_call",
4161
+ "mcp_server_tool_call"
4162
+ ]),
4163
+ id: import_v415.z.string(),
4164
+ arguments: import_v415.z.record(import_v415.z.string(), import_v415.z.unknown()).nullish(),
4165
+ name: import_v415.z.string().nullish(),
4166
+ server_name: import_v415.z.string().nullish(),
4167
+ search_type: import_v415.z.string().nullish(),
4168
+ signature: import_v415.z.string().nullish()
4169
+ }).loose();
4170
+ const builtinToolResult = import_v415.z.object({
4171
+ type: import_v415.z.enum([
4172
+ "google_search_result",
4173
+ "code_execution_result",
4174
+ "url_context_result",
4175
+ "file_search_result",
4176
+ "google_maps_result",
4177
+ "mcp_server_tool_result"
4178
+ ]),
4179
+ call_id: import_v415.z.string(),
4180
+ result: import_v415.z.unknown().nullish(),
4181
+ is_error: import_v415.z.boolean().nullish(),
4182
+ name: import_v415.z.string().nullish(),
4183
+ server_name: import_v415.z.string().nullish(),
4184
+ signature: import_v415.z.string().nullish()
4185
+ }).loose();
4186
+ return import_v415.z.union([
4187
+ textContent,
4188
+ imageContent,
4189
+ thoughtContent,
4190
+ functionCallContent,
4191
+ builtinToolCall,
4192
+ builtinToolResult,
4193
+ import_v415.z.object({ type: import_v415.z.string() }).loose()
4194
+ ]);
4195
+ };
4196
+ var googleInteractionsResponseSchema = (0, import_provider_utils17.lazySchema)(
4197
+ () => (0, import_provider_utils17.zodSchema)(
4198
+ import_v415.z.object({
4199
+ /*
4200
+ * `id` is omitted from the response body when `store: false` (fully
4201
+ * stateless mode) — there is no server-side interaction record for the
4202
+ * client to reference. `nullish` lets the schema accept that shape.
4203
+ */
4204
+ id: import_v415.z.string().nullish(),
4205
+ created: import_v415.z.string().nullish(),
4206
+ updated: import_v415.z.string().nullish(),
4207
+ status: interactionStatusSchema(),
4208
+ model: import_v415.z.string().nullish(),
4209
+ agent: import_v415.z.string().nullish(),
4210
+ outputs: import_v415.z.array(contentBlockSchema()).nullish(),
4211
+ usage: usageSchema2().nullish(),
4212
+ service_tier: import_v415.z.string().nullish(),
4213
+ previous_interaction_id: import_v415.z.string().nullish(),
4214
+ response_modalities: import_v415.z.array(import_v415.z.string()).nullish()
4215
+ }).loose()
4216
+ )
4217
+ );
4218
+ var googleInteractionsEventSchema = (0, import_provider_utils17.lazySchema)(
4219
+ () => (0, import_provider_utils17.zodSchema)(
4220
+ (() => {
4221
+ const status = interactionStatusSchema();
4222
+ const annotation = annotationSchema();
4223
+ const thoughtSummaryItem = thoughtSummaryItemSchema();
4224
+ const interactionStartEvent = import_v415.z.object({
4225
+ event_type: import_v415.z.literal("interaction.start"),
4226
+ event_id: import_v415.z.string().nullish(),
4227
+ interaction: import_v415.z.object({
4228
+ /*
4229
+ * `id` is omitted when `store: false` (fully stateless mode);
4230
+ * see the matching note on `googleInteractionsResponseSchema.id`.
4231
+ */
4232
+ id: import_v415.z.string().nullish(),
4233
+ created: import_v415.z.string().nullish(),
4234
+ model: import_v415.z.string().nullish(),
4235
+ agent: import_v415.z.string().nullish(),
4236
+ status: status.nullish()
4237
+ }).loose()
4238
+ }).loose();
4239
+ const contentStartEvent = import_v415.z.object({
4240
+ event_type: import_v415.z.literal("content.start"),
4241
+ event_id: import_v415.z.string().nullish(),
4242
+ index: import_v415.z.number(),
4243
+ content: contentBlockSchema()
4244
+ }).loose();
4245
+ const contentDeltaText = import_v415.z.object({
4246
+ type: import_v415.z.literal("text"),
4247
+ text: import_v415.z.string()
4248
+ }).loose();
4249
+ const contentDeltaThoughtSummary = import_v415.z.object({
4250
+ type: import_v415.z.literal("thought_summary"),
4251
+ content: thoughtSummaryItem.nullish()
4252
+ }).loose();
4253
+ const contentDeltaThoughtSignature = import_v415.z.object({
4254
+ type: import_v415.z.literal("thought_signature"),
4255
+ signature: import_v415.z.string().nullish()
4256
+ }).loose();
4257
+ const contentDeltaFunctionCall = import_v415.z.object({
4258
+ type: import_v415.z.literal("function_call"),
4259
+ id: import_v415.z.string(),
4260
+ name: import_v415.z.string(),
4261
+ arguments: import_v415.z.record(import_v415.z.string(), import_v415.z.unknown()).nullish(),
4262
+ signature: import_v415.z.string().nullish()
4263
+ }).loose();
4264
+ const contentDeltaTextAnnotation = import_v415.z.object({
4265
+ type: import_v415.z.literal("text_annotation"),
4266
+ annotations: import_v415.z.array(annotation).nullish()
4267
+ }).loose();
4268
+ const contentDeltaImage = import_v415.z.object({
4269
+ type: import_v415.z.literal("image"),
4270
+ data: import_v415.z.string().nullish(),
4271
+ mime_type: import_v415.z.string().nullish(),
4272
+ resolution: import_v415.z.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4273
+ uri: import_v415.z.string().nullish()
4274
+ }).loose();
4275
+ const contentDeltaBuiltinToolCall = import_v415.z.object({
4276
+ type: import_v415.z.enum([
4277
+ "google_search_call",
4278
+ "code_execution_call",
4279
+ "url_context_call",
4280
+ "file_search_call",
4281
+ "google_maps_call",
4282
+ "mcp_server_tool_call"
4283
+ ]),
4284
+ id: import_v415.z.string(),
4285
+ arguments: import_v415.z.record(import_v415.z.string(), import_v415.z.unknown()).nullish(),
4286
+ name: import_v415.z.string().nullish(),
4287
+ server_name: import_v415.z.string().nullish(),
4288
+ search_type: import_v415.z.string().nullish(),
4289
+ signature: import_v415.z.string().nullish()
4290
+ }).loose();
4291
+ const contentDeltaBuiltinToolResult = import_v415.z.object({
4292
+ type: import_v415.z.enum([
4293
+ "google_search_result",
4294
+ "code_execution_result",
4295
+ "url_context_result",
4296
+ "file_search_result",
4297
+ "google_maps_result",
4298
+ "mcp_server_tool_result"
4299
+ ]),
4300
+ call_id: import_v415.z.string(),
4301
+ result: import_v415.z.unknown().nullish(),
4302
+ is_error: import_v415.z.boolean().nullish(),
4303
+ name: import_v415.z.string().nullish(),
4304
+ server_name: import_v415.z.string().nullish(),
4305
+ signature: import_v415.z.string().nullish()
4306
+ }).loose();
4307
+ const contentDeltaUnknown = import_v415.z.object({ type: import_v415.z.string() }).loose();
4308
+ const contentDeltaUnion = import_v415.z.union([
4309
+ contentDeltaText,
4310
+ contentDeltaImage,
4311
+ contentDeltaThoughtSummary,
4312
+ contentDeltaThoughtSignature,
4313
+ contentDeltaFunctionCall,
4314
+ contentDeltaTextAnnotation,
4315
+ contentDeltaBuiltinToolCall,
4316
+ contentDeltaBuiltinToolResult,
4317
+ contentDeltaUnknown
4318
+ ]);
4319
+ const contentDeltaEvent = import_v415.z.object({
4320
+ event_type: import_v415.z.literal("content.delta"),
4321
+ event_id: import_v415.z.string().nullish(),
4322
+ index: import_v415.z.number(),
4323
+ delta: contentDeltaUnion
4324
+ }).loose();
4325
+ const contentStopEvent = import_v415.z.object({
4326
+ event_type: import_v415.z.literal("content.stop"),
4327
+ event_id: import_v415.z.string().nullish(),
4328
+ index: import_v415.z.number()
4329
+ }).loose();
4330
+ const interactionStatusUpdateEvent = import_v415.z.object({
4331
+ event_type: import_v415.z.literal("interaction.status_update"),
4332
+ event_id: import_v415.z.string().nullish(),
4333
+ interaction_id: import_v415.z.string().nullish(),
4334
+ status
4335
+ }).loose();
4336
+ const interactionCompleteEvent = import_v415.z.object({
4337
+ event_type: import_v415.z.literal("interaction.complete"),
4338
+ event_id: import_v415.z.string().nullish(),
4339
+ interaction: import_v415.z.object({
4340
+ id: import_v415.z.string().nullish(),
4341
+ status: status.nullish(),
4342
+ usage: usageSchema2().nullish(),
4343
+ service_tier: import_v415.z.string().nullish()
4344
+ }).loose()
4345
+ }).loose();
4346
+ const errorEvent = import_v415.z.object({
4347
+ event_type: import_v415.z.literal("error"),
4348
+ event_id: import_v415.z.string().nullish(),
4349
+ error: import_v415.z.object({
4350
+ code: import_v415.z.string().nullish(),
4351
+ message: import_v415.z.string().nullish()
4352
+ }).loose().nullish()
4353
+ }).loose();
4354
+ const unknownEvent = import_v415.z.object({ event_type: import_v415.z.string() }).loose();
4355
+ return import_v415.z.union([
4356
+ interactionStartEvent,
4357
+ contentStartEvent,
4358
+ contentDeltaEvent,
4359
+ contentStopEvent,
4360
+ interactionStatusUpdateEvent,
4361
+ interactionCompleteEvent,
4362
+ errorEvent,
4363
+ unknownEvent
4364
+ ]);
4365
+ })()
4366
+ )
4367
+ );
4368
+
4369
+ // src/interactions/google-interactions-language-model-options.ts
4370
+ var import_provider_utils18 = require("@ai-sdk/provider-utils");
4371
+ var import_v416 = require("zod/v4");
4372
+ var googleInteractionsLanguageModelOptions = (0, import_provider_utils18.lazySchema)(
4373
+ () => (0, import_provider_utils18.zodSchema)(
4374
+ import_v416.z.object({
4375
+ previousInteractionId: import_v416.z.string().nullish(),
4376
+ store: import_v416.z.boolean().nullish(),
4377
+ agent: import_v416.z.string().nullish(),
4378
+ agentConfig: import_v416.z.union([
4379
+ import_v416.z.object({
4380
+ type: import_v416.z.literal("dynamic")
4381
+ }).loose(),
4382
+ import_v416.z.object({
4383
+ type: import_v416.z.literal("deep-research"),
4384
+ thinkingSummaries: import_v416.z.enum(["auto", "none"]).nullish(),
4385
+ visualization: import_v416.z.enum(["off", "auto"]).nullish(),
4386
+ collaborativePlanning: import_v416.z.boolean().nullish()
4387
+ })
4388
+ ]).nullish(),
4389
+ thinkingLevel: import_v416.z.enum(["minimal", "low", "medium", "high"]).nullish(),
4390
+ thinkingSummaries: import_v416.z.enum(["auto", "none"]).nullish(),
4391
+ imageConfig: import_v416.z.object({
4392
+ aspectRatio: import_v416.z.enum([
4393
+ "1:1",
4394
+ "2:3",
4395
+ "3:2",
4396
+ "3:4",
4397
+ "4:3",
4398
+ "4:5",
4399
+ "5:4",
4400
+ "9:16",
4401
+ "16:9",
4402
+ "21:9",
4403
+ "1:8",
4404
+ "8:1",
4405
+ "1:4",
4406
+ "4:1"
4407
+ ]).nullish(),
4408
+ imageSize: import_v416.z.enum(["1K", "2K", "4K", "512"]).nullish()
4409
+ }).nullish(),
4410
+ mediaResolution: import_v416.z.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4411
+ responseModalities: import_v416.z.array(import_v416.z.enum(["text", "image", "audio", "video", "document"])).nullish(),
4412
+ serviceTier: import_v416.z.enum(["flex", "standard", "priority"]).nullish(),
4413
+ /**
4414
+ * Alternative to AI SDK `system` message. If both are set, the AI SDK
4415
+ * `system` message wins and a warning is emitted.
4416
+ */
4417
+ systemInstruction: import_v416.z.string().nullish(),
4418
+ /**
4419
+ * Per-block signature for round-tripping `thought.signature` and
4420
+ * `function_call.signature` blocks. Set by the SDK on output reasoning /
4421
+ * tool-call parts; passed back unchanged on input parts so the API
4422
+ * accepts the prior turn.
4423
+ */
4424
+ signature: import_v416.z.string().nullish(),
4425
+ /**
4426
+ * Set by the SDK on output assistant messages. The converter uses it to
4427
+ * decide which messages to drop when compacting under
4428
+ * `previousInteractionId`.
4429
+ */
4430
+ interactionId: import_v416.z.string().nullish(),
4431
+ /**
4432
+ * Maximum time, in milliseconds, to poll a background interaction (agent
4433
+ * call) before giving up. Defaults to 30 minutes. Long-running agents
4434
+ * such as deep research can take tens of minutes — increase if needed.
4435
+ */
4436
+ pollingTimeoutMs: import_v416.z.number().int().positive().nullish()
4437
+ })
4438
+ )
4439
+ );
4440
+
4441
+ // src/interactions/parse-google-interactions-outputs.ts
4442
+ function googleProviderMetadata({
4443
+ signature,
4444
+ interactionId
4445
+ }) {
4446
+ const google2 = {};
4447
+ if (signature != null) {
4448
+ google2.signature = signature;
4449
+ }
4450
+ if (interactionId != null) {
4451
+ google2.interactionId = interactionId;
4452
+ }
4453
+ return Object.keys(google2).length > 0 ? { providerMetadata: { google: google2 } } : {};
4454
+ }
4455
+ var BUILTIN_TOOL_CALL_TYPES2 = /* @__PURE__ */ new Set([
4456
+ "google_search_call",
4457
+ "code_execution_call",
4458
+ "url_context_call",
4459
+ "file_search_call",
4460
+ "google_maps_call",
4461
+ "mcp_server_tool_call"
4462
+ ]);
4463
+ var BUILTIN_TOOL_RESULT_TYPES2 = /* @__PURE__ */ new Set([
4464
+ "google_search_result",
4465
+ "code_execution_result",
4466
+ "url_context_result",
4467
+ "file_search_result",
4468
+ "google_maps_result",
4469
+ "mcp_server_tool_result"
4470
+ ]);
4471
+ function builtinToolNameFromCallType2(type) {
4472
+ return type.replace(/_call$/, "");
4473
+ }
4474
+ function builtinToolNameFromResultType2(type) {
4475
+ return type.replace(/_result$/, "");
4476
+ }
4477
+ function parseGoogleInteractionsOutputs({
4478
+ outputs,
4479
+ generateId: generateId3,
4480
+ interactionId
4481
+ }) {
4482
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4483
+ const content = [];
4484
+ let hasFunctionCall = false;
4485
+ if (outputs == null) {
4486
+ return { content, hasFunctionCall };
4487
+ }
4488
+ for (const block of outputs) {
4489
+ if (block == null || typeof block !== "object") continue;
4490
+ const type = block.type;
4491
+ if (typeof type !== "string") continue;
4492
+ switch (type) {
4493
+ case "text": {
4494
+ const text = (_a = block.text) != null ? _a : "";
4495
+ const annotations = block.annotations;
4496
+ content.push({
4497
+ type: "text",
4498
+ text,
4499
+ ...googleProviderMetadata({ interactionId })
4500
+ });
4501
+ const sources = annotationsToSources({ annotations, generateId: generateId3 });
4502
+ for (const source of sources) {
4503
+ content.push(source);
4504
+ }
4505
+ break;
4506
+ }
4507
+ case "thought": {
4508
+ const thought = block;
4509
+ const summary = Array.isArray(thought.summary) ? thought.summary : [];
4510
+ const text = summary.filter(
4511
+ (item) => (item == null ? void 0 : item.type) === "text" && typeof item.text === "string"
4512
+ ).map((item) => item.text).join("\n");
4513
+ content.push({
4514
+ type: "reasoning",
4515
+ text,
4516
+ ...googleProviderMetadata({
4517
+ signature: thought.signature,
4518
+ interactionId
4519
+ })
4520
+ });
4521
+ break;
4522
+ }
4523
+ case "image": {
4524
+ const image = block;
4525
+ if (image.data != null && image.data.length > 0) {
4526
+ content.push({
4527
+ type: "file",
4528
+ mediaType: (_b = image.mime_type) != null ? _b : "image/png",
4529
+ data: image.data,
4530
+ ...googleProviderMetadata({ interactionId })
4531
+ });
4532
+ } else if (image.uri != null && image.uri.length > 0) {
4533
+ content.push({
4534
+ type: "file",
4535
+ mediaType: (_c = image.mime_type) != null ? _c : "image/png",
4536
+ data: "",
4537
+ providerMetadata: {
4538
+ google: {
4539
+ ...interactionId != null ? { interactionId } : {},
4540
+ imageUri: image.uri
4541
+ }
4542
+ }
4543
+ });
4544
+ }
4545
+ break;
4546
+ }
4547
+ case "function_call": {
4548
+ hasFunctionCall = true;
4549
+ const call = block;
4550
+ content.push({
4551
+ type: "tool-call",
4552
+ toolCallId: call.id,
4553
+ toolName: call.name,
4554
+ input: JSON.stringify((_d = call.arguments) != null ? _d : {}),
4555
+ ...googleProviderMetadata({
4556
+ signature: call.signature,
4557
+ interactionId
4558
+ })
4559
+ });
4560
+ break;
4561
+ }
4562
+ default: {
4563
+ if (BUILTIN_TOOL_CALL_TYPES2.has(type)) {
4564
+ const call = block;
4565
+ const toolName = type === "mcp_server_tool_call" ? (_e = call.name) != null ? _e : "mcp_server_tool" : builtinToolNameFromCallType2(type);
4566
+ const input = JSON.stringify((_f = call.arguments) != null ? _f : {});
4567
+ content.push({
4568
+ type: "tool-call",
4569
+ toolCallId: (_g = call.id) != null ? _g : generateId3(),
4570
+ toolName,
4571
+ input,
4572
+ providerExecuted: true
4573
+ });
4574
+ } else if (BUILTIN_TOOL_RESULT_TYPES2.has(type)) {
4575
+ const result = block;
4576
+ const toolName = type === "mcp_server_tool_result" ? (_h = result.name) != null ? _h : "mcp_server_tool" : builtinToolNameFromResultType2(type);
4577
+ content.push({
4578
+ type: "tool-result",
4579
+ toolCallId: (_i = result.call_id) != null ? _i : generateId3(),
4580
+ toolName,
4581
+ result: (_j = result.result) != null ? _j : null
4582
+ });
4583
+ const sources = builtinToolResultToSources({
4584
+ block,
4585
+ generateId: generateId3
4586
+ });
4587
+ for (const source of sources) {
4588
+ content.push(source);
4589
+ }
4590
+ }
4591
+ break;
4592
+ }
4593
+ }
4594
+ }
4595
+ return { content, hasFunctionCall };
4596
+ }
4597
+
4598
+ // src/interactions/poll-google-interactions.ts
4599
+ var import_provider_utils19 = require("@ai-sdk/provider-utils");
4600
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]);
4601
+ function isTerminalStatus(status) {
4602
+ return status != null && TERMINAL_STATUSES.has(status);
4603
+ }
4604
+ var DEFAULT_INITIAL_DELAY_MS = 1e3;
4605
+ var DEFAULT_MAX_DELAY_MS = 1e4;
4606
+ var DEFAULT_TIMEOUT_MS = 30 * 60 * 1e3;
4607
+ async function pollGoogleInteractionUntilTerminal({
4608
+ baseURL,
4609
+ interactionId,
4610
+ headers,
4611
+ fetch,
4612
+ abortSignal,
4613
+ initialDelayMs = DEFAULT_INITIAL_DELAY_MS,
4614
+ maxDelayMs = DEFAULT_MAX_DELAY_MS,
4615
+ timeoutMs = DEFAULT_TIMEOUT_MS
4616
+ }) {
4617
+ if (interactionId == null || interactionId.length === 0) {
4618
+ throw new Error(
4619
+ "google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id."
4620
+ );
4621
+ }
4622
+ const startedAt = Date.now();
4623
+ let nextDelayMs = initialDelayMs;
4624
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4625
+ while (true) {
4626
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
4627
+ throw new DOMException("Polling was aborted", "AbortError");
4628
+ }
4629
+ if (Date.now() - startedAt > timeoutMs) {
4630
+ throw new Error(
4631
+ `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4632
+ );
4633
+ }
4634
+ await (0, import_provider_utils19.delay)(nextDelayMs, { abortSignal });
4635
+ const {
4636
+ value: response,
4637
+ rawValue: rawResponse,
4638
+ responseHeaders
4639
+ } = await (0, import_provider_utils19.getFromApi)({
4640
+ url,
4641
+ headers,
4642
+ failedResponseHandler: googleFailedResponseHandler,
4643
+ successfulResponseHandler: (0, import_provider_utils19.createJsonResponseHandler)(
4644
+ googleInteractionsResponseSchema
4645
+ ),
4646
+ abortSignal,
4647
+ fetch
4648
+ });
4649
+ if (isTerminalStatus(response.status)) {
4650
+ return { response, rawResponse, responseHeaders };
4651
+ }
4652
+ nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4653
+ }
4654
+ }
4655
+
4656
+ // src/interactions/prepare-google-interactions-tools.ts
4657
+ function prepareGoogleInteractionsTools({
4658
+ tools,
4659
+ toolChoice
4660
+ }) {
4661
+ var _a, _b, _c, _d;
4662
+ const toolWarnings = [];
4663
+ const normalized = (tools == null ? void 0 : tools.length) ? tools : void 0;
4664
+ if (normalized == null) {
4665
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
4666
+ }
4667
+ const interactionsTools = [];
4668
+ for (const tool of normalized) {
4669
+ if (tool.type === "function") {
4670
+ interactionsTools.push({
4671
+ type: "function",
4672
+ name: tool.name,
4673
+ description: (_a = tool.description) != null ? _a : "",
4674
+ parameters: tool.inputSchema
4675
+ });
4676
+ continue;
4677
+ }
4678
+ if (tool.type === "provider") {
4679
+ const args = (_b = tool.args) != null ? _b : {};
4680
+ switch (tool.id) {
4681
+ case "google.google_search": {
4682
+ const searchTypesArg = args.searchTypes;
4683
+ let search_types;
4684
+ if (searchTypesArg != null && typeof searchTypesArg === "object") {
4685
+ const list = [];
4686
+ if (searchTypesArg.webSearch != null) list.push("web_search");
4687
+ if (searchTypesArg.imageSearch != null) list.push("image_search");
4688
+ if (list.length > 0) {
4689
+ search_types = list;
4690
+ }
4691
+ }
4692
+ interactionsTools.push({
4693
+ type: "google_search",
4694
+ ...search_types != null ? { search_types } : {}
4695
+ });
4696
+ break;
4697
+ }
4698
+ case "google.code_execution": {
4699
+ interactionsTools.push({ type: "code_execution" });
4700
+ break;
4701
+ }
4702
+ case "google.url_context": {
4703
+ interactionsTools.push({ type: "url_context" });
4704
+ break;
4705
+ }
4706
+ case "google.file_search": {
4707
+ interactionsTools.push({
4708
+ type: "file_search",
4709
+ ...args.fileSearchStoreNames != null ? {
4710
+ file_search_store_names: args.fileSearchStoreNames
4711
+ } : {},
4712
+ ...args.topK != null ? { top_k: args.topK } : {},
4713
+ ...args.metadataFilter != null ? { metadata_filter: args.metadataFilter } : {}
4714
+ });
4715
+ break;
4716
+ }
4717
+ case "google.google_maps": {
4718
+ interactionsTools.push({
4719
+ type: "google_maps",
4720
+ ...args.latitude != null ? { latitude: args.latitude } : {},
4721
+ ...args.longitude != null ? { longitude: args.longitude } : {},
4722
+ ...args.enableWidget != null ? { enable_widget: args.enableWidget } : {}
4723
+ });
4724
+ break;
4725
+ }
4726
+ case "google.computer_use": {
4727
+ interactionsTools.push({
4728
+ type: "computer_use",
4729
+ environment: (_c = args.environment) != null ? _c : "browser",
4730
+ ...args.excludedPredefinedFunctions != null ? {
4731
+ excludedPredefinedFunctions: args.excludedPredefinedFunctions
4732
+ } : {}
4733
+ });
4734
+ break;
4735
+ }
4736
+ case "google.mcp_server": {
4737
+ interactionsTools.push({
4738
+ type: "mcp_server",
4739
+ ...args.name != null ? { name: args.name } : {},
4740
+ ...args.url != null ? { url: args.url } : {},
4741
+ ...args.headers != null ? { headers: args.headers } : {},
4742
+ ...args.allowedTools != null ? { allowed_tools: args.allowedTools } : {}
4743
+ });
4744
+ break;
4745
+ }
4746
+ case "google.retrieval": {
4747
+ const vertexAiSearchConfig = (_d = args.vertexAiSearchConfig) != null ? _d : void 0;
4748
+ interactionsTools.push({
4749
+ type: "retrieval",
4750
+ ...args.retrievalTypes != null ? {
4751
+ retrieval_types: args.retrievalTypes
4752
+ } : { retrieval_types: ["vertex_ai_search"] },
4753
+ ...vertexAiSearchConfig != null ? { vertex_ai_search_config: vertexAiSearchConfig } : {}
4754
+ });
4755
+ break;
4756
+ }
4757
+ default: {
4758
+ toolWarnings.push({
4759
+ type: "unsupported",
4760
+ feature: `provider-defined tool ${tool.id}`,
4761
+ details: `provider-defined tool ${tool.id} is not supported by google.interactions; tool dropped.`
4762
+ });
4763
+ break;
4764
+ }
4765
+ }
4766
+ continue;
4767
+ }
4768
+ toolWarnings.push({
4769
+ type: "unsupported",
4770
+ feature: `tool of type ${tool.type}`,
4771
+ details: "Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."
4772
+ });
4773
+ }
4774
+ const hasFunctionTool = interactionsTools.some((t) => t.type === "function");
4775
+ let mappedToolChoice;
4776
+ if (toolChoice != null && hasFunctionTool) {
4777
+ switch (toolChoice.type) {
4778
+ case "auto":
4779
+ mappedToolChoice = "auto";
4780
+ break;
4781
+ case "required":
4782
+ mappedToolChoice = "any";
4783
+ break;
4784
+ case "none":
4785
+ mappedToolChoice = "none";
4786
+ break;
4787
+ case "tool":
4788
+ mappedToolChoice = {
4789
+ allowed_tools: {
4790
+ mode: "validated",
4791
+ tools: [toolChoice.toolName]
4792
+ }
4793
+ };
4794
+ break;
4795
+ }
4796
+ }
4797
+ return {
4798
+ tools: interactionsTools.length > 0 ? interactionsTools : void 0,
4799
+ toolChoice: mappedToolChoice,
4800
+ toolWarnings
4801
+ };
4802
+ }
4803
+
4804
+ // src/interactions/synthesize-google-interactions-agent-stream.ts
4805
+ function synthesizeGoogleInteractionsAgentStream({
4806
+ response,
4807
+ warnings,
4808
+ generateId: generateId3,
4809
+ includeRawChunks,
4810
+ headerServiceTier
4811
+ }) {
4812
+ return new ReadableStream({
4813
+ start(controller) {
4814
+ var _a, _b, _c;
4815
+ controller.enqueue({ type: "stream-start", warnings });
4816
+ const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
4817
+ let timestamp;
4818
+ const created = response.created;
4819
+ if (typeof created === "string") {
4820
+ const parsed = new Date(created);
4821
+ if (!Number.isNaN(parsed.getTime())) {
4822
+ timestamp = parsed;
4823
+ }
4824
+ }
4825
+ controller.enqueue({
4826
+ type: "response-metadata",
4827
+ ...interactionId != null ? { id: interactionId } : {},
4828
+ modelId: (_a = response.model) != null ? _a : void 0,
4829
+ ...timestamp ? { timestamp } : {}
4830
+ });
4831
+ if (includeRawChunks) {
4832
+ controller.enqueue({ type: "raw", rawValue: response });
4833
+ }
4834
+ const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
4835
+ outputs: (_b = response.outputs) != null ? _b : null,
4836
+ generateId: generateId3,
4837
+ interactionId
4838
+ });
4839
+ let blockCounter = 0;
4840
+ const nextBlockId = () => `${interactionId != null ? interactionId : "agent"}:${blockCounter++}`;
4841
+ for (const part of content) {
4842
+ switch (part.type) {
4843
+ case "text": {
4844
+ const id = nextBlockId();
4845
+ const providerMetadata2 = part.providerMetadata;
4846
+ controller.enqueue({ type: "text-start", id });
4847
+ if (part.text.length > 0) {
4848
+ controller.enqueue({ type: "text-delta", id, delta: part.text });
4849
+ }
4850
+ controller.enqueue({
4851
+ type: "text-end",
4852
+ id,
4853
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
4854
+ });
4855
+ break;
4856
+ }
4857
+ case "reasoning": {
4858
+ const id = nextBlockId();
4859
+ const providerMetadata2 = part.providerMetadata;
4860
+ controller.enqueue({ type: "reasoning-start", id });
4861
+ if (part.text.length > 0) {
4862
+ controller.enqueue({
4863
+ type: "reasoning-delta",
4864
+ id,
4865
+ delta: part.text
4866
+ });
4867
+ }
4868
+ controller.enqueue({
4869
+ type: "reasoning-end",
4870
+ id,
4871
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
4872
+ });
4873
+ break;
4874
+ }
4875
+ case "tool-call": {
4876
+ const providerMetadata2 = part.providerMetadata;
4877
+ controller.enqueue({
4878
+ type: "tool-input-start",
4879
+ id: part.toolCallId,
4880
+ toolName: part.toolName,
4881
+ ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {}
4882
+ });
4883
+ controller.enqueue({
4884
+ type: "tool-input-delta",
4885
+ id: part.toolCallId,
4886
+ delta: part.input
4887
+ });
4888
+ controller.enqueue({
4889
+ type: "tool-input-end",
4890
+ id: part.toolCallId
4891
+ });
4892
+ controller.enqueue({
4893
+ type: "tool-call",
4894
+ toolCallId: part.toolCallId,
4895
+ toolName: part.toolName,
4896
+ input: part.input,
4897
+ ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {},
4898
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
4899
+ });
4900
+ break;
4901
+ }
4902
+ case "tool-result": {
4903
+ controller.enqueue({
4904
+ type: "tool-result",
4905
+ toolCallId: part.toolCallId,
4906
+ toolName: part.toolName,
4907
+ result: part.result
4908
+ });
4909
+ break;
4910
+ }
4911
+ case "source":
4912
+ case "file": {
4913
+ controller.enqueue(part);
4914
+ break;
4915
+ }
4916
+ default:
4917
+ break;
4918
+ }
4919
+ }
4920
+ const serviceTier = (_c = response.service_tier) != null ? _c : headerServiceTier;
4921
+ const finishReason = {
4922
+ unified: mapGoogleInteractionsFinishReason({
4923
+ status: response.status,
4924
+ hasFunctionCall
4925
+ }),
4926
+ raw: response.status
4927
+ };
4928
+ const providerMetadata = {
4929
+ google: {
4930
+ ...interactionId != null ? { interactionId } : {},
4931
+ ...serviceTier != null ? { serviceTier } : {}
4932
+ }
4933
+ };
4934
+ controller.enqueue({
4935
+ type: "finish",
4936
+ finishReason,
4937
+ usage: convertGoogleInteractionsUsage(response.usage),
4938
+ providerMetadata
4939
+ });
4940
+ controller.close();
4941
+ }
4942
+ });
4943
+ }
4944
+
4945
+ // src/interactions/google-interactions-language-model.ts
4946
+ var GoogleInteractionsLanguageModel = class {
4947
+ constructor(modelOrAgent, config) {
4948
+ this.specificationVersion = "v3";
4949
+ if (typeof modelOrAgent === "string") {
4950
+ this.modelId = modelOrAgent;
4951
+ this.agent = void 0;
4952
+ } else {
4953
+ this.modelId = modelOrAgent.agent;
4954
+ this.agent = modelOrAgent.agent;
4955
+ }
4956
+ this.config = config;
4957
+ }
4958
+ get provider() {
4959
+ return this.config.provider;
4960
+ }
4961
+ get supportedUrls() {
4962
+ if (this.config.supportedUrls) {
4963
+ return this.config.supportedUrls();
4964
+ }
4965
+ return {
4966
+ "image/*": [/^https?:\/\/.+/],
4967
+ "application/pdf": [/^https?:\/\/.+/],
4968
+ "audio/*": [/^https?:\/\/.+/],
4969
+ "video/*": [
4970
+ /^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,
4971
+ /^https?:\/\/youtu\.be\/.+/,
4972
+ /^gs:\/\/.+/
4973
+ ]
4974
+ };
4975
+ }
4976
+ async getArgs(options) {
4977
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
4978
+ const warnings = [];
4979
+ const opts = await (0, import_provider_utils20.parseProviderOptions)({
4980
+ provider: "google",
4981
+ providerOptions: options.providerOptions,
4982
+ schema: googleInteractionsLanguageModelOptions
4983
+ });
4984
+ const isAgent = this.agent != null;
4985
+ const hasTools = options.tools != null && options.tools.length > 0;
4986
+ let toolsForBody;
4987
+ let toolChoiceForBody;
4988
+ if (hasTools && isAgent) {
4989
+ warnings.push({
4990
+ type: "other",
4991
+ message: "google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body."
4992
+ });
4993
+ } else if (hasTools) {
4994
+ const prepared = prepareGoogleInteractionsTools({
4995
+ tools: options.tools,
4996
+ toolChoice: options.toolChoice
4997
+ });
4998
+ toolsForBody = prepared.tools;
4999
+ toolChoiceForBody = prepared.toolChoice;
5000
+ warnings.push(...prepared.toolWarnings);
5001
+ }
5002
+ let responseMimeType;
5003
+ let responseFormat;
5004
+ if (((_a = options.responseFormat) == null ? void 0 : _a.type) === "json") {
5005
+ if (isAgent) {
5006
+ warnings.push({
5007
+ type: "other",
5008
+ message: "google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."
5009
+ });
5010
+ } else {
5011
+ responseMimeType = "application/json";
5012
+ if (options.responseFormat.schema != null) {
5013
+ responseFormat = options.responseFormat.schema;
5014
+ }
5015
+ }
5016
+ }
5017
+ const {
5018
+ input,
5019
+ systemInstruction: convertedSystemInstruction,
5020
+ warnings: convWarnings
5021
+ } = convertToGoogleInteractionsInput({
5022
+ prompt: options.prompt,
5023
+ previousInteractionId: (_b = opts == null ? void 0 : opts.previousInteractionId) != null ? _b : void 0,
5024
+ store: (_c = opts == null ? void 0 : opts.store) != null ? _c : void 0,
5025
+ mediaResolution: (_d = opts == null ? void 0 : opts.mediaResolution) != null ? _d : void 0
5026
+ });
5027
+ warnings.push(...convWarnings);
5028
+ let systemInstruction = convertedSystemInstruction;
5029
+ const optionSystemInstruction = (_e = opts == null ? void 0 : opts.systemInstruction) != null ? _e : void 0;
5030
+ if (systemInstruction != null && optionSystemInstruction != null) {
5031
+ warnings.push({
5032
+ type: "other",
5033
+ message: "google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."
5034
+ });
5035
+ } else if (systemInstruction == null && optionSystemInstruction != null) {
5036
+ systemInstruction = optionSystemInstruction;
5037
+ }
5038
+ let generationConfig;
5039
+ if (isAgent) {
5040
+ const droppedFields = [];
5041
+ if (options.temperature != null) droppedFields.push("temperature");
5042
+ if (options.topP != null) droppedFields.push("topP");
5043
+ if (options.seed != null) droppedFields.push("seed");
5044
+ if (options.stopSequences != null && options.stopSequences.length > 0) {
5045
+ droppedFields.push("stopSequences");
5046
+ }
5047
+ if (options.maxOutputTokens != null)
5048
+ droppedFields.push("maxOutputTokens");
5049
+ if ((opts == null ? void 0 : opts.thinkingLevel) != null) droppedFields.push("thinkingLevel");
5050
+ if ((opts == null ? void 0 : opts.thinkingSummaries) != null) {
5051
+ droppedFields.push("thinkingSummaries");
5052
+ }
5053
+ if ((opts == null ? void 0 : opts.imageConfig) != null) droppedFields.push("imageConfig");
5054
+ if (droppedFields.length > 0) {
5055
+ warnings.push({
5056
+ type: "other",
5057
+ message: `google.interactions: ${droppedFields.join(", ")} ${droppedFields.length === 1 ? "is" : "are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`
5058
+ });
5059
+ }
5060
+ generationConfig = void 0;
5061
+ } else {
5062
+ generationConfig = pruneUndefined({
5063
+ temperature: (_f = options.temperature) != null ? _f : void 0,
5064
+ top_p: (_g = options.topP) != null ? _g : void 0,
5065
+ seed: (_h = options.seed) != null ? _h : void 0,
5066
+ stop_sequences: options.stopSequences != null && options.stopSequences.length > 0 ? options.stopSequences : void 0,
5067
+ max_output_tokens: (_i = options.maxOutputTokens) != null ? _i : void 0,
5068
+ thinking_level: (_j = opts == null ? void 0 : opts.thinkingLevel) != null ? _j : void 0,
5069
+ thinking_summaries: (_k = opts == null ? void 0 : opts.thinkingSummaries) != null ? _k : void 0,
5070
+ image_config: (opts == null ? void 0 : opts.imageConfig) != null ? pruneUndefined({
5071
+ aspect_ratio: (_l = opts.imageConfig.aspectRatio) != null ? _l : void 0,
5072
+ image_size: (_m = opts.imageConfig.imageSize) != null ? _m : void 0
5073
+ }) : void 0,
5074
+ tool_choice: toolChoiceForBody
5075
+ });
5076
+ }
5077
+ let agentConfig;
5078
+ if (isAgent && (opts == null ? void 0 : opts.agentConfig) != null) {
5079
+ const ac = opts.agentConfig;
5080
+ if (ac.type === "deep-research") {
5081
+ agentConfig = pruneUndefined({
5082
+ type: "deep-research",
5083
+ thinking_summaries: (_n = ac.thinkingSummaries) != null ? _n : void 0,
5084
+ visualization: (_o = ac.visualization) != null ? _o : void 0,
5085
+ collaborative_planning: (_p = ac.collaborativePlanning) != null ? _p : void 0
5086
+ });
5087
+ } else if (ac.type === "dynamic") {
5088
+ agentConfig = { type: "dynamic" };
5089
+ }
5090
+ }
5091
+ const args = pruneUndefined({
5092
+ ...isAgent ? { agent: this.agent } : { model: this.modelId },
5093
+ input,
5094
+ system_instruction: systemInstruction,
5095
+ tools: toolsForBody,
5096
+ response_format: responseFormat,
5097
+ response_mime_type: responseMimeType,
5098
+ response_modalities: (opts == null ? void 0 : opts.responseModalities) != null ? opts.responseModalities : void 0,
5099
+ previous_interaction_id: (_q = opts == null ? void 0 : opts.previousInteractionId) != null ? _q : void 0,
5100
+ service_tier: (_r = opts == null ? void 0 : opts.serviceTier) != null ? _r : void 0,
5101
+ store: (_s = opts == null ? void 0 : opts.store) != null ? _s : void 0,
5102
+ generation_config: generationConfig != null && Object.keys(generationConfig).length > 0 ? generationConfig : void 0,
5103
+ agent_config: agentConfig,
5104
+ ...isAgent ? { background: true } : {}
5105
+ });
5106
+ return {
5107
+ args,
5108
+ warnings,
5109
+ isAgent,
5110
+ pollingTimeoutMs: (_t = opts == null ? void 0 : opts.pollingTimeoutMs) != null ? _t : void 0
5111
+ };
5112
+ }
5113
+ async doGenerate(options) {
5114
+ var _a, _b, _c, _d, _e, _f;
5115
+ const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5116
+ const url = `${this.config.baseURL}/interactions`;
5117
+ const mergedHeaders = (0, import_provider_utils20.combineHeaders)(
5118
+ this.config.headers ? await (0, import_provider_utils20.resolve)(this.config.headers) : void 0,
5119
+ options.headers
5120
+ );
5121
+ const postResult = await (0, import_provider_utils20.postJsonToApi)({
5122
+ url,
5123
+ headers: mergedHeaders,
5124
+ body: args,
5125
+ failedResponseHandler: googleFailedResponseHandler,
5126
+ successfulResponseHandler: (0, import_provider_utils20.createJsonResponseHandler)(
5127
+ googleInteractionsResponseSchema
5128
+ ),
5129
+ abortSignal: options.abortSignal,
5130
+ fetch: this.config.fetch
5131
+ });
5132
+ let {
5133
+ responseHeaders,
5134
+ value: response,
5135
+ rawValue: rawResponse
5136
+ } = postResult;
5137
+ if (isAgent && !isTerminalStatus(response.status)) {
5138
+ const polled = await pollGoogleInteractionUntilTerminal({
5139
+ baseURL: this.config.baseURL,
5140
+ interactionId: response.id,
5141
+ headers: mergedHeaders,
5142
+ fetch: this.config.fetch,
5143
+ abortSignal: options.abortSignal,
5144
+ timeoutMs: pollingTimeoutMs
5145
+ });
5146
+ response = polled.response;
5147
+ rawResponse = polled.rawResponse;
5148
+ responseHeaders = (_a = polled.responseHeaders) != null ? _a : responseHeaders;
5149
+ }
5150
+ const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
5151
+ const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
5152
+ outputs: (_b = response.outputs) != null ? _b : null,
5153
+ generateId: (_c = this.config.generateId) != null ? _c : import_provider_utils20.generateId,
5154
+ interactionId
5155
+ });
5156
+ const finishReason = {
5157
+ unified: mapGoogleInteractionsFinishReason({
5158
+ status: response.status,
5159
+ hasFunctionCall
5160
+ }),
5161
+ raw: response.status
5162
+ };
5163
+ const serviceTier = (_e = (_d = response.service_tier) != null ? _d : responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"]) != null ? _e : void 0;
5164
+ const providerMetadata = {
5165
+ google: {
5166
+ ...interactionId != null ? { interactionId } : {},
5167
+ ...serviceTier != null ? { serviceTier } : {}
5168
+ }
5169
+ };
5170
+ let timestamp;
5171
+ if (typeof response.created === "string") {
5172
+ const parsed = new Date(response.created);
5173
+ if (!Number.isNaN(parsed.getTime())) {
5174
+ timestamp = parsed;
5175
+ }
5176
+ }
5177
+ return {
5178
+ content,
5179
+ finishReason,
5180
+ usage: convertGoogleInteractionsUsage(response.usage),
5181
+ warnings,
5182
+ providerMetadata,
5183
+ request: { body: args },
5184
+ response: {
5185
+ headers: responseHeaders,
5186
+ body: rawResponse,
5187
+ ...interactionId != null ? { id: interactionId } : {},
5188
+ ...timestamp ? { timestamp } : {},
5189
+ modelId: (_f = response.model) != null ? _f : void 0
5190
+ }
5191
+ };
5192
+ }
5193
+ async doStream(options) {
5194
+ var _a;
5195
+ const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5196
+ const url = `${this.config.baseURL}/interactions`;
5197
+ const mergedHeaders = (0, import_provider_utils20.combineHeaders)(
5198
+ this.config.headers ? await (0, import_provider_utils20.resolve)(this.config.headers) : void 0,
5199
+ options.headers
5200
+ );
5201
+ if (isAgent) {
5202
+ return this.doStreamAgent({
5203
+ args,
5204
+ warnings,
5205
+ url,
5206
+ mergedHeaders,
5207
+ options,
5208
+ pollingTimeoutMs
5209
+ });
5210
+ }
5211
+ const body = { ...args, stream: true };
5212
+ const { responseHeaders, value: response } = await (0, import_provider_utils20.postJsonToApi)({
5213
+ url,
5214
+ headers: mergedHeaders,
5215
+ body,
5216
+ failedResponseHandler: googleFailedResponseHandler,
5217
+ successfulResponseHandler: (0, import_provider_utils20.createEventSourceResponseHandler)(
5218
+ googleInteractionsEventSchema
5219
+ ),
5220
+ abortSignal: options.abortSignal,
5221
+ fetch: this.config.fetch
5222
+ });
5223
+ const headerServiceTier = responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"];
5224
+ const transform = buildGoogleInteractionsStreamTransform({
5225
+ warnings,
5226
+ generateId: (_a = this.config.generateId) != null ? _a : import_provider_utils20.generateId,
5227
+ includeRawChunks: options.includeRawChunks,
5228
+ serviceTier: headerServiceTier
5229
+ });
5230
+ return {
5231
+ stream: response.pipeThrough(transform),
5232
+ request: { body },
5233
+ response: { headers: responseHeaders }
5234
+ };
5235
+ }
5236
+ /*
5237
+ * Drive the streaming surface for agent calls. Agent calls require
5238
+ * `background: true`, which is incompatible with `stream: true` on POST.
5239
+ *
5240
+ * In principle the API also exposes `GET /interactions/{id}?stream=true`
5241
+ * to replay events as the agent runs. In practice the connection is
5242
+ * idle for long stretches while the agent thinks (deep-research can run
5243
+ * for a minute or more between SSE events), and undici's default body
5244
+ * timeout terminates the request mid-flight with `UND_ERR_BODY_TIMEOUT`.
5245
+ * Tuning the timeout per-call would require the caller to thread an
5246
+ * `undici.Agent` through `fetch`, which contradicts the AI SDK's
5247
+ * pluggable-fetch contract.
5248
+ *
5249
+ * We therefore drive `doStream` exactly like `doGenerate` for agents:
5250
+ * POST with `background: true`, poll `GET /interactions/{id}` until
5251
+ * terminal, then synthesize the stream from the final outputs. The
5252
+ * user-facing surface stays identical -- text-start / text-delta /
5253
+ * text-end / finish parts arrive in the same order as a true SSE
5254
+ * response, just buffered until the agent completes.
5255
+ */
5256
+ async doStreamAgent({
5257
+ args,
5258
+ warnings,
5259
+ url,
5260
+ mergedHeaders,
5261
+ options,
5262
+ pollingTimeoutMs
5263
+ }) {
5264
+ var _a, _b;
5265
+ const postResult = await (0, import_provider_utils20.postJsonToApi)({
5266
+ url,
5267
+ headers: mergedHeaders,
5268
+ body: args,
5269
+ failedResponseHandler: googleFailedResponseHandler,
5270
+ successfulResponseHandler: (0, import_provider_utils20.createJsonResponseHandler)(
5271
+ googleInteractionsResponseSchema
5272
+ ),
5273
+ abortSignal: options.abortSignal,
5274
+ fetch: this.config.fetch
5275
+ });
5276
+ let { responseHeaders: postHeaders, value: postResponse } = postResult;
5277
+ const interactionId = postResponse.id;
5278
+ if (interactionId == null || interactionId.length === 0) {
5279
+ throw new Error(
5280
+ "google.interactions: agent POST response did not include an interaction id; cannot poll for the agent result."
5281
+ );
5282
+ }
5283
+ if (!isTerminalStatus(postResponse.status)) {
5284
+ const polled = await pollGoogleInteractionUntilTerminal({
5285
+ baseURL: this.config.baseURL,
5286
+ interactionId,
5287
+ headers: mergedHeaders,
5288
+ fetch: this.config.fetch,
5289
+ abortSignal: options.abortSignal,
5290
+ timeoutMs: pollingTimeoutMs
5291
+ });
5292
+ postResponse = polled.response;
5293
+ postHeaders = (_a = polled.responseHeaders) != null ? _a : postHeaders;
5294
+ }
5295
+ const stream = synthesizeGoogleInteractionsAgentStream({
5296
+ response: postResponse,
5297
+ warnings,
5298
+ generateId: (_b = this.config.generateId) != null ? _b : import_provider_utils20.generateId,
5299
+ includeRawChunks: options.includeRawChunks,
5300
+ headerServiceTier: postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"]
5301
+ });
5302
+ return {
5303
+ stream,
5304
+ request: { body: args },
5305
+ response: { headers: postHeaders }
5306
+ };
5307
+ }
5308
+ };
5309
+ function pruneUndefined(obj) {
5310
+ const result = {};
5311
+ for (const [key, value] of Object.entries(obj)) {
5312
+ if (value === void 0) continue;
5313
+ result[key] = value;
5314
+ }
5315
+ return result;
5316
+ }
5317
+
5318
+ // src/google-provider.ts
5319
+ function createGoogleGenerativeAI(options = {}) {
5320
+ var _a, _b;
5321
+ const baseURL = (_a = (0, import_provider_utils21.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
5322
+ const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
5323
+ const getHeaders = () => (0, import_provider_utils21.withUserAgentSuffix)(
5324
+ {
5325
+ "x-goog-api-key": (0, import_provider_utils21.loadApiKey)({
5326
+ apiKey: options.apiKey,
5327
+ environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
5328
+ description: "Google Generative AI"
5329
+ }),
5330
+ ...options.headers
5331
+ },
5332
+ `ai-sdk/google/${VERSION}`
5333
+ );
5334
+ const createChatModel = (modelId) => {
5335
+ var _a2;
5336
+ return new GoogleGenerativeAILanguageModel(modelId, {
5337
+ provider: providerName,
5338
+ baseURL,
5339
+ headers: getHeaders,
5340
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils21.generateId,
5341
+ supportedUrls: () => ({
5342
+ "*": [
5343
+ // Google Generative Language "files" endpoint
5344
+ // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
5345
+ new RegExp(`^${baseURL}/files/.*$`),
5346
+ // YouTube URLs (public or unlisted videos)
5347
+ new RegExp(
5348
+ `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
5349
+ ),
5350
+ new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
5351
+ ]
5352
+ }),
5353
+ fetch: options.fetch
5354
+ });
5355
+ };
5356
+ const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
5357
+ provider: providerName,
5358
+ baseURL,
5359
+ headers: getHeaders,
5360
+ fetch: options.fetch
5361
+ });
5362
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
5363
+ provider: providerName,
5364
+ baseURL,
5365
+ headers: getHeaders,
5366
+ fetch: options.fetch
3047
5367
  });
3048
5368
  const createVideoModel = (modelId) => {
3049
5369
  var _a2;
@@ -3052,9 +5372,22 @@ function createGoogleGenerativeAI(options = {}) {
3052
5372
  baseURL,
3053
5373
  headers: getHeaders,
3054
5374
  fetch: options.fetch,
3055
- generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils16.generateId
5375
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils21.generateId
3056
5376
  });
3057
5377
  };
5378
+ const createInteractionsModel = (modelIdOrAgent) => {
5379
+ var _a2;
5380
+ return new GoogleInteractionsLanguageModel(
5381
+ modelIdOrAgent,
5382
+ {
5383
+ provider: `${providerName}.interactions`,
5384
+ baseURL,
5385
+ headers: getHeaders,
5386
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils21.generateId,
5387
+ fetch: options.fetch
5388
+ }
5389
+ );
5390
+ };
3058
5391
  const provider = function(modelId) {
3059
5392
  if (new.target) {
3060
5393
  throw new Error(
@@ -3075,6 +5408,7 @@ function createGoogleGenerativeAI(options = {}) {
3075
5408
  provider.imageModel = createImageModel;
3076
5409
  provider.video = createVideoModel;
3077
5410
  provider.videoModel = createVideoModel;
5411
+ provider.interactions = createInteractionsModel;
3078
5412
  provider.tools = googleTools;
3079
5413
  return provider;
3080
5414
  }