@clearideas/agent-runtime-sandbox 0.5.0 → 0.6.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,408 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { chmod, lstat, mkdir, mkdtemp, open, readdir, readFile, readlink, rename, rm, unlink, } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { assertSandboxPath, assertSandboxResourceLimits, } from "./contracts.js";
7
+ export const DEFAULT_BUBBLEWRAP_BINDS = [
8
+ "/usr",
9
+ "/bin",
10
+ "/sbin",
11
+ "/lib",
12
+ "/lib32",
13
+ "/lib64",
14
+ "/libx32",
15
+ "/etc/alternatives",
16
+ "/etc/ld.so.cache",
17
+ "/etc/ld.so.conf",
18
+ "/etc/ld.so.conf.d",
19
+ ];
20
+ const SANDBOX_ROOT = "/workspace";
21
+ const ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
22
+ const isMissing = (error) => error?.code === "ENOENT";
23
+ const collect = async (binary, args, signal) => {
24
+ const child = spawn(binary, args, {
25
+ stdio: ["ignore", "pipe", "pipe"],
26
+ ...(signal ? { signal } : {}),
27
+ });
28
+ const stdout = [];
29
+ const stderr = [];
30
+ child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)));
31
+ child.stderr.on("data", (chunk) => stderr.push(Buffer.from(chunk)));
32
+ const exitCode = await new Promise((resolve) => {
33
+ child.once("error", () => resolve(127));
34
+ child.once("exit", (code) => resolve(code ?? 1));
35
+ });
36
+ return {
37
+ stdout: Buffer.concat(stdout).toString("utf8"),
38
+ stderr: Buffer.concat(stderr).toString("utf8"),
39
+ exitCode,
40
+ };
41
+ };
42
+ /**
43
+ * A local sandbox provider built on bubblewrap (bwrap): separate user, PID,
44
+ * IPC, UTS, cgroup, and network namespaces, read-only binds of host system
45
+ * directories, a private /workspace backed by a host directory the provider
46
+ * owns, and prlimit-enforced memory, CPU, process, and file-size limits.
47
+ * Requires Linux with unprivileged user namespaces. It runs without a
48
+ * container daemon and is the reference provider for local development and
49
+ * continuous integration.
50
+ */
51
+ export class BubblewrapSandboxProvider {
52
+ name = "bubblewrap";
53
+ capabilities = {
54
+ readOnlyAttachments: true,
55
+ };
56
+ #binary;
57
+ #prlimit;
58
+ #binds;
59
+ #stateDirectory;
60
+ #environment;
61
+ #now;
62
+ #sandboxes = new Map();
63
+ #bindArguments;
64
+ #prlimitAvailable;
65
+ #probe;
66
+ constructor(options = {}) {
67
+ this.#binary = options.binary ?? "bwrap";
68
+ this.#prlimit = options.prlimitBinary ?? "prlimit";
69
+ this.#binds = options.binds ?? DEFAULT_BUBBLEWRAP_BINDS;
70
+ this.#stateDirectory = path.resolve(options.stateDirectory ?? tmpdir());
71
+ this.#environment = options.environment ?? {};
72
+ this.#now = options.now ?? (() => new Date());
73
+ for (const [name] of Object.entries(this.#environment)) {
74
+ if (!ENVIRONMENT_NAME.test(name))
75
+ throw new Error(`Invalid environment name: ${name}`);
76
+ }
77
+ }
78
+ /** Resolve bind arguments once; symbolic links (for example /bin → usr/bin) are recreated as links. */
79
+ async #bindArgumentList() {
80
+ if (this.#bindArguments)
81
+ return this.#bindArguments;
82
+ const args = [];
83
+ for (const bind of this.#binds) {
84
+ if (!path.isAbsolute(bind))
85
+ throw new Error(`Bind must be absolute: ${bind}`);
86
+ const stats = await lstat(bind).catch((error) => {
87
+ if (isMissing(error))
88
+ return undefined;
89
+ throw error;
90
+ });
91
+ if (!stats)
92
+ continue;
93
+ if (stats.isSymbolicLink()) {
94
+ args.push("--symlink", await readlink(bind), bind);
95
+ }
96
+ else {
97
+ args.push("--ro-bind", bind, bind);
98
+ }
99
+ }
100
+ this.#bindArguments = args;
101
+ return args;
102
+ }
103
+ /** Confirm bubblewrap can create an isolated sandbox on this host. */
104
+ async probe(options) {
105
+ if (!this.#probe) {
106
+ this.#probe = (async () => {
107
+ const binds = await this.#bindArgumentList();
108
+ const result = await collect(this.#binary, [
109
+ "--unshare-all",
110
+ "--die-with-parent",
111
+ "--new-session",
112
+ "--clearenv",
113
+ ...binds,
114
+ "--proc",
115
+ "/proc",
116
+ "--dev",
117
+ "/dev",
118
+ "--tmpfs",
119
+ "/tmp",
120
+ "--tmpfs",
121
+ SANDBOX_ROOT,
122
+ "--",
123
+ "/bin/true",
124
+ ], options?.signal);
125
+ if (result.exitCode !== 0) {
126
+ throw new Error(`bubblewrap is unavailable (exit ${result.exitCode}): ${result.stderr.trim() || "install bubblewrap and enable unprivileged user namespaces"}`);
127
+ }
128
+ const prlimit = await collect(this.#prlimit, ["--version"]);
129
+ this.#prlimitAvailable = prlimit.exitCode === 0;
130
+ })();
131
+ this.#probe.catch(() => {
132
+ this.#probe = undefined;
133
+ });
134
+ }
135
+ await this.#probe;
136
+ }
137
+ /** True when prlimit is available and resource limits are enforced. */
138
+ get limitsEnforced() {
139
+ return this.#prlimitAvailable;
140
+ }
141
+ async validate(spec, options) {
142
+ if (spec.network !== "none")
143
+ throw new Error("Bubblewrap sandbox only permits network: none.");
144
+ assertSandboxPath(spec.workingDirectory);
145
+ assertSandboxResourceLimits(spec.limits);
146
+ for (const attachment of spec.attachments ?? []) {
147
+ assertSandboxPath(attachment.target);
148
+ if (!path.isAbsolute(attachment.source))
149
+ throw new Error(`Attachment source must be absolute: ${attachment.source}`);
150
+ }
151
+ await this.probe(options);
152
+ }
153
+ async create(spec, options) {
154
+ await this.validate(spec, options);
155
+ await mkdir(this.#stateDirectory, { recursive: true });
156
+ const hostRoot = await mkdtemp(path.join(this.#stateDirectory, "agent-runtime-bwrap-"));
157
+ const hostWorkspace = path.join(hostRoot, "workspace");
158
+ await mkdir(hostWorkspace, { mode: 0o700 });
159
+ const id = `bwrap-${randomUUID()}`;
160
+ this.#sandboxes.set(id, {
161
+ hostRoot,
162
+ hostWorkspace,
163
+ spec,
164
+ limitsEnforced: this.#prlimitAvailable === true,
165
+ });
166
+ return {
167
+ id,
168
+ provider: this.name,
169
+ createdAt: this.#now().toISOString(),
170
+ providerData: {
171
+ hostRoot,
172
+ limitsEnforced: this.#prlimitAvailable === true,
173
+ ...(spec.metadata ?? {}),
174
+ },
175
+ };
176
+ }
177
+ async putFiles(handle, files, options) {
178
+ const state = this.#state(handle);
179
+ for (const file of files) {
180
+ options?.signal?.throwIfAborted();
181
+ const mode = file.mode ?? 0o600;
182
+ if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0o777) {
183
+ throw new Error(`Invalid sandbox file mode: ${String(file.mode)}`);
184
+ }
185
+ const target = await this.#hostPath(state, file.path, { forWrite: true });
186
+ await mkdir(path.dirname(target), { recursive: true });
187
+ const temporary = `${target}.${randomUUID()}.tmp`;
188
+ let descriptor;
189
+ try {
190
+ descriptor = await open(temporary, "wx", 0o600);
191
+ await descriptor.writeFile(file.content);
192
+ await descriptor.close();
193
+ descriptor = undefined;
194
+ await chmod(temporary, mode);
195
+ await rename(temporary, target);
196
+ }
197
+ catch (error) {
198
+ await descriptor?.close().catch(() => undefined);
199
+ await unlink(temporary).catch(() => undefined);
200
+ throw error;
201
+ }
202
+ }
203
+ }
204
+ async *execute(handle, command, options) {
205
+ const state = this.#state(handle);
206
+ const binds = await this.#bindArgumentList();
207
+ const args = [
208
+ "--unshare-all",
209
+ "--die-with-parent",
210
+ "--new-session",
211
+ "--clearenv",
212
+ ...binds,
213
+ "--proc",
214
+ "/proc",
215
+ "--dev",
216
+ "/dev",
217
+ "--tmpfs",
218
+ "/tmp",
219
+ "--bind",
220
+ state.hostWorkspace,
221
+ SANDBOX_ROOT,
222
+ ];
223
+ for (const attachment of state.spec.attachments ?? []) {
224
+ args.push("--ro-bind", attachment.source, assertSandboxPath(attachment.target));
225
+ }
226
+ args.push("--chdir", assertSandboxPath(command.cwd ?? state.spec.workingDirectory));
227
+ const environment = {
228
+ PATH: "/usr/local/bin:/usr/bin:/bin",
229
+ HOME: "/tmp",
230
+ LANG: "C.UTF-8",
231
+ PYTHONDONTWRITEBYTECODE: "1",
232
+ ...this.#environment,
233
+ ...(command.environment ?? {}),
234
+ };
235
+ for (const [name, value] of Object.entries(environment)) {
236
+ if (!ENVIRONMENT_NAME.test(name))
237
+ throw new Error(`Invalid environment name: ${name}`);
238
+ args.push("--setenv", name, value);
239
+ }
240
+ args.push("--");
241
+ if (state.limitsEnforced) {
242
+ const limits = state.spec.limits;
243
+ const timeoutSeconds = Math.max(1, Math.ceil((command.timeoutMs ?? limits.timeoutMs) / 1_000));
244
+ args.push(this.#prlimit, `--as=${(limits.memoryMb ?? 1_024) * 1_048_576}`, `--cpu=${timeoutSeconds}`, `--nproc=${limits.processLimit ?? 128}`, `--fsize=${(limits.workspaceTmpfsMb ?? 1_024) * 1_048_576}`, "--");
245
+ }
246
+ args.push(command.command, ...(command.args ?? []));
247
+ const controller = new AbortController();
248
+ const onAbort = () => controller.abort(options?.signal?.reason);
249
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
250
+ const timeout = command.timeoutMs
251
+ ? setTimeout(() => controller.abort(new Error("Sandbox command timed out.")), command.timeoutMs)
252
+ : undefined;
253
+ try {
254
+ const child = spawn(this.#binary, args, {
255
+ stdio: ["ignore", "pipe", "pipe"],
256
+ signal: controller.signal,
257
+ killSignal: "SIGKILL",
258
+ });
259
+ const events = [];
260
+ let wake;
261
+ let ended = false;
262
+ const append = (event) => {
263
+ events.push(event);
264
+ wake?.();
265
+ wake = undefined;
266
+ };
267
+ child.stdout.setEncoding("utf8");
268
+ child.stderr.setEncoding("utf8");
269
+ child.stdout.on("data", (data) => append({ type: "stdout", data }));
270
+ child.stderr.on("data", (data) => append({ type: "stderr", data }));
271
+ child.once("error", (error) => {
272
+ if (error.code === "ABORT_ERR")
273
+ return;
274
+ append({ type: "stderr", data: error.message });
275
+ });
276
+ child.once("exit", (code, signal) => {
277
+ append({
278
+ type: "exit",
279
+ exitCode: code ?? (signal ? 137 : 1),
280
+ ...(signal ? { signal } : {}),
281
+ });
282
+ ended = true;
283
+ wake?.();
284
+ });
285
+ while (!ended || events.length > 0) {
286
+ const event = events.shift();
287
+ if (event)
288
+ yield event;
289
+ else
290
+ await new Promise((resolve) => {
291
+ wake = resolve;
292
+ });
293
+ }
294
+ }
295
+ finally {
296
+ if (timeout)
297
+ clearTimeout(timeout);
298
+ options?.signal?.removeEventListener("abort", onAbort);
299
+ }
300
+ }
301
+ async listFiles(handle, directory, options) {
302
+ const state = this.#state(handle);
303
+ const normalized = assertSandboxPath(directory);
304
+ const root = await this.#hostPath(state, normalized, {
305
+ forWrite: false,
306
+ }).catch(() => undefined);
307
+ if (!root)
308
+ return [];
309
+ const files = [];
310
+ const pending = [normalized];
311
+ while (pending.length > 0) {
312
+ options?.signal?.throwIfAborted();
313
+ const current = pending.shift();
314
+ const hostCurrent = this.#translate(state, current);
315
+ let entries;
316
+ try {
317
+ entries = await readdir(hostCurrent, { withFileTypes: true });
318
+ }
319
+ catch (error) {
320
+ if (isMissing(error))
321
+ continue;
322
+ throw error;
323
+ }
324
+ entries.sort((left, right) => (left.name < right.name ? -1 : 1));
325
+ for (const entry of entries) {
326
+ if (entry.isSymbolicLink())
327
+ continue;
328
+ const sandboxPath = `${current}/${entry.name}`;
329
+ if (!/^[A-Za-z0-9._-]+$/u.test(entry.name) ||
330
+ entry.name === "." ||
331
+ entry.name === "..")
332
+ continue;
333
+ if (entry.isDirectory()) {
334
+ pending.push(sandboxPath);
335
+ }
336
+ else if (entry.isFile()) {
337
+ const stats = await lstat(path.join(hostCurrent, entry.name));
338
+ if (stats.isFile())
339
+ files.push({ path: sandboxPath, size: stats.size });
340
+ }
341
+ }
342
+ }
343
+ return files;
344
+ }
345
+ async readFile(handle, filePath, options) {
346
+ options?.signal?.throwIfAborted();
347
+ const state = this.#state(handle);
348
+ const target = await this.#hostPath(state, filePath, { forWrite: false });
349
+ const stats = await lstat(target);
350
+ if (!stats.isFile())
351
+ throw new Error(`Sandbox path is not a regular file: ${filePath}`);
352
+ return readFile(target);
353
+ }
354
+ async terminate(handle) {
355
+ const state = this.#sandboxes.get(handle.id);
356
+ this.#sandboxes.delete(handle.id);
357
+ const hostRoot = state?.hostRoot ??
358
+ (typeof handle.providerData?.hostRoot === "string"
359
+ ? handle.providerData.hostRoot
360
+ : undefined);
361
+ if (!hostRoot)
362
+ return;
363
+ if (hostRoot !== this.#stateDirectory &&
364
+ hostRoot.startsWith(`${this.#stateDirectory}${path.sep}`)) {
365
+ await rm(hostRoot, { recursive: true, force: true });
366
+ }
367
+ }
368
+ #state(handle) {
369
+ const state = this.#sandboxes.get(handle.id);
370
+ if (handle.provider !== this.name || !state) {
371
+ throw new Error("Sandbox handle does not belong to this BubblewrapSandboxProvider.");
372
+ }
373
+ return state;
374
+ }
375
+ #translate(state, sandboxPath) {
376
+ const normalized = assertSandboxPath(sandboxPath);
377
+ if (normalized === SANDBOX_ROOT)
378
+ return state.hostWorkspace;
379
+ return path.join(state.hostWorkspace, ...normalized.slice(SANDBOX_ROOT.length + 1).split("/"));
380
+ }
381
+ /**
382
+ * Map a sandbox path to the host directory, refusing any symbolic link
383
+ * component so software inside the sandbox cannot redirect host-side reads
384
+ * or writes outside the sandbox's own directory.
385
+ */
386
+ async #hostPath(state, sandboxPath, options) {
387
+ const target = this.#translate(state, sandboxPath);
388
+ let current = state.hostWorkspace;
389
+ const relative = path.relative(state.hostWorkspace, target);
390
+ for (const segment of relative ? relative.split(path.sep) : []) {
391
+ current = path.join(current, segment);
392
+ const stats = await lstat(current).catch((error) => {
393
+ if (isMissing(error))
394
+ return undefined;
395
+ throw error;
396
+ });
397
+ if (!stats) {
398
+ if (options.forWrite)
399
+ return target;
400
+ throw new Error(`Sandbox path does not exist: ${sandboxPath}`);
401
+ }
402
+ if (stats.isSymbolicLink()) {
403
+ throw new Error(`Sandbox path crosses a symbolic link: ${sandboxPath}`);
404
+ }
405
+ }
406
+ return target;
407
+ }
408
+ }
@@ -6,16 +6,32 @@ export interface SandboxResourceLimits {
6
6
  processLimit?: number;
7
7
  maximumOutputBytes?: number;
8
8
  maximumOutputFiles?: number;
9
+ /** Size of the /workspace filesystem for providers that allocate one. */
10
+ workspaceTmpfsMb?: number;
9
11
  }
10
12
  /** Validates provider-bound limits before untrusted code reaches a sandbox. */
11
13
  export declare const assertSandboxResourceLimits: (limits: SandboxResourceLimits) => void;
14
+ /** A host directory bound read-only into the sandbox at creation. */
15
+ export interface SandboxAttachment {
16
+ /** Absolute host directory. */
17
+ source: string;
18
+ /** Normalized target beneath /workspace. */
19
+ target: string;
20
+ }
12
21
  export interface SandboxSpec {
13
22
  image: string;
14
23
  workingDirectory: string;
15
24
  network: SandboxNetworkPolicy;
16
25
  limits: SandboxResourceLimits;
26
+ /** Honored only by providers whose capabilities declare readOnlyAttachments. */
27
+ attachments?: SandboxAttachment[];
28
+ /** Provider-visible labels, e.g. the owning run id for host cleanup. */
17
29
  metadata?: Record<string, string | number | boolean>;
18
30
  }
31
+ export interface SandboxProviderCapabilities {
32
+ /** The provider can bind host directories read-only from SandboxSpec.attachments. */
33
+ readOnlyAttachments?: boolean;
34
+ }
19
35
  export interface SandboxHandle {
20
36
  id: string;
21
37
  provider: string;
@@ -51,6 +67,11 @@ export interface SandboxFileInfo {
51
67
  }
52
68
  export interface SandboxProvider {
53
69
  readonly name: string;
70
+ readonly capabilities?: SandboxProviderCapabilities;
71
+ /** Check that a specification could be created without creating it. */
72
+ validate?(spec: SandboxSpec, options?: {
73
+ signal?: AbortSignal;
74
+ }): Promise<void>;
54
75
  create(spec: SandboxSpec, options?: {
55
76
  signal?: AbortSignal;
56
77
  }): Promise<SandboxHandle>;
package/dist/contracts.js CHANGED
@@ -24,6 +24,9 @@ export const assertSandboxResourceLimits = (limits) => {
24
24
  if (limits.maximumOutputFiles != null) {
25
25
  positiveSafeInteger(limits.maximumOutputFiles, "Sandbox maximumOutputFiles", 1_000_000);
26
26
  }
27
+ if (limits.workspaceTmpfsMb != null) {
28
+ positiveSafeInteger(limits.workspaceTmpfsMb, "Sandbox workspaceTmpfsMb", 1_048_576);
29
+ }
27
30
  };
28
31
  const SAFE_WORKSPACE_PATH = /^\/workspace(?:\/[A-Za-z0-9._-]+)*$/u;
29
32
  export const assertSandboxPath = (value) => {
package/dist/docker.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type SandboxCommand, type SandboxFileInfo, type SandboxHandle, type SandboxInputFile, type SandboxProcessEvent, type SandboxProvider, type SandboxSpec } from "./contracts.js";
1
+ import { type SandboxCommand, type SandboxFileInfo, type SandboxHandle, type SandboxInputFile, type SandboxProcessEvent, type SandboxProvider, type SandboxProviderCapabilities, type SandboxSpec } from "./contracts.js";
2
2
  export interface DockerSandboxProviderOptions {
3
3
  binary?: string;
4
4
  allowedImages: string[];
@@ -7,7 +7,9 @@ export interface DockerSandboxProviderOptions {
7
7
  export declare class DockerSandboxProvider implements SandboxProvider {
8
8
  #private;
9
9
  readonly name = "docker";
10
+ readonly capabilities: SandboxProviderCapabilities;
10
11
  constructor(options: DockerSandboxProviderOptions);
12
+ validate(spec: SandboxSpec): Promise<void>;
11
13
  create(spec: SandboxSpec, options?: {
12
14
  signal?: AbortSignal;
13
15
  }): Promise<SandboxHandle>;
package/dist/docker.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { assertSandboxResourceLimits, assertSandboxPath, } from "./contracts.js";
4
+ const LABEL_KEY = /^[a-z0-9][a-z0-9._-]*$/u;
5
+ const LABEL_VALUE = /^[A-Za-z0-9._:-]*$/u;
4
6
  const collect = async (binary, args, input, signal) => {
5
7
  const child = spawn(binary, args, {
6
8
  stdio: ["pipe", "pipe", "pipe"],
@@ -43,6 +45,9 @@ const collect = async (binary, args, input, signal) => {
43
45
  };
44
46
  export class DockerSandboxProvider {
45
47
  name = "docker";
48
+ capabilities = {
49
+ readOnlyAttachments: true,
50
+ };
46
51
  #binary;
47
52
  #allowedImages;
48
53
  #now;
@@ -53,14 +58,30 @@ export class DockerSandboxProvider {
53
58
  this.#allowedImages = new Set(options.allowedImages);
54
59
  this.#now = options.now ?? (() => new Date());
55
60
  }
56
- async create(spec, options) {
61
+ async validate(spec) {
57
62
  if (!this.#allowedImages.has(spec.image))
58
63
  throw new Error(`Docker image is not allowed: ${spec.image}`);
59
64
  if (spec.network !== "none")
60
65
  throw new Error("Docker reference sandbox only permits network: none.");
61
66
  assertSandboxPath(spec.workingDirectory);
62
67
  assertSandboxResourceLimits(spec.limits);
68
+ for (const attachment of spec.attachments ?? []) {
69
+ assertSandboxPath(attachment.target);
70
+ if (!attachment.source.startsWith("/") ||
71
+ attachment.source.includes(":")) {
72
+ throw new Error(`Docker attachment source must be an absolute path without colons: ${attachment.source}`);
73
+ }
74
+ }
75
+ for (const [key, value] of Object.entries(spec.metadata ?? {})) {
76
+ if (!LABEL_KEY.test(key) || !LABEL_VALUE.test(String(value))) {
77
+ throw new Error(`Docker label is invalid: ${key}`);
78
+ }
79
+ }
80
+ }
81
+ async create(spec, options) {
82
+ await this.validate(spec);
63
83
  const name = `agent-runtime-${randomUUID()}`;
84
+ const workspaceSize = spec.limits.workspaceTmpfsMb ?? 256;
64
85
  const args = [
65
86
  "create",
66
87
  "--name",
@@ -75,7 +96,7 @@ export class DockerSandboxProvider {
75
96
  "65532:65532",
76
97
  "--read-only",
77
98
  "--tmpfs",
78
- "/workspace:rw,noexec,nosuid,nodev,size=256m,uid=65532,gid=65532,mode=0700",
99
+ `/workspace:rw,noexec,nosuid,nodev,size=${workspaceSize}m,uid=65532,gid=65532,mode=0700`,
79
100
  "--tmpfs",
80
101
  "/tmp:rw,noexec,nosuid,nodev,size=64m,uid=65532,gid=65532,mode=0700",
81
102
  "--workdir",
@@ -86,6 +107,14 @@ export class DockerSandboxProvider {
86
107
  String(spec.limits.cpuCount ?? 1),
87
108
  "--pids-limit",
88
109
  String(spec.limits.processLimit ?? 64),
110
+ ...(spec.attachments ?? []).flatMap((attachment) => [
111
+ "--volume",
112
+ `${attachment.source}:${attachment.target}:ro`,
113
+ ]),
114
+ ...Object.entries(spec.metadata ?? {}).flatMap(([key, value]) => [
115
+ "--label",
116
+ `${key}=${String(value)}`,
117
+ ]),
89
118
  spec.image,
90
119
  "sleep",
91
120
  "infinity",
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export * from "./contracts.js";
2
2
  export * from "./docker.js";
3
+ export * from "./bubblewrap.js";
3
4
  export * from "./provider-adapter.js";
5
+ export * from "./policy.js";
6
+ export * from "./run-sandbox.js";
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
1
  export * from "./contracts.js";
2
2
  export * from "./docker.js";
3
+ export * from "./bubblewrap.js";
3
4
  export * from "./provider-adapter.js";
5
+ export * from "./policy.js";
6
+ export * from "./run-sandbox.js";
@@ -0,0 +1,114 @@
1
+ import type { WorkspaceMode } from "@clearideas/agent-runtime-contracts";
2
+ import type { AgentTool, ResolvedWorkspace, RunSandboxCommandRequest } from "@clearideas/agent-runtime-core";
3
+ import { type SandboxInputFile } from "./contracts.js";
4
+ /** Built-in operations served by the runtime-shipped helper. */
5
+ export declare const BUILTIN_WORKSPACE_TOOLS: readonly ["list_files", "read_file", "search_files", "write_file", "delete_file"];
6
+ export type BuiltinWorkspaceTool = (typeof BUILTIN_WORKSPACE_TOOLS)[number];
7
+ export declare const BUILTIN_READ_TOOLS: readonly BuiltinWorkspaceTool[];
8
+ export declare const SHELL_TOOL_NAME = "shell";
9
+ export declare const SANDBOX_MOUNT_DIRECTORY = "/workspace/mounts";
10
+ export declare const SANDBOX_OUTPUT_DIRECTORY = "/workspace/output";
11
+ export declare const SANDBOX_STAGING_DIRECTORY = "/workspace/staging";
12
+ export declare const SANDBOX_STEPS_DIRECTORY = "/workspace/steps";
13
+ export declare const SANDBOX_HELPER_PATH = "/workspace/bin/agent-fs";
14
+ export declare const SANDBOX_WORKSPACES_FILE = "/workspace/workspaces.json";
15
+ export declare const DEFAULT_HELPER_COMMAND: string[];
16
+ export interface RunSandboxArgumentPolicy {
17
+ /** Maximum argument count for program entries. Defaults to limits.maxArgs. */
18
+ maxCount?: number | undefined;
19
+ /** Regular expressions the first argument must match when present. */
20
+ allowPatterns?: string[] | undefined;
21
+ /** Regular expressions no argument may match. */
22
+ denyPatterns?: string[] | undefined;
23
+ }
24
+ export interface RunSandboxCommandEntry {
25
+ description?: string | undefined;
26
+ /** Fixed argv; may contain {file}, {mount}, and {output}. */
27
+ argv?: string[] | undefined;
28
+ /** Program the model may pass arguments to. */
29
+ program?: string | undefined;
30
+ args?: RunSandboxArgumentPolicy | undefined;
31
+ /** Globs the {file} argument must match. Defaults to every mount file. */
32
+ inputs?: string[] | undefined;
33
+ /** Workspace references the entry applies to. Defaults to all. */
34
+ workspaces?: string[] | undefined;
35
+ /** Effective binding modes the entry applies to. Defaults to both. */
36
+ modes?: WorkspaceMode[] | undefined;
37
+ timeoutMs?: number | undefined;
38
+ }
39
+ export interface RunSandboxShellPolicy {
40
+ enabled: boolean;
41
+ /** Interpreter argv; the command string is appended. */
42
+ program?: string[] | undefined;
43
+ timeoutMs?: number | undefined;
44
+ modes?: WorkspaceMode[] | undefined;
45
+ }
46
+ export interface RunSandboxLimits {
47
+ memoryMb: number;
48
+ cpuCount: number;
49
+ processLimit: number;
50
+ workspaceTmpfsMb: number;
51
+ commandTimeoutMs: number;
52
+ maxCommandTimeoutMs: number;
53
+ maxCommandsPerRun: number;
54
+ maxTotalSandboxSeconds: number;
55
+ maxStdoutBytes: number;
56
+ maxStderrBytes: number;
57
+ maxArgs: number;
58
+ maxArgBytes: number;
59
+ maxTotalStagedBytes: number;
60
+ maxOutputFiles: number;
61
+ maxOutputBytes: number;
62
+ }
63
+ export declare const DEFAULT_RUN_SANDBOX_LIMITS: RunSandboxLimits;
64
+ export interface RunSandboxPolicy {
65
+ commands: Record<string, RunSandboxCommandEntry>;
66
+ shell: RunSandboxShellPolicy;
67
+ limits: RunSandboxLimits;
68
+ }
69
+ export type RunSandboxLimitOverrides = {
70
+ [Key in keyof RunSandboxLimits]?: number | undefined;
71
+ };
72
+ export declare const resolveRunSandboxLimits: (partial?: RunSandboxLimitOverrides) => RunSandboxLimits;
73
+ export declare const resolveRunSandboxPolicy: (input: {
74
+ commands?: Record<string, RunSandboxCommandEntry> | undefined;
75
+ shell?: Partial<RunSandboxShellPolicy> | undefined;
76
+ limits?: RunSandboxLimitOverrides | undefined;
77
+ }) => RunSandboxPolicy;
78
+ export declare const validateRunSandboxPolicy: (policy: RunSandboxPolicy) => void;
79
+ export declare class SandboxPolicyError extends Error {
80
+ readonly code: string;
81
+ constructor(code: string, message: string);
82
+ }
83
+ /** Describe the bare (un-prefixed) tools a binding exposes after host policy. */
84
+ export declare const describeWorkspaceTools: (workspace: ResolvedWorkspace, policy: RunSandboxPolicy) => AgentTool[];
85
+ export interface AdmittedCommand {
86
+ kind: RunSandboxCommandRequest["kind"];
87
+ name: string;
88
+ policyEntry?: string;
89
+ argv: string[];
90
+ cwd: string;
91
+ timeoutMs: number;
92
+ /** Files to stage before execution (tool content, step code). */
93
+ stagedFiles: SandboxInputFile[];
94
+ /** Directory collected as artifacts after execution. */
95
+ outputDirectory: string;
96
+ /** Helper invocation flags that expect JSON output. */
97
+ expectsJson: boolean;
98
+ }
99
+ export interface AdmissionContext {
100
+ policy: RunSandboxPolicy;
101
+ workspace?: ResolvedWorkspace;
102
+ commandId: string;
103
+ helperCommand: readonly string[];
104
+ /** Runtime profile argv builder for code steps. */
105
+ codeProfile?: (language: string) => {
106
+ extension: string;
107
+ argv: (sourcePath: string) => string[];
108
+ } | undefined;
109
+ }
110
+ /**
111
+ * Decide whether a request may execute and, if so, the exact argv. Every
112
+ * argument the model supplied is validated here before it reaches a process.
113
+ */
114
+ export declare const admitCommand: (request: RunSandboxCommandRequest, context: AdmissionContext) => AdmittedCommand;