ai-agentmanager 1.71.0 → 1.72.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.
@@ -0,0 +1,155 @@
1
+ // Night watch: does merged work still hold on the latest main? An agent's proof (proof.js) shows
2
+ // its checks passed on its own branch. Later merges can break that without any one review seeing
3
+ // it. So, for work merged in the last days, the recorded commands are run again against the latest
4
+ // main, in a checkout of its own (the agent's folder is left alone), and each is compared with
5
+ // what was recorded. A proof that no longer holds names the commits since its merge that changed
6
+ // the same files: where to look first. Off until you turn it on (it runs agents' commands on this
7
+ // computer); run by hand any time. A command that changes things is never run (proof.js).
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import * as git from './git.js';
12
+ import { changesThings, compareRun, parseProof, proofPath } from './proof.js';
13
+
14
+ export const NIGHT_DEFAULTS = { enabled: false, hour: 3, days: 14, maxAgents: 12 };
15
+ const MAX_COMMANDS = 6;
16
+ // Installed dependencies are not part of git: the agent's own are lent to the checkout.
17
+ const DEPS = ['node_modules', '.venv', 'venv', 'vendor'];
18
+
19
+ export function nightSettings(config = {}) {
20
+ const n = config.nightWatch ?? {};
21
+ const num = (v, d, lo, hi) => (Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Number(v))) : d);
22
+ return { enabled: n.enabled === true, hour: num(n.hour, NIGHT_DEFAULTS.hour, 0, 23), days: num(n.days, NIGHT_DEFAULTS.days, 1, 90), maxAgents: num(n.maxAgents, NIGHT_DEFAULTS.maxAgents, 1, 50) };
23
+ }
24
+
25
+ /** Whether a scheduled run is due: on, at its hour or after, and not yet run today. */
26
+ export function due(settings, lastRunAt, t = new Date()) {
27
+ if (!settings.enabled || t.getHours() < settings.hour) return false;
28
+ const last = lastRunAt ? new Date(lastRunAt) : null;
29
+ return !last || last.toDateString() !== t.toDateString();
30
+ }
31
+
32
+ /** The merged work to watch: merged in the last `days`, its agent still known, newest first. */
33
+ export function watchList(items, { days, maxAgents }, t = Date.now()) {
34
+ return items
35
+ .filter((it) => it.agentId && it.facts?.mergeCommit && Date.parse(it.mergedAt) >= t - days * 86_400_000)
36
+ .sort((a, b) => b.mergedAt.localeCompare(a.mergedAt))
37
+ .slice(0, maxAgents);
38
+ }
39
+
40
+ /** One merged piece of work: { status: 'holds' | 'broken' | 'skipped', why?, results, suspects }. */
41
+ export function verdictOf(results) {
42
+ const ran = results.filter((r) => r.status !== 'skipped');
43
+ if (!ran.length) return 'skipped';
44
+ return ran.some((r) => r.status === 'differs') ? 'broken' : 'holds';
45
+ }
46
+
47
+ export class NightWatch {
48
+ constructor({ manager, store, quality, run, config = {}, log = () => {}, readProof = (id) => fs.readFileSync(proofPath(id), 'utf8') }) {
49
+ Object.assign(this, { manager, store, quality, run, config, log, readProof });
50
+ store.data.nightWatch ??= { lastRunAt: null, runs: {} };
51
+ this.state = store.data.nightWatch;
52
+ this.running = null;
53
+ }
54
+
55
+ get settings() {
56
+ return nightSettings(this.config);
57
+ }
58
+
59
+ view() {
60
+ const runs = Object.values(this.state.runs).sort((a, b) => b.mergedAt.localeCompare(a.mergedAt));
61
+ return { settings: this.settings, lastRunAt: this.state.lastRunAt, running: Boolean(this.running), runs, broken: runs.filter((r) => r.status === 'broken').length };
62
+ }
63
+
64
+ /** Called on a timer: runs when due. */
65
+ tick(t = new Date()) {
66
+ if (this.running || !due(this.settings, this.state.lastRunAt, t)) return null;
67
+ return this.runAll().catch((e) => this.log(`night watch: ${e.message}`));
68
+ }
69
+
70
+ /** Watch every piece of merged work in the list now. The person's call, or the schedule's. */
71
+ async runAll() {
72
+ if (this.running) return this.running;
73
+ this.running = (async () => {
74
+ const list = watchList(this.quality.view().items, this.settings);
75
+ for (const it of list) {
76
+ const r = await this.watch(it).catch((e) => ({ status: 'skipped', why: e.message, results: [], suspects: [] }));
77
+ this.state.runs[it.url] = { url: it.url, number: it.number ?? null, title: it.title ?? null, agentId: it.agentId, mergedAt: it.mergedAt, at: new Date().toISOString(), ...r };
78
+ const a = this.store.get(it.agentId);
79
+ if (a) this.manager.patch(a.id, { nightWatch: { at: new Date().toISOString(), status: r.status, mainSha: r.mainSha ?? null, broken: (r.results ?? []).filter((x) => x.status === 'differs').map((x) => x.title), suspects: (r.suspects ?? []).slice(0, 3), url: it.url } });
80
+ }
81
+ // Kept for the work still watched, and a little after (twice its days).
82
+ const keep = Date.now() - 2 * this.settings.days * 86_400_000;
83
+ for (const [url, r] of Object.entries(this.state.runs)) if (Date.parse(r.mergedAt) < keep) delete this.state.runs[url];
84
+ this.state.lastRunAt = new Date().toISOString();
85
+ this.store.save();
86
+ return this.view();
87
+ })().finally(() => (this.running = null));
88
+ return this.running;
89
+ }
90
+
91
+ /** One merged piece of work against the latest main. */
92
+ async watch(it) {
93
+ const agent = this.store.get(it.agentId);
94
+ let entries = [];
95
+ try {
96
+ entries = parseProof(this.readProof(it.agentId)).filter((e) => e.command);
97
+ } catch {}
98
+ if (!entries.length) return { status: 'skipped', why: 'It recorded no commands', results: [], suspects: [] };
99
+ const repoDir = agent?.sourceDir;
100
+ if (!repoDir || !(await git.isGitRepo(repoDir))) return { status: 'skipped', why: 'Its repository is not on this computer', results: [], suspects: [] };
101
+ await git.fetch(repoDir).catch(() => {});
102
+ const base = it.facts.base || 'main';
103
+ const ref = await git.run('git', ['rev-parse', '--verify', '--quiet', `origin/${base}`], { cwd: repoDir }).catch(() => git.run('git', ['rev-parse', '--verify', base], { cwd: repoDir }));
104
+ const dest = fs.mkdtempSync(path.join(os.tmpdir(), 'agentmgr-night-'));
105
+ try {
106
+ await git.run('git', ['worktree', 'add', '--detach', '--force', dest, ref], { cwd: repoDir, timeout: 5 * 60_000 });
107
+ for (const d of DEPS) {
108
+ const from = agent.workdir && path.join(agent.workdir, d);
109
+ if (from && fs.existsSync(from) && !fs.existsSync(path.join(dest, d))) fs.symlinkSync(from, path.join(dest, d));
110
+ }
111
+ const results = [];
112
+ let ran = 0;
113
+ for (const e of entries) {
114
+ const why = changesThings(e.command) ?? (ran >= MAX_COMMANDS ? `only the first ${MAX_COMMANDS} are run` : null);
115
+ if (why) {
116
+ results.push({ title: e.title, command: e.command, status: 'skipped', why });
117
+ continue;
118
+ }
119
+ ran++;
120
+ this.log(`night watch: ${it.title ?? it.url}: ${e.command}`);
121
+ const r = await this.run(e.command, { cwd: dest, timeoutMs: 180_000 });
122
+ results.push({ title: e.title, command: e.command, code: r.code, tail: String(r.tail ?? '').split('\n').slice(-8).join('\n').slice(-800), ...compareRun(e, r) });
123
+ }
124
+ const status = verdictOf(results);
125
+ // Where to look first: the commits since its merge that changed the files it changed.
126
+ let suspects = [];
127
+ if (status === 'broken') {
128
+ const files = (it.facts.files ?? []).slice(0, 100);
129
+ const out = await git.run('git', ['log', '--format=%h%x09%s%x09%cI', '-n', '8', `${it.facts.mergeCommit}..${ref}`, '--', ...files], { cwd: repoDir }).catch(() => '');
130
+ suspects = out.split('\n').filter(Boolean).map((l) => {
131
+ const [sha, subject, at] = l.split('\t');
132
+ return { sha, subject, at };
133
+ });
134
+ }
135
+ return { status, mainSha: ref.slice(0, 9), results, suspects };
136
+ } finally {
137
+ await git.run('git', ['worktree', 'remove', '--force', dest], { cwd: repoDir }).catch(async () => {
138
+ fs.rmSync(dest, { recursive: true, force: true });
139
+ await git.run('git', ['worktree', 'prune'], { cwd: repoDir }).catch(() => {});
140
+ });
141
+ }
142
+ }
143
+ }
144
+
145
+ export function nightMarkdown(v) {
146
+ const out = ['# Night watch', '', v.lastRunAt ? `Last run ${v.lastRunAt}. ${v.broken} of ${v.runs.length} no longer hold on main.` : 'Not run yet.', ''];
147
+ for (const r of v.runs) {
148
+ out.push(`## ${r.status === 'broken' ? 'No longer holds' : r.status === 'holds' ? 'Holds' : 'Not checked'}: ${r.number ? `#${r.number} ` : ''}${r.title ?? r.url}`, '');
149
+ if (r.why) out.push(r.why, '');
150
+ for (const x of r.results ?? []) out.push(`- ${x.status === 'differs' ? 'Differs' : x.status === 'same' ? 'Same' : 'Skipped'}: ${x.title} \`${x.command}\`${x.status === 'differs' ? ` (exit ${x.code})` : ''}`);
151
+ if (r.suspects?.length) out.push('', 'Changed the same files since it merged:', ...r.suspects.map((s) => `- ${s.sha} ${s.subject}`));
152
+ out.push('');
153
+ }
154
+ return out.join('\n').trimEnd();
155
+ }
package/src/races.js CHANGED
@@ -68,6 +68,60 @@ export class Races extends EventEmitter {
68
68
  return this.view(id);
69
69
  }
70
70
 
71
+ /**
72
+ * Try the other path: an agent wrote down the ways it weighed (## Options, its preferred one
73
+ * first, the one it takes). Path `n` is started as a second agent from the same base commit,
74
+ * told to take that path, and the two are raced: the scoreboard, a test command run in both,
75
+ * and picking the one to keep. A path already being tried is not started twice.
76
+ */
77
+ tryPath(agentId, n) {
78
+ const src = this.manager.mustGet(agentId);
79
+ const paths = src.brief?.options?.paths ?? [];
80
+ n = Number(n);
81
+ if (!paths.length) throw err(409, 'It has not written the paths it weighed (## Options in its brief)');
82
+ if (!Number.isInteger(n) || n < 2 || n > paths.length) throw err(400, `Pick a path from 2 to ${paths.length}: path 1 is the one it takes`);
83
+ if (src.kind !== 'task' || src.team) throw err(409, 'Only a task agent of its own can try another path');
84
+ // In a race: only the one its own Try this path started (not a race of variants, nor one where it is the other path).
85
+ if (src.raceId && this.store.data.races[src.raceId] && this.store.data.races[src.raceId].tryOf !== src.id) throw err(409, 'It is already in a race');
86
+ const repoDir = src.sourceDir ?? src.workdir;
87
+ if (!src.repo && !repoDir) throw err(409, 'It has no repository to start another agent in');
88
+ const label = `path-${n}`;
89
+ let race = src.raceId ? this.store.data.races[src.raceId] : null;
90
+ if (race && race.members.some((m) => this.manager.get(m)?.variant?.label === label)) throw err(409, `Path ${n} is already being tried`);
91
+ const p = paths[n - 1];
92
+ const first = paths[0];
93
+ const say = (x) => `"${x.name}"${x.what ? ` (${x.what})` : ''}`;
94
+ const raceId = race?.id ?? `r${crypto.randomBytes(3).toString('hex')}`;
95
+ const instructions = `Take path ${n}, ${say(p)}. Another agent is taking path 1, ${say(first)}: do not take that one. In ## Options, put the path you take first.`;
96
+ const a = this.manager.create({
97
+ intent: `${src.intent}\n\nApproach for this attempt: ${instructions}`,
98
+ name: `${src.name}-path${n}`,
99
+ ...(src.repo ? { repo: src.repo } : { dir: repoDir }),
100
+ worktree: true,
101
+ // The commit the first agent started from (its branch would carry its own path).
102
+ base: src.baseRef?.split(' @ ')[1] ?? undefined,
103
+ permissionMode: src.permissionMode ?? undefined,
104
+ model: src.model ?? undefined,
105
+ engine: src.engine ?? undefined,
106
+ project: src.project ?? undefined,
107
+ priority: src.priority,
108
+ autonomy: src.autonomy?.level ?? undefined,
109
+ designDoc: src.designDoc ?? undefined,
110
+ // (It starts at once: what done means was agreed for the task with the first agent.)
111
+ acceptance: false,
112
+ race: { id: raceId, variant: { label, model: src.model ?? null, instructions: `Path ${n}: ${p.name}` } },
113
+ });
114
+ // The race is made once the agent is: a refused one leaves none behind.
115
+ if (!race) {
116
+ race = { id: raceId, intent: src.intent, testCommand: null, createdAt: now(), members: [src.id], tests: {}, winner: null, tryOf: src.id };
117
+ this.store.data.races[raceId] = race;
118
+ this.manager.patch(src.id, { raceId, variant: { label: 'path-1', model: src.model ?? null, instructions: `Path 1: ${first.name}` } });
119
+ }
120
+ race.members.push(a.id);
121
+ this.save(race);
122
+ return this.view(race.id);
123
+ }
124
+
71
125
  get(id) {
72
126
  const race = this.store.data.races[id];
73
127
  if (!race) throw err(404, `No race ${id}`);
package/src/server.js CHANGED
@@ -60,6 +60,10 @@ import { Quality } from './quality.js';
60
60
  import { recordMarkdown } from './record.js';
61
61
  import { Weekly } from './weekly.js';
62
62
  import { queueMarkdown, readQueue } from './readfirst.js';
63
+ import { blameMarkdown } from './blame.js';
64
+ import { Echo } from './echo.js';
65
+ import { calibration, calibrationLines, calibrationMarkdown, cleanGuess } from './calibration.js';
66
+ import { NightWatch, nightMarkdown, nightSettings } from './nightwatch.js';
63
67
  import { glance, glanceLine, glanceMarkdown } from '../public/glance.js';
64
68
  import { traceMarkdown, traceOf } from './trace.js';
65
69
  import { PRIVATE_MESSAGE, keptPrivate, mustBeShareable } from './private.js';
@@ -359,6 +363,16 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
359
363
  const quality = new Quality({ manager, store, config, who: me, onChange: () => pushQuality() });
360
364
  // Standards per repository: lessons from what went wrong, high-risk paths, and the quality bar (standards.js).
361
365
  const standards = new Standards({ manager, store, config, quality, onChange: () => pushQuality() });
366
+ // Night watch: merged work's recorded commands run again against the latest main (nightwatch.js). Off until turned on.
367
+ const nightWatch = new NightWatch({ manager, store, quality, run: runCheck, config, log: (m) => console.log(`[agentmgr] ${m}`) });
368
+ setInterval(() => nightWatch.tick(), 10 * 60_000).unref();
369
+ // Bug echo: a lesson accepted, the agents at work in that repository checked for the same mistake (echo.js).
370
+ const echo = new Echo({ manager, standards, review, log: (m) => console.log(`[agentmgr] ${m}`) });
371
+ const echoLesson = (key, lesson) => {
372
+ if (config.echo?.enabled === false || config.standards?.enabled === false || lesson?.state !== 'accepted') return lesson;
373
+ echo.run(key, lesson).catch((e) => console.log(`[agentmgr] bug echo: ${e.message}`));
374
+ return lesson;
375
+ };
362
376
  // A week's work and achievements on one page, for management (weekly.js); written as a draft file when the week is over.
363
377
  const weekly = new Weekly({ manager, store, worklog, value, quality, who: me, config });
364
378
  // AI News: the frontier labs' latest releases, summarized (news.js).
@@ -625,7 +639,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
625
639
  // Agents the assistant's own session starts: its limits apply, and they are marked as its.
626
640
  const extra = assistant.admit(req.headers['x-agentmgr-agent'], list, opts);
627
641
  if (extra.startedBy) proposed.refuseSetAside(list);
628
- const created = manager.createMany(list, { ...opts, ...extra });
642
+ // Your guess (calibration.js): yours only, so not on the ones the assistant starts. Checked first.
643
+ const guess = extra.startedBy ? null : cleanGuess(opts.guess);
644
+ let created = manager.createMany(list, { ...opts, ...extra });
645
+ if (guess) {
646
+ for (const a of created) manager.patch(a.id, { guess });
647
+ created = created.map((a) => manager.view(store.get(a.id) ?? a));
648
+ }
629
649
  if (!extra.startedBy) repeats.record(created.map((a) => ({ text: a.intent, projectKey: projectOf(store.get(a.id) ?? a).key })));
630
650
  if (extra.startedBy) {
631
651
  for (const a of created) notifier.send('assistant', a, `was started by the assistant: ${a.intent.replace(/\s+/g, ' ').slice(0, 160)}`);
@@ -1101,6 +1121,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1101
1121
  // Attachments: copied once to a shared folder and listed in the request every attempt gets.
1102
1122
  const withFiles = ({ attachments, ...body } = {}) => ({ ...body, intent: manager.withSharedAttachments(body.intent, attachments) });
1103
1123
  api.post('/races', wrap((req) => races.create(withFiles(req.body ?? {}))));
1124
+ // Try the other path: the path it weighed and did not take, raced against the one it took (races.js).
1125
+ api.post('/agents/:id/try-path', wrap((req) => {
1126
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Another path is tried when the person asks, not an agent');
1127
+ return races.tryPath(req.params.id, req.body?.path);
1128
+ }));
1104
1129
  api.get('/races/:id', wrap((req) => races.view(req.params.id)));
1105
1130
  api.post('/races/:id/tests', wrap((req) => races.runTests(req.params.id, req.body ?? {})));
1106
1131
  api.get('/races/:id/diff/:agent', wrap((req) => races.diff(req.params.id, req.params.agent)));
@@ -1281,6 +1306,34 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1281
1306
  const g = glance(store.list().map((a) => manager.view(a)));
1282
1307
  return { ...g, line: glanceLine(g), markdown: glanceMarkdown(g, { all: req.query.all === '1' }) };
1283
1308
  }));
1309
+ // Scope fence: allow an area it changes outside its task, or pull it back (fence.js).
1310
+ api.post('/agents/:id/fence', wrap((req) => {
1311
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'What is in scope is said by the person, not by an agent');
1312
+ return manager.setFence(req.params.id, req.body ?? {});
1313
+ }));
1314
+ // Your calibration: your guesses at the start against what happened (calibration.js).
1315
+ // The Read first level is gone once the work is reviewed: it is kept with the guess first.
1316
+ const keepActual = (v) => {
1317
+ if (v?.guess && v.readFirst && v.guess.actual?.review !== v.readFirst.level) manager.patch(v.id, { guess: { ...v.guess, actual: { review: v.readFirst.level } } });
1318
+ };
1319
+ api.put('/agents/:id/guess', wrap((req) => {
1320
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'A guess is yours, not an agent\'s');
1321
+ const a = manager.mustGet(req.params.id);
1322
+ const guess = cleanGuess(req.body ?? {});
1323
+ manager.patch(a.id, { guess: guess ? { ...guess, ...(a.guess?.actual ? { actual: a.guess.actual } : {}) } : null });
1324
+ return manager.view(manager.get(a.id));
1325
+ }));
1326
+ api.get('/calibration', wrap((req) => {
1327
+ const views = store.list().map((a) => manager.view(a));
1328
+ for (const v of views) keepActual(v);
1329
+ const c = calibration(store.list().map((a) => manager.view(a)));
1330
+ return { ...c, lines: calibrationLines(c), ...(req.query.format === 'md' ? { markdown: calibrationMarkdown(c) } : {}) };
1331
+ }));
1332
+ // Why is this line here: the moment in the agent's conversation that wrote it (blame.js).
1333
+ api.get('/agents/:id/why', wrap((req) => {
1334
+ const b = manager.whyLine(req.params.id, { file: req.query.file, line: req.query.line, text: req.query.text });
1335
+ return req.query.format === 'md' ? { ...b, markdown: blameMarkdown(b, { file: b.file, lineNo: b.line, line: b.text }) } : b;
1336
+ }));
1284
1337
  api.get('/read-first', wrap((req) => {
1285
1338
  const items = readQueue(store.list(), (a) => manager.view(a));
1286
1339
  return req.query.format === 'md' ? { markdown: queueMarkdown(items) } : { items };
@@ -1294,7 +1347,10 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1294
1347
  if (b.agent) ids = [manager.mustGet(b.agent).id];
1295
1348
  else if (Number(b.olderThanDays) > 0) ids = readQueue(store.list(), (a) => manager.view(a)).filter((i) => Date.parse(i.finishedAt) < Date.now() - Number(b.olderThanDays) * 86_400_000).map((i) => i.agentId);
1296
1349
  else throw fail(400, 'Give agent, or olderThanDays');
1297
- for (const id of ids) manager.patch(id, { reviewed: b.reviewed === false ? null : { at } });
1350
+ for (const id of ids) {
1351
+ keepActual(manager.view(manager.get(id)));
1352
+ manager.patch(id, { reviewed: b.reviewed === false ? null : { at } });
1353
+ }
1298
1354
  return { marked: ids.length, items: readQueue(store.list(), (a) => manager.view(a)) };
1299
1355
  }));
1300
1356
  // Weekly summary (weekly.js): a week's work and achievements on one page, for management. A draft: nothing is sent.
@@ -1442,8 +1498,48 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1442
1498
  };
1443
1499
  api.get('/standards', wrap(() => standards.view()));
1444
1500
  api.put('/standards/repo', wrap((req) => standards.update(standards.find(String(yours(req).key ?? '')), { risk: req.body.risk, bar: req.body.bar })));
1445
- api.post('/standards/lessons', wrap((req) => standards.addLesson(standards.find(String(yours(req).key ?? '')), req.body.text)));
1446
- api.put('/standards/lessons/:id', wrap((req) => standards.setLesson(standards.find(String(yours(req).key ?? '')), req.params.id, { state: req.body.state, text: req.body.text })));
1501
+ api.post('/standards/lessons', wrap((req) => {
1502
+ const key = standards.find(String(yours(req).key ?? ''));
1503
+ return echoLesson(key, standards.addLesson(key, req.body.text));
1504
+ }));
1505
+ api.put('/standards/lessons/:id', wrap((req) => {
1506
+ const key = standards.find(String(yours(req).key ?? ''));
1507
+ const was = standards.lesson(key, req.params.id).state;
1508
+ const l = standards.setLesson(key, req.params.id, { state: req.body.state, text: req.body.text });
1509
+ return was === 'accepted' && req.body.text === undefined ? l : echoLesson(key, l);
1510
+ }));
1511
+ // Check the agents at work against an accepted lesson again (bug echo), or act on one flagged.
1512
+ api.post('/standards/lessons/:id/echo', wrap(async (req) => {
1513
+ const key = standards.find(String(yours(req).key ?? ''));
1514
+ const l = standards.lesson(key, req.params.id);
1515
+ if (l.state !== 'accepted') throw fail(409, 'Only an accepted lesson is checked against the agents at work');
1516
+ return { checked: await echo.run(key, l) };
1517
+ }));
1518
+ api.get('/night-watch', wrap((req) => {
1519
+ const v = nightWatch.view();
1520
+ return req.query.format === 'md' ? { ...v, markdown: nightMarkdown(v) } : v;
1521
+ }));
1522
+ api.post('/night-watch/run', wrap(async (req) => {
1523
+ if (req.headers['x-agentmgr-agent']) throw fail(403, "Night watch runs agents' commands: the person starts it, not an agent");
1524
+ const p = nightWatch.runAll();
1525
+ if (req.body?.wait !== false) return p;
1526
+ p.catch((e) => console.log(`[agentmgr] night watch: ${e.message}`));
1527
+ return nightWatch.view();
1528
+ }));
1529
+ api.put('/night-watch', wrap((req) => {
1530
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'Night watch is set by the person, not by an agent');
1531
+ const b = req.body ?? {};
1532
+ const next = { ...config.nightWatch };
1533
+ if (typeof b.enabled === 'boolean') next.enabled = b.enabled;
1534
+ for (const k of ['hour', 'days']) if (b[k] !== undefined) next[k] = Number(b[k]);
1535
+ config.nightWatch = nightSettings({ nightWatch: next });
1536
+ saveConfig({ nightWatch: config.nightWatch });
1537
+ return nightWatch.view();
1538
+ }));
1539
+ api.post('/agents/:id/echo', wrap((req) => {
1540
+ if (req.headers['x-agentmgr-agent']) throw fail(403, 'The person acts on a flagged mistake, not an agent');
1541
+ return echo.act(req.params.id, String(req.body?.lesson ?? ''), req.body?.act);
1542
+ }));
1447
1543
  api.delete('/standards/lessons/:id', wrap((req) => (yours(req), standards.removeLesson(standards.find(String(req.query.key ?? '')), req.params.id))));
1448
1544
  api.post('/standards/lessons/:id/draft', wrap((req) => standards.draft(standards.find(String(yours(req).key ?? '')), req.params.id)));
1449
1545
  api.get('/agents/:id/standards', wrap((req) => standards.assess(req.params.id)));
@@ -1912,6 +2008,16 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1912
2008
  return { ok: true };
1913
2009
  }),
1914
2010
  );
2011
+ // The box under the terminal: text typed and submitted by the daemon (manager.typeIn).
2012
+ api.post(
2013
+ '/agents/:id/term/send',
2014
+ wrap((req) => {
2015
+ const agent = termAgent(req.params.id);
2016
+ if (typeof req.body?.text !== 'string') throw fail(400, 'text (string) is required');
2017
+ manager.typeIn(agent.id, req.body.text, termKind(req.body.kind));
2018
+ return { ok: true };
2019
+ }),
2020
+ );
1915
2021
  api.post(
1916
2022
  '/agents/:id/term/resize',
1917
2023
  wrap((req) => {