@jeevanand/agent-browserbox-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jeevanand Maurya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,113 @@
1
- # Temporary Holding Version
1
+ # @jeevanand/agent-browserbox-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A sandboxed computer in the browser, for AI agents and anything else that
4
+ must run untrusted code: a filesystem, a shell, and JavaScript, Python and
5
+ WebAssembly runtimes. It runs entirely on the user's device, with no backend
6
+ and no VM service, isolated in its own origin.
7
+
8
+ The SDK is 3 kB (gzip) with no dependencies. The runtime it drives is loaded
9
+ in a hidden frame from another origin, so your page needs no special headers
10
+ and nothing in the box can touch your page.
11
+
12
+ ```sh
13
+ npm install @jeevanand/agent-browserbox-sdk
14
+ ```
15
+
16
+ ```ts
17
+ import { BrowserBox } from '@jeevanand/agent-browserbox-sdk';
18
+
19
+ const box = await BrowserBox.boot();
20
+
21
+ await box.fs.writeFile('main.js', 'print(6 * 7)');
22
+ const { exitCode, stdout } = await box.exec('js main.js'); // 0, "42\n"
23
+
24
+ const p = await box.spawn('echo building && sleep 1 && echo done');
25
+ for await (const chunk of p.output) console.log(chunk); // as it happens
26
+ await p.exit; // 0
27
+
28
+ box.teardown();
29
+ ```
30
+
31
+ ## API
32
+
33
+ ### `BrowserBox.boot(options?)`
34
+
35
+ | Option | Default | |
36
+ |---|---|---|
37
+ | `id` | `'default'` (a fresh id for in-memory boxes) | Which box. Each id is a separate machine with its own files, settings and processes. Booting the same id again, e.g. after a reload, reattaches to its files. Letters, digits, `-` and `_`. |
38
+ | `storage` | `'persistent'` | `'persistent'`: files survive reloads. `'memory'`: nothing is written to disk, and everything is gone when the box is torn down. |
39
+ | `runtimeUrl` | the hosted runtime | Base URL of the runtime. Self-host it with [`@jeevanand/agent-browserbox-runtime`](../runtime). |
40
+ | `permissions` | `'deny'` | What to answer when code in the box asks for a capability (today: network access from `curl` and `js --net`). `'deny'`, `'allow'`, or `(request) => 'once' \| 'always' \| 'deny'`. |
41
+ | `container` | `document.body` | Where the hidden frame goes. |
42
+ | `timeoutMs` | `30000` | Give up booting after this long. |
43
+
44
+ The box has `id`, `version`, `home` (the default working directory), `caps`
45
+ (platform features available) and `storage` (`'opfs'`: files persist across
46
+ reloads, `'memory'`: they do not).
47
+
48
+ ```ts
49
+ // One throwaway machine per agent task:
50
+ const box = await BrowserBox.boot({ storage: 'memory' });
51
+ // A project that should still be there tomorrow:
52
+ const project = await BrowserBox.boot({ id: 'my-project' });
53
+ ```
54
+
55
+ ### Files: `box.fs`
56
+
57
+ `readFile(path)` → `Uint8Array` · `readTextFile(path)` · `writeFile(path, string | Uint8Array)` ·
58
+ `mkdir(path)` · `readdir(path)` → `FileStat[]` · `stat(path)` → `FileStat | null` ·
59
+ `exists(path)` · `rm(path, { recursive })` · `rename(from, to)` · `cp(from, to)`
60
+
61
+ Relative paths resolve against `box.home`. Parent folders are created as needed.
62
+ Errors are `BoxError`s with a `code` (`ENOENT`, `EEXIST`, `ENOTDIR`, …).
63
+
64
+ ### Commands
65
+
66
+ - `box.exec(command, { cwd, env, timeoutMs })` → `{ exitCode, stdout, stderr }`
67
+ - `box.spawn(command, { cwd, env, timeoutMs })` → a process with `output`,
68
+ `stdout` and `stderr` (`ReadableStream<string>`), `exit` (a promise of the exit
69
+ code) and `kill()`.
70
+
71
+ Exit code 124 means the command timed out, 130 that it was killed. Output is
72
+ plain text: colour codes are removed, and `exec` collapses progress bars
73
+ (lines redrawn with `\r`) to their final state.
74
+
75
+ Commands run in BrowserBox's shell (`help` lists them): files and text (`ls`,
76
+ `cat`, `grep`, `find`, `sort`, …), `js` (JavaScript in a sandboxed worker),
77
+ `wasm` (WASI programs), `curl`, `gzip`, `npm` (records dependencies; packages
78
+ load from esm.sh) and `pkg install python|git|sqlite|zip|esbuild` for more.
79
+ It is not bash, and there is no Node.js.
80
+
81
+ ### `box.teardown()`
82
+
83
+ Removes the frame and fails any call still pending.
84
+
85
+ ## Isolation, and what to know
86
+
87
+ - **The box runs on the runtime's origin**, in a frame with no access to your
88
+ page, and your page has no access to it except through this API. Code inside
89
+ runs in further sandboxed frames and workers with an opaque origin.
90
+ - **Network access needs permission.** `curl` and `js --net` ask, and the
91
+ answer comes from your `permissions` option (deny by default). Installing
92
+ packages (`pkg`, `npm`) fetches from fixed registries without asking.
93
+ - **Every box is a separate machine.** Each id has its own kernel, files,
94
+ settings and permission grants; boxes never see each other's files.
95
+ - **Storage is per embedding site.** Browsers partition a cross-site frame's
96
+ storage by the top-level site, so your boxes never see another site's, even
97
+ with the same id.
98
+
99
+ ## Self-hosting
100
+
101
+ The default runtime is hosted on GitHub Pages. To serve it yourself:
102
+
103
+ ```sh
104
+ npx @jeevanand/agent-browserbox-runtime # http://127.0.0.1:4180/
105
+ ```
106
+
107
+ or copy its files into your site (`npx @jeevanand/agent-browserbox-runtime --dir`
108
+ prints where they are) and pass that URL as `runtimeUrl`. Use the same version
109
+ of the SDK and the runtime.
110
+
111
+ ## License
112
+
113
+ MIT
@@ -0,0 +1,116 @@
1
+ import { PROTOCOL_VERSION, type ExecOptions, type ExecResult, type FileStat, type Method, type Methods, type PermissionDecision, type PermissionRequest } from './protocol.js';
2
+ export type { ExecOptions, ExecResult, FileStat, PermissionDecision, PermissionRequest };
3
+ export { PROTOCOL_VERSION };
4
+ /** This SDK's version. Always released together with the runtime of the same version. */
5
+ export declare const VERSION = "0.1.1";
6
+ /**
7
+ * The hosted runtime of exactly this SDK's version. Released runtimes never
8
+ * change, so a newer runtime can never break an app on this SDK. Self-host it
9
+ * with @jeevanand/agent-browserbox-runtime.
10
+ */
11
+ export declare const DEFAULT_RUNTIME_URL = "https://jeevanandmaurya.github.io/agent-browserbox/runtime/0.1.1/";
12
+ export type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
13
+ export interface BootOptions {
14
+ /** Base URL of the runtime (the folder holding embed/, kernel/, assets/). Default: the hosted runtime. */
15
+ runtimeUrl?: string;
16
+ /**
17
+ * Which box. Each id is a separate machine with its own files, settings and
18
+ * processes; booting the same id again (e.g. after a reload) reattaches to
19
+ * its files. Letters, digits, '-' and '_'. Default: 'default', or a fresh id
20
+ * for an in-memory box.
21
+ */
22
+ id?: string;
23
+ /** 'persistent' (default): files survive reloads. 'memory': everything is gone when the box is torn down. */
24
+ storage?: 'persistent' | 'memory';
25
+ /** Element the hidden runtime frame is added to. Default: document.body. */
26
+ container?: HTMLElement;
27
+ /**
28
+ * What to answer when code in the box asks for a capability (network access,
29
+ * …). 'deny' (default), 'allow', or a function deciding per request.
30
+ */
31
+ permissions?: 'deny' | 'allow' | PermissionHandler;
32
+ /** Give up booting after this many ms. Default 30000. */
33
+ timeoutMs?: number;
34
+ }
35
+ /** An error from the box. `code` is set for filesystem errors (ENOENT, EEXIST, …). */
36
+ export declare class BoxError extends Error {
37
+ readonly code?: string | undefined;
38
+ constructor(message: string, code?: string | undefined);
39
+ }
40
+ interface Sink {
41
+ out: ReadableStreamDefaultController<string>[];
42
+ stdout: ReadableStreamDefaultController<string>[];
43
+ stderr: ReadableStreamDefaultController<string>[];
44
+ exit(code: number): void;
45
+ }
46
+ /** A running command in the box. */
47
+ export declare class BoxProcess {
48
+ readonly pid: number;
49
+ private box;
50
+ /** stdout and stderr together, in the order they were written. */
51
+ readonly output: ReadableStream<string>;
52
+ readonly stdout: ReadableStream<string>;
53
+ readonly stderr: ReadableStream<string>;
54
+ /** Resolves with the exit code (124: timed out, 130: killed). */
55
+ readonly exit: Promise<number>;
56
+ /** @internal */
57
+ constructor(pid: number, box: BrowserBox, attach: (sink: Sink) => void);
58
+ /** Stops the command. Resolves false if it had already finished. */
59
+ kill(): Promise<boolean>;
60
+ }
61
+ /** The box's filesystem. Paths are absolute, or relative to the box's home. */
62
+ export declare class BoxFs {
63
+ #private;
64
+ private box;
65
+ /** @internal */
66
+ constructor(box: BrowserBox);
67
+ readFile(path: string): Promise<Uint8Array>;
68
+ readTextFile(path: string): Promise<string>;
69
+ /** Creates parent folders as needed. */
70
+ writeFile(path: string, data: string | Uint8Array): Promise<void>;
71
+ /** Creates parent folders as needed. */
72
+ mkdir(path: string): Promise<void>;
73
+ readdir(path?: string): Promise<FileStat[]>;
74
+ /** Null when nothing is there. */
75
+ stat(path: string): Promise<FileStat | null>;
76
+ exists(path: string): Promise<boolean>;
77
+ rm(path: string, opts?: {
78
+ recursive?: boolean;
79
+ }): Promise<void>;
80
+ rename(from: string, to: string): Promise<void>;
81
+ cp(from: string, to: string): Promise<void>;
82
+ }
83
+ /**
84
+ * A sandboxed computer in the browser: a filesystem, a shell, and JavaScript,
85
+ * Python and WebAssembly runtimes, all inside a hidden frame on the runtime's
86
+ * origin. Nothing in it can reach the embedding page.
87
+ *
88
+ * const box = await BrowserBox.boot();
89
+ * await box.fs.writeFile('hello.py', 'print(6 * 7)');
90
+ * const { stdout } = await box.exec('python hello.py');
91
+ */
92
+ export declare class BrowserBox {
93
+ #private;
94
+ readonly fs: BoxFs;
95
+ /** Runtime version. */
96
+ readonly version: string;
97
+ /** This box's id. */
98
+ readonly id: string;
99
+ /** Default working directory; relative paths resolve against it. */
100
+ readonly home: string;
101
+ /** Platform features the runtime has (e.g. 'opfs', 'webgpu'). */
102
+ readonly caps: readonly string[];
103
+ /** 'opfs': files persist across reloads (separately for each embedding site). 'memory': they do not. */
104
+ readonly storage: 'opfs' | 'memory';
105
+ private constructor();
106
+ /** Starts a box: loads the runtime in a hidden frame and connects to it. */
107
+ static boot(opts?: BootOptions): Promise<BrowserBox>;
108
+ /** Runs a shell command line to completion and returns its output. */
109
+ exec(command: string, opts?: ExecOptions): Promise<ExecResult>;
110
+ /** Starts a shell command line and streams its output. */
111
+ spawn(command: string, opts?: ExecOptions): Promise<BoxProcess>;
112
+ /** Shuts the box down: removes its frame and fails anything still pending. */
113
+ teardown(): void;
114
+ /** @internal Low-level call into the runtime. */
115
+ call<M extends Method>(method: M, ...args: Parameters<Methods[M]>): Promise<ReturnType<Methods[M]>>;
116
+ }
package/dist/index.js ADDED
@@ -0,0 +1,267 @@
1
+ import { PROTOCOL_VERSION, } from './protocol.js';
2
+ export { PROTOCOL_VERSION };
3
+ /** This SDK's version. Always released together with the runtime of the same version. */
4
+ export const VERSION = '0.1.1';
5
+ /**
6
+ * The hosted runtime of exactly this SDK's version. Released runtimes never
7
+ * change, so a newer runtime can never break an app on this SDK. Self-host it
8
+ * with @jeevanand/agent-browserbox-runtime.
9
+ */
10
+ export const DEFAULT_RUNTIME_URL = `https://jeevanandmaurya.github.io/agent-browserbox/runtime/${VERSION}/`;
11
+ /** An error from the box. `code` is set for filesystem errors (ENOENT, EEXIST, …). */
12
+ export class BoxError extends Error {
13
+ code;
14
+ constructor(message, code) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = 'BoxError';
18
+ }
19
+ }
20
+ /** A running command in the box. */
21
+ export class BoxProcess {
22
+ pid;
23
+ box;
24
+ /** stdout and stderr together, in the order they were written. */
25
+ output;
26
+ stdout;
27
+ stderr;
28
+ /** Resolves with the exit code (124: timed out, 130: killed). */
29
+ exit;
30
+ /** @internal */
31
+ constructor(pid, box, attach) {
32
+ this.pid = pid;
33
+ this.box = box;
34
+ const sink = { out: [], stdout: [], stderr: [], exit: () => undefined };
35
+ const stream = (list) => new ReadableStream({ start: (c) => void list.push(c) });
36
+ this.output = stream(sink.out);
37
+ this.stdout = stream(sink.stdout);
38
+ this.stderr = stream(sink.stderr);
39
+ this.exit = new Promise((resolve) => (sink.exit = resolve));
40
+ attach(sink);
41
+ }
42
+ /** Stops the command. Resolves false if it had already finished. */
43
+ kill() {
44
+ return this.box.call('kill', this.pid);
45
+ }
46
+ }
47
+ /** The box's filesystem. Paths are absolute, or relative to the box's home. */
48
+ export class BoxFs {
49
+ box;
50
+ /** @internal */
51
+ constructor(box) {
52
+ this.box = box;
53
+ }
54
+ #abs(path) {
55
+ return path.startsWith('/') ? path : `${this.box.home.replace(/\/$/, '')}/${path}`;
56
+ }
57
+ readFile(path) {
58
+ return this.box.call('fs.readFile', this.#abs(path));
59
+ }
60
+ readTextFile(path) {
61
+ return this.box.call('fs.readTextFile', this.#abs(path));
62
+ }
63
+ /** Creates parent folders as needed. */
64
+ writeFile(path, data) {
65
+ return this.box.call('fs.writeFile', this.#abs(path), data);
66
+ }
67
+ /** Creates parent folders as needed. */
68
+ mkdir(path) {
69
+ return this.box.call('fs.mkdir', this.#abs(path));
70
+ }
71
+ readdir(path = '.') {
72
+ return this.box.call('fs.readdir', this.#abs(path));
73
+ }
74
+ /** Null when nothing is there. */
75
+ stat(path) {
76
+ return this.box.call('fs.stat', this.#abs(path));
77
+ }
78
+ exists(path) {
79
+ return this.box.call('fs.exists', this.#abs(path));
80
+ }
81
+ rm(path, opts) {
82
+ return this.box.call('fs.rm', this.#abs(path), opts);
83
+ }
84
+ rename(from, to) {
85
+ return this.box.call('fs.rename', this.#abs(from), this.#abs(to));
86
+ }
87
+ cp(from, to) {
88
+ return this.box.call('fs.cp', this.#abs(from), this.#abs(to));
89
+ }
90
+ }
91
+ /**
92
+ * A sandboxed computer in the browser: a filesystem, a shell, and JavaScript,
93
+ * Python and WebAssembly runtimes, all inside a hidden frame on the runtime's
94
+ * origin. Nothing in it can reach the embedding page.
95
+ *
96
+ * const box = await BrowserBox.boot();
97
+ * await box.fs.writeFile('hello.py', 'print(6 * 7)');
98
+ * const { stdout } = await box.exec('python hello.py');
99
+ */
100
+ export class BrowserBox {
101
+ fs = new BoxFs(this);
102
+ /** Runtime version. */
103
+ version;
104
+ /** This box's id. */
105
+ id;
106
+ /** Default working directory; relative paths resolve against it. */
107
+ home;
108
+ /** Platform features the runtime has (e.g. 'opfs', 'webgpu'). */
109
+ caps;
110
+ /** 'opfs': files persist across reloads (separately for each embedding site). 'memory': they do not. */
111
+ storage;
112
+ #port;
113
+ #frame;
114
+ #permissions;
115
+ #nextId = 1;
116
+ #calls = new Map();
117
+ #sinks = new Map();
118
+ /** Events for processes whose spawn() has not returned yet. */
119
+ #early = new Map();
120
+ #closed = null;
121
+ constructor(port, frame, hello, permissions) {
122
+ this.#port = port;
123
+ this.#frame = frame;
124
+ this.#permissions = permissions;
125
+ this.version = hello.version;
126
+ this.id = hello.id;
127
+ this.home = hello.home;
128
+ this.caps = hello.caps;
129
+ this.storage = hello.storage;
130
+ port.onmessage = (e) => this.#onMessage(e.data);
131
+ }
132
+ /** Starts a box: loads the runtime in a hidden frame and connects to it. */
133
+ static boot(opts = {}) {
134
+ const base = new URL(opts.runtimeUrl ?? DEFAULT_RUNTIME_URL, globalThis.location?.href);
135
+ if (!base.pathname.endsWith('/'))
136
+ base.pathname += '/';
137
+ const memory = opts.storage === 'memory';
138
+ const id = opts.id ?? (memory ? `mem-${crypto.randomUUID()}` : 'default');
139
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id))
140
+ return Promise.reject(new BoxError(`invalid box id "${id}": use letters, digits, '-' and '_' (at most 64)`));
141
+ const src = new URL(`embed/?box=${encodeURIComponent(id)}&storage=${memory ? 'memory' : 'opfs'}`, base);
142
+ const permissions = typeof opts.permissions === 'function' ? opts.permissions : opts.permissions === 'allow' ? () => 'once' : () => 'deny';
143
+ const frame = document.createElement('iframe');
144
+ frame.src = src.href;
145
+ frame.title = 'BrowserBox runtime';
146
+ frame.setAttribute('aria-hidden', 'true');
147
+ frame.style.cssText = 'position:absolute;width:0;height:0;border:0;visibility:hidden';
148
+ return new Promise((resolve, reject) => {
149
+ const fail = (message) => {
150
+ cleanup();
151
+ frame.remove();
152
+ reject(new BoxError(message));
153
+ };
154
+ const timer = setTimeout(() => fail(`the runtime at ${src.href} did not respond within ${opts.timeoutMs ?? 30000} ms`), opts.timeoutMs ?? 30000);
155
+ const onWindowMessage = (e) => {
156
+ if (e.source !== frame.contentWindow || e.origin !== src.origin || e.data?.type !== 'bbx:embed-ready')
157
+ return;
158
+ const { port1, port2 } = new MessageChannel();
159
+ port1.onmessage = (m) => {
160
+ const msg = m.data;
161
+ if (msg.t === 'refused')
162
+ return fail(`the runtime refused to connect: ${msg.error}`);
163
+ if (msg.t !== 'hello')
164
+ return;
165
+ cleanup();
166
+ resolve(new BrowserBox(port1, frame, msg, permissions));
167
+ };
168
+ frame.contentWindow.postMessage({ type: 'bbx:connect', protocol: PROTOCOL_VERSION }, src.origin, [port2]);
169
+ };
170
+ const cleanup = () => {
171
+ clearTimeout(timer);
172
+ removeEventListener('message', onWindowMessage);
173
+ };
174
+ addEventListener('message', onWindowMessage);
175
+ (opts.container ?? document.body).append(frame);
176
+ });
177
+ }
178
+ /** Runs a shell command line to completion and returns its output. */
179
+ exec(command, opts) {
180
+ return this.call('exec', command, opts);
181
+ }
182
+ /** Starts a shell command line and streams its output. */
183
+ async spawn(command, opts) {
184
+ const pid = await this.call('spawn', command, opts);
185
+ return new BoxProcess(pid, this, (sink) => {
186
+ this.#sinks.set(pid, sink);
187
+ for (const ev of this.#early.get(pid) ?? [])
188
+ this.#deliver(pid, ev);
189
+ this.#early.delete(pid);
190
+ });
191
+ }
192
+ /** Shuts the box down: removes its frame and fails anything still pending. */
193
+ teardown() {
194
+ if (this.#closed)
195
+ return;
196
+ this.#closed = new BoxError('the box was torn down');
197
+ for (const c of this.#calls.values())
198
+ c.reject(this.#closed);
199
+ this.#calls.clear();
200
+ for (const pid of [...this.#sinks.keys()])
201
+ this.#deliver(pid, { t: 'exit', exitCode: 130 });
202
+ this.#port.close();
203
+ this.#frame.remove();
204
+ }
205
+ /** @internal Low-level call into the runtime. */
206
+ call(method, ...args) {
207
+ if (this.#closed)
208
+ return Promise.reject(this.#closed);
209
+ const id = this.#nextId++;
210
+ return new Promise((resolve, reject) => {
211
+ this.#calls.set(id, { resolve: resolve, reject });
212
+ this.#port.postMessage({ t: 'call', id, method, args });
213
+ });
214
+ }
215
+ #onMessage(msg) {
216
+ switch (msg.t) {
217
+ case 'result': {
218
+ const c = this.#calls.get(msg.id);
219
+ this.#calls.delete(msg.id);
220
+ if (msg.ok)
221
+ c?.resolve(msg.value);
222
+ else
223
+ c?.reject(new BoxError(msg.error, msg.code));
224
+ return;
225
+ }
226
+ case 'output':
227
+ return this.#route(msg.pid, { t: 'output', stream: msg.stream, data: msg.data });
228
+ case 'exit':
229
+ return this.#route(msg.pid, { t: 'exit', exitCode: msg.exitCode });
230
+ case 'permission':
231
+ void Promise.resolve()
232
+ .then(() => this.#permissions(msg.request))
233
+ .catch(() => 'deny')
234
+ .then((decision) => this.#port.postMessage({ t: 'permission-answer', id: msg.id, decision }));
235
+ return;
236
+ }
237
+ }
238
+ #route(pid, ev) {
239
+ if (this.#sinks.has(pid))
240
+ return this.#deliver(pid, ev);
241
+ const list = this.#early.get(pid) ?? [];
242
+ list.push(ev);
243
+ this.#early.set(pid, list);
244
+ }
245
+ #deliver(pid, ev) {
246
+ const sink = this.#sinks.get(pid);
247
+ if (!sink)
248
+ return;
249
+ // A stream the reader cancelled throws on enqueue/close; that reader just stops getting data.
250
+ const each = (list, fn) => {
251
+ for (const c of list) {
252
+ try {
253
+ fn(c);
254
+ }
255
+ catch {
256
+ /* cancelled */
257
+ }
258
+ }
259
+ };
260
+ if (ev.t === 'output')
261
+ return each([...sink.out, ...sink[ev.stream]], (c) => c.enqueue(ev.data));
262
+ each([...sink.out, ...sink.stdout, ...sink.stderr], (c) => c.close());
263
+ this.#sinks.delete(pid);
264
+ sink.exit(ev.exitCode);
265
+ }
266
+ }
267
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,GAWjB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAAE,gBAAgB,EAAE,CAAC;AAE5B,yFAAyF;AACzF,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,8DAA8D,OAAO,GAAG,CAAC;AA2B5G,sFAAsF;AACtF,MAAM,OAAO,QAAS,SAAQ,KAAK;IAGtB,IAAI;IAFf,YACE,OAAe,EACN,IAAa;QAEtB,KAAK,CAAC,OAAO,CAAC,CAAC;oBAFN,IAAI;QAGb,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAWD,oCAAoC;AACpC,MAAM,OAAO,UAAU;IAUV,GAAG;IACJ,GAAG;IAVb,kEAAkE;IACzD,MAAM,CAAyB;IAC/B,MAAM,CAAyB;IAC/B,MAAM,CAAyB;IACxC,iEAAiE;IACxD,IAAI,CAAkB;IAE/B,gBAAgB;IAChB,YACW,GAAW,EACZ,GAAe,EACvB,MAA4B;mBAFnB,GAAG;mBACJ,GAAG;QAGX,MAAM,IAAI,GAAS,EAAE,GAAG,EAAE,EAA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AO,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QACjG,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;CACF"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The wire protocol between the SDK (in the embedding page) and the runtime
3
+ * (a hidden iframe on the runtime's origin). Shared by both sides; bump
4
+ * PROTOCOL_VERSION on any incompatible change.
5
+ *
6
+ * Handshake, over window.postMessage:
7
+ * runtime → parent { type: 'bbx:embed-ready' }
8
+ * SDK → runtime { type: 'bbx:connect', protocol } + a MessagePort
9
+ * Everything after that goes over the port: calls and results, process
10
+ * output and exit, and permission questions.
11
+ */
12
+ export declare const PROTOCOL_VERSION = 1;
13
+ export interface Hello {
14
+ t: 'hello';
15
+ protocol: number;
16
+ /** Runtime version. */
17
+ version: string;
18
+ /** The box's id. */
19
+ id: string;
20
+ /** The default working directory for commands. */
21
+ home: string;
22
+ /** Platform features available in the runtime (e.g. 'opfs', 'webgpu'). */
23
+ caps: string[];
24
+ /** 'opfs' when files persist across reloads (per embedding site), 'memory' when not. */
25
+ storage: 'opfs' | 'memory';
26
+ }
27
+ export interface Refused {
28
+ t: 'refused';
29
+ error: string;
30
+ }
31
+ export interface FileStat {
32
+ path: string;
33
+ name: string;
34
+ kind: 'file' | 'dir';
35
+ size: number;
36
+ /** Last modified, ms since the epoch. */
37
+ mtime: number;
38
+ }
39
+ export interface ExecOptions {
40
+ /** Working directory. Default: the runtime's home. */
41
+ cwd?: string;
42
+ /** Extra environment variables for the command. */
43
+ env?: Record<string, string>;
44
+ /** Kill the command after this many ms (exit code 124). */
45
+ timeoutMs?: number;
46
+ }
47
+ export interface ExecResult {
48
+ exitCode: number;
49
+ stdout: string;
50
+ stderr: string;
51
+ }
52
+ export type PermissionDecision = 'once' | 'always' | 'deny';
53
+ export interface PermissionRequest {
54
+ /** What is asked for: 'fs.write', 'exec', 'net', 'clipboard', 'notify' or 'system'. */
55
+ cap: string;
56
+ /** Who is asking, e.g. a command. */
57
+ actor: string;
58
+ /** Short human title, e.g. "Network access". */
59
+ title: string;
60
+ /** The exact thing being approved (command, path, URL). */
61
+ detail: string;
62
+ }
63
+ /** Calls the SDK can make, with their arguments and results. */
64
+ export interface Methods {
65
+ info(): Hello;
66
+ 'fs.readFile'(path: string): Uint8Array;
67
+ 'fs.readTextFile'(path: string): string;
68
+ 'fs.writeFile'(path: string, data: string | Uint8Array): void;
69
+ 'fs.mkdir'(path: string): void;
70
+ 'fs.readdir'(path: string): FileStat[];
71
+ 'fs.stat'(path: string): FileStat | null;
72
+ 'fs.exists'(path: string): boolean;
73
+ 'fs.rm'(path: string, opts?: {
74
+ recursive?: boolean;
75
+ }): void;
76
+ 'fs.rename'(from: string, to: string): void;
77
+ 'fs.cp'(from: string, to: string): void;
78
+ exec(command: string, opts?: ExecOptions): ExecResult;
79
+ /** Starts a command; its output and exit arrive as events. Returns its process id. */
80
+ spawn(command: string, opts?: ExecOptions): number;
81
+ kill(pid: number): boolean;
82
+ }
83
+ export type Method = keyof Methods;
84
+ /** SDK → runtime. */
85
+ export type ToRuntime = {
86
+ t: 'call';
87
+ id: number;
88
+ method: Method;
89
+ args: unknown[];
90
+ } | {
91
+ t: 'permission-answer';
92
+ id: number;
93
+ decision: PermissionDecision;
94
+ };
95
+ /** Runtime → SDK. */
96
+ export type FromRuntime = Hello | Refused | {
97
+ t: 'result';
98
+ id: number;
99
+ ok: true;
100
+ value: unknown;
101
+ } | {
102
+ t: 'result';
103
+ id: number;
104
+ ok: false;
105
+ error: string;
106
+ code?: string;
107
+ } | {
108
+ t: 'output';
109
+ pid: number;
110
+ stream: 'stdout' | 'stderr';
111
+ data: string;
112
+ } | {
113
+ t: 'exit';
114
+ pid: number;
115
+ exitCode: number;
116
+ } | {
117
+ t: 'permission';
118
+ id: number;
119
+ request: PermissionRequest;
120
+ };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The wire protocol between the SDK (in the embedding page) and the runtime
3
+ * (a hidden iframe on the runtime's origin). Shared by both sides; bump
4
+ * PROTOCOL_VERSION on any incompatible change.
5
+ *
6
+ * Handshake, over window.postMessage:
7
+ * runtime → parent { type: 'bbx:embed-ready' }
8
+ * SDK → runtime { type: 'bbx:connect', protocol } + a MessagePort
9
+ * Everything after that goes over the port: calls and results, process
10
+ * output and exit, and permission questions.
11
+ */
12
+ export const PROTOCOL_VERSION = 1;
13
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@jeevanand/agent-browserbox-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "A sandboxed computer in the browser for AI agents: filesystem, shell, JavaScript, Python and WebAssembly, isolated in its own origin. No backend.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./protocol": {
15
+ "types": "./dist/protocol.d.ts",
16
+ "import": "./dist/protocol.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "src",
22
+ "README.md"
23
+ ],
24
+ "sideEffects": false,
25
+ "keywords": [
26
+ "sandbox",
27
+ "ai-agent",
28
+ "agent",
29
+ "browser",
30
+ "vm",
31
+ "virtual-machine",
32
+ "filesystem",
33
+ "shell",
34
+ "wasm",
35
+ "python",
36
+ "llm"
37
+ ],
38
+ "homepage": "https://github.com/jeevanandmaurya/agent-browserbox/tree/main/packages/sdk#readme",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/jeevanandmaurya/agent-browserbox.git",
42
+ "directory": "packages/sdk"
43
+ },
44
+ "bugs": {
45
+ "url": "https://github.com/jeevanandmaurya/agent-browserbox/issues"
46
+ },
47
+ "author": "Jeevanand Maurya",
48
+ "license": "MIT",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc -p tsconfig.json",
54
+ "prepack": "npm run build"
55
+ }
56
+ }
package/src/index.ts ADDED
@@ -0,0 +1,318 @@
1
+ import {
2
+ PROTOCOL_VERSION,
3
+ type ExecOptions,
4
+ type ExecResult,
5
+ type FileStat,
6
+ type FromRuntime,
7
+ type Hello,
8
+ type Method,
9
+ type Methods,
10
+ type PermissionDecision,
11
+ type PermissionRequest,
12
+ type ToRuntime,
13
+ } from './protocol.js';
14
+
15
+ export type { ExecOptions, ExecResult, FileStat, PermissionDecision, PermissionRequest };
16
+ export { PROTOCOL_VERSION };
17
+
18
+ /** This SDK's version. Always released together with the runtime of the same version. */
19
+ export const VERSION = '0.1.1';
20
+
21
+ /**
22
+ * The hosted runtime of exactly this SDK's version. Released runtimes never
23
+ * change, so a newer runtime can never break an app on this SDK. Self-host it
24
+ * with @jeevanand/agent-browserbox-runtime.
25
+ */
26
+ export const DEFAULT_RUNTIME_URL = `https://jeevanandmaurya.github.io/agent-browserbox/runtime/${VERSION}/`;
27
+
28
+ export type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
29
+
30
+ export interface BootOptions {
31
+ /** Base URL of the runtime (the folder holding embed/, kernel/, assets/). Default: the hosted runtime. */
32
+ runtimeUrl?: string;
33
+ /**
34
+ * Which box. Each id is a separate machine with its own files, settings and
35
+ * processes; booting the same id again (e.g. after a reload) reattaches to
36
+ * its files. Letters, digits, '-' and '_'. Default: 'default', or a fresh id
37
+ * for an in-memory box.
38
+ */
39
+ id?: string;
40
+ /** 'persistent' (default): files survive reloads. 'memory': everything is gone when the box is torn down. */
41
+ storage?: 'persistent' | 'memory';
42
+ /** Element the hidden runtime frame is added to. Default: document.body. */
43
+ container?: HTMLElement;
44
+ /**
45
+ * What to answer when code in the box asks for a capability (network access,
46
+ * …). 'deny' (default), 'allow', or a function deciding per request.
47
+ */
48
+ permissions?: 'deny' | 'allow' | PermissionHandler;
49
+ /** Give up booting after this many ms. Default 30000. */
50
+ timeoutMs?: number;
51
+ }
52
+
53
+ /** An error from the box. `code` is set for filesystem errors (ENOENT, EEXIST, …). */
54
+ export class BoxError extends Error {
55
+ constructor(
56
+ message: string,
57
+ readonly code?: string,
58
+ ) {
59
+ super(message);
60
+ this.name = 'BoxError';
61
+ }
62
+ }
63
+
64
+ interface Sink {
65
+ out: ReadableStreamDefaultController<string>[];
66
+ stdout: ReadableStreamDefaultController<string>[];
67
+ stderr: ReadableStreamDefaultController<string>[];
68
+ exit(code: number): void;
69
+ }
70
+
71
+ type ProcEvent = { t: 'output'; stream: 'stdout' | 'stderr'; data: string } | { t: 'exit'; exitCode: number };
72
+
73
+ /** A running command in the box. */
74
+ export class BoxProcess {
75
+ /** stdout and stderr together, in the order they were written. */
76
+ readonly output: ReadableStream<string>;
77
+ readonly stdout: ReadableStream<string>;
78
+ readonly stderr: ReadableStream<string>;
79
+ /** Resolves with the exit code (124: timed out, 130: killed). */
80
+ readonly exit: Promise<number>;
81
+
82
+ /** @internal */
83
+ constructor(
84
+ readonly pid: number,
85
+ private box: BrowserBox,
86
+ attach: (sink: Sink) => void,
87
+ ) {
88
+ const sink: Sink = { out: [], stdout: [], stderr: [], exit: () => undefined };
89
+ const stream = (list: ReadableStreamDefaultController<string>[]) => new ReadableStream<string>({ start: (c) => void list.push(c) });
90
+ this.output = stream(sink.out);
91
+ this.stdout = stream(sink.stdout);
92
+ this.stderr = stream(sink.stderr);
93
+ this.exit = new Promise((resolve) => (sink.exit = resolve));
94
+ attach(sink);
95
+ }
96
+
97
+ /** Stops the command. Resolves false if it had already finished. */
98
+ kill(): Promise<boolean> {
99
+ return this.box.call('kill', this.pid);
100
+ }
101
+ }
102
+
103
+ /** The box's filesystem. Paths are absolute, or relative to the box's home. */
104
+ export class BoxFs {
105
+ /** @internal */
106
+ constructor(private box: BrowserBox) {}
107
+
108
+ #abs(path: string): string {
109
+ return path.startsWith('/') ? path : `${this.box.home.replace(/\/$/, '')}/${path}`;
110
+ }
111
+
112
+ readFile(path: string): Promise<Uint8Array> {
113
+ return this.box.call('fs.readFile', this.#abs(path));
114
+ }
115
+ readTextFile(path: string): Promise<string> {
116
+ return this.box.call('fs.readTextFile', this.#abs(path));
117
+ }
118
+ /** Creates parent folders as needed. */
119
+ writeFile(path: string, data: string | Uint8Array): Promise<void> {
120
+ return this.box.call('fs.writeFile', this.#abs(path), data);
121
+ }
122
+ /** Creates parent folders as needed. */
123
+ mkdir(path: string): Promise<void> {
124
+ return this.box.call('fs.mkdir', this.#abs(path));
125
+ }
126
+ readdir(path = '.'): Promise<FileStat[]> {
127
+ return this.box.call('fs.readdir', this.#abs(path));
128
+ }
129
+ /** Null when nothing is there. */
130
+ stat(path: string): Promise<FileStat | null> {
131
+ return this.box.call('fs.stat', this.#abs(path));
132
+ }
133
+ exists(path: string): Promise<boolean> {
134
+ return this.box.call('fs.exists', this.#abs(path));
135
+ }
136
+ rm(path: string, opts?: { recursive?: boolean }): Promise<void> {
137
+ return this.box.call('fs.rm', this.#abs(path), opts);
138
+ }
139
+ rename(from: string, to: string): Promise<void> {
140
+ return this.box.call('fs.rename', this.#abs(from), this.#abs(to));
141
+ }
142
+ cp(from: string, to: string): Promise<void> {
143
+ return this.box.call('fs.cp', this.#abs(from), this.#abs(to));
144
+ }
145
+ }
146
+
147
+ /**
148
+ * A sandboxed computer in the browser: a filesystem, a shell, and JavaScript,
149
+ * Python and WebAssembly runtimes, all inside a hidden frame on the runtime's
150
+ * origin. Nothing in it can reach the embedding page.
151
+ *
152
+ * const box = await BrowserBox.boot();
153
+ * await box.fs.writeFile('hello.py', 'print(6 * 7)');
154
+ * const { stdout } = await box.exec('python hello.py');
155
+ */
156
+ export class BrowserBox {
157
+ readonly fs = new BoxFs(this);
158
+ /** Runtime version. */
159
+ readonly version: string;
160
+ /** This box's id. */
161
+ readonly id: string;
162
+ /** Default working directory; relative paths resolve against it. */
163
+ readonly home: string;
164
+ /** Platform features the runtime has (e.g. 'opfs', 'webgpu'). */
165
+ readonly caps: readonly string[];
166
+ /** 'opfs': files persist across reloads (separately for each embedding site). 'memory': they do not. */
167
+ readonly storage: 'opfs' | 'memory';
168
+
169
+ #port: MessagePort;
170
+ #frame: HTMLIFrameElement;
171
+ #permissions: PermissionHandler;
172
+ #nextId = 1;
173
+ #calls = new Map<number, { resolve(v: unknown): void; reject(e: Error): void }>();
174
+ #sinks = new Map<number, Sink>();
175
+ /** Events for processes whose spawn() has not returned yet. */
176
+ #early = new Map<number, ProcEvent[]>();
177
+ #closed: BoxError | null = null;
178
+
179
+ private constructor(port: MessagePort, frame: HTMLIFrameElement, hello: Hello, permissions: PermissionHandler) {
180
+ this.#port = port;
181
+ this.#frame = frame;
182
+ this.#permissions = permissions;
183
+ this.version = hello.version;
184
+ this.id = hello.id;
185
+ this.home = hello.home;
186
+ this.caps = hello.caps;
187
+ this.storage = hello.storage;
188
+ port.onmessage = (e: MessageEvent<FromRuntime>) => this.#onMessage(e.data);
189
+ }
190
+
191
+ /** Starts a box: loads the runtime in a hidden frame and connects to it. */
192
+ static boot(opts: BootOptions = {}): Promise<BrowserBox> {
193
+ const base = new URL(opts.runtimeUrl ?? DEFAULT_RUNTIME_URL, globalThis.location?.href);
194
+ if (!base.pathname.endsWith('/')) base.pathname += '/';
195
+ const memory = opts.storage === 'memory';
196
+ const id = opts.id ?? (memory ? `mem-${crypto.randomUUID()}` : 'default');
197
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) return Promise.reject(new BoxError(`invalid box id "${id}": use letters, digits, '-' and '_' (at most 64)`));
198
+ const src = new URL(`embed/?box=${encodeURIComponent(id)}&storage=${memory ? 'memory' : 'opfs'}`, base);
199
+ const permissions: PermissionHandler = typeof opts.permissions === 'function' ? opts.permissions : opts.permissions === 'allow' ? () => 'once' : () => 'deny';
200
+
201
+ const frame = document.createElement('iframe');
202
+ frame.src = src.href;
203
+ frame.title = 'BrowserBox runtime';
204
+ frame.setAttribute('aria-hidden', 'true');
205
+ frame.style.cssText = 'position:absolute;width:0;height:0;border:0;visibility:hidden';
206
+
207
+ return new Promise<BrowserBox>((resolve, reject) => {
208
+ const fail = (message: string) => {
209
+ cleanup();
210
+ frame.remove();
211
+ reject(new BoxError(message));
212
+ };
213
+ const timer = setTimeout(() => fail(`the runtime at ${src.href} did not respond within ${opts.timeoutMs ?? 30000} ms`), opts.timeoutMs ?? 30000);
214
+ const onWindowMessage = (e: MessageEvent) => {
215
+ if (e.source !== frame.contentWindow || e.origin !== src.origin || e.data?.type !== 'bbx:embed-ready') return;
216
+ const { port1, port2 } = new MessageChannel();
217
+ port1.onmessage = (m: MessageEvent<FromRuntime>) => {
218
+ const msg = m.data;
219
+ if (msg.t === 'refused') return fail(`the runtime refused to connect: ${msg.error}`);
220
+ if (msg.t !== 'hello') return;
221
+ cleanup();
222
+ resolve(new BrowserBox(port1, frame, msg, permissions));
223
+ };
224
+ frame.contentWindow!.postMessage({ type: 'bbx:connect', protocol: PROTOCOL_VERSION }, src.origin, [port2]);
225
+ };
226
+ const cleanup = () => {
227
+ clearTimeout(timer);
228
+ removeEventListener('message', onWindowMessage);
229
+ };
230
+ addEventListener('message', onWindowMessage);
231
+ (opts.container ?? document.body).append(frame);
232
+ });
233
+ }
234
+
235
+ /** Runs a shell command line to completion and returns its output. */
236
+ exec(command: string, opts?: ExecOptions): Promise<ExecResult> {
237
+ return this.call('exec', command, opts);
238
+ }
239
+
240
+ /** Starts a shell command line and streams its output. */
241
+ async spawn(command: string, opts?: ExecOptions): Promise<BoxProcess> {
242
+ const pid = await this.call('spawn', command, opts);
243
+ return new BoxProcess(pid, this, (sink) => {
244
+ this.#sinks.set(pid, sink);
245
+ for (const ev of this.#early.get(pid) ?? []) this.#deliver(pid, ev);
246
+ this.#early.delete(pid);
247
+ });
248
+ }
249
+
250
+ /** Shuts the box down: removes its frame and fails anything still pending. */
251
+ teardown(): void {
252
+ if (this.#closed) return;
253
+ this.#closed = new BoxError('the box was torn down');
254
+ for (const c of this.#calls.values()) c.reject(this.#closed);
255
+ this.#calls.clear();
256
+ for (const pid of [...this.#sinks.keys()]) this.#deliver(pid, { t: 'exit', exitCode: 130 });
257
+ this.#port.close();
258
+ this.#frame.remove();
259
+ }
260
+
261
+ /** @internal Low-level call into the runtime. */
262
+ call<M extends Method>(method: M, ...args: Parameters<Methods[M]>): Promise<ReturnType<Methods[M]>> {
263
+ if (this.#closed) return Promise.reject(this.#closed);
264
+ const id = this.#nextId++;
265
+ return new Promise((resolve, reject) => {
266
+ this.#calls.set(id, { resolve: resolve as (v: unknown) => void, reject });
267
+ this.#port.postMessage({ t: 'call', id, method, args } satisfies ToRuntime);
268
+ });
269
+ }
270
+
271
+ #onMessage(msg: FromRuntime): void {
272
+ switch (msg.t) {
273
+ case 'result': {
274
+ const c = this.#calls.get(msg.id);
275
+ this.#calls.delete(msg.id);
276
+ if (msg.ok) c?.resolve(msg.value);
277
+ else c?.reject(new BoxError(msg.error, msg.code));
278
+ return;
279
+ }
280
+ case 'output':
281
+ return this.#route(msg.pid, { t: 'output', stream: msg.stream, data: msg.data });
282
+ case 'exit':
283
+ return this.#route(msg.pid, { t: 'exit', exitCode: msg.exitCode });
284
+ case 'permission':
285
+ void Promise.resolve()
286
+ .then(() => this.#permissions(msg.request))
287
+ .catch((): PermissionDecision => 'deny')
288
+ .then((decision) => this.#port.postMessage({ t: 'permission-answer', id: msg.id, decision } satisfies ToRuntime));
289
+ return;
290
+ }
291
+ }
292
+
293
+ #route(pid: number, ev: ProcEvent): void {
294
+ if (this.#sinks.has(pid)) return this.#deliver(pid, ev);
295
+ const list = this.#early.get(pid) ?? [];
296
+ list.push(ev);
297
+ this.#early.set(pid, list);
298
+ }
299
+
300
+ #deliver(pid: number, ev: ProcEvent): void {
301
+ const sink = this.#sinks.get(pid);
302
+ if (!sink) return;
303
+ // A stream the reader cancelled throws on enqueue/close; that reader just stops getting data.
304
+ const each = (list: ReadableStreamDefaultController<string>[], fn: (c: ReadableStreamDefaultController<string>) => void) => {
305
+ for (const c of list) {
306
+ try {
307
+ fn(c);
308
+ } catch {
309
+ /* cancelled */
310
+ }
311
+ }
312
+ };
313
+ if (ev.t === 'output') return each([...sink.out, ...sink[ev.stream]], (c) => c.enqueue(ev.data));
314
+ each([...sink.out, ...sink.stdout, ...sink.stderr], (c) => c.close());
315
+ this.#sinks.delete(pid);
316
+ sink.exit(ev.exitCode);
317
+ }
318
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The wire protocol between the SDK (in the embedding page) and the runtime
3
+ * (a hidden iframe on the runtime's origin). Shared by both sides; bump
4
+ * PROTOCOL_VERSION on any incompatible change.
5
+ *
6
+ * Handshake, over window.postMessage:
7
+ * runtime → parent { type: 'bbx:embed-ready' }
8
+ * SDK → runtime { type: 'bbx:connect', protocol } + a MessagePort
9
+ * Everything after that goes over the port: calls and results, process
10
+ * output and exit, and permission questions.
11
+ */
12
+ export const PROTOCOL_VERSION = 1;
13
+
14
+ export interface Hello {
15
+ t: 'hello';
16
+ protocol: number;
17
+ /** Runtime version. */
18
+ version: string;
19
+ /** The box's id. */
20
+ id: string;
21
+ /** The default working directory for commands. */
22
+ home: string;
23
+ /** Platform features available in the runtime (e.g. 'opfs', 'webgpu'). */
24
+ caps: string[];
25
+ /** 'opfs' when files persist across reloads (per embedding site), 'memory' when not. */
26
+ storage: 'opfs' | 'memory';
27
+ }
28
+
29
+ export interface Refused {
30
+ t: 'refused';
31
+ error: string;
32
+ }
33
+
34
+ export interface FileStat {
35
+ path: string;
36
+ name: string;
37
+ kind: 'file' | 'dir';
38
+ size: number;
39
+ /** Last modified, ms since the epoch. */
40
+ mtime: number;
41
+ }
42
+
43
+ export interface ExecOptions {
44
+ /** Working directory. Default: the runtime's home. */
45
+ cwd?: string;
46
+ /** Extra environment variables for the command. */
47
+ env?: Record<string, string>;
48
+ /** Kill the command after this many ms (exit code 124). */
49
+ timeoutMs?: number;
50
+ }
51
+
52
+ export interface ExecResult {
53
+ exitCode: number;
54
+ stdout: string;
55
+ stderr: string;
56
+ }
57
+
58
+ export type PermissionDecision = 'once' | 'always' | 'deny';
59
+
60
+ export interface PermissionRequest {
61
+ /** What is asked for: 'fs.write', 'exec', 'net', 'clipboard', 'notify' or 'system'. */
62
+ cap: string;
63
+ /** Who is asking, e.g. a command. */
64
+ actor: string;
65
+ /** Short human title, e.g. "Network access". */
66
+ title: string;
67
+ /** The exact thing being approved (command, path, URL). */
68
+ detail: string;
69
+ }
70
+
71
+ /** Calls the SDK can make, with their arguments and results. */
72
+ export interface Methods {
73
+ info(): Hello;
74
+ 'fs.readFile'(path: string): Uint8Array;
75
+ 'fs.readTextFile'(path: string): string;
76
+ 'fs.writeFile'(path: string, data: string | Uint8Array): void;
77
+ 'fs.mkdir'(path: string): void;
78
+ 'fs.readdir'(path: string): FileStat[];
79
+ 'fs.stat'(path: string): FileStat | null;
80
+ 'fs.exists'(path: string): boolean;
81
+ 'fs.rm'(path: string, opts?: { recursive?: boolean }): void;
82
+ 'fs.rename'(from: string, to: string): void;
83
+ 'fs.cp'(from: string, to: string): void;
84
+ exec(command: string, opts?: ExecOptions): ExecResult;
85
+ /** Starts a command; its output and exit arrive as events. Returns its process id. */
86
+ spawn(command: string, opts?: ExecOptions): number;
87
+ kill(pid: number): boolean;
88
+ }
89
+
90
+ export type Method = keyof Methods;
91
+
92
+ /** SDK → runtime. */
93
+ export type ToRuntime =
94
+ | { t: 'call'; id: number; method: Method; args: unknown[] }
95
+ | { t: 'permission-answer'; id: number; decision: PermissionDecision };
96
+
97
+ /** Runtime → SDK. */
98
+ export type FromRuntime =
99
+ | Hello
100
+ | Refused
101
+ | { t: 'result'; id: number; ok: true; value: unknown }
102
+ | { t: 'result'; id: number; ok: false; error: string; code?: string }
103
+ | { t: 'output'; pid: number; stream: 'stdout' | 'stderr'; data: string }
104
+ | { t: 'exit'; pid: number; exitCode: number }
105
+ | { t: 'permission'; id: number; request: PermissionRequest };