@saturn-universe/tools 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.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/container-sandbox.d.ts +168 -0
  3. package/dist/container-sandbox.js +1241 -0
  4. package/dist/counter.d.ts +5 -0
  5. package/dist/counter.js +82 -0
  6. package/dist/data-review.d.ts +4 -0
  7. package/dist/data-review.js +146 -0
  8. package/dist/execution-backend.d.ts +55 -0
  9. package/dist/execution-backend.js +339 -0
  10. package/dist/executor.d.ts +25 -0
  11. package/dist/executor.js +978 -0
  12. package/dist/file-window.d.ts +3 -0
  13. package/dist/file-window.js +12 -0
  14. package/dist/index.d.ts +27 -0
  15. package/dist/index.js +17 -0
  16. package/dist/mcp-headers.d.ts +3 -0
  17. package/dist/mcp-headers.js +51 -0
  18. package/dist/mcp-http.d.ts +3 -0
  19. package/dist/mcp-http.js +253 -0
  20. package/dist/mcp-stdio.d.ts +2 -0
  21. package/dist/mcp-stdio.js +147 -0
  22. package/dist/mcp-wire.d.ts +33 -0
  23. package/dist/mcp-wire.js +85 -0
  24. package/dist/mcp.d.ts +19 -0
  25. package/dist/mcp.js +325 -0
  26. package/dist/path-containment.d.ts +3 -0
  27. package/dist/path-containment.js +11 -0
  28. package/dist/planner.d.ts +3 -0
  29. package/dist/planner.js +162 -0
  30. package/dist/process-manager.d.ts +67 -0
  31. package/dist/process-manager.js +423 -0
  32. package/dist/process-output.d.ts +34 -0
  33. package/dist/process-output.js +162 -0
  34. package/dist/process-worker.d.ts +1 -0
  35. package/dist/process-worker.js +202 -0
  36. package/dist/registry.d.ts +33 -0
  37. package/dist/registry.js +227 -0
  38. package/dist/search.d.ts +9 -0
  39. package/dist/search.js +96 -0
  40. package/dist/team.d.ts +36 -0
  41. package/dist/team.js +284 -0
  42. package/dist/text-patch.d.ts +15 -0
  43. package/dist/text-patch.js +81 -0
  44. package/dist/todo.d.ts +3 -0
  45. package/dist/todo.js +105 -0
  46. package/dist/workspace-discovery.d.ts +42 -0
  47. package/dist/workspace-discovery.js +404 -0
  48. package/dist/workspace-snapshot.d.ts +28 -0
  49. package/dist/workspace-snapshot.js +371 -0
  50. package/dist/workspace.d.ts +22 -0
  51. package/dist/workspace.js +1819 -0
  52. package/package.json +16 -3
  53. package/README.md +0 -3
@@ -0,0 +1,1241 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { RuntimeError } from '@saturn-universe/core';
5
+ import { terminateProcessTree } from './execution-backend.js';
6
+ import { relativePathWithin } from './path-containment.js';
7
+ const DOCKER_SOCK_PATTERN = /docker\.sock(?:$|[\\/])/i;
8
+ export const DEFAULT_ALLOWED_TARGET_CAPABILITIES = ['SYS_CHROOT'];
9
+ const DENIED_TARGET_CAPABILITIES = new Set([
10
+ 'ALL',
11
+ 'SYS_ADMIN',
12
+ 'NET_ADMIN',
13
+ 'SYS_MODULE',
14
+ 'SYS_RAWIO',
15
+ 'SYS_BOOT',
16
+ 'MAC_ADMIN',
17
+ 'MAC_OVERRIDE',
18
+ 'BPF',
19
+ 'PERFMON',
20
+ 'DAC_OVERRIDE',
21
+ 'DAC_READ_SEARCH',
22
+ 'SETUID',
23
+ 'SETGID',
24
+ 'MKNOD',
25
+ 'NET_RAW',
26
+ 'SYS_PTRACE',
27
+ ]);
28
+ const FORBIDDEN_TARGET_SEED_PREFIXES = [
29
+ '/proc',
30
+ '/sys',
31
+ '/dev',
32
+ '/etc',
33
+ '/bin',
34
+ '/sbin',
35
+ '/usr',
36
+ '/lib',
37
+ '/lib64',
38
+ '/boot',
39
+ '/run',
40
+ '/var/run',
41
+ '/workspace',
42
+ ];
43
+ export const CONTAINER_PROCESS_LAUNCH_SCRIPT = [
44
+ 'pidfile="$1"',
45
+ 'shift',
46
+ 'printf \'%s\\n\' "$$" > "$pidfile"',
47
+ 'if command -v setsid >/dev/null 2>&1 && ! kill -0 "-$$" 2>/dev/null; then',
48
+ ' exec setsid "$@"',
49
+ 'fi',
50
+ 'exec "$@"',
51
+ ].join('\n');
52
+ export const CONTAINER_PROCESS_STOP_SCRIPT = [
53
+ 'pidfile="$1"',
54
+ 'token="$2"',
55
+ 'pgid=""',
56
+ 'if [ -r "$pidfile" ]; then',
57
+ ' IFS= read -r pgid < "$pidfile" || true',
58
+ 'fi',
59
+ 'case "$pgid" in',
60
+ ' \'\'|*[!0-9]*) pgid="" ;;',
61
+ 'esac',
62
+ 'is_pid_alive() {',
63
+ ' p="$1"',
64
+ ' [ -n "$p" ] && kill -0 "$p" 2>/dev/null || return 1',
65
+ ' if [ -r "/proc/$p/stat" ]; then',
66
+ ' st=$(cat "/proc/$p/stat" 2>/dev/null || true)',
67
+ ' case "$st" in',
68
+ " *') Z '*|*') X '*) return 1 ;;",
69
+ ' esac',
70
+ ' fi',
71
+ ' return 0',
72
+ '}',
73
+ 'list_token_pids() {',
74
+ ' [ -n "$token" ] || return 0',
75
+ ' for envf in /proc/[0-9]*/environ; do',
76
+ ' [ -r "$envf" ] || continue',
77
+ ' p=${envf#/proc/}',
78
+ ' p=${p%/environ}',
79
+ ' [ "$p" = "$$" ] || [ "$p" = "1" ] && continue',
80
+ ' if tr \'\\0\' \'\\n\' < "$envf" 2>/dev/null | grep -Fx "SATURN_PROCESS_TOKEN=$token" >/dev/null 2>&1; then',
81
+ ' if is_pid_alive "$p"; then',
82
+ ' printf \'%s\\n\' "$p"',
83
+ ' fi',
84
+ ' fi',
85
+ ' done',
86
+ '}',
87
+ 'pgrp_alive() {',
88
+ ' [ -n "$pgid" ] && [ "$pgid" -gt 1 ] 2>/dev/null || return 1',
89
+ ' if kill -0 "-$pgid" 2>/dev/null; then',
90
+ ' if [ -r "/proc/$pgid/stat" ]; then',
91
+ ' st=$(cat "/proc/$pgid/stat" 2>/dev/null || true)',
92
+ ' case "$st" in',
93
+ " *') Z '*|*') X '*)",
94
+ ' for sf in /proc/[0-9]*/stat; do',
95
+ ' [ -r "$sf" ] || continue',
96
+ ' p=${sf#/proc/}',
97
+ ' p=${p%/stat}',
98
+ ' [ "$p" = "$$" ] || [ "$p" = "$pgid" ] && continue',
99
+ ' s=$(cat "$sf" 2>/dev/null || true)',
100
+ ' rest=${s#*) }',
101
+ ' set -- $rest 2>/dev/null || continue',
102
+ ' [ "$1" = "Z" ] || [ "$1" = "X" ] && continue',
103
+ ' [ "$3" = "$pgid" ] && return 0',
104
+ ' done',
105
+ ' return 1',
106
+ ' ;;',
107
+ ' esac',
108
+ ' fi',
109
+ ' return 0',
110
+ ' fi',
111
+ ' is_pid_alive "$pgid"',
112
+ '}',
113
+ 'alive() {',
114
+ ' if pgrp_alive; then',
115
+ ' return 0',
116
+ ' fi',
117
+ ' [ -n "$(list_token_pids)" ]',
118
+ '}',
119
+ 'signal_all() {',
120
+ ' sig="$1"',
121
+ ' if [ -n "$pgid" ] && [ "$pgid" -gt 1 ] 2>/dev/null; then',
122
+ ' kill "-$sig" "-$pgid" 2>/dev/null || true',
123
+ ' kill "-$sig" "$pgid" 2>/dev/null || true',
124
+ ' fi',
125
+ ' for p in $(list_token_pids); do',
126
+ ' kill "-$sig" "$p" 2>/dev/null || true',
127
+ ' done',
128
+ '}',
129
+ 'if alive; then',
130
+ ' signal_all TERM',
131
+ ' i=0',
132
+ ' while [ "$i" -lt 10 ] && alive; do',
133
+ ' sleep 0.05 2>/dev/null || sleep 1',
134
+ ' i=$((i + 1))',
135
+ ' done',
136
+ ' if alive; then',
137
+ ' signal_all KILL',
138
+ ' i=0',
139
+ ' while [ "$i" -lt 20 ] && alive; do',
140
+ ' sleep 0.05 2>/dev/null || sleep 1',
141
+ ' i=$((i + 1))',
142
+ ' done',
143
+ ' fi',
144
+ 'fi',
145
+ 'rm -f "$pidfile" 2>/dev/null || true',
146
+ 'if alive; then',
147
+ ' exit 1',
148
+ 'fi',
149
+ 'exit 0',
150
+ ].join('\n');
151
+ function assertValidImageName(image) {
152
+ const trimmed = image.trim();
153
+ if (!trimmed || /[\0\r\n\s]/.test(trimmed)) {
154
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Invalid sandbox image name: "${image}"`);
155
+ }
156
+ }
157
+ function assertNoDockerSock(hostPath, containerPath) {
158
+ if (DOCKER_SOCK_PATTERN.test(hostPath) || DOCKER_SOCK_PATTERN.test(containerPath)) {
159
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Mounting docker.sock inside a sandbox is forbidden');
160
+ }
161
+ }
162
+ const FORBIDDEN_HOST_MOUNT_PREFIXES = [
163
+ '/etc',
164
+ '/proc',
165
+ '/sys',
166
+ '/dev',
167
+ '/var/run',
168
+ '/run',
169
+ '/boot',
170
+ '/root',
171
+ '/workspace',
172
+ ];
173
+ export function normalizeReadonlyContainerPath(containerPath) {
174
+ if (!containerPath || /[\0\r\n\\]/.test(containerPath)) {
175
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid readonly mount container path');
176
+ }
177
+ if (containerPath.split('/').includes('..')) {
178
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Readonly mount containerPath cannot contain "..": "${containerPath}"`);
179
+ }
180
+ const normalized = path.posix.normalize(containerPath);
181
+ if (!normalized.startsWith('/readonly/') || normalized === '/readonly/' || normalized.includes('/../')) {
182
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Readonly mount containerPath must reside under /readonly/: "${containerPath}"`);
183
+ }
184
+ return normalized;
185
+ }
186
+ export function validateReadonlyMount(mount) {
187
+ const hostRaw = typeof mount.hostPath === 'string' ? mount.hostPath.trim() : '';
188
+ const containerRaw = typeof mount.containerPath === 'string' ? mount.containerPath.trim() : '';
189
+ if (!hostRaw || /[\0\r\n]/.test(hostRaw)) {
190
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid readonly mount host path');
191
+ }
192
+ if (hostRaw.split(/[\\/]/).includes('..')) {
193
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Readonly mount hostPath cannot contain "..": "${mount.hostPath}"`);
194
+ }
195
+ assertNoDockerSock(hostRaw, containerRaw);
196
+ const normalizedPosixHost = path.posix.normalize(hostRaw.replaceAll('\\', '/'));
197
+ const normalizedLower = normalizedPosixHost.replace(/\/+$/, '').toLowerCase() || '/';
198
+ if (normalizedLower === '/' || /^[a-z]:$/.test(normalizedLower)) {
199
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Readonly mount cannot expose filesystem root: "${mount.hostPath}"`);
200
+ }
201
+ for (const prefix of FORBIDDEN_HOST_MOUNT_PREFIXES) {
202
+ if (normalizedLower === prefix || normalizedLower.startsWith(`${prefix}/`)) {
203
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Readonly mount cannot expose protected host path "${prefix}": "${mount.hostPath}"`);
204
+ }
205
+ }
206
+ const segments = normalizedLower.split('/').filter(Boolean);
207
+ if (segments.some((part) => part === '.saturn' || part === '.env' || part.startsWith('.env.'))) {
208
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Readonly mount cannot expose protected host paths: "${mount.hostPath}"`);
209
+ }
210
+ return {
211
+ hostPath: mount.hostPath,
212
+ containerPath: normalizeReadonlyContainerPath(containerRaw),
213
+ };
214
+ }
215
+ export function validateTargetName(rawName) {
216
+ const trimmed = (rawName ?? 'target').trim();
217
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(trimmed)) {
218
+ throw new RuntimeError('SANDBOX_TARGET_NAME_INVALID', `Invalid target name "${rawName ?? ''}": must match ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$`);
219
+ }
220
+ return trimmed.toLowerCase();
221
+ }
222
+ export function validateTargetCapabilities(requested, allowed = DEFAULT_ALLOWED_TARGET_CAPABILITIES) {
223
+ if (!requested || requested.length === 0)
224
+ return [];
225
+ const allowedSet = new Set(allowed.map((cap) => cap.trim().toUpperCase()));
226
+ const validated = [];
227
+ const seen = new Set();
228
+ for (const rawCap of requested) {
229
+ const cap = rawCap.trim().toUpperCase();
230
+ if (!/^[A-Z0-9_]+$/.test(cap)) {
231
+ throw new RuntimeError('SANDBOX_TARGET_CAPABILITY_DENIED', `Invalid Linux capability: "${rawCap}"`);
232
+ }
233
+ if (DENIED_TARGET_CAPABILITIES.has(cap) || !allowedSet.has(cap)) {
234
+ throw new RuntimeError('SANDBOX_TARGET_CAPABILITY_DENIED', `Capability "${cap}" is not permitted for target containers (allowed: ${[...allowedSet].join(', ') || 'none'})`);
235
+ }
236
+ if (!seen.has(cap)) {
237
+ seen.add(cap);
238
+ validated.push(cap);
239
+ }
240
+ }
241
+ return validated;
242
+ }
243
+ export function validateTargetSeedFilePath(containerPath) {
244
+ if (typeof containerPath !== 'string' ||
245
+ !containerPath ||
246
+ /[\0\r\n\\]/.test(containerPath) ||
247
+ !containerPath.startsWith('/')) {
248
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file container path must be an absolute POSIX path: "${String(containerPath)}"`);
249
+ }
250
+ const rawSegments = containerPath.split('/');
251
+ if (rawSegments.includes('..')) {
252
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file container path cannot contain "..": "${containerPath}"`);
253
+ }
254
+ if (containerPath.endsWith('/')) {
255
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file container path must point to a file, not a directory: "${containerPath}"`);
256
+ }
257
+ const normalized = path.posix.normalize(containerPath);
258
+ if (normalized === '/' || normalized.endsWith('/')) {
259
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file container path cannot target "/": "${containerPath}"`);
260
+ }
261
+ assertNoDockerSock(normalized, normalized);
262
+ for (const prefix of FORBIDDEN_TARGET_SEED_PREFIXES) {
263
+ if (normalized === prefix || normalized.startsWith(`${prefix}/`)) {
264
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file container path cannot target protected directory "${prefix}": "${containerPath}"`);
265
+ }
266
+ }
267
+ return normalized;
268
+ }
269
+ export function buildTargetDockerRunArgs(spec) {
270
+ assertValidImageName(spec.image);
271
+ if (!spec.workDirHost || spec.workDirHost.includes('\0')) {
272
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid target host work directory');
273
+ }
274
+ const workDirContainer = path.posix.normalize(spec.workDirContainer || '/workspace');
275
+ if (!workDirContainer.startsWith('/') || workDirContainer.includes('\0')) {
276
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid target container work directory');
277
+ }
278
+ assertNoDockerSock(spec.workDirHost, workDirContainer);
279
+ const networkName = spec.networkName?.trim();
280
+ if (!networkName ||
281
+ !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(networkName) ||
282
+ networkName === 'host' ||
283
+ networkName === 'bridge' ||
284
+ networkName === 'none') {
285
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Target container requires an isolated internal network name, got: "${spec.networkName}"`);
286
+ }
287
+ const alias = validateTargetName(spec.networkAlias);
288
+ const targetName = validateTargetName(spec.targetName);
289
+ if (typeof spec.command !== 'string' || !spec.command.trim() || spec.command.includes('\0')) {
290
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid target container startup command');
291
+ }
292
+ const validatedCaps = validateTargetCapabilities(spec.capAdd, spec.allowedCapabilities ?? DEFAULT_ALLOWED_TARGET_CAPABILITIES);
293
+ const args = ['run', '-d', '--init', '--name', spec.name];
294
+ if (spec.backend === 'gvisor')
295
+ args.push('--runtime=runsc');
296
+ else if (spec.backend === 'sysbox')
297
+ args.push('--runtime=sysbox-runc');
298
+ args.push('--cap-drop=ALL', '--security-opt=no-new-privileges');
299
+ for (const cap of validatedCaps) {
300
+ args.push(`--cap-add=${cap}`);
301
+ }
302
+ if (spec.backend !== 'sysbox') {
303
+ if (validatedCaps.length > 0) {
304
+ // Run as uid 0:0 when allowlisted capabilities are granted so non-root image defaults keep CapEff.
305
+ args.push('--user', '0:0');
306
+ }
307
+ else if (spec.user) {
308
+ args.push('--user', spec.user);
309
+ }
310
+ }
311
+ args.push(`--network=${networkName}`, `--network-alias=${alias}`);
312
+ if (spec.resources?.cpus !== undefined)
313
+ args.push(`--cpus=${spec.resources.cpus}`);
314
+ if (spec.resources?.memoryMb !== undefined)
315
+ args.push(`--memory=${spec.resources.memoryMb}m`);
316
+ if (spec.resources?.pidsLimit !== undefined)
317
+ args.push(`--pids-limit=${spec.resources.pidsLimit}`);
318
+ const tmpfsMb = spec.tmpfsSizeMb ?? 512;
319
+ args.push('--tmpfs', `/tmp:rw,noexec,nosuid,size=${tmpfsMb}m`);
320
+ args.push('--label', 'saturn.managed=true', '--label', 'saturn.role=target', '--label', `saturn.workspace=${spec.workspaceHash}`, '--label', `saturn.run=${spec.runId}`, '--label', `saturn.run_id=${spec.runId}`, '--label', `saturn.target=${targetName}`);
321
+ for (const [k, v] of Object.entries(spec.extraLabels ?? {})) {
322
+ args.push('--label', `${k}=${v}`);
323
+ }
324
+ args.push('-v', `${spec.workDirHost}:${workDirContainer}:rw`);
325
+ for (const mount of spec.seedMounts ?? []) {
326
+ assertNoDockerSock(mount.hostPath, mount.containerPath);
327
+ const safePath = validateTargetSeedFilePath(mount.containerPath);
328
+ args.push('-v', `${mount.hostPath}:${safePath}:ro`);
329
+ }
330
+ args.push('-w', workDirContainer);
331
+ args.push('-e', 'HOME=/tmp', '-e', 'TERM=xterm-256color', '-e', 'SATURN_SANDBOX_TARGET=1');
332
+ args.push(spec.image, '/bin/sh', '-c', spec.command);
333
+ if (args.includes('--privileged')) {
334
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Privileged target containers are forbidden');
335
+ }
336
+ return args;
337
+ }
338
+ export function buildDockerRunArgs(spec) {
339
+ assertValidImageName(spec.image);
340
+ if (!spec.workDirHost || spec.workDirHost.includes('\0')) {
341
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid sandbox host work directory');
342
+ }
343
+ const workDirContainer = path.posix.normalize(spec.workDirContainer || '/workspace');
344
+ if (!workDirContainer.startsWith('/') || workDirContainer.includes('\0')) {
345
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Invalid sandbox container work directory');
346
+ }
347
+ assertNoDockerSock(spec.workDirHost, workDirContainer);
348
+ const args = ['run', '-d', '--init', '--name', spec.name];
349
+ if (spec.backend === 'gvisor')
350
+ args.push('--runtime=runsc');
351
+ else if (spec.backend === 'sysbox')
352
+ args.push('--runtime=sysbox-runc');
353
+ args.push('--cap-drop=ALL', '--security-opt=no-new-privileges');
354
+ for (const cap of spec.capAdd ?? []) {
355
+ if (!/^[A-Z0-9_]+$/.test(cap)) {
356
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Invalid Linux capability: "${cap}"`);
357
+ }
358
+ args.push(`--cap-add=${cap}`);
359
+ }
360
+ if (spec.user && spec.backend !== 'sysbox') {
361
+ args.push('--user', spec.user);
362
+ }
363
+ if (spec.network === 'none') {
364
+ args.push('--network=none');
365
+ }
366
+ else if (spec.network === 'bridge') {
367
+ args.push('--network=bridge');
368
+ }
369
+ else if (spec.network === 'internal') {
370
+ args.push(`--network=${spec.networkName?.trim() || 'bridge'}`);
371
+ }
372
+ else if (spec.network === 'proxy') {
373
+ args.push(`--network=${spec.networkName?.trim() || 'bridge'}`);
374
+ if (spec.proxyUrl?.trim()) {
375
+ args.push('-e', `HTTP_PROXY=${spec.proxyUrl.trim()}`, '-e', `HTTPS_PROXY=${spec.proxyUrl.trim()}`);
376
+ }
377
+ }
378
+ if (spec.kvm === true) {
379
+ args.push('--device', '/dev/kvm');
380
+ }
381
+ if (spec.resources?.cpus !== undefined)
382
+ args.push(`--cpus=${spec.resources.cpus}`);
383
+ if (spec.resources?.memoryMb !== undefined)
384
+ args.push(`--memory=${spec.resources.memoryMb}m`);
385
+ if (spec.resources?.pidsLimit !== undefined)
386
+ args.push(`--pids-limit=${spec.resources.pidsLimit}`);
387
+ const tmpfsMb = spec.tmpfsSizeMb ?? 512;
388
+ args.push('--tmpfs', `/tmp:rw,noexec,nosuid,size=${tmpfsMb}m`);
389
+ args.push('--label', 'saturn.managed=true', '--label', `saturn.workspace=${spec.workspaceHash}`, '--label', `saturn.run=${spec.runId}`, '--label', `saturn.member=${spec.memberId}`);
390
+ for (const [k, v] of Object.entries(spec.extraLabels ?? {})) {
391
+ args.push('--label', `${k}=${v}`);
392
+ }
393
+ args.push('-v', `${spec.workDirHost}:${workDirContainer}:${spec.workDirReadOnly ? 'ro' : 'rw'}`);
394
+ for (const rawMount of spec.readonlyMounts ?? []) {
395
+ const mount = validateReadonlyMount(rawMount);
396
+ args.push('-v', `${mount.hostPath}:${mount.containerPath}:ro`);
397
+ }
398
+ args.push('-w', workDirContainer);
399
+ args.push('-e', 'HOME=/tmp', '-e', 'TERM=xterm-256color', '-e', 'SATURN_SANDBOX=1');
400
+ args.push(spec.image, '/bin/sh', '-c', 'trap "exit 0" TERM INT; while :; do sleep 3600; done');
401
+ if (args.includes('--privileged')) {
402
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', 'Privileged sandbox containers are forbidden');
403
+ }
404
+ return args;
405
+ }
406
+ export function dockerClientEnvironment(base = process.env) {
407
+ const env = {};
408
+ for (const key of [
409
+ 'SystemRoot',
410
+ 'WINDIR',
411
+ 'TEMP',
412
+ 'TMP',
413
+ 'TMPDIR',
414
+ 'HOME',
415
+ 'USERPROFILE',
416
+ 'DOCKER_HOST',
417
+ 'DOCKER_CONTEXT',
418
+ 'DOCKER_CONFIG',
419
+ 'DOCKER_TLS_VERIFY',
420
+ 'DOCKER_CERT_PATH',
421
+ 'LANG',
422
+ 'ComSpec',
423
+ ]) {
424
+ if (base[key] !== undefined)
425
+ env[key] = base[key];
426
+ }
427
+ const pathVal = base.PATH ?? base.Path;
428
+ if (pathVal !== undefined)
429
+ env.PATH = pathVal;
430
+ return env;
431
+ }
432
+ async function runSimpleCli(binary, args, timeoutMs = 15_000, signal) {
433
+ return new Promise((resolve) => {
434
+ let settled = false;
435
+ let child;
436
+ try {
437
+ child = spawn(binary, [...args], {
438
+ env: dockerClientEnvironment(),
439
+ shell: false,
440
+ windowsHide: true,
441
+ stdio: ['ignore', 'pipe', 'pipe'],
442
+ });
443
+ }
444
+ catch (error) {
445
+ resolve({
446
+ exitCode: null,
447
+ stdout: '',
448
+ stderr: '',
449
+ error: error instanceof Error ? error : new Error(String(error)),
450
+ });
451
+ return;
452
+ }
453
+ const out = [];
454
+ const err = [];
455
+ const finish = (result) => {
456
+ if (settled)
457
+ return;
458
+ settled = true;
459
+ clearTimeout(timer);
460
+ signal?.removeEventListener('abort', onAbort);
461
+ resolve({
462
+ exitCode: result.exitCode,
463
+ stdout: Buffer.concat(out).toString('utf8'),
464
+ stderr: Buffer.concat(err).toString('utf8'),
465
+ ...(result.error ? { error: result.error } : {}),
466
+ });
467
+ };
468
+ const onAbort = () => {
469
+ child.kill('SIGKILL');
470
+ finish({ exitCode: null, error: new Error('Aborted') });
471
+ };
472
+ const timer = setTimeout(() => {
473
+ child.kill('SIGKILL');
474
+ finish({ exitCode: null, error: new Error('Command timed out') });
475
+ }, timeoutMs);
476
+ signal?.addEventListener('abort', onAbort, { once: true });
477
+ child.stdout?.on('data', (chunk) => out.push(chunk));
478
+ child.stderr?.on('data', (chunk) => err.push(chunk));
479
+ child.once('error', (error) => finish({ exitCode: null, error }));
480
+ child.once('close', (code) => finish({ exitCode: code }));
481
+ });
482
+ }
483
+ async function captureCombinedCli(binary, args, maxBytes = 16_384, timeoutMs = 10_000) {
484
+ return new Promise((resolve) => {
485
+ let settled = false;
486
+ let truncated = false;
487
+ let total = 0;
488
+ const chunks = [];
489
+ let child;
490
+ try {
491
+ child = spawn(binary, [...args], {
492
+ env: dockerClientEnvironment(),
493
+ shell: false,
494
+ windowsHide: true,
495
+ stdio: ['ignore', 'pipe', 'pipe'],
496
+ });
497
+ }
498
+ catch (error) {
499
+ resolve({
500
+ exitCode: null,
501
+ combined: '',
502
+ truncated: false,
503
+ error: error instanceof Error ? error : new Error(String(error)),
504
+ });
505
+ return;
506
+ }
507
+ const finish = (exitCode, error) => {
508
+ if (settled)
509
+ return;
510
+ settled = true;
511
+ clearTimeout(timer);
512
+ const buf = Buffer.concat(chunks);
513
+ resolve({
514
+ exitCode,
515
+ combined: (buf.length > maxBytes ? buf.subarray(0, maxBytes) : buf).toString('utf8'),
516
+ truncated: truncated || buf.length > maxBytes,
517
+ ...(error ? { error } : {}),
518
+ });
519
+ };
520
+ const appendChunk = (chunk) => {
521
+ if (total >= maxBytes) {
522
+ truncated = true;
523
+ child.kill('SIGKILL');
524
+ return;
525
+ }
526
+ const remaining = maxBytes - total;
527
+ if (chunk.length > remaining) {
528
+ chunks.push(chunk.subarray(0, remaining));
529
+ total += remaining;
530
+ truncated = true;
531
+ child.kill('SIGKILL');
532
+ }
533
+ else {
534
+ chunks.push(chunk);
535
+ total += chunk.length;
536
+ }
537
+ };
538
+ const timer = setTimeout(() => {
539
+ child.kill('SIGKILL');
540
+ finish(null, new Error('Command timed out'));
541
+ }, timeoutMs);
542
+ child.stdout?.on('data', appendChunk);
543
+ child.stderr?.on('data', appendChunk);
544
+ child.once('error', (error) => finish(null, error));
545
+ child.once('close', (code) => finish(code));
546
+ });
547
+ }
548
+ export function createDockerContainerRunner(dockerBinary = 'docker') {
549
+ return {
550
+ async checkRuntime(backend) {
551
+ const info = await runSimpleCli(dockerBinary, ['info', '--format', '{{json .}}'], 10_000);
552
+ if (info.error || info.exitCode !== 0) {
553
+ const detail = info.stderr.trim() || info.error?.message || `exit ${info.exitCode}`;
554
+ return { ok: false, reason: `Docker daemon unavailable: ${detail}` };
555
+ }
556
+ if (backend === 'gvisor' || backend === 'sysbox') {
557
+ const expectedRuntime = backend === 'gvisor' ? 'runsc' : 'sysbox-runc';
558
+ try {
559
+ const parsed = JSON.parse(info.stdout);
560
+ if (!parsed.Runtimes || !Object.hasOwn(parsed.Runtimes, expectedRuntime)) {
561
+ return {
562
+ ok: false,
563
+ reason: `Required runtime "${expectedRuntime}" is not registered in Docker info`,
564
+ };
565
+ }
566
+ }
567
+ catch {
568
+ return {
569
+ ok: false,
570
+ reason: `Could not verify Docker runtime "${expectedRuntime}" from docker info`,
571
+ };
572
+ }
573
+ }
574
+ return { ok: true };
575
+ },
576
+ async hasImage(image) {
577
+ const inspect = await runSimpleCli(dockerBinary, ['image', 'inspect', image], 10_000);
578
+ return !inspect.error && inspect.exitCode === 0;
579
+ },
580
+ async listManagedContainers(labels) {
581
+ const args = ['ps', '-a'];
582
+ for (const [key, value] of Object.entries(labels)) {
583
+ args.push('--filter', `label=${key}=${value}`);
584
+ }
585
+ args.push('--format', '{{json .}}');
586
+ const res = await runSimpleCli(dockerBinary, args, 10_000);
587
+ if (res.error || res.exitCode !== 0)
588
+ return [];
589
+ const containers = [];
590
+ for (const line of res.stdout.split(/\r?\n/)) {
591
+ const trimmed = line.trim();
592
+ if (!trimmed)
593
+ continue;
594
+ try {
595
+ const parsed = JSON.parse(trimmed);
596
+ const labelMap = {};
597
+ for (const pair of (parsed.Labels ?? '').split(',')) {
598
+ const eq = pair.indexOf('=');
599
+ if (eq > 0)
600
+ labelMap[pair.slice(0, eq)] = pair.slice(eq + 1);
601
+ }
602
+ if (parsed.ID) {
603
+ containers.push({
604
+ id: parsed.ID,
605
+ name: parsed.Names ?? parsed.ID,
606
+ labels: labelMap,
607
+ });
608
+ }
609
+ }
610
+ catch {
611
+ // Ignore malformed output line
612
+ }
613
+ }
614
+ return containers;
615
+ },
616
+ async startContainer(spec) {
617
+ const args = buildDockerRunArgs(spec);
618
+ const res = await runSimpleCli(dockerBinary, args, 30_000);
619
+ if (res.error || res.exitCode !== 0) {
620
+ const msg = res.stderr.trim() || res.error?.message || `docker run exited ${res.exitCode}`;
621
+ throw new RuntimeError('SANDBOX_START_FAILED', `Failed to start sandbox container: ${msg}`);
622
+ }
623
+ const containerId = res.stdout.trim().split(/\r?\n/)[0]?.trim();
624
+ if (!containerId) {
625
+ throw new RuntimeError('SANDBOX_START_FAILED', 'docker run returned no container ID');
626
+ }
627
+ return { containerId };
628
+ },
629
+ async execInContainer(options) {
630
+ options.signal.throwIfAborted();
631
+ const execArgs = [
632
+ 'exec',
633
+ ...(options.stdin !== undefined ? ['-i'] : []),
634
+ '-w',
635
+ options.workdir,
636
+ options.containerId,
637
+ ...options.command,
638
+ ];
639
+ let child;
640
+ try {
641
+ child = spawn(dockerBinary, execArgs, {
642
+ env: dockerClientEnvironment(),
643
+ shell: false,
644
+ windowsHide: true,
645
+ detached: process.platform !== 'win32',
646
+ stdio: options.stdin !== undefined ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'],
647
+ });
648
+ }
649
+ catch (error) {
650
+ return {
651
+ launched: false,
652
+ exitCode: null,
653
+ signal: null,
654
+ startError: error instanceof Error ? error.message : String(error),
655
+ };
656
+ }
657
+ return new Promise((resolve) => {
658
+ let launched = false;
659
+ let settled = false;
660
+ let stopping = false;
661
+ let closed = false;
662
+ let pendingWrite = Promise.resolve();
663
+ const finish = async (result) => {
664
+ if (settled)
665
+ return;
666
+ settled = true;
667
+ clearTimeout(timer);
668
+ options.signal.removeEventListener('abort', stop);
669
+ await pendingWrite;
670
+ resolve(result);
671
+ };
672
+ const collect = (fn) => (chunk) => {
673
+ pendingWrite = pendingWrite.then(async () => {
674
+ await fn(chunk);
675
+ if (options.shouldStop?.())
676
+ stop();
677
+ });
678
+ };
679
+ const stop = () => {
680
+ if (stopping || settled)
681
+ return;
682
+ stopping = true;
683
+ void (async () => {
684
+ const confirmed = await terminateProcessTree(child.pid, dockerBinary);
685
+ if (!confirmed && child.exitCode === null && child.signalCode === null)
686
+ child.kill('SIGKILL');
687
+ for (let i = 0; i < 30 && !closed; i++)
688
+ await new Promise((done) => setTimeout(done, 10));
689
+ const treeConfirmed = confirmed && (child.exitCode !== null || child.signalCode !== null);
690
+ child.stdin?.destroy();
691
+ child.stdout?.destroy();
692
+ child.stderr?.destroy();
693
+ const cancelled = options.signal.aborted &&
694
+ options.signal.reason?.name !== 'TimeoutError';
695
+ void finish({
696
+ launched,
697
+ exitCode: child.exitCode,
698
+ signal: child.signalCode,
699
+ timedOut: !cancelled,
700
+ cancelled,
701
+ terminationConfirmed: treeConfirmed,
702
+ });
703
+ })();
704
+ };
705
+ const timer = setTimeout(stop, options.timeoutMs);
706
+ options.signal.addEventListener('abort', stop, { once: true });
707
+ child.stdin?.on('error', () => { });
708
+ child.stdout?.on('data', collect(options.onStdout));
709
+ child.stderr?.on('data', collect(options.onStderr));
710
+ child.once('spawn', () => {
711
+ launched = true;
712
+ if (options.stdin !== undefined && child.stdin && !child.stdin.destroyed) {
713
+ child.stdin.end(options.stdin, 'utf8');
714
+ }
715
+ });
716
+ child.on('error', (error) => {
717
+ if (!launched) {
718
+ void finish({
719
+ launched: false,
720
+ exitCode: null,
721
+ signal: null,
722
+ startError: error.message,
723
+ });
724
+ }
725
+ });
726
+ child.once('close', (code, exitSignal) => {
727
+ closed = true;
728
+ if (!launched || stopping)
729
+ return;
730
+ void finish({
731
+ launched: true,
732
+ exitCode: code,
733
+ signal: exitSignal,
734
+ });
735
+ });
736
+ });
737
+ },
738
+ async execCaptureBuffer(containerId, command, options = {}) {
739
+ const maxBytes = options.maxBytes ?? 64 * 1024;
740
+ const timeoutMs = options.timeoutMs ?? 10_000;
741
+ const args = ['exec', ...(options.workdir ? ['-w', options.workdir] : []), containerId, ...command];
742
+ return new Promise((resolve, reject) => {
743
+ let settled = false;
744
+ let truncated = false;
745
+ let total = 0;
746
+ const out = [];
747
+ const err = [];
748
+ const child = spawn(dockerBinary, args, {
749
+ env: dockerClientEnvironment(),
750
+ shell: false,
751
+ windowsHide: true,
752
+ stdio: ['ignore', 'pipe', 'pipe'],
753
+ });
754
+ const finish = (code) => {
755
+ if (settled)
756
+ return;
757
+ settled = true;
758
+ clearTimeout(timer);
759
+ options.signal?.removeEventListener('abort', onAbort);
760
+ const buf = Buffer.concat(out);
761
+ resolve({
762
+ exitCode: code,
763
+ stdout: buf.length > maxBytes ? buf.subarray(0, maxBytes) : buf,
764
+ stderr: Buffer.concat(err),
765
+ truncated: truncated || buf.length > maxBytes,
766
+ });
767
+ };
768
+ const onAbort = () => {
769
+ child.kill('SIGKILL');
770
+ if (!settled) {
771
+ settled = true;
772
+ clearTimeout(timer);
773
+ reject(options.signal?.reason ?? new Error('Aborted'));
774
+ }
775
+ };
776
+ const timer = setTimeout(() => {
777
+ child.kill('SIGKILL');
778
+ finish(null);
779
+ }, timeoutMs);
780
+ options.signal?.addEventListener('abort', onAbort, { once: true });
781
+ child.stdout?.on('data', (chunk) => {
782
+ if (total >= maxBytes) {
783
+ truncated = true;
784
+ child.kill('SIGKILL');
785
+ return;
786
+ }
787
+ const remaining = maxBytes - total;
788
+ if (chunk.length > remaining) {
789
+ out.push(chunk.subarray(0, remaining));
790
+ total += remaining;
791
+ truncated = true;
792
+ child.kill('SIGKILL');
793
+ }
794
+ else {
795
+ out.push(chunk);
796
+ total += chunk.length;
797
+ }
798
+ });
799
+ child.stderr?.on('data', (chunk) => {
800
+ if (err.reduce((s, b) => s + b.length, 0) < 8192)
801
+ err.push(chunk);
802
+ });
803
+ child.once('error', (error) => {
804
+ if (!settled) {
805
+ settled = true;
806
+ clearTimeout(timer);
807
+ options.signal?.removeEventListener('abort', onAbort);
808
+ reject(error);
809
+ }
810
+ });
811
+ child.once('close', (code) => finish(code));
812
+ });
813
+ },
814
+ spawnExec(containerId, command, workdir, signal) {
815
+ return spawn(dockerBinary, ['exec', '-w', workdir, containerId, ...command], {
816
+ env: dockerClientEnvironment(),
817
+ shell: false,
818
+ windowsHide: true,
819
+ signal,
820
+ stdio: ['ignore', 'pipe', 'pipe'],
821
+ });
822
+ },
823
+ async removeContainer(containerId) {
824
+ await runSimpleCli(dockerBinary, ['rm', '-f', containerId], 15_000);
825
+ },
826
+ async createInternalNetwork(name, labels) {
827
+ const args = ['network', 'create', '--internal'];
828
+ for (const [key, value] of Object.entries(labels)) {
829
+ args.push('--label', `${key}=${value}`);
830
+ }
831
+ args.push(name);
832
+ const res = await runSimpleCli(dockerBinary, args, 15_000);
833
+ if (res.error || res.exitCode !== 0) {
834
+ const msg = res.stderr.trim() || res.error?.message || `docker network create exited ${res.exitCode}`;
835
+ if (/already exists/i.test(msg))
836
+ return;
837
+ throw new RuntimeError('SANDBOX_NETWORK_FAILED', `Failed to create internal network "${name}": ${msg}`);
838
+ }
839
+ },
840
+ async connectNetwork(networkName, containerId, aliases) {
841
+ const args = ['network', 'connect'];
842
+ for (const alias of aliases ?? []) {
843
+ args.push('--alias', alias);
844
+ }
845
+ args.push(networkName, containerId);
846
+ let res = await runSimpleCli(dockerBinary, args, 15_000);
847
+ if (res.error || res.exitCode !== 0) {
848
+ const msg = res.stderr.trim() || res.error?.message || `docker network connect exited ${res.exitCode}`;
849
+ if (/already exists in network|already connected/i.test(msg))
850
+ return;
851
+ if (/private \(none\) mode|cannot be connected to multiple networks/i.test(msg)) {
852
+ await runSimpleCli(dockerBinary, ['network', 'disconnect', 'none', containerId], 10_000);
853
+ res = await runSimpleCli(dockerBinary, args, 15_000);
854
+ if (!res.error && res.exitCode === 0)
855
+ return;
856
+ const retryMsg = res.stderr.trim() || res.error?.message || `docker network connect exited ${res.exitCode}`;
857
+ if (/already exists in network|already connected/i.test(retryMsg))
858
+ return;
859
+ throw new RuntimeError('SANDBOX_NETWORK_FAILED', `Failed to connect container "${containerId}" to network "${networkName}": ${retryMsg}`);
860
+ }
861
+ throw new RuntimeError('SANDBOX_NETWORK_FAILED', `Failed to connect container "${containerId}" to network "${networkName}": ${msg}`);
862
+ }
863
+ },
864
+ async disconnectNetwork(networkName, containerId) {
865
+ await runSimpleCli(dockerBinary, ['network', 'disconnect', '-f', networkName, containerId], 10_000);
866
+ },
867
+ async removeNetwork(networkName) {
868
+ await runSimpleCli(dockerBinary, ['network', 'rm', networkName], 10_000);
869
+ },
870
+ async listManagedNetworks(labels) {
871
+ const args = ['network', 'ls'];
872
+ for (const [key, value] of Object.entries(labels)) {
873
+ args.push('--filter', `label=${key}=${value}`);
874
+ }
875
+ args.push('--format', '{{json .}}');
876
+ const res = await runSimpleCli(dockerBinary, args, 10_000);
877
+ if (res.error || res.exitCode !== 0)
878
+ return [];
879
+ const networks = [];
880
+ for (const line of res.stdout.split(/\r?\n/)) {
881
+ const trimmed = line.trim();
882
+ if (!trimmed)
883
+ continue;
884
+ try {
885
+ const parsed = JSON.parse(trimmed);
886
+ const labelMap = {};
887
+ for (const pair of (parsed.Labels ?? '').split(',')) {
888
+ const eq = pair.indexOf('=');
889
+ if (eq > 0)
890
+ labelMap[pair.slice(0, eq)] = pair.slice(eq + 1);
891
+ }
892
+ if (parsed.ID && parsed.Name) {
893
+ networks.push({
894
+ id: parsed.ID,
895
+ name: parsed.Name,
896
+ labels: labelMap,
897
+ });
898
+ }
899
+ }
900
+ catch {
901
+ // Ignore malformed output line
902
+ }
903
+ }
904
+ return networks;
905
+ },
906
+ async startTargetContainer(spec) {
907
+ const args = buildTargetDockerRunArgs(spec);
908
+ const res = await runSimpleCli(dockerBinary, args, 30_000);
909
+ if (res.error || res.exitCode !== 0) {
910
+ const msg = res.stderr.trim() || res.error?.message || `docker run exited ${res.exitCode}`;
911
+ throw new RuntimeError('SANDBOX_TARGET_START_FAILED', `Failed to start target container: ${msg}`);
912
+ }
913
+ const containerId = res.stdout.trim().split(/\r?\n/)[0]?.trim();
914
+ if (!containerId) {
915
+ throw new RuntimeError('SANDBOX_TARGET_START_FAILED', 'docker run returned no target container ID');
916
+ }
917
+ return { containerId };
918
+ },
919
+ async inspectContainerState(containerId) {
920
+ const res = await runSimpleCli(dockerBinary, ['inspect', '--format', '{{json .State}}', containerId], 10_000);
921
+ if (res.error || res.exitCode !== 0) {
922
+ return {
923
+ exists: false,
924
+ running: false,
925
+ error: res.stderr.trim() || res.error?.message || `docker inspect exited ${res.exitCode}`,
926
+ };
927
+ }
928
+ try {
929
+ const parsed = JSON.parse(res.stdout.trim());
930
+ return {
931
+ exists: true,
932
+ running: Boolean(parsed.Running),
933
+ ...(parsed.Status !== undefined ? { status: parsed.Status } : {}),
934
+ ...(parsed.ExitCode !== undefined ? { exitCode: parsed.ExitCode } : {}),
935
+ ...(parsed.Error ? { error: parsed.Error } : {}),
936
+ };
937
+ }
938
+ catch {
939
+ return {
940
+ exists: false,
941
+ running: false,
942
+ error: 'Malformed docker inspect output',
943
+ };
944
+ }
945
+ },
946
+ async getContainerLogs(containerId, options = {}) {
947
+ const tailLines = Math.max(1, Math.min(500, Math.floor(options.tailLines ?? 80)));
948
+ const maxBytes = Math.max(256, Math.min(65_536, Math.floor(options.maxBytes ?? 16_384)));
949
+ const res = await captureCombinedCli(dockerBinary, ['logs', '--tail', String(tailLines), containerId], maxBytes, 10_000);
950
+ if (res.error && !res.combined) {
951
+ throw new RuntimeError('SANDBOX_TARGET_LOGS_FAILED', `Failed to read target container logs: ${res.error.message}`);
952
+ }
953
+ return {
954
+ logs: res.combined,
955
+ truncated: res.truncated,
956
+ };
957
+ },
958
+ buildExecProcessInput(containerId, workdir, input, executionKey) {
959
+ const token = executionKey
960
+ ? createHash('sha256').update(`${containerId}:${executionKey}`).digest('hex').slice(0, 24)
961
+ : randomUUID().replace(/-/g, '').slice(0, 24);
962
+ const pidFile = `/tmp/.saturn-proc-${token}.pid`;
963
+ const clientEnv = dockerClientEnvironment();
964
+ return {
965
+ program: dockerBinary,
966
+ args: [
967
+ 'exec',
968
+ '-i',
969
+ '-w',
970
+ workdir,
971
+ '-e',
972
+ `SATURN_PROCESS_TOKEN=${token}`,
973
+ containerId,
974
+ '/bin/sh',
975
+ '-c',
976
+ CONTAINER_PROCESS_LAUNCH_SCRIPT,
977
+ '--',
978
+ pidFile,
979
+ input.program,
980
+ ...input.args,
981
+ ],
982
+ cwd: process.cwd(),
983
+ env: clientEnv,
984
+ stopCommand: {
985
+ program: dockerBinary,
986
+ args: ['exec', containerId, '/bin/sh', '-c', CONTAINER_PROCESS_STOP_SCRIPT, '--', pidFile, token],
987
+ cwd: process.cwd(),
988
+ env: clientEnv,
989
+ timeoutMs: 5000,
990
+ },
991
+ ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
992
+ };
993
+ },
994
+ };
995
+ }
996
+ export function hostPathToContainerPath(session, hostOrContainerPath) {
997
+ if (hostOrContainerPath.startsWith('/')) {
998
+ const normalized = path.posix.normalize(hostOrContainerPath);
999
+ if (normalized === session.containerWorkDir ||
1000
+ normalized.startsWith(session.containerWorkDir + '/') ||
1001
+ normalized.startsWith('/readonly/')) {
1002
+ return normalized;
1003
+ }
1004
+ }
1005
+ const rel = relativePathWithin(session.hostWorkDir, hostOrContainerPath);
1006
+ if (!rel)
1007
+ return session.containerWorkDir;
1008
+ const posixRel = rel.split(path.sep).join('/');
1009
+ return path.posix.join(session.containerWorkDir, posixRel);
1010
+ }
1011
+ export function containerPathToHostPath(session, suppliedPath) {
1012
+ if (!suppliedPath.startsWith('/'))
1013
+ return undefined;
1014
+ const normalized = path.posix.normalize(suppliedPath);
1015
+ if (normalized === session.containerWorkDir)
1016
+ return session.hostWorkDir;
1017
+ if (normalized.startsWith(session.containerWorkDir + '/')) {
1018
+ const rel = normalized.slice(session.containerWorkDir.length + 1);
1019
+ return rel ? path.join(session.hostWorkDir, ...rel.split('/')) : session.hostWorkDir;
1020
+ }
1021
+ return undefined;
1022
+ }
1023
+ export function createContainerSandboxBackend({ runner, hostFallback, resolveSession, failClosed, resolveRecoveryContext, recoverSession, onAfterCommand, }) {
1024
+ const isFailClosed = (target) => typeof failClosed === 'function' ? failClosed(target) : Boolean(failClosed);
1025
+ const denyHostFallback = (target) => {
1026
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', target?.agentSessionId
1027
+ ? 'No active sandbox container for this session; refusing unsafe host fallback under fail_closed policy.'
1028
+ : 'Sandbox container unavailable; refusing unsafe host fallback under fail_closed policy.');
1029
+ };
1030
+ const backend = {
1031
+ kind: 'container',
1032
+ resolveContext(workingDirectory, target) {
1033
+ const session = resolveSession(target);
1034
+ if (session) {
1035
+ return {
1036
+ kind: 'container',
1037
+ effectiveRoot: session.hostWorkDir,
1038
+ containerWorkDir: session.containerWorkDir,
1039
+ readonly: session.readonly,
1040
+ readonlyMounts: session.readonlyMounts,
1041
+ containerId: session.containerId,
1042
+ backend,
1043
+ };
1044
+ }
1045
+ const recovery = resolveRecoveryContext?.(target);
1046
+ if (recovery) {
1047
+ return {
1048
+ kind: 'container',
1049
+ effectiveRoot: recovery.hostWorkDir,
1050
+ containerWorkDir: recovery.containerWorkDir,
1051
+ readonly: recovery.readonly,
1052
+ readonlyMounts: recovery.readonlyMounts,
1053
+ containerId: 'pending-recovery',
1054
+ backend,
1055
+ };
1056
+ }
1057
+ if (isFailClosed(target) && target?.agentSessionId)
1058
+ denyHostFallback(target);
1059
+ return hostFallback.resolveContext(workingDirectory, target);
1060
+ },
1061
+ shellInvocation(command, target) {
1062
+ const session = resolveSession(target);
1063
+ if (session || resolveRecoveryContext?.(target)) {
1064
+ return { program: '/bin/sh', args: ['-c', command] };
1065
+ }
1066
+ if (isFailClosed(target) && target?.agentSessionId)
1067
+ denyHostFallback(target);
1068
+ return hostFallback.shellInvocation(command, target);
1069
+ },
1070
+ async runCommand(input, target) {
1071
+ let session = resolveSession(target);
1072
+ if (!session && recoverSession && target?.agentSessionId) {
1073
+ session = await recoverSession(target);
1074
+ }
1075
+ if (!session) {
1076
+ if (isFailClosed(target) && target?.agentSessionId)
1077
+ denyHostFallback(target);
1078
+ return hostFallback.runCommand(input, target);
1079
+ }
1080
+ const containerCwd = hostPathToContainerPath(session, input.cwd);
1081
+ let spillWrite;
1082
+ const result = await runner.execInContainer({
1083
+ containerId: session.containerId,
1084
+ command: [input.program, ...input.args],
1085
+ workdir: containerCwd,
1086
+ ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
1087
+ timeoutMs: input.timeoutMs,
1088
+ signal: input.signal,
1089
+ async onStdout(chunk) {
1090
+ const write = input.output.append(chunk, 0);
1091
+ if (write) {
1092
+ spillWrite = write;
1093
+ await write;
1094
+ }
1095
+ },
1096
+ async onStderr(chunk) {
1097
+ const write = input.output.append(chunk, 1);
1098
+ if (write) {
1099
+ spillWrite = write;
1100
+ await write;
1101
+ }
1102
+ },
1103
+ shouldStop: () => input.output.outputLimitExceeded,
1104
+ });
1105
+ await spillWrite;
1106
+ const capture = await input.output.finish();
1107
+ if (!result.launched && result.startError) {
1108
+ return {
1109
+ effect: 'none',
1110
+ outcome: {
1111
+ status: 'error',
1112
+ error: { code: 'PROCESS_START_FAILED', message: result.startError, retryable: false },
1113
+ },
1114
+ };
1115
+ }
1116
+ if (capture.spillLimitExceeded) {
1117
+ const confirmed = Boolean(result.terminationConfirmed);
1118
+ return {
1119
+ effect: !result.launched ? 'none' : confirmed ? input.effect : 'unknown',
1120
+ outcome: {
1121
+ status: 'error',
1122
+ error: {
1123
+ code: 'PROCESS_OUTPUT_LIMIT_EXCEEDED',
1124
+ message: confirmed
1125
+ ? 'Process output spill limit exceeded and the process was terminated'
1126
+ : 'Process output spill limit exceeded; process termination could not be confirmed',
1127
+ retryable: false,
1128
+ },
1129
+ data: {
1130
+ ...capture,
1131
+ exitCode: result.exitCode,
1132
+ signal: result.signal,
1133
+ terminationConfirmed: confirmed,
1134
+ },
1135
+ },
1136
+ };
1137
+ }
1138
+ if (result.timedOut || result.cancelled) {
1139
+ const confirmed = Boolean(result.terminationConfirmed);
1140
+ return {
1141
+ effect: !result.launched ? 'none' : confirmed ? input.effect : 'unknown',
1142
+ outcome: {
1143
+ status: result.cancelled ? 'cancelled' : 'error',
1144
+ error: {
1145
+ code: result.cancelled ? 'CANCELLED' : 'TIMEOUT',
1146
+ message: confirmed
1147
+ ? `Process ${result.cancelled ? 'cancelled' : 'timed out'} and was terminated`
1148
+ : `Process ${result.cancelled ? 'cancelled' : 'timed out'}; tree termination could not be confirmed`,
1149
+ retryable: false,
1150
+ },
1151
+ data: {
1152
+ ...capture,
1153
+ exitCode: result.exitCode,
1154
+ signal: result.signal,
1155
+ terminationConfirmed: confirmed,
1156
+ },
1157
+ },
1158
+ };
1159
+ }
1160
+ const postWarning = onAfterCommand ? await onAfterCommand(session) : undefined;
1161
+ const data = { exitCode: result.exitCode, signal: result.signal, ...capture };
1162
+ if (capture.spillError) {
1163
+ return {
1164
+ effect: input.effect,
1165
+ outcome: {
1166
+ status: 'error',
1167
+ error: { code: 'PROCESS_OUTPUT_SPILL_FAILED', message: capture.spillError, retryable: false },
1168
+ data: { ...data, stdout: capture.stdout, stderr: capture.stderr },
1169
+ },
1170
+ };
1171
+ }
1172
+ const spill = capture.spillPath
1173
+ ? `\nOutput truncated (${capture.totalBytes} bytes, ${capture.totalLines} lines). Use read_file at ${capture.spillPath} for the bounded spill output.`
1174
+ : '';
1175
+ const warningText = typeof postWarning === 'string' && postWarning.trim() ? `\n${postWarning.trim()}` : '';
1176
+ return {
1177
+ effect: input.effect,
1178
+ outcome: {
1179
+ status: 'success',
1180
+ content: [
1181
+ {
1182
+ type: 'text',
1183
+ text: `Process exit: ${result.exitCode ?? result.signal}${spill}${warningText}\nstdout:\n${capture.stdout}\nstderr:\n${capture.stderr}`,
1184
+ },
1185
+ ],
1186
+ data,
1187
+ },
1188
+ };
1189
+ },
1190
+ async readContainerFile(containerPath, offset, limit, signal, target) {
1191
+ const session = resolveSession(target);
1192
+ if (!session) {
1193
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', 'No active sandbox session for container read');
1194
+ }
1195
+ const normalized = path.posix.normalize(containerPath);
1196
+ if (!normalized.startsWith('/') || normalized.includes('\0')) {
1197
+ throw new RuntimeError('WORKSPACE_PATH_INVALID', 'Invalid container path');
1198
+ }
1199
+ const command = offset > 0
1200
+ ? ['/bin/sh', '-c', 'exec tail -c +"$1" -- "$2"', '--', String(offset + 1), normalized]
1201
+ : ['cat', '--', normalized];
1202
+ const res = await runner.execCaptureBuffer(session.containerId, command, {
1203
+ workdir: session.containerWorkDir,
1204
+ maxBytes: limit + 1,
1205
+ signal,
1206
+ });
1207
+ if (res.exitCode !== 0 && !res.truncated) {
1208
+ const errText = res.stderr.toString('utf8').trim();
1209
+ throw new RuntimeError('WORKSPACE_PATH_INVALID', errText || `Container path unavailable: ${normalized}`);
1210
+ }
1211
+ const more = res.stdout.length > limit || res.truncated;
1212
+ return {
1213
+ bytes: res.stdout.subarray(0, Math.min(res.stdout.length, limit)),
1214
+ more,
1215
+ };
1216
+ },
1217
+ spawnRipgrep(args, cwd, signal, target) {
1218
+ const session = resolveSession(target);
1219
+ if (!session) {
1220
+ if (isFailClosed(target) && target?.agentSessionId)
1221
+ denyHostFallback(target);
1222
+ return undefined;
1223
+ }
1224
+ const containerCwd = hostPathToContainerPath(session, cwd);
1225
+ return runner.spawnExec(session.containerId, ['rg', ...args], containerCwd, signal);
1226
+ },
1227
+ wrapStartProcess(input, target, executionKey) {
1228
+ const session = resolveSession(target);
1229
+ if (!session) {
1230
+ if (resolveRecoveryContext?.(target))
1231
+ denyHostFallback(target);
1232
+ if (isFailClosed(target) && target?.agentSessionId)
1233
+ denyHostFallback(target);
1234
+ return input;
1235
+ }
1236
+ const containerCwd = hostPathToContainerPath(session, input.cwd);
1237
+ return runner.buildExecProcessInput(session.containerId, containerCwd, input, executionKey);
1238
+ },
1239
+ };
1240
+ return backend;
1241
+ }