Skip to content

AI, fully local on your computer.

43.4 KB
Raw Blame
import { totalmem } from 'node:os'
import type { ChatDepthMode } from '../../../shared/types'
import { promptCacheServerArgs } from '../../../shared/prompt-cache-rules'
import type {
  ChatMessage,
  HealthStatus,
  ModelRuntime,
  RuntimeChatOptions,
  RuntimeStartOptions
} from './index'
import type { RuntimeTimings } from './index'
import { LlamaServer, combineSignals, type LlamaServerOptions } from './sidecar'

// Real local inference (spec §3.2, §7.5). `LlamaRuntime` drops in behind
// the existing `ModelRuntime` interface: it spawns a `llama.cpp` `llama-server` sidecar
// bound to 127.0.0.1 (see `sidecar.ts`), then streams tokens from the server's
// OpenAI-compatible `/v1/chat/completions` endpoint. The server applies the model's
// chat template, so we send plain role/content messages — we never hand-roll Qwen's
// prompt format. Fully offline: the only socket is loopback to the sidecar.

/**
 * Args every CHAT sidecar gets (first verified against the llama.cpp b9585 source; the argv was
 * re-verified on b11146 under #512 and on the current pin b12110 under #729 — `model-manifests/runtime-sources.yaml`;
 * rationale in architecture.md "Chat & streaming"):
 *   --jinja                      the kwargs-driven thinking switch only acts in the
 *                                jinja template path (b9585 already defaulted to jinja;
 *                                pinned explicitly so the mechanism's precondition is
 *                                stated in code, not assumed from upstream defaults)
 *   --reasoning-format deepseek  thinking output streams as separate
 *                                `delta.reasoning_content` frames — never inline
 *                                `<think>` tags in `delta.content`
 *   -np 1                        ONE server slot instead of b9849's four (see below)
 * The E5 embedder composes `LlamaServer` directly and does not get these.
 */
/**
 * `-np 1` (issue #319, owner decision 2026-09-07): one server slot, not b9849's default of four
 * unified ones. CHAT ONLY — the embedder, the reranker, translation (`TRANSLATION_SLOT_ARGS`) and
 * vision (`VISION_SLOT_ARGS`) keep their own args; the latter two already pass the long form
 * `--parallel 1` for their own reasons.
 *
 * Why one slot is correct here: the app is single-user by design and already serialises every lane
 * that reaches this server — the model-slot arbiter (`analysis/model-slot-arbiter.ts`) hands the
 * one slot between chat and yielding builds, and the local API admits one external request with a
 * queue depth of one, answering 429 beyond that (`local-api/admission.ts`). The four slots were
 * never used in parallel, and they cost card memory exactly where the fit decides between full and
 * half speed.
 *
 * What `-np` does NOT change: the CONTEXT WINDOW. `--ctx-size` is the TOTAL cache size on both
 * settings, and each slot sees all of it. Measured on the pin, same model, same context, one thing
 * varied (`eval/results/hardware/i9-9900x-rtx-3090-24gb-128gb/leg7-baseline-q5km.stderr.log` vs
 * `leg1-np-1.stderr.log`):
 *   -np auto  →  n_parallel = 4, kv_unified = true,  n_seq_max = 4, n_ctx = n_ctx_seq = 8192,
 *                n_slots = 4, n_ctx_slot = 8192   ·  KV 512.00 MiB  ·  recurrent state 1,795.50 MiB
 *   -np 1     →  n_parallel = 1, kv_unified = false, n_seq_max = 1, n_ctx = n_ctx_seq = 8192,
 *                n_slots = 1, n_ctx_slot = 8192   ·  KV 512.00 MiB  ·  recurrent state   448.88 MiB
 * The KV (and, on Gemma, the sliding-window) cache is sized in CELLS from `--ctx-size` and is
 * counted ONCE either way; only the RECURRENT state is per-sequence, so it drops exactly 4×. That
 * is why the manifests' `estimated_context_cache_gib` terms were recomputed for one slot while
 * three of the seven did not move at all (`model-benchmarks.md` §6.6, 2026-09-07 amendment).
 *
 * What it bought, measured (#318 leg 1, RTX 3090, 27B Q5 at ctx 8192, the app's own rung-1a argv):
 * 62/66 layers at 30.4 tok/s → **66/66 at 51.0 tok/s**, the one variant that fully offloads Q5 on a
 * 24 GB card while keeping MTP. On the 8 GB card (leg 2) the four slots cost the 9B 440 MiB and the
 * fit missed a full offload by 133.
 *
 * Accepted cost (owner) — CORRECTED 2026-09-09 (issue #399). The original clause said the host-RAM
 * prompt cache RESTORES an evicted prefix, so the cost was a restore rather than a full re-prefill.
 * That measured false on 11 of our 14 chat models: recurrent state (the whole qwen3.5/qwen3.8 line)
 * and a sliding window (all four gemma4 manifests) both close the restore path, so the server saves
 * the conversation and then silently re-prefills it anyway. Three positive controls (dense qwen3,
 * qwen3moe, mistral3) did restore, and `-np 2` re-prefilled token for token even into a slot nothing
 * had ever touched — so no slot arrangement fixes it and the only lever is NOT EVICTING. The
 * decision to run one slot still stands (nothing here is caused by `-np 1`; four slots lose the
 * restore the same way). What changed instead: the model-slot arbiter waits before resuming a
 * parked deep-index build (#399 D3(a)), and the unreadable cache copy was switched off for the
 * affected families (#399 D5). Also measured: on a DOCUMENTS ask only the ~227-token system prefix
 * is ever reused anyway, so the length-proportional cost belongs to the plain-chat path alone.
 * Record: `model-benchmarks.md` §6.6 "2026-09-09 correction (#399)".
 *
 * REVERSED on b11146 (#512): qwen3.5 and gemma4 restore an evicted, extended conversation (48 of
 * ~1,700 tokens re-prefilled), so the family list is gone and every chat model gets the cache with
 * a RAM-scaled ceiling; `disable_prompt_cache: true` opts a manifest out
 * (`shared/prompt-cache-rules.ts`).
 */
/**
 * `-lv 4` (log verbosity): the pinned build prints its load log (`load_tensors: offloaded X/Y
 * layers to GPU`, the per-device model and KV buffer sizes) only from verbosity 4 up; the
 * default 3 prints none of it, which left the placement parser (benchmark.md "Your model")
 * with nothing to read (verified 2026-09-05 on the shipped binary: 3 → no lines, 4 → the
 * lines, 5 → also the `--fit` dry-run pass with 0.00 MiB buffers, which would double the
 * offload line). Load-time lines only; per-request logging is unchanged at 4.
 */
export const CHAT_SERVER_ARGS = ['--jinja', '--reasoning-format', 'deepseek', '-lv', '4', '-np', '1'] as const

/**
 * Physical-batch cap for the chat sidecar's prompt prefill (RT-1, perf audit 2026-06-18).
 * llama-server defaults `--batch-size`/`--ubatch-size` to 512, which chunks prefill — the
 * dominant time-to-first-token cost — into 512-token pieces. We raise it to the context size
 * but cap at 2048 (a low-risk start, validated on b9585, the pin at the time; the whole prompt
 * can't exceed n_ctx anyway, so `min(ctx, 2048)` never over-allocates the batch). Mirrors the
 * reranker, which raises its batch to the context for the same reason (reranker/llama.ts:96-115).
 */
export const CHAT_MAX_PHYSICAL_BATCH = 2048

/** Per-runtime overrides; mostly test seams forwarded to `LlamaServer`. */
export type LlamaRuntimeDeps = Pick<
  LlamaServerOptions,
  | 'spawn'
  | 'fetchImpl'
  | 'findPort'
  | 'threads'
  | 'healthTimeoutMs'
  | 'healthIntervalMs'
  | 'host'
  // GPU ladder: forces CPU via `extraArgs: ['--device','none']` — `--device none` is
  // the ONLY CPU-forcing mechanism, NEVER `-ngl` — and hooks mid-session crashes.
  | 'extraArgs'
  | 'onUnexpectedExit'
  // The placement parser's stderr feed (benchmark.md "Your model"): llama.cpp's load log is
  // the only place the real offload outcome is reported. Observability only.
  | 'onStderrData'
> & {
  binPath: string
  /** Total machine RAM for the prompt-cache ceiling (#512); defaults to `os.totalmem()`. */
  totalRamBytes?: number
}

/**
 * What an answer-depth mode means for the chat request (LOCKED — architecture.md
 * "Chat & streaming"):
 *
 *   fast      thinking off + temperature 0.7 + a modest token cap — quick answers
 *   balanced  thinking off, the server/model sampling defaults — the default mode,
 *             also used whenever `mode` is omitted (document answers, old callers)
 *   deep      thinking ON + temperature 0.6 (Qwen3's documented thinking-mode
 *             sampling), uncapped
 *
 * `enableThinking` is ALWAYS explicit: the server defaults to `--reasoning auto` (verified on
 * b9585; thinking still ON by default on b11146, #512, and on the b12110 pin, #729), which turns thinking ON for any
 * template that supports it (all four bundled Qwen3 models) — omitting the kwarg would make every
 * mode think.
 * Explicit `RuntimeChatOptions.maxTokens`/`temperature` win over these values.
 */
export interface ModeRequestParams {
  enableThinking: boolean
  temperature?: number
  maxTokens?: number
}

export const FAST_TEMPERATURE = 0.7
export const FAST_MAX_TOKENS = 1024
export const DEEP_TEMPERATURE = 0.6

/** Map an answer-depth mode to request parameters. Omitted/unknown = 'balanced'. */
export function requestParamsForMode(mode?: ChatDepthMode): ModeRequestParams {
  switch (mode) {
    case 'fast':
      return { enableThinking: false, temperature: FAST_TEMPERATURE, maxTokens: FAST_MAX_TOKENS }
    case 'deep':
      return { enableThinking: true, temperature: DEEP_TEMPERATURE }
    default:
      return { enableThinking: false }
  }
}

interface ChatCompletionChunk {
  choices?: Array<{
    delta?: { content?: string; reasoning_content?: string }
    /**
     * Why the model stopped THIS choice: 'stop' (EOS / a stop token — a complete reply),
     * 'length' (hit the token/context ceiling — the reply is CUT OFF mid-output), or null on
     * intermediate chunks. llama-server sends it on the final content chunk before `[DONE]`.
     */
    finish_reason?: string | null
  }>
  /**
   * llama-server's per-request timing block (#290/#291). It rides the `finish_reason` chunk
   * itself — pinned by the captured transcripts `tests/fixtures/chat-sse-timings-b9849.txt` (#298)
   * `chat-sse-timings-b11146.txt` (#512) and `chat-sse-timings-b12110.txt` (the current pin, #729). The reader still tolerates it on ANY
   * chunk, including one with no `choices`, so a future server that moves it keeps working.
   */
  timings?: RuntimeTimings
  /**
   * #598: a prompt-progress event, sent because the request asks for `return_progress` — one when
   * the slot starts (0 %) and one after every prompt batch. Its delta is `{role, content: null}`,
   * so it carries no text; the reader takes it as proof that prefill is advancing. Shape pinned by
   * `tests/fixtures/chat-sse-progress-b11146.txt`.
   */
  prompt_progress?: { total?: number; cache?: number; processed?: number; time_ms?: number }
}

/**
 * Parse one SSE line → content/reasoning deltas, a finish reason, a `[DONE]` sentinel, an
 * in-band ERROR frame, or nothing.
 *
 * F-02 (audit 2026-07-16): llama-server reports a mid-generation failure IN-BAND on the open
 * stream and then closes it without `[DONE]`. Two carrier shapes exist on b9849 (no capture of
 * either on b11146 or the current pin b12110) — the same pair the repo verified for the translation reader
 * (TA-4 M3, architecture.md "translation audit"): a `data: {"error":{message,type,…}}` frame and a
 * bare `error: {…}` SSE FIELD line. Both used to fall through as keep-alives (`{}`), so the reader ended
 * cleanly and a partial answer persisted as complete. Both now map to `streamError`. An
 * `error:` field line with an unparseable payload is still an error (a present error field is
 * never a keep-alive), surfaced content-free. RE-VERIFY both shapes against a captured smoke
 * transcript on every runtime pin bump (TS-3(a), BUILD_STATE §5 TS-3 inventory).
 */
function parseSseLine(line: string): {
  delta?: string
  reasoning?: string
  finishReason?: string
  done?: boolean
  streamError?: ChatStreamError
  /** A top-level `timings` object on this chunk (#290/#291) — read off ANY data chunk. */
  timings?: RuntimeTimings
  /** #598: a `prompt_progress` event — prefill advanced by a batch (or the slot just started). */
  progress?: boolean
} {
  const t = line.trim()
  // F-02: the bare `error: {…}` SSE field-line carrier (mirrors completion.ts's M3 handling).
  if (t.startsWith('error:')) {
    const data = t.slice('error:'.length).trim()
    if (!data) return { streamError: new ChatStreamError('', '') }
    try {
      const parsed = JSON.parse(data) as {
        error?: { message?: string; type?: string }
        message?: string
        type?: string
      }
      const e = parsed.error ?? parsed
      return { streamError: new ChatStreamError(e.message?.trim() ?? '', e.type?.trim() ?? '') }
    } catch {
      return { streamError: new ChatStreamError('', '') }
    }
  }
  if (!t.startsWith('data:')) return {}
  const data = t.slice(5).trim()
  if (data === '[DONE]') return { done: true }
  try {
    const json = JSON.parse(data) as ChatCompletionChunk & {
      error?: { message?: string; type?: string }
    }
    // F-02: the `data: {"error":{…}}` carrier — a top-level error object is terminal, never a delta.
    if (json.error != null && typeof json.error === 'object') {
      return {
        streamError: new ChatStreamError(
          json.error.message?.trim() ?? '',
          json.error.type?.trim() ?? ''
        )
      }
    }
    const choice = json.choices?.[0]
    const d = choice?.delta
    const out: {
      delta?: string
      reasoning?: string
      finishReason?: string
      timings?: RuntimeTimings
      progress?: boolean
    } = {}
    // #290/#291: the server's timing block. Read from whichever chunk carries it — with or
    // without `choices` — and let the reader keep the LAST one seen (llama-server's are cumulative
    // for the request, so the last is the complete one).
    if (json.timings != null && typeof json.timings === 'object') out.timings = json.timings
    if (json.prompt_progress != null && typeof json.prompt_progress === 'object') out.progress = true
    if (typeof d?.content === 'string' && d.content.length > 0) out.delta = d.content
    if (typeof d?.reasoning_content === 'string' && d.reasoning_content.length > 0) {
      out.reasoning = d.reasoning_content
    }
    // Only a non-null finish_reason is meaningful — intermediate chunks carry null.
    if (typeof choice?.finish_reason === 'string' && choice.finish_reason.length > 0) {
      out.finishReason = choice.finish_reason
    }
    return out
  } catch {
    // Ignore non-JSON keep-alives / partial frames; the next read completes them.
  }
  return {}
}

/** #594: does this SSE text hold anything but blank lines and comments (`:`, the keep-alive ping)?
 *  Shared with the translation reader (`readCompletionSSE`, #605). */
export function isModelOutput(text: string): boolean {
  return text.split('\n').some((line) => {
    const t = line.trim()
    return t !== '' && !t.startsWith(':')
  })
}

/**
 * CB-5 — the only cancellation source on the completion stream used to be the user's AbortSignal, so
 * a sidecar that *hangs* (GPU driver stall, deadlocked slot) left `readChatSSE` awaiting the next SSE
 * read forever: the conversation stayed wedged in `inFlightStreams` and every new send bounced. This
 * distinct error is raised by the idle watchdog when no chunk arrives within the budget; the chat IPC
 * maps it to the friendly `main.chat.runtimeUnresponsive` copy. Non-abort, so a regenerate turn's
 * prior reply is restored (it is NOT a user Stop) rather than lost.
 */
export class RuntimeUnresponsiveError extends Error {
  /** `what` names the signal that stopped (#598): model output, prompt progress, any byte, the headers. */
  constructor(idleMs: number, what = 'output') {
    super(`The model stopped responding (no ${what} for ${idleMs}ms).`)
    this.name = 'RuntimeUnresponsiveError'
  }
}

/** True when `err` is a {@link RuntimeUnresponsiveError} (the hung-sidecar idle timeout, CB-5). */
export function isRuntimeUnresponsiveError(err: unknown): boolean {
  return err instanceof RuntimeUnresponsiveError
}

/**
 * #600 — the connection to the chat sidecar broke while a request was in flight: the process died
 * (a crash, an OS or Task Manager kill) or the request reached a sidecar that is gone. undici
 * reports it as a bare `TypeError` ("fetch failed" before the headers, "terminated" once the body
 * streams), which used to reach the user as raw text. Measured in Electron 43.7.7 (undici 7.29.1)
 * by killing a b11146 server at each phase: a queued request → "fetch failed" (cause
 * `ECONNRESET`); a request in prefill or mid-stream → "terminated" (cause `ECONNRESET`); a new
 * request to the dead port → "fetch failed" (cause `ECONNREFUSED`); all within 3 ms of the kill.
 * A deliberate model stop or switch never reaches here — it ends the answer first (the model-stop
 * hook), so its signal is already aborted. The chat IPC maps this to `main.chat.connectionLost`.
 */
export class RuntimeConnectionLostError extends Error {
  /** `cause` is undici's socket error; its message and code ride the log line (structural, content-free). */
  constructor(cause?: unknown) {
    super(`The connection to the AI model was lost${describeSocketLoss(cause)}.`, cause === undefined ? undefined : { cause })
    this.name = 'RuntimeConnectionLostError'
  }
}

/** ` (terminated: ECONNRESET)` for undici's socket error; empty when there is none. */
function describeSocketLoss(cause: unknown): string {
  if (!(cause instanceof Error)) return ''
  const code = (cause.cause as { code?: unknown } | undefined)?.code
  return ` (${cause.message}${typeof code === 'string' ? ': ' + code : ''})`
}

/** True when `err` is a {@link RuntimeConnectionLostError} (#600). */
export function isRuntimeConnectionLostError(err: unknown): boolean {
  return err instanceof RuntimeConnectionLostError
}

/** undici's cause codes for a socket that closed or refused under a request (#600). */
const CONNECTION_LOSS_CODES = new Set(['ECONNRESET', 'ECONNREFUSED', 'ECONNABORTED', 'EPIPE', 'UND_ERR_SOCKET'])

/**
 * #600: does `err` mean the sidecar's socket went away? "terminated" is undici's error for a body
 * whose connection closed; "fetch failed" counts only with a socket-loss cause, so undici's own
 * timeouts (`UND_ERR_HEADERS_TIMEOUT`) and anything else keep their old path.
 */
function isConnectionLoss(err: unknown): boolean {
  if (!(err instanceof TypeError)) return false
  if (err.message === 'terminated') return true
  const code = (err.cause as { code?: unknown } | undefined)?.code
  return err.message === 'fetch failed' && typeof code === 'string' && CONNECTION_LOSS_CODES.has(code)
}

/**
 * F-02 (audit 2026-07-16) — a MID-STREAM in-band error frame on the open completion stream.
 * llama-server reports a mid-generation failure (slot error, context-shift refusal, grammar
 * failure, server-side-handled OOM) in-band and then closes the stream WITHOUT `[DONE]`;
 * `readChatSSE` throws this instead of ending cleanly, so a partially-generated answer can
 * never persist as if complete. `withChatStream` maps it to the friendly
 * `main.chat.streamError` copy; the raw reason goes to the local log only.
 *
 * `serverMessage`/`serverType` are upstream-STRUCTURAL only (the SEC-N3 posture shared with
 * `ChatRequestError`): the sidecar is our own loopback llama.cpp server and its error payloads
 * are a reason code/type, never user document/prompt content — re-verify on every runtime pin
 * bump (TS-3(a)).
 */
export class ChatStreamError extends Error {
  readonly serverMessage: string
  readonly serverType: string
  constructor(serverMessage: string, serverType: string) {
    super(`Chat stream failed${serverMessage ? `: ${serverMessage}` : ''}`)
    this.name = 'ChatStreamError'
    this.serverMessage = serverMessage
    this.serverType = serverType
  }
}

/** True when `err` is a {@link ChatStreamError} (an in-band mid-stream error frame, F-02). */
export function isChatStreamError(err: unknown): boolean {
  return err instanceof ChatStreamError
}

/**
 * The completion watchdog's budgets (CB-5). Before the FIRST chunk (token or reasoning delta) the
 * server is prefilling — legitimately slow on a long prompt — after which inter-chunk gaps are
 * milliseconds, so a much tighter STREAM budget means "wedged". Reasoning deltas count as chunks,
 * so a long "thinking" phase is safe.
 *
 * #598: prefill has TWO clocks, because every pinned build (b9849, b11146 and b12110 alike) writes an SSE
 * comment ping after every ~30 s of silence from their HTTP thread, which keeps pinging while the
 * compute loop is wedged (measured on b11146: one compute thread suspended for 151.7 s, a ping every
 * 30 s, `/health` 200 in 62 ms). So a ping proves the PROCESS is alive and nothing more:
 *   - `prefillMs`, the process clock — any byte, pings included, re-arms it. A frozen process
 *     sends nothing and ends here, as it did before #598.
 *   - `progressMs`, the compute clock — only a `prompt_progress` event (the request asks for
 *     `return_progress`: one at slot start, then one per prompt batch) or model output re-arms it.
 *     It runs only once the server has sent a progress event, so a server that sends none keeps
 *     the pre-#598 behaviour. Calibrated per batch of up to `CHAT_MAX_PHYSICAL_BATCH` (2048) tokens —
 *     re-calibrate if that cap changes, since one event comes per batch: one 2,015-token batch took
 *     up to 414 s for the 9B on the i7-8550U laptop in power-saver mode (`eval/results/hardware/
 *     i7-8550u-uhd-620-shared-8gb-laptop-16gb/leg0-*`), ~100 s on an i7-8700; later batches of a
 *     long prompt run slower than the first. The owner set 10 min (first 7, raised once those two
 *     facts were weighed: 7 min sat at the slowest batch measured, ≈421 s for a full one).
 */
export interface IdleWatchdog {
  /** Max silence before the first chunk: no bytes at all, pings included (the process clock, #598). */
  prefillMs: number
  /** Max time between prompt-progress events before the first chunk (the compute clock, #598). */
  progressMs: number
  /** Max wait between chunks once streaming has started. SSE comment pings do not count (#594). */
  streamMs: number
}
/**
 * Which clock ends the next read (#594, #598). Once output has started, the stream budget, less
 * the waiting time since the last output; before it, the process clock (re-armed by every read,
 * so always whole) or the compute clock, whichever runs out first. The compute clock counts once
 * the server has sent a progress event. Shared by `readChatSSE` and the translation reader
 * (`readCompletionSSE`, #605).
 */
export function nextReadBudget(
  idle: IdleWatchdog,
  s: { started: boolean; quietMs: number; sawProgress: boolean; stalledMs: number }
): { waitMs: number; budget: { ms: number; what: string } } {
  if (s.started) return { waitMs: idle.streamMs - s.quietMs, budget: { ms: idle.streamMs, what: 'output' } }
  if (s.sawProgress && idle.progressMs - s.stalledMs < idle.prefillMs) {
    return { waitMs: idle.progressMs - s.stalledMs, budget: { ms: idle.progressMs, what: 'prompt progress' } }
  }
  return { waitMs: idle.prefillMs, budget: { ms: idle.prefillMs, what: 'data at all (pings included)' } }
}
const PREFILL_IDLE_MS = 120_000
const PROGRESS_IDLE_MS = 600_000
const STREAM_IDLE_MS = 30_000
const DEFAULT_IDLE: IdleWatchdog = {
  prefillMs: PREFILL_IDLE_MS,
  progressMs: PROGRESS_IDLE_MS,
  streamMs: STREAM_IDLE_MS
}
/**
 * #594/#598: the wait for the response HEADERS (`LlamaRuntime.chatStream`), 180 s (owner). The
 * pinned builds send the headers when the slot STARTS, before any prompt batch is decoded (upstream
 * `server-context.cpp`; measured: 14–26 ms on b11146, 18 ms on b9849, 14–17 ms on b12110), so this wait is tokenisation
 * plus queueing for the one slot (`-np 1`). It is long only behind a cancelled request, whose
 * current batch must finish first — up to one batch, which can exceed this on a slow CPU (accepted).
 */
const HEADER_WAIT_MS = 180_000

/** An `AbortError`-named error so `isAbortError` treats a signal-driven read cancel as a clean stop. */
function abortReadError(): Error {
  const err = new Error('The stream read was aborted.')
  err.name = 'AbortError'
  return err
}

/**
 * Race one `reader.read()` against an idle timer (CB-5). Resolves with the read result, rejects with
 * `RuntimeUnresponsiveError` if `waitMs` elapses first (cancelling the reader), or rejects with the
 * read's own error. A user Stop wins first: an aborted `signal` rejects with an `AbortError` so the
 * partial persists exactly as today — a hang is NEVER converted to an abort or vice-versa. A `settled`
 * guard makes the first outcome authoritative (no double-settle). `budget` is the clock the error
 * names: `waitMs` is only what is LEFT of it after pings (#594, #598). The translation reader
 * (`readCompletionSSE`) races its reads the same way (#605).
 */
export function readWithIdleTimeout<T>(
  reader: ReadableStreamDefaultReader<T>,
  waitMs: number,
  budget: { ms: number; what: string },
  signal?: AbortSignal
): ReturnType<ReadableStreamDefaultReader<T>['read']> {
  return new Promise((resolve, reject) => {
    let settled = false
    const timer = setTimeout(() => {
      if (settled) return
      settled = true
      cleanup()
      // A wedged sidecar: cancel the reader so undici releases the socket, then surface the timeout.
      void reader.cancel().catch(() => {})
      reject(new RuntimeUnresponsiveError(budget.ms, budget.what))
    }, Math.max(0, waitMs))
    const onAbort = (): void => {
      if (settled) return
      settled = true
      cleanup()
      reject(abortReadError())
    }
    const cleanup = (): void => {
      clearTimeout(timer)
      signal?.removeEventListener('abort', onAbort)
    }
    if (signal?.aborted) {
      onAbort()
      return
    }
    signal?.addEventListener('abort', onAbort, { once: true })
    reader.read().then(
      (result) => {
        if (settled) return
        settled = true
        cleanup()
        resolve(result)
      },
      (err) => {
        if (settled) return
        settled = true
        cleanup()
        reject(err)
      }
    )
  })
}

/**
 * Parse a Server-Sent-Events stream of OpenAI chat-completion chunks, yielding each
 * answer-text delta. Reasoning deltas (`delta.reasoning_content`, Deep mode) are
 * reported through `onReasoning` and are NEVER yielded — the yielded stream stays
 * answer-only, so the locked streaming token contract is untouched. The final chunk's
 * `finish_reason` (e.g. 'length' when the reply was cut off at the token/context ceiling)
 * is reported through `onFinish` so callers can flag a truncated answer — it is never part
 * of the yielded content. Handles partial lines across reads, ignores keep-alive/comment
 * lines, and stops on the `[DONE]` sentinel. Honours `signal` so an aborted request stops
 * promptly and cancels the underlying reader.
 *
 * F-02 (audit 2026-07-16): an IN-BAND error frame (`data: {"error":{…}}` or a bare
 * `error: {…}` field line — the server's graceful mid-generation failure report, followed by
 * a close without `[DONE]`) throws a `ChatStreamError` instead of ending cleanly, so a
 * partially-generated answer can never persist as if complete.
 *
 * CB-5: each read is raced against a two-phase idle watchdog (`DEFAULT_IDLE`) so a HUNG sidecar
 * rejects with `RuntimeUnresponsiveError` instead of wedging the conversation forever. A user Stop
 * still wins first.
 *
 * #594: every pinned build sends an SSE comment ping (`:`) after every ~30 s of silence
 * (`--sse-ping-interval`, default 30 — b9849 too, which the #594 record had wrong; b12110 unchanged, #729). A ping is the
 * server's HTTP thread, not the model, so once the first chunk has landed it no longer resets the
 * stream budget: the budget counts the time spent WAITING since the last model output — any bytes
 * but blank lines and comments, a split line's start included — on the monotonic clock (time the
 * consumer spends between pulls never counts).
 *
 * #598: before the first chunk a ping re-arms only the process clock (`prefillMs`); the compute
 * clock (`progressMs`) counts waiting time since the last `prompt_progress` event or model output,
 * the same way, and runs once the server has sent a progress event (see `IdleWatchdog`).
 *
 * #290/#291: the server's top-level `timings` block is remembered from whichever chunk carries it
 * (the `finish_reason` chunk — captured in `tests/fixtures/chat-sse-timings-b9849.txt`, #298, and
 * `chat-sse-timings-b11146.txt`, #512; a chunk with no `choices` is tolerated too) and handed up
 * with the finish reason ONCE, at the `[DONE]` sentinel or the clean close. Deferring the hand-up
 * to the sentinel (instead of firing on the `finish_reason` chunk) is what lets a trailing
 * timings-only chunk still be attached; no consumer observes the difference —
 * every caller reads the captured value after the stream completes, and the finish chunk's delta is
 * empty. A stream that never reaches the sentinel (abort, error frame, idle watchdog) hands up
 * nothing, exactly as before.
 */
export async function* readChatSSE(
  body: ReadableStream<Uint8Array>,
  signal?: AbortSignal,
  onReasoning?: (delta: string) => void,
  onFinish?: (finishReason: string, timings?: RuntimeTimings) => void
): AsyncGenerator<string, void, unknown> {
  const reader = body.getReader()
  const decoder = new TextDecoder()
  let buffer = ''
  // The FIRST chunk gets the generous prefill budget; once any chunk (token OR reasoning delta) has
  // landed, later reads get the tighter stream budget. Re-armed per read, so a steady stream resets it.
  let sawChunk = false
  // #594: stream phase only — time spent waiting since the model's last output (pings don't count).
  let quietMs = 0
  // #598: prefill only — time spent waiting since the last progress event or model output, and
  // whether the server sends progress events at all (the compute clock runs only once it has).
  let stalledMs = 0
  let sawProgress = false
  // The finish reason + the last timings block seen, handed up together at the sentinel/close.
  let finishReason: string | undefined
  let timings: RuntimeTimings | undefined
  const finish = (): void => {
    if (finishReason) onFinish?.(finishReason, timings)
  }
  try {
    for (;;) {
      if (signal?.aborted) return
      // Which clock ends this read: the stream budget once a chunk landed; before that the process
      // clock (re-armed by every read, so always whole) or the compute clock, whichever runs out first.
      const { waitMs, budget } = nextReadBudget(DEFAULT_IDLE, { started: sawChunk, quietMs, sawProgress, stalledMs })
      const waitStart = performance.now() // monotonic: a wall-clock step must not eat the budget
      const { done, value } = await readWithIdleTimeout(reader, waitMs, budget, signal)
      if (done) break
      const waited = performance.now() - waitStart
      quietMs += waited
      stalledMs += waited
      buffer += decoder.decode(value, { stream: true })
      // Anything but a blank line or an SSE comment is the model's output (#594) — the start of
      // one split across reads included.
      if (isModelOutput(buffer)) quietMs = 0
      let nl: number
      while ((nl = buffer.indexOf('\n')) >= 0) {
        const line = buffer.slice(0, nl)
        buffer = buffer.slice(nl + 1)
        const r = parseSseLine(line)
        // F-02: an in-band error frame is TERMINAL — reject instead of ending cleanly, so a
        // partial can never masquerade as a finished reply. A user Stop still wins: a
        // signal-aborted read never reaches this loop, and consumers treat a race via
        // `isAbortError(err, signal)` (signal-aborted ⇒ abort semantics, partial kept).
        if (r.streamError) throw r.streamError
        // The finish reason rides the final content chunk, which arrives BEFORE `[DONE]`; it is
        // captured here and surfaced at the sentinel (with the timings) so a 'length' stop is
        // never dropped and a timings block on a later chunk is never missed.
        if (r.finishReason) finishReason = r.finishReason
        if (r.timings) timings = r.timings
        if (r.progress) sawProgress = true
        // #598: only a parsed progress event or real model output proves the compute loop moved —
        // never a role-only or timings-only frame, which a wedged server could still send.
        if (r.progress || r.delta || r.reasoning) stalledMs = 0
        if (r.done) {
          finish()
          return
        }
        // A reasoning delta counts as a live chunk (a long "thinking" phase must not trip the
        // watchdog); switch to the tighter inter-chunk budget once anything has streamed.
        if (r.reasoning) {
          sawChunk = true
          onReasoning?.(r.reasoning)
        }
        if (r.delta) {
          sawChunk = true
          yield r.delta
        }
      }
    }
    // Flush any final line the server sent without a trailing newline before closing.
    buffer += decoder.decode()
    const r = parseSseLine(buffer)
    // F-02: a server that dies mid-write can flush the error frame WITHOUT a trailing newline.
    if (r.streamError) throw r.streamError
    if (r.finishReason) finishReason = r.finishReason
    if (r.timings) timings = r.timings
    if (r.reasoning) onReasoning?.(r.reasoning)
    if (r.delta) yield r.delta
    // A clean close without `[DONE]` still hands the captured finish up (byte-identical to the
    // pre-#290 behaviour for a stream whose finish chunk was the last thing sent).
    finish()
  } finally {
    try {
      await reader.cancel()
    } catch {
      /* the stream may already be closed */
    }
  }
}

export class LlamaRuntime implements ModelRuntime {
  readonly modelId: string
  private readonly server: LlamaServer
  /** The `--ctx-size` this server was launched with — the real context window (§L0). */
  private readonly ctxTokens: number

  constructor(opts: RuntimeStartOptions, deps: LlamaRuntimeDeps) {
    this.modelId = opts.modelId
    this.ctxTokens = opts.contextTokens
    this.server = new LlamaServer({
      binPath: deps.binPath,
      modelPath: opts.modelPath,
      contextTokens: opts.contextTokens,
      physicalBatchSize: Math.min(opts.contextTokens, CHAT_MAX_PHYSICAL_BATCH),
      // #512: exactly one `--cache-ram` — the RAM-scaled ceiling, or 0 for a manifest that sets
      // `disable_prompt_cache: true` (rule in `shared/prompt-cache-rules.ts`). It sits between the
      // shared const and the ladder's rung args so a rung can still override what it needs to
      // (`--device none`).
      extraArgs: [
        ...CHAT_SERVER_ARGS,
        ...promptCacheServerArgs({
          disablePromptCache: opts.disablePromptCache,
          totalRamBytes: deps.totalRamBytes ?? totalmem()
        }),
        ...(deps.extraArgs ?? [])
      ],
      onUnexpectedExit: deps.onUnexpectedExit,
      onStderrData: deps.onStderrData,
      spawn: deps.spawn,
      fetchImpl: deps.fetchImpl,
      findPort: deps.findPort,
      threads: deps.threads,
      healthTimeoutMs: deps.healthTimeoutMs,
      healthIntervalMs: deps.healthIntervalMs,
      host: deps.host
    })
  }

  async start(): Promise<void> {
    await this.server.start()
  }

  async stop(): Promise<void> {
    await this.server.stop()
  }

  async health(): Promise<HealthStatus> {
    return this.server.health()
  }

  /** The launched context window (`--ctx-size`) — the budget chat/RAG assembly trims against (§L0). */
  contextWindow(): number {
    return this.ctxTokens
  }

  /**
   * Stream assistant tokens from the OpenAI-compatible endpoint. `messages` map
   * directly to role/content; `maxTokens`/`temperature` map to `max_tokens`/
   * `temperature` (explicit values win over the mode mapping). The answer-depth
   * `mode` maps to `chat_template_kwargs.enable_thinking` — per-request support verified
   * on b9585, on b11146 (#512) and on the b12110 pin (#729) — plus the per-mode sampling defaults; with
   * thinking on, reasoning deltas surface via `options.onReasoning`, never in the
   * yielded answer stream. Aborts the fetch + generator on `options.signal`.
   */
  async *chatStream(
    messages: ChatMessage[],
    options?: RuntimeChatOptions
  ): AsyncGenerator<string, void, unknown> {
    const mode = requestParamsForMode(options?.mode)
    const maxTokens = options?.maxTokens ?? mode.maxTokens
    const temperature = options?.temperature ?? mode.temperature
    const body = JSON.stringify({
      model: this.modelId,
      messages: messages.map((m) => ({ role: m.role, content: m.content })),
      stream: true,
      chat_template_kwargs: { enable_thinking: mode.enableThinking },
      // Reuse the slot's KV cache for the longest common token prefix across turns instead of
      // re-prefilling the whole prompt every request. We set this EXPLICITLY rather than relying
      // on the llama-server default (which has changed across releases): with a stable system
      // prefix — e.g. the skill fence bracketed in `system` for plain chat (skills §5/§22-A6) —
      // the injected fence is prefilled once and then cached, so toggling a skill on costs one
      // prefill, not one per turn. Loopback-only, no telemetry — purely a local compute hint.
      cache_prompt: true,
      // #598: a `prompt_progress` event at slot start and after every prompt batch (both pins) —
      // the only sign that prefill is advancing, which `readChatSSE`'s compute clock watches. The
      // events carry no text; the local API re-serialises tokens, so its clients never see them.
      return_progress: true,
      ...(maxTokens != null ? { max_tokens: maxTokens } : {}),
      ...(temperature != null ? { temperature } : {}),
      // Grammar-constrained decoding (D55): constrain the output to a JSON Schema. llama-server's
      // OpenAI-compatible endpoint compiles it to a GBNF grammar so the model can only emit a JSON
      // value matching the schema — the load-bearing guarantee the bank categorizer relies on (a
      // category outside the fixed enum is unrepresentable). Omitted ⇒ unconstrained free text.
      ...(options?.responseSchema
        ? {
            response_format: {
              type: 'json_schema',
              json_schema: {
                name: options.responseSchemaName ?? 'response',
                schema: options.responseSchema,
                strict: true
              }
            }
          }
        : {})
    })

    // #594: CB-5's watchdog starts at `res.body`, so a sidecar that took the request and never sent
    // its headers left the turn — and every busy signal it holds — waiting until undici's own
    // headers timeout ended it after 300 s (304.8 s measured in Electron 43.7.7) as a raw "fetch
    // failed". The headers get their own budget (`HEADER_WAIT_MS`); the request keeps following the
    // caller after they arrive, so a user Stop tears the stream down as before.
    const request = combineSignals(options?.signal, HEADER_WAIT_MS)
    try {
      let res: Response
      try {
        res = await this.server.fetch('/v1/chat/completions', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body,
          signal: request.signal
        })
      } catch (err) {
        // Only the deadline aborts the request while the caller's signal is clear; a Stop wins a tie.
        if (request.signal.aborted && !options?.signal?.aborted) {
          throw new RuntimeUnresponsiveError(HEADER_WAIT_MS, 'response headers')
        }
        // #600: the sidecar died under the request (or is gone) — a typed error, never raw text.
        if (!options?.signal?.aborted && isConnectionLoss(err)) throw new RuntimeConnectionLostError(err)
        throw err
      }
      if (!res.ok) {
        // Read the body for the REASON: llama-server returns a JSON error
        // (`{error:{message,type}}`) that explains the failure — most importantly
        // `exceed_context_size_error` when the prompt is larger than the model's context
        // window. Surfacing it turns an opaque "HTTP 400" into an actionable error and
        // drains the body so undici releases the connection. (readBody handles no-body.)
        // Still under the deadline: a stalled error body leaves only the status (#594).
        throw await chatRequestError(res)
      }
      if (!res.body) {
        throw new ChatRequestError(res.status, 'empty response body', '')
      }
      request.disarmTimeout() // the SSE body has CB-5's own watchdog
      try {
        yield* readChatSSE(res.body, options?.signal, options?.onReasoning, options?.onFinish)
      } catch (err) {
        // #600: the body's socket closed under the stream ("terminated"); a Stop wins a tie.
        if (!options?.signal?.aborted && isConnectionLoss(err)) throw new RuntimeConnectionLostError(err)
        throw err
      }
    } finally {
      request.clear()
    }
  }
}

/**
 * Cap on how much of a non-JSON error body we keep in the message.
 *
 * INVARIANT (SEC-N3, §22-M1): `serverMessage` must stay STRUCTURAL ONLY. The sidecar is our own
 * loopback llama.cpp server and its error bodies are upstream-structural (an HTTP status + a reason
 * code/type), never user document/prompt content — so this 500-char tail surfaced via chat-stream.ts
 * and doctasks/manager.ts carries nothing content-bearing. RE-VERIFY this on every runtime/llama.cpp
 * pin bump; if a future server ever echoed request content into an error body, sanitize the fallback
 * here to a fixed structural string + numeric status. Recorded as an accepted Info residual in
 * docs/security-model.md.
 */
const ERROR_BODY_MAX_CHARS = 500

/**
 * A failed `/v1/chat/completions` request, carrying the HTTP status plus the server's
 * own error `message`/`type` when it sent the OpenAI-style `{error:{…}}` body. The
 * message stays "Chat request failed: HTTP <status>" (callers/tests match on it) with the
 * server reason appended.
 */
export class ChatRequestError extends Error {
  readonly status: number
  readonly serverMessage: string
  readonly serverType: string
  constructor(status: number, serverMessage: string, serverType: string) {
    super(`Chat request failed: HTTP ${status}${serverMessage ? ` — ${serverMessage}` : ''}`)
    this.name = 'ChatRequestError'
    this.status = status
    this.serverMessage = serverMessage
    this.serverType = serverType
  }
}

/** Build a `ChatRequestError` from a non-ok Response, extracting the server's reason. */
async function chatRequestError(res: Response): Promise<ChatRequestError> {
  let serverMessage = ''
  let serverType = ''
  try {
    const raw = await res.text()
    if (raw) {
      try {
        const parsed = JSON.parse(raw) as { error?: { message?: string; type?: string } }
        serverMessage = parsed.error?.message?.trim() ?? ''
        serverType = parsed.error?.type?.trim() ?? ''
        if (!serverMessage) serverMessage = raw.slice(0, ERROR_BODY_MAX_CHARS)
      } catch {
        serverMessage = raw.slice(0, ERROR_BODY_MAX_CHARS)
      }
    }
  } catch {
    // Body unreadable (already consumed / stream error) — the status alone must do.
  }
  return new ChatRequestError(res.status, serverMessage, serverType)
}

/**
 * True when a chat request was rejected because the prompt exceeds the model's context
 * window (llama-server `exceed_context_size_error`, an HTTP 400). The doctask + chat
 * layers map this to a friendly "too large for this model" message instead of a raw code.
 */
export function isExceedContextError(err: unknown): boolean {
  if (!(err instanceof ChatRequestError)) return false
  if (err.serverType === 'exceed_context_size_error') return true
  return err.status === 400 && /context size|context window|n_ctx|exceed/i.test(err.serverMessage)
}

/** Factory mirroring `createMockRuntime`; selected by the runtime factory when a binary + weights exist. */
export function createLlamaRuntime(opts: RuntimeStartOptions, deps: LlamaRuntimeDeps): LlamaRuntime {
  return new LlamaRuntime(opts, deps)
}