@saturn-universe/runtime-host 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 (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +478 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +472 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,1519 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { chmod, copyFile, lstat, mkdir, open, readdir, readFile, realpath, rename, rm, unlink, } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { RuntimeError, validateWorkSubpath } from '@saturn-universe/core';
6
+ import { computeDirectoryBytes, createContainerSandboxBackend, createDockerContainerRunner, createHostExecutionBackend, DEFAULT_ALLOWED_TARGET_CAPABILITIES, isContainedPath, validateReadonlyMount, validateTargetCapabilities, validateTargetName, validateTargetSeedFilePath, } from '@saturn-universe/tools';
7
+ import { resolveSessionPaths } from './session-paths.js';
8
+ const DEFAULT_IMAGES = {
9
+ docker: 'saturn-sandbox:latest',
10
+ gvisor: 'saturn-sandbox:latest',
11
+ sysbox: 'saturn-sandbox:latest',
12
+ };
13
+ const SKIPPED_SNAPSHOT_ENTRIES = new Set(['.saturn']);
14
+ function isExcludedSnapshotName(name) {
15
+ return SKIPPED_SNAPSHOT_ENTRIES.has(name) || /^\.env(?:\..*)?$/i.test(name);
16
+ }
17
+ export function sanitizeSandboxSegment(value) {
18
+ const cleaned = value
19
+ .trim()
20
+ .replace(/[^A-Za-z0-9._-]/g, '_')
21
+ .replace(/\.\.+/g, '_');
22
+ if (!cleaned || cleaned === '.' || cleaned === '..')
23
+ return 'unknown';
24
+ return cleaned.slice(0, 64);
25
+ }
26
+ export function computeWorkspaceHash(workspaceRoot) {
27
+ const normalized = process.platform === 'win32' ? workspaceRoot.toLowerCase() : workspaceRoot;
28
+ return createHash('sha256').update(normalized).digest('hex').slice(0, 16);
29
+ }
30
+ async function writeMetaAtomic(metaPath, record) {
31
+ await mkdir(path.dirname(metaPath), { recursive: true });
32
+ const temp = `${metaPath}.${randomUUID()}.tmp`;
33
+ const handle = await open(temp, 'wx', 0o600);
34
+ try {
35
+ try {
36
+ await handle.writeFile(JSON.stringify(record, null, 2) + '\n', 'utf8');
37
+ }
38
+ finally {
39
+ await handle.close();
40
+ }
41
+ await rename(temp, metaPath);
42
+ }
43
+ finally {
44
+ await unlink(temp).catch(() => { });
45
+ }
46
+ }
47
+ async function snapshotWorkspaceToWorkDir(workspaceRoot, workDir, softLimitBytes) {
48
+ const canonicalRoot = await realpath(workspaceRoot);
49
+ await rm(workDir, { recursive: true, force: true });
50
+ await mkdir(workDir, { recursive: true });
51
+ let totalBytes = 0;
52
+ async function walk(srcDir, destDir) {
53
+ const entries = await readdir(srcDir, { withFileTypes: true });
54
+ for (const entry of entries) {
55
+ if (isExcludedSnapshotName(entry.name))
56
+ continue;
57
+ const srcPath = path.join(srcDir, entry.name);
58
+ const destPath = path.join(destDir, entry.name);
59
+ let info;
60
+ try {
61
+ info = await lstat(srcPath);
62
+ }
63
+ catch {
64
+ continue;
65
+ }
66
+ if (info.isSymbolicLink()) {
67
+ const real = await realpath(srcPath).catch(() => undefined);
68
+ if (!real || !isContainedPath(canonicalRoot, real))
69
+ continue;
70
+ continue;
71
+ }
72
+ if (info.isDirectory()) {
73
+ await mkdir(destPath, { recursive: true });
74
+ await walk(srcPath, destPath);
75
+ }
76
+ else if (info.isFile()) {
77
+ totalBytes += info.size;
78
+ if (softLimitBytes !== undefined && totalBytes > softLimitBytes) {
79
+ throw new RuntimeError('SANDBOX_DISK_LIMIT_EXCEEDED', `Workspace snapshot exceeded sandbox disk soft limit (${softLimitBytes} bytes)`);
80
+ }
81
+ await copyFile(srcPath, destPath);
82
+ if (process.platform !== 'win32') {
83
+ await chmod(destPath, info.mode & 0o777).catch(() => { });
84
+ }
85
+ }
86
+ }
87
+ }
88
+ await walk(canonicalRoot, workDir);
89
+ }
90
+ async function resolveContainedSubpathDir(baseDir, subpath) {
91
+ if (!existsSync(baseDir))
92
+ return undefined;
93
+ const canonicalBase = await realpath(baseDir).catch(() => undefined);
94
+ if (!canonicalBase)
95
+ return undefined;
96
+ const candidate = path.resolve(canonicalBase, ...subpath.split('/'));
97
+ if (!isContainedPath(canonicalBase, candidate))
98
+ return undefined;
99
+ try {
100
+ const realTarget = await realpath(candidate);
101
+ const info = await lstat(realTarget);
102
+ if (canonicalBase !== realTarget && isContainedPath(canonicalBase, realTarget) && info.isDirectory()) {
103
+ return realTarget;
104
+ }
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ return undefined;
110
+ }
111
+ async function resolveWorkSubpathSource(workspaceRoot, rawSubpath, sessionId, mainWorkDir) {
112
+ let subpath;
113
+ try {
114
+ subpath = validateWorkSubpath(rawSubpath);
115
+ }
116
+ catch (error) {
117
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', error instanceof Error ? error.message : `Invalid workSubpath: ${rawSubpath}`);
118
+ }
119
+ if (sessionId) {
120
+ const fromAssets = await resolveContainedSubpathDir(resolveSessionPaths(workspaceRoot, sessionId).assetsDir, subpath);
121
+ if (fromAssets)
122
+ return { subpath, sourceDir: fromAssets };
123
+ }
124
+ const canonicalRoot = await realpath(workspaceRoot);
125
+ const candidate = path.resolve(canonicalRoot, ...subpath.split('/'));
126
+ if (!isContainedPath(canonicalRoot, candidate)) {
127
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Worker workSubpath escapes workspace root: ${rawSubpath}`);
128
+ }
129
+ const fromRoot = await resolveContainedSubpathDir(canonicalRoot, subpath);
130
+ if (fromRoot)
131
+ return { subpath, sourceDir: fromRoot };
132
+ if (mainWorkDir) {
133
+ const fromMainSandbox = await resolveContainedSubpathDir(mainWorkDir, subpath);
134
+ if (fromMainSandbox)
135
+ return { subpath, sourceDir: fromMainSandbox };
136
+ }
137
+ const invalidDirectory = () => new RuntimeError('SANDBOX_CONFIG_INVALID', `Worker workSubpath must resolve to a directory inside workspace: ${subpath}`);
138
+ // Find the nearest existing ancestor without following dangling links. Resolve it
139
+ // before creating anything so a missing child through an outside link cannot write there.
140
+ let ancestor = candidate;
141
+ const missing = [];
142
+ try {
143
+ while (ancestor !== canonicalRoot) {
144
+ const info = await lstat(ancestor).catch((error) => {
145
+ if (error.code !== 'ENOENT')
146
+ throw error;
147
+ });
148
+ if (info)
149
+ break;
150
+ missing.unshift(path.basename(ancestor));
151
+ ancestor = path.dirname(ancestor);
152
+ }
153
+ const realAncestor = await realpath(ancestor);
154
+ if (!isContainedPath(canonicalRoot, realAncestor) || !(await lstat(realAncestor)).isDirectory())
155
+ throw invalidDirectory();
156
+ const target = path.join(realAncestor, ...missing);
157
+ if (missing.length > 0)
158
+ await mkdir(target, { recursive: true });
159
+ const sourceDir = await resolveContainedSubpathDir(canonicalRoot, subpath);
160
+ if (sourceDir)
161
+ return { subpath, sourceDir };
162
+ }
163
+ catch {
164
+ throw invalidDirectory();
165
+ }
166
+ throw invalidDirectory();
167
+ }
168
+ function resolveReadonlyMounts(workspaceRoot, mounts) {
169
+ if (!mounts?.length)
170
+ return [];
171
+ const resolved = [];
172
+ for (const mount of mounts) {
173
+ const preValidated = validateReadonlyMount(mount);
174
+ const hostPath = path.isAbsolute(preValidated.hostPath)
175
+ ? path.resolve(preValidated.hostPath)
176
+ : path.resolve(workspaceRoot, preValidated.hostPath);
177
+ const validated = validateReadonlyMount({
178
+ hostPath,
179
+ containerPath: preValidated.containerPath,
180
+ });
181
+ if (existsSync(hostPath)) {
182
+ const realHost = realpathSync(hostPath);
183
+ validateReadonlyMount({
184
+ hostPath: realHost,
185
+ containerPath: validated.containerPath,
186
+ });
187
+ }
188
+ resolved.push(validated);
189
+ }
190
+ return resolved;
191
+ }
192
+ export function createSandboxManager(options) {
193
+ const { root, mode, logger, allowUnsafeFallback = false } = options;
194
+ const checkKvmAvailable = options.checkKvmAvailable ?? (() => process.platform !== 'win32' && existsSync('/dev/kvm'));
195
+ const sandboxConfig = mode.sandbox ?? {
196
+ backend: 'host',
197
+ scope: 'none',
198
+ fallbackPolicy: 'fail_closed',
199
+ };
200
+ const backend = sandboxConfig.backend;
201
+ const scope = sandboxConfig.scope ?? (backend === 'host' ? 'none' : 'per_run_and_worker');
202
+ const workspaceHash = computeWorkspaceHash(root);
203
+ const sandboxesRoot = path.join(root, '.saturn', 'sandboxes');
204
+ const sessionsRoot = path.join(root, '.saturn', 'sessions');
205
+ const resolveSandboxesBase = (sessionId) => sessionId ? resolveSessionPaths(root, sessionId).sandboxesDir : sandboxesRoot;
206
+ const runner = options.runner ?? createDockerContainerRunner();
207
+ const hostFallback = createHostExecutionBackend((wd) => wd);
208
+ let state = backend === 'host' || scope === 'none' ? 'disabled' : 'unavailable';
209
+ let fallbackActive = false;
210
+ let statusReason;
211
+ let disposed = false;
212
+ let ttlCleanupTimer;
213
+ const maxConcurrentContainers = sandboxConfig.maxConcurrentContainers ?? 6;
214
+ const sessionsByAgentSession = new Map();
215
+ const sandboxRequiredSessions = new Set();
216
+ const quotaExceededSessions = new Map();
217
+ const runMemberSessions = new Map();
218
+ const childSessionsByParent = new Map();
219
+ const parentBySession = new Map();
220
+ const runProbeContext = new Map();
221
+ const pendingAllocations = new Map();
222
+ const pendingRecoveries = new Map();
223
+ const memberNetworks = new Map();
224
+ const memberTargets = new Map();
225
+ const pendingNetworkCreations = new Map();
226
+ const tornDownSessions = new Set();
227
+ let activeCleanup;
228
+ let cleanupRequested = false;
229
+ let reservedContainers = 0;
230
+ function countActiveTargets() {
231
+ let count = 0;
232
+ for (const map of memberTargets.values())
233
+ count += map.size;
234
+ return count;
235
+ }
236
+ function activeContainerCount() {
237
+ return sessionsByAgentSession.size + countActiveTargets() + reservedContainers;
238
+ }
239
+ const resolvedImage = backend === 'host' ? undefined : (sandboxConfig.image ?? DEFAULT_IMAGES[backend]);
240
+ const containerBackend = backend === 'host' ? undefined : backend;
241
+ const softLimitBytes = sandboxConfig.resources?.diskSoftLimitMb !== undefined
242
+ ? sandboxConfig.resources.diskSoftLimitMb * 1024 * 1024
243
+ : undefined;
244
+ async function startMemberContainer(params) {
245
+ const safeRun = sanitizeSandboxSegment(params.runId);
246
+ const safeMember = sanitizeSandboxSegment(params.memberId);
247
+ const kvmRequested = sandboxConfig.kvm === true;
248
+ const kvmActive = kvmRequested && checkKvmAvailable();
249
+ if (kvmRequested && !kvmActive && params.logKvmUnavailable) {
250
+ logger.info({
251
+ code: 'SANDBOX_KVM_UNAVAILABLE',
252
+ device: '/dev/kvm',
253
+ modeRef: mode.ref,
254
+ runId: params.runId,
255
+ memberId: params.memberId,
256
+ }, 'KVM requested but /dev/kvm is unavailable on host; continuing without KVM');
257
+ }
258
+ const posixUser = process.platform !== 'win32' &&
259
+ containerBackend !== 'sysbox' &&
260
+ typeof process.getuid === 'function' &&
261
+ typeof process.getgid === 'function'
262
+ ? `${process.getuid()}:${process.getgid()}`
263
+ : undefined;
264
+ const containerName = `saturn-${workspaceHash}-${safeRun.slice(0, 12)}-${safeMember.slice(0, 16)}-${randomUUID().slice(0, 8)}`;
265
+ const { containerId } = await runner.startContainer({
266
+ backend: containerBackend,
267
+ name: containerName,
268
+ image: resolvedImage,
269
+ workDirHost: params.workDir,
270
+ workDirContainer: params.containerWorkDir,
271
+ workDirReadOnly: params.readonly,
272
+ network: params.effectiveNetwork,
273
+ ...(sandboxConfig.networkName ? { networkName: sandboxConfig.networkName } : {}),
274
+ ...(sandboxConfig.proxyUrl ? { proxyUrl: sandboxConfig.proxyUrl } : {}),
275
+ ...(sandboxConfig.capAdd ? { capAdd: sandboxConfig.capAdd } : {}),
276
+ ...(params.readonlyMounts.length ? { readonlyMounts: params.readonlyMounts } : {}),
277
+ ...(kvmActive ? { kvm: true } : {}),
278
+ ...(sandboxConfig.tmpfsSizeMb !== undefined ? { tmpfsSizeMb: sandboxConfig.tmpfsSizeMb } : {}),
279
+ ...(sandboxConfig.resources ? { resources: sandboxConfig.resources } : {}),
280
+ ...(posixUser ? { user: posixUser } : {}),
281
+ workspaceHash,
282
+ runId: params.runId,
283
+ memberId: params.memberId,
284
+ });
285
+ return { containerId, containerName, kvmActive };
286
+ }
287
+ async function recoverQuotaExceededSession(agentSessionId) {
288
+ const existing = sessionsByAgentSession.get(agentSessionId)?.session;
289
+ if (existing)
290
+ return existing;
291
+ const inflight = pendingRecoveries.get(agentSessionId);
292
+ if (inflight)
293
+ return inflight;
294
+ const record = quotaExceededSessions.get(agentSessionId);
295
+ if (!record ||
296
+ disposed ||
297
+ state !== 'ready' ||
298
+ fallbackActive ||
299
+ !containerBackend ||
300
+ !resolvedImage ||
301
+ tornDownSessions.has(agentSessionId)) {
302
+ return undefined;
303
+ }
304
+ const work = (async () => {
305
+ const stillExisting = sessionsByAgentSession.get(agentSessionId)?.session;
306
+ if (stillExisting)
307
+ return stillExisting;
308
+ if (softLimitBytes !== undefined && record.consecutiveFailures >= 3) {
309
+ const currentBytes = await computeDirectoryBytes(record.entry.session.hostWorkDir);
310
+ if (currentBytes > softLimitBytes) {
311
+ throw new RuntimeError('SANDBOX_DISK_LIMIT_EXCEEDED', `Sandbox disk soft limit still exceeded (${currentBytes} > ${softLimitBytes} bytes) after ${record.consecutiveFailures} recovery attempts; remove large files before continuing.`);
312
+ }
313
+ record.consecutiveFailures = 0;
314
+ }
315
+ if (activeContainerCount() >= maxConcurrentContainers) {
316
+ throw new RuntimeError('SANDBOX_CONTAINER_LIMIT_EXCEEDED', `Maximum of ${maxConcurrentContainers} concurrent sandbox containers reached`);
317
+ }
318
+ let reserved = true;
319
+ reservedContainers += 1;
320
+ try {
321
+ const prevSession = record.entry.session;
322
+ const { containerId, containerName } = await startMemberContainer({
323
+ runId: prevSession.runId,
324
+ memberId: prevSession.memberId,
325
+ workDir: prevSession.hostWorkDir,
326
+ containerWorkDir: prevSession.containerWorkDir,
327
+ readonly: prevSession.readonly,
328
+ effectiveNetwork: prevSession.network,
329
+ readonlyMounts: prevSession.readonlyMounts,
330
+ logKvmUnavailable: false,
331
+ });
332
+ const nowIso = new Date().toISOString();
333
+ const recoveredSession = {
334
+ ...prevSession,
335
+ containerId,
336
+ };
337
+ const updatedMeta = {
338
+ ...record.entry.meta,
339
+ containerId,
340
+ containerName,
341
+ status: 'running',
342
+ updatedAt: nowIso,
343
+ };
344
+ await writeMetaAtomic(record.entry.metaPath, updatedMeta);
345
+ sessionsByAgentSession.set(agentSessionId, {
346
+ ...record.entry,
347
+ session: recoveredSession,
348
+ meta: updatedMeta,
349
+ });
350
+ reserved = false;
351
+ reservedContainers -= 1;
352
+ let set = runMemberSessions.get(prevSession.runId);
353
+ if (!set)
354
+ runMemberSessions.set(prevSession.runId, (set = new Set()));
355
+ set.add(agentSessionId);
356
+ const memberNetwork = memberNetworks.get(agentSessionId);
357
+ if (memberNetwork && runner.connectNetwork) {
358
+ if (recoveredSession.network === 'none') {
359
+ await runner.disconnectNetwork?.('none', containerId).catch(() => { });
360
+ }
361
+ await runner.connectNetwork(memberNetwork.networkName, containerId);
362
+ memberNetwork.connectedContainers.add(containerId);
363
+ }
364
+ return recoveredSession;
365
+ }
366
+ finally {
367
+ if (reserved)
368
+ reservedContainers -= 1;
369
+ }
370
+ })().finally(() => {
371
+ pendingRecoveries.delete(agentSessionId);
372
+ });
373
+ pendingRecoveries.set(agentSessionId, work);
374
+ return work;
375
+ }
376
+ const containerBackendExecutor = createContainerSandboxBackend({
377
+ runner,
378
+ hostFallback,
379
+ resolveSession: (target) => {
380
+ if (state !== 'ready' || fallbackActive || !target?.agentSessionId)
381
+ return undefined;
382
+ return sessionsByAgentSession.get(target.agentSessionId)?.session;
383
+ },
384
+ failClosed: (target) => Boolean(target?.agentSessionId && sandboxRequiredSessions.has(target.agentSessionId)) ||
385
+ (!fallbackActive && !allowUnsafeFallback && sandboxConfig.fallbackPolicy !== 'allow_host_fallback'),
386
+ resolveRecoveryContext: (target) => {
387
+ if (state !== 'ready' || fallbackActive || !target?.agentSessionId)
388
+ return undefined;
389
+ const entry = quotaExceededSessions.get(target.agentSessionId)?.entry;
390
+ if (!entry)
391
+ return undefined;
392
+ return {
393
+ hostWorkDir: entry.session.hostWorkDir,
394
+ containerWorkDir: entry.session.containerWorkDir,
395
+ readonly: entry.session.readonly,
396
+ readonlyMounts: entry.session.readonlyMounts,
397
+ };
398
+ },
399
+ recoverSession: async (target) => {
400
+ if (!target?.agentSessionId)
401
+ return undefined;
402
+ return recoverQuotaExceededSession(target.agentSessionId);
403
+ },
404
+ onAfterCommand: async (session) => {
405
+ if (softLimitBytes === undefined)
406
+ return;
407
+ const bytes = await computeDirectoryBytes(session.hostWorkDir);
408
+ const softWarnBytes = Math.floor(softLimitBytes * 0.8);
409
+ if (bytes <= softLimitBytes) {
410
+ quotaExceededSessions.delete(session.agentSessionId);
411
+ if (bytes > softWarnBytes) {
412
+ const usedMb = (bytes / (1024 * 1024)).toFixed(1);
413
+ const limitMb = (softLimitBytes / (1024 * 1024)).toFixed(1);
414
+ const pct = Math.round((bytes / softLimitBytes) * 100);
415
+ return `[SANDBOX DISK WARNING] /workspace is using ${usedMb} MiB / ${limitMb} MiB (${pct}%). Remove unused large attachments or temporary files soon to avoid container termination.`;
416
+ }
417
+ return;
418
+ }
419
+ const entry = sessionsByAgentSession.get(session.agentSessionId);
420
+ const memberNetwork = memberNetworks.get(session.agentSessionId);
421
+ if (memberNetwork?.connectedContainers.has(session.containerId)) {
422
+ await runner.disconnectNetwork?.(memberNetwork.networkName, session.containerId).catch(() => { });
423
+ memberNetwork.connectedContainers.delete(session.containerId);
424
+ }
425
+ await runner.removeContainer(session.containerId).catch(() => { });
426
+ sessionsByAgentSession.delete(session.agentSessionId);
427
+ runMemberSessions.get(session.runId)?.delete(session.agentSessionId);
428
+ if (entry) {
429
+ const updated = {
430
+ ...entry.meta,
431
+ status: 'quota_exceeded',
432
+ updatedAt: new Date().toISOString(),
433
+ };
434
+ entry.meta = updated;
435
+ await writeMetaAtomic(entry.metaPath, updated).catch(() => { });
436
+ const prevFailures = quotaExceededSessions.get(session.agentSessionId)?.consecutiveFailures ?? 0;
437
+ quotaExceededSessions.set(session.agentSessionId, {
438
+ entry,
439
+ consecutiveFailures: prevFailures + 1,
440
+ });
441
+ }
442
+ throw new RuntimeError('SANDBOX_DISK_LIMIT_EXCEEDED', `Sandbox disk soft limit exceeded (${bytes} > ${softLimitBytes} bytes); container ${session.containerId} terminated. A recovery container mounting the same /workspace will start on your next shell call—delete large files in /workspace immediately.`);
443
+ },
444
+ });
445
+ const executionBackend = backend === 'host' || scope === 'none' ? hostFallback : containerBackendExecutor;
446
+ function applyFallbackOrThrow(code, message) {
447
+ const canFallback = allowUnsafeFallback || sandboxConfig.fallbackPolicy === 'allow_host_fallback';
448
+ if (!canFallback) {
449
+ state = 'unavailable';
450
+ statusReason = message;
451
+ throw new RuntimeError(code, message);
452
+ }
453
+ state = 'fallback_host';
454
+ fallbackActive = true;
455
+ statusReason = message;
456
+ logger.error({ code, backend, modeRef: mode.ref, image: resolvedImage ?? null }, `WARNING: Sandbox unavailable (${message}); falling back to UNSAFE HOST EXECUTION.`);
457
+ }
458
+ async function listSandboxRoots() {
459
+ const roots = [sandboxesRoot];
460
+ try {
461
+ for (const sessionEntry of await readdir(sessionsRoot, { withFileTypes: true })) {
462
+ if (sessionEntry.isDirectory()) {
463
+ roots.push(path.join(sessionsRoot, sessionEntry.name, 'sandboxes'));
464
+ }
465
+ }
466
+ }
467
+ catch {
468
+ // No session directories yet.
469
+ }
470
+ return roots;
471
+ }
472
+ async function collectRunMetaPaths(runDir) {
473
+ const metas = [path.join(runDir, 'main', 'meta.json')];
474
+ try {
475
+ const workersDir = path.join(runDir, 'workers');
476
+ for (const worker of await readdir(workersDir)) {
477
+ metas.push(path.join(workersDir, worker, 'meta.json'));
478
+ }
479
+ }
480
+ catch {
481
+ // No workers directory
482
+ }
483
+ try {
484
+ const targetsDir = path.join(runDir, 'targets');
485
+ for (const targetOrMember of await readdir(targetsDir)) {
486
+ const directMeta = path.join(targetsDir, targetOrMember, 'meta.json');
487
+ if (existsSync(directMeta)) {
488
+ metas.push(directMeta);
489
+ }
490
+ else {
491
+ try {
492
+ for (const subTarget of await readdir(path.join(targetsDir, targetOrMember))) {
493
+ metas.push(path.join(targetsDir, targetOrMember, subTarget, 'meta.json'));
494
+ }
495
+ }
496
+ catch {
497
+ // Ignore non-directory target entries
498
+ }
499
+ }
500
+ }
501
+ }
502
+ catch {
503
+ // No targets directory
504
+ }
505
+ return metas;
506
+ }
507
+ async function cleanExpiredRunsInRoot(baseRoot) {
508
+ let runDirs;
509
+ try {
510
+ runDirs = await readdir(baseRoot);
511
+ }
512
+ catch {
513
+ return;
514
+ }
515
+ const now = Date.now();
516
+ for (const runEntry of runDirs) {
517
+ if (disposed)
518
+ return;
519
+ const runDir = path.join(baseRoot, runEntry);
520
+ const metas = await collectRunMetaPaths(runDir);
521
+ let allExpiredOrCleaned = true;
522
+ let sawAnyMeta = false;
523
+ for (const metaPath of metas) {
524
+ if (disposed)
525
+ return;
526
+ try {
527
+ const parsed = JSON.parse(await readFile(metaPath, 'utf8'));
528
+ sawAnyMeta = true;
529
+ const expired = parsed.expiresAt !== undefined && Date.parse(parsed.expiresAt) <= now;
530
+ if (parsed.status === 'running' || !expired) {
531
+ allExpiredOrCleaned = false;
532
+ }
533
+ else {
534
+ await rm(path.dirname(metaPath), { recursive: true, force: true }).catch(() => { });
535
+ }
536
+ }
537
+ catch {
538
+ // Ignore missing/unreadable meta
539
+ }
540
+ }
541
+ if (!disposed && sawAnyMeta && allExpiredOrCleaned) {
542
+ await rm(runDir, { recursive: true, force: true }).catch(() => { });
543
+ }
544
+ }
545
+ }
546
+ async function pruneRetainedRunWorkDirs(baseRoot, keepRecent = 2) {
547
+ if (disposed || sandboxConfig.retention?.mode !== 'ttl')
548
+ return;
549
+ let runDirs;
550
+ try {
551
+ runDirs = await readdir(baseRoot);
552
+ }
553
+ catch {
554
+ return;
555
+ }
556
+ const completedRuns = [];
557
+ for (const runEntry of runDirs) {
558
+ if (disposed)
559
+ return;
560
+ const runDir = path.join(baseRoot, runEntry);
561
+ const metas = await collectRunMetaPaths(runDir);
562
+ let anyRunning = false;
563
+ let latestMs = 0;
564
+ let hasMeta = false;
565
+ for (const metaPath of metas) {
566
+ try {
567
+ const parsed = JSON.parse(await readFile(metaPath, 'utf8'));
568
+ hasMeta = true;
569
+ if (parsed.status === 'running' ||
570
+ (parsed.runId && runMemberSessions.get(parsed.runId)?.size)) {
571
+ anyRunning = true;
572
+ break;
573
+ }
574
+ const ts = Date.parse(parsed.updatedAt ?? parsed.createdAt ?? '');
575
+ if (Number.isFinite(ts) && ts > latestMs)
576
+ latestMs = ts;
577
+ }
578
+ catch {
579
+ // Ignore missing/unreadable meta
580
+ }
581
+ }
582
+ if (hasMeta && !anyRunning) {
583
+ completedRuns.push({ runDir, updatedAtMs: latestMs, metas });
584
+ }
585
+ }
586
+ completedRuns.sort((a, b) => b.updatedAtMs - a.updatedAtMs);
587
+ for (const oldRun of completedRuns.slice(keepRecent)) {
588
+ if (disposed)
589
+ return;
590
+ for (const metaPath of oldRun.metas) {
591
+ if (disposed)
592
+ return;
593
+ await rm(path.join(path.dirname(metaPath), 'work'), { recursive: true, force: true }).catch(() => { });
594
+ }
595
+ }
596
+ }
597
+ async function cleanExpiredTtlDirectories() {
598
+ if (disposed)
599
+ return;
600
+ const roots = await listSandboxRoots();
601
+ for (const baseRoot of roots) {
602
+ if (disposed)
603
+ return;
604
+ await cleanExpiredRunsInRoot(baseRoot);
605
+ if (disposed)
606
+ return;
607
+ await pruneRetainedRunWorkDirs(baseRoot);
608
+ }
609
+ }
610
+ function scheduleCleanupDirectories(targetRoot) {
611
+ if (disposed)
612
+ return;
613
+ if (activeCleanup) {
614
+ cleanupRequested = true;
615
+ return;
616
+ }
617
+ activeCleanup = (async () => {
618
+ try {
619
+ if (targetRoot) {
620
+ await pruneRetainedRunWorkDirs(targetRoot);
621
+ }
622
+ else {
623
+ await cleanExpiredTtlDirectories();
624
+ }
625
+ }
626
+ catch {
627
+ // Best-effort background retention cleanup
628
+ }
629
+ finally {
630
+ activeCleanup = undefined;
631
+ if (cleanupRequested && !disposed) {
632
+ cleanupRequested = false;
633
+ scheduleCleanupDirectories();
634
+ }
635
+ }
636
+ })();
637
+ }
638
+ async function allocateMemberSandbox(params) {
639
+ if (disposed || state !== 'ready' || fallbackActive || !containerBackend || !resolvedImage)
640
+ return;
641
+ if (sessionsByAgentSession.has(params.agentSessionId))
642
+ return;
643
+ const inflight = pendingAllocations.get(params.agentSessionId);
644
+ if (inflight)
645
+ return inflight;
646
+ const work = (async () => {
647
+ if (sessionsByAgentSession.has(params.agentSessionId))
648
+ return;
649
+ if (activeContainerCount() >= maxConcurrentContainers) {
650
+ throw new RuntimeError('SANDBOX_CONTAINER_LIMIT_EXCEEDED', `Maximum of ${maxConcurrentContainers} concurrent sandbox containers reached`);
651
+ }
652
+ let reserved = true;
653
+ reservedContainers += 1;
654
+ try {
655
+ const effectiveSessionId = params.sessionId ?? findMainSessionForRun(params.runId)?.meta.sessionId;
656
+ const safeRun = sanitizeSandboxSegment(params.runId);
657
+ const safeMember = sanitizeSandboxSegment(params.memberId);
658
+ const runSandboxesRoot = resolveSandboxesBase(effectiveSessionId);
659
+ const memberDir = params.role === 'main'
660
+ ? path.join(runSandboxesRoot, safeRun, 'main')
661
+ : path.join(runSandboxesRoot, safeRun, 'workers', safeMember);
662
+ const workDir = path.join(memberDir, 'work');
663
+ const metaPath = path.join(memberDir, 'meta.json');
664
+ const inheritedSubpath = params.workSubpath ??
665
+ (params.parentAgentSessionId
666
+ ? sessionsByAgentSession.get(params.parentAgentSessionId)?.workSubpath
667
+ : undefined);
668
+ const isCtfMode = mode.ref === 'ctf@1' || mode.ref.startsWith('ctf@');
669
+ if (isCtfMode && params.role === 'worker' && !inheritedSubpath?.trim()) {
670
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Worker "${params.memberId}" in ctf@1 mode requires a non-empty workSubpath; refusing to snapshot the entire workspace root`);
671
+ }
672
+ const mainWorkDir = params.role === 'worker'
673
+ ? (findMainSessionForRun(params.runId)?.session.hostWorkDir ??
674
+ path.join(runSandboxesRoot, safeRun, 'main', 'work'))
675
+ : undefined;
676
+ const resolvedSubpath = inheritedSubpath !== undefined
677
+ ? await resolveWorkSubpathSource(root, inheritedSubpath, effectiveSessionId, mainWorkDir)
678
+ : undefined;
679
+ if (resolvedSubpath) {
680
+ await snapshotWorkspaceToWorkDir(resolvedSubpath.sourceDir, workDir, softLimitBytes);
681
+ }
682
+ else if (isCtfMode && params.role === 'main' && effectiveSessionId) {
683
+ const assetsDir = resolveSessionPaths(root, effectiveSessionId).assetsDir;
684
+ if (existsSync(assetsDir) && (await lstat(assetsDir).catch(() => undefined))?.isDirectory()) {
685
+ await snapshotWorkspaceToWorkDir(assetsDir, workDir, softLimitBytes);
686
+ }
687
+ else {
688
+ await rm(workDir, { recursive: true, force: true });
689
+ await mkdir(workDir, { recursive: true });
690
+ }
691
+ }
692
+ else {
693
+ await snapshotWorkspaceToWorkDir(root, workDir, softLimitBytes);
694
+ }
695
+ const readonly = params.sandboxProfile === 'readonly';
696
+ const effectiveNetwork = readonly ? 'none' : (sandboxConfig.network ?? 'none');
697
+ const containerWorkDir = '/workspace';
698
+ const readonlyMounts = resolveReadonlyMounts(root, sandboxConfig.readonlyMounts);
699
+ const { containerId, containerName, kvmActive } = await startMemberContainer({
700
+ runId: params.runId,
701
+ memberId: params.memberId,
702
+ workDir,
703
+ containerWorkDir,
704
+ readonly,
705
+ effectiveNetwork,
706
+ readonlyMounts,
707
+ logKvmUnavailable: true,
708
+ });
709
+ const nowIso = new Date().toISOString();
710
+ const ttlHours = sandboxConfig.retention?.mode === 'ttl' ? (sandboxConfig.retention.ttlHours ?? 24) : undefined;
711
+ const meta = {
712
+ version: 1,
713
+ workspaceRoot: root,
714
+ workspaceHash,
715
+ ...(effectiveSessionId !== undefined ? { sessionId: effectiveSessionId } : {}),
716
+ runId: params.runId,
717
+ role: params.role,
718
+ memberId: params.memberId,
719
+ agentSessionId: params.agentSessionId,
720
+ sandboxProfile: params.sandboxProfile,
721
+ backend,
722
+ image: resolvedImage,
723
+ containerId,
724
+ containerName,
725
+ workDir,
726
+ readonly,
727
+ ...(resolvedSubpath ? { workSubpath: resolvedSubpath.subpath } : {}),
728
+ network: effectiveNetwork,
729
+ createdAt: nowIso,
730
+ updatedAt: nowIso,
731
+ ...(ttlHours !== undefined
732
+ ? { expiresAt: new Date(Date.now() + ttlHours * 3600 * 1000).toISOString() }
733
+ : {}),
734
+ status: 'running',
735
+ };
736
+ await writeMetaAtomic(metaPath, meta);
737
+ const session = {
738
+ runId: params.runId,
739
+ agentSessionId: params.agentSessionId,
740
+ memberId: params.memberId,
741
+ containerId,
742
+ hostWorkDir: workDir,
743
+ containerWorkDir,
744
+ readonly,
745
+ readonlyMounts,
746
+ backend: containerBackend,
747
+ image: resolvedImage,
748
+ network: effectiveNetwork,
749
+ };
750
+ sessionsByAgentSession.set(params.agentSessionId, {
751
+ session,
752
+ metaPath,
753
+ memberDir,
754
+ ...(resolvedSubpath ? { workSubpath: resolvedSubpath.subpath } : {}),
755
+ meta,
756
+ });
757
+ sandboxRequiredSessions.add(params.agentSessionId);
758
+ reserved = false;
759
+ reservedContainers -= 1;
760
+ let set = runMemberSessions.get(params.runId);
761
+ if (!set)
762
+ runMemberSessions.set(params.runId, (set = new Set()));
763
+ set.add(params.agentSessionId);
764
+ if (params.parentAgentSessionId) {
765
+ let children = childSessionsByParent.get(params.parentAgentSessionId);
766
+ if (!children) {
767
+ children = new Set();
768
+ childSessionsByParent.set(params.parentAgentSessionId, children);
769
+ }
770
+ children.add(params.agentSessionId);
771
+ parentBySession.set(params.agentSessionId, params.parentAgentSessionId);
772
+ }
773
+ if (params.role === 'main') {
774
+ let probeSummary;
775
+ try {
776
+ const probe = await runner.execCaptureBuffer(containerId, ['/usr/local/bin/saturn-sandbox-probe'], {
777
+ workdir: containerWorkDir,
778
+ maxBytes: 16384,
779
+ timeoutMs: 5000,
780
+ });
781
+ if (probe.exitCode === 0 && probe.stdout.length > 0) {
782
+ probeSummary = probe.stdout.toString('utf8').replace(/\s+/g, ' ').trim().slice(0, 1024);
783
+ }
784
+ }
785
+ catch {
786
+ // Probe binary is optional in custom/minimal images.
787
+ }
788
+ runProbeContext.set(params.runId, {
789
+ backend,
790
+ image: resolvedImage,
791
+ containerWorkDir,
792
+ network: effectiveNetwork,
793
+ fallbackActive: false,
794
+ ...(sandboxConfig.capAdd?.length ? { capAdd: sandboxConfig.capAdd } : {}),
795
+ tmpNoexec: true,
796
+ ...(kvmActive ? { kvmActive: true } : {}),
797
+ ...(probeSummary ? { probeSummary } : {}),
798
+ });
799
+ }
800
+ }
801
+ finally {
802
+ if (reserved)
803
+ reservedContainers -= 1;
804
+ }
805
+ })().finally(() => {
806
+ pendingAllocations.delete(params.agentSessionId);
807
+ });
808
+ pendingAllocations.set(params.agentSessionId, work);
809
+ return work;
810
+ }
811
+ function isTargetServicesEnabled() {
812
+ return (!disposed &&
813
+ state === 'ready' &&
814
+ !fallbackActive &&
815
+ backend !== 'host' &&
816
+ scope !== 'none' &&
817
+ Boolean(sandboxConfig.allowTargetServices));
818
+ }
819
+ function isWorkerTargetServicesEnabled() {
820
+ return isTargetServicesEnabled() && Boolean(sandboxConfig.workerAllowTargetServices);
821
+ }
822
+ function buildMemberNetworkName(runId, agentSessionId) {
823
+ const safeRunShort = sanitizeSandboxSegment(runId)
824
+ .toLowerCase()
825
+ .replace(/[^a-z0-9_-]/g, '_')
826
+ .slice(0, 12);
827
+ const sessionHash = createHash('sha256').update(agentSessionId).digest('hex').slice(0, 8);
828
+ return `saturn-net-${workspaceHash.slice(0, 8)}-${safeRunShort || 'run'}-${sessionHash}`;
829
+ }
830
+ function findMainSessionForRun(runId) {
831
+ const sessionIds = runMemberSessions.get(runId);
832
+ if (!sessionIds)
833
+ return undefined;
834
+ for (const id of sessionIds) {
835
+ const entry = sessionsByAgentSession.get(id);
836
+ if (entry?.meta.role === 'main')
837
+ return entry;
838
+ }
839
+ return undefined;
840
+ }
841
+ function resolveTargetOwner(runId, agentSessionId) {
842
+ if (agentSessionId !== undefined) {
843
+ const entry = sessionsByAgentSession.get(agentSessionId);
844
+ if (!entry || entry.session.runId !== runId) {
845
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', `No active sandbox session "${agentSessionId}" found for run "${runId}"`);
846
+ }
847
+ return entry;
848
+ }
849
+ const mainEntry = findMainSessionForRun(runId);
850
+ if (!mainEntry) {
851
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', `No active main sandbox session found for run "${runId}"`);
852
+ }
853
+ return mainEntry;
854
+ }
855
+ async function ensureMemberInternalNetwork(ownerEntry) {
856
+ if (!runner.createInternalNetwork || !runner.connectNetwork) {
857
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', 'Container runner does not support isolated internal network management');
858
+ }
859
+ const ownerSessionId = ownerEntry.session.agentSessionId;
860
+ const existing = memberNetworks.get(ownerSessionId);
861
+ let networkState;
862
+ if (existing) {
863
+ networkState = existing;
864
+ }
865
+ else {
866
+ const inflight = pendingNetworkCreations.get(ownerSessionId);
867
+ if (inflight) {
868
+ networkState = await inflight;
869
+ }
870
+ else {
871
+ const promise = (async () => {
872
+ const networkName = buildMemberNetworkName(ownerEntry.session.runId, ownerSessionId);
873
+ await runner.createInternalNetwork(networkName, {
874
+ 'saturn.managed': 'true',
875
+ 'saturn.workspace': workspaceHash,
876
+ 'saturn.run': ownerEntry.session.runId,
877
+ 'saturn.run_id': ownerEntry.session.runId,
878
+ 'saturn.agent_session': ownerSessionId,
879
+ 'saturn.member': ownerEntry.session.memberId,
880
+ });
881
+ const created = {
882
+ runId: ownerEntry.session.runId,
883
+ networkName,
884
+ connectedContainers: new Set(),
885
+ };
886
+ memberNetworks.set(ownerSessionId, created);
887
+ return created;
888
+ })().finally(() => {
889
+ pendingNetworkCreations.delete(ownerSessionId);
890
+ });
891
+ pendingNetworkCreations.set(ownerSessionId, promise);
892
+ networkState = await promise;
893
+ }
894
+ }
895
+ const containerId = ownerEntry.session.containerId;
896
+ if (!networkState.connectedContainers.has(containerId)) {
897
+ if (ownerEntry.session.network === 'none') {
898
+ await runner.disconnectNetwork?.('none', containerId).catch(() => { });
899
+ }
900
+ await runner.connectNetwork(networkState.networkName, containerId);
901
+ networkState.connectedContainers.add(containerId);
902
+ }
903
+ return networkState;
904
+ }
905
+ async function writeSeedMounts(seedDir, seedFiles) {
906
+ await rm(seedDir, { recursive: true, force: true });
907
+ if (!seedFiles)
908
+ return [];
909
+ const entries = Object.entries(seedFiles);
910
+ if (entries.length === 0)
911
+ return [];
912
+ if (entries.length > 16) {
913
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', 'At most 16 seedFiles are allowed per target');
914
+ }
915
+ await mkdir(seedDir, { recursive: true });
916
+ const seenContainerPaths = new Set();
917
+ const mounts = [];
918
+ let index = 0;
919
+ for (const [rawContainerPath, content] of entries) {
920
+ const containerPath = validateTargetSeedFilePath(rawContainerPath);
921
+ if (seenContainerPaths.has(containerPath)) {
922
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Duplicate normalized seedFiles path: "${containerPath}"`);
923
+ }
924
+ if (typeof content !== 'string') {
925
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file content for "${containerPath}" must be a string`);
926
+ }
927
+ if (Buffer.byteLength(content, 'utf8') > 1024 * 1024) {
928
+ throw new RuntimeError('SANDBOX_TARGET_SEED_PATH_INVALID', `Seed file "${containerPath}" exceeds 1 MiB limit`);
929
+ }
930
+ seenContainerPaths.add(containerPath);
931
+ const pathHash = createHash('sha256').update(containerPath).digest('hex').slice(0, 12);
932
+ const hostPath = path.join(seedDir, `${index}-${pathHash}`);
933
+ index += 1;
934
+ const handle = await open(hostPath, 'wx', 0o644);
935
+ try {
936
+ await handle.writeFile(content, 'utf8');
937
+ }
938
+ finally {
939
+ await handle.close();
940
+ }
941
+ mounts.push({ hostPath, containerPath });
942
+ }
943
+ return mounts;
944
+ }
945
+ async function finalizeTargetEntry(entry) {
946
+ await runner.removeContainer(entry.containerId).catch(() => { });
947
+ await rm(entry.seedDir, { recursive: true, force: true }).catch(() => { });
948
+ const updated = {
949
+ ...entry.meta,
950
+ status: 'cleaned',
951
+ updatedAt: new Date().toISOString(),
952
+ };
953
+ entry.meta = updated;
954
+ await writeMetaAtomic(entry.metaPath, updated).catch(() => { });
955
+ }
956
+ async function teardownMemberTargetsAndNetwork(agentSessionId) {
957
+ const targetsMap = memberTargets.get(agentSessionId);
958
+ if (targetsMap && targetsMap.size > 0) {
959
+ const entries = [...targetsMap.values()];
960
+ targetsMap.clear();
961
+ await Promise.all(entries.map((entry) => finalizeTargetEntry(entry)));
962
+ }
963
+ memberTargets.delete(agentSessionId);
964
+ const networkState = memberNetworks.get(agentSessionId);
965
+ if (networkState) {
966
+ for (const containerId of networkState.connectedContainers) {
967
+ await runner.disconnectNetwork?.(networkState.networkName, containerId).catch(() => { });
968
+ }
969
+ networkState.connectedContainers.clear();
970
+ await runner.removeNetwork?.(networkState.networkName).catch(() => { });
971
+ memberNetworks.delete(agentSessionId);
972
+ }
973
+ }
974
+ async function teardownRunTargetsAndNetwork(runId) {
975
+ const ownerIds = new Set();
976
+ for (const id of runMemberSessions.get(runId) ?? [])
977
+ ownerIds.add(id);
978
+ for (const [ownerId, net] of memberNetworks.entries()) {
979
+ if (net.runId === runId)
980
+ ownerIds.add(ownerId);
981
+ }
982
+ for (const [ownerId, targetsMap] of memberTargets.entries()) {
983
+ for (const entry of targetsMap.values()) {
984
+ if (entry.runId === runId) {
985
+ ownerIds.add(ownerId);
986
+ break;
987
+ }
988
+ }
989
+ }
990
+ await Promise.all([...ownerIds].map((ownerId) => teardownMemberTargetsAndNetwork(ownerId)));
991
+ }
992
+ async function finalizeEntry(agentSessionId, terminalStatus) {
993
+ const quotaEntry = quotaExceededSessions.get(agentSessionId)?.entry;
994
+ quotaExceededSessions.delete(agentSessionId);
995
+ sandboxRequiredSessions.delete(agentSessionId);
996
+ const entry = sessionsByAgentSession.get(agentSessionId);
997
+ tornDownSessions.add(agentSessionId);
998
+ if (!entry) {
999
+ if (quotaEntry && sandboxConfig.retention?.mode === 'on_success' && terminalStatus === 'completed') {
1000
+ await rm(quotaEntry.session.hostWorkDir, { recursive: true, force: true }).catch(() => { });
1001
+ }
1002
+ return;
1003
+ }
1004
+ sessionsByAgentSession.delete(agentSessionId);
1005
+ const memberNetwork = memberNetworks.get(agentSessionId);
1006
+ if (memberNetwork?.connectedContainers.has(entry.session.containerId)) {
1007
+ await runner.disconnectNetwork?.(memberNetwork.networkName, entry.session.containerId).catch(() => { });
1008
+ memberNetwork.connectedContainers.delete(entry.session.containerId);
1009
+ }
1010
+ await runner.removeContainer(entry.session.containerId).catch(() => { });
1011
+ const nowIso = new Date().toISOString();
1012
+ const updated = {
1013
+ ...entry.meta,
1014
+ status: terminalStatus,
1015
+ updatedAt: nowIso,
1016
+ };
1017
+ entry.meta = updated;
1018
+ await writeMetaAtomic(entry.metaPath, updated).catch(() => { });
1019
+ if (sandboxConfig.retention?.mode === 'on_success' && terminalStatus === 'completed') {
1020
+ await rm(entry.session.hostWorkDir, { recursive: true, force: true }).catch(() => { });
1021
+ }
1022
+ }
1023
+ async function teardownWorkerInternal(runId, agentSessionId, status, visited) {
1024
+ if (visited.has(agentSessionId))
1025
+ return;
1026
+ visited.add(agentSessionId);
1027
+ const children = [...(childSessionsByParent.get(agentSessionId) ?? [])];
1028
+ for (const childId of children) {
1029
+ await teardownWorkerInternal(runId, childId, status, visited);
1030
+ }
1031
+ childSessionsByParent.delete(agentSessionId);
1032
+ const parentId = parentBySession.get(agentSessionId);
1033
+ if (parentId) {
1034
+ childSessionsByParent.get(parentId)?.delete(agentSessionId);
1035
+ parentBySession.delete(agentSessionId);
1036
+ }
1037
+ await teardownMemberTargetsAndNetwork(agentSessionId);
1038
+ const mappedStatus = status === 'completed' ? 'completed' : status === 'failed' ? 'failed' : 'cancelled';
1039
+ await finalizeEntry(agentSessionId, mappedStatus);
1040
+ runMemberSessions.get(runId)?.delete(agentSessionId);
1041
+ }
1042
+ return {
1043
+ executionBackend,
1044
+ async activate(signal) {
1045
+ if (backend === 'host' || scope === 'none') {
1046
+ state = 'disabled';
1047
+ fallbackActive = false;
1048
+ statusReason = undefined;
1049
+ return;
1050
+ }
1051
+ signal?.throwIfAborted();
1052
+ const check = await runner.checkRuntime(backend);
1053
+ if (!check.ok) {
1054
+ applyFallbackOrThrow('SANDBOX_UNAVAILABLE', check.reason ?? `Sandbox runtime "${backend}" is unavailable`);
1055
+ return;
1056
+ }
1057
+ signal?.throwIfAborted();
1058
+ const orphans = await runner
1059
+ .listManagedContainers({ 'saturn.managed': 'true', 'saturn.workspace': workspaceHash })
1060
+ .catch(() => []);
1061
+ for (const orphan of orphans) {
1062
+ await runner.removeContainer(orphan.id).catch(() => { });
1063
+ }
1064
+ const orphanNetworks = await runner
1065
+ .listManagedNetworks?.({ 'saturn.managed': 'true', 'saturn.workspace': workspaceHash })
1066
+ .catch(() => []);
1067
+ for (const orphanNet of orphanNetworks ?? []) {
1068
+ await runner.removeNetwork?.(orphanNet.name).catch(() => { });
1069
+ }
1070
+ signal?.throwIfAborted();
1071
+ if (!resolvedImage || !(await runner.hasImage(resolvedImage))) {
1072
+ applyFallbackOrThrow('SANDBOX_IMAGE_MISSING', `Sandbox image "${resolvedImage ?? '(unspecified)'}" is missing locally`);
1073
+ return;
1074
+ }
1075
+ state = 'ready';
1076
+ fallbackActive = false;
1077
+ statusReason = undefined;
1078
+ scheduleCleanupDirectories();
1079
+ if (!ttlCleanupTimer && sandboxConfig.retention?.mode === 'ttl') {
1080
+ ttlCleanupTimer = setInterval(() => {
1081
+ scheduleCleanupDirectories();
1082
+ }, 30 * 60_000);
1083
+ ttlCleanupTimer.unref?.();
1084
+ }
1085
+ },
1086
+ async ensureMainSandbox(runId, agentSessionId, sessionId) {
1087
+ await allocateMemberSandbox({
1088
+ runId,
1089
+ ...(sessionId !== undefined ? { sessionId } : {}),
1090
+ role: 'main',
1091
+ memberId: 'main',
1092
+ agentSessionId,
1093
+ sandboxProfile: 'main',
1094
+ });
1095
+ },
1096
+ async syncMainWorkspaceSubpaths(runId, subpaths, sessionId) {
1097
+ if (disposed || state !== 'ready' || fallbackActive || !containerBackend) {
1098
+ return { synced: [], skipped: [], partial: false };
1099
+ }
1100
+ const mainEntry = findMainSessionForRun(runId);
1101
+ if (!mainEntry) {
1102
+ return { synced: [], skipped: [], partial: false };
1103
+ }
1104
+ const unique = [...new Set(subpaths)];
1105
+ if (unique.length === 0) {
1106
+ return { synced: [], skipped: [], partial: false };
1107
+ }
1108
+ const effectiveSessionId = mainEntry.meta.sessionId ?? sessionId;
1109
+ const resolvedTargets = [];
1110
+ for (const rawSubpath of unique) {
1111
+ const { subpath, sourceDir } = await resolveWorkSubpathSource(root, rawSubpath, effectiveSessionId);
1112
+ const destDir = path.resolve(mainEntry.session.hostWorkDir, ...subpath.split('/'));
1113
+ if (!isContainedPath(mainEntry.session.hostWorkDir, destDir)) {
1114
+ throw new RuntimeError('SANDBOX_CONFIG_INVALID', `Worker workSubpath escapes main sandbox workDir: ${rawSubpath}`);
1115
+ }
1116
+ resolvedTargets.push({ subpath, sourceDir, destDir });
1117
+ }
1118
+ const budgetBytes = softLimitBytes !== undefined ? Math.floor(softLimitBytes * 0.85) : undefined;
1119
+ let usedBytes = budgetBytes !== undefined ? await computeDirectoryBytes(mainEntry.session.hostWorkDir) : 0;
1120
+ const synced = [];
1121
+ const skipped = [];
1122
+ let partial = false;
1123
+ for (const { subpath, sourceDir, destDir } of resolvedTargets) {
1124
+ if (budgetBytes !== undefined && existsSync(destDir)) {
1125
+ const priorBytes = await computeDirectoryBytes(destDir);
1126
+ usedBytes = Math.max(0, usedBytes - priorBytes);
1127
+ }
1128
+ await rm(destDir, { recursive: true, force: true });
1129
+ await mkdir(destDir, { recursive: true });
1130
+ let subpathPartial = false;
1131
+ const walkSync = async (srcDir, targetDir) => {
1132
+ const entries = await readdir(srcDir, { withFileTypes: true });
1133
+ for (const entry of entries) {
1134
+ if (isExcludedSnapshotName(entry.name))
1135
+ continue;
1136
+ const srcPath = path.join(srcDir, entry.name);
1137
+ const destPath = path.join(targetDir, entry.name);
1138
+ let info;
1139
+ try {
1140
+ info = await lstat(srcPath);
1141
+ }
1142
+ catch {
1143
+ continue;
1144
+ }
1145
+ if (info.isSymbolicLink())
1146
+ continue;
1147
+ if (info.isDirectory()) {
1148
+ await mkdir(destPath, { recursive: true });
1149
+ await walkSync(srcPath, destPath);
1150
+ }
1151
+ else if (info.isFile()) {
1152
+ if (budgetBytes !== undefined && usedBytes + info.size > budgetBytes) {
1153
+ const isSmallDescription = /\.(?:md|txt)$/iu.test(entry.name) && info.size <= 1_048_576;
1154
+ if (!isSmallDescription || usedBytes + info.size > softLimitBytes) {
1155
+ subpathPartial = true;
1156
+ partial = true;
1157
+ continue;
1158
+ }
1159
+ }
1160
+ await copyFile(srcPath, destPath);
1161
+ if (process.platform !== 'win32') {
1162
+ await chmod(destPath, info.mode & 0o777).catch(() => { });
1163
+ }
1164
+ usedBytes += info.size;
1165
+ }
1166
+ }
1167
+ };
1168
+ await walkSync(sourceDir, destDir);
1169
+ synced.push(subpath);
1170
+ if (subpathPartial)
1171
+ skipped.push(subpath);
1172
+ }
1173
+ return { synced, skipped, partial };
1174
+ },
1175
+ async ensureWorkerSandbox({ runId, sessionId, memberId, agentSessionId, parentAgentSessionId, sandboxProfile = 'default', workSubpath, }) {
1176
+ await allocateMemberSandbox({
1177
+ runId,
1178
+ ...(sessionId !== undefined ? { sessionId } : {}),
1179
+ role: 'worker',
1180
+ memberId,
1181
+ agentSessionId,
1182
+ ...(parentAgentSessionId !== undefined ? { parentAgentSessionId } : {}),
1183
+ sandboxProfile,
1184
+ ...(workSubpath !== undefined ? { workSubpath } : {}),
1185
+ });
1186
+ },
1187
+ isAgentIsolated(runId, agentSessionId) {
1188
+ if (disposed ||
1189
+ state !== 'ready' ||
1190
+ fallbackActive ||
1191
+ backend === 'host' ||
1192
+ scope === 'none' ||
1193
+ tornDownSessions.has(agentSessionId)) {
1194
+ return false;
1195
+ }
1196
+ const entry = sessionsByAgentSession.get(agentSessionId);
1197
+ if (entry)
1198
+ return entry.session.runId === runId;
1199
+ return scope === 'per_run_and_worker';
1200
+ },
1201
+ async teardownWorker(runId, agentSessionId, status) {
1202
+ await teardownWorkerInternal(runId, agentSessionId, status, new Set());
1203
+ },
1204
+ async teardownRun(runId, status) {
1205
+ await teardownRunTargetsAndNetwork(runId);
1206
+ const sessionIds = [...(runMemberSessions.get(runId) ?? [])];
1207
+ const runSessionId = sessionIds
1208
+ .map((id) => sessionsByAgentSession.get(id)?.meta.sessionId)
1209
+ .find((id) => typeof id === 'string' && id.length > 0);
1210
+ const mappedStatus = status === 'completed' ? 'completed' : status === 'failed' ? 'failed' : 'cancelled';
1211
+ await Promise.all(sessionIds.map((id) => finalizeEntry(id, mappedStatus)));
1212
+ for (const id of sessionIds) {
1213
+ childSessionsByParent.delete(id);
1214
+ const parentId = parentBySession.get(id);
1215
+ if (parentId) {
1216
+ childSessionsByParent.get(parentId)?.delete(id);
1217
+ parentBySession.delete(id);
1218
+ }
1219
+ }
1220
+ runMemberSessions.delete(runId);
1221
+ runProbeContext.delete(runId);
1222
+ scheduleCleanupDirectories(resolveSandboxesBase(runSessionId));
1223
+ },
1224
+ getProbeContext(runId, agentSessionId) {
1225
+ if (backend === 'host' || scope === 'none')
1226
+ return undefined;
1227
+ const base = runId && runProbeContext.has(runId)
1228
+ ? runProbeContext.get(runId)
1229
+ : {
1230
+ backend,
1231
+ ...(resolvedImage ? { image: resolvedImage } : {}),
1232
+ containerWorkDir: '/workspace',
1233
+ ...(sandboxConfig.network ? { network: sandboxConfig.network } : {}),
1234
+ fallbackActive,
1235
+ ...(sandboxConfig.capAdd?.length ? { capAdd: sandboxConfig.capAdd } : {}),
1236
+ tmpNoexec: true,
1237
+ };
1238
+ const sessionWorkSubpath = agentSessionId
1239
+ ? sessionsByAgentSession.get(agentSessionId)?.workSubpath
1240
+ : undefined;
1241
+ return sessionWorkSubpath ? { ...base, workSubpath: sessionWorkSubpath } : base;
1242
+ },
1243
+ isTargetServicesEnabled,
1244
+ isWorkerTargetServicesEnabled,
1245
+ async startTarget(input) {
1246
+ if (!isTargetServicesEnabled() || !containerBackend || !resolvedImage) {
1247
+ throw new RuntimeError('SANDBOX_TARGET_DISABLED', 'Target service containers are only available when container sandbox and allowTargetServices are enabled');
1248
+ }
1249
+ if (!runner.startTargetContainer || !runner.inspectContainerState || !runner.getContainerLogs) {
1250
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', 'Configured container runner does not support target service containers');
1251
+ }
1252
+ const ownerEntry = resolveTargetOwner(input.runId, input.agentSessionId);
1253
+ if (ownerEntry.meta.role === 'worker' && !isWorkerTargetServicesEnabled()) {
1254
+ throw new RuntimeError('SANDBOX_TARGET_DISABLED', 'Target service containers are disabled for worker sandboxes (enable sandbox.worker_allow_target_services)');
1255
+ }
1256
+ if (ownerEntry.session.readonly) {
1257
+ throw new RuntimeError('SANDBOX_TARGET_DISABLED', 'Read-only worker sandboxes cannot launch target service containers');
1258
+ }
1259
+ const targetName = validateTargetName(input.name);
1260
+ if (typeof input.command !== 'string' || !input.command.trim() || input.command.length > 4096) {
1261
+ throw new RuntimeError('INVALID_ARGUMENTS', 'Target command must be a non-empty string (<= 4096 chars)');
1262
+ }
1263
+ if (!Number.isInteger(input.port) || input.port < 1024 || input.port > 65535) {
1264
+ throw new RuntimeError('INVALID_ARGUMENTS', 'Target port must be an integer between 1024 and 65535');
1265
+ }
1266
+ const ownerSessionId = ownerEntry.session.agentSessionId;
1267
+ const maxTargets = sandboxConfig.maxTargetsPerRun ?? 2;
1268
+ let targetsForMember = memberTargets.get(ownerSessionId);
1269
+ if (targetsForMember?.has(targetName)) {
1270
+ throw new RuntimeError('SANDBOX_TARGET_ALREADY_EXISTS', `Target container "${targetName}" is already running for member "${ownerEntry.session.memberId}"; call sandbox_target_down first`);
1271
+ }
1272
+ if ((targetsForMember?.size ?? 0) >= maxTargets) {
1273
+ throw new RuntimeError('SANDBOX_TARGET_LIMIT_EXCEEDED', `Maximum of ${maxTargets} concurrent target containers per member exceeded`);
1274
+ }
1275
+ if (activeContainerCount() >= maxConcurrentContainers) {
1276
+ throw new RuntimeError('SANDBOX_CONTAINER_LIMIT_EXCEEDED', `Maximum of ${maxConcurrentContainers} concurrent sandbox containers reached`);
1277
+ }
1278
+ const allowedCaps = sandboxConfig.allowedTargetCapabilities ?? DEFAULT_ALLOWED_TARGET_CAPABILITIES;
1279
+ const validatedCaps = validateTargetCapabilities(input.capabilities, allowedCaps);
1280
+ const readyTimeoutMs = Math.max(500, Math.min(60_000, Math.floor(input.readyTimeoutMs ?? 10_000)));
1281
+ const safeRun = sanitizeSandboxSegment(input.runId);
1282
+ const safeOwner = sanitizeSandboxSegment(ownerEntry.session.memberId);
1283
+ const runSandboxesRoot = resolveSandboxesBase(ownerEntry.meta.sessionId);
1284
+ const targetDir = path.join(runSandboxesRoot, safeRun, 'targets', safeOwner, targetName);
1285
+ const workDir = path.join(targetDir, 'work');
1286
+ const seedDir = path.join(targetDir, 'seeds');
1287
+ const metaPath = path.join(targetDir, 'meta.json');
1288
+ await snapshotWorkspaceToWorkDir(ownerEntry.session.hostWorkDir, workDir, softLimitBytes);
1289
+ if (process.platform !== 'win32' && validatedCaps.length > 0) {
1290
+ await chmod(workDir, 0o777).catch(() => { });
1291
+ }
1292
+ let reserved = true;
1293
+ reservedContainers += 1;
1294
+ let startedContainerId;
1295
+ try {
1296
+ const seedMounts = await writeSeedMounts(seedDir, input.seedFiles);
1297
+ const networkState = await ensureMemberInternalNetwork(ownerEntry);
1298
+ const posixUser = validatedCaps.length === 0 &&
1299
+ process.platform !== 'win32' &&
1300
+ containerBackend !== 'sysbox' &&
1301
+ typeof process.getuid === 'function' &&
1302
+ typeof process.getgid === 'function'
1303
+ ? `${process.getuid()}:${process.getgid()}`
1304
+ : undefined;
1305
+ const containerName = `saturn-target-${workspaceHash.slice(0, 8)}-${safeRun.slice(0, 8)}-${safeOwner.slice(0, 10)}-${targetName.slice(0, 14)}-${randomUUID().slice(0, 6)}`;
1306
+ const started = await runner.startTargetContainer({
1307
+ backend: containerBackend,
1308
+ name: containerName,
1309
+ image: resolvedImage,
1310
+ workDirHost: workDir,
1311
+ workDirContainer: '/workspace',
1312
+ networkName: networkState.networkName,
1313
+ networkAlias: targetName,
1314
+ command: input.command,
1315
+ capAdd: validatedCaps,
1316
+ allowedCapabilities: allowedCaps,
1317
+ seedMounts,
1318
+ ...(sandboxConfig.tmpfsSizeMb !== undefined ? { tmpfsSizeMb: sandboxConfig.tmpfsSizeMb } : {}),
1319
+ ...(sandboxConfig.resources ? { resources: sandboxConfig.resources } : {}),
1320
+ ...(posixUser ? { user: posixUser } : {}),
1321
+ workspaceHash,
1322
+ runId: input.runId,
1323
+ targetName,
1324
+ extraLabels: {
1325
+ 'saturn.agent_session': ownerSessionId,
1326
+ 'saturn.owner_member': ownerEntry.session.memberId,
1327
+ },
1328
+ });
1329
+ startedContainerId = started.containerId;
1330
+ const deadline = Date.now() + readyTimeoutMs;
1331
+ let running = false;
1332
+ while (true) {
1333
+ const inspected = await runner.inspectContainerState(startedContainerId);
1334
+ if (inspected.running) {
1335
+ running = true;
1336
+ break;
1337
+ }
1338
+ if (inspected.exists &&
1339
+ inspected.status &&
1340
+ inspected.status !== 'created' &&
1341
+ inspected.status !== 'restarting') {
1342
+ const logResult = await runner
1343
+ .getContainerLogs(startedContainerId, { tailLines: 40, maxBytes: 8192 })
1344
+ .catch(() => ({ logs: '', truncated: false }));
1345
+ throw new RuntimeError('SANDBOX_TARGET_EXITED', `Target container "${targetName}" exited prematurely (status=${inspected.status}, exitCode=${inspected.exitCode ?? 'unknown'})${logResult.logs ? `\n${logResult.logs}` : ''}`);
1346
+ }
1347
+ if (Date.now() >= deadline) {
1348
+ break;
1349
+ }
1350
+ await new Promise((resolve) => setTimeout(resolve, 100));
1351
+ }
1352
+ if (!running) {
1353
+ const logResult = await runner
1354
+ .getContainerLogs(startedContainerId, { tailLines: 40, maxBytes: 8192 })
1355
+ .catch(() => ({ logs: '', truncated: false }));
1356
+ throw new RuntimeError('SANDBOX_TARGET_START_TIMEOUT', `Target container "${targetName}" did not become ready within ${readyTimeoutMs}ms${logResult.logs ? `\n${logResult.logs}` : ''}`);
1357
+ }
1358
+ const initialLogResult = await runner
1359
+ .getContainerLogs(startedContainerId, { tailLines: 40, maxBytes: 8192 })
1360
+ .catch(() => ({ logs: '', truncated: false }));
1361
+ const nowIso = new Date().toISOString();
1362
+ const ttlHours = sandboxConfig.retention?.mode === 'ttl' ? (sandboxConfig.retention.ttlHours ?? 24) : undefined;
1363
+ const meta = {
1364
+ version: 1,
1365
+ workspaceRoot: root,
1366
+ workspaceHash,
1367
+ runId: input.runId,
1368
+ role: 'target',
1369
+ memberId: `target:${targetName}`,
1370
+ agentSessionId: ownerSessionId,
1371
+ sandboxProfile: 'target',
1372
+ backend,
1373
+ image: resolvedImage,
1374
+ containerId: startedContainerId,
1375
+ containerName,
1376
+ workDir,
1377
+ readonly: false,
1378
+ network: 'internal',
1379
+ networkName: networkState.networkName,
1380
+ port: input.port,
1381
+ createdAt: nowIso,
1382
+ updatedAt: nowIso,
1383
+ ...(ttlHours !== undefined
1384
+ ? { expiresAt: new Date(Date.now() + ttlHours * 3600 * 1000).toISOString() }
1385
+ : {}),
1386
+ status: 'running',
1387
+ };
1388
+ await writeMetaAtomic(metaPath, meta);
1389
+ targetsForMember = memberTargets.get(ownerSessionId);
1390
+ if (!targetsForMember) {
1391
+ targetsForMember = new Map();
1392
+ memberTargets.set(ownerSessionId, targetsForMember);
1393
+ }
1394
+ targetsForMember.set(targetName, {
1395
+ name: targetName,
1396
+ runId: input.runId,
1397
+ ownerAgentSessionId: ownerSessionId,
1398
+ containerId: startedContainerId,
1399
+ containerName,
1400
+ networkName: networkState.networkName,
1401
+ port: input.port,
1402
+ targetDir,
1403
+ workDir,
1404
+ seedDir,
1405
+ metaPath,
1406
+ meta,
1407
+ });
1408
+ reserved = false;
1409
+ reservedContainers -= 1;
1410
+ return {
1411
+ targetId: startedContainerId,
1412
+ name: targetName,
1413
+ host: targetName,
1414
+ port: input.port,
1415
+ network: networkState.networkName,
1416
+ status: 'running',
1417
+ initialLogs: initialLogResult.logs,
1418
+ };
1419
+ }
1420
+ catch (error) {
1421
+ if (reserved) {
1422
+ reserved = false;
1423
+ reservedContainers -= 1;
1424
+ }
1425
+ if (startedContainerId) {
1426
+ await runner.removeContainer(startedContainerId).catch(() => { });
1427
+ }
1428
+ await rm(seedDir, { recursive: true, force: true }).catch(() => { });
1429
+ throw error;
1430
+ }
1431
+ },
1432
+ async stopTarget(runId, name, agentSessionId) {
1433
+ if (!isTargetServicesEnabled()) {
1434
+ throw new RuntimeError('SANDBOX_TARGET_DISABLED', 'Target service containers are not enabled for this sandbox');
1435
+ }
1436
+ const targetName = validateTargetName(name);
1437
+ const ownerId = agentSessionId ?? findMainSessionForRun(runId)?.session.agentSessionId;
1438
+ const targetsForOwner = ownerId ? memberTargets.get(ownerId) : undefined;
1439
+ const entry = targetsForOwner?.get(targetName);
1440
+ if (!entry || entry.runId !== runId) {
1441
+ throw new RuntimeError('SANDBOX_TARGET_NOT_FOUND', `No active target container named "${targetName}" in run "${runId}"`);
1442
+ }
1443
+ targetsForOwner.delete(targetName);
1444
+ if (targetsForOwner.size === 0 && ownerId)
1445
+ memberTargets.delete(ownerId);
1446
+ await finalizeTargetEntry(entry);
1447
+ return {
1448
+ targetId: entry.containerId,
1449
+ name: targetName,
1450
+ status: 'stopped',
1451
+ };
1452
+ },
1453
+ async getTargetLogs(runId, name, tailLines = 80, agentSessionId) {
1454
+ if (!isTargetServicesEnabled()) {
1455
+ throw new RuntimeError('SANDBOX_TARGET_DISABLED', 'Target service containers are not enabled for this sandbox');
1456
+ }
1457
+ if (!runner.getContainerLogs) {
1458
+ throw new RuntimeError('SANDBOX_UNAVAILABLE', 'Configured container runner does not support target container logs');
1459
+ }
1460
+ const targetName = validateTargetName(name);
1461
+ const ownerId = agentSessionId ?? findMainSessionForRun(runId)?.session.agentSessionId;
1462
+ const entry = ownerId ? memberTargets.get(ownerId)?.get(targetName) : undefined;
1463
+ if (!entry || entry.runId !== runId) {
1464
+ throw new RuntimeError('SANDBOX_TARGET_NOT_FOUND', `No active target container named "${targetName}" in run "${runId}"`);
1465
+ }
1466
+ const boundedTail = Math.max(1, Math.min(500, Math.floor(tailLines)));
1467
+ const result = await runner.getContainerLogs(entry.containerId, {
1468
+ tailLines: boundedTail,
1469
+ maxBytes: 16_384,
1470
+ });
1471
+ return {
1472
+ targetId: entry.containerId,
1473
+ name: targetName,
1474
+ logs: result.logs,
1475
+ truncated: result.truncated,
1476
+ };
1477
+ },
1478
+ status() {
1479
+ return {
1480
+ backend,
1481
+ scope,
1482
+ state,
1483
+ ...(resolvedImage ? { image: resolvedImage } : {}),
1484
+ activeContainers: sessionsByAgentSession.size + countActiveTargets(),
1485
+ fallbackActive,
1486
+ ...(statusReason ? { reason: statusReason } : {}),
1487
+ };
1488
+ },
1489
+ async dispose() {
1490
+ disposed = true;
1491
+ cleanupRequested = false;
1492
+ if (ttlCleanupTimer) {
1493
+ clearInterval(ttlCleanupTimer);
1494
+ ttlCleanupTimer = undefined;
1495
+ }
1496
+ await activeCleanup?.catch(() => { });
1497
+ const ownerIds = new Set([
1498
+ ...memberTargets.keys(),
1499
+ ...memberNetworks.keys(),
1500
+ ...sessionsByAgentSession.keys(),
1501
+ ]);
1502
+ await Promise.all([...ownerIds].map((ownerId) => teardownMemberTargetsAndNetwork(ownerId)));
1503
+ const activeIds = new Set([
1504
+ ...sessionsByAgentSession.keys(),
1505
+ ...quotaExceededSessions.keys(),
1506
+ ]);
1507
+ await Promise.all([...activeIds].map((id) => finalizeEntry(id, 'cancelled')));
1508
+ quotaExceededSessions.clear();
1509
+ sandboxRequiredSessions.clear();
1510
+ runMemberSessions.clear();
1511
+ childSessionsByParent.clear();
1512
+ parentBySession.clear();
1513
+ runProbeContext.clear();
1514
+ memberTargets.clear();
1515
+ memberNetworks.clear();
1516
+ tornDownSessions.clear();
1517
+ },
1518
+ };
1519
+ }