@eum-agent/llm-protocol-google 0.0.0-stage → 1.2.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,1617 @@
1
+ import { z } from "zod";
2
+ import { createHash } from "node:crypto";
3
+ //#region src/brand.ts
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/connection-fetch.ts
7
+ function withConnectionHeaders(fetch, headers) {
8
+ const configured = Object.entries(headers ?? {});
9
+ if (configured.length === 0) return fetch;
10
+ return (input, init) => {
11
+ const merged = new Headers(input instanceof Request ? input.headers : void 0);
12
+ for (const [name, value] of new Headers(init?.headers)) merged.set(name, value);
13
+ for (const [name, value] of configured) merged.set(name, value);
14
+ return fetch(input, {
15
+ ...init,
16
+ headers: merged
17
+ });
18
+ };
19
+ }
20
+ //#endregion
21
+ //#region src/facts.ts
22
+ const facts = {
23
+ outputLimit: {
24
+ support: "optional",
25
+ ordinary: 8192
26
+ },
27
+ temperature: null,
28
+ modelThinkingSwitch: true,
29
+ limits: {
30
+ requestBytes: 20971520,
31
+ images: 14
32
+ }
33
+ };
34
+ //#endregion
35
+ //#region src/http.ts
36
+ function googleUrl(base, path) {
37
+ if (typeof base !== "string") throw new Error("Google Base URL is required");
38
+ const url = new URL(base);
39
+ 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");
40
+ return `${url.href.replace(/\/+$/, "")}/${path}`;
41
+ }
42
+ async function readGoogleJson(response, maxBytes) {
43
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("Invalid Google response byte budget");
44
+ const length = response.headers.get("content-length");
45
+ if (length !== null && /^\d+$/.test(length) && Number(length) > maxBytes) {
46
+ await response.body?.cancel();
47
+ throw new Error("Google response exceeds its byte budget");
48
+ }
49
+ if (!response.body) throw new Error("Google response has no body");
50
+ const reader = response.body.getReader();
51
+ const decoder = new TextDecoder("utf-8", { fatal: true });
52
+ let text = "", bytes = 0;
53
+ try {
54
+ for (;;) {
55
+ const next = await reader.read();
56
+ if (next.done) break;
57
+ bytes += next.value.byteLength;
58
+ if (bytes > maxBytes) throw new Error("Google response exceeds its byte budget");
59
+ text += decoder.decode(next.value, { stream: true });
60
+ }
61
+ return {
62
+ body: JSON.parse(text + decoder.decode()),
63
+ bytes
64
+ };
65
+ } finally {
66
+ await reader.cancel().catch(() => {});
67
+ reader.releaseLock();
68
+ }
69
+ }
70
+ async function googleContextWindowExceeded(response) {
71
+ try {
72
+ if (response.status !== 400) return false;
73
+ const { body } = await readGoogleJson(response, 65536);
74
+ const message = body?.error?.message;
75
+ return typeof message === "string" && /input token count.*exceeds the maximum number of tokens/i.test(message);
76
+ } catch {
77
+ return false;
78
+ } finally {
79
+ await response.body?.cancel().catch(() => {});
80
+ }
81
+ }
82
+ async function requireGoogleSuccess(response) {
83
+ if (response.ok) return;
84
+ await response.body?.cancel().catch(() => {});
85
+ throw Object.assign(/* @__PURE__ */ new Error(`Google request failed with HTTP ${response.status}`), { status: response.status });
86
+ }
87
+ function googleImageBytes(data) {
88
+ const encoded = z.string().min(1).parse(data);
89
+ 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");
90
+ return Buffer.from(encoded, "base64");
91
+ }
92
+ //#endregion
93
+ //#region src/policy.ts
94
+ const GOOGLE_PROTOCOL = "gemini-interactions";
95
+ const GOOGLE_CHAT_MODELS = [
96
+ "gemini-4-argon",
97
+ "gemini-3.8-flash",
98
+ "gemini-3.7-flash",
99
+ "gemini-3.6-flash",
100
+ "gemini-3.5-flash",
101
+ "gemini-3.5-flash-lite",
102
+ "gemini-3.1-flash-lite",
103
+ "gemini-3.1-pro-preview",
104
+ "gemini-3.1-pro-preview-customtools",
105
+ "gemini-3-flash-preview",
106
+ "gemini-2.5-pro",
107
+ "gemini-2.5-flash",
108
+ "gemini-2.5-flash-lite"
109
+ ];
110
+ const GOOGLE_IMAGE_MODELS = [
111
+ "gemini-nano-banana-2.1",
112
+ "gemini-3.1-flash-image",
113
+ "gemini-3.1-flash-lite-image",
114
+ "gemini-3-pro-image",
115
+ "nano-banana-pro-preview",
116
+ "gemini-2.5-flash-image"
117
+ ];
118
+ function googleCandidates(model) {
119
+ if (GOOGLE_CHAT_MODELS.includes(model)) return [{
120
+ profile: "google-chat-v1",
121
+ label: "Gemini conversation",
122
+ chat: true
123
+ }];
124
+ if (GOOGLE_IMAGE_MODELS.includes(model)) return [{
125
+ profile: "google-image-v1",
126
+ label: "Gemini image generation",
127
+ chat: true,
128
+ generation: ["image"]
129
+ }];
130
+ return [{
131
+ profile: "google-chat-v1",
132
+ label: "Gemini conversation",
133
+ chat: true
134
+ }];
135
+ }
136
+ function validateGoogleExecution(input) {
137
+ 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");
138
+ return {
139
+ protocolId: GOOGLE_PROTOCOL,
140
+ profile: input.requested.profile
141
+ };
142
+ }
143
+ function googleEfforts(model) {
144
+ if (model === "gemini-nano-banana-2.1") return [
145
+ "minimal",
146
+ "medium",
147
+ "high"
148
+ ];
149
+ const three = [
150
+ "low",
151
+ "medium",
152
+ "high"
153
+ ];
154
+ const four = ["minimal", ...three];
155
+ if ([
156
+ "gemini-4-argon",
157
+ "gemini-3.8-flash",
158
+ "gemini-3.7-flash",
159
+ "gemini-3.1-pro-preview",
160
+ "gemini-3.1-pro-preview-customtools",
161
+ "gemini-2.5-pro",
162
+ "gemini-2.5-flash",
163
+ "gemini-2.5-flash-lite"
164
+ ].includes(model)) return three;
165
+ if ([
166
+ "gemini-3.6-flash",
167
+ "gemini-3.5-flash",
168
+ "gemini-3.5-flash-lite",
169
+ "gemini-3-flash-preview"
170
+ ].includes(model)) return four;
171
+ if (model === "gemini-3.1-flash-lite") return ["high"];
172
+ return [];
173
+ }
174
+ function validateGoogleParams(model, params) {
175
+ const allowed = /* @__PURE__ */ new Set([
176
+ "thinking",
177
+ "effort",
178
+ "efforts",
179
+ "maxTokens",
180
+ "contextWindow",
181
+ "effortCache",
182
+ "nativeImage"
183
+ ]);
184
+ for (const key of Object.keys(params)) if (!allowed.has(key)) throw new Error(`invalid-params: ${key} is unsupported by Google Interactions`);
185
+ if (params.thinking !== void 0 && typeof params.thinking !== "boolean") throw new Error("invalid-params: thinking must be a boolean");
186
+ 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");
187
+ 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");
188
+ }
189
+ //#endregion
190
+ //#region src/generation.ts
191
+ const ordinaryRatios = [
192
+ "1:1",
193
+ "2:3",
194
+ "3:2",
195
+ "3:4",
196
+ "4:3",
197
+ "4:5",
198
+ "5:4",
199
+ "9:16",
200
+ "16:9",
201
+ "21:9"
202
+ ];
203
+ const wideRatios = [
204
+ ...ordinaryRatios,
205
+ "1:8",
206
+ "8:1",
207
+ "1:4",
208
+ "4:1"
209
+ ];
210
+ function googleImageParamsSchema(model) {
211
+ if (!GOOGLE_IMAGE_MODELS.includes(model)) return z.strictObject({});
212
+ const base = {
213
+ aspectRatio: z.enum(model === "gemini-nano-banana-2.1" || model === "gemini-3.1-flash-image" ? wideRatios : ordinaryRatios).optional(),
214
+ mimeType: z.literal("image/jpeg").optional()
215
+ };
216
+ if (model === "gemini-2.5-flash-image") return z.strictObject(base);
217
+ const sizes = model === "gemini-3.1-flash-lite-image" ? ["1K"] : model === "gemini-3.1-flash-image" ? [
218
+ "512",
219
+ "1K",
220
+ "2K",
221
+ "4K"
222
+ ] : [
223
+ "1K",
224
+ "2K",
225
+ "4K"
226
+ ];
227
+ return z.strictObject({
228
+ ...base,
229
+ imageSize: z.enum(sizes).optional()
230
+ });
231
+ }
232
+ function fail(code, resultState, message) {
233
+ throw Object.assign(new Error(message), {
234
+ name: "GenerationFailure",
235
+ code,
236
+ resultState
237
+ });
238
+ }
239
+ function googleGenerationModels(input) {
240
+ 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) => ({
241
+ id: row.id,
242
+ label: row.id,
243
+ outputKinds: ["image"],
244
+ operations: [...row.capabilities?.imageGeneration === "unsupported" || row.capabilities?.imageGeneration === "unknown" ? [] : [{
245
+ id: "create",
246
+ inputKinds: [],
247
+ minInputs: 0,
248
+ maxInputs: 0,
249
+ paramsSchema: googleImageParamsSchema(row.id)
250
+ }], ...row.capabilities?.imageEdit === "unsupported" || row.capabilities?.imageEdit === "unknown" ? [] : [{
251
+ id: "edit",
252
+ inputKinds: ["image"],
253
+ minInputs: 1,
254
+ maxInputs: row.id === "gemini-2.5-flash-image" ? 3 : 14,
255
+ paramsSchema: googleImageParamsSchema(row.id)
256
+ }]]
257
+ }));
258
+ }
259
+ function createGoogleGenerationPort(call, fetcher) {
260
+ return { async generate(request, signal) {
261
+ signal.throwIfAborted();
262
+ if (!googleGenerationModels(call).some((row) => row.id === call.model)) fail("unavailable", "not-submitted", "The Google image execution profile is not configured");
263
+ const parsed = googleImageParamsSchema(call.model).safeParse(request.params);
264
+ if (!parsed.success) fail("invalid-params", "not-submitted", "The selected Google image model does not support these parameters");
265
+ 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");
266
+ if (request.operation === "create" && request.inputs.length !== 0) fail("invalid-input", "not-submitted", "Image creation does not accept reference inputs");
267
+ const maxInputs = call.model === "gemini-2.5-flash-image" ? 3 : 14;
268
+ if (request.operation === "edit" && (request.inputs.length < 1 || request.inputs.length > maxInputs)) fail("invalid-input", "not-submitted", "The number of image references is unsupported");
269
+ const content = [{
270
+ type: "text",
271
+ text: request.prompt
272
+ }];
273
+ let inputBytes = 0;
274
+ for (const file of request.inputs) {
275
+ if (![
276
+ "image/png",
277
+ "image/jpeg",
278
+ "image/webp",
279
+ "image/heic",
280
+ "image/heif"
281
+ ].includes(file.mediaType)) fail("invalid-input", "not-submitted", "The image reference has an unsupported media type");
282
+ const chunks = [];
283
+ let size = 0;
284
+ for await (const chunk of file.read(signal)) {
285
+ signal.throwIfAborted();
286
+ size += chunk.byteLength;
287
+ inputBytes += chunk.byteLength;
288
+ if (size > file.size || inputBytes > 14680064) fail("too-large", "not-submitted", "Inline image references exceed the Google request budget");
289
+ chunks.push(chunk);
290
+ }
291
+ if (size !== file.size) fail("invalid-input", "not-submitted", "The authorized image reference changed size");
292
+ content.push({
293
+ type: "image",
294
+ mime_type: file.mediaType,
295
+ data: Buffer.concat(chunks).toString("base64")
296
+ });
297
+ }
298
+ const params = parsed.data;
299
+ const body = JSON.stringify({
300
+ model: call.model,
301
+ stream: false,
302
+ store: false,
303
+ input: content,
304
+ response_format: {
305
+ type: "image",
306
+ ...params.aspectRatio === void 0 ? {} : { aspect_ratio: params.aspectRatio },
307
+ ..."imageSize" in params && params.imageSize !== void 0 ? { image_size: params.imageSize } : {},
308
+ ...params.mimeType === void 0 ? {} : { mime_type: params.mimeType }
309
+ }
310
+ });
311
+ if (Buffer.byteLength(body) > 20971520) fail("too-large", "not-submitted", "The Google image request exceeds 20 MiB");
312
+ const url = googleUrl(call.config.baseUrl, "interactions");
313
+ const accounting = call.accountingDispatch?.attempt(0);
314
+ let outcome = "failed";
315
+ let submission = "unknown";
316
+ try {
317
+ let response;
318
+ try {
319
+ response = await fetcher(url, {
320
+ method: "POST",
321
+ headers: {
322
+ "content-type": "application/json",
323
+ "x-goog-api-key": call.secrets.apiKey ?? ""
324
+ },
325
+ body,
326
+ signal,
327
+ redirect: "error"
328
+ });
329
+ } catch {
330
+ fail(signal.aborted ? "cancelled" : "network", "unknown", "The Google image submission result is unknown");
331
+ }
332
+ submission = "submitted";
333
+ if (!response.ok) {
334
+ await response.body?.cancel().catch(() => {});
335
+ 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}`);
336
+ }
337
+ try {
338
+ const raw = (await readGoogleJson(response, 402653184)).body;
339
+ const envelope = raw && typeof raw === "object" ? raw : void 0;
340
+ const usage = envelope?.usage && typeof envelope.usage === "object" ? envelope.usage : void 0;
341
+ const reportedUsage = usage ? {
342
+ ...typeof usage.total_input_tokens === "number" ? { inputTokens: usage.total_input_tokens } : {},
343
+ ...typeof usage.total_output_tokens === "number" && typeof usage.total_thought_tokens === "number" ? { outputTokens: usage.total_output_tokens + usage.total_thought_tokens } : {},
344
+ ...typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {},
345
+ ...typeof usage.total_cached_tokens === "number" ? { cacheReadTokens: usage.total_cached_tokens } : {}
346
+ } : void 0;
347
+ if (reportedUsage) accounting?.report({
348
+ sequence: 1,
349
+ ...reportedUsage
350
+ });
351
+ const result = z.object({
352
+ status: z.literal("completed"),
353
+ steps: z.array(z.object({
354
+ type: z.string(),
355
+ content: z.array(z.object({ type: z.string() }).passthrough()).optional()
356
+ }))
357
+ }).parse(raw);
358
+ const assets = [];
359
+ const text = [];
360
+ let outputBytes = 0;
361
+ for (const step of result.steps) {
362
+ if (step.type === "thought") continue;
363
+ if (step.type !== "model_output") fail("invalid-output", "not-delivered", "Google returned an unsupported generation step");
364
+ for (const item of step.content ?? []) if (item.type === "text") text.push(z.string().parse(item.text));
365
+ else if (item.type === "image") {
366
+ const mediaType = z.enum([
367
+ "image/png",
368
+ "image/jpeg",
369
+ "image/webp"
370
+ ]).parse(item.mime_type);
371
+ if (params.mimeType && mediaType !== params.mimeType) fail("invalid-output", "not-delivered", "Google returned an image in a different format");
372
+ const bytes = googleImageBytes(item.data);
373
+ outputBytes += bytes.byteLength;
374
+ if (outputBytes > 268435456 || assets.length >= 8) fail("too-large", "not-delivered", "Google image output exceeds its delivery budget");
375
+ assets.push({
376
+ mediaType,
377
+ body: (async function* () {
378
+ yield bytes;
379
+ })()
380
+ });
381
+ } else fail("invalid-output", "not-delivered", "Google returned an unsupported generation content type");
382
+ }
383
+ if (!assets.length) fail("invalid-output", "not-delivered", "Google returned no image");
384
+ outcome = "success";
385
+ return {
386
+ assets,
387
+ ...text.length ? { text: text.join("\n") } : {},
388
+ ...reportedUsage ? { usage: reportedUsage } : {}
389
+ };
390
+ } catch (error) {
391
+ if (error?.name === "GenerationFailure") throw error;
392
+ fail(signal.aborted ? "cancelled" : "invalid-output", "not-delivered", "The Google image response is incomplete or invalid");
393
+ }
394
+ } finally {
395
+ accounting?.end({
396
+ outcome: signal.aborted ? "cancelled" : outcome,
397
+ submission
398
+ });
399
+ }
400
+ } };
401
+ }
402
+ //#endregion
403
+ //#region src/request.ts
404
+ function imageBlocks(file, fingerprint) {
405
+ return [{
406
+ type: "text",
407
+ text: file.label
408
+ }, ...file.fate === "send" ? [{
409
+ type: "image",
410
+ mime_type: file.mediaType,
411
+ data: fingerprint ? file.ref.forModel?.id ?? file.ref.id : file.data ?? ""
412
+ }] : []];
413
+ }
414
+ function googleSteps(request, plan, fingerprint = false, replay, toolHistory = true, onReplay) {
415
+ const steps = [];
416
+ const callNames = /* @__PURE__ */ new Map();
417
+ const note = (notes) => {
418
+ const text = notes?.map((one) => one.text).join("\n\n");
419
+ if (text) steps.push({
420
+ type: "user_input",
421
+ content: [{
422
+ type: "text",
423
+ text
424
+ }]
425
+ });
426
+ };
427
+ request.messages.forEach((message, messageIndex) => {
428
+ if (message.role === "assistant") note(message.volatile);
429
+ const signatures = replay?.(messageIndex);
430
+ let content = [];
431
+ let outputSignature;
432
+ let outputPartIndex = -1;
433
+ const flush = () => {
434
+ if (content.length && outputSignature) onReplay?.({
435
+ messageIndex,
436
+ partIndex: outputPartIndex,
437
+ kind: "output",
438
+ signature: outputSignature
439
+ });
440
+ if (content.length) steps.push({
441
+ type: message.role === "user" ? "user_input" : "model_output",
442
+ content,
443
+ ...outputSignature ? { signature: outputSignature } : {}
444
+ });
445
+ content = [];
446
+ outputSignature = void 0;
447
+ };
448
+ message.content.forEach((part, partIndex) => {
449
+ const signedOutput = signatures?.get(partIndex);
450
+ if (signedOutput?.kind === "output") {
451
+ flush();
452
+ outputSignature = signedOutput.signature;
453
+ outputPartIndex = partIndex;
454
+ }
455
+ if (part.type === "thinking") {
456
+ const signature = signatures?.get(partIndex)?.signature;
457
+ if (signature) {
458
+ onReplay?.({
459
+ messageIndex,
460
+ partIndex,
461
+ kind: "thought",
462
+ signature
463
+ });
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
+ function buildGoogleRequest(call, request, support, fingerprint = false, onReplay) {
533
+ const selected = call.configuredModels.find((row) => row.id === call.model)?.execution;
534
+ if (selected?.protocolId !== call.protocolId || !["google-chat-v1", "google-image-v1"].includes(selected?.profile ?? "")) throw new Error("Google conversation execution profile is not configured");
535
+ validateGoogleParams(call.model, request.params ?? {});
536
+ const row = call.configuredModels.find((one) => one.id === call.model);
537
+ const entry = support.catalogue(call.providerId, call.model);
538
+ const params = support.resolveParams({
539
+ facts,
540
+ entry,
541
+ stored: request.params ?? {},
542
+ model: call.model,
543
+ endpoint: support.endpoint(call.providerId)
544
+ });
545
+ const media = support.mediaContextOf({
546
+ facts,
547
+ entry,
548
+ stored: request.params ?? {},
549
+ endpoint: support.endpoint(call.providerId),
550
+ fileKinds: ["image"]
551
+ });
552
+ const plan = support.planMedia(request, {
553
+ ...media,
554
+ acceptsImages: row?.capabilities?.imageInput === void 0 ? entry ? media.acceptsImages : false : row.capabilities.imageInput === "supported"
555
+ });
556
+ if (request.purpose === "summary" && (!Number.isSafeInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) < 1)) throw new Error("summaryMaxTokens must be a positive integer");
557
+ const maxTokens = request.purpose === "summary" ? Math.min(request.summaryMaxTokens, params.maxTokens ?? Infinity) : params.maxTokens;
558
+ const wantedEffort = typeof request.params?.effort === "string" ? request.params.effort : params.effort;
559
+ 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);
560
+ const toolsSupported = row?.capabilities?.toolCalling === "supported" || row?.capabilities?.toolCalling === void 0 && entry?.tool_call === true;
561
+ const standaloneSummary = request.purpose === "summary" && request.summaryShape !== "continuation";
562
+ const allowTools = toolsSupported && !standaloneSummary;
563
+ const system = [
564
+ ...request.system ?? [],
565
+ ...nativeImages(call, support) && !standaloneSummary ? ["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, support)) 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, support),
575
+ store: false,
576
+ input: googleSteps(request, plan, fingerprint, (index) => replaySignatures(call, request, index, support), allowTools, onReplay),
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
+ function googlePrefix(call, request, support) {
619
+ const plan = support.planMedia({
620
+ ...request,
621
+ files: void 0
622
+ }, {
623
+ acceptsImages: true,
624
+ limits: facts.limits
625
+ });
626
+ return support.inspectionFingerprint({
627
+ model: call.model,
628
+ input: googleSteps(request, plan, true)
629
+ });
630
+ }
631
+ function googleResponseFingerprint(content, support) {
632
+ return support.inspectionFingerprint(content.map((part) => {
633
+ if (part.type !== "file") return part;
634
+ return {
635
+ type: part.type,
636
+ file: part.file
637
+ };
638
+ }));
639
+ }
640
+ function replaySignatures(call, request, index, support) {
641
+ const message = request.messages[index];
642
+ const replay = message?.modelReplay;
643
+ if (!replay || replay.protocolId !== call.protocolId || replay.providerId !== call.providerId || replay.model !== call.model || message.outputTruncation?.incompleteThinking || !call.connectionFingerprint) return void 0;
644
+ const parsed = Replay.safeParse(replay.data);
645
+ if (!parsed.success || parsed.data.connectionFingerprint !== call.connectionFingerprint || parsed.data.responseFingerprint !== googleResponseFingerprint(message.content, support)) return void 0;
646
+ if (googlePrefix(call, {
647
+ ...request,
648
+ messages: request.messages.slice(0, index),
649
+ volatile: message.volatile
650
+ }, support) !== parsed.data.prefixFingerprint) return void 0;
651
+ return new Map(parsed.data.signatures.map((one) => [one.part, one]));
652
+ }
653
+ function googleRequestText(body) {
654
+ const texts = [];
655
+ if (body.system_instruction) texts.push(body.system_instruction);
656
+ if (body.tools) texts.push(JSON.stringify(body.tools));
657
+ for (const step of body.input) if (step.type === "function_call") texts.push(String(step.name), JSON.stringify(step.arguments));
658
+ else if (step.type === "function_result") {
659
+ if (typeof step.result === "string") texts.push(step.result);
660
+ else if (Array.isArray(step.result)) {
661
+ for (const item of step.result) if (item.type === "text") texts.push(item.text);
662
+ } else texts.push(JSON.stringify(step.result));
663
+ } else {
664
+ const content = step.type === "thought" ? step.summary : step.content;
665
+ if (Array.isArray(content)) {
666
+ for (const item of content) if (item.type === "text") texts.push(item.text);
667
+ }
668
+ }
669
+ return texts.join("\n");
670
+ }
671
+ function googleHiddenInputTokens(call, request, support) {
672
+ return request.messages.reduce((total, message, index) => {
673
+ if (!replaySignatures(call, request, index, support)) return total;
674
+ const parsed = Replay.safeParse(message.modelReplay?.data);
675
+ return total + (parsed.success ? parsed.data.thoughtTokens : 0);
676
+ }, 0);
677
+ }
678
+ function nativeImages(call, support) {
679
+ const capabilities = call.configuredModels.find((one) => one.id === call.model)?.capabilities;
680
+ return capabilities === void 0 ? support.catalogue(call.providerId, call.model)?.modalities?.output?.includes("image") === true : capabilities.imageGeneration === "supported" || capabilities.imageEdit === "supported";
681
+ }
682
+ //#endregion
683
+ //#region src/display.ts
684
+ function imageDisplayParser() {
685
+ const marker = "[[image-display:link]]";
686
+ let pending = "";
687
+ let link = false;
688
+ return {
689
+ get link() {
690
+ return link;
691
+ },
692
+ push(text, flush = false) {
693
+ pending += text;
694
+ let output = "";
695
+ while (pending) if (pending.startsWith(marker)) {
696
+ link = true;
697
+ pending = pending.slice(22);
698
+ } else if (!flush && marker.startsWith(pending)) break;
699
+ else {
700
+ output += pending[0];
701
+ pending = pending.slice(1);
702
+ }
703
+ return output;
704
+ }
705
+ };
706
+ }
707
+ //#endregion
708
+ //#region src/stream.ts
709
+ const Event = z.object({ event_type: z.string() }).passthrough();
710
+ const Usage = z.object({
711
+ total_input_tokens: z.number().int().nonnegative(),
712
+ total_output_tokens: z.number().int().nonnegative(),
713
+ total_thought_tokens: z.number().int().nonnegative(),
714
+ total_cached_tokens: z.number().int().nonnegative().optional()
715
+ });
716
+ const Start = z.object({
717
+ type: z.enum([
718
+ "model_output",
719
+ "thought",
720
+ "function_call"
721
+ ]),
722
+ id: z.string().optional(),
723
+ name: z.string().optional(),
724
+ arguments: z.record(z.string(), z.unknown()).optional(),
725
+ signature: z.string().optional(),
726
+ content: z.array(z.object({ type: z.string() }).passthrough()).optional(),
727
+ summary: z.array(z.object({
728
+ type: z.literal("text"),
729
+ text: z.string()
730
+ })).optional()
731
+ });
732
+ async function* googleEvents(response) {
733
+ if (!response.body) throw new Error("Google response has no stream");
734
+ const reader = response.body.getReader();
735
+ const decoder = new TextDecoder();
736
+ let buffer = "";
737
+ let bytes = 0;
738
+ try {
739
+ for (;;) {
740
+ const next = await reader.read();
741
+ bytes += next.value?.byteLength ?? 0;
742
+ if (bytes > 268435456) throw new Error("Google chat response exceeds its byte budget");
743
+ buffer += decoder.decode(next.value, { stream: !next.done });
744
+ buffer = buffer.replace(/\r\n/g, "\n");
745
+ let boundary = buffer.indexOf("\n\n");
746
+ while (boundary !== -1) {
747
+ const frame = buffer.slice(0, boundary);
748
+ buffer = buffer.slice(boundary + 2);
749
+ const data = frame.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
750
+ if (data) yield Event.parse(JSON.parse(data));
751
+ boundary = buffer.indexOf("\n\n");
752
+ }
753
+ if (Buffer.byteLength(buffer) > 16777216) throw new Error("Google stream frame exceeds its byte budget");
754
+ if (next.done) return;
755
+ }
756
+ } finally {
757
+ await reader.cancel().catch(() => {});
758
+ reader.releaseLock();
759
+ }
760
+ }
761
+ async function* mapGoogleStream(events, call, support, prefixFingerprint, maxTokens, outputSink, signal = new AbortController().signal, usageReporter) {
762
+ const steps = /* @__PURE__ */ new Map();
763
+ let imageCount = 0;
764
+ let imageBytes = 0;
765
+ let linkDisplay = false;
766
+ const addText = (state, raw, flush = false) => {
767
+ const text = state.display.push(raw, flush);
768
+ linkDisplay ||= state.display.link;
769
+ state.text += text;
770
+ if (text) {
771
+ const last = state.content.at(-1);
772
+ if (last?.type === "text") last.text += text;
773
+ else state.content.push({
774
+ type: "text",
775
+ text
776
+ });
777
+ }
778
+ return text;
779
+ };
780
+ const addImage = (state, item) => {
781
+ const mediaType = z.enum([
782
+ "image/png",
783
+ "image/jpeg",
784
+ "image/webp"
785
+ ]).parse(item.mime_type);
786
+ const data = z.string().min(1).parse(item.data);
787
+ imageCount++;
788
+ imageBytes += Math.ceil(data.length * 3 / 4);
789
+ if (imageCount > 8 || imageBytes > 268435456) throw new Error("Google image output exceeds its budget");
790
+ state.content.push({
791
+ type: "image",
792
+ mediaType,
793
+ data
794
+ });
795
+ };
796
+ let latestUsage;
797
+ let usageSequence = 0;
798
+ const reportUsage = () => {
799
+ if (!latestUsage) return;
800
+ usageReporter?.report({
801
+ sequence: ++usageSequence,
802
+ ...latestUsage.total_input_tokens === void 0 ? {} : { inputTokens: latestUsage.total_input_tokens },
803
+ ...latestUsage.total_output_tokens === void 0 || latestUsage.total_thought_tokens === void 0 ? {} : { outputTokens: latestUsage.total_output_tokens + latestUsage.total_thought_tokens },
804
+ ...latestUsage.total_cached_tokens === void 0 ? {} : { cacheReadTokens: latestUsage.total_cached_tokens }
805
+ });
806
+ };
807
+ for await (const event of events) {
808
+ if (event.metadata !== void 0) {
809
+ const metadata = z.object({ total_usage: Usage.partial().optional() }).parse(event.metadata);
810
+ if (metadata.total_usage !== void 0) {
811
+ latestUsage = {
812
+ ...latestUsage,
813
+ ...metadata.total_usage
814
+ };
815
+ reportUsage();
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
+ latestUsage = {
919
+ ...latestUsage,
920
+ ...final.usage
921
+ };
922
+ reportUsage();
923
+ const interaction = {
924
+ ...final,
925
+ usage: Usage.parse(latestUsage)
926
+ };
927
+ const usedOutput = interaction.usage.total_output_tokens + interaction.usage.total_thought_tokens;
928
+ if (!Number.isSafeInteger(usedOutput)) throw new Error("Google usage exceeds integer capacity");
929
+ const truncated = interaction.status === "budget_exceeded" || interaction.status === "incomplete" && maxTokens !== void 0 && usedOutput >= maxTokens;
930
+ if (interaction.status === "incomplete" && !truncated) throw new Error("Google incomplete response has no confirmed output-budget reason");
931
+ const incompleteToolCalls = [];
932
+ let incompleteThinking = false;
933
+ const content = [];
934
+ const signatures = [];
935
+ let ordinal = 0;
936
+ for (const state of steps.values()) {
937
+ if (!state.stopped && !truncated) throw new Error("Google interaction completed with an unfinished step");
938
+ if (!state.stopped && state.type === "function_call") {
939
+ incompleteToolCalls.push({
940
+ id: state.id ?? "",
941
+ ...state.name ? { name: state.name } : {}
942
+ });
943
+ continue;
944
+ }
945
+ if (!state.stopped && state.type === "thought") incompleteThinking = true;
946
+ if (state.type === "function_call") content.push({
947
+ type: "tool-use",
948
+ id: z.string().min(1).parse(state.id),
949
+ name: z.string().min(1).parse(state.name),
950
+ input: z.record(z.string(), z.unknown()).parse(JSON.parse(state.arguments || "{}"))
951
+ });
952
+ else if (state.type === "thought") {
953
+ if (state.stopped && state.signature) signatures.push({
954
+ part: content.length,
955
+ signature: state.signature
956
+ });
957
+ content.push({
958
+ type: "thinking",
959
+ text: state.text
960
+ });
961
+ } else {
962
+ const outputStart = content.length;
963
+ if (!state.stopped) addText(state, "", true);
964
+ for (const part of state.content) if (part.type === "text") content.push(part);
965
+ else {
966
+ if (!outputSink) throw new Error("Native image output has no session file receiver");
967
+ signal.throwIfAborted();
968
+ const bytes = googleImageBytes(part.data);
969
+ const result = await outputSink.publish({
970
+ ordinal: ordinal++,
971
+ mediaType: part.mediaType,
972
+ name: `generated.${part.mediaType.split("/")[1]}`,
973
+ body: (async function* () {
974
+ yield bytes;
975
+ })()
976
+ }, signal);
977
+ content.push({
978
+ type: "file",
979
+ file: result.file,
980
+ ...linkDisplay ? { display: "link" } : {}
981
+ });
982
+ }
983
+ if (state.stopped && state.signature && content.length > outputStart) signatures.push({
984
+ part: outputStart,
985
+ endPart: content.length - 1,
986
+ kind: "output",
987
+ signature: state.signature
988
+ });
989
+ }
990
+ }
991
+ const usage = interaction.usage;
992
+ const replayData = signatures.length && call.connectionFingerprint ? {
993
+ connectionFingerprint: call.connectionFingerprint,
994
+ prefixFingerprint,
995
+ responseFingerprint: googleResponseFingerprint(content, support),
996
+ thoughtTokens: usage.total_thought_tokens,
997
+ signatures
998
+ } : void 0;
999
+ if (replayData && Buffer.byteLength(JSON.stringify(replayData)) > 2097152) throw new Error("Google thought replay exceeds 2 MiB; continuing without its signature is unsafe");
1000
+ yield {
1001
+ kind: "final",
1002
+ finishReason: truncated ? "max-tokens" : interaction.status === "requires_action" ? "tool-calls" : "stop",
1003
+ ...incompleteToolCalls.length || incompleteThinking ? { outputTruncation: {
1004
+ incompleteToolCalls,
1005
+ ...incompleteThinking ? { incompleteThinking: true } : {}
1006
+ } } : {},
1007
+ usage: {
1008
+ inputTokens: usage.total_input_tokens,
1009
+ outputTokens: usedOutput,
1010
+ ...usage.total_cached_tokens === void 0 ? {} : { cacheReadTokens: usage.total_cached_tokens }
1011
+ },
1012
+ message: {
1013
+ role: "assistant",
1014
+ content
1015
+ },
1016
+ ...replayData ? { replayData } : {}
1017
+ };
1018
+ return;
1019
+ } else if (event.event_type === "error") throw new Error("Google stream reported an error");
1020
+ }
1021
+ throw support.interruptedFailure();
1022
+ }
1023
+ async function* googleJsonEvents(response) {
1024
+ const interaction = z.object({
1025
+ status: z.string(),
1026
+ usage: z.record(z.string(), z.unknown()),
1027
+ steps: z.array(z.object({ type: z.string() }).passthrough())
1028
+ }).parse((await readGoogleJson(response, 402653184)).body);
1029
+ for (const [index, step] of interaction.steps.entries()) {
1030
+ yield {
1031
+ event_type: "step.start",
1032
+ index,
1033
+ step
1034
+ };
1035
+ yield {
1036
+ event_type: "step.stop",
1037
+ index
1038
+ };
1039
+ }
1040
+ yield {
1041
+ event_type: "interaction.completed",
1042
+ interaction
1043
+ };
1044
+ }
1045
+ //#endregion
1046
+ //#region src/port.ts
1047
+ function createGooglePort(call, support, fetcher, options = {}) {
1048
+ function prepare(request) {
1049
+ const emitted = /* @__PURE__ */ new Map();
1050
+ const raw = buildGoogleRequest(call, request, support, false, (one) => {
1051
+ const group = emitted.get(one.messageIndex) ?? [];
1052
+ group.push(one);
1053
+ emitted.set(one.messageIndex, group);
1054
+ });
1055
+ const replaySelections = support.prepareReplaySelections(request, ({ message, messageIndex, part }) => {
1056
+ const emissions = emitted.get(messageIndex);
1057
+ if (!part) return {
1058
+ mode: "google-native",
1059
+ textIncluded: false,
1060
+ group: message.id,
1061
+ ...emissions?.length ? { selectedText: JSON.stringify(emissions.map(({ partIndex, kind, signature }) => ({
1062
+ partIndex,
1063
+ kind,
1064
+ signature
1065
+ }))) } : { reason: "not-applicable" }
1066
+ };
1067
+ const included = emissions?.some((one) => one.kind === "thought" && message.content[one.partIndex] === part) === true;
1068
+ return {
1069
+ mode: "google-native-summary",
1070
+ textIncluded: included && part.text !== "",
1071
+ group: message.id,
1072
+ reason: included ? "covered-by-native" : "not-applicable"
1073
+ };
1074
+ });
1075
+ const built = {
1076
+ ...raw,
1077
+ body: support.freezePayload(raw.body),
1078
+ capacity: support.freezePayload(raw.capacity ?? {})
1079
+ };
1080
+ const fields = /* @__PURE__ */ new Map();
1081
+ let mediaIndex = 0;
1082
+ const block = (item) => {
1083
+ if ((item.type === "thought" || item.type === "model_output") && typeof item.signature === "string") fields.set(item, /* @__PURE__ */ new Map([["signature", {
1084
+ kind: "replay",
1085
+ value: JSON.stringify({
1086
+ sha256: createHash("sha256").update(item.signature).digest("hex"),
1087
+ byteLength: Buffer.byteLength(item.signature),
1088
+ mode: `google-${item.type}`,
1089
+ model: built.body.model
1090
+ })
1091
+ }]]));
1092
+ if (item.type === "image") {
1093
+ const file = built.plan.sent[mediaIndex++];
1094
+ if (!file || item.data !== (file.data ?? "")) throw new Error("prepared_media_selection_mismatch");
1095
+ const data = file.data ?? "", hash = createHash("sha256");
1096
+ for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
1097
+ fields.set(item, /* @__PURE__ */ new Map([["data", {
1098
+ kind: "media",
1099
+ value: JSON.stringify({
1100
+ sha256: hash.digest("hex"),
1101
+ byteLength: Buffer.byteLength(data, "base64"),
1102
+ variantId: file.variantId,
1103
+ mediaType: file.mediaType,
1104
+ width: file.width,
1105
+ height: file.height
1106
+ })
1107
+ }]]));
1108
+ }
1109
+ for (const key of ["content", "result"]) if (Array.isArray(item[key])) {
1110
+ for (const child of item[key]) if (child && typeof child === "object") block(child);
1111
+ }
1112
+ };
1113
+ for (const step of built.body.input) block(step);
1114
+ if (mediaIndex !== built.plan.sent.length) throw new Error("prepared_media_selection_mismatch");
1115
+ return {
1116
+ ...built,
1117
+ replaySelections,
1118
+ fields,
1119
+ request: {
1120
+ ...request,
1121
+ params: support.freezePayload(request.params ?? {})
1122
+ },
1123
+ prefix: googlePrefix(call, request, support),
1124
+ hiddenInputTokens: googleHiddenInputTokens(call, request, support),
1125
+ fingerprint: support.freezePayload({
1126
+ protocol: call.protocolId,
1127
+ connection: call.connectionFingerprint,
1128
+ model: call.model,
1129
+ settings: built.body.generation_config
1130
+ })
1131
+ };
1132
+ }
1133
+ return support.createPreparedPort({
1134
+ prepare,
1135
+ semantics(payload) {
1136
+ return {
1137
+ replaySelections: payload.replaySelections,
1138
+ mediaSelections: () => support.mediaSelections(payload.plan),
1139
+ format: "request-semantic-v1",
1140
+ protocolId: call.protocolId,
1141
+ adapterVersion: "1",
1142
+ rendererVersion: "google-interactions-v1",
1143
+ parameters: Object.freeze(Object.fromEntries(Object.entries(payload.body).filter(([key]) => ![
1144
+ "model",
1145
+ "input",
1146
+ "system_instruction",
1147
+ "tools",
1148
+ "stream",
1149
+ "store"
1150
+ ].includes(key)))),
1151
+ toolDefinitions: payload.body.tools ?? Object.freeze([]),
1152
+ frames: () => support.semanticFrames(payload.body, {
1153
+ omitRoot: ["stream", "store"],
1154
+ fields: payload.fields
1155
+ })
1156
+ };
1157
+ },
1158
+ async inspect(payload, signal) {
1159
+ signal.throwIfAborted();
1160
+ const started = support.performance?.now();
1161
+ const { body, plan, capacity, maxTokens, request, hiddenInputTokens, fingerprint } = payload;
1162
+ support.performance?.observe({
1163
+ stage: "model.project",
1164
+ measurementPurpose: "request",
1165
+ durationMs: support.performance.now() - started,
1166
+ count: 1
1167
+ });
1168
+ const serialization = support.performance?.now();
1169
+ const text = googleRequestText(body);
1170
+ support.performance?.observe({
1171
+ stage: "model.serialize",
1172
+ measurementPurpose: "request",
1173
+ durationMs: support.performance.now() - serialization,
1174
+ count: 1
1175
+ });
1176
+ const inspection = support.inspect({
1177
+ body,
1178
+ request,
1179
+ capacity,
1180
+ textTokens: 0,
1181
+ textBytes: Buffer.byteLength(text),
1182
+ tokenizer: "utf8-bytes-quarter-v1",
1183
+ mediaTokens: plan.tokens,
1184
+ hiddenInputTokens,
1185
+ outputReserve: maxTokens ?? capacity?.output ?? 0,
1186
+ outputReserveSource: maxTokens === void 0 ? "capacity" : "enforced",
1187
+ fingerprint
1188
+ });
1189
+ const textTokens = await support.measureText(text, signal);
1190
+ signal.throwIfAborted();
1191
+ return {
1192
+ ...inspection,
1193
+ inputTokens: inspection.inputTokens + textTokens
1194
+ };
1195
+ },
1196
+ async *stream(built, signal, observer, scope) {
1197
+ signal.throwIfAborted();
1198
+ const { request, prefix } = built;
1199
+ const body = JSON.stringify(built.body);
1200
+ if (Buffer.byteLength(body) > 20971520) throw support.failures.create({
1201
+ code: "request-too-large",
1202
+ stage: "request",
1203
+ category: "request-too-large",
1204
+ source: "protocol",
1205
+ retryable: false
1206
+ });
1207
+ const url = googleUrl(call.config.baseUrl, "interactions");
1208
+ yield* support.withChatAttempts({
1209
+ retainCleanup: scope.retainCleanup,
1210
+ beforeAttempt: (_signal, ordinal) => observer?.beforeAttempt?.(ordinal),
1211
+ accountingDispatch: call.accountingDispatch,
1212
+ effective: {
1213
+ outputLimit: built.body.generation_config.max_output_tokens,
1214
+ effort: built.body.generation_config.thinking_level
1215
+ },
1216
+ signal,
1217
+ ...options,
1218
+ ...nativeImages(call, support) ? { maxRetries: 0 } : {},
1219
+ async *attempt(attemptSignal, progress, attempt, usageReporter) {
1220
+ const count = attempt + 1;
1221
+ const observe = (event) => {
1222
+ try {
1223
+ observer?.observe?.(event);
1224
+ } catch {}
1225
+ };
1226
+ observe({
1227
+ stage: "attempt",
1228
+ phase: "start",
1229
+ attempt: count
1230
+ });
1231
+ observe({
1232
+ stage: "first-response",
1233
+ phase: "start",
1234
+ attempt: count
1235
+ });
1236
+ let firstResponse = false;
1237
+ let ended = false;
1238
+ let outcome = "unknown";
1239
+ let timeout;
1240
+ const abortedOutcome = () => {
1241
+ const reason = support.failures.verified(attemptSignal.reason);
1242
+ if (reason?.code !== "stream-idle-timeout") return "cancelled";
1243
+ timeout = reason;
1244
+ return "timeout";
1245
+ };
1246
+ let unconsumed;
1247
+ const markDispatched = () => {
1248
+ try {
1249
+ observer?.dispatched({
1250
+ attempt,
1251
+ presentation: {
1252
+ schema: "chat.dispatch-settings.v1",
1253
+ data: {
1254
+ model: {
1255
+ availability: "resolved",
1256
+ value: built.body.model,
1257
+ origin: "protocol"
1258
+ },
1259
+ effort: built.body.generation_config.thinking_level ? {
1260
+ availability: "resolved",
1261
+ value: built.body.generation_config.thinking_level,
1262
+ origin: "protocol"
1263
+ } : {
1264
+ availability: "resolved",
1265
+ value: "default",
1266
+ origin: "protocol"
1267
+ }
1268
+ }
1269
+ }
1270
+ });
1271
+ } catch {}
1272
+ };
1273
+ try {
1274
+ attemptSignal.throwIfAborted();
1275
+ let response;
1276
+ try {
1277
+ const pending = fetcher(url, {
1278
+ method: "POST",
1279
+ headers: {
1280
+ "content-type": "application/json",
1281
+ "x-goog-api-key": call.secrets.apiKey ?? ""
1282
+ },
1283
+ body,
1284
+ signal: attemptSignal,
1285
+ redirect: "error"
1286
+ });
1287
+ markDispatched();
1288
+ response = await pending;
1289
+ unconsumed = response.body;
1290
+ } catch {
1291
+ attemptSignal.throwIfAborted();
1292
+ throw support.failures.create({
1293
+ code: "stream-interrupted",
1294
+ stage: "transport",
1295
+ category: "network",
1296
+ source: "transport",
1297
+ retryable: true
1298
+ });
1299
+ }
1300
+ attemptSignal.throwIfAborted();
1301
+ firstResponse = true;
1302
+ observe({
1303
+ stage: "first-response",
1304
+ phase: "end",
1305
+ attempt: count,
1306
+ outcome: "ok"
1307
+ });
1308
+ if (!response.ok) {
1309
+ const exceeded = await googleContextWindowExceeded(response);
1310
+ attemptSignal.throwIfAborted();
1311
+ const retryAfterHeader = response.headers.get("retry-after")?.trim();
1312
+ const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : NaN;
1313
+ const status = response.status;
1314
+ if (exceeded) throw support.failures.create({
1315
+ code: "context-window-exceeded",
1316
+ stage: "request",
1317
+ category: "request-too-large",
1318
+ source: "protocol",
1319
+ status,
1320
+ retryable: false
1321
+ });
1322
+ const failure = support.failures.create({
1323
+ code: status === 413 ? "request-too-large" : "http-error",
1324
+ stage: "transport",
1325
+ category: status === 413 ? "request-too-large" : "provider",
1326
+ source: "protocol",
1327
+ status,
1328
+ retryable: [
1329
+ 408,
1330
+ 409,
1331
+ 429
1332
+ ].includes(status) || status >= 500
1333
+ });
1334
+ throw Object.assign(failure, { retryAfterMs: Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter * 1e3 : void 0 });
1335
+ }
1336
+ if (!response.headers.get("content-type")?.toLowerCase().includes("text/event-stream") && !response.headers.get("content-type")?.toLowerCase().includes("application/json")) {
1337
+ await response.body?.cancel().catch(() => {});
1338
+ throw support.failures.create({
1339
+ code: "response-invalid",
1340
+ stage: "response-validation",
1341
+ category: "protocol",
1342
+ source: "protocol",
1343
+ retryable: false
1344
+ });
1345
+ }
1346
+ const observed = support.observeResponseProgress(response, progress);
1347
+ unconsumed = void 0;
1348
+ let final;
1349
+ 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, usageReporter)) {
1350
+ progress();
1351
+ 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");
1352
+ if (chunk.kind === "final" && nativeImages(call, support) && chunk.finishReason === "max-tokens") throw new Error("Truncated native image output cannot be automatically continued");
1353
+ if (chunk.kind === "final") {
1354
+ final = chunk;
1355
+ break;
1356
+ }
1357
+ yield chunk;
1358
+ }
1359
+ if (final) {
1360
+ outcome = "ok";
1361
+ ended = true;
1362
+ observe({
1363
+ stage: "attempt",
1364
+ phase: "end",
1365
+ attempt: count,
1366
+ outcome
1367
+ });
1368
+ yield final;
1369
+ }
1370
+ } catch (error) {
1371
+ outcome = attemptSignal.aborted ? abortedOutcome() : "error";
1372
+ throw error;
1373
+ } finally {
1374
+ if (unconsumed) {
1375
+ const body = unconsumed;
1376
+ scope.retainCleanup(async () => {
1377
+ await body.cancel();
1378
+ }).catch(() => {});
1379
+ }
1380
+ if (!firstResponse) observe({
1381
+ stage: "first-response",
1382
+ phase: "end",
1383
+ attempt: count,
1384
+ outcome,
1385
+ ...timeout ? { failure: timeout } : {}
1386
+ });
1387
+ if (!ended) observe({
1388
+ stage: "attempt",
1389
+ phase: "end",
1390
+ attempt: count,
1391
+ outcome,
1392
+ ...timeout ? { failure: timeout } : {}
1393
+ });
1394
+ }
1395
+ },
1396
+ classify(error) {
1397
+ if (support.failures.owns(error)) return {
1398
+ error,
1399
+ retryable: error.retryable === true,
1400
+ retryAfterMs: error.retryAfterMs
1401
+ };
1402
+ return {
1403
+ error: support.failures.create({
1404
+ code: "response-invalid",
1405
+ stage: "response-validation",
1406
+ category: "protocol",
1407
+ source: "protocol",
1408
+ retryable: false
1409
+ }),
1410
+ retryable: false
1411
+ };
1412
+ }
1413
+ });
1414
+ }
1415
+ });
1416
+ }
1417
+ //#endregion
1418
+ //#region src/probe.ts
1419
+ const Page = z.object({
1420
+ models: z.array(z.object({
1421
+ name: z.string().min(1),
1422
+ displayName: z.string().optional(),
1423
+ inputTokenLimit: z.number().int().positive().optional(),
1424
+ outputTokenLimit: z.number().int().positive().optional(),
1425
+ thinking: z.boolean().optional(),
1426
+ temperature: z.number().optional(),
1427
+ maxTemperature: z.number().optional(),
1428
+ supportedGenerationMethods: z.array(z.string()).optional()
1429
+ })).default([]),
1430
+ nextPageToken: z.string().optional()
1431
+ });
1432
+ async function pageOf(probe, fetcher, token, remaining, signal) {
1433
+ const url = new URL(googleUrl(probe.config.baseUrl, "models"));
1434
+ url.searchParams.set("pageSize", "100");
1435
+ if (token !== void 0) url.searchParams.set("pageToken", token);
1436
+ const response = await fetcher(url.href, {
1437
+ method: "GET",
1438
+ headers: { "x-goog-api-key": probe.secrets.apiKey ?? "" },
1439
+ signal,
1440
+ redirect: "error"
1441
+ });
1442
+ await requireGoogleSuccess(response);
1443
+ const result = await readGoogleJson(response, remaining);
1444
+ return {
1445
+ page: Page.parse(result.body),
1446
+ bytes: result.bytes
1447
+ };
1448
+ }
1449
+ async function listGoogleModels(probe, fetcher) {
1450
+ const offers = /* @__PURE__ */ new Map();
1451
+ const seen = /* @__PURE__ */ new Set();
1452
+ const signal = AbortSignal.any([probe.signal, AbortSignal.timeout(3e4)]);
1453
+ let remaining = Math.min(probe.maxResponseBytes ?? 8388608, 8388608);
1454
+ let token;
1455
+ for (let index = 0; index < 20; index += 1) {
1456
+ const result = await pageOf(probe, fetcher, token, remaining, signal);
1457
+ remaining -= result.bytes;
1458
+ for (const row of result.page.models) {
1459
+ const model = row.name.replace(/^models\//, "");
1460
+ if (!model || offers.has(model)) continue;
1461
+ const execution = googleCandidates(model);
1462
+ const sampled = row.temperature !== void 0 || row.maxTemperature !== void 0;
1463
+ offers.set(model, {
1464
+ model,
1465
+ ...row.displayName === void 0 ? {} : { name: row.displayName },
1466
+ ...row.inputTokenLimit === void 0 ? {} : { inputLimit: row.inputTokenLimit },
1467
+ ...row.outputTokenLimit === void 0 ? {} : { maxOutput: row.outputTokenLimit },
1468
+ ...row.thinking === void 0 ? {} : { reasoning: row.thinking },
1469
+ ...sampled ? { temperature: true } : {},
1470
+ ...row.supportedGenerationMethods === void 0 ? {} : { chat: row.supportedGenerationMethods.includes("generateContent") },
1471
+ execution
1472
+ });
1473
+ if (offers.size > 1e3) throw new Error("Google model listing exceeds 1000 models");
1474
+ }
1475
+ token = result.page.nextPageToken || void 0;
1476
+ if (token === void 0) return { offers: [...offers.values()] };
1477
+ if (seen.has(token)) throw new Error("Google model listing repeated a page token");
1478
+ seen.add(token);
1479
+ if (remaining < 1) throw new Error("Google model listing exhausted its byte budget");
1480
+ }
1481
+ throw new Error("Google model listing exceeds 20 pages");
1482
+ }
1483
+ async function testGoogleConnection(probe, fetcher) {
1484
+ await pageOf(probe, fetcher, void 0, probe.maxResponseBytes ?? 8388608, AbortSignal.any([probe.signal, AbortSignal.timeout(3e4)]));
1485
+ }
1486
+ //#endregion
1487
+ //#region src/support.ts
1488
+ function inputLimit(offer) {
1489
+ return Number.isSafeInteger(offer.inputLimit) && Number(offer.inputLimit) > 0 ? offer.inputLimit : void 0;
1490
+ }
1491
+ function normalizeOffers(input) {
1492
+ return Object.fromEntries(input.offers.map((offer) => [offer.model, {
1493
+ id: offer.model,
1494
+ ...offer.name === void 0 ? {} : { name: offer.name },
1495
+ ...offer.chat === void 0 ? {} : { chat: offer.chat },
1496
+ ...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
1497
+ ...offer.efforts?.length ? { reasoning_options: [{
1498
+ type: "effort",
1499
+ values: [...offer.efforts]
1500
+ }] } : {},
1501
+ ...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
1502
+ ...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
1503
+ ...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
1504
+ ...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
1505
+ ...offer.input === void 0 ? {} : { input: [...offer.input] },
1506
+ ...offer.output === void 0 ? {} : { output: [...offer.output] }
1507
+ } },
1508
+ ...!offer.contextWindow && inputLimit(offer) === void 0 && !offer.maxOutput ? {} : { limit: {
1509
+ ...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
1510
+ ...inputLimit(offer) === void 0 ? {} : { input: inputLimit(offer) },
1511
+ ...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
1512
+ } },
1513
+ ...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
1514
+ }]));
1515
+ }
1516
+ function lazySupport(read) {
1517
+ return new Proxy({}, { get(_target, key) {
1518
+ if (key === "normalizeListing") return normalizeOffers;
1519
+ const service = read();
1520
+ if (!service) throw new Error("Chat model support is unavailable");
1521
+ const value = Reflect.get(service, key);
1522
+ return typeof value === "function" ? value.bind(service) : value;
1523
+ } });
1524
+ }
1525
+ //#endregion
1526
+ //#region src/protocol.ts
1527
+ function googleProtocolType(support, fetcher) {
1528
+ return {
1529
+ type: "gemini-interactions",
1530
+ label: "Gemini Interactions API",
1531
+ logo: GEMINI_LOGO,
1532
+ fields: [{
1533
+ key: "baseUrl",
1534
+ kind: "url",
1535
+ label: "Base URL",
1536
+ required: true
1537
+ }],
1538
+ userConfigurable: true,
1539
+ optionsSchema: z.strictObject({}),
1540
+ facts,
1541
+ executionCandidates: ({ model, capabilities }) => capabilities?.imageGeneration === "supported" || capabilities?.imageEdit === "supported" ? [{
1542
+ profile: "google-image-v1",
1543
+ label: "Gemini image generation",
1544
+ chat: capabilities.chat !== "unsupported",
1545
+ generation: ["image"]
1546
+ }] : googleCandidates(model),
1547
+ validateExecution: validateGoogleExecution,
1548
+ prepareParams(input) {
1549
+ const effective = { ...input.params };
1550
+ const changes = [];
1551
+ for (const [key, value] of Object.entries(input.params)) try {
1552
+ validateGoogleParams(input.model, { [key]: value });
1553
+ } catch (error) {
1554
+ if (input.explicitKeys.includes(key)) throw error;
1555
+ delete effective[key];
1556
+ changes.push({
1557
+ field: key,
1558
+ reason: "incompatible inherited parameter"
1559
+ });
1560
+ }
1561
+ const result = support.prepareParams({
1562
+ ...input,
1563
+ params: effective
1564
+ }, facts);
1565
+ validateGoogleParams(input.model, result.effectiveParams);
1566
+ return {
1567
+ ...result,
1568
+ changes: [...changes, ...result.changes]
1569
+ };
1570
+ },
1571
+ effortCacheCapability: () => ({
1572
+ status: "unknown",
1573
+ reason: "google-effort-cache-unverified"
1574
+ }),
1575
+ adapters: {
1576
+ chat: {
1577
+ fileKinds: ["image"],
1578
+ toolCalling(model, input) {
1579
+ const toolCall = support.catalogue(input.providerId, model)?.tool_call;
1580
+ return input.configuredModels.find((row) => row.id === model)?.capabilities?.toolCalling ?? (toolCall === true ? "supported" : toolCall === false ? "unsupported" : "unknown");
1581
+ },
1582
+ nativeOutputKinds(model, input) {
1583
+ const capabilities = input.configuredModels.find((row) => row.id === model)?.capabilities;
1584
+ const state = capabilities?.imageGeneration;
1585
+ return state === "supported" || capabilities?.imageEdit === "supported" || state === void 0 && support.catalogue(input.providerId, model)?.modalities?.output?.includes("image") ? ["image"] : [];
1586
+ },
1587
+ nativeImageParamsSchema: (model) => googleImageParamsSchema(model),
1588
+ supportsModel(model, input) {
1589
+ 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");
1590
+ },
1591
+ createPort: (call) => createGooglePort(call, support, withConnectionHeaders(fetcher, call.headers))
1592
+ },
1593
+ image: {
1594
+ models: googleGenerationModels,
1595
+ createPort: (call) => createGoogleGenerationPort(call, withConnectionHeaders(fetcher, call.headers))
1596
+ }
1597
+ },
1598
+ normalizeListing: (input) => normalizeOffers(input),
1599
+ listModels: (probe) => listGoogleModels(probe, withConnectionHeaders(fetcher, probe.headers)),
1600
+ testConnection: (probe) => testGoogleConnection(probe, withConnectionHeaders(fetcher, probe.headers))
1601
+ };
1602
+ }
1603
+ //#endregion
1604
+ //#region src/index.ts
1605
+ const TOOL_NAMES = [];
1606
+ const plugin = {
1607
+ name: "@eum-agent/llm-protocol-google",
1608
+ requires: ["network"],
1609
+ optionalServices: ["model-support"],
1610
+ apply(ctx) {
1611
+ const support = lazySupport(() => ctx.services.find("model-support"));
1612
+ const network = ctx.services.get("network");
1613
+ ctx.modelProtocols.register(googleProtocolType(support, network.fetch));
1614
+ }
1615
+ };
1616
+ //#endregion
1617
+ export { TOOL_NAMES, plugin as default };