Skip to content

Open source CapCut alternative.

TypeScript

feat(app): route turns by typed kind so conversation never reaches the action loop

David Le0818003f9cfc
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 389b83db..01958c3c 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -454,37 +454,16 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
progress: (@MainActor @Sendable (String) -> Void)? = nil,
answerStream: (@MainActor @Sendable (String) -> Void)? = nil
) async -> UserQueryCommandHandlingResult {
- guard permissionPolicy.allowedCapabilities.contains(.input) else {
- return await failHarnessRun(
- command: command,
- response: "Vision navigation needs input permission, which isn't granted.",
- reason: "inputNotPermitted",
- appName: "",
- traceID: traceID,
- conversationID: conversationID,
- agentID: agentID,
- preparedTurnMetadata: preparedTurnMetadata
- )
- }
// A resume pins the task's original target, so it can drive that app even when it (or nothing) is
- // frontmost — which is the common case right after a relaunch. A fresh turn with no frontmost app
- // and no pinned target still has nothing to drive, so it fails cleanly.
+ // frontmost — which is the common case right after a relaunch. Resolve the frontmost app up front
+ // (no guard yet): its name feeds the understanding prompt, and a conversational turn needs no app
+ // at all — only the action path below requires one.
let frontmost = MacWindowResolver().frontmostUserAppTarget()
- guard forcedDriveTarget != nil || frontmost != nil else {
- return await failHarnessRun(
- command: command,
- response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",
- reason: "noFrontmostApp",
- appName: "",
- traceID: traceID,
- conversationID: conversationID,
- agentID: agentID,
- preparedTurnMetadata: preparedTurnMetadata
- )
- }
let frontmostAppName = frontmost?.appName ?? forcedDriveTarget?.appName ?? "the frontmost app"
let frontmostBundleIdentifier = frontmost?.bundleIdentifier ?? forcedDriveTarget?.bundleIdentifier
+ // The backend is needed by BOTH paths — the conversational responder and the action loop — so it
+ // is built before the turn is classified.
guard var configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {
return await failHarnessRun(
command: command,
@@ -528,6 +507,57 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
let understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {
await understandingBoundary.understand(command: command, frontmostAppName: frontmostAppName)
}
+
+ // TWO-TIER SPLIT. A turn the understanding boundary typed `.converse` (a greeting, a thanks, a
+ // question answerable in words) never touches the action machinery: it is answered by a responder
+ // that holds no tools, so a misread greeting can't run a command. Gated on the typed enum, never
+ // the user's words. Everything below — the input/frontmost guards and the whole guarded loop —
+ // runs only for an actionable turn. (A nil understanding means the classifier was unavailable;
+ // it degrades to the action path against the raw command, the conservative existing behavior.)
+ if understanding?.turnKind == .converse {
+ return await runConversationalReply(
+ command: command,
+ frontmostAppName: frontmostAppName,
+ backend: backend,
+ transcript: transcript,
+ trace: trace,
+ traceID: traceID,
+ conversationID: conversationID,
+ agentID: agentID,
+ preparedTurnMetadata: preparedTurnMetadata,
+ answerStream: answerStream
+ )
+ }
+
+ // ACTION PATH from here down. These guards are action-only — a conversational turn already
+ // returned above, so it never needs input permission or a frontmost app window to drive.
+ guard permissionPolicy.allowedCapabilities.contains(.input) else {
+ return await failHarnessRun(
+ command: command,
+ response: "Vision navigation needs input permission, which isn't granted.",
+ reason: "inputNotPermitted",
+ appName: frontmostAppName,
+ traceID: traceID,
+ conversationID: conversationID,
+ agentID: agentID,
+ preparedTurnMetadata: preparedTurnMetadata,
+ transcript: transcript
+ )
+ }
+ // A fresh turn with no frontmost app and no pinned target has nothing to drive, so it fails cleanly.
+ guard forcedDriveTarget != nil || frontmost != nil else {
+ return await failHarnessRun(
+ command: command,
+ response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",
+ reason: "noFrontmostApp",
+ appName: frontmostAppName,
+ traceID: traceID,
+ conversationID: conversationID,
+ agentID: agentID,
+ preparedTurnMetadata: preparedTurnMetadata,
+ transcript: transcript
+ )
+ }
if let restated = understanding?.restatedGoal, !restated.isEmpty {
progress?(restated)
}
@@ -1025,6 +1055,80 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
return result
}
+ /// The conversational arm of the two-tier split: a turn typed `.converse` is answered here, with no
+ /// action loop, no tools, no world model, and no permission gate. The reply streams into the notch
+ /// chin token-by-token and the turn completes as a chat message. Because this path is reached only on
+ /// a typed `.converse` classification and the responder holds no tools, a misread greeting can never
+ /// produce a command — the safety is structural, not a matter of planner discipline.
+ @MainActor
+ private func runConversationalReply(
+ command: String,
+ frontmostAppName: String,
+ backend: DonkeyBackendInferenceClient,
+ transcript: ConversationTranscript,
+ trace: HarnessTurnTrace,
+ traceID: String,
+ conversationID: String,
+ agentID: String,
+ preparedTurnMetadata: [String: String],
+ answerStream: (@MainActor @Sendable (String) -> Void)?
+ ) async -> UserQueryCommandHandlingResult {
+ transcript.systemEvent("Conversational turn — responding without driving the Mac.")
+ VisionGroundingLog.emit("conversation traceID=\(traceID) kind=converse")
+
+ // Carry the same bounded rolling conversation context the planner would get, so multi-turn chat
+ // keeps continuity ("what did I just ask?") without ever entering the action loop.
+ let textGenerator = HostedTextGenerator(backend: backend)
+ let compactionDriver = ConversationCompactionDriver(
+ conversationStore: genericHarnessLifecycle.conversationStore,
+ coordinator: genericHarnessLifecycle.coordinator,
+ compactor: genericHarnessLifecycle.compactor,
+ generate: { await textGenerator.generate($0) }
+ )
+ let conversationContext = await compactionDriver.rollingContext(agentID: agentID)
+
+ let responder = HostedHarnessConversationalResponder(backend: backend, trace: trace)
+ let streamed = await responder.respond(
+ command: command,
+ frontmostAppName: frontmostAppName,
+ conversationContext: conversationContext,
+ onDelta: answerStream ?? { _ in }
+ )
+ let reply = (streamed?.isEmpty == false) ? streamed! : "Hey! What can I help you with?"
+ transcript.response(reply)
+ transcript.writeSummary(Self.deterministicThreadSummary(
+ command: command, app: frontmostAppName, outcome: "ok", steps: [], finalDetail: reply
+ ))
+
+ let decision = AppHarnessDecision(
+ kind: .respond,
+ message: reply,
+ traceID: traceID,
+ metadata: ["structuredDecision": "true", "router": "conversation"]
+ )
+ // A conversational turn is genuinely finished — there is no pending work to resume — so the agent
+ // completes. The row still surfaces as `.chatting` so the reply lands in the chin as a message
+ // (the same completed + chatting pairing the empty turn uses).
+ _ = await genericHarnessLifecycle.coordinator.complete(
+ agentID: agentID,
+ reason: "Conversational turn"
+ )
+ let result = UserQueryCommandHandlingResult(
+ status: .completed,
+ threadStatus: .chatting,
+ decision: decision,
+ summary: reply,
+ traceID: traceID,
+ metadata: preparedTurnMetadata.merging([
+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,
+ "appHarness.router": "conversation"
+ ]) { _, new in new }
+ )
+ await coordinatorRegistry.finish(conversationID: conversationID)
+ logHandlingResult(result, stage: "conversation", hint: reply)
+ return result
+ }
+
/// Fail-safe exit for the vision-navigation route when it can't even start (no frontmost app,
/// backend unconfigured, input not permitted). Mirrors the other non-local routes' lifecycle.
/// Even an aborted start gets a thread file: the thread is the session's complete record, and a
@@ -1037,12 +1141,21 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
traceID: String,
conversationID: String,
agentID: String,
- preparedTurnMetadata: [String: String]
+ preparedTurnMetadata: [String: String],
+ transcript existingTranscript: ConversationTranscript? = nil
) async -> UserQueryCommandHandlingResult {
VisionGroundingLog.emit("aborted traceID=\(traceID) reason=\(reason) app=\(appName)")
- let transcript = ConversationTranscript(id: conversationID)
- transcript.begin(id: conversationID, app: appName)
- transcript.userMessage(command)
+ // Reuse the turn's open transcript when the abort happens after it was started (the action-only
+ // guards run after the user message is already recorded); otherwise open a fresh one, since even
+ // a turn that never got past its first guard must still leave a thread file on disk.
+ let transcript: ConversationTranscript
+ if let existingTranscript {
+ transcript = existingTranscript
+ } else {
+ transcript = ConversationTranscript(id: conversationID)
+ transcript.begin(id: conversationID, app: appName)
+ transcript.userMessage(command)
+ }
transcript.error("Run could not start (\(reason)).")
transcript.response(response)
let decision = AppHarnessDecision(
@@ -1211,7 +1324,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
private static var userQueryGrantedPermissions: Set<HarnessPermission> {
- [
+ // Internal capabilities are always available; the macOS-backed ones (screen capture,
+ // accessibility, input) are kept only when the system grants them right now. A missing one
+ // drops out so the first tool that needs it stops at the notch gate and is requested in the
+ // conversation — onboarding is optional, not a prerequisite.
+ HarnessSystemPermissionBridge.granting([
.conversation,
.userPrompt,
.verification,
@@ -1222,7 +1339,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
.screenCapture,
.accessibility,
.input
- ]
+ ])
}
/// Picks the app the harness drive operates. The understood target app wins whenever it names a
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index eb508dd8..23fb0fa8 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -36,7 +36,12 @@ public enum DonkeyPrompts {
/// `CommandLayerFunctionDeclarations` / `DonkeyCommandLayer`), not here.
public static let realtimeCommandSystemInstruction = """
You are Donkey, a fast macOS assistant — an expert computer user sitting next \
- to the user. Act directly and immediately with the registered tools, preferring \
+ 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 \
@@ -98,7 +103,21 @@ public enum DonkeyPrompts {
USER REQUEST: \(command)
Fill the fields:
- - restatedGoal: one concrete imperative sentence capturing exactly what to accomplish.
+ - turnKind: what this turn fundamentally is. Decide this FIRST and let it govern everything else:
+ - "converse": a greeting ("hi", "hey", "yo"), thanks, acknowledgement, small talk, or a
+ question you can answer in words alone — about you, your abilities, general knowledge, or the
+ conversation so far — WITHOUT doing anything on the Mac. When in doubt between converse and
+ act for a bare greeting or a "can you…"/"what is…" question, choose converse. A conversational
+ turn must NEVER be turned into a task: do not invent a command, an app to open, or a thing to
+ fetch. There is no default action for "hi".
+ - "act": the user wants something actually DONE on the machine — open/launch/quit an app, play
+ or control media, find or open files, read or change a setting, write or edit a file, operate
+ an app, send/post something, run a command. Only this kind ever drives the Mac.
+ - "clarify": actionable in spirit, but too ambiguous or missing a critical, user-owned detail to
+ proceed safely (and you cannot reasonably pick a default). Used with needsClarification=true.
+ - restatedGoal: for "act"/"clarify", one concrete imperative sentence capturing exactly what to
+ accomplish. For "converse", a short restatement of what the user said or is asking — NOT an
+ invented task. Never leave this empty.
Resolve casual or incomplete phrasing into the likely concrete intent ("turn it down a
little" → lower the volume; "the new Taylor album" → the latest Taylor Swift album).
- targetAppName: the macOS app that must be driven through its GUI to do this. Set it only when
@@ -109,9 +128,10 @@ public enum DonkeyPrompts {
- parameters: the concrete details needed to do it (e.g. title, recipient, query, value), as
string key/values. Omit what is not specified.
- successCriteria: what would be visible on screen once the goal is done.
- - needsClarification: set true ONLY when the request is genuinely ambiguous or missing detail
- that you cannot reasonably resolve, or when it is destructive without a clear target. For an
- under-specified but low-risk, reversible request, pick sensible specifics and set this false.
+ - needsClarification: set true exactly when turnKind is "clarify" — the request is genuinely
+ ambiguous or missing detail that you cannot reasonably resolve, or it is destructive without a
+ clear target. Always false for "converse" and for an under-specified but low-risk, reversible
+ "act" request (pick sensible specifics instead).
Do NOT ask for a detail the request already implies (the request named the language, the
source, or the file — use it), and do NOT ask the user to choose HOW to do the work or
whether some resource exists; deciding the method and finding things out yourself is your
@@ -127,6 +147,43 @@ public enum DonkeyPrompts {
"""
}
+ // MARK: - Conversational reply (turnKind == .converse, no action loop)
+
+ /// The responder for a conversational turn. It has NO tools and cannot touch the Mac — by
+ /// construction, not by instruction — so this prompt is purely about voice and substance. A turn
+ /// only reaches here once the understanding boundary typed it `.converse`; the action planner and
+ /// every guarded tool are out of scope. Reply text streams straight into the notch.
+ public static func conversationalResponse(
+ command: String,
+ frontmostAppName: String,
+ conversationContext: String?
+ ) -> String {
+ let contextBlock: String
+ if let conversationContext, !conversationContext.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ contextBlock = "\nCONVERSATION SO FAR (most recent last):\n\(conversationContext)\n"
+ } else {
+ contextBlock = ""
+ }
+ return """
+ You are Donkey: a fast, friendly macOS assistant who lives in the notch and can 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 to three short, warm sentences. Be genuinely helpful and concrete. If the user is \
+ just saying hello, greet them back and, in a few words, offer what you can do ("I can play music, \
+ find files, tweak settings, draft things — what do you need?") without dumping a feature list. 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.
+ \(contextBlock)
+ The app in front of them is "\(frontmostAppName)".
+
+ USER: \(command)
+
+ Reply with the message text only — no JSON, no quotes, no preamble.
+ """
+ }
+
// MARK: - Harness step planning (every step of the loop)
/// At most this many world-model elements are described to the model
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessConversationalResponder.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessConversationalResponder.swift
new file mode 100644
index 00000000..112235c4
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessConversationalResponder.swift
@@ -0,0 +1,59 @@
+import DonkeyContracts
+import Foundation
+
+/// The conversational arm of the two-tier turn split. When the request-understanding boundary types a
+/// turn `.converse` (a greeting, a thanks, a question answerable in words), the caller routes here
+/// instead of into the action loop.
+///
+/// The defining property is what this boundary CANNOT do: it is handed no tool registry, no world
+/// model, and no executor, so it can only produce text. A greeting that was misread can at worst yield
+/// a slightly-off reply — never a shell command, an app action, or a permission prompt. That safety is
+/// structural, which is the whole point of separating the responder from the action planner.
+@MainActor
+public final class HostedHarnessConversationalResponder {
+ private let generator: HostedTextGenerator
+ /// Optional turn-trace sink. The single responder call is recorded with its clipped prompt, clipped
+ /// reply, and span, so a conversational turn is as traceable in the thread as a planned one.
+ private let trace: (any HarnessTurnTracing)?
+
+ public init(backend: DonkeyBackendInferenceClient, trace: (any HarnessTurnTracing)? = nil) {
+ // A conversational reply is short and wants to feel instant; a tight cap keeps it snappy.
+ self.generator = HostedTextGenerator(backend: backend, maxOutputTokens: 800, timeoutSeconds: 30)
+ self.trace = trace
+ }
+
+ /// Streams a conversational reply for `command`, delivering each delta to `onDelta` as it arrives
+ /// and returning the full text. `conversationContext` is the bounded rolling view of the thread so
+ /// far (nil on a fresh turn). Returns nil only on a transport/empty failure, so the caller can fall
+ /// back to a plain greeting rather than showing nothing.
+ public func respond(
+ command: String,
+ frontmostAppName: String,
+ conversationContext: String?,
+ onDelta: @escaping @MainActor @Sendable (String) -> Void
+ ) async -> String? {
+ let prompt = DonkeyPrompts.conversationalResponse(
+ command: command,
+ frontmostAppName: frontmostAppName,
+ conversationContext: conversationContext
+ )
+ let startedAt = RunTraceTimestamp.now()
+ // Prefer the streamed reply so it types into the chin live; if streaming is unavailable or fails
+ // (transport, empty), fall back to a single non-streaming generation so a real question still gets
+ // a real answer instead of a canned greeting.
+ var reply = await generator.generateStreaming(prompt, onDelta: onDelta)
+ if reply?.isEmpty != false {
+ reply = await generator.generate(prompt)
+ }
+ trace?.recordModelCall(TraceModelCall(
+ kind: .conversationalReply,
+ prompt: prompt,
+ response: reply ?? "<no output text>",
+ finishReason: nil,
+ status: (reply?.isEmpty == false) ? .ok : .empty,
+ startedAt: startedAt,
+ endedAt: .now()
+ ))
+ return reply
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
index 7a17e31c..43334341 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
@@ -9,7 +9,13 @@ import Foundation
/// this only sharpens what "the goal" means and which app to drive, so the planner stops re-deriving
/// intent from a raw string on every step.
public struct HarnessRequestUnderstanding: Sendable, Equatable {
- /// The user's request restated as one concrete imperative goal.
+ /// What this turn fundamentally is: a conversation, an action on the Mac, or a clarifying question.
+ /// Decided here, before any action machinery exists, and the single fact the caller routes on —
+ /// only `.act` ever reaches the action planner. A `.converse` turn is answered by a responder that
+ /// holds no action tools, so a misclassified greeting can never run a command.
+ public var turnKind: HarnessTurnKind
+ /// The user's request restated. For `.act`/`.clarify` it is one concrete imperative goal; for
+ /// `.converse` it is a short restatement of what the user said, never an invented task.
public var restatedGoal: String
/// The macOS app the request needs to operate through its GUI. Left nil/empty for pure
/// conversation, for whatever app is already frontmost, and for tasks an expert would do with
@@ -31,6 +37,7 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {
public var executionPreference: ExecutionPreference
public init(
+ turnKind: HarnessTurnKind = .act,
restatedGoal: String,
targetAppName: String? = nil,
parameters: [String: String] = [:],
@@ -39,6 +46,7 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {
clarifyingQuestion: String? = nil,
executionPreference: ExecutionPreference = .background
) {
+ self.turnKind = turnKind
self.restatedGoal = restatedGoal
self.targetAppName = targetAppName
self.parameters = parameters
@@ -87,6 +95,7 @@ public final class HostedHarnessRequestUnderstanding {
let restated = wire.restatedGoal?.trimmingCharacters(in: .whitespacesAndNewlines)
guard let restated, !restated.isEmpty else { return nil }
return HarnessRequestUnderstanding(
+ turnKind: wire.turnKind.flatMap { HarnessTurnKind(rawValue: $0) } ?? .act,
restatedGoal: restated,
targetAppName: wire.targetAppName.flatMap { $0.isEmpty ? nil : $0 },
parameters: wire.parameters ?? [:],
@@ -125,6 +134,7 @@ public final class HostedHarnessRequestUnderstanding {
// MARK: - Wire
private struct UnderstandingWire: Decodable {
+ var turnKind: String?
var restatedGoal: String?
var targetAppName: String?
var parameters: [String: String]?
@@ -134,12 +144,13 @@ public final class HostedHarnessRequestUnderstanding {
var executionPreference: String?
private enum CodingKeys: String, CodingKey {
- case restatedGoal, targetAppName, parameters, successCriteria, needsClarification, clarifyingQuestion
+ case turnKind, restatedGoal, targetAppName, parameters, successCriteria, needsClarification, clarifyingQuestion
case executionPreference
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
+ turnKind = try container.decodeIfPresent(String.self, forKey: .turnKind)
restatedGoal = try container.decodeIfPresent(String.self, forKey: .restatedGoal)
targetAppName = try container.decodeIfPresent(String.self, forKey: .targetAppName)
successCriteria = try container.decodeIfPresent(String.self, forKey: .successCriteria)
@@ -203,8 +214,12 @@ public final class HostedHarnessRequestUnderstanding {
"schema": .object([
"type": .string("object"),
"additionalProperties": .bool(false),
- "required": .array([.string("restatedGoal"), .string("needsClarification")]),
+ "required": .array([.string("turnKind"), .string("restatedGoal"), .string("needsClarification")]),
"properties": .object([
+ "turnKind": .object([
+ "type": .string("string"),
+ "enum": .array([.string("converse"), .string("act"), .string("clarify")])
+ ]),
"restatedGoal": .object(["type": .string("string")]),
"targetAppName": .object(["type": .string("string")]),
"parameters": .object([
diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
index a7839f45..d89aedbb 100644
--- a/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessTraceContracts.swift
@@ -8,6 +8,8 @@ public enum TraceModelCallKind: String, Codable, Equatable, Sendable {
case understanding
/// A per-step planning call (the first sample or a feedback-driven retry).
case plannerStep
+ /// The single responder call for a conversational turn (turnKind == .converse). No tools, no loop.
+ case conversationalReply
/// The background call that rewrites the compacted thread summary.
case conversationSummary
}
diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessTurnKind.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessTurnKind.swift
new file mode 100644
index 00000000..4849041e
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessTurnKind.swift
@@ -0,0 +1,22 @@
+import Foundation
+
+/// What a user turn fundamentally is, decided once by the request-understanding boundary before any
+/// action machinery is touched. This is the first-class routing fact behind "conversations first":
+/// a turn becomes a conversation, an action, or a clarifying question — and only `.act` is ever allowed
+/// to reach the action planner and the Mac.
+///
+/// Like ``ExecutionPreference``, this is a typed field the model sets — never inferred by matching the
+/// user's words. Deterministic code branches on this enum, never on the raw string. A greeting or a
+/// plain question classifies as `.converse` and is answered by a responder that holds no action tools,
+/// so a misread can never run a shell command.
+public enum HarnessTurnKind: String, Codable, Equatable, Sendable {
+ /// A greeting, acknowledgement, small talk, or a question answerable in words without driving the
+ /// Mac. Routed to the conversational responder; no action loop, no tools, no permission gate.
+ case converse
+ /// A request to actually do something on the machine (open, play, find, change, send, write a file,
+ /// operate an app). The only kind that enters the guarded action loop.
+ case act
+ /// Actionable in spirit but too ambiguous or missing a critical, user-owned detail to proceed
+ /// safely. The turn asks one specific question before doing anything.
+ case clarify
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift b/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
index 8548eb04..b13d6f78 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/HarnessTurnTrace.swift
@@ -126,6 +126,7 @@ public final class HarnessTurnTrace: HarnessTurnTracing, @unchecked Sendable {
switch kind {
case .understanding: return "understanding"
case .plannerStep: return "planner step"
+ case .conversationalReply: return "conversational reply"
case .conversationSummary: return "thread summary"
}
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift
new file mode 100644
index 00000000..9c47dcfc
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift
@@ -0,0 +1,67 @@
+import DonkeyAI
+import DonkeyContracts
+import Foundation
+import Testing
+
+/// The two-tier split lives or dies on this one decoded field: `turnKind` is what routes a turn to the
+/// no-tools responder versus the action loop. These tests pin the wire decode so a greeting classified
+/// `converse` never silently falls through to the action path (the "hi → curl wttr.in" failure).
+@Suite
+@MainActor
+struct HostedHarnessRequestUnderstandingTests {
+ private func understanding(forResponseJSON json: String) async -> HarnessRequestUnderstanding? {
+ // The backend wraps the model's text under `output_text`; the boundary pulls the JSON object out
+ // of it and decodes the typed understanding.
+ let envelope = try! JSONSerialization.data(withJSONObject: ["output_text": json])
+ let backend = DonkeyBackendInferenceClient(
+ configuration: DonkeyBackendInferenceConfiguration(
+ baseURL: URL(string: "https://donkey.example")!,
+ clientID: "client-1"
+ ),
+ httpClient: SingleResponseHTTPClient(data: envelope, statusCode: 200)
+ )
+ return await HostedHarnessRequestUnderstanding(backend: backend)
+ .understand(command: "hi", frontmostAppName: "Finder")
+ }
+
+ @Test
+ func classifiesAGreetingAsConverse() async {
+ let result = await understanding(forResponseJSON: #"""
+ {"turnKind":"converse","restatedGoal":"The user said hi.","needsClarification":false}
+ """#)
+ #expect(result?.turnKind == .converse)
+ #expect(result?.needsClarification == false)
+ }
+
+ @Test
+ func classifiesADoableRequestAsAct() async {
+ let result = await understanding(forResponseJSON: #"""
+ {"turnKind":"act","restatedGoal":"Lower the system volume.","targetAppName":"","needsClarification":false}
+ """#)
+ #expect(result?.turnKind == .act)
+ }
+
+ @Test
+ func anUnknownOrMissingTurnKindDegradesToAct() async {
+ // A reply missing the field (older model, partial output) must NOT accidentally route to the
+ // responder — the conservative default is the action path, matching the nil-understanding degrade.
+ let result = await understanding(forResponseJSON: #"""
+ {"restatedGoal":"Open Safari.","needsClarification":false}
+ """#)
+ #expect(result?.turnKind == .act)
+ }
+}
+
+private final class SingleResponseHTTPClient: AIHTTPClient, @unchecked Sendable {
+ let data: Data
+ let statusCode: Int
+
+ init(data: Data, statusCode: Int) {
+ self.data = data
+ self.statusCode = statusCode
+ }
+
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ (data, HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: nil, headerFields: [:])!)
+ }
+}