@capybara-hq/plugin-device-docker 0.0.0-stage → 0.1.0-rc.21

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/dist/index.mjs ADDED
@@ -0,0 +1,2451 @@
1
+ import { createRequire as __capybaraCreateRequire } from "node:module";
2
+ import { fileURLToPath as __capybaraFileURLToPath } from "node:url";
3
+ import { dirname as __capybaraPathDirname } from "node:path";
4
+ const require = __capybaraCreateRequire(import.meta.url);
5
+ const __capybara_filename = __capybaraFileURLToPath(import.meta.url);
6
+ const __capybara_dirname = __capybaraPathDirname(__capybara_filename);
7
+
8
+ // src/index.ts
9
+ import { DEVICE_PROVIDER_EXTENSION_POINT, defineExtension, ui } from "@capybara-hq/plugin-sdk";
10
+ import { z } from "zod";
11
+
12
+ // src/provider.ts
13
+ import { randomUUID } from "node:crypto";
14
+ import { isIP } from "node:net";
15
+ import { networkInterfaces } from "node:os";
16
+ import {
17
+ FileSystemGoneError,
18
+ SANDBOX_TAG_RE,
19
+ SandboxGoneError,
20
+ validateAllowHost,
21
+ validateSandboxPathShape as validateSandboxPathShape3
22
+ } from "@capybara-hq/plugin-sdk";
23
+
24
+ // src/docker-api.ts
25
+ import { request } from "node:http";
26
+ var DOCKER_API_VERSION = "v1.44";
27
+ var MAX_BODY_BYTES = 4 * 1024 * 1024;
28
+ var DockerApiError = class extends Error {
29
+ constructor(status, message) {
30
+ super(message);
31
+ this.status = status;
32
+ this.name = "DockerApiError";
33
+ }
34
+ status;
35
+ };
36
+ var isStatus = (e, ...status) => e instanceof DockerApiError && status.includes(e.status);
37
+ function parseEndpoint(endpoint) {
38
+ if (endpoint.startsWith("unix://")) {
39
+ const socketPath = endpoint.slice("unix://".length);
40
+ if (!socketPath.startsWith("/")) throw new Error(`invalid unix endpoint: ${endpoint}`);
41
+ return { socketPath };
42
+ }
43
+ const m = endpoint.match(/^tcp:\/\/(\[[^\]]+\]|[^:/]+):(\d{1,5})\/?$/);
44
+ if (!m)
45
+ throw new Error(`invalid endpoint (expected tcp://host:port or unix:///path): ${endpoint}`);
46
+ return { host: m[1].replace(/^\[|\]$/g, ""), port: Number(m[2]) };
47
+ }
48
+ function readBody(res, signal) {
49
+ return new Promise((resolve, reject) => {
50
+ const chunks = [];
51
+ let size = 0;
52
+ const onAbort = () => {
53
+ res.destroy();
54
+ reject(abortReason(signal));
55
+ };
56
+ signal.addEventListener("abort", onAbort, { once: true });
57
+ res.on("data", (c) => {
58
+ size += c.byteLength;
59
+ if (size <= MAX_BODY_BYTES) chunks.push(c);
60
+ });
61
+ res.on("end", () => {
62
+ signal.removeEventListener("abort", onAbort);
63
+ resolve(Buffer.concat(chunks));
64
+ });
65
+ res.on("error", (e) => {
66
+ signal.removeEventListener("abort", onAbort);
67
+ reject(e);
68
+ });
69
+ });
70
+ }
71
+ function abortReason(signal) {
72
+ return signal.reason instanceof Error ? signal.reason : new Error("aborted");
73
+ }
74
+ function errorMessage(status, body) {
75
+ try {
76
+ const j = JSON.parse(body.toString("utf8"));
77
+ if (typeof j.message === "string") return j.message;
78
+ } catch {
79
+ }
80
+ return body.toString("utf8").trim() || `HTTP ${status}`;
81
+ }
82
+ function createDockerClient(endpoint) {
83
+ const target = parseEndpoint(endpoint);
84
+ const pathOf = (path, query) => {
85
+ const qs = new URLSearchParams();
86
+ for (const [k, v] of Object.entries(query ?? {})) if (v !== void 0) qs.set(k, String(v));
87
+ const s = qs.toString();
88
+ return `/${DOCKER_API_VERSION}${path}${s === "" ? "" : `?${s}`}`;
89
+ };
90
+ return {
91
+ json(method, path, opts) {
92
+ opts.signal.throwIfAborted();
93
+ const payload = opts.body === void 0 ? void 0 : Buffer.from(JSON.stringify(opts.body));
94
+ return new Promise((resolve, reject) => {
95
+ const req = request({
96
+ ...target,
97
+ method,
98
+ path: pathOf(path, opts.query),
99
+ // A fresh connection per request: the socket proxy closes idle keep-alive connections
100
+ // (HAProxy's `timeout http-request 30s` also bounds keep-alive idle time), and reusing
101
+ // one fails with "socket hang up".
102
+ agent: false,
103
+ headers: {
104
+ ...payload && {
105
+ "content-type": "application/json",
106
+ "content-length": payload.byteLength
107
+ }
108
+ },
109
+ signal: opts.signal
110
+ });
111
+ req.on("error", (e) => reject(opts.signal.aborted ? abortReason(opts.signal) : e));
112
+ req.on("response", (res) => {
113
+ readBody(res, opts.signal).then((body) => {
114
+ const status = res.statusCode ?? 0;
115
+ if (status < 200 || status >= 300) {
116
+ reject(new DockerApiError(status, errorMessage(status, body)));
117
+ return;
118
+ }
119
+ const text = body.toString("utf8").trim();
120
+ if (text === "") {
121
+ resolve(void 0);
122
+ return;
123
+ }
124
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
125
+ try {
126
+ let last;
127
+ for (const l of lines) {
128
+ last = JSON.parse(l);
129
+ const err = last.error;
130
+ if (typeof err === "string") {
131
+ reject(new DockerApiError(500, err));
132
+ return;
133
+ }
134
+ }
135
+ resolve(last);
136
+ } catch {
137
+ resolve(text);
138
+ }
139
+ }, reject);
140
+ });
141
+ req.end(payload);
142
+ });
143
+ },
144
+ hijack(path, body, signal) {
145
+ signal.throwIfAborted();
146
+ const payload = Buffer.from(JSON.stringify(body));
147
+ return new Promise((resolve, reject) => {
148
+ const req = request({
149
+ ...target,
150
+ method: "POST",
151
+ path: pathOf(path),
152
+ headers: {
153
+ "content-type": "application/json",
154
+ "content-length": payload.byteLength,
155
+ connection: "Upgrade",
156
+ upgrade: "tcp"
157
+ }
158
+ });
159
+ const onAbort = () => req.destroy(abortReason(signal));
160
+ signal.addEventListener("abort", onAbort, { once: true });
161
+ const done = () => signal.removeEventListener("abort", onAbort);
162
+ req.on("error", (e) => {
163
+ done();
164
+ reject(signal.aborted ? abortReason(signal) : e);
165
+ });
166
+ req.on("upgrade", (_res, socket, head) => {
167
+ done();
168
+ if (head.byteLength > 0) socket.unshift(head);
169
+ resolve(socket);
170
+ });
171
+ req.on("response", (res) => {
172
+ done();
173
+ readBody(res, AbortSignal.timeout(1e4)).then((b) => {
174
+ const status = res.statusCode ?? 0;
175
+ reject(new DockerApiError(status, errorMessage(status, b)));
176
+ }, reject);
177
+ });
178
+ req.end(payload);
179
+ });
180
+ }
181
+ };
182
+ }
183
+ var StreamDemuxer = class {
184
+ constructor(onFrame) {
185
+ this.onFrame = onFrame;
186
+ }
187
+ onFrame;
188
+ buf = Buffer.alloc(0);
189
+ push(chunk) {
190
+ this.buf = this.buf.byteLength === 0 ? chunk : Buffer.concat([this.buf, chunk]);
191
+ while (this.buf.byteLength >= 8) {
192
+ const size = this.buf.readUInt32BE(4);
193
+ if (this.buf.byteLength < 8 + size) return;
194
+ const kind = this.buf[0];
195
+ const data = this.buf.subarray(8, 8 + size);
196
+ this.buf = this.buf.subarray(8 + size);
197
+ if (kind === 1 || kind === 2) this.onFrame(kind, data);
198
+ }
199
+ }
200
+ };
201
+
202
+ // src/listing.ts
203
+ import { posix } from "node:path";
204
+ import {
205
+ DEVICE_SCAN_SKIPPED_BASE_DIRS,
206
+ DEVICE_SCAN_SKIPPED_DIRS,
207
+ isDeviceProjectName,
208
+ MAX_DEVICE_LIST_ENTRIES,
209
+ MAX_DEVICE_SCAN_DEPTH,
210
+ MAX_DEVICE_SCAN_DIRS,
211
+ MAX_DEVICE_SCAN_RESULTS,
212
+ validateSandboxPathShape
213
+ } from "@capybara-hq/plugin-sdk";
214
+ var LIST_AREA = "/workspace";
215
+ var LIST_TIMEOUT_SECONDS = 30;
216
+ var LIST_PATH = "/usr/local/bin:/usr/bin:/bin";
217
+ var LIST_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
218
+ var LIST_SCRIPT = `
219
+ import errno, json, os, stat, sys
220
+ op, p, limit = sys.argv[1], sys.argv[2], int(sys.argv[3])
221
+ L = "${LIST_AREA}"
222
+ W = os.path.realpath(L)
223
+ def out(o):
224
+ sys.stdout.write(json.dumps(o)); sys.exit(0)
225
+ def key(s):
226
+ return s.encode("utf-16-be", "surrogatepass")
227
+ def under(r, a):
228
+ return r == a or r.startswith(a + "/")
229
+ def fail(e):
230
+ out({"e": "read", "c": errno.errorcode.get(getattr(e, "errno", None) or 0, "")})
231
+ def plain_dir(e):
232
+ try:
233
+ return e.is_dir(follow_symlinks=False)
234
+ except OSError:
235
+ return False
236
+ q = os.path.normpath(p)
237
+ if not os.path.isabs(q) or not under(q, L):
238
+ out({"e": "policy"})
239
+ try:
240
+ r = os.path.realpath(q)
241
+ except OSError as e:
242
+ fail(e)
243
+ if not under(r, W):
244
+ out({"e": "policy"})
245
+ try:
246
+ st = os.stat(r)
247
+ except (FileNotFoundError, NotADirectoryError):
248
+ out({"r": None if op == "list" else []})
249
+ except OSError as e:
250
+ fail(e)
251
+ if not stat.S_ISDIR(st.st_mode):
252
+ out({"e": "notdir"})
253
+ try:
254
+ with os.scandir(r) as it:
255
+ ents = sorted(it, key=lambda e: key(e.name))
256
+ except OSError as e:
257
+ fail(e)
258
+ def is_dir(d, e):
259
+ try:
260
+ if e.is_dir(follow_symlinks=False):
261
+ return True
262
+ if not e.is_symlink():
263
+ return False
264
+ t = os.path.realpath(os.path.join(d, e.name))
265
+ return under(t, W) and os.path.isdir(t)
266
+ except OSError:
267
+ return False
268
+ if op == "list":
269
+ out({"r": {"entries": [{"name": e.name, "isDir": is_dir(r, e)} for e in ents[:limit]], "truncated": len(ents) > limit}})
270
+ skip_any = ${JSON.stringify(DEVICE_SCAN_SKIPPED_DIRS)}
271
+ skip_base = ${JSON.stringify(DEVICE_SCAN_SKIPPED_BASE_DIRS)}
272
+ found = []
273
+ def below(d, rel, es, depth):
274
+ if any(e.name == ".git" or (e.name == "AGENTS.md" and not plain_dir(e)) for e in es):
275
+ found.append(rel)
276
+ if depth >= ${MAX_DEVICE_SCAN_DEPTH}:
277
+ return []
278
+ return [(os.path.join(d, e.name), e.name if rel == "" else rel + "/" + e.name) for e in es
279
+ if plain_dir(e) and not e.name.startswith(".")
280
+ and e.name not in skip_any and not (depth == 0 and e.name in skip_base)]
281
+ visits = 1
282
+ level = below(r, "", ents, 0)
283
+ depth = 1
284
+ while level and visits < ${MAX_DEVICE_SCAN_DIRS}:
285
+ level.sort(key=lambda n: key(n[1]))
286
+ nxt = []
287
+ for d, rel in level:
288
+ if visits >= ${MAX_DEVICE_SCAN_DIRS}:
289
+ break
290
+ visits += 1
291
+ try:
292
+ with os.scandir(d) as it:
293
+ es = list(it)
294
+ except OSError:
295
+ continue
296
+ nxt.extend(below(d, rel, es, depth))
297
+ level = nxt
298
+ depth += 1
299
+ out({"r": found})
300
+ `;
301
+ function checkListPath(path) {
302
+ if (!path.startsWith("/")) {
303
+ throw new Error(`invalid sandbox path ${JSON.stringify(path)}: path must be absolute`);
304
+ }
305
+ let p = posix.normalize(path);
306
+ if (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
307
+ const errors = validateSandboxPathShape(p);
308
+ if (errors.length > 0) {
309
+ throw new Error(`invalid sandbox path ${JSON.stringify(path)}: ${errors.join("; ")}`);
310
+ }
311
+ if (p !== LIST_AREA && !p.startsWith(`${LIST_AREA}/`)) throw outside(path);
312
+ return p;
313
+ }
314
+ function listLimit(limit) {
315
+ if (!Number.isInteger(limit) || limit < 0) {
316
+ throw new Error(`list limit must be a non-negative integer, got ${String(limit)}`);
317
+ }
318
+ return Math.min(limit, MAX_DEVICE_LIST_ENTRIES);
319
+ }
320
+ var outside = (path) => new Error(
321
+ `${path} is outside the sandbox's workspace (${LIST_AREA}); a cloud device offers only that, in either mode`
322
+ );
323
+ function answerOf(op, path, run, noPython) {
324
+ const text = (b) => Buffer.from(b).toString("utf8").trim().slice(0, 300);
325
+ if (run.exitCode === 127) throw new Error(noPython);
326
+ if (run.exitCode === 137) {
327
+ throw new Error(
328
+ `${op} ${path} took longer than ${LIST_TIMEOUT_SECONDS} s and was stopped; try a smaller directory or a base further down`
329
+ );
330
+ }
331
+ let res;
332
+ if (run.exitCode === 0 && !run.truncated) {
333
+ try {
334
+ res = JSON.parse(Buffer.from(run.stdout).toString("utf8"));
335
+ } catch {
336
+ res = void 0;
337
+ }
338
+ }
339
+ if (res === void 0 || typeof res !== "object" || res === null) {
340
+ const why = run.exitCode === 0 ? "an unreadable answer" : `exit code ${String(run.exitCode)}`;
341
+ throw new Error(`${op} ${path} failed in the sandbox (${why}): ${text(run.stderr)}`);
342
+ }
343
+ if (res.e === "policy") throw outside(path);
344
+ if (res.e === "notdir") throw new Error(`${path} is not a directory`);
345
+ if (res.e === "read") {
346
+ const code = typeof res.c === "string" && /^[A-Z0-9_]+$/.test(res.c) ? ` (${res.c})` : "";
347
+ throw new Error(`${path} cannot be read${code}`);
348
+ }
349
+ if (res.e !== void 0) throw new Error(`${op} ${path} failed in the sandbox`);
350
+ return res.r ?? null;
351
+ }
352
+ function finishList(path, run, noPython) {
353
+ const r = answerOf("list", path, run, noPython);
354
+ if (r === null) return null;
355
+ const v = r;
356
+ if (!Array.isArray(v.entries) || typeof v.truncated !== "boolean" || !v.entries.every(
357
+ (e) => typeof e?.name === "string" && typeof e.isDir === "boolean"
358
+ )) {
359
+ throw new Error(`list ${path} answered an invalid result`);
360
+ }
361
+ return {
362
+ entries: v.entries.map((e) => ({
363
+ name: e.name,
364
+ isDir: e.isDir
365
+ })),
366
+ truncated: v.truncated
367
+ };
368
+ }
369
+ var byCodeUnit = (a, b) => a < b ? -1 : a > b ? 1 : 0;
370
+ function finishScan(base, run, noPython) {
371
+ const r = answerOf("scan", base, run, noPython);
372
+ if (!Array.isArray(r) || !r.every((x) => typeof x === "string")) {
373
+ throw new Error(`scan ${base} answered an invalid result`);
374
+ }
375
+ const out = [];
376
+ const seen = /* @__PURE__ */ new Set();
377
+ for (const rel of r) {
378
+ const path = rel === "" ? base : `${base}/${rel}`;
379
+ const name = path.slice(path.lastIndexOf("/") + 1);
380
+ if (seen.has(path) || !isDeviceProjectName(name)) continue;
381
+ if (validateSandboxPathShape(path).length > 0) continue;
382
+ seen.add(path);
383
+ out.push({ path, suggestedName: name });
384
+ }
385
+ return out.sort((a, b) => byCodeUnit(a.path, b.path)).slice(0, MAX_DEVICE_SCAN_RESULTS);
386
+ }
387
+
388
+ // src/operations.ts
389
+ import { createHash as createHash2, randomBytes } from "node:crypto";
390
+ import { posix as posix2 } from "node:path";
391
+ import {
392
+ parseSandboxBrowseScope,
393
+ parseSandboxExecutionRef,
394
+ parseSandboxOperationRef,
395
+ parseSandboxOperationScope,
396
+ parseSandboxPreparationScope,
397
+ SandboxOperationOutcomeUnknownError,
398
+ SandboxPermissionUnsupportedError,
399
+ SandboxScopeDeniedError,
400
+ SandboxScopeValidationError,
401
+ validateSandboxPathShape as validateSandboxPathShape2
402
+ } from "@capybara-hq/plugin-sdk";
403
+
404
+ // src/runtime-source.ts
405
+ import { createHash } from "node:crypto";
406
+ import { SANDBOX_RUNTIME_SOURCE } from "@capybara-hq/plugin-sdk";
407
+ var RUNTIME_DIR = "/opt/capybara-runtime";
408
+ var OPERATION_AGENT = `${RUNTIME_DIR}/capybara-operation.py`;
409
+ var OPERATION_AGENT_SHA256 = "0459ca268c00950cfaf0838a9d505dc25d40b0b5b1e23ca6a042804b6c48417a";
410
+ var RUNTIME_BUNDLE_VERSION = 2;
411
+ var SDK_RUNTIME_FILES = Object.freeze(["native-files.py", "linux-sandbox.py"]);
412
+ function sdkRuntimeDigests() {
413
+ if (SANDBOX_RUNTIME_SOURCE.version !== RUNTIME_BUNDLE_VERSION) {
414
+ throw new Error(
415
+ `device-docker stages runtime bundle v${RUNTIME_BUNDLE_VERSION}, the SDK has v${SANDBOX_RUNTIME_SOURCE.version}`
416
+ );
417
+ }
418
+ const out = {};
419
+ for (const name of SDK_RUNTIME_FILES) {
420
+ const file = SANDBOX_RUNTIME_SOURCE.files.find((f) => f.name === name);
421
+ if (!file) throw new Error(`the SDK runtime bundle has no ${name}`);
422
+ const digest = createHash("sha256").update(file.source).digest("hex");
423
+ if (digest !== file.sha256)
424
+ throw new Error(`the SDK runtime ${name} does not match its digest`);
425
+ out[name] = digest;
426
+ }
427
+ return out;
428
+ }
429
+ function stagedRuntimeDigests() {
430
+ return { ...sdkRuntimeDigests(), "capybara-operation.py": OPERATION_AGENT_SHA256 };
431
+ }
432
+
433
+ // src/operations.ts
434
+ var PROTECTED = Object.freeze(["/tmp/.capybara-exec-", "/skills/.capybara-ops", "/opt/capybara"]);
435
+ function protectedRoot(path, write) {
436
+ const p = posix2.normalize(path);
437
+ for (const entry of PROTECTED) {
438
+ const bare = entry.replace(/-$/, "");
439
+ const inside = p === bare || p.startsWith(`${entry.replace(/\/$/, "")}/`);
440
+ if (write && (inside || entry.startsWith(`${p.replace(/\/$/, "")}/`))) return true;
441
+ if (!write && inside && entry !== "/tmp/.capybara-exec-") return true;
442
+ }
443
+ return false;
444
+ }
445
+ var PYTHON = "/usr/bin/python3";
446
+ var NATIVE_MAX_OUTPUT = 64 * 1024 * 1024;
447
+ var RECORD_RETENTION_MS = 60 * 60 * 1e3;
448
+ function operationUuid(operationId) {
449
+ const h = createHash2("sha256").update(`capybara-operation\0${operationId}`).digest("hex");
450
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
451
+ }
452
+ function operationControlPath(tag, operationId) {
453
+ return `/tmp/.capybara-exec-${tag}-${operationUuid(operationId)}`;
454
+ }
455
+ var opKey = (operationId) => createHash2("sha256").update(operationId).digest("hex");
456
+ function canonical(value) {
457
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
458
+ if (value !== null && typeof value === "object") {
459
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
460
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
461
+ }
462
+ return JSON.stringify(value);
463
+ }
464
+ function inputHash(method, scope, input) {
465
+ return createHash2("sha256").update(canonical({ method, scope, input })).digest("hex");
466
+ }
467
+ function request2(body) {
468
+ const json = Buffer.from(JSON.stringify(body));
469
+ return Buffer.concat([Buffer.from(`${json.byteLength}
470
+ `), json]);
471
+ }
472
+ function parseFrames(raw) {
473
+ const frames = { out: [], err: [], result: null };
474
+ let at = 0;
475
+ while (at + 5 <= raw.byteLength) {
476
+ const kind = String.fromCharCode(raw[at]);
477
+ const size = raw.readUInt32BE(at + 1);
478
+ if (at + 5 + size > raw.byteLength) break;
479
+ const data = raw.subarray(at + 5, at + 5 + size);
480
+ if (kind === "O") frames.out.push(data);
481
+ else if (kind === "E") frames.err.push(data);
482
+ else if (kind === "R") frames.result = JSON.parse(data.toString("utf8"));
483
+ at += 5 + size;
484
+ }
485
+ return frames;
486
+ }
487
+ function soleResult(raw) {
488
+ if (raw.byteLength === 0) return null;
489
+ if (raw.byteLength < 5 || String.fromCharCode(raw[0]) !== "R") return "malformed";
490
+ if (5 + raw.readUInt32BE(1) !== raw.byteLength) return "malformed";
491
+ try {
492
+ return JSON.parse(raw.subarray(5).toString("utf8"));
493
+ } catch {
494
+ return "malformed";
495
+ }
496
+ }
497
+ function refusalError(result) {
498
+ const refused = result?.events?.find((e) => e.event === "refused");
499
+ if (!refused) return null;
500
+ switch (refused.code) {
501
+ case "UNAVAILABLE":
502
+ return new SandboxPermissionUnsupportedError(
503
+ `Restricted execution is unavailable on this device: ${refused.message ?? "unsupported"}`
504
+ );
505
+ case "SCOPE_DENIED":
506
+ case "ROOT_CHANGED":
507
+ return new SandboxScopeDeniedError(
508
+ "A granted root is missing its pinned identity or the path is outside the operation scope"
509
+ );
510
+ case "REVOKED":
511
+ return new SandboxScopeDeniedError("The operation was revoked before it started");
512
+ case "EXPIRED":
513
+ return new SandboxScopeDeniedError("The operation's admission deadline passed");
514
+ case "CANCELLED":
515
+ return null;
516
+ default:
517
+ return new Error(`Restricted launch refused (${refused.code ?? "unknown"})`);
518
+ }
519
+ }
520
+ function refusedFrame(raw, nonce) {
521
+ const result = parseFrames(raw).result;
522
+ if (!result || result.nonce !== nonce) return null;
523
+ if (result.events?.some((e) => e.event === "refused" && e.code === "CANCELLED")) {
524
+ return "cancelled";
525
+ }
526
+ return refusalError(result);
527
+ }
528
+ function checkPath(p) {
529
+ const errors = validateSandboxPathShape2(p);
530
+ if (errors.length > 0) {
531
+ throw new SandboxScopeDeniedError(`Invalid native path: ${errors.join("; ")}`);
532
+ }
533
+ }
534
+ var ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
535
+ function checkedEnv(env) {
536
+ const out = {};
537
+ for (const [k, v] of Object.entries(env ?? {})) {
538
+ if (!ENV_KEY_RE.test(k)) throw new Error(`invalid environment variable name: ${k}`);
539
+ out[k] = v;
540
+ }
541
+ return out;
542
+ }
543
+ function nativeReply(result, restricted) {
544
+ const error = refusalError(result);
545
+ if (error) throw error;
546
+ if (!result) {
547
+ throw new SandboxPermissionUnsupportedError(
548
+ "The device has no operation runtime (use an image with /opt/capybara-runtime)"
549
+ );
550
+ }
551
+ const reply = result.native;
552
+ if (!reply) throw new Error("The native helper gave no reply");
553
+ if (reply.error) {
554
+ if (reply.error.code === "SCOPE_DENIED" || restricted && reply.error.code === "EACCES") {
555
+ throw new SandboxScopeDeniedError("The native path is outside the operation scope");
556
+ }
557
+ throw new Error(`Native operation failed (${reply.error.code})`);
558
+ }
559
+ return reply.result;
560
+ }
561
+ function nativeResult(method, value) {
562
+ if (method === "readFile") {
563
+ const v = value;
564
+ return v && { data: new Uint8Array(Buffer.from(v.dataB64, "base64")), truncated: v.truncated };
565
+ }
566
+ if (method === "writeFile") return void 0;
567
+ return value;
568
+ }
569
+ var OUTSIDE_UNSUPPORTED = "device-docker has no outside of its instance: the container is the sandbox, so an escalated (device) operation cannot run here";
570
+ var NARROWER_UNSUPPORTED = "device-docker runs operations on the whole instance only (the container is the sandbox): a narrower filesystem grant needs restricted filters this provider does not offer";
571
+ function appliedWithin(network, applied) {
572
+ if (applied === null) return false;
573
+ if (network.kind === "open-public") return true;
574
+ if (network.kind === "environment") return false;
575
+ if (applied.mode === "none") return true;
576
+ if (network.kind === "none" || applied.mode === "open-public") return false;
577
+ const granted = new Set(network.hosts.map((host) => host.toLowerCase()));
578
+ return applied.allowHosts.every((host) => granted.has(host.toLowerCase()));
579
+ }
580
+ function isInstanceScope(scope) {
581
+ return scope.filesystem.kind === "scoped" && scope.network.kind !== "environment" && // writable roots are also readable (SandboxFileScope): a writable `/` is the whole instance
582
+ scope.filesystem.writeRoots.includes("/");
583
+ }
584
+ function createOperations(deps) {
585
+ const { transport: t } = deps;
586
+ const record = async (h, ref, method, hash, signal, retainUntilMs) => {
587
+ const r = await t.run(h, {
588
+ cmd: [PYTHON, "-I", OPERATION_AGENT, "consume"],
589
+ user: "root",
590
+ stdin: request2({
591
+ opKey: opKey(ref.operationId),
592
+ method,
593
+ inputHash: hash,
594
+ admitBeforeMs: ref.admitBeforeMs,
595
+ expiresAtMs: Math.max(ref.admitBeforeMs, retainUntilMs ?? 0) + RECORD_RETENTION_MS
596
+ }),
597
+ maxOutputBytes: 1 << 20,
598
+ signal
599
+ });
600
+ if (r.aborted) signal.throwIfAborted();
601
+ const result = parseFrames(r.stdout).result;
602
+ if (r.exitCode !== 0 || !result) {
603
+ throw new SandboxPermissionUnsupportedError(
604
+ "The device has no operation runtime (use an image with /opt/capybara-runtime)"
605
+ );
606
+ }
607
+ const error = refusalError(result);
608
+ if (error) throw error;
609
+ switch (result.state) {
610
+ case "new":
611
+ return { state: "new", generation: String(result.generation) };
612
+ case "duplicate":
613
+ return {
614
+ state: "duplicate",
615
+ generation: String(result.record?.generation)
616
+ };
617
+ case "revoked":
618
+ throw new SandboxScopeDeniedError("The operation was revoked");
619
+ case "expired":
620
+ throw new SandboxScopeDeniedError("The operation's admission deadline passed");
621
+ case "mismatch":
622
+ throw new SandboxScopeValidationError(
623
+ "This operation ID was consumed with a different method or input"
624
+ );
625
+ default:
626
+ throw new Error("Unexpected operation record state");
627
+ }
628
+ };
629
+ const checkNetwork = async (h, scope, signal) => {
630
+ if (!appliedWithin(scope.network, await t.appliedNetwork(h, signal))) {
631
+ throw new SandboxScopeDeniedError(
632
+ "The instance's network allows more than this operation's network; device-docker cannot narrow it per operation, so the operation is refused"
633
+ );
634
+ }
635
+ };
636
+ const consume = async (h, ref, method, hash, signal) => {
637
+ const r = await record(h, ref, method, hash, signal);
638
+ if (r.state === "duplicate") {
639
+ throw new SandboxOperationOutcomeUnknownError(
640
+ "This operation ID was already consumed; its outcome is not retried"
641
+ );
642
+ }
643
+ };
644
+ const agent = async (h, o) => {
645
+ const r = await t.run(h, o);
646
+ return { run: r, frames: parseFrames(r.stdout) };
647
+ };
648
+ const nativeOp = async (h, scope, method, native, signal) => {
649
+ signal.throwIfAborted();
650
+ checkPath(String(native.path));
651
+ const input = { ...native, dataB64: void 0, data: digestOf(native.dataB64) };
652
+ await consume(h, scope, method, inputHash(method, scope, input), signal);
653
+ const { frames } = await agent(h, {
654
+ cmd: [PYTHON, "-I", OPERATION_AGENT, "direct"],
655
+ user: "sandbox",
656
+ stdin: request2({
657
+ opKey: opKey(scope.operationId),
658
+ admitBeforeMs: scope.admitBeforeMs,
659
+ expect: sdkRuntimeDigests(),
660
+ kind: "device",
661
+ native: { method, ...native }
662
+ }),
663
+ maxOutputBytes: NATIVE_MAX_OUTPUT,
664
+ signal
665
+ });
666
+ signal.throwIfAborted();
667
+ return nativeResult(method, nativeReply(frames.result, false));
668
+ };
669
+ const execOp = async (h, scope, args) => {
670
+ args.signal.throwIfAborted();
671
+ const input = { ...args, signal: void 0, env: args.env };
672
+ await checkNetwork(h, scope, args.signal);
673
+ await consume(h, scope, "exec", inputHash("exec", scope, input), args.signal);
674
+ const ctl = operationControlPath(scope.tag, scope.operationId);
675
+ return t.execFull(
676
+ h,
677
+ { ...args, tag: scope.tag },
678
+ ctl,
679
+ [
680
+ PYTHON,
681
+ "-I",
682
+ OPERATION_AGENT,
683
+ "full",
684
+ opKey(scope.operationId),
685
+ String(scope.admitBeforeMs),
686
+ ctl,
687
+ "--"
688
+ ],
689
+ randomBytes(16).toString("hex")
690
+ );
691
+ };
692
+ const checkScope = (scope) => {
693
+ if (scope.filesystem.kind === "device" || scope.network.kind === "environment") {
694
+ throw new SandboxPermissionUnsupportedError(OUTSIDE_UNSUPPORTED);
695
+ }
696
+ if (!isInstanceScope(scope)) throw new SandboxPermissionUnsupportedError(NARROWER_UNSUPPORTED);
697
+ };
698
+ const checkRoots = (readRoots, writeRoots) => {
699
+ for (const root of writeRoots) {
700
+ if (protectedRoot(root, true)) {
701
+ throw new SandboxScopeDeniedError(
702
+ "A writable root may not contain the provider's records or control files"
703
+ );
704
+ }
705
+ }
706
+ for (const root of readRoots) {
707
+ if (protectedRoot(root, false)) {
708
+ throw new SandboxScopeDeniedError(
709
+ "A readable root may not be inside the provider's records"
710
+ );
711
+ }
712
+ }
713
+ };
714
+ const rootStep = async (h, command, body, signal, started = false) => {
715
+ const o = {
716
+ cmd: [PYTHON, "-I", OPERATION_AGENT, command],
717
+ user: "root",
718
+ stdin: request2(body),
719
+ maxOutputBytes: 1 << 20,
720
+ signal
721
+ };
722
+ const r = started ? await t.run(h, o) : await t.runIfRunning(h, o);
723
+ if (r === "not-running") return r;
724
+ if (r.aborted) signal.throwIfAborted();
725
+ const result = parseFrames(r.stdout).result;
726
+ if (!result) throw new Error(`The operation record step ${command} gave no result`);
727
+ const error = refusalError(result);
728
+ if (error) throw error;
729
+ return result;
730
+ };
731
+ const exactRef = (h, input) => {
732
+ const ref = parseSandboxExecutionRef(input);
733
+ if (ref.instanceId !== h.id || ref.executionId !== operationUuid(ref.operationId)) {
734
+ throw new SandboxScopeDeniedError("The execution reference names another instance");
735
+ }
736
+ return ref;
737
+ };
738
+ const bgCall = (h, command, ref, extra, signal) => rootStep(
739
+ h,
740
+ command,
741
+ { executionId: ref.executionId, generation: ref.instanceGeneration, ...extra },
742
+ signal
743
+ );
744
+ const stopExecution = async (h, executionId, generation, graceMs, signal, aborted = false) => {
745
+ const key = { executionId, generation, anyGeneration: generation === null };
746
+ const plan = await rootStep(h, "bg-stop-plan", key, signal);
747
+ if (plan === "not-running") return { outcome: "lost" };
748
+ if (plan.outcome) return toStopResult(plan.outcome);
749
+ let signalled = false;
750
+ const target = plan.signal;
751
+ if (target) {
752
+ const r = await t.runIfRunning(h, {
753
+ cmd: [PYTHON, "-I", OPERATION_AGENT, "bg-signal"],
754
+ user: "sandbox",
755
+ stdin: request2({ ...target, graceMs }),
756
+ maxOutputBytes: 1 << 20,
757
+ signal
758
+ });
759
+ if (r === "not-running") return { outcome: "lost" };
760
+ signalled = parseFrames(r.stdout).result?.signalled === true;
761
+ }
762
+ const claim = await rootStep(
763
+ h,
764
+ "bg-stop-claim",
765
+ { ...key, signalled, ...aborted && { aborted } },
766
+ signal
767
+ );
768
+ if (claim === "not-running") return { outcome: "lost" };
769
+ return toStopResult(claim);
770
+ };
771
+ const abortStart = async (h, scope, ref) => {
772
+ const cleanup = AbortSignal.timeout(3e4);
773
+ await rootStep(
774
+ h,
775
+ "cancel-mark",
776
+ { opKey: opKey(scope.operationId), expiresAtMs: scope.admitBeforeMs + RECORD_RETENTION_MS },
777
+ cleanup
778
+ ).then(() => stopExecution(h, ref.executionId, ref.instanceGeneration, 0, cleanup, true)).catch(() => void 0);
779
+ };
780
+ const abortIfContested = async (h, scope, ref) => {
781
+ const check = await rootStep(
782
+ h,
783
+ "bg-contested",
784
+ { executionId: ref.executionId, generation: ref.instanceGeneration },
785
+ AbortSignal.timeout(15e3)
786
+ ).catch(() => "not-running");
787
+ if (check !== "not-running" && check.contested === true) await abortStart(h, scope, ref);
788
+ };
789
+ const MAX_OUTPUT_READ = 65536;
790
+ const bytes = (result) => new Uint8Array(Buffer.from(String(result.dataB64 ?? ""), "base64"));
791
+ const background = {
792
+ async start(h, input, args) {
793
+ args.signal.throwIfAborted();
794
+ const scope = parseSandboxOperationScope(input);
795
+ checkScope(scope);
796
+ if (typeof args.taskId !== "string" || args.taskId.length === 0 || args.taskId.length > 128) {
797
+ throw new SandboxScopeValidationError("Supply a task id of 1 to 128 characters");
798
+ }
799
+ if (!Number.isSafeInteger(args.retainUntilMs) || args.retainUntilMs <= 0) {
800
+ throw new SandboxScopeValidationError("Supply retainUntilMs as a positive safe integer");
801
+ }
802
+ checkPath(args.outputPath);
803
+ const input2 = { ...args, signal: void 0 };
804
+ await checkNetwork(h, scope, args.signal);
805
+ const consumed = await record(
806
+ h,
807
+ scope,
808
+ "backgroundStart",
809
+ inputHash("backgroundStart", scope, input2),
810
+ args.signal,
811
+ args.retainUntilMs
812
+ );
813
+ const ref = Object.freeze({
814
+ executionId: operationUuid(scope.operationId),
815
+ operationId: scope.operationId,
816
+ instanceId: h.id,
817
+ instanceGeneration: consumed.generation
818
+ });
819
+ if (consumed.state === "duplicate") {
820
+ await abortIfContested(h, scope, ref);
821
+ return ref;
822
+ }
823
+ const barrier = t.backgroundLaunchBarrier?.(args.taskId);
824
+ const launch = {
825
+ ...barrier !== void 0 && { barrier },
826
+ opKey: opKey(scope.operationId),
827
+ admitBeforeMs: scope.admitBeforeMs,
828
+ expect: sdkRuntimeDigests(),
829
+ executionId: ref.executionId,
830
+ // the whole instance: the agent's device kind (no launcher), under the instance network
831
+ kind: "device",
832
+ writeRoots: [],
833
+ readRoots: [],
834
+ network: scope.network,
835
+ command: args.command,
836
+ cwd: args.cwd ?? "/workspace",
837
+ env: checkedEnv(args.env),
838
+ timeoutMs: args.timeoutMs,
839
+ maxOutputBytes: args.maxOutputBytes,
840
+ taskId: args.taskId,
841
+ outputPath: args.outputPath,
842
+ retainUntilMs: args.retainUntilMs
843
+ };
844
+ const secret = randomBytes(16).toString("hex");
845
+ const token = randomBytes(16).toString("hex");
846
+ const prepared = await rootStep(
847
+ h,
848
+ "bg-prepare",
849
+ {
850
+ executionId: ref.executionId,
851
+ secret,
852
+ token,
853
+ start: launch,
854
+ opKey: opKey(scope.operationId),
855
+ taskId: args.taskId,
856
+ retainUntilMs: args.retainUntilMs,
857
+ ...t.backgroundSpoolCapBytes?.(args.taskId) !== void 0 && {
858
+ spoolCapBytes: t.backgroundSpoolCapBytes(args.taskId)
859
+ }
860
+ },
861
+ args.signal,
862
+ true
863
+ );
864
+ if (prepared === "not-running" || prepared.existing) {
865
+ throw new SandboxOperationOutcomeUnknownError(
866
+ "This execution was already prepared; reconcile it by its reference"
867
+ );
868
+ }
869
+ let outcome = "failed";
870
+ try {
871
+ await t.beforeBackgroundLaunch?.(args.taskId, { secret, token, ...launch });
872
+ let stdin = request2({ secret, token, ...launch });
873
+ if (t.interceptBackgroundStdin)
874
+ stdin = await t.interceptBackgroundStdin(args.taskId, stdin);
875
+ const cmd = [PYTHON, "-I", OPERATION_AGENT, "bg-start"];
876
+ const r = await t.run(h, {
877
+ cmd: t.backgroundStartCommand?.(args.taskId, cmd) ?? cmd,
878
+ user: "sandbox",
879
+ stdin,
880
+ maxOutputBytes: 1 << 20,
881
+ signal: args.signal
882
+ });
883
+ const sole = soleResult(r.stdout);
884
+ if (r.exitCode !== 0 || r.aborted || r.timedOut || sole === "malformed") {
885
+ throw new SandboxOperationOutcomeUnknownError(
886
+ "The background start did not finish and was aborted; reconcile it by its reference"
887
+ );
888
+ }
889
+ outcome = "unknown";
890
+ const result = t.loseBackgroundAck?.(args.taskId) ? null : sole;
891
+ const error = refusalError(result);
892
+ if (error) {
893
+ outcome = "refused";
894
+ throw error;
895
+ }
896
+ if (!result?.started) {
897
+ throw new SandboxOperationOutcomeUnknownError(
898
+ "The background start was not acknowledged; reconcile it by its reference"
899
+ );
900
+ }
901
+ outcome = "acknowledged";
902
+ return ref;
903
+ } finally {
904
+ if (outcome === "refused" || outcome === "failed") await abortStart(h, scope, ref);
905
+ if (outcome === "unknown") await abortIfContested(h, scope, ref);
906
+ }
907
+ },
908
+ async status(h, input, signal) {
909
+ signal.throwIfAborted();
910
+ const ref = exactRef(h, input);
911
+ const result = await bgCall(h, "bg-status", ref, {}, signal);
912
+ if (result === "not-running" || result.state === "lost") return { state: "lost" };
913
+ if (result.state === "running") return { state: "running" };
914
+ return {
915
+ state: "exited",
916
+ exitCode: typeof result.exitCode === "number" ? result.exitCode : null,
917
+ timedOut: result.timedOut === true
918
+ };
919
+ },
920
+ async tail(h, input, opts) {
921
+ opts.signal.throwIfAborted();
922
+ const ref = exactRef(h, input);
923
+ if (!Number.isInteger(opts.maxBytes) || opts.maxBytes < 0 || opts.maxBytes > MAX_OUTPUT_READ) {
924
+ throw new SandboxScopeDeniedError("Supply maxBytes as an integer from 0 to 65536");
925
+ }
926
+ const result = await bgCall(h, "bg-tail", ref, { maxBytes: opts.maxBytes }, opts.signal);
927
+ if (result === "not-running") return { unavailable: "lost" };
928
+ if (result.unavailable === "lost" || result.unavailable === "expired") {
929
+ return { unavailable: result.unavailable };
930
+ }
931
+ return { data: bytes(result), truncated: result.truncated === true };
932
+ },
933
+ async readOutput(h, input, opts) {
934
+ opts.signal.throwIfAborted();
935
+ const ref = exactRef(h, input);
936
+ if (!Number.isSafeInteger(opts.offset) || opts.offset < 0) {
937
+ throw new SandboxScopeDeniedError("Supply offset as a nonnegative safe integer");
938
+ }
939
+ if (!Number.isInteger(opts.maxBytes) || opts.maxBytes < 0 || opts.maxBytes > MAX_OUTPUT_READ) {
940
+ throw new SandboxScopeDeniedError("Supply maxBytes as an integer from 0 to 65536");
941
+ }
942
+ const result = await bgCall(
943
+ h,
944
+ "bg-read",
945
+ ref,
946
+ { offset: opts.offset, maxBytes: opts.maxBytes },
947
+ opts.signal
948
+ );
949
+ if (result === "not-running") return { unavailable: "lost" };
950
+ if (result.unavailable === "lost" || result.unavailable === "expired") {
951
+ return { unavailable: result.unavailable };
952
+ }
953
+ const data = bytes(result);
954
+ return {
955
+ data,
956
+ offset: opts.offset,
957
+ nextOffset: opts.offset + data.byteLength,
958
+ totalBytes: Number(result.totalBytes)
959
+ };
960
+ },
961
+ async stop(h, input, opts) {
962
+ opts.signal.throwIfAborted();
963
+ const ref = exactRef(h, input);
964
+ return stopExecution(h, ref.executionId, ref.instanceGeneration, opts.graceMs, opts.signal);
965
+ }
966
+ };
967
+ return {
968
+ /**
969
+ * Support v2 of this instance (approval-only profiles design, "SDK and protocol"): the
970
+ * container is the sandbox (`boundary: "instance"`, no restricted filters, no outside), its
971
+ * egress proxy offers open-public (unless the deployment refuses it) and allowlists, never
972
+ * per-operation hosts, and background work is supervised exactly. The staged runtime (the
973
+ * agent's records and native helper) must be root-owned, read-only and match its digests;
974
+ * otherwise nothing is offered and the reason says why. Never starts or resumes the instance.
975
+ */
976
+ async permissionSupport(h, signal) {
977
+ signal.throwIfAborted();
978
+ const unavailable = (reason) => ({
979
+ version: 2,
980
+ boundary: "instance",
981
+ restricted: null,
982
+ network: { openPublic: false, allowlist: false, perOperationHosts: false },
983
+ outsideSandbox: false,
984
+ background: false,
985
+ unavailableReason: reason
986
+ });
987
+ const names = Object.keys(stagedRuntimeDigests()).sort();
988
+ const staged = await t.runIfRunning(h, {
989
+ cmd: [
990
+ "/bin/sh",
991
+ "-c",
992
+ 'cd "$1" && shift && stat -c "%u %a %F %n" . /opt "$@" && sha256sum -- "$@"',
993
+ "capybara-probe",
994
+ RUNTIME_DIR,
995
+ ...names
996
+ ],
997
+ user: "sandbox",
998
+ env: ["PATH=/usr/bin:/bin"],
999
+ maxOutputBytes: 64 * 1024,
1000
+ signal
1001
+ });
1002
+ if (staged === "not-running") {
1003
+ throw new Error("The device instance is not running; probe it during execution");
1004
+ }
1005
+ if (staged.exitCode !== 0) return unavailable("The image has no staged operation runtime");
1006
+ const lines = staged.stdout.toString("utf8").trim().split("\n");
1007
+ const expect = stagedRuntimeDigests();
1008
+ for (const line of lines.slice(0, names.length + 2)) {
1009
+ const m = line.match(/^(\d+) ([0-7]+) (.+?) (\S+)$/);
1010
+ const writable = (Number.parseInt(m?.[2] ?? "777", 8) & 18) !== 0;
1011
+ if (m?.[1] !== "0" || writable || /symbolic/.test(m[3] ?? "")) {
1012
+ return unavailable("The staged operation runtime is not root-owned and read-only");
1013
+ }
1014
+ }
1015
+ const digests = lines.slice(names.length + 2);
1016
+ if (digests.length !== names.length) {
1017
+ return unavailable("The staged operation runtime is incomplete");
1018
+ }
1019
+ for (const line of digests) {
1020
+ const [digest, name] = line.split(/\s+/);
1021
+ if (!name || expect[name] !== digest) {
1022
+ return unavailable(`The staged ${name ?? "runtime"} does not match its digest`);
1023
+ }
1024
+ }
1025
+ return {
1026
+ version: 2,
1027
+ boundary: "instance",
1028
+ restricted: null,
1029
+ network: {
1030
+ openPublic: deps.network.openPublic,
1031
+ allowlist: true,
1032
+ perOperationHosts: false
1033
+ },
1034
+ outsideSandbox: false,
1035
+ background: true
1036
+ };
1037
+ },
1038
+ async operation(h, input, signal) {
1039
+ signal.throwIfAborted();
1040
+ const scope = parseSandboxOperationScope(input);
1041
+ checkScope(scope);
1042
+ const both = (s) => AbortSignal.any([signal, s]);
1043
+ return {
1044
+ exec: (args) => execOp(h, scope, { ...args, signal: both(args.signal) }),
1045
+ readFile: async (path, o) => nativeOp(
1046
+ h,
1047
+ scope,
1048
+ "readFile",
1049
+ { path, maxBytes: o.maxBytes },
1050
+ both(o.signal)
1051
+ ),
1052
+ writeFile: async (path, data, s) => {
1053
+ await nativeOp(
1054
+ h,
1055
+ scope,
1056
+ "writeFile",
1057
+ { path, dataB64: Buffer.from(data).toString("base64") },
1058
+ both(s)
1059
+ );
1060
+ },
1061
+ stat: async (path, s) => nativeOp(h, scope, "stat", { path }, both(s)),
1062
+ list: async (path, o) => nativeOp(h, scope, "list", { path, limit: o.limit }, both(o.signal)),
1063
+ scan: async (base, o) => nativeOp(h, scope, "scan", { path: base }, both(o.signal))
1064
+ };
1065
+ },
1066
+ async browse(h, input, signal) {
1067
+ signal.throwIfAborted();
1068
+ const scope = parseSandboxBrowseScope(input);
1069
+ checkRoots(scope.readRoots, []);
1070
+ const run = async (method, native, s) => {
1071
+ const sig = AbortSignal.any([signal, s]);
1072
+ sig.throwIfAborted();
1073
+ checkPath(String(native.path));
1074
+ await consume(h, scope, `browse-${method}`, inputHash(method, scope, native), sig);
1075
+ const { frames } = await agent(h, {
1076
+ cmd: [PYTHON, "-I", OPERATION_AGENT, "direct"],
1077
+ user: "sandbox",
1078
+ stdin: request2({
1079
+ opKey: opKey(scope.operationId),
1080
+ admitBeforeMs: scope.admitBeforeMs,
1081
+ expect: sdkRuntimeDigests(),
1082
+ kind: "scoped",
1083
+ readRoots: [...scope.readRoots],
1084
+ writeRoots: [],
1085
+ native: { method, ...native }
1086
+ }),
1087
+ maxOutputBytes: NATIVE_MAX_OUTPUT,
1088
+ signal: sig
1089
+ });
1090
+ sig.throwIfAborted();
1091
+ return nativeReply(frames.result, true);
1092
+ };
1093
+ return {
1094
+ stat: async (path, s) => await run("stat", { path }, s),
1095
+ list: async (path, o) => await run("list", { path, limit: o.limit }, o.signal),
1096
+ scan: async (base, o) => await run("scan", { path: base }, o.signal)
1097
+ };
1098
+ },
1099
+ async prepare(h, input, signal) {
1100
+ signal.throwIfAborted();
1101
+ const scope = parseSandboxPreparationScope(input);
1102
+ const roots = scope.writeRoots.map((root) => {
1103
+ if (posix2.normalize(root) !== root) {
1104
+ throw new SandboxScopeDeniedError("Preparation roots must be canonical absolute paths");
1105
+ }
1106
+ if (scope.purpose === "skills") {
1107
+ if (root !== "/skills" && !root.startsWith("/skills/")) {
1108
+ throw new SandboxScopeDeniedError("Skills are prepared only under /skills");
1109
+ }
1110
+ return {
1111
+ path: root,
1112
+ base: "/opt/capybara/skills",
1113
+ relative: root.slice("/skills".length)
1114
+ };
1115
+ }
1116
+ const m = root.match(/^\/workspace\/attachments\/[^/]+(\/.*)?$/);
1117
+ if (!m) {
1118
+ throw new SandboxScopeDeniedError(
1119
+ "Attachments are prepared only under /workspace/attachments/<conversation>"
1120
+ );
1121
+ }
1122
+ return { path: root, base: "/workspace", relative: root.slice("/workspace".length) };
1123
+ });
1124
+ const user = scope.purpose === "skills" ? "root" : "sandbox";
1125
+ const run = async (method, native, s) => {
1126
+ const sig = AbortSignal.any([signal, s]);
1127
+ sig.throwIfAborted();
1128
+ checkPath(String(native.path));
1129
+ const { frames } = await agent(h, {
1130
+ cmd: [PYTHON, "-I", OPERATION_AGENT, "direct"],
1131
+ user,
1132
+ stdin: request2({
1133
+ expect: sdkRuntimeDigests(),
1134
+ kind: "prepare",
1135
+ prepareRoots: roots,
1136
+ publicFiles: scope.purpose === "skills",
1137
+ native: { method, ...native }
1138
+ }),
1139
+ maxOutputBytes: NATIVE_MAX_OUTPUT,
1140
+ signal: sig
1141
+ });
1142
+ sig.throwIfAborted();
1143
+ return nativeResult(method, nativeReply(frames.result, true));
1144
+ };
1145
+ return {
1146
+ readFile: async (path, o) => await run("readFile", { path, maxBytes: o.maxBytes }, o.signal),
1147
+ writeFile: async (path, data, s) => {
1148
+ await run("writeFile", { path, dataB64: Buffer.from(data).toString("base64") }, s);
1149
+ },
1150
+ stat: async (path, s) => await run("stat", { path }, s)
1151
+ };
1152
+ },
1153
+ background,
1154
+ async revokeOperation(h, input, signal) {
1155
+ signal.throwIfAborted();
1156
+ const ref = parseSandboxOperationRef(input);
1157
+ const marker = {
1158
+ opKey: opKey(ref.operationId),
1159
+ expiresAtMs: ref.admitBeforeMs + RECORD_RETENTION_MS
1160
+ };
1161
+ const first = await rootStep(h, "revoke", marker, signal);
1162
+ if (first === "not-running") {
1163
+ if (Date.now() > ref.admitBeforeMs) return;
1164
+ throw new Error("The device instance is not running; the revocation stays pending");
1165
+ }
1166
+ const uuid = operationUuid(ref.operationId);
1167
+ await t.killOperation(h, uuid, signal);
1168
+ await stopExecution(h, uuid, null, 0, signal);
1169
+ await t.afterRevokeKill?.(ref.operationId);
1170
+ const second = await rootStep(h, "revoke", marker, signal);
1171
+ if (second === "not-running" || second.generation !== first.generation) {
1172
+ throw new Error("The device instance restarted during the revocation; retry it");
1173
+ }
1174
+ }
1175
+ };
1176
+ }
1177
+ function toStopResult(result) {
1178
+ switch (result.outcome) {
1179
+ case "already-exited":
1180
+ return {
1181
+ outcome: "already-exited",
1182
+ exitCode: typeof result.exitCode === "number" ? result.exitCode : null,
1183
+ timedOut: result.timedOut === true
1184
+ };
1185
+ case "stopped":
1186
+ return { outcome: "stopped" };
1187
+ default:
1188
+ return { outcome: "lost" };
1189
+ }
1190
+ }
1191
+ function digestOf(data) {
1192
+ return typeof data === "string" ? createHash2("sha256").update(data).digest("hex") : void 0;
1193
+ }
1194
+
1195
+ // src/provider.ts
1196
+ function publishedImages(version) {
1197
+ return {
1198
+ sandbox: `ghcr.io/capybara-hq/capybara-sandbox:${version}`,
1199
+ egress: `ghcr.io/capybara-hq/capybara-sandbox-egress:${version}`
1200
+ };
1201
+ }
1202
+ var SANDBOX_USER = "1000:1000";
1203
+ var ROOT_USER = "0:0";
1204
+ var INIT_USER = ROOT_USER;
1205
+ var PROXY_PORT = 3128;
1206
+ var SOCKS_PORT = 1080;
1207
+ var PIDS_LIMIT = 1024;
1208
+ var MIB = 1024 * 1024;
1209
+ var GIB = 1024 * MIB;
1210
+ var STOP_SECONDS = 5;
1211
+ var KILL_GRACE_MS = 3e3;
1212
+ var EXIT_WAIT_MS = 3e4;
1213
+ var STDERR_ROOM = 64 * 1024;
1214
+ var LABEL = "dev.capybara.sandbox";
1215
+ var LABEL_NAME = "dev.capybara.sandbox.name";
1216
+ var LABEL_ROLE = "dev.capybara.sandbox.role";
1217
+ var LABEL_ALLOW = "dev.capybara.sandbox.allow-hosts";
1218
+ var LABEL_NET = "dev.capybara.sandbox.network";
1219
+ var LABEL_EGRESS_MODE = "dev.capybara.sandbox.mode";
1220
+ var NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$/;
1221
+ var ENV_KEY_RE2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
1222
+ function sandboxResourceNames(name) {
1223
+ return {
1224
+ container: name,
1225
+ egress: `${name}-egress`,
1226
+ network: `${name}-net`,
1227
+ workspace: `${name}-workspace`,
1228
+ skills: `${name}-skills`
1229
+ };
1230
+ }
1231
+ function networkOf(limits) {
1232
+ const network = limits.network;
1233
+ if (network === void 0) return { kind: "allowlist", hosts: [] };
1234
+ if (network.kind !== "open-public" && network.kind !== "allowlist") {
1235
+ throw new Error(`unknown sandbox network kind: ${String(network.kind)}`);
1236
+ }
1237
+ return network;
1238
+ }
1239
+ function planInstance(limits, refuseOpenNetwork = false) {
1240
+ const network = networkOf(limits);
1241
+ const shmBytes = Math.min(GIB, Math.max(1, Math.floor(limits.memoryMb / 4)) * MIB);
1242
+ if (network.kind === "open-public") {
1243
+ if (refuseOpenNetwork) {
1244
+ throw new Error(
1245
+ 'Sandbox network "open-public" is refused: the device-docker plugin setting refuseOpenNetwork is true. Set extensionConfig."device-docker".refuseOpenNetwork to false, or have the org switch its cloud network to the allowlist.'
1246
+ );
1247
+ }
1248
+ return { mode: "open-public", allowHosts: [], shmBytes };
1249
+ }
1250
+ if (network.hosts.length === 0) return { mode: "none", allowHosts: [], shmBytes };
1251
+ return { mode: "allowlist", allowHosts: [...network.hosts], shmBytes };
1252
+ }
1253
+ function sandboxEnv(name, mode) {
1254
+ const env = ["HOME=/workspace", "LANG=C.UTF-8"];
1255
+ if (mode === "none") return env;
1256
+ const host = sandboxResourceNames(name).egress;
1257
+ const proxy = `http://${host}:${PROXY_PORT}`;
1258
+ return [
1259
+ ...env,
1260
+ `HTTP_PROXY=${proxy}`,
1261
+ `HTTPS_PROXY=${proxy}`,
1262
+ `http_proxy=${proxy}`,
1263
+ `https_proxy=${proxy}`,
1264
+ "NO_PROXY=localhost,127.0.0.1,::1",
1265
+ "no_proxy=localhost,127.0.0.1,::1",
1266
+ `ALL_PROXY=${proxy}`,
1267
+ `all_proxy=${proxy}`,
1268
+ `GRPC_PROXY=${proxy}`,
1269
+ `grpc_proxy=${proxy}`,
1270
+ `GIT_SSH_COMMAND=ssh -o ProxyCommand='nc -X 5 -x ${host}:${SOCKS_PORT} %h %p'`
1271
+ ];
1272
+ }
1273
+ function egressProxyEnv(mode, allowHosts, testHosts, deniedCidrs = [], testResolve) {
1274
+ const env = [`MODE=${mode}`, `PORT=${PROXY_PORT}`, `SOCKS_PORT=${SOCKS_PORT}`];
1275
+ if (mode === "allowlist") env.push(`ALLOW_HOSTS=${JSON.stringify(allowHosts)}`);
1276
+ if (deniedCidrs.length > 0) env.push(`DENIED_CIDRS=${JSON.stringify(deniedCidrs)}`);
1277
+ if (testHosts) env.push(`CAPYBARA_EGRESS_TEST_HOSTS=${JSON.stringify(testHosts)}`);
1278
+ if (testResolve) env.push(`CAPYBARA_EGRESS_TEST_RESOLVE=${JSON.stringify(testResolve)}`);
1279
+ return env;
1280
+ }
1281
+ var INHIBIT_IPV4 = "com.docker.network.bridge.inhibit_ipv4";
1282
+ function internalNetworkCreateBody(name, labels) {
1283
+ return {
1284
+ Name: sandboxResourceNames(name).network,
1285
+ Driver: "bridge",
1286
+ Internal: true,
1287
+ EnableIPv6: false,
1288
+ Options: { [INHIBIT_IPV4]: "true" },
1289
+ Labels: labels
1290
+ };
1291
+ }
1292
+ function internalNetworkHardened(options) {
1293
+ return options?.[INHIBIT_IPV4] === "true";
1294
+ }
1295
+ var MIN_ENGINE_MAJOR = 25;
1296
+ function engineSupported(version) {
1297
+ const major = /^(\d+)\./.exec(version)?.[1];
1298
+ return major !== void 0 && Number(major) >= MIN_ENGINE_MAJOR;
1299
+ }
1300
+ function hostDeniedCidrs(endpoint, interfaces = networkInterfaces()) {
1301
+ let host;
1302
+ if (endpoint.startsWith("/") || endpoint.startsWith("unix:")) host = "localhost";
1303
+ else {
1304
+ try {
1305
+ host = new URL(endpoint.replace(/^tcp:/, "http:")).hostname.replace(/^\[|\]$/g, "");
1306
+ } catch {
1307
+ return [];
1308
+ }
1309
+ }
1310
+ const local = host === "localhost" || host === "::1" || /^127\./.test(host);
1311
+ if (!local) return [];
1312
+ const out = [];
1313
+ for (const list of Object.values(interfaces)) {
1314
+ for (const i of list ?? []) {
1315
+ if (i.internal) continue;
1316
+ const address = i.address.split("%")[0];
1317
+ const family = isIP(address);
1318
+ if (family === 4) out.push(`${address}/32`);
1319
+ else if (family === 6) out.push(`${address}/128`);
1320
+ }
1321
+ }
1322
+ return [...new Set(out)];
1323
+ }
1324
+ function planLabels(plan) {
1325
+ return {
1326
+ [LABEL_NET]: plan.mode,
1327
+ [LABEL_ALLOW]: JSON.stringify(plan.allowHosts)
1328
+ };
1329
+ }
1330
+ function labelNetwork(labels) {
1331
+ const kind = labels[LABEL_NET];
1332
+ if (kind !== "none" && kind !== "open-public" && kind !== "allowlist") return null;
1333
+ let allowHosts = [];
1334
+ try {
1335
+ const parsed = JSON.parse(labels[LABEL_ALLOW] ?? "[]");
1336
+ if (Array.isArray(parsed)) allowHosts = parsed.filter((h) => typeof h === "string");
1337
+ } catch {
1338
+ return null;
1339
+ }
1340
+ return { mode: kind, allowHosts };
1341
+ }
1342
+ function updateDecision(labels, plan) {
1343
+ const from = labelNetwork(labels);
1344
+ if (from === null) return "recreate";
1345
+ if (plan.mode === "none" || from.mode === "none") return "recreate";
1346
+ if (plan.mode === "open-public" || from.mode === "open-public") {
1347
+ return plan.mode === from.mode ? "updated" : "recreate";
1348
+ }
1349
+ return from.allowHosts.every((h) => plan.allowHosts.includes(h)) ? "updated" : "recreate";
1350
+ }
1351
+ function proxyModeOf(plan) {
1352
+ if (plan.mode === "none") throw new Error("no-network plan cannot be applied in place");
1353
+ return plan.mode;
1354
+ }
1355
+ var IN_SANDBOX_GRACE_SECONDS = 5;
1356
+ var EXEC_WRAPPER = 'c=$1; echo $$ > "$c.pid" 2>/dev/null; if [ -e "$c.kill" ]; then exit 137; fi; timeout -s KILL "$3" /bin/bash -c "$2"; s=$?; if [ $s -eq 124 ] || [ $s -eq 137 ]; then for p in $(pgrep -s $$); do [ "$p" = $$ ] || kill -9 "$p" 2>/dev/null; done; fi; rm -f "$c.pid"; exit $s';
1357
+ function execArgv(ctl, command, timeoutMs) {
1358
+ const seconds = Math.ceil(timeoutMs / 1e3) + IN_SANDBOX_GRACE_SECONDS;
1359
+ return [
1360
+ "setsid",
1361
+ "-w",
1362
+ "/bin/sh",
1363
+ "-c",
1364
+ EXEC_WRAPPER,
1365
+ "capybara-exec",
1366
+ ctl,
1367
+ command,
1368
+ String(seconds)
1369
+ ];
1370
+ }
1371
+ var KILL_TREE = 'k() { for t in $(pgrep -P "$1"); do kill -9 -"$t" 2>/dev/null; done; kill -9 -"$1" 2>/dev/null; pkill -9 -s "$1" 2>/dev/null; }; ';
1372
+ var TERM_AGENTS = 'g() { a="capybara-operation[.]py (exec|native) capybara-exec $1"; for q in $(pgrep -f -- "$a"); do kill -TERM "$q" 2>/dev/null; done; i=0; while pgrep -f -- "$a" >/dev/null && [ $i -lt 200 ]; do sleep 0.05; i=$((i+1)); done; }; ';
1373
+ var KILL_ALL_SCRIPT = `${KILL_TREE}${TERM_AGENTS}g "/tmp/[.]capybara-exec-"; for q in $(pgrep -f -- "capybara-exec /tmp/[.]capybara-exec-"); do k "$q"; kill -9 "$q" 2>/dev/null; done; exit 0`;
1374
+ var KILL_TAGGED_SCRIPT = `${KILL_TREE}${TERM_AGENTS}u='[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'; a=$(printf "%s|" "$@" | sed "s/|$//"); g "/tmp/[.]capybara-exec-($a)-$u( |$)"; for t in "$@"; do for q in $(pgrep -f -- "capybara-exec /tmp/[.]capybara-exec-$t-$u( |$)"); do k "$q"; kill -9 "$q" 2>/dev/null; done; done; exit 0`;
1375
+ var KILL_OPERATION_SCRIPT = `${KILL_TREE}for q in $(pgrep -f -- "capybara-exec /tmp/[.]capybara-exec-[a-z0-9-]+-$1( |$)"); do k "$q"; kill -9 "$q" 2>/dev/null; done; exit 0`;
1376
+ function execControlPath(tag) {
1377
+ if (tag !== void 0 && !SANDBOX_TAG_RE.test(tag)) throw new Error("invalid sandbox tag");
1378
+ return tag === void 0 ? `/tmp/.capybara-exec-${randomUUID()}` : `/tmp/.capybara-exec-${tag}-${randomUUID()}`;
1379
+ }
1380
+ var KILL_SCRIPT = `${KILL_TREE}c=$1; : > "$c.kill" 2>/dev/null; i=0; while [ ! -s "$c.pid" ] && [ $i -lt 20 ]; do sleep 0.05; i=$((i+1)); done; p=$(cat "$c.pid" 2>/dev/null); if [ -n "$p" ]; then k "$p"; rm -f "$c.kill"; fi; for q in $(pgrep -f -- "capybara-exec $c"); do k "$q"; kill -9 "$q" 2>/dev/null; done; rm -f "$c.pid"; exit 0`;
1381
+ var READ_SCRIPT = 'if [ ! -e "$1" ]; then exit 3; fi; if [ -d "$1" ]; then exit 4; fi; exec head -c "$2" -- "$1"';
1382
+ var WRITE_SCRIPT = 'set -e; mkdir -p -- "$(dirname -- "$1")"; head -c "$2" > "$1"';
1383
+ var STAT_SCRIPT = 'if [ ! -e "$1" ]; then exit 3; fi; exec stat -L -c "%s %F" -- "$1"';
1384
+ function after(ms, fn) {
1385
+ const t = AbortSignal.timeout(ms);
1386
+ t.addEventListener("abort", fn, { once: true });
1387
+ return { cancel: () => t.removeEventListener("abort", fn) };
1388
+ }
1389
+ function sleep(ms, signal) {
1390
+ signal.throwIfAborted();
1391
+ return new Promise((resolve, reject) => {
1392
+ const onAbort = () => {
1393
+ t.cancel();
1394
+ reject(abortReason(signal));
1395
+ };
1396
+ const t = after(ms, () => {
1397
+ signal.removeEventListener("abort", onAbort);
1398
+ resolve();
1399
+ });
1400
+ signal.addEventListener("abort", onAbort, { once: true });
1401
+ });
1402
+ }
1403
+ function checkPath2(p) {
1404
+ const errors = validateSandboxPathShape3(p);
1405
+ if (errors.length > 0)
1406
+ throw new Error(`invalid sandbox path ${JSON.stringify(p)}: ${errors.join("; ")}`);
1407
+ if (p === RECORDS_VIEW || p.startsWith(`${RECORDS_VIEW}/`)) {
1408
+ throw new Error(`sandbox path ${JSON.stringify(p)} is reserved for the provider's records`);
1409
+ }
1410
+ }
1411
+ var RECORDS_VIEW = "/skills/.capybara-ops";
1412
+ var NotRunningError = class extends Error {
1413
+ constructor(container, opts) {
1414
+ super(`sandbox container ${container} is not running`, opts);
1415
+ this.name = "NotRunningError";
1416
+ }
1417
+ };
1418
+ function createDockerSandbox(cfg, test = {}, log) {
1419
+ const api = createDockerClient(cfg.endpoint);
1420
+ const baseLabels = (name, role) => ({
1421
+ ...test.labels,
1422
+ [LABEL]: "1",
1423
+ [LABEL_NAME]: name,
1424
+ [LABEL_ROLE]: role
1425
+ });
1426
+ const enc = encodeURIComponent;
1427
+ const postCreate = async (path, opts) => {
1428
+ const text = JSON.stringify(opts.body ?? null);
1429
+ if (/[^\x00-\x7f]/.test(text)) {
1430
+ throw new Error(
1431
+ `device-docker: ${path} request contains non-ASCII characters (image, names, labels, environment and allowHosts must be ASCII; use punycode for hostnames)`
1432
+ );
1433
+ }
1434
+ return api.json("POST", path, opts);
1435
+ };
1436
+ const ignore = (...status) => (e) => {
1437
+ if (!isStatus(e, ...status)) throw e;
1438
+ };
1439
+ const removeWithRetry = async (path, signal) => {
1440
+ for (let i = 0; ; i++) {
1441
+ try {
1442
+ await api.json("DELETE", path, { signal });
1443
+ return;
1444
+ } catch (e) {
1445
+ if (isStatus(e, 404)) return;
1446
+ if (i >= 20 || !isStatus(e, 403, 409, 500)) throw e;
1447
+ await sleep(250, signal);
1448
+ }
1449
+ }
1450
+ };
1451
+ const destroyByName = async (name, signal) => {
1452
+ signal.throwIfAborted();
1453
+ const n = sandboxResourceNames(name);
1454
+ await Promise.all(
1455
+ [n.container, n.egress].map(
1456
+ (c) => api.json("DELETE", `/containers/${enc(c)}`, { query: { force: true }, signal }).catch(ignore(404, 409))
1457
+ )
1458
+ );
1459
+ await removeWithRetry(`/networks/${enc(n.network)}`, signal);
1460
+ };
1461
+ const destroyFileSystemByName = async (name, signal) => {
1462
+ signal.throwIfAborted();
1463
+ if (!NAME_RE.test(name)) throw new Error(`invalid sandbox name: ${name}`);
1464
+ const n = sandboxResourceNames(name);
1465
+ await destroyByName(name, signal);
1466
+ await Promise.all([
1467
+ removeWithRetry(`/volumes/${enc(n.workspace)}`, signal),
1468
+ removeWithRetry(`/volumes/${enc(n.skills)}`, signal)
1469
+ ]);
1470
+ };
1471
+ const checkFileSystem = async (fsId, signal) => {
1472
+ const n = sandboxResourceNames(fsId);
1473
+ const found = await Promise.all(
1474
+ [
1475
+ [n.workspace, "workspace"],
1476
+ [n.skills, "skills"]
1477
+ ].map(async ([vol, role]) => {
1478
+ try {
1479
+ const v = await api.json(
1480
+ "GET",
1481
+ `/volumes/${enc(vol)}`,
1482
+ { signal }
1483
+ );
1484
+ return { vol, state: v.Labels?.[LABEL_ROLE] === role ? "ok" : "unlabelled" };
1485
+ } catch (e) {
1486
+ if (isStatus(e, 404)) return { vol, state: "missing" };
1487
+ throw e;
1488
+ }
1489
+ })
1490
+ );
1491
+ return {
1492
+ ok: found.every((f) => f.state === "ok"),
1493
+ unlabelled: found.filter((f) => f.state === "unlabelled").map((f) => f.vol)
1494
+ };
1495
+ };
1496
+ const ensureVolume = async (body, signal) => {
1497
+ try {
1498
+ await api.json("GET", `/volumes/${enc(body.Name)}`, { signal });
1499
+ return;
1500
+ } catch (e) {
1501
+ if (!isStatus(e, 404)) throw e;
1502
+ }
1503
+ await postCreate("/volumes/create", { body, signal });
1504
+ };
1505
+ const pull = async (image, signal) => {
1506
+ await api.json("POST", "/images/create", { query: { fromImage: image }, signal });
1507
+ };
1508
+ const createContainer = async (name, body, signal) => {
1509
+ const go = () => postCreate("/containers/create", { query: { name }, body, signal });
1510
+ try {
1511
+ await go();
1512
+ } catch (e) {
1513
+ if (!(isStatus(e, 404) && /no such image/i.test(e.message))) throw e;
1514
+ await pull(String(body.Image), signal);
1515
+ await go();
1516
+ }
1517
+ };
1518
+ const start = (container, signal) => api.json("POST", `/containers/${enc(container)}/start`, { signal }).catch(ignore(304));
1519
+ const unpause = (container, signal) => api.json("POST", `/containers/${enc(container)}/unpause`, { signal }).catch(ignore(409));
1520
+ const ensureSharedNetwork = async (signal) => {
1521
+ try {
1522
+ await api.json("GET", `/networks/${enc(cfg.network)}`, { signal });
1523
+ } catch (e) {
1524
+ if (!isStatus(e, 404)) throw e;
1525
+ await postCreate("/networks/create", {
1526
+ body: {
1527
+ Name: cfg.network,
1528
+ Driver: "bridge",
1529
+ // Containers on the shared network (the egress proxies) cannot reach each other.
1530
+ Options: { "com.docker.network.bridge.enable_icc": "false" },
1531
+ Labels: { ...test.labels, [LABEL]: "1", [LABEL_ROLE]: "shared-network" }
1532
+ },
1533
+ signal
1534
+ }).catch(ignore(409));
1535
+ }
1536
+ };
1537
+ let engineChecked;
1538
+ const checkEngine = (signal) => {
1539
+ engineChecked ??= api.json("GET", "/version", { signal }).then((v) => {
1540
+ if (!engineSupported(String(v.Version ?? ""))) {
1541
+ throw new Error(
1542
+ `device-docker needs Docker Engine ${MIN_ENGINE_MAJOR} or newer (found ${String(v.Version)}): older bridge drivers keep a host gateway on the sandbox's internal network. Upgrade Docker.`
1543
+ );
1544
+ }
1545
+ }).catch((e) => {
1546
+ engineChecked = void 0;
1547
+ throw e;
1548
+ });
1549
+ return engineChecked;
1550
+ };
1551
+ const ensureInternalNetwork = async (name, signal) => {
1552
+ const n = sandboxResourceNames(name);
1553
+ try {
1554
+ const existing = await api.json(
1555
+ "GET",
1556
+ `/networks/${enc(n.network)}`,
1557
+ { signal }
1558
+ );
1559
+ return internalNetworkHardened(existing.Options);
1560
+ } catch (e) {
1561
+ if (!isStatus(e, 404)) throw e;
1562
+ await checkEngine(signal);
1563
+ await postCreate("/networks/create", {
1564
+ body: internalNetworkCreateBody(name, baseLabels(name, "network")),
1565
+ signal
1566
+ }).catch(ignore(409));
1567
+ return true;
1568
+ }
1569
+ };
1570
+ const waitEgressReady = async (container, signal) => {
1571
+ for (let i = 0; ; i++) {
1572
+ const r = await run(container, {
1573
+ cmd: ["wget", "-q", "-O", "-", `http://127.0.0.1:${PROXY_PORT}/healthz`],
1574
+ user: "",
1575
+ maxOutputBytes: 1024,
1576
+ signal
1577
+ }).catch((e) => {
1578
+ if (signal.aborted) throw abortReason(signal);
1579
+ if (i >= 50) throw e;
1580
+ return null;
1581
+ });
1582
+ if (r?.exitCode === 0) return;
1583
+ if (i >= 50) throw new Error("sandbox egress proxy did not become ready");
1584
+ await sleep(100, signal);
1585
+ }
1586
+ };
1587
+ const createEgress = async (name, mode, allowHosts, signal, mayExist = false) => {
1588
+ const n = sandboxResourceNames(name);
1589
+ const made = createContainer(
1590
+ n.egress,
1591
+ {
1592
+ Image: cfg.egressProxyImage,
1593
+ Env: egressProxyEnv(
1594
+ mode,
1595
+ allowHosts,
1596
+ test.egressTestHosts,
1597
+ [...cfg.deniedCidrs ?? [], ...hostDeniedCidrs(cfg.endpoint)],
1598
+ test.egressTestResolve
1599
+ ),
1600
+ Labels: {
1601
+ ...baseLabels(name, "egress"),
1602
+ [LABEL_EGRESS_MODE]: mode,
1603
+ [LABEL_ALLOW]: JSON.stringify(allowHosts)
1604
+ },
1605
+ HostConfig: {
1606
+ NetworkMode: cfg.network,
1607
+ Init: true,
1608
+ ReadonlyRootfs: true,
1609
+ CapDrop: ["ALL"],
1610
+ SecurityOpt: ["no-new-privileges:true"],
1611
+ Memory: 128 * MIB,
1612
+ MemorySwap: 128 * MIB,
1613
+ NanoCpus: 5e8,
1614
+ PidsLimit: 128
1615
+ },
1616
+ NetworkingConfig: { EndpointsConfig: { [cfg.network]: {}, [n.network]: {} } }
1617
+ },
1618
+ signal
1619
+ );
1620
+ await (mayExist ? made.catch(ignore(409)) : made);
1621
+ await start(n.egress, signal);
1622
+ await waitEgressReady(n.egress, signal);
1623
+ };
1624
+ const ensureEgressRunning = async (name, mode, allowHosts, signal) => {
1625
+ const n = sandboxResourceNames(name);
1626
+ await ensureSharedNetwork(signal);
1627
+ if (!await ensureInternalNetwork(name, signal)) return false;
1628
+ let running;
1629
+ try {
1630
+ const c = await api.json(
1631
+ "GET",
1632
+ `/containers/${enc(n.egress)}/json`,
1633
+ { signal }
1634
+ );
1635
+ if (c.State.Paused) await unpause(n.egress, signal);
1636
+ running = c.State.Running;
1637
+ } catch (e) {
1638
+ if (!isStatus(e, 404)) throw e;
1639
+ await createEgress(name, mode, allowHosts, signal, true);
1640
+ return true;
1641
+ }
1642
+ if (!running) {
1643
+ await start(n.egress, signal);
1644
+ await waitEgressReady(n.egress, signal);
1645
+ }
1646
+ return true;
1647
+ };
1648
+ async function run(container, o) {
1649
+ o.signal.throwIfAborted();
1650
+ const startedAt = Date.now();
1651
+ let execId;
1652
+ try {
1653
+ const r = await api.json("POST", `/containers/${enc(container)}/exec`, {
1654
+ body: {
1655
+ AttachStdin: o.stdin !== void 0,
1656
+ AttachStdout: true,
1657
+ AttachStderr: true,
1658
+ Tty: false,
1659
+ Cmd: o.cmd,
1660
+ ...o.user !== "" && { User: o.user },
1661
+ ...o.env && { Env: o.env },
1662
+ ...o.cwd !== void 0 && { WorkingDir: o.cwd }
1663
+ },
1664
+ signal: o.signal
1665
+ });
1666
+ execId = r.Id;
1667
+ } catch (e) {
1668
+ if (isStatus(e, 404)) {
1669
+ throw new SandboxGoneError(`sandbox container ${container} no longer exists`, { cause: e });
1670
+ }
1671
+ if (isStatus(e, 409)) throw new NotRunningError(container, { cause: e });
1672
+ throw e;
1673
+ }
1674
+ let socket;
1675
+ try {
1676
+ socket = await api.hijack(`/exec/${execId}/start`, { Detach: false, Tty: false }, o.signal);
1677
+ } catch (e) {
1678
+ if (isStatus(e, 404)) {
1679
+ throw new SandboxGoneError(`sandbox container ${container} no longer exists`, { cause: e });
1680
+ }
1681
+ if (isStatus(e, 409)) throw new NotRunningError(container, { cause: e });
1682
+ if (!o.signal.aborted) throw e;
1683
+ await o.kill?.().catch(() => void 0);
1684
+ return {
1685
+ exitCode: null,
1686
+ stdout: Buffer.alloc(0),
1687
+ stderr: Buffer.alloc(0),
1688
+ truncated: false,
1689
+ timedOut: false,
1690
+ aborted: true
1691
+ };
1692
+ }
1693
+ const out = [];
1694
+ const err = [];
1695
+ let used = 0;
1696
+ let truncated = false;
1697
+ let timedOut = false;
1698
+ let aborted = false;
1699
+ let stopping = false;
1700
+ const demux = new StreamDemuxer((kind, data) => {
1701
+ const room = o.maxOutputBytes - used;
1702
+ if (data.byteLength > room) truncated = true;
1703
+ if (room <= 0) return;
1704
+ const keep = data.byteLength > room ? data.subarray(0, room) : data;
1705
+ used += keep.byteLength;
1706
+ (kind === 1 ? out : err).push(Buffer.from(keep));
1707
+ });
1708
+ const ended = new Promise((resolve) => {
1709
+ socket.on("data", (c) => demux.push(c));
1710
+ socket.on("error", (e) => resolve(e));
1711
+ socket.on("close", () => resolve(null));
1712
+ socket.on("end", () => {
1713
+ socket.destroy();
1714
+ resolve(null);
1715
+ });
1716
+ });
1717
+ let grace;
1718
+ let killing;
1719
+ const stop = () => {
1720
+ if (stopping) return;
1721
+ stopping = true;
1722
+ const cut = () => {
1723
+ grace = after(KILL_GRACE_MS, () => socket.destroy());
1724
+ };
1725
+ if (o.kill)
1726
+ killing = o.kill().catch(() => void 0).finally(cut);
1727
+ else socket.destroy();
1728
+ };
1729
+ const timer = o.timeoutMs === void 0 ? void 0 : after(o.timeoutMs, () => {
1730
+ timedOut = true;
1731
+ stop();
1732
+ });
1733
+ const onAbort = () => {
1734
+ aborted = true;
1735
+ stop();
1736
+ };
1737
+ o.signal.addEventListener("abort", onAbort, { once: true });
1738
+ if (o.signal.aborted) onAbort();
1739
+ if (o.stdin !== void 0 && o.stdin.byteLength > 0) socket.write(o.stdin);
1740
+ const streamError = await ended;
1741
+ await killing;
1742
+ timer?.cancel();
1743
+ grace?.cancel();
1744
+ o.signal.removeEventListener("abort", onAbort);
1745
+ const result = {
1746
+ stdout: Buffer.concat(out),
1747
+ stderr: Buffer.concat(err),
1748
+ truncated,
1749
+ timedOut,
1750
+ aborted
1751
+ };
1752
+ if (timedOut || aborted) return { ...result, exitCode: null };
1753
+ if (streamError) throw streamError;
1754
+ const deadline = o.timeoutMs !== void 0 ? startedAt + o.timeoutMs : Date.now() + EXIT_WAIT_MS;
1755
+ try {
1756
+ for (; ; ) {
1757
+ const s = await api.json(
1758
+ "GET",
1759
+ `/exec/${execId}/json`,
1760
+ { signal: AbortSignal.any([o.signal, AbortSignal.timeout(1e4)]) }
1761
+ );
1762
+ if (!s.Running) return { ...result, exitCode: s.ExitCode };
1763
+ if (Date.now() >= deadline) {
1764
+ if (!o.kill) throw new Error("sandbox command did not report an exit status");
1765
+ await o.kill().catch(() => void 0);
1766
+ return { ...result, timedOut: true, exitCode: null };
1767
+ }
1768
+ await sleep(50, o.signal);
1769
+ }
1770
+ } catch (e) {
1771
+ if (o.signal.aborted) {
1772
+ await o.kill?.().catch(() => void 0);
1773
+ return { ...result, aborted: true, exitCode: null };
1774
+ }
1775
+ throw e;
1776
+ }
1777
+ }
1778
+ const killer = (container, ctl) => () => (
1779
+ // 杀进程不受调用方 signal 影响(它往往正是已中止的那个)
1780
+ killOrRestart(container, ["/bin/sh", "-c", KILL_SCRIPT, "capybara-kill", ctl])
1781
+ );
1782
+ const killOrRestart = async (container, cmd, signal) => {
1783
+ const within = (ms) => signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
1784
+ const ok = await run(container, {
1785
+ cmd,
1786
+ user: SANDBOX_USER,
1787
+ maxOutputBytes: 4096,
1788
+ signal: within(15e3)
1789
+ }).then(
1790
+ (r) => r.exitCode === 0 && !r.aborted,
1791
+ () => false
1792
+ );
1793
+ if (ok) return;
1794
+ signal?.throwIfAborted();
1795
+ log?.warn(
1796
+ "device-docker: the kill command could not run; restarting the container, which also ends other commands in it",
1797
+ { container }
1798
+ );
1799
+ await api.json("POST", `/containers/${enc(container)}/restart`, {
1800
+ query: { t: 0 },
1801
+ signal: within(6e4)
1802
+ });
1803
+ await initRecords(container);
1804
+ };
1805
+ async function initRecords(container) {
1806
+ const body = Buffer.from("2\n{}");
1807
+ await run(container, {
1808
+ cmd: ["/usr/bin/python3", "-I", OPERATION_AGENT, "init"],
1809
+ user: ROOT_USER,
1810
+ stdin: body,
1811
+ maxOutputBytes: 1 << 20,
1812
+ signal: AbortSignal.timeout(6e4)
1813
+ }).catch(() => void 0);
1814
+ }
1815
+ const fileOp = async (h, o, signal) => {
1816
+ const r = await autoStart(h, signal, () => run(h.id, { ...o, signal }));
1817
+ if (r.aborted) throw abortReason(signal);
1818
+ return r;
1819
+ };
1820
+ const listOp = (h, op, path, limit, signal) => fileOp(
1821
+ h,
1822
+ {
1823
+ cmd: [
1824
+ "timeout",
1825
+ "-s",
1826
+ "KILL",
1827
+ String(LIST_TIMEOUT_SECONDS),
1828
+ "python3",
1829
+ "-I",
1830
+ "-c",
1831
+ LIST_SCRIPT,
1832
+ op,
1833
+ path,
1834
+ String(limit)
1835
+ ],
1836
+ user: SANDBOX_USER,
1837
+ env: [`PATH=${LIST_PATH}`],
1838
+ maxOutputBytes: LIST_MAX_OUTPUT_BYTES
1839
+ },
1840
+ signal
1841
+ );
1842
+ async function autoStart(h, signal, fn) {
1843
+ try {
1844
+ return await fn();
1845
+ } catch (e) {
1846
+ if (!(e instanceof NotRunningError)) throw e;
1847
+ if (await resume(h, signal) === "gone") {
1848
+ throw new SandboxGoneError(`sandbox container ${h.id} no longer exists`, { cause: e });
1849
+ }
1850
+ return await fn();
1851
+ }
1852
+ }
1853
+ async function resume(h, signal) {
1854
+ signal.throwIfAborted();
1855
+ let c;
1856
+ try {
1857
+ c = await api.json("GET", `/containers/${enc(h.id)}/json`, { signal });
1858
+ } catch (e) {
1859
+ if (isStatus(e, 404)) return "gone";
1860
+ throw e;
1861
+ }
1862
+ const labels = c.Config.Labels ?? {};
1863
+ const net = labelNetwork(labels) ?? { mode: "none", allowHosts: [] };
1864
+ if (net.mode === "open-public" && cfg.refuseOpenNetwork) return "gone";
1865
+ if (net.mode !== "none" && !await ensureEgressRunning(h.id, net.mode, net.allowHosts, signal))
1866
+ return "gone";
1867
+ try {
1868
+ if (c.State.Paused) await unpause(h.id, signal);
1869
+ else if (!c.State.Running) await start(h.id, signal);
1870
+ } catch (e) {
1871
+ if (isStatus(e, 404)) return "gone";
1872
+ throw e;
1873
+ }
1874
+ if (!c.State.Running) await initRecords(h.id);
1875
+ return "resumed";
1876
+ }
1877
+ const stderrOf = (r) => r.stderr.toString("utf8").trim().slice(0, 500);
1878
+ const execWith = async (h, args, ctl, prefix = [], nonce) => {
1879
+ args.signal.throwIfAborted();
1880
+ const env = [];
1881
+ for (const [k, v] of Object.entries(args.env ?? {})) {
1882
+ if (!ENV_KEY_RE2.test(k)) throw new Error(`invalid environment variable name: ${k}`);
1883
+ env.push(`${k}=${v}`);
1884
+ }
1885
+ if (nonce !== void 0) env.push(`CAPYBARA_ADMISSION_NONCE=${nonce}`);
1886
+ const r = await autoStart(
1887
+ h,
1888
+ args.signal,
1889
+ () => run(h.id, {
1890
+ cmd: [...prefix, ...execArgv(ctl, args.command, args.timeoutMs)],
1891
+ user: SANDBOX_USER,
1892
+ env,
1893
+ cwd: args.cwd ?? "/workspace",
1894
+ maxOutputBytes: args.maxOutputBytes,
1895
+ timeoutMs: args.timeoutMs,
1896
+ signal: args.signal,
1897
+ kill: killer(h.id, ctl)
1898
+ })
1899
+ );
1900
+ if (prefix.length > 0 && r.exitCode === 125 && r.stdout[0] === 82) {
1901
+ const refused = refusedFrame(r.stdout, nonce ?? "");
1902
+ if (refused === "cancelled") {
1903
+ return { exitCode: null, stdout: "", stderr: "", truncated: false, timedOut: false };
1904
+ }
1905
+ if (refused) throw refused;
1906
+ }
1907
+ return {
1908
+ exitCode: r.exitCode,
1909
+ stdout: decodeOutput(r.stdout, r.truncated),
1910
+ stderr: decodeOutput(r.stderr, r.truncated),
1911
+ truncated: r.truncated,
1912
+ timedOut: r.timedOut
1913
+ };
1914
+ };
1915
+ const userOf = (u) => u === "root" ? ROOT_USER : SANDBOX_USER;
1916
+ const transport = {
1917
+ run: (h, o) => autoStart(
1918
+ h,
1919
+ o.signal,
1920
+ () => run(h.id, { ...o, user: userOf(o.user), cwd: "/", ...o.kill && { kill: o.kill } })
1921
+ ),
1922
+ async runIfRunning(h, o) {
1923
+ try {
1924
+ return await run(h.id, { ...o, user: userOf(o.user), cwd: "/" });
1925
+ } catch (e) {
1926
+ if (e instanceof NotRunningError) return "not-running";
1927
+ throw e;
1928
+ }
1929
+ },
1930
+ execFull: (h, args, ctl, prefix, nonce) => execWith(h, args, ctl, prefix, nonce),
1931
+ async appliedNetwork(h, signal) {
1932
+ try {
1933
+ const c = await api.json(
1934
+ "GET",
1935
+ `/containers/${enc(h.id)}/json`,
1936
+ { signal }
1937
+ );
1938
+ return labelNetwork(c.Config.Labels ?? {});
1939
+ } catch (e) {
1940
+ if (isStatus(e, 404)) {
1941
+ throw new SandboxGoneError(`sandbox container ${h.id} no longer exists`, { cause: e });
1942
+ }
1943
+ throw e;
1944
+ }
1945
+ },
1946
+ killOperation: async (h, uuid, signal) => {
1947
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(uuid)) {
1948
+ throw new Error("invalid operation control id");
1949
+ }
1950
+ await killOrRestart(
1951
+ h.id,
1952
+ ["/bin/sh", "-c", KILL_OPERATION_SCRIPT, "capybara-killop", uuid],
1953
+ signal
1954
+ );
1955
+ },
1956
+ backgroundLaunchBarrier: test.backgroundLaunchBarrier,
1957
+ afterRevokeKill: test.afterRevokeKill,
1958
+ backgroundSpoolCapBytes: test.backgroundSpoolCapBytes,
1959
+ beforeBackgroundLaunch: test.beforeBackgroundLaunch,
1960
+ loseBackgroundAck: test.loseBackgroundAck,
1961
+ backgroundStartCommand: test.backgroundStartCommand,
1962
+ interceptBackgroundStdin: test.interceptBackgroundStdin
1963
+ };
1964
+ const operations = createOperations({
1965
+ transport,
1966
+ network: { openPublic: !cfg.refuseOpenNetwork }
1967
+ });
1968
+ const report = async (device, signal) => {
1969
+ signal.throwIfAborted();
1970
+ const limits = device.handle === null ? null : await instanceLimits(device.handle, signal);
1971
+ const lines = limits === null ? [] : reportLimitLines(limits);
1972
+ const revision = [
1973
+ cfg.version ?? "unversioned",
1974
+ cfg.runtime,
1975
+ device.handle?.id ?? "none",
1976
+ ...limits === null ? [] : [limitsRevision(limits)]
1977
+ ].join(":");
1978
+ return {
1979
+ revision,
1980
+ description: {
1981
+ en: "A Docker container (runc or gVisor) with its files on a volume; the container is the sandbox.",
1982
+ zh: "Docker 容器(runc 或 gVisor),文件保存在卷上;容器本身就是沙箱。"
1983
+ },
1984
+ home: null,
1985
+ limits: lines,
1986
+ reset: true
1987
+ };
1988
+ };
1989
+ const instanceLimits = async (h, signal) => {
1990
+ let c;
1991
+ try {
1992
+ c = await api.json("GET", `/containers/${enc(h.id)}/json`, { signal });
1993
+ } catch (e) {
1994
+ if (isStatus(e, 404)) return null;
1995
+ throw e;
1996
+ }
1997
+ let diskMb = null;
1998
+ if (cfg.volumeDriver !== void 0) {
1999
+ try {
2000
+ const v = await api.json(
2001
+ "GET",
2002
+ `/volumes/${enc(sandboxResourceNames(h.id).workspace)}`,
2003
+ { signal }
2004
+ );
2005
+ diskMb = parseSizeMb(v.Options?.size);
2006
+ } catch (e) {
2007
+ if (!isStatus(e, 404)) throw e;
2008
+ }
2009
+ }
2010
+ const nanoCpus = c.HostConfig?.NanoCpus ?? 0;
2011
+ const memory = c.HostConfig?.Memory ?? 0;
2012
+ return {
2013
+ cpu: nanoCpus > 0 ? nanoCpus / 1e9 : null,
2014
+ memoryMb: memory > 0 ? Math.round(memory / MIB) : null,
2015
+ diskMb
2016
+ };
2017
+ };
2018
+ return {
2019
+ // docker exec instances are independent; auto-start tolerates concurrent starts (304 / 409)
2020
+ concurrentExec: true,
2021
+ limitsApplyAt: "instance",
2022
+ // the egress proxy enforces a host allowlist (an empty one is NetworkMode none)
2023
+ networkAllowlist: true,
2024
+ report,
2025
+ async createFileSystem({ name, limits, signal }) {
2026
+ signal.throwIfAborted();
2027
+ if (!NAME_RE.test(name)) throw new Error(`invalid sandbox name: ${name}`);
2028
+ checkLimits(limits);
2029
+ const n = sandboxResourceNames(name);
2030
+ await ensureVolume(
2031
+ {
2032
+ Name: n.workspace,
2033
+ Labels: baseLabels(name, "workspace"),
2034
+ ...cfg.volumeDriver !== void 0 && {
2035
+ Driver: cfg.volumeDriver,
2036
+ DriverOpts: { size: `${limits.diskMb}M` }
2037
+ }
2038
+ },
2039
+ signal
2040
+ );
2041
+ await ensureVolume({ Name: n.skills, Labels: baseLabels(name, "skills") }, signal);
2042
+ return { id: name };
2043
+ },
2044
+ async destroyFileSystem(fs, signal) {
2045
+ await destroyFileSystemByName(fs.id, signal);
2046
+ },
2047
+ destroyFileSystemByName,
2048
+ async create({ name, image, limits, fileSystem, signal }) {
2049
+ signal.throwIfAborted();
2050
+ if (!NAME_RE.test(name)) throw new Error(`invalid sandbox name: ${name}`);
2051
+ if (!NAME_RE.test(fileSystem.id)) {
2052
+ throw new Error(`invalid file system id: ${fileSystem.id}`);
2053
+ }
2054
+ checkLimits(limits);
2055
+ const sandboxImage = image ?? cfg.defaultImage;
2056
+ if (sandboxImage === void 0) {
2057
+ throw new Error("device-docker: create got no image and the provider has no default image");
2058
+ }
2059
+ const plan = planInstance(limits, cfg.refuseOpenNetwork);
2060
+ const n = sandboxResourceNames(name);
2061
+ const v = sandboxResourceNames(fileSystem.id);
2062
+ const gone = () => new FileSystemGoneError(
2063
+ `sandbox file system ${fileSystem.id} is gone (volume ${v.workspace} or ${v.skills} missing)`
2064
+ );
2065
+ if (!(await checkFileSystem(fileSystem.id, signal)).ok) throw gone();
2066
+ await destroyByName(name, signal);
2067
+ try {
2068
+ let networkMode = "none";
2069
+ if (plan.mode !== "none") {
2070
+ await ensureSharedNetwork(signal);
2071
+ await ensureInternalNetwork(name, signal);
2072
+ await createEgress(name, plan.mode, plan.allowHosts, signal);
2073
+ networkMode = n.network;
2074
+ }
2075
+ const memory = limits.memoryMb * MIB;
2076
+ const tmpMb = Math.max(16, Math.min(limits.diskMb, Math.floor(limits.memoryMb / 2)));
2077
+ await createContainer(
2078
+ n.container,
2079
+ {
2080
+ Image: sandboxImage,
2081
+ User: INIT_USER,
2082
+ WorkingDir: "/workspace",
2083
+ Cmd: ["sleep", "infinity"],
2084
+ Env: sandboxEnv(name, plan.mode),
2085
+ Labels: { ...baseLabels(name, "sandbox"), ...planLabels(plan) },
2086
+ HostConfig: {
2087
+ Runtime: cfg.runtime,
2088
+ Init: true,
2089
+ NanoCpus: Math.round(limits.cpu * 1e9),
2090
+ Memory: memory,
2091
+ MemorySwap: memory,
2092
+ PidsLimit: PIDS_LIMIT,
2093
+ ReadonlyRootfs: true,
2094
+ CapDrop: ["ALL"],
2095
+ SecurityOpt: ["no-new-privileges:true"],
2096
+ IpcMode: "private",
2097
+ NetworkMode: networkMode,
2098
+ // One profile for every instance: room for browsers and other shared-memory users.
2099
+ ShmSize: plan.shmBytes,
2100
+ Tmpfs: { "/tmp": `rw,nosuid,nodev,size=${tmpMb}m,mode=1777` },
2101
+ Mounts: [
2102
+ { Type: "volume", Source: v.workspace, Target: "/workspace" },
2103
+ { Type: "volume", Source: v.skills, Target: "/skills", ReadOnly: true },
2104
+ // Writable mount of the same volume: only root can enter it (/opt/capybara is
2105
+ // 0700), and the plugin writes skills through it.
2106
+ { Type: "volume", Source: v.skills, Target: "/opt/capybara/skills" }
2107
+ ]
2108
+ }
2109
+ },
2110
+ signal
2111
+ );
2112
+ const after2 = await checkFileSystem(fileSystem.id, signal);
2113
+ if (!after2.ok) {
2114
+ await destroyByName(name, signal);
2115
+ await Promise.all(
2116
+ after2.unlabelled.map((u) => removeWithRetry(`/volumes/${enc(u)}`, signal))
2117
+ );
2118
+ throw gone();
2119
+ }
2120
+ await start(n.container, signal);
2121
+ await initRecords(n.container);
2122
+ } catch (e) {
2123
+ if (!signal.aborted) {
2124
+ await destroyByName(name, AbortSignal.timeout(6e4)).catch(() => void 0);
2125
+ }
2126
+ throw e;
2127
+ }
2128
+ return { id: name };
2129
+ },
2130
+ resume,
2131
+ // Called under the kernel's exclusive lease when the device's network changed
2132
+ async update(h, limits, signal) {
2133
+ signal.throwIfAborted();
2134
+ checkLimits(limits);
2135
+ const plan = planInstance(limits, cfg.refuseOpenNetwork);
2136
+ let c;
2137
+ try {
2138
+ c = await api.json("GET", `/containers/${enc(h.id)}/json`, { signal });
2139
+ } catch (e) {
2140
+ if (isStatus(e, 404)) return "recreate";
2141
+ throw e;
2142
+ }
2143
+ if (updateDecision(c.Config.Labels ?? {}, plan) === "recreate") return "recreate";
2144
+ const n = sandboxResourceNames(h.id);
2145
+ await api.json("DELETE", `/containers/${enc(n.egress)}`, { query: { force: true }, signal }).catch(ignore(404));
2146
+ await ensureSharedNetwork(signal);
2147
+ if (!await ensureInternalNetwork(h.id, signal)) return "recreate";
2148
+ try {
2149
+ await createEgress(h.id, proxyModeOf(plan), plan.allowHosts, signal);
2150
+ } catch (e) {
2151
+ await api.json("DELETE", `/containers/${enc(n.egress)}`, {
2152
+ query: { force: true },
2153
+ signal: AbortSignal.timeout(6e4)
2154
+ }).catch(() => void 0);
2155
+ throw e;
2156
+ }
2157
+ if (!c.State.Running) {
2158
+ await api.json("POST", `/containers/${enc(n.egress)}/stop`, { query: { t: STOP_SECONDS }, signal }).catch(ignore(304, 404));
2159
+ }
2160
+ return "updated";
2161
+ },
2162
+ async suspend(h, signal) {
2163
+ signal.throwIfAborted();
2164
+ const n = sandboxResourceNames(h.id);
2165
+ for (const c of [n.container, n.egress]) {
2166
+ await api.json("POST", `/containers/${enc(c)}/stop`, { query: { t: STOP_SECONDS }, signal }).catch(ignore(304, 404));
2167
+ }
2168
+ },
2169
+ async destroy(h, signal) {
2170
+ await destroyByName(h.id, signal);
2171
+ },
2172
+ destroyByName,
2173
+ async killAll(h, signal) {
2174
+ signal.throwIfAborted();
2175
+ await autoStart(
2176
+ h,
2177
+ signal,
2178
+ () => run(h.id, { cmd: ["true"], user: SANDBOX_USER, maxOutputBytes: 1024, signal })
2179
+ );
2180
+ await killOrRestart(h.id, ["/bin/sh", "-c", KILL_ALL_SCRIPT, "capybara-killall"], signal);
2181
+ },
2182
+ async killTagged(h, tags, signal) {
2183
+ signal.throwIfAborted();
2184
+ for (const t of tags) {
2185
+ if (!SANDBOX_TAG_RE.test(t)) throw new Error("invalid sandbox tag");
2186
+ }
2187
+ if (tags.length === 0) return;
2188
+ await autoStart(
2189
+ h,
2190
+ signal,
2191
+ () => run(h.id, { cmd: ["true"], user: SANDBOX_USER, maxOutputBytes: 1024, signal })
2192
+ );
2193
+ await killOrRestart(
2194
+ h.id,
2195
+ ["/bin/sh", "-c", KILL_TAGGED_SCRIPT, "capybara-killtagged", ...tags],
2196
+ signal
2197
+ );
2198
+ },
2199
+ // `args.actor` is informational in phase 1: not used for anything
2200
+ async exec(h, args) {
2201
+ args.signal.throwIfAborted();
2202
+ return execWith(h, args, execControlPath(args.tag));
2203
+ },
2204
+ async readFile(h, path, opts) {
2205
+ opts.signal.throwIfAborted();
2206
+ checkPath2(path);
2207
+ const want = opts.maxBytes + 1;
2208
+ const r = await fileOp(
2209
+ h,
2210
+ {
2211
+ cmd: ["/bin/sh", "-c", READ_SCRIPT, "capybara-read", path, String(want)],
2212
+ user: SANDBOX_USER,
2213
+ maxOutputBytes: want + STDERR_ROOM
2214
+ },
2215
+ opts.signal
2216
+ );
2217
+ if (r.exitCode === 3 || r.exitCode === 4) return null;
2218
+ if (r.exitCode !== 0) throw new Error(`cannot read ${path}: ${stderrOf(r)}`);
2219
+ const truncated = r.stdout.byteLength > opts.maxBytes;
2220
+ const data = truncated ? r.stdout.subarray(0, opts.maxBytes) : r.stdout;
2221
+ return { data: new Uint8Array(data), truncated };
2222
+ },
2223
+ async writeFile(h, path, data, signal) {
2224
+ signal.throwIfAborted();
2225
+ checkPath2(path);
2226
+ const skills = path === "/skills" || path.startsWith("/skills/");
2227
+ const r = await fileOp(
2228
+ h,
2229
+ {
2230
+ cmd: [
2231
+ "/bin/sh",
2232
+ "-c",
2233
+ WRITE_SCRIPT,
2234
+ "capybara-write",
2235
+ skills ? `/opt/capybara${path}` : path,
2236
+ String(data.byteLength)
2237
+ ],
2238
+ user: skills ? ROOT_USER : SANDBOX_USER,
2239
+ stdin: data,
2240
+ maxOutputBytes: STDERR_ROOM
2241
+ },
2242
+ signal
2243
+ );
2244
+ if (r.exitCode !== 0) throw new Error(`cannot write ${path}: ${stderrOf(r)}`);
2245
+ },
2246
+ async stat(h, path, signal) {
2247
+ signal.throwIfAborted();
2248
+ checkPath2(path);
2249
+ const r = await fileOp(
2250
+ h,
2251
+ {
2252
+ cmd: ["/bin/sh", "-c", STAT_SCRIPT, "capybara-stat", path],
2253
+ user: SANDBOX_USER,
2254
+ maxOutputBytes: STDERR_ROOM
2255
+ },
2256
+ signal
2257
+ );
2258
+ if (r.exitCode === 3) return null;
2259
+ const m = r.stdout.toString("utf8").match(/^(\d+) (.+)\n?$/);
2260
+ if (r.exitCode !== 0 || !m) throw new Error(`cannot stat ${path}: ${stderrOf(r)}`);
2261
+ return { size: Number(m[1]), isDir: m[2] === "directory" };
2262
+ },
2263
+ // the container's workspace is the whole area a cloud device offers (core spec 2026-11-14
2264
+ // §4.2): the instance is the sandbox, and the kernel scopes a cloud device's projects to it
2265
+ async list(h, path, opts) {
2266
+ opts.signal.throwIfAborted();
2267
+ const p = checkListPath(path);
2268
+ const r = await listOp(h, "list", p, listLimit(opts.limit), opts.signal);
2269
+ return finishList(p, r, NO_PYTHON);
2270
+ },
2271
+ async scan(h, base, opts) {
2272
+ opts.signal.throwIfAborted();
2273
+ const b = checkListPath(base);
2274
+ const r = await listOp(h, "scan", b, 0, opts.signal);
2275
+ return finishScan(b, r, NO_PYTHON);
2276
+ },
2277
+ // The operation contract (operations.ts): fresh immutable scopes per invocation.
2278
+ permissionSupport: operations.permissionSupport,
2279
+ operation: operations.operation,
2280
+ prepare: operations.prepare,
2281
+ browse: operations.browse,
2282
+ revokeOperation: operations.revokeOperation,
2283
+ background: operations.background
2284
+ };
2285
+ }
2286
+ var NO_PYTHON = "device-docker: the sandbox image has no python3 or no timeout (looked up in /usr/local/bin, /usr/bin, /bin), which list and scan need; use the published image or add them to your own";
2287
+ function decodeOutput(buf, truncated) {
2288
+ let end = buf.byteLength;
2289
+ if (truncated) {
2290
+ for (let i = end - 1; i >= 0 && i >= end - 4; i--) {
2291
+ const b = buf[i];
2292
+ if ((b & 192) === 128) continue;
2293
+ const need = b >= 240 ? 4 : b >= 224 ? 3 : b >= 192 ? 2 : 1;
2294
+ if (end - i < need) end = i;
2295
+ break;
2296
+ }
2297
+ }
2298
+ return buf.subarray(0, end).toString("utf8");
2299
+ }
2300
+ function checkLimits(l) {
2301
+ if (!(l.cpu > 0) || !(l.memoryMb > 0) || !(l.diskMb > 0)) {
2302
+ throw new Error("sandbox limits cpu, memoryMb and diskMb must be positive");
2303
+ }
2304
+ for (const host of networkOf(l).hosts) {
2305
+ const errors = validateAllowHost(host);
2306
+ if (errors.length > 0)
2307
+ throw new Error(`invalid network.hosts entry ${host}: ${errors.join("; ")}`);
2308
+ }
2309
+ }
2310
+ function parseSizeMb(size) {
2311
+ const m = /^(\d+(?:\.\d+)?)([kKmMgGtT]?)[bB]?$/.exec(size?.trim() ?? "");
2312
+ if (!m) return null;
2313
+ const n = Number(m[1]);
2314
+ const unit = (m[2] ?? "").toLowerCase();
2315
+ const mb = unit === "t" ? n * 1024 * 1024 : unit === "g" ? n * 1024 : unit === "m" ? n : unit === "k" ? n / 1024 : n / MIB;
2316
+ return mb > 0 ? Math.round(mb) : null;
2317
+ }
2318
+ function reportLimitLines(l) {
2319
+ const out = [];
2320
+ if (l.cpu !== null) {
2321
+ out.push({ label: { en: "CPU", zh: "CPU" }, value: `${Number(l.cpu.toFixed(2))}` });
2322
+ }
2323
+ if (l.memoryMb !== null) {
2324
+ out.push({ label: { en: "Memory", zh: "内存" }, value: `${l.memoryMb} MB` });
2325
+ }
2326
+ if (l.diskMb !== null) {
2327
+ out.push({ label: { en: "Disk", zh: "磁盘" }, value: `${l.diskMb} MB` });
2328
+ }
2329
+ return out;
2330
+ }
2331
+ function limitsRevision(l) {
2332
+ return [l.cpu, l.memoryMb, l.diskMb].map((v) => v === null ? "-" : String(v)).join("-");
2333
+ }
2334
+
2335
+ // src/index.ts
2336
+ var NETWORK_NAME = /^cap[a-zA-Z0-9_.-]*$/;
2337
+ var isCidr = (v) => z.cidrv4().safeParse(v).success || z.cidrv6().safeParse(v).success;
2338
+ var DeploymentConfig = z.object({
2339
+ /** Docker socket proxy address (docker/sandbox-proxy): `tcp://sandbox-proxy:2375` or `unix:///path`. */
2340
+ endpoint: ui(
2341
+ z.string().regex(/^(tcp:\/\/(\[[^\]]+\]|[^:/]+):\d{1,5}\/?|unix:\/\/\/.+)$/, {
2342
+ message: "endpoint must be tcp://host:port or unix:///path"
2343
+ }),
2344
+ { label: { zh: "Docker 代理地址", en: "Docker proxy endpoint" } }
2345
+ ),
2346
+ /** Container runtime: runc (default) or gVisor's runsc (registered in the Docker daemon). */
2347
+ runtime: ui(z.enum(["runc", "runsc"]).default("runc"), {
2348
+ label: { zh: "容器运行时", en: "Container runtime" }
2349
+ }),
2350
+ /**
2351
+ * The shared sandbox network: every egress proxy joins it for its outbound leg; created as a
2352
+ * bridge with container-to-container traffic disabled when it does not exist. It must start
2353
+ * with `cap` (the socket proxy only admits such network names).
2354
+ */
2355
+ network: ui(
2356
+ z.string().regex(NETWORK_NAME, {
2357
+ message: "network must start with 'cap' (the socket proxy only allows cap* networks)"
2358
+ }).default("capybara-sandbox"),
2359
+ { label: { zh: "沙箱网络", en: "Sandbox network" } }
2360
+ ),
2361
+ /**
2362
+ * Egress proxy image (plugins/device-docker/egress-proxy/Dockerfile). Unset: the image
2363
+ * published with this plugin's version, `ghcr.io/capybara-hq/capybara-sandbox-egress:<version>`.
2364
+ */
2365
+ egressProxyImage: ui(z.string().min(1).optional(), {
2366
+ label: { zh: "出站代理镜像", en: "Egress proxy image" },
2367
+ help: {
2368
+ zh: "留空则用随本插件版本发布的镜像 ghcr.io/capybara-hq/capybara-sandbox-egress:<插件版本>;离线部署填自己构建的镜像。",
2369
+ en: "Empty: the image published with this plugin's version, ghcr.io/capybara-hq/capybara-sandbox-egress:<plugin version>. Set it to your own build for an offline deployment."
2370
+ },
2371
+ placeholder: "ghcr.io/capybara-hq/capybara-sandbox-egress:<plugin version>"
2372
+ }),
2373
+ /** Driver of the workspace volume (only a driver with a `size` option limits disk); unset = local. */
2374
+ volumeDriver: ui(z.string().min(1).optional(), {
2375
+ label: { zh: "卷驱动", en: "Volume driver" }
2376
+ }),
2377
+ /**
2378
+ * The deployment's own addresses (its public or corporate ranges, IPv4 / IPv6 CIDRs) the
2379
+ * egress proxy refuses in every mode, on top of the private, loopback, link-local, CGNAT,
2380
+ * metadata and reserved ranges it always refuses (README "Network and egress").
2381
+ */
2382
+ deniedCidrs: ui(
2383
+ z.array(
2384
+ z.string().refine(isCidr, {
2385
+ message: "deniedCidrs entries must be IPv4 or IPv6 CIDRs such as 203.0.113.0/24 or 2001:db8::/32"
2386
+ })
2387
+ ).max(256).optional(),
2388
+ {
2389
+ label: { zh: "额外拒绝的地址段", en: "Extra denied address ranges" },
2390
+ help: {
2391
+ zh: "部署自身的公网或办公网地址段(CIDR,如 203.0.113.0/24);出站代理在所有模式下都拒绝连接这些地址,另外始终拒绝内网、本机、链路本地、CGNAT 与云元数据地址。",
2392
+ en: "The deployment's own public or corporate ranges (CIDRs such as 203.0.113.0/24); the egress proxy refuses them in every mode, on top of the private, loopback, link-local, CGNAT and cloud metadata addresses it always refuses."
2393
+ }
2394
+ }
2395
+ ),
2396
+ /**
2397
+ * Refuse the open public network (default `false`): locked-down deployments refuse every
2398
+ * `create` / `update` whose effective network is `open-public`, with an error naming this
2399
+ * setting, and an existing open-public instance answers `gone` on resume / auto-start (the
2400
+ * kernel recreates it under the rule). The org's cloud network then has to be the allowlist.
2401
+ */
2402
+ refuseOpenNetwork: ui(z.boolean().default(false), {
2403
+ label: { zh: "拒绝开放网络", en: "Refuse open network" },
2404
+ help: {
2405
+ zh: "开启后,有效网络为开放(任意公网主机、挡住内网与本机地址)的设备无法创建或更新,错误会指出本设置;适合只允许白名单的部署。",
2406
+ en: "When on, a device whose effective network is open-public (any public host, private and loopback addresses refused) cannot be created or updated; the error names this setting. For deployments that only allow the allowlist."
2407
+ }
2408
+ })
2409
+ }).strict();
2410
+ function providerConfig(c, version = plugin.version) {
2411
+ const images = publishedImages(version);
2412
+ return {
2413
+ ...c,
2414
+ egressProxyImage: c.egressProxyImage ?? images.egress,
2415
+ defaultImage: images.sandbox,
2416
+ version
2417
+ };
2418
+ }
2419
+ var plugin = defineExtension({
2420
+ name: "device-docker",
2421
+ version: "0.1.0-rc.21",
2422
+ // device-provider@1 (report, networkAllowlist, scopes with projectRoot / writeRoots) is the
2423
+ // rc.51 SDK's.
2424
+ sdk: "^0.1.0-rc.51",
2425
+ provides: [DEVICE_PROVIDER_EXTENSION_POINT],
2426
+ // Only the deployment config and the Docker endpoint: no platform capability to declare
2427
+ permissions: {},
2428
+ config: { deployment: DeploymentConfig },
2429
+ setup(ctx) {
2430
+ ctx.provide(
2431
+ DEVICE_PROVIDER_EXTENSION_POINT,
2432
+ createDockerSandbox(
2433
+ providerConfig(ctx.config),
2434
+ {},
2435
+ ctx.log
2436
+ )
2437
+ );
2438
+ }
2439
+ });
2440
+ var index_default = plugin;
2441
+ export {
2442
+ DeploymentConfig,
2443
+ IN_SANDBOX_GRACE_SECONDS,
2444
+ createDockerSandbox,
2445
+ decodeOutput,
2446
+ index_default as default,
2447
+ execArgv,
2448
+ providerConfig,
2449
+ publishedImages,
2450
+ sandboxResourceNames
2451
+ };