@0perator/operator 0.1.25 → 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
@@ -8,15 +8,16 @@ import { useCallback, useEffect, useRef, useState } from "react";
8
8
  import { render, Box, Text, useApp } from "ink";
9
9
  import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
+ import { RemoteHost } from "./remote/host.js";
11
12
  import { Session } from "./session.js";
12
13
  import { AuroraRouter } from "./router/router.js";
13
14
  import { BackgroundAgents } from "./background/index.js";
14
15
  import { loadSettings } from "./config/settings.js";
15
16
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
16
17
  import { join } from "node:path";
17
- import { homedir } from "node:os";
18
+ import { homedir, hostname } from "node:os";
18
19
  import { createHash } from "node:crypto";
19
- const VERSION = "0.1.25";
20
+ const VERSION = "0.1.27";
20
21
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
21
22
  const settings = loadSettings();
22
23
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -41,6 +42,9 @@ if (sd) {
41
42
  if (sd.idleSec !== undefined)
42
43
  process.env.KODE_SEARXNG_IDLE_SEC = String(sd.idleSec);
43
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";
44
48
  // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
45
49
  // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
46
50
  // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
@@ -128,6 +132,7 @@ const HELP = [
128
132
  " /help this list",
129
133
  " /model current endpoint (aurora · 1M), context %, turn count",
130
134
  " /endpoints show the aurora endpoint + live health",
135
+ " /services ensure/inspect the service lever (aurora+autopilot+searxng); /services stop",
131
136
  " /compact force-compact the conversation now",
132
137
  " /remember <note> store a note to recall in future sessions",
133
138
  " /memory [query] show remembered notes (all, or matching query)",
@@ -151,6 +156,7 @@ const isErrorResult = (s) => /^(error|loop guard|\[interrupted)/i.test(s.trim())
151
156
  function Root() {
152
157
  const { exit } = useApp();
153
158
  const [boot, setBoot] = useState("checking");
159
+ const [bootDetail, setBootDetail] = useState(""); // live line during the service-lever preflight
154
160
  const [entries, setEntries] = useState([]);
155
161
  const [live, setLive] = useState(null);
156
162
  const [status, setStatus] = useState("idle");
@@ -171,11 +177,31 @@ function Root() {
171
177
  // adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
172
178
  const [approval, setApproval] = useState(null);
173
179
  const alwaysAllowRef = useRef(new Set());
180
+ // Pending gated approvals by id. Both the local keystroke and a remote follower's approval_response
181
+ // route through settleApproval — FIRST answer wins (§7); the map delete makes it idempotent.
182
+ const pendingApprovals = useRef(new Map());
183
+ const settleApproval = useCallback((id, allow, always = false) => {
184
+ const resolve = pendingApprovals.current.get(id);
185
+ if (!resolve)
186
+ return; // already settled (first-wins)
187
+ pendingApprovals.current.delete(id);
188
+ resolve(allow);
189
+ setApproval((cur) => {
190
+ if (cur && cur.id === id && allow && always)
191
+ alwaysAllowRef.current.add(cur.name);
192
+ return cur && cur.id === id ? null : cur;
193
+ });
194
+ }, []);
174
195
  const approveFn = useCallback((name, args) => {
175
196
  if (alwaysAllowRef.current.has(name))
176
197
  return Promise.resolve(true);
177
- return new Promise((resolve) => setApproval({ name, args, resolve }));
178
- }, []);
198
+ const id = "ap_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
199
+ return new Promise((resolve) => {
200
+ pendingApprovals.current.set(id, resolve);
201
+ setApproval({ id, name, args, resolve: (b) => settleApproval(id, b) });
202
+ remoteRef.current?.approvalRequest(id, name, args); // mirror to followers (owner-scoped)
203
+ });
204
+ }, [settleApproval]);
179
205
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
180
206
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
181
207
  // only, no network fan-out at session start). Background agents stay local-only + lean.
@@ -229,7 +255,10 @@ function Root() {
229
255
  const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
230
256
  const queued = useRef("");
231
257
  const statusRef = useRef("idle");
232
- const setStat = (s) => { statusRef.current = s; setStatus(s); };
258
+ // Remote-control host (SPEC/remote-session.md): non-null only while /remotecontrol is active. Every
259
+ // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
260
+ const remoteRef = useRef(null);
261
+ const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
233
262
  const push = (e) => setEntries((prev) => [...prev, e]);
234
263
  const submitRef = useRef(() => { });
235
264
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
@@ -242,9 +271,27 @@ function Root() {
242
271
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
243
272
  }, [session]);
244
273
  useEffect(() => {
245
- 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);
246
288
  setBoot(ok ? "ready" : "down");
247
- 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) {
248
295
  try {
249
296
  const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
250
297
  if (session.restore(saved)) {
@@ -258,7 +305,11 @@ function Root() {
258
305
  }
259
306
  catch { /* no saved session to resume */ }
260
307
  }
261
- }).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
+ })();
262
313
  }, []);
263
314
  // Show who's signed in (best-effort, non-blocking): load stored creds, verify against the backend.
264
315
  useEffect(() => {
@@ -278,6 +329,8 @@ function Root() {
278
329
  }, []);
279
330
  const sendTurn = useCallback(async (text) => {
280
331
  push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
332
+ remoteRef.current?.userPrompt(text); // mirror to followers
333
+ remoteRef.current?.turnStart(); // allocate this turn's assistant id (stable stream→final)
281
334
  liveText.current = "";
282
335
  liveReasoning.current = "";
283
336
  setLive(null);
@@ -287,12 +340,13 @@ function Root() {
287
340
  setStat("thinking");
288
341
  try {
289
342
  const outcome = await session.send(text, {
290
- onRoute: (label, pct) => { setRoute(label); setCtxPct(pct); },
343
+ onRoute: (label, pct) => { setRoute(label); setCtxPct(pct); remoteRef.current?.setStatus(pct, label); },
291
344
  onDelta: (chunk) => {
292
345
  liveText.current += chunk;
293
346
  setLiveTok((t) => t + 1); // ≈1 token per streamed delta — batched with setLive, no extra render
294
347
  setStat("streaming");
295
348
  setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current || undefined } });
349
+ remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
296
350
  },
297
351
  onReasoning: (chunk) => {
298
352
  // Thinking streams before/between content — accumulate it and show it dimmed in the live entry
@@ -303,6 +357,7 @@ function Root() {
303
357
  // counter + tok/s keep moving during a long thinking phase (they were frozen before content).
304
358
  setStat("thinking");
305
359
  setLive({ kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current } });
360
+ remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
306
361
  },
307
362
  onAutoContinue: (round) => {
308
363
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
@@ -322,6 +377,7 @@ function Root() {
322
377
  durationMs, summary: firstLine(ev.result),
323
378
  };
324
379
  push({ kind: "tool", step });
380
+ remoteRef.current?.toolStep(step);
325
381
  }
326
382
  liveText.current = "";
327
383
  liveReasoning.current = "";
@@ -331,6 +387,7 @@ function Root() {
331
387
  });
332
388
  if (outcome.interrupted) {
333
389
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
390
+ remoteRef.current?.system("⎋ interrupted — output above kept");
334
391
  }
335
392
  else if (outcome.content.trim()) {
336
393
  // Keep the final answer's thinking (dim, above the answer), plus a dim note when generation was
@@ -342,6 +399,7 @@ function Root() {
342
399
  : undefined;
343
400
  const reasoning = [liveReasoning.current.trim(), stopNote].filter(Boolean).join("\n") || undefined;
344
401
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
402
+ remoteRef.current?.finalAssistant(outcome.content, reasoning);
345
403
  }
346
404
  // Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
347
405
  if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
@@ -370,6 +428,7 @@ function Root() {
370
428
  }, []);
371
429
  const sys = useCallback((text) => {
372
430
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
431
+ remoteRef.current?.system(text);
373
432
  }, []);
374
433
  const handleSlash = useCallback(async (cmd) => {
375
434
  const [name, ...rest] = cmd.slice(1).split(/\s+/);
@@ -461,6 +520,24 @@ function Root() {
461
520
  sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
462
521
  break;
463
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
+ }
464
541
  case "bg":
465
542
  if (!arg) {
466
543
  const l = bg.list();
@@ -475,9 +552,39 @@ function Root() {
475
552
  sys(`spawned ${id} in the background — /bg to list · /bg stop ${id} to cancel`);
476
553
  }
477
554
  break;
555
+ case "remotecontrol":
556
+ case "remote": {
557
+ if (remoteRef.current) {
558
+ remoteRef.current.stop();
559
+ remoteRef.current = null;
560
+ sys("remote control stopped — followers detached");
561
+ break;
562
+ }
563
+ const { loadCredentials } = await import("./auth/store.js");
564
+ const creds = await loadCredentials().catch(() => null);
565
+ const token = process.env.KODE_OPERATOR_TOKEN || creds?.token || "";
566
+ const url = process.env.KODE_RELAY_URL || "wss://api.axe.onl/session/ws";
567
+ const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
568
+ onPrompt: (text) => submitRef.current(text), // follower drives a turn
569
+ onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
570
+ onInterrupt: () => s.interrupt(), // follower cancels the turn
571
+ onState: (st, detail) => {
572
+ if (st === "live")
573
+ sys(`✷ remote control LIVE — session ${rh.id} · attach from the app to drive it. /remotecontrol again to stop.`);
574
+ else if (st === "error")
575
+ sys(`remote control error: ${detail ?? "connection lost"} — /remotecontrol to retry`);
576
+ else if (st === "closed")
577
+ sys("remote control disconnected");
578
+ },
579
+ });
580
+ remoteRef.current = rh;
581
+ rh.connect();
582
+ sys(`connecting remote control → ${url} …`);
583
+ break;
584
+ }
478
585
  default: sys(`unknown command /${name} — try /help`);
479
586
  }
480
- }, [exit, sys, bg, authUser]);
587
+ }, [exit, sys, bg, authUser, approval, settleApproval]);
481
588
  const onSubmit = useCallback((text) => {
482
589
  const t = text.trim();
483
590
  if (t.startsWith("/")) {
@@ -508,9 +615,9 @@ function Root() {
508
615
  return () => clearInterval(id);
509
616
  }, [status]);
510
617
  if (boot === "checking")
511
- return _jsx(Text, { dimColor: true, children: "connecting to Aurora\u2026" });
618
+ return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Aurora…" });
512
619
  if (boot === "down") {
513
- 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" })] }));
514
621
  }
515
622
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
516
623
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -521,14 +628,9 @@ function Root() {
521
628
  ? `${SPIN[Math.floor(elapsed * 4) % SPIN.length]} ${fmtMeta(elapsed, liveTok)}`
522
629
  : metrics;
523
630
  return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, authUser: authUser, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, onApprovalDecide: (allow, always) => {
524
- setApproval((cur) => {
525
- if (cur) {
526
- if (allow && always)
527
- alwaysAllowRef.current.add(cur.name);
528
- cur.resolve(allow);
529
- }
530
- return null;
531
- });
631
+ const cur = approval;
632
+ if (cur)
633
+ settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
532
634
  } }));
533
635
  }
534
636
  // `operator auth …` runs as a plain CLI before the Ink shell — no TTY needed, so PAT login works
@@ -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,172 @@
1
+ const V = 1;
2
+ export class RemoteHost {
3
+ url;
4
+ token;
5
+ meta;
6
+ cb;
7
+ ws = null;
8
+ seq = 0;
9
+ sessionId = null;
10
+ ownerSub = null;
11
+ closedByUs = false;
12
+ // Transcript mirror for late-joiner snapshots (upsert by id, same semantics followers use).
13
+ entries = [];
14
+ activity = "idle";
15
+ ctxPct = 0;
16
+ route = "aurora";
17
+ curAsstId = null; // per-turn assistant message id (stable across stream→final)
18
+ liveTimer = null;
19
+ livePending = null;
20
+ turnN = 0;
21
+ constructor(url, token, meta, cb) {
22
+ this.url = url;
23
+ this.token = token;
24
+ this.meta = meta;
25
+ this.cb = cb;
26
+ }
27
+ connect() {
28
+ this.cb.onState?.("connecting");
29
+ let ws;
30
+ try {
31
+ ws = new WebSocket(this.url);
32
+ }
33
+ catch (e) {
34
+ this.cb.onState?.("error", String(e));
35
+ return;
36
+ }
37
+ this.ws = ws;
38
+ ws.addEventListener("open", () => {
39
+ this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined });
40
+ });
41
+ ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
42
+ ws.addEventListener("close", () => { this.cb.onState?.(this.closedByUs ? "closed" : "error", this.closedByUs ? undefined : "relay closed"); });
43
+ ws.addEventListener("error", () => { this.cb.onState?.("error", "socket error"); });
44
+ }
45
+ get id() { return this.sessionId; }
46
+ get connected() { return !!this.ws && this.ws.readyState === 1; }
47
+ stop() {
48
+ this.closedByUs = true;
49
+ if (this.liveTimer) {
50
+ clearTimeout(this.liveTimer);
51
+ this.liveTimer = null;
52
+ }
53
+ try {
54
+ this.ws?.close();
55
+ }
56
+ catch { /* ignore */ }
57
+ this.ws = null;
58
+ }
59
+ onMessage(data) {
60
+ let f;
61
+ try {
62
+ f = JSON.parse(data);
63
+ }
64
+ catch {
65
+ return;
66
+ }
67
+ if (f.v !== V)
68
+ return;
69
+ switch (f.type) {
70
+ case "welcome":
71
+ this.sessionId = f.payload?.sessionId ?? this.sessionId;
72
+ this.ownerSub = f.payload?.ownerSub ?? null;
73
+ this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host });
74
+ this.cb.onState?.("live");
75
+ break;
76
+ case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
77
+ this.sendSnapshot();
78
+ break;
79
+ case "prompt":
80
+ if (typeof f.payload?.text === "string")
81
+ this.cb.onPrompt(f.payload.text);
82
+ break;
83
+ case "approval_response":
84
+ if (f.payload?.id)
85
+ this.cb.onApprovalResponse(String(f.payload.id), !!f.payload.approve);
86
+ break;
87
+ case "interrupt":
88
+ this.cb.onInterrupt();
89
+ break;
90
+ case "error":
91
+ this.cb.onState?.("error", f.payload?.message ?? f.payload?.code);
92
+ break;
93
+ }
94
+ }
95
+ send(type, sessionId, payload, seq = null) {
96
+ if (!this.ws || this.ws.readyState !== 1)
97
+ return;
98
+ const frame = { v: V, type, sessionId: sessionId ?? this.sessionId, seq, ts: Date.now(), payload };
99
+ try {
100
+ this.ws.send(JSON.stringify(frame));
101
+ }
102
+ catch { /* dropped; follower re-attaches on gap */ }
103
+ }
104
+ state(type, payload) { this.send(type, this.sessionId, payload, ++this.seq); }
105
+ sendSnapshot() {
106
+ this.flushLive();
107
+ this.send("snapshot", this.sessionId, { transcript: this.entries, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route } }, this.seq);
108
+ }
109
+ // ── mirror upserts ────────────────────────────────────────────────────────
110
+ upsertMessage(id, role, content, reasoning) {
111
+ const e = { kind: "message", message: { id, role, content, ...(reasoning ? { reasoning } : {}) } };
112
+ const i = this.entries.findIndex((x) => x.kind === "message" && x.message.id === id);
113
+ if (i >= 0)
114
+ this.entries[i] = e;
115
+ else
116
+ this.entries.push(e);
117
+ return e;
118
+ }
119
+ upsertTool(step) {
120
+ const e = { kind: "tool", step };
121
+ const i = this.entries.findIndex((x) => x.kind === "tool" && x.step.id === step.id);
122
+ if (i >= 0)
123
+ this.entries[i] = e;
124
+ else
125
+ this.entries.push(e);
126
+ return e;
127
+ }
128
+ // ── public turn-aware emitters (called from cli.tsx sendTurn) ──────────────
129
+ userPrompt(text) {
130
+ const e = this.upsertMessage("u" + (++this.turnN) + "_" + Date.now().toString(36), "user", text);
131
+ this.state("transcript", { entry: e });
132
+ }
133
+ turnStart() { this.curAsstId = "a" + this.turnN + "_" + Date.now().toString(36); }
134
+ /** streaming assistant content/reasoning — coalesced to ~one flush per 80ms (§8 flush-rate). */
135
+ streamAssistant(content, reasoning) {
136
+ if (!this.curAsstId)
137
+ this.turnStart();
138
+ this.livePending = { content, reasoning };
139
+ if (this.liveTimer)
140
+ return;
141
+ this.liveTimer = setTimeout(() => this.flushLive(), 80);
142
+ }
143
+ flushLive() {
144
+ if (this.liveTimer) {
145
+ clearTimeout(this.liveTimer);
146
+ this.liveTimer = null;
147
+ }
148
+ if (!this.livePending || !this.curAsstId)
149
+ return;
150
+ const { content, reasoning } = this.livePending;
151
+ this.livePending = null;
152
+ const e = this.upsertMessage(this.curAsstId, "assistant", content, reasoning);
153
+ this.state("transcript", { entry: e });
154
+ }
155
+ finalAssistant(content, reasoning) {
156
+ if (!this.curAsstId)
157
+ this.turnStart();
158
+ this.flushLive();
159
+ const e = this.upsertMessage(this.curAsstId, "assistant", content, reasoning);
160
+ this.state("transcript", { entry: e });
161
+ this.curAsstId = null;
162
+ }
163
+ system(content) {
164
+ const e = this.upsertMessage("s" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), "system", content);
165
+ this.state("transcript", { entry: e });
166
+ }
167
+ toolStep(step) { this.state("tool_step", { step: this.pickTool(step) }); }
168
+ pickTool(step) { this.upsertTool(step); return step; }
169
+ setActivity(state, label) { this.activity = state; this.state("activity", { state, ...(label ? { label } : {}) }); }
170
+ setStatus(ctxPct, route) { this.ctxPct = ctxPct; this.route = route; this.state("status", { ctxPct, route }); }
171
+ approvalRequest(id, tool, args) { this.state("approval_request", { id, tool, args }); }
172
+ }
@@ -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
+ }
@@ -572,12 +572,21 @@ const TOOLS = [
572
572
  },
573
573
  {
574
574
  name: "skill_fetch", safe: true,
575
- description: "Fetch one AXE skill by slug from the Operator registry (operator.axe.onl /v1/skills/{slug}) and return its instructions to follow. Read-only.",
575
+ description: "Fetch one AXE skill by name from the hub (or your profile) and return its full instructions to follow/apply. Checks your saved profile skills first, then the hub (operator.axe.onl/skills.axe.onl). Read-only.",
576
576
  parameters: { type: "object", properties: {
577
- slug: { type: "string", description: "the skill slug/name to fetch" },
577
+ slug: { type: "string", description: "the skill name/slug to fetch and use" },
578
578
  }, required: ["slug"] },
579
579
  run: (a) => skillFetch(str(a.slug)),
580
580
  },
581
+ {
582
+ name: "skill_save",
583
+ description: "Save a reusable skill to your profile so it persists and is available next session with no settings edit — auto-harvest a new capability. Saved skills are listed by skill_list and loaded by skill_fetch (profile skills take precedence over the hub). Use when you've worked out a repeatable playbook worth keeping.",
584
+ parameters: { type: "object", properties: {
585
+ name: { type: "string", description: "short skill name (kebab-cased automatically)" },
586
+ content: { type: "string", description: "the skill instructions/playbook (skillmd or plain markdown)" },
587
+ }, required: ["name", "content"] },
588
+ run: (a) => skillSave(str(a.name), str(a.content)),
589
+ },
581
590
  ];
582
591
  // AXE skill registry (parity with the Python core): a REMOTE HTTPS registry reachable from every surface
583
592
  // (CLI/web/mobile), so skills work everywhere without local fleet access. Bearer from OPERATOR_TOKEN or
@@ -619,18 +628,95 @@ async function operatorGet(path) {
619
628
  return null;
620
629
  }
621
630
  async function skillList(query) {
622
- const r = await operatorGet(`/v1/skills${query ? `?q=${encodeURIComponent(query)}` : ""}`);
623
- if (r === null)
624
- return "error: skill registry unreachable (operator.axe.onl / skills.axe.onl)";
625
- return JSON.stringify(r).slice(0, 8000);
631
+ // Prefer the ranked /search when a query is given; fall back to the full list.
632
+ const local = await localSkills();
633
+ const localBlock = local.length ? `your profile skills:\n${local.map((l) => `• ${l.name} (profile)`).join("\n")}\n\n` : "";
634
+ const path = query ? `/v1/skills/search?q=${encodeURIComponent(query)}` : "/v1/skills";
635
+ const r = (await operatorGet(path)) ?? (query ? await operatorGet("/v1/skills") : null);
636
+ if (r === null) {
637
+ return localBlock ? `${localBlock}(hub unreachable — showing profile skills only)` : "error: skill registry unreachable (operator.axe.onl / skills.axe.onl)";
638
+ }
639
+ const arr = Array.isArray(r) ? r : r.results ?? r.skills ?? [];
640
+ if (!Array.isArray(arr) || arr.length === 0)
641
+ return `${localBlock}${query ? `no hub skills match "${query}"` : "no skills in the hub yet"}`;
642
+ // Compact one-line-per-skill: name — description (from the skillmd metadata).
643
+ const lines = arr.slice(0, 40).map((s) => {
644
+ const desc = s?.metadata?.taxonomy?.description ?? s?.metadata?.description ?? s?.description ?? "";
645
+ return `• ${s?.name ?? "?"}${desc ? ` — ${String(desc).replace(/\s+/g, " ").slice(0, 140)}` : ""}`;
646
+ });
647
+ return `${localBlock}${arr.length} hub skill${arr.length === 1 ? "" : "s"} (skill_fetch <name> to use one):\n${lines.join("\n")}`;
626
648
  }
627
649
  async function skillFetch(slug) {
628
650
  if (!slug)
629
- return "error: skill_fetch needs a slug";
651
+ return "error: skill_fetch needs a slug (name)";
652
+ // Personal profile skills win over the hub (a user's own saved version is
653
+ // theirs to trust), and work even when the hub is unreachable.
654
+ for (const ls of await localSkills()) {
655
+ if (ls.name === slug || ls.name === slugify(slug)) {
656
+ try {
657
+ const { readFile } = await nodeImport("node:fs/promises");
658
+ return `# skill: ${ls.name} (profile)\n\n${await readFile(ls.file, "utf8")}`.slice(0, 24000);
659
+ }
660
+ catch { /* fall through to hub */ }
661
+ }
662
+ }
630
663
  const r = await operatorGet(`/v1/skills/${encodeURIComponent(slug)}`);
631
664
  if (r === null)
632
665
  return `error: skill '${slug}' unreachable or not found`;
633
- return typeof r === "string" ? r : JSON.stringify(r).slice(0, 16000);
666
+ if (typeof r === "string")
667
+ return r;
668
+ // The hub returns the full skillmd in `content` — that's the usable instruction
669
+ // set. Return it directly (with a short provenance header) so the model can
670
+ // apply the skill, rather than dumping the metadata JSON.
671
+ const o = r;
672
+ if (o.content)
673
+ return `# skill: ${o.name ?? slug}${o.version ? ` v${o.version}` : ""}\n\n${o.content}`.slice(0, 24000);
674
+ return JSON.stringify(r).slice(0, 16000);
675
+ }
676
+ // Save a skill to the user's local profile so it persists + is reusable next
677
+ // session without any settings edit. This is the "profile skills" A/B against
678
+ // hub-only: local skills live at ~/.axe/operator/skills/<name>.md and are listed
679
+ // by skill_list alongside the hub. (Contributing to the shared hub needs the hub
680
+ // write endpoint — separate; this is the always-available personal path.)
681
+ function slugify(s) {
682
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "skill";
683
+ }
684
+ async function localSkillsDir() {
685
+ const { homedir } = await nodeImport("node:os");
686
+ const { join } = await nodeImport("node:path");
687
+ return join(homedir(), ".axe", "operator", "skills");
688
+ }
689
+ async function skillSave(name, content) {
690
+ if (!name || !content)
691
+ return "error: skill_save needs name and content";
692
+ try {
693
+ const { mkdir, writeFile } = await nodeImport("node:fs/promises");
694
+ const { join } = await nodeImport("node:path");
695
+ const dir = await localSkillsDir();
696
+ await mkdir(dir, { recursive: true });
697
+ const file = join(dir, `${slugify(name)}.md`);
698
+ // Stamp skillmd frontmatter if the content doesn't already carry it.
699
+ const body = content.trimStart().startsWith("---")
700
+ ? content
701
+ : `---\nname: ${slugify(name)}\nsource: profile\n---\n\n${content}`;
702
+ await writeFile(file, body, "utf8");
703
+ return `saved skill '${slugify(name)}' to your profile (${file}) — reusable next session; skill_fetch ${slugify(name)} to load it.`;
704
+ }
705
+ catch (e) {
706
+ return `error saving skill: ${e.message}`;
707
+ }
708
+ }
709
+ async function localSkills() {
710
+ try {
711
+ const { readdir } = await nodeImport("node:fs/promises");
712
+ const { join } = await nodeImport("node:path");
713
+ const dir = await localSkillsDir();
714
+ const files = (await readdir(dir).catch(() => []));
715
+ return files.filter((f) => f.endsWith(".md")).map((f) => ({ name: f.replace(/\.md$/, ""), file: join(dir, f) }));
716
+ }
717
+ catch {
718
+ return [];
719
+ }
634
720
  }
635
721
  export const registry = new Map(TOOLS.map(t => [t.name, t]));
636
722
  export function toSchemas(reg = registry) {
@@ -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.25",
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": {
@@ -25,7 +25,8 @@
25
25
  "dependencies": {
26
26
  "chalk": "^5.6.2",
27
27
  "ink": "^5.0.1",
28
- "react": "^18.3.1"
28
+ "react": "^18.3.1",
29
+ "ws": "^8.18.0"
29
30
  },
30
31
  "devDependencies": {
31
32
  "@types/node": "^22.20.3",