index.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. * Note: this example intentionally overrides the built-in `bash` tool to show
  9. * how built-in tools can be replaced. Alternatively, you could sandbox `bash`
  10. * via `tool_call` input mutation without replacing the tool.
  11. *
  12. * Config files (merged, project takes precedence):
  13. * - ~/.pi/agent/extensions/sandbox.json (global)
  14. * - <cwd>/.pi/sandbox.json (project-local)
  15. *
  16. * Example .pi/sandbox.json:
  17. * ```json
  18. * {
  19. * "enabled": true,
  20. * "network": {
  21. * "allowedDomains": ["github.com", "*.github.com"],
  22. * "deniedDomains": []
  23. * },
  24. * "filesystem": {
  25. * "denyRead": ["~/.ssh", "~/.aws"],
  26. * "allowWrite": [".", "/tmp"],
  27. * "denyWrite": [".env"]
  28. * }
  29. * }
  30. * ```
  31. *
  32. * Usage:
  33. * - `pi -e ./sandbox` - sandbox enabled with default/config settings
  34. * - `pi -e ./sandbox --no-sandbox` - disable sandboxing
  35. * - `/sandbox` - show current sandbox configuration
  36. *
  37. * Setup:
  38. * 1. Copy sandbox/ directory to ~/.pi/agent/extensions/
  39. * 2. Run `npm install` in ~/.pi/agent/extensions/sandbox/
  40. *
  41. * Linux also requires: bubblewrap, socat, ripgrep
  42. */
  43. import { spawn } from "node:child_process";
  44. import { existsSync, readFileSync } from "node:fs";
  45. import { join } from "node:path";
  46. import { SandboxManager, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
  47. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  48. import { type BashOperations, createBashTool, getAgentDir } from "@earendil-works/pi-coding-agent";
  49. interface SandboxConfig extends SandboxRuntimeConfig {
  50. enabled?: boolean;
  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. function loadConfig(cwd: string): SandboxConfig {
  76. const projectConfigPath = join(cwd, ".pi", "sandbox.json");
  77. const globalConfigPath = join(getAgentDir(), "extensions", "sandbox.json");
  78. let globalConfig: Partial<SandboxConfig> = {};
  79. let projectConfig: Partial<SandboxConfig> = {};
  80. if (existsSync(globalConfigPath)) {
  81. try {
  82. globalConfig = JSON.parse(readFileSync(globalConfigPath, "utf-8"));
  83. } catch (e) {
  84. console.error(`Warning: Could not parse ${globalConfigPath}: ${e}`);
  85. }
  86. }
  87. if (existsSync(projectConfigPath)) {
  88. try {
  89. projectConfig = JSON.parse(readFileSync(projectConfigPath, "utf-8"));
  90. } catch (e) {
  91. console.error(`Warning: Could not parse ${projectConfigPath}: ${e}`);
  92. }
  93. }
  94. return deepMerge(deepMerge(DEFAULT_CONFIG, globalConfig), projectConfig);
  95. }
  96. function deepMerge(base: SandboxConfig, overrides: Partial<SandboxConfig>): SandboxConfig {
  97. const result: SandboxConfig = { ...base };
  98. if (overrides.enabled !== undefined) result.enabled = overrides.enabled;
  99. if (overrides.network) {
  100. result.network = { ...base.network, ...overrides.network };
  101. }
  102. if (overrides.filesystem) {
  103. result.filesystem = { ...base.filesystem, ...overrides.filesystem };
  104. }
  105. const extOverrides = overrides as {
  106. ignoreViolations?: Record<string, string[]>;
  107. enableWeakerNestedSandbox?: boolean;
  108. };
  109. const extResult = result as { ignoreViolations?: Record<string, string[]>; enableWeakerNestedSandbox?: boolean };
  110. if (extOverrides.ignoreViolations) {
  111. extResult.ignoreViolations = extOverrides.ignoreViolations;
  112. }
  113. if (extOverrides.enableWeakerNestedSandbox !== undefined) {
  114. extResult.enableWeakerNestedSandbox = extOverrides.enableWeakerNestedSandbox;
  115. }
  116. return result;
  117. }
  118. function createSandboxedBashOps(): BashOperations {
  119. return {
  120. async exec(command, cwd, { onData, signal, timeout }) {
  121. if (!existsSync(cwd)) {
  122. throw new Error(`Working directory does not exist: ${cwd}`);
  123. }
  124. const wrappedCommand = await SandboxManager.wrapWithSandbox(command);
  125. return new Promise((resolve, reject) => {
  126. const child = spawn("bash", ["-c", wrappedCommand], {
  127. cwd,
  128. detached: true,
  129. stdio: ["ignore", "pipe", "pipe"],
  130. });
  131. let timedOut = false;
  132. let timeoutHandle: NodeJS.Timeout | undefined;
  133. if (timeout !== undefined && timeout > 0) {
  134. timeoutHandle = setTimeout(() => {
  135. timedOut = true;
  136. if (child.pid) {
  137. try {
  138. process.kill(-child.pid, "SIGKILL");
  139. } catch {
  140. child.kill("SIGKILL");
  141. }
  142. }
  143. }, timeout * 1000);
  144. }
  145. child.stdout?.on("data", onData);
  146. child.stderr?.on("data", onData);
  147. child.on("error", (err) => {
  148. if (timeoutHandle) clearTimeout(timeoutHandle);
  149. reject(err);
  150. });
  151. const onAbort = () => {
  152. if (child.pid) {
  153. try {
  154. process.kill(-child.pid, "SIGKILL");
  155. } catch {
  156. child.kill("SIGKILL");
  157. }
  158. }
  159. };
  160. signal?.addEventListener("abort", onAbort, { once: true });
  161. child.on("close", (code) => {
  162. if (timeoutHandle) clearTimeout(timeoutHandle);
  163. signal?.removeEventListener("abort", onAbort);
  164. if (signal?.aborted) {
  165. reject(new Error("aborted"));
  166. } else if (timedOut) {
  167. reject(new Error(`timeout:${timeout}`));
  168. } else {
  169. resolve({ exitCode: code });
  170. }
  171. });
  172. });
  173. },
  174. };
  175. }
  176. export default function (pi: ExtensionAPI) {
  177. pi.registerFlag("no-sandbox", {
  178. description: "Disable OS-level sandboxing for bash commands",
  179. type: "boolean",
  180. default: false,
  181. });
  182. const localCwd = process.cwd();
  183. const localBash = createBashTool(localCwd);
  184. let sandboxEnabled = false;
  185. let sandboxInitialized = false;
  186. pi.registerTool({
  187. ...localBash,
  188. label: "bash (sandboxed)",
  189. async execute(id, params, signal, onUpdate, _ctx) {
  190. if (!sandboxEnabled || !sandboxInitialized) {
  191. return localBash.execute(id, params, signal, onUpdate);
  192. }
  193. const sandboxedBash = createBashTool(localCwd, {
  194. operations: createSandboxedBashOps(),
  195. });
  196. return sandboxedBash.execute(id, params, signal, onUpdate);
  197. },
  198. });
  199. pi.on("user_bash", () => {
  200. if (!sandboxEnabled || !sandboxInitialized) return;
  201. return { operations: createSandboxedBashOps() };
  202. });
  203. pi.on("session_start", async (_event, ctx) => {
  204. const noSandbox = pi.getFlag("no-sandbox") as boolean;
  205. if (noSandbox) {
  206. sandboxEnabled = false;
  207. ctx.ui.notify("Sandbox disabled via --no-sandbox", "warning");
  208. return;
  209. }
  210. const config = loadConfig(ctx.cwd);
  211. if (!config.enabled) {
  212. sandboxEnabled = false;
  213. ctx.ui.notify("Sandbox disabled via config", "info");
  214. return;
  215. }
  216. const platform = process.platform;
  217. if (platform !== "darwin" && platform !== "linux") {
  218. sandboxEnabled = false;
  219. ctx.ui.notify(`Sandbox not supported on ${platform}`, "warning");
  220. return;
  221. }
  222. try {
  223. const configExt = config as unknown as {
  224. ignoreViolations?: Record<string, string[]>;
  225. enableWeakerNestedSandbox?: boolean;
  226. };
  227. await SandboxManager.initialize({
  228. network: config.network,
  229. filesystem: config.filesystem,
  230. ignoreViolations: configExt.ignoreViolations,
  231. enableWeakerNestedSandbox: configExt.enableWeakerNestedSandbox,
  232. });
  233. sandboxEnabled = true;
  234. sandboxInitialized = true;
  235. const networkCount = config.network?.allowedDomains?.length ?? 0;
  236. const writeCount = config.filesystem?.allowWrite?.length ?? 0;
  237. ctx.ui.setStatus(
  238. "sandbox",
  239. ctx.ui.theme.fg("accent", `🔒 Sandbox: ${networkCount} domains, ${writeCount} write paths`),
  240. );
  241. ctx.ui.notify("Sandbox initialized", "info");
  242. } catch (err) {
  243. sandboxEnabled = false;
  244. ctx.ui.notify(`Sandbox initialization failed: ${err instanceof Error ? err.message : err}`, "error");
  245. }
  246. });
  247. pi.on("session_shutdown", async () => {
  248. if (sandboxInitialized) {
  249. try {
  250. await SandboxManager.reset();
  251. } catch {
  252. // Ignore cleanup errors
  253. }
  254. }
  255. });
  256. pi.registerCommand("sandbox", {
  257. description: "Show sandbox configuration",
  258. handler: async (_args, ctx) => {
  259. if (!sandboxEnabled) {
  260. ctx.ui.notify("Sandbox is disabled", "info");
  261. return;
  262. }
  263. const config = loadConfig(ctx.cwd);
  264. const lines = [
  265. "Sandbox Configuration:",
  266. "",
  267. "Network:",
  268. ` Allowed: ${config.network?.allowedDomains?.join(", ") || "(none)"}`,
  269. ` Denied: ${config.network?.deniedDomains?.join(", ") || "(none)"}`,
  270. "",
  271. "Filesystem:",
  272. ` Deny Read: ${config.filesystem?.denyRead?.join(", ") || "(none)"}`,
  273. ` Allow Write: ${config.filesystem?.allowWrite?.join(", ") || "(none)"}`,
  274. ` Deny Write: ${config.filesystem?.denyWrite?.join(", ") || "(none)"}`,
  275. ];
  276. ctx.ui.notify(lines.join("\n"), "info");
  277. },
  278. });
  279. }