@0perator/operator 0.0.7 → 0.1.21
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.
- package/dist/auth/client.js +17 -0
- package/dist/auth/commands.js +124 -27
- package/dist/background/index.js +59 -18
- package/dist/cli.js +129 -14
- package/dist/config/settings.js +4 -1
- package/dist/engine/agent.js +24 -6
- package/dist/engine/aurora.js +20 -4
- package/dist/engine/grandmaster.js +172 -0
- package/dist/memory/index.js +0 -0
- package/dist/session.js +1 -0
- package/dist/tools/computer.js +279 -0
- package/dist/tools/registry.js +215 -11
- package/dist/tools/sandbox.js +129 -13
- package/dist/ui/App.js +3 -2
- package/dist/ui/ApprovalPrompt.js +45 -0
- package/dist/ui/AuthScreen.js +2 -2
- package/dist/ui/BgPanel.js +12 -1
- package/dist/ui/Composer.js +11 -2
- package/dist/ui/Markdown.js +76 -0
- package/dist/ui/Masthead.js +78 -0
- package/dist/ui/StatusRule.js +12 -3
- package/dist/ui/Transcript.js +8 -3
- package/dist/update.js +16 -4
- package/package.json +2 -1
package/dist/auth/client.js
CHANGED
|
@@ -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
|
+
}
|
package/dist/auth/commands.js
CHANGED
|
@@ -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
|
|
4
|
-
// login --
|
|
5
|
-
//
|
|
6
|
-
//
|
|
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 {
|
|
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
|
-
|
|
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
|
|
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,
|
|
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
|
-
|
|
44
|
+
return false;
|
|
19
45
|
}
|
|
20
46
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
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
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
|
89
|
-
|
|
90
|
-
|
|
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
|
}
|
package/dist/background/index.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
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 (
|
|
37
|
-
info.tokens =
|
|
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 (
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
@@ -7,6 +7,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
7
7
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
8
8
|
import { render, Box, Text, useApp } from "ink";
|
|
9
9
|
import { App } from "./ui/index.js";
|
|
10
|
+
import { mastheadLines } from "./ui/Masthead.js";
|
|
10
11
|
import { Session } from "./session.js";
|
|
11
12
|
import { AuroraRouter } from "./router/router.js";
|
|
12
13
|
import { BackgroundAgents } from "./background/index.js";
|
|
@@ -15,11 +16,32 @@ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
|
15
16
|
import { join } from "node:path";
|
|
16
17
|
import { homedir } from "node:os";
|
|
17
18
|
import { createHash } from "node:crypto";
|
|
18
|
-
const VERSION = "0.
|
|
19
|
+
const VERSION = "0.1.21";
|
|
19
20
|
// operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
|
|
20
21
|
const settings = loadSettings();
|
|
21
22
|
// Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
|
|
22
23
|
process.env.KODE_SANDBOX = settings.sandbox.mode;
|
|
24
|
+
// Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
|
|
25
|
+
// registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
|
|
26
|
+
// action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
|
|
27
|
+
// a bg session has no approver, so denial is the only safe posture (no silent computer use). When
|
|
28
|
+
// disabled the tools are never registered at all (zero surface). Only cli.tsx (node) touches this, so the
|
|
29
|
+
// mobile bundle never sees these tools.
|
|
30
|
+
let computerAskRules = {};
|
|
31
|
+
let computerDenyRules = {};
|
|
32
|
+
if (settings.computer.enabled) {
|
|
33
|
+
const { COMPUTER_TOOLS, COMPUTER_TOOL_NAMES, setComputerEnabled } = await import("./tools/computer.js");
|
|
34
|
+
const { registry } = await import("./tools/registry.js");
|
|
35
|
+
setComputerEnabled(true);
|
|
36
|
+
for (const t of COMPUTER_TOOLS)
|
|
37
|
+
registry.set(t.name, t);
|
|
38
|
+
computerAskRules = Object.fromEntries(COMPUTER_TOOL_NAMES.map((n) => [n, "ask"]));
|
|
39
|
+
computerDenyRules = Object.fromEntries(COMPUTER_TOOL_NAMES.map((n) => [n, "deny"]));
|
|
40
|
+
}
|
|
41
|
+
// Foreground policy = the owner's settings with computer tools forced to "ask". When computer control is
|
|
42
|
+
// off, computerAskRules is empty, so this is behaviorally identical to settings.permissions (an empty
|
|
43
|
+
// rules object keeps a "bypass" policy inert — zero overhead).
|
|
44
|
+
const fgPermissions = { ...settings.permissions, rules: { ...settings.permissions.rules, ...computerAskRules } };
|
|
23
45
|
// Session persistence: the conversation is auto-saved every turn and reloaded by `operator --resume`.
|
|
24
46
|
// It lives in a central per-workspace state dir — NEVER in the working directory, where it would be
|
|
25
47
|
// grepped back into the model's own context (self-poisoning → runaway ctx growth), committed by
|
|
@@ -46,7 +68,22 @@ function buildRouter() {
|
|
|
46
68
|
eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
|
|
47
69
|
return new AuroraRouter(eps);
|
|
48
70
|
}
|
|
49
|
-
|
|
71
|
+
// Project context: auto-load a per-repo instructions file (AGENTS.md / CLAUDE.md / .operator/AGENTS.md)
|
|
72
|
+
// from the working dir and append it to the system prompt, so Operator picks up house rules, conventions
|
|
73
|
+
// and build commands the way Claude Code / Codex do. First match wins; capped so a huge file can't blow
|
|
74
|
+
// the prompt. Best-effort — a missing file is normal.
|
|
75
|
+
function loadProjectContext() {
|
|
76
|
+
for (const name of ["AGENTS.md", "CLAUDE.md", ".operator/AGENTS.md", "OPERATOR.md"]) {
|
|
77
|
+
try {
|
|
78
|
+
const t = readFileSync(join(process.cwd(), name), "utf8").trim();
|
|
79
|
+
if (t)
|
|
80
|
+
return `\n\n## Project context (${name}, auto-loaded from the working directory)\n${t.slice(0, 8000)}`;
|
|
81
|
+
}
|
|
82
|
+
catch { /* not present — try the next */ }
|
|
83
|
+
}
|
|
84
|
+
return "";
|
|
85
|
+
}
|
|
86
|
+
const SYSTEM_PROMPT = (settings.systemPrompt ??
|
|
50
87
|
`You are Operator, a terse local terminal coding agent. Use your tools to inspect and edit the ` +
|
|
51
88
|
`workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
|
|
52
89
|
`\nContext window: 1,048,576 tokens (1M) — you run on the Aurora model served locally with a full ` +
|
|
@@ -55,7 +92,16 @@ const SYSTEM_PROMPT = settings.systemPrompt ??
|
|
|
55
92
|
`build) call spawn_agent with a fully self-contained instruction — it runs on another Aurora session ` +
|
|
56
93
|
`in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
|
|
57
94
|
`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
|
|
95
|
+
`spawn many at once — they all share this one model.` +
|
|
96
|
+
`\n## Finding things\nWhen asked to find files, work, a project, or past output NOT in the current ` +
|
|
97
|
+
`working directory, do NOT give up after a workspace grep/memory_search. Actually find it: (1) run ` +
|
|
98
|
+
`ls ~ first to see the REAL top-level folders — projects often live in non-obvious ones (e.g. ~/Axwell), ` +
|
|
99
|
+
`not just ~/Projects; (2) then search with a BOUNDED, fast command and a GENEROUS timeout so it is ` +
|
|
100
|
+
`never killed mid-search — shell_exec {"command":"find ~ -maxdepth 4 -iname \\"*name*\\" 2>/dev/null | ` +
|
|
101
|
+
`head -80","timeout_ms":60000}. Do NOT use an unbounded find / (too slow, it times out). Also check ` +
|
|
102
|
+
`~/.axe/repos and any folder ls ~ revealed, and widen the pattern (a repo may be named slightly ` +
|
|
103
|
+
`differently). Only report not-found after this real search, and say exactly where you looked.`) +
|
|
104
|
+
loadProjectContext();
|
|
59
105
|
const MAX_BG = 4; // concurrent background sub-agents — all share the single Aurora 1M endpoint, so cap fan-out
|
|
60
106
|
const HELP = [
|
|
61
107
|
"commands:",
|
|
@@ -76,6 +122,11 @@ const HELP = [
|
|
|
76
122
|
let ID = 0;
|
|
77
123
|
const nextId = () => `e${++ID}`;
|
|
78
124
|
const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
|
|
125
|
+
// Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
|
|
126
|
+
// tokens past 1000. One helper so the live line and the settled metric read identically.
|
|
127
|
+
const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
|
|
128
|
+
const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k tokens` : `${n} token${n === 1 ? "" : "s"}`);
|
|
129
|
+
const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`;
|
|
79
130
|
const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim());
|
|
80
131
|
function Root() {
|
|
81
132
|
const { exit } = useApp();
|
|
@@ -92,6 +143,19 @@ function Root() {
|
|
|
92
143
|
// setLive re-render that already happens, so there's no performance cost and no animation timer.
|
|
93
144
|
const [bgAgents, setBgAgents] = useState([]);
|
|
94
145
|
const [authUser, setAuthUser] = useState(""); // signed-in identity for the status rule
|
|
146
|
+
const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
|
|
147
|
+
const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
|
|
148
|
+
// phase where no content tokens stream — that was the "timer stuck" bug (Ink only re-renders on deltas).
|
|
149
|
+
// Tool-approval bridge: when the permission policy returns "ask", session.approve(name,args) parks the
|
|
150
|
+
// decision here and <ApprovalPrompt> renders it; the keystroke resolves the promise. "allow always"
|
|
151
|
+
// adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
|
|
152
|
+
const [approval, setApproval] = useState(null);
|
|
153
|
+
const alwaysAllowRef = useRef(new Set());
|
|
154
|
+
const approveFn = useCallback((name, args) => {
|
|
155
|
+
if (alwaysAllowRef.current.has(name))
|
|
156
|
+
return Promise.resolve(true);
|
|
157
|
+
return new Promise((resolve) => setApproval({ name, args, resolve }));
|
|
158
|
+
}, []);
|
|
95
159
|
const sessionRef = useRef(null); // lazy — never reconstruct on re-render
|
|
96
160
|
// MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
|
|
97
161
|
// only, no network fan-out at session start). Background agents stay local-only + lean.
|
|
@@ -103,7 +167,8 @@ function Root() {
|
|
|
103
167
|
maxTokens: settings.maxTokens,
|
|
104
168
|
temperature: settings.temperature,
|
|
105
169
|
recall: settings.memory.recall,
|
|
106
|
-
permissions:
|
|
170
|
+
permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
|
|
171
|
+
approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
|
|
107
172
|
telemetry: settings.telemetry, // local-only metrics by default
|
|
108
173
|
// Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
|
|
109
174
|
// sub-agent can't spawn more (no fork bombs). Cap at MAX_BG — all sub-agents share the one Aurora
|
|
@@ -131,13 +196,17 @@ function Root() {
|
|
|
131
196
|
]),
|
|
132
197
|
maxTokens: settings.maxTokens,
|
|
133
198
|
temperature: settings.temperature,
|
|
199
|
+
// Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
|
|
200
|
+
// denied outright. (No-op when computer control is off.) Everything else runs as normal.
|
|
201
|
+
permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
|
|
134
202
|
}), () => setBgAgents(bgRef.current.list()), (agent, result) => {
|
|
135
203
|
setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
|
|
136
204
|
setBgAgents(bgRef.current.list());
|
|
137
|
-
});
|
|
205
|
+
}, settings.endpoints.aurora.model);
|
|
138
206
|
}
|
|
139
207
|
const bg = bgRef.current;
|
|
140
208
|
const liveText = useRef("");
|
|
209
|
+
const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
|
|
141
210
|
const queued = useRef("");
|
|
142
211
|
const statusRef = useRef("idle");
|
|
143
212
|
const setStat = (s) => { statusRef.current = s; setStatus(s); };
|
|
@@ -190,8 +259,11 @@ function Root() {
|
|
|
190
259
|
const sendTurn = useCallback(async (text) => {
|
|
191
260
|
push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
|
|
192
261
|
liveText.current = "";
|
|
262
|
+
liveReasoning.current = "";
|
|
193
263
|
setLive(null);
|
|
194
264
|
setLiveTok(0); // reset the live counter at the start of the turn
|
|
265
|
+
turnStartRef.current = Date.now();
|
|
266
|
+
setElapsed(0);
|
|
195
267
|
setStat("thinking");
|
|
196
268
|
try {
|
|
197
269
|
const outcome = await session.send(text, {
|
|
@@ -200,7 +272,17 @@ function Root() {
|
|
|
200
272
|
liveText.current += chunk;
|
|
201
273
|
setLiveTok((t) => t + 1); // ≈1 token per streamed delta — batched with setLive, no extra render
|
|
202
274
|
setStat("streaming");
|
|
203
|
-
setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current } });
|
|
275
|
+
setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current || undefined } });
|
|
276
|
+
},
|
|
277
|
+
onReasoning: (chunk) => {
|
|
278
|
+
// Thinking streams before/between content — accumulate it and show it dimmed in the live entry
|
|
279
|
+
// (renderEntry renders `reasoning` above the answer, dimColor). Distinct from onDelta so the
|
|
280
|
+
// thought process reads at lower opacity than the real answer, per the requested look.
|
|
281
|
+
liveReasoning.current += chunk;
|
|
282
|
+
setLiveTok((t) => t + 1); // reasoning tokens ARE generated tokens — count them so the live
|
|
283
|
+
// counter + tok/s keep moving during a long thinking phase (they were frozen before content).
|
|
284
|
+
setStat("thinking");
|
|
285
|
+
setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current } });
|
|
204
286
|
},
|
|
205
287
|
onAutoContinue: (round) => {
|
|
206
288
|
push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
|
|
@@ -222,6 +304,7 @@ function Root() {
|
|
|
222
304
|
push({ kind: "tool", step });
|
|
223
305
|
}
|
|
224
306
|
liveText.current = "";
|
|
307
|
+
liveReasoning.current = "";
|
|
225
308
|
setLive(null);
|
|
226
309
|
setStat("thinking");
|
|
227
310
|
},
|
|
@@ -230,15 +313,21 @@ function Root() {
|
|
|
230
313
|
push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
|
|
231
314
|
}
|
|
232
315
|
else if (outcome.content.trim()) {
|
|
233
|
-
|
|
316
|
+
// Keep the final answer's thinking (dim, above the answer), plus a dim note when generation was
|
|
317
|
+
// cut short — loop breaker, output-limit truncation, or content filter — so a short/odd answer
|
|
318
|
+
// is never a mystery.
|
|
319
|
+
const stopNote = outcome.stopReason === "repetition" ? "(output truncated — loop detected)"
|
|
320
|
+
: outcome.stopReason === "length" ? "(truncated at the output limit — ask me to continue)"
|
|
321
|
+
: outcome.stopReason === "content_filter" ? "(the model stopped — content filter)"
|
|
322
|
+
: undefined;
|
|
323
|
+
const reasoning = [liveReasoning.current.trim(), stopNote].filter(Boolean).join("\n") || undefined;
|
|
234
324
|
push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
|
|
235
325
|
}
|
|
236
326
|
// Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
|
|
237
327
|
if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
|
|
238
328
|
const tok = outcome.tokens ?? 0;
|
|
239
329
|
const secs = (outcome.durationMs ?? 0) / 1000;
|
|
240
|
-
|
|
241
|
-
setMetrics(`${tok} tok · ${tps >= 10 ? Math.round(tps) : tps.toFixed(1)} tok/s · ${secs.toFixed(1)}s`);
|
|
330
|
+
setMetrics(fmtMeta(secs, tok));
|
|
242
331
|
}
|
|
243
332
|
}
|
|
244
333
|
catch (e) {
|
|
@@ -386,18 +475,41 @@ function Root() {
|
|
|
386
475
|
} // Ctrl-C / ESC at rest quits
|
|
387
476
|
session.interrupt();
|
|
388
477
|
}, [exit]);
|
|
478
|
+
// Live clock: a lightweight interval ticks `elapsed` while a turn is active, so the timer advances
|
|
479
|
+
// even through a long reasoning phase that streams no content tokens (the "timer stuck" bug — Ink
|
|
480
|
+
// only re-renders on deltas otherwise). Torn down the moment we go idle. MUST be declared with the
|
|
481
|
+
// other hooks, ABOVE the boot early-returns below — otherwise it's skipped on the first render and the
|
|
482
|
+
// hook count changes when boot flips to "ready" ("Rendered more hooks than during the previous render").
|
|
483
|
+
useEffect(() => {
|
|
484
|
+
const active = status === "thinking" || status === "streaming" || status === "executing" || status === "recovering";
|
|
485
|
+
if (!active)
|
|
486
|
+
return;
|
|
487
|
+
const id = setInterval(() => setElapsed((Date.now() - turnStartRef.current) / 1000), 250);
|
|
488
|
+
return () => clearInterval(id);
|
|
489
|
+
}, [status]);
|
|
389
490
|
if (boot === "checking")
|
|
390
491
|
return _jsx(Text, { dimColor: true, children: "connecting to Aurora\u2026" });
|
|
391
492
|
if (boot === "down") {
|
|
392
493
|
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
494
|
}
|
|
394
|
-
// While
|
|
395
|
-
//
|
|
495
|
+
// While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
|
|
496
|
+
// seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
|
|
497
|
+
// turn's numbers mid-turn — the clock always moves.
|
|
396
498
|
const SPIN = "⣾⣽⣻⢿⡿⣟⣯⣷";
|
|
397
|
-
const
|
|
398
|
-
|
|
499
|
+
const active = status === "streaming" || status === "thinking" || status === "executing" || status === "recovering";
|
|
500
|
+
const liveMetrics = active
|
|
501
|
+
? `${SPIN[Math.floor(elapsed * 4) % SPIN.length]} ${fmtMeta(elapsed, liveTok)}`
|
|
399
502
|
: 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
|
|
503
|
+
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) => {
|
|
504
|
+
setApproval((cur) => {
|
|
505
|
+
if (cur) {
|
|
506
|
+
if (allow && always)
|
|
507
|
+
alwaysAllowRef.current.add(cur.name);
|
|
508
|
+
cur.resolve(allow);
|
|
509
|
+
}
|
|
510
|
+
return null;
|
|
511
|
+
});
|
|
512
|
+
} }));
|
|
401
513
|
}
|
|
402
514
|
// `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
|
|
403
515
|
// headless (CI / SSH). Anything else falls through to the interactive REPL below.
|
|
@@ -416,4 +528,7 @@ if (!process.stdin.isTTY) {
|
|
|
416
528
|
process.stderr.write("kode-tsi needs an interactive terminal (TTY). For scripted turns, import { Session } from kode-tsi.\n");
|
|
417
529
|
process.exit(1);
|
|
418
530
|
}
|
|
531
|
+
// Boot masthead (design #29) — printed ONCE to stdout before Ink mounts, so the big gradient wordmark
|
|
532
|
+
// lives in permanent scrollback and never enters Ink's dynamic-frame redraw (reflow-safe by construction).
|
|
533
|
+
process.stdout.write(mastheadLines(`aurora · 1M · v${VERSION}`).join("\n") + "\n");
|
|
419
534
|
render(_jsx(Root, {}));
|
package/dist/config/settings.js
CHANGED
|
@@ -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
|