@mariozechner/pi-coding-agent 0.44.0 → 0.45.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.
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Sandbox Extension - OS-level sandboxing for bash commands
3
+ *
4
+ * Uses @anthropic-ai/sandbox-runtime to enforce filesystem and network
5
+ * restrictions on bash commands at the OS level (sandbox-exec on macOS,
6
+ * bubblewrap on Linux).
7
+ *
8
+ * Config files (merged, project takes precedence):
9
+ * - ~/.pi/agent/sandbox.json (global)
10
+ * - <cwd>/.pi/sandbox.json (project-local)
11
+ *
12
+ * Example .pi/sandbox.json:
13
+ * ```json
14
+ * {
15
+ * "enabled": true,
16
+ * "network": {
17
+ * "allowedDomains": ["github.com", "*.github.com"],
18
+ * "deniedDomains": []
19
+ * },
20
+ * "filesystem": {
21
+ * "denyRead": ["~/.ssh", "~/.aws"],
22
+ * "allowWrite": [".", "/tmp"],
23
+ * "denyWrite": [".env"]
24
+ * }
25
+ * }
26
+ * ```
27
+ *
28
+ * Usage:
29
+ * - `pi -e ./sandbox` - sandbox enabled with default/config settings
30
+ * - `pi -e ./sandbox --no-sandbox` - disable sandboxing
31
+ * - `/sandbox` - show current sandbox configuration
32
+ *
33
+ * Setup:
34
+ * 1. Copy sandbox/ directory to ~/.pi/agent/extensions/
35
+ * 2. Run `npm install` in ~/.pi/agent/extensions/sandbox/
36
+ *
37
+ * Linux also requires: bubblewrap, socat, ripgrep
38
+ */
39
+
40
+ import { spawn } from "node:child_process";
41
+ import { existsSync, readFileSync } from "node:fs";
42
+ import { homedir } from "node:os";
43
+ import { join } from "node:path";
44
+ import { SandboxManager, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
45
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
46
+ import { type BashOperations, createBashTool } from "@mariozechner/pi-coding-agent";
47
+
48
+ interface SandboxConfig extends SandboxRuntimeConfig {
49
+ enabled?: boolean;
50
+ }
51
+
52
+ const DEFAULT_CONFIG: SandboxConfig = {
53
+ enabled: true,
54
+ network: {
55
+ allowedDomains: [
56
+ "npmjs.org",
57
+ "*.npmjs.org",
58
+ "registry.npmjs.org",
59
+ "registry.yarnpkg.com",
60
+ "pypi.org",
61
+ "*.pypi.org",
62
+ "github.com",
63
+ "*.github.com",
64
+ "api.github.com",
65
+ "raw.githubusercontent.com",
66
+ ],
67
+ deniedDomains: [],
68
+ },
69
+ filesystem: {
70
+ denyRead: ["~/.ssh", "~/.aws", "~/.gnupg"],
71
+ allowWrite: [".", "/tmp"],
72
+ denyWrite: [".env", ".env.*", "*.pem", "*.key"],
73
+ },
74
+ };
75
+
76
+ function loadConfig(cwd: string): SandboxConfig {
77
+ const projectConfigPath = join(cwd, ".pi", "sandbox.json");
78
+ const globalConfigPath = join(homedir(), ".pi", "agent", "sandbox.json");
79
+
80
+ let globalConfig: Partial<SandboxConfig> = {};
81
+ let projectConfig: Partial<SandboxConfig> = {};
82
+
83
+ if (existsSync(globalConfigPath)) {
84
+ try {
85
+ globalConfig = JSON.parse(readFileSync(globalConfigPath, "utf-8"));
86
+ } catch (e) {
87
+ console.error(`Warning: Could not parse ${globalConfigPath}: ${e}`);
88
+ }
89
+ }
90
+
91
+ if (existsSync(projectConfigPath)) {
92
+ try {
93
+ projectConfig = JSON.parse(readFileSync(projectConfigPath, "utf-8"));
94
+ } catch (e) {
95
+ console.error(`Warning: Could not parse ${projectConfigPath}: ${e}`);
96
+ }
97
+ }
98
+
99
+ return deepMerge(deepMerge(DEFAULT_CONFIG, globalConfig), projectConfig);
100
+ }
101
+
102
+ function deepMerge(base: SandboxConfig, overrides: Partial<SandboxConfig>): SandboxConfig {
103
+ const result: SandboxConfig = { ...base };
104
+
105
+ if (overrides.enabled !== undefined) result.enabled = overrides.enabled;
106
+ if (overrides.network) {
107
+ result.network = { ...base.network, ...overrides.network };
108
+ }
109
+ if (overrides.filesystem) {
110
+ result.filesystem = { ...base.filesystem, ...overrides.filesystem };
111
+ }
112
+
113
+ const extOverrides = overrides as {
114
+ ignoreViolations?: Record<string, string[]>;
115
+ enableWeakerNestedSandbox?: boolean;
116
+ };
117
+ const extResult = result as { ignoreViolations?: Record<string, string[]>; enableWeakerNestedSandbox?: boolean };
118
+
119
+ if (extOverrides.ignoreViolations) {
120
+ extResult.ignoreViolations = extOverrides.ignoreViolations;
121
+ }
122
+ if (extOverrides.enableWeakerNestedSandbox !== undefined) {
123
+ extResult.enableWeakerNestedSandbox = extOverrides.enableWeakerNestedSandbox;
124
+ }
125
+
126
+ return result;
127
+ }
128
+
129
+ function createSandboxedBashOps(): BashOperations {
130
+ return {
131
+ async exec(command, cwd, { onData, signal, timeout }) {
132
+ if (!existsSync(cwd)) {
133
+ throw new Error(`Working directory does not exist: ${cwd}`);
134
+ }
135
+
136
+ const wrappedCommand = await SandboxManager.wrapWithSandbox(command);
137
+
138
+ return new Promise((resolve, reject) => {
139
+ const child = spawn("bash", ["-c", wrappedCommand], {
140
+ cwd,
141
+ detached: true,
142
+ stdio: ["ignore", "pipe", "pipe"],
143
+ });
144
+
145
+ let timedOut = false;
146
+ let timeoutHandle: NodeJS.Timeout | undefined;
147
+
148
+ if (timeout !== undefined && timeout > 0) {
149
+ timeoutHandle = setTimeout(() => {
150
+ timedOut = true;
151
+ if (child.pid) {
152
+ try {
153
+ process.kill(-child.pid, "SIGKILL");
154
+ } catch {
155
+ child.kill("SIGKILL");
156
+ }
157
+ }
158
+ }, timeout * 1000);
159
+ }
160
+
161
+ child.stdout?.on("data", onData);
162
+ child.stderr?.on("data", onData);
163
+
164
+ child.on("error", (err) => {
165
+ if (timeoutHandle) clearTimeout(timeoutHandle);
166
+ reject(err);
167
+ });
168
+
169
+ const onAbort = () => {
170
+ if (child.pid) {
171
+ try {
172
+ process.kill(-child.pid, "SIGKILL");
173
+ } catch {
174
+ child.kill("SIGKILL");
175
+ }
176
+ }
177
+ };
178
+
179
+ signal?.addEventListener("abort", onAbort, { once: true });
180
+
181
+ child.on("close", (code) => {
182
+ if (timeoutHandle) clearTimeout(timeoutHandle);
183
+ signal?.removeEventListener("abort", onAbort);
184
+
185
+ if (signal?.aborted) {
186
+ reject(new Error("aborted"));
187
+ } else if (timedOut) {
188
+ reject(new Error(`timeout:${timeout}`));
189
+ } else {
190
+ resolve({ exitCode: code });
191
+ }
192
+ });
193
+ });
194
+ },
195
+ };
196
+ }
197
+
198
+ export default function (pi: ExtensionAPI) {
199
+ pi.registerFlag("no-sandbox", {
200
+ description: "Disable OS-level sandboxing for bash commands",
201
+ type: "boolean",
202
+ default: false,
203
+ });
204
+
205
+ const localCwd = process.cwd();
206
+ const localBash = createBashTool(localCwd);
207
+
208
+ let sandboxEnabled = false;
209
+ let sandboxInitialized = false;
210
+
211
+ pi.registerTool({
212
+ ...localBash,
213
+ label: "bash (sandboxed)",
214
+ async execute(id, params, onUpdate, _ctx, signal) {
215
+ if (!sandboxEnabled || !sandboxInitialized) {
216
+ return localBash.execute(id, params, signal, onUpdate);
217
+ }
218
+
219
+ const sandboxedBash = createBashTool(localCwd, {
220
+ operations: createSandboxedBashOps(),
221
+ });
222
+ return sandboxedBash.execute(id, params, signal, onUpdate);
223
+ },
224
+ });
225
+
226
+ pi.on("user_bash", () => {
227
+ if (!sandboxEnabled || !sandboxInitialized) return;
228
+ return { operations: createSandboxedBashOps() };
229
+ });
230
+
231
+ pi.on("session_start", async (_event, ctx) => {
232
+ const noSandbox = pi.getFlag("no-sandbox") as boolean;
233
+
234
+ if (noSandbox) {
235
+ sandboxEnabled = false;
236
+ ctx.ui.notify("Sandbox disabled via --no-sandbox", "warning");
237
+ return;
238
+ }
239
+
240
+ const config = loadConfig(ctx.cwd);
241
+
242
+ if (!config.enabled) {
243
+ sandboxEnabled = false;
244
+ ctx.ui.notify("Sandbox disabled via config", "info");
245
+ return;
246
+ }
247
+
248
+ const platform = process.platform;
249
+ if (platform !== "darwin" && platform !== "linux") {
250
+ sandboxEnabled = false;
251
+ ctx.ui.notify(`Sandbox not supported on ${platform}`, "warning");
252
+ return;
253
+ }
254
+
255
+ try {
256
+ const configExt = config as unknown as {
257
+ ignoreViolations?: Record<string, string[]>;
258
+ enableWeakerNestedSandbox?: boolean;
259
+ };
260
+
261
+ await SandboxManager.initialize({
262
+ network: config.network,
263
+ filesystem: config.filesystem,
264
+ ignoreViolations: configExt.ignoreViolations,
265
+ enableWeakerNestedSandbox: configExt.enableWeakerNestedSandbox,
266
+ });
267
+
268
+ sandboxEnabled = true;
269
+ sandboxInitialized = true;
270
+
271
+ const networkCount = config.network?.allowedDomains?.length ?? 0;
272
+ const writeCount = config.filesystem?.allowWrite?.length ?? 0;
273
+ ctx.ui.setStatus(
274
+ "sandbox",
275
+ ctx.ui.theme.fg("accent", `🔒 Sandbox: ${networkCount} domains, ${writeCount} write paths`),
276
+ );
277
+ ctx.ui.notify("Sandbox initialized", "info");
278
+ } catch (err) {
279
+ sandboxEnabled = false;
280
+ ctx.ui.notify(`Sandbox initialization failed: ${err instanceof Error ? err.message : err}`, "error");
281
+ }
282
+ });
283
+
284
+ pi.on("session_shutdown", async () => {
285
+ if (sandboxInitialized) {
286
+ try {
287
+ await SandboxManager.reset();
288
+ } catch {
289
+ // Ignore cleanup errors
290
+ }
291
+ }
292
+ });
293
+
294
+ pi.registerCommand("sandbox", {
295
+ description: "Show sandbox configuration",
296
+ handler: async (_args, ctx) => {
297
+ if (!sandboxEnabled) {
298
+ ctx.ui.notify("Sandbox is disabled", "info");
299
+ return;
300
+ }
301
+
302
+ const config = loadConfig(ctx.cwd);
303
+ const lines = [
304
+ "Sandbox Configuration:",
305
+ "",
306
+ "Network:",
307
+ ` Allowed: ${config.network?.allowedDomains?.join(", ") || "(none)"}`,
308
+ ` Denied: ${config.network?.deniedDomains?.join(", ") || "(none)"}`,
309
+ "",
310
+ "Filesystem:",
311
+ ` Deny Read: ${config.filesystem?.denyRead?.join(", ") || "(none)"}`,
312
+ ` Allow Write: ${config.filesystem?.allowWrite?.join(", ") || "(none)"}`,
313
+ ` Deny Write: ${config.filesystem?.denyWrite?.join(", ") || "(none)"}`,
314
+ ];
315
+ ctx.ui.notify(lines.join("\n"), "info");
316
+ },
317
+ });
318
+ }
@@ -0,0 +1,92 @@
1
+ {
2
+ "name": "pi-extension-sandbox",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "pi-extension-sandbox",
9
+ "version": "1.0.0",
10
+ "dependencies": {
11
+ "@anthropic-ai/sandbox-runtime": "^0.0.26"
12
+ }
13
+ },
14
+ "node_modules/@anthropic-ai/sandbox-runtime": {
15
+ "version": "0.0.26",
16
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.26.tgz",
17
+ "integrity": "sha512-DYV5LSsVMnzq0lbfaYMSpxZPUMAx4+hy343dRss+pVCLIfF62qOhxpYfZ5TmOk1GTDQm5f9wPprMNSStmnsV4w==",
18
+ "license": "Apache-2.0",
19
+ "dependencies": {
20
+ "@pondwader/socks5-server": "^1.0.10",
21
+ "@types/lodash-es": "^4.17.12",
22
+ "commander": "^12.1.0",
23
+ "lodash-es": "^4.17.21",
24
+ "shell-quote": "^1.8.3",
25
+ "zod": "^3.24.1"
26
+ },
27
+ "bin": {
28
+ "srt": "dist/cli.js"
29
+ },
30
+ "engines": {
31
+ "node": ">=18.0.0"
32
+ }
33
+ },
34
+ "node_modules/@pondwader/socks5-server": {
35
+ "version": "1.0.10",
36
+ "resolved": "https://registry.npmjs.org/@pondwader/socks5-server/-/socks5-server-1.0.10.tgz",
37
+ "integrity": "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==",
38
+ "license": "MIT"
39
+ },
40
+ "node_modules/@types/lodash": {
41
+ "version": "4.17.23",
42
+ "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.23.tgz",
43
+ "integrity": "sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA==",
44
+ "license": "MIT"
45
+ },
46
+ "node_modules/@types/lodash-es": {
47
+ "version": "4.17.12",
48
+ "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",
49
+ "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
50
+ "license": "MIT",
51
+ "dependencies": {
52
+ "@types/lodash": "*"
53
+ }
54
+ },
55
+ "node_modules/commander": {
56
+ "version": "12.1.0",
57
+ "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",
58
+ "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==",
59
+ "license": "MIT",
60
+ "engines": {
61
+ "node": ">=18"
62
+ }
63
+ },
64
+ "node_modules/lodash-es": {
65
+ "version": "4.17.22",
66
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.22.tgz",
67
+ "integrity": "sha512-XEawp1t0gxSi9x01glktRZ5HDy0HXqrM0x5pXQM98EaI0NxO6jVM7omDOxsuEo5UIASAnm2bRp1Jt/e0a2XU8Q==",
68
+ "license": "MIT"
69
+ },
70
+ "node_modules/shell-quote": {
71
+ "version": "1.8.3",
72
+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
73
+ "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
74
+ "license": "MIT",
75
+ "engines": {
76
+ "node": ">= 0.4"
77
+ },
78
+ "funding": {
79
+ "url": "https://github.com/sponsors/ljharb"
80
+ }
81
+ },
82
+ "node_modules/zod": {
83
+ "version": "3.25.76",
84
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
85
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
86
+ "license": "MIT",
87
+ "funding": {
88
+ "url": "https://github.com/sponsors/colinhacks"
89
+ }
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "pi-extension-sandbox",
3
+ "private": true,
4
+ "version": "1.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "clean": "echo 'nothing to clean'",
8
+ "build": "echo 'nothing to build'",
9
+ "check": "echo 'nothing to check'"
10
+ },
11
+ "pi": {
12
+ "extensions": [
13
+ "./index.ts"
14
+ ]
15
+ },
16
+ "dependencies": {
17
+ "@anthropic-ai/sandbox-runtime": "^0.0.26"
18
+ }
19
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pi-extension-with-deps",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pi-extension-with-deps",
9
- "version": "1.8.0",
9
+ "version": "1.9.0",
10
10
  "dependencies": {
11
11
  "ms": "^2.1.3"
12
12
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-extension-with-deps",
3
3
  "private": true,
4
- "version": "1.8.0",
4
+ "version": "1.9.0",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "clean": "echo 'nothing to clean'",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mariozechner/pi-coding-agent",
3
- "version": "0.44.0",
3
+ "version": "0.45.0",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {
@@ -39,9 +39,9 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "@mariozechner/clipboard": "^0.3.0",
42
- "@mariozechner/pi-agent-core": "^0.44.0",
43
- "@mariozechner/pi-ai": "^0.44.0",
44
- "@mariozechner/pi-tui": "^0.44.0",
42
+ "@mariozechner/pi-agent-core": "^0.45.0",
43
+ "@mariozechner/pi-ai": "^0.45.0",
44
+ "@mariozechner/pi-tui": "^0.45.0",
45
45
  "chalk": "^5.5.0",
46
46
  "cli-highlight": "^2.1.11",
47
47
  "diff": "^8.0.2",