@0perator/operator 0.1.284 → 0.1.313

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 (99) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +3 -2
  3. package/dist/acp/config-options.js +15 -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 +304 -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 +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/moa.js +5 -1
  34. package/dist/engine/net-error.js +24 -0
  35. package/dist/engine/repetition-guard.js +180 -0
  36. package/dist/engine/selfheal.js +8 -0
  37. package/dist/engine/toolcalls.js +51 -1
  38. package/dist/engine/verify-gate.js +2 -0
  39. package/dist/flywheel/processor.js +78 -31
  40. package/dist/flywheel/srft.js +13 -0
  41. package/dist/hooks/index.js +196 -0
  42. package/dist/mcp/config.js +21 -1
  43. package/dist/memory/index.js +0 -0
  44. package/dist/memory/providers.js +210 -0
  45. package/dist/memory/session-catalog.js +422 -0
  46. package/dist/memory/session-providers.js +121 -0
  47. package/dist/memory/session-sources.js +335 -0
  48. package/dist/memory/skylark.js +131 -0
  49. package/dist/models/bench.js +103 -0
  50. package/dist/models/registry.js +144 -0
  51. package/dist/models/switch.js +69 -0
  52. package/dist/observability/blackbox.js +37 -0
  53. package/dist/permissions/policy.js +31 -6
  54. package/dist/router/discovery.js +127 -0
  55. package/dist/router/models.js +117 -24
  56. package/dist/router/portal.js +100 -0
  57. package/dist/router/router.js +1 -1
  58. package/dist/services/preflight.js +55 -7
  59. package/dist/session.js +316 -46
  60. package/dist/tools/chauffeur.js +12 -0
  61. package/dist/tools/executor.js +19 -9
  62. package/dist/tools/find-files.js +483 -0
  63. package/dist/tools/git-pr.js +94 -0
  64. package/dist/tools/incident-tools.js +82 -0
  65. package/dist/tools/memory.js +12 -2
  66. package/dist/tools/registry.js +281 -85
  67. package/dist/tools/semantic-compress.js +124 -0
  68. package/dist/tools/shell-context.js +1 -0
  69. package/dist/tools/shell-jobs.js +160 -0
  70. package/dist/tools/shell-session.js +170 -4
  71. package/dist/tools/wave-tools.js +609 -0
  72. package/dist/tools/wave2-tools.js +411 -0
  73. package/dist/ui/App.js +15 -4
  74. package/dist/ui/BgPanel.js +30 -6
  75. package/dist/ui/Composer.js +11 -1
  76. package/dist/ui/QuestionPrompt.js +31 -11
  77. package/dist/ui/SessionPicker.js +86 -0
  78. package/dist/ui/StatusRule.js +5 -5
  79. package/dist/ui/ToolStep.js +2 -1
  80. package/dist/ui/Transcript.js +17 -1
  81. package/dist/ui/index.js +1 -1
  82. package/dist/ui/liveTools.js +21 -3
  83. package/dist/ui/slashCommands.js +2 -0
  84. package/dist/util/screenshots.js +74 -8
  85. package/dist/util/slash.js +2 -2
  86. package/package.json +8 -2
  87. package/dist/engine/cli.js +0 -1171
  88. package/dist/router/models.js.bak +0 -78
  89. package/dist/router/models.js.bak-1791259923 +0 -78
  90. package/dist/router/models.js.bak-pre-gateway +0 -78
  91. package/dist/router/models.js.bak-pre-patch2 +0 -78
  92. package/dist/router/models.js.bak2 +0 -78
  93. package/dist/services/model-autodetect.js +0 -240
  94. package/dist/tools/native-redirect.js +0 -140
  95. package/dist/tools/power-tools.js +0 -627
  96. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  97. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  98. package/dist/ui/BusTray.js +0 -70
  99. package/dist/ui/resize.js +0 -160
@@ -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();
@@ -108,7 +108,11 @@ export async function runDelegateTask(args, deps = defaultDeps) {
108
108
  return "error: delegate_task needs a non-empty `task` — a self-contained subtask; the sub-agent sees nothing else";
109
109
  const modelId = String(args.model ?? "").trim() || DEFAULT_DELEGATE_MODEL;
110
110
  const settings = await deps.loadSettings();
111
- const { profile, error } = selectModel(modelRegistry(settings.models), modelId);
111
+ // Gate BYO providers (Claude/OpenAI/Gemini/Qwen/…) on the user actually having stored that provider's key,
112
+ // the same check /model applies — so an unconnected provider fails fast with the actionable "store the key"
113
+ // error BEFORE a sub-agent session is spun up (and before setModel would refuse it anyway, more expensively).
114
+ const hasByo = deps.hasByo ?? (await nodeImport("../auth/byo.js")).hasByoToken;
115
+ const { profile, error } = selectModel(modelRegistry(settings.models), modelId, hasByo);
112
116
  if (error || !profile)
113
117
  return `error: delegate_task: ${error ?? `unknown model "${modelId}"`}`;
114
118
  if (profile.kind !== "single") {
@@ -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
+ }
@@ -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
@@ -23,6 +23,33 @@ function summarizeTask(task) {
23
23
  s = s.charAt(0).toUpperCase() + s.slice(1);
24
24
  return s.length > 56 ? s.slice(0, 55) + "…" : (s || task.replace(/\s+/g, " ").slice(0, 56));
25
25
  }
26
+ const PROGRESS_MAX = 80; // chars of the derived mission line kept for the panel
27
+ // Turn a chunk of the child's live reasoning into a one-line "what I'm doing now" mission phrase: the LAST
28
+ // sentence-like clause is its most recent intent. Pure + exported so the derivation is unit-testable without a
29
+ // running sub-agent. Returns undefined when there's nothing meaningful yet, so the caller keeps the prior line.
30
+ export function progressFromReasoning(reasoning) {
31
+ if (!reasoning)
32
+ return undefined;
33
+ const t = reasoning.replace(/^…\s*/, "").replace(/\s+/g, " ").trim();
34
+ if (!t)
35
+ return undefined;
36
+ const clauses = t.split(/(?<=[.!?。!?])\s+/).map((s) => s.trim()).filter(Boolean);
37
+ const last = (clauses.length ? clauses[clauses.length - 1] : t).replace(/^[-*•\d.)\s]+/, "").trim();
38
+ if (!last)
39
+ return undefined;
40
+ return last.length > PROGRESS_MAX ? last.slice(0, PROGRESS_MAX - 1) + "…" : last;
41
+ }
42
+ const OUTPUT_TAIL_MAX = 72; // chars of the latest tool result surfaced in the panel
43
+ // The last non-blank line of a tool result, whitespace-collapsed and capped — a glanceable "what came back"
44
+ // without dumping a multi-KB payload into the live frame. Pure + exported for testing.
45
+ export function outputTail(result) {
46
+ const lines = result.split("\n").map((l) => l.trim()).filter(Boolean);
47
+ const last = lines.length ? lines[lines.length - 1] : "";
48
+ if (!last)
49
+ return undefined;
50
+ const one = last.replace(/\s+/g, " ");
51
+ return one.length > OUTPUT_TAIL_MAX ? one.slice(0, OUTPUT_TAIL_MAX - 1) + "…" : one;
52
+ }
26
53
  export class BackgroundAgents {
27
54
  makeSession;
28
55
  onChange;
@@ -237,6 +264,11 @@ export class BackgroundAgents {
237
264
  onReasoning: (chunk) => {
238
265
  const t = ((info.thought ?? "") + chunk).replace(/\s+/g, " ");
239
266
  info.thought = t.length > THOUGHT_MAX ? "…" + t.slice(-(THOUGHT_MAX - 1)) : t;
267
+ // Continually-updating mission line ("what I'm doing now") — persists across tool batches (unlike
268
+ // thought, cleared below) so the owner always sees the current objective, not just the raw tool.
269
+ const p = progressFromReasoning(info.thought);
270
+ if (p)
271
+ info.progress = p;
240
272
  const now = Date.now();
241
273
  if (now - lastThoughtEmit > THOUGHT_EMIT_MS) {
242
274
  lastThoughtEmit = now;
@@ -255,6 +287,10 @@ export class BackgroundAgents {
255
287
  info.round = (info.round ?? 0) + 1;
256
288
  const settled = events.map((e) => ({ name: e.name, arg: shortArg(e.args), running: false }));
257
289
  info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
290
+ // Keep a short tail of the latest tool's output so the owner sees the work's EFFECT, not just its name
291
+ // — the "I have no visibility on what anyone is doing" gap. Skipped for an empty/errored result.
292
+ const lastOut = events.length ? String(events[events.length - 1].result ?? "").trim() : "";
293
+ info.lastOutput = lastOut ? outputTail(lastOut) : undefined;
258
294
  info.thought = undefined;
259
295
  this.touchProgress(id); // a completed round is unambiguous progress — reset the stall clock
260
296
  this.onChange();
@@ -311,6 +347,8 @@ export class BackgroundAgents {
311
347
  info.tokens = total; // authoritative llama.cpp count summed across sends
312
348
  info.durationMs = r.durationMs ?? (Date.now() - (info.startedAt ?? Date.now()));
313
349
  info.thought = undefined; // no live thinking once finished
350
+ info.progress = undefined;
351
+ info.lastOutput = undefined; // live mission/output lines belong to a WORKING agent
314
352
  if (info.steps)
315
353
  info.steps = info.steps.map((s) => ({ ...s, running: false }));
316
354
  this.clearStallTimer(id);
@@ -338,6 +376,8 @@ export class BackgroundAgents {
338
376
  catch (e) {
339
377
  info.status = "stopped";
340
378
  info.thought = undefined;
379
+ info.progress = undefined;
380
+ info.lastOutput = undefined;
341
381
  if (info.steps)
342
382
  info.steps = info.steps.map((s) => ({ ...s, running: false }));
343
383
  this.clearStallTimer(id);
package/dist/bus/inbox.js CHANGED
@@ -58,6 +58,26 @@ export function pollBus(agent = selfAgent(), opts = {}) {
58
58
  }
59
59
  return out;
60
60
  }
61
+ /** Build the wake-prompt text for an idle autonomous session from a batch of incoming bus messages, applying an
62
+ * optional sender allowlist. Returns null when nothing should wake a turn (empty batch, or none match the
63
+ * allowlist). PURE + tested — the cli.tsx poller calls this, then routes the text to the submit/queue path.
64
+ * Contract: a rendered bus message is only displayed; THIS is what puts a peer message into the model's context
65
+ * as an actionable turn. `allow` unset/empty = any sender wakes; otherwise only senders in the list. */
66
+ export function buildMentorWake(incoming, allow) {
67
+ const toWake = allow && allow.length ? incoming.filter((m) => allow.includes(m.from)) : incoming;
68
+ if (!toWake.length)
69
+ return null;
70
+ return (`[mentor-wake] ${toWake.length} new bus message(s) arrived — review and act on them now:\n\n` +
71
+ toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n"));
72
+ }
73
+ /** Per-source cooldown selection for wake-on-mentor (ping-pong guard). From a buffer of pending wake messages,
74
+ * return the subset whose source last woke the session at least `cooldownMs` ago — a source's FIRST message is
75
+ * always ready (no prior stamp). The caller stamps `lastBySource` for each returned source and drops them from
76
+ * the buffer; messages NOT returned stay buffered and coalesce into the next wake after the window, so a source
77
+ * firing rapidly can't drive back-to-back turns and nothing is lost. Pure + tested. */
78
+ export function selectReadyWakes(buffer, lastBySource, now, cooldownMs) {
79
+ return buffer.filter((m) => now - (lastBySource.get(m.from) ?? 0) >= cooldownMs);
80
+ }
61
81
  /** Read the archive of messages `agent` SENT — the switchboard CLI/lib mirrors a copy into sent/ on every
62
82
  * send so this session can surface its OWN outbound traffic ("you sent X to Y") inline, the counterpart to
63
83
  * pollBus. Same oldest-first, consume-once (move to sent-read/), corrupt-skip discipline. [] when no bus. */