Files
museion/Museion/ACPEngineClient.swift
AlexKucera 9ccfe83ec0
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
refactor(acp): land PR #199 audit fixes
Reviewer fanout (ponytail/security/general) over #199 found no
behavior defects. Apply the accepted non-behavioral findings:

- requestOutcome helper dedups the two outcome tasks; the two
  discarded wedge tasks drop their unread do/catch scaffolding
- awaitBounded doc names its real bound (window is green-world
  only; the RED-world watchdog is the fake's /bin/sleep 30 exit)
- send() gains a ponytail ceiling comment: queued sends are
  unbounded and a send racing close() writes onto a closed handle
  (benign, probe-verified) — bounded by the model's sequential
  sends; guard if a looping caller appears
- request() doc notes a timed-out request's bytes may still land
  on the wire (late replies dropped, ids never reused)

Suite 697/697 green post-change; format+lint clean.
2026-11-19 10:34:16 +01:00

379 lines
14 KiB
Swift

//
// 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.21.5 —
// 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.
/// brief-27: stdin writes ride a dedicated writer queue, so engine
/// backpressure (a full pipe) can stall a send but never a deadline,
/// Stop delivery, or teardown.
///
/// 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")
/// brief-27: stdin writes (and the stdin handle's own close) ride this
/// dedicated writer queue. The state queue NEVER touches the pipe — a
/// full pipe (hung engine not reading stdin) blocks only this writer, so
/// request deadlines, Stop delivery, and close()'s bookkeeping stay live
/// behind it. Serial = the wire order every send site already had.
private let writerQueue = DispatchQueue(label: "com.babylondreams.Museion.acp-client-writer")
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)?
/// Every notification (method + params), in wire order (#178: the
/// EngineTransport seam's message rail). Always set before start() — the
/// host does it from MainActor, and process.run() provides the
/// happens-before for the queue-confined reads below.
var onMessage: (@Sendable (String, JSONValue?) -> Void)?
/// #137 (S4, ADR-0014): one Hermes profile per LLM surface — the chat
/// engine keeps the default `museion`; pass engines spawn `-p museion-passN`.
init(binaryPath: String, profile: String = "museion") {
process.executableURL = URL(fileURLWithPath: binaryPath)
process.arguments = ["acp", "-p", profile]
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. Notifications (method + params) arrive on `onMessage`
/// in wire order; set it before calling.
func start() 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()
}
/// 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.
/// brief-27: a timed-out request's bytes may still reach the engine once
/// the child unblocks (the deadline fails the caller, never dequeues the
/// write) — phantom engine work only: ids are never reused and the
/// response path drops unknown ids, so a late reply can never misroute.
/// (No default arguments: the only caller is EngineHost, which rides the
/// seam — `EngineTransport.request`'s convenience owns the default shape.)
func request(_ method: String, params: JSONValue?, timeout: TimeInterval) 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
}
// brief-27: straight to the writer queue — never through the state
// queue, so a blocked write can't pin the deadline armed below.
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). Always called with
/// explicit params (session/cancel) — no default, same reasoning as request.
func notify(_ method: String, params: JSONValue?) {
let payload: [String: Any] = [
"jsonrpc": "2.0",
"method": method,
"params": params?.any ?? [String: Any](),
]
guard let raw = try? JSONSerialization.data(withJSONObject: payload) else { return }
// brief-27: writer queue, not the state queue (see request).
send(raw)
}
/// Graceful teardown: SIGTERM → 1 s grace → SIGKILL → reap, so the
/// child never outlives the app (same pattern as EngineProbe.terminateAndReap).
/// brief-27: bounded even when a stdin write is blocked on a full pipe —
/// bookkeeping syncs on the (I/O-free) state queue, and child
/// termination never queues behind the writer.
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()
// brief-27: the stdin WRITE handle closes on the writer queue — a
// blocked write may still own it (it unblocks only once the child's
// read end died, which the kill above just arranged); closing under
// a live write would race Foundation. The reader handles have no
// writers — their handlers are already off, so they close here.
writerQueue.async {
try? self.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.
/// brief-27: the write runs on the WRITER queue, never the state queue —
/// a blocked write here starves no deadline and no teardown.
private func send(_ data: Data) {
// ponytail: queued sends are unbounded, and a send racing close() writes
// onto a closed handle (benign — write throws a catchable CocoaError 512
// that try? swallows; probe-verified by two independent reviewers).
// Bounded today by MentorSessionModel's sequential-send discipline (a
// request is awaited before the next; worst case one prompt + one
// cancel). Add a closed/depth guard here if a looping or
// non-MainActor caller ever appears.
writerQueue.async {
var framed = Data(data)
framed.append(0x0A)
try? self.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() {
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) }
}
}
/// Buffer incoming bytes, split on \n, decode each line as one JSON-RPC message.
private func ingest(_ data: Data) {
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)
}
}
private func dispatch(_ object: [String: Any]) {
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) })
}
}
}