Open source CapCut alternative.
TypeScript
feat(app): understand follow-up turns against the conversation's rolling context
David Lee3d40cfe83d1
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 23088ee8..9bb8f538 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -561,11 +561,29 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// A fresh turn — no assistant reply yet in this conversation — lets a `.converse` reply stream// straight out of the understanding boundary in ONE round trip: the same call that types the turn- // also generates the reply, and the field extractor streams it to the chin live. A follow-up may- // lean on earlier context the understanding boundary never sees, so it uses the non-streaming- // understanding and routes any converse reply through the context-aware responder below.+ // also generates the reply, and the field extractor streams it to the chin live. A follow-up uses+ // the non-streaming understanding and routes any converse reply through the responder below.let priorEvents = await genericHarnessLifecycle.conversationStore.events(conversationID: conversationID)let isFreshTurn = !priorEvents.contains { $0.role == .assistant }+ // Any turn with history ("retry", "make it shorter", "now send it") only means anything against+ // the turns it continues, so the understanding boundary gets the same bounded rolling context the+ // planner and converse responder carry. Without it, "retry" after a failed video generation was+ // typed as a fresh GUI task on whatever app happened to be frontmost. Keyed on prior events of ANY+ // role — not `isFreshTurn`'s assistant check — so a turn after a crash or mid-run follow-up that+ // never produced an assistant reply still carries the user's own earlier messages.+ let conversationContext: String?+ if priorEvents.isEmpty {+ conversationContext = nil+ } else {+ let textGenerator = HostedTextGenerator(backend: backend)+ let compactionDriver = ConversationCompactionDriver(+ conversationStore: genericHarnessLifecycle.conversationStore,+ coordinator: genericHarnessLifecycle.coordinator,+ compactor: genericHarnessLifecycle.compactor,+ generate: { await textGenerator.generate($0) }+ )+ conversationContext = await compactionDriver.rollingContext(agentID: agentID)+ }// A pure continuation of the same turn (gate approval, auto-resume) arrives with the understanding// the first run produced and skips the boundary entirely — no second round-trip, and the goal,// parameters, and chosen skills stay exactly what the turn started with. Only a fresh or follow-up@@ -582,6 +600,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {frontmostAppName: frontmostAppName,skillCatalog: skillSelectionCatalog,attachments: attachmentInfos,+ conversationContext: conversationContext,onReplyDelta: answerStream ?? { _ in })}@@ -589,7 +608,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {command: command,frontmostAppName: frontmostAppName,skillCatalog: skillSelectionCatalog,- attachments: attachmentInfos+ attachments: attachmentInfos,+ conversationContext: conversationContext)}// Persist the freshly computed understanding on the root agent so a later resume of THIS turn@@ -621,6 +641,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {preparedTurnMetadata: preparedTurnMetadata,inlineReply: understanding?.conversationReply,inlineReplyAlreadyStreamed: isFreshTurn,+ conversationContext: conversationContext,answerStream: answerStream)}@@ -1392,6 +1413,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {preparedTurnMetadata: [String: String],inlineReply: String?,inlineReplyAlreadyStreamed: Bool,+ conversationContext: String?,answerStream: (@MainActor @Sendable (String) -> Void)?) async -> UserQueryCommandHandlingResult {transcript.systemEvent("Conversational turn — responding without driving the Mac.")@@ -1399,22 +1421,12 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// On a fresh turn the understanding boundary already generated AND streamed this reply live (one// round trip), so adopt it as-is — re-emitting would double it on screen. A follow-up turn falls to- // the context-aware responder, which streams a reply that can see the earlier conversation.+ // the context-aware responder, which streams a reply against the rolling conversation context the+ // caller already built for the understanding boundary.let reply: Stringif let inlineReply, !inlineReply.isEmpty, inlineReplyAlreadyStreamed {reply = inlineReply} else {- // 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,diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex 18863ca5..7d0194bb 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -89,8 +89,17 @@ public enum DonkeyPrompts {command: String,frontmostAppName: String,skillCatalog: String? = nil,- attachments: [HarnessAttachmentInfo] = []+ attachments: [HarnessAttachmentInfo] = [],+ conversationContext: String?) -> String {+ let trimmedContext = conversationContext?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ let conversationBlock = trimmedContext.isEmpty+ ? ""+ : "\nCONVERSATION SO FAR (most recent last) — this request continues it. Resolve every "+ + "reference (\"it\", \"that\", \"retry\", \"again\", \"the file\") against this history. "+ + "\"Retry\"/\"try again\" means re-run the previous turn's goal with the same target, "+ + "surface, and skills — restate that goal concretely, never as a new task in whatever "+ + "app is in front:\n\(trimmedContext)\n"let trimmedCatalog = skillCatalog?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""let skillsBlock = trimmedCatalog.isEmpty? ""@@ -108,7 +117,7 @@ public enum DonkeyPrompts {does that. Be broad in what you accept and specific in what you capture.The app currently in front of the user is "\(frontmostAppName)".-+ \(conversationBlock)USER REQUEST: \(command)\(attachmentsBlock)\(skillsBlock)Fill the fields:diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swiftindex 2b3851c1..29cefc7b 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift@@ -132,11 +132,15 @@ public final class HostedHarnessRequestUnderstanding {/// raw-command fallback (observed: the same prompt returning nil on one run and a clean classification/// on the next). A signed-out session or spent balance is terminal — retrying re-issues the same doomed/// call — so those stop immediately.+ /// `conversationContext` is deliberately non-defaulted: every caller must state the turn's history+ /// (nil only for a genuinely history-less turn), so a new call site can't silently run context-blind+ /// — the failure mode that once typed "retry" as a fresh task on the frontmost app.public func understand(command: String,frontmostAppName: String,skillCatalog: String? = nil,- attachments: [HarnessAttachmentInfo] = []+ attachments: [HarnessAttachmentInfo] = [],+ conversationContext: String?) async -> HarnessRequestUnderstanding? {var augmentedCatalog = skillCatalog ?? ""if let finderGuidance = BuiltInLocalAppSkillPacks.skillGuidance(forID: "finder") {@@ -147,7 +151,8 @@ public final class HostedHarnessRequestUnderstanding {command: command,frontmostAppName: frontmostAppName,skillCatalog: augmentedCatalog.isEmpty ? nil : augmentedCatalog,- attachments: attachments+ attachments: attachments,+ conversationContext: conversationContext)for _ in 0..<Self.maxAttempts {let startedAt = RunTraceTimestamp.now()@@ -157,7 +162,8 @@ public final class HostedHarnessRequestUnderstanding {command: command,frontmostAppName: frontmostAppName,skillCatalog: augmentedCatalog.isEmpty ? nil : augmentedCatalog,- attachments: attachments+ attachments: attachments,+ conversationContext: conversationContext))let endedAt = RunTraceTimestamp.now()@@ -208,6 +214,7 @@ public final class HostedHarnessRequestUnderstanding {frontmostAppName: String,skillCatalog: String? = nil,attachments: [HarnessAttachmentInfo] = [],+ conversationContext: String?,onReplyDelta: @escaping @MainActor @Sendable (String) -> Void) async -> HarnessRequestUnderstanding? {var augmentedCatalog = skillCatalog ?? ""@@ -219,7 +226,8 @@ public final class HostedHarnessRequestUnderstanding {command: command,frontmostAppName: frontmostAppName,skillCatalog: augmentedCatalog.isEmpty ? nil : augmentedCatalog,- attachments: attachments+ attachments: attachments,+ conversationContext: conversationContext)let startedAt = RunTraceTimestamp.now()let streamer = ReplyFieldStreamer()@@ -383,7 +391,8 @@ public final class HostedHarnessRequestUnderstanding {command: String,frontmostAppName: String,skillCatalog: String?,- attachments: [HarnessAttachmentInfo] = []+ attachments: [HarnessAttachmentInfo],+ conversationContext: String?) -> RemoteInferenceResponseCreateRequest {RemoteInferenceResponseCreateRequest(input: .array([@@ -396,7 +405,8 @@ public final class HostedHarnessRequestUnderstanding {command: command,frontmostAppName: frontmostAppName,skillCatalog: skillCatalog,- attachments: attachments+ attachments: attachments,+ conversationContext: conversationContext))])])diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swiftindex 496293b7..76012949 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift@@ -21,16 +21,11 @@ public struct HarnessStepExecutionResult: Equatable, Sendable {/// updated by the previous tool's result, and returns the next call (or nil to stop). It expresses/// completion by returning a `run.complete` lifecycle call, which ends the loop.public protocol HarnessNextStepPlanning: Sendable {+ /// `rollingContext` is non-defaulted on purpose: every caller states the conversation history it+ /// plans against (nil only when there genuinely is none), so no call site can run context-blind.func planNextStep(for task: HarnessAgentState, rollingContext: String?) async -> HarnessToolCall?}-public extension HarnessNextStepPlanning {- /// Convenience for callers without rolling conversation context (e.g. tests).- func planNextStep(for task: HarnessAgentState) async -> HarnessToolCall? {- await planNextStep(for: task, rollingContext: nil)- }-}-/// Produces the bounded rolling context — recent conversation events plus a rolling summary of older/// turns — that a step's planner prompt carries, so a long conversation stays coherent without resending/// its whole history. When the rolling context grows past the policy threshold the implementation writes@@ -77,7 +72,7 @@ public struct GenericHarnessRuntime: Sendable {maxNoProgressSteps: Int = 6,maxIdenticalRepeats: Int = 3,maxRepeatedFailures: Int = 3,- compactor: (any HarnessConversationCompacting)? = nil,+ compactor: (any HarnessConversationCompacting)?,onStep: (@Sendable (HarnessStepExecutionResult) async -> Void)? = nil) async -> [HarnessStepExecutionResult] {var results: [HarnessStepExecutionResult] = []diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swiftindex 5ff075e8..4dac61a9 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ConversationFollowUpInjectionTests.swift@@ -155,7 +155,7 @@ struct ConversationFollowUpInjectionTests {)let planner = InjectingPlanner(coordinator: coordinator, agentID: task.id, injectText: "also empty the trash")- let steps = await runtime.run(agentID: task.id, planner: planner, maxSteps: 10)+ let steps = await runtime.run(agentID: task.id, planner: planner, maxSteps: 10, compactor: nil)// The queued instruction is delivered at the next loop iteration, so the run completes rather than// stalling, and the original goal is untouched (the follow-up amended the work in place).@@ -175,8 +175,8 @@ struct ConversationFollowUpInjectionTests {let taskB = await coordinator.createAgent(id: "task-b", conversationID: "thread-b", goal: "goal B", grantedPermissions: [.lifecycle])let planner = ObserveThenCompletePlanner()- async let runA = runtime.run(agentID: taskA.id, planner: planner, maxSteps: 5)- async let runB = runtime.run(agentID: taskB.id, planner: planner, maxSteps: 5)+ async let runA = runtime.run(agentID: taskA.id, planner: planner, maxSteps: 5, compactor: nil)+ async let runB = runtime.run(agentID: taskB.id, planner: planner, maxSteps: 5, compactor: nil)_ = await (runA, runB)let finalA = await coordinator.agent(id: taskA.id)@@ -215,7 +215,7 @@ struct ConversationFollowUpInjectionTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-timeout", conversationID: "t", goal: "go forever", grantedPermissions: [.lifecycle])- _ = await runtime.run(agentID: task.id, planner: AlwaysProgressPlanner(), maxSteps: 3)+ _ = await runtime.run(agentID: task.id, planner: AlwaysProgressPlanner(), maxSteps: 3, compactor: nil)let finalTask = await coordinator.agent(id: task.id)#expect(finalTask?.status == .timedOut)@@ -231,7 +231,7 @@ struct ConversationFollowUpInjectionTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-giveup", conversationID: "t", goal: "g", grantedPermissions: [.lifecycle])- _ = await runtime.run(agentID: task.id, planner: GivesUpPlanner(), maxSteps: 5)+ _ = await runtime.run(agentID: task.id, planner: GivesUpPlanner(), maxSteps: 5, compactor: nil)let finalTask = await coordinator.agent(id: task.id)#expect(finalTask?.status == .failedSafe)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swiftindex e3b46f23..9563c95f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalRunner.swift@@ -99,7 +99,7 @@ enum FunctionalEvalRunner {// Real one-shot understanding, fed the production skill catalog so it surfaces the right skill.let skillCatalog = BuiltInLocalAppSkillPacks.skillSelectionCatalog()let understanding = await HostedHarnessRequestUnderstanding(backend: backend)- .understand(command: prompt, frontmostAppName: frontmostApp, skillCatalog: skillCatalog)+ .understand(command: prompt, frontmostAppName: frontmostApp, skillCatalog: skillCatalog, conversationContext: nil)let preloadedSkillGuides: [String] = (understanding?.relevantSkillIDs ?? []).prefix(2).compactMap { BuiltInLocalAppSkillPacks.skillGuidance(forID: $0) }@@ -157,7 +157,7 @@ enum FunctionalEvalRunner {)let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)- _ = await runtime.run(agentID: agent.id, planner: planner, maxSteps: maxSteps)+ _ = await runtime.run(agentID: agent.id, planner: planner, maxSteps: maxSteps, compactor: nil)let final = await coordinator.agent(id: agent.id)return FunctionalEvalRun(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 712485f1..ef952c8b 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -204,7 +204,7 @@ struct GenericHarnessTests {grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubReplanningPlanner(), maxSteps: 5)+ let steps = await runtime.run(agentID: task.id, planner: StubReplanningPlanner(), maxSteps: 5, compactor: nil)#expect(steps.map { $0.toolResult?.toolName } == ["test.observe", "run.complete"])let finalTask = await coordinator.agent(id: task.id)@@ -233,7 +233,7 @@ struct GenericHarnessTests {grantedPermissions: [.conversation, .lifecycle])- let steps = await runtime.run(agentID: task.id, planner: AlwaysRespondsPlanner(), maxSteps: 5)+ let steps = await runtime.run(agentID: task.id, planner: AlwaysRespondsPlanner(), maxSteps: 5, compactor: nil)#expect(steps.map { $0.toolResult?.toolName } == ["conversation.respond"])let finalTask = await coordinator.agent(id: task.id)@@ -523,7 +523,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-loop", conversationID: "t", goal: "loop", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubLoopingPlanner(), maxSteps: 100)+ let steps = await runtime.run(agentID: task.id, planner: StubLoopingPlanner(), maxSteps: 100, compactor: nil)// Stops after the repeat guard trips (well under the ceiling), not 100 steps.#expect(steps.count < 5)@@ -546,7 +546,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-dup", conversationID: "t", goal: "dup", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubDuplicatePlanner(), maxSteps: 30)+ let steps = await runtime.run(agentID: task.id, planner: StubDuplicatePlanner(), maxSteps: 30, compactor: nil)// The action executes exactly once; everything after is a blocked duplicate, so no 16 copies.let realRuns = steps.filter { $0.toolResult?.toolName == "test.act" && $0.toolResult?.status == .succeeded }@@ -576,7 +576,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-probe", conversationID: "t", goal: "probe", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubRepeatPlanner(), maxSteps: 30)+ let steps = await runtime.run(agentID: task.id, planner: StubRepeatPlanner(), maxSteps: 30, compactor: nil)let blocked = steps.first { $0.toolResult?.metadata["reason"] == "duplicateAction" }#expect(blocked != nil)@@ -619,7 +619,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-hammer", conversationID: "t", goal: "hammer", grantedPermissions: [.lifecycle])- _ = await runtime.run(agentID: task.id, planner: StubActThenHammerPlanner(), maxSteps: 30)+ _ = await runtime.run(agentID: task.id, planner: StubActThenHammerPlanner(), maxSteps: 30, compactor: nil)// Real work happened and a read followed it (the weak evidence gate would pass), yet a run that// ends by hammering one call is stuck, not done.@@ -647,7 +647,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-stall", conversationID: "t", goal: "stall", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubBusyPlanner(), maxSteps: 100, maxNoProgressSteps: 4)+ let steps = await runtime.run(agentID: task.id, planner: StubBusyPlanner(), maxSteps: 100, maxNoProgressSteps: 4, compactor: nil)#expect(steps.count <= 5)let finalTask = await coordinator.agent(id: task.id)@@ -836,7 +836,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-refail", conversationID: "t", goal: "refail", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubAlternatingPlanner(), maxSteps: 100)+ let steps = await runtime.run(agentID: task.id, planner: StubAlternatingPlanner(), maxSteps: 100, compactor: nil)// Three identical failures with successful observes between them — stops at the third// failure (5 steps), far below what the no-progress streak alone would allow.@@ -910,7 +910,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-reread", conversationID: "t", goal: "reread", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubRereadingPlanner(), maxSteps: 100)+ let steps = await runtime.run(agentID: task.id, planner: StubRereadingPlanner(), maxSteps: 100, compactor: nil)// The first read adds the fact (real progress); repeats teach nothing and trip the// identical-call guard instead of looping.@@ -948,7 +948,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-malformed", conversationID: "t", goal: "malformed", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubMalformedPlanner(), maxSteps: 100)+ let steps = await runtime.run(agentID: task.id, planner: StubMalformedPlanner(), maxSteps: 100, compactor: nil)#expect(steps.count == 3)let finalTask = await coordinator.agent(id: task.id)@@ -984,7 +984,7 @@ struct GenericHarnessTests {let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)let task = await coordinator.createAgent(id: "task-long", conversationID: "t", goal: "count to 60", grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubProgressingPlanner())+ let steps = await runtime.run(agentID: task.id, planner: StubProgressingPlanner(), compactor: nil)// 60 advances + 1 complete — well past the old 40 cap.#expect(steps.count == 61)@@ -1023,7 +1023,7 @@ struct GenericHarnessTests {grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubActThenCompletePlanner(), maxSteps: 6)+ let steps = await runtime.run(agentID: task.id, planner: StubActThenCompletePlanner(), maxSteps: 6, compactor: nil)#expect(steps.map { $0.toolResult?.toolName } == ["test.act", "run.complete", "test.observe", "run.complete"])#expect(steps[1].toolResult?.status == .failed)@@ -1062,7 +1062,7 @@ struct GenericHarnessTests {grantedPermissions: [.lifecycle])- let steps = await runtime.run(agentID: task.id, planner: StubActThenCompletePlanner(), maxSteps: 4)+ let steps = await runtime.run(agentID: task.id, planner: StubActThenCompletePlanner(), maxSteps: 4, compactor: nil)#expect(steps.map { $0.toolResult?.toolName } == ["test.evidence-act", "run.complete"])let finalTask = await coordinator.agent(id: task.id)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swiftindex e6b3a14a..a2ce2308 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/GreetingRoundTripEvalTests.swift@@ -45,6 +45,7 @@ struct GreetingRoundTripEvalTests {command: "Hi",frontmostAppName: "Finder",skillCatalog: BuiltInLocalAppSkillPacks.skillSelectionCatalog(),+ conversationContext: nil,onReplyDelta: { delta in streamed.append(delta) })diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swiftindex 529ddfa2..4affc552 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessPromptEval/HarnessPromptEvalRunner.swift@@ -180,7 +180,8 @@ enum HarnessEvalRunner {.understand(command: scenario.prompt,frontmostAppName: scenario.frontmostApp,- skillCatalog: skillCatalog+ skillCatalog: skillCatalog,+ conversationContext: nil)// Preload the guides for the skills the understanding picked — mirrors production so the eval tests@@ -242,7 +243,7 @@ enum HarnessEvalRunner {)let runtime = GenericHarnessRuntime(coordinator: coordinator, registry: registry)- _ = await runtime.run(agentID: agent.id, planner: planner, maxSteps: scenario.maxSteps)+ _ = await runtime.run(agentID: agent.id, planner: planner, maxSteps: scenario.maxSteps, compactor: nil)let final = await coordinator.agent(id: agent.id)return HarnessEvalRun(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swiftindex 11e6d2f8..68c37044 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift@@ -21,7 +21,7 @@ struct HostedHarnessRequestUnderstandingTests {httpClient: SingleResponseHTTPClient(data: envelope, statusCode: 200))return await HostedHarnessRequestUnderstanding(backend: backend)- .understand(command: "hi", frontmostAppName: "Finder")+ .understand(command: "hi", frontmostAppName: "Finder", conversationContext: nil)}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftindex 215b1058..78168460 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -21,7 +21,7 @@ struct HostedHarnessStepPlannerTests {))- let call = await planner.planNextStep(for: task(goal: "delete it", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "delete it", toolHistory: []), rollingContext: nil)#expect(call?.name == "user.clarify")#expect(call?.input["question"] == "Which file should I delete?")@@ -44,7 +44,7 @@ struct HostedHarnessStepPlannerTests {resultStatus: .succeeded,summary: "Observed the window.")- let call = await planner.planNextStep(for: task(goal: "delete it", toolHistory: [priorStep]))+ let call = await planner.planNextStep(for: task(goal: "delete it", toolHistory: [priorStep]), rollingContext: nil)#expect(call?.name == "ax.observe")}@@ -62,7 +62,7 @@ struct HostedHarnessStepPlannerTests {))- let call = await planner.planNextStep(for: task(goal: "raw untouched command", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "raw untouched command", toolHistory: []), rollingContext: nil)#expect(call?.name == "ax.observe")let body = requestBodyString(httpClient)@@ -80,7 +80,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)let planner = makePlanner(httpClient: httpClient, understanding: nil)- _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)let body = requestBodyString(httpClient)#expect(body.contains("open settings"))@@ -95,7 +95,7 @@ struct HostedHarnessStepPlannerTests {])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "ax.observe")#expect(httpClient.requests.count == 2)@@ -116,7 +116,7 @@ struct HostedHarnessStepPlannerTests {])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(httpClient.requests.count == 3)@@ -138,7 +138,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = SequencedHTTPClient(responses: [(blocked, 200), (blocked, 200), (blocked, 200)])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "note the album tracklist", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "note the album tracklist", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "plannerContentFiltered(RECITATION)")@@ -160,7 +160,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = SequencedHTTPClient(responses: [(empty, 200), (empty, 200), (empty, 200)])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "plannerEmptyReply")@@ -176,7 +176,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = SequencedHTTPClient(responses: [unauthorized, unauthorized, unauthorized])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "sessionSignedOut")@@ -194,7 +194,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = SequencedHTTPClient(responses: [outOfCredits, outOfCredits, outOfCredits])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "insufficientCredits")@@ -216,7 +216,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = SequencedHTTPClient(responses: [serverError, serverError, serverError])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "harnessPlanFailed")@@ -238,7 +238,7 @@ struct HostedHarnessStepPlannerTests {])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "plannerReturnedNoTool")@@ -252,7 +252,7 @@ struct HostedHarnessStepPlannerTests {])let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "ax.observe")let retryBody = requestBodyString(httpClient, index: 1)@@ -270,7 +270,7 @@ struct HostedHarnessStepPlannerTests {)let planner = makePlanner(httpClient: httpClient, understanding: nil)- let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)#expect(call?.name == "ax.observe")#expect(planner.lastThinking == "The window state is unknown, so I observe before acting.")@@ -299,7 +299,7 @@ struct HostedHarnessStepPlannerTests {))- _ = await planner.planNextStep(for: task(goal: "create a subtitled clip", toolHistory: []))+ _ = await planner.planNextStep(for: task(goal: "create a subtitled clip", toolHistory: []), rollingContext: nil)let narration = LocalAppUserQueryCommandHandler.stepNarration(for: step, planner: planner)#expect(narration == longNarration)@@ -338,10 +338,10 @@ struct HostedHarnessStepPlannerTests {understanding: nil)- _ = await planner.planNextStep(for: task(goal: "fill the form", toolHistory: []))+ _ = await planner.planNextStep(for: task(goal: "fill the form", toolHistory: []), rollingContext: nil)#expect(planner.lastNarration == "Loading the PDF skill.")- _ = await planner.planNextStep(for: task(goal: "fill the form", toolHistory: []))+ _ = await planner.planNextStep(for: task(goal: "fill the form", toolHistory: []), rollingContext: nil)// Not the prior step's line, and derived from this step's own command.#expect(planner.lastNarration != "Loading the PDF skill.")#expect(planner.lastNarration == "Running `ls -la`.")@@ -379,7 +379,7 @@ struct HostedHarnessStepPlannerTests {understanding: nil)- let call = await planner.planNextStep(for: task(goal: "confirm what is playing", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "confirm what is playing", toolHistory: []), rollingContext: nil)#expect(call?.name == "shell_exec")#expect(call?.input["command"] == "date")@@ -419,7 +419,7 @@ struct HostedHarnessStepPlannerTests {understanding: nil)- let call = await planner.planNextStep(for: task(goal: "confirm what is playing", toolHistory: []))+ let call = await planner.planNextStep(for: task(goal: "confirm what is playing", toolHistory: []), rollingContext: nil)#expect(call?.name == "run.failSafe")#expect(call?.input["reason"] == "plannerOmittedRequiredInput(shell_exec)")@@ -438,7 +438,7 @@ struct HostedHarnessStepPlannerTests {let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)let planner = makePlanner(httpClient: httpClient, understanding: nil)- _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))+ _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []), rollingContext: nil)let body = try #require(try JSONSerialization.jsonObject(with: Data(requestBodyString(httpClient, index: 0).utf8)) as? [String: Any]@@ -468,7 +468,7 @@ struct HostedHarnessStepPlannerTests {HarnessWorldElement(id: "lbl1", label: "Banner", role: "staticText", isActionEligible: false)]- _ = await planner.planNextStep(for: state)+ _ = await planner.planNextStep(for: state, rollingContext: nil)let body = requestBodyString(httpClient, index: 0)#expect(body.contains("@(100,200 80x30)"))@@ -488,7 +488,7 @@ struct HostedHarnessStepPlannerTests {)}- _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: history))+ _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: history), rollingContext: nil)let body = requestBodyString(httpClient, index: 0)// The first three steps fall outside the detailed window but stay visible condensed.@@ -513,7 +513,7 @@ struct HostedHarnessStepPlannerTests {summary: "listed three files")- let call = await planner.planNextStep(for: task(goal: "tidy my downloads", toolHistory: [prior]))+ let call = await planner.planNextStep(for: task(goal: "tidy my downloads", toolHistory: [prior]), rollingContext: nil)#expect(call?.name == "ax.observe")let body = try #require(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swiftindex a7623263..d2ed9a0e 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaylistLiveE2ETests.swift@@ -134,7 +134,7 @@ struct MusicPlaylistLiveE2ETests {successCriteria: "A library playlist named \"\(playlistName)\" exists and lists the 10 songs")- let steps = await runtime.run(agentID: task.id, planner: ScriptedPlaylistPlanner(playlistName: playlistName)) { step in+ let steps = await runtime.run(agentID: task.id, planner: ScriptedPlaylistPlanner(playlistName: playlistName), compactor: nil) { step inguard let result = step.toolResult else { return }transcript.step(number: step.task.toolHistory.count,diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 6016bb60..4a405878 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -142,7 +142,10 @@ on through the general file, image, and document tools.The context sent to the model is always bounded. The harness keeps the currentturn, relevant task state, recent useful evidence, summaries, memory, and-pending questions — never unbounded raw history.+pending questions — never unbounded raw history. A turn that continues a+conversation is understood against that conversation's rolling history, so a+follow-up like "retry" or "make it shorter" resolves to the earlier goal.+Every boundary that reads a turn takes that context as a required input.The app catalog is part of this step. If a requested app or capability is notsupported, the harness surfaces conversation, clarification, or a safe stop. It