@ai-sdk/google 3.0.89 → 3.0.91

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.
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  GoogleGenerativeAILanguageModel: () => GoogleGenerativeAILanguageModel,
24
+ GoogleInteractionsLanguageModel: () => GoogleInteractionsLanguageModel,
24
25
  getGroundingMetadataSchema: () => getGroundingMetadataSchema,
25
26
  getUrlContextMetadataSchema: () => getUrlContextMetadataSchema,
26
27
  googleTools: () => googleTools
@@ -294,6 +295,8 @@ function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId) {
294
295
  });
295
296
  break;
296
297
  case "image-data":
298
+ case "file-data": {
299
+ const topLevelMediaType = String(contentPart.mediaType).split("/")[0];
297
300
  parts.push(
298
301
  {
299
302
  inlineData: {
@@ -302,10 +305,11 @@ function appendLegacyToolResultParts(parts, toolName, outputValue, toolCallId) {
302
305
  }
303
306
  },
304
307
  {
305
- text: "Tool executed successfully and returned this image as a response"
308
+ text: `Tool executed successfully and returned this ${topLevelMediaType === "image" ? "image" : "file"} as a response`
306
309
  }
307
310
  );
308
311
  break;
312
+ }
309
313
  default:
310
314
  parts.push({ text: JSON.stringify(contentPart) });
311
315
  break;
@@ -507,7 +511,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
507
511
  name: part.toolName,
508
512
  response: {
509
513
  name: part.toolName,
510
- content: output.type === "execution-denied" ? (_e = output.reason) != null ? _e : "Tool execution denied." : output.value
514
+ content: output.type === "execution-denied" ? (_e = output.reason) != null ? _e : "Tool call execution denied." : output.value
511
515
  }
512
516
  }
513
517
  });
@@ -1236,6 +1240,12 @@ function mapGoogleGenerativeAIFinishReason({
1236
1240
  }
1237
1241
 
1238
1242
  // src/google-generative-ai-language-model.ts
1243
+ var configurableSafetySettingCategories = [
1244
+ "HARM_CATEGORY_HATE_SPEECH",
1245
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
1246
+ "HARM_CATEGORY_HARASSMENT",
1247
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT"
1248
+ ];
1239
1249
  var GoogleGenerativeAILanguageModel = class {
1240
1250
  constructor(modelId, config) {
1241
1251
  this.specificationVersion = "v3";
@@ -1266,7 +1276,7 @@ var GoogleGenerativeAILanguageModel = class {
1266
1276
  toolChoice,
1267
1277
  providerOptions
1268
1278
  }, { isStreaming = false } = {}) {
1269
- var _a, _b;
1279
+ var _a, _b, _c;
1270
1280
  const warnings = [];
1271
1281
  const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
1272
1282
  let googleOptions = await (0, import_provider_utils4.parseProviderOptions)({
@@ -1341,6 +1351,11 @@ var GoogleGenerativeAILanguageModel = class {
1341
1351
  isVertexProvider
1342
1352
  });
1343
1353
  const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a : false : void 0;
1354
+ const safetyThreshold = googleOptions == null ? void 0 : googleOptions.threshold;
1355
+ const safetySettings = (_b = googleOptions == null ? void 0 : googleOptions.safetySettings) != null ? _b : safetyThreshold != null ? configurableSafetySettingCategories.map((category) => ({
1356
+ category,
1357
+ threshold: safetyThreshold
1358
+ })) : void 0;
1344
1359
  const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
1345
1360
  ...googleToolConfig,
1346
1361
  ...streamFunctionCallArguments && {
@@ -1370,7 +1385,7 @@ var GoogleGenerativeAILanguageModel = class {
1370
1385
  responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
1371
1386
  // so this is needed as an escape hatch:
1372
1387
  // TODO convert into provider option
1373
- ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
1388
+ ((_c = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _c : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
1374
1389
  ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
1375
1390
  audioTimestamp: googleOptions.audioTimestamp
1376
1391
  },
@@ -1386,7 +1401,7 @@ var GoogleGenerativeAILanguageModel = class {
1386
1401
  },
1387
1402
  contents,
1388
1403
  systemInstruction: isGemmaModel ? void 0 : systemInstruction,
1389
- safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
1404
+ safetySettings,
1390
1405
  tools: googleTools2,
1391
1406
  toolConfig,
1392
1407
  cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
@@ -2444,9 +2459,2908 @@ var googleTools = {
2444
2459
  */
2445
2460
  vertexRagStore
2446
2461
  };
2462
+
2463
+ // src/interactions/google-interactions-language-model.ts
2464
+ var import_provider_utils18 = require("@ai-sdk/provider-utils");
2465
+
2466
+ // src/interactions/convert-google-interactions-usage.ts
2467
+ function convertGoogleInteractionsUsage(usage) {
2468
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2469
+ if (usage == null) {
2470
+ return {
2471
+ inputTokens: {
2472
+ total: void 0,
2473
+ noCache: void 0,
2474
+ cacheRead: void 0,
2475
+ cacheWrite: void 0
2476
+ },
2477
+ outputTokens: {
2478
+ total: void 0,
2479
+ text: void 0,
2480
+ reasoning: void 0
2481
+ },
2482
+ raw: void 0
2483
+ };
2484
+ }
2485
+ const totalInput = (_a = usage.total_input_tokens) != null ? _a : 0;
2486
+ const totalOutput = (_b = usage.total_output_tokens) != null ? _b : 0;
2487
+ const totalThought = (_c = usage.total_thought_tokens) != null ? _c : 0;
2488
+ const totalCached = (_d = usage.total_cached_tokens) != null ? _d : 0;
2489
+ return {
2490
+ inputTokens: {
2491
+ total: (_e = usage.total_input_tokens) != null ? _e : void 0,
2492
+ noCache: usage.total_input_tokens == null ? void 0 : totalInput - totalCached,
2493
+ cacheRead: (_f = usage.total_cached_tokens) != null ? _f : void 0,
2494
+ cacheWrite: void 0
2495
+ },
2496
+ outputTokens: {
2497
+ total: usage.total_output_tokens == null && usage.total_thought_tokens == null ? void 0 : totalOutput + totalThought,
2498
+ text: (_g = usage.total_output_tokens) != null ? _g : void 0,
2499
+ reasoning: (_h = usage.total_thought_tokens) != null ? _h : void 0
2500
+ },
2501
+ raw: usage
2502
+ };
2503
+ }
2504
+ function getGoogleInteractionsOutputTokensByModality(usage) {
2505
+ const byModality = usage == null ? void 0 : usage.output_tokens_by_modality;
2506
+ if (byModality == null) {
2507
+ return void 0;
2508
+ }
2509
+ const result = {};
2510
+ for (const entry of byModality) {
2511
+ if ((entry == null ? void 0 : entry.modality) != null && entry.tokens != null) {
2512
+ result[entry.modality] = entry.tokens;
2513
+ }
2514
+ }
2515
+ return Object.keys(result).length > 0 ? result : void 0;
2516
+ }
2517
+
2518
+ // src/interactions/extract-google-interactions-sources.ts
2519
+ var KNOWN_DOC_EXTENSIONS = {
2520
+ pdf: "application/pdf",
2521
+ txt: "text/plain",
2522
+ md: "text/markdown",
2523
+ markdown: "text/markdown",
2524
+ doc: "application/msword",
2525
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
2526
+ };
2527
+ function inferDocMediaType(uriOrName) {
2528
+ const lower = uriOrName.toLowerCase();
2529
+ for (const [ext, media] of Object.entries(KNOWN_DOC_EXTENSIONS)) {
2530
+ if (lower.endsWith(`.${ext}`)) return media;
2531
+ }
2532
+ return "application/octet-stream";
2533
+ }
2534
+ function basename(uriOrName) {
2535
+ const parts = uriOrName.split("/");
2536
+ const last = parts[parts.length - 1];
2537
+ return last && last.length > 0 ? last : void 0;
2538
+ }
2539
+ function annotationToSource({
2540
+ annotation,
2541
+ generateId: generateId2
2542
+ }) {
2543
+ var _a, _b, _c, _d, _e;
2544
+ switch (annotation.type) {
2545
+ case "url_citation": {
2546
+ const a = annotation;
2547
+ if (a.url == null || a.url.length === 0) return void 0;
2548
+ return {
2549
+ type: "source",
2550
+ sourceType: "url",
2551
+ id: generateId2(),
2552
+ url: a.url,
2553
+ ...a.title != null ? { title: a.title } : {}
2554
+ };
2555
+ }
2556
+ case "file_citation": {
2557
+ const a = annotation;
2558
+ const uri = (_b = (_a = a.url) != null ? _a : a.document_uri) != null ? _b : a.file_name;
2559
+ if (uri == null || uri.length === 0) return void 0;
2560
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
2561
+ return {
2562
+ type: "source",
2563
+ sourceType: "url",
2564
+ id: generateId2(),
2565
+ url: uri,
2566
+ ...a.file_name != null ? { title: a.file_name } : {}
2567
+ };
2568
+ }
2569
+ const filename = (_c = a.file_name) != null ? _c : basename(uri);
2570
+ const mediaType = inferDocMediaType(uri);
2571
+ return {
2572
+ type: "source",
2573
+ sourceType: "document",
2574
+ id: generateId2(),
2575
+ mediaType,
2576
+ title: (_e = (_d = a.file_name) != null ? _d : filename) != null ? _e : uri,
2577
+ ...filename != null ? { filename } : {}
2578
+ };
2579
+ }
2580
+ case "place_citation": {
2581
+ const a = annotation;
2582
+ if (a.url == null || a.url.length === 0) return void 0;
2583
+ return {
2584
+ type: "source",
2585
+ sourceType: "url",
2586
+ id: generateId2(),
2587
+ url: a.url,
2588
+ ...a.name != null ? { title: a.name } : {}
2589
+ };
2590
+ }
2591
+ default:
2592
+ return void 0;
2593
+ }
2594
+ }
2595
+ function builtinToolResultToSources({
2596
+ block,
2597
+ generateId: generateId2
2598
+ }) {
2599
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2600
+ const sources = [];
2601
+ switch (block.type) {
2602
+ case "url_context_result": {
2603
+ const result = (_a = block.result) != null ? _a : [];
2604
+ for (const entry of result) {
2605
+ if ((entry == null ? void 0 : entry.url) == null || entry.url.length === 0) continue;
2606
+ if (entry.status != null && entry.status !== "success") continue;
2607
+ sources.push({
2608
+ type: "source",
2609
+ sourceType: "url",
2610
+ id: generateId2(),
2611
+ url: entry.url
2612
+ });
2613
+ }
2614
+ break;
2615
+ }
2616
+ case "google_search_result": {
2617
+ const result = (_b = block.result) != null ? _b : [];
2618
+ for (const entry of result) {
2619
+ const url = entry == null ? void 0 : entry.url;
2620
+ if (url == null || url.length === 0) continue;
2621
+ sources.push({
2622
+ type: "source",
2623
+ sourceType: "url",
2624
+ id: generateId2(),
2625
+ url,
2626
+ ...entry.title != null ? { title: entry.title } : {}
2627
+ });
2628
+ }
2629
+ break;
2630
+ }
2631
+ case "google_maps_result": {
2632
+ const result = (_c = block.result) != null ? _c : [];
2633
+ for (const entry of result) {
2634
+ for (const place of (_d = entry.places) != null ? _d : []) {
2635
+ if (place.url == null || place.url.length === 0) continue;
2636
+ sources.push({
2637
+ type: "source",
2638
+ sourceType: "url",
2639
+ id: generateId2(),
2640
+ url: place.url,
2641
+ ...place.name != null ? { title: place.name } : {}
2642
+ });
2643
+ }
2644
+ }
2645
+ break;
2646
+ }
2647
+ case "file_search_result": {
2648
+ const result = (_e = block.result) != null ? _e : [];
2649
+ for (const raw of result) {
2650
+ if (raw == null || typeof raw !== "object") continue;
2651
+ const entry = raw;
2652
+ const uri = (_g = (_f = entry.url) != null ? _f : entry.document_uri) != null ? _g : entry.file_name;
2653
+ if (uri == null || uri.length === 0) continue;
2654
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
2655
+ sources.push({
2656
+ type: "source",
2657
+ sourceType: "url",
2658
+ id: generateId2(),
2659
+ url: uri,
2660
+ ...entry.title != null ? { title: entry.title } : {}
2661
+ });
2662
+ continue;
2663
+ }
2664
+ const filename = (_h = entry.file_name) != null ? _h : basename(uri);
2665
+ const mediaType = inferDocMediaType(uri);
2666
+ sources.push({
2667
+ type: "source",
2668
+ sourceType: "document",
2669
+ id: generateId2(),
2670
+ mediaType,
2671
+ title: (_k = (_j = (_i = entry.title) != null ? _i : entry.file_name) != null ? _j : filename) != null ? _k : uri,
2672
+ ...filename != null ? { filename } : {}
2673
+ });
2674
+ }
2675
+ break;
2676
+ }
2677
+ default:
2678
+ break;
2679
+ }
2680
+ return sources;
2681
+ }
2682
+ function annotationsToSources({
2683
+ annotations,
2684
+ generateId: generateId2
2685
+ }) {
2686
+ var _a;
2687
+ if (annotations == null) return [];
2688
+ const seen = /* @__PURE__ */ new Set();
2689
+ const sources = [];
2690
+ for (const annotation of annotations) {
2691
+ const source = annotationToSource({ annotation, generateId: generateId2 });
2692
+ if (source == null) continue;
2693
+ const key = source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a = source.filename) != null ? _a : source.title}`;
2694
+ if (seen.has(key)) continue;
2695
+ seen.add(key);
2696
+ sources.push(source);
2697
+ }
2698
+ return sources;
2699
+ }
2700
+
2701
+ // src/interactions/map-google-interactions-finish-reason.ts
2702
+ function mapGoogleInteractionsFinishReason({
2703
+ status,
2704
+ hasFunctionCall
2705
+ }) {
2706
+ switch (status) {
2707
+ case "completed":
2708
+ return hasFunctionCall ? "tool-calls" : "stop";
2709
+ case "requires_action":
2710
+ return "tool-calls";
2711
+ case "failed":
2712
+ return "error";
2713
+ case "incomplete":
2714
+ return "length";
2715
+ case "cancelled":
2716
+ return "other";
2717
+ case "in_progress":
2718
+ default:
2719
+ return "other";
2720
+ }
2721
+ }
2722
+
2723
+ // src/interactions/build-google-interactions-stream-transform.ts
2724
+ var BUILTIN_TOOL_CALL_TYPES = /* @__PURE__ */ new Set([
2725
+ "google_search_call",
2726
+ "code_execution_call",
2727
+ "url_context_call",
2728
+ "file_search_call",
2729
+ "google_maps_call",
2730
+ "mcp_server_tool_call"
2731
+ ]);
2732
+ var BUILTIN_TOOL_RESULT_TYPES = /* @__PURE__ */ new Set([
2733
+ "google_search_result",
2734
+ "code_execution_result",
2735
+ "url_context_result",
2736
+ "file_search_result",
2737
+ "google_maps_result",
2738
+ "mcp_server_tool_result"
2739
+ ]);
2740
+ function builtinToolNameFromCallType(type) {
2741
+ return type.replace(/_call$/, "");
2742
+ }
2743
+ function builtinToolNameFromResultType(type) {
2744
+ return type.replace(/_result$/, "");
2745
+ }
2746
+ function buildGoogleInteractionsStreamTransform({
2747
+ warnings,
2748
+ generateId: generateId2,
2749
+ includeRawChunks,
2750
+ serviceTier: headerServiceTier
2751
+ }) {
2752
+ let interactionId;
2753
+ let usage;
2754
+ let serviceTier = headerServiceTier;
2755
+ let finishStatus;
2756
+ let hasFunctionCall = false;
2757
+ const openBlocks = /* @__PURE__ */ new Map();
2758
+ const emittedSourceKeys = /* @__PURE__ */ new Set();
2759
+ function sourceKey(source) {
2760
+ var _a;
2761
+ return source.sourceType === "url" ? `url:${source.url}` : `doc:${(_a = source.filename) != null ? _a : source.title}`;
2762
+ }
2763
+ return new TransformStream({
2764
+ start(controller) {
2765
+ controller.enqueue({ type: "stream-start", warnings });
2766
+ },
2767
+ transform(chunk, controller) {
2768
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
2769
+ if (includeRawChunks) {
2770
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2771
+ }
2772
+ if (!chunk.success) {
2773
+ finishStatus = "failed";
2774
+ controller.enqueue({ type: "error", error: chunk.error });
2775
+ return;
2776
+ }
2777
+ const value = chunk.value;
2778
+ const eventType = value.event_type;
2779
+ switch (eventType) {
2780
+ case "interaction.created": {
2781
+ const event = value;
2782
+ const interaction = event.interaction;
2783
+ interactionId = (interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0 ? interaction.id : void 0;
2784
+ const created = interaction == null ? void 0 : interaction.created;
2785
+ let timestamp;
2786
+ if (typeof created === "string") {
2787
+ const parsed = new Date(created);
2788
+ if (!Number.isNaN(parsed.getTime())) {
2789
+ timestamp = parsed;
2790
+ }
2791
+ }
2792
+ controller.enqueue({
2793
+ type: "response-metadata",
2794
+ ...interactionId != null ? { id: interactionId } : {},
2795
+ modelId: interaction == null ? void 0 : interaction.model,
2796
+ ...timestamp ? { timestamp } : {}
2797
+ });
2798
+ break;
2799
+ }
2800
+ case "step.start": {
2801
+ const event = value;
2802
+ const step = event.step;
2803
+ const index = event.index;
2804
+ const blockId = `${interactionId != null ? interactionId : "interaction"}:${index}`;
2805
+ const stepType = step == null ? void 0 : step.type;
2806
+ if (stepType === "model_output") {
2807
+ const initial = (_a = step == null ? void 0 : step.content) == null ? void 0 : _a[0];
2808
+ if ((initial == null ? void 0 : initial.type) === "text") {
2809
+ openBlocks.set(index, {
2810
+ kind: "text",
2811
+ id: blockId,
2812
+ emittedSourceKeys: /* @__PURE__ */ new Set()
2813
+ });
2814
+ controller.enqueue({ type: "text-start", id: blockId });
2815
+ const initialSources = annotationsToSources({
2816
+ annotations: initial.annotations,
2817
+ generateId: generateId2
2818
+ });
2819
+ for (const source of initialSources) {
2820
+ const key = sourceKey(source);
2821
+ if (emittedSourceKeys.has(key)) continue;
2822
+ emittedSourceKeys.add(key);
2823
+ controller.enqueue(source);
2824
+ }
2825
+ } else if ((initial == null ? void 0 : initial.type) === "image") {
2826
+ openBlocks.set(index, {
2827
+ kind: "image",
2828
+ id: blockId,
2829
+ ...initial.data != null ? { data: initial.data } : {},
2830
+ ...initial.mime_type != null ? { mimeType: initial.mime_type } : {},
2831
+ ...initial.uri != null ? { uri: initial.uri } : {}
2832
+ });
2833
+ } else {
2834
+ openBlocks.set(index, {
2835
+ kind: "pending_model_output",
2836
+ id: blockId
2837
+ });
2838
+ }
2839
+ } else if (stepType === "thought") {
2840
+ const signature = step == null ? void 0 : step.signature;
2841
+ openBlocks.set(index, {
2842
+ kind: "reasoning",
2843
+ id: blockId,
2844
+ ...signature != null ? { signature } : {}
2845
+ });
2846
+ controller.enqueue({ type: "reasoning-start", id: blockId });
2847
+ if (Array.isArray(step == null ? void 0 : step.summary)) {
2848
+ for (const item of step.summary) {
2849
+ if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") {
2850
+ controller.enqueue({
2851
+ type: "reasoning-delta",
2852
+ id: blockId,
2853
+ delta: item.text
2854
+ });
2855
+ }
2856
+ }
2857
+ }
2858
+ } else if (stepType === "function_call") {
2859
+ const toolCallId = (_b = step == null ? void 0 : step.id) != null ? _b : blockId;
2860
+ const toolName = (_c = step == null ? void 0 : step.name) != null ? _c : "unknown";
2861
+ hasFunctionCall = true;
2862
+ const state = {
2863
+ kind: "function_call",
2864
+ id: blockId,
2865
+ toolCallId,
2866
+ toolName,
2867
+ argumentsAccum: "",
2868
+ ...(step == null ? void 0 : step.signature) != null ? { signature: step.signature } : {}
2869
+ };
2870
+ openBlocks.set(index, state);
2871
+ controller.enqueue({
2872
+ type: "tool-input-start",
2873
+ id: toolCallId,
2874
+ toolName
2875
+ });
2876
+ } else if (stepType != null && BUILTIN_TOOL_CALL_TYPES.has(stepType)) {
2877
+ const toolName = stepType === "mcp_server_tool_call" ? (_d = step == null ? void 0 : step.name) != null ? _d : "mcp_server_tool" : builtinToolNameFromCallType(stepType);
2878
+ const toolCallId = (_e = step == null ? void 0 : step.id) != null ? _e : blockId;
2879
+ const state = {
2880
+ kind: "builtin_tool_call",
2881
+ id: blockId,
2882
+ blockType: stepType,
2883
+ toolCallId,
2884
+ toolName,
2885
+ arguments: (_f = step == null ? void 0 : step.arguments) != null ? _f : {},
2886
+ callEmitted: false
2887
+ };
2888
+ openBlocks.set(index, state);
2889
+ } else if (stepType != null && BUILTIN_TOOL_RESULT_TYPES.has(stepType)) {
2890
+ const toolName = stepType === "mcp_server_tool_result" ? (_g = step == null ? void 0 : step.name) != null ? _g : "mcp_server_tool" : builtinToolNameFromResultType(stepType);
2891
+ const callId = (_h = step == null ? void 0 : step.call_id) != null ? _h : blockId;
2892
+ const state = {
2893
+ kind: "builtin_tool_result",
2894
+ id: blockId,
2895
+ blockType: stepType,
2896
+ callId,
2897
+ toolName,
2898
+ result: (_i = step == null ? void 0 : step.result) != null ? _i : null,
2899
+ ...(step == null ? void 0 : step.is_error) != null ? { isError: step.is_error } : {},
2900
+ resultEmitted: false
2901
+ };
2902
+ openBlocks.set(index, state);
2903
+ } else {
2904
+ openBlocks.set(index, { kind: "unknown", id: blockId });
2905
+ }
2906
+ break;
2907
+ }
2908
+ case "step.delta": {
2909
+ const event = value;
2910
+ let open = openBlocks.get(event.index);
2911
+ if (open == null) break;
2912
+ const dtype = (_j = event.delta) == null ? void 0 : _j.type;
2913
+ if (open.kind === "pending_model_output") {
2914
+ if (dtype === "text" || dtype === "text_annotation" || dtype === "text_annotation_delta") {
2915
+ const promoted = {
2916
+ kind: "text",
2917
+ id: open.id,
2918
+ emittedSourceKeys: /* @__PURE__ */ new Set()
2919
+ };
2920
+ openBlocks.set(event.index, promoted);
2921
+ open = promoted;
2922
+ controller.enqueue({ type: "text-start", id: promoted.id });
2923
+ }
2924
+ }
2925
+ if (dtype === "image" && (open.kind === "pending_model_output" || open.kind === "text" || open.kind === "image")) {
2926
+ const img = event.delta;
2927
+ const google = {};
2928
+ if (interactionId != null) google.interactionId = interactionId;
2929
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
2930
+ if ((img == null ? void 0 : img.data) != null && img.data.length > 0) {
2931
+ controller.enqueue({
2932
+ type: "file",
2933
+ mediaType: (_k = img.mime_type) != null ? _k : "image/png",
2934
+ data: img.data,
2935
+ ...providerMetadata ? { providerMetadata } : {}
2936
+ });
2937
+ } else if ((img == null ? void 0 : img.uri) != null && img.uri.length > 0) {
2938
+ const uriProviderMetadata = {
2939
+ google: {
2940
+ ...interactionId != null ? { interactionId } : {},
2941
+ imageUri: img.uri
2942
+ }
2943
+ };
2944
+ controller.enqueue({
2945
+ type: "file",
2946
+ mediaType: (_l = img.mime_type) != null ? _l : "image/png",
2947
+ data: "",
2948
+ providerMetadata: uriProviderMetadata
2949
+ });
2950
+ }
2951
+ if (open.kind === "image") {
2952
+ open.data = void 0;
2953
+ open.uri = void 0;
2954
+ }
2955
+ break;
2956
+ }
2957
+ if (dtype === "video" && (open.kind === "pending_model_output" || open.kind === "text")) {
2958
+ const videoDelta = event.delta;
2959
+ const google = {};
2960
+ if (interactionId != null) google.interactionId = interactionId;
2961
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
2962
+ if ((videoDelta == null ? void 0 : videoDelta.data) != null && videoDelta.data.length > 0) {
2963
+ controller.enqueue({
2964
+ type: "file",
2965
+ mediaType: (_m = videoDelta.mime_type) != null ? _m : "video/mp4",
2966
+ data: videoDelta.data,
2967
+ ...providerMetadata ? { providerMetadata } : {}
2968
+ });
2969
+ } else if ((videoDelta == null ? void 0 : videoDelta.uri) != null && videoDelta.uri.length > 0) {
2970
+ const uriProviderMetadata = {
2971
+ google: {
2972
+ ...interactionId != null ? { interactionId } : {},
2973
+ videoUri: videoDelta.uri
2974
+ }
2975
+ };
2976
+ controller.enqueue({
2977
+ type: "file",
2978
+ mediaType: (_n = videoDelta.mime_type) != null ? _n : "video/mp4",
2979
+ data: "",
2980
+ providerMetadata: uriProviderMetadata
2981
+ });
2982
+ }
2983
+ break;
2984
+ }
2985
+ const delta = event.delta;
2986
+ if (open.kind === "text" && (delta == null ? void 0 : delta.type) === "text") {
2987
+ const text = (_o = delta.text) != null ? _o : "";
2988
+ if (text.length > 0) {
2989
+ controller.enqueue({
2990
+ type: "text-delta",
2991
+ id: open.id,
2992
+ delta: text
2993
+ });
2994
+ }
2995
+ } else if (open.kind === "text" && ((delta == null ? void 0 : delta.type) === "text_annotation" || (delta == null ? void 0 : delta.type) === "text_annotation_delta")) {
2996
+ const sources = annotationsToSources({
2997
+ annotations: delta.annotations,
2998
+ generateId: generateId2
2999
+ });
3000
+ for (const source of sources) {
3001
+ const key = sourceKey(source);
3002
+ if (emittedSourceKeys.has(key)) continue;
3003
+ emittedSourceKeys.add(key);
3004
+ open.emittedSourceKeys.add(key);
3005
+ controller.enqueue(source);
3006
+ }
3007
+ } else if (open.kind === "image" && (delta == null ? void 0 : delta.type) === "image") {
3008
+ if (delta.data != null) open.data = delta.data;
3009
+ if (delta.mime_type != null) open.mimeType = delta.mime_type;
3010
+ if (delta.uri != null) open.uri = delta.uri;
3011
+ } else if (open.kind === "reasoning") {
3012
+ if ((delta == null ? void 0 : delta.type) === "thought_summary") {
3013
+ const item = delta.content;
3014
+ if ((item == null ? void 0 : item.type) === "text" && typeof item.text === "string") {
3015
+ controller.enqueue({
3016
+ type: "reasoning-delta",
3017
+ id: open.id,
3018
+ delta: item.text
3019
+ });
3020
+ }
3021
+ } else if ((delta == null ? void 0 : delta.type) === "thought_signature") {
3022
+ const signature = delta.signature;
3023
+ if (signature != null) {
3024
+ open.signature = signature;
3025
+ }
3026
+ }
3027
+ } else if (open.kind === "function_call" && (delta == null ? void 0 : delta.type) === "arguments_delta") {
3028
+ const slice = typeof delta.arguments === "string" ? delta.arguments : "";
3029
+ if (slice.length > 0) {
3030
+ open.argumentsAccum += slice;
3031
+ controller.enqueue({
3032
+ type: "tool-input-delta",
3033
+ id: open.toolCallId,
3034
+ delta: slice
3035
+ });
3036
+ }
3037
+ if (delta.id != null) {
3038
+ open.toolCallId = delta.id;
3039
+ }
3040
+ if (delta.signature != null) {
3041
+ open.signature = delta.signature;
3042
+ }
3043
+ hasFunctionCall = true;
3044
+ } else if (open.kind === "builtin_tool_call" && (delta == null ? void 0 : delta.type) === open.blockType) {
3045
+ if (delta.id != null) open.toolCallId = delta.id;
3046
+ if (delta.arguments != null && typeof delta.arguments === "object") {
3047
+ open.arguments = delta.arguments;
3048
+ }
3049
+ if (delta.name != null && open.blockType === "mcp_server_tool_call") {
3050
+ open.toolName = delta.name;
3051
+ }
3052
+ } else if (open.kind === "builtin_tool_result" && (delta == null ? void 0 : delta.type) === open.blockType) {
3053
+ if (delta.call_id != null) open.callId = delta.call_id;
3054
+ if (delta.result !== void 0) open.result = delta.result;
3055
+ if (delta.is_error != null) open.isError = delta.is_error;
3056
+ if (delta.name != null && open.blockType === "mcp_server_tool_result") {
3057
+ open.toolName = delta.name;
3058
+ }
3059
+ }
3060
+ break;
3061
+ }
3062
+ case "step.stop": {
3063
+ const event = value;
3064
+ const open = openBlocks.get(event.index);
3065
+ if (open == null) break;
3066
+ if (open.kind === "text") {
3067
+ const textProviderMetadata = interactionId != null ? { google: { interactionId } } : void 0;
3068
+ controller.enqueue({
3069
+ type: "text-end",
3070
+ id: open.id,
3071
+ ...textProviderMetadata ? { providerMetadata: textProviderMetadata } : {}
3072
+ });
3073
+ } else if (open.kind === "reasoning") {
3074
+ const google = {};
3075
+ if (open.signature != null) google.signature = open.signature;
3076
+ if (interactionId != null) google.interactionId = interactionId;
3077
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3078
+ controller.enqueue({
3079
+ type: "reasoning-end",
3080
+ id: open.id,
3081
+ ...providerMetadata ? { providerMetadata } : {}
3082
+ });
3083
+ } else if (open.kind === "image") {
3084
+ const google = {};
3085
+ if (interactionId != null) google.interactionId = interactionId;
3086
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3087
+ if (open.data != null && open.data.length > 0) {
3088
+ controller.enqueue({
3089
+ type: "file",
3090
+ mediaType: (_p = open.mimeType) != null ? _p : "image/png",
3091
+ data: open.data,
3092
+ ...providerMetadata ? { providerMetadata } : {}
3093
+ });
3094
+ } else if (open.uri != null && open.uri.length > 0) {
3095
+ const uriProviderMetadata = {
3096
+ google: {
3097
+ ...interactionId != null ? { interactionId } : {},
3098
+ imageUri: open.uri
3099
+ }
3100
+ };
3101
+ controller.enqueue({
3102
+ type: "file",
3103
+ mediaType: (_q = open.mimeType) != null ? _q : "image/png",
3104
+ data: "",
3105
+ providerMetadata: uriProviderMetadata
3106
+ });
3107
+ }
3108
+ } else if (open.kind === "function_call") {
3109
+ const accumulated = open.argumentsAccum.length > 0 ? open.argumentsAccum : "{}";
3110
+ controller.enqueue({
3111
+ type: "tool-input-end",
3112
+ id: open.toolCallId
3113
+ });
3114
+ const google = {};
3115
+ if (open.signature != null) google.signature = open.signature;
3116
+ if (interactionId != null) google.interactionId = interactionId;
3117
+ const providerMetadata = Object.keys(google).length > 0 ? { google } : void 0;
3118
+ controller.enqueue({
3119
+ type: "tool-call",
3120
+ toolCallId: open.toolCallId,
3121
+ toolName: open.toolName,
3122
+ input: accumulated,
3123
+ ...providerMetadata ? { providerMetadata } : {}
3124
+ });
3125
+ } else if (open.kind === "builtin_tool_call" && !open.callEmitted) {
3126
+ controller.enqueue({
3127
+ type: "tool-call",
3128
+ toolCallId: open.toolCallId,
3129
+ toolName: open.toolName,
3130
+ input: JSON.stringify((_r = open.arguments) != null ? _r : {}),
3131
+ providerExecuted: true
3132
+ });
3133
+ open.callEmitted = true;
3134
+ } else if (open.kind === "builtin_tool_result" && !open.resultEmitted) {
3135
+ controller.enqueue({
3136
+ type: "tool-result",
3137
+ toolCallId: open.callId,
3138
+ toolName: open.toolName,
3139
+ result: (_s = open.result) != null ? _s : null
3140
+ });
3141
+ open.resultEmitted = true;
3142
+ const sources = builtinToolResultToSources({
3143
+ block: {
3144
+ type: open.blockType,
3145
+ call_id: open.callId,
3146
+ result: open.result
3147
+ },
3148
+ generateId: generateId2
3149
+ });
3150
+ for (const source of sources) {
3151
+ const key = sourceKey(source);
3152
+ if (emittedSourceKeys.has(key)) continue;
3153
+ emittedSourceKeys.add(key);
3154
+ controller.enqueue(source);
3155
+ }
3156
+ }
3157
+ openBlocks.delete(event.index);
3158
+ break;
3159
+ }
3160
+ case "interaction.status_update":
3161
+ case "interaction.in_progress":
3162
+ case "interaction.requires_action": {
3163
+ const event = value;
3164
+ if (event.status != null) {
3165
+ finishStatus = event.status;
3166
+ } else if (eventType === "interaction.requires_action") {
3167
+ finishStatus = "requires_action";
3168
+ } else {
3169
+ finishStatus = "in_progress";
3170
+ }
3171
+ break;
3172
+ }
3173
+ case "interaction.completed": {
3174
+ const event = value;
3175
+ const interaction = event.interaction;
3176
+ if ((interaction == null ? void 0 : interaction.id) != null && interaction.id.length > 0) {
3177
+ interactionId = interaction.id;
3178
+ }
3179
+ if ((interaction == null ? void 0 : interaction.status) != null) {
3180
+ finishStatus = interaction.status;
3181
+ }
3182
+ if ((interaction == null ? void 0 : interaction.usage) != null) {
3183
+ usage = interaction.usage;
3184
+ }
3185
+ if ((interaction == null ? void 0 : interaction.service_tier) != null) {
3186
+ serviceTier = interaction.service_tier;
3187
+ }
3188
+ break;
3189
+ }
3190
+ case "error": {
3191
+ const event = value;
3192
+ finishStatus = "failed";
3193
+ const errorPayload = (_t = event.error) != null ? _t : {
3194
+ message: "Unknown interaction error"
3195
+ };
3196
+ controller.enqueue({ type: "error", error: errorPayload });
3197
+ break;
3198
+ }
3199
+ default:
3200
+ break;
3201
+ }
3202
+ },
3203
+ flush(controller) {
3204
+ const finishReason = {
3205
+ unified: mapGoogleInteractionsFinishReason({
3206
+ status: finishStatus,
3207
+ hasFunctionCall
3208
+ }),
3209
+ raw: finishStatus
3210
+ };
3211
+ const outputTokensByModality = getGoogleInteractionsOutputTokensByModality(usage);
3212
+ const providerMetadata = {
3213
+ google: {
3214
+ ...interactionId != null ? { interactionId } : {},
3215
+ ...serviceTier != null ? { serviceTier } : {},
3216
+ ...outputTokensByModality != null ? { outputTokensByModality } : {}
3217
+ }
3218
+ };
3219
+ controller.enqueue({
3220
+ type: "finish",
3221
+ finishReason,
3222
+ usage: convertGoogleInteractionsUsage(usage),
3223
+ providerMetadata
3224
+ });
3225
+ }
3226
+ });
3227
+ }
3228
+
3229
+ // src/interactions/convert-to-google-interactions-input.ts
3230
+ var import_provider_utils12 = require("@ai-sdk/provider-utils");
3231
+ function getTopLevelMediaType(mediaType) {
3232
+ const slashIndex = mediaType.indexOf("/");
3233
+ return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);
3234
+ }
3235
+ function isFullMediaType(mediaType) {
3236
+ const slashIndex = mediaType.indexOf("/");
3237
+ if (slashIndex === -1) {
3238
+ return false;
3239
+ }
3240
+ const subtype = mediaType.substring(slashIndex + 1);
3241
+ return subtype.length > 0 && subtype !== "*";
3242
+ }
3243
+ function convertToGoogleInteractionsInput({
3244
+ prompt,
3245
+ previousInteractionId,
3246
+ store,
3247
+ mediaResolution
3248
+ }) {
3249
+ var _a, _b, _c, _d, _e, _f, _g;
3250
+ const warnings = [];
3251
+ const incoherentCombo = previousInteractionId != null && store === false;
3252
+ const shouldCompact = previousInteractionId != null && store !== false;
3253
+ if (incoherentCombo) {
3254
+ warnings.push({
3255
+ type: "other",
3256
+ 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."
3257
+ });
3258
+ }
3259
+ const compactedPrompt = shouldCompact ? compactPromptForPreviousInteraction({
3260
+ prompt,
3261
+ previousInteractionId
3262
+ }) : prompt;
3263
+ const systemTexts = [];
3264
+ const steps = [];
3265
+ for (const message of compactedPrompt) {
3266
+ switch (message.role) {
3267
+ case "system": {
3268
+ systemTexts.push(message.content);
3269
+ break;
3270
+ }
3271
+ case "user": {
3272
+ const content = [];
3273
+ for (const part of message.content) {
3274
+ if (part.type === "text") {
3275
+ content.push({ type: "text", text: part.text });
3276
+ } else if (part.type === "file") {
3277
+ const fileBlock = convertFilePartToContent({
3278
+ part,
3279
+ warnings,
3280
+ mediaResolution
3281
+ });
3282
+ if (fileBlock != null) {
3283
+ content.push(fileBlock);
3284
+ }
3285
+ }
3286
+ }
3287
+ const merged = mergeAdjacentTextContent(content);
3288
+ if (merged.length > 0) {
3289
+ steps.push({ type: "user_input", content: merged });
3290
+ }
3291
+ break;
3292
+ }
3293
+ case "assistant": {
3294
+ let pendingModelOutput = [];
3295
+ const flushModelOutput = () => {
3296
+ if (pendingModelOutput.length > 0) {
3297
+ steps.push({ type: "model_output", content: pendingModelOutput });
3298
+ pendingModelOutput = [];
3299
+ }
3300
+ };
3301
+ for (const part of message.content) {
3302
+ if (part.type === "text") {
3303
+ pendingModelOutput.push({ type: "text", text: part.text });
3304
+ } else if (part.type === "reasoning") {
3305
+ flushModelOutput();
3306
+ const signature = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.signature;
3307
+ steps.push({
3308
+ type: "thought",
3309
+ ...signature != null ? { signature } : {},
3310
+ summary: part.text.length > 0 ? [{ type: "text", text: part.text }] : void 0
3311
+ });
3312
+ } else if (part.type === "file") {
3313
+ const fileBlock = convertFilePartToContent({
3314
+ part,
3315
+ warnings,
3316
+ mediaResolution
3317
+ });
3318
+ if (fileBlock != null) {
3319
+ pendingModelOutput.push(fileBlock);
3320
+ }
3321
+ } else if (part.type === "tool-call") {
3322
+ flushModelOutput();
3323
+ const signature = (_d = (_c = part.providerOptions) == null ? void 0 : _c.google) == null ? void 0 : _d.signature;
3324
+ const args = typeof part.input === "string" ? safeParseToolArgs(part.input) : (_e = part.input) != null ? _e : {};
3325
+ steps.push({
3326
+ type: "function_call",
3327
+ id: part.toolCallId,
3328
+ name: part.toolName,
3329
+ arguments: args,
3330
+ ...signature != null ? { signature } : {}
3331
+ });
3332
+ } else {
3333
+ warnings.push({
3334
+ type: "other",
3335
+ message: `google.interactions: unsupported assistant content part type "${part.type}"; part dropped.`
3336
+ });
3337
+ }
3338
+ }
3339
+ flushModelOutput();
3340
+ break;
3341
+ }
3342
+ case "tool": {
3343
+ const content = [];
3344
+ for (const part of message.content) {
3345
+ if (part.type !== "tool-result") {
3346
+ warnings.push({
3347
+ type: "other",
3348
+ message: `google.interactions: unsupported tool message part type "${part.type}"; part dropped.`
3349
+ });
3350
+ continue;
3351
+ }
3352
+ const block = convertToolResultPart({
3353
+ toolCallId: part.toolCallId,
3354
+ toolName: part.toolName,
3355
+ output: part.output,
3356
+ signature: (_g = (_f = part.providerOptions) == null ? void 0 : _f.google) == null ? void 0 : _g.signature,
3357
+ warnings
3358
+ });
3359
+ content.push(block);
3360
+ }
3361
+ if (content.length > 0) {
3362
+ steps.push({ type: "user_input", content });
3363
+ }
3364
+ break;
3365
+ }
3366
+ }
3367
+ }
3368
+ const systemInstruction = systemTexts.length > 0 ? systemTexts.join("\n\n") : void 0;
3369
+ return { input: steps, systemInstruction, warnings };
3370
+ }
3371
+ function convertFilePartToContent({
3372
+ part,
3373
+ warnings,
3374
+ mediaResolution
3375
+ }) {
3376
+ const topLevel = getTopLevelMediaType(part.mediaType);
3377
+ let kind;
3378
+ switch (topLevel) {
3379
+ case "image":
3380
+ kind = "image";
3381
+ break;
3382
+ case "audio":
3383
+ kind = "audio";
3384
+ break;
3385
+ case "video":
3386
+ kind = "video";
3387
+ break;
3388
+ case "application":
3389
+ kind = "document";
3390
+ break;
3391
+ default:
3392
+ kind = void 0;
3393
+ }
3394
+ if (kind == null) {
3395
+ warnings.push({
3396
+ type: "other",
3397
+ message: `google.interactions: unsupported file media type "${part.mediaType}"; part dropped.`
3398
+ });
3399
+ return void 0;
3400
+ }
3401
+ const resolutionField = mediaResolution != null && (kind === "image" || kind === "video") ? { resolution: mediaResolution } : {};
3402
+ if (part.data instanceof URL) {
3403
+ return {
3404
+ type: kind,
3405
+ uri: part.data.toString(),
3406
+ ...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {},
3407
+ ...resolutionField
3408
+ };
3409
+ }
3410
+ if (!isFullMediaType(part.mediaType)) {
3411
+ warnings.push({
3412
+ type: "other",
3413
+ message: `google.interactions: inline file data requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.`
3414
+ });
3415
+ return void 0;
3416
+ }
3417
+ return {
3418
+ type: kind,
3419
+ data: (0, import_provider_utils12.convertToBase64)(part.data),
3420
+ mime_type: part.mediaType,
3421
+ ...resolutionField
3422
+ };
3423
+ }
3424
+ function compactPromptForPreviousInteraction({
3425
+ prompt,
3426
+ previousInteractionId
3427
+ }) {
3428
+ const out = [];
3429
+ const droppedToolCallIds = /* @__PURE__ */ new Set();
3430
+ for (const message of prompt) {
3431
+ if (message.role === "assistant") {
3432
+ const matchesLinkedInteraction = message.content.some((part) => {
3433
+ var _a, _b;
3434
+ const partInteractionId = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.interactionId;
3435
+ return partInteractionId === previousInteractionId;
3436
+ });
3437
+ if (matchesLinkedInteraction) {
3438
+ for (const part of message.content) {
3439
+ if (part.type === "tool-call") {
3440
+ droppedToolCallIds.add(part.toolCallId);
3441
+ }
3442
+ }
3443
+ continue;
3444
+ }
3445
+ out.push(message);
3446
+ continue;
3447
+ }
3448
+ if (message.role === "tool") {
3449
+ const remaining = message.content.filter((part) => {
3450
+ if (part.type !== "tool-result") {
3451
+ return true;
3452
+ }
3453
+ return !droppedToolCallIds.has(part.toolCallId);
3454
+ });
3455
+ if (remaining.length === 0) {
3456
+ continue;
3457
+ }
3458
+ out.push({
3459
+ ...message,
3460
+ content: remaining
3461
+ });
3462
+ continue;
3463
+ }
3464
+ out.push(message);
3465
+ }
3466
+ return out;
3467
+ }
3468
+ function safeParseToolArgs(input) {
3469
+ try {
3470
+ const parsed = (0, import_provider_utils12.secureJsonParse)(input);
3471
+ if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) {
3472
+ return parsed;
3473
+ }
3474
+ return { value: parsed };
3475
+ } catch (e) {
3476
+ return { value: input };
3477
+ }
3478
+ }
3479
+ function convertToolResultPart({
3480
+ toolCallId,
3481
+ toolName,
3482
+ output,
3483
+ signature,
3484
+ warnings
3485
+ }) {
3486
+ var _a;
3487
+ const base = {
3488
+ type: "function_result",
3489
+ call_id: toolCallId,
3490
+ name: toolName,
3491
+ ...signature != null ? { signature } : {}
3492
+ };
3493
+ switch (output.type) {
3494
+ case "text":
3495
+ return { ...base, result: output.value };
3496
+ case "json":
3497
+ return { ...base, result: JSON.stringify(output.value) };
3498
+ case "error-text":
3499
+ return { ...base, is_error: true, result: output.value };
3500
+ case "error-json":
3501
+ return { ...base, is_error: true, result: JSON.stringify(output.value) };
3502
+ case "execution-denied":
3503
+ return {
3504
+ ...base,
3505
+ is_error: true,
3506
+ result: (_a = output.reason) != null ? _a : "Tool execution denied by user."
3507
+ };
3508
+ case "content": {
3509
+ const blocks = [];
3510
+ for (const item of output.value) {
3511
+ if (item.type === "text") {
3512
+ blocks.push({ type: "text", text: item.text });
3513
+ } else if (item.type === "image-data") {
3514
+ const imageBlock = filePartToImageBlock({
3515
+ part: {
3516
+ type: "file",
3517
+ mediaType: item.mediaType,
3518
+ data: item.data
3519
+ },
3520
+ warnings
3521
+ });
3522
+ if (imageBlock != null) {
3523
+ blocks.push(imageBlock);
3524
+ }
3525
+ } else if (item.type === "image-url") {
3526
+ const imageBlock = filePartToImageBlock({
3527
+ part: {
3528
+ type: "file",
3529
+ mediaType: "image/*",
3530
+ data: new URL(item.url)
3531
+ },
3532
+ warnings
3533
+ });
3534
+ if (imageBlock != null) {
3535
+ blocks.push(imageBlock);
3536
+ }
3537
+ } else if (item.type === "file-data" || item.type === "file-url") {
3538
+ const mediaType = item.type === "file-data" ? item.mediaType : "application/*";
3539
+ const topLevel = getTopLevelMediaType(mediaType);
3540
+ if (topLevel !== "image") {
3541
+ warnings.push({
3542
+ type: "other",
3543
+ message: `google.interactions: tool-result file with mediaType "${mediaType}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`
3544
+ });
3545
+ continue;
3546
+ }
3547
+ const imageBlock = filePartToImageBlock({
3548
+ part: item.type === "file-data" ? {
3549
+ type: "file",
3550
+ mediaType: item.mediaType,
3551
+ data: item.data
3552
+ } : {
3553
+ type: "file",
3554
+ mediaType,
3555
+ data: new URL(item.url)
3556
+ },
3557
+ warnings
3558
+ });
3559
+ if (imageBlock != null) {
3560
+ blocks.push(imageBlock);
3561
+ }
3562
+ } else {
3563
+ warnings.push({
3564
+ type: "other",
3565
+ message: `google.interactions: tool-result content part type "${item.type}" is not supported; part dropped.`
3566
+ });
3567
+ }
3568
+ }
3569
+ return { ...base, result: blocks };
3570
+ }
3571
+ }
3572
+ }
3573
+ function filePartToImageBlock({
3574
+ part,
3575
+ warnings
3576
+ }) {
3577
+ if (part.data instanceof URL) {
3578
+ return {
3579
+ type: "image",
3580
+ uri: part.data.toString(),
3581
+ ...isFullMediaType(part.mediaType) ? { mime_type: part.mediaType } : {}
3582
+ };
3583
+ }
3584
+ if (!isFullMediaType(part.mediaType)) {
3585
+ warnings.push({
3586
+ type: "other",
3587
+ message: `google.interactions: tool-result image part requires a full IANA media type (e.g. "image/png"), got "${part.mediaType}"; part dropped.`
3588
+ });
3589
+ return void 0;
3590
+ }
3591
+ return {
3592
+ type: "image",
3593
+ data: (0, import_provider_utils12.convertToBase64)(part.data),
3594
+ mime_type: part.mediaType
3595
+ };
3596
+ }
3597
+ function mergeAdjacentTextContent(content) {
3598
+ if (content.length < 2) {
3599
+ return content;
3600
+ }
3601
+ const result = [];
3602
+ for (const block of content) {
3603
+ const last = result[result.length - 1];
3604
+ if (block.type === "text" && last != null && last.type === "text" && last.annotations == null && block.annotations == null) {
3605
+ const merged = {
3606
+ type: "text",
3607
+ text: `${last.text}
3608
+
3609
+ ${block.text}`
3610
+ };
3611
+ result[result.length - 1] = merged;
3612
+ continue;
3613
+ }
3614
+ result.push(block);
3615
+ }
3616
+ return result;
3617
+ }
3618
+
3619
+ // src/interactions/google-interactions-api.ts
3620
+ var import_provider_utils13 = require("@ai-sdk/provider-utils");
3621
+ var import_v411 = require("zod/v4");
3622
+ var tokenByModalitySchema = () => import_v411.z.object({
3623
+ modality: import_v411.z.string().nullish(),
3624
+ tokens: import_v411.z.number().nullish()
3625
+ }).loose();
3626
+ var usageSchema2 = () => import_v411.z.object({
3627
+ total_input_tokens: import_v411.z.number().nullish(),
3628
+ total_output_tokens: import_v411.z.number().nullish(),
3629
+ total_thought_tokens: import_v411.z.number().nullish(),
3630
+ total_cached_tokens: import_v411.z.number().nullish(),
3631
+ total_tool_use_tokens: import_v411.z.number().nullish(),
3632
+ total_tokens: import_v411.z.number().nullish(),
3633
+ input_tokens_by_modality: import_v411.z.array(tokenByModalitySchema()).nullish(),
3634
+ output_tokens_by_modality: import_v411.z.array(tokenByModalitySchema()).nullish(),
3635
+ cached_tokens_by_modality: import_v411.z.array(tokenByModalitySchema()).nullish(),
3636
+ tool_use_tokens_by_modality: import_v411.z.array(tokenByModalitySchema()).nullish(),
3637
+ grounding_tool_count: import_v411.z.array(
3638
+ import_v411.z.object({
3639
+ type: import_v411.z.string().nullish(),
3640
+ count: import_v411.z.number().nullish()
3641
+ }).loose()
3642
+ ).nullish()
3643
+ }).loose();
3644
+ var interactionStatusSchema = () => import_v411.z.enum([
3645
+ "in_progress",
3646
+ "requires_action",
3647
+ "completed",
3648
+ "failed",
3649
+ "cancelled",
3650
+ "incomplete"
3651
+ ]);
3652
+ var annotationSchema = () => {
3653
+ const urlCitation = import_v411.z.object({
3654
+ type: import_v411.z.literal("url_citation"),
3655
+ url: import_v411.z.string().nullish(),
3656
+ title: import_v411.z.string().nullish(),
3657
+ start_index: import_v411.z.number().nullish(),
3658
+ end_index: import_v411.z.number().nullish()
3659
+ }).loose();
3660
+ const fileCitation = import_v411.z.object({
3661
+ type: import_v411.z.literal("file_citation"),
3662
+ file_name: import_v411.z.string().nullish(),
3663
+ document_uri: import_v411.z.string().nullish(),
3664
+ url: import_v411.z.string().nullish(),
3665
+ page_number: import_v411.z.number().nullish(),
3666
+ media_id: import_v411.z.string().nullish(),
3667
+ start_index: import_v411.z.number().nullish(),
3668
+ end_index: import_v411.z.number().nullish(),
3669
+ custom_metadata: import_v411.z.record(import_v411.z.string(), import_v411.z.unknown()).nullish()
3670
+ }).loose();
3671
+ const placeCitation = import_v411.z.object({
3672
+ type: import_v411.z.literal("place_citation"),
3673
+ name: import_v411.z.string().nullish(),
3674
+ url: import_v411.z.string().nullish(),
3675
+ place_id: import_v411.z.string().nullish(),
3676
+ start_index: import_v411.z.number().nullish(),
3677
+ end_index: import_v411.z.number().nullish()
3678
+ }).loose();
3679
+ return import_v411.z.union([
3680
+ urlCitation,
3681
+ fileCitation,
3682
+ placeCitation,
3683
+ import_v411.z.object({ type: import_v411.z.string() }).loose()
3684
+ ]);
3685
+ };
3686
+ var thoughtSummaryItemSchema = () => import_v411.z.object({
3687
+ type: import_v411.z.string(),
3688
+ text: import_v411.z.string().nullish(),
3689
+ data: import_v411.z.string().nullish(),
3690
+ mime_type: import_v411.z.string().nullish()
3691
+ }).loose();
3692
+ var contentBlockSchema = () => {
3693
+ const textContent = import_v411.z.object({
3694
+ type: import_v411.z.literal("text"),
3695
+ text: import_v411.z.string(),
3696
+ annotations: import_v411.z.array(annotationSchema()).nullish()
3697
+ }).loose();
3698
+ const imageContent = import_v411.z.object({
3699
+ type: import_v411.z.literal("image"),
3700
+ data: import_v411.z.string().nullish(),
3701
+ mime_type: import_v411.z.string().nullish(),
3702
+ resolution: import_v411.z.enum(["low", "medium", "high", "ultra_high"]).nullish(),
3703
+ uri: import_v411.z.string().nullish()
3704
+ }).loose();
3705
+ const videoContent = import_v411.z.object({
3706
+ type: import_v411.z.literal("video"),
3707
+ data: import_v411.z.string().nullish(),
3708
+ mime_type: import_v411.z.string().nullish(),
3709
+ uri: import_v411.z.string().nullish()
3710
+ }).loose();
3711
+ return import_v411.z.union([
3712
+ textContent,
3713
+ imageContent,
3714
+ videoContent,
3715
+ import_v411.z.object({ type: import_v411.z.string() }).loose()
3716
+ ]);
3717
+ };
3718
+ var BUILTIN_TOOL_CALL_STEP_TYPES = [
3719
+ "google_search_call",
3720
+ "code_execution_call",
3721
+ "url_context_call",
3722
+ "file_search_call",
3723
+ "google_maps_call",
3724
+ "mcp_server_tool_call"
3725
+ ];
3726
+ var BUILTIN_TOOL_RESULT_STEP_TYPES = [
3727
+ "google_search_result",
3728
+ "code_execution_result",
3729
+ "url_context_result",
3730
+ "file_search_result",
3731
+ "google_maps_result",
3732
+ "mcp_server_tool_result"
3733
+ ];
3734
+ var stepSchema = () => {
3735
+ const userInputStep = import_v411.z.object({
3736
+ type: import_v411.z.literal("user_input"),
3737
+ content: import_v411.z.array(contentBlockSchema()).nullish()
3738
+ }).loose();
3739
+ const modelOutputStep = import_v411.z.object({
3740
+ type: import_v411.z.literal("model_output"),
3741
+ content: import_v411.z.array(contentBlockSchema()).nullish()
3742
+ }).loose();
3743
+ const functionCallStep = import_v411.z.object({
3744
+ type: import_v411.z.literal("function_call"),
3745
+ id: import_v411.z.string(),
3746
+ name: import_v411.z.string(),
3747
+ arguments: import_v411.z.record(import_v411.z.string(), import_v411.z.unknown()).nullish(),
3748
+ signature: import_v411.z.string().nullish()
3749
+ }).loose();
3750
+ const thoughtStep = import_v411.z.object({
3751
+ type: import_v411.z.literal("thought"),
3752
+ signature: import_v411.z.string().nullish(),
3753
+ summary: import_v411.z.array(thoughtSummaryItemSchema()).nullish()
3754
+ }).loose();
3755
+ const builtinToolCallStep = import_v411.z.object({
3756
+ type: import_v411.z.enum(BUILTIN_TOOL_CALL_STEP_TYPES),
3757
+ id: import_v411.z.string(),
3758
+ arguments: import_v411.z.record(import_v411.z.string(), import_v411.z.unknown()).nullish(),
3759
+ name: import_v411.z.string().nullish(),
3760
+ server_name: import_v411.z.string().nullish(),
3761
+ search_type: import_v411.z.string().nullish(),
3762
+ signature: import_v411.z.string().nullish()
3763
+ }).loose();
3764
+ const builtinToolResultStep = import_v411.z.object({
3765
+ type: import_v411.z.enum(BUILTIN_TOOL_RESULT_STEP_TYPES),
3766
+ call_id: import_v411.z.string(),
3767
+ result: import_v411.z.unknown().nullish(),
3768
+ is_error: import_v411.z.boolean().nullish(),
3769
+ name: import_v411.z.string().nullish(),
3770
+ server_name: import_v411.z.string().nullish(),
3771
+ signature: import_v411.z.string().nullish()
3772
+ }).loose();
3773
+ return import_v411.z.union([
3774
+ userInputStep,
3775
+ modelOutputStep,
3776
+ functionCallStep,
3777
+ thoughtStep,
3778
+ builtinToolCallStep,
3779
+ builtinToolResultStep,
3780
+ import_v411.z.object({ type: import_v411.z.string() }).loose()
3781
+ ]);
3782
+ };
3783
+ var googleInteractionsResponseSchema = (0, import_provider_utils13.lazySchema)(
3784
+ () => (0, import_provider_utils13.zodSchema)(
3785
+ import_v411.z.object({
3786
+ /*
3787
+ * `id` is omitted from the response body when `store: false` (fully
3788
+ * stateless mode) — there is no server-side interaction record for the
3789
+ * client to reference. `nullish` lets the schema accept that shape.
3790
+ */
3791
+ id: import_v411.z.string().nullish(),
3792
+ created: import_v411.z.string().nullish(),
3793
+ updated: import_v411.z.string().nullish(),
3794
+ status: interactionStatusSchema(),
3795
+ model: import_v411.z.string().nullish(),
3796
+ agent: import_v411.z.string().nullish(),
3797
+ steps: import_v411.z.array(stepSchema()).nullish(),
3798
+ usage: usageSchema2().nullish(),
3799
+ service_tier: import_v411.z.string().nullish(),
3800
+ previous_interaction_id: import_v411.z.string().nullish(),
3801
+ response_modalities: import_v411.z.array(import_v411.z.string()).nullish()
3802
+ }).loose()
3803
+ )
3804
+ );
3805
+ var googleInteractionsEventSchema = (0, import_provider_utils13.lazySchema)(
3806
+ () => (0, import_provider_utils13.zodSchema)(
3807
+ (() => {
3808
+ const status = interactionStatusSchema();
3809
+ const annotation = annotationSchema();
3810
+ const thoughtSummaryItem = thoughtSummaryItemSchema();
3811
+ const interactionCreatedEvent = import_v411.z.object({
3812
+ event_type: import_v411.z.literal("interaction.created"),
3813
+ event_id: import_v411.z.string().nullish(),
3814
+ interaction: import_v411.z.object({
3815
+ /*
3816
+ * `id` is omitted when `store: false` (fully stateless mode);
3817
+ * see the matching note on `googleInteractionsResponseSchema.id`.
3818
+ */
3819
+ id: import_v411.z.string().nullish(),
3820
+ created: import_v411.z.string().nullish(),
3821
+ model: import_v411.z.string().nullish(),
3822
+ agent: import_v411.z.string().nullish(),
3823
+ status: status.nullish()
3824
+ }).loose()
3825
+ }).loose();
3826
+ const stepStartEvent = import_v411.z.object({
3827
+ event_type: import_v411.z.literal("step.start"),
3828
+ event_id: import_v411.z.string().nullish(),
3829
+ index: import_v411.z.number(),
3830
+ step: stepSchema()
3831
+ }).loose();
3832
+ const stepDeltaText = import_v411.z.object({
3833
+ type: import_v411.z.literal("text"),
3834
+ text: import_v411.z.string()
3835
+ }).loose();
3836
+ const stepDeltaThoughtSummary = import_v411.z.object({
3837
+ type: import_v411.z.literal("thought_summary"),
3838
+ content: thoughtSummaryItem.nullish()
3839
+ }).loose();
3840
+ const stepDeltaThoughtSignature = import_v411.z.object({
3841
+ type: import_v411.z.literal("thought_signature"),
3842
+ signature: import_v411.z.string().nullish()
3843
+ }).loose();
3844
+ const stepDeltaArgumentsDelta = import_v411.z.object({
3845
+ type: import_v411.z.literal("arguments_delta"),
3846
+ arguments: import_v411.z.string().nullish(),
3847
+ id: import_v411.z.string().nullish(),
3848
+ signature: import_v411.z.string().nullish()
3849
+ }).loose();
3850
+ const stepDeltaTextAnnotation = import_v411.z.object({
3851
+ type: import_v411.z.enum(["text_annotation_delta", "text_annotation"]),
3852
+ annotations: import_v411.z.array(annotation).nullish()
3853
+ }).loose();
3854
+ const stepDeltaImage = import_v411.z.object({
3855
+ type: import_v411.z.literal("image"),
3856
+ data: import_v411.z.string().nullish(),
3857
+ mime_type: import_v411.z.string().nullish(),
3858
+ resolution: import_v411.z.enum(["low", "medium", "high", "ultra_high"]).nullish(),
3859
+ uri: import_v411.z.string().nullish()
3860
+ }).loose();
3861
+ const stepDeltaVideo = import_v411.z.object({
3862
+ type: import_v411.z.literal("video"),
3863
+ data: import_v411.z.string().nullish(),
3864
+ mime_type: import_v411.z.string().nullish(),
3865
+ uri: import_v411.z.string().nullish()
3866
+ }).loose();
3867
+ const stepDeltaBuiltinToolCall = import_v411.z.object({
3868
+ type: import_v411.z.enum(BUILTIN_TOOL_CALL_STEP_TYPES),
3869
+ id: import_v411.z.string().nullish(),
3870
+ arguments: import_v411.z.record(import_v411.z.string(), import_v411.z.unknown()).nullish(),
3871
+ name: import_v411.z.string().nullish(),
3872
+ server_name: import_v411.z.string().nullish(),
3873
+ search_type: import_v411.z.string().nullish(),
3874
+ signature: import_v411.z.string().nullish()
3875
+ }).loose();
3876
+ const stepDeltaBuiltinToolResult = import_v411.z.object({
3877
+ type: import_v411.z.enum(BUILTIN_TOOL_RESULT_STEP_TYPES),
3878
+ call_id: import_v411.z.string().nullish(),
3879
+ result: import_v411.z.unknown().nullish(),
3880
+ is_error: import_v411.z.boolean().nullish(),
3881
+ name: import_v411.z.string().nullish(),
3882
+ server_name: import_v411.z.string().nullish(),
3883
+ signature: import_v411.z.string().nullish()
3884
+ }).loose();
3885
+ const stepDeltaUnknown = import_v411.z.object({ type: import_v411.z.string() }).loose();
3886
+ const stepDeltaUnion = import_v411.z.union([
3887
+ stepDeltaText,
3888
+ stepDeltaImage,
3889
+ stepDeltaVideo,
3890
+ stepDeltaThoughtSummary,
3891
+ stepDeltaThoughtSignature,
3892
+ stepDeltaArgumentsDelta,
3893
+ stepDeltaTextAnnotation,
3894
+ stepDeltaBuiltinToolCall,
3895
+ stepDeltaBuiltinToolResult,
3896
+ stepDeltaUnknown
3897
+ ]);
3898
+ const stepDeltaEvent = import_v411.z.object({
3899
+ event_type: import_v411.z.literal("step.delta"),
3900
+ event_id: import_v411.z.string().nullish(),
3901
+ index: import_v411.z.number(),
3902
+ delta: stepDeltaUnion
3903
+ }).loose();
3904
+ const stepStopEvent = import_v411.z.object({
3905
+ event_type: import_v411.z.literal("step.stop"),
3906
+ event_id: import_v411.z.string().nullish(),
3907
+ index: import_v411.z.number()
3908
+ }).loose();
3909
+ const interactionStatusUpdateEvent = import_v411.z.object({
3910
+ event_type: import_v411.z.literal("interaction.status_update"),
3911
+ event_id: import_v411.z.string().nullish(),
3912
+ interaction_id: import_v411.z.string().nullish(),
3913
+ status: status.nullish()
3914
+ }).loose();
3915
+ const interactionInProgressEvent = import_v411.z.object({
3916
+ event_type: import_v411.z.literal("interaction.in_progress"),
3917
+ event_id: import_v411.z.string().nullish(),
3918
+ interaction_id: import_v411.z.string().nullish(),
3919
+ status: status.nullish()
3920
+ }).loose();
3921
+ const interactionRequiresActionEvent = import_v411.z.object({
3922
+ event_type: import_v411.z.literal("interaction.requires_action"),
3923
+ event_id: import_v411.z.string().nullish(),
3924
+ interaction_id: import_v411.z.string().nullish(),
3925
+ status: status.nullish()
3926
+ }).loose();
3927
+ const interactionCompletedEvent = import_v411.z.object({
3928
+ event_type: import_v411.z.literal("interaction.completed"),
3929
+ event_id: import_v411.z.string().nullish(),
3930
+ interaction: import_v411.z.object({
3931
+ id: import_v411.z.string().nullish(),
3932
+ status: status.nullish(),
3933
+ usage: usageSchema2().nullish(),
3934
+ service_tier: import_v411.z.string().nullish()
3935
+ }).loose()
3936
+ }).loose();
3937
+ const errorEvent = import_v411.z.object({
3938
+ event_type: import_v411.z.literal("error"),
3939
+ event_id: import_v411.z.string().nullish(),
3940
+ error: import_v411.z.object({
3941
+ code: import_v411.z.string().nullish(),
3942
+ message: import_v411.z.string().nullish()
3943
+ }).loose().nullish()
3944
+ }).loose();
3945
+ const unknownEvent = import_v411.z.object({ event_type: import_v411.z.string() }).loose();
3946
+ return import_v411.z.union([
3947
+ interactionCreatedEvent,
3948
+ stepStartEvent,
3949
+ stepDeltaEvent,
3950
+ stepStopEvent,
3951
+ interactionStatusUpdateEvent,
3952
+ interactionInProgressEvent,
3953
+ interactionRequiresActionEvent,
3954
+ interactionCompletedEvent,
3955
+ errorEvent,
3956
+ unknownEvent
3957
+ ]);
3958
+ })()
3959
+ )
3960
+ );
3961
+
3962
+ // src/interactions/google-interactions-language-model-options.ts
3963
+ var import_provider_utils14 = require("@ai-sdk/provider-utils");
3964
+ var import_v412 = require("zod/v4");
3965
+ var googleInteractionsLanguageModelOptions = (0, import_provider_utils14.lazySchema)(
3966
+ () => (0, import_provider_utils14.zodSchema)(
3967
+ import_v412.z.object({
3968
+ previousInteractionId: import_v412.z.string().nullish(),
3969
+ store: import_v412.z.boolean().nullish(),
3970
+ agent: import_v412.z.string().nullish(),
3971
+ agentConfig: import_v412.z.union([
3972
+ import_v412.z.object({
3973
+ type: import_v412.z.literal("dynamic")
3974
+ }).loose(),
3975
+ import_v412.z.object({
3976
+ type: import_v412.z.literal("deep-research"),
3977
+ thinkingSummaries: import_v412.z.enum(["auto", "none"]).nullish(),
3978
+ visualization: import_v412.z.enum(["off", "auto"]).nullish(),
3979
+ collaborativePlanning: import_v412.z.boolean().nullish()
3980
+ })
3981
+ ]).nullish(),
3982
+ thinkingLevel: import_v412.z.enum(["minimal", "low", "medium", "high"]).nullish(),
3983
+ thinkingSummaries: import_v412.z.enum(["auto", "none"]).nullish(),
3984
+ /**
3985
+ * Output-format entries that map directly to the API's `response_format`
3986
+ * array. Use this to request image, audio, or non-JSON text outputs
3987
+ * with full control over `mime_type`, `aspect_ratio`, and `image_size`.
3988
+ *
3989
+ * Entries are sent in order. The AI SDK call-level `responseFormat: {
3990
+ * type: 'json', schema }` still drives JSON-mode and adds a matching
3991
+ * text entry automatically; entries listed here are appended.
3992
+ */
3993
+ responseFormat: import_v412.z.array(
3994
+ import_v412.z.union([
3995
+ import_v412.z.object({
3996
+ type: import_v412.z.literal("text"),
3997
+ mimeType: import_v412.z.string().nullish(),
3998
+ schema: import_v412.z.unknown().nullish()
3999
+ }).loose(),
4000
+ import_v412.z.object({
4001
+ type: import_v412.z.literal("image"),
4002
+ mimeType: import_v412.z.string().nullish(),
4003
+ aspectRatio: import_v412.z.enum([
4004
+ "1:1",
4005
+ "2:3",
4006
+ "3:2",
4007
+ "3:4",
4008
+ "4:3",
4009
+ "4:5",
4010
+ "5:4",
4011
+ "9:16",
4012
+ "16:9",
4013
+ "21:9",
4014
+ "1:8",
4015
+ "8:1",
4016
+ "1:4",
4017
+ "4:1"
4018
+ ]).nullish(),
4019
+ imageSize: import_v412.z.enum(["1K", "2K", "4K", "512"]).nullish()
4020
+ }).loose(),
4021
+ import_v412.z.object({
4022
+ type: import_v412.z.literal("audio"),
4023
+ mimeType: import_v412.z.string().nullish()
4024
+ }).loose()
4025
+ ])
4026
+ ).nullish(),
4027
+ /**
4028
+ * @deprecated Use `responseFormat` with a `{ type: 'image', ... }`
4029
+ * entry instead. Retained for backwards compatibility; the SDK
4030
+ * translates it into a matching `response_format` image entry and
4031
+ * emits a warning when set.
4032
+ */
4033
+ imageConfig: import_v412.z.object({
4034
+ aspectRatio: import_v412.z.enum([
4035
+ "1:1",
4036
+ "2:3",
4037
+ "3:2",
4038
+ "3:4",
4039
+ "4:3",
4040
+ "4:5",
4041
+ "5:4",
4042
+ "9:16",
4043
+ "16:9",
4044
+ "21:9",
4045
+ "1:8",
4046
+ "8:1",
4047
+ "1:4",
4048
+ "4:1"
4049
+ ]).nullish(),
4050
+ imageSize: import_v412.z.enum(["1K", "2K", "4K", "512"]).nullish()
4051
+ }).nullish(),
4052
+ mediaResolution: import_v412.z.enum(["low", "medium", "high", "ultra_high"]).nullish(),
4053
+ responseModalities: import_v412.z.array(import_v412.z.enum(["text", "image", "audio", "video", "document"])).nullish(),
4054
+ serviceTier: import_v412.z.enum(["flex", "standard", "priority"]).nullish(),
4055
+ /**
4056
+ * Alternative to AI SDK `system` message. If both are set, the AI SDK
4057
+ * `system` message wins and a warning is emitted.
4058
+ */
4059
+ systemInstruction: import_v412.z.string().nullish(),
4060
+ /**
4061
+ * Per-block signature for round-tripping `thought.signature` and
4062
+ * `function_call.signature` blocks. Set by the SDK on output reasoning /
4063
+ * tool-call parts; passed back unchanged on input parts so the API
4064
+ * accepts the prior turn.
4065
+ */
4066
+ signature: import_v412.z.string().nullish(),
4067
+ /**
4068
+ * Set by the SDK on output assistant messages. The converter uses it to
4069
+ * decide which messages to drop when compacting under
4070
+ * `previousInteractionId`.
4071
+ */
4072
+ interactionId: import_v412.z.string().nullish(),
4073
+ /**
4074
+ * Maximum time, in milliseconds, to poll a background interaction (agent
4075
+ * call) before giving up. Defaults to 30 minutes. Long-running agents
4076
+ * such as deep research can take tens of minutes — increase if needed.
4077
+ */
4078
+ pollingTimeoutMs: import_v412.z.number().int().positive().nullish(),
4079
+ /**
4080
+ * Run the interaction in the background. Required for agents whose
4081
+ * server-side workflow cannot complete within a single request/response.
4082
+ * When `true`, the POST returns with a non-terminal status and the SDK
4083
+ * polls `GET /interactions/{id}` until the work completes. Some agents
4084
+ * reject `true`; see the agent's documentation for which mode it
4085
+ * requires.
4086
+ */
4087
+ background: import_v412.z.boolean().nullish(),
4088
+ /**
4089
+ * Environment configuration for the agent sandbox. Only applies to agent
4090
+ * calls (`google.interactions({ agent })`); ignored on model-id calls.
4091
+ *
4092
+ * - `"remote"`: provision a fresh sandbox for this call.
4093
+ * - any other string: an existing `environment_id` to reuse.
4094
+ * - object: provision a fresh sandbox and optionally preload `sources`
4095
+ * and/or constrain outbound traffic via `network`.
4096
+ */
4097
+ environment: import_v412.z.union([
4098
+ import_v412.z.string(),
4099
+ import_v412.z.object({
4100
+ type: import_v412.z.literal("remote"),
4101
+ sources: import_v412.z.array(
4102
+ import_v412.z.union([
4103
+ import_v412.z.object({
4104
+ type: import_v412.z.literal("gcs"),
4105
+ source: import_v412.z.string(),
4106
+ target: import_v412.z.string().nullish()
4107
+ }),
4108
+ import_v412.z.object({
4109
+ type: import_v412.z.literal("repository"),
4110
+ source: import_v412.z.string(),
4111
+ target: import_v412.z.string().nullish()
4112
+ }),
4113
+ import_v412.z.object({
4114
+ type: import_v412.z.literal("inline"),
4115
+ content: import_v412.z.string(),
4116
+ target: import_v412.z.string()
4117
+ })
4118
+ ])
4119
+ ).nullish(),
4120
+ network: import_v412.z.union([
4121
+ import_v412.z.literal("disabled"),
4122
+ import_v412.z.object({
4123
+ allowlist: import_v412.z.array(
4124
+ import_v412.z.object({
4125
+ domain: import_v412.z.string(),
4126
+ transform: import_v412.z.array(import_v412.z.record(import_v412.z.string(), import_v412.z.string())).nullish()
4127
+ })
4128
+ )
4129
+ })
4130
+ ]).nullish()
4131
+ })
4132
+ ]).nullish()
4133
+ })
4134
+ )
4135
+ );
4136
+
4137
+ // src/interactions/parse-google-interactions-outputs.ts
4138
+ function googleProviderMetadata({
4139
+ signature,
4140
+ interactionId
4141
+ }) {
4142
+ const google = {};
4143
+ if (signature != null) {
4144
+ google.signature = signature;
4145
+ }
4146
+ if (interactionId != null) {
4147
+ google.interactionId = interactionId;
4148
+ }
4149
+ return Object.keys(google).length > 0 ? { providerMetadata: { google } } : {};
4150
+ }
4151
+ var BUILTIN_TOOL_CALL_TYPES2 = /* @__PURE__ */ new Set([
4152
+ "google_search_call",
4153
+ "code_execution_call",
4154
+ "url_context_call",
4155
+ "file_search_call",
4156
+ "google_maps_call",
4157
+ "mcp_server_tool_call"
4158
+ ]);
4159
+ var BUILTIN_TOOL_RESULT_TYPES2 = /* @__PURE__ */ new Set([
4160
+ "google_search_result",
4161
+ "code_execution_result",
4162
+ "url_context_result",
4163
+ "file_search_result",
4164
+ "google_maps_result",
4165
+ "mcp_server_tool_result"
4166
+ ]);
4167
+ function builtinToolNameFromCallType2(type) {
4168
+ return type.replace(/_call$/, "");
4169
+ }
4170
+ function builtinToolNameFromResultType2(type) {
4171
+ return type.replace(/_result$/, "");
4172
+ }
4173
+ function parseGoogleInteractionsOutputs({
4174
+ steps,
4175
+ generateId: generateId2,
4176
+ interactionId
4177
+ }) {
4178
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
4179
+ const content = [];
4180
+ let hasFunctionCall = false;
4181
+ if (steps == null) {
4182
+ return { content, hasFunctionCall };
4183
+ }
4184
+ for (const step of steps) {
4185
+ if (step == null || typeof step !== "object") continue;
4186
+ const type = step.type;
4187
+ if (typeof type !== "string") continue;
4188
+ switch (type) {
4189
+ case "user_input": {
4190
+ break;
4191
+ }
4192
+ case "model_output": {
4193
+ const blocks = (_a = step.content) != null ? _a : [];
4194
+ for (const block of blocks) {
4195
+ if (block == null || typeof block !== "object") continue;
4196
+ const blockType = block.type;
4197
+ if (blockType === "text") {
4198
+ const text = (_b = block.text) != null ? _b : "";
4199
+ const annotations = block.annotations;
4200
+ content.push({
4201
+ type: "text",
4202
+ text,
4203
+ ...googleProviderMetadata({ interactionId })
4204
+ });
4205
+ const sources = annotationsToSources({ annotations, generateId: generateId2 });
4206
+ for (const source of sources) {
4207
+ content.push(source);
4208
+ }
4209
+ } else if (blockType === "image") {
4210
+ const image = block;
4211
+ if (image.data != null && image.data.length > 0) {
4212
+ content.push({
4213
+ type: "file",
4214
+ mediaType: (_c = image.mime_type) != null ? _c : "image/png",
4215
+ data: image.data,
4216
+ ...googleProviderMetadata({ interactionId })
4217
+ });
4218
+ } else if (image.uri != null && image.uri.length > 0) {
4219
+ content.push({
4220
+ type: "file",
4221
+ mediaType: (_d = image.mime_type) != null ? _d : "image/png",
4222
+ data: "",
4223
+ providerMetadata: {
4224
+ google: {
4225
+ ...interactionId != null ? { interactionId } : {},
4226
+ imageUri: image.uri
4227
+ }
4228
+ }
4229
+ });
4230
+ }
4231
+ } else if (blockType === "video") {
4232
+ const video = block;
4233
+ if (video.data != null && video.data.length > 0) {
4234
+ content.push({
4235
+ type: "file",
4236
+ mediaType: (_e = video.mime_type) != null ? _e : "video/mp4",
4237
+ data: video.data,
4238
+ ...googleProviderMetadata({ interactionId })
4239
+ });
4240
+ } else if (video.uri != null && video.uri.length > 0) {
4241
+ content.push({
4242
+ type: "file",
4243
+ mediaType: (_f = video.mime_type) != null ? _f : "video/mp4",
4244
+ data: "",
4245
+ providerMetadata: {
4246
+ google: {
4247
+ ...interactionId != null ? { interactionId } : {},
4248
+ videoUri: video.uri
4249
+ }
4250
+ }
4251
+ });
4252
+ }
4253
+ }
4254
+ }
4255
+ break;
4256
+ }
4257
+ case "thought": {
4258
+ const thought = step;
4259
+ const summary = Array.isArray(thought.summary) ? thought.summary : [];
4260
+ const text = summary.filter(
4261
+ (item) => (item == null ? void 0 : item.type) === "text" && typeof item.text === "string"
4262
+ ).map((item) => item.text).join("\n");
4263
+ content.push({
4264
+ type: "reasoning",
4265
+ text,
4266
+ ...googleProviderMetadata({
4267
+ signature: thought.signature,
4268
+ interactionId
4269
+ })
4270
+ });
4271
+ break;
4272
+ }
4273
+ case "function_call": {
4274
+ hasFunctionCall = true;
4275
+ const call = step;
4276
+ content.push({
4277
+ type: "tool-call",
4278
+ toolCallId: call.id,
4279
+ toolName: call.name,
4280
+ input: JSON.stringify((_g = call.arguments) != null ? _g : {}),
4281
+ ...googleProviderMetadata({
4282
+ signature: call.signature,
4283
+ interactionId
4284
+ })
4285
+ });
4286
+ break;
4287
+ }
4288
+ default: {
4289
+ if (BUILTIN_TOOL_CALL_TYPES2.has(type)) {
4290
+ const call = step;
4291
+ const toolName = type === "mcp_server_tool_call" ? (_h = call.name) != null ? _h : "mcp_server_tool" : builtinToolNameFromCallType2(type);
4292
+ const input = JSON.stringify((_i = call.arguments) != null ? _i : {});
4293
+ content.push({
4294
+ type: "tool-call",
4295
+ toolCallId: (_j = call.id) != null ? _j : generateId2(),
4296
+ toolName,
4297
+ input,
4298
+ providerExecuted: true
4299
+ });
4300
+ } else if (BUILTIN_TOOL_RESULT_TYPES2.has(type)) {
4301
+ const result = step;
4302
+ const toolName = type === "mcp_server_tool_result" ? (_k = result.name) != null ? _k : "mcp_server_tool" : builtinToolNameFromResultType2(type);
4303
+ content.push({
4304
+ type: "tool-result",
4305
+ toolCallId: (_l = result.call_id) != null ? _l : generateId2(),
4306
+ toolName,
4307
+ result: (_m = result.result) != null ? _m : null
4308
+ });
4309
+ const sources = builtinToolResultToSources({
4310
+ block: step,
4311
+ generateId: generateId2
4312
+ });
4313
+ for (const source of sources) {
4314
+ content.push(source);
4315
+ }
4316
+ }
4317
+ break;
4318
+ }
4319
+ }
4320
+ }
4321
+ return { content, hasFunctionCall };
4322
+ }
4323
+
4324
+ // src/interactions/poll-google-interactions.ts
4325
+ var import_provider_utils16 = require("@ai-sdk/provider-utils");
4326
+
4327
+ // src/interactions/cancel-google-interaction.ts
4328
+ var import_provider_utils15 = require("@ai-sdk/provider-utils");
4329
+ var getOriginalFetch = () => globalThis.fetch;
4330
+ async function cancelGoogleInteraction({
4331
+ baseURL,
4332
+ interactionId,
4333
+ headers,
4334
+ fetch = getOriginalFetch()
4335
+ }) {
4336
+ if (interactionId == null || interactionId.length === 0) {
4337
+ return;
4338
+ }
4339
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}/cancel`;
4340
+ try {
4341
+ const response = await fetch(url, {
4342
+ method: "POST",
4343
+ headers: (0, import_provider_utils15.withUserAgentSuffix)(
4344
+ (0, import_provider_utils15.combineHeaders)({ "Content-Type": "application/json" }, headers),
4345
+ (0, import_provider_utils15.getRuntimeEnvironmentUserAgent)()
4346
+ ),
4347
+ body: "{}"
4348
+ });
4349
+ try {
4350
+ await response.text();
4351
+ } catch (e) {
4352
+ }
4353
+ } catch (e) {
4354
+ }
4355
+ }
4356
+
4357
+ // src/interactions/poll-google-interactions.ts
4358
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]);
4359
+ function isTerminalStatus(status) {
4360
+ return status != null && TERMINAL_STATUSES.has(status);
4361
+ }
4362
+ var DEFAULT_INITIAL_DELAY_MS = 1e3;
4363
+ var DEFAULT_MAX_DELAY_MS = 1e4;
4364
+ var DEFAULT_TIMEOUT_MS = 30 * 60 * 1e3;
4365
+ async function pollGoogleInteractionUntilTerminal({
4366
+ baseURL,
4367
+ interactionId,
4368
+ headers,
4369
+ fetch,
4370
+ abortSignal,
4371
+ initialDelayMs = DEFAULT_INITIAL_DELAY_MS,
4372
+ maxDelayMs = DEFAULT_MAX_DELAY_MS,
4373
+ timeoutMs = DEFAULT_TIMEOUT_MS
4374
+ }) {
4375
+ if (interactionId == null || interactionId.length === 0) {
4376
+ throw new Error(
4377
+ "google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id."
4378
+ );
4379
+ }
4380
+ const startedAt = Date.now();
4381
+ let nextDelayMs = initialDelayMs;
4382
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4383
+ const cancelOnServer = () => cancelGoogleInteraction({ baseURL, interactionId, headers, fetch });
4384
+ try {
4385
+ while (true) {
4386
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
4387
+ await cancelOnServer();
4388
+ throw new DOMException("Polling was aborted", "AbortError");
4389
+ }
4390
+ if (Date.now() - startedAt > timeoutMs) {
4391
+ throw new Error(
4392
+ `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4393
+ );
4394
+ }
4395
+ await (0, import_provider_utils16.delay)(nextDelayMs, { abortSignal });
4396
+ const {
4397
+ value: response,
4398
+ rawValue: rawResponse,
4399
+ responseHeaders
4400
+ } = await (0, import_provider_utils16.getFromApi)({
4401
+ url,
4402
+ headers,
4403
+ failedResponseHandler: googleFailedResponseHandler,
4404
+ successfulResponseHandler: (0, import_provider_utils16.createJsonResponseHandler)(
4405
+ googleInteractionsResponseSchema
4406
+ ),
4407
+ abortSignal,
4408
+ fetch
4409
+ });
4410
+ if (isTerminalStatus(response.status)) {
4411
+ return { response, rawResponse, responseHeaders };
4412
+ }
4413
+ nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4414
+ }
4415
+ } catch (error) {
4416
+ if ((0, import_provider_utils16.isAbortError)(error)) {
4417
+ await cancelOnServer();
4418
+ }
4419
+ throw error;
4420
+ }
4421
+ }
4422
+
4423
+ // src/interactions/prepare-google-interactions-tools.ts
4424
+ function prepareGoogleInteractionsTools({
4425
+ tools,
4426
+ toolChoice
4427
+ }) {
4428
+ var _a, _b, _c, _d;
4429
+ const toolWarnings = [];
4430
+ const normalized = (tools == null ? void 0 : tools.length) ? tools : void 0;
4431
+ if (normalized == null) {
4432
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
4433
+ }
4434
+ const interactionsTools = [];
4435
+ for (const tool of normalized) {
4436
+ if (tool.type === "function") {
4437
+ interactionsTools.push({
4438
+ type: "function",
4439
+ name: tool.name,
4440
+ description: (_a = tool.description) != null ? _a : "",
4441
+ parameters: tool.inputSchema
4442
+ });
4443
+ continue;
4444
+ }
4445
+ if (tool.type === "provider") {
4446
+ const args = (_b = tool.args) != null ? _b : {};
4447
+ switch (tool.id) {
4448
+ case "google.google_search": {
4449
+ const searchTypesArg = args.searchTypes;
4450
+ let search_types;
4451
+ if (searchTypesArg != null && typeof searchTypesArg === "object") {
4452
+ const list = [];
4453
+ if (searchTypesArg.webSearch != null) list.push("web_search");
4454
+ if (searchTypesArg.imageSearch != null) list.push("image_search");
4455
+ if (list.length > 0) {
4456
+ search_types = list;
4457
+ }
4458
+ }
4459
+ interactionsTools.push({
4460
+ type: "google_search",
4461
+ ...search_types != null ? { search_types } : {}
4462
+ });
4463
+ break;
4464
+ }
4465
+ case "google.code_execution": {
4466
+ interactionsTools.push({ type: "code_execution" });
4467
+ break;
4468
+ }
4469
+ case "google.url_context": {
4470
+ interactionsTools.push({ type: "url_context" });
4471
+ break;
4472
+ }
4473
+ case "google.file_search": {
4474
+ interactionsTools.push({
4475
+ type: "file_search",
4476
+ ...args.fileSearchStoreNames != null ? {
4477
+ file_search_store_names: args.fileSearchStoreNames
4478
+ } : {},
4479
+ ...args.topK != null ? { top_k: args.topK } : {},
4480
+ ...args.metadataFilter != null ? { metadata_filter: args.metadataFilter } : {}
4481
+ });
4482
+ break;
4483
+ }
4484
+ case "google.google_maps": {
4485
+ interactionsTools.push({
4486
+ type: "google_maps",
4487
+ ...args.latitude != null ? { latitude: args.latitude } : {},
4488
+ ...args.longitude != null ? { longitude: args.longitude } : {},
4489
+ ...args.enableWidget != null ? { enable_widget: args.enableWidget } : {}
4490
+ });
4491
+ break;
4492
+ }
4493
+ case "google.computer_use": {
4494
+ interactionsTools.push({
4495
+ type: "computer_use",
4496
+ environment: (_c = args.environment) != null ? _c : "browser",
4497
+ ...args.excludedPredefinedFunctions != null ? {
4498
+ excludedPredefinedFunctions: args.excludedPredefinedFunctions
4499
+ } : {}
4500
+ });
4501
+ break;
4502
+ }
4503
+ case "google.mcp_server": {
4504
+ interactionsTools.push({
4505
+ type: "mcp_server",
4506
+ ...args.name != null ? { name: args.name } : {},
4507
+ ...args.url != null ? { url: args.url } : {},
4508
+ ...args.headers != null ? { headers: args.headers } : {},
4509
+ ...args.allowedTools != null ? { allowed_tools: args.allowedTools } : {}
4510
+ });
4511
+ break;
4512
+ }
4513
+ case "google.retrieval": {
4514
+ const vertexAiSearchConfig = (_d = args.vertexAiSearchConfig) != null ? _d : void 0;
4515
+ interactionsTools.push({
4516
+ type: "retrieval",
4517
+ ...args.retrievalTypes != null ? {
4518
+ retrieval_types: args.retrievalTypes
4519
+ } : { retrieval_types: ["vertex_ai_search"] },
4520
+ ...vertexAiSearchConfig != null ? { vertex_ai_search_config: vertexAiSearchConfig } : {}
4521
+ });
4522
+ break;
4523
+ }
4524
+ default: {
4525
+ toolWarnings.push({
4526
+ type: "unsupported",
4527
+ feature: `provider-defined tool ${tool.id}`,
4528
+ details: `provider-defined tool ${tool.id} is not supported by google.interactions; tool dropped.`
4529
+ });
4530
+ break;
4531
+ }
4532
+ }
4533
+ continue;
4534
+ }
4535
+ toolWarnings.push({
4536
+ type: "unsupported",
4537
+ feature: `tool of type ${tool.type}`,
4538
+ details: "Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."
4539
+ });
4540
+ }
4541
+ const hasFunctionTool = interactionsTools.some((t) => t.type === "function");
4542
+ let mappedToolChoice;
4543
+ if (toolChoice != null && hasFunctionTool) {
4544
+ switch (toolChoice.type) {
4545
+ case "auto":
4546
+ mappedToolChoice = "auto";
4547
+ break;
4548
+ case "required":
4549
+ mappedToolChoice = "any";
4550
+ break;
4551
+ case "none":
4552
+ mappedToolChoice = "none";
4553
+ break;
4554
+ case "tool":
4555
+ mappedToolChoice = {
4556
+ allowed_tools: {
4557
+ mode: "validated",
4558
+ tools: [toolChoice.toolName]
4559
+ }
4560
+ };
4561
+ break;
4562
+ }
4563
+ }
4564
+ return {
4565
+ tools: interactionsTools.length > 0 ? interactionsTools : void 0,
4566
+ toolChoice: mappedToolChoice,
4567
+ toolWarnings
4568
+ };
4569
+ }
4570
+
4571
+ // src/interactions/stream-google-interactions.ts
4572
+ var import_provider_utils17 = require("@ai-sdk/provider-utils");
4573
+ var DEFAULT_MAX_RETRIES = 3;
4574
+ var DEFAULT_RETRY_DELAY_MS = 500;
4575
+ function streamGoogleInteractionEvents({
4576
+ baseURL,
4577
+ interactionId,
4578
+ headers,
4579
+ fetch,
4580
+ abortSignal,
4581
+ maxRetries = DEFAULT_MAX_RETRIES,
4582
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS
4583
+ }) {
4584
+ if (interactionId.length === 0) {
4585
+ throw new Error(
4586
+ "google.interactions: cannot stream a background interaction without an id."
4587
+ );
4588
+ }
4589
+ const eventSourceHeaders = {
4590
+ ...headers,
4591
+ accept: "text/event-stream"
4592
+ };
4593
+ let lastEventId;
4594
+ let complete = false;
4595
+ let attempt = 0;
4596
+ let receivedAnyEventThisAttempt = false;
4597
+ let currentReader;
4598
+ const internalAbort = new AbortController();
4599
+ const upstreamAbortHandler = () => internalAbort.abort();
4600
+ if (abortSignal != null) {
4601
+ if (abortSignal.aborted) {
4602
+ internalAbort.abort();
4603
+ } else {
4604
+ abortSignal.addEventListener("abort", upstreamAbortHandler, {
4605
+ once: true
4606
+ });
4607
+ }
4608
+ }
4609
+ const effectiveSignal = internalAbort.signal;
4610
+ function buildUrl() {
4611
+ const base = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4612
+ const params = new URLSearchParams({ stream: "true" });
4613
+ if (lastEventId != null) {
4614
+ params.set("last_event_id", lastEventId);
4615
+ }
4616
+ return `${base}?${params.toString()}`;
4617
+ }
4618
+ async function openReader() {
4619
+ const { value: stream } = await (0, import_provider_utils17.getFromApi)({
4620
+ url: buildUrl(),
4621
+ headers: eventSourceHeaders,
4622
+ failedResponseHandler: googleFailedResponseHandler,
4623
+ successfulResponseHandler: (0, import_provider_utils17.createEventSourceResponseHandler)(
4624
+ googleInteractionsEventSchema
4625
+ ),
4626
+ abortSignal: effectiveSignal,
4627
+ fetch
4628
+ });
4629
+ return stream.getReader();
4630
+ }
4631
+ return new ReadableStream({
4632
+ async start(controller) {
4633
+ try {
4634
+ while (!complete && !effectiveSignal.aborted) {
4635
+ if (currentReader == null) {
4636
+ try {
4637
+ currentReader = await openReader();
4638
+ receivedAnyEventThisAttempt = false;
4639
+ } catch (error) {
4640
+ if ((0, import_provider_utils17.isAbortError)(error) || effectiveSignal.aborted) {
4641
+ controller.error(error);
4642
+ return;
4643
+ }
4644
+ attempt++;
4645
+ if (attempt >= maxRetries) {
4646
+ controller.error(error);
4647
+ return;
4648
+ }
4649
+ await (0, import_provider_utils17.delay)(retryDelayMs * attempt, {
4650
+ abortSignal: effectiveSignal
4651
+ });
4652
+ continue;
4653
+ }
4654
+ }
4655
+ try {
4656
+ const { done, value } = await currentReader.read();
4657
+ if (done) {
4658
+ currentReader = void 0;
4659
+ if (complete) break;
4660
+ if (!receivedAnyEventThisAttempt) {
4661
+ attempt++;
4662
+ if (attempt >= maxRetries) {
4663
+ controller.error(
4664
+ new Error(
4665
+ "google.interactions: SSE stream closed without producing any events."
4666
+ )
4667
+ );
4668
+ return;
4669
+ }
4670
+ await (0, import_provider_utils17.delay)(retryDelayMs * attempt, {
4671
+ abortSignal: effectiveSignal
4672
+ });
4673
+ } else {
4674
+ attempt = 0;
4675
+ }
4676
+ continue;
4677
+ }
4678
+ receivedAnyEventThisAttempt = true;
4679
+ if (value.success) {
4680
+ const ev = value.value;
4681
+ if (typeof ev.event_id === "string" && ev.event_id.length > 0) {
4682
+ lastEventId = ev.event_id;
4683
+ }
4684
+ if (ev.event_type === "interaction.completed" || ev.event_type === "error") {
4685
+ complete = true;
4686
+ }
4687
+ }
4688
+ controller.enqueue(value);
4689
+ } catch (error) {
4690
+ if ((0, import_provider_utils17.isAbortError)(error) || effectiveSignal.aborted) {
4691
+ controller.error(error);
4692
+ return;
4693
+ }
4694
+ currentReader = void 0;
4695
+ attempt++;
4696
+ if (attempt >= maxRetries) {
4697
+ controller.error(error);
4698
+ return;
4699
+ }
4700
+ await (0, import_provider_utils17.delay)(retryDelayMs * attempt, {
4701
+ abortSignal: effectiveSignal
4702
+ });
4703
+ }
4704
+ }
4705
+ controller.close();
4706
+ } catch (error) {
4707
+ controller.error(error);
4708
+ } finally {
4709
+ if (abortSignal != null) {
4710
+ abortSignal.removeEventListener("abort", upstreamAbortHandler);
4711
+ }
4712
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
4713
+ });
4714
+ currentReader = void 0;
4715
+ if (effectiveSignal.aborted && !complete) {
4716
+ await cancelGoogleInteraction({
4717
+ baseURL,
4718
+ interactionId,
4719
+ headers,
4720
+ fetch
4721
+ });
4722
+ }
4723
+ }
4724
+ },
4725
+ cancel() {
4726
+ internalAbort.abort();
4727
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
4728
+ });
4729
+ currentReader = void 0;
4730
+ }
4731
+ });
4732
+ }
4733
+
4734
+ // src/interactions/synthesize-google-interactions-agent-stream.ts
4735
+ function synthesizeGoogleInteractionsAgentStream({
4736
+ response,
4737
+ warnings,
4738
+ generateId: generateId2,
4739
+ includeRawChunks,
4740
+ headerServiceTier
4741
+ }) {
4742
+ return new ReadableStream({
4743
+ start(controller) {
4744
+ var _a, _b, _c;
4745
+ controller.enqueue({ type: "stream-start", warnings });
4746
+ const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
4747
+ let timestamp;
4748
+ const created = response.created;
4749
+ if (typeof created === "string") {
4750
+ const parsed = new Date(created);
4751
+ if (!Number.isNaN(parsed.getTime())) {
4752
+ timestamp = parsed;
4753
+ }
4754
+ }
4755
+ controller.enqueue({
4756
+ type: "response-metadata",
4757
+ ...interactionId != null ? { id: interactionId } : {},
4758
+ modelId: (_a = response.model) != null ? _a : void 0,
4759
+ ...timestamp ? { timestamp } : {}
4760
+ });
4761
+ if (includeRawChunks) {
4762
+ controller.enqueue({ type: "raw", rawValue: response });
4763
+ }
4764
+ const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
4765
+ steps: (_b = response.steps) != null ? _b : null,
4766
+ generateId: generateId2,
4767
+ interactionId
4768
+ });
4769
+ let blockCounter = 0;
4770
+ const nextBlockId = () => `${interactionId != null ? interactionId : "agent"}:${blockCounter++}`;
4771
+ for (const part of content) {
4772
+ switch (part.type) {
4773
+ case "text": {
4774
+ const id = nextBlockId();
4775
+ const providerMetadata2 = part.providerMetadata;
4776
+ controller.enqueue({ type: "text-start", id });
4777
+ if (part.text.length > 0) {
4778
+ controller.enqueue({ type: "text-delta", id, delta: part.text });
4779
+ }
4780
+ controller.enqueue({
4781
+ type: "text-end",
4782
+ id,
4783
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
4784
+ });
4785
+ break;
4786
+ }
4787
+ case "reasoning": {
4788
+ const id = nextBlockId();
4789
+ const providerMetadata2 = part.providerMetadata;
4790
+ controller.enqueue({ type: "reasoning-start", id });
4791
+ if (part.text.length > 0) {
4792
+ controller.enqueue({
4793
+ type: "reasoning-delta",
4794
+ id,
4795
+ delta: part.text
4796
+ });
4797
+ }
4798
+ controller.enqueue({
4799
+ type: "reasoning-end",
4800
+ id,
4801
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
4802
+ });
4803
+ break;
4804
+ }
4805
+ case "tool-call": {
4806
+ const providerMetadata2 = part.providerMetadata;
4807
+ controller.enqueue({
4808
+ type: "tool-input-start",
4809
+ id: part.toolCallId,
4810
+ toolName: part.toolName,
4811
+ ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {}
4812
+ });
4813
+ controller.enqueue({
4814
+ type: "tool-input-delta",
4815
+ id: part.toolCallId,
4816
+ delta: part.input
4817
+ });
4818
+ controller.enqueue({
4819
+ type: "tool-input-end",
4820
+ id: part.toolCallId
4821
+ });
4822
+ controller.enqueue({
4823
+ type: "tool-call",
4824
+ toolCallId: part.toolCallId,
4825
+ toolName: part.toolName,
4826
+ input: part.input,
4827
+ ...part.providerExecuted ? { providerExecuted: part.providerExecuted } : {},
4828
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
4829
+ });
4830
+ break;
4831
+ }
4832
+ case "tool-result": {
4833
+ controller.enqueue({
4834
+ type: "tool-result",
4835
+ toolCallId: part.toolCallId,
4836
+ toolName: part.toolName,
4837
+ result: part.result
4838
+ });
4839
+ break;
4840
+ }
4841
+ case "source":
4842
+ case "file": {
4843
+ controller.enqueue(part);
4844
+ break;
4845
+ }
4846
+ default:
4847
+ break;
4848
+ }
4849
+ }
4850
+ const serviceTier = (_c = response.service_tier) != null ? _c : headerServiceTier;
4851
+ const finishReason = {
4852
+ unified: mapGoogleInteractionsFinishReason({
4853
+ status: response.status,
4854
+ hasFunctionCall
4855
+ }),
4856
+ raw: response.status
4857
+ };
4858
+ const providerMetadata = {
4859
+ google: {
4860
+ ...interactionId != null ? { interactionId } : {},
4861
+ ...serviceTier != null ? { serviceTier } : {}
4862
+ }
4863
+ };
4864
+ controller.enqueue({
4865
+ type: "finish",
4866
+ finishReason,
4867
+ usage: convertGoogleInteractionsUsage(response.usage),
4868
+ providerMetadata
4869
+ });
4870
+ controller.close();
4871
+ }
4872
+ });
4873
+ }
4874
+
4875
+ // src/interactions/google-interactions-language-model.ts
4876
+ var GoogleInteractionsLanguageModel = class {
4877
+ constructor(modelOrAgent, config) {
4878
+ this.specificationVersion = "v3";
4879
+ if (typeof modelOrAgent === "string") {
4880
+ this.modelId = modelOrAgent;
4881
+ this.agent = void 0;
4882
+ } else if ("managedAgent" in modelOrAgent) {
4883
+ this.modelId = modelOrAgent.managedAgent;
4884
+ this.agent = modelOrAgent.managedAgent;
4885
+ } else {
4886
+ this.modelId = modelOrAgent.agent;
4887
+ this.agent = modelOrAgent.agent;
4888
+ }
4889
+ this.config = config;
4890
+ }
4891
+ get provider() {
4892
+ return this.config.provider;
4893
+ }
4894
+ get supportedUrls() {
4895
+ if (this.config.supportedUrls) {
4896
+ return this.config.supportedUrls();
4897
+ }
4898
+ return {
4899
+ "image/*": [/^https?:\/\/.+/],
4900
+ "application/pdf": [/^https?:\/\/.+/],
4901
+ "audio/*": [/^https?:\/\/.+/],
4902
+ "video/*": [
4903
+ /^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,
4904
+ /^https?:\/\/youtu\.be\/.+/,
4905
+ /^gs:\/\/.+/
4906
+ ]
4907
+ };
4908
+ }
4909
+ async getArgs(options) {
4910
+ 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;
4911
+ const warnings = [];
4912
+ const opts = await (0, import_provider_utils18.parseProviderOptions)({
4913
+ provider: "google",
4914
+ providerOptions: options.providerOptions,
4915
+ schema: googleInteractionsLanguageModelOptions
4916
+ });
4917
+ const isAgent = this.agent != null;
4918
+ const hasTools = options.tools != null && options.tools.length > 0;
4919
+ let toolsForBody;
4920
+ let toolChoiceForBody;
4921
+ if (hasTools && isAgent) {
4922
+ warnings.push({
4923
+ type: "other",
4924
+ message: "google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body."
4925
+ });
4926
+ } else if (hasTools) {
4927
+ const prepared = prepareGoogleInteractionsTools({
4928
+ tools: options.tools,
4929
+ toolChoice: options.toolChoice
4930
+ });
4931
+ toolsForBody = prepared.tools;
4932
+ toolChoiceForBody = prepared.toolChoice;
4933
+ warnings.push(...prepared.toolWarnings);
4934
+ }
4935
+ const responseFormatEntries = [];
4936
+ if (((_a = options.responseFormat) == null ? void 0 : _a.type) === "json") {
4937
+ if (isAgent) {
4938
+ warnings.push({
4939
+ type: "other",
4940
+ message: "google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."
4941
+ });
4942
+ } else {
4943
+ const entry = {
4944
+ type: "text",
4945
+ mime_type: "application/json",
4946
+ ...options.responseFormat.schema != null ? { schema: options.responseFormat.schema } : {}
4947
+ };
4948
+ responseFormatEntries.push(entry);
4949
+ }
4950
+ }
4951
+ if ((opts == null ? void 0 : opts.responseFormat) != null) {
4952
+ for (const entry of opts.responseFormat) {
4953
+ if (entry.type === "text") {
4954
+ responseFormatEntries.push(
4955
+ pruneUndefined({
4956
+ type: "text",
4957
+ mime_type: (_b = entry.mimeType) != null ? _b : void 0,
4958
+ schema: (_c = entry.schema) != null ? _c : void 0
4959
+ })
4960
+ );
4961
+ } else if (entry.type === "image") {
4962
+ responseFormatEntries.push(
4963
+ pruneUndefined({
4964
+ type: "image",
4965
+ mime_type: (_d = entry.mimeType) != null ? _d : void 0,
4966
+ aspect_ratio: (_e = entry.aspectRatio) != null ? _e : void 0,
4967
+ image_size: (_f = entry.imageSize) != null ? _f : void 0
4968
+ })
4969
+ );
4970
+ } else if (entry.type === "audio") {
4971
+ responseFormatEntries.push(
4972
+ pruneUndefined({
4973
+ type: "audio",
4974
+ mime_type: (_g = entry.mimeType) != null ? _g : void 0
4975
+ })
4976
+ );
4977
+ }
4978
+ }
4979
+ }
4980
+ const {
4981
+ input,
4982
+ systemInstruction: convertedSystemInstruction,
4983
+ warnings: convWarnings
4984
+ } = convertToGoogleInteractionsInput({
4985
+ prompt: options.prompt,
4986
+ previousInteractionId: (_h = opts == null ? void 0 : opts.previousInteractionId) != null ? _h : void 0,
4987
+ store: (_i = opts == null ? void 0 : opts.store) != null ? _i : void 0,
4988
+ mediaResolution: (_j = opts == null ? void 0 : opts.mediaResolution) != null ? _j : void 0
4989
+ });
4990
+ warnings.push(...convWarnings);
4991
+ let systemInstruction = convertedSystemInstruction;
4992
+ const optionSystemInstruction = (_k = opts == null ? void 0 : opts.systemInstruction) != null ? _k : void 0;
4993
+ if (systemInstruction != null && optionSystemInstruction != null) {
4994
+ warnings.push({
4995
+ type: "other",
4996
+ message: "google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."
4997
+ });
4998
+ } else if (systemInstruction == null && optionSystemInstruction != null) {
4999
+ systemInstruction = optionSystemInstruction;
5000
+ }
5001
+ let generationConfig;
5002
+ if (isAgent) {
5003
+ const droppedFields = [];
5004
+ if (options.temperature != null) droppedFields.push("temperature");
5005
+ if (options.topP != null) droppedFields.push("topP");
5006
+ if (options.seed != null) droppedFields.push("seed");
5007
+ if (options.stopSequences != null && options.stopSequences.length > 0) {
5008
+ droppedFields.push("stopSequences");
5009
+ }
5010
+ if (options.maxOutputTokens != null)
5011
+ droppedFields.push("maxOutputTokens");
5012
+ if ((opts == null ? void 0 : opts.thinkingLevel) != null) droppedFields.push("thinkingLevel");
5013
+ if ((opts == null ? void 0 : opts.thinkingSummaries) != null) {
5014
+ droppedFields.push("thinkingSummaries");
5015
+ }
5016
+ if ((opts == null ? void 0 : opts.imageConfig) != null) droppedFields.push("imageConfig");
5017
+ if (droppedFields.length > 0) {
5018
+ warnings.push({
5019
+ type: "other",
5020
+ 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.`
5021
+ });
5022
+ }
5023
+ generationConfig = void 0;
5024
+ } else {
5025
+ generationConfig = pruneUndefined({
5026
+ temperature: (_l = options.temperature) != null ? _l : void 0,
5027
+ top_p: (_m = options.topP) != null ? _m : void 0,
5028
+ seed: (_n = options.seed) != null ? _n : void 0,
5029
+ stop_sequences: options.stopSequences != null && options.stopSequences.length > 0 ? options.stopSequences : void 0,
5030
+ max_output_tokens: (_o = options.maxOutputTokens) != null ? _o : void 0,
5031
+ thinking_level: (_p = opts == null ? void 0 : opts.thinkingLevel) != null ? _p : void 0,
5032
+ thinking_summaries: (_q = opts == null ? void 0 : opts.thinkingSummaries) != null ? _q : void 0,
5033
+ tool_choice: toolChoiceForBody
5034
+ });
5035
+ if ((opts == null ? void 0 : opts.imageConfig) != null) {
5036
+ const alreadyHasImageEntry = responseFormatEntries.some(
5037
+ (entry) => entry.type === "image"
5038
+ );
5039
+ warnings.push({
5040
+ type: "other",
5041
+ 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.'
5042
+ });
5043
+ if (!alreadyHasImageEntry) {
5044
+ responseFormatEntries.push({
5045
+ type: "image",
5046
+ mime_type: "image/png",
5047
+ ...opts.imageConfig.aspectRatio != null ? { aspect_ratio: opts.imageConfig.aspectRatio } : {},
5048
+ ...opts.imageConfig.imageSize != null ? { image_size: opts.imageConfig.imageSize } : {}
5049
+ });
5050
+ }
5051
+ }
5052
+ }
5053
+ let agentConfig;
5054
+ if (isAgent && (opts == null ? void 0 : opts.agentConfig) != null) {
5055
+ const ac = opts.agentConfig;
5056
+ if (ac.type === "deep-research") {
5057
+ agentConfig = pruneUndefined({
5058
+ type: "deep-research",
5059
+ thinking_summaries: (_r = ac.thinkingSummaries) != null ? _r : void 0,
5060
+ visualization: (_s = ac.visualization) != null ? _s : void 0,
5061
+ collaborative_planning: (_t = ac.collaborativePlanning) != null ? _t : void 0
5062
+ });
5063
+ } else if (ac.type === "dynamic") {
5064
+ agentConfig = { type: "dynamic" };
5065
+ }
5066
+ }
5067
+ let environment;
5068
+ if ((opts == null ? void 0 : opts.environment) != null) {
5069
+ if (!isAgent) {
5070
+ warnings.push({
5071
+ type: "other",
5072
+ message: "google.interactions: environment is only supported when an agent is set; environment will be omitted from the request body."
5073
+ });
5074
+ } else if (typeof opts.environment === "string") {
5075
+ environment = opts.environment;
5076
+ } else {
5077
+ const env = opts.environment;
5078
+ const sources = (_u = env.sources) == null ? void 0 : _u.map((s) => {
5079
+ var _a2;
5080
+ if (s.type === "inline") {
5081
+ return {
5082
+ type: "inline",
5083
+ content: s.content,
5084
+ target: s.target
5085
+ };
5086
+ }
5087
+ return pruneUndefined({
5088
+ type: s.type,
5089
+ source: s.source,
5090
+ target: (_a2 = s.target) != null ? _a2 : void 0
5091
+ });
5092
+ });
5093
+ let network;
5094
+ if (env.network === "disabled") {
5095
+ network = "disabled";
5096
+ } else if (env.network != null) {
5097
+ network = {
5098
+ allowlist: env.network.allowlist.map(
5099
+ (entry) => {
5100
+ var _a2;
5101
+ return pruneUndefined({
5102
+ domain: entry.domain,
5103
+ transform: (_a2 = entry.transform) != null ? _a2 : void 0
5104
+ });
5105
+ }
5106
+ )
5107
+ };
5108
+ }
5109
+ environment = pruneUndefined({
5110
+ type: "remote",
5111
+ sources: sources != null && sources.length > 0 ? sources : void 0,
5112
+ network
5113
+ });
5114
+ }
5115
+ }
5116
+ const args = pruneUndefined({
5117
+ ...isAgent ? { agent: this.agent } : { model: this.modelId },
5118
+ input,
5119
+ system_instruction: systemInstruction,
5120
+ tools: toolsForBody,
5121
+ response_format: responseFormatEntries.length > 0 ? responseFormatEntries : void 0,
5122
+ response_modalities: (opts == null ? void 0 : opts.responseModalities) != null ? opts.responseModalities : void 0,
5123
+ previous_interaction_id: (_v = opts == null ? void 0 : opts.previousInteractionId) != null ? _v : void 0,
5124
+ service_tier: (_w = opts == null ? void 0 : opts.serviceTier) != null ? _w : void 0,
5125
+ store: (_x = opts == null ? void 0 : opts.store) != null ? _x : void 0,
5126
+ generation_config: generationConfig != null && Object.keys(generationConfig).length > 0 ? generationConfig : void 0,
5127
+ agent_config: agentConfig,
5128
+ environment,
5129
+ background: (_y = opts == null ? void 0 : opts.background) != null ? _y : void 0
5130
+ });
5131
+ return {
5132
+ args,
5133
+ warnings,
5134
+ isAgent,
5135
+ isBackground: (opts == null ? void 0 : opts.background) === true,
5136
+ pollingTimeoutMs: (_z = opts == null ? void 0 : opts.pollingTimeoutMs) != null ? _z : void 0
5137
+ };
5138
+ }
5139
+ async doGenerate(options) {
5140
+ var _a, _b, _c, _d, _e, _f;
5141
+ const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5142
+ const url = `${this.config.baseURL}/interactions`;
5143
+ const mergedHeaders = (0, import_provider_utils18.combineHeaders)(
5144
+ INTERACTIONS_API_REVISION_HEADER,
5145
+ this.config.headers ? await (0, import_provider_utils18.resolve)(this.config.headers) : void 0,
5146
+ options.headers
5147
+ );
5148
+ const postResult = await (0, import_provider_utils18.postJsonToApi)({
5149
+ url,
5150
+ headers: mergedHeaders,
5151
+ body: args,
5152
+ failedResponseHandler: googleFailedResponseHandler,
5153
+ successfulResponseHandler: (0, import_provider_utils18.createJsonResponseHandler)(
5154
+ googleInteractionsResponseSchema
5155
+ ),
5156
+ abortSignal: options.abortSignal,
5157
+ fetch: this.config.fetch
5158
+ });
5159
+ let {
5160
+ responseHeaders,
5161
+ value: response,
5162
+ rawValue: rawResponse
5163
+ } = postResult;
5164
+ if (isAgent && !isTerminalStatus(response.status)) {
5165
+ const polled = await pollGoogleInteractionUntilTerminal({
5166
+ baseURL: this.config.baseURL,
5167
+ interactionId: response.id,
5168
+ headers: mergedHeaders,
5169
+ fetch: this.config.fetch,
5170
+ abortSignal: options.abortSignal,
5171
+ timeoutMs: pollingTimeoutMs
5172
+ });
5173
+ response = polled.response;
5174
+ rawResponse = polled.rawResponse;
5175
+ responseHeaders = (_a = polled.responseHeaders) != null ? _a : responseHeaders;
5176
+ }
5177
+ const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
5178
+ const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
5179
+ steps: (_b = response.steps) != null ? _b : null,
5180
+ generateId: (_c = this.config.generateId) != null ? _c : import_provider_utils18.generateId,
5181
+ interactionId
5182
+ });
5183
+ const finishReason = {
5184
+ unified: mapGoogleInteractionsFinishReason({
5185
+ status: response.status,
5186
+ hasFunctionCall
5187
+ }),
5188
+ raw: response.status
5189
+ };
5190
+ const serviceTier = (_e = (_d = response.service_tier) != null ? _d : responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"]) != null ? _e : void 0;
5191
+ const outputTokensByModality = getGoogleInteractionsOutputTokensByModality(
5192
+ response.usage
5193
+ );
5194
+ const providerMetadata = {
5195
+ google: {
5196
+ ...interactionId != null ? { interactionId } : {},
5197
+ ...serviceTier != null ? { serviceTier } : {},
5198
+ ...outputTokensByModality != null ? { outputTokensByModality } : {}
5199
+ }
5200
+ };
5201
+ let timestamp;
5202
+ if (typeof response.created === "string") {
5203
+ const parsed = new Date(response.created);
5204
+ if (!Number.isNaN(parsed.getTime())) {
5205
+ timestamp = parsed;
5206
+ }
5207
+ }
5208
+ return {
5209
+ content,
5210
+ finishReason,
5211
+ usage: convertGoogleInteractionsUsage(response.usage),
5212
+ warnings,
5213
+ providerMetadata,
5214
+ request: { body: args },
5215
+ response: {
5216
+ headers: responseHeaders,
5217
+ body: rawResponse,
5218
+ ...interactionId != null ? { id: interactionId } : {},
5219
+ ...timestamp ? { timestamp } : {},
5220
+ modelId: (_f = response.model) != null ? _f : void 0
5221
+ }
5222
+ };
5223
+ }
5224
+ async doStream(options) {
5225
+ var _a;
5226
+ const { args, warnings, isBackground, pollingTimeoutMs } = await this.getArgs(options);
5227
+ const url = `${this.config.baseURL}/interactions`;
5228
+ const mergedHeaders = (0, import_provider_utils18.combineHeaders)(
5229
+ INTERACTIONS_API_REVISION_HEADER,
5230
+ this.config.headers ? await (0, import_provider_utils18.resolve)(this.config.headers) : void 0,
5231
+ options.headers
5232
+ );
5233
+ if (isBackground) {
5234
+ return this.doStreamBackground({
5235
+ args,
5236
+ warnings,
5237
+ url,
5238
+ mergedHeaders,
5239
+ options,
5240
+ pollingTimeoutMs
5241
+ });
5242
+ }
5243
+ const body = { ...args, stream: true };
5244
+ const { responseHeaders, value: response } = await (0, import_provider_utils18.postJsonToApi)({
5245
+ url,
5246
+ headers: mergedHeaders,
5247
+ body,
5248
+ failedResponseHandler: googleFailedResponseHandler,
5249
+ successfulResponseHandler: (0, import_provider_utils18.createEventSourceResponseHandler)(
5250
+ googleInteractionsEventSchema
5251
+ ),
5252
+ abortSignal: options.abortSignal,
5253
+ fetch: this.config.fetch
5254
+ });
5255
+ const headerServiceTier = responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"];
5256
+ const transform = buildGoogleInteractionsStreamTransform({
5257
+ warnings,
5258
+ generateId: (_a = this.config.generateId) != null ? _a : import_provider_utils18.generateId,
5259
+ includeRawChunks: options.includeRawChunks,
5260
+ serviceTier: headerServiceTier
5261
+ });
5262
+ return {
5263
+ stream: response.pipeThrough(transform),
5264
+ request: { body },
5265
+ response: { headers: responseHeaders }
5266
+ };
5267
+ }
5268
+ /*
5269
+ * Drive the streaming surface for agent calls. Agents require
5270
+ * `background: true`, which is incompatible with `stream: true` on POST.
5271
+ *
5272
+ * Approach:
5273
+ * 1. POST `/interactions` with `background: true`. The response includes
5274
+ * the interaction id and an initial (usually non-terminal) status.
5275
+ * 2. If the POST status is already terminal (rare), synthesize a stream
5276
+ * from the polled outputs and we're done.
5277
+ * 3. Otherwise open `GET /interactions/{id}?stream=true` and pipe the
5278
+ * SSE events through `buildGoogleInteractionsStreamTransform` so the
5279
+ * consumer receives text deltas / thinking summaries / tool events as
5280
+ * they happen instead of all at once at the end.
5281
+ *
5282
+ * The SSE connection can drop while the agent idles between events
5283
+ * (`UND_ERR_BODY_TIMEOUT`); `streamGoogleInteractionEvents` handles the
5284
+ * reconnect-with-`last_event_id` loop transparently.
5285
+ */
5286
+ async doStreamBackground({
5287
+ args,
5288
+ warnings,
5289
+ url,
5290
+ mergedHeaders,
5291
+ options,
5292
+ pollingTimeoutMs
5293
+ }) {
5294
+ var _a, _b;
5295
+ const postResult = await (0, import_provider_utils18.postJsonToApi)({
5296
+ url,
5297
+ headers: mergedHeaders,
5298
+ body: args,
5299
+ failedResponseHandler: googleFailedResponseHandler,
5300
+ successfulResponseHandler: (0, import_provider_utils18.createJsonResponseHandler)(
5301
+ googleInteractionsResponseSchema
5302
+ ),
5303
+ abortSignal: options.abortSignal,
5304
+ fetch: this.config.fetch
5305
+ });
5306
+ const { responseHeaders: postHeaders, value: postResponse } = postResult;
5307
+ const interactionId = postResponse.id;
5308
+ if (interactionId == null || interactionId.length === 0) {
5309
+ throw new Error(
5310
+ "google.interactions: background POST response did not include an interaction id; cannot stream the result."
5311
+ );
5312
+ }
5313
+ const headerServiceTier = postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"];
5314
+ if (isTerminalStatus(postResponse.status)) {
5315
+ const synthesized = synthesizeGoogleInteractionsAgentStream({
5316
+ response: postResponse,
5317
+ warnings,
5318
+ generateId: (_a = this.config.generateId) != null ? _a : import_provider_utils18.generateId,
5319
+ includeRawChunks: options.includeRawChunks,
5320
+ headerServiceTier
5321
+ });
5322
+ return {
5323
+ stream: synthesized,
5324
+ request: { body: args },
5325
+ response: { headers: postHeaders }
5326
+ };
5327
+ }
5328
+ void pollingTimeoutMs;
5329
+ const events = streamGoogleInteractionEvents({
5330
+ baseURL: this.config.baseURL,
5331
+ interactionId,
5332
+ headers: mergedHeaders,
5333
+ fetch: this.config.fetch,
5334
+ abortSignal: options.abortSignal
5335
+ });
5336
+ const transform = buildGoogleInteractionsStreamTransform({
5337
+ warnings,
5338
+ generateId: (_b = this.config.generateId) != null ? _b : import_provider_utils18.generateId,
5339
+ includeRawChunks: options.includeRawChunks,
5340
+ serviceTier: headerServiceTier
5341
+ });
5342
+ return {
5343
+ stream: events.pipeThrough(transform),
5344
+ request: { body: args },
5345
+ response: { headers: postHeaders }
5346
+ };
5347
+ }
5348
+ };
5349
+ var INTERACTIONS_API_REVISION_HEADER = {
5350
+ "Api-Revision": "2026-05-20"
5351
+ };
5352
+ function pruneUndefined(obj) {
5353
+ const result = {};
5354
+ for (const [key, value] of Object.entries(obj)) {
5355
+ if (value === void 0) continue;
5356
+ result[key] = value;
5357
+ }
5358
+ return result;
5359
+ }
2447
5360
  // Annotate the CommonJS export names for ESM import in node:
2448
5361
  0 && (module.exports = {
2449
5362
  GoogleGenerativeAILanguageModel,
5363
+ GoogleInteractionsLanguageModel,
2450
5364
  getGroundingMetadataSchema,
2451
5365
  getUrlContextMetadataSchema,
2452
5366
  googleTools