CI / ci (push) Canceled after 0s
Engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown, and the per-surface residency rules (resident chat engine; one-shot pass engines spawned per run, torn down at the verdict, ADR-0014) — moves out of MentorSessionModel into EngineHost behind the EngineTransport seam. The model keeps session + turn coordination and stays the only observable the panes see; ACPEngineClient becomes the seam's production adapter, and a scripted in-process engine (ScriptedEngine) becomes the second adapter — engine-behaviour tests (streaming, crash, cancel, restart, per-surface spawn) now run without child processes, retiring the zsh fake-server rigs from logic tests (#30 flake family). Exactly one real-process wire smoke per LLM surface survives (chat two-act + parameterized pass1/pass2): the held-turn cancel contract, hung-child SIGTERM teardown, handshake, streamed turn, crash, restart. One-shot teardown is structural (withOneShot closes at body end, every exit path); the one-shot slot is claimed before the first suspension so the at-most-one invariant holds across the spawn/handshake awaits. Suite: 652 executed / 652 passed / 0 failed (653 argument cases), counted from the xcresult; swiftformat idempotent, swiftlint clean on touched files. Closes #178
342 lines
12 KiB
Swift
342 lines
12 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.
|
|
///
|
|
/// 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)?
|
|
/// 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.
|
|
/// (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
|
|
}
|
|
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). 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 }
|
|
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() {
|
|
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) })
|
|
}
|
|
}
|
|
}
|