@0perator/operator 0.0.6
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/README.md +73 -0
- package/dist/auth/client.js +94 -0
- package/dist/auth/commands.js +99 -0
- package/dist/auth/store.js +99 -0
- package/dist/background/index.js +64 -0
- package/dist/cli.js +407 -0
- package/dist/config/settings.js +85 -0
- package/dist/engine/agent.js +232 -0
- package/dist/engine/aurora.js +213 -0
- package/dist/engine/compaction.js +111 -0
- package/dist/engine/contract.js +8 -0
- package/dist/engine/messages.js +85 -0
- package/dist/engine/router-adapter.js +29 -0
- package/dist/engine/selfheal.js +46 -0
- package/dist/engine/toolcalls.js +164 -0
- package/dist/index.browser.js +22 -0
- package/dist/index.js +23 -0
- package/dist/mcp/client.js +95 -0
- package/dist/mcp/config.js +73 -0
- package/dist/mcp/index.js +101 -0
- package/dist/mcp/stdio.js +149 -0
- package/dist/memory/index.js +0 -0
- package/dist/observability/index.js +60 -0
- package/dist/permissions/audit.js +50 -0
- package/dist/permissions/index.js +48 -0
- package/dist/permissions/policy.js +54 -0
- package/dist/router/router.js +94 -0
- package/dist/session.js +265 -0
- package/dist/tools/executor.js +0 -0
- package/dist/tools/registry.js +380 -0
- package/dist/tools/sandbox.js +90 -0
- package/dist/ui/ActivitySpinner.js +48 -0
- package/dist/ui/App.js +16 -0
- package/dist/ui/AuthScreen.js +17 -0
- package/dist/ui/BgPanel.js +24 -0
- package/dist/ui/Composer.js +119 -0
- package/dist/ui/Header.js +22 -0
- package/dist/ui/StatusRule.js +11 -0
- package/dist/ui/ThinkingSpinner.js +61 -0
- package/dist/ui/ToolStep.js +32 -0
- package/dist/ui/Transcript.js +22 -0
- package/dist/ui/format.js +6 -0
- package/dist/ui/index.js +9 -0
- package/dist/ui/types.js +3 -0
- package/dist/ui/useInputHistory.js +97 -0
- package/dist/update.js +57 -0
- package/package.json +47 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
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 { Session } from "./session.js";
|
|
11
|
+
import { AuroraRouter } from "./router/router.js";
|
|
12
|
+
import { BackgroundAgents } from "./background/index.js";
|
|
13
|
+
import { loadSettings } from "./config/settings.js";
|
|
14
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
const VERSION = "0.0.6";
|
|
17
|
+
// operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
|
|
18
|
+
const settings = loadSettings();
|
|
19
|
+
// Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
|
|
20
|
+
process.env.KODE_SANDBOX = settings.sandbox.mode;
|
|
21
|
+
// Session persistence: the conversation is auto-saved here every turn; `operator --resume` reloads it.
|
|
22
|
+
const SESSION_FILE = process.env.KODE_SESSION_FILE ?? join(process.cwd(), ".operator-session.json");
|
|
23
|
+
const RESUME = process.argv.includes("--resume") || process.argv.includes("-r") || process.env.KODE_RESUME === "1";
|
|
24
|
+
// Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
|
|
25
|
+
// and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
|
|
26
|
+
// 1,048,576-token context at full speed). No size-based routing decision remains.
|
|
27
|
+
function buildRouter() {
|
|
28
|
+
const aurora = { name: "aurora", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow };
|
|
29
|
+
// Primary first; the optional failover is only reached via the router's health-gated recover() when
|
|
30
|
+
// the primary errors (routeBySize always picks aurora at index 0 since 1M fits every prompt).
|
|
31
|
+
const eps = [aurora];
|
|
32
|
+
const fo = settings.endpoints.failover;
|
|
33
|
+
if (fo)
|
|
34
|
+
eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
|
|
35
|
+
return new AuroraRouter(eps);
|
|
36
|
+
}
|
|
37
|
+
const SYSTEM_PROMPT = settings.systemPrompt ??
|
|
38
|
+
`You are Operator, a terse local terminal coding agent. Use your tools to inspect and edit the ` +
|
|
39
|
+
`workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
|
|
40
|
+
`\nContext window: 1,048,576 tokens (1M) — you run on the Aurora model served locally with a full ` +
|
|
41
|
+
`1M-token context. You can hold very large files and long histories; do not claim a smaller limit.` +
|
|
42
|
+
`\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
|
|
43
|
+
`build) call spawn_agent with a fully self-contained instruction — it runs on another Aurora session ` +
|
|
44
|
+
`in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
|
|
45
|
+
`live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
|
|
46
|
+
`spawn many at once — they all share this one model.`;
|
|
47
|
+
const MAX_BG = 4; // concurrent background sub-agents — all share the single Aurora 1M endpoint, so cap fan-out
|
|
48
|
+
const HELP = [
|
|
49
|
+
"commands:",
|
|
50
|
+
" /help this list",
|
|
51
|
+
" /model current endpoint (aurora · 1M), context %, turn count",
|
|
52
|
+
" /endpoints show the aurora endpoint + live health",
|
|
53
|
+
" /compact force-compact the conversation now",
|
|
54
|
+
" /remember <note> store a note to recall in future sessions",
|
|
55
|
+
" /memory [query] show remembered notes (all, or matching query)",
|
|
56
|
+
" /mcp count of fleet MCP tools this session (KODE_TSI_MCP=1)",
|
|
57
|
+
" /login [token] · /logout · /whoami AXE account sign-in (device grant via shell, or paste a token)",
|
|
58
|
+
" /bg <task|stop id> spawn a background sub-agent, list, or stop one",
|
|
59
|
+
" /new start a fresh conversation",
|
|
60
|
+
" /clear clear the screen (keeps the conversation)",
|
|
61
|
+
" /exit /quit leave operator",
|
|
62
|
+
"esc — interrupt a running turn (or quit when idle)",
|
|
63
|
+
].join("\n");
|
|
64
|
+
let ID = 0;
|
|
65
|
+
const nextId = () => `e${++ID}`;
|
|
66
|
+
const firstLine = (s) => (s.split("\n")[0] ?? "").slice(0, 100);
|
|
67
|
+
const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim());
|
|
68
|
+
function Root() {
|
|
69
|
+
const { exit } = useApp();
|
|
70
|
+
const [boot, setBoot] = useState("checking");
|
|
71
|
+
const [entries, setEntries] = useState([]);
|
|
72
|
+
const [live, setLive] = useState(null);
|
|
73
|
+
const [status, setStatus] = useState("idle");
|
|
74
|
+
const [stepLabel, setStepLabel] = useState(""); // tool(s) currently executing, for the step animation
|
|
75
|
+
const [route, setRoute] = useState("aurora");
|
|
76
|
+
const [ctxPct, setCtxPct] = useState(0);
|
|
77
|
+
const [metrics, setMetrics] = useState(""); // last turn's "N tok · X tok/s · Ys" for the status rule
|
|
78
|
+
const [liveTok, setLiveTok] = useState(0); // live output-token count for the CURRENT turn — animates the
|
|
79
|
+
// status rule as tokens stream (each SSE delta ≈ 1 token). Zero extra renders: it rides the per-delta
|
|
80
|
+
// setLive re-render that already happens, so there's no performance cost and no animation timer.
|
|
81
|
+
const [bgAgents, setBgAgents] = useState([]);
|
|
82
|
+
const [authUser, setAuthUser] = useState(""); // signed-in identity for the status rule
|
|
83
|
+
const sessionRef = useRef(null); // lazy — never reconstruct on re-render
|
|
84
|
+
// MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
|
|
85
|
+
// only, no network fan-out at session start). Background agents stay local-only + lean.
|
|
86
|
+
if (!sessionRef.current) {
|
|
87
|
+
sessionRef.current = new Session({
|
|
88
|
+
systemPrompt: SYSTEM_PROMPT,
|
|
89
|
+
router: buildRouter(),
|
|
90
|
+
mcp: settings.mcp,
|
|
91
|
+
maxTokens: settings.maxTokens,
|
|
92
|
+
temperature: settings.temperature,
|
|
93
|
+
recall: settings.memory.recall,
|
|
94
|
+
permissions: settings.permissions, // default bypass — zero gates until turned on
|
|
95
|
+
telemetry: settings.telemetry, // local-only metrics by default
|
|
96
|
+
// Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
|
|
97
|
+
// sub-agent can't spawn more (no fork bombs). Cap at MAX_BG — all sub-agents share the one Aurora
|
|
98
|
+
// endpoint, so past the cap we refuse with guidance rather than thrash the shared KV cache.
|
|
99
|
+
spawnAgent: (task) => {
|
|
100
|
+
const mgr = bgRef.current;
|
|
101
|
+
if (!mgr)
|
|
102
|
+
return "background manager not ready yet — retry in a moment";
|
|
103
|
+
if (mgr.activeCount() >= MAX_BG)
|
|
104
|
+
return `at capacity: ${MAX_BG} sub-agents already running on the single Aurora 1M endpoint — wait for one to finish (see the background panel) before spawning more`;
|
|
105
|
+
const id = mgr.spawn(task);
|
|
106
|
+
return `spawned background sub-agent ${id} — it posts its result here when done. Keep working; watch its live tokens + time in the background panel.`;
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const session = sessionRef.current;
|
|
111
|
+
// Background sub-agents run on their own Session against the same single Aurora 1M endpoint as the
|
|
112
|
+
// foreground — one model, one context tier.
|
|
113
|
+
const bgRef = useRef(null);
|
|
114
|
+
if (!bgRef.current) {
|
|
115
|
+
bgRef.current = new BackgroundAgents(() => new Session({
|
|
116
|
+
systemPrompt: SYSTEM_PROMPT,
|
|
117
|
+
router: new AuroraRouter([
|
|
118
|
+
{ name: "aurora", base: settings.endpoints.aurora.base, model: settings.endpoints.aurora.model, ctxLimit: settings.endpoints.aurora.ctxWindow },
|
|
119
|
+
]),
|
|
120
|
+
maxTokens: settings.maxTokens,
|
|
121
|
+
temperature: settings.temperature,
|
|
122
|
+
}), () => setBgAgents(bgRef.current.list()), (agent, result) => {
|
|
123
|
+
setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
|
|
124
|
+
setBgAgents(bgRef.current.list());
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const bg = bgRef.current;
|
|
128
|
+
const liveText = useRef("");
|
|
129
|
+
const queued = useRef("");
|
|
130
|
+
const statusRef = useRef("idle");
|
|
131
|
+
const setStat = (s) => { statusRef.current = s; setStatus(s); };
|
|
132
|
+
const push = (e) => setEntries((prev) => [...prev, e]);
|
|
133
|
+
const submitRef = useRef(() => { });
|
|
134
|
+
// Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
|
|
135
|
+
// spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
|
|
136
|
+
useEffect(() => {
|
|
137
|
+
const onExit = () => session.shutdown();
|
|
138
|
+
const onTerm = () => { session.shutdown(); process.exit(0); };
|
|
139
|
+
process.once("exit", onExit);
|
|
140
|
+
process.once("SIGTERM", onTerm);
|
|
141
|
+
return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
|
|
142
|
+
}, [session]);
|
|
143
|
+
useEffect(() => {
|
|
144
|
+
session.health().then((ok) => {
|
|
145
|
+
setBoot(ok ? "ready" : "down");
|
|
146
|
+
if (ok && RESUME) {
|
|
147
|
+
try {
|
|
148
|
+
const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
|
|
149
|
+
if (session.restore(saved)) {
|
|
150
|
+
const restored = saved
|
|
151
|
+
.filter((m) => (m.role === "user" || m.role === "assistant") && m.content.trim())
|
|
152
|
+
.map((m) => ({ kind: "message", message: { id: nextId(), role: m.role, content: m.content } }));
|
|
153
|
+
setEntries(restored);
|
|
154
|
+
setCtxPct(session.ctxPct());
|
|
155
|
+
push({ kind: "message", message: { id: nextId(), role: "system", content: `resumed ${session.turnCount()} prior turns` } });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch { /* no saved session to resume */ }
|
|
159
|
+
}
|
|
160
|
+
}).catch(() => setBoot("down"));
|
|
161
|
+
}, []);
|
|
162
|
+
// Show who's signed in (best-effort, non-blocking): load stored creds, verify against the backend.
|
|
163
|
+
useEffect(() => {
|
|
164
|
+
void (async () => {
|
|
165
|
+
try {
|
|
166
|
+
const { loadCredentials } = await import("./auth/store.js");
|
|
167
|
+
const { verifyToken } = await import("./auth/client.js");
|
|
168
|
+
const creds = await loadCredentials();
|
|
169
|
+
if (!creds)
|
|
170
|
+
return;
|
|
171
|
+
const acct = await verifyToken(creds.token);
|
|
172
|
+
if (acct)
|
|
173
|
+
setAuthUser(acct.email ?? acct.external_id);
|
|
174
|
+
}
|
|
175
|
+
catch { /* auth is optional — never block the REPL */ }
|
|
176
|
+
})();
|
|
177
|
+
}, []);
|
|
178
|
+
const sendTurn = useCallback(async (text) => {
|
|
179
|
+
push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
|
|
180
|
+
liveText.current = "";
|
|
181
|
+
setLive(null);
|
|
182
|
+
setLiveTok(0); // reset the live counter at the start of the turn
|
|
183
|
+
setStat("thinking");
|
|
184
|
+
try {
|
|
185
|
+
const outcome = await session.send(text, {
|
|
186
|
+
onRoute: (label, pct) => { setRoute(label); setCtxPct(pct); },
|
|
187
|
+
onDelta: (chunk) => {
|
|
188
|
+
liveText.current += chunk;
|
|
189
|
+
setLiveTok((t) => t + 1); // ≈1 token per streamed delta — batched with setLive, no extra render
|
|
190
|
+
setStat("streaming");
|
|
191
|
+
setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current } });
|
|
192
|
+
},
|
|
193
|
+
onAutoContinue: (round) => {
|
|
194
|
+
push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
|
|
195
|
+
},
|
|
196
|
+
onSelfHeal: (kind) => {
|
|
197
|
+
// A recovery reads as the agent working it out, NOT an error — show the calm "adjusting"
|
|
198
|
+
// animation instead of surfacing a raw http 400/5xx. The next delta/tool flips status back.
|
|
199
|
+
setStepLabel(kind === "context_exceeded" ? "adjusting context" : kind === "unavailable" ? "reconnecting" : "recovering");
|
|
200
|
+
setStat("recovering");
|
|
201
|
+
},
|
|
202
|
+
onToolStart: (names) => { setStepLabel(names.join(", ")); setStat("executing"); },
|
|
203
|
+
onToolBatch: (events, durationMs) => {
|
|
204
|
+
for (const ev of events) {
|
|
205
|
+
const step = {
|
|
206
|
+
id: nextId(), name: ev.name, args: ev.args,
|
|
207
|
+
status: isErrorResult(ev.result) ? "error" : "done",
|
|
208
|
+
durationMs, summary: firstLine(ev.result),
|
|
209
|
+
};
|
|
210
|
+
push({ kind: "tool", step });
|
|
211
|
+
}
|
|
212
|
+
liveText.current = "";
|
|
213
|
+
setLive(null);
|
|
214
|
+
setStat("thinking");
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
if (outcome.interrupted) {
|
|
218
|
+
push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
|
|
219
|
+
}
|
|
220
|
+
else if (outcome.content.trim()) {
|
|
221
|
+
const reasoning = outcome.stopReason === "repetition" ? "(output truncated — loop detected)" : undefined;
|
|
222
|
+
push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
|
|
223
|
+
}
|
|
224
|
+
// Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
|
|
225
|
+
if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
|
|
226
|
+
const tok = outcome.tokens ?? 0;
|
|
227
|
+
const secs = (outcome.durationMs ?? 0) / 1000;
|
|
228
|
+
const tps = outcome.genMs && outcome.genMs > 0 ? tok / (outcome.genMs / 1000) : secs > 0 ? tok / secs : 0;
|
|
229
|
+
setMetrics(`${tok} tok · ${tps >= 10 ? Math.round(tps) : tps.toFixed(1)} tok/s · ${secs.toFixed(1)}s`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
catch (e) {
|
|
233
|
+
push({ kind: "message", message: { id: nextId(), role: "assistant", content: `[turn error: ${e.message}]` } });
|
|
234
|
+
}
|
|
235
|
+
finally {
|
|
236
|
+
liveText.current = "";
|
|
237
|
+
setLive(null);
|
|
238
|
+
setCtxPct(session.ctxPct());
|
|
239
|
+
setStat("idle");
|
|
240
|
+
try {
|
|
241
|
+
writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()));
|
|
242
|
+
}
|
|
243
|
+
catch { /* auto-save is best-effort */ }
|
|
244
|
+
const q = queued.current;
|
|
245
|
+
queued.current = "";
|
|
246
|
+
if (q)
|
|
247
|
+
submitRef.current(q);
|
|
248
|
+
}
|
|
249
|
+
}, []);
|
|
250
|
+
const sys = useCallback((text) => {
|
|
251
|
+
push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
|
|
252
|
+
}, []);
|
|
253
|
+
const handleSlash = useCallback(async (cmd) => {
|
|
254
|
+
const [name, ...rest] = cmd.slice(1).split(/\s+/);
|
|
255
|
+
const arg = rest.join(" ").trim();
|
|
256
|
+
const s = session;
|
|
257
|
+
switch (name) {
|
|
258
|
+
case "help":
|
|
259
|
+
sys(HELP);
|
|
260
|
+
break;
|
|
261
|
+
case "exit":
|
|
262
|
+
case "quit":
|
|
263
|
+
s.shutdown();
|
|
264
|
+
exit();
|
|
265
|
+
break;
|
|
266
|
+
case "clear":
|
|
267
|
+
setEntries([]);
|
|
268
|
+
setLive(null);
|
|
269
|
+
break;
|
|
270
|
+
case "new":
|
|
271
|
+
s.reset();
|
|
272
|
+
setEntries([]);
|
|
273
|
+
setLive(null);
|
|
274
|
+
setCtxPct(0);
|
|
275
|
+
sys("started a fresh conversation");
|
|
276
|
+
break;
|
|
277
|
+
case "model":
|
|
278
|
+
sys(`route: ${s.currentRoute()} · ctx ${s.ctxPct()}% · turns ${s.turnCount()}`);
|
|
279
|
+
break;
|
|
280
|
+
case "route":
|
|
281
|
+
if (s.pinRoute(arg || "auto"))
|
|
282
|
+
sys(arg && arg !== "auto" ? `routing pinned to ${arg}` : "routing set to auto (by size)");
|
|
283
|
+
else
|
|
284
|
+
sys(`unknown endpoint "${arg}" — see /endpoints`);
|
|
285
|
+
break;
|
|
286
|
+
case "compact": {
|
|
287
|
+
const n = await s.compactNow();
|
|
288
|
+
sys(n > 0 ? `compacted ${n} earlier messages` : "nothing to compact yet");
|
|
289
|
+
setCtxPct(s.ctxPct());
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
case "remember":
|
|
293
|
+
if (!arg) {
|
|
294
|
+
sys("usage: /remember <note> — store something to recall in future sessions");
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
sys((await s.remember(arg)) ? "remembered" : "could not store that note");
|
|
298
|
+
break;
|
|
299
|
+
case "memory": {
|
|
300
|
+
const m = await s.memoryText(arg || undefined, 10);
|
|
301
|
+
sys(m || "(no memories yet — /remember <note> to add one)");
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
case "whoami":
|
|
305
|
+
sys(authUser ? `signed in as ${authUser}` : "not signed in — run `operator auth login` in your shell");
|
|
306
|
+
break;
|
|
307
|
+
case "logout": {
|
|
308
|
+
const { clearCredentials } = await import("./auth/store.js");
|
|
309
|
+
await clearCredentials();
|
|
310
|
+
setAuthUser("");
|
|
311
|
+
sys("signed out");
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
case "login": {
|
|
315
|
+
// Device-grant needs the terminal for the browser handoff — do it from the shell. A PAT can be
|
|
316
|
+
// pasted inline here (`/login <token>`) for a quick headless sign-in.
|
|
317
|
+
if (!arg) {
|
|
318
|
+
sys("run `operator auth login` in your shell (browser sign-in), or `/login <token>` to paste a token");
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
const { verifyToken } = await import("./auth/client.js");
|
|
322
|
+
const { saveCredentials } = await import("./auth/store.js");
|
|
323
|
+
const acct = await verifyToken(arg);
|
|
324
|
+
if (!acct) {
|
|
325
|
+
sys("that token was rejected");
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
await saveCredentials({ token: arg, user: acct.external_id, issuedAt: Date.now() });
|
|
329
|
+
setAuthUser(acct.email ?? acct.external_id);
|
|
330
|
+
sys(`signed in as ${acct.email ?? acct.external_id}`);
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
case "mcp": {
|
|
334
|
+
const n = s.mcpToolCount();
|
|
335
|
+
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)");
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
case "endpoints": {
|
|
339
|
+
const h = await s.endpointHealth();
|
|
340
|
+
sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
case "bg":
|
|
344
|
+
if (!arg) {
|
|
345
|
+
const l = bg.list();
|
|
346
|
+
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>)");
|
|
347
|
+
}
|
|
348
|
+
else if (arg.startsWith("stop ")) {
|
|
349
|
+
const id = arg.slice(5).trim();
|
|
350
|
+
sys(bg.stop(id) ? `stopped ${id}` : `unknown agent ${id}`);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
const id = bg.spawn(arg);
|
|
354
|
+
sys(`spawned ${id} in the background — /bg to list · /bg stop ${id} to cancel`);
|
|
355
|
+
}
|
|
356
|
+
break;
|
|
357
|
+
default: sys(`unknown command /${name} — try /help`);
|
|
358
|
+
}
|
|
359
|
+
}, [exit, sys, bg, authUser]);
|
|
360
|
+
const onSubmit = useCallback((text) => {
|
|
361
|
+
const t = text.trim();
|
|
362
|
+
if (t.startsWith("/")) {
|
|
363
|
+
void handleSlash(t);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
void sendTurn(text);
|
|
367
|
+
}, [sendTurn, handleSlash]);
|
|
368
|
+
submitRef.current = onSubmit;
|
|
369
|
+
const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; }, []);
|
|
370
|
+
const onInterrupt = useCallback(() => {
|
|
371
|
+
if (statusRef.current === "idle") {
|
|
372
|
+
session.shutdown();
|
|
373
|
+
return exit();
|
|
374
|
+
} // Ctrl-C / ESC at rest quits
|
|
375
|
+
session.interrupt();
|
|
376
|
+
}, [exit]);
|
|
377
|
+
if (boot === "checking")
|
|
378
|
+
return _jsx(Text, { dimColor: true, children: "connecting to Aurora\u2026" });
|
|
379
|
+
if (boot === "down") {
|
|
380
|
+
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." })] }));
|
|
381
|
+
}
|
|
382
|
+
// While tokens are streaming, show a LIVE animated count in the status rule (the braille glyph advances
|
|
383
|
+
// and the number ticks up per token); when idle, show the last turn's final "N tok · X tok/s · Ys".
|
|
384
|
+
const SPIN = "⣾⣽⣻⢿⡿⣟⣯⣷";
|
|
385
|
+
const liveMetrics = (status === "streaming" || status === "thinking") && liveTok > 0
|
|
386
|
+
? `${SPIN[liveTok % SPIN.length]} ${liveTok} tok`
|
|
387
|
+
: metrics;
|
|
388
|
+
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 }));
|
|
389
|
+
}
|
|
390
|
+
// `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
|
|
391
|
+
// headless (CI / SSH). Anything else falls through to the interactive REPL below.
|
|
392
|
+
if (process.argv[2] === "auth") {
|
|
393
|
+
const { runAuth } = await import("./auth/commands.js");
|
|
394
|
+
process.exit(await runAuth(process.argv.slice(3)));
|
|
395
|
+
}
|
|
396
|
+
// `operator update` (bareword, like `claude update`) and `operator --update` both self-update.
|
|
397
|
+
if (process.argv[2] === "update" || process.argv.includes("--update")) {
|
|
398
|
+
const { runUpdate } = await import("./update.js");
|
|
399
|
+
process.exit(await runUpdate());
|
|
400
|
+
}
|
|
401
|
+
// The Ink shell needs a real terminal (raw-mode keyboard). Fail clearly instead of crashing deep
|
|
402
|
+
// in useInput when piped/non-interactive — for scripted use, drive Session (src/session.ts) directly.
|
|
403
|
+
if (!process.stdin.isTTY) {
|
|
404
|
+
process.stderr.write("kode-tsi needs an interactive terminal (TTY). For scripted turns, import { Session } from kode-tsi.\n");
|
|
405
|
+
process.exit(1);
|
|
406
|
+
}
|
|
407
|
+
render(_jsx(Root, {}));
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// operator/settings.json — a user configuration layer (backlog #49), same shape as a typical coding
|
|
2
|
+
// agent's settings.json. Loaded once at startup by cli.tsx. Precedence: env var > settings.json > built-in
|
|
3
|
+
// default. Never throws — a missing or malformed file just falls back to defaults, same as an env
|
|
4
|
+
// var that was never set.
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
// The sole endpoint: Aurora on :8097 at its REAL served context — 1,048,576 tokens (the native window
|
|
9
|
+
// of the Qwen3.5-MoE hybrid-linear-attention base; verified via /props). This is the one model
|
|
10
|
+
// kode/operator serves. Override base/model in settings.json to point at any OpenAI-compatible server.
|
|
11
|
+
const DEFAULTS = {
|
|
12
|
+
endpoints: {
|
|
13
|
+
aurora: { base: "http://127.0.0.1:8097", ctxWindow: 1048576, model: "aurora-code-1" },
|
|
14
|
+
// Interim degraded HA: JL2 dolphin3-tools:8b via the local SSH tunnel (com.axe.jl2-ollama-tunnel).
|
|
15
|
+
// Reached only on primary failure; small ctx. Replaced by the true 24GB hot-standby (task #50).
|
|
16
|
+
failover: { base: "http://127.0.0.1:11435", ctxWindow: 8192, model: "dolphin3-tools:8b" },
|
|
17
|
+
},
|
|
18
|
+
maxTokens: 32768, // generous per-reply output cap — 1M ctx has ample room; clampMaxTokens still trims
|
|
19
|
+
// to the space left after the prompt so a reply never overflows. A small cap (was
|
|
20
|
+
// 2048) forced the model to truncate + work around; this lets full files/answers land.
|
|
21
|
+
temperature: 0.7,
|
|
22
|
+
mcp: false,
|
|
23
|
+
memory: { recall: true },
|
|
24
|
+
permissions: { mode: "bypass" }, // zero gates by default — enforcement is opt-in
|
|
25
|
+
telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
|
|
26
|
+
sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
|
|
27
|
+
};
|
|
28
|
+
function settingsPath() {
|
|
29
|
+
return process.env.KODE_TSI_SETTINGS ?? join(homedir(), ".axe", "operator", "settings.json");
|
|
30
|
+
}
|
|
31
|
+
function isPlainObject(v) {
|
|
32
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
33
|
+
}
|
|
34
|
+
/** Deep-merge `override` onto `base`. Plain objects recurse; arrays and primitives replace wholesale. */
|
|
35
|
+
function deepMerge(base, override) {
|
|
36
|
+
if (!isPlainObject(override))
|
|
37
|
+
return base;
|
|
38
|
+
const out = { ...base };
|
|
39
|
+
for (const [k, v] of Object.entries(override)) {
|
|
40
|
+
const baseVal = base?.[k];
|
|
41
|
+
out[k] = isPlainObject(v) && isPlainObject(baseVal) ? deepMerge(baseVal, v) : v;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
/** Parsed settings file, or undefined on any read/parse failure — malformed JSON is not an error here. */
|
|
46
|
+
function readSettingsFile(path) {
|
|
47
|
+
try {
|
|
48
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Fold env vars over the file+default merge — the top layer of the precedence stack. Only an env
|
|
55
|
+
* var that's actually set overrides; an unset one leaves the file/default value alone. */
|
|
56
|
+
function applyEnv(s) {
|
|
57
|
+
const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox } };
|
|
58
|
+
if (process.env.KODE_MODEL)
|
|
59
|
+
out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, model: process.env.KODE_MODEL } }; // AI-agnostic quick-swap (keeps failover)
|
|
60
|
+
const base = process.env.KODE_AURORA ?? process.env.KODE_1M; // KODE_1M kept as a back-compat alias for the base override
|
|
61
|
+
if (base)
|
|
62
|
+
out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, base } };
|
|
63
|
+
if (process.env.KODE_TSI_MCP !== undefined)
|
|
64
|
+
out.mcp = process.env.KODE_TSI_MCP === "1";
|
|
65
|
+
if (process.env.KODE_SYSTEM_PROMPT)
|
|
66
|
+
out.systemPrompt = process.env.KODE_SYSTEM_PROMPT;
|
|
67
|
+
const pm = process.env.KODE_PERMISSIONS;
|
|
68
|
+
if (pm === "bypass" || pm === "audit" || pm === "gated")
|
|
69
|
+
out.permissions = { ...out.permissions, mode: pm };
|
|
70
|
+
if (process.env.KODE_TELEMETRY === "0")
|
|
71
|
+
out.telemetry = { ...out.telemetry, enabled: false };
|
|
72
|
+
const sb = process.env.KODE_SANDBOX;
|
|
73
|
+
if (sb === "off" || sb === "workspace" || sb === "strict")
|
|
74
|
+
out.sandbox = { mode: sb };
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/** Load operator settings: built-in defaults <- ~/.axe/operator/settings.json (override path via
|
|
78
|
+
* KODE_TSI_SETTINGS) <- env vars. Never throws. */
|
|
79
|
+
export function loadSettings() {
|
|
80
|
+
const file = readSettingsFile(settingsPath());
|
|
81
|
+
// structuredClone the base so a returned settings object never aliases the module-level DEFAULTS —
|
|
82
|
+
// deepMerge only recurses into keys the override touches, so an untouched nested endpoint would
|
|
83
|
+
// otherwise flow through by reference and a later mutation would corrupt defaults process-wide.
|
|
84
|
+
return applyEnv(deepMerge(structuredClone(DEFAULTS), file));
|
|
85
|
+
}
|