@toolpal/sandbox 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.
@@ -0,0 +1,60 @@
1
+ import sjson from "secure-json-parse";
2
+ /**
3
+ * Newline-delimited JSON frames from an untrusted child. The byte cap applies
4
+ * before parsing, and parsing strips `__proto__`/`constructor.prototype` keys.
5
+ */
6
+ export function readFrames(stream, opts) {
7
+ let chunks = [];
8
+ let size = 0;
9
+ let broken = false;
10
+ const fail = (reason) => {
11
+ if (broken)
12
+ return;
13
+ broken = true;
14
+ chunks = [];
15
+ opts.onViolation(reason);
16
+ };
17
+ stream.on("data", (data) => {
18
+ if (broken)
19
+ return;
20
+ let start = 0;
21
+ for (let nl = data.indexOf(10); nl !== -1; nl = data.indexOf(10, start)) {
22
+ const piece = data.subarray(start, nl);
23
+ if (size + piece.length > opts.maxFrameBytes)
24
+ return fail("frame exceeds size limit");
25
+ chunks.push(piece);
26
+ const line = Buffer.concat(chunks).toString("utf8");
27
+ chunks = [];
28
+ size = 0;
29
+ start = nl + 1;
30
+ if (line.trim() === "")
31
+ continue;
32
+ let frame;
33
+ try {
34
+ frame = sjson.parse(line, undefined, {
35
+ protoAction: "remove",
36
+ constructorAction: "remove",
37
+ });
38
+ }
39
+ catch {
40
+ return fail("malformed frame");
41
+ }
42
+ if (frame === null ||
43
+ typeof frame !== "object" ||
44
+ typeof frame.type !== "string") {
45
+ return fail("frame without a type");
46
+ }
47
+ opts.onFrame(frame);
48
+ if (broken)
49
+ return;
50
+ }
51
+ const rest = data.subarray(start);
52
+ if (size + rest.length > opts.maxFrameBytes)
53
+ return fail("frame exceeds size limit");
54
+ if (rest.length > 0) {
55
+ chunks.push(rest);
56
+ size += rest.length;
57
+ }
58
+ });
59
+ }
60
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAC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Ac,CAAC;YACnB,IAAI,CAAC;gBACH,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,EAAE;oBACnC,WAAW,EAAE,QAAQ;oBACrB,iBAAiB,EAAE,QAAQ;iBAC5B,CAAC,CAAC;YACL,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACjC,CAAC;YACD,IACE,KAAK,KAAK,IAAI;gBACd,OAAO,KAAK,KAAK,QAAQ;gBACzB,OAAQ,KAAe,CAAC,IAAI,KAAK,QAAQ,EACzC,CAAC;gBACD,OAAO,IAAI,CAAC,sBAAsB,CAAC,CAAC;YACtC,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,KAAc,CAAC,CAAC;YAC7B,IAAI,MAAM;gBAAE,OAAO;QACrB,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,aAAa;YAAE,OAAO,IAAI,CAAC,0BAA0B,CAAC,CAAC;QACrF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClB,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC;QACtB,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** `child/runner.mjs` sits next to both `src/` and `dist/`, so the same relative URL works for either. */
2
+ export declare const RUNNER_PATH: string;
3
+ //# sourceMappingURL=runner-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-path.d.ts","sourceRoot":"","sources":["../src/runner-path.ts"],"names":[],"mappings":"AAEA,0GAA0G;AAC1G,eAAO,MAAM,WAAW,QAAiE,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { fileURLToPath } from "node:url";
2
+ /** `child/runner.mjs` sits next to both `src/` and `dist/`, so the same relative URL works for either. */
3
+ export const RUNNER_PATH = fileURLToPath(new URL("../child/runner.mjs", import.meta.url));
4
+ //# sourceMappingURL=runner-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-path.js","sourceRoot":"","sources":["../src/runner-path.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,0GAA0G;AAC1G,MAAM,CAAC,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,qBAAqB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC"}
@@ -0,0 +1,62 @@
1
+ import { type NodeRuntime } from "./node-version.js";
2
+ import { type CallDirs, type CallOptions, type SpawnSpec, type ToolDescription } from "./tool-process.js";
3
+ export interface SupervisorOptions {
4
+ /** Node binary for tool processes (default: TOOLPAL_NODE, then the current node). */
5
+ nodePath?: string | undefined;
6
+ maxProcessesPerTool?: number;
7
+ idleTimeoutMs?: number;
8
+ maxCallsPerProcess?: number;
9
+ maxOutputBytes?: number;
10
+ startupTimeoutMs?: number;
11
+ /** Test-only: see {@link NodeRuntime.simulateGuard}. Ignored below Node 25. */
12
+ simulateGuard?: boolean;
13
+ }
14
+ export interface RunSpec extends SpawnSpec {
15
+ /** Pool identity: processes are reused only for identical code + grants + env. */
16
+ key: string;
17
+ }
18
+ /**
19
+ * How a call's files get in and out of the tool's private folders. The tool's
20
+ * process cannot read the caller's paths, so the host copies in both directions.
21
+ */
22
+ export interface CallFiles {
23
+ /** Copies the caller's files into `dirs.inputDir` and returns the input to send instead. */
24
+ stage(dirs: CallDirs): Promise<unknown>;
25
+ /**
26
+ * Takes the files the tool returned out of `dirs.outputDir`, which is deleted
27
+ * afterwards, and returns the output to report instead.
28
+ */
29
+ collect(output: unknown, dirs: CallDirs): Promise<unknown>;
30
+ }
31
+ export interface RunOptions extends Omit<CallOptions, "outputDir"> {
32
+ isolation?: "warm" | "per-call";
33
+ /** For a tool that is handed files or returns them; it needs the `tmp` permission. */
34
+ files?: CallFiles | undefined;
35
+ }
36
+ export interface RunResult {
37
+ output: unknown;
38
+ durationMs: number;
39
+ node: string;
40
+ /** How the "no network" rule is enforced for this call. */
41
+ netIsolation: "native" | "best-effort" | "not-applicable";
42
+ }
43
+ export declare class Supervisor {
44
+ private readonly pools;
45
+ private readonly opts;
46
+ private closed;
47
+ constructor(opts?: SupervisorOptions);
48
+ runtime(): Promise<NodeRuntime>;
49
+ run(spec: RunSpec, input: unknown, opts: RunOptions): Promise<RunResult>;
50
+ /**
51
+ * Loads a bundle with no permissions at all and returns what `defineTool`
52
+ * describes. Used at build time to generate the manifest.
53
+ */
54
+ describe(spec: Omit<SpawnSpec, "permissions" | "env">): Promise<ToolDescription & {
55
+ sdkVersion: string | null;
56
+ }>;
57
+ close(): Promise<void>;
58
+ private pool;
59
+ private acquire;
60
+ private release;
61
+ }
62
+ //# sourceMappingURL=supervisor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor.d.ts","sourceRoot":"","sources":["../src/supervisor.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAsB,MAAM,mBAAmB,CAAC;AACzE,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,WAAW,EAEhB,KAAK,SAAS,EACd,KAAK,eAAe,EAErB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,WAAW,iBAAiB;IAChC,qFAAqF;IACrF,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,+EAA+E;IAC/E,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,OAAQ,SAAQ,SAA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AC,IAAI,CAAC,CAa3B;IAID,OAAO,CAAC,IAAI;YASE,OAAO;IAwCrB,OAAO,CAAC,OAAO;CA0BhB"}
@@ -0,0 +1,172 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { normalizePermissions } from "@toolpal/manifest";
3
+ import { SandboxError } from "./errors.js";
4
+ import { resolveNodeRuntime } from "./node-version.js";
5
+ import { ToolProcess, } from "./tool-process.js";
6
+ export class Supervisor {
7
+ pools = new Map();
8
+ opts;
9
+ closed = false;
10
+ constructor(opts = {}) {
11
+ this.opts = {
12
+ nodePath: opts.nodePath,
13
+ maxProcessesPerTool: opts.maxProcessesPerTool ?? 2,
14
+ idleTimeoutMs: opts.idleTimeoutMs ?? 30_000,
15
+ maxCallsPerProcess: opts.maxCallsPerProcess ?? 1000,
16
+ maxOutputBytes: opts.maxOutputBytes ?? 4 * 1024 * 1024,
17
+ startupTimeoutMs: opts.startupTimeoutMs ?? 15_000,
18
+ simulateGuard: opts.simulateGuard ?? false,
19
+ };
20
+ }
21
+ async runtime() {
22
+ const runtime = await resolveNodeRuntime(this.opts.nodePath);
23
+ if (this.opts.simulateGuard && runtime.netMode === "native") {
24
+ return { ...runtime, netMode: "guard", simulateGuard: true };
25
+ }
26
+ return runtime;
27
+ }
28
+ async run(spec, input, opts) {
29
+ if (this.closed)
30
+ throw new SandboxError("ABORTED", "supervisor is closed");
31
+ const runtime = await this.runtime();
32
+ const isolation = opts.isolation ?? "warm";
33
+ if (opts.files && !spec.permissions.tmp) {
34
+ throw new SandboxError("INVALID_TOOL", "a tool with file inputs or outputs needs the `tmp` permission");
35
+ }
36
+ const proc = await this.acquire(spec, runtime, isolation, opts.onLog);
37
+ let dirs;
38
+ try {
39
+ let sent = input;
40
+ if (opts.files) {
41
+ try {
42
+ dirs = await proc.openCallDirs();
43
+ sent = await opts.files.stage(dirs);
44
+ }
45
+ catch (err) {
46
+ // A new process is only unref'd after a call, and this one will not get one.
47
+ proc.unref();
48
+ throw err;
49
+ }
50
+ }
51
+ const started = performance.now();
52
+ let output = await proc.call(sent, { ...opts, outputDir: dirs?.outputDir });
53
+ if (opts.files && dirs)
54
+ output = await opts.files.collect(output, dirs);
55
+ return {
56
+ output,
57
+ durationMs: Math.round(performance.now() - started),
58
+ node: proc.childNodeVersion || runtime.version,
59
+ netIsolation: spec.permissions.net
60
+ ? "not-applicable"
61
+ : runtime.netMode === "native"
62
+ ? "native"
63
+ : "best-effort",
64
+ };
65
+ }
66
+ finally {
67
+ await dirs?.remove();
68
+ this.release(spec.key, proc, isolation);
69
+ }
70
+ }
71
+ /**
72
+ * Loads a bundle with no permissions at all and returns what `defineTool`
73
+ * describes. Used at build time to generate the manifest.
74
+ */
75
+ async describe(spec) {
76
+ const runtime = await this.runtime();
77
+ const proc = await ToolProcess.start({ ...spec, permissions: normalizePermissions({}), env: {} }, runtime, { startupTimeoutMs: this.opts.startupTimeoutMs, maxOutputBytes: this.opts.maxOutputBytes });
78
+ proc.terminate();
79
+ if (!proc.description) {
80
+ throw new SandboxError("INVALID_TOOL", "tool did not describe itself (is it built with defineTool?)");
81
+ }
82
+ return { ...proc.description, sdkVersion: proc.sdkVersion };
83
+ }
84
+ async close() {
85
+ this.closed = true;
86
+ const exits = [];
87
+ for (const pool of this.pools.values()) {
88
+ for (const timer of pool.idleTimers.values())
89
+ clearTimeout(timer);
90
+ for (const proc of [...pool.idle, ...pool.busy]) {
91
+ exits.push(new Promise((resolve) => proc.onExit(resolve)));
92
+ proc.terminate(new SandboxError("ABORTED", "supervisor closed"));
93
+ }
94
+ for (const wake of pool.waiters.splice(0))
95
+ wake();
96
+ }
97
+ this.pools.clear();
98
+ await Promise.all(exits);
99
+ }
100
+ // ---------------------------------------------------------------------------
101
+ pool(key) {
102
+ let pool = this.pools.get(key);
103
+ if (!pool) {
104
+ pool = { idle: [], idleTimers: new Map(), busy: new Set(), starting: 0, waiters: [] };
105
+ this.pools.set(key, pool);
106
+ }
107
+ return pool;
108
+ }
109
+ async acquire(spec, runtime, isolation, onLog) {
110
+ const pool = this.pool(spec.key);
111
+ for (;;) {
112
+ if (this.closed)
113
+ throw new SandboxError("ABORTED", "supervisor is closed");
114
+ while (isolation === "warm" && pool.idle.length > 0) {
115
+ const proc = pool.idle.pop();
116
+ clearTimeout(pool.idleTimers.get(proc));
117
+ pool.idleTimers.delete(proc);
118
+ if (proc.alive) {
119
+ pool.busy.add(proc);
120
+ return proc;
121
+ }
122
+ }
123
+ if (pool.busy.size + pool.starting < this.opts.maxProcessesPerTool) {
124
+ pool.starting++;
125
+ let proc;
126
+ try {
127
+ proc = await ToolProcess.start(spec, runtime, {
128
+ startupTimeoutMs: this.opts.startupTimeoutMs,
129
+ maxOutputBytes: this.opts.maxOutputBytes,
130
+ onLog,
131
+ });
132
+ }
133
+ catch (err) {
134
+ pool.starting--;
135
+ pool.waiters.shift()?.(); // the slot is free again
136
+ throw err;
137
+ }
138
+ pool.starting--;
139
+ pool.busy.add(proc);
140
+ return proc;
141
+ }
142
+ await new Promise((resolve) => pool.waiters.push(resolve));
143
+ }
144
+ }
145
+ release(key, proc, isolation) {
146
+ const pool = this.pools.get(key);
147
+ if (!pool) {
148
+ proc.terminate();
149
+ return;
150
+ }
151
+ pool.busy.delete(proc);
152
+ const reusable = !this.closed &&
153
+ isolation === "warm" &&
154
+ proc.alive &&
155
+ proc.callsServed < this.opts.maxCallsPerProcess;
156
+ if (reusable) {
157
+ pool.idle.push(proc);
158
+ const timer = setTimeout(() => {
159
+ pool.idleTimers.delete(proc);
160
+ pool.idle = pool.idle.filter((p) => p !== proc);
161
+ proc.terminate();
162
+ }, this.opts.idleTimeoutMs);
163
+ timer.unref();
164
+ pool.idleTimers.set(proc, timer);
165
+ }
166
+ else {
167
+ proc.terminate();
168
+ }
169
+ pool.waiters.shift()?.();
170
+ }
171
+ }
172
+ //# sourceMappingURL=supervisor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor.js","sourceRoot":"","sources":["../src/supervisor.ts"],"names":[],"mappings":"AAAA,O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IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YAC5B,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACnC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,SAAS,EAAE,CAAC;QACnB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,EAAE,CAAC;IAC3B,CAAC;CACF"}
@@ -0,0 +1,95 @@
1
+ import type { Permissions } from "@toolpal/manifest";
2
+ import { SandboxError } from "./errors.js";
3
+ import type { NodeRuntime } from "./node-version.js";
4
+ export interface ToolExampleInput {
5
+ title?: string;
6
+ prompt?: string;
7
+ input: Record<string, unknown>;
8
+ }
9
+ export interface ToolDescription {
10
+ description: string;
11
+ inputSchema: Record<string, unknown>;
12
+ outputSchema: Record<string, unknown>;
13
+ examples?: ToolExampleInput[];
14
+ }
15
+ export interface LogEntry {
16
+ level: "debug" | "info" | "warn" | "error";
17
+ message: string;
18
+ data?: unknown;
19
+ }
20
+ export type LogHandler = (entry: LogEntry) => void;
21
+ /** Everything needed to start a process for one tool with one set of grants. */
22
+ export interface SpawnSpec {
23
+ /** Directory the tool may read (its extracted package or project dir). */
24
+ toolDir: string;
25
+ /** Absolute path of `dist/tool.mjs` inside `toolDir`. */
26
+ entryPath: string;
27
+ /** `sha256-<base64>` of the entry bytes; verified by the child before running anything. */
28
+ entryIntegrity: string;
29
+ permissions: Permissions;
30
+ memoryMb: number;
31
+ /** Env vars handed to the tool: declared in the manifest and supplied by the consumer. */
32
+ env: Record<string, string>;
33
+ }
34
+ export interface CallOptions {
35
+ timeoutMs: number;
36
+ signal?: AbortSignal | undefined;
37
+ onLog?: LogHandler | undefined;
38
+ /** The call's `ctx.outputDir`: the `outputDir` of the folders `openCallDirs` made for it. */
39
+ outputDir?: string | undefined;
40
+ }
41
+ /** One call's folders, inside the temp dir that only this tool's process can use. */
42
+ export interface CallDirs {
43
+ /** Copies of the files the caller hands over go here before the call. */
44
+ inputDir: string;
45
+ /** The tool writes the files it returns here. */
46
+ outputDir: string;
47
+ }
48
+ export declare function buildNodeArgs(spec: SpawnSpec, runtime: NodeRuntime, tmpDir?: string): string[];
49
+ export declare function buildChildEnv(spec: SpawnSpec, tmpDir?: string): Record<string, string>;
50
+ export declare function netModeFor(spec: SpawnSpec, runtime: NodeRuntime): "open" | "native" | "guard";
51
+ /** One permission-restricted child process running one tool. Handles one call at a time. */
52
+ export declare class ToolProcess {
53
+ private readonly child;
54
+ private readonly tmpDir;
55
+ private readonly maxOutputBytes;
56
+ callsServed: number;
57
+ description: ToolDescription | null;
58
+ sdkVersion: string | null;
59
+ childNodeVersion: string;
60
+ private state;
61
+ private pending;
62
+ private readyWaiter;
63
+ private stderrTail;
64
+ private callSeq;
65
+ private logsThisCall;
66
+ private exitListeners;
67
+ private constructor();
68
+ static start(spec: SpawnSpec, runtime: NodeRuntime, opts: {
69
+ startupTimeoutMs: number;
70
+ maxOutputBytes: number;
71
+ onLog?: LogHandler | undefined;
72
+ }): Promise<ToolProcess>;
73
+ get alive(): boolean;
74
+ onExit(listener: () => void): void;
75
+ /**
76
+ * Makes the folders for one call's files. They are new and randomly named, so
77
+ * the tool cannot have put anything in their place; `remove` deletes them.
78
+ */
79
+ openCallDirs(): Promise<CallDirs & {
80
+ remove(): Promise<void>;
81
+ }>;
82
+ call(input: unknown, opts: CallOptions): Promise<unknown>;
83
+ /** Kill the process; a pending call or startup rejects with `err`. */
84
+ terminate(err?: SandboxError): void;
85
+ ref(): void;
86
+ /** Idle processes must not keep the host's event loop alive (scripts exit on their own). */
87
+ unref(): void;
88
+ private wire;
89
+ private onFrame;
90
+ private failStartup;
91
+ private rejectAll;
92
+ private classifyExit;
93
+ private writeFrame;
94
+ }
95
+ //# sourceMappingURL=tool-process.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-process.d.ts","sourceRoot":"","sources":["../src/tool-process.ts"],"names":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