@0perator/operator 0.1.274 → 0.1.275

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.
@@ -0,0 +1,1171 @@
1
+ #!/usr/bin/env node
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // KODE-TSI entry — the Ink shell. Thin by design: all engine logic lives in Session (src/session.ts,
4
+ // headless + tested); this file only maps Session's streaming callbacks onto React state and renders
5
+ // the SPEC §6 <App>. The port's whole point — full-frame React reconciliation + Ink <Static> — is what
6
+ // makes the scroll/echo/overwrite bug class of the ANSI-cursor Python core structurally impossible.
7
+ import { useCallback, useEffect, useRef, useState } from "react";
8
+ import { render, Box, Text, useApp } from "ink";
9
+ import { App } from "./ui/index.js";
10
+ import { mastheadLines } from "./ui/Masthead.js";
11
+ import { RemoteHost } from "./remote/host.js";
12
+ import { isErrorResult } from "./ui/format.js";
13
+ import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
14
+ import { Session } from "./session.js";
15
+ import { AuroraRouter } from "./router/router.js";
16
+ import { BackgroundAgents } from "./background/index.js";
17
+ import { loadSettings, saveSettings } from "./config/settings.js";
18
+ import { disposeShellSession } from "./tools/registry.js";
19
+ import { EventSink } from "./telemetry/events.js";
20
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
21
+ import { expandFileMentions } from "./util/mentions.js";
22
+ import { join, dirname } from "node:path";
23
+ import { homedir, hostname } from "node:os";
24
+ import { createHash } from "node:crypto";
25
+ // RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
26
+ // (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
27
+ // Single source of truth = package.json, read at runtime — so the splash/statusline can never drift
28
+ // from the published version again (the "update said 0.63 but it shows 0.62" bug).
29
+ const VERSION = (() => {
30
+ try {
31
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
32
+ }
33
+ catch {
34
+ return "0.0.0";
35
+ }
36
+ })();
37
+ // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
38
+ const settings = loadSettings();
39
+ // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
40
+ process.env.KODE_SANDBOX = settings.sandbox.mode;
41
+ // web_search reads KODE_AUTOPILOT_URL / KODE_SEARXNG_URL from the env at exec; project them from the
42
+ // settings layer so a settings.json backend works without the user exporting anything. applyEnv already
43
+ // folded any real env var into settings.search (env wins), so this never clobbers an explicit export.
44
+ if (settings.search?.autopilotUrl)
45
+ process.env.KODE_AUTOPILOT_URL = settings.search.autopilotUrl;
46
+ if (settings.search?.searxngUrl)
47
+ process.env.KODE_SEARXNG_URL = settings.search.searxngUrl;
48
+ if (settings.search?.searxngEngines)
49
+ process.env.KODE_SEARXNG_ENGINES = settings.search.searxngEngines;
50
+ const sd = settings.search?.docker;
51
+ if (sd) {
52
+ if (sd.enabled === false)
53
+ process.env.KODE_SEARXNG_MANAGE = "0";
54
+ if (sd.port)
55
+ process.env.KODE_SEARXNG_PORT = String(sd.port);
56
+ if (sd.image)
57
+ process.env.KODE_SEARXNG_IMAGE = sd.image;
58
+ if (sd.idleSec !== undefined)
59
+ process.env.KODE_SEARXNG_IDLE_SEC = String(sd.idleSec);
60
+ }
61
+ // The searxng module reads this env flag in its own sync exit hook; project the setting so it applies.
62
+ if (settings.services?.stopOnExit?.searxng === false)
63
+ process.env.KODE_STOP_SEARXNG_ON_EXIT = "0";
64
+ // Remote-engine auth. When this Operator points at a REMOTE engine (KODE_AURORA=https://api.axe.onl),
65
+ // the gateway fronts the model with operator-token auth, so the model call must carry the bearer. Load
66
+ // it once at boot from the keychain (or KODE_OPERATOR_TOKEN) and hand it to the engine; a local :8097
67
+ // never receives it (aurora.ts only sends to a non-loopback base), so this is safe on JL1 and costs
68
+ // nothing there. This is what lets a thin client (a 4 GB MacBook) run Operator against JL1's Aurora.
69
+ try {
70
+ const { loadCredentials } = await import("./auth/store.js");
71
+ const { setOperatorToken } = await import("./engine/aurora.js");
72
+ const creds = await loadCredentials().catch(() => null);
73
+ setOperatorToken(process.env.KODE_OPERATOR_TOKEN || creds?.token || undefined);
74
+ }
75
+ catch { /* auth is optional — a local engine needs none */ }
76
+ // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
77
+ // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
78
+ // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
79
+ // a bg session has no approver, so denial is the only safe posture (no silent computer use). When
80
+ // disabled the tools are never registered at all (zero surface). Only cli.tsx (node) touches this, so the
81
+ // mobile bundle never sees these tools.
82
+ let computerAskRules = {};
83
+ let computerDenyRules = {};
84
+ let embodimentHub; // injected hub: STANDARD servers + chauffeur
85
+ let chauffeurServer; // set when embodiment is on & fleet off
86
+ if (settings.computer.enabled) {
87
+ const { COMPUTER_TOOLS, COMPUTER_TOOL_NAMES, setComputerEnabled } = await import("./tools/computer.js");
88
+ const { registry } = await import("./tools/registry.js");
89
+ setComputerEnabled(true);
90
+ for (const t of COMPUTER_TOOLS)
91
+ registry.set(t.name, t);
92
+ // Embodiment also wires chauffeur (robust textual-AX computer use) when installed. When the owner has
93
+ // opted into the full fleet (settings.mcp), chauffeur is already reachable there, so we don't double-wire;
94
+ // otherwise we collect its server config to join the standard injected hub below.
95
+ const { buildChauffeurServer, CHAUFFEUR_ACTION_NAMES, CHAUFFEUR_TOOL_NAMES } = await import("./tools/chauffeur.js");
96
+ if (!settings.mcp)
97
+ chauffeurServer = (await buildChauffeurServer()) ?? undefined;
98
+ // Foreground: computer_* and chauffeur ACTIONS prompt ("ask"); chauffeur READS (list_windows,
99
+ // get_window_state, …) are intentionally NOT gated, so the model reads the screen freely and completes
100
+ // a task end-to-end without walking the owner through each step. Only real input/mutation asks.
101
+ const askNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_ACTION_NAMES : [])];
102
+ computerAskRules = Object.fromEntries(askNames.map((n) => [n, "ask"]));
103
+ // Background sub-agents have no approver, so DENY every embodiment tool, reads included.
104
+ const denyNames = [...COMPUTER_TOOL_NAMES, ...(chauffeurServer ? CHAUFFEUR_TOOL_NAMES : [])];
105
+ computerDenyRules = Object.fromEntries(denyNames.map((n) => [n, "deny"]));
106
+ }
107
+ // STANDARD MCP: report-mcp (PDF tools) ships with Operator — always injected, even without the full-fleet
108
+ // `mcp` setting, so a bare Operator can build PDFs out of the box. When the fleet IS on it's already in the
109
+ // config, so we only inject standalone when the fleet is off. Chauffeur (if collected) joins the same hub.
110
+ if (!settings.mcp) {
111
+ const { loadStandardServers, McpHub } = await import("./mcp/index.js");
112
+ const servers = [...(await loadStandardServers()), ...(chauffeurServer ? [chauffeurServer] : [])];
113
+ if (servers.length)
114
+ embodimentHub = new McpHub(servers);
115
+ }
116
+ // Foreground policy = the owner's settings with computer tools forced to "ask". When computer control is
117
+ // off, computerAskRules is empty, so this is behaviorally identical to settings.permissions (an empty
118
+ // rules object keeps a "bypass" policy inert — zero overhead).
119
+ const fgPermissions = { ...settings.permissions, rules: { ...settings.permissions.rules, ...computerAskRules } };
120
+ // Session persistence: the conversation is auto-saved every turn and reloaded by `operator --resume`.
121
+ // It lives in a central per-workspace state dir — NEVER in the working directory, where it would be
122
+ // grepped back into the model's own context (self-poisoning → runaway ctx growth), committed by
123
+ // accident, or listed as project litter. One file per cwd (keyed by a short hash) so --resume stays
124
+ // scoped to the directory you launched in.
125
+ const SESSION_DIR = join(homedir(), ".axe", "operator", "sessions");
126
+ const SESSION_FILE = process.env.KODE_SESSION_FILE ??
127
+ join(SESSION_DIR, `${createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16)}.json`);
128
+ try {
129
+ mkdirSync(SESSION_DIR, { recursive: true });
130
+ }
131
+ catch { /* best-effort; the write is guarded too */ }
132
+ const RESUME = process.argv.includes("--resume") || process.argv.includes("-r") || process.env.KODE_RESUME === "1";
133
+ // Shared frozen-OperatorEvent stream (telemetry/events.ts) — the ONE sink for the whole session: tool +
134
+ // control events (emitted by the permission wrapper when enforcing), plus turn / service / remote-control
135
+ // events emitted below. Writes local JSONL + POSTs to KODE_TELEMETRY_URL if set (the dashboard's feed).
136
+ // The sink always exists so the audit trail works even with telemetry off; turn/service events are gated
137
+ // on telemetry.enabled so the metrics stream honors the off switch.
138
+ const SESSION_ID = createHash("sha1").update(`${process.cwd()}:${Date.now()}`).digest("hex").slice(0, 12);
139
+ // Scratchpad (per session) + handoff (per working directory). Projected to env for the scratchpad /
140
+ // session_handoff tools; the handoff is auto-loaded into the system prompt below so the next session in
141
+ // this directory resumes from it. Kept under ~/.axe/operator, never in the workspace.
142
+ const WORKSPACE_HASH = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16);
143
+ process.env.KODE_SCRATCH_FILE = join(homedir(), ".axe", "operator", "scratch", `${SESSION_ID}.md`);
144
+ process.env.KODE_HANDOFF_FILE = join(homedir(), ".axe", "operator", "handoff", `${WORKSPACE_HASH}.md`);
145
+ try {
146
+ mkdirSync(dirname(process.env.KODE_SCRATCH_FILE), { recursive: true });
147
+ mkdirSync(dirname(process.env.KODE_HANDOFF_FILE), { recursive: true });
148
+ }
149
+ catch { /* best-effort; the tools guard too */ }
150
+ const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: "cli" };
151
+ const eventSink = new EventSink();
152
+ const emitTelemetry = settings.telemetry.enabled !== false;
153
+ // Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
154
+ // and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
155
+ // 1,048,576-token context at full speed). No size-based routing decision remains.
156
+ function buildRouter() {
157
+ const aurora = { name: "operator-1m", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow };
158
+ // Primary first; the optional failover is only reached via the router's health-gated recover() when
159
+ // the primary errors (routeBySize always picks aurora at index 0 since 1M fits every prompt).
160
+ const eps = [aurora];
161
+ const fo = settings.endpoints.failover;
162
+ if (fo)
163
+ eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
164
+ return new AuroraRouter(eps);
165
+ }
166
+ // Project context: auto-load a per-repo instructions file (AGENTS.md / CLAUDE.md / .operator/AGENTS.md)
167
+ // from the working dir and append it to the system prompt, so Operator picks up house rules, conventions
168
+ // and build commands the way modern coding agents do. First match wins; capped so a huge file can't blow
169
+ // the prompt. Best-effort — a missing file is normal.
170
+ function loadProjectContext() {
171
+ for (const name of ["AGENTS.md", "CLAUDE.md", ".operator/AGENTS.md", "OPERATOR.md"]) {
172
+ try {
173
+ const t = readFileSync(join(process.cwd(), name), "utf8").trim();
174
+ if (t)
175
+ return `\n\n## Project context (${name}, auto-loaded from the working directory)\n${t.slice(0, 8000)}`;
176
+ }
177
+ catch { /* not present — try the next */ }
178
+ }
179
+ return "";
180
+ }
181
+ // Session handoff: the note the previous session in THIS directory wrote for its future self (via the
182
+ // session_handoff tool). Auto-loaded here so the agent resumes seamlessly. Capped so a runaway handoff
183
+ // can't dominate the prompt.
184
+ function loadHandoff() {
185
+ try {
186
+ const t = readFileSync(process.env.KODE_HANDOFF_FILE ?? "", "utf8").trim();
187
+ if (t)
188
+ return `\n\n## Handoff from your previous session here (you wrote this for yourself)\n${t.slice(0, 6000)}\n\nContinue from where it leaves off, and update it with session_handoff before you finish.`;
189
+ }
190
+ catch { /* none yet */ }
191
+ return "";
192
+ }
193
+ // Embodiment guidance, appended only when computer control is on. It steers Aurora to READ the screen
194
+ // with chauffeur's textual accessibility tree instead of hand-rolling osascript — the exact loop that
195
+ // failed on Slack (AppleScript can't read Electron UIs). chauffeur is reachable either via the scoped
196
+ // embodiment hub or the full fleet MCP.
197
+ const chauffeurReady = !!chauffeurServer || settings.mcp;
198
+ const EMBODIMENT_GUIDE = settings.computer.enabled
199
+ ? `\n## Controlling this computer\nComputer control is ON (every action asks the owner first). Drive apps with ` +
200
+ `computer_app_open / computer_app_activate, computer_type, computer_key, computer_click, computer_screenshot.` +
201
+ (chauffeurReady
202
+ ? ` To SEE the screen use the chauffeur tools — NEVER shell_exec/osascript/System Events to read or drive ` +
203
+ `a GUI (AppleScript cannot read Electron apps like Slack/VS Code/Discord and just errors). For ANY ` +
204
+ `request about what is on screen, or to click/read/drive an app, you MUST call the chauffeur tools — ` +
205
+ `never answer from memory and never say you cannot see the screen. First call: chauffeur:list_windows. ` +
206
+ `Correct usage, follow it exactly:\n` +
207
+ `- Do NOT pass a "session" argument to any chauffeur tool. Omit it — the implicit session is used ` +
208
+ `automatically. (Inventing a session label causes "session has ended" errors.)\n` +
209
+ `- At the START of any on-screen task, call chauffeur:set_agent_cursor_enabled {enabled: true} so the ` +
210
+ `owner can watch the agent's cursor move — do this before the first click/type/drag.\n` +
211
+ `- To read a window: call chauffeur:list_windows, take a window_id + pid FROM THAT RESULT, then ` +
212
+ `immediately chauffeur:get_window_state {pid, window_id} → a TEXT accessibility tree (roles, labels, ` +
213
+ `values, clickable elements + coordinates). window_ids go stale, so always list_windows again right ` +
214
+ `before get_window_state; never reuse an old id.\n` +
215
+ `- To act: chauffeur:click / chauffeur:type_text / chauffeur:press_key, addressing elements by the info ` +
216
+ `from the latest get_window_state.\n` +
217
+ `- If ANY chauffeur tool returns "session has ended", call chauffeur:start_session ONCE (no arguments), ` +
218
+ `then retry the read — do not loop the failing call.\n` +
219
+ `Work END-TO-END from the owner's one instruction: read → decide → act by chaining these tools yourself, ` +
220
+ `then report the result. Reads run without a prompt; only actions ask. Use ask_user only for a genuine ` +
221
+ `owner decision — never to walk through a task you can just do.`
222
+ : ` NOTE: reliably READING on-screen UI (especially Electron apps like Slack) needs the chauffeur driver, ` +
223
+ `which is not installed here; computer_screenshot only saves a PNG you cannot read back yet. Do not ` +
224
+ `hand-write osascript to scrape a GUI — it will error on Electron apps.`)
225
+ : "";
226
+ const SYSTEM_PROMPT = (settings.systemPrompt ??
227
+ `You are Operator, AXE's terminal coding agent — built by AXE, running on AXE's own model. Refer to ` +
228
+ `yourself as Operator and to the platform as AXE; never call yourself or the platform Claude, ` +
229
+ `Anthropic, or any other vendor. When you encounter files or directories on disk named "claude", ` +
230
+ `".claude", "anthropic", etc., describe them neutrally (by their literal path, or as "AI tooling ` +
231
+ `files") — do not attribute them to a vendor. Use your tools to inspect and edit the ` +
232
+ `workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
233
+ `\nContext window: 1,048,576 tokens (1M) — you run on AXE's model served locally with a full ` +
234
+ `1M-token context. You can hold very large files and long histories; do not claim a smaller limit.` +
235
+ `\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT of each other — reading several ` +
236
+ `files, running several greps/checks, inspecting multiple unrelated things — issue them as multiple ` +
237
+ `tool calls in a SINGLE message so they run in parallel, instead of one call, waiting, then the next. ` +
238
+ `Only serialize when one call's output feeds the next call's input (e.g. read a file, then edit it), ` +
239
+ `or when a call mutates something the next call depends on seeing. Batching independent reads is ` +
240
+ `almost always faster and is the default you should reach for; do not artificially serialize work ` +
241
+ `that has no real dependency.` +
242
+ `\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
243
+ `build) call spawn_agent with a fully self-contained instruction — it runs on another session ` +
244
+ `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
245
+ `live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
246
+ `spawn many at once — they all share this one model.` +
247
+ `\n## Finding things\nTo search file CONTENTS (a symbol, a string, a config key), use the search tool ` +
248
+ `(ripgrep — fast, parallel, .gitignore-aware) scoped to a directory: search {"pattern":"…","path":"src"}, ` +
249
+ `and set files_with_matches to just locate the files before reading them. NEVER run ` +
250
+ `\`find ~/ -maxdepth N | grep | grep\` over the whole home directory — it is slow, hits the command ` +
251
+ `timeout, and can wedge the shell. Narrow FIRST: check the 2-3 most likely directories before any broad ` +
252
+ `sweep, and batch independent searches in ONE message so they run in parallel.\nWhen asked to find a ` +
253
+ `project or file by NAME that is NOT in the working directory: (1) run ls ~ to see the REAL top-level ` +
254
+ `folders (projects live in non-obvious ones — e.g. ~/Axwell, ~/.axe/repos, ~/Desktop — not just ` +
255
+ `~/Projects); (2) then a BOUNDED find scoped to a SPECIFIC directory with a generous timeout — ` +
256
+ `shell_exec {"command":"find ~/.axe/repos -maxdepth 3 -iname \\"*name*\\" 2>/dev/null | head -80",` +
257
+ `"timeout_ms":60000} — never an unbounded find over all of ~ or /. Widen the pattern if a repo may be ` +
258
+ `named differently. Only report not-found after this real search, and say exactly where you looked.` +
259
+ `\n## Scratchpad & handoff\nUse the scratchpad tool for private working notes, plans, and intermediate ` +
260
+ `results — think there, not in the workspace or your reply. Before you finish a substantial task, or ` +
261
+ `when you're running low on context, call session_handoff to record what you did, the state, and the ` +
262
+ `next steps: your next session in this directory loads it automatically, so write it for your future self.`) +
263
+ loadProjectContext() + loadHandoff() + EMBODIMENT_GUIDE;
264
+ const MAX_BG = 4; // concurrent background sub-agents — all share the single Aurora 1M endpoint, so cap fan-out
265
+ const HELP = [
266
+ "commands:",
267
+ " /help this list",
268
+ " /model [id] pick a model: operator-1m · operator-128k · moa (mixture-of-agents)",
269
+ " /endpoints show the Operator endpoint + live health",
270
+ " /services ensure/inspect the service lever (Operator+autopilot+searxng); /services stop",
271
+ " /audit [n] recent tool + control-plane events from the audit trail (default 15)",
272
+ " /dashboard launch the live swarm console (watches every Operator session)",
273
+ " /plan plan mode: read-only research + propose a plan (/plan again to execute)",
274
+ " /mode [plan|manual|auto] set operating mode (plan · manual · autonomous); also Shift+Tab to cycle",
275
+ " /think extended reasoning: Operator thinks before answering (/think again = off)",
276
+ " /ultrathink deep, exhaustive reasoning for hard problems (/ultrathink again = off)",
277
+ " /compact force-compact the conversation now",
278
+ " /remember <note> store a note to recall in future sessions",
279
+ " /memory [query] show remembered notes (all, or matching query)",
280
+ " /mcp count of fleet MCP tools this session (KODE_TSI_MCP=1)",
281
+ " /login [token] · /logout · /whoami AXE account sign-in (device grant via shell, or paste a token)",
282
+ " /bg <task|stop id> spawn a background sub-agent, list, or stop one",
283
+ " /new start a fresh conversation",
284
+ " /clear clear the screen (keeps the conversation)",
285
+ " /exit /quit leave operator",
286
+ "esc — interrupt a running turn (or quit when idle)",
287
+ ].join("\n");
288
+ // Slash commands a remote-control FOLLOWER is allowed to drive (RemoteHost `command` frame →
289
+ // SPEC/remote-session.md extension; see REMOTE_RICH_HEAD_AUDIT.md). This is BOTH the allowlist enforced
290
+ // in the "remotecontrol" case's onCommand below AND what's advertised in RemoteCapabilities.commands —
291
+ // one list, so a follower's command palette never offers something the host will actually refuse.
292
+ // Deliberately excludes: exit/quit (kills the host process), login/logout (mutates the owner's stored
293
+ // AXE credentials), and remotecontrol/remote (a follower must never be able to kick every other
294
+ // follower off the session it's attached to). Those four are the only slash commands that act OUTSIDE
295
+ // the tool/permission system (direct switch-case side effects, ungated whether local or remote) —
296
+ // everything below still runs with the same local privilege a `prompt` frame already has today.
297
+ const REMOTE_SAFE_COMMANDS = [
298
+ { name: "help", description: "list available commands" },
299
+ { name: "model", description: "pick a model: operator-1m · operator-128k · moa (mixture-of-agents)", args: "[id]" },
300
+ { name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
301
+ { name: "endpoints", description: "show the Operator endpoint + live health" },
302
+ { name: "services", description: "ensure/inspect the service lever (Operator+autopilot+searxng); stop searxng", args: "[stop]" },
303
+ { name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
304
+ { name: "dashboard", description: "launch the live swarm console" },
305
+ { name: "plan", description: "toggle plan mode (read-only research + propose a plan)" },
306
+ { name: "mode", description: "set operating mode: plan · manual · autonomous", args: "[plan|manual|auto]" },
307
+ { name: "think", description: "toggle extended reasoning" },
308
+ { name: "ultrathink", description: "toggle deep, exhaustive reasoning" },
309
+ { name: "compact", description: "force-compact the conversation now" },
310
+ { name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
311
+ { name: "memory", description: "show remembered notes", args: "[query]" },
312
+ { name: "mcp", description: "count of fleet MCP tools this session" },
313
+ { name: "whoami", description: "show signed-in identity" },
314
+ { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
315
+ { name: "new", description: "start a fresh conversation" },
316
+ { name: "clear", description: "clear the screen (keeps the conversation)" },
317
+ ];
318
+ const REMOTE_SAFE_COMMAND_NAMES = new Set(REMOTE_SAFE_COMMANDS.map((c) => c.name));
319
+ let ID = 0;
320
+ const nextId = () => `e${++ID}`;
321
+ const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
322
+ // Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
323
+ // tokens past 1000. One helper so the live line and the settled metric read identically.
324
+ const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
325
+ const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k tokens` : `${n} token${n === 1 ? "" : "s"}`);
326
+ const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`;
327
+ function Root() {
328
+ const { exit } = useApp();
329
+ const [boot, setBoot] = useState("checking");
330
+ const [bootDetail, setBootDetail] = useState(""); // live line during the service-lever preflight
331
+ const [entries, setEntries] = useState([]);
332
+ const [live, setLive] = useState(null);
333
+ const [status, setStatus] = useState("idle");
334
+ const [stepLabel, setStepLabel] = useState(""); // tool(s) currently executing, for the step animation
335
+ const [liveTools, setLiveTools] = useState([]); // one row per call in the CURRENT batch,
336
+ // live: seeded "running" by onToolStart, each flips to done/error independently as onToolResult fires
337
+ // for it — see ui/liveTools.ts. Cleared once the batch settles (onToolBatch).
338
+ const [route, setRoute] = useState("operator-1m");
339
+ const [ctxPct, setCtxPct] = useState(0);
340
+ const [metrics, setMetrics] = useState(""); // last turn's "N tok · X tok/s · Ys" for the status rule
341
+ const [liveTok, setLiveTok] = useState(0); // live output-token count for the CURRENT turn — animates the
342
+ // status rule as tokens stream (each SSE delta ≈ 1 token). Zero extra renders: it rides the per-delta
343
+ // setLive re-render that already happens, so there's no performance cost and no animation timer.
344
+ const [bgAgents, setBgAgents] = useState([]);
345
+ const [authUser, setAuthUser] = useState(""); // signed-in identity for the status rule
346
+ const [planMode, setPlanMode] = useState(false); // /plan: read-only research + propose, shown as a status badge
347
+ // Operating mode, cycled with Shift+Tab (like Claude Code): auto (no gate) → manual (approve mutations)
348
+ // → plan (read-only + propose) → auto. Auto=bypass policy, Manual=gated policy, Plan=session plan mode.
349
+ const [opMode, setOpMode] = useState(settings.permissions.mode === "gated" ? "manual" : "auto");
350
+ // Ref mirror of opMode so buildCapabilities() reflects the LIVE mode synchronously (a follower's mode
351
+ // selector must light up the instant it changes, before React flushes the setOpMode state update).
352
+ const opModeRef = useRef(opMode);
353
+ const [thinkMode, setThinkMode] = useState("off"); // /think, /ultrathink badge
354
+ const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
355
+ const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
356
+ // phase where no content tokens stream — that was the "timer stuck" bug (Ink only re-renders on deltas).
357
+ // Tool-approval bridge: when the permission policy returns "ask", session.approve(name,args) parks the
358
+ // decision here and <ApprovalPrompt> renders it; the keystroke resolves the promise. "allow always"
359
+ // adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
360
+ const [approval, setApproval] = useState(null);
361
+ // ask_user bridge: the model's clarification question, parked here until the owner — locally, or a
362
+ // remote follower during /remotecontrol — picks an option. Mirrors the approval bridge's
363
+ // first-wins: both a local pick and a follower's ask_user_response settle through settleQuestion.
364
+ const [question, setQuestion] = useState(null);
365
+ const pendingQuestions = useRef(new Map());
366
+ const settleQuestion = useCallback((id, answer) => {
367
+ const resolve = pendingQuestions.current.get(id);
368
+ if (!resolve)
369
+ return; // already settled (first-wins)
370
+ pendingQuestions.current.delete(id);
371
+ resolve(answer);
372
+ setQuestion((cur) => (cur && cur.id === id ? null : cur));
373
+ }, []);
374
+ const askUser = useCallback((q, options) => new Promise((resolve) => {
375
+ const id = "q_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
376
+ pendingQuestions.current.set(id, resolve);
377
+ setQuestion({ id, question: q, options, resolve: (a) => settleQuestion(id, a) });
378
+ remoteRef.current?.askUser(id, q, options); // mirror to followers (owner-scoped)
379
+ }), [settleQuestion]);
380
+ // /model picker: same QuestionPrompt UI pattern as ask_user, but purely local (never relayed) —
381
+ // it's a session setting, not something the model is asking.
382
+ const [modelPicker, setModelPicker] = useState(null);
383
+ const alwaysAllowRef = useRef(new Set());
384
+ // Pending gated approvals by id. Both the local keystroke and a remote follower's approval_response
385
+ // route through settleApproval — FIRST answer wins (§7); the map delete makes it idempotent.
386
+ const pendingApprovals = useRef(new Map());
387
+ const settleApproval = useCallback((id, allow, always = false) => {
388
+ const resolve = pendingApprovals.current.get(id);
389
+ if (!resolve)
390
+ return; // already settled (first-wins)
391
+ pendingApprovals.current.delete(id);
392
+ resolve(allow);
393
+ setApproval((cur) => {
394
+ if (cur && cur.id === id && allow && always)
395
+ alwaysAllowRef.current.add(cur.name);
396
+ return cur && cur.id === id ? null : cur;
397
+ });
398
+ }, []);
399
+ const approveFn = useCallback((name, args) => {
400
+ if (alwaysAllowRef.current.has(name))
401
+ return Promise.resolve(true);
402
+ const id = "ap_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
403
+ return new Promise((resolve) => {
404
+ pendingApprovals.current.set(id, resolve);
405
+ setApproval({ id, name, args, resolve: (b) => settleApproval(id, b) });
406
+ remoteRef.current?.approvalRequest(id, name, args); // mirror to followers (owner-scoped)
407
+ });
408
+ }, [settleApproval]);
409
+ const sessionRef = useRef(null); // lazy — never reconstruct on re-render
410
+ // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
411
+ // only, no network fan-out at session start). Background agents stay local-only + lean.
412
+ if (!sessionRef.current) {
413
+ sessionRef.current = new Session({
414
+ systemPrompt: SYSTEM_PROMPT,
415
+ router: buildRouter(),
416
+ mcp: settings.mcp,
417
+ mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
418
+ maxTokens: settings.maxTokens,
419
+ temperature: settings.temperature,
420
+ recall: settings.memory.recall,
421
+ models: settings.models, // /model registry overrides (router/models.ts has the built-in defaults)
422
+ moa: settings.moa, // MOA proposers/aggregator config (MOA-DESIGN.md); absent = "/model moa" explains
423
+ activeModel: settings.activeModel, // persisted /model choice, applied at startup
424
+ permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
425
+ approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
426
+ askUser, // registers the ask_user tool so the model can put a clarifying question to the owner
427
+ telemetry: settings.telemetry, // local-only metrics by default
428
+ eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // frozen event stream (tool/control audit)
429
+ // Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
430
+ // sub-agent can't spawn more (no fork bombs). Cap at MAX_BG — all sub-agents share the one Aurora
431
+ // endpoint, so past the cap we refuse with guidance rather than thrash the shared KV cache.
432
+ spawnAgent: (task) => {
433
+ const mgr = bgRef.current;
434
+ if (!mgr)
435
+ return "background manager not ready yet — retry in a moment";
436
+ if (mgr.activeCount() >= MAX_BG)
437
+ return `at capacity: ${MAX_BG} sub-agents already running on the single Operator 1M endpoint — wait for one to finish (see the background panel) before spawning more`;
438
+ const id = mgr.spawn(task);
439
+ return `spawned background sub-agent ${id} — it posts its result here when done. Keep working; watch its live tokens + time in the background panel.`;
440
+ },
441
+ });
442
+ }
443
+ const session = sessionRef.current;
444
+ // Background sub-agents run on their own Session against the same single Aurora 1M endpoint as the
445
+ // foreground — one model, one context tier.
446
+ const bgRef = useRef(null);
447
+ if (!bgRef.current) {
448
+ bgRef.current = new BackgroundAgents(() => new Session({
449
+ systemPrompt: SYSTEM_PROMPT,
450
+ router: new AuroraRouter([
451
+ { name: "operator-1m", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow },
452
+ ]),
453
+ maxTokens: settings.maxTokens,
454
+ temperature: settings.temperature,
455
+ // Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
456
+ // denied outright. (No-op when computer control is off.) Everything else runs as normal.
457
+ permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
458
+ }), () => setBgAgents(bgRef.current.list()), (agent, result) => {
459
+ setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
460
+ setBgAgents(bgRef.current.list());
461
+ }, settings.endpoints.aurora.model);
462
+ }
463
+ const bg = bgRef.current;
464
+ const liveText = useRef("");
465
+ const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
466
+ const queued = useRef("");
467
+ const statusRef = useRef("idle");
468
+ // Remote-control host (SPEC/remote-session.md): non-null only while /remotecontrol is active. Every
469
+ // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
470
+ const remoteRef = useRef(null);
471
+ const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
472
+ const push = (e) => setEntries((prev) => [...prev, e]);
473
+ const submitRef = useRef(() => { });
474
+ // AXE skills fetched/saved THIS session (name -> a best-effort description) — there's no persistent
475
+ // skill-loader/registry in this codebase to read from (skills are hub-fetched on demand by the
476
+ // skill_fetch/skill_save tools, see tools/registry.ts), so this is the closest real signal for
477
+ // RemoteCapabilities.skills: "what has this session actually pulled in," tracked from onToolBatch
478
+ // below. Session-scoped by design — a fresh session starts with an empty list, matching /model's own
479
+ // lack of persistence across sessions.
480
+ const skillsRef = useRef(new Map());
481
+ // Assembles RemoteCapabilities from the real registries at call time — commands (the remote-safe
482
+ // allowlist above), skills (skillsRef), MCP servers (session.mcpServers() — empty until first-turn
483
+ // discovery has run, see session.ts maybeRecall), models (session.modelRegistry()), permission mode,
484
+ // cwd, and the active model. Cheap to call liberally: RemoteHost.setCapabilities() only touches the
485
+ // wire when the result actually differs from what's already been sent.
486
+ // mcpServers reports the REAL per-server tool count here (toolCount) alongside the full tools[] —
487
+ // RemoteHost.setCapabilities() is what trims tools[] to a wire-safe preview (REMOTE_RICH_HEAD_AUDIT.md
488
+ // §4 BLOCKER: this fleet's own MCP surface is 600+ tools, comfortably over the SPEC §8 256 KB frame
489
+ // cap if enumerated in full); building it honestly here means toolCount survives that trim intact.
490
+ const buildCapabilities = () => ({
491
+ commands: REMOTE_SAFE_COMMANDS,
492
+ skills: [...skillsRef.current.entries()].map(([name, description]) => ({ name, description })),
493
+ mcpServers: session.mcpServers().map((s) => ({ name: s.name, toolCount: s.tools.length, tools: s.tools })),
494
+ models: session.modelRegistry().map((m) => ({ id: m.id, label: m.label, ctx: m.ctx ?? 0, kind: m.kind })),
495
+ mode: opModeRef.current, // live operating mode (Plan/Manual/Autonomous) — a follower can read + drive it via /mode
496
+ cwd: process.cwd(),
497
+ model: session.currentModel(),
498
+ });
499
+ // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
500
+ // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
501
+ useEffect(() => {
502
+ const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); };
503
+ const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); process.exit(0); };
504
+ process.once("exit", onExit);
505
+ process.once("SIGTERM", onTerm);
506
+ return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
507
+ }, [session]);
508
+ useEffect(() => {
509
+ void (async () => {
510
+ // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
511
+ // health, so a cold box self-heals instead of dropping the owner at "start it yourself and relaunch".
512
+ let reports = [];
513
+ try {
514
+ const preflight = await import("./services/preflight.js");
515
+ reports = await preflight.ensureServices({
516
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
517
+ autopilot: settings.services?.autopilot,
518
+ onProgress: setBootDetail,
519
+ });
520
+ // If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
521
+ // eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
522
+ if (reports.find((r) => r.name === "aurora")?.state === "started") {
523
+ void preflight.warmAurora(settings.endpoints.aurora.base, settings.endpoints.aurora.model);
524
+ }
525
+ }
526
+ catch { /* preflight is best-effort — fall through to the authoritative health check */ }
527
+ const ok = await session.health().catch(() => false);
528
+ setBoot(ok ? "ready" : "down");
529
+ if (!ok) {
530
+ const a = reports.find((r) => r.name === "aurora");
531
+ setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
532
+ return;
533
+ }
534
+ if (RESUME) {
535
+ try {
536
+ const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
537
+ if (session.restore(saved)) {
538
+ const restored = saved
539
+ .filter((m) => (m.role === "user" || m.role === "assistant") && m.content.trim())
540
+ .map((m) => ({ kind: "message", message: { id: nextId(), role: m.role, content: m.content } }));
541
+ setEntries(restored);
542
+ setCtxPct(session.ctxPct());
543
+ push({ kind: "message", message: { id: nextId(), role: "system", content: `resumed ${session.turnCount()} prior turns` } });
544
+ }
545
+ }
546
+ catch { /* no saved session to resume */ }
547
+ }
548
+ // Feed the service-lever outcome to the frozen event stream (dashboard service-health tiles).
549
+ if (emitTelemetry) {
550
+ for (const r of reports) {
551
+ const state = r.state === "started" ? "started" : r.state === "up" ? "up" : "down";
552
+ eventSink.emit({ kind: "service", session: SESSION_ID, actor: EVENT_ACTOR, service: { name: r.name, state } });
553
+ }
554
+ }
555
+ // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
556
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
557
+ if (line)
558
+ push({ kind: "message", message: { id: nextId(), role: "system", content: `services: ${line} · searxng lazy` } });
559
+ })();
560
+ }, []);
561
+ // Show who's signed in (best-effort, non-blocking): load stored creds, verify against the backend.
562
+ useEffect(() => {
563
+ void (async () => {
564
+ try {
565
+ const { loadCredentials } = await import("./auth/store.js");
566
+ const { verifyToken } = await import("./auth/client.js");
567
+ const creds = await loadCredentials();
568
+ if (!creds)
569
+ return;
570
+ const acct = await verifyToken(creds.token);
571
+ if (acct)
572
+ setAuthUser(acct.email ?? acct.external_id);
573
+ }
574
+ catch { /* auth is optional — never block the REPL */ }
575
+ })();
576
+ }, []);
577
+ const sendTurn = useCallback(async (text) => {
578
+ push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
579
+ remoteRef.current?.userPrompt(text); // mirror to followers
580
+ remoteRef.current?.turnStart(); // allocate this turn's assistant id (stable stream→final)
581
+ liveText.current = "";
582
+ liveReasoning.current = "";
583
+ setLive(null);
584
+ setLiveTok(0); // reset the live counter at the start of the turn
585
+ turnStartRef.current = Date.now();
586
+ setElapsed(0);
587
+ setStat("thinking");
588
+ try {
589
+ const outcome = await session.send(expandFileMentions(text), {
590
+ onRoute: (label, pct) => { setRoute(label); setCtxPct(pct); remoteRef.current?.setStatus(pct, label); },
591
+ onDelta: (chunk) => {
592
+ liveText.current += chunk;
593
+ setLiveTok((t) => t + 1); // ≈1 token per streamed delta — batched with setLive, no extra render
594
+ setStat("streaming");
595
+ setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current || undefined } });
596
+ remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
597
+ },
598
+ onReasoning: (chunk) => {
599
+ // Thinking streams before/between content — accumulate it and show it dimmed in the live entry
600
+ // (renderEntry renders `reasoning` above the answer, dimColor). Distinct from onDelta so the
601
+ // thought process reads at lower opacity than the real answer, per the requested look.
602
+ liveReasoning.current += chunk;
603
+ setLiveTok((t) => t + 1); // reasoning tokens ARE generated tokens — count them so the live
604
+ // counter + tok/s keep moving during a long thinking phase (they were frozen before content).
605
+ setStat("thinking");
606
+ setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current } });
607
+ remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
608
+ },
609
+ onAutoContinue: (round) => {
610
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
611
+ },
612
+ onSelfHeal: (kind) => {
613
+ // A recovery reads as the agent working it out, NOT an error — show the calm "adjusting"
614
+ // animation instead of surfacing a raw http 400/5xx. The next delta/tool flips status back.
615
+ setStepLabel(kind === "context_exceeded" ? "adjusting context" : kind === "unavailable" ? "reconnecting" : "recovering");
616
+ setStat("recovering");
617
+ },
618
+ onToolStart: (calls) => {
619
+ setStepLabel(calls.map((c) => c.name).join(", "));
620
+ setStat("executing");
621
+ setLiveTools(seedLiveTools(calls));
622
+ },
623
+ onToolResult: (id, result) => {
624
+ setLiveTools((rows) => settleLiveTool(rows, id, result));
625
+ },
626
+ onToolBatch: (events, durationMs) => {
627
+ for (const ev of events) {
628
+ const step = {
629
+ id: nextId(), name: ev.name, args: ev.args,
630
+ status: isErrorResult(ev.result) ? "error" : "done",
631
+ durationMs, summary: firstLine(ev.result),
632
+ };
633
+ push({ kind: "tool", step });
634
+ remoteRef.current?.toolStep(step);
635
+ // Track skills this session has actually pulled in, for RemoteCapabilities.skills (see
636
+ // skillsRef above) — the description is synthetic (this codebase has no skill metadata to
637
+ // read a real one from), not sourced from the fetched skillmd content.
638
+ if (!isErrorResult(ev.result)) {
639
+ if (ev.name === "skill_fetch") {
640
+ const slug = String(ev.args?.slug ?? "").trim();
641
+ if (slug)
642
+ skillsRef.current.set(slug, "loaded this session via skill_fetch");
643
+ }
644
+ else if (ev.name === "skill_save") {
645
+ const nm = String(ev.args?.name ?? "").trim();
646
+ if (nm)
647
+ skillsRef.current.set(nm, "saved to profile this session via skill_save");
648
+ }
649
+ }
650
+ }
651
+ liveText.current = "";
652
+ liveReasoning.current = "";
653
+ setLive(null);
654
+ setLiveTools([]); // batch settled — the per-call rows are now in the settled transcript above
655
+ setStat("thinking");
656
+ },
657
+ });
658
+ if (outcome.interrupted) {
659
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
660
+ remoteRef.current?.system("⎋ interrupted — output above kept");
661
+ }
662
+ else if (outcome.content.trim()) {
663
+ // Keep the final answer's thinking (dim, above the answer), plus a dim note when generation was
664
+ // cut short — loop breaker, output-limit truncation, or content filter — so a short/odd answer
665
+ // is never a mystery.
666
+ const stopNote = outcome.stopReason === "repetition" ? "(output truncated — loop detected)"
667
+ : outcome.stopReason === "length" ? "(truncated at the output limit — ask me to continue)"
668
+ : outcome.stopReason === "content_filter" ? "(the model stopped — content filter)"
669
+ : undefined;
670
+ const reasoning = [liveReasoning.current.trim(), stopNote].filter(Boolean).join("\n") || undefined;
671
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
672
+ remoteRef.current?.finalAssistant(outcome.content, reasoning);
673
+ }
674
+ // Surface the turn's real metrics: wall time · output tokens @ decode tok/s · prefill size. The
675
+ // prefill number is the key one on a local model — it's where "0 tokens for N seconds" goes (the
676
+ // model reading the prompt), otherwise invisible.
677
+ if (!outcome.interrupted && (outcome.tokens || outcome.durationMs || outcome.promptTokens)) {
678
+ const tok = outcome.tokens ?? 0;
679
+ const durationMs = outcome.durationMs ?? 0;
680
+ const secs = durationMs / 1000;
681
+ const tps = outcome.genMs && outcome.genMs > 0 ? Math.round(tok / (outcome.genMs / 1000)) : 0;
682
+ const prefill = outcome.promptTokens ?? 0;
683
+ const parts = [fmtDuration(secs), `${fmtTokens(tok).replace(/ tokens?$/, " tok")}${tps ? ` @ ${tps} tok/s` : ""}`];
684
+ if (prefill)
685
+ parts.push(`${fmtTokens(prefill).replace(/ tokens?$/, "")} prefill`);
686
+ setMetrics(`(${parts.join(" · ")})`);
687
+ // Feed the same numbers to the frozen event stream (dashboard + mobile). Gated on telemetry.enabled.
688
+ if (emitTelemetry) {
689
+ eventSink.emit({ kind: "turn", session: SESSION_ID, actor: EVENT_ACTOR,
690
+ turn: { tokens: tok, tokPerSec: secs > 0 ? Math.round(tok / secs) : undefined, ctxPct: session.ctxPct(), route: session.currentRoute(), durationMs } });
691
+ }
692
+ }
693
+ }
694
+ catch (e) {
695
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: `[turn error: ${e.message}]` } });
696
+ }
697
+ finally {
698
+ liveText.current = "";
699
+ setLive(null);
700
+ setLiveTools([]); // an interrupt/error mid-batch must not leave stale "running" rows on screen
701
+ setCtxPct(session.ctxPct());
702
+ setStat("idle");
703
+ try {
704
+ writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()));
705
+ }
706
+ catch { /* auto-save is best-effort */ }
707
+ // Re-check capabilities after every turn: MCP discovery (first-turn only) may have just landed,
708
+ // and any skill_fetch/skill_save this turn updated skillsRef above. A no-op diff never hits the wire.
709
+ remoteRef.current?.setCapabilities(buildCapabilities());
710
+ const q = queued.current;
711
+ queued.current = "";
712
+ if (q)
713
+ submitRef.current(q);
714
+ }
715
+ }, []);
716
+ const sys = useCallback((text) => {
717
+ push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
718
+ remoteRef.current?.system(text);
719
+ }, []);
720
+ // Single code path for a mode change — Shift+Tab (onCycleMode), the /mode slash command (local or
721
+ // driven by a remote follower), and /plan all funnel here so the policy, the plan flag, the status
722
+ // badge, and the follower-facing capabilities stay in lockstep. auto=Autonomous (bypass policy, no
723
+ // approvals), manual=gated (mutations ask), plan=read-only research (session plan mode).
724
+ const applyMode = useCallback((next, quiet) => {
725
+ if (next === "plan") {
726
+ session.setPlanMode(true);
727
+ }
728
+ else {
729
+ session.setPlanMode(false);
730
+ session.setPermissionMode(next === "auto" ? "bypass" : "gated");
731
+ }
732
+ opModeRef.current = next;
733
+ setPlanMode(next === "plan");
734
+ setOpMode(next);
735
+ if (!quiet)
736
+ sys(next === "auto"
737
+ ? "◆ mode → AUTONOMOUS — I execute without asking (shift+tab to cycle)"
738
+ : next === "manual"
739
+ ? "◈ mode → MANUAL — I ask before mutating (writes/edits/shell) (shift+tab to cycle)"
740
+ : "◔ mode → PLAN — read-only research + a proposed plan; nothing runs (shift+tab to cycle)");
741
+ remoteRef.current?.setCapabilities(buildCapabilities()); // re-sync attached followers' mode selector
742
+ }, [sys]);
743
+ const handleSlash = useCallback(async (cmd) => {
744
+ const [name, ...rest] = cmd.slice(1).split(/\s+/);
745
+ const arg = rest.join(" ").trim();
746
+ const s = session;
747
+ switch (name) {
748
+ case "help":
749
+ sys(HELP);
750
+ break;
751
+ case "exit":
752
+ case "quit":
753
+ bg.dispose();
754
+ s.shutdown();
755
+ exit();
756
+ break;
757
+ case "clear":
758
+ setEntries([]);
759
+ setLive(null);
760
+ break;
761
+ case "new":
762
+ s.reset();
763
+ setEntries([]);
764
+ setLive(null);
765
+ setCtxPct(0);
766
+ sys("started a fresh conversation");
767
+ break;
768
+ case "model": {
769
+ // Apply a selection (picker choice or `/model <id>`), persist it, and reflect it on the
770
+ // status rule right away — the router only updates its label mid-turn (onRoute), and MOA has
771
+ // no router of its own at all, so this is the one place that's always accurate immediately.
772
+ const apply = (id) => {
773
+ const r = s.setModel(id);
774
+ if (!r.ok) {
775
+ sys(`${r.error} — run /model for the list`);
776
+ return;
777
+ }
778
+ setRoute(s.currentModel());
779
+ saveSettings({ activeModel: s.currentModel() });
780
+ sys(`model → ${s.currentModel()} · ctx ${s.ctxPct()}% · turns ${s.turnCount()}`);
781
+ remoteRef.current?.setCapabilities(buildCapabilities()); // active model changed — re-sync attached followers
782
+ };
783
+ if (arg) {
784
+ apply(arg);
785
+ break;
786
+ }
787
+ const active = s.currentModel();
788
+ const models = s.modelRegistry();
789
+ const options = models.map((m) => `${m.label}${m.id === active ? " (active)" : ""}`);
790
+ setModelPicker({
791
+ question: "Select a model",
792
+ options,
793
+ resolve: (answer) => {
794
+ setModelPicker(null);
795
+ const idx = options.indexOf(answer);
796
+ apply(idx >= 0 ? models[idx].id : answer.trim());
797
+ },
798
+ });
799
+ break;
800
+ }
801
+ case "route":
802
+ if (s.pinRoute(arg || "auto"))
803
+ sys(arg && arg !== "auto" ? `routing pinned to ${arg}` : "routing set to auto (by size)");
804
+ else
805
+ sys(`unknown endpoint "${arg}" — see /endpoints`);
806
+ break;
807
+ case "compact": {
808
+ const n = await s.compactNow();
809
+ sys(n > 0 ? `compacted ${n} earlier messages` : "nothing to compact yet");
810
+ setCtxPct(s.ctxPct());
811
+ break;
812
+ }
813
+ case "remember":
814
+ if (!arg) {
815
+ sys("usage: /remember <note> — store something to recall in future sessions");
816
+ break;
817
+ }
818
+ sys((await s.remember(arg)) ? "remembered" : "could not store that note");
819
+ break;
820
+ case "memory": {
821
+ const m = await s.memoryText(arg || undefined, 10);
822
+ sys(m || "(no memories yet — /remember <note> to add one)");
823
+ break;
824
+ }
825
+ case "whoami":
826
+ sys(authUser ? `signed in as ${authUser}` : "not signed in — run `operator auth login` in your shell");
827
+ break;
828
+ case "logout": {
829
+ const { clearCredentials } = await import("./auth/store.js");
830
+ await clearCredentials();
831
+ setAuthUser("");
832
+ sys("signed out");
833
+ break;
834
+ }
835
+ case "login": {
836
+ // No arg → run the device-grant flow inline (RFC 8628): request a code, open the browser to the
837
+ // approval page, poll until the human approves, then store the token + verify. A PAT can still be
838
+ // pasted (`/login <token>`) for a quick headless sign-in (handled below).
839
+ if (!arg) {
840
+ const { requestDeviceCode, awaitApproval } = await import("./auth/client.js");
841
+ const { openBrowser } = await import("./auth/commands.js");
842
+ const { saveCredentials } = await import("./auth/store.js");
843
+ const { setOperatorToken } = await import("./engine/aurora.js");
844
+ try {
845
+ const dc = await requestDeviceCode();
846
+ const url = dc.verification_uri_complete ?? dc.verification_uri;
847
+ const opened = openBrowser(url);
848
+ sys(`◔ sign-in: ${opened ? "opened" : "open"} ${dc.verification_uri} and approve with code \x1b[1m${dc.user_code}\x1b[0m — waiting…`);
849
+ const r = await awaitApproval(dc);
850
+ if (r.state === "approved") {
851
+ await saveCredentials({ token: r.token, user: r.account.external_id, issuedAt: Date.now() });
852
+ setOperatorToken(r.token); // so a remote engine call carries the fresh bearer immediately
853
+ setAuthUser(r.account.email ?? r.account.external_id);
854
+ sys(`✓ Authenticated as ${r.account.email ?? r.account.external_id}`);
855
+ }
856
+ else {
857
+ sys(`sign-in ${r.state} — /login to retry`);
858
+ }
859
+ }
860
+ catch (e) {
861
+ sys(`sign-in failed: ${e instanceof Error ? e.message : String(e)} — /login to retry`);
862
+ }
863
+ break;
864
+ }
865
+ const { verifyToken } = await import("./auth/client.js");
866
+ const { saveCredentials } = await import("./auth/store.js");
867
+ const acct = await verifyToken(arg);
868
+ if (!acct) {
869
+ sys("that token was rejected");
870
+ break;
871
+ }
872
+ await saveCredentials({ token: arg, user: acct.external_id, issuedAt: Date.now() });
873
+ setAuthUser(acct.email ?? acct.external_id);
874
+ sys(`signed in as ${acct.email ?? acct.external_id}`);
875
+ break;
876
+ }
877
+ case "mcp": {
878
+ const n = s.mcpToolCount();
879
+ sys(n > 0 ? `${n} fleet MCP tools available this session` : "no MCP tools (enable with KODE_TSI_MCP=1, then send a message to discover)");
880
+ break;
881
+ }
882
+ case "endpoints": {
883
+ const h = await s.endpointHealth();
884
+ sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
885
+ break;
886
+ }
887
+ case "plan": {
888
+ const on = !s.inPlanMode();
889
+ applyMode(on ? "plan" : "auto", true); // policy + follower caps sync; custom message below
890
+ sys(on
891
+ ? "◔ plan mode ON — I'll research read-only and propose a plan; writes/edits/shell mutations are blocked. /plan again to approve + execute."
892
+ : "plan mode OFF — back to normal execution.");
893
+ break;
894
+ }
895
+ case "mode": {
896
+ // Set the operating mode by name (owner OR a remote follower via a `command` frame). Mirrors
897
+ // Shift+Tab's cycle but addressable: /mode plan | manual | autonomous. No arg → report current.
898
+ const a = arg.toLowerCase();
899
+ const target = a === "plan" ? "plan"
900
+ : (a === "manual" || a === "gated") ? "manual"
901
+ : (a === "auto" || a === "autonomous" || a === "bypass") ? "auto"
902
+ : null;
903
+ if (!target) {
904
+ sys(`mode is ${opModeRef.current === "auto" ? "AUTONOMOUS" : opModeRef.current.toUpperCase()} — usage: /mode plan | manual | autonomous`);
905
+ break;
906
+ }
907
+ applyMode(target);
908
+ break;
909
+ }
910
+ case "think": {
911
+ const on = s.currentThinkMode() !== "think";
912
+ s.setThinkMode(on ? "think" : "off");
913
+ setThinkMode(on ? "think" : "off");
914
+ sys(on ? "✲ think ON — Operator reasons (shown dimmed) before answering. /think again to turn off."
915
+ : "think off — back to fast direct answers.");
916
+ break;
917
+ }
918
+ case "ultrathink": {
919
+ const on = s.currentThinkMode() !== "ultrathink";
920
+ s.setThinkMode(on ? "ultrathink" : "off");
921
+ setThinkMode(on ? "ultrathink" : "off");
922
+ sys(on ? "✲✲ ultrathink ON — Operator reasons deeply + exhaustively before answering (slower, deeper). /ultrathink again to turn off."
923
+ : "ultrathink off — back to fast direct answers.");
924
+ break;
925
+ }
926
+ case "audit": {
927
+ // The human-supervisor view of the frozen event stream: recent tool decisions + control events
928
+ // (tier denials, signature lines, RC) straight from the audit JSONL. Read-only.
929
+ const n = Math.max(1, Math.min(50, Number(arg) || 15));
930
+ const file = (process.env.KODE_EVENTS_FILE || process.env.KODE_AUDIT_FILE || join(homedir(), ".axe", "operator", "events.jsonl"));
931
+ let lines = [];
932
+ try {
933
+ lines = readFileSync(file, "utf8").trim().split("\n").filter(Boolean);
934
+ }
935
+ catch { /* no audit yet */ }
936
+ if (!lines.length) {
937
+ sys(`no audit events yet (${settings.permissions.tier ?? "admin"} tier, ${settings.permissions.mode} mode). Events record once enforcement is on.`);
938
+ break;
939
+ }
940
+ const rows = lines.slice(-n).map((l) => { try {
941
+ return JSON.parse(l);
942
+ }
943
+ catch {
944
+ return null;
945
+ } }).filter(Boolean)
946
+ .filter((e) => e.kind === "tool" || e.kind === "control")
947
+ .map((e) => {
948
+ const t = new Date(e.ts).toLocaleTimeString();
949
+ if (e.kind === "tool")
950
+ return ` ${t} ${e.tool.decision === "deny" ? "✗" : e.tool.approved === false ? "⃠" : "●"} ${e.tool.name} [${e.tool.outcome}]${e.tool.args ? " " + String(e.tool.args).slice(0, 60) : ""}`;
951
+ return ` ${t} ⚑ ${e.control.event}${e.control.detail ? " " + e.control.detail : ""}`;
952
+ });
953
+ sys(rows.length ? `audit (last ${rows.length}):\n` + rows.join("\n") : "no tool/control events in the audit log yet");
954
+ break;
955
+ }
956
+ case "dashboard": {
957
+ // Launch the live swarm console (dashboard/server.mjs) if it isn't already up. It live-tails
958
+ // ~/.axe/operator/events.jsonl, so it shows EVERY Operator session with zero per-session config.
959
+ const port = Number(process.env.KODE_DASHBOARD_PORT) || 8899;
960
+ const url = `http://127.0.0.1:${port}`;
961
+ const net = await import("node:net");
962
+ const up = await new Promise((resolve) => {
963
+ const s = net.connect(port, "127.0.0.1");
964
+ s.on("connect", () => { s.destroy(); resolve(true); });
965
+ s.on("error", () => resolve(false));
966
+ setTimeout(() => { try {
967
+ s.destroy();
968
+ }
969
+ catch { /* noop */ } resolve(false); }, 800);
970
+ });
971
+ if (up) {
972
+ sys(`swarm console already running → ${url}`);
973
+ break;
974
+ }
975
+ try {
976
+ const { spawn } = await import("node:child_process");
977
+ const { fileURLToPath } = await import("node:url");
978
+ const { dirname } = await import("node:path");
979
+ const server = join(dirname(fileURLToPath(import.meta.url)), "..", "dashboard", "server.mjs");
980
+ const child = spawn(process.execPath, [server], { detached: true, stdio: "ignore", env: { ...process.env, PORT: String(port) } });
981
+ child.unref();
982
+ sys(`launched the swarm console → ${url} — live-tailing ~/.axe/operator/events.jsonl (every Operator session, zero config). Open it in a browser.`);
983
+ }
984
+ catch (e) {
985
+ sys(`could not launch the dashboard: ${e.message}`);
986
+ }
987
+ break;
988
+ }
989
+ case "services": {
990
+ // The lever, on demand: `/services` probes + starts any down launchd service; `/services stop`
991
+ // tears down only the session-scoped SearXNG (Aurora/autopilot are shared and stay up).
992
+ if (arg === "stop") {
993
+ const { stopSessionServices } = await import("./services/preflight.js");
994
+ await stopSessionServices({ searxng: true });
995
+ sys("stopped session-scoped services (SearXNG). Operator + autopilot are shared and stay up.");
996
+ break;
997
+ }
998
+ sys("checking services…");
999
+ const { ensureServices } = await import("./services/preflight.js");
1000
+ const reports = await ensureServices({
1001
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
1002
+ autopilot: settings.services?.autopilot,
1003
+ });
1004
+ sys("services:\n" + reports.map((r) => ` ${r.state === "up" || r.state === "started" ? "●" : "○"} ${r.name} ${r.state}${r.detail ? " " + r.detail : ""}`).join("\n") + "\n · searxng: lazy (starts on first web_search, stops on idle/exit)");
1005
+ break;
1006
+ }
1007
+ case "bg":
1008
+ if (!arg) {
1009
+ const l = bg.list();
1010
+ sys(l.length ? "background agents:\n" + l.map((a) => ` ${a.id} [${a.status}]${a.round ? ` round ${a.round}` : ""} ${a.label}`).join("\n") : "no background agents (spawn: /bg <task>)");
1011
+ }
1012
+ else if (arg.startsWith("stop ")) {
1013
+ const id = arg.slice(5).trim();
1014
+ sys(bg.stop(id) ? `stopped ${id}` : `unknown agent ${id}`);
1015
+ }
1016
+ else {
1017
+ const id = bg.spawn(arg);
1018
+ sys(`spawned ${id} in the background — /bg to list · /bg stop ${id} to cancel`);
1019
+ }
1020
+ break;
1021
+ case "remotecontrol":
1022
+ case "remote": {
1023
+ if (remoteRef.current) {
1024
+ remoteRef.current.stop();
1025
+ remoteRef.current = null;
1026
+ sys("remote control stopped — followers detached");
1027
+ break;
1028
+ }
1029
+ const { loadCredentials } = await import("./auth/store.js");
1030
+ const creds = await loadCredentials().catch(() => null);
1031
+ const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
1032
+ // Preflight: with no token the host would still open the socket and send hello{token:""},
1033
+ // and the relay verifies the host token then CLOSES on a non-200 — which surfaced to the
1034
+ // owner only as a generic "connection lost", hiding the real cause (not signed in on THIS
1035
+ // box). Refuse legibly instead: name the fix, don't touch the wire. (An expired/rejected
1036
+ // token still fails at the relay and reports its own "error" frame; this catches the far
1037
+ // more common absent-token case with zero false positives, since "" is unambiguous.)
1038
+ if (!token) {
1039
+ sys("remote control needs an Operator sign-in on THIS machine — none found.\n" +
1040
+ " Sign in here first, then re-run /remotecontrol:\n" +
1041
+ " • run `operator auth login` in your shell (browser sign-in), or\n" +
1042
+ " • /login <token> to paste a token\n" +
1043
+ " Without a token the relay rejects the host and closes the connection.");
1044
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_no_token" } });
1045
+ break;
1046
+ }
1047
+ const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
1048
+ const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
1049
+ onPrompt: (text) => submitRef.current(text), // follower drives a turn
1050
+ onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
1051
+ onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
1052
+ onInterrupt: () => s.interrupt(), // follower cancels the turn
1053
+ // A follower drove a slash command. Reuse the EXACT same path a local `/name args` line
1054
+ // takes (submitRef → onSubmit → handleSlash) — never a second implementation of the
1055
+ // switch — but only for names on the remote-safe allowlist; anything else is refused
1056
+ // locally-visibly (sys + an audit event) rather than silently dropped or silently run.
1057
+ onCommand: (name, args) => {
1058
+ if (!REMOTE_SAFE_COMMAND_NAMES.has(name)) {
1059
+ sys(`remote control: blocked "/${name}" from a follower — not exposed for remote dispatch`);
1060
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command_blocked", detail: name } });
1061
+ return;
1062
+ }
1063
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_command", detail: args ? `${name} ${args}` : name } });
1064
+ submitRef.current(`/${name}${args ? " " + args : ""}`);
1065
+ },
1066
+ onState: (st, detail) => {
1067
+ if (st === "live")
1068
+ 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.`);
1069
+ else if (st === "error")
1070
+ sys(`remote control error: ${detail ?? "connection lost"} — /remotecontrol to retry`);
1071
+ else if (st === "closed")
1072
+ sys("remote control disconnected");
1073
+ // Frozen event stream: the persistent RC indicator + dashboard read these control events.
1074
+ if (st === "live")
1075
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_connected", detail: rh.id ?? undefined } });
1076
+ else if (st === "closed" || st === "error")
1077
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_disconnected", detail } });
1078
+ },
1079
+ });
1080
+ remoteRef.current = rh;
1081
+ rh.setCapabilities(buildCapabilities()); // cached now, so the very first attach's snapshot already carries it
1082
+ rh.connect();
1083
+ sys(`connecting remote control → ${url} …`);
1084
+ break;
1085
+ }
1086
+ default: sys(`unknown command /${name} — try /help`);
1087
+ }
1088
+ }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode]);
1089
+ const onSubmit = useCallback((text) => {
1090
+ const t = text.trim();
1091
+ if (t.startsWith("/")) {
1092
+ void handleSlash(t);
1093
+ return;
1094
+ }
1095
+ void sendTurn(text);
1096
+ }, [sendTurn, handleSlash]);
1097
+ submitRef.current = onSubmit;
1098
+ const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; }, []);
1099
+ // Shift+Tab cycles the operating mode (Claude-Code parity). auto→manual→plan→auto. Auto drives with
1100
+ // no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
1101
+ const onCycleMode = useCallback(() => {
1102
+ const cur = opModeRef.current;
1103
+ const next = cur === "auto" ? "manual" : cur === "manual" ? "plan" : "auto";
1104
+ applyMode(next);
1105
+ }, [applyMode]);
1106
+ const onInterrupt = useCallback(() => {
1107
+ if (statusRef.current === "idle") {
1108
+ bg.dispose();
1109
+ session.shutdown();
1110
+ return exit();
1111
+ } // Ctrl-C / ESC at rest quits
1112
+ session.interrupt();
1113
+ }, [exit]);
1114
+ // Live clock: a lightweight interval ticks `elapsed` while a turn is active, so the timer advances
1115
+ // even through a long reasoning phase that streams no content tokens (the "timer stuck" bug — Ink
1116
+ // only re-renders on deltas otherwise). Torn down the moment we go idle. MUST be declared with the
1117
+ // other hooks, ABOVE the boot early-returns below — otherwise it's skipped on the first render and the
1118
+ // hook count changes when boot flips to "ready" ("Rendered more hooks than during the previous render").
1119
+ useEffect(() => {
1120
+ const active = status === "thinking" || status === "streaming" || status === "executing" || status === "recovering";
1121
+ if (!active)
1122
+ return;
1123
+ const id = setInterval(() => setElapsed((Date.now() - turnStartRef.current) / 1000), 250);
1124
+ return () => clearInterval(id);
1125
+ }, [status]);
1126
+ if (boot === "checking")
1127
+ return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
1128
+ if (boot === "down") {
1129
+ 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" })] }));
1130
+ }
1131
+ // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
1132
+ // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
1133
+ // turn's numbers mid-turn — the clock always moves.
1134
+ const SPIN = "⣾⣽⣻⢿⡿⣟⣯⣷";
1135
+ const active = status === "streaming" || status === "thinking" || status === "executing" || status === "recovering";
1136
+ const spin = SPIN[Math.floor(elapsed * 4) % SPIN.length];
1137
+ // Before the first token streams, the model is PREFILLING (reading the prompt) — that's the "0 tokens
1138
+ // for N seconds" the user sees. Label it honestly instead of showing a frozen "0 tokens", so a slow
1139
+ // local prefill reads as work in progress, not a hang. Once tokens flow, show the live count + elapsed.
1140
+ const liveMetrics = active
1141
+ ? liveTok === 0
1142
+ ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
1143
+ : `${spin} ${fmtMeta(elapsed, liveTok)}`
1144
+ : metrics;
1145
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, onApprovalDecide: (allow, always) => {
1146
+ const cur = approval;
1147
+ if (cur)
1148
+ settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
1149
+ } }));
1150
+ }
1151
+ // `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
1152
+ // headless (CI / SSH). Anything else falls through to the interactive REPL below.
1153
+ if (process.argv[2] === "auth") {
1154
+ const { runAuth } = await import("./auth/commands.js");
1155
+ process.exit(await runAuth(process.argv.slice(3)));
1156
+ }
1157
+ // `operator update` (bareword) and `operator --update` both self-update.
1158
+ if (process.argv[2] === "update" || process.argv.includes("--update")) {
1159
+ const { runUpdate } = await import("./update.js");
1160
+ process.exit(await runUpdate());
1161
+ }
1162
+ // The Ink shell needs a real terminal (raw-mode keyboard). Fail clearly instead of crashing deep
1163
+ // in useInput when piped/non-interactive — for scripted use, drive Session (src/session.ts) directly.
1164
+ if (!process.stdin.isTTY) {
1165
+ process.stderr.write("kode-tsi needs an interactive terminal (TTY). For scripted turns, import { Session } from kode-tsi.\n");
1166
+ process.exit(1);
1167
+ }
1168
+ // Boot masthead (design #29) — printed ONCE to stdout before Ink mounts, so the big gradient wordmark
1169
+ // lives in permanent scrollback and never enters Ink's dynamic-frame redraw (reflow-safe by construction).
1170
+ process.stdout.write(mastheadLines(`Operator · 1M · v${VERSION}`).join("\n") + "\n");
1171
+ render(_jsx(Root, {}));