@0perator/operator 0.2.0 → 0.2.2-next.0

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 (117) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +15 -5
  4. package/dist/auth/identity.js +1 -0
  5. package/dist/auth/staff.js +55 -0
  6. package/dist/autonomy/agent-cli.js +1 -1
  7. package/dist/autonomy/delegate-mode.js +2 -2
  8. package/dist/autonomy/delegate.js +41 -14
  9. package/dist/autonomy/headless.js +37 -10
  10. package/dist/autonomy/index.js +2 -4
  11. package/dist/autonomy/pr-isolation.js +92 -0
  12. package/dist/autonomy/pr-preflight.js +474 -0
  13. package/dist/autonomy/session-factory.js +13 -12
  14. package/dist/autonomy/subagent-model.js +17 -7
  15. package/dist/background/capacity.js +136 -0
  16. package/dist/background/evidence.js +42 -0
  17. package/dist/background/index.js +311 -44
  18. package/dist/background/lane-phase.js +60 -0
  19. package/dist/background/lane-summary.js +151 -0
  20. package/dist/background/notices.js +12 -3
  21. package/dist/background/synthesis.js +25 -0
  22. package/dist/browser/capture.js +505 -0
  23. package/dist/browser/engine.js +4 -3
  24. package/dist/browser/page-capture.js +167 -0
  25. package/dist/browser/png.js +116 -0
  26. package/dist/browser/visual-compare.js +229 -0
  27. package/dist/bus/beam-drop.js +55 -0
  28. package/dist/bus/inbox.js +157 -7
  29. package/dist/cli.js +316 -120
  30. package/dist/config/features.js +3 -3
  31. package/dist/config/managed.js +40 -1
  32. package/dist/config/persona.js +80 -29
  33. package/dist/config/product-hosts.js +2 -0
  34. package/dist/config/settings.js +289 -31
  35. package/dist/config/skills-index.js +37 -14
  36. package/dist/config/staff-prompt.js +12 -0
  37. package/dist/engine/agent.js +52 -41
  38. package/dist/engine/aurora.js +54 -13
  39. package/dist/engine/batch-scheduler.js +4 -13
  40. package/dist/engine/compaction.js +1 -1
  41. package/dist/engine/continuation.js +66 -32
  42. package/dist/engine/decision-points.js +2 -3
  43. package/dist/engine/fanout.js +16 -0
  44. package/dist/engine/identity.js +42 -0
  45. package/dist/engine/loop-guard.js +26 -83
  46. package/dist/engine/messages.js +2 -2
  47. package/dist/engine/moa.js +23 -1
  48. package/dist/engine/native-vision-node.js +72 -0
  49. package/dist/engine/native-vision.js +103 -0
  50. package/dist/engine/net-error.js +15 -0
  51. package/dist/engine/rolling-summary.js +142 -93
  52. package/dist/engine/verify-gate.js +37 -7
  53. package/dist/engine/waterfall.js +33 -0
  54. package/dist/gateway-cli.js +24 -4
  55. package/dist/memory/live-progress.js +4 -5
  56. package/dist/memory/session-index.js +3 -3
  57. package/dist/moa/codeact-lane.js +98 -0
  58. package/dist/moa/codeact-sandbox.js +409 -0
  59. package/dist/moa/codeact.js +140 -0
  60. package/dist/permissions/artifact-visibility.js +10 -0
  61. package/dist/permissions/index.js +2 -1
  62. package/dist/permissions/policy.js +9 -2
  63. package/dist/permissions/tier.js +13 -3
  64. package/dist/products/craft.js +92 -3
  65. package/dist/products/temple.js +20 -1
  66. package/dist/products/voice.js +112 -0
  67. package/dist/remote/grants.js +119 -0
  68. package/dist/remote/host.js +33 -5
  69. package/dist/router/free-models.js +5 -9
  70. package/dist/router/models.js +80 -26
  71. package/dist/router/provider-models.js +78 -0
  72. package/dist/router/router.js +15 -3
  73. package/dist/selfimprove/index.js +8 -6
  74. package/dist/selfimprove/lessons.js +23 -0
  75. package/dist/services/preflight.js +35 -91
  76. package/dist/session.js +316 -125
  77. package/dist/skills/catalogue.js +5 -2
  78. package/dist/skills/finder.js +4 -4
  79. package/dist/skills/install-guard.js +68 -0
  80. package/dist/skills/install.js +67 -0
  81. package/dist/toolchain/manifest.json +13 -13
  82. package/dist/tools/background-result.js +1 -1
  83. package/dist/tools/beam.js +246 -0
  84. package/dist/tools/classes.js +103 -0
  85. package/dist/tools/contract.js +1 -1
  86. package/dist/tools/craft.js +36 -2
  87. package/dist/tools/deferred.js +7 -3
  88. package/dist/tools/doc-text.js +1 -1
  89. package/dist/tools/executor.js +25 -15
  90. package/dist/tools/generation-gateway.js +94 -0
  91. package/dist/tools/registry.js +135 -158
  92. package/dist/tools/sandbox.js +6 -6
  93. package/dist/ui/App.js +17 -6
  94. package/dist/ui/ApprovalPrompt.js +1 -1
  95. package/dist/ui/BgPanel.js +15 -10
  96. package/dist/ui/Composer.js +44 -2
  97. package/dist/ui/Header.js +1 -6
  98. package/dist/ui/StatusRule.js +20 -8
  99. package/dist/ui/ToolStep.js +3 -3
  100. package/dist/ui/Transcript.js +41 -14
  101. package/dist/ui/batchLine.js +4 -4
  102. package/dist/ui/editdiff.js +2 -4
  103. package/dist/ui/format.js +4 -20
  104. package/dist/ui/liveTools.js +3 -3
  105. package/dist/ui/modelPicker.js +10 -6
  106. package/dist/ui/opsMode.js +20 -0
  107. package/dist/ui/phase.js +4 -2
  108. package/dist/ui/slashCommands.js +1 -0
  109. package/dist/ui/types.js +0 -2
  110. package/dist/ui/voice.js +185 -0
  111. package/dist/update-check.js +17 -6
  112. package/dist/update.js +1 -2
  113. package/dist/util/audio-io.js +82 -0
  114. package/dist/util/slash.js +2 -2
  115. package/dist/vision/pairs.js +239 -0
  116. package/package.json +1 -1
  117. package/dist/tools/mutating.js +0 -15
@@ -1,12 +1,14 @@
1
1
  // operator/settings.json — a user configuration layer (backlog #49), same shape as a typical coding
2
2
  // agent's settings.json. Loaded once at startup by cli.tsx. Precedence: env var > settings.json > built-in
3
- // default. Never throws — a missing or malformed file just falls back to defaults, same as an env
4
- // var that was never set.
5
- import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
3
+ // default. loadSettings never throws: a missing file means defaults; a broken one means the last good copy
4
+ // (settings.json.last-good) or defaults, with a warning from settingsLoadProblems(). saveSettings is atomic,
5
+ // locked, and throws when it cannot save.
6
+ import { readFileSync, mkdirSync, openSync, writeSync, fsyncSync, closeSync, fchmodSync, renameSync, unlinkSync, statSync, realpathSync } from "node:fs";
7
+ import { randomBytes } from "node:crypto";
6
8
  import { dirname } from "node:path";
7
9
  import { operatorPath } from "./home.js";
8
10
  import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
9
- import { MIN_CONTEXT_PIN, DEFAULT_ACTIVE_MODEL, GATEWAY_BASE, LOCAL_GATEWAY_BASE } from "../router/models.js";
11
+ import { MIN_CONTEXT_PIN, DEFAULT_ACTIVE_MODEL, GATEWAY_BASE, LOCAL_GATEWAY_BASE, gatewayModelFor, isRetiredAuroraBase } from "../router/models.js";
10
12
  import { LEGACY_API_HOST, PRODUCT_API_HOST } from "./product-hosts.js";
11
13
  /** Resolve an endpoint's bearer from config/env/secret-file (first hit wins); undefined when none set
12
14
  * (a local/un-gated endpoint). Keeps the raw key out of settings when `apiKeyEnv`/`apiKeyFile` are used. */
@@ -40,7 +42,7 @@ const DEFAULTS = {
40
42
  // Fallback literal for hosts without a running operator-runtime gateway (mobile, browser, dev).
41
43
  // Fleet nodes with ~/.operator/runtime/server.json dynamically override this at startup via the
42
44
  // gateway-discovery path in cli.tsx — single source of truth, enterprise-safe for both postures.
43
- aurora: { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" }, // == DEFAULT_AURORA_ENDPOINT: buildEndpointChain puts the router's `main` before it
45
+ aurora: { base: LOCAL_GATEWAY_BASE.replace(/\/v1\/?$/, ""), ctxWindow: 262144, model: "main" }, // == DEFAULT_AURORA_ENDPOINT: the local router's `main`
44
46
  // No built-in standby: a deployment names its own in settings.json (endpoints.failover — same model and the
45
47
  // same real window as the primary, so a failover holds a live session instead of truncating it).
46
48
  },
@@ -73,12 +75,13 @@ const DEFAULTS = {
73
75
  vision: { autostart: false, launchdLabel: "co.0perator.vision", plistPath: "~/Library/LaunchAgents/co.0perator.vision.plist", legacyLabels: ["axe.vision-bot"], url: "http://127.0.0.1:7788" },
74
76
  stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
75
77
  },
76
- // MOA (2026-10-31, James): a planner/specialist team — Cortana plans, delegates each step to a
77
- // gpt-oss-20b sub-agent, checks the result and writes the answer (and reads images). Both on JL1 through the gateway.
78
- // Was parallel drafts (gpt-oss-20b + Cortana) merged by Cortana (10/30). settings.moa replaces it wholesale.
78
+ // MOA (2026-11-30, James): the cloud planner holds the planner + composer seat (plans, checks, writes the answer)
79
+ // through the gateway's planner-cloud route; the specialist is the gateway's operator-flash route = the JL1 worker,
80
+ // then the JL2 worker (no cloud leg). Sub-agents use the gateway's subagent pool (JL2 first, then JL1). The previous
81
+ // team's two routes were retired from the gateway 2026-11-30. settings.moa replaces it wholesale.
79
82
  moa: {
80
- planner: { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
81
- specialist: { id: "gpt-oss-20b" },
83
+ planner: { id: "planner-cloud", endpoint: GATEWAY_BASE, model: "planner-cloud" },
84
+ specialist: { id: "operator-flash" },
82
85
  },
83
86
  activeModel: DEFAULT_ACTIVE_MODEL, // /model default for a fresh install: the router's operator-flash route (0.1.361; was the Aurora row)
84
87
  // Autonomy: everything conservative. keepAwake off; dream OFF and read-mostly with a board-only
@@ -114,14 +117,143 @@ function deepMerge(base, override) {
114
117
  }
115
118
  return out;
116
119
  }
117
- /** Parsed settings file, or undefined on any read/parse failure — malformed JSON is not an error here. */
120
+ function shapeOf(v) {
121
+ return v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
122
+ }
123
+ /** Enumerated settings where a wrong value silently changes what the agent may do. */
124
+ const ENUMS = {
125
+ "permissions.mode": ["bypass", "audit", "gated"],
126
+ "sandbox.mode": ["off", "workspace", "strict"],
127
+ };
128
+ /** The file's values, minus any whose shape differs from the default's (a string where the default is an object,
129
+ * …) or that is not one of an ENUMS value. Each drop is reported in `problems`. Keys with no default pass through
130
+ * unchanged, so a newer build's settings keep working on an older one. */
131
+ function dropMistyped(base, file, problems, at = "") {
132
+ const out = {};
133
+ for (const [k, v] of Object.entries(file)) {
134
+ const key = at ? `${at}.${k}` : k;
135
+ const def = isPlainObject(base) ? base[k] : undefined;
136
+ if (def !== undefined && shapeOf(v) !== shapeOf(def)) {
137
+ problems.push(`settings.${key} ignored: expected ${shapeOf(def)}, got ${shapeOf(v)}`);
138
+ continue;
139
+ }
140
+ if (ENUMS[key] && !ENUMS[key].includes(v)) {
141
+ problems.push(`settings.${key} ignored: ${JSON.stringify(v)} is not one of ${ENUMS[key].join(" | ")}`);
142
+ continue;
143
+ }
144
+ out[k] = isPlainObject(v) && isPlainObject(def) ? dropMistyped(def, v, problems, key) : v;
145
+ }
146
+ return out;
147
+ }
148
+ /** "line L column C" for a JSON.parse error that only gives a position. */
149
+ function parseErrorReason(text, e) {
150
+ const msg = e instanceof Error ? e.message : String(e);
151
+ const m = /at position (\d+)/.exec(msg);
152
+ if (!m || /line \d+/.test(msg))
153
+ return msg;
154
+ const before = text.slice(0, Number(m[1])).split("\n");
155
+ return `${msg} (line ${before.length} column ${before[before.length - 1].length + 1})`;
156
+ }
118
157
  function readSettingsFile(path) {
158
+ let text;
159
+ try {
160
+ text = readFileSync(path, "utf8");
161
+ }
162
+ catch (e) {
163
+ if (e.code === "ENOENT")
164
+ return { kind: "missing" };
165
+ return { kind: "broken", reason: e instanceof Error ? e.message : String(e) };
166
+ }
167
+ let value;
168
+ try {
169
+ value = JSON.parse(text);
170
+ }
171
+ catch (e) {
172
+ return { kind: "broken", reason: parseErrorReason(text, e) };
173
+ }
174
+ if (!isPlainObject(value))
175
+ return { kind: "broken", reason: `the top level is ${shapeOf(value)}, not an object` };
176
+ return { kind: "ok", value, text };
177
+ }
178
+ const lastGoodPath = (path) => `${path}.last-good`;
179
+ /** Write `text` to `path` atomically: a temp file in the same directory, fsync, rename. A symlinked settings file
180
+ * keeps its link: the write lands on the target. */
181
+ function writeFileAtomic(path, text, mode) {
182
+ let target = path;
183
+ try {
184
+ target = realpathSync(path);
185
+ }
186
+ catch { /* not there yet */ }
187
+ const tmp = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
188
+ const fd = openSync(tmp, "wx", mode);
119
189
  try {
120
- return JSON.parse(readFileSync(path, "utf8"));
190
+ writeSync(fd, text);
191
+ fchmodSync(fd, mode);
192
+ fsyncSync(fd);
193
+ }
194
+ catch (e) {
195
+ closeSync(fd);
196
+ try {
197
+ unlinkSync(tmp);
198
+ }
199
+ catch { /* already gone */ }
200
+ throw e;
201
+ }
202
+ closeSync(fd);
203
+ try {
204
+ renameSync(tmp, target);
205
+ }
206
+ catch (e) {
207
+ try {
208
+ unlinkSync(tmp);
209
+ }
210
+ catch { /* already gone */ }
211
+ throw e;
212
+ }
213
+ }
214
+ function fileMode(path, fallback) {
215
+ try {
216
+ return statSync(path).mode & 0o777;
121
217
  }
122
218
  catch {
219
+ return fallback;
220
+ }
221
+ }
222
+ /** Keep settings.json.last-good equal to the newest copy that parsed. A failure here costs only the fallback copy,
223
+ * so it is not an error for the caller. */
224
+ function refreshLastGood(path, text) {
225
+ const lg = lastGoodPath(path);
226
+ try {
227
+ if (readFileSync(lg, "utf8") === text)
228
+ return;
229
+ }
230
+ catch { /* no copy yet */ }
231
+ try {
232
+ writeFileAtomic(lg, text, fileMode(path, 0o600));
233
+ }
234
+ catch { /* see above */ }
235
+ }
236
+ let loadProblems = [];
237
+ /** What the last loadSettings() could not use: an unreadable settings file, values it dropped. Empty when clean.
238
+ * cli.tsx prints these at boot. */
239
+ export function settingsLoadProblems() {
240
+ return loadProblems;
241
+ }
242
+ /** The settings file's usable values: the file, else its last good copy, else nothing. Problems go in `problems`. */
243
+ function readUsableSettings(path, problems) {
244
+ const read = readSettingsFile(path);
245
+ if (read.kind === "missing")
123
246
  return undefined;
247
+ if (read.kind === "ok") {
248
+ refreshLastGood(path, read.text);
249
+ return read.value;
124
250
  }
251
+ const lg = readSettingsFile(lastGoodPath(path));
252
+ const fallback = lg.kind === "ok"
253
+ ? `using the last good copy ${lastGoodPath(path)}`
254
+ : "no last good copy, running on built-in defaults (permissions, models and routes are NOT yours)";
255
+ problems.push(`${path} is unreadable: ${read.reason} — ${fallback}. Fix the file; it was left as it is`);
256
+ return lg.kind === "ok" ? lg.value : undefined;
125
257
  }
126
258
  /** Fold env vars over the file+default merge — the top layer of the precedence stack. Only an env
127
259
  * var that's actually set overrides; an unset one leaves the file/default value alone. */
@@ -135,6 +267,14 @@ function applyEnv(s) {
135
267
  const base = process.env.KODE_AURORA ?? process.env.KODE_1M; // KODE_1M kept as a back-compat alias for the base override
136
268
  if (base)
137
269
  out.endpoints = { ...out.endpoints, aurora: { ...out.endpoints.aurora, base } };
270
+ // OPERATOR_FLEET_NODES — env lane for fleet.auroraNodes (which discovery.ts probes + auto-catalogs),
271
+ // alongside settings.json, for launchd/deployment config: "http://host:port,http://host:port".
272
+ const fleetNodes = process.env.OPERATOR_FLEET_NODES ?? process.env.KODE_FLEET_NODES;
273
+ if (fleetNodes) {
274
+ const nodes = fleetNodes.split(",").map((s) => s.trim()).filter(Boolean);
275
+ if (nodes.length)
276
+ out.fleet = { ...out.fleet, auroraNodes: nodes };
277
+ }
138
278
  const pin = parseContextArg(process.env.KODE_CONTEXT); // context cap: 300k|600k|1m sets it, "auto" clears the file's pin
139
279
  if (pin === null)
140
280
  out.contextPin = undefined;
@@ -363,9 +503,23 @@ const CLOUD_FAILOVERS = [
363
503
  { name: "axe-cloud", base: `https://${LEGACY_API_HOST}`, model: "main", ctxLimit: 307200, transport: "openai" },
364
504
  ];
365
505
  /** The shipped endpoints.aurora literal (DEFAULTS) — a box that never named its own primary. */
366
- const DEFAULT_AURORA_ENDPOINT = { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" };
506
+ const DEFAULT_AURORA_ENDPOINT = DEFAULTS.endpoints.aurora;
367
507
  function isDefaultAuroraLiteral(e) {
368
- return e.base.replace(/\/+$/, "") === DEFAULT_AURORA_ENDPOINT.base && e.model === DEFAULT_AURORA_ENDPOINT.model && e.ctxWindow === DEFAULT_AURORA_ENDPOINT.ctxWindow;
508
+ return e.base.replace(/\/+$/, "") === DEFAULT_AURORA_ENDPOINT.base && e.ctxWindow === DEFAULT_AURORA_ENDPOINT.ctxWindow && !e.apiKey && !e.apiKeyEnv && !e.apiKeyFile;
509
+ }
510
+ /** A saved endpoints.aurora (or failover) on the retired :8097 moves to the router's `main`, never an error. Its model
511
+ * id stays when the gateway serves it (operator-flash); Aurora's own ids (aurora-code-1, aurora, operator-1m) become
512
+ * `main`. A failover there is dropped: the cloud tier already backs the router. Pure. */
513
+ export function migrateRetiredAurora(s) {
514
+ const { aurora, failover } = s.endpoints;
515
+ if (!isRetiredAuroraBase(aurora.base) && !isRetiredAuroraBase(failover?.base))
516
+ return s;
517
+ const endpoints = { ...s.endpoints };
518
+ if (isRetiredAuroraBase(aurora.base))
519
+ endpoints.aurora = { ...DEFAULT_AURORA_ENDPOINT, model: gatewayModelFor(aurora.model) };
520
+ if (isRetiredAuroraBase(failover?.base))
521
+ delete endpoints.failover;
522
+ return { ...s, endpoints };
369
523
  }
370
524
  /** The local router's `main` capability (the one door, loopback): the default primary when the owner named none. */
371
525
  const ROUTER_MAIN = { name: "main", base: LOCAL_GATEWAY_BASE.replace(/\/v1\/?$/, ""), model: "main", ctxLimit: 262144 };
@@ -399,11 +553,14 @@ export function buildEndpointChain(s) {
399
553
  seen.add(key);
400
554
  chain.push(ep);
401
555
  };
402
- // 11/25: the built-in primary is the local router's `main` capability, not a launchd-owned Aurora. Only the shipped
403
- // literal is demoted: an owner's own endpoints.aurora (or the gateway's discovered port) stays first.
556
+ // 11/25: the built-in primary is the local router's `main` capability (or the model a migrated :8097 setting named);
557
+ // an owner's own endpoints.aurora (or the gateway's discovered port) stays first.
404
558
  if (isDefaultAuroraLiteral(aurora))
405
- add({ ...ROUTER_MAIN });
406
- add({ name: "operator-1m", base: aurora.base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(aurora), loopbackAuth: true });
559
+ add({ ...ROUTER_MAIN, model: aurora.model });
560
+ else if (isRetiredAuroraBase(aurora.base))
561
+ add({ ...ROUTER_MAIN, model: gatewayModelFor(aurora.model) });
562
+ else
563
+ add({ name: "operator-1m", base: aurora.base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(aurora), loopbackAuth: true });
407
564
  for (const base of (s.fleet?.auroraNodes ?? []).filter(Boolean)) {
408
565
  const cfg = { base, model: aurora.model, ctxWindow: aurora.ctxWindow };
409
566
  add({ name: `fleet-${hostLabel(base)}`, base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(cfg) });
@@ -449,11 +606,14 @@ export function applySandboxFloor(s, sandboxPinned) {
449
606
  return ownerPrivate ? s : { ...s, sandbox: { ...s.sandbox, mode: "workspace" } };
450
607
  }
451
608
  export function loadSettings() {
452
- const file = readSettingsFile(settingsPath());
609
+ const problems = [];
610
+ const raw = readUsableSettings(settingsPath(), problems);
611
+ const file = raw ? dropMistyped(DEFAULTS, raw, problems) : undefined;
612
+ loadProblems = problems;
453
613
  // structuredClone the base so a returned settings object never aliases the module-level DEFAULTS —
454
614
  // deepMerge only recurses into keys the override touches, so an untouched nested endpoint would
455
615
  // otherwise flow through by reference and a later mutation would corrupt defaults process-wide.
456
- const merged = applyEnv(deepMerge(structuredClone(DEFAULTS), file));
616
+ const merged = migrateRetiredAurora(applyEnv(deepMerge(structuredClone(DEFAULTS), file)));
457
617
  // Managed policy goes LAST: over defaults, the user's file and env. Absent file = identity function.
458
618
  const managed = loadManagedPolicy();
459
619
  const flywheelPinned = (isPlainObject(file) && isPlainObject(file.selfImprove) && typeof file.selfImprove.flywheel === "boolean") ||
@@ -478,19 +638,117 @@ export function loadSettings() {
478
638
  out = applySandboxFloor(out, sandboxPinned);
479
639
  return resolveModelMode(out);
480
640
  }
481
- /** Persist a partial settings patch onto whatever's on disk (deep-merged, file values win over
482
- * defaults for anything the patch doesn't touch), so a runtime choice like /model survives a
483
- * restart. Best-effort — same "never throws" contract as loadSettings; a write failure just means
484
- * the choice doesn't survive a restart, it doesn't affect the running process. */
485
- export function saveSettings(patch) {
486
- const path = settingsPath();
487
- const current = readSettingsFile(path);
488
- const merged = deepMerge(isPlainObject(current) ? current : {}, patch);
641
+ const LOCK_WAIT_MS = 2000;
642
+ const LOCK_STALE_MS = 10_000;
643
+ function sleepMs(ms) {
644
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
645
+ }
646
+ function lockIsStale(lock, body) {
489
647
  try {
490
- mkdirSync(dirname(path), { recursive: true });
491
- writeFileSync(path, JSON.stringify(merged, null, 2) + "\n", "utf8");
648
+ const { pid, at } = JSON.parse(body);
649
+ if (typeof at === "number" && Date.now() - at > LOCK_STALE_MS)
650
+ return true;
651
+ if (typeof pid === "number" && pid !== process.pid) {
652
+ try {
653
+ process.kill(pid, 0);
654
+ }
655
+ catch (e) {
656
+ if (e.code === "ESRCH")
657
+ return true;
658
+ }
659
+ }
660
+ return false;
492
661
  }
493
662
  catch {
494
- /* best-effort — see loadSettings */
663
+ try {
664
+ return Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS;
665
+ }
666
+ catch {
667
+ return false;
668
+ }
669
+ }
670
+ }
671
+ /** Run `fn` holding settings.json.lock (O_EXCL create; pid + timestamp inside). A lock older than LOCK_STALE_MS, or
672
+ * whose holder is gone, is broken; otherwise wait up to LOCK_WAIT_MS, then throw. */
673
+ function withSettingsLock(path, fn) {
674
+ const lock = `${path}.lock`;
675
+ const body = JSON.stringify({ pid: process.pid, at: Date.now(), id: randomBytes(6).toString("hex") });
676
+ const deadline = Date.now() + LOCK_WAIT_MS;
677
+ for (;;) {
678
+ try {
679
+ const fd = openSync(lock, "wx", 0o600);
680
+ try {
681
+ writeSync(fd, body);
682
+ }
683
+ finally {
684
+ closeSync(fd);
685
+ }
686
+ break;
687
+ }
688
+ catch (e) {
689
+ if (e.code !== "EEXIST")
690
+ throw e;
691
+ }
692
+ let held = "";
693
+ try {
694
+ held = readFileSync(lock, "utf8");
695
+ }
696
+ catch {
697
+ continue;
698
+ }
699
+ if (lockIsStale(lock, held)) {
700
+ // Move it aside and check it is still the lock judged stale; a fresh one taken meanwhile is put back.
701
+ const aside = `${lock}.${process.pid}.${randomBytes(4).toString("hex")}.stale`;
702
+ try {
703
+ renameSync(lock, aside);
704
+ }
705
+ catch {
706
+ continue;
707
+ }
708
+ let moved = "";
709
+ try {
710
+ moved = readFileSync(aside, "utf8");
711
+ }
712
+ catch { /* gone */ }
713
+ try {
714
+ if (moved !== held)
715
+ renameSync(aside, lock);
716
+ else
717
+ unlinkSync(aside);
718
+ }
719
+ catch { /* its owner finished, or it is gone */ }
720
+ continue;
721
+ }
722
+ if (Date.now() >= deadline)
723
+ throw new Error(`${path} is locked by another Operator (${lock}: ${held.trim()}); not saved`);
724
+ sleepMs(25);
495
725
  }
726
+ try {
727
+ return fn();
728
+ }
729
+ finally {
730
+ try {
731
+ if (readFileSync(lock, "utf8") === body)
732
+ unlinkSync(lock);
733
+ }
734
+ catch { /* already gone */ }
735
+ }
736
+ }
737
+ /** Persist a partial settings patch onto what is on disk NOW: under settings.json.lock it re-reads the file, deep-merges
738
+ * the patch (file values win for anything it does not touch) and writes it atomically, keeping the file's mode. A
739
+ * function patch is given the current file, for a change that depends on it (a list to append to). Throws when the
740
+ * file cannot be saved, including when it is unreadable (it is never written over). */
741
+ export function saveSettings(patch) {
742
+ const path = settingsPath();
743
+ mkdirSync(dirname(path), { recursive: true });
744
+ withSettingsLock(path, () => {
745
+ const current = readSettingsFile(path);
746
+ if (current.kind === "broken")
747
+ throw new Error(`${path} is unreadable (${current.reason}); not saved over it — fix the file first`);
748
+ const base = current.kind === "ok" ? current.value : {};
749
+ const text = JSON.stringify(deepMerge(base, typeof patch === "function" ? patch(base) : patch), null, 2) + "\n";
750
+ const mode = fileMode(path, 0o600);
751
+ writeFileAtomic(path, text, mode);
752
+ refreshLastGood(path, text);
753
+ });
496
754
  }
@@ -3,7 +3,6 @@
3
3
  // renderSkillsIndex is sync so composeSystemPrompt can drop it in without going async.
4
4
  import { get_operator_home } from "./home.js";
5
5
  const INDEX_CAP = 4000;
6
- const INDEX_DESC = 57;
7
6
  function nodeBuiltins() {
8
7
  try {
9
8
  const proc = globalThis.process;
@@ -43,6 +42,33 @@ function field(fm, key) {
43
42
  const m = fm.match(new RegExp(`^${key}:\\s*(.*)$`, "m"));
44
43
  return m ? yamlScalar(m[1]) : "";
45
44
  }
45
+ /** `metadata.operator.tags` from a skill's frontmatter, inline (`[a, b]`) or as a `- a` list. Skills written
46
+ * before the key was renamed carry `metadata.hermes`, which is read when `operator` is absent. */
47
+ export function skillTags(raw) {
48
+ const fm = frontmatter(raw);
49
+ const meta = fm && /^metadata:[ \t]*\r?\n((?:[ \t]+.*(?:\r?\n|$))*)/m.exec(fm)?.[1];
50
+ if (!meta)
51
+ return [];
52
+ for (const key of ["operator", "hermes"]) {
53
+ const block = new RegExp(`^([ \\t]+)${key}:[ \\t]*\\r?\\n((?:\\1[ \\t]+.*(?:\\r?\\n|$))*)`, "m").exec(meta)?.[2];
54
+ if (block === undefined)
55
+ continue;
56
+ const m = /^[ \t]+tags:[ \t]*(.*)$/m.exec(block);
57
+ if (!m)
58
+ return [];
59
+ if (m[1].trim().startsWith("["))
60
+ return m[1].trim().replace(/^\[|\]$/g, "").split(",").map(yamlScalar).filter(Boolean);
61
+ const items = [];
62
+ for (const line of block.slice(m.index + m[0].length).split(/\r?\n/).slice(1)) {
63
+ const li = /^[ \t]+-[ \t]+(.*)$/.exec(line);
64
+ if (!li)
65
+ break;
66
+ items.push(yamlScalar(li[1]));
67
+ }
68
+ return items.filter(Boolean);
69
+ }
70
+ return [];
71
+ }
46
72
  function parseDescription(raw) {
47
73
  const fm = frontmatter(raw);
48
74
  if (fm) {
@@ -84,7 +110,7 @@ function readSkill(fs, file) {
84
110
  catch { /* empty */ }
85
111
  const fallback = file.replace(/\\/g, "/").split("/").pop()?.replace(/\.md$/i, "") || "skill";
86
112
  const leaf = fallback === "SKILL" ? (file.replace(/\\/g, "/").split("/").slice(-2, -1)[0] || "skill") : fallback;
87
- return { name: parseName(raw, leaf), description: parseDescription(raw) };
113
+ return { name: parseName(raw, leaf), description: parseDescription(raw), tags: skillTags(raw) };
88
114
  }
89
115
  export function listLocalSkills() {
90
116
  const b = nodeBuiltins();
@@ -107,7 +133,7 @@ export function listLocalSkills() {
107
133
  const full = b.path.join(root, ent.name);
108
134
  if (ent.isFile() && ent.name.endsWith(".md")) {
109
135
  const meta = readSkill(b.fs, full);
110
- found.push({ name: meta.name, file: full, dir: false, description: meta.description });
136
+ found.push({ name: meta.name, file: full, dir: false, description: meta.description, tags: meta.tags });
111
137
  }
112
138
  }
113
139
  const walk = (dir, depth) => {
@@ -127,7 +153,7 @@ export function listLocalSkills() {
127
153
  const skillMd = b.path.join(full, "SKILL.md");
128
154
  if (isFile(b.fs, skillMd)) {
129
155
  const meta = readSkill(b.fs, skillMd);
130
- found.push({ name: meta.name, file: skillMd, dir: true, root: full, description: meta.description });
156
+ found.push({ name: meta.name, file: skillMd, dir: true, root: full, description: meta.description, tags: meta.tags });
131
157
  }
132
158
  else {
133
159
  walk(full, depth + 1);
@@ -160,20 +186,17 @@ export function resolveSkillFile(skillRoot, filePath) {
160
186
  return null;
161
187
  return target;
162
188
  }
189
+ /** The installed skills' names, comma-separated, under INDEX_CAP: what each does is skill_list's answer, its body
190
+ * skill_fetch's (the deferred tools' split: names in the prompt, the rest on demand). */
163
191
  export function renderSkillsIndex() {
164
- const skills = listLocalSkills();
165
- if (!skills.length)
166
- return "";
167
- const lines = [];
192
+ const names = [];
168
193
  let used = 0;
169
- for (const s of skills) {
170
- const desc = s.description.replace(/\s+/g, " ").trim().slice(0, INDEX_DESC);
171
- const line = `${s.name}: ${desc}`;
172
- const next = used + line.length + (lines.length ? 1 : 0);
194
+ for (const s of listLocalSkills()) {
195
+ const next = used + s.name.length + (names.length ? 2 : 0);
173
196
  if (next > INDEX_CAP)
174
197
  break;
175
- lines.push(line);
198
+ names.push(s.name);
176
199
  used = next;
177
200
  }
178
- return lines.join("\n");
201
+ return names.join(", ");
179
202
  }
@@ -0,0 +1,12 @@
1
+ // Operating standards added to the system prompt for staff ("op") only. Not shipped to anyone else: the wiring calls
2
+ // staffPromptAddition(userType()), which is empty for an external user. Plain operating rules, no internal names.
3
+ import { userTypeAtLeast } from "../auth/staff.js";
4
+ export const STAFF_PROMPT = [
5
+ "Staff operating standards:",
6
+ "- Write no comments unless the reason is genuinely non-obvious.",
7
+ "- Verify before you say it is done: run the real check, and report a failure as a failure.",
8
+ "- Keep the text between tool calls short; keep a final summary short and concrete.",
9
+ "- Do exactly what was asked and stop; mention, do not do, anything adjacent.",
10
+ "- If a request rests on a misconception, say so plainly before acting.",
11
+ ].join("\n");
12
+ export const staffPromptAddition = (type) => (userTypeAtLeast(type, "op") ? STAFF_PROMPT : "");