Skip to content

Open source CapCut alternative.

TypeScript

feat(app): surface the skill catalog to the step planner and persist its thinking

David Lebb8972d29fa2
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 367534cd..71f23e56 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -393,7 +393,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
appName: appName,
appGuidance: appGuidance,
understanding: understanding,
- environmentSummary: environmentSummary
+ environmentSummary: environmentSummary,
+ skillCatalog: Self.installedSkillCatalog()
)
_ = await genericHarnessLifecycle.coordinator.startRunning(
taskID: taskID,
@@ -426,7 +427,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
await MainActor.run {
let narration = Self.stepNarration(for: step, planner: planner)
if let result = step.toolResult {
- transcript.thinking(narration)
+ // The thread file gets the model's full thought summary (when thinking is on);
+ // the overlay/progress gets only the clipped one-line narration below. The full
+ // reasoning is persisted here and nowhere else, so the planning context stays bounded.
+ transcript.thinking(planner.lastThinking ?? narration)
transcript.toolCall(tool: result.toolName, input: step.task.toolHistory.last?.call.input ?? [:])
transcript.toolResult(tool: result.toolName, status: result.status.rawValue, output: result.summary)
}
@@ -802,6 +806,27 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
return (resolved.appName ?? requested, resolved.bundleIdentifier)
}
+ /// A compact, one-line-per-skill catalog of every installed app skill — id, description, the apps it
+ /// covers, and any validated `skill_run` scripts — surfaced to the planner each step. App-specific
+ /// guidance is only preloaded for the resolved GUI drive target, so without this the planner never
+ /// learns that a script-driven skill (e.g. Music playback, Notes capture) exists when the task has no
+ /// GUI target app — and it improvises fragile commands instead of running the validated script.
+ /// Lists every skill unconditionally; the planner does the routing, so no intent is matched here.
+ private static func installedSkillCatalog() -> String? {
+ let skills = BuiltInLocalAppSkillPacks.descriptors().sorted { $0.id < $1.id }
+ guard !skills.isEmpty else { return nil }
+ let lines = skills.map { skill -> String in
+ let apps = (skill.metadata["apps"]?.isEmpty == false) ? " · apps: \(skill.metadata["apps"]!)" : ""
+ let scripts = skill.scripts.isEmpty
+ ? ""
+ : " · skill_run: " + skill.scripts.map { script in
+ script.purpose.isEmpty ? script.id : "\(script.id) (\(script.purpose))"
+ }.joined(separator: ", ")
+ return " - \(skill.id) — \(skill.description)\(apps)\(scripts)"
+ }
+ return lines.joined(separator: "\n")
+ }
+
/// Builds a one-step cursor-path visualization toward the exact screen point a just-executed action
/// clicked, in screen-normalized coordinates for the overlay. Returns nil for steps that did not
/// move the pointer (observation, conversation, AXPress without a coordinate fallback).
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index 19a5fd03..c36da4af 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -129,6 +129,7 @@ public enum DonkeyPrompts {
appGuidance: String?,
understanding: HarnessRequestUnderstanding?,
environmentSummary: String?,
+ skillCatalog: String? = nil,
retryNote: String? = nil
) -> String {
let elementsBlock = harnessStepElementsBlock(task.worldModel.elements)
@@ -163,6 +164,16 @@ public enum DonkeyPrompts {
guidanceBlock = ""
}
+ // The full installed-skill catalog, so the planner can route to an authoritative playbook even
+ // when the task has no GUI target app (e.g. playing music or saving a note by script): those
+ // skills are not preloaded above because no specific app window is being driven.
+ let skillCatalogBlock: String
+ if let skillCatalog, !skillCatalog.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ skillCatalogBlock = "\nINSTALLED APP SKILLS (authoritative playbooks for these apps/domains — when the task maps to one, get its full guide with app_skill and run its validated scripts with skill_run instead of improvising raw commands):\n\(skillCatalog)\n"
+ } else {
+ skillCatalogBlock = ""
+ }
+
// Prefer the restated goal parsed once up front; fall back to the raw task goal when no
// understanding was produced.
let restatedGoal = understanding?.restatedGoal
@@ -177,7 +188,7 @@ public enum DonkeyPrompts {
GOAL: \(goalText)
\(understandingBlock)
\(historyBlock)
- \(factsBlock)\(environmentBlock)\(guidanceBlock)
+ \(factsBlock)\(environmentBlock)\(guidanceBlock)\(skillCatalogBlock)
\(elementsBlock)
AVAILABLE TOOLS:
@@ -193,9 +204,11 @@ public enum DonkeyPrompts {
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".
- - Driving a specific app with no operating guide above? Look its skill up first (app_skill, or
- skill.search for workflows) — the installed skill is the authority on how that app is
- operated and overrides assumptions.
+ - 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. 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.
- 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. To build a long note/document (a tracklist, lyrics, a
@@ -211,6 +224,10 @@ public enum DonkeyPrompts {
- 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.
Return JSON: {"tool": "<one tool name>", "input": {"key": "value", ...}, "reason": "<one sentence>"}.\(retryNote.map { "\nIMPORTANT: \($0)" } ?? "")
"""
}
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index 861373a7..bc976559 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -24,6 +24,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// One-line summary of which command-line tools are installed on this Mac (and versions), so the
/// planner only reaches for tools that exist. Empty when the probe was skipped or found nothing.
private let environmentSummary: String?
+ /// Compact catalog of every installed app skill (id, description, covered apps, validated scripts),
+ /// so the planner can route to an authoritative playbook even when no GUI app is the drive target —
+ /// e.g. playing music or saving a note by script. nil when no skills are installed.
+ private let skillCatalog: String?
private let uptimeMS: @Sendable () -> Double
/// Uptime (ms) at which the planner first chose an *action* tool (something that changes app
@@ -32,12 +36,21 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
public private(set) var firstActionUptimeMS: Double?
/// Most recent one-line rationale, surfaced to the user as the run's narration.
public private(set) var lastNarration: String?
+ /// The model's full thought summary for the most recent step, when thinking is enabled. Persisted
+ /// to the thread transcript (not fed back into the per-step prompt, so context stays bounded).
+ public private(set) var lastThinking: String?
/// Names of the registered read-only tools (observe/verify/respond/lifecycle), derived from each
/// descriptor's safety class. A tool counts as an "action" for first-action timing exactly when it
/// is NOT read-only, so this stays in sync with the tools instead of a hand-maintained name list.
private let readOnlyToolNames: Set<String>
+ /// Per-tool required input keys (every declared input minus the optional ones). Used to catch a
+ /// malformed decision that names a tool but omits all of its required input — emitting that only
+ /// yields `invalidInput`, and repeated it fails the run (a real failure mode: an empty `shell_exec`
+ /// looping until failSafe). The planner retries once with a corrective note instead.
+ private let requiredInputKeys: [String: Set<String>]
+
public init(
backend: DonkeyBackendInferenceClient,
descriptors: [HarnessToolDescriptor],
@@ -45,6 +58,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
appGuidance: String?,
understanding: HarnessRequestUnderstanding? = nil,
environmentSummary: String? = nil,
+ skillCatalog: String? = nil,
uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }
) {
self.backend = backend
@@ -53,8 +67,13 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
self.appGuidance = appGuidance
self.understanding = understanding
self.environmentSummary = environmentSummary
+ self.skillCatalog = skillCatalog
self.uptimeMS = uptimeMS
self.readOnlyToolNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))
+ self.requiredInputKeys = Dictionary(
+ descriptors.map { ($0.name, Set($0.inputSchema.keys).subtracting($0.optionalInputKeys)) },
+ uniquingKeysWith: { current, _ in current }
+ )
}
public func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {
@@ -69,43 +88,69 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
descriptors.contains(where: { $0.name == "user.clarify" }) {
return HarnessToolCall(name: "user.clarify", input: ["question": question])
}
- // One bad model sample must not kill the run, and an empty tool name must never read as
- // completion (a refusal or truncated reply would otherwise be recorded as success). Retry the
- // inference once with the failure fed back; only then fail safe.
+ // One bad model sample must not kill the run. Following the Hermes agent's recovery model, a
+ // malformed, empty, or under-specified decision is fed back to the model and re-asked up to
+ // `maxPlanAttempts` times — and each retry boosts the output-token budget, so a reply truncated
+ // at the cap can complete on the next try. Only after the budget is spent do we fail safe. An
+ // empty tool name never reads as completion (a refusal/truncation would otherwise record as
+ // success); the runtime's stall guard remains the final backstop for genuine loops.
var retryNote: String?
- for attempt in 0..<2 {
+ let lastAttempt = Self.maxPlanAttempts - 1
+ for attempt in 0...lastAttempt {
let decision: Decision
do {
- decision = try await decide(task: task, retryNote: retryNote)
+ decision = try await decide(task: task, retryNote: retryNote, attempt: attempt)
} catch {
- guard attempt == 0 else { break }
+ guard attempt < lastAttempt else { break }
retryNote = "Your previous reply could not be used (\(String(describing: error).prefix(200))). "
- + "Reply with exactly one JSON object naming one tool from AVAILABLE TOOLS."
+ + "Reply with exactly ONE JSON object naming one tool from AVAILABLE TOOLS, with every "
+ + "required input field filled. For a tool that needs no input, use an empty object: {}."
continue
}
lastNarration = decision.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration
+ lastThinking = decision.thinking.flatMap { $0.isEmpty ? nil : $0 }
guard let toolName = decision.tool.flatMap({ $0.isEmpty ? nil : $0 }) else {
- guard attempt == 0 else {
+ guard attempt < lastAttempt else {
return HarnessToolCall(name: "run.failSafe", input: ["reason": "plannerReturnedNoTool"])
}
retryNote = "Your previous reply named no tool. Pick exactly one tool from AVAILABLE TOOLS; "
+ "choose run.complete only when the goal is already confirmed by observed evidence."
continue
}
+ // Catch a malformed decision that names a tool but supplies none of its required input.
+ // Re-ask with a corrective note; once the retry budget is spent, let it through and rely on
+ // the runtime's invalidInput + stall handling so we never loop here.
+ let providedInput = decision.input ?? [:]
+ if attempt < lastAttempt,
+ let required = requiredInputKeys[toolName], !required.isEmpty,
+ Set(providedInput.keys).isDisjoint(with: required) {
+ let keys = required.sorted().joined(separator: ", ")
+ retryNote = "Your previous reply chose \(toolName) but included none of its required input "
+ + "(\(keys)). Re-issue \(toolName) with that input filled in, or choose a different tool."
+ continue
+ }
if !readOnlyToolNames.contains(toolName), firstActionUptimeMS == nil {
firstActionUptimeMS = uptimeMS()
}
- return HarnessToolCall(name: toolName, input: decision.input ?? [:])
+ return HarnessToolCall(name: toolName, input: providedInput)
}
return HarnessToolCall(name: "run.failSafe", input: ["reason": "harnessPlanFailed"])
}
+ /// Max planning samples per step before failing safe. The first is the normal call; the rest are
+ /// feedback-driven retries (malformed JSON, empty tool, missing required input, or a reply truncated
+ /// at the token cap). Mirrors the Hermes agent's "retry up to 3 with feedback" recovery.
+ private static let maxPlanAttempts = 3
+
// MARK: - Model call
private struct Decision: Sendable {
var tool: String?
var input: [String: String]?
var reason: String?
+ /// The model's full thought summary for this step (thinking enabled), persisted to the thread.
+ /// Separate from `reason`, which is the one-line rationale shown live in the overlay.
+ var thinking: String?
}
private struct DecisionWire: Decodable {
@@ -164,8 +209,24 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// caller fails safe instead of stalling the whole run on a hung provider.
private static let stepTimeoutSeconds: TimeInterval = 45
- private func decide(task: HarnessTaskState, retryNote: String?) async throws -> Decision {
- let request = responseRequest(task: task, retryNote: retryNote)
+ /// Thinking level for each planning step. The planner runs on a Gemini 3.x model, which takes a
+ /// `thinking_level` (minimal | low | medium | high), NOT the legacy integer `thinking_budget` —
+ /// that knob is silently ignored on these models. `medium` is the model's own default and gives the
+ /// strongest everyday decision quality on the one call that decides everything (which tool, what
+ /// input, act-vs-verify-vs-complete); we set it explicitly so the choice is intentional rather than
+ /// an accident of an ignored parameter. The reasoning summary is persisted to the thread; it is
+ /// never fed back into the prompt, so context stays bounded.
+ private static let plannerThinkingLevel = "medium"
+
+ /// Base output-token budget for a planning reply, and the ceiling a boosted retry may reach. Sized
+ /// with headroom for both the thinking and the tool-call JSON. Each retry raises the budget
+ /// (`base * (attempt + 1)`, capped) so a reply truncated at the cap can complete — the Hermes
+ /// agent's truncation-recovery boost.
+ private static let baseMaxOutputTokens = 3_000
+ private static let maxOutputTokensCap = 8_000
+
+ private func decide(task: HarnessTaskState, retryNote: String?, attempt: Int) async throws -> Decision {
+ let request = responseRequest(task: task, retryNote: retryNote, attempt: attempt)
let backend = self.backend
let response = try await AIDeadline.enforce(seconds: Self.stepTimeoutSeconds) {
try await backend.createResponse(request)
@@ -176,11 +237,17 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
}
let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)
let wire = try JSONDecoder().decode(DecisionWire.self, from: Data(json.utf8))
- return Decision(tool: wire.tool, input: wire.input, reason: wire.reason)
+ return Decision(
+ tool: wire.tool,
+ input: wire.input,
+ reason: wire.reason,
+ thinking: RemoteInferenceResponseHelpers.reasoningText(from: response)
+ )
}
- private func responseRequest(task: HarnessTaskState, retryNote: String?) -> RemoteInferenceResponseCreateRequest {
+ private func responseRequest(task: HarnessTaskState, retryNote: String?, attempt: Int) -> RemoteInferenceResponseCreateRequest {
let toolNames = descriptors.map(\.name)
+ let maxOutputTokens = min(Self.baseMaxOutputTokens * (attempt + 1), Self.maxOutputTokensCap)
return RemoteInferenceResponseCreateRequest(
input: .array([
.object([
@@ -195,6 +262,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
appGuidance: appGuidance,
understanding: understanding,
environmentSummary: environmentSummary,
+ skillCatalog: skillCatalog,
retryNote: retryNote
))
])
@@ -228,8 +296,8 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
metadata: ["source": "hosted-harness-step-planner", "prompt_version": "harness-step-v1"],
parameters: [
"temperature": .number(0),
- "max_output_tokens": .number(2_000),
- "thinking_budget": .number(0)
+ "max_output_tokens": .number(Double(maxOutputTokens)),
+ "thinking_level": .string(Self.plannerThinkingLevel)
]
)
}
diff --git a/apps/Donkey/Sources/DonkeyAI/RemoteInferenceResponseHelpers.swift b/apps/Donkey/Sources/DonkeyAI/RemoteInferenceResponseHelpers.swift
index 8b994fe1..e1d4d566 100644
--- a/apps/Donkey/Sources/DonkeyAI/RemoteInferenceResponseHelpers.swift
+++ b/apps/Donkey/Sources/DonkeyAI/RemoteInferenceResponseHelpers.swift
@@ -26,6 +26,18 @@ enum RemoteInferenceResponseHelpers {
return nil
}
+ /// The model's thought summary, when thinking was enabled. The backend separates this from
+ /// `output_text` (which carries the structured tool-call JSON), so reasoning can be persisted to
+ /// the thread without corrupting the decision parse. nil/empty when thinking was off.
+ static func reasoningText(from value: RemoteInferenceJSONValue) -> String? {
+ guard let text = value.objectValue?["reasoning_text"]?.stringValue,
+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ return nil
+ }
+ return text
+ }
+
static func jsonValue(_ value: Any) -> RemoteInferenceJSONValue {
switch value {
case let string as String:
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
index cb642ec5..067fff4d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/ThreadTranscript.swift
@@ -68,10 +68,12 @@ public final class ThreadTranscript: @unchecked Sendable {
appendEntry(role: .user, kind: .message, title: nil, body: text, fenced: false)
}
- /// The assistant's reasoning before a tool call.
+ /// The assistant's reasoning before a tool call — the model's thought summary when thinking is on,
+ /// otherwise the one-line rationale. Bounded so a verbose chain of thought can't bloat the thread
+ /// file; the full reasoning lives only here, never in the per-step planning prompt.
public func thinking(_ text: String?) {
guard let text = text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else { return }
- appendEntry(role: .assistant, kind: .thinking, title: nil, body: text, fenced: false)
+ appendEntry(role: .assistant, kind: .thinking, title: nil, body: Self.clip(text, 4_000), fenced: false)
}
/// The assistant invoking a tool, with its input.
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
new file mode 100644
index 00000000..39976241
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
@@ -0,0 +1,46 @@
+import DonkeyAI
+import DonkeyHarness
+import Foundation
+import Testing
+
+@Suite
+struct HarnessStepPromptTests {
+ private func task(goal: String) -> HarnessTaskState {
+ HarnessTaskState(id: "t", threadID: "th", goal: goal, status: .running, worldModel: HarnessWorldModel())
+ }
+
+ /// The installed-skill catalog must reach the planner prompt verbatim, with routing instructions —
+ /// this is what lets the planner run a validated `skill_run` script for "play music"/"save a note"
+ /// instead of improvising osascript when no GUI app is the drive target (the loop the user hit).
+ @Test
+ func includesSkillCatalogAndRoutingInstruction() {
+ let catalog = " - music — Play music locally in Apple Music · apps: Music · skill_run: scripts-play-media-by-search (Play Media By Search)"
+ let prompt = DonkeyPrompts.harnessStep(
+ task: task(goal: "play some coldplay"),
+ descriptors: [],
+ appName: "iTerm2",
+ appGuidance: nil,
+ understanding: nil,
+ environmentSummary: nil,
+ skillCatalog: catalog
+ )
+ #expect(prompt.contains("authoritative playbooks for these apps/domains"))
+ #expect(prompt.contains("scripts-play-media-by-search"))
+ #expect(prompt.contains("skill_run"))
+ }
+
+ /// With no catalog the block is omitted entirely (no empty header dangling in the prompt).
+ @Test
+ func omitsSkillCatalogWhenNil() {
+ let prompt = DonkeyPrompts.harnessStep(
+ task: task(goal: "what time is it"),
+ descriptors: [],
+ appName: "iTerm2",
+ appGuidance: nil,
+ understanding: nil,
+ environmentSummary: nil,
+ skillCatalog: nil
+ )
+ #expect(!prompt.contains("authoritative playbooks for these apps/domains"))
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift
index 024e1333..1e0218e7 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift
@@ -104,8 +104,12 @@ struct HostedHarnessStepPlannerTests {
}
@Test
- func failsSafeAfterTwoFailedInferences() async {
+ func failsSafeAfterThreeFailedInferences() async {
+ // Following Hermes' "retry up to 3 with feedback", the planner re-asks twice before failing
+ // safe — three model round-trips total — and each retry boosts the output-token budget so a
+ // reply truncated at the cap can complete on a later attempt.
let httpClient = SequencedHTTPClient(responses: [
+ (Data(), 500),
(Data(), 500),
(Data(), 500)
])
@@ -114,7 +118,10 @@ struct HostedHarnessStepPlannerTests {
let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))
#expect(call?.name == "run.failSafe")
- #expect(httpClient.requests.count == 2)
+ #expect(httpClient.requests.count == 3)
+ // The retried requests raise max_output_tokens (2000 → 4000 → 6000) to recover truncation.
+ #expect(maxOutputTokens(httpClient, index: 1) > maxOutputTokens(httpClient, index: 0))
+ #expect(maxOutputTokens(httpClient, index: 2) > maxOutputTokens(httpClient, index: 1))
}
@Test
@@ -148,6 +155,66 @@ struct HostedHarnessStepPlannerTests {
#expect(retryBody.contains("named no tool"))
}
+ @Test
+ func capturesThinkingFromResponseAndRequestsAThinkingLevel() async {
+ // Thinking is enabled on the planning call via thinking_level (the param Gemini 3.x honors, not
+ // the legacy integer budget), and the model's thought summary (returned separately from
+ // output_text so it can't corrupt the decision JSON) is captured for the thread transcript.
+ let httpClient = FixtureHTTPClient(
+ data: Data(#"{"output_text":"{\"tool\":\"ax.observe\",\"reason\":\"look first\"}","reasoning_text":"The window state is unknown, so I observe before acting."}"#.utf8),
+ statusCode: 200
+ )
+ let planner = makePlanner(httpClient: httpClient, understanding: nil)
+
+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))
+
+ #expect(call?.name == "ax.observe")
+ #expect(planner.lastThinking == "The window state is unknown, so I observe before acting.")
+ let body = requestBodyString(httpClient, index: 0)
+ #expect(body.contains("thinking_level"))
+ #expect(!body.contains("thinking_budget"))
+ }
+
+ @Test
+ func retriesOnceWhenChosenToolMissesAllRequiredInput() async {
+ // The exact loop the user hit: the model chose shell_exec with NO command (its required input),
+ // which only yields invalidInput and, repeated, fails the run. The planner must retry once with
+ // a corrective note, then use the corrected call.
+ let httpClient = SequencedHTTPClient(responses: [
+ (Data(#"{"output_text":"{\"tool\":\"shell_exec\",\"reason\":\"verify\"}"}"#.utf8), 200),
+ (Data(#"{"output_text":"{\"tool\":\"shell_exec\",\"input\":{\"command\":\"date\"},\"reason\":\"verify\"}"}"#.utf8), 200)
+ ])
+ let planner = HostedHarnessStepPlanner(
+ backend: DonkeyBackendInferenceClient(
+ configuration: DonkeyBackendInferenceConfiguration(
+ baseURL: URL(string: "https://donkey.example")!,
+ clientID: "client-1"
+ ),
+ httpClient: httpClient
+ ),
+ descriptors: [
+ HarnessToolDescriptor(
+ name: "shell_exec",
+ pluginID: "core",
+ summary: "Run a single-line command.",
+ inputSchema: ["command": "The command.", "timeoutSeconds": "Budget."],
+ optionalInputKeys: ["timeoutSeconds"],
+ safetyClass: .guardedInput
+ )
+ ],
+ appName: "Notes",
+ appGuidance: nil,
+ understanding: nil
+ )
+
+ let call = await planner.planNextStep(for: task(goal: "confirm what is playing", toolHistory: []))
+
+ #expect(call?.name == "shell_exec")
+ #expect(call?.input["command"] == "date")
+ #expect(httpClient.requests.count == 2)
+ #expect(requestBodyString(httpClient, index: 1).contains("none of its required input"))
+ }
+
@Test
func promptRendersElementGeometryValueAndEligibility() async {
let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)
@@ -249,6 +316,17 @@ struct HostedHarnessStepPlannerTests {
requestBodyString(requests: httpClient.requests, index: index)
}
+ /// Pulls the numeric `max_output_tokens` out of a captured request body, to assert the per-retry
+ /// boost. Returns 0 when absent so a missing key fails the comparison loudly.
+ private func maxOutputTokens(_ httpClient: SequencedHTTPClient, index: Int) -> Int {
+ let body = requestBodyString(httpClient, index: index)
+ guard let range = body.range(of: #""max_output_tokens"\s*:\s*"#, options: .regularExpression) else {
+ return 0
+ }
+ let digits = body[range.upperBound...].prefix { $0.isNumber }
+ return Int(digits) ?? 0
+ }
+
private func requestBodyString(requests: [URLRequest], index: Int) -> String {
guard requests.indices.contains(index),
let body = requests[index].httpBody,