@ai-sdk/google 4.0.5 → 4.0.6

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