@agentforge-ai/sandbox 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +197 -0
- package/README.md +108 -0
- package/dist/container-pool.d.ts +89 -0
- package/dist/container-pool.js +539 -0
- package/dist/container-pool.js.map +1 -0
- package/dist/docker-sandbox.d.ts +92 -0
- package/dist/docker-sandbox.js +343 -0
- package/dist/docker-sandbox.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +701 -0
- package/dist/index.js.map +1 -0
- package/dist/sandbox-manager.d.ts +77 -0
- package/dist/sandbox-manager.js +498 -0
- package/dist/sandbox-manager.js.map +1 -0
- package/dist/security.d.ts +59 -0
- package/dist/security.js +89 -0
- package/dist/security.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
// src/docker-sandbox.ts
|
|
2
|
+
import Dockerode from "dockerode";
|
|
3
|
+
import { randomUUID } from "crypto";
|
|
4
|
+
|
|
5
|
+
// src/security.ts
|
|
6
|
+
var BLOCKED_BIND_PREFIXES = [
|
|
7
|
+
"/var/run/docker.sock",
|
|
8
|
+
"/etc",
|
|
9
|
+
"/proc",
|
|
10
|
+
"/sys",
|
|
11
|
+
"/dev",
|
|
12
|
+
"/boot",
|
|
13
|
+
"/root"
|
|
14
|
+
];
|
|
15
|
+
var DEFAULT_CAP_DROP = ["ALL"];
|
|
16
|
+
var BASE_ALLOWED_IMAGE_PREFIXES = [
|
|
17
|
+
"node:",
|
|
18
|
+
"python:",
|
|
19
|
+
"ubuntu:",
|
|
20
|
+
"debian:",
|
|
21
|
+
"alpine:",
|
|
22
|
+
"agentforge/"
|
|
23
|
+
];
|
|
24
|
+
function validateBind(bind) {
|
|
25
|
+
const hostPath = bind.split(":")[0];
|
|
26
|
+
if (!hostPath) {
|
|
27
|
+
throw new SecurityError(`Invalid bind mount spec: "${bind}"`);
|
|
28
|
+
}
|
|
29
|
+
for (const blocked of BLOCKED_BIND_PREFIXES) {
|
|
30
|
+
if (hostPath === blocked || hostPath.startsWith(blocked + "/") || hostPath.startsWith(blocked)) {
|
|
31
|
+
throw new SecurityError(
|
|
32
|
+
`Bind mount "${bind}" is blocked. Host path "${hostPath}" matches blocked prefix "${blocked}".`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function validateBinds(binds) {
|
|
38
|
+
for (const bind of binds) {
|
|
39
|
+
validateBind(bind);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function validateImageName(image) {
|
|
43
|
+
if (!image || typeof image !== "string") {
|
|
44
|
+
throw new SecurityError("Image name must be a non-empty string.");
|
|
45
|
+
}
|
|
46
|
+
if (/[;&|`$(){}[\]<>]/.test(image)) {
|
|
47
|
+
throw new SecurityError(`Image name "${image}" contains forbidden characters.`);
|
|
48
|
+
}
|
|
49
|
+
if (process.env["NODE_ENV"] !== "production") {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const extraPrefixes = (process.env["AGENTFORGE_ALLOWED_IMAGES"] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
53
|
+
const allowedPrefixes = [...BASE_ALLOWED_IMAGE_PREFIXES, ...extraPrefixes];
|
|
54
|
+
const allowed = allowedPrefixes.some((prefix) => image.startsWith(prefix));
|
|
55
|
+
if (!allowed) {
|
|
56
|
+
throw new SecurityError(
|
|
57
|
+
`Image "${image}" is not on the allow-list. Allowed prefixes: ${allowedPrefixes.join(", ")}. Add custom prefixes via AGENTFORGE_ALLOWED_IMAGES env var.`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function validateCommand(command) {
|
|
62
|
+
if (!command || typeof command !== "string") {
|
|
63
|
+
throw new SecurityError("Command must be a non-empty string.");
|
|
64
|
+
}
|
|
65
|
+
const dangerousPatterns = [
|
|
66
|
+
/docker\.sock/i,
|
|
67
|
+
/nsenter\s/i,
|
|
68
|
+
/mount\s+-t\s+proc/i
|
|
69
|
+
];
|
|
70
|
+
for (const pattern of dangerousPatterns) {
|
|
71
|
+
if (pattern.test(command)) {
|
|
72
|
+
throw new SecurityError(
|
|
73
|
+
`Command contains a potentially dangerous pattern: ${pattern.source}`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
var SecurityError = class extends Error {
|
|
79
|
+
constructor(message) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.name = "SecurityError";
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// src/docker-sandbox.ts
|
|
86
|
+
var DEFAULT_IMAGE = "node:22-slim";
|
|
87
|
+
var DEFAULT_EXEC_TIMEOUT_MS = 3e4;
|
|
88
|
+
var DEFAULT_CONTAINER_WORKSPACE = "/workspace";
|
|
89
|
+
function demuxDockerStream(buffer) {
|
|
90
|
+
let stdout = "";
|
|
91
|
+
let stderr = "";
|
|
92
|
+
let offset = 0;
|
|
93
|
+
while (offset + 8 <= buffer.length) {
|
|
94
|
+
const streamType = buffer[offset];
|
|
95
|
+
const frameSize = buffer.readUInt32BE(offset + 4);
|
|
96
|
+
offset += 8;
|
|
97
|
+
if (offset + frameSize > buffer.length) break;
|
|
98
|
+
const chunk = buffer.slice(offset, offset + frameSize).toString("utf8");
|
|
99
|
+
offset += frameSize;
|
|
100
|
+
if (streamType === 1) {
|
|
101
|
+
stdout += chunk;
|
|
102
|
+
} else if (streamType === 2) {
|
|
103
|
+
stderr += chunk;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { stdout, stderr };
|
|
107
|
+
}
|
|
108
|
+
var DockerSandbox = class {
|
|
109
|
+
config;
|
|
110
|
+
docker;
|
|
111
|
+
container = null;
|
|
112
|
+
containerId = null;
|
|
113
|
+
killTimer = null;
|
|
114
|
+
/**
|
|
115
|
+
* @param config - Sandbox configuration.
|
|
116
|
+
* @param docker - Optional pre-configured Dockerode instance (useful in tests).
|
|
117
|
+
*/
|
|
118
|
+
constructor(config, docker) {
|
|
119
|
+
const image = config.image ?? DEFAULT_IMAGE;
|
|
120
|
+
validateImageName(image);
|
|
121
|
+
if (config.binds && config.binds.length > 0) {
|
|
122
|
+
validateBinds(config.binds);
|
|
123
|
+
}
|
|
124
|
+
this.config = {
|
|
125
|
+
...config,
|
|
126
|
+
image,
|
|
127
|
+
containerWorkspacePath: config.containerWorkspacePath ?? DEFAULT_CONTAINER_WORKSPACE
|
|
128
|
+
};
|
|
129
|
+
this.docker = docker ?? new Dockerode(
|
|
130
|
+
process.env["DOCKER_HOST"] ? { host: process.env["DOCKER_HOST"] } : { socketPath: "/var/run/docker.sock" }
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
// Lifecycle
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
/**
|
|
137
|
+
* Create and start the Docker container.
|
|
138
|
+
* Idempotent — calling start() on an already-running sandbox is a no-op.
|
|
139
|
+
*/
|
|
140
|
+
async start() {
|
|
141
|
+
if (this.container) return;
|
|
142
|
+
const { image, scope, resourceLimits, binds, env, timeout, workspaceAccess, workspacePath, containerWorkspacePath } = this.config;
|
|
143
|
+
const name = `agentforge-${scope}-${randomUUID().slice(0, 8)}`;
|
|
144
|
+
const envArray = Object.entries(env ?? {}).map(([k, v]) => `${k}=${v}`);
|
|
145
|
+
const allBinds = [...binds ?? []];
|
|
146
|
+
if (workspaceAccess !== "none" && workspacePath) {
|
|
147
|
+
const mode = workspaceAccess === "ro" ? "ro" : "rw";
|
|
148
|
+
allBinds.push(`${workspacePath}:${containerWorkspacePath}:${mode}`);
|
|
149
|
+
}
|
|
150
|
+
const hostConfig = {
|
|
151
|
+
// Resource limits
|
|
152
|
+
CpuShares: resourceLimits?.cpuShares,
|
|
153
|
+
Memory: resourceLimits?.memoryMb ? resourceLimits.memoryMb * 1024 * 1024 : void 0,
|
|
154
|
+
PidsLimit: resourceLimits?.pidsLimit ?? 256,
|
|
155
|
+
// Security hardening
|
|
156
|
+
CapDrop: [...DEFAULT_CAP_DROP],
|
|
157
|
+
SecurityOpt: ["no-new-privileges:true"],
|
|
158
|
+
ReadonlyRootfs: false,
|
|
159
|
+
// Bind mounts
|
|
160
|
+
Binds: allBinds.length > 0 ? allBinds : void 0
|
|
161
|
+
};
|
|
162
|
+
this.container = await this.docker.createContainer({
|
|
163
|
+
name,
|
|
164
|
+
Image: image,
|
|
165
|
+
// Keep container alive — we run commands via exec
|
|
166
|
+
Cmd: ["/bin/sh", "-c", "while true; do sleep 3600; done"],
|
|
167
|
+
Env: envArray,
|
|
168
|
+
AttachStdin: false,
|
|
169
|
+
AttachStdout: false,
|
|
170
|
+
AttachStderr: false,
|
|
171
|
+
Tty: false,
|
|
172
|
+
NetworkDisabled: resourceLimits?.networkDisabled ?? false,
|
|
173
|
+
WorkingDir: containerWorkspacePath,
|
|
174
|
+
Labels: {
|
|
175
|
+
"agentforge.scope": scope,
|
|
176
|
+
"agentforge.managed": "true"
|
|
177
|
+
},
|
|
178
|
+
HostConfig: hostConfig
|
|
179
|
+
});
|
|
180
|
+
await this.container.start();
|
|
181
|
+
this.containerId = this.container.id;
|
|
182
|
+
if (timeout && timeout > 0) {
|
|
183
|
+
this.killTimer = setTimeout(() => {
|
|
184
|
+
void this.destroy();
|
|
185
|
+
}, timeout * 1e3);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Stop the container gracefully (10 s grace period then SIGKILL).
|
|
190
|
+
* The container is kept for potential restart.
|
|
191
|
+
*/
|
|
192
|
+
async stop() {
|
|
193
|
+
this._clearKillTimer();
|
|
194
|
+
if (!this.container) return;
|
|
195
|
+
try {
|
|
196
|
+
const info = await this.container.inspect();
|
|
197
|
+
if (info.State.Running) {
|
|
198
|
+
await this.container.stop({ t: 10 });
|
|
199
|
+
}
|
|
200
|
+
} catch {
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Destroy the container and release all resources.
|
|
205
|
+
* Safe to call multiple times.
|
|
206
|
+
*/
|
|
207
|
+
async destroy() {
|
|
208
|
+
this._clearKillTimer();
|
|
209
|
+
const container = this.container;
|
|
210
|
+
this.container = null;
|
|
211
|
+
this.containerId = null;
|
|
212
|
+
if (!container) return;
|
|
213
|
+
try {
|
|
214
|
+
await container.remove({ force: true });
|
|
215
|
+
} catch {
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// ---------------------------------------------------------------------------
|
|
219
|
+
// Execution
|
|
220
|
+
// ---------------------------------------------------------------------------
|
|
221
|
+
/**
|
|
222
|
+
* Execute a shell command inside the running container.
|
|
223
|
+
*
|
|
224
|
+
* @param command - Shell command string passed to `/bin/sh -c`.
|
|
225
|
+
* @param options - Per-call options (timeout, cwd, env overrides).
|
|
226
|
+
*/
|
|
227
|
+
async exec(command, options = {}) {
|
|
228
|
+
if (!this.container) {
|
|
229
|
+
throw new Error("DockerSandbox: container is not running. Call start() first.");
|
|
230
|
+
}
|
|
231
|
+
validateCommand(command);
|
|
232
|
+
const timeoutMs = options.timeout ?? DEFAULT_EXEC_TIMEOUT_MS;
|
|
233
|
+
const envOverride = Object.entries(options.env ?? {}).map(([k, v]) => `${k}=${v}`);
|
|
234
|
+
const execInstance = await this.container.exec({
|
|
235
|
+
Cmd: ["/bin/sh", "-c", command],
|
|
236
|
+
AttachStdout: true,
|
|
237
|
+
AttachStderr: true,
|
|
238
|
+
Tty: false,
|
|
239
|
+
WorkingDir: options.cwd,
|
|
240
|
+
Env: envOverride.length > 0 ? envOverride : void 0
|
|
241
|
+
});
|
|
242
|
+
return new Promise((resolve, reject) => {
|
|
243
|
+
const timer = setTimeout(() => {
|
|
244
|
+
reject(new Error(`DockerSandbox: exec timed out after ${timeoutMs}ms`));
|
|
245
|
+
}, timeoutMs);
|
|
246
|
+
execInstance.start({ hijack: true, stdin: false }, (err, stream) => {
|
|
247
|
+
if (err) {
|
|
248
|
+
clearTimeout(timer);
|
|
249
|
+
reject(err);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (!stream) {
|
|
253
|
+
clearTimeout(timer);
|
|
254
|
+
reject(new Error("DockerSandbox: no stream returned from exec"));
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
const chunks = [];
|
|
258
|
+
stream.on("data", (chunk) => chunks.push(chunk));
|
|
259
|
+
stream.on("end", async () => {
|
|
260
|
+
clearTimeout(timer);
|
|
261
|
+
try {
|
|
262
|
+
const raw = Buffer.concat(chunks);
|
|
263
|
+
const { stdout, stderr } = demuxDockerStream(raw);
|
|
264
|
+
const inspectResult = await execInstance.inspect();
|
|
265
|
+
const exitCode = inspectResult.ExitCode ?? 0;
|
|
266
|
+
resolve({ stdout, stderr, exitCode });
|
|
267
|
+
} catch (inspectErr) {
|
|
268
|
+
reject(inspectErr);
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
stream.on("error", (streamErr) => {
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
reject(streamErr);
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Read a file from the container filesystem by running `cat`.
|
|
280
|
+
*
|
|
281
|
+
* @param path - Absolute path inside the container.
|
|
282
|
+
*/
|
|
283
|
+
async readFile(path) {
|
|
284
|
+
const result = await this.exec(`cat "${path.replace(/"/g, '\\"')}"`);
|
|
285
|
+
if (result.exitCode !== 0) {
|
|
286
|
+
throw new Error(
|
|
287
|
+
`DockerSandbox.readFile: failed to read "${path}" (exit ${result.exitCode}): ${result.stderr}`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
return result.stdout;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Write content to a file inside the container using base64 encoding
|
|
294
|
+
* to avoid shell quoting issues.
|
|
295
|
+
*
|
|
296
|
+
* @param path - Absolute path inside the container.
|
|
297
|
+
* @param content - UTF-8 string content.
|
|
298
|
+
*/
|
|
299
|
+
async writeFile(path, content) {
|
|
300
|
+
const b64 = Buffer.from(content, "utf8").toString("base64");
|
|
301
|
+
const cmd = `printf '%s' "${b64}" | base64 -d > "${path.replace(/"/g, '\\"')}"`;
|
|
302
|
+
const result = await this.exec(cmd);
|
|
303
|
+
if (result.exitCode !== 0) {
|
|
304
|
+
throw new Error(
|
|
305
|
+
`DockerSandbox.writeFile: failed to write "${path}" (exit ${result.exitCode}): ${result.stderr}`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// ---------------------------------------------------------------------------
|
|
310
|
+
// Health
|
|
311
|
+
// ---------------------------------------------------------------------------
|
|
312
|
+
/**
|
|
313
|
+
* Returns true if the underlying Docker container is running.
|
|
314
|
+
*/
|
|
315
|
+
async isRunning() {
|
|
316
|
+
if (!this.container) return false;
|
|
317
|
+
try {
|
|
318
|
+
const info = await this.container.inspect();
|
|
319
|
+
return info.State.Running === true;
|
|
320
|
+
} catch {
|
|
321
|
+
return false;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Returns the Docker container ID or null if not yet started.
|
|
326
|
+
*/
|
|
327
|
+
getContainerId() {
|
|
328
|
+
return this.containerId;
|
|
329
|
+
}
|
|
330
|
+
// ---------------------------------------------------------------------------
|
|
331
|
+
// Private helpers
|
|
332
|
+
// ---------------------------------------------------------------------------
|
|
333
|
+
_clearKillTimer() {
|
|
334
|
+
if (this.killTimer !== null) {
|
|
335
|
+
clearTimeout(this.killTimer);
|
|
336
|
+
this.killTimer = null;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// src/container-pool.ts
|
|
342
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
343
|
+
var DEFAULT_MAX_SIZE = 3;
|
|
344
|
+
var DEFAULT_IDLE_TIMEOUT_SECONDS = 300;
|
|
345
|
+
var SWEEP_INTERVAL_MS = 3e4;
|
|
346
|
+
var ContainerPool = class {
|
|
347
|
+
config;
|
|
348
|
+
docker;
|
|
349
|
+
entries = /* @__PURE__ */ new Map();
|
|
350
|
+
sweepTimer = null;
|
|
351
|
+
draining = false;
|
|
352
|
+
constructor(config, docker) {
|
|
353
|
+
this.config = {
|
|
354
|
+
maxSize: DEFAULT_MAX_SIZE,
|
|
355
|
+
idleTimeoutSeconds: DEFAULT_IDLE_TIMEOUT_SECONDS,
|
|
356
|
+
...config
|
|
357
|
+
};
|
|
358
|
+
this.docker = docker;
|
|
359
|
+
}
|
|
360
|
+
// ---------------------------------------------------------------------------
|
|
361
|
+
// Public API
|
|
362
|
+
// ---------------------------------------------------------------------------
|
|
363
|
+
/**
|
|
364
|
+
* Pre-warm the pool up to `maxSize` containers.
|
|
365
|
+
* Resolves once all warm containers are started.
|
|
366
|
+
*/
|
|
367
|
+
async warmUp() {
|
|
368
|
+
const needed = this.config.maxSize - this.entries.size;
|
|
369
|
+
if (needed <= 0) return;
|
|
370
|
+
await Promise.all(
|
|
371
|
+
Array.from({ length: needed }).map(async () => {
|
|
372
|
+
await this._addEntry();
|
|
373
|
+
})
|
|
374
|
+
);
|
|
375
|
+
this._startSweep();
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Acquire an idle sandbox from the pool.
|
|
379
|
+
*
|
|
380
|
+
* If an idle entry is available, it is marked in-use and returned immediately.
|
|
381
|
+
* If the pool is not yet at capacity, a new container is started and returned.
|
|
382
|
+
* If the pool is at capacity and all containers are in use, the LRU idle
|
|
383
|
+
* container is evicted and a fresh one is started.
|
|
384
|
+
*
|
|
385
|
+
* @throws If the pool is draining.
|
|
386
|
+
*/
|
|
387
|
+
async acquire() {
|
|
388
|
+
if (this.draining) {
|
|
389
|
+
throw new Error("ContainerPool: pool is draining \u2014 cannot acquire new sandboxes.");
|
|
390
|
+
}
|
|
391
|
+
const idle = this._lruIdle();
|
|
392
|
+
if (idle) {
|
|
393
|
+
idle.inUse = true;
|
|
394
|
+
idle.lastUsedAt = Date.now();
|
|
395
|
+
return idle.sandbox;
|
|
396
|
+
}
|
|
397
|
+
if (this.entries.size < this.config.maxSize) {
|
|
398
|
+
const entry2 = await this._addEntry();
|
|
399
|
+
entry2.inUse = true;
|
|
400
|
+
entry2.lastUsedAt = Date.now();
|
|
401
|
+
return entry2.sandbox;
|
|
402
|
+
}
|
|
403
|
+
const lruKey = this._lruAnyKey();
|
|
404
|
+
if (lruKey) {
|
|
405
|
+
const evicted = this.entries.get(lruKey);
|
|
406
|
+
this.entries.delete(lruKey);
|
|
407
|
+
void evicted.sandbox.destroy().catch(() => {
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
const entry = await this._addEntry();
|
|
411
|
+
entry.inUse = true;
|
|
412
|
+
entry.lastUsedAt = Date.now();
|
|
413
|
+
return entry.sandbox;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Release a previously acquired sandbox back to the pool.
|
|
417
|
+
* The sandbox is reset to an idle state for future reuse.
|
|
418
|
+
*/
|
|
419
|
+
async release(sandbox) {
|
|
420
|
+
for (const entry of this.entries.values()) {
|
|
421
|
+
if (entry.sandbox === sandbox) {
|
|
422
|
+
entry.inUse = false;
|
|
423
|
+
entry.lastUsedAt = Date.now();
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
await sandbox.destroy();
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Drain the pool: stop acquiring and destroy all containers.
|
|
431
|
+
* After draining, the pool stays in a drained state and rejects new acquires.
|
|
432
|
+
*/
|
|
433
|
+
async drain() {
|
|
434
|
+
if (this.draining && this.entries.size === 0) return;
|
|
435
|
+
this.draining = true;
|
|
436
|
+
this._stopSweep();
|
|
437
|
+
await Promise.all(
|
|
438
|
+
Array.from(this.entries.values()).map(
|
|
439
|
+
(entry) => entry.sandbox.destroy().catch(() => {
|
|
440
|
+
})
|
|
441
|
+
)
|
|
442
|
+
);
|
|
443
|
+
this.entries.clear();
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Returns the current number of entries (in-use + idle).
|
|
447
|
+
*/
|
|
448
|
+
get size() {
|
|
449
|
+
return this.entries.size;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Returns the number of idle (available) entries.
|
|
453
|
+
*/
|
|
454
|
+
get idleCount() {
|
|
455
|
+
let count = 0;
|
|
456
|
+
for (const entry of this.entries.values()) {
|
|
457
|
+
if (!entry.inUse) count++;
|
|
458
|
+
}
|
|
459
|
+
return count;
|
|
460
|
+
}
|
|
461
|
+
// ---------------------------------------------------------------------------
|
|
462
|
+
// Private helpers
|
|
463
|
+
// ---------------------------------------------------------------------------
|
|
464
|
+
async _addEntry() {
|
|
465
|
+
const sandboxConfig = {
|
|
466
|
+
image: this.config.image,
|
|
467
|
+
scope: this.config.scope,
|
|
468
|
+
workspaceAccess: "none"
|
|
469
|
+
};
|
|
470
|
+
const sandbox = new DockerSandbox(sandboxConfig, this.docker);
|
|
471
|
+
await sandbox.start();
|
|
472
|
+
const id = randomUUID2();
|
|
473
|
+
const entry = {
|
|
474
|
+
sandbox,
|
|
475
|
+
createdAt: Date.now(),
|
|
476
|
+
lastUsedAt: Date.now(),
|
|
477
|
+
inUse: false
|
|
478
|
+
};
|
|
479
|
+
this.entries.set(id, entry);
|
|
480
|
+
return entry;
|
|
481
|
+
}
|
|
482
|
+
/** Return the idle entry with the smallest lastUsedAt (LRU idle). */
|
|
483
|
+
_lruIdle() {
|
|
484
|
+
let best = null;
|
|
485
|
+
for (const entry of this.entries.values()) {
|
|
486
|
+
if (!entry.inUse) {
|
|
487
|
+
if (!best || entry.lastUsedAt < best.lastUsedAt) {
|
|
488
|
+
best = entry;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return best;
|
|
493
|
+
}
|
|
494
|
+
/** Return the key of the entry with the smallest lastUsedAt (LRU any). */
|
|
495
|
+
_lruAnyKey() {
|
|
496
|
+
let bestKey = null;
|
|
497
|
+
let bestTime = Infinity;
|
|
498
|
+
for (const [key, entry] of this.entries) {
|
|
499
|
+
if (entry.lastUsedAt < bestTime) {
|
|
500
|
+
bestTime = entry.lastUsedAt;
|
|
501
|
+
bestKey = key;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return bestKey;
|
|
505
|
+
}
|
|
506
|
+
/** Start periodic idle-eviction sweep. */
|
|
507
|
+
_startSweep() {
|
|
508
|
+
if (this.sweepTimer) return;
|
|
509
|
+
this.sweepTimer = setInterval(() => void this._sweep(), SWEEP_INTERVAL_MS);
|
|
510
|
+
if (this.sweepTimer.unref) this.sweepTimer.unref();
|
|
511
|
+
}
|
|
512
|
+
_stopSweep() {
|
|
513
|
+
if (this.sweepTimer) {
|
|
514
|
+
clearInterval(this.sweepTimer);
|
|
515
|
+
this.sweepTimer = null;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/** Remove and destroy containers that have been idle past the timeout. */
|
|
519
|
+
async _sweep() {
|
|
520
|
+
if (this.draining) return;
|
|
521
|
+
const nowMs = Date.now();
|
|
522
|
+
const idleTimeoutMs = this.config.idleTimeoutSeconds * 1e3;
|
|
523
|
+
const evictions = [];
|
|
524
|
+
for (const [key, entry] of this.entries) {
|
|
525
|
+
if (!entry.inUse && nowMs - entry.lastUsedAt > idleTimeoutMs) {
|
|
526
|
+
evictions.push([key, entry]);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
for (const [key, entry] of evictions) {
|
|
530
|
+
this.entries.delete(key);
|
|
531
|
+
await entry.sandbox.destroy().catch(() => {
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
export {
|
|
537
|
+
ContainerPool
|
|
538
|
+
};
|
|
539
|
+
//# sourceMappingURL=container-pool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/docker-sandbox.ts","../src/security.ts","../src/container-pool.ts"],"sourcesContent":["/**\n * @module docker-sandbox\n *\n * DockerSandbox — a container-backed {@link SandboxProvider} for AgentForge.\n *\n * Each instance manages exactly one Docker container. The container is\n * created lazily on the first call to {@link DockerSandbox.start}, executed\n * via the Docker exec API, and destroyed via {@link DockerSandbox.destroy}.\n *\n * @example\n * ```ts\n * const sandbox = new DockerSandbox({\n * scope: 'agent',\n * workspaceAccess: 'ro',\n * workspacePath: '/home/user/project',\n * resourceLimits: { memoryMb: 512, cpuShares: 512 },\n * });\n * await sandbox.start();\n * const result = await sandbox.exec('echo hello');\n * console.log(result.stdout); // \"hello\\n\"\n * await sandbox.destroy();\n * ```\n */\n\nimport Dockerode from 'dockerode';\nimport { randomUUID } from 'node:crypto';\nimport type { DockerSandboxConfig, ExecOptions, ExecResult, SandboxProvider } from './types.js';\nimport { DEFAULT_CAP_DROP, SecurityError, validateBinds, validateCommand, validateImageName } from './security.js';\n\n/** Default Docker image used when none is specified. */\nconst DEFAULT_IMAGE = 'node:22-slim';\n\n/** Default per-exec timeout in milliseconds. */\nconst DEFAULT_EXEC_TIMEOUT_MS = 30_000;\n\n/** Default container workspace mount point. */\nconst DEFAULT_CONTAINER_WORKSPACE = '/workspace';\n\n// ---------------------------------------------------------------------------\n// Stream demuxing\n// ---------------------------------------------------------------------------\n\n/**\n * Decodes the multiplexed stream that Docker returns for exec output.\n *\n * Docker prefixes every chunk with an 8-byte header:\n * [stream_type(1)] [0(3)] [size(4 BE)]\n * where stream_type is 1 = stdout, 2 = stderr.\n */\nfunction demuxDockerStream(buffer: Buffer): { stdout: string; stderr: string } {\n let stdout = '';\n let stderr = '';\n let offset = 0;\n\n while (offset + 8 <= buffer.length) {\n const streamType = buffer[offset];\n const frameSize = buffer.readUInt32BE(offset + 4);\n offset += 8;\n\n if (offset + frameSize > buffer.length) break;\n\n const chunk = buffer.slice(offset, offset + frameSize).toString('utf8');\n offset += frameSize;\n\n if (streamType === 1) {\n stdout += chunk;\n } else if (streamType === 2) {\n stderr += chunk;\n }\n }\n\n return { stdout, stderr };\n}\n\n// ---------------------------------------------------------------------------\n// DockerSandbox\n// ---------------------------------------------------------------------------\n\n/**\n * Container-based sandbox using the Docker engine.\n *\n * Implements the {@link SandboxProvider} interface for full lifecycle\n * management, command execution, and file I/O within an isolated container.\n */\nexport class DockerSandbox implements SandboxProvider {\n private readonly config: Required<\n Pick<DockerSandboxConfig, 'scope' | 'workspaceAccess' | 'image' | 'containerWorkspacePath'>\n > &\n DockerSandboxConfig;\n\n private readonly docker: Dockerode;\n private container: Dockerode.Container | null = null;\n private containerId: string | null = null;\n private killTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param config - Sandbox configuration.\n * @param docker - Optional pre-configured Dockerode instance (useful in tests).\n */\n constructor(config: DockerSandboxConfig, docker?: Dockerode) {\n // Validate security constraints eagerly\n const image = config.image ?? DEFAULT_IMAGE;\n validateImageName(image);\n\n if (config.binds && config.binds.length > 0) {\n validateBinds(config.binds);\n }\n\n this.config = {\n ...config,\n image,\n containerWorkspacePath: config.containerWorkspacePath ?? DEFAULT_CONTAINER_WORKSPACE,\n };\n\n this.docker =\n docker ??\n new Dockerode(\n process.env['DOCKER_HOST']\n ? { host: process.env['DOCKER_HOST'] }\n : { socketPath: '/var/run/docker.sock' },\n );\n }\n\n // ---------------------------------------------------------------------------\n // Lifecycle\n // ---------------------------------------------------------------------------\n\n /**\n * Create and start the Docker container.\n * Idempotent — calling start() on an already-running sandbox is a no-op.\n */\n async start(): Promise<void> {\n if (this.container) return;\n\n const { image, scope, resourceLimits, binds, env, timeout, workspaceAccess, workspacePath, containerWorkspacePath } = this.config;\n\n const name = `agentforge-${scope}-${randomUUID().slice(0, 8)}`;\n\n const envArray = Object.entries(env ?? {}).map(([k, v]) => `${k}=${v}`);\n\n // Build bind mounts\n const allBinds: string[] = [...(binds ?? [])];\n\n // Mount workspace if configured\n if (workspaceAccess !== 'none' && workspacePath) {\n const mode = workspaceAccess === 'ro' ? 'ro' : 'rw';\n allBinds.push(`${workspacePath}:${containerWorkspacePath}:${mode}`);\n }\n\n const hostConfig: Dockerode.HostConfig = {\n // Resource limits\n CpuShares: resourceLimits?.cpuShares,\n Memory: resourceLimits?.memoryMb ? resourceLimits.memoryMb * 1024 * 1024 : undefined,\n PidsLimit: resourceLimits?.pidsLimit ?? 256,\n\n // Security hardening\n CapDrop: [...DEFAULT_CAP_DROP],\n SecurityOpt: ['no-new-privileges:true'],\n ReadonlyRootfs: false,\n\n // Bind mounts\n Binds: allBinds.length > 0 ? allBinds : undefined,\n };\n\n this.container = await this.docker.createContainer({\n name,\n Image: image,\n // Keep container alive — we run commands via exec\n Cmd: ['/bin/sh', '-c', 'while true; do sleep 3600; done'],\n Env: envArray,\n AttachStdin: false,\n AttachStdout: false,\n AttachStderr: false,\n Tty: false,\n NetworkDisabled: resourceLimits?.networkDisabled ?? false,\n WorkingDir: containerWorkspacePath,\n Labels: {\n 'agentforge.scope': scope,\n 'agentforge.managed': 'true',\n },\n HostConfig: hostConfig,\n });\n\n await this.container.start();\n this.containerId = this.container.id;\n\n // Auto-kill after configured timeout\n if (timeout && timeout > 0) {\n this.killTimer = setTimeout(() => {\n void this.destroy();\n }, timeout * 1000);\n }\n }\n\n /**\n * Stop the container gracefully (10 s grace period then SIGKILL).\n * The container is kept for potential restart.\n */\n async stop(): Promise<void> {\n this._clearKillTimer();\n if (!this.container) return;\n\n try {\n const info = await this.container.inspect();\n if (info.State.Running) {\n await this.container.stop({ t: 10 });\n }\n } catch {\n // Container may already be stopped — ignore\n }\n }\n\n /**\n * Destroy the container and release all resources.\n * Safe to call multiple times.\n */\n async destroy(): Promise<void> {\n this._clearKillTimer();\n const container = this.container;\n this.container = null;\n this.containerId = null;\n\n if (!container) return;\n\n try {\n await container.remove({ force: true });\n } catch {\n // Already gone — ignore\n }\n }\n\n // ---------------------------------------------------------------------------\n // Execution\n // ---------------------------------------------------------------------------\n\n /**\n * Execute a shell command inside the running container.\n *\n * @param command - Shell command string passed to `/bin/sh -c`.\n * @param options - Per-call options (timeout, cwd, env overrides).\n */\n async exec(command: string, options: ExecOptions = {}): Promise<ExecResult> {\n if (!this.container) {\n throw new Error('DockerSandbox: container is not running. Call start() first.');\n }\n\n // Defense-in-depth command validation\n validateCommand(command);\n\n const timeoutMs = options.timeout ?? DEFAULT_EXEC_TIMEOUT_MS;\n const envOverride = Object.entries(options.env ?? {}).map(([k, v]) => `${k}=${v}`);\n\n const execInstance = await this.container.exec({\n Cmd: ['/bin/sh', '-c', command],\n AttachStdout: true,\n AttachStderr: true,\n Tty: false,\n WorkingDir: options.cwd,\n Env: envOverride.length > 0 ? envOverride : undefined,\n });\n\n return new Promise<ExecResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`DockerSandbox: exec timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n execInstance.start({ hijack: true, stdin: false }, (err, stream) => {\n if (err) {\n clearTimeout(timer);\n reject(err);\n return;\n }\n\n if (!stream) {\n clearTimeout(timer);\n reject(new Error('DockerSandbox: no stream returned from exec'));\n return;\n }\n\n const chunks: Buffer[] = [];\n\n stream.on('data', (chunk: Buffer) => chunks.push(chunk));\n\n stream.on('end', async () => {\n clearTimeout(timer);\n try {\n const raw = Buffer.concat(chunks);\n const { stdout, stderr } = demuxDockerStream(raw);\n\n // Inspect exec to get exit code\n const inspectResult = await execInstance.inspect();\n const exitCode = inspectResult.ExitCode ?? 0;\n\n resolve({ stdout, stderr, exitCode });\n } catch (inspectErr) {\n reject(inspectErr);\n }\n });\n\n stream.on('error', (streamErr: Error) => {\n clearTimeout(timer);\n reject(streamErr);\n });\n });\n });\n }\n\n /**\n * Read a file from the container filesystem by running `cat`.\n *\n * @param path - Absolute path inside the container.\n */\n async readFile(path: string): Promise<string> {\n const result = await this.exec(`cat \"${path.replace(/\"/g, '\\\\\"')}\"`);\n if (result.exitCode !== 0) {\n throw new Error(\n `DockerSandbox.readFile: failed to read \"${path}\" (exit ${result.exitCode}): ${result.stderr}`,\n );\n }\n return result.stdout;\n }\n\n /**\n * Write content to a file inside the container using base64 encoding\n * to avoid shell quoting issues.\n *\n * @param path - Absolute path inside the container.\n * @param content - UTF-8 string content.\n */\n async writeFile(path: string, content: string): Promise<void> {\n const b64 = Buffer.from(content, 'utf8').toString('base64');\n const cmd = `printf '%s' \"${b64}\" | base64 -d > \"${path.replace(/\"/g, '\\\\\"')}\"`;\n const result = await this.exec(cmd);\n if (result.exitCode !== 0) {\n throw new Error(\n `DockerSandbox.writeFile: failed to write \"${path}\" (exit ${result.exitCode}): ${result.stderr}`,\n );\n }\n }\n\n // ---------------------------------------------------------------------------\n // Health\n // ---------------------------------------------------------------------------\n\n /**\n * Returns true if the underlying Docker container is running.\n */\n async isRunning(): Promise<boolean> {\n if (!this.container) return false;\n try {\n const info = await this.container.inspect();\n return info.State.Running === true;\n } catch {\n return false;\n }\n }\n\n /**\n * Returns the Docker container ID or null if not yet started.\n */\n getContainerId(): string | null {\n return this.containerId;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private _clearKillTimer(): void {\n if (this.killTimer !== null) {\n clearTimeout(this.killTimer);\n this.killTimer = null;\n }\n }\n}\n","/**\n * @module security\n *\n * Security helpers for the Docker sandbox implementation.\n *\n * Centralised in one module so policy changes propagate everywhere.\n * All validation functions throw {@link SecurityError} on violations.\n */\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Host-side paths that must never be bind-mounted into a sandbox container.\n * Mounting these paths would allow container-escape or privilege escalation.\n */\nexport const BLOCKED_BIND_PREFIXES: readonly string[] = [\n '/var/run/docker.sock',\n '/etc',\n '/proc',\n '/sys',\n '/dev',\n '/boot',\n '/root',\n];\n\n/**\n * Linux capabilities dropped by default for every sandbox container.\n * We start with no capabilities at all (drop \"ALL\") then add nothing back.\n */\nexport const DEFAULT_CAP_DROP: readonly string[] = ['ALL'];\n\n/**\n * Allowed image name patterns (non-arbitrary image names in production).\n * Only images that match one of these prefixes are permitted.\n * In test / dev the list can be extended via AGENTFORGE_ALLOWED_IMAGES env var.\n */\nconst BASE_ALLOWED_IMAGE_PREFIXES: readonly string[] = [\n 'node:',\n 'python:',\n 'ubuntu:',\n 'debian:',\n 'alpine:',\n 'agentforge/',\n];\n\n// ---------------------------------------------------------------------------\n// Validation functions\n// ---------------------------------------------------------------------------\n\n/**\n * Throws if the provided bind-mount spec contains a blocked host path.\n *\n * @param bind - A bind-mount spec in `host:container[:mode]` format.\n * @throws {SecurityError} when the host path is on the block-list.\n */\nexport function validateBind(bind: string): void {\n const hostPath = bind.split(':')[0];\n if (!hostPath) {\n throw new SecurityError(`Invalid bind mount spec: \"${bind}\"`);\n }\n\n for (const blocked of BLOCKED_BIND_PREFIXES) {\n if (hostPath === blocked || hostPath.startsWith(blocked + '/') || hostPath.startsWith(blocked)) {\n throw new SecurityError(\n `Bind mount \"${bind}\" is blocked. Host path \"${hostPath}\" matches blocked prefix \"${blocked}\".`,\n );\n }\n }\n}\n\n/**\n * Validate all bind mounts in the provided array.\n * @throws {SecurityError} on the first violation found.\n */\nexport function validateBinds(binds: string[]): void {\n for (const bind of binds) {\n validateBind(bind);\n }\n}\n\n/**\n * Validate that an image name is on the allow-list.\n *\n * In production (NODE_ENV === 'production') only known safe images are allowed.\n * In development/test any image name that passes format validation is accepted.\n *\n * Additional allowed prefixes can be injected via the\n * `AGENTFORGE_ALLOWED_IMAGES` env var (comma-separated prefixes).\n *\n * @param image - Docker image name, e.g. `node:22-slim`.\n * @throws {SecurityError} if the image is not permitted.\n */\nexport function validateImageName(image: string): void {\n if (!image || typeof image !== 'string') {\n throw new SecurityError('Image name must be a non-empty string.');\n }\n\n // Reject obviously dangerous patterns (shell metacharacters)\n if (/[;&|`$(){}[\\]<>]/.test(image)) {\n throw new SecurityError(`Image name \"${image}\" contains forbidden characters.`);\n }\n\n if (process.env['NODE_ENV'] !== 'production') {\n // In dev/test, just ensure the name is a plausible Docker image reference\n return;\n }\n\n // Build the full allow-list (base + env-configured extras)\n const extraPrefixes = (process.env['AGENTFORGE_ALLOWED_IMAGES'] ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n\n const allowedPrefixes = [...BASE_ALLOWED_IMAGE_PREFIXES, ...extraPrefixes];\n\n const allowed = allowedPrefixes.some((prefix) => image.startsWith(prefix));\n if (!allowed) {\n throw new SecurityError(\n `Image \"${image}\" is not on the allow-list. ` +\n `Allowed prefixes: ${allowedPrefixes.join(', ')}. ` +\n `Add custom prefixes via AGENTFORGE_ALLOWED_IMAGES env var.`,\n );\n }\n}\n\n/**\n * Validate that a command does not contain obvious escape attempts.\n * This is a defense-in-depth measure — the container itself is the primary boundary.\n *\n * @param command - The shell command to validate.\n * @throws {SecurityError} if the command contains dangerous patterns.\n */\nexport function validateCommand(command: string): void {\n if (!command || typeof command !== 'string') {\n throw new SecurityError('Command must be a non-empty string.');\n }\n\n // Block attempts to access the Docker socket from within the container\n const dangerousPatterns = [\n /docker\\.sock/i,\n /nsenter\\s/i,\n /mount\\s+-t\\s+proc/i,\n ];\n\n for (const pattern of dangerousPatterns) {\n if (pattern.test(command)) {\n throw new SecurityError(\n `Command contains a potentially dangerous pattern: ${pattern.source}`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error class\n// ---------------------------------------------------------------------------\n\n/**\n * A structured error type for sandbox security violations.\n */\nexport class SecurityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SecurityError';\n }\n}\n","/**\n * @module container-pool\n *\n * ContainerPool — maintains a pool of warm {@link DockerSandbox} instances\n * to amortise container cold-start latency.\n *\n * Design:\n * - A fixed-size pool of pre-started containers (warm slots).\n * - {@link ContainerPool.acquire} returns the least-recently-used idle\n * container or starts a new one if the pool has not yet reached capacity.\n * - {@link ContainerPool.release} marks a container as idle so it can be reused.\n * - An idle-eviction sweep runs periodically and destroys containers that have\n * been idle longer than `idleTimeoutSeconds`.\n * - LRU eviction is applied when the pool is at capacity and a new container is\n * requested but none are idle.\n */\n\nimport type Dockerode from 'dockerode';\nimport { DockerSandbox } from './docker-sandbox.js';\nimport type { DockerSandboxConfig, PoolConfig, PoolEntry, SandboxProvider } from './types.js';\nimport { randomUUID } from 'node:crypto';\n\nconst DEFAULT_MAX_SIZE = 3;\nconst DEFAULT_IDLE_TIMEOUT_SECONDS = 300;\nconst SWEEP_INTERVAL_MS = 30_000;\n\n/**\n * A pool of warm Docker containers that can be acquired and released for reuse.\n *\n * @example\n * ```ts\n * const pool = new ContainerPool({ image: 'node:22-slim', scope: 'agent' });\n * await pool.warmUp();\n *\n * const sb = await pool.acquire();\n * await sb.exec('node -e \"console.log(1+1)\"');\n * await pool.release(sb);\n *\n * await pool.drain();\n * ```\n */\nexport class ContainerPool {\n private readonly config: Required<PoolConfig>;\n private readonly docker?: Dockerode;\n private readonly entries: Map<string, PoolEntry> = new Map();\n private sweepTimer: ReturnType<typeof setInterval> | null = null;\n private draining = false;\n\n constructor(config: PoolConfig, docker?: Dockerode) {\n this.config = {\n maxSize: DEFAULT_MAX_SIZE,\n idleTimeoutSeconds: DEFAULT_IDLE_TIMEOUT_SECONDS,\n ...config,\n };\n this.docker = docker;\n }\n\n // ---------------------------------------------------------------------------\n // Public API\n // ---------------------------------------------------------------------------\n\n /**\n * Pre-warm the pool up to `maxSize` containers.\n * Resolves once all warm containers are started.\n */\n async warmUp(): Promise<void> {\n const needed = this.config.maxSize - this.entries.size;\n if (needed <= 0) return;\n\n await Promise.all(\n Array.from({ length: needed }).map(async () => {\n await this._addEntry();\n }),\n );\n\n this._startSweep();\n }\n\n /**\n * Acquire an idle sandbox from the pool.\n *\n * If an idle entry is available, it is marked in-use and returned immediately.\n * If the pool is not yet at capacity, a new container is started and returned.\n * If the pool is at capacity and all containers are in use, the LRU idle\n * container is evicted and a fresh one is started.\n *\n * @throws If the pool is draining.\n */\n async acquire(): Promise<SandboxProvider> {\n if (this.draining) {\n throw new Error('ContainerPool: pool is draining — cannot acquire new sandboxes.');\n }\n\n // 1. Find an idle entry (LRU = smallest lastUsedAt)\n const idle = this._lruIdle();\n if (idle) {\n idle.inUse = true;\n idle.lastUsedAt = Date.now();\n return idle.sandbox;\n }\n\n // 2. Pool has spare capacity — start a fresh container\n if (this.entries.size < this.config.maxSize) {\n const entry = await this._addEntry();\n entry.inUse = true;\n entry.lastUsedAt = Date.now();\n return entry.sandbox;\n }\n\n // 3. Pool at capacity, all in use — evict LRU entry and replace\n const lruKey = this._lruAnyKey();\n if (lruKey) {\n const evicted = this.entries.get(lruKey)!;\n this.entries.delete(lruKey);\n void evicted.sandbox.destroy().catch(() => {/* best-effort */});\n }\n\n const entry = await this._addEntry();\n entry.inUse = true;\n entry.lastUsedAt = Date.now();\n return entry.sandbox;\n }\n\n /**\n * Release a previously acquired sandbox back to the pool.\n * The sandbox is reset to an idle state for future reuse.\n */\n async release(sandbox: SandboxProvider): Promise<void> {\n for (const entry of this.entries.values()) {\n if (entry.sandbox === sandbox) {\n entry.inUse = false;\n entry.lastUsedAt = Date.now();\n return;\n }\n }\n // Sandbox not found in pool — destroy it to avoid leaks\n await sandbox.destroy();\n }\n\n /**\n * Drain the pool: stop acquiring and destroy all containers.\n * After draining, the pool stays in a drained state and rejects new acquires.\n */\n async drain(): Promise<void> {\n if (this.draining && this.entries.size === 0) return;\n this.draining = true;\n this._stopSweep();\n\n await Promise.all(\n Array.from(this.entries.values()).map((entry) =>\n entry.sandbox.destroy().catch(() => {/* best-effort */}),\n ),\n );\n this.entries.clear();\n }\n\n /**\n * Returns the current number of entries (in-use + idle).\n */\n get size(): number {\n return this.entries.size;\n }\n\n /**\n * Returns the number of idle (available) entries.\n */\n get idleCount(): number {\n let count = 0;\n for (const entry of this.entries.values()) {\n if (!entry.inUse) count++;\n }\n return count;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private async _addEntry(): Promise<PoolEntry> {\n const sandboxConfig: DockerSandboxConfig = {\n image: this.config.image,\n scope: this.config.scope,\n workspaceAccess: 'none',\n };\n\n const sandbox = new DockerSandbox(sandboxConfig, this.docker);\n await sandbox.start();\n\n const id = randomUUID();\n const entry: PoolEntry = {\n sandbox,\n createdAt: Date.now(),\n lastUsedAt: Date.now(),\n inUse: false,\n };\n\n this.entries.set(id, entry);\n return entry;\n }\n\n /** Return the idle entry with the smallest lastUsedAt (LRU idle). */\n private _lruIdle(): PoolEntry | null {\n let best: PoolEntry | null = null;\n for (const entry of this.entries.values()) {\n if (!entry.inUse) {\n if (!best || entry.lastUsedAt < best.lastUsedAt) {\n best = entry;\n }\n }\n }\n return best;\n }\n\n /** Return the key of the entry with the smallest lastUsedAt (LRU any). */\n private _lruAnyKey(): string | null {\n let bestKey: string | null = null;\n let bestTime = Infinity;\n for (const [key, entry] of this.entries) {\n if (entry.lastUsedAt < bestTime) {\n bestTime = entry.lastUsedAt;\n bestKey = key;\n }\n }\n return bestKey;\n }\n\n /** Start periodic idle-eviction sweep. */\n private _startSweep(): void {\n if (this.sweepTimer) return;\n this.sweepTimer = setInterval(() => void this._sweep(), SWEEP_INTERVAL_MS);\n if (this.sweepTimer.unref) this.sweepTimer.unref();\n }\n\n private _stopSweep(): void {\n if (this.sweepTimer) {\n clearInterval(this.sweepTimer);\n this.sweepTimer = null;\n }\n }\n\n /** Remove and destroy containers that have been idle past the timeout. */\n private async _sweep(): Promise<void> {\n if (this.draining) return;\n\n const nowMs = Date.now();\n const idleTimeoutMs = this.config.idleTimeoutSeconds * 1000;\n\n const evictions: [string, PoolEntry][] = [];\n\n for (const [key, entry] of this.entries) {\n if (!entry.inUse && nowMs - entry.lastUsedAt > idleTimeoutMs) {\n evictions.push([key, entry]);\n }\n }\n\n for (const [key, entry] of evictions) {\n this.entries.delete(key);\n await entry.sandbox.destroy().catch(() => {/* best-effort */});\n }\n }\n}\n"],"mappings":";AAwBA,OAAO,eAAe;AACtB,SAAS,kBAAkB;;;ACRpB,IAAM,wBAA2C;AAAA,E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