@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.
Files changed (47) hide show
  1. package/README.md +73 -0
  2. package/dist/auth/client.js +94 -0
  3. package/dist/auth/commands.js +99 -0
  4. package/dist/auth/store.js +99 -0
  5. package/dist/background/index.js +64 -0
  6. package/dist/cli.js +407 -0
  7. package/dist/config/settings.js +85 -0
  8. package/dist/engine/agent.js +232 -0
  9. package/dist/engine/aurora.js +213 -0
  10. package/dist/engine/compaction.js +111 -0
  11. package/dist/engine/contract.js +8 -0
  12. package/dist/engine/messages.js +85 -0
  13. package/dist/engine/router-adapter.js +29 -0
  14. package/dist/engine/selfheal.js +46 -0
  15. package/dist/engine/toolcalls.js +164 -0
  16. package/dist/index.browser.js +22 -0
  17. package/dist/index.js +23 -0
  18. package/dist/mcp/client.js +95 -0
  19. package/dist/mcp/config.js +73 -0
  20. package/dist/mcp/index.js +101 -0
  21. package/dist/mcp/stdio.js +149 -0
  22. package/dist/memory/index.js +0 -0
  23. package/dist/observability/index.js +60 -0
  24. package/dist/permissions/audit.js +50 -0
  25. package/dist/permissions/index.js +48 -0
  26. package/dist/permissions/policy.js +54 -0
  27. package/dist/router/router.js +94 -0
  28. package/dist/session.js +265 -0
  29. package/dist/tools/executor.js +0 -0
  30. package/dist/tools/registry.js +380 -0
  31. package/dist/tools/sandbox.js +90 -0
  32. package/dist/ui/ActivitySpinner.js +48 -0
  33. package/dist/ui/App.js +16 -0
  34. package/dist/ui/AuthScreen.js +17 -0
  35. package/dist/ui/BgPanel.js +24 -0
  36. package/dist/ui/Composer.js +119 -0
  37. package/dist/ui/Header.js +22 -0
  38. package/dist/ui/StatusRule.js +11 -0
  39. package/dist/ui/ThinkingSpinner.js +61 -0
  40. package/dist/ui/ToolStep.js +32 -0
  41. package/dist/ui/Transcript.js +22 -0
  42. package/dist/ui/format.js +6 -0
  43. package/dist/ui/index.js +9 -0
  44. package/dist/ui/types.js +3 -0
  45. package/dist/ui/useInputHistory.js +97 -0
  46. package/dist/update.js +57 -0
  47. package/package.json +47 -0
@@ -0,0 +1,149 @@
1
+ import { flattenResult } from "./client.js";
2
+ // node:child_process is loaded LAZILY (variable-specifier import, never a literal) so this module is
3
+ // node-free AT LOAD — safe in the browser/JSCore engine bundle. esbuild --platform=neutral can't resolve
4
+ // a variable specifier, so it stays a runtime import on the node path. A stdio server is a node-only
5
+ // transport; browser/JSCore hosts use http MCP servers exclusively and never instantiate this client.
6
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
7
+ export class McpStdioClient {
8
+ command;
9
+ args;
10
+ env;
11
+ timeoutMs;
12
+ proc = null;
13
+ starting = null;
14
+ buf = "";
15
+ id = 0;
16
+ pending = new Map();
17
+ dead = false;
18
+ constructor(command, args = [], env = {}, timeoutMs = 20_000) {
19
+ this.command = command;
20
+ this.args = args;
21
+ this.env = env;
22
+ this.timeoutMs = timeoutMs;
23
+ }
24
+ async ensureStarted() {
25
+ if (this.starting)
26
+ return this.starting;
27
+ this.starting = (async () => {
28
+ const { spawn } = await nodeImport("node:child_process");
29
+ return new Promise((resolve, reject) => {
30
+ let proc;
31
+ try {
32
+ proc = spawn(this.command, this.args, {
33
+ stdio: ["pipe", "pipe", "ignore"],
34
+ env: { ...process.env, ...this.env },
35
+ });
36
+ }
37
+ catch (e) {
38
+ reject(e instanceof Error ? e : new Error(String(e)));
39
+ return;
40
+ }
41
+ this.proc = proc;
42
+ proc.on("error", (e) => this.fail(e)); // e.g. ENOENT: binary not found
43
+ proc.on("exit", () => this.fail(new Error("MCP server exited")));
44
+ proc.stdout.setEncoding("utf8");
45
+ proc.stdout.on("data", (chunk) => this.onData(chunk));
46
+ // Handshake: initialize (awaited) → notifications/initialized (fire-and-forget).
47
+ this.rpc("initialize", {
48
+ protocolVersion: "2024-11-05",
49
+ capabilities: {},
50
+ clientInfo: { name: "operator", version: "0.0.1" },
51
+ })
52
+ .then(() => {
53
+ this.notify("notifications/initialized", {});
54
+ resolve();
55
+ })
56
+ .catch(reject);
57
+ });
58
+ })();
59
+ return this.starting;
60
+ }
61
+ fail(err) {
62
+ this.dead = true;
63
+ for (const p of this.pending.values()) {
64
+ clearTimeout(p.timer);
65
+ p.reject(err);
66
+ }
67
+ this.pending.clear();
68
+ }
69
+ onData(chunk) {
70
+ this.buf += chunk;
71
+ let nl;
72
+ while ((nl = this.buf.indexOf("\n")) >= 0) {
73
+ const line = this.buf.slice(0, nl).trim();
74
+ this.buf = this.buf.slice(nl + 1);
75
+ if (!line)
76
+ continue;
77
+ let msg;
78
+ try {
79
+ msg = JSON.parse(line);
80
+ }
81
+ catch {
82
+ continue; // ignore server log noise that isn't JSON-RPC
83
+ }
84
+ if (typeof msg.id !== "number")
85
+ continue; // a notification, not our reply
86
+ if (!("result" in msg) && !("error" in msg))
87
+ continue; // a request echo (e.g. `cat`), not a JSON-RPC response
88
+ const p = this.pending.get(msg.id);
89
+ if (!p)
90
+ continue;
91
+ this.pending.delete(msg.id);
92
+ clearTimeout(p.timer);
93
+ if (msg.error)
94
+ p.reject(new Error(msg.error.message ?? JSON.stringify(msg.error)));
95
+ else
96
+ p.resolve(msg.result);
97
+ }
98
+ }
99
+ write(obj) {
100
+ if (!this.proc || this.dead)
101
+ throw new Error("MCP server not running");
102
+ this.proc.stdin.write(JSON.stringify(obj) + "\n");
103
+ }
104
+ notify(method, params) {
105
+ try {
106
+ this.write({ jsonrpc: "2.0", method, params });
107
+ }
108
+ catch {
109
+ /* best-effort notification */
110
+ }
111
+ }
112
+ rpc(method, params = {}) {
113
+ return new Promise((resolve, reject) => {
114
+ const id = ++this.id;
115
+ const timer = setTimeout(() => {
116
+ this.pending.delete(id);
117
+ reject(new Error(`timeout: ${method}`));
118
+ }, this.timeoutMs);
119
+ this.pending.set(id, { resolve, reject, timer });
120
+ try {
121
+ this.write({ jsonrpc: "2.0", id, method, params });
122
+ }
123
+ catch (e) {
124
+ this.pending.delete(id);
125
+ clearTimeout(timer);
126
+ reject(e instanceof Error ? e : new Error(String(e)));
127
+ }
128
+ });
129
+ }
130
+ async listTools() {
131
+ await this.ensureStarted();
132
+ const r = (await this.rpc("tools/list"));
133
+ return r?.tools ?? [];
134
+ }
135
+ async callTool(name, args) {
136
+ await this.ensureStarted();
137
+ return flattenResult((await this.rpc("tools/call", { name, arguments: args })));
138
+ }
139
+ stop() {
140
+ this.dead = true;
141
+ try {
142
+ this.proc?.kill();
143
+ }
144
+ catch {
145
+ /* already gone */
146
+ }
147
+ this.proc = null;
148
+ }
149
+ }
Binary file
@@ -0,0 +1,60 @@
1
+ // Operator observability — SPEC §12. Records METRICS ONLY (never prompt/response content): turn counts,
2
+ // tool-batch sizes + durations, self-heal events, and errors — the "is it healthy, what breaks" signal an
3
+ // enterprise deployment needs. Local-first: a silent append-only JSONL on the user's own disk by default
4
+ // (zero network, zero friction, best-effort — never throws, never blocks a turn). A remote sink is OPT-IN
5
+ // via KODE_TELEMETRY_URL (fire-and-forget POST). Disable entirely with telemetry.enabled=false.
6
+ import { appendFile, mkdir } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ import { join, dirname } from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ const DEFAULT_FILE = process.env.KODE_TELEMETRY_FILE ?? join(homedir(), ".axe", "operator", "telemetry.jsonl");
11
+ export class Telemetry {
12
+ enabled;
13
+ file;
14
+ endpoint;
15
+ session = randomUUID();
16
+ lastWrite = Promise.resolve(); // serialized so events land in order + flushed() awaits all
17
+ constructor(cfg = {}) {
18
+ this.enabled = cfg.enabled ?? true;
19
+ this.file = cfg.file ?? DEFAULT_FILE;
20
+ this.endpoint = process.env.KODE_TELEMETRY_URL ?? cfg.endpoint;
21
+ }
22
+ /** Record one metrics event. Best-effort: a disabled telemetry or any I/O failure is a silent no-op. */
23
+ record(ev) {
24
+ if (!this.enabled)
25
+ return;
26
+ const line = { ts: new Date().toISOString(), session: this.session, ...ev };
27
+ this.lastWrite = this.lastWrite.then(() => this.write(line)); // chain: ordered + awaitable via flushed()
28
+ }
29
+ /** Resolves once all queued events have been written. The app never awaits this (telemetry is
30
+ * best-effort); it makes telemetry deterministically testable without sleeping. */
31
+ flushed() {
32
+ return this.lastWrite;
33
+ }
34
+ async write(line) {
35
+ try {
36
+ await mkdir(dirname(this.file), { recursive: true });
37
+ await appendFile(this.file, JSON.stringify(line) + "\n", "utf8");
38
+ }
39
+ catch {
40
+ /* local telemetry is best-effort */
41
+ }
42
+ if (this.endpoint) {
43
+ try {
44
+ const ctrl = new AbortController();
45
+ const t = setTimeout(() => ctrl.abort(), 3000);
46
+ await fetch(this.endpoint, { method: "POST", signal: ctrl.signal, headers: { "content-type": "application/json" }, body: JSON.stringify(line) }).catch(() => { });
47
+ clearTimeout(t);
48
+ }
49
+ catch {
50
+ /* remote sink is fire-and-forget; a down endpoint never affects the turn */
51
+ }
52
+ }
53
+ }
54
+ /** The Error's class (name) or first token — NEVER the message (which could carry paths/data). */
55
+ static errorClass(e) {
56
+ if (e instanceof Error)
57
+ return e.name || e.constructor?.name || "Error";
58
+ return String(e).split(/[:\s]/)[0]?.slice(0, 40) || "unknown";
59
+ }
60
+ }
@@ -0,0 +1,50 @@
1
+ // Append-only audit log for agent tool actions — SPEC §11. One JSONL line per tool call: what ran, the
2
+ // decision, the outcome. This is the "who did what" trail an enterprise security review requires. Writes
3
+ // ONLY when the policy audits (audit/gated mode) — in bypass it's never constructed, so the owner's
4
+ // default experience writes nothing. Best-effort: a log-write failure never blocks or fails a turn.
5
+ // node:fs/os/path are imported LAZILY inside record() (not at module top) so this module stays node-free
6
+ // at load time — that keeps it safe to export from the browser/JSCore engine bundle (index.browser.ts),
7
+ // where a client injects its own audit sink and never hits the file path. Only the Node CLI writes files.
8
+ //
9
+ // The specifier MUST route through this indirection, never a literal import("node:fs/promises"): esbuild
10
+ // --platform=neutral (the SPEC/conformance run-jsc.sh gate) statically resolves a literal import() at
11
+ // build time and fails the node-free bundle. A variable specifier is opaque to that analysis, so esbuild
12
+ // leaves it a true runtime import — the node branch never runs in JSCore, so the browser bundle stays clean.
13
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
14
+ const DEFAULT_FILE = process.env.KODE_AUDIT_FILE ?? "~/.axe/operator/audit.jsonl";
15
+ /** Summarize args for the log without leaking secrets or bloating the line. Keeps the shape a reviewer
16
+ * needs (which path, which command head) and drops values that could be sensitive. */
17
+ export function digestArgs(_name, args) {
18
+ const s = (v, n = 120) => (typeof v === "string" ? v : JSON.stringify(v ?? "")).slice(0, n);
19
+ if (typeof args.command === "string")
20
+ return `$ ${s(args.command)}`;
21
+ if (Array.isArray(args.args))
22
+ return `git ${s(args.args.join(" "))}`;
23
+ if (typeof args.path === "string")
24
+ return s(args.path, 200);
25
+ if (typeof args.url === "string")
26
+ return s(args.url, 200);
27
+ const keys = Object.keys(args);
28
+ return keys.length ? `{${keys.join(",")}}` : "";
29
+ }
30
+ export class AuditLog {
31
+ file;
32
+ constructor(file = DEFAULT_FILE) {
33
+ this.file = file;
34
+ }
35
+ /** Append one entry. Never throws (best-effort observability, not a gate). node:fs is imported here,
36
+ * lazily, so the module is node-free at load (browser/JSCore bundle safe). */
37
+ async record(entry) {
38
+ try {
39
+ const [{ appendFile, mkdir }, os, { join, dirname }] = await Promise.all([
40
+ nodeImport("node:fs/promises"), nodeImport("node:os"), nodeImport("node:path"),
41
+ ]);
42
+ const file = this.file.startsWith("~/") ? join(os.homedir(), this.file.slice(2)) : this.file;
43
+ await mkdir(dirname(file), { recursive: true });
44
+ await appendFile(file, JSON.stringify(entry) + "\n", "utf8");
45
+ }
46
+ catch {
47
+ /* audit is best-effort — no fs (browser) or a write failure must never break a turn */
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,48 @@
1
+ import { AuditLog, digestArgs } from "./audit.js";
2
+ export { PermissionPolicy } from "./policy.js";
3
+ const DENIED = (name) => `Permission denied: "${name}" was refused by the operator permission policy. ` +
4
+ `Ask the user to approve it, or run in a mode that allows it.`;
5
+ export function withPermissions(inner, policy, opts = {}) {
6
+ if (policy.inert)
7
+ return inner; // bypass + no rules → nothing to enforce or log; skip the layer entirely
8
+ const audit = policy.audits ? opts.audit ?? new AuditLog() : undefined;
9
+ async function gate(name, args, exec) {
10
+ const decision = policy.decide(name, args);
11
+ const t0 = performance.now();
12
+ if (decision === "deny") {
13
+ await audit?.record(mk(name, args, decision, "denied", { approved: false }));
14
+ return DENIED(name);
15
+ }
16
+ let approved;
17
+ if (decision === "ask") {
18
+ approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
19
+ if (!approved) {
20
+ await audit?.record(mk(name, args, decision, "denied", { approved: false }));
21
+ return DENIED(name);
22
+ }
23
+ }
24
+ let result;
25
+ try {
26
+ result = await exec();
27
+ }
28
+ catch (e) {
29
+ // The inner executor's contract is resolve-not-reject; if one ever throws, record + surface as a string.
30
+ await audit?.record(mk(name, args, decision, "error", { approved, durationMs: performance.now() - t0 }));
31
+ return `error: ${e instanceof Error ? e.message : String(e)}`;
32
+ }
33
+ const outcome = /^error/i.test(result.trim()) ? "error" : "ok";
34
+ await audit?.record(mk(name, args, decision, outcome, { approved, durationMs: performance.now() - t0 }));
35
+ return result;
36
+ }
37
+ return {
38
+ execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
39
+ executeParallel: (calls) =>
40
+ // Gate each call individually (its own decision + audit), preserving order. We can't hand a
41
+ // pre-denied call to inner.executeParallel, so route per-call through execute (the executor's
42
+ // own read-only/mutating parallelism still applies to the ones that reach it via execute).
43
+ Promise.all(calls.map((c) => gate(c.name, c.args, () => inner.execute(c.name, c.args)))),
44
+ };
45
+ }
46
+ function mk(tool, args, decision, outcome, extra) {
47
+ return { ts: new Date().toISOString(), tool, args: digestArgs(tool, args), decision, outcome, ...extra };
48
+ }
@@ -0,0 +1,54 @@
1
+ // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise.
2
+ const DEFAULT_SAFE = ["file_read", "grep_search", "list_directory", "memory_search", "web_fetch"];
3
+ // Genuinely destructive shell shapes — in "gated" these escalate a would-be "allow" to "ask" even for
4
+ // an allow-listed tool. Deliberately small + conservative (false positives just add one approval).
5
+ const DANGEROUS = [
6
+ /\brm\s+-[a-z]*r[a-z]*f?\b/i, // rm -rf …
7
+ /\bgit\s+push\b.*--force|\b--force\b.*\bpush\b/i,
8
+ /\b(mkfs|dd)\b/i,
9
+ /\bshutdown\b|\breboot\b/i,
10
+ /:\(\)\s*\{.*\}\s*;/, // fork bomb
11
+ /\bchmod\s+-R\s+0?00\b/i,
12
+ />\s*\/dev\/sd[a-z]/i,
13
+ ];
14
+ function looksDangerous(_name, args) {
15
+ const cmd = typeof args.command === "string" ? args.command : "";
16
+ const gitArgs = Array.isArray(args.args) ? args.args.join(" ") : "";
17
+ const blob = `${cmd} ${gitArgs}`;
18
+ return blob.trim().length > 0 && DANGEROUS.some((re) => re.test(blob));
19
+ }
20
+ export class PermissionPolicy {
21
+ mode;
22
+ rules;
23
+ safe;
24
+ constructor(cfg = {}) {
25
+ this.mode = cfg.mode ?? "bypass";
26
+ this.rules = cfg.rules ?? {};
27
+ this.safe = new Set(cfg.safeTools ?? DEFAULT_SAFE);
28
+ }
29
+ /** True when the policy can never block or prompt — lets the wrapper skip itself entirely (no overhead). */
30
+ get inert() {
31
+ return this.mode === "bypass" && Object.keys(this.rules).length === 0;
32
+ }
33
+ /** Whether tool actions should be recorded (audit.ts). Off in bypass; on in audit/gated. */
34
+ get audits() {
35
+ return this.mode !== "bypass";
36
+ }
37
+ currentMode() {
38
+ return this.mode;
39
+ }
40
+ /** The decision for one tool call. A per-tool rule always wins; otherwise mode drives it. */
41
+ decide(name, args) {
42
+ const rule = this.rules[name];
43
+ if (rule)
44
+ return rule; // explicit override — highest precedence
45
+ if (this.mode === "bypass" || this.mode === "audit")
46
+ return "allow"; // audit records but never blocks
47
+ // "gated": read-only tools run; mutating tools ask; a dangerous shell shape always asks.
48
+ if (this.safe.has(name))
49
+ return "allow";
50
+ if (looksDangerous(name, args))
51
+ return "ask";
52
+ return "ask"; // any mutating tool
53
+ }
54
+ }
@@ -0,0 +1,94 @@
1
+ // ONE model: Aurora at its native 1M context on :8097 (the air/1m/saddle roster collapsed here once 1M
2
+ // served at full speed). The router still handles N endpoints generically; this default just has one.
3
+ const DEFAULT_ENDPOINTS = [
4
+ { name: "aurora", base: "http://127.0.0.1:8097", model: "aurora", ctxLimit: 1048576 },
5
+ ];
6
+ // Leave headroom under the hard ctx limit — mirrors SPEC §5's 0.85 compaction threshold, so
7
+ // routing and compaction agree on what "fits."
8
+ const FIT_MARGIN = 0.85;
9
+ export class AuroraRouter {
10
+ endpoints;
11
+ idx = 0;
12
+ unhealthy = new Set();
13
+ pinned = process.env.KODE_NO_ROUTER === "1";
14
+ constructor(endpoints = DEFAULT_ENDPOINTS) {
15
+ if (!endpoints.length)
16
+ throw new Error("AuroraRouter needs at least one endpoint");
17
+ this.endpoints = endpoints;
18
+ }
19
+ current() {
20
+ return this.endpoints[this.idx];
21
+ }
22
+ get base() {
23
+ return this.current().base;
24
+ }
25
+ get model() {
26
+ return this.current().model;
27
+ }
28
+ ctxLimit() {
29
+ return this.current().ctxLimit;
30
+ }
31
+ routeBySize(approxTokens) {
32
+ if (this.pinned)
33
+ return this.current();
34
+ for (let i = this.idx; i < this.endpoints.length; i++) {
35
+ if (approxTokens <= this.endpoints[i].ctxLimit * FIT_MARGIN) {
36
+ this.idx = i;
37
+ return this.current();
38
+ }
39
+ }
40
+ // Nothing fits even at the largest endpoint — best effort, let compaction/self-heal handle it.
41
+ this.idx = this.endpoints.length - 1;
42
+ return this.current();
43
+ }
44
+ escalate() {
45
+ if (this.pinned)
46
+ return this.current();
47
+ this.idx = this.endpoints.length - 1;
48
+ return this.current();
49
+ }
50
+ failover() {
51
+ if (this.pinned)
52
+ return this.current();
53
+ const failed = this.current().name;
54
+ this.unhealthy.add(failed);
55
+ const candidate = this.endpoints.find(e => e.name !== failed && !this.unhealthy.has(e.name))
56
+ ?? this.endpoints.find(e => e.name !== failed)
57
+ ?? this.current();
58
+ this.idx = this.endpoints.indexOf(candidate);
59
+ return this.current();
60
+ }
61
+ // Extensions beyond the frozen Router interface, for the engine's self-heal bookkeeping.
62
+ markHealthy(name) {
63
+ this.unhealthy.delete(name);
64
+ }
65
+ /** All configured endpoints (for /endpoints). */
66
+ list() {
67
+ return this.endpoints;
68
+ }
69
+ /** Currently-selected endpoint's name (for the /route display). */
70
+ currentName() {
71
+ return this.current().name;
72
+ }
73
+ /** Pin routing to a named endpoint, or pass undefined/"auto" to restore size-based routing (for /route). */
74
+ pin(name) {
75
+ if (!name || name === "auto") {
76
+ this.pinned = false;
77
+ return true;
78
+ }
79
+ const i = this.endpoints.findIndex((e) => e.name === name);
80
+ if (i < 0)
81
+ return false;
82
+ this.idx = i;
83
+ this.pinned = true;
84
+ return true;
85
+ }
86
+ // Call at a turn boundary (or after a compaction that shrank the conversation) to let
87
+ // routeBySize re-evaluate from the smallest endpoint, and to clear the per-turn unhealthy set so
88
+ // an endpoint that had a transient failure last turn isn't permanently blacklisted from failover.
89
+ resetTurn() {
90
+ this.unhealthy.clear();
91
+ if (!this.pinned)
92
+ this.idx = 0;
93
+ }
94
+ }