@0perator/operator 0.1.26 → 0.1.27

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
@@ -17,7 +17,7 @@ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
17
17
  import { join } from "node:path";
18
18
  import { homedir, hostname } from "node:os";
19
19
  import { createHash } from "node:crypto";
20
- const VERSION = "0.1.26";
20
+ const VERSION = "0.1.27";
21
21
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
22
22
  const settings = loadSettings();
23
23
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -42,6 +42,9 @@ if (sd) {
42
42
  if (sd.idleSec !== undefined)
43
43
  process.env.KODE_SEARXNG_IDLE_SEC = String(sd.idleSec);
44
44
  }
45
+ // The searxng module reads this env flag in its own sync exit hook; project the setting so it applies.
46
+ if (settings.services?.stopOnExit?.searxng === false)
47
+ process.env.KODE_STOP_SEARXNG_ON_EXIT = "0";
45
48
  // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
46
49
  // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
47
50
  // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
@@ -129,6 +132,7 @@ const HELP = [
129
132
  " /help this list",
130
133
  " /model current endpoint (aurora · 1M), context %, turn count",
131
134
  " /endpoints show the aurora endpoint + live health",
135
+ " /services ensure/inspect the service lever (aurora+autopilot+searxng); /services stop",
132
136
  " /compact force-compact the conversation now",
133
137
  " /remember <note> store a note to recall in future sessions",
134
138
  " /memory [query] show remembered notes (all, or matching query)",
@@ -152,6 +156,7 @@ const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim())
152
156
  function Root() {
153
157
  const { exit } = useApp();
154
158
  const [boot, setBoot] = useState("checking");
159
+ const [bootDetail, setBootDetail] = useState(""); // live line during the service-lever preflight
155
160
  const [entries, setEntries] = useState([]);
156
161
  const [live, setLive] = useState(null);
157
162
  const [status, setStatus] = useState("idle");
@@ -266,9 +271,27 @@ function Root() {
266
271
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
267
272
  }, [session]);
268
273
  useEffect(() => {
269
- session.health().then((ok) => {
274
+ void (async () => {
275
+ // Service lever: bring Aurora (required) and autopilot (optional) up via launchd BEFORE gating on
276
+ // health, so a cold box self-heals instead of dropping the owner at "start it yourself and relaunch".
277
+ let reports = [];
278
+ try {
279
+ const { ensureServices } = await import("./services/preflight.js");
280
+ reports = await ensureServices({
281
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
282
+ autopilot: settings.services?.autopilot,
283
+ onProgress: setBootDetail,
284
+ });
285
+ }
286
+ catch { /* preflight is best-effort — fall through to the authoritative health check */ }
287
+ const ok = await session.health().catch(() => false);
270
288
  setBoot(ok ? "ready" : "down");
271
- if (ok && RESUME) {
289
+ if (!ok) {
290
+ const a = reports.find((r) => r.name === "aurora");
291
+ setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
292
+ return;
293
+ }
294
+ if (RESUME) {
272
295
  try {
273
296
  const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
274
297
  if (session.restore(saved)) {
@@ -282,7 +305,11 @@ function Root() {
282
305
  }
283
306
  catch { /* no saved session to resume */ }
284
307
  }
285
- }).catch(() => setBoot("down"));
308
+ // Confirm, once in scrollback, what the lever did (started = it was down and we brought it up).
309
+ const line = reports.map((r) => `${r.name} ${r.state === "up" ? "✓" : r.state === "started" ? "✓ started" : "✗"}`).join(" · ");
310
+ if (line)
311
+ push({ kind: "message", message: { id: nextId(), role: "system", content: `services: ${line} · searxng lazy` } });
312
+ })();
286
313
  }, []);
287
314
  // Show who's signed in (best-effort, non-blocking): load stored creds, verify against the backend.
288
315
  useEffect(() => {
@@ -493,6 +520,24 @@ function Root() {
493
520
  sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
494
521
  break;
495
522
  }
523
+ case "services": {
524
+ // The lever, on demand: `/services` probes + starts any down launchd service; `/services stop`
525
+ // tears down only the session-scoped SearXNG (Aurora/autopilot are shared and stay up).
526
+ if (arg === "stop") {
527
+ const { stopSessionServices } = await import("./services/preflight.js");
528
+ await stopSessionServices({ searxng: true });
529
+ sys("stopped session-scoped services (SearXNG). Aurora + autopilot are shared and stay up.");
530
+ break;
531
+ }
532
+ sys("checking services…");
533
+ const { ensureServices } = await import("./services/preflight.js");
534
+ const reports = await ensureServices({
535
+ aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
536
+ autopilot: settings.services?.autopilot,
537
+ });
538
+ 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)");
539
+ break;
540
+ }
496
541
  case "bg":
497
542
  if (!arg) {
498
543
  const l = bg.list();
@@ -570,9 +615,9 @@ function Root() {
570
615
  return () => clearInterval(id);
571
616
  }, [status]);
572
617
  if (boot === "checking")
573
- return _jsx(Text, { dimColor: true, children: "connecting to Aurora\u2026" });
618
+ return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Aurora…" });
574
619
  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." })] }));
620
+ 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
621
  }
577
622
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
578
623
  // 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
@@ -76,6 +83,20 @@ function applyEnv(s) {
76
83
  out.sandbox = { mode: sb };
77
84
  if (process.env.KODE_COMPUTER === "1")
78
85
  out.computer = { enabled: true };
86
+ // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of BOTH launchd services (Operator then
87
+ // only probes + reports); KODE_STOP_SEARXNG_ON_EXIT=0 keeps the SearXNG container running after exit.
88
+ if (out.services) {
89
+ if (process.env.KODE_SERVICES_AUTOSTART === "0") {
90
+ out.services = {
91
+ ...out.services,
92
+ aurora: { ...out.services.aurora, autostart: false },
93
+ autopilot: { ...out.services.autopilot, autostart: false },
94
+ };
95
+ }
96
+ if (process.env.KODE_STOP_SEARXNG_ON_EXIT === "0") {
97
+ out.services = { ...out.services, stopOnExit: { ...out.services.stopOnExit, searxng: false } };
98
+ }
99
+ }
79
100
  if (process.env.KODE_AUTOPILOT_URL || process.env.KODE_SEARXNG_URL) {
80
101
  out.search = {
81
102
  ...out.search,
@@ -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
+ }
@@ -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.27",
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": {