Open source CapCut alternative.
TypeScript
fix(app): keep unprompted workspace tools inside the conversation folder
David Leeb0f5b6d3275
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex bcb225e6..0e9dc431 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -462,11 +462,15 @@ public enum DonkeyPrompts {memory goes stale and verbatim reproductions get blocked by the provider's content filter. Fora 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, and your shell runs- there. Give every file a bare relative name (`fields.json`, `out.pdf`) so it lands there. For- a task with input files, copy them in first (`cp <abs input> .`) and work on the copies, so- inputs and output stay together. Reuse this folder on follow-ups; `ls` to reconcile. Save- elsewhere only when the user names a location.+ - 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.- 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/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swiftindex 1feed79c..3b74c69a 100644--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift@@ -134,15 +134,16 @@ public enum DonkeyCommandLayer {HarnessToolDescriptor(name: Command.imageRender.rawValue,pluginID: pluginID,- summary: "Render HTML/SVG markup YOU write into a crisp PNG (or PDF) image, using the same built-in headless browser as web_snapshot. This is how you CREATE an image of text or data — an infographic, diagram, chart, standings/bracket, poster, card, certificate, or any explanatory graphic about any topic. Unlike image.generate (a generative model that garbles text and numbers), this renders your exact markup, so every label and value is sharp and you control the whole layout. Write one self-contained HTML document (inline CSS, system fonts, inline <svg> for shapes, data: URIs for any images), then pass it here. Follow the `design` skill for how to make it look good. It only renders your markup and writes the output file, so it runs without consent.",+ summary: "Render HTML/SVG markup YOU write into a crisp PNG (or PDF) image, using the same built-in headless browser as web_snapshot. This is how you CREATE an image of text or data — an infographic, diagram, chart, standings/bracket, poster, card, certificate, or any explanatory graphic about any topic. Unlike image.generate (a generative model that garbles text and numbers), this renders your exact markup, so every label and value is sharp and you control the whole layout. Write one self-contained HTML document (inline CSS, system fonts, inline <svg> for shapes, data: URIs for any images), then pass it here. Follow the `design` skill for how to make it look good. It reads markup from your workspace and writes the output file there, so it runs without consent.",inputSchema: [- "html": "A complete, self-contained HTML (or SVG) document to render. Inline all CSS; use system fonts; remote fonts/images are not loaded (embed images as data: URIs).",+ "html": "A complete, self-contained HTML (or SVG) document to render. Inline all CSS; use system fonts; remote fonts/images are not loaded (embed images as data: URIs). Omit when providing `htmlPath`.",+ "htmlPath": "Optional path to a file IN YOUR WORKSPACE holding the HTML/SVG markup to render — use it for large or complex documents to avoid escaping, truncation, or token-budget errors. Confined to the workspace: absolute or `..` paths are re-rooted there.","width": "Canvas width in pixels (default 1200, 200–4000). Author your layout to this width.","height": "Optional canvas height in pixels (200–8000). Omit to fit the content's natural height.","format": "\"png\" (default) or \"pdf\".","destination": "Optional output name. A relative name or subfolder (e.g. charts/q3.png) lands in the conversation's workspace folder; this runs without consent, so the output always stays inside that folder (else ~/Downloads) — absolute or .. paths are re-rooted there, not written elsewhere. Omit to save to the workspace, else ~/Downloads."],- optionalInputKeys: ["width", "height", "format", "destination"],+ optionalInputKeys: ["html", "htmlPath", "width", "height", "format", "destination"],outputSchema: ["filePath": "Path to the saved PNG or PDF."],requiredPermissions: [],safetyClass: .readOnly,diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 022cca78..e9c765d2 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -172,8 +172,23 @@ public enum DonkeyCommandBackends {/// the conversation workspace (or ~/Downloads when none is set yet); see `resolveOutputDestination`.@MainActorprivate static func imageRender(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {- guard let html = trimmed(context.call.input["html"]) else {- return invalidInput(context, "image_render requires `html` — the HTML/SVG markup to render.")+ // `html` (inline markup) wins when both are supplied; the schema tells the model to omit it when+ // passing `htmlPath`. The htmlPath file is read from inside the workspace only (see resolveInputPath).+ var html: String = ""+ if let htmlInput = trimmed(context.call.input["html"]) {+ html = htmlInput+ } else if let htmlPathInput = trimmed(context.call.input["htmlPath"]) {+ let path = resolveInputPath(htmlPathInput, baseDir: workspaceBaseDir(context))+ do {+ html = try String(contentsOf: path, encoding: .utf8)+ } catch {+ return failed(context, "image_render could not read htmlPath '\(htmlPathInput)': \(error.localizedDescription)", reason: "imageRenderReadFailed")+ }+ guard !html.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ return invalidInput(context, "image_render's htmlPath file '\(htmlPathInput)' is empty — it must contain the HTML/SVG markup to render.")+ }+ } else {+ return invalidInput(context, "image_render requires either `html` or `htmlPath` — the HTML/SVG markup or path to render.")}let format = (trimmed(context.call.input["format"]) ?? "png").lowercased()guard format == "png" || format == "pdf" else {@@ -284,6 +299,25 @@ public enum DonkeyCommandBackends {return (value?.isEmpty == false) ? value : nil}+ /// 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+ /// absolute path, a `~` path, or a `..` climb is re-rooted under `base` rather than honored. Neither+ /// side of the tool can reach a file Donkey doesn't own.+ private static func resolveInputPath(_ rawPath: String, baseDir: String?) -> URL {+ let base: URL = {+ if let baseDir, !baseDir.isEmpty {+ return URL(fileURLWithPath: (baseDir as NSString).expandingTildeInPath, isDirectory: true)+ }+ return FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Downloads", isDirectory: true)+ }()+ let safeComponents = rawPath+ .split(separator: "/", omittingEmptySubsequences: true)+ .filter { $0 != ".." && $0 != "." }+ return safeComponents.reduce(base) { $0.appendingPathComponent(String($1)) }+ }+/// Shared destination rule for the no-consent capture/render tools (`image_render`, `web_snapshot`).////// The result is ALWAYS inside `base` — the conversation workspace `baseDir` when one exists, else@@ -855,17 +889,15 @@ public enum DonkeyCommandBackends {let store = ShellPermissionPolicyStore.sharedlet signature = classification.signature- // The agent doesn't ask permission to read or change files in the dedicated folder it owns. A- // reversible-write file command (cp, mkdir, mv, tee, …) runs unprompted when the conversation has a- // working directory AND the command is provably confined to it: every segment is a bounded file- // mutator (no interpreter can ride along — `cp a b && python3 evil.py` fails the bounded check), and- // every path it names resolves inside the workspace (no absolute, `~`, or `..` escape). High-risk- // still gates regardless. Anything touching a file Donkey didn't make, or running opaque code, falls- // through to the normal consent prompt.- if classification.tier == .reversibleWrite,+ // 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.isBoundedWorkspaceCommand(command),- ShellCommandClassifier.commandStaysWithin(command, workspace: workspace) {+ ShellCommandClassifier.isUnpromptedWorkspaceMutation(command, workspace: workspace) {return nil}diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/finder/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/finder/SKILL.mdindex 64a38a1f..515a7090 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/finder/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/finder/SKILL.md@@ -19,10 +19,19 @@ Almost everything Finder does is faster through shell_exec. Use Finder scripting- Reveal the result so the user sees it: `open -R ~/Documents/Reports/report.pdf`.## Delete = trash, not rm-- Prefer the reversible Finder trash: `osascript -e 'tell app "Finder" to delete POSIX file "/Users/me/old.txt"'`.-- `rm` is destructive and asks every time; reach for it only when the user explicitly wants permanent deletion.+- For the USER's files, prefer the reversible Finder trash: `osascript -e 'tell app "Finder" to delete POSIX file "/Users/me/old.txt"'`. `rm` outside your own workspace is destructive and asks every time — reach for it only when the user explicitly wants permanent deletion.+- Inside the workspace folder you own, `rm` with the full workspace path (`rm "<workspace>/scratch.txt"`) runs without asking — including a clean-up chain of file commands like `mv "<workspace>/a" "<workspace>/b" && rm "<workspace>/a"`. A bare name, `*`, `$VAR`, or any non-file command in the chain still prompts.- Emptying the trash is irreversible — always confirm with the user first.+## Creating and Naming Folders and Files+- When creating directories (folders) or files to organize documents, do NOT use the user's raw prompt or simply truncate the input.+- **Root Folders:**+ - Generate a very short, user-friendly, and descriptive folder name (2-4 words), ensuring you **correct any spelling mistakes** in the user's query (e.g., `"standard daviation chart"` -> `"Standard Deviation Chart"`).+ - Format the root folder name as a nice, natural sentence or title with space-separated words, using natural capitalization (e.g., `"Collapsing the Notch"`, `"Organize tax files"`).+ - Deterministically or creatively map the conversation ID or target to a super-friendly 3-4 letter word (such as `mint`, `wave`, `cozy`, `fern`, `pine`, `glen`, `vibe`, `snug`, `glow`, `plum`), and append it at the end of the root folder name as a capitalized unique hash word (e.g., `"Collapsing the Notch Cozy"`, `"Organize Tax Files Cozy"`).+- **Child Folders and Files:**+ - Any child folders and files created *inside* the root folder should be formatted in **CamelCase** (or **PascalCase** where each word is capitalized with no spaces), correcting any spelling mistakes (e.g., a folder name like `"tax receipts"` becomes `TaxReceipts`, and a file name like `"f1120 form.pdf"` becomes `F1120Form.pdf`).+## Verify- After a move/copy/trash, confirm with a read: `ls ~/Documents/Reports`, `stat -f '%N' file`, or check the Trash: `ls ~/.Trash`.diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swiftindex 420f8712..ef1d9170 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift@@ -55,20 +55,23 @@ public enum ShellCommandClassifier {// MARK: - Public API- /// Reversible-write signatures whose whole job is creating or transforming files, and whose ENTIRE- /// effect is its visible path arguments — the core file mutators. When the conversation has a dedicated- /// working directory the agent owns, and every path the command names stays inside that directory, these- /// run WITHOUT a consent prompt: the agent is manipulating its own sandbox, exactly the work the user- /// said it shouldn't have to ask to do.+ /// 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.////// 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/// look at the command line can see — so "a workspace exists" is no containment at all for them. They/// stay on the normal consent path, surfacing a clear "runs a … script" prompt the user can- /// always-allow. Tools with side effects beyond the filesystem (osascript, open, killall, …) are absent- /// for the same reason.+ /// always-allow. `sed -i` is absent for a related reason: its file operand can't be told apart from its+ /// script argument statically, so it too prompts. Tools with side effects beyond the filesystem+ /// (osascript, open, killall, …) are absent for the same reason.public static let workspaceFileToolSignatures: Set<String> = [- "mkdir", "touch", "cp", "mv", "ln", "tee", "sed -i"+ "mkdir", "touch", "cp", "mv", "ln", "tee", "rm", "rmdir", "chmod"]/// Whether a classification signature is a bounded file mutator that may run unprompted inside the@@ -77,49 +80,54 @@ public enum ShellCommandClassifier {workspaceFileToolSignatures.contains(signature)}- /// True only when EVERY segment of the command is a read or a bounded workspace file-mutator. This is- /// what makes the no-consent workspace bypass sound for a CHAIN: a benign `cp` (which would otherwise be- /// the deciding signature on `cp a b && python3 evil.py`) cannot carry a piggybacked interpreter through- /// unprompted, because the `python3` segment is reversible but is not a workspace file tool, so the- /// chain as a whole fails this check and prompts.- public static func isBoundedWorkspaceCommand(_ command: String) -> Bool {- for rawSegment in splitSegments(command) {- let tokens = tokenize(rawSegment)- guard !tokens.isEmpty else { continue }- let segment = classifySegment(tokens)- if segment.tier == .read { continue }- if segment.tier == .reversibleWrite, isWorkspaceFileTool(segment.signature) { continue }- return false- }- return true- }-- /// Whether every filesystem path the command names resolves INSIDE `workspace`. Paired with- /// `isBoundedWorkspaceCommand` so the no-consent bypass fires only when the command both uses bounded- /// tools AND cannot reach outside the folder Donkey owns — escape is then impossible by construction.- /// Argv-token analysis on technical fields, never natural-language intent: a bare name (no slash) is a- /// file in the working directory, which IS the workspace, and stays in; an absolute path, a `~` path, or- /// a relative path that climbs out with `..` must resolve within the workspace or the command is treated- /// as reaching outside (and so prompts). A token that merely contains `/` but is not a real path (a- /// `sed` script like `s/a/b/`) resolves under the workspace and stays in, so it never forces a prompt.- public static func commandStaysWithin(_ command: String, workspace: String) -> Bool {+ /// 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:+ ///+ /// 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.pathguard !root.isEmpty else { return false }- for raw in argvTokens(command) {- let token = raw.trimmingCharacters(in: CharacterSet(charactersIn: "\\\"'"))- guard tokenLooksLikePath(token) else { continue }- let expanded = (token as NSString).expandingTildeInPath- let resolved = (expanded as NSString).isAbsolutePath- ? URL(fileURLWithPath: expanded).standardizedFileURL.path- : URL(fileURLWithPath: root).appendingPathComponent(expanded).standardizedFileURL.path- if resolved != root, !resolved.hasPrefix(root + "/") { return false }- }- return true- }- private static func tokenLooksLikePath(_ token: String) -> Bool {- guard !token.isEmpty, !token.hasPrefix("-") else { return false }- return token.hasPrefix("/") || token.hasPrefix("~") || token.contains("/")+ // No runtime expansion the static anchor check can't see, anywhere in the line.+ guard !command.contains("$"), !command.contains("`") else { return false }++ let 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+ }+ }+ return sawPathOperand}/// Classify a one-line command. The overall tier is the most restrictive@@ -361,8 +369,8 @@ public enum ShellCommandClassifier {/// Quote-aware split into argv tokens, honoring single/double quotes and backslash escapes (quote/// characters are kept in the token so a path detector can dequote and an executable normalizer can- /// path-strip). The shared primitive behind `tokenize` (which then drops leading env assignments),- /// `commandStaysWithin`, and the output-file detector — so none of them re-implement shell quoting.+ /// path-strip). The shared primitive behind `tokenize` (which then drops leading env assignments) and+ /// the output-file detector — so neither re-implements shell quoting.static func argvTokens(_ segment: String) -> [String] {var tokens: [String] = []var current = ""@@ -499,10 +507,12 @@ public enum ShellCommandClassifier {/// scutil, plutil, sed) are handled in `refine` and intentionally absent here.////// `cd`/`pushd`/`popd` are pure directory navigation: they change only the shell's working directory and- /// touch no file or state, so they are reads. This matters because `cd <dir> && <real command>` is the- /// idiom the planner uses to scope work into the folder it owns — 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.+ /// touch no file or state, so they are reads. This matters because `cd <dir> && <read or bundled tool>`+ /// 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.)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/Tests/DonkeyRuntimeTests/ImageRenderTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ImageRenderTests.swiftnew file mode 100644index 00000000..beaf2663--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ImageRenderTests.swift@@ -0,0 +1,77 @@+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct ImageRenderTests {+ @MainActor+ private func run(_ input: [String: String], baseDir: String?) async -> HarnessToolResult? {+ let descriptor = DonkeyCommandLayer.descriptors.first { $0.name == "image_render" }!+ var worldModel = HarnessWorldModel()+ if let baseDir {+ worldModel.facts["workspace.baseDir"] = baseDir+ }+ let context = HarnessToolExecutionContext(+ agentID: "test",+ call: HarnessToolCall(name: "image_render", input: input),+ descriptor: descriptor,+ worldModel: worldModel,+ grantedPermissions: []+ )+ return await DonkeyCommandBackends.makeExecutor()(context)+ }++ @Test+ @MainActor+ func imageRenderRequiresEitherHtmlOrHtmlPath() async {+ let result = await run([:], baseDir: nil)+ #expect(result?.status == .invalidInput)+ }++ @Test+ @MainActor+ func imageRenderWithDirectHtmlSucceeds() async throws {+ let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+ try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: tempDir) }++ let expectedDestination = tempDir.appendingPathComponent("output.png")+ let htmlContent = "<html><body><h1>Hello World</h1></body></html>"++ let result = await run([+ "html": htmlContent,+ "destination": "output.png",+ "format": "png"+ ], baseDir: tempDir.path)++ #expect(result?.status == .succeeded)+ #expect(FileManager.default.fileExists(atPath: expectedDestination.path))+ }++ @Test+ @MainActor+ func imageRenderWithHtmlPathSucceeds() async throws {+ let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+ try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: tempDir) }++ // Write template HTML file to workspace+ let templatePath = tempDir.appendingPathComponent("template.html")+ let htmlContent = "<html><body style='background: red;'><h1>Render from path</h1></body></html>"+ try htmlContent.write(to: templatePath, atomically: true, encoding: .utf8)++ let expectedDestination = tempDir.appendingPathComponent("rendered_output.png")++ // Pass relative path "template.html"+ let result = await run([+ "htmlPath": "template.html",+ "destination": "rendered_output.png",+ "format": "png"+ ], baseDir: tempDir.path)++ #expect(result?.status == .succeeded)+ #expect(FileManager.default.fileExists(atPath: expectedDestination.path))+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swiftindex a41ec7bf..d9f98e49 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift@@ -209,14 +209,26 @@ struct ShellCommandClassifierTests {@Testfunc boundedFileMutatorsAreWorkspaceTools() {// The core file mutators whose whole effect is their visible path arguments: reversible, and- // recognized as workspace file tools so the consent gate can skip the prompt when a workspace exists- // and every path stays inside it.- for command in ["cp a.pdf out/", "mv a b", "mkdir out", "touch x.json",- "tee fields.json", "sed -i '' s/a/b/ x"] {+ // recognized as workspace file tools so the consent gate can skip the prompt when the command is a+ // single anchored mutation inside the workspace. `sed -i` is intentionally NOT here — its file+ // operand can't be told apart from its script statically, so it prompts.+ for command in ["cp a.pdf out/", "mv a b", "mkdir out", "touch x.json", "tee fields.json"] {let c = ShellCommandClassifier.classify(command)#expect(c.tier == .reversibleWrite)#expect(ShellCommandClassifier.isWorkspaceFileTool(c.signature), "expected workspace tool: \(command) → \(c.signature)")}+ #expect(!ShellCommandClassifier.isWorkspaceFileTool("sed -i"))+ }++ @Test+ func highRiskWorkspaceToolsAreWorkspaceTools() {+ // High-risk tools that are strictly for file manipulation inside the workspace (rm, rmdir, chmod)+ // are recognized as workspace file tools so they can run unprompted when anchored to the workspace.+ for command in ["rm a.pdf", "rmdir out", "chmod +x run.sh"] {+ let c = ShellCommandClassifier.classify(command)+ #expect(c.tier == .highRisk)+ #expect(ShellCommandClassifier.isWorkspaceFileTool(c.signature), "expected workspace tool: \(command) → \(c.signature)")+ }}@Test@@ -231,28 +243,53 @@ struct ShellCommandClassifierTests {}@Test- func boundedWorkspaceCommandRejectsRidealongInterpreter() {- // The chaining hole: a benign `cp` can be the deciding signature, but a piggybacked interpreter must- // not ride through the bypass — isBoundedWorkspaceCommand inspects EVERY segment.- #expect(ShellCommandClassifier.isBoundedWorkspaceCommand("cp a b && mkdir out"))- #expect(ShellCommandClassifier.isBoundedWorkspaceCommand("ls && cp a b"))- #expect(!ShellCommandClassifier.isBoundedWorkspaceCommand("cp a b && python3 evil.py"))- #expect(!ShellCommandClassifier.isBoundedWorkspaceCommand("python3 map.py"))+ 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.+ 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\"",+ "mkdir \"\(ws)/out\" && cp \"\(ws)/a.txt\" \"\(ws)/out/a.txt\"",+ "rm \"\(ws)/a\" ; rm \"\(ws)/b\"",+ ] {+ #expect(ShellCommandClassifier.isUnpromptedWorkspaceMutation(command, workspace: ws), "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 commandStaysWithinDetectsEscape() {+ func unpromptedWorkspaceMutationRejectsEverythingNotStaticallyAnchored() {let ws = "/Users/me/Downloads/donkey/conv1"- // Relative paths and absolute paths inside the workspace stay in.- #expect(ShellCommandClassifier.commandStaysWithin("cp a.pdf out/b.pdf", workspace: ws))- #expect(ShellCommandClassifier.commandStaysWithin("mv data/x.csv \(ws)/y.csv", workspace: ws))- #expect(ShellCommandClassifier.commandStaysWithin("tee fields.json", workspace: ws))- // A sed script that merely contains slashes is not a real path and stays in.- #expect(ShellCommandClassifier.commandStaysWithin("sed -i '' 's/a/b/' file.txt", workspace: ws))- // Absolute-outside, `~`, and `..` escapes all reach out of the workspace.- #expect(!ShellCommandClassifier.commandStaysWithin("cp a.pdf /Users/me/Documents/b.pdf", workspace: ws))- #expect(!ShellCommandClassifier.commandStaysWithin("mv x ~/Desktop/x", workspace: ws))- #expect(!ShellCommandClassifier.commandStaysWithin("cp a.pdf ../b.pdf", workspace: 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+ "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+ "ls \"\(ws)\"", // not a mutator at all+ ] {+ #expect(!ShellCommandClassifier.isUnpromptedWorkspaceMutation(command, workspace: ws), "should prompt: \(command)")+ }}@Testdiff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 6393b459..472dc6e4 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -232,6 +232,13 @@ tokens into a risk tier:| **reversible write** | changing a setting, opening an app | asks once, then remembers the choice || **high risk** | `sudo`, `rm`, `dd`, piping a download into a shell | asks every time, never remembered |+One exception keeps the agent fluent in the folder it owns: file commands (`mv`, `cp`, `mkdir`, `rm`,+`chmod`) whose every path is written out in full inside the conversation's own folder run without a+prompt — including a clean-up chain like `mv … && rm …` where every link is such a command. The agent+managing the files it created shouldn't have to ask. Anything that can't be read off the command line+as staying in that folder — a bare name, a glob, a shell variable, or a chained command that is not+one of those file commands — still asks.+The planner discovers what is available by doing. It runs the command it needsby name, and a "command not found" is just another observation it adapts to —reaching for another tool or reporting what is missing. It never probes the