@0perator/operator 0.1.313 → 0.1.322

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/autonomy/agent-cli.js +6 -2
  2. package/dist/autonomy/cron.js +1 -1
  3. package/dist/autonomy/delegate.js +29 -4
  4. package/dist/autonomy/index.js +22 -0
  5. package/dist/autonomy/profile.js +1 -1
  6. package/dist/browser/cdp.js +1 -1
  7. package/dist/cli.js +128 -43
  8. package/dist/config/persona.js +29 -12
  9. package/dist/config/settings.js +12 -7
  10. package/dist/engine/agent.js +4 -2
  11. package/dist/engine/aurora.js +8 -3
  12. package/dist/engine/batch-scheduler.js +3 -3
  13. package/dist/engine/compaction.js +1 -1
  14. package/dist/engine/loop-guard.js +1 -1
  15. package/dist/engine/router-adapter.js +1 -0
  16. package/dist/idle/activity.js +20 -0
  17. package/dist/idle/index.js +5 -0
  18. package/dist/idle/monitor.js +71 -0
  19. package/dist/idle/policy.js +66 -0
  20. package/dist/idle/proc.js +22 -0
  21. package/dist/idle/reaper.js +69 -0
  22. package/dist/idle/session-record.js +59 -0
  23. package/dist/index.js +1 -1
  24. package/dist/mcp/config.js +72 -14
  25. package/dist/mcp/index.js +9 -2
  26. package/dist/memory/index.js +1 -1
  27. package/dist/permissions/index.js +22 -7
  28. package/dist/permissions/tier.js +1 -1
  29. package/dist/remote/host.js +20 -2
  30. package/dist/remote/safe-commands.js +38 -0
  31. package/dist/services/preflight.js +54 -2
  32. package/dist/services/store-sync.js +111 -0
  33. package/dist/session-teardown.js +10 -1
  34. package/dist/session.js +43 -1
  35. package/dist/skills/catalogue.js +1 -1
  36. package/dist/tools/chauffeur-native.js +155 -0
  37. package/dist/tools/chauffeur.js +14 -3
  38. package/dist/tools/download.js +229 -0
  39. package/dist/tools/executor.js +1 -1
  40. package/dist/tools/monitoring-tools.js +312 -0
  41. package/dist/tools/paths.js +154 -0
  42. package/dist/tools/registry.js +309 -18
  43. package/dist/tools/shell-jobs.js +5 -2
  44. package/dist/tools/shell-session.js +4 -2
  45. package/dist/tools/tool-output-spill.js +1 -1
  46. package/dist/ui/Composer.js +5 -2
  47. package/dist/ui/QuestionPrompt.js +1 -1
  48. package/dist/ui/ToolStep.js +16 -1
  49. package/dist/ui/liveTools.js +1 -1
  50. package/dist/util/mentions.js +1 -1
  51. package/dist/vault/store.js +1 -1
  52. package/mcp/README.md +88 -0
  53. package/mcp/ocr-macos.swift +45 -0
  54. package/mcp/powertools-media.mjs +464 -0
  55. package/mcp/powertools-toolbox.mjs +1114 -0
  56. package/mcp/powertools.md +210 -0
  57. package/mcp/powertools.mjs +861 -0
  58. package/package.json +2 -1
@@ -211,10 +211,14 @@ async function runProcess(file, argv, opts) {
211
211
  return;
212
212
  }
213
213
  ownChild(child, `delegate_to_agent:${opts.label}`, { cmd: `${file} ${argv.join(" ")}`.slice(0, 240), group: true });
214
- // ownChild unref's the child (background-job semantics). Here the tool AWAITS it, so re-ref it: while this
215
- // delegation is in flight the child must keep the loop alive until it exits, or the await can never settle.
214
+ // ownChild unref's the child AND its stdout/stderr pipes (background-job semantics). Here the tool AWAITS the
215
+ // child's "close", which fires only once those pipes EOF, so re-ref all three. Re-reffing the process handle
216
+ // alone is not enough: a spawned CLI can leave a grandchild holding the pipe open past its own exit, and in that
217
+ // window the loop would have nothing refed while "close" is still pending — an unsettled await (node exits 13).
216
218
  try {
217
219
  child.ref?.();
220
+ child.stdout?.ref?.();
221
+ child.stderr?.ref?.();
218
222
  }
219
223
  catch { /* not a real ChildProcess */ }
220
224
  const term = (sig) => { try {
@@ -1,4 +1,4 @@
1
- // Cron — Hermes-shaped scheduled headless runs (operator-home-v2 §7). Jobs live in
1
+ // Cron — scheduled headless runs (operator-home-v2 §7). Jobs live in
2
2
  // <home>/cron/jobs.json; every execution appends one JSONL line to <home>/cron/executions.jsonl and
3
3
  // drops the run's output text under <home>/cron/output/<id>-<ts>.txt. A job is either a fixed
4
4
  // interval ({kind:"interval", everyMinutes}) or a 5-field cron expression ({kind:"cron", expr}).
@@ -47,17 +47,31 @@ export async function delegationDepth() {
47
47
  return Math.max(scoped, Number.isFinite(env) && env > 0 ? Math.floor(env) : 0);
48
48
  }
49
49
  // ── Settings + brief ────────────────────────────────────────────────────────
50
+ /** A loopback Aurora profile (operator-1m/128k): its STATIC profile endpoint (127.0.0.1:8097) is a
51
+ * placeholder — the live port is published dynamically to server.json (the local gateway). Matched so a
52
+ * delegate to it is pointed at the live gateway, never a remote (scout/cortana) or BYO target. */
53
+ function isLocalAuroraProfile(p) {
54
+ const ep = p.endpoint ?? "";
55
+ return /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(ep) && (p.model ?? "") === "aurora-code-1";
56
+ }
50
57
  /** Point a settings object at `profile`'s endpoint. Pure (the base is never mutated). `activeModel` + the
51
58
  * ctx window are what size the child's lean-harness prompt and compaction ceiling (a 32K Scout must not be
52
59
  * budgeted like the 300K Aurora); no failover (a sub-agent must not silently hop to a different model);
53
60
  * MCP off (a heavy tool catalogue overruns a small-context model, and each delegation would otherwise spawn
54
- * the owner's MCP servers). The router binding itself is Session.setModel's job, not this function's. */
55
- export function deriveDelegateSettings(base, profile) {
61
+ * the owner's MCP servers). The router binding itself is Session.setModel's job, not this function's —
62
+ * which re-resolves the profile from the registry, so `endpointOverride` (the live gateway for a local
63
+ * Aurora target) must ALSO replace the profile's endpoint in settings.models, not just endpoints.aurora. */
64
+ export function deriveDelegateSettings(base, profile, endpointOverride) {
65
+ const endpoint = endpointOverride || endpointBase(profile.endpoint ?? "");
66
+ const models = endpointOverride
67
+ ? [...(base.models ?? []), { ...profile, endpoint: `${endpointOverride}/v1` }]
68
+ : base.models;
56
69
  return {
57
70
  ...base,
71
+ models,
58
72
  endpoints: {
59
73
  aurora: {
60
- base: endpointBase(profile.endpoint ?? ""),
74
+ base: endpoint,
61
75
  model: profile.model ?? profile.id,
62
76
  ctxWindow: profile.ctx ?? base.endpoints.aurora.ctxWindow,
63
77
  },
@@ -118,13 +132,24 @@ export async function runDelegateTask(args, deps = defaultDeps) {
118
132
  if (profile.kind !== "single") {
119
133
  return `error: delegate_task: "${profile.id}" is an orchestrated profile with no endpoint of its own — pick a single-endpoint model`;
120
134
  }
135
+ // A delegate to the LOCAL Aurora must hit the live dynamic gateway (server.json, e.g. :52100), not the
136
+ // profile's static :8097 — which is unserved (the port is dynamic). Resolve it the SAME way the headless
137
+ // entry + ensureServices do (discoverAuroraEndpoint, strip /v1). Scoped to loopback Aurora — remote
138
+ // (scout/cortana) and BYO targets keep their own endpoints untouched.
139
+ let auroraOverride;
140
+ if (isLocalAuroraProfile(profile)) {
141
+ const { discoverAuroraEndpoint } = (await nodeImport("../services/preflight.js"));
142
+ const dyn = await discoverAuroraEndpoint();
143
+ if (dyn)
144
+ auroraOverride = dyn.replace(/\/v1\/?$/, "");
145
+ }
121
146
  const id = `delegate-${profile.id}-${Date.now().toString(36)}-${++_seq}`;
122
147
  // Isolation: the child never writes the owner's live memory / rolling summary (see autonomy/profile.ts).
123
148
  const { tmpdir } = (await nodeImport("node:os"));
124
149
  const dir = `${tmpdir()}/operator-${id}`;
125
150
  let session;
126
151
  try {
127
- session = await deps.createSession(deriveDelegateSettings(settings, profile), {
152
+ session = await deps.createSession(deriveDelegateSettings(settings, profile, auroraOverride), {
128
153
  extra: {
129
154
  sessionId: id,
130
155
  memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
@@ -19,6 +19,7 @@ import { runAcp } from "../acp/run.js";
19
19
  import { boardPath, addTask, readBoard } from "./board.js";
20
20
  import { routinesPath, readRoutines } from "./routines.js";
21
21
  import { readableRoutine, nextFire, runRoutine, launchdPlist, launchdLabel, crontabLine } from "./routine-run.js";
22
+ import { ensureServices } from "../services/preflight.js";
22
23
  const AUTONOMY_COMMANDS = new Set(["run", "loop", "board", "routine", "dream", "acp", "media-robot"]);
23
24
  /** Split argv (after the subcommand) into --bool flags, --key value pairs, and positionals. `--` ends
24
25
  * flag parsing so a task string starting with a dash is preserved. */
@@ -232,6 +233,27 @@ export async function dispatchAutonomy(argv, settings) {
232
233
  const cmd = argv[2];
233
234
  if (!cmd || !AUTONOMY_COMMANDS.has(cmd))
234
235
  return null;
236
+ // Headless paths skip the interactive preflight (cli.tsx's ensureServices), which both RESOLVES the
237
+ // dynamic Aurora endpoint from the operator-runtime server.json AND brings the launchd gateway UP if it
238
+ // is down. Mirror that FULL blueprint here — the same EnsureCfg (aurora launchd cfg + optional services) —
239
+ // so a headless `operator run/loop/board/routine` on a cold box self-heals instead of failing with a
240
+ // baseless "/v1/chat/completions" (Failed to parse URL) against the empty endpoints.aurora.base sentinel.
241
+ // Guarded to the empty-base case (the only time we must discover/start), and gateway-aware: carry the
242
+ // gateway's published api_key (server.json) onto the endpoint config so the router authenticates to it.
243
+ if (!settings.endpoints.aurora.base) {
244
+ const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
245
+ await ensureServices({
246
+ aurora: auroraCfg,
247
+ autopilot: settings.services?.autopilot,
248
+ vision: settings.services?.vision,
249
+ onProgress: (m) => process.stderr.write(`[services] ${m}\n`),
250
+ });
251
+ if (auroraCfg.base)
252
+ settings.endpoints.aurora.base = auroraCfg.base;
253
+ const apiKey = auroraCfg.apiKey;
254
+ if (apiKey && !settings.endpoints.aurora.apiKey)
255
+ settings.endpoints.aurora.apiKey = apiKey;
256
+ }
235
257
  const f = parseFlags(argv.slice(3), VALUED);
236
258
  if (cmd === "run" || cmd === "loop") {
237
259
  const prompt = f.positional.join(" ").trim();
@@ -1,4 +1,4 @@
1
- // Profile-bound headless sessions — the engine seam for Bot Mode (GW-OHV3-A / Hermes-parity gap #1).
1
+ // Profile-bound headless sessions — the engine seam for Bot Mode (GW-OHV3-A).
2
2
  // A "bot" the messaging gateway runs (one per Telegram/Discord/Slack identity) is nothing more than a
3
3
  // long-lived headless Session with its OWN model, persona, memory, and working dir — i.e. a $KODE_PROFILE.
4
4
  // This module turns a ProfileConfig into such a Session by DERIVING settings and composing the existing
@@ -1,6 +1,6 @@
1
1
  // Browser automation core (HV3-02) — a zero-new-dependency Chrome DevTools Protocol client.
2
2
  // WHY: web_fetch is a dumb GET; agents need a REAL page — JS-rendered content, forms, clicks, and
3
- // session state across calls. The discipline inherited from Hermes' browser layer: TEXT-FIRST —
3
+ // session state across calls. The discipline inherited from the reference browser layer: TEXT-FIRST —
4
4
  // read pages as DOM text / JS eval; screenshots only when a human must see pixels.
5
5
  // Purity: EVERY node builtin is reached via lazy getBuiltinModule/import (same contract as
6
6
  // src/tools/shell-session.ts) — registry.ts imports this module's wrapper, and run() bodies only
package/dist/cli.js CHANGED
@@ -10,6 +10,7 @@ import { App } from "./ui/index.js";
10
10
  import { mastheadLines } from "./ui/Masthead.js";
11
11
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
12
12
  import { RemoteHost } from "./remote/host.js";
13
+ import { REMOTE_SAFE_COMMANDS, REMOTE_SAFE_COMMAND_NAMES } from "./remote/safe-commands.js";
13
14
  import { newCode, pairURL } from "./remote/pairing.js";
14
15
  import { qrToTerminal } from "./ui/qr.js";
15
16
  import { pollBus, pollSent, selfAgent, buildMentorWake, selectReadyWakes } from "./bus/inbox.js";
@@ -35,13 +36,15 @@ import { describeTurnError } from "./engine/net-error.js";
35
36
  import { hasByoToken } from "./auth/byo.js";
36
37
  import { getDiscoveredModels } from "./router/discovery.js";
37
38
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
38
- import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
39
+ import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
40
+ import { lastActiveAt as idleLastActiveAt, resolveIdlePolicy, startIdleMonitor, touchWork } from "./idle/index.js";
39
41
  import { disposeBrowserNow } from "./browser/session.js";
40
42
  import { EventSink, defaultEventsFile } from "./telemetry/events.js";
41
43
  import { SessionTracker } from "./telemetry/lifecycle.js";
42
44
  import { centralRecording, defaultIngest, setCentralEnabled } from "./telemetry/ingest.js";
43
45
  import { Teardown } from "./util/teardown.js";
44
46
  import { installProcessTeardown } from "./session-teardown.js";
47
+ import { createStoreClient, resolveStoreKey } from "./services/store-sync.js";
45
48
  import { reapStaleChildren } from "./util/owned-children.js";
46
49
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync } from "node:fs";
47
50
  import { expandFileMentions } from "./util/mentions.js";
@@ -356,12 +359,28 @@ const tracker = new SessionTracker(eventSink, SESSION_ID, EVENT_ACTOR, VERSION,
356
359
  // at rest, SIGINT/SIGHUP/SIGTERM and a plain process exit all call into it (wired below, before render), so it runs exactly once.
357
360
  // It stops SESSION-owned things only — never the launchd-owned Aurora/autopilot (preflight only ever brings those UP).
358
361
  const teardown = new Teardown();
362
+ const storeClient = settings.store?.endpoint
363
+ ? createStoreClient((process.env.KODE_STORE_URL || settings.store.endpoint).replace(/\/+$/, ""), resolveStoreKey(settings.store))
364
+ : undefined;
359
365
  installProcessTeardown(teardown, {
360
- recordEnd: (r) => tracker.end(r === "quit" ? "ok" : r),
366
+ recordEnd: (r) => tracker.end(r === "quit" || r === "idle" ? "ok" : r),
361
367
  flushTelemetry: () => defaultIngest().shutdown(2000),
362
368
  flushTelemetrySync: () => defaultIngest().persistSync(),
363
369
  disposeShells: disposeShellSession,
364
370
  disposeBrowser: disposeBrowserNow,
371
+ storeClient,
372
+ buildArchive: () => {
373
+ try {
374
+ const raw = readFileSync(sessionArchive.file, "utf8");
375
+ const doc = JSON.parse(raw);
376
+ if (!doc.messages?.length)
377
+ return null;
378
+ return doc;
379
+ }
380
+ catch {
381
+ return null;
382
+ }
383
+ },
365
384
  });
366
385
  // Children a previous Operator left behind (it crashed, or was killed -9; detached shells/jobs and Chrome outlive their parent).
367
386
  let REAPED = { owners: 0, killed: [], skipped: 0 };
@@ -477,7 +496,7 @@ const HELP = [
477
496
  " /memory [query] show remembered notes (all, or matching query)",
478
497
  " /allow <tool:args> auto-allow a tool+args glob pattern in gated mode (e.g. bash:npm test*)",
479
498
  " /skill <name|off> activate a skill as a system-prompt directive (/skill off to deactivate)",
480
- " /mcp [on|off] fleet MCP tools: status, or switch the layer on/off (saved)",
499
+ " /mcp [on|off] fleet MCP: status · on/off (saved) · /mcp reload (from disk) · /mcp add powertools <root>",
481
500
  " /login · /logout · /whoami /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>); /login <token>",
482
501
  " /agents [id] detailed sub-agent status, or /agents <id> for a deep view + controls (msg/stop)",
483
502
  " /bg <task|stop id> spawn a background sub-agent, list, or stop one",
@@ -488,38 +507,7 @@ const HELP = [
488
507
  ].join("\n");
489
508
  // Slash commands a remote-control FOLLOWER is allowed to drive (RemoteHost `command` frame →
490
509
  // SPEC/remote-session.md extension; see REMOTE_RICH_HEAD_AUDIT.md). This is BOTH the allowlist enforced
491
- // in the "remotecontrol" case's onCommand below AND what's advertised in RemoteCapabilities.commands —
492
- // one list, so a follower's command palette never offers something the host will actually refuse.
493
- // Deliberately excludes: exit/quit (kills the host process), login/logout (mutates the owner's stored
494
- // AXE credentials), and remotecontrol/remote (a follower must never be able to kick every other
495
- // follower off the session it's attached to). Those four are the only slash commands that act OUTSIDE
496
- // the tool/permission system (direct switch-case side effects, ungated whether local or remote) —
497
- // everything below still runs with the same local privilege a `prompt` frame already has today.
498
- const REMOTE_SAFE_COMMANDS = [
499
- { name: "help", description: "list available commands" },
500
- { name: "model", description: "pick a model: operator-1m · operator-128k · moa (mixture-of-agents)", args: "[id]" },
501
- { name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
502
- { name: "endpoints", description: "show the Operator endpoint + live health" },
503
- { name: "services", description: "ensure/inspect the service lever (Operator+autopilot+searxng); stop searxng", args: "[stop]" },
504
- { name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
505
- { name: "dashboard", description: "launch the live swarm console" },
506
- { name: "plan", description: "toggle plan mode (read-only research + propose a plan)" },
507
- { name: "mode", description: "set operating mode: plan · manual · autonomous", args: "[plan|manual|auto]" },
508
- { name: "think", description: "toggle extended reasoning" },
509
- { name: "ultrathink", description: "toggle deep, exhaustive reasoning" },
510
- { name: "compact", description: "force-compact the conversation now" },
511
- { name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
512
- { name: "memory", description: "show remembered notes", args: "[query]" },
513
- { name: "skill", description: "activate a skill as a system-prompt directive, or /skill off", args: "<name|off>" },
514
- { name: "mcp", description: "fleet MCP tools: status · switch the layer on/off", args: "[on|off]" },
515
- { name: "whoami", description: "show signed-in identity" },
516
- { name: "agents", description: "detailed sub-agent status, or a per-agent deep view + controls", args: "[id] [msg <text>|stop]" },
517
- { name: "monitor", description: "toggle live event stream (tool decisions, turns, control)" },
518
- { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
519
- { name: "new", description: "start a fresh conversation" },
520
- { name: "clear", description: "clear the screen (keeps the conversation)" },
521
- ];
522
- const REMOTE_SAFE_COMMAND_NAMES = new Set(REMOTE_SAFE_COMMANDS.map((c) => c.name));
510
+ // REMOTE_SAFE_COMMANDS / NAMES imported from ./remote/safe-commands.js (follower allowlist).
523
511
  let ID = 0;
524
512
  const nextId = () => `e${++ID}`;
525
513
  // Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
@@ -782,8 +770,11 @@ function Root() {
782
770
  // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
783
771
  const remoteRef = useRef(null);
784
772
  const [rcConnected, setRcConnected] = useState(false); // remote-control live? drives the footer controller icon
773
+ const rcConnectedRef = useRef(false);
774
+ rcConnectedRef.current = rcConnected; // a follower attached = someone is watching: the idle monitor reads this
785
775
  const [rcActive, setRcActive] = useState(false); // remote-control ENABLED/listening (host up) — distinct from rcConnected (a follower is attached); the footer shows OFF(gray) vs ON-waiting(amber) vs LIVE(green)
786
- const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); };
776
+ const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); if (s === "idle")
777
+ touchWork(); };
787
778
  const push = (e) => setEntries((prev) => [...prev, e]);
788
779
  const submitRef = useRef(() => { });
789
780
  // AXE skills fetched/saved THIS session (name -> a best-effort description) — there's no persistent
@@ -831,12 +822,32 @@ function Root() {
831
822
  let reports = [];
832
823
  try {
833
824
  const preflight = await import("./services/preflight.js");
825
+ const bootBase = settings.endpoints.aurora.base; // "" sentinel until the gateway's published port resolves
826
+ const bootKeyBefore = settings.endpoints.aurora.apiKey;
827
+ const auroraCfg = { base: bootBase, ...settings.services?.aurora };
834
828
  reports = await preflight.ensureServices({
835
- aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
829
+ aurora: auroraCfg,
836
830
  autopilot: settings.services?.autopilot,
837
831
  vision: settings.services?.vision,
838
832
  onProgress: setBootDetail,
839
833
  });
834
+ // ensureServices discovers the dynamic port from server.json and mutates auroraCfg.base —
835
+ // propagate it back so the router, warmup, and health checks use the live endpoint.
836
+ if (auroraCfg.base && auroraCfg.base !== settings.endpoints.aurora.base) {
837
+ settings.endpoints.aurora.base = auroraCfg.base;
838
+ }
839
+ // The supervisor publishes the gateway's api_key alongside its port (server.json) — carry it onto the
840
+ // endpoint config so the router authenticates to the loopback gateway (resolveEndpointApiKey → token).
841
+ const bootKey = auroraCfg.apiKey;
842
+ if (bootKey && !settings.endpoints.aurora.apiKey)
843
+ settings.endpoints.aurora.apiKey = bootKey;
844
+ // The Session — and its router — were built at first render, while aurora.base was still the ""
845
+ // sentinel. Mutating settings alone leaves that router probing a blank base ("Can't reach Operator"
846
+ // with the gateway up, 0.1.321). Rebuild the chain from the resolved settings and swap it in — the
847
+ // order the headless factory gets for free (ensureServices, THEN buildRouterFromSettings).
848
+ if (settings.endpoints.aurora.base !== bootBase || settings.endpoints.aurora.apiKey !== bootKeyBefore) {
849
+ session.useRouter(buildRouter());
850
+ }
840
851
  // If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
841
852
  // eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
842
853
  if (reports.find((r) => r.name === "aurora")?.state === "started") {
@@ -1217,6 +1228,27 @@ function Root() {
1217
1228
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
1218
1229
  remoteRef.current?.system(text);
1219
1230
  }, []);
1231
+ // Idle-session policy (idle/): end a session nobody has touched for a while, never one that is working. This is the one entry that
1232
+ // mounts an interactive TUI, so headless/ACP/serve sessions are never subject to it. Ends through the SAME Teardown as /exit.
1233
+ useEffect(() => {
1234
+ const policy = resolveIdlePolicy(settings.idle);
1235
+ if (!policy.enabled)
1236
+ return;
1237
+ const startedAt = Date.now();
1238
+ const mon = startIdleMonitor({
1239
+ policy,
1240
+ version: VERSION,
1241
+ state: () => ({
1242
+ startedAt,
1243
+ lastActiveAt: idleLastActiveAt(),
1244
+ busy: statusRef.current !== "idle" || runningJobCount() > 0 || (bgRef.current?.activeCount() ?? 0) > 0 || rcConnectedRef.current,
1245
+ }),
1246
+ notify: sys,
1247
+ end: () => { void teardown.run("idle"); exit(); },
1248
+ });
1249
+ teardown.add("idle-monitor", () => mon.stop(), { order: 20 });
1250
+ return () => mon.stop();
1251
+ }, []);
1220
1252
  // Say so when this launch cleaned up after a previous one — silently killing processes would be worse than the orphans.
1221
1253
  useEffect(() => {
1222
1254
  const n = REAPED.killed.length;
@@ -1701,7 +1733,9 @@ function Root() {
1701
1733
  break;
1702
1734
  }
1703
1735
  case "mcp": {
1704
- const a = (arg ?? "").trim().toLowerCase();
1736
+ const raw = (arg ?? "").trim();
1737
+ const [verb, ...rest] = raw.split(/\s+/);
1738
+ const a = (verb ?? "").toLowerCase();
1705
1739
  if (a === "on") {
1706
1740
  sys("enabling MCP tools…");
1707
1741
  const n = await s.enableMcp();
@@ -1712,10 +1746,54 @@ function Root() {
1712
1746
  saveSettings({ mcp: false });
1713
1747
  sys("MCP off for new sessions (saved) — tools already loaded stay until you restart");
1714
1748
  }
1749
+ else if (a === "reload") {
1750
+ sys("reloading MCP from disk (base + the extra MCP config)…");
1751
+ const n = await s.reloadMcp();
1752
+ saveSettings({ mcp: true });
1753
+ sys(n > 0 ? `MCP reloaded · ${n} fleet tools` : "MCP reloaded, but no tools discovered — check mcp_servers.json and the extra MCP config");
1754
+ }
1755
+ else if (a === "add") {
1756
+ // Live-drive: `/mcp add powertools [root]` upserts into writable overlay then reloads.
1757
+ const kind = (rest[0] ?? "").toLowerCase();
1758
+ if (kind === "powertools" || kind === "pt") {
1759
+ const root = rest[1] || process.cwd();
1760
+ const { resolve: pathResolve } = await import("node:path");
1761
+ const { fileURLToPath } = await import("node:url");
1762
+ // powertools.mjs ships next to this package's mcp/ folder — resolve from kode-tsi root.
1763
+ const powertoolsPath = pathResolve(fileURLToPath(new URL(".", import.meta.url)), "..", "mcp", "powertools.mjs");
1764
+ const absRoot = pathResolve(root);
1765
+ try {
1766
+ const { upsertMcpServer } = await import("./mcp/config.js");
1767
+ // No tools allowlist — advertise whatever powertools soft-miss surface is present (v0.3 toolbox).
1768
+ const written = await upsertMcpServer("powertools", {
1769
+ transport: "stdio",
1770
+ command: "node",
1771
+ args: [powertoolsPath],
1772
+ env: { POWERTOOLS_ROOT: absRoot },
1773
+ });
1774
+ const n = await s.reloadMcp();
1775
+ saveSettings({ mcp: true });
1776
+ sys(`powertools added · root=${absRoot} · wrote ${written} · ${n} fleet tools (alias: pt)`);
1777
+ }
1778
+ catch (e) {
1779
+ sys(`couldn't add powertools: ${e instanceof Error ? e.message : String(e)}`);
1780
+ }
1781
+ }
1782
+ else {
1783
+ sys("usage: /mcp add powertools [root] — upserts secure CLI powertools MCP (root sandboxes path tools)");
1784
+ }
1785
+ }
1715
1786
  else {
1716
1787
  const n = s.mcpToolCount();
1717
- sys(n > 0 ? `${n} fleet MCP tools available this session · /mcp off to disable for new sessions`
1718
- : settings.mcp ? "MCP is on — tools are discovered when you send your first message" : "no MCP tools loaded — /mcp on to enable them");
1788
+ const servers = s.mcpServers();
1789
+ const inv = servers.length
1790
+ ? "\n" + servers.map((sv) => ` · ${sv.name}: ${sv.tools.map((t) => t.name).join(", ") || "(no tools)"}`).join("\n")
1791
+ : "";
1792
+ sys(n > 0
1793
+ ? `${n} fleet MCP tools this session · /mcp reload · /mcp off${inv}`
1794
+ : settings.mcp
1795
+ ? "MCP is on — tools are discovered when you send your first message · /mcp reload after config edits"
1796
+ : "no MCP tools loaded — /mcp on · /mcp add powertools [root] · /mcp reload");
1719
1797
  }
1720
1798
  break;
1721
1799
  }
@@ -1923,11 +2001,18 @@ function Root() {
1923
2001
  }
1924
2002
  sys("checking services…");
1925
2003
  const { ensureServices } = await import("./services/preflight.js");
2004
+ const svcAuroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
1926
2005
  const reports = await ensureServices({
1927
- aurora: { base: settings.endpoints.aurora.base, ...settings.services?.aurora },
2006
+ aurora: svcAuroraCfg,
1928
2007
  autopilot: settings.services?.autopilot,
1929
2008
  vision: settings.services?.vision,
1930
2009
  });
2010
+ if (svcAuroraCfg.base && svcAuroraCfg.base !== settings.endpoints.aurora.base) {
2011
+ settings.endpoints.aurora.base = svcAuroraCfg.base;
2012
+ }
2013
+ const svcKey = svcAuroraCfg.apiKey;
2014
+ if (svcKey && !settings.endpoints.aurora.apiKey)
2015
+ settings.endpoints.aurora.apiKey = svcKey;
1931
2016
  const { searxngStatus, probeSearxng } = await import("./tools/searxng.js");
1932
2017
  const sxActive = searxngStatus() === "active";
1933
2018
  const sxUp = sxActive || await probeSearxng().catch(() => false);
@@ -2162,7 +2247,7 @@ function Root() {
2162
2247
  }, [sendTurn, handleSlash]);
2163
2248
  submitRef.current = onSubmit;
2164
2249
  const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; setQueuedPreview(queued.current); }, []);
2165
- // Shift+Tab cycles the operating mode (Claude-Code parity). auto→manual→plan→auto. Auto drives with
2250
+ // Shift+Tab cycles the operating mode (matches Claude Code). auto→manual→plan→auto. Auto drives with
2166
2251
  // no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
2167
2252
  const onCycleMode = useCallback(() => {
2168
2253
  const cur = opModeRef.current;
@@ -2268,7 +2353,7 @@ function Root() {
2268
2353
  if (boot === "checking")
2269
2354
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
2270
2355
  if (boot === "down") {
2271
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsx(Text, { dimColor: true, children: "The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/com.imi.aurora-serve" })] }));
2356
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsx(Text, { dimColor: true, children: "The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/ai.operator.gateway" })] }));
2272
2357
  }
2273
2358
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
2274
2359
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -88,7 +88,7 @@ export function appendMemory(text, scope = "project", cwd = process.cwd()) {
88
88
  return "";
89
89
  }
90
90
  }
91
- /** Load `$KODE_HOME/SOUL.md` — the Hermes-style identity file. When present, it REPLACES basePersona as
91
+ /** Load `$KODE_HOME/SOUL.md` — a dedicated identity file. When present, it REPLACES basePersona as
92
92
  * the identity block (settings.systemPrompt still wins as explicit override). Head-kept under a cap:
93
93
  * identity leads with what matters most, and an oversized SOUL.md must not be able to blow the prompt
94
94
  * budget every session. Best-effort, never throws. */
@@ -104,7 +104,7 @@ export function loadSoul() {
104
104
  return null;
105
105
  }
106
106
  }
107
- // Structured memories (Hermes parity): `memories/MEMORY.md` (agent notes, hard char budget 2200) and
107
+ // Structured memories: `memories/MEMORY.md` (agent notes, hard char budget 2200) and
108
108
  // `memories/USER.md` (user profile, budget 1375). These are injected BEFORE the legacy flat memories.md
109
109
  // so both layers co-exist during migration. Tail-kept (newest survives the cap, oldest trimmed). Files
110
110
  // are edited by the `memory` tool (batch add/replace/remove with budget enforcement), not appended.
@@ -202,6 +202,12 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
202
202
  `and no AI / Co-Authored-By / Claude-Session trailers.` +
203
203
  `\n## This machine\nWorking dir: ${cwd}` +
204
204
  ctxLine +
205
+ `\n## Talking about yourself\nYou are Operator, whichever model is serving you — the model underneath can change between sessions (or mid-session with /model) and you are still Operator. When asked what you are or which model you run on, ` +
206
+ `say you are Operator (AXE's agent) and give the context window above. Never name, guess or compare backend models (do not say ` +
207
+ `"I am Cortana" or "this is Aurora"), and do not recite hostnames, IP addresses, ports, URLs or file paths for a model's server ` +
208
+ `("running on <host> at <ip>:<port>") unless the owner asks where it runs or you need the address to do the task — you cannot see ` +
209
+ `which backend answered; the footer and /model show the route. If the owner greets you by a model name ("hello cortana"), answer ` +
210
+ `as Operator in the first person, briefly, without confirming or denying which model it is.` +
205
211
  `\n## Don't starve the serving model — decode is RAM-bound\nYour own model is served locally on THIS box. ` +
206
212
  `Loading another large model into memory here (a multi-GB MLX/FLUX/LLM checkpoint, a big \`ml.load\`) competes ` +
207
213
  `for RAM, pushes the box into swap, and collapses your decode to ~1 token/sec — a turn then grinds for an hour ` +
@@ -272,7 +278,7 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
272
278
  // 96e159b swallowed the OPENING line of the section below ("## Running scripts — …\nFor anything more
273
279
  // than a ONE-LINE snippet, write "), orphaning its tail mid-sentence: the LIVE interactive persona
274
280
  // shipped as "...rather than guessing.the script to a file…" — no heading, no space (the persona
275
- // parity test's red on main was the witness). Restored as its own section; do not re-splice.
281
+ // regression test's red on main was the witness). Restored as its own section; do not re-splice.
276
282
  `\n## Running scripts — never inline a multi-line script\nFor anything more than a ONE-LINE snippet, write ` +
277
283
  `the script to a file with file_write and run the file (\`python3 /tmp/probe.py\`). Do NOT embed a ` +
278
284
  `multi-line program inside \`python3 -c "…"\` or \`bash -c "…"\`: the newlines, \`#\` comments and quotes ` +
@@ -312,17 +318,28 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
312
318
  `(shN) and your call returns at once. A finished background job announces itself with a short notice ` +
313
319
  `(exit code, last lines) at your next turn, so do NOT poll bash_output in a loop; read more only when ` +
314
320
  `the notice's tail isn't enough.` +
321
+ `\n## Downloading files\nUse the download_file tool — never curl/wget in bash. It fails loudly on any HTTP error, resumes, retries, ` +
322
+ `refuses an HTML page standing in for the file, verifies size and (when you pass sha256) the hash, and runs in the background; you are ` +
323
+ `notified on completion with the final size + sha256 or the exact error. Start downloads ONE at a time, pass sha256/expected_bytes ` +
324
+ `when a trustworthy value is published, and NEVER say a file is downloaded until the completion notice says so — read the result ` +
325
+ `back (size, \`file\`) if you did not get one. A 0-byte file, an HTML file with an .iso/.zip name, or a failed hash is a FAILURE: ` +
326
+ `report it and fix the URL; do not retry the same command or claim success. Bash curl that writes a file without -f is refused.\n` +
315
327
  `\n## Finding things\nTo search file CONTENTS (a symbol, a string, a config key), use the search tool ` +
316
328
  `(ripgrep — fast, parallel, .gitignore-aware) scoped to a directory: search {"pattern":"…","path":"src"}, ` +
317
- `and set files_with_matches to just locate the files before reading them. NEVER run ` +
318
- `\`find ~/ -maxdepth N | grep | grep\` over the whole home directory — it is slow, hits the command ` +
319
- `timeout, and can wedge the shell. Narrow FIRST: check the 2-3 most likely directories before any broad ` +
320
- `sweep, and batch independent searches in ONE message so they run in parallel.\nWhen asked to find a ` +
321
- `project or file by NAME that is NOT in the working directory: (1) call find_files {"query":"name"} ` +
322
- `first — it reads the OS search index (whole home, instant) and takes kind/extension/modified_within/size ` +
323
- `filters; (2) if it reports the index unavailable, run ls ~ to see the REAL top-level ` +
324
- `folders (projects live in non-obvious ones — e.g. ~/Axwell, ~/.axe/repos, ~/Desktop — not just ` +
325
- `~/Projects); (3) then a BOUNDED find scoped to a SPECIFIC directory with a generous timeout — ` +
329
+ `and set files_with_matches to just locate the files before reading them. The search tool HARD-REFUSES ` +
330
+ `path=$HOME, /, /Users, and other machine-wide roots — do not retry with bash \`grep -r\` / \`rg\` over ` +
331
+ `those same roots; that is the hang you just avoided. NEVER run \`find ~/ | grep\` or ` +
332
+ `search {"path":"$HOME"} — it wedges the TUI for minutes. Narrow FIRST: check the 2-3 most likely ` +
333
+ `directories before any broad sweep, and batch independent searches in ONE message so they run in ` +
334
+ `parallel.\nWhen asked about a FLEET HOST / new box / server name (acropolis, jl1, jla, …): do NOT ` +
335
+ `ripgrep the home directory. Order: (1) \`~/.ssh/config\` Host entries + \`ssh <name> 'hostname; uptime'\`; ` +
336
+ `(2) \`gh repo view axetechnologies/<name>\` / \`gh repo list\` for the matching remote; (3) AGENTS.md / ` +
337
+ `fleet docs / switchboard threads. Content-search only inside a known repo checkout after that.\nWhen ` +
338
+ `asked to find a project or file by NAME that is NOT in the working directory: (1) call find_files ` +
339
+ `{"query":"name"} first — it reads the OS search index (whole home, instant) and takes ` +
340
+ `kind/extension/modified_within/size filters; (2) if it reports the index unavailable, run ls ~ to see ` +
341
+ `the REAL top-level folders (projects live in non-obvious ones — e.g. ~/Axwell, ~/.axe/repos, ~/Desktop ` +
342
+ `— not just ~/Projects); (3) then a BOUNDED find scoped to a SPECIFIC directory with a generous timeout — ` +
326
343
  `shell_exec {"command":"find ~/.axe/repos -maxdepth 3 -iname \\"*name*\\" 2>/dev/null | head -80",` +
327
344
  `"timeout_ms":60000} — never an unbounded find over all of ~ or /. Widen the pattern if a repo may be ` +
328
345
  `named differently. Only report not-found after this real search, and say exactly where you looked.` +
@@ -32,13 +32,14 @@ export function resolveEndpointApiKey(ep) {
32
32
  }
33
33
  return undefined;
34
34
  }
35
- // The sole endpoint: Aurora on :8097 at its REAL served context — 307,200 tokens (300K; the llama-server
36
- // runs --ctx-size 307200 with q8_0 KV cache, standardized on JL1+JL2 2026-09-27). ctxWindow MUST match the
37
- // server's real --ctx-size: an inflated value (it was 1048576/"1M") makes compaction fire far too late — the
38
- // server's real ceiling is hit first, forcing a failover. Override base/model in settings.json for any
39
- // OpenAI-compatible server.
35
+ // Aurora endpoint is discovered from ~/.operator/runtime/server.json (dynamic port).
36
+ // The empty base below is a sentinel — preflight reads server.json and resolves the real base_url
37
+ // before any request. ctxWindow MUST match the server's real --ctx-size. Override in settings.json.
40
38
  const DEFAULTS = {
41
39
  endpoints: {
40
+ // Fallback literal for hosts without a running operator-runtime gateway (mobile, browser, dev).
41
+ // Fleet nodes with ~/.operator/runtime/server.json dynamically override this at startup via the
42
+ // gateway-discovery path in cli.tsx — single source of truth, enterprise-safe for both postures.
42
43
  aurora: { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" },
43
44
  // HA hot-standby: JL2 (64GB) serving Aurora @ 300K on the LAN — task #50, replaces the old
44
45
  // dolphin3-tools:8b "8k trap". Same model + same real window as primary, so a failover holds any live
@@ -67,7 +68,7 @@ const DEFAULTS = {
67
68
  // Service lever — JL1 defaults. On a machine without these launchd agents every start step just fails
68
69
  // harmlessly and the boot screen falls back to the manual hint (autostart is best-effort by design).
69
70
  services: {
70
- aurora: { autostart: true, launchdLabel: "com.imi.aurora-serve", plistPath: "~/Library/LaunchAgents/com.imi.aurora-serve.plist", waitSec: 90 },
71
+ aurora: { autostart: true, launchdLabel: "ai.operator.gateway", plistPath: "~/Library/LaunchAgents/ai.operator.gateway.plist", waitSec: 90 },
71
72
  autopilot: { autostart: true, launchdLabel: "com.axe.autopilot", plistPath: "~/Library/LaunchAgents/com.axe.autopilot.plist", url: "http://127.0.0.1:9333" },
72
73
  vision: { autostart: false, launchdLabel: "axe.vision-bot", plistPath: "~/Library/LaunchAgents/axe.vision-bot.plist", url: "http://127.0.0.1:7788", remoteUrl: "http://192.168.1.103:8095" },
73
74
  stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
@@ -159,6 +160,10 @@ function applyEnv(s) {
159
160
  }
160
161
  if (process.env.KODE_TELEMETRY === "0")
161
162
  out.telemetry = { ...out.telemetry, enabled: false };
163
+ if (process.env.KODE_STORE_URL)
164
+ out.store = { ...out.store, endpoint: process.env.KODE_STORE_URL };
165
+ if (process.env.KODE_STORE_KEY)
166
+ out.store = { ...out.store, key: process.env.KODE_STORE_KEY };
162
167
  const jn = process.env.KODE_BG_JOB_NOTICES;
163
168
  if (jn === "wake" || jn === "queue" || jn === "off")
164
169
  out.background = { ...out.background, jobNotices: jn };
@@ -338,7 +343,7 @@ export function buildEndpointChain(s) {
338
343
  seen.add(key);
339
344
  chain.push(ep);
340
345
  };
341
- add({ name: "operator-1m", base: aurora.base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(aurora) });
346
+ add({ name: "operator-1m", base: aurora.base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(aurora), loopbackAuth: true });
342
347
  for (const base of (s.fleet?.auroraNodes ?? []).filter(Boolean)) {
343
348
  const cfg = { base, model: aurora.model, ctxWindow: aurora.ctxWindow };
344
349
  add({ name: `fleet-${hostLabel(base)}`, base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(cfg) });
@@ -583,7 +583,7 @@ export async function runTurn(userInput, conversation, opts) {
583
583
  const continuationMax = Math.max(0, opts.turnContinuation?.maxNudges ?? ANNOUNCE_NUDGE_MAX);
584
584
  let announceNudges = 0;
585
585
  let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
586
- // Spectre-parity (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
586
+ // Spectre fix (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
587
587
  let truncationContinues = 0;
588
588
  const TRUNCATION_CONTINUE_MAX = 3;
589
589
  // One-shot: the empty-retry path sets this to the perturbed temperature for the NEXT request only (0 = use
@@ -764,6 +764,7 @@ export async function runTurn(userInput, conversation, opts) {
764
764
  base: endpoint.base,
765
765
  model: endpoint.model,
766
766
  token: endpoint.token,
767
+ loopbackAuth: endpoint.loopbackAuth,
767
768
  transport: endpoint.transport,
768
769
  maxTokens,
769
770
  // Empty-retry perturbation: a greedy (temp 0) empty is deterministic, so the retry must change the
@@ -930,6 +931,7 @@ export async function runTurn(userInput, conversation, opts) {
930
931
  base: endpoint.base,
931
932
  model: endpoint.model,
932
933
  token: endpoint.token,
934
+ loopbackAuth: endpoint.loopbackAuth,
933
935
  transport: endpoint.transport,
934
936
  maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
935
937
  temperature: opts.temperature,
@@ -1256,7 +1258,7 @@ export async function runTurn(userInput, conversation, opts) {
1256
1258
  // answered as the instruction it is) to actually call the tool(s), and keep going. Bounded per turn
1257
1259
  // (continuationMax) so it can never force an unbounded turn; the converge guard stops circling. A truncated
1258
1260
  // reply ("length") has an unreliable tail, so it is left to the normal finalize path.
1259
- // Spectre-parity fix (b), verified by nova's loop trace + live screenshot: a round CUT OFF by the
1261
+ // Spectre fix (b), verified by nova's loop trace + live screenshot: a round CUT OFF by the
1260
1262
  // output limit that still produced non-empty text was finalizing the turn — the model was mid-work,
1261
1263
  // the owner saw it stop halfway, and think-mode models hit this most (long reasoning eats the budget).
1262
1264
  // Keep the partial artifact, demand an exact continuation, bounded (3/turn) so a pathological model