Files

324 lines
18 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import Combine
import Foundation
enum MCPGuestKey {
static let limit = 64
static func accepts(_ keys: String) -> Bool {
guard keys.utf8.count == 1, let byte = keys.utf8.first else { return false }
return byte == 32 || (48...57).contains(byte) || (65...90).contains(byte) || (97...122).contains(byte)
}
}
@MainActor
final class MCPBASICRun: ObservableObject {
@Published private(set) var status = ""
@Published private(set) var busy = false
@Published private(set) var runID: String?
@Published private(set) var receipt: [String: Any]?
private struct Run {
let id: String
let document: UUID
let revision: Int
let snapshot: VCCMachineSnapshot
let guestSource: String
}
private var inspection: MCPDebuggerInspection?
private var run: Run?
private weak var machine: MachineModel?
private var sourceChanges: AnyCancellable?
private var requestedDocument: UUID?
private var requestedRevision: Int?
private var generation = UUID()
private var sending = false
private var sent: [String: String] = [:]
private var verifiedPrompt = false
private var currentApproval: (() -> Bool)?
func reset() {
if let run { machine?.cancelMCPInput(runID: run.id) }
generation = UUID()
run = nil
inspection = nil
runID = nil
receipt = nil
requestedDocument = nil
requestedRevision = nil
sourceChanges = nil
currentApproval = nil
busy = false
sending = false
verifiedPrompt = false
sent.removeAll()
status = ""
}
func start(model: BASICDevelopmentModel, bothChoices: Bool, isCurrent: @escaping () -> Bool) async {
guard !busy, !sending, isCurrent() else { return }
reset()
busy = true
machine = model.machine
currentApproval = isCurrent
sourceChanges = model.$source.dropFirst().sink { [weak self] _ in self?.reset() }
let ticket = generation, document = model.documentID, revision = model.sourceRevision
requestedDocument = document
requestedRevision = revision
let current = { self.generation == ticket && document == model.documentID && revision == model.sourceRevision && isCurrent() }
defer { if generation == ticket { busy = false } }
do {
var branches: [[String: Any]] = []
for key in bothChoices ? ["2", "1"] : [""] {
try require(current(), "The approved revision or connection changed.")
status = "Starting the reviewed BASIC program…"
guard let (snapshot, guestSource) = await model.performTransfer(run: true, reviewIsCurrent: current) else {
throw ProfileFailure.message(model.message ?? "The BASIC workspace could not start this run.")
}
try require(current() && model.machine.basicWorkspaceOwner == model.workspaceID, "The BASIC workspace changed.")
let started = Run(id: UUID().uuidString, document: document, revision: revision, snapshot: snapshot, guestSource: guestSource)
run = started
runID = started.id
sent.removeAll()
verifiedPrompt = false
if bothChoices {
status = key == "2" ? "Checking Mars in the CoCo…" : "Checking Earth in the CoCo…"
branches.append(try await checkChoice(key, model: model, run: started))
}
}
try require(current(), "The approved revision or connection changed.")
if bothChoices {
let mismatches = branches.filter { $0["color_matches"] as? Bool == false }
receipt = ["document_id": document.uuidString, "revision": revision, "branches": branches,
"verified": mismatches.isEmpty, "behavior_verified": true]
verifiedPrompt = true
if let first = mismatches.first {
status = "Both greetings and PRINT 7 verified. Choice " + (first["key"] as? String ?? "") +
" displayed " + (first["background_rgb"] as? String ?? "") + " instead of the expected " +
(first["expected_color"] as? String ?? "") + " background."
} else { status = "Verified both choices and PRINT 7." }
} else { status = "BASIC started. The client can read the guest screen and send a single letter, digit or space at a time." }
} catch {
if generation == ticket {
status += " " + error.localizedDescription
run = nil
runID = nil
}
}
}
private func require(_ condition: Bool, _ reason: String) throws {
guard condition else { throw ProfileFailure.message(reason) }
}
private func validate(_ model: BASICDevelopmentModel, _ expected: Run) throws {
try require(run?.id == expected.id && currentApproval?() == true && model.documentID == expected.document
&& model.sourceRevision == expected.revision && model.machine.basicWorkspaceOwner == model.workspaceID,
"The run or reviewed document has changed.")
}
private func screen(_ model: BASICDevelopmentModel, _ expected: Run) async throws -> [String: Any] {
let deadline = ContinuousClock.now.advanced(by: .seconds(1))
while true {
try validate(model, expected)
do {
let result = try await model.machine.mcpScreen(expected: expected.snapshot, source: expected.guestSource)
try validate(model, expected)
return result
} catch {
// WIDTH can temporarily switch out BASIC's RAM while redrawing.
guard error.localizedDescription == "Direct BASIC access requires the normal BASIC memory map",
ContinuousClock.now < deadline else { throw error }
try await Task.sleep(for: .milliseconds(45))
}
}
}
private func type(_ keys: String, model: BASICDevelopmentModel, run: Run) async throws {
let deadline = ContinuousClock.now.advanced(by: .seconds(2))
while true {
try validate(model, run)
do {
try await model.machine.mcpPaste(keys, runID: run.id, direct: keys == "PRINT 7\n",
expected: run.snapshot, source: run.guestSource)
try validate(model, run)
return
} catch {
// Both refusals occur before the controller queues any keys. A ROM
// interrupt or GIME text update may temporarily obscure direct mode.
let beforeTyping = ["Direct BASIC access requires the normal BASIC memory map",
"The guest is not at the expected BASIC input state."]
guard beforeTyping.contains(error.localizedDescription), ContinuousClock.now < deadline else { throw error }
try await Task.sleep(for: .milliseconds(45))
}
}
}
private func wait(_ reason: String, model: BASICDevelopmentModel, run: Run,
until: ([String: Any], [String]) -> Bool) async throws -> [String: Any] {
let clock = ContinuousClock()
let end = clock.now.advanced(by: .seconds(6))
var last = ""
var state = ""
while clock.now < end {
let result = try await screen(model, run)
last = result["text"] as? String ?? ""
state = "frame \(result["frame"] ?? "?"), paste \(result["paste_remaining"] ?? "?"), direct input \(result["direct_prompt"] ?? "?")"
if until(result, last.components(separatedBy: "\n")) { return result }
try await Task.sleep(for: .milliseconds(75))
}
throw ProfileFailure.message("Timed out waiting for " + reason + " (" + state + "). Guest screen: " + String(last.suffix(350)))
}
private static func hasMenu(_ lines: [String]) -> Bool {
let shown = lines.map { $0.trimmingCharacters(in: .whitespaces).lowercased() }.filter { !$0.isEmpty }
guard shown.count >= 2 else { return false }
let first = shown[shown.count - 2], second = shown[shown.count - 1]
return first.hasPrefix("1") && first.contains("earth") && second.hasPrefix("2") && second.contains("mars")
}
private func checkChoice(_ key: String, model: BASICDevelopmentModel, run: Run) async throws -> [String: Any] {
let menu = try await wait("the 40-column choice menu", model: model, run: run) { s, lines in
s["columns"] as? Int == 40 && Self.hasMenu(lines) && s["direct_prompt"] as? Bool == false
}
try await type("3", model: model, run: run)
let menuFrame = menu["frame"] as? UInt64 ?? 0
let ignored = try await wait("the menu after the unrelated key", model: model, run: run) { s, _ in
Self.hasMenu((s["text"] as? String ?? "").components(separatedBy: "\n")) && s["direct_prompt"] as? Bool == false &&
s["paste_remaining"] as? Int == 0 && (s["frame"] as? UInt64 ?? 0) >= menuFrame + 10
}
try await type(key, model: model, run: run)
let greeting = key == "1" ? "Hello Nice Blue Dot World!" : "Bring a warm coat!"
let output = try await wait("the greeting and BASIC prompt", model: model, run: run) { s, lines in
s["direct_prompt"] as? Bool == true && s["paste_remaining"] as? Int == 0 &&
lines.contains { $0.trimmingCharacters(in: .whitespaces) == "OK" }
}
let text = output["text"] as? String ?? ""
let lines = text.components(separatedBy: "\n")
guard let row = lines.firstIndex(where: { $0.trimmingCharacters(in: .whitespaces) == greeting }) else {
throw ProfileFailure.message("Expected “" + greeting + "” for choice " + key + ". Guest screen: " + text)
}
guard let sample = (output["colors"] as? [[String: Int]])?.first(where: { $0["row"] == row }),
let rgb = sample["rgb"] else {
throw ProfileFailure.message("The greeting has no measurable text-cell background.")
}
let red = (rgb >> 16) & 255, green = (rgb >> 8) & 255, blue = rgb & 255
// Require a strongly dominant primary. Composite palette 37 renders amber
// (#FFBF39); its largest component is red, which alone cannot verify red.
let dominant = key == "1" ? blue : red
let others = key == "1" ? max(red, green) : max(green, blue)
let correct = dominant >= 32 && dominant >= 2 * others
try require(sample["palette_value"] == (key == "1" ? 10 : 37), "The greeting used an unexpected GIME palette value.")
try await type("PRINT 7\n", model: model, run: run)
let prompt = try await wait("the result of PRINT 7", model: model, run: run) { s, rows in
let compact = rows.map { $0.trimmingCharacters(in: .whitespaces).uppercased() }.filter { !$0.isEmpty }
return compact.suffix(3) == ["PRINT 7", "7", "OK"] && s["direct_prompt"] as? Bool == true && s["paste_remaining"] as? Int == 0
}
return ["key": key, "run_id": run.id, "invalid_key": "3", "invalid_screen": ignored["text"] ?? "",
"screen": text, "greeting": lines[row], "color_matches": correct, "expected_color": key == "1" ? "blue" : "red", "background_rgb": String(format: "#%06X", rgb), "cell": sample,
"frame": output["frame"] ?? 0, "signal": output["signal"] ?? 0, "columns": output["columns"] ?? 0,
"processor": run.snapshot.use6309 ? "HD6309" : "MC6809", "command_screen": prompt["text"] ?? ""]
}
private func debug(_ tool: String, _ args: [String: Any], model: BASICDevelopmentModel, run: Run) async throws -> [String: Any] {
// The BASIC bridge verifies exact detokenized source plus run identity.
let observed = try await model.machine.checkReviewedBASIC(run.snapshot, source: run.guestSource)
try validate(model, run)
guard MCPDebuggerInspection.sameProgram(observed, run.snapshot) else { throw ProfileFailure.message("stale_run") }
if tool == "get_debug_snapshot" {
guard args.count == 1 else { throw ProfileFailure.message("invalid_arguments") }
let captured = try await MCPDebuggerInspection.capture(model.machine)
let state = captured.machine
guard MCPDebuggerInspection.sameProgram(state, run.snapshot) else { throw ProfileFailure.message("stale_run") }
guard state.state == .paused else { throw ProfileFailure.message("pause_required") }
let stop = model.machine.basicDebug
var watches: [[String: String]] = [], watchStatus = "Pause at a supported BASIC statement to inspect watches."
var mapped: [String: Any]?
if state.basicDebugAttached && !state.basicStepping && state.basicStoppedLine >= 0 {
mapped = ["line": state.basicStoppedLine, "address": Int(state.programCounter)]
let (variables, error) = await model.machine.inspectBASIC(source: model.source, stop: stop)
if let variables {
watches = model.watches.compactMap { name in BASICWatch(name).map { ["name": name, "value": $0.value(in: variables)] } }
watchStatus = "available"
} else { watchStatus = error ?? "BASIC variable memory is unavailable." }
}
let bytes = captured.logicalMemory, available = captured.logicalMemoryAvailable
guard bytes.count >= 0x1d, available.count >= 0x1d, available[0x19..<0x1d].allSatisfy({ $0 != 0 }) else {
throw ProfileFailure.message("memory_unavailable")
}
let start = Int(bytes[0x19]) * 256 + Int(bytes[0x1a]), end = Int(bytes[0x1b]) * 256 + Int(bytes[0x1c])
// A second source check binds the parsed interpreter pointers and watches to the same paused stop.
let now = try await model.machine.checkReviewedBASIC(run.snapshot, source: run.guestSource)
try validate(model, run)
guard MCPDebuggerInspection.sameProgram(now, state), now.state == .paused, now.cycles == state.cycles,
end >= start else { throw ProfileFailure.message("stale_snapshot") }
inspection = try MCPDebuggerInspection(runID: run.id, capture: captured,
scope: ["document_id": run.document.uuidString, "revision": run.revision],
sourceStop: mapped, watches: watches, watchStatus: watchStatus, ranges: [start..<end])
}
guard let inspection else { throw ProfileFailure.message("no_snapshot") }
return try inspection.reply(tool: tool, arguments: args)
}
func handle(tool: String, arguments: [String: Any], model: BASICDevelopmentModel) async -> [String: Any] {
if tool == "get_run" {
guard let requestedDocument, let requestedRevision else { return ["error": "no_run"] }
guard currentApproval?() == true, model.documentID == requestedDocument, model.sourceRevision == requestedRevision,
arguments.count == 2, arguments["document_id"] as? String == requestedDocument.uuidString,
arguments["revision"] as? Int == requestedRevision else { return ["error": "revision_conflict"] }
var result: [String: Any] = ["document_id": requestedDocument.uuidString, "revision": requestedRevision,
"busy": busy, "status": status, "run_id": runID as Any? ?? NSNull()]
if let receipt { result["receipt"] = receipt }
return ["result": result]
}
guard let run else { return ["error": "no_run"] }
do {
try validate(model, run)
guard arguments["run_id"] as? String == run.id else { return ["error": "stale_run"] }
if tool == "get_debug_snapshot" || tool == "read_debug_memory" {
return ["result": try await debug(tool, arguments, model: model, run: run)]
}
if tool == "read_screen_text", arguments.count == 1 {
var observation = try await screen(model, run)
observation["run_id"] = run.id
observation["revision"] = run.revision
return ["result": observation]
}
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) || keys == "PRINT 7\n"
else { return ["error": "invalid_arguments"] }
let accepted = ["result": ["run_id": run.id, "request_id": request, "accepted": true] as [String: Any]]
if let previous = sent[request] { return previous == keys ? accepted : ["error": "request_conflict"] }
guard sent.count < MCPGuestKey.limit else { return ["error": "input_limit_reached"] }
guard !busy, !sending, !verifiedPrompt else { return ["error": "input_unavailable"] }
sending = true
defer { if self.run?.id == run.id { sending = false } }
try await type(keys, model: model, run: run)
sent[request] = keys
verifiedPrompt = keys == "PRINT 7\n"
return accepted
} catch { return ["error": error.localizedDescription] }
}
#if DEBUG
static func bootFixture(_ machine: MachineModel, romDirectory: URL,
use6309: Bool = CommandLine.arguments.contains("--basic-6309"),
composite: Bool = CommandLine.arguments.contains("--mcp-composite")) async throws {
var profile = ConfigurationProfile(name: "Isolated BASIC review")
profile.systemROM = romDirectory.appendingPathComponent("coco3.rom")
profile.media.rom = romDirectory.appendingPathComponent("disk11.rom")
var layout = CartridgeAssignments()
layout.slots[0].kind = .floppy
profile.media.cartridges = layout
profile.sound = false
profile.videoOutput = composite ? 1 : 0
profile.machine.use6309 = use6309
await machine.loadProfile(profile)
if let issue = machine.profileError { throw ProfileFailure.message(issue) }
machine.resume()
try await machine.waitForMCPFixturePrompt()
}
#endif
}