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