@0perator/operator 0.1.285 → 0.1.321

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.
Files changed (118) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +308 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +217 -44
  11. package/dist/autonomy/delegate.js +34 -5
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/index.js +22 -0
  14. package/dist/autonomy/profile.js +1 -1
  15. package/dist/autonomy/session-factory.js +25 -16
  16. package/dist/background/index.js +40 -0
  17. package/dist/browser/cdp.js +1 -1
  18. package/dist/bus/inbox.js +20 -0
  19. package/dist/classifier/config.js +47 -0
  20. package/dist/classifier/modes.js +41 -0
  21. package/dist/classifier/types.js +1 -0
  22. package/dist/cli.js +645 -93
  23. package/dist/config/features.js +69 -0
  24. package/dist/config/persona.js +143 -107
  25. package/dist/config/scaffold.js +15 -0
  26. package/dist/config/settings.js +107 -12
  27. package/dist/consolidation/sleep.js +73 -11
  28. package/dist/engine/agent.js +279 -20
  29. package/dist/engine/anthropic-chat.js +343 -0
  30. package/dist/engine/aurora.js +109 -16
  31. package/dist/engine/batch-scheduler.js +41 -9
  32. package/dist/engine/classifier.js +85 -0
  33. package/dist/engine/compaction.js +25 -6
  34. package/dist/engine/fast-start.js +25 -0
  35. package/dist/engine/loop-guard.js +448 -0
  36. package/dist/engine/net-error.js +24 -0
  37. package/dist/engine/repetition-guard.js +180 -0
  38. package/dist/engine/router-adapter.js +1 -0
  39. package/dist/engine/selfheal.js +8 -0
  40. package/dist/engine/toolcalls.js +51 -1
  41. package/dist/engine/verify-gate.js +2 -0
  42. package/dist/flywheel/processor.js +78 -31
  43. package/dist/flywheel/srft.js +13 -0
  44. package/dist/hooks/index.js +196 -0
  45. package/dist/idle/activity.js +20 -0
  46. package/dist/idle/index.js +5 -0
  47. package/dist/idle/monitor.js +71 -0
  48. package/dist/idle/policy.js +66 -0
  49. package/dist/idle/proc.js +22 -0
  50. package/dist/idle/reaper.js +69 -0
  51. package/dist/idle/session-record.js +59 -0
  52. package/dist/index.js +1 -1
  53. package/dist/mcp/config.js +93 -15
  54. package/dist/mcp/index.js +9 -2
  55. package/dist/memory/index.js +0 -0
  56. package/dist/memory/providers.js +210 -0
  57. package/dist/memory/session-catalog.js +422 -0
  58. package/dist/memory/session-providers.js +121 -0
  59. package/dist/memory/session-sources.js +335 -0
  60. package/dist/memory/skylark.js +131 -0
  61. package/dist/models/bench.js +103 -0
  62. package/dist/models/registry.js +144 -0
  63. package/dist/models/switch.js +69 -0
  64. package/dist/observability/blackbox.js +37 -0
  65. package/dist/permissions/index.js +22 -7
  66. package/dist/permissions/policy.js +31 -6
  67. package/dist/permissions/tier.js +1 -1
  68. package/dist/remote/host.js +20 -2
  69. package/dist/remote/safe-commands.js +38 -0
  70. package/dist/router/discovery.js +127 -0
  71. package/dist/router/models.js +107 -16
  72. package/dist/router/portal.js +100 -0
  73. package/dist/router/router.js +1 -1
  74. package/dist/services/preflight.js +108 -8
  75. package/dist/services/store-sync.js +111 -0
  76. package/dist/session-teardown.js +10 -1
  77. package/dist/session.js +338 -46
  78. package/dist/skills/catalogue.js +1 -1
  79. package/dist/tools/chauffeur-native.js +155 -0
  80. package/dist/tools/chauffeur.js +26 -3
  81. package/dist/tools/download.js +229 -0
  82. package/dist/tools/executor.js +19 -9
  83. package/dist/tools/find-files.js +483 -0
  84. package/dist/tools/git-pr.js +94 -0
  85. package/dist/tools/incident-tools.js +82 -0
  86. package/dist/tools/memory.js +12 -2
  87. package/dist/tools/monitoring-tools.js +312 -0
  88. package/dist/tools/paths.js +154 -0
  89. package/dist/tools/registry.js +582 -95
  90. package/dist/tools/semantic-compress.js +124 -0
  91. package/dist/tools/shell-context.js +1 -0
  92. package/dist/tools/shell-jobs.js +163 -0
  93. package/dist/tools/shell-session.js +174 -6
  94. package/dist/tools/tool-output-spill.js +1 -1
  95. package/dist/tools/wave-tools.js +609 -0
  96. package/dist/tools/wave2-tools.js +411 -0
  97. package/dist/ui/App.js +15 -4
  98. package/dist/ui/BgPanel.js +30 -6
  99. package/dist/ui/Composer.js +15 -2
  100. package/dist/ui/QuestionPrompt.js +32 -12
  101. package/dist/ui/SessionPicker.js +86 -0
  102. package/dist/ui/StatusRule.js +5 -5
  103. package/dist/ui/ToolStep.js +17 -1
  104. package/dist/ui/Transcript.js +17 -1
  105. package/dist/ui/index.js +1 -1
  106. package/dist/ui/liveTools.js +21 -3
  107. package/dist/ui/slashCommands.js +2 -0
  108. package/dist/util/mentions.js +1 -1
  109. package/dist/util/screenshots.js +74 -8
  110. package/dist/util/slash.js +2 -2
  111. package/dist/vault/store.js +1 -1
  112. package/mcp/README.md +88 -0
  113. package/mcp/ocr-macos.swift +45 -0
  114. package/mcp/powertools-media.mjs +464 -0
  115. package/mcp/powertools-toolbox.mjs +1114 -0
  116. package/mcp/powertools.md +210 -0
  117. package/mcp/powertools.mjs +861 -0
  118. package/package.json +9 -2
@@ -0,0 +1,127 @@
1
+ // Model discovery — turn "a server is running on the fleet" into a named, truthfully-sized model profile
2
+ // WITHOUT editing the catalog. Frontier model platforms treat models as DATA the serving layer advertises
3
+ // (OpenAI `GET /v1/models` + llama.cpp `/props`) and a gateway polls + auto-catalogs them; this is that
4
+ // layer for Operator. Drop a llama.cpp/vLLM/TGI server onto a fleet node, list its base in
5
+ // settings.fleet.auroraNodes, and it appears in `/model` — named by the server, with its REAL context
6
+ // window read from `/props` — no code change, and no hand-typed ctx that can drift from the served wall
7
+ // (the "operator-1m labelled 300K while serving 600K" class of bug the manual catalog kept producing).
8
+ //
9
+ // Design mirrors the rest of router/models.ts: health-gated (a base that doesn't answer in time is simply
10
+ // absent — an honest picker never offers a dead endpoint, same spirit as visibleModels), merged UNDER
11
+ // settings.models (an explicit hand override by id ALWAYS wins — discovery informs, never overrides an
12
+ // owner's choice), and cached with a short TTL so it never runs on a render/keystroke path. Kept
13
+ // dependency-free except the ModelProfile type (the no-cycle rule models.ts documents).
14
+ const DEFAULTS = { timeoutMs: 2500, marginPct: 0.98 };
15
+ /** A bare base ("http://host:8097") → the OpenAI base the AuroraRouter wants ("http://host:8097/v1").
16
+ * settings.fleet.auroraNodes holds bare bases; ModelProfile.endpoint includes /v1. */
17
+ function v1(base) {
18
+ return base.replace(/\/+$/, "") + "/v1";
19
+ }
20
+ /** A stable, human-ish host tag ("192.168.1.103:8097") for ids/labels when a server advertises no alias. */
21
+ function hostTag(base) {
22
+ try {
23
+ const u = new URL(base);
24
+ return u.port ? `${u.hostname}:${u.port}` : u.hostname;
25
+ }
26
+ catch {
27
+ return base.replace(/^https?:\/\//, "").replace(/\/+$/, "");
28
+ }
29
+ }
30
+ function slug(s) {
31
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
32
+ }
33
+ function fmtK(n) {
34
+ return n >= 1000 ? `${Math.round(n / 1000)}K` : String(n);
35
+ }
36
+ /** A served model id that is actually a filesystem path (llama.cpp's default when `--alias` is unset) is
37
+ * not a name a human picked — fall back to the host tag rather than show a gguf path in the picker. Set
38
+ * the server's `--alias` to its friendly name and discovery uses it: that's the true self-registration. */
39
+ function isPathLike(id) {
40
+ return !!id && (id.includes("/") || id.toLowerCase().endsWith(".gguf"));
41
+ }
42
+ async function getJson(url, timeoutMs, f) {
43
+ const ctl = new AbortController();
44
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
45
+ try {
46
+ const r = await f(url, { signal: ctl.signal });
47
+ if (!r.ok)
48
+ return null;
49
+ return await r.json();
50
+ }
51
+ catch {
52
+ return null; // unreachable / timeout / bad JSON → treated as "down", never throws into the caller
53
+ }
54
+ finally {
55
+ clearTimeout(t);
56
+ }
57
+ }
58
+ /** Probe one fleet base and build a ModelProfile from what the SERVER reports, or null if it doesn't
59
+ * answer `/props` in time (→ absent from the picker). `/props` is the source of truth for the context
60
+ * window (default_generation_settings.n_ctx) and the self-chosen name (model_alias); `/v1/models` is a
61
+ * secondary name source. */
62
+ export async function probeHost(base, opts = {}) {
63
+ const timeoutMs = opts.timeoutMs ?? DEFAULTS.timeoutMs;
64
+ const marginPct = opts.marginPct ?? DEFAULTS.marginPct;
65
+ const f = opts.fetchImpl ?? fetch;
66
+ const bare = base.replace(/\/+$/, "");
67
+ const props = await getJson(`${bare}/props`, timeoutMs, f);
68
+ if (!props)
69
+ return null; // health gate: no /props → down → not offered
70
+ const nCtx = Number(props?.default_generation_settings?.n_ctx ?? props?.n_ctx);
71
+ if (!Number.isFinite(nCtx) || nCtx <= 0)
72
+ return null; // can't size it truthfully → skip
73
+ const models = await getJson(`${v1(bare)}/models`, timeoutMs, f);
74
+ const servedId = models?.data?.[0]?.id;
75
+ // The self-chosen name: the first candidate that is a real name, not a path — llama.cpp sets BOTH
76
+ // model_alias and the /v1/models id to the gguf PATH when `--alias` is unset, so a path from either
77
+ // source is rejected and we fall back to a host tag rather than leak a filesystem path into the picker.
78
+ const alias = [props?.model_alias, servedId].find((x) => typeof x === "string" && x.length > 0 && !isPathLike(x));
79
+ const tag = hostTag(bare);
80
+ const ctx = Math.floor(nCtx * marginPct);
81
+ return {
82
+ id: alias ? `fleet-${slug(alias)}-${slug(tag)}` : `fleet-${slug(tag)}`,
83
+ label: alias ? `${alias} (${tag})` : `Aurora ${fmtK(nCtx)} @ ${tag}`,
84
+ kind: "single",
85
+ endpoint: v1(bare),
86
+ model: servedId || alias || "aurora-code-1",
87
+ ctx,
88
+ desc: `auto-discovered — served ${nCtx.toLocaleString()} ctx${props?.total_slots ? `, ${props.total_slots} slot(s)` : ""} at ${tag}`,
89
+ };
90
+ }
91
+ /** Probe every base in parallel, drop the unreachable, and dedup by endpoint (a box listed twice) keeping
92
+ * the first. Result is meant to be MERGED UNDER settings.models:
93
+ * modelRegistry([...discovered, ...(settings.models ?? [])])
94
+ * so a hand-written override by id always wins over the auto-discovered record. */
95
+ export async function discoverFleetModels(bases, opts = {}) {
96
+ const uniq = [...new Set((bases ?? []).filter(Boolean))];
97
+ const probed = await Promise.all(uniq.map((b) => probeHost(b, opts)));
98
+ const out = [];
99
+ const seen = new Set();
100
+ for (const p of probed) {
101
+ if (!p || seen.has(p.endpoint))
102
+ continue;
103
+ seen.add(p.endpoint);
104
+ out.push(p);
105
+ }
106
+ return out;
107
+ }
108
+ // ── cache ────────────────────────────────────────────────────────────────
109
+ // Discovery hits the network, so it must never run on a render/keystroke path. A short TTL keeps the
110
+ // picker fresh (a newly-started node shows within one TTL) without re-probing every `/model` open.
111
+ let cache = null;
112
+ const TTL_MS = 60_000;
113
+ /** Cached discovery for the given bases: the last good result within the TTL, else an awaited refresh.
114
+ * A probe wave that finds nothing returns [] (callers then show builtins + settings.models only). */
115
+ export async function getDiscoveredModels(bases, opts = {}) {
116
+ const key = [...new Set((bases ?? []).filter(Boolean))].sort().join(",");
117
+ const now = Date.now();
118
+ if (cache && cache.key === key && now - cache.at < TTL_MS)
119
+ return cache.models;
120
+ const models = await discoverFleetModels(bases, opts);
121
+ cache = { at: now, key, models };
122
+ return models;
123
+ }
124
+ /** Reset the cache — tests, and a forced `/model` refresh. */
125
+ export function clearDiscoveryCache() {
126
+ cache = null;
127
+ }
@@ -1,3 +1,5 @@
1
+ /** Fallback walk order, strongest → cheapest. */
2
+ export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
1
3
  export const DEFAULT_MODEL_ID = "operator-1m";
2
4
  // Back-compat aliases: the user-facing ids were renamed aurora-* -> operator-* (the outward name is
3
5
  // Operator; "aurora" is the internal model, never shown). The OLD ids still resolve — a persisted
@@ -8,22 +10,32 @@ export const MODEL_ALIASES = {
8
10
  "aurora-128k": "operator-128k",
9
11
  "spectre": "cortana", // flagship renamed Spectre -> Cortana 35B (2026-10-07); old id keeps resolving
10
12
  };
13
+ /** AXE's one shared model gateway (Caddy + AuthGate op_ verify + LiteLLM with server-side fallbacks, JL2).
14
+ * Fleet entries list it FIRST so one public name keeps answering when a box is down; the portal client
15
+ * (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";
11
17
  export const BUILTIN_MODELS = [
12
- { id: "operator-1m", 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: 300000 },
13
- { id: "operator-128k", 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 },
18
+ { 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
+ { 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 },
14
20
  // QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
15
21
  // account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
16
22
  // authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
17
23
  // to the served truth (observeContext).
18
- { id: "qwen3.8-max", label: "Qwen 3.8 Max", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
19
- { id: "qwen3.8-flash", label: "Qwen 3.8 Flash", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
24
+ { id: "qwen3.8-max", tier: "power_turbo", label: "Qwen 3.8 Max", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
25
+ { id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
26
+ // Claude — a BYO Anthropic connector, so "delegate to Claude" and `/model claude-sonnet` work. Unlike the
27
+ // qwen/OpenAI connectors (OpenAI dialect), Claude speaks the NATIVE Anthropic Messages wire — transport
28
+ // "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
29
+ // Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Hidden
30
+ // from the picker until the key is stored; ctx is Anthropic's documented 200K, self-clamps to served truth.
31
+ { id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 4.5", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: "https://api.anthropic.com/v1", model: "claude-sonnet-4-5", ctx: 200000, byo: "anthropic", transport: "anthropic" },
20
32
  // AXE Token Plan: api.axe.onl is AXE's OWN gateway (nginx + LiteLLM) and the Operator token is its
21
33
  // native auth (authHeaders scoping sends it to *.axe.onl — aurora.ts). Third-party `sk-axe-…` virtual
22
34
  // keys are the V1 vendor plan (_ai-docs/architecture/axe-model-vendor.md); until the gateway actually
23
35
  // issues them, gating this profile behind an unconnectable BYO account hid our OWN flagship remote
24
36
  // lane from our own picker (2026-10-12 picker-truth audit) — so it is a plain profile today. When V1
25
37
  // ships, reintroduce the byo:"axe" SKU as a SEPARATE connector id, never by re-gating this one.
26
- { id: "axe-aurora-300k", 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: "https://api.axe.onl/v1", model: "aurora-code-1", ctx: 307200, transport: "openai" },
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" },
27
39
  // Spectre — the flagship, replacing Ghost (2026-10-07). Ghost 32B was the prior self-hosted abliterated
28
40
  // Qwen3-VL-32B on this slot; retired when Spectre proved 4× faster at equal capability (its weights + restore
29
41
  // command are kept at ~/.axe/logs/ghost-restore-cmd.txt — reversible). Spectre = Huihui-Qwen3.6-35B-A3B-
@@ -35,18 +47,29 @@ export const BUILTIN_MODELS = [
35
47
  // truncated a round at token 32767 (finish=length) mid-tool-call, and that cut call poisoned the session (0.1.259).
36
48
  // 32000 sits just UNDER the real wall (margin) AND under LEAN_HARNESS_CTX so Cortana drops the heavy memory/handoff
37
49
  // (which alone was ~16K = half the window) — persona + unrestricted layer kept. Raise ONLY if the server's --ctx-size does.
38
- { id: "cortana", label: "Cortana 35B (JL1)", kind: "single", desc: "flagship MoE — abliterated Qwen3.6-35B-A3B (~3B active; ~40 tok/s ONLY when JL1 is quiet — shares the box with the 300K cloud slots and fell to 1-4 tok/s under fleet load; pick for vision/uncensored jobs, prefer Operator 1M local otherwise)", endpoint: "http://192.168.1.103:8112/v1", model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 262144 },
50
+ { id: "cortana", tier: "power", label: "Cortana 35B (JL1)", kind: "single", desc: "flagship MoE — abliterated Qwen3.6-35B-A3B (~3B active; ~40 tok/s ONLY when JL1 is quiet — shares the box with the 300K cloud slots and fell to 1-4 tok/s under fleet load; pick for vision/uncensored jobs, prefer Operator 1M local otherwise). GATEWAY-FIRST: the shared gateway answers by its own fallback (Aurora) when JL1 is down, then the LAN box direct; cold huge prefills can hit the Cloudflare ~125s edge cutoff)", endpoint: "http://192.168.1.103:8112/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8112/v1"], endpointModels: ["cortana", "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf"], model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 262144 },
39
51
  // Qwen3-4B — fast LOCAL tier (stock qwen3-4b-mlx-q4, 2.26GB MLX 4-bit, ctx 40960) served via mlx_lm.server
40
52
  // on JL1:8110. Qwen3 vocab (151936) — the same family as ghost-32b, so it's the review-recommended quick tier
41
53
  // AND the vocab lineage for ghost spec-decode (the actual draft is Qwen3-0.6B, too small to list here). Runs
42
54
  // /no_think for speed. Picked (2026-10-07) from a fleet-wide 3B-class review; no 3B had been execution-graded,
43
55
  // so this is the evidence-led default pending a dyno/coding-eval bench. 40960 ≥ LEAN_HARNESS_CTX → full harness.
44
- { id: "scout", label: "Scout 4B", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit)", endpoint: "http://192.168.1.103:8110/v1", model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
56
+ { id: "scout", tier: "lite", label: "Scout 4B", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit; gateway-first, LAN direct as failover)", endpoint: "http://192.168.1.103:8110/v1", endpoints: [GATEWAY_BASE, "http://192.168.1.103:8110/v1"], endpointModels: ["scout", "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4"], model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
45
57
  // Venice 24B — a LIGHTER uncensored alternative to the 35B Spectre: Dolphin-Mistral-24B-Venice-Edition
46
58
  // (Q4_K_M, ~14GB) with a bolted-on Mistral-Small-3.1 mmproj for vision. Dense 24B (not MoE), served on
47
59
  // JL1:8114 via llama.cpp (--jinja, q8 KV). ctx 32768 ≥ LEAN_HARNESS_CTX → full harness. A quick drop-in to
48
60
  // test a smaller/different flavour alongside Spectre without the 35B footprint.
49
- { id: "venice-24b", label: "Venice 24B", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114) — slot stopped today; hidden from the picker, resolves by id once launched", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768, hidden: true },
61
+ { id: "venice-24b", tier: "economy", label: "Venice 24B", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114) — slot stopped today; hidden from the picker, resolves by id once launched", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768, hidden: true },
62
+ // Falcon-H1-34B — a NOVEL architecture nobody else on the fleet runs: hybrid SSM+attention, trained with a
63
+ // genuinely long native context (no YaRN stretch needed — 262144 is baked into the GGUF's own metadata,
64
+ // confirmed via gguf-py header read, rope.freq_base ≈1e11). Served JL1:8101, q8_0 KV, parallel=1. Not one
65
+ // of our own fine-tunes — picked specifically to try something outside the Qwen/Aurora lineage.
66
+ { id: "falcon-h1-34b", tier: "power", label: "Falcon-H1 34B (JL1)", kind: "single", desc: "novel hybrid SSM+attention architecture, native 256K context (no rope extension) — not ours, picked to try something different from the Qwen/Aurora lineage", endpoint: "http://192.168.1.103:8101/v1", model: "/Volumes/Ai Storage/axe-models/falcon-h1-34b/Falcon-H1-34B-Instruct-Q4_K_M.gguf", ctx: 262144 },
67
+ // Casanova (axe/newton-base-32b) — OUR OWN fine-tune, Qwen2-architecture, 32B. Source was MLX 4-bit
68
+ // quantized (group_size 64, affine) — dequantized via mlx_lm --dequantize, reconverted+requantized to
69
+ // Q4_K_M via convert_hf_to_gguf.py + llama-quantize (2026-10-22). Native ctx is only 32768, so 128K here is
70
+ // a 4x YaRN stretch (--rope-scaling yarn --yarn-orig-ctx 32768 --rope-scale 4) — untested at the edge,
71
+ // verify with a real long-context probe before trusting it near the ceiling.
72
+ { id: "casanova", tier: "power", label: "Casanova 32B (JL1)", kind: "single", desc: "our own fine-tune (axe/newton-base-32b) — 128K via 4x YaRN stretch from a 32K native window", endpoint: "http://192.168.1.103:8102/v1", model: "/Users/home/.axe/gguf-converted/casanova-current/casanova-current-Q4_K_M.gguf", ctx: 131072 },
50
73
  // Code tier for the coding/Replit-clone surface — Qwen2.5-Coder-3B has a real chat template + tool-calling
51
74
  // + FIM (ollama reports "completion, tools, insert"), unlike StarCoder2/replit-code (completion-only, can't
52
75
  // drive an agent loop). Ollama on JL1, on-demand (loads ~3GB, so SELECT only when JL1 swap has headroom).
@@ -56,9 +79,31 @@ export const BUILTIN_MODELS = [
56
79
  // transport:"openai" = Ollama /v1. ENDPOINT FIX 2026-10-12: was 127.0.0.1:11434, which only resolves
57
80
  // ON JL1 — every laptop picker entry pointed at its own dead loopback. LAN address like the other
58
81
  // JL1 slots.
59
- { id: "qwen-coder", label: "Qwen Coder 3B (JL1)", kind: "single", desc: "code tier — Qwen2.5-Coder-3B Q4_K_M (chat + tool-calling + FIM), Ollama on JL1:11434 (on-demand ~3GB); Qwen Research Licence, non-commercial", endpoint: "http://192.168.1.103:11434/v1", model: "qwen2.5-coder:3b", ctx: 32000, transport: "openai" },
60
- { id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "the team slot — fans each turn to aurora-local + Cortana 35B + Qwen-Coder 3B proposers (settings.moa, 60s fan-out, graceful per-draft failure) and synthesizes with local Aurora as agent-loop aggregator; roster + benchmark in _ai-docs" },
82
+ { id: "qwen-coder", tier: "lite", label: "Qwen Coder 3B (JL1)", kind: "single", desc: "code tier — Qwen2.5-Coder-3B Q4_K_M (chat + tool-calling + FIM), Ollama on JL1:11434 (on-demand ~3GB); Qwen Research Licence, non-commercial", endpoint: "http://192.168.1.103:11434/v1", model: "qwen2.5-coder:3b", ctx: 32000, transport: "openai" },
83
+ // Belmont 30b — an OWNER-ONLY trial of muse (muse0P abliterated, Q4_K_M ~16.9GB), served under the alias
84
+ // `muse-op` on llama.cpp :8113. FAILOVER pair: JL2 primary (192.168.1.146:8113), JL1 standby
85
+ // (192.168.1.103:8113) — same model/alias on both, so the router can hop JL2->JL1 on a busy/5xx. JL1 runs
86
+ // overnight training, so muse is served on JL2 and only falls back to JL1 when that box is free (it must be
87
+ // running on at least one box to answer — nothing here starts a server). ctx 131072 matches the served
88
+ // n_ctx on :8113 (JL1 /props: muse0P, n_ctx 131072); the earlier 16384 understated it 8x and instantly
89
+ // stalled the full headless harness at ctxPct=99 (it sits ABOVE LEAN_HARNESS_CTX, so Belmont gets the
90
+ // full harness). Keep this equal to the serve scripts' --ctx-size on both boxes.
91
+ // ownerOnly: enterprise-grade private trial — hidden from every picker and refused for any non-owner seat.
92
+ { id: "belmont-30b", tier: "economy", label: "Belmont 30b", kind: "single", desc: "OWNER-ONLY trial — muse (muse-op, abliterated 30B Q4_K_M) on llama.cpp :8113, JL2 primary + JL1 failover; must be served on a box to answer", endpoints: ["http://192.168.1.146:8113/v1", "http://192.168.1.103:8113/v1"], model: "muse-op", ctx: 131072, ownerOnly: true, leanPersona: true },
93
+ { id: "moa", tier: "power_turbo", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "the team slot — fans each turn to aurora-local + Cortana 35B + Qwen-Coder 3B proposers (settings.moa, 60s fan-out, graceful per-draft failure) and synthesizes with local Aurora as agent-loop aggregator; roster + benchmark in _ai-docs" },
61
94
  ];
95
+ export const BYO_PRESETS = {
96
+ openai: { label: "OpenAI", endpoint: "https://api.openai.com/v1", model: "gpt-5", ctx: 272000, account: "openai" },
97
+ anthropic: { label: "Anthropic", endpoint: "https://api.anthropic.com/v1", model: "claude-sonnet-4-5", ctx: 200000, account: "anthropic", transport: "anthropic" },
98
+ gemini: { label: "Gemini", endpoint: "https://generativelanguage.googleapis.com/v1beta/openai", model: "gemini-2.5-pro", ctx: 1000000, account: "gemini" },
99
+ groq: { label: "Groq", endpoint: "https://api.groq.com/openai/v1", model: "llama-3.3-70b-versatile", ctx: 131072, account: "groq" },
100
+ deepseek: { label: "DeepSeek", endpoint: "https://api.deepseek.com/v1", model: "deepseek-chat", ctx: 131072, account: "deepseek" },
101
+ mistral: { label: "Mistral", endpoint: "https://api.mistral.ai/v1", model: "mistral-large-latest", ctx: 131072, account: "mistral" },
102
+ openrouter: { label: "OpenRouter", endpoint: "https://openrouter.ai/api/v1", model: "openai/gpt-5", ctx: 200000, account: "openrouter" },
103
+ together: { label: "Together", endpoint: "https://api.together.xyz/v1", model: "meta-llama/Llama-3.3-70B-Instruct-Turbo", ctx: 131072, account: "together" },
104
+ xai: { label: "xAI Grok", endpoint: "https://api.x.ai/v1", model: "grok-4", ctx: 256000, account: "xai" },
105
+ qwen: { label: "QwenCloud", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, account: "qwen" },
106
+ };
62
107
  /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
63
108
  * built-in by id, or adding a new one) — same shape either way, so /model doesn't care which. */
64
109
  export function modelRegistry(overrides) {
@@ -73,6 +118,41 @@ export function findModel(registry, id) {
73
118
  const canon = MODEL_ALIASES[id] ?? id; // aurora-1m -> operator-1m (old ids keep resolving)
74
119
  return registry.find((m) => m.id === canon);
75
120
  }
121
+ /** The tier of a model id (alias-aware), or undefined when the profile has none. */
122
+ export function tierOf(registry, id) {
123
+ return findModel(registry, id)?.tier;
124
+ }
125
+ /** Every profile at exactly `tier`, in registry order. Picker-truth semantics by default:
126
+ * hidden and ownerOnly profiles are not OFFERED by tier (they still resolve by id elsewhere). */
127
+ export function profilesByTier(registry, tier, opts) {
128
+ return registry.filter((m) => m.tier === tier && (opts?.includeHidden || (!m.hidden && !m.ownerOnly)));
129
+ }
130
+ /**
131
+ * Resolve a tier to a concrete profile. Exact tier first (registry order decides within a tier —
132
+ * builtins lead with the recommended default). When the tier is empty, `fallback` walks the
133
+ * ladder: "down" (default) degrades toward cheaper tiers — a routing request never silently
134
+ * UPGRADES to a pricier class — while "up" climbs toward stronger ones (use when a floor matters
135
+ * more than cost); "none" is exact-only.
136
+ */
137
+ export function resolveByTier(registry, tier, opts) {
138
+ const fallback = opts?.fallback ?? "down";
139
+ const start = TIER_LADDER.indexOf(tier);
140
+ if (start === -1)
141
+ return undefined;
142
+ const order = fallback === "none" ? [tier]
143
+ : fallback === "down" ? TIER_LADDER.slice(start)
144
+ : [...TIER_LADDER.slice(0, start + 1)].reverse();
145
+ for (const t of order) {
146
+ const hit = profilesByTier(registry, t, opts)[0];
147
+ if (hit)
148
+ return hit;
149
+ }
150
+ return undefined;
151
+ }
152
+ /** The tier a grandmaster spawn lane wants (string-literal lanes — engine types never import here). */
153
+ export function laneTier(lane) {
154
+ return lane === "reasoning" ? "power" : "lite";
155
+ }
76
156
  /** The configured context window (tokens) for a model id — from BUILTIN_MODELS + settings overrides — or
77
157
  * Infinity if unknown. Used to pick a LEAN harness: a small-context model (e.g. a self-hosted 8K Venice)
78
158
  * can't take Operator's full memory + handoff injection (sized for Aurora's 300K); it fills the window and
@@ -86,25 +166,36 @@ export function modelCtxFor(id, overrides) {
86
166
  /** ctx window below which the lean harness (no heavy memory/handoff) kicks in. Aurora/Qwen (128K+) stay
87
167
  * full; a self-hosted small model (Venice 8K, or a 16K bump) goes lean. */
88
168
  export const LEAN_HARNESS_CTX = 32768;
169
+ /** Whether a model runs the lean harness: small context (< LEAN_HARNESS_CTX) OR a profile that forces it via
170
+ * `leanPersona` (a weak but big-context model). The ONE place both surfaces (cli.tsx, session-factory) decide. */
171
+ export function leanHarnessFor(id, overrides) {
172
+ if (modelCtxFor(id, overrides) < LEAN_HARNESS_CTX)
173
+ return true;
174
+ return !!findModel(modelRegistry(overrides), id ?? "")?.leanPersona;
175
+ }
89
176
  /** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
90
177
  * directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
91
178
  * which this module intentionally doesn't import). `hasByo` (injected by the caller, see auth/byo)
92
179
  * gates BYO connector profiles: honest "not connected" beats a request-time 401. */
93
- export function selectModel(registry, id, hasByo) {
180
+ export function selectModel(registry, id, hasByo, isOwner = true) {
94
181
  const profile = findModel(registry, id);
95
182
  if (!profile)
96
183
  return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
97
- if (profile.kind === "single" && !profile.endpoint)
184
+ if (profile.kind === "single" && !profile.endpoint && !profile.endpoints?.length)
98
185
  return { error: `model "${id}" has no endpoint configured` };
186
+ if (profile.ownerOnly && !isOwner)
187
+ return { error: `"${id}" is owner-only` };
99
188
  if (profile.byo && hasByo && !hasByo(profile.byo)) {
100
- return { error: `"${id}" is not connected — store the ${profile.byo} key first: operator auth byo ${profile.byo}` };
189
+ return { error: `"${id}" is not connected — store the ${profile.byo} key first: operator auth byo-key ${profile.byo}` };
101
190
  }
102
191
  return { profile };
103
192
  }
104
193
  /** The picker-truth view of a registry: drops BYO profiles whose key isn't connected (and ALL
105
- * unresolvable ones when the resolver is absent — a picker must never offer what setModel refuses). */
106
- export function visibleModels(registry, hasByo) {
107
- return registry.filter((p) => !p.hidden && (!p.byo || (hasByo ? hasByo(p.byo) : false)));
194
+ * unresolvable ones when the resolver is absent — a picker must never offer what setModel refuses),
195
+ * and owner-only profiles for any non-owner seat. `isOwner` defaults true (the implicit local owner);
196
+ * a narrowed-tier surface MUST pass isOwner=false so an owner-only lane never leaks into its picker. */
197
+ export function visibleModels(registry, hasByo, isOwner = true) {
198
+ return registry.filter((p) => !p.hidden && (!p.ownerOnly || isOwner) && (!p.byo || (hasByo ? hasByo(p.byo) : false)));
108
199
  }
109
200
  /** Strip a trailing /v1 so a ModelProfile/MoaAggregator endpoint can feed the AuroraRouter, whose
110
201
  * base is bare (engine/aurora.ts's chat() appends /v1/chat/completions itself). */
@@ -0,0 +1,100 @@
1
+ // Portal client — live per-model state from the AXE portal control plane, read through the gateway
2
+ // (GET /api/v1/models, AuthGate-gated). Read path only: it annotates the /model picker and powers an honest
3
+ // "this model is offline" note. It NEVER decides which models are offered or routed (the registry does), and
4
+ // ANY failure — signed out, 401, 502, junk JSON, timeout, network — yields `undefined`, so the picker renders
5
+ // exactly as it did before the portal existed. Absent-from-the-list means UNKNOWN, never offline.
6
+ import { GATEWAY_BASE } from "./models.js";
7
+ import { authHeaders } from "../engine/aurora.js";
8
+ const STATES = new Set(["loaded", "available", "loading", "parked", "offline", "failed"]);
9
+ /** The portal catalog URL, derived from the one gateway address (models.ts GATEWAY_BASE). */
10
+ export function portalModelsUrl(gatewayBase = GATEWAY_BASE) {
11
+ return `${new URL(gatewayBase).origin}/api/v1/models`;
12
+ }
13
+ /** Pure: OpenAI-shaped `{object:"list", data:[{id,state,node|owned_by,stale?}]}` → catalog. Entries without a
14
+ * string id or a known state are skipped (unknown stays unknown); a non-list body yields undefined. */
15
+ export function parsePortalModels(body) {
16
+ if (typeof body !== "object" || body === null)
17
+ return undefined;
18
+ const data = body.data;
19
+ if (!Array.isArray(data))
20
+ return undefined;
21
+ const out = new Map();
22
+ for (const raw of data) {
23
+ if (typeof raw !== "object" || raw === null)
24
+ continue;
25
+ const m = raw;
26
+ if (typeof m.id !== "string" || typeof m.state !== "string" || !STATES.has(m.state))
27
+ continue;
28
+ const node = typeof m.node === "string" ? m.node : typeof m.owned_by === "string" ? m.owned_by : undefined;
29
+ out.set(m.id, { state: m.state, node, stale: m.stale === true });
30
+ }
31
+ return out;
32
+ }
33
+ /** Pure: the id the PORTAL knows a registry profile by — its gateway alias (endpointModels[0]) or its served
34
+ * model name. A profile whose served name is a filesystem path (a direct-only llama-server) simply never matches,
35
+ * which is the point: absent from the portal catalog means unknown. */
36
+ export function portalIdFor(p) {
37
+ return p.endpointModels?.[0] ?? p.model ?? p.id;
38
+ }
39
+ /** Pure: the picker marker for one model, "" when the portal doesn't know it. ● loaded, ○ available/parked/
40
+ * loading, ✕ offline/failed, ? stale (the control plane is serving a last-known value for that node). */
41
+ export function stateMarker(m) {
42
+ if (!m)
43
+ return "";
44
+ if (m.stale)
45
+ return "? ";
46
+ if (m.state === "loaded")
47
+ return "● ";
48
+ if (m.state === "offline" || m.state === "failed")
49
+ return "✕ ";
50
+ return "○ ";
51
+ }
52
+ /** Pure: the picker rows with portal markers applied — same count, same order, same text; a row only changes
53
+ * (gains a leading marker) where the portal knows its id. `cat` undefined (portal unreachable) returns the rows as-is. */
54
+ export function markPickerOptions(plain, portalIds, cat) {
55
+ return plain.map((t, i) => `${stateMarker(cat?.get(portalIds[i]))}${t}`);
56
+ }
57
+ /** Pure: one honest line for a selection the portal reports down; undefined (no note) otherwise. */
58
+ export function offlineNote(label, m) {
59
+ if (!m || m.stale || (m.state !== "offline" && m.state !== "failed"))
60
+ return undefined;
61
+ return `${label} is ${m.state}${m.node ? ` on ${m.node}` : ""} — the gateway will try its fallback, or pick another with /model`;
62
+ }
63
+ const DEFAULTS = { timeoutMs: 3000, ttlMs: 30_000, failTtlMs: 5000 };
64
+ let cache;
65
+ let inflight;
66
+ export function resetPortalCache() {
67
+ cache = undefined;
68
+ inflight = undefined;
69
+ }
70
+ /** Live catalog or undefined. Never throws. Successes cache 30s, failures 5s (so a picker opened repeatedly while
71
+ * the gateway is down doesn't stall on a fresh 3s timeout each time); concurrent callers share one request. */
72
+ export function fetchPortalModels(opts = {}) {
73
+ const now = (opts.now ?? Date.now)();
74
+ const url = portalModelsUrl(opts.gatewayBase);
75
+ if (cache && cache.key === url && now - cache.at < cache.ttl)
76
+ return Promise.resolve(cache.value);
77
+ if (inflight)
78
+ return inflight;
79
+ const f = opts.fetchImpl ?? fetch;
80
+ const timeoutMs = opts.timeoutMs ?? DEFAULTS.timeoutMs;
81
+ const ttlMs = opts.ttlMs ?? DEFAULTS.ttlMs;
82
+ inflight = (async () => {
83
+ const ac = new AbortController();
84
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
85
+ let value;
86
+ try {
87
+ const res = await f(url, { headers: { Accept: "application/json", ...authHeaders({ base: url, model: "" }) }, signal: ac.signal });
88
+ value = res.ok ? parsePortalModels(await res.json()) : undefined;
89
+ }
90
+ catch {
91
+ value = undefined;
92
+ }
93
+ finally {
94
+ clearTimeout(timer);
95
+ }
96
+ cache = { at: (opts.now ?? Date.now)(), ttl: value ? ttlMs : DEFAULTS.failTtlMs, value, key: url };
97
+ return value;
98
+ })().finally(() => { inflight = undefined; });
99
+ return inflight;
100
+ }
@@ -1,7 +1,7 @@
1
1
  // ONE model: Aurora at its native 1M context on :8097 (the air/1m/saddle roster collapsed here once 1M
2
2
  // served at full speed). The router still handles N endpoints generically; this default just has one.
3
3
  const DEFAULT_ENDPOINTS = [
4
- { name: "aurora", base: "http://127.0.0.1:8097", model: "aurora", ctxLimit: 307200 },
4
+ { name: "aurora", base: "http://127.0.0.1:8097", model: "aurora", ctxLimit: 1000000 },
5
5
  ];
6
6
  // Leave headroom under the hard ctx limit — mirrors SPEC §5's 0.85 compaction threshold, so
7
7
  // routing and compaction agree on what "fits."
@@ -11,6 +11,12 @@
11
11
  // because that would break every other client. launchd's KeepAlive is the real supervisor — the
12
12
  // lever just makes sure the job is loaded and the port is live before the REPL opens.
13
13
  // • autopilot (:9333) is optional and handled the same start-only way (non-fatal if it won't come up).
14
+ // • vision (:7788, axe.vision-bot) is OFF BY DEFAULT — the media-pipeline ADR (2026-10-19) keeps the
15
+ // GPU with Aurora, so boot only PROBES + reports it (settings DEFAULTS ship autostart:false). The
16
+ // start happens at POINT OF NEED: ensureVisionUp() below, called by the image_analyze vision chain
17
+ // when a local vision target is down. A launchd-disabled job makes bootstrap fail I/O-error(5)
18
+ // until `enable` runs first — ensureLaunchd's kick-failure path (bootout→enable→bootstrap→kickstart)
19
+ // is exactly that repair.
14
20
  // • SearXNG is session-scoped and owned by tools/searxng.ts (lazy start + idle/exit stop) — the only
15
21
  // service Operator tears down, via stopSessionServices() below.
16
22
  const nodeImport = (m) => import(/* @vite-ignore */ m);
@@ -120,20 +126,114 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
120
126
  ? { name, state: "started" }
121
127
  : { name, state: "down", detail: `started the launchd job but ${name} did not report ready at ${healthUrl} within ${waitSec}s` };
122
128
  }
123
- /** Ensure the services Operator depends on are up. Aurora first (required, health-gated); autopilot is
124
- * optional and never blocks. Returns one report per service for the boot UI. */
129
+ /** The live gateway the supervisor publishes to ~/.operator/runtime/server.json. The contract is
130
+ * that the supervisor writes {base_url, api_key, pid} and consumers read BOTH: `base` to reach the dynamic
131
+ * port, `apiKey` to authenticate to it. Returns null when server.json is absent (gateway not running yet). */
132
+ export async function discoverAuroraServer() {
133
+ try {
134
+ const { readFile } = await nodeImport("node:fs/promises");
135
+ const serverJson = `${process.env.HOME ?? ""}/.operator/runtime/server.json`;
136
+ const raw = await readFile(serverJson, "utf8");
137
+ const state = JSON.parse(raw);
138
+ if (state.base_url && typeof state.base_url === "string") {
139
+ return { base: state.base_url, apiKey: typeof state.api_key === "string" ? state.api_key : undefined };
140
+ }
141
+ }
142
+ catch { /* server.json absent or unreadable — gateway not running yet */ }
143
+ return null;
144
+ }
145
+ /** Back-compat shim: just the base_url (e.g. "http://127.0.0.1:52100/v1") or null. */
146
+ export async function discoverAuroraEndpoint() {
147
+ return (await discoverAuroraServer())?.base ?? null;
148
+ }
149
+ /** Ensure the services Operator depends on are up. Aurora first (required, health-gated); autopilot and
150
+ * vision are optional and never block. Returns one report per service for the boot UI.
151
+ * Mutates cfg.aurora.base in-place when the dynamic port is discovered from server.json. */
125
152
  export async function ensureServices(cfg) {
126
153
  const reports = [];
127
- reports.push(await ensureLaunchd("aurora", `${cfg.aurora.base.replace(/\/$/, "")}/health`, true, cfg.aurora, cfg.onProgress));
154
+ // Apply a server.json discovery onto cfg.aurora (dynamic port + api_key). Falls back to the
155
+ // existing cfg.aurora.base when server.json is absent (e.g. a settings.json static override).
156
+ const applyDiscovered = (d) => {
157
+ if (!d)
158
+ return false;
159
+ cfg.aurora.base = d.base.replace(/\/v1\/?$/, "");
160
+ if (d.apiKey)
161
+ cfg.aurora.apiKey = d.apiKey; // carry the gateway's published key onto the cfg
162
+ return true;
163
+ };
164
+ applyDiscovered(await discoverAuroraServer());
165
+ if (cfg.aurora.base) {
166
+ const healthUrl = `${cfg.aurora.base.replace(/\/$/, "")}/health`;
167
+ reports.push(await ensureLaunchd("aurora", healthUrl, true, cfg.aurora, cfg.onProgress));
168
+ // After launchd start, re-discover in case the port changed (fresh spawn)
169
+ if (reports[0]?.state === "started" || reports[0]?.state === "down") {
170
+ applyDiscovered(await discoverAuroraServer());
171
+ }
172
+ }
173
+ else {
174
+ // No endpoint discovered and no static override — kickstart the gateway, then discover
175
+ reports.push(await ensureLaunchd("aurora", "", true, cfg.aurora, cfg.onProgress));
176
+ // Wait a beat for server.json to appear after gateway start
177
+ await new Promise((r) => setTimeout(r, 3000));
178
+ const retry = await discoverAuroraServer();
179
+ if (applyDiscovered(retry)) {
180
+ const retryHealth = `${cfg.aurora.base.replace(/\/$/, "")}/health`;
181
+ if (await waitReady(retryHealth, true, cfg.aurora.waitSec ?? 45)) {
182
+ reports[reports.length - 1] = { name: "aurora", state: "started", detail: `discovered at ${retry.base}` };
183
+ }
184
+ }
185
+ }
128
186
  if (cfg.autopilot) {
129
- const url = (cfg.autopilot.url ?? "http://127.0.0.1:9333").replace(/\/$/, "");
130
- // Optional service: cap the readiness wait hard so a present-but-unhealthy autopilot can never hold
131
- // the REPL for the required-service budget (Aurora's 90s). A real `node serve` answers in <2s.
132
- const apCfg = { ...cfg.autopilot, waitSec: Math.min(cfg.autopilot.waitSec ?? 8, 8) };
133
- reports.push(await ensureLaunchd("autopilot", `${url}/`, false, apCfg, cfg.onProgress));
187
+ reports.push(await ensureOptional("autopilot", cfg.autopilot, cfg.onProgress));
188
+ }
189
+ if (cfg.vision) {
190
+ reports.push(await ensureOptional("vision", cfg.vision, cfg.onProgress, "/health"));
134
191
  }
135
192
  return reports;
136
193
  }
194
+ /** One optional companion: cap the readiness wait hard so a present-but-unhealthy service can never hold
195
+ * the REPL for the required-service budget (Aurora's 90s). A real node server answers in <2s. `healthPath`
196
+ * is "" for services with no /health route (any answer counts) or "/health" for ones that do. */
197
+ async function ensureOptional(name, cfg, onProgress, healthPath = "/") {
198
+ const url = (cfg.url ?? (name === "vision" ? "http://127.0.0.1:7788" : "http://127.0.0.1:9333")).replace(/\/$/, "");
199
+ const optCfg = { ...cfg, waitSec: Math.min(cfg.waitSec ?? 8, 8) };
200
+ return ensureLaunchd(name, `${url}${healthPath}`, healthPath !== "/", optCfg, onProgress);
201
+ }
202
+ /** Point-of-need vision start — the ADR's deferred auto-on, done client-side. image_analyze calls this
203
+ * when a LOCAL vision target fails /health, so the media pipeline comes up for the turn that needs it
204
+ * while boot never touches it (GPU stays with Aurora by default). Reuses the full ensureLaunchd repair
205
+ * (kickstart → bootout/enable/bootstrap/kickstart), so a job left launchd-disabled — by `media-pipeline
206
+ * off` or a stale eval pause — self-heals here instead of dying with bootstrap I/O-error(5). Single-flight:
207
+ * concurrent callers share one start attempt; a short negative TTL so a genuinely broken worker doesn't
208
+ * re-kick launchd on every retry. Returns true iff vision answered /health. */
209
+ let visionStart = null;
210
+ let visionStartFailedAt = 0;
211
+ const VISION_START_TTL_MS = 60_000;
212
+ export function ensureVisionUp(url = "http://127.0.0.1:7788") {
213
+ if (visionStart)
214
+ return visionStart;
215
+ if (Date.now() - visionStartFailedAt < VISION_START_TTL_MS)
216
+ return Promise.resolve(false);
217
+ visionStart = (async () => {
218
+ const uid = typeof process.getuid === "function" ? process.getuid() : NaN;
219
+ if (Number.isNaN(uid)) {
220
+ visionStartFailedAt = Date.now();
221
+ return false;
222
+ }
223
+ const r = await ensureLaunchd("vision", `${url.replace(/\/$/, "")}/health`, true, {
224
+ autostart: true,
225
+ launchdLabel: "axe.vision-bot",
226
+ plistPath: "~/Library/LaunchAgents/axe.vision-bot.plist",
227
+ waitSec: 12, // qwen2.5vl:7b is an ollama-backed worker — a cold load is seconds, not minutes
228
+ });
229
+ const ok = r.state === "up" || r.state === "started";
230
+ if (!ok)
231
+ visionStartFailedAt = Date.now();
232
+ visionStart = null;
233
+ return ok;
234
+ })();
235
+ return visionStart;
236
+ }
137
237
  /** Best-effort install of an optional companion (autopilot / chauffeur) via the packaged setup script,
138
238
  * DETACHED so it never blocks boot. Sourcing (fleet rsync / clone) lives in scripts/setup-services.sh —
139
239
  * kept out of the JS so the mobile bundle carries no installer. No-ops if the script or spawn is absent. */