@0perator/operator 0.1.350 → 0.1.351

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,14 +940,11 @@ 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");
@@ -984,7 +997,7 @@ function Root() {
984
997
  }
985
998
  }
986
999
  // 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(" · ");
1000
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : r.state === "idle" ? "on demand" : "✗"}`).join(" · ");
988
1001
  if (line) {
989
1002
  // SearXNG is lazy (starts on first web_search), but if a backend is ALREADY reachable — an explicit
990
1003
  // KODE_SEARXNG_URL, or a container still up from a prior session — show ✓ instead of a misleading
@@ -2686,7 +2699,7 @@ function Root() {
2686
2699
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
2687
2700
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
2688
2701
  : 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) => {
2702
+ 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
2703
  const cur = approval;
2691
2704
  if (cur)
2692
2705
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -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
@@ -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
  }
@@ -1193,6 +1196,13 @@ export class Session {
1193
1196
  // would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
1194
1197
  this.ctrl = new AbortController();
1195
1198
  try {
1199
+ if (this.onDemand && this.modelId === DEFAULT_MODEL_ID) {
1200
+ const fresh = await this.onDemand(this.ctrl.signal);
1201
+ if (fresh)
1202
+ this.useRouter(fresh);
1203
+ if (this.ctrl.signal.aborted)
1204
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1205
+ }
1196
1206
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1197
1207
  if (this.ctrl.signal.aborted)
1198
1208
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
@@ -2868,8 +2868,10 @@ const TOOLS = [
2868
2868
  run: runSkillCatalog,
2869
2869
  },
2870
2870
  // ── Chauffeur native tools (gated on binary availability) ──
2871
+ // The screen reads are not `safe`: that would grant screen capture to every seat tier and run it unprompted in
2872
+ // gated and plan mode. It is computer control, like computer_screenshot (tier.ts).
2871
2873
  {
2872
- name: "desktop_screenshot", safe: true,
2874
+ name: "desktop_screenshot", safe: false,
2873
2875
  contract: { v: 1, effects: ["device"], bins: ["chauffeur-local", "chauffeur", "sh"] },
2874
2876
  description: "Screenshot the desktop or one window via Chauffeur (text + image).",
2875
2877
  parameters: { type: "object", properties: {
@@ -2892,7 +2894,7 @@ const TOOLS = [
2892
2894
  run: desktopClick,
2893
2895
  },
2894
2896
  {
2895
- name: "desktop_read", safe: true,
2897
+ name: "desktop_read", safe: false,
2896
2898
  contract: { v: 1, effects: ["device"], bins: ["chauffeur-local", "chauffeur", "sh"] },
2897
2899
  description: "Read the accessibility tree / window state of a running application via Chauffeur.",
2898
2900
  parameters: { type: "object", properties: {
@@ -62,12 +62,20 @@ function termGroup(pid) {
62
62
  catch { }
63
63
  return false;
64
64
  }
65
- /** Deadline sweep shared by status/list: a running task past its deadline is terminated now. */
66
- function enforceDeadline(meta) {
67
- if (!alive(meta.pid) || !overdue(meta))
65
+ /** Deadline note shared by status/list: a report, never a signal. */
66
+ function deadlineNote(meta) {
67
+ return alive(meta.pid) && overdue(meta) ? " (deadline passed — shell_task_kill stops it)" : "";
68
+ }
69
+ /** The OS start time of `pid` (`ps -o lstart=`), or "" when it is gone or unreadable. lstart is strftime %c in
70
+ * local time, so the C locale and UTC are pinned: the same process reads the same from any session. */
71
+ async function procStart(pid) {
72
+ try {
73
+ const env = { ...process.env, LC_ALL: "C", TZ: "UTC" };
74
+ return (await pexecFile("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 5_000, encoding: "utf8", env })).stdout.trim();
75
+ }
76
+ catch {
68
77
  return "";
69
- termGroup(meta.pid);
70
- return " (deadline passed — terminated)";
78
+ }
71
79
  }
72
80
  async function shellTaskStartRun(args) {
73
81
  const command = str(args.command);
@@ -94,7 +102,7 @@ async function shellTaskStartRun(args) {
94
102
  }
95
103
  child.unref();
96
104
  await log.close();
97
- const meta = { id, label, command, pid, logFile, started: new Date().toISOString(), deadlineMs };
105
+ const meta = { id, label, command, pid, logFile, started: new Date().toISOString(), deadlineMs, lstart: await procStart(pid) };
98
106
  await writeJson(join(tasksDir(), `${id}.json`), meta);
99
107
  const timer = setTimeout(() => termGroup(pid), deadlineMs);
100
108
  timer.unref?.();
@@ -107,7 +115,7 @@ async function shellTaskStatusRun(args) {
107
115
  const meta = await taskMeta(id);
108
116
  if (!meta)
109
117
  return `error: task ${id} not found`;
110
- const note = enforceDeadline(meta);
118
+ const note = deadlineNote(meta);
111
119
  const { open } = await fsp();
112
120
  let tailText = "";
113
121
  try {
@@ -159,7 +167,7 @@ async function shellTaskListRun() {
159
167
  const meta = await taskMeta(f.replace(/\.json$/, ""));
160
168
  if (!meta)
161
169
  continue;
162
- const note = enforceDeadline(meta);
170
+ const note = deadlineNote(meta);
163
171
  rows.push(`${meta.id} ${alive(meta.pid) ? "RUNNING" : "STOPPED"}${note} pid=${meta.pid} ${meta.label}`);
164
172
  }
165
173
  return rows.length ? rows.join("\n") : "no background tasks";
@@ -173,6 +181,9 @@ async function shellTaskKillRun(args) {
173
181
  return `error: task ${id} not found`;
174
182
  if (!alive(meta.pid))
175
183
  return `task ${id} already stopped`;
184
+ if (!meta.lstart || (await procStart(meta.pid)) !== meta.lstart) {
185
+ return `task ${id} not signalled: pid ${meta.pid} could not be confirmed as the process this task started`;
186
+ }
176
187
  return termGroup(meta.pid) ? `killed ${id} (pid ${meta.pid})` : `task ${id} already stopped`;
177
188
  }
178
189
  // ─── sql_exec (approval-gated; argv, never a shell string) ──────────────────
@@ -188,8 +199,9 @@ async function sqlExecRun(args) {
188
199
  return "error: database path required for sqlite";
189
200
  if (!flagSafe(db))
190
201
  return "error: database path must not start with '-'";
202
+ // argv keeps /bin/sh out, but sqlite3 itself runs a dot-command query (.shell, .system, .output); -safe refuses them.
191
203
  try {
192
- return (await pexecFile("sqlite3", ["-header", "-column", db, query], opts)).stdout || "(no output)";
204
+ return (await pexecFile("sqlite3", ["-safe", "-header", "-column", db, query], opts)).stdout || "(no output)";
193
205
  }
194
206
  catch (e) {
195
207
  return `error: ${e.stderr?.trim() || e.message}`;
@@ -200,6 +212,9 @@ async function sqlExecRun(args) {
200
212
  return "error: connection string required for psql";
201
213
  if (!flagSafe(db))
202
214
  return "error: connection string must not start with '-'";
215
+ // psql -c runs a string that starts with a backslash as a meta-command, and \! is a shell.
216
+ if (query.trimStart().startsWith("\\"))
217
+ return "error: psql backslash commands are refused — send SQL only";
203
218
  try {
204
219
  return (await pexecFile("psql", ["--no-psqlrc", db, "-c", query], opts)).stdout || "(no output)";
205
220
  }
@@ -330,7 +345,7 @@ async function securityScanRun(args) {
330
345
  export const WAVE2_TOOLS = [
331
346
  {
332
347
  name: "shell_task_start", safe: false,
333
- contract: { v: 1, effects: ["exec"], bins: ["bash"] },
348
+ contract: { v: 1, effects: ["exec"], bins: ["bash", "ps"] },
334
349
  description: "Start a long-running background shell task with a deadline. Returns a task id for monitoring.",
335
350
  parameters: { type: "object", properties: {
336
351
  command: { type: "string" },
@@ -341,7 +356,7 @@ export const WAVE2_TOOLS = [
341
356
  },
342
357
  {
343
358
  name: "shell_task_status", safe: true,
344
- contract: { v: 1, effects: ["read", "destructive"] },
359
+ contract: { v: 1, effects: ["read"] },
345
360
  description: "Check a background task's status and tail its log. Optionally match a regex in recent output.",
346
361
  parameters: { type: "object", properties: {
347
362
  id: { type: "string" },
@@ -351,14 +366,14 @@ export const WAVE2_TOOLS = [
351
366
  },
352
367
  {
353
368
  name: "shell_task_list", safe: true,
354
- contract: { v: 1, effects: ["read", "destructive"] },
369
+ contract: { v: 1, effects: ["read"] },
355
370
  description: "List background shell tasks and their status (running/stopped).",
356
371
  parameters: { type: "object", properties: {} },
357
372
  run: shellTaskListRun,
358
373
  },
359
374
  {
360
375
  name: "shell_task_kill", safe: false,
361
- contract: { v: 1, effects: ["destructive"] },
376
+ contract: { v: 1, effects: ["destructive"], bins: ["ps"] },
362
377
  description: "Terminate a background shell task (and its process group) by id.",
363
378
  parameters: { type: "object", properties: {
364
379
  id: { type: "string" },
package/dist/ui/App.js CHANGED
@@ -45,7 +45,7 @@ function BackgroundHint({ rows }) {
45
45
  return hint ? _jsx(Text, { dimColor: true, children: ` · ${hint}` }) : null;
46
46
  }
47
47
  export function App(props) {
48
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, prefill = "", liveTools = [], route, ctxPct, ctxPin, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], onBackground, tasks = [], onSubmit, onQueue, queuedPreview = [], onEditQueued, onDropQueued, onInterrupt, onCycleMode, onCycleContext, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, secretPrompt = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
48
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, prefill = "", liveTools = [], route, ctxPct, ctxWindow, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], onBackground, tasks = [], onSubmit, onQueue, queuedPreview = [], onEditQueued, onDropQueued, onInterrupt, onCycleMode, onCycleContext, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, secretPrompt = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
49
49
  useTerminalSize(); // subscribe so the inline pinned UI (status rule, composer, footer) reflows the instant the terminal resizes
50
50
  const thinking = status === "thinking" || status === "streaming";
51
51
  // A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
@@ -60,7 +60,7 @@ export function App(props) {
60
60
  // be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
61
61
  const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(SecretPrompt, { pending: secretPrompt }), _jsx(QuestionPrompt, { pending: planExitPicker }), _jsx(ArtifactPicker, { pending: artifactsPicker }), _jsx(SessionPicker, { pending: sessionsPicker })] }));
62
62
  // The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
63
- const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, ctxPin: ctxPin, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview.length ? _jsx(Text, { color: "yellow", children: queuedHint(queuedPreview) }) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, queued: queuedPreview.length, onEditQueued: onEditQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onBackground: onBackground, onCycleMode: onCycleMode, onCycleContext: onCycleContext, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!secretPrompt || !!planExitPicker || !!artifactsPicker || !!sessionsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${caffeinated ? "☕ " : ""}${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
63
+ const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, ctxWindow: ctxWindow, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview.length ? _jsx(Text, { color: "yellow", children: queuedHint(queuedPreview) }) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, queued: queuedPreview.length, onEditQueued: onEditQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onBackground: onBackground, onCycleMode: onCycleMode, onCycleContext: onCycleContext, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!secretPrompt || !!planExitPicker || !!artifactsPicker || !!sessionsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${caffeinated ? "☕ " : ""}${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
64
64
  // Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
65
65
  // region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
66
66
  // no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
@@ -44,6 +44,7 @@ export function truncateToWidth(s, max) {
44
44
  // the terminal is too narrow to hold every badge, `info` is truncated so cellWidth(right) ≤ cols-3 —
45
45
  // which keeps the leading fill ≥ 1 and the whole line at cols-1, so the rule never becomes the line that
46
46
  // wraps (the creep bug) no matter how many badges are lit or how narrow the window.
47
+ const ROUTE_LABELS = { "operator-1m": "aurora" };
47
48
  export function statusRight(p, cols) {
48
49
  const who = p.user ? `◆ ${p.user} · ` : "";
49
50
  const seat = p.tier && p.tier !== "admin" ? `⛨ ${p.tier} · ` : ""; // a narrowed seat shows; owner's admin doesn't
@@ -51,12 +52,12 @@ export function statusRight(p, cols) {
51
52
  const think = p.thinkMode === "ultrathink" ? `✲✲ ultrathink · ` : p.thinkMode === "think" ? `✲ think · ` : "";
52
53
  const tok = p.sessionTokens && p.sessionTokens > 0 ? `Σ${fmtK(p.sessionTokens)} · ` : ""; // session token total
53
54
  // ctx as a fill ring (○◔◑◕●) + the exact % — a glance shows how full the context window is, the number keeps precision.
54
- // Show the active model's id (operator-1m, cortana, claude-opus, moa, custom …), never the leg that answered
55
- // ("cortana@192.168.1.103:8112" read as noise; /endpoints lists the legs). No display rewrite of the id: the old
56
- // one turned operator-1m into "aurora-300k", indistinguishable from the dead cloud profile axe-aurora-300k.
57
- const routeLabel = p.route;
58
- const pin = p.ctxPin ? `ctx ${p.ctxPin} ` : "";
59
- let info = `${think}${plan}${seat}${who}${routeLabel} · ${pin}${ring(p.ctxPct)} ${Math.round(p.ctxPct)}% · ${tok}v${p.version}${p.build ? ` ·${p.build}` : ""}`;
55
+ // Show the active model (cortana, claude-opus, moa, custom …) and the window it runs on, never the leg that answered
56
+ // ("cortana@192.168.1.103:8112" read as noise; /endpoints lists the legs). The default model reads as "aurora", not
57
+ // its id operator-1m (owner, 11/03: "just aurora 300k"), and the window is the one served, not a pin above it.
58
+ const routeLabel = ROUTE_LABELS[p.route] ?? p.route;
59
+ const window = p.ctxWindow ? ` ${p.ctxWindow}` : "";
60
+ let info = `${think}${plan}${seat}${who}${routeLabel}${window} ${ring(p.ctxPct)} ${Math.round(p.ctxPct)}% · ${tok}v${p.version}${p.build ? ` ·${p.build}` : ""}`;
60
61
  let right = `✷ OPERATOR · ${info} ─`;
61
62
  const maxRight = cols - 3; // leaves fill ≥ 1 and total = cols-1
62
63
  if (cellWidth(right) > maxRight) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.350",
3
+ "version": "0.1.351",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",