pi-glovebox 0.0.0-stage → 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peter Ferenczy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # pi-glovebox
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
+ <img src="assets/glovebox.webp" alt="A white π reaching into a stainless steel glovebox whose window shows bash, read, write and edit among fairy lights" width="360">
4
+
5
+ A [Pi](https://github.com/earendil-works/pi) extension that runs the model's `bash`, `read`, `write` and `edit` calls in a sandbox you start, such as [sbox](https://github.com/DavHau/sbox), instead of in Pi's process. The sandbox runs without Pi's config, credentials or session history. They talk over a Unix socket.
6
+
7
+ Every call becomes one command run by `pi-glovebox-server` inside your sandbox:
8
+
9
+ | Tool | Command |
10
+ |---|---|
11
+ | `bash` | `bash -c <command>` in Pi's working directory |
12
+ | `read` | `: < file` to check access, `head -c 4100` to detect images with Pi's own detector, `cat` |
13
+ | `write` | `mkdir -p`, then `cat > file` with the content on stdin |
14
+ | `edit` | `: < file && : >> file` to check access, `cat`, `cat > file` |
15
+
16
+ Commands get the server's environment, not Pi's. Aborts and timeouts close the connection, and the server kills the command's process group.
17
+
18
+ pi-glovebox also blocks calls to tools that would run in Pi's process instead, returning an error the model sees:
19
+
20
+ - every tool built into Pi, such as `grep`, `find`, `ls` and `codemode`, even if another extension activates it;
21
+ - `bash`, `read`, `write` or `edit` when another extension provides it.
22
+
23
+ ## When to use it
24
+
25
+ Pi sandbox extensions mostly take one of three approaches:
26
+
27
+ - check tool calls against allow and deny lists, often asking the user, and wrap bash commands in an OS sandbox;
28
+ - run the tools in a micro-VM the extension manages;
29
+ - run all of Pi, extensions included, in a container.
30
+
31
+ pi-glovebox separates where Pi runs from where the model's commands run, and leaves the second entirely to you: a bubblewrap or sbox sandbox, a container, a VM, or another machine reached through a forwarded socket. It has no policy and asks no questions, so it also works unattended, and Pi's process, environment, files and session history stay outside whatever you choose.
32
+
33
+ ## Requirements
34
+
35
+ - Node.js 22 or later for the server, and `bash`, `cat`, `head` and `mkdir` inside the sandbox.
36
+ - Pi's working directory must exist at the same path inside the sandbox.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pi install npm:pi-glovebox # or: pi install git:github.com/421anon/pi-glovebox
42
+ npm install -g pi-glovebox # pi-glovebox-server, or: nix-build -E '(import <nixpkgs> { }).callPackage ./. { }'
43
+ ```
44
+
45
+ ## Use
46
+
47
+ ```bash
48
+ SOCKET_DIR=$(mktemp -d)
49
+ env -i PATH="$PATH" HOME="$HOME" USER="$USER" sbox --bind "$SOCKET_DIR" "$SOCKET_DIR" -- pi-glovebox-server "$SOCKET_DIR/socket" &
50
+ PI_GLOVEBOX_SOCKET="$SOCKET_DIR/socket" pi --no-builtin-tools
51
+ ```
52
+
53
+ This sandbox sees the project read-write, `/nix` and the directories on your `PATH` read-only, and little else of the host: not the rest of `$HOME`, host `/tmp`, Pi's processes or the shell's environment. The server is ready once the socket exists.
54
+
55
+ - `env -i` keeps exported API keys out of the sandbox, since sbox passes its environment through.
56
+ - `--no-builtin-tools` leaves Pi's own tools inactive. If pi-glovebox fails to load, Pi has no tools unless another extension activates Pi's own.
57
+ - Other extensions, including their tools, run in Pi's process with Pi's environment. Load only extensions you trust, or pass `--no-extensions` and name each with `-e`.
58
+ - The bash environment Pi normally sets (`PI_SESSION_ID`, `PI_MODEL`, …) and the `shellPath` and `shellCommandPrefix` settings do not reach the sandbox.
59
+ - Anything that can reach the socket can run commands in the sandbox.
60
+ - Pi still reads `AGENTS.md`, skills, extensions and settings from the host. If the model can write them, it can influence later sessions; see Pi's `--no-context-files`, `--no-skills`, `--no-extensions` and `--no-approve`.
61
+ - Pi saves truncated bash output under its `TMPDIR`. Mount that directory into the sandbox if the model should read those files.
62
+
63
+ ## Protocol
64
+
65
+ One connection runs one command. The client sends one line of JSON, `{"argv": [...], "cwd": "/abs/path", "stdin": "optional text"}`. The server answers with frames of a 1-byte type, a 4-byte big-endian length and a payload: type 1 carries output (stdout and stderr as they arrive), type 2 carries the exit code as JSON (`null` if the command was killed by a signal or could not start) and is last. Closing the connection early kills the command's process group; a malformed request closes it without running anything.
66
+
67
+ ## License
68
+
69
+ [MIT](LICENSE)
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import net from "node:net";
4
+
5
+ const output = 1;
6
+ const exit = 2;
7
+
8
+ const frame = (type, payload) => {
9
+ const header = Buffer.alloc(5);
10
+ header[0] = type;
11
+ header.writeUInt32BE(payload.length, 1);
12
+ return Buffer.concat([header, payload]);
13
+ };
14
+
15
+ net
16
+ .createServer((socket) => {
17
+ let received = Buffer.alloc(0);
18
+ let child;
19
+ let exited = false;
20
+
21
+ const finish = (code) => {
22
+ if (exited) return;
23
+ exited = true;
24
+ socket.end(frame(exit, Buffer.from(JSON.stringify(code))));
25
+ };
26
+
27
+ const forward = (stream) =>
28
+ stream.on("data", (chunk) => {
29
+ if (socket.write(frame(output, chunk))) return;
30
+ stream.pause();
31
+ socket.once("drain", () => stream.resume());
32
+ });
33
+
34
+ socket.on("error", () => {});
35
+ socket.on("close", () => {
36
+ if (!child || exited) return;
37
+ try {
38
+ process.kill(-child.pid, "SIGKILL");
39
+ } catch {}
40
+ });
41
+
42
+ socket.on("data", function onRequest(chunk) {
43
+ received = Buffer.concat([received, chunk]);
44
+ const end = received.indexOf(10);
45
+ if (end < 0) return;
46
+ socket.off("data", onRequest);
47
+
48
+ let request;
49
+ try {
50
+ request = JSON.parse(received.subarray(0, end).toString());
51
+ } catch {}
52
+ const valid =
53
+ Array.isArray(request?.argv) &&
54
+ request.argv.length > 0 &&
55
+ request.argv.every((arg) => typeof arg === "string") &&
56
+ typeof request.cwd === "string" &&
57
+ (request.stdin === undefined || typeof request.stdin === "string");
58
+ if (!valid) return socket.destroy();
59
+ try {
60
+ child = spawn(request.argv[0], request.argv.slice(1), { cwd: request.cwd, detached: true });
61
+ } catch (error) {
62
+ socket.write(frame(output, Buffer.from(`${error.message}\n`)));
63
+ return finish(null);
64
+ }
65
+ forward(child.stdout);
66
+ forward(child.stderr);
67
+ child.on("error", (error) => {
68
+ socket.write(frame(output, Buffer.from(`${error.message}\n`)));
69
+ finish(null);
70
+ });
71
+ child.on("close", (code) => finish(code));
72
+ child.stdin.on("error", () => {});
73
+ child.stdin.end(request.stdin ?? "");
74
+ });
75
+ })
76
+ .listen(process.argv[2]);
@@ -0,0 +1,133 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import net from "node:net";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import {
8
+ createBashTool,
9
+ createEditTool,
10
+ createReadTool,
11
+ createWriteTool,
12
+ detectSupportedImageMimeTypeFromFile,
13
+ type ExtensionAPI,
14
+ } from "@earendil-works/pi-coding-agent";
15
+
16
+ const socketPath = process.env.PI_GLOVEBOX_SOCKET;
17
+ if (!socketPath) throw new Error("PI_GLOVEBOX_SOCKET is not set");
18
+
19
+ const imageSniffBytes = "4100";
20
+ const ownFile = realpathSync(fileURLToPath(import.meta.url));
21
+ const ownPaths = [ownFile, path.dirname(ownFile)];
22
+ const ownTools = ["bash", "read", "write", "edit"];
23
+
24
+ type Request = { argv: string[]; cwd: string; stdin?: string };
25
+ type Options = { onData?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number };
26
+ type Result = { output: Buffer; exitCode: number | null };
27
+
28
+ const run = (request: Request, { onData, signal, timeout }: Options = {}) =>
29
+ new Promise<Result>((resolve, reject) => {
30
+ const socket = net.createConnection(socketPath);
31
+ const output: Buffer[] = [];
32
+ let received = Buffer.alloc(0);
33
+ let exitCode: number | null | undefined;
34
+
35
+ const stop = (error: Error) => {
36
+ socket.destroy();
37
+ reject(error);
38
+ };
39
+ const abort = () => stop(new Error("aborted"));
40
+ const timer = timeout ? setTimeout(() => stop(new Error(`timeout:${timeout}`)), timeout * 1000) : undefined;
41
+ signal?.addEventListener("abort", abort, { once: true });
42
+
43
+ socket.on("data", (chunk) => {
44
+ received = Buffer.concat([received, chunk]);
45
+ while (received.length >= 5 && received.length >= 5 + received.readUInt32BE(1)) {
46
+ const payload = received.subarray(5, 5 + received.readUInt32BE(1));
47
+ if (received[0] === 1) {
48
+ if (onData) onData(payload);
49
+ else output.push(payload);
50
+ } else {
51
+ exitCode = JSON.parse(payload.toString());
52
+ }
53
+ received = received.subarray(5 + payload.length);
54
+ }
55
+ });
56
+ socket.on("error", reject);
57
+ socket.on("close", () => {
58
+ clearTimeout(timer);
59
+ signal?.removeEventListener("abort", abort);
60
+ if (exitCode === undefined) reject(new Error("pi-glovebox: connection closed before the command finished"));
61
+ else resolve({ output: Buffer.concat(output), exitCode });
62
+ });
63
+
64
+ if (signal?.aborted) abort();
65
+ else socket.write(`${JSON.stringify(request)}\n`);
66
+ });
67
+
68
+ const succeed = async (argv: string[], stdin?: string) => {
69
+ const { output, exitCode } = await run({ argv, cwd: "/", stdin });
70
+ if (exitCode !== 0) throw new Error(output.toString().trim() || `exit code ${exitCode}`);
71
+ return output;
72
+ };
73
+
74
+ const shell = (script: string, file: string, stdin?: string) =>
75
+ succeed(["bash", "-c", script, "pi-glovebox", file], stdin).then(() => {});
76
+
77
+ const detectImageMimeType = async (file: string) => {
78
+ const head = await succeed(["head", "-c", imageSniffBytes, "--", file]);
79
+ const directory = await mkdtemp(path.join(tmpdir(), "pi-glovebox-"));
80
+ try {
81
+ await writeFile(path.join(directory, "head"), head);
82
+ return await detectSupportedImageMimeTypeFromFile(path.join(directory, "head"));
83
+ } finally {
84
+ await rm(directory, { recursive: true, force: true });
85
+ }
86
+ };
87
+
88
+ export default function (pi: ExtensionAPI) {
89
+ const cwd = process.cwd();
90
+ pi.on("tool_call", ({ toolName }) => {
91
+ const source = pi.getAllTools().find((tool) => tool.name === toolName)?.sourceInfo;
92
+ if (source?.source === "builtin") {
93
+ return { block: true, reason: `pi-glovebox: ${toolName} is built into Pi and would run outside the sandbox` };
94
+ }
95
+ if (ownTools.includes(toolName) && !(source && existsSync(source.path) && ownPaths.includes(realpathSync(source.path)))) {
96
+ return { block: true, reason: `pi-glovebox: ${toolName} comes from ${source?.path}, not pi-glovebox, and would run outside the sandbox` };
97
+ }
98
+ });
99
+ pi.registerTool(
100
+ createBashTool(cwd, {
101
+ operations: {
102
+ exec: (command, directory, options) =>
103
+ run({ argv: ["bash", "-c", command], cwd: directory }, options).then(({ exitCode }) => ({ exitCode })),
104
+ },
105
+ }),
106
+ );
107
+ pi.registerTool(
108
+ createReadTool(cwd, {
109
+ operations: {
110
+ readFile: (file) => succeed(["cat", "--", file]),
111
+ access: (file) => shell(': < "$1"', file),
112
+ detectImageMimeType,
113
+ },
114
+ }),
115
+ );
116
+ pi.registerTool(
117
+ createWriteTool(cwd, {
118
+ operations: {
119
+ writeFile: (file, content) => shell('cat > "$1"', file, content),
120
+ mkdir: (directory) => succeed(["mkdir", "-p", "--", directory]).then(() => {}),
121
+ },
122
+ }),
123
+ );
124
+ pi.registerTool(
125
+ createEditTool(cwd, {
126
+ operations: {
127
+ readFile: (file) => succeed(["cat", "--", file]),
128
+ writeFile: (file, content) => shell('cat > "$1"', file, content),
129
+ access: (file) => shell(': < "$1" && : >> "$1"', file),
130
+ },
131
+ }),
132
+ );
133
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "pi-glovebox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Run Pi's bash, read, write and edit tools in a separate sandbox, reached over a Unix socket",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi-extension",
8
+ "sandbox",
9
+ "bubblewrap"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "Peter Ferenczy <ggpeti@gmail.com>",
13
+ "homepage": "https://github.com/421anon/pi-glovebox#readme",
14
+ "bugs": "https://github.com/421anon/pi-glovebox/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/421anon/pi-glovebox.git"
18
+ },
19
+ "type": "module",
20
+ "bin": {
21
+ "pi-glovebox-server": "bin/pi-glovebox-server.mjs"
22
+ },
23
+ "files": [
24
+ "bin",
25
+ "extensions"
26
+ ],
27
+ "pi": {
28
+ "extensions": [
29
+ "./extensions/index.ts"
30
+ ]
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-coding-agent": "*"
34
+ },
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "scripts": {
39
+ "test": "node --test"
40
+ }
41
+ }