@ai-sdk/google 4.0.5 → 4.0.7

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.
@@ -182,7 +182,8 @@ import {
182
182
  getTopLevelMediaType,
183
183
  isFullMediaType,
184
184
  resolveFullMediaType,
185
- resolveProviderReference
185
+ resolveProviderReference,
186
+ secureJsonParse
186
187
  } from "@ai-sdk/provider-utils";
187
188
  var SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator";
188
189
  var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s;
@@ -500,7 +501,7 @@ function convertToGoogleMessages(prompt, options) {
500
501
  return {
501
502
  toolCall: {
502
503
  toolType: serverToolType,
503
- args: typeof part.input === "string" ? JSON.parse(part.input) : part.input,
504
+ args: typeof part.input === "string" ? secureJsonParse(part.input) : part.input,
504
505
  id: serverToolCallId
505
506
  },
506
507
  thoughtSignature: effectiveThoughtSignature
@@ -2890,7 +2891,2920 @@ var googleTools = {
2890
2891
  */
2891
2892
  vertexRagStore
2892
2893
  };
2894
+
2895
+ // src/interactions/google-interactions-language-model.ts
2896
+ import {
2897
+ combineHeaders as combineHeaders4,
2898
+ createEventSourceResponseHandler as createEventSourceResponseHandler3,
2899
+ createJsonResponseHandler as createJsonResponseHandler4,
2900
+ generateId as defaultGenerateId,
2901
+ parseProviderOptions as parseProviderOptions3,
2902
+ postJsonToApi as postJsonToApi3,
2903
+ resolve as resolve3,
2904
+ serializeModelOptions as serializeModelOptions3,
2905
+ WORKFLOW_DESERIALIZE as WORKFLOW_DESERIALIZE3,
2906
+ WORKFLOW_SERIALIZE as WORKFLOW_SERIALIZE3
2907
+ } from "@ai-sdk/provider-utils";
2908
+
2909
+ // src/interactions/convert-google-interactions-usage.ts
2910
+ function convertGoogleInteractionsUsage(usage) {
2911
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2912
+ if (usage == null) {
2913
+ return {
2914
+ inputTokens: {
2915
+ total: void 0,
2916
+ noCache: void 0,
2917
+ cacheRead: void 0,
2918
+ cacheWrite: void 0
2919
+ },
2920
+ outputTokens: {
2921
+ total: void 0,
2922
+ text: void 0,
2923
+ reasoning: void 0
2924
+ },
2925
+ raw: void 0
2926
+ };
2927
+ }
2928
+ const totalInput = (_a = usage.total_input_tokens) != null ? _a : 0;
2929
+ const totalOutput = (_b = usage.total_output_tokens) != null ? _b : 0;
2930
+ const totalThought = (_c = usage.total_thought_tokens) != null ? _c : 0;
2931
+ const totalCached = (_d = usage.total_cached_tokens) != null ? _d : 0;
2932
+ return {
2933
+ inputTokens: {
2934
+ total: (_e = usage.total_input_tokens) != null ? _e : void 0,
2935
+ noCache: usage.total_input_tokens == null ? void 0 : totalInput - totalCached,
2936
+ cacheRead: (_f = usage.total_cached_tokens) != null ? _f : void 0,
2937
+ cacheWrite: void 0
2938
+ },
2939
+ outputTokens: {
2940
+ total: usage.total_output_tokens == null && usage.total_thought_tokens == null ? void 0 : totalOutput + totalThought,
2941
+ text: (_g = usage.total_output_tokens) != null ? _g : void 0,
2942
+ reasoning: (_h = usage.total_thought_tokens) != null ? _h : void 0
2943
+ },
2944
+ raw: usage
2945
+ };
2946
+ }
2947
+ function getGoogleInteractionsOutputTokensByModality(usage) {
2948
+ const byModality = usage == null ? void 0 : usage.output_tokens_by_modality;
2949
+ if (byModality == null) {
2950
+ return void 0;
2951
+ }
2952
+ const result = {};
2953
+ for (const entry of byModality) {
2954
+ if ((entry == null ? void 0 : entry.modality) != null && entry.tokens != null) {
2955
+ result[entry.modality] = entry.tokens;
2956
+ }
2957
+ }
2958
+ return Object.keys(result).length > 0 ? result : void 0;
2959
+ }
2960
+
2961
+ // src/interactions/extract-google-interactions-sources.ts
2962
+ var KNOWN_DOC_EXTENSIONS = {
2963
+ pdf: "application/pdf",
2964
+ txt: "text/plain",
2965
+ md: "text/markdown",
2966
+ markdown: "text/markdown",
2967
+ doc: "application/msword",
2968
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
2969
+ };
2970
+ function inferDocMediaType(uriOrName) {
2971
+ const lower = uriOrName.toLowerCase();
2972
+ for (const [ext, media] of Object.entries(KNOWN_DOC_EXTENSIONS)) {
2973
+ if (lower.endsWith(`.${ext}`)) return media;
2974
+ }
2975
+ return "application/octet-stream";
2976
+ }
2977
+ function basename(uriOrName) {
2978
+ const parts = uriOrName.split("/");
2979
+ const last = parts[parts.length - 1];
2980
+ return last && last.length > 0 ? last : void 0;
2981
+ }
2982
+ function annotationToSource({
2983
+ annotation,
2984
+ generateId: generateId2
2985
+ }) {
2986
+ var _a, _b, _c, _d, _e;
2987
+ switch (annotation.type) {
2988
+ case "url_citation": {
2989
+ const urlCitation = annotation;
2990
+ if (urlCitation.url == null || urlCitation.url.length === 0) {
2991
+ return void 0;
2992
+ }
2993
+ return {
2994
+ type: "source",
2995
+ sourceType: "url",
2996
+ id: generateId2(),
2997
+ url: urlCitation.url,
2998
+ ...urlCitation.title != null ? { title: urlCitation.title } : {}
2999
+ };
3000
+ }
3001
+ case "file_citation": {
3002
+ const fileCitation = annotation;
3003
+ const uri = (_b = (_a = fileCitation.url) != null ? _a : fileCitation.document_uri) != null ? _b : fileCitation.file_name;
3004
+ if (uri == null || uri.length === 0) return void 0;
3005
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
3006
+ return {
3007
+ type: "source",
3008
+ sourceType: "url",
3009
+ id: generateId2(),
3010
+ url: uri,
3011
+ ...fileCitation.file_name != null ? { title: fileCitation.file_name } : {}
3012
+ };
3013
+ }
3014
+ const filename = (_c = fileCitation.file_name) != null ? _c : basename(uri);
3015
+ const mediaType = inferDocMediaType(uri);
3016
+ return {
3017
+ type: "source",
3018
+ sourceType: "document",
3019
+ id: generateId2(),
3020
+ mediaType,
3021
+ title: (_e = (_d = fileCitation.file_name) != null ? _d : filename) != null ? _e : uri,
3022
+ ...filename != null ? { filename } : {}
3023
+ };
3024
+ }
3025
+ case "place_citation": {
3026
+ const placeCitation = annotation;
3027
+ if (placeCitation.url == null || placeCitation.url.length === 0) {
3028
+ return void 0;
3029
+ }
3030
+ return {
3031
+ type: "source",
3032
+ sourceType: "url",
3033
+ id: generateId2(),
3034
+ url: placeCitation.url,
3035
+ ...placeCitation.name != null ? { title: placeCitation.name } : {}
3036
+ };
3037
+ }
3038
+ default:
3039
+ return void 0;
3040
+ }
3041
+ }
3042
+ function builtinToolResultToSources({
3043
+ block,
3044
+ generateId: generateId2
3045
+ }) {
3046
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
3047
+ const sources = [];
3048
+ switch (block.type) {
3049
+ case "url_context_result": {
3050
+ const result = (_a = block.result) != null ? _a : [];
3051
+ for (const entry of result) {
3052
+ if ((entry == null ? void 0 : entry.url) == null || entry.url.length === 0) continue;
3053
+ if (entry.status != null && entry.status !== "success") continue;
3054
+ sources.push({
3055
+ type: "source",
3056
+ sourceType: "url",
3057
+ id: generateId2(),
3058
+ url: entry.url
3059
+ });
3060
+ }
3061
+ break;
3062
+ }
3063
+ case "google_search_result": {
3064
+ const result = (_b = block.result) != null ? _b : [];
3065
+ for (const entry of result) {
3066
+ const url = entry == null ? void 0 : entry.url;
3067
+ if (url == null || url.length === 0) continue;
3068
+ sources.push({
3069
+ type: "source",
3070
+ sourceType: "url",
3071
+ id: generateId2(),
3072
+ url,
3073
+ ...entry.title != null ? { title: entry.title } : {}
3074
+ });
3075
+ }
3076
+ break;
3077
+ }
3078
+ case "google_maps_result": {
3079
+ const result = (_c = block.result) != null ? _c : [];
3080
+ for (const entry of result) {
3081
+ for (const place of (_d = entry.places) != null ? _d : []) {
3082
+ if (place.url == null || place.url.length === 0) continue;
3083
+ sources.push({
3084
+ type: "source",
3085
+ sourceType: "url",
3086
+ id: generateId2(),
3087
+ url: place.url,
3088
+ ...place.name != null ? { title: place.name } : {}
3089
+ });
3090
+ }
3091
+ }
3092
+ break;
3093
+ }
3094
+ case "file_search_result": {
3095
+ const result = (_e = block.result) != null ? _e : [];
3096
+ for (const raw of result) {
3097
+ if (raw == null || typeof raw !== "object") continue;
3098
+ const entry = raw;
3099
+ const uri = (_g = (_f = entry.url) != null ? _f : entry.document_uri) != null ? _g : entry.file_name;
3100
+ if (uri == null || uri.length === 0) continue;
3101
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
3102
+ sources.push({
3103
+ type: "source",
3104
+ sourceType: "url",
3105
+ id: generateId2(),
3106
+ url: uri,
3107
+ ...entry.title != null ? { title: entry.title } : {}
3108
+ });
3109
+ continue;
3110
+ }
3111
+ const filename = (_h = entry.file_name) != null ? _h : basename(uri);
3112
+ const mediaType = inferDocMediaType(uri);
3113
+ sources.push({
3114
+ type: "source",
3115
+ sourceType: "document",
3116
+ id: generateId2(),
3117
+ mediaType,
3118
+ title: (_k = (_j = (_i = entry.title) != null ? _i : entry.file_name) != null ? _j : filename) != null ? _k : uri,
3119
+ ...filename != null ? { filename } : {}
3120
+ });
3121
+ }
3122
+ break;
3123
+ }
3124
+ default:
3125
+ break;
3126
+ }
3127
+ return sources;
3128
+ }
3129
+ function annotationsToSources({
3130
+ annotations,
3131
+ generateId: generateId2
3132
+ }) {
3133
+ var _a;
3134
+ if (annotations == null) return [];
3135
+ const seen = /* @__PURE__ */ new Set();
3136
+ const sources = [];
3137
+ for (const annotation of annotations) {
3138
+ const source = annotationToSource({ annotation, generateId: generateId2 });
3139
+ if (source == null) continue;
3140
+ const key = source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a = source.filename) != null ? _a : source.title}`;
3141
+ if (seen.has(key)) continue;
3142
+ seen.add(key);
3143
+ sources.push(source);
3144
+ }
3145
+ return sources;
3146
+ }
3147
+
3148
+ // src/interactions/map-google-interactions-finish-reason.ts
3149
+ function mapGoogleInteractionsFinishReason({
3150
+ status,
3151
+ hasFunctionCall
3152
+ }) {
3153
+ switch (status) {
3154
+ case "completed":
3155
+ return hasFunctionCall ? "tool-calls" : "stop";
3156
+ case "requires_action":
3157
+ return "tool-calls";
3158
+ case "failed":
3159
+ return "error";
3160
+ case "incomplete":
3161
+ return "length";
3162
+ case "cancelled":
3163
+ return "other";
3164
+ case "in_progress":
3165
+ default:
3166
+ return "other";
3167
+ }
3168
+ }
3169
+
3170
+ // src/interactions/build-google-interactions-stream-transform.ts
3171
+ var BUILTIN_TOOL_CALL_TYPES = /* @__PURE__ */ new Set([
3172
+ "google_search_call",
3173
+ "code_execution_call",
3174
+ "url_context_call",
3175
+ "file_search_call",
3176
+ "google_maps_call",
3177
+ "mcp_server_tool_call"
3178
+ ]);
3179
+ var BUILTIN_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([
3180
+ "google_search_result",
3181
+ "code_execution_result",
3182
+ "url_context_result",
3183
+ "file_search_result",
3184
+ "google_maps_result",
3185
+ "mcp_server_tool_result"
3186
+ ]);
3187
+ function builtinToolNameFromCallType(type) {
3188
+ return type.replace(/_call$/, "");
3189
+ }
3190
+ function builtinToolNameFromResultType(type) {
3191
+ return type.replace(/_result$/, "");
3192
+ }
3193
+ function buildGoogleInteractionsStreamTransform({
3194
+ warnings,
3195
+ generateId: generateId2,
3196
+ includeRawChunks,
3197
+ serviceTier: headerServiceTier
3198
+ }) {
3199
+ let interactionId;
3200
+ let usage;
3201
+ let serviceTier = headerServiceTier;
3202
+ let finishStatus;
3203
+ let hasFunctionCall = false;
3204
+ const openBlocks = /* @__PURE__ */ new Map();
3205
+ const emittedSourceKeys = /* @__PURE__ */ new Set();
3206
+ function sourceKey(source) {
3207
+ var _a;
3208
+ return source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a = source.filename) != null ? _a : source.title}`;
3209
+ }
3210
+ return new TransformStream({
3211
+ start(controller) {
3212
+ controller.enqueue({ type: "stream-start", warnings });
3213
+ },
3214
+ transform(chunk, controller) {
3215
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
3216
+ if (includeRawChunks) {
3217
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3218
+ }
3219
+ if (!chunk.success) {
3220
+ finishStatus = "failed";
3221
+ controller.enqueue({ type: "error", error: chunk.error });
3222
+ return;
3223
+ }
3224
+ const value = chunk.value;
3225
+ const eventType = value.event_type;
3226
+ switch (eventType) {
3227
+ case "interaction.created": {
3228
+ const event = value;
3229
+ const interaction = event.interaction;
3230
+ interactionId = (interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0 ? interaction.id : void 0;
3231
+ const created = interaction == null ? void 0 : interaction.created;
3232
+ let timestamp;
3233
+ if (typeof created === "string") {
3234
+ const parsed = new Date(created);
3235
+ if (!Number.isNaN(parsed.getTime())) {
3236
+ timestamp = parsed;
3237
+ }
3238
+ }
3239
+ controller.enqueue({
3240
+ type: "response-metadata",
3241
+ ...interactionId != null ? { id: interactionId } : {},
3242
+ modelId: interaction == null ? void 0 : interaction.model,
3243
+ ...timestamp ? { timestamp } : {}
3244
+ });
3245
+ break;
3246
+ }
3247
+ case "step.start": {
3248
+ const event = value;
3249
+ const step = event.step;
3250
+ const index = event.index;
3251
+ const blockId = `${interactionId != null ? interactionId : "interaction"}:${index}`;
3252
+ const stepType = step == null ? void 0 : step.type;
3253
+ if (stepType === "model_output") {
3254
+ const initial = (_a = step == null ? void 0 : step.content) == null ? void 0 : _a[0];
3255
+ if ((initial == null ? void 0 : initial.type) === "text") {
3256
+ openBlocks.set(index, {
3257
+ kind: "text",
3258
+ id: blockId,
3259
+ emittedSourceKeys: /* @__PURE__ */ new Set()
3260
+ });
3261
+ controller.enqueue({ type: "text-start", id: blockId });
3262
+ const initialSources = annotationsToSources({
3263
+ annotations: initial.annotations,
3264
+ generateId: generateId2
3265
+ });
3266
+ for (const source of initialSources) {
3267
+ const key = sourceKey(source);
3268
+ if (emittedSourceKeys.has(key)) continue;
3269
+ emittedSourceKeys.add(key);
3270
+ controller.enqueue(source);
3271
+ }
3272
+ } else if ((initial == null ? void 0 : initial.type) === "image") {
3273
+ openBlocks.set(index, {
3274
+ kind: "image",
3275
+ id: blockId,
3276
+ ...initial.data != null ? { data: initial.data } : {},
3277
+ ...initial.mime_type != null ? { mimeType: initial.mime_type } : {},
3278
+ ...initial.uri != null ? { uri: initial.uri } : {}
3279
+ });
3280
+ } else {
3281
+ openBlocks.set(index, {
3282
+ kind: "pending_model_output",
3283
+ id: blockId
3284
+ });
3285
+ }
3286
+ } else if (stepType === "thought") {
3287
+ const signature = step == null ? void 0 : step.signature;
3288
+ openBlocks.set(index, {
3289
+ kind: "reasoning",
3290
+ id: blockId,
3291
+ ...signature != null ? { signature } : {}
3292
+ });
3293
+ controller.enqueue({ type: "reasoning-start", id: blockId });
3294
+ if (Array.isArray(step == null ? void 0 : step.summary)) {
3295
+ for (const item of step.summary) {
3296
+ if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") {
3297
+ controller.enqueue({
3298
+ type: "reasoning-delta",
3299
+ id: blockId,
3300
+ delta: item.text
3301
+ });
3302
+ }
3303
+ }
3304
+ }
3305
+ } else if (stepType === "function_call") {
3306
+ const toolCallId = (_b = step == null ? void 0 : step.id) != null ? _b : blockId;
3307
+ const toolName = (_c = step == null ? void 0 : step.name) != null ? _c : "unknown";
3308
+ hasFunctionCall = true;
3309
+ const state = {
3310
+ kind: "function_call",
3311
+ id: blockId,
3312
+ toolCallId,
3313
+ toolName,
3314
+ argumentsAccum: "",
3315
+ ...(step == null ? void 0 : step.signature) != null ? { signature: step.signature } : {}
3316
+ };
3317
+ openBlocks.set(index, state);
3318
+ controller.enqueue({
3319
+ type: "tool-input-start",
3320
+ id: toolCallId,
3321
+ toolName
3322
+ });
3323
+ } else if (stepType != null && BUILTIN_TOOL_CALL_TYPES.has(stepType)) {
3324
+ const toolName = stepType === "mcp_server_tool_call" ? (_d = step == null ? void 0 : step.name) != null ? _d : "mcp_server_tool" : builtinToolNameFromCallType(stepType);
3325
+ const toolCallId = (_e = step == null ? void 0 : step.id) != null ? _e : blockId;
3326
+ const state = {
3327
+ kind: "builtin_tool_call",
3328
+ id: blockId,
3329
+ blockType: stepType,
3330
+ toolCallId,
3331
+ toolName,
3332
+ arguments: (_f = step == null ? void 0 : step.arguments) != null ? _f : {},
3333
+ callEmitted: false
3334
+ };
3335
+ openBlocks.set(index, state);
3336
+ } else if (stepType != null && BUILTIN_TOOL_RESULT_TYPES.has(stepType)) {
3337
+ const toolName = stepType === "mcp_server_tool_result" ? (_g = step == null ? void 0 : step.name) != null ? _g : "mcp_server_tool" : builtinToolNameFromResultType(stepType);
3338
+ const callId = (_h = step == null ? void 0 : step.call_id) != null ? _h : blockId;
3339
+ const state = {
3340
+ kind: "builtin_tool_result",
3341
+ id: blockId,
3342
+ blockType: stepType,
3343
+ callId,
3344
+ toolName,
3345
+ result: (_i = step == null ? void 0 : step.result) != null ? _i : null,
3346
+ ...(step == null ? void 0 : step.is_error) != null ? { isError: step.is_error } : {},
3347
+ resultEmitted: false
3348
+ };
3349
+ openBlocks.set(index, state);
3350
+ } else {
3351
+ openBlocks.set(index, { kind: "unknown", id: blockId });
3352
+ }
3353
+ break;
3354
+ }
3355
+ case "step.delta": {
3356
+ const event = value;
3357
+ let open = openBlocks.get(event.index);
3358
+ if (open == null) break;
3359
+ const dtype = (_j = event.delta) == null ? void 0 : _j.type;
3360
+ if (open.kind === "pending_model_output") {
3361
+ if (dtype === "text" || dtype === "text_annotation" || dtype === "text_annotation_delta") {
3362
+ const promoted = {
3363
+ kind: "text",
3364
+ id: open.id,
3365
+ emittedSourceKeys: /* @__PURE__ */ new Set()
3366
+ };
3367
+ openBlocks.set(event.index, promoted);
3368
+ open = promoted;
3369
+ controller.enqueue({ type: "text-start", id: promoted.id });
3370
+ }
3371
+ }
3372
+ if (dtype === "image" && (open.kind === "pending_model_output" || open.kind === "text" || open.kind === "image")) {
3373
+ const imageDelta = event.delta;
3374
+ const google = {};
3375
+ if (interactionId != null) google.interactionId = interactionId;
3376
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3377
+ if ((imageDelta == null ? void 0 : imageDelta.data) != null && imageDelta.data.length > 0) {
3378
+ controller.enqueue({
3379
+ type: "file",
3380
+ mediaType: (_k = imageDelta.mime_type) != null ? _k : "image/png",
3381
+ data: { type: "data", data: imageDelta.data },
3382
+ ...providerMetadata ? { providerMetadata } : {}
3383
+ });
3384
+ } else if ((imageDelta == null ? void 0 : imageDelta.uri) != null && imageDelta.uri.length > 0) {
3385
+ controller.enqueue({
3386
+ type: "file",
3387
+ mediaType: (_l = imageDelta.mime_type) != null ? _l : "image/png",
3388
+ data: { type: "url", url: new URL(imageDelta.uri) },
3389
+ ...providerMetadata ? { providerMetadata } : {}
3390
+ });
3391
+ }
3392
+ if (open.kind === "image") {
3393
+ open.data = void 0;
3394
+ open.uri = void 0;
3395
+ }
3396
+ break;
3397
+ }
3398
+ if (dtype === "video" && (open.kind === "pending_model_output" || open.kind === "text")) {
3399
+ const videoDelta = event.delta;
3400
+ const google = {};
3401
+ if (interactionId != null) google.interactionId = interactionId;
3402
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3403
+ if ((videoDelta == null ? void 0 : videoDelta.data) != null && videoDelta.data.length > 0) {
3404
+ controller.enqueue({
3405
+ type: "file",
3406
+ mediaType: (_m = videoDelta.mime_type) != null ? _m : "video/mp4",
3407
+ data: { type: "data", data: videoDelta.data },
3408
+ ...providerMetadata ? { providerMetadata } : {}
3409
+ });
3410
+ } else if ((videoDelta == null ? void 0 : videoDelta.uri) != null && videoDelta.uri.length > 0) {
3411
+ controller.enqueue({
3412
+ type: "file",
3413
+ mediaType: (_n = videoDelta.mime_type) != null ? _n : "video/mp4",
3414
+ data: { type: "url", url: new URL(videoDelta.uri) },
3415
+ ...providerMetadata ? { providerMetadata } : {}
3416
+ });
3417
+ }
3418
+ break;
3419
+ }
3420
+ const delta = event.delta;
3421
+ if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text") {
3422
+ const text = (_o = delta.text) != null ? _o : "";
3423
+ if (text.length > 0) {
3424
+ controller.enqueue({
3425
+ type: "text-delta",
3426
+ id: open.id,
3427
+ delta: text
3428
+ });
3429
+ }
3430
+ } else if (open.kind === "text" && ((delta == null ? void 0 : delta.type) === "text_annotation" || (delta == null ? void 0 : delta.type) === "text_annotation_delta")) {
3431
+ const sources = annotationsToSources({
3432
+ annotations: delta.annotations,
3433
+ generateId: generateId2
3434
+ });
3435
+ for (const source of sources) {
3436
+ const key = sourceKey(source);
3437
+ if (emittedSourceKeys.has(key)) continue;
3438
+ emittedSourceKeys.add(key);
3439
+ open.emittedSourceKeys.add(key);
3440
+ controller.enqueue(source);
3441
+ }
3442
+ } else if (open.kind === "image" && (delta == null ? void 0 : delta.type) === "image") {
3443
+ if (delta.data != null) open.data = delta.data;
3444
+ if (delta.mime_type != null) open.mimeType = delta.mime_type;
3445
+ if (delta.uri != null) open.uri = delta.uri;
3446
+ } else if (open.kind === "reasoning") {
3447
+ if ((delta == null ? void 0 : delta.type) === "thought_summary") {
3448
+ const item = delta.content;
3449
+ if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") {
3450
+ controller.enqueue({
3451
+ type: "reasoning-delta",
3452
+ id: open.id,
3453
+ delta: item.text
3454
+ });
3455
+ }
3456
+ } else if ((delta == null ? void 0 : delta.type) === "thought_signature") {
3457
+ const signature = delta.signature;
3458
+ if (signature != null) {
3459
+ open.signature = signature;
3460
+ }
3461
+ }
3462
+ } else if (open.kind === "function_call" && (delta == null ? void 0 : delta.type) === "arguments_delta") {
3463
+ const slice = typeof delta.arguments === "string" ? delta.arguments : "";
3464
+ if (slice.length > 0) {
3465
+ open.argumentsAccum += slice;
3466
+ controller.enqueue({
3467
+ type: "tool-input-delta",
3468
+ id: open.toolCallId,
3469
+ delta: slice
3470
+ });
3471
+ }
3472
+ if (delta.id != null) {
3473
+ open.toolCallId = delta.id;
3474
+ }
3475
+ if (delta.signature != null) {
3476
+ open.signature = delta.signature;
3477
+ }
3478
+ hasFunctionCall = true;
3479
+ } else if (open.kind === "builtin_tool_call" && (delta == null ? void 0 : delta.type) === open.blockType) {
3480
+ if (delta.id != null) open.toolCallId = delta.id;
3481
+ if (delta.arguments != null && typeof delta.arguments === "object") {
3482
+ open.arguments = delta.arguments;
3483
+ }
3484
+ if (delta.name != null && open.blockType === "mcp_server_tool_call") {
3485
+ open.toolName = delta.name;
3486
+ }
3487
+ } else if (open.kind === "builtin_tool_result" && (delta == null ? void 0 : delta.type) === open.blockType) {
3488
+ if (delta.call_id != null) open.callId = delta.call_id;
3489
+ if (delta.result !== void 0) open.result = delta.result;
3490
+ if (delta.is_error != null) open.isError = delta.is_error;
3491
+ if (delta.name != null && open.blockType === "mcp_server_tool_result") {
3492
+ open.toolName = delta.name;
3493
+ }
3494
+ }
3495
+ break;
3496
+ }
3497
+ case "step.stop": {
3498
+ const event = value;
3499
+ const open = openBlocks.get(event.index);
3500
+ if (open == null) break;
3501
+ if (open.kind === "text") {
3502
+ const textProviderMetadata = interactionId != null ? { google: { interactionId } } : void 0;
3503
+ controller.enqueue({
3504
+ type: "text-end",
3505
+ id: open.id,
3506
+ ...textProviderMetadata ? { providerMetadata: textProviderMetadata } : {}
3507
+ });
3508
+ } else if (open.kind === "reasoning") {
3509
+ const google = {};
3510
+ if (open.signature != null) google.signature = open.signature;
3511
+ if (interactionId != null) google.interactionId = interactionId;
3512
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3513
+ controller.enqueue({
3514
+ type: "reasoning-end",
3515
+ id: open.id,
3516
+ ...providerMetadata ? { providerMetadata } : {}
3517
+ });
3518
+ } else if (open.kind === "image") {
3519
+ const google = {};
3520
+ if (interactionId != null) google.interactionId = interactionId;
3521
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3522
+ if (open.data != null && open.data.length > 0) {
3523
+ controller.enqueue({
3524
+ type: "file",
3525
+ mediaType: (_p = open.mimeType) != null ? _p : "image/png",
3526
+ data: { type: "data", data: open.data },
3527
+ ...providerMetadata ? { providerMetadata } : {}
3528
+ });
3529
+ } else if (open.uri != null && open.uri.length > 0) {
3530
+ controller.enqueue({
3531
+ type: "file",
3532
+ mediaType: (_q = open.mimeType) != null ? _q : "image/png",
3533
+ data: { type: "url", url: new URL(open.uri) },
3534
+ ...providerMetadata ? { providerMetadata } : {}
3535
+ });
3536
+ }
3537
+ } else if (open.kind === "function_call") {
3538
+ const accumulated = open.argumentsAccum.length > 0 ? open.argumentsAccum : "{}";
3539
+ controller.enqueue({
3540
+ type: "tool-input-end",
3541
+ id: open.toolCallId
3542
+ });
3543
+ const google = {};
3544
+ if (open.signature != null) google.signature = open.signature;
3545
+ if (interactionId != null) google.interactionId = interactionId;
3546
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3547
+ controller.enqueue({
3548
+ type: "tool-call",
3549
+ toolCallId: open.toolCallId,
3550
+ toolName: open.toolName,
3551
+ input: accumulated,
3552
+ ...providerMetadata ? { providerMetadata } : {}
3553
+ });
3554
+ } else if (open.kind === "builtin_tool_call" && !open.callEmitted) {
3555
+ controller.enqueue({
3556
+ type: "tool-call",
3557
+ toolCallId: open.toolCallId,
3558
+ toolName: open.toolName,
3559
+ input: JSON.stringify((_r = open.arguments) != null ? _r : {}),
3560
+ providerExecuted: true
3561
+ });
3562
+ open.callEmitted = true;
3563
+ } else if (open.kind === "builtin_tool_result" && !open.resultEmitted) {
3564
+ controller.enqueue({
3565
+ type: "tool-result",
3566
+ toolCallId: open.callId,
3567
+ toolName: open.toolName,
3568
+ result: (_s = open.result) != null ? _s : null
3569
+ });
3570
+ open.resultEmitted = true;
3571
+ const sources = builtinToolResultToSources({
3572
+ block: {
3573
+ type: open.blockType,
3574
+ call_id: open.callId,
3575
+ result: open.result
3576
+ },
3577
+ generateId: generateId2
3578
+ });
3579
+ for (const source of sources) {
3580
+ const key = sourceKey(source);
3581
+ if (emittedSourceKeys.has(key)) continue;
3582
+ emittedSourceKeys.add(key);
3583
+ controller.enqueue(source);
3584
+ }
3585
+ }
3586
+ openBlocks.delete(event.index);
3587
+ break;
3588
+ }
3589
+ case "interaction.status_update":
3590
+ case "interaction.in_progress":
3591
+ case "interaction.requires_action": {
3592
+ const event = value;
3593
+ if (event.status != null) {
3594
+ finishStatus = event.status;
3595
+ } else if (eventType === "interaction.requires_action") {
3596
+ finishStatus = "requires_action";
3597
+ } else {
3598
+ finishStatus = "in_progress";
3599
+ }
3600
+ break;
3601
+ }
3602
+ case "interaction.completed": {
3603
+ const event = value;
3604
+ const interaction = event.interaction;
3605
+ if ((interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0) {
3606
+ interactionId = interaction.id;
3607
+ }
3608
+ if ((interaction == null ? void 0 : interaction.status) != null) {
3609
+ finishStatus = interaction.status;
3610
+ }
3611
+ if ((interaction == null ? void 0 : interaction.usage) != null) {
3612
+ usage = interaction.usage;
3613
+ }
3614
+ if ((interaction == null ? void 0 : interaction.service_tier) != null) {
3615
+ serviceTier = interaction.service_tier;
3616
+ }
3617
+ break;
3618
+ }
3619
+ case "error": {
3620
+ const event = value;
3621
+ finishStatus = "failed";
3622
+ const errorPayload = (_t = event.error) != null ? _t : {
3623
+ message: "Unknown interaction error"
3624
+ };
3625
+ controller.enqueue({ type: "error", error: errorPayload });
3626
+ break;
3627
+ }
3628
+ default:
3629
+ break;
3630
+ }
3631
+ },
3632
+ flush(controller) {
3633
+ const finishReason = {
3634
+ unified: mapGoogleInteractionsFinishReason({
3635
+ status: finishStatus,
3636
+ hasFunctionCall
3637
+ }),
3638
+ raw: finishStatus
3639
+ };
3640
+ const outputTokensByModality = getGoogleInteractionsOutputTokensByModality(usage);
3641
+ const providerMetadata = {
3642
+ google: {
3643
+ ...interactionId != null ? { interactionId } : {},
3644
+ ...serviceTier != null ? { serviceTier } : {},
3645
+ ...outputTokensByModality != null ? { outputTokensByModality } : {}
3646
+ }
3647
+ };
3648
+ controller.enqueue({
3649
+ type: "finish",
3650
+ finishReason,
3651
+ usage: convertGoogleInteractionsUsage(usage),
3652
+ providerMetadata
3653
+ });
3654
+ }
3655
+ });
3656
+ }
3657
+
3658
+ // src/interactions/convert-to-google-interactions-input.ts
3659
+ import {
3660
+ convertToBase64 as convertToBase642,
3661
+ getTopLevelMediaType as getTopLevelMediaType2,
3662
+ isFullMediaType as isFullMediaType2,
3663
+ resolveFullMediaType as resolveFullMediaType2,
3664
+ resolveProviderReference as resolveProviderReference2,
3665
+ secureJsonParse as secureJsonParse2
3666
+ } from "@ai-sdk/provider-utils";
3667
+ function convertToGoogleInteractionsInput({
3668
+ prompt,
3669
+ previousInteractionId,
3670
+ store,
3671
+ mediaResolution
3672
+ }) {
3673
+ var _a, _b, _c, _d, _e, _f, _g;
3674
+ const warnings = [];
3675
+ const incoherentCombo = previousInteractionId != null && store === false;
3676
+ const shouldCompact = previousInteractionId != null && store !== false;
3677
+ if (incoherentCombo) {
3678
+ warnings.push({
3679
+ type: "other",
3680
+ 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."
3681
+ });
3682
+ }
3683
+ const compactedPrompt = shouldCompact ? compactPromptForPreviousInteraction({
3684
+ prompt,
3685
+ previousInteractionId
3686
+ }) : prompt;
3687
+ const systemTexts = [];
3688
+ const steps = [];
3689
+ for (const message of compactedPrompt) {
3690
+ switch (message.role) {
3691
+ case "system": {
3692
+ systemTexts.push(message.content);
3693
+ break;
3694
+ }
3695
+ case "user": {
3696
+ const content = [];
3697
+ for (const part of message.content) {
3698
+ if (part.type === "text") {
3699
+ content.push({ type: "text", text: part.text });
3700
+ } else if (part.type === "file") {
3701
+ const fileBlock = convertFilePartToContent({
3702
+ part,
3703
+ warnings,
3704
+ mediaResolution
3705
+ });
3706
+ if (fileBlock != null) {
3707
+ content.push(fileBlock);
3708
+ }
3709
+ }
3710
+ }
3711
+ const merged = mergeAdjacentTextContent(content);
3712
+ if (merged.length > 0) {
3713
+ steps.push({ type: "user_input", content: merged });
3714
+ }
3715
+ break;
3716
+ }
3717
+ case "assistant": {
3718
+ let pendingModelOutput = [];
3719
+ const flushModelOutput = () => {
3720
+ if (pendingModelOutput.length > 0) {
3721
+ steps.push({ type: "model_output", content: pendingModelOutput });
3722
+ pendingModelOutput = [];
3723
+ }
3724
+ };
3725
+ for (const part of message.content) {
3726
+ if (part.type === "text") {
3727
+ pendingModelOutput.push({ type: "text", text: part.text });
3728
+ } else if (part.type === "reasoning") {
3729
+ flushModelOutput();
3730
+ const signature = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.signature;
3731
+ steps.push({
3732
+ type: "thought",
3733
+ ...signature != null ? { signature } : {},
3734
+ summary: part.text.length > 0 ? [{ type: "text", text: part.text }] : void 0
3735
+ });
3736
+ } else if (part.type === "file") {
3737
+ const fileBlock = convertFilePartToContent({
3738
+ part,
3739
+ warnings,
3740
+ mediaResolution
3741
+ });
3742
+ if (fileBlock != null) {
3743
+ pendingModelOutput.push(fileBlock);
3744
+ }
3745
+ } else if (part.type === "tool-call") {
3746
+ flushModelOutput();
3747
+ const signature = (_d = (_c = part.providerOptions) == null ? void 0 : _c.google) == null ? void 0 : _d.signature;
3748
+ const args = typeof part.input === "string" ? safeParseToolArgs(part.input) : (_e = part.input) != null ? _e : {};
3749
+ steps.push({
3750
+ type: "function_call",
3751
+ id: part.toolCallId,
3752
+ name: part.toolName,
3753
+ arguments: args,
3754
+ ...signature != null ? { signature } : {}
3755
+ });
3756
+ } else {
3757
+ warnings.push({
3758
+ type: "other",
3759
+ message: `google.interactions: unsupported assistant content part type "${part.type}"; part dropped.`
3760
+ });
3761
+ }
3762
+ }
3763
+ flushModelOutput();
3764
+ break;
3765
+ }
3766
+ case "tool": {
3767
+ const content = [];
3768
+ for (const part of message.content) {
3769
+ if (part.type !== "tool-result") {
3770
+ warnings.push({
3771
+ type: "other",
3772
+ message: `google.interactions: unsupported tool message part type "${part.type}"; part dropped.`
3773
+ });
3774
+ continue;
3775
+ }
3776
+ const block = convertToolResultPart({
3777
+ toolCallId: part.toolCallId,
3778
+ toolName: part.toolName,
3779
+ output: part.output,
3780
+ signature: (_g = (_f = part.providerOptions) == null ? void 0 : _f.google) == null ? void 0 : _g.signature,
3781
+ warnings
3782
+ });
3783
+ content.push(block);
3784
+ }
3785
+ if (content.length > 0) {
3786
+ steps.push({ type: "user_input", content });
3787
+ }
3788
+ break;
3789
+ }
3790
+ }
3791
+ }
3792
+ const systemInstruction = systemTexts.length > 0 ? systemTexts.join("\n\n") : void 0;
3793
+ return { input: steps, systemInstruction, warnings };
3794
+ }
3795
+ function convertFilePartToContent({
3796
+ part,
3797
+ warnings,
3798
+ mediaResolution
3799
+ }) {
3800
+ if (part.data.type === "text") {
3801
+ return {
3802
+ type: "text",
3803
+ text: part.data.text
3804
+ };
3805
+ }
3806
+ const topLevel = getTopLevelMediaType2(part.mediaType);
3807
+ let kind;
3808
+ switch (topLevel) {
3809
+ case "image":
3810
+ kind = "image";
3811
+ break;
3812
+ case "audio":
3813
+ kind = "audio";
3814
+ break;
3815
+ case "video":
3816
+ kind = "video";
3817
+ break;
3818
+ case "application":
3819
+ kind = "document";
3820
+ break;
3821
+ default:
3822
+ kind = void 0;
3823
+ }
3824
+ if (kind == null) {
3825
+ warnings.push({
3826
+ type: "other",
3827
+ message: `google.interactions: unsupported file media type "${part.mediaType}"; part dropped.`
3828
+ });
3829
+ return void 0;
3830
+ }
3831
+ const resolutionField = mediaResolution != null && (kind === "image" || kind === "video") ? { resolution: mediaResolution } : {};
3832
+ switch (part.data.type) {
3833
+ case "data": {
3834
+ const mimeType = resolveFullMediaType2({ part });
3835
+ return {
3836
+ type: kind,
3837
+ data: convertToBase642(part.data.data),
3838
+ mime_type: mimeType,
3839
+ ...resolutionField
3840
+ };
3841
+ }
3842
+ case "url": {
3843
+ return {
3844
+ type: kind,
3845
+ uri: part.data.url.toString(),
3846
+ ...isFullMediaType2(part.mediaType) ? { mime_type: part.mediaType } : {},
3847
+ ...resolutionField
3848
+ };
3849
+ }
3850
+ case "reference": {
3851
+ const uri = resolveProviderReference2({
3852
+ reference: part.data.reference,
3853
+ provider: "google"
3854
+ });
3855
+ return {
3856
+ type: kind,
3857
+ uri,
3858
+ ...isFullMediaType2(part.mediaType) ? { mime_type: part.mediaType } : {},
3859
+ ...resolutionField
3860
+ };
3861
+ }
3862
+ }
3863
+ }
3864
+ function compactPromptForPreviousInteraction({
3865
+ prompt,
3866
+ previousInteractionId
3867
+ }) {
3868
+ const out = [];
3869
+ const droppedToolCallIds = /* @__PURE__ */ new Set();
3870
+ for (const message of prompt) {
3871
+ if (message.role === "assistant") {
3872
+ const matchesLinkedInteraction = message.content.some((part) => {
3873
+ var _a, _b;
3874
+ const partInteractionId = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.interactionId;
3875
+ return partInteractionId === previousInteractionId;
3876
+ });
3877
+ if (matchesLinkedInteraction) {
3878
+ for (const part of message.content) {
3879
+ if (part.type === "tool-call") {
3880
+ droppedToolCallIds.add(part.toolCallId);
3881
+ }
3882
+ }
3883
+ continue;
3884
+ }
3885
+ out.push(message);
3886
+ continue;
3887
+ }
3888
+ if (message.role === "tool") {
3889
+ const remaining = message.content.filter((part) => {
3890
+ if (part.type !== "tool-result") {
3891
+ return true;
3892
+ }
3893
+ return !droppedToolCallIds.has(part.toolCallId);
3894
+ });
3895
+ if (remaining.length === 0) {
3896
+ continue;
3897
+ }
3898
+ out.push({
3899
+ ...message,
3900
+ content: remaining
3901
+ });
3902
+ continue;
3903
+ }
3904
+ out.push(message);
3905
+ }
3906
+ return out;
3907
+ }
3908
+ function safeParseToolArgs(input) {
3909
+ try {
3910
+ const parsed = secureJsonParse2(input);
3911
+ if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) {
3912
+ return parsed;
3913
+ }
3914
+ return { value: parsed };
3915
+ } catch (e) {
3916
+ return { value: input };
3917
+ }
3918
+ }
3919
+ function convertToolResultPart({
3920
+ toolCallId,
3921
+ toolName,
3922
+ output,
3923
+ signature,
3924
+ warnings
3925
+ }) {
3926
+ var _a;
3927
+ const base = {
3928
+ type: "function_result",
3929
+ call_id: toolCallId,
3930
+ name: toolName,
3931
+ ...signature != null ? { signature } : {}
3932
+ };
3933
+ switch (output.type) {
3934
+ case "text":
3935
+ return { ...base, result: output.value };
3936
+ case "json":
3937
+ return { ...base, result: JSON.stringify(output.value) };
3938
+ case "error-text":
3939
+ return { ...base, is_error: true, result: output.value };
3940
+ case "error-json":
3941
+ return { ...base, is_error: true, result: JSON.stringify(output.value) };
3942
+ case "execution-denied":
3943
+ return {
3944
+ ...base,
3945
+ is_error: true,
3946
+ result: (_a = output.reason) != null ? _a : "Tool execution denied by user."
3947
+ };
3948
+ case "content": {
3949
+ const blocks = [];
3950
+ for (const item of output.value) {
3951
+ if (item.type === "text") {
3952
+ blocks.push({ type: "text", text: item.text });
3953
+ } else if (item.type === "file") {
3954
+ const topLevel = getTopLevelMediaType2(item.mediaType);
3955
+ if (topLevel !== "image") {
3956
+ warnings.push({
3957
+ type: "other",
3958
+ message: `google.interactions: tool-result file with mediaType "${item.mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`
3959
+ });
3960
+ continue;
3961
+ }
3962
+ const imageBlock = filePartToImageBlock({ part: item, warnings });
3963
+ if (imageBlock != null) {
3964
+ blocks.push(imageBlock);
3965
+ }
3966
+ } else {
3967
+ warnings.push({
3968
+ type: "other",
3969
+ message: `google.interactions: tool-result content part type "${item.type}" is not supported; part dropped.`
3970
+ });
3971
+ }
3972
+ }
3973
+ return { ...base, result: blocks };
3974
+ }
3975
+ }
3976
+ }
3977
+ function filePartToImageBlock({
3978
+ part,
3979
+ warnings
3980
+ }) {
3981
+ switch (part.data.type) {
3982
+ case "data": {
3983
+ const mimeType = isFullMediaType2(part.mediaType) ? part.mediaType : resolveFullMediaType2({
3984
+ part: {
3985
+ type: "file",
3986
+ mediaType: part.mediaType,
3987
+ data: part.data
3988
+ }
3989
+ });
3990
+ return {
3991
+ type: "image",
3992
+ data: convertToBase642(part.data.data),
3993
+ mime_type: mimeType
3994
+ };
3995
+ }
3996
+ case "url":
3997
+ return {
3998
+ type: "image",
3999
+ uri: part.data.url.toString(),
4000
+ ...isFullMediaType2(part.mediaType) ? { mime_type: part.mediaType } : {}
4001
+ };
4002
+ case "reference": {
4003
+ const uri = resolveProviderReference2({
4004
+ reference: part.data.reference,
4005
+ provider: "google"
4006
+ });
4007
+ return {
4008
+ type: "image",
4009
+ uri,
4010
+ ...isFullMediaType2(part.mediaType) ? { mime_type: part.mediaType } : {}
4011
+ };
4012
+ }
4013
+ case "text": {
4014
+ warnings.push({
4015
+ type: "other",
4016
+ message: 'google.interactions: tool-result image part with `data.type === "text"` is not representable as an image; part dropped.'
4017
+ });
4018
+ return void 0;
4019
+ }
4020
+ }
4021
+ }
4022
+ function mergeAdjacentTextContent(content) {
4023
+ if (content.length < 2) {
4024
+ return content;
4025
+ }
4026
+ const result = [];
4027
+ for (const block of content) {
4028
+ const last = result[result.length - 1];
4029
+ if (block.type === "text" && last != null && last.type === "text" && last.annotations == null && block.annotations == null) {
4030
+ const merged = {
4031
+ type: "text",
4032
+ text: `${last.text}
4033
+
4034
+ ${block.text}`
4035
+ };
4036
+ result[result.length - 1] = merged;
4037
+ continue;
4038
+ }
4039
+ result.push(block);
4040
+ }
4041
+ return result;
4042
+ }
4043
+
4044
+ // src/interactions/google-interactions-api.ts
4045
+ import {
4046
+ lazySchema as lazySchema12,
4047
+ zodSchema as zodSchema12
4048
+ } from "@ai-sdk/provider-utils";
4049
+ import { z as z13 } from "zod/v4";
4050
+ var tokenByModalitySchema = () => z13.object({
4051
+ modality: z13.string().nullish(),
4052
+ tokens: z13.number().nullish()
4053
+ }).loose();
4054
+ var usageSchema2 = () => z13.object({
4055
+ total_input_tokens: z13.number().nullish(),
4056
+ total_output_tokens: z13.number().nullish(),
4057
+ total_thought_tokens: z13.number().nullish(),
4058
+ total_cached_tokens: z13.number().nullish(),
4059
+ total_tool_use_tokens: z13.number().nullish(),
4060
+ total_tokens: z13.number().nullish(),
4061
+ input_tokens_by_modality: z13.array(tokenByModalitySchema()).nullish(),
4062
+ output_tokens_by_modality: z13.array(tokenByModalitySchema()).nullish(),
4063
+ cached_tokens_by_modality: z13.array(tokenByModalitySchema()).nullish(),
4064
+ tool_use_tokens_by_modality: z13.array(tokenByModalitySchema()).nullish(),
4065
+ grounding_tool_count: z13.array(
4066
+ z13.object({
4067
+ type: z13.string().nullish(),
4068
+ count: z13.number().nullish()
4069
+ }).loose()
4070
+ ).nullish()
4071
+ }).loose();
4072
+ var interactionStatusSchema = () => z13.enum([
4073
+ "in_progress",
4074
+ "requires_action",
4075
+ "completed",
4076
+ "failed",
4077
+ "cancelled",
4078
+ "incomplete"
4079
+ ]);
4080
+ var annotationSchema = () => {
4081
+ const urlCitation = z13.object({
4082
+ type: z13.literal("url_citation"),
4083
+ url: z13.string().nullish(),
4084
+ title: z13.string().nullish(),
4085
+ start_index: z13.number().nullish(),
4086
+ end_index: z13.number().nullish()
4087
+ }).loose();
4088
+ const fileCitation = z13.object({
4089
+ type: z13.literal("file_citation"),
4090
+ file_name: z13.string().nullish(),
4091
+ document_uri: z13.string().nullish(),
4092
+ url: z13.string().nullish(),
4093
+ page_number: z13.number().nullish(),
4094
+ media_id: z13.string().nullish(),
4095
+ start_index: z13.number().nullish(),
4096
+ end_index: z13.number().nullish(),
4097
+ custom_metadata: z13.record(z13.string(), z13.unknown()).nullish()
4098
+ }).loose();
4099
+ const placeCitation = z13.object({
4100
+ type: z13.literal("place_citation"),
4101
+ name: z13.string().nullish(),
4102
+ url: z13.string().nullish(),
4103
+ place_id: z13.string().nullish(),
4104
+ start_index: z13.number().nullish(),
4105
+ end_index: z13.number().nullish()
4106
+ }).loose();
4107
+ return z13.union([
4108
+ urlCitation,
4109
+ fileCitation,
4110
+ placeCitation,
4111
+ z13.object({ type: z13.string() }).loose()
4112
+ ]);
4113
+ };
4114
+ var thoughtSummaryItemSchema = () => z13.object({
4115
+ type: z13.string(),
4116
+ text: z13.string().nullish(),
4117
+ data: z13.string().nullish(),
4118
+ mime_type: z13.string().nullish()
4119
+ }).loose();
4120
+ var contentBlockSchema = () => {
4121
+ const textContent = z13.object({
4122
+ type: z13.literal("text"),
4123
+ text: z13.string(),
4124
+ annotations: z13.array(annotationSchema()).nullish()
4125
+ }).loose();
4126
+ const imageContent = z13.object({
4127
+ type: z13.literal("image"),
4128
+ data: z13.string().nullish(),
4129
+ mime_type: z13.string().nullish(),
4130
+ resolution: z13.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4131
+ uri: z13.string().nullish()
4132
+ }).loose();
4133
+ const videoContent = z13.object({
4134
+ type: z13.literal("video"),
4135
+ data: z13.string().nullish(),
4136
+ mime_type: z13.string().nullish(),
4137
+ uri: z13.string().nullish()
4138
+ }).loose();
4139
+ return z13.union([
4140
+ textContent,
4141
+ imageContent,
4142
+ videoContent,
4143
+ z13.object({ type: z13.string() }).loose()
4144
+ ]);
4145
+ };
4146
+ var BUILTIN_TOOL_CALL_STEP_TYPES = [
4147
+ "google_search_call",
4148
+ "code_execution_call",
4149
+ "url_context_call",
4150
+ "file_search_call",
4151
+ "google_maps_call",
4152
+ "mcp_server_tool_call"
4153
+ ];
4154
+ var BUILTIN_TOOL_RESULT_STEP_TYPES = [
4155
+ "google_search_result",
4156
+ "code_execution_result",
4157
+ "url_context_result",
4158
+ "file_search_result",
4159
+ "google_maps_result",
4160
+ "mcp_server_tool_result"
4161
+ ];
4162
+ var stepSchema = () => {
4163
+ const userInputStep = z13.object({
4164
+ type: z13.literal("user_input"),
4165
+ content: z13.array(contentBlockSchema()).nullish()
4166
+ }).loose();
4167
+ const modelOutputStep = z13.object({
4168
+ type: z13.literal("model_output"),
4169
+ content: z13.array(contentBlockSchema()).nullish()
4170
+ }).loose();
4171
+ const functionCallStep = z13.object({
4172
+ type: z13.literal("function_call"),
4173
+ id: z13.string(),
4174
+ name: z13.string(),
4175
+ arguments: z13.record(z13.string(), z13.unknown()).nullish(),
4176
+ signature: z13.string().nullish()
4177
+ }).loose();
4178
+ const thoughtStep = z13.object({
4179
+ type: z13.literal("thought"),
4180
+ signature: z13.string().nullish(),
4181
+ summary: z13.array(thoughtSummaryItemSchema()).nullish()
4182
+ }).loose();
4183
+ const builtinToolCallStep = z13.object({
4184
+ type: z13.enum(BUILTIN_TOOL_CALL_STEP_TYPES),
4185
+ id: z13.string(),
4186
+ arguments: z13.record(z13.string(), z13.unknown()).nullish(),
4187
+ name: z13.string().nullish(),
4188
+ server_name: z13.string().nullish(),
4189
+ search_type: z13.string().nullish(),
4190
+ signature: z13.string().nullish()
4191
+ }).loose();
4192
+ const builtinToolResultStep = z13.object({
4193
+ type: z13.enum(BUILTIN_TOOL_RESULT_STEP_TYPES),
4194
+ call_id: z13.string(),
4195
+ result: z13.unknown().nullish(),
4196
+ is_error: z13.boolean().nullish(),
4197
+ name: z13.string().nullish(),
4198
+ server_name: z13.string().nullish(),
4199
+ signature: z13.string().nullish()
4200
+ }).loose();
4201
+ return z13.union([
4202
+ userInputStep,
4203
+ modelOutputStep,
4204
+ functionCallStep,
4205
+ thoughtStep,
4206
+ builtinToolCallStep,
4207
+ builtinToolResultStep,
4208
+ z13.object({ type: z13.string() }).loose()
4209
+ ]);
4210
+ };
4211
+ var googleInteractionsResponseSchema = lazySchema12(
4212
+ () => zodSchema12(
4213
+ z13.object({
4214
+ /*
4215
+ * `id` is omitted from the response body when `store: false` (fully
4216
+ * stateless mode) — there is no server-side interaction record for the
4217
+ * client to reference. `nullish` lets the schema accept that shape.
4218
+ */
4219
+ id: z13.string().nullish(),
4220
+ created: z13.string().nullish(),
4221
+ updated: z13.string().nullish(),
4222
+ status: interactionStatusSchema(),
4223
+ model: z13.string().nullish(),
4224
+ agent: z13.string().nullish(),
4225
+ steps: z13.array(stepSchema()).nullish(),
4226
+ usage: usageSchema2().nullish(),
4227
+ service_tier: z13.string().nullish(),
4228
+ previous_interaction_id: z13.string().nullish(),
4229
+ response_modalities: z13.array(z13.string()).nullish()
4230
+ }).loose()
4231
+ )
4232
+ );
4233
+ var googleInteractionsEventSchema = lazySchema12(
4234
+ () => zodSchema12(
4235
+ (() => {
4236
+ const status = interactionStatusSchema();
4237
+ const annotation = annotationSchema();
4238
+ const thoughtSummaryItem = thoughtSummaryItemSchema();
4239
+ const interactionCreatedEvent = z13.object({
4240
+ event_type: z13.literal("interaction.created"),
4241
+ event_id: z13.string().nullish(),
4242
+ interaction: z13.object({
4243
+ /*
4244
+ * `id` is omitted when `store: false` (fully stateless mode);
4245
+ * see the matching note on `googleInteractionsResponseSchema.id`.
4246
+ */
4247
+ id: z13.string().nullish(),
4248
+ created: z13.string().nullish(),
4249
+ model: z13.string().nullish(),
4250
+ agent: z13.string().nullish(),
4251
+ status: status.nullish()
4252
+ }).loose()
4253
+ }).loose();
4254
+ const stepStartEvent = z13.object({
4255
+ event_type: z13.literal("step.start"),
4256
+ event_id: z13.string().nullish(),
4257
+ index: z13.number(),
4258
+ step: stepSchema()
4259
+ }).loose();
4260
+ const stepDeltaText = z13.object({
4261
+ type: z13.literal("text"),
4262
+ text: z13.string()
4263
+ }).loose();
4264
+ const stepDeltaThoughtSummary = z13.object({
4265
+ type: z13.literal("thought_summary"),
4266
+ content: thoughtSummaryItem.nullish()
4267
+ }).loose();
4268
+ const stepDeltaThoughtSignature = z13.object({
4269
+ type: z13.literal("thought_signature"),
4270
+ signature: z13.string().nullish()
4271
+ }).loose();
4272
+ const stepDeltaArgumentsDelta = z13.object({
4273
+ type: z13.literal("arguments_delta"),
4274
+ arguments: z13.string().nullish(),
4275
+ id: z13.string().nullish(),
4276
+ signature: z13.string().nullish()
4277
+ }).loose();
4278
+ const stepDeltaTextAnnotation = z13.object({
4279
+ type: z13.enum(["text_annotation_delta", "text_annotation"]),
4280
+ annotations: z13.array(annotation).nullish()
4281
+ }).loose();
4282
+ const stepDeltaImage = z13.object({
4283
+ type: z13.literal("image"),
4284
+ data: z13.string().nullish(),
4285
+ mime_type: z13.string().nullish(),
4286
+ resolution: z13.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4287
+ uri: z13.string().nullish()
4288
+ }).loose();
4289
+ const stepDeltaVideo = z13.object({
4290
+ type: z13.literal("video"),
4291
+ data: z13.string().nullish(),
4292
+ mime_type: z13.string().nullish(),
4293
+ uri: z13.string().nullish()
4294
+ }).loose();
4295
+ const stepDeltaBuiltinToolCall = z13.object({
4296
+ type: z13.enum(BUILTIN_TOOL_CALL_STEP_TYPES),
4297
+ id: z13.string().nullish(),
4298
+ arguments: z13.record(z13.string(), z13.unknown()).nullish(),
4299
+ name: z13.string().nullish(),
4300
+ server_name: z13.string().nullish(),
4301
+ search_type: z13.string().nullish(),
4302
+ signature: z13.string().nullish()
4303
+ }).loose();
4304
+ const stepDeltaBuiltinToolResult = z13.object({
4305
+ type: z13.enum(BUILTIN_TOOL_RESULT_STEP_TYPES),
4306
+ call_id: z13.string().nullish(),
4307
+ result: z13.unknown().nullish(),
4308
+ is_error: z13.boolean().nullish(),
4309
+ name: z13.string().nullish(),
4310
+ server_name: z13.string().nullish(),
4311
+ signature: z13.string().nullish()
4312
+ }).loose();
4313
+ const stepDeltaUnknown = z13.object({ type: z13.string() }).loose();
4314
+ const stepDeltaUnion = z13.union([
4315
+ stepDeltaText,
4316
+ stepDeltaImage,
4317
+ stepDeltaVideo,
4318
+ stepDeltaThoughtSummary,
4319
+ stepDeltaThoughtSignature,
4320
+ stepDeltaArgumentsDelta,
4321
+ stepDeltaTextAnnotation,
4322
+ stepDeltaBuiltinToolCall,
4323
+ stepDeltaBuiltinToolResult,
4324
+ stepDeltaUnknown
4325
+ ]);
4326
+ const stepDeltaEvent = z13.object({
4327
+ event_type: z13.literal("step.delta"),
4328
+ event_id: z13.string().nullish(),
4329
+ index: z13.number(),
4330
+ delta: stepDeltaUnion
4331
+ }).loose();
4332
+ const stepStopEvent = z13.object({
4333
+ event_type: z13.literal("step.stop"),
4334
+ event_id: z13.string().nullish(),
4335
+ index: z13.number()
4336
+ }).loose();
4337
+ const interactionStatusUpdateEvent = z13.object({
4338
+ event_type: z13.literal("interaction.status_update"),
4339
+ event_id: z13.string().nullish(),
4340
+ interaction_id: z13.string().nullish(),
4341
+ status: status.nullish()
4342
+ }).loose();
4343
+ const interactionInProgressEvent = z13.object({
4344
+ event_type: z13.literal("interaction.in_progress"),
4345
+ event_id: z13.string().nullish(),
4346
+ interaction_id: z13.string().nullish(),
4347
+ status: status.nullish()
4348
+ }).loose();
4349
+ const interactionRequiresActionEvent = z13.object({
4350
+ event_type: z13.literal("interaction.requires_action"),
4351
+ event_id: z13.string().nullish(),
4352
+ interaction_id: z13.string().nullish(),
4353
+ status: status.nullish()
4354
+ }).loose();
4355
+ const interactionCompletedEvent = z13.object({
4356
+ event_type: z13.literal("interaction.completed"),
4357
+ event_id: z13.string().nullish(),
4358
+ interaction: z13.object({
4359
+ id: z13.string().nullish(),
4360
+ status: status.nullish(),
4361
+ usage: usageSchema2().nullish(),
4362
+ service_tier: z13.string().nullish()
4363
+ }).loose()
4364
+ }).loose();
4365
+ const errorEvent = z13.object({
4366
+ event_type: z13.literal("error"),
4367
+ event_id: z13.string().nullish(),
4368
+ error: z13.object({
4369
+ code: z13.string().nullish(),
4370
+ message: z13.string().nullish()
4371
+ }).loose().nullish()
4372
+ }).loose();
4373
+ const unknownEvent = z13.object({ event_type: z13.string() }).loose();
4374
+ return z13.union([
4375
+ interactionCreatedEvent,
4376
+ stepStartEvent,
4377
+ stepDeltaEvent,
4378
+ stepStopEvent,
4379
+ interactionStatusUpdateEvent,
4380
+ interactionInProgressEvent,
4381
+ interactionRequiresActionEvent,
4382
+ interactionCompletedEvent,
4383
+ errorEvent,
4384
+ unknownEvent
4385
+ ]);
4386
+ })()
4387
+ )
4388
+ );
4389
+
4390
+ // src/interactions/google-interactions-language-model-options.ts
4391
+ import {
4392
+ lazySchema as lazySchema13,
4393
+ zodSchema as zodSchema13
4394
+ } from "@ai-sdk/provider-utils";
4395
+ import { z as z14 } from "zod/v4";
4396
+ var googleInteractionsLanguageModelOptions = lazySchema13(
4397
+ () => zodSchema13(
4398
+ z14.object({
4399
+ previousInteractionId: z14.string().nullish(),
4400
+ store: z14.boolean().nullish(),
4401
+ agent: z14.string().nullish(),
4402
+ agentConfig: z14.union([
4403
+ z14.object({
4404
+ type: z14.literal("dynamic")
4405
+ }).loose(),
4406
+ z14.object({
4407
+ type: z14.literal("deep-research"),
4408
+ thinkingSummaries: z14.enum(["auto", "none"]).nullish(),
4409
+ visualization: z14.enum(["off", "auto"]).nullish(),
4410
+ collaborativePlanning: z14.boolean().nullish()
4411
+ })
4412
+ ]).nullish(),
4413
+ thinkingLevel: z14.enum(["minimal", "low", "medium", "high"]).nullish(),
4414
+ thinkingSummaries: z14.enum(["auto", "none"]).nullish(),
4415
+ /**
4416
+ * Output-format entries that map directly to the API's `response_format`
4417
+ * array. Use this to request image, audio, or non-JSON text outputs
4418
+ * with full control over `mime_type`, `aspect_ratio`, and `image_size`.
4419
+ *
4420
+ * Entries are sent in order. The AI SDK call-level `responseFormat: {
4421
+ * type: 'json', schema }` still drives JSON-mode and adds a matching
4422
+ * text entry automatically; entries listed here are appended.
4423
+ */
4424
+ responseFormat: z14.array(
4425
+ z14.union([
4426
+ z14.object({
4427
+ type: z14.literal("text"),
4428
+ mimeType: z14.string().nullish(),
4429
+ schema: z14.unknown().nullish()
4430
+ }).loose(),
4431
+ z14.object({
4432
+ type: z14.literal("image"),
4433
+ mimeType: z14.string().nullish(),
4434
+ aspectRatio: z14.enum([
4435
+ "1:1",
4436
+ "2:3",
4437
+ "3:2",
4438
+ "3:4",
4439
+ "4:3",
4440
+ "4:5",
4441
+ "5:4",
4442
+ "9:16",
4443
+ "16:9",
4444
+ "21:9",
4445
+ "1:8",
4446
+ "8:1",
4447
+ "1:4",
4448
+ "4:1"
4449
+ ]).nullish(),
4450
+ imageSize: z14.enum(["1K", "2K", "4K", "512"]).nullish()
4451
+ }).loose(),
4452
+ z14.object({
4453
+ type: z14.literal("audio"),
4454
+ mimeType: z14.string().nullish()
4455
+ }).loose()
4456
+ ])
4457
+ ).nullish(),
4458
+ /**
4459
+ * @deprecated Use `responseFormat` with a `{ type: 'image', ... }`
4460
+ * entry instead. Retained for backwards compatibility; the SDK
4461
+ * translates it into a matching `response_format` image entry and
4462
+ * emits a warning when set.
4463
+ */
4464
+ imageConfig: z14.object({
4465
+ aspectRatio: z14.enum([
4466
+ "1:1",
4467
+ "2:3",
4468
+ "3:2",
4469
+ "3:4",
4470
+ "4:3",
4471
+ "4:5",
4472
+ "5:4",
4473
+ "9:16",
4474
+ "16:9",
4475
+ "21:9",
4476
+ "1:8",
4477
+ "8:1",
4478
+ "1:4",
4479
+ "4:1"
4480
+ ]).nullish(),
4481
+ imageSize: z14.enum(["1K", "2K", "4K", "512"]).nullish()
4482
+ }).nullish(),
4483
+ mediaResolution: z14.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4484
+ responseModalities: z14.array(z14.enum(["text", "image", "audio", "video", "document"])).nullish(),
4485
+ serviceTier: z14.enum(["flex", "standard", "priority"]).nullish(),
4486
+ /**
4487
+ * Alternative to AI SDK `system` message. If both are set, the AI SDK
4488
+ * `system` message wins and a warning is emitted.
4489
+ */
4490
+ systemInstruction: z14.string().nullish(),
4491
+ /**
4492
+ * Per-block signature for round-tripping `thought.signature` and
4493
+ * `function_call.signature` blocks. Set by the SDK on output reasoning /
4494
+ * tool-call parts; passed back unchanged on input parts so the API
4495
+ * accepts the prior turn.
4496
+ */
4497
+ signature: z14.string().nullish(),
4498
+ /**
4499
+ * Set by the SDK on output assistant messages. The converter uses it to
4500
+ * decide which messages to drop when compacting under
4501
+ * `previousInteractionId`.
4502
+ */
4503
+ interactionId: z14.string().nullish(),
4504
+ /**
4505
+ * Maximum time, in milliseconds, to poll a background interaction (agent
4506
+ * call) before giving up. Defaults to 30 minutes. Long-running agents
4507
+ * such as deep research can take tens of minutes — increase if needed.
4508
+ */
4509
+ pollingTimeoutMs: z14.number().int().positive().nullish(),
4510
+ /**
4511
+ * Run the interaction in the background. Required for agents whose
4512
+ * server-side workflow cannot complete within a single request/response.
4513
+ * When `true`, the POST returns with a non-terminal status and the SDK
4514
+ * polls `GET /interactions/{id}` until the work completes. Some agents
4515
+ * reject `true`; see the agent's documentation for which mode it
4516
+ * requires.
4517
+ */
4518
+ background: z14.boolean().nullish(),
4519
+ /**
4520
+ * Environment configuration for the agent sandbox. Only applies to agent
4521
+ * calls (`google.interactions({ agent })`); ignored on model-id calls.
4522
+ *
4523
+ * - `"remote"`: provision a fresh sandbox for this call.
4524
+ * - any other string: an existing `environment_id` to reuse.
4525
+ * - object: provision a fresh sandbox and optionally preload `sources`
4526
+ * and/or constrain outbound traffic via `network`.
4527
+ */
4528
+ environment: z14.union([
4529
+ z14.string(),
4530
+ z14.object({
4531
+ type: z14.literal("remote"),
4532
+ sources: z14.array(
4533
+ z14.union([
4534
+ z14.object({
4535
+ type: z14.literal("gcs"),
4536
+ source: z14.string(),
4537
+ target: z14.string().nullish()
4538
+ }),
4539
+ z14.object({
4540
+ type: z14.literal("repository"),
4541
+ source: z14.string(),
4542
+ target: z14.string().nullish()
4543
+ }),
4544
+ z14.object({
4545
+ type: z14.literal("inline"),
4546
+ content: z14.string(),
4547
+ target: z14.string()
4548
+ })
4549
+ ])
4550
+ ).nullish(),
4551
+ network: z14.union([
4552
+ z14.literal("disabled"),
4553
+ z14.object({
4554
+ allowlist: z14.array(
4555
+ z14.object({
4556
+ domain: z14.string(),
4557
+ transform: z14.array(z14.record(z14.string(), z14.string())).nullish()
4558
+ })
4559
+ )
4560
+ })
4561
+ ]).nullish()
4562
+ })
4563
+ ]).nullish()
4564
+ })
4565
+ )
4566
+ );
4567
+
4568
+ // src/interactions/parse-google-interactions-outputs.ts
4569
+ function googleProviderMetadata({
4570
+ signature,
4571
+ interactionId
4572
+ }) {
4573
+ const google = {};
4574
+ if (signature != null) {
4575
+ google.signature = signature;
4576
+ }
4577
+ if (interactionId != null) {
4578
+ google.interactionId = interactionId;
4579
+ }
4580
+ return Object.keys(google).length > 0 ? { providerMetadata: { google } } : {};
4581
+ }
4582
+ var BUILTIN_TOOL_CALL_TYPES2 = /* @__PURE__ */ new Set([
4583
+ "google_search_call",
4584
+ "code_execution_call",
4585
+ "url_context_call",
4586
+ "file_search_call",
4587
+ "google_maps_call",
4588
+ "mcp_server_tool_call"
4589
+ ]);
4590
+ var BUILTIN_TOOL_RESULT_TYPES2 = /* @__PURE__ */ new Set([
4591
+ "google_search_result",
4592
+ "code_execution_result",
4593
+ "url_context_result",
4594
+ "file_search_result",
4595
+ "google_maps_result",
4596
+ "mcp_server_tool_result"
4597
+ ]);
4598
+ function builtinToolNameFromCallType2(type) {
4599
+ return type.replace(/_call$/, "");
4600
+ }
4601
+ function builtinToolNameFromResultType2(type) {
4602
+ return type.replace(/_result$/, "");
4603
+ }
4604
+ function parseGoogleInteractionsOutputs({
4605
+ steps,
4606
+ generateId: generateId2,
4607
+ interactionId
4608
+ }) {
4609
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
4610
+ const content = [];
4611
+ let hasFunctionCall = false;
4612
+ if (steps == null) {
4613
+ return { content, hasFunctionCall };
4614
+ }
4615
+ for (const step of steps) {
4616
+ if (step == null || typeof step !== "object") continue;
4617
+ const type = step.type;
4618
+ if (typeof type !== "string") continue;
4619
+ switch (type) {
4620
+ case "user_input": {
4621
+ break;
4622
+ }
4623
+ case "model_output": {
4624
+ const blocks = (_a = step.content) != null ? _a : [];
4625
+ for (const block of blocks) {
4626
+ if (block == null || typeof block !== "object") continue;
4627
+ const blockType = block.type;
4628
+ if (blockType === "text") {
4629
+ const text = (_b = block.text) != null ? _b : "";
4630
+ const annotations = block.annotations;
4631
+ content.push({
4632
+ type: "text",
4633
+ text,
4634
+ ...googleProviderMetadata({ interactionId })
4635
+ });
4636
+ const sources = annotationsToSources({ annotations, generateId: generateId2 });
4637
+ for (const source of sources) {
4638
+ content.push(source);
4639
+ }
4640
+ } else if (blockType === "image") {
4641
+ const image = block;
4642
+ if (image.data != null && image.data.length > 0) {
4643
+ content.push({
4644
+ type: "file",
4645
+ mediaType: (_c = image.mime_type) != null ? _c : "image/png",
4646
+ data: { type: "data", data: image.data },
4647
+ ...googleProviderMetadata({ interactionId })
4648
+ });
4649
+ } else if (image.uri != null && image.uri.length > 0) {
4650
+ content.push({
4651
+ type: "file",
4652
+ mediaType: (_d = image.mime_type) != null ? _d : "image/png",
4653
+ data: { type: "url", url: new URL(image.uri) },
4654
+ ...googleProviderMetadata({ interactionId })
4655
+ });
4656
+ }
4657
+ } else if (blockType === "video") {
4658
+ const video = block;
4659
+ if (video.data != null && video.data.length > 0) {
4660
+ content.push({
4661
+ type: "file",
4662
+ mediaType: (_e = video.mime_type) != null ? _e : "video/mp4",
4663
+ data: { type: "data", data: video.data },
4664
+ ...googleProviderMetadata({ interactionId })
4665
+ });
4666
+ } else if (video.uri != null && video.uri.length > 0) {
4667
+ content.push({
4668
+ type: "file",
4669
+ mediaType: (_f = video.mime_type) != null ? _f : "video/mp4",
4670
+ data: { type: "url", url: new URL(video.uri) },
4671
+ ...googleProviderMetadata({ interactionId })
4672
+ });
4673
+ }
4674
+ }
4675
+ }
4676
+ break;
4677
+ }
4678
+ case "thought": {
4679
+ const thought = step;
4680
+ const summary = Array.isArray(thought.summary) ? thought.summary : [];
4681
+ const text = summary.filter(
4682
+ (item) => (item == null ? void 0 : item.type) === "text" && typeof item.text === "string"
4683
+ ).map((item) => item.text).join("\n");
4684
+ content.push({
4685
+ type: "reasoning",
4686
+ text,
4687
+ ...googleProviderMetadata({
4688
+ signature: thought.signature,
4689
+ interactionId
4690
+ })
4691
+ });
4692
+ break;
4693
+ }
4694
+ case "function_call": {
4695
+ hasFunctionCall = true;
4696
+ const call = step;
4697
+ content.push({
4698
+ type: "tool-call",
4699
+ toolCallId: call.id,
4700
+ toolName: call.name,
4701
+ input: JSON.stringify((_g = call.arguments) != null ? _g : {}),
4702
+ ...googleProviderMetadata({
4703
+ signature: call.signature,
4704
+ interactionId
4705
+ })
4706
+ });
4707
+ break;
4708
+ }
4709
+ default: {
4710
+ if (BUILTIN_TOOL_CALL_TYPES2.has(type)) {
4711
+ const call = step;
4712
+ const toolName = type === "mcp_server_tool_call" ? (_h = call.name) != null ? _h : "mcp_server_tool" : builtinToolNameFromCallType2(type);
4713
+ const input = JSON.stringify((_i = call.arguments) != null ? _i : {});
4714
+ content.push({
4715
+ type: "tool-call",
4716
+ toolCallId: (_j = call.id) != null ? _j : generateId2(),
4717
+ toolName,
4718
+ input,
4719
+ providerExecuted: true
4720
+ });
4721
+ } else if (BUILTIN_TOOL_RESULT_TYPES2.has(type)) {
4722
+ const result = step;
4723
+ const toolName = type === "mcp_server_tool_result" ? (_k = result.name) != null ? _k : "mcp_server_tool" : builtinToolNameFromResultType2(type);
4724
+ content.push({
4725
+ type: "tool-result",
4726
+ toolCallId: (_l = result.call_id) != null ? _l : generateId2(),
4727
+ toolName,
4728
+ result: (_m = result.result) != null ? _m : null
4729
+ });
4730
+ const sources = builtinToolResultToSources({
4731
+ block: step,
4732
+ generateId: generateId2
4733
+ });
4734
+ for (const source of sources) {
4735
+ content.push(source);
4736
+ }
4737
+ }
4738
+ break;
4739
+ }
4740
+ }
4741
+ }
4742
+ return { content, hasFunctionCall };
4743
+ }
4744
+
4745
+ // src/interactions/poll-google-interactions.ts
4746
+ import {
4747
+ createJsonResponseHandler as createJsonResponseHandler3,
4748
+ delay,
4749
+ getFromApi,
4750
+ isAbortError
4751
+ } from "@ai-sdk/provider-utils";
4752
+
4753
+ // src/interactions/cancel-google-interaction.ts
4754
+ import {
4755
+ combineHeaders as combineHeaders3,
4756
+ getRuntimeEnvironmentUserAgent,
4757
+ withUserAgentSuffix
4758
+ } from "@ai-sdk/provider-utils";
4759
+ var getOriginalFetch = () => globalThis.fetch;
4760
+ async function cancelGoogleInteraction({
4761
+ baseURL,
4762
+ interactionId,
4763
+ headers,
4764
+ fetch = getOriginalFetch()
4765
+ }) {
4766
+ if (interactionId == null || interactionId.length === 0) {
4767
+ return;
4768
+ }
4769
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}/cancel`;
4770
+ try {
4771
+ const response = await fetch(url, {
4772
+ method: "POST",
4773
+ headers: withUserAgentSuffix(
4774
+ combineHeaders3({ "Content-Type": "application/json" }, headers),
4775
+ getRuntimeEnvironmentUserAgent()
4776
+ ),
4777
+ body: "{}"
4778
+ });
4779
+ try {
4780
+ await response.text();
4781
+ } catch (e) {
4782
+ }
4783
+ } catch (e) {
4784
+ }
4785
+ }
4786
+
4787
+ // src/interactions/poll-google-interactions.ts
4788
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]);
4789
+ function isTerminalStatus(status) {
4790
+ return status != null && TERMINAL_STATUSES.has(status);
4791
+ }
4792
+ var DEFAULT_INITIAL_DELAY_MS = 1e3;
4793
+ var DEFAULT_MAX_DELAY_MS = 1e4;
4794
+ var DEFAULT_TIMEOUT_MS = 30 * 60 * 1e3;
4795
+ async function pollGoogleInteractionUntilTerminal({
4796
+ baseURL,
4797
+ interactionId,
4798
+ headers,
4799
+ fetch,
4800
+ abortSignal,
4801
+ initialDelayMs = DEFAULT_INITIAL_DELAY_MS,
4802
+ maxDelayMs = DEFAULT_MAX_DELAY_MS,
4803
+ timeoutMs = DEFAULT_TIMEOUT_MS
4804
+ }) {
4805
+ if (interactionId == null || interactionId.length === 0) {
4806
+ throw new Error(
4807
+ "google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id."
4808
+ );
4809
+ }
4810
+ const startedAt = Date.now();
4811
+ let nextDelayMs = initialDelayMs;
4812
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4813
+ const cancelOnServer = () => cancelGoogleInteraction({ baseURL, interactionId, headers, fetch });
4814
+ try {
4815
+ while (true) {
4816
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
4817
+ await cancelOnServer();
4818
+ throw new DOMException("Polling was aborted", "AbortError");
4819
+ }
4820
+ if (Date.now() - startedAt > timeoutMs) {
4821
+ throw new Error(
4822
+ `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4823
+ );
4824
+ }
4825
+ await delay(nextDelayMs, { abortSignal });
4826
+ const {
4827
+ value: response,
4828
+ rawValue: rawResponse,
4829
+ responseHeaders
4830
+ } = await getFromApi({
4831
+ url,
4832
+ headers,
4833
+ failedResponseHandler: googleFailedResponseHandler,
4834
+ successfulResponseHandler: createJsonResponseHandler3(
4835
+ googleInteractionsResponseSchema
4836
+ ),
4837
+ abortSignal,
4838
+ fetch
4839
+ });
4840
+ if (isTerminalStatus(response.status)) {
4841
+ return { response, rawResponse, responseHeaders };
4842
+ }
4843
+ nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4844
+ }
4845
+ } catch (error) {
4846
+ if (isAbortError(error)) {
4847
+ await cancelOnServer();
4848
+ }
4849
+ throw error;
4850
+ }
4851
+ }
4852
+
4853
+ // src/interactions/prepare-google-interactions-tools.ts
4854
+ function prepareGoogleInteractionsTools({
4855
+ tools,
4856
+ toolChoice
4857
+ }) {
4858
+ var _a, _b, _c, _d;
4859
+ const toolWarnings = [];
4860
+ const normalized = (tools == null ? void 0 : tools.length) ? tools : void 0;
4861
+ if (normalized == null) {
4862
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
4863
+ }
4864
+ const interactionsTools = [];
4865
+ for (const tool of normalized) {
4866
+ if (tool.type === "function") {
4867
+ interactionsTools.push({
4868
+ type: "function",
4869
+ name: tool.name,
4870
+ description: (_a = tool.description) != null ? _a : "",
4871
+ parameters: tool.inputSchema
4872
+ });
4873
+ continue;
4874
+ }
4875
+ if (tool.type === "provider") {
4876
+ const args = (_b = tool.args) != null ? _b : {};
4877
+ switch (tool.id) {
4878
+ case "google.google_search": {
4879
+ const searchTypesArg = args.searchTypes;
4880
+ let search_types;
4881
+ if (searchTypesArg != null && typeof searchTypesArg === "object") {
4882
+ const list = [];
4883
+ if (searchTypesArg.webSearch != null) list.push("web_search");
4884
+ if (searchTypesArg.imageSearch != null) list.push("image_search");
4885
+ if (list.length > 0) {
4886
+ search_types = list;
4887
+ }
4888
+ }
4889
+ interactionsTools.push({
4890
+ type: "google_search",
4891
+ ...search_types != null ? { search_types } : {}
4892
+ });
4893
+ break;
4894
+ }
4895
+ case "google.code_execution": {
4896
+ interactionsTools.push({ type: "code_execution" });
4897
+ break;
4898
+ }
4899
+ case "google.url_context": {
4900
+ interactionsTools.push({ type: "url_context" });
4901
+ break;
4902
+ }
4903
+ case "google.file_search": {
4904
+ interactionsTools.push({
4905
+ type: "file_search",
4906
+ ...args.fileSearchStoreNames != null ? {
4907
+ file_search_store_names: args.fileSearchStoreNames
4908
+ } : {},
4909
+ ...args.topK != null ? { top_k: args.topK } : {},
4910
+ ...args.metadataFilter != null ? { metadata_filter: args.metadataFilter } : {}
4911
+ });
4912
+ break;
4913
+ }
4914
+ case "google.google_maps": {
4915
+ interactionsTools.push({
4916
+ type: "google_maps",
4917
+ ...args.latitude != null ? { latitude: args.latitude } : {},
4918
+ ...args.longitude != null ? { longitude: args.longitude } : {},
4919
+ ...args.enableWidget != null ? { enable_widget: args.enableWidget } : {}
4920
+ });
4921
+ break;
4922
+ }
4923
+ case "google.computer_use": {
4924
+ interactionsTools.push({
4925
+ type: "computer_use",
4926
+ environment: (_c = args.environment) != null ? _c : "browser",
4927
+ ...args.excludedPredefinedFunctions != null ? {
4928
+ excludedPredefinedFunctions: args.excludedPredefinedFunctions
4929
+ } : {}
4930
+ });
4931
+ break;
4932
+ }
4933
+ case "google.mcp_server": {
4934
+ interactionsTools.push({
4935
+ type: "mcp_server",
4936
+ ...args.name != null ? { name: args.name } : {},
4937
+ ...args.url != null ? { url: args.url } : {},
4938
+ ...args.headers != null ? { headers: args.headers } : {},
4939
+ ...args.allowedTools != null ? { allowed_tools: args.allowedTools } : {}
4940
+ });
4941
+ break;
4942
+ }
4943
+ case "google.retrieval": {
4944
+ const vertexAiSearchConfig = (_d = args.vertexAiSearchConfig) != null ? _d : void 0;
4945
+ interactionsTools.push({
4946
+ type: "retrieval",
4947
+ ...args.retrievalTypes != null ? {
4948
+ retrieval_types: args.retrievalTypes
4949
+ } : { retrieval_types: ["vertex_ai_search"] },
4950
+ ...vertexAiSearchConfig != null ? { vertex_ai_search_config: vertexAiSearchConfig } : {}
4951
+ });
4952
+ break;
4953
+ }
4954
+ default: {
4955
+ toolWarnings.push({
4956
+ type: "unsupported",
4957
+ feature: `provider-defined tool ${tool.id}`,
4958
+ details: `provider-defined tool ${tool.id} is not supported by google.interactions; tool dropped.`
4959
+ });
4960
+ break;
4961
+ }
4962
+ }
4963
+ continue;
4964
+ }
4965
+ toolWarnings.push({
4966
+ type: "unsupported",
4967
+ feature: `tool of type ${tool.type}`,
4968
+ details: "Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."
4969
+ });
4970
+ }
4971
+ const hasFunctionTool = interactionsTools.some((t) => t.type === "function");
4972
+ let mappedToolChoice;
4973
+ if (toolChoice != null && hasFunctionTool) {
4974
+ switch (toolChoice.type) {
4975
+ case "auto":
4976
+ mappedToolChoice = "auto";
4977
+ break;
4978
+ case "required":
4979
+ mappedToolChoice = "any";
4980
+ break;
4981
+ case "none":
4982
+ mappedToolChoice = "none";
4983
+ break;
4984
+ case "tool":
4985
+ mappedToolChoice = {
4986
+ allowed_tools: {
4987
+ mode: "validated",
4988
+ tools: [toolChoice.toolName]
4989
+ }
4990
+ };
4991
+ break;
4992
+ }
4993
+ }
4994
+ return {
4995
+ tools: interactionsTools.length > 0 ? interactionsTools : void 0,
4996
+ toolChoice: mappedToolChoice,
4997
+ toolWarnings
4998
+ };
4999
+ }
5000
+
5001
+ // src/interactions/stream-google-interactions.ts
5002
+ import {
5003
+ createEventSourceResponseHandler as createEventSourceResponseHandler2,
5004
+ delay as delay2,
5005
+ getFromApi as getFromApi2,
5006
+ isAbortError as isAbortError2
5007
+ } from "@ai-sdk/provider-utils";
5008
+ var DEFAULT_MAX_RETRIES = 3;
5009
+ var DEFAULT_RETRY_DELAY_MS = 500;
5010
+ function streamGoogleInteractionEvents({
5011
+ baseURL,
5012
+ interactionId,
5013
+ headers,
5014
+ fetch,
5015
+ abortSignal,
5016
+ maxRetries = DEFAULT_MAX_RETRIES,
5017
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS
5018
+ }) {
5019
+ if (interactionId.length === 0) {
5020
+ throw new Error(
5021
+ "google.interactions: cannot stream a background interaction without an id."
5022
+ );
5023
+ }
5024
+ const eventSourceHeaders = {
5025
+ ...headers,
5026
+ accept: "text/event-stream"
5027
+ };
5028
+ let lastEventId;
5029
+ let complete = false;
5030
+ let attempt = 0;
5031
+ let receivedAnyEventThisAttempt = false;
5032
+ let currentReader;
5033
+ const internalAbort = new AbortController();
5034
+ const upstreamAbortHandler = () => internalAbort.abort();
5035
+ if (abortSignal != null) {
5036
+ if (abortSignal.aborted) {
5037
+ internalAbort.abort();
5038
+ } else {
5039
+ abortSignal.addEventListener("abort", upstreamAbortHandler, {
5040
+ once: true
5041
+ });
5042
+ }
5043
+ }
5044
+ const effectiveSignal = internalAbort.signal;
5045
+ function buildUrl() {
5046
+ const base = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
5047
+ const params = new URLSearchParams({ stream: "true" });
5048
+ if (lastEventId != null) {
5049
+ params.set("last_event_id", lastEventId);
5050
+ }
5051
+ return `${base}?${params.toString()}`;
5052
+ }
5053
+ async function openReader() {
5054
+ const { value: stream } = await getFromApi2({
5055
+ url: buildUrl(),
5056
+ headers: eventSourceHeaders,
5057
+ failedResponseHandler: googleFailedResponseHandler,
5058
+ successfulResponseHandler: createEventSourceResponseHandler2(
5059
+ googleInteractionsEventSchema
5060
+ ),
5061
+ abortSignal: effectiveSignal,
5062
+ fetch
5063
+ });
5064
+ return stream.getReader();
5065
+ }
5066
+ return new ReadableStream({
5067
+ async start(controller) {
5068
+ try {
5069
+ while (!complete && !effectiveSignal.aborted) {
5070
+ if (currentReader == null) {
5071
+ try {
5072
+ currentReader = await openReader();
5073
+ receivedAnyEventThisAttempt = false;
5074
+ } catch (error) {
5075
+ if (isAbortError2(error) || effectiveSignal.aborted) {
5076
+ controller.error(error);
5077
+ return;
5078
+ }
5079
+ attempt++;
5080
+ if (attempt >= maxRetries) {
5081
+ controller.error(error);
5082
+ return;
5083
+ }
5084
+ await delay2(retryDelayMs * attempt, {
5085
+ abortSignal: effectiveSignal
5086
+ });
5087
+ continue;
5088
+ }
5089
+ }
5090
+ try {
5091
+ const { done, value } = await currentReader.read();
5092
+ if (done) {
5093
+ currentReader = void 0;
5094
+ if (complete) break;
5095
+ if (!receivedAnyEventThisAttempt) {
5096
+ attempt++;
5097
+ if (attempt >= maxRetries) {
5098
+ controller.error(
5099
+ new Error(
5100
+ "google.interactions: SSE stream closed without producing any events."
5101
+ )
5102
+ );
5103
+ return;
5104
+ }
5105
+ await delay2(retryDelayMs * attempt, {
5106
+ abortSignal: effectiveSignal
5107
+ });
5108
+ } else {
5109
+ attempt = 0;
5110
+ }
5111
+ continue;
5112
+ }
5113
+ receivedAnyEventThisAttempt = true;
5114
+ if (value.success) {
5115
+ const streamEvent = value.value;
5116
+ if (typeof streamEvent.event_id === "string" && streamEvent.event_id.length > 0) {
5117
+ lastEventId = streamEvent.event_id;
5118
+ }
5119
+ if (streamEvent.event_type === "interaction.completed" || streamEvent.event_type === "error") {
5120
+ complete = true;
5121
+ }
5122
+ }
5123
+ controller.enqueue(value);
5124
+ } catch (error) {
5125
+ if (isAbortError2(error) || effectiveSignal.aborted) {
5126
+ controller.error(error);
5127
+ return;
5128
+ }
5129
+ currentReader = void 0;
5130
+ attempt++;
5131
+ if (attempt >= maxRetries) {
5132
+ controller.error(error);
5133
+ return;
5134
+ }
5135
+ await delay2(retryDelayMs * attempt, {
5136
+ abortSignal: effectiveSignal
5137
+ });
5138
+ }
5139
+ }
5140
+ controller.close();
5141
+ } catch (error) {
5142
+ controller.error(error);
5143
+ } finally {
5144
+ if (abortSignal != null) {
5145
+ abortSignal.removeEventListener("abort", upstreamAbortHandler);
5146
+ }
5147
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
5148
+ });
5149
+ currentReader = void 0;
5150
+ if (effectiveSignal.aborted && !complete) {
5151
+ await cancelGoogleInteraction({
5152
+ baseURL,
5153
+ interactionId,
5154
+ headers,
5155
+ fetch
5156
+ });
5157
+ }
5158
+ }
5159
+ },
5160
+ cancel() {
5161
+ internalAbort.abort();
5162
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
5163
+ });
5164
+ currentReader = void 0;
5165
+ }
5166
+ });
5167
+ }
5168
+
5169
+ // src/interactions/synthesize-google-interactions-agent-stream.ts
5170
+ function synthesizeGoogleInteractionsAgentStream({
5171
+ response,
5172
+ warnings,
5173
+ generateId: generateId2,
5174
+ includeRawChunks,
5175
+ headerServiceTier
5176
+ }) {
5177
+ return new ReadableStream({
5178
+ start(controller) {
5179
+ var _a, _b, _c;
5180
+ controller.enqueue({ type: "stream-start", warnings });
5181
+ const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
5182
+ let timestamp;
5183
+ const created = response.created;
5184
+ if (typeof created === "string") {
5185
+ const parsed = new Date(created);
5186
+ if (!Number.isNaN(parsed.getTime())) {
5187
+ timestamp = parsed;
5188
+ }
5189
+ }
5190
+ controller.enqueue({
5191
+ type: "response-metadata",
5192
+ ...interactionId != null ? { id: interactionId } : {},
5193
+ modelId: (_a = response.model) != null ? _a : void 0,
5194
+ ...timestamp ? { timestamp } : {}
5195
+ });
5196
+ if (includeRawChunks) {
5197
+ controller.enqueue({ type: "raw", rawValue: response });
5198
+ }
5199
+ const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
5200
+ steps: (_b = response.steps) != null ? _b : null,
5201
+ generateId: generateId2,
5202
+ interactionId
5203
+ });
5204
+ let blockCounter = 0;
5205
+ const nextBlockId = () => `${interactionId != null ? interactionId : "agent"}:${blockCounter++}`;
5206
+ for (const part of content) {
5207
+ switch (part.type) {
5208
+ case "text": {
5209
+ const id = nextBlockId();
5210
+ const providerMetadata2 = part.providerMetadata;
5211
+ controller.enqueue({ type: "text-start", id });
5212
+ if (part.text.length > 0) {
5213
+ controller.enqueue({ type: "text-delta", id, delta: part.text });
5214
+ }
5215
+ controller.enqueue({
5216
+ type: "text-end",
5217
+ id,
5218
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
5219
+ });
5220
+ break;
5221
+ }
5222
+ case "reasoning": {
5223
+ const id = nextBlockId();
5224
+ const providerMetadata2 = part.providerMetadata;
5225
+ controller.enqueue({ type: "reasoning-start", id });
5226
+ if (part.text.length > 0) {
5227
+ controller.enqueue({
5228
+ type: "reasoning-delta",
5229
+ id,
5230
+ delta: part.text
5231
+ });
5232
+ }
5233
+ controller.enqueue({
5234
+ type: "reasoning-end",
5235
+ id,
5236
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
5237
+ });
5238
+ break;
5239
+ }
5240
+ case "tool-call": {
5241
+ const providerMetadata2 = part.providerMetadata;
5242
+ controller.enqueue({
5243
+ type: "tool-input-start",
5244
+ id: part.toolCallId,
5245
+ toolName: part.toolName,
5246
+ ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {}
5247
+ });
5248
+ controller.enqueue({
5249
+ type: "tool-input-delta",
5250
+ id: part.toolCallId,
5251
+ delta: part.input
5252
+ });
5253
+ controller.enqueue({
5254
+ type: "tool-input-end",
5255
+ id: part.toolCallId
5256
+ });
5257
+ controller.enqueue({
5258
+ type: "tool-call",
5259
+ toolCallId: part.toolCallId,
5260
+ toolName: part.toolName,
5261
+ input: part.input,
5262
+ ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {},
5263
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
5264
+ });
5265
+ break;
5266
+ }
5267
+ case "tool-result": {
5268
+ controller.enqueue({
5269
+ type: "tool-result",
5270
+ toolCallId: part.toolCallId,
5271
+ toolName: part.toolName,
5272
+ result: part.result
5273
+ });
5274
+ break;
5275
+ }
5276
+ case "source":
5277
+ case "file": {
5278
+ controller.enqueue(part);
5279
+ break;
5280
+ }
5281
+ default:
5282
+ break;
5283
+ }
5284
+ }
5285
+ const serviceTier = (_c = response.service_tier) != null ? _c : headerServiceTier;
5286
+ const finishReason = {
5287
+ unified: mapGoogleInteractionsFinishReason({
5288
+ status: response.status,
5289
+ hasFunctionCall
5290
+ }),
5291
+ raw: response.status
5292
+ };
5293
+ const providerMetadata = {
5294
+ google: {
5295
+ ...interactionId != null ? { interactionId } : {},
5296
+ ...serviceTier != null ? { serviceTier } : {}
5297
+ }
5298
+ };
5299
+ controller.enqueue({
5300
+ type: "finish",
5301
+ finishReason,
5302
+ usage: convertGoogleInteractionsUsage(response.usage),
5303
+ providerMetadata
5304
+ });
5305
+ controller.close();
5306
+ }
5307
+ });
5308
+ }
5309
+
5310
+ // src/interactions/google-interactions-language-model.ts
5311
+ var GoogleInteractionsLanguageModel = class _GoogleInteractionsLanguageModel {
5312
+ constructor(modelOrAgent, config) {
5313
+ this.specificationVersion = "v4";
5314
+ if (typeof modelOrAgent === "string") {
5315
+ this.modelId = modelOrAgent;
5316
+ this.agent = void 0;
5317
+ } else if ("managedAgent" in modelOrAgent) {
5318
+ this.modelId = modelOrAgent.managedAgent;
5319
+ this.agent = modelOrAgent.managedAgent;
5320
+ } else {
5321
+ this.modelId = modelOrAgent.agent;
5322
+ this.agent = modelOrAgent.agent;
5323
+ }
5324
+ this.config = config;
5325
+ }
5326
+ static [WORKFLOW_SERIALIZE3](model) {
5327
+ return {
5328
+ ...serializeModelOptions3({
5329
+ modelId: model.modelId,
5330
+ config: model.config
5331
+ }),
5332
+ agent: model.agent
5333
+ };
5334
+ }
5335
+ static [WORKFLOW_DESERIALIZE3](options) {
5336
+ return new _GoogleInteractionsLanguageModel(
5337
+ options.agent != null ? { agent: options.agent } : options.modelId,
5338
+ options.config
5339
+ );
5340
+ }
5341
+ get provider() {
5342
+ return this.config.provider;
5343
+ }
5344
+ get supportedUrls() {
5345
+ if (this.config.supportedUrls) {
5346
+ return this.config.supportedUrls();
5347
+ }
5348
+ return {
5349
+ "image/*": [/^https?:\/\/.+/],
5350
+ "application/pdf": [/^https?:\/\/.+/],
5351
+ "audio/*": [/^https?:\/\/.+/],
5352
+ "video/*": [
5353
+ /^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,
5354
+ /^https?:\/\/youtu\.be\/.+/,
5355
+ /^gs:\/\/.+/
5356
+ ]
5357
+ };
5358
+ }
5359
+ async getArgs(options) {
5360
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
5361
+ const warnings = [];
5362
+ const googleOptions = await parseProviderOptions3({
5363
+ provider: "google",
5364
+ providerOptions: options.providerOptions,
5365
+ schema: googleInteractionsLanguageModelOptions
5366
+ });
5367
+ const isAgent = this.agent != null;
5368
+ const hasTools = options.tools != null && options.tools.length > 0;
5369
+ let toolsForBody;
5370
+ let toolChoiceForBody;
5371
+ if (hasTools && isAgent) {
5372
+ warnings.push({
5373
+ type: "other",
5374
+ message: "google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body."
5375
+ });
5376
+ } else if (hasTools) {
5377
+ const prepared = prepareGoogleInteractionsTools({
5378
+ tools: options.tools,
5379
+ toolChoice: options.toolChoice
5380
+ });
5381
+ toolsForBody = prepared.tools;
5382
+ toolChoiceForBody = prepared.toolChoice;
5383
+ warnings.push(...prepared.toolWarnings);
5384
+ }
5385
+ const responseFormatEntries = [];
5386
+ if (((_a = options.responseFormat) == null ? void 0 : _a.type) === "json") {
5387
+ if (isAgent) {
5388
+ warnings.push({
5389
+ type: "other",
5390
+ message: "google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."
5391
+ });
5392
+ } else {
5393
+ const entry = {
5394
+ type: "text",
5395
+ mime_type: "application/json",
5396
+ ...options.responseFormat.schema != null ? { schema: options.responseFormat.schema } : {}
5397
+ };
5398
+ responseFormatEntries.push(entry);
5399
+ }
5400
+ }
5401
+ if ((googleOptions == null ? void 0 : googleOptions.responseFormat) != null) {
5402
+ for (const entry of googleOptions.responseFormat) {
5403
+ if (entry.type === "text") {
5404
+ responseFormatEntries.push(
5405
+ pruneUndefined({
5406
+ type: "text",
5407
+ mime_type: (_b = entry.mimeType) != null ? _b : void 0,
5408
+ schema: (_c = entry.schema) != null ? _c : void 0
5409
+ })
5410
+ );
5411
+ } else if (entry.type === "image") {
5412
+ responseFormatEntries.push(
5413
+ pruneUndefined({
5414
+ type: "image",
5415
+ mime_type: (_d = entry.mimeType) != null ? _d : void 0,
5416
+ aspect_ratio: (_e = entry.aspectRatio) != null ? _e : void 0,
5417
+ image_size: (_f = entry.imageSize) != null ? _f : void 0
5418
+ })
5419
+ );
5420
+ } else if (entry.type === "audio") {
5421
+ responseFormatEntries.push(
5422
+ pruneUndefined({
5423
+ type: "audio",
5424
+ mime_type: (_g = entry.mimeType) != null ? _g : void 0
5425
+ })
5426
+ );
5427
+ }
5428
+ }
5429
+ }
5430
+ const {
5431
+ input,
5432
+ systemInstruction: convertedSystemInstruction,
5433
+ warnings: convWarnings
5434
+ } = convertToGoogleInteractionsInput({
5435
+ prompt: options.prompt,
5436
+ previousInteractionId: (_h = googleOptions == null ? void 0 : googleOptions.previousInteractionId) != null ? _h : void 0,
5437
+ store: (_i = googleOptions == null ? void 0 : googleOptions.store) != null ? _i : void 0,
5438
+ mediaResolution: (_j = googleOptions == null ? void 0 : googleOptions.mediaResolution) != null ? _j : void 0
5439
+ });
5440
+ warnings.push(...convWarnings);
5441
+ let systemInstruction = convertedSystemInstruction;
5442
+ const optionSystemInstruction = (_k = googleOptions == null ? void 0 : googleOptions.systemInstruction) != null ? _k : void 0;
5443
+ if (systemInstruction != null && optionSystemInstruction != null) {
5444
+ warnings.push({
5445
+ type: "other",
5446
+ message: "google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."
5447
+ });
5448
+ } else if (systemInstruction == null && optionSystemInstruction != null) {
5449
+ systemInstruction = optionSystemInstruction;
5450
+ }
5451
+ let generationConfig;
5452
+ if (isAgent) {
5453
+ const droppedFields = [];
5454
+ if (options.temperature != null) droppedFields.push("temperature");
5455
+ if (options.topP != null) droppedFields.push("topP");
5456
+ if (options.seed != null) droppedFields.push("seed");
5457
+ if (options.stopSequences != null && options.stopSequences.length > 0) {
5458
+ droppedFields.push("stopSequences");
5459
+ }
5460
+ if (options.maxOutputTokens != null)
5461
+ droppedFields.push("maxOutputTokens");
5462
+ if ((googleOptions == null ? void 0 : googleOptions.thinkingLevel) != null)
5463
+ droppedFields.push("thinkingLevel");
5464
+ if ((googleOptions == null ? void 0 : googleOptions.thinkingSummaries) != null) {
5465
+ droppedFields.push("thinkingSummaries");
5466
+ }
5467
+ if ((googleOptions == null ? void 0 : googleOptions.imageConfig) != null) droppedFields.push("imageConfig");
5468
+ if (droppedFields.length > 0) {
5469
+ warnings.push({
5470
+ type: "other",
5471
+ 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.`
5472
+ });
5473
+ }
5474
+ generationConfig = void 0;
5475
+ } else {
5476
+ generationConfig = pruneUndefined({
5477
+ temperature: (_l = options.temperature) != null ? _l : void 0,
5478
+ top_p: (_m = options.topP) != null ? _m : void 0,
5479
+ seed: (_n = options.seed) != null ? _n : void 0,
5480
+ stop_sequences: options.stopSequences != null && options.stopSequences.length > 0 ? options.stopSequences : void 0,
5481
+ max_output_tokens: (_o = options.maxOutputTokens) != null ? _o : void 0,
5482
+ thinking_level: (_p = googleOptions == null ? void 0 : googleOptions.thinkingLevel) != null ? _p : void 0,
5483
+ thinking_summaries: (_q = googleOptions == null ? void 0 : googleOptions.thinkingSummaries) != null ? _q : void 0,
5484
+ tool_choice: toolChoiceForBody
5485
+ });
5486
+ if ((googleOptions == null ? void 0 : googleOptions.imageConfig) != null) {
5487
+ const alreadyHasImageEntry = responseFormatEntries.some(
5488
+ (entry) => entry.type === "image"
5489
+ );
5490
+ warnings.push({
5491
+ type: "other",
5492
+ message: alreadyHasImageEntry ? "google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively." : 'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'
5493
+ });
5494
+ if (!alreadyHasImageEntry) {
5495
+ responseFormatEntries.push({
5496
+ type: "image",
5497
+ mime_type: "image/png",
5498
+ ...googleOptions.imageConfig.aspectRatio != null ? { aspect_ratio: googleOptions.imageConfig.aspectRatio } : {},
5499
+ ...googleOptions.imageConfig.imageSize != null ? { image_size: googleOptions.imageConfig.imageSize } : {}
5500
+ });
5501
+ }
5502
+ }
5503
+ }
5504
+ let agentConfig;
5505
+ if (isAgent && (googleOptions == null ? void 0 : googleOptions.agentConfig) != null) {
5506
+ const agentConfigOptions = googleOptions.agentConfig;
5507
+ if (agentConfigOptions.type === "deep-research") {
5508
+ agentConfig = pruneUndefined({
5509
+ type: "deep-research",
5510
+ thinking_summaries: (_r = agentConfigOptions.thinkingSummaries) != null ? _r : void 0,
5511
+ visualization: (_s = agentConfigOptions.visualization) != null ? _s : void 0,
5512
+ collaborative_planning: (_t = agentConfigOptions.collaborativePlanning) != null ? _t : void 0
5513
+ });
5514
+ } else if (agentConfigOptions.type === "dynamic") {
5515
+ agentConfig = { type: "dynamic" };
5516
+ }
5517
+ }
5518
+ let environment;
5519
+ if ((googleOptions == null ? void 0 : googleOptions.environment) != null) {
5520
+ if (!isAgent) {
5521
+ warnings.push({
5522
+ type: "other",
5523
+ message: "google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."
5524
+ });
5525
+ } else if (typeof googleOptions.environment === "string") {
5526
+ environment = googleOptions.environment;
5527
+ } else {
5528
+ const environmentOptions = googleOptions.environment;
5529
+ const sources = (_u = environmentOptions.sources) == null ? void 0 : _u.map((source) => {
5530
+ var _a2;
5531
+ if (source.type === "inline") {
5532
+ return {
5533
+ type: "inline",
5534
+ content: source.content,
5535
+ target: source.target
5536
+ };
5537
+ }
5538
+ return pruneUndefined({
5539
+ type: source.type,
5540
+ source: source.source,
5541
+ target: (_a2 = source.target) != null ? _a2 : void 0
5542
+ });
5543
+ });
5544
+ let network;
5545
+ if (environmentOptions.network === "disabled") {
5546
+ network = "disabled";
5547
+ } else if (environmentOptions.network != null) {
5548
+ network = {
5549
+ allowlist: environmentOptions.network.allowlist.map(
5550
+ (entry) => {
5551
+ var _a2;
5552
+ return pruneUndefined({
5553
+ domain: entry.domain,
5554
+ transform: (_a2 = entry.transform) != null ? _a2 : void 0
5555
+ });
5556
+ }
5557
+ )
5558
+ };
5559
+ }
5560
+ environment = pruneUndefined({
5561
+ type: "remote",
5562
+ sources: sources != null && sources.length > 0 ? sources : void 0,
5563
+ network
5564
+ });
5565
+ }
5566
+ }
5567
+ const args = pruneUndefined({
5568
+ ...isAgent ? { agent: this.agent } : { model: this.modelId },
5569
+ input,
5570
+ system_instruction: systemInstruction,
5571
+ tools: toolsForBody,
5572
+ response_format: responseFormatEntries.length > 0 ? responseFormatEntries : void 0,
5573
+ response_modalities: (googleOptions == null ? void 0 : googleOptions.responseModalities) != null ? googleOptions.responseModalities : void 0,
5574
+ previous_interaction_id: (_v = googleOptions == null ? void 0 : googleOptions.previousInteractionId) != null ? _v : void 0,
5575
+ service_tier: (_w = googleOptions == null ? void 0 : googleOptions.serviceTier) != null ? _w : void 0,
5576
+ store: (_x = googleOptions == null ? void 0 : googleOptions.store) != null ? _x : void 0,
5577
+ generation_config: generationConfig != null && Object.keys(generationConfig).length > 0 ? generationConfig : void 0,
5578
+ agent_config: agentConfig,
5579
+ environment,
5580
+ background: (_y = googleOptions == null ? void 0 : googleOptions.background) != null ? _y : void 0
5581
+ });
5582
+ return {
5583
+ args,
5584
+ warnings,
5585
+ isAgent,
5586
+ isBackground: (googleOptions == null ? void 0 : googleOptions.background) === true,
5587
+ pollingTimeoutMs: (_z = googleOptions == null ? void 0 : googleOptions.pollingTimeoutMs) != null ? _z : void 0
5588
+ };
5589
+ }
5590
+ async doGenerate(options) {
5591
+ var _a, _b, _c, _d, _e, _f;
5592
+ const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5593
+ const url = `${this.config.baseURL}/interactions`;
5594
+ const mergedHeaders = combineHeaders4(
5595
+ this.config.headers ? await resolve3(this.config.headers) : void 0,
5596
+ options.headers
5597
+ );
5598
+ const postResult = await postJsonToApi3({
5599
+ url,
5600
+ headers: mergedHeaders,
5601
+ body: args,
5602
+ failedResponseHandler: googleFailedResponseHandler,
5603
+ successfulResponseHandler: createJsonResponseHandler4(
5604
+ googleInteractionsResponseSchema
5605
+ ),
5606
+ abortSignal: options.abortSignal,
5607
+ fetch: this.config.fetch
5608
+ });
5609
+ let {
5610
+ responseHeaders,
5611
+ value: response,
5612
+ rawValue: rawResponse
5613
+ } = postResult;
5614
+ if (isAgent && !isTerminalStatus(response.status)) {
5615
+ const polled = await pollGoogleInteractionUntilTerminal({
5616
+ baseURL: this.config.baseURL,
5617
+ interactionId: response.id,
5618
+ headers: mergedHeaders,
5619
+ fetch: this.config.fetch,
5620
+ abortSignal: options.abortSignal,
5621
+ timeoutMs: pollingTimeoutMs
5622
+ });
5623
+ response = polled.response;
5624
+ rawResponse = polled.rawResponse;
5625
+ responseHeaders = (_a = polled.responseHeaders) != null ? _a : responseHeaders;
5626
+ }
5627
+ const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
5628
+ const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
5629
+ steps: (_b = response.steps) != null ? _b : null,
5630
+ generateId: (_c = this.config.generateId) != null ? _c : defaultGenerateId,
5631
+ interactionId
5632
+ });
5633
+ const finishReason = {
5634
+ unified: mapGoogleInteractionsFinishReason({
5635
+ status: response.status,
5636
+ hasFunctionCall
5637
+ }),
5638
+ raw: response.status
5639
+ };
5640
+ const serviceTier = (_e = (_d = response.service_tier) != null ? _d : responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"]) != null ? _e : void 0;
5641
+ const outputTokensByModality = getGoogleInteractionsOutputTokensByModality(
5642
+ response.usage
5643
+ );
5644
+ const providerMetadata = {
5645
+ google: {
5646
+ ...interactionId != null ? { interactionId } : {},
5647
+ ...serviceTier != null ? { serviceTier } : {},
5648
+ ...outputTokensByModality != null ? { outputTokensByModality } : {}
5649
+ }
5650
+ };
5651
+ let timestamp;
5652
+ if (typeof response.created === "string") {
5653
+ const parsed = new Date(response.created);
5654
+ if (!Number.isNaN(parsed.getTime())) {
5655
+ timestamp = parsed;
5656
+ }
5657
+ }
5658
+ return {
5659
+ content,
5660
+ finishReason,
5661
+ usage: convertGoogleInteractionsUsage(response.usage),
5662
+ warnings,
5663
+ providerMetadata,
5664
+ request: { body: args },
5665
+ response: {
5666
+ headers: responseHeaders,
5667
+ body: rawResponse,
5668
+ ...interactionId != null ? { id: interactionId } : {},
5669
+ ...timestamp ? { timestamp } : {},
5670
+ modelId: (_f = response.model) != null ? _f : void 0
5671
+ }
5672
+ };
5673
+ }
5674
+ async doStream(options) {
5675
+ var _a;
5676
+ const { args, warnings, isBackground, pollingTimeoutMs } = await this.getArgs(options);
5677
+ const url = `${this.config.baseURL}/interactions`;
5678
+ const mergedHeaders = combineHeaders4(
5679
+ this.config.headers ? await resolve3(this.config.headers) : void 0,
5680
+ options.headers
5681
+ );
5682
+ if (isBackground) {
5683
+ return this.doStreamBackground({
5684
+ args,
5685
+ warnings,
5686
+ url,
5687
+ mergedHeaders,
5688
+ options,
5689
+ pollingTimeoutMs
5690
+ });
5691
+ }
5692
+ const body = { ...args, stream: true };
5693
+ const { responseHeaders, value: response } = await postJsonToApi3({
5694
+ url,
5695
+ headers: mergedHeaders,
5696
+ body,
5697
+ failedResponseHandler: googleFailedResponseHandler,
5698
+ successfulResponseHandler: createEventSourceResponseHandler3(
5699
+ googleInteractionsEventSchema
5700
+ ),
5701
+ abortSignal: options.abortSignal,
5702
+ fetch: this.config.fetch
5703
+ });
5704
+ const headerServiceTier = responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"];
5705
+ const transform = buildGoogleInteractionsStreamTransform({
5706
+ warnings,
5707
+ generateId: (_a = this.config.generateId) != null ? _a : defaultGenerateId,
5708
+ includeRawChunks: options.includeRawChunks,
5709
+ serviceTier: headerServiceTier
5710
+ });
5711
+ return {
5712
+ stream: response.pipeThrough(transform),
5713
+ request: { body },
5714
+ response: { headers: responseHeaders }
5715
+ };
5716
+ }
5717
+ /*
5718
+ * Drive the streaming surface for agent calls. Agents require
5719
+ * `background: true`, which is incompatible with `stream: true` on POST.
5720
+ *
5721
+ * Approach:
5722
+ * 1. POST `/interactions` with `background: true`. The response includes
5723
+ * the interaction id and an initial (usually non-terminal) status.
5724
+ * 2. If the POST status is already terminal (rare), synthesize a stream
5725
+ * from the polled outputs and we're done.
5726
+ * 3. Otherwise open `GET /interactions/{id}?stream=true` and pipe the
5727
+ * SSE events through `buildGoogleInteractionsStreamTransform` so the
5728
+ * consumer receives text deltas / thinking summaries / tool events as
5729
+ * they happen instead of all at once at the end.
5730
+ *
5731
+ * The SSE connection can drop while the agent idles between events
5732
+ * (`UND_ERR_BODY_TIMEOUT`); `streamGoogleInteractionEvents` handles the
5733
+ * reconnect-with-`last_event_id` loop transparently.
5734
+ */
5735
+ async doStreamBackground({
5736
+ args,
5737
+ warnings,
5738
+ url,
5739
+ mergedHeaders,
5740
+ options,
5741
+ pollingTimeoutMs
5742
+ }) {
5743
+ var _a, _b;
5744
+ const postResult = await postJsonToApi3({
5745
+ url,
5746
+ headers: mergedHeaders,
5747
+ body: args,
5748
+ failedResponseHandler: googleFailedResponseHandler,
5749
+ successfulResponseHandler: createJsonResponseHandler4(
5750
+ googleInteractionsResponseSchema
5751
+ ),
5752
+ abortSignal: options.abortSignal,
5753
+ fetch: this.config.fetch
5754
+ });
5755
+ const { responseHeaders: postHeaders, value: postResponse } = postResult;
5756
+ const interactionId = postResponse.id;
5757
+ if (interactionId == null || interactionId.length === 0) {
5758
+ throw new Error(
5759
+ "google.interactions: background POST response did not include an interaction id; cannot stream the result."
5760
+ );
5761
+ }
5762
+ const headerServiceTier = postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"];
5763
+ if (isTerminalStatus(postResponse.status)) {
5764
+ const synthesized = synthesizeGoogleInteractionsAgentStream({
5765
+ response: postResponse,
5766
+ warnings,
5767
+ generateId: (_a = this.config.generateId) != null ? _a : defaultGenerateId,
5768
+ includeRawChunks: options.includeRawChunks,
5769
+ headerServiceTier
5770
+ });
5771
+ return {
5772
+ stream: synthesized,
5773
+ request: { body: args },
5774
+ response: { headers: postHeaders }
5775
+ };
5776
+ }
5777
+ void pollingTimeoutMs;
5778
+ const events = streamGoogleInteractionEvents({
5779
+ baseURL: this.config.baseURL,
5780
+ interactionId,
5781
+ headers: mergedHeaders,
5782
+ fetch: this.config.fetch,
5783
+ abortSignal: options.abortSignal
5784
+ });
5785
+ const transform = buildGoogleInteractionsStreamTransform({
5786
+ warnings,
5787
+ generateId: (_b = this.config.generateId) != null ? _b : defaultGenerateId,
5788
+ includeRawChunks: options.includeRawChunks,
5789
+ serviceTier: headerServiceTier
5790
+ });
5791
+ return {
5792
+ stream: events.pipeThrough(transform),
5793
+ request: { body: args },
5794
+ response: { headers: postHeaders }
5795
+ };
5796
+ }
5797
+ };
5798
+ function pruneUndefined(obj) {
5799
+ const result = {};
5800
+ for (const [key, value] of Object.entries(obj)) {
5801
+ if (value === void 0) continue;
5802
+ result[key] = value;
5803
+ }
5804
+ return result;
5805
+ }
2893
5806
  export {
5807
+ GoogleInteractionsLanguageModel,
2894
5808
  GoogleLanguageModel,
2895
5809
  GoogleSpeechModel,
2896
5810
  getGroundingMetadataSchema,