feat(acp): add M0 ACP bridge — engine child + mentor pane (fixes #14)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Spawn hermes acp -p museion over NDJSON JSON-RPC stdio via a hand-rolled thin client (no Swift SDK exists). The mentor debug pane streams replies, renders fix-card tool calls as structured cards (ADR-0006), cancels via session/cancel, tears down on quit (willTerminate), and surfaces a restart prompt on engine crash — never data loss. Version verify against state.json is advisory. Fake ACP server test double (zsh speaking real NDJSON) covers handshake, streaming + fix-card, drift, crash latch, cancel, teardown. 36/36 tests green; finish-audit fixes included (wired binaryPath, focus-loss teardown bug, double onCrash latch). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
c0b2cb0b93
commit
f21d3a6844
12 files changed
+1271
-10
No files matched your search
@@ -0,0 +1,331 @@
|
||||
//
|
||||
// ACPEngineClient.swift
|
||||
// Museion
|
||||
//
|
||||
// M0 ACP bridge (#14): a hand-rolled thin client speaking NDJSON JSON-RPC on
|
||||
// stdio to `hermes acp -p museion` (ponytail: no Swift ACP SDK exists;
|
||||
// revisit if one appears). Wire facts verified against adapter 0.20.6 —
|
||||
// one JSON message per \n-terminated line, stdout is the wire, stderr is
|
||||
// engine logs (never parsed for protocol state).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A decoded JSON value — Sendable all the way down, so wire payloads cross
|
||||
/// isolation boundaries as values, not `Any` boxes.
|
||||
nonisolated enum JSONValue: Sendable, Equatable {
|
||||
case object([String: JSONValue])
|
||||
case array([JSONValue])
|
||||
case string(String)
|
||||
case number(Double)
|
||||
case bool(Bool)
|
||||
case null
|
||||
}
|
||||
|
||||
nonisolated extension JSONValue {
|
||||
/// JSONSerialization bridge (decode side).
|
||||
init(_ any: Any) {
|
||||
switch any {
|
||||
case let object as [String: Any]:
|
||||
self = .object(object.mapValues { JSONValue($0) })
|
||||
case let array as [Any]:
|
||||
self = .array(array.map { JSONValue($0) })
|
||||
case let string as String:
|
||||
self = .string(string)
|
||||
case let number as NSNumber:
|
||||
// ponytail: NSNumber(bool) also answers Int/Double — bool must be tested first.
|
||||
if CFGetTypeID(number) == CFBooleanGetTypeID() {
|
||||
self = .bool(number.boolValue)
|
||||
} else {
|
||||
self = .number(number.doubleValue)
|
||||
}
|
||||
default:
|
||||
self = .null
|
||||
}
|
||||
}
|
||||
|
||||
/// JSONSerialization bridge (encode side).
|
||||
var any: Any {
|
||||
switch self {
|
||||
case let .object(object): object.mapValues { $0.any }
|
||||
case let .array(array): array.map(\.any)
|
||||
case let .string(string): string
|
||||
case let .number(number): number
|
||||
case let .bool(bool): bool
|
||||
case .null: NSNull()
|
||||
}
|
||||
}
|
||||
|
||||
var stringValue: String? {
|
||||
if case let .string(string) = self {
|
||||
return string
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var objectValue: [String: JSONValue]? {
|
||||
if case let .object(object) = self {
|
||||
return object
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Thin async ACP client: spawns the engine child, frames NDJSON on stdio,
|
||||
/// matches responses to pending requests, and delivers notifications in wire
|
||||
/// order. Requests are expected to be strictly sequential (initialize →
|
||||
/// session/new → prompt), matching the pane's usage.
|
||||
///
|
||||
/// Wire facts baked in (verified against adapter 0.20.6 + the acp SDK):
|
||||
/// - `session/cancel` is a JSON-RPC *notification* (interfaces.py — CancelNotification).
|
||||
/// - Responses carry camelCase keys (`agentInfo`, `sessionId`, `stopReason`).
|
||||
/// - Notifications discriminate updates on `update.sessionUpdate`.
|
||||
final nonisolated class ACPEngineClient: @unchecked Sendable {
|
||||
struct TransportError: Error, CustomStringConvertible {
|
||||
let message: String
|
||||
var description: String {
|
||||
message
|
||||
}
|
||||
}
|
||||
|
||||
private let process = Process()
|
||||
private let stdinPipe = Pipe()
|
||||
private let stdoutPipe = Pipe()
|
||||
private let stderrPipe = Pipe()
|
||||
/// All mutable state below is confined to this serial queue.
|
||||
private let queue = DispatchQueue(label: "com.babylondreams.Museion.acp-client")
|
||||
private var pending: [Int: CheckedContinuation<JSONValue?, any Error>] = [:]
|
||||
private var buffer = Data()
|
||||
private var currentID = 0
|
||||
private var closed = false
|
||||
private var started = false
|
||||
/// Latched on first fire — child-exit AND stdout-EOF both arrive for one
|
||||
/// crash; onCrash must surface exactly once.
|
||||
private var crashed = false
|
||||
|
||||
/// Fires when the child dies unexpectedly (crash or EOF) — never on an
|
||||
/// explicit `close()`, which is the app's own teardown.
|
||||
var onCrash: (@Sendable () -> Void)?
|
||||
/// stderr lines (engine logs) — surfaced for the restart prompt's details.
|
||||
var onStderrLine: (@Sendable (String) -> Void)?
|
||||
|
||||
init(binaryPath: String) {
|
||||
process.executableURL = URL(fileURLWithPath: binaryPath)
|
||||
process.arguments = ["acp", "-p", "museion"]
|
||||
process.standardInput = stdinPipe
|
||||
process.standardOutput = stdoutPipe
|
||||
process.standardError = stderrPipe
|
||||
}
|
||||
|
||||
/// The child's pid (tests verify teardown reaped it).
|
||||
var childProcessIdentifier: pid_t {
|
||||
process.processIdentifier
|
||||
}
|
||||
|
||||
/// Spawn the child. `onMessage` receives every notification (method +
|
||||
/// params), in wire order.
|
||||
func start(onMessage: @escaping @Sendable (_ method: String, _ params: JSONValue?) -> Void) throws {
|
||||
guard !started else { return }
|
||||
started = true
|
||||
// A crashed engine closes the pipe; ignoring SIGPIPE turns a kill-signal
|
||||
// into a plain EPIPE write error instead of taking the app down.
|
||||
signal(SIGPIPE, SIG_IGN)
|
||||
try process.run()
|
||||
process.terminationHandler = { [weak self] _ in
|
||||
self?.queue.async { self?.failAll("engine exited (code \(self?.process.terminationStatus ?? 0))") }
|
||||
}
|
||||
readStderr()
|
||||
readStdout(onMessage: onMessage)
|
||||
}
|
||||
|
||||
/// Send a JSON-RPC request and await its matching response result.
|
||||
/// A request that gets no answer within `timeout` fails — a hung engine
|
||||
/// must surface as an error (→ restart prompt), never an eternal await.
|
||||
func request(_ method: String, params: JSONValue? = nil, timeout: TimeInterval = 15) async throws -> JSONValue? {
|
||||
let id = queue.sync {
|
||||
currentID += 1
|
||||
return currentID
|
||||
}
|
||||
let payload: [String: Any] = [
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"method": method,
|
||||
"params": params?.any ?? [String: Any](),
|
||||
]
|
||||
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else {
|
||||
throw TransportError(message: "unencodable request: \(method)")
|
||||
}
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
let registered = queue.sync { () -> Bool in
|
||||
guard !closed else { return false }
|
||||
pending[id] = continuation
|
||||
return true
|
||||
}
|
||||
guard registered else {
|
||||
continuation.resume(throwing: TransportError(message: "engine closed before \(method)"))
|
||||
return
|
||||
}
|
||||
queue.async { self.send(raw) }
|
||||
// ponytail: deadline on the same serial queue — fires only if the
|
||||
// response hasn't already resumed and removed the continuation.
|
||||
queue.asyncAfter(deadline: .now() + timeout) {
|
||||
if let continuation = self.pending.removeValue(forKey: id) {
|
||||
continuation.resume(throwing: TransportError(message: "\(method) timed out after \(Int(timeout)) s"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a JSON-RPC notification (no id, no response).
|
||||
func notify(_ method: String, params: JSONValue? = nil) {
|
||||
let payload: [String: Any] = [
|
||||
"jsonrpc": "2.0",
|
||||
"method": method,
|
||||
"params": params?.any ?? [String: Any](),
|
||||
]
|
||||
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else { return }
|
||||
queue.async { self.send(raw) }
|
||||
}
|
||||
|
||||
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the child
|
||||
/// never outlives the app (same pattern as EngineProbe.terminateAndReap).
|
||||
func close() {
|
||||
let alreadyClosed = queue.sync {
|
||||
if closed {
|
||||
return true
|
||||
}
|
||||
closed = true
|
||||
for (_, continuation) in pending {
|
||||
continuation.resume(throwing: TransportError(message: "engine closed"))
|
||||
}
|
||||
pending.removeAll()
|
||||
return false
|
||||
}
|
||||
guard !alreadyClosed else { return }
|
||||
// Handlers off BEFORE closing handles — a readability handler firing on
|
||||
// a closed handle crashes Foundation.
|
||||
stdoutPipe.fileHandleForReading.readabilityHandler = nil
|
||||
stderrPipe.fileHandleForReading.readabilityHandler = nil
|
||||
if process.isRunning {
|
||||
process.terminate()
|
||||
let grace = Date().addingTimeInterval(1.0)
|
||||
while process.isRunning, Date() < grace {
|
||||
Thread.sleep(forTimeInterval: 0.01)
|
||||
}
|
||||
if process.isRunning {
|
||||
kill(process.processIdentifier, SIGKILL)
|
||||
}
|
||||
}
|
||||
process.waitUntilExit()
|
||||
try? stdinPipe.fileHandleForWriting.close()
|
||||
try? stdoutPipe.fileHandleForReading.close()
|
||||
try? stderrPipe.fileHandleForReading.close()
|
||||
}
|
||||
|
||||
// MARK: - Private (everything below runs on `queue` unless noted)
|
||||
|
||||
/// Frame and write one NDJSON line. A failed write (child gone) is dropped:
|
||||
/// the crash path owns the UX, not the send.
|
||||
private func send(_ data: Data) {
|
||||
var framed = Data(data)
|
||||
framed.append(0x0A)
|
||||
try? stdinPipe.fileHandleForWriting.write(contentsOf: framed)
|
||||
}
|
||||
|
||||
/// Fail every pending request and surface the crash — the one exit path
|
||||
/// for both an unexpected child exit and an stdout EOF. Latched: both
|
||||
/// signals arrive for one crash, onCrash fires exactly once.
|
||||
private func failAll(_ reason: String) {
|
||||
guard !closed, !crashed else { return }
|
||||
crashed = true
|
||||
for (_, continuation) in pending {
|
||||
continuation.resume(throwing: TransportError(message: reason))
|
||||
}
|
||||
pending.removeAll()
|
||||
onCrash?()
|
||||
}
|
||||
|
||||
private func readStderr() {
|
||||
stderrPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
|
||||
let data = handle.availableData
|
||||
guard !data.isEmpty else {
|
||||
handle.readabilityHandler = nil
|
||||
return
|
||||
}
|
||||
let text = String(data: data, encoding: .utf8) ?? ""
|
||||
for line in text.split(separator: "\n") {
|
||||
self?.onStderrLine?(String(line))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func readStdout(onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
|
||||
stdoutPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
|
||||
let data = handle.availableData
|
||||
guard !data.isEmpty else {
|
||||
handle.readabilityHandler = nil
|
||||
self?.queue.async { self?.failAll("engine stdout closed (EOF)") }
|
||||
return
|
||||
}
|
||||
self?.queue.async { self?.ingest(data, onMessage: onMessage) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffer incoming bytes, split on \n, decode each line as one JSON-RPC message.
|
||||
private func ingest(_ data: Data, onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
|
||||
buffer.append(data)
|
||||
// ponytail: 1 MB line cap — a corrupt/hostile engine streaming one
|
||||
// newline-free line would otherwise grow the buffer unbounded.
|
||||
if buffer.count > 1_048_576, buffer.firstIndex(of: 0x0A) == nil {
|
||||
buffer.removeAll()
|
||||
return
|
||||
}
|
||||
while let newline = buffer.firstIndex(of: 0x0A) {
|
||||
let line = buffer.subdata(in: buffer.startIndex ..< newline)
|
||||
buffer.removeSubrange(buffer.startIndex ... newline)
|
||||
guard !line.isEmpty,
|
||||
let json = try? JSONSerialization.jsonObject(with: line),
|
||||
let object = json as? [String: Any] else { continue }
|
||||
dispatch(object, onMessage: onMessage)
|
||||
}
|
||||
}
|
||||
|
||||
private func dispatch(_ object: [String: Any], onMessage: @escaping @Sendable (String, JSONValue?) -> Void) {
|
||||
let id = object["id"] as? Int
|
||||
let method = object["method"] as? String
|
||||
|
||||
// Server→client request (id + method): M0 has no permission/fs/terminal
|
||||
// handlers — answer -32601 so the engine never waits on us (the adapter
|
||||
// always offers a deny option; this is us taking it).
|
||||
if let id, let method {
|
||||
let reply: [String: Any] = [
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"error": ["code": -32601, "message": "Museion M0 handles no server requests"],
|
||||
]
|
||||
if let raw = try? JSONSerialization.data(withJSONObject: reply) {
|
||||
send(raw)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Response to one of our requests — already on the queue; direct access.
|
||||
if let id {
|
||||
guard let continuation = pending.removeValue(forKey: id) else { return }
|
||||
if let error = object["error"] as? [String: Any] {
|
||||
let code = (error["code"] as? Int) ?? -1
|
||||
// ponytail: truncated so a runaway engine can't balloon the restart prompt.
|
||||
let message = String(((error["message"] as? String) ?? "unknown error").prefix(500))
|
||||
continuation.resume(throwing: TransportError(message: "\(code): \(message)"))
|
||||
} else {
|
||||
continuation.resume(returning: object["result"].map { JSONValue($0) })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Notification.
|
||||
if let method {
|
||||
onMessage(method, object["params"].map { JSONValue($0) })
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user