Skip to content

AI, fully local on your computer.

52.5 KB
Raw Blame
import { waitForEngineSpawns } from './spawn-gate'
import { engineChildEnv } from './engine-env'
import { spawn as nodeSpawn, type SpawnOptions } from 'node:child_process'
import { randomBytes } from 'node:crypto'
import { existsSync } from 'node:fs'
import { cpus } from 'node:os'
import { join } from 'node:path'
import net from 'node:net'
import { log } from '../logging'
import { perfMark, perfMs } from '../perf'
import { isDamagedFilesVerdict, verifyBinaryBeforeSpawn } from '../binary-verifier'
import type { HealthStatus } from './index'
import {
  EngineCannotRunError,
  EngineFilesUnreadableError,
  classifyLoadFailure,
  classifySpawnError,
  clearEngineProblemFor,
  describeLoadFailure,
  pathFreeSpawnError,
  reportEngineProblem,
  reportDamagedEngineFiles
} from './engine-load'

// Sidecar discovery + lifecycle (spec §6, §7.5). Locates the prebuilt `llama-server`
// binary on the drive and manages the child process that both the chat runtime
// (`LlamaRuntime`) and the real embedder (`E5Embedder`) drive over loopback HTTP.
//
// LOCALHOST-ONLY (non-negotiable): the server is always spawned with
// `--host 127.0.0.1`; we never bind `0.0.0.0` or a routable interface. The offline
// guard exempts loopback precisely so this local socket is allowed; a routable bind
// would expose local inference to the LAN and violate the spec.

/** Loopback host every sidecar binds + every loopback fetch targets. Never routable. */
export const LOOPBACK_HOST = '127.0.0.1'

/** Platform-specific `llama-server` executable name. */
export function llamaServerBinaryName(platform: NodeJS.Platform = process.platform): string {
  return platform === 'win32' ? 'llama-server.exe' : 'llama-server'
}

/** OS sub-directory key under `runtime/llama.cpp/` (spec §6 drive layout). */
export function llamaOsDir(platform: NodeJS.Platform = process.platform): string {
  if (platform === 'win32') return 'win'
  if (platform === 'darwin') return 'mac'
  return 'linux'
}

/** Directory that holds the platform sidecar binaries: `runtime/llama.cpp/<os>/`. */
export function llamaServerDir(rootPath: string, platform: NodeJS.Platform = process.platform): string {
  return join(rootPath, 'runtime', 'llama.cpp', llamaOsDir(platform))
}

/** Options for the sidecar binary resolvers. */
export interface ResolveBinOptions {
  /**
   * Whether this is a developer build (`!app.isPackaged`). The `HILBERTRAUM_LLAMA_BIN` /
   * `HILBERTRAUM_WHISPER_BIN` env overrides spawn an arbitrary, UNVERIFIED binary, so they
   * are honoured ONLY in dev (security audit M-5). In a packaged build the override is
   * ignored (and logged) and resolution falls back to the on-drive location. Defaults to
   * `false` (ignore the override) so a caller that forgets to pass it fails SAFE.
   */
  isDev?: boolean
}

/**
 * Resolve the `llama-server` binary, or `null` when it is absent. Pure I/O check (only
 * `existsSync`) so a "binary present?" decision has no surprises. A `HILBERTRAUM_LLAMA_BIN`
 * env override points at an explicit binary for DEV ONLY (still validated for existence);
 * in a packaged build it is ignored — see M-5 / `ResolveBinOptions`.
 */
export function resolveLlamaServerPath(
  rootPath: string,
  platform: NodeJS.Platform = process.platform,
  env: NodeJS.ProcessEnv = process.env,
  opts: ResolveBinOptions = {}
): string | null {
  const override = env.HILBERTRAUM_LLAMA_BIN?.trim()
  if (override) {
    if (opts.isDev) return existsSync(override) ? override : null
    // Packaged build: never spawn an env-supplied, unverified binary.
    log.warn('Ignoring HILBERTRAUM_LLAMA_BIN in a packaged build (dev-only override)')
  }
  const candidate = join(llamaServerDir(rootPath, platform), llamaServerBinaryName(platform))
  return existsSync(candidate) ? candidate : null
}

/**
 * Resolve the pure-CPU safety-net binary at `runtime/llama.cpp/<os>/cpu/` (shipped on
 * win/linux), or `null` when absent — the fallback ladder's rung 3 (architecture.md
 * GPU record §5.2). Deliberately ignores `HILBERTRAUM_LLAMA_BIN`: the override points at one
 * explicit binary and has no implied sibling.
 */
export function resolveCpuFallbackServerPath(
  rootPath: string,
  platform: NodeJS.Platform = process.platform
): string | null {
  const candidate = join(llamaServerDir(rootPath, platform), 'cpu', llamaServerBinaryName(platform))
  return existsSync(candidate) ? candidate : null
}

/** A sane default thread count: half the logical cores, at least 1. */
export function defaultThreadCount(): number {
  let count = 0
  try {
    count = cpus().length
  } catch {
    count = 0
  }
  return Math.max(1, Math.floor(count / 2) || 1)
}

/**
 * Ask the OS for a free TCP port on loopback by listening on port 0 then closing.
 * (`net.createServer().listen` is an inbound bind, not the outbound `connect` the
 * offline guard watches — so this stays loopback-only and guard-clean.)
 */
export function findFreePort(host: string = LOOPBACK_HOST): Promise<number> {
  return new Promise((resolve, reject) => {
    const srv = net.createServer()
    srv.once('error', reject)
    srv.listen(0, host, () => {
      const addr = srv.address()
      const port = addr && typeof addr === 'object' ? addr.port : 0
      srv.close(() => (port > 0 ? resolve(port) : reject(new Error('Could not find a free port'))))
    })
  })
}

const delay = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))

/**
 * Does a start-failure message describe a PORT-BIND race rather than a device/driver/model
 * fault (REL-1)? `findFreePort` binds port 0, reads the assigned port, then CLOSES the listener
 * before handing the number to `llama-server --port N`; in that TOCTOU window another process —
 * or a sibling in-app sidecar (chat + embedder + reranker + vision start near-simultaneously) —
 * can grab the port, so the child exits "address already in use". That is transient: the start
 * retries ONCE on a fresh port (`LlamaServer.start`), and the GPU ladder must NOT persist
 * `gpuAutoDisabled` for it (factory.ts). Matched against the start error message, which carries
 * the captured stderr tail. `EADDRINUSE` also matches the Windows `WSAEADDRINUSE`; the textual
 * Windows winsock message is matched explicitly.
 */
export function isBindRaceError(message: string): boolean {
  return /address already in use|EADDRINUSE|only one usage of each socket address/i.test(message)
}

/**
 * A spawn or fs error's errno code (`ENOENT`, `EACCES`, `EPERM`, …) — validated as one, never the
 * message: Node's spawn error carries the binary path in `message`, `syscall` and `path` and the
 * whole argv in `spawnargs`, an fs error its path (#712). Unlike `pathFreeSpawnError`, nothing
 * falls back to the message.
 */
export function errnoCode(err: unknown): string | null {
  const code = (err as { code?: unknown } | null | undefined)?.code
  return typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,31}$/.test(code) ? code : null
}

/** The suffix `stderrSuffix()` builds; the classifier below splits the tail off at it. */
const LAST_OUTPUT_MARKER = ' — last output: '

/** ANSI colour codes; llama.cpp prints its first line before `--log-colors off` is parsed (#515). */
const ANSI_RE = new RegExp(String.fromCharCode(27) + '\\[[0-9;]*m', 'g')
/** llama.cpp's per-line log prefix: elapsed time since start plus a one-letter level. */
const LOG_PREFIX_RE = /^\d+\.\d\d\.\d\d\d\.\d\d\d ([DIWE]) /

/**
 * The line of the ` — last output: …` tail that names the failure, or '' when there is no tail
 * (#515). In order: the FIRST error-level log line — llama.cpp prints the root cause first and
 * generic "failed to load" / "exiting due to …" lines after it, identically on every rung — then
 * the first unprefixed `error …` line (an argument error, followed by a usage screen), then the
 * last line. The per-process timestamp is stripped, so two processes failing the same way compare
 * equal; the last line alone never did (a colour reset, or a generic exit notice).
 */
function failureLine(message: string): string {
  const at = message.lastIndexOf(LAST_OUTPUT_MARKER)
  if (at < 0) return ''
  const lines = message
    .slice(at + LAST_OUTPUT_MARKER.length)
    .replace(ANSI_RE, '')
    .split('\n')
    .map((line) => line.trim())
    .filter((line) => line.length > 0)
  const strip = (line: string): string => line.replace(LOG_PREFIX_RE, '').trim()
  const error = lines.find((line) => LOG_PREFIX_RE.exec(line)?.[1] === 'E')
  if (error) return strip(error)
  const argError = lines.find((line) => /^error\b/i.test(line))
  if (argError) return argError
  return strip(lines.at(-1) ?? '')
}

/**
 * A comparable CLASS for a start failure (#312), for the ladder's CPU control probe: two rungs
 * that died the same way share a signature, so the ladder can tell "this MODEL will not load
 * anywhere" from "this DEVICE is broken" without reading llama.cpp's own vocabulary — which
 * drifts between builds, and in which a VRAM allocation failure reads exactly like an
 * unsupported-architecture failure.
 *
 * Covers the shapes this module throws — `launch` (spawn error), `exit:code N` /
 * `exit:signal S`, `timeout` (the health budget) — and `integrity`, the pre-spawn hash-mismatch
 * message it threw until #1012 round 6 (a mismatch is now the typed engine-files error) — plus
 * the failure line of the captured `— last output:` tail (`failureLine`: the first error-level
 * line, timestamp stripped — #515). Progress lines are deliberately ignored: two loads of the same
 * broken weight print different progress before the same error. Returns null for anything else, and the
 * ladder treats "no signature" as a device fault (its conservative default).
 */
export function failureSignature(reason: string): string | null {
  const exit = /^llama-server exited before becoming healthy \((code -?\d+|signal \S+?)\)/.exec(reason)
  const kind = exit
    ? `exit:${exit[1]}`
    : /^llama-server failed pre-spawn integrity verification/.test(reason)
      ? 'integrity'
      : /^llama-server failed to launch:/.test(reason)
        ? 'launch'
        : /^llama-server did not become healthy within \d+ms/.test(reason)
          ? 'timeout'
          : null
  if (kind === null) return null
  const tail = failureLine(reason)
  return tail ? `${kind} | ${tail}` : kind
}

/** A request abort signal plus a `clear()` that cancels its backing timeout timer. */
export interface CombinedAbort {
  /** Aborts on EITHER the per-request timeout OR the optional caller signal. */
  readonly signal: AbortSignal
  /**
   * Cancel the timeout timer (and detach the caller listener). Call in a `finally` once the
   * request settles, so an early completion — the norm — does not leave the timer pending for
   * its full `timeoutMs` (REL-4: a large ingestion runs hundreds of embed/rerank batches; an
   * unref'd-but-uncleared timer + `any`-listener per batch would otherwise pile up by the
   * thousand before they age out). Idempotent.
   */
  clear(): void
  /**
   * Cancel ONLY the timeout timer; the signal keeps following the caller until `clear()`. For a
   * deadline that bounds part of a request: the chat request's covers its response headers, while
   * a user Stop must still tear the open stream down (#594). Idempotent.
   */
  disarmTimeout(): void
}

/**
 * A request abort that fires on EITHER the per-request timeout OR an optional caller signal
 * (a user "Stop"). Used by the embedder + reranker + vision loopback fetches so a "Stop" during
 * query embedding / rerank / vision cancels promptly, not only on timeout (M-C5).
 *
 * Unlike a bare `AbortSignal.timeout`, the timer is OWNED here so the caller can `clear()` it the
 * instant the request settles (REL-4). The timeout still aborts with a `TimeoutError` DOMException
 * and is unref'd, so behaviour and quit-blocking are unchanged — only the lifetime is bounded.
 */
export function combineSignals(caller: AbortSignal | undefined, timeoutMs: number): CombinedAbort {
  const controller = new AbortController()
  const timer = setTimeout(
    () => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')),
    timeoutMs
  )
  // Don't let a pending request timeout keep the process alive (matches AbortSignal.timeout).
  ;(timer as { unref?: () => void }).unref?.()

  const onCallerAbort = (): void => controller.abort(caller!.reason)
  if (caller) {
    if (caller.aborted) controller.abort(caller.reason)
    else caller.addEventListener('abort', onCallerAbort, { once: true })
  }

  let cleared = false
  return {
    signal: controller.signal,
    clear(): void {
      if (cleared) return
      cleared = true
      clearTimeout(timer)
      caller?.removeEventListener('abort', onCallerAbort)
    },
    disarmTimeout(): void {
      clearTimeout(timer)
    }
  }
}

/**
 * #635: wait for a SHARED lazy start — or stop waiting the moment this caller's own signal aborts.
 * The start is never cancelled: other callers may share it (an import embeds with no signal while
 * a question waits on the same start), and a start that lands simply serves the next request. The
 * abandoned waiter rejects with `signal.reason`, the same value the request's `fetch` rejects with
 * once `combineSignals` hands it the caller's signal, so a Stop reads the same before and after the
 * start. A start that fails after every waiter left stays a handled rejection.
 *
 * A start that lands after every waiter left serves nobody yet. An owner with an idle timer must
 * arm it when the start settles, because the waiters' own settle-time arming ran while the start
 * was still in flight (vision and translation, #637).
 *
 * Only a lock or quit cancels the start itself (the sidecars' `startAbort`, #244).
 */
export function waitUnlessAborted<T>(start: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
  if (!signal) return start
  if (signal.aborted) {
    start.catch(() => undefined)
    return Promise.reject(signal.reason)
  }
  return new Promise<T>((resolve, reject) => {
    const onAbort = (): void => reject(signal.reason)
    signal.addEventListener('abort', onAbort, { once: true })
    start.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort))
  })
}

// ---- Injectable seams (so the server can be unit-tested with no real binary) -----

/** A readable stream surface — just enough to drain + capture the child's stderr. */
export interface ReadableLike {
  on(event: 'data', listener: (chunk: unknown) => void): unknown
  /** A stream error. Node emits one (`ENOTCONN`) on a piped stdio stream when the spawn itself
   *  failed before the pipes were opened — measured for a `cwd` of MAX_PATH or more on Windows
   *  (#787) — and an unhandled one is an uncaught exception in the main process. Every spawn site
   *  attaches its listener through `guardChildStdio` (#790). */
  on(event: 'error', listener: (err: unknown) => void): unknown
}

/** Minimal child-process surface we depend on (real `ChildProcess` satisfies it). */
export interface ChildProcessLike {
  readonly pid?: number
  readonly killed: boolean
  /** Present when spawned with a piped stdout (the GPU probe); absent otherwise. */
  readonly stdout?: ReadableLike | null
  /** Present when spawned with a piped stderr; absent in tests' fake children. */
  readonly stderr?: ReadableLike | null
  kill(signal?: NodeJS.Signals | number): boolean
  /** Detach the child from the parent's event loop so it can't keep Electron alive on quit
   *  (REL-8). Optional: test fakes omit it, so call sites use `child.unref?.()`. */
  unref?(): void
  on(event: string, listener: (...args: unknown[]) => void): unknown
  once(event: string, listener: (...args: unknown[]) => void): unknown
}

export type SpawnFn = (command: string, args: string[], options: SpawnOptions) => ChildProcessLike
export type FetchFn = typeof fetch

const realSpawn: SpawnFn = (command, args, options) => nodeSpawn(command, args, options)

// ---- Crash-exit child reap (full-audit 2026-07-11 CODE-11) ------------------------------
//
// A hard `uncaughtException` skips the graceful will-quit teardown (which stops + awaits
// every sidecar), and on Windows the children survive the parent's `process.exit(1)` — up
// to five co-resident llama-servers plus whisper-cli, holding GBs of RAM and loopback
// ports. Every sidecar spawn funnels through `LlamaServer` (chat / embedder / reranker /
// vision / translation) or `WhisperCliTranscriber`; both register their live child PIDs
// here so the crash handler (`main/index.ts`) can best-effort kill them synchronously
// before dying. Dependency-free and throw-safe: each kill is wrapped, and a PID that is
// already gone (or was recycled to a foreign process the kill then fails on) is skipped.

/**
 * The engine FAMILY a live sidecar child belongs to (F-32). Both families execute from a shared
 * per-family install dir (`runtime/llama.cpp/<os>/` and `runtime/whisper.cpp/<os>/`), so the
 * engine-installer's in-use guard partitions the registry by family: a `llama_cpp` (re-)install
 * is refused while ANY llama-server-backed child (chat/embedder/reranker/vision/translation) is
 * live, a `whisper_cpp` install while a transcription/dictation child runs. Structurally identical
 * to runtime-download's `EngineFamily`; kept local so this low-level module owns no upward import.
 */
export type SidecarFamily = 'llama_cpp' | 'whisper_cpp' | 'kiwix_tools'

const liveSidecarPids = new Map<number, SidecarFamily>()

/** Record a just-spawned sidecar child so a crash exit can reap it (CODE-11) and the engine
 *  installer can see its family is in use (F-32). */
export function registerSidecarChild(pid: number | undefined, family: SidecarFamily): void {
  if (typeof pid === 'number' && Number.isInteger(pid) && pid > 0) liveSidecarPids.set(pid, family)
}

/** Forget a sidecar child that exited/errored — on its own or via stop() (CODE-11). */
export function unregisterSidecarChild(pid: number | undefined): void {
  if (typeof pid === 'number') liveSidecarPids.delete(pid)
}

/** One end of a child's stdio, as far as `guardChildStdio` needs it (#790). */
export interface StdioErrorSource {
  on(event: 'error', listener: (err: unknown) => void): unknown
}

export type StdioStreamName = 'stdin' | 'stdout' | 'stderr'

/**
 * #790: give every piped stdio stream of a just-spawned child an `'error'` listener. Each spawn
 * site calls it right after `spawn()` returns, before any await; a stream that is not piped is
 * absent (null) and skipped.
 *
 * A piped stream can emit an `'error'` of its own, beside the child's. libuv opens the pipes partway
 * through `uv_spawn` on Windows (after the cwd and PATH steps, before the program lookup and
 * CreateProcessW); a spawn that fails before that leaves them unopened, and Node's first read on
 * one emits `ENOTCONN`, after the child's own ENOENT. Measured in Node 24.13 and Electron 43.8.3:
 * a `cwd` of MAX_PATH or more is the one trigger (#787; only kiwix-serve passes a cwd). A missing
 * binary or cwd, an over-long binary path, an elevation refusal and no PATH fail after the pipes
 * are open (EOF, no stream error); a damaged, empty, locked or over-long-command-line spawn throws
 * synchronously. With no listener, the stream's error is an uncaught exception: in the main process,
 * a crash.
 *
 * The child's own `'error'` / `'exit'` / `'close'` stay the owner of every outcome; the stream's
 * error is absorbed. On a child that did start (it has a PID) one is not known to happen; it is
 * logged with its code only (`errnoCode`, never the message), and `onStreamError` lets a site
 * whose answer IS that stream's content stop trusting it (the GPU probe's stdout).
 */
export function guardChildStdio(
  child: {
    readonly pid?: number
    readonly stdin?: StdioErrorSource | null
    readonly stdout?: StdioErrorSource | null
    readonly stderr?: StdioErrorSource | null
  },
  program: string,
  onStreamError?: (stream: StdioStreamName) => void
): void {
  for (const stream of ['stdin', 'stdout', 'stderr'] as const) {
    child[stream]?.on('error', (err: unknown) => {
      if (typeof child.pid === 'number') {
        log.warn('A pipe of a child process failed after it started; what it carries is no longer read', {
          program,
          stream,
          code: errnoCode(err)
        })
      }
      onStreamError?.(stream)
    })
  }
}

/** Read-only view of the currently registered sidecar PIDs — all families, or one (tests /
 *  diagnostics / the F-32 per-family in-use guard). */
export function registeredSidecarPids(family?: SidecarFamily): number[] {
  const pids: number[] = []
  for (const [pid, f] of liveSidecarPids) {
    if (!family || f === family) pids.push(pid)
  }
  return pids
}

/**
 * Best-effort synchronous kill of every still-registered sidecar child (CODE-11) — the
 * `uncaughtException` handler's last act before `process.exit(1)`. SIGKILL directly, no
 * polite-then-escalate: the parent is crashing NOW and no event loop remains to run a
 * grace timer. Each kill is wrapped so one dead/foreign PID never stops the loop; the
 * registry is cleared either way (the process is exiting). `kill` is a test seam.
 */
export function killRegisteredSidecarChildren(
  kill: (pid: number, signal: NodeJS.Signals) => unknown = (pid, signal) => process.kill(pid, signal)
): void {
  for (const pid of [...liveSidecarPids.keys()]) {
    try {
      kill(pid, 'SIGKILL')
    } catch {
      /* already gone / not ours — best-effort */
    }
    liveSidecarPids.delete(pid)
  }
}

/** What a server that died on its own (not via `stop()`) left behind. */
export interface UnexpectedExitInfo {
  exitCode: number | null
  exitSignal: string | null
  stderrTail: string
}

export interface LlamaServerOptions {
  binPath: string
  /** Absolute path to the GGUF weight file. */
  modelPath: string
  contextTokens: number
  /**
   * Physical batch size for prompt prefill — emitted as `--batch-size`/`--ubatch-size`
   * (RT-1, perf audit 2026-06-18). llama-server's 512 default chunks prefill into 512-token
   * pieces; the dominant time-to-first-token cost (skill fence + RAG excerpts + history, 3.5–15s
   * on CPU per Skills §17) is prefill, and a larger physical batch processes it in fewer passes
   * (and materially improves prompt-processing throughput on GPU). Only the CHAT sidecar sets
   * this; the embedder/reranker tune their own batch via extraArgs (reranker/llama.ts:96-115).
   */
  physicalBatchSize?: number
  /** Extra CLI args (e.g. `['--embedding']` for the embeddings server). */
  extraArgs?: string[]
  threads?: number
  /** Max time to wait for `/health` to report ready before failing the start. */
  healthTimeoutMs?: number
  /** Poll interval while waiting for health. */
  healthIntervalMs?: number
  host?: string
  /**
   * Fired when the child exits AFTER having become healthy, outside `stop()` — i.e. a
   * mid-session crash (driver crash, VRAM exhaustion). Start-time failures are NOT
   * reported here (they already throw from `start()`); the GPU crash auto-fallback
   * (architecture.md GPU record §5.3) hangs off this hook.
   */
  onUnexpectedExit?: (info: UnexpectedExitInfo) => void
  /**
   * Observe the child's stderr as it streams (issue #42 reopen). The stderr tail kept for
   * error messages is CAPPED (`STDERR_TAIL_MAX`), so a load-time line — e.g. llama.cpp's
   * `load_tensors: offloaded X/Y layers to GPU`, the only place the real offload outcome is
   * reported — can age out of it before `/health` turns ready; this hook sees every chunk.
   * Observability only: a throwing hook must never break the drain (guarded at the call site).
   */
  onStderrData?: (text: string) => void
  /**
   * Abort an IN-FLIGHT `start()` (#159 / BE-1): when this signal fires, the health wait
   * stops at its next poll iteration, the spawned child is killed via the normal `stop()`
   * path (no orphan), and `start()` rejects with an `AbortError` DOMException. Wired by the
   * translation sidecar so a lock/quit teardown no longer awaits the full spawn + health
   * window (up to `healthTimeoutMs` — 180 s by default) of a ~10 GB cold start it is about
   * to kill anyway. Optional: absent ⇒ behavior byte-identical for every other consumer.
   */
  startAbortSignal?: AbortSignal
  // Test seams:
  spawn?: SpawnFn
  /** #530: the OS the load-failure classifier reports (default `process.platform`). */
  platform?: NodeJS.Platform
  /** #530: the Windows System32 DLL check the classifier consults after a DLL-shaped exit code. */
  systemDllExists?: (dll: string) => boolean
  fetchImpl?: FetchFn
  findPort?: (host: string) => Promise<number>
  /** Grace period after SIGTERM before escalating to SIGKILL on stop() (default 2000ms). */
  killGraceMs?: number
}

/** The `AbortError` a signal-aborted `start()` rejects with (#159 / BE-1). */
export function isStartAbortError(err: unknown): boolean {
  return err instanceof DOMException && err.name === 'AbortError'
}

const DEFAULT_HEALTH_TIMEOUT_MS = 180_000
/**
 * Steady-state CAP for the readiness poll. RT-5: `waitForHealthy` backs off from
 * `INITIAL_HEALTH_INTERVAL_MS` up to this value rather than polling at a fixed 250 ms —
 * a sidecar that becomes ready quickly (a small model / warm page cache) is detected in
 * tens of ms instead of paying up to a full interval of dead time on every start / model
 * switch, while a slow multi-GB load still settles to this gentle cap instead of hammering
 * `/health`. The overall timeout budget (`healthTimeoutMs`) is unchanged.
 */
const DEFAULT_HEALTH_INTERVAL_MS = 250
/** First readiness-poll delay; the interval doubles each miss up to `healthIntervalMs`. */
const INITIAL_HEALTH_INTERVAL_MS = 50
const DEFAULT_KILL_GRACE_MS = 2_000
/** Per-probe timeout so a hung (accepts-but-never-responds) server can't stall the poll. */
const HEALTH_PROBE_TIMEOUT_MS = 3_000
/**
 * #530: how long a start failure waits for the child's `'close'` (stdio drained) after its
 * `'exit'` before reading the stderr tail. Node may emit `'exit'` while output is still in the
 * pipe — the reason the GPU probe resolves on `'close'` — and the tail now decides whether the
 * OS loader refused the program. A real child closes within a millisecond or two of exiting
 * (stderr arrived BEFORE exit in 40 of 40 measured loader failures); the bound only stops a pipe
 * held open by something else from stalling the start.
 */
const STDERR_DRAIN_MS = 100

/**
 * Owns one `llama-server` child process bound to loopback. Spawns it, waits for the
 * `/health` endpoint to report ready (with a timeout — never hangs the app on a wedged
 * server), exposes a loopback `fetch` against it, and kills it cleanly on `stop()`
 * (waiting for exit so no orphan survives). Both `LlamaRuntime` and `E5Embedder`
 * compose this; neither re-implements process hygiene.
 */
/** Keep only the last N chars of captured stderr (enough to show the failing reason). */
const STDERR_TAIL_MAX = 4000

/**
 * API-key redaction for sidecar stderr — two layers at DIFFERENT points, deliberately
 * (review 2026-08-18: an earlier design ran both per chunk, and the generic pass mangled
 * a chunk-split key's first half so the exact pass could never reassemble and remove the
 * remainder — a 44-hex-char fragment survived every pass while tests stayed green):
 *
 *  - `redactExactKey` runs at the DRAIN over a sliding hold-back window (below), so the
 *    known per-spawn key can never leave the drain — whole, chunk-split, or as an
 *    escaped prefix — toward the tail OR the `onStderrData` observer.
 *  - `redactSidecarSecrets` adds the generic `api…key <value>` form and runs ONCE at
 *    read time on tail-derived sinks (start-failure errors → `gpuLastError`, the audit
 *    trail, the app log, the support-log export), guarding a future pin that echoes some
 *    other secret shape. Only value-shaped tokens (≥8 chars) are candidates —
 *    llama-server's routine "api_keys: 1 keys loaded" count line and prose like
 *    "set LLAMA_API_KEY to …" must survive un-mangled.
 */
export function redactExactKey(text: string, key: string | null): string {
  return key ? text.split(key).join('[redacted]') : text
}

export function redactSidecarSecrets(text: string, key: string | null): string {
  const exact = redactExactKey(text, key)
  return exact.replace(/(api[-_]?key\S*[\s:=]+)(?!\[redacted\])(\S{8,})/gi, '$1[redacted]')
}

/**
 * Partial-line hold-back at the stderr drain: published text cannot be un-published, so
 * the drain publishes only COMPLETE lines and carries the trailing partial line until
 * its newline arrives. A chunk-split key always lives inside a partial line (hex holds
 * no newline), so by the time any line publishes, the exact-key pass has seen the whole
 * key and removed it — while complete lines (offload reports, bind errors) flow with
 * unchanged timing. Tail reads flush the carry (`redactedTail`), so error messages never
 * lose a final unterminated line. The cap force-publishes a pathological newline-less
 * stream so the carry cannot grow without bound.
 */
const STDERR_CARRY_MAX = 4096

export class LlamaServer {
  port: number | null = null
  /**
   * Per-spawn API key the child requires on every request (llama-server's `LLAMA_API_KEY`,
   * verified enforced on the pinned build). Hex so random material can never collide with
   * substring assertions on joined argv. Regenerated on each spawn; never leaves the main
   * process, never appears in argv (visible in process lists) or in `process.env` (which
   * every other child would inherit).
   */
  private apiKey: string | null = null
  private child: ChildProcessLike | null = null
  private spawnError: Error | null = null
  private exited = false
  private exitCode: number | null = null
  private exitSignal: string | null = null
  /**
   * #530: THIS spawn's `'close'` (every stdio stream drained). Per spawn, never shared: on the
   * bind-retry path a previous child's late `'close'` must not mark the retry's pipe as drained.
   */
  private closeState: { closed: boolean; promise: Promise<void> } | null = null
  /** Published (exact-key-redacted) stderr, capped at STDERR_TAIL_MAX. */
  private stderrTail = ''
  /** The held-back last ≤STDERR_REDACT_HOLDBACK chars — see the hold-back note above. */
  private stderrCarry = ''
  /** True once /health reported ready — gates the unexpected-exit hook. */
  private ready = false
  /** True while stop() is tearing the child down — an exit then is EXPECTED. */
  private stopping = false
  /**
   * The in-flight `start()` (REL-2, audit 2026-06-28). `this.child` alone can't gate a
   * single-flight start because it is assigned only AFTER the pre-spawn verify + `findPort`
   * resolve — two overlapping `start()` calls both passed the `if (this.child)` guard and
   * both spawned, the second orphaning the first (port + RAM, never stopped). Holding the
   * promise lets a concurrent caller share the one start AND wait for HEALTH, not just for
   * the child handle. Mirrors the latch in `e5.ts`, `reranker/llama.ts`, `vision/runtime.ts`.
   */
  private starting: Promise<void> | null = null

  private readonly host: string
  private readonly spawn: SpawnFn
  private readonly fetchImpl: FetchFn
  private readonly findPort: (host: string) => Promise<number>
  private readonly healthTimeoutMs: number
  private readonly healthIntervalMs: number
  private readonly killGraceMs: number

  constructor(private readonly opts: LlamaServerOptions) {
    this.host = opts.host ?? LOOPBACK_HOST
    this.spawn = opts.spawn ?? realSpawn
    this.fetchImpl = opts.fetchImpl ?? fetch
    this.findPort = opts.findPort ?? findFreePort
    this.healthTimeoutMs = opts.healthTimeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS
    this.healthIntervalMs = opts.healthIntervalMs ?? DEFAULT_HEALTH_INTERVAL_MS
    this.killGraceMs = opts.killGraceMs ?? DEFAULT_KILL_GRACE_MS
  }

  /** The CLI args used to launch the server. LOCALHOST-ONLY: `--host 127.0.0.1`. */
  buildArgs(port: number): string[] {
    const threads = this.opts.threads ?? defaultThreadCount()
    // RT-1: emit `--batch-size`/`--ubatch-size` only when a physical batch is requested (the
    // chat sidecar). Unset ⇒ no flags ⇒ llama-server's 512 default, leaving the embedder and
    // reranker (which set their own batch via extraArgs) untouched.
    const batchArgs =
      this.opts.physicalBatchSize != null
        ? [
            '--batch-size',
            String(this.opts.physicalBatchSize),
            '--ubatch-size',
            String(this.opts.physicalBatchSize)
          ]
        : []
    return [
      '--host',
      this.host,
      '--port',
      String(port),
      '--model',
      this.opts.modelPath,
      '--ctx-size',
      String(this.opts.contextTokens),
      '--threads',
      String(threads),
      // #515: stdout is NUL on Windows, which llama.cpp's `--log-colors auto` reads as a terminal,
      // so every stderr line came colour-coded into the tail that error strings, the audit trail,
      // the log export and the #312 failure signature are built from. On both b9849 and b11146.
      '--log-colors',
      'off',
      ...batchArgs,
      ...(this.opts.extraArgs ?? [])
    ]
  }

  baseUrl(): string {
    return `http://${this.host}:${this.port}`
  }

  /** Loopback fetch against this server (exempt from the offline guard by design).
   *  Sole HTTP chokepoint for every consumer — the per-spawn API key is injected here,
   *  so no call site can reach the child unauthenticated or needs to know the key. */
  fetch(path: string, init?: RequestInit): Promise<Response> {
    if (this.port == null) throw new Error('llama-server is not started')
    if (this.apiKey == null) return this.fetchImpl(`${this.baseUrl()}${path}`, init)
    // Headers-merge form: call sites pass plain object literals today, but a Headers
    // instance or entries array must keep working too.
    const headers = new Headers(init?.headers)
    headers.set('authorization', `Bearer ${this.apiKey}`)
    return this.fetchImpl(`${this.baseUrl()}${path}`, { ...init, headers })
  }

  /**
   * Spawn the server and block until it is healthy (or throw on timeout/crash). Single-flight
   * (REL-2): a second concurrent `start()` returns the in-flight start instead of spawning a
   * second child. An already-started server (latch cleared, child set) short-circuits.
   */
  async start(): Promise<void> {
    if (this.starting) return this.starting
    if (this.child) return
    const run = this.startWithBindRetry()
    this.starting = run
    try {
      await run
    } finally {
      // Clear on both success and failure: a failed start cleans up `this.child` (via
      // waitForHealthy → stop()), so a later retry must be able to begin a fresh start.
      this.starting = null
    }
  }

  /**
   * Run `doStart()`, retrying ONCE if the child died of a port-bind race (REL-1). The port
   * `findFreePort` hands us can be stolen between its listener close and the child's bind, so
   * one "address already in use" exit is transient — a fresh `doStart()` acquires a NEW free
   * port and almost always wins. The retry is bounded to one attempt: a second consecutive bind
   * failure (vanishingly unlikely) propagates so the ladder/caller still sees a real failure
   * rather than spinning. A non-bind start failure (timeout, bad model, spawn error) never
   * retries. `doStart()`'s failure path already clears `this.child`, so the retry begins clean.
   */
  private async startWithBindRetry(): Promise<void> {
    try {
      await this.doStart()
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err)
      if (!isBindRaceError(message)) throw err
      await this.doStart()
    }
  }

  private async doStart(): Promise<void> {
    const startT0 = performance.now()
    // #159 (BE-1): a teardown may have begun before this start ran at all — don't even spawn.
    this.throwIfStartAborted()
    // Re-hash the engine copy against its install marker BEFORE we spawn it (vuln-scan B;
    // since #1012 every file the marker records, not only the program). A packaged-build
    // tamper (`mismatch`) throws here, before any port/child is allocated, so the ladder
    // cleanly falls to the next rung / MockRuntime. Dev + legacy drives resolve skip-* and
    // proceed. Covers the chat runtime, embedder, reranker, and vision — every llama-server
    // spawn funnels through this method.
    // #516: an engine install replacing this folder holds spawns until its swap is over.
    await waitForEngineSpawns('llama_cpp')
    this.throwIfStartAborted()
    const verdict = await verifyBinaryBeforeSpawn(this.opts.binPath)
    if (isDamagedFilesVerdict(verdict)) {
      // #1012: a file of the copy is gone or changed (code review round 6: a changed one too — a copy cut
      // short, bit-rot, or a tamper, which the verifier's own log line records) — the engine's own files
      // are damaged, never the GPU or the model: the typed error the ladder walks on from (a Kit's `cpu/`
      // net has files of its own), and the verdict the "Install again" offer reads (a reinstall evicts the
      // cached verdict). A teardown that began meanwhile records none.
      this.throwIfStartAborted()
      throw reportDamagedEngineFiles('llama_cpp', this.opts.binPath, this.opts.platform)
    }
    if (verdict === 'unreadable') {
      // #1012 review R-2: a file could not be read just now — no verdict, and no evidence about the GPU
      // or the model for the ladder (`isEngineFilesUnreadableError`); the next attempt reads again.
      this.throwIfStartAborted()
      throw new EngineFilesUnreadableError('llama-server')
    }
    this.spawnError = null
    this.exited = false
    this.exitCode = null
    this.exitSignal = null
    this.stderrTail = ''
    this.stderrCarry = ''
    this.ready = false
    this.stopping = false
    this.port = await this.findPort(this.host)

    // stdin/stdout ignored; stderr PIPED. We never read stdout (health/chat go over HTTP),
    // so it is discarded — a piped-but-undrained stdout would fill the OS pipe buffer and
    // block a chatty `llama-server`. stderr is piped AND drained (below): draining prevents
    // the same deadlock, and the captured tail explains a failed start (e.g. a port
    // conflict's "bind: address already in use").
    // Per-spawn API key, delivered via CHILD-SCOPED env only: argv is banned (visible to
    // any same-user process list, and llama-server echoes resolved params to stderr), and
    // the parent's own `process.env` must stay clean (whisper-cli, tar, and the GPU probe
    // would inherit it). `engineChildEnv` copies process.env for THIS child only, without the
    // llama.cpp variables and config files of the host (#730).
    this.apiKey = randomBytes(32).toString('hex')
    let child: ChildProcessLike
    try {
      child = this.spawn(this.opts.binPath, this.buildArgs(this.port), {
        stdio: ['ignore', 'ignore', 'pipe'],
        // REL-7: never flash a console window on Windows for this high-frequency spawn (every
        // model start), matching the tar / transcriber / runtime-download spawns. No-op off Windows.
        windowsHide: true,
        env: engineChildEnv(this.opts.binPath, { LLAMA_API_KEY: this.apiKey })
      })
    } catch (err) {
      // #530: Node throws SYNCHRONOUSLY for spawn errors outside its short async list (EPERM,
      // `spawn UNKNOWN` — how an antivirus or application-control block often surfaces). That
      // escaped every caller unclassified; it now takes the async 'error' path's shape.
      this.port = null
      this.throwLaunchFailure(err)
    }
    // #790: a spawn that fails before its pipes are open also errors the stderr stream; the child's
    // own 'error' below fails the start, the stream's must not crash the main process.
    guardChildStdio(child, 'llama-server')
    this.child = child
    const closeState = { closed: false, promise: Promise.resolve() }
    closeState.promise = new Promise<void>((resolve) => {
      child.once('close', () => {
        closeState.closed = true
        resolve()
      })
    })
    this.closeState = closeState
    // CODE-11: make the child reachable by the crash-exit reap for as long as it lives.
    // F-32: every LlamaServer consumer (chat/embedder/reranker/vision/translation) runs the
    // shared `runtime/llama.cpp/<os>/` binary, so it registers under the llama_cpp family.
    registerSidecarChild(child.pid, 'llama_cpp')
    // A healthy server died on its own: tell the owner once (#656). The 'error' and 'exit' handlers
    // below both land here, and Node may emit 'exit' after 'error' for the same death; the
    // consumers' own guards hold only while their restart is in flight, so a second report could
    // audit, notify and (on the CPU path) stop the model a second time. The flag belongs to THIS
    // spawn: a late event from an earlier child (the bind retry) cannot use up the current one's.
    // Exits before health are start failures and throw from waitForHealthy; a stop() is expected.
    let exitReported = false
    const reportUnexpectedExit = (): void => {
      if (exitReported || !this.ready || this.stopping) return
      exitReported = true
      this.opts.onUnexpectedExit?.({
        exitCode: this.exitCode,
        exitSignal: this.exitSignal,
        stderrTail: this.redactedTail()
      })
    }
    child.stderr?.on('data', (chunk: unknown) => {
      // Exact-key redaction over carry + chunk, so the key can never leave the drain
      // toward the tail OR the observer — whole, chunk-split, or as a prefix (see the
      // partial-line hold-back note above). Re-passing carried text is safe: a partial
      // key is untouched by the exact match until it completes, and '[redacted]' never
      // reassembles into key material.
      const combined = redactExactKey(this.stderrCarry + String(chunk), this.apiKey)
      let cut = combined.lastIndexOf('\n') + 1 // 0 when no complete line yet
      if (combined.length - cut > STDERR_CARRY_MAX) cut = combined.length
      const published = combined.slice(0, cut)
      this.stderrCarry = combined.slice(cut)
      if (published.length > 0) {
        this.stderrTail = (this.stderrTail + published).slice(-STDERR_TAIL_MAX)
        try {
          this.opts.onStderrData?.(published)
        } catch {
          /* observability only — never break the stderr drain */
        }
      }
    })
    child.once('error', (err: unknown) => {
      // CODE-11: an 'error' means the process is gone (ECHILD/EPIPE) or never started
      // (spawn ENOENT) — either way there is nothing left for the crash reap to kill.
      unregisterSidecarChild(child.pid)
      this.spawnError = err instanceof Error ? err : new Error(String(err))
      // An 'error' after the process is up means it is gone (the OS reports it via
      // ECHILD, an EPIPE writing to a dead child) — possibly without ever emitting
      // 'exit'. Mark it exited — like the 'exit' handler does — so stop()'s grace race
      // resolves AND its SIGKILL escalation is correctly skipped (the child is already
      // dead). `stop()` clears `ready`, so we record the exit whenever it's during
      // teardown too; the unexpected-exit hook still only fires for a healthy server
      // dying on its own (the GPU crash auto-fallback path, architecture.md §5.3).
      // Start-time errors are consulted by waitForHealthy instead, so they don't set this.
      if ((this.ready || this.stopping) && !this.exited) {
        this.exited = true
        reportUnexpectedExit()
      }
    })
    child.once('exit', (code: unknown, signal: unknown) => {
      unregisterSidecarChild(child.pid) // CODE-11: dead — off the crash-reap kill list
      this.exited = true
      this.exitCode = typeof code === 'number' ? code : null
      this.exitSignal = typeof signal === 'string' ? signal : null
      // A crash AFTER the server was healthy (and not during stop()) is the
      // mid-generation failure path — report it so the GPU auto-fallback can react.
      reportUnexpectedExit()
    })

    await this.waitForHealthy()
    this.ready = true
    // #530: this program runs — a refusal recorded against THIS binary (an intermittent block that
    // went away) is stale. A refusal of another binary of the family stays.
    clearEngineProblemFor('llama_cpp', this.opts.binPath)
    // Wall-clock model load for THIS rung attempt: binary verify + spawn + first healthy
    // /health. The embedding flag separates the chat runtime from the E5 sidecar.
    perfMark('sidecar_healthy', {
      port: this.port,
      embedding: this.opts.extraArgs?.includes('--embedding') ?? false,
      ms: perfMs(startT0)
    })
  }

  /** The captured stderr for tail-derived sinks: flushes the held-back carry (so the
   *  final — usually most important — line is never missing) and applies the generic
   *  api-key pattern once, at read time. Exact-key removal already happened at the drain.
   *  Public: read-only diagnostics — a caller (e.g. `LlamaReranker.stderrTail()`) can confirm
   *  what a start actually logged (device offload, a fit spill) without this class growing a
   *  bespoke event for every such question. Diagnostics-only; no in-repo caller today. */
  redactedTail(): string {
    // #515: no colour codes in anything built from the tail (the first line is printed before
    // `--log-colors off` takes effect; an older binary may ignore the flag).
    return redactSidecarSecrets(this.stderrTail + this.stderrCarry, this.apiKey).replace(ANSI_RE, '')
  }

  /** #530: wait (bounded) for `'close'` after an early `'exit'`, so the tail is complete. */
  private async awaitStderrDrain(): Promise<void> {
    const state = this.closeState
    // A fake child with no stderr stream has nothing to drain.
    if (!state || state.closed || !this.child?.stderr) return
    let timer: ReturnType<typeof setTimeout> | undefined
    await Promise.race([state.promise, new Promise<void>((resolve) => (timer = setTimeout(resolve, STDERR_DRAIN_MS)))])
    clearTimeout(timer)
  }

  /**
   * #530: the program never started. On Windows a refusal by policy or security software comes
   * back as a spawn error (EPERM / UNKNOWN / EACCES) — the OS refused it, so the typed error and
   * the verdict. Anything else keeps the `failed to launch` shape, now WITHOUT the absolute path
   * Node puts in the message (`spawn <path> EACCES` reached document rows); the log keeps it.
   */
  private throwLaunchFailure(err: unknown): never {
    const failure = classifySpawnError(err, this.opts.platform)
    const raw = err instanceof Error ? err.message : String(err)
    if (failure) {
      const problem = { family: 'llama_cpp' as const, ...failure }
      log.warn('llama-server cannot run on this computer — the operating system refused to start it', {
        problem: describeLoadFailure(failure),
        binPath: this.opts.binPath,
        error: raw
      })
      reportEngineProblem(problem, this.opts.binPath)
      throw new EngineCannotRunError('llama-server', problem)
    }
    log.warn('llama-server failed to launch', { binPath: this.opts.binPath, error: raw })
    throw new Error(`llama-server failed to launch: ${pathFreeSpawnError(err)}`)
  }

  /**
   * #530: the OS loader refused the program (a missing system library, a system too old, a
   * missing Windows runtime, a code-integrity block) — record the session verdict and throw the
   * typed, path-free error instead of the generic exit message, so no caller reads it as a GPU,
   * model or memory fault. The raw tail (it holds the drive path) goes to the local log once.
   */
  private throwIfEngineCannotRun(): void {
    const tail = this.redactedTail()
    const failure = classifyLoadFailure({
      exitCode: this.exitCode,
      signal: this.exitSignal,
      stderr: tail,
      platform: this.opts.platform,
      systemDllExists: this.opts.systemDllExists
    })
    if (!failure) return
    const problem = { family: 'llama_cpp' as const, ...failure }
    log.warn('llama-server cannot run on this computer — the operating system refused to start it', {
      problem: describeLoadFailure(failure),
      binPath: this.opts.binPath,
      stderr: tail.trim().slice(-1000)
    })
    reportEngineProblem(problem, this.opts.binPath)
    throw new EngineCannotRunError('llama-server', problem)
  }

  /** A ` — last output: …` suffix from the captured stderr tail, or '' if none. */
  private stderrSuffix(): string {
    const tail = this.redactedTail().trim()
    return tail ? ` — last output: ${tail}` : ''
  }

  /** #159 (BE-1): abort an in-flight start — kill the child (normal stop path, no orphan)
   *  and reject with an AbortError. No-op when no signal is wired or it hasn't fired. */
  private throwIfStartAborted(): void {
    if (this.opts.startAbortSignal?.aborted) {
      throw new DOMException('llama-server start aborted', 'AbortError')
    }
  }

  private async waitForHealthy(): Promise<void> {
    const deadline = Date.now() + this.healthTimeoutMs
    // RT-5: start small and back off (×2) up to the configured cap, so a fast-ready
    // sidecar is picked up promptly instead of waiting a full fixed interval. Tests that
    // pass a tiny `healthIntervalMs` (e.g. 1) cap the initial too, keeping them fast.
    let interval = Math.min(INITIAL_HEALTH_INTERVAL_MS, this.healthIntervalMs)
    for (;;) {
      // #159 (BE-1): a lock/quit teardown fired the start-abort signal — stop waiting for
      // health, kill the child now, and reject the start. Checked per iteration, so the
      // worst-case abort latency is one poll interval + one bounded probe, not the
      // remaining health-timeout budget.
      if (this.opts.startAbortSignal?.aborted) {
        await this.stop()
        this.throwIfStartAborted()
      }
      if (this.spawnError) {
        const spawnError = this.spawnError
        await this.stop()
        this.throwLaunchFailure(spawnError)
      }
      if (this.exited) {
        // #530: the tail decides whether the OS loader refused the program, so let it drain.
        await this.awaitStderrDrain()
        this.child = null
        this.throwIfEngineCannotRun()
        const code = this.exitCode != null ? `code ${this.exitCode}` : `signal ${this.exitSignal}`
        // A port conflict or bad model makes llama-server exit immediately — the stderr
        // tail (e.g. "bind: address already in use") explains which.
        throw new Error(`llama-server exited before becoming healthy (${code})${this.stderrSuffix()}`)
      }
      const h = await this.health()
      if (h.healthy) return
      if (Date.now() >= deadline) {
        await this.stop()
        throw new Error(
          `llama-server did not become healthy within ${this.healthTimeoutMs}ms${this.stderrSuffix()}`
        )
      }
      await delay(interval)
      interval = Math.min(interval * 2, this.healthIntervalMs)
    }
  }

  /** Poll `/health`; ready → healthy. Failures/timeouts are reported, never thrown. */
  async health(): Promise<HealthStatus> {
    if (this.port == null) return { healthy: false, message: 'Not started', port: null }
    try {
      // Bound each probe: a server that accepts the socket but never responds would
      // otherwise hang the await and the deadline check below would never be reached.
      const res = await this.fetch('/health', {
        method: 'GET',
        signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS)
      })
      const healthy = res.ok
      return {
        healthy,
        port: this.port,
        message: healthy
          ? `llama-server ready on ${this.host}:${this.port}`
          : `llama-server not ready (HTTP ${res.status})`
      }
    } catch (err) {
      return {
        healthy: false,
        port: this.port,
        message: `Health check failed: ${err instanceof Error ? err.message : String(err)}`
      }
    }
  }

  /** Kill the child and wait for it to exit so no orphaned process survives. */
  async stop(): Promise<void> {
    this.stopping = true
    this.ready = false
    const child = this.child
    this.child = null
    this.port = null
    if (!child) return
    if (child.killed || this.exited) return

    // Resolve the wait on EITHER 'exit' or 'error': a child that died via 'error'
    // without ever emitting 'exit' (M-C1) would otherwise never settle this race.
    const exited = new Promise<void>((resolve) => {
      child.once('exit', () => resolve())
      child.once('error', () => resolve())
    })
    try {
      child.kill()
    } catch {
      // kill() itself threw (already-dead child, EPERM): do NOT bail early (M-C2) — a
      // surviving orphan would still hold VRAM + the port. Fall through to race the
      // grace window and attempt SIGKILL like the normal path.
    }
    // Force-kill if it ignores the polite signal, but never hang the quit path.
    // NB: gate on `this.exited` (set by the 'exit' listener), NOT `child.killed` —
    // `child.killed` becomes true the moment a signal is *sent* (line above), so it is
    // always true here and would skip the escalation entirely, leaving an orphan on a
    // process that ignored SIGTERM (mac/Linux; Windows kill() is already forceful).
    await Promise.race([exited, delay(this.killGraceMs)])
    if (!this.exited) {
      try {
        child.kill('SIGKILL')
      } catch {
        /* best-effort */
      }
    }
  }
}