@0perator/operator 0.1.274 → 0.1.276

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.
@@ -98,14 +98,6 @@ export async function verifyToken(token, timeoutMs = 10_000) {
98
98
  const r = await verifyTokenDetailed(token, timeoutMs);
99
99
  return r.state === "ok" ? r.account : null;
100
100
  }
101
- /** Boot-time "signed in": true ONLY for a token the backend ACCEPTS. An absent, expired, revoked or unverifiable
102
- * (offline / backend down) token is NOT signed in — the Remote Control auto-start keys on this so an unsigned
103
- * session boots silent instead of dialing the relay to be told "token verification failed" on every launch. */
104
- export async function isSignedIn(token, timeoutMs = 5_000) {
105
- if (!token)
106
- return false;
107
- return (await verifyTokenDetailed(token, timeoutMs)).state === "ok";
108
- }
109
101
  export function authBase() {
110
102
  return AUTH_BASE;
111
103
  }
@@ -11,9 +11,20 @@ import { operatorPath } from "../config/home.js";
11
11
  const SERVICE = "axe-operator"; // keychain service — shared contract with the Python client
12
12
  const ACCOUNT = "default";
13
13
  const FILE = process.env.KODE_CREDENTIALS ?? operatorPath("credentials.json");
14
+ // Every keychain call is a CHILD PROCESS, and at boot one is AWAITED before the first frame (cli.tsx
15
+ // top-level). A `security`/`secret-tool` that never returns — locked login keychain behind a GUI prompt,
16
+ // SSH/launchd context, MDM enrollment hiccup — used to hang Operator's startup indefinitely (measured:
17
+ // a keychain process that sleeps 5s turns `operator --version` from 0.46s into 5.60s; the sleep is the
18
+ // unbounded case). So the lookup gets a HARD BUDGET: on expiry the child is killed and we degrade to the
19
+ // 0600-file fallback. Override with KODE_KEYCHAIN_TIMEOUT_MS (0 disables the timeout).
20
+ const KEYCHAIN_TIMEOUT_MS = (() => {
21
+ const n = Number(process.env.KODE_KEYCHAIN_TIMEOUT_MS);
22
+ return Number.isFinite(n) && n >= 0 ? n : 1500;
23
+ })();
24
+ let timedOutOnce = false;
14
25
  function run(cmd, args, input) {
15
26
  return new Promise((resolve, reject) => {
16
- const child = execFile(cmd, args, (err, stdout) => (err ? reject(err) : resolve(stdout.toString())));
27
+ const child = execFile(cmd, args, KEYCHAIN_TIMEOUT_MS > 0 ? { timeout: KEYCHAIN_TIMEOUT_MS } : {}, (err, stdout) => (err ? reject(err) : resolve(stdout.toString())));
17
28
  if (input !== undefined) {
18
29
  child.stdin?.end(input);
19
30
  }
@@ -51,8 +62,16 @@ async function keychainGet() {
51
62
  return (await run("secret-tool", ["lookup", "service", SERVICE, "account", ACCOUNT])).trim() || null;
52
63
  }
53
64
  }
54
- catch {
55
- /* not found / no keychain */
65
+ catch (err) {
66
+ // Two different silences used to be conflated here: "no entry" (normal, signed-out box) and
67
+ // "the helper never answered" (locked keychain / hung helper). The second is an operator-visible
68
+ // fault — say it ONCE on stderr, then keep booting on the file fallback.
69
+ if (err?.killed || err?.signal === "SIGTERM") {
70
+ if (!timedOutOnce) {
71
+ timedOutOnce = true;
72
+ process.stderr.write(`operator: keychain lookup timed out after ${KEYCHAIN_TIMEOUT_MS}ms — falling back to the file store (sign-in state may read stale)\n`);
73
+ }
74
+ }
56
75
  }
57
76
  return null;
58
77
  }
@@ -79,15 +98,26 @@ async function readMeta() {
79
98
  }
80
99
  /** Persist credentials: token to the keychain (or, if unavailable, the 0600 file), metadata always to file. */
81
100
  export async function saveCredentials(creds) {
101
+ credsCache = null; // any write invalidates the memoized read (a fresh sign-in beats the cached miss)
82
102
  await mkdir(dirname(FILE), { recursive: true, mode: 0o700 });
83
103
  const inKeychain = await keychainSet(creds.token);
84
104
  // File holds metadata always; it holds the token too ONLY when the keychain couldn't (fallback).
85
105
  const onDisk = { user: creds.user, host: creds.host, issuedAt: creds.issuedAt, ...(inKeychain ? {} : { token: creds.token }) };
86
106
  await writeFile(FILE, JSON.stringify(onDisk, null, 2), { mode: 0o600 });
87
107
  await chmod(FILE, 0o600).catch(() => { });
108
+ credsCache = null;
109
+ }
110
+ /** Load credentials, or null if not signed in. Prefers the keychain token; falls back to the file's.
111
+ * Single-flighted: a session boot reaches this from FOUR sites (cli top-level bootCreds, the RC
112
+ * auto-start gate, the footer sign-in effect, and every /remotecontrol|/pair invocation). Each used to
113
+ * spawn its own keychain child process on the critical path; now the first call's (now time-bounded)
114
+ * promise is shared, so one boot costs at most ONE keychain read. save/clear drop the cache so an
115
+ * in-session sign-in is seen immediately by the next caller. */
116
+ let credsCache = null;
117
+ export function loadCredentials() {
118
+ return (credsCache ??= loadCredentialsFresh());
88
119
  }
89
- /** Load credentials, or null if not signed in. Prefers the keychain token; falls back to the file's. */
90
- export async function loadCredentials() {
120
+ async function loadCredentialsFresh() {
91
121
  const meta = await readMeta();
92
122
  const token = (await keychainGet()) ?? meta.token ?? null;
93
123
  if (!token)
@@ -96,6 +126,7 @@ export async function loadCredentials() {
96
126
  }
97
127
  /** Sign out: drop the keychain entry and the on-disk file. */
98
128
  export async function clearCredentials() {
129
+ credsCache = null;
99
130
  await keychainClear();
100
131
  await rm(FILE, { force: true });
101
132
  }
@@ -25,12 +25,6 @@ export const DELEGATE_TIMEOUT_MS = 10 * 60_000;
25
25
  /** Absolute per-turn round ceiling for a sub-agent — the same cap background sub-agents get (cli.tsx): a
26
26
  * delegated agent that hits it isn't converging, and each round burns a (possibly shared) model slot. */
27
27
  export const DELEGATE_MAX_ROUNDS = 50;
28
- /** Soft round budget handed to the child, kept BELOW the hard ceiling on purpose. runTurn's ceiling is
29
- * Math.max(soft + 1, maxRoundsHard), and createAutonomySession forwards the owner's autonomy.maxRounds (default
30
- * 100000, "unbounded autonomy") as the soft budget — so without this a delegated child's 50-round cap was really
31
- * 100001 and only the wall-clock bound stopped a runaway. Past this the engine also ends a genuine no-progress
32
- * stall early instead of running it to the ceiling. */
33
- export const DELEGATE_SOFT_ROUNDS = 25;
34
28
  // Default deps: loaded lazily — session-factory pulls node-only modules statically (see cron.sessionExecutor).
35
29
  const defaultDeps = {
36
30
  loadSettings: async () => (await nodeImport("../config/settings.js")).loadSettings(),
@@ -106,26 +100,14 @@ const msg = (e) => (e instanceof Error ? e.message : String(e));
106
100
  // ── The `delegate_task` tool (registry wires run: runDelegateTask) ──────────
107
101
  /**
108
102
  * Run `args.task` on a sub-agent backed by `args.model` (default "scout") and return its final answer, or an
109
- * `error: ...` string (the tool contract: never throws — the outer guard covers the setup steps the inner
110
- * try/catches don't, e.g. a settings load). Result size is bounded downstream — the executor's capToolResult
111
- * spills anything over 40KB to disk and hands the planner a re-readable pointer.
103
+ * `error: ...` string (the tool contract: never throws). Result size is bounded downstream — the executor's
104
+ * capToolResult spills anything over 40KB to disk and hands the planner a re-readable pointer.
112
105
  */
113
106
  export async function runDelegateTask(args, deps = defaultDeps) {
114
- try {
115
- return await delegate(args, deps);
116
- }
117
- catch (e) {
118
- return `error: delegate_task: ${msg(e)}`;
119
- }
120
- }
121
- async function delegate(args, deps) {
122
107
  const depth = await delegationDepth();
123
108
  if (depth >= MAX_DELEGATE_DEPTH) {
124
109
  return `error: delegate_task refused — already inside a delegated sub-agent (depth ${depth}, max ${MAX_DELEGATE_DEPTH}). Sub-agents cannot delegate; do the work directly with your own tools.`;
125
110
  }
126
- if (args.task != null && typeof args.task !== "string") {
127
- return "error: delegate_task: `task` must be a string — the complete, self-contained subtask text (an object/array would reach the sub-agent as \"[object Object]\")";
128
- }
129
111
  const task = String(args.task ?? "").trim();
130
112
  if (!task)
131
113
  return "error: delegate_task needs a non-empty `task` — a self-contained subtask; the sub-agent sees nothing else";
@@ -148,7 +130,6 @@ async function delegate(args, deps) {
148
130
  sessionId: id,
149
131
  memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
150
132
  rollingSummaryPath: `${dir}/summary.md`,
151
- maxRounds: DELEGATE_SOFT_ROUNDS,
152
133
  maxRoundsHard: DELEGATE_MAX_ROUNDS,
153
134
  sleepConsolidation: { enabled: false }, // a short-lived child must not consolidate the owner's knowledge base
154
135
  },
@@ -5,8 +5,6 @@
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { Session } from "../session.js";
7
7
  import { AuroraRouter } from "../router/router.js";
8
- import { visibleRegistry } from "../tools/registry.js";
9
- import { setActivePowerTools } from "../tools/power-tools.js";
10
8
  import { composeSystemPrompt } from "../config/persona.js";
11
9
  import { modelCtxFor, LEAN_HARNESS_CTX } from "../router/models.js";
12
10
  import { compactionThreshold, compactionCeilingTokens, turnWallClockMs } from "../config/settings.js";
@@ -35,10 +33,8 @@ export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
35
33
  * to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
36
34
  * MCP tool set directly. Permissions default to the owner's configured policy. */
37
35
  export function createAutonomySession(settings, opts = {}) {
38
- setActivePowerTools(settings.powerTools); // arm the power-tools run() backstop for headless runs too
39
36
  return new Session({
40
37
  systemPrompt: buildHeadlessSystemPrompt(settings, opts.cwd),
41
- toolRegistry: visibleRegistry(settings.powerTools), // flag-gated tool set, in sync with the headless catalogue
42
38
  router: buildRouterFromSettings(settings),
43
39
  cwd: opts.cwd,
44
40
  mcp: settings.mcp,
package/dist/cli.js CHANGED
@@ -1,14 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  // KODE-TSI entry — the Ink shell. Thin by design: all engine logic lives in Session (src/session.ts,
4
4
  // headless + tested); this file only maps Session's streaming callbacks onto React state and renders
5
5
  // the SPEC §6 <App>. The port's whole point — full-frame React reconciliation + Ink <Static> — is what
6
6
  // makes the scroll/echo/overwrite bug class of the ANSI-cursor Python core structurally impossible.
7
7
  import { useCallback, useEffect, useRef, useState } from "react";
8
- import { render, Text, useApp } from "ink";
8
+ import { render, Box, Text, useApp } from "ink";
9
9
  import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
- import { createResizeSafeStdout } from "./ui/resize.js";
12
11
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
13
12
  import { RemoteHost } from "./remote/host.js";
14
13
  import { newCode, pairURL } from "./remote/pairing.js";
@@ -30,8 +29,7 @@ import { applyToolsBinPath, operatorPath } from "./config/home.js";
30
29
  import { ensureOperatorHome } from "./config/scaffold.js";
31
30
  import { listLocalSkills } from "./config/skills-index.js";
32
31
  import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
33
- import { disposeShellSession, getAgentTasks, visibleRegistry } from "./tools/registry.js";
34
- import { setActivePowerTools } from "./tools/power-tools.js";
32
+ import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
35
33
  import { disposeBrowserNow } from "./browser/session.js";
36
34
  import { EventSink, defaultEventsFile } from "./telemetry/events.js";
37
35
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
@@ -55,9 +53,22 @@ const VERSION = (() => {
55
53
  return "0.0.0";
56
54
  }
57
55
  })();
56
+ // Fast paths that must NOT mount Ink/React (so `operator --version` works with no TTY and returns instantly)
57
+ // — and must not do ANY identity I/O either. They used to sit BELOW the boot credential load, so even
58
+ // `--version` paid a keychain child-process spawn on the critical path: with a hung `security` helper the
59
+ // "instant" command took the full 5s of a 5s sleep (∞ if the keychain never answers). Hoisted above every
60
+ // awaited boot import, they now exit before the first process spawn — version/help are pure constants.
61
+ if (process.argv.includes("--version") || process.argv.includes("-V")) {
62
+ process.stdout.write(VERSION + "\n");
63
+ process.exit(0);
64
+ }
65
+ if (process.argv.includes("--help")) {
66
+ process.stdout.write(mastheadLines(`300K · v${VERSION}`).join("\n") +
67
+ "\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator --update update to the latest build (git fast-forward)\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator run <task> run one task headless\n operator --version print the version\n");
68
+ process.exit(0);
69
+ }
58
70
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
59
71
  const settings = loadSettings();
60
- setActivePowerTools(settings.powerTools); // arm the power-tools run() backstop to this box's flags (fail-closed otherwise)
61
72
  // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
62
73
  // root, ignore-everything .gitignore, README, settings.example.json, home.json). Idempotent, never throws.
63
74
  const HOME_SCAFFOLD = ensureOperatorHome({ version: VERSION });
@@ -357,7 +368,7 @@ const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`
357
368
  function Root() {
358
369
  const { exit } = useApp();
359
370
  const [boot, setBoot] = useState("checking");
360
- const [bootDetail, setBootDetail] = useState(""); // live line during the model auto-detect + service-lever preflight
371
+ const [bootDetail, setBootDetail] = useState(""); // live line during the service-lever preflight
361
372
  const [entries, setEntries] = useState([]);
362
373
  const [live, setLive] = useState(null);
363
374
  const [status, setStatus] = useState("idle");
@@ -452,14 +463,11 @@ function Root() {
452
463
  });
453
464
  }, [settleApproval]);
454
465
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
455
- const bootChainRef = useRef(null); // set when the boot auto-detect adopted a NON-default endpoint — background sub-agents follow it instead of the dead configured base
456
- const degradedRef = useRef(false); // booted with no reachable model — the next turn re-runs the probe before it goes to a dead endpoint
457
466
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
458
467
  // only, no network fan-out at session start). Background agents stay local-only + lean.
459
468
  if (!sessionRef.current) {
460
469
  sessionRef.current = new Session({
461
470
  systemPrompt: SYSTEM_PROMPT,
462
- toolRegistry: visibleRegistry(settings.powerTools), // feature-flagged power-tools: schemas+executor match the prompt catalogue
463
471
  thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
464
472
  router: buildRouter(),
465
473
  mcp: settings.mcp,
@@ -559,13 +567,12 @@ function Root() {
559
567
  if (!bgRef.current) {
560
568
  bgRef.current = new BackgroundAgents((cwd) => new Session({
561
569
  systemPrompt: SYSTEM_PROMPT,
562
- toolRegistry: visibleRegistry(settings.powerTools), // bg sub-agents see the same flag-gated tool set
563
- router: new AuroraRouter(bootChainRef.current
564
- ? bootChainRef.current.map((e) => ({ ...e })) // the model the boot auto-detect actually connected to — a sub-agent must not aim at the dead configured base
565
- : [{ name: "operator-1m", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow }]),
570
+ router: new AuroraRouter([
571
+ { name: "operator-1m", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow },
572
+ ]),
566
573
  maxTokens: settings.maxTokens,
567
574
  maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling also bounds a sub-agent's spend
568
- maxRoundsHard: 100000, // owner directive (2026-10-10): unbounded like the foreground — a delegated sub-agent runs its task to completion, not cut at 50. The stall break (loop.stallAfter) + loop guard remain the real runaway protection (a genuine no-progress spin still stops); this removes only the fixed round ceiling.
575
+ maxRoundsHard: 50, // a focused delegated sub-agent that hits 50 rounds isn't converging — cap it well below the foreground's 200 so a review/fix agent can't run away to round 40+ burning the shared Aurora (seen live 09-26)
569
576
  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")
570
577
  cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
571
578
  temperature: settings.temperature,
@@ -639,80 +646,32 @@ function Root() {
639
646
  process.once("SIGTERM", onTerm);
640
647
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
641
648
  }, [session]);
642
- // Probe-don't-assume model selection (services/model-autodetect.ts). Connects this session to whatever model is
643
- // HEALTHY — the active one first, then same-model standbys (failover / fleet nodes), then every other registry
644
- // profile — instead of hard-launching one port and freezing the boot when it is down. At boot the launchd Service
645
- // lever is the LAST resort (after nothing answered), bounded; on a later re-check (a degraded boot's next turn) it
646
- // only probes. Session-only: never writes activeModel, so the owner's preferred model returns when it does.
647
- // Adopts the choice into the session and returns the outcome — the CALLER prints it (the boot must print AFTER a
648
- // --resume restore replaces the transcript).
649
- const autodetect = useCallback(async (opts) => {
650
- const ad = await import("./services/model-autodetect.js");
651
- const { getByoToken } = await import("./auth/byo.js");
652
- const cfg = settings.autodetect;
653
- const aur = settings.endpoints.aurora;
654
- const waitSec = cfg?.waitSec ?? 25;
655
- const [cur] = session.endpoints();
656
- const standby = [
657
- ...(settings.endpoints.failover ? [{ id: "failover", base: settings.endpoints.failover.base, model: settings.endpoints.failover.model, ctx: settings.endpoints.failover.ctxWindow }] : []),
658
- ...(settings.fleet?.auroraNodes ?? []).filter(Boolean).map((base) => ({ id: `node:${ad.hostPort(base)}`, base, model: aur.model, ctx: aur.ctxWindow })),
659
- ];
660
- const cands = ad.buildCandidates({
661
- active: { id: session.currentModel(), base: cur.base, model: cur.model, ctx: cur.ctxWindow },
662
- standby,
663
- registry: session.modelRegistry(),
664
- byoToken: getByoToken,
665
- allowCloud: cfg?.cloud !== false,
666
- enabled: cfg?.enabled !== false,
667
- });
668
- const outcome = await ad.detectBoot(cands, {
669
- probe: (c, signal) => ad.probeCandidate(c, { timeoutMs: cfg?.timeoutMs, signal }),
670
- launch: opts.boot
671
- ? async () => {
672
- const { ensureServices } = await import("./services/preflight.js");
673
- const [r] = await ensureServices({
674
- aurora: { base: aur.base, ...settings.services?.aurora, waitSec: Math.min(settings.services?.aurora?.waitSec ?? 45, waitSec) },
675
- onProgress: setBootDetail,
676
- });
677
- return r ?? { state: "skipped" };
678
- }
679
- : undefined,
680
- onProgress: opts.boot ? setBootDetail : undefined,
681
- waitSec: opts.boot ? waitSec : 0,
682
- });
683
- if (outcome.kind !== "degraded" && outcome.chosen.source !== "active") {
684
- const c = outcome.chosen;
685
- const chain = ad.routerChain(c, cands);
686
- if (c.profileId)
687
- session.setModel(c.profileId); // keep the active /model id truthful (status rule, capabilities, ctx lookups)
688
- session.adoptEndpoints(chain); // the chosen endpoint first + its same-model siblings, so a mid-session death still hops
689
- bootChainRef.current = chain;
690
- setRoute(c.id);
691
- }
692
- degradedRef.current = outcome.kind === "degraded";
693
- return outcome;
694
- }, [session]);
695
649
  useEffect(() => {
696
650
  void (async () => {
697
- setBootDetail("detecting model…");
698
- // Optional companions (autopilot) come up alongside the model probe, never blocking it.
699
- const companions = import("./services/preflight.js")
700
- .then((p) => p.ensureServices({ autopilot: settings.services?.autopilot, onProgress: setBootDetail }))
701
- .catch(() => []);
702
- const ad = await import("./services/model-autodetect.js");
703
- // Never bricks the boot: a probe/launch fault degrades to the same "open, no model yet" state as nothing-reachable.
704
- const outcome = await autodetect({ boot: true }).catch((e) => {
705
- degradedRef.current = true;
706
- return { kind: "degraded", tried: [], launch: { state: "down", detail: String(e?.message ?? e) } };
707
- });
708
- const reports = await companions;
709
- // If the lever COLD-STARTED the model, prime it (fire-and-forget) so the first real turn doesn't
710
- // eat the graph/Metal warmup. Only a launch warms — an already-up model needs nothing.
711
- if (outcome.kind === "launched") {
651
+ // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
652
+ // health, so a cold box self-heals instead of dropping the owner at "start it yourself and relaunch".
653
+ let reports = [];
654
+ try {
712
655
  const preflight = await import("./services/preflight.js");
713
- void preflight.warmAurora(outcome.chosen.base, outcome.chosen.model);
656
+ reports = await preflight.ensureServices({
657
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
658
+ autopilot: settings.services?.autopilot,
659
+ onProgress: setBootDetail,
660
+ });
661
+ // If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
662
+ // eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
663
+ if (reports.find((r) => r.name === "aurora")?.state === "started") {
664
+ void preflight.warmAurora(settings.endpoints.aurora.base, settings.endpoints.aurora.model);
665
+ }
666
+ }
667
+ catch { /* preflight is best-effort — fall through to the authoritative health check */ }
668
+ const ok = await session.health().catch(() => false);
669
+ setBoot(ok ? "ready" : "down");
670
+ if (!ok) {
671
+ const a = reports.find((r) => r.name === "aurora");
672
+ setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
673
+ return;
714
674
  }
715
- setBoot("ready");
716
675
  if (RESUME) {
717
676
  try {
718
677
  const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
@@ -727,22 +686,15 @@ function Root() {
727
686
  }
728
687
  catch { /* no saved session to resume */ }
729
688
  }
730
- // Feed the boot outcome to the frozen event stream (dashboard service-health tiles). The "aurora" tile keeps
731
- // meaning "the configured Aurora base" — emitted only when the probe actually said something about it.
689
+ // Feed the service-lever outcome to the frozen event stream (dashboard service-health tiles).
732
690
  if (emitTelemetry) {
733
- const aurora = ad.stateOfBase(outcome, settings.endpoints.aurora.base);
734
- const tiles = [...(aurora ? [{ name: "aurora", state: aurora }] : []), ...reports.map((r) => ({ name: r.name, state: (r.state === "started" ? "started" : r.state === "up" ? "up" : "down") }))];
735
- for (const t of tiles)
736
- eventSink.emit({ kind: "service", session: SESSION_ID, actor: EVENT_ACTOR, service: t });
691
+ for (const r of reports) {
692
+ const state = r.state === "started" ? "started" : r.state === "up" ? "up" : "down";
693
+ eventSink.emit({ kind: "service", session: SESSION_ID, actor: EVENT_ACTOR, service: { name: r.name, state } });
694
+ }
737
695
  }
738
- // Say which model we connected to when it is not the configured one, or that none was reachable (silent on the
739
- // happy path — the services line below confirms it).
740
- const note = ad.describeOutcome(outcome);
741
- if (note)
742
- push({ kind: "message", message: { id: nextId(), role: "system", content: note } });
743
696
  // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
744
- const modelPart = outcome.kind === "degraded" ? "model ✗" : `model ${outcome.chosen.id} ${outcome.kind === "launched" ? "✓ started" : "✓"}`;
745
- const line = [modelPart, ...reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`)].join(" · ");
697
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
746
698
  if (line) {
747
699
  // SearXNG is lazy (starts on first web_search), but if a backend is ALREADY reachable — an explicit
748
700
  // KODE_SEARXNG_URL, or a container still up from a prior session — show ✓ instead of a misleading
@@ -757,15 +709,11 @@ function Root() {
757
709
  // (submitRef → handleSlash) — never a second connect implementation. Token-gated with a SILENT skip
758
710
  // when unsigned, so a no-token box is never spammed with the sign-in hint every launch; and guarded on
759
711
  // remoteRef so it never double-starts an already-live host. The owner can still /remotecontrol to stop.
760
- // "Signed in" means a token the backend ACCEPTS, not merely one that exists: a stale/expired token used to
761
- // dial wss://…/session/ws on every boot and print "token verification failed" + "relay closed". Unsigned (or
762
- // unverifiable) → no connect at all, no error lines; /remotecontrol still starts it on demand after sign-in.
763
712
  if (rcAutostart(settings) && !remoteRef.current) {
764
713
  const { loadCredentials } = await import("./auth/store.js");
765
- const { isSignedIn } = await import("./auth/client.js");
766
714
  const creds = await loadCredentials().catch(() => null);
767
715
  const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
768
- if (await isSignedIn(token))
716
+ if (token)
769
717
  submitRef.current("/remotecontrol");
770
718
  }
771
719
  })();
@@ -799,14 +747,6 @@ function Root() {
799
747
  setElapsed(0);
800
748
  setStat("thinking");
801
749
  try {
802
- if (degradedRef.current) {
803
- // Booted with no model reachable: re-probe before this turn goes to a dead endpoint — a model that was still
804
- // loading, or a node that came back, is picked up with no relaunch. One probe round; never blocks past it.
805
- const ad = await import("./services/model-autodetect.js");
806
- const o = await autodetect({ boot: false }).catch(() => null);
807
- if (o && o.kind !== "degraded")
808
- sys(ad.describeOutcome(o) || `→ model: ${o.chosen.id} @ ${ad.hostPort(o.chosen.base)}`);
809
- }
810
750
  const outcome = await session.send(expandFileMentions(text), {
811
751
  onRoute: (label, pct) => {
812
752
  setRoute(label);
@@ -1788,6 +1728,9 @@ function Root() {
1788
1728
  }, [boot]);
1789
1729
  if (boot === "checking")
1790
1730
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
1731
+ if (boot === "down") {
1732
+ 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, _jsx(Text, { dimColor: true, children: "The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/com.imi.aurora-serve" })] }));
1733
+ }
1791
1734
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
1792
1735
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
1793
1736
  // turn's numbers mid-turn — the clock always moves.
@@ -1810,16 +1753,7 @@ function Root() {
1810
1753
  }
1811
1754
  // `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
1812
1755
  // headless (CI / SSH). Anything else falls through to the interactive REPL below.
1813
- // Fast paths that must NOT mount Ink/React (so `operator --version` works with no TTY and returns instantly).
1814
- if (process.argv.includes("--version") || process.argv.includes("-V")) {
1815
- process.stdout.write(VERSION + "\n");
1816
- process.exit(0);
1817
- }
1818
- if (process.argv.includes("--help")) {
1819
- process.stdout.write(mastheadLines(`300K · v${VERSION}`).join("\n") +
1820
- "\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator --update update to the latest build (git fast-forward)\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator run <task> run one task headless\n operator --version print the version\n");
1821
- process.exit(0);
1822
- }
1756
+ // (--version/--help fast paths hoisted to the top of the module — they must never touch keychain/network.)
1823
1757
  if (process.argv[2] === "auth") {
1824
1758
  const { runAuth } = await import("./auth/commands.js");
1825
1759
  process.exit(await runAuth(process.argv.slice(3), settings));
@@ -1888,11 +1822,19 @@ else {
1888
1822
  catch { /* best-effort; a write failure just re-shows next boot */ }
1889
1823
  }
1890
1824
  }
1891
- // Inline: Ink erases the previous frame by LOGICAL line count, but a terminal that shrinks reflows the frame's
1892
- // full-width lines onto extra rows — so every redraw during a resize strands the top of the old frame (the
1893
- // status line + prompt, once per resize event). Render through the resize-safe stdout (ui/resize.ts): it
1894
- // erases the rows the frame really occupies and redraws once per drag. Fullscreen draws in the alt screen,
1895
- // which doesn't reflow, so it keeps the bare stream.
1896
- const inkInstance = render(_jsx(Root, {}), FULLSCREEN ? undefined : { stdout: createResizeSafeStdout() });
1825
+ const inkInstance = render(_jsx(Root, {}));
1897
1826
  if (FULLSCREEN)
1898
1827
  void inkInstance.waitUntilExit().then(leaveAltScreen);
1828
+ // Ink erases the previous frame by line COUNT, computed from the terminal width at draw time. When the
1829
+ // window is minimized or resized, a resize event with a changed/zero width desyncs that count, so every
1830
+ // later re-render (a keystroke, the 250ms clock) APPENDS the status rule instead of overwriting it — the
1831
+ // "a new line every time I type" screen-fill. Force a full clear on each resize so Ink re-syncs to the
1832
+ // real terminal and redraws from a clean slate instead of stacking stale frames.
1833
+ let resizeClear;
1834
+ process.stdout.on?.("resize", () => {
1835
+ clearTimeout(resizeClear);
1836
+ resizeClear = setTimeout(() => { try {
1837
+ inkInstance.clear();
1838
+ }
1839
+ catch { /* stdout detached */ } }, 16);
1840
+ });
@@ -6,7 +6,7 @@ import { readFileSync, appendFileSync, mkdirSync } from "node:fs";
6
6
  import { join, dirname } from "node:path";
7
7
  import { operatorPath } from "./home.js";
8
8
  import { renderHarnessContext } from "./operator-harness.js";
9
- import { renderToolCatalogue, visibleRegistry } from "../tools/registry.js";
9
+ import { renderToolCatalogue } from "../tools/registry.js";
10
10
  import { renderSkillsIndex } from "./skills-index.js";
11
11
  // Project context: auto-load a per-repo instructions file from `cwd` and append it to the system prompt, so
12
12
  // Operator picks up house rules, conventions and build commands the way modern coding agents do. First match
@@ -224,16 +224,14 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
224
224
  `OPEN it for them yourself (bash \`open <url-or-local-path>\`) and put the clickable link in your reply — ` +
225
225
  `never leave them to ask "open it for me". Skip the auto-open inside a media-robot / headless batch.` +
226
226
  `\n## The media pipeline — what you ACTUALLY have (don't invent tools)\nYour media stack is three ` +
227
- `scale-to-zero fleet workers, nothing else — do NOT offer ComfyUI, standalone SDXL, Juggernaut/EpicRealism, ` +
227
+ `scale-to-zero fleet workers, nothing else — do NOT offer ComfyUI, SDXL, Juggernaut/RealVis/EpicRealism, ` +
228
228
  `FLUX.1-dev/pro, Midjourney, or a cloud image API as if available; they are not wired in, and suggesting ` +
229
229
  `them is a hallucinated capability. (a) IMAGES — \`image_generate\` → FLUX.1-schnell (4-bit MLX) on the ` +
230
- `image broker by default. schnell is speed-tuned: strong but not a photoreal ceiling. For PHOTOREAL from ` +
231
- `text alone, pass \`quality: "photoreal"\`: it routes to the identity broker, where RealVisXL IS wired ` +
232
- `(SDXL text-to-image, ~1024px, slower, no face needed) — that is your photoreal path, so you never need to ` +
233
- `build one. To enrich the prompt, pass \`expand: true\` — the broker rewrites your prompt through the Aurora ` +
234
- `expander into a richer, more cinematic prompt (the expanded text comes back in the result and is logged); ` +
235
- `combine with a larger \`size\`. Those are your real quality levers — reach for them instead of claiming ` +
236
- `you need a model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
230
+ `image broker. schnell is speed-tuned: strong but not a dev/pro-tier photoreal ceiling. When the owner ` +
231
+ `wants higher quality, pass \`expand: true\` — the broker rewrites your prompt through the Aurora expander ` +
232
+ `into a richer, more cinematic prompt (the expanded text comes back in the result and is logged); combine ` +
233
+ `with a larger \`size\`. That is your real quality lever — reach for it instead of claiming you need a ` +
234
+ `model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
237
235
  `— \`video_generate\` → LTX-Video-0.9.5 on the video broker, with \`expand\` and \`reference_image\` ` +
238
236
  `(IMAGE-TO-VIDEO): pass an image and LTX conditions on it as the FIRST FRAME, so the subject in the clip ` +
239
237
  `IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → a Qwen2-VL worker on the ` +
@@ -242,25 +240,22 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
242
240
  `auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
243
241
  `your generate prompt from what you actually SAW.` +
244
242
  `\n**Likeness is LIVE — this is how you "generate HER".** To make a SPECIFIC person, pass their FACE photo ` +
245
- `as \`reference\` to \`image_generate\`: it routes to the identity broker (the same RealVisXL wired above, plus IP-Adapter-FaceID) ` +
243
+ `as \`reference\` to \`image_generate\`: it routes to the identity broker (RealVisXL + IP-Adapter-FaceID) ` +
246
244
  `which preserves that exact face (arcface-verified) in whatever new scene/pose your prompt describes — you ` +
247
245
  `do NOT build your own pipeline for this, the tool does it. The result carries an honest \`axe_identity\` ` +
248
246
  `block — if \`identity_applied\` is false or \`fidelity_note\` is weak/none, SAY so; never pass a look-alike ` +
249
247
  `off as an exact match. A VIDEO of that person from a shared image works too (its first frame IS the real ` +
250
248
  `photo) via \`reference_image\` on \`video_generate\`. Every generation is logged to a provenance flywheel, ` +
251
249
  `so the pipeline compounds with use.` +
252
- `\n**A media tool that errors is an OUTAGE, not a missing capability.** If \`image_generate\` / \`video_generate\` / ` +
253
- `\`image_analyze\` / \`voice_*\` returns an error (worker down, 5xx, timeout): retry once, and if it is still down ` +
254
- `TELL THE OWNER. NEVER install ComfyUI, diffusers, comfy-cli, inference.sh or any CLI, and NEVER download ` +
255
- `diffusion/vision/voice weights, to substitute for it on your own initiative — the shell will redirect it ` +
256
- `anyway, and the capability already exists as the tool. Only when the OWNER explicitly asks for that install: ` +
257
- `say the native tool already covers it, and if they still want it, run it (the shell redirects once — re-issue ` +
258
- `the same command to proceed; a weight download stays blocked until the owner lifts it).` +
259
250
  `\n## Deep research — \`deep_research\` (cited, multi-source)\nWhen a question needs more than one search — a ` +
260
251
  `comparison, a state-of-the-art survey, sourced background — reach for \`deep_research\`: it plans several ` +
261
252
  `search angles, fans out \`web_search\` + \`web_fetch\` across them, and returns a brief with inline source ` +
262
253
  `citations. A single lookup is faster with plain \`web_search\`; use \`deep_research\` when depth and ` +
263
254
  `citations matter. It never invents sources — if the search backend is down it says so rather than guessing.` +
255
+ // 96e159b swallowed the OPENING line of the section below ("## Running scripts — …\nFor anything more
256
+ // than a ONE-LINE snippet, write "), orphaning its tail mid-sentence: the LIVE interactive persona
257
+ // shipped as "...rather than guessing.the script to a file…" — no heading, no space (the persona
258
+ // parity test's red on main was the witness). Restored as its own section; do not re-splice.
264
259
  `\n## Running scripts — never inline a multi-line script\nFor anything more than a ONE-LINE snippet, write ` +
265
260
  `the script to a file with file_write and run the file (\`python3 /tmp/probe.py\`). Do NOT embed a ` +
266
261
  `multi-line program inside \`python3 -c "…"\` or \`bash -c "…"\`: the newlines, \`#\` comments and quotes ` +
@@ -348,19 +343,11 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
348
343
  `when you're running low on context, call session_handoff to record what you did, the state, and the ` +
349
344
  `next steps: your next session in this directory loads it automatically, so write it for your future self.` +
350
345
  (opts.interactive
351
- ? `\n## Sub-agents\nUse them to cover more ground and finish faster. You have spawn_agent and delegate_task: ` +
352
- `farm a self-contained subtask to a parallel session that posts its result back while you keep working. ` +
353
- `Reach for them PROACTIVELY — run the work like a staff engineer directing a team, not a solo grind:\n` +
354
- `- COVERAGE: fan out independent pieces at once — search several subsystems, draft multiple files, audit N ` +
355
- `things in parallel. Each sub-agent's noise stays OUT of your context, so you cover far more ground without ` +
356
- `bloating this thread.\n` +
357
- `- SPEED: parallelize what isn't bottlenecked on this one model — tool/IO-bound subtasks, or subtasks you ` +
358
- `route to a DIFFERENT backend (delegate_task with model: e.g. cortana or a cloud tier) so they genuinely run ` +
359
- `alongside you. N sub-agents on this ONE local model SERIALIZE at the model, so spawn several only when they ` +
360
- `run on different endpoints OR the win is coverage / context-isolation rather than wall-clock.\n` +
361
- `- Give each a FULLY self-contained instruction (it can't see this chat and can't ask questions). Skip ` +
362
- `trivial inline work. The user watches each sub-agent live — its own colour, tokens, and time — in the ` +
363
- `background panel.`
346
+ ? `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
347
+ `build) call spawn_agent with a fully self-contained instruction — it runs on another session ` +
348
+ `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
349
+ `live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
350
+ `spawn many at once — they all share this one model.`
364
351
  : ""));
365
352
  }
366
353
  const LEAN_NOTE = "\n\n(Lean harness: long-term memory + handoff omitted to fit this model's smaller context — answer from the live conversation; do not recite stored notes.)";
@@ -417,6 +404,6 @@ export function composeSystemPrompt(o) {
417
404
  renderHarnessContext(cwd) +
418
405
  (lean ? LEAN_NOTE : loadHandoff()) +
419
406
  (skillsIdx ? `\n\n## Skills installed locally (skill_fetch <name> loads one; skill_fetch <name> <file_path> reads its references/templates/scripts)\n${skillsIdx}` : "") +
420
- renderToolCatalogue(visibleRegistry(o.settings.powerTools), { lean }) +
407
+ renderToolCatalogue(undefined, { lean }) +
421
408
  (interactive ? renderEmbodimentGuide(!!o.settings.computer?.enabled, o.chauffeurReady ?? !!o.settings.mcp) : ""));
422
409
  }