ai-agentmanager 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +767 -2
  4. package/SECURITY.md +44 -0
  5. package/bin/agentmgr-hub.js +16 -0
  6. package/bin/agentmgr.js +4 -0
  7. package/docs/architecture.md +67 -0
  8. package/docs/distributed.md +147 -0
  9. package/docs/engines.md +177 -0
  10. package/docs/images/agents.jpg +0 -0
  11. package/docs/images/conflict-radar.jpg +0 -0
  12. package/docs/plugins.md +81 -0
  13. package/package.json +56 -4
  14. package/public/app.js +3083 -0
  15. package/public/hub/hub.css +230 -0
  16. package/public/hub/hub.js +766 -0
  17. package/public/hub/index.html +146 -0
  18. package/public/hub/term.js +147 -0
  19. package/public/index.html +342 -0
  20. package/public/share.html +34 -0
  21. package/public/share.js +41 -0
  22. package/public/style.css +541 -0
  23. package/public/touchscroll.js +73 -0
  24. package/public/transport.js +78 -0
  25. package/scripts/build-release.sh +58 -0
  26. package/scripts/fix-pty.js +15 -0
  27. package/src/backlog.js +413 -0
  28. package/src/brief.js +512 -0
  29. package/src/cli.js +1447 -0
  30. package/src/client.js +49 -0
  31. package/src/config.js +109 -0
  32. package/src/conflicts.js +105 -0
  33. package/src/engines/antigravity.js +296 -0
  34. package/src/engines/claude.js +98 -0
  35. package/src/engines/codex.js +331 -0
  36. package/src/engines/index.js +37 -0
  37. package/src/fleet.js +176 -0
  38. package/src/git.js +340 -0
  39. package/src/hub.js +857 -0
  40. package/src/hubactions.js +107 -0
  41. package/src/hubbacklog.js +373 -0
  42. package/src/hublink.js +437 -0
  43. package/src/inbox.js +94 -0
  44. package/src/judge.js +278 -0
  45. package/src/livebrowser.js +637 -0
  46. package/src/manager.js +2554 -0
  47. package/src/notify.js +284 -0
  48. package/src/plugins.js +119 -0
  49. package/src/preview.js +334 -0
  50. package/src/races.js +192 -0
  51. package/src/remote.js +284 -0
  52. package/src/server.js +759 -0
  53. package/src/service.js +150 -0
  54. package/src/sessions.js +160 -0
  55. package/src/store.js +104 -0
  56. package/src/stuck.js +160 -0
  57. package/src/tracker.js +311 -0
  58. package/src/trust.js +44 -0
package/src/hublink.js ADDED
@@ -0,0 +1,437 @@
1
+ // This machine's link to a hub (see hub.js). The daemon connects out, proves who it is
2
+ // with the key it made when it joined, and pushes a whitelisted view of its agents and
3
+ // inbox whenever they change. What the hub may see or do is decided here, by the "hub"
4
+ // section of config.json, never by the hub (see hubactions.js for the permissions).
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import WebSocket from 'ws';
10
+ import { paths } from './config.js';
11
+ import { challengePayload, checkHubUrl, fleetState, isTailscaleHost, projectRef, PROTOCOL } from './fleet.js';
12
+ import { ENGINES, installed } from './engines/index.js';
13
+ import { agentFor, runAction, terminalPermission } from './hubactions.js';
14
+
15
+ const LINK = () => path.join(paths.home, 'hub-link.json');
16
+ const AUDIT = () => path.join(paths.home, 'hub-audit.log');
17
+ const SEND_EVERY_MS = 2_000;
18
+ const PING_EVERY_MS = 15_000;
19
+ const MAX_CHANNELS = 16;
20
+ const MAX_RPCS = 8;
21
+ const BACKLOG_BYTES = 256 * 1024; // history sent when a hub terminal opens
22
+ // Flow control: a hub that can't keep up loses output, then gets a fresh screen once it drains.
23
+ const LAG_HIGH = 2 * 1024 * 1024;
24
+ const LAG_LOW = 256 * 1024;
25
+ export const DEFAULT_HUB_POLICY = { allow: ['view'], projects: ['*'] };
26
+
27
+ const now = () => new Date().toISOString();
28
+ const err = (status, message) => Object.assign(new Error(message), { status });
29
+
30
+ function readLink() {
31
+ try {
32
+ return JSON.parse(fs.readFileSync(LINK(), 'utf8'));
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function writeLink(link) {
39
+ const tmp = `${LINK()}.${process.pid}.tmp`;
40
+ fs.writeFileSync(tmp, JSON.stringify(link, null, 2), { mode: 0o600 });
41
+ fs.renameSync(tmp, LINK());
42
+ }
43
+
44
+ export function audit(line) {
45
+ try {
46
+ fs.appendFileSync(AUDIT(), `${now()} ${line}\n`, { mode: 0o600 });
47
+ } catch {}
48
+ }
49
+
50
+ export function hubPolicy(config) {
51
+ const h = config.hub ?? {};
52
+ return {
53
+ allow: Array.isArray(h.allow) ? h.allow.map(String) : DEFAULT_HUB_POLICY.allow,
54
+ projects: Array.isArray(h.projects) && h.projects.length ? h.projects.map(String) : DEFAULT_HUB_POLICY.projects,
55
+ };
56
+ }
57
+
58
+ export class HubLink {
59
+ /** urls(): this machine's UI addresses for "Open on <machine>" links (remote access). */
60
+ constructor({ manager, config, version, urls = () => [], backlog = null }) {
61
+ this.manager = manager;
62
+ this.backlog = backlog;
63
+ this.config = config;
64
+ this.version = version;
65
+ this.urls = urls;
66
+ this.ws = null;
67
+ this.connected = false;
68
+ this.lastError = null;
69
+ this.retry = 0;
70
+ this.timers = {};
71
+ this.lastSent = null;
72
+ this.channels = new Map(); // hub terminal channel -> { agentId, kind, session, pending, timer, lagging }
73
+ this.rpcs = 0;
74
+ this.onChange = () => this.schedule();
75
+ manager.on('change', this.onChange);
76
+ manager.on('removed', this.onChange);
77
+ }
78
+
79
+ get link() {
80
+ return readLink();
81
+ }
82
+
83
+ policy() {
84
+ return hubPolicy(this.config);
85
+ }
86
+
87
+ status() {
88
+ const l = this.link;
89
+ if (!l) return { joined: false, policy: this.policy() };
90
+ return {
91
+ joined: true,
92
+ url: l.url,
93
+ name: l.name,
94
+ runnerId: l.runnerId,
95
+ hubName: l.hubName,
96
+ joinedAt: l.joinedAt,
97
+ connected: this.connected,
98
+ lastError: this.lastError,
99
+ policy: this.policy(),
100
+ };
101
+ }
102
+
103
+ start() {
104
+ if (this.link) this.connect();
105
+ }
106
+
107
+ /** Enroll with a one-time code from the hub; makes this machine's key pair. */
108
+ async join(rawUrl, code, name) {
109
+ const url = checkHubUrl(rawUrl);
110
+ if (!String(code ?? '').trim()) throw err(400, 'Invite code is required');
111
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
112
+ const res = await fetch(`${url}/api/join`, {
113
+ method: 'POST',
114
+ headers: { 'content-type': 'application/json' },
115
+ body: JSON.stringify({
116
+ code,
117
+ name: name || os.hostname().replace(/\.local$/i, ''),
118
+ publicKey: publicKey.export({ type: 'spki', format: 'pem' }),
119
+ version: this.version,
120
+ }),
121
+ }).catch((e) => {
122
+ throw err(502, `Cannot reach the hub at ${url}: ${e.cause?.message ?? e.message}`);
123
+ });
124
+ const body = await res.json().catch(() => ({}));
125
+ if (!res.ok || !body.runnerId) throw err(res.status === 401 ? 401 : 502, body.error || `The hub refused to join (HTTP ${res.status})`);
126
+ this.disconnect();
127
+ writeLink({
128
+ url,
129
+ runnerId: body.runnerId,
130
+ name: body.name,
131
+ hubName: body.hubName,
132
+ joinedAt: now(),
133
+ privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }),
134
+ });
135
+ audit(`joined hub ${url} as ${body.name} (${body.runnerId}); policy ${JSON.stringify(this.policy())}`);
136
+ this.retry = 0;
137
+ this.connect();
138
+ return this.status();
139
+ }
140
+
141
+ /** Leave the hub: it forgets this machine, and the key is deleted here. */
142
+ async leave() {
143
+ const l = this.link;
144
+ if (!l) return this.status();
145
+ if (this.connected) {
146
+ this.ws.send(JSON.stringify({ t: 'leave' }));
147
+ await new Promise((r) => setTimeout(r, 200));
148
+ }
149
+ this.disconnect();
150
+ fs.rmSync(LINK(), { force: true });
151
+ audit(`left hub ${l.url}`);
152
+ this.lastError = null;
153
+ return this.status();
154
+ }
155
+
156
+ connect() {
157
+ const l = this.link;
158
+ if (!l || this.ws) return;
159
+ const wsUrl = `${l.url.replace(/^http/, 'ws')}/ws/runner`;
160
+ const ws = new WebSocket(wsUrl, { handshakeTimeout: 10_000, maxPayload: 1024 * 1024 });
161
+ this.ws = ws;
162
+ ws.on('message', (raw) => {
163
+ let msg;
164
+ try {
165
+ msg = JSON.parse(raw.toString());
166
+ } catch {
167
+ return;
168
+ }
169
+ if (msg.t === 'challenge') {
170
+ const sig = crypto.sign(null, challengePayload(String(msg.nonce), l.runnerId), l.privateKey).toString('base64');
171
+ ws.send(
172
+ JSON.stringify({
173
+ t: 'hello',
174
+ runnerId: l.runnerId,
175
+ sig,
176
+ protocol: PROTOCOL,
177
+ version: this.version,
178
+ platform: `${process.platform}-${process.arch}`,
179
+ policy: this.policy(),
180
+ urls: this.urls(),
181
+ }),
182
+ );
183
+ } else if (msg.t === 'welcome') {
184
+ this.connected = true;
185
+ this.lastError = null;
186
+ this.retry = 0;
187
+ audit(`connected to hub ${l.url}`);
188
+ this.lastSent = null;
189
+ this.send(true);
190
+ this.timers.ping = setInterval(() => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ t: 'ping' })), PING_EVERY_MS);
191
+ } else if (!this.connected || msg.t === 'pong') {
192
+ // nothing to do
193
+ } else if (msg.t === 'rpc') {
194
+ this.onRpc(ws, msg);
195
+ } else if (typeof msg.t === 'string' && msg.t.startsWith('term-')) {
196
+ this.onTerm(ws, msg);
197
+ } else {
198
+ audit(`refused "${String(msg.t).slice(0, 30)}" from hub: unknown message`);
199
+ }
200
+ });
201
+ ws.on('close', (code, reason) => {
202
+ if (this.ws !== ws) return;
203
+ const was = this.connected;
204
+ this.cleanup();
205
+ if (code === 4401 || code === 4403) {
206
+ // The hub doesn't know this machine any more: stop retrying until it joins again.
207
+ this.lastError = code === 4403 ? 'Removed from the hub; join again to reconnect' : 'The hub did not recognize this machine; join again';
208
+ audit(`hub ${l.url} refused this machine (${code} ${reason})`);
209
+ return;
210
+ }
211
+ if (was) audit(`disconnected from hub ${l.url} (${code})`);
212
+ this.lastError ??= `Disconnected (${code}${reason?.length ? ` ${reason}` : ''})`;
213
+ this.reconnectLater();
214
+ });
215
+ ws.on('error', (e) => {
216
+ this.lastError = e.message;
217
+ });
218
+ }
219
+
220
+ reconnectLater() {
221
+ if (this.timers.retry || !this.link) return;
222
+ const delay = Math.min(30_000, 1_000 * 2 ** this.retry++) * (0.7 + Math.random() * 0.6);
223
+ this.timers.retry = setTimeout(() => {
224
+ this.timers.retry = null;
225
+ this.connect();
226
+ }, delay);
227
+ }
228
+
229
+ // ------------------------------------------------------------- actions
230
+
231
+ async onRpc(ws, msg) {
232
+ const reply = (m) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ t: 'rpc-result', id: msg.id, ...m }));
233
+ const action = String(msg.action ?? '').slice(0, 40);
234
+ const args = msg.args && typeof msg.args === 'object' && !Array.isArray(msg.args) ? msg.args : {};
235
+ const where = args.agent ? ` on ${String(args.agent).slice(0, 40)}` : args.project ? ` in ${String(args.project).slice(0, 40)}` : '';
236
+ if (this.rpcs >= MAX_RPCS) return reply({ ok: false, status: 429, error: 'Too many actions at once' });
237
+ this.rpcs++;
238
+ try {
239
+ const result = await runAction(this.manager, this.policy(), action, args);
240
+ audit(`hub did ${action}${where}`);
241
+ reply({ ok: true, result });
242
+ this.schedule();
243
+ } catch (e) {
244
+ audit(`hub ${e.status === 403 ? 'was refused' : 'failed'} ${action}${where}: ${e.message}`);
245
+ reply({ ok: false, status: e.status || 500, error: e.message });
246
+ } finally {
247
+ this.rpcs--;
248
+ }
249
+ }
250
+
251
+ // ------------------------------------------------------------- terminals
252
+
253
+ onTerm(ws, msg) {
254
+ const ch = Number(msg.ch);
255
+ if (!Number.isInteger(ch) || ch < 0) return;
256
+ const out = (m) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ ...m, ch }));
257
+ const c = this.channels.get(ch);
258
+ if (msg.t === 'term-open') {
259
+ if (c) return out({ t: 'term-error', error: 'Channel in use' });
260
+ try {
261
+ if (this.channels.size >= MAX_CHANNELS) throw Object.assign(new Error('Too many terminals open from the hub'), { status: 429 });
262
+ const { kind, perm } = terminalPermission(msg.kind);
263
+ const policy = this.policy();
264
+ if (!policy.allow.includes(perm)) throw Object.assign(new Error(`This machine doesn't allow "${perm}" from the hub`), { status: 403 });
265
+ const agent = agentFor(this.manager, policy, msg.agent);
266
+ const chan = { agentId: agent.id, kind, session: null, pending: '', timer: null, lagging: false };
267
+ this.channels.set(ch, chan);
268
+ this.attachChannel(ws, ch, chan);
269
+ if (msg.cols > 0 && msg.rows > 0) this.manager.resize(agent.id, msg.cols | 0, msg.rows | 0, kind);
270
+ audit(`hub opened the ${kind} terminal of ${agent.id}`);
271
+ } catch (e) {
272
+ audit(`hub was refused a terminal on ${String(msg.agent).slice(0, 40)}: ${e.message}`);
273
+ out({ t: 'term-error', error: e.message });
274
+ }
275
+ return;
276
+ }
277
+ if (!c) return;
278
+ if (msg.t === 'term-in' && typeof msg.d === 'string') this.manager.write(c.agentId, msg.d.slice(0, 64 * 1024), c.kind);
279
+ else if (msg.t === 'term-resize') this.manager.resize(c.agentId, msg.cols | 0, msg.rows | 0, c.kind);
280
+ else if (msg.t === 'term-close') {
281
+ this.closeChannel(ch);
282
+ audit(`hub closed the ${c.kind} terminal of ${c.agentId}`);
283
+ }
284
+ }
285
+
286
+ attachChannel(ws, ch, chan) {
287
+ const out = (m) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ ...m, ch }));
288
+ const flush = () => {
289
+ chan.timer = null;
290
+ if (!chan.pending) return;
291
+ const d = chan.pending;
292
+ chan.pending = '';
293
+ if (chan.lagging) return;
294
+ if (ws.bufferedAmount > LAG_HIGH) {
295
+ chan.lagging = true;
296
+ // Once caught up, start over with the current screen instead of leaving a gap.
297
+ chan.lagTimer = setInterval(() => {
298
+ if (ws.readyState !== ws.OPEN) return clearInterval(chan.lagTimer);
299
+ if (ws.bufferedAmount < LAG_LOW) {
300
+ clearInterval(chan.lagTimer);
301
+ this.reattach(ws, ch, chan);
302
+ }
303
+ }, 500);
304
+ return;
305
+ }
306
+ out({ t: 'term-out', d });
307
+ };
308
+ const client = {
309
+ send: (m) => {
310
+ if (m.t === 'o') {
311
+ chan.pending += m.d;
312
+ chan.timer ??= setTimeout(flush, 30);
313
+ } else {
314
+ flush();
315
+ out({ t: 'term-msg', msg: m });
316
+ }
317
+ },
318
+ close: () => {
319
+ this.closeChannel(ch);
320
+ out({ t: 'term-end' });
321
+ },
322
+ };
323
+ const n = chan.kind.startsWith('shell:') ? Number(chan.kind.slice(6)) : 0;
324
+ chan.session = n ? this.manager.attachShell(chan.agentId, client, n) : this.manager.attach(chan.agentId, client);
325
+ let backlog = chan.session.backlog ?? '';
326
+ if (backlog.length > BACKLOG_BYTES) {
327
+ // Start at a line boundary so the cut doesn't land inside an escape sequence.
328
+ const cut = backlog.length - BACKLOG_BYTES;
329
+ const nl = backlog.indexOf('\n', cut);
330
+ backlog = backlog.slice(nl === -1 ? cut : nl + 1);
331
+ }
332
+ out({ t: 'term-hello', kind: chan.kind, running: chan.session.running, backlog });
333
+ }
334
+
335
+ reattach(ws, ch, chan) {
336
+ chan.session?.detach();
337
+ chan.lagging = false;
338
+ chan.pending = '';
339
+ this.attachChannel(ws, ch, chan);
340
+ }
341
+
342
+ closeChannel(ch) {
343
+ const c = this.channels.get(ch);
344
+ if (!c) return;
345
+ clearTimeout(c.timer);
346
+ clearInterval(c.lagTimer);
347
+ c.session?.detach();
348
+ this.channels.delete(ch);
349
+ }
350
+
351
+ cleanup() {
352
+ for (const ch of [...this.channels.keys()]) this.closeChannel(ch);
353
+ clearInterval(this.timers.ping);
354
+ clearTimeout(this.timers.send);
355
+ this.timers.ping = this.timers.send = null;
356
+ this.ws = null;
357
+ this.connected = false;
358
+ }
359
+
360
+ disconnect() {
361
+ clearTimeout(this.timers.retry);
362
+ this.timers.retry = null;
363
+ const ws = this.ws;
364
+ this.cleanup();
365
+ ws?.removeAllListeners('close');
366
+ ws?.on('error', () => {});
367
+ ws?.close();
368
+ }
369
+
370
+ /** At most one state frame per SEND_EVERY_MS, and only when something changed. */
371
+ schedule() {
372
+ if (!this.connected || this.timers.send) return;
373
+ this.timers.send = setTimeout(() => {
374
+ this.timers.send = null;
375
+ this.send();
376
+ }, SEND_EVERY_MS);
377
+ }
378
+
379
+ state() {
380
+ const policy = this.policy();
381
+ if (!policy.allow.includes('view')) return { agents: [], inbox: [] };
382
+ const create = policy.allow.includes('create');
383
+ const projects = create ? this.manager.listProjects().map((p) => ({ ...p, warm: this.manager.projectWarm(p) })) : [];
384
+ return fleetState(
385
+ { agents: this.manager.list(), inbox: this.manager.inbox(), projects, capacity: create ? this.capacity() : null, labels: this.labels() },
386
+ policy,
387
+ );
388
+ }
389
+
390
+ /** Labels the hub's backlog can require: config "hub.labels" plus os and arch. */
391
+ labels() {
392
+ const os = { darwin: 'mac', linux: 'linux', win32: 'windows' }[process.platform] ?? process.platform;
393
+ const engines = Object.values(ENGINES).filter((e) => installed(e, this.config)).map((e) => `engine:${e.id}`);
394
+ return [`os:${os}`, `arch:${process.arch}`, ...engines, ...(Array.isArray(this.config.hub?.labels) ? this.config.hub.labels : [])];
395
+ }
396
+
397
+ /** Room for the hub's backlog: this machine's limits, minus its own backlog's active items. */
398
+ capacity() {
399
+ const busyBy = {};
400
+ let busy = 0;
401
+ for (const it of this.backlog?.items() ?? []) {
402
+ if (it.status !== 'active') continue;
403
+ busy++;
404
+ const entry = Object.values(this.manager.store.data.projects ?? {}).find((p) => p.key === it.projectKey);
405
+ const ref = projectRef(entry ?? { key: it.projectKey, name: it.projectName });
406
+ busyBy[ref] = (busyBy[ref] ?? 0) + 1;
407
+ }
408
+ return {
409
+ max: this.config.hub?.maxAgents ?? this.config.backlogMaxActive ?? 4,
410
+ perProject: this.config.hub?.perProject ?? this.config.backlogParallel ?? 2,
411
+ busy,
412
+ busyBy,
413
+ };
414
+ }
415
+
416
+ send(force = false) {
417
+ if (!this.connected) return;
418
+ const raw = JSON.stringify({ t: 'state', ...this.state() });
419
+ if (!force && raw === this.lastSent) return;
420
+ this.lastSent = raw;
421
+ this.ws.send(raw);
422
+ }
423
+
424
+ stop() {
425
+ this.manager.off('change', this.onChange);
426
+ this.manager.off('removed', this.onChange);
427
+ this.disconnect();
428
+ }
429
+ }
430
+
431
+ /** UI addresses for the hub's links: remote-access URLs, Tailscale ones first. */
432
+ export function linkUrls(remoteUrls) {
433
+ return remoteUrls
434
+ .map((u) => ({ url: u.url, label: isTailscaleHost(u.address) ? 'tailscale' : u.iface, tailscale: isTailscaleHost(u.address), vpn: u.vpn }))
435
+ .sort((a, b) => b.tailscale - a.tailscale || a.vpn - b.vpn)
436
+ .map(({ vpn, ...u }) => u);
437
+ }
package/src/inbox.js ADDED
@@ -0,0 +1,94 @@
1
+ // Decision inbox: questions agents ask without stopping, answered from one place.
2
+ // Agents append questions to QUESTIONS.md next to their brief; answers go back into
3
+ // their session as a message. Live prompts (permission menus) are answered with keys.
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { briefDir } from './brief.js';
8
+
9
+ export const QUESTIONS_FILE = 'QUESTIONS.md';
10
+ export const questionsPath = (agentId) => path.join(briefDir(agentId), QUESTIONS_FILE);
11
+
12
+ export const questionsPrompt = (file) =>
13
+ `When you need a decision from the user that doesn't have to stop all your work (a choice between options, ` +
14
+ `a preference, a missing detail), don't wait in the terminal: add it to ${file} and keep going on whatever you can ` +
15
+ 'do meanwhile, using your best default. Agent Manager collects these into the user\'s inbox. One question per heading, ' +
16
+ 'never edit or remove earlier ones:\n' +
17
+ '## <the question, one line>\n' +
18
+ 'Options: <option A> | <option B> (optional)\n' +
19
+ 'Default: <what you will assume until answered> (optional)\n' +
20
+ '<one or two lines of context> (optional)\n' +
21
+ 'Answers arrive in this session as a message starting with "Answer to your question". Apply them when they come. ' +
22
+ 'Use the terminal (or your question tool) only when you truly cannot continue without the answer.';
23
+
24
+ const qid = (text) => crypto.createHash('sha1').update(text.trim().toLowerCase()).digest('hex').slice(0, 10);
25
+
26
+ /** Parse QUESTIONS.md into [{ id, question, options, default, context }]. */
27
+ export function parseQuestions(markdown) {
28
+ const out = [];
29
+ let cur = null;
30
+ for (const raw of String(markdown ?? '').split('\n')) {
31
+ const line = raw.trimEnd();
32
+ const h = /^#{2,3}\s+(?:Q\d*[:.]\s*)?(.+)$/.exec(line);
33
+ if (h) {
34
+ cur = { id: qid(h[1]), question: h[1].trim(), options: [], default: null, context: '' };
35
+ if (!out.some((q) => q.id === cur.id)) out.push(cur);
36
+ else cur = null;
37
+ continue;
38
+ }
39
+ if (!cur) continue;
40
+ const opt = /^\s*options?\s*:\s*(.+)$/i.exec(line);
41
+ const def = /^\s*(?:default|proceeding with|assuming)\s*:\s*(.+)$/i.exec(line);
42
+ if (opt) cur.options = opt[1].split('|').map((s) => s.trim()).filter(Boolean).slice(0, 6);
43
+ else if (def) cur.default = def[1].trim();
44
+ else if (line.trim()) cur.context = `${cur.context ? `${cur.context} ` : ''}${line.trim()}`.slice(0, 600);
45
+ }
46
+ return out;
47
+ }
48
+
49
+ const cache = new Map(); // file -> { mtimeMs, questions }
50
+ export function loadQuestions(agentId) {
51
+ const file = questionsPath(agentId);
52
+ try {
53
+ const { mtimeMs } = fs.statSync(file);
54
+ const hit = cache.get(file);
55
+ if (hit?.mtimeMs === mtimeMs) return hit.questions;
56
+ const questions = parseQuestions(fs.readFileSync(file, 'utf8'));
57
+ cache.set(file, { mtimeMs, questions });
58
+ return questions;
59
+ } catch {
60
+ cache.delete(file);
61
+ return [];
62
+ }
63
+ }
64
+
65
+ export const answerMessage = (q, text) => `Answer to your question "${q.question}": ${text}`;
66
+
67
+ /**
68
+ * Answer choices visible in a live prompt: numbered menu lines ("❯ 1. Yes", "2. No").
69
+ * `screen` is recent terminal output; cursor moves become spaces before matching.
70
+ */
71
+ export function promptChoices(screen) {
72
+ const text = String(screen ?? '')
73
+ .replace(/\x1b\[(\d*)C/g, (_, n) => ' '.repeat(Math.min(Number(n || 1), 8)))
74
+ .replace(/\x1b\[[0-9;]*[ABDGHJKfm]/g, '\n')
75
+ .replace(/\x1b\[[0-9;?<>=]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')
76
+ .replace(/\r/g, '\n');
77
+ const lines = text.split('\n').map((l) => l.replace(/\s+/g, ' ').trim());
78
+ // The last menu on screen wins: walk back from the end, collecting "N. label" lines.
79
+ const choices = new Map();
80
+ let question = '';
81
+ for (let i = lines.length - 1; i >= 0; i--) {
82
+ const m = /^(?:[❯>›]\s*)?(\d)[.)]\s+(.{1,80})$/.exec(lines[i]);
83
+ if (m) {
84
+ if (!choices.has(m[1])) choices.set(m[1], m[2].trim());
85
+ } else if (choices.size && lines[i]) {
86
+ question = lines[i].slice(0, 200);
87
+ break;
88
+ }
89
+ }
90
+ return {
91
+ question,
92
+ choices: [...choices.entries()].sort(([a], [b]) => a - b).map(([key, label]) => ({ key, label })),
93
+ };
94
+ }