@jeevanand/agent-browserbox-runtime 0.1.0 → 0.1.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 (25) hide show
  1. package/README.md +1 -1
  2. package/bin/serve.mjs +2 -2
  3. package/dist/assets/{anthropic-Cc12J4F-.js → anthropic-S3ckT02t.js} +2 -2
  4. package/dist/assets/{bridge-Bqc3YIRQ.js → bridge-DY2WnNx7.js} +1 -1
  5. package/dist/assets/{build-bryiJ-b6.js → build-BNa5TW3M.js} +1 -1
  6. package/dist/assets/{bundle-rO6AXpFE.js → bundle-8opp8__C.js} +1 -1
  7. package/dist/assets/{dev-impl-CfwRFPRf.js → dev-impl-BRiXVAGb.js} +1 -1
  8. package/dist/assets/{github-CrzofUbV.js → github-Dwhv0h55.js} +1 -1
  9. package/dist/assets/{html-DI-AyJM9.js → html-R2xYS1Rp.js} +1 -1
  10. package/dist/assets/{main-DBKsMgp-.js → main-VEpSfsM_.js} +9 -9
  11. package/dist/assets/{node.browser-CCRW_leA.js → node.browser-1OJr47If.js} +1 -1
  12. package/dist/assets/{node.browser-D_wxWW2g.js → node.browser-cOXEGsLT.js} +1 -1
  13. package/dist/assets/{openai-D6_sZyaT.js → openai-CThAXVqN.js} +1 -1
  14. package/dist/assets/{pkg-esbuild-DxKODBC3.js → pkg-esbuild-BuQjm7dB.js} +1 -1
  15. package/dist/assets/{pkg-git-Ds2ZjUJG.js → pkg-git-jawfIVoq.js} +1 -1
  16. package/dist/assets/{pkg-python-Cps4de9u.js → pkg-python-CoNK0IjJ.js} +1 -1
  17. package/dist/assets/{pkg-zip-B_IjTDzR.js → pkg-zip-BdZ_Lkdk.js} +1 -1
  18. package/dist/assets/{publish-gZ8mQa6L.js → publish-CHt_Qrq5.js} +1 -1
  19. package/dist/assets/{publish-impl-DV1nd6hh.js → publish-impl-BqjdM7Ux.js} +3 -3
  20. package/dist/assets/{server-CnIXpfUH.js → server-C5Sd62CK.js} +1 -1
  21. package/dist/assets/{webllm-CGpOYyn6.js → webllm-wsrhCAP4.js} +1 -1
  22. package/dist/embed/index.html +2 -2
  23. package/dist/kernel/bridge.html +1 -1
  24. package/dist/kernel/packages.json +1 -1
  25. package/package.json +2 -2
@@ -319,4 +319,4 @@ async function runWasi(m, out, err) {
319
319
  }
320
320
  return { exitCode };
321
321
  }
322
- `,d=`python.packages`,f=262144,p=class{os;proc;#e;#t;#n=1;#r=!1;#i=new Map;#a=null;constructor(e,t){this.os=e,this.proc=e.procs.spawn({name:t.name,kind:`sandbox`,ppid:t.ppid,detail:t.network?`isolated worker · network allowed`:`isolated worker · no network`,onKill:()=>this.#o()});let n=this.#e=o(document.createElement(`iframe`));n.setAttribute(`sandbox`,`allow-scripts`),n.style.display=`none`,n.src=new URL(t.network?`sandbox-net.html`:`sandbox.html`,a).href,this.#t=new Promise((e,t)=>{let r=setTimeout(()=>t(Error(`sandbox failed to start`)),15e3),i=t=>{if(t.source===n.contentWindow){if(t.data?.type===`hello`){let t=new MessageChannel;t.port1.onmessage=n=>{n.data?.type===`ready`&&(clearTimeout(r),t.port1.onmessage=e=>this.#i.get(e.data.id)?.(e.data),e(t.port1))},n.contentWindow.postMessage({type:`boot`,src:u},`*`,[t.port2])}else t.data?.type===`crash`&&this.#a?.(String(t.data.error))}};addEventListener(`message`,i),this.proc.signal.addEventListener(`abort`,()=>{removeEventListener(`message`,i),clearTimeout(r),t(Error(`sandbox was killed`))})}),this.#t.catch(()=>void 0),document.body.append(n)}get alive(){return!this.#r}#o(){this.#r=!0,this.#e.remove()}dispose(){this.#r||this.os.procs.exit(this.proc.pid)}async run(e,t={}){let n=performance.now(),i=t.cwd??`/`,a=``,o=``,s=e=>{let t=performance.now()-n;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:a,stderr:o,ms:t,...e}},c;try{c=await this.#t}catch(e){return s({error:e.message})}let l=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(n=>{let u=(e,r=!1)=>{clearTimeout(m),this.#i.delete(l),this.#a=null,t.signal?.removeEventListener(`abort`,d),this.proc.signal.removeEventListener(`abort`,p),r?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),n(s(e))},d=()=>u({error:`aborted`},!0),p=()=>u({error:`sandbox was killed`}),m=setTimeout(()=>u({error:`timed out after ${t.timeoutMs??3e4} ms`,timedOut:!0},!0),t.timeoutMs??3e4);t.signal?.addEventListener(`abort`,d),this.proc.signal.addEventListener(`abort`,p),this.#a=e=>u({error:e},!0),this.#i.set(l,e=>{e.type===`stdout`?(a.length<f&&(a+=e.data),t.onStdout?.(e.data)):e.type===`stderr`?(o.length<f&&(o+=e.data),t.onStderr?.(e.data)):e.type===`progress`?t.onProgress?.({label:e.label,loaded:e.loaded,total:e.total}):e.type===`rpc`?this.#s(i,e.method,e.params).then(t=>c.postMessage({type:`rpc-result`,rid:e.rid,value:t}),t=>c.postMessage({type:`rpc-result`,rid:e.rid,error:t.message})):e.type===`done`&&(async()=>{if(e.error)return u({error:e.error});try{for(let t of e.result?.files??[])await this.os.fs.writeFile(r(i,t.path),t.data)}catch(e){return u({error:`could not write files back: ${e.message}`})}let t=e.result?.exitCode;u({ok:t===void 0||t===0,value:e.result?.value,exitCode:t,response:e.result?.response})})()}),c.postMessage({id:l,...e})})}async#s(e,t,n){let i=this.os.fs,a=(i=0)=>{if(typeof n[i]!=`string`)throw Error(`${t}: path must be a string`);return r(e,n[i])};switch(t){case`fs.readText`:return i.readText(a());case`fs.readFile`:return i.readFile(a());case`fs.writeFile`:return i.writeFile(a(),n[1]);case`fs.appendFile`:return i.appendFile(a(),n[1]);case`fs.readdir`:return i.readdir(a());case`fs.exists`:return i.exists(a());case`fs.mkdir`:return i.mkdir(a());case`fs.rm`:return i.rm(a(),{recursive:!0});case`fs.glob`:return i.glob(String(n[0]),e);default:throw Error(`unknown sandbox call: ${t}`)}}};async function m(e,t,n={}){let r=new p(e,{name:`js`,network:n.network,ppid:n.ppid});try{return await r.run({op:`js`,code:t,args:n.args,env:n.env},n)}finally{r.dispose()}}async function h(e,t,n={}){let r=new p(e,{name:n.name??`wasm`,ppid:n.ppid});try{return await r.run({op:`wasm`,wasm:t,args:n.args,stdin:n.stdin,name:n.name},n)}finally{r.dispose()}}var g=null,_=!1;async function v(){try{let e=await caches.open(l),t=await Promise.all(c.map(async t=>{let n=await e.match(s+t);return n?{path:t,data:new Uint8Array(await n.arrayBuffer())}:null}));return t.every(e=>e!==null)?t:void 0}catch{return}}async function y(e,t){let n=[],r=25165824;for await(let i of e.fs.walk(t,{maxDepth:6}))if(!(i.kind!==`file`||i.size>8388608||i.size>r)&&(r-=i.size,n.push({path:i.path.slice(t===`/`?1:t.length+1),data:await e.fs.readFile(i.path)}),n.length>=400))break;return n}async function b(e,t,n={}){g?.alive||(g=new p(e,{name:`python`,network:!1}),_=!1);let r=n.cwd??`/tmp`,i=await y(e,r),a=!_,o=a?await v():void 0,c=a?e.settings.get(d,[]):[],l=[...new Set([...c,...n.packages??[]])],u=await g.run({op:`python`,code:t,packages:l.length?l:void 0,files:i,pyodideUrl:s,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return _=g.alive&&!u.timedOut,u}var x=new Map;async function S(e,t,n,r,i={}){let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return x.get(n)?.dispose(),x.delete(n),a();if(t===`load`){x.get(n)?.dispose();let t=new p(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});x.set(n,t);let a=await t.run({op:`server-load`,code:r.code??``,env:r.env},{...i,timeoutMs:15e3});return a.ok||(t.dispose(),x.delete(n)),a}let o=x.get(n);return!o?.alive||!r.req?a(`backend not loaded`):o.run({op:`server-request`,req:r.req,origin:r.origin??`http://localhost`},{...i,timeoutMs:i.timeoutMs??3e4})}var C=`SharedWorker`in globalThis,w=n(i(location.search)),T=null;function E(){if(C)return new SharedWorker(new URL(new URL(`main-DBKsMgp-.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w}).port;T??=new Worker(new URL(new URL(`main-DBKsMgp-.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w});let e=new MessageChannel;return T.postMessage({type:`connect`},[e.port2]),e.port1}var D=`bbx-window-${crypto.randomUUID()}`;navigator.locks?.request(D,()=>new Promise(()=>void 0));var O=new t(Promise.resolve({port:E(),lock:D,shared:C}),`host`),k=new Map;O.handle({"host.run":async(e,t,n,r)=>{let i=new AbortController;k.set(e,i);let a=await O.handle({}),o={...r,signal:i.signal,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t}),onProgress:t=>a.emit(`host:progress`,{runId:e,...t}),env:n.env};try{return t===`js`?await m(O,n.code,{...o,args:n.args,network:n.network,ppid:n.ppid}):t===`python`?await b(O,n.code,{...o,packages:n.packages}):await h(O,n.wasm,{...o,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid})}finally{k.delete(e)}},"host.backend":async(e,t,n,r,i)=>{let a=await O.handle({});return S(O,t,n,r,{...i,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t})})}}).then(e=>e.on(`host:abort`,e=>k.get(e)?.abort()));var A=new Set([location.origin,...e]),j=!1;addEventListener(`message`,e=>{if(!(e.source!==parent||e.data?.type!==`bbx:connect`||j)){if(!A.has(e.origin))return parent.postMessage({type:`bbx:refused`},e.origin);j=!0,parent.postMessage({type:`bbx:port`,lock:D,shared:C},e.origin,[E()])}}),parent!==window&&parent.postMessage({type:`bbx:ready`},`*`);
322
+ `,d=`python.packages`,f=262144,p=class{os;proc;#e;#t;#n=1;#r=!1;#i=new Map;#a=null;constructor(e,t){this.os=e,this.proc=e.procs.spawn({name:t.name,kind:`sandbox`,ppid:t.ppid,detail:t.network?`isolated worker · network allowed`:`isolated worker · no network`,onKill:()=>this.#o()});let n=this.#e=o(document.createElement(`iframe`));n.setAttribute(`sandbox`,`allow-scripts`),n.style.display=`none`,n.src=new URL(t.network?`sandbox-net.html`:`sandbox.html`,a).href,this.#t=new Promise((e,t)=>{let r=setTimeout(()=>t(Error(`sandbox failed to start`)),15e3),i=t=>{if(t.source===n.contentWindow){if(t.data?.type===`hello`){let t=new MessageChannel;t.port1.onmessage=n=>{n.data?.type===`ready`&&(clearTimeout(r),t.port1.onmessage=e=>this.#i.get(e.data.id)?.(e.data),e(t.port1))},n.contentWindow.postMessage({type:`boot`,src:u},`*`,[t.port2])}else t.data?.type===`crash`&&this.#a?.(String(t.data.error))}};addEventListener(`message`,i),this.proc.signal.addEventListener(`abort`,()=>{removeEventListener(`message`,i),clearTimeout(r),t(Error(`sandbox was killed`))})}),this.#t.catch(()=>void 0),document.body.append(n)}get alive(){return!this.#r}#o(){this.#r=!0,this.#e.remove()}dispose(){this.#r||this.os.procs.exit(this.proc.pid)}async run(e,t={}){let n=performance.now(),i=t.cwd??`/`,a=``,o=``,s=e=>{let t=performance.now()-n;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:a,stderr:o,ms:t,...e}},c;try{c=await this.#t}catch(e){return s({error:e.message})}let l=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(n=>{let u=(e,r=!1)=>{clearTimeout(m),this.#i.delete(l),this.#a=null,t.signal?.removeEventListener(`abort`,d),this.proc.signal.removeEventListener(`abort`,p),r?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),n(s(e))},d=()=>u({error:`aborted`},!0),p=()=>u({error:`sandbox was killed`}),m=setTimeout(()=>u({error:`timed out after ${t.timeoutMs??3e4} ms`,timedOut:!0},!0),t.timeoutMs??3e4);t.signal?.addEventListener(`abort`,d),this.proc.signal.addEventListener(`abort`,p),this.#a=e=>u({error:e},!0),this.#i.set(l,e=>{e.type===`stdout`?(a.length<f&&(a+=e.data),t.onStdout?.(e.data)):e.type===`stderr`?(o.length<f&&(o+=e.data),t.onStderr?.(e.data)):e.type===`progress`?t.onProgress?.({label:e.label,loaded:e.loaded,total:e.total}):e.type===`rpc`?this.#s(i,e.method,e.params).then(t=>c.postMessage({type:`rpc-result`,rid:e.rid,value:t}),t=>c.postMessage({type:`rpc-result`,rid:e.rid,error:t.message})):e.type===`done`&&(async()=>{if(e.error)return u({error:e.error});try{for(let t of e.result?.files??[])await this.os.fs.writeFile(r(i,t.path),t.data)}catch(e){return u({error:`could not write files back: ${e.message}`})}let t=e.result?.exitCode;u({ok:t===void 0||t===0,value:e.result?.value,exitCode:t,response:e.result?.response})})()}),c.postMessage({id:l,...e})})}async#s(e,t,n){let i=this.os.fs,a=(i=0)=>{if(typeof n[i]!=`string`)throw Error(`${t}: path must be a string`);return r(e,n[i])};switch(t){case`fs.readText`:return i.readText(a());case`fs.readFile`:return i.readFile(a());case`fs.writeFile`:return i.writeFile(a(),n[1]);case`fs.appendFile`:return i.appendFile(a(),n[1]);case`fs.readdir`:return i.readdir(a());case`fs.exists`:return i.exists(a());case`fs.mkdir`:return i.mkdir(a());case`fs.rm`:return i.rm(a(),{recursive:!0});case`fs.glob`:return i.glob(String(n[0]),e);default:throw Error(`unknown sandbox call: ${t}`)}}};async function m(e,t,n={}){let r=new p(e,{name:`js`,network:n.network,ppid:n.ppid});try{return await r.run({op:`js`,code:t,args:n.args,env:n.env},n)}finally{r.dispose()}}async function h(e,t,n={}){let r=new p(e,{name:n.name??`wasm`,ppid:n.ppid});try{return await r.run({op:`wasm`,wasm:t,args:n.args,stdin:n.stdin,name:n.name},n)}finally{r.dispose()}}var g=null,_=!1;async function v(){try{let e=await caches.open(l),t=await Promise.all(c.map(async t=>{let n=await e.match(s+t);return n?{path:t,data:new Uint8Array(await n.arrayBuffer())}:null}));return t.every(e=>e!==null)?t:void 0}catch{return}}async function y(e,t){let n=[],r=25165824;for await(let i of e.fs.walk(t,{maxDepth:6}))if(!(i.kind!==`file`||i.size>8388608||i.size>r)&&(r-=i.size,n.push({path:i.path.slice(t===`/`?1:t.length+1),data:await e.fs.readFile(i.path)}),n.length>=400))break;return n}async function b(e,t,n={}){g?.alive||(g=new p(e,{name:`python`,network:!1}),_=!1);let r=n.cwd??`/tmp`,i=await y(e,r),a=!_,o=a?await v():void 0,c=a?e.settings.get(d,[]):[],l=[...new Set([...c,...n.packages??[]])],u=await g.run({op:`python`,code:t,packages:l.length?l:void 0,files:i,pyodideUrl:s,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return _=g.alive&&!u.timedOut,u}var x=new Map;async function S(e,t,n,r,i={}){let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return x.get(n)?.dispose(),x.delete(n),a();if(t===`load`){x.get(n)?.dispose();let t=new p(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});x.set(n,t);let a=await t.run({op:`server-load`,code:r.code??``,env:r.env},{...i,timeoutMs:15e3});return a.ok||(t.dispose(),x.delete(n)),a}let o=x.get(n);return!o?.alive||!r.req?a(`backend not loaded`):o.run({op:`server-request`,req:r.req,origin:r.origin??`http://localhost`},{...i,timeoutMs:i.timeoutMs??3e4})}var C=`SharedWorker`in globalThis,w=n(i(location.search)),T=null;function E(){if(C)return new SharedWorker(new URL(new URL(`main-VEpSfsM_.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w}).port;T??=new Worker(new URL(new URL(`main-VEpSfsM_.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:w});let e=new MessageChannel;return T.postMessage({type:`connect`},[e.port2]),e.port1}var D=`bbx-window-${crypto.randomUUID()}`;navigator.locks?.request(D,()=>new Promise(()=>void 0));var O=new t(Promise.resolve({port:E(),lock:D,shared:C}),`host`),k=new Map;O.handle({"host.run":async(e,t,n,r)=>{let i=new AbortController;k.set(e,i);let a=await O.handle({}),o={...r,signal:i.signal,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t}),onProgress:t=>a.emit(`host:progress`,{runId:e,...t}),env:n.env};try{return t===`js`?await m(O,n.code,{...o,args:n.args,network:n.network,ppid:n.ppid}):t===`python`?await b(O,n.code,{...o,packages:n.packages}):await h(O,n.wasm,{...o,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid})}finally{k.delete(e)}},"host.backend":async(e,t,n,r,i)=>{let a=await O.handle({});return S(O,t,n,r,{...i,onStdout:t=>a.emit(`host:out`,{runId:e,s:`o`,t}),onStderr:t=>a.emit(`host:out`,{runId:e,s:`e`,t})})}}).then(e=>e.on(`host:abort`,e=>k.get(e)?.abort()));var A=new Set([location.origin,...e]),j=!1;addEventListener(`message`,e=>{if(!(e.source!==parent||e.data?.type!==`bbx:connect`||j)){if(!A.has(e.origin))return parent.postMessage({type:`bbx:refused`},e.origin);j=!0,parent.postMessage({type:`bbx:port`,lock:D,shared:C},e.origin,[E()])}}),parent!==window&&parent.postMessage({type:`bbx:ready`},`*`);
@@ -1,2 +1,2 @@
1
- import{S as e,_ as t,y as n}from"./main-DBKsMgp-.js";import{t as r}from"./bundle-rO6AXpFE.js";import{t as i}from"./html-DI-AyJM9.js";const a=/\.(tsx?|jsx|mts|cts)$/,o=/* @__PURE__ */ new Set([`package.json`,`package-lock.json`,`tsconfig.json`,`jsconfig.json`,`vite.config.ts`,`vite.config.js`,`AGENTS.md`,`CLAUDE.md`,`README.md`]),s=/* @__PURE__ */ new Set([`node_modules`,`.git`,`dist`,`.bbx`]);async function c(c,l){let u=/* @__PURE__ */ new Map,d=[],f=await c.readText(e(l,`package.json`)).then(e=>JSON.parse(e),()=>null),p=await c.readText(e(l,`tsconfig.json`)).then(e=>JSON.parse(e.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g,``).replace(/,(\s*[}\]])/g,`$1`)),()=>null),m={};for(let t of[`.env`,`.env.production`]){let n=await c.readText(e(l,t)).catch(()=>``);for(let e of n.split(`
1
+ import{S as e,_ as t,y as n}from"./main-VEpSfsM_.js";import{t as r}from"./bundle-8opp8__C.js";import{t as i}from"./html-R2xYS1Rp.js";const a=/\.(tsx?|jsx|mts|cts)$/,o=/* @__PURE__ */ new Set([`package.json`,`package-lock.json`,`tsconfig.json`,`jsconfig.json`,`vite.config.ts`,`vite.config.js`,`AGENTS.md`,`CLAUDE.md`,`README.md`]),s=/* @__PURE__ */ new Set([`node_modules`,`.git`,`dist`,`.bbx`]);async function c(c,l){let u=/* @__PURE__ */ new Map,d=[],f=await c.readText(e(l,`package.json`)).then(e=>JSON.parse(e),()=>null),p=await c.readText(e(l,`tsconfig.json`)).then(e=>JSON.parse(e.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g,``).replace(/,(\s*[}\]])/g,`$1`)),()=>null),m={};for(let t of[`.env`,`.env.production`]){let n=await c.readText(e(l,t)).catch(()=>``);for(let e of n.split(`
2
2
  `)){let t=/^\s*((?:VITE_|PUBLIC_)\w+)\s*=\s*(.*?)\s*$/.exec(e);t&&(m[t[1]]=t[2].replace(/^(['"])(.*)\1$/,`$2`))}}let h=e=>r({fs:c,root:l,entry:e,target:`browser`,production:!0,env:m,pkg:f,tsconfig:p}),g=[],_=async e=>{for(let t of await c.readdir(e).catch(()=>[]))t.name.startsWith(`.`)||s.has(t.name)||(t.kind===`dir`?await _(t.path):g.length<2e3&&g.push(t.path))};await _(l);let v=[`server.ts`,`server.js`,`server.mjs`].find(t=>g.includes(e(l,t)))??null,y=g.filter(e=>/\.html?$/i.test(e)),b=async(e,t)=>{let n=await i(c,{root:l,htmlPath:e,path:`/`,port:0,runtime:!1,bundle:h});d.push(...n.errors),u.set(t,new TextEncoder().encode(n.html))};if(y.length)for(let e of y)await b(e,e.slice(l.length));else await b(null,`/index.html`);for(let e of g){let r=t(e);y.includes(e)||a.test(e)||o.has(r)||r===v||n(e)===`css`&&e.includes(`/src/`)||u.set(e.slice(l.length),await c.readFile(e))}return{files:u,errors:d,backend:v}}export{c as buildSite};
@@ -1 +1 @@
1
- import{C as e,S as t,n,v as r,w as i,x as a,y as o}from"./main-DBKsMgp-.js";import{n as s,t as c}from"./npm-DF8ts_uH.js";const l=[`.tsx`,`.ts`,`.jsx`,`.js`,`.mjs`,`.cjs`,`.json`,`.css`],u=/\.(png|jpe?g|gif|webp|avif|bmp|ico|svg|woff2?|ttf|otf|eot|mp3|wav|ogg|mp4|webm|pdf)$/i,d=/\.(txt|md|html|glsl|wgsl|vert|frag|csv)$/i;function f(e,t){if(t===`raw`)return`text`;if(t===`url`||t===`inline`)return`dataurl`;let n=o(e);return e.endsWith(`.module.css`)?`local-css`:n===`css`?`css`:n===`ts`||n===`mts`||n===`cts`?`ts`:n===`tsx`?`tsx`:n===`js`||n===`jsx`||n===`mjs`||n===`cjs`?`jsx`:n===`json`?`json`:n===`wasm`?`binary`:d.test(e)?`text`:u.test(e)?`dataurl`:`text`}const p=e=>{let t=e.location?`${e.location.file.replace(/^vfs:/,``)}:${e.location.line}:${e.location.column+1}: `:``,n=e.location?.lineText?`\n ${e.location.lineText.trim()}`:``;return`${t}${e.text}${n}`};async function m(o){let{fs:u,root:d}=o,m=new c(o.pkg??null,o.target===`browser`&&!o.production),h=o.fetcher??fetch,g=/* @__PURE__ */ new Set,_=o.tsconfig?.compilerOptions?.paths??{},v=i(d,o.tsconfig?.compilerOptions?.baseUrl??`.`),y=m.versions,b=o.tsconfig?.compilerOptions?.jsxImportSource??(y.preact&&!y.react?`preact`:`react`),x=async e=>(await u.stat(e).catch(()=>null))?.kind===`file`;async function S(e){if(await x(e))return e;for(let t of l)if(await x(e+t))return e+t;if(/\.jsx?$/.test(e)){for(let t of[`.ts`,`.tsx`])if(await x(e.replace(/\.jsx?$/,t)))return e.replace(/\.jsx?$/,t)}for(let t of l)if(await x(`${e}/index${t}`))return`${e}/index${t}`;return null}function C(e){let n=[];for(let[t,r]of Object.entries(_)){let a=t.indexOf(`*`);if(a<0?e!==t:!(e.startsWith(t.slice(0,a))&&e.endsWith(t.slice(a+1))))continue;let o=a<0?``:e.slice(a,e.length-(t.length-a-1));for(let e of r)n.push(i(v,e.replace(`*`,o)))}return!n.length&&e.startsWith(`@/`)&&n.push(t(d,`src`,e.slice(2))),n}let w={name:`bbx`,setup(n){n.onResolve({filter:/.*/},async n=>{let[o,s=``]=n.path.split(`?`);if(n.namespace===`npm`||/^https?:\/\//.test(o)){let e=n.namespace===`npm`?n.importer:void 0;return/^(https?:)?\/\/|^\.{0,2}\//.test(n.path)?{path:m.canonical(new URL(n.path,e).href),namespace:`npm`}:{path:m.url(n.path),namespace:`npm`}}let c,l=n.importer?.startsWith(`/`)?r(n.importer):n.resolveDir||d;if(o.startsWith(`./`)||o.startsWith(`../`)||o===`.`||o===`..`)c=[i(l,o)];else if(o.startsWith(`/`))c=a(d,o)&&d!==`/`?[e(o)]:[t(d,o)];else if(c=C(o),!c.length)return{path:m.url(n.path),namespace:`npm`};for(let e of c){if(!a(d,e))return{errors:[{text:`${n.path} is outside the project folder (${d})`}]};let t=await S(e);if(t)return{path:t,namespace:`vfs`,pluginData:{query:s}}}return{errors:[{text:`Could not find "${n.path}"${n.importer?` (imported by ${n.importer})`:``}`}]}}),n.onLoad({filter:/.*/,namespace:`vfs`},async e=>(g.add(e.path),{contents:await u.readFile(e.path),loader:f(e.path,e.pluginData?.query??``),resolveDir:r(e.path)})),n.onLoad({filter:/.*/,namespace:`npm`},async e=>({contents:await s(e.path,h),loader:/\.css(\?|$)/.test(new URL(e.path).pathname)?`css`:`js`}))}},T={MODE:o.production?`production`:`development`,DEV:!o.production,PROD:!!o.production,SSR:o.target===`server`,BASE_URL:`/`,...o.env},E=o.entry;try{let e=await(await n()).build({...typeof E==`string`?{entryPoints:[E]}:{stdin:{contents:E.contents,resolveDir:E.dir,sourcefile:E.name,loader:`tsx`}},bundle:!0,write:!1,outdir:`/out`,format:o.target===`server`?`iife`:`esm`,globalName:o.target===`server`?`__bbxServer`:void 0,platform:`browser`,target:`es2022`,jsx:`automatic`,jsxImportSource:b,define:{"process.env.NODE_ENV":o.production?`"production"`:`"development"`,"import.meta.env":JSON.stringify(T),...Object.fromEntries(Object.entries(T).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)]))},minify:!!o.production,logLevel:`silent`,charset:`utf8`,plugins:[w]}),t=t=>e.outputFiles?.find(e=>e.path.endsWith(t))?.text??``;return{js:t(`.js`),css:t(`.css`),errors:[],warnings:e.warnings.map(p),inputs:[...g]}}catch(e){let t=e;return{js:``,css:``,errors:t.errors?.length?t.errors.map(p):[e.message??String(e)],warnings:(t.warnings??[]).map(p),inputs:[...g]}}}async function h(e,t){let n=``;for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return`data:${t};base64,${btoa(n)}`}export{h as n,m as t};
1
+ import{C as e,S as t,n,v as r,w as i,x as a,y as o}from"./main-VEpSfsM_.js";import{n as s,t as c}from"./npm-DF8ts_uH.js";const l=[`.tsx`,`.ts`,`.jsx`,`.js`,`.mjs`,`.cjs`,`.json`,`.css`],u=/\.(png|jpe?g|gif|webp|avif|bmp|ico|svg|woff2?|ttf|otf|eot|mp3|wav|ogg|mp4|webm|pdf)$/i,d=/\.(txt|md|html|glsl|wgsl|vert|frag|csv)$/i;function f(e,t){if(t===`raw`)return`text`;if(t===`url`||t===`inline`)return`dataurl`;let n=o(e);return e.endsWith(`.module.css`)?`local-css`:n===`css`?`css`:n===`ts`||n===`mts`||n===`cts`?`ts`:n===`tsx`?`tsx`:n===`js`||n===`jsx`||n===`mjs`||n===`cjs`?`jsx`:n===`json`?`json`:n===`wasm`?`binary`:d.test(e)?`text`:u.test(e)?`dataurl`:`text`}const p=e=>{let t=e.location?`${e.location.file.replace(/^vfs:/,``)}:${e.location.line}:${e.location.column+1}: `:``,n=e.location?.lineText?`\n ${e.location.lineText.trim()}`:``;return`${t}${e.text}${n}`};async function m(o){let{fs:u,root:d}=o,m=new c(o.pkg??null,o.target===`browser`&&!o.production),h=o.fetcher??fetch,g=/* @__PURE__ */ new Set,_=o.tsconfig?.compilerOptions?.paths??{},v=i(d,o.tsconfig?.compilerOptions?.baseUrl??`.`),y=m.versions,b=o.tsconfig?.compilerOptions?.jsxImportSource??(y.preact&&!y.react?`preact`:`react`),x=async e=>(await u.stat(e).catch(()=>null))?.kind===`file`;async function S(e){if(await x(e))return e;for(let t of l)if(await x(e+t))return e+t;if(/\.jsx?$/.test(e)){for(let t of[`.ts`,`.tsx`])if(await x(e.replace(/\.jsx?$/,t)))return e.replace(/\.jsx?$/,t)}for(let t of l)if(await x(`${e}/index${t}`))return`${e}/index${t}`;return null}function C(e){let n=[];for(let[t,r]of Object.entries(_)){let a=t.indexOf(`*`);if(a<0?e!==t:!(e.startsWith(t.slice(0,a))&&e.endsWith(t.slice(a+1))))continue;let o=a<0?``:e.slice(a,e.length-(t.length-a-1));for(let e of r)n.push(i(v,e.replace(`*`,o)))}return!n.length&&e.startsWith(`@/`)&&n.push(t(d,`src`,e.slice(2))),n}let w={name:`bbx`,setup(n){n.onResolve({filter:/.*/},async n=>{let[o,s=``]=n.path.split(`?`);if(n.namespace===`npm`||/^https?:\/\//.test(o)){let e=n.namespace===`npm`?n.importer:void 0;return/^(https?:)?\/\/|^\.{0,2}\//.test(n.path)?{path:m.canonical(new URL(n.path,e).href),namespace:`npm`}:{path:m.url(n.path),namespace:`npm`}}let c,l=n.importer?.startsWith(`/`)?r(n.importer):n.resolveDir||d;if(o.startsWith(`./`)||o.startsWith(`../`)||o===`.`||o===`..`)c=[i(l,o)];else if(o.startsWith(`/`))c=a(d,o)&&d!==`/`?[e(o)]:[t(d,o)];else if(c=C(o),!c.length)return{path:m.url(n.path),namespace:`npm`};for(let e of c){if(!a(d,e))return{errors:[{text:`${n.path} is outside the project folder (${d})`}]};let t=await S(e);if(t)return{path:t,namespace:`vfs`,pluginData:{query:s}}}return{errors:[{text:`Could not find "${n.path}"${n.importer?` (imported by ${n.importer})`:``}`}]}}),n.onLoad({filter:/.*/,namespace:`vfs`},async e=>(g.add(e.path),{contents:await u.readFile(e.path),loader:f(e.path,e.pluginData?.query??``),resolveDir:r(e.path)})),n.onLoad({filter:/.*/,namespace:`npm`},async e=>({contents:await s(e.path,h),loader:/\.css(\?|$)/.test(new URL(e.path).pathname)?`css`:`js`}))}},T={MODE:o.production?`production`:`development`,DEV:!o.production,PROD:!!o.production,SSR:o.target===`server`,BASE_URL:`/`,...o.env},E=o.entry;try{let e=await(await n()).build({...typeof E==`string`?{entryPoints:[E]}:{stdin:{contents:E.contents,resolveDir:E.dir,sourcefile:E.name,loader:`tsx`}},bundle:!0,write:!1,outdir:`/out`,format:o.target===`server`?`iife`:`esm`,globalName:o.target===`server`?`__bbxServer`:void 0,platform:`browser`,target:`es2022`,jsx:`automatic`,jsxImportSource:b,define:{"process.env.NODE_ENV":o.production?`"production"`:`"development"`,"import.meta.env":JSON.stringify(T),...Object.fromEntries(Object.entries(T).map(([e,t])=>[`import.meta.env.${e}`,JSON.stringify(t)]))},minify:!!o.production,logLevel:`silent`,charset:`utf8`,plugins:[w]}),t=t=>e.outputFiles?.find(e=>e.path.endsWith(t))?.text??``;return{js:t(`.js`),css:t(`.css`),errors:[],warnings:e.warnings.map(p),inputs:[...g]}}catch(e){let t=e;return{js:``,css:``,errors:t.errors?.length?t.errors.map(p):[e.message??String(e)],warnings:(t.warnings??[]).map(p),inputs:[...g]}}}async function h(e,t){let n=``;for(let t=0;t<e.length;t+=32768)n+=String.fromCharCode(...e.subarray(t,t+32768));return`data:${t};base64,${btoa(n)}`}export{h as n,m as t};
@@ -1,4 +1,4 @@
1
- import{i as e,r as t}from"./npm-DF8ts_uH.js";import{S as n,_ as r,l as i,u as a}from"./main-DBKsMgp-.js";function o(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=[];for(let i=0;i<e.length;i++){let a=e[i],o=/^--?([\w-]+)(?:=(.*))?$/.exec(a);o?o[2]===void 0?(o[1]===`port`||o[1]===`p`)&&e[i+1]&&/^\d+$/.test(e[i+1])?n.set(`port`,e[++i]):t.add(o[1]):n.set(o[1],o[2]):r.push(a)}return{flags:t,values:n,rest:r}}async function s(e,t){let r=e.os.fs,i=await r.readText(n(t,`index.html`)).catch(()=>null);return i===null||/<script[^>]+type\s*=\s*["']?module/i.test(i)?!0:(await r.glob(`**/*.{ts,tsx,jsx}`,t,1)).length>0||await r.exists(n(t,`package.json`))}const c={error:a.red,warn:a.yellow,info:a.cyan,log:``,debug:a.dim};function l(e){let t=new Date(e.t).toTimeString().slice(0,8);return`${a.dim}${t} ${e.source.padEnd(7)}${a.reset} ${c[e.level]}${e.text}${a.reset}\n`}async function u(e,t,n){let{os:r,out:o}=e;!r.packages.isInstalled(`esbuild`)&&await s(e,t)&&(o(`${a.dim}this project needs the bundler: installing esbuild${a.reset}\n`),await r.packages.install(`esbuild`,i(`esbuild`,o)),o(`
1
+ import{i as e,r as t}from"./npm-DF8ts_uH.js";import{S as n,_ as r,l as i,u as a}from"./main-VEpSfsM_.js";function o(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=[];for(let i=0;i<e.length;i++){let a=e[i],o=/^--?([\w-]+)(?:=(.*))?$/.exec(a);o?o[2]===void 0?(o[1]===`port`||o[1]===`p`)&&e[i+1]&&/^\d+$/.test(e[i+1])?n.set(`port`,e[++i]):t.add(o[1]):n.set(o[1],o[2]):r.push(a)}return{flags:t,values:n,rest:r}}async function s(e,t){let r=e.os.fs,i=await r.readText(n(t,`index.html`)).catch(()=>null);return i===null||/<script[^>]+type\s*=\s*["']?module/i.test(i)?!0:(await r.glob(`**/*.{ts,tsx,jsx}`,t,1)).length>0||await r.exists(n(t,`package.json`))}const c={error:a.red,warn:a.yellow,info:a.cyan,log:``,debug:a.dim};function l(e){let t=new Date(e.t).toTimeString().slice(0,8);return`${a.dim}${t} ${e.source.padEnd(7)}${a.reset} ${c[e.level]}${e.text}${a.reset}\n`}async function u(e,t,n){let{os:r,out:o}=e;!r.packages.isInstalled(`esbuild`)&&await s(e,t)&&(o(`${a.dim}this project needs the bundler: installing esbuild${a.reset}\n`),await r.packages.install(`esbuild`,i(`esbuild`,o)),o(`
2
2
  `));let c=await r.dev.start({root:t,port:n.port,network:n.network});return o(`\n ${a.green}${a.bold}serving${a.reset} ${c.root}\n`),o(` ${a.bold}➜${a.reset} ${a.cyan}${c.url}${a.reset} ${a.dim}opens in Preview${a.reset}\n`),c.backend&&o(` ${a.dim}backend${a.reset} ${c.backend}${c.network?` (network allowed)`:` (no network: serve --net to allow)`}\n`),o(` ${a.dim}npm packages load from esm.sh · files reload on save · serve logs ${c.port} · serve stop ${c.port}${a.reset}\n\n`),n.open!==!1&&r.openApp(`preview`,{dev:c.port}),c.port}const d={name:`serve`,summary:`dev server for a project folder: bundles TS/JSX, reloads on save, runs server.ts`,usage:`serve [dir] [--port N] [--net] [--no-open] | serve list | serve logs [port] | serve stop [port|all]`,async run(e){let{os:t,out:n}=e,{flags:r,values:i,rest:s}=o(e.args),[c]=s,d=await t.dev.list(),f=e=>{let t=e?Number(e):d.length===1?d[0].port:NaN;if(!Number.isFinite(t))throw Error(d.length?`which server? ${d.map(e=>e.port).join(`, `)}`:`nothing is being served`);return t};if(c===`list`||c===`ls`){if(!d.length)return n(`${a.dim}nothing is being served. Start one: serve [dir]${a.reset}\n`);for(let e of d)n(`${a.cyan}${e.url.padEnd(24)}${a.reset} ${e.root}${e.backend?` ${a.dim}backend ${e.backend}${a.reset}`:``}\n`);return}if(c===`stop`){let e=s[1]===`all`?d.map(e=>e.port):[f(s[1])];for(let r of e)n(await t.dev.stop(r)?`stopped :${r}\n`:`nothing on :${r}\n`);return}if(c===`logs`||c===`log`){let e=await t.dev.logs(f(s[1]),{limit:Number(i.get(`n`)??100)});e.length||n(`${a.dim}no output yet${a.reset}\n`);for(let t of e)n(l(t));return}if(c===`open`){t.openApp(`preview`,{dev:f(s[1])});return}let p=i.has(`port`)?Number(i.get(`port`)):void 0;if(p!==void 0&&!(p>0&&p<65536))throw Error(`--port must be a number between 1 and 65535`);await u(e,e.path(c??`.`),{port:p,network:r.has(`net`),open:!r.has(`no-open`)})}};async function f(e){let t=await e.os.fs.readText(n(e.shell.cwd,`package.json`)).catch(()=>null);if(t===null)return null;try{return JSON.parse(t)}catch(e){throw Error(`package.json is not valid JSON: ${e.message}`)}}const p=(e,t)=>e.os.fs.writeFile(n(e.shell.cwd,`package.json`),JSON.stringify(t,null,2)+`
3
3
  `),m=e=>({name:r(e.shell.cwd).toLowerCase().replace(/[^a-z0-9-_.]/g,`-`)||`app`,version:`0.1.0`,private:!0,type:`module`,scripts:{dev:`serve`},dependencies:{}});async function h(e){let t;try{t=await fetch(`https://registry.npmjs.org/${e.replace(`/`,`%2F`)}/latest`)}catch{throw Error(`could not reach the npm registry to look up ${e} (offline?)`)}if(t.status===404)throw Error(`no such package on npm: ${e}`);if(!t.ok)throw Error(`npm registry: HTTP ${t.status} for ${e}`);return(await t.json()).version}const g=/\b(vite|next|webpack|parcel|serve|http-server|live-server|react-scripts|astro|nuxt|svelte-kit)\b/,_={name:`npm`,summary:`manage package.json; npm run dev serves the project (packages load from esm.sh)`,usage:`npm init | npm install <pkg>[@version]… [-D] | npm uninstall <pkg>… | npm ls | npm run dev`,async run(r){let{out:i}=r,{flags:s,rest:c}=o(r.args),[l=`help`,...d]=c;switch(l){case`init`:return await f(r)?i(`package.json already exists
4
4
  `):(await p(r,m(r)),i(`wrote ${n(r.shell.cwd,`package.json`)}\n`));case`install`:case`i`:case`add`:{let n=await f(r)??m(r);if(!d.length)return i(`${a.dim}nothing to download: packages listed in package.json load from esm.sh when the app is bundled, and are cached after that.${a.reset}\n`);let o=s.has(`D`)||s.has(`save-dev`)?`devDependencies`:`dependencies`,c=n[o]??={};for(let n of d){let r=n.lastIndexOf(`@`),[o,s]=r>0?[n.slice(0,r),n.slice(r+1)]:[n,``];if(!e(o)[0])throw Error(`not a package name: ${n}`);let l=t(s)??await h(o);c[o]=`^${l}`,i(`${a.green}+${a.reset} ${o}@${l}\n`)}return await p(r,n),i(`${a.dim}saved to package.json · loaded from esm.sh when the app is bundled${a.reset}\n`)}case`uninstall`:case`remove`:case`rm`:case`un`:{let e=await f(r);if(!e)throw Error(`no package.json here`);for(let t of d){let n=!!(e.dependencies?.[t]??e.devDependencies?.[t]);delete e.dependencies?.[t],delete e.devDependencies?.[t],i(n?`${a.red}-${a.reset} ${t}\n`:`${t} was not a dependency\n`)}return p(r,e)}case`ls`:case`list`:{let e=await f(r),t={...e?.dependencies,...e?.devDependencies};if(!Object.keys(t).length)return i(`${a.dim}no dependencies${a.reset}\n`);for(let[e,n]of Object.entries(t))i(`${e}@${n}\n`);return}case`start`:case`run`:case`run-script`:{let e=l===`start`?`start`:d[0],t=await f(r);if(!e)return i(Object.entries(t?.scripts??{}).map(([e,t])=>` ${e}: ${t}\n`).join(``)||`${a.dim}no scripts${a.reset}\n`);let n=t?.scripts?.[e]??``;if([`dev`,`start`,`serve`,`preview`].includes(e)||g.test(n)){await u(r,r.shell.cwd,{open:!0});return}if(!n)throw Error(`no script "${e}" in package.json`);return i(`${a.dim}> ${n}${a.reset}\n`),r.shell.run(n,{out:r.out,err:r.err,signal:r.signal})}default:return i(`${_.usage}\n${a.dim}There is no node_modules here: dependencies are fetched from esm.sh and bundled by serve.${a.reset}\n`),l===`help`?0:1}}},v={name:`npx`,summary:`npx vite / serve / http-server start the dev server`,usage:`npx vite | npx serve [dir] | npx http-server [dir]`,async run(e){let[t,...n]=e.args;if(t&&/^(vite|serve|http-server|live-server)(@.*)?$/.test(t))await u(e,e.path(n.find(e=>!e.startsWith(`-`))??`.`),{open:!0});else throw Error(`npx ${t??``}: only dev servers are available here (npx vite, npx serve). Packages for your app go in package.json (npm install <pkg>).`)}};export{_ as npmCommand,v as npxCommand,d as serveCommand};
@@ -1,2 +1,2 @@
1
- import{S as e,b as t}from"./main-DBKsMgp-.js";const n=/* @__PURE__ */ new Set([`.git`,`node_modules`,`.bbx`,`.sessions`,`.DS_Store`]),r=5e3;function i(e){return e.split(`
1
+ import{S as e,b as t}from"./main-VEpSfsM_.js";const n=/* @__PURE__ */ new Set([`.git`,`node_modules`,`.bbx`,`.sessions`,`.DS_Store`]),r=5e3;function i(e){return e.split(`
2
2
  `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`)&&!e.startsWith(`!`)).map(e=>{let n=e.endsWith(`/`),r=e.replace(/\/$/,``).replace(/^\//,``),i=t(r.includes(`/`)?r:`**/${r}`),a=t(r);return(e,t)=>(!n||t)&&(i.test(`/`+e)||a.test(e)||i.test(e))})}async function a(t,a){let o=i(await t.readText(e(a,`.gitignore`)).catch(()=>``)),s=/* @__PURE__ */ new Map,c=0,l=async(e,i)=>{for(let a of await t.readdir(e).catch(()=>[])){let e=i?`${i}/${a.name}`:a.name;if(!(n.has(a.name)||o.some(t=>t(e,a.kind===`dir`)))){if(a.kind===`dir`)await l(a.path,e);else{if(s.size>=r)throw Error(`more than ${r} files: add a .gitignore for build output and dependencies`);let n=await t.readFile(a.path);if(c+=n.length,c>209715200)throw Error(`the folder is over 200 MB; leave large files out with .gitignore`);s.set(e,n)}}}};return await l(a,``),s}const o=e=>[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``),s=async e=>o(await crypto.subtle.digest(`SHA-1`,e));async function c(e){let t=new TextEncoder().encode(`blob ${e.length}\0`),n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),s(n)}function l(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}const u=e=>Uint8Array.from(atob(e.replace(/\s/g,``)),e=>e.charCodeAt(0));async function d(e,t,n){let r=Array(e.length),i=0;return await Promise.all(Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let t=i++;r[t]=await n(e[t])}})),r}var f=class extends Error{status;constructor(e,t){super(e),this.status=t}},p=class{token;fetcher;api;constructor(e,t=fetch,n=`https://api.github.com`){this.token=e,this.fetcher=t,this.api=n}async req(e,t,n){let r;try{r=await this.fetcher(`${this.api}${t}`,{method:e,headers:{authorization:`Bearer ${this.token}`,accept:`application/vnd.github+json`,"x-github-api-version":`2022-11-28`,...n?{"content-type":`application/json`}:{}},body:n?JSON.stringify(n):void 0})}catch{throw new f(`could not reach api.github.com (offline?)`,0)}if(r.status===204)return;let i=await r.json().catch(()=>({}));if(!r.ok){let e=i.errors?.map(e=>e.message).filter(Boolean).join(`; `),t=r.status===401?` (the token is invalid or expired: gh auth login)`:r.status===403||r.status===404?` (does the token have access to this repository, with Contents read and write?)`:``;throw new f(`GitHub: ${i.message??r.statusText}${e?`: ${e}`:``}${t}`,r.status)}return i}user(){return this.req(`GET`,`/user`)}repo(e){return this.req(`GET`,`/repos/${e}`)}createRepo(e,t={}){return this.req(`POST`,t.org?`/orgs/${t.org}/repos`:`/user/repos`,{name:e,private:!!t.private,description:t.description,auto_init:!0})}async#e(e,t){try{return(await this.req(`GET`,`/repos/${e}/git/ref/heads/${encodeURIComponent(t)}`)).object.sha}catch(e){if(e instanceof f&&(e.status===404||e.status===409))return null;throw e}}async push(e,t,n,r,i){let a=await this.repo(e),o=await this.#e(e,t);if(o||=await this.#e(e,a.default_branch),!o&&(await this.req(`PUT`,`/repos/${e}/contents/.gitkeep`,{message:`Initial commit`,content:``,branch:t}),o=await this.#e(e,t),!o))throw new f(`could not start the empty repository`,0);let s=await this.req(`GET`,`/repos/${e}/git/commits/${o}`),u=await this.req(`GET`,`/repos/${e}/git/trees/${s.tree.sha}?recursive=1`),p=new Map(u.tree.filter(e=>e.type===`blob`).map(e=>[e.path,e])),m=await Promise.all([...n].map(async([e,t])=>({path:e,data:t,sha:await c(t)}))),h=m.filter(e=>p.get(e.path)?.sha!==e.sha),g=0;await d(h,6,async t=>{if((await this.req(`POST`,`/repos/${e}/git/blobs`,{content:l(t.data),encoding:`base64`})).sha!==t.sha)throw new f(`checksum mismatch for ${t.path}`,0);i?.(`uploaded ${++g}/${h.length} ${t.path}`)});let _=[...p.keys()].filter(e=>!n.has(e)&&!u.truncated);if(!h.length&&!_.length)return null;let v=await this.req(`POST`,`/repos/${e}/git/trees`,{tree:m.map(e=>({path:e.path,mode:p.get(e.path)?.mode===`100755`?`100755`:`100644`,type:`blob`,sha:e.sha}))}),y=await this.req(`POST`,`/repos/${e}/git/commits`,{message:r,tree:v.sha,parents:[o]});await this.#e(e,t)?await this.req(`PATCH`,`/repos/${e}/git/refs/heads/${encodeURIComponent(t)}`,{sha:y.sha}):await this.req(`POST`,`/repos/${e}/git/refs`,{ref:`refs/heads/${t}`,sha:y.sha});let b=h.filter(e=>!p.has(e.path)).length;return{sha:y.sha,url:y.html_url,added:b,changed:h.length-b,removed:_.length}}async clone(e,t,n){let r=await this.repo(e),i=t??r.default_branch,a=await this.#e(e,i);if(!a)return{files:/* @__PURE__ */ new Map,branch:i};let o=await this.req(`GET`,`/repos/${e}/git/commits/${a}`),s=(await this.req(`GET`,`/repos/${e}/git/trees/${o.tree.sha}?recursive=1`)).tree.filter(e=>e.type===`blob`);if(s.length>3e3)throw new f(`${e} has ${s.length} files; that is too many to fetch one by one`,0);let c=/* @__PURE__ */ new Map,l=0;return await d(s,8,async t=>{let r=await this.req(`GET`,`/repos/${e}/git/blobs/${t.sha}`);c.set(t.path,u(r.content)),n?.(`${++l}/${s.length} ${t.path}`)}),{files:c,branch:i}}createPr(e,t){return this.repo(e).then(n=>this.req(`POST`,`/repos/${e}/pulls`,{head:t.head,base:t.base??n.default_branch,title:t.title,body:t.body??``,draft:!!t.draft}))}async enablePages(e,t){try{await this.req(`POST`,`/repos/${e}/pages`,{source:{branch:t,path:`/`}})}catch(n){if(!(n instanceof f&&(n.status===409||n.status===422)))throw n;await this.req(`PUT`,`/repos/${e}/pages`,{source:{branch:t,path:`/`}})}return(await this.req(`GET`,`/repos/${e}/pages`)).html_url}};export{p as GitHub,d as n,s as r,a as t};
@@ -1,4 +1,4 @@
1
- import{C as e,S as t,_ as n,v as r,w as i,x as a,y as o}from"./main-DBKsMgp-.js";import{n as s}from"./bundle-rO6AXpFE.js";const c={js:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,jsx:`JavaScript (JSX)`,ts:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,tsx:`TypeScript (TSX)`,py:`Python`,json:`JSON`,jsonl:`JSON Lines`,css:`CSS`,scss:`SCSS`,less:`Less`,html:`HTML`,htm:`HTML`,xml:`XML`,svg:`SVG`,md:`Markdown`,markdown:`Markdown`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,yml:`YAML`,yaml:`YAML`,toml:`TOML`,ini:`INI`,csv:`CSV`,tsv:`TSV`,sql:`SQL`,rs:`Rust`,go:`Go`,c:`C`,h:`C`,cpp:`C++`,cc:`C++`,hpp:`C++`,java:`Java`,kt:`Kotlin`,rb:`Ruby`,php:`PHP`,swift:`Swift`,lua:`Lua`,r:`R`,wat:`WebAssembly Text`,vue:`Vue`,svelte:`Svelte`,txt:`Plain Text`,log:`Log`},l=/* @__PURE__ */ new Set([`txt`,`log`,`csv`,`tsv`,`env`,`conf`,`cfg`,`gitignore`,`gitattributes`,`editorconfig`,`lock`,`properties`,`rst`,`tex`,`diff`,`patch`]),u=/* @__PURE__ */ new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`ico`]),d=/* @__PURE__ */ new Set([`mp3`,`wav`,`ogg`,`oga`,`flac`,`m4a`,`aac`,`opus`]),f=/* @__PURE__ */ new Set([`mp4`,`webm`,`ogv`,`mov`,`m4v`]),p=/* @__PURE__ */ new Set([`zip`,`tar`,`gz`,`tgz`,`bz2`,`xz`,`7z`,`rar`]);function m(e,t=!1){if(t)return`dir`;let r=o(e);return r===`md`||r===`markdown`?`markdown`:r===`html`||r===`htm`?`html`:r===`svg`?`svg`:r===`pdf`?`pdf`:u.has(r)?`image`:d.has(r)?`audio`:f.has(r)?`video`:p.has(r)?`archive`:l.has(r)?`text`:r in c?`code`:!r||n(e).startsWith(`.`)?`text`:`binary`}function h(e){let t=m(e);return t===`text`||t===`code`||t===`markdown`}const g={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,bmp:`image/bmp`,ico:`image/x-icon`,svg:`image/svg+xml`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,oga:`audio/ogg`,flac:`audio/flac`,m4a:`audio/mp4`,aac:`audio/aac`,opus:`audio/ogg`,mp4:`video/mp4`,webm:`video/webm`,ogv:`video/ogg`,mov:`video/quicktime`,m4v:`video/mp4`,pdf:`application/pdf`,html:`text/html`,htm:`text/html`,css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,json:`application/json`,md:`text/markdown`,txt:`text/plain`,csv:`text/csv`,xml:`application/xml`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,wasm:`application/wasm`};function _(e){return g[o(e)]??(h(e)?`text/plain`:`application/octet-stream`)}var v=`// BrowserBox dev runtime. Injected as the first script of every page Preview
1
+ import{C as e,S as t,_ as n,v as r,w as i,x as a,y as o}from"./main-VEpSfsM_.js";import{n as s}from"./bundle-8opp8__C.js";const c={js:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,jsx:`JavaScript (JSX)`,ts:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,tsx:`TypeScript (TSX)`,py:`Python`,json:`JSON`,jsonl:`JSON Lines`,css:`CSS`,scss:`SCSS`,less:`Less`,html:`HTML`,htm:`HTML`,xml:`XML`,svg:`SVG`,md:`Markdown`,markdown:`Markdown`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,yml:`YAML`,yaml:`YAML`,toml:`TOML`,ini:`INI`,csv:`CSV`,tsv:`TSV`,sql:`SQL`,rs:`Rust`,go:`Go`,c:`C`,h:`C`,cpp:`C++`,cc:`C++`,hpp:`C++`,java:`Java`,kt:`Kotlin`,rb:`Ruby`,php:`PHP`,swift:`Swift`,lua:`Lua`,r:`R`,wat:`WebAssembly Text`,vue:`Vue`,svelte:`Svelte`,txt:`Plain Text`,log:`Log`},l=/* @__PURE__ */ new Set([`txt`,`log`,`csv`,`tsv`,`env`,`conf`,`cfg`,`gitignore`,`gitattributes`,`editorconfig`,`lock`,`properties`,`rst`,`tex`,`diff`,`patch`]),u=/* @__PURE__ */ new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`ico`]),d=/* @__PURE__ */ new Set([`mp3`,`wav`,`ogg`,`oga`,`flac`,`m4a`,`aac`,`opus`]),f=/* @__PURE__ */ new Set([`mp4`,`webm`,`ogv`,`mov`,`m4v`]),p=/* @__PURE__ */ new Set([`zip`,`tar`,`gz`,`tgz`,`bz2`,`xz`,`7z`,`rar`]);function m(e,t=!1){if(t)return`dir`;let r=o(e);return r===`md`||r===`markdown`?`markdown`:r===`html`||r===`htm`?`html`:r===`svg`?`svg`:r===`pdf`?`pdf`:u.has(r)?`image`:d.has(r)?`audio`:f.has(r)?`video`:p.has(r)?`archive`:l.has(r)?`text`:r in c?`code`:!r||n(e).startsWith(`.`)?`text`:`binary`}function h(e){let t=m(e);return t===`text`||t===`code`||t===`markdown`}const g={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,bmp:`image/bmp`,ico:`image/x-icon`,svg:`image/svg+xml`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,oga:`audio/ogg`,flac:`audio/flac`,m4a:`audio/mp4`,aac:`audio/aac`,opus:`audio/ogg`,mp4:`video/mp4`,webm:`video/webm`,ogv:`video/ogg`,mov:`video/quicktime`,m4v:`video/mp4`,pdf:`application/pdf`,html:`text/html`,htm:`text/html`,css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,json:`application/json`,md:`text/markdown`,txt:`text/plain`,csv:`text/csv`,xml:`application/xml`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,wasm:`application/wasm`};function _(e){return g[o(e)]??(h(e)?`text/plain`:`application/octet-stream`)}var v=`// BrowserBox dev runtime. Injected as the first script of every page Preview
2
2
  // serves from a dev server. The page runs in an opaque-origin frame, so this
3
3
  // connects it to the virtual server through its parent:
4
4
  // - fetch() and XMLHttpRequest to the page's own address are answered by the
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-XKyaHtl9.js";function t(e){return{connect(t){let{peer:n}=t,r=/* @__PURE__ */ new Map,i=e=>{let t=r.get(e);if(!t)throw Error(`not attached to agent session ${e}`);return t},a=e=>{r.get(e.sid)?.detach(),r.set(e.sid,e);let i=null,a,o=()=>{clearTimeout(a),a=void 0,i&&n.emit(`agent`,{sid:e.sid,event:i}),i=null};return e.onEvent(t=>{t.type===`text`||t.type===`thinking`?(i&&i.type!==t.type&&o(),i?i.delta+=t.delta:i={type:t.type,delta:t.delta},a??=setTimeout(o,33)):(o(),n.emit(`agent`,{sid:e.sid,event:t}))}),e.onAsk((n,r)=>t.ask({kind:`user`,sid:e.sid,payload:{question:n,options:r}},void 0,!0)),e.prompter=(n,r)=>t.ask({kind:`perm`,sid:e.sid,payload:n},r).catch(()=>`deny`),{sid:e.sid,pid:e.pid}};return{handlers:{"agent.create":async t=>a(await e.agents.create(t)),"agent.attach":async t=>a(await e.agents.attach(t)),"agent.live":()=>e.agents.live(),"agent.probeModels":(t,n)=>e.agents.probeModels(t,n),"agent.send":(e,t,n)=>i(e).send(t,n),"agent.rewind":(e,t,n)=>i(e).rewind(t,n),"agent.changes":e=>i(e).changes(),"agent.stop":e=>i(e).stop(),"agent.snapshot":e=>i(e).snapshot(),"agent.context":e=>i(e).context(),"agent.compact":e=>i(e).compact(),"agent.probeMcp":t=>e.agents.probeMcp(t),"agent.detach":e=>{r.get(e)?.detach(),r.delete(e)},"agent.dispose":e=>{r.get(e)?.dispose(),r.delete(e)}},drop(){for(let e of r.values())e.detach()}}}}}const n=`/home/user`,r=`/home/agent`;function i(e,t,n,r){return{name:e,summary:t,usage:n,run:async e=>(await r()).run(e)}}const a=i(`serve`,`dev server for a project folder: bundles TS/JSX, reloads on save, runs server.ts`,`serve [dir] [--port N] [--net] [--no-open] | serve list | serve logs [port] | serve stop [port|all]`,()=>import(`./dev-impl-CfwRFPRf.js`).then(e=>e.serveCommand)),o=i(`npm`,`manage package.json; npm run dev serves the project (packages load from esm.sh)`,`npm init | npm install <pkg>[@version]… [-D] | npm uninstall <pkg>… | npm ls | npm run dev`,()=>import(`./dev-impl-CfwRFPRf.js`).then(e=>e.npmCommand)),s=i(`npx`,`npx vite / serve / http-server start the dev server`,`npx vite | npx serve [dir] | npx http-server [dir]`,()=>import(`./dev-impl-CfwRFPRf.js`).then(e=>e.npxCommand));let c=null;function l(){return typeof navigator<`u`&&`gpu`in navigator}function u(){return c??=(async()=>{if(!l())throw Error(`WebGPU is not available in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`No WebGPU adapter found`);let t=await e.requestDevice();return t.lost.then(()=>c=null),t})().catch(e=>{throw c=null,e})}const d=16777216;async function f(e){if(!Number.isInteger(e.outputLength)||e.outputLength<1||e.outputLength>d)throw Error(`outputLength must be 1..${d}`);if(e.input.length>d)throw Error(`input is limited to ${d} elements`);let t=await u(),n=performance.now();t.pushErrorScope(`validation`);let r=!0,i=t.createShaderModule({code:e.wgsl}),a=(await i.getCompilationInfo()).messages.filter(e=>e.type===`error`);if(a.length)throw t.popErrorScope(),r=!1,Error(`WGSL compile error:
1
+ import{n as e}from"./rolldown-runtime-XKyaHtl9.js";function t(e){return{connect(t){let{peer:n}=t,r=/* @__PURE__ */ new Map,i=e=>{let t=r.get(e);if(!t)throw Error(`not attached to agent session ${e}`);return t},a=e=>{r.get(e.sid)?.detach(),r.set(e.sid,e);let i=null,a,o=()=>{clearTimeout(a),a=void 0,i&&n.emit(`agent`,{sid:e.sid,event:i}),i=null};return e.onEvent(t=>{t.type===`text`||t.type===`thinking`?(i&&i.type!==t.type&&o(),i?i.delta+=t.delta:i={type:t.type,delta:t.delta},a??=setTimeout(o,33)):(o(),n.emit(`agent`,{sid:e.sid,event:t}))}),e.onAsk((n,r)=>t.ask({kind:`user`,sid:e.sid,payload:{question:n,options:r}},void 0,!0)),e.prompter=(n,r)=>t.ask({kind:`perm`,sid:e.sid,payload:n},r).catch(()=>`deny`),{sid:e.sid,pid:e.pid}};return{handlers:{"agent.create":async t=>a(await e.agents.create(t)),"agent.attach":async t=>a(await e.agents.attach(t)),"agent.live":()=>e.agents.live(),"agent.probeModels":(t,n)=>e.agents.probeModels(t,n),"agent.send":(e,t,n)=>i(e).send(t,n),"agent.rewind":(e,t,n)=>i(e).rewind(t,n),"agent.changes":e=>i(e).changes(),"agent.stop":e=>i(e).stop(),"agent.snapshot":e=>i(e).snapshot(),"agent.context":e=>i(e).context(),"agent.compact":e=>i(e).compact(),"agent.probeMcp":t=>e.agents.probeMcp(t),"agent.detach":e=>{r.get(e)?.detach(),r.delete(e)},"agent.dispose":e=>{r.get(e)?.dispose(),r.delete(e)}},drop(){for(let e of r.values())e.detach()}}}}}const n=`/home/user`,r=`/home/agent`;function i(e,t,n,r){return{name:e,summary:t,usage:n,run:async e=>(await r()).run(e)}}const a=i(`serve`,`dev server for a project folder: bundles TS/JSX, reloads on save, runs server.ts`,`serve [dir] [--port N] [--net] [--no-open] | serve list | serve logs [port] | serve stop [port|all]`,()=>import(`./dev-impl-BRiXVAGb.js`).then(e=>e.serveCommand)),o=i(`npm`,`manage package.json; npm run dev serves the project (packages load from esm.sh)`,`npm init | npm install <pkg>[@version]… [-D] | npm uninstall <pkg>… | npm ls | npm run dev`,()=>import(`./dev-impl-BRiXVAGb.js`).then(e=>e.npmCommand)),s=i(`npx`,`npx vite / serve / http-server start the dev server`,`npx vite | npx serve [dir] | npx http-server [dir]`,()=>import(`./dev-impl-BRiXVAGb.js`).then(e=>e.npxCommand));let c=null;function l(){return typeof navigator<`u`&&`gpu`in navigator}function u(){return c??=(async()=>{if(!l())throw Error(`WebGPU is not available in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`No WebGPU adapter found`);let t=await e.requestDevice();return t.lost.then(()=>c=null),t})().catch(e=>{throw c=null,e})}const d=16777216;async function f(e){if(!Number.isInteger(e.outputLength)||e.outputLength<1||e.outputLength>d)throw Error(`outputLength must be 1..${d}`);if(e.input.length>d)throw Error(`input is limited to ${d} elements`);let t=await u(),n=performance.now();t.pushErrorScope(`validation`);let r=!0,i=t.createShaderModule({code:e.wgsl}),a=(await i.getCompilationInfo()).messages.filter(e=>e.type===`error`);if(a.length)throw t.popErrorScope(),r=!1,Error(`WGSL compile error:
2
2
  `+a.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join(`
3
3
  `));let o=new Float32Array(Math.max(1,e.input.length));o.set(e.input);let s=t.createBuffer({size:o.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});t.queue.writeBuffer(s,0,o);let c=e.outputLength*4,l=t.createBuffer({size:c,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),f=t.createBuffer({size:c,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});try{let a=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]}),o=await t.createComputePipelineAsync({layout:t.createPipelineLayout({bindGroupLayouts:[a]}),compute:{module:i,entryPoint:`main`}}),u=t.createBindGroup({layout:a,entries:[{binding:0,resource:{buffer:s}},{binding:1,resource:{buffer:l}}]}),d=t.createCommandEncoder(),p=d.beginComputePass();p.setPipeline(o),p.setBindGroup(0,u);let[m,h=1,g=1]=e.workgroups??[Math.ceil(e.outputLength/64)],ee=t.limits.maxComputeWorkgroupsPerDimension;if(Math.max(m,h,g)>ee)throw Error(`dispatch of ${Math.max(m,h,g)} workgroups exceeds the device limit of ${ee} per dimension; use a larger @workgroup_size or a 2D dispatch via workgroups`);p.dispatchWorkgroups(m,h,g),p.end(),d.copyBufferToBuffer(l,0,f,0,c),t.queue.submit([d.finish()]),r=!1;let _=await t.popErrorScope();if(_)throw Error(`WebGPU validation error: ${_.message}`);await f.mapAsync(GPUMapMode.READ);let v=new Float32Array(f.getMappedRange().slice(0));return f.unmap(),{output:v,ms:performance.now()-n}}finally{r&&t.popErrorScope().catch(()=>null),s.destroy(),l.destroy(),f.destroy()}}function p(e){let t=[];for(let n of e.split(`/`))n&&n!==`.`&&(n===`..`?t.pop():t.push(n));return`/`+t.join(`/`)}function m(e,t){return p(t?t.startsWith(`/`)?t:`${e}/${t}`:e)}function h(e){let t=p(e),n=t.lastIndexOf(`/`);return n<=0?`/`:t.slice(0,n)}function g(e){let t=p(e);return t.slice(t.lastIndexOf(`/`)+1)}function ee(e){let t=g(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n+1).toLowerCase()}function _(...e){return p(e.join(`/`))}function v(e,t){let n=p(e),r=p(t);return n===`/`||r===n||r.startsWith(n+`/`)}function te(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];r===`*`?e[n+1]===`*`?(n++,e[n+1]===`/`?(n++,t+=`(?:.*/)?`):t+=`.*`):t+=`[^/]*`:t+=r===`?`?`[^/]`:r===`{`?`(?:`:r===`}`?`)`:r===`,`?`|`:/[.+^$()|[\]\\]/.test(r)?`\\${r}`:r}return RegExp(`^${t}$`)}const y={BASE_URL:`./`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1},b=e=>new URL(e,globalThis.location?.href??`http://localhost/`).href,x=y.VITE_KERNEL_URL||b(`../kernel/`),ne=y.VITE_AGENT_URL||b(`../agent/`);y.VITE_DOCS_URL||b(`../docs/`),y.VITE_OS_URL||b(`../os/`);const re=y.VITE_PREVIEW_URL||b(`../preview/`);new URL(`frame.html`,re).href;const ie=(y.VITE_ALLOWED_ORIGINS||``).split(`,`).map(e=>e.trim()).filter(Boolean);y.VITE_EMBED_ORIGINS?y.VITE_EMBED_ORIGINS.split(`,`).map(e=>e.trim()).filter(Boolean):ie.length;function ae(e,t){return globalThis.crossOriginIsolated&&e.setAttribute(`credentialless`,``),e}const S=`https://cdn.jsdelivr.net/pyodide/v0.29.0/full/`,oe=[`pyodide.js`,`pyodide.asm.js`,`pyodide.asm.wasm`,`python_stdlib.zip`,`pyodide-lock.json`],C=`bbx-packs`;var se=`// BrowserBox sandbox runtime. This file is shipped as text and started as a
4
4
  // Worker inside an opaque-origin iframe, so it must stay dependency-free JS.
@@ -344,12 +344,12 @@ async function runWasi(m, out, err) {
344
344
  `)}},{name:`wc`,summary:`count lines, words and bytes (Rust/WASM)`,usage:`wc [-l] [file…]`,async run(e){let{opts:t,rest:n}=k(e.args),r=new TextEncoder().encode(await L(e,n)),i=e.os.kcore.wc(r);e.out(t.has(`l`)?`${i.lines}\n`:`${String(i.lines).padStart(7)} ${String(i.words).padStart(7)} ${String(i.bytes).padStart(7)}\n`)}},{name:`sort`,summary:`sort lines`,usage:`sort [-r] [-n] [-u] [file…]`,async run(e){let{opts:t,rest:n}=k(e.args),r=R(await L(e,n));r.sort(t.has(`n`)?(e,t)=>parseFloat(e)-parseFloat(t):void 0),t.has(`r`)&&r.reverse(),t.has(`u`)&&(r=[...new Set(r)]),r.length&&e.out(r.join(`
345
345
  `)+`
346
346
  `)}},{name:`uniq`,summary:`drop adjacent duplicate lines`,usage:`uniq [-c] [file…]`,async run(e){let{opts:t,rest:n}=k(e.args),r=[];for(let t of R(await L(e,n))){let e=r.at(-1);e&&e[0]===t?e[1]++:r.push([t,1])}for(let[n,i]of r)e.out(t.has(`c`)?`${String(i).padStart(7)} ${n}\n`:`${n}\n`)}},{name:`tee`,summary:`copy stdin to files and stdout`,usage:`tee [-a] file…`,async run(e){let{opts:t,rest:n}=k(e.args);for(let r of n)await(t.has(`a`)?e.os.fs.appendFile(e.path(r),e.stdin):e.os.fs.writeFile(e.path(r),e.stdin));e.out(e.stdin)}},{name:`sha256sum`,summary:`SHA-256 digest (Web Crypto)`,usage:`sha256sum [file…]`,async run(e){let t=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,e))].map(e=>e.toString(16).padStart(2,`0`)).join(``);if(!e.args.length)return void e.out(`${await t(new TextEncoder().encode(e.stdin))} -\n`);for(let n of e.args)e.out(`${await t(await e.os.fs.readFile(e.path(n)))} ${n}\n`)}},{name:`hash`,summary:`fast FNV-1a content hash (Rust/WASM)`,usage:`hash file…`,async run(e){for(let t of e.args)e.out(`${e.os.kcore.hash(await e.os.fs.readFile(e.path(t)))} ${t}\n`)}},{name:`gzip`,summary:`compress a file to file.gz (Compression Streams)`,usage:`gzip file…`,async run(e){if(!(`CompressionStream`in globalThis))throw Error(`Compression Streams are not supported in this browser`);for(let t of e.args){let n=e.path(t);await e.os.fs.writeFile(n+`.gz`,await Be(await e.os.fs.readFile(n),new CompressionStream(`gzip`))),await e.os.fs.rm(n)}}},{name:`gunzip`,summary:`decompress file.gz`,usage:`gunzip file.gz…`,async run(e){if(!(`DecompressionStream`in globalThis))throw Error(`Compression Streams are not supported in this browser`);for(let t of e.args){let n=e.path(t);if(!n.endsWith(`.gz`))throw Error(`${t}: unknown suffix`);await e.os.fs.writeFile(n.slice(0,-3),await Be(await e.os.fs.readFile(n),new DecompressionStream(`gzip`))),await e.os.fs.rm(n)}}}],He=[];function Ue(...e){for(let t of e)He.some(e=>e.name===t.name)||He.push(t)}function We(e){return e.register(...ke,...Ve,...Re,...Te,Pe,Fe,a,o,s,...He)}function z(e){return e}const B=(e,t=[])=>({type:`object`,properties:e,required:t,additionalProperties:!1});function V(e,t=3e4){if(e.length<=t)return e;let n=Math.floor(t*.7);return`${e.slice(0,n)}\n\n… [${e.length-t} characters omitted] …\n\n${e.slice(e.length-(t-n))}`}const Ge=e=>`mcp.${e}.token`,Ke=`2025-06-18`;var qe=class{url;token;#e=1;#t=null;#n=null;constructor(e,t){this.url=e,this.token=t}async#r(e,t){let n;try{n=await fetch(this.url,{method:`POST`,signal:t,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,...this.#n?{"mcp-protocol-version":Ke}:{},...this.#t?{"mcp-session-id":this.#t}:{},...this.token?{authorization:`Bearer ${this.token}`}:{}},body:JSON.stringify(e)})}catch(e){throw t?.aborted?e:Error(`Could not reach ${new URL(this.url).host}. The server is down or does not allow requests from browsers (CORS).`)}if(n.status===401||n.status===403)throw Error(`${new URL(this.url).host} rejected the credentials (HTTP ${n.status}). Check the token.`);if(!n.ok)throw Error(`${new URL(this.url).host} answered HTTP ${n.status}: ${(await n.text().catch(()=>``)).slice(0,200)}`);return n}async#i(e,t,n){let r=this.#e++,i=await this.#r({jsonrpc:`2.0`,id:r,method:e,...t?{params:t}:{}},n);this.#t=i.headers.get(`mcp-session-id`)??this.#t;let a;if((i.headers.get(`content-type`)??``).includes(`text/event-stream`)){let e=i.body.pipeThrough(new TextDecoderStream).getReader(),t=``;outer:for(;;){let{value:n,done:i}=await e.read();if(i)break;t+=n;let o;for(;(o=t.search(/\r?\n\r?\n/))>=0;){let n=t.slice(0,o);t=t.slice(o).replace(/^\r?\n\r?\n/,``);let i=n.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).join(`
347
- `);if(!i)continue;let s=JSON.parse(i);if(s.id===r){a=s,e.cancel();break outer}}}}else a=await i.json();if(!a)throw Error(`no reply to ${e}`);if(a.error)throw Error(`${e} failed: ${a.error.message}`);return a.result}init(e){return this.#n??=(async()=>{await this.#i(`initialize`,{protocolVersion:Ke,capabilities:{},clientInfo:{name:`BrowserBox`,version:`0.1.0`}},e),await this.#r({jsonrpc:`2.0`,method:`notifications/initialized`},e)})().catch(e=>{throw this.#n=null,e})}async listTools(e){await this.init(e);let t=[],n;do{let r=await this.#i(`tools/list`,n?{cursor:n}:void 0,e);t.push(...r.tools),n=r.nextCursor}while(n&&t.length<500);return t}async callTool(e,t,n){await this.init(n);let r=await this.#i(`tools/call`,{name:e,arguments:t},n),i=(r.content??[]).map(e=>e.type===`text`?e.text??``:`[${e.type}${e.mimeType?` ${e.mimeType}`:``}]`).join(`
347
+ `);if(!i)continue;let s=JSON.parse(i);if(s.id===r){a=s,e.cancel();break outer}}}}else a=await i.json();if(!a)throw Error(`no reply to ${e}`);if(a.error)throw Error(`${e} failed: ${a.error.message}`);return a.result}init(e){return this.#n??=(async()=>{await this.#i(`initialize`,{protocolVersion:Ke,capabilities:{},clientInfo:{name:`BrowserBox`,version:`0.1.1`}},e),await this.#r({jsonrpc:`2.0`,method:`notifications/initialized`},e)})().catch(e=>{throw this.#n=null,e})}async listTools(e){await this.init(e);let t=[],n;do{let r=await this.#i(`tools/list`,n?{cursor:n}:void 0,e);t.push(...r.tools),n=r.nextCursor}while(n&&t.length<500);return t}async callTool(e,t,n){await this.init(n);let r=await this.#i(`tools/call`,{name:e,arguments:t},n),i=(r.content??[]).map(e=>e.type===`text`?e.text??``:`[${e.type}${e.mimeType?` ${e.mimeType}`:``}]`).join(`
348
348
  `);if(r.isError)throw Error(i||`the tool reported an error`);return i||`(no output)`}};const Je=e=>e.replace(/[^a-zA-Z0-9_-]/g,`_`);var Ye=class{os;#e=/* @__PURE__ */ new Map;errors=/* @__PURE__ */ new Map;constructor(e){this.os=e}servers(){return this.os.settings.get(`mcp.servers`,[])}async#t(e){let t=await this.os.secrets.get(Ge(e.name)),n=`${e.url}\n${t??``}`,r=this.#e.get(e.name);return r?.key===n?{client:r.client,fresh:!1,key:n}:{client:new qe(e.url,t),fresh:!0,key:n}}async tools(){let e=[];for(let t of this.servers().filter(e=>e.enabled&&e.via===`direct`)){let{client:n,fresh:r,key:i}=await this.#t(t);if(r){let e=n.listTools().then(e=>e.map(e=>({name:`mcp__${Je(t.name)}__${Je(e.name)}`.slice(0,64),description:`[${t.name} connector] ${e.description??e.name}`,input_schema:{type:`object`,properties:e.inputSchema?.properties??{},required:e.inputSchema?.required??[]},cap:()=>`net`,describe:n=>`${t.name}: ${e.name} ${JSON.stringify(n).slice(0,300)}`,run:async(t,r)=>V(await n.callTool(e.name,t,r.signal))})));this.#e.set(t.name,{key:i,client:n,tools:e})}try{e.push(...await this.#e.get(t.name).tools),this.errors.delete(t.name)}catch(e){let n=e.message;this.errors.get(t.name)!==n&&this.os.notify({title:`Connector “${t.name}” is unavailable`,body:n,level:`warn`}),this.errors.set(t.name,n),this.#e.delete(t.name)}}return e}async probe(e){let t=this.servers().find(t=>t.name===e);if(!t)throw Error(`no such connector: ${e}`);this.#e.delete(e);let{client:n}=await this.#t(t);return(await n.listTools()).map(e=>({name:e.name,description:e.description??``}))}async relayed(){return Promise.all(this.servers().filter(e=>e.enabled&&e.via===`anthropic`).map(async e=>({name:Je(e.name),url:e.url,token:await this.os.secrets.get(Ge(e.name))})))}};const Xe={name:`agent`,summary:`talk to the AI agent from the command line`,usage:`agent ["task"] — no argument starts an interactive session (/exit to leave, /new to reset)`,async run(e){let{Agent:t}=await Promise.resolve().then(()=>Kt),{describeModel:n,loadConfig:r}=await Promise.resolve().then(()=>et),{out:i,tty:a}=e,o=!1,s=!1,c=()=>{o&&i(`
349
349
  `),o=!1},l=new t(e.os,{onEvent(t){if(t.type===`text`)i(t.delta),o=!0;else if(t.type===`tool_start`)c(),i(`${M.cyan}▸ ${t.name}${M.reset} ${M.dim}${t.summary.split(`
350
350
  `)[0].slice(0,140)}${M.reset}\n`);else if(t.type===`tool_end`){let e=t.result.split(`
351
351
  `).find(e=>e.trim())??``;i(` ${t.isError?`${M.red}✗`:`${M.green}✓`}${M.reset} ${M.dim}${e.slice(0,140)}${t.result.length>e.length?` …`:``}${M.reset}\n`)}else t.type===`status`&&t.text?(c(),i(`${M.dim}${t.text}${M.reset}\n`)):t.type===`note`?(c(),i(`${M.yellow}${t.text}${M.reset}\n`)):t.type===`error`?(c(),s=!0,e.err(`${M.red}${t.message}${M.reset}\n`)):t.type===`done`&&c()},async ask(e,t){return c(),a?(i(`${M.yellow}?${M.reset} ${e}${t?.length?` ${M.dim}(${t.join(` / `)})${M.reset}`:``}\n`),await a.readLine(`answer> `)??`(no answer)`):`No terminal is attached, so the user cannot answer. Use your best judgement.`},prompter:a?async e=>{c(),i(`${M.yellow}Allow ${e.title}?${M.reset} ${M.dim}${e.detail.split(`
352
- `)[0].slice(0,160)}${M.reset}\n`);let t=(await a.readLine(`[y]es / [a]lways / [n]o > `)??`n`).trim().toLowerCase();return t.startsWith(`a`)?`always`:t.startsWith(`y`)?`once`:`deny`}:void 0},{ppid:e.shell.ppid});l.shell.cwd=e.shell.cwd;let u=()=>l.stop();e.signal.addEventListener(`abort`,u);try{let t=e.args.join(` `).trim()||e.stdin.trim();if(t)return await l.send(t),+!!s;if(!a)throw Error(`usage: agent "task"`);for(i(`${M.bold}BrowserBox agent${M.reset} ${M.dim}${n(r(e.os))} — /exit to leave, /new for a fresh session${M.reset}\n`);;){let t=await a.readLine(`${M.magenta}agent>${M.reset} `);if(t===null||t.trim()===`/exit`||t.trim()===`/quit`||(t.trim()===`/new`?(l.reset(),i(`${M.dim}Started a new session.${M.reset}\n`)):t.trim()&&await l.send(t),e.signal.aborted))break}return 0}finally{e.signal.removeEventListener(`abort`,u),l.dispose()}}},Ze=i(`gh`,`GitHub: sign in, create and clone repositories, push a folder, open pull requests`,`gh auth login|status|logout · gh repo create <name> [--public] · gh repo clone <owner/repo> [dir] · gh push [dir] [--repo owner/name] [--branch b] [-m msg] · gh pr create --head <branch> --title <t> [--body b] [--base main] [--repo owner/name]`,()=>import(`./publish-impl-DV1nd6hh.js`).then(e=>e.ghCommand)),Qe=i(`deploy`,`build a project for production and publish it to Netlify, Vercel or GitHub Pages`,`deploy [dir] --to netlify|vercel|github-pages [--name site-name] [--repo owner/name]`,()=>import(`./publish-impl-DV1nd6hh.js`).then(e=>e.deployCommand)),$e=i(`build`,`production build of a project: bundled, minified, ready for any static host`,`build [dir] [--out dist]`,()=>import(`./publish-impl-DV1nd6hh.js`).then(e=>e.buildCommand));var et=/* @__PURE__ */ e({describeModel:()=>it,loadConfig:()=>W});const H={provider:`anthropic`,anthropicModel:`claude-opus-5-5`,effort:`medium`,localBaseUrl:`http://localhost:11434/v1`,localModel:``,openaiBaseUrl:`https://api.openai.com/v1`,openaiModel:``,webllmModel:`Qwen2.5-Coder-1.5B-Instruct-q4f16_1-MLC`,maxSteps:50,instructions:``,webSearch:!0,contextWindow:32768,autoCompact:!0,corsRelay:``},U={anthropic:`anthropic.apiKey`,openai:`openai.apiKey`,local:`local.apiKey`},tt=`agent.config`,nt=e=>{try{let t=new URL(e).hostname;return t===`localhost`||t===`127.0.0.1`||t===`[::1]`||/^(10|192\.168|172\.(1[6-9]|2\d|3[01]))\./.test(t)||t.endsWith(`.local`)}catch{return!1}};function W(e){let t=e.settings.get(tt,{});return t.provider===`openai`&&t.localBaseUrl===void 0&&t.openaiBaseUrl&&nt(t.openaiBaseUrl)?{...H,...t,provider:`local`,localBaseUrl:t.openaiBaseUrl,localModel:t.openaiModel??``,openaiBaseUrl:H.openaiBaseUrl,openaiModel:``}:{...H,...t}}function rt(e,t){let n={...W(e),...t};return e.settings.set(tt,n),n}function it(e){return e.provider===`anthropic`?e.anthropicModel:e.provider===`local`?`${e.localModel||`no model`} @ ${e.localBaseUrl.replace(/^https?:\/\//,``)}`:e.provider===`openai`?`${e.openaiModel||`no model`} @ ${e.openaiBaseUrl.replace(/^https?:\/\//,``)}`:`${e.webllmModel} (WebGPU)`}function at(e,t=``){return t.trim()?`${t.trim().replace(/\/+$/,``)}/${e}`:e}function ot(e,t,n=``){let r=e;try{r=new URL(e).host}catch{}if(n.trim())return`Could not reach ${r} through the relay ${n}. Check that the relay is running and allows ${r}.`;if(t===`local`)return`Could not reach ${r}. Is the server running, and does it allow this page's origin (CORS)? For Ollama: OLLAMA_ORIGINS="*" ollama serve`;let i=/(^|\.)ollama\.com$/.test(r)?` For Ollama Cloud you can instead run Ollama on your computer, sign in (ollama signin) and use Local server: it runs the -cloud models for you.`:``;return`${r} did not accept a request from this page. Browsers only let a web page call servers that allow it (CORS), and ${r} does not (or the address is wrong, or you are offline). Set a relay in Settings → Model → OpenAI-compatible API (relay/worker.js in the BrowserBox repository is one you can deploy for free), or use a provider that allows browser requests, such as OpenRouter.${i}`}async function st(e,t,n,r={}){let i;try{i=await fetch(at(`${e.replace(/\/+$/,``)}/models`,r.relay),{headers:t?{authorization:`Bearer ${t}`}:{},signal:n})}catch{throw Error(ot(e,r.kind??`local`,r.relay))}if(!i.ok)throw Error(`${e} answered ${i.status} ${i.statusText}`);return((await i.json()).data??[]).map(e=>e.id).sort()}const ct=[{name:`setup`,summary:`connect a model and install the default packages`,usage:`setup | setup --defaults (no questions)`,async run(e){let{os:t,out:n,tty:r}=e,i=async(e,t,n=!1)=>{let r=await e.readLine(t,{secret:n});if(r===null)throw Error(`setup cancelled`);return r.trim()};if(r&&!e.args.includes(`--defaults`)){let e=t.settings.get(`user.name`,``),a=(await i(r,`Your name ${M.dim}(${e?`${e} · `:``}for greetings · Enter to skip)${M.reset}: `)).slice(0,40);a&&(t.settings.set(`user.name`,a),n(`${M.green}✓${M.reset} Hi, ${a}\n`));let o=await i(r,`Anthropic API key ${M.dim}(hidden · Enter to skip)${M.reset}: `,!0);if(o)await t.secrets.set(U.anthropic,o),rt(t,{provider:`anthropic`}),n(`${M.green}✓${M.reset} Claude Opus 5.5 · key stored encrypted\n`);else for(;;){let e=await i(r,`Local model server ${M.dim}(e.g. ${H.localBaseUrl} · Enter to skip)${M.reset}: `);if(!e){n(`${M.dim}no model yet: add one later in Settings → Model${M.reset}\n`);break}try{let a=await st(e,null);if(!a.length)throw Error(`${e} has no models loaded`);let o=a[0];a.length>1&&(a.forEach((e,t)=>n(` ${t+1} ${e}\n`)),o=a[Number(await i(r,`model ${M.dim}[1]${M.reset}: `))-1]??a[0]),rt(t,{provider:`local`,localBaseUrl:e,localModel:o}),n(`${M.green}✓${M.reset} ${o} on ${e}\n`);break}catch(e){n(`${M.yellow}${e.message}${M.reset}\n`)}}}await Ne(e,Ie(t).filter(e=>!t.packages.isInstalled(e))),t.settings.keys().includes(`ui.theme`)||t.settings.set(`ui.theme`,`system`),t.settings.set(`setup.done`,!0),n(`${M.dim}done · python: pkg install python · run setup again any time${M.reset}\n`)}},Xe,Ze,Qe,$e],lt=e=>!e.subarray(0,8192).includes(0),ut=e=>{let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)},dt=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0));var ft=class{os;list=[];constructor(e){this.os=e}begin(e){this.list.push({turn:e,at:Date.now(),files:[]})}#e(){return this.list.reduce((e,t)=>e+t.files.reduce((e,t)=>e+(t.before?.length??0),0),0)}async capture(e){let t=this.list.at(-1),n=/* @__PURE__ */ new Map;if(!t)return n;let r=[];for(let t of e)if((await this.os.fs.stat(t).catch(()=>null))?.kind===`dir`){for await(let e of this.os.fs.walk(t))if(e.kind===`file`&&r.push(e.path),r.length>500)break}else r.push(t);for(let e of r){let r=t.files.find(t=>t.path===e);if(!r){let n=await this.os.fs.stat(e).catch(()=>null);if(!n)r={path:e,before:null};else if(n.kind!==`file`||n.size>2097152||this.#e()+n.size>25165824)r={path:e,before:null,skipped:!0};else{let t=await this.os.fs.readFile(e);r=lt(t)?{path:e,before:new TextDecoder().decode(t)}:{path:e,before:ut(t),binary:!0}}t.files.push(r)}n.set(e,r.binary||r.skipped?null:r.before)}return n}since(e){let t=/* @__PURE__ */ new Map;for(let n of this.list)if(n.turn>=e)for(let e of n.files)t.has(e.path)||t.set(e.path,e);return[...t.values()]}async restore(e){let t=[],n=[];for(let r of this.since(e))r.skipped?n.push(r.path):(r.before===null?await this.os.fs.rm(r.path,{recursive:!0}).catch(()=>void 0):await this.os.fs.writeFile(r.path,r.binary?dt(r.before):r.before),t.push(r.path));return this.drop(e),{restored:t,skipped:n}}drop(e){this.list=this.list.filter(t=>t.turn<e)}};const pt=2e4;function mt(e){if(!e)return[];let t=e.split(`
352
+ `)[0].slice(0,160)}${M.reset}\n`);let t=(await a.readLine(`[y]es / [a]lways / [n]o > `)??`n`).trim().toLowerCase();return t.startsWith(`a`)?`always`:t.startsWith(`y`)?`once`:`deny`}:void 0},{ppid:e.shell.ppid});l.shell.cwd=e.shell.cwd;let u=()=>l.stop();e.signal.addEventListener(`abort`,u);try{let t=e.args.join(` `).trim()||e.stdin.trim();if(t)return await l.send(t),+!!s;if(!a)throw Error(`usage: agent "task"`);for(i(`${M.bold}BrowserBox agent${M.reset} ${M.dim}${n(r(e.os))} — /exit to leave, /new for a fresh session${M.reset}\n`);;){let t=await a.readLine(`${M.magenta}agent>${M.reset} `);if(t===null||t.trim()===`/exit`||t.trim()===`/quit`||(t.trim()===`/new`?(l.reset(),i(`${M.dim}Started a new session.${M.reset}\n`)):t.trim()&&await l.send(t),e.signal.aborted))break}return 0}finally{e.signal.removeEventListener(`abort`,u),l.dispose()}}},Ze=i(`gh`,`GitHub: sign in, create and clone repositories, push a folder, open pull requests`,`gh auth login|status|logout · gh repo create <name> [--public] · gh repo clone <owner/repo> [dir] · gh push [dir] [--repo owner/name] [--branch b] [-m msg] · gh pr create --head <branch> --title <t> [--body b] [--base main] [--repo owner/name]`,()=>import(`./publish-impl-BqjdM7Ux.js`).then(e=>e.ghCommand)),Qe=i(`deploy`,`build a project for production and publish it to Netlify, Vercel or GitHub Pages`,`deploy [dir] --to netlify|vercel|github-pages [--name site-name] [--repo owner/name]`,()=>import(`./publish-impl-BqjdM7Ux.js`).then(e=>e.deployCommand)),$e=i(`build`,`production build of a project: bundled, minified, ready for any static host`,`build [dir] [--out dist]`,()=>import(`./publish-impl-BqjdM7Ux.js`).then(e=>e.buildCommand));var et=/* @__PURE__ */ e({describeModel:()=>it,loadConfig:()=>W});const H={provider:`anthropic`,anthropicModel:`claude-opus-5-5`,effort:`medium`,localBaseUrl:`http://localhost:11434/v1`,localModel:``,openaiBaseUrl:`https://api.openai.com/v1`,openaiModel:``,webllmModel:`Qwen2.5-Coder-1.5B-Instruct-q4f16_1-MLC`,maxSteps:50,instructions:``,webSearch:!0,contextWindow:32768,autoCompact:!0,corsRelay:``},U={anthropic:`anthropic.apiKey`,openai:`openai.apiKey`,local:`local.apiKey`},tt=`agent.config`,nt=e=>{try{let t=new URL(e).hostname;return t===`localhost`||t===`127.0.0.1`||t===`[::1]`||/^(10|192\.168|172\.(1[6-9]|2\d|3[01]))\./.test(t)||t.endsWith(`.local`)}catch{return!1}};function W(e){let t=e.settings.get(tt,{});return t.provider===`openai`&&t.localBaseUrl===void 0&&t.openaiBaseUrl&&nt(t.openaiBaseUrl)?{...H,...t,provider:`local`,localBaseUrl:t.openaiBaseUrl,localModel:t.openaiModel??``,openaiBaseUrl:H.openaiBaseUrl,openaiModel:``}:{...H,...t}}function rt(e,t){let n={...W(e),...t};return e.settings.set(tt,n),n}function it(e){return e.provider===`anthropic`?e.anthropicModel:e.provider===`local`?`${e.localModel||`no model`} @ ${e.localBaseUrl.replace(/^https?:\/\//,``)}`:e.provider===`openai`?`${e.openaiModel||`no model`} @ ${e.openaiBaseUrl.replace(/^https?:\/\//,``)}`:`${e.webllmModel} (WebGPU)`}function at(e,t=``){return t.trim()?`${t.trim().replace(/\/+$/,``)}/${e}`:e}function ot(e,t,n=``){let r=e;try{r=new URL(e).host}catch{}if(n.trim())return`Could not reach ${r} through the relay ${n}. Check that the relay is running and allows ${r}.`;if(t===`local`)return`Could not reach ${r}. Is the server running, and does it allow this page's origin (CORS)? For Ollama: OLLAMA_ORIGINS="*" ollama serve`;let i=/(^|\.)ollama\.com$/.test(r)?` For Ollama Cloud you can instead run Ollama on your computer, sign in (ollama signin) and use Local server: it runs the -cloud models for you.`:``;return`${r} did not accept a request from this page. Browsers only let a web page call servers that allow it (CORS), and ${r} does not (or the address is wrong, or you are offline). Set a relay in Settings → Model → OpenAI-compatible API (relay/worker.js in the BrowserBox repository is one you can deploy for free), or use a provider that allows browser requests, such as OpenRouter.${i}`}async function st(e,t,n,r={}){let i;try{i=await fetch(at(`${e.replace(/\/+$/,``)}/models`,r.relay),{headers:t?{authorization:`Bearer ${t}`}:{},signal:n})}catch{throw Error(ot(e,r.kind??`local`,r.relay))}if(!i.ok)throw Error(`${e} answered ${i.status} ${i.statusText}`);return((await i.json()).data??[]).map(e=>e.id).sort()}const ct=[{name:`setup`,summary:`connect a model and install the default packages`,usage:`setup | setup --defaults (no questions)`,async run(e){let{os:t,out:n,tty:r}=e,i=async(e,t,n=!1)=>{let r=await e.readLine(t,{secret:n});if(r===null)throw Error(`setup cancelled`);return r.trim()};if(r&&!e.args.includes(`--defaults`)){let e=t.settings.get(`user.name`,``),a=(await i(r,`Your name ${M.dim}(${e?`${e} · `:``}for greetings · Enter to skip)${M.reset}: `)).slice(0,40);a&&(t.settings.set(`user.name`,a),n(`${M.green}✓${M.reset} Hi, ${a}\n`));let o=await i(r,`Anthropic API key ${M.dim}(hidden · Enter to skip)${M.reset}: `,!0);if(o)await t.secrets.set(U.anthropic,o),rt(t,{provider:`anthropic`}),n(`${M.green}✓${M.reset} Claude Opus 5.5 · key stored encrypted\n`);else for(;;){let e=await i(r,`Local model server ${M.dim}(e.g. ${H.localBaseUrl} · Enter to skip)${M.reset}: `);if(!e){n(`${M.dim}no model yet: add one later in Settings → Model${M.reset}\n`);break}try{let a=await st(e,null);if(!a.length)throw Error(`${e} has no models loaded`);let o=a[0];a.length>1&&(a.forEach((e,t)=>n(` ${t+1} ${e}\n`)),o=a[Number(await i(r,`model ${M.dim}[1]${M.reset}: `))-1]??a[0]),rt(t,{provider:`local`,localBaseUrl:e,localModel:o}),n(`${M.green}✓${M.reset} ${o} on ${e}\n`);break}catch(e){n(`${M.yellow}${e.message}${M.reset}\n`)}}}await Ne(e,Ie(t).filter(e=>!t.packages.isInstalled(e))),t.settings.keys().includes(`ui.theme`)||t.settings.set(`ui.theme`,`system`),t.settings.set(`setup.done`,!0),n(`${M.dim}done · python: pkg install python · run setup again any time${M.reset}\n`)}},Xe,Ze,Qe,$e],lt=e=>!e.subarray(0,8192).includes(0),ut=e=>{let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)},dt=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0));var ft=class{os;list=[];constructor(e){this.os=e}begin(e){this.list.push({turn:e,at:Date.now(),files:[]})}#e(){return this.list.reduce((e,t)=>e+t.files.reduce((e,t)=>e+(t.before?.length??0),0),0)}async capture(e){let t=this.list.at(-1),n=/* @__PURE__ */ new Map;if(!t)return n;let r=[];for(let t of e)if((await this.os.fs.stat(t).catch(()=>null))?.kind===`dir`){for await(let e of this.os.fs.walk(t))if(e.kind===`file`&&r.push(e.path),r.length>500)break}else r.push(t);for(let e of r){let r=t.files.find(t=>t.path===e);if(!r){let n=await this.os.fs.stat(e).catch(()=>null);if(!n)r={path:e,before:null};else if(n.kind!==`file`||n.size>2097152||this.#e()+n.size>25165824)r={path:e,before:null,skipped:!0};else{let t=await this.os.fs.readFile(e);r=lt(t)?{path:e,before:new TextDecoder().decode(t)}:{path:e,before:ut(t),binary:!0}}t.files.push(r)}n.set(e,r.binary||r.skipped?null:r.before)}return n}since(e){let t=/* @__PURE__ */ new Map;for(let n of this.list)if(n.turn>=e)for(let e of n.files)t.has(e.path)||t.set(e.path,e);return[...t.values()]}async restore(e){let t=[],n=[];for(let r of this.since(e))r.skipped?n.push(r.path):(r.before===null?await this.os.fs.rm(r.path,{recursive:!0}).catch(()=>void 0):await this.os.fs.writeFile(r.path,r.binary?dt(r.before):r.before),t.push(r.path));return this.drop(e),{restored:t,skipped:n}}drop(e){this.list=this.list.filter(t=>t.turn<e)}};const pt=2e4;function mt(e){if(!e)return[];let t=e.split(`
353
353
  `);return t.at(-1)===``&&t.pop(),t}function ht(e,t){let n=e.length,r=t.length,i=n+r,a=/* @__PURE__ */ new Map([[1,0]]),o=[],s=!1;for(let c=0;c<=Math.min(i,4e3);c++){o.push(new Map(a));for(let i=-c;i<=c;i+=2){let o=i===-c||i!==c&&(a.get(i-1)??-1)<(a.get(i+1)??-1)?a.get(i+1)??0:(a.get(i-1)??0)+1,l=o-i;for(;o<n&&l<r&&e[o]===t[l];)o++,l++;if(a.set(i,o),o>=n&&l>=r){s=!0;break}}if(s)break}if(!s)return null;let c=[],l=n,u=r;for(let n=o.length-1;n>=0;n--){let r=o[n],i=l-u,a=i===-n||i!==n&&(r.get(i-1)??-1)<(r.get(i+1)??-1)?i+1:i-1,s=r.get(a)??0,d=s-a;for(;l>s&&u>d;)c.push({kind:` `,text:e[l-1],old:l,new:u}),l--,u--;n>0&&(l===s?c.push({kind:`+`,text:t[u-1],new:u}):c.push({kind:`-`,text:e[l-1],old:l})),l=s,u=d}return c.reverse()}function gt(e,t,n,r=3){let i={path:e,before:t===null?null:`file`,after:n===null?null:`file`,added:0,removed:0,hunks:[]},a=mt(t??``),o=mt(n??``);if(a.length>pt||o.length>pt)return{...i,note:`Too large to show line by line.`};let s=ht(a,o);if(!s)return{...i,added:o.length,removed:a.length,note:`Changed throughout; too different to show line by line.`};i.added=s.filter(e=>e.kind===`+`).length,i.removed=s.filter(e=>e.kind===`-`).length;let c=s.map((e,t)=>e.kind===` `?-1:t).filter(e=>e>=0),l=0;for(;l<c.length;){let e=Math.max(0,c[l]-r),t=Math.min(s.length-1,c[l]+r);for(;l+1<c.length&&c[l+1]-r<=t+1;)l++,t=Math.min(s.length-1,c[l]+r);let n=s.slice(e,t+1),a=n[0];i.hunks.push({oldStart:a.old??n.find(e=>e.old)?.old??1,newStart:a.new??n.find(e=>e.new)?.new??1,lines:n}),l++,e=t}return i}var _t=`---
354
354
  name: explorer
355
355
  description: Read-only investigator for searching and summarising many files without changing anything.
@@ -420,15 +420,15 @@ ${i.subagent?`- You are a sub-agent: complete the task you were given and finish
420
420
  `:``}
421
421
  # Style
422
422
  Write for someone reading a chat window: lead with the outcome, keep it brief, use Markdown where it helps, and refer to files by their path.
423
- ${l(s)?`\n# Skills\nReusable instructions for specific kinds of task. When a request matches one, call use_skill with its name first and follow what it says.\n${l(s)}\n`:``}${l(c)?`\n# Custom agents\nSpecialised sub-agents you can delegate to with spawn_agent (pass the name as \`agent\`).\n${l(c)}\n`:``}${u.length?`\n# Environment variables\nSet by the user and available in the shell (as $NAME), in run_js (as env.NAME) and in Python (os.environ): ${u.join(`, `)}\n`:``}${i.persona?`\n# Your role: ${i.persona.name}\n${i.persona.body}\n`:``}${o.trim()?`\n# Project instructions (${r}/AGENTS.md)\nFollow these for work in this folder. Keep the file up to date when you learn how the project works (/init writes it).\n${o.trim().slice(0,8e3)}\n`:``}${a.trim()?`\n# Memory (${r}/MEMORY.md)\n${a.trim().slice(0,6e3)}\n`:``}${t.instructions.trim()?`\n# User instructions\n${t.instructions.trim()}\n`:``}`}var K=class extends Error{retryable;constructor(e,t=!1){super(e),this.retryable=t,this.name=`ProviderError`}};async function At(e,t){if(t.provider===`anthropic`){let n=await e.secrets.get(U.anthropic);if(!n)throw new K(`No Anthropic API key yet. Add one in Settings → Model, or switch to a local model there.`);return(await import(`./anthropic-Cc12J4F-.js`)).createAnthropicProvider(t,n,await e.mcp.relayed())}if(t.provider===`local`)return(await import(`./openai-D6_sZyaT.js`)).createOpenAiProvider(t,{kind:`local`,baseUrl:t.localBaseUrl,model:t.localModel},await e.secrets.get(U.local));if(t.provider===`openai`){let n=await e.secrets.get(U.openai);if(!n)throw new K(`No API key for the OpenAI-compatible API yet. Add one in Settings → Model.`);return(await import(`./openai-D6_sZyaT.js`)).createOpenAiProvider(t,{kind:`openai`,baseUrl:t.openaiBaseUrl,model:t.openaiModel},n)}return(await import(`./webllm-CGpOYyn6.js`)).createWebLlmProvider(e,t)}function jt(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return[`input must be a JSON object`];let n=t,r=[];for(let t of e.required??[])(n[t]===void 0||n[t]===null)&&r.push(`missing required property "${t}"`);for(let[t,i]of Object.entries(n)){let n=e.properties[t];if(!n){e.additionalProperties===!1&&r.push(`unknown property "${t}"`);continue}if(i==null)continue;let a=n.type,o=Array.isArray(i)?`array`:typeof i;!a||a===o||a===`integer`&&typeof i==`number`&&Number.isInteger(i)||a===`number`&&o===`number`?Array.isArray(n.enum)&&!n.enum.includes(i)&&r.push(`property "${t}" must be one of ${JSON.stringify(n.enum)}`):r.push(`property "${t}" must be ${a}, got ${o}`)}return r}const Mt=e=>`[${e.source}] ${e.level===`log`?``:`${e.level}: `}${e.text}`,Nt=/* @__PURE__ */ new Map,Pt=[z({name:`dev_server`,description:"Run a web app you are building, like `npm run dev`. start serves a project folder at a virtual http://localhost:<port>/ and opens it in the Preview panel: index.html (or src/main.tsx/jsx/ts/js without one) with TypeScript, JSX, CSS modules and JSON bundled by esbuild; npm packages listed in package.json (or imported by name) load from esm.sh; files reload on save. Requests the page makes to its own address are answered from project files or by a backend: a server.ts/server.js that does `export default { fetch(request, env) { return new Response(...) } }` (env.fs reads and writes project files; env holds .env variables). Client-side routes get index.html. After starting or changing the app, call preview_logs to see console output, errors and failed requests.",input_schema:B({action:{type:`string`,enum:[`start`,`stop`,`list`]},path:{type:`string`,description:`project folder (start); default: the working directory`},port:{type:`number`,description:`start: a specific port; stop: which server`},network:{type:`boolean`,description:`let the backend make outbound requests (default false)`}},[`action`]),cap:e=>e.action===`start`&&e.network?`net`:null,describe:e=>e.action===`start`?`Serve ${e.path??`.`}`:e.action===`stop`?`Stop the dev server${e.port?` on :${e.port}`:``}`:`List dev servers`,async run(e,t){let n=t.os.dev;if(e.action===`list`){let e=await n.list();return e.length?e.map(e=>`${e.url} → ${e.root}${e.backend?` (backend ${e.backend})`:``}`).join(`
423
+ ${l(s)?`\n# Skills\nReusable instructions for specific kinds of task. When a request matches one, call use_skill with its name first and follow what it says.\n${l(s)}\n`:``}${l(c)?`\n# Custom agents\nSpecialised sub-agents you can delegate to with spawn_agent (pass the name as \`agent\`).\n${l(c)}\n`:``}${u.length?`\n# Environment variables\nSet by the user and available in the shell (as $NAME), in run_js (as env.NAME) and in Python (os.environ): ${u.join(`, `)}\n`:``}${i.persona?`\n# Your role: ${i.persona.name}\n${i.persona.body}\n`:``}${o.trim()?`\n# Project instructions (${r}/AGENTS.md)\nFollow these for work in this folder. Keep the file up to date when you learn how the project works (/init writes it).\n${o.trim().slice(0,8e3)}\n`:``}${a.trim()?`\n# Memory (${r}/MEMORY.md)\n${a.trim().slice(0,6e3)}\n`:``}${t.instructions.trim()?`\n# User instructions\n${t.instructions.trim()}\n`:``}`}var K=class extends Error{retryable;constructor(e,t=!1){super(e),this.retryable=t,this.name=`ProviderError`}};async function At(e,t){if(t.provider===`anthropic`){let n=await e.secrets.get(U.anthropic);if(!n)throw new K(`No Anthropic API key yet. Add one in Settings → Model, or switch to a local model there.`);return(await import(`./anthropic-S3ckT02t.js`)).createAnthropicProvider(t,n,await e.mcp.relayed())}if(t.provider===`local`)return(await import(`./openai-CThAXVqN.js`)).createOpenAiProvider(t,{kind:`local`,baseUrl:t.localBaseUrl,model:t.localModel},await e.secrets.get(U.local));if(t.provider===`openai`){let n=await e.secrets.get(U.openai);if(!n)throw new K(`No API key for the OpenAI-compatible API yet. Add one in Settings → Model.`);return(await import(`./openai-CThAXVqN.js`)).createOpenAiProvider(t,{kind:`openai`,baseUrl:t.openaiBaseUrl,model:t.openaiModel},n)}return(await import(`./webllm-wsrhCAP4.js`)).createWebLlmProvider(e,t)}function jt(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return[`input must be a JSON object`];let n=t,r=[];for(let t of e.required??[])(n[t]===void 0||n[t]===null)&&r.push(`missing required property "${t}"`);for(let[t,i]of Object.entries(n)){let n=e.properties[t];if(!n){e.additionalProperties===!1&&r.push(`unknown property "${t}"`);continue}if(i==null)continue;let a=n.type,o=Array.isArray(i)?`array`:typeof i;!a||a===o||a===`integer`&&typeof i==`number`&&Number.isInteger(i)||a===`number`&&o===`number`?Array.isArray(n.enum)&&!n.enum.includes(i)&&r.push(`property "${t}" must be one of ${JSON.stringify(n.enum)}`):r.push(`property "${t}" must be ${a}, got ${o}`)}return r}const Mt=e=>`[${e.source}] ${e.level===`log`?``:`${e.level}: `}${e.text}`,Nt=/* @__PURE__ */ new Map,Pt=[z({name:`dev_server`,description:"Run a web app you are building, like `npm run dev`. start serves a project folder at a virtual http://localhost:<port>/ and opens it in the Preview panel: index.html (or src/main.tsx/jsx/ts/js without one) with TypeScript, JSX, CSS modules and JSON bundled by esbuild; npm packages listed in package.json (or imported by name) load from esm.sh; files reload on save. Requests the page makes to its own address are answered from project files or by a backend: a server.ts/server.js that does `export default { fetch(request, env) { return new Response(...) } }` (env.fs reads and writes project files; env holds .env variables). Client-side routes get index.html. After starting or changing the app, call preview_logs to see console output, errors and failed requests.",input_schema:B({action:{type:`string`,enum:[`start`,`stop`,`list`]},path:{type:`string`,description:`project folder (start); default: the working directory`},port:{type:`number`,description:`start: a specific port; stop: which server`},network:{type:`boolean`,description:`let the backend make outbound requests (default false)`}},[`action`]),cap:e=>e.action===`start`&&e.network?`net`:null,describe:e=>e.action===`start`?`Serve ${e.path??`.`}`:e.action===`stop`?`Stop the dev server${e.port?` on :${e.port}`:``}`:`List dev servers`,async run(e,t){let n=t.os.dev;if(e.action===`list`){let e=await n.list();return e.length?e.map(e=>`${e.url} → ${e.root}${e.backend?` (backend ${e.backend})`:``}`).join(`
424
424
  `):`No dev servers are running.`}if(e.action===`stop`){let t=await n.list(),r=e.port?[e.port]:t.map(e=>e.port);for(let e of r)await n.stop(e);return r.length?`Stopped ${r.map(e=>`:${e}`).join(`, `)}.`:`Nothing was running.`}let r=t.path(e.path??`.`);t.os.packages.isInstalled(`esbuild`)||(t.progress(`installing the esbuild package…
425
425
  `),await t.os.packages.install(`esbuild`));let i=await n.start({root:r,port:e.port,network:e.network});t.os.openApp(`preview`,{dev:i.port}),await new Promise(e=>setTimeout(e,1500));let a=await n.logs(i.port);Nt.set(String(i.port),a.at(-1)?.seq??0);let o=a.filter(e=>e.level===`error`||e.level===`warn`);return[`Serving ${i.root} at ${i.url} (virtual; it opens in the Preview panel, not in other tabs).`,i.backend?`Backend: ${i.backend}${i.network?` (network allowed)`:` (no network)`}.`:`No backend (add server.ts to answer API requests).`,o.length?`Problems so far:\n${o.map(Mt).join(`
426
426
  `)}`:a.length?`Console so far:\n${a.slice(-20).map(Mt).join(`
427
427
  `)}`:`No console output yet.`].join(`
428
428
  `)}}),z({name:`preview_logs`,description:`Read what the app on a dev server printed since you last looked: browser console output, uncaught errors, failed requests (404/500), build errors and the backend's console. Preview reloads by itself when files change, so after editing wait a moment (wait_ms) and read the logs to check your change worked.`,input_schema:B({port:{type:`number`,description:`default: the only running server`},wait_ms:{type:`number`,description:`wait this long first, for a reload to finish (default 1200, max 10000)`},all:{type:`boolean`,description:`return everything kept (the last 500 entries), not only new ones`}}),cap:()=>null,describe:e=>`Read preview logs${e.port?` for :${e.port}`:``}`,async run(e,t){let n=await t.os.dev.list(),r=e.port??(n.length===1?n[0].port:void 0);if(r===void 0)return n.length?`Several servers are running (${n.map(e=>e.port).join(`, `)}): pass port.`:`No dev server is running. Start one with dev_server.`;await new Promise(t=>setTimeout(t,Math.min(1e4,Math.max(0,e.wait_ms??1200))));let i=String(r),a=await t.os.dev.logs(r,{after:e.all?0:Nt.get(i)??0});if(a.length&&Nt.set(i,a.at(-1).seq),!a.length)return`Nothing new. (Is the Preview panel showing this app? The page only runs while it is open.)`;let o=a.filter(e=>e.level===`error`).length;return`${a.length} entr${a.length===1?`y`:`ies`}${o?`, ${o} error${o===1?``:`s`}`:``}:\n${a.slice(-200).map(Mt).join(`
429
429
  `)}`}})];function Ft(e){let t=[];e.stdout&&t.push(e.stdout.trimEnd()),e.stderr&&t.push(`[stderr]\n${e.stderr.trimEnd()}`),e.value!==void 0&&t.push(`[return value]\n${e.value}`),e.error&&t.push(`[error]\n${e.error}`),e.exitCode!==void 0&&e.exitCode!==0&&t.push(`[exit code ${e.exitCode}]`);let n=V(t.join(`
430
- `)||`(no output)`);if(!e.ok)throw Error(n);return n}const It=[z({name:`shell`,description:"Run a command line in the BrowserBox shell (not bash, but POSIX-flavoured): pipes, redirects, &&, ||, ;, $VARS and globs work. Commands include ls, cat, grep, find, head, tail, wc, sort, uniq, mkdir, rm, cp, mv, tree, du, curl, js, python, wasm, gpu, ps, kill, open, sha256sum, gzip. Run `help` to list them all. Installed packages add more commands (see `pkg list`). The working directory persists between calls (cd works). There is no npm, apt or native compiler.",input_schema:B({command:{type:`string`}},[`command`]),cap:()=>`exec`,describe:e=>e.command,async run(e,t){let n=``,r=e=>{n+=e,t.progress(e)},i=await t.shell.run(e.command,{out:r,err:r,signal:t.signal}),a=V(De(n).trimEnd()||`(no output)`);if(i!==0)throw Error(`${a}\n[exit code ${i}]`);return a}}),z({name:`run_js`,description:"Run JavaScript in an isolated sandbox (a Worker in an opaque-origin frame; no DOM). The code is the body of an async function: use await and return a value. Globals: `fs` (async: readText, readFile, writeFile, appendFile, readdir, exists, mkdir, rm, glob — paths relative to the working directory), `print(...)`, `console`. fetch only works when network is true, and then only for CORS-enabled URLs. Good for computation, data processing and generating files.",input_schema:B({code:{type:`string`},network:{type:`boolean`,description:`allow outbound network (asks the user)`},timeout_ms:{type:`integer`,description:`default 30000, max 300000`}},[`code`]),cap:e=>e.network?`net`:`exec`,describe:e=>`${e.network?`[network] `:``}${e.code}`,async run(e,t){return Ft(await de(t.os,e.code,{cwd:t.shell.cwd,env:A(t.shell.env),network:e.network,timeoutMs:Math.min(e.timeout_ms??3e4,3e5),signal:t.signal,onStdout:t.progress,onStderr:t.progress,ppid:t.pid}))}}),z({name:`run_wasm`,description:`Run a WebAssembly program (WASI preview1, stdio only) from a .wasm file in the filesystem. Returns its stdout, stderr and exit code.`,input_schema:B({path:{type:`string`},args:{type:`array`,items:{type:`string`}},stdin:{type:`string`}},[`path`]),cap:()=>`exec`,describe:e=>`Run ${e.path} ${(e.args??[]).join(` `)}`,async run(e,t){let n=await t.os.fs.readFile(t.path(e.path));return Ft(await fe(t.os,n,{name:e.path,args:e.args,stdin:e.stdin,signal:t.signal,onStdout:t.progress,onStderr:t.progress,ppid:t.pid}))}}),z({name:`gpu_compute`,description:"Run a WGSL compute shader on the GPU with WebGPU. The shader must define `@compute @workgroup_size(...) fn main(...)`, with `@group(0) @binding(0) var<storage, read> input: array<f32>;` and `@group(0) @binding(1) var<storage, read_write> output: array<f32>;`. Input comes from `input` (numbers) or `input_file` (a JSON array). Returns the first values and summary statistics; use output_file to save the full result as JSON.",input_schema:B({wgsl:{type:`string`},input:{type:`array`,items:{type:`number`}},input_file:{type:`string`},output_length:{type:`integer`,description:`number of f32 values in the output buffer`},workgroups:{type:`array`,items:{type:`integer`},description:`[x, y?, z?] dispatch counts; default ceil(output_length / 64)`},output_file:{type:`string`}},[`wgsl`,`output_length`]),cap:()=>`exec`,describe:e=>`GPU compute → ${e.output_length} values`,async run(e,t){let n=e.input_file?JSON.parse(await t.os.fs.readText(t.path(e.input_file))):e.input??[],r=await f({wgsl:e.wgsl,input:n,outputLength:e.output_length,workgroups:e.workgroups}),i=1/0,a=-1/0,o=0;for(let e of r.output)e<i&&(i=e),e>a&&(a=e),o+=e;return e.output_file&&await t.os.fs.writeFile(t.path(e.output_file),JSON.stringify(Array.from(r.output))),`GPU time ${r.ms.toFixed(1)} ms · ${r.output.length} values · min ${i} · max ${a} · sum ${o}\nfirst values: ${JSON.stringify(Array.from(r.output.slice(0,32)))}${e.output_file?`\nsaved to ${t.path(e.output_file)}`:``}`}})],Lt=[z({name:`github`,description:`Work with GitHub through its REST API (git's own protocol does not work from a browser). status: who is signed in, and where folders were pushed. push: commit a folder's current files to a repository branch as one commit (creates the repository if needed; private unless private=false; .gitignore respected); repeat pushes of a folder go to the same place. clone: fetch a repository's files into a folder. create_repo: a new repository. create_pr: open a pull request from head into base. Needs the user's GitHub token (Settings → Accounts).`,input_schema:B({action:{type:`string`,enum:[`status`,`push`,`clone`,`create_repo`,`create_pr`]},path:{type:`string`,description:`folder to push, or to clone into`},repo:{type:`string`,description:`owner/name, or just name for your own account`},branch:{type:`string`},message:{type:`string`,description:`commit message`},private:{type:`boolean`},title:{type:`string`},body:{type:`string`},head:{type:`string`,description:`create_pr: the branch with the changes`},base:{type:`string`,description:`create_pr: the branch to merge into (default branch if omitted)`}},[`action`]),cap:e=>e.action===`status`?null:`net`,describe:e=>e.action===`push`?`Push ${e.path??`.`} to GitHub${e.repo?` (${e.repo})`:``}`:e.action===`create_pr`?`Open a pull request: ${e.title??``}`:`GitHub: ${e.action} ${e.repo??``}`,async run(e,t){let n=await import(`./publish-gZ8mQa6L.js`),r=e=>t.progress(e+`
431
- `);if(e.action===`status`){let e=await n.github(t.os).then(e=>e.user()).then(e=>`Signed in to GitHub as ${e.login}.`,e=>e.message),r=t.os.settings.get(`publish.links`,{});return`${e}\nFolders and where they were published:\n${JSON.stringify(r,null,2)}`}if(e.action===`push`)return n.pushFolder(t.os,t.path(e.path??`.`),{repo:e.repo,branch:e.branch,message:e.message,private:e.private},r);if(e.action===`clone`){if(!e.repo)throw Error(`clone needs repo`);return n.cloneRepo(t.os,e.repo,e.path?t.path(e.path):null,t.shell.cwd,{branch:e.branch},r)}let i=await n.github(t.os);if(e.action===`create_repo`){if(!e.repo)throw Error(`create_repo needs repo`);let t=await i.createRepo(e.repo.split(`/`).pop(),{private:e.private??!0,org:e.repo.includes(`/`)?e.repo.split(`/`)[0]:void 0});return`Created ${t.full_name}: ${t.html_url}`}let a=await n.repoName(i,e.repo??n.linksFor(t.os,t.shell.cwd).github?.repo??``);if(!e.head||!e.title)throw Error(`create_pr needs head and title`);let o=await i.createPr(a,{head:e.head,base:e.base,title:e.title,body:e.body});return`Opened pull request #${o.number}: ${o.html_url}`}}),z({name:`deploy`,description:`Build a web project for production (pages bundled and minified, npm packages included) and publish it as a static site: netlify, vercel or github-pages. Returns the live URL. The first deploy of a folder needs a target; later ones reuse it and update the same site. A server.ts backend is not deployed (static hosting). Needs the user's token for that host (Settings → Accounts).`,input_schema:B({path:{type:`string`,description:`project folder (default: working directory)`},target:{type:`string`,enum:[`netlify`,`vercel`,`github-pages`]},name:{type:`string`,description:`site or project name (first deploy)`},repo:{type:`string`,description:`github-pages: owner/name`}}),cap:()=>`net`,describe:e=>`Deploy ${e.path??`.`}${e.target?` to ${e.target}`:``}`,async run(e,t){let n=await(await import(`./publish-gZ8mQa6L.js`)).deployFolder(t.os,t.path(e.path??`.`),{target:e.target,name:e.name,repo:e.repo},e=>t.progress(e+`
430
+ `)||`(no output)`);if(!e.ok)throw Error(n);return n}const It=[z({name:`shell`,description:"Run a command line in the BrowserBox shell (not bash, but POSIX-flavoured): pipes, redirects, &&, ||, ;, $VARS and globs work. Commands include ls, cat, grep, find, head, tail, wc, sort, uniq, mkdir, rm, cp, mv, tree, du, curl, js, python, wasm, gpu, ps, kill, open, sha256sum, gzip. Run `help` to list them all. Installed packages add more commands (see `pkg list`). The working directory persists between calls (cd works). There is no npm, apt or native compiler.",input_schema:B({command:{type:`string`}},[`command`]),cap:()=>`exec`,describe:e=>e.command,async run(e,t){let n=``,r=e=>{n+=e,t.progress(e)},i=await t.shell.run(e.command,{out:r,err:r,signal:t.signal}),a=V(De(n).trimEnd()||`(no output)`);if(i!==0)throw Error(`${a}\n[exit code ${i}]`);return a}}),z({name:`run_js`,description:"Run JavaScript in an isolated sandbox (a Worker in an opaque-origin frame; no DOM). The code is the body of an async function: use await and return a value. Globals: `fs` (async: readText, readFile, writeFile, appendFile, readdir, exists, mkdir, rm, glob — paths relative to the working directory), `print(...)`, `console`. fetch only works when network is true, and then only for CORS-enabled URLs. Good for computation, data processing and generating files.",input_schema:B({code:{type:`string`},network:{type:`boolean`,description:`allow outbound network (asks the user)`},timeout_ms:{type:`integer`,description:`default 30000, max 300000`}},[`code`]),cap:e=>e.network?`net`:`exec`,describe:e=>`${e.network?`[network] `:``}${e.code}`,async run(e,t){return Ft(await de(t.os,e.code,{cwd:t.shell.cwd,env:A(t.shell.env),network:e.network,timeoutMs:Math.min(e.timeout_ms??3e4,3e5),signal:t.signal,onStdout:t.progress,onStderr:t.progress,ppid:t.pid}))}}),z({name:`run_wasm`,description:`Run a WebAssembly program (WASI preview1, stdio only) from a .wasm file in the filesystem. Returns its stdout, stderr and exit code.`,input_schema:B({path:{type:`string`},args:{type:`array`,items:{type:`string`}},stdin:{type:`string`}},[`path`]),cap:()=>`exec`,describe:e=>`Run ${e.path} ${(e.args??[]).join(` `)}`,async run(e,t){let n=await t.os.fs.readFile(t.path(e.path));return Ft(await fe(t.os,n,{name:e.path,args:e.args,stdin:e.stdin,signal:t.signal,onStdout:t.progress,onStderr:t.progress,ppid:t.pid}))}}),z({name:`gpu_compute`,description:"Run a WGSL compute shader on the GPU with WebGPU. The shader must define `@compute @workgroup_size(...) fn main(...)`, with `@group(0) @binding(0) var<storage, read> input: array<f32>;` and `@group(0) @binding(1) var<storage, read_write> output: array<f32>;`. Input comes from `input` (numbers) or `input_file` (a JSON array). Returns the first values and summary statistics; use output_file to save the full result as JSON.",input_schema:B({wgsl:{type:`string`},input:{type:`array`,items:{type:`number`}},input_file:{type:`string`},output_length:{type:`integer`,description:`number of f32 values in the output buffer`},workgroups:{type:`array`,items:{type:`integer`},description:`[x, y?, z?] dispatch counts; default ceil(output_length / 64)`},output_file:{type:`string`}},[`wgsl`,`output_length`]),cap:()=>`exec`,describe:e=>`GPU compute → ${e.output_length} values`,async run(e,t){let n=e.input_file?JSON.parse(await t.os.fs.readText(t.path(e.input_file))):e.input??[],r=await f({wgsl:e.wgsl,input:n,outputLength:e.output_length,workgroups:e.workgroups}),i=1/0,a=-1/0,o=0;for(let e of r.output)e<i&&(i=e),e>a&&(a=e),o+=e;return e.output_file&&await t.os.fs.writeFile(t.path(e.output_file),JSON.stringify(Array.from(r.output))),`GPU time ${r.ms.toFixed(1)} ms · ${r.output.length} values · min ${i} · max ${a} · sum ${o}\nfirst values: ${JSON.stringify(Array.from(r.output.slice(0,32)))}${e.output_file?`\nsaved to ${t.path(e.output_file)}`:``}`}})],Lt=[z({name:`github`,description:`Work with GitHub through its REST API (git's own protocol does not work from a browser). status: who is signed in, and where folders were pushed. push: commit a folder's current files to a repository branch as one commit (creates the repository if needed; private unless private=false; .gitignore respected); repeat pushes of a folder go to the same place. clone: fetch a repository's files into a folder. create_repo: a new repository. create_pr: open a pull request from head into base. Needs the user's GitHub token (Settings → Accounts).`,input_schema:B({action:{type:`string`,enum:[`status`,`push`,`clone`,`create_repo`,`create_pr`]},path:{type:`string`,description:`folder to push, or to clone into`},repo:{type:`string`,description:`owner/name, or just name for your own account`},branch:{type:`string`},message:{type:`string`,description:`commit message`},private:{type:`boolean`},title:{type:`string`},body:{type:`string`},head:{type:`string`,description:`create_pr: the branch with the changes`},base:{type:`string`,description:`create_pr: the branch to merge into (default branch if omitted)`}},[`action`]),cap:e=>e.action===`status`?null:`net`,describe:e=>e.action===`push`?`Push ${e.path??`.`} to GitHub${e.repo?` (${e.repo})`:``}`:e.action===`create_pr`?`Open a pull request: ${e.title??``}`:`GitHub: ${e.action} ${e.repo??``}`,async run(e,t){let n=await import(`./publish-CHt_Qrq5.js`),r=e=>t.progress(e+`
431
+ `);if(e.action===`status`){let e=await n.github(t.os).then(e=>e.user()).then(e=>`Signed in to GitHub as ${e.login}.`,e=>e.message),r=t.os.settings.get(`publish.links`,{});return`${e}\nFolders and where they were published:\n${JSON.stringify(r,null,2)}`}if(e.action===`push`)return n.pushFolder(t.os,t.path(e.path??`.`),{repo:e.repo,branch:e.branch,message:e.message,private:e.private},r);if(e.action===`clone`){if(!e.repo)throw Error(`clone needs repo`);return n.cloneRepo(t.os,e.repo,e.path?t.path(e.path):null,t.shell.cwd,{branch:e.branch},r)}let i=await n.github(t.os);if(e.action===`create_repo`){if(!e.repo)throw Error(`create_repo needs repo`);let t=await i.createRepo(e.repo.split(`/`).pop(),{private:e.private??!0,org:e.repo.includes(`/`)?e.repo.split(`/`)[0]:void 0});return`Created ${t.full_name}: ${t.html_url}`}let a=await n.repoName(i,e.repo??n.linksFor(t.os,t.shell.cwd).github?.repo??``);if(!e.head||!e.title)throw Error(`create_pr needs head and title`);let o=await i.createPr(a,{head:e.head,base:e.base,title:e.title,body:e.body});return`Opened pull request #${o.number}: ${o.html_url}`}}),z({name:`deploy`,description:`Build a web project for production (pages bundled and minified, npm packages included) and publish it as a static site: netlify, vercel or github-pages. Returns the live URL. The first deploy of a folder needs a target; later ones reuse it and update the same site. A server.ts backend is not deployed (static hosting). Needs the user's token for that host (Settings → Accounts).`,input_schema:B({path:{type:`string`,description:`project folder (default: working directory)`},target:{type:`string`,enum:[`netlify`,`vercel`,`github-pages`]},name:{type:`string`,description:`site or project name (first deploy)`},repo:{type:`string`,description:`github-pages: owner/name`}}),cap:()=>`net`,describe:e=>`Deploy ${e.path??`.`}${e.target?` to ${e.target}`:``}`,async run(e,t){let n=await(await import(`./publish-CHt_Qrq5.js`)).deployFolder(t.os,t.path(e.path??`.`),{target:e.target,name:e.name,repo:e.repo},e=>t.progress(e+`
432
432
  `));return`Deployed ${n.files} files to ${n.target}: ${n.url}${n.note}`}})],q=(e,t)=>e.every(e=>v(`/home/agent`,t.path(e))||v(`/tmp`,t.path(e)))?null:`fs.write`;function Rt(e){let t=Math.min(e.length,4096);for(let n=0;n<t;n++)if(e[n]===0)return!0;return!1}const zt=[z({name:`read_file`,description:`Read a text file from the virtual filesystem. Returns lines prefixed with line numbers. Use offset/limit (in lines) for large files.`,input_schema:B({path:{type:`string`},offset:{type:`integer`,description:`1-based first line`},limit:{type:`integer`,description:`max lines (default 2000)`}},[`path`]),cap:()=>null,describe:e=>`Read ${e.path}`,async run(e,t){let n=await t.os.fs.readFile(t.path(e.path));if(Rt(n))return`(binary file, ${n.length} bytes)`;let r=new TextDecoder().decode(n).split(`
433
433
  `),i=Math.max(1,e.offset??1),a=r.slice(i-1,i-1+(e.limit??2e3));return V(a.map((e,t)=>`${String(i+t).padStart(5)}\t${e}`).join(`
434
434
  `)+(i-1+a.length<r.length?`\n(${r.length} lines total; showing ${i}–${i+a.length-1})`:``),6e4)||`(empty file)`}}),z({name:`write_file`,description:`Create or overwrite a file with the given content. Parent directories are created automatically.`,input_schema:B({path:{type:`string`},content:{type:`string`}},[`path`,`content`]),cap:(e,t)=>q([e.path],t),describe:e=>`Write ${e.path} (${e.content.length} chars)`,async run(e,t){return await t.os.fs.writeFile(t.path(e.path),e.content),`Wrote ${e.content.length} characters to ${t.path(e.path)}`}}),z({name:`edit_file`,description:`Replace an exact string in a file. old_string must match exactly and be unique unless replace_all is true. Prefer this over rewriting whole files.`,input_schema:B({path:{type:`string`},old_string:{type:`string`},new_string:{type:`string`},replace_all:{type:`boolean`}},[`path`,`old_string`,`new_string`]),cap:(e,t)=>q([e.path],t),describe:e=>`Edit ${e.path}`,async run(e,t){let n=t.path(e.path),r=await t.os.fs.readText(n);if(!e.old_string)throw Error(`old_string must not be empty`);let i=r.split(e.old_string).length-1;if(i===0)throw Error(`old_string was not found in the file. Read the file again and match it exactly, including whitespace.`);if(i>1&&!e.replace_all)throw Error(`old_string occurs ${i} times. Add surrounding context to make it unique, or set replace_all.`);return await t.os.fs.writeFile(n,e.replace_all?r.split(e.old_string).join(e.new_string):r.replace(e.old_string,()=>e.new_string)),`Edited ${n} (${e.replace_all?i:1} replacement${i>1&&e.replace_all?`s`:``})`}}),z({name:`list_dir`,description:`List a directory: name, kind, size and modification time of each entry.`,input_schema:B({path:{type:`string`,description:`defaults to the working directory`}}),cap:()=>null,describe:e=>`List ${e.path??`.`}`,async run(e,t){let n=await t.os.fs.readdir(t.path(e.path??`.`));return n.length?V(n.map(e=>`${e.kind===`dir`?`dir `:`file`} ${String(e.size).padStart(9)} ${e.mtime?new Date(e.mtime).toISOString().slice(0,16):` `} ${e.name}${e.kind===`dir`?`/`:``}`).join(`
@@ -455,7 +455,7 @@ Continue the task from where you left off. Do not redo finished work.`:``}`}]}],
455
455
  `)[0].slice(0,100)}\n`):e.type===`error`&&i(`error: ${e.message}\n`)},ask:async()=>`Sub-agents cannot ask the user. Use your best judgement and note the assumption in your report.`,prompter:this.host.prompter},{ppid:this.proc.pid,depth:this.#n+1,persona:a}),s=()=>o.stop();r.addEventListener(`abort`,s);try{return await o.send(t),r.throwIfAborted(),o.lastText()||`(the sub-agent produced no report)`}finally{r.removeEventListener(`abort`,s),o.dispose()}}#g(){let e=this.messages.at(-1);if(e?.role!==`assistant`)return;let t=e.content.filter(e=>e.type===`tool_use`);t.length&&this.#c({role:`user`,content:t.map(e=>({type:`tool_result`,tool_use_id:e.id,content:`Interrupted before this tool ran.`,is_error:!0}))})}};const en=`${r}/.sessions`;async function tn(e,t){await e.fs.writeFile(`${en}/${t.id}.json`,JSON.stringify(t))}async function nn(e,t){return JSON.parse(await e.fs.readText(`${en}/${t}.json`))}function rn(e){let t=e.find(e=>e.role===`user`)?.content.find(e=>e.type===`text`),n=(t?.type===`text`?t.text.replace(/<file path="[^"]*"[^>]*?(?:\/>|>[\s\S]*?<\/file>)/g,``).replace(/<mode>[\s\S]*?<\/mode>/g,``):``).trim().replace(/\s+/g,` `);return n.length>60?n.slice(0,57)+`…`:n||`New session`}var an=class{os;#e=/* @__PURE__ */ new Map;constructor(e){this.os=e,e.bus.on(`proc:exit`,({proc:e})=>{for(let[t,n]of this.#e)n.agent.proc.pid===e.pid&&this.#e.delete(t)})}async create(e={}){let t=e.resume?await nn(this.os,e.resume):null,n=t&&this.#e.get(t.id);if(n)return this.#n(t.id,n);let r={listeners:/* @__PURE__ */ new Set,asker:null,waiting:[],created:Date.now(),private:!e.resume&&!!e.private},i=new $t(this.os,{onEvent:e=>{for(let t of[...r.listeners])t(e);(e.type===`done`||e.type===`usage`)&&this.#t(r)},ask:(e,t)=>r.asker?r.asker(e,t):new Promise(n=>r.waiting.push({q:e,options:t,resolve:n})),get prompter(){return r.prompter}},{ppid:e.ppid,id:t?.id});return r.agent=i,t&&(i.messages=t.messages,i.transcript=t.transcript??t.messages,i.todos=t.todos??[],i.checkpoints.list=t.checkpoints??[],i.diffs=t.diffs??{}),this.#e.set(i.id,r),this.#n(i.id,r)}async attach(e){let t=this.#e.get(e);if(!t)throw Error(`no live agent session: ${e}`);return this.#n(e,t)}async live(){return[...this.#e.entries()].filter(([,e])=>!e.private).sort((e,t)=>t[1].created-e[1].created).map(([e,t])=>({sid:e,pid:t.agent.proc.pid,busy:t.agent.busy,title:rn(t.agent.transcript)}))}probeMcp(e){return this.os.mcp.probe(e)}async probeModels(e,t=`local`){return st(e,await this.os.secrets.get(t===`local`?U.local:U.openai),void 0,{kind:t,relay:t===`openai`?W(this.os).corsRelay:``})}async#t(e){!e.private&&e.agent.transcript.length&&await tn(this.os,{id:e.agent.id,title:rn(e.agent.transcript),updated:Date.now(),messages:e.agent.messages,transcript:e.agent.transcript,todos:e.agent.todos,checkpoints:e.agent.checkpoints.list,diffs:e.agent.diffs}).catch(e=>this.os.notify({title:`Could not save the agent session`,body:e.message,level:`warn`}))}#n(e,t){let n=/* @__PURE__ */ new Set,r=null,i=this.#e,a=()=>{for(let e of n)t.listeners.delete(e);n.clear(),t.asker===r&&(t.asker=null)};return{sid:e,pid:t.agent.proc.pid,send:(e,n)=>t.agent.send(e,n),rewind:async(e,n)=>{let r=await t.agent.rewind(e,n);return await this.#t(t),r},changes:async()=>t.agent.checkpoints.list.map(e=>({turn:e.turn,at:e.at,files:e.files.map(e=>({path:e.path,before:e.binary?null:e.before,existed:e.before!==null||!!e.skipped,binary:!!e.binary,skipped:!!e.skipped}))})),stop:()=>t.agent.stop(),context:async()=>t.agent.context(),compact:()=>t.agent.compact(),async snapshot(){return{sid:e,private:t.private,pid:t.agent.proc.pid,busy:t.agent.busy,title:rn(t.agent.transcript),messages:t.agent.transcript,todos:t.agent.todos,total:{...t.agent.total},context:t.agent.context(),diffs:t.agent.diffs}},onEvent(e){return n.add(e),t.listeners.add(e),()=>{n.delete(e),t.listeners.delete(e)}},onAsk(e){r=t.asker=e;for(let n of t.waiting.splice(0))e(n.q,n.options).then(n.resolve)},get prompter(){return t.prompter},set prompter(e){t.prompter=e},detach(){if(t.private)return this.dispose();a()},dispose(){a(),i.delete(e),t.agent.dispose()}}}};function on(e){e.mcp=new Ye(e),e.agents=new an(e),Ue(...ct),e.seeders.push(async()=>{if(await e.fs.exists(`/home/agent/skills`))return;let{SEED:t}=await Promise.resolve().then(()=>Ct);for(let[n,r]of t)await e.fs.writeFile(n,r)})}const sn={box:null,storage:`opfs`};function cn(e){let t=/^bbx-box:(opfs|memory):([A-Za-z0-9_-]{1,64})$/.exec(e);return t?{box:t[2],storage:t[1]}:sn}function ln(e,t){return t.storage===`memory`?null:t.box===null?e:`${e}:box:${t.box}`}var un=class{#e=/* @__PURE__ */ new Map;on(e,t){let n=this.#e.get(e);return n||this.#e.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}emit(e,t){let n=this.#e.get(e);if(n)for(let r of[...n])try{r(t)}catch(t){console.error(`[bus] handler for "${String(e)}" threw`,t)}}};function dn(){let e=globalThis,t=globalThis.navigator??{},n=(e,t)=>typeof e==`object`&&!!e&&t in e,r=(e,t,n,r,i)=>({id:e,group:t,label:n,ok:!!r,use:i});return[r(`wasm`,`Compute`,`WebAssembly`,n(e,`WebAssembly`),`Rust kernel core, WASI programs, Pyodide`),r(`wasm-streaming`,`Compute`,`WASM streaming compile`,typeof WebAssembly?.instantiateStreaming==`function`,`Fast kernel boot`),r(`workers`,`Compute`,`Web Workers`,n(e,`Worker`),`Sandboxed code execution`),r(`sab`,`Compute`,`SharedArrayBuffer`,n(e,`SharedArrayBuffer`)&&e.crossOriginIsolated===!0,`Threads (needs cross-origin isolation)`),r(`webgpu`,`Compute`,`WebGPU`,n(t,`gpu`),`GPU compute tool, GPU Lab, in-browser LLM`),r(`scheduler`,`Compute`,`Scheduler API`,n(e,`scheduler`),`Prioritised background work`),r(`compression`,`Compute`,`Compression Streams`,n(e,`CompressionStream`),`gzip / gunzip`),r(`crypto`,`Compute`,`Web Crypto`,n(e.crypto,`subtle`),`Secret encryption, hashing`),r(`opfs`,`Storage`,`Origin Private File System`,n(t.storage,`getDirectory`),`Persistent root filesystem`),r(`fsaccess`,`Storage`,`File System Access`,n(e,`showDirectoryPicker`),`Mount real folders at /mnt`),r(`indexeddb`,`Storage`,`IndexedDB`,n(e,`indexedDB`),`Encrypted secrets`),r(`persist`,`Storage`,`Persistent storage`,n(t.storage,`persist`),`Protect data from eviction`),r(`cache`,`Storage`,`Cache Storage`,n(e,`caches`),`Offline boot, model weights`),r(`sw`,`System`,`Service Worker`,n(t,`serviceWorker`),`Instant offline boot`),r(`locks`,`System`,`Web Locks`,n(t,`locks`),`Cross-tab coordination`),r(`broadcast`,`System`,`BroadcastChannel`,n(e,`BroadcastChannel`),`Cross-tab filesystem events`),r(`notifications`,`System`,`Notifications`,n(e,`Notification`),`Agent task alerts`),r(`clipboard`,`System`,`Async Clipboard`,n(t,`clipboard`),`Clipboard tools`),r(`wakelock`,`System`,`Screen Wake Lock`,n(t,`wakeLock`),`Keep awake during long agent runs`),r(`share`,`System`,`Web Share`,n(t,`share`),`Share files`),r(`viewtransitions`,`System`,`View Transitions`,n(globalThis.document,`startViewTransition`),`Window animations`),r(`memory`,`System`,`Memory measurement`,n(globalThis.performance,`memory`)||n(globalThis.performance,`measureUserAgentSpecificMemory`),`Task Manager`),r(`battery`,`System`,`Battery Status`,n(t,`getBattery`),`System monitor`),r(`fetch-stream`,`Network`,`Streaming fetch`,n(e,`ReadableStream`),`LLM token streaming`),r(`websocket`,`Network`,`WebSocket`,n(e,`WebSocket`),`Realtime connections`),r(`webrtc`,`Network`,`WebRTC`,n(e,`RTCPeerConnection`),`Peer-to-peer`),r(`webtransport`,`Network`,`WebTransport`,n(e,`WebTransport`),`Low-latency transport`),r(`netinfo`,`Network`,`Network Information`,n(t,`connection`),`System monitor`),r(`offscreen`,`Graphics & Media`,`OffscreenCanvas`,n(e,`OffscreenCanvas`),`Off-thread rendering`),r(`webgl2`,`Graphics & Media`,`WebGL 2`,n(e,`WebGL2RenderingContext`),`Graphics fallback`),r(`webcodecs`,`Graphics & Media`,`WebCodecs`,n(e,`VideoEncoder`),`Media processing`),r(`webaudio`,`Graphics & Media`,`Web Audio`,n(e,`AudioContext`),`Sound`),r(`speech-tts`,`Graphics & Media`,`Speech synthesis`,n(e,`speechSynthesis`),`Agent speak tool`),r(`speech-stt`,`Graphics & Media`,`Speech recognition`,n(e,`SpeechRecognition`)||n(e,`webkitSpeechRecognition`),`Voice input`),r(`capture`,`Graphics & Media`,`Screen Capture`,n(t.mediaDevices,`getDisplayMedia`),`Screenshots`),r(`usb`,`Devices`,`WebUSB`,n(t,`usb`),`Hardware access`),r(`serial`,`Devices`,`Web Serial`,n(t,`serial`),`Hardware access`),r(`bluetooth`,`Devices`,`Web Bluetooth`,n(t,`bluetooth`),`Hardware access`),r(`hid`,`Devices`,`WebHID`,n(t,`hid`),`Hardware access`),r(`gamepad`,`Devices`,`Gamepad`,n(t,`getGamepads`),`Input`),r(`prompt-api`,`AI`,`Built-in Prompt API`,n(e,`LanguageModel`),`On-device model`),r(`webnn`,`AI`,`WebNN`,n(t,`ml`),`Neural network acceleration`)]}var fn=new URL(`kcore-COUztiEr.wasm`,import.meta.url).href;const pn=new TextEncoder;var mn=class{#e=null;#t=null;get loaded(){return this.#e!==null}load(){return this.#t??=(async()=>{try{let{instance:e}=await WebAssembly.instantiateStreaming(fetch(fn),{});this.#e=e.exports}catch(e){console.warn(`[kcore] wasm unavailable, using JS fallbacks`,e)}})()}#n(e,t){let n=this.#e,r=n.alloc(e.length);try{return new Uint8Array(n.memory.buffer,r,e.length).set(e),t(n,r)}finally{n.dealloc(r,e.length)}}hash(e){if(this.#e)return this.#n(e,(t,n)=>BigInt.asUintN(64,t.fnv1a64(n,e.length)).toString(16).padStart(16,`0`));let t=14695981039346656037n;for(let n of e)t=BigInt.asUintN(64,(t^BigInt(n))*1099511628211n);return t.toString(16).padStart(16,`0`)}searchLines(e,t,n=!1,r=1e3){let i=pn.encode(t);if(this.#e)return this.#n(e,(t,a)=>{let o=t.alloc(i.length),s=t.alloc(r*8);try{new Uint8Array(t.memory.buffer,o,i.length).set(i);let c=t.search_lines(a,e.length,o,i.length,+!!n,s,r),l=new DataView(t.memory.buffer,s,r*8),u=[];for(let e=0;e<Math.min(c,r);e++)u.push({line:l.getUint32(e*8,!0),offset:l.getUint32(e*8+4,!0)});return{total:c,matches:u}}finally{t.dealloc(o,i.length),t.dealloc(s,r*8)}});let a=new TextDecoder().decode(e),o=n?t.toLowerCase():t,s=[],c=0,l=0;return a.split(`
456
456
  `).forEach((e,t)=>{(n?e.toLowerCase():e).includes(o)&&(s.length<r&&s.push({line:t+1,offset:l}),c++),l+=pn.encode(e).length+1}),{total:c,matches:s}}wc(e){if(this.#e)return this.#n(e,(t,n)=>{let r=t.alloc(12);try{t.wc(n,e.length,r);let i=new DataView(t.memory.buffer,r,12);return{lines:i.getUint32(0,!0),words:i.getUint32(4,!0),bytes:i.getUint32(8,!0)}}finally{t.dealloc(r,12)}});let t=new TextDecoder().decode(e);return{lines:(t.match(/\n/g)??[]).length,words:(t.match(/\S+/g)??[]).length,bytes:e.length}}estimateTokens(e){if(this.#e){let t=pn.encode(e);return this.#n(t,(e,n)=>e.estimate_tokens(n,t.length))}return Math.ceil(e.length/3.6)}};let hn=null,J=null;function gn(e){hn=e,J=null}function _n(){return hn?(J??=hn().catch(e=>{throw J=null,e}),J):Promise.reject(/* @__PURE__ */ Error(`esbuild is not available here`))}const vn=`0.25.5`,yn=`https://cdn.jsdelivr.net/npm/esbuild-wasm@${vn}/`,bn=[`esm/browser.min.js`,`esbuild.wasm`];async function xn(e,t){e.isInstalled(`esbuild`)||(t(`installing the esbuild package for the dev server`),await e.install(`esbuild`));let n=await caches.open(C),r=async e=>await n.match(`https://cdn.jsdelivr.net/npm/esbuild-wasm@0.25.5/`+e)??fetch(`https://cdn.jsdelivr.net/npm/esbuild-wasm@0.25.5/`+e),i=await(await r(bn[0])).text(),a=URL.createObjectURL(new Blob([i],{type:`text/javascript`}));try{let e=await import(
457
457
  /* @vite-ignore */
458
- a),n=await WebAssembly.compile(await(await r(bn[1])).arrayBuffer());return await e.initialize({wasmModule:n,worker:!1}),t(`esbuild ${vn} ready`),e}finally{URL.revokeObjectURL(a)}}var Sn=class{os;#e=null;constructor(e){this.os=e}#t(){return this.#e??=import(`./server-CnIXpfUH.js`).then(e=>new e.DevServers(this.os)),this.#e}start(e){return this.#t().then(t=>t.start(e))}async stop(e){return this.#e?(await this.#e).stop(e):!1}async list(){return this.#e?(await this.#e).list():[]}page(e,t){return this.#t().then(n=>n.page(e,t))}request(e,t){return this.#t().then(n=>n.request(e,t))}log(e,t){this.#e?.then(n=>n.log(e,t))}async logs(e,t){if(!this.#e)throw Error(`nothing is serving on port ${e} (see: serve list)`);return(await this.#e).logs(e,t)}},Cn=class{settings;#e=async()=>`deny`;constructor(e){this.settings=e}setPrompter(e){this.#e=e}prompt(e,t){return this.#e(e,t)}get mode(){return this.settings.get(`perms.mode`,`ask`)}set mode(e){this.settings.set(`perms.mode`,e)}grants(){return this.settings.get(`perms.grants`,[])}revoke(e){this.settings.set(`perms.grants`,this.grants().filter(t=>t!==e))}isGranted(e){return this.mode===`auto`||this.grants().includes(e)}async request(e,t){if(this.isGranted(e.cap))return!0;let n=await(t??this.#e)(e);return n===`always`&&this.settings.set(`perms.grants`,[.../* @__PURE__ */ new Set([...this.grants(),e.cap])]),n!==`deny`}},wn=class{bus;#e=1;#t=/* @__PURE__ */ new Map;constructor(e){this.bus=e}spawn(e){let t=new AbortController,n={pid:e.pid??this.#e++,ppid:e.ppid??0,name:e.name,kind:e.kind,started:Date.now(),state:`running`,detail:e.detail??``,cpuMs:0,memBytes:0,signal:t.signal};return this.#t.set(n.pid,{proc:n,ctl:t,onKill:e.onKill}),this.bus.emit(`proc:spawn`,n),n}update(e,t){let n=this.#t.get(e);n&&(Object.assign(n.proc,t),this.bus.emit(`proc:update`,n.proc))}account(e,t){let n=this.#t.get(e);n&&(n.proc.cpuMs+=t)}kill(e,t=`killed`){let n=this.#t.get(e);if(!n)return!1;this.#t.delete(e);for(let n of this.list())n.ppid===e&&this.kill(n.pid,t);n.ctl.abort(new DOMException(t,`AbortError`));try{n.onKill?.()}catch(e){console.error(`[proc] onKill for ${n.proc.name} threw`,e)}return this.bus.emit(`proc:exit`,{proc:n.proc,reason:t}),!0}exit(e){this.kill(e,`exit`)}get(e){return this.#t.get(e)?.proc}list(){return[...this.#t.values()].map(e=>e.proc)}},Y=class e extends Error{code;constructor(t,n,r){super(`${t}: ${r??e.text[t]}, '${n}'`),this.code=t,this.name=`FsError`}static text={ENOENT:`no such file or directory`,EEXIST:`file already exists`,ENOTDIR:`not a directory`,EISDIR:`is a directory`,EACCES:`permission denied`,ENOTEMPTY:`directory not empty`,EIO:`i/o error`}};const Tn=new TextEncoder;var En=class{label=`procfs`;readonly=!0;#e;constructor(e){this.#e={ps:()=>e.procs.list().map(e=>`${e.pid}\t${e.ppid}\t${e.kind}\t${e.state}\t${Math.round(e.cpuMs)}ms\t${e.name}\t${e.detail}`).join(`
458
+ a),n=await WebAssembly.compile(await(await r(bn[1])).arrayBuffer());return await e.initialize({wasmModule:n,worker:!1}),t(`esbuild ${vn} ready`),e}finally{URL.revokeObjectURL(a)}}var Sn=class{os;#e=null;constructor(e){this.os=e}#t(){return this.#e??=import(`./server-C5Sd62CK.js`).then(e=>new e.DevServers(this.os)),this.#e}start(e){return this.#t().then(t=>t.start(e))}async stop(e){return this.#e?(await this.#e).stop(e):!1}async list(){return this.#e?(await this.#e).list():[]}page(e,t){return this.#t().then(n=>n.page(e,t))}request(e,t){return this.#t().then(n=>n.request(e,t))}log(e,t){this.#e?.then(n=>n.log(e,t))}async logs(e,t){if(!this.#e)throw Error(`nothing is serving on port ${e} (see: serve list)`);return(await this.#e).logs(e,t)}},Cn=class{settings;#e=async()=>`deny`;constructor(e){this.settings=e}setPrompter(e){this.#e=e}prompt(e,t){return this.#e(e,t)}get mode(){return this.settings.get(`perms.mode`,`ask`)}set mode(e){this.settings.set(`perms.mode`,e)}grants(){return this.settings.get(`perms.grants`,[])}revoke(e){this.settings.set(`perms.grants`,this.grants().filter(t=>t!==e))}isGranted(e){return this.mode===`auto`||this.grants().includes(e)}async request(e,t){if(this.isGranted(e.cap))return!0;let n=await(t??this.#e)(e);return n===`always`&&this.settings.set(`perms.grants`,[.../* @__PURE__ */ new Set([...this.grants(),e.cap])]),n!==`deny`}},wn=class{bus;#e=1;#t=/* @__PURE__ */ new Map;constructor(e){this.bus=e}spawn(e){let t=new AbortController,n={pid:e.pid??this.#e++,ppid:e.ppid??0,name:e.name,kind:e.kind,started:Date.now(),state:`running`,detail:e.detail??``,cpuMs:0,memBytes:0,signal:t.signal};return this.#t.set(n.pid,{proc:n,ctl:t,onKill:e.onKill}),this.bus.emit(`proc:spawn`,n),n}update(e,t){let n=this.#t.get(e);n&&(Object.assign(n.proc,t),this.bus.emit(`proc:update`,n.proc))}account(e,t){let n=this.#t.get(e);n&&(n.proc.cpuMs+=t)}kill(e,t=`killed`){let n=this.#t.get(e);if(!n)return!1;this.#t.delete(e);for(let n of this.list())n.ppid===e&&this.kill(n.pid,t);n.ctl.abort(new DOMException(t,`AbortError`));try{n.onKill?.()}catch(e){console.error(`[proc] onKill for ${n.proc.name} threw`,e)}return this.bus.emit(`proc:exit`,{proc:n.proc,reason:t}),!0}exit(e){this.kill(e,`exit`)}get(e){return this.#t.get(e)?.proc}list(){return[...this.#t.values()].map(e=>e.proc)}},Y=class e extends Error{code;constructor(t,n,r){super(`${t}: ${r??e.text[t]}, '${n}'`),this.code=t,this.name=`FsError`}static text={ENOENT:`no such file or directory`,EEXIST:`file already exists`,ENOTDIR:`not a directory`,EISDIR:`is a directory`,EACCES:`permission denied`,ENOTEMPTY:`directory not empty`,EIO:`i/o error`}};const Tn=new TextEncoder;var En=class{label=`procfs`;readonly=!0;#e;constructor(e){this.#e={ps:()=>e.procs.list().map(e=>`${e.pid}\t${e.ppid}\t${e.kind}\t${e.state}\t${Math.round(e.cpuMs)}ms\t${e.name}\t${e.detail}`).join(`
459
459
  `)+`
460
460
  `,mounts:()=>e.fs.mounts().map(e=>`${e.fs.label}\t${e.point}\t${e.fs.readonly?`ro`:`rw`}`).join(`
461
461
  `)+`
@@ -463,7 +463,7 @@ a),n=await WebAssembly.compile(await(await r(bn[1])).arrayBuffer());return await
463
463
  `)+`
464
464
  `,uptime:()=>`${((performance.now()-e.bootStart)/1e3).toFixed(1)}\n`,version:()=>`BrowserBox ${e.version} (${navigator.userAgent})\n`,meminfo:async()=>{let e=await navigator.storage?.estimate?.().catch(()=>void 0),t=performance.memory;return[`DeviceMemoryGB:\t${navigator.deviceMemory??`unknown`}`,`JsHeapUsed:\t${t?.usedJSHeapSize??`unknown`}`,`JsHeapLimit:\t${t?.jsHeapSizeLimit??`unknown`}`,`StorageUsed:\t${e?.usage??`unknown`}`,`StorageQuota:\t${e?.quota??`unknown`}`,`Cores:\t${navigator.hardwareConcurrency??`unknown`}`].join(`
465
465
  `)+`
466
- `}}}async readFile(e){let t=this.#e[e.slice(1)];if(!t)throw new Y(e===`/`?`EISDIR`:`ENOENT`,e);return Tn.encode(await t())}async writeFile(e){throw new Y(`EACCES`,e)}async readdir(e){if(e!==`/`)throw new Y(`ENOTDIR`,e);return Object.keys(this.#e).map(e=>({path:`/`+e,name:e,kind:`file`,size:0,mtime:Date.now()}))}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t=e.slice(1);return t in this.#e?{path:e,name:t,kind:`file`,size:0,mtime:Date.now()}:null}async mkdir(e){throw new Y(`EACCES`,e)}async remove(e){throw new Y(`EACCES`,e)}};const Dn=`bbx-secrets`;function On(e){return e===null?Promise.reject(/* @__PURE__ */ Error(`in-memory`)):new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function X(e,t,n){return new Promise((r,i)=>{let a=n(e.transaction(`kv`,t).objectStore(`kv`));a.onsuccess=()=>r(a.result),a.onerror=()=>i(a.error)})}var kn=class{dbName;#e=null;#t=/* @__PURE__ */ new Map;constructor(e=Dn){this.dbName=e}#n(){return this.#e??=On(this.dbName)}async#r(e){let t=await X(e,`readonly`,e=>e.get(`#master`));if(t)return t;let n=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return await X(e,`readwrite`,e=>e.put(n,`#master`)),n}async get(e){try{let t=await this.#n(),n=await X(t,`readonly`,t=>t.get(e));if(!n)return this.#t.get(e)??null;let r=await crypto.subtle.decrypt({name:`AES-GCM`,iv:n.iv},await this.#r(t),n.data);return new TextDecoder().decode(r)}catch{return this.#t.get(e)??null}}async set(e,t){if(!t)return this.delete(e);try{let n=await this.#n(),r=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),i=await crypto.subtle.encrypt({name:`AES-GCM`,iv:r},await this.#r(n),new TextEncoder().encode(t));await X(n,`readwrite`,t=>t.put({iv:r,data:i},e))}catch{this.#t.set(e,t)}}async delete(e){this.#t.delete(e);try{await X(await this.#n(),`readwrite`,t=>t.delete(e))}catch{}}async has(e){return await this.get(e)!==null}},An=class{bus;onWrite;#e=/* @__PURE__ */ new Map;constructor(e,t){this.bus=e,this.onWrite=t}hydrate(e){this.#e=new Map(e);for(let[t,n]of e)this.bus.emit(`settings:change`,{key:t,value:n})}entries(){return[...this.#e]}get(e,t){return this.#e.has(e)?this.#e.get(e):t}set(e,t){this.applyRemote(e,t),this.onWrite?.(e,t)}delete(e){this.set(e,void 0)}applyRemote(e,t){t===void 0?this.#e.delete(e):this.#e.set(e,t),this.bus.emit(`settings:change`,{key:e,value:t})}keys(){return[...this.#e.keys()]}};const Z=`bbx-settings`;function jn(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function Mn(e=Z){if(e===null)return[];try{let t=await jn(e);return await new Promise((e,n)=>{let r=[],i=t.transaction(`kv`,`readonly`).objectStore(`kv`).openCursor();i.onsuccess=()=>{let t=i.result;if(!t)return e(r);r.push([String(t.key),t.value]),t.continue()},i.onerror=()=>n(i.error)})}catch{return[]}}async function Nn(e,t,n=Z){if(n!==null)try{let r=(await jn(n)).transaction(`kv`,`readwrite`).objectStore(`kv`);t===void 0?r.delete(e):r.put(t,e)}catch{}}var Pn=class{label;#e=/* @__PURE__ */ new Map;constructor(e,t){this.label=t,this.#e.set(`/`,e)}async#t(e,t=!1){let n=this.#e.get(e);if(n)return n;let r=await this.#t(h(e),t);try{let n=await r.getDirectoryHandle(g(e),{create:t});return this.#e.set(e,n),n}catch(t){throw this.#n(t,e)}}#n(e,t){let n=e?.name;return n===`NotFoundError`?new Y(`ENOENT`,t):n===`TypeMismatchError`?new Y(`ENOTDIR`,t):n===`NotAllowedError`||n===`SecurityError`?new Y(`EACCES`,t):n===`InvalidModificationError`?new Y(`ENOTEMPTY`,t):new Y(`EIO`,t,e?.message)}async readFile(e){try{let t=await(await this.#t(h(e))).getFileHandle(g(e));for(let e=0;;e++)try{return new Uint8Array(await(await t.getFile()).arrayBuffer())}catch(t){if(e>=4||t?.name!==`NotReadableError`)throw t;await new Promise(t=>setTimeout(t,20*(e+1)))}}catch(t){if(t instanceof Y)throw t;let n=this.#n(t,e);throw n.code===`ENOTDIR`?new Y(`EISDIR`,e):n}}async writeFile(e,t){try{let n=await(await(await this.#t(h(e))).getFileHandle(g(e),{create:!0})).createWritable();await n.write(t),await n.close()}catch(t){throw t instanceof Y?t:this.#n(t,e)}}async readdir(e){let t=await this.#t(e),n=e===`/`?`/`:e+`/`,r=[];for await(let[e,i]of t.entries()){let t=n+e;i.kind===`directory`?r.push(Promise.resolve({path:t,name:e,kind:`dir`,size:0,mtime:0})):r.push(i.getFile().then(n=>({path:t,name:e,kind:`file`,size:n.size,mtime:n.lastModified})).catch(()=>({path:t,name:e,kind:`file`,size:0,mtime:0})))}return Promise.all(r)}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t;try{t=await this.#t(h(e))}catch{return null}let n=g(e);try{let r=await(await t.getFileHandle(n)).getFile();return{path:e,name:n,kind:`file`,size:r.size,mtime:r.lastModified}}catch{try{return await t.getDirectoryHandle(n),{path:e,name:n,kind:`dir`,size:0,mtime:0}}catch{return null}}}async mkdir(e){await this.#t(e,!0)}async remove(e,t){if(e===`/`)throw new Y(`EACCES`,e);try{await(await this.#t(h(e))).removeEntry(g(e),{recursive:t})}catch(t){throw t instanceof Y?t:this.#n(t,e)}for(let t of[...this.#e.keys()])(t===e||t.startsWith(e+`/`))&&this.#e.delete(t)}},Fn=class{label=`memfs`;#e=/* @__PURE__ */ new Map([[`/`,{kind:`dir`,mtime:Date.now()}]]);async readFile(e){let t=this.#e.get(e);if(!t)throw new Y(`ENOENT`,e);if(t.kind===`dir`)throw new Y(`EISDIR`,e);return t.data.slice()}async writeFile(e,t){let n=this.#e.get(h(e));if(!n)throw new Y(`ENOENT`,h(e));if(n.kind!==`dir`)throw new Y(`ENOTDIR`,h(e));if(this.#e.get(e)?.kind===`dir`)throw new Y(`EISDIR`,e);this.#e.set(e,{kind:`file`,data:t.slice(),mtime:Date.now()})}async readdir(e){let t=this.#e.get(e);if(!t)throw new Y(`ENOENT`,e);if(t.kind!==`dir`)throw new Y(`ENOTDIR`,e);let n=e===`/`?`/`:e+`/`,r=[];for(let[e,t]of this.#e)e!==`/`&&e.startsWith(n)&&!e.slice(n.length).includes(`/`)&&r.push(this.#t(e,t));return r}async stat(e){let t=this.#e.get(e);return t?this.#t(e,t):null}async mkdir(e){if(e===`/`)return;let t=this.#e.get(e);if(t){if(t.kind===`dir`)return;throw new Y(`EEXIST`,e)}await this.mkdir(h(e)),this.#e.set(e,{kind:`dir`,mtime:Date.now()})}async remove(e,t){if(!this.#e.get(e))throw new Y(`ENOENT`,e);if(e===`/`)throw new Y(`EACCES`,e);let n=e+`/`,r=[...this.#e.keys()].filter(e=>e.startsWith(n));if(r.length&&!t)throw new Y(`ENOTEMPTY`,e);for(let e of r)this.#e.delete(e);this.#e.delete(e)}#t(e,t){return{path:e,name:g(e),kind:t.kind,size:t.data?.byteLength??0,mtime:t.mtime}}};const In=new TextEncoder,Ln=new TextDecoder;var Rn=class{bus;#e=[];#t;#n;constructor(e){this.bus=e,this.#t=new Promise(e=>this.#n=e)}get ready(){return this.#t}markReady(){this.#n()}mount(e,t){e=p(e),this.#e=this.#e.filter(t=>t.point!==e),this.#e.push({point:e,fs:t}),this.#e.sort((e,t)=>t.point.length-e.point.length),this.bus.emit(`fs:change`,{path:e,type:`mount`})}unmount(e){e=p(e),this.#e=this.#e.filter(t=>t.point!==e||t.point===`/`),this.bus.emit(`fs:change`,{path:e,type:`mount`})}mounts(){return this.#e}async#r(e){await this.#t;let t=p(e);for(let e of this.#e)if(v(e.point,t))return{fs:e.fs,rel:e.point===`/`?t:t.slice(e.point.length)||`/`,path:t};throw new Y(`ENOENT`,t,`no filesystem mounted`)}async readFile(e){let t=await this.#r(e);return t.fs.readFile(t.rel)}async readText(e){return Ln.decode(await this.readFile(e))}async writeFile(e,t){let n=await this.#r(e);if(n.fs.readonly)throw new Y(`EACCES`,n.path,`read-only filesystem`);let r=typeof t==`string`?In.encode(t):t;await n.fs.mkdir(h(n.rel)),await n.fs.writeFile(n.rel,r),this.bus.emit(`fs:change`,{path:n.path,type:`write`})}async appendFile(e,t){let n=typeof t==`string`?In.encode(t):t,r=/* @__PURE__ */ new Uint8Array;try{r=await this.readFile(e)}catch(e){if(!(e instanceof Y&&e.code===`ENOENT`))throw e}let i=new Uint8Array(r.length+n.length);i.set(r),i.set(n,r.length),await this.writeFile(e,i)}async readdir(e){let t=await this.#r(e),n=(await t.fs.readdir(t.rel)).map(e=>({...e,path:_(t.path,e.name)}));for(let e of this.#e)e.point!==`/`&&h(e.point)===t.path&&!n.some(t=>t.name===g(e.point))&&n.push({path:e.point,name:g(e.point),kind:`dir`,size:0,mtime:0});return n.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`dir`?-1:1)}async stat(e){let t=p(e);if(await this.#t,this.#e.some(e=>e.point===t))return{path:t,name:g(t),kind:`dir`,size:0,mtime:0};let n=await this.#r(t),r=await n.fs.stat(n.rel);return r?{...r,path:n.path,name:g(n.path)}:null}async exists(e){return await this.stat(e).catch(()=>null)!==null}async mkdir(e){let t=await this.#r(e);if(t.fs.readonly)throw new Y(`EACCES`,t.path,`read-only filesystem`);await t.fs.mkdir(t.rel),this.bus.emit(`fs:change`,{path:t.path,type:`mkdir`})}async rm(e,t={}){let n=await this.#r(e);if(n.fs.readonly)throw new Y(`EACCES`,n.path,`read-only filesystem`);if(this.#e.some(e=>e.point===n.path))throw new Y(`EACCES`,n.path,`is a mount point`);await n.fs.remove(n.rel,t.recursive??!1),this.bus.emit(`fs:change`,{path:n.path,type:`remove`})}async cp(e,t){let n=await this.stat(e);if(!n)throw new Y(`ENOENT`,e);if(n.kind===`file`)return this.writeFile(t,await this.readFile(e));if(v(e,t))throw new Y(`EACCES`,t,`cannot copy a directory into itself`);await this.mkdir(t);for(let n of await this.readdir(e))await this.cp(n.path,_(t,n.name))}async mv(e,t){p(e)!==p(t)&&(await this.cp(e,t),await this.rm(e,{recursive:!0}))}async*walk(e,t={}){let n=[[p(e),0]];for(;n.length;){let[e,r]=n.pop();t.signal?.throwIfAborted();let i;try{i=await this.readdir(e)}catch{continue}for(let e of i)yield e,e.kind===`dir`&&r+1<(t.maxDepth??32)&&e.path!==`/proc`&&n.push([e.path,r+1])}}async glob(e,t=`/`,n=2e3){let r=e.startsWith(`/`)?e:_(t,e).replace(/\/$/,``),i=r.search(/[*?{]/);if(i<0)return await this.exists(r)?[p(r)]:[];let a=h(r.slice(0,i)+`x`),o=te(r),s=[];for await(let e of this.walk(a))if(o.test(e.path)&&s.push(e.path),s.length>=n)break;return s.sort()}},zn=class{version=`0.1.0`;bootStart=0;bus=new un;settings=new An(this.bus,(e,t)=>{Nn(e,t,ln(Z,this.instance)),this.onSettingWritten?.(e,t)});onSettingWritten;secrets;instance;perms=new Cn(this.settings);procs=new wn(this.bus);fs=new Rn(this.bus);kcore=new mn;caps=dn();shells;ui=null;packages;dev=new Sn(this);constructor(e={}){this.instance=e.instance??sn,this.secrets=new kn(ln(Dn,this.instance)),this.packages=new je(this,e.packages),gn(()=>xn(this.packages,e=>this.log(`dev`,e)))}kernelLog=[];rootKind=`memory`;bootMarks=[];mark(e){this.bootMarks.push({name:e,at:Math.round(performance.now()*10)/10})}log(e,t){let n={t:Math.round(performance.now()),src:e,msg:t};this.kernelLog.push(n),this.kernelLog.length>500&&this.kernelLog.shift(),this.bus.emit(`kmsg`,n)}hasCap(e){return this.caps.find(t=>t.id===e)?.ok??!1}notify(e){this.bus.emit(`notify`,typeof e==`string`?{title:e}:e)}openApp(e,t){this.bus.emit(`app:open`,{id:e,args:t})}async start(){this.log(`kernel`,`BrowserBox ${this.version}`);let e=this.procs.spawn({name:`kernel`,kind:`service`,detail:`event bus, vfs, process table`});this.procs.update(e.pid,{state:`idle`});let t=this.kcore.load().then(()=>this.log(`kcore`,this.kcore.loaded?`WebAssembly core loaded`:`WebAssembly unavailable, using JavaScript fallbacks`));this.settings.hydrate(await Mn(ln(Z,this.instance))),this.log(`settings`,`${this.settings.keys().length} keys loaded`);let n=this.instance.box;n!==null&&this.log(`kernel`,`box ${n} (${this.instance.storage})`);try{if(this.instance.storage===`memory`)throw Error(`in-memory box`);let e=await navigator.storage.getDirectory();n!==null&&(e=await(await e.getDirectoryHandle(`boxes`,{create:!0})).getDirectoryHandle(n,{create:!0})),this.fs.mount(`/`,new Pn(e,`opfs`)),this.rootKind=`opfs`,this.log(`vfs`,`mounted opfs${n===null?``:` boxes/${n}`} on / (persistent)`)}catch(e){this.fs.mount(`/`,new Fn),this.log(`vfs`,this.instance.storage===`memory`?`mounted memfs on / (in-memory box)`:`OPFS unavailable (${e.message}): mounted memfs on / (not persistent)`)}this.fs.mount(`/tmp`,new Fn),this.fs.mount(`/proc`,new En(this)),this.fs.markReady(),this.log(`vfs`,`mounted memfs on /tmp, procfs on /proc`);try{await this.#e()}catch(e){this.log(`init`,`seeding the filesystem failed: ${e.message}`)}let r=this.packages.installed();this.log(`pkg`,r.length?`installed: ${r.join(`, `)}`:`no packages installed`);let i=this.hasCap(`webgpu`)?`WebGPU available`:`no WebGPU`;this.log(`caps`,`${this.caps.filter(e=>e.ok).length}/${this.caps.length} platform features · ${i} · ${navigator.hardwareConcurrency??`?`} cores`),navigator.storage?.persist?.().then(e=>this.log(`vfs`,e?`storage marked persistent`:`storage may be evicted under pressure`)).catch(()=>!1),await t,this.log(`kernel`,`ready`)}seeders=[];async#e(){if(this.instance.box!==null)await Promise.all([this.fs.mkdir(n),this.fs.mkdir(`/mnt`)]);else{for(let e of this.seeders)await e();await this.fs.exists(`/home/user/Welcome.md`)||(await Promise.all([this.fs.mkdir(`${n}/Documents`),this.fs.mkdir(r),this.fs.mkdir(`/mnt`)]),await this.fs.writeFile(`${n}/Welcome.md`,`# Welcome to BrowserBox
466
+ `}}}async readFile(e){let t=this.#e[e.slice(1)];if(!t)throw new Y(e===`/`?`EISDIR`:`ENOENT`,e);return Tn.encode(await t())}async writeFile(e){throw new Y(`EACCES`,e)}async readdir(e){if(e!==`/`)throw new Y(`ENOTDIR`,e);return Object.keys(this.#e).map(e=>({path:`/`+e,name:e,kind:`file`,size:0,mtime:Date.now()}))}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t=e.slice(1);return t in this.#e?{path:e,name:t,kind:`file`,size:0,mtime:Date.now()}:null}async mkdir(e){throw new Y(`EACCES`,e)}async remove(e){throw new Y(`EACCES`,e)}};const Dn=`bbx-secrets`;function On(e){return e===null?Promise.reject(/* @__PURE__ */ Error(`in-memory`)):new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function X(e,t,n){return new Promise((r,i)=>{let a=n(e.transaction(`kv`,t).objectStore(`kv`));a.onsuccess=()=>r(a.result),a.onerror=()=>i(a.error)})}var kn=class{dbName;#e=null;#t=/* @__PURE__ */ new Map;constructor(e=Dn){this.dbName=e}#n(){return this.#e??=On(this.dbName)}async#r(e){let t=await X(e,`readonly`,e=>e.get(`#master`));if(t)return t;let n=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return await X(e,`readwrite`,e=>e.put(n,`#master`)),n}async get(e){try{let t=await this.#n(),n=await X(t,`readonly`,t=>t.get(e));if(!n)return this.#t.get(e)??null;let r=await crypto.subtle.decrypt({name:`AES-GCM`,iv:n.iv},await this.#r(t),n.data);return new TextDecoder().decode(r)}catch{return this.#t.get(e)??null}}async set(e,t){if(!t)return this.delete(e);try{let n=await this.#n(),r=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),i=await crypto.subtle.encrypt({name:`AES-GCM`,iv:r},await this.#r(n),new TextEncoder().encode(t));await X(n,`readwrite`,t=>t.put({iv:r,data:i},e))}catch{this.#t.set(e,t)}}async delete(e){this.#t.delete(e);try{await X(await this.#n(),`readwrite`,t=>t.delete(e))}catch{}}async has(e){return await this.get(e)!==null}},An=class{bus;onWrite;#e=/* @__PURE__ */ new Map;constructor(e,t){this.bus=e,this.onWrite=t}hydrate(e){this.#e=new Map(e);for(let[t,n]of e)this.bus.emit(`settings:change`,{key:t,value:n})}entries(){return[...this.#e]}get(e,t){return this.#e.has(e)?this.#e.get(e):t}set(e,t){this.applyRemote(e,t),this.onWrite?.(e,t)}delete(e){this.set(e,void 0)}applyRemote(e,t){t===void 0?this.#e.delete(e):this.#e.set(e,t),this.bus.emit(`settings:change`,{key:e,value:t})}keys(){return[...this.#e.keys()]}};const Z=`bbx-settings`;function jn(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>r.result.createObjectStore(`kv`),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function Mn(e=Z){if(e===null)return[];try{let t=await jn(e);return await new Promise((e,n)=>{let r=[],i=t.transaction(`kv`,`readonly`).objectStore(`kv`).openCursor();i.onsuccess=()=>{let t=i.result;if(!t)return e(r);r.push([String(t.key),t.value]),t.continue()},i.onerror=()=>n(i.error)})}catch{return[]}}async function Nn(e,t,n=Z){if(n!==null)try{let r=(await jn(n)).transaction(`kv`,`readwrite`).objectStore(`kv`);t===void 0?r.delete(e):r.put(t,e)}catch{}}var Pn=class{label;#e=/* @__PURE__ */ new Map;constructor(e,t){this.label=t,this.#e.set(`/`,e)}async#t(e,t=!1){let n=this.#e.get(e);if(n)return n;let r=await this.#t(h(e),t);try{let n=await r.getDirectoryHandle(g(e),{create:t});return this.#e.set(e,n),n}catch(t){throw this.#n(t,e)}}#n(e,t){let n=e?.name;return n===`NotFoundError`?new Y(`ENOENT`,t):n===`TypeMismatchError`?new Y(`ENOTDIR`,t):n===`NotAllowedError`||n===`SecurityError`?new Y(`EACCES`,t):n===`InvalidModificationError`?new Y(`ENOTEMPTY`,t):new Y(`EIO`,t,e?.message)}async readFile(e){try{let t=await(await this.#t(h(e))).getFileHandle(g(e));for(let e=0;;e++)try{return new Uint8Array(await(await t.getFile()).arrayBuffer())}catch(t){if(e>=4||t?.name!==`NotReadableError`)throw t;await new Promise(t=>setTimeout(t,20*(e+1)))}}catch(t){if(t instanceof Y)throw t;let n=this.#n(t,e);throw n.code===`ENOTDIR`?new Y(`EISDIR`,e):n}}async writeFile(e,t){try{let n=await(await(await this.#t(h(e))).getFileHandle(g(e),{create:!0})).createWritable();await n.write(t),await n.close()}catch(t){throw t instanceof Y?t:this.#n(t,e)}}async readdir(e){let t=await this.#t(e),n=e===`/`?`/`:e+`/`,r=[];for await(let[e,i]of t.entries()){let t=n+e;i.kind===`directory`?r.push(Promise.resolve({path:t,name:e,kind:`dir`,size:0,mtime:0})):r.push(i.getFile().then(n=>({path:t,name:e,kind:`file`,size:n.size,mtime:n.lastModified})).catch(()=>({path:t,name:e,kind:`file`,size:0,mtime:0})))}return Promise.all(r)}async stat(e){if(e===`/`)return{path:e,name:``,kind:`dir`,size:0,mtime:0};let t;try{t=await this.#t(h(e))}catch{return null}let n=g(e);try{let r=await(await t.getFileHandle(n)).getFile();return{path:e,name:n,kind:`file`,size:r.size,mtime:r.lastModified}}catch{try{return await t.getDirectoryHandle(n),{path:e,name:n,kind:`dir`,size:0,mtime:0}}catch{return null}}}async mkdir(e){await this.#t(e,!0)}async remove(e,t){if(e===`/`)throw new Y(`EACCES`,e);try{await(await this.#t(h(e))).removeEntry(g(e),{recursive:t})}catch(t){throw t instanceof Y?t:this.#n(t,e)}for(let t of[...this.#e.keys()])(t===e||t.startsWith(e+`/`))&&this.#e.delete(t)}},Fn=class{label=`memfs`;#e=/* @__PURE__ */ new Map([[`/`,{kind:`dir`,mtime:Date.now()}]]);async readFile(e){let t=this.#e.get(e);if(!t)throw new Y(`ENOENT`,e);if(t.kind===`dir`)throw new Y(`EISDIR`,e);return t.data.slice()}async writeFile(e,t){let n=this.#e.get(h(e));if(!n)throw new Y(`ENOENT`,h(e));if(n.kind!==`dir`)throw new Y(`ENOTDIR`,h(e));if(this.#e.get(e)?.kind===`dir`)throw new Y(`EISDIR`,e);this.#e.set(e,{kind:`file`,data:t.slice(),mtime:Date.now()})}async readdir(e){let t=this.#e.get(e);if(!t)throw new Y(`ENOENT`,e);if(t.kind!==`dir`)throw new Y(`ENOTDIR`,e);let n=e===`/`?`/`:e+`/`,r=[];for(let[e,t]of this.#e)e!==`/`&&e.startsWith(n)&&!e.slice(n.length).includes(`/`)&&r.push(this.#t(e,t));return r}async stat(e){let t=this.#e.get(e);return t?this.#t(e,t):null}async mkdir(e){if(e===`/`)return;let t=this.#e.get(e);if(t){if(t.kind===`dir`)return;throw new Y(`EEXIST`,e)}await this.mkdir(h(e)),this.#e.set(e,{kind:`dir`,mtime:Date.now()})}async remove(e,t){if(!this.#e.get(e))throw new Y(`ENOENT`,e);if(e===`/`)throw new Y(`EACCES`,e);let n=e+`/`,r=[...this.#e.keys()].filter(e=>e.startsWith(n));if(r.length&&!t)throw new Y(`ENOTEMPTY`,e);for(let e of r)this.#e.delete(e);this.#e.delete(e)}#t(e,t){return{path:e,name:g(e),kind:t.kind,size:t.data?.byteLength??0,mtime:t.mtime}}};const In=new TextEncoder,Ln=new TextDecoder;var Rn=class{bus;#e=[];#t;#n;constructor(e){this.bus=e,this.#t=new Promise(e=>this.#n=e)}get ready(){return this.#t}markReady(){this.#n()}mount(e,t){e=p(e),this.#e=this.#e.filter(t=>t.point!==e),this.#e.push({point:e,fs:t}),this.#e.sort((e,t)=>t.point.length-e.point.length),this.bus.emit(`fs:change`,{path:e,type:`mount`})}unmount(e){e=p(e),this.#e=this.#e.filter(t=>t.point!==e||t.point===`/`),this.bus.emit(`fs:change`,{path:e,type:`mount`})}mounts(){return this.#e}async#r(e){await this.#t;let t=p(e);for(let e of this.#e)if(v(e.point,t))return{fs:e.fs,rel:e.point===`/`?t:t.slice(e.point.length)||`/`,path:t};throw new Y(`ENOENT`,t,`no filesystem mounted`)}async readFile(e){let t=await this.#r(e);return t.fs.readFile(t.rel)}async readText(e){return Ln.decode(await this.readFile(e))}async writeFile(e,t){let n=await this.#r(e);if(n.fs.readonly)throw new Y(`EACCES`,n.path,`read-only filesystem`);let r=typeof t==`string`?In.encode(t):t;await n.fs.mkdir(h(n.rel)),await n.fs.writeFile(n.rel,r),this.bus.emit(`fs:change`,{path:n.path,type:`write`})}async appendFile(e,t){let n=typeof t==`string`?In.encode(t):t,r=/* @__PURE__ */ new Uint8Array;try{r=await this.readFile(e)}catch(e){if(!(e instanceof Y&&e.code===`ENOENT`))throw e}let i=new Uint8Array(r.length+n.length);i.set(r),i.set(n,r.length),await this.writeFile(e,i)}async readdir(e){let t=await this.#r(e),n=(await t.fs.readdir(t.rel)).map(e=>({...e,path:_(t.path,e.name)}));for(let e of this.#e)e.point!==`/`&&h(e.point)===t.path&&!n.some(t=>t.name===g(e.point))&&n.push({path:e.point,name:g(e.point),kind:`dir`,size:0,mtime:0});return n.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`dir`?-1:1)}async stat(e){let t=p(e);if(await this.#t,this.#e.some(e=>e.point===t))return{path:t,name:g(t),kind:`dir`,size:0,mtime:0};let n=await this.#r(t),r=await n.fs.stat(n.rel);return r?{...r,path:n.path,name:g(n.path)}:null}async exists(e){return await this.stat(e).catch(()=>null)!==null}async mkdir(e){let t=await this.#r(e);if(t.fs.readonly)throw new Y(`EACCES`,t.path,`read-only filesystem`);await t.fs.mkdir(t.rel),this.bus.emit(`fs:change`,{path:t.path,type:`mkdir`})}async rm(e,t={}){let n=await this.#r(e);if(n.fs.readonly)throw new Y(`EACCES`,n.path,`read-only filesystem`);if(this.#e.some(e=>e.point===n.path))throw new Y(`EACCES`,n.path,`is a mount point`);await n.fs.remove(n.rel,t.recursive??!1),this.bus.emit(`fs:change`,{path:n.path,type:`remove`})}async cp(e,t){let n=await this.stat(e);if(!n)throw new Y(`ENOENT`,e);if(n.kind===`file`)return this.writeFile(t,await this.readFile(e));if(v(e,t))throw new Y(`EACCES`,t,`cannot copy a directory into itself`);await this.mkdir(t);for(let n of await this.readdir(e))await this.cp(n.path,_(t,n.name))}async mv(e,t){p(e)!==p(t)&&(await this.cp(e,t),await this.rm(e,{recursive:!0}))}async*walk(e,t={}){let n=[[p(e),0]];for(;n.length;){let[e,r]=n.pop();t.signal?.throwIfAborted();let i;try{i=await this.readdir(e)}catch{continue}for(let e of i)yield e,e.kind===`dir`&&r+1<(t.maxDepth??32)&&e.path!==`/proc`&&n.push([e.path,r+1])}}async glob(e,t=`/`,n=2e3){let r=e.startsWith(`/`)?e:_(t,e).replace(/\/$/,``),i=r.search(/[*?{]/);if(i<0)return await this.exists(r)?[p(r)]:[];let a=h(r.slice(0,i)+`x`),o=te(r),s=[];for await(let e of this.walk(a))if(o.test(e.path)&&s.push(e.path),s.length>=n)break;return s.sort()}},zn=class{version=`0.1.1`;bootStart=0;bus=new un;settings=new An(this.bus,(e,t)=>{Nn(e,t,ln(Z,this.instance)),this.onSettingWritten?.(e,t)});onSettingWritten;secrets;instance;perms=new Cn(this.settings);procs=new wn(this.bus);fs=new Rn(this.bus);kcore=new mn;caps=dn();shells;ui=null;packages;dev=new Sn(this);constructor(e={}){this.instance=e.instance??sn,this.secrets=new kn(ln(Dn,this.instance)),this.packages=new je(this,e.packages),gn(()=>xn(this.packages,e=>this.log(`dev`,e)))}kernelLog=[];rootKind=`memory`;bootMarks=[];mark(e){this.bootMarks.push({name:e,at:Math.round(performance.now()*10)/10})}log(e,t){let n={t:Math.round(performance.now()),src:e,msg:t};this.kernelLog.push(n),this.kernelLog.length>500&&this.kernelLog.shift(),this.bus.emit(`kmsg`,n)}hasCap(e){return this.caps.find(t=>t.id===e)?.ok??!1}notify(e){this.bus.emit(`notify`,typeof e==`string`?{title:e}:e)}openApp(e,t){this.bus.emit(`app:open`,{id:e,args:t})}async start(){this.log(`kernel`,`BrowserBox ${this.version}`);let e=this.procs.spawn({name:`kernel`,kind:`service`,detail:`event bus, vfs, process table`});this.procs.update(e.pid,{state:`idle`});let t=this.kcore.load().then(()=>this.log(`kcore`,this.kcore.loaded?`WebAssembly core loaded`:`WebAssembly unavailable, using JavaScript fallbacks`));this.settings.hydrate(await Mn(ln(Z,this.instance))),this.log(`settings`,`${this.settings.keys().length} keys loaded`);let n=this.instance.box;n!==null&&this.log(`kernel`,`box ${n} (${this.instance.storage})`);try{if(this.instance.storage===`memory`)throw Error(`in-memory box`);let e=await navigator.storage.getDirectory();n!==null&&(e=await(await e.getDirectoryHandle(`boxes`,{create:!0})).getDirectoryHandle(n,{create:!0})),this.fs.mount(`/`,new Pn(e,`opfs`)),this.rootKind=`opfs`,this.log(`vfs`,`mounted opfs${n===null?``:` boxes/${n}`} on / (persistent)`)}catch(e){this.fs.mount(`/`,new Fn),this.log(`vfs`,this.instance.storage===`memory`?`mounted memfs on / (in-memory box)`:`OPFS unavailable (${e.message}): mounted memfs on / (not persistent)`)}this.fs.mount(`/tmp`,new Fn),this.fs.mount(`/proc`,new En(this)),this.fs.markReady(),this.log(`vfs`,`mounted memfs on /tmp, procfs on /proc`);try{await this.#e()}catch(e){this.log(`init`,`seeding the filesystem failed: ${e.message}`)}let r=this.packages.installed();this.log(`pkg`,r.length?`installed: ${r.join(`, `)}`:`no packages installed`);let i=this.hasCap(`webgpu`)?`WebGPU available`:`no WebGPU`;this.log(`caps`,`${this.caps.filter(e=>e.ok).length}/${this.caps.length} platform features · ${i} · ${navigator.hardwareConcurrency??`?`} cores`),navigator.storage?.persist?.().then(e=>this.log(`vfs`,e?`storage marked persistent`:`storage may be evicted under pressure`)).catch(()=>!1),await t,this.log(`kernel`,`ready`)}seeders=[];async#e(){if(this.instance.box!==null)await Promise.all([this.fs.mkdir(n),this.fs.mkdir(`/mnt`)]);else{for(let e of this.seeders)await e();await this.fs.exists(`/home/user/Welcome.md`)||(await Promise.all([this.fs.mkdir(`${n}/Documents`),this.fs.mkdir(r),this.fs.mkdir(`/mnt`)]),await this.fs.writeFile(`${n}/Welcome.md`,`# Welcome to BrowserBox
467
467
 
468
468
  BrowserBox is an operating system for AI agents that runs entirely in this
469
469
  browser tab. Nothing leaves your machine except the model requests you configure.
@@ -479,4 +479,4 @@ The agent works in \`/home/agent\`. Files there survive reloads.
479
479
  `),await this.fs.writeFile(`${r}/MEMORY.md`,`# Agent memory
480
480
 
481
481
  Durable notes the agent keeps across sessions. Edit freely.
482
- `))}}async mountNativeFolder(){throw Error(`Mounting a folder needs a window: use Files → Mount.`)}mountHandle(e){let t=`/mnt/${e.name.replace(/[^\w.-]+/g,`_`)||`folder`}`;return this.fs.mount(t,new Pn(e,`native:${e.name}`)),t}},Bn={id:`esbuild`,version:vn,summary:`bundler for TypeScript, JSX and CSS (WebAssembly); used by serve`,commands:[`esbuild`],tools:[],default:!1,remote:bn.map(e=>yn+e),remoteBytes:4e6},Vn={id:`git`,version:`isomorphic-git 1.x`,summary:`Version control for repositories in the virtual filesystem (clone needs a relay; no push)`,commands:[`git`],tools:[],default:!0},Hn={id:`python`,version:`3.13.2 (Pyodide 0.29)`,summary:`CPython compiled to WebAssembly, with the standard library`,commands:[`python`,`python3`,`pip`,`pip3`],tools:[`run_python`],default:!1,remote:oe.map(e=>S+e),remoteBytes:12e6};const Un=/* #__PURE__ */ Object.assign({"./esbuild/manifest.ts":Bn,"./git/manifest.ts":Vn,"./python/manifest.ts":Hn,"./sqlite/manifest.ts":{id:`sqlite`,version:`SQLite 3 (sql.js)`,summary:`SQL database engine for .db files in the workspace`,commands:[`sqlite3`],tools:[],default:!0},"./zip/manifest.ts":{id:`zip`,version:`fflate`,summary:`Create and extract zip archives`,commands:[`zip`,`unzip`],tools:[],default:!0}}),Wn=/* #__PURE__ */ Object.assign({"./esbuild/index.ts":()=>import(`./pkg-esbuild-DxKODBC3.js`).then(e=>e.default),"./git/index.ts":()=>import(`./pkg-git-Ds2ZjUJG.js`).then(e=>e.default),"./python/index.ts":()=>import(`./pkg-python-Cps4de9u.js`).then(e=>e.default),"./sqlite/index.ts":()=>import(`./pkg-sqlite-BexM5lLo.js`).then(e=>e.default),"./zip/index.ts":()=>import(`./pkg-zip-B_IjTDzR.js`).then(e=>e.default)}),Gn=Object.values(Un).sort((e,t)=>e.id.localeCompare(t.id));function Kn(e){let t=Wn[`./${e}/index.ts`];return t?t():Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))}const qn={manifests:Gn,load:Kn};var Jn=class{os;#e=1;constructor(e){this.os=e}async open(e={}){let t=this.os,n=null,r=null,i=null,a=t.procs.spawn({name:`bbsh`,kind:`shell`,ppid:e.ppid,onKill:()=>i?.abort()});t.procs.update(a.pid,{state:`idle`});let o=We(new xe(t,{cwd:e.cwd,ppid:a.pid,confined:e.confined,prompter:e.prompter,tty:{readLine:(e,t)=>n?n(e,t?.secret??!1):Promise.resolve(null),clear:()=>r?.()}})),s={id:`sh${this.#e++}`,cwd:o.cwd,home:o.env.HOME??`/`,async run(e,n){if(a.signal.aborted)throw Error(`this shell has exited`);e.trim()&&o.history.at(-1)!==e&&o.history.push(e),i=new AbortController;let r=()=>i?.abort();n.signal?.addEventListener(`abort`,r),t.procs.update(a.pid,{state:`running`,detail:e.slice(0,60)});let c=performance.now();try{return await o.run(e,{out:n.out,err:n.err,signal:i.signal})}finally{n.signal?.removeEventListener(`abort`,r),i=null,s.cwd=o.cwd,t.procs.account(a.pid,performance.now()-c),t.procs.update(a.pid,{state:`idle`,detail:o.cwd})}},complete:e=>o.complete(e),onReadLine(e){n=e},onClear(e){r=e},close:()=>t.procs.exit(a.pid)};return s}};const Yn=Object.values(/* @__PURE__ */ Object.assign({"/src/apps/agent/manifest.ts":{id:`agent`,name:`Agent`,icon:`spark`,width:520,height:760,order:1,external:ne},"/src/apps/browser/manifest.ts":{id:`browser`,name:`Browser`,icon:`globe`,width:900,height:600,order:6},"/src/apps/editor/manifest.ts":{id:`editor`,name:`Editor`,icon:`edit`,width:820,height:560,order:4},"/src/apps/files/manifest.ts":{id:`files`,name:`Files`,icon:`folder`,width:780,height:500,order:3},"/src/apps/gpulab/manifest.ts":{id:`gpulab`,name:`GPU Lab`,icon:`cube`,width:860,height:580,order:7},"/src/apps/help/manifest.ts":{id:`help`,name:`Help`,icon:`question`,width:980,height:680,order:9,singleton:!0},"/src/apps/preview/manifest.ts":{id:`preview`,name:`Preview`,icon:`eye`,width:760,height:540,order:10,hidden:!0},"/src/apps/settings/manifest.ts":{id:`settings`,name:`Settings`,icon:`gear`,width:720,height:560,order:9,singleton:!0},"/src/apps/sysinfo/manifest.ts":{id:`sysinfo`,name:`System`,icon:`info`,width:760,height:540,order:8,singleton:!0},"/src/apps/taskmgr/manifest.ts":{id:`taskmgr`,name:`Task Manager`,icon:`activity`,width:760,height:500,order:5,singleton:!0},"/src/apps/terminal/manifest.ts":{id:`terminal`,name:`Terminal`,icon:`terminal`,width:760,height:480,order:2}})).sort((e,t)=>e.order-t.order);var Xn=class{port;#e=1;#t=/* @__PURE__ */ new Map;#n={};#r=/* @__PURE__ */ new Map;closed=!1;constructor(e){this.port=e,e.onmessage=e=>void this.#i(e.data)}handle(e){return Object.assign(this.#n,e),this}call(e,...t){return this.closed?Promise.reject(/* @__PURE__ */ Error(`connection closed`)):new Promise((n,r)=>{let i=this.#e++;this.#t.set(i,{resolve:n,reject:r}),this.port.postMessage({k:`call`,id:i,m:e,a:t})})}emit(e,t){this.closed||this.port.postMessage({k:`evt`,n:e,p:t})}on(e,t){let n=this.#r.get(e);return n||this.#r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}close(){if(!this.closed){this.closed=!0,this.port.close();for(let e of this.#t.values())e.reject(/* @__PURE__ */ Error(`connection closed`));this.#t.clear()}}async#i(e){if(e.k===`call`){let t=Object.hasOwn(this.#n,e.m)?this.#n[e.m]:void 0;try{if(!t)throw Error(`unknown method: ${e.m}`);let n=await t(...e.a);this.closed||this.port.postMessage({k:`ok`,id:e.id,v:n})}catch(t){let n=t;this.closed||this.port.postMessage({k:`err`,id:e.id,e:{name:n?.name??`Error`,message:n?.message??String(t)}})}}else if(e.k===`ok`||e.k===`err`){let t=this.#t.get(e.id);if(this.#t.delete(e.id),!t)return;if(e.k===`ok`)t.resolve(e.v);else{let n=Error(e.e.message);n.name=e.e.name,t.reject(n)}}else if(e.k===`evt`)for(let t of[...this.#r.get(e.n)??[]])try{t(e.p)}catch(t){console.error(`[rpc] listener for "${e.n}" threw`,t)}}};const Q=e=>({pid:e.pid,ppid:e.ppid,name:e.name,kind:e.kind,started:e.started,state:e.state,detail:e.detail,cpuMs:e.cpuMs,memBytes:e.memBytes}),Zn=[`fs:change`,`settings:change`,`notify`,`app:open`,`kmsg`,`dev:update`,`dev:log`];var Qn=class{os;shared;#e=/* @__PURE__ */ new Map;#t=1;#n=1;#r=1;#i=/* @__PURE__ */ new Map;#a=/* @__PURE__ */ new Map;#o=null;#s=[];constructor(e,t){this.os=e,this.shared=t;for(let t of Zn)e.bus.on(t,e=>this.#c(`bus`,{type:t,payload:e},this.#o));e.bus.on(`proc:spawn`,e=>this.#c(`bus`,{type:`proc:spawn`,payload:Q(e)})),e.bus.on(`proc:update`,e=>this.#c(`bus`,{type:`proc:update`,payload:Q(e)})),e.bus.on(`proc:exit`,({proc:e,reason:t})=>this.#c(`bus`,{type:`proc:exit`,payload:{proc:Q(e),reason:t}})),e.perms.setPrompter((e,t)=>this.#l({kind:`perm`,payload:e},t).catch(()=>`deny`)),e.ui={call:(e,...t)=>this.#l({kind:`ui`,payload:{method:e,args:t}},void 0,[...this.#e.values()].find(e=>e.role===`ui`))},ue({run:(e,t,n)=>this.#u(e,t,n),backend:(e,t,n,r)=>this.#d(e,t,n,r)})}use(e){return this.#s.push(e),this}#c(e,t,n=null){for(let r of this.#e.values())r.id!==n&&r.role===`ui`&&r.peer.emit(e,t)}#l(e,t,n){return new Promise((r,i)=>{let a=this.#n++,o={...e,askId:a},s=n?[n]:[...this.#e.values()].filter(e=>e.role===`ui`);if(!s.length)return i(/* @__PURE__ */ Error(`no window is connected to answer`));this.#i.set(a,{ask:o,resolve:e=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);r(e)}},targets:new Set(s.map(e=>e.id))}),t?.addEventListener(`abort`,()=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);i(t.reason)}});for(let e of s)e.peer.emit(`ask`,o)})}async#u(e,t,n){let r=[...this.#e.values()].find(e=>e.role===`host`);if(!r)return{ok:!1,stdout:``,stderr:``,ms:0,error:`No window is open to host the sandbox. Open the agent window or the desktop.`};let i=this.#r++;this.#a.set(i,n);let a=()=>r.peer.emit(`host:abort`,i);n.signal?.addEventListener(`abort`,a);try{return await r.peer.call(`host.run`,i,e,t,{cwd:n.cwd,timeoutMs:n.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{n.signal?.removeEventListener(`abort`,a),this.#a.delete(i)}}async#d(e,t,n,r){let i=[...this.#e.values()].find(e=>e.role===`host`);if(!i)return{ok:!1,stdout:``,stderr:``,ms:0,error:e===`request`?`backend not loaded`:`No window is open to host the backend. Open the agent window or the desktop.`};let a=this.#r++;this.#a.set(a,r);try{return await i.peer.call(`host.backend`,a,e,t,n,{cwd:r.cwd,timeoutMs:r.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{this.#a.delete(a)}}connect(e){let t=new Xn(e),n={id:this.#t++,peer:t,role:`new`,shells:/* @__PURE__ */ new Map,drops:[]},r=this.os,i=r.fs,a=this,o=e=>{this.#o=n.id;try{return e()}finally{this.#o=null}},s=e=>{let t=n.shells.get(e);if(!t)throw Error(`no such shell: ${e}`);return t};t.handle({async hello(e){return n.role=e,await i.ready,{clientId:n.id,pidBase:n.id*1e5,version:r.version,rootKind:r.rootKind,shared:a.shared,settings:r.settings.entries(),procs:r.procs.list().map(Q),mounts:i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),bootMarks:r.bootMarks,log:r.kernelLog}},"fs.readFile":e=>i.readFile(e),"fs.writeFile":(e,t)=>i.writeFile(e,t),"fs.appendFile":(e,t)=>i.appendFile(e,t),"fs.readdir":e=>i.readdir(e),"fs.stat":e=>i.stat(e),"fs.mkdir":e=>i.mkdir(e),"fs.rm":(e,t)=>i.rm(e,t),"fs.cp":(e,t)=>i.cp(e,t),"fs.mv":(e,t)=>i.mv(e,t),"fs.glob":(e,t,n)=>i.glob(e,t,n),"fs.unmount":e=>i.unmount(e),"fs.mounts":()=>i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),"fs.mountHandle":e=>r.mountHandle(e),"dev.start":e=>r.dev.start(e),"dev.stop":e=>r.dev.stop(e),"dev.list":()=>r.dev.list(),"dev.page":(e,t)=>r.dev.page(e,t),"dev.request":(e,t)=>r.dev.request(e,t),"dev.log":(e,t)=>r.dev.log(e,t),"dev.logs":(e,t)=>r.dev.logs(e,t),"settings.set":(e,t)=>o(()=>r.settings.set(e,t)),"secrets.has":e=>r.secrets.has(e),"secrets.set":(e,t)=>r.secrets.set(e,t),"secrets.delete":e=>r.secrets.delete(e),"procs.spawn":e=>{if(Math.floor(e.pid/1e5)!==n.id)throw Error(`pid outside this client’s range`);r.procs.spawn({pid:e.pid,name:e.name,kind:e.kind,ppid:e.ppid,detail:e.detail,onKill:()=>t.emit(`proc:kill`,e.pid)})},"procs.update":(e,t)=>r.procs.update(e,t),"procs.account":(e,t)=>r.procs.account(e,t),"procs.kill":(e,t)=>r.procs.kill(e,t),"bus.emit":(e,t)=>{if(e!==`notify`&&e!==`app:open`)throw Error(`windows may not emit ${String(e)}`);o(()=>r.bus.emit(e,e===`app:open`?{...t,fromWindow:n.role===`ui`}:t))},"shell.open":async e=>{let i=e?.confined?(e,t)=>this.#l({kind:`perm`,payload:e},t,n).catch(()=>`deny`):void 0,a=await r.shells.open({...e,prompter:i});return n.shells.set(a.id,a),a.onReadLine((e,t)=>this.#l({kind:`tty`,shellId:a.id,payload:{prompt:e,secret:t}},void 0,n)),a.onClear(()=>t.emit(`shell:clear`,a.id)),{id:a.id,cwd:a.cwd,home:a.home}},"shell.run":async(e,n,r)=>{let i=s(e),a=new AbortController,o=t.on(`shell:abort`,e=>e===n&&a.abort());try{let o=await i.run(r,{out:e=>t.emit(`shell:out`,{runId:n,s:`o`,t:e}),err:e=>t.emit(`shell:out`,{runId:n,s:`e`,t:e}),signal:a.signal});for(let t of[...this.#i.values()])t.ask.shellId===e&&t.resolve(null);return{code:o,cwd:i.cwd}}finally{o()}},"shell.complete":(e,t)=>s(e).complete(t),"shell.close":e=>{n.shells.get(e)?.close(),n.shells.delete(e)},answer:(e,t)=>{let r=this.#i.get(e);r?.targets.has(n.id)&&r.resolve(t)}});let c={id:n.id,peer:t,ask:(e,t,r)=>this.#l(e,t,r?n:void 0)};for(let e of this.#s){let{handlers:r,drop:i}=e.connect(c);t.handle(r),i&&n.drops.push(i)}t.on(`host:out`,({runId:e,s:t,t:n})=>{let r=this.#a.get(e);(t===`o`?r?.onStdout:r?.onStderr)?.(n)}),t.on(`host:progress`,({runId:e,...t})=>this.#a.get(e)?.onProgress?.(t)),t.on(`alive`,e=>{navigator.locks?.request(e,()=>this.#f(n))}),t.on(`bye`,()=>this.#f(n)),this.#e.set(n.id,n)}#f(e){if(this.#e.delete(e.id)){e.peer.close();for(let t of e.drops)t();for(let t of e.shells.values())t.close();for(let t of this.os.procs.list())Math.floor(t.pid/1e5)===e.id&&this.os.procs.kill(t.pid,`window closed`);for(let[t,n]of this.#i)n.targets.delete(e.id),n.targets.size||(this.#i.delete(t),n.resolve(n.ask.kind===`perm`?`deny`:null))}}};const $n=self,er=`SharedWorkerGlobalScope`in self;Le(Yn);const $=new zn({packages:qn,instance:cn(self.name)});on($),$.shells=new Jn($);const tr=new Qn($,er).use(t($));if($.start().then(()=>$.mark(`kernel-ready`)),!er){let e=new BroadcastChannel(`bbx-settings:${self.name}`);$.onSettingWritten=(t,n)=>e.postMessage({key:t,value:n}),e.onmessage=e=>$.settings.applyRemote(e.data.key,e.data.value)}er?$n.onconnect=e=>tr.connect(e.ports[0]):$n.onmessage=e=>e.data?.type===`connect`&&tr.connect(e.ports[0]);export{p as C,_ as S,g as _,at as a,te as b,z as c,j as d,A as f,ge as g,_e as h,K as i,Me as l,ce as m,_n as n,ot as o,k as p,Ft as r,B as s,Y as t,M as u,h as v,m as w,v as x,ee as y};
482
+ `))}}async mountNativeFolder(){throw Error(`Mounting a folder needs a window: use Files → Mount.`)}mountHandle(e){let t=`/mnt/${e.name.replace(/[^\w.-]+/g,`_`)||`folder`}`;return this.fs.mount(t,new Pn(e,`native:${e.name}`)),t}},Bn={id:`esbuild`,version:vn,summary:`bundler for TypeScript, JSX and CSS (WebAssembly); used by serve`,commands:[`esbuild`],tools:[],default:!1,remote:bn.map(e=>yn+e),remoteBytes:4e6},Vn={id:`git`,version:`isomorphic-git 1.x`,summary:`Version control for repositories in the virtual filesystem (clone needs a relay; no push)`,commands:[`git`],tools:[],default:!0},Hn={id:`python`,version:`3.13.2 (Pyodide 0.29)`,summary:`CPython compiled to WebAssembly, with the standard library`,commands:[`python`,`python3`,`pip`,`pip3`],tools:[`run_python`],default:!1,remote:oe.map(e=>S+e),remoteBytes:12e6};const Un=/* #__PURE__ */ Object.assign({"./esbuild/manifest.ts":Bn,"./git/manifest.ts":Vn,"./python/manifest.ts":Hn,"./sqlite/manifest.ts":{id:`sqlite`,version:`SQLite 3 (sql.js)`,summary:`SQL database engine for .db files in the workspace`,commands:[`sqlite3`],tools:[],default:!0},"./zip/manifest.ts":{id:`zip`,version:`fflate`,summary:`Create and extract zip archives`,commands:[`zip`,`unzip`],tools:[],default:!0}}),Wn=/* #__PURE__ */ Object.assign({"./esbuild/index.ts":()=>import(`./pkg-esbuild-BuQjm7dB.js`).then(e=>e.default),"./git/index.ts":()=>import(`./pkg-git-jawfIVoq.js`).then(e=>e.default),"./python/index.ts":()=>import(`./pkg-python-CoNK0IjJ.js`).then(e=>e.default),"./sqlite/index.ts":()=>import(`./pkg-sqlite-BexM5lLo.js`).then(e=>e.default),"./zip/index.ts":()=>import(`./pkg-zip-BdZ_Lkdk.js`).then(e=>e.default)}),Gn=Object.values(Un).sort((e,t)=>e.id.localeCompare(t.id));function Kn(e){let t=Wn[`./${e}/index.ts`];return t?t():Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))}const qn={manifests:Gn,load:Kn};var Jn=class{os;#e=1;constructor(e){this.os=e}async open(e={}){let t=this.os,n=null,r=null,i=null,a=t.procs.spawn({name:`bbsh`,kind:`shell`,ppid:e.ppid,onKill:()=>i?.abort()});t.procs.update(a.pid,{state:`idle`});let o=We(new xe(t,{cwd:e.cwd,ppid:a.pid,confined:e.confined,prompter:e.prompter,tty:{readLine:(e,t)=>n?n(e,t?.secret??!1):Promise.resolve(null),clear:()=>r?.()}})),s={id:`sh${this.#e++}`,cwd:o.cwd,home:o.env.HOME??`/`,async run(e,n){if(a.signal.aborted)throw Error(`this shell has exited`);e.trim()&&o.history.at(-1)!==e&&o.history.push(e),i=new AbortController;let r=()=>i?.abort();n.signal?.addEventListener(`abort`,r),t.procs.update(a.pid,{state:`running`,detail:e.slice(0,60)});let c=performance.now();try{return await o.run(e,{out:n.out,err:n.err,signal:i.signal})}finally{n.signal?.removeEventListener(`abort`,r),i=null,s.cwd=o.cwd,t.procs.account(a.pid,performance.now()-c),t.procs.update(a.pid,{state:`idle`,detail:o.cwd})}},complete:e=>o.complete(e),onReadLine(e){n=e},onClear(e){r=e},close:()=>t.procs.exit(a.pid)};return s}};const Yn=Object.values(/* @__PURE__ */ Object.assign({"/src/apps/agent/manifest.ts":{id:`agent`,name:`Agent`,icon:`spark`,width:520,height:760,order:1,external:ne},"/src/apps/browser/manifest.ts":{id:`browser`,name:`Browser`,icon:`globe`,width:900,height:600,order:6},"/src/apps/editor/manifest.ts":{id:`editor`,name:`Editor`,icon:`edit`,width:820,height:560,order:4},"/src/apps/files/manifest.ts":{id:`files`,name:`Files`,icon:`folder`,width:780,height:500,order:3},"/src/apps/gpulab/manifest.ts":{id:`gpulab`,name:`GPU Lab`,icon:`cube`,width:860,height:580,order:7},"/src/apps/help/manifest.ts":{id:`help`,name:`Help`,icon:`question`,width:980,height:680,order:9,singleton:!0},"/src/apps/preview/manifest.ts":{id:`preview`,name:`Preview`,icon:`eye`,width:760,height:540,order:10,hidden:!0},"/src/apps/settings/manifest.ts":{id:`settings`,name:`Settings`,icon:`gear`,width:720,height:560,order:9,singleton:!0},"/src/apps/sysinfo/manifest.ts":{id:`sysinfo`,name:`System`,icon:`info`,width:760,height:540,order:8,singleton:!0},"/src/apps/taskmgr/manifest.ts":{id:`taskmgr`,name:`Task Manager`,icon:`activity`,width:760,height:500,order:5,singleton:!0},"/src/apps/terminal/manifest.ts":{id:`terminal`,name:`Terminal`,icon:`terminal`,width:760,height:480,order:2}})).sort((e,t)=>e.order-t.order);var Xn=class{port;#e=1;#t=/* @__PURE__ */ new Map;#n={};#r=/* @__PURE__ */ new Map;closed=!1;constructor(e){this.port=e,e.onmessage=e=>void this.#i(e.data)}handle(e){return Object.assign(this.#n,e),this}call(e,...t){return this.closed?Promise.reject(/* @__PURE__ */ Error(`connection closed`)):new Promise((n,r)=>{let i=this.#e++;this.#t.set(i,{resolve:n,reject:r}),this.port.postMessage({k:`call`,id:i,m:e,a:t})})}emit(e,t){this.closed||this.port.postMessage({k:`evt`,n:e,p:t})}on(e,t){let n=this.#r.get(e);return n||this.#r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}close(){if(!this.closed){this.closed=!0,this.port.close();for(let e of this.#t.values())e.reject(/* @__PURE__ */ Error(`connection closed`));this.#t.clear()}}async#i(e){if(e.k===`call`){let t=Object.hasOwn(this.#n,e.m)?this.#n[e.m]:void 0;try{if(!t)throw Error(`unknown method: ${e.m}`);let n=await t(...e.a);this.closed||this.port.postMessage({k:`ok`,id:e.id,v:n})}catch(t){let n=t;this.closed||this.port.postMessage({k:`err`,id:e.id,e:{name:n?.name??`Error`,message:n?.message??String(t)}})}}else if(e.k===`ok`||e.k===`err`){let t=this.#t.get(e.id);if(this.#t.delete(e.id),!t)return;if(e.k===`ok`)t.resolve(e.v);else{let n=Error(e.e.message);n.name=e.e.name,t.reject(n)}}else if(e.k===`evt`)for(let t of[...this.#r.get(e.n)??[]])try{t(e.p)}catch(t){console.error(`[rpc] listener for "${e.n}" threw`,t)}}};const Q=e=>({pid:e.pid,ppid:e.ppid,name:e.name,kind:e.kind,started:e.started,state:e.state,detail:e.detail,cpuMs:e.cpuMs,memBytes:e.memBytes}),Zn=[`fs:change`,`settings:change`,`notify`,`app:open`,`kmsg`,`dev:update`,`dev:log`];var Qn=class{os;shared;#e=/* @__PURE__ */ new Map;#t=1;#n=1;#r=1;#i=/* @__PURE__ */ new Map;#a=/* @__PURE__ */ new Map;#o=null;#s=[];constructor(e,t){this.os=e,this.shared=t;for(let t of Zn)e.bus.on(t,e=>this.#c(`bus`,{type:t,payload:e},this.#o));e.bus.on(`proc:spawn`,e=>this.#c(`bus`,{type:`proc:spawn`,payload:Q(e)})),e.bus.on(`proc:update`,e=>this.#c(`bus`,{type:`proc:update`,payload:Q(e)})),e.bus.on(`proc:exit`,({proc:e,reason:t})=>this.#c(`bus`,{type:`proc:exit`,payload:{proc:Q(e),reason:t}})),e.perms.setPrompter((e,t)=>this.#l({kind:`perm`,payload:e},t).catch(()=>`deny`)),e.ui={call:(e,...t)=>this.#l({kind:`ui`,payload:{method:e,args:t}},void 0,[...this.#e.values()].find(e=>e.role===`ui`))},ue({run:(e,t,n)=>this.#u(e,t,n),backend:(e,t,n,r)=>this.#d(e,t,n,r)})}use(e){return this.#s.push(e),this}#c(e,t,n=null){for(let r of this.#e.values())r.id!==n&&r.role===`ui`&&r.peer.emit(e,t)}#l(e,t,n){return new Promise((r,i)=>{let a=this.#n++,o={...e,askId:a},s=n?[n]:[...this.#e.values()].filter(e=>e.role===`ui`);if(!s.length)return i(/* @__PURE__ */ Error(`no window is connected to answer`));this.#i.set(a,{ask:o,resolve:e=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);r(e)}},targets:new Set(s.map(e=>e.id))}),t?.addEventListener(`abort`,()=>{if(this.#i.delete(a)){for(let e of s)e.peer.emit(`ask:done`,a);i(t.reason)}});for(let e of s)e.peer.emit(`ask`,o)})}async#u(e,t,n){let r=[...this.#e.values()].find(e=>e.role===`host`);if(!r)return{ok:!1,stdout:``,stderr:``,ms:0,error:`No window is open to host the sandbox. Open the agent window or the desktop.`};let i=this.#r++;this.#a.set(i,n);let a=()=>r.peer.emit(`host:abort`,i);n.signal?.addEventListener(`abort`,a);try{return await r.peer.call(`host.run`,i,e,t,{cwd:n.cwd,timeoutMs:n.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{n.signal?.removeEventListener(`abort`,a),this.#a.delete(i)}}async#d(e,t,n,r){let i=[...this.#e.values()].find(e=>e.role===`host`);if(!i)return{ok:!1,stdout:``,stderr:``,ms:0,error:e===`request`?`backend not loaded`:`No window is open to host the backend. Open the agent window or the desktop.`};let a=this.#r++;this.#a.set(a,r);try{return await i.peer.call(`host.backend`,a,e,t,n,{cwd:r.cwd,timeoutMs:r.timeoutMs})}catch(e){return{ok:!1,stdout:``,stderr:``,ms:0,error:`sandbox host failed: ${e.message}`}}finally{this.#a.delete(a)}}connect(e){let t=new Xn(e),n={id:this.#t++,peer:t,role:`new`,shells:/* @__PURE__ */ new Map,drops:[]},r=this.os,i=r.fs,a=this,o=e=>{this.#o=n.id;try{return e()}finally{this.#o=null}},s=e=>{let t=n.shells.get(e);if(!t)throw Error(`no such shell: ${e}`);return t};t.handle({async hello(e){return n.role=e,await i.ready,{clientId:n.id,pidBase:n.id*1e5,version:r.version,rootKind:r.rootKind,shared:a.shared,settings:r.settings.entries(),procs:r.procs.list().map(Q),mounts:i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),bootMarks:r.bootMarks,log:r.kernelLog}},"fs.readFile":e=>i.readFile(e),"fs.writeFile":(e,t)=>i.writeFile(e,t),"fs.appendFile":(e,t)=>i.appendFile(e,t),"fs.readdir":e=>i.readdir(e),"fs.stat":e=>i.stat(e),"fs.mkdir":e=>i.mkdir(e),"fs.rm":(e,t)=>i.rm(e,t),"fs.cp":(e,t)=>i.cp(e,t),"fs.mv":(e,t)=>i.mv(e,t),"fs.glob":(e,t,n)=>i.glob(e,t,n),"fs.unmount":e=>i.unmount(e),"fs.mounts":()=>i.mounts().map(e=>({point:e.point,label:e.fs.label,readonly:e.fs.readonly??!1})),"fs.mountHandle":e=>r.mountHandle(e),"dev.start":e=>r.dev.start(e),"dev.stop":e=>r.dev.stop(e),"dev.list":()=>r.dev.list(),"dev.page":(e,t)=>r.dev.page(e,t),"dev.request":(e,t)=>r.dev.request(e,t),"dev.log":(e,t)=>r.dev.log(e,t),"dev.logs":(e,t)=>r.dev.logs(e,t),"settings.set":(e,t)=>o(()=>r.settings.set(e,t)),"secrets.has":e=>r.secrets.has(e),"secrets.set":(e,t)=>r.secrets.set(e,t),"secrets.delete":e=>r.secrets.delete(e),"procs.spawn":e=>{if(Math.floor(e.pid/1e5)!==n.id)throw Error(`pid outside this client’s range`);r.procs.spawn({pid:e.pid,name:e.name,kind:e.kind,ppid:e.ppid,detail:e.detail,onKill:()=>t.emit(`proc:kill`,e.pid)})},"procs.update":(e,t)=>r.procs.update(e,t),"procs.account":(e,t)=>r.procs.account(e,t),"procs.kill":(e,t)=>r.procs.kill(e,t),"bus.emit":(e,t)=>{if(e!==`notify`&&e!==`app:open`)throw Error(`windows may not emit ${String(e)}`);o(()=>r.bus.emit(e,e===`app:open`?{...t,fromWindow:n.role===`ui`}:t))},"shell.open":async e=>{let i=e?.confined?(e,t)=>this.#l({kind:`perm`,payload:e},t,n).catch(()=>`deny`):void 0,a=await r.shells.open({...e,prompter:i});return n.shells.set(a.id,a),a.onReadLine((e,t)=>this.#l({kind:`tty`,shellId:a.id,payload:{prompt:e,secret:t}},void 0,n)),a.onClear(()=>t.emit(`shell:clear`,a.id)),{id:a.id,cwd:a.cwd,home:a.home}},"shell.run":async(e,n,r)=>{let i=s(e),a=new AbortController,o=t.on(`shell:abort`,e=>e===n&&a.abort());try{let o=await i.run(r,{out:e=>t.emit(`shell:out`,{runId:n,s:`o`,t:e}),err:e=>t.emit(`shell:out`,{runId:n,s:`e`,t:e}),signal:a.signal});for(let t of[...this.#i.values()])t.ask.shellId===e&&t.resolve(null);return{code:o,cwd:i.cwd}}finally{o()}},"shell.complete":(e,t)=>s(e).complete(t),"shell.close":e=>{n.shells.get(e)?.close(),n.shells.delete(e)},answer:(e,t)=>{let r=this.#i.get(e);r?.targets.has(n.id)&&r.resolve(t)}});let c={id:n.id,peer:t,ask:(e,t,r)=>this.#l(e,t,r?n:void 0)};for(let e of this.#s){let{handlers:r,drop:i}=e.connect(c);t.handle(r),i&&n.drops.push(i)}t.on(`host:out`,({runId:e,s:t,t:n})=>{let r=this.#a.get(e);(t===`o`?r?.onStdout:r?.onStderr)?.(n)}),t.on(`host:progress`,({runId:e,...t})=>this.#a.get(e)?.onProgress?.(t)),t.on(`alive`,e=>{navigator.locks?.request(e,()=>this.#f(n))}),t.on(`bye`,()=>this.#f(n)),this.#e.set(n.id,n)}#f(e){if(this.#e.delete(e.id)){e.peer.close();for(let t of e.drops)t();for(let t of e.shells.values())t.close();for(let t of this.os.procs.list())Math.floor(t.pid/1e5)===e.id&&this.os.procs.kill(t.pid,`window closed`);for(let[t,n]of this.#i)n.targets.delete(e.id),n.targets.size||(this.#i.delete(t),n.resolve(n.ask.kind===`perm`?`deny`:null))}}};const $n=self,er=`SharedWorkerGlobalScope`in self;Le(Yn);const $=new zn({packages:qn,instance:cn(self.name)});on($),$.shells=new Jn($);const tr=new Qn($,er).use(t($));if($.start().then(()=>$.mark(`kernel-ready`)),!er){let e=new BroadcastChannel(`bbx-settings:${self.name}`);$.onSettingWritten=(t,n)=>e.postMessage({key:t,value:n}),e.onmessage=e=>$.settings.applyRemote(e.data.key,e.data.value)}er?$n.onconnect=e=>tr.connect(e.ports[0]):$n.onmessage=e=>e.data?.type===`connect`&&tr.connect(e.ports[0]);export{p as C,_ as S,g as _,at as a,te as b,z as c,j as d,A as f,ge as g,_e as h,K as i,Me as l,ce as m,_n as n,ot as o,k as p,Ft as r,B as s,Y as t,M as u,h as v,m as w,v as x,ee as y};
@@ -1 +1 @@
1
- import{n as e}from"./anthropic-Cc12J4F-.js";function t(t){throw new e(`${t} requires Node.js or a Node-compatible runtime`)}const n=3e4;var r=/* @__PURE__ */ (()=>{class t extends e{constructor(e,t){super(e),t!==void 0&&(this.cause=t)}}return t._errorName=`SessionMemoryError`,t})(),i=class{constructor(e,n){t(`SessionMemoryStores`)}get roots(){return t(`SessionMemoryStores`)}get readOnlyRoots(){return t(`SessionMemoryStores`)}download(e){return t(`SessionMemoryStores`)}finish(){return t(`SessionMemoryStores`)}syncAll(e){return t(`SessionMemoryStores`)}syncIfDue(){return t(`SessionMemoryStores`)}flushWrites(e){return t(`SessionMemoryStores`)}dispose(){return t(`SessionMemoryStores`)}};function a(e){return t(`setupSkills`)}function o(e){return t(`betaAgentToolset20260401`)}export{n as MEMORY_FLUSH_TIMEOUT_MS,r as SessionMemoryError,i as SessionMemoryStores,o as betaAgentToolset20260401,a as setupSkills};
1
+ import{n as e}from"./anthropic-S3ckT02t.js";function t(t){throw new e(`${t} requires Node.js or a Node-compatible runtime`)}const n=3e4;var r=/* @__PURE__ */ (()=>{class t extends e{constructor(e,t){super(e),t!==void 0&&(this.cause=t)}}return t._errorName=`SessionMemoryError`,t})(),i=class{constructor(e,n){t(`SessionMemoryStores`)}get roots(){return t(`SessionMemoryStores`)}get readOnlyRoots(){return t(`SessionMemoryStores`)}download(e){return t(`SessionMemoryStores`)}finish(){return t(`SessionMemoryStores`)}syncAll(e){return t(`SessionMemoryStores`)}syncIfDue(){return t(`SessionMemoryStores`)}flushWrites(e){return t(`SessionMemoryStores`)}dispose(){return t(`SessionMemoryStores`)}};function a(e){return t(`setupSkills`)}function o(e){return t(`betaAgentToolset20260401`)}export{n as MEMORY_FLUSH_TIMEOUT_MS,r as SessionMemoryError,i as SessionMemoryStores,o as betaAgentToolset20260401,a as setupSkills};
@@ -1 +1 @@
1
- import{n as e}from"./anthropic-Cc12J4F-.js";function t(t){return new Proxy({},{get(n,r){if(typeof r!=`symbol`)throw new e(`\`${t}.${r}\` is not available in this environment; it needs a Node.js-compatible runtime`)}})}const n=/* @__PURE__ */ t(`fs`),r=/* @__PURE__ */ t(`path`);export{n as fs,r as path};
1
+ import{n as e}from"./anthropic-S3ckT02t.js";function t(t){return new Proxy({},{get(n,r){if(typeof r!=`symbol`)throw new e(`\`${t}.${r}\` is not available in this environment; it needs a Node.js-compatible runtime`)}})}const n=/* @__PURE__ */ t(`fs`),r=/* @__PURE__ */ t(`path`);export{n as fs,r as path};
@@ -1,3 +1,3 @@
1
- import{a as e,i as t,o as n}from"./main-DBKsMgp-.js";function r(e,t){let n=[{role:`system`,content:e}];for(let e of t)if(e.role===`assistant`){let t=e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=e.content.flatMap(e=>e.type===`tool_use`?[{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input)}}]:[]);n.push({role:`assistant`,content:t||null,...r.length?{tool_calls:r}:{}})}else{for(let t of e.content)t.type===`tool_result`&&n.push({role:`tool`,tool_call_id:t.tool_use_id,content:t.is_error?`ERROR: ${t.content}`:t.content});let t=e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
1
+ import{a as e,i as t,o as n}from"./main-VEpSfsM_.js";function r(e,t){let n=[{role:`system`,content:e}];for(let e of t)if(e.role===`assistant`){let t=e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=e.content.flatMap(e=>e.type===`tool_use`?[{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input)}}]:[]);n.push({role:`assistant`,content:t||null,...r.length?{tool_calls:r}:{}})}else{for(let t of e.content)t.type===`tool_result`&&n.push({role:`tool`,tool_call_id:t.tool_use_id,content:t.is_error?`ERROR: ${t.content}`:t.content});let t=e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
2
2
  `);t&&n.push({role:`user`,content:t})}return n}async function*i(e){let t=e.pipeThrough(new TextDecoderStream).getReader(),n=``;for(;;){let{value:e,done:r}=await t.read();if(r)break;n+=e;let i;for(;(i=n.indexOf(`
3
3
  `))>=0;){let e=n.slice(0,i).trim();n=n.slice(i+1),e.startsWith(`data:`)&&(yield e.slice(5).trim())}}}function a(a,o,s){let c=o.baseUrl.replace(/\/+$/,``),l=o.kind===`local`?`the local server`:`the API`,u=o.kind===`openai`?a.corsRelay:``;return{id:o.kind,contextBudget:Math.floor(a.contextWindow*.75),contextWindow:a.contextWindow,async turn(a){if(!o.model)throw new t(`No model selected for ${l}. Pick one in Settings → Model.`);let d;try{d=await fetch(e(`${c}/chat/completions`,u),{method:`POST`,signal:a.signal,headers:{"content-type":`application/json`,...s?{authorization:`Bearer ${s}`}:{}},body:JSON.stringify({model:o.model,stream:!0,messages:r(a.system,a.messages),...a.tools.length?{tools:a.tools.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.input_schema}}))}:{}})})}catch(e){throw a.signal.aborted?e:new t(n(c,o.kind,u),!0)}if(!d.ok||!d.body){let e=await d.text().catch(()=>``);throw new t(`${c} answered ${d.status}: ${e.slice(0,400)||d.statusText}`,d.status>=500)}let f=``,p=``,m=``,h=o.model,g={input:0,output:0,cacheRead:0},_=[];for await(let e of i(d.body)){if(e===`[DONE]`)break;let t;try{t=JSON.parse(e)}catch{continue}t.model&&(h=t.model),t.usage&&Object.assign(g,{input:t.usage.prompt_tokens??0,output:t.usage.completion_tokens??0});let n=t.choices?.[0];if(!n)continue;let r=n.delta;r?.content&&(f+=r.content,a.onText(r.content));let i=r?.reasoning_content??r?.reasoning;i&&(p+=i,a.onThinking(i));for(let e of r?.tool_calls??[]){let t=_[e.index]??={id:``,name:``,args:``};e.id&&(t.id=e.id),e.function?.name&&(t.name+=e.function.name),e.function?.arguments&&(t.args+=e.function.arguments)}n.finish_reason&&(m=n.finish_reason)}let v=[];return p&&v.push({type:`thinking`,text:p}),f&&v.push({type:`text`,text:f}),_.filter(Boolean).forEach((e,t)=>{let n={},r;try{let t=JSON.parse(e.args||`{}`);typeof t==`object`&&t&&!Array.isArray(t)?n=t:r=e.args}catch{r=e.args}v.push({type:`tool_use`,id:e.id||`call_${Date.now()}_${t}`,name:e.name,input:n,invalid:r})}),{content:v,stop:v.some(e=>e.type===`tool_use`)?`tool_use`:m===`length`?`max_tokens`:`end`,usage:g,model:h}}}}export{a as createOpenAiProvider};
@@ -1 +1 @@
1
- import{t as e}from"./bundle-rO6AXpFE.js";import{_ as t,v as n,y as r}from"./main-DBKsMgp-.js";var i={commands:[{name:`esbuild`,summary:`bundle TypeScript/JSX/CSS into files (npm packages from esm.sh)`,usage:`esbuild src/main.tsx --outfile=dist/app.js (also writes dist/app.css when there is CSS)`,async run(i){let a=i.args.find(e=>!e.startsWith(`-`)),o=i.args.find(e=>e.startsWith(`--outfile=`))?.slice(10);if(!a)throw Error(`usage: esbuild <entry> --outfile=<file>`);let s=i.path(a),c=i.path(o??`dist/${t(s).replace(/\.\w+$/,``)}.js`),l=i.shell.cwd,u=await i.os.fs.readText(`${l}/package.json`).then(e=>JSON.parse(e),()=>null),d=performance.now(),f=await e({fs:i.os.fs,root:l,entry:s,target:`browser`,pkg:u});for(let e of f.warnings)i.err(`warning: ${e}\n`);if(f.errors.length){for(let e of f.errors)i.err(`error: ${e}\n`);return 1}if(await i.os.fs.mkdir(n(c)),await i.os.fs.writeFile(c,f.js),i.out(`${c} ${(f.js.length/1024).toFixed(1)} KB\n`),f.css){let e=c.slice(0,-r(c).length-1)+`.css`;await i.os.fs.writeFile(e,f.css),i.out(`${e} ${(f.css.length/1024).toFixed(1)} KB\n`)}i.out(`done in ${Math.round(performance.now()-d)} ms\n`)}}]};export{i as default};
1
+ import{t as e}from"./bundle-8opp8__C.js";import{_ as t,v as n,y as r}from"./main-VEpSfsM_.js";var i={commands:[{name:`esbuild`,summary:`bundle TypeScript/JSX/CSS into files (npm packages from esm.sh)`,usage:`esbuild src/main.tsx --outfile=dist/app.js (also writes dist/app.css when there is CSS)`,async run(i){let a=i.args.find(e=>!e.startsWith(`-`)),o=i.args.find(e=>e.startsWith(`--outfile=`))?.slice(10);if(!a)throw Error(`usage: esbuild <entry> --outfile=<file>`);let s=i.path(a),c=i.path(o??`dist/${t(s).replace(/\.\w+$/,``)}.js`),l=i.shell.cwd,u=await i.os.fs.readText(`${l}/package.json`).then(e=>JSON.parse(e),()=>null),d=performance.now(),f=await e({fs:i.os.fs,root:l,entry:s,target:`browser`,pkg:u});for(let e of f.warnings)i.err(`warning: ${e}\n`);if(f.errors.length){for(let e of f.errors)i.err(`error: ${e}\n`);return 1}if(await i.os.fs.mkdir(n(c)),await i.os.fs.writeFile(c,f.js),i.out(`${c} ${(f.js.length/1024).toFixed(1)} KB\n`),f.css){let e=c.slice(0,-r(c).length-1)+`.css`;await i.os.fs.writeFile(e,f.css),i.out(`${e} ${(f.css.length/1024).toFixed(1)} KB\n`)}i.out(`done in ${Math.round(performance.now()-d)} ms\n`)}}]};export{i as default};
@@ -1,4 +1,4 @@
1
- import{r as e,t}from"./rolldown-runtime-XKyaHtl9.js";import{p as n,t as r,u as i}from"./main-DBKsMgp-.js";var a=/* @__PURE__ */ t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),o=/* @__PURE__ */ t((e=>{
1
+ import{r as e,t}from"./rolldown-runtime-XKyaHtl9.js";import{p as n,t as r,u as i}from"./main-VEpSfsM_.js";var a=/* @__PURE__ */ t((e=>{e.byteLength=c,e.toByteArray=u,e.fromByteArray=p;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e){var t=s(e),n=t[0],r=t[1];return(n+r)*3/4-r}function l(e,t,n){return(t+n)*3/4-n}function u(e){for(var t,i=s(e),a=i[0],o=i[1],c=new r(l(e,a,o)),u=0,d=o>0?a-4:a,f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,c[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,c[u++]=t>>8&255,c[u++]=t&255),c}function d(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[e&63]}function f(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(d(r));return i.join(``)}function p(e){for(var n,r=e.length,i=r%3,a=[],o=16383,s=0,c=r-i;s<c;s+=o)a.push(f(e,s,s+o>c?c:s+o));return i===1?(n=e[r-1],a.push(t[n>>2]+t[n<<4&63]+`==`)):i===2&&(n=(e[r-2]<<8)+e[r-1],a.push(t[n>>10]+t[n>>4&63]+t[n<<2&63]+`=`)),a.join(``)}})),o=/* @__PURE__ */ t((e=>{
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
3
  e.read=function(e,t,n,r,i){var a,o,s=i*8-r-1,c=(1<<s)-1,l=c>>1,u=-7,d=n?i-1:0,f=n?-1:1,p=e[t+d];for(d+=f,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=a*256+e[t+d],d+=f,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=r;u>0;o=o*256+e[t+d],d+=f,u-=8);if(a===0)a=1-l;else if(a===c)return o?NaN:(p?-1:1)*(1/0);else o+=2**r,a-=l;return(p?-1:1)*o*2**(a-r)},e.write=function(e,t,n,r,i,a){var o,s,c,l=a*8-i-1,u=(1<<l)-1,d=u>>1,f=i===23?2**-24-2**-77:0,p=r?0:a-1,m=r?1:-1,h=+(t<0||t===0&&1/t<0);for(t=Math.abs(t),isNaN(t)||t===1/0?(s=+!!isNaN(t),o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=2**-o)<1&&(o--,c*=2),o+d>=1?t+=f/c:t+=f*2**(1-d),t*c>=2&&(o++,c/=2),o+d>=u?(s=0,o=u):o+d>=1?(s=(t*c-1)*2**i,o+=d):(s=t*2**(d-1)*2**i,o=0));i>=8;e[n+p]=s&255,p+=m,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;e[n+p]=o&255,p+=m,o/=256,l-=8);e[n+p-m]|=h*128}})),s=/* @__PURE__ */ t((e=>{
4
4
  /*!
@@ -1,4 +1,4 @@
1
- import{c as e,f as t,g as n,m as r,p as i,r as a,s as o}from"./main-DBKsMgp-.js";function s(e,t){return t.value!==void 0&&t.value!==`None`&&e.out(t.value+`
1
+ import{c as e,f as t,g as n,m as r,p as i,r as a,s as o}from"./main-VEpSfsM_.js";function s(e,t){return t.value!==void 0&&t.value!==`None`&&e.out(t.value+`
2
2
  `),t.error&&e.err(t.error+`
3
3
  `),+!t.ok}const c=(e,r)=>n(e.os,r,{cwd:e.shell.cwd,env:t(e.shell.env),signal:e.signal,onStdout:e.out,onStderr:e.err}),l={name:`python`,summary:`run Python 3.13 (CPython on WebAssembly, via Pyodide)`,usage:`python file.py | python -c "code" | python -m pip install <pkg> | python -V (files in the cwd are visible; changes are written back)`,async run(e){let{opts:t,rest:n}=i(e.args);if(t.has(`V`)||t.has(`version`))return s(e,await c(e,`import sys, pyodide
4
4
  print(f"Python {sys.version.split()[0]} (Pyodide {pyodide.__version__})")`));if(t.has(`m`))return n[0]===`pip`?u.run({...e,args:n.slice(1)}):s(e,await c(e,`import runpy, sys\nsys.argv = ${JSON.stringify(n)}\nrunpy.run_module(${JSON.stringify(n[0]??``)}, run_name="__main__")`));let r=t.has(`c`)?n[0]??``:n[0]?await e.os.fs.readText(e.path(n[0])):e.stdin;if(!r.trim())throw Error(`nothing to run: pass a file, -c "code", or pipe code in`);return s(e,await c(e,r))}},u={name:`pip`,summary:`install Python packages (PyPI pure-Python wheels and Pyodide builds) with micropip`,usage:`pip install <pkg>… | pip install -r requirements.txt | pip uninstall <pkg>… | pip list | pip show <pkg> | pip freeze`,async run(e){let[t=`help`,...n]=e.args,i=()=>e.os.settings.get(r,[]),a=e=>e.split(/[<>=!~\[; ]/)[0].toLowerCase();if(t===`install`){let t=[];for(let r=0;r<n.length;r++){let i=n[r];if(i===`-r`||i===`--requirement`){let i=await e.os.fs.readText(e.path(n[++r]??``));t.push(...i.split(`