@agentproto/command-sandbox 0.2.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,191 @@
1
+ /**
2
+ * OS-level process confinement — macOS Seatbelt (`sandbox-exec`) and Linux
3
+ * bubblewrap (`bwrap`) backends for wrapping a spawned argv.
4
+ *
5
+ * Extracted from `@agentproto/runtime`'s original `command-tools.ts`-only
6
+ * use (which still consumes this package for `command_execute`) so
7
+ * `@agentproto/driver-agent-cli` can wrap its OWN adapter-child spawn
8
+ * (`define-agent-cli.ts` / `print-arm.ts`) through the identical policy and
9
+ * backends, without creating a circular package dependency — `runtime`
10
+ * depends on `driver-agent-cli` (it spawns adapter sessions), so
11
+ * `driver-agent-cli` cannot depend back on `runtime`. This package has zero
12
+ * workspace dependencies; both sides depend on it.
13
+ *
14
+ * The allowlist (`command-tools.ts` in `runtime`) gates WHICH binary may
15
+ * run; this bounds what that binary (or, for the adapter-spawn use, the
16
+ * agent-cli child itself) may READ/WRITE and — in strict mode — reach on
17
+ * the network. It closes the residual gap where an allowlisted interpreter
18
+ * (`bash`, `node`, `python3`, …) reads `~/.ssh/id_rsa` or exfiltrates: the
19
+ * cwd anchor bounds the working directory, not what the process opens.
20
+ *
21
+ * The Seatbelt profile was validated empirically (2026-07): under it `node`
22
+ * / `cat` read workspace files fine, `~/.ssh` reads fail with EPERM, and
23
+ * strict mode makes network connects fail with EPERM. Re-validated 2026-07-22
24
+ * against a REAL `npx`-spawned adapter child (`@agentclientprotocol/
25
+ * claude-agent-acp`, the actual `claude-code` AGENT-CLI.md bin): npm's
26
+ * arborist `lstat`s $HOME itself while resolving config and hard-fails with
27
+ * EPERM without a metadata-only re-allow across $HOME (see
28
+ * `buildSeatbeltProfile`) — content read/write and directory listing under
29
+ * $HOME stay denied; only stat/lstat-class metadata is re-opened.
30
+ *
31
+ * ## Two config keys, one file, deliberately not shared (PR 6b)
32
+ *
33
+ * `.agentproto/command-sandbox.json` governs TWO independent confinement
34
+ * axes that happen to live in the same file: the top-level `mode` (read by
35
+ * `loadSandboxConfig`) confines a single `command_execute` call; the nested
36
+ * `adapterSpawn` key (read by `loadAdapterSpawnSandboxConfig`) confines the
37
+ * ENTIRE adapter-spawn process tree for the life of a session. A workspace
38
+ * does NOT get `adapterSpawn` confinement for free by setting the top-level
39
+ * `mode` — it must set `adapterSpawn.mode` explicitly. This is deliberate,
40
+ * not an oversight: a misconfigured `command_execute` jail breaks one
41
+ * command's execution (the caller sees a failed tool call and can retry
42
+ * unconfined); a misconfigured adapter-spawn jail breaks the WHOLE session
43
+ * (every tool call, every turn, for as long as the adapter runs) — a
44
+ * strictly larger blast radius that deserves its own explicit opt-in rather
45
+ * than silently inheriting whatever `command_execute` happened to be
46
+ * configured with.
47
+ */
48
+ type SandboxMode = "off" | "workspace" | "strict";
49
+ /** Per-workspace config read from `.agentproto/command-sandbox.json`. */
50
+ interface CommandSandboxConfig {
51
+ /**
52
+ * - `off` — no confinement (default; today's behavior).
53
+ * - `workspace` — deny access to the home directory OUTSIDE the workspace
54
+ * (protects ~/.ssh, ~/.aws, credentials, …); system paths
55
+ * stay readable so interpreters still run. Network allowed.
56
+ * - `strict` — `workspace` + deny ALL network.
57
+ */
58
+ mode: SandboxMode;
59
+ /** Extra absolute paths to grant read access (e.g. a shared cache). */
60
+ extraReadPaths: string[];
61
+ /** Network policy. Forced to `deny` when `mode === "strict"`. */
62
+ network: "deny" | "allow";
63
+ }
64
+ /** Inputs the backend needs to build a confinement for one command. */
65
+ interface SandboxPolicy {
66
+ workspace: string;
67
+ extraReadPaths: string[];
68
+ /**
69
+ * Extra absolute paths to grant READ+WRITE access, outside the
70
+ * workspace — e.g. a toolchain's self-managed install directory
71
+ * (`~/Library/pnpm/.tools`) or a per-spawn scratch dir created before
72
+ * the wrap (`CLAUDE_CONFIG_DIR`'s mkdtemp'd settings dir). Unlike
73
+ * `extraReadPaths`, these are also writable. Defaults to `[]` when
74
+ * omitted by a caller built against the pre-`extraWritePaths` shape.
75
+ */
76
+ extraWritePaths?: string[];
77
+ network: "deny" | "allow";
78
+ }
79
+ interface CommandSandbox {
80
+ readonly id: string;
81
+ /**
82
+ * Wrap `argv` so the command runs confined, returning the new argv to spawn
83
+ * (e.g. `["sandbox-exec", "-p", <profile>, ...argv]`). Never throws —
84
+ * sandboxing is best-effort hardening, so an empty argv is returned as-is.
85
+ */
86
+ wrap(argv: string[], policy: SandboxPolicy): string[];
87
+ }
88
+ declare const DEFAULT_SANDBOX_CONFIG: CommandSandboxConfig;
89
+ /**
90
+ * Escape hatch: overrides the workspace config file's `mode` when set to a
91
+ * valid `SandboxMode`, without editing the tracked `.agentproto/
92
+ * command-sandbox.json`. Two directions this matters: forcing `off` when a
93
+ * workspace has opted into `workspace`/`strict` but one call legitimately
94
+ * needs broad access (e.g. a one-off `pnpm install`), or forcing `workspace`/
95
+ * `strict` on for a session/CI run without committing a config file. Any
96
+ * other value (unset, typo, empty) is ignored and the file/default applies.
97
+ */
98
+ declare const COMMAND_SANDBOX_MODE_ENV = "AGENTPROTO_COMMAND_SANDBOX_MODE";
99
+ /**
100
+ * Load + normalize the per-workspace sandbox config. Missing file, bad JSON, or
101
+ * an unknown mode all fall back to `off` (fail-open on config, not on
102
+ * confinement — a broken config must not silently pretend to sandbox; that's
103
+ * surfaced by the caller when a mode is set but no backend exists).
104
+ * `COMMAND_SANDBOX_MODE_ENV`, when set to a valid mode, overrides whatever the
105
+ * file (or the default) resolved to.
106
+ */
107
+ declare function loadSandboxConfig(workspace: string): Promise<CommandSandboxConfig>;
108
+ /**
109
+ * Confinement config for the ADAPTER-SPAWN axis — a distinct, explicit
110
+ * `adapterSpawn` key in the same `.agentproto/command-sandbox.json` file
111
+ * `loadSandboxConfig` reads (see the module doc for why this isn't just the
112
+ * top-level `mode`).
113
+ */
114
+ interface AdapterSpawnSandboxConfig {
115
+ /**
116
+ * `undefined` ⇒ the file has no `adapterSpawn` key at all (or no file
117
+ * exists) — this axis was never engaged by the workspace, so a caller
118
+ * that also passed no explicit mode stays silently unconfined (today's
119
+ * behavior). A resolved `SandboxMode`, INCLUDING explicit `"off"`, means
120
+ * the workspace (or `ADAPTER_COMMAND_SANDBOX_MODE_ENV`) engaged this axis
121
+ * on purpose.
122
+ */
123
+ mode: SandboxMode | undefined;
124
+ /** Extra read-only paths merged with the adapter-spawn wrapper's own
125
+ * built-in toolchain defaults (`defaultToolchainReadPaths()`). */
126
+ extraReadPaths: string[];
127
+ /** Extra read+write paths merged with the built-in toolchain defaults
128
+ * (`defaultToolchainWritePaths()`). */
129
+ extraWritePaths: string[];
130
+ /** Network policy. Forced to `deny` when `mode === "strict"`. */
131
+ network: "deny" | "allow";
132
+ }
133
+ /**
134
+ * Escape hatch for the adapter-spawn axis, mirroring `COMMAND_SANDBOX_MODE_ENV`
135
+ * but kept as a SEPARATE env var rather than reusing it — forcing
136
+ * `command_execute` into `workspace` mode for a CI run should not, as a side
137
+ * effect, also confine every adapter's own process tree (and vice versa).
138
+ */
139
+ declare const ADAPTER_COMMAND_SANDBOX_MODE_ENV = "AGENTPROTO_ADAPTER_COMMAND_SANDBOX_MODE";
140
+ /**
141
+ * Load + normalize the adapter-spawn confinement config from the `adapterSpawn`
142
+ * key of `.agentproto/command-sandbox.json`. Missing file / bad JSON / no
143
+ * `adapterSpawn` key ⇒ `mode: undefined` (axis untouched, NOT `"off"` — see
144
+ * `AdapterSpawnSandboxConfig.mode`'s doc for why that distinction matters).
145
+ * An `adapterSpawn` key that IS present but carries an unknown/missing `mode`
146
+ * resolves to `"off"`, matching `loadSandboxConfig`'s fail-open-on-config
147
+ * posture. `ADAPTER_COMMAND_SANDBOX_MODE_ENV`, when set to a valid mode,
148
+ * overrides whatever the file resolved to.
149
+ */
150
+ declare function loadAdapterSpawnSandboxConfig(workspace: string): Promise<AdapterSpawnSandboxConfig>;
151
+ /**
152
+ * Build a macOS Seatbelt (SBPL) profile for the policy. Strategy: start
153
+ * permissive (`allow default`) so interpreters can read their runtime + system
154
+ * libraries, then DENY the whole home directory (the crown jewels — ~/.ssh,
155
+ * ~/.aws, credentials), then RE-ALLOW the workspace subpath, any explicit
156
+ * extra read paths (read-only), and any explicit extra write paths
157
+ * (read+write — e.g. a toolchain's self-managed install dir living under
158
+ * `$HOME`, which a read-only re-allow can't satisfy). SBPL is
159
+ * last-match-wins, so the workspace/extra re-allows override the home deny.
160
+ * Strict mode also denies all network. Exported for testing.
161
+ */
162
+ declare function buildSeatbeltProfile(policy: SandboxPolicy): string;
163
+ /** macOS Seatbelt backend — wraps argv as `sandbox-exec -p <profile> …`. */
164
+ declare const seatbeltSandbox: CommandSandbox;
165
+ /**
166
+ * Build the bubblewrap argv (everything after `bwrap`). Unlike Seatbelt's
167
+ * "deny home except workspace", bwrap is allowlist-by-construction: ONLY the
168
+ * paths bound here are visible, so `$HOME` secrets (~/.ssh, credentials) are
169
+ * simply absent from the mount namespace. System dirs are read-only, the
170
+ * workspace + extra reads are bound read-only, extra writes are bound
171
+ * read-write (`--bind-try`, not `--ro-bind-try` — e.g. a toolchain's
172
+ * self-managed install dir, or a per-spawn scratch dir that may not exist yet
173
+ * when the argv is built), and strict mode adds `--unshare-net` for an
174
+ * isolated (no-connectivity) network namespace. Exported for testing.
175
+ *
176
+ * Empirically validated (2026-07, ubuntu container): workspace reads succeed,
177
+ * `~/.ssh` reads fail (invisible), and `--unshare-net` makes connects fail with
178
+ * ENETUNREACH.
179
+ */
180
+ declare function buildBwrapArgs(argv: string[], policy: SandboxPolicy): string[];
181
+ /** Linux bubblewrap backend — wraps argv as `bwrap <binds> -- …`. */
182
+ declare const bwrapSandbox: CommandSandbox;
183
+ /**
184
+ * The confinement backend available on this host, or `null` when none applies
185
+ * (macOS → Seatbelt, Linux → bubblewrap when installed, Windows unsupported).
186
+ * Callers warn when a sandbox mode is configured but this returns null — so a
187
+ * missing backend never silently pretends to confine.
188
+ */
189
+ declare function resolveCommandSandbox(): CommandSandbox | null;
190
+
191
+ export { ADAPTER_COMMAND_SANDBOX_MODE_ENV, type AdapterSpawnSandboxConfig, COMMAND_SANDBOX_MODE_ENV, type CommandSandbox, type CommandSandboxConfig, DEFAULT_SANDBOX_CONFIG, type SandboxMode, type SandboxPolicy, buildBwrapArgs, buildSeatbeltProfile, bwrapSandbox, loadAdapterSpawnSandboxConfig, loadSandboxConfig, resolveCommandSandbox, seatbeltSandbox };
package/dist/index.mjs ADDED
@@ -0,0 +1,175 @@
1
+ import { existsSync } from 'fs';
2
+ import { readFile } from 'fs/promises';
3
+ import { homedir } from 'os';
4
+ import { resolve } from 'path';
5
+
6
+ /**
7
+ * @agentproto/command-sandbox v0.1.0
8
+ * OS-level process confinement (Seatbelt / bubblewrap) for a spawned argv.
9
+ */
10
+
11
+ var CONFIG_REL = ".agentproto/command-sandbox.json";
12
+ var DEFAULT_SANDBOX_CONFIG = {
13
+ mode: "off",
14
+ extraReadPaths: [],
15
+ network: "allow"
16
+ };
17
+ var COMMAND_SANDBOX_MODE_ENV = "AGENTPROTO_COMMAND_SANDBOX_MODE";
18
+ async function loadSandboxConfig(workspace) {
19
+ const path = resolve(workspace, CONFIG_REL);
20
+ let resolved = DEFAULT_SANDBOX_CONFIG;
21
+ if (existsSync(path)) {
22
+ try {
23
+ const parsed = JSON.parse(
24
+ await readFile(path, "utf8")
25
+ );
26
+ const mode = parsed.mode === "workspace" || parsed.mode === "strict" ? parsed.mode : "off";
27
+ const extraReadPaths = Array.isArray(parsed.extraReadPaths) ? parsed.extraReadPaths.filter((x) => typeof x === "string") : [];
28
+ const network = mode === "strict" || parsed.network === "deny" ? "deny" : "allow";
29
+ resolved = { mode, extraReadPaths, network };
30
+ } catch {
31
+ resolved = DEFAULT_SANDBOX_CONFIG;
32
+ }
33
+ }
34
+ const envMode = process.env[COMMAND_SANDBOX_MODE_ENV];
35
+ if (envMode === "off" || envMode === "workspace" || envMode === "strict") {
36
+ return {
37
+ ...resolved,
38
+ mode: envMode,
39
+ network: envMode === "strict" ? "deny" : resolved.network
40
+ };
41
+ }
42
+ return resolved;
43
+ }
44
+ var DEFAULT_ADAPTER_SPAWN_SANDBOX_CONFIG = {
45
+ mode: void 0,
46
+ extraReadPaths: [],
47
+ extraWritePaths: [],
48
+ network: "allow"
49
+ };
50
+ var ADAPTER_COMMAND_SANDBOX_MODE_ENV = "AGENTPROTO_ADAPTER_COMMAND_SANDBOX_MODE";
51
+ async function loadAdapterSpawnSandboxConfig(workspace) {
52
+ const path = resolve(workspace, CONFIG_REL);
53
+ let resolved = DEFAULT_ADAPTER_SPAWN_SANDBOX_CONFIG;
54
+ if (existsSync(path)) {
55
+ try {
56
+ const parsed = JSON.parse(await readFile(path, "utf8"));
57
+ const raw = parsed.adapterSpawn;
58
+ if (raw && typeof raw === "object") {
59
+ const mode = raw.mode === "workspace" || raw.mode === "strict" || raw.mode === "off" ? raw.mode : "off";
60
+ const extraReadPaths = Array.isArray(raw.extraReadPaths) ? raw.extraReadPaths.filter((x) => typeof x === "string") : [];
61
+ const extraWritePaths = Array.isArray(raw.extraWritePaths) ? raw.extraWritePaths.filter((x) => typeof x === "string") : [];
62
+ const network = mode === "strict" || raw.network === "deny" ? "deny" : "allow";
63
+ resolved = { mode, extraReadPaths, extraWritePaths, network };
64
+ }
65
+ } catch {
66
+ resolved = DEFAULT_ADAPTER_SPAWN_SANDBOX_CONFIG;
67
+ }
68
+ }
69
+ const envMode = process.env[ADAPTER_COMMAND_SANDBOX_MODE_ENV];
70
+ if (envMode === "off" || envMode === "workspace" || envMode === "strict") {
71
+ return {
72
+ ...resolved,
73
+ mode: envMode,
74
+ network: envMode === "strict" ? "deny" : resolved.network
75
+ };
76
+ }
77
+ return resolved;
78
+ }
79
+ function sbplQuote(p) {
80
+ return p.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
81
+ }
82
+ function buildSeatbeltProfile(policy) {
83
+ const home = homedir();
84
+ const ws = resolve(policy.workspace);
85
+ const parts = [
86
+ "(version 1)",
87
+ "(allow default)",
88
+ `(deny file-read* file-write* (subpath "${sbplQuote(home)}"))`,
89
+ // Metadata-only re-allow across all of $HOME (stat/lstat — existence,
90
+ // permissions, mtime; NOT directory listing or file content, both of
91
+ // which need file-read-data and stay denied). Empirically required
92
+ // (2026-07): npm/npx's arborist `lstat`s ancestor directories while
93
+ // resolving config/paths and hard-fails with EPERM on $HOME itself
94
+ // otherwise — even for a workspace-cwd invocation that never reads
95
+ // any OTHER file under $HOME. Without this, no npx-spawned adapter
96
+ // (claude-agent-acp included) can even start under `workspace` mode.
97
+ `(allow file-read-metadata (subpath "${sbplQuote(home)}"))`,
98
+ `(allow file-read* file-write* (subpath "${sbplQuote(ws)}"))`
99
+ ];
100
+ for (const extra of policy.extraReadPaths) {
101
+ parts.push(`(allow file-read* (subpath "${sbplQuote(resolve(extra))}"))`);
102
+ }
103
+ for (const extra of policy.extraWritePaths ?? []) {
104
+ parts.push(
105
+ `(allow file-read* file-write* (subpath "${sbplQuote(resolve(extra))}"))`
106
+ );
107
+ }
108
+ if (policy.network === "deny") parts.push("(deny network*)");
109
+ return parts.join("");
110
+ }
111
+ var seatbeltSandbox = {
112
+ id: "seatbelt",
113
+ wrap(argv, policy) {
114
+ if (argv.length === 0) return argv;
115
+ return ["sandbox-exec", "-p", buildSeatbeltProfile(policy), ...argv];
116
+ }
117
+ };
118
+ var BWRAP_SYSTEM_DIRS = [
119
+ "/usr",
120
+ "/usr/local",
121
+ "/bin",
122
+ "/sbin",
123
+ "/lib",
124
+ "/lib64",
125
+ "/etc",
126
+ "/opt"
127
+ ];
128
+ function buildBwrapArgs(argv, policy) {
129
+ const ws = resolve(policy.workspace);
130
+ const out = [
131
+ "--die-with-parent",
132
+ "--proc",
133
+ "/proc",
134
+ "--dev",
135
+ "/dev",
136
+ "--tmpfs",
137
+ "/tmp"
138
+ ];
139
+ for (const d of BWRAP_SYSTEM_DIRS) out.push("--ro-bind-try", d, d);
140
+ out.push("--bind", ws, ws);
141
+ for (const extra of policy.extraReadPaths) {
142
+ const p = resolve(extra);
143
+ out.push("--ro-bind-try", p, p);
144
+ }
145
+ for (const extra of policy.extraWritePaths ?? []) {
146
+ const p = resolve(extra);
147
+ out.push("--bind-try", p, p);
148
+ }
149
+ if (policy.network === "deny") out.push("--unshare-net");
150
+ out.push("--", ...argv);
151
+ return out;
152
+ }
153
+ var bwrapSandbox = {
154
+ id: "bwrap",
155
+ wrap(argv, policy) {
156
+ if (argv.length === 0) return argv;
157
+ return ["bwrap", ...buildBwrapArgs(argv, policy)];
158
+ }
159
+ };
160
+ function bwrapAvailable() {
161
+ return existsSync("/usr/bin/bwrap") || existsSync("/bin/bwrap") || existsSync("/usr/local/bin/bwrap");
162
+ }
163
+ function resolveCommandSandbox() {
164
+ if (process.platform === "darwin" && existsSync("/usr/bin/sandbox-exec")) {
165
+ return seatbeltSandbox;
166
+ }
167
+ if (process.platform === "linux" && bwrapAvailable()) {
168
+ return bwrapSandbox;
169
+ }
170
+ return null;
171
+ }
172
+
173
+ export { ADAPTER_COMMAND_SANDBOX_MODE_ENV, COMMAND_SANDBOX_MODE_ENV, DEFAULT_SANDBOX_CONFIG, buildBwrapArgs, buildSeatbeltProfile, bwrapSandbox, loadAdapterSpawnSandboxConfig, loadSandboxConfig, resolveCommandSandbox, seatbeltSandbox };
174
+ //# sourceMappingURL=index.mjs.map
175
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;AAiGA,IAAM,UAAA,GAAa,kCAAA;AAEZ,IAAM,sBAAA,GAA+C;AAAA,EAC1D,IAAA,EAAM,KAAA;AAAA,EACN,gBAAgB,EAAC;AAAA,EACjB,OAAA,EAAS;AACX;AAWO,IAAM,wBAAA,GAA2B;AAUxC,eAAsB,kBACpB,SAAA,EAC+B;AAC/B,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,SA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S Seatbelt (`sandbox-exec`) and Linux\n * bubblewrap (`bwrap`) backends for wrapping a spawned argv.\n *\n * Extracted from `@agentproto/runtime`'s original `command-tools.ts`-only\n * use (which still consumes this package for `command_execute`) so\n * `@agentproto/driver-agent-cli` can wrap its OWN adapter-child spawn\n * (`define-agent-cli.ts` / `print-arm.ts`) through the identical policy and\n * backends, without creating a circular package dependency — `runtime`\n * depends on `driver-agent-cli` (it spawns adapter sessions), so\n * `driver-agent-cli` cannot depend back on `runtime`. This package has zero\n * workspace dependencies; both sides depend on it.\n *\n * The allowlist (`command-tools.ts` in `runtime`) gates WHICH binary may\n * run; this bounds what that binary (or, for the adapter-spawn use, the\n * agent-cli child itself) may READ/WRITE and — in strict mode — reach on\n * the network. It closes the residual gap where an allowlisted interpreter\n * (`bash`, `node`, `python3`, …) reads `~/.ssh/id_rsa` or exfiltrates: the\n * cwd anchor bounds the working directory, not what the process opens.\n *\n * The Seatbelt profile was validated empirically (2026-07): under it `node`\n * / `cat` read workspace files fine, `~/.ssh` reads fail with EPERM, and\n * strict mode makes network connects fail with EPERM. Re-validated 2026-07-22\n * against a REAL `npx`-spawned adapter child (`@agentclientprotocol/\n * claude-agent-acp`, the actual `claude-code` AGENT-CLI.md bin): npm's\n * arborist `lstat`s $HOME itself while resolving config and hard-fails with\n * EPERM without a metadata-only re-allow across $HOME (see\n * `buildSeatbeltProfile`) — content read/write and directory listing under\n * $HOME stay denied; only stat/lstat-class metadata is re-opened.\n *\n * ## Two config keys, one file, deliberately not shared (PR 6b)\n *\n * `.agentproto/command-sandbox.json` governs TWO independent confinement\n * axes that happen to live in the same file: the top-level `mode` (read by\n * `loadSandboxConfig`) confines a single `command_execute` call; the nested\n * `adapterSpawn` key (read by `loadAdapterSpawnSandboxConfig`) confines the\n * ENTIRE adapter-spawn process tree for the life of a session. A workspace\n * does NOT get `adapterSpawn` confinement for free by setting the top-level\n * `mode` — it must set `adapterSpawn.mode` explicitly. This is deliberate,\n * not an oversight: a misconfigured `command_execute` jail breaks one\n * command's execution (the caller sees a failed tool call and can retry\n * unconfined); a misconfigured adapter-spawn jail breaks the WHOLE session\n * (every tool call, every turn, for as long as the adapter runs) — a\n * strictly larger blast radius that deserves its own explicit opt-in rather\n * than silently inheriting whatever `command_execute` happened to be\n * configured with.\n */\n\nimport { existsSync } from \"node:fs\"\nimport { readFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { resolve } from \"node:path\"\n\nexport type SandboxMode = \"off\" | \"workspace\" | \"strict\"\n\n/** Per-workspace config read from `.agentproto/command-sandbox.json`. */\nexport interface CommandSandboxConfig {\n /**\n * - `off` — no confinement (default; today's behavior).\n * - `workspace` — deny access to the home directory OUTSIDE the workspace\n * (protects ~/.ssh, ~/.aws, credentials, …); system paths\n * stay readable so interpreters still run. Network allowed.\n * - `strict` — `workspace` + deny ALL network.\n */\n mode: SandboxMode\n /** Extra absolute paths to grant read access (e.g. a shared cache). */\n extraReadPaths: string[]\n /** Network policy. Forced to `deny` when `mode === \"strict\"`. */\n network: \"deny\" | \"allow\"\n}\n\n/** Inputs the backend needs to build a confinement for one command. */\nexport interface SandboxPolicy {\n workspace: string\n extraReadPaths: string[]\n /**\n * Extra absolute paths to grant READ+WRITE access, outside the\n * workspace — e.g. a toolchain's self-managed install directory\n * (`~/Library/pnpm/.tools`) or a per-spawn scratch dir created before\n * the wrap (`CLAUDE_CONFIG_DIR`'s mkdtemp'd settings dir). Unlike\n * `extraReadPaths`, these are also writable. Defaults to `[]` when\n * omitted by a caller built against the pre-`extraWritePaths` shape.\n */\n extraWritePaths?: string[]\n network: \"deny\" | \"allow\"\n}\n\nexport interface CommandSandbox {\n readonly id: string\n /**\n * Wrap `argv` so the command runs confined, returning the new argv to spawn\n * (e.g. `[\"sandbox-exec\", \"-p\", <profile>, ...argv]`). Never throws —\n * sandboxing is best-effort hardening, so an empty argv is returned as-is.\n */\n wrap(argv: string[], policy: SandboxPolicy): string[]\n}\n\nconst CONFIG_REL = \".agentproto/command-sandbox.json\"\n\nexport const DEFAULT_SANDBOX_CONFIG: CommandSandboxConfig = {\n mode: \"off\",\n extraReadPaths: [],\n network: \"allow\",\n}\n\n/**\n * Escape hatch: overrides the workspace config file's `mode` when set to a\n * valid `SandboxMode`, without editing the tracked `.agentproto/\n * command-sandbox.json`. Two directions this matters: forcing `off` when a\n * workspace has opted into `workspace`/`strict` but one call legitimately\n * needs broad access (e.g. a one-off `pnpm install`), or forcing `workspace`/\n * `strict` on for a session/CI run without committing a config file. Any\n * other value (unset, typo, empty) is ignored and the file/default applies.\n */\nexport const COMMAND_SANDBOX_MODE_ENV = \"AGENTPROTO_COMMAND_SANDBOX_MODE\"\n\n/**\n * Load + normalize the per-workspace sandbox config. Missing file, bad JSON, or\n * an unknown mode all fall back to `off` (fail-open on config, not on\n * confinement — a broken config must not silently pretend to sandbox; that's\n * surfaced by the caller when a mode is set but no backend exists).\n * `COMMAND_SANDBOX_MODE_ENV`, when set to a valid mode, overrides whatever the\n * file (or the default) resolved to.\n */\nexport async function loadSandboxConfig(\n workspace: string,\n): Promise<CommandSandboxConfig> {\n const path = resolve(workspace, CONFIG_REL)\n let resolved = DEFAULT_SANDBOX_CONFIG\n if (existsSync(path)) {\n try {\n const parsed = JSON.parse(\n await readFile(path, \"utf8\"),\n ) as Partial<CommandSandboxConfig>\n const mode: SandboxMode =\n parsed.mode === \"workspace\" || parsed.mode === \"strict\"\n ? parsed.mode\n : \"off\"\n const extraReadPaths = Array.isArray(parsed.extraReadPaths)\n ? parsed.extraReadPaths.filter((x): x is string => typeof x === \"string\")\n : []\n // strict implies network deny; workspace honors the field (default allow).\n const network: \"deny\" | \"allow\" =\n mode === \"strict\" || parsed.network === \"deny\" ? \"deny\" : \"allow\"\n resolved = { mode, extraReadPaths, network }\n } catch {\n resolved = DEFAULT_SANDBOX_CONFIG\n }\n }\n const envMode = process.env[COMMAND_SANDBOX_MODE_ENV]\n if (envMode === \"off\" || envMode === \"workspace\" || envMode === \"strict\") {\n return {\n ...resolved,\n mode: envMode,\n network: envMode === \"strict\" ? \"deny\" : resolved.network,\n }\n }\n return resolved\n}\n\n/**\n * Confinement config for the ADAPTER-SPAWN axis — a distinct, explicit\n * `adapterSpawn` key in the same `.agentproto/command-sandbox.json` file\n * `loadSandboxConfig` reads (see the module doc for why this isn't just the\n * top-level `mode`).\n */\nexport interface AdapterSpawnSandboxConfig {\n /**\n * `undefined` ⇒ the file has no `adapterSpawn` key at all (or no file\n * exists) — this axis was never engaged by the workspace, so a caller\n * that also passed no explicit mode stays silently unconfined (today's\n * behavior). A resolved `SandboxMode`, INCLUDING explicit `\"off\"`, means\n * the workspace (or `ADAPTER_COMMAND_SANDBOX_MODE_ENV`) engaged this axis\n * on purpose.\n */\n mode: SandboxMode | undefined\n /** Extra read-only paths merged with the adapter-spawn wrapper's own\n * built-in toolchain defaults (`defaultToolchainReadPaths()`). */\n extraReadPaths: string[]\n /** Extra read+write paths merged with the built-in toolchain defaults\n * (`defaultToolchainWritePaths()`). */\n extraWritePaths: string[]\n /** Network policy. Forced to `deny` when `mode === \"strict\"`. */\n network: \"deny\" | \"allow\"\n}\n\nconst DEFAULT_ADAPTER_SPAWN_SANDBOX_CONFIG: AdapterSpawnSandboxConfig = {\n mode: undefined,\n extraReadPaths: [],\n extraWritePaths: [],\n network: \"allow\",\n}\n\n/**\n * Escape hatch for the adapter-spawn axis, mirroring `COMMAND_SANDBOX_MODE_ENV`\n * but kept as a SEPARATE env var rather than reusing it — forcing\n * `command_execute` into `workspace` mode for a CI run should not, as a side\n * effect, also confine every adapter's own process tree (and vice versa).\n */\nexport const ADAPTER_COMMAND_SANDBOX_MODE_ENV =\n \"AGENTPROTO_ADAPTER_COMMAND_SANDBOX_MODE\"\n\n/**\n * Load + normalize the adapter-spawn confinement config from the `adapterSpawn`\n * key of `.agentproto/command-sandbox.json`. Missing file / bad JSON / no\n * `adapterSpawn` key ⇒ `mode: undefined` (axis untouched, NOT `\"off\"` — see\n * `AdapterSpawnSandboxConfig.mode`'s doc for why that distinction matters).\n * An `adapterSpawn` key that IS present but carries an unknown/missing `mode`\n * resolves to `\"off\"`, matching `loadSandboxConfig`'s fail-open-on-config\n * posture. `ADAPTER_COMMAND_SANDBOX_MODE_ENV`, when set to a valid mode,\n * overrides whatever the file resolved to.\n */\nexport async function loadAdapterSpawnSandboxConfig(\n workspace: string,\n): Promise<AdapterSpawnSandboxConfig> {\n const path = resolve(workspace, CONFIG_REL)\n let resolved = DEFAULT_ADAPTER_SPAWN_SANDBOX_CONFIG\n if (existsSync(path)) {\n try {\n const parsed = JSON.parse(await readFile(path, \"utf8\")) as {\n adapterSpawn?: Record<string, unknown>\n }\n const raw = parsed.adapterSpawn\n if (raw && typeof raw === \"object\") {\n const mode: SandboxMode =\n raw.mode === \"workspace\" || raw.mode === \"strict\" || raw.mode === \"off\"\n ? raw.mode\n : \"off\"\n const extraReadPaths = Array.isArray(raw.extraReadPaths)\n ? raw.extraReadPaths.filter((x): x is string => typeof x === \"string\")\n : []\n const extraWritePaths = Array.isArray(raw.extraWritePaths)\n ? raw.extraWritePaths.filter((x): x is string => typeof x === \"string\")\n : []\n const network: \"deny\" | \"allow\" =\n mode === \"strict\" || raw.network === \"deny\" ? \"deny\" : \"allow\"\n resolved = { mode, extraReadPaths, extraWritePaths, network }\n }\n } catch {\n resolved = DEFAULT_ADAPTER_SPAWN_SANDBOX_CONFIG\n }\n }\n const envMode = process.env[ADAPTER_COMMAND_SANDBOX_MODE_ENV]\n if (envMode === \"off\" || envMode === \"workspace\" || envMode === \"strict\") {\n return {\n ...resolved,\n mode: envMode,\n network: envMode === \"strict\" ? \"deny\" : resolved.network,\n }\n }\n return resolved\n}\n\n/** Escape a path for embedding in an SBPL string literal. */\nfunction sbplQuote(p: string): string {\n return p.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')\n}\n\n/**\n * Build a macOS Seatbelt (SBPL) profile for the policy. Strategy: start\n * permissive (`allow default`) so interpreters can read their runtime + system\n * libraries, then DENY the whole home directory (the crown jewels — ~/.ssh,\n * ~/.aws, credentials), then RE-ALLOW the workspace subpath, any explicit\n * extra read paths (read-only), and any explicit extra write paths\n * (read+write — e.g. a toolchain's self-managed install dir living under\n * `$HOME`, which a read-only re-allow can't satisfy). SBPL is\n * last-match-wins, so the workspace/extra re-allows override the home deny.\n * Strict mode also denies all network. Exported for testing.\n */\nexport function buildSeatbeltProfile(policy: SandboxPolicy): string {\n const home = homedir()\n const ws = resolve(policy.workspace)\n const parts = [\n \"(version 1)\",\n \"(allow default)\",\n `(deny file-read* file-write* (subpath \"${sbplQuote(home)}\"))`,\n // Metadata-only re-allow across all of $HOME (stat/lstat — existence,\n // permissions, mtime; NOT directory listing or file content, both of\n // which need file-read-data and stay denied). Empirically required\n // (2026-07): npm/npx's arborist `lstat`s ancestor directories while\n // resolving config/paths and hard-fails with EPERM on $HOME itself\n // otherwise — even for a workspace-cwd invocation that never reads\n // any OTHER file under $HOME. Without this, no npx-spawned adapter\n // (claude-agent-acp included) can even start under `workspace` mode.\n `(allow file-read-metadata (subpath \"${sbplQuote(home)}\"))`,\n `(allow file-read* file-write* (subpath \"${sbplQuote(ws)}\"))`,\n ]\n for (const extra of policy.extraReadPaths) {\n parts.push(`(allow file-read* (subpath \"${sbplQuote(resolve(extra))}\"))`)\n }\n for (const extra of policy.extraWritePaths ?? []) {\n parts.push(\n `(allow file-read* file-write* (subpath \"${sbplQuote(resolve(extra))}\"))`,\n )\n }\n if (policy.network === \"deny\") parts.push(\"(deny network*)\")\n return parts.join(\"\")\n}\n\n/** macOS Seatbelt backend — wraps argv as `sandbox-exec -p <profile> …`. */\nexport const seatbeltSandbox: CommandSandbox = {\n id: \"seatbelt\",\n wrap(argv, policy) {\n if (argv.length === 0) return argv\n return [\"sandbox-exec\", \"-p\", buildSeatbeltProfile(policy), ...argv]\n },\n}\n\n/** Read-only system directories bubblewrap binds so interpreters find their\n * binaries + shared libraries. `--ro-bind-try` skips any that don't exist on\n * the distro (e.g. no `/lib64` on some), so the same list is portable. */\nconst BWRAP_SYSTEM_DIRS: readonly string[] = [\n \"/usr\",\n \"/usr/local\",\n \"/bin\",\n \"/sbin\",\n \"/lib\",\n \"/lib64\",\n \"/etc\",\n \"/opt\",\n]\n\n/**\n * Build the bubblewrap argv (everything after `bwrap`). Unlike Seatbelt's\n * \"deny home except workspace\", bwrap is allowlist-by-construction: ONLY the\n * paths bound here are visible, so `$HOME` secrets (~/.ssh, credentials) are\n * simply absent from the mount namespace. System dirs are read-only, the\n * workspace + extra reads are bound read-only, extra writes are bound\n * read-write (`--bind-try`, not `--ro-bind-try` — e.g. a toolchain's\n * self-managed install dir, or a per-spawn scratch dir that may not exist yet\n * when the argv is built), and strict mode adds `--unshare-net` for an\n * isolated (no-connectivity) network namespace. Exported for testing.\n *\n * Empirically validated (2026-07, ubuntu container): workspace reads succeed,\n * `~/.ssh` reads fail (invisible), and `--unshare-net` makes connects fail with\n * ENETUNREACH.\n */\nexport function buildBwrapArgs(argv: string[], policy: SandboxPolicy): string[] {\n const ws = resolve(policy.workspace)\n const out: string[] = [\n \"--die-with-parent\",\n \"--proc\",\n \"/proc\",\n \"--dev\",\n \"/dev\",\n \"--tmpfs\",\n \"/tmp\",\n ]\n for (const d of BWRAP_SYSTEM_DIRS) out.push(\"--ro-bind-try\", d, d)\n out.push(\"--bind\", ws, ws)\n for (const extra of policy.extraReadPaths) {\n const p = resolve(extra)\n out.push(\"--ro-bind-try\", p, p)\n }\n for (const extra of policy.extraWritePaths ?? []) {\n const p = resolve(extra)\n out.push(\"--bind-try\", p, p)\n }\n if (policy.network === \"deny\") out.push(\"--unshare-net\")\n out.push(\"--\", ...argv)\n return out\n}\n\n/** Linux bubblewrap backend — wraps argv as `bwrap <binds> -- …`. */\nexport const bwrapSandbox: CommandSandbox = {\n id: \"bwrap\",\n wrap(argv, policy) {\n if (argv.length === 0) return argv\n return [\"bwrap\", ...buildBwrapArgs(argv, policy)]\n },\n}\n\n/** Absolute path to a `bwrap` binary, or null when bubblewrap isn't installed. */\nfunction bwrapAvailable(): boolean {\n return (\n existsSync(\"/usr/bin/bwrap\") ||\n existsSync(\"/bin/bwrap\") ||\n existsSync(\"/usr/local/bin/bwrap\")\n )\n}\n\n/**\n * The confinement backend available on this host, or `null` when none applies\n * (macOS → Seatbelt, Linux → bubblewrap when installed, Windows unsupported).\n * Callers warn when a sandbox mode is configured but this returns null — so a\n * missing backend never silently pretends to confine.\n */\nexport function resolveCommandSandbox(): CommandSandbox | null {\n if (process.platform === \"darwin\" && existsSync(\"/usr/bin/sandbox-exec\")) {\n return seatbeltSandbox\n }\n if (process.platform === \"linux\" && bwrapAvailable()) {\n return bwrapSandbox\n }\n return null\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@agentproto/command-sandbox",
3
+ "version": "0.2.0",
4
+ "description": "@agentproto/command-sandbox — OS-level process confinement (macOS Seatbelt / Linux bubblewrap) for a spawned argv. Extracted so both @agentproto/runtime's command_execute tool and @agentproto/driver-agent-cli's adapter-spawn can wrap a child process through the same policy/backends without a circular package dependency.",
5
+ "keywords": [
6
+ "agentproto",
7
+ "sandbox",
8
+ "seatbelt",
9
+ "bubblewrap",
10
+ "confinement",
11
+ "open-standard",
12
+ "agentic"
13
+ ],
14
+ "homepage": "https://agentproto.sh",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/agentproto/ts",
18
+ "directory": "packages/command-sandbox"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/agentproto/ts/issues"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "type": "module",
25
+ "main": "dist/index.mjs",
26
+ "module": "dist/index.mjs",
27
+ "types": "dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.mjs",
32
+ "default": "./dist/index.mjs"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^25.6.2",
46
+ "tsup": "^8.5.1",
47
+ "typescript": "^5.9.3",
48
+ "vitest": "^3.2.4",
49
+ "@agentproto/tooling": "0.1.0-alpha.0"
50
+ },
51
+ "scripts": {
52
+ "dev": "tsup --watch",
53
+ "build": "tsup",
54
+ "clean": "rm -rf dist",
55
+ "check-types": "tsc --noEmit",
56
+ "test": "vitest run",
57
+ "test:watch": "vitest"
58
+ }
59
+ }