Skip to content

Open source CapCut alternative.

TypeScript

Add runtime

David Le0563da8aa91b
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swift
index 515ce144..b0cad930 100644
--- a/apps/Donkey/Package.swift
+++ b/apps/Donkey/Package.swift
@@ -44,6 +44,35 @@ let package = Package(
resources: [
.copy("Resources/theme.json")
]
+ ),
+ .testTarget(
+ name: "DonkeyRuntimeTests",
+ dependencies: [
+ "DonkeyContracts",
+ "DonkeyRuntime"
+ ],
+ swiftSettings: [
+ .unsafeFlags([
+ "-F",
+ "/Library/Developer/CommandLineTools/Library/Developer/Frameworks"
+ ])
+ ],
+ linkerSettings: [
+ .unsafeFlags([
+ "-F",
+ "/Library/Developer/CommandLineTools/Library/Developer/Frameworks",
+ "-L",
+ "/Library/Developer/CommandLineTools/Library/Developer/usr/lib",
+ "-Xlinker",
+ "-rpath",
+ "-Xlinker",
+ "/Library/Developer/CommandLineTools/Library/Developer/Frameworks",
+ "-Xlinker",
+ "-rpath",
+ "-Xlinker",
+ "/Library/Developer/CommandLineTools/Library/Developer/usr/lib"
+ ])
+ ]
)
]
)
diff --git a/apps/Donkey/Sources/DonkeyContracts/PlaceholderSnapshots.swift b/apps/Donkey/Sources/DonkeyContracts/PlaceholderSnapshots.swift
index 8db7424c..b70ca6b1 100644
--- a/apps/Donkey/Sources/DonkeyContracts/PlaceholderSnapshots.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/PlaceholderSnapshots.swift
@@ -4,11 +4,27 @@ public struct RuntimeStatusSnapshot: Equatable, Sendable {
public var isReady: Bool
public var summary: String
public var sourcePlan: String
+ public var lifecycleState: RunLifecycleState
+ public var latestEventSummary: String?
+ public var eventCount: Int
+ public var requiresInputRelease: Bool
- public init(isReady: Bool, summary: String, sourcePlan: String) {
+ public init(
+ isReady: Bool,
+ summary: String,
+ sourcePlan: String,
+ lifecycleState: RunLifecycleState = .idle,
+ latestEventSummary: String? = nil,
+ eventCount: Int = 0,
+ requiresInputRelease: Bool = false
+ ) {
self.isReady = isReady
self.summary = summary
self.sourcePlan = sourcePlan
+ self.lifecycleState = lifecycleState
+ self.latestEventSummary = latestEventSummary
+ self.eventCount = eventCount
+ self.requiresInputRelease = requiresInputRelease
}
}
diff --git a/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
new file mode 100644
index 00000000..79df28a4
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift
@@ -0,0 +1,279 @@
+import Foundation
+
+public enum RunLifecycleState: String, Equatable, Sendable {
+ case idle
+ case starting
+ case running
+ case paused
+ case stopping
+ case completed
+ case aborted
+ case timedOut
+ case failed
+
+ public var isTerminal: Bool {
+ switch self {
+ case .completed, .aborted, .timedOut, .failed:
+ return true
+ case .idle, .starting, .running, .paused, .stopping:
+ return false
+ }
+ }
+}
+
+public enum RunEventStream: String, Equatable, Sendable {
+ case assistant
+ case tool
+ case lifecycle
+ case reflex
+}
+
+public enum ToolCallCapability: String, CaseIterable, Equatable, Hashable, Sendable {
+ case capture
+ case accessibility
+ case model
+ case input
+ case persistence
+ case perception
+ case controller
+}
+
+public enum ToolCallDecision: Equatable, Sendable {
+ case allow
+ case deny(reason: String)
+ case ask(reason: String)
+
+ public var isAllowed: Bool {
+ self == .allow
+ }
+}
+
+public struct ToolCallPolicy: Equatable, Sendable {
+ public var allowedCapabilities: Set<ToolCallCapability>
+ public var deniedCapabilities: Set<ToolCallCapability>
+ public var approvalRequiredCapabilities: Set<ToolCallCapability>
+
+ public init(
+ allowedCapabilities: Set<ToolCallCapability> = ToolCallPolicy.defaultAllowedCapabilities,
+ deniedCapabilities: Set<ToolCallCapability> = [.input],
+ approvalRequiredCapabilities: Set<ToolCallCapability> = []
+ ) {
+ self.allowedCapabilities = allowedCapabilities
+ self.deniedCapabilities = deniedCapabilities
+ self.approvalRequiredCapabilities = approvalRequiredCapabilities
+ }
+
+ public func decision(for capability: ToolCallCapability) -> ToolCallDecision {
+ if deniedCapabilities.contains(capability) {
+ return .deny(reason: "\(capability.rawValue) capability is denied by policy")
+ }
+
+ if approvalRequiredCapabilities.contains(capability) {
+ return .ask(reason: "\(capability.rawValue) capability requires approval")
+ }
+
+ if allowedCapabilities.contains(capability) {
+ return .allow
+ }
+
+ return .deny(reason: "\(capability.rawValue) capability is not explicitly allowed")
+ }
+
+ public static let defaultAllowedCapabilities: Set<ToolCallCapability> = [
+ .capture,
+ .accessibility,
+ .model,
+ .persistence,
+ .perception,
+ .controller
+ ]
+
+ public static let `default` = ToolCallPolicy()
+}
+
+public struct RunSession: Equatable, Sendable {
+ public var id: String
+ public var userGoal: String
+ public var targetID: String
+ public var runtimeProfile: String
+ public var permissionPolicy: ToolCallPolicy
+ public var lifecycleState: RunLifecycleState
+
+ public init(
+ id: String = UUID().uuidString,
+ userGoal: String,
+ targetID: String,
+ runtimeProfile: String = "default",
+ permissionPolicy: ToolCallPolicy = .default,
+ lifecycleState: RunLifecycleState = .idle
+ ) {
+ self.id = id
+ self.userGoal = userGoal
+ self.targetID = targetID
+ self.runtimeProfile = runtimeProfile
+ self.permissionPolicy = permissionPolicy
+ self.lifecycleState = lifecycleState
+ }
+}
+
+public struct AssistantRunEvent: Equatable, Sendable {
+ public var message: String
+
+ public init(message: String) {
+ self.message = message
+ }
+}
+
+public struct ToolRunEvent: Equatable, Sendable {
+ public var capability: ToolCallCapability
+ public var decision: ToolCallDecision
+ public var toolName: String?
+
+ public init(
+ capability: ToolCallCapability,
+ decision: ToolCallDecision,
+ toolName: String? = nil
+ ) {
+ self.capability = capability
+ self.decision = decision
+ self.toolName = toolName
+ }
+}
+
+public struct LifecycleRunEvent: Equatable, Sendable {
+ public var state: RunLifecycleState
+ public var reason: String?
+
+ public init(state: RunLifecycleState, reason: String? = nil) {
+ self.state = state
+ self.reason = reason
+ }
+}
+
+public struct ReflexRunEvent: Equatable, Sendable {
+ public var frameID: String?
+ public var stateID: String?
+ public var actionID: String?
+ public var sampled: Bool
+
+ public init(
+ frameID: String? = nil,
+ stateID: String? = nil,
+ actionID: String? = nil,
+ sampled: Bool = true
+ ) {
+ self.frameID = frameID
+ self.stateID = stateID
+ self.actionID = actionID
+ self.sampled = sampled
+ }
+}
+
+public enum RunEventPayload: Equatable, Sendable {
+ case assistant(AssistantRunEvent)
+ case tool(ToolRunEvent)
+ case lifecycle(LifecycleRunEvent)
+ case reflex(ReflexRunEvent)
+}
+
+public struct RunEvent: Equatable, Sendable {
+ public var sequence: Int
+ public var stream: RunEventStream
+ public var summary: String
+ public var payload: RunEventPayload
+ public var traceID: String?
+ public var metadata: [String: String]
+ public var requiresInputRelease: Bool
+
+ public init(
+ sequence: Int = 0,
+ stream: RunEventStream,
+ summary: String,
+ payload: RunEventPayload,
+ traceID: String? = nil,
+ metadata: [String: String] = [:],
+ requiresInputRelease: Bool = false
+ ) {
+ self.sequence = sequence
+ self.stream = stream
+ self.summary = summary
+ self.payload = payload
+ self.traceID = traceID
+ self.metadata = metadata
+ self.requiresInputRelease = requiresInputRelease
+ }
+
+ public func assigningSequence(_ sequence: Int) -> RunEvent {
+ var copy = self
+ copy.sequence = sequence
+ return copy
+ }
+}
+
+public struct RunWorldStateSummary: Equatable, Sendable {
+ public var stateID: String
+ public var summary: String
+ public var confidence: Double
+
+ public init(stateID: String, summary: String, confidence: Double) {
+ self.stateID = stateID
+ self.summary = summary
+ self.confidence = confidence
+ }
+}
+
+public struct RunPlannerHint: Equatable, Sendable {
+ public var id: String
+ public var summary: String
+ public var isValid: Bool
+
+ public init(id: String, summary: String, isValid: Bool = true) {
+ self.id = id
+ self.summary = summary
+ self.isValid = isValid
+ }
+}
+
+public struct RunFailureSummary: Equatable, Sendable {
+ public var traceID: String
+ public var summary: String
+
+ public init(traceID: String, summary: String) {
+ self.traceID = traceID
+ self.summary = summary
+ }
+}
+
+public struct RunContextPackage: Equatable, Sendable {
+ public var sessionID: String
+ public var userGoal: String
+ public var targetID: String
+ public var runtimeProfile: String
+ public var latestWorldState: RunWorldStateSummary?
+ public var transcriptSummary: String
+ public var droppedTranscriptCharacterCount: Int
+ public var activeHints: [RunPlannerHint]
+ public var recentFailures: [RunFailureSummary]
+
+ public init(
+ sessionID: String,
+ userGoal: String,
+ targetID: String,
+ runtimeProfile: String,
+ latestWorldState: RunWorldStateSummary? = nil,
+ transcriptSummary: String,
+ droppedTranscriptCharacterCount: Int = 0,
+ activeHints: [RunPlannerHint] = [],
+ recentFailures: [RunFailureSummary] = []
+ ) {
+ self.sessionID = sessionID
+ self.userGoal = userGoal
+ self.targetID = targetID
+ self.runtimeProfile = runtimeProfile
+ self.latestWorldState = latestWorldState
+ self.transcriptSummary = transcriptSummary
+ self.droppedTranscriptCharacterCount = droppedTranscriptCharacterCount
+ self.activeHints = activeHints
+ self.recentFailures = recentFailures
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/InMemoryRunEventStore.swift b/apps/Donkey/Sources/DonkeyRuntime/InMemoryRunEventStore.swift
new file mode 100644
index 00000000..0ebdc606
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/InMemoryRunEventStore.swift
@@ -0,0 +1,29 @@
+import DonkeyContracts
+import Foundation
+
+public actor InMemoryRunEventStore {
+ private var events: [RunEvent] = []
+ private var nextSequence = 1
+
+ public init() {}
+
+ @discardableResult
+ public func append(_ event: RunEvent) -> RunEvent {
+ let sequencedEvent = event.assigningSequence(nextSequence)
+ nextSequence += 1
+ events.append(sequencedEvent)
+ return sequencedEvent
+ }
+
+ public func allEvents() -> [RunEvent] {
+ events
+ }
+
+ public func latestEvent() -> RunEvent? {
+ events.last
+ }
+
+ public func count() -> Int {
+ events.count
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LatestRunSessionQueue.swift b/apps/Donkey/Sources/DonkeyRuntime/LatestRunSessionQueue.swift
new file mode 100644
index 00000000..aa55b775
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/LatestRunSessionQueue.swift
@@ -0,0 +1,49 @@
+import DonkeyContracts
+import Foundation
+
+public struct RunSessionTicket: Equatable, Sendable {
+ public var session: RunSession
+ public var droppedBeforeStartCount: Int
+
+ public init(session: RunSession, droppedBeforeStartCount: Int) {
+ self.session = session
+ self.droppedBeforeStartCount = droppedBeforeStartCount
+ }
+}
+
+public actor LatestRunSessionQueue {
+ private var latestSession: RunSession?
+ private var droppedSessionCount = 0
+
+ public init() {}
+
+ public func submit(_ session: RunSession) {
+ if latestSession != nil {
+ droppedSessionCount += 1
+ }
+
+ latestSession = session
+ }
+
+ public func nextLatest() -> RunSessionTicket? {
+ guard let latestSession else { return nil }
+
+ let ticket = RunSessionTicket(
+ session: latestSession,
+ droppedBeforeStartCount: droppedSessionCount
+ )
+
+ self.latestSession = nil
+ droppedSessionCount = 0
+
+ return ticket
+ }
+
+ public func pendingSessionCount() -> Int {
+ latestSession == nil ? 0 : 1
+ }
+
+ public func droppedCount() -> Int {
+ droppedSessionCount
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfRunLoopBoundary.swift b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfRunLoopBoundary.swift
index 91b59846..740fea71 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfRunLoopBoundary.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfRunLoopBoundary.swift
@@ -11,8 +11,15 @@ public struct OffTheShelfRunLoopBoundary: RuntimeStatusProviding {
public func snapshot() -> RuntimeStatusSnapshot {
RuntimeStatusSnapshot(
isReady: false,
- summary: "Real-time run loop integration boundary",
- sourcePlan: "plans/20-off-the-shelf-run-loop.md"
+ summary: "Run coordinator ready to create sessions",
+ sourcePlan: "plans/20-off-the-shelf-run-loop.md",
+ lifecycleState: .idle
)
}
+
+ public func makeCoordinator(
+ contextAssembler: RunContextAssembler = RunContextAssembler()
+ ) -> RunCoordinator {
+ RunCoordinator(contextAssembler: contextAssembler)
+ }
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
new file mode 100644
index 00000000..50555841
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunContextAssembler.swift
@@ -0,0 +1,41 @@
+import DonkeyContracts
+import Foundation
+
+public struct RunContextAssembler: Equatable, Sendable {
+ public var maxTranscriptCharacters: Int
+
+ public init(maxTranscriptCharacters: Int = 2_000) {
+ self.maxTranscriptCharacters = max(0, maxTranscriptCharacters)
+ }
+
+ public func build(
+ session: RunSession,
+ latestWorldState: RunWorldStateSummary? = nil,
+ transcriptSummary: String = "",
+ activeHints: [RunPlannerHint] = [],
+ recentFailures: [RunFailureSummary] = []
+ ) -> RunContextPackage {
+ let boundedTranscript = bounded(transcriptSummary)
+
+ return RunContextPackage(
+ sessionID: session.id,
+ userGoal: session.userGoal,
+ targetID: session.targetID,
+ runtimeProfile: session.runtimeProfile,
+ latestWorldState: latestWorldState,
+ transcriptSummary: boundedTranscript.text,
+ droppedTranscriptCharacterCount: boundedTranscript.droppedCount,
+ activeHints: activeHints.filter(\.isValid),
+ recentFailures: recentFailures
+ )
+ }
+
+ private func bounded(_ text: String) -> (text: String, droppedCount: Int) {
+ guard text.count > maxTranscriptCharacters else {
+ return (text, 0)
+ }
+
+ let suffix = String(text.suffix(maxTranscriptCharacters))
+ return (suffix, text.count - suffix.count)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
new file mode 100644
index 00000000..965bf513
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/RunCoordinator.swift
@@ -0,0 +1,235 @@
+import DonkeyContracts
+import Foundation
+
+public actor RunCoordinator {
+ private let sessionQueue: LatestRunSessionQueue
+ private let eventStore: InMemoryRunEventStore
+ private let contextAssembler: RunContextAssembler
+ private var currentSession: RunSession?
+ private var lifecycleState: RunLifecycleState = .idle
+ private var requiresInputRelease = false
+
+ public init(
+ sessionQueue: LatestRunSessionQueue = LatestRunSessionQueue(),
+ eventStore: InMemoryRunEventStore = InMemoryRunEventStore(),
+ contextAssembler: RunContextAssembler = RunContextAssembler()
+ ) {
+ self.sessionQueue = sessionQueue
+ self.eventStore = eventStore
+ self.contextAssembler = contextAssembler
+ }
+
+ public func submit(_ session: RunSession) async {
+ await sessionQueue.submit(session)
+ }
+
+ @discardableResult
+ public func startNext() async -> RunSessionTicket? {
+ guard let ticket = await sessionQueue.nextLatest() else { return nil }
+
+ currentSession = ticket.session
+ await transition(to: .starting, reason: "Run session accepted")
+ await transition(to: .running, reason: "Run session started")
+
+ if ticket.droppedBeforeStartCount > 0 {
+ await appendAssistantEvent(
+ summary: "Dropped \(ticket.droppedBeforeStartCount) stale run session(s)",
+ message: "Latest-session queue kept the newest run request."
+ )
+ }
+
+ return ticket
+ }
+
+ @discardableResult
+ public func start(_ session: RunSession) async -> RunSessionTicket? {
+ await submit(session)
+ return await startNext()
+ }
+
+ public func pause(reason: String? = nil) async {
+ await transition(to: .paused, reason: reason ?? "Run paused")
+ }
+
+ public func resume(reason: String? = nil) async {
+ await transition(to: .running, reason: reason ?? "Run resumed")
+ }
+
+ public func complete(reason: String? = nil) async {
+ await transition(to: .stopping, reason: "Run stopping before completion")
+ await transition(to: .completed, reason: reason ?? "Run completed")
+ }
+
+ public func abort(reason: String? = nil) async {
+ requiresInputRelease = true
+ await transition(
+ to: .aborted,
+ reason: reason ?? "Run aborted",
+ requiresInputRelease: true
+ )
+ }
+
+ public func timeout(reason: String? = nil) async {
+ requiresInputRelease = true
+ await transition(
+ to: .timedOut,
+ reason: reason ?? "Run timed out",
+ requiresInputRelease: true
+ )
+ }
+
+ public func fail(reason: String? = nil) async {
+ await transition(to: .failed, reason: reason ?? "Run failed")
+ }
+
+ @discardableResult
+ public func recordToolCall(
+ capability: ToolCallCapability,
+ toolName: String? = nil
+ ) async -> ToolCallDecision {
+ let decision = activePolicy().decision(for: capability)
+ let event = RunEvent(
+ stream: .tool,
+ summary: "\(capability.rawValue) tool call \(decision.summaryFragment)",
+ payload: .tool(
+ ToolRunEvent(
+ capability: capability,
+ decision: decision,
+ toolName: toolName
+ )
+ )
+ )
+ await eventStore.append(event)
+ return decision
+ }
+
+ public func appendReflexSample(
+ frameID: String? = nil,
+ stateID: String? = nil,
+ actionID: String? = nil,
+ traceID: String? = nil
+ ) async {
+ await eventStore.append(
+ RunEvent(
+ stream: .reflex,
+ summary: "Reflex sample recorded",
+ payload: .reflex(
+ ReflexRunEvent(
+ frameID: frameID,
+ stateID: stateID,
+ actionID: actionID
+ )
+ ),
+ traceID: traceID
+ )
+ )
+ }
+
+ public func buildContext(
+ latestWorldState: RunWorldStateSummary? = nil,
+ transcriptSummary: String = "",
+ activeHints: [RunPlannerHint] = [],
+ recentFailures: [RunFailureSummary] = []
+ ) -> RunContextPackage? {
+ guard let currentSession else { return nil }
+
+ return contextAssembler.build(
+ session: currentSession,
+ latestWorldState: latestWorldState,
+ transcriptSummary: transcriptSummary,
+ activeHints: activeHints,
+ recentFailures: recentFailures
+ )
+ }
+
+ public func snapshot() async -> RuntimeStatusSnapshot {
+ let latestEvent = await eventStore.latestEvent()
+ let eventCount = await eventStore.count()
+
+ return RuntimeStatusSnapshot(
+ isReady: lifecycleState == .running,
+ summary: summary(for: lifecycleState),
+ sourcePlan: "plans/20-off-the-shelf-run-loop.md",
+ lifecycleState: lifecycleState,
+ latestEventSummary: latestEvent?.summary,
+ eventCount: eventCount,
+ requiresInputRelease: requiresInputRelease
+ )
+ }
+
+ public func events() async -> [RunEvent] {
+ await eventStore.allEvents()
+ }
+
+ private func transition(
+ to state: RunLifecycleState,
+ reason: String?,
+ requiresInputRelease: Bool = false
+ ) async {
+ lifecycleState = state
+
+ let event = RunEvent(
+ stream: .lifecycle,
+ summary: summary(for: state),
+ payload: .lifecycle(
+ LifecycleRunEvent(
+ state: state,
+ reason: reason
+ )
+ ),
+ requiresInputRelease: requiresInputRelease
+ )
+
+ await eventStore.append(event)
+ }
+
+ private func appendAssistantEvent(summary: String, message: String) async {
+ await eventStore.append(
+ RunEvent(
+ stream: .assistant,
+ summary: summary,
+ payload: .assistant(AssistantRunEvent(message: message))
+ )
+ )
+ }
+
+ private func activePolicy() -> ToolCallPolicy {
+ currentSession?.permissionPolicy ?? .default
+ }
+
+ private func summary(for state: RunLifecycleState) -> String {
+ switch state {
+ case .idle:
+ return "Run coordinator idle"
+ case .starting:
+ return "Run starting"
+ case .running:
+ return "Run running"
+ case .paused:
+ return "Run paused"
+ case .stopping:
+ return "Run stopping"
+ case .completed:
+ return "Run completed"
+ case .aborted:
+ return "Run aborted"
+ case .timedOut:
+ return "Run timed out"
+ case .failed:
+ return "Run failed"
+ }
+ }
+}
+
+private extension ToolCallDecision {
+ var summaryFragment: String {
+ switch self {
+ case .allow:
+ return "allowed"
+ case .deny:
+ return "denied"
+ case .ask:
+ return "requires approval"
+ }
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift
new file mode 100644
index 00000000..a9e154ae
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/RunCoordinatorTests.swift
@@ -0,0 +1,218 @@
+import DonkeyContracts
+@testable import DonkeyRuntime
+import Testing
+
+@Suite
+struct RunCoordinatorTests {
+ @Test
+ func coordinatorLifecycleEmitsOrderedEvents() async {
+ let coordinator = RunCoordinator()
+
+ let ticket = await coordinator.start(
+ RunSession(
+ id: "session-1",
+ userGoal: "tap when ready",
+ targetID: "target-1"
+ )
+ )
+ #expect(ticket?.session.id == "session-1")
+
+ await coordinator.pause(reason: "operator paused")
+ await coordinator.resume(reason: "operator resumed")
+ await coordinator.complete(reason: "done")
+
+ let events = await coordinator.events()
+ #expect(events.map(\.sequence) == [1, 2, 3, 4, 5, 6])
+ #expect(lifecycleStates(in: events) == [
+ .starting,
+ .running,
+ .paused,
+ .running,
+ .stopping,
+ .completed
+ ])
+
+ let snapshot = await coordinator.snapshot()
+ #expect(snapshot.lifecycleState == .completed)
+ #expect(snapshot.eventCount == 6)
+ #expect(snapshot.latestEventSummary == "Run completed")
+ }
+
+ @Test
+ func abortEmitsTerminalLifecycleEventAndRequestsInputRelease() async {
+ let coordinator = RunCoordinator()
+
+ _ = await coordinator.start(
+ RunSession(
+ id: "session-abort",
+ userGoal: "run until stopped",
+ targetID: "target-1"
+ )
+ )
+ await coordinator.abort(reason: "stop requested")
+
+ let events = await coordinator.events()
+ #expect(lifecycleStates(in: events).last == .aborted)
+ #expect(events.last?.requiresInputRelease == true)
+
+ let snapshot = await coordinator.snapshot()
+ #expect(snapshot.lifecycleState == .aborted)
+ #expect(snapshot.requiresInputRelease == true)
+ }
+
+ @Test
+ func timeoutDoesNotCreateInputActionAndRequestsInputRelease() async {
+ let coordinator = RunCoordinator()
+
+ _ = await coordinator.start(
+ RunSession(
+ id: "session-timeout",
+ userGoal: "run with deadline",
+ targetID: "target-1"
+ )
+ )
+ await coordinator.timeout(reason: "deadline exceeded")
+
+ let events = await coordinator.events()
+ #expect(lifecycleStates(in: events).last == .timedOut)
+ #expect(events.last?.requiresInputRelease == true)
+ #expect(!events.contains { event in
+ guard case .tool(let payload) = event.payload else { return false }
+ return payload.capability == .input
+ })
+ }
+
+ @Test
+ func latestSessionQueueDropsStaleSessions() async {
+ let queue = LatestRunSessionQueue()
+ await queue.submit(
+ RunSession(id: "stale", userGoal: "old goal", targetID: "target-1")
+ )
+ await queue.submit(
+ RunSession(id: "latest", userGoal: "new goal", targetID: "target-1")
+ )
+
+ let ticket = await queue.nextLatest()
+
+ #expect(ticket?.session.id == "latest")
+ #expect(ticket?.droppedBeforeStartCount == 1)
+ #expect(await queue.nextLatest() == nil)
+ }
+
+ @Test
+ func permissionPolicyDeniesInputByDefault() async {
+ let coordinator = RunCoordinator()
+
+ _ = await coordinator.start(
+ RunSession(
+ id: "session-policy",
+ userGoal: "try input",
+ targetID: "target-1"
+ )
+ )
+
+ let decision = await coordinator.recordToolCall(
+ capability: .input,
+ toolName: "synthetic-input"
+ )
+
+ #expect(!decision.isAllowed)
+
+ let events = await coordinator.events()
+ #expect(events.last?.stream == .tool)
+ guard case .tool(let payload) = events.last?.payload else {
+ Issue.record("Expected a tool event")
+ return
+ }
+ #expect(payload.capability == .input)
+ #expect(!payload.decision.isAllowed)
+ }
+
+ @Test
+ func eventStorePreservesAppendOrderAcrossStreams() async {
+ let store = InMemoryRunEventStore()
+
+ await store.append(
+ RunEvent(
+ stream: .assistant,
+ summary: "assistant",
+ payload: .assistant(AssistantRunEvent(message: "thinking"))
+ )
+ )
+ await store.append(
+ RunEvent(
+ stream: .tool,
+ summary: "tool",
+ payload: .tool(
+ ToolRunEvent(
+ capability: .capture,
+ decision: .allow
+ )
+ )
+ )
+ )
+ await store.append(
+ RunEvent(
+ stream: .lifecycle,
+ summary: "lifecycle",
+ payload: .lifecycle(LifecycleRunEvent(state: .running))
+ )
+ )
+ await store.append(
+ RunEvent(
+ stream: .reflex,
+ summary: "reflex",
+ payload: .reflex(ReflexRunEvent(frameID: "frame-1"))
+ )
+ )
+
+ let events = await store.allEvents()
+ #expect(events.map(\.sequence) == [1, 2, 3, 4])
+ #expect(events.map(\.stream) == [.assistant, .tool, .lifecycle, .reflex])
+ }
+
+ @Test
+ func contextAssemblerBoundsTranscriptAndPreservesCurrentContext() {
+ let assembler = RunContextAssembler(maxTranscriptCharacters: 10)
+ let session = RunSession(
+ id: "session-context",
+ userGoal: "avoid hazards",
+ targetID: "subway-surfers",
+ runtimeProfile: "iphone-mirroring"
+ )
+ let worldState = RunWorldStateSummary(
+ stateID: "state-1",
+ summary: "player in center lane",
+ confidence: 0.9
+ )
+ let context = assembler.build(
+ session: session,
+ latestWorldState: worldState,
+ transcriptSummary: "0123456789abcdef",
+ activeHints: [
+ RunPlannerHint(id: "hint-1", summary: "prefer center", isValid: true),
+ RunPlannerHint(id: "hint-2", summary: "expired", isValid: false)
+ ],
+ recentFailures: [
+ RunFailureSummary(traceID: "trace-1", summary: "missed left hazard")
+ ]
+ )
+
+ #expect(context.sessionID == "session-context")
+ #expect(context.userGoal == "avoid hazards")
+ #expect(context.targetID == "subway-surfers")
+ #expect(context.runtimeProfile == "iphone-mirroring")
+ #expect(context.latestWorldState == worldState)
+ #expect(context.transcriptSummary == "6789abcdef")
+ #expect(context.droppedTranscriptCharacterCount == 6)
+ #expect(context.activeHints.map(\.id) == ["hint-1"])
+ #expect(context.recentFailures.map(\.traceID) == ["trace-1"])
+ }
+
+ private func lifecycleStates(in events: [RunEvent]) -> [RunLifecycleState] {
+ events.compactMap { event in
+ guard case .lifecycle(let payload) = event.payload else { return nil }
+ return payload.state
+ }
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index 3324c6d9..4f284393 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -11,6 +11,7 @@ Plans describe what we might build. Guides describe what Donkey currently suppor
## Engineering Guides
- [Swift MVC Guide](guides/swift-mvc.md): Swift/AppKit/SwiftUI organization rules for model-view-controller boundaries.
+- [Minimal Run Coordinator](guides/minimal-run-coordinator.md): in-memory run lifecycle, events, policy checks, session queueing, and context compaction boundary.
## Navigation Rules
diff --git a/docs/guides/README.md b/docs/guides/README.md
index d5dd7c1e..578219d6 100644
--- a/docs/guides/README.md
+++ b/docs/guides/README.md
@@ -9,3 +9,4 @@ Guides explain what Donkey supports and how to maintain it. They should stay rea
## Technical Guidelines
- [Swift MVC Guide](swift-mvc.md)
+- [Minimal Run Coordinator](minimal-run-coordinator.md)
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
new file mode 100644
index 00000000..5909efa4
--- /dev/null
+++ b/docs/guides/minimal-run-coordinator.md
@@ -0,0 +1,42 @@
+# Minimal Run Coordinator
+
+## Supported Behavior
+
+Donkey supports a minimal in-memory runtime coordinator for the future off-the-shelf run loop.
+
+The coordinator can:
+
+- accept run sessions with a user goal, target id, runtime profile, and permission policy
+- keep only the latest pending live-control session request
+- publish ordered `assistant`, `tool`, `lifecycle`, and `reflex` events
+- move through explicit lifecycle states for start, pause, resume, completion, abort, timeout, and failure
+- deny unsafe input tool calls by default
+- mark aborts and timeouts as requiring held-input release
+- build bounded planner context from the current session, world-state summary, transcript summary, valid hints, and recent failures
+
+This is a coordination foundation only. It does not capture the screen, run perception models, call LLMs, or execute OS input.
+
+## Technical Guidelines
+
+- Keep shared event, policy, lifecycle, and context types in `DonkeyContracts`.
+- Keep coordinator state and append ordering in `DonkeyRuntime`; UI code should read status through narrow provider boundaries.
+- Treat `RunCoordinator` as the owner of lifecycle and event ordering, not as the owner of perception, controller internals, or input backends.
+- Keep input actions denied unless a caller provides a policy that explicitly allows them.
+- Preserve latest-request-wins behavior for live-control sessions so stale work cannot build up behind the reflex loop.
+- Use sampled or summarized reflex events until a measured trace sink exists.
+
+## Verification
+
+From `apps/Donkey/`:
+
+```sh
+swift test
+```
+
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, and context compaction.
+
+## Source Entry Points
+
+- Runtime contracts live in `apps/Donkey/Sources/DonkeyContracts/RunLoopContracts.swift`.
+- Runtime coordination lives in `apps/Donkey/Sources/DonkeyRuntime/`.
+- The source plan remains active in `plans/20-off-the-shelf-run-loop.md`.
diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.md
index 4577ee6c..eb0c687c 100644
--- a/plans/20-off-the-shelf-run-loop.md
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -81,6 +81,113 @@ Runtime rules:
- cap queue sizes at 1 in the reflex path
- benchmark each component separately and together
+## Product-Grade Run Loop
+
+Wrap the low-latency loop in an OpenClaw-inspired runtime shell, but do not make Donkey depend on OpenClaw, Pi, or a generic agent framework in the hot path.
+
+The product loop should look like:
+
+```text
+intake
+ -> session queue
+ -> context assembly
+ -> local perception / model inference
+ -> deterministic controller
+ -> tool / action execution
+ -> streaming events
+ -> transcript / trace persistence
+ -> compaction / recovery
+```
+
+The runtime shell owns coordination. It loads target adapters and skills, resolves model/auth/runtime profiles, subscribes to model/tool/reflex events, enforces queue sizes and deadlines, applies tool permission policy, and bridges events back to UI or client streams.
+
+The runtime shell does not own per-frame perception logic, controller policy internals, or direct OS input. Those stay behind explicit capture, perception, controller, and action-engine interfaces.
+
+### Event Bridge
+
+Publish a small set of typed event streams:
+
+- `assistant`: user-visible reasoning, recovery notes, explanations, summaries
+- `tool`: capture, perception, controller, action, Accessibility, model, and persistence calls
+- `lifecycle`: run started, paused, resumed, aborted, timed out, completed
+- `reflex`: frame, state, and action trace events, sampled or summarized to avoid hot-path overhead
+
+All event envelopes should include trace ids where possible. Reflex events must be cheap to emit and safe to drop or sample when the loop is under pressure.
+
+### Run Coordination Responsibilities
+
+The coordinator should provide the product-grade parts around the loop:
+
+- session queue with latest-request-wins behavior for live control
+- run lifecycle state: idle, starting, running, paused, stopping, completed, failed
+- tool permission policy for capture, Accessibility, model calls, and input actions
+- transcript and trace persistence with a single writer or explicit append lock
+- context compaction before slow planner calls
+- streaming event publication for UI/client observers
+- abort and timeout handling that releases held input and closes streams
+- sandbox/focus guard for risky tools and OS input
+- bounded queues, deadlines, and stale-frame drops
+
+### Conceptual Runtime Shape
+
+This pseudocode is conceptual. It describes coordination boundaries, not the exact Swift API.
+
+```swift
+while run.isActive {
+ let ticket = await sessionQueue.nextLatest()
+
+ let context = await contextAssembler.build(
+ session: ticket.session,
+ latestWorldState: stateStore.latest(),
+ transcriptSummary: transcript.compactedSummary(),
+ activeHints: hintStore.validHints()
+ )
+
+ let plannerResult = await planner.maybeGenerate(
+ context: context,
+ timeout: policy.plannerTimeout
+ )
+
+ await hintStore.publishValidated(plannerResult.hints)
+ await stream.publish(plannerResult.events)
+
+ while let frame = await frameBuffer.latestIfFresh() {
+ let state = await perception.update(frame)
+ let action = controller.decide(state, hintStore.validHints())
+
+ guard await permissionPolicy.allows(action),
+ await focusGuard.targetIsSafe()
+ else {
+ await lifecycle.pause(reason: .unsafeActionSurface)
+ break
+ }
+
+ let result = await actionEngine.execute(action)
+ await traceStore.append(frame, state, action, result)
+ await stream.publishReflexSample(frame, state, action, result)
+ }
+}
+```
+
+Separate the loops in implementation:
+
+- reflex loop: latest-frame-wins capture, local perception, deterministic controller, bounded action execution
+- planner loop: context assembly, model call, validated planner hints, memory updates
+- tool/action loop: permission checks, sandbox/focus guard, execution, trace persistence
+
+Remote LLM and chat-style local LLM work belongs in the planner loop. It must never be required for reflex ticks or direct input.
+
+### Interfaces To Define
+
+Define these contracts before the first production coordinator implementation:
+
+- `RunSession`: user goal, target id, runtime profile, permission scope, lifecycle state
+- `RunEvent`: assistant/tool/lifecycle/reflex event envelope with trace ids
+- `ToolCallPolicy`: allow, deny, or ask rules for capture, Accessibility, model, and input actions
+- `TranscriptStore` / `TraceStore`: append-only persistence with a single writer or explicit lock
+- `ContextAssembler`: compact planner context from world state, traces, memory, screenshots, and user goal
+- `RunCoordinator`: queueing, cancellation, timeouts, event bridging, and lifecycle ownership
+
## Platform Defaults
### Windows
@@ -281,10 +388,14 @@ Runtime: native core where the hot path needs it
4. Add one off-the-shelf detector or template signal.
5. Add one deterministic rule that emits a safe semantic action.
6. Add action calibration and focus guard.
-7. Add trace logging and latency report.
-8. Add optional segmentation only if detection/templates fail.
-9. Add OCR only for text-dependent screens.
-10. Add slow LLM recovery after the reflex loop works.
+7. Add a minimal Swift runtime coordinator around `DonkeyRuntime`.
+8. Use `OffTheShelfRunLoopBoundary` as the first status/event boundary.
+9. Add session queue, lifecycle state, permission policy, and abort handling.
+10. Add trace logging and latency report.
+11. Add optional segmentation only if detection/templates fail.
+12. Add OCR only for text-dependent screens.
+13. Add slow LLM recovery after the reflex loop works.
+14. Add transcript compaction and memory writes only after planner hints are useful.
## Acceptance Criteria
@@ -295,6 +406,12 @@ Runtime: native core where the hot path needs it
- p95 reflex latency stays under the target budget.
- LLM output is validated before it changes controller configuration.
- Segmentation and OCR are cropped and measured before live use.
+- The runtime coordinator can start, pause, abort, timeout, and complete a run.
+- Abort releases held input and publishes a terminal lifecycle event.
+- Session queue drops stale live-control work instead of building backlog.
+- Permission policy can deny unsafe input before action execution.
+- Transcript and trace writes stay ordered under concurrent model/tool/reflex events.
+- Context compaction keeps planner input bounded while preserving the latest goal, state, failures, and valid hints.
## Where To Look