@0perator/operator 0.1.263 → 0.1.274

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,6 +98,14 @@ 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
+ }
101
109
  export function authBase() {
102
110
  return AUTH_BASE;
103
111
  }
@@ -25,6 +25,12 @@ 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;
28
34
  // Default deps: loaded lazily — session-factory pulls node-only modules statically (see cron.sessionExecutor).
29
35
  const defaultDeps = {
30
36
  loadSettings: async () => (await nodeImport("../config/settings.js")).loadSettings(),
@@ -100,14 +106,26 @@ const msg = (e) => (e instanceof Error ? e.message : String(e));
100
106
  // ── The `delegate_task` tool (registry wires run: runDelegateTask) ──────────
101
107
  /**
102
108
  * Run `args.task` on a sub-agent backed by `args.model` (default "scout") and return its final answer, or an
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.
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.
105
112
  */
106
113
  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) {
107
122
  const depth = await delegationDepth();
108
123
  if (depth >= MAX_DELEGATE_DEPTH) {
109
124
  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.`;
110
125
  }
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
+ }
111
129
  const task = String(args.task ?? "").trim();
112
130
  if (!task)
113
131
  return "error: delegate_task needs a non-empty `task` — a self-contained subtask; the sub-agent sees nothing else";
@@ -130,6 +148,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
130
148
  sessionId: id,
131
149
  memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
132
150
  rollingSummaryPath: `${dir}/summary.md`,
151
+ maxRounds: DELEGATE_SOFT_ROUNDS,
133
152
  maxRoundsHard: DELEGATE_MAX_ROUNDS,
134
153
  sleepConsolidation: { enabled: false }, // a short-lived child must not consolidate the owner's knowledge base
135
154
  },
@@ -5,6 +5,8 @@
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";
8
10
  import { composeSystemPrompt } from "../config/persona.js";
9
11
  import { modelCtxFor, LEAN_HARNESS_CTX } from "../router/models.js";
10
12
  import { compactionThreshold, compactionCeilingTokens, turnWallClockMs } from "../config/settings.js";
@@ -33,8 +35,10 @@ export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
33
35
  * to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
34
36
  * MCP tool set directly. Permissions default to the owner's configured policy. */
35
37
  export function createAutonomySession(settings, opts = {}) {
38
+ setActivePowerTools(settings.powerTools); // arm the power-tools run() backstop for headless runs too
36
39
  return new Session({
37
40
  systemPrompt: buildHeadlessSystemPrompt(settings, opts.cwd),
41
+ toolRegistry: visibleRegistry(settings.powerTools), // flag-gated tool set, in sync with the headless catalogue
38
42
  router: buildRouterFromSettings(settings),
39
43
  cwd: opts.cwd,
40
44
  mcp: settings.mcp,
package/dist/cli.js CHANGED
@@ -1,17 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { jsx as _jsx } 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, Box, Text, useApp } from "ink";
8
+ import { render, 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";
11
12
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
12
13
  import { RemoteHost } from "./remote/host.js";
14
+ import { newCode, pairURL } from "./remote/pairing.js";
15
+ import { qrToTerminal } from "./ui/qr.js";
13
16
  import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
14
- import { isErrorResult } from "./ui/format.js";
17
+ import { isErrorResult, resultPreview } from "./ui/format.js";
15
18
  import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
16
19
  import { Session } from "./session.js";
17
20
  import { cacheBustNotice } from "./engine/aurora.js";
@@ -25,8 +28,10 @@ import { caps } from "./ui/capabilities.js";
25
28
  import { composeSystemPrompt, appendMemory } from "./config/persona.js";
26
29
  import { applyToolsBinPath, operatorPath } from "./config/home.js";
27
30
  import { ensureOperatorHome } from "./config/scaffold.js";
31
+ import { listLocalSkills } from "./config/skills-index.js";
28
32
  import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
29
- import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
33
+ import { disposeShellSession, getAgentTasks, visibleRegistry } from "./tools/registry.js";
34
+ import { setActivePowerTools } from "./tools/power-tools.js";
30
35
  import { disposeBrowserNow } from "./browser/session.js";
31
36
  import { EventSink, defaultEventsFile } from "./telemetry/events.js";
32
37
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
@@ -52,6 +57,7 @@ const VERSION = (() => {
52
57
  })();
53
58
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
54
59
  const settings = loadSettings();
60
+ setActivePowerTools(settings.powerTools); // arm the power-tools run() backstop to this box's flags (fail-closed otherwise)
55
61
  // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
56
62
  // root, ignore-everything .gitignore, README, settings.example.json, home.json). Idempotent, never throws.
57
63
  const HOME_SCAFFOLD = ensureOperatorHome({ version: VERSION });
@@ -300,7 +306,7 @@ const HELP = [
300
306
  " /remember <note> store a note to recall in future sessions",
301
307
  " /memory [query] show remembered notes (all, or matching query)",
302
308
  " /mcp [on|off] fleet MCP tools: status, or switch the layer on/off (saved)",
303
- " /login <email> · /logout · /whoami sign in by 6-digit email code (then /login <code>); /login <token> or --browser",
309
+ " /login · /logout · /whoami /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>); /login <token>",
304
310
  " /agents detailed sub-agent status: running/queued/done/errored + metrics",
305
311
  " /bg <task|stop id> spawn a background sub-agent, list, or stop one",
306
312
  " /new start a fresh conversation",
@@ -343,7 +349,6 @@ const REMOTE_SAFE_COMMANDS = [
343
349
  const REMOTE_SAFE_COMMAND_NAMES = new Set(REMOTE_SAFE_COMMANDS.map((c) => c.name));
344
350
  let ID = 0;
345
351
  const nextId = () => `e${++ID}`;
346
- const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
347
352
  // Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
348
353
  // tokens past 1000. One helper so the live line and the settled metric read identically.
349
354
  const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
@@ -352,7 +357,7 @@ const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`
352
357
  function Root() {
353
358
  const { exit } = useApp();
354
359
  const [boot, setBoot] = useState("checking");
355
- const [bootDetail, setBootDetail] = useState(""); // live line during the service-lever preflight
360
+ const [bootDetail, setBootDetail] = useState(""); // live line during the model auto-detect + service-lever preflight
356
361
  const [entries, setEntries] = useState([]);
357
362
  const [live, setLive] = useState(null);
358
363
  const [status, setStatus] = useState("idle");
@@ -447,11 +452,14 @@ function Root() {
447
452
  });
448
453
  }, [settleApproval]);
449
454
  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
450
457
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
451
458
  // only, no network fan-out at session start). Background agents stay local-only + lean.
452
459
  if (!sessionRef.current) {
453
460
  sessionRef.current = new Session({
454
461
  systemPrompt: SYSTEM_PROMPT,
462
+ toolRegistry: visibleRegistry(settings.powerTools), // feature-flagged power-tools: schemas+executor match the prompt catalogue
455
463
  thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
456
464
  router: buildRouter(),
457
465
  mcp: settings.mcp,
@@ -551,12 +559,13 @@ function Root() {
551
559
  if (!bgRef.current) {
552
560
  bgRef.current = new BackgroundAgents((cwd) => new Session({
553
561
  systemPrompt: SYSTEM_PROMPT,
554
- router: new AuroraRouter([
555
- { name: "operator-1m", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow },
556
- ]),
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 }]),
557
566
  maxTokens: settings.maxTokens,
558
567
  maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling also bounds a sub-agent's spend
559
- 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)
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.
560
569
  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")
561
570
  cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
562
571
  temperature: settings.temperature,
@@ -586,10 +595,12 @@ function Root() {
586
595
  setLiveTok(liveTokRef.current);
587
596
  }, 64)).current;
588
597
  const queued = useRef("");
598
+ const [queuedPreview, setQueuedPreview] = useState(""); // reactive mirror of the queue, shown above the composer so a type-while-thinking message is VISIBLE
589
599
  const statusRef = useRef("idle");
590
600
  // Remote-control host (SPEC/remote-session.md): non-null only while /remotecontrol is active. Every
591
601
  // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
592
602
  const remoteRef = useRef(null);
603
+ const [rcConnected, setRcConnected] = useState(false); // remote-control live? drives the footer controller icon
593
604
  const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
594
605
  const push = (e) => setEntries((prev) => [...prev, e]);
595
606
  const submitRef = useRef(() => { });
@@ -628,32 +639,80 @@ function Root() {
628
639
  process.once("SIGTERM", onTerm);
629
640
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
630
641
  }, [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]);
631
695
  useEffect(() => {
632
696
  void (async () => {
633
- // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
634
- // health, so a cold box self-heals instead of dropping the owner at "start it yourself and relaunch".
635
- let reports = [];
636
- try {
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") {
637
712
  const preflight = await import("./services/preflight.js");
638
- reports = await preflight.ensureServices({
639
- aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
640
- autopilot: settings.services?.autopilot,
641
- onProgress: setBootDetail,
642
- });
643
- // If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
644
- // eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
645
- if (reports.find((r) => r.name === "aurora")?.state === "started") {
646
- void preflight.warmAurora(settings.endpoints.aurora.base, settings.endpoints.aurora.model);
647
- }
648
- }
649
- catch { /* preflight is best-effort — fall through to the authoritative health check */ }
650
- const ok = await session.health().catch(() => false);
651
- setBoot(ok ? "ready" : "down");
652
- if (!ok) {
653
- const a = reports.find((r) => r.name === "aurora");
654
- setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
655
- return;
713
+ void preflight.warmAurora(outcome.chosen.base, outcome.chosen.model);
656
714
  }
715
+ setBoot("ready");
657
716
  if (RESUME) {
658
717
  try {
659
718
  const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
@@ -668,15 +727,22 @@ function Root() {
668
727
  }
669
728
  catch { /* no saved session to resume */ }
670
729
  }
671
- // Feed the service-lever outcome to the frozen event stream (dashboard service-health tiles).
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.
672
732
  if (emitTelemetry) {
673
- for (const r of reports) {
674
- const state = r.state === "started" ? "started" : r.state === "up" ? "up" : "down";
675
- eventSink.emit({ kind: "service", session: SESSION_ID, actor: EVENT_ACTOR, service: { name: r.name, state } });
676
- }
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 });
677
737
  }
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 } });
678
743
  // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
679
- const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
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(" · ");
680
746
  if (line) {
681
747
  // SearXNG is lazy (starts on first web_search), but if a backend is ALREADY reachable — an explicit
682
748
  // KODE_SEARXNG_URL, or a container still up from a prior session — show ✓ instead of a misleading
@@ -691,11 +757,15 @@ function Root() {
691
757
  // (submitRef → handleSlash) — never a second connect implementation. Token-gated with a SILENT skip
692
758
  // when unsigned, so a no-token box is never spammed with the sign-in hint every launch; and guarded on
693
759
  // 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.
694
763
  if (rcAutostart(settings) && !remoteRef.current) {
695
764
  const { loadCredentials } = await import("./auth/store.js");
765
+ const { isSignedIn } = await import("./auth/client.js");
696
766
  const creds = await loadCredentials().catch(() => null);
697
767
  const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
698
- if (token)
768
+ if (await isSignedIn(token))
699
769
  submitRef.current("/remotecontrol");
700
770
  }
701
771
  })();
@@ -729,6 +799,14 @@ function Root() {
729
799
  setElapsed(0);
730
800
  setStat("thinking");
731
801
  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
+ }
732
810
  const outcome = await session.send(expandFileMentions(text), {
733
811
  onRoute: (label, pct) => {
734
812
  setRoute(label);
@@ -817,7 +895,7 @@ function Root() {
817
895
  const step = {
818
896
  id: nextId(), name: ev.name, args: ev.args,
819
897
  status: isErrorResult(ev.result) ? "error" : "done",
820
- durationMs, summary: firstLine(ev.result),
898
+ durationMs, summary: resultPreview(ev.result),
821
899
  };
822
900
  steps.push(step);
823
901
  remoteRef.current?.toolStep(step);
@@ -922,6 +1000,7 @@ function Root() {
922
1000
  remoteRef.current?.setCapabilities(buildCapabilities());
923
1001
  const q = queued.current;
924
1002
  queued.current = "";
1003
+ setQueuedPreview("");
925
1004
  if (q)
926
1005
  submitRef.current(q);
927
1006
  }
@@ -1211,16 +1290,12 @@ function Root() {
1211
1290
  break;
1212
1291
  }
1213
1292
  if (intent === "empty") {
1214
- // A second consecutive bare /login escalates to the browser device-grant.
1215
- if (loginEmptyRetryRef.current) {
1216
- loginEmptyRetryRef.current = false;
1217
- await runBrowserLogin();
1218
- break;
1219
- }
1220
- loginEmptyRetryRef.current = true;
1221
- sys(pendingLoginEmailRef.current
1222
- ? `a code was sent to ${pendingLoginEmailRef.current} — enter it with /login <6-digit code> (or press /login again to open the browser)`
1223
- : "usage: /login <email> — sends a 6-digit sign-in code (then /login <code>). Press /login again to open the browser; /login <token> pastes a PAT.");
1293
+ // Bare /login is the HOT sign-in: open the browser + RFC 8628 device-grant IMMEDIATELY and poll to
1294
+ // approval, signing in IN-SESSION (the 0perator.co device page + awaitApproval close the loop now,
1295
+ // so the old "janky dead-end" note no longer applies). /login <email> still does the 6-digit-code
1296
+ // flow; /login <token> pastes a PAT; /login --browser is the same browser path, explicit.
1297
+ loginEmptyRetryRef.current = false;
1298
+ await runBrowserLogin();
1224
1299
  break;
1225
1300
  }
1226
1301
  if (intent === "code") { // a 6-digit code completes a pending email sign-in
@@ -1296,6 +1371,34 @@ function Root() {
1296
1371
  }
1297
1372
  break;
1298
1373
  }
1374
+ case "skills": {
1375
+ // List the locally-installed skills (operator-home skills index). The 60k+ fleet catalogue stays
1376
+ // searchable mid-task via the skill_list tool — this is just the at-a-glance local view, like /memory.
1377
+ const q = arg.toLowerCase();
1378
+ let skills = listLocalSkills();
1379
+ if (q)
1380
+ skills = skills.filter((sk) => sk.name.toLowerCase().includes(q) || (sk.description ?? "").toLowerCase().includes(q));
1381
+ if (!skills.length) {
1382
+ sys(q ? `no installed skills match "${arg}" — the fleet catalogue is still searchable mid-task via the skill_list tool` : "no skills installed locally — the fleet's 60k+ catalogue is searchable mid-task via the skill_list tool");
1383
+ break;
1384
+ }
1385
+ const rows = skills.slice(0, 40).map((sk) => ` ◆ ${sk.name}${sk.description ? ` — ${sk.description.length > 80 ? sk.description.slice(0, 79) + "…" : sk.description}` : ""}`);
1386
+ sys(`skills (${skills.length}${q ? ` matching "${arg}"` : ""}):\n` + rows.join("\n") + (skills.length > 40 ? `\n … +${skills.length - 40} more` : "") + "\n(the fleet's 60k+ catalogue is also searchable mid-task via the skill_list tool)");
1387
+ break;
1388
+ }
1389
+ case "deep-research":
1390
+ case "deepresearch":
1391
+ case "research": {
1392
+ // Sugar for the deep_research tool: plan angles → web_search fan-out → web_fetch → cited brief.
1393
+ // Kicks a real turn so the engine runs the tool (and the owner sees progress), never fabricates sources.
1394
+ if (!arg) {
1395
+ sys("usage: /deep-research <question> — fans out web searches, reads sources, returns a cited brief. One fact is faster with plain web_search.");
1396
+ break;
1397
+ }
1398
+ sys(`◍ deep research: "${arg}" — planning angles, searching + reading sources, then a cited brief…`);
1399
+ void sendTurn(`Use the deep_research tool to research this thoroughly and give me a cited, multi-source brief: ${arg}`);
1400
+ break;
1401
+ }
1299
1402
  case "endpoints": {
1300
1403
  const h = await s.endpointHealth();
1301
1404
  sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
@@ -1546,6 +1649,7 @@ function Root() {
1546
1649
  submitRef.current(`/${name}${args ? " " + args : ""}`);
1547
1650
  },
1548
1651
  onState: (st, detail) => {
1652
+ setRcConnected(st === "live"); // footer controller icon: green when live, gray otherwise
1549
1653
  if (st === "live")
1550
1654
  sys(`✷ remote control LIVE — session ${rh.id}\n Continue on your phone or at https://0perator.co/session/${rh.id}\n /remotecontrol again to stop.`);
1551
1655
  else if (st === "error")
@@ -1565,6 +1669,64 @@ function Root() {
1565
1669
  sys(`connecting remote control → ${url} …`);
1566
1670
  break;
1567
1671
  }
1672
+ case "pair": {
1673
+ // Show a QR a phone scans (Operator app → "Pair Desktop") to drive THIS session, e2e-encrypted. Same
1674
+ // token preflight as /remotecontrol — the host still authenticates to the relay under the owner's
1675
+ // token (the owner-scope gate); the scanned 128-bit code is the end-to-end key the relay never sees.
1676
+ if (remoteRef.current) {
1677
+ remoteRef.current.stop();
1678
+ remoteRef.current = null;
1679
+ setRcConnected(false);
1680
+ sys("pairing stopped — followers detached");
1681
+ break;
1682
+ }
1683
+ const { loadCredentials } = await import("./auth/store.js");
1684
+ const creds = await loadCredentials().catch(() => null);
1685
+ const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
1686
+ if (!token) {
1687
+ sys("pairing needs an Operator sign-in on THIS machine — none found.\n" +
1688
+ " Sign in here first, then re-run /pair:\n" +
1689
+ " • run `operator auth login` in your shell (browser sign-in), or\n" +
1690
+ " • /login <token> to paste a token");
1691
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_no_token" } });
1692
+ break;
1693
+ }
1694
+ const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
1695
+ const code = newCode();
1696
+ const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
1697
+ onPrompt: (text) => submitRef.current(text),
1698
+ onApprovalResponse: (id, approve) => settleApproval(id, approve),
1699
+ onAskUserResponse: (id, answer) => settleQuestion(id, answer),
1700
+ onInterrupt: () => s.interrupt(),
1701
+ onCommand: (cmdName, cmdArgs) => {
1702
+ if (!REMOTE_SAFE_COMMAND_NAMES.has(cmdName)) {
1703
+ sys(`remote control: blocked "/${cmdName}" from a follower — not exposed for remote dispatch`);
1704
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: cmdName } });
1705
+ return;
1706
+ }
1707
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: cmdArgs ? `${cmdName} ${cmdArgs}` : cmdName } });
1708
+ submitRef.current(`/${cmdName}${cmdArgs ? " " + cmdArgs : ""}`);
1709
+ },
1710
+ onState: (st, detail) => {
1711
+ setRcConnected(st === "live");
1712
+ if (st === "error")
1713
+ sys(`pairing error: ${detail ?? "connection lost"} — /pair to retry`);
1714
+ else if (st === "closed")
1715
+ sys("pairing disconnected");
1716
+ if (st === "live")
1717
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_connected", detail: rh.id ?? undefined } });
1718
+ else if (st === "closed" || st === "error")
1719
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_disconnected", detail } });
1720
+ },
1721
+ }, { sessionId: SESSION_ID, code });
1722
+ remoteRef.current = rh;
1723
+ rh.setCapabilities(buildCapabilities());
1724
+ rh.connect();
1725
+ const link = pairURL(code, SESSION_ID);
1726
+ const qr = await qrToTerminal(link);
1727
+ sys(`▮ Pair this desktop — in the Operator app tap "Pair Desktop → Scan QR" and point it here:\n\n${qr}\n\n …or choose "Paste code" and paste:\n ${link}\n\n End-to-end encrypted — the relay only ever sees a blind id, never the code. /pair again to stop.`);
1728
+ break;
1729
+ }
1568
1730
  default: sys(`unknown command /${name} — try /help`);
1569
1731
  }
1570
1732
  }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode]);
@@ -1576,7 +1738,7 @@ function Root() {
1576
1738
  void sendTurn(text);
1577
1739
  }, [sendTurn, handleSlash]);
1578
1740
  submitRef.current = onSubmit;
1579
- const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; }, []);
1741
+ const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; setQueuedPreview(queued.current); }, []);
1580
1742
  // Shift+Tab cycles the operating mode (Claude-Code parity). auto→manual→plan→auto. Auto drives with
1581
1743
  // no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
1582
1744
  const onCycleMode = useCallback(() => {
@@ -1626,9 +1788,6 @@ function Root() {
1626
1788
  }, [boot]);
1627
1789
  if (boot === "checking")
1628
1790
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
1629
- if (boot === "down") {
1630
- 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" })] }));
1631
- }
1632
1791
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
1633
1792
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
1634
1793
  // turn's numbers mid-turn — the clock always moves.
@@ -1643,7 +1802,7 @@ function Root() {
1643
1802
  ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
1644
1803
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
1645
1804
  : metrics;
1646
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, 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, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
1805
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, 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, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, rcConnected: rcConnected, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
1647
1806
  const cur = approval;
1648
1807
  if (cur)
1649
1808
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -1729,19 +1888,11 @@ else {
1729
1888
  catch { /* best-effort; a write failure just re-shows next boot */ }
1730
1889
  }
1731
1890
  }
1732
- const inkInstance = render(_jsx(Root, {}));
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() });
1733
1897
  if (FULLSCREEN)
1734
1898
  void inkInstance.waitUntilExit().then(leaveAltScreen);
1735
- // Ink erases the previous frame by line COUNT, computed from the terminal width at draw time. When the
1736
- // window is minimized or resized, a resize event with a changed/zero width desyncs that count, so every
1737
- // later re-render (a keystroke, the 250ms clock) APPENDS the status rule instead of overwriting it — the
1738
- // "a new line every time I type" screen-fill. Force a full clear on each resize so Ink re-syncs to the
1739
- // real terminal and redraws from a clean slate instead of stacking stale frames.
1740
- let resizeClear;
1741
- process.stdout.on?.("resize", () => {
1742
- clearTimeout(resizeClear);
1743
- resizeClear = setTimeout(() => { try {
1744
- inkInstance.clear();
1745
- }
1746
- catch { /* stdout detached */ } }, 16);
1747
- });