@omacode/sandbox 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # @omacode/sandbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Runs the shell commands of delegated child sessions in a sandbox, and leaves the user's own shell alone.
4
+
5
+ The sandbox is a standalone OpenCode plugin. It needs neither `micromanager` nor any other Omacode plugin.
6
+
7
+ ```bash
8
+ opencode plugin add @omacode/sandbox
9
+ ```
10
+
11
+ A child session is a session the host reports with a `parentID`; the plugin looks it up through `ctx.session.get`.
12
+ The decision is in `decide.ts`: a child's shell is wrapped, a root session's shell is not. The user's own commands are
13
+ never sandboxed.
14
+
15
+ When `micromanager` is installed too, it registers its workers with the sandbox service. That adds the facts the host
16
+ may not report: the worker's role, worktree, frozen files and grants. Without it the generic rule applies.
17
+
18
+ Filesystem and network rules come from `sandbox.ts`; the default is the package registries plus the project directory.
19
+ The sandbox is one per server, shared through a `globalThis` slot, so a tool hook from one plugin instance can note a
20
+ command that a shell hook from another instance wraps.
package/dist/decide.js ADDED
@@ -0,0 +1,35 @@
1
+ // Which shell commands belong to a child session and are therefore wrapped in the sandbox.
2
+ //
3
+ // The shell hook of OpenCode gets no session id (opencode 2.0.18: "create.before" gets { command, cwd, timeout,
4
+ // shell, env } only), so the shell plugin cannot ask "whose command is this?" there. It can only ask "was this
5
+ // command announced by a child session?" — the tool hook (execute.before) does know the session and notes the
6
+ // command before the shell is created. This module holds that decision, so it can be tested without a host.
7
+ //
8
+ // The invariant the decision exists for: a child shell of any plugin runs in the sandbox, and the user's own
9
+ // interactive shell never does. A root session (no parent) is the user's own; a delegated child (a parent) is not.
10
+ /** The shells the plugin wraps. OpenCode's shell tool is called "shell". */
11
+ export const SHELL_TOOL = "shell";
12
+ /**
13
+ * Whether this call is a shell command of a child session: one the sandbox wraps.
14
+ *
15
+ * A call counts when it is the shell tool and its session is a delegated child (it has a parent) or a known
16
+ * worker. A root session with no parent is the user's own interactive session, and its shell is left alone.
17
+ */
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);
26
+ }
27
+ /**
28
+ * Whether the session record says this session was delegated: a child session has a parent.
29
+ *
30
+ * The host drops the parent id for some sessions, so this is one signal among others and never the only one: a
31
+ * session the plugin knows as a worker is a worker even without a parent id.
32
+ */
33
+ export function isDelegated(facts) {
34
+ return Boolean(facts?.parentID) || Boolean(facts?.worker);
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,47 @@
1
1
  {
2
2
  "name": "@omacode/sandbox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Run delegated child sessions' shell commands in a sandbox",
7
+ "license": "Apache-2.0",
8
+ "author": "Tobias Rentschler <tobias-rentschler@gmx.de>",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/RentschlerTobias/Omacode.git",
12
+ "directory": "packages/sandbox"
13
+ },
14
+ "homepage": "https://github.com/RentschlerTobias/Omacode#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/RentschlerTobias/Omacode/issues"
17
+ },
18
+ "engines": {
19
+ "node": ">=22.18.0"
20
+ },
21
+ "keywords": [
22
+ "opencode",
23
+ "opencode-plugin",
24
+ "sandbox",
25
+ "bubblewrap",
26
+ "security"
27
+ ],
28
+ "scripts": {
29
+ "prepack": "node ../../scripts/pack-js.mjs",
30
+ "postpack": "node ../../scripts/pack-js.mjs --restore"
31
+ },
32
+ "exports": {
33
+ ".": "./dist/plugin.js",
34
+ "./wire": "./dist/wire.js",
35
+ "./decide": "./dist/decide.js",
36
+ "./sandbox": "./dist/sandbox.js"
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "dependencies": {
42
+ "@omacode/core": "1.0.0"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }