@0perator/operator 0.1.321 → 0.1.325

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.
@@ -237,7 +237,7 @@ export async function dispatchAutonomy(argv, settings) {
237
237
  // dynamic Aurora endpoint from the operator-runtime server.json AND brings the launchd gateway UP if it
238
238
  // is down. Mirror that FULL blueprint here — the same EnsureCfg (aurora launchd cfg + optional services) —
239
239
  // so a headless `operator run/loop/board/routine` on a cold box self-heals instead of failing with a
240
- // baseless "/v1/chat/completions" (Failed to parse URL) against the empty endpoints.aurora.base sentinel.
240
+ // baseless "/v1/chat/completions" (Failed to parse URL) against an unset (auto-discover) endpoints.aurora.base.
241
241
  // Guarded to the empty-base case (the only time we must discover/start), and gateway-aware: carry the
242
242
  // gateway's published api_key (server.json) onto the endpoint config so the router authenticates to it.
243
243
  if (!settings.endpoints.aurora.base) {
package/dist/cli.js CHANGED
@@ -822,7 +822,9 @@ function Root() {
822
822
  let reports = [];
823
823
  try {
824
824
  const preflight = await import("./services/preflight.js");
825
- const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
825
+ const bootBase = settings.endpoints.aurora.base; // "" = unset (auto-discover) until the gateway's published port resolves
826
+ const bootKeyBefore = settings.endpoints.aurora.apiKey;
827
+ const auroraCfg = { base: bootBase, ...settings.services?.aurora };
826
828
  reports = await preflight.ensureServices({
827
829
  aurora: auroraCfg,
828
830
  autopilot: settings.services?.autopilot,
@@ -839,6 +841,13 @@ function Root() {
839
841
  const bootKey = auroraCfg.apiKey;
840
842
  if (bootKey && !settings.endpoints.aurora.apiKey)
841
843
  settings.endpoints.aurora.apiKey = bootKey;
844
+ // The Session — and its router — were built at first render, while aurora.base was still ""
845
+ // (unset — auto-discover). Mutating settings alone leaves that router probing a blank base ("Can't reach Operator"
846
+ // with the gateway up, 0.1.321). Rebuild the chain from the resolved settings and swap it in — the
847
+ // order the headless factory gets for free (ensureServices, THEN buildRouterFromSettings).
848
+ if (settings.endpoints.aurora.base !== bootBase || settings.endpoints.aurora.apiKey !== bootKeyBefore) {
849
+ session.useRouter(buildRouter());
850
+ }
842
851
  // If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
843
852
  // eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
844
853
  if (reports.find((r) => r.name === "aurora")?.state === "started") {
@@ -2112,8 +2121,9 @@ function Root() {
2112
2121
  eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_no_token" } });
2113
2122
  break;
2114
2123
  }
2115
- const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
2116
- const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
2124
+ const { relayUrls, hostOf } = await import("./config/product-hosts.js");
2125
+ const urls = relayUrls(); // api.0perator.co first, api.axe.onl as fallback (KODE_RELAY_URL overrides, comma-separated)
2126
+ const rh = new RemoteHost(urls, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
2117
2127
  onPrompt: (text) => submitRef.current(text), // follower drives a turn
2118
2128
  onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
2119
2129
  onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
@@ -2139,7 +2149,7 @@ function Root() {
2139
2149
  onState: (st, detail) => {
2140
2150
  setRcConnected(st === "live"); // footer controller icon: green when live, gray otherwise
2141
2151
  if (st === "live")
2142
- sys(`✷ remote control LIVE — session ${rh.id}\n Continue on your phone or at https://0perator.co/session/${rh.id}\n /remotecontrol again to stop.`);
2152
+ sys(`✷ remote control LIVE via ${hostOf(rh.relayUrl)} — session ${rh.id}\n Continue on your phone or at https://0perator.co/session/${rh.id}\n /remotecontrol again to stop.`);
2143
2153
  // RC v2 A2: a drop is NOT a dead end — the host auto-reconnects to the SAME session id (no
2144
2154
  // re-mint). Show the quiet reconnecting state; only a genuine setup error is surfaced hard.
2145
2155
  else if (st === "connecting" && detail === "reconnecting")
@@ -2159,7 +2169,7 @@ function Root() {
2159
2169
  setRcActive(true);
2160
2170
  rh.setCapabilities(buildCapabilities()); // cached now, so the very first attach's snapshot already carries it
2161
2171
  rh.connect();
2162
- sys(`connecting remote control → ${url} …`);
2172
+ sys(`connecting remote control → ${hostOf(rh.relayUrl)} …`);
2163
2173
  break;
2164
2174
  }
2165
2175
  case "pair": {
@@ -2185,9 +2195,10 @@ function Root() {
2185
2195
  eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_no_token" } });
2186
2196
  break;
2187
2197
  }
2188
- const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
2198
+ const { relayUrls, hostOf } = await import("./config/product-hosts.js");
2199
+ const urls = relayUrls(); // api.0perator.co first, api.axe.onl as fallback (KODE_RELAY_URL overrides, comma-separated)
2189
2200
  const code = newCode();
2190
- const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
2201
+ const rh = new RemoteHost(urls, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
2191
2202
  onPrompt: (text) => submitRef.current(text),
2192
2203
  onApprovalResponse: (id, approve) => settleApproval(id, approve),
2193
2204
  onAskUserResponse: (id, answer) => settleQuestion(id, answer),
@@ -307,6 +307,12 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
307
307
  `progress / Next) so the owner sees where things stand at a glance without scrolling tool logs. This is ` +
308
308
  `Operator's Explanatory default: clarity, reasoning, and diagrams are the norm, not the exception — but ` +
309
309
  `keep every one of them tight, and never let the explanation delay or crowd out the tool calls themselves.`)) +
310
+ `\n## Task list — plan where the owner can see it\nFor multi-step work (3+ steps), or when the user gives several ` +
311
+ `tasks, write the plan FIRST with task_add — every step its own item, every "all N" instance enumerated — then ` +
312
+ `work it: exactly one task in_progress at a time (task_update), done only after you verified the step, never on ` +
313
+ `intent; a failed step is cancelled and replaced by a revised one. The list IS the plan and the owner watches it ` +
314
+ `live in the plan pane, so never restate the numbered plan in prose round after round — narrate only what you ` +
315
+ `are doing now.` +
310
316
  `\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT of each other, issue them as ` +
311
317
  `multiple tool calls in a SINGLE message so they run in parallel — including independent bash ` +
312
318
  `commands (they overlap for real; do NOT serialize unrelated shell work). Only serialize when one ` +
@@ -391,8 +397,11 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
391
397
  `when you're running low on context, call session_handoff to record what you did, the state, and the ` +
392
398
  `next steps: your next session in this directory loads it automatically, so write it for your future self.` +
393
399
  (opts.interactive
394
- ? `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
395
- `build) call spawn_agent (or delegate_task) with a fully self-contained instruction — it runs on another ` +
400
+ ? `\n## Sub-agents\nDecide and act in the SAME round: when the work splits into independent parts, call ` +
401
+ `spawn_agent NOW with every part in \`tasks\` (they run in parallel) — never write "I'll spawn sub-agents" or ` +
402
+ `"let me delegate" without making that call in the same round. For independent, parallelizable subtasks ` +
403
+ `(research per area, search a large tree, draft a file, a long build) give each a fully self-contained ` +
404
+ `instruction — it runs on another ` +
396
405
  `session in parallel and posts its result back here; keep working meanwhile. The user watches each ` +
397
406
  `sub-agent's live tokens + time in the background panel. Don't delegate trivial work you can do inline, ` +
398
407
  `and don't spawn many at once — they all share this one model.\n` +
@@ -0,0 +1,26 @@
1
+ // The product API host and its legacy fleet alias — ONE place for both names. They reach the same gateway
2
+ // (Cloudflare edge → JL2 Caddy :4100 → AuthGate verify → LiteLLM, and /session/ws → the RC relay), so the
3
+ // fallback covers an edge/zone failure of one NAME, never a different backend. Order matters: the product
4
+ // host first, the legacy host second. Both are trusted for the operator bearer in engine/aurora.ts
5
+ // (requiresOperatorToken) — keep that list in step with this one.
6
+ export const PRODUCT_API_HOST = "api.0perator.co";
7
+ export const LEGACY_API_HOST = "api.axe.onl";
8
+ export const API_HOSTS = [PRODUCT_API_HOST, LEGACY_API_HOST];
9
+ export const RELAY_URLS = API_HOSTS.map((h) => `wss://${h}/session/ws`);
10
+ /** The host part of a URL for status lines — or the raw string when it does not parse. A scheme-less
11
+ * KODE_RELAY_URL already fails inside RemoteHost's own error loop; a status line must never be the thing
12
+ * that throws (an unhandled rejection in a slash handler exits the whole CLI). */
13
+ export function hostOf(url) {
14
+ try {
15
+ return new URL(url).host;
16
+ }
17
+ catch {
18
+ return url;
19
+ }
20
+ }
21
+ /** Ordered relay URLs for the RC host. `KODE_RELAY_URL` overrides — comma-separated for an explicit order
22
+ * (a single URL still works exactly as before). */
23
+ export function relayUrls(env = process.env) {
24
+ const override = (env.KODE_RELAY_URL ?? "").split(",").map((s) => s.trim()).filter(Boolean);
25
+ return override.length ? override : [...RELAY_URLS];
26
+ }
@@ -8,6 +8,7 @@ import { dirname } from "node:path";
8
8
  import { operatorPath } from "./home.js";
9
9
  import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
10
10
  import { DEFAULT_MODEL_ID } from "../router/models.js";
11
+ import { LEGACY_API_HOST, PRODUCT_API_HOST } from "./product-hosts.js";
11
12
  /** Resolve an endpoint's bearer from config/env/secret-file (first hit wins); undefined when none set
12
13
  * (a local/un-gated endpoint). Keeps the raw key out of settings when `apiKeyEnv`/`apiKeyFile` are used. */
13
14
  export function resolveEndpointApiKey(ep) {
@@ -33,7 +34,7 @@ export function resolveEndpointApiKey(ep) {
33
34
  return undefined;
34
35
  }
35
36
  // Aurora endpoint is discovered from ~/.operator/runtime/server.json (dynamic port).
36
- // The empty base below is a sentinel — preflight reads server.json and resolves the real base_url
37
+ // The empty base below means unset (auto-discover) — preflight reads server.json and resolves the real base_url
37
38
  // before any request. ctxWindow MUST match the server's real --ctx-size. Override in settings.json.
38
39
  const DEFAULTS = {
39
40
  endpoints: {
@@ -304,15 +305,14 @@ function resolveModelMode(s) {
304
305
  // The AXE cloud tier — AXE's own gateway (nginx + LiteLLM → llama.cpp), the LAST-RESORT failover reached
305
306
  // only when the whole local fleet is wedged/degraded. Mirrors the `axe-aurora-300k` BUILTIN profile: same
306
307
  // served model + window. The base is bare (no `/v1` — aurora.ts appends it); it carries NO explicit token
307
- // because authHeaders() sends the operator bearer to *.axe.onl automatically (credential-scope guard). Opt
308
- // out with `settings.endpoints.cloudFailover === false` for a sovereign deployment that must never egress.
309
- const CLOUD_FAILOVER = {
310
- name: "axe-cloud",
311
- base: "https://api.axe.onl",
312
- model: "aurora-code-1",
313
- ctxLimit: 307200,
314
- transport: "openai",
315
- };
308
+ // because authHeaders() sends the operator bearer to the gateway domains automatically (credential-scope
309
+ // guard). Two legs for the SAME gateway, in order: the product name, then the legacy fleet name — a fallback
310
+ // for an edge/zone failure of one name (config/product-hosts.ts). Opt out with
311
+ // `settings.endpoints.cloudFailover === false` for a sovereign deployment that must never egress.
312
+ const CLOUD_FAILOVERS = [
313
+ { name: "operator-cloud", base: `https://${PRODUCT_API_HOST}`, model: "aurora-code-1", ctxLimit: 307200, transport: "openai" },
314
+ { name: "axe-cloud", base: `https://${LEGACY_API_HOST}`, model: "aurora-code-1", ctxLimit: 307200, transport: "openai" },
315
+ ];
316
316
  function hostLabel(base) {
317
317
  try {
318
318
  const u = new URL(base);
@@ -351,8 +351,11 @@ export function buildEndpointChain(s) {
351
351
  if (failover)
352
352
  add({ name: "failover", base: failover.base, model: failover.model, ctxLimit: failover.ctxWindow, token: resolveEndpointApiKey(failover) });
353
353
  if (s.endpoints.cloudFailover !== false) {
354
- const cfg = { base: CLOUD_FAILOVER.base, model: CLOUD_FAILOVER.model, ctxWindow: CLOUD_FAILOVER.ctxLimit };
355
- add({ ...CLOUD_FAILOVER, token: resolveEndpointApiKey(cfg) });
354
+ // No explicit token: authHeaders scopes the signed-in operator bearer to the gateway domains. Resolving a
355
+ // per-endpoint key here would send a LOCAL gateway key (KODE_AURORA_TOKEN) to both public names and displace
356
+ // the operator identity (review finding, 2026-10-28).
357
+ for (const cloud of CLOUD_FAILOVERS)
358
+ add({ ...cloud });
356
359
  }
357
360
  return chain;
358
361
  }
@@ -24,18 +24,6 @@ const DEFAULTS = {
24
24
  modelTier: "fast",
25
25
  maxLessonsPerFile: 50,
26
26
  };
27
- class SimpleIdleDetector {
28
- lastActivity = Date.now();
29
- recordActivity() {
30
- this.lastActivity = Date.now();
31
- }
32
- isIdle() {
33
- return (Date.now() - this.lastActivity) / 1000 >= 30; // default 30s idle threshold
34
- }
35
- idleSeconds() {
36
- return (Date.now() - this.lastActivity) / 1000;
37
- }
38
- }
39
27
  /** Deduplicate a JSONL memory file. Returns the deduped notes. */
40
28
  export function dedupMemoryFile(filepath) {
41
29
  if (!existsSync(filepath))
@@ -185,7 +173,7 @@ export function curateLessons(candidates) {
185
173
  existing.push(c);
186
174
  groups.set(key, existing);
187
175
  }
188
- return [...groups.entries()].map(([key, items]) => {
176
+ return [...groups.entries()].map(([, items]) => {
189
177
  const type = items[0].type;
190
178
  const count = items.reduce((s, i) => s + i.count, 0);
191
179
  const total = items.reduce((s, i) => s + i.total, 0);
@@ -390,7 +378,3 @@ function hashInput(input) {
390
378
  }
391
379
  return hash.toString(36);
392
380
  }
393
- // Lazy require for node:fs in browser context
394
- const require = (typeof globalThis !== "undefined" && globalThis.require)
395
- ? globalThis.require
396
- : undefined;
@@ -26,7 +26,7 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
26
26
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
27
27
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
28
28
  import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
29
- import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, detectUnfinishedAction } from "./continuation.js";
29
+ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction } from "./continuation.js";
30
30
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
31
31
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
32
32
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
@@ -550,6 +550,7 @@ export async function runTurn(userInput, conversation, opts) {
550
550
  let thinkLatched = false; // once a think-spiral is detected, force thinking:false for the rest of the turn
551
551
  let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
552
552
  let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
553
+ let delegationNudged = false; // the delegation-by-prose nudge (continuation.ts) fires at most once per turn
553
554
  let budgetWarned = false; // the one-time "near the time budget, converge" warning fires before the hard wall-clock stop
554
555
  const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
555
556
  let compactionFailStreak = 0; // consecutive rounds still over budget after compaction fired — the circuit breaker
@@ -581,6 +582,9 @@ export async function runTurn(userInput, conversation, opts) {
581
582
  // Turn-continuation: nudge a model that ends on an unperformed action announcement to actually do it (bounded).
582
583
  const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
583
584
  const continuationMax = Math.max(0, opts.turnContinuation?.maxNudges ?? ANNOUNCE_NUDGE_MAX);
585
+ // Delegation-by-prose guard applies only where spawn_agent is actually offered (interactive foreground; a bg
586
+ // sub-agent has no spawn tool and must not be told to call one).
587
+ const hasSpawnTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "spawn_agent");
584
588
  let announceNudges = 0;
585
589
  let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
586
590
  // Spectre fix (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
@@ -701,6 +705,7 @@ export async function runTurn(userInput, conversation, opts) {
701
705
  threshold: opts.compactionThreshold,
702
706
  ceilingTokens: opts.compactionCeilingTokens,
703
707
  minKeepTurns: opts.minKeepTurns,
708
+ preservedState: opts.preservedState?.(), // the active task list rides with the summary
704
709
  meter: globalTokenMeter, // SPEC §5: size to THIS endpoint's learned ratio, not chars/4
705
710
  meterKey: endpointKey(ep.base, ep.model),
706
711
  spill: opts.spill, // GW-10-COMPLETE: fitToWindow offloads (re-readable) when the host can write files
@@ -1144,6 +1149,13 @@ export async function runTurn(userInput, conversation, opts) {
1144
1149
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
1145
1150
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
1146
1151
  trackTouchedFiles(response.toolCalls, touchedFiles);
1152
+ // Delegation-by-prose guard: the round's narration said "spawn sub-agents / delegate" but none of its calls
1153
+ // delegated. Nudge ONCE per turn to make the call (tasks[] for parallel work) or stop announcing it — a
1154
+ // nudge, never a stop; the model may legitimately decide the work is sequential after all.
1155
+ if (!delegationNudged && hasSpawnTool && detectAnnouncedDelegation(response.content, response.toolCalls.map((c) => c.function?.name ?? ""))) {
1156
+ delegationNudged = true;
1157
+ conversation.user(DELEGATION_NUDGE);
1158
+ }
1147
1159
  // Poll-spin guard: an agent_status spin (auto-post pending, no other work, no status change) wastes the
1148
1160
  // turn — pollers are exempt from the loop guard above, so this catches them. Nudge once, then end the
1149
1161
  // turn so the auto-posted sub-agent results resume it (rather than burning the budget re-checking).
@@ -74,16 +74,21 @@ function hostOf(base) {
74
74
  return "";
75
75
  }
76
76
  }
77
- /** True when `base` is an AXE gateway host that fronts the model with operator-bearer auth (…axe.onl). LAN and
78
- * loopback fleet nodes are trusted but unauthenticated, so they never need a signed-in identity. */
77
+ // The gateway domains that front the model with operator-bearer auth: the product domain and the legacy fleet
78
+ // domain (config/product-hosts.ts keeps the host names; this is the trust list — keep the two in step).
79
+ const GATEWAY_DOMAINS = ["0perator.co", "axe.onl"];
80
+ function isGatewayDomain(h) {
81
+ return GATEWAY_DOMAINS.some((d) => h === d || h.endsWith(`.${d}`));
82
+ }
83
+ /** True when `base` is an AXE gateway host that fronts the model with operator-bearer auth (…0perator.co /
84
+ * …axe.onl). LAN and loopback fleet nodes are trusted but unauthenticated, so they never need a signed-in identity. */
79
85
  export function requiresOperatorToken(base) {
80
- const h = hostOf(base ?? "");
81
- return h === "axe.onl" || h.endsWith(".axe.onl");
86
+ return isGatewayDomain(hostOf(base ?? ""));
82
87
  }
83
88
  function isOperatorTrustedHost(h) {
84
89
  if (!h)
85
90
  return false;
86
- if (h === "axe.onl" || h.endsWith(".axe.onl"))
91
+ if (isGatewayDomain(h))
87
92
  return true;
88
93
  return /^(10\.|192\.168\.|127\.|localhost$|\[::1\]$)|^172\.(1[6-9]|2\d|3[01])\./.test(h) || h.endsWith(".local");
89
94
  }
@@ -360,7 +360,7 @@ export async function compact(conversation, opts) {
360
360
  // summary embeds specifics in prose); these blocks guarantee nothing critical was dropped.
361
361
  const summaryMsg = {
362
362
  role: "user", // never a 2nd system message — SPEC §1/§5
363
- content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}`,
363
+ content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}${opts.preservedState ? `\n\n${opts.preservedState}` : ""}`,
364
364
  };
365
365
  // N1 VERIFIED COMPACTION: proof-of-preservation rides with the summary (shared helper now — the
366
366
  // instant/prewritten path in session.ts MUST get the same guarantee, audit-engine §2).
@@ -53,3 +53,19 @@ export function detectUnfinishedAction(content) {
53
53
  const head = lines.length > 1 && lines[0].endsWith(":") ? [lines[0]] : [];
54
54
  return [...head, ...window].some((s) => ANNOUNCE_RE.test(s) && !HANDBACK_RE.test(s) && !DEFER_RE.test(s) && !CONDITIONAL_RE.test(s));
55
55
  }
56
+ // Delegation announced in prose but not performed. detectUnfinishedAction covers a TEXT-ONLY turn ending on an
57
+ // announcement; this covers a TOOL round whose narration says the model will spawn sub-agents / delegate / fan out
58
+ // while none of its calls delegated — the live failure (2026-10-28): a model that kept running bash itself,
59
+ // restating "then spawn sub-agents for each subsystem" round after round, and never calling spawn_agent.
60
+ const DELEGATION_RE = /\b(?:(?:spawning|spawn)\s+(?:a |the |some |more )?(?:parallel )?(?:sub-?)?agents?|(?:spinning|spin)\s+up\s+(?:sub-?)?agents?|sub-?agents?\s+(?:to|for|will|in parallel|per|should)|delegat(?:e|es|ed|ing)\s+(?:to|the|this|these|that|those|each|research|work|it|tasks?)|(?:fanning|fan)\s+out)\b/i;
61
+ const DELEGATION_TOOLS = new Set(["spawn_agent", "delegate_task", "delegate_to_agent"]);
62
+ export const DELEGATION_NUDGE = "You said you would delegate, but this round made no spawn_agent call. If parts of the work are independent, call " +
63
+ "spawn_agent NOW with each part as an entry in `tasks` (they run in parallel) — otherwise do the work yourself. " +
64
+ "Do not announce delegation again without making the call.";
65
+ /** True when a tool round's narration announces delegation and none of the round's calls delegated. */
66
+ export function detectAnnouncedDelegation(content, calledTools) {
67
+ if (calledTools.some((n) => DELEGATION_TOOLS.has(n)))
68
+ return false;
69
+ const text = (content ?? "").trim();
70
+ return !!text && DELEGATION_RE.test(text);
71
+ }
@@ -20,7 +20,6 @@ export class RollingSummarizer {
20
20
  opts;
21
21
  lastUpdateTokens = 0;
22
22
  lastUpdateBatches = 0;
23
- lastUpdateTime = 0;
24
23
  summaryCache = "";
25
24
  dirty = false;
26
25
  // GW-27-U2: how many user-turns the CURRENT cached summary covers (turnCount at fire time).
@@ -61,7 +60,6 @@ export class RollingSummarizer {
61
60
  * (GW-27-U2). Omitted => coverage unknown => treated as covering nothing: safe, just falls back
62
61
  * to the live summarize path. */
63
62
  markSummaryFired(turnsCovered) {
64
- this.lastUpdateTime = Date.now();
65
63
  this.dirty = false;
66
64
  this.coveredThroughTurns = typeof turnsCovered === "number" ? turnsCovered : 0;
67
65
  }
@@ -28,10 +28,9 @@ export async function runMutationCheck(cwd, verifyCommand, diffSha) {
28
28
  execSync("git stash push -m 'mutation-check-stash' -- .", { cwd, stdio: "pipe" });
29
29
  // Revert to the pre-change state
30
30
  execSync(`git checkout ${diffSha} -- .`, { cwd, stdio: "pipe" });
31
- // Run verification
32
- let verifyResult;
31
+ // Run verification — only pass/fail matters here, the output is not read
33
32
  try {
34
- verifyResult = execSync(verifyCommand, { cwd, encoding: "utf8", stdio: "pipe" });
33
+ execSync(verifyCommand, { cwd, encoding: "utf8", stdio: "pipe" });
35
34
  }
36
35
  catch (e) {
37
36
  // Verify failed — good! The tests actually test something.
@@ -201,7 +200,7 @@ export class FlywheelProcessor {
201
200
  /** Process all trajectories in the flywheel directory.
202
201
  * Applies SRFT masking, runs mutation checks, and outputs cleaned trajectories. */
203
202
  async processAll() {
204
- const { readdirSync, readFileSync, writeFileSync, existsSync, mkdirSync } = await import("node:fs");
203
+ const { readdirSync, readFileSync, existsSync, mkdirSync } = await import("node:fs");
205
204
  const { join } = await import("node:path");
206
205
  const flywheelDir = this.opts.flywheelDir;
207
206
  if (!existsSync(flywheelDir)) {
@@ -53,7 +53,6 @@ function capCapabilities(caps) {
53
53
  };
54
54
  }
55
55
  export class RemoteHost {
56
- url;
57
56
  token;
58
57
  meta;
59
58
  cb;
@@ -87,11 +86,20 @@ export class RemoteHost {
87
86
  keepaliveTimer = null;
88
87
  reconnectTimer = null;
89
88
  reconnectAttempts = 0;
89
+ // Ordered relay URLs (product host first, legacy host as fallback — config/product-hosts.ts). Rotation is per
90
+ // ATTEMPT: any dial that never reaches `welcome` — the first connect or a post-drop re-dial — moves to the next
91
+ // URL. A drop itself never rotates, so a re-dial that welcomes keeps the name the host was on; names only change
92
+ // when the current one stops answering.
93
+ urls;
94
+ urlIdx = 0;
95
+ welcomedThisAttempt = false;
90
96
  constructor(url, token, meta, cb, pairing) {
91
- this.url = url;
92
97
  this.token = token;
93
98
  this.meta = meta;
94
99
  this.cb = cb;
100
+ this.urls = (Array.isArray(url) ? url : [url]).filter(Boolean);
101
+ if (!this.urls.length)
102
+ throw new Error("RemoteHost needs at least one relay url");
95
103
  if (pairing) {
96
104
  this.sessionId = pairing.sessionId; // deterministic, so the QR's s=<sessionId> is known before connect
97
105
  this.paired = true;
@@ -105,12 +113,14 @@ export class RemoteHost {
105
113
  // session on a blip (the battlefield no-disconnect requirement). A deliberate stop() short-circuits it.
106
114
  openSocket() {
107
115
  this.cb.onState?.("connecting");
116
+ this.welcomedThisAttempt = false;
108
117
  let ws;
109
118
  try {
110
- ws = new WebSocket(this.url);
119
+ ws = new WebSocket(this.relayUrl);
111
120
  }
112
121
  catch (e) {
113
122
  this.cb.onState?.("error", String(e));
123
+ this.rotateUrl();
114
124
  this.scheduleReconnect();
115
125
  return;
116
126
  }
@@ -122,11 +132,18 @@ export class RemoteHost {
122
132
  });
123
133
  ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
124
134
  ws.addEventListener("close", () => {
125
- this.stopKeepalive();
126
135
  if (this.closedByUs) {
136
+ this.stopKeepalive();
127
137
  this.cb.onState?.("closed");
128
138
  return;
129
139
  }
140
+ // A superseded socket's late close (a `reconnect` re-dial that outran its closing handshake): not ours to
141
+ // rotate, re-dial, or stop the LIVE socket's keepalive.
142
+ if (ws !== this.ws)
143
+ return;
144
+ this.stopKeepalive();
145
+ if (!this.welcomedThisAttempt)
146
+ this.rotateUrl(); // this relay name never answered — try the next one
130
147
  this.cb.onState?.("connecting", "reconnecting"); // NOT a hard error — we re-dial the same session
131
148
  this.scheduleReconnect();
132
149
  });
@@ -156,6 +173,10 @@ export class RemoteHost {
156
173
  } }
157
174
  get id() { return this.sessionId; }
158
175
  get connected() { return !!this.ws && this.ws.readyState === 1; }
176
+ /** The relay URL this host is dialing (or live on) right now. */
177
+ get relayUrl() { return this.urls[this.urlIdx]; }
178
+ rotateUrl() { if (this.urls.length > 1)
179
+ this.urlIdx = (this.urlIdx + 1) % this.urls.length; }
159
180
  stop() {
160
181
  this.closedByUs = true;
161
182
  if (this.liveTimer) {
@@ -196,6 +217,7 @@ export class RemoteHost {
196
217
  }
197
218
  switch (f.type) {
198
219
  case "welcome":
220
+ this.welcomedThisAttempt = true;
199
221
  this.sessionId = f.payload?.sessionId ?? this.sessionId;
200
222
  this.ownerSub = f.payload?.ownerSub ?? null;
201
223
  if (typeof f.payload?.epoch === "number")
@@ -1,3 +1,15 @@
1
+ // Model registry — /model + MOA (MOA-DESIGN.md). Three switchable profiles: two "single" profiles
2
+ // that just point THIS session's AuroraRouter at an already-running llama-server (no server is ever
3
+ // started/stopped by selecting one), and "moa" (mixture-of-agents), which has no endpoint of its
4
+ // own — it fans a turn out to settings.moa's proposers and synthesizes with an aggregator (see
5
+ // engine/moa.ts + Session.setModel/sendMoa). Kept dependency-free (no settings.ts import) so both
6
+ // settings.ts and session.ts can import it without a cycle.
7
+ // ── Model tiers (PV2-11) ────────────────────────────────────────────────────
8
+ // A COMPUTE/COST CLASS orthogonal to a profile's id, so routing can ask for a class instead of a
9
+ // name ("give me a lite model for this sub-task") and degrade predictably when a class is empty.
10
+ // Ladder, strongest → cheapest: power_turbo > power > economy > lite > free. "free" is reserved
11
+ // for genuinely no-cost promotional slots; nothing on the fleet maps to it today.
12
+ import { LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
1
13
  /** Fallback walk order, strongest → cheapest. */
2
14
  export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
3
15
  export const DEFAULT_MODEL_ID = "operator-1m";
@@ -13,7 +25,9 @@ export const MODEL_ALIASES = {
13
25
  /** AXE's one shared model gateway (Caddy + AuthGate op_ verify + LiteLLM with server-side fallbacks, JL2).
14
26
  * Fleet entries list it FIRST so one public name keeps answering when a box is down; the portal client
15
27
  * (router/portal.ts) derives its host from this too, so the address lives in exactly one place. */
16
- export const GATEWAY_BASE = "https://api.axe.onl/v1";
28
+ export const GATEWAY_BASE = `https://${PRODUCT_API_HOST}/v1`;
29
+ /** The legacy fleet name for the SAME gateway — the ordered fallback behind GATEWAY_BASE, never a different backend. */
30
+ export const LEGACY_GATEWAY_BASE = `https://${LEGACY_API_HOST}/v1`;
17
31
  export const BUILTIN_MODELS = [
18
32
  { id: "operator-1m", tier: "power", label: "Operator 1M (local)", kind: "single", desc: "RECOMMENDED DEFAULT — local Aurora code model on this box's GPU (:8097, 24-47 tok/s measured, warm prefix-cache, no shared-slot contention); ctx 300K matched under the served 307,200 wall so compaction lands BEFORE the edge", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1000000 },
19
33
  { id: "operator-128k", tier: "economy", label: "Operator 128K", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
@@ -35,7 +49,7 @@ export const BUILTIN_MODELS = [
35
49
  // issues them, gating this profile behind an unconnectable BYO account hid our OWN flagship remote
36
50
  // lane from our own picker (2026-10-12 picker-truth audit) — so it is a plain profile today. When V1
37
51
  // ships, reintroduce the byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
38
- { id: "axe-aurora-300k", tier: "power", label: "Aurora 300K (AXE cloud)", kind: "single", desc: "remote shared slot via api.axe.onl — big-context fallback, NOT default: contended decode measured 1-4.6 tok/s vs local 24-47 (JL1 serves everyone); cold >~100K prefills can also hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, model: "aurora-code-1", ctx: 307200, transport: "openai" },
52
+ { id: "axe-aurora-300k", tier: "power", label: "Aurora 300K (AXE cloud)", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — big-context fallback, NOT default: contended decode measured 1-4.6 tok/s vs local 24-47 (JL1 serves everyone); cold >~100K prefills can also hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai" },
39
53
  // Spectre — the flagship, replacing Ghost (2026-10-07). Ghost 32B was the prior self-hosted abliterated
40
54
  // Qwen3-VL-32B on this slot; retired when Spectre proved 4× faster at equal capability (its weights + restore
41
55
  // command are kept at ~/.axe/logs/ghost-restore-cmd.txt — reversible). Spectre = Huihui-Qwen3.6-35B-A3B-