@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/README.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# operator — KODE-TSI
|
|
2
|
+
|
|
3
|
+
The TypeScript + [Ink](https://github.com/vadimdemedes/ink) port of KODE: an Aurora-backed agentic
|
|
4
|
+
terminal coding agent, built to the frozen `SPEC/` contract shared with the Python core (`kode`/`kode+`).
|
|
5
|
+
Launched as **`operator`** (1M-only) / **`operator+`** (Air⇄1M) — the AXE counterpart to Claude Code.
|
|
6
|
+
|
|
7
|
+
The port's reason to exist: a **full-frame React reconciler + Ink `<Static>`** render, which makes the
|
|
8
|
+
scroll / echo / prompt-overwrite bug class of the ANSI-cursor Python REPL *structurally impossible*.
|
|
9
|
+
|
|
10
|
+
## Architecture
|
|
11
|
+
|
|
12
|
+
One TypeScript engine, consumed by three surfaces (terminal / web / mobile) — never forked.
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
src/
|
|
16
|
+
├── engine/ # headless agent core — no UI, fully unit-tested
|
|
17
|
+
│ ├── aurora.ts # /v1 transport: SSE streaming, tool-call accumulation, AuroraHttpError,
|
|
18
|
+
│ │ # onDelta, decode-time loop-breaker (isDegenerate / trimLoop)
|
|
19
|
+
│ ├── agent.ts # runTurn: the model↔tools loop, self-heal, loop-guard, auto-continue,
|
|
20
|
+
│ │ # empty-dud recovery, <think> strip, compaction hook
|
|
21
|
+
│ ├── selfheal.ts # classify failures by CAUSE (context|transient|bad_request|auth) +
|
|
22
|
+
│ │ # exponential backoff w/ jitter (honors Retry-After)
|
|
23
|
+
│ ├── compaction.ts # endpoint-aware auto-compaction + fact-preserving summaryPrompt
|
|
24
|
+
│ ├── messages.ts # Msg/Conversation, buildMessages, tool-pair repair, shape validation
|
|
25
|
+
│ └── toolcalls.ts # recover text-emitted (Qwen XML / JSON) tool calls
|
|
26
|
+
├── router/router.ts # AuroraRouter — size-based routing, failover, Saddle fallback, pin/resetTurn
|
|
27
|
+
├── tools/ # the tool set (11): shell/file/grep/git/memory/checkpoint/web_fetch
|
|
28
|
+
│ ├── registry.ts # Tool defs + JSON schemas (toSchemas) + safe/mutating flags
|
|
29
|
+
│ └── executor.ts # dispatch: parallel (read-only) vs sequential (mutating), per-turn loop guard
|
|
30
|
+
├── session.ts # Session controller — binds engine + router + tools + summarizer; the
|
|
31
|
+
│ # headless, testable API the shell drives (send / interrupt / slash surface)
|
|
32
|
+
├── cli.tsx # the Ink shell — maps Session's streaming callbacks onto React state,
|
|
33
|
+
│ # slash commands, session persistence, TTY guard
|
|
34
|
+
├── ui/ # presentational Ink components (App, Transcript, Composer, StatusRule, …)
|
|
35
|
+
├── index.ts # Node EngineClient barrel (terminal + node tools)
|
|
36
|
+
└── index.browser.ts # browser-safe barrel (kode-web imports this — no node built-ins)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Capabilities
|
|
40
|
+
|
|
41
|
+
- **Routing / resilience** — Air (fast, 8K) ⇄ 1M (huge ctx), with a **Saddle** fallback the self-heal
|
|
42
|
+
reaches only after the Aurora tiers 5xx (degraded model beats a hard failure). Self-heal classifies
|
|
43
|
+
by cause and backs off exponentially; never storms a struggling server.
|
|
44
|
+
- **Long turns** — soft round budget (10) auto-continues to a hard cap (40) while the model is still
|
|
45
|
+
calling tools, so a big build finishes in one turn.
|
|
46
|
+
- **Never a mystery blank** — a loop-broken stream trims to its coherent prefix; an empty "dud" round
|
|
47
|
+
is nudged once, then falls back to reasoning, then to a clear message.
|
|
48
|
+
- **Fact-preserving compaction** — a verbatim FACTS/STATE summary + reasoning fallback; guards against
|
|
49
|
+
an empty summary destroying history.
|
|
50
|
+
- **Streaming** — live token stream with a caret; interrupt (ESC) tears the stream down at the transport.
|
|
51
|
+
- **Slash commands** — `/help /model /endpoints /route /compact /new /clear /exit`.
|
|
52
|
+
- **Session persistence** — auto-saved per turn; `operator --resume` reloads it.
|
|
53
|
+
|
|
54
|
+
## Run
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
operator+ # Air⇄1M routing (default)
|
|
58
|
+
operator # 1M-only
|
|
59
|
+
operator+ --resume # reload the last conversation
|
|
60
|
+
```
|
|
61
|
+
Requires Aurora serving locally (Air `:8098` / 1M `:8097`). Dev: `npm install && npm run dev`.
|
|
62
|
+
Env: `KODE_AIR`, `KODE_1M`, `KODE_SADDLE`, `KODE_TSI_ROUTER=1m`, `KODE_SYSTEM_PROMPT`, `KODE_SESSION_FILE`.
|
|
63
|
+
|
|
64
|
+
## Testing
|
|
65
|
+
|
|
66
|
+
The engine is UI-free by design, so it is verified headlessly end-to-end against live Aurora (streaming,
|
|
67
|
+
tools, self-heal→saddle, auto-continue, compaction, interrupt) plus mock-server integration for the
|
|
68
|
+
error paths and Ink render smokes for the display tree. `npm run build` typechecks the whole tree.
|
|
69
|
+
|
|
70
|
+
## Provenance
|
|
71
|
+
|
|
72
|
+
Built by **AXE Technology** and **IMI**. Shares the frozen `SPEC/` with the Python core; kode-web and
|
|
73
|
+
kode-mobile consume this same engine (browser barrel / Swift port) — the engine is the single source of truth.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Operator auth client — talks to the AuthGate operator-tsi backend (RFC 8628 device grant + PAT
|
|
2
|
+
// verify). The base URL is configurable (AXE_AUTH_URL) so it works against staging/prod/local without
|
|
3
|
+
// a code change. Pure transport + flow; the CLI commands (commands.ts) drive it and own the console.
|
|
4
|
+
const AUTH_BASE = (process.env.AXE_AUTH_URL ?? "https://gate.authgate.cloud").replace(/\/$/, "");
|
|
5
|
+
const CLIENT_ID = "operator-cli";
|
|
6
|
+
async function post(path, body, timeoutMs = 15_000) {
|
|
7
|
+
const ctrl = new AbortController();
|
|
8
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
9
|
+
try {
|
|
10
|
+
const res = await fetch(`${AUTH_BASE}${path}`, {
|
|
11
|
+
method: "POST",
|
|
12
|
+
signal: ctrl.signal,
|
|
13
|
+
headers: { "content-type": "application/json" },
|
|
14
|
+
body: JSON.stringify(body),
|
|
15
|
+
});
|
|
16
|
+
const json = await res.json().catch(() => ({}));
|
|
17
|
+
return { status: res.status, json };
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
clearTimeout(t);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Kick off a device-authorization grant: the CLI shows user_code, the human approves in a browser. */
|
|
24
|
+
export async function requestDeviceCode() {
|
|
25
|
+
const { status, json } = await post("/operator/device/code", { client_id: CLIENT_ID });
|
|
26
|
+
if (status !== 200)
|
|
27
|
+
throw new Error(`device/code failed (HTTP ${status})`);
|
|
28
|
+
return json;
|
|
29
|
+
}
|
|
30
|
+
/** One poll of the device-token endpoint. RFC 8628: pending/slow_down keep waiting, the rest are terminal. */
|
|
31
|
+
export async function pollDeviceToken(deviceCode) {
|
|
32
|
+
const { status, json } = await post("/operator/device/token", {
|
|
33
|
+
device_code: deviceCode,
|
|
34
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
35
|
+
});
|
|
36
|
+
if (status === 200 && json.access_token) {
|
|
37
|
+
return { state: "approved", token: json.access_token, account: (json.account ?? {}) };
|
|
38
|
+
}
|
|
39
|
+
// The error may be flat (`{error}`) or nested under FastAPI's `detail` (`{detail:{error}}` or
|
|
40
|
+
// `{detail:"..."}`) — accept both so a pending poll isn't misread as a terminal error.
|
|
41
|
+
const err = json?.error ?? json?.detail?.error ?? (typeof json?.detail === "string" ? json.detail : undefined);
|
|
42
|
+
switch (err) {
|
|
43
|
+
case "authorization_pending": return { state: "pending" };
|
|
44
|
+
case "slow_down": return { state: "slow_down" };
|
|
45
|
+
case "access_denied": return { state: "denied" };
|
|
46
|
+
case "expired_token": return { state: "expired" };
|
|
47
|
+
default: return { state: "expired" }; // unknown terminal error → stop waiting rather than spin
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Poll to completion, honoring the server interval + slow_down. onTick lets the CLI animate the wait. */
|
|
51
|
+
export async function awaitApproval(dc, opts = {}) {
|
|
52
|
+
let interval = Math.max(1, dc.interval) * 1000;
|
|
53
|
+
const deadline = Date.now() + dc.expires_in * 1000;
|
|
54
|
+
for (;;) {
|
|
55
|
+
if (opts.signal?.aborted)
|
|
56
|
+
return { state: "denied" };
|
|
57
|
+
if (Date.now() > deadline)
|
|
58
|
+
return { state: "expired" };
|
|
59
|
+
await new Promise((r) => setTimeout(r, interval));
|
|
60
|
+
opts.onTick?.();
|
|
61
|
+
const r = await pollDeviceToken(dc.device_code);
|
|
62
|
+
if (r.state === "slow_down") {
|
|
63
|
+
interval += 5_000;
|
|
64
|
+
continue;
|
|
65
|
+
} // RFC 8628: back off by 5s
|
|
66
|
+
if (r.state === "pending")
|
|
67
|
+
continue;
|
|
68
|
+
return r; // approved | denied | expired
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Validate a token (PAT or device-minted) against the backend. Returns the Account or null. */
|
|
72
|
+
export async function verifyToken(token, timeoutMs = 10_000) {
|
|
73
|
+
const ctrl = new AbortController();
|
|
74
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
75
|
+
try {
|
|
76
|
+
const res = await fetch(`${AUTH_BASE}/operator/verify`, {
|
|
77
|
+
headers: { authorization: `Bearer ${token}` },
|
|
78
|
+
signal: ctrl.signal,
|
|
79
|
+
});
|
|
80
|
+
if (res.status !== 200)
|
|
81
|
+
return null;
|
|
82
|
+
const json = await res.json().catch(() => ({}));
|
|
83
|
+
return (json.account ?? null);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
clearTimeout(t);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function authBase() {
|
|
93
|
+
return AUTH_BASE;
|
|
94
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// `operator auth <sub>` — the CLI auth surface, run BEFORE the Ink REPL mounts (cli.tsx intercepts it).
|
|
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)
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { platform } from "node:os";
|
|
9
|
+
import { requestDeviceCode, awaitApproval, verifyToken, authBase } from "./client.js";
|
|
10
|
+
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).
|
|
12
|
+
function openBrowser(url) {
|
|
13
|
+
const cmd = platform() === "darwin" ? "open" : platform() === "win32" ? "start" : "xdg-open";
|
|
14
|
+
try {
|
|
15
|
+
spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
/* headless / no browser — the printed URL + code is the fallback */
|
|
19
|
+
}
|
|
20
|
+
}
|
|
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());
|
|
27
|
+
return 1;
|
|
28
|
+
}
|
|
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;
|
|
32
|
+
}
|
|
33
|
+
// Device-grant path.
|
|
34
|
+
let dc;
|
|
35
|
+
try {
|
|
36
|
+
dc = await requestDeviceCode();
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
console.error(`✗ could not reach ${authBase()}: ${e.message}`);
|
|
40
|
+
return 1;
|
|
41
|
+
}
|
|
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);
|
|
46
|
+
const ctrl = new AbortController();
|
|
47
|
+
const onSig = () => ctrl.abort();
|
|
48
|
+
process.once("SIGINT", onSig);
|
|
49
|
+
try {
|
|
50
|
+
const r = await awaitApproval(dc, { signal: ctrl.signal, onTick: () => process.stdout.write(".") });
|
|
51
|
+
process.stdout.write("\n");
|
|
52
|
+
if (r.state !== "approved") {
|
|
53
|
+
console.error(`✗ sign-in ${r.state === "expired" ? "timed out" : r.state}`);
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
await saveCredentials({ token: r.token, user: r.account.external_id, host: authBase(), issuedAt: Date.now() });
|
|
57
|
+
console.log(`✓ signed in as ${r.account.email ?? r.account.external_id}`);
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
process.off("SIGINT", onSig);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async function logout() {
|
|
65
|
+
await clearCredentials();
|
|
66
|
+
console.log("✓ signed out");
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
async function status() {
|
|
70
|
+
const creds = await loadCredentials();
|
|
71
|
+
if (!creds) {
|
|
72
|
+
console.log("not signed in — run `operator auth login`");
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
const account = await verifyToken(creds.token);
|
|
76
|
+
if (!account) {
|
|
77
|
+
console.log(`stored credentials for ${creds.user ?? "?"} are no longer valid — run \`operator auth login\``);
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
console.log(`signed in as ${account.email ?? account.external_id} · ${creds.host ?? authBase()}`);
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
/** Dispatch `operator auth <sub> [args]`. Returns a process exit code. */
|
|
84
|
+
export async function runAuth(argv) {
|
|
85
|
+
const [sub, ...rest] = argv;
|
|
86
|
+
switch (sub) {
|
|
87
|
+
case "login": {
|
|
88
|
+
const i = rest.indexOf("--token");
|
|
89
|
+
const token = i >= 0 ? rest[i + 1] : undefined;
|
|
90
|
+
return login(token);
|
|
91
|
+
}
|
|
92
|
+
case "logout": return logout();
|
|
93
|
+
case "status":
|
|
94
|
+
case "whoami": return status();
|
|
95
|
+
default:
|
|
96
|
+
console.log("usage: operator auth <login [--token <pat>] | logout | status>");
|
|
97
|
+
return sub ? 1 : 0;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Operator credential store. The token lives in the OS keychain (macOS `security`, Linux `secret-tool`)
|
|
2
|
+
// under the service name below, with a 0600 JSON fallback at ~/.axe/operator/credentials.json when no
|
|
3
|
+
// keychain is available. Non-secret metadata (user, issued time, auth host) always goes to the JSON so
|
|
4
|
+
// `operator auth status` needs no network call. Both operator (this) and the Python `kode` read the
|
|
5
|
+
// SAME service + file, so a token minted by either client authenticates both.
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { readFile, writeFile, mkdir, rm } from "node:fs/promises";
|
|
8
|
+
import { homedir, platform } from "node:os";
|
|
9
|
+
import { join, dirname } from "node:path";
|
|
10
|
+
const SERVICE = "axe-operator"; // keychain service — shared contract with the Python client
|
|
11
|
+
const ACCOUNT = "default";
|
|
12
|
+
const FILE = process.env.KODE_CREDENTIALS ?? join(homedir(), ".axe", "operator", "credentials.json");
|
|
13
|
+
function run(cmd, args, input) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const child = execFile(cmd, args, (err, stdout) => (err ? reject(err) : resolve(stdout.toString())));
|
|
16
|
+
if (input !== undefined) {
|
|
17
|
+
child.stdin?.end(input);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
// KODE_NO_KEYCHAIN=1 forces the 0600-file store (CI/headless boxes with no keychain, and clean tests
|
|
22
|
+
// that must not touch the real OS keychain).
|
|
23
|
+
const NO_KEYCHAIN = process.env.KODE_NO_KEYCHAIN === "1";
|
|
24
|
+
async function keychainSet(token) {
|
|
25
|
+
if (NO_KEYCHAIN)
|
|
26
|
+
return false;
|
|
27
|
+
try {
|
|
28
|
+
if (platform() === "darwin") {
|
|
29
|
+
await run("security", ["add-generic-password", "-U", "-s", SERVICE, "-a", ACCOUNT, "-w", token]);
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
if (platform() === "linux") {
|
|
33
|
+
await run("secret-tool", ["store", "--label=" + SERVICE, "service", SERVICE, "account", ACCOUNT], token);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
/* no keychain / tool missing → file fallback */
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
async function keychainGet() {
|
|
43
|
+
if (NO_KEYCHAIN)
|
|
44
|
+
return null;
|
|
45
|
+
try {
|
|
46
|
+
if (platform() === "darwin") {
|
|
47
|
+
return (await run("security", ["find-generic-password", "-s", SERVICE, "-a", ACCOUNT, "-w"])).trim() || null;
|
|
48
|
+
}
|
|
49
|
+
if (platform() === "linux") {
|
|
50
|
+
return (await run("secret-tool", ["lookup", "service", SERVICE, "account", ACCOUNT])).trim() || null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
/* not found / no keychain */
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
async function keychainClear() {
|
|
59
|
+
if (NO_KEYCHAIN)
|
|
60
|
+
return;
|
|
61
|
+
try {
|
|
62
|
+
if (platform() === "darwin")
|
|
63
|
+
await run("security", ["delete-generic-password", "-s", SERVICE, "-a", ACCOUNT]);
|
|
64
|
+
else if (platform() === "linux")
|
|
65
|
+
await run("secret-tool", ["clear", "service", SERVICE, "account", ACCOUNT]);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
/* nothing stored */
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function readMeta() {
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(await readFile(FILE, "utf8"));
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return {};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Persist credentials: token to the keychain (or, if unavailable, the 0600 file), metadata always to file. */
|
|
80
|
+
export async function saveCredentials(creds) {
|
|
81
|
+
await mkdir(dirname(FILE), { recursive: true });
|
|
82
|
+
const inKeychain = await keychainSet(creds.token);
|
|
83
|
+
// File holds metadata always; it holds the token too ONLY when the keychain couldn't (fallback).
|
|
84
|
+
const onDisk = { user: creds.user, host: creds.host, issuedAt: creds.issuedAt, ...(inKeychain ? {} : { token: creds.token }) };
|
|
85
|
+
await writeFile(FILE, JSON.stringify(onDisk, null, 2), { mode: 0o600 });
|
|
86
|
+
}
|
|
87
|
+
/** Load credentials, or null if not signed in. Prefers the keychain token; falls back to the file's. */
|
|
88
|
+
export async function loadCredentials() {
|
|
89
|
+
const meta = await readMeta();
|
|
90
|
+
const token = (await keychainGet()) ?? meta.token ?? null;
|
|
91
|
+
if (!token)
|
|
92
|
+
return null;
|
|
93
|
+
return { token, user: meta.user, host: meta.host, issuedAt: meta.issuedAt };
|
|
94
|
+
}
|
|
95
|
+
/** Sign out: drop the keychain entry and the on-disk file. */
|
|
96
|
+
export async function clearCredentials() {
|
|
97
|
+
await keychainClear();
|
|
98
|
+
await rm(FILE, { force: true });
|
|
99
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export class BackgroundAgents {
|
|
2
|
+
makeSession;
|
|
3
|
+
onChange;
|
|
4
|
+
onDone;
|
|
5
|
+
agents = new Map();
|
|
6
|
+
seq = 0;
|
|
7
|
+
/** @param makeSession builds a fresh Session for a bg agent (shell pins it to 1M).
|
|
8
|
+
* @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
|
+
this.makeSession = makeSession;
|
|
12
|
+
this.onChange = onChange;
|
|
13
|
+
this.onDone = onDone;
|
|
14
|
+
}
|
|
15
|
+
list() {
|
|
16
|
+
return [...this.agents.values()].map((a) => ({ ...a.info }));
|
|
17
|
+
}
|
|
18
|
+
/** Spawn a background agent on `task`. Returns its short id (bg1, bg2, …). */
|
|
19
|
+
spawn(task) {
|
|
20
|
+
const id = `bg${++this.seq}`;
|
|
21
|
+
const label = task.replace(/\s+/g, " ").slice(0, 28);
|
|
22
|
+
const session = this.makeSession();
|
|
23
|
+
const info = { id, label, status: "working", task, round: 0, tokens: 0, startedAt: Date.now() };
|
|
24
|
+
this.agents.set(id, { info, session });
|
|
25
|
+
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.
|
|
31
|
+
onDelta: () => { info.tokens = (info.tokens ?? 0) + 1; },
|
|
32
|
+
onToolBatch: () => { info.round = (info.round ?? 0) + 1; this.onChange(); },
|
|
33
|
+
})
|
|
34
|
+
.then((r) => {
|
|
35
|
+
info.status = r.interrupted ? "stopped" : "idle";
|
|
36
|
+
if (typeof r.tokens === "number")
|
|
37
|
+
info.tokens = r.tokens; // authoritative llama.cpp count
|
|
38
|
+
info.durationMs = r.durationMs ?? (Date.now() - (info.startedAt ?? Date.now()));
|
|
39
|
+
this.onChange();
|
|
40
|
+
if (!r.interrupted && r.content.trim())
|
|
41
|
+
this.onDone(info, r.content);
|
|
42
|
+
})
|
|
43
|
+
.catch((e) => {
|
|
44
|
+
info.status = "stopped";
|
|
45
|
+
this.onChange();
|
|
46
|
+
this.onDone(info, `[${id} error: ${e instanceof Error ? e.message : String(e)}]`);
|
|
47
|
+
});
|
|
48
|
+
return id;
|
|
49
|
+
}
|
|
50
|
+
/** Stop a running agent (interrupts its turn). Returns false if the id is unknown. */
|
|
51
|
+
stop(id) {
|
|
52
|
+
const a = this.agents.get(id);
|
|
53
|
+
if (!a)
|
|
54
|
+
return false;
|
|
55
|
+
a.session.interrupt();
|
|
56
|
+
a.info.status = "stopped";
|
|
57
|
+
this.onChange();
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
/** Number of agents still working — for the status line. */
|
|
61
|
+
activeCount() {
|
|
62
|
+
return [...this.agents.values()].filter((a) => a.info.status === "working").length;
|
|
63
|
+
}
|
|
64
|
+
}
|