@jeevanand/agent-browserbox-runtime 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +19 -1
  2. package/bin/serve.mjs +2 -2
  3. package/dist/assets/{bridge-Bqc3YIRQ.js → bridge-BEwLXp_5.js} +2 -2
  4. package/dist/assets/{build-bryiJ-b6.js → build-DqisMe_5.js} +2 -2
  5. package/dist/assets/bundle-qe7w2kMM.js +1 -0
  6. package/dist/assets/{dev-impl-CfwRFPRf.js → dev-impl-DLIrrRxu.js} +4 -4
  7. package/dist/assets/embed-CqexLx9X.js +3 -0
  8. package/dist/assets/{html-DI-AyJM9.js → html-BggiUWIu.js} +3 -3
  9. package/dist/assets/{instance-CppC8T8t.js → instance-6eYt0v1_.js} +1 -1
  10. package/dist/assets/main-DzFuvDws.js +371 -0
  11. package/dist/assets/path-DGG-Mxbd.js +1 -0
  12. package/dist/assets/{pkg-esbuild-DxKODBC3.js → pkg-esbuild-QrU0ybpL.js} +1 -1
  13. package/dist/assets/{pkg-git-Ds2ZjUJG.js → pkg-git-BQFdAkWZ.js} +9 -9
  14. package/dist/assets/pkg-python-ytZLbJ8W.js +6 -0
  15. package/dist/assets/{pkg-sqlite-BexM5lLo.js → pkg-sqlite-CKGWzcwt.js} +1 -1
  16. package/dist/assets/pkg-zip-CL-568aV.js +1 -0
  17. package/dist/assets/rolldown-runtime-WkwZ5CU-.js +1 -0
  18. package/dist/assets/server-B0hTONK2.js +4 -0
  19. package/dist/embed/index.html +5 -5
  20. package/dist/kernel/bridge.html +2 -2
  21. package/dist/kernel/packages.json +1 -1
  22. package/lib/client/connect.d.ts +23 -0
  23. package/lib/client/connect.js +64 -0
  24. package/lib/client/index.d.ts +23 -0
  25. package/lib/client/index.js +16 -0
  26. package/lib/client/remote-kernel.d.ts +53 -0
  27. package/lib/client/remote-kernel.js +315 -0
  28. package/lib/config/origins.d.ts +13 -0
  29. package/lib/config/origins.js +35 -0
  30. package/lib/kernel/api.d.ts +145 -0
  31. package/lib/kernel/api.js +1 -0
  32. package/lib/kernel/bus.d.ts +6 -0
  33. package/lib/kernel/bus.js +24 -0
  34. package/lib/kernel/caps.d.ts +10 -0
  35. package/lib/kernel/caps.js +50 -0
  36. package/lib/kernel/dev/types.d.ts +71 -0
  37. package/lib/kernel/dev/types.js +8 -0
  38. package/lib/kernel/filetypes.d.ts +9 -0
  39. package/lib/kernel/filetypes.js +74 -0
  40. package/lib/kernel/format.d.ts +3 -0
  41. package/lib/kernel/format.js +23 -0
  42. package/lib/kernel/instance.d.ts +22 -0
  43. package/lib/kernel/instance.js +29 -0
  44. package/lib/kernel/kcore.d.ts +26 -0
  45. package/lib/kernel/kcore.js +105 -0
  46. package/lib/kernel/kcore.wasm +0 -0
  47. package/lib/kernel/paths.d.ts +3 -0
  48. package/lib/kernel/paths.js +3 -0
  49. package/lib/kernel/perms.d.ts +35 -0
  50. package/lib/kernel/perms.js +42 -0
  51. package/lib/kernel/proc.d.ts +45 -0
  52. package/lib/kernel/proc.js +69 -0
  53. package/lib/kernel/settings.d.ts +29 -0
  54. package/lib/kernel/settings.js +94 -0
  55. package/lib/kernel/types.d.ts +48 -0
  56. package/lib/kernel/types.js +1 -0
  57. package/lib/kernel/vfs/path.d.ts +11 -0
  58. package/lib/kernel/vfs/path.js +72 -0
  59. package/lib/kernel/vfs/types.d.ts +34 -0
  60. package/lib/kernel/vfs/types.js +17 -0
  61. package/lib/kernel-worker/wire.d.ts +38 -0
  62. package/lib/kernel-worker/wire.js +2 -0
  63. package/lib/rpc/peer.d.ts +12 -0
  64. package/lib/rpc/peer.js +85 -0
  65. package/lib/sandbox/isolation.d.ts +8 -0
  66. package/lib/sandbox/isolation.js +12 -0
  67. package/lib/shell/ansi.d.ts +15 -0
  68. package/lib/shell/ansi.js +23 -0
  69. package/package.json +8 -3
  70. package/dist/assets/anthropic-Cc12J4F-.js +0 -17
  71. package/dist/assets/bundle-rO6AXpFE.js +0 -1
  72. package/dist/assets/embed-CMbAHE2J.js +0 -3
  73. package/dist/assets/github-CrzofUbV.js +0 -2
  74. package/dist/assets/lib-aA6_aWm_.js +0 -68
  75. package/dist/assets/main-DBKsMgp-.js +0 -482
  76. package/dist/assets/node.browser-CCRW_leA.js +0 -1
  77. package/dist/assets/node.browser-D_wxWW2g.js +0 -1
  78. package/dist/assets/openai-D6_sZyaT.js +0 -3
  79. package/dist/assets/pkg-python-Cps4de9u.js +0 -6
  80. package/dist/assets/pkg-zip-B_IjTDzR.js +0 -1
  81. package/dist/assets/publish-gZ8mQa6L.js +0 -2
  82. package/dist/assets/publish-impl-DV1nd6hh.js +0 -7
  83. package/dist/assets/rolldown-runtime-XKyaHtl9.js +0 -1
  84. package/dist/assets/server-CnIXpfUH.js +0 -4
  85. package/dist/assets/webllm-CGpOYyn6.js +0 -11
  86. package/dist/icon.svg +0 -1
  87. package/dist/manifest.webmanifest +0 -10
  88. package/dist/preview/frame.html +0 -27
  89. package/dist/sw.js +0 -73
@@ -1,482 +0,0 @@
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:
2
- `+a.map(e=>` ${e.lineNum}:${e.linePos} ${e.message}`).join(`
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
- // Worker inside an opaque-origin iframe, so it must stay dependency-free JS.
5
- /* eslint-disable */
6
- let port;
7
- let nextRpc = 1;
8
- const pending = new Map();
9
- let pyodide = null;
10
-
11
- self.onmessage = (e) => {
12
- if (e.data?.type !== 'port') return;
13
- port = e.ports[0];
14
- port.onmessage = (ev) => handle(ev.data);
15
- port.postMessage({ type: 'ready' });
16
- };
17
-
18
- function rpc(id, method, params) {
19
- return new Promise((resolve, reject) => {
20
- const rid = nextRpc++;
21
- pending.set(rid, { resolve, reject });
22
- port.postMessage({ id, type: 'rpc', rid, method, params });
23
- });
24
- }
25
-
26
- function show(v) {
27
- if (typeof v === 'string') return v;
28
- if (v instanceof Error) return v.stack || String(v);
29
- try {
30
- return JSON.stringify(v, (_k, x) => (typeof x === 'bigint' ? x.toString() + 'n' : x), 2) ?? String(v);
31
- } catch {
32
- return String(v);
33
- }
34
- }
35
-
36
- async function handle(m) {
37
- if (m.type === 'rpc-result') {
38
- const p = pending.get(m.rid);
39
- pending.delete(m.rid);
40
- if (p) m.error ? p.reject(new Error(m.error)) : p.resolve(m.value);
41
- return;
42
- }
43
- const out = (data) => port.postMessage({ id: m.id, type: 'stdout', data });
44
- const err = (data) => port.postMessage({ id: m.id, type: 'stderr', data });
45
- try {
46
- let result;
47
- if (m.op === 'js') result = await runJs(m, out, err);
48
- else if (m.op === 'python') result = await runPython(m, out, err);
49
- else if (m.op === 'wasm') result = await runWasi(m, out, err);
50
- else if (m.op === 'server-load') result = await serverLoad(m);
51
- else if (m.op === 'server-request') result = await serverRequest(m);
52
- else throw new Error('unknown op ' + m.op);
53
- port.postMessage({ id: m.id, type: 'done', result });
54
- } catch (e) {
55
- port.postMessage({ id: m.id, type: 'done', error: e?.stack ? String(e.stack) : String(e) });
56
- }
57
- }
58
-
59
- // ---- JavaScript -----------------------------------------------------------
60
- async function runJs(m, out, err) {
61
- const line = (sink) => (...a) => sink(a.map(show).join(' ') + '\\n');
62
- const console = { log: line(out), info: line(out), debug: line(out), warn: line(err), error: line(err), table: line(out) };
63
- const call = (method) => (...params) => rpc(m.id, method, params);
64
- const fs = {
65
- readText: call('fs.readText'),
66
- readFile: call('fs.readFile'),
67
- writeFile: call('fs.writeFile'),
68
- appendFile: call('fs.appendFile'),
69
- readdir: call('fs.readdir'),
70
- exists: call('fs.exists'),
71
- mkdir: call('fs.mkdir'),
72
- rm: call('fs.rm'),
73
- glob: call('fs.glob'),
74
- };
75
- const AsyncFunction = (async () => {}).constructor;
76
- const fn = new AsyncFunction('fs', 'console', 'print', 'args', 'env', m.code);
77
- const value = await fn(fs, console, line(out), m.args ?? [], Object.freeze({ ...(m.env ?? {}) }));
78
- return { value: value === undefined ? undefined : show(value) };
79
- }
80
-
81
- // ---- Dev-server backend -----------------------------------------------------
82
- // The project's server.ts, bundled as a script that sets __bbxServer. It stays
83
- // loaded; each request is a job. Its console and fs go to whichever request is
84
- // running (the kernel sends one at a time).
85
- let backend = null;
86
- let currentJob = 0;
87
-
88
- async function serverLoad(m) {
89
- currentJob = m.id;
90
- const line = (type) => (...a) => port.postMessage({ id: currentJob, type, data: a.map(show).join(' ') + '\\n' });
91
- const console = { log: line('stdout'), info: line('stdout'), debug: line('stdout'), warn: line('stderr'), error: line('stderr'), table: line('stdout') };
92
- const call = (method) => (...params) => rpc(currentJob, method, params);
93
- const fs = {
94
- readText: call('fs.readText'), readFile: call('fs.readFile'), writeFile: call('fs.writeFile'), appendFile: call('fs.appendFile'),
95
- readdir: call('fs.readdir'), exists: call('fs.exists'), mkdir: call('fs.mkdir'), rm: call('fs.rm'), glob: call('fs.glob'),
96
- };
97
- const env = Object.freeze({ ...(m.env ?? {}), fs });
98
- const mod = new Function('console', 'fs', 'env', m.code + '\\n;return typeof __bbxServer === "undefined" ? undefined : __bbxServer;')(console, fs, env);
99
- const h = mod && (mod.default ?? mod);
100
- const handler = typeof h === 'function' ? h : h && typeof h.fetch === 'function' ? (req, e) => h.fetch(req, e) : null;
101
- if (!handler) throw new Error('the backend must export default a function (request) => Response, or an object with fetch(request)');
102
- backend = { handler, env };
103
- return { value: 'loaded' };
104
- }
105
-
106
- async function serverRequest(m) {
107
- if (!backend) throw new Error('backend not loaded');
108
- currentJob = m.id;
109
- const r = m.req;
110
- const init = { method: r.method, headers: r.headers };
111
- if (r.body && !/^(GET|HEAD)$/i.test(r.method)) init.body = r.body;
112
- const res = await backend.handler(new Request(m.origin + r.url, init), backend.env);
113
- if (res == null) return { response: null };
114
- if (!(res instanceof Response)) throw new Error('the backend returned ' + show(res) + ' instead of a Response');
115
- const headers = [];
116
- res.headers.forEach((v, k) => headers.push([k, v]));
117
- const buf = await res.arrayBuffer();
118
- return { response: { status: res.status, statusText: res.statusText, headers, body: new Uint8Array(buf) } };
119
- }
120
-
121
- // ---- Python (Pyodide, CPython compiled to WebAssembly) ---------------------
122
- async function runPython(m, out, err) {
123
- if (!pyodide) {
124
- const base = m.pyodideUrl;
125
- const progress = (label, loaded, total) => port.postMessage({ id: m.id, type: 'progress', label, loaded, total });
126
- const have = new Map((m.runtime ?? []).map((f) => [base + f.path, f.data]));
127
- if (!have.size) {
128
- // Not installed as a pack: fetch the big file ourselves so the download is visible.
129
- out('[python] downloading the Python runtime…\\n');
130
- const res = await fetch(base + 'pyodide.asm.wasm');
131
- const total = Number(res.headers.get('content-length')) || 0;
132
- const chunks = [];
133
- let loaded = 0;
134
- for (const reader = res.body.getReader(); ; ) {
135
- const { value, done } = await reader.read();
136
- if (done) break;
137
- chunks.push(value);
138
- loaded += value.length;
139
- progress('Python runtime', loaded, total);
140
- }
141
- have.set(base + 'pyodide.asm.wasm', new Uint8Array(await new Blob(chunks).arrayBuffer()));
142
- }
143
- // Serve the runtime's own files from memory instead of the network.
144
- const realFetch = self.fetch.bind(self);
145
- self.fetch = (input, init) => {
146
- const url = typeof input === 'string' ? input : input.url;
147
- const data = have.get(url);
148
- if (!data) return realFetch(input, init);
149
- const type = url.endsWith('.wasm') ? 'application/wasm' : url.endsWith('.json') ? 'application/json' : 'application/octet-stream';
150
- return Promise.resolve(new Response(data, { headers: { 'content-type': type } }));
151
- };
152
- const realImport = self.importScripts.bind(self);
153
- self.importScripts = (...urls) => {
154
- for (const url of urls) {
155
- const data = have.get(url);
156
- if (data) (0, eval)(new TextDecoder().decode(data));
157
- else realImport(url);
158
- }
159
- };
160
- importScripts(base + 'pyodide.js');
161
- pyodide = await loadPyodide({ indexURL: base });
162
- pyodide.FS.mkdirTree('/work');
163
- }
164
- if (m.env) pyodide.runPython('import os\\nos.environ.update(' + JSON.stringify(m.env) + ')');
165
- pyodide.setStdout({ batched: (s) => out(s + '\\n') });
166
- pyodide.setStderr({ batched: (s) => err(s + '\\n') });
167
- const FS = pyodide.FS;
168
- const before = new Map();
169
- for (const f of m.files ?? []) {
170
- const p = '/work/' + f.path;
171
- FS.mkdirTree(p.slice(0, p.lastIndexOf('/')));
172
- FS.writeFile(p, f.data);
173
- before.set(f.path, FS.stat(p).mtime.getTime?.() ?? FS.stat(p).mtime);
174
- }
175
- FS.chdir('/work');
176
- if (m.packages?.length) {
177
- await pyodide.loadPackage('micropip');
178
- await pyodide.pyimport('micropip').install(m.packages);
179
- }
180
- await pyodide.loadPackagesFromImports(m.code);
181
- const value = await pyodide.runPythonAsync(m.code);
182
- // Collect files the program created or modified under /work.
183
- const changed = [];
184
- const walk = (dir, rel) => {
185
- for (const name of FS.readdir(dir)) {
186
- if (name === '.' || name === '..') continue;
187
- const p = dir + '/' + name;
188
- const r = rel ? rel + '/' + name : name;
189
- const st = FS.stat(p);
190
- if (FS.isDir(st.mode)) walk(p, r);
191
- else {
192
- const mt = st.mtime.getTime?.() ?? st.mtime;
193
- if (before.get(r) !== mt && st.size <= 32 * 1024 * 1024) changed.push({ path: r, data: FS.readFile(p) });
194
- }
195
- }
196
- };
197
- walk('/work', '');
198
- for (const f of m.files ?? []) before.delete(f.path);
199
- let shown;
200
- if (value !== undefined && value !== null) {
201
- shown = typeof value?.toString === 'function' ? value.toString() : show(value);
202
- value?.destroy?.();
203
- }
204
- return { value: shown, files: changed };
205
- }
206
-
207
- // ---- WASI preview1 (enough for stdio programs) ----------------------------
208
- async function runWasi(m, out, err) {
209
- const enc = new TextEncoder();
210
- const dec = new TextDecoder();
211
- const args = [m.name ?? 'program', ...(m.args ?? [])].map((a) => enc.encode(a + '\\0'));
212
- const stdin = enc.encode(m.stdin ?? '');
213
- let stdinPos = 0;
214
- let memory;
215
- const view = () => new DataView(memory.buffer);
216
- const bytes = () => new Uint8Array(memory.buffer);
217
- class Exit extends Error {
218
- constructor(code) {
219
- super('exit ' + code);
220
- this.code = code;
221
- }
222
- }
223
- const ESUCCESS = 0, EBADF = 8, ENOSYS = 52;
224
- const wasi = {
225
- args_sizes_get(argc, bufSize) {
226
- view().setUint32(argc, args.length, true);
227
- view().setUint32(bufSize, args.reduce((n, a) => n + a.length, 0), true);
228
- return ESUCCESS;
229
- },
230
- args_get(argv, buf) {
231
- for (const a of args) {
232
- view().setUint32(argv, buf, true);
233
- bytes().set(a, buf);
234
- argv += 4;
235
- buf += a.length;
236
- }
237
- return ESUCCESS;
238
- },
239
- environ_sizes_get(count, size) {
240
- view().setUint32(count, 0, true);
241
- view().setUint32(size, 0, true);
242
- return ESUCCESS;
243
- },
244
- environ_get: () => ESUCCESS,
245
- clock_res_get(_id, res) {
246
- view().setBigUint64(res, 1000000n, true);
247
- return ESUCCESS;
248
- },
249
- clock_time_get(id, _prec, time) {
250
- const ms = id === 0 ? Date.now() : performance.now();
251
- view().setBigUint64(time, BigInt(Math.round(ms * 1e6)), true);
252
- return ESUCCESS;
253
- },
254
- random_get(buf, len) {
255
- for (let off = 0; off < len; off += 65536) crypto.getRandomValues(new Uint8Array(memory.buffer, buf + off, Math.min(65536, len - off)));
256
- return ESUCCESS;
257
- },
258
- fd_write(fd, iovs, iovsLen, nwritten) {
259
- if (fd !== 1 && fd !== 2) return EBADF;
260
- let total = 0;
261
- let text = '';
262
- for (let i = 0; i < iovsLen; i++) {
263
- const ptr = view().getUint32(iovs + i * 8, true);
264
- const len = view().getUint32(iovs + i * 8 + 4, true);
265
- text += dec.decode(bytes().subarray(ptr, ptr + len), { stream: true });
266
- total += len;
267
- }
268
- (fd === 1 ? out : err)(text);
269
- view().setUint32(nwritten, total, true);
270
- return ESUCCESS;
271
- },
272
- fd_read(fd, iovs, iovsLen, nread) {
273
- if (fd !== 0) return EBADF;
274
- let total = 0;
275
- for (let i = 0; i < iovsLen && stdinPos < stdin.length; i++) {
276
- const ptr = view().getUint32(iovs + i * 8, true);
277
- const len = view().getUint32(iovs + i * 8 + 4, true);
278
- const chunk = stdin.subarray(stdinPos, stdinPos + len);
279
- bytes().set(chunk, ptr);
280
- stdinPos += chunk.length;
281
- total += chunk.length;
282
- }
283
- view().setUint32(nread, total, true);
284
- return ESUCCESS;
285
- },
286
- fd_fdstat_get(fd, stat) {
287
- if (fd > 2) return EBADF;
288
- view().setUint8(stat, 2); // character device
289
- view().setUint16(stat + 2, 0, true);
290
- view().setBigUint64(stat + 8, 0xffffffffn, true);
291
- view().setBigUint64(stat + 16, 0n, true);
292
- return ESUCCESS;
293
- },
294
- fd_close: () => ESUCCESS,
295
- fd_seek: () => 70, // ESPIPE
296
- fd_prestat_get: () => EBADF,
297
- fd_prestat_dir_name: () => EBADF,
298
- proc_exit(code) {
299
- throw new Exit(code);
300
- },
301
- sched_yield: () => ESUCCESS,
302
- poll_oneoff: () => ENOSYS,
303
- };
304
- const module = await WebAssembly.compile(m.wasm);
305
- const imports = {};
306
- for (const imp of WebAssembly.Module.imports(module)) {
307
- if (imp.kind !== 'function') continue;
308
- (imports[imp.module] ??= {})[imp.name] =
309
- imp.module === 'wasi_snapshot_preview1' && wasi[imp.name] ? wasi[imp.name] : () => ENOSYS;
310
- }
311
- const instance = await WebAssembly.instantiate(module, imports);
312
- memory = instance.exports.memory;
313
- let exitCode = 0;
314
- try {
315
- if (typeof instance.exports._start === 'function') instance.exports._start();
316
- else if (typeof instance.exports.main === 'function') exitCode = instance.exports.main() | 0;
317
- else throw new Error('module exports neither _start nor main; exports: ' + Object.keys(instance.exports).join(', '));
318
- } catch (e) {
319
- if (e instanceof Exit) exitCode = e.code;
320
- else throw e;
321
- }
322
- return { exitCode };
323
- }
324
- `;const ce=`python.packages`,le=262144;var w=class{os;proc;#e;#t;#n=1;#r=!1;#i=/* @__PURE__ */ 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=ae(document.createElement(`iframe`));n.setAttribute(`sandbox`,`allow-scripts`),n.style.display=`none`,n.src=new URL(t.network?`sandbox-net.html`:`sandbox.html`,x).href,this.#t=new Promise((e,t)=>{let r=setTimeout(()=>t(/* @__PURE__ */ 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:se},`*`,[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(/* @__PURE__ */ 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(),r=t.cwd??`/`,i=``,a=``,o=e=>{let t=performance.now()-n;return this.os.procs.account(this.proc.pid,t),{ok:!1,stdout:i,stderr:a,ms:t,...e}},s;try{s=await this.#t}catch(e){return o({error:e.message})}let c=this.#n++;return this.os.procs.update(this.proc.pid,{state:`running`}),new Promise(n=>{let l=(e,r=!1)=>{clearTimeout(f),this.#i.delete(c),this.#a=null,t.signal?.removeEventListener(`abort`,u),this.proc.signal.removeEventListener(`abort`,d),r?this.dispose():this.os.procs.update(this.proc.pid,{state:`idle`}),n(o(e))},u=()=>l({error:`aborted`},!0),d=()=>l({error:`sandbox was killed`}),f=setTimeout(()=>l({error:`timed out after ${t.timeoutMs??3e4} ms`,timedOut:!0},!0),t.timeoutMs??3e4);t.signal?.addEventListener(`abort`,u),this.proc.signal.addEventListener(`abort`,d),this.#a=e=>l({error:e},!0),this.#i.set(c,e=>{e.type===`stdout`?(i.length<le&&(i+=e.data),t.onStdout?.(e.data)):e.type===`stderr`?(a.length<le&&(a+=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(r,e.method,e.params).then(t=>s.postMessage({type:`rpc-result`,rid:e.rid,value:t}),t=>s.postMessage({type:`rpc-result`,rid:e.rid,error:t.message})):e.type===`done`&&(async()=>{if(e.error)return l({error:e.error});try{for(let t of e.result?.files??[])await this.os.fs.writeFile(m(r,t.path),t.data)}catch(e){return l({error:`could not write files back: ${e.message}`})}let t=e.result?.exitCode;l({ok:t===void 0||t===0,value:e.result?.value,exitCode:t,response:e.result?.response})})()}),s.postMessage({id:c,...e})})}async#s(e,t,n){let r=this.os.fs,i=(r=0)=>{if(typeof n[r]!=`string`)throw Error(`${t}: path must be a string`);return m(e,n[r])};switch(t){case`fs.readText`:return r.readText(i());case`fs.readFile`:return r.readFile(i());case`fs.writeFile`:return r.writeFile(i(),n[1]);case`fs.appendFile`:return r.appendFile(i(),n[1]);case`fs.readdir`:return r.readdir(i());case`fs.exists`:return r.exists(i());case`fs.mkdir`:return r.mkdir(i());case`fs.rm`:return r.rm(i(),{recursive:!0});case`fs.glob`:return r.glob(String(n[0]),e);default:throw Error(`unknown sandbox call: ${t}`)}}};let T=null;function ue(e){T=e}async function de(e,t,n={}){if(T)return T.run(`js`,{code:t,args:n.args,network:n.network,ppid:n.ppid,env:n.env},n);let r=new w(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 fe(e,t,n={}){if(T)return T.run(`wasm`,{wasm:t,args:n.args,stdin:n.stdin,name:n.name,ppid:n.ppid},n);let r=new w(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()}}let E=null,pe=!1;async function me(){try{let e=await caches.open(C),t=await Promise.all(oe.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 he(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 ge(e,t,n={}){if(T)return T.run(`python`,{code:t,packages:n.packages,env:n.env},n);E?.alive||(E=new w(e,{name:`python`,network:!1}),pe=!1);let r=n.cwd??`/tmp`,i=await he(e,r),a=!pe,o=a?await me():void 0,s=a?e.settings.get(ce,[]):[],c=[.../* @__PURE__ */ new Set([...s,...n.packages??[]])],l=await E.run({op:`python`,code:t,packages:c.length?c:void 0,files:i,pyodideUrl:S,env:n.env,runtime:o},{timeoutMs:18e4,...n,cwd:r});return pe=E.alive&&!l.timedOut,l}const D=/* @__PURE__ */ new Map;async function _e(e,t,n,r,i={}){if(T)return T.backend(t,n,r,i);let a=e=>({ok:!e,stdout:``,stderr:``,ms:0,error:e});if(t===`stop`)return D.get(n)?.dispose(),D.delete(n),a();if(t===`load`){D.get(n)?.dispose();let t=new w(e,{name:`backend :${n}`,network:r.network,ppid:r.ppid});D.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(),D.delete(n)),a}let o=D.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 O=class extends Error{};function ve(e,t){let n=[],r=0,i=``,a=!1,o=!0,s=()=>{a&&n.push({kind:`word`,word:{text:i,bare:o}}),i=``,a=!1,o=!0},c=()=>{if(e[r+1]===`{`){let n=e.indexOf(`}`,r);if(n<0)throw new O("unterminated ${");let i=e.slice(r+2,n);return r=n,t[i]??``}let n=/^[A-Za-z_][A-Za-z0-9_]*|^\?/.exec(e.slice(r+1));return n?(r+=n[0].length,t[n[0]]??``):`$`};for(;r<e.length;r++){let l=e[r];if(l===`'`){let t=e.indexOf(`'`,r+1);if(t<0)throw new O(`unterminated '`);i+=e.slice(r+1,t),r=t,a=!0,o=!1}else if(l===`"`)for(a=!0,o=!1,r++;;r++){let t=e[r];if(t===void 0)throw new O(`unterminated "`);if(t===`"`)break;t===`\\`&&'"\\$`'.includes(e[r+1]??``)?i+=e[++r]:i+=t===`$`?c():t}else if(l===`\\`)r+1<e.length&&(i+=e[++r]),a=!0,o=!1;else if(l===`$`)i+=c(),a=!0;else if(l===` `||l===` `||l===`
325
- `)s();else if(l===`#`&&!a)break;else if(`|&;<>`.includes(l)){s();let t=e.slice(r,r+2);if(t===`&&`||t===`||`||t===`>>`)n.push({kind:`op`,op:t}),r++;else if(l===`&`)throw new O(`background jobs (&) are not supported`);else n.push({kind:`op`,op:l})}else l===`~`&&!a&&/^(\/|\s|$)/.test(e.slice(r+1))?i+=t.HOME??`~`:i+=l,a=!0}return s(),n}function ye(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`&&r===`"`?i++:a===r&&(r=``);else if(a===`\\`)i++;else if(a===`"`||a===`'`)r=a;else if(a===`#`&&(i===0||/\s/.test(e[i-1]))){e=e.slice(0,i);break}else if(a===`;`||e.startsWith(`&&`,i)||e.startsWith(`||`,i)){let r=a===`;`?`;`:e.slice(i,i+2);t.push({src:e.slice(n,i),next:r}),i+=r.length-1,n=i+1}}return t.push({src:e.slice(n),next:`;`}),t.filter((e,t,n)=>e.src.trim()||e.next!==`;`&&t<n.length-1)}function be(e,t){let n=ve(e,t),r=[],i=[],a={argv:[]},o=()=>{if(!a.argv.length)throw new O(`syntax error: empty command`);i.push(a),a={argv:[]}};for(let e=0;e<n.length;e++){let t=n[e];if(t.kind===`word`)a.argv.push(t.word);else if(t.op===`>`||t.op===`>>`||t.op===`<`){let r=n[++e];if(r?.kind!==`word`)throw new O(`syntax error: expected a file after ${t.op}`);t.op===`<`?a.stdin=r.word:a.stdout={target:r.word,append:t.op===`>>`}}else if(t.op===`|`)o();else{if(!a.argv.length&&!i.length&&t.op===`;`)continue;o(),r.push({stages:i,next:t.op}),i=[]}}return(a.argv.length||i.length)&&(o(),r.push({stages:i,next:`;`})),r}function k(e){let t=/* @__PURE__ */ new Set,n=[],r=!1;for(let i of e)if(!r&&i===`--`)r=!0;else if(!r&&i.startsWith(`--`)&&i.length>2)t.add(i.slice(2));else if(!r&&i.startsWith(`-`)&&i.length>1&&!/^-\d/.test(i))for(let e of i.slice(1))t.add(e);else n.push(i);return{opts:t,rest:n}}var xe=class{os;cwd;env;history=[];commands=/* @__PURE__ */ new Map;tty;ppid=0;confined;prompter;constructor(e,t={}){this.os=e,this.cwd=t.cwd??`/home/user`,this.confined=t.confined??!1,this.prompter=t.prompter,this.tty=t.tty,this.ppid=t.ppid??0,this.env={...e.settings.get(`env.vars`,{}),HOME:n,USER:`user`,SHELL:`/bin/bbsh`,AGENT_HOME:r,PATH:`/bin`,"?":`0`}}register(...e){for(let t of e)this.commands.set(t.name,t);return this}async#e(e){let t=[];for(let n of e){if(n.bare&&/[*?{]/.test(n.text)){let e=await this.os.fs.glob(n.text,this.cwd).catch(()=>[]);if(e.length){let r=this.cwd===`/`?`/`:this.cwd+`/`;t.push(...e.map(e=>!n.text.startsWith(`/`)&&e.startsWith(r)?e.slice(r.length):e));continue}}t.push(n.text)}return t}async run(e,t){let n=0,r=t.signal??new AbortController().signal;try{let i=!1;for(let a of ye(e)){if(!i){if(!a.src.trim())throw new O(`syntax error: empty command`);for(let e of be(a.src,this.env))n=await this.#t(e.stages,t,r);this.env[`?`]=String(n)}if(r.aborted)break;i=a.next===`&&`?n!==0:a.next===`||`&&n===0}}catch(e){t.err(`${e instanceof O?`bbsh`:`bbsh: error`}: ${e.message}\n`),n=2}return this.env[`?`]=String(n),n}async#t(e,t,n){let r=t.stdin??``,i=0;for(let a=0;a<e.length;a++){let o=e[a],s=a===e.length-1,c=await this.#e(o.argv),l=c[0],u=this.commands.get(l);if(!u)try{let e=await this.os.packages.provided(`commands`,l);e&&this.commands.set(l,u=e)}catch(e){return t.err(`bbsh: ${e.message}\n`),127}if(!u)return t.err(`bbsh: ${l}: command not found\n`),127;o.stdin&&(r=await this.os.fs.readText(m(this.cwd,o.stdin.text)));let d=``,f=!s||o.stdout!==void 0;try{i=await u.run({os:this.os,shell:this,args:c.slice(1),stdin:r,out:f?e=>d+=e:t.out,err:t.err,signal:n,tty:s&&!o.stdout?this.tty:void 0,path:e=>m(this.cwd,e)})??0}catch(e){if(n.aborted)return t.err(`^C
326
- `),130;t.err(`${l}: ${e.message}\n`),i=1}if(o.stdout){let e=m(this.cwd,o.stdout.target.text);try{o.stdout.append?await this.os.fs.appendFile(e,d):await this.os.fs.writeFile(e,d)}catch(e){return t.err(`bbsh: ${e.message}\n`),1}d=``}if(r=d,n.aborted)return 130}return i}async complete(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`|`),e.lastIndexOf(`;`))+1,n=e.slice(t);if(!/\S/.test(e.slice(0,t).split(/[|;&]/).pop()??``)&&!n.includes(`/`))return{start:t,options:[...this.commands.keys()].filter(e=>e.startsWith(n)).sort()};let r=n.lastIndexOf(`/`),i=r>=0?n.slice(0,r+1):``,a=n.slice(r+1),o=m(this.cwd,i.replace(/^~/,this.env.HOME??`~`)||`.`);return{start:t,options:(await this.os.fs.readdir(o).catch(()=>[])).filter(e=>e.name.startsWith(a)).map(e=>i+e.name+(e.kind===`dir`?`/`:` `))}}};async function Se(e,t,n){if(e.shell.confined&&!await e.os.perms.request({cap:`net`,actor:t,title:`Network access`,detail:n},e.shell.prompter))throw Error(`network access to ${n} was not allowed`)}const A=e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`?`));function Ce(e,t){return t.value!==void 0&&t.value!==`undefined`&&e.out(t.value+`
327
- `),t.error&&e.err(t.error+`
328
- `),t.ok?0:t.exitCode??1}async function we(e,t,n){if(n.has(`e`)||n.has(`c`))return{code:t[0]??``,args:t.slice(1)};if(t[0])return{code:await e.os.fs.readText(e.path(t[0])),args:t.slice(1)};if(e.stdin)return{code:e.stdin,args:[]};throw Error(`nothing to run: pass a file, -e "code", or pipe code in`)}const Te=[{name:`js`,summary:`run JavaScript in an isolated sandbox`,usage:`js [--net] file.js [args…] | js -e "code" (globals: fs, print, console, args)`,async run(e){let{opts:t,rest:n}=k(e.args),{code:r,args:i}=await we(e,n,t);return t.has(`net`)&&await Se(e,`js`,`network access for a JavaScript program`),Ce(e,await de(e.os,r,{cwd:e.shell.cwd,env:A(e.shell.env),args:i,network:t.has(`net`),signal:e.signal,onStdout:e.out,onStderr:e.err,ppid:e.shell.ppid,timeoutMs:12e4}))}},{name:`wasm`,summary:`run a WASI WebAssembly program`,usage:`wasm program.wasm [args…]`,async run(e){let t=e.args[0];if(!t)throw Error(`usage: wasm program.wasm [args…]`);let n=await e.os.fs.readFile(e.path(t));return Ce(e,await fe(e.os,n,{name:t,args:e.args.slice(1),stdin:e.stdin,signal:e.signal,onStdout:e.out,onStderr:e.err,ppid:e.shell.ppid}))}},{name:`gpu`,summary:`run a WGSL compute shader on WebGPU`,usage:`gpu shader.wgsl <outputLength> [input.json]`,async run(e){let[t,n,r]=e.args;if(!t||!n)throw Error(`usage: gpu shader.wgsl <outputLength> [input.json]`);let i=r?JSON.parse(await e.os.fs.readText(e.path(r))):e.stdin.trim()?JSON.parse(e.stdin):[],a=await f({wgsl:await e.os.fs.readText(e.path(t)),input:i,outputLength:Number(n)});e.out(JSON.stringify(Array.from(a.output.slice(0,64)))+(a.output.length>64?` … (${a.output.length} values)`:``)+`\n${a.ms.toFixed(1)} ms\n`)}},{name:`curl`,summary:`fetch a URL (subject to browser CORS rules)`,usage:`curl [-i] [-X METHOD] [-H "k: v"] [-d body] [-o file] url`,async run(e){let t=[...e.args],n={headers:{},signal:e.signal},r=``,i,a=!1;for(;t.length;){let e=t.shift();if(e===`-X`)n.method=t.shift();else if(e===`-H`){let e=t.shift()??``,r=e.indexOf(`:`);r>0&&(n.headers[e.slice(0,r).trim()]=e.slice(r+1).trim())}else if(e===`-d`||e===`--data`)n.body=t.shift(),n.method??=`POST`;else if(e===`-o`)i=t.shift();else if(e===`-i`)a=!0;else if(e===`-s`||e===`-L`)continue;else r=e}if(!r)throw Error(`usage: curl [options] url`);/^[a-z]+:\/\//i.test(r)||(r=`https://`+r),await Se(e,`curl`,r);let o;try{o=await fetch(r,n)}catch(t){throw e.signal.aborted?t:Error(`could not fetch ${r} — the server is unreachable or does not allow cross-origin requests (CORS)`)}return a&&(e.out(`HTTP ${o.status} ${o.statusText}\n`),o.headers.forEach((t,n)=>e.out(`${n}: ${t}\n`)),e.out(`
329
- `)),i?await e.os.fs.writeFile(e.path(i),new Uint8Array(await o.arrayBuffer())):e.out(await o.text()),o.ok?0:22}}];function j(e){if(!Number.isFinite(e))return`—`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=0;for(;e>=1024&&n<t.length-1;)e/=1024,n++;return`${n===0?e:e.toFixed(+(e<10))} ${t[n]}`}function Ee(e){if(e<1e3)return`${Math.round(e)} ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)} s`;let n=Math.floor(t/60);return n<60?`${n}m ${Math.floor(t%60)}s`:`${Math.floor(n/60)}h ${n%60}m`}const M={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`};function De(e){return e.replace(/\x1b\[[0-9;]*m/g,``).split(`
330
- `).map(e=>e.slice(e.lastIndexOf(`\r`)+1)).join(`
331
- `)}const Oe=e=>e?new Date(e).toISOString().slice(0,16).replace(`T`,` `):` `,N=e=>e.kind===`dir`?`${M.blue}${e.name}/${M.reset}`:e.name,ke=[{name:`pwd`,summary:`print the working directory`,async run({shell:e,out:t}){t(e.cwd+`
332
- `)}},{name:`cd`,summary:`change directory`,usage:`cd [dir]`,async run({args:e,shell:t,os:n,path:r}){let i=r(e[0]??t.env.HOME??`/`),a=await n.fs.stat(i);if(!a)throw Error(`no such directory: ${e[0]}`);if(a.kind!==`dir`)throw Error(`not a directory: ${e[0]}`);t.cwd=i}},{name:`ls`,summary:`list directory contents`,usage:`ls [-la] [path…]`,async run({args:e,os:t,out:n,path:r}){let{opts:i,rest:a}=k(e),o=a.length?a:[`.`],s=0;for(let e of o){let a=r(e),c=await t.fs.stat(a);if(!c){n(`ls: ${e}: no such file or directory\n`),s=1;continue}let l=c.kind===`dir`?await t.fs.readdir(a):[c];if(i.has(`a`)||(l=l.filter(e=>!e.name.startsWith(`.`))),o.length>1&&n(`${e}:\n`),i.has(`l`))for(let e of l)n(`${e.kind===`dir`?`d`:`-`} ${j(e.size).padStart(8)} ${Oe(e.mtime)} ${N(e)}\n`);else l.length&&n(l.map(N).join(` `)+`
333
- `)}return s}},{name:`tree`,summary:`show a directory tree`,usage:`tree [path] [-L depth]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=e.indexOf(`-L`),o=a>=0?Number(e[a+1])||3:4,s=r(e.filter((e,t)=>e!==`-L`&&t!==a+1)[0]??`.`),c=0,l=async(e,r,a)=>{if(a>=o)return;let s=await t.fs.readdir(e);for(let[e,t]of s.entries()){if(i.throwIfAborted(),++c>2e3)return;let o=e===s.length-1;n(`${r}${o?`└── `:`├── `}${N(t)}\n`),t.kind===`dir`&&t.path!==`/proc`&&await l(t.path,r+(o?` `:`│ `),a+1)}};n(`${s}\n`),await l(s,``,0),c>2e3&&n(`… (truncated)
334
- `)}},{name:`cat`,summary:`print files`,usage:`cat [file…]`,async run({args:e,os:t,out:n,stdin:r,path:i}){if(!e.length)return void n(r);for(let r of e)n(await t.fs.readText(i(r)))}},{name:`mkdir`,summary:`create directories (parents included)`,usage:`mkdir dir…`,async run({args:e,os:t,path:n}){let{rest:r}=k(e);if(!r.length)throw Error(`missing operand`);for(let e of r)await t.fs.mkdir(n(e))}},{name:`touch`,summary:`create empty files`,usage:`touch file…`,async run({args:e,os:t,path:n}){for(let r of e)await t.fs.exists(n(r))||await t.fs.writeFile(n(r),``)}},{name:`rm`,summary:`remove files or directories`,usage:`rm [-rf] path…`,async run({args:e,os:t,err:n,path:r}){let{opts:i,rest:a}=k(e);if(!a.length)throw Error(`missing operand`);let o=0;for(let e of a){let a=r(e),s=await t.fs.stat(a);s?s.kind===`dir`&&!i.has(`r`)&&!i.has(`R`)?(n(`rm: ${e}: is a directory (use -r)\n`),o=1):await t.fs.rm(a,{recursive:!0}):i.has(`f`)||(n(`rm: ${e}: no such file or directory\n`),o=1)}return o}},{name:`cp`,summary:`copy files or directories`,usage:`cp src… dest`,async run({args:e,os:t,path:n}){let{rest:r}=k(e);if(r.length<2)throw Error(`usage: cp src… dest`);let i=n(r.pop()),a=(await t.fs.stat(i))?.kind===`dir`;if(r.length>1&&!a)throw Error(`target is not a directory: ${i}`);for(let e of r)await t.fs.cp(n(e),a?_(i,g(n(e))):i)}},{name:`mv`,summary:`move or rename`,usage:`mv src… dest`,async run({args:e,os:t,path:n}){let{rest:r}=k(e);if(r.length<2)throw Error(`usage: mv src… dest`);let i=n(r.pop()),a=(await t.fs.stat(i))?.kind===`dir`;if(r.length>1&&!a)throw Error(`target is not a directory: ${i}`);for(let e of r)await t.fs.mv(n(e),a?_(i,g(n(e))):i)}},{name:`find`,summary:`find files by glob`,usage:`find [path] [-name glob] [-type f|d]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=e.indexOf(`-name`),o=e.indexOf(`-type`),s=a>=0?e[a+1]:void 0,c=o>=0?e[o+1]:void 0,l=r(e[0]&&!e[0].startsWith(`-`)?e[0]:`.`),u=s?RegExp(`^`+s.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)+`$`):null;for await(let e of t.fs.walk(l,{signal:i}))u&&!u.test(e.name)||c&&c===`d`!=(e.kind===`dir`)||n(e.path+`
335
- `)}},{name:`stat`,summary:`show file details`,usage:`stat path…`,async run({args:e,os:t,out:n,path:r}){for(let i of e){let e=await t.fs.stat(r(i));if(!e)throw Error(`${i}: no such file or directory`);n(` path: ${e.path}\n kind: ${e.kind}\n size: ${e.size} bytes\n mtime: ${e.mtime?new Date(e.mtime).toISOString():`-`}\n`)}}},{name:`du`,summary:`disk usage of a directory`,usage:`du [path]`,async run({args:e,os:t,out:n,path:r,signal:i}){let a=r(e[0]??`.`),o=0,s=0;for await(let e of t.fs.walk(a,{signal:i}))e.kind===`file`&&(o+=e.size,s++);n(`${j(o)}\t${s} files\t${a}\n`)}},{name:`df`,summary:`storage quota and mounts`,async run({os:e,out:t}){let n=await navigator.storage?.estimate?.().catch(()=>void 0);t(`origin storage: ${j(n?.usage??NaN)} used of ${j(n?.quota??NaN)}\n\n`);for(let n of e.fs.mounts())t(`${n.fs.label.padEnd(18)} ${n.fs.readonly?`ro`:`rw`} ${n.point}\n`)}},{name:`mount`,summary:`mount a real folder from this computer under /mnt`,async run({os:e,out:t}){t(`mounted at ${await e.mountNativeFolder()}\n`)}}],Ae={manifests:[],load:e=>Promise.reject(/* @__PURE__ */ Error(`package ${e} has no code`))},P=`pkg.installed`;var je=class{os;registry;#e=/* @__PURE__ */ new Map;#t=null;constructor(e,t=Ae){this.os=e,this.registry=t}manifests(){return this.registry.manifests}#n(e){return this.registry.manifests.find(t=>t.id===e)}#r(e,t){return this.registry.manifests.find(n=>n[t].includes(e))}installed(){return this.os.settings.get(P,[])}isInstalled(e){return this.installed().includes(e)}async#i(e){return this.#t??=fetch(new URL(`packages.json`,x)).then(e=>e.ok?e.json():{}).catch(()=>({})),[...((await this.#t)[e.id]??[]).map(e=>({url:new URL(`../${e.url}`,x).href,bytes:e.bytes})),...(e.remote??[]).map(e=>({url:e,bytes:0}))]}async list(){let e=await caches.open(C).catch(()=>null);return Promise.all(this.registry.manifests.map(async t=>{let n=0,r=!1;for(let i of await this.#i(t)){let t=i.bytes||Number((await e?.match(i.url))?.headers.get(`x-bbx-bytes`))||0;t||(r=!0),n+=t}let i=r&&!!t.remoteBytes;return{...t,installed:this.isInstalled(t.id),bytes:i?n+t.remoteBytes:n,estimated:i}}))}async install(e,t){let n=this.#n(e);if(!n)throw Error(`no such package: ${e} (see pkg list)`);let r=await this.#i(n),i=await caches.open(C),a=r.reduce((e,t)=>e+t.bytes,0),o=0;t?.(0,a);for(let e of r){let n=await i.match(e.url);if(n){o+=e.bytes||Number(n.headers.get(`x-bbx-bytes`))||0,a=Math.max(a,o),t?.(o,a);continue}let r=await fetch(e.url);if(!r.ok||!r.body)throw Error(`download failed (HTTP ${r.status}): ${e.url}`);e.bytes||(a+=Number(r.headers.get(`content-length`))||0);let s=[],c=0;for(let e=r.body.getReader();;){let{value:n,done:r}=await e.read();if(r)break;s.push(n),c+=n.length,o+=n.length,a=Math.max(a,o),t?.(o,a)}let l=new Headers(r.headers);l.set(`x-bbx-bytes`,String(c)),l.delete(`content-encoding`),l.delete(`content-length`),await i.put(e.url,new Response(new Blob(s),{headers:l}))}this.isInstalled(e)||this.os.settings.set(P,[...this.installed(),e].sort()),this.os.log(`pkg`,`installed ${e} ${n.version}`)}async remove(e){let t=this.#n(e);if(!t)throw Error(`no such package: ${e}`);this.os.settings.set(P,this.installed().filter(t=>t!==e)),this.#e.delete(e);let n=await caches.open(C);for(let e of await this.#i(t))await n.delete(e.url);this.os.log(`pkg`,`removed ${e}`)}load(e){if(!this.isInstalled(e))return Promise.reject(/* @__PURE__ */ Error(`package ${e} is not installed. Run: pkg install ${e}`));let t=this.#e.get(e);return t||(t=this.registry.load(e),this.#e.set(e,t),t.catch(()=>this.#e.delete(e))),t}async provided(e,t){let n=this.#r(t,e);if(!n)return null;if(!this.isInstalled(n.id))throw Error(`${t}: provided by the ${n.id} package, which is not installed. Run: pkg install ${n.id}`);return(await this.load(n.id))[e]?.find(e=>e.name===t)??null}async all(e){return(await Promise.all(this.registry.manifests.filter(t=>t[e].length&&this.isInstalled(t.id)).map(e=>this.load(e.id).catch(()=>null)))).flatMap(t=>t?.[e]??[])}};function Me(e,t){let n=-1;return(r,i)=>{let a=i?Math.min(100,Math.floor(r/i*100)):0;if(a===n)return;n=a;let o=Math.round(a/100*24);t(`\r${e.padEnd(8)} [${`#`.repeat(o)}${`.`.repeat(24-o)}] ${String(a).padStart(3)}% ${j(r)}${i?` / ${j(i)}`:``}`)}}async function Ne(e,t){for(let n of t){let t=Me(n,e.out);await e.os.packages.install(n,t),e.out(`\n${M.green}installed${M.reset} ${n}\n`)}}const Pe={name:`pkg`,summary:`package manager: list, info, install, remove`,usage:`pkg list | pkg info <name> | pkg install <name>… | pkg remove <name>…`,async run(e){let{os:t,out:n}=e,[r=`list`,...i]=e.args;if(r===`list`){for(let e of await t.packages.list())n(`${e.installed?`${M.green}i${M.reset}`:` `} ${M.bold}${e.id.padEnd(8)}${M.reset} ${(e.bytes?`${e.estimated?`~`:``}${j(e.bytes)}`:``).padStart(9)} ${e.summary}\n`);return n(`${M.dim}i = installed · pkg install <name>${M.reset}\n`)}if(r===`info`){let e=(await t.packages.list()).find(e=>e.id===i[0]);if(!e)throw Error(`no such package: ${i[0]??``}`);n(`${M.bold}${e.id}${M.reset} ${e.version}\n${e.summary}\nstatus: ${e.installed?`installed`:`not installed`}\nsize: ${e.bytes?`${e.estimated?`about `:``}${j(e.bytes)}`:`unknown until downloaded`}\ncommands: ${e.commands.join(`, `)||`—`}\ntools: ${e.tools.join(`, `)||`—`}\n`)}else{if(r===`install`){if(!i.length)throw Error(`usage: pkg install <name>…`);return Ne(e,i)}if(r===`remove`)for(let e of i)await t.packages.remove(e),n(`removed ${e}\n`);else throw Error(`usage: ${this.usage}`)}}},Fe={name:`dmesg`,summary:`print the kernel log`,async run({os:e,out:t}){for(let n of e.kernelLog)t(`${M.dim}[${(n.t/1e3).toFixed(3).padStart(9)}]${M.reset} ${n.src}: ${n.msg}\n`)}},Ie=e=>e.packages.manifests().filter(e=>e.default).map(e=>e.id),F=[];function Le(e){for(let t of e)F.some(e=>e.id===t.id)||F.push({id:t.id,name:t.name,hidden:t.hidden})}function I(){return F}const Re=[{name:`help`,summary:`list commands`,usage:`help [command]`,async run({args:e,shell:t,out:n}){let r=e[0]?t.commands.get(e[0]):void 0;if(e[0]&&!r)throw Error(`no such command: ${e[0]}`);if(r)return void n(`${M.bold}${r.name}${M.reset} — ${r.summary}\n${r.usage?`usage: ${r.usage}\n`:``}`);n(`${M.bold}BrowserBox shell${M.reset} — pipes (|), redirects (> >> <), && || ;, $VARS, globs, quotes.\n\n`);for(let e of[...t.commands.values()].sort((e,t)=>e.name.localeCompare(t.name)))n(` ${M.cyan}${e.name.padEnd(10)}${M.reset} ${e.summary}\n`)}},{name:`ps`,summary:`list processes`,async run({os:e,out:t}){t(`${M.dim}${`PID`.padStart(4)} ${`PPID`.padStart(4)} ${`KIND`.padEnd(8)} ${`STATE`.padEnd(8)} ${`CPU`.padStart(8)} NAME${M.reset}\n`);for(let n of e.procs.list())t(`${String(n.pid).padStart(4)} ${String(n.ppid).padStart(4)} ${n.kind.padEnd(8)} ${n.state.padEnd(8)} ${Ee(n.cpuMs).padStart(8)} ${n.name}${n.detail?` ${M.dim}${n.detail}${M.reset}`:``}\n`)}},{name:`kill`,summary:`terminate a process`,usage:`kill pid…`,async run({args:e,os:t,err:n}){if(!e.length)throw Error(`usage: kill pid…`);let r=0;for(let i of e)t.procs.kill(Number(i))||(n(`kill: ${i}: no such process\n`),r=1);return r}},{name:`open`,summary:`open an app, or a file in the right app`,usage:`open <app | path>`,async run({args:e,os:t,path:n,out:r}){let i=e[0];if(!i)return void r(`apps: ${I().filter(e=>!e.hidden).map(e=>e.id).join(`, `)}\n`);if(I().some(e=>e.id===i))return void t.openApp(i,e[1]?{path:n(e[1])}:{});let a=n(i),o=await t.fs.stat(a);if(!o)throw Error(`${i}: no such app or file`);o.kind===`dir`?t.openApp(`files`,{path:a}):/\.(html?|png|jpe?g|gif|webp|svg|avif|pdf|mp3|wav|ogg|mp4|webm)$/i.test(a)?t.openApp(`preview`,{path:a}):t.openApp(`editor`,{path:a})}},{name:`env`,summary:`print environment variables`,async run({shell:e,out:t}){for(let[n,r]of Object.entries(e.env))n!==`?`&&t(`${n}=${r}\n`)}},{name:`export`,summary:`set an environment variable`,usage:`export NAME=value`,async run({args:e,shell:t}){for(let n of e){let e=n.indexOf(`=`);if(e<1)throw Error(`usage: export NAME=value`);t.env[n.slice(0,e)]=n.slice(e+1)}}},{name:`clear`,summary:`clear the terminal`,async run({shell:e}){e.tty?.clear()}},{name:`history`,summary:`show command history`,async run({shell:e,out:t}){e.history.forEach((e,n)=>t(`${String(n+1).padStart(4)} ${e}\n`))}},{name:`date`,summary:`print the date and time`,async run({out:e}){e((/* @__PURE__ */ new Date()).toString()+`
336
- `)}},{name:`whoami`,summary:`print the user name`,async run({shell:e,out:t}){t((e.env.USER??`user`)+`
337
- `)}},{name:`uname`,summary:`print system information`,async run({os:e,out:t,args:n}){t(n.includes(`-a`)?`BrowserBox ${e.version} wasm32 ${navigator.userAgent}\n`:`BrowserBox
338
- `)}},{name:`uptime`,summary:`time since boot`,async run({os:e,out:t}){t(`up ${Ee(performance.now())}, ${e.procs.list().length} processes\n`)}},{name:`sysinfo`,summary:`platform capabilities and boot timings`,async run({os:e,out:t}){let n=await navigator.storage?.estimate?.().catch(()=>void 0);t(`${M.bold}BrowserBox ${e.version}${M.reset}\n`),t(`root fs ${e.rootKind===`opfs`?`OPFS (persistent)`:`memory (not persistent)`}\n`),t(`storage ${j(n?.usage??NaN)} / ${j(n?.quota??NaN)}\n`),t(`cores ${navigator.hardwareConcurrency??`?`}\n`),t(`boot ${e.bootMarks.map(e=>`${e.name} ${e.at}ms`).join(` → `)}\n\n`);for(let n of e.caps)t(`${n.ok?`${M.green}✓${M.reset}`:`${M.red}✗${M.reset}`} ${n.label.padEnd(26)} ${M.dim}${n.use}${M.reset}\n`)}},{name:`sleep`,summary:`wait N seconds`,usage:`sleep seconds`,async run({args:e,signal:t}){await new Promise((n,r)=>{let i=setTimeout(n,(Number(e[0])||0)*1e3);t.addEventListener(`abort`,()=>{clearTimeout(i),r(t.reason)})})}},{name:`notify`,summary:`show a notification`,usage:`notify title [body]`,async run({args:e,os:t}){t.notify({title:e[0]??`Notification`,body:e.slice(1).join(` `)||void 0})}},{name:`which`,summary:`locate a command`,async run({args:e,shell:t,out:n}){let r=0;for(let i of e)t.commands.has(i)?n(`/bin/${i}\n`):r=1;return r}},{name:`true`,summary:`succeed`,run:async()=>0},{name:`false`,summary:`fail`,run:async()=>1}];async function L(e,t){if(!t.length)return e.stdin;let n=``;for(let r of t)n+=await e.os.fs.readText(e.path(r));return n}const R=e=>{let t=e.split(`
339
- `);return t.at(-1)===``&&t.pop(),t};function ze(e,t){let n=e.indexOf(`-n`);if(n>=0)return{n:Number(e[n+1])||t,rest:e.filter((e,t)=>t!==n&&t!==n+1)};let r=e.find(e=>/^-\d+$/.test(e));return{n:r?Number(r.slice(1)):t,rest:e.filter(e=>e!==r)}}async function Be(e,t){let n=new Blob([e]).stream().pipeThrough(t);return new Uint8Array(await new Response(n).arrayBuffer())}const Ve=[{name:`echo`,summary:`print arguments`,async run({args:e,out:t}){let n=e[0]===`-n`;t((n?e.slice(1):e).join(` `)+(n?``:`
340
- `))}},{name:`grep`,summary:`search text with a regular expression`,usage:`grep [-i] [-n] [-v] [-r] [-F] pattern [path…]`,async run(e){let{opts:t,rest:n}=k(e.args),r=n.shift();if(r===void 0)throw Error(`usage: grep [-invrF] pattern [path…]`);let i=new RegExp(t.has(`F`)?r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`):r,t.has(`i`)?`i`:``),a=0,o=(n,r)=>{R(n).forEach((n,o)=>{if(i.test(n)===t.has(`v`))return;a++;let s=t.has(`v`)?n:n.replace(i,e=>`${M.red}${e}${M.reset}`);e.out(`${r?`${M.magenta}${r}${M.reset}:`:``}${t.has(`n`)?`${M.green}${o+1}${M.reset}:`:``}${s}\n`)})};n.length||o(e.stdin,null);for(let r of n){let i=e.path(r),a=await e.os.fs.stat(i);if(!a)throw Error(`${r}: no such file or directory`);if(a.kind===`file`)o(await e.os.fs.readText(i),n.length>1?r:null);else if(t.has(`r`))for await(let t of e.os.fs.walk(i,{signal:e.signal}))t.kind===`file`&&t.size<2e6&&o(await e.os.fs.readText(t.path).catch(()=>``),t.path);else throw Error(`${r}: is a directory (use -r)`)}return+!a}},{name:`head`,summary:`first lines of input`,usage:`head [-n N] [file…]`,async run(e){let{n:t,rest:n}=ze(e.args,10),r=R(await L(e,n)).slice(0,t);r.length&&e.out(r.join(`
341
- `)+`
342
- `)}},{name:`tail`,summary:`last lines of input`,usage:`tail [-n N] [file…]`,async run(e){let{n:t,rest:n}=ze(e.args,10),r=R(await L(e,n)).slice(-t);r.length&&e.out(r.join(`
343
- `)+`
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
- `)+`
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(`
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
- `),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
- `)[0].slice(0,140)}${M.reset}\n`);else if(t.type===`tool_end`){let e=t.result.split(`
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(`
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
- name: explorer
355
- description: Read-only investigator for searching and summarising many files without changing anything.
356
- tools: read_file, list_dir, glob, grep
357
- ---
358
-
359
- You investigate a question by reading files. You cannot modify anything. Search broadly first (glob, grep), then read only what matters. Finish with a short report: the answer, the evidence as file paths with line numbers, and anything you could not determine.
360
- `,vt=`---
361
- description: Explain a file or folder in plain language.
362
- ---
363
-
364
- Explain $ARGUMENTS in plain language: what it is for, how it is organised, and anything surprising. Read the relevant files first.
365
- `,yt=`---
366
- name: data-analysis
367
- description: Explore, clean and summarise a CSV or JSON file, with numbers checked by running code.
368
- ---
369
-
370
- # Analysing data
371
-
372
- 1. Look before computing: read the first lines of the file and report its shape and columns.
373
- 2. Do the arithmetic in code (run_python with pandas when the Python pack is installed, otherwise run_js) — never estimate figures by eye.
374
- 3. State how missing or malformed values were handled.
375
- 4. Report the findings first, then the method. If a chart helps, build it as an HTML page and show it.
376
- 5. Save derived files next to the source and name them in the answer.
377
- `,bt=`---
378
- name: web-page
379
- description: Build a self-contained web page, chart or small interactive tool and show it in the preview.
380
- ---
381
-
382
- # Building a web page
383
-
384
- 1. Write one complete HTML file in the working directory. Inline the CSS and JavaScript; do not depend on CDNs, because the preview may be offline.
385
- 2. Use system fonts, a readable type scale and enough contrast; make it work at 380px wide.
386
- 3. Draw charts with inline SVG or \`<canvas>\`.
387
- 4. Show it with show_html using the file path, so the user can also open and edit the file.
388
- 5. Say where the file is saved.
389
- `;function xt(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(e);if(!t)return{meta:{},body:e.trim()};let n={};for(let e of t[1].split(/\r?\n/)){let t=e.indexOf(`:`);t<1||e.trimStart().startsWith(`#`)||(n[e.slice(0,t).trim().toLowerCase()]=e.slice(t+1).trim().replace(/^(['"])(.*)\1$/,`$2`))}return{meta:n,body:e.slice(t[0].length).trim()}}function St(e){return(e??``).replace(/^\[|\]$/g,``).split(`,`).map(e=>e.trim().replace(/^(['"])(.*)\1$/,`$2`)).filter(Boolean)}var Ct=/* @__PURE__ */ e({SEED:()=>Dt});const wt={skill:`${r}/skills`,agent:`${r}/agents`,command:`${r}/commands`},Tt=/^[a-z0-9][a-z0-9-]{0,47}$/,Et=e=>Tt.test(e);async function G(e,t){let n=wt[t],r=new Set(e.settings.get(`ext.disabled`,[])),i=await e.fs.readdir(n).catch(()=>[]);return(await Promise.all(i.map(async i=>{let a=t===`skill`;if(a?i.kind!==`dir`:i.kind!==`file`||!i.name.endsWith(`.md`))return null;let o=a?i.name:i.name.slice(0,-3),s=a?`${i.path}/SKILL.md`:i.path,c=await e.fs.readText(s).catch(()=>null);if(c===null||!Et(o))return null;let{meta:l,body:u}=xt(c);return{kind:t,name:o,description:l.description??u.split(`
390
- `).find(e=>e.trim()&&!e.startsWith(`#`))?.trim().slice(0,160)??``,path:s,dir:a?i.path:n,body:u,tools:St(l.tools),enabled:!r.has(`${t}:${o}`)}}))).filter(e=>e!==null).sort((e,t)=>e.name.localeCompare(t.name))}const Dt=Object.entries(/* @__PURE__ */ Object.assign({"./seed/agents/explorer.md":_t,"./seed/commands/explain.md":vt,"./seed/skills/data-analysis/SKILL.md":yt,"./seed/skills/web-page/SKILL.md":bt})).map(([e,t])=>[`${r}/${e.slice(7)}`,t]);function Ot(e){let t=e=>`${e.id} (${[...e.commands,...e.tools].join(`, `)})`,n=e.packages.manifests().filter(t=>e.packages.isInstalled(t.id)),r=e.packages.manifests().filter(t=>!e.packages.isInstalled(t.id));return`installed: ${n.map(t).join(`; `)||`none`}.${r.length?` Not installed: ${r.map(t).join(`; `)} — when a task needs one, run \`pkg install <name>\` with the shell tool; its tools are available from your next step.`:``}`}async function kt(e,t,i){if(i.lite)return`You are BrowserBox's assistant, a small model running on the user's own device. Reply to the user's latest message directly and helpfully, using everything said earlier in this conversation. Be concise. If you are unsure what they want, ask one short question. You can also work with files in ${r}, run shell commands and run JavaScript when a request needs it.${t.instructions?`\n\n${t.instructions}`:``}`;let a=await e.fs.readText(`${r}/MEMORY.md`).catch(()=>``),o=await e.fs.readText(`/home/agent/AGENTS.md`).catch(()=>null)??await e.fs.readText(`/home/agent/CLAUDE.md`).catch(()=>``),[s,c]=await Promise.all([G(e,`skill`),i.subagent?[]:G(e,`agent`)]),l=e=>e.filter(e=>e.enabled).map(e=>`- ${e.name}: ${e.description}`).join(`
391
- `),u=Object.keys(e.settings.get(`env.vars`,{})),d=e.hasCap(`webgpu`)?`available`:`not available in this browser`;return`You are the agent built into BrowserBox, an operating system that runs entirely inside the user's browser tab. You act for the user through tools; everything you do happens on their device, inside a sandbox.
392
-
393
- # Environment
394
- - A virtual filesystem. The root is ${e.rootKind===`opfs`?`persistent (the browser's Origin Private File System)`:`in memory only and is lost on reload — tell the user if that matters`}. Your working directory is ${r}; the user's files are under ${n}; /tmp is in-memory scratch; /proc holds live system state; real folders the user chose to share appear under /mnt.
395
- - A shell with common Unix-style commands (run \`help\`). It is not bash: there is no node, apt or native compiler; \`npm install <pkg>\` only records the dependency in package.json (packages load from esm.sh when bundled). Packages add more: ${Ot(e)}
396
- - Code execution in isolated sandboxes: JavaScript (run_js), Python via WebAssembly (run_python), WASI programs (run_wasm), and GPU compute shaders (gpu_compute; WebGPU is ${d}).
397
- - Web apps: build them as a project folder (index.html or src/main.tsx, package.json for npm dependencies, optional server.ts backend) and run them with dev_server; it bundles TypeScript/JSX, reloads on save and shows the app in Preview. Check your work with preview_logs (console errors, failed requests) rather than assuming it rendered. For a single self-contained page, show_html is enough.
398
- - A desktop the user is looking at. show_html opens a rendered page in a window — the best way to present charts, reports and interactive results. open_app opens the editor, file manager and other apps.
399
- - Network access is limited by the browser: requests only succeed against servers that allow cross-origin access (CORS).${t.provider===`anthropic`&&t.webSearch?` For general web research use the web_search and web_fetch tools, which run server-side and are not limited by CORS.`:``}
400
-
401
- # The sandbox: what this machine is and is not
402
- Everything runs inside one browser tab on the user's device. There is no server behind you, no Linux kernel and no real processes; "processes" are BrowserBox's own (list_processes). Plan with these facts instead of discovering them by failing:
403
- - **Shell**: BrowserBox's own shell, POSIX-flavoured: pipes, redirects, &&, ||, ;, $VARS, globs, cd, history. Not bash: no $(…) substitution, functions, loops, job control (&), sudo, apt, brew, ssh, cron or systemd. Run \`help\` to see the commands that exist; \`pkg list\` for installable ones.
404
- - **No native toolchains**: no node, deno, gcc, make, cargo or java. JavaScript runs in run_js (a Web Worker: no DOM, no require/npm; \`fs\` and \`env\` objects are provided; network only when granted). C/Rust/Go only as prebuilt WASI .wasm files (run_wasm).
405
- - **Python** (the python package) is CPython 3.13 on WebAssembly (Pyodide). \`pip install\` works for pure-Python wheels and Pyodide's builds (numpy, pandas, scipy, matplotlib, scikit-learn…), not for other C extensions. No sockets, subprocess or real threads. The interpreter stays warm between calls; files in the working directory are synced in and out.
406
- - **Network**: the browser's fetch. A server must allow cross-origin requests (CORS) or the request fails with a network error. That is not a bug you can work around from code: say which host refused and suggest an alternative (an API that allows CORS, a file the user uploads${t.provider===`anthropic`&&t.webSearch?`, or web_search/web_fetch, which run server-side`:``}). No raw TCP, no localhost services unless the user runs one that allows this page. git can only clone through an HTTPS relay the user configures.
407
- - **Shipping**: the github tool (and \`gh\` in the shell) pushes a folder to a repository as one commit, clones, creates repositories and opens pull requests, through GitHub's API; plain \`git push\` to GitHub does not work from a browser. The deploy tool (\`deploy\`, \`build\`) builds a project for production and publishes it to Netlify, Vercel or GitHub Pages, returning the live URL. They use the user's tokens from Settings → Accounts: if one is missing, say so and where to add it.
408
- - **Web apps** run on the virtual dev server (dev_server, \`serve\`, \`npm run dev\`): there is no real port; the app shows in the Preview panel, its backend (server.ts) uses web APIs (Request/Response), not Node. Check results with preview_logs.
409
- - **Files**: one virtual filesystem. /home survives reloads (when persistent); /tmp does not. There are no users, owners, permissions, chmod or symlinks. The user's real computer is reachable only through folders they mount under /mnt.
410
- - **Isolation**: code you run is sandboxed in an opaque-origin frame: it cannot see BrowserBox's storage, API keys, cookies or the sites the user is logged into. Long or heavy work belongs in a sandbox (run_js, run_python), which can be stopped; timeouts apply (run_js 30 s by default, up to 5 min with timeout_ms).
411
- - **Resources**: a browser tab's memory (often 2–4 GB) and CPU. Keep files and outputs to a reasonable size; stream or chunk big data.
412
- When something is impossible here, say so plainly and offer the closest thing that does work, rather than trying commands that cannot exist.
413
-
414
- # Working here
415
- - You work in ${r} freely. Changing files elsewhere, running code and using the network may ask the user for permission; if they decline, respect it and find another way or explain what is blocked.
416
- - Verify your work by running it when you can, and report what actually happened — including failures.
417
- - Prefer acting to asking. Use ask_user only for decisions that are genuinely the user's.
418
- - ${r}/MEMORY.md is your long-term memory across sessions. When you learn something durable about the user or their projects, update it with the file tools.
419
- ${i.subagent?`- You are a sub-agent: complete the task you were given and finish with a clear report of what you did and found. You cannot ask the user questions.
420
- `:``}
421
- # Style
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(`
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
- `),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
- `)}`:a.length?`Console so far:\n${a.slice(-20).map(Mt).join(`
427
- `)}`:`No console output yet.`].join(`
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
- `)}`}})];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+`
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
- `),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
- `)+(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(`
435
- `)):`(empty directory)`}}),z({name:`glob`,description:`Find files by glob pattern, e.g. "**/*.ts" or "src/*.{js,css}". Returns matching paths.`,input_schema:B({pattern:{type:`string`},path:{type:`string`,description:`base directory (default: working directory)`}},[`pattern`]),cap:()=>null,describe:e=>`Glob ${e.pattern}`,async run(e,t){let n=await t.os.fs.glob(e.pattern,t.path(e.path??`.`),500);return n.length?n.join(`
436
- `):`No files matched.`}}),z({name:`grep`,description:`Search file contents under a path. pattern is a JavaScript regular expression unless literal is true (literal search runs in the Rust/WASM kernel core and is faster). Returns path:line:text.`,input_schema:B({pattern:{type:`string`},path:{type:`string`,description:`file or directory (default: working directory)`},glob:{type:`string`,description:`only search files whose name matches, e.g. "*.md"`},ignore_case:{type:`boolean`},literal:{type:`boolean`}},[`pattern`]),cap:()=>null,describe:e=>`Grep "${e.pattern}" in ${e.path??`.`}`,async run(e,t){let n=t.path(e.path??`.`),r=await t.os.fs.stat(n);if(!r)throw Error(`no such file or directory: ${n}`);let i=e.glob?RegExp(`^`+e.glob.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)+`$`):null,a=e.literal?null:new RegExp(e.pattern,e.ignore_case?`i`:``),o=[],s=0,c=async n=>{let r=await t.os.fs.readFile(n).catch(()=>null);if(!r||Rt(r))return;s++;let i=new TextDecoder().decode(r).split(`
437
- `);if(a)i.forEach((e,t)=>{o.length<300&&a.test(e)&&o.push(`${n}:${t+1}:${e.slice(0,300)}`)});else for(let a of t.os.kcore.searchLines(r,e.pattern,e.ignore_case,300).matches)o.length<300&&o.push(`${n}:${a.line}:${(i[a.line-1]??``).slice(0,300)}`)};if(r.kind===`file`)await c(n);else for await(let e of t.os.fs.walk(n,{signal:t.signal})){if(o.length>=300||s>5e3)break;e.kind===`file`&&e.size<2e6&&(!i||i.test(e.name))&&await c(e.path)}return o.length?V(o.join(`
438
- `))+(o.length>=300?`
439
- (showing the first 300 matches)`:``):`No matches in ${s} file${s===1?``:`s`}.`}}),z({name:`delete_path`,description:`Delete a file or a directory (recursively).`,input_schema:B({path:{type:`string`}},[`path`]),cap:(e,t)=>q([e.path],t),describe:e=>`Delete ${e.path}`,async run(e,t){return await t.os.fs.rm(t.path(e.path),{recursive:!0}),`Deleted ${t.path(e.path)}`}}),z({name:`move_path`,description:`Move or rename a file or directory. Set copy to true to copy instead.`,input_schema:B({from:{type:`string`},to:{type:`string`},copy:{type:`boolean`}},[`from`,`to`]),cap:(e,t)=>q(e.copy?[e.to]:[e.from,e.to],t),describe:e=>`${e.copy?`Copy`:`Move`} ${e.from} → ${e.to}`,async run(e,t){return await(e.copy?t.os.fs.cp(t.path(e.from),t.path(e.to)):t.os.fs.mv(t.path(e.from),t.path(e.to))),`${e.copy?`Copied`:`Moved`} ${t.path(e.from)} → ${t.path(e.to)}`}})];function Bt(e){if(!e.os.ui)throw Error(`no window is connected to do this`);return e.os.ui}const Vt={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `};function Ht(e){let t=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(e)?.[1]?.trim(),n=e.replace(/<(script|style|noscript|svg|iframe|template|head)\b[\s\S]*?<\/\1>/gi,` `).replace(/<a\b[^>]*\bhref="(https?:[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,(e,t,n)=>`${n} (${t})`).replace(/<\/(p|div|li|tr|h[1-6]|section|article)>|<br\s*\/?>/gi,`
440
- `).replace(/<[^>]+>/g,``).replace(/&(#x?[0-9a-f]+|\w+);/gi,(e,t)=>t[0]===`#`?String.fromCodePoint(t[1]?.toLowerCase()===`x`?parseInt(t.slice(2),16):Number(t.slice(1))):Vt[t]??e).replace(/[ \t]+/g,` `).replace(/\n\s*\n\s*/g,`
441
-
442
- `).trim();return(t?`# ${t}\n\n`:``)+n}const Ut=[z({name:`http_fetch`,description:`Make an HTTP request from the browser. Only works for servers that allow cross-origin requests (CORS) — many public APIs do, most ordinary web pages do not. HTML is converted to readable text unless raw is true. Use save_to to store the response body as a file (binary-safe).`,input_schema:B({url:{type:`string`},method:{type:`string`},headers:{type:`object`},body:{type:`string`},raw:{type:`boolean`},save_to:{type:`string`,description:`path to save the body to`}},[`url`]),cap:()=>`net`,describe:e=>`${e.method??`GET`} ${e.url}`,async run(e,t){let n=new URL(e.url);if(!/^https?:$/.test(n.protocol))throw Error(`only http and https URLs are supported`);let r;try{r=await fetch(n,{method:e.method??`GET`,headers:e.headers,body:e.body,signal:t.signal,credentials:`omit`,referrerPolicy:`no-referrer`})}catch(e){throw t.signal.aborted?e:Error(`Request to ${n.host} failed. The server is unreachable or does not send CORS headers, so a browser cannot read it. Try an API endpoint that supports CORS.`)}let i=r.headers.get(`content-type`)??``,a=`HTTP ${r.status} ${r.statusText}\ncontent-type: ${i}\n\n`;if(e.save_to){let n=new Uint8Array(await r.arrayBuffer());return await t.os.fs.writeFile(t.path(e.save_to),n),`${a}Saved ${j(n.length)} to ${t.path(e.save_to)}`}let o=await r.text();return a+V(i.includes(`html`)&&!e.raw?Ht(o):o)}}),z({name:`open_app`,get description(){return`Open an application window for the user. Apps: ${I().filter(e=>!e.hidden).map(e=>e.id).join(`, `)}. Pass path to open a file or folder (files, editor, preview) or url for the browser.`},get input_schema(){return B({app:{type:`string`,enum:I().map(e=>e.id)},path:{type:`string`},url:{type:`string`}},[`app`])},cap:()=>null,describe:e=>`Open ${e.app}${e.path?` ${e.path}`:``}`,async run(e,t){return t.os.openApp(e.app,{...e.path?{path:t.path(e.path)}:{},...e.url?{url:e.url}:{}}),`Opened ${e.app}.`}}),z({name:`show_html`,description:`Show the user a rendered HTML page in a Preview window — use it to present charts, reports, small apps or visualisations. Pass either html (a complete document; inline CSS/JS is fine, it runs sandboxed) or path to an .html file whose relative assets are resolved from the filesystem.`,input_schema:B({html:{type:`string`},path:{type:`string`},title:{type:`string`}}),cap:()=>null,describe:e=>`Show ${e.title??e.path??`HTML preview`}`,async run(e,t){if(!e.html&&!e.path)throw Error(`pass html or path`);return t.os.openApp(`preview`,e.path?{path:t.path(e.path),title:e.title}:{html:e.html,title:e.title??`Preview`}),`The preview window is open.`}}),z({name:`list_processes`,description:`List running processes (apps, agents, sandboxes, services) with pid, state and CPU time.`,input_schema:B({}),cap:()=>null,describe:()=>`List processes`,async run(e,t){return t.os.procs.list().map(e=>`${e.pid}\tppid ${e.ppid}\t${e.kind}\t${e.state}\t${Math.round(e.cpuMs)}ms\t${e.name}\t${e.detail}`).join(`
443
- `)}}),z({name:`kill_process`,description:`Terminate a process by pid.`,input_schema:B({pid:{type:`integer`}},[`pid`]),cap:()=>`system`,describe:e=>`Kill process ${e.pid}`,async run(e,t){if(e.pid===t.pid)throw Error(`refusing to kill the agent itself`);if(!t.os.procs.kill(e.pid))throw Error(`no such process: ${e.pid}`);return`Killed ${e.pid}.`}}),z({name:`system_info`,description:`Describe the environment: which browser APIs are available (WebGPU, OPFS, …), storage quota, mounts, cores and memory.`,input_schema:B({}),cap:()=>null,describe:()=>`System info`,async run(e,t){let n=await navigator.storage?.estimate?.().catch(()=>void 0);return[`BrowserBox ${t.os.version}; root filesystem: ${t.os.rootKind===`opfs`?`OPFS (persistent)`:`memory (lost on reload)`}`,`storage: ${j(n?.usage??NaN)} used of ${j(n?.quota??NaN)}; cores: ${navigator.hardwareConcurrency}; online: ${navigator.onLine}`,`mounts: ${t.os.fs.mounts().map(e=>`${e.point} (${e.fs.label})`).join(`, `)}`,`available: ${t.os.caps.filter(e=>e.ok).map(e=>e.label).join(`, `)}`,`unavailable: ${t.os.caps.filter(e=>!e.ok).map(e=>e.label).join(`, `)||`none`}`].join(`
444
- `)}}),z({name:`notify`,description:`Show the user a notification in every open BrowserBox window.`,input_schema:B({title:{type:`string`},body:{type:`string`}},[`title`]),cap:()=>null,describe:e=>`Notify: ${e.title}`,async run(e,t){return t.os.notify({title:e.title,body:e.body}),`Notification shown.`}}),z({name:`clipboard_write`,description:`Copy text to the user's clipboard.`,input_schema:B({text:{type:`string`}},[`text`]),cap:()=>`clipboard`,describe:e=>`Copy ${e.text.length} characters to the clipboard`,async run(e,t){return await Bt(t).call(`clipboard.write`,e.text),`Copied.`}}),z({name:`clipboard_read`,description:`Read text from the user's clipboard.`,input_schema:B({}),cap:()=>`clipboard`,describe:()=>`Read the clipboard`,async run(e,t){return V(await Bt(t).call(`clipboard.read`))||`(clipboard is empty)`}}),z({name:`speak`,description:`Read text aloud with speech synthesis.`,input_schema:B({text:{type:`string`}},[`text`]),cap:()=>`system`,describe:e=>`Speak: ${e.text.slice(0,80)}`,async run(e,t){return await Bt(t).call(`speak`,e.text.slice(0,2e3)),`Speaking.`}}),z({name:`ask_user`,description:`Ask the user a question and wait for their answer. Use it only when you are blocked on a decision that is genuinely theirs to make.`,input_schema:B({question:{type:`string`},options:{type:`array`,items:{type:`string`},description:`suggested answers`}},[`question`]),cap:()=>null,describe:e=>e.question,run:(e,t)=>t.ask(e.question,e.options)}),z({name:`todo_write`,description:`Publish your task list so the user can follow progress on multi-step work. Send the full list each time; statuses are pending, in_progress or done.`,input_schema:B({items:{type:`array`,items:{type:`object`,properties:{text:{type:`string`},status:{type:`string`,enum:[`pending`,`in_progress`,`done`]}},required:[`text`,`status`]}}},[`items`]),cap:()=>null,describe:e=>`Update task list (${Array.isArray(e.items)?e.items.length:0} items)`,async run(e,t){let n=(Array.isArray(e.items)?e.items:[]).filter(e=>e&&typeof e.text==`string`).map(e=>({text:e.text,status:[`pending`,`in_progress`,`done`].includes(e.status)?e.status:`pending`}));return t.setTodos(n),`Task list updated.`}}),z({name:`use_skill`,description:`Load a skill: returns its instructions and lists the supporting files in its folder. Call this before starting a task that matches a skill listed in your system prompt, then follow the instructions.`,input_schema:B({name:{type:`string`}},[`name`]),cap:()=>null,describe:e=>`Use skill ${e.name}`,async run(e,t){let n=(await G(t.os,`skill`)).filter(e=>e.enabled),r=n.find(t=>t.name===e.name);if(!r)throw Error(`No skill named "${e.name}". Available: ${n.map(e=>e.name).join(`, `)||`none`}`);let i=[];for await(let e of t.os.fs.walk(r.dir,{maxDepth:4}))e.kind===`file`&&e.path!==r.path&&i.push(e.path);return`# Skill: ${r.name}\nFolder: ${r.dir}\n\n${r.body}${i.length?`\n\nSupporting files:\n${i.map(e=>`- ${e}`).join(`
445
- `)}`:``}`}}),z({name:`spawn_agent`,description:`Delegate a self-contained task to a sub-agent with its own fresh context and the same tools. It starts with no knowledge of this conversation, so give it everything it needs. Returns its final report. Useful for keeping long explorations out of your own context.`,input_schema:B({task:{type:`string`},agent:{type:`string`,description:`name of a custom agent listed in your system prompt; omit for a general-purpose sub-agent`}},[`task`]),cap:()=>null,describe:e=>`${e.agent?`Agent ${e.agent}`:`Sub-agent`}: ${e.task.slice(0,120)}`,run:(e,t)=>t.spawnAgent(e.task,e.agent)})],Wt=[...zt,...It,...Ut,...Pt,...Lt],Gt=Wt.filter(e=>[`read_file`,`write_file`,`list_dir`,`shell`,`run_js`].includes(e.name));var Kt=/* @__PURE__ */ e({Agent:()=>$t});const qt=/* @__PURE__ */ new Set([`read_file`,`list_dir`,`glob`,`grep`,`http_fetch`,`system_info`,`list_processes`,`use_skill`,`ask_user`,`todo_write`,`preview_logs`,`web_search`,`web_fetch`]);function Jt(e,t){let n=e.input;return e.name===`write_file`||e.name===`edit_file`||e.name===`delete_path`?typeof n.path==`string`?[t(n.path)]:[]:e.name===`move_path`?[n.copy?null:n.from,n.to].filter(e=>typeof e==`string`).map(t):[]}function Yt(e,t=600){let n=0,r=[];for(let i of e.hunks){if(n+i.lines.length>t)return{...e,hunks:r,note:`Showing the first ${n} lines of the change.`};r.push(i),n+=i.lines.length}return e}const Xt=(e,t)=>t.content.reduce((t,n)=>t+e.kcore.estimateTokens(n.type===`tool_use`?JSON.stringify(n.input):n.type===`tool_result`?n.content:n.text),8);function Zt(e,t,n){let r=t=>t.reduce((t,n)=>t+Xt(e,n),0);if(r(t)<=n)return t;let i=t.map((e,n)=>n>=t.length-4?e:{...e,raw:void 0,content:e.content.map(e=>e.type===`tool_result`&&e.content.length>200?{...e,content:`[earlier output elided to save context]`}:e)});for(;i.length>4&&r(i)>n;){let e=i.findIndex((e,t)=>t>0&&e.role===`user`&&!e.content.some(e=>e.type===`tool_result`));if(e<=0)break;i=i.slice(e)}return i}const Qt=.85;var $t=class e{os;host;messages=[];transcript=[];todos=[];total={input:0,output:0,cacheRead:0};proc;shell;id;#e=null;#t=null;#n;#r;#i=[];#a=0;#o=0;#s=0;checkpoints;diffs={};constructor(e,t,n={}){this.os=e,this.host=t,this.#n=n.depth??0,this.#r=n.persona??null,this.id=n.id??`${(/* @__PURE__ */ new Date()).toISOString().slice(0,19).replace(/[:T]/g,`-`)}-${Math.random().toString(36).slice(2,6)}`,this.proc=e.procs.spawn({name:this.#r?`agent:${this.#r.name}`:this.#n?`sub-agent`:`agent`,kind:`agent`,ppid:n.ppid,detail:`idle`,onKill:()=>this.#e?.abort()}),e.procs.update(this.proc.pid,{state:`idle`}),this.shell=We(new xe(e,{cwd:r,ppid:this.proc.pid})),this.checkpoints=new ft(e)}get busy(){return this.#e!==null}stop(){this.#e?.abort()}dispose(){this.stop(),this.os.procs.exit(this.proc.pid)}lastText(){return this.transcript.findLast(e=>e.role===`assistant`&&e.content.some(e=>e.type===`text`))?.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
446
- `)??``}async send(e,t={}){if(this.busy)return;let n=this.#e=new AbortController,r=e=>this.host.onEvent(e),i=performance.now(),a=W(this.os);this.os.procs.update(this.proc.pid,{state:`running`,detail:it(a)});let o=await navigator.wakeLock?.request(`screen`).catch(()=>null),s=`end`;try{let i=await At(this.os,a),o=i.id===`webllm`,c=this.#r?.tools.length?new Set(this.#r.tools):null,l=async()=>[...o?Gt:Wt,...o?[]:await this.os.packages.all(`tools`),...o?[]:await this.os.mcp.tools()].filter(e=>this.#n===0||![`spawn_agent`,`ask_user`].includes(e.name)).filter(e=>e.name!==`open_app`||I().length>0).filter(e=>!c||c.has(e.name)).filter(e=>!t.plan||qt.has(e.name)),u=this.#i=await l();this.#a=i.contextWindow,this.#t??=await kt(this.os,a,{lite:o,subagent:this.#n>0,persona:this.#r}),r({type:`start`,model:it(a)});let d=a.autoCompact&&!o;d&&this.#d()&&await this.#f(i,n.signal,r,!0,!1),this.checkpoints.begin(this.transcript.length),this.#c({role:`user`,content:[{type:`text`,text:t.plan?`${e}\n\n<mode>Plan mode: investigate with read-only tools only, then reply with a short, numbered plan of what you would change and how you would check it (files, commands, tests). Do not make any changes yet: the user will review the plan and tell you to go ahead.</mode>`:e}]});for(let e=0;;e++){if(e>=a.maxSteps){r({type:`note`,text:`Stopped after ${a.maxSteps} steps (the limit in Settings → Model). Send a message to continue.`}),s=`max_steps`;break}e>0&&(u=this.#i=await l());let t=await this.#p(i,u,n.signal,r);this.#c({role:`assistant`,content:t.content,raw:t.raw});for(let e of[`input`,`output`,`cacheRead`])this.total[e]+=t.usage[e];if(this.#o=t.usage.input+t.usage.cacheRead+t.usage.output,r({type:`usage`,usage:t.usage,total:{...this.total},model:t.model,context:{used:this.#u(),window:this.#a},stats:t.stats}),t.stop===`pause`)continue;if(t.stop===`refusal`){r({type:`note`,text:`The model declined to continue with this request.`});break}let o=t.content.filter(e=>e.type===`tool_use`);if(!o.length){t.stop===`max_tokens`&&r({type:`note`,text:`The reply hit the output limit and was cut off. Ask the agent to continue.`});break}t.stop===`max_tokens`&&r({type:`note`,text:`The reply hit the output limit and was cut off, so its unfinished tool call was not run. The agent was asked to retry in smaller steps.`});let c=t.stop===`max_tokens`?o.map(e=>({type:`tool_result`,tool_use_id:e.id,is_error:!0,content:`Your output was cut off before this tool call was complete, so it was not run. Retry with a smaller input (for example, write large files in several parts).`})):await this.#m(o,u,n.signal,r);this.#c({role:`user`,content:c}),d&&this.#d()&&await this.#f(i,n.signal,r,!0,!0)}}catch(e){n.signal.aborted?s=`stopped`:(s=`error`,e instanceof K||console.error(`[agent]`,e),r({type:`error`,message:e instanceof K?e.message:`Unexpected error: ${e?.message??e}`})),this.#g()}finally{this.#e=null,o?.release().catch(()=>void 0),this.os.procs.account(this.proc.pid,performance.now()-i),this.os.procs.update(this.proc.pid,{state:`idle`,detail:`${this.transcript.length} messages`}),r({type:`done`,reason:s})}}async rewind(e,t){if(this.busy)throw Error(`Stop the agent first.`);let n=this.transcript[e];if(!n||n.role!==`user`||!n.content.some(e=>e.type===`text`))throw Error(`That is not one of your messages.`);let r=this.messages.indexOf(n);if(r<0&&this.messages.length===this.transcript.length&&(r=e),r<0){let e=JSON.stringify(n.content);r=this.messages.findIndex(t=>t.role===`user`&&JSON.stringify(t.content)===e)}if(r<0)throw Error(`The conversation was summarised after this message, so it cannot be rewound to here. Pick a later message.`);let i=t?await this.checkpoints.restore(e):(this.checkpoints.drop(e),{restored:[],skipped:[]});this.messages=this.messages.slice(0,r),this.transcript=this.transcript.slice(0,e);let a=new Set(this.transcript.flatMap(e=>e.content.flatMap(e=>e.type===`tool_use`?[e.id]:[])));for(let e of Object.keys(this.diffs))a.has(e)||delete this.diffs[e];return this.#o=0,i}#c(e){this.messages.push(e),this.transcript.push(e)}reset(){this.messages=[],this.transcript=[],this.#o=0}#l(){let e=e=>this.os.kcore.estimateTokens(e),t={system:e(this.#t??``),tools:e(JSON.stringify(this.#i.map(e=>[e.name,e.description,e.input_schema]))),user:0,assistant:0,toolCalls:0,toolResults:0};for(let n of this.messages)for(let r of n.content)r.type===`tool_use`?t.toolCalls+=e(JSON.stringify(r.input))+8:r.type===`tool_result`?t.toolResults+=e(r.content)+8:n.role===`user`?t.user+=e(r.text):t.assistant+=e(r.text);return t}#u(){return this.#o||Object.values(this.#l()).reduce((e,t)=>e+t,0)}#d(){return this.#a>0&&this.messages.length>1&&this.#u()>this.#a*Qt}context(){let e=W(this.os),t=e.provider===`webllm`;return{window:this.#a,used:this.#u(),reported:this.#o>0,parts:this.#l(),messages:this.messages.length,compactions:this.#s,autoCompactAt:e.autoCompact&&!t?Qt:0,rolling:t}}async compact(){if(this.busy)throw Error(`the agent is busy`);let e=this.#e=new AbortController,t=e=>this.host.onEvent(e);this.os.procs.update(this.proc.pid,{state:`running`,detail:`compacting`});try{let n=W(this.os),r=await At(this.os,n);return this.#a=r.contextWindow,await this.#f(r,e.signal,t,!1,!1)}catch(n){return e.signal.aborted||t({type:`error`,message:n instanceof K?n.message:`Could not compact: ${n?.message??n}`}),!1}finally{this.#e=null,this.os.procs.update(this.proc.pid,{state:`idle`,detail:`${this.transcript.length} messages`}),t({type:`done`,reason:`end`})}}async#f(e,t,n,r,i){if(this.messages.length<2||!this.#t)return!1;n({type:`status`,text:`Compacting the conversation to free up context…`});let a=this.#u(),o=e.contextBudget?Zt(this.os,this.messages,e.contextBudget):this.messages,s=await e.turn({system:this.#t,messages:[...o,{role:`user`,content:[{type:`text`,text:`Your context window is nearly full, so this conversation is about to be replaced by a summary that you write now. Do not call any tools. Write the summary for yourself to continue from, covering:
447
- 1. What the user asked for, in their words where it matters, including constraints and preferences.
448
- 2. What has been done so far: files created or changed (with paths), commands run and their outcomes, decisions made and why.
449
- 3. What is in progress right now and the exact next step.
450
- 4. Anything learned that must not be lost: errors hit and how they were resolved, facts about the environment, open questions.
451
- Be specific and complete rather than brief; anything left out is forgotten.`}]}],tools:this.#i.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),signal:t,onText:()=>void 0,onThinking:()=>void 0,onStatus:()=>void 0});for(let e of[`input`,`output`,`cacheRead`])this.total[e]+=s.usage[e];let c=s.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
452
- `).trim();if(n({type:`status`,text:``}),!c)return n({type:`note`,text:`Compaction failed: the model returned no summary. The conversation was left as it is.`}),!1;this.messages=[{role:`user`,content:[{type:`text`,text:`This session continues an earlier conversation that was compacted to free up context. Summary of everything so far:\n\n${c}${i?`
453
-
454
- Continue the task from where you left off. Do not redo finished work.`:``}`}]}],this.#o=0,this.#s++;let l=this.#u();return this.transcript.push({role:`assistant`,content:[{type:`server_note`,text:`Conversation compacted: about ${a.toLocaleString()} → ${l.toLocaleString()} tokens`}]}),n({type:`compact`,before:a,after:l,auto:r}),!0}async#p(e,t,n,r){let i=performance.now(),a=0,o=await e.turn({system:this.#t,messages:e.contextBudget?Zt(this.os,this.messages,e.contextBudget):this.messages,tools:t.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),signal:n,onText:e=>(a||=performance.now(),r({type:`text`,delta:e})),onThinking:e=>(a||=performance.now(),r({type:`thinking`,delta:e})),onStatus:e=>{a||(i=performance.now()),r({type:`status`,text:e})}}),s=performance.now(),c=Math.max(1,s-(a||i)),l=o.speed?{ms:s-i,ttft:o.speed.ttft,tps:o.speed.tps}:{ms:s-i,ttft:(a||s)-i,tps:a&&o.usage.output>1&&c>=150?o.usage.output/(c/1e3):0};return{...o,stats:l}}async#m(e,t,n,r){let i=e=>({os:this.os,shell:this.shell,signal:n,pid:this.proc.pid,path:e=>m(this.shell.cwd,String(e).replace(/^~(?=\/|$)/,this.shell.env.HOME??``)),ask:async(e,t)=>{this.os.procs.update(this.proc.pid,{state:`blocked`});try{return await this.host.ask(e,t)}finally{this.os.procs.update(this.proc.pid,{state:`running`})}},progress:t=>r({type:`tool_progress`,id:e,chunk:t}),setTodos:e=>{this.todos=e,r({type:`todos`,items:e})},spawnAgent:(t,i)=>this.#h(t,i,n,t=>r({type:`tool_progress`,id:e,chunk:t}))}),a=async e=>{let a=performance.now(),o=t=>({type:`tool_result`,tool_use_id:e.id,content:t,is_error:!0}),s=t.find(t=>t.name===e.name),c=e.name,l=!1,u;if(!s)u=o(`Unknown tool "${e.name}". Available tools: ${t.map(e=>e.name).join(`, `)}`);else if(e.invalid!==void 0)u=o(JSON.stringify({INVALID_JSON:e.invalid}));else{let t=jt(s.input_schema,e.input);if(t.length)u=o(`Invalid input for ${e.name}: ${t.join(`; `)}`);else{let t=i(e.id);c=s.describe(e.input),r({type:`tool_start`,id:e.id,name:e.name,summary:c,input:e.input}),l=!0;try{let i=s.cap(e.input,t),a=!0;if(i&&(this.os.procs.update(this.proc.pid,{state:`blocked`}),a=await this.os.perms.request({cap:i,actor:`The agent`,title:e.name,detail:c},this.host.prompter),this.os.procs.update(this.proc.pid,{state:`running`})),n.throwIfAborted(),!a)u=o(`The user denied permission for this action.`);else{let n=Jt(e,t.path),i=n.length?await this.checkpoints.capture(n):null;if(u={type:`tool_result`,tool_use_id:e.id,content:await s.run(e.input,t)},i&&e.name!==`move_path`&&n.length===1){let t=n[0];if(i.has(t)){let n=await this.os.fs.readText(t).catch(()=>null),a=Yt(gt(t,i.get(t)??null,n));this.diffs[e.id]=a,r({type:`file_change`,id:e.id,diff:a})}}}}catch(e){if(n.aborted)throw e;u=o(e?.message||String(e))}}}return l||r({type:`tool_start`,id:e.id,name:e.name,summary:c,input:e.input}),r({type:`tool_end`,id:e.id,result:u.content,isError:u.is_error??!1,ms:performance.now()-a}),u};if(e.every(e=>{let n=t.find(t=>t.name===e.name);try{return n!==void 0&&e.invalid===void 0&&n.cap(e.input,i(e.id))===null&&![`ask_user`,`spawn_agent`,`todo_write`].includes(e.name)}catch{return!1}}))return Promise.all(e.map(a));let o=[];for(let t of e)o.push(await a(t));return o}async#h(t,n,r,i){let a;if(n){let e=(await G(this.os,`agent`)).filter(e=>e.enabled);if(a=e.find(e=>e.name===n),!a)throw Error(`No agent named "${n}". Available: ${e.map(e=>e.name).join(`, `)||`none`}`)}let o=new e(this.os,{onEvent:e=>{e.type===`tool_start`?i(`▸ ${e.name}: ${e.summary.split(`
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
- `).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
- /* @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(`
459
- `)+`
460
- `,mounts:()=>e.fs.mounts().map(e=>`${e.fs.label}\t${e.point}\t${e.fs.readonly?`ro`:`rw`}`).join(`
461
- `)+`
462
- `,caps:()=>e.caps.map(e=>`${e.ok?`yes`:`no `}\t${e.id}\t${e.label}`).join(`
463
- `)+`
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
- `)+`
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
467
-
468
- BrowserBox is an operating system for AI agents that runs entirely in this
469
- browser tab. Nothing leaves your machine except the model requests you configure.
470
-
471
- - **Agent** — chat with an agent that can use every tool in the OS.
472
- - **Terminal** — a shell. Try \`help\`, \`ls /proc\`, \`agent "summarise this folder"\`.
473
- - **Files / Editor** — browse and edit the persistent filesystem (OPFS).
474
- - **Task Manager** — watch and kill processes, including running agents.
475
- - **Settings** — pick a model: Claude, a local server (Ollama, LM Studio,
476
- llama.cpp) or a model running in this tab on WebGPU.
477
-
478
- The agent works in \`/home/agent\`. Files there survive reloads.
479
- `),await this.fs.writeFile(`${r}/MEMORY.md`,`# Agent memory
480
-
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};