Open source CapCut alternative.
TypeScript
Centralize model context compaction
David Le4b2bfbb7cca1
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex ba63ced7..1691d3ac 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -261,7 +261,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let modelInput = Self.modelInput(for: command,context: context,- contextPacket: routing.contextPacket+ compactedContext: genericPreparedTurn.compactedContext)let commandRedaction = redactor.redact(modelInput.command, surface: .modelContext)let contextRedactions = modelInput.contextSnippets.map {@@ -964,13 +964,14 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {private static func modelInput(for command: String,context: PointerPromptCommandContext?,- contextPacket: AppHarnessContextPacket+ compactedContext: HarnessCompactedThreadContext) -> PointerPromptModelIntentInput {- let modelCommand = contextPacket.currentTurn.text+ let modelCommand = compactedContext.currentTurn?.text ?? command+ let compactedPrompt = compactedContext.promptTextguard let context, context.isFollowUp else {return PointerPromptModelIntentInput(command: modelCommand,- contextSnippets: []+ contextSnippets: [compactedPrompt].filter { !$0.isEmpty })}@@ -986,8 +987,8 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {command: modelCommand,contextSnippets: [taskContext,- contextPacket.promptText- ]+ compactedPrompt+ ].filter { !$0.isEmpty })}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swiftindex bab28f44..16797c0b 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedPlannerHintAdapter.swift@@ -74,7 +74,7 @@ public struct PlannerHintAdapterRequest: Equatable, Sendable {now: RunTraceTimestamp,routeRequest: AIModelRouteRequest = AIModelRouteRequest(jobType: .plannerHint)) {- self.context = context+ self.context = RunContextAssembler().compact(context)self.sourceTraceID = sourceTraceIDself.sourceFrameID = sourceFrameIDself.sourceStateID = sourceStateIDdiff --git a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftindex c2d74fe1..d7f13f51 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift@@ -24,13 +24,68 @@ public struct TaskIntentAdapterRequest: Equatable, Sendable {) {self.command = commandself.taskDefinitions = taskDefinitions- self.contextSnippets = contextSnippets+ self.contextSnippets = TaskIntentModelContextCompactor.compact(contextSnippets)self.appFinderCatalog = appFinderCatalogself.sourceTraceID = sourceTraceIDself.routeRequest = routeRequest}}+public struct TaskIntentModelContextCompactor: Equatable, Sendable {+ public var maxSnippets: Int+ public var maxSnippetCharacters: Int+ public var maxTotalCharacters: Int++ public init(+ maxSnippets: Int = 8,+ maxSnippetCharacters: Int = 1_200,+ maxTotalCharacters: Int = 4_800+ ) {+ self.maxSnippets = max(0, maxSnippets)+ self.maxSnippetCharacters = max(80, maxSnippetCharacters)+ self.maxTotalCharacters = max(80, maxTotalCharacters)+ }++ public func compact(_ snippets: [String]) -> [String] {+ var usedCharacters = 0+ var compacted: [String] = []++ for snippet in snippets.prefix(maxSnippets) {+ let trimmed = snippet.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { continue }++ let boundedSnippet = bounded(trimmed, maxCharacters: maxSnippetCharacters)+ let remainingCharacters = maxTotalCharacters - usedCharacters+ guard remainingCharacters > 0 else { break }++ let totalBoundedSnippet = bounded(boundedSnippet, maxCharacters: remainingCharacters)+ usedCharacters += totalBoundedSnippet.count+ compacted.append(totalBoundedSnippet)+ }++ return compacted+ }++ public static func compact(_ snippets: [String]) -> [String] {+ TaskIntentModelContextCompactor().compact(snippets)+ }++ private func bounded(_ value: String, maxCharacters: Int) -> String {+ guard value.count > maxCharacters else { return value }+ let marker = "\n...[compacted]...\n"+ guard maxCharacters > marker.count + 2 else {+ return String(value.suffix(maxCharacters))+ }++ let contentCharacters = maxCharacters - marker.count+ let prefixCharacters = contentCharacters / 2+ let suffixCharacters = contentCharacters - prefixCharacters+ let prefixEnd = value.index(value.startIndex, offsetBy: prefixCharacters)+ let suffixStart = value.index(value.endIndex, offsetBy: -suffixCharacters)+ return String(value[..<prefixEnd]) + marker + String(value[suffixStart...])+ }+}+public struct TaskIntentAdapterResult: Equatable, Sendable {public var intent: TaskIntent?public var trace: AIModelCallTracediff --git a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swiftindex ed48edc8..40f0c885 100644--- a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift@@ -3,9 +3,17 @@ import Foundationpublic struct RunContextAssembler: Equatable, Sendable {public var maxTranscriptCharacters: Int+ public var maxSummaryCharacters: Int+ public var maxMemoryRecordCharacters: Int- public init(maxTranscriptCharacters: Int = 2_000) {+ public init(+ maxTranscriptCharacters: Int = 2_000,+ maxSummaryCharacters: Int = 600,+ maxMemoryRecordCharacters: Int = 600+ ) {self.maxTranscriptCharacters = max(0, maxTranscriptCharacters)+ self.maxSummaryCharacters = max(80, maxSummaryCharacters)+ self.maxMemoryRecordCharacters = max(80, maxMemoryRecordCharacters)}public func build(@@ -17,30 +25,72 @@ public struct RunContextAssembler: Equatable, Sendable {memorySnapshot: RunMemorySnapshot? = nil,semanticMemoryResults: [RunMemorySemanticResult] = []) -> RunContextPackage {- let boundedTranscript = bounded(transcriptSummary)+ let boundedTranscript = suffixBounded(transcriptSummary, maxCharacters: maxTranscriptCharacters)let validHints = activeHints.filter(\.isValid)- return RunContextPackage(- sessionID: session.id,- userGoal: session.userGoal,- targetID: session.targetID,- runtimeProfile: session.runtimeProfile,- latestWorldState: latestWorldState,- transcriptSummary: boundedTranscript.text,- droppedTranscriptCharacterCount: boundedTranscript.droppedCount,- activeHints: validHints,- recentFailures: recentFailures,- memorySnapshot: boundedMemorySnapshot(memorySnapshot, fallbackHints: validHints, fallbackFailures: recentFailures),- semanticMemoryResults: boundedSemanticMemoryResults(semanticMemoryResults)+ return compact(+ RunContextPackage(+ sessionID: session.id,+ userGoal: session.userGoal,+ targetID: session.targetID,+ runtimeProfile: session.runtimeProfile,+ latestWorldState: latestWorldState,+ transcriptSummary: boundedTranscript.text,+ droppedTranscriptCharacterCount: boundedTranscript.droppedCount,+ activeHints: validHints,+ recentFailures: recentFailures,+ memorySnapshot: boundedMemorySnapshot(+ memorySnapshot,+ fallbackHints: validHints,+ fallbackFailures: recentFailures+ ),+ semanticMemoryResults: boundedSemanticMemoryResults(semanticMemoryResults)+ ))}- private func bounded(_ text: String) -> (text: String, droppedCount: Int) {- guard text.count > maxTranscriptCharacters else {+ public func compact(_ context: RunContextPackage) -> RunContextPackage {+ var context = context+ context.latestWorldState = context.latestWorldState.map(boundedWorldState)+ context.activeHints = context.activeHints.map(boundedHint)+ context.recentFailures = context.recentFailures.map(boundedFailure)+ context.memorySnapshot = context.memorySnapshot.map { snapshot in+ boundedMemorySnapshot(+ snapshot,+ fallbackHints: context.activeHints,+ fallbackFailures: context.recentFailures+ ) ?? snapshot+ }+ context.semanticMemoryResults = boundedSemanticMemoryResults(context.semanticMemoryResults)+ return context+ }++ private func bounded(_ text: String, maxCharacters: Int) -> (text: String, droppedCount: Int) {+ guard text.count > maxCharacters else {return (text, 0)}- let suffix = String(text.suffix(maxTranscriptCharacters))+ let marker = "\n...[compacted]...\n"+ guard maxCharacters > marker.count + 2 else {+ let suffix = String(text.suffix(maxCharacters))+ return (suffix, text.count - suffix.count)+ }++ let contentCharacters = maxCharacters - marker.count+ let prefixCharacters = contentCharacters / 2+ let suffixCharacters = contentCharacters - prefixCharacters+ let prefixEnd = text.index(text.startIndex, offsetBy: prefixCharacters)+ let suffixStart = text.index(text.endIndex, offsetBy: -suffixCharacters)+ let compacted = String(text[..<prefixEnd]) + marker + String(text[suffixStart...])+ return (compacted, text.count - compacted.count)+ }++ private func suffixBounded(_ text: String, maxCharacters: Int) -> (text: String, droppedCount: Int) {+ guard text.count > maxCharacters else {+ return (text, 0)+ }++ let suffix = String(text.suffix(maxCharacters))return (suffix, text.count - suffix.count)}@@ -60,10 +110,15 @@ public struct RunContextAssembler: Equatable, Sendable {}snapshot.recentStates = Array(snapshot.recentStates.suffix(5))+ .map(boundedWorldState)snapshot.recentFailures = Array(snapshot.recentFailures.suffix(5))+ .map(boundedFailure)snapshot.userInstructions = Array(snapshot.userInstructions.suffix(5))+ .map(boundedMemoryRecord)snapshot.safetyStops = Array(snapshot.safetyStops.suffix(5))+ .map(boundedMemoryRecord)snapshot.targetRecords = Array(snapshot.targetRecords.suffix(10))+ .map(boundedMemoryRecord)return snapshot}@@ -81,4 +136,39 @@ public struct RunContextAssembler: Equatable, Sendable {}return bounded}++ private func boundedWorldState(_ state: RunWorldStateSummary) -> RunWorldStateSummary {+ let boundedSummary = bounded(state.summary, maxCharacters: maxSummaryCharacters)+ return RunWorldStateSummary(+ stateID: state.stateID,+ summary: boundedSummary.text,+ confidence: state.confidence+ )+ }++ private func boundedHint(_ hint: RunPlannerHint) -> RunPlannerHint {+ RunPlannerHint(+ id: hint.id,+ summary: bounded(hint.summary, maxCharacters: maxSummaryCharacters).text,+ isValid: hint.isValid+ )+ }++ private func boundedFailure(_ failure: RunFailureSummary) -> RunFailureSummary {+ RunFailureSummary(+ traceID: failure.traceID,+ summary: bounded(failure.summary, maxCharacters: maxSummaryCharacters).text+ )+ }++ private func boundedMemoryRecord(_ record: AgentMemoryRecord) -> AgentMemoryRecord {+ let boundedValue = bounded(record.value, maxCharacters: maxMemoryRecordCharacters)+ guard boundedValue.droppedCount > 0 else { return record }++ var record = record+ record.value = boundedValue.text+ record.metadata["compaction.truncated"] = "true"+ record.metadata["compaction.droppedCharacters"] = String(boundedValue.droppedCount)+ return record+ }}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex 89ea9488..acc54f3c 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -986,6 +986,26 @@ struct AIHarnessAdapterTests {#expect(request?.appFinderCatalog.first?.appID == "com.apple.Music")}+ @Test+ func taskIntentRequestsCompactContextSnippetsBeforeModelCalls() {+ let snippets = (0..<12).map { index in+ "snippet-\(index) " + String(repeating: "\(index)", count: 2_000)+ }++ let request = TaskIntentAdapterRequest(+ command: "continue",+ taskDefinitions: [],+ contextSnippets: snippets,+ sourceTraceID: "trace-compact-intent"+ )++ #expect(request.contextSnippets.count == 4)+ #expect(request.contextSnippets.allSatisfy { $0.count <= 1_200 })+ #expect(request.contextSnippets.joined().count <= 4_800)+ #expect(request.contextSnippets.first?.contains("snippet-0") == true)+ #expect(request.contextSnippets.first?.contains("[compacted]") == true)+ }+@Testfunc processBackedLocalLLMTaskIntentAdapterDecodesWrappedStructuredOutput() async throws {let adapter = ProcessBackedLocalLLMTaskIntentAdapter(@@ -1963,6 +1983,43 @@ struct AIHarnessAdapterTests {#expect(planner.providerOrder == [.donkeyBackend])}+ @Test+ func plannerHintRequestsCompactMemoryBeforeProviderCalls() {+ let longMemory = "important prefix " + String(repeating: "planner-memory ", count: 100)+ let request = PlannerHintAdapterRequest(+ context: RunContextPackage(+ sessionID: "session-compact-planner",+ userGoal: "recover",+ targetID: "target-1",+ runtimeProfile: "dry-run",+ latestWorldState: RunWorldStateSummary(+ stateID: "state-long",+ summary: String(repeating: "state ", count: 200),+ confidence: 0.4+ ),+ transcriptSummary: "",+ memorySnapshot: RunMemorySnapshot(+ targetRecords: [+ memoryRecord(+ id: "memory-long",+ value: longMemory,+ targetID: "target-1"+ )+ ]+ )+ ),+ sourceTraceID: "trace-compact-planner",+ sourceStateID: "state-long",+ now: timestamp(10)+ )++ let record = request.context.memorySnapshot?.targetRecords.first+ #expect(request.context.latestWorldState?.summary.count == 600)+ #expect(record?.value.count == 600)+ #expect(record?.value.contains("important prefix") == true)+ #expect(record?.metadata["compaction.truncated"] == "true")+ }+@Testfunc semanticMemoryRetrievalUsesBudgetsAndTargetScope() async {let records = [diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex e5278285..81d3bb9d 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -78,17 +78,23 @@ execution state.## Smart Compaction-The harness should never send raw unbounded history to a model. Before a model-call or planner step, the thread compactor builds a bounded context packet. It-keeps the current turn, active and waiting task state, pending questions or-permissions, pinned events, durable summaries, the most recent useful events,-recent tool summaries, and a bounded asset list.+The harness never sends raw unbounded history to a model. Before model-backed+intent routing, generic planning, or slow-planner hint generation, compaction+builds a bounded context packet. It keeps the current turn, active and waiting+task state, pending questions or permissions, pinned events, durable summaries,+the most recent useful events, recent tool summaries, memory summaries, and a+bounded asset list.Large event bodies are truncated. Raw screenshots, full Accessibility trees,script source, and long tool outputs should be saved as artifacts or structuredrecords and summarized into the prompt. Compaction metadata records what wasincluded, dropped, or truncated so the decision remains inspectable.+Pointer-prompt hosted intent calls consume the generic compacted thread context+rather than ad hoc thread snippets. Slow planner calls consume a compacted run+context, including bounded world-state, failure, hint, memory, and semantic+memory summaries.+## Turn FlowThe desired loop is:diff --git a/plans/master-plan.md b/plans/master-plan.mdindex bfe13eab..1d8956da 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,21 +21,17 @@ even when there are no active tasks.## Current Sequence-1. Make smart compaction central for every model and planner call. Preserve the- current turn, active task state, pending gates, summaries, recent useful- events, assets, and tool traces while storing bulky screenshots, full- Accessibility trees, script source, and long outputs as artifacts.-2. Move app-specific behavior into skills. Music, Notes, Numbers, browser+1. Move app-specific behavior into skills. Music, Notes, Numbers, browserworkflows, app knowledge, and future app-specific behavior should live inskill packs, plugin/catalog data, generated artifacts, or memory instead ofcore Swift prompt branches.-3. Build the application-learning task. It should safely explore an app, capture+2. Build the application-learning task. It should safely explore an app, capturescreenshots and Accessibility trees, distill surfaces/workflows, generatescripts where useful, validate them, and save a reusable skill pack.-4. Wire interruption and permission gates into the UI. The notch/task UI should+3. Wire interruption and permission gates into the UI. The notch/task UI shouldcontrol generic harness tasks and show the exact pending approval orchanged-course state.-5. Delete old app-specific paths once the generic path covers them. Remove+4. Delete old app-specific paths once the generic path covers them. Removehardcoded Music/Notes/Numbers/media/weather-style prompt rules, catalogspecial cases, repair logic, and demo-only workflow branches.