@0perator/operator 0.1.26 → 0.1.28

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/cli.js CHANGED
@@ -13,11 +13,12 @@ import { Session } from "./session.js";
13
13
  import { AuroraRouter } from "./router/router.js";
14
14
  import { BackgroundAgents } from "./background/index.js";
15
15
  import { loadSettings } from "./config/settings.js";
16
+ import { EventSink } from "./telemetry/events.js";
16
17
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
17
18
  import { join } from "node:path";
18
19
  import { homedir, hostname } from "node:os";
19
20
  import { createHash } from "node:crypto";
20
- const VERSION = "0.1.26";
21
+ const VERSION = "0.1.28";
21
22
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
22
23
  const settings = loadSettings();
23
24
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -42,6 +43,9 @@ if (sd) {
42
43
  if (sd.idleSec !== undefined)
43
44
  process.env.KODE_SEARXNG_IDLE_SEC = String(sd.idleSec);
44
45
  }
46
+ // The searxng module reads this env flag in its own sync exit hook; project the setting so it applies.
47
+ if (settings.services?.stopOnExit?.searxng === false)
48
+ process.env.KODE_STOP_SEARXNG_ON_EXIT = "0";
45
49
  // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
46
50
  // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
47
51
  // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
@@ -76,6 +80,15 @@ try {
76
80
  }
77
81
  catch { /* best-effort; the write is guarded too */ }
78
82
  const RESUME = process.argv.includes("--resume") || process.argv.includes("-r") || process.env.KODE_RESUME === "1";
83
+ // Shared frozen-OperatorEvent stream (telemetry/events.ts) — the ONE sink for the whole session: tool +
84
+ // control events (emitted by the permission wrapper when enforcing), plus turn / service / remote-control
85
+ // events emitted below. Writes local JSONL + POSTs to KODE_TELEMETRY_URL if set (the dashboard's feed).
86
+ // The sink always exists so the audit trail works even with telemetry off; turn/service events are gated
87
+ // on telemetry.enabled so the metrics stream honors the off switch.
88
+ const SESSION_ID = createHash("sha1").update(`${process.cwd()}:${Date.now()}`).digest("hex").slice(0, 12);
89
+ const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: "cli" };
90
+ const eventSink = new EventSink();
91
+ const emitTelemetry = settings.telemetry.enabled !== false;
79
92
  // Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
80
93
  // and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
81
94
  // 1,048,576-token context at full speed). No size-based routing decision remains.
@@ -129,6 +142,7 @@ const HELP = [
129
142
  " /help this list",
130
143
  " /model current endpoint (aurora · 1M), context %, turn count",
131
144
  " /endpoints show the aurora endpoint + live health",
145
+ " /services ensure/inspect the service lever (aurora+autopilot+searxng); /services stop",
132
146
  " /compact force-compact the conversation now",
133
147
  " /remember <note> store a note to recall in future sessions",
134
148
  " /memory [query] show remembered notes (all, or matching query)",
@@ -152,6 +166,7 @@ const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim())
152
166
  function Root() {
153
167
  const { exit } = useApp();
154
168
  const [boot, setBoot] = useState("checking");
169
+ const [bootDetail, setBootDetail] = useState(""); // live line during the service-lever preflight
155
170
  const [entries, setEntries] = useState([]);
156
171
  const [live, setLive] = useState(null);
157
172
  const [status, setStatus] = useState("idle");
@@ -211,6 +226,7 @@ function Root() {
211
226
  permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
212
227
  approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
213
228
  telemetry: settings.telemetry, // local-only metrics by default
229
+ eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // frozen event stream (tool/control audit)
214
230
  // Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
215
231
  // sub-agent can't spawn more (no fork bombs). Cap at MAX_BG — all sub-agents share the one Aurora
216
232
  // endpoint, so past the cap we refuse with guidance rather than thrash the shared KV cache.
@@ -266,9 +282,27 @@ function Root() {
266
282
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
267
283
  }, [session]);
268
284
  useEffect(() => {
269
- session.health().then((ok) => {
285
+ void (async () => {
286
+ // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
287
+ // health, so a cold box self-heals instead of dropping the owner at "start it yourself and relaunch".
288
+ let reports = [];
289
+ try {
290
+ const { ensureServices } = await import("./services/preflight.js");
291
+ reports = await ensureServices({
292
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
293
+ autopilot: settings.services?.autopilot,
294
+ onProgress: setBootDetail,
295
+ });
296
+ }
297
+ catch { /* preflight is best-effort — fall through to the authoritative health check */ }
298
+ const ok = await session.health().catch(() => false);
270
299
  setBoot(ok ? "ready" : "down");
271
- if (ok && RESUME) {
300
+ if (!ok) {
301
+ const a = reports.find((r) => r.name === "aurora");
302
+ setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
303
+ return;
304
+ }
305
+ if (RESUME) {
272
306
  try {
273
307
  const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
274
308
  if (session.restore(saved)) {
@@ -282,7 +316,18 @@ function Root() {
282
316
  }
283
317
  catch { /* no saved session to resume */ }
284
318
  }
285
- }).catch(() => setBoot("down"));
319
+ // Feed the service-lever outcome to the frozen event stream (dashboard service-health tiles).
320
+ if (emitTelemetry) {
321
+ for (const r of reports) {
322
+ const state = r.state === "started" ? "started" : r.state === "up" ? "up" : "down";
323
+ eventSink.emit({ kind: "service", session: SESSION_ID, actor: EVENT_ACTOR, service: { name: r.name, state } });
324
+ }
325
+ }
326
+ // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
327
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
328
+ if (line)
329
+ push({ kind: "message", message: { id: nextId(), role: "system", content: `services: ${line} · searxng lazy` } });
330
+ })();
286
331
  }, []);
287
332
  // Show who's signed in (best-effort, non-blocking): load stored creds, verify against the backend.
288
333
  useEffect(() => {
@@ -377,8 +422,14 @@ function Root() {
377
422
  // Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
378
423
  if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
379
424
  const tok = outcome.tokens ?? 0;
380
- const secs = (outcome.durationMs ?? 0) / 1000;
425
+ const durationMs = outcome.durationMs ?? 0;
426
+ const secs = durationMs / 1000;
381
427
  setMetrics(fmtMeta(secs, tok));
428
+ // Feed the same numbers to the frozen event stream (dashboard + mobile). Gated on telemetry.enabled.
429
+ if (emitTelemetry) {
430
+ eventSink.emit({ kind: "turn", session: SESSION_ID, actor: EVENT_ACTOR,
431
+ turn: { tokens: tok, tokPerSec: secs > 0 ? Math.round(tok / secs) : undefined, ctxPct: session.ctxPct(), route: session.currentRoute(), durationMs } });
432
+ }
382
433
  }
383
434
  }
384
435
  catch (e) {
@@ -493,6 +544,24 @@ function Root() {
493
544
  sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
494
545
  break;
495
546
  }
547
+ case "services": {
548
+ // The lever, on demand: `/services` probes + starts any down launchd service; `/services stop`
549
+ // tears down only the session-scoped SearXNG (Aurora/autopilot are shared and stay up).
550
+ if (arg === "stop") {
551
+ const { stopSessionServices } = await import("./services/preflight.js");
552
+ await stopSessionServices({ searxng: true });
553
+ sys("stopped session-scoped services (SearXNG). Aurora + autopilot are shared and stay up.");
554
+ break;
555
+ }
556
+ sys("checking services…");
557
+ const { ensureServices } = await import("./services/preflight.js");
558
+ const reports = await ensureServices({
559
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
560
+ autopilot: settings.services?.autopilot,
561
+ });
562
+ sys("services:\n" + reports.map((r) => ` ${r.state === "up" || r.state === "started" ? "●" : "○"} ${r.name} ${r.state}${r.detail ? " " + r.detail : ""}`).join("\n") + "\n · searxng: lazy (starts on first web_search, stops on idle/exit)");
563
+ break;
564
+ }
496
565
  case "bg":
497
566
  if (!arg) {
498
567
  const l = bg.list();
@@ -530,6 +599,11 @@ function Root() {
530
599
  sys(`remote control error: ${detail ?? "connection lost"} — /remotecontrol to retry`);
531
600
  else if (st === "closed")
532
601
  sys("remote control disconnected");
602
+ // Frozen event stream: the persistent RC indicator + dashboard read these control events.
603
+ if (st === "live")
604
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_connected", detail: rh.id ?? undefined } });
605
+ else if (st === "closed" || st === "error")
606
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "rc_disconnected", detail } });
533
607
  },
534
608
  });
535
609
  remoteRef.current = rh;
@@ -570,9 +644,9 @@ function Root() {
570
644
  return () => clearInterval(id);
571
645
  }, [status]);
572
646
  if (boot === "checking")
573
- return _jsx(Text, { dimColor: true, children: "connecting to Aurora\u2026" });
647
+ return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Aurora…" });
574
648
  if (boot === "down") {
575
- 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." })] }));
649
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Aurora on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsx(Text, { dimColor: true, children: "Aurora is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/com.imi.aurora-serve" })] }));
576
650
  }
577
651
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
578
652
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -26,6 +26,13 @@ const DEFAULTS = {
26
26
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
27
27
  computer: { enabled: false }, // computer control OFF by default; enable with KODE_COMPUTER=1 or settings.json
28
28
  search: {}, // web_search backend unset by default; set search.searxngUrl / search.autopilotUrl or the env vars
29
+ // Service lever — JL1 defaults. On a machine without these launchd agents every start step just fails
30
+ // harmlessly and the boot screen falls back to the manual hint (autostart is best-effort by design).
31
+ services: {
32
+ aurora: { autostart: true, launchdLabel: "com.imi.aurora-serve", plistPath: "~/Library/LaunchAgents/com.imi.aurora-serve.plist", waitSec: 90 },
33
+ autopilot: { autostart: true, launchdLabel: "com.axe.autopilot", plistPath: "~/Library/LaunchAgents/com.axe.autopilot.plist", url: "http://127.0.0.1:9333" },
34
+ stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
35
+ },
29
36
  };
30
37
  function settingsPath() {
31
38
  return process.env.KODE_TSI_SETTINGS ?? join(homedir(), ".axe", "operator", "settings.json");
@@ -56,7 +63,7 @@ function readSettingsFile(path) {
56
63
  /** Fold env vars over the file+default merge — the top layer of the precedence stack. Only an env
57
64
  * var that's actually set overrides; an unset one leaves the file/default value alone. */
58
65
  function applyEnv(s) {
59
- const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox }, computer: { ...s.computer }, search: { ...s.search } };
66
+ const out = { ...s, endpoints: { ...s.endpoints }, memory: { ...s.memory }, permissions: { ...s.permissions }, telemetry: { ...s.telemetry }, sandbox: { ...s.sandbox }, computer: { ...s.computer }, search: { ...s.search }, services: s.services ? structuredClone(s.services) : undefined };
60
67
  if (process.env.KODE_MODEL)
61
68
  out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, model: process.env.KODE_MODEL } }; // AI-agnostic quick-swap (keeps failover)
62
69
  const base = process.env.KODE_AURORA ?? process.env.KODE_1M; // KODE_1M kept as a back-compat alias for the base override
@@ -69,6 +76,9 @@ function applyEnv(s) {
69
76
  const pm = process.env.KODE_PERMISSIONS;
70
77
  if (pm === "bypass" || pm === "audit" || pm === "gated")
71
78
  out.permissions = { ...out.permissions, mode: pm };
79
+ const tier = process.env.KODE_TIER; // identity tool-tier ceiling (admin=full fleet, enterprise=core+skills, readonly=inspect)
80
+ if (tier === "admin" || tier === "enterprise" || tier === "readonly")
81
+ out.permissions = { ...out.permissions, tier };
72
82
  if (process.env.KODE_TELEMETRY === "0")
73
83
  out.telemetry = { ...out.telemetry, enabled: false };
74
84
  const sb = process.env.KODE_SANDBOX;
@@ -76,6 +86,20 @@ function applyEnv(s) {
76
86
  out.sandbox = { mode: sb };
77
87
  if (process.env.KODE_COMPUTER === "1")
78
88
  out.computer = { enabled: true };
89
+ // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of BOTH launchd services (Operator then
90
+ // only probes + reports); KODE_STOP_SEARXNG_ON_EXIT=0 keeps the SearXNG container running after exit.
91
+ if (out.services) {
92
+ if (process.env.KODE_SERVICES_AUTOSTART === "0") {
93
+ out.services = {
94
+ ...out.services,
95
+ aurora: { ...out.services.aurora, autostart: false },
96
+ autopilot: { ...out.services.autopilot, autostart: false },
97
+ };
98
+ }
99
+ if (process.env.KODE_STOP_SEARXNG_ON_EXIT === "0") {
100
+ out.services = { ...out.services, stopOnExit: { ...out.services.stopOnExit, searxng: false } };
101
+ }
102
+ }
79
103
  if (process.env.KODE_AUTOPILOT_URL || process.env.KODE_SEARXNG_URL) {
80
104
  out.search = {
81
105
  ...out.search,
@@ -1,8 +1,10 @@
1
1
  // Operator observability — SPEC §12. Records METRICS ONLY (never prompt/response content): turn counts,
2
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.
3
+ // enterprise deployment needs. LOCAL-ONLY: a silent append-only JSONL on the user's own disk (zero
4
+ // network, best-effort — never throws, never blocks a turn); disable with telemetry.enabled=false. The
5
+ // REMOTE sink is now the frozen OperatorEvent stream (telemetry/events.ts, EventSink) which is the single
6
+ // poster to KODE_TELEMETRY_URL — one wire shape for mobile, the dashboard, and the audit log; this module
7
+ // no longer POSTs its own ad-hoc shape to that URL (that would collide with the frozen stream).
6
8
  import { appendFile, mkdir } from "node:fs/promises";
7
9
  import { homedir } from "node:os";
8
10
  import { join, dirname } from "node:path";
@@ -11,13 +13,13 @@ const DEFAULT_FILE = process.env.KODE_TELEMETRY_FILE ?? join(homedir(), ".axe",
11
13
  export class Telemetry {
12
14
  enabled;
13
15
  file;
14
- endpoint;
15
16
  session = randomUUID();
16
17
  lastWrite = Promise.resolve(); // serialized so events land in order + flushed() awaits all
17
18
  constructor(cfg = {}) {
18
19
  this.enabled = cfg.enabled ?? true;
19
20
  this.file = cfg.file ?? DEFAULT_FILE;
20
- this.endpoint = process.env.KODE_TELEMETRY_URL ?? cfg.endpoint;
21
+ // cfg.endpoint / KODE_TELEMETRY_URL are intentionally NOT read here anymore — the remote sink is the
22
+ // frozen OperatorEvent stream (EventSink), the single poster to that URL. This module stays local-only.
21
23
  }
22
24
  /** Record one metrics event. Best-effort: a disabled telemetry or any I/O failure is a silent no-op. */
23
25
  record(ev) {
@@ -39,17 +41,6 @@ export class Telemetry {
39
41
  catch {
40
42
  /* local telemetry is best-effort */
41
43
  }
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
44
  }
54
45
  /** The Error's class (name) or first token — NEVER the message (which could carry paths/data). */
55
46
  static errorClass(e) {
@@ -1,17 +1,7 @@
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";
1
+ // Safe argument digest for the audit trail. The permission wrapper (index.ts) records one OperatorEvent
2
+ // per tool call (telemetry/events.ts is the sink + wire shape); this keeps the argument-summarizing that
3
+ // a "who did what" review needs while never leaking secrets or bloating the line. Pure + node-free, so it
4
+ // is safe to import from any bundle (the CLI and the JSCore/browser engine alike).
15
5
  /** Summarize args for the log without leaking secrets or bloating the line. Keeps the shape a reviewer
16
6
  * needs (which path, which command head) and drops values that could be sensitive. */
17
7
  export function digestArgs(_name, args) {
@@ -27,24 +17,3 @@ export function digestArgs(_name, args) {
27
17
  const keys = Object.keys(args);
28
18
  return keys.length ? `{${keys.join(",")}}` : "";
29
19
  }
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
- }
@@ -1,23 +1,36 @@
1
- import { AuditLog, digestArgs } from "./audit.js";
1
+ import { digestArgs } from "./audit.js";
2
+ import { EventSink } from "../telemetry/events.js";
2
3
  export { PermissionPolicy } from "./policy.js";
3
4
  const DENIED = (name) => `Permission denied: "${name}" was refused by the operator permission policy. ` +
4
5
  `Ask the user to approve it, or run in a mode that allows it.`;
6
+ const TIER_DENIED = (name, tier) => `Permission denied: "${name}" is not available on the "${tier}" tier. ` +
7
+ `This seat has a narrowed toolset; a full-access (admin) seat is required for this tool.`;
5
8
  export function withPermissions(inner, policy, opts = {}) {
6
9
  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;
10
+ return inner; // bypass + admin tier + no rules → nothing to enforce or log; skip entirely
11
+ const sink = policy.audits ? opts.sink ?? new EventSink() : undefined;
12
+ const actor = opts.actor ?? { tier: policy.currentTier(), surface: "cli" };
13
+ const session = opts.session ?? "";
14
+ const tool = (t) => sink?.emit({ kind: "tool", session, actor, tool: t });
9
15
  async function gate(name, args, exec) {
16
+ const digest = digestArgs(name, args);
10
17
  const decision = policy.decide(name, args);
11
18
  const t0 = performance.now();
12
19
  if (decision === "deny") {
13
- await audit?.record(mk(name, args, decision, "denied", { approved: false }));
20
+ // Distinguish a tier-ceiling denial (this seat can't have the tool at all) from a rule/mode denial.
21
+ if (!policy.allowsTool(name)) {
22
+ sink?.emit({ kind: "control", session, actor, control: { event: "tool_denied_by_tier", detail: `${name} @ ${actor.tier}` } });
23
+ tool({ name, args: digest, decision, outcome: "denied", approved: false });
24
+ return TIER_DENIED(name, actor.tier);
25
+ }
26
+ tool({ name, args: digest, decision, outcome: "denied", approved: false });
14
27
  return DENIED(name);
15
28
  }
16
29
  let approved;
17
30
  if (decision === "ask") {
18
31
  approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
19
32
  if (!approved) {
20
- await audit?.record(mk(name, args, decision, "denied", { approved: false }));
33
+ tool({ name, args: digest, decision, outcome: "denied", approved: false });
21
34
  return DENIED(name);
22
35
  }
23
36
  }
@@ -27,22 +40,19 @@ export function withPermissions(inner, policy, opts = {}) {
27
40
  }
28
41
  catch (e) {
29
42
  // 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 }));
43
+ tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0 });
31
44
  return `error: ${e instanceof Error ? e.message : String(e)}`;
32
45
  }
33
46
  const outcome = /^error/i.test(result.trim()) ? "error" : "ok";
34
- await audit?.record(mk(name, args, decision, outcome, { approved, durationMs: performance.now() - t0 }));
47
+ tool({ name, args: digest, decision, outcome, approved, durationMs: performance.now() - t0 });
35
48
  return result;
36
49
  }
37
50
  return {
38
51
  execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
39
52
  executeParallel: (calls) =>
40
- // Gate each call individually (its own decision + audit), preserving order. We can't hand a
53
+ // Gate each call individually (its own decision + event), preserving order. We can't hand a
41
54
  // pre-denied call to inner.executeParallel, so route per-call through execute (the executor's
42
55
  // own read-only/mutating parallelism still applies to the ones that reach it via execute).
43
56
  Promise.all(calls.map((c) => gate(c.name, c.args, () => inner.execute(c.name, c.args)))),
44
57
  };
45
58
  }
46
- function mk(tool, args, decision, outcome, extra) {
47
- return { ts: new Date().toISOString(), tool, args: digestArgs(tool, args), decision, outcome, ...extra };
48
- }
@@ -1,3 +1,9 @@
1
+ // Operator permission policy — SPEC §11 (agent safety). Decides, per tool call, whether it may run,
2
+ // must be approved, or is refused. DESIGNED TO BE INERT BY DEFAULT: mode "bypass" (the default) allows
3
+ // everything with no prompt and no log — zero gates, zero overhead — so the owner's experience is
4
+ // unchanged until they deliberately turn enforcement on. Enterprise deployments flip mode to "gated"
5
+ // (mutating tools require approval) or tighten `rules`; "audit" allows-but-records (see audit.ts).
6
+ import { tierAllows } from "./tier.js";
1
7
  // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise.
2
8
  const DEFAULT_SAFE = ["file_read", "grep_search", "list_directory", "memory_search", "web_fetch"];
3
9
  // Genuinely destructive shell shapes — in "gated" these escalate a would-be "allow" to "ask" even for
@@ -21,27 +27,42 @@ export class PermissionPolicy {
21
27
  mode;
22
28
  rules;
23
29
  safe;
30
+ tier;
24
31
  constructor(cfg = {}) {
25
32
  this.mode = cfg.mode ?? "bypass";
26
33
  this.rules = cfg.rules ?? {};
27
34
  this.safe = new Set(cfg.safeTools ?? DEFAULT_SAFE);
35
+ this.tier = cfg.tier ?? "admin";
28
36
  }
29
- /** True when the policy can never block or prompt — lets the wrapper skip itself entirely (no overhead). */
37
+ /** True when the policy can never block, prompt, or log — lets the wrapper skip itself entirely (no
38
+ * overhead). Requires the full-access owner tier: a narrowed tier is always enforced, even in bypass. */
30
39
  get inert() {
31
- return this.mode === "bypass" && Object.keys(this.rules).length === 0;
40
+ return this.mode === "bypass" && this.tier === "admin" && Object.keys(this.rules).length === 0;
32
41
  }
33
- /** Whether tool actions should be recorded (audit.ts). Off in bypass; on in audit/gated. */
42
+ /** Whether tool actions should be recorded. On in audit/gated, or whenever a tier is enforced (a
43
+ * multi-tenant seat is always audited — "who did what" is the point of a seat). */
34
44
  get audits() {
35
- return this.mode !== "bypass";
45
+ return this.mode !== "bypass" || this.tier !== "admin";
36
46
  }
37
47
  currentMode() {
38
48
  return this.mode;
39
49
  }
40
- /** The decision for one tool call. A per-tool rule always wins; otherwise mode drives it. */
50
+ currentTier() {
51
+ return this.tier;
52
+ }
53
+ /** True iff `name` is within this identity's tier ceiling. A tool outside it can never run, even with a
54
+ * per-tool "allow" rule — the tier is the security boundary, rules only narrow within it. */
55
+ allowsTool(name) {
56
+ return tierAllows(this.tier, name);
57
+ }
58
+ /** The decision for one tool call. Tier ceiling first (a denied tool can't be granted by any rule),
59
+ * then an explicit per-tool rule, then mode. */
41
60
  decide(name, args) {
61
+ if (!this.allowsTool(name))
62
+ return "deny"; // tier ceiling — absolute, above rules and mode
42
63
  const rule = this.rules[name];
43
64
  if (rule)
44
- return rule; // explicit override — highest precedence
65
+ return rule; // explicit override within the tier
45
66
  if (this.mode === "bypass" || this.mode === "audit")
46
67
  return "allow"; // audit records but never blocks
47
68
  // "gated": read-only tools run; mutating tools ask; a dangerous shell shape always asks.
@@ -0,0 +1,28 @@
1
+ // Enterprise seat: core coding + skills hub. An ALLOWLIST by design — anything not named here (fleet MCP
2
+ // tools mcp__*, computer_* control, future privileged tools) is denied, so new tools are safe-by-default.
3
+ const ENTERPRISE_ALLOW = new Set([
4
+ "file_read", "file_write", "file_edit", "grep_search", "list_directory",
5
+ "shell_exec", "shell_background", "bash_output", "bash_kill",
6
+ "git_command", "checkpoint", "task_add", "task_list", "task_update",
7
+ "memory_search", "memory_store", "web_fetch", "web_search",
8
+ "skill_list", "skill_fetch", "skill_save",
9
+ ]);
10
+ // Readonly seat: inspection only (a superset-safe subset of the enterprise allowlist).
11
+ const READONLY_ALLOW = new Set([
12
+ "file_read", "grep_search", "list_directory", "bash_output", "task_list",
13
+ "memory_search", "web_fetch", "web_search", "skill_list", "skill_fetch",
14
+ ]);
15
+ export const TIERS = ["admin", "enterprise", "readonly"];
16
+ export function isTier(v) {
17
+ return v === "admin" || v === "enterprise" || v === "readonly";
18
+ }
19
+ /** Whether `tool` is within `tier`'s grant. admin = everything; the others are explicit allowlists so any
20
+ * unlisted tool (including every dynamically-named MCP fleet tool) is denied by default. */
21
+ export function tierAllows(tier, tool) {
22
+ switch (tier) {
23
+ case "admin": return true;
24
+ case "enterprise": return ENTERPRISE_ALLOW.has(tool);
25
+ case "readonly": return READONLY_ALLOW.has(tool);
26
+ default: return false;
27
+ }
28
+ }
@@ -0,0 +1,121 @@
1
+ // Session service lever — Operator ensures its supporting services are running on start, so a cold box
2
+ // never drops the owner into "go start it yourself and relaunch". CLI-only: every node:child_process
3
+ // import is LAZY via an opaque specifier (same discipline as tools/searxng.ts + tools/sandbox.ts) so the
4
+ // platform:neutral mobile JSCore bundle never resolves it — on mobile these functions simply no-op
5
+ // (there is no launchd; ensureServices returns everything "down" and the caller reports it).
6
+ //
7
+ // TWO tiers, and the split is the whole point:
8
+ // • Aurora (:8097) is SHARED, always-on infrastructure owned by launchd — the mobile app (via
9
+ // com.imi.aurora-tunnel), api.axe.onl / aurora.axe.onl, and LAN web clients all read it. Operator
10
+ // only ever brings it UP (kickstart, else bootstrap, the launchd job); it NEVER stops Aurora on exit,
11
+ // because that would break every other client. launchd's KeepAlive is the real supervisor — the
12
+ // lever just makes sure the job is loaded and the port is live before the REPL opens.
13
+ // • autopilot (:9333) is optional and handled the same start-only way (non-fatal if it won't come up).
14
+ // • SearXNG is session-scoped and owned by tools/searxng.ts (lazy start + idle/exit stop) — the only
15
+ // service Operator tears down, via stopSessionServices() below.
16
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
17
+ function expandHome(p) {
18
+ return p.startsWith("~/") ? `${process.env.HOME ?? ""}${p.slice(1)}` : p;
19
+ }
20
+ /** Run a launchctl subcommand, resolving { code, out }. Never throws (missing binary -> code 127). */
21
+ async function launchctl(args, timeoutMs = 15_000) {
22
+ const { execFile } = await nodeImport("node:child_process");
23
+ return new Promise((resolve) => {
24
+ const child = execFile("launchctl", args, { timeout: timeoutMs }, (err, stdout, stderr) => {
25
+ resolve({ code: err ? (typeof err.code === "number" ? err.code : 1) : 0, out: `${stdout || ""}${stderr || ""}`.trim() });
26
+ });
27
+ child.on?.("error", () => resolve({ code: 127, out: "launchctl not available" }));
28
+ });
29
+ }
30
+ /** Probe a health URL. `ready` = 2xx. `loading` = the port answered but not 2xx (llama.cpp serves 503
31
+ * while it mmaps the model — the service is coming up on its own and must NOT be restarted). `refused`
32
+ * = nothing is listening. When okOnly is false any answer counts as `ready` (autopilot has no /health). */
33
+ async function probe(url, okOnly, ms = 2500) {
34
+ const ctrl = new AbortController();
35
+ const t = setTimeout(() => ctrl.abort(), ms);
36
+ try {
37
+ const r = await fetch(url, { signal: ctrl.signal });
38
+ return r.ok || !okOnly ? "ready" : "loading";
39
+ }
40
+ catch {
41
+ return "refused";
42
+ }
43
+ finally {
44
+ clearTimeout(t);
45
+ }
46
+ }
47
+ /** Poll until the URL is `ready` or the budget runs out. Returns true iff it became ready. */
48
+ async function waitReady(url, okOnly, waitSec) {
49
+ for (let i = 0; i < waitSec; i += 2) {
50
+ if ((await probe(url, okOnly)) === "ready")
51
+ return true;
52
+ await new Promise((res) => setTimeout(res, 2000));
53
+ }
54
+ return (await probe(url, okOnly)) === "ready";
55
+ }
56
+ /** Bring a launchd-owned service up. If it is already loading on its own, just wait — never restart a
57
+ * mid-load model. If nothing is listening, restart the loaded job, else bootout any half-state and
58
+ * bootstrap the plist fresh, then poll. Best-effort by construction — on a machine without that agent
59
+ * every launchctl step fails and we return "down" with the reason so the caller shows the manual hint. */
60
+ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
61
+ const waitSec = cfg.waitSec ?? 45;
62
+ const first = await probe(healthUrl, okOnly);
63
+ if (first === "ready")
64
+ return { name, state: "up" };
65
+ // Already coming up on its own (Aurora /health = 503 while loading) — wait it out, do NOT restart.
66
+ if (first === "loading") {
67
+ onProgress?.(`${name} is loading…`);
68
+ return (await waitReady(healthUrl, okOnly, waitSec))
69
+ ? { name, state: "up" }
70
+ : { name, state: "down", detail: `${name} still loading after ${waitSec}s` };
71
+ }
72
+ if (cfg.autostart === false)
73
+ return { name, state: "down", detail: "down (autostart off)" };
74
+ const label = cfg.launchdLabel;
75
+ const uid = typeof process.getuid === "function" ? process.getuid() : NaN;
76
+ if (!label || Number.isNaN(uid))
77
+ return { name, state: "down", detail: "down (no launchd label/uid)" };
78
+ onProgress?.(`starting ${name} via launchd…`);
79
+ const target = `gui/${uid}/${label}`;
80
+ // 1) fast path: the job is loaded but its port died — kick it.
81
+ const kick = await launchctl(["kickstart", "-k", target]);
82
+ if (kick.code !== 0) {
83
+ // 2) not cleanly loaded — clear any half-state (bootout, ignore "no such process") then bootstrap
84
+ // the plist fresh and start it. Tolerate the known bootstrap I/O-error(5) race: the job usually
85
+ // still lands in the domain, so we poll the port regardless of the exit code.
86
+ if (!cfg.plistPath)
87
+ return { name, state: "down", detail: `down (kickstart failed: ${kick.out.slice(0, 80)}; no plistPath to bootstrap)` };
88
+ await launchctl(["bootout", target]).catch(() => undefined);
89
+ await new Promise((res) => setTimeout(res, 1500)); // let the old proc release the port + mlock
90
+ await launchctl(["enable", target]);
91
+ await launchctl(["bootstrap", `gui/${uid}`, expandHome(cfg.plistPath)]);
92
+ await launchctl(["kickstart", target]);
93
+ }
94
+ // 3) poll — a heavy model (Aurora is ~20G with mlock) needs time to mmap + report ready.
95
+ return (await waitReady(healthUrl, okOnly, waitSec))
96
+ ? { name, state: "started" }
97
+ : { name, state: "down", detail: `started the launchd job but ${name} did not report ready at ${healthUrl} within ${waitSec}s` };
98
+ }
99
+ /** Ensure the services Operator depends on are up. Aurora first (required, health-gated); autopilot is
100
+ * optional and never blocks. Returns one report per service for the boot UI. */
101
+ export async function ensureServices(cfg) {
102
+ const reports = [];
103
+ reports.push(await ensureLaunchd("aurora", `${cfg.aurora.base.replace(/\/$/, "")}/health`, true, cfg.aurora, cfg.onProgress));
104
+ if (cfg.autopilot) {
105
+ const url = (cfg.autopilot.url ?? "http://127.0.0.1:9333").replace(/\/$/, "");
106
+ reports.push(await ensureLaunchd("autopilot", `${url}/`, false, cfg.autopilot, cfg.onProgress));
107
+ }
108
+ return reports;
109
+ }
110
+ /** Tear down ONLY the session-scoped services on exit. Aurora and autopilot are shared, always-on, and
111
+ * owned by launchd — Operator never stops them (other clients depend on :8097). SearXNG is the one
112
+ * service Operator owns end to end. Best-effort; safe to call more than once. */
113
+ export async function stopSessionServices(opts) {
114
+ if (opts?.searxng === false)
115
+ return;
116
+ try {
117
+ const { stopManagedSearxng } = await import("../tools/searxng.js");
118
+ await stopManagedSearxng();
119
+ }
120
+ catch { /* mobile bundle / already stopped */ }
121
+ }
package/dist/session.js CHANGED
@@ -51,6 +51,9 @@ export class Session {
51
51
  policy;
52
52
  approve;
53
53
  telemetry;
54
+ eventSink;
55
+ eventActor;
56
+ sessionId;
54
57
  mcpSchemas = []; // merged in after first-turn discovery (empty until then)
55
58
  wantMcp;
56
59
  systemPrompt;
@@ -80,6 +83,9 @@ export class Session {
80
83
  this.policy = new PermissionPolicy(cfg.permissions);
81
84
  this.approve = cfg.approve;
82
85
  this.telemetry = new Telemetry(cfg.telemetry);
86
+ this.eventSink = cfg.eventSink;
87
+ this.eventActor = cfg.eventActor;
88
+ this.sessionId = cfg.sessionId;
83
89
  this.tools = this.buildTools(); // local-only until first-turn MCP discovery rebinds it
84
90
  }
85
91
  /** The effective system prompt: the base persona plus any memory recalled this session. Injected as
@@ -92,7 +98,7 @@ export class Session {
92
98
  /** Compose the tool executor: local tools + MCP (composite) with the permission/audit layer on top.
93
99
  * withPermissions returns the composite UNCHANGED when the policy is inert (bypass) — zero overhead. */
94
100
  buildTools() {
95
- return withPermissions(withMcp(this.executor, this.hub), this.policy, { approve: this.approve });
101
+ return withPermissions(withMcp(this.executor, this.hub), this.policy, { approve: this.approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
96
102
  }
97
103
  /** Is the currently-selected endpoint reachable? Lets the shell fail clearly before a turn. */
98
104
  health() {
@@ -0,0 +1,68 @@
1
+ // Operator event stream — the ONE frozen wire shape (v1) for everything a supervising human or dashboard
2
+ // needs to watch the agent swarm: tool calls (the audit trail), turns (telemetry), control-plane
3
+ // decisions (tier grants/denials, remote-control state), and service-lever transitions. Mobile, the live
4
+ // dashboard, and the on-disk audit log all render the SAME envelope, so there is exactly one contract to
5
+ // agree on. FROZEN v1: add fields, never repurpose or remove one; bump `v` for a breaking change.
6
+ //
7
+ // CLI-only sink, node-lazy (opaque specifier, same discipline as audit.ts/searxng.ts) so this module is
8
+ // node-free at load and safe to import from the JSCore/browser bundle — there the file/HTTP branches are
9
+ // simply never reached (a mobile host injects its own sink). Best-effort by construction: a sink failure
10
+ // never blocks or fails a turn — observability is not a gate.
11
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
12
+ export const EVENT_V = 1;
13
+ /** Emits OperatorEvents to a local JSONL file and, if configured, an HTTP sink. Both best-effort. The
14
+ * HTTP POST is fire-and-forget with a short timeout so a slow/down sink never stalls a turn. */
15
+ export class EventSink {
16
+ file;
17
+ url;
18
+ onEvent;
19
+ constructor(opts = {}) {
20
+ this.file = opts.file ?? process.env.KODE_EVENTS_FILE ?? process.env.KODE_AUDIT_FILE ?? "~/.axe/operator/events.jsonl";
21
+ this.url = opts.url ?? process.env.KODE_TELEMETRY_URL;
22
+ // In-process callback bridge — the ONLY path that works on mobile (JSCore has no fs and the phone is
23
+ // not a KODE_TELEMETRY_URL backend), same pattern as the bg-agents host bridge. A native/web host sets
24
+ // this to marshal each event into its own store and render the control-plane surface.
25
+ this.onEvent = opts.onEvent;
26
+ }
27
+ /** Fill in envelope boilerplate and dispatch. Callers pass kind + the matching payload + actor. */
28
+ emit(e) {
29
+ const full = { v: EVENT_V, ts: new Date().toISOString(), ...e };
30
+ // In-process listener first (synchronous, never throws out) so a host callback sees every event even
31
+ // where fs/HTTP are absent (mobile). Then fire-and-forget the file + HTTP sinks off the hot path.
32
+ try {
33
+ this.onEvent?.(full);
34
+ }
35
+ catch { /* a host listener must never break a turn */ }
36
+ void this.write(full);
37
+ void this.post(full);
38
+ }
39
+ async write(e) {
40
+ try {
41
+ const [{ appendFile, mkdir }, os, { join, dirname }] = await Promise.all([
42
+ nodeImport("node:fs/promises"), nodeImport("node:os"), nodeImport("node:path"),
43
+ ]);
44
+ const file = this.file.startsWith("~/") ? join(os.homedir(), this.file.slice(2)) : this.file;
45
+ await mkdir(dirname(file), { recursive: true });
46
+ await appendFile(file, JSON.stringify(e) + "\n", "utf8");
47
+ }
48
+ catch { /* best-effort: no fs (mobile) or a write failure must never break a turn */ }
49
+ }
50
+ async post(e) {
51
+ if (!this.url)
52
+ return;
53
+ const ctrl = new AbortController();
54
+ const t = setTimeout(() => ctrl.abort(), 3000);
55
+ try {
56
+ await fetch(this.url, {
57
+ method: "POST",
58
+ headers: { "content-type": "application/json" },
59
+ body: JSON.stringify(e),
60
+ signal: ctrl.signal,
61
+ });
62
+ }
63
+ catch { /* remote sink down/slow — local JSONL still has it; never block the turn */ }
64
+ finally {
65
+ clearTimeout(t);
66
+ }
67
+ }
68
+ }
@@ -98,9 +98,10 @@ async function armHooks() {
98
98
  catch {
99
99
  spawnSyncFn = null;
100
100
  }
101
- // Clean session exit: stop synchronously (bounded) so we don't leak the container.
101
+ // Clean session exit: stop synchronously (bounded) so we don't leak the container — unless the owner
102
+ // opted to keep it warm past exit (settings.services.stopOnExit.searxng=false / KODE_STOP_SEARXNG_ON_EXIT=0).
102
103
  process.on("exit", () => {
103
- if (!managed || !spawnSyncFn)
104
+ if (!managed || !spawnSyncFn || process.env.KODE_STOP_SEARXNG_ON_EXIT === "0")
104
105
  return;
105
106
  try {
106
107
  spawnSyncFn("docker", ["stop", "-t", "2", CONTAINER], { timeout: 6000, stdio: "ignore" });
@@ -109,9 +110,13 @@ async function armHooks() {
109
110
  /* best-effort */
110
111
  }
111
112
  });
112
- // Ctrl-C / kill: stop then let the default handler end the process.
113
+ // Ctrl-C / kill: stop then let the default handler end the process (respecting the keep-warm opt-out).
113
114
  for (const sig of ["SIGINT", "SIGTERM"]) {
114
115
  process.once(sig, () => {
116
+ if (process.env.KODE_STOP_SEARXNG_ON_EXIT === "0") {
117
+ process.exit(0);
118
+ return;
119
+ }
115
120
  void stopManagedSearxng().finally(() => process.exit(0));
116
121
  });
117
122
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
5
5
  "type": "module",
6
6
  "bin": {