60 lines
3.0 KiB
Swift
60 lines
3.0 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
|
|
/// Input receipts belong to one native launch and cannot be reused after its grant is retired.
|
|
@MainActor
|
|
final class MCPCompiledRunIO {
|
|
private let machine: MachineModel
|
|
private let runID: String
|
|
private let expected: VCCMachineSnapshot
|
|
private let assembly: Bool
|
|
private let lease = VCCCompiledRunLease()
|
|
private var accepted: [String: String] = [:]
|
|
private var sending = false
|
|
|
|
init(machine: MachineModel, runID: String, expected: VCCMachineSnapshot, assembly: Bool) {
|
|
self.machine = machine
|
|
self.runID = runID
|
|
self.expected = expected
|
|
self.assembly = assembly
|
|
}
|
|
|
|
func invalidate() {
|
|
lease.invalidate()
|
|
machine.cancelMCPInput(runID: runID)
|
|
}
|
|
|
|
func finalScreenText() async throws -> String? {
|
|
let result = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected,
|
|
assembly: assembly, key: nil, readScreen: false, finalScreen: true)
|
|
guard lease.isValid else { throw ProfileFailure.message("stale_run") }
|
|
return result["text"] as? String
|
|
}
|
|
|
|
func reply(_ tool: String, arguments: [String: Any]) async throws -> [String: Any] {
|
|
guard lease.isValid, arguments["run_id"] as? String == runID else { throw ProfileFailure.message("stale_run") }
|
|
if tool == "read_screen_text", arguments.count == 1 {
|
|
let result = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected,
|
|
assembly: assembly, key: nil, readScreen: true)
|
|
guard lease.isValid else { throw ProfileFailure.message("stale_run") }
|
|
return result
|
|
}
|
|
guard tool == "send_keys", arguments.count == 3,
|
|
let request = arguments["request_id"] as? String, (1...64).contains(request.utf8.count),
|
|
let keys = arguments["keys"] as? String, MCPGuestKey.accepts(keys),
|
|
let chord = CocoKeyboard.chord(for: keys) else { throw ProfileFailure.message("invalid_arguments") }
|
|
let prior = accepted[request]
|
|
if let prior, prior != keys { throw ProfileFailure.message("request_conflict") }
|
|
guard !sending else { throw ProfileFailure.message("input_busy") }
|
|
guard prior != nil || accepted.count < MCPGuestKey.limit else { throw ProfileFailure.message("input_limit_reached") }
|
|
sending = true
|
|
defer { sending = false }
|
|
// Revalidate even cached receipts. Only the first accepted request submits a chord.
|
|
_ = try await machine.mcpCompiledGuest(lease: lease, runID: runID, expected: expected, assembly: assembly,
|
|
key: prior == nil ? NSNumber(value: chord) : nil, readScreen: false)
|
|
guard lease.isValid else { throw ProfileFailure.message("stale_run") }
|
|
accepted[request] = keys
|
|
return ["run_id": runID, "request_id": request, "accepted": true]
|
|
}
|
|
}
|