AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { existsSync } from 'node:fs'
import { tMain } from '../i18n'
import type { EngineProblem, GpuDevice, PlacementDevice } from '../../../shared/types'
import type { SpeculativeDecoding } from '../../../shared/manifest'
import type {
ChatMessage,
HealthStatus,
ModelRuntime,
RuntimeBackend,
RuntimeChatOptions,
RuntimeFactory,
RuntimeStartOptions
} from './index'
import { createMockRuntime } from './mock'
import { createLlamaRuntime, RuntimeConnectionLostError } from './llama'
import { createPlacementParser, recordModelPlacement } from './placement'
import { probeGpuDevices } from './gpu'
import { displayDevice, primaryUsefulDevice } from '../../../shared/gpu-rules'
import { startModelPrefetch, type ModelPrefetch } from './prefetch'
import { isEngineCannotRunError, isEngineFilesUnreadableError, type EngineCannotRunError } from './engine-load'
import { isNextModelLoadSuppressed, recordModelLoadRead } from '../read-speed'
import {
failureSignature,
isBindRaceError,
resolveCpuFallbackServerPath,
resolveLlamaServerPath,
type UnexpectedExitInfo
} from './sidecar'
// Availability-aware runtime selector + the GPU start LADDER (architecture.md GPU
// record §5.2). The app MUST still launch —
// and the test suite MUST still pass — with zero model files, zero binaries, and zero
// GPUs, so the real `LlamaRuntime` is opt-in by availability (binary + weights present)
// and every GPU decision degrades automatically:
//
// rung 1a default binary + the MTP speculative-decoding flags (#182) — ONLY for a
// manifest that opts in AND a machine the probe proves can hold the model
// plus the draft head in one device's VRAM. Skipped, never failed, otherwise.
// rung 1 default binary, NO device args (b9585: ngl=auto + fit=on → VRAM-aware
// offload; on a GPU-less machine this IS CPU mode — the ladder ends here
// for almost everyone)
// rung 2 same binary, forced CPU (`--device none` is the ONLY CPU-forcing
// mechanism — NEVER pass `-ngl`)
// rung 3 pure-CPU safety-net binary (`runtime/llama.cpp/<os>/cpu/`, if present)
// rung 4 MockRuntime (the existing graceful-fallback rule —
// the app can never be *stuck*)
//
// `gpuMode: 'off'` (Settings) and `gpuAutoDisabled` (a previously detected problem)
// skip rung 1. A rung-1 failure reports through `onGpuFailure` so the caller persists
// `gpuAutoDisabled` + `gpuLastError` — no repeated GPU health timeouts on later starts —
// once a forced-CPU rung proves the model loads here (#312); every rung dying of the model
// instead names the MODEL (`onModelLoadFailure`) and latches it for the session (#372), so
// no repeated health timeouts on later starts of THAT model either.
// GPU state is INJECTED (read-callbacks), never read from the DB here — keeps the
// ladder pure and unit-testable with the existing fake seams.
/**
* The #109 hidden warm-up generation. `waitForHealthy` resolves as soon as llama-server
* answers `/health`, but the FIRST generation still pays a one-time prefill/graph warm-up
* that measured 6–8× the settled TTFT (10–30 s on CPU-only machines) — so "ready" wasn't
* ready. After a real rung comes up (and its backend label is set), the ladder runs one
* tiny content-free generation against the inner runtime and discards the output, so the
* user's real first prompt lands on a warmed path. The extra seconds live inside the
* existing "Starting…" state, where the user already expects to wait.
*
* Deliberate decisions (design record: architecture.md "First-answer warm-up hint (#39)"):
* - `inner.chatStream` is called DIRECTLY, so the #39 `served` flag does NOT flip: the
* real first prompt still pays the full system-prompt prefill (the warm-up shares no
* `cache_prompt` prefix with it), so the #39 warm-up hint stays armed as a safety net.
* - Thinking off (omitted mode = 'balanced' → `enable_thinking: false`), tiny cap,
* loopback-only, output discarded — never persisted, never audited as a chat.
* - A warm-up failure that is NOT a cancel never fails the start: the server IS healthy.
* A mid-warm-up crash still reports via `onUnexpectedExit` (§5.3 GPU auto-fallback).
*/
export const WARMUP_PROMPT = 'Hi'
export const WARMUP_MAX_TOKENS = 8
/**
* Overall cap on the warm-up window. The worst #109 measurement was ~28 s (9B, 16 GB
* CPU-only laptop), so 90 s is ~3× headroom for bigger models/slower machines while
* guaranteeing a pathological warm-up cannot dominate the start (the health wait itself
* budgets 180 s). On expiry the request is aborted, a warning is logged, and the start
* proceeds to ready — the cap trades a possibly-cold first prompt for a bounded start.
*/
const WARMUP_TIMEOUT_MS = 90_000
/**
* Server flags that switch ON the trained-in MTP draft head some GGUFs already carry
* (issue #182; measured evidence in model-benchmarks.md §9.4 "MTP speculative decoding",
* design record: architecture.md "MTP speculative decoding"). CODE-OWNED and constant —
* the manifest names a scheme, it never supplies arguments (see `SpeculativeDecoding`).
*
* `--spec-draft-n-max 2` is the measured pick: n=2 gave 77–91 % draft acceptance and
* +38–45 % decode; n=3/4 neither broke nor helped (acceptance falls to 64 % at n=4).
* Deliberately NOT included: the `--spec-draft-type-k/v q8_0` + `--cache-type-k/v q8_0`
* quartet — it recovers ~1.6 GiB of VRAM but quantizes the MAIN KV cache, whose long-context
* quality is unvalidated on our harness, and it still does not make Q6_K fit 24 GB.
*/
export const MTP_SERVER_ARGS: readonly string[] = ['--spec-type', 'draft-mtp', '--spec-draft-n-max', '2']
/**
* Free VRAM (MiB) an MTP start needs ON TOP of the weight file's own bytes, before the
* ladder will try rung 1a. Two measured components (§9.4, i9-9900X + RTX 3090, ctx 8192):
* a full-offload llama-server peaks ~1.3–1.4 GiB above the GGUF's size (KV + compute
* buffers), and the draft head plus its own KV costs ~2 GiB more. 3.5 GiB is that sum with
* no padding, so the guard reproduces the measured verdicts exactly: Q4 (15.9 GiB) and Q5
* (18.5 GiB) clear a 24 GB card, Q6_K (21.3 GiB) does NOT — which is precisely why the q6
* manifest does not opt in.
*
* The guard exists because llama.cpp's `--fit` does not FAIL when VRAM is short: it silently
* offloads fewer layers, so an unaffordable MTP start would look healthy while decoding at
* partial-offload speed (the issue-#42 class). A skipped rung 1a costs nothing; a silent
* partial offload costs everything the flag was added to buy.
*
* MEASURED AT FOUR SLOTS, kept unchanged at one (issue #319, owner decision 2026-09-07). Since the
* chat server passes `-np 1` the recurrent state an MTP start pays is 4× smaller (Q5 on the rig:
* 1,795.50 → 448.88 MiB, #318 leg 1), so 3.5 GiB is now MORE headroom than the rung needs. That is
* the safe direction — the guard refuses a rung it could have run, never the reverse — and the
* verdicts it was calibrated to reproduce (Q4/Q5 clear a 24 GB card, Q6_K does not) are unchanged.
* Re-deriving it for one slot would let Q6_K through on hardware nobody has measured it on.
*
* Not to be confused with the picker's `estimated_context_cache_gib` (see the two 27B manifests):
* this constant gates whether rung 1a is ATTEMPTED and covers the draft head's own weights + KV;
* that term is the context cache the fit estimate adds to EVERY start. Different consumers, no
* double count.
*/
const MTP_VRAM_HEADROOM_MB = 3584
/**
* Model ids whose speculative rung has been proven unviable ON THIS MACHINE, for the rest
* of the app session. Module-level and session-scoped on purpose (the `read-speed.ts`
* suppression idiom), never persisted: the reasons are hardware/driver state, and a wrong
* latch must not outlive the process.
*
* Without it, a machine where the flag fails would pay a doomed multi-GB model load on
* EVERY start before falling through to rung 1. Cleared by "Try GPU again" (the user
* explicitly asking for the accelerated path back) — see `tryGpuAgain`.
*/
const speculativeSuppressed = new Set<string>()
/** Latch this model's speculative rung off for the rest of the session. */
export function suppressSpeculative(modelId: string): void {
speculativeSuppressed.add(modelId)
}
/** True once {@link suppressSpeculative} has latched this model off this session. */
export function isSpeculativeSuppressed(modelId: string): boolean {
return speculativeSuppressed.has(modelId)
}
/** Re-arm every latched model (wired to "Try GPU again"; also the test reset). */
export function clearSpeculativeSuppression(): void {
speculativeSuppressed.clear()
}
/**
* #372: models the ladder has already blamed THIS SESSION (`onModelLoadFailure` fired — every
* rung died of the model, not the device), keyed by model id, valued by the reason it was
* blamed with. A second start of such a model goes straight to the notice + the rung-4 mock
* instead of re-walking the rungs: each rung can wait the full health timeout (180 s), so a
* repeat attempt on a corrupt or unsupported weight used to cost up to three timeouts before
* the user got the demo runtime again.
*
* Same idiom as {@link speculativeSuppressed} (#182): module-level, session-scoped, never
* persisted — a wrong latch must not outlive the process. It has its OWN clearing rule
* (architecture.md GPU record §5.2, #372): "Try GPU again" is about the graphics card and does
* NOT touch it; what re-arms a model is evidence that the FILE or the RUNTIME changed —
* "Verify checksum" on the model (a re-verified file is a new file), an in-app download of
* that model (`onModelInstalled`), a chat-engine install (a new binary may load what the old
* one could not — every latch clears), and an app restart (session-only anyway).
*
* Only a failure `failureSignature` recognises latches (a sidecar throw shape; never a bind
* race), so a transient port collision can never exile a good model for the whole session.
*/
const modelLoadLatched = new Map<string, string>()
/** Latch this model as unloadable for the rest of the session (the ladder's blame path). */
export function latchModelLoad(modelId: string, reason: string): void {
modelLoadLatched.set(modelId, reason)
}
/** The reason {@link latchModelLoad} recorded for this model this session, or null. */
export function modelLoadLatchReason(modelId: string): string | null {
return modelLoadLatched.get(modelId) ?? null
}
/** Re-arm ONE model — "Verify checksum" on it, or a completed in-app download of it. */
export function clearModelLoadLatch(modelId: string): void {
modelLoadLatched.delete(modelId)
}
/** Re-arm EVERY model — a chat-engine (runtime binary) install; also the test reset. */
export function clearModelLoadLatches(): void {
modelLoadLatched.clear()
}
/** GPU-ladder hooks; all optional — omitting them yields plain rung-1-only behavior. */
export interface GpuLadderDeps {
/** User intent from Settings ('auto' default). */
getGpuMode?: () => 'auto' | 'off'
/** The persisted auto-disable flag (a previously detected GPU problem). */
getGpuAutoDisabled?: () => boolean
/** Persist a rung-1 (GPU attempt) failure; must never throw. */
onGpuFailure?: (reason: string) => void
/**
* Probe used to label a rung-1 start 'gpu' vs 'cpu' (inject the session cache).
* `null` means UNKNOWN (its kill-timeout, #380; a refused program, #530; a crash or a failed
* spawn, #653) — NOT "no device". When it lists no device, a start whose own load log filed
* buffers on a graphics device is labelled gpu from that log instead (#653).
*/
probeDevices?: (binPath: string) => Promise<GpuDevice[] | null>
/** Resolve the rung-3 safety-net binary (default: `<os>/cpu/llama-server[.exe]`). */
resolveCpuBin?: (rootPath: string) => string | null
/**
* Fired when a runtime whose backend label is 'gpu' dies mid-session (§5.3). The
* caller persists the flags, restarts the model ONCE (the ladder then starts at
* rung 2), and surfaces the friendly compatibility-mode notice.
*/
onGpuCrash?: (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void
/**
* #182: fired INSTEAD of {@link onGpuCrash} when the runtime that died mid-session was
* the speculative rung. The GPU itself is not the suspect — the extra flags are — so the
* caller must NOT persist `gpuAutoDisabled` (that would exile the machine to CPU over an
* optional speed-up). The ladder has already latched the model off speculative for the
* session, so the caller's restart comes back on the plain GPU rung.
*/
onSpeculativeCrash?: (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void
/**
* #599: fired when a runtime that is NOT on the GPU dies mid-session (a CPU-mode crash, an OS
* kill). Nothing changes device here, so the caller restarts the model once per session
* (`createCpuCrashAutoRestart`) and stops it after a second crash. Before #599 this exit was
* dropped: every surface kept saying "running" and each later turn failed on the dead port.
*/
onCpuCrash?: (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void
}
/** Extra knobs `makeLlama` receives per rung. */
export interface LlamaRungOptions {
extraArgs: string[]
onUnexpectedExit: (info: UnexpectedExitInfo) => void
/** The placement parser's stderr feed for this attempt (benchmark.md "Your model"). */
onStderrData?: (text: string) => void
}
export interface RuntimeSelectionDeps {
/** Drive root used to resolve `runtime/llama.cpp/<os>/llama-server`. */
rootPath: string
/** The current machine's fingerprint, stamped on every placement record (optional). */
machineKey?: () => string | null
/** Dev build — gates the dev-only `HILBERTRAUM_LLAMA_BIN` override (M-5). Default false. */
isDev?: boolean
/** Resolve the sidecar binary (defaults to `resolveLlamaServerPath`). */
resolveBin?: (rootPath: string) => string | null
/** Check whether the model weight file exists (defaults to `existsSync`). */
modelExists?: (modelPath: string) => boolean
/** Build the real runtime (defaults to `createLlamaRuntime`). */
makeLlama?: (opts: RuntimeStartOptions, binPath: string, rung?: LlamaRungOptions) => ModelRuntime
/** Build the mock runtime (defaults to `createMockRuntime`). */
makeMock?: (opts: RuntimeStartOptions) => ModelRuntime
/** Hook fired with the chosen backend (used for logging). */
onSelect?: (kind: 'llama' | 'mock', opts: RuntimeStartOptions, reason: string) => void
/**
* Observability for the #109 warm-up generation; never affects control flow.
* 'done' = the warm-up completed, 'timeout' = the {@link WARMUP_TIMEOUT_MS} cap
* aborted it, 'failed' = it errored for a non-cancel reason — in every case the
* start proceeds to ready.
*/
onWarmup?: (opts: RuntimeStartOptions, event: 'done' | 'timeout' | 'failed', detail?: string) => void
/** Test seam: override the {@link WARMUP_TIMEOUT_MS} cap. */
warmupTimeoutMs?: number
/**
* Observability for the #114 concurrent prefetch; never affects control flow.
* 'started' = the reader began alongside the first rung's load, 'skipped' = the
* weights were just hashed (page-cache-warm — reading them again buys nothing),
* 'done' = the reader reached EOF before the load finished, 'aborted' = the load
* (or a stop) ended the window first — the normal outcome, 'failed' = a read
* error; the load proceeds unassisted.
*/
onPrefetch?: (
opts: RuntimeStartOptions,
event: 'started' | 'skipped' | 'done' | 'aborted' | 'failed',
detail?: string
) => void
/**
* #182 observability for the speculative rung; never affects control flow.
* 'enabled' = rung 1a was SPAWNED with the MTP flags (a 'failed' follows if it would not
* come up), 'skipped' = the precondition said no — reason in `detail`, nothing spawned,
* 'failed' = rung 1a would not start and the walk continues on the plain GPU rung,
* 'crashed' = a running MTP rung died mid-session. The last two latch the model off for
* the rest of the session.
*/
onSpeculative?: (
opts: RuntimeStartOptions,
event: 'enabled' | 'skipped' | 'failed' | 'crashed',
detail?: string
) => void
/**
* #312: fired once when EVERY real rung failed AND the forced-CPU rungs died the same way
* as the GPU rung — the model, not this machine's device, is the common cause. Nothing is
* persisted (`gpuAutoDisabled` stays untouched); the caller names the MODEL to the user.
* The walk still ends on the rung-4 mock, whose replies disclose that they are simulated.
*
* #372: ALSO fired when every rung failed and no GPU verdict was held at all — acceleration
* off, `gpuAutoDisabled` already persisted, or the GPU rung's failure was a bind race — so
* the model is named whatever the cause ("could not be loaded on this computer" stays
* accurate); `onGpuFailure` never fires on that path. And fired AGAIN, without any rung
* spawned, on every later start of a model this session already latched as unloadable
* ({@link modelLoadLatchReason}) — the user is told once more why the replies are simulated.
*/
onModelLoadFailure?: (opts: RuntimeStartOptions, reason: string) => void
/**
* #530: fired once when EVERY real rung failed because the operating system refused to start
* the engine program (`EngineCannotRunError` — a missing system library, a system too old, a
* missing Windows runtime, a code-integrity block). Neither the GPU nor the model is blamed:
* nothing is persisted, nothing is latched, and the walk ends on the rung-4 mock. The caller
* tells the user the ENGINE cannot run. (A rung the loader refused never counts in the #312
* comparison either — so a later rung that does start, a Windows Kit's `cpu/` build beside a
* damaged main folder, lands without `gpuAutoDisabled`.)
*/
onEngineCannotRun?: (opts: RuntimeStartOptions, problem: EngineProblem) => void
/**
* #1012 code review rounds 3–4: fired once when the pre-spawn check could not read one of the engine's
* files just now (`EngineFilesUnreadableError` — an antivirus scan holding it, say) on a rung, and no
* other rung failed in a way that is evidence (a failed MTP rung 1a, a bind race or an engine refusal
* is none). Nothing is blamed, persisted or latched; the walk ends on the rung-4 mock, and the caller
* tells the user to try again in a minute. The next start walks the whole ladder again.
*/
onEngineFilesUnreadable?: (opts: RuntimeStartOptions) => void
/** Test seam: override the prefetch reader (default {@link startModelPrefetch}). */
makePrefetch?: (paths: string[]) => ModelPrefetch
/** GPU ladder hooks. Omitted → defaults (gpuMode 'auto', no persistence). */
gpu?: GpuLadderDeps
}
interface Rung {
/** Reason fragment for onSelect/logging. */
label: string
binPath: string
extraArgs: string[]
/** True for the GPU attempts — the rung whose failure auto-disables GPU (rung 1). */
gpuAttempt: boolean
/**
* #182: rung 1a — the same binary and the same auto-offload as rung 1, plus
* {@link MTP_SERVER_ARGS}. Its failure is NEVER a GPU fault (rung 1 follows immediately
* and is the real GPU verdict), so it never persists `gpuAutoDisabled`.
*/
speculative?: boolean
}
/**
* The CODE-2 cancellation outcome (full-audit 2026-07-11): thrown out of a ladder
* `start()` that was cancelled by `stop()` (quit / "Lock now" / a manual model stop).
* Content-free; the auto-start path logs it, users never see it.
*/
function cancelledStartError(): Error {
return new Error('Model start was cancelled (stopped while loading)')
}
/**
* The `device_info` row with the largest `pick`, or null when the list is empty or every value
* is zero. Used by the #380 / #653 load-log label to name the device a start actually landed on.
* The shared `displayDevice` cannot be reused here: it takes `GpuDevice[]`, whose `totalMb` is
* non-null, while a `PlacementDevice`'s is nullable (the log need not have printed it).
*/
function largestPlacementRow(
rows: readonly PlacementDevice[],
pick: (d: PlacementDevice) => number
): PlacementDevice | null {
return rows.reduce<PlacementDevice | null>((best, d) => (pick(d) > (best ? pick(best) : 0) ? d : best), null)
}
/**
* The ladder runtime: presents one `ModelRuntime` to the `RuntimeManager`, walking the
* rungs inside `start()`. `backend`/`gpuName` expose where it landed (→ RuntimeStatus).
*/
class LadderRuntime implements ModelRuntime {
readonly modelId: string
backend: RuntimeBackend = 'cpu'
/**
* #599: the backend label above is final. Until then 'cpu' is only the default, so a rung-1
* server that dies before its GPU probe resolves must not count as a CPU-mode crash (it would
* restart on the same GPU rung and spend the model's one CPU restart).
*/
private labelled = false
gpuName: string | null = null
private inner: ModelRuntime | null = null
/** #39: flips on the first streamed chunk of the first real generation since start(). */
private served = false
/**
* Set by `stop()` (full-audit 2026-07-11 CODE-2): a quit / "Lock now" / model stop must
* not wait out the remaining rungs' health timeouts (up to ~9 min serial on a failing
* ladder). The flag aborts the walk at the next rung boundary; the in-flight rung's
* runtime is stopped directly (`startingInner`), which unblocks its `waitForHealthy`
* via the existing exit-check throw — never a bare timeout race, which would orphan the
* loading child (report §2.3). Permanent for this instance: the manager builds a fresh
* `LadderRuntime` per start, so a cancelled ladder is never restarted.
*/
private cancelled = false
/** The rung runtime whose `start()` is currently in flight (CODE-2), if any. */
private startingInner: ModelRuntime | null = null
/** The #114 concurrent prefetch riding the first rung's load window, if any. */
private prefetch: ModelPrefetch | null = null
constructor(
private readonly opts: RuntimeStartOptions,
private readonly rungs: Rung[],
private readonly deps: {
makeLlama: NonNullable<RuntimeSelectionDeps['makeLlama']>
/** The current machine's fingerprint for the placement record (services/performance.ts). */
machineKey?: () => string | null
makeMock: NonNullable<RuntimeSelectionDeps['makeMock']>
onSelect?: RuntimeSelectionDeps['onSelect']
onWarmup?: RuntimeSelectionDeps['onWarmup']
onSpeculative?: RuntimeSelectionDeps['onSpeculative']
onModelLoadFailure?: RuntimeSelectionDeps['onModelLoadFailure']
onEngineCannotRun?: RuntimeSelectionDeps['onEngineCannotRun']
onEngineFilesUnreadable?: RuntimeSelectionDeps['onEngineFilesUnreadable']
warmupTimeoutMs: number
onPrefetch?: RuntimeSelectionDeps['onPrefetch']
makePrefetch: NonNullable<RuntimeSelectionDeps['makePrefetch']>
gpu: GpuLadderDeps
}
) {
this.modelId = opts.modelId
}
async start(): Promise<void> {
let lastError: unknown = null
// #1012 code review round 3: the last failure that is not `unreadable` — a rung that could not read its
// engine files proved nothing, so it never decides the reason.
let lastEvidence: unknown = null
// #1012 code review round 4 — one rule: a walk in which ANY rung was skipped as `unreadable` latches
// nothing (no model latch, no persisted GPU failure, no MTP latch) and only reports. `sawEvidence`: a
// non-speculative rung failed in a way that says something about the model or the device (not a bind
// race, not an engine refusal) — it picks the model notice over the files-unreadable one.
let sawUnreadable = false
let sawEvidence = false
/** This walk's rung 1a latched MTP off — taken back if a later rung turns out unreadable. */
let speculativeLatched = false
// #312: a rung-1 failure is only a DEVICE verdict once the forced-CPU rungs have had
// their say, so it is held here instead of persisted on the spot. The forced-CPU rungs
// are the control probe: one of them starting proves the model loads on this machine
// (flush — today's behaviour, one rung later); all of them dying the SAME way as the
// GPU rung proves the model is the common cause (drop, blame the model). A cancelled
// walk simply never reaches either point — it blames nothing (CODE-2).
let pendingGpuFailure: { reason: string; signature: string | null } | null = null
/** #312: the last forced-CPU rung's failure class — the control side of the comparison. */
let cpuSignature: string | null = null
/**
* #530: the last rung the OS loader refused. Such a rung is no evidence about the GPU or the
* model, so it never enters the #312 comparison; when it is ALL the walk saw, the engine is
* named instead of either.
*/
let engineFailure: EngineCannotRunError | null = null
// #372: this model was already blamed this session — every rung died of the model. Do not
// pay the rung health timeouts again: name it once more and go straight to the rung-4
// mock, exactly the outcome the first walk reached, minus the wait. Checked AFTER the
// CODE-2 cancel point so a cancelled start still settles as cancelled, never as the mock.
const latched = modelLoadLatchReason(this.opts.modelId)
if (latched !== null) {
if (this.cancelled) throw cancelledStartError()
this.deps.onModelLoadFailure?.(this.opts, latched)
await this.fallBackToMock(`model latched as unloadable this session (#372): ${latched}`)
return
}
// #182: the #108 read sample and the #114 prefetch belong to the first rung we actually
// SPAWN, which is no longer the same thing as `rungs[0]`: a skipped speculative rung
// consumes index 0 without opening a load window, and gating on the index would have
// silently switched both off on every machine that skips it.
let attempted = 0
for (const rung of this.rungs) {
// CODE-2: cancelled between rungs — abort the walk instead of paying the next
// rung's health timeout.
if (this.cancelled) throw cancelledStartError()
// Kick the (cached) probe off BEFORE the server start so the two run
// concurrently — the model load dominates, so by the time the server is healthy
// the backend label is normally already known. Probing only after health would
// stall the first start by up to the probe's 10 s bound and mislabel a crash
// inside that window as 'cpu'.
//
// #380: the concurrent kick-off STAYS — but it is no longer the only guard against a
// wrong label. The unlock seams now settle this session's probe refresh BEFORE the
// auto-start is called, so on the path that produced the #330 mislabel the cached
// answer is already in hand here; and when the probe lists no device (unknown, or since
// #653 an empty answer), this start's own GPU buffers below still label it rather than "cpu".
const probe = this.deps.gpu.probeDevices ?? ((bin: string) => probeGpuDevices(bin))
// #182: the speculative rung is the ONE rung that must know the device BEFORE it
// spawns — its whole justification is measured on a fully offloaded GPU start, and
// llama.cpp answers a VRAM shortfall by silently offloading fewer layers rather than
// failing. So this await is deliberate, and deliberately narrow: it happens only for
// a manifest that opted in, the probe is the session-cached one (sub-second after the
// first call; its child is capped at 10 s, after the pre-spawn check of the engine's files,
// which since #1012 reads the whole copy: up to a few seconds on a USB 2 stick on the
// session's first call; never rejects), and the very next rung reuses the same cached
// answer. Every other model keeps the concurrent probe below untouched.
if (rung.speculative) {
const verdict = await this.speculativeVerdict(probe, rung.binPath)
// CODE-2: an await inside the walk is a cancellation point like any other.
if (this.cancelled) throw cancelledStartError()
if (!verdict.ok) {
this.deps.onSpeculative?.(this.opts, 'skipped', verdict.reason)
continue
}
}
const probePromise = rung.gpuAttempt
? probe(rung.binPath).catch(() => null)
: null
if (rung.speculative) this.deps.onSpeculative?.(this.opts, 'enabled')
// One placement reading per attempt (a retried rung must not sum two loads).
const placement = createPlacementParser()
const runtime = this.deps.makeLlama(this.opts, rung.binPath, {
extraArgs: rung.extraArgs,
onStderrData: placement.onStderrData,
// Only a crash of a runtime that actually landed on the GPU triggers the
// auto-fallback; a CPU-mode crash gets its own bounded restart (#599).
onUnexpectedExit: (info) => {
if (this.backend !== 'gpu') {
// An exit before the label settled keeps its pre-#599 path (the start's own handling).
if (this.labelled) this.deps.gpu.onCpuCrash?.(this.opts, info)
return
}
// #182: on the speculative rung the extra flags are the prime suspect, not the
// device — latch MTP off for the session and route to the speculative handler,
// which restarts on the plain GPU rung instead of exiling the machine to CPU.
if (rung.speculative) {
suppressSpeculative(this.opts.modelId)
this.deps.onSpeculative?.(this.opts, 'crashed', describeExit(info))
this.deps.gpu.onSpeculativeCrash?.(this.opts, info)
return
}
this.deps.gpu.onGpuCrash?.(this.opts, info)
}
})
// Visible to stop() so a cancel can reach the in-flight LlamaServer (CODE-2).
this.startingInner = runtime
// #114: concurrent sequential prefetch of the weights, riding the FIRST rung's load
// window (a later rung re-reads a file the failed attempt already pulled through the
// page cache — prefetching again buys nothing, same reasoning as the #108 sample
// rule below). Skipped when the install-state pass just hashed the file (the page
// cache is already warm — the same one-shot signal that suppresses the #108 sample,
// peeked here without consuming it). Evidence + design record: prefetch.ts header.
// Aborted the moment the load window ends (either way), on a CODE-2 stop, and never
// awaited — a prefetch failure means the load proceeds unassisted, nothing more.
const firstAttempt = attempted++ === 0
if (firstAttempt) {
if (isNextModelLoadSuppressed()) {
this.deps.onPrefetch?.(this.opts, 'skipped', 'weights just hashed — page-cache-warm')
} else {
const prefetch = this.deps.makePrefetch(this.opts.weightPaths ?? [this.opts.modelPath])
this.prefetch = prefetch
this.deps.onPrefetch?.(this.opts, 'started')
void prefetch.done.then((outcome) => this.deps.onPrefetch?.(this.opts, outcome))
}
}
const loadT0 = performance.now()
try {
await runtime.start()
} catch (err) {
this.abortPrefetch()
this.startingInner = null
lastError = err
if (!isEngineFilesUnreadableError(err)) lastEvidence = err
try {
await runtime.stop()
} catch {
/* best-effort cleanup; the start error is what matters */
}
// CODE-2: a start that failed because the cancel KILLED it must abort the walk —
// and must never be persisted as a GPU fault (the child was loading, not broken),
// so this check runs before the gpuAttempt branch below (which now HOLDS it — #312).
if (this.cancelled) throw cancelledStartError()
// #530: the OS refused to start the program — not the GPU's fault, not the model's, and not
// the MTP flags' (so no speculative latch either). Try the next rung: a Windows Kit's
// `cpu/` build has its own DLLs and may still run beside a damaged main folder.
if (isEngineCannotRunError(err)) {
engineFailure = err
continue
}
// #1012 review R-2: the pre-spawn check could not read an engine file just now (an antivirus
// holding it). No evidence about the GPU, the model or the MTP flags — nothing is held, persisted
// or latched; the next rung (or the next start) reads the files again.
if (isEngineFilesUnreadableError(err)) {
sawUnreadable = true
// Round 4: this walk latches nothing, so an MTP latch its rung 1a set is taken back.
if (speculativeLatched) {
speculativeSuppressed.delete(this.opts.modelId)
speculativeLatched = false
}
continue
}
const reason = err instanceof Error ? err.message : String(err)
// #182: rung 1a failing says nothing about the GPU — the plain GPU rung is next in
// the walk and IS the device verdict. Never persist `gpuAutoDisabled` here (an
// unsupported flag on an older runtime would otherwise exile the machine to CPU),
// but do latch the model off so later starts skip the doomed multi-GB load attempt.
if (rung.speculative) {
if (!sawUnreadable) {
suppressSpeculative(this.opts.modelId)
speculativeLatched = true
}
this.deps.onSpeculative?.(this.opts, 'failed', reason)
continue
}
// Round 4: what decides between the model notice and the files-unreadable one (a bind race is
// no evidence, nor is the engine refusal handled above). Round 6: only a CONTROL rung (a forced-CPU
// one) points at the model; a GPU rung that failed says nothing about it when its control did not run.
if (!rung.gpuAttempt && !isBindRaceError(reason)) sawEvidence = true
if (rung.gpuAttempt) {
// REL-1: a port-bind race is a transient TOCTOU collision, NOT a GPU/device fault
// (LlamaServer already retried once on a fresh port). Don't auto-disable GPU for the
// whole session over one unlucky port steal — only a genuine device/driver/model
// failure persists `gpuAutoDisabled`.
// #312: hold the rest for the forced-CPU control below; persisting here would
// blame the device for a model that cannot be loaded anywhere on this machine.
if (!isBindRaceError(reason)) pendingGpuFailure = { reason, signature: failureSignature(reason) }
} else {
// #312: the control's own failure — its class is what decides the held verdict.
cpuSignature = failureSignature(reason)
}
continue
}
this.abortPrefetch()
this.startingInner = null
// #108: the load window just read the model's files start-to-finish — bytes over
// elapsed is an honest effective media read speed, as a byproduct. FIRST rung of
// the walk only: a later rung re-reads a file the failed attempt already pulled
// through the page cache, so its number would be inflated. (A start whose
// install-state pass just hashed the file is suppressed inside read-speed.ts for
// the same page-cache reason — and since #392 so is a start over a weight hashed
// ANYWHERE this session, which is why the file set is passed too: the same
// `weightPaths ?? [modelPath]` expression the prefetch above uses, so the sample rule
// and the prefetch see one file set.) Excludes the #109 warm-up (which runs below) and
// never throws; a mock rung never reaches here. `weightBytes` covers a vision
// model's mmproj too — the bare modelPath stat under-counts it. Since #114 the
// window is prefetch-assisted — the figure remains the honest effective rate the
// user FELT for this load (this module's contract), now closer to what the medium
// can actually deliver.
if (firstAttempt) {
recordModelLoadRead(
this.opts.modelPath,
performance.now() - loadT0,
this.opts.modelId,
this.opts.weightBytes,
this.opts.weightPaths ?? [this.opts.modelPath]
)
}
// CODE-2: cancelled while THIS rung came up but the kill missed it (the pre-spawn
// window: verify/findPort run before `this.child` exists, and `doStart` resets the
// `stopping` flag) — stop the fresh server and abort rather than hand it back.
if (this.cancelled) {
try {
await runtime.stop()
} catch {
/* best-effort — the queued manager stop re-stops idempotently */
}
throw cancelledStartError()
}
// #312: this rung is accepted, and it is a forced-CPU one — the control probe says the
// model loads on this machine, so the held rung-1 failure WAS the device's. Persist it
// now (today's behaviour, one rung later) so later starts skip the GPU health timeout.
// After the CODE-2 check above on purpose: a cancelled walk still blames nothing. #1012 round 4:
// nor does a walk with a rung skipped as `unreadable` (a control rung that could not read its
// files proved nothing about the card).
if (!rung.gpuAttempt && pendingGpuFailure && !sawUnreadable) {
this.deps.gpu.onGpuFailure?.(pendingGpuFailure.reason)
}
pendingGpuFailure = null
this.inner = runtime
/** #653: why a GPU label came from this start's own log rather than the probe (onSelect). */
let labelNote = ''
if (probePromise) {
// The rung-1 binary auto-offloads when a device exists; a probe that LISTS one labels
// the start gpu and names it. Owner call 2 (#653): never demoted by the log — a start
// that offloads 0 layers beside a listed card still holds its compute buffer there and
// runs the prefill on it, so a driver crash can still hit it and §5.3 is its crash path.
const devices = await probePromise
if (devices !== null && devices.length > 0) {
this.backend = 'gpu'
// LABEL ONLY (PR #303 audit M8.2 / P5 residual): the device a reader may SHOW is the
// shared `displayDevice` one — the budget device (the largest USEFUL card), else the
// largest device that does not look integrated even when it is under the usable gate
// (a 4 GB card; until #321 lowered the gate to 5,120 this also caught every 6 GB laptop
// card, which the Vulkan backend reports at 5,7xx–5,9xx MiB), else the first
// listed. On a hybrid [iGPU, dGPU] box `devices[0]` named the iGPU while the model
// actually ran on the dGPU — and on a hybrid [iGPU, SMALL dGPU] box the old fallback did
// the same, because nothing was "useful". Rung selection, `--fit` and the "never -ngl"
// policy are untouched — and no `--device` is passed to steer them (#320, decided
// 2026-09-07): on b9849 the fit does NOT spread layers over every listed device. It drops
// the integrated one BY TYPE before the filling pass, measured on both hybrid machines
// (`eval/results/hardware/i9-14900k-rtx-3080-ti-12gb-64gb/leg5-baseline.*` — both devices
// in `device_info`, then "using device Vulkan0" only; `…/ryzen-7-5800h-rtx-3060-laptop-
// 6gb-14gb/leg5-device-landing.comment.md` — iGPU listed FIRST, every buffer on the RTX,
// the fit's own "device 0" was Vulkan1), so an app-side `--device` would change nothing
// and would break the ladder's "`--device none` is the only device argument" contract.
this.gpuName = displayDevice(devices)?.device.name ?? null
} else if (placement.holdsGpuBuffers()) {
// #380 / #653: the probe gave no answer (`null`: its 10 s bound under this very load —
// on the #330 round trip a `--list-devices` that takes 1.07 s idle took 7.7 s beside the
// weight upload —, a crash, a refused program) or an EMPTY one, yet this start's own log
// filed buffers on a device its `device_info` block lists as a graphics card (the parser's
// `holdsGpuBuffers`). That is first-hand evidence about THIS start, so
// it labels it, rather than call a card-speed start "cpu" and push that verdict into
// the chat header, Diagnostics, the persisted `ModelPlacement`, the #322 speed identity,
// the #473 chat share and the §5.3 crash auto-fallback gate. Owner call 1 (#653): the
// evidence is a GPU BUFFER, never the offload line, which b9849 and b11146 both print as
// `offloaded 37/37 layers to GPU` on a machine with no usable device, and never a CPU-side
// buffer the `isCpuDevice` blacklist misses (ggml's `AMX` on a Sapphire Rapids CPU).
// Before #653 the unknown path read that line, so a GPU-less PC whose probe gave no
// answer was labelled gpu; and an empty answer outranked the log, so a card start whose
// probe child crashed was labelled cpu for the whole session.
this.backend = 'gpu'
labelNote =
devices === null
? ', from the load log: the device probe gave no answer'
: ', from the load log: the device probe listed no device'
//
// The NAME is the device this start's COMPUTE BUFFERS landed on — never `devices[0]`.
// `placement.ts` pushes the `device_info` rows in LOG order, which is not the order the
// fit used: on this project's own hybrid evidence (`eval/results/hardware/ryzen-7-
// 5800h-rtx-3060-laptop-6gb-14gb/leg5-device-landing.comment.md`) `Vulkan0` is the AMD
// iGPU, listed FIRST and given no buffers at all, while every buffer went to `Vulkan1`,
// the RTX 3060 Laptop. Naming the first row would credit the iGPU for a start that ran
// on the card — exactly the DR2 / M8.2 defect `displayDevice` exists to prevent on the
// probe path. With no compute buffer line printed, the largest row is the better guess
// than the first one, for the same reason.
const reading = placement.reading()
const used =
largestPlacementRow(reading.devices, (d) => d.computeMb ?? 0) ??
largestPlacementRow(reading.devices, (d) => d.totalMb ?? 0)
this.gpuName = (used ?? reading.devices[0])?.name ?? null
} else {
// No device listed (or no answer) and nothing of this start on a card: CPU mode.
this.backend = 'cpu'
this.gpuName = null
}
} else {
this.backend = 'cpu'
this.gpuName = null
}
this.labelled = true
// #1012 code review round 5: a higher rung of this walk could not read the engine's files, so this
// start may run lower (on the processor) than the machine allows, for this session and without a
// notice. Nothing was latched; the next start walks again. Said once, in the selection's log line.
const unreadableNote = sawUnreadable ? '; a higher rung could not read the engine files just now' : ''
this.deps.onSelect?.('llama', this.opts, `started via ${rung.label} (backend: ${this.backend}${labelNote}${unreadableNote})`)
// benchmark.md "Your model": what this start's log said about where the model landed.
// Recorded after the backend label so the observation carries the same verdict the UI
// shows; the observer (IPC layer) persists it. Never throws into the start.
recordModelPlacement({
modelId: this.opts.modelId,
contextTokens: this.opts.contextTokens,
backend: this.backend === 'gpu' ? 'gpu' : 'cpu',
...placement.reading(),
machineKey: this.deps.machineKey?.() ?? null,
at: new Date().toISOString()
})
// #109: pay the one-time prefill/graph warm-up NOW, inside the "Starting…" window,
// so start() only resolves once the user's real first prompt lands on a warmed path.
// Ordering matters: the backend label above is already set, so a GPU crash during
// the warm-up routes through the §5.3 onGpuCrash auto-fallback (gated on
// backend === 'gpu'). Real llama rungs only — the rung-4 mock below streams
// instantly and must keep starting instantly (zero-assets suites rely on it).
await this.warmUp(runtime)
// CODE-2: a stop()/quit during the warm-up window stopped the inner server (the
// warm-up stream then erred and was swallowed above) — the ladder must settle as
// CANCELLED, never proceed to ready or fall through to another rung.
if (this.cancelled) {
try {
await runtime.stop()
} catch {
/* best-effort — stop() already stopped it; the queued manager stop re-stops */
}
throw cancelledStartError()
}
return
}
// CODE-2: a cancelled start must settle as CANCELLED, not commit the rung-4 mock —
// the queued stop would then have to undo a runtime nobody asked for.
if (this.cancelled) throw cancelledStartError()
// #312: every real rung failed, so the control probe has answered. Same class on both
// sides ⇒ the MODEL is the common cause: drop the held failure (nothing persisted,
// `gpuLastError` untouched) and name the model instead. Anything else — differing
// classes, or a shape `failureSignature` does not recognise on either side — stays a
// device verdict, exactly as before: unknown evidence must never un-blame a real GPU
// fault and reinstate a multi-minute health timeout on every later start.
// #1012 code review round 3: the reason and the blame come from the last failure that is evidence —
// a rung that could not read its engine files proved nothing, so it never hides an earlier one.
const decisive = lastEvidence ?? lastError
const reason = decisive instanceof Error ? decisive.message : String(decisive)
// #1012 code review rounds 3–4: a rung of this walk could not read the engine's files just now, so the
// walk latches nothing — no model latch, no persisted GPU failure (no MTP latch either, above) — and the
// next start (a re-select) walks the whole ladder again. It only reports: the model notice when a
// CONTROL rung failed in a way that is evidence, else the files-unreadable notice (no silent demo
// runtime). Round 6: checked FIRST, before the engine refusal below — a copy that was only unreadable
// must not read as "the engine cannot run on this computer" (a refused `cpu/` net keeps its own verdict).
if (sawUnreadable) {
if (sawEvidence) this.deps.onModelLoadFailure?.(this.opts, reason)
else this.deps.onEngineFilesUnreadable?.(this.opts)
await this.fallBackToMock(`a start attempt could not read the AI engine's files just now: ${reason}`)
return
}
// #530: every rung that failed was refused by the OS loader — the ENGINE cannot run here.
// Nothing is persisted and nothing is latched: installing the missing library (or the
// runtime) and choosing Check again, or restarting, must find a clean slate.
if (engineFailure !== null && pendingGpuFailure === null && cpuSignature === null) {
this.deps.onEngineCannotRun?.(this.opts, engineFailure.problem)
await this.fallBackToMock(`the AI engine cannot run on this computer: ${engineFailure.message}`)
return
}
if (pendingGpuFailure) {
const modelFault = cpuSignature !== null && cpuSignature === pendingGpuFailure.signature
if (modelFault) this.blameModel(pendingGpuFailure.reason)
else this.deps.gpu.onGpuFailure?.(pendingGpuFailure.reason)
pendingGpuFailure = null
} else if (lastEvidence !== null) {
// #372: no GPU verdict was held — acceleration is off, `gpuAutoDisabled` is already
// persisted (no GPU rung ran), or the GPU rung's failure was a bind race (REL-1, never
// held). There is no device comparison to make and nothing to persist; the model is
// still the thing that could not be loaded on this computer, so name it. The latch
// needs a recognised failure class (never a bind race): a transient port collision on
// the last rung fires the notice but must not exile the model for the session.
const latch = cpuSignature !== null && !isBindRaceError(reason)
if (latch) this.blameModel(reason)
else this.deps.onModelLoadFailure?.(this.opts, reason)
}
// Rung 4 — the existing graceful fallback: the app can never be stuck. The mock's
// replies are visibly simulated, and the next start retries the ladder — from rung 2
// when the rung-1 failure was persisted as a device fault, and from rung 1 again when
// #312 blamed the model instead (the auto-disable flag was never written) — unless
// #372 latched the model, in which case the next start skips the walk entirely.
await this.fallBackToMock(`all llama-server start attempts failed: ${reason}`)
}
/** #312/#372: the model is the common cause — name it to the user, latch it for the session. */
private blameModel(reason: string): void {
latchModelLoad(this.opts.modelId, reason)
this.deps.onModelLoadFailure?.(this.opts, reason)
}
/** Rung 4: commit the mock runtime (the app can never be stuck) and log why. */
private async fallBackToMock(selectReason: string): Promise<void> {
const mock = this.deps.makeMock(this.opts)
await mock.start()
this.inner = mock
this.backend = 'mock'
this.gpuName = null
this.deps.onSelect?.('mock', this.opts, selectReason)
}
/**
* #182: may rung 1a run on THIS machine, right now? Conservative by construction — every
* "don't know" answers no, because a skipped speculative rung costs nothing while a wrong
* yes costs a silent partial offload (or, off-GPU, an unmeasured configuration).
*
* Ordered cheapest-first so the common no-op paths never touch the probe.
*/
private async speculativeVerdict(
probe: (binPath: string) => Promise<GpuDevice[] | null>,
binPath: string
): Promise<{ ok: true } | { ok: false; reason: string }> {
if (isSpeculativeSuppressed(this.opts.modelId)) {
return { ok: false, reason: 'latched off for this session by an earlier attempt' }
}
const bytes = this.opts.weightBytes
if (bytes == null || !(bytes > 0)) {
// `startModelRuntime` always supplies this; a null means a file stat failed, i.e. the
// VRAM check below cannot be made. Refuse rather than guess.
return { ok: false, reason: 'weight size unknown — cannot check VRAM headroom' }
}
const devices = await probe(binPath).catch(() => null)
// #380: "don't know" answers no, like every other branch here — an unknown probe cannot
// establish the VRAM headroom the measured gain depends on.
if (devices === null) {
return {
ok: false,
reason: 'device probe gave no answer (timed out, crashed, or the engine could not start) — cannot check VRAM headroom'
}
}
if (devices.length === 0) {
return { ok: false, reason: 'no GPU device (the measured gain is a full-offload GPU result)' }
}
const neededMb = Math.ceil(bytes / (1024 * 1024)) + MTP_VRAM_HEADROOM_MB
// ONE device must hold all of it: a multi-device split with a draft head is unmeasured,
// so free VRAM is never summed across cards. That device is the budget device every other
// VRAM rule uses (#473): taking whichever device reports the most free memory let a hybrid
// box's integrated GPU — a UHD 770 reports 48,060 MiB free of shared RAM beside an
// RTX 3080 Ti's 11,316 — pass the check for the discrete card.
const best = primaryUsefulDevice(devices)
if (best === null) {
return { ok: false, reason: 'no usable graphics card (only integrated or small devices)' }
}
if (best.freeMb < neededMb) {
return {
ok: false,
reason: `not enough free VRAM (${best.freeMb} MiB free on ${best.name}, ${neededMb} MiB needed)`
}
}
return { ok: true }
}
/**
* The #109 hidden warm-up generation (see the constants above for the design record
* pointer). Runs against the INNER runtime so the #39 `served` flag stays false —
* the warm-up is not a real generation and must not disarm the warm-up hint. Never
* throws: a cancel is detected by the caller via `this.cancelled`; any other failure
* (including the cap abort) is logged through `onWarmup` and the start proceeds —
* the server is healthy, a cold first prompt is strictly better than a failed start.
*/
private async warmUp(runtime: ModelRuntime): Promise<void> {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), this.deps.warmupTimeoutMs)
try {
// No `mode` = 'balanced' → `enable_thinking: false` (requestParamsForMode) — the
// warm-up must never burn seconds on reasoning tokens. Content-free, tiny cap,
// loopback-only; the output is discarded, never persisted, never audited as a chat.
const stream = runtime.chatStream([{ role: 'user', content: WARMUP_PROMPT }], {
maxTokens: WARMUP_MAX_TOKENS,
signal: controller.signal
})
for await (const _token of stream) {
/* discard — the request exists only to pay the one-time warm-up cost */
}
this.deps.onWarmup?.(this.opts, 'done')
} catch (err) {
// A cancel (stop()/quit killed the server mid-warm-up) is handled by the caller's
// re-check of `this.cancelled` — don't log it as a warm-up fault.
if (!this.cancelled) {
const detail = err instanceof Error ? err.message : String(err)
this.deps.onWarmup?.(this.opts, controller.signal.aborted ? 'timeout' : 'failed', detail)
}
} finally {
clearTimeout(timer)
}
}
/** #114: end the prefetch window. Idempotent; safe when no prefetch ran. */
private abortPrefetch(): void {
this.prefetch?.abort()
this.prefetch = null
}
async stop(): Promise<void> {
// CODE-2: flag first so the walk aborts at the next rung boundary…
this.cancelled = true
// …and the #114 prefetch reader must not keep the drive busy past a stop/lock.
this.abortPrefetch()
// …then unblock an in-flight rung: `LlamaServer.stop()` during `waitForHealthy` makes
// the readiness loop throw via its exit check (the layer that already worked — this
// makes it reachable). Best-effort: the walk's catch path re-stops idempotently.
const starting = this.startingInner
this.startingInner = null
if (starting) {
try {
await starting.stop()
} catch {
/* best-effort — the ladder's own failure path re-stops the rung runtime */
}
}
const inner = this.inner
this.inner = null
if (inner && inner !== starting) await inner.stop()
}
async health(): Promise<HealthStatus> {
if (!this.inner) return { healthy: false, message: 'Not started', port: null }
return this.inner.health()
}
chatStream(
messages: ChatMessage[],
options?: RuntimeChatOptions
): AsyncGenerator<string, void, unknown> {
// #600: only a runtime captured before it was stopped gets here. After a deliberate stop the
// caller's turn is already aborted (the model-stop hook), so it counts as a Stop; after a crash
// restart the model really is gone — the typed error gives the user words, not this text.
if (!this.inner) throw new RuntimeConnectionLostError()
// #39: the first streamed chunk — an answer token, or in Deep mode a reasoning delta
// that arrives before any answer token — proves the one-time prefill is done, so the
// Chat warm-up hint must stop claiming the model is still warming up. Mark on either.
const markServed = (): void => {
if (!options?.auxiliary) this.served = true // a helper call is no first answer (#1003)
}
const inner = this.inner.chatStream(
messages,
options?.onReasoning
? {
...options,
onReasoning: (delta) => {
markServed()
options.onReasoning?.(delta)
}
}
: options
)
return (async function* () {
for await (const token of inner) {
markServed()
yield token
}
})()
}
/** #39: true once ANY real generation has streamed since this runtime started. */
warmedUp(): boolean {
return this.served
}
/**
* The launched context window (§L0). Every rung (and the mock fallback) starts with the
* SAME `opts.contextTokens`, so this is rung-independent and valid before/after `start()`.
*/
contextWindow(): number {
return this.opts.contextTokens
}
}
/**
* Build a `RuntimeFactory` that returns the GPU-ladder runtime when the sidecar binary
* + the model weights are present, else `MockRuntime`. Pure + dependency-injected so
* the selection + ladder logic is unit-testable without spawning anything.
*/
export function createSelectingRuntimeFactory(deps: RuntimeSelectionDeps): RuntimeFactory {
const resolveBin =
deps.resolveBin ??
((root: string) => resolveLlamaServerPath(root, process.platform, process.env, { isDev: deps.isDev }))
const modelExists = deps.modelExists ?? existsSync
const makeLlama =
deps.makeLlama ??
((opts: RuntimeStartOptions, binPath: string, rung?: LlamaRungOptions) =>
createLlamaRuntime(opts, {
binPath,
extraArgs: rung?.extraArgs,
onUnexpectedExit: rung?.onUnexpectedExit,
onStderrData: rung?.onStderrData
}))
const makeMock = deps.makeMock ?? createMockRuntime
const gpu = deps.gpu ?? {}
const resolveCpuBin = gpu.resolveCpuBin ?? ((root: string) => resolveCpuFallbackServerPath(root))
return (opts: RuntimeStartOptions): ModelRuntime => {
const binPath = resolveBin(deps.rootPath)
if (!binPath) {
deps.onSelect?.('mock', opts, 'no llama-server binary on the drive')
return makeMock(opts)
}
if (!modelExists(opts.modelPath)) {
deps.onSelect?.('mock', opts, 'model weights not present')
return makeMock(opts)
}
const tryGpu = (gpu.getGpuMode?.() ?? 'auto') === 'auto' && !(gpu.getGpuAutoDisabled?.() ?? false)
const rungs: Rung[] = []
if (tryGpu) {
// Rung 1a (#182): rung 1 plus the MTP flags, for a manifest that opts in. Listed
// BEFORE rung 1 so the plain GPU attempt is its automatic fallback — a rung 1a that
// will not start (an older runtime that rejects the flag, a weight without the draft
// head, a VRAM refusal) costs one attempt and lands on exactly today's behavior. The
// rung is DECLARED here and gated at walk time, where the device probe can be awaited.
if (opts.speculativeDecoding === 'mtp') {
rungs.push({
label: 'rung 1a (GPU auto-offload + MTP speculative decoding)',
binPath,
extraArgs: [...MTP_SERVER_ARGS],
gpuAttempt: true,
speculative: true
})
}
// Rung 1: NO -ngl / --device args — b9585 defaults to ngl=auto + fit=on.
rungs.push({ label: 'rung 1 (default args, GPU auto-offload)', binPath, extraArgs: [], gpuAttempt: true })
}
// Rung 2: same binary, forced CPU. `--device none` is the ONLY way we force CPU.
rungs.push({
label: tryGpu ? 'rung 2 (--device none)' : 'rung 2 (--device none; GPU off/auto-disabled)',
binPath,
extraArgs: ['--device', 'none'],
gpuAttempt: false
})
// Rung 3: the pure-CPU safety-net build, when the drive ships one.
const cpuBin = resolveCpuBin(deps.rootPath)
if (cpuBin && cpuBin !== binPath) {
rungs.push({ label: 'rung 3 (pure-CPU safety-net build)', binPath: cpuBin, extraArgs: [], gpuAttempt: false })
}
return new LadderRuntime(opts, rungs, {
makeLlama,
machineKey: deps.machineKey,
makeMock,
onSelect: deps.onSelect,
onWarmup: deps.onWarmup,
onSpeculative: deps.onSpeculative,
onModelLoadFailure: deps.onModelLoadFailure,
onEngineCannotRun: deps.onEngineCannotRun,
onEngineFilesUnreadable: deps.onEngineFilesUnreadable,
warmupTimeoutMs: deps.warmupTimeoutMs ?? WARMUP_TIMEOUT_MS,
onPrefetch: deps.onPrefetch,
makePrefetch: deps.makePrefetch ?? startModelPrefetch,
gpu
})
}
}
export interface GpuCrashFallbackDeps {
/** Restart the same model (the ladder now starts at rung 2 — CPU). */
restart: (opts: RuntimeStartOptions) => Promise<unknown>
/** Persist `gpuAutoDisabled` + `gpuLastError`; must never throw. */
persistFailure: (reason: string) => void
/** Surface the friendly one-line notice (renderer broadcast + log). */
notify?: (message: string) => void
}
/** One-line human summary of an unexpected sidecar exit, used by the crash handlers. */
function describeExit(info: UnexpectedExitInfo): string {
const code = info.exitCode != null ? `code ${info.exitCode}` : `signal ${info.exitSignal}`
const tail = info.stderrTail.trim()
return `crashed mid-session (${code})${tail ? ` — last output: ${tail}` : ''}`
}
/**
* Shared shape of the mid-generation auto-restart handlers: react once, restart the same
* model ONCE, and never loop. Re-entrancy guarded — overlapping crash reports while a
* restart is in flight are ignored.
*/
function createCrashAutoRestart(
react: (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void,
restart: (opts: RuntimeStartOptions) => Promise<unknown>
): (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void {
let restarting = false
return (opts, info) => {
if (restarting) return
restarting = true
react(opts, info)
// restart() may throw SYNCHRONOUSLY (before returning a promise). Without this
// try/catch the throw escapes before `.finally` is attached, `restarting` stays
// true forever, and EVERY future crash auto-fallback is silently suppressed (M-C3).
try {
void restart(opts)
.catch(() => undefined) // a failed restart surfaces on the user's next start
.finally(() => {
restarting = false
})
} catch {
restarting = false // a sync throw surfaces on the user's next start; re-arm the guard
}
}
}
/**
* The §5.3 mid-generation crash handler: persist the auto-disable flag, restart the
* same model ONCE at CPU, and surface the compatibility-mode notice — so the user's
* *next* message just works. (After the restart the backend is CPU and the ladder no
* longer routes crashes here.) The notice is the friendly §11.4 copy
* (`main.runtime.compatibilityMode`, emitted via tMain — runtime:notice is ephemeral, i18n
* record §3.3 rule 2): never "GPU failed" / "your hardware is bad" — CPU mode is normal,
* not degraded.
*/
export function createGpuCrashAutoFallback(
deps: GpuCrashFallbackDeps
): (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void {
return createCrashAutoRestart((_opts, info) => {
deps.persistFailure(describeExit(info))
deps.notify?.(tMain('main.runtime.compatibilityMode'))
}, deps.restart)
}
/**
* #182: the same handler for a crash of the SPECULATIVE rung. Two deliberate differences
* from its GPU sibling — the reason both exist:
*
* - it does NOT persist `gpuAutoDisabled`. The device is not the suspect; the optional
* extra flags are, and the ladder has already latched them off for this session. Exiling
* a working GPU to CPU over a speed-up would be a far worse outcome than losing the
* speed-up, and would need a Diagnostics visit ("Try GPU again") to undo.
* - its notice says what actually happened: the restart lands back on the GPU, so the
* compatibility-mode copy ("responses may be a bit slower") would be a plain lie.
*/
export function createSpeculativeCrashAutoFallback(deps: {
restart: (opts: RuntimeStartOptions) => Promise<unknown>
/** Observability only — never persisted as a GPU fault. */
onCrash?: (reason: string) => void
notify?: (message: string) => void
}): (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void {
return createCrashAutoRestart((_opts, info) => {
deps.onCrash?.(describeExit(info))
deps.notify?.(tMain('main.runtime.speedUpDisabled'))
}, deps.restart)
}
/**
* #599: the handler for a CPU-mode crash (`onCpuCrash`). Owner decision 2026-10-06: restart the same
* model once per model per session, with a notice; a second crash of that model stops it, with a
* notice, so a model that keeps crashing is never respawned in a loop. No GPU flag is touched — the
* device did not change. The budget is separate from the GPU fallback: a GPU crash restarts on CPU
* (§5.3), and that CPU runtime still gets its one restart.
*/
export function createCpuCrashAutoRestart(deps: {
restart: (opts: RuntimeStartOptions) => Promise<unknown>
/** Drop the dead runtime so every surface says stopped (`RuntimeManager.stopCrashed`). */
stop: (opts: RuntimeStartOptions) => Promise<unknown>
/**
* The workspace admits work (AUD-02). A crash during a lock does nothing here — the lock's
* teardown stops the model anyway — so it neither spends the restart nor announces one.
*/
admitsWork?: () => boolean
/** Observability only (the audit event). */
onCrash?: (reason: string) => void
notify?: (message: string) => void
}): (opts: RuntimeStartOptions, info: UnexpectedExitInfo) => void {
const restarted = new Set<string>()
// Overlapping reports while a restart or stop is in flight are the same crash. (`LlamaServer`
// reports one death once since #656; this guard still keeps a re-entrant report out.)
let busy = false
return (opts, info) => {
if (busy) return
if (deps.admitsWork && !deps.admitsWork()) return
const first = !restarted.has(opts.modelId)
restarted.add(opts.modelId)
deps.onCrash?.(describeExit(info))
deps.notify?.(tMain(first ? 'main.runtime.crashRestarting' : 'main.runtime.crashStopped'))
busy = true
// restart()/stop() may throw synchronously — never leave the latch stuck (M-C3).
try {
void (first ? deps.restart(opts) : deps.stop(opts))
.catch(() => undefined) // a failed restart surfaces on the user's next start
.finally(() => {
busy = false
})
} catch {
busy = false
}
}
}