@0perator/operator 0.1.350 → 0.1.352

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.
@@ -276,17 +276,18 @@ export async function dispatchAutonomy(argv, settings) {
276
276
  const cmd = argv[2];
277
277
  if (!cmd || !AUTONOMY_COMMANDS.has(cmd))
278
278
  return null;
279
- // Headless paths skip the interactive preflight (cli.tsx's ensureServices), which both RESOLVES the
280
- // dynamic Aurora endpoint from the operator-runtime server.json AND brings the launchd gateway UP if it
281
- // is down. Mirror that FULL blueprint here — the same EnsureCfg (aurora launchd cfg + optional services) —
282
- // so a headless `operator run/loop/board/routine` on a cold box self-heals instead of failing with a
283
- // baseless "/v1/chat/completions" (Failed to parse URL) against an unset (auto-discover) endpoints.aurora.base.
279
+ // Headless paths skip the interactive preflight (cli.tsx's ensureServices), which RESOLVES the dynamic Aurora
280
+ // endpoint from the operator-runtime server.json. Mirror it here — the same EnsureCfg (aurora launchd cfg +
281
+ // optional services) — so a headless `operator run/loop/board/routine` never sends to a baseless
282
+ // "/v1/chat/completions" (Failed to parse URL). Aurora itself loads on demand: the session's onDemand hook starts
283
+ // it for the first turn on it (session-factory.ts), so a run on another model never loads it.
284
284
  // Guarded to the empty-base case (the only time we must discover/start), and gateway-aware: carry the
285
285
  // gateway's published api_key (server.json) onto the endpoint config so the router authenticates to it.
286
286
  if (!settings.endpoints.aurora.base) {
287
287
  const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
288
288
  await ensureServices({
289
289
  aurora: auroraCfg,
290
+ auroraOnDemand: true, // resolve the endpoint only: a run on Aurora loads it at its first turn
290
291
  autopilot: settings.services?.autopilot,
291
292
  vision: settings.services?.vision,
292
293
  onProgress: (m) => process.stderr.write(`[services] ${m}\n`),
@@ -13,6 +13,7 @@ import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.
13
13
  import { compactionThreshold, compactionCeilingTokens, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
14
14
  import { resolveMode } from "../classifier/modes.js";
15
15
  import { classifierConfig } from "../classifier/config.js";
16
+ import { auroraOnDemand } from "../services/preflight.js";
16
17
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
17
18
  * multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
18
19
  * wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
@@ -63,6 +64,9 @@ export function createAutonomySession(settings, opts = {}) {
63
64
  fastStart: settings.fastStart,
64
65
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
65
66
  activeModel: settings.activeModel,
67
+ // A local Aurora loads for the first turn on it (owner, 11/03), never for the run starting: a run on moa or cortana
68
+ // (setModel below) never loads it.
69
+ onDemand: auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, () => buildRouterFromSettings(settings)),
66
70
  contextPin: settings.contextPin, // the owner's /context choice (KODE_CONTEXT wins in loadSettings) holds for headless, ACP and delegated runs too
67
71
  permissions: opts.permissions ?? settings.permissions,
68
72
  // Audit attribution: without these every headless/cron/dream tool event carried session:"" and no seat.
package/dist/cli.js CHANGED
@@ -245,7 +245,7 @@ if (settings.computer.enabled) {
245
245
  const askNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_ACTION_NAMES : [])];
246
246
  computerAskRules = Object.fromEntries(askNames.map((n) => [n, "ask"]));
247
247
  // Background sub-agents have no approver, so DENY every embodiment tool, reads included.
248
- const denyNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
248
+ const denyNames = [...COMPUTER_TOOL_NAMES, "desktop_screenshot", "desktop_read", ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
249
249
  computerDenyRules = Object.fromEntries(denyNames.map((n) => [n, "deny"]));
250
250
  }
251
251
  // STANDARD MCP: report-mcp (PDF tools) ships with Operator — always injected, even without the full-fleet
@@ -644,6 +644,18 @@ function Root() {
644
644
  const freeRowsRef = useRef([]);
645
645
  const freeStaleRef = useRef(false); // served from the disk cache after a failed read → the rows say " · cached"
646
646
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
647
+ // Aurora loads on demand (owner, 11/03): the first turn that needs a local Aurora starts the launchd gateway, and boot
648
+ // never does. The hook is built on first use; it is inert where Aurora is not a launchd job on this box.
649
+ const auroraHookRef = useRef(null);
650
+ const auroraForTurn = async (signal) => {
651
+ if (!auroraHookRef.current) {
652
+ const { auroraOnDemand } = await import("./services/preflight.js");
653
+ auroraHookRef.current = auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, buildRouter, () => {
654
+ push({ kind: "message", message: { id: nextId(), role: "system", content: "aurora is not loaded — loading it for this turn…" } });
655
+ });
656
+ }
657
+ return auroraHookRef.current(signal);
658
+ };
647
659
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
648
660
  // only, no network fan-out at session start). Background agents stay local-only + lean.
649
661
  if (!sessionRef.current) {
@@ -651,6 +663,8 @@ function Root() {
651
663
  systemPrompt: SYSTEM_PROMPT,
652
664
  thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
653
665
  router: buildRouter(),
666
+ applyActiveModel: true, // the persisted /model choice still applies with the shell's chain injected
667
+ onDemand: auroraForTurn,
654
668
  memory: buildMemory(settings.memory), // provider composite when configured; bare store (byte-identical) otherwise
655
669
  mcp: settings.mcp,
656
670
  mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
@@ -796,9 +810,10 @@ function Root() {
796
810
  background: true, // endpoint gate: this is a sub-agent — its Aurora requests yield the shared single slot to the interactive main turn (fixes the sub-agent-contention crawl + "4 min for a prompt")
797
811
  cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
798
812
  temperature: settings.temperature,
799
- // Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
800
- // denied outright. (No-op when computer control is off.) Everything else runs as normal.
801
- permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
813
+ // Sub-agents have no approval prompt: any computer_* call is denied outright, and `unattended` keeps the
814
+ // signature lines live (permissions/signature.ts), so a force-push, deploy or destructive command is
815
+ // denied too, computer control on or off. The seat's tier still applies. Everything else runs as normal.
816
+ permissions: { mode: "bypass", tier: settings.permissions.tier, rules: computerDenyRules, unattended: true },
802
817
  eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // a sub-agent's tool calls belong to THIS session in the ledger
803
818
  });
804
819
  const r = child.setModel(model);
@@ -903,6 +918,7 @@ function Root() {
903
918
  const auroraCfg = { base: bootBase, ...settings.services?.aurora };
904
919
  reports = await preflight.ensureServices({
905
920
  aurora: auroraCfg,
921
+ auroraOnDemand: true, // resolve and report Aurora only: the turn that needs it loads it
906
922
  autopilot: settings.services?.autopilot,
907
923
  vision: settings.services?.vision,
908
924
  onProgress: setBootDetail,
@@ -924,18 +940,18 @@ function Root() {
924
940
  if (settings.endpoints.aurora.base !== bootBase || settings.endpoints.aurora.apiKey !== bootKeyBefore) {
925
941
  session.useRouter(buildRouter());
926
942
  }
927
- // If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
928
- // eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
929
- if (reports.find((r) => r.name === "aurora")?.state === "started") {
930
- void preflight.warmAurora(settings.endpoints.aurora.base, settings.endpoints.aurora.model);
931
- }
932
943
  }
933
944
  catch { /* preflight is best-effort — fall through to the authoritative health check */ }
934
- const ok = await session.health().catch(() => false);
945
+ // A local Aurora that is not loaded is not a failed boot: it loads on the first turn that needs it, and a
946
+ // session on another model (moa, cortana) never needs it.
947
+ const ok = reports.find((r) => r.name === "aurora")?.state === "idle" || (await session.health().catch(() => false));
935
948
  setBoot(ok ? "ready" : "down");
936
949
  if (!ok) {
937
950
  const a = reports.find((r) => r.name === "aurora");
938
- setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
951
+ // Another model (moa, cortana) failed on its own endpoint: name that one, not Aurora's.
952
+ setBootDetail(session.currentModel() === DEFAULT_MODEL_ID
953
+ ? a?.detail ?? `no response from ${session.healthTarget()}`
954
+ : `${session.currentModel()}: no response from ${session.healthTarget()}`);
939
955
  return;
940
956
  }
941
957
  // The primary's served window, learned now rather than after the first overflow — AFTER the lever, so the gateway's
@@ -984,7 +1000,7 @@ function Root() {
984
1000
  }
985
1001
  }
986
1002
  // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
987
- const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
1003
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : r.state === "idle" ? "on demand" : "✗"}`).join(" · ");
988
1004
  if (line) {
989
1005
  // SearXNG is lazy (starts on first web_search), but if a backend is ALREADY reachable — an explicit
990
1006
  // KODE_SEARXNG_URL, or a container still up from a prior session — show ✓ instead of a misleading
@@ -2670,7 +2686,9 @@ function Root() {
2670
2686
  if (boot === "checking")
2671
2687
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
2672
2688
  if (boot === "down") {
2673
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsxs(Text, { dimColor: true, children: ["The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/", settings.services?.aurora?.launchdLabel ?? "co.0perator.gateway"] })] }));
2689
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, session.currentModel() === DEFAULT_MODEL_ID
2690
+ ? _jsxs(Text, { dimColor: true, children: ["The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/", settings.services?.aurora?.launchdLabel ?? "co.0perator.gateway"] })
2691
+ : _jsxs(Text, { dimColor: true, children: ["Start on Aurora instead: set \"activeModel\": \"", DEFAULT_MODEL_ID, "\" in settings.json, then /model ", session.currentModel(), " once it is reachable."] })] }));
2674
2692
  }
2675
2693
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
2676
2694
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -2686,7 +2704,7 @@ function Root() {
2686
2704
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
2687
2705
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
2688
2706
  : metrics;
2689
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, ctxPin: ctxPin ? fmtCtx(ctxPin) : undefined, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
2707
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, ctxWindow: session.currentModel() === "moa" ? (ctxPin ? fmtCtx(ctxPin) : undefined) : fmtCtx(ctxPin ? Math.min(ctxPin, session.servedContext()) : session.servedContext()), version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
2690
2708
  const cur = approval;
2691
2709
  if (cur)
2692
2710
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -640,3 +640,26 @@ export async function health(base) {
640
640
  return false;
641
641
  }
642
642
  }
643
+ /** Does anything serve at {base}? The boot check's probe, which may face llama-server (GET /health → {"status":"ok"}),
644
+ * the portal router (GET /healthz → {"ok":true}; it has no /health) or any other OpenAI-compatible endpoint (GET
645
+ * /v1/models: any answer below 500, a 401/403 included, proves it is up). Each probe is bounded, so a hung endpoint
646
+ * can't hold the boot screen. A llama-server still loading answers 503 everywhere: not reachable yet. */
647
+ export async function reachable(base, timeoutMs = 3000) {
648
+ if (!base)
649
+ return false;
650
+ const get = (path) => fetch(`${base}${path}`, { signal: AbortSignal.timeout(timeoutMs) });
651
+ for (const [path, ok] of [["/health", (j) => j?.status === "ok"], ["/healthz", (j) => j?.ok === true]]) {
652
+ try {
653
+ const res = await get(path);
654
+ if (res.ok && ok(await res.json().catch(() => null)))
655
+ return true;
656
+ }
657
+ catch { /* not this probe — try the next */ }
658
+ }
659
+ try {
660
+ return (await get("/v1/models")).status < 500;
661
+ }
662
+ catch {
663
+ return false;
664
+ }
665
+ }
@@ -48,17 +48,20 @@ export class PermissionPolicy {
48
48
  safe;
49
49
  tier;
50
50
  allow;
51
+ unattended;
51
52
  constructor(cfg = {}) {
52
53
  this.mode = cfg.mode ?? "bypass";
53
54
  this.rules = cfg.rules ?? {};
54
55
  this.safe = new Set(cfg.safeTools ?? DEFAULT_SAFE);
55
56
  this.tier = cfg.tier ?? "admin";
56
57
  this.allow = cfg.allow ?? [];
58
+ this.unattended = cfg.unattended === true;
57
59
  }
58
60
  /** True when the policy can never block, prompt, or log — lets the wrapper skip itself entirely (no
59
- * overhead). Requires the full-access owner tier: a narrowed tier is always enforced, even in bypass. */
61
+ * overhead). Requires the full-access owner tier: a narrowed tier is always enforced, even in bypass. An
62
+ * unattended policy is never inert: with no owner to answer, the signature lines are its only floor. */
60
63
  get inert() {
61
- return this.mode === "bypass" && this.tier === "admin" && Object.keys(this.rules).length === 0;
64
+ return this.mode === "bypass" && this.tier === "admin" && !this.unattended && Object.keys(this.rules).length === 0;
62
65
  }
63
66
  /** Whether tool actions should be recorded. On in audit/gated, or whenever a tier is enforced (a
64
67
  * multi-tenant seat is always audited — "who did what" is the point of a seat). */
@@ -5,11 +5,11 @@
5
5
  // (there is no launchd; ensureServices returns everything "down" and the caller reports it).
6
6
  //
7
7
  // TWO tiers, and the split is the whole point:
8
- // • Aurora (:8097) is SHARED, always-on infrastructure owned by launchd — the mobile app (via
9
- // ai.operator.tunnel), api.axe.onl / aurora.axe.onl, and LAN web clients all read it. Operator
10
- // only ever brings it UP (kickstart, else bootstrap, the launchd job); it NEVER stops Aurora on exit,
11
- // because that would break every other client. launchd's KeepAlive is the real supervisor — the
12
- // lever just makes sure the job is loaded and the port is live before the REPL opens.
8
+ // • Aurora is SHARED infrastructure owned by launchd (co.0perator.gateway) — the router's jl2 backend, the
9
+ // mobile app and LAN clients all read it — and it loads ON DEMAND (owner, 11/03): only the turn that needs
10
+ // it starts it (ensureAurora, wired as the Session's onDemand hook). Boot never does: auroraAtBoot resolves
11
+ // the published endpoint and reports `idle` for a local job that is not serving. Operator only ever brings
12
+ // it UP; it NEVER stops Aurora on exit, because that would break every other client.
13
13
  // • autopilot (:9333) is optional and handled the same start-only way (non-fatal if it won't come up).
14
14
  // • vision (:7788, axe.vision-bot) is OFF BY DEFAULT — the media-pipeline ADR (2026-10-19) keeps the
15
15
  // GPU with Aurora, so boot only PROBES + reports it (settings DEFAULTS ship autostart:false). The
@@ -100,6 +100,17 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
100
100
  ? { name, state: "up" }
101
101
  : { name, state: "down", detail: `${name} still loading after ${waitSec}s` };
102
102
  }
103
+ const refused = await kickLaunchd(name, cfg, onProgress);
104
+ if (refused)
105
+ return refused;
106
+ // 3) poll — a heavy model (Aurora is ~20G with mlock) needs time to mmap + report ready.
107
+ return (await waitReady(healthUrl, okOnly, waitSec))
108
+ ? { name, state: "started" }
109
+ : { name, state: "down", detail: `started the launchd job but ${name} did not report ready at ${healthUrl} within ${waitSec}s` };
110
+ }
111
+ /** Start `name`'s launchd job: kickstart -k when it is loaded, else bootout any half-state and bootstrap the plist
112
+ * fresh. Returns the report when it will not start it (autostart off, no label/uid, plist missing), else null. */
113
+ async function kickLaunchd(name, cfg, onProgress) {
103
114
  if (cfg.autostart === false)
104
115
  return { name, state: "down", detail: "down (autostart off)" };
105
116
  cfg = await withLegacyLabel(cfg);
@@ -135,10 +146,7 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
135
146
  await launchctl(["bootstrap", `gui/${uid}`, expandHome(cfg.plistPath)]);
136
147
  await launchctl(["kickstart", target]);
137
148
  }
138
- // 3) poll — a heavy model (Aurora is ~20G with mlock) needs time to mmap + report ready.
139
- return (await waitReady(healthUrl, okOnly, waitSec))
140
- ? { name, state: "started" }
141
- : { name, state: "down", detail: `started the launchd job but ${name} did not report ready at ${healthUrl} within ${waitSec}s` };
149
+ return null;
142
150
  }
143
151
  /** The live gateway the supervisor publishes to ~/.operator/runtime/server.json. The contract is
144
152
  * that the supervisor writes {base_url, api_key, pid} and consumers read BOTH: `base` to reach the dynamic
@@ -160,43 +168,89 @@ export async function discoverAuroraServer() {
160
168
  export async function discoverAuroraEndpoint() {
161
169
  return (await discoverAuroraServer())?.base ?? null;
162
170
  }
163
- /** Ensure the services Operator depends on are up. Aurora first (required, health-gated); autopilot and
164
- * vision are optional and never block. Returns one report per service for the boot UI.
165
- * Mutates cfg.aurora.base in-place when the dynamic port is discovered from server.json. */
166
- export async function ensureServices(cfg) {
167
- const reports = [];
168
- // Apply a server.json discovery onto cfg.aurora (dynamic port + api_key). Falls back to the
169
- // existing cfg.aurora.base when server.json is absent (e.g. a settings.json static override).
170
- const applyDiscovered = (d) => {
171
- if (!d)
172
- return false;
173
- cfg.aurora.base = d.base.replace(/\/v1\/?$/, "");
174
- if (d.apiKey)
175
- cfg.aurora.apiKey = d.apiKey; // carry the gateway's published key onto the cfg
176
- return true;
177
- };
178
- applyDiscovered(await discoverAuroraServer());
179
- if (cfg.aurora.base) {
180
- const healthUrl = `${cfg.aurora.base.replace(/\/$/, "")}/health`;
181
- reports.push(await ensureLaunchd("aurora", healthUrl, true, cfg.aurora, cfg.onProgress));
182
- // After launchd start, re-discover in case the port changed (fresh spawn)
183
- if (reports[0]?.state === "started" || reports[0]?.state === "down") {
184
- applyDiscovered(await discoverAuroraServer());
185
- }
186
- }
171
+ const auroraHealth = (base) => (base ? `${base.replace(/\/$/, "")}/health` : "");
172
+ /** Apply a server.json discovery onto an Aurora cfg: the dynamic port and the gateway's published api_key. Keeps the
173
+ * existing base when server.json is absent (a settings.json static override). */
174
+ function applyDiscovered(cfg, d) {
175
+ if (!d)
176
+ return;
177
+ cfg.base = d.base.replace(/\/v1\/?$/, "");
178
+ if (d.apiKey)
179
+ cfg.apiKey = d.apiKey;
180
+ }
181
+ /** True iff Aurora is a launchd job on this box (its plist, or a legacy one, is on disk): the only case it loads on
182
+ * demand. A remote or tester endpoint has no job here and keeps the old health-gated boot. */
183
+ async function localAuroraJob(cfg) {
184
+ const job = await withLegacyLabel(cfg);
185
+ return !!job.launchdLabel && !!job.plistPath && (await fileExists(expandHome(job.plistPath)));
186
+ }
187
+ /** Boot's view of Aurora: resolve the published endpoint and report, never start the gateway. A local job that is not
188
+ * serving is `idle` (the first turn that needs it loads it); with no local job it is `down`, as before. */
189
+ export async function auroraAtBoot(cfg) {
190
+ applyDiscovered(cfg, await discoverAuroraServer());
191
+ const state = cfg.base ? await probe(auroraHealth(cfg.base), true) : "refused";
192
+ if (state === "ready")
193
+ return { name: "aurora", state: "up" };
194
+ if (await localAuroraJob(cfg))
195
+ return { name: "aurora", state: "idle", detail: state === "loading" ? "loading" : "loads on first use" };
196
+ return { name: "aurora", state: "down", detail: cfg.base ? `no response from ${cfg.base}` : "no gateway endpoint published" };
197
+ }
198
+ /** Aurora for a turn that needs it: serving → nothing; loading → wait; else start the launchd job and wait. */
199
+ export async function ensureAurora(cfg, onProgress, signal) {
200
+ applyDiscovered(cfg, await discoverAuroraServer());
201
+ const first = cfg.base ? await probe(auroraHealth(cfg.base), true) : "refused";
202
+ if (first === "ready")
203
+ return { name: "aurora", state: "up" };
204
+ if (first === "loading")
205
+ onProgress?.("aurora is loading…");
187
206
  else {
188
- // No endpoint discovered and no static override — kickstart the gateway, then discover
189
- reports.push(await ensureLaunchd("aurora", "", true, cfg.aurora, cfg.onProgress));
190
- // Wait a beat for server.json to appear after gateway start
191
- await new Promise((r) => setTimeout(r, 3000));
192
- const retry = await discoverAuroraServer();
193
- if (applyDiscovered(retry)) {
194
- const retryHealth = `${cfg.aurora.base.replace(/\/$/, "")}/health`;
195
- if (await waitReady(retryHealth, true, cfg.aurora.waitSec ?? 45)) {
196
- reports[reports.length - 1] = { name: "aurora", state: "started", detail: `discovered at ${retry.base}` };
197
- }
198
- }
207
+ const refused = await kickLaunchd("aurora", cfg, onProgress);
208
+ if (refused)
209
+ return refused;
199
210
  }
211
+ const waitSec = cfg.waitSec ?? 90;
212
+ return (await waitForAurora(cfg, waitSec, signal))
213
+ ? { name: "aurora", state: first === "loading" ? "up" : "started" }
214
+ : { name: "aurora", state: "down", detail: `aurora did not report ready within ${waitSec}s` };
215
+ }
216
+ /** Poll until the published endpoint answers /health, re-reading server.json each time: the gateway publishes its
217
+ * base only once llama-server is spawned and deletes server.json when it stops, so a base read before the kick is
218
+ * stale or absent. Polling that one is the 11/03 boot that sat 90 s on "starting aurora via launchd…" with Aurora
219
+ * ready after 16 s. */
220
+ export async function waitForAurora(cfg, waitSec, signal) {
221
+ for (let waited = 0;; waited += 2) {
222
+ applyDiscovered(cfg, await discoverAuroraServer());
223
+ if (cfg.base && (await probe(auroraHealth(cfg.base), true)) === "ready")
224
+ return true;
225
+ if (waited >= waitSec || signal?.aborted)
226
+ return false;
227
+ await new Promise((res) => setTimeout(res, 2000));
228
+ }
229
+ }
230
+ /** The Session's onDemand hook for a local Aurora: before a turn on the default model, make sure the gateway is
231
+ * serving (start it if not), and when its published base or key changed write them onto `endpoint` and return
232
+ * `rebuild()`. Inert where Aurora is not a local launchd job, so a remote endpoint is never probed per turn. */
233
+ export function auroraOnDemand(endpoint, svc, rebuild, onProgress) {
234
+ let local;
235
+ return async (signal) => {
236
+ local ??= localAuroraJob(svc ?? {});
237
+ if (!(await local))
238
+ return null;
239
+ const cfg = { ...svc, base: endpoint.base, apiKey: endpoint.apiKey };
240
+ await ensureAurora(cfg, onProgress, signal);
241
+ if (cfg.base === endpoint.base && cfg.apiKey === endpoint.apiKey)
242
+ return null;
243
+ endpoint.base = cfg.base;
244
+ if (cfg.apiKey)
245
+ endpoint.apiKey = cfg.apiKey;
246
+ return rebuild();
247
+ };
248
+ }
249
+ /** Ensure the services Operator depends on are up. Aurora first (required, health-gated; with auroraOnDemand only
250
+ * resolved and reported); autopilot and vision are optional and never block. Returns one report per service for the
251
+ * boot UI. Mutates cfg.aurora.base in-place when the dynamic port is discovered from server.json. */
252
+ export async function ensureServices(cfg) {
253
+ const reports = [cfg.auroraOnDemand ? await auroraAtBoot(cfg.aurora) : await ensureAurora(cfg.aurora, cfg.onProgress)];
200
254
  if (cfg.autopilot) {
201
255
  reports.push(await ensureOptional("autopilot", cfg.autopilot, cfg.onProgress));
202
256
  }
package/dist/session.js CHANGED
@@ -5,7 +5,7 @@ import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
5
  import { recordTruncation } from "./observability/blackbox.js";
6
6
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE } from "./engine/messages.js";
7
7
  import { scratchDirFor } from "./config/scratch.js";
8
- import { chat, health, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
8
+ import { chat, health, reachable, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
9
9
  import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
10
10
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
11
11
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
@@ -313,6 +313,7 @@ export class Session {
313
313
  pin; // the owner's context pin (tokens); undefined = auto — read live by the engine router
314
314
  servedByBase = new Map(); // raw n_ctx learned per base (probeServedContext)
315
315
  moaConfig;
316
+ onDemand;
316
317
  classifier;
317
318
  fastStartConfig;
318
319
  fastStartEnabled;
@@ -457,12 +458,14 @@ export class Session {
457
458
  this.registry = modelRegistry(cfg.models);
458
459
  this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
459
460
  this.moaConfig = cfg.moa;
461
+ this.onDemand = cfg.onDemand;
460
462
  this.classifier = cfg.classifier;
461
463
  this.fastStartConfig = cfg.fastStart;
462
464
  this.fastStartEnabled = isFeatureEnabled("fastStart", { features: cfg.features }) && !!cfg.fastStart;
463
465
  // Apply the persisted /model choice, unless a router was explicitly injected (tests / bg agents
464
- // pinned to a fixed endpoint) — an injected router owns routing, /model doesn't override it.
465
- if (!cfg.router && cfg.activeModel && cfg.activeModel !== DEFAULT_MODEL_ID) {
466
+ // pinned to a fixed endpoint) — an injected router owns routing, /model doesn't override it. The shell's own
467
+ // chain is injected too, so it opts in: without that every interactive session started on the default model.
468
+ if ((!cfg.router || cfg.applyActiveModel) && cfg.activeModel && cfg.activeModel !== DEFAULT_MODEL_ID) {
466
469
  if (!this.setModel(cfg.activeModel).ok)
467
470
  this.modelId = DEFAULT_MODEL_ID; // unavailable at startup → quiet fallback
468
471
  }
@@ -651,9 +654,18 @@ export class Session {
651
654
  const carried = this.convo.all.some((m) => typeof m.content === "string" && m.content.includes(header));
652
655
  return carried ? undefined : this.activeSkillBlock;
653
656
  }
654
- /** Is the currently-selected endpoint reachable? Lets the shell fail clearly before a turn. */
657
+ /** The base health() probes: the planner's for MOA (sendMoa builds its own router from it; `inner` is still the
658
+ * shell's first-render chain, whose base was blank before the boot lever resolved the gateway port), else the
659
+ * selected endpoint's. */
660
+ healthTarget() {
661
+ const planner = findModel(this.liveRegistry(), this.modelId)?.kind === "orchestrated" ? moaTeam(this.moaConfig)?.planner : undefined;
662
+ return planner ? endpointBase(planner.endpoint) : this.inner.base;
663
+ }
664
+ /** Is the endpoint the current model talks to reachable? Lets the shell fail clearly before a turn. Probes the
665
+ * way reachable() does, because a non-default model's endpoint is often the portal router, which has /healthz
666
+ * and /v1/models but no llama-server /health: 0.1.351 failed every boot on moa/cortana with the gateway up. */
655
667
  health() {
656
- return health(this.inner.base);
668
+ return reachable(this.healthTarget());
657
669
  }
658
670
  /** The calibration key for the endpoint this session's requests ACTUALLY reach (failover/MOA-aware
659
671
  * — the same base/model the live turn and the summarizer go to, via onRoute capture). */
@@ -1193,6 +1205,13 @@ export class Session {
1193
1205
  // would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
1194
1206
  this.ctrl = new AbortController();
1195
1207
  try {
1208
+ if (this.onDemand && this.modelId === DEFAULT_MODEL_ID) {
1209
+ const fresh = await this.onDemand(this.ctrl.signal);
1210
+ if (fresh)
1211
+ this.useRouter(fresh);
1212
+ if (this.ctrl.signal.aborted)
1213
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1214
+ }
1196
1215
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1197
1216
  if (this.ctrl.signal.aborted)
1198
1217
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };