Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
fix(execution): managed Git recipes work under the Linux sandbox
leen.zhoub66a658cd626
diff --git a/packages/execution/src/managed/managed-directories.ts b/packages/execution/src/managed/managed-directories.tsnew file mode 100644index 0000000..77e5479--- /dev/null+++ b/packages/execution/src/managed/managed-directories.ts@@ -0,0 +1,70 @@+import { lstat, mkdir, realpath, rmdir } from "node:fs/promises";+import { dirname } from "node:path";+import { within } from "../core/paths.ts";+import { ExecError } from "../core/types.ts";++async function present(path: string) {+ try {+ await lstat(path);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;+ throw error;+ }+}++/**+ * Linux only: bubblewrap can bind a write path only when it exists, and SRT drops an absent one,+ * leaving it read-only (`git worktree add` then cannot create its branch directory). The fixed+ * recipe names the directories its command will create; they are made here, one component at a+ * time beneath a held root, so the sandbox gets the same exact capability Seatbelt grants for an+ * absent literal path. Returns what was made, deepest last.+ */+export async function createRecipeDirectories(paths: string[], roots: string[]) {+ const created: string[] = [];+ try {+ for (const path of paths) {+ const missing: string[] = [];+ let at = path;+ while (!(await present(at))) {+ missing.unshift(at);+ const parent = dirname(at);+ if (parent === at) throw new ExecError("outside_workplace");+ at = parent;+ }+ if (!missing.length) continue;+ // The existing ancestor must be a real directory inside a held root, not a link out of it.+ if (+ !roots.some((root) => within(root, at)) ||+ !(await lstat(at)).isDirectory() ||+ (await realpath(at)) !== at+ )+ throw new ExecError("outside_workplace", "write_path_alias");+ for (const directory of missing) {+ // Not recursive: a name that appeared meanwhile (EEXIST) is not ours to trust.+ await mkdir(directory);+ created.push(directory);+ if (!(await lstat(directory)).isDirectory() || (await realpath(directory)) !== directory)+ throw new ExecError("outside_workplace", "write_path_alias");+ }+ }+ return created;+ } catch (error) {+ await removeRecipeDirectories(created);+ throw error;+ }+}++/** Undoes createRecipeDirectories after a failed recipe; directories the command filled stay. */+export async function removeRecipeDirectories(created: string[]) {+ for (const directory of [...created].reverse()) {+ try {+ await rmdir(directory);+ } catch (error) {+ // Filled by the command (its own state now) or already gone: either way nothing of ours+ // is left to remove, and the recipe's own error is what the caller reports.+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== "ENOTEMPTY" && code !== "EEXIST" && code !== "ENOENT") throw error;+ }+ }+}diff --git a/packages/execution/src/managed/managed-git.ts b/packages/execution/src/managed/managed-git.tsindex 7423183..67749aa 100644--- a/packages/execution/src/managed/managed-git.ts+++ b/packages/execution/src/managed/managed-git.ts@@ -295,6 +295,7 @@ export function createManagedGit(options: ExecOptions) {cwd: string,identities: ManagedPathIdentity[],writes: string[],+ creates: string[] = [],denies: string[] = [];if (operation.kind === "create") {if (@@ -338,6 +339,8 @@ export function createManagedGit(options: ExecOptions) {join(source.common.path, "logs", "refs", "heads", "pibot"),join(source.common.path, "packed-refs.lock"),];+ // packed-refs.lock is a file Git takes only to delete a packed ref; it stays absent.+ creates = writes.slice(0, 4);} else if (operation.kind === "integrate") {const target = operation.target;if (operation.allowMerge) {@@ -382,6 +385,7 @@ export function createManagedGit(options: ExecOptions) {join(source.common.path, "refs", "heads"),join(source.common.path, "logs", "refs", "heads"),];+ creates = [join(source.common.path, "logs", "refs", "heads")];} else {const target = operation.worktree;if (@@ -429,10 +433,12 @@ export function createManagedGit(options: ExecOptions) {? [operation.integratedInto.root, operation.integratedInto.git]: []),];+ // bubblewrap makes every write path its own bind mount, and a mount point cannot be+ // deleted (EBUSY). On Linux the tree and its admin folder are writable through their parents+ // only; the capability is the same, since parent and `worktrees` already hold them.writes = [operation.parent.path,- target.root.path,- target.git.path,+ ...(options.platform === "linux" ? [] : [target.root.path, target.git.path]),join(source.common.path, "worktrees"),];}@@ -486,6 +492,7 @@ export function createManagedGit(options: ExecOptions) {cwd: join(options.tempDir, "managed-operations"),identities,writePaths: writes,+ createDirectories: creates,denyPaths: denies,command,...(options.platform === "win32"@@ -666,6 +673,12 @@ export function createManagedGit(options: ExecOptions) {]: []),],+ // `git pack-refs` (gc) removes emptied loose-ref directories; the branch may need them back.+ createDirectories: [+ join(repository.common.path, "refs", "heads", "pibot"),+ join(repository.common.path, "logs", "refs", "heads", "pibot"),+ ...(syncing ? [join(repository.common.path, "refs", "pibot-sync")] : []),+ ],denyPaths: [join(repository.common.path, "config"), join(repository.common.path, "hooks")],command,...(windowsSteps ? { windowsSteps } : {}),diff --git a/packages/execution/src/managed/managed-recipe.ts b/packages/execution/src/managed/managed-recipe.tsindex 1ed7af2..8d6d93c 100644--- a/packages/execution/src/managed/managed-recipe.ts+++ b/packages/execution/src/managed/managed-recipe.ts@@ -6,11 +6,13 @@ import { dirname, join, relative, sep } from "node:path";import { commandEnvironment } from "../command/environment.ts";import { executeHostedCommand } from "../command/foreground-host.ts";import { executeProcess } from "../command/process.ts";+import { within } from "../core/paths.ts";import { ExecError, type ExecOptions } from "../core/types.ts";import { gitDefaultWriteDenies } from "../git/git-init-sandbox.ts";import { createSandboxConfig } from "../sandbox/sandbox-config.ts";import { sensitiveReadBoundary } from "../sandbox/sensitive-paths.ts";import { holdManagedPaths, type ManagedPathIdentity } from "./managed-boundary.ts";+import { createRecipeDirectories, removeRecipeDirectories } from "./managed-directories.ts";import { managedIdentityStrategy } from "./managed-identity.ts";export interface ManagedRecipe {@@ -29,6 +31,11 @@ export interface ManagedRecipe {network?: import("../core/types.ts").NetworkSettings;returnFailure?: boolean;writePaths: string[];+ /**+ * Write paths that are directories the command itself would create (a new worktree, a branch+ * namespace). Linux makes the absent ones first, because bubblewrap binds only existing paths.+ */+ createDirectories?: string[];readPaths?: string[];denyPaths?: string[];removedPaths?: string[];@@ -42,7 +49,11 @@ export interface ManagedRecipe {export async function runManagedRecipe(options: ExecOptions, input: ManagedRecipe) {if (!["darwin", "linux", "win32"].includes(options.platform))throw new ExecError("isolation_unavailable");- if (typeof input.assertAuthorized !== "function" || !input.identities.length)+ if (+ typeof input.assertAuthorized !== "function" ||+ !input.identities.length ||+ input.createDirectories?.some((path) => !input.writePaths.includes(path))+ )throw new ExecError("invalid_input");if (input.privateRecovery) {const recoveryParent = dirname(input.privateRecovery);@@ -143,55 +154,79 @@ export async function runManagedRecipe(options: ExecOptions, input: ManagedRecipif (!result) throw new ExecError("invalid_input");return result;}- const sandbox = createSandboxConfig(options);- const config = await sandbox.config(- input.identities.map((value) => value.path),- input.network ?? { allowAll: false, domains: [] },- signal,- { botHome: input.home, dataDir: input.dataDir },- );- // Replace the broad setup roots with exact recipe capabilities. Never expose this profile to runCommand.- config.filesystem.allowWrite = [- ...input.writePaths,- ...(input.privateJournal ? [input.privateJournal] : []),- ...(input.privateRecovery ? [input.privateRecovery] : []),- ].map((path) => ({ path, literal: true }));- // The fixed recipe replaced the ordinary command roots; no broad manifest class survives.- config.filesystem.gitManifestWriteRoots = [];- config.filesystem.allowRead ??= [];- config.filesystem.allowRead.push(- ...[- ...(input.readPaths ?? []),+ // Seatbelt grants an absent literal path as is; only bubblewrap needs it made first.+ const created =+ options.platform === "linux"+ ? await createRecipeDirectories(+ input.createDirectories ?? [],+ input.identities.map((value) => value.path),+ )+ : [];+ let succeeded = false;+ try {+ const sandbox = createSandboxConfig(options);+ const config = await sandbox.config(+ input.identities.map((value) => value.path),+ input.network ?? { allowAll: false, domains: [] },+ signal,+ { botHome: input.home, dataDir: input.dataDir },+ );+ // Replace the broad setup roots with exact recipe capabilities. Never expose this profile to runCommand.+ config.filesystem.allowWrite = [+ ...input.writePaths,+ ...(input.privateJournal ? [input.privateJournal] : []),...(input.privateRecovery ? [input.privateRecovery] : []),- ].map((path) => ({ path, literal: true as const })),- );- config.filesystem.denyWrite.push(- ...[...(input.denyPaths ?? []), ...(await gitDefaultWriteDenies(input.writePaths))].map(- (path) => ({ path, literal: true as const }),- ),- );- const env = commandEnvironment(options.platform, options.env, input.home, options.tempDir);- const result = await executeHostedCommand({- options,- config,- allowAll: false,- command: input.command,- commandText: input.label,- commandId: id,- cwd: input.cwd,- env,- signal,- log,- dispatch: input.assertAuthorized,- prepared: async () => {- await held.check();- await input.beforeDispatch?.();- await held.check();- },- });- await held.check(new Set(input.removedPaths));- if (result.exitCode !== 0 && !input.returnFailure) throw new ExecError("command_failed");- return result;+ ].map((path) => ({ path, literal: true }));+ // The fixed recipe replaced the ordinary command roots; no broad manifest class survives.+ config.filesystem.gitManifestWriteRoots = [];+ config.filesystem.allowRead ??= [];+ config.filesystem.allowRead.push(+ ...[+ ...(input.readPaths ?? []),+ ...(input.privateRecovery ? [input.privateRecovery] : []),+ ].map((path) => ({ path, literal: true as const })),+ );+ // Linux scans every root for `.git` entries and pins each with a bind mount (or a+ // placeholder for an absent one). Inside a tree this fixed recipe deletes, those mounts+ // make the deletion fail with EBUSY; the tree goes as a whole, so pinning it guards nothing.+ if (options.platform === "linux" && input.removedPaths?.length) {+ const removed = input.removedPaths;+ config.filesystem.denyWrite = config.filesystem.denyWrite.filter(+ (entry) =>+ typeof entry === "string" || !removed.some((root) => within(root, entry.path)),+ );+ }+ config.filesystem.denyWrite.push(+ ...[...(input.denyPaths ?? []), ...(await gitDefaultWriteDenies(input.writePaths))].map(+ (path) => ({ path, literal: true as const }),+ ),+ );+ const env = commandEnvironment(options.platform, options.env, input.home, options.tempDir);+ const result = await executeHostedCommand({+ options,+ config,+ allowAll: false,+ command: input.command,+ commandText: input.label,+ commandId: id,+ cwd: input.cwd,+ env,+ signal,+ log,+ dispatch: input.assertAuthorized,+ prepared: async () => {+ await held.check();+ await input.beforeDispatch?.();+ await held.check();+ },+ });+ await held.check(new Set(input.removedPaths));+ if (result.exitCode !== 0 && !input.returnFailure) throw new ExecError("command_failed");+ succeeded = result.exitCode === 0;+ return result;+ } finally {+ if (!succeeded) await removeRecipeDirectories(created);+ }} finally {log.end();}