@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
@@ -99,8 +99,13 @@ export function getOperatorToken() { return _operatorToken; }
99
99
  * loopback exclusion: an ingest on a loopback AuthGate is exactly where the bearer is required). */
100
100
  export function operatorTrustedUrl(url) { return isOperatorTrustedHost(hostOf(url)); }
101
101
  export function authHeaders(o) {
102
- if (!isRemoteBase(o.base))
103
- return {}; // a local server never gets any bearer — vendor or operator
102
+ if (!isRemoteBase(o.base)) {
103
+ // A local llama-server normally gets no bearer. The one exception is the local gateway (server.json),
104
+ // which publishes an api_key for its loopback port: send that EXPLICIT, loopback-safe key (loopbackAuth)
105
+ // when present. A BYO vendor key never sets loopbackAuth, and the operator identity token is never the
106
+ // source here, so neither can leak to a local server.
107
+ return o.loopbackAuth && o.token ? { Authorization: `Bearer ${o.token}` } : {};
108
+ }
104
109
  const token = o.token ?? (isOperatorTrustedHost(hostOf(o.base)) ? _operatorToken : undefined);
105
110
  return token ? { Authorization: `Bearer ${token}` } : {};
106
111
  }
@@ -272,7 +277,7 @@ async function fetchChat(o, body) {
272
277
  method: "POST",
273
278
  headers: { "Content-Type": "application/json", ...authHeaders(o) },
274
279
  body,
275
- signal: o.signal, // SPEC §9 interrupt parity: tears down the in-flight stream on abort, not at the next loop boundary
280
+ signal: o.signal, // SPEC §9 interrupt handling: tears down the in-flight stream on abort, not at the next loop boundary
276
281
  });
277
282
  }
278
283
  catch (e) {
@@ -16,14 +16,14 @@
16
16
  // • Barrier tools (git_command/checkpoint/computer_*/browser*/delegate_*/…) can touch ANYTHING and
17
17
  // share a device — they run alone, in input order.
18
18
  // • Shell tools (bash/shell_exec) can also touch anything, but INDEPENDENT shells in one round run
19
- // concurrently (Cursor-parity). A shell waits for every prior non-shell; later non-shells wait for
19
+ // concurrently (matches Cursor). A shell waits for every prior non-shell; later non-shells wait for
20
20
  // the whole shell wave. Shells do NOT wait for each other. (Ephemeral one-shot processes when a
21
21
  // round has ≥2 shells — see shellExecMode; lone bash still uses the persistent session.)
22
22
  // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
23
23
  // failure never strands its dependents — the chain advances regardless.
24
24
  // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
25
25
  export const cancelledResult = (name) => `cancelled: ${name} did not start — the turn was interrupted before it ran`;
26
- /** Foreground shells that may run concurrently within one model round (Cursor-parity). */
26
+ /** Foreground shells that may run concurrently within one model round (matches Cursor). */
27
27
  const SHELL_EXACT = new Set(["bash", "shell_exec"]);
28
28
  const BARRIER_EXACT = new Set([
29
29
  "shell_background", "bash_kill",
@@ -136,7 +136,7 @@ export function runBatch(calls, opts) {
136
136
  gate.push(p); // a barrier runs ALONE: waits for everything prior
137
137
  }
138
138
  else if (kind === "shell") {
139
- // Cursor-parity: independent shells overlap. Wait for prior barriers + prior NON-shell work;
139
+ // Matching Cursor: independent shells overlap. Wait for prior barriers + prior NON-shell work;
140
140
  // do NOT wait for other shells in this wave.
141
141
  gate.push(afterBarrier);
142
142
  for (const p of inflight)
@@ -142,7 +142,7 @@ export function fitToWindow(conversation, opts, targetRatio) {
142
142
  return out;
143
143
  }
144
144
  /** Clamp generation length so prompt + output never exceeds the window. A static max_tokens plus a
145
- * deep-session prompt otherwise gets the model squeezed to a truncated reply (parity with the Python
145
+ * deep-session prompt otherwise gets the model squeezed to a truncated reply (matching the Python
146
146
  * core's _predict_budget). `built` already includes the system message, so pass systemPrompt:undefined
147
147
  * to avoid double-counting it; tool-schema tokens still come from opts.tools. Floored (≥1024) so a
148
148
  * tool-calling round keeps room to emit a full tool call's arguments instead of truncating mid-JSON — a
@@ -74,7 +74,7 @@ const EXIT_TRAILER_RE = /(?:\[exit (\d+)\]|^\(no output; exit (\d+|\?)\))\s*$/;
74
74
  export function isRepeatable(name, args) {
75
75
  if (POLLER_TOOLS.has(name))
76
76
  return true;
77
- // Hermes parity: generated/MCP poller naming conventions are legitimately re-invoked with identical args.
77
+ // A known allowance: generated/MCP poller naming conventions are legitimately re-invoked with identical args.
78
78
  if (name.endsWith("_poll") || name.endsWith("_get_result"))
79
79
  return true;
80
80
  return SHELL_TOOLS.has(name) && POLL_COMMAND_RE.test(String(args.command ?? ""));
@@ -10,6 +10,7 @@ const toRE = (e) => ({
10
10
  ctxWindow: e.ctxLimit,
11
11
  label: e.name,
12
12
  token: e.token,
13
+ loopbackAuth: e.loopbackAuth,
13
14
  transport: e.transport,
14
15
  });
15
16
  function estimateTokens(messages, tools) {
@@ -0,0 +1,20 @@
1
+ // Owner activity for THIS process: when they last typed, when the last piece of work finished. Module-level on purpose — the
2
+ // Composer, the turn loop and the monitor live in different trees and must not need a shared ref to agree on one clock.
3
+ let lastInputAt = Date.now();
4
+ let lastWorkAt = 0;
5
+ /** The owner pressed a key / pasted / submitted. Cheap enough to call on every keystroke. */
6
+ export function touchInput(now = Date.now()) {
7
+ lastInputAt = now;
8
+ }
9
+ /** A turn, job or agent just finished: the clock for "nobody has looked at this" starts now, not when it began. */
10
+ export function touchWork(now = Date.now()) {
11
+ lastWorkAt = now;
12
+ }
13
+ export function lastActiveAt() {
14
+ return Math.max(lastInputAt, lastWorkAt);
15
+ }
16
+ /** Test seam: forget everything and start the clock at `now`. */
17
+ export function resetActivity(now = Date.now()) {
18
+ lastInputAt = now;
19
+ lastWorkAt = 0;
20
+ }
@@ -0,0 +1,5 @@
1
+ export { DEFAULT_IDLE_POLICY, evaluateIdle, formatSpan, resolveIdlePolicy } from "./policy.js";
2
+ export { lastActiveAt, resetActivity, touchInput, touchWork } from "./activity.js";
3
+ export { startIdleMonitor } from "./monitor.js";
4
+ export { listSessionRecords, parseSessionRecord, removeSessionRecord, writeSessionRecord } from "./session-record.js";
5
+ export { REAPER_SLACK_MS, STALE_HEARTBEAT_MS, executeReap, planReap } from "./reaper.js";
@@ -0,0 +1,71 @@
1
+ // The in-app half: one unref'd timer per interactive session. Each tick it publishes the session record (for the reaper), asks
2
+ // `evaluateIdle` what to do, warns once per idle spell, and — after a short grace in which the owner can still save the session
3
+ // by pressing a key — ends it through the ONE idempotent Teardown, the same path as /exit. It never signals anything itself.
4
+ import { evaluateIdle, formatSpan } from "./policy.js";
5
+ import { removeSessionRecord, writeSessionRecord } from "./session-record.js";
6
+ export function startIdleMonitor(deps) {
7
+ const now = deps.now ?? Date.now;
8
+ const pidStartedAt = Math.round(Date.now() - process.uptime() * 1000);
9
+ let warnedFor = null; // "<reason>@<lastActiveAt>": warn once per idle spell, again only after the owner came back and left
10
+ let ending = false;
11
+ let timer;
12
+ const publish = (s, t) => {
13
+ if (deps.record === false)
14
+ return;
15
+ const r = { pid: process.pid, pidStartedAt, startedAt: s.startedAt, lastActiveAt: s.lastActiveAt, heartbeatAt: t, busy: s.busy, ...(deps.version ? { version: deps.version } : {}), ...(deps.tty ? { tty: deps.tty } : {}) };
16
+ writeSessionRecord(r);
17
+ };
18
+ const tick = () => {
19
+ if (ending)
20
+ return;
21
+ const t = now();
22
+ const s = deps.state();
23
+ publish(s, t);
24
+ const d = evaluateIdle(s, t, deps.policy);
25
+ if (d.action === "none") {
26
+ warnedFor = null;
27
+ return;
28
+ }
29
+ if (d.action === "warn") {
30
+ const key = `${d.reason}@${s.lastActiveAt}`;
31
+ if (warnedFor === key)
32
+ return;
33
+ warnedFor = key;
34
+ deps.notify(d.reason === "idle"
35
+ ? `No activity — this session ends in ${formatSpan(d.endsInMs)}. Press any key to keep it.`
36
+ : `This session reaches its ${formatSpan(deps.policy.absoluteMs)} limit in ${formatSpan(d.endsInMs)}.`);
37
+ return;
38
+ }
39
+ ending = true;
40
+ deps.notify(d.reason === "idle" ? `Idle for ${formatSpan(deps.policy.idleMs)} — ending the session.` : `Session limit of ${formatSpan(deps.policy.absoluteMs)} reached — ending the session.`);
41
+ const finish = () => {
42
+ // The owner may have come back during the grace: judge again, on fresh state, before pulling the plug.
43
+ const again = evaluateIdle(deps.state(), now(), deps.policy);
44
+ if (again.action === "end") {
45
+ stop();
46
+ deps.end(again.reason);
47
+ return;
48
+ }
49
+ ending = false;
50
+ warnedFor = null;
51
+ };
52
+ if (deps.policy.graceMs <= 0)
53
+ finish();
54
+ else {
55
+ timer = setTimeout(finish, deps.policy.graceMs);
56
+ timer.unref?.();
57
+ }
58
+ };
59
+ const stop = () => {
60
+ if (timer)
61
+ clearTimeout(timer);
62
+ timer = undefined;
63
+ if (deps.record !== false)
64
+ removeSessionRecord();
65
+ };
66
+ const every = deps.tickMs ?? 30_000;
67
+ const interval = setInterval(tick, every);
68
+ interval.unref?.();
69
+ tick();
70
+ return { tick, stop: () => { clearInterval(interval); stop(); } };
71
+ }
@@ -0,0 +1,66 @@
1
+ // Idle-session policy: pure, no I/O. Two clocks, the way every mature platform does it (Codespaces, Session Manager, Coder):
2
+ // idle — no owner input and no finished work for `idleMs` → warn at idleMs-warnMs, then end the session
3
+ // absolute — the session has lived `absoluteMs` whatever it did → end it (a hard cap an activity bump can't push past)
4
+ // A session that is DOING something (a turn, a background job or agent, a connected remote) is never idle: Jupyter's
5
+ // `cull_busy=false`. The monitor (monitor.ts) and the external reaper (reaper.ts) both call `evaluateIdle`, so they cannot disagree.
6
+ export const DEFAULT_IDLE_POLICY = {
7
+ enabled: true,
8
+ idleMs: 60 * 60_000,
9
+ warnMs: 5 * 60_000,
10
+ absoluteMs: 8 * 60 * 60_000,
11
+ graceMs: 10_000,
12
+ };
13
+ const num = (v) => {
14
+ const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
15
+ return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : undefined;
16
+ };
17
+ /** Settings, then env (env wins). `KODE_IDLE_MINUTES=0` or `KODE_IDLE_ABSOLUTE_HOURS=0` switches that clock off; a bad value is ignored. */
18
+ export function resolveIdlePolicy(raw, env = process.env) {
19
+ const s = (raw && typeof raw === "object" ? raw : {});
20
+ const d = DEFAULT_IDLE_POLICY;
21
+ const minutes = num(env.KODE_IDLE_MINUTES) ?? num(s.idleMinutes);
22
+ const warn = num(env.KODE_IDLE_WARN_MINUTES) ?? num(s.warnMinutes);
23
+ const hours = num(env.KODE_IDLE_ABSOLUTE_HOURS) ?? num(s.absoluteHours);
24
+ const grace = num(s.graceSeconds);
25
+ const off = env.KODE_IDLE === "0" || s.enabled === false;
26
+ const idleMs = minutes === undefined ? d.idleMs : minutes * 60_000;
27
+ return {
28
+ enabled: !off,
29
+ idleMs,
30
+ // a warning longer than the idle window would fire before the idle clock even started
31
+ warnMs: Math.min(warn === undefined ? d.warnMs : warn * 60_000, idleMs),
32
+ absoluteMs: hours === undefined ? d.absoluteMs : hours * 3_600_000,
33
+ graceMs: grace === undefined ? d.graceMs : grace * 1000,
34
+ };
35
+ }
36
+ export function evaluateIdle(state, now, policy) {
37
+ if (!policy.enabled)
38
+ return { action: "none" };
39
+ const age = now - state.startedAt;
40
+ // The absolute cap ends a session even when it is busy only if the owner is also gone: a long job the owner is watching
41
+ // (recent input) is theirs to finish. Busy + no input for a whole idle window past the cap is an abandoned runaway.
42
+ if (policy.absoluteMs > 0 && age >= policy.absoluteMs) {
43
+ const abandoned = policy.idleMs === 0 || now - state.lastActiveAt >= policy.idleMs;
44
+ if (!state.busy || abandoned)
45
+ return { action: "end", reason: "absolute" };
46
+ }
47
+ if (state.busy || policy.idleMs === 0)
48
+ return { action: "none" };
49
+ const idle = now - state.lastActiveAt;
50
+ if (idle >= policy.idleMs)
51
+ return { action: "end", reason: "idle" };
52
+ if (policy.warnMs > 0 && idle >= policy.idleMs - policy.warnMs)
53
+ return { action: "warn", reason: "idle", endsInMs: policy.idleMs - idle };
54
+ if (policy.absoluteMs > 0 && policy.warnMs > 0 && age >= policy.absoluteMs - policy.warnMs) {
55
+ return { action: "warn", reason: "absolute", endsInMs: policy.absoluteMs - age };
56
+ }
57
+ return { action: "none" };
58
+ }
59
+ /** "47m", "1h 05m", "30s" — for the warning line and the logs. */
60
+ export function formatSpan(ms) {
61
+ const s = Math.max(0, Math.round(ms / 1000));
62
+ if (s < 90)
63
+ return `${s}s`;
64
+ const m = Math.round(s / 60);
65
+ return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
66
+ }
@@ -0,0 +1,22 @@
1
+ // What the reaper needs to know about a pid, from the OS. `ps` is the portable source on macOS and Linux (no /proc on macOS).
2
+ import { execFileSync } from "node:child_process";
3
+ export function pidAlive(pid) {
4
+ try {
5
+ process.kill(pid, 0);
6
+ return true;
7
+ }
8
+ catch (e) {
9
+ return e.code === "EPERM";
10
+ }
11
+ }
12
+ /** The pid's start time in ms since epoch, or undefined when it cannot be read. `ps -o lstart=` prints local time with second precision. */
13
+ export function pidStartedAt(pid) {
14
+ try {
15
+ const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 3000, env: { ...process.env, LC_ALL: "C" } }).trim();
16
+ const t = Date.parse(out);
17
+ return Number.isFinite(t) ? t : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
@@ -0,0 +1,69 @@
1
+ // The backstop: an external sweep (scripts/idle-reaper, run by launchd) that ends an interactive session whose own monitor did not —
2
+ // a wedged event loop, a monitor that crashed, a build without the monitor. It judges ONLY pids that published a session record
3
+ // (session-record.ts), by the same `evaluateIdle` the monitor uses, but with slack so it never races the monitor's graceful path.
4
+ // Pure planning (`planReap`) is split from the signalling (`executeReap`) so every decision is testable without killing anything.
5
+ import { evaluateIdle, formatSpan } from "./policy.js";
6
+ /** The monitor ticks every 30s and warns/grace-waits before it ends a session; the reaper waits this much longer than the
7
+ * policy before it steps in, so a healthy session is always ended by its own monitor. */
8
+ export const REAPER_SLACK_MS = 5 * 60_000;
9
+ /** No heartbeat for this long = the session's loop is wedged: nothing alive in there can be "busy". */
10
+ export const STALE_HEARTBEAT_MS = 10 * 60_000;
11
+ const START_TOLERANCE_MS = 5000;
12
+ export function planReap(records, d) {
13
+ const slacked = { ...d.policy, idleMs: d.policy.idleMs === 0 ? 0 : d.policy.idleMs + REAPER_SLACK_MS, absoluteMs: d.policy.absoluteMs === 0 ? 0 : d.policy.absoluteMs + REAPER_SLACK_MS, warnMs: 0 };
14
+ return records.map((r) => {
15
+ if (!d.alive(r.pid))
16
+ return { pid: r.pid, verdict: "forget", why: "process is gone" };
17
+ const real = d.startedAt(r.pid);
18
+ if (real !== undefined && Math.abs(real - r.pidStartedAt) > START_TOLERANCE_MS)
19
+ return { pid: r.pid, verdict: "forget", why: "pid was recycled by another process" };
20
+ if (real === undefined)
21
+ return { pid: r.pid, verdict: "keep", why: "cannot verify the pid's identity" };
22
+ const wedged = d.now - r.heartbeatAt >= STALE_HEARTBEAT_MS;
23
+ const dec = evaluateIdle({ startedAt: r.startedAt, lastActiveAt: r.lastActiveAt, busy: wedged ? false : r.busy }, d.now, slacked);
24
+ if (dec.action === "end") {
25
+ const idle = formatSpan(d.now - r.lastActiveAt);
26
+ return { pid: r.pid, verdict: "end", reason: dec.reason, why: dec.reason === "idle" ? `idle ${idle}${wedged ? ", heartbeat stale" : ""}` : `lived ${formatSpan(d.now - r.startedAt)}, past the limit` };
27
+ }
28
+ return { pid: r.pid, verdict: "keep", why: r.busy && !wedged ? "busy" : "within policy" };
29
+ });
30
+ }
31
+ /** Apply a plan. `enforce:false` is the dry run: log what would happen, signal nothing, forget nothing. */
32
+ export async function executeReap(plan, enforce, d) {
33
+ const out = { ended: [], killed: [], forgotten: [], kept: [] };
34
+ const wait = d.termWaitMs ?? 15_000;
35
+ for (const p of plan) {
36
+ if (p.verdict === "keep") {
37
+ out.kept.push(p.pid);
38
+ continue;
39
+ }
40
+ if (p.verdict === "forget") {
41
+ d.log(`${enforce ? "forget" : "would forget"} record ${p.pid}: ${p.why}`);
42
+ if (enforce) {
43
+ d.forget(p.pid);
44
+ out.forgotten.push(p.pid);
45
+ }
46
+ continue;
47
+ }
48
+ if (!enforce) {
49
+ d.log(`would end ${p.pid} (${p.reason}): ${p.why}`);
50
+ out.ended.push(p.pid);
51
+ continue;
52
+ }
53
+ d.log(`ending ${p.pid} (${p.reason}): ${p.why} — SIGTERM`);
54
+ d.kill(p.pid, "SIGTERM"); // Operator's SIGTERM handler runs the same Teardown as /exit
55
+ const t0 = Date.now();
56
+ while (d.alive(p.pid) && Date.now() - t0 < wait)
57
+ await d.sleep(250);
58
+ if (d.alive(p.pid)) {
59
+ d.log(`${p.pid} ignored SIGTERM for ${formatSpan(wait)} — SIGKILL`);
60
+ d.kill(p.pid, "SIGKILL");
61
+ out.killed.push(p.pid);
62
+ }
63
+ out.ended.push(p.pid);
64
+ d.forget(p.pid);
65
+ }
66
+ if (enforce && out.ended.length)
67
+ d.reapLeftovers?.();
68
+ return out;
69
+ }
@@ -0,0 +1,59 @@
1
+ // One small record per live interactive session at <home>/run/sessions/<pid>.json. It is how the external reaper (reaper.ts) knows what
2
+ // to judge: the session says when it started, when its owner was last active and whether it is busy, and refreshes `heartbeatAt`
3
+ // every tick. The reaper only ever touches pids that have a record here, so a launchd-owned service (Aurora, autopilot, the swarm
4
+ // console) — which never writes one — can never be reached by it.
5
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { operatorPath } from "../config/home.js";
8
+ const dir = () => operatorPath("run", "sessions");
9
+ const fileFor = (pid) => join(dir(), `${pid}.json`);
10
+ export function writeSessionRecord(r) {
11
+ try {
12
+ mkdirSync(dir(), { recursive: true, mode: 0o700 });
13
+ const tmp = `${fileFor(r.pid)}.tmp`;
14
+ writeFileSync(tmp, JSON.stringify(r), { mode: 0o600 });
15
+ renameSync(tmp, fileFor(r.pid)); // atomic: a concurrent reaper never reads half a file
16
+ }
17
+ catch { /* best-effort: a session that cannot write its record is simply invisible to the reaper */ }
18
+ }
19
+ export function removeSessionRecord(pid = process.pid) {
20
+ try {
21
+ rmSync(fileFor(pid), { force: true });
22
+ }
23
+ catch { /* */ }
24
+ }
25
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
26
+ export function parseSessionRecord(text) {
27
+ try {
28
+ const r = JSON.parse(text);
29
+ if (!isNum(r.pid) || r.pid <= 1 || !isNum(r.pidStartedAt) || !isNum(r.startedAt) || !isNum(r.lastActiveAt) || !isNum(r.heartbeatAt) || typeof r.busy !== "boolean")
30
+ return null;
31
+ return {
32
+ pid: r.pid, pidStartedAt: r.pidStartedAt, startedAt: r.startedAt, lastActiveAt: r.lastActiveAt, heartbeatAt: r.heartbeatAt, busy: r.busy,
33
+ ...(typeof r.version === "string" ? { version: r.version } : {}),
34
+ ...(typeof r.tty === "string" ? { tty: r.tty } : {}),
35
+ };
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ export function listSessionRecords() {
42
+ let names;
43
+ try {
44
+ names = readdirSync(dir()).filter((n) => /^\d+\.json$/.test(n));
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ const out = [];
50
+ for (const n of names) {
51
+ try {
52
+ const r = parseSessionRecord(readFileSync(join(dir(), n), "utf8"));
53
+ if (r && `${r.pid}.json` === n)
54
+ out.push(r);
55
+ }
56
+ catch { /* unreadable: skip */ }
57
+ }
58
+ return out;
59
+ }
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ export { registry, toSchemas } from "./tools/registry.js";
24
24
  // MCP fleet-tool surface (SPEC §10) — the node barrel exposes the FULL subsystem (http + stdio + config
25
25
  // file), for hosts that run in node (the CLI, and kode-web's Electron main process where the hub lives).
26
26
  export { McpHub, withMcp } from "./mcp/index.js";
27
- export { loadMcpConfig } from "./mcp/config.js";
27
+ export { loadMcpConfig, upsertMcpServer, mcpWritePath } from "./mcp/config.js";
28
28
  export { McpHttpClient } from "./mcp/client.js";
29
29
  // UI (kode-web can reuse these Ink components' patterns; kode-web renders its own React DOM tree)
30
30
  export { App } from "./ui/index.js";
@@ -61,24 +61,22 @@ function expand(obj, secrets) {
61
61
  }
62
62
  return obj;
63
63
  }
64
- /** Load + secret-expand + normalize the server map. Returns [] on any failure (never throws). Node path
65
- * only (reads a file); browser/JSCore hosts inject their http server list into McpHub directly instead. */
66
- export async function loadMcpConfig(configPath = env().KODE_MCP_CONFIG, secretsPath = env().KODE_MCP_SECRETS) {
67
- const cfgPath = configPath ?? (await defaultPath("mcp_servers.json"));
68
- const secPath = secretsPath ?? (await defaultPath(".mcp_secrets.json"));
69
- let raw;
70
- try {
71
- raw = (await readJson(cfgPath));
72
- }
73
- catch {
74
- return [];
75
- }
76
- const secrets = await loadSecrets(secPath);
77
- const servers = (raw && typeof raw === "object" && "mcpServers" in raw ? raw.mcpServers : raw) ?? {};
64
+ function normalizeServerMap(raw) {
65
+ if (!raw || typeof raw !== "object")
66
+ return {};
67
+ const o = raw;
68
+ const servers = ("mcpServers" in o ? o.mcpServers : o);
69
+ return servers && typeof servers === "object" ? servers : {};
70
+ }
71
+ function toConfigs(servers, secrets) {
78
72
  return Object.entries(servers).map(([name, cfg]) => {
79
73
  const c = expand(cfg, secrets);
80
74
  const t = (c.type ?? c.transport ?? (c.url ? "http" : "stdio"));
81
75
  const transport = t === "http" || t === "sse" || t === "streamable-http" ? "http" : "stdio";
76
+ const toolsRaw = c.tools;
77
+ const tools = Array.isArray(toolsRaw)
78
+ ? toolsRaw.filter((t) => typeof t === "string" && t.length > 0)
79
+ : undefined;
82
80
  return {
83
81
  name,
84
82
  transport,
@@ -88,6 +86,66 @@ export async function loadMcpConfig(configPath = env().KODE_MCP_CONFIG, secretsP
88
86
  args: c.args,
89
87
  env: c.env,
90
88
  advertise: c.advertise !== false,
89
+ // Hub filters advertise set by bare tool name when present (see McpHub.discover).
90
+ ...(tools && tools.length ? { tools } : {}),
91
91
  };
92
92
  });
93
93
  }
94
+ /** Load + secret-expand + normalize the server map. Returns [] on any failure (never throws). Node path
95
+ * only (reads a file); browser/JSCore hosts inject their http server list into McpHub directly instead.
96
+ *
97
+ * Merge-load: after the base config, if `$KODE_MCP_EXTRA` points at a JSON file, those servers are
98
+ * layered on top (same name → extra wins). Lets live-drive add powertools without rewriting the fleet
99
+ * registry — pair with `/mcp reload` so the hub rediscovers without a process restart. */
100
+ export async function loadMcpConfig(configPath = env().KODE_MCP_CONFIG, secretsPath = env().KODE_MCP_SECRETS) {
101
+ const cfgPath = configPath ?? (await defaultPath("mcp_servers.json"));
102
+ const secPath = secretsPath ?? (await defaultPath(".mcp_secrets.json"));
103
+ let raw;
104
+ try {
105
+ raw = await readJson(cfgPath);
106
+ }
107
+ catch {
108
+ raw = {};
109
+ }
110
+ const secrets = await loadSecrets(secPath);
111
+ const merged = { ...normalizeServerMap(raw) };
112
+ const extraPath = env().KODE_MCP_EXTRA;
113
+ if (extraPath) {
114
+ try {
115
+ Object.assign(merged, normalizeServerMap(await readJson(extraPath)));
116
+ }
117
+ catch {
118
+ /* missing/garbled extra — ignore */
119
+ }
120
+ }
121
+ return toConfigs(merged, secrets);
122
+ }
123
+ /** Resolve where a live `/mcp add` write should land: `$KODE_MCP_EXTRA` if set, else the operator-home
124
+ * mcp_servers.json (creating it when absent). Never touches a read-only `$KODE_MCP_CONFIG` override
125
+ * unless it is also the extra path — fleet registries stay intact. */
126
+ export async function mcpWritePath() {
127
+ const extra = env().KODE_MCP_EXTRA;
128
+ if (extra)
129
+ return extra;
130
+ return defaultPath("mcp_servers.json");
131
+ }
132
+ /** Upsert one server entry into the writable overlay (see mcpWritePath). Returns the path written. */
133
+ export async function upsertMcpServer(name, entry) {
134
+ const { mkdir, writeFile } = await nodeImport("node:fs/promises");
135
+ const { dirname } = await nodeImport("node:path");
136
+ const path = await mcpWritePath();
137
+ let raw = {};
138
+ try {
139
+ raw = (await readJson(path));
140
+ }
141
+ catch {
142
+ raw = {};
143
+ }
144
+ const wrapped = raw && typeof raw === "object" && "mcpServers" in raw;
145
+ const servers = normalizeServerMap(raw);
146
+ servers[name] = entry;
147
+ const out = wrapped ? { ...raw, mcpServers: servers } : servers;
148
+ await mkdir(dirname(path), { recursive: true });
149
+ await writeFile(path, JSON.stringify(out, null, 2) + "\n", "utf8");
150
+ return path;
151
+ }
package/dist/mcp/index.js CHANGED
@@ -31,8 +31,15 @@ export class McpHub {
31
31
  return new McpHub(await loadMcpConfig());
32
32
  }
33
33
  /** Discover tools from every advertised server (HTTP + stdio), once. Failures are per-server
34
- * (a down gateway or a missing stdio binary is skipped) so the rest still register — never throws. */
35
- async discover() {
34
+ * (a down gateway or a missing stdio binary is skipped) so the rest still register — never throws.
35
+ * Pass `{ force: true }` after `/mcp reload` / config upsert to tear down clients and rediscover. */
36
+ async discover(opts) {
37
+ if (opts?.force) {
38
+ this.shutdown();
39
+ this.tools.clear();
40
+ this.clients = [];
41
+ this.ready = null;
42
+ }
36
43
  if (this.ready)
37
44
  return this.ready;
38
45
  this.ready = (async () => {
@@ -1,5 +1,5 @@
1
1
  // Auto-memory — SPEC §8. A durable, append-only note store the agent recalls at session start and
2
- // writes to as it learns, so operator remembers across sessions (parity with the Python core's
2
+ // writes to as it learns, so operator remembers across sessions (matching the Python core's
3
3
  // auto-memory). JSONL on disk; recall by recency or substring. The memory_store/memory_search TOOLS
4
4
  // (tools/registry.ts) and the session's start-of-run recall both read/write through this one store.
5
5
  //
@@ -4,10 +4,15 @@ import { centralRecording } from "../telemetry/ingest.js";
4
4
  import { runBatch, defaultClassify, defaultKeys, cancelledResult } from "../engine/batch-scheduler.js";
5
5
  import { registrySafeTools } from "./tier.js";
6
6
  export { PermissionPolicy } from "./policy.js";
7
- const DENIED = (name) => `Permission denied: "${name}" was refused by the operator permission policy. ` +
8
- `Ask the user to approve it, or run in a mode that allows it.`;
9
- const TIER_DENIED = (name, tier) => `Permission denied: "${name}" is not available on the "${tier}" tier. ` +
10
- `This seat has a narrowed toolset; a full-access (admin) seat is required for this tool.`;
7
+ const NO_RETRY = "Do not retry this call or an equivalent; choose another approach or ask the user.";
8
+ const DENIED = (name, why) => `Permission denied: "${name}" was denied ` +
9
+ (why === "policy" ? "BY POLICY (the operator permission policy refuses it)."
10
+ : why === "user" ? "BY THE USER (the approval prompt was declined)."
11
+ : "BY POLICY (it needs approval and no approver is available to give it).") +
12
+ ` ${NO_RETRY}`;
13
+ const TIER_DENIED = (name, tier) => `Permission denied: "${name}" was denied BY POLICY: it is not available on the "${tier}" tier. ` +
14
+ `This seat has a narrowed toolset; a full-access (admin) seat is required for this tool. ${NO_RETRY}`;
15
+ const REPEAT_DENIED = (first) => `${first} (Repeat of an already-denied call; it was not executed or re-prompted.)`;
11
16
  export function withPermissions(inner, policy, opts = {}) {
12
17
  if (policy.inert && !centralRecording())
13
18
  return inner; // bypass + admin tier + no rules, signed out → nothing to enforce or log; skip entirely
@@ -18,6 +23,9 @@ export function withPermissions(inner, policy, opts = {}) {
18
23
  const sinkNow = () => (recording() ? (lazySink ??= new EventSink()) : undefined);
19
24
  const actor = opts.actor ?? { tier: policy.currentTier(), surface: "cli" };
20
25
  const session = opts.session ?? "";
26
+ // Identical (tool+args) calls already denied in this wrapper's lifetime -> the message returned then. A repeat is
27
+ // refused outright: no execution, no second approval prompt.
28
+ const denied = new Map();
21
29
  const tool = (t, argHash) => {
22
30
  const connectorId = connectorOf(t.name);
23
31
  sinkNow()?.emit({ kind: "tool", session, actor, tool: { ...t, ...(argHash ? { argHash } : {}), ...(connectorId ? { connectorId } : {}) } });
@@ -28,6 +36,13 @@ export function withPermissions(inner, policy, opts = {}) {
28
36
  async function gate(name, args, exec, batch, signal) {
29
37
  const digest = digestArgs(name, args);
30
38
  const argHash = recording() ? argHashOf(args, digest) : undefined; // hashed BEFORE the tool runs: the args as issued
39
+ const denyKey = `${name}\0${argHashOf(args, digest)}`;
40
+ const prior = denied.get(denyKey);
41
+ if (prior) {
42
+ tool({ name, args: digest, decision: "deny", outcome: "denied", approved: false, ...batch }, argHash);
43
+ return REPEAT_DENIED(prior);
44
+ }
45
+ const refuse = (msg) => { denied.set(denyKey, msg); return msg; };
31
46
  const decision = policy.decide(name, args);
32
47
  const t0 = performance.now();
33
48
  if (decision === "deny") {
@@ -35,10 +50,10 @@ export function withPermissions(inner, policy, opts = {}) {
35
50
  if (!policy.allowsTool(name)) {
36
51
  sinkNow()?.emit({ kind: "control", session, actor, control: { event: "tool_denied_by_tier", detail: `${name} @ ${actor.tier}` } });
37
52
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
38
- return TIER_DENIED(name, actor.tier);
53
+ return refuse(TIER_DENIED(name, actor.tier));
39
54
  }
40
55
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
41
- return DENIED(name);
56
+ return refuse(DENIED(name, "policy"));
42
57
  }
43
58
  let approved;
44
59
  if (decision === "ask") {
@@ -50,7 +65,7 @@ export function withPermissions(inner, policy, opts = {}) {
50
65
  approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
51
66
  if (!approved) {
52
67
  tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
53
- return DENIED(name);
68
+ return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
54
69
  }
55
70
  }
56
71
  // An esc during the (human) approval wait: the approval may land AFTER the interrupt, and an approved edit
@@ -27,7 +27,7 @@ const ENTERPRISE_MUTATING = [
27
27
  const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING]);
28
28
  // Readonly seat: inspection only = the registry-safe tools minus READONLY_SAFE_EXCLUDED. Every member is
29
29
  // registry `safe: true`, so no workspace-mutating tool can be in it — widening it means marking a tool safe
30
- // in the registry, which test/permissions-parity.test.mts holds to account.
30
+ // in the registry, which a dedicated permissions test holds to account.
31
31
  const READONLY_ALLOW = new Set(SAFE_TOOLS.filter((n) => !READONLY_SAFE_EXCLUDED.includes(n)));
32
32
  export const TIERS = ["admin", "enterprise", "readonly"];
33
33
  export function isTier(v) {