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