@jeevanand/agent-browserbox-sdk 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/dist/index.d.ts +110 -0
- package/dist/index.js +261 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.d.ts +120 -0
- package/dist/protocol.js +13 -0
- package/dist/protocol.js.map +1 -0
- package/package.json +54 -4
- package/src/index.ts +311 -0
- package/src/protocol.ts +105 -0
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
|
-
#
|
|
1
|
+
# @jeevanand/agent-browserbox-sdk
|
|
2
2
|
|
|
3
|
-
|
|
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
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
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
|
+
/** Where the hosted runtime lives. Self-host it with @jeevanand/agent-browserbox-runtime. */
|
|
5
|
+
export declare const DEFAULT_RUNTIME_URL = "https://jeevanandmaurya.github.io/agent-browserbox/runtime/";
|
|
6
|
+
export type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
|
|
7
|
+
export interface BootOptions {
|
|
8
|
+
/** Base URL of the runtime (the folder holding embed/, kernel/, assets/). Default: the hosted runtime. */
|
|
9
|
+
runtimeUrl?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Which box. Each id is a separate machine with its own files, settings and
|
|
12
|
+
* processes; booting the same id again (e.g. after a reload) reattaches to
|
|
13
|
+
* its files. Letters, digits, '-' and '_'. Default: 'default', or a fresh id
|
|
14
|
+
* for an in-memory box.
|
|
15
|
+
*/
|
|
16
|
+
id?: string;
|
|
17
|
+
/** 'persistent' (default): files survive reloads. 'memory': everything is gone when the box is torn down. */
|
|
18
|
+
storage?: 'persistent' | 'memory';
|
|
19
|
+
/** Element the hidden runtime frame is added to. Default: document.body. */
|
|
20
|
+
container?: HTMLElement;
|
|
21
|
+
/**
|
|
22
|
+
* What to answer when code in the box asks for a capability (network access,
|
|
23
|
+
* …). 'deny' (default), 'allow', or a function deciding per request.
|
|
24
|
+
*/
|
|
25
|
+
permissions?: 'deny' | 'allow' | PermissionHandler;
|
|
26
|
+
/** Give up booting after this many ms. Default 30000. */
|
|
27
|
+
timeoutMs?: number;
|
|
28
|
+
}
|
|
29
|
+
/** An error from the box. `code` is set for filesystem errors (ENOENT, EEXIST, …). */
|
|
30
|
+
export declare class BoxError extends Error {
|
|
31
|
+
readonly code?: string | undefined;
|
|
32
|
+
constructor(message: string, code?: string | undefined);
|
|
33
|
+
}
|
|
34
|
+
interface Sink {
|
|
35
|
+
out: ReadableStreamDefaultController<string>[];
|
|
36
|
+
stdout: ReadableStreamDefaultController<string>[];
|
|
37
|
+
stderr: ReadableStreamDefaultController<string>[];
|
|
38
|
+
exit(code: number): void;
|
|
39
|
+
}
|
|
40
|
+
/** A running command in the box. */
|
|
41
|
+
export declare class BoxProcess {
|
|
42
|
+
readonly pid: number;
|
|
43
|
+
private box;
|
|
44
|
+
/** stdout and stderr together, in the order they were written. */
|
|
45
|
+
readonly output: ReadableStream<string>;
|
|
46
|
+
readonly stdout: ReadableStream<string>;
|
|
47
|
+
readonly stderr: ReadableStream<string>;
|
|
48
|
+
/** Resolves with the exit code (124: timed out, 130: killed). */
|
|
49
|
+
readonly exit: Promise<number>;
|
|
50
|
+
/** @internal */
|
|
51
|
+
constructor(pid: number, box: BrowserBox, attach: (sink: Sink) => void);
|
|
52
|
+
/** Stops the command. Resolves false if it had already finished. */
|
|
53
|
+
kill(): Promise<boolean>;
|
|
54
|
+
}
|
|
55
|
+
/** The box's filesystem. Paths are absolute, or relative to the box's home. */
|
|
56
|
+
export declare class BoxFs {
|
|
57
|
+
#private;
|
|
58
|
+
private box;
|
|
59
|
+
/** @internal */
|
|
60
|
+
constructor(box: BrowserBox);
|
|
61
|
+
readFile(path: string): Promise<Uint8Array>;
|
|
62
|
+
readTextFile(path: string): Promise<string>;
|
|
63
|
+
/** Creates parent folders as needed. */
|
|
64
|
+
writeFile(path: string, data: string | Uint8Array): Promise<void>;
|
|
65
|
+
/** Creates parent folders as needed. */
|
|
66
|
+
mkdir(path: string): Promise<void>;
|
|
67
|
+
readdir(path?: string): Promise<FileStat[]>;
|
|
68
|
+
/** Null when nothing is there. */
|
|
69
|
+
stat(path: string): Promise<FileStat | null>;
|
|
70
|
+
exists(path: string): Promise<boolean>;
|
|
71
|
+
rm(path: string, opts?: {
|
|
72
|
+
recursive?: boolean;
|
|
73
|
+
}): Promise<void>;
|
|
74
|
+
rename(from: string, to: string): Promise<void>;
|
|
75
|
+
cp(from: string, to: string): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A sandboxed computer in the browser: a filesystem, a shell, and JavaScript,
|
|
79
|
+
* Python and WebAssembly runtimes, all inside a hidden frame on the runtime's
|
|
80
|
+
* origin. Nothing in it can reach the embedding page.
|
|
81
|
+
*
|
|
82
|
+
* const box = await BrowserBox.boot();
|
|
83
|
+
* await box.fs.writeFile('hello.py', 'print(6 * 7)');
|
|
84
|
+
* const { stdout } = await box.exec('python hello.py');
|
|
85
|
+
*/
|
|
86
|
+
export declare class BrowserBox {
|
|
87
|
+
#private;
|
|
88
|
+
readonly fs: BoxFs;
|
|
89
|
+
/** Runtime version. */
|
|
90
|
+
readonly version: string;
|
|
91
|
+
/** This box's id. */
|
|
92
|
+
readonly id: string;
|
|
93
|
+
/** Default working directory; relative paths resolve against it. */
|
|
94
|
+
readonly home: string;
|
|
95
|
+
/** Platform features the runtime has (e.g. 'opfs', 'webgpu'). */
|
|
96
|
+
readonly caps: readonly string[];
|
|
97
|
+
/** 'opfs': files persist across reloads (separately for each embedding site). 'memory': they do not. */
|
|
98
|
+
readonly storage: 'opfs' | 'memory';
|
|
99
|
+
private constructor();
|
|
100
|
+
/** Starts a box: loads the runtime in a hidden frame and connects to it. */
|
|
101
|
+
static boot(opts?: BootOptions): Promise<BrowserBox>;
|
|
102
|
+
/** Runs a shell command line to completion and returns its output. */
|
|
103
|
+
exec(command: string, opts?: ExecOptions): Promise<ExecResult>;
|
|
104
|
+
/** Starts a shell command line and streams its output. */
|
|
105
|
+
spawn(command: string, opts?: ExecOptions): Promise<BoxProcess>;
|
|
106
|
+
/** Shuts the box down: removes its frame and fails anything still pending. */
|
|
107
|
+
teardown(): void;
|
|
108
|
+
/** @internal Low-level call into the runtime. */
|
|
109
|
+
call<M extends Method>(method: M, ...args: Parameters<Methods[M]>): Promise<ReturnType<Methods[M]>>;
|
|
110
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { PROTOCOL_VERSION, } from './protocol.js';
|
|
2
|
+
export { PROTOCOL_VERSION };
|
|
3
|
+
/** Where the hosted runtime lives. Self-host it with @jeevanand/agent-browserbox-runtime. */
|
|
4
|
+
export const DEFAULT_RUNTIME_URL = 'https://jeevanandmaurya.github.io/agent-browserbox/runtime/';
|
|
5
|
+
/** An error from the box. `code` is set for filesystem errors (ENOENT, EEXIST, …). */
|
|
6
|
+
export class BoxError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(message, code) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.name = 'BoxError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** A running command in the box. */
|
|
15
|
+
export class BoxProcess {
|
|
16
|
+
pid;
|
|
17
|
+
box;
|
|
18
|
+
/** stdout and stderr together, in the order they were written. */
|
|
19
|
+
output;
|
|
20
|
+
stdout;
|
|
21
|
+
stderr;
|
|
22
|
+
/** Resolves with the exit code (124: timed out, 130: killed). */
|
|
23
|
+
exit;
|
|
24
|
+
/** @internal */
|
|
25
|
+
constructor(pid, box, attach) {
|
|
26
|
+
this.pid = pid;
|
|
27
|
+
this.box = box;
|
|
28
|
+
const sink = { out: [], stdout: [], stderr: [], exit: () => undefined };
|
|
29
|
+
const stream = (list) => new ReadableStream({ start: (c) => void list.push(c) });
|
|
30
|
+
this.output = stream(sink.out);
|
|
31
|
+
this.stdout = stream(sink.stdout);
|
|
32
|
+
this.stderr = stream(sink.stderr);
|
|
33
|
+
this.exit = new Promise((resolve) => (sink.exit = resolve));
|
|
34
|
+
attach(sink);
|
|
35
|
+
}
|
|
36
|
+
/** Stops the command. Resolves false if it had already finished. */
|
|
37
|
+
kill() {
|
|
38
|
+
return this.box.call('kill', this.pid);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** The box's filesystem. Paths are absolute, or relative to the box's home. */
|
|
42
|
+
export class BoxFs {
|
|
43
|
+
box;
|
|
44
|
+
/** @internal */
|
|
45
|
+
constructor(box) {
|
|
46
|
+
this.box = box;
|
|
47
|
+
}
|
|
48
|
+
#abs(path) {
|
|
49
|
+
return path.startsWith('/') ? path : `${this.box.home.replace(/\/$/, '')}/${path}`;
|
|
50
|
+
}
|
|
51
|
+
readFile(path) {
|
|
52
|
+
return this.box.call('fs.readFile', this.#abs(path));
|
|
53
|
+
}
|
|
54
|
+
readTextFile(path) {
|
|
55
|
+
return this.box.call('fs.readTextFile', this.#abs(path));
|
|
56
|
+
}
|
|
57
|
+
/** Creates parent folders as needed. */
|
|
58
|
+
writeFile(path, data) {
|
|
59
|
+
return this.box.call('fs.writeFile', this.#abs(path), data);
|
|
60
|
+
}
|
|
61
|
+
/** Creates parent folders as needed. */
|
|
62
|
+
mkdir(path) {
|
|
63
|
+
return this.box.call('fs.mkdir', this.#abs(path));
|
|
64
|
+
}
|
|
65
|
+
readdir(path = '.') {
|
|
66
|
+
return this.box.call('fs.readdir', this.#abs(path));
|
|
67
|
+
}
|
|
68
|
+
/** Null when nothing is there. */
|
|
69
|
+
stat(path) {
|
|
70
|
+
return this.box.call('fs.stat', this.#abs(path));
|
|
71
|
+
}
|
|
72
|
+
exists(path) {
|
|
73
|
+
return this.box.call('fs.exists', this.#abs(path));
|
|
74
|
+
}
|
|
75
|
+
rm(path, opts) {
|
|
76
|
+
return this.box.call('fs.rm', this.#abs(path), opts);
|
|
77
|
+
}
|
|
78
|
+
rename(from, to) {
|
|
79
|
+
return this.box.call('fs.rename', this.#abs(from), this.#abs(to));
|
|
80
|
+
}
|
|
81
|
+
cp(from, to) {
|
|
82
|
+
return this.box.call('fs.cp', this.#abs(from), this.#abs(to));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A sandboxed computer in the browser: a filesystem, a shell, and JavaScript,
|
|
87
|
+
* Python and WebAssembly runtimes, all inside a hidden frame on the runtime's
|
|
88
|
+
* origin. Nothing in it can reach the embedding page.
|
|
89
|
+
*
|
|
90
|
+
* const box = await BrowserBox.boot();
|
|
91
|
+
* await box.fs.writeFile('hello.py', 'print(6 * 7)');
|
|
92
|
+
* const { stdout } = await box.exec('python hello.py');
|
|
93
|
+
*/
|
|
94
|
+
export class BrowserBox {
|
|
95
|
+
fs = new BoxFs(this);
|
|
96
|
+
/** Runtime version. */
|
|
97
|
+
version;
|
|
98
|
+
/** This box's id. */
|
|
99
|
+
id;
|
|
100
|
+
/** Default working directory; relative paths resolve against it. */
|
|
101
|
+
home;
|
|
102
|
+
/** Platform features the runtime has (e.g. 'opfs', 'webgpu'). */
|
|
103
|
+
caps;
|
|
104
|
+
/** 'opfs': files persist across reloads (separately for each embedding site). 'memory': they do not. */
|
|
105
|
+
storage;
|
|
106
|
+
#port;
|
|
107
|
+
#frame;
|
|
108
|
+
#permissions;
|
|
109
|
+
#nextId = 1;
|
|
110
|
+
#calls = new Map();
|
|
111
|
+
#sinks = new Map();
|
|
112
|
+
/** Events for processes whose spawn() has not returned yet. */
|
|
113
|
+
#early = new Map();
|
|
114
|
+
#closed = null;
|
|
115
|
+
constructor(port, frame, hello, permissions) {
|
|
116
|
+
this.#port = port;
|
|
117
|
+
this.#frame = frame;
|
|
118
|
+
this.#permissions = permissions;
|
|
119
|
+
this.version = hello.version;
|
|
120
|
+
this.id = hello.id;
|
|
121
|
+
this.home = hello.home;
|
|
122
|
+
this.caps = hello.caps;
|
|
123
|
+
this.storage = hello.storage;
|
|
124
|
+
port.onmessage = (e) => this.#onMessage(e.data);
|
|
125
|
+
}
|
|
126
|
+
/** Starts a box: loads the runtime in a hidden frame and connects to it. */
|
|
127
|
+
static boot(opts = {}) {
|
|
128
|
+
const base = new URL(opts.runtimeUrl ?? DEFAULT_RUNTIME_URL, globalThis.location?.href);
|
|
129
|
+
if (!base.pathname.endsWith('/'))
|
|
130
|
+
base.pathname += '/';
|
|
131
|
+
const memory = opts.storage === 'memory';
|
|
132
|
+
const id = opts.id ?? (memory ? `mem-${crypto.randomUUID()}` : 'default');
|
|
133
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(id))
|
|
134
|
+
return Promise.reject(new BoxError(`invalid box id "${id}": use letters, digits, '-' and '_' (at most 64)`));
|
|
135
|
+
const src = new URL(`embed/?box=${encodeURIComponent(id)}&storage=${memory ? 'memory' : 'opfs'}`, base);
|
|
136
|
+
const permissions = typeof opts.permissions === 'function' ? opts.permissions : opts.permissions === 'allow' ? () => 'once' : () => 'deny';
|
|
137
|
+
const frame = document.createElement('iframe');
|
|
138
|
+
frame.src = src.href;
|
|
139
|
+
frame.title = 'BrowserBox runtime';
|
|
140
|
+
frame.setAttribute('aria-hidden', 'true');
|
|
141
|
+
frame.style.cssText = 'position:absolute;width:0;height:0;border:0;visibility:hidden';
|
|
142
|
+
return new Promise((resolve, reject) => {
|
|
143
|
+
const fail = (message) => {
|
|
144
|
+
cleanup();
|
|
145
|
+
frame.remove();
|
|
146
|
+
reject(new BoxError(message));
|
|
147
|
+
};
|
|
148
|
+
const timer = setTimeout(() => fail(`the runtime at ${src.href} did not respond within ${opts.timeoutMs ?? 30000} ms`), opts.timeoutMs ?? 30000);
|
|
149
|
+
const onWindowMessage = (e) => {
|
|
150
|
+
if (e.source !== frame.contentWindow || e.origin !== src.origin || e.data?.type !== 'bbx:embed-ready')
|
|
151
|
+
return;
|
|
152
|
+
const { port1, port2 } = new MessageChannel();
|
|
153
|
+
port1.onmessage = (m) => {
|
|
154
|
+
const msg = m.data;
|
|
155
|
+
if (msg.t === 'refused')
|
|
156
|
+
return fail(`the runtime refused to connect: ${msg.error}`);
|
|
157
|
+
if (msg.t !== 'hello')
|
|
158
|
+
return;
|
|
159
|
+
cleanup();
|
|
160
|
+
resolve(new BrowserBox(port1, frame, msg, permissions));
|
|
161
|
+
};
|
|
162
|
+
frame.contentWindow.postMessage({ type: 'bbx:connect', protocol: PROTOCOL_VERSION }, src.origin, [port2]);
|
|
163
|
+
};
|
|
164
|
+
const cleanup = () => {
|
|
165
|
+
clearTimeout(timer);
|
|
166
|
+
removeEventListener('message', onWindowMessage);
|
|
167
|
+
};
|
|
168
|
+
addEventListener('message', onWindowMessage);
|
|
169
|
+
(opts.container ?? document.body).append(frame);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/** Runs a shell command line to completion and returns its output. */
|
|
173
|
+
exec(command, opts) {
|
|
174
|
+
return this.call('exec', command, opts);
|
|
175
|
+
}
|
|
176
|
+
/** Starts a shell command line and streams its output. */
|
|
177
|
+
async spawn(command, opts) {
|
|
178
|
+
const pid = await this.call('spawn', command, opts);
|
|
179
|
+
return new BoxProcess(pid, this, (sink) => {
|
|
180
|
+
this.#sinks.set(pid, sink);
|
|
181
|
+
for (const ev of this.#early.get(pid) ?? [])
|
|
182
|
+
this.#deliver(pid, ev);
|
|
183
|
+
this.#early.delete(pid);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** Shuts the box down: removes its frame and fails anything still pending. */
|
|
187
|
+
teardown() {
|
|
188
|
+
if (this.#closed)
|
|
189
|
+
return;
|
|
190
|
+
this.#closed = new BoxError('the box was torn down');
|
|
191
|
+
for (const c of this.#calls.values())
|
|
192
|
+
c.reject(this.#closed);
|
|
193
|
+
this.#calls.clear();
|
|
194
|
+
for (const pid of [...this.#sinks.keys()])
|
|
195
|
+
this.#deliver(pid, { t: 'exit', exitCode: 130 });
|
|
196
|
+
this.#port.close();
|
|
197
|
+
this.#frame.remove();
|
|
198
|
+
}
|
|
199
|
+
/** @internal Low-level call into the runtime. */
|
|
200
|
+
call(method, ...args) {
|
|
201
|
+
if (this.#closed)
|
|
202
|
+
return Promise.reject(this.#closed);
|
|
203
|
+
const id = this.#nextId++;
|
|
204
|
+
return new Promise((resolve, reject) => {
|
|
205
|
+
this.#calls.set(id, { resolve: resolve, reject });
|
|
206
|
+
this.#port.postMessage({ t: 'call', id, method, args });
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
#onMessage(msg) {
|
|
210
|
+
switch (msg.t) {
|
|
211
|
+
case 'result': {
|
|
212
|
+
const c = this.#calls.get(msg.id);
|
|
213
|
+
this.#calls.delete(msg.id);
|
|
214
|
+
if (msg.ok)
|
|
215
|
+
c?.resolve(msg.value);
|
|
216
|
+
else
|
|
217
|
+
c?.reject(new BoxError(msg.error, msg.code));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
case 'output':
|
|
221
|
+
return this.#route(msg.pid, { t: 'output', stream: msg.stream, data: msg.data });
|
|
222
|
+
case 'exit':
|
|
223
|
+
return this.#route(msg.pid, { t: 'exit', exitCode: msg.exitCode });
|
|
224
|
+
case 'permission':
|
|
225
|
+
void Promise.resolve()
|
|
226
|
+
.then(() => this.#permissions(msg.request))
|
|
227
|
+
.catch(() => 'deny')
|
|
228
|
+
.then((decision) => this.#port.postMessage({ t: 'permission-answer', id: msg.id, decision }));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
#route(pid, ev) {
|
|
233
|
+
if (this.#sinks.has(pid))
|
|
234
|
+
return this.#deliver(pid, ev);
|
|
235
|
+
const list = this.#early.get(pid) ?? [];
|
|
236
|
+
list.push(ev);
|
|
237
|
+
this.#early.set(pid, list);
|
|
238
|
+
}
|
|
239
|
+
#deliver(pid, ev) {
|
|
240
|
+
const sink = this.#sinks.get(pid);
|
|
241
|
+
if (!sink)
|
|
242
|
+
return;
|
|
243
|
+
// A stream the reader cancelled throws on enqueue/close; that reader just stops getting data.
|
|
244
|
+
const each = (list, fn) => {
|
|
245
|
+
for (const c of list) {
|
|
246
|
+
try {
|
|
247
|
+
fn(c);
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
/* cancelled */
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
if (ev.t === 'output')
|
|
255
|
+
return each([...sink.out, ...sink[ev.stream]], (c) => c.enqueue(ev.data));
|
|
256
|
+
each([...sink.out, ...sink.stdout, ...sink.stderr], (c) => c.close());
|
|
257
|
+
this.#sinks.delete(pid);
|
|
258
|
+
sink.exit(ev.exitCode);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
//# 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,6FAA6F;AAC7F,MAAM,CAAC,MAAM,mBAAmB,GAAG,6DAA6D,CAAC;AA2BjG,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,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,SAAS,EAAE,CAAC;QAC9E,MAAM,MAAM,GAAG,CAAC,IAA+C,EAAE,EAAE,CAAC,IAAI,cAAc,CAAS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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
|
+
};
|
package/dist/protocol.js
ADDED
|
@@ -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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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,311 @@
|
|
|
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
|
+
/** Where the hosted runtime lives. Self-host it with @jeevanand/agent-browserbox-runtime. */
|
|
19
|
+
export const DEFAULT_RUNTIME_URL = 'https://jeevanandmaurya.github.io/agent-browserbox/runtime/';
|
|
20
|
+
|
|
21
|
+
export type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
|
|
22
|
+
|
|
23
|
+
export interface BootOptions {
|
|
24
|
+
/** Base URL of the runtime (the folder holding embed/, kernel/, assets/). Default: the hosted runtime. */
|
|
25
|
+
runtimeUrl?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Which box. Each id is a separate machine with its own files, settings and
|
|
28
|
+
* processes; booting the same id again (e.g. after a reload) reattaches to
|
|
29
|
+
* its files. Letters, digits, '-' and '_'. Default: 'default', or a fresh id
|
|
30
|
+
* for an in-memory box.
|
|
31
|
+
*/
|
|
32
|
+
id?: string;
|
|
33
|
+
/** 'persistent' (default): files survive reloads. 'memory': everything is gone when the box is torn down. */
|
|
34
|
+
storage?: 'persistent' | 'memory';
|
|
35
|
+
/** Element the hidden runtime frame is added to. Default: document.body. */
|
|
36
|
+
container?: HTMLElement;
|
|
37
|
+
/**
|
|
38
|
+
* What to answer when code in the box asks for a capability (network access,
|
|
39
|
+
* …). 'deny' (default), 'allow', or a function deciding per request.
|
|
40
|
+
*/
|
|
41
|
+
permissions?: 'deny' | 'allow' | PermissionHandler;
|
|
42
|
+
/** Give up booting after this many ms. Default 30000. */
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** An error from the box. `code` is set for filesystem errors (ENOENT, EEXIST, …). */
|
|
47
|
+
export class BoxError extends Error {
|
|
48
|
+
constructor(
|
|
49
|
+
message: string,
|
|
50
|
+
readonly code?: string,
|
|
51
|
+
) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = 'BoxError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface Sink {
|
|
58
|
+
out: ReadableStreamDefaultController<string>[];
|
|
59
|
+
stdout: ReadableStreamDefaultController<string>[];
|
|
60
|
+
stderr: ReadableStreamDefaultController<string>[];
|
|
61
|
+
exit(code: number): void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type ProcEvent = { t: 'output'; stream: 'stdout' | 'stderr'; data: string } | { t: 'exit'; exitCode: number };
|
|
65
|
+
|
|
66
|
+
/** A running command in the box. */
|
|
67
|
+
export class BoxProcess {
|
|
68
|
+
/** stdout and stderr together, in the order they were written. */
|
|
69
|
+
readonly output: ReadableStream<string>;
|
|
70
|
+
readonly stdout: ReadableStream<string>;
|
|
71
|
+
readonly stderr: ReadableStream<string>;
|
|
72
|
+
/** Resolves with the exit code (124: timed out, 130: killed). */
|
|
73
|
+
readonly exit: Promise<number>;
|
|
74
|
+
|
|
75
|
+
/** @internal */
|
|
76
|
+
constructor(
|
|
77
|
+
readonly pid: number,
|
|
78
|
+
private box: BrowserBox,
|
|
79
|
+
attach: (sink: Sink) => void,
|
|
80
|
+
) {
|
|
81
|
+
const sink: Sink = { out: [], stdout: [], stderr: [], exit: () => undefined };
|
|
82
|
+
const stream = (list: ReadableStreamDefaultController<string>[]) => new ReadableStream<string>({ start: (c) => void list.push(c) });
|
|
83
|
+
this.output = stream(sink.out);
|
|
84
|
+
this.stdout = stream(sink.stdout);
|
|
85
|
+
this.stderr = stream(sink.stderr);
|
|
86
|
+
this.exit = new Promise((resolve) => (sink.exit = resolve));
|
|
87
|
+
attach(sink);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Stops the command. Resolves false if it had already finished. */
|
|
91
|
+
kill(): Promise<boolean> {
|
|
92
|
+
return this.box.call('kill', this.pid);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The box's filesystem. Paths are absolute, or relative to the box's home. */
|
|
97
|
+
export class BoxFs {
|
|
98
|
+
/** @internal */
|
|
99
|
+
constructor(private box: BrowserBox) {}
|
|
100
|
+
|
|
101
|
+
#abs(path: string): string {
|
|
102
|
+
return path.startsWith('/') ? path : `${this.box.home.replace(/\/$/, '')}/${path}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
readFile(path: string): Promise<Uint8Array> {
|
|
106
|
+
return this.box.call('fs.readFile', this.#abs(path));
|
|
107
|
+
}
|
|
108
|
+
readTextFile(path: string): Promise<string> {
|
|
109
|
+
return this.box.call('fs.readTextFile', this.#abs(path));
|
|
110
|
+
}
|
|
111
|
+
/** Creates parent folders as needed. */
|
|
112
|
+
writeFile(path: string, data: string | Uint8Array): Promise<void> {
|
|
113
|
+
return this.box.call('fs.writeFile', this.#abs(path), data);
|
|
114
|
+
}
|
|
115
|
+
/** Creates parent folders as needed. */
|
|
116
|
+
mkdir(path: string): Promise<void> {
|
|
117
|
+
return this.box.call('fs.mkdir', this.#abs(path));
|
|
118
|
+
}
|
|
119
|
+
readdir(path = '.'): Promise<FileStat[]> {
|
|
120
|
+
return this.box.call('fs.readdir', this.#abs(path));
|
|
121
|
+
}
|
|
122
|
+
/** Null when nothing is there. */
|
|
123
|
+
stat(path: string): Promise<FileStat | null> {
|
|
124
|
+
return this.box.call('fs.stat', this.#abs(path));
|
|
125
|
+
}
|
|
126
|
+
exists(path: string): Promise<boolean> {
|
|
127
|
+
return this.box.call('fs.exists', this.#abs(path));
|
|
128
|
+
}
|
|
129
|
+
rm(path: string, opts?: { recursive?: boolean }): Promise<void> {
|
|
130
|
+
return this.box.call('fs.rm', this.#abs(path), opts);
|
|
131
|
+
}
|
|
132
|
+
rename(from: string, to: string): Promise<void> {
|
|
133
|
+
return this.box.call('fs.rename', this.#abs(from), this.#abs(to));
|
|
134
|
+
}
|
|
135
|
+
cp(from: string, to: string): Promise<void> {
|
|
136
|
+
return this.box.call('fs.cp', this.#abs(from), this.#abs(to));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* A sandboxed computer in the browser: a filesystem, a shell, and JavaScript,
|
|
142
|
+
* Python and WebAssembly runtimes, all inside a hidden frame on the runtime's
|
|
143
|
+
* origin. Nothing in it can reach the embedding page.
|
|
144
|
+
*
|
|
145
|
+
* const box = await BrowserBox.boot();
|
|
146
|
+
* await box.fs.writeFile('hello.py', 'print(6 * 7)');
|
|
147
|
+
* const { stdout } = await box.exec('python hello.py');
|
|
148
|
+
*/
|
|
149
|
+
export class BrowserBox {
|
|
150
|
+
readonly fs = new BoxFs(this);
|
|
151
|
+
/** Runtime version. */
|
|
152
|
+
readonly version: string;
|
|
153
|
+
/** This box's id. */
|
|
154
|
+
readonly id: string;
|
|
155
|
+
/** Default working directory; relative paths resolve against it. */
|
|
156
|
+
readonly home: string;
|
|
157
|
+
/** Platform features the runtime has (e.g. 'opfs', 'webgpu'). */
|
|
158
|
+
readonly caps: readonly string[];
|
|
159
|
+
/** 'opfs': files persist across reloads (separately for each embedding site). 'memory': they do not. */
|
|
160
|
+
readonly storage: 'opfs' | 'memory';
|
|
161
|
+
|
|
162
|
+
#port: MessagePort;
|
|
163
|
+
#frame: HTMLIFrameElement;
|
|
164
|
+
#permissions: PermissionHandler;
|
|
165
|
+
#nextId = 1;
|
|
166
|
+
#calls = new Map<number, { resolve(v: unknown): void; reject(e: Error): void }>();
|
|
167
|
+
#sinks = new Map<number, Sink>();
|
|
168
|
+
/** Events for processes whose spawn() has not returned yet. */
|
|
169
|
+
#early = new Map<number, ProcEvent[]>();
|
|
170
|
+
#closed: BoxError | null = null;
|
|
171
|
+
|
|
172
|
+
private constructor(port: MessagePort, frame: HTMLIFrameElement, hello: Hello, permissions: PermissionHandler) {
|
|
173
|
+
this.#port = port;
|
|
174
|
+
this.#frame = frame;
|
|
175
|
+
this.#permissions = permissions;
|
|
176
|
+
this.version = hello.version;
|
|
177
|
+
this.id = hello.id;
|
|
178
|
+
this.home = hello.home;
|
|
179
|
+
this.caps = hello.caps;
|
|
180
|
+
this.storage = hello.storage;
|
|
181
|
+
port.onmessage = (e: MessageEvent<FromRuntime>) => this.#onMessage(e.data);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Starts a box: loads the runtime in a hidden frame and connects to it. */
|
|
185
|
+
static boot(opts: BootOptions = {}): Promise<BrowserBox> {
|
|
186
|
+
const base = new URL(opts.runtimeUrl ?? DEFAULT_RUNTIME_URL, globalThis.location?.href);
|
|
187
|
+
if (!base.pathname.endsWith('/')) base.pathname += '/';
|
|
188
|
+
const memory = opts.storage === 'memory';
|
|
189
|
+
const id = opts.id ?? (memory ? `mem-${crypto.randomUUID()}` : 'default');
|
|
190
|
+
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)`));
|
|
191
|
+
const src = new URL(`embed/?box=${encodeURIComponent(id)}&storage=${memory ? 'memory' : 'opfs'}`, base);
|
|
192
|
+
const permissions: PermissionHandler = typeof opts.permissions === 'function' ? opts.permissions : opts.permissions === 'allow' ? () => 'once' : () => 'deny';
|
|
193
|
+
|
|
194
|
+
const frame = document.createElement('iframe');
|
|
195
|
+
frame.src = src.href;
|
|
196
|
+
frame.title = 'BrowserBox runtime';
|
|
197
|
+
frame.setAttribute('aria-hidden', 'true');
|
|
198
|
+
frame.style.cssText = 'position:absolute;width:0;height:0;border:0;visibility:hidden';
|
|
199
|
+
|
|
200
|
+
return new Promise<BrowserBox>((resolve, reject) => {
|
|
201
|
+
const fail = (message: string) => {
|
|
202
|
+
cleanup();
|
|
203
|
+
frame.remove();
|
|
204
|
+
reject(new BoxError(message));
|
|
205
|
+
};
|
|
206
|
+
const timer = setTimeout(() => fail(`the runtime at ${src.href} did not respond within ${opts.timeoutMs ?? 30000} ms`), opts.timeoutMs ?? 30000);
|
|
207
|
+
const onWindowMessage = (e: MessageEvent) => {
|
|
208
|
+
if (e.source !== frame.contentWindow || e.origin !== src.origin || e.data?.type !== 'bbx:embed-ready') return;
|
|
209
|
+
const { port1, port2 } = new MessageChannel();
|
|
210
|
+
port1.onmessage = (m: MessageEvent<FromRuntime>) => {
|
|
211
|
+
const msg = m.data;
|
|
212
|
+
if (msg.t === 'refused') return fail(`the runtime refused to connect: ${msg.error}`);
|
|
213
|
+
if (msg.t !== 'hello') return;
|
|
214
|
+
cleanup();
|
|
215
|
+
resolve(new BrowserBox(port1, frame, msg, permissions));
|
|
216
|
+
};
|
|
217
|
+
frame.contentWindow!.postMessage({ type: 'bbx:connect', protocol: PROTOCOL_VERSION }, src.origin, [port2]);
|
|
218
|
+
};
|
|
219
|
+
const cleanup = () => {
|
|
220
|
+
clearTimeout(timer);
|
|
221
|
+
removeEventListener('message', onWindowMessage);
|
|
222
|
+
};
|
|
223
|
+
addEventListener('message', onWindowMessage);
|
|
224
|
+
(opts.container ?? document.body).append(frame);
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Runs a shell command line to completion and returns its output. */
|
|
229
|
+
exec(command: string, opts?: ExecOptions): Promise<ExecResult> {
|
|
230
|
+
return this.call('exec', command, opts);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Starts a shell command line and streams its output. */
|
|
234
|
+
async spawn(command: string, opts?: ExecOptions): Promise<BoxProcess> {
|
|
235
|
+
const pid = await this.call('spawn', command, opts);
|
|
236
|
+
return new BoxProcess(pid, this, (sink) => {
|
|
237
|
+
this.#sinks.set(pid, sink);
|
|
238
|
+
for (const ev of this.#early.get(pid) ?? []) this.#deliver(pid, ev);
|
|
239
|
+
this.#early.delete(pid);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Shuts the box down: removes its frame and fails anything still pending. */
|
|
244
|
+
teardown(): void {
|
|
245
|
+
if (this.#closed) return;
|
|
246
|
+
this.#closed = new BoxError('the box was torn down');
|
|
247
|
+
for (const c of this.#calls.values()) c.reject(this.#closed);
|
|
248
|
+
this.#calls.clear();
|
|
249
|
+
for (const pid of [...this.#sinks.keys()]) this.#deliver(pid, { t: 'exit', exitCode: 130 });
|
|
250
|
+
this.#port.close();
|
|
251
|
+
this.#frame.remove();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** @internal Low-level call into the runtime. */
|
|
255
|
+
call<M extends Method>(method: M, ...args: Parameters<Methods[M]>): Promise<ReturnType<Methods[M]>> {
|
|
256
|
+
if (this.#closed) return Promise.reject(this.#closed);
|
|
257
|
+
const id = this.#nextId++;
|
|
258
|
+
return new Promise((resolve, reject) => {
|
|
259
|
+
this.#calls.set(id, { resolve: resolve as (v: unknown) => void, reject });
|
|
260
|
+
this.#port.postMessage({ t: 'call', id, method, args } satisfies ToRuntime);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
#onMessage(msg: FromRuntime): void {
|
|
265
|
+
switch (msg.t) {
|
|
266
|
+
case 'result': {
|
|
267
|
+
const c = this.#calls.get(msg.id);
|
|
268
|
+
this.#calls.delete(msg.id);
|
|
269
|
+
if (msg.ok) c?.resolve(msg.value);
|
|
270
|
+
else c?.reject(new BoxError(msg.error, msg.code));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
case 'output':
|
|
274
|
+
return this.#route(msg.pid, { t: 'output', stream: msg.stream, data: msg.data });
|
|
275
|
+
case 'exit':
|
|
276
|
+
return this.#route(msg.pid, { t: 'exit', exitCode: msg.exitCode });
|
|
277
|
+
case 'permission':
|
|
278
|
+
void Promise.resolve()
|
|
279
|
+
.then(() => this.#permissions(msg.request))
|
|
280
|
+
.catch((): PermissionDecision => 'deny')
|
|
281
|
+
.then((decision) => this.#port.postMessage({ t: 'permission-answer', id: msg.id, decision } satisfies ToRuntime));
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
#route(pid: number, ev: ProcEvent): void {
|
|
287
|
+
if (this.#sinks.has(pid)) return this.#deliver(pid, ev);
|
|
288
|
+
const list = this.#early.get(pid) ?? [];
|
|
289
|
+
list.push(ev);
|
|
290
|
+
this.#early.set(pid, list);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
#deliver(pid: number, ev: ProcEvent): void {
|
|
294
|
+
const sink = this.#sinks.get(pid);
|
|
295
|
+
if (!sink) return;
|
|
296
|
+
// A stream the reader cancelled throws on enqueue/close; that reader just stops getting data.
|
|
297
|
+
const each = (list: ReadableStreamDefaultController<string>[], fn: (c: ReadableStreamDefaultController<string>) => void) => {
|
|
298
|
+
for (const c of list) {
|
|
299
|
+
try {
|
|
300
|
+
fn(c);
|
|
301
|
+
} catch {
|
|
302
|
+
/* cancelled */
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
if (ev.t === 'output') return each([...sink.out, ...sink[ev.stream]], (c) => c.enqueue(ev.data));
|
|
307
|
+
each([...sink.out, ...sink.stdout, ...sink.stderr], (c) => c.close());
|
|
308
|
+
this.#sinks.delete(pid);
|
|
309
|
+
sink.exit(ev.exitCode);
|
|
310
|
+
}
|
|
311
|
+
}
|
package/src/protocol.ts
ADDED
|
@@ -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 };
|