@omacode/sandbox 0.1.1 → 1.0.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.
@@ -7,44 +7,29 @@
7
7
  //
8
8
  // The invariant the decision exists for: a child shell of any plugin runs in the sandbox, and the user's own
9
9
  // interactive shell never does. A root session (no parent) is the user's own; a delegated child (a parent) is not.
10
-
11
- /** A tool call, as the tool hook sees it. */
12
- export interface ShellCall {
13
- readonly tool: string
14
- readonly sessionID?: string
15
- readonly agent?: string
16
- }
17
-
18
- /** What is known about the session a call comes from. */
19
- export interface SessionFacts {
20
- /** The session that started this one. A delegated child has one; a root session (the user's own) has none. */
21
- readonly parentID?: string
22
- /** The session is a worker of the plugin that started it, whatever the session record says. */
23
- readonly worker?: boolean
24
- }
25
-
26
10
  /** The shells the plugin wraps. OpenCode's shell tool is called "shell". */
27
- export const SHELL_TOOL = "shell"
28
-
11
+ export const SHELL_TOOL = "shell";
29
12
  /**
30
13
  * Whether this call is a shell command of a child session: one the sandbox wraps.
31
14
  *
32
15
  * A call counts when it is the shell tool and its session is a delegated child (it has a parent) or a known
33
16
  * worker. A root session with no parent is the user's own interactive session, and its shell is left alone.
34
17
  */
35
- export function isChildShell(call: ShellCall, facts: SessionFacts | undefined): boolean {
36
- if (call.tool !== SHELL_TOOL) return false
37
- if (!call.sessionID) return false
38
- if (facts?.worker) return true
39
- return Boolean(facts?.parentID)
18
+ export function isChildShell(call, facts) {
19
+ if (call.tool !== SHELL_TOOL)
20
+ return false;
21
+ if (!call.sessionID)
22
+ return false;
23
+ if (facts?.worker)
24
+ return true;
25
+ return Boolean(facts?.parentID);
40
26
  }
41
-
42
27
  /**
43
28
  * Whether the session record says this session was delegated: a child session has a parent.
44
29
  *
45
30
  * The host drops the parent id for some sessions, so this is one signal among others and never the only one: a
46
31
  * session the plugin knows as a worker is a worker even without a parent id.
47
32
  */
48
- export function isDelegated(facts: SessionFacts | undefined): boolean {
49
- return Boolean(facts?.parentID) || Boolean(facts?.worker)
33
+ export function isDelegated(facts) {
34
+ return Boolean(facts?.parentID) || Boolean(facts?.worker);
50
35
  }
package/dist/plugin.js ADDED
@@ -0,0 +1,61 @@
1
+ // The sandbox plugin: a child session's shell command runs in the sandbox, and the user's own shell does not.
2
+ //
3
+ // It works on its own, with no micromanager installed: the host's session record says whether a session was
4
+ // delegated, and that is enough. The micromanager, when it is there, adds what it knows about its own workers
5
+ // (their role, their worktree, their frozen files, their job's grants) through the deps.
6
+ //
7
+ // import sandbox from "@omacode/sandbox"
8
+ // export default sandbox
9
+ import { claim } from "@omacode/core/registry";
10
+ import { installShell } from "./wire.js";
11
+ import { startSandbox, WorkerShells } from "./sandbox.js";
12
+ /**
13
+ * The sandbox and the shells of one server, shared between its instances: the tool hook of one instance notes a
14
+ * child's command, and the shell hook of another takes it.
15
+ */
16
+ const SHARED = (globalThis.__omacodeSandbox ??= {});
17
+ export const defaultShellDeps = (deps = {}, session) => {
18
+ const shells = deps.shells ?? (SHARED.shells ??= new WorkerShells());
19
+ const sandbox = deps.sandbox ?? (() => (SHARED.sandbox ??= startSandbox(true)));
20
+ return {
21
+ sandbox,
22
+ session: deps.session ?? session ?? (async () => undefined),
23
+ extra: deps.extra,
24
+ env: deps.env,
25
+ domains: deps.domains,
26
+ shells: deps.shells
27
+ ? { expect: (c, s) => deps.shells.expect(c, s), take: (c) => deps.shells.take(c), sessionOf: (c) => deps.shells.sessionOf(c) }
28
+ : { expect: (c, s) => shells.expect(c, s), take: (c) => shells.take(c), sessionOf: (c) => shells.sessionOf(c) },
29
+ unwrapped: deps.unwrapped,
30
+ temp: deps.temp,
31
+ rules: deps.rules,
32
+ log: deps.log,
33
+ };
34
+ };
35
+ export default {
36
+ id: "omacode-sandbox",
37
+ setup: async (ctx, deps = {}) => {
38
+ const anyCtx = ctx;
39
+ if (!claim("sandbox", anyCtx.location?.directory))
40
+ return;
41
+ // The host's session record says whether a command comes from a delegated child. Without this lookup the
42
+ // plugin would wrap nothing: parentID is the whole reason a command is sandboxed.
43
+ const session = deps.session ?? (async (sessionID) => {
44
+ try {
45
+ return (await anyCtx.session?.get?.({ sessionID }));
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ });
51
+ const shell = await installShell(anyCtx, defaultShellDeps(deps, session));
52
+ // The tool hook of the plugin on its own: it notes the commands of the child sessions. A plugin that redacts a
53
+ // call before the shell sees it notes the redacted command itself, through the handle.
54
+ await anyCtx.tool?.hook("execute.before", async (call) => {
55
+ await shell.note(call);
56
+ });
57
+ },
58
+ };
59
+ export { installShell } from "./wire.js";
60
+ export { isChildShell, isDelegated, SHELL_TOOL } from "./decide.js";
61
+ export { cleanEnv, looksSecret, neverHanded, REGISTRIES, rulesFor, startSandbox, tempDirFor, withTemp, WorkerShells } from "./sandbox.js";
@@ -0,0 +1,236 @@
1
+ // The shell plugin's sandbox: the rules a worker's command runs under, and the sandbox that runs it. The wiring that
2
+ // decides which command is a child's lives in src/shell/wire.ts, and the decision itself in src/shell/decide.ts.
3
+ //
4
+ // The inner boundary of a worker's shell command (the user, 2026-10-20): the permission layer reads a command's text,
5
+ // not what it does once it runs, so a writer's `npm test` ran the project's code with the user's full rights. Every
6
+ // worker command now runs under Anthropic's sandbox-runtime (bubblewrap on Linux, Seatbelt on macOS, a proxy for the
7
+ // network): a writer writes only into its own worktree, a reader nowhere, nobody reads the user's keys, and the
8
+ // network reaches the package registries and whatever the user granted for the job.
9
+ //
10
+ // The environment is an allowlist: a command starts with the variables named here, the user's "env" setting and the
11
+ // job's grants, and nothing else, so a token under a name nobody thought of stays out. Some variables are never handed
12
+ // on, whatever is granted: they open the user's desktop, agent sockets or this plugin's own credentials.
13
+ //
14
+ // Spike, 2026-10-20 (sandbox-runtime 0.0.81): per-call rules isolate two worktrees from each other; wrapping costs
15
+ // ~25-35 ms per command; `npm test` and `uv run pytest` (with PyPI allowed) pass; the environment is passed through
16
+ // as it is, so cleaning it is ours. On Linux a glob in denyRead covers the files that exist when the command is wrapped.
17
+ import { TELEMETRY_OFF } from "@omacode/core/telemetry";
18
+ import { createHash } from "node:crypto";
19
+ import { mkdirSync } from "node:fs";
20
+ import { homedir, tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ import { heldOutRoot } from "@omacode/core/heldout";
23
+ import { configFileName, userStateDir } from "@omacode/core/paths";
24
+ import { looksSecret } from "@omacode/core/secrets";
25
+ // The registries a build or a test run reaches for its dependencies.
26
+ export const REGISTRIES = [
27
+ "registry.npmjs.org", "registry.yarnpkg.com",
28
+ "pypi.org", "files.pythonhosted.org",
29
+ "crates.io", "static.crates.io", "index.crates.io",
30
+ "proxy.golang.org", "sum.golang.org",
31
+ ];
32
+ // What no worker command reads: keys, credential stores, the plugin's and OpenCode's own configuration, browser
33
+ // profiles, and environment files in the project (".env.example" stays readable).
34
+ export const DENY_READ = [
35
+ "~/.ssh", "~/.gnupg", "~/.netrc", "~/.password-store", "~/.local/share/keyrings", "~/.pki",
36
+ "~/.config/opencode", "~/.config/gh", "~/.config/hub", "~/.docker", "~/.kube", "~/.aws", "~/.azure", "~/.config/gcloud",
37
+ "~/.mozilla", "~/.config/chromium", "~/.config/google-chrome", "~/.config/BraveSoftware",
38
+ "~/.local/share/opencode", "~/.local/state/omacode", "~/.local/state/micromanager",
39
+ ];
40
+ // Variables a command keeps. A name ending in "*" is a prefix.
41
+ export const ENV_ALLOW = [
42
+ "PATH", "HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_*", "TERM", "SHELL", "TZ", "COLORTERM",
43
+ "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME",
44
+ "NODE_*", "npm_config_*", "COREPACK_*", "UV_*", "PYTHON*", "VIRTUAL_ENV", "CONDA_PREFIX", "PIP_*",
45
+ "CARGO_HOME", "RUSTUP_HOME", "RUSTFLAGS", "GOPATH", "GOCACHE", "GOFLAGS", "JAVA_HOME",
46
+ "CC", "CXX", "CFLAGS", "CXXFLAGS", "LDFLAGS", "PKG_CONFIG_PATH", "CUDA_PATH", "NVCC_CCBIN",
47
+ ];
48
+ // Variables never handed on, whatever the user granted: sockets into the desktop, the session bus (and through it the
49
+ // keyring), agent sockets, and the credentials of the hub, the decider and Claude Code.
50
+ const NEVER = [
51
+ /^SSH_AUTH_SOCK$/, /^SSH_AGENT_PID$/, /^GPG_AGENT_INFO$/, /^DBUS_/, /^HYPRLAND_/, /^WAYLAND_DISPLAY$/, /^DISPLAY$/,
52
+ /^XDG_RUNTIME_DIR$/, /SOCKET/, /^OPENCODE_SERVER_/, /^CLAUDE_CODE_/, /^JEV_/, /^HERDR_/, /^ALACRITTY_SOCKET$/,
53
+ ];
54
+ // A name that looks like it holds a secret: such a variable is granted by the user only, never by the decider.
55
+ export { looksSecret };
56
+ export function neverHanded(name) {
57
+ return NEVER.some((re) => re.test(name));
58
+ }
59
+ const matches = (name, pattern) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
60
+ // The environment a worker command runs with: the allowlist, the user's "env" setting and the job's grants, minus the
61
+ // never list. CI=1 keeps test runners from waiting for input.
62
+ export function cleanEnv(env, extra = []) {
63
+ const allow = [...ENV_ALLOW, ...extra];
64
+ const out = {};
65
+ for (const [name, value] of Object.entries(env)) {
66
+ if (value === undefined || neverHanded(name))
67
+ continue;
68
+ if (allow.some((p) => matches(name, p)))
69
+ out[name] = value;
70
+ }
71
+ out.CI = "1";
72
+ // No usage reports from what a worker runs (core/telemetry.ts).
73
+ Object.assign(out, TELEMETRY_OFF);
74
+ return out;
75
+ }
76
+ // Where the workers' temp directories live. sandbox-runtime hands every command TMPDIR=/tmp/claude, which nothing
77
+ // creates and which every worker would share (2026-10-27: mktemp failed in every worker, and headless Chromium could
78
+ // not make its profile); each worker gets its own instead, unreadable to the others.
79
+ export function tempRoot() {
80
+ return join(tmpdir(), `micromanager-${process.getuid?.() ?? "user"}`);
81
+ }
82
+ // A worker's temp directory, made on first use: one per key (a job's worktree or reader directory).
83
+ export function tempDirFor(key) {
84
+ const dir = join(tempRoot(), createHash("sha1").update(key).digest("hex").slice(0, 16));
85
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
86
+ return dir;
87
+ }
88
+ // The command as the sandbox runs it: with its temp directory as TMPDIR, after sandbox-runtime set its own.
89
+ export function withTemp(command, temp) {
90
+ if (!temp)
91
+ return command;
92
+ const dirs = {
93
+ tmp: temp,
94
+ cache: join(temp, "cache"),
95
+ data: join(temp, "data"),
96
+ state: join(temp, "state"),
97
+ npm: join(temp, "npm"),
98
+ pip: join(temp, "pip"),
99
+ uv: join(temp, "uv"),
100
+ };
101
+ for (const dir of Object.values(dirs))
102
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
103
+ const q = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
104
+ return [
105
+ `export TMPDIR=${q(dirs.tmp)} TMP=${q(dirs.tmp)} TEMP=${q(dirs.tmp)}`,
106
+ `XDG_CACHE_HOME=${q(dirs.cache)} XDG_DATA_HOME=${q(dirs.data)} XDG_STATE_HOME=${q(dirs.state)}`,
107
+ `npm_config_cache=${q(dirs.npm)} PIP_CACHE_DIR=${q(dirs.pip)} UV_CACHE_DIR=${q(dirs.uv)}`,
108
+ ].join(" ") + `; ${command}`;
109
+ }
110
+ // A writer writes its own worktree, a reader nothing; both have a private temp directory (never /tmp as a whole: the
111
+ // spike's first run let worker B write into A's worktree through it). Environment files of the project stay unreadable.
112
+ export function rulesFor(input) {
113
+ const own = [...(input.writer ? [input.worktree ?? input.dir] : []), ...(input.temp ? [input.temp] : [])];
114
+ return {
115
+ network: { allowedDomains: [...new Set([...REGISTRIES, ...(input.domains ?? [])])], deniedDomains: [] },
116
+ filesystem: {
117
+ // The held-out cases of fitness contracts (src/contract.ts) live in the plugin's state directory, which DENY_READ
118
+ // names by its default place; with XDG_STATE_HOME set it is elsewhere, so it is named by where it is.
119
+ denyRead: [...DENY_READ, userStateDir(), heldOutRoot(), tempRoot(), join(input.dir, "**/.env"), join(input.dir, "**/.env.*")],
120
+ allowRead: [join(input.dir, "**/.env.example"), ...(input.temp ? [input.temp] : [])],
121
+ allowWrite: own,
122
+ // A frozen test inside the writer's own worktree: `sed -i` must not get around what the edit tools may not do.
123
+ denyWrite: [...(input.frozen ?? [])],
124
+ },
125
+ };
126
+ }
127
+ // A plan job's writer (A1-T7): the caller passes the plan root as `worktree` and the worker's own directory as `dir`,
128
+ // so only the plan area (plus its temp dir) is writable and the project stays read-only. The caller decides WHETHER a
129
+ // plan writer may start at all: with no sandbox, a plan job runs reader-only (src/native.ts).
130
+ export function planRules(input) {
131
+ return rulesFor({ ...input, writer: true, worktree: input.worktree });
132
+ }
133
+ const BASE = { network: { allowedDomains: [...REGISTRIES], deniedDomains: [] }, filesystem: { denyRead: [...DENY_READ], allowRead: [], allowWrite: [], denyWrite: [] } };
134
+ // Checks once per server whether the sandbox can run; its proxy starts with the first command it wraps, so a server
135
+ // (or a test) that never runs a worker command keeps no proxy alive. A sandbox that cannot run leaves the plugin
136
+ // working without one: commands are not wrapped, the environment is still cleaned, and src/decide.ts sends writers'
137
+ // commands to the decider again.
138
+ export async function startSandbox(enabled = true) {
139
+ const off = (reason) => ({ available: false, reason, wrap: async (command) => command, stop: async () => undefined });
140
+ if (!enabled)
141
+ return off(`switched off in ${configFileName()}`);
142
+ try {
143
+ const { SandboxManager } = await import("@anthropic-ai/sandbox-runtime");
144
+ if (!SandboxManager.isSupportedPlatform())
145
+ return off(`no sandbox on ${process.platform}`);
146
+ const deps = await SandboxManager.checkDependenciesAsync();
147
+ if (deps.errors.length)
148
+ return off(deps.errors.join("; "));
149
+ let started;
150
+ return {
151
+ available: true,
152
+ wrap: async (command, rules) => {
153
+ await (started ??= SandboxManager.initialize(BASE));
154
+ return SandboxManager.wrapWithSandbox(command, undefined, rules);
155
+ },
156
+ stop: async () => {
157
+ if (started)
158
+ await SandboxManager.reset();
159
+ started = undefined;
160
+ },
161
+ };
162
+ }
163
+ catch (err) {
164
+ return off(`sandbox-runtime did not start: ${String(err)}`);
165
+ }
166
+ }
167
+ // The home directory as sandbox-runtime expands "~", for tests and messages.
168
+ export const HOME = homedir();
169
+ // The shells a worker asked for, by their command text. OpenCode's shell hook gets no session id (opencode 2.0.18:
170
+ // { command, cwd, timeout, shell, env } only), and a directory is no proof: a reader works in the project itself, so
171
+ // every shell there, the user's own agent's and the micromanager's included, got wrapped. The shell tool's
172
+ // execute.before does know the session; it notes a worker's command here, and the shell hook wraps only what it takes.
173
+ //
174
+ // The session that asked is remembered with the command, so the shell hook can ask what it knows about that
175
+ // session (its role, its worktree, its job's grants) without guessing from the directory.
176
+ // The fuse of WorkerShells: how many noted commands may wait for the shell hook at once. A live session has a
177
+ // handful; reaching this number means thousands of workers died between the tool hook and the shell, and the
178
+ // oldest of those stale notes can go. It is far above any real load precisely because dropping a command that
179
+ // is still in flight would let it run unsandboxed.
180
+ const MAX_NOTED_COMMANDS = 2_000;
181
+ export class WorkerShells {
182
+ #pending = new Map();
183
+ #sessions = new Map();
184
+ expect(command, sessionID) {
185
+ this.#pending.set(command, (this.#pending.get(command) ?? 0) + 1);
186
+ if (sessionID) {
187
+ const sessions = this.#sessions.get(command) ?? [];
188
+ sessions.push(sessionID);
189
+ this.#sessions.set(command, sessions);
190
+ }
191
+ // Every entry still held is a command the shell hook has not taken: take deletes a count the moment it
192
+ // reaches zero, so the fuse never evicts to make room for a zero, and dropping one at the cap drops its
193
+ // session list with it. Neither map keeps keys its commands have left behind.
194
+ while (this.#pending.size > MAX_NOTED_COMMANDS) {
195
+ const stale = this.#pending.keys().next().value;
196
+ this.#pending.delete(stale);
197
+ this.#sessions.delete(stale);
198
+ }
199
+ while (this.#sessions.size > MAX_NOTED_COMMANDS)
200
+ this.#sessions.delete(this.#sessions.keys().next().value);
201
+ }
202
+ take(command) {
203
+ const n = this.#pending.get(command);
204
+ if (!n)
205
+ return false;
206
+ if (n <= 1)
207
+ this.#pending.delete(command);
208
+ else
209
+ this.#pending.set(command, n - 1);
210
+ return true;
211
+ }
212
+ /**
213
+ * The session that asked for this command, when one is known.
214
+ *
215
+ * The shell hook reads it right after the take, so the list is trimmed here: the last session out deletes the
216
+ * key, so this map holds the sessions of the pending commands and nothing else, and normal operation leaves it
217
+ * as empty as the list of pending commands.
218
+ */
219
+ sessionOf(command) {
220
+ const sessions = this.#sessions.get(command);
221
+ if (!sessions?.length)
222
+ return undefined;
223
+ const session = sessions.shift();
224
+ if (!sessions.length)
225
+ this.#sessions.delete(command);
226
+ return session;
227
+ }
228
+ /** How many noted commands the shell hook has not taken yet. For tests and diagnostics; normally ~0. */
229
+ get pendingCount() {
230
+ return this.#pending.size;
231
+ }
232
+ /** How many commands still have a remembered session. For tests and diagnostics; normally ~0. */
233
+ get sessionCount() {
234
+ return this.#sessions.size;
235
+ }
236
+ }
package/dist/wire.js ADDED
@@ -0,0 +1,111 @@
1
+ // The shell plugin's wiring: a child session's shell command is wrapped in the sandbox, and the user's own shell is
2
+ // not. It works on its own (no micromanager installed): the session record's parent id is enough to tell a child
3
+ // from a root session. When the micromanager is there, it adds what it knows about its own workers: their role,
4
+ // their worktree, their frozen files and the job's grants.
5
+ //
6
+ // Two hooks are used, and the order matters: the tool hook (execute.before) knows the session and notes the
7
+ // command; the shell hook (create.before) has the command and wraps it. A command nobody announced is left alone,
8
+ // which is what keeps another agent's shell and the user's own out of the sandbox.
9
+ //
10
+ // The decision lives in decide.ts, so it can be tested without a host: a delegated child (a session with a parent)
11
+ // is wrapped, a root session (the user's own) never is.
12
+ import { cleanEnv, planRules, rulesFor, withTemp } from "./sandbox.js";
13
+ import { isChildShell } from "./decide.js";
14
+ /**
15
+ * The rules of a command, when the plugin knows nothing more about the session: a writer writes its own
16
+ * directory, a reader nowhere, and the network reaches the registries and whatever was granted.
17
+ *
18
+ * A plan job's worker is the exception: it writes in the plan area and its own temp directory only, so the project
19
+ * stays read-only (A1-T7).
20
+ */
21
+ export function defaultRules(facts, input) {
22
+ const dir = facts.dir ?? input.cwd ?? process.cwd();
23
+ if (facts.plan && facts.planRoot) {
24
+ return planRules({
25
+ role: facts.role ?? "investigator",
26
+ writer: true,
27
+ dir,
28
+ worktree: facts.planRoot,
29
+ domains: facts.domains ?? [],
30
+ frozen: [],
31
+ temp: facts.temp,
32
+ });
33
+ }
34
+ return rulesFor({
35
+ role: facts.role ?? "code",
36
+ writer: facts.writer ?? true,
37
+ dir,
38
+ worktree: facts.worktree ?? dir,
39
+ domains: facts.domains ?? [],
40
+ frozen: facts.frozen ?? [],
41
+ temp: facts.temp,
42
+ });
43
+ }
44
+ /** The facts of a session: what its record says, plus what the plugin knows about it. */
45
+ export async function factsOf(deps, sessionID, cwd) {
46
+ const record = await deps.session(sessionID).catch(() => undefined);
47
+ const extra = deps.extra?.(sessionID, cwd) ?? {};
48
+ return { parentID: record?.parentID, ...extra };
49
+ }
50
+ /**
51
+ * Install the shell plugin's wiring.
52
+ *
53
+ * The caller notes the commands of child sessions (handle.note); the shell hook wraps the commands it takes. A
54
+ * command that no child session announced is left exactly as it is.
55
+ *
56
+ * The caller notes the commands itself, because a plugin that redacts a call before the shell sees it has to note
57
+ * the redacted command, not the one the model wrote.
58
+ */
59
+ export async function installShell(ctx, deps) {
60
+ const rules = deps.rules ?? defaultRules;
61
+ const note = async (call) => {
62
+ if (!call.sessionID)
63
+ return;
64
+ // A session the plugin knows as its own worker needs no host lookup; any other session is looked up, because the
65
+ // host's record says whether it was delegated (a child) or is the user's own (a root session).
66
+ const worker = deps.isWorker?.(call.sessionID);
67
+ const record = worker ? undefined : await deps.session(call.sessionID).catch(() => undefined);
68
+ const facts = { parentID: record?.parentID, worker };
69
+ if (!isChildShell(call, facts))
70
+ return;
71
+ const command = String(call.input?.command ?? "");
72
+ if (command)
73
+ deps.shells.expect(command, call.sessionID);
74
+ };
75
+ await ctx.shell?.hook("create.before", async (input) => {
76
+ if (!deps.shells.take(input.command))
77
+ return;
78
+ const cwd = String(input.cwd ?? "");
79
+ const sessionID = deps.shells.sessionOf(input.command);
80
+ const facts = sessionID ? await factsOf(deps, sessionID, cwd) : {};
81
+ // A session the plugin knows as its own is judged by the plugin's own rule: the facts it has about it (and the
82
+ // command's directory) decide. A session it does not know at all is a child of some other plugin: the generic
83
+ // rule holds, a delegated child is wrapped. The user's own shell is a root session, and no rule wraps it.
84
+ if (facts.known) {
85
+ if (!facts.worker && !facts.dir)
86
+ return;
87
+ }
88
+ else if (!facts.parentID) {
89
+ return;
90
+ }
91
+ input.env = cleanEnv(input.env ?? process.env, [...(deps.env ?? []), ...(facts.env ?? [])]);
92
+ // The user's switch: the job runs as if no sandbox existed, with the cleaned environment and its grants only.
93
+ if (facts.off)
94
+ return;
95
+ const box = await deps.sandbox();
96
+ if (!box.available)
97
+ return;
98
+ const temp = facts.temp ?? deps.temp?.(cwd);
99
+ const own = { ...facts, temp };
100
+ const wrapped = await box.wrap(withTemp(input.command, temp), rules(own, input));
101
+ const seen = deps.unwrapped;
102
+ if (seen) {
103
+ seen.set(wrapped, input.command);
104
+ if (seen.size > 500)
105
+ seen.delete(seen.keys().next().value);
106
+ }
107
+ input.command = wrapped;
108
+ await deps.onWrap?.(own);
109
+ });
110
+ return { note };
111
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omacode/sandbox",
3
- "version": "0.1.1",
3
+ "version": "1.0.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Run delegated child sessions' shell commands in a sandbox",
@@ -16,7 +16,7 @@
16
16
  "url": "https://github.com/RentschlerTobias/Omacode/issues"
17
17
  },
18
18
  "engines": {
19
- "node": ">=22.12.0"
19
+ "node": ">=22.18.0"
20
20
  },
21
21
  "keywords": [
22
22
  "opencode",
@@ -26,20 +26,20 @@
26
26
  "security"
27
27
  ],
28
28
  "scripts": {
29
- "prepack": "node ../../scripts/copy-license.mjs",
30
- "postpack": "node ../../scripts/copy-license.mjs --remove"
29
+ "prepack": "node ../../scripts/pack-js.mjs",
30
+ "postpack": "node ../../scripts/pack-js.mjs --restore"
31
31
  },
32
32
  "exports": {
33
- ".": "./src/plugin.ts",
34
- "./wire": "./src/wire.ts",
35
- "./decide": "./src/decide.ts",
36
- "./sandbox": "./src/sandbox.ts"
33
+ ".": "./dist/plugin.js",
34
+ "./wire": "./dist/wire.js",
35
+ "./decide": "./dist/decide.js",
36
+ "./sandbox": "./dist/sandbox.js"
37
37
  },
38
38
  "files": [
39
- "src"
39
+ "dist"
40
40
  ],
41
41
  "dependencies": {
42
- "@omacode/core": "0.1.1"
42
+ "@omacode/core": "1.0.0"
43
43
  },
44
44
  "publishConfig": {
45
45
  "access": "public"
package/src/plugin.ts DELETED
@@ -1,75 +0,0 @@
1
- // The sandbox plugin: a child session's shell command runs in the sandbox, and the user's own shell does not.
2
- //
3
- // It works on its own, with no micromanager installed: the host's session record says whether a session was
4
- // delegated, and that is enough. The micromanager, when it is there, adds what it knows about its own workers
5
- // (their role, their worktree, their frozen files, their job's grants) through the deps.
6
- //
7
- // import sandbox from "@omacode/sandbox"
8
- // export default sandbox
9
-
10
- import { claim } from "@omacode/core/registry"
11
- import { installShell, type ShellDeps } from "./wire.ts"
12
- import { startSandbox, WorkerShells, type Wrapper } from "./sandbox.ts"
13
-
14
- export interface ShellPluginDeps extends Partial<ShellDeps> {
15
- /** The shells of the server, shared between the instances of one host. */
16
- readonly shells?: WorkerShells
17
- /** The sandbox of the server, shared between the instances of one host. */
18
- readonly sandbox?: () => Promise<Wrapper>
19
- }
20
-
21
- /**
22
- * The sandbox and the shells of one server, shared between its instances: the tool hook of one instance notes a
23
- * child's command, and the shell hook of another takes it.
24
- */
25
- const SHARED: { shells?: WorkerShells; sandbox?: Promise<Wrapper> } =
26
- ((globalThis as { __omacodeSandbox?: { shells?: WorkerShells; sandbox?: Promise<Wrapper> } }).__omacodeSandbox ??= {})
27
-
28
- export const defaultShellDeps = (deps: ShellPluginDeps = {}, session?: ShellDeps["session"]): ShellDeps => {
29
- const shells = deps.shells ?? (SHARED.shells ??= new WorkerShells())
30
- const sandbox = deps.sandbox ?? (() => (SHARED.sandbox ??= startSandbox(true)))
31
- return {
32
- sandbox,
33
- session: deps.session ?? session ?? (async () => undefined),
34
- extra: deps.extra,
35
- env: deps.env,
36
- domains: deps.domains,
37
- shells: deps.shells
38
- ? { expect: (c, s) => deps.shells!.expect(c, s), take: (c) => deps.shells!.take(c), sessionOf: (c) => deps.shells!.sessionOf(c) }
39
- : { expect: (c, s) => shells.expect(c, s), take: (c) => shells.take(c), sessionOf: (c) => shells.sessionOf(c) },
40
- unwrapped: deps.unwrapped,
41
- temp: deps.temp,
42
- rules: deps.rules,
43
- log: deps.log,
44
- }
45
- }
46
-
47
- export default {
48
- id: "omacode-sandbox",
49
- setup: async (ctx: unknown, deps: ShellPluginDeps = {}): Promise<void> => {
50
- if (!claim("sandbox")) return
51
- const anyCtx = ctx as {
52
- tool?: { hook(name: string, cb: (call: any) => Promise<void> | void): Promise<unknown> }
53
- session?: { get?(args: { sessionID: string }): Promise<unknown> }
54
- }
55
- // The host's session record says whether a command comes from a delegated child. Without this lookup the
56
- // plugin would wrap nothing: parentID is the whole reason a command is sandboxed.
57
- const session: ShellDeps["session"] = deps.session ?? (async (sessionID) => {
58
- try {
59
- return (await anyCtx.session?.get?.({ sessionID })) as Awaited<ReturnType<ShellDeps["session"]>>
60
- } catch {
61
- return undefined
62
- }
63
- })
64
- const shell = await installShell(anyCtx, defaultShellDeps(deps, session))
65
- // The tool hook of the plugin on its own: it notes the commands of the child sessions. A plugin that redacts a
66
- // call before the shell sees it notes the redacted command itself, through the handle.
67
- await anyCtx.tool?.hook("execute.before", async (call: any) => {
68
- await shell.note(call)
69
- })
70
- },
71
- }
72
-
73
- export { installShell } from "./wire.ts"
74
- export { isChildShell, isDelegated, SHELL_TOOL, type SessionFacts, type ShellCall } from "./decide.ts"
75
- export { cleanEnv, looksSecret, neverHanded, REGISTRIES, rulesFor, startSandbox, tempDirFor, withTemp, WorkerShells, type Rules, type Wrapper } from "./sandbox.ts"
package/src/sandbox.ts DELETED
@@ -1,233 +0,0 @@
1
- // The shell plugin's sandbox: the rules a worker's command runs under, and the sandbox that runs it. The wiring that
2
- // decides which command is a child's lives in src/shell/wire.ts, and the decision itself in src/shell/decide.ts.
3
- //
4
- // The inner boundary of a worker's shell command (the user, 2026-10-20): the permission layer reads a command's text,
5
- // not what it does once it runs, so a writer's `npm test` ran the project's code with the user's full rights. Every
6
- // worker command now runs under Anthropic's sandbox-runtime (bubblewrap on Linux, Seatbelt on macOS, a proxy for the
7
- // network): a writer writes only into its own worktree, a reader nowhere, nobody reads the user's keys, and the
8
- // network reaches the package registries and whatever the user granted for the job.
9
- //
10
- // The environment is an allowlist: a command starts with the variables named here, the user's "env" setting and the
11
- // job's grants, and nothing else, so a token under a name nobody thought of stays out. Some variables are never handed
12
- // on, whatever is granted: they open the user's desktop, agent sockets or this plugin's own credentials.
13
- //
14
- // Spike, 2026-10-20 (sandbox-runtime 0.0.81): per-call rules isolate two worktrees from each other; wrapping costs
15
- // ~25-35 ms per command; `npm test` and `uv run pytest` (with PyPI allowed) pass; the environment is passed through
16
- // as it is, so cleaning it is ours. On Linux a glob in denyRead covers the files that exist when the command is wrapped.
17
-
18
- import { createHash } from "node:crypto"
19
- import { mkdirSync } from "node:fs"
20
- import { homedir, tmpdir } from "node:os"
21
- import { join } from "node:path"
22
-
23
- import { heldOutRoot } from "@omacode/core/heldout"
24
- import { looksSecret } from "@omacode/core/secrets"
25
-
26
- // The registries a build or a test run reaches for its dependencies.
27
- export const REGISTRIES: readonly string[] = [
28
- "registry.npmjs.org", "registry.yarnpkg.com",
29
- "pypi.org", "files.pythonhosted.org",
30
- "crates.io", "static.crates.io", "index.crates.io",
31
- "proxy.golang.org", "sum.golang.org",
32
- ]
33
-
34
- // What no worker command reads: keys, credential stores, the plugin's and OpenCode's own configuration, browser
35
- // profiles, and environment files in the project (".env.example" stays readable).
36
- export const DENY_READ: readonly string[] = [
37
- "~/.ssh", "~/.gnupg", "~/.netrc", "~/.password-store", "~/.local/share/keyrings", "~/.pki",
38
- "~/.config/opencode", "~/.config/gh", "~/.config/hub", "~/.docker", "~/.kube", "~/.aws", "~/.azure", "~/.config/gcloud",
39
- "~/.mozilla", "~/.config/chromium", "~/.config/google-chrome", "~/.config/BraveSoftware",
40
- "~/.local/share/opencode", "~/.local/state/micromanager",
41
- ]
42
-
43
- // Variables a command keeps. A name ending in "*" is a prefix.
44
- export const ENV_ALLOW: readonly string[] = [
45
- "PATH", "HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_*", "TERM", "SHELL", "TZ", "COLORTERM",
46
- "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME",
47
- "NODE_*", "npm_config_*", "COREPACK_*", "UV_*", "PYTHON*", "VIRTUAL_ENV", "CONDA_PREFIX", "PIP_*",
48
- "CARGO_HOME", "RUSTUP_HOME", "RUSTFLAGS", "GOPATH", "GOCACHE", "GOFLAGS", "JAVA_HOME",
49
- "CC", "CXX", "CFLAGS", "CXXFLAGS", "LDFLAGS", "PKG_CONFIG_PATH", "CUDA_PATH", "NVCC_CCBIN",
50
- ]
51
-
52
- // Variables never handed on, whatever the user granted: sockets into the desktop, the session bus (and through it the
53
- // keyring), agent sockets, and the credentials of the hub, Jev and Claude Code.
54
- const NEVER: readonly RegExp[] = [
55
- /^SSH_AUTH_SOCK$/, /^SSH_AGENT_PID$/, /^GPG_AGENT_INFO$/, /^DBUS_/, /^HYPRLAND_/, /^WAYLAND_DISPLAY$/, /^DISPLAY$/,
56
- /^XDG_RUNTIME_DIR$/, /SOCKET/, /^OPENCODE_SERVER_/, /^CLAUDE_CODE_/, /^JEV_/, /^HERDR_/, /^ALACRITTY_SOCKET$/,
57
- ]
58
-
59
- // A name that looks like it holds a secret: such a variable is granted by the user only, never by Jev.
60
- export { looksSecret }
61
-
62
- export function neverHanded(name: string): boolean {
63
- return NEVER.some((re) => re.test(name))
64
- }
65
-
66
- const matches = (name: string, pattern: string) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)
67
-
68
- // The environment a worker command runs with: the allowlist, the user's "env" setting and the job's grants, minus the
69
- // never list. CI=1 keeps test runners from waiting for input.
70
- export function cleanEnv(env: Readonly<Record<string, string | undefined>>, extra: readonly string[] = []): Record<string, string> {
71
- const allow = [...ENV_ALLOW, ...extra]
72
- const out: Record<string, string> = {}
73
- for (const [name, value] of Object.entries(env)) {
74
- if (value === undefined || neverHanded(name)) continue
75
- if (allow.some((p) => matches(name, p))) out[name] = value
76
- }
77
- out.CI = "1"
78
- return out
79
- }
80
-
81
- // The sandbox rules of one command, as sandbox-runtime takes them per call.
82
- export interface Rules {
83
- readonly network: { readonly allowedDomains: string[]; readonly deniedDomains: string[] }
84
- readonly filesystem: { readonly denyRead: string[]; readonly allowRead: string[]; readonly allowWrite: string[]; readonly denyWrite: string[] }
85
- }
86
-
87
- export interface RuleInput {
88
- readonly role: string
89
- readonly writer: boolean
90
- readonly dir: string // where the worker works: its worktree (writer), or what it reads
91
- readonly worktree?: string // a writer's worktree root, the one place it writes
92
- readonly domains?: readonly string[] // the user's "network" setting and the job's granted domains
93
- readonly frozen?: readonly string[] // absolute paths a writer may read and run but not change (src/native.ts)
94
- readonly temp?: string // the worker's own temp directory (tempDirFor), the one place a reader writes
95
- }
96
-
97
- // Where the workers' temp directories live. sandbox-runtime hands every command TMPDIR=/tmp/claude, which nothing
98
- // creates and which every worker would share (2026-10-27: mktemp failed in every worker, and headless Chromium could
99
- // not make its profile); each worker gets its own instead, unreadable to the others.
100
- export function tempRoot(): string {
101
- return join(tmpdir(), `micromanager-${process.getuid?.() ?? "user"}`)
102
- }
103
-
104
- // A worker's temp directory, made on first use: one per key (a job's worktree or reader directory).
105
- export function tempDirFor(key: string): string {
106
- const dir = join(tempRoot(), createHash("sha1").update(key).digest("hex").slice(0, 16))
107
- mkdirSync(dir, { recursive: true, mode: 0o700 })
108
- return dir
109
- }
110
-
111
- // The command as the sandbox runs it: with its temp directory as TMPDIR, after sandbox-runtime set its own.
112
- export function withTemp(command: string, temp: string | undefined): string {
113
- if (!temp) return command
114
- const dirs = {
115
- tmp: temp,
116
- cache: join(temp, "cache"),
117
- data: join(temp, "data"),
118
- state: join(temp, "state"),
119
- npm: join(temp, "npm"),
120
- pip: join(temp, "pip"),
121
- uv: join(temp, "uv"),
122
- }
123
- for (const dir of Object.values(dirs)) mkdirSync(dir, { recursive: true, mode: 0o700 })
124
- const q = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`
125
- return [
126
- `export TMPDIR=${q(dirs.tmp)} TMP=${q(dirs.tmp)} TEMP=${q(dirs.tmp)}`,
127
- `XDG_CACHE_HOME=${q(dirs.cache)} XDG_DATA_HOME=${q(dirs.data)} XDG_STATE_HOME=${q(dirs.state)}`,
128
- `npm_config_cache=${q(dirs.npm)} PIP_CACHE_DIR=${q(dirs.pip)} UV_CACHE_DIR=${q(dirs.uv)}`,
129
- ].join(" ") + `; ${command}`
130
- }
131
-
132
- // A writer writes its own worktree, a reader nothing; both have a private temp directory (never /tmp as a whole: the
133
- // spike's first run let worker B write into A's worktree through it). Environment files of the project stay unreadable.
134
- export function rulesFor(input: RuleInput): Rules {
135
- const own = [...(input.writer ? [input.worktree ?? input.dir] : []), ...(input.temp ? [input.temp] : [])]
136
- return {
137
- network: { allowedDomains: [...new Set([...REGISTRIES, ...(input.domains ?? [])])], deniedDomains: [] },
138
- filesystem: {
139
- // The held-out cases of fitness contracts (src/contract.ts) live in the plugin's state directory, which DENY_READ
140
- // names by its default place; with XDG_STATE_HOME set it is elsewhere, so it is named by where it is.
141
- denyRead: [...DENY_READ, heldOutRoot(), tempRoot(), join(input.dir, "**/.env"), join(input.dir, "**/.env.*")],
142
- allowRead: [join(input.dir, "**/.env.example"), ...(input.temp ? [input.temp] : [])],
143
- allowWrite: own,
144
- // A frozen test inside the writer's own worktree: `sed -i` must not get around what the edit tools may not do.
145
- denyWrite: [...(input.frozen ?? [])],
146
- },
147
- }
148
- }
149
-
150
- // The sandbox the plugin runs worker commands in, or why there is none.
151
- export interface Wrapper {
152
- readonly available: boolean
153
- readonly reason?: string // why not: platform, missing bubblewrap/socat/ripgrep, the user's setting
154
- wrap(command: string, rules: Rules): Promise<string>
155
- stop(): Promise<void> // the proxy keeps a process alive; a server never stops it, a test does
156
- }
157
-
158
- const BASE: Rules = { network: { allowedDomains: [...REGISTRIES], deniedDomains: [] }, filesystem: { denyRead: [...DENY_READ], allowRead: [], allowWrite: [], denyWrite: [] } }
159
-
160
- // Checks once per server whether the sandbox can run; its proxy starts with the first command it wraps, so a server
161
- // (or a test) that never runs a worker command keeps no proxy alive. A sandbox that cannot run leaves the plugin
162
- // working without one: commands are not wrapped, the environment is still cleaned, and src/decide.ts sends writers'
163
- // commands to Jev again.
164
- export async function startSandbox(enabled = true): Promise<Wrapper> {
165
- const off = (reason: string): Wrapper => ({ available: false, reason, wrap: async (command) => command, stop: async () => undefined })
166
- if (!enabled) return off("switched off in micromanager.jsonc")
167
- try {
168
- const { SandboxManager } = await import("@anthropic-ai/sandbox-runtime")
169
- if (!SandboxManager.isSupportedPlatform()) return off(`no sandbox on ${process.platform}`)
170
- const deps = await SandboxManager.checkDependenciesAsync()
171
- if (deps.errors.length) return off(deps.errors.join("; "))
172
- let started: Promise<void> | undefined
173
- return {
174
- available: true,
175
- wrap: async (command, rules) => {
176
- await (started ??= SandboxManager.initialize(BASE as never))
177
- return SandboxManager.wrapWithSandbox(command, undefined, rules as never)
178
- },
179
- stop: async () => {
180
- if (started) await SandboxManager.reset()
181
- started = undefined
182
- },
183
- }
184
- } catch (err) {
185
- return off(`sandbox-runtime did not start: ${String(err)}`)
186
- }
187
- }
188
-
189
- // The home directory as sandbox-runtime expands "~", for tests and messages.
190
- export const HOME = homedir()
191
-
192
- // The shells a worker asked for, by their command text. OpenCode's shell hook gets no session id (opencode 2.0.18:
193
- // { command, cwd, timeout, shell, env } only), and a directory is no proof: a reader works in the project itself, so
194
- // every shell there, the user's own agent's and the micromanager's included, got wrapped. The shell tool's
195
- // execute.before does know the session; it notes a worker's command here, and the shell hook wraps only what it takes.
196
- //
197
- // The session that asked is remembered with the command, so the shell hook can ask what it knows about that
198
- // session (its role, its worktree, its job's grants) without guessing from the directory.
199
- export class WorkerShells {
200
- readonly #pending = new Map<string, number>()
201
- readonly #sessions = new Map<string, string[]>()
202
-
203
- expect(command: string, sessionID?: string): void {
204
- this.#pending.set(command, (this.#pending.get(command) ?? 0) + 1)
205
- if (sessionID) {
206
- const sessions = this.#sessions.get(command) ?? []
207
- sessions.push(sessionID)
208
- this.#sessions.set(command, sessions)
209
- }
210
- if (this.#pending.size > 500) this.#pending.delete(this.#pending.keys().next().value!)
211
- if (this.#sessions.size > 500) this.#sessions.delete(this.#sessions.keys().next().value!)
212
- }
213
-
214
- take(command: string): boolean {
215
- const n = this.#pending.get(command)
216
- if (!n) return false
217
- if (n === 1) this.#pending.delete(command)
218
- else this.#pending.set(command, n - 1)
219
- return true
220
- }
221
-
222
- /**
223
- * The session that asked for this command, when one is known.
224
- *
225
- * The shell hook reads it right after the take, so the list is trimmed there and not here: a command nobody takes
226
- * again leaves its session behind, and the list is as bounded as the list of pending commands.
227
- */
228
- sessionOf(command: string): string | undefined {
229
- const sessions = this.#sessions.get(command)
230
- if (!sessions?.length) return undefined
231
- return sessions.shift()
232
- }
233
- }
package/src/wire.ts DELETED
@@ -1,184 +0,0 @@
1
- // The shell plugin's wiring: a child session's shell command is wrapped in the sandbox, and the user's own shell is
2
- // not. It works on its own (no micromanager installed): the session record's parent id is enough to tell a child
3
- // from a root session. When the micromanager is there, it adds what it knows about its own workers: their role,
4
- // their worktree, their frozen files and the job's grants.
5
- //
6
- // Two hooks are used, and the order matters: the tool hook (execute.before) knows the session and notes the
7
- // command; the shell hook (create.before) has the command and wraps it. A command nobody announced is left alone,
8
- // which is what keeps another agent's shell and the user's own out of the sandbox.
9
- //
10
- // The decision lives in decide.ts, so it can be tested without a host: a delegated child (a session with a parent)
11
- // is wrapped, a root session (the user's own) never is.
12
-
13
- import { cleanEnv, rulesFor, withTemp, type Rules, type Wrapper } from "./sandbox.ts"
14
- import { isChildShell, type SessionFacts, type ShellCall } from "./decide.ts"
15
-
16
- /** What the shell hook gets (opencode 2.0.18: "create.before" gets the shell to start). */
17
- export interface ShellInput {
18
- command: string
19
- cwd?: string
20
- env?: Record<string, string | undefined>
21
- }
22
-
23
- /** The host's session record, as far as the shell plugin reads it. */
24
- export interface SessionRecord {
25
- /** The session that started this one; a delegated child has one, a root session none. */
26
- parentID?: string
27
- /** The agent the session runs. */
28
- agent?: string
29
- location?: { directory?: string }
30
- directory?: string
31
- }
32
-
33
- /** What the plugin knows about the session a command comes from, beyond the session record. */
34
- export interface SessionExtra {
35
- /** The session is a worker of this plugin. */
36
- readonly worker?: boolean
37
- /**
38
- * The plugin knows this session as one of its own, whatever the command's directory says. A plugin that knows a
39
- * session by its own bookkeeping says so here, so that its own rule for that session holds; a session the plugin
40
- * does not know at all is a child of some other plugin, and the generic rule (a delegated child is wrapped) holds.
41
- */
42
- readonly known?: boolean
43
- /** The role it works as (src/roles.ts). */
44
- readonly role?: string
45
- /** Whether it writes; a reader writes nowhere. */
46
- readonly writer?: boolean
47
- /** Its own directory: the worktree of a writer, the project of a reader. */
48
- readonly dir?: string
49
- /** The worktree root it may write in. */
50
- readonly worktree?: string
51
- /** Files it may read and run but not change. */
52
- readonly frozen?: readonly string[]
53
- /** The job's granted hosts. */
54
- readonly domains?: readonly string[]
55
- /** The job's granted environment names. */
56
- readonly env?: readonly string[]
57
- /** The session's own temp directory, where its commands write their scratch files. */
58
- readonly temp?: string
59
- /** The project the session works in, when the plugin knows one. */
60
- readonly project?: string
61
- /** The job the session works for, when the plugin knows one. */
62
- readonly jobId?: string
63
- }
64
-
65
- /** The shells the plugin wraps. The host's shell tool is called "shell". */
66
- export interface WorkerShells {
67
- expect(command: string, sessionID?: string): void
68
- take(command: string): boolean
69
- sessionOf(command: string): string | undefined
70
- }
71
-
72
- export interface ShellDeps {
73
- /** The sandbox the commands run in, or why there is none. */
74
- readonly sandbox: () => Promise<Wrapper>
75
- /** The session record of a session, or undefined when the host does not know it. */
76
- readonly session: (sessionID: string) => Promise<SessionRecord | undefined>
77
- /** What the plugin knows about a session, beyond its record. The cwd is the command's directory. */
78
- readonly extra?: (sessionID: string, cwd?: string) => SessionExtra | undefined
79
- /**
80
- * Whether a session is one of this plugin's workers, without a command in hand. The tool hook notes a worker's
81
- * command before the shell hook knows its directory, so the session itself is the only thing it can go by.
82
- */
83
- readonly isWorker?: (sessionID: string) => boolean
84
- /** The environment names every worker command keeps. */
85
- readonly env?: readonly string[]
86
- /** The hosts every worker command may reach. */
87
- readonly domains?: readonly string[]
88
- /** The command of a worker session is noted here, and the shell hook takes it from here. */
89
- readonly shells: WorkerShells
90
- /** A wrapped command -> the command the worker wrote. The permission layer judges the worker's own command. */
91
- readonly unwrapped?: Map<string, string>
92
- /** Where the worker's own temp directory is. */
93
- readonly temp?: (key: string) => string
94
- /** The rules of a command. The default is a writer's own worktree, a reader nowhere. */
95
- readonly rules?: (facts: SessionFacts & SessionExtra, input: ShellInput) => Rules
96
- /** Called after a command was wrapped, so the plugin can note the sandbox in its own state. */
97
- readonly onWrap?: (facts: SessionFacts & SessionExtra) => void | Promise<void>
98
- /** A line in the plugin's log. */
99
- readonly log?: (level: "info" | "warn" | "error", message: string) => void
100
- }
101
-
102
- /**
103
- * The rules of a command, when the plugin knows nothing more about the session: a writer writes its own
104
- * directory, a reader nowhere, and the network reaches the registries and whatever was granted.
105
- */
106
- export function defaultRules(facts: SessionFacts & SessionExtra, input: ShellInput): Rules {
107
- const dir = facts.dir ?? input.cwd ?? process.cwd()
108
- return rulesFor({
109
- role: facts.role ?? "code",
110
- writer: facts.writer ?? true,
111
- dir,
112
- worktree: facts.worktree ?? dir,
113
- domains: facts.domains ?? [],
114
- frozen: facts.frozen ?? [],
115
- temp: facts.temp,
116
- })
117
- }
118
-
119
- /** The facts of a session: what its record says, plus what the plugin knows about it. */
120
- export async function factsOf(deps: ShellDeps, sessionID: string, cwd?: string): Promise<SessionFacts & SessionExtra> {
121
- const record = await deps.session(sessionID).catch(() => undefined)
122
- const extra = deps.extra?.(sessionID, cwd) ?? {}
123
- return { parentID: record?.parentID, ...extra }
124
- }
125
- /** The shell plugin's hooks, so a plugin that already has a tool hook can call note() from it. */
126
- export interface ShellHandle {
127
- /** Note a shell command of a child session, so the shell hook wraps it. */
128
- note(call: ShellCall): Promise<void>
129
- }
130
-
131
- /**
132
- * Install the shell plugin's wiring.
133
- *
134
- * The caller notes the commands of child sessions (handle.note); the shell hook wraps the commands it takes. A
135
- * command that no child session announced is left exactly as it is.
136
- *
137
- * The caller notes the commands itself, because a plugin that redacts a call before the shell sees it has to note
138
- * the redacted command, not the one the model wrote.
139
- */
140
- export async function installShell(ctx: any, deps: ShellDeps): Promise<ShellHandle> {
141
- const rules = deps.rules ?? defaultRules
142
-
143
- const note = async (call: ShellCall): Promise<void> => {
144
- if (!call.sessionID) return
145
- // A session the plugin knows as its own worker needs no host lookup; any other session is looked up, because the
146
- // host's record says whether it was delegated (a child) or is the user's own (a root session).
147
- const worker = deps.isWorker?.(call.sessionID)
148
- const record = worker ? undefined : await deps.session(call.sessionID).catch(() => undefined)
149
- const facts: SessionFacts = { parentID: record?.parentID, worker }
150
- if (!isChildShell(call, facts)) return
151
- const command = String((call as { input?: Record<string, unknown> }).input?.command ?? "")
152
- if (command) deps.shells.expect(command, call.sessionID)
153
- }
154
-
155
- await ctx.shell?.hook("create.before", async (input: ShellInput) => {
156
- if (!deps.shells.take(input.command)) return
157
- const cwd = String(input.cwd ?? "")
158
- const sessionID = deps.shells.sessionOf(input.command)
159
- const facts = sessionID ? await factsOf(deps, sessionID, cwd) : {}
160
- // A session the plugin knows as its own is judged by the plugin's own rule: the facts it has about it (and the
161
- // command's directory) decide. A session it does not know at all is a child of some other plugin: the generic
162
- // rule holds, a delegated child is wrapped. The user's own shell is a root session, and no rule wraps it.
163
- if (facts.known) {
164
- if (!facts.worker && !facts.dir) return
165
- } else if (!facts.parentID) {
166
- return
167
- }
168
- input.env = cleanEnv(input.env ?? process.env, [...(deps.env ?? []), ...(facts.env ?? [])])
169
- const box = await deps.sandbox()
170
- if (!box.available) return
171
- const temp = facts.temp ?? deps.temp?.(cwd)
172
- const own = { ...facts, temp }
173
- const wrapped = await box.wrap(withTemp(input.command, temp), rules(own, input))
174
- const seen = deps.unwrapped
175
- if (seen) {
176
- seen.set(wrapped, input.command)
177
- if (seen.size > 500) seen.delete(seen.keys().next().value!)
178
- }
179
- input.command = wrapped
180
- await deps.onWrap?.(own)
181
- })
182
-
183
- return { note }
184
- }