Public: anyone can read this; the crew can change it.

FORGE_CREW_SANDBOX=require holds crew runs while the agent sandbox is unavailable #16233

Closed opened this
Closed without merging

sold/sandbox-require → main 2 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +170 −9
docs/APPS.md +1
@@ -1864,6 +1864,7 @@ a link to the milestone (`docs/PLANNING.md`); its progress never does.
18641864 | `FORGE_CREW_CPUS` | `4` | cores one crew run may use (`cpu.max` on its own cell cgroup, where the cpu controller is delegated) |
18651865 | `FORGE_CREW_BUDGET_USD` | `5` | spend per run unless the agent says otherwise |
18661866 | `FORGE_CREW_TIMEOUT_MIN` | `45` | wall-clock limit of one agent run |
1867 | `FORGE_CREW_SANDBOX` | `off` | `require` keeps crew runs queued (held, with the reason in the run's log) while the host cannot run the shell sandbox; `off` runs them unrestricted on purpose |
18671868 | `FORGE_CREW_ALLOW_HOSTS` | — | hosts an agent's shell may reach, comma-separated |
18681869 | `FORGE_CLAUDE` | `claude` on `PATH` | the Claude Code binary |
18691870 | `FORGE_CLAUDE_CONFIG_DIR` | conversations: `$FORGE_APP_DATA/claude-config`; runs: Claude Code's own | a `CLAUDE_CONFIG_DIR`; conversation sessions live there so a release keeps them |
src/crew/dispatch.ts +17 −2
@@ -109,6 +109,7 @@ import {
109109 } from "./guard.ts";
110110 import { noteProtection } from "../kernel/protection.ts";
111111 import { dataInTemp, sandboxAvailable, sweepRunTmp } from "./sandbox.ts";
112 import { SANDBOX_ENV, sandboxHoldSentence } from "./sandbox_policy.ts";
112113 import { sandboxCause } from "./sandbox_cause.ts";
113114 import { mayDirectCrew } from "./direct.ts";
114115 import {
@@ -238,7 +239,7 @@ export async function startCrew(
238239 // The default the Capacity page shows and goes back to (`core/capacity.ts`).
239240 noteBooted(app.db, "crew.concurrency", String(options.concurrency));
240241 const sandbox = await sandboxAvailable();
241 noteProtection(app, "crew shells", sandbox);
242 noteProtection(app, "crew shells", sandbox, options.sandboxRequired === true ? `its runs are refused (${SANDBOX_ENV}=require)` : undefined);
242243 // Temp directories of runs a stopped forge never finished: old enough
243244 // that no forge beside this one (a rollout) can still be using them.
244245 try {
@@ -254,7 +255,12 @@ export async function startCrew(
254255 "the data directory is inside the temp directory: agents' shells are denied only the forge's own pieces of it, not all of it",
255256 { dataDir: app.config.dataDir, tmpdir: tmpdir() },
256257 );
257 if (!sandbox.ok)
258 if (!sandbox.ok && options.sandboxRequired === true)
259 log.warn("agent sandbox not available here; crew runs are refused", {
260 cause: sandboxCause(sandbox.reason).words,
261 reason: sandbox.reason,
262 });
263 else if (!sandbox.ok)
258264 log.warn("agent sandbox not available here; runs are unrestricted", {
259265 cause: sandboxCause(sandbox.reason).words,
260266 reason: sandbox.reason,
@@ -1738,6 +1744,15 @@ export function pump(
17381744 }
17391745 const fresh = getRun(app.db, queued.id);
17401746 if (!fresh || fresh.state !== "queued") continue;
1747 // No sandbox and the forge asked for one: agent-written shell does not run unrestricted (`sandbox_policy.ts`).
1748 if (options.sandboxRequired === true && options.sandboxEnforced === false) {
1749 held.set(fresh.id, "sandbox");
1750 if (!noted.has(fresh.id)) {
1751 noted.add(fresh.id);
1752 appendRunLog(app.config.dataDir, fresh.id, `queued, not started: ${sandboxHoldSentence(options.sandboxNote ?? "")}`);
1753 }
1754 continue;
1755 }
17411756 // A fresh run queued before Archive is cancelled, not started, and
17421757 // stays cancelled through Wake. One carrying on after a pause or a
17431758 // restart (attempt > 0) is already going, and finishes.
src/crew/runner.ts +2
@@ -260,6 +260,8 @@ export interface CrewOptions {
260260 readonly sandboxEnforced?: boolean | undefined;
261261 /** Why it cannot, when it cannot — said once in every run's log. */
262262 readonly sandboxNote?: string | undefined;
263 /** Refuse crew runs while the sandbox is unavailable (`sandbox_policy.ts`). */
264 readonly sandboxRequired?: boolean | undefined;
263265 /** Milliseconds between the crew's ticks; tests pass a small one. @default 5000 */
264266 readonly tickMs?: number | undefined;
265267 /**
src/crew/sandbox_policy.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * Whether a forge whose host cannot hold an agent's shell to the sandbox
3 * still runs the crew.
4 *
5 * `FORGE_CREW_SANDBOX` says it: `require` refuses crew runs while the sandbox
6 * is unavailable (they stay queued, held as "sandbox", with the sentence below
7 * in the run's log); `off` runs them unrestricted on purpose (a developer's
8 * machine, a container that is already the sandbox) and the boot warning stays.
9 * Unset follows `DEFAULT_MODE`: `off` until every forge that legitimately runs
10 * without bubblewrap sets it, then `require` — the one line to change.
11 */
12
13 import { sandboxCause } from "./sandbox_cause.ts";
14
15 export const SANDBOX_ENV = "FORGE_CREW_SANDBOX";
16
17 export type SandboxMode = "require" | "off";
18
19 /** What an unset `FORGE_CREW_SANDBOX` means. */
20 export const DEFAULT_MODE: SandboxMode = "off";
21
22 /** The mode `env` asks for; anything unrecognised is the default. */
23 export function sandboxMode(env: Record<string, string | undefined>): SandboxMode {
24 const value = (env[SANDBOX_ENV] ?? "").trim().toLowerCase();
25 return value === "require" || value === "off" ? value : DEFAULT_MODE;
26 }
27
28 /** Why a run waits, naming the cause the probe reported and what to do. */
29 export function sandboxHoldSentence(reason: string): string {
30 return `this forge requires the agent sandbox and it is unavailable here (${sandboxCause(reason).words}); make the host able to run bubblewrap and socat, or set ${SANDBOX_ENV}=off to run the crew unrestricted on purpose.`;
31 }
src/kernel/protection.ts +10 −6
@@ -12,7 +12,9 @@
1212 * run one file's note was another file's footer.
1313 */
1414
15 const lacking = new WeakMap<object, Map<string, string>>();
15 const UNCONTAINED = "uncontained";
16
17 const lacking = new WeakMap<object, Map<string, { reason: string; outcome: string }>>();
1618
1719 /**
1820 * A part says what it lacks (`ok`: nothing) and why,
@@ -22,19 +24,21 @@ export function noteProtection(
2224 app: object,
2325 part: string,
2426 result: { ok: true } | { ok: false; reason: string },
27 outcome = UNCONTAINED,
2528 ): void {
2629 let notes = lacking.get(app);
2730 if (notes === undefined) lacking.set(app, (notes = new Map()));
2831 if (result.ok) notes.delete(part);
29 else notes.set(part, result.reason);
32 else notes.set(part, { reason: result.reason, outcome });
3033 }
3134
3235 /** The one-line notice, or `undefined` when nothing is reduced. Plain text: escape it. */
3336 export function protectionNotice(app: object): string | undefined {
3437 const notes = lacking.get(app);
3538 if (notes === undefined || notes.size === 0) return undefined;
36 const parts = [...notes]
37 .sort(([a], [b]) => a.localeCompare(b))
38 .map(([part, reason]) => `${part} (${reason})`);
39 return `Reduced protection: ${parts.join("; ")} run${parts.length === 1 ? "s" : ""} uncontained.`;
39 const sorted = [...notes].sort(([a], [b]) => a.localeCompare(b));
40 const open = sorted.filter(([, n]) => n.outcome === UNCONTAINED).map(([part, n]) => `${part} (${n.reason})`);
41 const stopped = sorted.filter(([, n]) => n.outcome !== UNCONTAINED).map(([part, n]) => `${part} (${n.reason}) ${n.outcome}`);
42 const said = [...(open.length === 0 ? [] : [`${open.join("; ")} run${open.length === 1 ? "s" : ""} uncontained`]), ...stopped];
43 return `Reduced protection: ${said.join("; ")}.`;
4044 }
src/main.ts +2
@@ -89,6 +89,7 @@ import { takePresence, warmBehind } from "./apps/presence.ts";
8989 import { STALE_AFTER_MS } from "./runs/lease.ts";
9090 import { runnerSettings, startCrew, sweepAssigned } from "./crew/dispatch.ts";
9191 import { configureConversation, resumeInterrupted } from "./crew/conversation.ts";
92 import { sandboxMode } from "./crew/sandbox_policy.ts";
9293 import { CREW_OFF_IN_PREVIEW, crewOffInPreview } from "./crew/preview.ts";
9394 import { typeSafeDecider } from "./crew/decide.ts";
9495 import { graphInstagram } from "./crew/instagram.ts";
@@ -735,6 +736,7 @@ const crew = appsOn && !crewHeldOff
735736 concurrency: positive(process.env.FORGE_CREW_CONCURRENCY, hosted ? 1 : Number(capacityDefault("crew.concurrency"))),
736737 budgetUsd: Number(process.env.FORGE_CREW_BUDGET_USD) || 5,
737738 runTimeoutMs: crewRunMs,
739 sandboxRequired: sandboxMode(process.env) === "require",
738740 allowHosts: (process.env.FORGE_CREW_ALLOW_HOSTS ?? "")
739741 .split(",")
740742 .map((h) => h.trim())
src/runs/held.ts +2 −1
@@ -21,7 +21,7 @@ import type { Database } from "bun:sqlite";
2121 export const HELD_FRESH_MS = 2 * 60_000;
2222
2323 /** Why the dispatcher held a run. */
24 export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap" | "clone" | "focus";
24 export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap" | "clone" | "focus" | "sandbox";
2525
2626 /** How vitals names each cause: "2 by a shut valve". */
2727 export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = {
@@ -34,6 +34,7 @@ export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = {
3434 cap: "a bet's daily cap",
3535 clone: "a clone backing off",
3636 focus: "the owner's focus",
37 sandbox: "the agent sandbox being unavailable",
3738 };
3839
3940 /** How long a pass remembers when it last held a run; a day bounds the map. */
test/crew-sandbox-required.test.ts added +105
@@ -0,0 +1,105 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createRun, getRun } from "../src/core/runs.ts";
7 import { createUser } from "../src/core/users.ts";
8 import { pump } from "../src/crew/dispatch.ts";
9 import type { CrewOptions } from "../src/crew/runner.ts";
10 import { DEFAULT_MODE, sandboxHoldSentence, sandboxMode } from "../src/crew/sandbox_policy.ts";
11 import { noteProtection, protectionNotice } from "../src/kernel/protection.ts";
12 import { heldRuns } from "../src/runs/held.ts";
13 import { readRunLog } from "../src/runs/log.ts";
14
15 describe("FORGE_CREW_SANDBOX", () => {
16 test("require and off are read; anything else is the default", () => {
17 expect(sandboxMode({ FORGE_CREW_SANDBOX: "require" })).toBe("require");
18 expect(sandboxMode({ FORGE_CREW_SANDBOX: " OFF " })).toBe("off");
19 expect(sandboxMode({})).toBe(DEFAULT_MODE);
20 expect(sandboxMode({ FORGE_CREW_SANDBOX: "maybe" })).toBe(DEFAULT_MODE);
21 });
22 test("the sentence names the cause and what to do, in one line", () => {
23 const words = sandboxHoldSentence("bwrap is not installed");
24 expect(words).toContain("missing binary: bwrap");
25 expect(words).toContain("FORGE_CREW_SANDBOX=off");
26 expect(words).not.toContain("\n");
27 });
28 test("the footer says refused, beside what runs uncontained", () => {
29 const app = {};
30 noteProtection(app, "crew shells", { ok: false, reason: "x" }, "its runs are refused (FORGE_CREW_SANDBOX=require)");
31 expect(protectionNotice(app)).toBe("Reduced protection: crew shells (x) its runs are refused (FORGE_CREW_SANDBOX=require).");
32 noteProtection(app, "apps", { ok: false, reason: "y" });
33 expect(protectionNotice(app)).toContain("apps (y) runs uncontained; crew shells (x)");
34 });
35 });
36
37 describe("the dispatcher and a host without the sandbox", () => {
38 let dataDir: string;
39 let app: App;
40 let repoId = "";
41 const roomy = () => ({ freeBytes: 100, totalBytes: 100 });
42 const base = {
43 forgeUrl: "http://127.0.0.1:1",
44 localUrl: "http://127.0.0.1:1",
45 binary: "/nonexistent-agent",
46 concurrency: 3,
47 budgetUsd: 1,
48 runTimeoutMs: 60_000,
49 sandboxEnforced: false,
50 sandboxNote: "bwrap is not installed",
51 };
52 const as = (extra: object) => ({ ...base, ...extra }) as unknown as CrewOptions;
53
54 beforeAll(async () => {
55 dataDir = await mkdtemp(join(tmpdir(), "forge-sandbox-required-"));
56 app = createApp({ dataDir, port: 0, disk: roomy });
57 const owner = await createUser(app.db, {
58 origin: "seed",
59 trusted: true,
60 username: "sandboxer",
61 email: "[email protected]",
62 password: "a-good-passphrase",
63 });
64 if (!owner.ok) throw new Error(String(owner.error));
65 repoId = crypto.randomUUID();
66 app.db
67 .query("INSERT INTO repo (id, owner_id, name, visibility, created_at) VALUES (?1, ?2, 'sbx', 'private', ?3)")
68 .run(repoId, owner.value.id, new Date().toISOString());
69 });
70 afterAll(async () => {
71 app.close();
72 await rm(dataDir, { recursive: true, force: true });
73 });
74
75 test("required and unavailable: the run stays queued, held as sandbox, with the sentence once", () => {
76 const queued = createRun(app.db, { repoId, kind: "agent" });
77 const going = new Map<string, Promise<void>>();
78 pump(app, as({ sandboxRequired: true }), going);
79 pump(app, as({ sandboxRequired: true }), going);
80 expect(getRun(app.db, queued.id)?.state).toBe("queued");
81 expect(going.size).toBe(0);
82 expect(heldRuns(app.db).get(queued.id)).toBe("sandbox");
83 const log = readRunLog(dataDir, queued.id).lines.join("\n");
84 expect(log).toContain("queued, not started: this forge requires the agent sandbox");
85 expect(log).toContain("missing binary: bwrap");
86 expect(log.split("requires the agent sandbox").length - 1).toBe(1);
87 });
88
89 test("not required (the opt-out, or today's default): the run starts", async () => {
90 const queued = createRun(app.db, { repoId, kind: "agent" });
91 const going = new Map<string, Promise<void>>();
92 pump(app, as({ sandboxRequired: false }), going);
93 expect(going.has(queued.id)).toBe(true);
94 await Promise.all(going.values());
95 expect(heldRuns(app.db).get(queued.id)).toBeUndefined();
96 });
97
98 test("required and the sandbox available: the run starts", async () => {
99 const queued = createRun(app.db, { repoId, kind: "agent" });
100 const going = new Map<string, Promise<void>>();
101 pump(app, as({ sandboxRequired: true, sandboxEnforced: true }), going);
102 expect(going.has(queued.id)).toBe(true);
103 await Promise.all(going.values());
104 });
105 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs