sliccy 1.25.0 → 1.26.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 (27) hide show
  1. package/dist/node-server/index.js +5 -1
  2. package/dist/ui/assets/{___vite-browser-external_commonjs-proxy-CHwSqyaL.js → ___vite-browser-external_commonjs-proxy-7U87kfBv.js} +1 -1
  3. package/dist/ui/assets/{anthropic-D8zI8Nff.js → anthropic-CfFsAbhs.js} +1 -1
  4. package/dist/ui/assets/{azure-openai-responses-Cn4_jzZn.js → azure-openai-responses-DX9SzdYk.js} +1 -1
  5. package/dist/ui/assets/{bsh-watchdog-Xz_nMzv3.js → bsh-watchdog-DthzjzbF.js} +1 -1
  6. package/dist/ui/assets/{google--oqRhLvu.js → google-Dgcj8p2Y.js} +1 -1
  7. package/dist/ui/assets/{google-gemini-cli-B6mB4wL_.js → google-gemini-cli-3EajcUec.js} +1 -1
  8. package/dist/ui/assets/{google-shared-r_CAb7zy.js → google-shared-D1yWx-8k.js} +1 -1
  9. package/dist/ui/assets/{google-vertex-CKlcmQCp.js → google-vertex-CWmtNuIQ.js} +1 -1
  10. package/dist/ui/assets/{index-BFFYFi3J.js → index-CgFkFStV.js} +1 -1
  11. package/dist/ui/assets/{index-CIrAhfog.js → index-DIookCYH.js} +1 -1
  12. package/dist/ui/assets/{index-W9ryXG_v.js → index-DJPmZw4a.js} +10 -10
  13. package/dist/ui/assets/{index-DM18cGzV.js → index-d-ZPN7pB.js} +1 -1
  14. package/dist/ui/assets/{index-CeFIcjS_.js → index-nEt-VnbM.js} +1 -1
  15. package/dist/ui/assets/{json-parse-DYeOImVX.js → json-parse-CRcpIgF_.js} +1 -1
  16. package/dist/ui/assets/{mistral-Bs98_Nne.js → mistral-B5PVshqk.js} +1 -1
  17. package/dist/ui/assets/{offscreen-client-Dn63QmN9.js → offscreen-client-Dj7EBRST.js} +1 -1
  18. package/dist/ui/assets/{openai-codex-responses-2iZbtSiB.js → openai-codex-responses-q2oyEW2I.js} +1 -1
  19. package/dist/ui/assets/{openai-completions-CbVbaGxp.js → openai-completions-DwmKL5b1.js} +1 -1
  20. package/dist/ui/assets/{openai-responses-3q4QP6Y1.js → openai-responses-I0hZgQNc.js} +1 -1
  21. package/dist/ui/assets/{openai-responses-shared-Ce1dVnHc.js → openai-responses-shared-DipKQ09W.js} +1 -1
  22. package/dist/ui/assets/pyodide-4ipJLcSu.js +3 -0
  23. package/dist/ui/assets/{sql-wasm-HmbifZVM.js → sql-wasm-xEgzZ1j4.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 +3 -3
  27. package/dist/ui/assets/pyodide-CZ-fFl8u.js +0 -3
@@ -624,7 +624,11 @@ async function main() {
624
624
  app.use(express.json({ limit: '50mb' }));
625
625
  app.get('/api/runtime-config', (_req, res) => {
626
626
  res.json({
627
- trayWorkerBaseUrl: RUNTIME_FLAGS.leadWorkerBaseUrl ?? process.env['WORKER_BASE_URL'] ?? null,
627
+ trayWorkerBaseUrl: RUNTIME_FLAGS.leadWorkerBaseUrl ??
628
+ (process.env['WORKER_BASE_URL']?.trim() || null) ??
629
+ (DEV_MODE
630
+ ? 'https://slicc-tray-hub-staging.minivelos.workers.dev'
631
+ : 'https://www.sliccy.ai'),
628
632
  trayJoinUrl: discoveredTrayJoinUrl ?? null,
629
633
  });
630
634
  });
@@ -1 +1 @@
1
- import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{f as r}from"./index-W9ryXG_v.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-DJPmZw4a.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-W9ryXG_v.js";import{p as Rt}from"./json-parse-DYeOImVX.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-DJPmZw4a.js";import{p as Rt}from"./json-parse-CRcpIgF_.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-W9ryXG_v.js";import{p as O,c as N,a as g}from"./openai-responses-shared-Ce1dVnHc.js";import"./hash-DMDecQcg.js";import"./json-parse-DYeOImVX.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-DJPmZw4a.js";import{p as O,c as N,a as g}from"./openai-responses-shared-DipKQ09W.js";import"./hash-DMDecQcg.js";import"./json-parse-CRcpIgF_.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,2 +1,2 @@
1
- import{c as u}from"./index-W9ryXG_v.js";const l=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of l)await s.exists(r)&&await p(s,r,t,e);return t}async function p(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const i=g(n);if(!i)continue;const a=await s.readFile(n,{encoding:"utf-8"}),c=typeof a=="string"?a:new TextDecoder().decode(a),f=m(c);e.push({path:n,hostnamePattern:i,matchPatterns:f})}}function g(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 m(s){const t=s.split(`
1
+ import{c as u}from"./index-DJPmZw4a.js";const l=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of l)await s.exists(r)&&await p(s,r,t,e);return t}async function p(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const i=g(n);if(!i)continue;const a=await s.readFile(n,{encoding:"utf-8"}),c=typeof a=="string"?a:new TextDecoder().decode(a),f=m(c);e.push({path:n,hostnamePattern:i,matchPatterns:f})}}function g(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 m(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 h(s,t){if(t.startsWith("*.")){const e=t.slice(1);return s.endsWith(e)&&s.length>e.length}return s===t}function v(s,t){try{const e=new URL(s),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;const[,n,i,a]=r;return n!=="*"&&e.protocol.slice(0,-1)!==n||!h(e.hostname,i)?!1:a?x(e.pathname+e.search,a):!0}catch{return!1}}function x(s,t){const e="^"+t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$";return new RegExp(e).test(s)}function w(s,t){try{const e=new URL(t);return s.filter(r=>h(e.hostname,r.hostnamePattern)?r.matchPatterns.length>0?r.matchPatterns.some(n=>v(t,n)):!0:!1)}catch{return[]}}const o=u("bsh-watchdog");class S{transport;fs;execute;discoveryIntervalMs;entries=[];discoveryTimer=null;running=!1;executing=new Set;constructor(t){this.transport=t.transport,this.fs=t.fs,this.execute=t.execute,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),o.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(),o.info("BSH watchdog stopped"))}async discover(){try{this.entries=await d(this.fs),o.debug("BSH discovery complete",{count:this.entries.length})}catch(t){o.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;if(!r.startsWith("http://")&&!r.startsWith("https://")||this.entries.length===0)return;const n=w(this.entries,r);if(n.length!==0)for(const i of n){const a=`${i.path}::${r}`;this.executing.has(a)||(this.executing.add(a),o.info("BSH watchdog executing script",{script:i.path,url:r}),this.execute(i.path).then(c=>{c.exitCode!==0?o.warn("BSH script failed",{script:i.path,url:r,exitCode:c.exitCode,stderr:c.stderr.slice(0,200)}):o.info("BSH script completed",{script:i.path,url:r})}).catch(c=>{o.error("BSH script execution error",{script:i.path,url:r,error:c instanceof Error?c.message:String(c)})}).finally(()=>{this.executing.delete(a)}))}}}export{S 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-r_CAb7zy.js";import{A as G,g as b,a as L,b as O,d as A}from"./index-W9ryXG_v.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-D1yWx-8k.js";import{A as G,g as b,a as L,b as O,d as A}from"./index-DJPmZw4a.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-W9ryXG_v.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-r_CAb7zy.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-DJPmZw4a.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-D1yWx-8k.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-W9ryXG_v.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-DJPmZw4a.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-r_CAb7zy.js";import{A as S,a as R,b as N,d as A}from"./index-W9ryXG_v.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-D1yWx-8k.js";import{A as S,a as R,b as N,d as A}from"./index-DJPmZw4a.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,4 +1,4 @@
1
- import{i as F,r as g,h as A,j as L,k as T,l as _,m as C,n as D,o as P}from"./index-W9ryXG_v.js";import{M as B,p as V,S as b,q as X,u as Y,v as q,w as z,x as U,W as Z,y as G,z as J,B as Q,C as N,D as ee,E as se,F as ie}from"./index-W9ryXG_v.js";function I(s){return s.startsWith("/")?{valid:!1,error:`Absolute path not allowed: ${s}`}:s.split("/").some(l=>l==="..")?{valid:!1,error:`Path traversal not allowed: ${s}`}:s.includes("%2e%2e")||s.includes("%2E%2E")?{valid:!1,error:`Encoded path traversal not allowed: ${s}`}:{valid:!0}}async function x(s,i){const l=i.split("/").filter(Boolean);let o="";for(const e of l){o+="/"+e;try{await s.mkdir(o)}catch{}}}async function O(s,i,l="/workspace/skills"){const o=`${l}/${i}`;await F(s);let e;try{e=await g(s,o)}catch(d){return{success:!1,skill:i,version:"unknown",error:`Failed to read manifest: ${d instanceof Error?d.message:String(d)}`}}if(e.skill!==i)return{success:!1,skill:i,version:e.version,error:`Manifest skill name "${e.skill}" does not match directory name "${i}"`};const p=await A(s);if(p.includes(e.skill))return{success:!1,skill:e.skill,version:e.version,error:`Skill "${e.skill}" is already installed`};const u=L(e,p);if(!u.ok)return{success:!1,skill:e.skill,version:e.version,error:`Missing dependencies: ${u.missing.join(", ")}`};const t=T(e,p);if(!t.ok)return{success:!1,skill:e.skill,version:e.version,error:`Conflicting skills: ${t.conflicting.join(", ")}`};const c={},h=[];try{if(e.adds&&e.adds.length>0)for(const n of e.adds){const k=I(n);if(!k.valid)return{success:!1,skill:e.skill,version:e.version,error:k.error};const $=`${o}/add/${n}`,a=`/${n}`;try{const r=a.substring(0,a.lastIndexOf("/"));r&&await x(s,r),await s.copyFile($,a),h.push(n);const f=await s.readTextFile(a);c[n]=await _(f)}catch(r){return{success:!1,skill:e.skill,version:e.version,error:`Failed to copy ${n}: ${r instanceof Error?r.message:String(r)}`}}}if(e.modifies&&e.modifies.length>0)for(const n of e.modifies){const k=I(n);if(!k.valid)return{success:!1,skill:e.skill,version:e.version,error:k.error};const $=`${o}/modify/${n}`;try{const a=await s.readTextFile($);let r="";try{r=await s.readTextFile(`/${n}`)}catch{}let f;if(a.includes("// APPEND_AFTER:")){const w=a.split(`
1
+ import{i as F,r as g,h as A,j as L,k as T,l as _,m as C,n as D,o as P}from"./index-DJPmZw4a.js";import{M as B,p as V,S as b,q as X,u as Y,v as q,w as z,x as U,W as Z,y as G,z as J,B as Q,C as N,D as ee,E as se,F as ie}from"./index-DJPmZw4a.js";function I(s){return s.startsWith("/")?{valid:!1,error:`Absolute path not allowed: ${s}`}:s.split("/").some(l=>l==="..")?{valid:!1,error:`Path traversal not allowed: ${s}`}:s.includes("%2e%2e")||s.includes("%2E%2E")?{valid:!1,error:`Encoded path traversal not allowed: ${s}`}:{valid:!0}}async function x(s,i){const l=i.split("/").filter(Boolean);let o="";for(const e of l){o+="/"+e;try{await s.mkdir(o)}catch{}}}async function O(s,i,l="/workspace/skills"){const o=`${l}/${i}`;await F(s);let e;try{e=await g(s,o)}catch(d){return{success:!1,skill:i,version:"unknown",error:`Failed to read manifest: ${d instanceof Error?d.message:String(d)}`}}if(e.skill!==i)return{success:!1,skill:i,version:e.version,error:`Manifest skill name "${e.skill}" does not match directory name "${i}"`};const p=await A(s);if(p.includes(e.skill))return{success:!1,skill:e.skill,version:e.version,error:`Skill "${e.skill}" is already installed`};const u=L(e,p);if(!u.ok)return{success:!1,skill:e.skill,version:e.version,error:`Missing dependencies: ${u.missing.join(", ")}`};const t=T(e,p);if(!t.ok)return{success:!1,skill:e.skill,version:e.version,error:`Conflicting skills: ${t.conflicting.join(", ")}`};const c={},h=[];try{if(e.adds&&e.adds.length>0)for(const n of e.adds){const k=I(n);if(!k.valid)return{success:!1,skill:e.skill,version:e.version,error:k.error};const $=`${o}/add/${n}`,a=`/${n}`;try{const r=a.substring(0,a.lastIndexOf("/"));r&&await x(s,r),await s.copyFile($,a),h.push(n);const f=await s.readTextFile(a);c[n]=await _(f)}catch(r){return{success:!1,skill:e.skill,version:e.version,error:`Failed to copy ${n}: ${r instanceof Error?r.message:String(r)}`}}}if(e.modifies&&e.modifies.length>0)for(const n of e.modifies){const k=I(n);if(!k.valid)return{success:!1,skill:e.skill,version:e.version,error:k.error};const $=`${o}/modify/${n}`;try{const a=await s.readTextFile($);let r="";try{r=await s.readTextFile(`/${n}`)}catch{}let f;if(a.includes("// APPEND_AFTER:")){const w=a.split(`
2
2
  `),v=w.find(S=>S.includes("// APPEND_AFTER:"))?.split("// APPEND_AFTER:")[1]?.trim(),m=w.filter(S=>!S.includes("// APPEND_AFTER:")).join(`
3
3
  `);if(v&&r.includes(v)){const S=r.indexOf(v)+v.length,E=r.indexOf(`
4
4
  `,S);if(E===-1){const y=r.endsWith(`
@@ -1 +1 @@
1
- import{c as f,H as C}from"./index-W9ryXG_v.js";import{I as P,J as v,R as H}from"./index-W9ryXG_v.js";const u="[slicc-tab-group]";let g=null;async function p(a){try{if(g!==null)try{await chrome.tabs.group({tabIds:a,groupId:g});return}catch(e){console.info(u,"Tab group removed by user, recreating",{tabId:a,previousGroupId:g,error:e instanceof Error?e.message:String(e)}),g=null}g=await chrome.tabs.group({tabIds:a}),await chrome.tabGroups.update(g,{title:"slicc",color:"pink",collapsed:!1})}catch(e){console.warn(u,"Tab grouping failed (best-effort, continuing without group)",{tabId:a,error:e instanceof Error?e.message:String(e)})}}const h=f("cdp:debugger");class y{_state="disconnected";listeners=new Map;sessionToTab=new Map;attachedTabs=new Set;onEventHandler=(e,s,t)=>{if(!this.attachedTabs.has(e.tabId))return;let n;for(const[o,i]of this.sessionToTab)if(i===e.tabId){n=o;break}h.debug("Event",{tabId:e.tabId,method:s,sessionId:n});const r=this.listeners.get(s);if(r){const o=n?{...t,sessionId:n}:t??{};for(const i of r)try{i(o)}catch(d){h.error("CDP event listener error",{method:s,error:d instanceof Error?d.message:String(d)})}}};onDetachHandler=(e,s)=>{h.warn("Debugger detached",{tabId:e.tabId,reason:s}),this.attachedTabs.delete(e.tabId);for(const[t,n]of this.sessionToTab)n===e.tabId&&this.sessionToTab.delete(t);this.attachedTabs.size===0&&(this._state="disconnected")};get state(){return this._state}async connect(e){if(this._state!=="disconnected")throw new Error(`Cannot connect: state is ${this._state}`);chrome.debugger.onEvent.addListener(this.onEventHandler),chrome.debugger.onDetach.addListener(this.onDetachHandler),this._state="connected",h.info("DebuggerClient connected (extension mode)")}disconnect(){for(const e of this.attachedTabs)chrome.debugger.detach({tabId:e}).catch(s=>{h.debug("Detach during disconnect",{tabId:e,error:s instanceof Error?s.message:String(s)})});chrome.debugger.onEvent.removeListener(this.onEventHandler),chrome.debugger.onDetach.removeListener(this.onDetachHandler),this.attachedTabs.clear(),this.sessionToTab.clear(),this._state="disconnected",h.info("DebuggerClient disconnected")}async send(e,s,t,n){if(this._state!=="connected")throw new Error("DebuggerClient is not connected");switch(e){case"Target.getTargets":return this.handleGetTargets();case"Target.attachToTarget":return this.handleAttachToTarget(s);case"Target.detachFromTarget":return this.handleDetachFromTarget(s);case"Target.createTarget":return this.handleCreateTarget(s);case"Target.closeTarget":return this.handleCloseTarget(s);default:return this.sendCdpCommand(e,s,t)}}on(e,s){let t=this.listeners.get(e);t||(t=new Set,this.listeners.set(e,t)),t.add(s)}off(e,s){const t=this.listeners.get(e);t&&(t.delete(s),t.size===0&&this.listeners.delete(e))}once(e,s=3e4){return new Promise((t,n)=>{const r=setTimeout(()=>{this.off(e,o),n(new Error(`Timed out waiting for event: ${e}`))},s),o=i=>{clearTimeout(r),this.off(e,o),t(i)};this.on(e,o)})}async handleGetTargets(){const[e,s]=await Promise.all([chrome.tabs.query({}),chrome.tabs.query({active:!0,currentWindow:!0})]),t=new Set(s.map(r=>r.id));return{targetInfos:e.map(r=>({targetId:String(r.id),type:"page",title:r.title??"",url:r.url??"",attached:this.attachedTabs.has(r.id),active:t.has(r.id)}))}}async handleAttachToTarget(e){const s=e.targetId,t=parseInt(s,10);if(!Number.isFinite(t)||t<=0)throw new Error(`Invalid targetId: ${s}`);this.attachedTabs.has(t)||(await chrome.debugger.attach({tabId:t},"1.3"),this.attachedTabs.add(t));const n=s;return this.sessionToTab.set(n,t),{sessionId:n}}async handleDetachFromTarget(e){const s=e.sessionId;return this.sessionToTab.get(s)!==void 0&&this.sessionToTab.delete(s),{}}async handleCreateTarget(e){const s=e.url??"about:blank",t=await chrome.tabs.create({url:s,active:!1});return await p(t.id),{targetId:String(t.id)}}async handleCloseTarget(e){const s=e.targetId,t=parseInt(s,10);if(!Number.isFinite(t)||t<=0)throw new Error(`Invalid targetId: ${s}`);for(const[n,r]of this.sessionToTab)r===t&&this.sessionToTab.delete(n);return this.attachedTabs.has(t)&&(this.attachedTabs.delete(t),await chrome.debugger.detach({tabId:t}).catch(n=>{h.debug("Detach before close failed",{tabId:t,error:n instanceof Error?n.message:String(n)})})),await chrome.tabs.remove(t),{success:!0}}async sendCdpCommand(e,s,t){const n=t?this.sessionToTab.get(t):void 0;if(n===void 0)throw new Error(`No tab attached for sessionId: ${t??"(none)"}. Attach to a target first.`);return h.debug("Send",{method:e,tabId:n,sessionId:t}),await chrome.debugger.sendCommand({tabId:n},e,s)??{}}}class I{_state="disconnected";nextCommandId=1;listeners=new Map;pendingCommands=new Map;messageHandler=null;get state(){return this._state}async connect(e){if(this._state!=="disconnected")throw new Error(`Cannot connect: state is ${this._state}`);this.messageHandler=s=>{if(!T(s))return;const t=s;if(t.source!=="service-worker")return;const n=t.payload;n.type==="cdp-response"?this.handleCdpResponse(n):n.type==="cdp-event"&&this.handleCdpEvent(n)},chrome.runtime.onMessage.addListener(this.messageHandler),this._state="connected"}disconnect(){this.messageHandler&&(chrome.runtime.onMessage.removeListener(this.messageHandler),this.messageHandler=null);for(const[,e]of this.pendingCommands)clearTimeout(e.timer),e.reject(new Error("CDP proxy disconnected"));this.pendingCommands.clear(),this.listeners.clear(),this._state="disconnected"}async send(e,s,t,n=3e4){if(this._state!=="connected")throw new Error("OffscreenCdpProxy is not connected");const r=this.nextCommandId++,o={type:"cdp-command",id:r,method:e,params:s,sessionId:t};return new Promise((i,d)=>{let c=!1;const m=setTimeout(()=>{c||(c=!0,this.pendingCommands.delete(r),d(new Error(`CDP command timed out after ${n}ms: ${e}`)))},n);this.pendingCommands.set(r,{resolve:i,reject:d,timer:m}),chrome.runtime.sendMessage({source:"offscreen",payload:o}).catch(l=>{c||(c=!0,this.pendingCommands.delete(r),clearTimeout(m),d(new Error(`Failed to send CDP command: ${l instanceof Error?l.message:String(l)}`)))})})}on(e,s){let t=this.listeners.get(e);t||(t=new Set,this.listeners.set(e,t)),t.add(s)}off(e,s){const t=this.listeners.get(e);t&&(t.delete(s),t.size===0&&this.listeners.delete(e))}once(e,s=3e4){return new Promise((t,n)=>{const r=setTimeout(()=>{this.off(e,o),n(new Error(`Timed out waiting for event: ${e}`))},s),o=i=>{clearTimeout(r),this.off(e,o),t(i)};this.on(e,o)})}handleCdpResponse(e){const s=this.pendingCommands.get(e.id);s&&(this.pendingCommands.delete(e.id),clearTimeout(s.timer),e.error?s.reject(new Error(e.error)):s.resolve(e.result??{}))}handleCdpEvent(e){const s=this.listeners.get(e.method);if(s)for(const t of s)try{t(e.params??{})}catch{}}}function T(a){return typeof a=="object"&&a!==null&&"source"in a&&"payload"in a}class E{_state="disconnected";nextCommandId=1;listeners=new Map;pendingCommands=new Map;messageHandler=null;get state(){return this._state}async connect(e){if(this._state!=="disconnected")throw new Error(`Cannot connect: state is ${this._state}`);this.messageHandler=s=>{try{if(!b(s))return;const t=s;t.source==="offscreen"&&t.payload.type==="panel-cdp-response"&&this.handleCdpResponse(t.payload),t.source==="service-worker"&&t.payload.type==="cdp-event"&&this.handleCdpEvent(t.payload)}catch(t){console.error("[panel-cdp-proxy] Error in message handler:",t)}},chrome.runtime.onMessage.addListener(this.messageHandler),this._state="connected"}disconnect(){this.messageHandler&&(chrome.runtime.onMessage.removeListener(this.messageHandler),this.messageHandler=null);for(const[,e]of this.pendingCommands)clearTimeout(e.timer),e.reject(new Error("Panel CDP proxy disconnected"));this.pendingCommands.clear(),this.listeners.clear(),this._state="disconnected"}async send(e,s,t,n=3e4){if(this._state!=="connected")throw new Error("PanelCdpProxy is not connected");const r=this.nextCommandId++,o={type:"panel-cdp-command",id:r,method:e,params:s,sessionId:t};return new Promise((i,d)=>{let c=!1;const m=setTimeout(()=>{c||(c=!0,this.pendingCommands.delete(r),d(new Error(`CDP command timed out after ${n}ms: ${e}`)))},n);this.pendingCommands.set(r,{resolve:i,reject:d,timer:m}),chrome.runtime.sendMessage({source:"panel",payload:o}).catch(l=>{c||(c=!0,this.pendingCommands.delete(r),clearTimeout(m),d(new Error(`Failed to send CDP command: ${l instanceof Error?l.message:String(l)}`)))})})}on(e,s){let t=this.listeners.get(e);t||(t=new Set,this.listeners.set(e,t)),t.add(s)}off(e,s){const t=this.listeners.get(e);t&&(t.delete(s),t.size===0&&this.listeners.delete(e))}once(e,s=3e4){return new Promise((t,n)=>{const r=setTimeout(()=>{this.off(e,o),n(new Error(`Timed out waiting for event: ${e}`))},s),o=i=>{clearTimeout(r),this.off(e,o),t(i)};this.on(e,o)})}handleCdpResponse(e){const s=this.pendingCommands.get(e.id);if(!s){console.warn(`[panel-cdp-proxy] Ignoring CDP response with unknown id ${e.id}`);return}this.pendingCommands.delete(e.id),clearTimeout(s.timer),e.error?s.reject(new Error(e.error)):s.resolve(e.result??{})}handleCdpEvent(e){const s=this.listeners.get(e.method);if(s)for(const t of s)try{t(e.params??{})}catch(n){console.error(`[panel-cdp-proxy] Listener error for event "${e.method}":`,n)}}}function b(a){return typeof a=="object"&&a!==null&&"source"in a&&"payload"in a}export{C as BrowserAPI,P as CDPClient,y as DebuggerClient,v as HarRecorder,I as OffscreenCdpProxy,E as PanelCdpProxy,H as RemoteCDPTransport};
1
+ import{c as f,H as C}from"./index-DJPmZw4a.js";import{I as P,J as v,R as H}from"./index-DJPmZw4a.js";const u="[slicc-tab-group]";let g=null;async function p(a){try{if(g!==null)try{await chrome.tabs.group({tabIds:a,groupId:g});return}catch(e){console.info(u,"Tab group removed by user, recreating",{tabId:a,previousGroupId:g,error:e instanceof Error?e.message:String(e)}),g=null}g=await chrome.tabs.group({tabIds:a}),await chrome.tabGroups.update(g,{title:"slicc",color:"pink",collapsed:!1})}catch(e){console.warn(u,"Tab grouping failed (best-effort, continuing without group)",{tabId:a,error:e instanceof Error?e.message:String(e)})}}const h=f("cdp:debugger");class y{_state="disconnected";listeners=new Map;sessionToTab=new Map;attachedTabs=new Set;onEventHandler=(e,s,t)=>{if(!this.attachedTabs.has(e.tabId))return;let n;for(const[o,i]of this.sessionToTab)if(i===e.tabId){n=o;break}h.debug("Event",{tabId:e.tabId,method:s,sessionId:n});const r=this.listeners.get(s);if(r){const o=n?{...t,sessionId:n}:t??{};for(const i of r)try{i(o)}catch(d){h.error("CDP event listener error",{method:s,error:d instanceof Error?d.message:String(d)})}}};onDetachHandler=(e,s)=>{h.warn("Debugger detached",{tabId:e.tabId,reason:s}),this.attachedTabs.delete(e.tabId);for(const[t,n]of this.sessionToTab)n===e.tabId&&this.sessionToTab.delete(t);this.attachedTabs.size===0&&(this._state="disconnected")};get state(){return this._state}async connect(e){if(this._state!=="disconnected")throw new Error(`Cannot connect: state is ${this._state}`);chrome.debugger.onEvent.addListener(this.onEventHandler),chrome.debugger.onDetach.addListener(this.onDetachHandler),this._state="connected",h.info("DebuggerClient connected (extension mode)")}disconnect(){for(const e of this.attachedTabs)chrome.debugger.detach({tabId:e}).catch(s=>{h.debug("Detach during disconnect",{tabId:e,error:s instanceof Error?s.message:String(s)})});chrome.debugger.onEvent.removeListener(this.onEventHandler),chrome.debugger.onDetach.removeListener(this.onDetachHandler),this.attachedTabs.clear(),this.sessionToTab.clear(),this._state="disconnected",h.info("DebuggerClient disconnected")}async send(e,s,t,n){if(this._state!=="connected")throw new Error("DebuggerClient is not connected");switch(e){case"Target.getTargets":return this.handleGetTargets();case"Target.attachToTarget":return this.handleAttachToTarget(s);case"Target.detachFromTarget":return this.handleDetachFromTarget(s);case"Target.createTarget":return this.handleCreateTarget(s);case"Target.closeTarget":return this.handleCloseTarget(s);default:return this.sendCdpCommand(e,s,t)}}on(e,s){let t=this.listeners.get(e);t||(t=new Set,this.listeners.set(e,t)),t.add(s)}off(e,s){const t=this.listeners.get(e);t&&(t.delete(s),t.size===0&&this.listeners.delete(e))}once(e,s=3e4){return new Promise((t,n)=>{const r=setTimeout(()=>{this.off(e,o),n(new Error(`Timed out waiting for event: ${e}`))},s),o=i=>{clearTimeout(r),this.off(e,o),t(i)};this.on(e,o)})}async handleGetTargets(){const[e,s]=await Promise.all([chrome.tabs.query({}),chrome.tabs.query({active:!0,currentWindow:!0})]),t=new Set(s.map(r=>r.id));return{targetInfos:e.map(r=>({targetId:String(r.id),type:"page",title:r.title??"",url:r.url??"",attached:this.attachedTabs.has(r.id),active:t.has(r.id)}))}}async handleAttachToTarget(e){const s=e.targetId,t=parseInt(s,10);if(!Number.isFinite(t)||t<=0)throw new Error(`Invalid targetId: ${s}`);this.attachedTabs.has(t)||(await chrome.debugger.attach({tabId:t},"1.3"),this.attachedTabs.add(t));const n=s;return this.sessionToTab.set(n,t),{sessionId:n}}async handleDetachFromTarget(e){const s=e.sessionId;return this.sessionToTab.get(s)!==void 0&&this.sessionToTab.delete(s),{}}async handleCreateTarget(e){const s=e.url??"about:blank",t=await chrome.tabs.create({url:s,active:!1});return await p(t.id),{targetId:String(t.id)}}async handleCloseTarget(e){const s=e.targetId,t=parseInt(s,10);if(!Number.isFinite(t)||t<=0)throw new Error(`Invalid targetId: ${s}`);for(const[n,r]of this.sessionToTab)r===t&&this.sessionToTab.delete(n);return this.attachedTabs.has(t)&&(this.attachedTabs.delete(t),await chrome.debugger.detach({tabId:t}).catch(n=>{h.debug("Detach before close failed",{tabId:t,error:n instanceof Error?n.message:String(n)})})),await chrome.tabs.remove(t),{success:!0}}async sendCdpCommand(e,s,t){const n=t?this.sessionToTab.get(t):void 0;if(n===void 0)throw new Error(`No tab attached for sessionId: ${t??"(none)"}. Attach to a target first.`);return h.debug("Send",{method:e,tabId:n,sessionId:t}),await chrome.debugger.sendCommand({tabId:n},e,s)??{}}}class I{_state="disconnected";nextCommandId=1;listeners=new Map;pendingCommands=new Map;messageHandler=null;get state(){return this._state}async connect(e){if(this._state!=="disconnected")throw new Error(`Cannot connect: state is ${this._state}`);this.messageHandler=s=>{if(!T(s))return;const t=s;if(t.source!=="service-worker")return;const n=t.payload;n.type==="cdp-response"?this.handleCdpResponse(n):n.type==="cdp-event"&&this.handleCdpEvent(n)},chrome.runtime.onMessage.addListener(this.messageHandler),this._state="connected"}disconnect(){this.messageHandler&&(chrome.runtime.onMessage.removeListener(this.messageHandler),this.messageHandler=null);for(const[,e]of this.pendingCommands)clearTimeout(e.timer),e.reject(new Error("CDP proxy disconnected"));this.pendingCommands.clear(),this.listeners.clear(),this._state="disconnected"}async send(e,s,t,n=3e4){if(this._state!=="connected")throw new Error("OffscreenCdpProxy is not connected");const r=this.nextCommandId++,o={type:"cdp-command",id:r,method:e,params:s,sessionId:t};return new Promise((i,d)=>{let c=!1;const m=setTimeout(()=>{c||(c=!0,this.pendingCommands.delete(r),d(new Error(`CDP command timed out after ${n}ms: ${e}`)))},n);this.pendingCommands.set(r,{resolve:i,reject:d,timer:m}),chrome.runtime.sendMessage({source:"offscreen",payload:o}).catch(l=>{c||(c=!0,this.pendingCommands.delete(r),clearTimeout(m),d(new Error(`Failed to send CDP command: ${l instanceof Error?l.message:String(l)}`)))})})}on(e,s){let t=this.listeners.get(e);t||(t=new Set,this.listeners.set(e,t)),t.add(s)}off(e,s){const t=this.listeners.get(e);t&&(t.delete(s),t.size===0&&this.listeners.delete(e))}once(e,s=3e4){return new Promise((t,n)=>{const r=setTimeout(()=>{this.off(e,o),n(new Error(`Timed out waiting for event: ${e}`))},s),o=i=>{clearTimeout(r),this.off(e,o),t(i)};this.on(e,o)})}handleCdpResponse(e){const s=this.pendingCommands.get(e.id);s&&(this.pendingCommands.delete(e.id),clearTimeout(s.timer),e.error?s.reject(new Error(e.error)):s.resolve(e.result??{}))}handleCdpEvent(e){const s=this.listeners.get(e.method);if(s)for(const t of s)try{t(e.params??{})}catch{}}}function T(a){return typeof a=="object"&&a!==null&&"source"in a&&"payload"in a}class E{_state="disconnected";nextCommandId=1;listeners=new Map;pendingCommands=new Map;messageHandler=null;get state(){return this._state}async connect(e){if(this._state!=="disconnected")throw new Error(`Cannot connect: state is ${this._state}`);this.messageHandler=s=>{try{if(!b(s))return;const t=s;t.source==="offscreen"&&t.payload.type==="panel-cdp-response"&&this.handleCdpResponse(t.payload),t.source==="service-worker"&&t.payload.type==="cdp-event"&&this.handleCdpEvent(t.payload)}catch(t){console.error("[panel-cdp-proxy] Error in message handler:",t)}},chrome.runtime.onMessage.addListener(this.messageHandler),this._state="connected"}disconnect(){this.messageHandler&&(chrome.runtime.onMessage.removeListener(this.messageHandler),this.messageHandler=null);for(const[,e]of this.pendingCommands)clearTimeout(e.timer),e.reject(new Error("Panel CDP proxy disconnected"));this.pendingCommands.clear(),this.listeners.clear(),this._state="disconnected"}async send(e,s,t,n=3e4){if(this._state!=="connected")throw new Error("PanelCdpProxy is not connected");const r=this.nextCommandId++,o={type:"panel-cdp-command",id:r,method:e,params:s,sessionId:t};return new Promise((i,d)=>{let c=!1;const m=setTimeout(()=>{c||(c=!0,this.pendingCommands.delete(r),d(new Error(`CDP command timed out after ${n}ms: ${e}`)))},n);this.pendingCommands.set(r,{resolve:i,reject:d,timer:m}),chrome.runtime.sendMessage({source:"panel",payload:o}).catch(l=>{c||(c=!0,this.pendingCommands.delete(r),clearTimeout(m),d(new Error(`Failed to send CDP command: ${l instanceof Error?l.message:String(l)}`)))})})}on(e,s){let t=this.listeners.get(e);t||(t=new Set,this.listeners.set(e,t)),t.add(s)}off(e,s){const t=this.listeners.get(e);t&&(t.delete(s),t.size===0&&this.listeners.delete(e))}once(e,s=3e4){return new Promise((t,n)=>{const r=setTimeout(()=>{this.off(e,o),n(new Error(`Timed out waiting for event: ${e}`))},s),o=i=>{clearTimeout(r),this.off(e,o),t(i)};this.on(e,o)})}handleCdpResponse(e){const s=this.pendingCommands.get(e.id);if(!s){console.warn(`[panel-cdp-proxy] Ignoring CDP response with unknown id ${e.id}`);return}this.pendingCommands.delete(e.id),clearTimeout(s.timer),e.error?s.reject(new Error(e.error)):s.resolve(e.result??{})}handleCdpEvent(e){const s=this.listeners.get(e.method);if(s)for(const t of s)try{t(e.params??{})}catch(n){console.error(`[panel-cdp-proxy] Listener error for event "${e.method}":`,n)}}}function b(a){return typeof a=="object"&&a!==null&&"source"in a&&"payload"in a}export{C as BrowserAPI,P as CDPClient,y as DebuggerClient,v as HarRecorder,I as OffscreenCdpProxy,E as PanelCdpProxy,H as RemoteCDPTransport};