@0perator/operator 0.0.7 → 0.1.17

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.
@@ -92,3 +92,20 @@ export async function verifyToken(token, timeoutMs = 10_000) {
92
92
  export function authBase() {
93
93
  return AUTH_BASE;
94
94
  }
95
+ /** Request a sign-in code by email. Server emails a 6-digit code (10-min TTL). */
96
+ export async function signupStart(email) {
97
+ const { status, json } = await post("/operator/signup/start", { email });
98
+ if (status === 200)
99
+ return { ok: true };
100
+ const error = json?.error ?? json?.detail?.error ?? (typeof json?.detail === "string" ? json.detail : `http_${status}`);
101
+ return { ok: false, error, status };
102
+ }
103
+ /** Exchange (email, 6-digit code) for an operator token. Burns the code on success. */
104
+ export async function signupVerify(email, code) {
105
+ const { status, json } = await post("/operator/signup/verify", { email, code });
106
+ if (status === 200 && json?.token) {
107
+ return { ok: true, token: json.token, account: (json.account ?? { external_id: email }) };
108
+ }
109
+ const error = json?.error ?? json?.detail?.error ?? (typeof json?.detail === "string" ? json.detail : `http_${status}`);
110
+ return { ok: false, error, status };
111
+ }
@@ -1,36 +1,112 @@
1
1
  // `operator auth <sub>` — the CLI auth surface, run BEFORE the Ink REPL mounts (cli.tsx intercepts it).
2
2
  // Plain console I/O (no Ink) so it works headless / over SSH. Subcommands:
3
- // login device-authorization grant: show a code, open the browser, poll to approval
4
- // login --token <t> paste a personal access token (CI / headless), validate + store
5
- // logout clear the stored credentials
6
- // status | whoami show who's signed in (verified against the backend)
3
+ // login smooth default: email + 6-digit code, no browser (prompts interactively)
4
+ // login --email <addr> same email-code flow, email supplied up front
5
+ // login --browser RFC 8628 device grant: show a code, open the browser, poll to approval
6
+ // login --token <pat> paste a personal access token (CI / headless), validate + store
7
+ // logout clear the stored credentials
8
+ // status | whoami show who's signed in (verified against the backend)
9
+ //
10
+ // The email-code path is the default because the terminal→browser device dance is janky (auto-open is
11
+ // unreliable across setups, and "click Connect" only works if you're already signed into AuthGate in
12
+ // your default browser). Email-code needs nothing but your inbox, and it's the SAME flow the mobile app
13
+ // uses — one story across surfaces.
7
14
  import { spawn } from "node:child_process";
8
15
  import { platform } from "node:os";
9
- import { requestDeviceCode, awaitApproval, verifyToken, authBase } from "./client.js";
16
+ import { createInterface } from "node:readline/promises";
17
+ import { requestDeviceCode, awaitApproval, verifyToken, authBase, signupStart, signupVerify, } from "./client.js";
10
18
  import { saveCredentials, loadCredentials, clearCredentials } from "./store.js";
11
- // Best-effort open the verification URL in the user's browser (never required — the code is printed too).
19
+ /** One-line prompt on the real TTY. Runs before Ink mounts, so plain readline is safe. */
20
+ async function ask(question) {
21
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
22
+ try {
23
+ return (await rl.question(question)).trim();
24
+ }
25
+ finally {
26
+ rl.close();
27
+ }
28
+ }
29
+ // Best-effort open a URL in the user's browser. Returns whether the launch was dispatched (not whether a
30
+ // window actually appeared — the printed URL is always the real fallback). Crucially, a child-process
31
+ // spawn failure (e.g. ENOENT for a missing opener) surfaces ASYNCHRONOUSLY as an 'error' event, not as a
32
+ // throw — left unhandled it can crash the process, so we attach a no-op handler.
12
33
  function openBrowser(url) {
13
- const cmd = platform() === "darwin" ? "open" : platform() === "win32" ? "start" : "xdg-open";
34
+ const os = platform();
35
+ const cmd = os === "darwin" ? "open" : os === "win32" ? "cmd" : "xdg-open";
36
+ const args = os === "win32" ? ["/c", "start", "", url] : [url];
14
37
  try {
15
- spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
38
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
39
+ child.on("error", () => { });
40
+ child.unref();
41
+ return true;
16
42
  }
17
43
  catch {
18
- /* headless / no browser — the printed URL + code is the fallback */
44
+ return false;
19
45
  }
20
46
  }
21
- async function login(token) {
22
- if (token) {
23
- // PAT path: validate then store. Never store an unverified token.
24
- const account = await verifyToken(token);
25
- if (!account) {
26
- console.error("✗ that token was rejected by " + authBase());
47
+ // --- email + 6-digit code (the smooth default) --------------------------------------
48
+ async function loginEmail(emailArg) {
49
+ const email = (emailArg ?? (await ask("Email: "))).trim();
50
+ if (!email) {
51
+ console.error("✗ no email given");
52
+ return 1;
53
+ }
54
+ const started = await signupStart(email);
55
+ if (!started.ok) {
56
+ if (started.error === "invalid_email")
57
+ console.error(`✗ "${email}" doesn't look like a valid email address`);
58
+ else if (started.error === "too_many_requests")
59
+ console.error("✗ too many codes requested for that address — wait a few minutes, then try again");
60
+ else
61
+ console.error(`✗ couldn't start sign-in via ${authBase()} (${started.error})`);
62
+ return 1;
63
+ }
64
+ console.log(`\n ✓ Sent a 6-digit code to ${email} (valid 10 minutes).`);
65
+ // The server allows up to 5 verify attempts per code before burning it; mirror that here so a typo
66
+ // doesn't force a whole new code round-trip.
67
+ for (let attempt = 1; attempt <= 5; attempt++) {
68
+ const code = await ask(" Enter code: ");
69
+ if (!code) {
70
+ console.error("✗ cancelled");
27
71
  return 1;
28
72
  }
29
- await saveCredentials({ token, user: account.external_id, host: authBase(), issuedAt: Date.now() });
30
- console.log(`✓ signed in as ${account.email ?? account.external_id} (personal access token)`);
31
- return 0;
73
+ const v = await signupVerify(email, code);
74
+ if (v.ok) {
75
+ await saveCredentials({ token: v.token, user: v.account.external_id, host: authBase(), issuedAt: Date.now() });
76
+ console.log(`\n ✓ signed in as ${v.account.email ?? v.account.external_id}\n`);
77
+ return 0;
78
+ }
79
+ if (v.error === "invalid_code") {
80
+ console.error(attempt < 5 ? " ✗ wrong code — try again" : " ✗ wrong code");
81
+ continue;
82
+ }
83
+ if (v.error === "no_pending_code") {
84
+ console.error("✗ that code expired — run `operator auth login` again for a fresh one");
85
+ return 1;
86
+ }
87
+ if (v.error === "too_many_attempts") {
88
+ console.error("✗ too many wrong tries — run `operator auth login` again for a fresh code");
89
+ return 1;
90
+ }
91
+ console.error(`✗ sign-in failed (${v.error})`);
92
+ return 1;
93
+ }
94
+ console.error("✗ too many wrong tries — run `operator auth login` again for a fresh code");
95
+ return 1;
96
+ }
97
+ // --- personal access token paste (CI / headless) ------------------------------------
98
+ async function loginToken(token) {
99
+ const account = await verifyToken(token);
100
+ if (!account) {
101
+ console.error("✗ that token was rejected by " + authBase());
102
+ return 1;
32
103
  }
33
- // Device-grant path.
104
+ await saveCredentials({ token, user: account.external_id, host: authBase(), issuedAt: Date.now() });
105
+ console.log(`✓ signed in as ${account.email ?? account.external_id} (personal access token)`);
106
+ return 0;
107
+ }
108
+ // --- RFC 8628 device grant (browser) ------------------------------------------------
109
+ async function loginDevice() {
34
110
  let dc;
35
111
  try {
36
112
  dc = await requestDeviceCode();
@@ -39,10 +115,13 @@ async function login(token) {
39
115
  console.error(`✗ could not reach ${authBase()}: ${e.message}`);
40
116
  return 1;
41
117
  }
42
- console.log(`\n To sign in, open: ${dc.verification_uri}`);
43
- console.log(` and enter code: \x1b[1m${dc.user_code}\x1b[0m\n`);
44
- console.log(" (opening your browser… waiting for approval — Ctrl-C to cancel)");
45
- openBrowser(dc.verification_uri);
118
+ const sep = dc.verification_uri.includes("?") ? "&" : "?";
119
+ const approveUrl = dc.verification_uri_complete ?? `${dc.verification_uri}${sep}code=${encodeURIComponent(dc.user_code)}`;
120
+ const opened = openBrowser(approveUrl);
121
+ console.log(`\n ${opened ? "Opening your browser" : "Open this URL"} to approve — you must be signed in to AuthGate there, then click Connect:\n`);
122
+ console.log(` \x1b[1m${approveUrl}\x1b[0m\n`);
123
+ console.log(` (verification code \x1b[1m${dc.user_code}\x1b[0m, if the page asks for it)`);
124
+ console.log(` Waiting for approval — Ctrl-C to cancel. Tip: \`operator auth login\` (no --browser) signs in by email instead, no browser needed.`);
46
125
  const ctrl = new AbortController();
47
126
  const onSig = () => ctrl.abort();
48
127
  process.once("SIGINT", onSig);
@@ -61,6 +140,14 @@ async function login(token) {
61
140
  process.off("SIGINT", onSig);
62
141
  }
63
142
  }
143
+ // Default interactive login: offer the smooth email path first, browser as an explicit fallback.
144
+ async function loginDefault() {
145
+ console.log("\n Sign in to Operator.");
146
+ const email = await ask(" Email (or press Enter to sign in via browser): ");
147
+ if (email)
148
+ return loginEmail(email);
149
+ return loginDevice();
150
+ }
64
151
  async function logout() {
65
152
  await clearCredentials();
66
153
  console.log("✓ signed out");
@@ -80,20 +167,30 @@ async function status() {
80
167
  console.log(`signed in as ${account.email ?? account.external_id} · ${creds.host ?? authBase()}`);
81
168
  return 0;
82
169
  }
170
+ function flagValue(rest, flag) {
171
+ const i = rest.indexOf(flag);
172
+ return i >= 0 ? rest[i + 1] : undefined;
173
+ }
83
174
  /** Dispatch `operator auth <sub> [args]`. Returns a process exit code. */
84
175
  export async function runAuth(argv) {
85
176
  const [sub, ...rest] = argv;
86
177
  switch (sub) {
87
178
  case "login": {
88
- const i = rest.indexOf("--token");
89
- const token = i >= 0 ? rest[i + 1] : undefined;
90
- return login(token);
179
+ const token = flagValue(rest, "--token");
180
+ if (token)
181
+ return loginToken(token);
182
+ const email = flagValue(rest, "--email");
183
+ if (email)
184
+ return loginEmail(email);
185
+ if (rest.includes("--browser"))
186
+ return loginDevice();
187
+ return loginDefault();
91
188
  }
92
189
  case "logout": return logout();
93
190
  case "status":
94
191
  case "whoami": return status();
95
192
  default:
96
- console.log("usage: operator auth <login [--token <pat>] | logout | status>");
193
+ console.log("usage: operator auth <login [--email <addr> | --browser | --token <pat>] | logout | status>");
97
194
  return sub ? 1 : 0;
98
195
  }
99
196
  }
@@ -1,16 +1,20 @@
1
+ import { buildBrief, inferType, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, } from "../engine/grandmaster.js";
1
2
  export class BackgroundAgents {
2
3
  makeSession;
3
4
  onChange;
4
5
  onDone;
6
+ modelName;
5
7
  agents = new Map();
6
8
  seq = 0;
7
9
  /** @param makeSession builds a fresh Session for a bg agent (shell pins it to 1M).
8
10
  * @param onChange fired whenever any agent's status changes (shell re-renders the panel).
9
- * @param onDone fired when an agent finishes, with its final answer (shell posts it to the transcript). */
10
- constructor(makeSession, onChange, onDone) {
11
+ * @param onDone fired when an agent finishes, with its final answer (shell posts it to the transcript).
12
+ * @param modelName the model the child runs on, recorded for UI surfacing (grandmaster §5). */
13
+ constructor(makeSession, onChange, onDone, modelName = "aurora-code-1") {
11
14
  this.makeSession = makeSession;
12
15
  this.onChange = onChange;
13
16
  this.onDone = onDone;
17
+ this.modelName = modelName;
14
18
  }
15
19
  list() {
16
20
  return [...this.agents.values()].map((a) => ({ ...a.info }));
@@ -18,34 +22,71 @@ export class BackgroundAgents {
18
22
  /** Spawn a background agent on `task`. Returns its short id (bg1, bg2, …). */
19
23
  spawn(task) {
20
24
  const id = `bg${++this.seq}`;
25
+ const type = inferType(task);
26
+ const brief = buildBrief({ objective: task, type }, process.cwd());
27
+ const lane = routeLane(brief, { type });
21
28
  const label = task.replace(/\s+/g, " ").slice(0, 28);
22
29
  const session = this.makeSession();
23
- const info = { id, label, status: "working", task, round: 0, tokens: 0, startedAt: Date.now() };
30
+ const info = { id, label, status: "working", task, round: 0, tokens: 0, startedAt: Date.now(), model: this.modelName, lane };
24
31
  this.agents.set(id, { info, session });
25
32
  this.onChange();
26
- session
27
- .send(task, {
28
- // Count streamed tokens live (~1 per SSE delta) so the panel shows progress, but DON'T
29
- // re-render per delta — the count is picked up on the next round tick (onToolBatch). This
30
- // keeps a background agent from flooding the shell with re-renders while it streams.
33
+ void this.run(id, session, info, brief, type);
34
+ return id;
35
+ }
36
+ async run(id, session, info, brief, type) {
37
+ let total = 0;
38
+ const hooks = {
31
39
  onDelta: () => { info.tokens = (info.tokens ?? 0) + 1; },
32
40
  onToolBatch: () => { info.round = (info.round ?? 0) + 1; this.onChange(); },
33
- })
34
- .then((r) => {
41
+ };
42
+ try {
43
+ let r = await session.send(brief, hooks);
44
+ total += r.tokens ?? 0;
45
+ let fa = extractFinalAnswer(r.content, type);
46
+ // Mechanism 2: one repair round on a schema failure — feed the error back, re-run just the final step.
47
+ if (!fa.ok && !r.interrupted) {
48
+ const r2 = await session.send(repairPrompt(fa.errors ?? [], type), hooks);
49
+ total += r2.tokens ?? 0;
50
+ const fa2 = extractFinalAnswer(r2.content, type);
51
+ if (fa2.ok) {
52
+ fa = fa2;
53
+ r = r2;
54
+ }
55
+ else {
56
+ info.malformed = true;
57
+ fa = fa2.value ? fa2 : fa;
58
+ r = r2;
59
+ }
60
+ }
61
+ // Mechanism 3: verify-before-done (never on the model's say-so).
62
+ if (fa.ok && fa.value) {
63
+ const v = await verifyFinalAnswer(fa.value, type, process.cwd());
64
+ info.verified = v.verified;
65
+ info.verifyDetail = v.detail;
66
+ }
35
67
  info.status = r.interrupted ? "stopped" : "idle";
36
- if (typeof r.tokens === "number")
37
- info.tokens = r.tokens; // authoritative llama.cpp count
68
+ if (total > 0)
69
+ info.tokens = total; // authoritative llama.cpp count summed across sends
38
70
  info.durationMs = r.durationMs ?? (Date.now() - (info.startedAt ?? Date.now()));
39
71
  this.onChange();
40
- if (!r.interrupted && r.content.trim())
41
- this.onDone(info, r.content);
42
- })
43
- .catch((e) => {
72
+ if (r.interrupted)
73
+ return;
74
+ // The parent sees the structured summary when we have one, tagged with verify/lane state so it can
75
+ // decide whether to trust the child (mechanism 5 is the UI surfacing the same fields).
76
+ const summary = (fa.value && typeof fa.value.summary === "string" && fa.value.summary.trim())
77
+ ? fa.value.summary.trim()
78
+ : (r.content.trim() || "(no output)");
79
+ const tag = info.malformed ? " ⚠ malformed final_answer (unstructured)"
80
+ : info.verified === false ? ` ⚠ unverified: ${info.verifyDetail}`
81
+ : info.verified ? " ✓ verified"
82
+ : "";
83
+ this.onDone(info, `${summary}${tag}`);
84
+ }
85
+ catch (e) {
44
86
  info.status = "stopped";
45
87
  this.onChange();
46
88
  this.onDone(info, `[${id} error: ${e instanceof Error ? e.message : String(e)}]`);
47
- });
48
- return id;
89
+ }
49
90
  }
50
91
  /** Stop a running agent (interrupts its turn). Returns false if the id is unknown. */
51
92
  stop(id) {
package/dist/cli.js CHANGED
@@ -15,11 +15,32 @@ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import { homedir } from "node:os";
17
17
  import { createHash } from "node:crypto";
18
- const VERSION = "0.0.7";
18
+ const VERSION = "0.1.17";
19
19
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
20
20
  const settings = loadSettings();
21
21
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
22
22
  process.env.KODE_SANDBOX = settings.sandbox.mode;
23
+ // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
24
+ // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
25
+ // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
26
+ // a bg session has no approver, so denial is the only safe posture (no silent computer use). When
27
+ // disabled the tools are never registered at all (zero surface). Only cli.tsx (node) touches this, so the
28
+ // mobile bundle never sees these tools.
29
+ let computerAskRules = {};
30
+ let computerDenyRules = {};
31
+ if (settings.computer.enabled) {
32
+ const { COMPUTER_TOOLS, COMPUTER_TOOL_NAMES, setComputerEnabled } = await import("./tools/computer.js");
33
+ const { registry } = await import("./tools/registry.js");
34
+ setComputerEnabled(true);
35
+ for (const t of COMPUTER_TOOLS)
36
+ registry.set(t.name, t);
37
+ computerAskRules = Object.fromEntries(COMPUTER_TOOL_NAMES.map((n) => [n, "ask"]));
38
+ computerDenyRules = Object.fromEntries(COMPUTER_TOOL_NAMES.map((n) => [n, "deny"]));
39
+ }
40
+ // Foreground policy = the owner's settings with computer tools forced to "ask". When computer control is
41
+ // off, computerAskRules is empty, so this is behaviorally identical to settings.permissions (an empty
42
+ // rules object keeps a "bypass" policy inert — zero overhead).
43
+ const fgPermissions = { ...settings.permissions, rules: { ...settings.permissions.rules, ...computerAskRules } };
23
44
  // Session persistence: the conversation is auto-saved every turn and reloaded by `operator --resume`.
24
45
  // It lives in a central per-workspace state dir — NEVER in the working directory, where it would be
25
46
  // grepped back into the model's own context (self-poisoning → runaway ctx growth), committed by
@@ -46,7 +67,22 @@ function buildRouter() {
46
67
  eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
47
68
  return new AuroraRouter(eps);
48
69
  }
49
- const SYSTEM_PROMPT = settings.systemPrompt ??
70
+ // Project context: auto-load a per-repo instructions file (AGENTS.md / CLAUDE.md / .operator/AGENTS.md)
71
+ // from the working dir and append it to the system prompt, so Operator picks up house rules, conventions
72
+ // and build commands the way Claude Code / Codex do. First match wins; capped so a huge file can't blow
73
+ // the prompt. Best-effort — a missing file is normal.
74
+ function loadProjectContext() {
75
+ for (const name of ["AGENTS.md", "CLAUDE.md", ".operator/AGENTS.md", "OPERATOR.md"]) {
76
+ try {
77
+ const t = readFileSync(join(process.cwd(), name), "utf8").trim();
78
+ if (t)
79
+ return `\n\n## Project context (${name}, auto-loaded from the working directory)\n${t.slice(0, 8000)}`;
80
+ }
81
+ catch { /* not present — try the next */ }
82
+ }
83
+ return "";
84
+ }
85
+ const SYSTEM_PROMPT = (settings.systemPrompt ??
50
86
  `You are Operator, a terse local terminal coding agent. Use your tools to inspect and edit the ` +
51
87
  `workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
52
88
  `\nContext window: 1,048,576 tokens (1M) — you run on the Aurora model served locally with a full ` +
@@ -55,7 +91,16 @@ const SYSTEM_PROMPT = settings.systemPrompt ??
55
91
  `build) call spawn_agent with a fully self-contained instruction — it runs on another Aurora session ` +
56
92
  `in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
57
93
  `live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
58
- `spawn many at once — they all share this one model.`;
94
+ `spawn many at once — they all share this one model.` +
95
+ `\n## Finding things\nWhen asked to find files, work, a project, or past output NOT in the current ` +
96
+ `working directory, do NOT give up after a workspace grep/memory_search. Actually find it: (1) run ` +
97
+ `ls ~ first to see the REAL top-level folders — projects often live in non-obvious ones (e.g. ~/Axwell), ` +
98
+ `not just ~/Projects; (2) then search with a BOUNDED, fast command and a GENEROUS timeout so it is ` +
99
+ `never killed mid-search — shell_exec {"command":"find ~ -maxdepth 4 -iname \\"*name*\\" 2>/dev/null | ` +
100
+ `head -80","timeout_ms":60000}. Do NOT use an unbounded find / (too slow, it times out). Also check ` +
101
+ `~/.axe/repos and any folder ls ~ revealed, and widen the pattern (a repo may be named slightly ` +
102
+ `differently). Only report not-found after this real search, and say exactly where you looked.`) +
103
+ loadProjectContext();
59
104
  const MAX_BG = 4; // concurrent background sub-agents — all share the single Aurora 1M endpoint, so cap fan-out
60
105
  const HELP = [
61
106
  "commands:",
@@ -76,6 +121,11 @@ const HELP = [
76
121
  let ID = 0;
77
122
  const nextId = () => `e${++ID}`;
78
123
  const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
124
+ // Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
125
+ // tokens past 1000. One helper so the live line and the settled metric read identically.
126
+ const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
127
+ const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k tokens` : `${n} token${n === 1 ? "" : "s"}`);
128
+ const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`;
79
129
  const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim());
80
130
  function Root() {
81
131
  const { exit } = useApp();
@@ -92,6 +142,19 @@ function Root() {
92
142
  // setLive re-render that already happens, so there's no performance cost and no animation timer.
93
143
  const [bgAgents, setBgAgents] = useState([]);
94
144
  const [authUser, setAuthUser] = useState(""); // signed-in identity for the status rule
145
+ const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
146
+ const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
147
+ // phase where no content tokens stream — that was the "timer stuck" bug (Ink only re-renders on deltas).
148
+ // Tool-approval bridge: when the permission policy returns "ask", session.approve(name,args) parks the
149
+ // decision here and <ApprovalPrompt> renders it; the keystroke resolves the promise. "allow always"
150
+ // adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
151
+ const [approval, setApproval] = useState(null);
152
+ const alwaysAllowRef = useRef(new Set());
153
+ const approveFn = useCallback((name, args) => {
154
+ if (alwaysAllowRef.current.has(name))
155
+ return Promise.resolve(true);
156
+ return new Promise((resolve) => setApproval({ name, args, resolve }));
157
+ }, []);
95
158
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
96
159
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
97
160
  // only, no network fan-out at session start). Background agents stay local-only + lean.
@@ -103,7 +166,8 @@ function Root() {
103
166
  maxTokens: settings.maxTokens,
104
167
  temperature: settings.temperature,
105
168
  recall: settings.memory.recall,
106
- permissions: settings.permissions, // default bypass — zero gates until turned on
169
+ permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
170
+ approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
107
171
  telemetry: settings.telemetry, // local-only metrics by default
108
172
  // Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
109
173
  // sub-agent can't spawn more (no fork bombs). Cap at MAX_BG — all sub-agents share the one Aurora
@@ -131,13 +195,17 @@ function Root() {
131
195
  ]),
132
196
  maxTokens: settings.maxTokens,
133
197
  temperature: settings.temperature,
198
+ // Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
199
+ // denied outright. (No-op when computer control is off.) Everything else runs as normal.
200
+ permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
134
201
  }), () => setBgAgents(bgRef.current.list()), (agent, result) => {
135
202
  setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
136
203
  setBgAgents(bgRef.current.list());
137
- });
204
+ }, settings.endpoints.aurora.model);
138
205
  }
139
206
  const bg = bgRef.current;
140
207
  const liveText = useRef("");
208
+ const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
141
209
  const queued = useRef("");
142
210
  const statusRef = useRef("idle");
143
211
  const setStat = (s) => { statusRef.current = s; setStatus(s); };
@@ -190,8 +258,11 @@ function Root() {
190
258
  const sendTurn = useCallback(async (text) => {
191
259
  push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
192
260
  liveText.current = "";
261
+ liveReasoning.current = "";
193
262
  setLive(null);
194
263
  setLiveTok(0); // reset the live counter at the start of the turn
264
+ turnStartRef.current = Date.now();
265
+ setElapsed(0);
195
266
  setStat("thinking");
196
267
  try {
197
268
  const outcome = await session.send(text, {
@@ -200,7 +271,17 @@ function Root() {
200
271
  liveText.current += chunk;
201
272
  setLiveTok((t) => t + 1); // ≈1 token per streamed delta — batched with setLive, no extra render
202
273
  setStat("streaming");
203
- setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current } });
274
+ setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current || undefined } });
275
+ },
276
+ onReasoning: (chunk) => {
277
+ // Thinking streams before/between content — accumulate it and show it dimmed in the live entry
278
+ // (renderEntry renders `reasoning` above the answer, dimColor). Distinct from onDelta so the
279
+ // thought process reads at lower opacity than the real answer, per the requested look.
280
+ liveReasoning.current += chunk;
281
+ setLiveTok((t) => t + 1); // reasoning tokens ARE generated tokens — count them so the live
282
+ // counter + tok/s keep moving during a long thinking phase (they were frozen before content).
283
+ setStat("thinking");
284
+ setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current } });
204
285
  },
205
286
  onAutoContinue: (round) => {
206
287
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
@@ -222,6 +303,7 @@ function Root() {
222
303
  push({ kind: "tool", step });
223
304
  }
224
305
  liveText.current = "";
306
+ liveReasoning.current = "";
225
307
  setLive(null);
226
308
  setStat("thinking");
227
309
  },
@@ -230,15 +312,21 @@ function Root() {
230
312
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
231
313
  }
232
314
  else if (outcome.content.trim()) {
233
- const reasoning = outcome.stopReason === "repetition" ? "(output truncated — loop detected)" : undefined;
315
+ // Keep the final answer's thinking (dim, above the answer), plus a dim note when generation was
316
+ // cut short — loop breaker, output-limit truncation, or content filter — so a short/odd answer
317
+ // is never a mystery.
318
+ const stopNote = outcome.stopReason === "repetition" ? "(output truncated — loop detected)"
319
+ : outcome.stopReason === "length" ? "(truncated at the output limit — ask me to continue)"
320
+ : outcome.stopReason === "content_filter" ? "(the model stopped — content filter)"
321
+ : undefined;
322
+ const reasoning = [liveReasoning.current.trim(), stopNote].filter(Boolean).join("\n") || undefined;
234
323
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
235
324
  }
236
325
  // Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
237
326
  if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
238
327
  const tok = outcome.tokens ?? 0;
239
328
  const secs = (outcome.durationMs ?? 0) / 1000;
240
- const tps = outcome.genMs && outcome.genMs > 0 ? tok / (outcome.genMs / 1000) : secs > 0 ? tok / secs : 0;
241
- setMetrics(`${tok} tok · ${tps >= 10 ? Math.round(tps) : tps.toFixed(1)} tok/s · ${secs.toFixed(1)}s`);
329
+ setMetrics(fmtMeta(secs, tok));
242
330
  }
243
331
  }
244
332
  catch (e) {
@@ -386,18 +474,41 @@ function Root() {
386
474
  } // Ctrl-C / ESC at rest quits
387
475
  session.interrupt();
388
476
  }, [exit]);
477
+ // Live clock: a lightweight interval ticks `elapsed` while a turn is active, so the timer advances
478
+ // even through a long reasoning phase that streams no content tokens (the "timer stuck" bug — Ink
479
+ // only re-renders on deltas otherwise). Torn down the moment we go idle. MUST be declared with the
480
+ // other hooks, ABOVE the boot early-returns below — otherwise it's skipped on the first render and the
481
+ // hook count changes when boot flips to "ready" ("Rendered more hooks than during the previous render").
482
+ useEffect(() => {
483
+ const active = status === "thinking" || status === "streaming" || status === "executing" || status === "recovering";
484
+ if (!active)
485
+ return;
486
+ const id = setInterval(() => setElapsed((Date.now() - turnStartRef.current) / 1000), 250);
487
+ return () => clearInterval(id);
488
+ }, [status]);
389
489
  if (boot === "checking")
390
490
  return _jsx(Text, { dimColor: true, children: "connecting to Aurora\u2026" });
391
491
  if (boot === "down") {
392
492
  return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Aurora on the configured endpoint." }), _jsx(Text, { dimColor: true, children: "Start Aurora (llama-server on :8097) and relaunch." })] }));
393
493
  }
394
- // While tokens are streaming, show a LIVE animated count in the status rule (the braille glyph advances
395
- // and the number ticks up per token); when idle, show the last turn's final "N tok · X tok/s · Ys".
494
+ // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
495
+ // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
496
+ // turn's numbers mid-turn — the clock always moves.
396
497
  const SPIN = "⣾⣽⣻⢿⡿⣟⣯⣷";
397
- const liveMetrics = (status === "streaming" || status === "thinking") && liveTok > 0
398
- ? `${SPIN[liveTok % SPIN.length]} ${liveTok} tok`
498
+ const active = status === "streaming" || status === "thinking" || status === "executing" || status === "recovering";
499
+ const liveMetrics = active
500
+ ? `${SPIN[Math.floor(elapsed * 4) % SPIN.length]} ${fmtMeta(elapsed, liveTok)}`
399
501
  : metrics;
400
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, authUser: authUser, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt }));
502
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, authUser: authUser, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, onApprovalDecide: (allow, always) => {
503
+ setApproval((cur) => {
504
+ if (cur) {
505
+ if (allow && always)
506
+ alwaysAllowRef.current.add(cur.name);
507
+ cur.resolve(allow);
508
+ }
509
+ return null;
510
+ });
511
+ } }));
401
512
  }
402
513
  // `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
403
514
  // headless (CI / SSH). Anything else falls through to the interactive REPL below.
@@ -24,6 +24,7 @@ const DEFAULTS = {
24
24
  permissions: { mode: "bypass" }, // zero gates by default — enforcement is opt-in
25
25
  telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
26
26
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
27
+ computer: { enabled: false }, // computer control OFF by default; enable with KODE_COMPUTER=1 or settings.json
27
28
  };
28
29
  function settingsPath() {
29
30
  return process.env.KODE_TSI_SETTINGS ?? join(homedir(), ".axe", "operator", "settings.json");
@@ -54,7 +55,7 @@ function readSettingsFile(path) {
54
55
  /** Fold env vars over the file+default merge — the top layer of the precedence stack. Only an env
55
56
  * var that's actually set overrides; an unset one leaves the file/default value alone. */
56
57
  function applyEnv(s) {
57
- const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox } };
58
+ const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox }, computer: { ...s.computer } };
58
59
  if (process.env.KODE_MODEL)
59
60
  out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, model: process.env.KODE_MODEL } }; // AI-agnostic quick-swap (keeps failover)
60
61
  const base = process.env.KODE_AURORA ?? process.env.KODE_1M; // KODE_1M kept as a back-compat alias for the base override
@@ -72,6 +73,8 @@ function applyEnv(s) {
72
73
  const sb = process.env.KODE_SANDBOX;
73
74
  if (sb === "off" || sb === "workspace" || sb === "strict")
74
75
  out.sandbox = { mode: sb };
76
+ if (process.env.KODE_COMPUTER === "1")
77
+ out.computer = { enabled: true };
75
78
  return out;
76
79
  }
77
80
  /** Load operator settings: built-in defaults <- ~/.axe/operator/settings.json (override path via