@eum-agent/llm-protocol-google 0.0.0-stage → 1.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1431 @@
1
+ import { z } from "zod";
2
+ //#region src/brand.ts
3
+ /** Official Gemini sparkle, supplied as self-contained SVG. */
4
+ const GEMINI_LOGO = "data:image/svg+xml,%3Csvg%20class%3D%22_footerSpark_dppzc_90%22%20width%3D%2264%22%20height%3D%2264%22%20viewBox%3D%220%200%2064%2064%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M57.0667%2028.6103C52.1359%2026.4878%2047.8217%2023.576%2044.1223%2019.8784C40.4247%2016.1808%2037.5128%2011.8649%2035.3902%206.9342C34.5754%205.04449%2033.9206%203.10204%2033.4186%201.11049C33.2549%200.459368%2032.6711%200.0010376%2032%200.0010376C31.3288%200.0010376%2030.745%200.459368%2030.5813%201.11049C30.0793%203.10204%2029.4246%205.04267%2028.6097%206.9342C26.4872%2011.8649%2023.5753%2016.1808%2019.8777%2019.8784C16.18%2023.576%2011.864%2026.4878%206.93327%2028.6103C5.04353%2029.4251%203.10105%2030.0799%201.10947%2030.5819C0.458338%2030.7456%200%2031.3294%200%2032.0005C0%2032.6716%200.458338%2033.2555%201.10947%2033.4191C3.10105%2033.9211%205.04172%2034.5759%206.93327%2035.3907C11.864%2037.5132%2016.1782%2040.4251%2019.8777%2044.1226C23.5771%2047.8202%2026.4872%2052.1361%2028.6097%2057.0668C29.4246%2058.9565%2030.0793%2060.899%2030.5813%2062.8905C30.745%2063.5416%2031.3288%2064%2032%2064C32.6711%2064%2033.2549%2063.5416%2033.4186%2062.8905C33.9206%2060.899%2034.5754%2058.9583%2035.3902%2057.0668C37.5128%2052.1361%2040.4247%2047.822%2044.1223%2044.1226C47.8199%2040.4251%2052.1359%2037.5132%2057.0667%2035.3907C58.9564%2034.5759%2060.8989%2033.9211%2062.8905%2033.4191C63.5416%2033.2555%2064%2032.6716%2064%2032.0005C64%2031.3294%2063.5416%2030.7456%2062.8905%2030.5819C60.8989%2030.0799%2058.9582%2029.4251%2057.0667%2028.6103Z%22%20fill%3D%22white%22%3E%3C%2Fpath%3E%3Cmask%20id%3D%22mask0_10859_4894%22%20style%3D%22mask-type%3Aalpha%22%20maskUnits%3D%22userSpaceOnUse%22%20x%3D%220%22%20y%3D%220%22%20width%3D%2264%22%20height%3D%2264%22%3E%3Cpath%20d%3D%22M32%200C32.6711%201.144e-05%2033.2553%200.458263%2033.4189%201.10938C33.9209%203.10093%2034.5758%205.04389%2035.3906%206.93359C37.5131%2011.8639%2040.4247%2016.1796%2044.1221%2019.877C47.8215%2023.5745%2052.1357%2026.4869%2057.0664%2028.6094C58.958%2029.4242%2060.899%2030.0791%2062.8906%2030.5811C63.5415%2030.7448%2063.9998%2031.3281%2064%2031.999C64%2032.6701%2063.5417%2033.2542%2062.8906%2033.418C60.899%2033.9199%2058.9561%2034.5748%2057.0664%2035.3896C52.1358%2037.5121%2047.8196%2040.4237%2044.1221%2044.1211C40.4246%2047.8204%2037.5131%2052.1349%2035.3906%2057.0654C34.5758%2058.957%2033.9209%2060.8981%2033.4189%2062.8896C33.2552%2063.5407%2032.6711%2063.999%2032%2063.999C31.3289%2063.999%2030.7448%2063.5407%2030.5811%2062.8896C30.0791%2060.8981%2029.4242%2058.9551%2028.6094%2057.0654C26.4869%2052.1349%2023.5773%2047.8186%2019.8779%2044.1211C16.1786%2040.4237%2011.8642%2037.5121%206.93359%2035.3896C5.04204%2034.5748%203.10096%2033.9199%201.10938%2033.418C0.458309%2033.2542%200%2032.6701%200%2031.999C0.000201548%2031.3281%200.458463%2030.7448%201.10938%2030.5811C3.10096%2030.0791%205.04386%2029.4242%206.93359%2028.6094C11.8643%2026.4869%2016.1804%2023.5745%2019.8779%2019.877C23.5753%2016.1796%2026.4869%2011.8639%2028.6094%206.93359C29.4242%205.04207%2030.0791%203.10093%2030.5811%201.10938C30.7448%200.45826%2031.3289%200%2032%200Z%22%20fill%3D%22black%22%3E%3C%2Fpath%3E%3Cpath%20d%3D%22M32%200C32.6711%201.144e-05%2033.2553%200.458263%2033.4189%201.10938C33.9209%203.10093%2034.5758%205.04389%2035.3906%206.93359C37.5131%2011.8639%2040.4247%2016.1796%2044.1221%2019.877C47.8215%2023.5745%2052.1357%2026.4869%2057.0664%2028.6094C58.958%2029.4242%2060.899%2030.0791%2062.8906%2030.5811C63.5415%2030.7448%2063.9998%2031.3281%2064%2031.999C64%2032.6701%2063.5417%2033.2542%2062.8906%2033.418C60.899%2033.9199%2058.9561%2034.5748%2057.0664%2035.3896C52.1358%2037.5121%2047.8196%2040.4237%2044.1221%2044.1211C40.4246%2047.8204%2037.5131%2052.1349%2035.3906%2057.0654C34.5758%2058.957%2033.9209%2060.8981%2033.4189%2062.8896C33.2552%2063.5407%2032.6711%2063.999%2032%2063.999C31.3289%2063.999%2030.7448%2063.5407%2030.5811%2062.8896C30.0791%2060.8981%2029.4242%2058.9551%2028.6094%2057.0654C26.4869%2052.1349%2023.5773%2047.8186%2019.8779%2044.1211C16.1786%2040.4237%2011.8642%2037.5121%206.93359%2035.3896C5.04204%2034.5748%203.10096%2033.9199%201.10938%2033.418C0.458309%2033.2542%200%2032.6701%200%2031.999C0.000201548%2031.3281%200.458463%2030.7448%201.10938%2030.5811C3.10096%2030.0791%205.04386%2029.4242%206.93359%2028.6094C11.8643%2026.4869%2016.1804%2023.5745%2019.8779%2019.877C23.5753%2016.1796%2026.4869%2011.8639%2028.6094%206.93359C29.4242%205.04207%2030.0791%203.10093%2030.5811%201.10938C30.7448%200.45826%2031.3289%200%2032%200Z%22%20fill%3D%22url%28%23paint0_linear_10859_4894%29%22%3E%3C%2Fpath%3E%3C%2Fmask%3E%3Cg%20mask%3D%22url%28%23mask0_10859_4894%29%22%3E%3Cg%20filter%3D%22url%28%23filter0_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2214.2084%22%20cy%3D%2216.7164%22%20rx%3D%2214.2084%22%20ry%3D%2216.7164%22%20transform%3D%22matrix%280.942343%200.334649%20-0.334656%200.94234%20-7.979%2013.7735%29%22%20fill%3D%22%23FFE432%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter1_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2227.0543%22%20cy%3D%222.55114%22%20rx%3D%2218.3944%22%20ry%3D%2218.7985%22%20fill%3D%22%23FC413D%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter2_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2219.2245%22%20cy%3D%2224.9042%22%20rx%3D%2219.2245%22%20ry%3D%2224.9042%22%20transform%3D%22matrix%280.998807%20-0.0488254%200.0488266%200.998807%20-1.72778%2032.6573%29%22%20fill%3D%22%2300B95C%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter3_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2219.2245%22%20cy%3D%2224.9042%22%20rx%3D%2219.2245%22%20ry%3D%2224.9042%22%20transform%3D%22matrix%280.998807%20-0.0488254%200.0488266%200.998807%20-1.72778%2032.6573%29%22%20fill%3D%22%2300B95C%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter4_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2218.8429%22%20cy%3D%2220.7441%22%20rx%3D%2218.8429%22%20ry%3D%2220.7441%22%20transform%3D%22matrix%280.854301%20-0.519779%200.51979%200.854294%20-7.13574%2047.5078%29%22%20fill%3D%22%2300B95C%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter5_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2266.4617%22%20cy%3D%2224.977%22%20rx%3D%2218.0933%22%20ry%3D%2217.4229%22%20fill%3D%22%233186FF%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter6_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2220.9292%22%20cy%3D%2222.0752%22%20rx%3D%2220.9292%22%20ry%3D%2222.0752%22%20transform%3D%22matrix%280.79599%200.60531%20-0.60532%200.795982%20-2.81885%20-7.43323%29%22%20fill%3D%22%23FBBC04%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter7_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2224.1311%22%20cy%3D%2222.2919%22%20rx%3D%2224.1311%22%20ry%3D%2222.2919%22%20transform%3D%22matrix%280.824037%200.566536%20-0.566546%200.82403%2039.6338%200.310608%29%22%20fill%3D%22%233186FF%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter8_f_10859_4894%29%22%3E%3Cpath%20d%3D%22M54.2255%20-2.30403C57.0195%201.49462%2053.4294%208.8804%2046.2068%2014.1926C38.9842%2019.5048%2030.8642%2020.7318%2028.0702%2016.9331C25.2762%2013.1345%2028.8663%205.74867%2036.0889%200.436486C43.3115%20-4.8757%2051.4315%20-6.10267%2054.2255%20-2.30403Z%22%20fill%3D%22%23749BFF%22%3E%3C%2Fpath%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter9_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2227.5853%22%20cy%3D%2217.1478%22%20rx%3D%2227.5853%22%20ry%3D%2217.1478%22%20transform%3D%22matrix%280.733166%20-0.680049%200.680061%200.733155%20-12.2583%209.49695%29%22%20fill%3D%22%23FC413D%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3Cg%20filter%3D%22url%28%23filter10_f_10859_4894%29%22%3E%3Cellipse%20cx%3D%2214.7819%22%20cy%3D%228.59637%22%20rx%3D%2214.7819%22%20ry%3D%228.59637%22%20transform%3D%22matrix%280.813186%200.582004%20-0.582016%200.813177%206.37842%2030.511%29%22%20fill%3D%22%23FFEE48%22%3E%3C%2Fellipse%3E%3C%2Fg%3E%3C%2Fg%3E%3Cdefs%3E%3Cfilter%20id%3D%22filter0_f_10859_4894%22%20x%3D%22-19.618%22%20y%3D%2212.9027%22%20width%3D%2238.8681%22%20height%3D%2242.7562%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%222.45965%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter1_f_10859_4894%22%20x%3D%22-15.1223%22%20y%3D%22-40.0296%22%20width%3D%2284.3533%22%20height%3D%2285.1615%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%2211.8911%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter2_f_10859_4894%22%20x%3D%22-20.7682%22%20y%3D%2211.4835%22%20width%3D%2278.9161%22%20height%3D%2290.2196%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%2210.1086%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter3_f_10859_4894%22%20x%3D%22-20.7682%22%20y%3D%2211.4835%22%20width%3D%2278.9161%22%20height%3D%2290.2196%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%2210.1086%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter4_f_10859_4894%22%20x%3D%22-19.85%22%20y%3D%2214.9664%22%20width%3D%2279.1886%22%20height%3D%2280.9378%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%2210.1086%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter5_f_10859_4894%22%20x%3D%2229.1561%22%20y%3D%22-11.6582%22%20width%3D%2274.6111%22%20height%3D%2273.2703%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%229.60613%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter6_f_10859_4894%22%20x%3D%22-38.291%22%20y%3D%22-16.2687%22%20width%3D%2277.538%22%20height%3D%2278.1513%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%228.70591%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter7_f_10859_4894%22%20x%3D%227.78038%22%20y%3D%22-6.0981%22%20width%3D%2278.2181%22%20height%3D%2276.8982%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%227.77473%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter8_f_10859_4894%22%20x%3D%2213.2082%22%20y%3D%22-18.425%22%20width%3D%2255.8793%22%20height%3D%2251.4791%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%226.95694%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter9_f_10859_4894%22%20x%3D%22-15.4739%22%20y%3D%22-31.0272%22%20width%3D%2270.2034%22%20height%3D%2268.6735%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%225.87598%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3Cfilter%20id%3D%22filter10_f_10859_4894%22%20x%3D%22-14.173%22%20y%3D%2220.474%22%20width%3D%2255.1373%22%20height%3D%2251.261%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeGaussianBlur%20stdDeviation%3D%227.27253%22%20result%3D%22effect1_foregroundBlur_10859_4894%22%3E%3C%2FfeGaussianBlur%3E%3C%2Ffilter%3E%3ClinearGradient%20id%3D%22paint0_linear_10859_4894%22%20x1%3D%2218.1931%22%20y1%3D%2242.821%22%20x2%3D%2251.4335%22%20y2%3D%2214.7959%22%20gradientUnits%3D%22userSpaceOnUse%22%3E%3Cstop%20stop-color%3D%22%234893FC%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%220.27%22%20stop-color%3D%22%234893FC%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%220.776981%22%20stop-color%3D%22%23969DFF%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23BD99FE%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3C%2Fsvg%3E";
5
+ //#endregion
6
+ //#region src/facts.ts
7
+ /** Native Interactions limits and parameter spelling, independent of catalogue capacity. */
8
+ const facts = {
9
+ outputLimit: {
10
+ support: "optional",
11
+ ordinary: 8192
12
+ },
13
+ temperature: null,
14
+ modelThinkingSwitch: true,
15
+ limits: {
16
+ requestBytes: 20971520,
17
+ images: 14
18
+ }
19
+ };
20
+ //#endregion
21
+ //#region src/http.ts
22
+ /** Bounded HTTP primitives for the native Google wire. */
23
+ /** Resolves a resource beneath a configured API root and refuses credentials or inference paths. */
24
+ function googleUrl(base, path) {
25
+ if (typeof base !== "string") throw new Error("Google Base URL is required");
26
+ const url = new URL(base);
27
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || /\/(interactions|models)(\/|$)|:generateContent$/.test(url.pathname)) throw new Error("Google Base URL must be an API root without credentials, query or inference path");
28
+ return `${url.href.replace(/\/+$/, "")}/${path}`;
29
+ }
30
+ /** Reads bounded UTF-8 JSON, rejecting byte overflow before allocating the complete response. */
31
+ async function readGoogleJson(response, maxBytes) {
32
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("Invalid Google response byte budget");
33
+ const length = response.headers.get("content-length");
34
+ if (length !== null && /^\d+$/.test(length) && Number(length) > maxBytes) {
35
+ await response.body?.cancel();
36
+ throw new Error("Google response exceeds its byte budget");
37
+ }
38
+ if (!response.body) throw new Error("Google response has no body");
39
+ const reader = response.body.getReader();
40
+ const decoder = new TextDecoder("utf-8", { fatal: true });
41
+ let text = "", bytes = 0;
42
+ try {
43
+ for (;;) {
44
+ const next = await reader.read();
45
+ if (next.done) break;
46
+ bytes += next.value.byteLength;
47
+ if (bytes > maxBytes) throw new Error("Google response exceeds its byte budget");
48
+ text += decoder.decode(next.value, { stream: true });
49
+ }
50
+ return {
51
+ body: JSON.parse(text + decoder.decode()),
52
+ bytes
53
+ };
54
+ } finally {
55
+ await reader.cancel().catch(() => {});
56
+ reader.releaseLock();
57
+ }
58
+ }
59
+ /** Converts an HTTP refusal to a bounded, credential-free error carrying only its status. */
60
+ async function requireGoogleSuccess(response) {
61
+ if (response.ok) return;
62
+ await response.body?.cancel().catch(() => {});
63
+ throw Object.assign(/* @__PURE__ */ new Error(`Google request failed with HTTP ${response.status}`), { status: response.status });
64
+ }
65
+ /** Verifies lossless Base64 encoding before the host performs MIME and image decoding. */
66
+ function googleImageBytes(data) {
67
+ const encoded = z.string().min(1).parse(data);
68
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) throw new Error("Google image data is not valid Base64");
69
+ return Buffer.from(encoded, "base64");
70
+ }
71
+ //#endregion
72
+ //#region src/policy.ts
73
+ /** Native protocol identity, shared by all supported Google model profiles. */
74
+ const GOOGLE_PROTOCOL = "gemini-interactions";
75
+ /** Built-in conversational metadata; new identifiers may use the same native protocol. */
76
+ const GOOGLE_CHAT_MODELS = [
77
+ "gemini-4-argon",
78
+ "gemini-3.8-flash",
79
+ "gemini-3.7-flash",
80
+ "gemini-3.6-flash",
81
+ "gemini-3.5-flash",
82
+ "gemini-3.5-flash-lite",
83
+ "gemini-3.1-flash-lite",
84
+ "gemini-3.1-pro-preview",
85
+ "gemini-3.1-pro-preview-customtools",
86
+ "gemini-3-flash-preview",
87
+ "gemini-2.5-pro",
88
+ "gemini-2.5-flash",
89
+ "gemini-2.5-flash-lite"
90
+ ];
91
+ /** Built-in native image metadata, including ordinary text conversation support. */
92
+ const GOOGLE_IMAGE_MODELS = [
93
+ "gemini-nano-banana-2.1",
94
+ "gemini-3.1-flash-image",
95
+ "gemini-3.1-flash-lite-image",
96
+ "gemini-3-pro-image",
97
+ "nano-banana-pro-preview",
98
+ "gemini-2.5-flash-image"
99
+ ];
100
+ /** Returns executable candidates for one exact upstream model id without network activity. */
101
+ function googleCandidates(model) {
102
+ if (GOOGLE_CHAT_MODELS.includes(model)) return [{
103
+ profile: "google-chat-v1",
104
+ label: "Gemini conversation",
105
+ chat: true
106
+ }];
107
+ if (GOOGLE_IMAGE_MODELS.includes(model)) return [{
108
+ profile: "google-image-v1",
109
+ label: "Gemini image generation",
110
+ chat: true,
111
+ generation: ["image"]
112
+ }];
113
+ return [{
114
+ profile: "google-chat-v1",
115
+ label: "Gemini conversation",
116
+ chat: true
117
+ }];
118
+ }
119
+ /** Validates one explicitly selected native execution profile without trusting remote method names. */
120
+ function validateGoogleExecution(input) {
121
+ if (input.requested.protocolId !== "gemini-interactions" || !["google-chat-v1", "google-image-v1"].includes(input.requested.profile)) throw new Error("This Google execution profile is unsupported");
122
+ return {
123
+ protocolId: GOOGLE_PROTOCOL,
124
+ profile: input.requested.profile
125
+ };
126
+ }
127
+ /** Verified thinking levels for exact native models; unverified controls remain unavailable. */
128
+ function googleEfforts(model) {
129
+ if (model === "gemini-nano-banana-2.1") return [
130
+ "minimal",
131
+ "medium",
132
+ "high"
133
+ ];
134
+ const three = [
135
+ "low",
136
+ "medium",
137
+ "high"
138
+ ];
139
+ const four = ["minimal", ...three];
140
+ if ([
141
+ "gemini-4-argon",
142
+ "gemini-3.8-flash",
143
+ "gemini-3.7-flash",
144
+ "gemini-3.1-pro-preview",
145
+ "gemini-3.1-pro-preview-customtools",
146
+ "gemini-2.5-pro",
147
+ "gemini-2.5-flash",
148
+ "gemini-2.5-flash-lite"
149
+ ].includes(model)) return three;
150
+ if ([
151
+ "gemini-3.6-flash",
152
+ "gemini-3.5-flash",
153
+ "gemini-3.5-flash-lite",
154
+ "gemini-3-flash-preview"
155
+ ].includes(model)) return four;
156
+ if (model === "gemini-3.1-flash-lite") return ["high"];
157
+ return [];
158
+ }
159
+ /** Static facts from official model pages, usable before an authenticated catalogue refresh. */
160
+ function googleModelEntry(model) {
161
+ if (!GOOGLE_CHAT_MODELS.includes(model) && !GOOGLE_IMAGE_MODELS.includes(model)) return void 0;
162
+ if (GOOGLE_IMAGE_MODELS.includes(model)) return {
163
+ id: model,
164
+ chat: true,
165
+ tool_call: false,
166
+ attachment: true,
167
+ temperature: false,
168
+ ...model === "gemini-nano-banana-2.1" ? {
169
+ reasoning: true,
170
+ reasoning_options: [{
171
+ type: "effort",
172
+ values: [...googleEfforts(model)]
173
+ }],
174
+ limit: {
175
+ input: 131072,
176
+ output: 32768
177
+ }
178
+ } : {},
179
+ modalities: {
180
+ input: ["text", "image"],
181
+ output: ["text", "image"]
182
+ }
183
+ };
184
+ const efforts = [...googleEfforts(model)];
185
+ return {
186
+ id: model,
187
+ chat: true,
188
+ reasoning: true,
189
+ tool_call: true,
190
+ attachment: true,
191
+ temperature: false,
192
+ reasoning_options: [...model === "gemini-2.5-flash-lite" ? [{ type: "toggle" }] : [], ...efforts.length ? [{
193
+ type: "effort",
194
+ values: efforts
195
+ }] : []],
196
+ modalities: {
197
+ input: ["text", "image"],
198
+ output: ["text"]
199
+ },
200
+ limit: model === "gemini-4-argon" ? {
201
+ context: 1048576,
202
+ output: 65536
203
+ } : {
204
+ input: 1048576,
205
+ output: 65536
206
+ }
207
+ };
208
+ }
209
+ /** Rejects unsupported native controls, including budget fields belonging to other Google APIs. */
210
+ function validateGoogleParams(model, params) {
211
+ const allowed = /* @__PURE__ */ new Set([
212
+ "thinking",
213
+ "effort",
214
+ "efforts",
215
+ "maxTokens",
216
+ "contextWindow",
217
+ "effortCache",
218
+ "nativeImage"
219
+ ]);
220
+ for (const key of Object.keys(params)) if (!allowed.has(key)) throw new Error(`invalid-params: ${key} is unsupported by Google Interactions`);
221
+ if (params.thinking !== void 0 && typeof params.thinking !== "boolean") throw new Error("invalid-params: thinking must be a boolean");
222
+ if ((params.thinking === false || params.effort === "none") && model !== "gemini-2.5-flash-lite") throw new Error("invalid-params: this Google model has no thinking-off control");
223
+ if (params.effort !== void 0 && params.effort !== "" && !(params.effort === "none" && model === "gemini-2.5-flash-lite") && (typeof params.effort !== "string" || !googleEfforts(model).includes(params.effort))) throw new Error("invalid-params: effort is unsupported by this exact Google model");
224
+ }
225
+ //#endregion
226
+ //#region src/generation.ts
227
+ const ordinaryRatios = [
228
+ "1:1",
229
+ "2:3",
230
+ "3:2",
231
+ "3:4",
232
+ "4:3",
233
+ "4:5",
234
+ "5:4",
235
+ "9:16",
236
+ "16:9",
237
+ "21:9"
238
+ ];
239
+ const wideRatios = [
240
+ ...ordinaryRatios,
241
+ "1:8",
242
+ "8:1",
243
+ "1:4",
244
+ "4:1"
245
+ ];
246
+ /** Strict settings for known image backends; unknown models accept default settings only. */
247
+ function googleImageParamsSchema(model) {
248
+ if (!GOOGLE_IMAGE_MODELS.includes(model)) return z.strictObject({});
249
+ const base = {
250
+ aspectRatio: z.enum(model === "gemini-nano-banana-2.1" || model === "gemini-3.1-flash-image" ? wideRatios : ordinaryRatios).optional(),
251
+ mimeType: z.literal("image/jpeg").optional()
252
+ };
253
+ if (model === "gemini-2.5-flash-image") return z.strictObject(base);
254
+ const sizes = model === "gemini-3.1-flash-lite-image" ? ["1K"] : model === "gemini-3.1-flash-image" ? [
255
+ "512",
256
+ "1K",
257
+ "2K",
258
+ "4K"
259
+ ] : [
260
+ "1K",
261
+ "2K",
262
+ "4K"
263
+ ];
264
+ return z.strictObject({
265
+ ...base,
266
+ imageSize: z.enum(sizes).optional()
267
+ });
268
+ }
269
+ function fail(code, resultState, message) {
270
+ throw Object.assign(new Error(message), {
271
+ name: "GenerationFailure",
272
+ code,
273
+ resultState
274
+ });
275
+ }
276
+ /** Describes configured native Google image execution without network activity. */
277
+ function googleGenerationModels(input) {
278
+ return input.configuredModels.filter((row) => row.execution?.protocolId === "gemini-interactions" && ["google-chat-v1", "google-image-v1"].includes(row.execution.profile) && (row.capabilities?.imageGeneration === "supported" || row.capabilities?.imageEdit === "supported" || row.capabilities?.imageGeneration === void 0 && GOOGLE_IMAGE_MODELS.includes(row.id))).map((row) => ({
279
+ id: row.id,
280
+ label: row.id,
281
+ outputKinds: ["image"],
282
+ operations: [...row.capabilities?.imageGeneration === "unsupported" || row.capabilities?.imageGeneration === "unknown" ? [] : [{
283
+ id: "create",
284
+ inputKinds: [],
285
+ minInputs: 0,
286
+ maxInputs: 0,
287
+ paramsSchema: googleImageParamsSchema(row.id)
288
+ }], ...row.capabilities?.imageEdit === "unsupported" || row.capabilities?.imageEdit === "unknown" ? [] : [{
289
+ id: "edit",
290
+ inputKinds: ["image"],
291
+ minInputs: 1,
292
+ maxInputs: row.id === "gemini-2.5-flash-image" ? 3 : 14,
293
+ paramsSchema: googleImageParamsSchema(row.id)
294
+ }]]
295
+ }));
296
+ }
297
+ /** Creates a native image port; one invocation submits at most one generation request. */
298
+ function createGoogleGenerationPort(call, fetcher) {
299
+ return { async generate(request, signal) {
300
+ signal.throwIfAborted();
301
+ if (!googleGenerationModels(call).some((row) => row.id === call.model)) fail("unavailable", "not-submitted", "The Google image execution profile is not configured");
302
+ const parsed = googleImageParamsSchema(call.model).safeParse(request.params);
303
+ if (!parsed.success) fail("invalid-params", "not-submitted", "The selected Google image model does not support these parameters");
304
+ if (request.outputKind !== "image" || !googleGenerationModels(call).find((row) => row.id === call.model)?.operations.some((one) => one.id === request.operation)) fail("unsupported", "not-submitted", "The requested Google image operation is unsupported");
305
+ if (request.operation === "create" && request.inputs.length !== 0) fail("invalid-input", "not-submitted", "Image creation does not accept reference inputs");
306
+ const maxInputs = call.model === "gemini-2.5-flash-image" ? 3 : 14;
307
+ if (request.operation === "edit" && (request.inputs.length < 1 || request.inputs.length > maxInputs)) fail("invalid-input", "not-submitted", "The number of image references is unsupported");
308
+ const content = [{
309
+ type: "text",
310
+ text: request.prompt
311
+ }];
312
+ let inputBytes = 0;
313
+ for (const file of request.inputs) {
314
+ if (![
315
+ "image/png",
316
+ "image/jpeg",
317
+ "image/webp",
318
+ "image/heic",
319
+ "image/heif"
320
+ ].includes(file.mediaType)) fail("invalid-input", "not-submitted", "The image reference has an unsupported media type");
321
+ const chunks = [];
322
+ let size = 0;
323
+ for await (const chunk of file.read(signal)) {
324
+ signal.throwIfAborted();
325
+ size += chunk.byteLength;
326
+ inputBytes += chunk.byteLength;
327
+ if (size > file.size || inputBytes > 14680064) fail("too-large", "not-submitted", "Inline image references exceed the Google request budget");
328
+ chunks.push(chunk);
329
+ }
330
+ if (size !== file.size) fail("invalid-input", "not-submitted", "The authorized image reference changed size");
331
+ content.push({
332
+ type: "image",
333
+ mime_type: file.mediaType,
334
+ data: Buffer.concat(chunks).toString("base64")
335
+ });
336
+ }
337
+ const params = parsed.data;
338
+ const body = JSON.stringify({
339
+ model: call.model,
340
+ stream: false,
341
+ store: false,
342
+ input: content,
343
+ response_format: {
344
+ type: "image",
345
+ ...params.aspectRatio === void 0 ? {} : { aspect_ratio: params.aspectRatio },
346
+ ..."imageSize" in params && params.imageSize !== void 0 ? { image_size: params.imageSize } : {},
347
+ ...params.mimeType === void 0 ? {} : { mime_type: params.mimeType }
348
+ }
349
+ });
350
+ if (Buffer.byteLength(body) > 20971520) fail("too-large", "not-submitted", "The Google image request exceeds 20 MiB");
351
+ const url = googleUrl(call.config.baseUrl, "interactions");
352
+ let response;
353
+ try {
354
+ response = await fetcher(url, {
355
+ method: "POST",
356
+ headers: {
357
+ "content-type": "application/json",
358
+ "x-goog-api-key": call.secrets.apiKey ?? ""
359
+ },
360
+ body,
361
+ signal,
362
+ redirect: "error"
363
+ });
364
+ } catch {
365
+ fail(signal.aborted ? "cancelled" : "network", "unknown", "The Google image submission result is unknown");
366
+ }
367
+ if (!response.ok) {
368
+ await response.body?.cancel().catch(() => {});
369
+ fail(response.status === 401 ? "credential-unavailable" : response.status === 403 ? "forbidden" : response.status === 429 ? "quota" : "provider", "not-delivered", `Google image generation failed with HTTP ${response.status}`);
370
+ }
371
+ try {
372
+ const result = z.object({
373
+ status: z.literal("completed"),
374
+ steps: z.array(z.object({
375
+ type: z.string(),
376
+ content: z.array(z.object({ type: z.string() }).passthrough()).optional()
377
+ }))
378
+ }).parse((await readGoogleJson(response, 402653184)).body);
379
+ const assets = [];
380
+ const text = [];
381
+ let outputBytes = 0;
382
+ for (const step of result.steps) {
383
+ if (step.type === "thought") continue;
384
+ if (step.type !== "model_output") fail("invalid-output", "not-delivered", "Google returned an unsupported generation step");
385
+ for (const item of step.content ?? []) if (item.type === "text") text.push(z.string().parse(item.text));
386
+ else if (item.type === "image") {
387
+ const mediaType = z.enum([
388
+ "image/png",
389
+ "image/jpeg",
390
+ "image/webp"
391
+ ]).parse(item.mime_type);
392
+ if (params.mimeType && mediaType !== params.mimeType) fail("invalid-output", "not-delivered", "Google returned an image in a different format");
393
+ const bytes = googleImageBytes(item.data);
394
+ outputBytes += bytes.byteLength;
395
+ if (outputBytes > 268435456 || assets.length >= 8) fail("too-large", "not-delivered", "Google image output exceeds its delivery budget");
396
+ assets.push({
397
+ mediaType,
398
+ body: (async function* () {
399
+ yield bytes;
400
+ })()
401
+ });
402
+ } else fail("invalid-output", "not-delivered", "Google returned an unsupported generation content type");
403
+ }
404
+ if (!assets.length) fail("invalid-output", "not-delivered", "Google returned no image");
405
+ return {
406
+ assets,
407
+ ...text.length ? { text: text.join("\n") } : {}
408
+ };
409
+ } catch (error) {
410
+ if (error?.name === "GenerationFailure") throw error;
411
+ fail(signal.aborted ? "cancelled" : "invalid-output", "not-delivered", "The Google image response is incomplete or invalid");
412
+ }
413
+ } };
414
+ }
415
+ //#endregion
416
+ //#region src/request.ts
417
+ function imageBlocks(file, fingerprint) {
418
+ return [{
419
+ type: "text",
420
+ text: file.label
421
+ }, ...file.fate === "send" ? [{
422
+ type: "image",
423
+ mime_type: file.mediaType,
424
+ data: fingerprint ? file.ref.forModel?.id ?? file.ref.id : file.data ?? ""
425
+ }] : []];
426
+ }
427
+ /** Converts neutral history into native steps, preserving tool correlation and note positions. */
428
+ function googleSteps(request, plan, fingerprint = false, replay, toolHistory = true) {
429
+ const steps = [];
430
+ const callNames = /* @__PURE__ */ new Map();
431
+ const note = (notes) => {
432
+ const text = notes?.map((one) => one.text).join("\n\n");
433
+ if (text) steps.push({
434
+ type: "user_input",
435
+ content: [{
436
+ type: "text",
437
+ text
438
+ }]
439
+ });
440
+ };
441
+ request.messages.forEach((message, messageIndex) => {
442
+ if (message.role === "assistant") note(message.volatile);
443
+ const signatures = replay?.(messageIndex);
444
+ let content = [];
445
+ let outputSignature;
446
+ const flush = () => {
447
+ if (content.length) steps.push({
448
+ type: message.role === "user" ? "user_input" : "model_output",
449
+ content,
450
+ ...outputSignature ? { signature: outputSignature } : {}
451
+ });
452
+ content = [];
453
+ outputSignature = void 0;
454
+ };
455
+ message.content.forEach((part, partIndex) => {
456
+ const signedOutput = signatures?.get(partIndex);
457
+ if (signedOutput?.kind === "output") {
458
+ flush();
459
+ outputSignature = signedOutput.signature;
460
+ }
461
+ if (part.type === "thinking") {
462
+ const signature = signatures?.get(partIndex)?.signature;
463
+ if (signature) {
464
+ flush();
465
+ steps.push({
466
+ type: "thought",
467
+ signature,
468
+ summary: part.text ? [{
469
+ type: "text",
470
+ text: part.text
471
+ }] : []
472
+ });
473
+ }
474
+ } else if (part.type === "text") {
475
+ if (part.text) content.push({
476
+ type: "text",
477
+ text: part.text
478
+ });
479
+ } else if (part.type === "file") {
480
+ const file = plan.at(messageIndex, partIndex);
481
+ const blocks = imageBlocks(file, fingerprint);
482
+ content.push(...message.role === "assistant" && file.fate === "send" ? blocks.filter((one) => one.type !== "text") : blocks);
483
+ } else if (part.type === "tool-use") {
484
+ if (!toolHistory) {
485
+ content.push({
486
+ type: "text",
487
+ text: `[Previous tool call ${part.name}: ${JSON.stringify(part.input)}]`
488
+ });
489
+ return;
490
+ }
491
+ flush();
492
+ const previousName = callNames.get(part.id);
493
+ if (previousName !== void 0 && previousName !== part.name) throw new Error("Google history repeats a function call ID with a different name");
494
+ callNames.set(part.id, part.name);
495
+ steps.push({
496
+ type: "function_call",
497
+ id: part.id,
498
+ name: part.name,
499
+ arguments: part.input
500
+ });
501
+ } else if (part.type === "tool-result") {
502
+ if (!toolHistory) {
503
+ content.push({
504
+ type: "text",
505
+ text: `[Previous tool result ${part.toolUseId}${part.isError ? " failed" : ""}]: ${part.content}`
506
+ });
507
+ for (let index = 0; index < (part.files?.length ?? 0); index++) content.push(...imageBlocks(plan.at(messageIndex, partIndex, index), fingerprint));
508
+ return;
509
+ }
510
+ flush();
511
+ const files = part.files ?? [];
512
+ const name = callNames.get(part.toolUseId);
513
+ if (!name) throw new Error("Google tool result is missing its preceding named function call");
514
+ steps.push({
515
+ type: "function_result",
516
+ call_id: part.toolUseId,
517
+ name,
518
+ result: files.length ? [...part.content ? [{
519
+ type: "text",
520
+ text: part.content
521
+ }] : [], ...files.flatMap((_, index) => imageBlocks(plan.at(messageIndex, partIndex, index), fingerprint))] : part.content,
522
+ ...part.isError === void 0 ? {} : { is_error: part.isError }
523
+ });
524
+ }
525
+ if ([...signatures?.values() ?? []].some((one) => one.kind === "output" && one.endPart === partIndex)) flush();
526
+ });
527
+ flush();
528
+ });
529
+ note(request.volatile);
530
+ return steps;
531
+ }
532
+ /** Builds the actual request and the media plan without reading credentials or making network calls. */
533
+ function buildGoogleRequest(call, request, support, fingerprint = false) {
534
+ const selected = call.configuredModels.find((row) => row.id === call.model)?.execution;
535
+ if (selected?.protocolId !== call.protocolId || !["google-chat-v1", "google-image-v1"].includes(selected?.profile ?? "")) throw new Error("Google conversation execution profile is not configured");
536
+ validateGoogleParams(call.model, request.params ?? {});
537
+ const row = call.configuredModels.find((one) => one.id === call.model);
538
+ const entry = support.catalogue(call.providerId, call.model) ?? googleModelEntry(call.model);
539
+ const params = support.resolveParams({
540
+ facts,
541
+ entry,
542
+ stored: request.params ?? {},
543
+ model: call.model,
544
+ endpoint: support.endpoint(call.providerId)
545
+ });
546
+ const media = support.mediaContextOf({
547
+ facts,
548
+ entry,
549
+ stored: request.params ?? {},
550
+ endpoint: support.endpoint(call.providerId),
551
+ fileKinds: ["image"]
552
+ });
553
+ const plan = support.planMedia(request, {
554
+ ...media,
555
+ acceptsImages: row?.capabilities?.imageInput === void 0 ? entry ? media.acceptsImages : false : row.capabilities.imageInput === "supported"
556
+ });
557
+ if (request.purpose === "summary" && (!Number.isSafeInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) < 1)) throw new Error("summaryMaxTokens must be a positive integer");
558
+ const maxTokens = request.purpose === "summary" ? Math.min(request.summaryMaxTokens, params.maxTokens ?? Infinity) : params.maxTokens;
559
+ const wantedEffort = typeof request.params?.effort === "string" ? request.params.effort : params.effort;
560
+ const effort = request.params?.thinking === false || wantedEffort === "none" || wantedEffort === "" ? void 0 : wantedEffort ?? (call.model === "gemini-2.5-flash-lite" && request.params?.thinking === true ? "low" : void 0);
561
+ const toolsSupported = row?.capabilities?.toolCalling === "supported" || row?.capabilities?.toolCalling === void 0 && entry?.tool_call === true;
562
+ const allowTools = toolsSupported && request.purpose !== "summary";
563
+ const system = [
564
+ ...request.system ?? [],
565
+ ...nativeImages(call) && request.purpose !== "summary" ? ["Use native image output for image requests; do not call another image tool unless a different target is explicitly requested. If the user explicitly requests links only, emit [[image-display:link]] with the image. The host supplies its real file link after saving."] : [],
566
+ ...!toolsSupported ? ["The current model does not support tool calling. Do not claim to execute tools or fabricate tool results."] : []
567
+ ];
568
+ const imageParams = request.purpose === "summary" ? void 0 : request.params?.nativeImage;
569
+ if (imageParams !== void 0 && !nativeImages(call)) throw new Error("Native image settings require image output support");
570
+ const image = imageParams === void 0 ? void 0 : googleImageParamsSchema(call.model).parse(imageParams);
571
+ return {
572
+ body: {
573
+ model: call.model,
574
+ stream: !nativeImages(call),
575
+ store: false,
576
+ input: googleSteps(request, plan, fingerprint, (index) => replaySignatures(call, request, index, support), allowTools),
577
+ ...system.length ? { system_instruction: system.join("\n\n") } : {},
578
+ ...allowTools && request.tools?.length ? { tools: request.tools.map((tool) => ({
579
+ type: "function",
580
+ name: tool.name,
581
+ description: tool.description,
582
+ parameters: tool.inputSchema
583
+ })) } : {},
584
+ ...request.purpose === "summary" ? { response_format: {
585
+ type: "text",
586
+ mime_type: "text/plain"
587
+ } } : image ? { response_format: [{ type: "text" }, {
588
+ type: "image",
589
+ ..."aspectRatio" in image && image.aspectRatio !== void 0 ? { aspect_ratio: image.aspectRatio } : {},
590
+ ..."imageSize" in image && image.imageSize !== void 0 ? { image_size: image.imageSize } : {},
591
+ ..."mimeType" in image && image.mimeType !== void 0 ? { mime_type: image.mimeType } : {}
592
+ }] } : {},
593
+ generation_config: {
594
+ thinking_summaries: "auto",
595
+ ...maxTokens === void 0 ? {} : { max_output_tokens: maxTokens },
596
+ ...effort === void 0 ? {} : { thinking_level: effort },
597
+ ...allowTools && request.toolChoice === "none" ? { tool_choice: "none" } : {}
598
+ }
599
+ },
600
+ plan,
601
+ capacity: entry?.limit,
602
+ maxTokens,
603
+ allowTools
604
+ };
605
+ }
606
+ const Replay = z.strictObject({
607
+ connectionFingerprint: z.string().min(1),
608
+ prefixFingerprint: z.string(),
609
+ responseFingerprint: z.string(),
610
+ thoughtTokens: z.number().int().nonnegative(),
611
+ signatures: z.array(z.strictObject({
612
+ part: z.number().int().nonnegative(),
613
+ signature: z.string().min(1),
614
+ kind: z.enum(["thought", "output"]).optional(),
615
+ endPart: z.number().int().nonnegative().optional()
616
+ }))
617
+ });
618
+ /**
619
+ * Binds signature replay to retained input/output history. System instructions and tools are
620
+ * interaction-scoped in the native API and may change between decisions without rewriting history.
621
+ */
622
+ function googlePrefix(call, request, support) {
623
+ const plan = support.planMedia({
624
+ ...request,
625
+ files: void 0
626
+ }, {
627
+ acceptsImages: true,
628
+ limits: facts.limits
629
+ });
630
+ return support.inspectionFingerprint({
631
+ model: call.model,
632
+ input: googleSteps(request, plan, true)
633
+ });
634
+ }
635
+ /** Fingerprints the transcript fields a signed response covers, without host-assigned metadata. */
636
+ function googleResponseFingerprint(content, support) {
637
+ return support.inspectionFingerprint(content.map((part) => {
638
+ if (part.type !== "file") return part;
639
+ return {
640
+ type: part.type,
641
+ file: part.file
642
+ };
643
+ }));
644
+ }
645
+ function replaySignatures(call, request, index, support) {
646
+ const message = request.messages[index];
647
+ const replay = message?.modelReplay;
648
+ if (!replay || replay.protocolId !== call.protocolId || replay.providerId !== call.providerId || replay.model !== call.model || message.outputTruncation?.incompleteThinking || !call.connectionFingerprint) return void 0;
649
+ const parsed = Replay.safeParse(replay.data);
650
+ if (!parsed.success || parsed.data.connectionFingerprint !== call.connectionFingerprint || parsed.data.responseFingerprint !== googleResponseFingerprint(message.content, support)) return void 0;
651
+ if (googlePrefix(call, {
652
+ ...request,
653
+ messages: request.messages.slice(0, index),
654
+ volatile: message.volatile
655
+ }, support) !== parsed.data.prefixFingerprint) return void 0;
656
+ return new Map(parsed.data.signatures.map((one) => [one.part, one]));
657
+ }
658
+ /** Projects only readable native request fields; opaque signatures and image bytes are never text. */
659
+ function googleRequestText(body) {
660
+ const texts = [];
661
+ if (body.system_instruction) texts.push(body.system_instruction);
662
+ if (body.tools) texts.push(JSON.stringify(body.tools));
663
+ for (const step of body.input) if (step.type === "function_call") texts.push(String(step.name), JSON.stringify(step.arguments));
664
+ else if (step.type === "function_result") {
665
+ if (typeof step.result === "string") texts.push(step.result);
666
+ else if (Array.isArray(step.result)) {
667
+ for (const item of step.result) if (item.type === "text") texts.push(item.text);
668
+ } else texts.push(JSON.stringify(step.result));
669
+ } else {
670
+ const content = step.type === "thought" ? step.summary : step.content;
671
+ if (Array.isArray(content)) {
672
+ for (const item of content) if (item.type === "text") texts.push(item.text);
673
+ }
674
+ }
675
+ return texts.join("\n");
676
+ }
677
+ /** Counts opaque retained thought tokens only when their full replay binding is still valid. */
678
+ function googleHiddenInputTokens(call, request, support) {
679
+ return request.messages.reduce((total, message, index) => {
680
+ if (!replaySignatures(call, request, index, support)) return total;
681
+ const parsed = Replay.safeParse(message.modelReplay?.data);
682
+ return total + (parsed.success ? parsed.data.thoughtTokens : 0);
683
+ }, 0);
684
+ }
685
+ /** Native image output is opt-in through effective capabilities, with known plugin facts as fallback. */
686
+ function nativeImages(call) {
687
+ const capabilities = call.configuredModels.find((one) => one.id === call.model)?.capabilities;
688
+ return capabilities === void 0 ? googleModelEntry(call.model)?.modalities?.output?.includes("image") === true : capabilities.imageGeneration === "supported" || capabilities.imageEdit === "supported";
689
+ }
690
+ //#endregion
691
+ //#region src/display.ts
692
+ /** Removes an invocation-local presentation marker without leaking split chunks to the user. */
693
+ function imageDisplayParser() {
694
+ const marker = "[[image-display:link]]";
695
+ let pending = "";
696
+ let link = false;
697
+ return {
698
+ /** Whether any complete marker requested link-only delivery for this response. */
699
+ get link() {
700
+ return link;
701
+ },
702
+ /** Returns safe visible text, retaining at most one marker prefix between chunks. */
703
+ push(text, flush = false) {
704
+ pending += text;
705
+ let output = "";
706
+ while (pending) if (pending.startsWith(marker)) {
707
+ link = true;
708
+ pending = pending.slice(22);
709
+ } else if (!flush && marker.startsWith(pending)) break;
710
+ else {
711
+ output += pending[0];
712
+ pending = pending.slice(1);
713
+ }
714
+ return output;
715
+ }
716
+ };
717
+ }
718
+ //#endregion
719
+ //#region src/stream.ts
720
+ const Event = z.object({ event_type: z.string() }).passthrough();
721
+ const Usage = z.object({
722
+ total_input_tokens: z.number().int().nonnegative(),
723
+ total_output_tokens: z.number().int().nonnegative(),
724
+ total_thought_tokens: z.number().int().nonnegative(),
725
+ total_cached_tokens: z.number().int().nonnegative().optional()
726
+ });
727
+ const Start = z.object({
728
+ type: z.enum([
729
+ "model_output",
730
+ "thought",
731
+ "function_call"
732
+ ]),
733
+ id: z.string().optional(),
734
+ name: z.string().optional(),
735
+ arguments: z.record(z.string(), z.unknown()).optional(),
736
+ signature: z.string().optional(),
737
+ content: z.array(z.object({ type: z.string() }).passthrough()).optional(),
738
+ summary: z.array(z.object({
739
+ type: z.literal("text"),
740
+ text: z.string()
741
+ })).optional()
742
+ });
743
+ /** Parses a framed SSE response and cancels its reader when the consumer stops. */
744
+ async function* googleEvents(response) {
745
+ if (!response.body) throw new Error("Google response has no stream");
746
+ const reader = response.body.getReader();
747
+ const decoder = new TextDecoder();
748
+ let buffer = "";
749
+ let bytes = 0;
750
+ try {
751
+ for (;;) {
752
+ const next = await reader.read();
753
+ bytes += next.value?.byteLength ?? 0;
754
+ if (bytes > 268435456) throw new Error("Google chat response exceeds its byte budget");
755
+ buffer += decoder.decode(next.value, { stream: !next.done });
756
+ buffer = buffer.replace(/\r\n/g, "\n");
757
+ let boundary = buffer.indexOf("\n\n");
758
+ while (boundary !== -1) {
759
+ const frame = buffer.slice(0, boundary);
760
+ buffer = buffer.slice(boundary + 2);
761
+ const data = frame.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
762
+ if (data) yield Event.parse(JSON.parse(data));
763
+ boundary = buffer.indexOf("\n\n");
764
+ }
765
+ if (Buffer.byteLength(buffer) > 16777216) throw new Error("Google stream frame exceeds its byte budget");
766
+ if (next.done) return;
767
+ }
768
+ } finally {
769
+ await reader.cancel().catch(() => {});
770
+ reader.releaseLock();
771
+ }
772
+ }
773
+ /** Maps provider steps to neutral deltas and one complete transcript message. */
774
+ async function* mapGoogleStream(events, call, support, prefixFingerprint, maxTokens, outputSink, signal = new AbortController().signal) {
775
+ const steps = /* @__PURE__ */ new Map();
776
+ let imageCount = 0;
777
+ let imageBytes = 0;
778
+ let linkDisplay = false;
779
+ const addText = (state, raw, flush = false) => {
780
+ const text = state.display.push(raw, flush);
781
+ linkDisplay ||= state.display.link;
782
+ state.text += text;
783
+ if (text) {
784
+ const last = state.content.at(-1);
785
+ if (last?.type === "text") last.text += text;
786
+ else state.content.push({
787
+ type: "text",
788
+ text
789
+ });
790
+ }
791
+ return text;
792
+ };
793
+ const addImage = (state, item) => {
794
+ const mediaType = z.enum([
795
+ "image/png",
796
+ "image/jpeg",
797
+ "image/webp"
798
+ ]).parse(item.mime_type);
799
+ const data = z.string().min(1).parse(item.data);
800
+ imageCount++;
801
+ imageBytes += Math.ceil(data.length * 3 / 4);
802
+ if (imageCount > 8 || imageBytes > 268435456) throw new Error("Google image output exceeds its budget");
803
+ state.content.push({
804
+ type: "image",
805
+ mediaType,
806
+ data
807
+ });
808
+ };
809
+ let latestUsage;
810
+ for await (const event of events) {
811
+ if (event.metadata !== void 0) {
812
+ const metadata = z.object({ total_usage: Usage.partial().optional() }).parse(event.metadata);
813
+ if (metadata.total_usage !== void 0) latestUsage = {
814
+ ...latestUsage,
815
+ ...metadata.total_usage
816
+ };
817
+ }
818
+ if (event.event_type === "step.start") {
819
+ const index = z.number().int().nonnegative().parse(event.index);
820
+ const step = Start.parse(event.step);
821
+ if (steps.has(index)) throw new Error("Google stream repeated a step index");
822
+ const state = {
823
+ ...step,
824
+ text: "",
825
+ arguments: step.arguments && Object.keys(step.arguments).length ? JSON.stringify(step.arguments) : "",
826
+ signature: step.signature ?? "",
827
+ stopped: false,
828
+ content: [],
829
+ display: imageDisplayParser()
830
+ };
831
+ steps.set(index, state);
832
+ if (step.type === "thought") {
833
+ state.text = step.summary?.map((one) => one.text).join("") ?? "";
834
+ if (state.text) yield {
835
+ kind: "thinking-delta",
836
+ text: state.text
837
+ };
838
+ } else if (step.type === "model_output") for (const item of step.content ?? []) if (item.type === "text") {
839
+ const text = addText(state, z.string().parse(item.text));
840
+ if (text) yield {
841
+ kind: "text-delta",
842
+ text
843
+ };
844
+ } else if (item.type === "image") {
845
+ const text = addText(state, "", true);
846
+ if (text) yield {
847
+ kind: "text-delta",
848
+ text
849
+ };
850
+ addImage(state, item);
851
+ } else throw new Error("Unsupported Google model output content");
852
+ if (step.type === "function_call") yield {
853
+ kind: "tool-call-delta",
854
+ id: z.string().min(1).parse(step.id),
855
+ name: z.string().min(1).parse(step.name),
856
+ inputDelta: step.arguments && Object.keys(step.arguments).length ? JSON.stringify(step.arguments) : ""
857
+ };
858
+ } else if (event.event_type === "step.delta") {
859
+ const index = z.number().int().nonnegative().parse(event.index);
860
+ const state = steps.get(index);
861
+ if (!state || state.stopped) throw new Error("Google delta has no active step");
862
+ const delta = z.object({ type: z.string() }).passthrough().parse(event.delta);
863
+ if (delta.type === "text" && state.type === "model_output") {
864
+ const text = addText(state, z.string().parse(delta.text));
865
+ if (text) yield {
866
+ kind: "text-delta",
867
+ text
868
+ };
869
+ } else if (delta.type === "image" && state.type === "model_output") {
870
+ const text = addText(state, "", true);
871
+ if (text) yield {
872
+ kind: "text-delta",
873
+ text
874
+ };
875
+ addImage(state, delta);
876
+ } else if (delta.type === "thought_summary" && state.type === "thought") {
877
+ const content = z.object({
878
+ type: z.literal("text"),
879
+ text: z.string()
880
+ }).parse(delta.content);
881
+ state.text += content.text;
882
+ yield {
883
+ kind: "thinking-delta",
884
+ text: content.text
885
+ };
886
+ } else if (delta.type === "thought_signature" && state.type === "thought") state.signature += z.string().parse(delta.signature);
887
+ else if (delta.type === "arguments_delta" && state.type === "function_call") {
888
+ const inputDelta = z.string().parse(delta.arguments);
889
+ state.arguments += inputDelta;
890
+ yield {
891
+ kind: "tool-call-delta",
892
+ id: z.string().min(1).parse(state.id),
893
+ name: z.string().min(1).parse(state.name),
894
+ inputDelta
895
+ };
896
+ } else throw new Error(`Unsupported Google stream delta: ${delta.type}`);
897
+ } else if (event.event_type === "step.stop") {
898
+ const state = steps.get(z.number().int().nonnegative().parse(event.index));
899
+ if (!state || state.stopped) throw new Error("Google stop has no active step");
900
+ if (state.type === "model_output") {
901
+ const text = addText(state, "", true);
902
+ if (text) yield {
903
+ kind: "text-delta",
904
+ text
905
+ };
906
+ }
907
+ state.stopped = true;
908
+ } else if (event.event_type === "interaction.completed") {
909
+ const final = z.object({
910
+ status: z.enum([
911
+ "completed",
912
+ "requires_action",
913
+ "incomplete",
914
+ "budget_exceeded"
915
+ ]),
916
+ usage: Usage.partial().optional()
917
+ }).parse(event.interaction);
918
+ const interaction = {
919
+ ...final,
920
+ usage: Usage.parse({
921
+ ...latestUsage,
922
+ ...final.usage
923
+ })
924
+ };
925
+ const usedOutput = interaction.usage.total_output_tokens + interaction.usage.total_thought_tokens;
926
+ if (!Number.isSafeInteger(usedOutput)) throw new Error("Google usage exceeds integer capacity");
927
+ const truncated = interaction.status === "budget_exceeded" || interaction.status === "incomplete" && maxTokens !== void 0 && usedOutput >= maxTokens;
928
+ if (interaction.status === "incomplete" && !truncated) throw new Error("Google incomplete response has no confirmed output-budget reason");
929
+ const incompleteToolCalls = [];
930
+ let incompleteThinking = false;
931
+ const content = [];
932
+ const signatures = [];
933
+ let ordinal = 0;
934
+ for (const state of steps.values()) {
935
+ if (!state.stopped && !truncated) throw new Error("Google interaction completed with an unfinished step");
936
+ if (!state.stopped && state.type === "function_call") {
937
+ incompleteToolCalls.push({
938
+ id: state.id ?? "",
939
+ ...state.name ? { name: state.name } : {}
940
+ });
941
+ continue;
942
+ }
943
+ if (!state.stopped && state.type === "thought") incompleteThinking = true;
944
+ if (state.type === "function_call") content.push({
945
+ type: "tool-use",
946
+ id: z.string().min(1).parse(state.id),
947
+ name: z.string().min(1).parse(state.name),
948
+ input: z.record(z.string(), z.unknown()).parse(JSON.parse(state.arguments || "{}"))
949
+ });
950
+ else if (state.type === "thought") {
951
+ if (state.stopped && state.signature) signatures.push({
952
+ part: content.length,
953
+ signature: state.signature
954
+ });
955
+ content.push({
956
+ type: "thinking",
957
+ text: state.text
958
+ });
959
+ } else {
960
+ const outputStart = content.length;
961
+ if (!state.stopped) addText(state, "", true);
962
+ for (const part of state.content) if (part.type === "text") content.push(part);
963
+ else {
964
+ if (!outputSink) throw new Error("Native image output has no session file receiver");
965
+ signal.throwIfAborted();
966
+ const bytes = googleImageBytes(part.data);
967
+ const result = await outputSink.publish({
968
+ ordinal: ordinal++,
969
+ mediaType: part.mediaType,
970
+ name: `generated.${part.mediaType.split("/")[1]}`,
971
+ body: (async function* () {
972
+ yield bytes;
973
+ })()
974
+ }, signal);
975
+ content.push({
976
+ type: "file",
977
+ file: result.file,
978
+ ...linkDisplay ? { display: "link" } : {}
979
+ });
980
+ }
981
+ if (state.stopped && state.signature && content.length > outputStart) signatures.push({
982
+ part: outputStart,
983
+ endPart: content.length - 1,
984
+ kind: "output",
985
+ signature: state.signature
986
+ });
987
+ }
988
+ }
989
+ const usage = interaction.usage;
990
+ const replayData = signatures.length && call.connectionFingerprint ? {
991
+ connectionFingerprint: call.connectionFingerprint,
992
+ prefixFingerprint,
993
+ responseFingerprint: googleResponseFingerprint(content, support),
994
+ thoughtTokens: usage.total_thought_tokens,
995
+ signatures
996
+ } : void 0;
997
+ if (replayData && Buffer.byteLength(JSON.stringify(replayData)) > 2097152) throw new Error("Google thought replay exceeds 2 MiB; continuing without its signature is unsafe");
998
+ yield {
999
+ kind: "final",
1000
+ finishReason: truncated ? "max-tokens" : interaction.status === "requires_action" ? "tool-calls" : "stop",
1001
+ ...incompleteToolCalls.length || incompleteThinking ? { outputTruncation: {
1002
+ incompleteToolCalls,
1003
+ ...incompleteThinking ? { incompleteThinking: true } : {}
1004
+ } } : {},
1005
+ usage: {
1006
+ inputTokens: usage.total_input_tokens,
1007
+ outputTokens: usedOutput,
1008
+ ...usage.total_cached_tokens === void 0 ? {} : { cacheReadTokens: usage.total_cached_tokens }
1009
+ },
1010
+ message: {
1011
+ role: "assistant",
1012
+ content
1013
+ },
1014
+ ...replayData ? { replayData } : {}
1015
+ };
1016
+ return;
1017
+ } else if (event.event_type === "error") throw new Error("Google stream reported an error");
1018
+ }
1019
+ throw support.interruptedFailure();
1020
+ }
1021
+ /** Normalizes bounded nonstreaming native replies through the same ordered assembler. */
1022
+ async function* googleJsonEvents(response) {
1023
+ const interaction = z.object({
1024
+ status: z.string(),
1025
+ usage: z.record(z.string(), z.unknown()),
1026
+ steps: z.array(z.object({ type: z.string() }).passthrough())
1027
+ }).parse((await readGoogleJson(response, 402653184)).body);
1028
+ for (const [index, step] of interaction.steps.entries()) {
1029
+ yield {
1030
+ event_type: "step.start",
1031
+ index,
1032
+ step
1033
+ };
1034
+ yield {
1035
+ event_type: "step.stop",
1036
+ index
1037
+ };
1038
+ }
1039
+ yield {
1040
+ event_type: "interaction.completed",
1041
+ interaction
1042
+ };
1043
+ }
1044
+ //#endregion
1045
+ //#region src/port.ts
1046
+ /** Creates a stateless Google port; request construction and inspection perform no network calls. */
1047
+ function createGooglePort(call, support, fetcher, options = {}) {
1048
+ return {
1049
+ inspect(request) {
1050
+ const { body, plan, capacity, maxTokens } = buildGoogleRequest(call, request, support, true);
1051
+ return support.inspect({
1052
+ body,
1053
+ request,
1054
+ capacity,
1055
+ textTokens: support.measureText(googleRequestText(body)),
1056
+ tokenizer: "o200k_base-google-interactions-v1",
1057
+ mediaTokens: plan.tokens,
1058
+ hiddenInputTokens: googleHiddenInputTokens(call, request, support),
1059
+ outputReserve: maxTokens ?? capacity?.output ?? 0,
1060
+ outputReserveSource: maxTokens === void 0 ? "capacity" : "enforced",
1061
+ fingerprint: {
1062
+ protocol: call.protocolId,
1063
+ connection: call.connectionFingerprint,
1064
+ model: call.model,
1065
+ settings: body.generation_config,
1066
+ capacity
1067
+ }
1068
+ });
1069
+ },
1070
+ async *stream(request, signal, observer) {
1071
+ signal.throwIfAborted();
1072
+ const built = buildGoogleRequest(call, request, support);
1073
+ const body = JSON.stringify(built.body);
1074
+ if (Buffer.byteLength(body) > 20971520) throw support.failures.create({
1075
+ code: "request-too-large",
1076
+ stage: "request",
1077
+ category: "request-too-large",
1078
+ source: "protocol",
1079
+ retryable: false
1080
+ });
1081
+ const url = googleUrl(call.config.baseUrl, "interactions");
1082
+ const prefix = googlePrefix(call, request, support);
1083
+ yield* support.withChatAttempts({
1084
+ signal,
1085
+ ...options,
1086
+ ...nativeImages(call) ? { maxRetries: 0 } : {},
1087
+ async *attempt(attemptSignal, progress, attempt) {
1088
+ const count = attempt + 1;
1089
+ const observe = (event) => {
1090
+ try {
1091
+ observer?.observe?.(event);
1092
+ } catch {}
1093
+ };
1094
+ observe({
1095
+ stage: "attempt",
1096
+ phase: "start",
1097
+ attempt: count
1098
+ });
1099
+ observe({
1100
+ stage: "first-response",
1101
+ phase: "start",
1102
+ attempt: count
1103
+ });
1104
+ let firstResponse = false;
1105
+ let ended = false;
1106
+ let outcome = "unknown";
1107
+ try {
1108
+ attemptSignal.throwIfAborted();
1109
+ let response;
1110
+ try {
1111
+ response = await fetcher(url, {
1112
+ method: "POST",
1113
+ headers: {
1114
+ "content-type": "application/json",
1115
+ "x-goog-api-key": call.secrets.apiKey ?? ""
1116
+ },
1117
+ body,
1118
+ signal: attemptSignal,
1119
+ redirect: "error"
1120
+ });
1121
+ } catch {
1122
+ attemptSignal.throwIfAborted();
1123
+ throw support.failures.create({
1124
+ code: "stream-interrupted",
1125
+ stage: "transport",
1126
+ category: "network",
1127
+ source: "transport",
1128
+ retryable: true
1129
+ });
1130
+ }
1131
+ firstResponse = true;
1132
+ observe({
1133
+ stage: "first-response",
1134
+ phase: "end",
1135
+ attempt: count,
1136
+ outcome: "ok"
1137
+ });
1138
+ if (!response.ok) {
1139
+ await response.body?.cancel().catch(() => {});
1140
+ const retryAfter = Number(response.headers.get("retry-after"));
1141
+ const status = response.status;
1142
+ const failure = support.failures.create({
1143
+ code: status === 413 ? "request-too-large" : "http-error",
1144
+ stage: "transport",
1145
+ category: status === 413 ? "request-too-large" : "provider",
1146
+ source: "protocol",
1147
+ status,
1148
+ retryable: [
1149
+ 408,
1150
+ 409,
1151
+ 429
1152
+ ].includes(status) || status >= 500
1153
+ });
1154
+ throw Object.assign(failure, { retryAfterMs: Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter * 1e3 : void 0 });
1155
+ }
1156
+ if (!response.headers.get("content-type")?.toLowerCase().includes("text/event-stream") && !response.headers.get("content-type")?.toLowerCase().includes("application/json")) {
1157
+ await response.body?.cancel().catch(() => {});
1158
+ throw support.failures.create({
1159
+ code: "response-invalid",
1160
+ stage: "response-validation",
1161
+ category: "protocol",
1162
+ source: "protocol",
1163
+ retryable: false
1164
+ });
1165
+ }
1166
+ try {
1167
+ observer?.dispatched({ attempt });
1168
+ } catch {}
1169
+ const observed = support.observeResponseProgress(response, progress);
1170
+ let final;
1171
+ for await (const chunk of mapGoogleStream(response.headers.get("content-type")?.toLowerCase().includes("text/event-stream") ? googleEvents(observed) : googleJsonEvents(observed), call, support, prefix, built.maxTokens, request.outputSink, attemptSignal)) {
1172
+ progress();
1173
+ if (!built.allowTools && (chunk.kind === "tool-call-delta" || chunk.kind === "final" && chunk.message.content.some((part) => part.type === "tool-use"))) throw new Error("Google returned unsupported tool calls");
1174
+ if (chunk.kind === "final" && nativeImages(call) && chunk.finishReason === "max-tokens") throw new Error("Truncated native image output cannot be automatically continued");
1175
+ if (chunk.kind === "final") {
1176
+ final = chunk;
1177
+ break;
1178
+ }
1179
+ yield chunk;
1180
+ }
1181
+ if (final) {
1182
+ outcome = "ok";
1183
+ ended = true;
1184
+ observe({
1185
+ stage: "attempt",
1186
+ phase: "end",
1187
+ attempt: count,
1188
+ outcome
1189
+ });
1190
+ yield final;
1191
+ }
1192
+ } catch (error) {
1193
+ outcome = attemptSignal.aborted ? "cancelled" : "error";
1194
+ throw error;
1195
+ } finally {
1196
+ if (!firstResponse) observe({
1197
+ stage: "first-response",
1198
+ phase: "end",
1199
+ attempt: count,
1200
+ outcome
1201
+ });
1202
+ if (!ended) observe({
1203
+ stage: "attempt",
1204
+ phase: "end",
1205
+ attempt: count,
1206
+ outcome
1207
+ });
1208
+ }
1209
+ },
1210
+ classify(error) {
1211
+ if (support.failures.owns(error)) return {
1212
+ error,
1213
+ retryable: error.retryable === true,
1214
+ retryAfterMs: error.retryAfterMs
1215
+ };
1216
+ return {
1217
+ error: support.failures.create({
1218
+ code: "response-invalid",
1219
+ stage: "response-validation",
1220
+ category: "protocol",
1221
+ source: "protocol",
1222
+ retryable: false
1223
+ }),
1224
+ retryable: false
1225
+ };
1226
+ }
1227
+ });
1228
+ }
1229
+ };
1230
+ }
1231
+ //#endregion
1232
+ //#region src/probe.ts
1233
+ const Page = z.object({
1234
+ models: z.array(z.object({
1235
+ name: z.string().min(1),
1236
+ displayName: z.string().optional(),
1237
+ inputTokenLimit: z.number().int().positive().optional(),
1238
+ outputTokenLimit: z.number().int().positive().optional()
1239
+ })).default([]),
1240
+ nextPageToken: z.string().optional()
1241
+ });
1242
+ async function pageOf(probe, fetcher, token, remaining, signal) {
1243
+ const url = new URL(googleUrl(probe.config.baseUrl, "models"));
1244
+ url.searchParams.set("pageSize", "100");
1245
+ if (token !== void 0) url.searchParams.set("pageToken", token);
1246
+ const response = await fetcher(url.href, {
1247
+ method: "GET",
1248
+ headers: { "x-goog-api-key": probe.secrets.apiKey ?? "" },
1249
+ signal,
1250
+ redirect: "error"
1251
+ });
1252
+ await requireGoogleSuccess(response);
1253
+ const result = await readGoogleJson(response, remaining);
1254
+ return {
1255
+ page: Page.parse(result.body),
1256
+ bytes: result.bytes
1257
+ };
1258
+ }
1259
+ /** Reads every native model page within one 30-second, 1000-model, 20-page byte budget. */
1260
+ async function listGoogleModels(probe, fetcher) {
1261
+ const offers = /* @__PURE__ */ new Map();
1262
+ const seen = /* @__PURE__ */ new Set();
1263
+ const signal = AbortSignal.any([probe.signal, AbortSignal.timeout(3e4)]);
1264
+ let remaining = Math.min(probe.maxResponseBytes ?? 8388608, 8388608);
1265
+ let token;
1266
+ for (let index = 0; index < 20; index += 1) {
1267
+ const result = await pageOf(probe, fetcher, token, remaining, signal);
1268
+ remaining -= result.bytes;
1269
+ for (const row of result.page.models) {
1270
+ const model = row.name.replace(/^models\//, "");
1271
+ if (!model || offers.has(model)) continue;
1272
+ const execution = googleCandidates(model);
1273
+ const entry = googleModelEntry(model);
1274
+ offers.set(model, {
1275
+ model,
1276
+ ...row.displayName === void 0 ? {} : { name: row.displayName },
1277
+ ...row.inputTokenLimit === void 0 ? {} : { contextWindow: row.inputTokenLimit },
1278
+ ...row.outputTokenLimit === void 0 ? {} : { maxOutput: row.outputTokenLimit },
1279
+ ...entry ? {
1280
+ input: entry.modalities?.input,
1281
+ output: entry.modalities?.output,
1282
+ toolCall: entry.tool_call,
1283
+ reasoning: entry.reasoning,
1284
+ temperature: entry.temperature
1285
+ } : {},
1286
+ execution
1287
+ });
1288
+ if (offers.size > 1e3) throw new Error("Google model listing exceeds 1000 models");
1289
+ }
1290
+ token = result.page.nextPageToken || void 0;
1291
+ if (token === void 0) return { offers: [...offers.values()] };
1292
+ if (seen.has(token)) throw new Error("Google model listing repeated a page token");
1293
+ seen.add(token);
1294
+ if (remaining < 1) throw new Error("Google model listing exhausted its byte budget");
1295
+ }
1296
+ throw new Error("Google model listing exceeds 20 pages");
1297
+ }
1298
+ /** Tests authentication with one read-only page; no model inference is submitted. */
1299
+ async function testGoogleConnection(probe, fetcher) {
1300
+ await pageOf(probe, fetcher, void 0, probe.maxResponseBytes ?? 8388608, AbortSignal.any([probe.signal, AbortSignal.timeout(3e4)]));
1301
+ }
1302
+ //#endregion
1303
+ //#region src/support.ts
1304
+ /** Normalizes official facts without requiring an installed Chat capability. */
1305
+ function normalizeOffers(input) {
1306
+ return Object.fromEntries(input.offers.map((offer) => [offer.model, {
1307
+ id: offer.model,
1308
+ ...offer.name === void 0 ? {} : { name: offer.name },
1309
+ ...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
1310
+ ...offer.efforts?.length ? { reasoning_options: [{
1311
+ type: "effort",
1312
+ values: [...offer.efforts]
1313
+ }] } : {},
1314
+ ...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
1315
+ ...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
1316
+ ...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
1317
+ ...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
1318
+ ...offer.input === void 0 ? {} : { input: [...offer.input] },
1319
+ ...offer.output === void 0 ? {} : { output: [...offer.output] }
1320
+ } },
1321
+ ...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
1322
+ ...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
1323
+ ...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
1324
+ } },
1325
+ ...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
1326
+ }]));
1327
+ }
1328
+ /** The owner-qualified accessor is read per operation; withdrawal never exposes an old service. */
1329
+ function lazySupport(read) {
1330
+ return new Proxy({}, { get(_target, key) {
1331
+ if (key === "normalizeListing") return normalizeOffers;
1332
+ const service = read();
1333
+ if (!service) throw new Error("Chat model support is unavailable");
1334
+ const value = Reflect.get(service, key);
1335
+ return typeof value === "function" ? value.bind(service) : value;
1336
+ } });
1337
+ }
1338
+ //#endregion
1339
+ //#region src/protocol.ts
1340
+ /** Builds native capabilities using host support and a routed fetch; construction makes no requests. */
1341
+ function googleProtocolType(support, fetcher) {
1342
+ return {
1343
+ type: "gemini-interactions",
1344
+ label: "Gemini Interactions API",
1345
+ logo: GEMINI_LOGO,
1346
+ fields: [{
1347
+ key: "baseUrl",
1348
+ kind: "url",
1349
+ label: "Base URL",
1350
+ required: true
1351
+ }],
1352
+ userConfigurable: true,
1353
+ optionsSchema: z.strictObject({}),
1354
+ facts,
1355
+ executionCandidates: ({ model, capabilities }) => capabilities?.imageGeneration === "supported" || capabilities?.imageEdit === "supported" ? [{
1356
+ profile: "google-image-v1",
1357
+ label: "Gemini image generation",
1358
+ chat: capabilities.chat !== "unsupported",
1359
+ generation: ["image"]
1360
+ }] : googleCandidates(model),
1361
+ validateExecution: validateGoogleExecution,
1362
+ prepareParams(input) {
1363
+ const effective = { ...input.params };
1364
+ const changes = [];
1365
+ for (const [key, value] of Object.entries(input.params)) try {
1366
+ validateGoogleParams(input.model, { [key]: value });
1367
+ } catch (error) {
1368
+ if (input.explicitKeys.includes(key)) throw error;
1369
+ delete effective[key];
1370
+ changes.push({
1371
+ field: key,
1372
+ reason: "incompatible inherited parameter"
1373
+ });
1374
+ }
1375
+ const result = support.prepareParams({
1376
+ ...input,
1377
+ params: effective
1378
+ }, facts);
1379
+ validateGoogleParams(input.model, result.effectiveParams);
1380
+ return {
1381
+ ...result,
1382
+ changes: [...changes, ...result.changes]
1383
+ };
1384
+ },
1385
+ effortCacheCapability: () => ({
1386
+ status: "unknown",
1387
+ reason: "google-effort-cache-unverified"
1388
+ }),
1389
+ adapters: {
1390
+ chat: {
1391
+ fileKinds: ["image"],
1392
+ toolCalling(model, input) {
1393
+ return input.configuredModels.find((row) => row.id === model)?.capabilities?.toolCalling ?? (googleModelEntry(model)?.tool_call === true ? "supported" : googleModelEntry(model)?.tool_call === false ? "unsupported" : "unknown");
1394
+ },
1395
+ nativeOutputKinds(model, input) {
1396
+ const capabilities = input.configuredModels.find((row) => row.id === model)?.capabilities;
1397
+ const state = capabilities?.imageGeneration;
1398
+ return state === "supported" || capabilities?.imageEdit === "supported" || state === void 0 && googleModelEntry(model)?.modalities?.output?.includes("image") ? ["image"] : [];
1399
+ },
1400
+ nativeImageParamsSchema: (model) => googleImageParamsSchema(model),
1401
+ supportsModel(model, input) {
1402
+ return input.configuredModels.some((row) => row.id === model && row.execution?.protocolId === "gemini-interactions" && ["google-chat-v1", "google-image-v1"].includes(row.execution.profile) && row.capabilities?.chat !== "unsupported");
1403
+ },
1404
+ createPort: (call) => createGooglePort(call, support, fetcher)
1405
+ },
1406
+ image: {
1407
+ models: googleGenerationModels,
1408
+ createPort: (call) => createGoogleGenerationPort(call, fetcher)
1409
+ }
1410
+ },
1411
+ normalizeListing: (input) => normalizeOffers(input),
1412
+ listModels: (probe) => listGoogleModels(probe, fetcher),
1413
+ testConnection: (probe) => testGoogleConnection(probe, fetcher)
1414
+ };
1415
+ }
1416
+ //#endregion
1417
+ //#region src/index.ts
1418
+ /** Protocol owners contribute no Agent tools. */
1419
+ const TOOL_NAMES = [];
1420
+ const plugin = {
1421
+ name: "@eum-agent/llm-protocol-google",
1422
+ requires: ["network"],
1423
+ optionalServices: ["model-support"],
1424
+ apply(ctx) {
1425
+ const support = lazySupport(() => ctx.services.find("model-support"));
1426
+ const network = ctx.services.get("network");
1427
+ ctx.modelProtocols.register(googleProtocolType(support, network.fetch));
1428
+ }
1429
+ };
1430
+ //#endregion
1431
+ export { TOOL_NAMES, plugin as default };