@ai-sdk/google 3.0.67 → 3.0.70

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