@0perator/operator 0.1.360-next.1 → 0.1.360-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,7 @@ import { homedir, userInfo } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { ToolchainError, isManaged, resolveToolchainBin, storeEntryMeta, storeEntryOf, verifyState } from "./config/toolchain.js";
9
9
  import { formatAge } from "./memory/session-catalog.js";
10
+ import { isLaunchdDisabled } from "./services/preflight.js";
10
11
  const LABEL = "co.0perator.gateway";
11
12
  function paths() {
12
13
  const home = process.env.OPERATOR_HOME || join(homedir(), ".operator"); // the runtime's home, not the CLI's config home
@@ -40,7 +41,10 @@ function server(file) {
40
41
  return undefined;
41
42
  }
42
43
  }
43
- const launchctl = (...args) => spawnSync("launchctl", args, { stdio: "ignore" }).status ?? 1;
44
+ const realLaunchctl = (args) => {
45
+ const r = spawnSync("launchctl", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
46
+ return { status: r.status ?? 1, out: r.stdout ?? "" };
47
+ };
44
48
  const domain = () => `gui/${userInfo().uid}`;
45
49
  /** What the gateway will launch: on a managed box the aurora consumer's binary or nothing; otherwise the legacy chain's
46
50
  * links (the PATH lookup that ends that chain happens inside the gateway, with the gateway's own PATH). */
@@ -83,7 +87,7 @@ const USAGE = `usage: operator gateway {start [-d]|stop|status|health|logs}
83
87
  status gateway, llama-server, models, binary and toolchain
84
88
  health llama-server /health
85
89
  logs follow the gateway and llama-server logs`;
86
- export async function runGateway(args, out = (s) => process.stdout.write(s + "\n")) {
90
+ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n"), launchctl = realLaunchctl) {
87
91
  const p = paths();
88
92
  const [cmd = "status", ...rest] = args;
89
93
  switch (cmd) {
@@ -93,15 +97,20 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
93
97
  out(`${p.plist} is not installed — run operator-runtime/scripts/install.sh first.`);
94
98
  return 1;
95
99
  }
96
- launchctl("bootstrap", domain(), p.plist);
97
- const code = launchctl("kickstart", "-k", `${domain()}/${LABEL}`);
100
+ const disabled = launchctl(["print-disabled", domain()]);
101
+ if (disabled.status === 0 && isLaunchdDisabled(disabled.out, LABEL)) {
102
+ out(`${LABEL} is disabled in launchd — not starting it (launchctl enable ${domain()}/${LABEL} first if you mean to)`);
103
+ return 1;
104
+ }
105
+ launchctl(["bootstrap", domain(), p.plist]);
106
+ const code = launchctl(["kickstart", "-k", `${domain()}/${LABEL}`]).status;
98
107
  out(code === 0 ? "gateway started through launchd" : "launchctl kickstart failed");
99
108
  return code;
100
109
  }
101
110
  return spawnSync(process.execPath, [p.gateway, ...rest], { stdio: "inherit" }).status ?? 1;
102
111
  }
103
112
  case "stop": {
104
- launchctl("bootout", `${domain()}/${LABEL}`);
113
+ launchctl(["bootout", `${domain()}/${LABEL}`]);
105
114
  const gw = readPid(p.bootLock);
106
115
  const llama = server(p.serverJson)?.pid;
107
116
  for (const pid of [gw, llama])
@@ -13,7 +13,18 @@
13
13
  import { LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
14
14
  /** Fallback walk order, strongest → cheapest. */
15
15
  export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
16
+ /** The Aurora row whose endpoints are the shell's own chain (endpoints.aurora + its failover legs). Since 0.1.361 it is
17
+ * no longer the model a fresh install starts on — that is DEFAULT_ACTIVE_MODEL. */
16
18
  export const DEFAULT_MODEL_ID = "operator-1m";
19
+ /** The model a session starts on when settings.activeModel is not set (a fresh install): the router's
20
+ * `operator-flash` route. A persisted activeModel always wins. */
21
+ export const DEFAULT_ACTIVE_MODEL = "operator-flash";
22
+ /** Rows retired from the picker (11/25): never in /model or the ACP dropdown, still resolvable by id so a persisted
23
+ * activeModel, a script or a delegate target keeps working. A settings.models row with one of these ids is hidden too
24
+ * unless it says `hidden: false`. */
25
+ export const RETIRED_MODEL_IDS = new Set([
26
+ "operator-1m", "aurora", "cortana", "thor", "scout", "casanova", "falcon-h1-34b", "qwen-coder", "belmont-30b", "venice-24b", "dolphin-7b",
27
+ ]);
17
28
  // Back-compat aliases: the user-facing ids were renamed aurora-* -> operator-* (the outward name is
18
29
  // Operator; "aurora" is the internal model, never shown). The OLD ids still resolve — a persisted
19
30
  // settings.activeModel: "aurora-1m", a `/model aurora-1m`, or any muscle memory keeps working — so the
@@ -45,27 +56,32 @@ const QWEN_BASE = "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
45
56
  export const ANTHROPIC_MAX_OUTPUT = 128_000;
46
57
  const QWEN_FLASH_MAX_OUTPUT = 131_072;
47
58
  const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
48
- // Registry order IS picker order (visibleModels keeps it): the local row, then the gateway rows, then the
59
+ // Registry order IS picker order (visibleModels keeps it): the main three, the local row, then the gateway rows, then the
49
60
  // connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
50
61
  // vendor rows (tier "free") arrive at runtime through Session.dynamicModels and land after all of these.
51
62
  // A deployment's own servers (direct endpoints, owner-only trials, its labels and descriptions) are NOT listed
52
63
  // here: they come from settings.models, which adds rows and overrides these by id (modelRegistry).
53
64
  export const BUILTIN_MODELS = [
65
+ // ── main (0.1.361): the three /model rows, in this order (ui/modelPicker.ts MAIN_MODEL_IDS) ─────────────────
66
+ // Router routes of the same name, gateway-first like every gateway row. `ctx` is the window the route serves.
67
+ { id: "operator-flash", tier: "power", label: "Operator-Flash", params: "125B-A6B", box: "gateway", kind: "single", desc: "the default model: a fast MoE with n-gram speculation", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-flash", "operator-flash"], model: "operator-flash", ctx: 131072 },
68
+ { id: "kimi-linear-48b", tier: "power", label: "Kimi-Linear", params: "48B-A3B", box: "gateway", kind: "single", desc: "long-context MoE", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["kimi-linear-48b", "kimi-linear-48b"], model: "kimi-linear-48b", ctx: 262144 },
69
+ { id: "qwen3.8-27b", tier: "power", label: "Qwen3.8", params: "27B", box: "gateway", kind: "single", desc: "dense model with n-gram and MTP speculation; loads on demand", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["qwen3.8-27b", "qwen3.8-27b"], model: "qwen3.8-27b", ctx: 131072 },
54
70
  // ── local ───────────────────────────────────────────────────────────────────────────────────────────────
55
- // THE one Aurora row (0.1.332). The 300K/600K/1M choice is a context PIN (settings.contextPin, /context,
56
- // Ctrl+X) applied over the served window — not three profiles of one model. The static :8097 is the
57
- // gateway-less fallback; on a gateway box Session.setModel restores the shell's chain for this id (the
58
- // dynamic port + the fleet and cloud legs buildEndpointChain assembles).
59
- { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "local", kind: "single", desc: "the default model, served on this machine; the gateway takes over when it is down", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000 },
71
+ // THE one Aurora row (0.1.332), retired from the picker 11/25 (RETIRED_MODEL_IDS). The 300K/600K/1M choice is a
72
+ // context PIN (settings.contextPin, /context, Ctrl+X) applied over the served window — not three profiles of one
73
+ // model. The static :8097 is the gateway-less fallback; on a gateway box Session.setModel restores the shell's chain
74
+ // for this id (the dynamic port + the fleet and cloud legs buildEndpointChain assembles).
75
+ { id: "operator-1m", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "local", kind: "single", desc: "served on this machine; the gateway takes over when it is down", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000, hidden: true },
60
76
  // ── gateway ─────────────────────────────────────────────────────────────────────────────────────────────
61
77
  // GATEWAY-FIRST: the local gateway when this machine runs one, then the public face. `ctx` is the window the
62
78
  // gateway serves. The 0.1.260 lesson stands: a profile that claims MORE than the server's --ctx-size makes the
63
79
  // engine overrun the wall and the server cuts a round mid-tool-call (0.1.259) — change a number ONLY when the
64
- // served window changes.
65
- { id: "cortana", tier: "power", label: "Cortana", params: "35B-A3B", box: "gateway", kind: "single", desc: "general model with vision", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["cortana", "cortana"], model: "cortana", ctx: 262144 },
80
+ // served window changes. cortana, thor and scout are retired from the picker (RETIRED_MODEL_IDS) and resolve by id.
81
+ { id: "cortana", tier: "power", label: "Cortana", params: "35B-A3B", box: "gateway", kind: "single", desc: "general model with vision", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["cortana", "cortana"], model: "cortana", ctx: 262144, hidden: true },
66
82
  { id: "gpt-oss-20b", tier: "economy", label: "gpt-oss", params: "20B-A3.6B", box: "gateway", kind: "single", desc: "OpenAI gpt-oss-20b — the MoA specialist", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["gpt-oss-20b", "gpt-oss-20b"], model: "gpt-oss-20b", ctx: 65536 },
67
- { id: "thor", tier: "power", label: "Thor", params: "32B", box: "gateway", kind: "single", desc: "reasoning model — thinks before answering", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["thor", "thor"], model: "thor", ctx: 32768 },
68
- { id: "scout", tier: "lite", label: "Scout", params: "4B", box: "gateway", kind: "single", desc: "fast small model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["scout", "scout"], model: "scout", ctx: 32000 },
83
+ { id: "thor", tier: "power", label: "Thor", params: "32B", box: "gateway", kind: "single", desc: "reasoning model — thinks before answering", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["thor", "thor"], model: "thor", ctx: 32768, hidden: true },
84
+ { id: "scout", tier: "lite", label: "Scout", params: "4B", box: "gateway", kind: "single", desc: "fast small model", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["scout", "scout"], model: "scout", ctx: 32000, hidden: true },
69
85
  // ── connected providers (BYO: hidden until the vendor key is connected — /model "+ Connect a provider key") ──
70
86
  // Claude — BYO Anthropic connectors, so "delegate to Claude" and `/model claude-sonnet` work. Unlike the
71
87
  // qwen/OpenAI connectors (OpenAI dialect), Claude speaks the NATIVE Anthropic Messages wire — transport
@@ -132,14 +148,32 @@ export function modelRegistry(overrides) {
132
148
  if (!overrides?.length)
133
149
  return BUILTIN_MODELS;
134
150
  const byId = new Map(BUILTIN_MODELS.map((m) => [m.id, m]));
135
- for (const m of overrides)
136
- byId.set(m.id, { ...byId.get(m.id), ...m });
151
+ for (const m of overrides) {
152
+ const merged = { ...byId.get(m.id), ...m };
153
+ byId.set(m.id, RETIRED_MODEL_IDS.has(m.id) && merged.hidden === undefined ? { ...merged, hidden: true } : merged);
154
+ }
137
155
  return [...byId.values()];
138
156
  }
139
157
  export function findModel(registry, id) {
140
158
  const canon = MODEL_ALIASES[id] ?? id; // aurora-1m -> operator-1m (old ids keep resolving)
141
159
  return registry.find((m) => m.id === canon);
142
160
  }
161
+ /** The router capability a failed turn falls back to when settings.fallbackModel is unset (11/25: the gateway's `main`
162
+ * route — Kimi/Athena behind the router — replaced the launchd-owned Aurora row as the fallback). */
163
+ export const DEFAULT_FALLBACK_MODEL = "main";
164
+ /** The model that answers a turn whose own legs all failed (Session.turnModel). A registry row with that id answers as
165
+ * itself; any other id is a router capability, reached through the gateway (loopback first, then the public face).
166
+ * Never the launchd-owned default row: a fallback must not wake a model the owner parked, so that id resolves to the
167
+ * default capability instead. */
168
+ export function fallbackProfile(registry, id) {
169
+ const want = id?.trim() || DEFAULT_FALLBACK_MODEL;
170
+ const canon = MODEL_ALIASES[want] ?? want;
171
+ const name = canon === DEFAULT_MODEL_ID ? DEFAULT_FALLBACK_MODEL : canon;
172
+ const row = findModel(registry, name);
173
+ if (row?.kind === "single")
174
+ return row;
175
+ return { id: name, label: name, box: "gateway", kind: "single", desc: "router capability", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: [name, name], model: name };
176
+ }
143
177
  /** The tier of a model id (alias-aware), or undefined when the profile has none. */
144
178
  export function tierOf(registry, id) {
145
179
  return findModel(registry, id)?.tier;
@@ -18,6 +18,17 @@
18
18
  // • SearXNG is session-scoped and owned by tools/searxng.ts (lazy start + idle/exit stop) — the only
19
19
  // service Operator tears down, via stopSessionServices() below.
20
20
  const nodeImport = (m) => import(/* @vite-ignore */ m);
21
+ /** True when `launchctl print-disabled` output lists `label` as disabled (`"label" => disabled`, or `true` on older
22
+ * macOS). A job the owner disabled is never started by Operator: `kickstart -k` would run a disabled job that is still
23
+ * loaded, and `enable` + `bootstrap` would undo the owner's `launchctl disable`. */
24
+ export function isLaunchdDisabled(printDisabled, label) {
25
+ const esc = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
+ return new RegExp(`"${esc}"\\s*=>\\s*(disabled|true)\\b`).test(printDisabled);
27
+ }
28
+ /** The one line a turn shows when the job it needs is disabled. */
29
+ export function disabledLine(name, label) {
30
+ return `${name} is disabled in launchd (${label}) — not starting it; using the next backend`;
31
+ }
21
32
  function expandHome(p) {
22
33
  return p.startsWith("~/") ? `${process.env.HOME ?? ""}${p.slice(1)}` : p;
23
34
  }
@@ -128,21 +139,26 @@ async function kickLaunchd(name, cfg, onProgress) {
128
139
  }
129
140
  return { name, state: "skipped", detail: `not installed (${expandHome(cfg.plistPath)} missing) — run: operator setup-services` };
130
141
  }
142
+ const run = cfg.launchctl ?? launchctl;
143
+ const disabled = await run(["print-disabled", `gui/${uid}`]);
144
+ if (disabled.code === 0 && isLaunchdDisabled(disabled.out, label))
145
+ return { name, state: "disabled", detail: disabledLine(name, label) };
131
146
  onProgress?.(`starting ${name} via launchd…`);
132
147
  const target = `gui/${uid}/${label}`;
133
148
  // 1) fast path: the job is loaded but its port died — kick it.
134
- const kick = await launchctl(["kickstart", "-k", target]);
149
+ const kick = await run(["kickstart", "-k", target]);
135
150
  if (kick.code !== 0) {
136
151
  // 2) not cleanly loaded — clear any half-state (bootout, ignore "no such process") then bootstrap
137
152
  // the plist fresh and start it. Tolerate the known bootstrap I/O-error(5) race: the job usually
138
- // still lands in the domain, so we poll the port regardless of the exit code.
153
+ // still lands in the domain, so we poll the port regardless of the exit code. `enable` clears a
154
+ // stale override only: a job the owner disabled was refused above.
139
155
  if (!cfg.plistPath)
140
156
  return { name, state: "down", detail: `down (kickstart failed: ${kick.out.slice(0, 80)}; no plistPath to bootstrap)` };
141
- await launchctl(["bootout", target]).catch(() => undefined);
157
+ await run(["bootout", target]).catch(() => undefined);
142
158
  await new Promise((res) => setTimeout(res, 1500)); // let the old proc release the port + mlock
143
- await launchctl(["enable", target]);
144
- await launchctl(["bootstrap", `gui/${uid}`, expandHome(cfg.plistPath)]);
145
- await launchctl(["kickstart", target]);
159
+ await run(["enable", target]);
160
+ await run(["bootstrap", `gui/${uid}`, expandHome(cfg.plistPath)]);
161
+ await run(["kickstart", target]);
146
162
  }
147
163
  return null;
148
164
  }
@@ -228,14 +244,21 @@ export async function waitForAurora(cfg, waitSec, signal) {
228
244
  /** The Session's onDemand hook for a local Aurora: before a turn on the default model, make sure the gateway is
229
245
  * serving (start it if not), and when its published base or key changed write them onto `endpoint` and return
230
246
  * `rebuild()`. Inert where Aurora is not a local launchd job, so a remote endpoint is never probed per turn. */
231
- export function auroraOnDemand(endpoint, svc, rebuild, onProgress) {
247
+ export function auroraOnDemand(endpoint, svc, rebuild, onProgress, onDisabled) {
232
248
  let local;
249
+ let told = false;
233
250
  return async (signal) => {
234
251
  local ??= localAuroraJob(svc ?? {});
235
252
  if (!(await local))
236
253
  return null;
237
254
  const cfg = { ...svc, base: endpoint.base, apiKey: endpoint.apiKey };
238
- await ensureAurora(cfg, onProgress, signal);
255
+ const report = await ensureAurora(cfg, onProgress, signal);
256
+ if (report.state === "disabled") {
257
+ if (!told && report.detail)
258
+ onDisabled?.(report.detail); // once per session: the router's next leg answers every turn
259
+ told = true;
260
+ return null;
261
+ }
239
262
  if (cfg.base === endpoint.base && cfg.apiKey === endpoint.apiKey)
240
263
  return null;
241
264
  endpoint.base = cfg.base;
package/dist/session.js CHANGED
@@ -9,6 +9,7 @@ import { homedir } from "node:os";
9
9
  import { chat, health, reachable, gateKey, isRemoteBase, shipsLlamaCacheKnobs, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
10
10
  import { claimSlot, releaseSlot } from "./engine/kv-slot.js";
11
11
  import { randomUUID } from "node:crypto";
12
+ import { recordDecodeSample, speedCompactionDue } from "./engine/speed-compaction.js";
12
13
  import { compact, compactionSplit, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
13
14
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
14
15
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
@@ -24,7 +25,7 @@ import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0
24
25
  import { AuroraRouter } from "./router/router.js";
25
26
  import { operatorAgentPersona } from "./config/operator-harness.js";
26
27
  import { progressDeadline, summaryCeilingMs, DeadlineError } from "./engine/progress-deadline.js";
27
- import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
28
+ import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
28
29
  import { probeServed, usableCtx } from "./router/discovery.js";
29
30
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
30
31
  import { askFrontDoor, recentTurns } from "./engine/front-door.js";
@@ -429,6 +430,9 @@ export class Session {
429
430
  maxRoundsHard;
430
431
  compactionThreshold;
431
432
  compactionCeilingTokens;
433
+ compactionMinDecodeTps;
434
+ decodeSamples = []; // the last measured turns' decode, for the speed trigger
435
+ fallbackModelId; // settings.fallbackModel (turnModel)
432
436
  background;
433
437
  owner;
434
438
  temperature;
@@ -574,6 +578,8 @@ export class Session {
574
578
  this.maxRoundsHard = cfg.maxRoundsHard;
575
579
  this.compactionThreshold = cfg.compactionThreshold;
576
580
  this.compactionCeilingTokens = cfg.compactionCeilingTokens;
581
+ this.compactionMinDecodeTps = cfg.compactionMinDecodeTps;
582
+ this.fallbackModelId = cfg.fallbackModel;
577
583
  this.contextFloor = cfg.contextFloor ?? AGENT_CTX_FLOOR;
578
584
  this.background = cfg.background ?? false;
579
585
  this.owner = cfg.owner;
@@ -1047,6 +1053,7 @@ export class Session {
1047
1053
  /** Reset the conversation to empty (for /new). */
1048
1054
  reset() {
1049
1055
  this.convo.replaceAll([]);
1056
+ this.decodeSamples = [];
1050
1057
  this.rollingSummarizer.clear(); // clear the rolling summary on new session
1051
1058
  this.planApproval.clear(); // a fresh conversation has no reviewed plan
1052
1059
  this.planReviewTold = false; // …and has not been told the mode
@@ -1096,7 +1103,7 @@ export class Session {
1096
1103
  /** The model answering this turn — the /model pick, or the default row once the pick's fallback took the turn — so a
1097
1104
  * read or decode rate is credited to the model that did the work, never to the owner's pick. */
1098
1105
  answeringModel() {
1099
- return this.turnFellBack ? DEFAULT_MODEL_ID : this.modelId;
1106
+ return this.turnFellBack ? fallbackProfile(this.liveRegistry(), this.fallbackModelId).id : this.modelId;
1100
1107
  }
1101
1108
  /** The endpoint chain for a single-endpoint profile (/model, and the MoA specialist's fast path). */
1102
1109
  routerForProfile(profile) {
@@ -1125,17 +1132,19 @@ export class Session {
1125
1132
  return new AuroraRouter(eps);
1126
1133
  }
1127
1134
  /** A turn's model as the owner reads it, and its fallback (runTurn's TurnModel): when every leg of another model
1128
- * fails, or it keeps finishing with nothing, the default Aurora row answers that turn — the owner's choice stays, so
1129
- * the next turn tries the chosen model first again. A row with `fallback: false` keeps its turns on its own legs. */
1135
+ * fails, or it keeps finishing with nothing, settings.fallbackModel answers that turn (default: the router's `main`,
1136
+ * never the launchd-owned Aurora row) — the owner's choice stays, so the next turn tries the chosen model first again.
1137
+ * A row with `fallback: false`, or the fallback itself, keeps its turns on its own legs. */
1130
1138
  turnModel(id) {
1131
1139
  const reg = this.liveRegistry();
1132
1140
  const profile = findModel(reg, id);
1133
1141
  if (profile?.kind !== "single")
1134
1142
  return undefined;
1135
- const aurora = profile.id === DEFAULT_MODEL_ID || profile.fallback === false ? undefined : findModel(reg, DEFAULT_MODEL_ID);
1143
+ const fb = fallbackProfile(reg, this.fallbackModelId);
1144
+ const use = profile.id === fb.id || profile.fallback === false ? undefined : fb;
1136
1145
  return {
1137
1146
  name: profile.label,
1138
- fallback: aurora ? () => { this.turnFellBack = true; return { name: aurora.label, router: this.wrap(this.chain ?? this.routerForProfile(aurora)) }; } : undefined,
1147
+ fallback: use ? () => { this.turnFellBack = true; return { name: use.label, router: this.wrap(this.routerForProfile(use)) }; } : undefined,
1139
1148
  };
1140
1149
  }
1141
1150
  /** Switch the active model (/model). A "single" profile rebuilds the router to point at that
@@ -1147,6 +1156,7 @@ export class Session {
1147
1156
  const { profile, error } = selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner);
1148
1157
  if (error || !profile)
1149
1158
  return { ok: false, error };
1159
+ this.decodeSamples = []; // another model's rate says nothing about this one
1150
1160
  if (profile.kind === "orchestrated" && !moaTeam(this.moaConfig)) {
1151
1161
  return { ok: false, error: `MOA needs a "moa" block (planner + specialist) in settings.json` };
1152
1162
  }
@@ -1498,6 +1508,9 @@ export class Session {
1498
1508
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1499
1509
  }
1500
1510
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1511
+ if (this.ctrl.signal.aborted)
1512
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1513
+ await this.maybeSpeedCompact(h);
1501
1514
  if (this.ctrl.signal.aborted)
1502
1515
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1503
1516
  this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
@@ -1517,6 +1530,32 @@ export class Session {
1517
1530
  this.turnThinkOff = false;
1518
1531
  }
1519
1532
  }
1533
+ /** Speed-aware compaction: the last measured turns decoded under compaction.minDecodeTps at a request big enough
1534
+ * for compaction to help, so compact now, before this turn's first request. The samples are cleared either way, so
1535
+ * the next trigger needs two fresh slow turns. A failed summarizer leaves the conversation as it was. */
1536
+ async maybeSpeedCompact(h) {
1537
+ const due = speedCompactionDue(this.decodeSamples, this.compactionMinDecodeTps, this.requestEstimate());
1538
+ if (!due)
1539
+ return;
1540
+ this.decodeSamples = [];
1541
+ h.onSpeedCompaction?.(due);
1542
+ const before = due.ctxTokens;
1543
+ h.onCompactionStart?.({ before });
1544
+ this.turnHandlers = h;
1545
+ let skipped;
1546
+ try {
1547
+ await this.compactNowInner();
1548
+ }
1549
+ catch {
1550
+ skipped = "summarizer_error"; // the turn still runs; the window-fill gate stays the backstop
1551
+ }
1552
+ finally {
1553
+ this.turnHandlers = undefined;
1554
+ const after = this.requestEstimate();
1555
+ this.telemetry.record({ type: "compaction", before, after, trigger: "decode", tps: Math.round(due.tps * 10) / 10, floorTps: due.floorTps, ...(skipped ? { skipped } : {}) });
1556
+ h.onCompactionEnd?.({ before, after });
1557
+ }
1558
+ }
1520
1559
  /** The front door (engine/front-door.ts). On the default model and MOA, the gateway answers a message its classifier
1521
1560
  * is confident needs no tools with its fast model in this session's voice; the reply joins the conversation like any
1522
1561
  * other. Returns null to run the turn as usual: the gateway says work (the owner sees its status line at once), it
@@ -1710,7 +1749,7 @@ export class Session {
1710
1749
  onServed: h.onServed,
1711
1750
  onSelfHeal: (kind, attempt, step) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt, step); },
1712
1751
  model: this.turnModel(turnModelId),
1713
- onFallback: (e) => { this.telemetry.record({ type: "model_fallback", from: turnModelId, to: DEFAULT_MODEL_ID, reason: e.reason, legs: e.legs.length }); h.onFallback?.(e); },
1752
+ onFallback: (e) => { this.telemetry.record({ type: "model_fallback", from: turnModelId, to: fallbackProfile(this.liveRegistry(), this.fallbackModelId).id, reason: e.reason, legs: e.legs.length }); h.onFallback?.(e); },
1714
1753
  onCompaction: (e) => { this.telemetry.record({ type: "compaction", ...e }); h.onCompaction?.(e); },
1715
1754
  onLoopCompaction: (e) => {
1716
1755
  if (e.replaced > 0)
@@ -1795,6 +1834,8 @@ export class Session {
1795
1834
  }
1796
1835
  }
1797
1836
  this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
1837
+ if (!this.turnFellBack)
1838
+ this.decodeSamples = recordDecodeSample(this.decodeSamples, { tokens: res.tokens, genMs: res.genMs, ctxTokens: this.requestEstimate() });
1798
1839
  // Instant compaction: feed token counts to the rolling summarizer. When a round ends without
1799
1840
  // tool calls and we've crossed the threshold, the summarizer triggers a background summary.
1800
1841
  const shouldSummarize = this.rollingSummarizer.feedRound(res.tokens ?? 0, res.toolCalls);