Open source CapCut alternative.
TypeScript
feat(app): confine task-work spawns to a kernel sandbox, gate out-of-folder writes on consent
David Le4baf273b609f
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex 0e9dc431..18863ca5 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -463,14 +463,15 @@ public enum DonkeyPrompts {a long note/document, generate with llm.generate toFile=true and assemble from the returnedfile — a big task always fits this way.- The `workspace` line under Known state names your working directory (full path shown), and your- shell runs there. Tools and reads may use bare names (`out.pdf`) — they land in it. But a file- move/copy/make/remove (mv, cp, mkdir, rm, chmod) runs WITHOUT asking only when every path is- written in full inside the workspace (so no `cd` needed): `mv "<workspace>/a.pdf"- "<workspace>/done/a.pdf"`, and a clean-up chain like `… && rm "<workspace>/tmp"` is fine too. A- bare name, `.`, `*`, `$VAR`, or a path outside the workspace makes it ask first. Pull inputs the- same way (`cp "<abs input>" "<workspace>/"`),- reuse this folder on follow-ups (`ls` to reconcile), and save elsewhere only when the user names- a location.+ shell runs there. Tools and reads may use bare names (`out.pdf`) — they land in it. Your file+ moves/copies/makes/removes (mv, cp, mkdir, rm, chmod) run without asking ONLY inside this folder,+ written in full: `mv "<workspace>/a.pdf" "<workspace>/done/a.pdf"`. The same command aimed at a+ file anywhere else asks the user first — that is expected, so do it when the task needs it. Reads+ are always free. Pull inputs with `cp "<abs input>" "<workspace>/"` and reuse this folder on+ follow-ups (`ls` to reconcile).+ - Never overwrite an existing user file unless the user explicitly asked ("save it back", "in+ place", "replace it"). Otherwise write a new copy or alternate version (`<name>-filled.pdf`,+ `<name>-v2.png`) and leave the original untouched.- The `workspace.files` line already shows the contents of the small files in that folder; acton them directly.- A question or chit-chat turn: answer with conversation.respond (set input.response), thendiff --git a/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift b/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swiftindex 541f893e..886e277f 100644--- a/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift+++ b/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift@@ -105,6 +105,13 @@ public struct ConversationWorkspace: Codable, Equatable, Sendable {/// Fact key for the machine-readable resolve directory, read by file-writing executors and hidden/// from the planner's prose facts dump.public static let baseDirFactKey = "workspace.baseDir"+ /// Fact key for the machine-readable workspace ROOT — the seatbelt jail's writable root, read at each+ /// task-work spawn to confine the tool. The stable owned folder, NOT `baseDir`, which can narrow to a+ /// subfolder and would then wrongly fence off the root. Hidden from the planner's prose facts dump.+ public static let rootDirFactKey = "workspace.rootDir"+ /// Fact key for the `\n`-joined declared input paths (the user's attachments / named files), read at+ /// each spawn to allow-list reads under the jail. Hidden from the planner's prose facts dump.+ public static let inputPathsFactKey = "workspace.inputPaths"/// Fact key for the inlined contents of the small text files in the working directory, surfaced to the/// planner every step so it never re-opens its own small inputs (the data file it copied in, a map it/// wrote). Sorts right after `workspace`, so it reads as part of the workspace block.diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex 7f179d0d..0cbe9419 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -384,6 +384,9 @@ public struct HarnessMediaCutRequest: Sendable {public var fillerWords: [String]/// Caller-judged removal spans as `"start-end,start-end"` seconds (e.g. a discourse "like").public var explicitRemovals: String?+ /// The conversation's workspace folder, so the engine confines its ffmpeg spawns there (the seatbelt+ /// jail) and lands the cut output inside it rather than beside an input that may sit outside the folder.+ public var workingDirectory: String?public init(inputPath: String,@@ -392,7 +395,8 @@ public struct HarnessMediaCutRequest: Sendable {removeSilence: Bool = false,transcriptPath: String? = nil,fillerWords: [String] = [],- explicitRemovals: String? = nil+ explicitRemovals: String? = nil,+ workingDirectory: String? = nil) {self.inputPath = inputPathself.outputPath = outputPath@@ -401,6 +405,7 @@ public struct HarnessMediaCutRequest: Sendable {self.transcriptPath = transcriptPathself.fillerWords = fillerWordsself.explicitRemovals = explicitRemovals+ self.workingDirectory = workingDirectory}}@@ -2409,7 +2414,8 @@ public enum BuiltInHarnessToolExecutors {removeSilence: removeSilence,transcriptPath: transcriptPath,fillerWords: fillerWords,- explicitRemovals: explicit+ explicitRemovals: explicit,+ workingDirectory: context.worldModel.facts[ConversationWorkspace.baseDirFactKey])guard let result = await cutter(request) else {return failed(context, "The media-cut engine is unavailable right now.", reason: "mediaCutterUnavailable")diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swiftindex 007b8358..3aef897b 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessContracts.swift@@ -173,6 +173,8 @@ public struct HarnessWorldModel: Codable, Equatable, Sendable {/// hidden everywhere at once instead of in separate hand-maintained filters that drift apart.public static let modelHiddenFactKeys: Set<String> = [ConversationWorkspace.baseDirFactKey,+ ConversationWorkspace.rootDirFactKey,+ ConversationWorkspace.inputPathsFactKey,HarnessAgentCoordinator.additionalInstructionsFactKey]diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swiftindex f55ee9b6..1a1b905c 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift@@ -726,13 +726,23 @@ public actor HarnessAgentCoordinator {let workspace = await conversationWorkspace(conversationID: task.conversationID) else { return }let newSummary = workspace.plannerSummary()let newBase = workspace.currentBaseDirectory.flatMap { $0.isEmpty ? nil : $0 }+ // The seatbelt jail's writable root (the stable owned folder) and the declared input paths it+ // allow-lists for reads — projected into facts so each task-work spawn can build its policy. Inputs+ // are `\n`-joined; a path containing a newline would corrupt the list, so drop any (paths never do).+ let newRoot = workspace.root.flatMap { $0.isEmpty ? nil : $0 }+ let inputs = workspace.attachments.map(\.path).filter { !$0.contains("\n") }+ let newInputs = inputs.isEmpty ? nil : inputs.joined(separator: "\n")// Per-step bookkeeping runs every planning iteration. Persisting re-serializes the WHOLE- // conversation store to disk, so skip it when neither workspace fact actually changed — otherwise a+ // conversation store to disk, so skip it when no workspace fact actually changed — otherwise a// long run does one redundant full-store write per step, growing with conversation size.guard task.worldModel.facts[ConversationWorkspace.summaryFactKey] != newSummary- || task.worldModel.facts[ConversationWorkspace.baseDirFactKey] != newBase else { return }+ || task.worldModel.facts[ConversationWorkspace.baseDirFactKey] != newBase+ || task.worldModel.facts[ConversationWorkspace.rootDirFactKey] != newRoot+ || task.worldModel.facts[ConversationWorkspace.inputPathsFactKey] != newInputs else { return }task.worldModel.facts[ConversationWorkspace.summaryFactKey] = newSummarytask.worldModel.facts[ConversationWorkspace.baseDirFactKey] = newBase+ task.worldModel.facts[ConversationWorkspace.rootDirFactKey] = newRoot+ task.worldModel.facts[ConversationWorkspace.inputPathsFactKey] = newInputstask.updatedAt = Date()tasksByID[agentID] = taskawait conversationStore?.upsertAgentSnapshot(task)diff --git a/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swiftindex 4b9b112b..c693db3b 100644--- a/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swift@@ -26,21 +26,23 @@ public struct CaptionOrchestrator: Sendable {private let translateCues: TranslateCuesprivate let transcribe: Transcribe- private let runTool: MediaPipeline.ToolRunner+ private let makeRunTool: @Sendable (SandboxPolicy?) -> MediaPipeline.ToolRunnerpublic init(translateCues: @escaping TranslateCues,transcribe: @escaping Transcribe,- runTool: @escaping MediaPipeline.ToolRunner = MediaPipeline.bundledToolRunner+ makeRunTool: @escaping @Sendable (SandboxPolicy?) -> MediaPipeline.ToolRunner = MediaPipeline.sandboxedRunner) {self.translateCues = translateCuesself.transcribe = transcribe- self.runTool = runTool+ self.makeRunTool = makeRunTool}public func caption(_ request: HarnessCaptionRequest) async -> HarnessCaptionOutcome {let workdir = DonkeyCommandBackends.resolvedWorkingDirectoryPath(request.workingDirectory)func path(_ name: String) -> String { (workdir as NSString).appendingPathComponent(name) }+ // Every bundled-tool spawn for this run is confined to the workspace (with the source readable).+ let runTool = makeRunTool(SandboxPolicy.forWorkspace(baseDirectory: request.workingDirectory, localSource: request.source))let startSec = request.clipStart.flatMap(Self.parseSeconds)let durationSec = request.clipDuration.flatMap(Self.parseSeconds)@@ -48,7 +50,7 @@ public struct CaptionOrchestrator: Sendable {// 1. Resolve to a local video, applying the requested span as we go (a URL span downloads only that// range; a local span is trimmed with an accurate re-encode, never `-c copy`).let base: String- switch resolveBase(request.source, startSec: startSec, durationSec: durationSec, workdir: workdir, makePath: path) {+ switch resolveBase(request.source, startSec: startSec, durationSec: durationSec, workdir: workdir, makePath: path, using: runTool) {case .ok(let resolved): base = resolvedcase .failed(let reason): return Self.fail(reason)}@@ -115,7 +117,7 @@ public struct CaptionOrchestrator: Sendable {private func resolveBase(_ source: String, startSec: Double?, durationSec: Double?, workdir: String,- makePath: (String) -> String+ makePath: (String) -> String, using runTool: MediaPipeline.ToolRunner) -> MediaStepResult {let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)let lower = trimmed.lowercased()diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 4d204b23..6beb5c38 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -299,6 +299,31 @@ public enum DonkeyCommandBackends {return (value?.isEmpty == false) ? value : nil}+ /// The folders Donkey created for this conversation — its workspace root and current base directory.+ /// Read from the typed workspace facts, never user text. These are the only places a file mutation runs+ /// WITHOUT a consent prompt; a write anywhere else is the user's to approve.+ private static func ownedRoots(_ context: HarnessToolExecutionContext) -> [String] {+ let facts = context.worldModel.facts+ let root = facts[ConversationWorkspace.rootDirFactKey].flatMap { $0.isEmpty ? nil : $0 }+ let base = facts[ConversationWorkspace.baseDirFactKey].flatMap { $0.isEmpty ? nil : $0 }+ var roots: [String] = []+ if let root { roots.append(root) }+ if let base, base != root { roots.append(base) }+ return roots+ }++ /// The seatbelt policy confining a shell spawn. Reads are open (the consent classifier already treats+ /// reads as free); writes are confined by the consent outcome. An UNPROMPTED command (a read, or a+ /// bounded mutator whose operands all sit in an owned folder) is held to the owned folders. A command+ /// the user APPROVED at a prompt also gets their home directory writable, so the approved write lands —+ /// the kernel still blocks `/System`, `/usr`, and other users. `nil` when no folder is owned yet, so the+ /// spawn runs unconfined exactly as before the jail existed; the consent prompt is the gate there.+ private static func shellPolicy(owned: [String], consented: Bool) -> SandboxPolicy? {+ guard !owned.isEmpty else { return nil }+ let writable = consented ? owned + [FileManager.default.homeDirectoryForCurrentUser.path] : owned+ return SandboxPolicy(writableRoots: writable, readableRoots: [], allowNetwork: true, allowAllReads: true)+ }+/// Resolve `image_render`'s `htmlPath` to a URL ALWAYS inside the workspace `baseDir` (or `~/Downloads`/// when none is set). image_render runs with no consent prompt and its `htmlPath` can be steered by/// content the model ingested, so — exactly like `resolveOutputDestination` on the output side — an@@ -741,11 +766,23 @@ public enum DonkeyCommandBackends {)}- // Classify by risk tier. Reads run immediately; anything that changes- // state needs consent (allow-once / always-allow) unless it was already- // granted. Nothing is silently refused.+ // Run from the conversation's working directory when one exists, so relative reads/writes land in+ // the agent's own folder instead of the home root; falls back to home for a run without a workspace.+ let workingDirectory = workspaceBaseDir(context)+ let owned = ownedRoots(context)++ // Decide consent. A command runs UNPROMPTED when it is a read, or a bounded file mutator whose every+ // operand sits inside a folder Donkey created — managing its own folder is not the user's to approve.+ // Anything else (a mutation reaching a user file, an interpreter, a network tool) prompts first;+ // nothing is silently refused.let classification = ShellCommandClassifier.classify(command)- if classification.tier != .read {+ let unprompted = classification.tier == .read+ || ShellCommandClassifier.everySegmentMutatesOnlyOwnedRoots(+ command,+ ownedRoots: owned,+ workingDirectory: workingDirectory ?? FileManager.default.homeDirectoryForCurrentUser.path+ )+ if !unprompted {if let gate = await consentGate(context, command: command, classification: classification) {return gate}@@ -753,11 +790,11 @@ public enum DonkeyCommandBackends {let timeout = context.call.input["timeoutSeconds"].flatMap(Double.init).map { min(max($0, 1), shellTimeoutMax) } ?? shellTimeout- // Run from the conversation's working directory when one exists, so relative reads/writes land in- // the agent's own folder instead of the home root; falls back to home for a run without a workspace.- let workingDirectory = workspaceBaseDir(context)+ // Confine the spawn (kernel-enforced): reads open, writes held to the owned folders — plus the user's+ // home when they approved this command at a prompt, so the approved write lands. nil → no folder yet.+ let policy = shellPolicy(owned: owned, consented: !unprompted)let result = await Task.detached(priority: .userInitiated) {- runShellSync(command, timeout: timeout, workingDirectory: workingDirectory)+ runShellSync(command, timeout: timeout, workingDirectory: workingDirectory, policy: policy)}.valuelet stdout = boundedOutput(result.stdout)@@ -889,18 +926,6 @@ public enum DonkeyCommandBackends {let store = ShellPermissionPolicyStore.sharedlet signature = classification.signature- // The agent doesn't ask permission to change files in the dedicated folder it owns. File commands- // (cp, mkdir, mv, tee, rm, chmod, …) run unprompted ONLY when EVERY command in the line is a bare- // bounded mutator whose every file operand is written as an explicit path inside the conversation's- // workspace — so a move-then-clean-up chain (`mv … && rm …`) is fine, but a wrapper, a `$`/`..`/- // glob/bare name, or any non-mutator segment (see `isUnpromptedWorkspaceMutation`) makes the whole- // line fall through to the normal consent prompt.- if (classification.tier == .reversibleWrite || classification.tier == .highRisk),- let workspace = workspaceBaseDir(context),- ShellCommandClassifier.isUnpromptedWorkspaceMutation(command, workspace: workspace) {- return nil- }-var allowed = falseif classification.tier != .highRisk {allowed = await store.isAlwaysAllowed(signature)@@ -1024,12 +1049,24 @@ public enum DonkeyCommandBackends {private static func runShellSync(_ command: String,timeout: TimeInterval,- workingDirectory: String? = nil+ workingDirectory: String? = nil,+ policy: SandboxPolicy? = nil) -> ShellResult {let process = Process()- process.executableURL = URL(fileURLWithPath: "/bin/zsh")- process.arguments = ["-c", command]- process.environment = shellEnvironment()+ // Under a policy, the command runs inside the seatbelt jail (writes confined to the owned folder,+ // plus home when consent approved it; reads open) with TMPDIR corralled into the folder. A nil+ // policy is a passthrough, so a run without an owned folder behaves exactly as before.+ let environment = WorkspaceSandbox.childEnvironment(shellEnvironment(), policy: policy)+ let (executable, arguments) = WorkspaceSandbox.wrap(+ executable: URL(fileURLWithPath: "/bin/zsh"),+ arguments: ["-c", command],+ policy: policy,+ environment: environment,+ bundledToolsDir: bundledToolsDirectory?.path+ )+ process.executableURL = executable+ process.arguments = arguments+ process.environment = environmentprocess.currentDirectoryURL = resolvedWorkingDirectory(workingDirectory)let output = runProcess(process, timeout: timeout)return ShellResult(@@ -1051,7 +1088,8 @@ public enum DonkeyCommandBackends {public static func runBundledTool(_ name: String,_ arguments: [String],- workingDirectory: String?+ workingDirectory: String?,+ policy: SandboxPolicy? = nil) -> (exitCode: Int32, stdout: String, stderr: String) {guard let directory = bundledToolsDirectory else {return (127, "", "Bundled tools directory is unavailable, so '\(name)' cannot run.")@@ -1061,9 +1099,19 @@ public enum DonkeyCommandBackends {return (127, "", "Bundled tool '\(name)' is missing from \(directory.path).")}let process = Process()- process.executableURL = binary- process.arguments = arguments- process.environment = shellEnvironment()+ // Same seatbelt jail as `runShellSync` when a policy is supplied (orchestrators thread one in);+ // a nil policy is a passthrough.+ let environment = WorkspaceSandbox.childEnvironment(shellEnvironment(), policy: policy)+ let (executable, wrappedArguments) = WorkspaceSandbox.wrap(+ executable: binary,+ arguments: arguments,+ policy: policy,+ environment: environment,+ bundledToolsDir: directory.path+ )+ process.executableURL = executable+ process.arguments = wrappedArguments+ process.environment = environmentprocess.currentDirectoryURL = resolvedWorkingDirectory(workingDirectory)// Concurrent drain via runProcess: the large `--full` dump on stdout and a verbose error on stderr// both flow without either pipe filling and deadlocking the child. Bounded by a generous timeout so adiff --git a/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swiftindex f8b1425b..ac7f3d99 100644--- a/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swift@@ -32,9 +32,21 @@ public struct FormFillOrchestrator: Sendable {return request.data}()+ // The filled PDF's destination — in the working folder by default, or wherever the user named it.+ let outPath = Self.resolve(request.out ?? "out.pdf", against: workingDirectory)++ // Confine pdf-fill to the workspace: it reads the form (and any data file, wherever the user+ // pointed) and writes the map + filled PDF into the working folder, plus the output's own folder+ // when the user named one outside it. nil with no owned folder.+ let policy = SandboxPolicy.forWorkspace(+ baseDirectory: request.workingDirectory,+ readableInputs: [formPath, Self.resolve(request.data, against: workingDirectory)],+ alsoWritable: [(outPath as NSString).deletingLastPathComponent]+ )+// 1. Read the WHOLE form in reading order (fields inline) for a single mapping pass.let read = DonkeyCommandBackends.runBundledTool(- "pdf-fill", ["form", formPath, "--full"], workingDirectory: workingDirectory+ "pdf-fill", ["form", formPath, "--full"], workingDirectory: workingDirectory, policy: policy)guard read.exitCode == 0, !read.stdout.isEmpty else {return HarnessFormFillOutcome(@@ -49,14 +61,13 @@ public struct FormFillOrchestrator: Sendable {}// 3. Write the map and apply it with `pdf-fill set` (writes a NEW pdf, regenerates appearances).- let outPath = Self.resolve(request.out ?? "out.pdf", against: workingDirectory)let mapPath = (workingDirectory as NSString).appendingPathComponent("map.json")guard let mapData = try? JSONSerialization.data(withJSONObject: map, options: [.sortedKeys]),(try? mapData.write(to: URL(fileURLWithPath: mapPath))) != nil else {return HarnessFormFillOutcome(text: "Could not write the field map.", succeeded: false)}let set = DonkeyCommandBackends.runBundledTool(- "pdf-fill", ["set", formPath, "--data", mapPath, "-o", outPath], workingDirectory: workingDirectory+ "pdf-fill", ["set", formPath, "--data", mapPath, "-o", outPath], workingDirectory: workingDirectory, policy: policy)// 4. Verify + reconcile from `pdf-fill set`'s own JSON report and the file on disk.diff --git a/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swift b/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swiftindex 375ca9bf..7850a609 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swift@@ -32,10 +32,20 @@ public enum MediaCutEngine {return failed("the media tools are still installing — try again in a moment")}- guard let duration = probeDuration(ffprobe, inputURL), duration > 0 else {+ // Confine every ffmpeg/ffprobe spawn to the workspace, allowing reads of the input + transcript+ // (which may sit outside it) and a write to the output's own folder — so an in-place save the user+ // asked for lands instead of EPERMing. nil policy with no workspace, so behavior is unchanged there.+ let workdir = request.workingDirectory+ let outputURL = resolveOutputURL(request: request, input: inputURL)+ let policy = SandboxPolicy.forWorkspace(+ baseDirectory: workdir,+ readableInputs: [request.inputPath, request.transcriptPath].compactMap { $0 },+ alsoWritable: [outputURL.deletingLastPathComponent().path]+ )+ guard let duration = probeDuration(ffprobe, inputURL, policy: policy, workingDirectory: workdir), duration > 0 else {return failed("could not read the file's duration — is \(inputURL.lastPathComponent) a real media file?")}- let streams = probeStreams(ffprobe, inputURL)+ let streams = probeStreams(ffprobe, inputURL, policy: policy, workingDirectory: workdir)guard streams.hasVideo || streams.hasAudio else {return failed("the file has no audio or video stream to edit")}@@ -47,7 +57,8 @@ public enum MediaCutEngine {let detect = runProcess(ffmpeg,["-hide_banner", "-nostats", "-i", inputURL.path, "-af", "silencedetect=noise=-30dB:d=0.5", "-f", "null", "-"],- timeout: max(120, duration)+ timeout: max(120, duration),+ policy: policy, workingDirectory: workdir)// silencedetect logs to stderr.removals += MediaCutPlanner.silenceSpans(fromSilenceDetect: detect.stderr, keepPauseSec: parameters.keepPauseSec)@@ -83,7 +94,6 @@ public enum MediaCutEngine {)}- let outputURL = resolveOutputURL(request: request, input: inputURL)let graph = MediaCutPlanner.filterGraph(keeping: keeps, hasVideo: streams.hasVideo, hasAudio: streams.hasAudio)let scriptURL = FileManager.default.temporaryDirectory.appendingPathComponent("donkey-mediacut-\(UUID().uuidString).txt")@@ -99,15 +109,15 @@ public enum MediaCutEngine {output: outputURL,script: scriptURL,streams: streams,- videoBitrate: streams.hasVideo ? probeVideoBitrate(ffprobe, inputURL) : nil+ videoBitrate: streams.hasVideo ? probeVideoBitrate(ffprobe, inputURL, policy: policy, workingDirectory: workdir) : nil)- let render = runProcess(ffmpeg, renderArgs, timeout: max(180, min(duration * 2, 1800)))+ let render = runProcess(ffmpeg, renderArgs, timeout: max(180, min(duration * 2, 1800)), policy: policy, workingDirectory: workdir)guard render.exitCode == 0, FileManager.default.fileExists(atPath: outputURL.path) else {let tail = String(render.stderr.suffix(400))return failed("ffmpeg render failed (exit \(render.exitCode)): \(tail)")}- let outputDuration = probeDuration(ffprobe, outputURL) ?? 0+ let outputDuration = probeDuration(ffprobe, outputURL, policy: policy, workingDirectory: workdir) ?? 0return HarnessMediaCutResult(outputPath: outputURL.path,removedSpanCount: cutCount,@@ -119,30 +129,33 @@ public enum MediaCutEngine {// MARK: - ffprobe helpers- private static func probeDuration(_ ffprobe: URL, _ url: URL) -> Double? {+ private static func probeDuration(_ ffprobe: URL, _ url: URL, policy: SandboxPolicy? = nil, workingDirectory: String? = nil) -> Double? {let result = runProcess(ffprobe,["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", url.path],- timeout: 30+ timeout: 30,+ policy: policy, workingDirectory: workingDirectory)return Double(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines))}- private static func probeStreams(_ ffprobe: URL, _ url: URL) -> (hasVideo: Bool, hasAudio: Bool) {+ private static func probeStreams(_ ffprobe: URL, _ url: URL, policy: SandboxPolicy? = nil, workingDirectory: String? = nil) -> (hasVideo: Bool, hasAudio: Bool) {let result = runProcess(ffprobe,["-v", "error", "-show_entries", "stream=codec_type", "-of", "default=noprint_wrappers=1:nokey=1", url.path],- timeout: 30+ timeout: 30,+ policy: policy, workingDirectory: workingDirectory)let types = Set(result.stdout.split(whereSeparator: { $0 == "\n" || $0 == "\r" }).map { String($0).trimmingCharacters(in: .whitespaces) })return (types.contains("video"), types.contains("audio"))}- private static func probeVideoBitrate(_ ffprobe: URL, _ url: URL) -> String? {+ private static func probeVideoBitrate(_ ffprobe: URL, _ url: URL, policy: SandboxPolicy? = nil, workingDirectory: String? = nil) -> String? {let result = runProcess(ffprobe,["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=bit_rate", "-of", "default=noprint_wrappers=1:nokey=1", url.path],- timeout: 30+ timeout: 30,+ policy: policy, workingDirectory: workingDirectory)let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)return (Int(value) != nil) ? value : nil@@ -171,14 +184,19 @@ public enum MediaCutEngine {return args}- /// Default output path: `<name>-tightened.<ext>` beside the source, unless the caller named one.+ /// Default output path: `<name>-tightened.<ext>` inside the workspace folder, unless the caller named+ /// one. Defaulting into the workspace keeps the write inside the jail's writable root; when the caller+ /// does name a path (an in-place save), the policy makes that folder writable too. With no workspace it+ /// falls back to beside the input.private static func resolveOutputURL(request: HarnessMediaCutRequest, input: URL) -> URL {if let outputPath = request.outputPath, !outputPath.isEmpty {return URL(fileURLWithPath: outputPath)}let ext = input.pathExtensionlet stem = input.deletingPathExtension().lastPathComponent- let directory = input.deletingLastPathComponent()+ let directory = request.workingDirectory+ .flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0, isDirectory: true) }+ ?? input.deletingLastPathComponent()let base = directory.appendingPathComponent("\(stem)-tightened")return ext.isEmpty ? base : base.appendingPathExtension(ext)}@@ -212,12 +230,21 @@ public enum MediaCutEngine {/// Run a bundled tool directly (no shell), draining stdout/stderr on background queues so a large/// stderr (silencedetect, ffmpeg progress) never deadlocks the pipe, bounded by `timeout`.- private static func runProcess(_ executable: URL, _ arguments: [String], timeout: TimeInterval) -> ProcessOutput {+ private static func runProcess(_ executable: URL, _ arguments: [String], timeout: TimeInterval,+ policy: SandboxPolicy? = nil, workingDirectory: String? = nil) -> ProcessOutput {let process = Process()- process.executableURL = executable- process.arguments = arguments- process.environment = DonkeyCommandBackends.shellEnvironment()- process.currentDirectoryURL = FileManager.default.homeDirectoryForCurrentUser+ // Under a policy the spawn runs in the seatbelt jail (writes confined to the workspace, reads locked+ // to system + the input/transcript). A nil policy is a passthrough — same as before the jail existed.+ let environment = WorkspaceSandbox.childEnvironment(DonkeyCommandBackends.shellEnvironment(), policy: policy)+ let (wrappedExecutable, wrappedArguments) = WorkspaceSandbox.wrap(+ executable: executable, arguments: arguments, policy: policy,+ environment: environment, bundledToolsDir: DonkeyCommandBackends.bundledToolsDirectory?.path+ )+ process.executableURL = wrappedExecutable+ process.arguments = wrappedArguments+ process.environment = environment+ // cwd must be the jail (not home) when confined — home is unreadable under the profile.+ process.currentDirectoryURL = DonkeyCommandBackends.resolvedWorkingDirectory(workingDirectory)let outPipe = Pipe()let errPipe = Pipe()diff --git a/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swift b/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swiftindex 2f6ecce6..bc883431 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swift@@ -30,9 +30,14 @@ public enum MediaPipeline {_ workingDirectory: String?) -> (exitCode: Int32, stdout: String, stderr: String)- /// The production runner, as a plain closure value so it can be a default argument.- public static let bundledToolRunner: ToolRunner = { name, arguments, workingDirectory in- DonkeyCommandBackends.runBundledTool(name, arguments, workingDirectory: workingDirectory)+ /// A production runner confined by `policy`: the `runBundledTool` path with each spawned tool inside the+ /// seatbelt jail. An orchestrator builds its policy (workspace folder + its source input) once per run+ /// and gets a runner from this; a `nil` policy runs the tool unconfined. The default `makeRunTool`+ /// injection point, so production jails and a test stub still slots in unchanged.+ public static let sandboxedRunner: @Sendable (SandboxPolicy?) -> ToolRunner = { policy in+ { name, arguments, workingDirectory in+ DonkeyCommandBackends.runBundledTool(name, arguments, workingDirectory: workingDirectory, policy: policy)+ }}/// Run a bundled tool and confirm it produced `outputPath` on disk. A non-zero exit or a missing filediff --git a/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swiftindex f884a6a1..2a71bd81 100644--- a/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swift@@ -39,7 +39,10 @@ public struct PdfParseOrchestrator: Sendable {outPath = resolved}- let result = DonkeyCommandBackends.runBundledTool("lit", arguments, workingDirectory: workingDirectory)+ // Confine lit to the workspace: it reads the input PDF (wherever the user pointed) and writes only+ // inside the working folder. nil when there's no owned folder, so behavior is unchanged there.+ let policy = SandboxPolicy.forWorkspace(baseDirectory: request.workingDirectory, readableInputs: [filePath])+ let result = DonkeyCommandBackends.runBundledTool("lit", arguments, workingDirectory: workingDirectory, policy: policy)guard result.exitCode == 0 else {let why = result.stderr.isEmpty ? result.stdout : result.stderrreturn HarnessPdfParseOutcome(text: "Could not parse \(request.file): \(why)", succeeded: false)diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swiftindex ef1d9170..09c63130 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift@@ -56,12 +56,10 @@ public enum ShellCommandClassifier {// MARK: - Public API/// The bare executables whose whole job is creating, transforming, or deleting files, and whose ENTIRE- /// effect is their visible path arguments — the core file mutators. Inside the dedicated folder the- /// agent owns, these run WITHOUT a consent prompt, but ONLY through the strict static contract in- /// `isUnpromptedWorkspaceMutation`: every command in the line a bare mutator with no wrapper, and- /// every file operand written as an explicit path inside the workspace. The agent manipulating its own- /// sandbox — including a move-then-clean-up chain — is exactly the work the user said it shouldn't have- /// to ask to do.+ /// effect is their visible path arguments — the core file mutators. A line of these runs WITHOUT a+ /// consent prompt only when every path it names sits inside a folder Donkey created (see+ /// `everySegmentMutatesOnlyOwnedRoots`): the agent managing its own folder is the work the user said it+ /// shouldn't have to approve. A mutation that reaches a file the user owns prompts like any other.////// Scripting interpreters (`python3`, `ruby`, `perl`, `node`) are deliberately ABSENT. Their effect is/// the code they run, not the paths in argv — `python3 script.py` can delete a user folder no static@@ -80,54 +78,88 @@ public enum ShellCommandClassifier {workspaceFileToolSignatures.contains(signature)}- /// The entire condition for running file mutations in the agent's own workspace WITHOUT a consent- /// prompt. Sound by construction, on technical argv tokens only — never natural-language intent:+ /// Whether EVERY command in the line is a bare bounded file mutator (`mv`, `rm`, `mkdir`, `chmod`, …)+ /// AND every path operand it names resolves inside one of `ownedRoots` — the folders Donkey created.+ /// Such a line runs WITHOUT a consent prompt: it only creates, moves, or deletes files, and only inside+ /// Donkey's own folder, so there is nothing to ask about. The moment an operand is an absolute path+ /// outside those roots, a `~` path, an unresolved `$VAR`/substitution, or a `..` climb that escapes, the+ /// line falls back to the normal prompt — a mutation of a file the user owns is the user's to approve.///- /// 1. EVERY command in the line is a bare bounded mutator (`mv`, `rm`, `mkdir`, `chmod`, …). A chain- /// (`cp … && rm …` to move a file then clean up) is fine because each link can only create, move, or- /// delete files; a single segment that is a wrapper (`xargs rm` reads paths from stdin the static- /// check can't see), an interpreter, or any non-mutator (`curl`, `osascript`) disqualifies the line.- /// 2. No `$` or backtick anywhere: `$HOME`, `$(…)`, `` `…` `` expand at runtime to paths this check- /// can never resolve, so any expansion disqualifies the line.- /// 3. EVERY file operand, in every command, is written as an explicit path that resolves inside- /// `workspace` — an absolute or `~` path readable straight off the line (`rm ~/Downloads/Foo/a.txt`).- /// A bare name, `.`, `*`, a relative path, a `..` climb, or a redirect target is not anchored to the- /// workspace and so prompts. (chmod's leading mode operand is not a path and is skipped.)- ///- /// Each command independently being a bounded mutator over only workspace-anchored operands means the- /// whole line can touch nothing outside the folder the agent owns. Anything that fails a clause falls- /// through to the normal consent prompt — never blocked, just asked once.- public static func isUnpromptedWorkspaceMutation(_ command: String, workspace: String) -> Bool {- let root = URL(fileURLWithPath: (workspace as NSString).expandingTildeInPath).standardizedFileURL.path- guard !root.isEmpty else { return false }-- // No runtime expansion the static anchor check can't see, anywhere in the line.- guard !command.contains("$"), !command.contains("`") else { return false }-+ /// A chain (`cp <ws>/a … && rm <ws>/tmp`, move then clean up) qualifies when each link is a bounded+ /// mutator with in-folder operands. A wrapper (`xargs rm` reads paths from stdin), an interpreter+ /// (`python3`), or any non-mutator segment (`curl`, `osascript`) disqualifies the line; command+ /// substitution surfaces its inner program as its own segment (split on `(`/backtick), so `rm $(curl …)`+ /// fails on `curl`. Argv tokens only — never natural-language intent. Operands resolve relative to+ /// `workingDirectory` (the workspace), and any resolution ambiguity errs toward prompting, never away.+ public static func everySegmentMutatesOnlyOwnedRoots(+ _ command: String,+ ownedRoots: [String],+ workingDirectory: String+ ) -> Bool {+ let owned = ownedRoots.compactMap(canonicalDirectory)+ guard !owned.isEmpty else { return false }+ let workdir = canonicalDirectory(workingDirectory) ?? (workingDirectory as NSString).expandingTildeInPathlet segments = splitSegments(command).map(tokenize).filter { !$0.isEmpty }guard !segments.isEmpty else { return false }-- var sawPathOperand = false- for var tokens in segments {- // Each command is a bare bounded mutator (the raw first token, so a wrapper like `xargs`/`env`- // can't qualify as the thing that runs).- let executable = executableName(tokens.removeFirst())- guard workspaceFileToolSignatures.contains(executable) else { return false }-- // Every file operand in this command is an explicit path inside the workspace.- var nonPathOperandsToSkip = (executable == "chmod") ? 1 : 0 // chmod's leading mode is not a path- for raw in tokens {- let token = raw.trimmingCharacters(in: CharacterSet(charactersIn: "\\\"'"))- if token.isEmpty || token.hasPrefix("-") { continue } // flags- if nonPathOperandsToSkip > 0 { nonPathOperandsToSkip -= 1; continue }- let expanded = (token as NSString).expandingTildeInPath- guard (expanded as NSString).isAbsolutePath else { return false } // no bare/relative/`.`/`*`- let resolved = URL(fileURLWithPath: expanded).standardizedFileURL.path // resolves any `..`- guard resolved == root || resolved.hasPrefix(root + "/") else { return false }- sawPathOperand = true+ for tokens in segments {+ guard workspaceFileToolSignatures.contains(executableName(tokens[0])) else { return false }+ for operand in pathOperands(of: tokens) {+ guard let resolved = resolveOperandPath(operand, workingDirectory: workdir),+ owned.contains(where: { isWithin(resolved, root: $0) }) else { return false }}}- return sawPathOperand+ return true+ }++ /// The path operands of a bounded-mutator segment: every token after the executable that is not an+ /// option flag (`-r`, `--recursive`). A non-path token like `chmod`'s mode (`644`) resolves under the+ /// workspace and so passes the containment check harmlessly. Flags carry no path to anchor.+ private static func pathOperands(of tokens: [String]) -> [String] {+ tokens.dropFirst().filter { !$0.hasPrefix("-") }+ }++ /// Resolve a mutator operand to an absolute path for the containment check, or nil when it cannot be+ /// pinned down — a `$VAR`/`${…}`/backtick the shell would expand, which we must NOT assume stays in the+ /// workspace. An absolute path is taken as written; `~` expands (to a path outside the workspace,+ /// failing containment); a relative path resolves against `workingDirectory`. `..` and `.` are folded+ /// out lexically so a `../escape` is measured at its real destination.+ private static func resolveOperandPath(_ operand: String, workingDirectory: String) -> String? {+ let dequoted = operand.trimmingCharacters(in: CharacterSet(charactersIn: "'\""))+ guard !dequoted.isEmpty, !dequoted.contains("$"), !dequoted.contains("`") else { return nil }+ let expanded = (dequoted as NSString).expandingTildeInPath+ let absolute = (expanded as NSString).isAbsolutePath+ ? expanded+ : (workingDirectory as NSString).appendingPathComponent(expanded)+ return lexicallyStandardized(absolute)+ }++ /// Fold `.` and `..` out of an absolute path WITHOUT touching symlinks — unlike `NSString.standardizingPath`,+ /// which resolves an existing `/private/tmp` back to `/tmp` and so would never prefix-match an owned root+ /// canonicalized with `realpath`. The operand is appended to a real-path'd working directory, so a purely+ /// lexical fold preserves that real prefix and the containment check stays exact.+ private static func lexicallyStandardized(_ path: String) -> String {+ var stack: [String] = []+ for component in path.split(separator: "/", omittingEmptySubsequences: true) {+ if component == "." { continue }+ if component == ".." { if !stack.isEmpty { stack.removeLast() }; continue }+ stack.append(String(component))+ }+ return "/" + stack.joined(separator: "/")+ }++ /// True when `path` is `root` itself or sits beneath it, comparing standardized absolute paths.+ private static func isWithin(_ path: String, root: String) -> Bool {+ path == root || path.hasPrefix(root.hasSuffix("/") ? root : root + "/")+ }++ /// Canonical absolute path of an existing directory (symlinks resolved via `realpath`), or nil when it+ /// does not exist. Owned roots and the working directory exist on disk, so they canonicalize cleanly and+ /// share a real-path prefix with operands resolved against the same working directory.+ private static func canonicalDirectory(_ path: String) -> String? {+ let expanded = (path as NSString).expandingTildeInPath+ guard !expanded.isEmpty, let resolved = realpath(expanded, nil) else { return nil }+ defer { free(resolved) }+ return String(cString: resolved)}/// Classify a one-line command. The overall tier is the most restrictive@@ -511,8 +543,8 @@ public enum ShellCommandClassifier {/// scopes a read into the agent's folder — without `cd` here it classified as an "unrecognized command"/// (reversibleWrite) and the most-restrictive-segment rule dragged the whole chain to a consent prompt,/// gating even a bundled tool reworking files the agent itself created. (A file MUTATION never rides a- /// `cd` chain unprompted — `isUnpromptedWorkspaceMutation` requires one command with explicit- /// workspace-anchored paths.)+ /// `cd` chain unprompted — `everySegmentMutatesOnlyOwnedRoots` requires every segment to be a bounded+ /// mutator, and `cd` is not one.)private static let readExecutables: Set<String> = ["cd", "pushd", "popd","ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "find", "mdfind", "mdls",diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swiftindex 1a64d0c0..eee81520 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swift@@ -36,27 +36,29 @@ public struct ShortsOrchestrator: Sendable {private let selectMoments: SelectMomentsprivate let transcribe: Transcribe- private let runTool: MediaPipeline.ToolRunner+ private let makeRunTool: @Sendable (SandboxPolicy?) -> MediaPipeline.ToolRunnerpublic init(selectMoments: @escaping SelectMoments,transcribe: @escaping Transcribe,- runTool: @escaping MediaPipeline.ToolRunner = MediaPipeline.bundledToolRunner+ makeRunTool: @escaping @Sendable (SandboxPolicy?) -> MediaPipeline.ToolRunner = MediaPipeline.sandboxedRunner) {self.selectMoments = selectMomentsself.transcribe = transcribe- self.runTool = runTool+ self.makeRunTool = makeRunTool}public func make(_ request: HarnessShortsRequest) async -> HarnessShortsOutcome {// Working directory: the conversation's own folder when present, else home — same rule as shell_exec// and the form filler, so produced clips land beside the rest of the task's output.let workdir = DonkeyCommandBackends.resolvedWorkingDirectoryPath(request.workingDirectory)+ // Every bundled-tool spawn for this run is confined to the workspace (with the source readable).+ let runTool = makeRunTool(SandboxPolicy.forWorkspace(baseDirectory: request.workingDirectory, localSource: request.source))// 1. Resolve the source to a local file (download a URL with yt-dlp first). Resolve ONCE — a second// call would re-download the URL.let sourcePath: String- switch resolveSource(request.source, workdir: workdir) {+ switch resolveSource(request.source, workdir: workdir, using: runTool) {case .ok(let resolved): sourcePath = resolvedcase .failed(let reason): return Self.fail(reason)}@@ -90,7 +92,7 @@ public struct ShortsOrchestrator: Sendable {let result = await MediaPipeline.fanOut(chosen) { index, moment inawait makeClip(index: index, moment: moment, sourcePath: sourcePath,- workdir: workdir, aspect: aspect, reframe: reframeWanted+ workdir: workdir, aspect: aspect, reframe: reframeWanted, using: runTool)}@@ -112,7 +114,7 @@ public struct ShortsOrchestrator: Sendable {/// that fails still ships, so one weak moment never sinks the whole job.private func makeClip(index: Int, moment: MomentSpan, sourcePath: String,- workdir: String, aspect: String, reframe: Bool+ workdir: String, aspect: String, reframe: Bool, using runTool: MediaPipeline.ToolRunner) async -> PipelineItemOutcome {let n = index + 1func path(_ name: String) -> String { (workdir as NSString).appendingPathComponent(name) }@@ -129,7 +131,7 @@ public struct ShortsOrchestrator: Sendable {if case let .failed(reason) = cut { return .failed(reason: "clip \(n): could not cut the span — \(reason)") }// b. Transcribe the clip (zero-based) for caption timings and write an SRT. Best-effort.- let srtPath = await captionSRT(forClip: clip, index: n, workdir: workdir)+ let srtPath = await captionSRT(forClip: clip, index: n, workdir: workdir, using: runTool)// c. Reframe to vertical, following the active speaker. On failure keep the original framing.var base = clip@@ -164,7 +166,7 @@ public struct ShortsOrchestrator: Sendable {/// Extract compact audio from the clip, transcribe it on-device (timings zero-based to the clip), and/// write an SRT next to it. Returns the SRT path, or nil when the clip has no usable transcript.- private func captionSRT(forClip clip: String, index n: Int, workdir: String) async -> String? {+ private func captionSRT(forClip clip: String, index n: Int, workdir: String, using runTool: MediaPipeline.ToolRunner) async -> String? {let clipAudio = (workdir as NSString).appendingPathComponent("clip_\(n).mp3")let audio = MediaPipeline.runStep("ffmpeg",@@ -185,7 +187,7 @@ public struct ShortsOrchestrator: Sendable {// MARK: - Source resolution- private func resolveSource(_ source: String, workdir: String) -> MediaStepResult {+ private func resolveSource(_ source: String, workdir: String, using runTool: MediaPipeline.ToolRunner) -> MediaStepResult {let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)let lower = trimmed.lowercased()if lower.hasPrefix("http://") || lower.hasPrefix("https://") {diff --git a/apps/Donkey/Sources/DonkeyRuntime/WorkspaceSandbox.swift b/apps/Donkey/Sources/DonkeyRuntime/WorkspaceSandbox.swiftnew file mode 100644index 00000000..88c65f2e--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/WorkspaceSandbox.swift@@ -0,0 +1,239 @@+import Foundation++/// What a single sandboxed spawn is allowed to touch on the filesystem. The runtime builds one of+/// these per task-work spawn (shell command, bundled tool, ffmpeg) from the conversation's workspace+/// and declared inputs; `WorkspaceSandbox` turns it into a seatbelt profile that the kernel enforces.+///+/// The policy carries the per-task data: where the child may WRITE (its workspace folder, plus any+/// location the user approved), and — for tools that read locked — which outside files it may READ. The+/// process-global read roots a tool needs merely to launch (system frameworks, the dyld cache, the dirs+/// on the child's PATH) come from the profile builder, so a caller never has to know them.+public struct SandboxPolicy: Sendable, Equatable {+ /// Directories the child may read AND write — the conversation's workspace folder, plus anywhere a+ /// consent prompt already approved. A write outside these is denied by the kernel (EPERM).+ public var writableRoots: [String]+ /// Files/directories the child may READ when `allowAllReads` is false — the task's declared inputs.+ /// Read-only: an input is something to act on, not write back. Ignored when `allowAllReads` is true.+ public var readableRoots: [String]+ /// Whether the child may use the network. True for now: API calls and downloads are common, and the+ /// egress tools that could exfiltrate (curl, scp, python) are gated by the shell consent classifier.+ public var allowNetwork: Bool+ /// When true the child may READ anywhere on disk and `readableRoots` is unused. Shell commands set+ /// this: the consent classifier already treats reads as free, so locking them only broke legitimate+ /// file-finding. Bundled-tool pipelines leave it false — a possibly-hostile input file should not let+ /// its tool read the rest of the disk, so those stay limited to `readableRoots`.+ public var allowAllReads: Bool++ public init(+ writableRoots: [String],+ readableRoots: [String] = [],+ allowNetwork: Bool = true,+ allowAllReads: Bool = false+ ) {+ self.writableRoots = writableRoots+ self.readableRoots = readableRoots+ self.allowNetwork = allowNetwork+ self.allowAllReads = allowAllReads+ }++ /// Policy for an orchestrator that runs a bundled tool on workspace files: confine writes to the+ /// workspace working directory (plus `alsoWritable` — e.g. the directory of an output the user asked+ /// to write in place) and allow reads of the named input file(s). Reads stay locked to those inputs.+ /// `nil` when there is no real workspace base (the working directory fell back to home), so the tool+ /// runs unconfined.+ public static func forWorkspace(+ baseDirectory: String?,+ readableInputs: [String] = [],+ alsoWritable: [String] = []+ ) -> SandboxPolicy? {+ guard let base = baseDirectory, !base.isEmpty else { return nil }+ return SandboxPolicy(+ writableRoots: ([base] + alsoWritable).filter { !$0.isEmpty },+ readableRoots: readableInputs.filter { !$0.isEmpty },+ allowNetwork: true+ )+ }++ /// Policy for an orchestrator whose input is a single local source that may sit outside the workspace —+ /// confine writes to the workspace and allow reading the source when it exists on disk. A URL source+ /// downloads into the folder and so needs no read rule. Shared by the caption and shorts pipelines.+ public static func forWorkspace(baseDirectory: String?, localSource: String) -> SandboxPolicy? {+ let named = (localSource as NSString).expandingTildeInPath+ let reads = FileManager.default.fileExists(atPath: named) ? [named] : []+ return forWorkspace(baseDirectory: baseDirectory, readableInputs: reads)+ }+}++/// Wraps a spawned process in a macOS seatbelt (`sandbox-exec`) profile so the kernel confines the+/// agent's untrusted tools to the directories the policy names — its workspace folder, plus anywhere a+/// consent prompt already approved.+///+/// This is the safety boundary for the UNTRUSTED spawn surface only — arbitrary shell commands and+/// bundled tools the planner composes. It does not (and cannot) confine the app's own in-process file+/// writes (`files.write`); `sandbox-exec` confines children, and the in-process equivalent would jail+/// the whole app. Those writes stay governed by `resolveWritePath`.+///+/// The jail is FILESYSTEM-ONLY: it leaves `network*`, `mach-lookup`, and Apple Events open so API+/// calls, `osascript`, and `open` still work. Non-filesystem side effects remain the job of the shell+/// consent classifier; the jail only removes the question "can this tool escape the folder?".+public enum WorkspaceSandbox {+ /// The OS sandbox wrapper. Deprecated by Apple but functional on every current macOS, and the same+ /// mechanism Chromium uses to confine its helpers. A future hardening step could call `sandbox_init`+ /// from a small spawn helper instead.+ public static let sandboxExecPath = "/usr/bin/sandbox-exec"++ /// Read-only system locations a binary needs merely to launch: dyld and its shared-cache cryptex,+ /// the system frameworks/libraries, resolver and timezone data. Verified empirically — without the+ /// cryptex and `/private/var/db/dyld` entries even `/bin/zsh` aborts under the profile. These are+ /// program/system data, never user documents, so allow-listing them keeps locked-reads intact.+ static let systemReadRoots: [String] = [+ "/usr", "/bin", "/sbin",+ "/System",+ "/Library",+ "/private/etc", // /etc/zshenv, hosts, resolv.conf+ "/private/var/db/dyld", // dyld closures+ "/private/var/db/timezone", // localtime data+ "/System/Volumes/Preboot/Cryptexes/OS" // dyld shared cache (the classic omission)+ ]++ /// User cache directories a well-behaved tool writes scratch into: the macOS per-user cache and the+ /// XDG `~/.cache` (yt-dlp's download cache, a tool's compiled-model cache). Allowed for write like the+ /// darwin temp — auto-purgeable, no user documents — so a bundled tool that insists on caching there+ /// doesn't EPERM mid-run. Resolved once; only existing dirs are kept.+ static var userCacheRoots: [String] {+ ["~/Library/Caches", "~/.cache"].compactMap(canonicalIfPresent)+ }++ /// True when this policy will actually confine a spawn — present and naming at least one writable+ /// root. A nil/empty policy means "no workspace yet"; callers spawn unwrapped (see `wrap`).+ public static func isActive(_ policy: SandboxPolicy?) -> Bool {+ guard let policy else { return false }+ return policy.writableRoots.contains { !$0.trimmingCharacters(in: .whitespaces).isEmpty }+ }++ /// Wrap an executable + arguments into the `sandbox-exec` invocation that runs them under `policy`.+ /// `policy == nil` (or inactive) returns the inputs UNCHANGED — fail-open. With no owned folder+ /// there is nothing to contain, and refusing every spawn would brick the agent on its first step;+ /// in practice the workspace root is created before the first tool runs, so task work is confined.+ /// `environment["PATH"]` and `bundledToolsDir` supply the program dirs the profile must allow for+ /// reads, so they match exactly what the child can execute.+ public static func wrap(+ executable: URL,+ arguments: [String],+ policy: SandboxPolicy?,+ environment: [String: String],+ bundledToolsDir: String?+ ) -> (executable: URL, arguments: [String]) {+ guard let policy, isActive(policy) else { return (executable, arguments) }+ let sbpl = profile(for: policy, programPath: environment["PATH"] ?? "", bundledToolsDir: bundledToolsDir)+ let args = ["-p", sbpl, "--", executable.path] + arguments+ return (URL(fileURLWithPath: sandboxExecPath), args)+ }++ /// The child environment for a sandboxed spawn: corral `TMPDIR` into `<jail>/.tmp` so well-behaved+ /// tools' scratch files stay inside the folder (and are cleaned with it). The profile separately+ /// allows the real per-user darwin temp for tools that ignore `TMPDIR` (`mkstemp`/`confstr`). A nil+ /// or inactive policy returns `base` unchanged.+ public static func childEnvironment(_ base: [String: String], policy: SandboxPolicy?) -> [String: String] {+ guard isActive(policy), let jail = policy?.writableRoots.first(where: { !$0.isEmpty }) else { return base }+ var environment = base+ let tmp = canonical(jail) + "/.tmp"+ try? FileManager.default.createDirectory(atPath: tmp, withIntermediateDirectories: true)+ environment["TMPDIR"] = tmp+ return environment+ }++ /// Build the seatbelt profile (SBPL) string for `policy`. `programPath` is the child's `PATH`+ /// (its dirs are allowed for read so binaries can be loaded); `bundledToolsDir` holds the bundled+ /// binaries + `libpdfium.dylib`. Every path is canonicalized (symlinks resolved) because the kernel+ /// matches subpaths on the real path — a workspace under `/tmp` or `/var` would otherwise fail to+ /// match its own write rule.+ public static func profile(for policy: SandboxPolicy, programPath: String, bundledToolsDir: String?) -> String {+ let writable = uniqued(policy.writableRoots.compactMap(canonicalIfPresent))+ let inputs = uniqued(policy.readableRoots.compactMap(canonicalIfPresent))++ var readRoots = systemReadRoots + programReadRoots(programPath)+ if let bundledToolsDir, let resolved = canonicalIfPresent(bundledToolsDir) { readRoots.append(resolved) }+ readRoots = uniqued(readRoots)++ let darwinTemp = canonical(NSTemporaryDirectory())++ var lines: [String] = [+ "(version 1)",+ "(deny default)",+ "(allow process-fork) (allow process-exec*)",+ "(allow sysctl-read) (allow mach-lookup) (allow signal (target self))",+ "(allow ipc-posix-shm*)",+ "(allow file-read-metadata)"+ ]+ if policy.allowNetwork { lines.append("(allow network*)") }++ // Reads. Shell commands (allowAllReads) may read anywhere — the consent classifier already treats+ // reads as free, so the agent can inspect files the user pointed it at. Bundled-tool pipelines stay+ // locked to system + program dirs + the task's declared inputs, so a hostile input file can't make+ // its tool read the rest of the disk. Directory listing/stat is covered globally by+ // file-read-metadata, so an input's siblings stay unreadable.+ if policy.allowAllReads {+ lines.append("(allow file-read* (subpath \"/\"))")+ } else {+ lines.append("(allow file-read* (literal \"/\")")+ for path in readRoots { lines.append(" (subpath \(quote(path)))") }+ for path in inputs { lines.append(" (subpath \(quote(path)))") }+ lines.append(")")+ }++ // Writes: the workspace folder(s) plus any consent-approved location, the per-user darwin temp and+ // user cache dirs (sanctioned scratch outside the jail — auto-purged, hold no user documents so a+ // tool's model/compile cache lands somewhere), and /dev pseudo-devices.+ lines.append("(allow file-read* file-write*")+ lines.append(" (subpath \"/dev\")")+ lines.append(" (subpath \(quote(darwinTemp)))")+ for path in userCacheRoots { lines.append(" (subpath \(quote(path)))") }+ for path in writable { lines.append(" (subpath \(quote(path)))") }+ lines.append(")")++ return lines.joined(separator: "\n")+ }++ // MARK: - Helpers++ /// Read-only program directories from the child's PATH (`/opt/homebrew/bin`, `/usr/local/bin`, a+ /// version manager's shims, the bundled-tools dir/overlay). Without these a binary on PATH cannot+ /// be loaded under a locked-reads profile. Only existing absolute directories are kept; they are+ /// program dirs, not user data.+ private static func programReadRoots(_ programPath: String) -> [String] {+ programPath+ .split(separator: ":", omittingEmptySubsequences: true)+ .map(String.init)+ .filter { $0.hasPrefix("/") }+ .compactMap(canonicalIfPresent)+ }++ /// Canonical absolute path with all symlinks resolved (`/var` → `/private/var`), via `realpath`.+ /// The kernel evaluates sandbox subpaths against the real path, so rules must use it too. Returns+ /// the tilde-expanded input unchanged when the path does not exist (realpath fails).+ static func canonical(_ path: String) -> String {+ canonicalIfPresent(path) ?? (path as NSString).expandingTildeInPath+ }++ /// Canonical path, or nil if it does not exist on disk — so non-existent allow-list entries are+ /// dropped rather than emitted as un-resolvable rules. `realpath` allocates the result buffer.+ private static func canonicalIfPresent(_ path: String) -> String? {+ let expanded = (path as NSString).expandingTildeInPath+ guard !expanded.isEmpty, let resolved = realpath(expanded, nil) else { return nil }+ defer { free(resolved) }+ return String(cString: resolved)+ }++ /// Order-preserving dedupe (the profile is more readable without repeated subpaths, and identical+ /// rules are pointless).+ private static func uniqued(_ paths: [String]) -> [String] {+ var seen = Set<String>()+ return paths.filter { seen.insert($0).inserted }+ }++ /// Quote a path as an SBPL string literal, escaping backslash and double-quote.+ private static func quote(_ path: String) -> String {+ "\"" + path.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swiftindex 0fc88a68..22f66f6e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swift@@ -53,7 +53,7 @@ struct CaptionOrchestratorTests {return lines.map { "[\(language)] \($0)" }},transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(20), backend: "stub") },- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.caption(@@ -78,7 +78,7 @@ struct CaptionOrchestratorTests {let orchestrator = CaptionOrchestrator(translateCues: { _, _ in recorder.recordTranslate(); return nil },transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(12), backend: "stub") },- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.caption(@@ -98,7 +98,7 @@ struct CaptionOrchestratorTests {let orchestrator = CaptionOrchestrator(translateCues: { _, _ in recorder.recordTranslate(); return nil },transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(8), backend: "stub") },- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.caption(HarnessCaptionRequest(source: "/no/such/file.mp4", translateTo: "Korean", workingDirectory: workdir)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swiftindex d9f98e49..55063cf7 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift@@ -243,55 +243,70 @@ struct ShellCommandClassifierTests {}@Test- func unpromptedWorkspaceMutationAllowsAnchoredMutators() {- let ws = "/Users/me/Downloads/donkey/conv1"- // Bounded mutators whose every file operand is an explicit absolute path inside the workspace —- // whether one command or a chain of them.+ func boundedMutatorsInsideTheOwnedFolderRunUnprompted() throws {+ // Every segment is a pure file mutator AND every operand resolves inside a folder Donkey created, so+ // the line runs without a prompt — the agent managing its own folder is not the user's to approve.+ let ws = try makeOwnedRoot()+ defer { try? FileManager.default.removeItem(atPath: ws) }+ func unprompted(_ c: String) -> Bool {+ ShellCommandClassifier.everySegmentMutatesOnlyOwnedRoots(c, ownedRoots: [ws], workingDirectory: ws)+ }for command in ["rm \"\(ws)/scratch.txt\"","mv \"\(ws)/a.pdf\" \"\(ws)/done/a.pdf\"","cp \"\(ws)/a.txt\" \"\(ws)/b.txt\"","mkdir \"\(ws)/out\"","touch \"\(ws)/x.json\"",- "chmod 755 \"\(ws)/run.sh\"", // chmod's leading mode operand is not a path- "chmod +x \"\(ws)/run.sh\"",- "mv \"\(ws)/a b.pdf\" \"\(ws)/c.pdf\"", // a quoted path with a space is one operand- // A move-then-clean-up chain: both links are mutators with workspace-anchored operands. This is- // the exact shape the planner emits to fix a nested path, which must not prompt.- "mv \"\(ws)/nested/\(ws)/out.pdf\" \"\(ws)/out.pdf\" && rm -rf \"\(ws)/nested\"",+ "chmod 755 \"\(ws)/run.sh\"",+ "mv \"\(ws)/a b.pdf\" \"\(ws)/c.pdf\"", // a quoted path with a space is one operand+ // A move-then-clean-up chain: both links are in-folder mutators — the shape the planner emits."mkdir \"\(ws)/out\" && cp \"\(ws)/a.txt\" \"\(ws)/out/a.txt\"","rm \"\(ws)/a\" ; rm \"\(ws)/b\"",+ "rm scratch.txt", // bare name → resolves inside the workspace+ "rm -rf .", // the workspace itself+ "mv data/x.csv out/y.csv", // relative operands stay inside] {- #expect(ShellCommandClassifier.isUnpromptedWorkspaceMutation(command, workspace: ws), "should run unprompted: \(command)")+ #expect(unprompted(command), "should run unprompted: \(command)")}- // An unquoted `~` path (zsh expands it) anchored to the real home resolves into the workspace too.- let homeWs = "\(NSHomeDirectory())/Downloads/donkey/conv1"- #expect(ShellCommandClassifier.isUnpromptedWorkspaceMutation("rm ~/Downloads/donkey/conv1/x.txt", workspace: homeWs))}@Test- func unpromptedWorkspaceMutationRejectsEverythingNotStaticallyAnchored() {- let ws = "/Users/me/Downloads/donkey/conv1"+ func mutationsReachingOutsideTheOwnedFolderPrompt() throws {+ // The security boundary: a bounded mutator whose operand leaves the owned folder — an absolute path+ // outside, a `~` path, a `..` climb, an unresolved `$VAR` — falls back to the consent prompt, as does+ // any wrapper/interpreter/non-mutator segment that reaches beyond the filesystem.+ let ws = try makeOwnedRoot()+ defer { try? FileManager.default.removeItem(atPath: ws) }+ func unprompted(_ c: String) -> Bool {+ ShellCommandClassifier.everySegmentMutatesOnlyOwnedRoots(c, ownedRoots: [ws], workingDirectory: ws)+ }for command in [- "rm -rf $HOME", // expansion to an absolute path the check can't see- "rm -rf \"\(ws)/$junk\"", // any `$` disqualifies- "rm -rf .", // not anchored- "rm -rf *", // glob, not anchored- "rm scratch.txt", // bare name- "mv data/x.csv \(ws)/y.csv", // a relative source operand- "cp \"\(ws)/a.txt\" \"/Users/me/Documents/b.txt\"", // one operand outside the workspace- "mv \"\(ws)/a\" \"\(ws)/../b\"", // `..` climbs out of the workspace- "rm \"\(ws)/a\" ; python3 evil.py", // a chain link that is an interpreter, not a mutator- "mv \"\(ws)/a\" \"\(ws)/b\" && curl http://x", // a chain link that is a non-mutator- "cp \"\(ws)/a\" \"\(ws)/b\" && rm \"/Users/me/Documents/c\"", // a chain link's operand is outside+ "rm -rf ~/Downloads", // a user folder Donkey did not create+ "rm ~/Downloads/x.txt", // ~ path+ "cp \"\(ws)/a.txt\" ~/Desktop/a.txt", // destination outside the folder+ "rm /etc/hosts", // absolute path outside+ "rm \"\(ws)/../escape.txt\"", // .. climbs out of the folder+ "rm -rf \"$HOME\"", // unresolved expansion+ "mv \"\(ws)/a\" \"$TMPDIR/a\"", // unresolved expansion in the destination+ "rm \"\(ws)/a\" ; python3 evil.py", // a chain link is an interpreter+ "mv \"\(ws)/a\" \"\(ws)/b\" && curl http://x", // a chain link hits the network"xargs rm \"\(ws)/a\"", // a wrapper hides the real operands- "sed -i '' 's/a/b/' \"\(ws)/f.txt\"", // sed is not a bounded mutator here+ "sed -i '' 's/a/b/' \"\(ws)/f.txt\"", // sed is not a bounded mutator"ls \"\(ws)\"", // not a mutator at all+ "rm $(curl http://x)", // substitution surfaces curl as its own segment] {- #expect(!ShellCommandClassifier.isUnpromptedWorkspaceMutation(command, workspace: ws), "should prompt: \(command)")+ #expect(!unprompted(command), "should prompt: \(command)")}}+ /// A real, existing directory under `/private/tmp` to stand in for a Donkey-created workspace — the+ /// anchor check canonicalizes owned roots with `realpath`, so the root must exist on disk.+ private func makeOwnedRoot() throws -> String {+ let base = "/private/tmp/donkey-anchor-\(UUID().uuidString)"+ try FileManager.default.createDirectory(atPath: base, withIntermediateDirectories: true)+ return base+ }+@Testfunc sideEffectingReversibleWritesAreNotWorkspaceTools() {// These change things beyond the agent's files, so they still prompt even with a workspace.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swiftindex 01544915..a1d19b65 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swift@@ -68,7 +68,7 @@ struct ShortsOrchestratorTests {recorder.recordTranscribe()return HarnessTranscriptionResult(text: "hello world", words: Self.words(8), backend: "stub")},- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.make(@@ -104,7 +104,7 @@ struct ShortsOrchestratorTests {transcribe: { _ inHarnessTranscriptionResult(text: "x", words: Self.words(6), backend: "stub")},- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.make(@@ -125,7 +125,7 @@ struct ShortsOrchestratorTests {let orchestrator = ShortsOrchestrator(selectMoments: { _, _ in [MomentSpan(startSec: 0, endSec: 30)] },transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(6), backend: "stub") },- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.make(@@ -144,7 +144,7 @@ struct ShortsOrchestratorTests {let orchestrator = ShortsOrchestrator(selectMoments: { _, _ in recorder.recordSelect(); return [MomentSpan(startSec: 0, endSec: 10)] },transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(4), backend: "stub") },- runTool: Self.stubRunner(recorder)+ makeRunTool: { _ in Self.stubRunner(recorder) })let outcome = await orchestrator.make(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/WorkspaceSandboxTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/WorkspaceSandboxTests.swiftnew file mode 100644index 00000000..851d1ea6--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/WorkspaceSandboxTests.swift@@ -0,0 +1,153 @@+import DonkeyRuntime+import Foundation+import Testing++/// Proves the seatbelt jail actually confines a spawned process: writes land only in the workspace+/// folder, declared inputs are readable but other files are not, and the wrapper is a no-op without a+/// policy. The integration cases run a real `/bin/zsh` under `WorkspaceSandbox.wrap` and observe the+/// kernel's EPERM, so a regression in the profile fails loudly rather than silently widening the jail.+///+/// Test files live under `/private/tmp` (NOT the per-user darwin temp, which the profile deliberately+/// allows as scratch) so an out-of-jail write target is genuinely outside every allowed write root.+@Suite+struct WorkspaceSandboxTests {++ // MARK: - Profile shape (pure, no spawn)++ @Test+ func profileEncodesTheJailAndDeclaredInputs() {+ let policy = SandboxPolicy(writableRoots: ["/private/tmp"], readableRoots: ["/etc/hosts"], allowNetwork: true)+ let sbpl = WorkspaceSandbox.profile(for: policy, programPath: "/usr/bin:/bin", bundledToolsDir: nil)+ #expect(sbpl.contains("(deny default)"))+ #expect(sbpl.contains("(allow network*)"))+ #expect(sbpl.contains("(subpath \"/private/tmp\")")) // the jail, writable+ #expect(sbpl.contains("(subpath \"/private/etc/hosts\")")) // declared input, canonicalized for read+ }++ @Test+ func allowAllReadsOpensEveryRead() {+ // Shell commands set allowAllReads: the profile opens reads everywhere instead of locking them to+ // declared inputs, so the agent can inspect a file the user pointed it at.+ let policy = SandboxPolicy(writableRoots: ["/private/tmp"], allowAllReads: true)+ let sbpl = WorkspaceSandbox.profile(for: policy, programPath: "/usr/bin:/bin", bundledToolsDir: nil)+ #expect(sbpl.contains("(allow file-read* (subpath \"/\"))"))+ }++ @Test+ func networkIsOmittedWhenDisallowed() {+ let policy = SandboxPolicy(writableRoots: ["/private/tmp"], readableRoots: [], allowNetwork: false)+ let sbpl = WorkspaceSandbox.profile(for: policy, programPath: "", bundledToolsDir: nil)+ #expect(!sbpl.contains("(allow network*)"))+ }++ @Test+ func wrapIsAPassthroughWithoutAPolicy() {+ let exe = URL(fileURLWithPath: "/bin/zsh")+ let (e1, a1) = WorkspaceSandbox.wrap(executable: exe, arguments: ["-c", "echo hi"], policy: nil,+ environment: [:], bundledToolsDir: nil)+ #expect(e1 == exe)+ #expect(a1 == ["-c", "echo hi"])+ // An empty policy is also inactive — nothing to contain.+ let empty = SandboxPolicy(writableRoots: [], readableRoots: [])+ #expect(WorkspaceSandbox.isActive(empty) == false)+ let (e2, _) = WorkspaceSandbox.wrap(executable: exe, arguments: [], policy: empty,+ environment: [:], bundledToolsDir: nil)+ #expect(e2 == exe)+ }++ @Test+ func wrapTargetsSandboxExec() {+ let policy = SandboxPolicy(writableRoots: ["/private/tmp"])+ let (exe, args) = WorkspaceSandbox.wrap(executable: URL(fileURLWithPath: "/bin/zsh"),+ arguments: ["-c", "echo hi"], policy: policy,+ environment: ["PATH": "/usr/bin:/bin"], bundledToolsDir: nil)+ #expect(exe.path == WorkspaceSandbox.sandboxExecPath)+ #expect(args.first == "-p")+ #expect(args.contains("/bin/zsh")) // the real executable after the `--` separator+ }++ // MARK: - Kernel-enforced containment (real sandbox-exec)++ @Test+ func confinesWritesAndReadsToThePolicy() throws {+ try requireSandboxExec()+ let base = try makeBase()+ defer { try? FileManager.default.removeItem(atPath: base) }+ let jail = base + "/jail"+ try FileManager.default.createDirectory(atPath: jail, withIntermediateDirectories: true)+ let input = base + "/input.txt" // declared → readable+ let secret = base + "/secret.txt" // NOT declared → unreadable+ let escape = base + "/escape.txt" // outside jail → unwritable+ try "declared".write(toFile: input, atomically: true, encoding: .utf8)+ try "topsecret".write(toFile: secret, atomically: true, encoding: .utf8)++ let policy = SandboxPolicy(writableRoots: [jail], readableRoots: [input], allowNetwork: false)++ // Write inside the jail → allowed.+ #expect(runZsh(": > '\(jail)/out.txt'", policy: policy) == 0)+ #expect(FileManager.default.fileExists(atPath: jail + "/out.txt"))++ // Write outside the jail → blocked by the kernel; the file must not appear.+ #expect(runZsh(": > '\(escape)'", policy: policy) != 0)+ #expect(FileManager.default.fileExists(atPath: escape) == false)++ // Read the declared input → allowed; read a non-declared file → blocked.+ #expect(runZsh("cat '\(input)' > /dev/null", policy: policy) == 0)+ #expect(runZsh("cat '\(secret)' > /dev/null", policy: policy) != 0)+ }++ @Test+ func shellReadsAreOpenButWritesStayConfined() throws {+ try requireSandboxExec()+ let base = try makeBase()+ defer { try? FileManager.default.removeItem(atPath: base) }+ let jail = base + "/jail"+ try FileManager.default.createDirectory(atPath: jail, withIntermediateDirectories: true)+ let secret = base + "/secret.txt" // NOT declared, but shell reads are open+ let escape = base + "/escape.txt" // outside jail → still unwritable+ try "topsecret".write(toFile: secret, atomically: true, encoding: .utf8)++ let policy = SandboxPolicy(writableRoots: [jail], allowNetwork: false, allowAllReads: true)++ // A non-declared file is readable (the consent classifier already treats reads as free)…+ #expect(runZsh("cat '\(secret)' > /dev/null", policy: policy) == 0)+ // …but a write outside the jail is still blocked by the kernel.+ #expect(runZsh(": > '\(escape)'", policy: policy) != 0)+ #expect(FileManager.default.fileExists(atPath: escape) == false)+ }++ // MARK: - Helpers++ private func requireSandboxExec() throws {+ try #require(FileManager.default.isExecutableFile(atPath: WorkspaceSandbox.sandboxExecPath))+ }++ /// A canonical base dir under /private/tmp (world-writable, and NOT under the per-user darwin temp+ /// the profile allows), so an out-of-jail target is genuinely denied.+ private func makeBase() throws -> String {+ let base = "/private/tmp/donkey-sbx-\(UUID().uuidString)"+ try FileManager.default.createDirectory(atPath: base, withIntermediateDirectories: true)+ return base+ }++ /// Run a one-line script via `/bin/zsh` wrapped by the policy; return the exit code.+ private func runZsh(_ script: String, policy: SandboxPolicy?) -> Int32 {+ let environment = ProcessInfo.processInfo.environment+ let (exe, args) = WorkspaceSandbox.wrap(+ executable: URL(fileURLWithPath: "/bin/zsh"),+ arguments: ["-c", script],+ policy: policy,+ environment: environment,+ bundledToolsDir: nil+ )+ let process = Process()+ process.executableURL = exe+ process.arguments = args+ process.environment = environment+ process.standardOutput = FileHandle.nullDevice+ process.standardError = FileHandle.nullDevice+ do { try process.run() } catch { return -1 }+ process.waitUntilExit()+ return process.terminationStatus+ }+}