@0perator/operator 0.1.285 → 0.1.321

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 (118) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +308 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +217 -44
  11. package/dist/autonomy/delegate.js +34 -5
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/index.js +22 -0
  14. package/dist/autonomy/profile.js +1 -1
  15. package/dist/autonomy/session-factory.js +25 -16
  16. package/dist/background/index.js +40 -0
  17. package/dist/browser/cdp.js +1 -1
  18. package/dist/bus/inbox.js +20 -0
  19. package/dist/classifier/config.js +47 -0
  20. package/dist/classifier/modes.js +41 -0
  21. package/dist/classifier/types.js +1 -0
  22. package/dist/cli.js +645 -93
  23. package/dist/config/features.js +69 -0
  24. package/dist/config/persona.js +143 -107
  25. package/dist/config/scaffold.js +15 -0
  26. package/dist/config/settings.js +107 -12
  27. package/dist/consolidation/sleep.js +73 -11
  28. package/dist/engine/agent.js +279 -20
  29. package/dist/engine/anthropic-chat.js +343 -0
  30. package/dist/engine/aurora.js +109 -16
  31. package/dist/engine/batch-scheduler.js +41 -9
  32. package/dist/engine/classifier.js +85 -0
  33. package/dist/engine/compaction.js +25 -6
  34. package/dist/engine/fast-start.js +25 -0
  35. package/dist/engine/loop-guard.js +448 -0
  36. package/dist/engine/net-error.js +24 -0
  37. package/dist/engine/repetition-guard.js +180 -0
  38. package/dist/engine/router-adapter.js +1 -0
  39. package/dist/engine/selfheal.js +8 -0
  40. package/dist/engine/toolcalls.js +51 -1
  41. package/dist/engine/verify-gate.js +2 -0
  42. package/dist/flywheel/processor.js +78 -31
  43. package/dist/flywheel/srft.js +13 -0
  44. package/dist/hooks/index.js +196 -0
  45. package/dist/idle/activity.js +20 -0
  46. package/dist/idle/index.js +5 -0
  47. package/dist/idle/monitor.js +71 -0
  48. package/dist/idle/policy.js +66 -0
  49. package/dist/idle/proc.js +22 -0
  50. package/dist/idle/reaper.js +69 -0
  51. package/dist/idle/session-record.js +59 -0
  52. package/dist/index.js +1 -1
  53. package/dist/mcp/config.js +93 -15
  54. package/dist/mcp/index.js +9 -2
  55. package/dist/memory/index.js +0 -0
  56. package/dist/memory/providers.js +210 -0
  57. package/dist/memory/session-catalog.js +422 -0
  58. package/dist/memory/session-providers.js +121 -0
  59. package/dist/memory/session-sources.js +335 -0
  60. package/dist/memory/skylark.js +131 -0
  61. package/dist/models/bench.js +103 -0
  62. package/dist/models/registry.js +144 -0
  63. package/dist/models/switch.js +69 -0
  64. package/dist/observability/blackbox.js +37 -0
  65. package/dist/permissions/index.js +22 -7
  66. package/dist/permissions/policy.js +31 -6
  67. package/dist/permissions/tier.js +1 -1
  68. package/dist/remote/host.js +20 -2
  69. package/dist/remote/safe-commands.js +38 -0
  70. package/dist/router/discovery.js +127 -0
  71. package/dist/router/models.js +107 -16
  72. package/dist/router/portal.js +100 -0
  73. package/dist/router/router.js +1 -1
  74. package/dist/services/preflight.js +108 -8
  75. package/dist/services/store-sync.js +111 -0
  76. package/dist/session-teardown.js +10 -1
  77. package/dist/session.js +338 -46
  78. package/dist/skills/catalogue.js +1 -1
  79. package/dist/tools/chauffeur-native.js +155 -0
  80. package/dist/tools/chauffeur.js +26 -3
  81. package/dist/tools/download.js +229 -0
  82. package/dist/tools/executor.js +19 -9
  83. package/dist/tools/find-files.js +483 -0
  84. package/dist/tools/git-pr.js +94 -0
  85. package/dist/tools/incident-tools.js +82 -0
  86. package/dist/tools/memory.js +12 -2
  87. package/dist/tools/monitoring-tools.js +312 -0
  88. package/dist/tools/paths.js +154 -0
  89. package/dist/tools/registry.js +582 -95
  90. package/dist/tools/semantic-compress.js +124 -0
  91. package/dist/tools/shell-context.js +1 -0
  92. package/dist/tools/shell-jobs.js +163 -0
  93. package/dist/tools/shell-session.js +174 -6
  94. package/dist/tools/tool-output-spill.js +1 -1
  95. package/dist/tools/wave-tools.js +609 -0
  96. package/dist/tools/wave2-tools.js +411 -0
  97. package/dist/ui/App.js +15 -4
  98. package/dist/ui/BgPanel.js +30 -6
  99. package/dist/ui/Composer.js +15 -2
  100. package/dist/ui/QuestionPrompt.js +32 -12
  101. package/dist/ui/SessionPicker.js +86 -0
  102. package/dist/ui/StatusRule.js +5 -5
  103. package/dist/ui/ToolStep.js +17 -1
  104. package/dist/ui/Transcript.js +17 -1
  105. package/dist/ui/index.js +1 -1
  106. package/dist/ui/liveTools.js +21 -3
  107. package/dist/ui/slashCommands.js +2 -0
  108. package/dist/util/mentions.js +1 -1
  109. package/dist/util/screenshots.js +74 -8
  110. package/dist/util/slash.js +2 -2
  111. package/dist/vault/store.js +1 -1
  112. package/mcp/README.md +88 -0
  113. package/mcp/ocr-macos.swift +45 -0
  114. package/mcp/powertools-media.mjs +464 -0
  115. package/mcp/powertools-toolbox.mjs +1114 -0
  116. package/mcp/powertools.md +210 -0
  117. package/mcp/powertools.mjs +861 -0
  118. package/package.json +9 -2
@@ -1,4 +1,4 @@
1
- // Cron — Hermes-shaped scheduled headless runs (operator-home-v2 §7). Jobs live in
1
+ // Cron — scheduled headless runs (operator-home-v2 §7). Jobs live in
2
2
  // <home>/cron/jobs.json; every execution appends one JSONL line to <home>/cron/executions.jsonl and
3
3
  // drops the run's output text under <home>/cron/output/<id>-<ts>.txt. A job is either a fixed
4
4
  // interval ({kind:"interval", everyMinutes}) or a 5-field cron expression ({kind:"cron", expr}).
@@ -12,6 +12,9 @@
12
12
  // src/tools/memory.ts) and the schedule math below is pure. The session-spawning default executor
13
13
  // is ALSO lazily imported — session-factory pulls node-only modules statically.
14
14
  import { operatorPath } from "../config/home.js";
15
+ import { withJobsLock, CronLockBusyError } from "./cron-lock.js";
16
+ import { advanceRun, newRun, runInFlight, runIsAbandoned } from "./cron-lifecycle.js";
17
+ import { openIncident } from "./incidents.js";
15
18
  const nodeImport = (m) => import(/* @vite-ignore */ m);
16
19
  let _fs = null;
17
20
  let _path = null;
@@ -139,13 +142,20 @@ export async function saveJobs(jobs) {
139
142
  fs.mkdirSync(path.dirname(p), { recursive: true });
140
143
  fs.writeFileSync(p, JSON.stringify(jobs, null, 2) + "\n", "utf8");
141
144
  }
142
- /** Append one execution record to cron/executions.jsonl (audit trail; never throws). */
143
- export async function recordExecution(jobId, ok, note) {
145
+ /** Append one execution record to cron/executions.jsonl (audit trail; never throws).
146
+ * With a run record this IS the archive: the full state trail + duration ride along. */
147
+ export async function recordExecution(jobId, ok, note, run) {
144
148
  try {
145
149
  const { fs, path } = await fsp();
146
150
  const p = cronExecutionsPath();
147
151
  fs.mkdirSync(path.dirname(p), { recursive: true });
148
- fs.appendFileSync(p, JSON.stringify({ t: Date.now(), jobId, ok, note }) + "\n", "utf8");
152
+ const rec = { t: Date.now(), jobId, ok, note };
153
+ if (run) {
154
+ rec.runId = run.runId;
155
+ rec.states = run.history;
156
+ rec.durationMs = (run.finishedAt ?? run.claimedAt) - run.claimedAt;
157
+ }
158
+ fs.appendFileSync(p, JSON.stringify(rec) + "\n", "utf8");
149
159
  }
150
160
  catch { /* best-effort — the log must never break a run */ }
151
161
  }
@@ -164,59 +174,204 @@ export async function writeOutput(jobId, text) {
164
174
  return "";
165
175
  }
166
176
  }
167
- /** Run one job through `execute`, record the execution, save the output, and advance
168
- * lastRunAt/nextRunAt in the jobs file. Shared by runDueJobs and runJobNow. */
169
- async function executeAndRecord(jobs, job, execute, startedAt) {
170
- let ok = false, note, output = "";
177
+ /** Advance one job's clock to `startedAt` — lastRunAt set, nextRunAt recomputed. Claim-time only. */
178
+ function advanceSchedule(job, startedAt) {
179
+ job.lastRunAt = startedAt;
180
+ const next = nextRun(job.schedule, startedAt);
181
+ if (next !== null)
182
+ job.nextRunAt = next;
183
+ else
184
+ delete job.nextRunAt;
185
+ }
186
+ function genRunId() {
187
+ return `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
188
+ }
189
+ /** This process's run-claim identity (host read lazily — neutral-bundle rule). */
190
+ async function claimIdentity() {
191
+ const os = (await nodeImport("node:os"));
192
+ return { pid: process.pid, host: os.hostname() };
193
+ }
194
+ /** Liveness probe for runIsAbandoned: ESRCH = dead; EPERM = alive but not ours. */
195
+ function pidAlive(pid) {
171
196
  try {
172
- output = (await execute(job)) ?? "";
173
- ok = true;
197
+ process.kill(pid, 0);
198
+ return true;
174
199
  }
175
200
  catch (e) {
176
- note = e instanceof Error ? e.message : String(e);
201
+ return e?.code === "EPERM";
202
+ }
203
+ }
204
+ /** Recover every ABANDONED run in `jobs` (claimer dead or past the stale deadline): archive it
205
+ * as a failure and free the job. Mutates in place; caller saves — and opens the incidents
206
+ * AFTER releasing the store lock (see callers), never while holding it. */
207
+ async function recoverAbandonedRuns(jobs, now, host) {
208
+ const recovered = [];
209
+ for (const j of jobs) {
210
+ if (!runIsAbandoned(j.run, now, { host, isAlive: pidAlive }))
211
+ continue;
212
+ const run = j.run;
213
+ advanceRun(run, "delivered", now, { ok: false, note: `abandoned by pid ${run.claimedBy.pid}@${run.claimedBy.host} (claimed ${new Date(run.claimedAt).toISOString()})` });
214
+ advanceRun(run, "archived", now);
215
+ await recordExecution(j.id, false, run.note, run);
216
+ delete j.run;
217
+ recovered.push({ jobId: j.id, run });
218
+ }
219
+ return recovered;
220
+ }
221
+ /** PV2-22 glue: a recovered (abandoned) run is a HIGH incident; a failed run is MEDIUM.
222
+ * openIncident dedupes per (source, jobId) and is best-effort by construction. */
223
+ async function reportRunIncident(jobId, run, severity, title) {
224
+ try {
225
+ await openIncident({ source: "cron", severity, title, detail: run.note, jobId, runId: run.runId });
226
+ }
227
+ catch { /* incidents must never break a cron run */ }
228
+ }
229
+ /** Drive one ALREADY-CLAIMED job through its lifecycle: preflight → executing → delivered.
230
+ * A failing preflight delivers the run as a failure WITHOUT executing. Never touches the
231
+ * jobs file (the trail lives on job.run in memory until finalizeRun archives it). */
232
+ async function runClaimedJob(job, execute, preflight) {
233
+ const run = job.run;
234
+ let ok = false, note, output = "";
235
+ advanceRun(run, "preflight", Date.now());
236
+ let preflightFailed = false;
237
+ if (preflight) {
238
+ try {
239
+ await preflight(job);
240
+ }
241
+ catch (e) {
242
+ preflightFailed = true;
243
+ note = `preflight: ${e instanceof Error ? e.message : String(e)}`;
244
+ }
245
+ }
246
+ if (preflightFailed) {
247
+ advanceRun(run, "delivered", Date.now(), { ok: false, note });
248
+ }
249
+ else {
250
+ advanceRun(run, "executing", Date.now());
251
+ try {
252
+ output = (await execute(job)) ?? "";
253
+ ok = true;
254
+ }
255
+ catch (e) {
256
+ note = e instanceof Error ? e.message : String(e);
257
+ }
258
+ advanceRun(run, "delivered", Date.now(), { ok, note });
177
259
  }
178
- await recordExecution(job.id, ok, note);
179
260
  if (ok)
180
261
  await writeOutput(job.id, output);
181
- const j = jobs.find((x) => x.id === job.id);
182
- if (j) {
183
- j.lastRunAt = startedAt;
184
- const next = nextRun(j.schedule, startedAt);
185
- if (next !== null)
186
- j.nextRunAt = next;
187
- else
188
- delete j.nextRunAt;
189
- }
190
262
  return { ok, note, output };
191
263
  }
264
+ /** Archive the finished run and free the job, under the store lock. A transient busy lock is
265
+ * tolerated: the run stays "claimed" in the file and the 15-min abandoned-run recovery is the
266
+ * self-heal; contention here is milliseconds-scale so that path is vanishingly rare. */
267
+ async function finalizeRun(job) {
268
+ const run = job.run;
269
+ advanceRun(run, "archived", Date.now());
270
+ await recordExecution(job.id, run.ok === true, run.note, run);
271
+ if (run.ok !== true) {
272
+ await reportRunIncident(job.id, run, "medium", `cron job ${job.id}: run failed`);
273
+ }
274
+ try {
275
+ await withJobsLock(async () => {
276
+ const jobs = await loadJobs();
277
+ const j = jobs.find((x) => x.id === job.id);
278
+ if (j && j.run?.runId === run.runId) {
279
+ delete j.run;
280
+ await saveJobs(jobs);
281
+ }
282
+ });
283
+ }
284
+ catch (e) {
285
+ if (!(e instanceof CronLockBusyError))
286
+ throw e;
287
+ }
288
+ }
192
289
  /**
193
290
  * Fire every due job (see dueJobs) through the injectable `execute` — the seam that keeps this
194
291
  * testable without spawning real sessions. Schedules advance even on failure (the execution log
195
- * carries the error) so a broken job can't hot-loop every tick. Returns per-batch counts.
292
+ * carries the error) so a broken job can't hot-loop every tick.
293
+ *
294
+ * CLAIM-THEN-EXECUTE (PV2-20): the due set is claimed ATOMICALLY under the cross-process store
295
+ * lock — load, advance every due schedule, save — and only then executed, outside the lock. A
296
+ * concurrent process (second session, headless routine) loads after the claim-save and sees
297
+ * nothing due, so a job can never double-run; previously schedules advanced only after the whole
298
+ * batch finished, leaving a minutes-wide double-run window. A busy lock means another process
299
+ * owns this tick: skip quietly, the jobs run there. Returns per-batch counts.
196
300
  */
197
- export async function runDueJobs(execute, nowMs = Date.now()) {
198
- const jobs = await loadJobs();
199
- const due = dueJobs(jobs, nowMs);
301
+ export async function runDueJobs(execute, nowMs = Date.now(), preflight) {
302
+ let claimed;
303
+ let recoveredRuns = [];
304
+ try {
305
+ const res = await withJobsLock(async () => {
306
+ const jobs = await loadJobs();
307
+ const by = await claimIdentity();
308
+ const recovered = await recoverAbandonedRuns(jobs, Date.now(), by.host);
309
+ // A job with an in-flight run is occupied — never claim it again (PV2-21).
310
+ const due = dueJobs(jobs, nowMs).filter((j) => !runInFlight(j.run));
311
+ const startedAt = Date.now();
312
+ for (const dj of due) {
313
+ advanceSchedule(dj, startedAt);
314
+ dj.run = newRun(genRunId(), by, startedAt);
315
+ }
316
+ if (due.length || recovered.length)
317
+ await saveJobs(jobs);
318
+ return { due, recovered };
319
+ });
320
+ claimed = res.due;
321
+ recoveredRuns = res.recovered;
322
+ }
323
+ catch (e) {
324
+ if (e instanceof CronLockBusyError)
325
+ return { ran: 0, ok: 0, failed: 0 };
326
+ throw e;
327
+ }
328
+ for (const { jobId, run } of recoveredRuns) {
329
+ await reportRunIncident(jobId, run, "high", `cron job ${jobId}: run abandoned`);
330
+ }
200
331
  let ok = 0, failed = 0;
201
- for (const dj of due) {
202
- const r = await executeAndRecord(jobs, dj, execute, Date.now());
332
+ for (const dj of claimed) {
333
+ const r = await runClaimedJob(dj, execute, preflight);
203
334
  if (r.ok)
204
335
  ok++;
205
336
  else
206
337
  failed++;
338
+ await finalizeRun(dj);
207
339
  }
208
- if (due.length)
209
- await saveJobs(jobs);
210
- return { ran: due.length, ok, failed };
340
+ return { ran: claimed.length, ok, failed };
211
341
  }
212
342
  /** Force one job NOW (the `cronjob run` tool action), regardless of its schedule. */
213
- export async function runJobNow(id, execute) {
214
- const jobs = await loadJobs();
215
- const job = jobs.find((j) => j.id === id);
343
+ export async function runJobNow(id, execute, preflight) {
344
+ let job;
345
+ let busyNote;
346
+ try {
347
+ job = await withJobsLock(async () => {
348
+ const jobs = await loadJobs();
349
+ const by = await claimIdentity();
350
+ await recoverAbandonedRuns(jobs, Date.now(), by.host); // recovered incidents ride the next tick's report
351
+ const j = jobs.find((x) => x.id === id);
352
+ if (j && runInFlight(j.run)) {
353
+ busyNote = `run ${j.run.runId} in flight (${j.run.state}, pid ${j.run.claimedBy.pid}@${j.run.claimedBy.host})`;
354
+ return undefined;
355
+ }
356
+ if (j) {
357
+ advanceSchedule(j, Date.now());
358
+ j.run = newRun(genRunId(), by, Date.now());
359
+ await saveJobs(jobs);
360
+ }
361
+ return j;
362
+ });
363
+ }
364
+ catch (e) {
365
+ if (e instanceof CronLockBusyError)
366
+ return `error: cron store busy (${e.message}) — try again`;
367
+ throw e;
368
+ }
369
+ if (busyNote)
370
+ return `error: job "${id}" is busy — ${busyNote}`;
216
371
  if (!job)
217
372
  return `error: no cron job "${id}"`;
218
- const r = await executeAndRecord(jobs, job, execute, Date.now());
219
- await saveJobs(jobs);
373
+ const r = await runClaimedJob(job, execute, preflight);
374
+ await finalizeRun(job);
220
375
  const next = job.nextRunAt ? new Date(job.nextRunAt).toISOString() : "n/a";
221
376
  return r.ok
222
377
  ? `ran ${job.id}: ok — next ${next} (${r.output.length} chars output)`
@@ -294,9 +449,18 @@ export async function runCronTool(args) {
294
449
  ...(String(args.name ?? "").trim() ? { name: String(args.name).trim() } : {}),
295
450
  schedule, task, enabled: true, nextRunAt: next ?? undefined,
296
451
  };
297
- const jobs = await loadJobs();
298
- jobs.push(job);
299
- await saveJobs(jobs);
452
+ try {
453
+ await withJobsLock(async () => {
454
+ const jobs = await loadJobs();
455
+ jobs.push(job);
456
+ await saveJobs(jobs);
457
+ });
458
+ }
459
+ catch (e) {
460
+ if (e instanceof CronLockBusyError)
461
+ return `error: cron store busy (${e.message}) — try again`;
462
+ throw e;
463
+ }
300
464
  return `created cron job ${job.id} (${readableSchedule(schedule)}) — next ${next ? new Date(next).toISOString() : "never (invalid cron dates)"}`;
301
465
  }
302
466
  if (action === "list") {
@@ -315,12 +479,21 @@ export async function runCronTool(args) {
315
479
  const id = String(args.id ?? "").trim();
316
480
  if (!id)
317
481
  return "error: remove needs an `id`";
318
- const jobs = await loadJobs();
319
- const kept = jobs.filter((j) => j.id !== id);
320
- if (kept.length === jobs.length)
321
- return `error: no cron job "${id}"`;
322
- await saveJobs(kept);
323
- return `removed cron job ${id}`;
482
+ try {
483
+ return await withJobsLock(async () => {
484
+ const jobs = await loadJobs();
485
+ const kept = jobs.filter((j) => j.id !== id);
486
+ if (kept.length === jobs.length)
487
+ return `error: no cron job "${id}"`;
488
+ await saveJobs(kept);
489
+ return `removed cron job ${id}`;
490
+ });
491
+ }
492
+ catch (e) {
493
+ if (e instanceof CronLockBusyError)
494
+ return `error: cron store busy (${e.message}) — try again`;
495
+ throw e;
496
+ }
324
497
  }
325
498
  if (action === "run") {
326
499
  const id = String(args.id ?? "").trim();
@@ -47,17 +47,31 @@ export async function delegationDepth() {
47
47
  return Math.max(scoped, Number.isFinite(env) && env > 0 ? Math.floor(env) : 0);
48
48
  }
49
49
  // ── Settings + brief ────────────────────────────────────────────────────────
50
+ /** A loopback Aurora profile (operator-1m/128k): its STATIC profile endpoint (127.0.0.1:8097) is a
51
+ * placeholder — the live port is published dynamically to server.json (the local gateway). Matched so a
52
+ * delegate to it is pointed at the live gateway, never a remote (scout/cortana) or BYO target. */
53
+ function isLocalAuroraProfile(p) {
54
+ const ep = p.endpoint ?? "";
55
+ return /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(ep) && (p.model ?? "") === "aurora-code-1";
56
+ }
50
57
  /** Point a settings object at `profile`'s endpoint. Pure (the base is never mutated). `activeModel` + the
51
58
  * ctx window are what size the child's lean-harness prompt and compaction ceiling (a 32K Scout must not be
52
59
  * budgeted like the 300K Aurora); no failover (a sub-agent must not silently hop to a different model);
53
60
  * MCP off (a heavy tool catalogue overruns a small-context model, and each delegation would otherwise spawn
54
- * the owner's MCP servers). The router binding itself is Session.setModel's job, not this function's. */
55
- export function deriveDelegateSettings(base, profile) {
61
+ * the owner's MCP servers). The router binding itself is Session.setModel's job, not this function's —
62
+ * which re-resolves the profile from the registry, so `endpointOverride` (the live gateway for a local
63
+ * Aurora target) must ALSO replace the profile's endpoint in settings.models, not just endpoints.aurora. */
64
+ export function deriveDelegateSettings(base, profile, endpointOverride) {
65
+ const endpoint = endpointOverride || endpointBase(profile.endpoint ?? "");
66
+ const models = endpointOverride
67
+ ? [...(base.models ?? []), { ...profile, endpoint: `${endpointOverride}/v1` }]
68
+ : base.models;
56
69
  return {
57
70
  ...base,
71
+ models,
58
72
  endpoints: {
59
73
  aurora: {
60
- base: endpointBase(profile.endpoint ?? ""),
74
+ base: endpoint,
61
75
  model: profile.model ?? profile.id,
62
76
  ctxWindow: profile.ctx ?? base.endpoints.aurora.ctxWindow,
63
77
  },
@@ -108,19 +122,34 @@ export async function runDelegateTask(args, deps = defaultDeps) {
108
122
  return "error: delegate_task needs a non-empty `task` — a self-contained subtask; the sub-agent sees nothing else";
109
123
  const modelId = String(args.model ?? "").trim() || DEFAULT_DELEGATE_MODEL;
110
124
  const settings = await deps.loadSettings();
111
- const { profile, error } = selectModel(modelRegistry(settings.models), modelId);
125
+ // Gate BYO providers (Claude/OpenAI/Gemini/Qwen/…) on the user actually having stored that provider's key,
126
+ // the same check /model applies — so an unconnected provider fails fast with the actionable "store the key"
127
+ // error BEFORE a sub-agent session is spun up (and before setModel would refuse it anyway, more expensively).
128
+ const hasByo = deps.hasByo ?? (await nodeImport("../auth/byo.js")).hasByoToken;
129
+ const { profile, error } = selectModel(modelRegistry(settings.models), modelId, hasByo);
112
130
  if (error || !profile)
113
131
  return `error: delegate_task: ${error ?? `unknown model "${modelId}"`}`;
114
132
  if (profile.kind !== "single") {
115
133
  return `error: delegate_task: "${profile.id}" is an orchestrated profile with no endpoint of its own — pick a single-endpoint model`;
116
134
  }
135
+ // A delegate to the LOCAL Aurora must hit the live dynamic gateway (server.json, e.g. :52100), not the
136
+ // profile's static :8097 — which is unserved (the port is dynamic). Resolve it the SAME way the headless
137
+ // entry + ensureServices do (discoverAuroraEndpoint, strip /v1). Scoped to loopback Aurora — remote
138
+ // (scout/cortana) and BYO targets keep their own endpoints untouched.
139
+ let auroraOverride;
140
+ if (isLocalAuroraProfile(profile)) {
141
+ const { discoverAuroraEndpoint } = (await nodeImport("../services/preflight.js"));
142
+ const dyn = await discoverAuroraEndpoint();
143
+ if (dyn)
144
+ auroraOverride = dyn.replace(/\/v1\/?$/, "");
145
+ }
117
146
  const id = `delegate-${profile.id}-${Date.now().toString(36)}-${++_seq}`;
118
147
  // Isolation: the child never writes the owner's live memory / rolling summary (see autonomy/profile.ts).
119
148
  const { tmpdir } = (await nodeImport("node:os"));
120
149
  const dir = `${tmpdir()}/operator-${id}`;
121
150
  let session;
122
151
  try {
123
- session = await deps.createSession(deriveDelegateSettings(settings, profile), {
152
+ session = await deps.createSession(deriveDelegateSettings(settings, profile, auroraOverride), {
124
153
  extra: {
125
154
  sessionId: id,
126
155
  memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
@@ -0,0 +1,135 @@
1
+ // PV2-22: Incident tracking — open/ack/resolve tied to cron/job failures.
2
+ //
3
+ // Adopted from the teacher's draft and hardened for multi-process reality: every read-modify-write
4
+ // of incidents.json runs under a cross-process lock (the cron-lock mechanism with its own lock dir —
5
+ // two ticks or a tick + a user's incident_resolve must never clobber each other), and openIncident
6
+ // DEDUPES per (source, jobId): a hot-failing every-minute job updates its one open incident instead
7
+ // of opening sixty an hour.
8
+ import { operatorPath } from "../config/home.js";
9
+ import { withJobsLock, CronLockBusyError } from "./cron-lock.js";
10
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
11
+ function incidentsFile() { return operatorPath("incidents.json"); }
12
+ function incidentsLockDir() { return operatorPath("incidents.lock"); }
13
+ /** Serialize every incidents.json read-modify-write across processes (reuses the cron-lock
14
+ * mechanism with its own lock dir). A busy lock degrades to best-effort: incidents must
15
+ * never break a cron run, so callers treat CronLockBusyError as a skipped write. */
16
+ async function withIncidentsLock(fn) {
17
+ return withJobsLock(fn, { lockDir: incidentsLockDir() });
18
+ }
19
+ async function loadIncidents() {
20
+ const { readFile } = await nodeImport("node:fs/promises");
21
+ try {
22
+ return JSON.parse(await readFile(incidentsFile(), "utf8"));
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ }
28
+ async function saveIncidents(incidents) {
29
+ const { writeFile, mkdir } = await nodeImport("node:fs/promises");
30
+ const { dirname } = await nodeImport("node:path");
31
+ const f = incidentsFile();
32
+ await mkdir(dirname(f), { recursive: true, mode: 0o700 });
33
+ await writeFile(f, JSON.stringify(incidents, null, 2), { encoding: "utf8", mode: 0o600 });
34
+ }
35
+ const SEVERITY_RANK = { low: 0, medium: 1, high: 2, critical: 3 };
36
+ /** Open an incident — or, when an OPEN one already exists for the same (source, jobId), absorb
37
+ * the new failure into it: refresh detail/runId, escalate severity (never downgrade). Lock-held;
38
+ * on a busy lock the incident is returned UNPERSISTED (best-effort — never breaks a cron run). */
39
+ export async function openIncident(opts) {
40
+ const fresh = () => ({
41
+ id: `inc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
42
+ state: "open",
43
+ severity: opts.severity ?? "medium",
44
+ source: opts.source, title: opts.title, detail: opts.detail,
45
+ jobId: opts.jobId, runId: opts.runId,
46
+ openedAt: new Date().toISOString(),
47
+ });
48
+ try {
49
+ return await withIncidentsLock(async () => {
50
+ const incidents = await loadIncidents();
51
+ if (opts.jobId) {
52
+ const existing = incidents.find(i => i.state === "open" && i.source === opts.source && i.jobId === opts.jobId);
53
+ if (existing) {
54
+ if (opts.detail)
55
+ existing.detail = opts.detail;
56
+ if (opts.runId)
57
+ existing.runId = opts.runId;
58
+ const next = opts.severity ?? "medium";
59
+ if (SEVERITY_RANK[next] > SEVERITY_RANK[existing.severity])
60
+ existing.severity = next;
61
+ await saveIncidents(incidents);
62
+ return existing;
63
+ }
64
+ }
65
+ const incident = fresh();
66
+ incidents.push(incident);
67
+ await saveIncidents(incidents);
68
+ return incident;
69
+ });
70
+ }
71
+ catch (e) {
72
+ if (e instanceof CronLockBusyError)
73
+ return fresh(); // unpersisted — documented best-effort
74
+ throw e;
75
+ }
76
+ }
77
+ export async function ackIncident(id) {
78
+ try {
79
+ return await withIncidentsLock(async () => {
80
+ const incidents = await loadIncidents();
81
+ const inc = incidents.find(i => i.id === id);
82
+ if (!inc)
83
+ return `error: incident ${id} not found`;
84
+ if (inc.state !== "open")
85
+ return `error: incident ${id} is ${inc.state}, not open`;
86
+ inc.state = "acknowledged";
87
+ inc.acknowledgedAt = new Date().toISOString();
88
+ await saveIncidents(incidents);
89
+ return `incident ${id} acknowledged`;
90
+ });
91
+ }
92
+ catch (e) {
93
+ if (e instanceof CronLockBusyError)
94
+ return `error: incident store busy — try again`;
95
+ throw e;
96
+ }
97
+ }
98
+ export async function resolveIncident(id, resolution, resolvedBy) {
99
+ try {
100
+ return await withIncidentsLock(async () => {
101
+ const incidents = await loadIncidents();
102
+ const inc = incidents.find(i => i.id === id);
103
+ if (!inc)
104
+ return `error: incident ${id} not found`;
105
+ if (inc.state === "resolved")
106
+ return `error: incident ${id} already resolved`;
107
+ inc.state = "resolved";
108
+ inc.resolvedAt = new Date().toISOString();
109
+ inc.resolution = resolution;
110
+ if (resolvedBy)
111
+ inc.resolvedBy = resolvedBy;
112
+ await saveIncidents(incidents);
113
+ return `incident ${id} resolved`;
114
+ });
115
+ }
116
+ catch (e) {
117
+ if (e instanceof CronLockBusyError)
118
+ return `error: incident store busy — try again`;
119
+ throw e;
120
+ }
121
+ }
122
+ export async function listIncidents(filter) {
123
+ let incidents = await loadIncidents();
124
+ if (filter?.state)
125
+ incidents = incidents.filter(i => i.state === filter.state);
126
+ if (filter?.severity)
127
+ incidents = incidents.filter(i => i.severity === filter.severity);
128
+ return incidents;
129
+ }
130
+ export async function formatIncidents(filter) {
131
+ const incidents = await listIncidents(filter);
132
+ if (!incidents.length)
133
+ return "no incidents";
134
+ return incidents.map(i => `${i.id} [${i.severity}] ${i.state} — ${i.title}${i.jobId ? ` (job: ${i.jobId})` : ""}${i.resolvedAt ? ` resolved: ${i.resolvedAt}` : ""}`).join("\n");
135
+ }
@@ -19,6 +19,7 @@ import { runAcp } from "../acp/run.js";
19
19
  import { boardPath, addTask, readBoard } from "./board.js";
20
20
  import { routinesPath, readRoutines } from "./routines.js";
21
21
  import { readableRoutine, nextFire, runRoutine, launchdPlist, launchdLabel, crontabLine } from "./routine-run.js";
22
+ import { ensureServices } from "../services/preflight.js";
22
23
  const AUTONOMY_COMMANDS = new Set(["run", "loop", "board", "routine", "dream", "acp", "media-robot"]);
23
24
  /** Split argv (after the subcommand) into --bool flags, --key value pairs, and positionals. `--` ends
24
25
  * flag parsing so a task string starting with a dash is preserved. */
@@ -232,6 +233,27 @@ export async function dispatchAutonomy(argv, settings) {
232
233
  const cmd = argv[2];
233
234
  if (!cmd || !AUTONOMY_COMMANDS.has(cmd))
234
235
  return null;
236
+ // Headless paths skip the interactive preflight (cli.tsx's ensureServices), which both RESOLVES the
237
+ // dynamic Aurora endpoint from the operator-runtime server.json AND brings the launchd gateway UP if it
238
+ // is down. Mirror that FULL blueprint here — the same EnsureCfg (aurora launchd cfg + optional services) —
239
+ // so a headless `operator run/loop/board/routine` on a cold box self-heals instead of failing with a
240
+ // baseless "/v1/chat/completions" (Failed to parse URL) against the empty endpoints.aurora.base sentinel.
241
+ // Guarded to the empty-base case (the only time we must discover/start), and gateway-aware: carry the
242
+ // gateway's published api_key (server.json) onto the endpoint config so the router authenticates to it.
243
+ if (!settings.endpoints.aurora.base) {
244
+ const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
245
+ await ensureServices({
246
+ aurora: auroraCfg,
247
+ autopilot: settings.services?.autopilot,
248
+ vision: settings.services?.vision,
249
+ onProgress: (m) => process.stderr.write(`[services] ${m}\n`),
250
+ });
251
+ if (auroraCfg.base)
252
+ settings.endpoints.aurora.base = auroraCfg.base;
253
+ const apiKey = auroraCfg.apiKey;
254
+ if (apiKey && !settings.endpoints.aurora.apiKey)
255
+ settings.endpoints.aurora.apiKey = apiKey;
256
+ }
235
257
  const f = parseFlags(argv.slice(3), VALUED);
236
258
  if (cmd === "run" || cmd === "loop") {
237
259
  const prompt = f.positional.join(" ").trim();
@@ -1,4 +1,4 @@
1
- // Profile-bound headless sessions — the engine seam for Bot Mode (GW-OHV3-A / Hermes-parity gap #1).
1
+ // Profile-bound headless sessions — the engine seam for Bot Mode (GW-OHV3-A).
2
2
  // A "bot" the messaging gateway runs (one per Telegram/Discord/Slack identity) is nothing more than a
3
3
  // long-lived headless Session with its OWN model, persona, memory, and working dir — i.e. a $KODE_PROFILE.
4
4
  // This module turns a ProfileConfig into such a Session by DERIVING settings and composing the existing
@@ -5,47 +5,46 @@
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { Session } from "../session.js";
7
7
  import { AuroraRouter } from "../router/router.js";
8
+ import { buildMemory } from "../memory/providers.js";
8
9
  import { composeSystemPrompt } from "../config/persona.js";
9
- import { modelCtxFor, LEAN_HARNESS_CTX } from "../router/models.js";
10
- import { compactionThreshold, compactionCeilingTokens, turnWallClockMs } from "../config/settings.js";
11
- /** Build the Aurora router (primary + optional degraded failover) from settings — the headless twin of
12
- * cli.tsx's buildRouter(). */
10
+ import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.js";
11
+ import { compactionThreshold, compactionCeilingTokens, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
12
+ /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
13
+ * multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
14
+ * wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
13
15
  export function buildRouterFromSettings(settings) {
14
- const eps = [{
15
- name: "operator-1m",
16
- base: settings.endpoints.aurora.base,
17
- model: settings.endpoints.aurora.model,
18
- ctxLimit: settings.endpoints.aurora.ctxWindow,
19
- }];
20
- const fo = settings.endpoints.failover;
21
- if (fo)
22
- eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
23
- return new AuroraRouter(eps);
16
+ return new AuroraRouter(buildEndpointChain(settings));
24
17
  }
25
18
  /** The full headless system prompt: the SAME composeSystemPrompt the TUI calls (persona + project context +
26
19
  * memory + handoff + catalogue), non-interactive — minus the TUI-only Sub-agents + embodiment sections. */
27
20
  export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
28
21
  const ctxTokens = modelCtxFor(settings.activeModel, settings.models);
29
- const lean = ctxTokens < LEAN_HARNESS_CTX; // small-ctx model → drop heavy memory/handoff (persona kept → stays uncensored)
22
+ const lean = leanHarnessFor(settings.activeModel, settings.models); // small-ctx OR a weak big-ctx model (leanPersona) → trim persona + drop heavy memory/handoff
30
23
  return composeSystemPrompt({ settings, cwd, ctxTokens, lean, interactive: false });
31
24
  }
32
25
  /** Construct a headless Session from settings. Unattended runs get NO ask_user handler (there's no owner
33
26
  * to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
34
27
  * MCP tool set directly. Permissions default to the owner's configured policy. */
35
28
  export function createAutonomySession(settings, opts = {}) {
36
- return new Session({
29
+ const session = new Session({
37
30
  systemPrompt: buildHeadlessSystemPrompt(settings, opts.cwd),
38
31
  router: buildRouterFromSettings(settings),
32
+ memory: buildMemory(settings.memory), // headless sessions get the same provider-layer memory surface
39
33
  cwd: opts.cwd,
40
34
  mcp: settings.mcp,
41
35
  maxTokens: settings.maxTokens,
42
36
  maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling; default unset ⇒ unattended runs are uncapped (free reign)
43
37
  maxTurnWallClockMs: turnWallClockMs(settings), // per-turn TIME brake (default 15min) — stops the hour-long crawling turn; loop mode continues the objective next turn
38
+ loopGuard: settings.loopGuard, // tool-loop + repetition guard thresholds
39
+ hooks: settings.hooks, // lifecycle hooks (settings.hooks); inert unless tool hooks are configured
40
+ unattended: true, // no owner watching: the loop guard hard-stops by default (settings.loopGuard.hardStop overrides)
44
41
  maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a deep unattended build runs to completion before the wrap-up nudge; was never passed here, so headless runs fell back to the engine's 10-round floor and cut long missions short
45
42
  temperature: settings.temperature,
46
43
  recall: settings.memory.recall,
47
44
  models: settings.models,
48
45
  moa: settings.moa,
46
+ fastStart: settings.fastStart,
47
+ features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
49
48
  activeModel: settings.activeModel,
50
49
  permissions: opts.permissions ?? settings.permissions,
51
50
  // Audit attribution: without these every headless/cron/dream tool event carried session:"" and no seat.
@@ -57,6 +56,16 @@ export function createAutonomySession(settings, opts = {}) {
57
56
  sleepConsolidation: settings.autonomy?.sleepConsolidation, // headless autonomy ("operator run/loop/dream") consolidates on idle too (0.1.177)
58
57
  ...opts.extra,
59
58
  });
59
+ // Bind the router to the SELECTED model, exactly as the interactive /model path (cli.tsx) and delegate_task
60
+ // (delegate.ts) do. The constructor skips activeModel when a router is injected — "an injected router owns
61
+ // routing" (session.ts) — and this factory always injects the default Aurora chain, so without this a
62
+ // non-default activeModel (e.g. belmont) silently ran on Aurora headless/ACP. setModel points this.inner at
63
+ // the profile's OWN endpoints (and its own fleet failover), so a non-Aurora model no longer self-heals onto
64
+ // Aurora. The default model keeps the richer buildEndpointChain failover. An unavailable/refused id leaves
65
+ // the default router — a quiet fallback matching the constructor.
66
+ if (settings.activeModel && settings.activeModel !== DEFAULT_MODEL_ID)
67
+ session.setModel(settings.activeModel);
68
+ return session;
60
69
  }
61
70
  /** Dream mode's permission posture. "readonly"/"gated" ⇒ a gated policy with no approver, so safe/read
62
71
  * tools run but every mutating tool asks → denies (there's no owner to approve): read-mostly by