@ai-sdk/google 3.0.88 → 3.0.90

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