/** * pi-model-swap — llama-swap model-swap controller for pi sessions * ============================================================================ * Implements `research/T002F-design-rev7.md` §7 as amended by * `research/T003F-design-review7.md` (MAJOR-4 + MINORs n-1..n-6 folded in). * * Surface * - tool `model_swap` (params: model, level?, dry_run?, go?, restore?) * - command `/swap [model] [level] [--dry-run] [--go] [--restore] [--status]` * * Ordering invariant (rev7 §7.1): MODEL FIRST (`setModel`), THINKING SECOND * (`setThinkingLevel`), then the verify request. Mirrors pi's own example * `examples/extensions/preset.ts` (setModel :136 → setThinkingLevel :147; * restore :276 → :278). * * Refusal rule (rev7 §7.1 step 2 + §7.5): a swap is refused when its eviction * set contains a model that a live session is bound to (claim file), or when a * census of that model's upstream port shows an established connection whose owner * pid is neither the model's own listener owner nor the controller's pid. * Unattributable ESTAB ⇒ refuse (default-deny). * * BLOCKER-1 (T006): the census allow-list is PID IDENTITY, never a name. `comm` is * `/proc//comm`, which any local process can set with `prctl(PR_SET_NAME)`, so * `comm == "llama-swap"` is evidence of nothing. A row is allowed only when its owner pid * owns the model's LISTEN socket, or owns the controller's LISTEN socket. `comm` is read * for the report line only. My own pid is never allow-listed: an ESTAB owned by this * process on a model's upstream port is by definition a direct consumer. * * BLOCKER-2 (T006): `GET /running` must be READ, not merely answered. A 200 whose body is * not the documented shape (an array of objects each carrying a string `id`) is a census * FAILURE — the eviction set is unknown, so the swap refuses. An empty set is accepted only * when the body itself says "nothing is running" (`[]`). A census that reads nothing is * never scored as a clean census. * * Phase set — ENUMERATED (MAJOR-4 fix; rev7 §7.3 never enumerated it and left * `rolling_back` out of the `bound` mapping, so the go gate and the §7.6 restore * leg had no defined passage): * * phases: idle | armed | verifying | committed | rolling_back | restoring * legacy alias accepted on read: `active` → normalised to `committed` (n-5) * * phase written by bound means legal next * ----------- --------------------------------- ------------------------- ---------------------------- * idle RELEASE step (MAJOR-3/T006: forward-leg step-4 failure — the binding was * never moved, nothing was evicted, so the claim is released) session default armed * armed §7.1 step 3 previous verifying | idle (release) * verifying §7.1 step 6 (before the request) target committed | rolling_back * committed §7.1 step 8, and the restore commit target (forward) / restored model armed | restoring * rolling_back §7.1 step 9 (verify failure) target (stranded on) restoring * restoring the go gate (step R0) restore destination = claim.previous (the model the swap left, n-4) verifying (see T006C note) * * MAJOR-3 (T006): `idle` is REACHABLE. The release write is the forward-leg step-4 failure * path (model not in registry / setModel false): `armed -> idle`, bound = previous. The two * edges that no write site ever used (`committed -> idle`, `rolling_back -> idle`) are gone * from TRANSITIONS (the edges they named are gone; the same defect class is swept in the * T006C MINOR-2 note below, which states the write-site/edge match edge by edge). * * T006C MINOR-2: the same defect class, in the edges above. The write sites are the five * `writeClaim` calls, and they take exactly nine edges: idle->armed, committed->armed, * committed->restoring, rolling_back->restoring, armed->idle, armed->verifying, * restoring->verifying, verifying->committed, verifying->rolling_back. * `armed -> rolling_back` and `restoring -> committed` had no write site and are DELETED * from TRANSITIONS and from this table (no write site is added — the shipped transitions are * the contract). `restoring -> rolling_back` is still declared in TRANSITIONS with no write * site; it is left in place and flagged to the planner (research/t006c-fixes.md). * * `claim.previous` (recorded at armed) is the go gate's restore destination. At * rolling_back, `claim.bound` is the model the session is STRANDED ON — using it as the * restore destination would make the authorised action (go back to what we left) unrepresentable. * * Step 0's phase check EXEMPTS self-claims (MAJOR-4): a live claim of mine in * {committed, rolling_back} does not block me — `rolling_back` admits exactly * one path, the go gate (`--go` / the §7.6 boundary leg) restoring `claim.previous`. * A live claim of mine in {armed, verifying, restoring} means a swap of mine is * in flight and re-entry is refused. Foreign live claims in any non-idle phase * refuse the swap (one card, one swap in flight). * * Hard rules this file obeys (rev7 §7, task rule 2): * - no server start/stop/kill, no port polling, no signals * - no `pgrep -f`, no `pkill -f`, no `rm` * - no llama-swap model-load endpoint, no llama-swap process-list endpoint (neither exists at v2.16.2) */ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { StringEnum } from "@earendil-works/pi-ai"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, } from "@earendil-works/pi-coding-agent"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- /** The seven levels pi documents (docs/extensions.md:1691-1697). */ type SwapLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; /** * T006C MINOR-4: the forward-leg level when `/swap` names none (§7.2 precedence 2). * `defaultLevel()` used to return this value while reading `cfg`/`ctx` for nothing * (`void cfg; void ctx;`) — the read was dead, so it is inlined and the function is gone. * OPEN ITEM (not fixed here, docs follow behaviour): §7.2 precedence 2 asks for * `settings.json:defaultThinkingLevel`; that read is not implemented in this build. */ const FALLBACK_LEVEL: SwapLevel = "medium"; /** MAJOR-4: the complete, enumerated phase set. No phase outside this set is legal. */ type Phase = "idle" | "armed" | "verifying" | "committed" | "rolling_back" | "restoring"; const PHASES: readonly Phase[] = ["idle", "armed", "verifying", "committed", "rolling_back", "restoring"]; /** n-5: rev7 §7.3's mapping names `active`; no step writes it. Read it as `committed`. */ const LEGACY_PHASE_ALIASES: Record = { active: "committed" }; /** Phases that mean "this session is parked on `bound` and constrains the card". */ const CONSTRAINING_PHASES: readonly Phase[] = ["armed", "verifying", "committed", "rolling_back", "restoring"]; /** Phases in which a swap of mine is already in flight (re-entry refused). */ const IN_FLIGHT_PHASES: readonly Phase[] = ["armed", "verifying", "restoring"]; /** Phases from which a forward swap may start (self-claim exemption, MAJOR-4). */ const FORWARD_FROM: readonly Phase[] = ["idle", "committed"]; /** Phases from which a restore may start (MAJOR-4: the go gate + the §7.6 boundary leg). */ const RESTORE_FROM: readonly Phase[] = ["committed", "rolling_back"]; /** Legal transitions, asserted by the writer so an illegal edge is a bug at the write site. */ const TRANSITIONS: Record = { idle: ["armed"], // MAJOR-3 (T006): `idle` is now a write target (the release step), so it is declared on the // edge that reaches it. `committed`/`rolling_back` no longer declare `idle` — no write site // ever took those edges, and a legality table that declares unreachable edges is a lie. // T006C MINOR-2: `rolling_back` deleted — no write site ever took armed -> rolling_back // (the verify failure writes from `verifying`, `:847`). armed: ["verifying", "idle"], verifying: ["committed", "rolling_back"], committed: ["armed", "restoring"], rolling_back: ["restoring"], // T006C MINOR-2: `committed` deleted — the restore commit is written from `verifying` (`:838`). // `rolling_back` stays declared with no write site today (flagged, not deleted). restoring: ["verifying", "rolling_back"], }; interface Claim { pid: number; /** /proc//stat field 22 (starttime) — guards PID reuse (rev7 §7.3). */ pidstart: number; phase: Phase; /** Model id (bare llama-swap id) this session is bound to. Semantics per phase, above. */ bound: string; target?: string; /** * The model the swap LEFT (recorded at `armed`). This is the restore destination the * go gate is allowed to authorise from `rolling_back` — NOT `bound`, which at * rolling_back names the model the session is stranded ON. Conflating the two makes * the authorised restore (going back to what we left) unrepresentable. */ previous?: string; /** level_before, so a crash between steps 4 and 8 does not lose the deep-role level. */ level?: SwapLevel; ts: number; } interface SwapConfig { /** llama-swap controller (the only inference endpoint the extension talks to). */ controllerUrl: string; controllerPort: number; /** Roster file — the ONLY source for the 13 upstream ports (rev7 §7.4). */ rosterPath: string; /** llama-swap config file — source of `startPort` for the ${PORT} macro. */ llamaSwapConfigPath: string; startPort: number; /** pi provider that fronts the controller. */ provider: string; /** Session default (restore target), bare model id under `provider`. */ sessionDefault: string; /** Strata's own port after OD-1 — corroboration only, never a port source. */ strataPort: number; /** Client bound on step 7 (§7.8): healthCheckTimeout 900 s + 60 s margin. */ verifyTimeoutMs: number; /** * MINOR-1 (T006): the census/status probe's OWN timeout. `verifyTimeoutMs` is 960 000 ms * (16 min) because it bounds the step-7 request that starts a model; a `GET /running` must * never inherit it — a stalled controller would hang `/swap --dry-run` for 16 minutes. */ probeTimeoutMs: number; /** Claim staleness outer bound (§7.3 / §7.8). */ claimStalenessS: number; /** §7.6 boundary leg: announce at one boundary, execute at the next. */ boundaryRestore: boolean; } /** * T008 (packaging): the machine-specific fields are NEUTRAL. They used to be one developer's * production box (`/media/adam/...`, `swift-1.5`, :1301), so a fresh install printed paths that do * not exist on the user's machine. The merge is `{...DEFAULT_CONFIG, ...configFile}`, so a config * that sets a key is unaffected — only absent keys change, and every machine-specific key is * REQUIRED (the fail-closed gate reports them). Timing knobs stay real defaults: they are not * machine identity. */ const DEFAULT_CONFIG: SwapConfig = { controllerUrl: "", controllerPort: 0, rosterPath: "", llamaSwapConfigPath: "", startPort: 0, provider: "", sessionDefault: "", strataPort: 0, verifyTimeoutMs: 960_000, probeTimeoutMs: 5_000, claimStalenessS: 1800, boundaryRestore: true, }; /** * The cold-start warning (§7.8), DERIVED from the eviction set. It used to be a fixed string * naming one developer's resident model, which (a) named a model that did not exist on the user's * machine and (b) fired on a same-model no-op where E is empty and nothing can be evicted. * Empty E ⇒ empty string ⇒ no warning line. For a single evicted model the text is byte-identical * to the old string, so S12/the harness assertion on "cold start" keeps its meaning. */ const coldStartWarningFor = (evictionSet: string[]): string => evictionSet.length === 0 ? "" : `This swap may evict ${evictionSet.join(", ")}. Recovery is a full cold start (minutes), not a fast rollback.`; // --------------------------------------------------------------------------- // Config + claim-file plumbing // --------------------------------------------------------------------------- interface LoadedConfig { cfg: SwapConfig; /** MAJOR-5 (T006): the config file exists but does not parse. Every mutator is gated on this. */ unreadable: boolean; path: string; error: string; } async function loadConfig(): Promise { const cfgPath = process.env.PI_MODEL_SWAP_CONFIG ?? join(getAgentDir(), "pi-model-swap.json"); try { const raw = JSON.parse(await readFile(cfgPath, "utf8")) as Partial; return { cfg: { ...DEFAULT_CONFIG, ...raw }, unreadable: false, path: cfgPath, error: "" }; } catch (err) { // MAJOR-5 (T006): the old fallback was `return DEFAULT_CONFIG`, and DEFAULT_CONFIG is // PRODUCTION (controller :1235, the real roster). One typo in the sandbox config aimed // the extension at the live controller — the inverse of fail-closed. DEFAULT_CONFIG is // kept as the field skeleton so the report can name what it would have pointed at, but // `unreadable` is set and every mutator refuses, with the config path in the report. return { cfg: DEFAULT_CONFIG, unreadable: true, path: cfgPath, error: err instanceof Error ? err.message : String(err), }; } } function claimDir(): string { return join(getAgentDir(), "state", "swap-state"); } function claimPath(pid: number): string { return join(claimDir(), `${pid}.json`); } /** /proc//stat field 22 = starttime. Field 2 (comm) may contain spaces → split after the last ')'. */ async function pidStarttime(pid: number): Promise { try { const stat = await readFile(`/proc/${pid}/stat`, "utf8"); const tail = stat.slice(stat.lastIndexOf(")") + 2).split(" "); const value = Number(tail[19]); // 22 - 3 (pid, comm, state consumed) = index 19 return Number.isFinite(value) ? value : undefined; } catch { return undefined; } } interface ReadClaim { claim?: Claim; /** A claim file exists but cannot be trusted: fail closed (rev7 §7.3). */ unreadable: boolean; live: boolean; expired: boolean; } async function readClaim(pid: number, cfg: SwapConfig): Promise { let raw: string; try { raw = await readFile(claimPath(pid), "utf8"); } catch (err) { // Absence is its own state: no claim file = idle. Only a PRESENT-but-broken file // fails closed (rev7 §7.3: parse failure is never absence). if ((err as NodeJS.ErrnoException).code === "ENOENT") return { unreadable: false, live: false, expired: false }; return { unreadable: true, live: false, expired: false }; } let parsed: unknown; try { parsed = JSON.parse(raw); } catch { return { unreadable: true, live: false, expired: false }; } const c = parsed as Partial; const rawPhase = typeof c.phase === "string" ? c.phase : ""; const phase = (LEGACY_PHASE_ALIASES[rawPhase] ?? rawPhase) as Phase; if ( typeof c.pid !== "number" || typeof c.pidstart !== "number" || typeof c.bound !== "string" || typeof c.ts !== "number" || !PHASES.includes(phase) ) { return { unreadable: true, live: false, expired: false }; } const claim: Claim = { pid: c.pid, pidstart: c.pidstart, phase, bound: c.bound, target: typeof c.target === "string" ? c.target : undefined, level: typeof c.level === "string" ? (c.level as SwapLevel) : undefined, // MAJOR-1 (T006): `previous` was written by writeClaim and DROPPED here, so // `self.claim.previous` was undefined for every claim read from disk and the go gate's // destination collapsed to sessionDefault — the exact inverse of the n-4 contract. previous: typeof c.previous === "string" ? c.previous : undefined, ts: c.ts, }; const start = await pidStarttime(claim.pid); const live = start === claim.pidstart; const ageS = (Date.now() - claim.ts) / 1000; // Live iff pid+pidstart match; the staleness bound is the OUTER bound (§7.8): // no claim may hold the gate shut past it. A dead pid releases immediately. return { claim, unreadable: false, live, expired: ageS > cfg.claimStalenessS }; } async function listClaimPids(): Promise { try { const names = await readdir(claimDir()); return names .filter((n) => n.endsWith(".json")) .map((n) => Number(n.slice(0, -5))) .filter((n) => Number.isFinite(n)); } catch { return []; } } /** Write a claim, asserting the transition is legal (MAJOR-4's transition table). */ async function writeClaim( pid: number, pidstart: number, from: Phase | undefined, to: Phase, bound: string, level: SwapLevel | undefined, target?: string, previous?: string, ): Promise { if (from && !TRANSITIONS[from].includes(to)) { throw new Error(`illegal claim transition ${from} -> ${to} (legal: ${TRANSITIONS[from].join(", ")})`); } const claim: Claim = { pid, pidstart, phase: to, bound, target, previous, level, ts: Date.now() }; const path = claimPath(pid); await mkdir(dirname(path), { recursive: true }); await writeFile(path, `${JSON.stringify(claim, null, 2)}\n`, "utf8"); return claim; } // --------------------------------------------------------------------------- // Roster → port map (rev7 §7.4: config parsing is the ONLY source for the 13 ports) // --------------------------------------------------------------------------- interface RosterEntry { id: string; url: string; port: number; usesPortMacro: boolean; } function scalarFromYaml(text: string, key: string): string | undefined { const m = new RegExp(`^${key}:\\s*(.+)$`, "m").exec(text); return m ? m[1].trim() : undefined; } /** * Parse `proxy:` out of the roster. `${PORT}` resolves to startPort + index in * roster order (ls-strings-v262.txt:78812). No endpoint is used to derive a port. */ async function readRoster(cfg: SwapConfig): Promise { const text = await readFile(cfg.rosterPath, "utf8"); let cfgText = ""; try { cfgText = await readFile(cfg.llamaSwapConfigPath, "utf8"); } catch { cfgText = ""; } const startPort = Number(scalarFromYaml(cfgText, "startPort") ?? cfg.startPort); const entries: RosterEntry[] = []; let current: { id: string; proxy?: string } | undefined; const flush = (): void => { if (!current?.proxy) return; const proxy = current.proxy; const usesPortMacro = proxy.includes("${PORT}"); const slot = entries.filter((e) => e.usesPortMacro).length; const port = usesPortMacro ? startPort + slot : Number(new URL(proxy).port); entries.push({ id: current!.id, url: proxy, port: Number.isFinite(port) ? port : NaN, usesPortMacro }); }; for (const line of text.split("\n")) { const idMatch = /^ ([A-Za-z0-9_.-]+):\s*(?:#.*)?$/.exec(line); if (idMatch) { flush(); current = { id: idMatch[1] }; continue; } const proxyMatch = /^ proxy:\s*(\S+)\s*$/.exec(line); if (proxyMatch && current) current.proxy = proxyMatch[1]; } flush(); return entries; } // --------------------------------------------------------------------------- // Census (rev7 §7.5) — ESTAB only, PID-IDENTITY allow-list (T006 BLOCKER-1), fail closed on // unattributable. rev7 §7.5 proposed identifying the llama-swap pid via /proc//comm; T006 // proved that route is a name check any local process can pass with prctl(PR_SET_NAME), so the // allow-list is resolved from LISTEN-socket pids instead. comm survives as report-only text. // // Empirical ss finding (tests/ss-probe4.cjs, this host): `ss -tanp state established // '( sport = :P )'` exits 0 and prints NOTHING even with a live ESTAB socket present — // combining `state established` with a filter expression is broken in this build. The // working form is `ss -tanp '( sport = :P or dport = :P )'` with ESTAB rows selected in // code. `dport` is required: a direct consumer's socket has the model's port as its // DESTINATION, so a sport-only filter sees only the server side and never the consumer. // --------------------------------------------------------------------------- interface CensusRow { local: string; peer: string; ownerPid?: number; ownerComm?: string; } interface CensusResult { port: number; estab: number; rows: CensusRow[]; /** Rows with no `users:(...)` attribution — default-deny. */ unattributable: number; /** Rows owned by a process whose comm is not llama-swap. */ foreign: CensusRow[]; error?: string; } async function censusPort(pi: ExtensionAPI, port: number, allowPids: Set): Promise { // No `state established` — see the empirical note above; ESTAB rows are selected here. const filter = `( sport = :${port} or dport = :${port} )`; const res = await pi.exec("ss", ["-tanp", filter], { timeout: 10_000 }); if (res.code !== 0) { return { port, estab: 0, rows: [], unattributable: 0, foreign: [], error: res.stderr.trim() || `ss exit ${res.code}` }; } const rows: CensusRow[] = []; for (const line of res.stdout.split("\n")) { if (!line.trim().startsWith("ESTAB")) continue; const cols = line.trim().split(/\s+/); const local = cols[3] ?? "?"; const peer = cols[4] ?? "?"; const pidMatch = /pid=(\d+)/.exec(line); const commMatch = /users:\(\("([^"]+)"/.exec(line); const row: CensusRow = { local, peer, ownerPid: pidMatch ? Number(pidMatch[1]) : undefined, ownerComm: commMatch?.[1] }; rows.push(row); } let unattributable = 0; const foreign: CensusRow[] = []; for (const row of rows) { if (row.ownerPid === undefined) { unattributable += 1; continue; } // BLOCKER-1 (T006): allow-list by PID IDENTITY. `allowPids` is {owner of this port's // LISTEN socket, owner of the controller's LISTEN socket}, both resolved from `ss -ltnp`. // The old code read /proc//comm and waved through anything named "llama-swap" — a // name any local process can set with prctl(PR_SET_NAME, "llama-swap") (see // research/t006-sandbox/spoof.c). comm is now report-only. if (allowPids.has(row.ownerPid)) continue; const comm = await commOf(row.ownerPid); foreign.push({ ...row, ownerComm: comm ?? row.ownerComm }); } return { port, estab: rows.length, rows, unattributable, foreign }; } /** Who owns the LISTEN socket on this port — the model's own server process. */ async function listenerOwner(pi: ExtensionAPI, port: number): Promise<{ ownerPid?: number; comm?: string }> { const res = await pi.exec("ss", ["-ltnp", `( sport = :${port} )`], { timeout: 10_000 }); if (res.code !== 0) return {}; for (const line of res.stdout.split("\n")) { if (!line.trim().startsWith("LISTEN")) continue; const pidMatch = /pid=(\d+)/.exec(line); const commMatch = /users:\(\("([^"]+)"/.exec(line); if (pidMatch) return { ownerPid: Number(pidMatch[1]), comm: commMatch?.[1] }; } return {}; } /** * BLOCKER-1 (T006): the controller's pid, resolved the same way the model listener's is — * from the LISTEN socket, never from a process name. Returns undefined when nothing listens * on the controller port, which shrinks the allow-list (fail closed), never widens it. */ async function controllerPid(pi: ExtensionAPI, cfg: SwapConfig): Promise { const owner = await listenerOwner(pi, cfg.controllerPort); return owner.ownerPid; } async function commOf(pid: number): Promise { try { return (await readFile(`/proc/${pid}/comm`, "utf8")).trim(); } catch { return undefined; } } // --------------------------------------------------------------------------- // Controller corroboration (rev7 §7.4). `/running` is llama-swap's; `/slots` is // Strata's — never poll `:1235/slots` (llama-swap does not serve it, 404). // --------------------------------------------------------------------------- interface RunningInfo { ok: boolean; status: number; body: string; models: string[]; error?: string; /** BLOCKER-2 (T006): set when the reply is 200-OK but not the documented `/running` shape. */ shapeError?: string; } async function getRunning(pi: ExtensionAPI, cfg: SwapConfig, apiKey?: string): Promise { // MINOR-1 (T006): the census probe gets its OWN short timeout. verifyTimeoutMs is 960 000 ms // (the step-7 client bound, §7.8) — a status read must never inherit a 16-minute hang. return getJson(pi, `${cfg.controllerUrl}/running`, cfg.probeTimeoutMs ?? 5_000, apiKey); } async function getJson(pi: ExtensionAPI, url: string, timeoutMs: number, apiKey?: string): Promise { const headers: Record = { "content-type": "application/json" }; if (apiKey) headers.authorization = `Bearer ${apiKey}`; try { const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) }); const body = await res.text(); if (!res.ok) return { ok: false, status: res.status, body, models: [] }; const parsed = parseRunningBody(body); return { ok: true, status: res.status, body, models: parsed.models, shapeError: parsed.error }; } catch (err) { return { ok: false, status: 0, body: "", models: [], error: err instanceof Error ? err.message : String(err) }; } } /** * BLOCKER-2 (T006): validate the `/running` shape instead of mining it for keys. * Documented shape (`research/ls-readme.md:47` — "/running - list currently running models"): * a JSON ARRAY whose elements are objects each carrying a string `id`. * The old `extractModelIds` walked the tree for any `id`/`model` string and returned `[]` * when it found none — and `[]` scored as "nothing resident", so a body that was not JSON at * all produced a vacuous-clean census. Here, anything that is not the documented shape is an * ERROR, not an empty set. `[]` (the controller saying "nothing is running") stays legal. * * T007 DEFECT-1 (2026-10-06): llama-swap v262 answers an ENVELOPE, not a bare array — * `{"running":[{"model":"swift-1.5","state":"ready","name":"",...}]}` — and keys the id `model`. * Both shapes are now accepted; anything else stays a shape ERROR. */ function parseRunningBody(body: string): { models: string[]; error?: string } { const trimmed = body.trim(); if (trimmed === "") return { models: [], error: "empty body" }; let data: unknown; try { data = JSON.parse(trimmed); } catch (err) { return { models: [], error: `body is not JSON (${err instanceof Error ? err.message : String(err)})` }; } // T007 DEFECT-1: v262 envelope -> unwrap it, then validate the list as before. // The T004 mock emitted the documented bare array, so every leg passed while the live // controller produced a shape error on every call (census reads nothing -> default-deny). if (data !== null && typeof data === "object" && !Array.isArray(data)) { const rec = data as Record; const list = rec.running ?? rec.models; if (!Array.isArray(list)) { return { models: [], error: 'body is an object with no "running"/"models" array' }; } data = list; } if (!Array.isArray(data)) { return { models: [], error: `body is ${data === null ? "null" : typeof data}, not an array of running models` }; } const ids: string[] = []; for (const [i, item] of data.entries()) { if (item === null || typeof item !== "object" || Array.isArray(item)) { return { models: [], error: `element ${i} is not an object` }; } const rec = item as Record; // v262 keys the id `model` (its `name` is "" and is a DISPLAY name, not an id — accepting it // would let T11's "object with no id" body score as a clean census). Take the first NON-EMPTY // of model|id (an empty string is a miss, so `??` is wrong). `state` is never read by the // census, so its absence stays legal. const id = [rec.model, rec.id].find((v) => typeof v === "string" && v !== ""); if (typeof id !== "string") { return { models: [], error: `element ${i} carries no non-empty string "model"/"id" — the shape is not /running` }; } ids.push(id); } return { models: [...new Set(ids)] }; } /** Step 7: one request, max_tokens 1, bounded by verifyTimeoutMs. Starting the target is llama-swap's job. */ async function verifyRequest( pi: ExtensionAPI, cfg: SwapConfig, target: string, level: SwapLevel, apiKey?: string, ): Promise<{ ok: boolean; detail: string }> { const headers: Record = { "content-type": "application/json" }; if (apiKey) headers.authorization = `Bearer ${apiKey}`; const body = JSON.stringify({ model: target, max_tokens: 1, messages: [{ role: "user", content: "ping" }], stream: false, chat_template_kwargs: { reasoning_effort: level }, }); try { const res = await fetch(`${cfg.controllerUrl}/v1/chat/completions`, { method: "POST", headers, body, signal: AbortSignal.timeout(cfg.verifyTimeoutMs), }); const text = await res.text(); return { ok: res.ok, detail: `${res.status} ${text.slice(0, 200).replace(/\s+/g, " ")}` }; } catch (err) { return { ok: false, detail: err instanceof Error ? err.message : String(err) }; } } // --------------------------------------------------------------------------- // Refusal report — ONE formatter, byte-identical in dry-run and live (§7.7) // --------------------------------------------------------------------------- function formatRefusal(lines: string[]): string { return ["REFUSED — swap would unload a model a live session is bound to", ...lines.map((l) => ` ${l}`)].join("\n"); } function formatPlan(lines: string[]): string { return lines.map((l) => `would: ${l}`).join("\n"); } /** * T006C MINOR-1: report RENDERING bound. A controller that answers 200 with 8000 valid ids * used to return a 1 220 760-byte / 8003-line tool response (measured: T006B `B huge valid * body`) — the swap fails closed, but the refusal itself blew the session context. * ONLY the rendering is capped. `running.models`, `evictionSet`, the census loop and the * `censusDeny` gate all still see the full set, so the cap cannot change which models end up * in the eviction set — the truncation line states the full count. */ const REPORT_LIST_CAP = 50; /** Cap a rendered list of lines: the first `cap` entries, then one truncation line. */ function capLines(lines: string[], cap = REPORT_LIST_CAP): string[] { if (lines.length <= cap) return lines; return [...lines.slice(0, cap), `…and ${lines.length - cap} more (truncated)`]; } /** Cap a rendered id list (one line): the first `cap` ids, then a trailing count. */ function capIds(ids: string[], emptyLabel: string, cap = REPORT_LIST_CAP): string { if (ids.length <= cap) return ids.join(", ") || emptyLabel; return `${ids.slice(0, cap).join(", ")}, …and ${ids.length - cap} more (truncated)`; } // --------------------------------------------------------------------------- // The swap engine — ONE code path, mutators behind `dryRun` (§7.7) // --------------------------------------------------------------------------- type SwapMode = "forward" | "restore"; interface SwapRequest { target: string; level?: SwapLevel; dryRun: boolean; go: boolean; mode: SwapMode; } interface SwapOutcome { report: string; refused: boolean; committed: boolean; rolledBack: boolean; } async function runSwap( pi: ExtensionAPI, cfg: SwapConfig, req: SwapRequest, ctx: ExtensionContext, ): Promise { const me = process.pid; const mystart = (await pidStarttime(me)) ?? 0; const notes: string[] = []; const plan: string[] = []; const refuse = (why: string[]): SwapOutcome => ({ report: formatRefusal(why), refused: true, committed: false, rolledBack: false }); const self = await readClaim(me, cfg); if (self.unreadable) return refuse([`my own claim file is unreadable/unparseable — fail closed (${claimPath(me)})`]); if (self.claim && self.live && !self.expired && IN_FLIGHT_PHASES.includes(self.claim.phase)) { return refuse([`my claim is ${self.claim.phase} — one swap in flight per session`]); } // MAJOR-4: step 0's phase check exempts self-claims. Foreign live claims gate the card. const foreign: string[] = []; for (const pid of await listClaimPids()) { if (pid === me) continue; const rc = await readClaim(pid, cfg); if (rc.unreadable) return refuse([`claim ${pid}.json is unreadable/unparseable — fail closed, parse failure is never absence`]); if (!rc.live || rc.expired) continue; if (CONSTRAINING_PHASES.includes(rc.claim!.phase)) foreign.push(`pid ${pid} phase ${rc.claim!.phase} bound ${rc.claim!.bound}`); } if (foreign.length > 0) return refuse(["another session has a swap in flight (one card, one swap):", ...foreign]); const selfPhase: Phase = self.claim && self.live && !self.expired ? self.claim.phase : "idle"; if (req.mode === "forward" && !FORWARD_FROM.includes(selfPhase)) { return refuse([ `my claim is ${selfPhase}; a forward swap starts only from ${FORWARD_FROM.join(" | ")}`, // T006C MINOR-3: the gate below enforces claim.previous, not claim.bound (MAJOR-1). selfPhase === "rolling_back" ? "a session in rolling_back admits only the go gate: /swap --go (restore target = claim.previous)" : "", ].filter(Boolean)); } if (req.mode === "restore" && !RESTORE_FROM.includes(selfPhase)) { return refuse([`my claim is ${selfPhase}; a restore starts only from ${RESTORE_FROM.join(" | ")}`]); } if (req.mode === "restore" && !req.go) { // rev7 §7.8: no automatic rollback. The §7.6 boundary leg is one of the two go paths, // so it arrives with go set; a bare restore is never authorised. return refuse([`a restore never executes without your go — /swap ${req.target} --go (rev7 §7.8: no automatic rollback)`]); } if (req.mode === "restore" && selfPhase === "rolling_back" && self.claim) { // n-4 + MAJOR-4: at rolling_back, `bound` is the model we are STRANDED ON. The go gate // authorises the restore to `previous` — the model the swap left. Restore destination // is claim.previous (session default as fallback), never an arbitrary model. const restoreTo = self.claim.previous ?? cfg.sessionDefault; if (req.target !== restoreTo) { return refuse([`rolling_back go gate: the restore destination is claim.previous (${restoreTo}), not ${req.target}`]); } } // Step 1: roster + ports → eviction set E = the model(s) currently resident. // MAJOR-4 (T006): an unreadable roster is a REFUSAL with a report, not an exception that // escapes through the tool as a stack trace. Fail closed WITH the report (§7.3). let roster: RosterEntry[]; try { roster = await readRoster(cfg); } catch (err) { return refuse([ `cannot read the roster ${cfg.rosterPath} (${err instanceof Error ? err.message : String(err)}) — the upstream ports are unknown, default-deny`, ]); } if (roster.length === 0) { return refuse([`roster ${cfg.rosterPath} yielded 0 proxy: entries — the port map is empty, default-deny`]); } const portOf = (id: string): number | undefined => roster.find((r) => r.id === id)?.port; const apiKey = await ctx.modelRegistry.getApiKeyForProvider(cfg.provider).catch(() => undefined); const running = await getRunning(pi, cfg, apiKey); if (!running.ok) { return refuse([`cannot read ${cfg.controllerUrl}/running (${running.error ?? running.status}) — the eviction set is unknown, default-deny`]); } // BLOCKER-2 (T006): a 200 whose body the parser cannot read is a census FAILURE, never an // empty eviction set. Fail closed on shape failure. if (running.shapeError) { return refuse([ `${cfg.controllerUrl}/running answered ${running.status} with a body that is not the documented shape: ${running.shapeError}`, `body (${running.body.length} bytes): ${running.body.slice(0, 120).replace(/\s+/g, " ")}`, `the eviction set is UNKNOWN — a census that reads nothing is not a clean census, default-deny`, ]); } // MINOR-4 (T006): exclude the target by NORMALISED id (provider prefix stripped, case-folded), // not bare-id equality. SPEC NOTE: if `/running` reports ids in a namespace that differs from // the roster ids, the target's own port gets censused (harmless, it only adds a row) — the // dangerous direction is a target name that COLLIDES with a different resident model, which // bare-id equality cannot see. Normalising is the code fix; the namespace question is §7.4's. const normId = (id: string): string => stripProvider(id, cfg.provider).toLowerCase(); const evictionSet = running.models.filter((m) => normId(m) !== normId(req.target)); // T006C MINOR-1: rendered list capped; the counts below are the FULL set sizes. notes.push(`resident: ${capIds(running.models, "(none)")} [${running.models.length} id(s) read]`); notes.push(`eviction set E: ${capIds(evictionSet, "(empty)")} [${evictionSet.length} model(s) in E]`); // T008: derived from E — a same-model no-op (E empty) warns about nothing, and the model named // is the model this swap can actually evict, not a hardcoded one. const coldStartWarning = coldStartWarningFor(evictionSet); // BLOCKER-1 (T006): the census allow-list is a set of PIDS, resolved from LISTEN sockets. // - the owner of the censused port's LISTEN socket (the model's own server process) // - the owner of the controller's LISTEN socket (llama-swap proxies to its upstreams) // My own pid is never on it: an ESTAB owned by this process on a model's upstream port is by // definition a direct consumer — the exact thing the census exists to catch. (In production // llama-swap's pid is never a pi pid; in the sandbox the mock controller shares the harness // pid, and this rule keeps the sandbox faithful to the production topology.) const ctlPid = await controllerPid(pi, cfg); const globalAllow = new Set(ctlPid !== undefined && ctlPid !== me ? [ctlPid] : []); const allowFor = async (port: number): Promise> => { const owner = await listenerOwner(pi, port); const s = new Set(globalAllow); if (owner.ownerPid !== undefined && owner.ownerPid !== me) s.add(owner.ownerPid); return s; }; // Step 2: census E — claims + sockets. Idle consumers count; unattributable counts. // MINOR-3 (T006): the gate is a typed deny flag set at the site that produces each line, // not a substring match over our own report text (a reformat used to delete the gate). const censusLines: string[] = []; let censusDeny = false; for (const id of evictionSet) { for (const rc of await claimConstraints(id, cfg, me)) { censusLines.push(rc); censusDeny = true; } const port = portOf(id); if (port === undefined) { censusLines.push(`model ${id} has no proxy: entry in ${cfg.rosterPath} — port unknown, default-deny`); censusDeny = true; continue; } const c = await censusPort(pi, port, await allowFor(port)); if (c.error) { censusLines.push(`census of :${port} failed (${c.error}) — default-deny`); censusDeny = true; } if (c.unattributable > 0) { censusLines.push(`:${port} ESTAB=${c.estab}, ${c.unattributable} unattributable — default-deny`); censusDeny = true; } for (const row of c.foreign) { censusLines.push( `:${port} direct consumer pid ${row.ownerPid} comm ${row.ownerComm ?? "?"} (${row.local} -> ${row.peer}) — pid is neither the listener owner nor the controller, default-deny`, ); censusDeny = true; } censusLines.push(...(await strataSlots(cfg, port))); } // T006C MINOR-1: cap the rendered census lines (the deny gate above/below is untouched). notes.push( ...(censusLines.length ? capLines(censusLines) : [`census clean: ${evictionSet.length} model(s), 0 foreign ESTAB`]), ); if (censusDeny) { return refuse(notes); } const levelBefore = pi.getThinkingLevel(); const levelTarget = req.mode === "restore" ? (self.claim?.level ?? levelBefore) : (req.level ?? FALLBACK_LEVEL); const previous = self.claim?.bound ?? cfg.sessionDefault; // Steps 3-9: mutators. In dry-run every one of these prints instead of acting (§7.7). plan.push(`write claim {phase: armed, bound: ${previous}, previous: ${previous}, level: ${levelBefore}}`); plan.push(`setModel(${cfg.provider}/${req.target})`); plan.push(`setThinkingLevel(${levelTarget}) (level_before ${levelBefore} stored for the restore leg)`); plan.push(`write claim {phase: verifying, bound: ${req.target}}`); if (coldStartWarning) plan.push(coldStartWarning); plan.push(`POST ${cfg.controllerUrl}/v1/chat/completions {model: ${req.target}, max_tokens: 1}`); plan.push(`write claim {phase: committed, bound: ${req.target}}`); if (req.dryRun) { return { report: [`DRY-RUN — nothing touched`, ...notes, "", formatPlan(plan)].join("\n"), refused: false, committed: false, rolledBack: false, }; } // Step 3 — the entry phase. A forward swap enters `armed`; the go gate / restore leg // enters `restoring` (MAJOR-4: rolling_back -> armed is not a legal edge). const entryPhase: Phase = req.mode === "restore" ? "restoring" : "armed"; await writeClaim(me, mystart, selfPhase, entryPhase, req.mode === "restore" ? req.target : previous, levelBefore, req.target, previous); // Step 4 — MODEL FIRST // MAJOR-3 (T006): the RELEASE step the header documents. On the FORWARD leg a step-4 failure // means the binding was never moved — nothing was evicted, nothing is stranded — so the claim // is RELEASED: phase `idle`, bound = previous (the model we are still on). That is the write // that makes `idle` reachable and frees the card immediately instead of holding it until pid // death or the 1800 s staleness bound. On the RESTORE leg the session IS stranded on the model // the go gate left it on, so the honest phase stays `rolling_back` (the go gate remains the // only way out) — releasing there would claim a safety the session does not have. const step4Failure = async (entryPhase: Phase, why: string): Promise => { const release = req.mode === "forward"; const phase: Phase = release ? "idle" : "rolling_back"; await writeClaim(me, mystart, entryPhase, phase, previous, levelBefore, req.target, previous); return { report: `REFUSED — model ${cfg.provider}/${req.target} ${why}. Claim ${ release ? `released: {phase: idle, bound: ${previous}} (the binding was never moved)` : `left at {phase: rolling_back, bound: ${previous}} — the go gate is the only way out` }.`, refused: true, committed: false, rolledBack: true, }; }; const model = ctx.modelRegistry.find(cfg.provider, req.target); if (!model) { return await step4Failure(entryPhase, "is not in the registry (no such id, or not in enabledModels)"); } const modelSet = await pi.setModel(model); if (!modelSet) { // rev7 assumption 7: setModel false = no API key ⇒ failed step 4, never a verifying claim. return await step4Failure(entryPhase, "setModel returned false (no API key resolves)"); } // Step 5 — THINKING SECOND (§7.2: never silently inherit level_before on the forward leg) pi.setThinkingLevel(levelTarget); // Step 6 — claim + warning BEFORE the request that can evict await writeClaim(me, mystart, entryPhase, "verifying", req.target, levelBefore, req.target, previous); if (coldStartWarning) ctx.ui.notify(coldStartWarning, "warning"); // Step 7 const verify = await verifyRequest(pi, cfg, req.target, levelTarget, apiKey); if (verify.ok) { // Step 8 await writeClaim(me, mystart, "verifying", "committed", req.target, levelBefore, req.target, previous); return { report: [`SWAPPED → ${cfg.provider}/${req.target} @ ${levelTarget}`, ...notes, `verify: ${verify.detail}`].join("\n"), refused: false, committed: true, rolledBack: false, }; } // Step 9 → §7.8 await writeClaim(me, mystart, "verifying", "rolling_back", req.target, levelBefore, req.target, previous); return { report: [ `VERIFY FAILED — ${verify.detail}`, coldStartWarning || "This swap evicts nothing (the target is the resident model); the verify request failed.", `claim {phase: rolling_back, bound: ${req.target}}`, `options: (1) restore to ${previous} now = full cold start; (2) leave the binding and let the next request pay it.`, `no restore executes without your go: /swap ${previous} --go`, ].join("\n"), refused: false, committed: false, rolledBack: true, }; } /** Claim-file constraints on a model in the eviction set (self-claim excluded, §7.3). */ async function claimConstraints(id: string, cfg: SwapConfig, me: number): Promise { const out: string[] = []; for (const pid of await listClaimPids()) { if (pid === me) continue; const rc = await readClaim(pid, cfg); if (rc.unreadable || (!rc.live && !rc.expired)) continue; if (rc.live && !rc.expired && CONSTRAINING_PHASES.includes(rc.claim!.phase) && rc.claim!.bound === id) { out.push(`pid ${pid} (phase ${rc.claim!.phase}) is bound to ${id} — unloading it strands that session`); } } return out; } /** * Strata corroboration only (§7.4): `/slots` belongs to Strata, not llama-swap. * Informational — the census never depends on it, and `:1235/slots` is never polled. */ async function strataSlots(cfg: SwapConfig, port: number): Promise { if (port !== cfg.strataPort) return []; try { const res = await fetch(`http://127.0.0.1:${cfg.strataPort}/slots`, { signal: AbortSignal.timeout(5_000) }); const body = await res.text(); if (!res.ok) return [`:${port}/slots (model server) status ${res.status} — corroboration skipped`]; return [`:${port}/slots (model server) ${body.slice(0, 160)}`]; } catch (err) { return [`:${port}/slots (model server) not reachable (${err instanceof Error ? err.message : String(err)}) — corroboration skipped`]; } } // --------------------------------------------------------------------------- // Argument parsing for /swap // --------------------------------------------------------------------------- interface ParsedArgs { target?: string; level?: SwapLevel; dryRun: boolean; go: boolean; restore: boolean; status: boolean; } const LEVELS: readonly SwapLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; function parseArgs(raw: string): ParsedArgs { const out: ParsedArgs = { dryRun: false, go: false, restore: false, status: false }; for (const token of raw.trim().split(/\s+/).filter(Boolean)) { if (token === "--dry-run") out.dryRun = true; else if (token === "--go") out.go = true; else if (token === "--restore") out.restore = true; else if (token === "--status") out.status = true; else if ((LEVELS as readonly string[]).includes(token)) out.level = token as SwapLevel; else if (!out.target) out.target = token; } return out; } function stripProvider(id: string, provider: string): string { return id.startsWith(`${provider}/`) ? id.slice(provider.length + 1) : id; } // --------------------------------------------------------------------------- // Extension // --------------------------------------------------------------------------- export default function modelSwapExtension(pi: ExtensionAPI): void { let cfg = DEFAULT_CONFIG; let boundaryRestoreArmed = false; // MAJOR-5 (T006): a corrupt pi-model-swap.json used to fall through to DEFAULT_CONFIG, which // is PRODUCTION (controller :1235, the real roster). Parse failure now sets a flag and every // mutator is gated on it — the inverse of fail-closed is the dangerous direction. let cfgUnreadable = false; let cfgPath = ""; let cfgError = ""; const load = async (): Promise => { const r = await loadConfig(); cfg = r.cfg; cfgUnreadable = r.unreadable; cfgPath = r.path; cfgError = r.error; }; const cfgRefusal = (): SwapOutcome => ({ report: formatRefusal([ `config ${cfgPath} is unreadable/unparseable (${cfgError}) — fail closed, nothing runs`, `no fallback defaults are configured (controller/roster/provider/sessionDefault are required keys); this session is NOT aimed at any controller until the config parses`, `fix the JSON at ${cfgPath} (or unset PI_MODEL_SWAP_CONFIG) and re-run`, ]), refused: true, committed: false, rolledBack: false, }); const statusReport = async (): Promise => { const me = process.pid; const self = await readClaim(me, cfg); const lines = [ cfgUnreadable ? `config: UNREADABLE (${cfgPath}) — ${cfgError} — fail closed, every swap refuses` : `config: ${cfgPath}`, `controller: ${cfg.controllerUrl} roster: ${cfg.rosterPath} startPort: ${cfg.startPort}`, `session default: ${cfg.provider}/${cfg.sessionDefault} my pid: ${me}`, self.unreadable ? `my claim: UNREADABLE (fail closed)` : self.claim ? `my claim: phase ${self.claim.phase} bound ${self.claim.bound} target ${self.claim.target ?? "-"} level ${self.claim.level ?? "-"} live ${self.live} expired ${self.expired}` : "my claim: none (idle)", ]; for (const pid of await listClaimPids()) { if (pid === me) continue; const rc = await readClaim(pid, cfg); lines.push( rc.unreadable ? `pid ${pid}: UNREADABLE (fail closed)` : `pid ${pid}: phase ${rc.claim?.phase} bound ${rc.claim?.bound} live ${rc.live} expired ${rc.expired}`, ); } return lines.join("\n"); }; const doSwap = async ( req: SwapRequest, ctx: ExtensionContext, ): Promise => { await load(); if (cfgUnreadable) return cfgRefusal(); return runSwap(pi, cfg, req, ctx); }; // --- tool --------------------------------------------------------------- pi.registerTool({ name: "model_swap", label: "Model Swap", description: "Swap this pi session to another llama-swap model (model first, thinking second). Refuses when the eviction set contains a model a live session is bound to. dry_run touches nothing.", promptSnippet: "Swap the session's model through llama-swap, with a refusal gate and dry-run", promptGuidelines: [ "Use model_swap with dry_run true first to see what a swap would do; it touches nothing.", "model_swap never starts, stops, or signals llama-swap; a refusal means a live session is bound to a model the swap would evict.", "After a swap, the session auto-restores to the session default at a turn boundary only on the go path.", ], parameters: Type.Object({ model: Type.Optional(Type.String({ description: "Target model id under the llama-swap provider, e.g. coder-non-thinking" })), level: Type.Optional(StringEnum(LEVELS as unknown as [SwapLevel, ...SwapLevel[]], { description: "Target thinking level" })), dry_run: Type.Optional(Type.Boolean({ description: "Print the refusal/plan, touch nothing" })), go: Type.Optional(Type.Boolean({ description: "Explicit go for a restore from rolling_back" })), restore: Type.Optional(Type.Boolean({ description: "Restore leg: go to the session default / claim.bound" })), }), async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const req = toRequest(params, cfg); if (!req) { return { content: [{ type: "text", text: "model_swap: `model` is required unless --status / restore is used" }], details: { refused: true, committed: false } }; } const outcome = await doSwap(req, ctx); return { content: [{ type: "text", text: outcome.report }], details: { refused: outcome.refused, committed: outcome.committed } }; }, }); // --- command ------------------------------------------------------------ pi.registerCommand("swap", { description: "Swap model through llama-swap: /swap [level] [--dry-run] [--go] [--restore] [--status]", getArgumentCompletions: (prefix: string) => { const flags = ["--dry-run", "--go", "--restore", "--status"].map((v) => ({ value: v, label: v })); const items = [...LEVELS.map((v) => ({ value: v, label: `level ${v}` })), ...flags]; const filtered = items.filter((i) => i.value.startsWith(prefix)); return filtered.length > 0 ? filtered : null; }, handler: async (args: string, ctx: ExtensionCommandContext) => { await load(); if (cfgUnreadable) { ctx.ui.notify(cfgRefusal().report, "warning"); return; } const a = parseArgs(args); if (a.status) { ctx.ui.notify(await statusReport(), "info"); return; } const target = a.target ? stripProvider(a.target, cfg.provider) : undefined; if (!target) { ctx.ui.notify("usage: /swap [level] [--dry-run] [--go] [--restore] [--status]", "info"); return; } const req: SwapRequest = { target, level: a.level, dryRun: a.dryRun, go: a.go, mode: a.restore ? "restore" : "forward", }; const outcome = await doSwap(req, ctx); ctx.ui.notify(outcome.report, outcome.refused ? "warning" : "info"); }, }); // --- §7.6 auto-restore: turn boundary only ------------------------------ // Announce at one boundary, execute at the next. The boundary leg is one of the // two go paths rev7 §7.8 enumerates, so executing it is Adam's go, not an // automatic rollback. pi.on("agent_settled", async (_event, ctx) => { await load(); if (cfgUnreadable) return; // MAJOR-5: never act on defaults that point at production if (!cfg.boundaryRestore) return; const self = await readClaim(process.pid, cfg); if (self.unreadable || !self.claim || !self.live || self.expired) return; if (self.claim.phase === "committed" && self.claim.bound === cfg.sessionDefault) { boundaryRestoreArmed = false; return; } if (self.claim.phase !== "committed" && self.claim.phase !== "rolling_back") return; const restoreTarget = cfg.sessionDefault; // MINOR-2 (T006): §7.6 always restores the session default if (!boundaryRestoreArmed) { boundaryRestoreArmed = true; ctx.ui.notify( `session default is ${cfg.provider}/${cfg.sessionDefault}, this session is on ${self.claim.bound} — restore at the next boundary (or /swap ${cfg.sessionDefault} --go now)`, "info", ); return; } const outcome = await doSwap({ target: restoreTarget, dryRun: false, go: true, mode: "restore" }, ctx); ctx.ui.notify(outcome.report, outcome.refused ? "warning" : "info"); boundaryRestoreArmed = false; }); pi.on("session_start", async (_event, ctx) => { await load(); if (cfgUnreadable) ctx.ui.notify(cfgRefusal().report, "warning"); void ctx; }); } function toRequest(params: { model?: string; level?: SwapLevel; dry_run?: boolean; go?: boolean; restore?: boolean; }, cfg: SwapConfig): SwapRequest | undefined { const restore = params.restore === true; const target = params.model ? stripProvider(params.model, cfg.provider) : undefined; if (!target && !restore) return undefined; return { target: target ?? cfg.sessionDefault, level: params.level, dryRun: params.dry_run === true, go: params.go === true, mode: restore ? "restore" : "forward", }; }