sliccy 1.27.0 → 1.28.1

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.
Files changed (26) hide show
  1. package/dist/node-server/index.js +37 -2
  2. package/dist/ui/assets/{___vite-browser-external_commonjs-proxy-Czotfmsq.js → ___vite-browser-external_commonjs-proxy-Cmb9zBUT.js} +1 -1
  3. package/dist/ui/assets/{anthropic-CvUpvFkp.js → anthropic-DuWlRZpT.js} +1 -1
  4. package/dist/ui/assets/{azure-openai-responses-DAU0aqrX.js → azure-openai-responses-Mf18OBAm.js} +1 -1
  5. package/dist/ui/assets/{bsh-watchdog-DcTLZJqx.js → bsh-watchdog-Cy8-MCiI.js} +1 -1
  6. package/dist/ui/assets/{google-hRTz4OcZ.js → google-dnYjk8Fg.js} +1 -1
  7. package/dist/ui/assets/{google-gemini-cli-BMtWjx3t.js → google-gemini-cli-CW5TUXrG.js} +1 -1
  8. package/dist/ui/assets/{google-shared-BSXV7Vjo.js → google-shared-52YT-STV.js} +1 -1
  9. package/dist/ui/assets/{google-vertex-DCpAvsSC.js → google-vertex-Cvd06MOV.js} +1 -1
  10. package/dist/ui/assets/{index-BbXBcqok.js → index-COxfqL_6.js} +13 -11
  11. package/dist/ui/assets/{index-DEEWGtRY.js → index-Cif-vpwj.js} +1 -1
  12. package/dist/ui/assets/{index-D1_eVqdL.js → index-Cj5FGv1O.js} +1 -1
  13. package/dist/ui/assets/{index-D8puAOsm.js → index-D5qCAmuj.js} +1 -1
  14. package/dist/ui/assets/{index-DshXoVK5.js → index-qZV7PBFf.js} +1 -1
  15. package/dist/ui/assets/{json-parse-23H3GokV.js → json-parse-DPL6t0PZ.js} +1 -1
  16. package/dist/ui/assets/{mistral-Ce_z06MB.js → mistral-CqzEB3Wd.js} +1 -1
  17. package/dist/ui/assets/{offscreen-client-BA5Wb9j5.js → offscreen-client-EF1SfFBJ.js} +1 -1
  18. package/dist/ui/assets/{openai-codex-responses-BN7TJ_eK.js → openai-codex-responses-DjhHU788.js} +1 -1
  19. package/dist/ui/assets/{openai-completions-EQOCui9u.js → openai-completions-DI3BzoVD.js} +1 -1
  20. package/dist/ui/assets/{openai-responses-BbToVHpR.js → openai-responses-CDRmRVXg.js} +1 -1
  21. package/dist/ui/assets/{openai-responses-shared-DsOu_P3E.js → openai-responses-shared-xnWIf7Sq.js} +1 -1
  22. package/dist/ui/assets/{pyodide-DB-oYC4I.js → pyodide-D7VX_btJ.js} +1 -1
  23. package/dist/ui/assets/{sql-wasm-CFrqANfF.js → sql-wasm-CFjKorYF.js} +1 -1
  24. package/dist/ui/index.html +1 -1
  25. package/dist/ui/packages/webapp/index.html +1 -1
  26. package/package.json +1 -1
@@ -786,6 +786,8 @@ async function main() {
786
786
  'content-length',
787
787
  'transfer-encoding',
788
788
  'x-proxy-cookie',
789
+ 'x-proxy-origin',
790
+ 'x-proxy-referer',
789
791
  ]);
790
792
  const headers = {};
791
793
  for (const [key, value] of Object.entries(req.headers)) {
@@ -796,8 +798,41 @@ async function main() {
796
798
  // Forbidden-header transport: browser cannot send Cookie via fetch(),
797
799
  // so the client encodes it as X-Proxy-Cookie. Restore it here.
798
800
  const proxyCookie = req.headers['x-proxy-cookie'];
799
- if (typeof proxyCookie === 'string') {
800
- headers['cookie'] = proxyCookie;
801
+ if (proxyCookie) {
802
+ headers['cookie'] = Array.isArray(proxyCookie) ? proxyCookie[0] : proxyCookie;
803
+ }
804
+ // Helper: check if an origin/referer value is a localhost URL
805
+ function isLocalhostOrigin(origin) {
806
+ if (!origin)
807
+ return false;
808
+ try {
809
+ const url = new URL(origin);
810
+ return (url.hostname === 'localhost' ||
811
+ url.hostname === '127.0.0.1' ||
812
+ url.hostname === '::1' ||
813
+ url.hostname === '[::1]');
814
+ }
815
+ catch {
816
+ return false;
817
+ }
818
+ }
819
+ // Forbidden-header transport: restore X-Proxy-Origin → Origin
820
+ const proxyOrigin = req.headers['x-proxy-origin'];
821
+ if (proxyOrigin) {
822
+ headers['origin'] = Array.isArray(proxyOrigin) ? proxyOrigin[0] : proxyOrigin;
823
+ }
824
+ else if (isLocalhostOrigin(headers['origin'])) {
825
+ // Only strip browser's auto-added localhost origin, preserve legitimate origins
826
+ delete headers['origin'];
827
+ }
828
+ // Forbidden-header transport: restore X-Proxy-Referer → Referer
829
+ const proxyReferer = req.headers['x-proxy-referer'];
830
+ if (proxyReferer) {
831
+ headers['referer'] = Array.isArray(proxyReferer) ? proxyReferer[0] : proxyReferer;
832
+ }
833
+ else if (isLocalhostOrigin(headers['referer'])) {
834
+ // Only strip browser's auto-added localhost referer, preserve legitimate referers
835
+ delete headers['referer'];
801
836
  }
802
837
  // Restore any X-Proxy-Proxy-* transport headers as Proxy-* headers
803
838
  for (const [key, value] of Object.entries(req.headers)) {
@@ -1 +1 @@
1
- import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{f as r}from"./index-BbXBcqok.js";const a=r(e);export{a as r};
1
+ import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{f as r}from"./index-COxfqL_6.js";const a=r(e);export{a as r};
@@ -1,4 +1,4 @@
1
- import{A as Us,g as Zt,a as Mt,b as Fs,K as Ds,t as Hs}from"./index-BbXBcqok.js";import{p as Rt}from"./json-parse-23H3GokV.js";import{s as j}from"./sanitize-unicode-cmozpu7l.js";import{h as Js,b as Xs}from"./github-copilot-headers-CrHPofPv.js";function f(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function a(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let es=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return es=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function ye(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const ot=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class g extends Error{}class S extends g{constructor(e,t,s,r){super(`${S.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new Je({message:s,cause:ot(t)});const i=t;return e===400?new ss(e,i,s,r):e===401?new ns(e,i,s,r):e===403?new rs(e,i,s,r):e===404?new is(e,i,s,r):e===409?new as(e,i,s,r):e===422?new os(e,i,s,r):e===429?new cs(e,i,s,r):e>=500?new ls(e,i,s,r):new S(e,i,s,r)}}class v extends S{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Je extends S{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ts extends Je{constructor({message:e}={}){super({message:e??"Request timed out."})}}class ss extends S{}class ns extends S{}class rs extends S{}class is extends S{}class as extends S{}class os extends S{}class cs extends S{}class ls extends S{}const Ks=/^[a-z][a-z0-9+.-]*:/i,Vs=n=>Ks.test(n);let ct=n=>(ct=Array.isArray,ct(n)),Tt=ct;function lt(n){return typeof n!="object"?{}:n??{}}function zs(n){if(!n)return!0;for(const e in n)return!1;return!0}function Qs(n,e){return Object.prototype.hasOwnProperty.call(n,e)}const Gs=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${n} must be an integer`);if(e<0)throw new g(`${n} must be a positive integer`);return e},us=n=>{try{return JSON.parse(n)}catch{return}},Ys=n=>new Promise(e=>setTimeout(e,n)),z="0.73.0",Zs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function en(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const tn=()=>{const n=en();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Et(Deno.build.os),"X-Stainless-Arch":Pt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Et(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Pt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=sn();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function sn(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,o=s[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}const Pt=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Et=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let vt;const nn=()=>vt??(vt=tn());function rn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function hs(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function ds(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return hs({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function pt(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function an(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const on=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function cn(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let At;function gt(n){let e;return(At??(e=new globalThis.TextEncoder,At=e.encode.bind(e)))(n)}let Ot;function It(n){let e;return(Ot??(e=new globalThis.TextDecoder,Ot=e.decode.bind(e)))(n)}var R,T;class be{constructor(){R.set(this,void 0),T.set(this,void 0),f(this,R,new Uint8Array),f(this,T,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;f(this,R,cn([a(this,R,"f"),t]));const s=[];let r;for(;(r=ln(a(this,R,"f"),a(this,T,"f")))!=null;){if(r.carriage&&a(this,T,"f")==null){f(this,T,r.index);continue}if(a(this,T,"f")!=null&&(r.index!==a(this,T,"f")+1||r.carriage)){s.push(It(a(this,R,"f").subarray(0,a(this,T,"f")-1))),f(this,R,a(this,R,"f").subarray(a(this,T,"f"))),f(this,T,null);continue}const i=a(this,T,"f")!==null?r.preceding-1:r.preceding,o=It(a(this,R,"f").subarray(0,i));s.push(o),f(this,R,a(this,R,"f").subarray(r.index)),f(this,T,null)}return s}flush(){return a(this,R,"f").length?this.decode(`
1
+ import{A as Us,g as Zt,a as Mt,b as Fs,K as Ds,t as Hs}from"./index-COxfqL_6.js";import{p as Rt}from"./json-parse-DPL6t0PZ.js";import{s as j}from"./sanitize-unicode-cmozpu7l.js";import{h as Js,b as Xs}from"./github-copilot-headers-CrHPofPv.js";function f(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function a(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let es=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return es=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function ye(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const ot=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class g extends Error{}class S extends g{constructor(e,t,s,r){super(`${S.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new Je({message:s,cause:ot(t)});const i=t;return e===400?new ss(e,i,s,r):e===401?new ns(e,i,s,r):e===403?new rs(e,i,s,r):e===404?new is(e,i,s,r):e===409?new as(e,i,s,r):e===422?new os(e,i,s,r):e===429?new cs(e,i,s,r):e>=500?new ls(e,i,s,r):new S(e,i,s,r)}}class v extends S{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Je extends S{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ts extends Je{constructor({message:e}={}){super({message:e??"Request timed out."})}}class ss extends S{}class ns extends S{}class rs extends S{}class is extends S{}class as extends S{}class os extends S{}class cs extends S{}class ls extends S{}const Ks=/^[a-z][a-z0-9+.-]*:/i,Vs=n=>Ks.test(n);let ct=n=>(ct=Array.isArray,ct(n)),Tt=ct;function lt(n){return typeof n!="object"?{}:n??{}}function zs(n){if(!n)return!0;for(const e in n)return!1;return!0}function Qs(n,e){return Object.prototype.hasOwnProperty.call(n,e)}const Gs=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${n} must be an integer`);if(e<0)throw new g(`${n} must be a positive integer`);return e},us=n=>{try{return JSON.parse(n)}catch{return}},Ys=n=>new Promise(e=>setTimeout(e,n)),z="0.73.0",Zs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function en(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const tn=()=>{const n=en();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Et(Deno.build.os),"X-Stainless-Arch":Pt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Et(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Pt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=sn();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function sn(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,o=s[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}const Pt=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Et=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let vt;const nn=()=>vt??(vt=tn());function rn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function hs(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function ds(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return hs({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function pt(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function an(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const on=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function cn(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let At;function gt(n){let e;return(At??(e=new globalThis.TextEncoder,At=e.encode.bind(e)))(n)}let Ot;function It(n){let e;return(Ot??(e=new globalThis.TextDecoder,Ot=e.decode.bind(e)))(n)}var R,T;class be{constructor(){R.set(this,void 0),T.set(this,void 0),f(this,R,new Uint8Array),f(this,T,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;f(this,R,cn([a(this,R,"f"),t]));const s=[];let r;for(;(r=ln(a(this,R,"f"),a(this,T,"f")))!=null;){if(r.carriage&&a(this,T,"f")==null){f(this,T,r.index);continue}if(a(this,T,"f")!=null&&(r.index!==a(this,T,"f")+1||r.carriage)){s.push(It(a(this,R,"f").subarray(0,a(this,T,"f")-1))),f(this,R,a(this,R,"f").subarray(a(this,T,"f"))),f(this,T,null);continue}const i=a(this,T,"f")!==null?r.preceding-1:r.preceding,o=It(a(this,R,"f").subarray(0,i));s.push(o),f(this,R,a(this,R,"f").subarray(r.index)),f(this,T,null)}return s}flush(){return a(this,R,"f").length?this.decode(`
2
2
  `):[]}}R=new WeakMap,T=new WeakMap;be.NEWLINE_CHARS=new Set([`
3
3
  `,"\r"]);be.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ln(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function un(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}const Fe={off:0,error:200,warn:300,info:400,debug:500},Bt=(n,e,t)=>{if(n){if(Qs(Fe,n))return n;x(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Fe))}`)}};function ge(){}function xe(n,e,t){return!e||Fe[n]>Fe[t]?ge:e[n].bind(e)}const hn={error:ge,warn:ge,info:ge,debug:ge};let $t=new WeakMap;function x(n){const e=n.logger,t=n.logLevel??"off";if(!e)return hn;const s=$t.get(e);if(s&&s[0]===t)return s[1];const r={error:xe("error",e,t),warn:xe("warn",e,t),info:xe("info",e,t),debug:xe("debug",e,t)};return $t.set(e,[t,r]),r}const H=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var Z;class I{constructor(e,t,s){this.iterator=e,Z.set(this,void 0),this.controller=t,f(this,Z,s)}static fromSSEResponse(e,t,s){let r=!1;const i=s?x(s):console;async function*o(){if(r)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of dn(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(l.event!=="ping"&&l.event==="error")throw new S(void 0,us(l.data)??l.data,void 0,e.headers)}c=!0}catch(l){if(ye(l))return;throw l}finally{c||t.abort()}}return new I(o,t,s)}static fromReadableStream(e,t,s){let r=!1;async function*i(){const c=new be,l=pt(e);for await(const d of l)for(const p of c.decode(d))yield p;for(const d of c.flush())yield d}async function*o(){if(r)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of i())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(ye(l))return;throw l}finally{c||t.abort()}}return new I(o,t,s)}[(Z=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const o=s.next();e.push(o),t.push(o)}return i.shift()}});return[new I(()=>r(e),this.controller,a(this,Z,"f")),new I(()=>r(t),this.controller,a(this,Z,"f"))]}toReadableStream(){const e=this;let t;return hs({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await t.next();if(i)return s.close();const o=gt(JSON.stringify(r)+`
4
4
  `);s.enqueue(o)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*dn(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new g("Attempted to iterate over a response with no body");const t=new pn,s=new be,r=pt(n.body);for await(const i of fn(r))for(const o of s.decode(i)){const c=t.decode(o);c&&(yield c)}for(const i of s.flush()){const o=t.decode(i);o&&(yield o)}}async function*fn(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?gt(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=un(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class pn{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
@@ -1 +1 @@
1
- import{O as f,a as c,r as m,i as E,b as _}from"./client-DFw1b8C8.js";import{A as h,g as l,b as R,s as y,d as I}from"./index-BbXBcqok.js";import{p as O,c as N,a as g}from"./openai-responses-shared-DsOu_P3E.js";import"./hash-DMDecQcg.js";import"./json-parse-23H3GokV.js";import"./sanitize-unicode-cmozpu7l.js";var b={};class v extends f{constructor({baseURL:r=m("OPENAI_BASE_URL"),apiKey:e=m("AZURE_OPENAI_API_KEY"),apiVersion:t=m("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:o,dangerouslyAllowBrowser:i,...u}={}){if(!t)throw new c("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o=="function"&&(i=!0),!o&&!e)throw new c("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&e)throw new c("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(u.defaultQuery={...u.defaultQuery,"api-version":t},r){if(n)throw new c("baseURL and endpoint are mutually exclusive")}else{if(n||(n=b.AZURE_OPENAI_ENDPOINT),!n)throw new c("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");r=`${n}/openai`}super({apiKey:o??e,baseURL:r,...u,...i!==void 0?{dangerouslyAllowBrowser:i}:{}}),this.apiVersion="",this.apiVersion=t,this.deploymentName=a}async buildRequest(r,e={}){if(P.has(r.path)&&r.method==="post"&&r.body!==void 0){if(!E(r.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||r.body.model||r.__metadata?.model;t!==void 0&&!this.baseURL.includes("/deployments")&&(r.path=`/deployments/${t}${r.path}`)}return super.buildRequest(r,e)}async authHeaders(r){return typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(r)}}const P=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var p={};const U="v1",w=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function S(s){const r=new Map;if(!s)return r;for(const e of s.split(",")){const t=e.trim();if(!t)continue;const[n,a]=t.split("=",2);!n||!a||r.set(n.trim(),a.trim())}return r}function z(s,r){return r?.azureDeploymentName?r.azureDeploymentName:S(p.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(s.id)||s.id}const Z=(s,r,e)=>{const t=new h;return(async()=>{const n=z(s,e),a={role:"assistant",content:[],api:"azure-openai-responses",provider:s.provider,model:s.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const o=e?.apiKey||l(s.provider)||"",i=L(s,o,e);let u=V(s,r,e,n);const d=await e?.onPayload?.(u,s);d!==void 0&&(u=d);const A=await i.responses.create(u,e?.signal?{signal:e.signal}:void 0);if(t.push({type:"start",partial:a}),await O(A,a,t,s),e?.signal?.aborted)throw new Error("Request was aborted");if(a.stopReason==="aborted"||a.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:a.stopReason,message:a}),t.end()}catch(o){for(const i of a.content)delete i.index;a.stopReason=e?.signal?.aborted?"aborted":"error",a.errorMessage=o instanceof Error?o.message:JSON.stringify(o),t.push({type:"error",reason:a.stopReason,error:a}),t.end()}})(),t},Y=(s,r,e)=>{const t=e?.apiKey||l(s.provider);if(!t)throw new Error(`No API key for provider: ${s.provider}`);const n=R(s,e,t),a=y(s)?e?.reasoning:I(e?.reasoning);return Z(s,r,{...n,reasoningEffort:a})};function M(s){return s.replace(/\/+$/,"")}function D(s){return`https://${s}.openai.azure.com/openai/v1`}function K(s,r){const e=r?.azureApiVersion||p.AZURE_OPENAI_API_VERSION||U,t=r?.azureBaseUrl?.trim()||p.AZURE_OPENAI_BASE_URL?.trim()||void 0,n=r?.azureResourceName||p.AZURE_OPENAI_RESOURCE_NAME;let a=t;if(!a&&n&&(a=D(n)),!a&&s.baseUrl&&(a=s.baseUrl),!a)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:M(a),apiVersion:e}}function L(s,r,e){if(!r){if(!p.AZURE_OPENAI_API_KEY)throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");r=p.AZURE_OPENAI_API_KEY}const t={...s.headers};e?.headers&&Object.assign(t,e.headers);const{baseUrl:n,apiVersion:a}=K(s,e);return new v({apiKey:r,apiVersion:a,dangerouslyAllowBrowser:!0,defaultHeaders:t,baseURL:n})}function V(s,r,e,t){const n=N(s,r,w),a={model:t,input:n,stream:!0,prompt_cache_key:e?.sessionId};return e?.maxTokens&&(a.max_output_tokens=e?.maxTokens),e?.temperature!==void 0&&(a.temperature=e?.temperature),r.tools&&(a.tools=g(r.tools)),s.reasoning&&(e?.reasoningEffort||e?.reasoningSummary?(a.reasoning={effort:e?.reasoningEffort||"medium",summary:e?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]):a.reasoning={effort:"none"}),a}export{Z as streamAzureOpenAIResponses,Y as streamSimpleAzureOpenAIResponses};
1
+ import{O as f,a as c,r as m,i as E,b as _}from"./client-DFw1b8C8.js";import{A as h,g as l,b as R,s as y,d as I}from"./index-COxfqL_6.js";import{p as O,c as N,a as g}from"./openai-responses-shared-xnWIf7Sq.js";import"./hash-DMDecQcg.js";import"./json-parse-DPL6t0PZ.js";import"./sanitize-unicode-cmozpu7l.js";var b={};class v extends f{constructor({baseURL:r=m("OPENAI_BASE_URL"),apiKey:e=m("AZURE_OPENAI_API_KEY"),apiVersion:t=m("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:o,dangerouslyAllowBrowser:i,...u}={}){if(!t)throw new c("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o=="function"&&(i=!0),!o&&!e)throw new c("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&e)throw new c("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(u.defaultQuery={...u.defaultQuery,"api-version":t},r){if(n)throw new c("baseURL and endpoint are mutually exclusive")}else{if(n||(n=b.AZURE_OPENAI_ENDPOINT),!n)throw new c("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");r=`${n}/openai`}super({apiKey:o??e,baseURL:r,...u,...i!==void 0?{dangerouslyAllowBrowser:i}:{}}),this.apiVersion="",this.apiVersion=t,this.deploymentName=a}async buildRequest(r,e={}){if(P.has(r.path)&&r.method==="post"&&r.body!==void 0){if(!E(r.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||r.body.model||r.__metadata?.model;t!==void 0&&!this.baseURL.includes("/deployments")&&(r.path=`/deployments/${t}${r.path}`)}return super.buildRequest(r,e)}async authHeaders(r){return typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(r)}}const P=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var p={};const U="v1",w=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function S(s){const r=new Map;if(!s)return r;for(const e of s.split(",")){const t=e.trim();if(!t)continue;const[n,a]=t.split("=",2);!n||!a||r.set(n.trim(),a.trim())}return r}function z(s,r){return r?.azureDeploymentName?r.azureDeploymentName:S(p.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(s.id)||s.id}const Z=(s,r,e)=>{const t=new h;return(async()=>{const n=z(s,e),a={role:"assistant",content:[],api:"azure-openai-responses",provider:s.provider,model:s.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const o=e?.apiKey||l(s.provider)||"",i=L(s,o,e);let u=V(s,r,e,n);const d=await e?.onPayload?.(u,s);d!==void 0&&(u=d);const A=await i.responses.create(u,e?.signal?{signal:e.signal}:void 0);if(t.push({type:"start",partial:a}),await O(A,a,t,s),e?.signal?.aborted)throw new Error("Request was aborted");if(a.stopReason==="aborted"||a.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:a.stopReason,message:a}),t.end()}catch(o){for(const i of a.content)delete i.index;a.stopReason=e?.signal?.aborted?"aborted":"error",a.errorMessage=o instanceof Error?o.message:JSON.stringify(o),t.push({type:"error",reason:a.stopReason,error:a}),t.end()}})(),t},Y=(s,r,e)=>{const t=e?.apiKey||l(s.provider);if(!t)throw new Error(`No API key for provider: ${s.provider}`);const n=R(s,e,t),a=y(s)?e?.reasoning:I(e?.reasoning);return Z(s,r,{...n,reasoningEffort:a})};function M(s){return s.replace(/\/+$/,"")}function D(s){return`https://${s}.openai.azure.com/openai/v1`}function K(s,r){const e=r?.azureApiVersion||p.AZURE_OPENAI_API_VERSION||U,t=r?.azureBaseUrl?.trim()||p.AZURE_OPENAI_BASE_URL?.trim()||void 0,n=r?.azureResourceName||p.AZURE_OPENAI_RESOURCE_NAME;let a=t;if(!a&&n&&(a=D(n)),!a&&s.baseUrl&&(a=s.baseUrl),!a)throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:M(a),apiVersion:e}}function L(s,r,e){if(!r){if(!p.AZURE_OPENAI_API_KEY)throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");r=p.AZURE_OPENAI_API_KEY}const t={...s.headers};e?.headers&&Object.assign(t,e.headers);const{baseUrl:n,apiVersion:a}=K(s,e);return new v({apiKey:r,apiVersion:a,dangerouslyAllowBrowser:!0,defaultHeaders:t,baseURL:n})}function V(s,r,e,t){const n=N(s,r,w),a={model:t,input:n,stream:!0,prompt_cache_key:e?.sessionId};return e?.maxTokens&&(a.max_output_tokens=e?.maxTokens),e?.temperature!==void 0&&(a.temperature=e?.temperature),r.tools&&(a.tools=g(r.tools)),s.reasoning&&(e?.reasoningEffort||e?.reasoningSummary?(a.reasoning={effort:e?.reasoningEffort||"medium",summary:e?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]):a.reasoning={effort:"none"}),a}export{Z as streamAzureOpenAIResponses,Y as streamSimpleAzureOpenAIResponses};
@@ -1,4 +1,4 @@
1
- import{c as l}from"./index-BbXBcqok.js";const p=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of p)await s.exists(r)&&await g(s,r,t,e);return t}async function g(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const o=m(n);if(!o)continue;const i=await s.readFile(n,{encoding:"utf-8"}),h=typeof i=="string"?i:new TextDecoder().decode(i),a=v(h);e.push({path:n,hostnamePattern:o,matchPatterns:a})}}function m(s){const t=s.split("/").pop()??"";if(!t.endsWith(".bsh"))return null;const e=t.slice(0,-4);return e?e.startsWith("-.")?"*"+e.slice(1):e:null}function v(s){const t=s.split(`
1
+ import{c as l}from"./index-COxfqL_6.js";const p=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of p)await s.exists(r)&&await g(s,r,t,e);return t}async function g(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const o=m(n);if(!o)continue;const i=await s.readFile(n,{encoding:"utf-8"}),h=typeof i=="string"?i:new TextDecoder().decode(i),a=v(h);e.push({path:n,hostnamePattern:o,matchPatterns:a})}}function m(s){const t=s.split("/").pop()??"";if(!t.endsWith(".bsh"))return null;const e=t.slice(0,-4);return e?e.startsWith("-.")?"*"+e.slice(1):e:null}function v(s){const t=s.split(`
2
2
  `).slice(0,10),e=[];for(const r of t){const n=r.match(/^\s*\/\/\s*@match\s+(.+)$/);n&&e.push(n[1].trim())}return e}function u(s,t){if(t.startsWith("*.")){const e=t.slice(1);return s.endsWith(e)&&s.length>e.length}return s===t}function w(s,t){try{const e=new URL(s),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;const[,n,o,i]=r;return n!=="*"&&e.protocol.slice(0,-1)!==n||!u(e.hostname,o)?!1:i?y(e.pathname+e.search,i):!0}catch{return!1}}function y(s,t){const e="^"+t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$";return new RegExp(e).test(s)}function x(s,t){try{const e=new URL(t);return s.filter(r=>u(e.hostname,r.hostnamePattern)?r.matchPatterns.length>0?r.matchPatterns.some(n=>w(t,n)):!0:!1)}catch{return[]}}const c=l("bsh-watchdog");class P{transport;fs;discoveryIntervalMs;entries=[];discoveryTimer=null;running=!1;executing=new Set;constructor(t){this.transport=t.transport,this.fs=t.fs,this.discoveryIntervalMs=t.discoveryIntervalMs??3e4}async start(){this.running||(this.running=!0,await this.discover(),this.discoveryTimer=setInterval(()=>{this.discover()},this.discoveryIntervalMs),this.transport.on("Page.frameNavigated",this.onFrameNavigated),c.info("BSH watchdog started",{scriptCount:this.entries.length}))}stop(){this.running&&(this.running=!1,this.transport.off("Page.frameNavigated",this.onFrameNavigated),this.discoveryTimer&&(clearInterval(this.discoveryTimer),this.discoveryTimer=null),this.entries=[],this.executing.clear(),c.info("BSH watchdog stopped"))}async discover(){try{this.entries=await d(this.fs),c.debug("BSH discovery complete",{count:this.entries.length})}catch(t){c.error("BSH discovery failed",{error:t instanceof Error?t.message:String(t)})}}getEntries(){return this.entries}onFrameNavigated=t=>{const e=t.frame;if(e?.parentId||!e?.url)return;const r=e.url,n=t.sessionId;if(!r.startsWith("http://")&&!r.startsWith("https://"))return;if(!n){c.warn("BSH watchdog: no sessionId in Page.frameNavigated params, skipping",{url:r});return}if(this.entries.length===0)return;const o=x(this.entries,r);if(o.length!==0)for(const i of o){const h=`${i.path}::${r}`;this.executing.has(h)||(this.executing.add(h),c.info("BSH watchdog executing script",{script:i.path,url:r}),this.executeInTargetPage(i.path,r,n).then(()=>{c.info("BSH script completed",{script:i.path,url:r})}).catch(a=>{c.error("BSH script execution error",{script:i.path,url:r,error:a instanceof Error?a.message:String(a)})}).finally(()=>{this.executing.delete(h)}))}};async executeInTargetPage(t,e,r){const n=await this.fs.readFile(t),i=`(async () => { try {
3
3
  ${typeof n=="string"?n:new TextDecoder().decode(n)}
4
4
  } catch(e) { console.error('[bsh]', e); } })()`;await this.transport.send("Runtime.enable",{},r);const a=(await this.transport.send("Runtime.evaluate",{expression:i,awaitPromise:!0,returnByValue:!0},r)).exceptionDetails;if(a){const f=a.exception?.description??a.text;c.warn("BSH script evaluation error",{script:t,url:e,error:f})}}}export{P as BshWatchdog};
@@ -1 +1 @@
1
- import{i as T,r as x,m as S,G as v,c as M,a as R,b as _}from"./google-shared-BSXV7Vjo.js";import{A as G,g as b,a as L,b as O,d as A}from"./index-BbXBcqok.js";import{s as E}from"./sanitize-unicode-cmozpu7l.js";let P=0;const f=(e,o,n)=>{const i=new G;return(async()=>{const t={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const r=n?.apiKey||b(e.provider)||"",l=N(e,r,n?.headers);let c=W(e,o,n);const m=await n?.onPayload?.(c,e);m!==void 0&&(c=m);const w=await l.models.generateContentStream(c);i.push({type:"start",partial:t});let a=null;const y=t.content,u=()=>y.length-1;for await(const g of w){t.responseId||=g.responseId;const h=g.candidates?.[0];if(h?.content?.parts)for(const s of h.content.parts){if(s.text!==void 0){const d=T(s);(!a||d&&a.type!=="thinking"||!d&&a.type!=="text")&&(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:y.length-1,content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t})),d?(a={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(a),i.push({type:"thinking_start",contentIndex:u(),partial:t})):(a={type:"text",text:""},t.content.push(a),i.push({type:"text_start",contentIndex:u(),partial:t}))),a.type==="thinking"?(a.thinking+=s.text,a.thinkingSignature=x(a.thinkingSignature,s.thoughtSignature),i.push({type:"thinking_delta",contentIndex:u(),delta:s.text,partial:t})):(a.text+=s.text,a.textSignature=x(a.textSignature,s.thoughtSignature),i.push({type:"text_delta",contentIndex:u(),delta:s.text,partial:t}))}if(s.functionCall){a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t}),a=null);const d=s.functionCall.id,p={type:"toolCall",id:!d||t.content.some(C=>C.type==="toolCall"&&C.id===d)?`${s.functionCall.name}_${Date.now()}_${++P}`:d,name:s.functionCall.name||"",arguments:s.functionCall.args??{},...s.thoughtSignature&&{thoughtSignature:s.thoughtSignature}};t.content.push(p),i.push({type:"toolcall_start",contentIndex:u(),partial:t}),i.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(p.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:u(),toolCall:p,partial:t})}}h?.finishReason&&(t.stopReason=S(h.finishReason),t.content.some(s=>s.type==="toolCall")&&(t.stopReason="toolUse")),g.usageMetadata&&(t.usage={input:g.usageMetadata.promptTokenCount||0,output:(g.usageMetadata.candidatesTokenCount||0)+(g.usageMetadata.thoughtsTokenCount||0),cacheRead:g.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:g.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},L(e,t.usage))}if(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw new Error("An unknown error occurred");i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(r){for(const l of t.content)"index"in l&&delete l.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=r instanceof Error?r.message:JSON.stringify(r),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},J=(e,o,n)=>{const i=n?.apiKey||b(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const t=O(e,n,i);if(!n?.reasoning)return f(e,o,{...t,thinking:{enabled:!1}});const r=A(n.reasoning),l=e;return k(l)||I(l)?f(e,o,{...t,thinking:{enabled:!0,level:K(r,l)}}):f(e,o,{...t,thinking:{enabled:!0,budgetTokens:U(l,r,n.thinkingBudgets)}})};function N(e,o,n){const i={};return e.baseUrl&&(i.baseUrl=e.baseUrl,i.apiVersion=""),(e.headers||n)&&(i.headers={...e.headers,...n}),new v({apiKey:o,httpOptions:Object.keys(i).length>0?i:void 0})}function W(e,o,n={}){const i=M(e,o),t={};n.temperature!==void 0&&(t.temperature=n.temperature),n.maxTokens!==void 0&&(t.maxOutputTokens=n.maxTokens);const r={...Object.keys(t).length>0&&t,...o.systemPrompt&&{systemInstruction:E(o.systemPrompt)},...o.tools&&o.tools.length>0&&{tools:R(o.tools)}};if(o.tools&&o.tools.length>0&&n.toolChoice?r.toolConfig={functionCallingConfig:{mode:_(n.toolChoice)}}:r.toolConfig=void 0,n.thinking?.enabled&&e.reasoning){const c={includeThoughts:!0};n.thinking.level!==void 0?c.thinkingLevel=n.thinking.level:n.thinking.budgetTokens!==void 0&&(c.thinkingBudget=n.thinking.budgetTokens),r.thinkingConfig=c}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(r.thinkingConfig=B(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");r.abortSignal=n.signal}return{model:e.id,contents:i,config:r}}function k(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function I(e){return/gemini-3(?:\.\d+)?-flash/.test(e.id.toLowerCase())}function B(e){return k(e)?{thinkingLevel:"LOW"}:I(e)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function K(e,o){if(k(o))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function U(e,o,n){return n?.[o]!==void 0?n[o]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}export{f as streamGoogle,J as streamSimpleGoogle};
1
+ import{i as T,r as x,m as S,G as v,c as M,a as R,b as _}from"./google-shared-52YT-STV.js";import{A as G,g as b,a as L,b as O,d as A}from"./index-COxfqL_6.js";import{s as E}from"./sanitize-unicode-cmozpu7l.js";let P=0;const f=(e,o,n)=>{const i=new G;return(async()=>{const t={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const r=n?.apiKey||b(e.provider)||"",l=N(e,r,n?.headers);let c=W(e,o,n);const m=await n?.onPayload?.(c,e);m!==void 0&&(c=m);const w=await l.models.generateContentStream(c);i.push({type:"start",partial:t});let a=null;const y=t.content,u=()=>y.length-1;for await(const g of w){t.responseId||=g.responseId;const h=g.candidates?.[0];if(h?.content?.parts)for(const s of h.content.parts){if(s.text!==void 0){const d=T(s);(!a||d&&a.type!=="thinking"||!d&&a.type!=="text")&&(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:y.length-1,content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t})),d?(a={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(a),i.push({type:"thinking_start",contentIndex:u(),partial:t})):(a={type:"text",text:""},t.content.push(a),i.push({type:"text_start",contentIndex:u(),partial:t}))),a.type==="thinking"?(a.thinking+=s.text,a.thinkingSignature=x(a.thinkingSignature,s.thoughtSignature),i.push({type:"thinking_delta",contentIndex:u(),delta:s.text,partial:t})):(a.text+=s.text,a.textSignature=x(a.textSignature,s.thoughtSignature),i.push({type:"text_delta",contentIndex:u(),delta:s.text,partial:t}))}if(s.functionCall){a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t}),a=null);const d=s.functionCall.id,p={type:"toolCall",id:!d||t.content.some(C=>C.type==="toolCall"&&C.id===d)?`${s.functionCall.name}_${Date.now()}_${++P}`:d,name:s.functionCall.name||"",arguments:s.functionCall.args??{},...s.thoughtSignature&&{thoughtSignature:s.thoughtSignature}};t.content.push(p),i.push({type:"toolcall_start",contentIndex:u(),partial:t}),i.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(p.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:u(),toolCall:p,partial:t})}}h?.finishReason&&(t.stopReason=S(h.finishReason),t.content.some(s=>s.type==="toolCall")&&(t.stopReason="toolUse")),g.usageMetadata&&(t.usage={input:g.usageMetadata.promptTokenCount||0,output:(g.usageMetadata.candidatesTokenCount||0)+(g.usageMetadata.thoughtsTokenCount||0),cacheRead:g.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:g.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},L(e,t.usage))}if(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw new Error("An unknown error occurred");i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(r){for(const l of t.content)"index"in l&&delete l.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=r instanceof Error?r.message:JSON.stringify(r),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},J=(e,o,n)=>{const i=n?.apiKey||b(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const t=O(e,n,i);if(!n?.reasoning)return f(e,o,{...t,thinking:{enabled:!1}});const r=A(n.reasoning),l=e;return k(l)||I(l)?f(e,o,{...t,thinking:{enabled:!0,level:K(r,l)}}):f(e,o,{...t,thinking:{enabled:!0,budgetTokens:U(l,r,n.thinkingBudgets)}})};function N(e,o,n){const i={};return e.baseUrl&&(i.baseUrl=e.baseUrl,i.apiVersion=""),(e.headers||n)&&(i.headers={...e.headers,...n}),new v({apiKey:o,httpOptions:Object.keys(i).length>0?i:void 0})}function W(e,o,n={}){const i=M(e,o),t={};n.temperature!==void 0&&(t.temperature=n.temperature),n.maxTokens!==void 0&&(t.maxOutputTokens=n.maxTokens);const r={...Object.keys(t).length>0&&t,...o.systemPrompt&&{systemInstruction:E(o.systemPrompt)},...o.tools&&o.tools.length>0&&{tools:R(o.tools)}};if(o.tools&&o.tools.length>0&&n.toolChoice?r.toolConfig={functionCallingConfig:{mode:_(n.toolChoice)}}:r.toolConfig=void 0,n.thinking?.enabled&&e.reasoning){const c={includeThoughts:!0};n.thinking.level!==void 0?c.thinkingLevel=n.thinking.level:n.thinking.budgetTokens!==void 0&&(c.thinkingBudget=n.thinking.budgetTokens),r.thinkingConfig=c}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(r.thinkingConfig=B(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");r.abortSignal=n.signal}return{model:e.id,contents:i,config:r}}function k(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function I(e){return/gemini-3(?:\.\d+)?-flash/.test(e.id.toLowerCase())}function B(e){return k(e)?{thinkingLevel:"LOW"}:I(e)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function K(e,o){if(k(o))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function U(e,o,n){return n?.[o]!==void 0?n[o]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}export{f as streamGoogle,J as streamSimpleGoogle};
@@ -1,2 +1,2 @@
1
- import{A as oe,a as ae,b as se,d as ie}from"./index-BbXBcqok.js";import{s as ce}from"./sanitize-unicode-cmozpu7l.js";import{c as le,a as ue,b as de,i as ge,r as V,d as he}from"./google-shared-BSXV7Vjo.js";var fe={};const Q="https://cloudcode-pa.googleapis.com",pe="https://daily-cloudcode-pa.sandbox.googleapis.com",me="https://autopush-cloudcode-pa.sandbox.googleapis.com",ye=[pe,me,Q],we={"User-Agent":"google-cloud-sdk vscode_cloudshelleditor/0.1","X-Goog-Api-Client":"gl-node/22.17.0","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},ke="1.18.4";function Ie(){return{"User-Agent":`antigravity/${fe.PI_AI_ANTIGRAVITY_VERSION||ke} darwin/arm64`}}const j="You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.**Absolute paths only****Proactiveness**";let be=0;const L=3,K=1e3,z=2,Te=500,Ee="interleaved-thinking-2025-05-14";function Ae(t,s){const o=a=>a>0?Math.ceil(a+1e3):void 0,n=s instanceof Headers?s:s?.headers;if(n){const a=n.get("retry-after");if(a){const d=Number(a);if(Number.isFinite(d)){const b=o(d*1e3);if(b!==void 0)return b}const A=new Date(a).getTime();if(!Number.isNaN(A)){const b=o(A-Date.now());if(b!==void 0)return b}}const u=n.get("x-ratelimit-reset");if(u){const d=Number.parseInt(u,10);if(!Number.isNaN(d)){const p=o(d*1e3-Date.now());if(p!==void 0)return p}}const c=n.get("x-ratelimit-reset-after");if(c){const d=Number(c);if(Number.isFinite(d)){const p=o(d*1e3);if(p!==void 0)return p}}}const e=t.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);if(e){const a=e[1]?parseInt(e[1],10):0,u=e[2]?parseInt(e[2],10):0,c=parseFloat(e[3]);if(!Number.isNaN(c)){const d=((a*60+u)*60+c)*1e3,p=o(d);if(p!==void 0)return p}}const h=t.match(/Please retry in ([0-9.]+)(ms|s)/i);if(h?.[1]){const a=parseFloat(h[1]);if(!Number.isNaN(a)&&a>0){const u=h[2].toLowerCase()==="ms"?a:a*1e3,c=o(u);if(c!==void 0)return c}}const i=t.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i);if(i?.[1]){const a=parseFloat(i[1]);if(!Number.isNaN(a)&&a>0){const u=i[2].toLowerCase()==="ms"?a:a*1e3,c=o(u);if(c!==void 0)return c}}}function Ce(t){return t.provider==="google-antigravity"&&t.id.startsWith("claude-")&&t.reasoning}function G(t){return/gemini-3(?:\.1)?-pro/.test(t.toLowerCase())}function Z(t){return/gemini-3(?:\.1)?-flash/.test(t.toLowerCase())}function ve(t){return G(t)||Z(t)}function xe(t,s){return t===429||t===500||t===502||t===503||t===504?!0:/resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(s)}function X(t){try{const s=JSON.parse(t);if(s.error?.message)return s.error.message}catch{}return t}function O(t,s){return new Promise((o,n)=>{if(s?.aborted){n(new Error("Request was aborted"));return}const e=setTimeout(o,t);s?.addEventListener("abort",()=>{clearTimeout(e),n(new Error("Request was aborted"))})})}const P=(t,s,o)=>{const n=new oe;return(async()=>{const e={role:"assistant",content:[],api:"google-gemini-cli",provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const h=o?.apiKey;if(!h)throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");let i,a;try{const g=JSON.parse(h);i=g.token,a=g.projectId}catch{throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.")}if(!i||!a)throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.");const u=t.provider==="google-antigravity",c=t.baseUrl?.trim(),d=c?[c]:u?ye:[Q];let p=Re(t,s,a,o,u);const A=await o?.onPayload?.(p,t);A!==void 0&&(p=A);const b=u?Ie():we,q={Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"text/event-stream",...b,...Ce(t)?{"anthropic-beta":Ee}:{},...o?.headers},U=JSON.stringify(p);let y,T,x,C=0;for(let g=0;g<=L;g++){if(o?.signal?.aborted)throw new Error("Request was aborted");try{if(x=`${d[C]}/v1internal:streamGenerateContent?alt=sse`,y=await fetch(x,{method:"POST",headers:q,body:U,signal:o?.signal}),y.ok)break;const r=await y.text();if((y.status===403||y.status===404)&&C<d.length-1){C++;continue}if(g<L&&xe(y.status,r)){C<d.length-1&&C++;const k=Ae(r,y),f=k??K*2**g,E=o?.maxRetryDelayMs??6e4;if(E>0&&k&&k>E){const M=Math.ceil(k/1e3);throw new Error(`Server requested ${M}s retry delay (max: ${Math.ceil(E/1e3)}s). ${X(r)}`)}await O(f,o?.signal);continue}throw new Error(`Cloud Code Assist API error (${y.status}): ${X(r)}`)}catch(m){if(m instanceof Error&&(m.name==="AbortError"||m.message==="Request was aborted"))throw new Error("Request was aborted");if(T=m instanceof Error?m:new Error(String(m)),T.message==="fetch failed"&&T.cause instanceof Error&&(T=new Error(`Network error: ${T.cause.message}`)),g<L){const r=K*2**g;await O(r,o?.signal);continue}throw T}}if(!y||!y.ok)throw T??new Error("Failed to get response after retries");let N=!1;const S=()=>{N||(n.push({type:"start",partial:e}),N=!0)},ee=()=>{e.content=[],e.usage={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},e.stopReason="stop",e.errorMessage=void 0,e.timestamp=Date.now(),N=!1},te=async g=>{if(!g.body)throw new Error("No response body");let m=!1,r=null;const k=e.content,f=()=>k.length-1,E=g.body.getReader(),M=new TextDecoder;let _="";const B=()=>{E.cancel().catch(()=>{})};o?.signal?.addEventListener("abort",B);try{for(;;){if(o?.signal?.aborted)throw new Error("Request was aborted");const{done:ne,value:re}=await E.read();if(ne)break;_+=M.decode(re,{stream:!0});const Y=_.split(`
1
+ import{A as oe,a as ae,b as se,d as ie}from"./index-COxfqL_6.js";import{s as ce}from"./sanitize-unicode-cmozpu7l.js";import{c as le,a as ue,b as de,i as ge,r as V,d as he}from"./google-shared-52YT-STV.js";var fe={};const Q="https://cloudcode-pa.googleapis.com",pe="https://daily-cloudcode-pa.sandbox.googleapis.com",me="https://autopush-cloudcode-pa.sandbox.googleapis.com",ye=[pe,me,Q],we={"User-Agent":"google-cloud-sdk vscode_cloudshelleditor/0.1","X-Goog-Api-Client":"gl-node/22.17.0","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},ke="1.18.4";function Ie(){return{"User-Agent":`antigravity/${fe.PI_AI_ANTIGRAVITY_VERSION||ke} darwin/arm64`}}const j="You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.**Absolute paths only****Proactiveness**";let be=0;const L=3,K=1e3,z=2,Te=500,Ee="interleaved-thinking-2025-05-14";function Ae(t,s){const o=a=>a>0?Math.ceil(a+1e3):void 0,n=s instanceof Headers?s:s?.headers;if(n){const a=n.get("retry-after");if(a){const d=Number(a);if(Number.isFinite(d)){const b=o(d*1e3);if(b!==void 0)return b}const A=new Date(a).getTime();if(!Number.isNaN(A)){const b=o(A-Date.now());if(b!==void 0)return b}}const u=n.get("x-ratelimit-reset");if(u){const d=Number.parseInt(u,10);if(!Number.isNaN(d)){const p=o(d*1e3-Date.now());if(p!==void 0)return p}}const c=n.get("x-ratelimit-reset-after");if(c){const d=Number(c);if(Number.isFinite(d)){const p=o(d*1e3);if(p!==void 0)return p}}}const e=t.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);if(e){const a=e[1]?parseInt(e[1],10):0,u=e[2]?parseInt(e[2],10):0,c=parseFloat(e[3]);if(!Number.isNaN(c)){const d=((a*60+u)*60+c)*1e3,p=o(d);if(p!==void 0)return p}}const h=t.match(/Please retry in ([0-9.]+)(ms|s)/i);if(h?.[1]){const a=parseFloat(h[1]);if(!Number.isNaN(a)&&a>0){const u=h[2].toLowerCase()==="ms"?a:a*1e3,c=o(u);if(c!==void 0)return c}}const i=t.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i);if(i?.[1]){const a=parseFloat(i[1]);if(!Number.isNaN(a)&&a>0){const u=i[2].toLowerCase()==="ms"?a:a*1e3,c=o(u);if(c!==void 0)return c}}}function Ce(t){return t.provider==="google-antigravity"&&t.id.startsWith("claude-")&&t.reasoning}function G(t){return/gemini-3(?:\.1)?-pro/.test(t.toLowerCase())}function Z(t){return/gemini-3(?:\.1)?-flash/.test(t.toLowerCase())}function ve(t){return G(t)||Z(t)}function xe(t,s){return t===429||t===500||t===502||t===503||t===504?!0:/resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(s)}function X(t){try{const s=JSON.parse(t);if(s.error?.message)return s.error.message}catch{}return t}function O(t,s){return new Promise((o,n)=>{if(s?.aborted){n(new Error("Request was aborted"));return}const e=setTimeout(o,t);s?.addEventListener("abort",()=>{clearTimeout(e),n(new Error("Request was aborted"))})})}const P=(t,s,o)=>{const n=new oe;return(async()=>{const e={role:"assistant",content:[],api:"google-gemini-cli",provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const h=o?.apiKey;if(!h)throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");let i,a;try{const g=JSON.parse(h);i=g.token,a=g.projectId}catch{throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.")}if(!i||!a)throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.");const u=t.provider==="google-antigravity",c=t.baseUrl?.trim(),d=c?[c]:u?ye:[Q];let p=Re(t,s,a,o,u);const A=await o?.onPayload?.(p,t);A!==void 0&&(p=A);const b=u?Ie():we,q={Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"text/event-stream",...b,...Ce(t)?{"anthropic-beta":Ee}:{},...o?.headers},U=JSON.stringify(p);let y,T,x,C=0;for(let g=0;g<=L;g++){if(o?.signal?.aborted)throw new Error("Request was aborted");try{if(x=`${d[C]}/v1internal:streamGenerateContent?alt=sse`,y=await fetch(x,{method:"POST",headers:q,body:U,signal:o?.signal}),y.ok)break;const r=await y.text();if((y.status===403||y.status===404)&&C<d.length-1){C++;continue}if(g<L&&xe(y.status,r)){C<d.length-1&&C++;const k=Ae(r,y),f=k??K*2**g,E=o?.maxRetryDelayMs??6e4;if(E>0&&k&&k>E){const M=Math.ceil(k/1e3);throw new Error(`Server requested ${M}s retry delay (max: ${Math.ceil(E/1e3)}s). ${X(r)}`)}await O(f,o?.signal);continue}throw new Error(`Cloud Code Assist API error (${y.status}): ${X(r)}`)}catch(m){if(m instanceof Error&&(m.name==="AbortError"||m.message==="Request was aborted"))throw new Error("Request was aborted");if(T=m instanceof Error?m:new Error(String(m)),T.message==="fetch failed"&&T.cause instanceof Error&&(T=new Error(`Network error: ${T.cause.message}`)),g<L){const r=K*2**g;await O(r,o?.signal);continue}throw T}}if(!y||!y.ok)throw T??new Error("Failed to get response after retries");let N=!1;const S=()=>{N||(n.push({type:"start",partial:e}),N=!0)},ee=()=>{e.content=[],e.usage={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},e.stopReason="stop",e.errorMessage=void 0,e.timestamp=Date.now(),N=!1},te=async g=>{if(!g.body)throw new Error("No response body");let m=!1,r=null;const k=e.content,f=()=>k.length-1,E=g.body.getReader(),M=new TextDecoder;let _="";const B=()=>{E.cancel().catch(()=>{})};o?.signal?.addEventListener("abort",B);try{for(;;){if(o?.signal?.aborted)throw new Error("Request was aborted");const{done:ne,value:re}=await E.read();if(ne)break;_+=M.decode(re,{stream:!0});const Y=_.split(`
2
2
  `);_=Y.pop()||"";for(const F of Y){if(!F.startsWith("data:"))continue;const H=F.slice(5).trim();if(!H)continue;let W;try{W=JSON.parse(H)}catch{continue}const I=W.response;if(!I)continue;e.responseId||=I.responseId;const R=I.candidates?.[0];if(R?.content?.parts)for(const l of R.content.parts){if(l.text!==void 0){m=!0;const w=ge(l);(!r||w&&r.type!=="thinking"||!w&&r.type!=="text")&&(r&&(r.type==="text"?n.push({type:"text_end",contentIndex:k.length-1,content:r.text,partial:e}):n.push({type:"thinking_end",contentIndex:f(),content:r.thinking,partial:e})),w?(r={type:"thinking",thinking:"",thinkingSignature:void 0},e.content.push(r),S(),n.push({type:"thinking_start",contentIndex:f(),partial:e})):(r={type:"text",text:""},e.content.push(r),S(),n.push({type:"text_start",contentIndex:f(),partial:e}))),r.type==="thinking"?(r.thinking+=l.text,r.thinkingSignature=V(r.thinkingSignature,l.thoughtSignature),n.push({type:"thinking_delta",contentIndex:f(),delta:l.text,partial:e})):(r.text+=l.text,r.textSignature=V(r.textSignature,l.thoughtSignature),n.push({type:"text_delta",contentIndex:f(),delta:l.text,partial:e}))}if(l.functionCall){m=!0,r&&(r.type==="text"?n.push({type:"text_end",contentIndex:f(),content:r.text,partial:e}):n.push({type:"thinking_end",contentIndex:f(),content:r.thinking,partial:e}),r=null);const w=l.functionCall.id,D={type:"toolCall",id:!w||e.content.some(J=>J.type==="toolCall"&&J.id===w)?`${l.functionCall.name}_${Date.now()}_${++be}`:w,name:l.functionCall.name||"",arguments:l.functionCall.args??{},...l.thoughtSignature&&{thoughtSignature:l.thoughtSignature}};e.content.push(D),S(),n.push({type:"toolcall_start",contentIndex:f(),partial:e}),n.push({type:"toolcall_delta",contentIndex:f(),delta:JSON.stringify(D.arguments),partial:e}),n.push({type:"toolcall_end",contentIndex:f(),toolCall:D,partial:e})}}if(R?.finishReason&&(e.stopReason=he(R.finishReason),e.content.some(l=>l.type==="toolCall")&&(e.stopReason="toolUse")),I.usageMetadata){const l=I.usageMetadata.promptTokenCount||0,w=I.usageMetadata.cachedContentTokenCount||0;e.usage={input:l-w,output:(I.usageMetadata.candidatesTokenCount||0)+(I.usageMetadata.thoughtsTokenCount||0),cacheRead:w,cacheWrite:0,totalTokens:I.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},ae(t,e.usage)}}}}finally{o?.signal?.removeEventListener("abort",B)}return r&&(r.type==="text"?n.push({type:"text_end",contentIndex:f(),content:r.text,partial:e}):n.push({type:"thinking_end",contentIndex:f(),content:r.thinking,partial:e})),m};let $=!1,v=y;for(let g=0;g<=z;g++){if(o?.signal?.aborted)throw new Error("Request was aborted");if(g>0){const r=Te*2**(g-1);if(await O(r,o?.signal),!x)throw new Error("Missing request URL");if(v=await fetch(x,{method:"POST",headers:q,body:U,signal:o?.signal}),!v.ok){const k=await v.text();throw new Error(`Cloud Code Assist API error (${v.status}): ${k}`)}}if(await te(v)){$=!0;break}g<z&&ee()}if(!$)throw new Error("Cloud Code Assist API returned an empty response");if(o?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="aborted"||e.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:e.stopReason,message:e}),n.end()}catch(h){for(const i of e.content)"index"in i&&delete i.index;e.stopReason=o?.signal?.aborted?"aborted":"error",e.errorMessage=h instanceof Error?h.message:JSON.stringify(h),n.push({type:"error",reason:e.stopReason,error:e}),n.end()}})(),n},Pe=(t,s,o)=>{const n=o?.apiKey;if(!n)throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");const e=se(t,o,n);if(!o?.reasoning)return P(t,s,{...e,thinking:{enabled:!1}});const h=ie(o.reasoning);if(ve(t.id))return P(t,s,{...e,thinking:{enabled:!0,level:Se(h,t.id)}});const a={...{minimal:1024,low:2048,medium:8192,high:16384},...o.thinkingBudgets},u=1024;let c=a[h];const d=Math.min((e.maxTokens||0)+c,t.maxTokens);return d<=c&&(c=Math.max(0,d-u)),P(t,s,{...e,maxTokens:d,thinking:{enabled:!0,budgetTokens:c}})};function Re(t,s,o,n={},e=!1){const h=le(t,s),i={};n.temperature!==void 0&&(i.temperature=n.temperature),n.maxTokens!==void 0&&(i.maxOutputTokens=n.maxTokens),n.thinking?.enabled&&t.reasoning?(i.thinkingConfig={includeThoughts:!0},n.thinking.level!==void 0?i.thinkingConfig.thinkingLevel=n.thinking.level:n.thinking.budgetTokens!==void 0&&(i.thinkingConfig.thinkingBudget=n.thinking.budgetTokens)):t.reasoning&&n.thinking&&!n.thinking.enabled&&(i.thinkingConfig=Ne(t.id));const a={contents:h};if(a.sessionId=n.sessionId,s.systemPrompt&&(a.systemInstruction={parts:[{text:ce(s.systemPrompt)}]}),Object.keys(i).length>0&&(a.generationConfig=i),s.tools&&s.tools.length>0){const u=t.id.startsWith("claude-");a.tools=ue(s.tools,u),n.toolChoice&&(a.toolConfig={functionCallingConfig:{mode:de(n.toolChoice)}})}if(e){const u=a.systemInstruction?.parts??[];a.systemInstruction={role:"user",parts:[{text:j},{text:`Please ignore following [ignore]${j}[/ignore]`},...u]}}return{project:o,model:t.id,request:a,...e?{requestType:"agent"}:{},userAgent:e?"antigravity":"pi-coding-agent",requestId:`${e?"agent":"pi"}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}function Ne(t){return G(t)?{thinkingLevel:"LOW"}:Z(t)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function Se(t,s){if(G(s))switch(t){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(t){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}export{Re as buildRequest,Ae as extractRetryDelay,P as streamGoogleGeminiCli,Pe as streamSimpleGoogleGeminiCli};
@@ -1,4 +1,4 @@
1
- import{G as Ko,t as zo}from"./index-BbXBcqok.js";import{s as te}from"./sanitize-unicode-cmozpu7l.js";var de={exports:{}},Ge={},Ve,vt;function Xo(){if(vt)return Ve;vt=1;function t(e,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Ve=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var n=new Date().getTime();if(e&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},o),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,n){this._fn=e,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},n=null,o=0,i=0;i<this._errors.length;i++){var l=this._errors[i],a=l.message,u=(e[a]||0)+1;e[a]=u,u>=o&&(n=l,o=u)}return n},Ve}var Tt;function Qo(){return Tt||(Tt=1,(function(t){var e=Xo();t.operation=function(n){var o=t.timeouts(n);return new e(o,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var o={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in n)o[i]=n[i];if(o.minTimeout>o.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var l=[],a=0;a<o.retries;a++)l.push(this.createTimeout(a,o));return n&&n.forever&&!l.length&&l.push(this.createTimeout(a,o)),l.sort(function(u,d){return u-d}),l},t.createTimeout=function(n,o){var i=o.randomize?Math.random()+1:1,l=Math.round(i*Math.max(o.minTimeout,1)*Math.pow(o.factor,n));return l=Math.min(l,o.maxTimeout),l},t.wrap=function(n,o,i){if(o instanceof Array&&(i=o,o=null),!i){i=[];for(var l in n)typeof n[l]=="function"&&i.push(l)}for(var a=0;a<i.length;a++){var u=i[a],d=n[u];n[u]=function(f){var h=t.operation(o),p=Array.prototype.slice.call(arguments,1),m=p.pop();p.push(function(g){h.retry(g)||(g&&(arguments[0]=h.mainError()),m.apply(this,arguments))}),h.attempt(function(){f.apply(n,p)})}.bind(n,d),n[u].options=o}}})(Ge)),Ge}var He,_t;function Zo(){return _t||(_t=1,He=Qo()),He}var Et;function jo(){if(Et)return de.exports;Et=1;const t=Zo(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class n extends Error{constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}}const o=(a,u,d)=>{const c=d.retries-(u-1);return a.attemptNumber=u,a.retriesLeft=c,a},i=a=>e.includes(a),l=(a,u)=>new Promise((d,c)=>{u={onFailedAttempt:()=>{},retries:10,...u};const f=t.operation(u);f.attempt(async h=>{try{d(await a(h))}catch(p){if(!(p instanceof Error)){c(new TypeError(`Non-error was thrown: "${p}". You should only throw errors.`));return}if(p instanceof n)f.stop(),c(p.originalError);else if(p instanceof TypeError&&!i(p.message))f.stop(),c(p);else{o(p,h,u);try{await u.onFailedAttempt(p)}catch(m){c(m);return}f.retry(p)||c(f.mainError())}}})});return de.exports=l,de.exports.default=l,de.exports.AbortError=n,de.exports}var eo=jo();const ei=Ko(eo);var ti={};/**
1
+ import{G as Ko,t as zo}from"./index-COxfqL_6.js";import{s as te}from"./sanitize-unicode-cmozpu7l.js";var de={exports:{}},Ge={},Ve,vt;function Xo(){if(vt)return Ve;vt=1;function t(e,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Ve=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var n=new Date().getTime();if(e&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},o),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,n){this._fn=e,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},n=null,o=0,i=0;i<this._errors.length;i++){var l=this._errors[i],a=l.message,u=(e[a]||0)+1;e[a]=u,u>=o&&(n=l,o=u)}return n},Ve}var Tt;function Qo(){return Tt||(Tt=1,(function(t){var e=Xo();t.operation=function(n){var o=t.timeouts(n);return new e(o,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var o={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in n)o[i]=n[i];if(o.minTimeout>o.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var l=[],a=0;a<o.retries;a++)l.push(this.createTimeout(a,o));return n&&n.forever&&!l.length&&l.push(this.createTimeout(a,o)),l.sort(function(u,d){return u-d}),l},t.createTimeout=function(n,o){var i=o.randomize?Math.random()+1:1,l=Math.round(i*Math.max(o.minTimeout,1)*Math.pow(o.factor,n));return l=Math.min(l,o.maxTimeout),l},t.wrap=function(n,o,i){if(o instanceof Array&&(i=o,o=null),!i){i=[];for(var l in n)typeof n[l]=="function"&&i.push(l)}for(var a=0;a<i.length;a++){var u=i[a],d=n[u];n[u]=function(f){var h=t.operation(o),p=Array.prototype.slice.call(arguments,1),m=p.pop();p.push(function(g){h.retry(g)||(g&&(arguments[0]=h.mainError()),m.apply(this,arguments))}),h.attempt(function(){f.apply(n,p)})}.bind(n,d),n[u].options=o}}})(Ge)),Ge}var He,_t;function Zo(){return _t||(_t=1,He=Qo()),He}var Et;function jo(){if(Et)return de.exports;Et=1;const t=Zo(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class n extends Error{constructor(u){super(),u instanceof Error?(this.originalError=u,{message:u}=u):(this.originalError=new Error(u),this.originalError.stack=this.stack),this.name="AbortError",this.message=u}}const o=(a,u,d)=>{const c=d.retries-(u-1);return a.attemptNumber=u,a.retriesLeft=c,a},i=a=>e.includes(a),l=(a,u)=>new Promise((d,c)=>{u={onFailedAttempt:()=>{},retries:10,...u};const f=t.operation(u);f.attempt(async h=>{try{d(await a(h))}catch(p){if(!(p instanceof Error)){c(new TypeError(`Non-error was thrown: "${p}". You should only throw errors.`));return}if(p instanceof n)f.stop(),c(p.originalError);else if(p instanceof TypeError&&!i(p.message))f.stop(),c(p);else{o(p,h,u);try{await u.onFailedAttempt(p)}catch(m){c(m);return}f.retry(p)||c(f.mainError())}}})});return de.exports=l,de.exports.default=l,de.exports.AbortError=n,de.exports}var eo=jo();const ei=Ko(eo);var ti={};/**
2
2
  * @license
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
@@ -1 +1 @@
1
- import{i as b,r as x,m as E,G as v,c as w,a as G,b as M,T as h}from"./google-shared-BSXV7Vjo.js";import{A as S,a as R,b as N,d as A}from"./index-BbXBcqok.js";import{s as P}from"./sanitize-unicode-cmozpu7l.js";var f={};const _="v1",D={THINKING_LEVEL_UNSPECIFIED:h.THINKING_LEVEL_UNSPECIFIED,MINIMAL:h.MINIMAL,LOW:h.LOW,MEDIUM:h.MEDIUM,HIGH:h.HIGH};let U=0;const m=(e,i,n)=>{const a=new S;return(async()=>{const t={role:"assistant",content:[],api:"google-vertex",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const r=V(n),d=r?K(e,r,n?.headers):H(e,j(n),B(n),n?.headers);let c=J(e,i,n);const C=await n?.onPayload?.(c,e);C!==void 0&&(c=C);const T=await d.models.generateContentStream(c);a.push({type:"start",partial:t});let o=null;const O=t.content,l=()=>O.length-1;for await(const u of T){t.responseId||=u.responseId;const p=u.candidates?.[0];if(p?.content?.parts)for(const s of p.content.parts){if(s.text!==void 0){const g=b(s);(!o||g&&o.type!=="thinking"||!g&&o.type!=="text")&&(o&&(o.type==="text"?a.push({type:"text_end",contentIndex:O.length-1,content:o.text,partial:t}):a.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t})),g?(o={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(o),a.push({type:"thinking_start",contentIndex:l(),partial:t})):(o={type:"text",text:""},t.content.push(o),a.push({type:"text_start",contentIndex:l(),partial:t}))),o.type==="thinking"?(o.thinking+=s.text,o.thinkingSignature=x(o.thinkingSignature,s.thoughtSignature),a.push({type:"thinking_delta",contentIndex:l(),delta:s.text,partial:t})):(o.text+=s.text,o.textSignature=x(o.textSignature,s.thoughtSignature),a.push({type:"text_delta",contentIndex:l(),delta:s.text,partial:t}))}if(s.functionCall){o&&(o.type==="text"?a.push({type:"text_end",contentIndex:l(),content:o.text,partial:t}):a.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t}),o=null);const g=s.functionCall.id,k={type:"toolCall",id:!g||t.content.some(y=>y.type==="toolCall"&&y.id===g)?`${s.functionCall.name}_${Date.now()}_${++U}`:g,name:s.functionCall.name||"",arguments:s.functionCall.args??{},...s.thoughtSignature&&{thoughtSignature:s.thoughtSignature}};t.content.push(k),a.push({type:"toolcall_start",contentIndex:l(),partial:t}),a.push({type:"toolcall_delta",contentIndex:l(),delta:JSON.stringify(k.arguments),partial:t}),a.push({type:"toolcall_end",contentIndex:l(),toolCall:k,partial:t})}}p?.finishReason&&(t.stopReason=E(p.finishReason),t.content.some(s=>s.type==="toolCall")&&(t.stopReason="toolUse")),u.usageMetadata&&(t.usage={input:u.usageMetadata.promptTokenCount||0,output:(u.usageMetadata.candidatesTokenCount||0)+(u.usageMetadata.thoughtsTokenCount||0),cacheRead:u.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:u.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},R(e,t.usage))}if(o&&(o.type==="text"?a.push({type:"text_end",contentIndex:l(),content:o.text,partial:t}):a.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw new Error("An unknown error occurred");a.push({type:"done",reason:t.stopReason,message:t}),a.end()}catch(r){for(const d of t.content)"index"in d&&delete d.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=r instanceof Error?r.message:JSON.stringify(r),a.push({type:"error",reason:t.stopReason,error:t}),a.end()}})(),a},tt=(e,i,n)=>{const a=N(e,n,void 0);if(!n?.reasoning)return m(e,i,{...a,thinking:{enabled:!1}});const t=A(n.reasoning),r=e;return I(r)||L(r)?m(e,i,{...a,thinking:{enabled:!0,level:$(t,r)}}):m(e,i,{...a,thinking:{enabled:!0,budgetTokens:F(r,t,n.thinkingBudgets)}})};function H(e,i,n,a){const t={};(e.headers||a)&&(t.headers={...e.headers,...a});const r=Object.values(t).some(Boolean);return new v({vertexai:!0,project:i,location:n,apiVersion:_,httpOptions:r?t:void 0})}function K(e,i,n){const a={};(e.headers||n)&&(a.headers={...e.headers,...n});const t=Object.values(a).some(Boolean);return new v({vertexai:!0,apiKey:i,apiVersion:_,httpOptions:t?a:void 0})}function V(e){const i=e?.apiKey?.trim()||f.GOOGLE_CLOUD_API_KEY?.trim();if(!(!i||W(i)))return i}function W(e){return/^<[^>]+>$/.test(e)}function j(e){const i=e?.project||f.GOOGLE_CLOUD_PROJECT||f.GCLOUD_PROJECT;if(!i)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return i}function B(e){const i=e?.location||f.GOOGLE_CLOUD_LOCATION;if(!i)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return i}function J(e,i,n={}){const a=w(e,i),t={};n.temperature!==void 0&&(t.temperature=n.temperature),n.maxTokens!==void 0&&(t.maxOutputTokens=n.maxTokens);const r={...Object.keys(t).length>0&&t,...i.systemPrompt&&{systemInstruction:P(i.systemPrompt)},...i.tools&&i.tools.length>0&&{tools:G(i.tools)}};if(i.tools&&i.tools.length>0&&n.toolChoice?r.toolConfig={functionCallingConfig:{mode:M(n.toolChoice)}}:r.toolConfig=void 0,n.thinking?.enabled&&e.reasoning){const c={includeThoughts:!0};n.thinking.level!==void 0?c.thinkingLevel=D[n.thinking.level]:n.thinking.budgetTokens!==void 0&&(c.thinkingBudget=n.thinking.budgetTokens),r.thinkingConfig=c}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(r.thinkingConfig=q(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");r.abortSignal=n.signal}return{model:e.id,contents:a,config:r}}function I(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function L(e){return/gemini-3(?:\.\d+)?-flash/.test(e.id.toLowerCase())}function q(e){const i=e;return I(i)?{thinkingLevel:h.LOW}:L(i)?{thinkingLevel:h.MINIMAL}:{thinkingBudget:0}}function $(e,i){if(I(i))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function F(e,i,n){return n?.[i]!==void 0?n[i]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[i]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[i]:-1}export{m as streamGoogleVertex,tt as streamSimpleGoogleVertex};
1
+ import{i as b,r as x,m as E,G as v,c as w,a as G,b as M,T as h}from"./google-shared-52YT-STV.js";import{A as S,a as R,b as N,d as A}from"./index-COxfqL_6.js";import{s as P}from"./sanitize-unicode-cmozpu7l.js";var f={};const _="v1",D={THINKING_LEVEL_UNSPECIFIED:h.THINKING_LEVEL_UNSPECIFIED,MINIMAL:h.MINIMAL,LOW:h.LOW,MEDIUM:h.MEDIUM,HIGH:h.HIGH};let U=0;const m=(e,i,n)=>{const a=new S;return(async()=>{const t={role:"assistant",content:[],api:"google-vertex",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const r=V(n),d=r?K(e,r,n?.headers):H(e,j(n),B(n),n?.headers);let c=J(e,i,n);const C=await n?.onPayload?.(c,e);C!==void 0&&(c=C);const T=await d.models.generateContentStream(c);a.push({type:"start",partial:t});let o=null;const O=t.content,l=()=>O.length-1;for await(const u of T){t.responseId||=u.responseId;const p=u.candidates?.[0];if(p?.content?.parts)for(const s of p.content.parts){if(s.text!==void 0){const g=b(s);(!o||g&&o.type!=="thinking"||!g&&o.type!=="text")&&(o&&(o.type==="text"?a.push({type:"text_end",contentIndex:O.length-1,content:o.text,partial:t}):a.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t})),g?(o={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(o),a.push({type:"thinking_start",contentIndex:l(),partial:t})):(o={type:"text",text:""},t.content.push(o),a.push({type:"text_start",contentIndex:l(),partial:t}))),o.type==="thinking"?(o.thinking+=s.text,o.thinkingSignature=x(o.thinkingSignature,s.thoughtSignature),a.push({type:"thinking_delta",contentIndex:l(),delta:s.text,partial:t})):(o.text+=s.text,o.textSignature=x(o.textSignature,s.thoughtSignature),a.push({type:"text_delta",contentIndex:l(),delta:s.text,partial:t}))}if(s.functionCall){o&&(o.type==="text"?a.push({type:"text_end",contentIndex:l(),content:o.text,partial:t}):a.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t}),o=null);const g=s.functionCall.id,k={type:"toolCall",id:!g||t.content.some(y=>y.type==="toolCall"&&y.id===g)?`${s.functionCall.name}_${Date.now()}_${++U}`:g,name:s.functionCall.name||"",arguments:s.functionCall.args??{},...s.thoughtSignature&&{thoughtSignature:s.thoughtSignature}};t.content.push(k),a.push({type:"toolcall_start",contentIndex:l(),partial:t}),a.push({type:"toolcall_delta",contentIndex:l(),delta:JSON.stringify(k.arguments),partial:t}),a.push({type:"toolcall_end",contentIndex:l(),toolCall:k,partial:t})}}p?.finishReason&&(t.stopReason=E(p.finishReason),t.content.some(s=>s.type==="toolCall")&&(t.stopReason="toolUse")),u.usageMetadata&&(t.usage={input:u.usageMetadata.promptTokenCount||0,output:(u.usageMetadata.candidatesTokenCount||0)+(u.usageMetadata.thoughtsTokenCount||0),cacheRead:u.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:u.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},R(e,t.usage))}if(o&&(o.type==="text"?a.push({type:"text_end",contentIndex:l(),content:o.text,partial:t}):a.push({type:"thinking_end",contentIndex:l(),content:o.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw new Error("An unknown error occurred");a.push({type:"done",reason:t.stopReason,message:t}),a.end()}catch(r){for(const d of t.content)"index"in d&&delete d.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=r instanceof Error?r.message:JSON.stringify(r),a.push({type:"error",reason:t.stopReason,error:t}),a.end()}})(),a},tt=(e,i,n)=>{const a=N(e,n,void 0);if(!n?.reasoning)return m(e,i,{...a,thinking:{enabled:!1}});const t=A(n.reasoning),r=e;return I(r)||L(r)?m(e,i,{...a,thinking:{enabled:!0,level:$(t,r)}}):m(e,i,{...a,thinking:{enabled:!0,budgetTokens:F(r,t,n.thinkingBudgets)}})};function H(e,i,n,a){const t={};(e.headers||a)&&(t.headers={...e.headers,...a});const r=Object.values(t).some(Boolean);return new v({vertexai:!0,project:i,location:n,apiVersion:_,httpOptions:r?t:void 0})}function K(e,i,n){const a={};(e.headers||n)&&(a.headers={...e.headers,...n});const t=Object.values(a).some(Boolean);return new v({vertexai:!0,apiKey:i,apiVersion:_,httpOptions:t?a:void 0})}function V(e){const i=e?.apiKey?.trim()||f.GOOGLE_CLOUD_API_KEY?.trim();if(!(!i||W(i)))return i}function W(e){return/^<[^>]+>$/.test(e)}function j(e){const i=e?.project||f.GOOGLE_CLOUD_PROJECT||f.GCLOUD_PROJECT;if(!i)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return i}function B(e){const i=e?.location||f.GOOGLE_CLOUD_LOCATION;if(!i)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return i}function J(e,i,n={}){const a=w(e,i),t={};n.temperature!==void 0&&(t.temperature=n.temperature),n.maxTokens!==void 0&&(t.maxOutputTokens=n.maxTokens);const r={...Object.keys(t).length>0&&t,...i.systemPrompt&&{systemInstruction:P(i.systemPrompt)},...i.tools&&i.tools.length>0&&{tools:G(i.tools)}};if(i.tools&&i.tools.length>0&&n.toolChoice?r.toolConfig={functionCallingConfig:{mode:M(n.toolChoice)}}:r.toolConfig=void 0,n.thinking?.enabled&&e.reasoning){const c={includeThoughts:!0};n.thinking.level!==void 0?c.thinkingLevel=D[n.thinking.level]:n.thinking.budgetTokens!==void 0&&(c.thinkingBudget=n.thinking.budgetTokens),r.thinkingConfig=c}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(r.thinkingConfig=q(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");r.abortSignal=n.signal}return{model:e.id,contents:a,config:r}}function I(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function L(e){return/gemini-3(?:\.\d+)?-flash/.test(e.id.toLowerCase())}function q(e){const i=e;return I(i)?{thinkingLevel:h.LOW}:L(i)?{thinkingLevel:h.MINIMAL}:{thinkingBudget:0}}function $(e,i){if(I(i))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function F(e,i,n){return n?.[i]!==void 0?n[i]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[i]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[i]:-1}export{m as streamGoogleVertex,tt as streamSimpleGoogleVertex};