@0perator/operator 0.1.235 → 0.1.262

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 (68) hide show
  1. package/README.md +2 -1
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +290 -62
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/prompt.js +41 -0
  6. package/dist/acp/run.js +40 -15
  7. package/dist/acp/tool-map.js +48 -0
  8. package/dist/auth/byo.js +15 -8
  9. package/dist/auth/client.js +12 -6
  10. package/dist/auth/commands.js +39 -4
  11. package/dist/auth/identity.js +136 -0
  12. package/dist/auth/store.js +7 -5
  13. package/dist/autonomy/board.js +3 -2
  14. package/dist/autonomy/cron.js +332 -0
  15. package/dist/autonomy/delegate.js +168 -0
  16. package/dist/autonomy/media-robot.js +2 -3
  17. package/dist/autonomy/routines.js +5 -4
  18. package/dist/autonomy/session-factory.js +6 -1
  19. package/dist/browser/cdp.js +266 -0
  20. package/dist/browser/session.js +286 -0
  21. package/dist/cli.js +75 -11
  22. package/dist/config/brand.js +3 -3
  23. package/dist/config/home.js +70 -0
  24. package/dist/config/managed.js +230 -0
  25. package/dist/config/persona.js +59 -9
  26. package/dist/config/scaffold.js +142 -0
  27. package/dist/config/settings.js +38 -4
  28. package/dist/config/skills-index.js +175 -0
  29. package/dist/consolidation/scheduler.js +3 -3
  30. package/dist/consolidation/sleep.js +3 -3
  31. package/dist/engine/agent.js +104 -17
  32. package/dist/engine/aurora.js +6 -0
  33. package/dist/engine/batch-scheduler.js +128 -0
  34. package/dist/engine/json-repair.js +105 -0
  35. package/dist/engine/messages.js +50 -3
  36. package/dist/engine/rolling-summary.js +7 -5
  37. package/dist/enterprise/cli.js +137 -0
  38. package/dist/flywheel/processor.js +30 -2
  39. package/dist/flywheel/secret-gate.js +123 -0
  40. package/dist/mcp/index.js +18 -24
  41. package/dist/memory/index.js +0 -0
  42. package/dist/memory/session-index.js +324 -0
  43. package/dist/memory/session-rewind.js +92 -0
  44. package/dist/memory/state-maintenance.js +441 -0
  45. package/dist/observability/index.js +3 -3
  46. package/dist/permissions/index.js +24 -12
  47. package/dist/router/models.js +27 -8
  48. package/dist/selfimprove/index.js +9 -7
  49. package/dist/session.js +16 -6
  50. package/dist/skills/catalogue.js +167 -0
  51. package/dist/telemetry/audit-verify.js +94 -0
  52. package/dist/telemetry/events.js +86 -6
  53. package/dist/telemetry/lifecycle.js +18 -0
  54. package/dist/tools/deferred.js +117 -0
  55. package/dist/tools/executor.js +19 -20
  56. package/dist/tools/memory.js +117 -0
  57. package/dist/tools/registry.js +152 -21
  58. package/dist/tools/sandbox.js +63 -17
  59. package/dist/tools/searxng.js +2 -2
  60. package/dist/tools/tool-output-spill.js +2 -2
  61. package/dist/ui/Transcript.js +14 -2
  62. package/dist/ui/useInputHistory.js +3 -3
  63. package/dist/vault/cli.js +48 -0
  64. package/dist/vault/store.js +157 -0
  65. package/dist/vault/tool.js +50 -0
  66. package/package.json +3 -5
  67. package/CHANGELOG.md +0 -2487
  68. package/dist/ui/BusTray.js +0 -70
package/dist/cli.js CHANGED
@@ -18,12 +18,17 @@ import { cacheBustNotice } from "./engine/aurora.js";
18
18
  import { seedCalibration } from "./engine/calibration-seed.js";
19
19
  import { AuroraRouter } from "./router/router.js";
20
20
  import { BackgroundAgents } from "./background/index.js";
21
- import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart } from "./config/settings.js";
21
+ import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat } from "./config/settings.js";
22
+ import { resolveSeat } from "./auth/identity.js";
23
+ import { PermissionPolicy } from "./permissions/index.js";
22
24
  import { caps } from "./ui/capabilities.js";
23
25
  import { composeSystemPrompt, appendMemory } from "./config/persona.js";
26
+ import { applyToolsBinPath, operatorPath } from "./config/home.js";
27
+ import { ensureOperatorHome } from "./config/scaffold.js";
24
28
  import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
25
29
  import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
26
- import { EventSink } from "./telemetry/events.js";
30
+ import { disposeBrowserNow } from "./browser/session.js";
31
+ import { EventSink, defaultEventsFile } from "./telemetry/events.js";
27
32
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
28
33
  import { expandFileMentions } from "./util/mentions.js";
29
34
  import { throttle } from "./util/throttle.js";
@@ -47,8 +52,27 @@ const VERSION = (() => {
47
52
  })();
48
53
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
49
54
  const settings = loadSettings();
55
+ // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
56
+ // root, ignore-everything .gitignore, README, settings.example.json, home.json). Idempotent, never throws.
57
+ const HOME_SCAFFOLD = ensureOperatorHome({ version: VERSION });
50
58
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
51
59
  process.env.KODE_SANDBOX = settings.sandbox.mode;
60
+ // operator-home-v2 phase 5: the managed owner-CLI toolkit is a SINGLE PATH addition
61
+ // ($KODE_HOME/tools/bin, materialized by operator-home/tools/toolkit-verify.sh). Projected once at
62
+ // startup so every child inherits it — persistent bash, exec-file tools, in-process cron sessions.
63
+ applyToolsBinPath();
64
+ // HV3-05a: state hygiene at session start — self-paced by its own heartbeat (skips when a run is
65
+ // <20h old), fire-and-forget so it never blocks boot; a repair (quarantine+reindex) is invisible
66
+ // unless it fails. Dynamic import keeps state-maintenance off the neutral bundle graph entirely.
67
+ void import("./memory/state-maintenance.js").then(async (m) => {
68
+ const last = await m.stateMaintenanceStatus();
69
+ if (last && Date.now() - last.ranAtMs < 20 * 3600_000)
70
+ return;
71
+ const r = await m.maintainState();
72
+ if (!r.ok && r.unresolved.length) {
73
+ process.stderr.write(`state maintenance: ${r.unresolved.length} unresolved issue(s) — see state/maintenance.json\n`);
74
+ }
75
+ }).catch(() => undefined);
52
76
  // web_search reads KODE_AUTOPILOT_URL / KODE_SEARXNG_URL from the env at exec; project them from the
53
77
  // settings layer so a settings.json backend works without the user exporting anything. applyEnv already
54
78
  // folded any real env var into settings.search (env wins), so this never clobbers an explicit export.
@@ -94,13 +118,28 @@ if (settings.services?.stopOnExit?.searxng === false)
94
118
  // it once at boot from the keychain (or KODE_OPERATOR_TOKEN) and hand it to the engine; a local :8097
95
119
  // never receives it (aurora.ts only sends to a non-loopback base), so this is safe on JL1 and costs
96
120
  // nothing there. This is what lets a thin client (a 4 GB MacBook) run Operator against JL1's Aurora.
121
+ let bootCreds = null;
97
122
  try {
98
123
  const { loadCredentials } = await import("./auth/store.js");
99
124
  const { setOperatorToken } = await import("./engine/aurora.js");
100
125
  const creds = await loadCredentials().catch(() => null);
126
+ bootCreds = process.env.KODE_OPERATOR_TOKEN ? { token: process.env.KODE_OPERATOR_TOKEN } : creds;
101
127
  setOperatorToken(process.env.KODE_OPERATOR_TOKEN || creds?.token || undefined);
102
128
  }
103
129
  catch { /* auth is optional — a local engine needs none */ }
130
+ // Seat resolution (enterprise SSO/RBAC readiness): with a managed auth policy deployed, the verified identity
131
+ // decides the widest tier this process may hold (it can only NARROW, never widen). With no managed policy this
132
+ // is a no-op and touches no network. `operator auth …` / --version / --help skip it (they must work signed-out).
133
+ const SKIP_SEAT = process.argv[2] === "auth" || process.argv[2] === "audit" || process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help");
134
+ const SEAT = SKIP_SEAT
135
+ ? { seat: { tier: settings.permissions.tier ?? "admin", source: "local-owner", reasons: ["seat resolution skipped for this command"] }, events: [], dropToken: false }
136
+ : await resolveSeat(settings, { creds: bootCreds });
137
+ setActiveSeat(SEAT.seat);
138
+ Object.assign(settings, applySeat(settings, SEAT.seat));
139
+ if (SEAT.dropToken) {
140
+ const { setOperatorToken } = await import("./engine/aurora.js");
141
+ setOperatorToken(undefined);
142
+ }
104
143
  // Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
105
144
  // registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
106
145
  // action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
@@ -150,7 +189,7 @@ const fgPermissions = { ...settings.permissions, rules: { ...settings.permission
150
189
  // grepped back into the model's own context (self-poisoning → runaway ctx growth), committed by
151
190
  // accident, or listed as project litter. One file per cwd (keyed by a short hash) so --resume stays
152
191
  // scoped to the directory you launched in.
153
- const SESSION_DIR = join(homedir(), ".axe", "operator", "sessions");
192
+ const SESSION_DIR = operatorPath("sessions");
154
193
  const SESSION_FILE = process.env.KODE_SESSION_FILE ??
155
194
  join(SESSION_DIR, `${createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16)}.json`);
156
195
  try {
@@ -168,15 +207,27 @@ const SESSION_ID = createHash("sha1").update(`${process.cwd()}:${Date.now()}`).d
168
207
  // session_handoff tools; the handoff is auto-loaded into the system prompt below so the next session in
169
208
  // this directory resumes from it. Kept under ~/.axe/operator, never in the workspace.
170
209
  const WORKSPACE_HASH = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16);
171
- process.env.KODE_SCRATCH_FILE = join(homedir(), ".axe", "operator", "scratch", `${SESSION_ID}.md`);
172
- process.env.KODE_HANDOFF_FILE = join(homedir(), ".axe", "operator", "handoff", `${WORKSPACE_HASH}.md`);
210
+ process.env.KODE_SCRATCH_FILE = operatorPath("scratch", `${SESSION_ID}.md`);
211
+ process.env.KODE_HANDOFF_FILE = operatorPath("handoff", `${WORKSPACE_HASH}.md`);
173
212
  try {
174
213
  mkdirSync(dirname(process.env.KODE_SCRATCH_FILE), { recursive: true });
175
214
  mkdirSync(dirname(process.env.KODE_HANDOFF_FILE), { recursive: true });
176
215
  }
177
216
  catch { /* best-effort; the tools guard too */ }
178
- const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: "cli" };
217
+ const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: process.argv[2] === "acp" ? "acp" : "cli", sub: settings.seat?.sub };
179
218
  const eventSink = new EventSink();
219
+ // Startup audit — only for a seat that is audited at all (a narrowed tier / audit / gated mode); the inert owner
220
+ // writes nothing. Names the managed policy in force (by content id), the resolved seat and why.
221
+ if (new PermissionPolicy(settings.permissions).audits) {
222
+ const m = settings.managed;
223
+ if (m?.status === "invalid")
224
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "policy_invalid", detail: `${m.path}: ${m.errors.join("; ")}`.slice(0, 400) } });
225
+ else if (m?.status === "ok")
226
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "policy_loaded", detail: `${m.path} id=${m.id}` } });
227
+ for (const ev of SEAT.events)
228
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: ev });
229
+ eventSink.emit({ kind: "control", session: SESSION_ID, actor: EVENT_ACTOR, control: { event: "session_start", detail: `entry=${process.argv[2] ?? "tui"} version=${VERSION} tier=${EVENT_ACTOR.tier} mode=${settings.permissions.mode} sandbox=${settings.sandbox.mode} policy=${m?.id ?? "none"} seat=${settings.seat?.source ?? "local-owner"} home=${HOME_SCAFFOLD.firstRun ? "created" : "existing"}` } });
230
+ }
180
231
  const emitTelemetry = settings.telemetry.enabled !== false;
181
232
  // Build the endpoint router. ONE model now: Aurora at its native 1M context on :8097 — both `operator`
182
233
  // and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
@@ -571,8 +622,8 @@ function Root() {
571
622
  // Backstop the slash-/ESC-quit paths: an ordinary terminal close or `kill` must still tear down any
572
623
  // spawned stdio MCP subprocesses (session.shutdown), or they orphan. exit runs sync; SIGTERM exits after.
573
624
  useEffect(() => {
574
- const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); };
575
- const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); process.exit(0); };
625
+ const onExit = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); disposeBrowserNow(); };
626
+ const onTerm = () => { bgRef.current?.dispose(); session.shutdown(); disposeShellSession(); disposeBrowserNow(); process.exit(0); };
576
627
  process.once("exit", onExit);
577
628
  process.once("SIGTERM", onTerm);
578
629
  return () => { process.off("exit", onExit); process.off("SIGTERM", onTerm); };
@@ -1298,7 +1349,8 @@ function Root() {
1298
1349
  // The human-supervisor view of the frozen event stream: recent tool decisions + control events
1299
1350
  // (tier denials, signature lines, RC) straight from the audit JSONL. Read-only.
1300
1351
  const n = Math.max(1, Math.min(50, Number(arg) || 15));
1301
- const file = (process.env.KODE_EVENTS_FILE || process.env.KODE_AUDIT_FILE || join(homedir(), ".axe", "operator", "events.jsonl"));
1352
+ const rawFile = defaultEventsFile();
1353
+ const file = rawFile.startsWith("~/") ? join(homedir(), rawFile.slice(2)) : rawFile;
1302
1354
  let lines = [];
1303
1355
  try {
1304
1356
  lines = readFileSync(file, "utf8").trim().split("\n").filter(Boolean);
@@ -1386,7 +1438,7 @@ function Root() {
1386
1438
  const server = join(dirname(fileURLToPath(import.meta.url)), "..", "dashboard", "server.mjs");
1387
1439
  const child = spawn(process.execPath, [server], { detached: true, stdio: "ignore", env: { ...process.env, PORT: String(port) } });
1388
1440
  child.unref();
1389
- sys(`launched the swarm console → ${url} — live-tailing ~/.axe/operator/events.jsonl (every Operator session, zero config). Open it in a browser.`);
1441
+ sys(`launched the swarm console → ${url} — live-tailing ${defaultEventsFile()} (every Operator session, zero config). Open it in a browser.`);
1390
1442
  }
1391
1443
  catch (e) {
1392
1444
  sys(`could not launch the dashboard: ${e.message}`);
@@ -1611,7 +1663,19 @@ if (process.argv.includes("--help")) {
1611
1663
  }
1612
1664
  if (process.argv[2] === "auth") {
1613
1665
  const { runAuth } = await import("./auth/commands.js");
1614
- process.exit(await runAuth(process.argv.slice(3)));
1666
+ process.exit(await runAuth(process.argv.slice(3), settings));
1667
+ }
1668
+ // `operator audit verify|tail` and `operator doctor` — the enterprise review surface: prove the audit trail is
1669
+ // intact, and show exactly what policy/seat/home posture is in force. Plain console, no TTY needed.
1670
+ if (process.argv[2] === "audit" || process.argv[2] === "doctor") {
1671
+ const { runEnterpriseCli } = await import("./enterprise/cli.js");
1672
+ process.exit(await runEnterpriseCli(process.argv.slice(2), settings, { version: VERSION, scaffold: HOME_SCAFFOLD }));
1673
+ }
1674
+ // `operator vault ...` — owner-side credential store for the browser (HV3-02b). The secret path
1675
+ // never crosses argv or model context: keychain prompt on macOS, stdin fallback elsewhere.
1676
+ if (process.argv[2] === "vault") {
1677
+ const { runVault } = await import("./vault/cli.js");
1678
+ process.exit(await runVault(process.argv.slice(3)));
1615
1679
  }
1616
1680
  // `operator update` (bareword) and `operator --update` both self-update.
1617
1681
  if (process.argv[2] === "update" || process.argv.includes("--update")) {
@@ -9,8 +9,8 @@
9
9
  // is deliberately IGNORED here. Only brand_name / gate_title / domain / logo are adopted. Best-effort,
10
10
  // never throws.
11
11
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
12
- import { homedir } from "node:os";
13
- import { join, dirname } from "node:path";
12
+ import { dirname } from "node:path";
13
+ import { operatorPath } from "./home.js";
14
14
  // CLI defaults — used offline and on first run. brand_color is the CLI's violet accent, NOT the tenant teal.
15
15
  export const BRAND_DEFAULT = {
16
16
  brand_name: "Operator",
@@ -22,7 +22,7 @@ export const BRAND_DEFAULT = {
22
22
  const BRAND_URL = process.env.AXE_BRAND_URL ?? "https://authgate.cloud/api/apps/operator/brand";
23
23
  const CACHE_TTL_MS = 60 * 60 * 1000; // 1h — brand rarely changes; keeps launch-time refreshes rare
24
24
  const FETCH_TIMEOUT_MS = 4000;
25
- function cachePath() { return join(homedir(), ".axe", "operator", "brand-cache.json"); }
25
+ function cachePath() { return operatorPath("brand-cache.json"); }
26
26
  function readCache() {
27
27
  try {
28
28
  return JSON.parse(readFileSync(cachePath(), "utf8"));
@@ -0,0 +1,70 @@
1
+ // Browser-safe home resolution: NO static `node:` imports — this module is reachable from the engine
2
+ // bundle (src/engine/rolling-summary.ts), and index.browser.ts must stay node-free (the esbuild
3
+ // --platform=neutral purity gate fails on any node builtin leak). Uses process.getBuiltinModule at
4
+ // call time, with env-only / relative fallbacks when node builtins are unavailable (JSCore/browser).
5
+ function builtins() {
6
+ try {
7
+ const proc = globalThis.process;
8
+ const os = proc?.getBuiltinModule?.("node:os");
9
+ const path = proc?.getBuiltinModule?.("node:path");
10
+ if (!os || !path)
11
+ return null;
12
+ return { os, path };
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ /**
19
+ * Resolve the operator home directory. Precedence:
20
+ * 1. `$KODE_HOME` when set — explicit override, wins over everything;
21
+ * 2. `$KODE_PROFILE` when set AND a valid profile name ([A-Za-z0-9_-]{1,64}) —
22
+ * resolves to `<defaultHome>/profiles/<name>` (an invalid name is IGNORED, not an error);
23
+ * 3. the default home `~/.axe/operator`.
24
+ */
25
+ export function get_operator_home() {
26
+ const env = globalThis.process?.env;
27
+ if (env?.KODE_HOME)
28
+ return env.KODE_HOME;
29
+ const b = builtins();
30
+ const defaultHome = b ? b.path.join(b.os.homedir(), ".axe", "operator") : ".axe/operator"; // node-less fallback: best-effort relative path
31
+ const profile = env?.KODE_PROFILE;
32
+ if (profile && /^[A-Za-z0-9_-]{1,64}$/.test(profile)) {
33
+ return b ? b.path.join(defaultHome, "profiles", profile) : `${defaultHome}/profiles/${profile}`;
34
+ }
35
+ return defaultHome;
36
+ }
37
+ /** Join one or more path segments under the operator home. */
38
+ export function operatorPath(...parts) {
39
+ const home = get_operator_home();
40
+ const b = builtins();
41
+ return b ? b.path.join(home, ...parts) : [home, ...parts].join("/");
42
+ }
43
+ /** The managed owner-CLI toolkit's single PATH addition (operator-home-v2 phase 5): every tool
44
+ * toolkit-verify.sh materializes lands here as a symlink. */
45
+ export function toolsBinPath() {
46
+ return operatorPath("tools", "bin");
47
+ }
48
+ /** Prepend `bin` to a PATH-style string. Delimiter-aware, idempotent (no-op when already present),
49
+ * and never emits an empty segment. Exported pure for tests. */
50
+ export function prependPath(pathValue, bin, sep) {
51
+ if (!pathValue)
52
+ return bin;
53
+ const parts = pathValue.split(sep);
54
+ return parts.includes(bin) ? pathValue : [bin, ...parts].join(sep);
55
+ }
56
+ /** Project `$KODE_HOME/tools/bin` onto the front of this process's PATH, once and idempotently
57
+ * (operator-home-v2 phase 5). Called at CLI startup so EVERY child — the persistent bash, the
58
+ * exec-file tools, and in-process cron/headless sessions — inherits the toolkit without touching
59
+ * anything else. Windows convention (`Path` key) is honored when `PATH` is absent. Browser/JSCore
60
+ * contexts have no process.env here: silent no-op, engine purity unaffected. */
61
+ export function applyToolsBinPath(env) {
62
+ const proc = globalThis.process;
63
+ const target = env ?? proc?.env;
64
+ if (!target)
65
+ return;
66
+ const sep = builtins()?.path.delimiter ?? (proc?.platform === "win32" ? ";" : ":");
67
+ const bin = toolsBinPath();
68
+ const key = target.PATH !== undefined || target.Path === undefined ? "PATH" : "Path";
69
+ target[key] = prependPath(target[key], bin, sep);
70
+ }
@@ -0,0 +1,230 @@
1
+ // Managed policy — the org-deployed, user-proof layer of the settings stack. Until now every control an
2
+ // enterprise cares about (tier, permission mode, sandbox, computer control, the training flywheel) lived in
3
+ // the user's own ~/.axe/operator/settings.json or an env var, i.e. a seat could un-narrow itself by deleting a
4
+ // line. A managed policy is a root-owned file outside the user's home that is applied LAST — over defaults,
5
+ // user settings and env — so it can only be changed by whoever can write /etc or /Library.
6
+ //
7
+ // macOS /Library/Application Support/Operator/managed-settings.json
8
+ // Linux /etc/operator/managed-settings.json
9
+ // Windows %ProgramData%\Operator\managed-settings.json
10
+ // dev/test $KODE_MANAGED_SETTINGS — honoured ONLY when no system file exists, so setting the variable can
11
+ // never switch a deployed policy off.
12
+ //
13
+ // Fail CLOSED: a policy that exists but cannot be trusted (unparseable, wrong types, group/world-writable,
14
+ // not root-owned) does not silently fall back to "no policy" — the seat runs read-only/gated until it is
15
+ // fixed, loudly. Absent file = no managed policy = nothing changes (the owner's local experience).
16
+ import { createHash } from "node:crypto";
17
+ import { existsSync, readFileSync, statSync } from "node:fs";
18
+ const TIER_NAMES = ["admin", "enterprise", "readonly"];
19
+ const MODE_NAMES = ["bypass", "audit", "gated"];
20
+ const RULE_NAMES = ["allow", "ask", "deny"];
21
+ const SANDBOX_NAMES = ["off", "workspace", "strict"];
22
+ export const LOCKDOWN = {
23
+ permissions: { mode: "gated", tier: "readonly" },
24
+ sandbox: { mode: "workspace" },
25
+ computer: { enabled: false },
26
+ mcp: false,
27
+ selfImprove: { flywheel: false },
28
+ };
29
+ export function systemManagedPaths(plat = process.platform, env = process.env) {
30
+ if (plat === "darwin")
31
+ return ["/Library/Application Support/Operator/managed-settings.json"];
32
+ if (plat === "win32")
33
+ return [`${env.ProgramData ?? "C:\\ProgramData"}\\Operator\\managed-settings.json`];
34
+ return ["/etc/operator/managed-settings.json"];
35
+ }
36
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
37
+ const isPosNum = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
38
+ function validateAuth(raw, errors) {
39
+ if (raw === undefined)
40
+ return undefined;
41
+ if (!isObj(raw)) {
42
+ errors.push("auth must be an object");
43
+ return undefined;
44
+ }
45
+ const out = {};
46
+ if (raw.requireSignIn !== undefined) {
47
+ if (typeof raw.requireSignIn === "boolean")
48
+ out.requireSignIn = raw.requireSignIn;
49
+ else
50
+ errors.push("auth.requireSignIn must be a boolean");
51
+ }
52
+ if (raw.maxTokenAgeHours !== undefined) {
53
+ if (isPosNum(raw.maxTokenAgeHours))
54
+ out.maxTokenAgeHours = raw.maxTokenAgeHours;
55
+ else
56
+ errors.push("auth.maxTokenAgeHours must be a positive number");
57
+ }
58
+ if (raw.offlineGraceHours !== undefined) {
59
+ if (isPosNum(raw.offlineGraceHours))
60
+ out.offlineGraceHours = raw.offlineGraceHours;
61
+ else
62
+ errors.push("auth.offlineGraceHours must be a positive number");
63
+ }
64
+ if (raw.allowedEmailDomains !== undefined) {
65
+ if (Array.isArray(raw.allowedEmailDomains) && raw.allowedEmailDomains.length > 0 && raw.allowedEmailDomains.every((d) => typeof d === "string" && d.length > 0)) {
66
+ out.allowedEmailDomains = raw.allowedEmailDomains.map((d) => d.toLowerCase().replace(/^@/, ""));
67
+ }
68
+ else
69
+ errors.push("auth.allowedEmailDomains must be a non-empty array of strings");
70
+ }
71
+ if (raw.roleTiers !== undefined) {
72
+ if (isObj(raw.roleTiers) && Object.values(raw.roleTiers).every((t) => typeof t === "string" && TIER_NAMES.includes(t)))
73
+ out.roleTiers = raw.roleTiers;
74
+ else
75
+ errors.push("auth.roleTiers must map role names to admin|enterprise|readonly");
76
+ }
77
+ if (raw.defaultTier !== undefined) {
78
+ if (typeof raw.defaultTier === "string" && TIER_NAMES.includes(raw.defaultTier))
79
+ out.defaultTier = raw.defaultTier;
80
+ else
81
+ errors.push("auth.defaultTier must be admin|enterprise|readonly");
82
+ }
83
+ return out;
84
+ }
85
+ /** Strict validation: every present key must have the right type/value, or it is an error (=> lockdown). Unknown
86
+ * top-level keys are reported but ignored — a newer policy file must not brick an older engine. */
87
+ export function validateManagedPolicy(raw) {
88
+ const errors = [];
89
+ const policy = {};
90
+ if (!isObj(raw))
91
+ return { policy, errors: ["policy must be a JSON object"], unknown: [] };
92
+ const known = new Set(["permissions", "sandbox", "computer", "mcp", "selfImprove", "unrestricted", "auth", "$schema", "_comment"]);
93
+ const unknown = Object.keys(raw).filter((k) => !known.has(k));
94
+ if (raw.permissions !== undefined) {
95
+ if (!isObj(raw.permissions))
96
+ errors.push("permissions must be an object");
97
+ else {
98
+ const p = {};
99
+ const { mode, tier, rules } = raw.permissions;
100
+ if (mode !== undefined) {
101
+ if (typeof mode === "string" && MODE_NAMES.includes(mode))
102
+ p.mode = mode;
103
+ else
104
+ errors.push("permissions.mode must be bypass|audit|gated");
105
+ }
106
+ if (tier !== undefined) {
107
+ if (typeof tier === "string" && TIER_NAMES.includes(tier))
108
+ p.tier = tier;
109
+ else
110
+ errors.push("permissions.tier must be admin|enterprise|readonly");
111
+ }
112
+ if (rules !== undefined) {
113
+ if (isObj(rules) && Object.values(rules).every((r) => typeof r === "string" && RULE_NAMES.includes(r)))
114
+ p.rules = rules;
115
+ else
116
+ errors.push("permissions.rules must map tool names to allow|ask|deny");
117
+ }
118
+ policy.permissions = p;
119
+ }
120
+ }
121
+ if (raw.sandbox !== undefined) {
122
+ if (isObj(raw.sandbox) && typeof raw.sandbox.mode === "string" && SANDBOX_NAMES.includes(raw.sandbox.mode))
123
+ policy.sandbox = { mode: raw.sandbox.mode };
124
+ else
125
+ errors.push("sandbox.mode must be off|workspace|strict");
126
+ }
127
+ if (raw.computer !== undefined) {
128
+ if (isObj(raw.computer) && raw.computer.enabled === false)
129
+ policy.computer = { enabled: false };
130
+ else
131
+ errors.push("computer.enabled may only be set to false (a policy can disable computer control, never grant it)");
132
+ }
133
+ if (raw.mcp !== undefined) {
134
+ if (typeof raw.mcp === "boolean")
135
+ policy.mcp = raw.mcp;
136
+ else
137
+ errors.push("mcp must be a boolean");
138
+ }
139
+ if (raw.selfImprove !== undefined) {
140
+ if (isObj(raw.selfImprove) && typeof raw.selfImprove.flywheel === "boolean")
141
+ policy.selfImprove = { flywheel: raw.selfImprove.flywheel };
142
+ else
143
+ errors.push("selfImprove.flywheel must be a boolean");
144
+ }
145
+ if (raw.unrestricted !== undefined) {
146
+ if (typeof raw.unrestricted === "boolean")
147
+ policy.unrestricted = raw.unrestricted;
148
+ else
149
+ errors.push("unrestricted must be a boolean");
150
+ }
151
+ const auth = validateAuth(raw.auth, errors);
152
+ if (auth)
153
+ policy.auth = auth;
154
+ return { policy, errors, unknown };
155
+ }
156
+ function trustProblem(path, system) {
157
+ if (process.platform === "win32")
158
+ return null; // ACLs are not representable in a mode word
159
+ const st = statSync(path);
160
+ if (!st.isFile())
161
+ return "not a regular file";
162
+ if ((st.mode & 0o022) !== 0)
163
+ return `writable by group/other (mode ${(st.mode & 0o777).toString(8)})`;
164
+ if (system && st.uid !== 0)
165
+ return `not owned by root (uid ${st.uid}) — the user it belongs to could edit their own policy`;
166
+ return null;
167
+ }
168
+ export function loadManagedPolicy(opts = {}) {
169
+ const systemPaths = opts.systemPaths ?? systemManagedPaths();
170
+ const envPath = "envPath" in opts ? opts.envPath : process.env.KODE_MANAGED_SETTINGS;
171
+ const sys = systemPaths.find((p) => existsSync(p));
172
+ const path = sys ?? (envPath && existsSync(envPath) ? envPath : undefined);
173
+ if (!path)
174
+ return { info: { status: "none", errors: [] } };
175
+ const system = sys !== undefined;
176
+ const bad = (errors) => ({ info: { status: "invalid", path, errors }, policy: LOCKDOWN });
177
+ let raw;
178
+ try {
179
+ const problem = trustProblem(path, system);
180
+ if (problem)
181
+ return bad([`untrusted policy file: ${problem}`]);
182
+ raw = readFileSync(path, "utf8");
183
+ }
184
+ catch (e) {
185
+ return bad([`cannot read policy file: ${e instanceof Error ? e.message : String(e)}`]);
186
+ }
187
+ let parsed;
188
+ try {
189
+ parsed = JSON.parse(raw);
190
+ }
191
+ catch (e) {
192
+ return bad([`policy is not valid JSON: ${e instanceof Error ? e.message : String(e)}`]);
193
+ }
194
+ const { policy, errors } = validateManagedPolicy(parsed);
195
+ if (errors.length)
196
+ return bad(errors);
197
+ const id = createHash("sha256").update(raw).digest("hex").slice(0, 12);
198
+ return { info: { status: "ok", path, id, errors: [], auth: policy.auth }, policy };
199
+ }
200
+ /** Overlay a policy on already-resolved settings (defaults <- user file <- env <- THIS). Pure. */
201
+ export function applyManagedPolicy(s, load) {
202
+ const out = { ...s, managed: load.info };
203
+ const p = load.policy;
204
+ if (!p)
205
+ return out;
206
+ if (p.permissions) {
207
+ const perms = { ...s.permissions };
208
+ if (p.permissions.mode)
209
+ perms.mode = p.permissions.mode;
210
+ if (p.permissions.tier)
211
+ perms.tier = p.permissions.tier;
212
+ // Under a managed enforcing mode a user's own `allow` rule must not pre-approve what the org gates —
213
+ // users may still TIGHTEN (ask/deny); the org's own rules win every conflict.
214
+ const enforcing = (p.permissions.mode ?? perms.mode) !== "bypass";
215
+ const userRules = Object.fromEntries(Object.entries(s.permissions.rules ?? {}).filter(([, r]) => !enforcing || r !== "allow"));
216
+ const rules = { ...userRules, ...(p.permissions.rules ?? {}) };
217
+ out.permissions = { ...perms, ...(Object.keys(rules).length ? { rules } : {}) };
218
+ }
219
+ if (p.sandbox)
220
+ out.sandbox = { ...s.sandbox, mode: p.sandbox.mode };
221
+ if (p.computer?.enabled === false)
222
+ out.computer = { ...s.computer, enabled: false };
223
+ if (typeof p.mcp === "boolean")
224
+ out.mcp = p.mcp;
225
+ if (p.selfImprove)
226
+ out.selfImprove = { ...s.selfImprove, flywheel: p.selfImprove.flywheel };
227
+ if (p.unrestricted === false)
228
+ out.unrestricted = false;
229
+ return out;
230
+ }
@@ -3,15 +3,18 @@
3
3
  // picks up the SAME project context + handoff the TUI does, without importing cli.tsx (which mounts
4
4
  // Ink and refuses a non-TTY). Pure, best-effort, never throws — a missing file is normal.
5
5
  import { readFileSync, appendFileSync, mkdirSync } from "node:fs";
6
- import { homedir } from "node:os";
7
6
  import { join, dirname } from "node:path";
7
+ import { operatorPath } from "./home.js";
8
8
  import { renderHarnessContext } from "./operator-harness.js";
9
9
  import { renderToolCatalogue } from "../tools/registry.js";
10
- // Project context: auto-load a per-repo instructions file (AGENTS.md / CLAUDE.md / .operator/AGENTS.md)
11
- // from `cwd` and append it to the system prompt, so Operator picks up house rules, conventions and build
12
- // commands the way modern coding agents do. First match wins; capped so a huge file can't blow the prompt.
10
+ import { renderSkillsIndex } from "./skills-index.js";
11
+ // Project context: auto-load a per-repo instructions file from `cwd` and append it to the system prompt, so
12
+ // Operator picks up house rules, conventions and build commands the way modern coding agents do. First match
13
+ // wins, so the ORDER is the brand precedence: our own `.operator/AGENTS.md`, then the vendor-neutral open
14
+ // standard (`AGENTS.md`, agents.md), then `OPERATOR.md` — Operator-branded and vendor-neutral names only.
15
+ // Capped so a huge file can't blow the prompt.
13
16
  export function loadProjectContext(cwd = process.cwd()) {
14
- for (const name of ["AGENTS.md", "CLAUDE.md", ".operator/AGENTS.md", "OPERATOR.md"]) {
17
+ for (const name of [".operator/AGENTS.md", "AGENTS.md", "OPERATOR.md"]) {
15
18
  try {
16
19
  const t = readFileSync(join(cwd, name), "utf8").trim();
17
20
  if (t)
@@ -28,13 +31,13 @@ export function loadProjectContext(cwd = process.cwd()) {
28
31
  // session. Global lives beside operator/settings.json (~/.axe/operator/memories.md; override with
29
32
  // KODE_MEMORIES_FILE); project is .operator/memories.md, or a repo-root memories.md. Global is emitted
30
33
  // FIRST and project LAST, so a repo-specific note overrides a global one — the same more-specific-wins
31
- // precedence as the settings layer (and as the CLAUDE.md chain in comparable agents). Capped so a huge file
34
+ // precedence as the settings layer. Capped so a huge file
32
35
  // can't blow the prompt — and the file is append-only (newest last), so the cap keeps the TAIL, like
33
36
  // loadHandoff; best-effort, never throws — a missing file is normal.
34
37
  const MEMORIES_CAP = 6000;
35
38
  const memoriesTail = (t) => (t.length > MEMORIES_CAP ? "…\n" + t.slice(-MEMORIES_CAP) : t);
36
39
  export function globalMemoriesPath() {
37
- return process.env.KODE_MEMORIES_FILE ?? join(homedir(), ".axe", "operator", "memories.md");
40
+ return process.env.KODE_MEMORIES_FILE ?? operatorPath("memories.md");
38
41
  }
39
42
  export function projectMemoriesPath(cwd = process.cwd()) {
40
43
  return join(cwd, ".operator", "memories.md");
@@ -85,6 +88,47 @@ export function appendMemory(text, scope = "project", cwd = process.cwd()) {
85
88
  return "";
86
89
  }
87
90
  }
91
+ /** Load `$KODE_HOME/SOUL.md` — the Hermes-style identity file. When present, it REPLACES basePersona as
92
+ * the identity block (settings.systemPrompt still wins as explicit override). Head-kept under a cap:
93
+ * identity leads with what matters most, and an oversized SOUL.md must not be able to blow the prompt
94
+ * budget every session. Best-effort, never throws. */
95
+ const SOUL_MD_CAP = 12000;
96
+ export function loadSoul() {
97
+ try {
98
+ const t = readFileSync(operatorPath("SOUL.md"), "utf8").trim();
99
+ if (!t)
100
+ return null;
101
+ return t.length > SOUL_MD_CAP ? t.slice(0, SOUL_MD_CAP) + "\n…" : t;
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ }
107
+ // Structured memories (Hermes parity): `memories/MEMORY.md` (agent notes, hard char budget 2200) and
108
+ // `memories/USER.md` (user profile, budget 1375). These are injected BEFORE the legacy flat memories.md
109
+ // so both layers co-exist during migration. Tail-kept (newest survives the cap, oldest trimmed). Files
110
+ // are edited by the `memory` tool (batch add/replace/remove with budget enforcement), not appended.
111
+ const MEMORY_MD_BUDGET = 2200;
112
+ const USER_MD_BUDGET = 1375;
113
+ function budgetTail(t, cap) {
114
+ return t.length > cap ? "…\n" + t.slice(-cap) : t;
115
+ }
116
+ export function loadStructuredMemories() {
117
+ let out = "";
118
+ try {
119
+ const t = readFileSync(operatorPath("memories", "MEMORY.md"), "utf8").trim();
120
+ if (t)
121
+ out += `\n\n## Agent memory (memories/MEMORY.md)\n${budgetTail(t, MEMORY_MD_BUDGET)}`;
122
+ }
123
+ catch { /* not yet */ }
124
+ try {
125
+ const t = readFileSync(operatorPath("memories", "USER.md"), "utf8").trim();
126
+ if (t)
127
+ out += `\n\n## User profile (memories/USER.md)\n${budgetTail(t, USER_MD_BUDGET)}`;
128
+ }
129
+ catch { /* not yet */ }
130
+ return out;
131
+ }
88
132
  // Session handoff: the note the previous session in THIS directory wrote for its future self (via the
89
133
  // session_handoff tool), pointed at by KODE_HANDOFF_FILE. Auto-loaded so the agent resumes seamlessly.
90
134
  export function loadHandoff() {
@@ -336,11 +380,17 @@ export function composeSystemPrompt(o) {
336
380
  const cwd = o.cwd ?? process.cwd();
337
381
  const lean = o.lean === true;
338
382
  const interactive = o.interactive === true;
339
- return ((o.settings.systemPrompt ?? basePersona(cwd, { ctxTokens: o.ctxTokens, interactive })) +
383
+ const identity = o.settings.systemPrompt ?? loadSoul() ?? basePersona(cwd, { ctxTokens: o.ctxTokens, interactive });
384
+ // Local-skills index (name: trigger, 4k cap) — the model must KNOW skills exist without spending a
385
+ // skill_list call; bodies stay pull-on-demand via skill_fetch. Skipped in lean (small-ctx) mode like
386
+ // the other heavy sections. Appended exactly like renderToolCatalogue, right before it.
387
+ const skillsIdx = lean ? "" : renderSkillsIndex();
388
+ return (identity +
340
389
  loadProjectContext(cwd) +
341
- (lean ? "" : loadMemories(cwd)) +
390
+ (lean ? "" : loadStructuredMemories() + loadMemories(cwd)) +
342
391
  renderHarnessContext(cwd) +
343
392
  (lean ? LEAN_NOTE : loadHandoff()) +
393
+ (skillsIdx ? `\n\n## Skills installed locally (skill_fetch <name> loads one; skill_fetch <name> <file_path> reads its references/templates/scripts)\n${skillsIdx}` : "") +
344
394
  renderToolCatalogue(undefined, { lean }) +
345
395
  (interactive ? renderEmbodimentGuide(!!o.settings.computer?.enabled, o.chauffeurReady ?? !!o.settings.mcp) : ""));
346
396
  }