@cruxy/cli 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@ import { authMissingKey, shouldUseColor, usageError, } from "../../errors/index.
5
5
  import { createRenderer } from "../../render/index.js";
6
6
  import { themeForColor } from "../../theme/index.js";
7
7
  import { CheckpointService } from "../../checkpoint/index.js";
8
+ import { SandboxService } from "../../sandbox/index.js";
8
9
  import { runInteractive } from "../repl.js";
9
10
  import { buildAgentSession } from "../session-factory.js";
10
11
  import { apiKeyEnvVar, maybeRunOnboarding } from "../onboard.js";
@@ -13,6 +14,7 @@ export function runCommand() {
13
14
  .description("run cruxy on a prompt (one-shot), or with no prompt for an interactive session")
14
15
  .argument("[prompt...]", "the task for cruxy to perform (omit for interactive)")
15
16
  .option("--plan", "plan mode: propose a step-by-step plan for approval before executing")
17
+ .option("--sandbox", "run shell + test commands inside an isolated container (fails loud if no runtime)")
16
18
  .action(async (promptParts, opts) => {
17
19
  const prompt = promptParts.join(" ").trim();
18
20
  const t = themeForColor(shouldUseColor(process.stdout));
@@ -61,7 +63,23 @@ export function runCommand() {
61
63
  const checkpoints = config.checkpoint.enabled
62
64
  ? new CheckpointService({ root: process.cwd(), config })
63
65
  : undefined;
64
- const session = buildAgentSession(config, apiKey, process.cwd(), Boolean(process.stdin.isTTY), planMode, renderer, checkpoints);
66
+ // Sandbox (C.16): opt-in via --sandbox or sandbox.enabled. Resolving the
67
+ // service probes the runtime and THROWS CRUXY_E_SANDBOX_UNAVAILABLE if it
68
+ // is missing — fail loud here, before the agent starts, rather than
69
+ // silently running un-sandboxed. When off, ctx.sandbox stays undefined and
70
+ // execution runs on the host, unchanged.
71
+ const sandboxEnabled = opts.sandbox ?? config.sandbox.enabled;
72
+ const sandbox = sandboxEnabled
73
+ ? await SandboxService.create({
74
+ config,
75
+ cwd: process.cwd(),
76
+ reporter: renderer,
77
+ })
78
+ : undefined;
79
+ if (sandbox) {
80
+ logger.info(t.muted(`sandbox: ${sandbox.runtimeName} (network ${config.sandbox.network})`));
81
+ }
82
+ const session = buildAgentSession(config, apiKey, process.cwd(), Boolean(process.stdin.isTTY), planMode, renderer, checkpoints, sandbox);
65
83
  if (interactive) {
66
84
  await runInteractive(session, undefined, renderer, checkpoints);
67
85
  return;
@@ -1,6 +1,7 @@
1
1
  import type { CruxyConfig } from "../config/index.js";
2
2
  import type { ApprovalDecision } from "../approval/index.js";
3
3
  import type { CheckpointService } from "../checkpoint/index.js";
4
+ import type { SandboxService } from "../sandbox/index.js";
4
5
  import type { StreamRenderer } from "../render/index.js";
5
6
  import { type ApproveAction } from "../tools/index.js";
6
7
  import { Session } from "../agent/index.js";
@@ -23,4 +24,4 @@ export declare function withCheckpointGate(requestApproval: (action: ApproveActi
23
24
  * over the shared U.3 allowlist and a `planRunner` so `session.send` proposes →
24
25
  * approves → executes. Plan mode is fully opt-in; the default path is unchanged.
25
26
  */
26
- export declare function buildAgentSession(config: CruxyConfig, apiKey: string, cwd: string, ttyInteractive: boolean, planMode?: boolean, renderer?: StreamRenderer, checkpoints?: CheckpointService): Session;
27
+ export declare function buildAgentSession(config: CruxyConfig, apiKey: string, cwd: string, ttyInteractive: boolean, planMode?: boolean, renderer?: StreamRenderer, checkpoints?: CheckpointService, sandbox?: SandboxService): Session;
@@ -87,7 +87,7 @@ export function withCheckpointGate(requestApproval, checkpoints, cwd) {
87
87
  * over the shared U.3 allowlist and a `planRunner` so `session.send` proposes →
88
88
  * approves → executes. Plan mode is fully opt-in; the default path is unchanged.
89
89
  */
90
- export function buildAgentSession(config, apiKey, cwd, ttyInteractive, planMode = false, renderer, checkpoints) {
90
+ export function buildAgentSession(config, apiKey, cwd, ttyInteractive, planMode = false, renderer, checkpoints, sandbox) {
91
91
  const provider = createProvider({
92
92
  provider: config.model.provider,
93
93
  apiKey,
@@ -120,6 +120,7 @@ export function buildAgentSession(config, apiKey, cwd, ttyInteractive, planMode
120
120
  git,
121
121
  projectInstructions,
122
122
  renderer,
123
+ sandbox,
123
124
  makeChildApproval: () => gate(new ApprovalService({ cwd, interactive: ttyInteractive, io })),
124
125
  });
125
126
  if (config.subagent.maxDepth > 0) {
@@ -136,7 +137,13 @@ export function buildAgentSession(config, apiKey, cwd, ttyInteractive, planMode
136
137
  policy: planPolicy,
137
138
  io,
138
139
  });
139
- const ctx = { cwd, config, logger, requestApproval: gate(approval) };
140
+ const ctx = {
141
+ cwd,
142
+ config,
143
+ logger,
144
+ requestApproval: gate(approval),
145
+ sandbox,
146
+ };
140
147
  const planRunner = ({ messages, projectInstructions, renderer: turnRenderer, }) => runPlanSession({
141
148
  provider,
142
149
  config,
@@ -166,7 +173,7 @@ export function buildAgentSession(config, apiKey, cwd, ttyInteractive, planMode
166
173
  interactive: ttyInteractive,
167
174
  io,
168
175
  });
169
- const ctx = { cwd, config, logger, requestApproval: gate(approval) };
176
+ const ctx = { cwd, config, logger, requestApproval: gate(approval), sandbox };
170
177
  return new Session({
171
178
  provider,
172
179
  registry: execRegistry,
@@ -283,6 +283,62 @@ export declare const SubagentConfigSchema: z.ZodObject<{
283
283
  timeoutMs?: number | undefined;
284
284
  } | undefined;
285
285
  }>;
286
+ /**
287
+ * Sandbox / container execution (C.16): defense-in-depth beneath the U.3 gate.
288
+ * When enabled, `run_command` and `run_tests` execute inside an isolated,
289
+ * network-denied, resource-capped, non-root container with only the project
290
+ * workdir mounted — never on the host directly. OFF by default (a container
291
+ * runtime isn't universal); turning it on is a hard promise, so if the runtime
292
+ * is missing execution FAILS LOUD rather than silently falling back to the host.
293
+ */
294
+ export declare const SandboxConfigSchema: z.ZodObject<{
295
+ /** Master switch. When true, shell + test commands run in the sandbox. */
296
+ enabled: z.ZodDefault<z.ZodBoolean>;
297
+ /**
298
+ * Base image the container runs. Must ship a POSIX `sh`. Pin by digest
299
+ * (`name@sha256:…`) where possible; cruxy never builds or substitutes one.
300
+ */
301
+ image: z.ZodDefault<z.ZodString>;
302
+ /**
303
+ * Egress policy. `none` denies all network (default deny); `host-loopback`
304
+ * permits reaching services on the host; `full` allows outbound. Anything
305
+ * other than `none` is a deliberate widening the user must opt into.
306
+ */
307
+ network: z.ZodDefault<z.ZodEnum<["none", "host-loopback", "full"]>>;
308
+ /** Memory cap (docker `--memory` syntax, e.g. `512m`, `2g`). */
309
+ memory: z.ZodDefault<z.ZodString>;
310
+ /** Process/thread cap (`--pids-limit`) — a fork-bomb guard. */
311
+ pids: z.ZodDefault<z.ZodNumber>;
312
+ /** CPU cap (docker `--cpus`, fractional allowed). */
313
+ cpus: z.ZodDefault<z.ZodNumber>;
314
+ /** Wall-clock timeout in ms; falls back to `shell.timeoutMs` when unset. */
315
+ timeout: z.ZodOptional<z.ZodNumber>;
316
+ /**
317
+ * Extra bind mounts beyond the workdir + tmp, each `src:dst[:ro|:rw]`.
318
+ * Explicit by construction — the default exposes ONLY the workdir. The
319
+ * docker socket and the cruxy home are rejected here (see policy.ts).
320
+ */
321
+ mounts: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
322
+ }, "strict", z.ZodTypeAny, {
323
+ image: string;
324
+ enabled: boolean;
325
+ memory: string;
326
+ network: "none" | "host-loopback" | "full";
327
+ pids: number;
328
+ cpus: number;
329
+ mounts: string[];
330
+ timeout?: number | undefined;
331
+ }, {
332
+ image?: string | undefined;
333
+ enabled?: boolean | undefined;
334
+ memory?: string | undefined;
335
+ network?: "none" | "host-loopback" | "full" | undefined;
336
+ pids?: number | undefined;
337
+ cpus?: number | undefined;
338
+ timeout?: number | undefined;
339
+ mounts?: string[] | undefined;
340
+ }>;
341
+ export type SandboxConfig = z.infer<typeof SandboxConfigSchema>;
286
342
  /** MCP server entry — stdio or URL transport (wired up in a later phase). */
287
343
  export declare const McpServerSchema: z.ZodObject<{
288
344
  command: z.ZodOptional<z.ZodString>;
@@ -551,6 +607,53 @@ export declare const CruxyConfigSchema: z.ZodObject<{
551
607
  command?: string | undefined;
552
608
  captureBytes?: number | undefined;
553
609
  }>>;
610
+ sandbox: z.ZodDefault<z.ZodObject<{
611
+ /** Master switch. When true, shell + test commands run in the sandbox. */
612
+ enabled: z.ZodDefault<z.ZodBoolean>;
613
+ /**
614
+ * Base image the container runs. Must ship a POSIX `sh`. Pin by digest
615
+ * (`name@sha256:…`) where possible; cruxy never builds or substitutes one.
616
+ */
617
+ image: z.ZodDefault<z.ZodString>;
618
+ /**
619
+ * Egress policy. `none` denies all network (default deny); `host-loopback`
620
+ * permits reaching services on the host; `full` allows outbound. Anything
621
+ * other than `none` is a deliberate widening the user must opt into.
622
+ */
623
+ network: z.ZodDefault<z.ZodEnum<["none", "host-loopback", "full"]>>;
624
+ /** Memory cap (docker `--memory` syntax, e.g. `512m`, `2g`). */
625
+ memory: z.ZodDefault<z.ZodString>;
626
+ /** Process/thread cap (`--pids-limit`) — a fork-bomb guard. */
627
+ pids: z.ZodDefault<z.ZodNumber>;
628
+ /** CPU cap (docker `--cpus`, fractional allowed). */
629
+ cpus: z.ZodDefault<z.ZodNumber>;
630
+ /** Wall-clock timeout in ms; falls back to `shell.timeoutMs` when unset. */
631
+ timeout: z.ZodOptional<z.ZodNumber>;
632
+ /**
633
+ * Extra bind mounts beyond the workdir + tmp, each `src:dst[:ro|:rw]`.
634
+ * Explicit by construction — the default exposes ONLY the workdir. The
635
+ * docker socket and the cruxy home are rejected here (see policy.ts).
636
+ */
637
+ mounts: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
638
+ }, "strict", z.ZodTypeAny, {
639
+ image: string;
640
+ enabled: boolean;
641
+ memory: string;
642
+ network: "none" | "host-loopback" | "full";
643
+ pids: number;
644
+ cpus: number;
645
+ mounts: string[];
646
+ timeout?: number | undefined;
647
+ }, {
648
+ image?: string | undefined;
649
+ enabled?: boolean | undefined;
650
+ memory?: string | undefined;
651
+ network?: "none" | "host-loopback" | "full" | undefined;
652
+ pids?: number | undefined;
653
+ cpus?: number | undefined;
654
+ timeout?: number | undefined;
655
+ mounts?: string[] | undefined;
656
+ }>>;
554
657
  mcpServers: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
555
658
  command: z.ZodOptional<z.ZodString>;
556
659
  args: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -634,6 +737,16 @@ export declare const CruxyConfigSchema: z.ZodObject<{
634
737
  captureBytes: number;
635
738
  command?: string | undefined;
636
739
  };
740
+ sandbox: {
741
+ image: string;
742
+ enabled: boolean;
743
+ memory: string;
744
+ network: "none" | "host-loopback" | "full";
745
+ pids: number;
746
+ cpus: number;
747
+ mounts: string[];
748
+ timeout?: number | undefined;
749
+ };
637
750
  mcpServers: Record<string, {
638
751
  command?: string | undefined;
639
752
  args?: string[] | undefined;
@@ -709,6 +822,16 @@ export declare const CruxyConfigSchema: z.ZodObject<{
709
822
  command?: string | undefined;
710
823
  captureBytes?: number | undefined;
711
824
  } | undefined;
825
+ sandbox?: {
826
+ image?: string | undefined;
827
+ enabled?: boolean | undefined;
828
+ memory?: string | undefined;
829
+ network?: "none" | "host-loopback" | "full" | undefined;
830
+ pids?: number | undefined;
831
+ cpus?: number | undefined;
832
+ timeout?: number | undefined;
833
+ mounts?: string[] | undefined;
834
+ } | undefined;
712
835
  mcpServers?: Record<string, {
713
836
  command?: string | undefined;
714
837
  args?: string[] | undefined;
@@ -194,6 +194,45 @@ export const SubagentConfigSchema = z
194
194
  .default({}),
195
195
  })
196
196
  .strict();
197
+ /**
198
+ * Sandbox / container execution (C.16): defense-in-depth beneath the U.3 gate.
199
+ * When enabled, `run_command` and `run_tests` execute inside an isolated,
200
+ * network-denied, resource-capped, non-root container with only the project
201
+ * workdir mounted — never on the host directly. OFF by default (a container
202
+ * runtime isn't universal); turning it on is a hard promise, so if the runtime
203
+ * is missing execution FAILS LOUD rather than silently falling back to the host.
204
+ */
205
+ export const SandboxConfigSchema = z
206
+ .object({
207
+ /** Master switch. When true, shell + test commands run in the sandbox. */
208
+ enabled: z.boolean().default(false),
209
+ /**
210
+ * Base image the container runs. Must ship a POSIX `sh`. Pin by digest
211
+ * (`name@sha256:…`) where possible; cruxy never builds or substitutes one.
212
+ */
213
+ image: z.string().min(1).default("node:20-bookworm-slim"),
214
+ /**
215
+ * Egress policy. `none` denies all network (default deny); `host-loopback`
216
+ * permits reaching services on the host; `full` allows outbound. Anything
217
+ * other than `none` is a deliberate widening the user must opt into.
218
+ */
219
+ network: z.enum(["none", "host-loopback", "full"]).default("none"),
220
+ /** Memory cap (docker `--memory` syntax, e.g. `512m`, `2g`). */
221
+ memory: z.string().min(1).default("512m"),
222
+ /** Process/thread cap (`--pids-limit`) — a fork-bomb guard. */
223
+ pids: z.number().int().positive().default(512),
224
+ /** CPU cap (docker `--cpus`, fractional allowed). */
225
+ cpus: z.number().positive().default(1),
226
+ /** Wall-clock timeout in ms; falls back to `shell.timeoutMs` when unset. */
227
+ timeout: z.number().int().positive().optional(),
228
+ /**
229
+ * Extra bind mounts beyond the workdir + tmp, each `src:dst[:ro|:rw]`.
230
+ * Explicit by construction — the default exposes ONLY the workdir. The
231
+ * docker socket and the cruxy home are rejected here (see policy.ts).
232
+ */
233
+ mounts: z.array(z.string().min(1)).default([]),
234
+ })
235
+ .strict();
197
236
  /** MCP server entry — stdio or URL transport (wired up in a later phase). */
198
237
  export const McpServerSchema = z
199
238
  .object({
@@ -216,6 +255,7 @@ export const CruxyConfigSchema = z
216
255
  checkpoint: CheckpointConfigSchema.default({}),
217
256
  subagent: SubagentConfigSchema.default({}),
218
257
  test: TestConfigSchema.default({}),
258
+ sandbox: SandboxConfigSchema.default({}),
219
259
  mcpServers: z.record(z.string(), McpServerSchema).default({}),
220
260
  logLevel: z.enum(LOG_LEVELS).default("info"),
221
261
  })
@@ -25,6 +25,27 @@ export declare function permissionDenied(path: string, underlying?: unknown): Cr
25
25
  export declare function indexEmbedderUnavailable(underlying?: unknown): CruxyError;
26
26
  export declare function indexStoreUnavailable(underlying?: unknown): CruxyError;
27
27
  export declare function indexFailed(underlying?: unknown): CruxyError;
28
+ /**
29
+ * Sandboxing was requested (`--sandbox` / `sandbox.enabled`) but no container
30
+ * runtime is available — docker isn't installed, or its daemon isn't running.
31
+ * THE CRITICAL RULE: this is fatal. A user who turned on the sandbox must never
32
+ * be silently dropped back onto un-sandboxed host execution, so we fail loud
33
+ * here rather than run the command anyway.
34
+ */
35
+ export declare function sandboxUnavailable(runtime?: string, underlying?: unknown): CruxyError;
36
+ /**
37
+ * The pinned sandbox base image could not be made available (the first-run
38
+ * pull failed, or the image does not exist). Fatal — without the image there
39
+ * is nothing to execute inside, and we never substitute another image.
40
+ */
41
+ export declare function sandboxImage(image: string, underlying?: unknown): CruxyError;
42
+ /**
43
+ * The container itself failed to start or run (a docker-level failure — bad
44
+ * flags, daemon error, `docker run` exit 125), as opposed to the command
45
+ * inside exiting non-zero (which is an ordinary result). Fatal: a sandbox that
46
+ * can't launch is never papered over with a host run.
47
+ */
48
+ export declare function sandboxExec(underlying?: unknown): CruxyError;
28
49
  /**
29
50
  * A side-effecting action needs approval but cruxy can't ask (non-interactive,
30
51
  * no policy). Default-deny — never auto-approve. A distinct exit code (10) so CI
@@ -224,6 +224,64 @@ export function indexFailed(underlying) {
224
224
  underlying,
225
225
  });
226
226
  }
227
+ // ── sandbox (exit 12) ─────────────────────────────────────────────────────────
228
+ /**
229
+ * Sandboxing was requested (`--sandbox` / `sandbox.enabled`) but no container
230
+ * runtime is available — docker isn't installed, or its daemon isn't running.
231
+ * THE CRITICAL RULE: this is fatal. A user who turned on the sandbox must never
232
+ * be silently dropped back onto un-sandboxed host execution, so we fail loud
233
+ * here rather than run the command anyway.
234
+ */
235
+ export function sandboxUnavailable(runtime = "docker", underlying) {
236
+ return new CruxyError({
237
+ code: ErrorCode.SandboxUnavailable,
238
+ title: `sandbox is enabled but the ${runtime} runtime is unavailable`,
239
+ cause: messageOf(underlying) ??
240
+ `${runtime} is not installed or its daemon is not reachable`,
241
+ nextSteps: [
242
+ `install ${runtime} and make sure its daemon is running`,
243
+ "or disable the sandbox: `cruxy config set sandbox.enabled false` (or drop --sandbox)",
244
+ ],
245
+ underlying,
246
+ meta: { runtime },
247
+ });
248
+ }
249
+ /**
250
+ * The pinned sandbox base image could not be made available (the first-run
251
+ * pull failed, or the image does not exist). Fatal — without the image there
252
+ * is nothing to execute inside, and we never substitute another image.
253
+ */
254
+ export function sandboxImage(image, underlying) {
255
+ return new CruxyError({
256
+ code: ErrorCode.SandboxImage,
257
+ title: `could not pull the sandbox image "${image}"`,
258
+ cause: messageOf(underlying),
259
+ nextSteps: [
260
+ "check the image name/tag and your network access to the registry",
261
+ 'set a reachable image, e.g. `cruxy config set sandbox.image "node:20-bookworm-slim"`',
262
+ ],
263
+ underlying,
264
+ meta: { image },
265
+ });
266
+ }
267
+ /**
268
+ * The container itself failed to start or run (a docker-level failure — bad
269
+ * flags, daemon error, `docker run` exit 125), as opposed to the command
270
+ * inside exiting non-zero (which is an ordinary result). Fatal: a sandbox that
271
+ * can't launch is never papered over with a host run.
272
+ */
273
+ export function sandboxExec(underlying) {
274
+ return new CruxyError({
275
+ code: ErrorCode.SandboxExec,
276
+ title: "the sandbox container failed to start",
277
+ cause: messageOf(underlying),
278
+ nextSteps: [
279
+ "re-run with --verbose for the underlying docker error",
280
+ "verify the docker daemon is healthy (`docker info`)",
281
+ ],
282
+ underlying,
283
+ });
284
+ }
227
285
  // ── approval (exit 10) ────────────────────────────────────────────────────────
228
286
  /**
229
287
  * A side-effecting action needs approval but cruxy can't ask (non-interactive,
@@ -52,6 +52,11 @@ export declare const ErrorCode: {
52
52
  readonly TestCommandNotFound: "CRUXY_E_TEST_COMMAND_NOT_FOUND";
53
53
  /** Carried inside a run_tests result (informational) — never fatal by itself. */
54
54
  readonly TestIterationLimit: "CRUXY_E_TEST_ITERATION_LIMIT";
55
+ /** Sandbox was enabled but no container runtime is available — fail loud,
56
+ * NEVER fall back to un-sandboxed host execution. */
57
+ readonly SandboxUnavailable: "CRUXY_E_SANDBOX_UNAVAILABLE";
58
+ readonly SandboxImage: "CRUXY_E_SANDBOX_IMAGE";
59
+ readonly SandboxExec: "CRUXY_E_SANDBOX_EXEC";
55
60
  };
56
61
  export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
57
62
  /** The process exit code for an error code (defaults to 1 for safety). */
@@ -64,6 +64,12 @@ export const ErrorCode = {
64
64
  TestCommandNotFound: "CRUXY_E_TEST_COMMAND_NOT_FOUND",
65
65
  /** Carried inside a run_tests result (informational) — never fatal by itself. */
66
66
  TestIterationLimit: "CRUXY_E_TEST_ITERATION_LIMIT",
67
+ // sandbox (exit 12)
68
+ /** Sandbox was enabled but no container runtime is available — fail loud,
69
+ * NEVER fall back to un-sandboxed host execution. */
70
+ SandboxUnavailable: "CRUXY_E_SANDBOX_UNAVAILABLE",
71
+ SandboxImage: "CRUXY_E_SANDBOX_IMAGE",
72
+ SandboxExec: "CRUXY_E_SANDBOX_EXEC",
67
73
  };
68
74
  /**
69
75
  * Category exit codes. Distinct per category so a caller (CI, a script) can
@@ -112,6 +118,11 @@ const EXIT_CODES = {
112
118
  // surfaces inside a run_tests result and is never fatal by itself.
113
119
  [ErrorCode.TestCommandNotFound]: 2,
114
120
  [ErrorCode.TestIterationLimit]: 11,
121
+ // A requested sandbox that can't be honored is fatal (fail loud, no host
122
+ // fallback) — its own exit code so CI/scripts can tell it apart.
123
+ [ErrorCode.SandboxUnavailable]: 12,
124
+ [ErrorCode.SandboxImage]: 12,
125
+ [ErrorCode.SandboxExec]: 12,
115
126
  };
116
127
  /** The process exit code for an error code (defaults to 1 for safety). */
117
128
  export function exitCodeFor(code) {
@@ -0,0 +1,22 @@
1
+ import type { SandboxCapability } from "./types.js";
2
+ /**
3
+ * Runtime detection (C.16): a container runtime is a *capability*, not an
4
+ * assumption. Presence means both that the binary exists AND its daemon
5
+ * answers — `docker` installed with a dead daemon is NOT available, and the
6
+ * caller must fail loud rather than pretend a box exists.
7
+ */
8
+ /** Injectable probe seam — spawns a short command and reports how it exited. */
9
+ export type RuntimeProbe = (bin: string, args: string[]) => Promise<{
10
+ code: number | null;
11
+ stdout: string;
12
+ stderr: string;
13
+ }>;
14
+ /**
15
+ * Detect the Docker runtime. `docker version --format {{.Server.Version}}`
16
+ * exits non-zero when the daemon is unreachable (even though the client is
17
+ * installed), so a zero exit with a server version is the honest "available"
18
+ * signal. Memoized for the process; pass a probe (tests) to bypass the cache.
19
+ */
20
+ export declare function detectDocker(probe?: RuntimeProbe): Promise<SandboxCapability>;
21
+ /** Clear the memoized capability (tests). */
22
+ export declare function resetDetectionCache(): void;
@@ -0,0 +1,67 @@
1
+ import { spawn } from "node:child_process";
2
+ /** Default probe: spawn the binary, capture output, treat a spawn error (e.g.
3
+ * ENOENT — binary missing) as a non-zero exit rather than a throw. */
4
+ const spawnProbe = (bin, args) => new Promise((resolve) => {
5
+ let child;
6
+ try {
7
+ child = spawn(bin, args);
8
+ }
9
+ catch (err) {
10
+ resolve({ code: null, stdout: "", stderr: err.message });
11
+ return;
12
+ }
13
+ let out = "";
14
+ let errText = "";
15
+ let settled = false;
16
+ const done = (code, stderr = errText) => {
17
+ if (settled)
18
+ return;
19
+ settled = true;
20
+ resolve({ code, stdout: out, stderr });
21
+ };
22
+ // The daemon can hang; a probe must never wedge startup.
23
+ const timer = setTimeout(() => {
24
+ child.kill("SIGKILL");
25
+ done(null, "timed out probing the runtime");
26
+ }, PROBE_TIMEOUT_MS);
27
+ timer.unref?.();
28
+ child.stdout?.on("data", (b) => (out += b.toString("utf8")));
29
+ child.stderr?.on("data", (b) => (errText += b.toString("utf8")));
30
+ child.on("error", (err) => done(null, err.message));
31
+ child.on("close", (code) => {
32
+ clearTimeout(timer);
33
+ done(code);
34
+ });
35
+ });
36
+ const PROBE_TIMEOUT_MS = 5000;
37
+ let cached;
38
+ /**
39
+ * Detect the Docker runtime. `docker version --format {{.Server.Version}}`
40
+ * exits non-zero when the daemon is unreachable (even though the client is
41
+ * installed), so a zero exit with a server version is the honest "available"
42
+ * signal. Memoized for the process; pass a probe (tests) to bypass the cache.
43
+ */
44
+ export function detectDocker(probe) {
45
+ if (probe)
46
+ return probeDocker(probe);
47
+ cached ??= probeDocker(spawnProbe);
48
+ return cached;
49
+ }
50
+ /** Clear the memoized capability (tests). */
51
+ export function resetDetectionCache() {
52
+ cached = undefined;
53
+ }
54
+ async function probeDocker(probe) {
55
+ const { code, stdout, stderr } = await probe("docker", [
56
+ "version",
57
+ "--format",
58
+ "{{.Server.Version}}",
59
+ ]);
60
+ if (code === 0 && stdout.trim().length > 0) {
61
+ return { available: true, runtime: "docker" };
62
+ }
63
+ const detail = code === null
64
+ ? "the docker binary is not installed or not on PATH"
65
+ : (stderr.trim().split("\n")[0] ?? "docker daemon is not reachable");
66
+ return { available: false, runtime: "docker", detail };
67
+ }
@@ -0,0 +1,32 @@
1
+ import type { ExecOptions, ExecResult, IsolationPolicy, SandboxRuntime } from "./types.js";
2
+ /**
3
+ * The shipped {@link SandboxRuntime}: shells out to the `docker` CLI (no SDK —
4
+ * matches the no-vendor-client ethos). {@link buildRunArgs} is a pure function
5
+ * so the entire isolation posture can be asserted from the argv without a live
6
+ * daemon; `exec` spawns docker, captures bias-capped output, enforces the
7
+ * wall-clock timeout by force-killing the container, and maps the result.
8
+ *
9
+ * The exit code from `docker run` is the command's own — EXCEPT `125`, which
10
+ * docker reserves for "the run itself failed" (bad flags, daemon error): that,
11
+ * and a spawn failure, are the only container-start failures, surfaced as a
12
+ * coded {@link sandboxExec} error. An ordinary non-zero command exit is a
13
+ * normal result (exit code is truth), never a thrown error and never a host run.
14
+ */
15
+ export declare class DockerRuntime implements SandboxRuntime {
16
+ private readonly bin;
17
+ readonly name = "docker";
18
+ constructor(bin?: string);
19
+ ensureImage(image: string, onPull?: () => void): Promise<void>;
20
+ /** Run a non-container docker subcommand to completion, capturing output. */
21
+ private simpleRun;
22
+ exec(command: string, policy: IsolationPolicy, opts: ExecOptions): Promise<ExecResult>;
23
+ private run;
24
+ /** Best-effort container teardown after a timeout kill. */
25
+ private forceRemove;
26
+ }
27
+ /**
28
+ * Build the `docker run` argv from a resolved policy. Pure and total — the
29
+ * single source of truth for the isolation boundary, asserted directly in
30
+ * tests. Order is stable for readability; docker is order-insensitive for flags.
31
+ */
32
+ export declare function buildRunArgs(policy: IsolationPolicy, container: string, command: string): string[];