@omacode/sandbox 0.0.0-stage → 0.1.1

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/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": "0.1.1",
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.12.0"
20
+ },
21
+ "keywords": [
22
+ "opencode",
23
+ "opencode-plugin",
24
+ "sandbox",
25
+ "bubblewrap",
26
+ "security"
27
+ ],
28
+ "scripts": {
29
+ "prepack": "node ../../scripts/copy-license.mjs",
30
+ "postpack": "node ../../scripts/copy-license.mjs --remove"
31
+ },
32
+ "exports": {
33
+ ".": "./src/plugin.ts",
34
+ "./wire": "./src/wire.ts",
35
+ "./decide": "./src/decide.ts",
36
+ "./sandbox": "./src/sandbox.ts"
37
+ },
38
+ "files": [
39
+ "src"
40
+ ],
41
+ "dependencies": {
42
+ "@omacode/core": "0.1.1"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
package/src/decide.ts ADDED
@@ -0,0 +1,50 @@
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
+
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
+ /** The shells the plugin wraps. OpenCode's shell tool is called "shell". */
27
+ export const SHELL_TOOL = "shell"
28
+
29
+ /**
30
+ * Whether this call is a shell command of a child session: one the sandbox wraps.
31
+ *
32
+ * A call counts when it is the shell tool and its session is a delegated child (it has a parent) or a known
33
+ * worker. A root session with no parent is the user's own interactive session, and its shell is left alone.
34
+ */
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)
40
+ }
41
+
42
+ /**
43
+ * Whether the session record says this session was delegated: a child session has a parent.
44
+ *
45
+ * The host drops the parent id for some sessions, so this is one signal among others and never the only one: a
46
+ * session the plugin knows as a worker is a worker even without a parent id.
47
+ */
48
+ export function isDelegated(facts: SessionFacts | undefined): boolean {
49
+ return Boolean(facts?.parentID) || Boolean(facts?.worker)
50
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,75 @@
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 ADDED
@@ -0,0 +1,233 @@
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 ADDED
@@ -0,0 +1,184 @@
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
+ }