@stixxert/pi-docker-sandbox 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,271 @@
1
+ # docker-sandbox-extension
2
+
3
+ A [pi](https://pi.dev) extension that gives an AI coding agent a **private
4
+ docker sandbox** to deploy into — powered by
5
+ [Docker Sandboxes](https://docs.docker.com/ai/sandboxes/) (`sbx`).
6
+
7
+ Each pi session gets its own **sandbox microVM with its own docker daemon**,
8
+ running in parallel to the agent. The agent can pull images, build, run
9
+ containers, and `docker compose up` — while the **host's docker is never
10
+ exposed to it**.
11
+
12
+ ## Why
13
+
14
+ Agents that can deploy are powerful; agents that can reach your real docker
15
+ daemon are a liability. With this extension:
16
+
17
+ - Every docker operation happens inside a disposable microVM with its own
18
+ daemon — nothing appears in the host's `docker ps`.
19
+ - The extension **never touches a host docker socket or CLI**; it only shells
20
+ out to `sbx exec`. There is no fallback path to the host daemon.
21
+ - Docker env vars (`DOCKER_HOST`, `DOCKER_CONTEXT`, …) are scrubbed and the
22
+ inner CLI is pinned to the sandbox daemon, so leaked host config cannot
23
+ redirect it.
24
+ - `docker_verify` runs a live isolation audit (PASS/FAIL per check).
25
+
26
+ ## Requirements
27
+
28
+ - [pi](https://pi.dev) (the extension runs in the host pi process)
29
+ - The Docker Sandboxes CLI (`sbx`) — a standalone binary; **no Docker Desktop
30
+ required**
31
+ - A host hypervisor for `sbx` to boot microVMs on. The sandbox is a real VM
32
+ with its own kernel, so the virtualization backend is platform-specific:
33
+ - **macOS 14 (Sonoma)+ on Apple silicon** — uses Apple's Virtualization
34
+ framework (Intel Macs are not supported by `sbx`)
35
+ - **Linux x86_64 with KVM** — needs hardware virtualization and your user
36
+ in the `kvm` group (`lsmod | grep kvm` should list `kvm_intel` /
37
+ `kvm_amd` / `kvm_arm64`)
38
+
39
+ See [Install](#install) for one-line installs per platform.
40
+
41
+ ## Install
42
+
43
+ **1. Install the `sbx` CLI** (one line per platform):
44
+
45
+ macOS — Apple silicon, Sonoma 14+:
46
+
47
+ ```bash
48
+ brew install docker/tap/sbx && sbx login
49
+ ```
50
+
51
+ Linux — Debian/Ubuntu x86_64 with KVM:
52
+
53
+ ```bash
54
+ curl -fsSL https://get.docker.com | sudo REPO_ONLY=1 sh && sudo apt-get install -y docker-sbx && sudo usermod -aG kvm "$USER" && newgrp kvm && sbx login
55
+ ```
56
+
57
+ First `sbx login` opens a browser for Docker OAuth and asks you to pick a
58
+ default network policy ("Balanced" is a good default). `newgrp kvm` drops you
59
+ into a shell with the group active; log out and back in for it to stick.
60
+
61
+ **2. Install the extension** — as a pi package (recommended). The repo
62
+ declares itself via the `pi` manifest in `package.json` (loads `index.ts`),
63
+ so it installs like any pi package — from git, npm, or a local checkout:
64
+
65
+ ```bash
66
+ pi install git:git@github.com:stixxert/pi-docker-sandbox
67
+ # or from npm:
68
+ pi install npm:@stixxert/pi-docker-sandbox
69
+ # or try it for a single run without installing:
70
+ pi -e git:git@github.com:stixxert/pi-docker-sandbox
71
+ # or install the checkout you're developing in:
72
+ pi install ./path/to/this/repo
73
+ ```
74
+
75
+ **Manually** — the extension is a single file with no build step, so you can
76
+ copy it to one of pi's auto-discovery locations, then `/reload` in pi:
77
+
78
+ ```bash
79
+ cp index.ts ~/.pi/agent/extensions/docker-sandbox.ts # global, or
80
+ cp index.ts .pi/extensions/docker-sandbox.ts # project-local
81
+ ```
82
+
83
+ or load it directly for a quick test:
84
+
85
+ ```bash
86
+ pi -e ./index.ts
87
+ ```
88
+
89
+ The sandbox is **auto-provisioned on first use** (2 CPU / 2 GB, session
90
+ workspace mounted). No manual steps required.
91
+
92
+ ## Tools
93
+
94
+ | Tool | Purpose |
95
+ |------|---------|
96
+ | `docker_status` | Sandbox presence, engine version, resources |
97
+ | `docker_verify` | Live isolation audit (PASS/FAIL per check) |
98
+ | `docker_resources` | VM memory/cpu/disk + docker disk + per-container usage, with warnings |
99
+ | `docker_prune` | Reclaim sandbox space (`docker system prune -af`) |
100
+ | `docker_ps` / `docker_images` | List containers / images in the sandbox |
101
+ | `docker_pull` | Pull an image into the sandbox daemon |
102
+ | `docker_run` | Run a container (ports, env, memory cap, volumes, network, restart; detach or foreground) |
103
+ | `docker_logs` / `docker_exec` | Inspect a running container |
104
+ | `docker_build` | Build an image from a workspace directory |
105
+ | `docker_init` | Scaffold a Dockerfile (+ compose) with language detection |
106
+ | `docker_compose` | Deploy/manage compose projects (`up -d --build`) |
107
+ | `docker_stop` / `docker_start` / `docker_rm` | Container lifecycle |
108
+ | `docker_curl` | Probe a published port from the host process (GET/POST/PUT) |
109
+ | `docker_sandbox_rm` | Remove this session's sandbox (microVM + everything inside) |
110
+ | `docker_gc` | Sweep stale `pi-sbx-*` sandboxes left by crashed sessions |
111
+
112
+ All containers get the label `com.pi.sandbox=true`.
113
+
114
+ ## Multi-session sandbox naming
115
+
116
+ Each pi session gets its own sandbox named `pi-sbx-<pid>-<random>` — unique per
117
+ process, never repeats, and independent of any host environment (herdr, tmux,
118
+ terminal). Concurrent sessions never share docker state. For a stable,
119
+ persistent name (e.g. a shared sandbox reused across restarts), pin
120
+ `DOCKER_SANDBOX` explicitly.
121
+
122
+ - `DOCKER_SANDBOX` — pin an explicit (e.g. shared, persistent) sandbox name.
123
+ - `DOCKER_SANDBOX_AUTOCREATE=0` — disable auto-provisioning (create manually
124
+ with `sbx create --name <name> shell <workspace-dir>` from a host pane).
125
+ - `DOCKER_SANDBOX_CPUS` / `DOCKER_SANDBOX_MEMORY` — resources for
126
+ auto-created sandboxes (default `2` / `2g`; sbx minimum memory is 1 GiB,
127
+ values below are clamped).
128
+ - `DOCKER_SANDBOX_WORKSPACE_RO=1` — mount the project **read-only** into the
129
+ sandbox (sbx requires the primary workspace to be rw, so a small scratch
130
+ primary is created and the project is mounted as a read-only additional
131
+ workspace). The agent writes project files through its normal tools
132
+ (`/workspace` in its own VM); the sandbox and any container it runs can
133
+ only read the project — even bind mounts from it are read-only. Builds and
134
+ compose still work; volume binds sourced from the project get `:ro` added
135
+ automatically.
136
+ - `DOCKER_SANDBOX_KEEPALIVE=1` — keep the sandbox VM running while the pi
137
+ session is alive (watchdog pokes it every ~60s), defeating sandboxd's
138
+ idle-stop for leave-it-running deploy flows.
139
+ - `DOCKER_SANDBOX_TEMPLATE=<name>` — use a pre-baked `sbx template` for
140
+ auto-created sandboxes (avoids re-pulling common images every session;
141
+ create with `sbx template save <name>` from a prepared sandbox).
142
+
143
+ ## Ports (verified rules)
144
+
145
+ - sbx does **not** auto-forward docker `-p` mappings — the extension
146
+ explicitly publishes them (`sbx ports <sandbox> --publish H:C`) after
147
+ `docker_run`/`docker_compose up` and reports the host URL
148
+ (`http://127.0.0.1:<hostport>/`). `docker_rm` unpublishes again.
149
+ - **Host ports < 1024** are privileged in macOS/Unix for any non-root process
150
+ (standard OS rule, not an sbx limitation) — irrelevant for dev (dev servers
151
+ run on 3000/8080/…) and only matters when reproducing a production URL
152
+ without a port number.
153
+ - **Avoid container port 80** — the sandbox's port proxy resets it (verified:
154
+ node, busybox, nginx). Use 3000/8080/8000 (`docker_init` templates do);
155
+ nginx-style images just need their listen port changed — the host URL is
156
+ unaffected.
157
+ - **UDP**: `sbx ports` accepts `H:C/udp` and a round-trip was verified
158
+ (node dgram echo); use `ports=["5000:5000/udp"]`.
159
+ - **Idle-stop**: sandboxd stops sandbox VMs ~2–4 min after the last `sbx`
160
+ call; `docker_run` defaults detached services to `restart=unless-stopped`
161
+ and `sbx ports` mappings survive VM restarts. For leave-it-running flows
162
+ set `DOCKER_SANDBOX_KEEPALIVE=1`.
163
+ - **Reboot cleanup**: `docker_rm`/`docker_compose down` unpublish port
164
+ mappings; after a host reboot let the session-start GC handle it, or run
165
+ `sbx rm --force $(sbx ls -q | grep pi-sbx)` from a host pane.
166
+ - Agent-side verification: `docker_curl` (host-side fetch, GET/POST/PUT with
167
+ optional body); human-side: `http://localhost:<hostport>/`.
168
+
169
+ See [boundary.md](boundary.md) for the full agent ↔ sbx boundary
170
+ model and usage guide (agent + human). The extension is not dependent on
171
+ gondolin — it runs in the host pi process and relies only on the
172
+ `/workspace` ↔ host-cwd path convention.
173
+
174
+ ## Sandbox lifecycle
175
+
176
+ | Event | What happens |
177
+ |-------|--------------|
178
+ | First `docker_*` call | Sandbox is auto-provisioned (unique name, session workspace mounted) and a **detached watchdog** is armed on the pi process |
179
+ | Session idle | Nothing — the sandbox stays ready; `sbx exec` auto-starts the VM if it was stopped |
180
+ | Session ends (exit, Ctrl+C/D, SIGHUP/SIGTERM, `/new`, `/resume`, `/fork`) | `session_shutdown` hook runs teardown immediately (fast path) |
181
+ | Session dies hard (`kill -9`, process-manager kill) | The watchdog (which polls the pi process and survives it) performs the same teardown within seconds — no event required |
182
+ | Watchdog also missed (host reboot) | Sandbox left stopped; the GC sweep reclaims it at the next session start |
183
+ | Manual | `docker_sandbox_rm` (this session's sandbox) / `docker_gc` (stale sandboxes) |
184
+
185
+ Teardown policy (`DOCKER_SANDBOX_TEARDOWN`, default `remove` for session
186
+ sandboxes, `none` for pinned `DOCKER_SANDBOX` names):
187
+
188
+ - `remove` — delete the microVM and everything inside it (images, containers,
189
+ volumes). State is rebuildable; nothing accumulates.
190
+ - `stop` — keep state, free memory; the VM restarts on next use.
191
+ - `none` — leave running (use for shared/persistent sandboxes).
192
+
193
+ Crash safety net: at every session start (and via `docker_gc [hours]`) the
194
+ extension sweeps sandboxes named `pi-sbx-*` that are **stopped**, not the
195
+ current session's, and older than `DOCKER_SANDBOX_GC_HOURS` (default `24`).
196
+ Note: `DOCKER_SANDBOX_GC_HOURS=0` **disables the automatic session-start
197
+ sweep**; the `docker_gc` tool still accepts `hours=0` for a manual any-age
198
+ sweep. Running sandboxes and non-pi sandboxes are never touched.
199
+
200
+ ## Path mapping
201
+
202
+ The agent's VM mounts the workspace at `/workspace`; the extension maps
203
+ `/workspace/<rel>` → `<host pi cwd>/<rel>`, which is also the path inside the
204
+ sandbox (the workspace is direct-mounted there). So `docker_build` contexts
205
+ and `docker_run` volume binds "just work".
206
+
207
+ ## Example deploy flow
208
+
209
+ ```
210
+ docker_status
211
+ docker_init(context=/workspace/myapp) # scaffold Dockerfile
212
+ docker_build(context=/workspace/myapp, tag=myapp:latest)
213
+ docker_run(image=myapp:latest, name=web, ports=["8080:80"], detach=true)
214
+ docker_logs(id=web, tail=50)
215
+ docker_verify # confirm isolation
216
+ docker_compose(file=/workspace/myapp/compose.yaml, action=up)
217
+ ```
218
+
219
+ ## Dockerfiles
220
+
221
+ Dockerfiles are ordinary files in the workspace — the agent authors/edits
222
+ them with its normal tools and builds them with `docker_build`. `docker_init`
223
+ bootstraps a sensible one for node (npm or pnpm), go, python, rust, or a
224
+ generic alpine base, plus a `.dockerignore` and optional `compose.yaml`.
225
+
226
+ ## Security
227
+
228
+ See [security.md](security.md) for the threat model, design
229
+ guarantees, and the `docker_verify` check list. For maximum project
230
+ protection, set `DOCKER_SANDBOX_WORKSPACE_RO=1`: the sandbox then has the
231
+ project mounted read-only and **all** project writes flow through the agent's
232
+ own sandboxed tools instead.
233
+
234
+ ## Host env forwarding (secure by default)
235
+
236
+ The extension passes **only a minimal safe set** of the pi host's environment
237
+ into the sandbox — `HOME`, `PATH`, `USER`, `LOGNAME`, `TMPDIR`, `SHELL`,
238
+ `LANG`, `TERM` (non-secret vars the `sbx` CLI and shells need). `DOCKER_*` /
239
+ `COMPOSE_*` are **always** stripped — a leaked `DOCKER_HOST` could redirect
240
+ the inner docker client. Everything else is confined by default:
241
+
242
+ - `DOCKER_SANDBOX_ENV_ALLOWLIST="A,B"` — opt in precisely: forward the
243
+ minimal set plus exactly `A` and `B` (e.g. the vars your compose file
244
+ interpolates with `${VAR}`). Docker-affecting vars cannot be allowlisted.
245
+ - `DOCKER_SANDBOX_ENV_PASSTHROUGH=1` — explicit opt-out: forward the host env
246
+ minus the docker vars (raw `sbx exec` semantics, for legacy workflows that
247
+ rely on broad compose interpolation).
248
+
249
+ Anything that runs inside the sandbox (containers, `docker_exec`'d commands)
250
+ can read whatever reaches it — so host API keys and tokens stay confined
251
+ unless you allowlist them deliberately. Prefer project-local `.env` files
252
+ (gitignored) over host-env interpolation for compose secrets.
253
+ `docker_verify` audits the active mode (`docker_status` reports it).
254
+
255
+ ## Development
256
+
257
+ ```sh
258
+ npm install
259
+ npm run typecheck # strict tsc against the pi SDK types
260
+ npm test # loads the extension with a mock pi API; no sbx needed
261
+ ```
262
+
263
+ The extension is a single file with no build step — `index.ts` is loaded
264
+ directly by pi (copy it to `~/.pi/agent/extensions/docker-sandbox.ts`, or
265
+ `pi install` the repo, see [Install](#install)). `package.json` doubles as the
266
+ pi package manifest (`pi.extensions`) and declares typecheck-only dev deps;
267
+ `tsconfig.json` keeps `tsc --strict` honest against the pi SDK types.
268
+
269
+ ## License
270
+
271
+ Apache-2.0 — see [LICENSE](LICENSE).
package/boundary.md ADDED
@@ -0,0 +1,185 @@
1
+ # The agent ↔ sbx boundary (and what the sandbox is for)
2
+
3
+ This document defines what the Docker Sandbox is, what it is not, the exact
4
+ trust boundary between the agent's own VM and the sandbox, and how to use it —
5
+ for the **agent** and for the **human operator**.
6
+
7
+ > **Not gondolin-specific.** This extension does **not depend on gondolin**
8
+ > (pi's default agent micro-VM). It runs entirely in the host pi process and
9
+ > relies on exactly one convention: the agent's workspace is mounted at
10
+ > `/workspace`, which the extension maps to the host pi cwd
11
+ > (`/workspace/<rel>` ↔ `<host cwd>/<rel>`). That mapping is a plain
12
+ > host-side path substitution — no gondolin mechanism is involved, and the
13
+ > same applies to any pi setup that mounts the workspace at `/workspace`.
14
+ > Gondolin is used throughout this document simply as the concrete reference
15
+ > deployment.
16
+
17
+ ## Topology
18
+
19
+ ```
20
+ host macOS (trusted operator)
21
+
22
+ ├─ pi process (host) ── extension docker-sandbox.ts ── only channel to sbx
23
+ │ │ path mapping: /workspace/<rel> ↔ <host cwd>/<rel>
24
+ │ ▼
25
+ │ agent's VM (e.g. gondolin) │ sbx microVM (Docker Sandbox)
26
+ │ └ /workspace (rw) │ └ /Users/…/project (rw or :ro)
27
+ │ agent's tools: │ └ private docker daemon (own images,
28
+ │ read/write/edit/bash │ containers, volumes)
29
+ │ (sandboxed by policy) │
30
+ └──────────────────────────────┴─────────────────────────────────────────────
31
+ same host directory mounted in both VMs (one mount, two views)
32
+ ```
33
+
34
+ ## What the sandbox is FOR
35
+
36
+ - A **disposable, isolated execution environment for containerized
37
+ workloads**: build images, run services, `docker compose up`, test deploys —
38
+ without touching the host's docker or the agent's own VM.
39
+ - A private docker daemon per pi session, with its own images/containers/
40
+ volumes, port-forwarded to host `localhost` only, torn down with the
41
+ session.
42
+ - Deploy verification (health checks, logs, exec) inside a real container
43
+ runtime.
44
+
45
+ ## What the sandbox is NOT
46
+
47
+ - ❌ Not a gateway to the host's docker (Docker Desktop / colima / dockerd).
48
+ The extension never opens a host docker socket and never invokes a host
49
+ `docker` CLI; there is no fallback path.
50
+ - ❌ Not the place where the agent edits project files. Project files are
51
+ written with the agent's normal tools in its own VM (`/workspace`); the
52
+ sandbox reads them (build contexts, volume binds). With
53
+ `DOCKER_SANDBOX_WORKSPACE_RO=1` the sandbox physically cannot modify the
54
+ project.
55
+ - ❌ Not a sandbox for the agent's file/network access — that is the agent's
56
+ own VM's job. The sbx sandbox only adds an isolated *docker runtime*.
57
+
58
+ ## Boundary guarantees (verified)
59
+
60
+ | Property | How it's enforced |
61
+ |---|---|
62
+ | Agent's docker reach = its own sandbox only | Every tool derives the sandbox name from the session (`pi-sbx-<pid>-<random>`, or an explicit `DOCKER_SANDBOX`); no tool accepts a foreign sandbox name; `sbx` CLI and host docker socket are absent from the agent's VM |
63
+ | One sandbox per session | Deterministic per-session name + auto-provision once; `docker_sandbox_rm` removes only that one; GC touches only stale `pi-sbx-*` sandboxes (never running ones, never non-pi ones) |
64
+ | No host docker access | Transport is `sbx exec` only; `DOCKER_*`/`COMPOSE_*` env scrubbed; inner docker pinned via `-H unix:///var/run/docker.sock` |
65
+ | Host env confidentiality | `DOCKER_*`/`COMPOSE_*` always stripped; secure by default (only a minimal safe set is forwarded); `DOCKER_SANDBOX_ENV_ALLOWLIST` opts in to specific vars, `_PASSTHROUGH` opts out entirely; `docker_verify` audits the active mode |
66
+ | Host files untouched | Only the session workspace is mounted into the sandbox; host `~/.docker`, `~/.ssh` etc. are not visible (audited by `docker_verify`) |
67
+ | Project writes (optional) | `DOCKER_SANDBOX_WORKSPACE_RO=1` → project mounted read-only; all project writes must go through the agent's own tools |
68
+ | Ports | Published on host `127.0.0.1` only (`sbx ports`); the agent probes them with `docker_curl` (host-side fetch); the agent's VM cannot reach host loopback |
69
+
70
+ ## Ports & networking (verified rules)
71
+
72
+ 1. **Publishing is explicit**: sbx does not auto-forward docker `-p`
73
+ mappings. The extension calls `sbx ports <sandbox> --publish H:C` after
74
+ `docker_run`/`docker_compose up` and reports the host URL
75
+ (`http://127.0.0.1:<hostport>/`). Compose port discovery reads both the
76
+ legacy `Ports` string and the structured `Publishers` array from
77
+ `docker compose ps --format '{{json .}}'`. `docker_rm` and
78
+ `docker_compose down` unpublish the container's mappings again (sbx would
79
+ otherwise leave stale mappings that answer with connection resets).
80
+ 2. **Host port ≥ 1024**: ports < 1024 are privileged in macOS/Unix for ANY
81
+ non-root process (`PermissionError: Errno 13`), not an sbx limitation.
82
+ Irrelevant for dev (dev servers use 3000/8080/…); only matters when
83
+ reproducing production URLs without a port number. Workaround if ever
84
+ needed: `sudo pfctl` port redirect or a reverse proxy on a high port.
85
+ 3. **Avoid container port 80**: the sandbox's port proxy resets connections
86
+ to container port 80 (verified with node, busybox httpd, nginx). Use
87
+ container ports like 3000/8080/8000 (the `docker_init` templates do); for
88
+ images that listen on 80 by default (e.g. nginx), reconfigure them — for
89
+ dev this is a one-line config change and the host URL is unaffected (the
90
+ host port is what appears in the URL).
91
+ 4. **UDP**: works. `sbx ports` accepts `H:C/udp`, and a host→sandbox UDP
92
+ round-trip was verified (node dgram echo server). Use `ports=["5000:5000/udp"]`.
93
+ 5. **Idle-stop**: sandboxd stops sandbox VMs ~2–4 minutes after the last
94
+ `sbx exec` client disconnects (not configurable via `sbx` CLI). Services
95
+ with `restart=unless-stopped` (the extension's default for detached runs)
96
+ come back on the next exec; `sbx ports` mappings survive. For
97
+ leave-it-running flows set `DOCKER_SANDBOX_KEEPALIVE=1` (the watchdog
98
+ pokes the sandbox every ~60s while the pi session is alive).
99
+ 6. **Verification paths**:
100
+ - Agent → `docker_curl http://127.0.0.1:<hostport>/` (host-side fetch;
101
+ GET/POST/PUT with optional body).
102
+ - Sandbox-internal → `docker_exec` against `127.0.0.1:<port>` (same docker
103
+ network).
104
+ - Human → open `http://localhost:<hostport>/` on the host.
105
+
106
+ ## How the AGENT should use it
107
+
108
+ - Run `docker_status` first; then deploy with
109
+ `docker_init` → `docker_build` → `docker_run`/`docker_compose`.
110
+ - Verify what you started: `docker_curl` (host), `docker_logs`, `docker_exec`.
111
+ - Do not attempt to reach the host's docker (there is no path), and do not
112
+ invent sandbox names — the session sandbox is `sessionSandboxName()` and
113
+ every tool targets it.
114
+ - Use non-80 container ports and ≥1024 host ports.
115
+ - Clean up: `docker_rm`/`docker_compose down` for containers;
116
+ `docker_sandbox_rm` for the whole sandbox; `docker_gc` for stale ones.
117
+
118
+ ## How the HUMAN should use it
119
+
120
+ - Prereqs: `sbx` CLI (`brew install docker/tap/sbx`), `sbx login`, `sandboxd`
121
+ running (`sbx daemon status`). Docker Desktop is NOT needed.
122
+ - The sandbox is auto-provisioned on first use; manage it with
123
+ `sbx ls` / `sbx stop <name>` / `sbx rm --force <name>`.
124
+ - Tune via env: `DOCKER_SANDBOX` (pin a name), `DOCKER_SANDBOX_TEARDOWN`
125
+ (`remove`/`stop`/`none`), `DOCKER_SANDBOX_WORKSPACE_RO=1`,
126
+ `DOCKER_SANDBOX_GC_HOURS`, `DOCKER_SANDBOX_CPUS`/`_MEMORY`, and env
127
+ confinement: `DOCKER_SANDBOX_ENV_ALLOWLIST="A,B"` (opt in) /
128
+ `DOCKER_SANDBOX_ENV_PASSTHROUGH=1` (opt out of the secure default).
129
+ - A sandbox is a dev/test environment, not a security boundary against the
130
+ host user; the workspace mount is the only host surface it sees.
131
+
132
+ ## Resources & failure modes (how the agent finds out, what to do)
133
+
134
+ The sandbox has fixed limits set at creation (`DOCKER_SANDBOX_CPUS`, default 2;
135
+ `DOCKER_SANDBOX_MEMORY`, default 2g). The agent is notified of pressure in two
136
+ ways:
137
+
138
+ 1. **Indirect (always):** docker tool calls surface it — builds fail with
139
+ no-space errors, `docker_ps` shows `Exited (137)` / `Restarting (137)`
140
+ (OOM-kill), pulls time out. The extension now has a 120s default timeout on
141
+ sandbox calls so an OOM-hung VM fails the tool call instead of hanging the
142
+ turn.
143
+ 2. **Direct (new):** `docker_resources` reports VM memory/cpu/disk, docker disk
144
+ (images/containers/build cache), and per-running-container cpu/mem, and
145
+ warns above 85% memory or disk. Run it when deploys fail or containers exit
146
+ abnormally.
147
+
148
+ Remediation ladder (in the agent's toolset):
149
+
150
+ | Symptom | Action |
151
+ |---|---|
152
+ | High memory / OOM kills | `docker_rm`/`docker_stop` heavy containers; cap them with `docker_run(memory=…)`; raise `DOCKER_SANDBOX_MEMORY` and recreate (`docker_sandbox_rm` → next call re-provisions) |
153
+ | High disk / no-space builds | `docker_prune` (optionally `volumes=true`) |
154
+ | Container restart-looping on OOM | `docker_stop` it; use `restart=no` for memory-capped containers (restart policy + cap = infinite restart loop) |
155
+ | VM unresponsive (sandboxd OOM) | `sbx ls`/`sbx stop <name>` from a host pane, or `docker_sandbox_rm` + recreate with bigger limits |
156
+
157
+ Caveat: resources are fixed at sandbox creation — changing `DOCKER_SANDBOX_CPUS`/
158
+ `_MEMORY` requires recreating the sandbox (session-scoped sandboxes are
159
+ recreated automatically on the next `docker_*` call after removal).
160
+
161
+ ## Known limitations / areas to look into
162
+
163
+ - **Container port 80** and **host ports < 1024** do not forward (see above);
164
+ both are dev-irrelevant with the documented workarounds.
165
+ - **Idle-stop**: sandboxd stops idle sandbox VMs ~2–4 min after the last sbx
166
+ call (not configurable); services auto-recover via `restart=unless-stopped`,
167
+ or keep the VM up with `DOCKER_SANDBOX_KEEPALIVE=1`.
168
+ - **Host reboot** kills both teardown mechanisms; cleanup happens via the GC
169
+ at the next session start, or manually with `sbx rm --force $(sbx ls -q | grep pi-sbx)`.
170
+ - **GC is sibling-safe**: every session writes an owner marker
171
+ (`<name>.pi-owner` with its pid) next to the sandbox state; the GC only
172
+ removes stopped `pi-sbx-*` sandboxes whose owner process is dead. Concurrent
173
+ sessions never reap each other's sandboxes, even with
174
+ `DOCKER_SANDBOX_GC_HOURS=0` (verified). Edge case: if the OS reuses a dead
175
+ session's pid, that stale sandbox lingers until manual cleanup — rare (needs
176
+ a crashed session whose teardown also failed) and harmless.
177
+ - **Concurrent sessions** each get their own sandbox; published host ports
178
+ must be unique across sessions (a taken host port falls back to an
179
+ ephemeral port).
180
+ - **Image pulls repeat per session** (each sandbox is a fresh VM). Pre-bake a
181
+ template to fix: `sbx template save <name>` from a sandbox with the images
182
+ pre-pulled, then set `DOCKER_SANDBOX_TEMPLATE=<name>` (or pass `--template`
183
+ to `sbx create`). Check `sbx template save --help` for exact syntax.
184
+ - sbx itself (VM kernel, port proxy, idle-stop) is Docker's product; its
185
+ quirks above are tracked here so behavior changes are noticed.