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/manager.js ADDED
@@ -0,0 +1,2554 @@
1
+ import crypto from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import pty from 'node-pty';
6
+ import { expandHome, paths } from './config.js';
7
+ import { DEFAULT_ENGINE, ENGINES, engineOf, installed } from './engines/index.js';
8
+ import {
9
+ DOC_KINDS,
10
+ briefDir,
11
+ briefPath,
12
+ briefPrompt,
13
+ conventionsPrompt,
14
+ docPrompt,
15
+ explainPrompt,
16
+ insightsPrompt,
17
+ loadBrief,
18
+ critiquePrompt,
19
+ humanAiMarkdown,
20
+ humanAiMessage,
21
+ humanAiPrompt,
22
+ parseJsonReply,
23
+ loadPlanFile,
24
+ planApprovedPrompt,
25
+ planPath,
26
+ planReviewPrompt,
27
+ } from './brief.js';
28
+
29
+ // One-off summaries / documents built from an agent's live context.
30
+ const SUMMARIES = {
31
+ explain: { field: 'explanation', prompt: explainPrompt },
32
+ insights: { field: 'insights', prompt: insightsPrompt },
33
+ ...Object.fromEntries(Object.keys(DOC_KINDS).map((k) => [k, { doc: k, prompt: (ctx) => docPrompt(k, ctx) }])),
34
+ humanai: { doc: 'humanai', run: 'runHumanAi' },
35
+ };
36
+ /** Read / write where a summary of `kind` is kept on the agent record. */
37
+ const getSummary = (agent, kind) => (SUMMARIES[kind].doc ? agent.docs?.[kind] : agent[SUMMARIES[kind].field]);
38
+ const summaryPatch = (agent, kind, value) =>
39
+ SUMMARIES[kind].doc ? { docs: { ...agent.docs, [kind]: value } } : { [SUMMARIES[kind].field]: value };
40
+ import { spawn } from 'node:child_process';
41
+ import * as git from './git.js';
42
+ import { conflictMessage, findConflicts, related, repoKey, summarize as summarizeConflicts } from './conflicts.js';
43
+ import { answerMessage, loadQuestions, questionsPath, questionsPrompt } from './inbox.js';
44
+ import { STUCK_DEFAULTS, detectStuck } from './stuck.js';
45
+ import { Judge, clashPrompt, finishMessage, hash, reviewPrompt, screenPrompt, stuckPrompt } from './judge.js';
46
+ import { findLocalUrls, findSignInLinks, parseCallback, parseUrl } from './preview.js';
47
+ import { Plugins } from './plugins.js';
48
+ import { runningClaude, scanClaudeSessions } from './sessions.js';
49
+ import {
50
+ bugFromRef,
51
+ extractRefs,
52
+ prDetails,
53
+ prFromUrl,
54
+ prsForBranch,
55
+ sumUsage,
56
+ } from './tracker.js';
57
+
58
+ // Per-session markers a parent Claude Code session sets. Inherited, they make the
59
+ // agent think it is a nested child session (which, among other things, turns
60
+ // transcript saving off, so the session could never be resumed).
61
+ const STRIP_ENV = [
62
+ 'AI_AGENT',
63
+ 'CLAUDECODE',
64
+ 'CLAUDE_CODE_CHILD_SESSION',
65
+ 'CLAUDE_CODE_ENTRYPOINT',
66
+ 'CLAUDE_CODE_EXECPATH',
67
+ 'CLAUDE_CODE_MESSAGING_SOCKET',
68
+ 'CLAUDE_CODE_MESSAGING_TOKEN',
69
+ 'CLAUDE_CODE_SESSION_ATTENDED',
70
+ 'CLAUDE_CODE_SESSION_ID',
71
+ 'CLAUDE_CODE_SSE_PORT',
72
+ 'CLAUDE_EFFORT',
73
+ 'CLAUDE_PID',
74
+ ];
75
+ // Prompts that block a background agent until someone answers in its terminal.
76
+ // Matched against output with ANSI codes and all whitespace removed, because
77
+ // Claude's TUI positions words with cursor moves instead of spaces.
78
+ const ANSI = /\x1b(\[[0-9;?<>=]*[ -\/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|[()][0-9A-B]|[=>78c])/g;
79
+ // When a link is found from several sources, the higher-ranked source is kept.
80
+ const SOURCE_RANK = { manual: 5, intent: 4, session: 3, branch: 2, mentioned: 1 };
81
+ const BUSY_IDLE_MS = 3000;
82
+ /** Looser stuck thresholds: candidates the judge looks at before anyone is bothered. */
83
+ const loosen = (o) => ({
84
+ repeatFailures: Math.max(2, Math.ceil(o.repeatFailures / 2)),
85
+ thrashReverts: Math.max(1, o.thrashReverts - 1),
86
+ thrashEdits: Math.max(4, Math.ceil(o.thrashEdits * 0.6)),
87
+ driftMinutes: Math.max(5, Math.ceil(o.driftMinutes / 2)),
88
+ driftActions: Math.max(10, Math.ceil(o.driftActions * 0.6)),
89
+ });
90
+
91
+ const planningPrompt = (agent) =>
92
+ `You are in a planning phase. The working copy of ${agent.repo || 'the repository'} is still being ` +
93
+ 'prepared (cloned) and is not available yet, so do not look for project files in the current folder ' +
94
+ 'and do not create or edit files here. Use this time with the user: restate the task, ask focused ' +
95
+ 'questions, gather requirements and constraints, and agree on an approach and a step-by-step plan. ' +
96
+ 'When the repository is ready, this session will move into it and you will be told.';
97
+
98
+ const handoffMessage = (agent) =>
99
+ `The repository is ready. You are now in its working copy at ${agent.workdir}` +
100
+ `${agent.branch ? ` (branch ${agent.branch})` : ''}. First review its CLAUDE.md, skills and hooks as instructed, ` +
101
+ 'then continue with the plan we agreed on.';
102
+
103
+ /**
104
+ * The project an agent belongs to, for grouping: a user-set name, else its repo
105
+ * (URL or the clone's origin remote, so a URL and a local clone of the same repo
106
+ * group together), else the folder's name.
107
+ */
108
+ /** Shell number for a terminal kind ('shell' -> 1, 'shell:3' -> 3), or 0 for Claude's own terminal. */
109
+ export function shellNumber(kind) {
110
+ const m = /^shell(?::(\d{1,3}))?$/.exec(kind ?? '');
111
+ return m ? Math.max(1, Number(m[1] ?? 1)) : 0;
112
+ }
113
+
114
+ /** Where the shared clone of a repo URL lives. */
115
+ export function repoCacheDir(repo) {
116
+ const hash = crypto.createHash('sha1').update(repo).digest('hex').slice(0, 6);
117
+ return path.join(paths.repos, `${git.repoNameFromUrl(repo)}-${hash}`);
118
+ }
119
+
120
+ export function projectOf(agent) {
121
+ if (agent.project) return { key: `custom:${agent.project.toLowerCase()}`, name: agent.project, source: 'custom' };
122
+ if (agent.kind === 'general') return { key: 'general', name: 'General', source: 'general' };
123
+ const url = agent.repo || agent.git?.remote;
124
+ if (url && /[:/]/.test(url)) {
125
+ const path = url
126
+ .trim()
127
+ .replace(/^[a-z+]+:\/\//i, '')
128
+ .replace(/^[^@/]+@/, '')
129
+ .replace(':', '/')
130
+ .replace(/\.git$/, '')
131
+ .replace(/\/+$/, '');
132
+ const parts = path.split('/').filter(Boolean);
133
+ const name = parts.at(-1) || path;
134
+ // github.com/org/repo -> key "github.com/org/repo"; file:// paths keep their full path.
135
+ return { key: `repo:${path.toLowerCase()}`, name, full: parts.slice(-2).join('/'), source: 'repo' };
136
+ }
137
+ const folder = agent.sourceDir || agent.requestedDir || (agent.workdir?.startsWith(paths.workspaces) ? null : agent.workdir);
138
+ if (folder) return { key: `dir:${folder}`, name: path.basename(folder), full: folder, source: 'folder' };
139
+ return { key: 'other', name: 'Other', source: 'other' };
140
+ }
141
+
142
+ /** A short, memorable shortcut for a project name: initials of its parts, or its first letters. */
143
+ export function suggestShortcut(name, taken = new Set()) {
144
+ const parts = String(name ?? '')
145
+ .toLowerCase()
146
+ .split(/[^a-z0-9]+/)
147
+ .filter(Boolean);
148
+ let base = parts.length > 1 ? parts.map((p) => p[0]).join('').slice(0, 4) : (parts[0] ?? 'p').slice(0, 3);
149
+ if (base.length < 2) base = (parts.join('') || 'proj').slice(0, 3);
150
+ let candidate = base;
151
+ for (let i = 2; taken.has(candidate); i++) candidate = `${base}${i}`;
152
+ return candidate;
153
+ }
154
+
155
+ export const validShortcut = (s) => /^[a-z][a-z0-9-]{0,15}$/.test(s);
156
+
157
+ export function slugify(text, max = 30) {
158
+ return (
159
+ text
160
+ .toLowerCase()
161
+ .replace(/[^a-z0-9]+/g, '-')
162
+ .replace(/^-+|-+$/g, '')
163
+ .slice(0, max)
164
+ .replace(/-+$/, '') || 'agent'
165
+ );
166
+ }
167
+
168
+ const now = () => new Date().toISOString();
169
+ /** Priority 0 (P0, most urgent) to 3 (P3); P2 is the default. Accepts 0-3, "P0"-"P3". */
170
+ export const parsePriority = (v, fallback = 2) => {
171
+ const n = Number(String(v ?? '').replace(/^p/i, ''));
172
+ return v !== undefined && v !== null && v !== '' && Number.isInteger(n) && n >= 0 && n <= 3 ? n : fallback;
173
+ };
174
+ const scrollbackFile = (id) => path.join(paths.scrollback, `${id}.log`);
175
+
176
+ /** Terminal output saved by the last flush, so a restarted daemon's terminal isn't blank. */
177
+ function loadScrollback(id) {
178
+ try {
179
+ const text = fs.readFileSync(scrollbackFile(id), 'utf8');
180
+ return text ? { chunks: [text], size: text.length } : { chunks: [], size: 0 };
181
+ } catch {
182
+ return { chunks: [], size: 0 };
183
+ }
184
+ }
185
+ const baseLabel = ({ ref, sha }) => `${ref} @ ${sha.slice(0, 9)}`;
186
+
187
+ export class AgentManager extends EventEmitter {
188
+ constructor({ store, config, plugins = new Plugins() }) {
189
+ super();
190
+ this.store = store;
191
+ this.config = config;
192
+ this.plugins = plugins; // policies before actions, listeners after (src/plugins.js)
193
+ this.runtimes = new Map(); // agent id -> { pty, chunks, size, clients, lastOutputAt, busy, stopping, exited }
194
+ this.shells = new Map(); // agent id -> ancillary shell runtime in the agent's folder
195
+ this.cursors = new Map(); // session id -> transcript scan cursor
196
+ this.locks = new Map();
197
+ this.refreshing = new Set();
198
+ this.lastPrCheck = new Map();
199
+ this.changeSets = new Map(); // agent id -> { files, baseSha, at }: what its branch changed (conflict radar)
200
+ this.conflicts = new Map(); // agent id -> [conflict]
201
+ this.activity = new Map(); // session id -> transcript activity window (stuck detection)
202
+ this.stuck = new Map(); // agent id -> [finding]
203
+ this.outbox = new Map(); // agent id -> [message] waiting to be typed into its session
204
+ // The AI judge: rules decide when to look, a model decides what is going on (see judge.js).
205
+ this.judge = new Judge({ config, call: (agent, prompt, { timeoutMs }) => this.oneShot(agent, prompt, { ...this.judgeModel(agent), timeoutMs }) });
206
+ this.stuckVerdicts = new Map(); // agent id -> Map(finding key -> { at, since, data })
207
+ this.signIns = new Map(); // agent id -> { url, port, callback, terminal, at, finished } from a CLI's sign-in link
208
+ this.seenLinks = new Map(); // agent id -> Set of sign-in links already raised
209
+ this.clashVerdicts = new Map(); // 'idA|idB' (sorted) -> { at, hash, a, b, data, pending }
210
+
211
+ // Processes do not survive a daemon restart, but their session IDs do.
212
+ // `desired` records whether the user wants the agent running; a restart,
213
+ // crash or reboot leaves it alone, so resumeAll() can bring agents back.
214
+ for (const agent of store.list()) {
215
+ if (!agent.desired) store.patch(agent.id, { desired: agent.status === 'running' ? 'running' : 'stopped' });
216
+ if (agent.status === 'running' || agent.status === 'preparing') {
217
+ const interrupted = agent.status === 'preparing';
218
+ store.patch(agent.id, {
219
+ status: interrupted ? 'error' : 'stopped',
220
+ error: interrupted ? 'Workspace setup was interrupted by a daemon restart' : agent.error,
221
+ // resumeAll() retries interrupted setups the user still wants running.
222
+ setupInterrupted: interrupted || undefined,
223
+ pid: null,
224
+ });
225
+ }
226
+ if (agent.progress) store.patch(agent.id, { progress: null });
227
+ for (const kind of Object.keys(SUMMARIES)) {
228
+ const cur = store.get(agent.id);
229
+ const v = getSummary(cur, kind);
230
+ if (v?.pending) store.patch(agent.id, summaryPatch(cur, kind, { ...v, pending: false }));
231
+ }
232
+ }
233
+ this.preparing = new Map(); // agent id -> { controller, done } for workspace setup in flight
234
+ // Project shortcuts ("cc" -> cloud-console), keyed by shortcut; every project gets one.
235
+ store.data.projects ??= {};
236
+ for (const agent of store.list()) this.registerProject(agent);
237
+
238
+ this.timer = setInterval(() => this.tick(), 1000);
239
+ this.timer.unref();
240
+ this.tickCount = 0;
241
+ }
242
+
243
+ // ---------------------------------------------------------------- queries
244
+
245
+ list() {
246
+ return this.store.list().map((a) => this.view(a));
247
+ }
248
+
249
+ get(ref) {
250
+ const agent = this.store.resolve(ref);
251
+ return agent && this.view(agent);
252
+ }
253
+
254
+ mustGet(ref) {
255
+ const agent = this.store.resolve(ref);
256
+ if (!agent) throw Object.assign(new Error(`No agent matches "${ref}"`), { status: 404 });
257
+ return agent;
258
+ }
259
+
260
+ view(agent) {
261
+ const rt = this.runtimes.get(agent.id);
262
+ const usage = { input: 0, output: 0, cacheCreation: 0, cacheRead: 0, requests: 0, total: 0 };
263
+ for (const s of agent.sessions ?? []) for (const k of Object.keys(usage)) usage[k] += s.usage?.[k] ?? 0;
264
+ usage.io = usage.input + usage.output;
265
+ const costs = (agent.sessions ?? []).map((s) => s.cost?.usd).filter((c) => c != null);
266
+ const prs = Object.values(agent.prs ?? {});
267
+ return {
268
+ ...agent,
269
+ results: this.results(agent, rt, prs),
270
+ priority: agent.priority ?? 2,
271
+ projectInfo: this.projectInfo(agent),
272
+ usage,
273
+ // Claude Code's own cost figure from the transcripts (absent until it records one).
274
+ costUsd: costs.length ? costs.reduce((a, b) => a + b, 0) : null,
275
+ prs: Object.values(agent.prs ?? {}),
276
+ bugs: Object.values(agent.bugs ?? {}),
277
+ conflicts: this.conflictGroups(agent),
278
+ stuck: this.activeStuck(agent),
279
+ questions: this.questionsView(agent),
280
+ outbox: this.outbox.get(agent.id)?.length ?? 0,
281
+ signIn: this.signInView(agent),
282
+ runtime: {
283
+ running: Boolean(rt?.pty),
284
+ busy: Boolean(rt?.pty && rt.busy),
285
+ planning: Boolean(rt?.pty && rt.planning),
286
+ attention: (rt?.pty && !rt.busy && rt.attention) || null,
287
+ // What the AI judge read on an idle screen no rule matched: a question or an error.
288
+ waiting: (rt?.pty && !rt.busy && !rt.attention && rt.waiting) || null,
289
+ clients: rt?.clients.size ?? 0,
290
+ shell: this.shellNumbers(agent.id).length > 0,
291
+ shells: this.shellNumbers(agent.id),
292
+ lastOutputAt: rt?.lastOutputAt ? new Date(rt.lastOutputAt).toISOString() : null,
293
+ prompt: rt?.pty && !rt.busy && rt.attention ? engineOf(agent).promptChoices(rt.tail) : null,
294
+ },
295
+ };
296
+ }
297
+
298
+ /**
299
+ * The end result / status / blockers for an agent: what the agent wrote under
300
+ * "## Results", plus what Agent Manager knows (PRs, checks, prompts, errors).
301
+ */
302
+ results(agent, rt, prs) {
303
+ const r = agent.brief?.results;
304
+ const delivered = (r?.delivered ?? []).map((text) => ({ text, source: 'agent' }));
305
+ const blockers = (r?.blockers ?? []).map((text) => ({ text, source: 'agent' }));
306
+ for (const p of prs) {
307
+ if (p.source === 'mentioned') continue;
308
+ const label = `PR ${p.number ? `#${p.number} ` : ''}${p.title ?? p.url}${p.state ? ` (${p.isDraft ? 'draft' : p.state.toLowerCase()})` : ''}`;
309
+ if (!delivered.some((d) => d.text.includes(p.url) || (p.number && d.text.includes(`#${p.number}`)))) {
310
+ delivered.push({ text: label, url: p.url, source: 'tracked' });
311
+ }
312
+ }
313
+ const failed = (agent.brief?.checks ?? []).filter((c) => c.state === 'failed');
314
+ for (const c of failed) blockers.push({ text: `Failing check: ${c.text}`, source: 'checks' });
315
+ const attention = rt?.pty && !rt.busy && rt.attention;
316
+ if (attention) blockers.push({ text: `${attention}: waiting for an answer in the terminal`, source: 'live' });
317
+ if (agent.status === 'error') blockers.push({ text: agent.error ?? 'Setup or launch failed', source: 'live' });
318
+
319
+ let outcome = r?.outcome ?? null;
320
+ if (!outcome) {
321
+ if (agent.status === 'error' || agent.brief?.status === 'blocked') outcome = 'blocked';
322
+ else if (agent.brief?.status === 'done') outcome = 'done';
323
+ else if (agent.brief?.status || rt?.pty || agent.status === 'preparing') outcome = 'in progress';
324
+ }
325
+ if (!outcome && !delivered.length && !blockers.length) return null;
326
+ return { outcome: outcome ?? 'in progress', delivered, blockers, notes: r?.notes ?? '', fromAgent: Boolean(r) };
327
+ }
328
+
329
+ changed(agent) {
330
+ this.emit('change', this.view(agent));
331
+ }
332
+
333
+ patch(id, fields) {
334
+ const agent = this.store.patch(id, fields);
335
+ if (agent) this.changed(agent);
336
+ return agent;
337
+ }
338
+
339
+ // --------------------------------------------------------------- projects
340
+
341
+ projectInfo(agent) {
342
+ const info = projectOf(agent);
343
+ const entry = Object.values(this.store.data.projects).find((p) => p.key === info.key);
344
+ return { ...info, shortcut: entry?.shortcut ?? null };
345
+ }
346
+
347
+ /** Make sure the agent's project has a shortcut; remember where it lives for "add @cc". */
348
+ registerProject(agent) {
349
+ if (!agent || agent.kind === 'general') return null;
350
+ const info = projectOf(agent);
351
+ if (info.key === 'other') return null;
352
+ const reg = this.store.data.projects;
353
+ let entry = Object.values(reg).find((p) => p.key === info.key);
354
+ if (!entry) {
355
+ const shortcut = suggestShortcut(info.name, new Set(Object.keys(reg)));
356
+ entry = reg[shortcut] = { shortcut, name: info.name, key: info.key, repo: null, dir: null, base: null, auto: true, createdAt: now() };
357
+ }
358
+ let changed = !entry.updatedAt;
359
+ const fill = { repo: agent.repo && git.isRemoteUrl(agent.repo) ? agent.repo : null, dir: agent.repo ? null : agent.sourceDir || agent.requestedDir || null };
360
+ for (const [k, v] of Object.entries(fill)) {
361
+ if (v && !entry[k]) {
362
+ entry[k] = v;
363
+ changed = true;
364
+ }
365
+ }
366
+ if (changed) {
367
+ entry.updatedAt = now();
368
+ this.store.save();
369
+ }
370
+ return entry;
371
+ }
372
+
373
+ /** Find a project by shortcut, name or full name (case-insensitive). */
374
+ resolveProject(ref) {
375
+ const r = String(ref ?? '').trim().replace(/^@/, '').toLowerCase();
376
+ if (!r) return null;
377
+ const all = Object.values(this.store.data.projects);
378
+ return all.find((p) => p.shortcut === r) ?? all.find((p) => p.name.toLowerCase() === r) ?? null;
379
+ }
380
+
381
+ listProjects() {
382
+ const agents = this.store.list();
383
+ return Object.values(this.store.data.projects)
384
+ .map((p) => {
385
+ const mine = agents.filter((a) => projectOf(a).key === p.key);
386
+ return { ...p, agents: mine.length, running: mine.filter((a) => this.runtimes.get(a.id)?.pty).length };
387
+ })
388
+ .sort((a, b) => a.shortcut.localeCompare(b.shortcut));
389
+ }
390
+
391
+ /** Whether new agents in this project start without a clone: its folder or repo is already here. */
392
+ projectWarm(entry) {
393
+ if (entry.dir) return fs.existsSync(entry.dir);
394
+ if (entry.repo && git.isRemoteUrl(entry.repo)) return fs.existsSync(repoCacheDir(entry.repo));
395
+ return true;
396
+ }
397
+
398
+ /** Register a project ahead of time: `{ shortcut, name?, repo? | dir?, base? }`. */
399
+ addProject({ shortcut, name, repo, dir, base }) {
400
+ const sc = String(shortcut ?? '').trim().toLowerCase();
401
+ if (!validShortcut(sc)) throw Object.assign(new Error('Shortcut: 1-16 lowercase letters, digits or "-", starting with a letter'), { status: 400 });
402
+ if (this.store.data.projects[sc]) throw Object.assign(new Error(`Shortcut "${sc}" is taken`), { status: 409 });
403
+ if (!repo && !dir && !name) throw Object.assign(new Error('Give a repo URL, a folder, or a name'), { status: 400 });
404
+ const pseudo = { project: repo || dir ? null : name, repo: repo || null, requestedDir: dir ? path.resolve(expandHome(dir)) : null };
405
+ const info = projectOf(pseudo);
406
+ const clash = Object.values(this.store.data.projects).find((p) => p.key === info.key);
407
+ if (clash) throw Object.assign(new Error(`That project already has the shortcut "${clash.shortcut}"`), { status: 409 });
408
+ this.store.data.projects[sc] = {
409
+ shortcut: sc,
410
+ name: name || info.name,
411
+ key: info.key,
412
+ repo: repo || null,
413
+ dir: pseudo.requestedDir,
414
+ base: base || null,
415
+ auto: false,
416
+ createdAt: now(),
417
+ updatedAt: now(),
418
+ };
419
+ this.store.save();
420
+ this.emitAll();
421
+ return this.store.data.projects[sc];
422
+ }
423
+
424
+ updateProject(ref, { shortcut, base }) {
425
+ const entry = this.resolveProject(ref);
426
+ if (!entry) throw Object.assign(new Error(`No project "${ref}"`), { status: 404 });
427
+ const reg = this.store.data.projects;
428
+ if (shortcut !== undefined && shortcut !== entry.shortcut) {
429
+ const sc = String(shortcut).trim().toLowerCase();
430
+ if (!validShortcut(sc)) throw Object.assign(new Error('Shortcut: 1-16 lowercase letters, digits or "-", starting with a letter'), { status: 400 });
431
+ if (reg[sc]) throw Object.assign(new Error(`Shortcut "${sc}" is taken`), { status: 409 });
432
+ delete reg[entry.shortcut];
433
+ entry.shortcut = sc;
434
+ reg[sc] = entry;
435
+ }
436
+ if (base !== undefined) entry.base = base || null;
437
+ entry.auto = false;
438
+ entry.updatedAt = now();
439
+ this.store.save();
440
+ this.emitAll();
441
+ return entry;
442
+ }
443
+
444
+ removeProject(ref) {
445
+ const entry = this.resolveProject(ref);
446
+ if (!entry) throw Object.assign(new Error(`No project "${ref}"`), { status: 404 });
447
+ delete this.store.data.projects[entry.shortcut];
448
+ this.store.save();
449
+ this.emitAll();
450
+ return { shortcut: entry.shortcut };
451
+ }
452
+
453
+ /** Re-broadcast every agent (their project shortcut may have changed). */
454
+ emitAll() {
455
+ for (const a of this.store.list()) this.changed(a);
456
+ this.emit('projects', this.listProjects());
457
+ }
458
+
459
+ // --------------------------------------------------------------- creation
460
+
461
+ /** Create one agent per intent. Workspace prep and launch continue in the background. */
462
+ createMany(intents, opts = {}) {
463
+ const list = intents.map((i) => i.trim()).filter(Boolean);
464
+ if (!list.length) throw Object.assign(new Error('At least one intent is required'), { status: 400 });
465
+ // Several intents against one folder would trample each other; isolate them.
466
+ const worktree = opts.worktree ?? (list.length > 1 && Boolean(opts.dir));
467
+ return list.map((intent, i) =>
468
+ this.create({ ...opts, intent, worktree, name: list.length > 1 && opts.name ? `${opts.name}-${i + 1}` : opts.name }),
469
+ );
470
+ }
471
+
472
+ /** A general Claude session with no repo or folder; the question (if any) is its first prompt. */
473
+ createGeneral({ question, name, permissionMode, model } = {}) {
474
+ return this.create({ kind: 'general', intent: question, name, permissionMode, model });
475
+ }
476
+
477
+ create({
478
+ kind = 'task',
479
+ intent,
480
+ name,
481
+ repo,
482
+ dir,
483
+ worktree = false,
484
+ base,
485
+ permissionMode,
486
+ model,
487
+ start = true,
488
+ plan = false,
489
+ planReview,
490
+ project,
491
+ priority,
492
+ workspace,
493
+ race,
494
+ engine,
495
+ sessionId: adopt,
496
+ imported,
497
+ }) {
498
+ intent = (intent ?? '').trim();
499
+ const engineDef = engineOf(engine || this.config.engine || DEFAULT_ENGINE);
500
+ const engineId = engineDef.id;
501
+ this.plugins.check('agent.create', {
502
+ input: { kind, intent, name, repo, dir, worktree, base, permissionMode: permissionMode || this.config.permissionMode || null, model, project, priority, engine: engineId, imported: Boolean(imported) },
503
+ });
504
+ if (permissionMode && !engineDef.permissionModes.includes(permissionMode)) {
505
+ throw Object.assign(new Error(`${engineDef.label} has no "${permissionMode}" mode (use ${engineDef.permissionModes.join(', ')})`), { status: 400 });
506
+ }
507
+ // Planning while cloning moves the session between folders, which needs the engine's support.
508
+ if (!engineDef.supports.planHandoff) plan = false;
509
+ const general = kind === 'general';
510
+ // A project shortcut (or name) fills in the repo / folder / base branch.
511
+ const entry = !general && project ? this.resolveProject(project) : null;
512
+ if (entry) {
513
+ if (!repo && !dir) {
514
+ repo = entry.repo ?? undefined;
515
+ dir = entry.dir ?? undefined;
516
+ // Agents started from a project's own clone always get their own worktree.
517
+ if (dir) worktree = true;
518
+ }
519
+ base ??= entry.base ?? undefined;
520
+ project = entry.key.startsWith('custom:') ? entry.name : null;
521
+ }
522
+ if (!intent && !general) throw Object.assign(new Error('Intent is required'), { status: 400 });
523
+ const id = crypto.randomBytes(3).toString('hex');
524
+ // An imported session keeps its ID, so the first start resumes it.
525
+ const sessionId = adopt || crypto.randomUUID();
526
+ const slug = name || intent ? slugify(name || intent) : `general-${id}`;
527
+ const refs = extractRefs(intent, this.config.bugPatterns);
528
+
529
+ const agent = {
530
+ id,
531
+ kind: general ? 'general' : 'task',
532
+ engine: engineId,
533
+ project: project?.trim() || null,
534
+ priority: parsePriority(priority),
535
+ name: name?.trim() || slug,
536
+ slug,
537
+ intent,
538
+ repo: general ? null : repo?.trim() || null,
539
+ requestedDir: general ? null : dir?.trim() || null,
540
+ workdir: null,
541
+ sourceDir: null,
542
+ branch: null,
543
+ worktree: !general && Boolean(worktree),
544
+ // Requested start point for the agent's branch (null = the repo's default branch).
545
+ base: general ? null : base?.trim() || null,
546
+ baseRef: null,
547
+ permissionMode: permissionMode || this.config.permissionMode,
548
+ model: model || null,
549
+ // Review the implementation plan before the agent implements it: null = no review.
550
+ planReview: !general && (planReview ?? this.config.planReview ?? false) ? { status: 'writing' } : null,
551
+ status: 'preparing',
552
+ desired: start ? 'running' : 'stopped',
553
+ error: null,
554
+ exitCode: null,
555
+ pid: null,
556
+ sessionId,
557
+ sessions: [{ id: sessionId, createdAt: now(), starts: 0 }],
558
+ git: null,
559
+ prs: {},
560
+ bugs: {},
561
+ dismissed: [],
562
+ notes: '',
563
+ createdAt: now(),
564
+ updatedAt: now(),
565
+ lastStartedAt: null,
566
+ stoppedAt: null,
567
+ ...(race ? { raceId: race.id, variant: race.variant } : {}),
568
+ ...(imported ? { imported } : {}),
569
+ };
570
+ for (const pr of refs.prs) agent.prs[pr.url] = { ...pr, source: 'intent' };
571
+ for (const bug of refs.bugs) agent.bugs[bug.key] = { ...bug, source: 'intent' };
572
+ this.store.put(agent);
573
+ this.registerProject(agent);
574
+ this.changed(agent);
575
+
576
+ this.plugins.emit('agent.created', { agent: this.auditView(agent) });
577
+ this.prepare(agent, { start, workspace }).catch(() => {});
578
+ // Planning only makes sense while there is a clone to wait for.
579
+ if (plan && agent.repo && git.isRemoteUrl(agent.repo)) {
580
+ try {
581
+ this.startPlanning(agent.id);
582
+ } catch {}
583
+ }
584
+ return this.view(agent);
585
+ }
586
+
587
+ prepare(agent, { start, workspace }) {
588
+ const controller = new AbortController();
589
+ const { signal } = controller;
590
+ // Progress is transient: broadcast it, but don't rewrite state.json for every tick.
591
+ let last = 0;
592
+ const progress = (p) => {
593
+ const cur = this.store.get(agent.id);
594
+ if (!cur) return;
595
+ const t = Date.now();
596
+ if (t - last < 500 && p.percent !== 100 && cur.progress?.phase === p.phase) return;
597
+ last = t;
598
+ cur.progress = { ...p, at: new Date(t).toISOString() };
599
+ this.changed(cur);
600
+ };
601
+ const done = (async () => {
602
+ try {
603
+ const ws = await (workspace ?? ((a, o) => this.prepareWorkspace(a, o)))(agent, { signal, progress });
604
+ progress({ phase: 'Reading git info' });
605
+ const info = await git.gitInfo(ws.workdir);
606
+ if (!this.store.get(agent.id)) return;
607
+ this.patch(agent.id, {
608
+ ...ws,
609
+ repo: ws.repo || agent.repo || info?.remote || null,
610
+ git: info,
611
+ status: 'stopped',
612
+ progress: null,
613
+ setupInterrupted: undefined,
614
+ });
615
+ this.registerProject(this.store.get(agent.id));
616
+ const rt = this.runtimes.get(agent.id);
617
+ if (this.closing) return; // shutting down: it resumes on the next start (desired is kept)
618
+ if (rt?.pty && rt.planning) this.maybeHandoff(agent.id).catch(() => {});
619
+ else if (this.store.get(agent.id)?.desired === 'running') this.start(agent.id);
620
+ } catch (err) {
621
+ if (this.store.get(agent.id)) {
622
+ this.patch(agent.id, { status: 'error', error: err.message, progress: null, setupInterrupted: undefined });
623
+ }
624
+ throw err;
625
+ } finally {
626
+ this.preparing.delete(agent.id);
627
+ }
628
+ })();
629
+ this.preparing.set(agent.id, { controller, done });
630
+ return done;
631
+ }
632
+
633
+ /** Re-run workspace setup for an agent whose setup failed or was interrupted. */
634
+ retrySetup(ref) {
635
+ const agent = this.mustGet(ref);
636
+ if (agent.status !== 'error' || agent.workdir) {
637
+ throw Object.assign(new Error('Only agents whose setup failed can be retried'), { status: 409 });
638
+ }
639
+ this.patch(agent.id, { status: 'preparing', error: null, desired: 'running' });
640
+ this.prepare(agent, { start: true }).catch(() => {});
641
+ // Bring back a planning session that a daemon restart interrupted.
642
+ if (agent.planning && !agent.planning.handedOffAt && !this.runtimes.get(agent.id)?.pty) {
643
+ try {
644
+ this.startPlanning(agent.id);
645
+ } catch {}
646
+ }
647
+ return this.view(agent);
648
+ }
649
+
650
+ withLock(key, fn) {
651
+ const prev = this.locks.get(key) ?? Promise.resolve();
652
+ const next = prev.catch(() => {}).then(fn);
653
+ this.locks.set(key, next);
654
+ return next;
655
+ }
656
+
657
+ async prepareWorkspace(agent, { signal, progress = () => {} } = {}) {
658
+ const { id, slug } = agent;
659
+ const cloneOpts = (phase) => ({
660
+ signal,
661
+ filter: this.config.cloneFilter || undefined,
662
+ onProgress: (p) => progress({ phase, ...p }),
663
+ });
664
+ if (agent.kind === 'general') {
665
+ fs.mkdirSync(paths.general, { recursive: true });
666
+ return { workdir: paths.general };
667
+ }
668
+ let repo = agent.repo;
669
+ let dir = agent.requestedDir ? path.resolve(expandHome(agent.requestedDir)) : null;
670
+ const branch = `agent/${slug}-${id}`;
671
+
672
+ // A "repo" that is really a local path is treated as the folder.
673
+ if (repo && !git.isRemoteUrl(repo)) {
674
+ dir ??= path.resolve(expandHome(repo));
675
+ repo = null;
676
+ }
677
+
678
+ if (repo && !dir) {
679
+ // One shared clone per repo; each agent gets its own worktree + branch off it.
680
+ const name = git.repoNameFromUrl(repo);
681
+ const base = repoCacheDir(repo);
682
+ if (this.locks.has(base)) progress({ phase: 'Waiting for another agent to finish cloning' });
683
+ await this.withLock(base, async () => {
684
+ signal?.throwIfAborted();
685
+ // A clone interrupted by a crash or restart is unusable; start it over.
686
+ if (fs.existsSync(base) && !(await git.isValidClone(base))) fs.rmSync(base, { recursive: true, force: true });
687
+ if (!fs.existsSync(base)) {
688
+ progress({ phase: 'Cloning' });
689
+ await git.clone(repo, base, { ...cloneOpts('Cloning'), noCheckout: true });
690
+ } else {
691
+ progress({ phase: 'Fetching' });
692
+ await git.fetch(base, { signal }).catch((err) => {
693
+ if (err.cancelled) throw err;
694
+ });
695
+ }
696
+ });
697
+ const workdir = path.join(paths.workspaces, `${name}-${slug}-${id}`);
698
+ let start;
699
+ await this.withLock(base, async () => {
700
+ signal?.throwIfAborted();
701
+ progress({ phase: 'Checking out' });
702
+ start = await git.resolveBase(base, agent.base);
703
+ await git.addWorktree(base, workdir, branch, start.sha, cloneOpts('Checking out'));
704
+ });
705
+ return { workdir, sourceDir: base, branch, worktree: true, repo, baseRef: baseLabel(start) };
706
+ }
707
+
708
+ if (repo && dir && !fs.existsSync(dir)) {
709
+ progress({ phase: 'Cloning' });
710
+ await git.clone(repo, dir, cloneOpts('Cloning'));
711
+ return { workdir: dir, repo };
712
+ }
713
+
714
+ if (!dir) {
715
+ const workdir = path.join(paths.workspaces, `${slug}-${id}`);
716
+ fs.mkdirSync(workdir, { recursive: true });
717
+ return { workdir, repo };
718
+ }
719
+
720
+ fs.mkdirSync(dir, { recursive: true });
721
+ // A worktree needs a git repo; for any other folder (the UI asks for worktrees by default) use it as is.
722
+ if (agent.worktree && (await git.isGitRepo(dir))) {
723
+ const top = await git.run('git', ['rev-parse', '--show-toplevel'], { cwd: dir });
724
+ const workdir = path.join(paths.workspaces, `${path.basename(top)}-${slug}-${id}`);
725
+ let start;
726
+ await this.withLock(top, async () => {
727
+ // Branch off the latest default branch (or the requested base), not whatever is checked out.
728
+ if (await git.hasRemote(top)) {
729
+ progress({ phase: 'Fetching' });
730
+ await git.fetch(top, { signal }).catch((err) => {
731
+ if (err.cancelled) throw err; // offline / no access: use the refs we already have
732
+ });
733
+ }
734
+ start = await git.resolveBase(top, agent.base);
735
+ progress({ phase: 'Checking out' });
736
+ await git.addWorktree(top, workdir, branch, start.sha, cloneOpts('Checking out'));
737
+ });
738
+ return { workdir, sourceDir: top, branch, worktree: true, repo, baseRef: baseLabel(start) };
739
+ }
740
+ return { workdir: dir, repo, worktree: false };
741
+ }
742
+
743
+ // -------------------------------------------------------------- lifecycle
744
+
745
+ /**
746
+ * Launch (or re-launch) claude for an agent. Resumes the current session if
747
+ * its transcript exists; `fresh` starts a new session ID, `sessionId` switches
748
+ * back to an earlier one.
749
+ */
750
+ start(ref, { fresh = false, sessionId } = {}) {
751
+ const agent = this.mustGet(ref);
752
+ if (this.closing) throw Object.assign(new Error('Agent Manager is shutting down'), { status: 503 });
753
+ const live = this.runtimes.get(agent.id);
754
+ if (!live?.pty) {
755
+ this.plugins.check('agent.start', { agent: this.auditView(agent), fresh });
756
+ this.plugins.emit('agent.starting', { agent: this.auditView(agent), fresh });
757
+ }
758
+ if (live?.pty) {
759
+ // "Start" on a planning session whose workspace is ready means: move it into the repo.
760
+ if (live.planning && agent.workdir && agent.status !== 'preparing') return this.maybeHandoff(agent.id, { force: true });
761
+ // Retry setup while the planning session keeps running.
762
+ if (agent.status === 'error' && !agent.workdir) return this.retrySetup(agent.id);
763
+ return this.view(agent);
764
+ }
765
+ if (agent.status === 'preparing') {
766
+ throw Object.assign(
767
+ new Error(`Workspace is still being prepared; plan with Claude meanwhile: agentmgr plan ${agent.id}`),
768
+ { status: 409 },
769
+ );
770
+ }
771
+ if (agent.status === 'error' && !agent.workdir) return this.retrySetup(agent.id);
772
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) {
773
+ throw Object.assign(new Error(`Working folder ${agent.workdir} no longer exists`), { status: 409 });
774
+ }
775
+
776
+ if (sessionId) {
777
+ if (!agent.sessions.some((s) => s.id === sessionId)) {
778
+ throw Object.assign(new Error(`Session ${sessionId} does not belong to this agent`), { status: 400 });
779
+ }
780
+ agent.sessionId = sessionId;
781
+ } else if (fresh) {
782
+ agent.sessionId = crypto.randomUUID();
783
+ agent.sessions.push({ id: agent.sessionId, createdAt: now(), starts: 0 });
784
+ }
785
+
786
+ let sid = agent.sessionId;
787
+ // A planning session ran in the holding folder: move its transcript into the
788
+ // workspace so the same session (same ID, full history) continues there.
789
+ const handoff = Boolean(agent.planning && !agent.planning.handedOffAt);
790
+ const engine = engineOf(agent);
791
+ if (handoff) engine.copySession({ fromCwd: agent.planning.dir, toCwd: agent.workdir, fromId: sid });
792
+ let resume = engine.hasSession(agent.workdir, sid);
793
+ if (!resume && !engine.supports.chooseSessionId && agent.lastStartedAt) {
794
+ // The engine picks its own IDs and we stopped before adopting one: find it rather than start over.
795
+ const known = new Set(this.store.list().flatMap((a) => a.sessions.map((s) => s.id)));
796
+ const prior = engine.recentSessions(agent.workdir, Date.parse(agent.lastStartedAt) - 1000).filter((f) => !known.has(f.sessionId));
797
+ if (prior.length === 1) {
798
+ sid = prior[0].sessionId;
799
+ agent.sessions.push({ id: sid, createdAt: now(), starts: 0, adopted: true });
800
+ resume = true;
801
+ }
802
+ }
803
+ const args = engine.launchArgs({
804
+ ...this.launchOptions(agent),
805
+ sessionId: sid,
806
+ resume,
807
+ name: agent.name,
808
+ prompt: resume ? (handoff ? handoffMessage(agent) : null) : agent.intent,
809
+ });
810
+ const proc = this.spawnAgent(agent, agent.workdir, args);
811
+
812
+ const session = agent.sessions.find((s) => s.id === sid);
813
+ if (session) {
814
+ session.starts = (session.starts ?? 0) + 1;
815
+ session.lastStartedAt = now();
816
+ }
817
+ this.patch(agent.id, {
818
+ status: 'running',
819
+ desired: 'running',
820
+ error: null,
821
+ exitCode: null,
822
+ pid: proc.pid,
823
+ lastStartedAt: now(),
824
+ sessions: agent.sessions,
825
+ sessionId: sid,
826
+ ...(handoff ? { planning: { ...agent.planning, ready: false, handedOffAt: now() } } : {}),
827
+ });
828
+ return this.view(this.store.get(agent.id));
829
+ }
830
+
831
+ /** What every launch of this agent passes its engine: options, its brief folder, instructions. */
832
+ launchOptions(agent, { planning = false } = {}) {
833
+ const engine = engineOf(agent);
834
+ let writableDir = null;
835
+ const prompts = [];
836
+ const task = agent.kind !== 'general';
837
+ const withBrief = Boolean(this.config.brief && task);
838
+ if (this.config.reviewConventions && task) prompts.push(conventionsPrompt({ withBrief, rulesFiles: engine.rulesFiles ?? null }));
839
+ if (withBrief) {
840
+ // Let the agent write its brief without a permission prompt: that one folder only.
841
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
842
+ const dir = fs.realpathSync(briefDir(agent.id));
843
+ writableDir = dir;
844
+ prompts.push(briefPrompt(path.join(dir, path.basename(briefPath(agent.id)))));
845
+ if (this.config.inbox !== false) prompts.push(questionsPrompt(path.join(dir, path.basename(questionsPath(agent.id)))));
846
+ }
847
+ if (agent.planReview && task) {
848
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
849
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(planPath(agent.id)));
850
+ writableDir ??= path.dirname(file);
851
+ prompts.push(agent.planReview.status === 'approved' ? planApprovedPrompt(file) : planReviewPrompt(file));
852
+ }
853
+ if (planning) prompts.push(planningPrompt(agent));
854
+ // Appended system prompts last only for the process they're passed to, so they go on every launch.
855
+ return { extra: engine.extraArgs(this.config), permissionMode: agent.permissionMode, model: agent.model, writableDir, instructions: prompts.join('\n\n') || null };
856
+ }
857
+
858
+ /** Spawn the agent's engine in a PTY, reusing its terminal clients and scrollback. */
859
+ spawnAgent(agent, cwd, args, { planning = false } = {}) {
860
+ const engine = engineOf(agent);
861
+ const prev = this.runtimes.get(agent.id) ?? { pty: null, ...loadScrollback(agent.id), restored: true };
862
+ const rt = {
863
+ pty: null,
864
+ planning,
865
+ chunks: prev?.chunks ?? [],
866
+ size: prev?.size ?? 0,
867
+ version: prev?.version ?? 0,
868
+ clients: prev?.clients ?? new Set(),
869
+ cols: prev?.cols ?? 120,
870
+ rows: prev?.rows ?? 34,
871
+ lastOutputAt: null,
872
+ busy: false,
873
+ stopping: false,
874
+ startedAt: Date.now(),
875
+ tail: '',
876
+ attention: null,
877
+ };
878
+ if (prev?.pty === null && rt.size) {
879
+ const note = prev.restored
880
+ ? 'daemon restarted; session resumed'
881
+ : prev.planning && !planning
882
+ ? 'moved into the repository'
883
+ : 'agent restarted';
884
+ this.appendOutput(rt, `\r\n\x1b[2m── ${note} ──\x1b[0m\r\n`);
885
+ }
886
+
887
+ if (this.config.trustAgentFolders) {
888
+ try {
889
+ engine.trust(cwd);
890
+ } catch (err) {
891
+ console.error(`[agentmgr] could not pre-trust ${cwd}: ${err.message}`);
892
+ }
893
+ }
894
+
895
+ let proc;
896
+ try {
897
+ proc = pty.spawn(engine.bin(this.config), args, {
898
+ name: 'xterm-256color',
899
+ cols: rt.cols,
900
+ rows: rt.rows,
901
+ cwd,
902
+ env: this.childEnv(agent),
903
+ });
904
+ } catch (err) {
905
+ this.patch(agent.id, { status: 'error', error: `Failed to launch ${engine.bin(this.config)}: ${err.message}` });
906
+ throw err;
907
+ }
908
+ rt.pty = proc;
909
+ this.runtimes.set(agent.id, rt);
910
+
911
+ proc.onData((data) => {
912
+ rt.linkScan = true;
913
+ rt.lastOutputAt = Date.now();
914
+ rt.tail = (rt.tail + data).slice(-4000);
915
+ this.appendOutput(rt, data);
916
+ this.broadcast(rt, { t: 'o', d: data });
917
+ if (!rt.busy) {
918
+ rt.busy = true;
919
+ rt.waiting = null;
920
+ rt.screenChecked = false;
921
+ const a = this.store.get(agent.id);
922
+ if (a) this.changed(a);
923
+ }
924
+ });
925
+ proc.onExit(({ exitCode, signal }) => {
926
+ clearTimeout(rt.killTimer);
927
+ rt.pty = null;
928
+ rt.busy = false;
929
+ rt.attention = null;
930
+ this.broadcast(rt, { t: 'exit', code: exitCode, signal });
931
+ const a = this.store.get(agent.id);
932
+ if (!a) return;
933
+ if (rt.planning) {
934
+ // The agent's own status (preparing / ready / error) is about the workspace; leave it.
935
+ this.patch(agent.id, { pid: null });
936
+ return;
937
+ }
938
+ this.patch(agent.id, {
939
+ status: rt.stopping ? 'stopped' : 'exited',
940
+ // Claude exiting by itself (e.g. /exit) is a deliberate close; don't auto-resume it.
941
+ ...(rt.stopping ? {} : { desired: 'stopped' }),
942
+ exitCode,
943
+ pid: null,
944
+ stoppedAt: now(),
945
+ });
946
+ this.refresh(agent.id, { withPrs: true }).catch(() => {});
947
+ });
948
+ return proc;
949
+ }
950
+
951
+ // -------------------------------------------------------------- planning
952
+
953
+ /**
954
+ * Run a planning session while the workspace is still being prepared: same
955
+ * session ID, in a holding folder, told that the repo is not there yet.
956
+ */
957
+ startPlanning(ref) {
958
+ const agent = this.mustGet(ref);
959
+ if (this.runtimes.get(agent.id)?.pty) return this.view(agent);
960
+ const waiting = agent.status === 'preparing' || (agent.status === 'error' && !agent.workdir);
961
+ if (!waiting) return this.start(agent.id); // workspace is ready: just run the agent there
962
+ if (!engineOf(agent).supports.planHandoff) {
963
+ throw Object.assign(new Error(`Planning while the repo clones isn't available for ${engineOf(agent).label} agents; it starts once the clone is ready`), { status: 409 });
964
+ }
965
+ if (agent.planning?.handedOffAt) {
966
+ throw Object.assign(new Error('This agent already moved into its workspace'), { status: 409 });
967
+ }
968
+ fs.mkdirSync(paths.planning, { recursive: true });
969
+ const sid = agent.sessionId;
970
+ const engine = engineOf(agent);
971
+ const resume = engine.hasSession(paths.planning, sid);
972
+ const args = engine.launchArgs({ ...this.launchOptions(agent, { planning: true }), sessionId: sid, resume, name: agent.name, prompt: resume ? null : agent.intent });
973
+ const proc = this.spawnAgent(agent, paths.planning, args, { planning: true });
974
+ this.patch(agent.id, {
975
+ desired: 'running',
976
+ pid: proc.pid,
977
+ planning: { dir: paths.planning, startedAt: agent.planning?.startedAt ?? now(), ready: false },
978
+ });
979
+ return this.view(this.store.get(agent.id));
980
+ }
981
+
982
+ /**
983
+ * Move a planning session into its now-ready workspace. Without `force` it
984
+ * only does so when nobody is looking at the terminal and Claude is idle, so
985
+ * it never yanks the session away mid-conversation; otherwise it flags the
986
+ * agent "ready" and waits for Continue in repo.
987
+ */
988
+ async maybeHandoff(id, { force = false } = {}) {
989
+ const agent = this.store.get(id);
990
+ const rt = this.runtimes.get(id);
991
+ if (!agent?.workdir || agent.status === 'preparing' || !(rt?.pty && rt.planning)) return agent && this.view(agent);
992
+ const idleMs = (this.config.handoffIdleSec ?? 5) * 1000;
993
+ const quiet = !rt.clients.size && !rt.busy && Date.now() - (rt.lastOutputAt ?? 0) >= idleMs;
994
+ if (!force && !quiet) {
995
+ if (!agent.planning?.ready) this.patch(id, { planning: { ...agent.planning, ready: true } });
996
+ return this.view(agent);
997
+ }
998
+ if (this.handingOff?.has(id)) return this.view(agent);
999
+ (this.handingOff ??= new Set()).add(id);
1000
+ try {
1001
+ await this.stop(id, { keepDesired: true });
1002
+ return this.start(id);
1003
+ } finally {
1004
+ this.handingOff.delete(id);
1005
+ }
1006
+ }
1007
+
1008
+ /**
1009
+ * Close the claude process. Session IDs are kept so it can be resumed later.
1010
+ * `keepDesired` is for daemon shutdown: the agent comes back on next start.
1011
+ */
1012
+ stop(ref, { timeoutMs = 5000, keepDesired = false } = {}) {
1013
+ const agent = this.mustGet(ref);
1014
+ if (this.runtimes.get(agent.id)?.pty) this.plugins.emit('agent.stopping', { agent: this.auditView(agent) });
1015
+ if (!keepDesired && agent.desired !== 'stopped') this.patch(agent.id, { desired: 'stopped' });
1016
+ const rt = this.runtimes.get(agent.id);
1017
+ if (!rt?.pty) return Promise.resolve(this.view(agent));
1018
+ rt.stopping = true;
1019
+ return new Promise((resolve) => {
1020
+ const done = rt.pty.onExit(() => {
1021
+ done.dispose();
1022
+ resolve(this.view(this.store.get(agent.id) ?? agent));
1023
+ });
1024
+ rt.pty.kill('SIGHUP');
1025
+ rt.killTimer = setTimeout(() => rt.pty?.kill('SIGKILL'), timeoutMs);
1026
+ });
1027
+ }
1028
+
1029
+ /** Daemon shutdown: close everything but remember which agents should come back. */
1030
+ async stopAll({ final = false } = {}) {
1031
+ // On a real shutdown, a workspace that finishes preparing afterwards must not launch its agent.
1032
+ if (final) this.closing = true;
1033
+ for (const id of this.shells.keys()) this.closeShell(id);
1034
+ await Promise.all(
1035
+ [...this.runtimes.entries()].filter(([, rt]) => rt.pty).map(([id]) => this.stop(id, { keepDesired: true })),
1036
+ );
1037
+ }
1038
+
1039
+ /**
1040
+ * Write everything a restart would otherwise lose: each terminal's scrollback,
1041
+ * session IDs Claude switched to (e.g. after /clear), token usage, and the
1042
+ * state file itself (fsynced). Runs every flushSec, on shutdown and on demand.
1043
+ */
1044
+ async flush() {
1045
+ if (this.flushing) return this.flushing;
1046
+ this.flushing = (async () => {
1047
+ let scrollback = 0;
1048
+ const live = [...this.runtimes.entries()].filter(([id, rt]) => rt.pty && this.store.get(id));
1049
+ for (const [id] of live) await this.refresh(id).catch(() => {});
1050
+ fs.mkdirSync(paths.scrollback, { recursive: true });
1051
+ for (const [id, rt] of this.runtimes) {
1052
+ if (!this.store.get(id) || !rt.size || rt.savedVersion === rt.version) continue;
1053
+ const file = scrollbackFile(id);
1054
+ const tmp = `${file}.${process.pid}.tmp`;
1055
+ fs.writeFileSync(tmp, rt.chunks.join(''));
1056
+ fs.renameSync(tmp, file);
1057
+ rt.savedVersion = rt.version;
1058
+ scrollback++;
1059
+ }
1060
+ this.store.save();
1061
+ this.lastFlushAt = now();
1062
+ this.emit('flushed', this.lastFlushAt);
1063
+ return { at: this.lastFlushAt, agents: this.store.list().length, running: live.length, scrollback };
1064
+ })();
1065
+ try {
1066
+ return await this.flushing;
1067
+ } finally {
1068
+ this.flushing = null;
1069
+ }
1070
+ }
1071
+
1072
+ /** Bring back every agent that was running when the daemon last stopped. */
1073
+ async resumeAll({ staggerMs = 400 } = {}) {
1074
+ const resumed = [];
1075
+ for (const agent of this.store.list()) {
1076
+ const retry = agent.setupInterrupted && !agent.workdir;
1077
+ if (agent.desired !== 'running' || (!agent.workdir && !retry) || this.runtimes.get(agent.id)?.pty) continue;
1078
+ try {
1079
+ this.start(agent.id);
1080
+ resumed.push(agent.id);
1081
+ } catch (err) {
1082
+ this.patch(agent.id, { status: 'error', error: `Auto-resume failed: ${err.message}` });
1083
+ }
1084
+ await new Promise((r) => setTimeout(r, staggerMs));
1085
+ }
1086
+ return resumed;
1087
+ }
1088
+
1089
+ childEnv(agent) {
1090
+ const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor' };
1091
+ for (const key of STRIP_ENV) delete env[key];
1092
+ return env;
1093
+ }
1094
+
1095
+ async remove(ref, { deleteWorkspace = false } = {}) {
1096
+ const agent = this.mustGet(ref);
1097
+ this.plugins.check('agent.remove', { agent: this.auditView(agent), deleteWorkspace });
1098
+ this.plugins.emit('agent.removed', { agent: this.auditView(agent), deleteWorkspace });
1099
+ const setup = this.preparing.get(agent.id);
1100
+ if (setup) {
1101
+ // Cancel the clone / checkout; git helpers clean up their partial output.
1102
+ setup.controller.abort();
1103
+ await setup.done.catch(() => {});
1104
+ }
1105
+ await this.stop(agent.id);
1106
+ const warnings = [];
1107
+ if (deleteWorkspace && agent.workdir) {
1108
+ try {
1109
+ if (agent.worktree && agent.sourceDir) {
1110
+ await git.removeWorktree(agent.sourceDir, agent.workdir);
1111
+ } else if (agent.workdir.startsWith(paths.workspaces + path.sep)) {
1112
+ fs.rmSync(agent.workdir, { recursive: true, force: true });
1113
+ } else {
1114
+ warnings.push(`Kept ${agent.workdir}: it is a folder you provided, not one agentmgr created`);
1115
+ }
1116
+ } catch (err) {
1117
+ warnings.push(err.message);
1118
+ }
1119
+ }
1120
+ this.closeShell(agent.id);
1121
+ if (agent.workdir && fs.existsSync(agent.workdir)) await git.deleteRefs(agent.workdir, `refs/agentmgr/${agent.id}/`).catch(() => {});
1122
+ else if (agent.sourceDir && fs.existsSync(agent.sourceDir)) await git.deleteRefs(agent.sourceDir, `refs/agentmgr/${agent.id}/`).catch(() => {});
1123
+ this.changeSets.delete(agent.id);
1124
+ for (const k of this.clashVerdicts.keys()) if (k.split('|').includes(agent.id)) this.clashVerdicts.delete(k);
1125
+ this.stuck.delete(agent.id);
1126
+ this.outbox.delete(agent.id);
1127
+ this.recomputeConflicts();
1128
+ fs.rmSync(briefDir(agent.id), { recursive: true, force: true });
1129
+ fs.rmSync(scrollbackFile(agent.id), { force: true });
1130
+ fs.rmSync(path.join(paths.uploads, agent.id), { recursive: true, force: true });
1131
+ for (const rt of this.shells.get(agent.id)?.values() ?? []) for (const client of rt.clients) client.close?.();
1132
+ this.shells.delete(agent.id);
1133
+ for (const key of this.cursors.keys()) {
1134
+ if (agent.sessions.some((s) => key.startsWith(`${s.id}:`) || key.includes(`/${s.id}/subagents/`))) {
1135
+ this.cursors.delete(key);
1136
+ }
1137
+ }
1138
+ for (const client of this.runtimes.get(agent.id)?.clients ?? []) client.close?.();
1139
+ this.runtimes.delete(agent.id);
1140
+ this.store.remove(agent.id);
1141
+ this.emit('removed', agent.id);
1142
+ return { id: agent.id, warnings };
1143
+ }
1144
+
1145
+ update(ref, fields) {
1146
+ const agent = this.mustGet(ref);
1147
+ const allowed = {};
1148
+ for (const key of ['name', 'notes', 'permissionMode', 'model', 'project']) if (key in fields) allowed[key] = fields[key];
1149
+ if ('priority' in fields) {
1150
+ const p = parsePriority(fields.priority, null);
1151
+ if (p === null) throw Object.assign(new Error('priority must be P0, P1, P2 or P3'), { status: 400 });
1152
+ allowed.priority = p;
1153
+ }
1154
+ if ('project' in allowed) allowed.project = String(allowed.project ?? '').trim() || null;
1155
+ return this.view(this.patch(agent.id, allowed));
1156
+ }
1157
+
1158
+ // --------------------------------------------------------------- terminal
1159
+
1160
+ appendOutput(rt, data) {
1161
+ rt.version = (rt.version ?? 0) + 1;
1162
+ rt.chunks.push(data);
1163
+ rt.size += data.length;
1164
+ const max = this.config.scrollbackBytes;
1165
+ while (rt.size > max && rt.chunks.length > 1) rt.size -= rt.chunks.shift().length;
1166
+ }
1167
+
1168
+ broadcast(rt, msg) {
1169
+ for (const client of rt.clients) client.send(msg);
1170
+ }
1171
+
1172
+ /** Attach a terminal client ({ send(msg), close() }). Returns the scrollback and a detach fn. */
1173
+ attach(ref, client) {
1174
+ const agent = this.mustGet(ref);
1175
+ this.plugins.check('terminal.open', { agent: this.auditView(agent), kind: 'claude' });
1176
+ let rt = this.runtimes.get(agent.id);
1177
+ if (!rt) {
1178
+ rt = { pty: null, ...loadScrollback(agent.id), restored: true, clients: new Set(), cols: 120, rows: 34 };
1179
+ this.runtimes.set(agent.id, rt);
1180
+ }
1181
+ rt.clients.add(client);
1182
+ this.changed(agent);
1183
+ return {
1184
+ backlog: rt.chunks.join(''),
1185
+ running: Boolean(rt.pty),
1186
+ detach: () => {
1187
+ rt.clients.delete(client);
1188
+ const a = this.store.get(agent.id);
1189
+ if (a) this.changed(a);
1190
+ },
1191
+ };
1192
+ }
1193
+
1194
+ /** The runtime behind a terminal kind: 'claude', or 'shell' / 'shell:N' for shell N (default 1). */
1195
+ termRuntime(id, kind) {
1196
+ const n = shellNumber(kind);
1197
+ return n ? this.shells.get(id)?.get(n) : this.runtimes.get(id);
1198
+ }
1199
+
1200
+ write(id, data, kind = 'claude') {
1201
+ this.termRuntime(id, kind)?.pty?.write(data);
1202
+ }
1203
+
1204
+ resize(id, cols, rows, kind = 'claude') {
1205
+ const rt = this.termRuntime(id, kind);
1206
+ if (!rt || !(cols > 0 && rows > 0)) return;
1207
+ rt.cols = cols;
1208
+ rt.rows = rows;
1209
+ try {
1210
+ rt.pty?.resize(cols, rows);
1211
+ } catch {}
1212
+ }
1213
+
1214
+ // ------------------------------------------------------- ancillary shells
1215
+
1216
+ /** The agent's shells (number -> runtime), created on first use. */
1217
+ shellsOf(agentId) {
1218
+ let m = this.shells.get(agentId);
1219
+ if (!m) this.shells.set(agentId, (m = new Map()));
1220
+ return m;
1221
+ }
1222
+
1223
+ /** Numbers of the agent's shells that are running, ascending. */
1224
+ shellNumbers(agentId) {
1225
+ return [...(this.shells.get(agentId)?.entries() ?? [])].filter(([, rt]) => rt.pty).map(([n]) => n).sort((a, b) => a - b);
1226
+ }
1227
+
1228
+ /** Start (if needed) login shell number `n` in the agent's folder, for running commands by hand. */
1229
+ openShell(ref, n = 1) {
1230
+ const agent = this.mustGet(ref);
1231
+ const shells = this.shellsOf(agent.id);
1232
+ const prev = shells.get(n);
1233
+ if (prev?.pty) return prev;
1234
+ if (!agent.workdir || !fs.existsSync(agent.workdir)) {
1235
+ throw Object.assign(new Error('The working folder is not ready yet'), { status: 409 });
1236
+ }
1237
+ const rt = {
1238
+ pty: null,
1239
+ chunks: prev?.chunks ?? [],
1240
+ size: prev?.size ?? 0,
1241
+ clients: prev?.clients ?? new Set(),
1242
+ cols: prev?.cols ?? 120,
1243
+ rows: prev?.rows ?? 34,
1244
+ };
1245
+ if (rt.size) this.appendOutput(rt, '\r\n\x1b[2m── new shell ──\x1b[0m\r\n');
1246
+ const proc = pty.spawn(this.config.shell, ['-l'], {
1247
+ name: 'xterm-256color',
1248
+ cols: rt.cols,
1249
+ rows: rt.rows,
1250
+ cwd: agent.workdir,
1251
+ env: this.childEnv(agent),
1252
+ });
1253
+ rt.pty = proc;
1254
+ shells.set(n, rt);
1255
+ proc.onData((data) => {
1256
+ rt.linkScan = true;
1257
+ this.appendOutput(rt, data);
1258
+ this.broadcast(rt, { t: 'o', d: data });
1259
+ });
1260
+ proc.onExit(({ exitCode }) => {
1261
+ rt.pty = null;
1262
+ this.broadcast(rt, { t: 'exit', code: exitCode });
1263
+ const a = this.store.get(agent.id);
1264
+ if (a) this.changed(a);
1265
+ });
1266
+ this.changed(agent);
1267
+ return rt;
1268
+ }
1269
+
1270
+ /** Lowest shell number the agent isn't using. */
1271
+ nextShellNumber(agentId) {
1272
+ const used = new Set(this.shellNumbers(agentId));
1273
+ let n = 1;
1274
+ while (used.has(n)) n++;
1275
+ return n;
1276
+ }
1277
+
1278
+ attachShell(ref, client, n = 1) {
1279
+ const agent = this.mustGet(ref);
1280
+ this.plugins.check('terminal.open', { agent: this.auditView(agent), kind: `shell:${n}` });
1281
+ const rt = this.openShell(agent.id, n);
1282
+ rt.clients.add(client);
1283
+ return {
1284
+ backlog: rt.chunks.join(''),
1285
+ running: true,
1286
+ detach: () => rt.clients.delete(client),
1287
+ };
1288
+ }
1289
+
1290
+ /** Close one shell, or all of the agent's shells when `n` is omitted. */
1291
+ closeShell(ref, n) {
1292
+ const id = this.store.resolve(ref)?.id ?? ref;
1293
+ for (const [num, rt] of this.shells.get(id) ?? []) {
1294
+ if (n === undefined || num === n) rt.pty?.kill('SIGHUP');
1295
+ }
1296
+ return { ok: true };
1297
+ }
1298
+
1299
+ /** Forget a closed shell's scrollback so its tab goes away. */
1300
+ dropShell(ref, n) {
1301
+ const id = this.store.resolve(ref)?.id ?? ref;
1302
+ const rt = this.shells.get(id)?.get(n);
1303
+ if (rt?.pty) rt.pty.kill('SIGHUP');
1304
+ for (const client of rt?.clients ?? []) client.close?.();
1305
+ this.shells.get(id)?.delete(n);
1306
+ const a = this.store.get(id);
1307
+ if (a) this.changed(a);
1308
+ return { ok: true };
1309
+ }
1310
+
1311
+ // --------------------------------------------------------------- browser tabs
1312
+
1313
+ /** Open a browser tab on an address (kept with the agent, so other devices see it too). */
1314
+ /**
1315
+ * Browser tabs: { n, url, mode } where mode "live" is a real browser on this machine streamed
1316
+ * to the tab, and "lite" loads the page in a frame (relayed to other devices). `raw` keeps an
1317
+ * address the browser itself reported (a popup's about:blank, a file: page) as it is.
1318
+ */
1319
+ addBrowser(ref, input, { mode, raw = false } = {}) {
1320
+ const agent = this.mustGet(ref);
1321
+ const url = raw ? String(input) : parseUrl(input).href;
1322
+ const tabs = agent.browsers ?? [];
1323
+ let n = 1;
1324
+ while (tabs.some((t) => t.n === n)) n++;
1325
+ const tab = { n, url, ...(mode === 'live' || mode === 'lite' ? { mode } : {}) };
1326
+ this.patch(agent.id, { browsers: [...tabs, tab] });
1327
+ return tab;
1328
+ }
1329
+
1330
+ setBrowser(ref, n, input, { mode, raw = false } = {}) {
1331
+ const agent = this.mustGet(ref);
1332
+ const cur = (agent.browsers ?? []).find((t) => t.n === n);
1333
+ if (!cur) throw Object.assign(new Error(`No browser tab ${n}`), { status: 404 });
1334
+ const url = input === undefined ? cur.url : raw ? String(input) : parseUrl(input).href;
1335
+ const tab = { ...cur, url, ...(mode === 'live' || mode === 'lite' ? { mode } : {}) };
1336
+ if (JSON.stringify(tab) !== JSON.stringify(cur)) this.patch(agent.id, { browsers: agent.browsers.map((t) => (t.n === n ? tab : t)) });
1337
+ return tab;
1338
+ }
1339
+
1340
+ dropBrowser(ref, n) {
1341
+ const agent = this.mustGet(ref);
1342
+ this.patch(agent.id, { browsers: (agent.browsers ?? []).filter((t) => t.n !== n) });
1343
+ return { ok: true };
1344
+ }
1345
+
1346
+ /** Local addresses the agent's session or shells printed recently, as suggestions. */
1347
+ localUrls(ref) {
1348
+ const agent = this.mustGet(ref);
1349
+ const tail = (rt) => (rt?.chunks ?? []).join('').slice(-200_000);
1350
+ const text = [...(this.shells.get(agent.id)?.values() ?? [])].map(tail).join('\n') + '\n' + tail(this.runtimes.get(agent.id));
1351
+ return findLocalUrls(text);
1352
+ }
1353
+
1354
+ // --------------------------------------------------- sign-in links (CLI OAuth)
1355
+
1356
+ /**
1357
+ * Terminals that printed something since the last look: a CLI's sign-in link (`railway login`,
1358
+ * `gh auth login --web`...) is raised so the UI can open it in a real browser window. Sign-in
1359
+ * pages refuse to show inside another page, and their callback goes to a port on this machine.
1360
+ */
1361
+ scanSignIns() {
1362
+ const look = (agentId, rt, terminal) => {
1363
+ if (!rt?.linkScan) return;
1364
+ rt.linkScan = false;
1365
+ const [link] = findSignInLinks(rt.chunks.join('').slice(-12_000), rt.cols);
1366
+ if (link) this.raiseSignIn(agentId, link, terminal);
1367
+ };
1368
+ for (const [id, rt] of this.runtimes) look(id, rt, engineOf(this.store.get(id) ?? {}).label);
1369
+ for (const [id, shells] of this.shells) for (const [n, rt] of shells) look(id, rt, `Shell ${n}`);
1370
+ }
1371
+
1372
+ raiseSignIn(agentId, link, terminal) {
1373
+ const seen = this.seenLinks.get(agentId) ?? new Set();
1374
+ this.seenLinks.set(agentId, seen);
1375
+ if (seen.has(link.url)) return false;
1376
+ seen.add(link.url);
1377
+ this.signIns.set(agentId, { ...link, terminal, at: now(), finished: null });
1378
+ const a = this.store.get(agentId);
1379
+ if (a) this.changed(a);
1380
+ return true;
1381
+ }
1382
+
1383
+ /** The sign-in link the person should open, for 15 minutes (a CLI waits about that long). */
1384
+ signInView(agent) {
1385
+ const s = this.signIns.get(agent.id);
1386
+ if (!s || Date.now() - Date.parse(s.at) > 15 * 60_000) return null;
1387
+ return s;
1388
+ }
1389
+
1390
+ /** A sign-in link pasted into a browser tab: raise it like one a terminal printed. */
1391
+ addSignIn(ref, url) {
1392
+ const agent = this.mustGet(ref);
1393
+ const [link] = findSignInLinks(String(url ?? ''));
1394
+ if (!link) throw Object.assign(new Error('That is not a sign-in link that returns to this machine'), { status: 400 });
1395
+ this.seenLinks.get(agent.id)?.delete(link.url);
1396
+ this.raiseSignIn(agent.id, link, 'Browser');
1397
+ return this.view(this.store.get(agent.id));
1398
+ }
1399
+
1400
+ dismissSignIn(ref) {
1401
+ const agent = this.mustGet(ref);
1402
+ this.signIns.delete(agent.id);
1403
+ this.changed(agent);
1404
+ return this.view(agent);
1405
+ }
1406
+
1407
+ /**
1408
+ * Finish a sign-in from another device: after approving, that device's browser lands on the
1409
+ * CLI's callback (http://127.0.0.1:PORT/...), which only exists on this machine. The person
1410
+ * pastes that address and it is requested here, only on the port the link named.
1411
+ */
1412
+ async finishSignIn(ref, input) {
1413
+ const agent = this.mustGet(ref);
1414
+ const s = this.signInView(agent);
1415
+ if (!s) throw Object.assign(new Error('No sign-in is waiting for this agent'), { status: 409 });
1416
+ const u = parseCallback(input, s.port);
1417
+ if (!u) throw Object.assign(new Error(`Paste the address your browser landed on; it starts with ${s.callback}`), { status: 400 });
1418
+ const { default: http } = await import(u.protocol === 'https:' ? 'node:https' : 'node:http');
1419
+ const result = await new Promise((resolve) => {
1420
+ const req = http.get(u, { timeout: 10_000, rejectUnauthorized: false }, (res) => {
1421
+ let body = '';
1422
+ res.on('data', (d) => body.length < 4000 && (body += d));
1423
+ res.on('end', () => resolve({ ok: res.statusCode < 400, status: res.statusCode, text: body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200) }));
1424
+ });
1425
+ req.on('timeout', () => req.destroy(new Error('timed out')));
1426
+ req.on('error', (e) => resolve({ ok: false, status: 0, text: e.code === 'ECONNREFUSED' ? 'Nothing is listening there any more; the CLI may have timed out. Run the login again.' : e.message }));
1427
+ });
1428
+ this.signIns.set(agent.id, { ...s, finished: { ...result, at: now() } });
1429
+ this.changed(agent);
1430
+ return this.view(this.store.get(agent.id));
1431
+ }
1432
+
1433
+ // ------------------------------------------------- sessions started elsewhere
1434
+
1435
+ /** Claude Code sessions started outside Agent Manager (in a terminal), to continue here. */
1436
+ scanSessions({ days = 30 } = {}) {
1437
+ const known = new Set(this.store.list().flatMap((a) => a.sessions.map((x) => x.id)));
1438
+ return scanClaudeSessions({ days: Math.max(1, Math.min(365, Number(days) || 30)), known, excludeDir: paths.home });
1439
+ }
1440
+
1441
+ /**
1442
+ * Continue sessions as agents, in the folder each ran in. One still open in a terminal is
1443
+ * refused (two places writing one conversation mixes it up) unless `copy`: then the agent
1444
+ * continues a copy under a new session ID and the terminal keeps the original.
1445
+ */
1446
+ importSessions(list, { start = true, copy = false } = {}) {
1447
+ const wanted = new Set((Array.isArray(list) ? list : []).map((x) => String(x?.sessionId ?? x)));
1448
+ if (!wanted.size) throw Object.assign(new Error('Pick at least one session'), { status: 400 });
1449
+ const found = this.scanSessions({ days: 365 }).filter((x) => wanted.has(x.sessionId));
1450
+ const out = [];
1451
+ for (const s of found) {
1452
+ if (!s.exists) {
1453
+ out.push({ sessionId: s.sessionId, error: `Its folder ${s.cwd} no longer exists` });
1454
+ continue;
1455
+ }
1456
+ if (s.inUse && !copy) {
1457
+ out.push({ sessionId: s.sessionId, error: 'Still open in a terminal: close it there first, or continue a copy' });
1458
+ continue;
1459
+ }
1460
+ let sessionId = s.sessionId;
1461
+ if (s.inUse) {
1462
+ sessionId = crypto.randomUUID();
1463
+ ENGINES.claude.copySession({ fromCwd: s.cwd, toCwd: s.cwd, fromId: s.sessionId, toId: sessionId });
1464
+ }
1465
+ const intent = (s.title && s.title.length > 8 ? s.title : s.firstAsk).replace(/\s+/g, ' ').slice(0, 300);
1466
+ const agent = this.create({
1467
+ intent,
1468
+ dir: s.cwd,
1469
+ worktree: false,
1470
+ engine: 'claude',
1471
+ start,
1472
+ sessionId,
1473
+ imported: { from: 'terminal', sessionId: s.sessionId, copy: sessionId !== s.sessionId, at: now() },
1474
+ });
1475
+ out.push({ sessionId: s.sessionId, agentId: agent.id, name: agent.name });
1476
+ }
1477
+ for (const id of wanted) if (!found.some((x) => x.sessionId === id)) out.push({ sessionId: id, error: 'No such session (or it belongs to an agent already)' });
1478
+ return out;
1479
+ }
1480
+
1481
+ /** Save a file the user attached in the UI, so its path can be handed to Claude. */
1482
+ saveUpload(ref, name, data) {
1483
+ const agent = this.mustGet(ref);
1484
+ const safe = path.basename(String(name || 'file')).replace(/[^\w.@+-]+/g, '_').slice(-120) || 'file';
1485
+ const dir = path.join(paths.uploads, agent.id);
1486
+ fs.mkdirSync(dir, { recursive: true });
1487
+ const file = path.join(dir, `${new Date().toISOString().replace(/[:.]/g, '-')}-${safe}`);
1488
+ fs.writeFileSync(file, data);
1489
+ return { path: file, size: data.length };
1490
+ }
1491
+
1492
+ // --------------------------------------------------------------- tracking
1493
+
1494
+ addLink(ref, { type, value, title }) {
1495
+ const agent = this.mustGet(ref);
1496
+ value = (value ?? '').trim();
1497
+ if (!value) throw Object.assign(new Error('Link value is required'), { status: 400 });
1498
+ if (type === 'pr') {
1499
+ const pr = { ...prFromUrl(value, 'manual'), ...(title ? { title } : {}) };
1500
+ agent.prs[pr.url] = { ...agent.prs[pr.url], ...pr };
1501
+ agent.dismissed = agent.dismissed.filter((k) => k !== pr.url);
1502
+ } else if (type === 'bug') {
1503
+ const bug = { ...bugFromRef(value, 'manual'), ...(title ? { title } : {}) };
1504
+ agent.bugs[bug.key] = { ...agent.bugs[bug.key], ...bug };
1505
+ agent.dismissed = agent.dismissed.filter((k) => k !== bug.key);
1506
+ } else {
1507
+ throw Object.assign(new Error('type must be "pr" or "bug"'), { status: 400 });
1508
+ }
1509
+ this.store.save();
1510
+ this.changed(agent);
1511
+ if (type === 'pr') this.refresh(agent.id, { withPrs: true }).catch(() => {});
1512
+ return this.view(agent);
1513
+ }
1514
+
1515
+ removeLink(ref, { type, key }) {
1516
+ const agent = this.mustGet(ref);
1517
+ const bag = type === 'pr' ? agent.prs : agent.bugs;
1518
+ if (bag[key]) {
1519
+ delete bag[key];
1520
+ if (!agent.dismissed.includes(key)) agent.dismissed.push(key);
1521
+ this.store.save();
1522
+ this.changed(agent);
1523
+ }
1524
+ return this.view(agent);
1525
+ }
1526
+
1527
+ mergeLinks(agent, bag, items, keyOf) {
1528
+ let changed = false;
1529
+ for (const item of items) {
1530
+ const key = keyOf(item);
1531
+ if (!key || agent.dismissed.includes(key)) continue;
1532
+ const cur = bag[key];
1533
+ if (!cur) {
1534
+ bag[key] = item;
1535
+ changed = true;
1536
+ continue;
1537
+ }
1538
+ const merged = { ...cur };
1539
+ for (const [k, v] of Object.entries(item)) {
1540
+ if (k === 'source') continue;
1541
+ if (v != null && merged[k] !== v) merged[k] = v;
1542
+ }
1543
+ if ((SOURCE_RANK[item.source] ?? 0) > (SOURCE_RANK[cur.source] ?? 0)) merged.source = item.source;
1544
+ if (JSON.stringify(merged) !== JSON.stringify(cur)) {
1545
+ bag[key] = merged;
1546
+ changed = true;
1547
+ }
1548
+ }
1549
+ return changed;
1550
+ }
1551
+
1552
+ /**
1553
+ * Claude may switch to a new session ID mid-run (e.g. /clear). Adopt a new
1554
+ * transcript in this agent's folder if nothing else claims it.
1555
+ */
1556
+ adoptSessions(agent) {
1557
+ const rt = this.runtimes.get(agent.id);
1558
+ if (!rt?.pty) return false;
1559
+ const known = new Set(this.store.list().flatMap((a) => a.sessions.map((s) => s.id)));
1560
+ const engine = engineOf(agent);
1561
+ const candidates = engine.recentSessions(agent.workdir, rt.startedAt - 1000).filter((f) => !known.has(f.sessionId));
1562
+ if (candidates.length !== 1) return false;
1563
+ const [cand] = candidates;
1564
+ // Not someone else's: a headless run (claude -p) in this folder, or a session a claude in a
1565
+ // terminal has open (or may have: a plain claude running in this same folder).
1566
+ if (agent.engine === 'claude' || !agent.engine) {
1567
+ try {
1568
+ const fd = fs.openSync(engine.sessionFile(agent.workdir, cand.sessionId), 'r');
1569
+ const buf = Buffer.alloc(8192);
1570
+ fs.readSync(fd, buf, 0, buf.length, 0);
1571
+ fs.closeSync(fd);
1572
+ if (/"entrypoint":"(?!cli")/.test(buf.toString('utf8'))) return false;
1573
+ } catch {}
1574
+ const running = runningClaude();
1575
+ let here = agent.workdir;
1576
+ try {
1577
+ here = fs.realpathSync(agent.workdir);
1578
+ } catch {}
1579
+ if (running.ids.has(cand.sessionId) || running.cwds.has(here) || running.cwds.has(agent.workdir)) return false;
1580
+ }
1581
+ let currentMtime = 0;
1582
+ try {
1583
+ currentMtime = fs.statSync(engine.sessionFile(agent.workdir, agent.sessionId)).mtimeMs;
1584
+ } catch {}
1585
+ if (currentMtime > cand.mtimeMs) return false;
1586
+ agent.sessions.push({ id: cand.sessionId, createdAt: now(), starts: 1, lastStartedAt: now(), adopted: true });
1587
+ agent.sessionId = cand.sessionId;
1588
+ return true;
1589
+ }
1590
+
1591
+ /** Pick up changes to the agent's brief file. */
1592
+ reloadBrief(id) {
1593
+ const agent = this.store.get(id);
1594
+ if (!agent) return;
1595
+ const brief = loadBrief(id, agent.brief);
1596
+ if (brief) {
1597
+ this.patch(id, { brief });
1598
+ // The agent says it is done: have the judge check the work before the person looks.
1599
+ if (brief.status === 'done' && agent.brief?.status !== 'done' && this.judge.enabled) this.requestReview(id, { trigger: 'brief' }).catch(() => {});
1600
+ }
1601
+ if (agent.planReview) {
1602
+ const file = loadPlanFile(id, agent.planReview);
1603
+ // A new or revised plan waits for review again, unless it was already approved (then it's a progress update).
1604
+ if (file) this.patch(id, { planReview: { ...agent.planReview, ...file, status: agent.planReview.status === 'approved' ? 'approved' : 'review' } });
1605
+ }
1606
+ }
1607
+
1608
+ // -------------------------------------------------------------- plan review
1609
+
1610
+ /** Approve the plan (optionally with notes); the agent starts implementing. */
1611
+ approvePlan(ref, note, { force = false } = {}) {
1612
+ const agent = this.mustGet(ref);
1613
+ if (!agent.planReview || agent.planReview.status === 'approved' || (!force && agent.planReview.status !== 'review')) throw Object.assign(new Error('There is no plan waiting for review'), { status: 409 });
1614
+ this.patch(agent.id, { planReview: { ...agent.planReview, status: 'approved', decidedAt: now(), note: note?.trim() || null } });
1615
+ return this.tell(agent.id, `Plan approved. Go ahead and implement it.${note?.trim() ? `\n\nNotes from the review:\n${note.trim()}` : ''}`);
1616
+ }
1617
+
1618
+ /** Send the plan back with what to change; the agent revises PLAN.md and waits again. */
1619
+ requestPlanChanges(ref, note) {
1620
+ const agent = this.mustGet(ref);
1621
+ if (!agent.planReview || agent.planReview.status === 'approved') throw Object.assign(new Error('There is no plan waiting for review'), { status: 409 });
1622
+ if (!note?.trim()) throw Object.assign(new Error('Say what should change'), { status: 400 });
1623
+ this.patch(agent.id, { planReview: { ...agent.planReview, status: 'changes', decidedAt: now(), note: note.trim() } });
1624
+ return this.tell(agent.id, `Plan changes requested. Revise the plan file and wait for approval again:\n${note.trim()}`);
1625
+ }
1626
+
1627
+ /** Turn plan review on (before the agent has implemented anything) or off (no longer waits). */
1628
+ setPlanReview(ref, on) {
1629
+ const agent = this.mustGet(ref);
1630
+ if (on && !agent.planReview) {
1631
+ this.patch(agent.id, { planReview: { status: 'writing' } });
1632
+ const file = path.join(briefDir(agent.id), path.basename(planPath(agent.id)));
1633
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
1634
+ // A running session got its instructions at launch; tell it now.
1635
+ if (this.runtimes.get(agent.id)?.pty) return this.tell(agent.id, `Change of process: ${planReviewPrompt(file)} If you already changed files, list them in the plan.`);
1636
+ }
1637
+ if (!on && agent.planReview && agent.planReview.status !== 'approved') return this.approvePlan(agent.id, null, { force: true });
1638
+ return this.view(this.store.get(agent.id));
1639
+ }
1640
+
1641
+ /**
1642
+ * Plain-language explanation of the intent and the brief's problem / solution, from a
1643
+ * separate one-shot Claude call with no tools and no MCP servers. The agent's own
1644
+ * session is never touched, so this never interrupts or adds context to its work.
1645
+ */
1646
+ explain(ref) {
1647
+ return this.summarize(ref, 'explain');
1648
+ }
1649
+
1650
+ /** Why / What / How / Now in three tidy points each. */
1651
+ insights(ref) {
1652
+ return this.summarize(ref, 'insights');
1653
+ }
1654
+
1655
+ /**
1656
+ * At most `summaryConcurrency` one-off Claude calls (documents, explain,
1657
+ * insights) at once; the rest wait. Resolves to a release function.
1658
+ */
1659
+ summarySlot() {
1660
+ this.summaryRunning ??= 0;
1661
+ this.summaryQueue ??= [];
1662
+ const max = this.config.summaryConcurrency ?? 2;
1663
+ const release = () => {
1664
+ this.summaryRunning--;
1665
+ this.summaryQueue.shift()?.();
1666
+ };
1667
+ if (this.summaryRunning < max) {
1668
+ this.summaryRunning++;
1669
+ return Promise.resolve(release);
1670
+ }
1671
+ return new Promise((resolve) =>
1672
+ this.summaryQueue.push(() => {
1673
+ this.summaryRunning++;
1674
+ resolve(release);
1675
+ }),
1676
+ );
1677
+ }
1678
+
1679
+ /** Start one or more summaries without waiting; returns the agent view right away. */
1680
+ summarizeInBackground(ref, kinds) {
1681
+ const agent = this.mustGet(ref);
1682
+ for (const kind of kinds) {
1683
+ if (!SUMMARIES[kind]) throw Object.assign(new Error(`Unknown document "${kind}"`), { status: 400 });
1684
+ }
1685
+ for (const kind of kinds) this.summarize(agent.id, kind).catch(() => {}); // errors are stored on the agent
1686
+ return this.view(this.store.get(agent.id));
1687
+ }
1688
+
1689
+ /** A stakeholder document: analysis, design, flow or proposal. */
1690
+ document(ref, kind) {
1691
+ if (!SUMMARIES[kind]?.doc) throw Object.assign(new Error(`Unknown document "${kind}"`), { status: 400 });
1692
+ return this.summarize(ref, kind);
1693
+ }
1694
+
1695
+ summarize(ref, kind) {
1696
+ const agent = this.mustGet(ref);
1697
+ this.explaining ??= new Map();
1698
+ const key = `${kind}:${agent.id}`;
1699
+ if (this.explaining.has(key)) return this.explaining.get(key);
1700
+ this.patch(agent.id, summaryPatch(agent, kind, { ...getSummary(agent, kind), pending: true, error: null }));
1701
+ const run = this.summarySlot()
1702
+ .then((release) =>
1703
+ this.explainContext(agent)
1704
+ .then((ctx) => (SUMMARIES[kind].run ? this[SUMMARIES[kind].run](agent, ctx) : this.runExplain(agent, { ...ctx, agentName: agent.name }, kind)))
1705
+ .finally(release),
1706
+ )
1707
+ .catch((e) => {
1708
+ const cur = this.store.get(agent.id);
1709
+ if (cur) this.patch(agent.id, summaryPatch(cur, kind, { ...getSummary(cur, kind), pending: false, error: e.message }));
1710
+ throw e;
1711
+ })
1712
+ .finally(() => this.explaining.delete(key));
1713
+ this.explaining.set(key, run);
1714
+ return run;
1715
+ }
1716
+
1717
+ /** What the agent is actually doing: its session, repo changes, live status and brief. */
1718
+ async explainContext(agent) {
1719
+ const v = this.view(agent);
1720
+ const file = briefPath(agent.id);
1721
+ const briefMarkdown = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
1722
+ const planningOnly = agent.planning && !agent.planning.handedOffAt && !agent.workdir;
1723
+ const sessionDir = planningOnly ? agent.planning.dir : agent.workdir;
1724
+ const engine = engineOf(agent);
1725
+ const { digest } = sessionDir ? engine.digest(engine.sessionFile(sessionDir, agent.sessionId)) : { digest: '' };
1726
+ const phase = v.runtime.planning ? 'planning while the workspace is prepared' : agent.status;
1727
+ const status = [
1728
+ `status: ${phase}${v.runtime.running ? (v.runtime.busy ? ' (working right now)' : ' (idle, waiting for the next instruction)') : ''}`,
1729
+ `priority: P${agent.priority ?? 2}`,
1730
+ v.runtime.attention ? `blocked on: ${v.runtime.attention} (waiting for the user to answer in the terminal)` : null,
1731
+ v.runtime.waiting ? `seems to be waiting on the user: ${v.runtime.waiting.summary}` : null,
1732
+ agent.error ? `error: ${agent.error}` : null,
1733
+ `last activity: ${v.runtime.lastOutputAt ?? agent.sessions.find((s) => s.id === agent.sessionId)?.lastActivity ?? 'unknown'}`,
1734
+ agent.repo ? `repo: ${agent.repo}` : null,
1735
+ agent.git?.branch ? `branch: ${agent.git.branch}${agent.baseRef ? ` (branched from ${agent.baseRef})` : ''}` : null,
1736
+ v.prs.length ? `PRs: ${v.prs.map((p) => `${p.url}${p.state ? ` [${p.state}]` : ''}${p.title ? ` ${p.title}` : ''}`).join('; ')}` : null,
1737
+ v.bugs.length ? `issues: ${v.bugs.map((b) => b.key).join(', ')}` : null,
1738
+ ]
1739
+ .filter(Boolean)
1740
+ .join('\n');
1741
+ let repo = '';
1742
+ if (agent.workdir) {
1743
+ const sha = agent.baseRef?.split(' @ ')[1];
1744
+ const ch = await git.changeSummary(agent.workdir, sha).catch(() => null);
1745
+ if (ch) {
1746
+ repo = [
1747
+ ch.commits.length ? `commits since branching:\n${ch.commits.join('\n')}` : 'no commits since branching',
1748
+ ch.uncommitted.length ? `uncommitted changes:\n${ch.uncommitted.join('\n')}` : 'no uncommitted changes',
1749
+ ch.diffstat ? `diffstat:\n${ch.diffstat}` : '',
1750
+ ]
1751
+ .filter(Boolean)
1752
+ .join('\n\n');
1753
+ }
1754
+ }
1755
+ return { intent: agent.intent, status, digest, repo, briefMarkdown };
1756
+ }
1757
+
1758
+ /** The engine (and model) that writes an agent's summaries: its own when it can make a one-shot call, else Claude Code. */
1759
+ writerFor(agent) {
1760
+ const engine = engineOf(agent).supports.oneShot ? engineOf(agent) : engineOf(DEFAULT_ENGINE);
1761
+ return { engine, model: engine.id === DEFAULT_ENGINE ? this.config.explainModel : this.config.engines?.[engine.id]?.explainModel };
1762
+ }
1763
+
1764
+ /**
1765
+ * Who double-checks the writer: `critique: { engine, model }` from config.json if set, else
1766
+ * another installed engine (a different provider sees different things), else the same
1767
+ * engine with another model.
1768
+ */
1769
+ criticFor(writer) {
1770
+ const pick = this.config.critique ?? {};
1771
+ const usable = (e) => e?.supports.oneShot && installed(e, this.config);
1772
+ if (pick.engine && usable(ENGINES[pick.engine])) return { engine: ENGINES[pick.engine], model: pick.model ?? this.config.engines?.[pick.engine]?.explainModel };
1773
+ const other = Object.values(ENGINES).find((e) => e.id !== writer.engine.id && usable(e));
1774
+ if (other) return { engine: other, model: other.id === DEFAULT_ENGINE ? this.config.explainModel : this.config.engines?.[other.id]?.explainModel };
1775
+ if (writer.engine.id === DEFAULT_ENGINE) return { engine: writer.engine, model: pick.model ?? (/opus/i.test(writer.model ?? '') ? 'sonnet' : 'opus') };
1776
+ return { engine: writer.engine, model: pick.model ?? writer.model };
1777
+ }
1778
+
1779
+ runExplain(agent, ctx, kind = 'explain') {
1780
+ const { prompt } = SUMMARIES[kind];
1781
+ return this.oneShot(agent, prompt(ctx), this.writerFor(agent)).then((markdown) => {
1782
+ const cur = this.store.get(agent.id);
1783
+ if (!cur) return null;
1784
+ return this.view(
1785
+ this.patch(
1786
+ agent.id,
1787
+ summaryPatch(cur, kind, { markdown, at: now(), briefUpdatedAt: cur.brief?.updatedAt ?? null, pending: false, error: null }),
1788
+ ),
1789
+ );
1790
+ });
1791
+ }
1792
+
1793
+ /** One tool-less, read-only call to an engine; resolves to its text output. */
1794
+ oneShot(agent, text, { engine, model, timeoutMs = 300_000 }) {
1795
+ // Some engines take the prompt as an argument instead of on stdin.
1796
+ const args = [...engine.extraArgs(this.config), ...engine.oneShotArgs(this.config, { model, prompt: text })];
1797
+ return new Promise((resolve, reject) => {
1798
+ const child = spawn(engine.bin(this.config), args, { cwd: paths.home, env: this.childEnv(agent), stdio: ['pipe', 'pipe', 'pipe'] });
1799
+ let out = '';
1800
+ let err = '';
1801
+ const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
1802
+ child.stdout.on('data', (d) => (out += d));
1803
+ child.stderr.on('data', (d) => (err += d));
1804
+ child.on('error', reject);
1805
+ child.on('close', (code) => {
1806
+ clearTimeout(timer);
1807
+ if (code === 0 && out.trim()) resolve(out.trim());
1808
+ else reject(new Error(`${engine.label} one-shot call failed (exit ${code}): ${(err || out).trim().slice(-300)}`));
1809
+ });
1810
+ child.stdin.end(engine.oneShotStdin === false ? '' : text);
1811
+ });
1812
+ }
1813
+
1814
+ /** Human vs AI: the writer splits and answers the open questions, then another model double-checks it. */
1815
+ async runHumanAi(agent, ctx) {
1816
+ const writer = this.writerFor(agent);
1817
+ const data = parseJsonReply(await this.oneShot(agent, humanAiPrompt(ctx), writer));
1818
+ if (!Array.isArray(data.human) || !Array.isArray(data.ai)) throw new Error('The reply was missing the "human" or "ai" list');
1819
+ data.human = data.human.slice(0, 5);
1820
+ data.ai = data.ai.slice(0, 5);
1821
+ const critic = this.criticFor(writer);
1822
+ const label = `${critic.engine.label}${critic.model ? ` (${critic.model})` : ''}`;
1823
+ let critique;
1824
+ try {
1825
+ critique = { label, data: parseJsonReply(await this.oneShot(agent, critiquePrompt(ctx, data), critic)) };
1826
+ } catch (err) {
1827
+ critique = { label, error: err.message.slice(0, 300) };
1828
+ }
1829
+ const cur = this.store.get(agent.id);
1830
+ if (!cur) return null;
1831
+ const doc = { data, critique, answers: {}, writer: `${writer.engine.label}${writer.model ? ` (${writer.model})` : ''}` };
1832
+ return this.view(
1833
+ this.patch(
1834
+ agent.id,
1835
+ summaryPatch(cur, 'humanai', { ...doc, markdown: humanAiMarkdown(doc), at: now(), briefUpdatedAt: cur.brief?.updatedAt ?? null, pending: false, error: null }),
1836
+ ),
1837
+ );
1838
+ }
1839
+
1840
+ /** Keep the person's answers to the Human vs AI questions; with `send`, also tell the agent. */
1841
+ humanAiAnswers(ref, answers, { send = false } = {}) {
1842
+ const agent = this.mustGet(ref);
1843
+ const doc = agent.docs?.humanai;
1844
+ if (!doc?.data) throw Object.assign(new Error('Write the Human vs AI review first'), { status: 409 });
1845
+ const clean = {};
1846
+ for (const [i, v] of Object.entries(answers ?? {})) if (doc.data.human[Number(i)] && typeof v === 'string') clean[i] = v.slice(0, 4000);
1847
+ const next = { ...doc, answers: clean };
1848
+ next.markdown = humanAiMarkdown(next);
1849
+ this.patch(agent.id, summaryPatch(agent, 'humanai', next));
1850
+ if (send) {
1851
+ if (!Object.values(clean).some((v) => v.trim())) throw Object.assign(new Error('Answer at least one question first'), { status: 400 });
1852
+ return this.tell(agent.id, humanAiMessage(next));
1853
+ }
1854
+ return this.view(this.store.get(agent.id));
1855
+ }
1856
+
1857
+ briefFile(ref) {
1858
+ const agent = this.mustGet(ref);
1859
+ const file = briefPath(agent.id);
1860
+ return { path: file, markdown: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null };
1861
+ }
1862
+
1863
+ async refresh(ref, { withPrs = false } = {}) {
1864
+ const id = this.mustGet(ref).id;
1865
+ if (this.refreshing.has(id)) return this.view(this.store.get(id));
1866
+ this.refreshing.add(id);
1867
+ try {
1868
+ this.reloadBrief(id);
1869
+ const agent = this.store.get(id);
1870
+ // Before handoff, a planning session's transcript lives in the planning folder.
1871
+ const planningOnly = agent?.planning && !agent.planning.handedOffAt && !agent.workdir;
1872
+ const sessionDir = planningOnly ? agent.planning.dir : agent?.workdir;
1873
+ if (!sessionDir) return agent && this.view(agent);
1874
+ let changed = agent.workdir ? this.adoptSessions(agent) : false;
1875
+
1876
+ const info = agent.workdir ? await git.gitInfo(agent.workdir) : agent.git;
1877
+ if (!this.store.get(id)) return null;
1878
+ if (info !== undefined && JSON.stringify({ ...info, updatedAt: 0 }) !== JSON.stringify({ ...agent.git, updatedAt: 0 })) {
1879
+ agent.git = info;
1880
+ changed = true;
1881
+ }
1882
+
1883
+ const engine = engineOf(agent);
1884
+ for (const session of agent.sessions) {
1885
+ const file = engine.sessionFile(sessionDir, session.id);
1886
+ const key = `${session.id}:${file}`; // the transcript moves at handoff; rescan the new copy
1887
+ const cursor = this.cursors.get(key) ?? { offset: 0 };
1888
+ this.cursors.set(key, cursor);
1889
+ const res = engine.scan(file, cursor, this.config.bugPatterns);
1890
+ const subMaps = engine.subagentFiles(sessionDir, session.id).map((sub) => {
1891
+ const c = this.cursors.get(sub) ?? { offset: 0 };
1892
+ this.cursors.set(sub, c);
1893
+ engine.scan(sub, c);
1894
+ return c.usage;
1895
+ });
1896
+ const usage = sumUsage(cursor.usage, ...subMaps);
1897
+ if (usage.requests && JSON.stringify(session.usage) !== JSON.stringify(usage)) {
1898
+ session.usage = usage;
1899
+ changed = true;
1900
+ }
1901
+ for (const key of ['title', 'lastPrompt', 'cost', 'lastActivity']) {
1902
+ if (res[key] != null && JSON.stringify(session[key]) !== JSON.stringify(res[key])) {
1903
+ session[key] = res[key];
1904
+ changed = true;
1905
+ }
1906
+ }
1907
+ const prs = res.prs.map((p) => ({ ...p, sessionId: session.id }));
1908
+ changed = this.mergeLinks(agent, agent.prs, prs, (p) => p.url) || changed;
1909
+ changed = this.mergeLinks(agent, agent.bugs, res.bugs, (b) => b.key) || changed;
1910
+ }
1911
+
1912
+ if (withPrs) {
1913
+ this.lastPrCheck.set(id, Date.now());
1914
+ const branchPrs = await prsForBranch(agent.workdir, info?.branch);
1915
+ changed = this.mergeLinks(agent, agent.prs, branchPrs, (p) => p.url) || changed;
1916
+ // Fill in title/state for PRs we only know by URL, and keep open ones current.
1917
+ const stale = Object.values(agent.prs).filter(
1918
+ (p) => p.source !== 'branch' && (!p.state || p.state === 'OPEN'),
1919
+ );
1920
+ for (const pr of stale.slice(0, 10)) {
1921
+ const d = await prDetails(pr.url);
1922
+ if (d) changed = this.mergeLinks(agent, agent.prs, [{ ...d, source: pr.source }], (p) => p.url) || changed;
1923
+ }
1924
+ }
1925
+
1926
+ await this.updateChanges(agent);
1927
+ this.updateStuck(agent, sessionDir);
1928
+
1929
+ if (changed && this.store.get(id)) {
1930
+ agent.updatedAt = now();
1931
+ this.store.save();
1932
+ this.changed(agent);
1933
+ }
1934
+ return this.view(agent);
1935
+ } finally {
1936
+ this.refreshing.delete(id);
1937
+ }
1938
+ }
1939
+
1940
+ // ------------------------------------------------------ telling an agent
1941
+
1942
+ /**
1943
+ * Type a message into an agent's session as if the user sent it: queued until the agent
1944
+ * is idle (not mid-turn, no prompt open), resuming a closed agent first.
1945
+ */
1946
+ /** The fields of an agent that policies and audit listeners see. */
1947
+ auditView(agent) {
1948
+ return {
1949
+ id: agent.id,
1950
+ name: agent.name,
1951
+ kind: agent.kind,
1952
+ engine: agent.engine ?? DEFAULT_ENGINE,
1953
+ intent: agent.intent,
1954
+ repo: agent.repo ?? null,
1955
+ workdir: agent.workdir ?? null,
1956
+ branch: agent.git?.branch ?? null,
1957
+ permissionMode: agent.permissionMode ?? null,
1958
+ model: agent.model ?? null,
1959
+ project: agent.projectInfo?.name ?? null,
1960
+ status: agent.status,
1961
+ };
1962
+ }
1963
+
1964
+ tell(ref, text, { source = 'user' } = {}) {
1965
+ const agent = this.mustGet(ref);
1966
+ text = String(text ?? '').trim();
1967
+ if (!text) throw Object.assign(new Error('Message is empty'), { status: 400 });
1968
+ this.plugins.check('agent.message', { agent: this.auditView(agent), text, source });
1969
+ this.plugins.emit('agent.message', { agent: this.auditView(agent), text, source });
1970
+ if (!this.outbox.has(agent.id)) this.outbox.set(agent.id, []);
1971
+ this.outbox.get(agent.id).push({ text, source, at: now() });
1972
+ if (!this.runtimes.get(agent.id)?.pty && agent.workdir && agent.status !== 'preparing') this.start(agent.id);
1973
+ this.changed(agent);
1974
+ return this.view(this.store.get(agent.id));
1975
+ }
1976
+
1977
+ deliverOutbox(t = Date.now()) {
1978
+ for (const [id, queue] of this.outbox) {
1979
+ const rt = this.runtimes.get(id);
1980
+ if (!queue.length) {
1981
+ this.outbox.delete(id);
1982
+ continue;
1983
+ }
1984
+ // Idle, no prompt open, and not right after our last message (give it time to react).
1985
+ if (!rt?.pty || rt.busy || rt.attention || rt.planning || t - (rt.startedAt ?? 0) < 2500 || t - (rt.toldAt ?? 0) < 8000) continue;
1986
+ const { text } = queue.shift();
1987
+ rt.toldAt = t;
1988
+ // Bracketed paste keeps a multi-line message as one message instead of submitting each line.
1989
+ rt.pty.write(text.includes('\n') ? `\x1b[200~${text}\x1b[201~` : text);
1990
+ setTimeout(() => rt.pty?.write('\r'), 250);
1991
+ const a = this.store.get(id);
1992
+ if (a) this.changed(a);
1993
+ }
1994
+ }
1995
+
1996
+ // ------------------------------------------------------- conflict radar
1997
+
1998
+ /** Recompute what an agent's branch changed since it branched (needs a base commit). */
1999
+ async updateChanges(agent) {
2000
+ const baseSha = agent.baseRef?.split(' @ ')[1];
2001
+ if (!agent.workdir || !baseSha || agent.kind === 'general' || !fs.existsSync(agent.workdir)) return;
2002
+ // A full diff against the base is heavier than git status; once a minute is enough for overlaps.
2003
+ const prev0 = this.changeSets.get(agent.id);
2004
+ if (prev0 && Date.now() - Date.parse(prev0.at) < (this.config.conflictRefreshSec ?? 60) * 1000) return;
2005
+ const res = await git.changes(agent.workdir, baseSha).catch(() => null);
2006
+ if (!res || !this.store.get(agent.id)) return;
2007
+ const prev = this.changeSets.get(agent.id);
2008
+ this.changeSets.set(agent.id, { ...res, baseSha, at: now() });
2009
+ if (JSON.stringify(prev?.files) !== JSON.stringify(res.files)) this.recomputeConflicts();
2010
+ }
2011
+
2012
+ recomputeConflicts() {
2013
+ const entries = [...this.changeSets.entries()]
2014
+ .map(([id, c]) => ({ agent: this.store.get(id), changes: c, baseSha: c.baseSha }))
2015
+ .filter((e) => e.agent);
2016
+ const next = findConflicts(entries);
2017
+ this.judgeClashes(entries, next);
2018
+ const ids = new Set([...this.conflicts.keys(), ...next.keys()]);
2019
+ const before = this.conflicts;
2020
+ this.conflicts = next;
2021
+ for (const id of ids) {
2022
+ if (JSON.stringify(before.get(id) ?? []) === JSON.stringify(next.get(id) ?? [])) continue;
2023
+ const a = this.store.get(id);
2024
+ if (a) this.changed(a);
2025
+ }
2026
+ }
2027
+
2028
+ /**
2029
+ * Ask the judge about pairs of agents in one repo that share a file (the rule's overlaps) or a
2030
+ * folder (candidates the rule can't see: the same module changed from different files).
2031
+ * Once per pair until their changes move, and at most every 30 minutes.
2032
+ */
2033
+ judgeClashes(entries, overlaps) {
2034
+ if (!this.judge.enabled) return;
2035
+ const dirs = (e) => new Set(Object.keys(e.changes.files).map((f) => path.dirname(f)).filter((d) => d !== '.'));
2036
+ const byRepo = new Map();
2037
+ for (const e of entries) {
2038
+ const k = repoKey(e.agent);
2039
+ if (k && e.agent.kind !== 'general') (byRepo.get(k) ?? byRepo.set(k, []).get(k)).push(e);
2040
+ }
2041
+ for (const group of byRepo.values()) {
2042
+ for (let i = 0; i < group.length; i++) {
2043
+ for (let j = i + 1; j < group.length; j++) {
2044
+ const [x, y] = [group[i], group[j]].sort((p, q) => p.agent.id.localeCompare(q.agent.id));
2045
+ if (related(x.agent, y.agent)) continue;
2046
+ const shareFile = (overlaps.get(x.agent.id) ?? []).some((c) => c.with.id === y.agent.id);
2047
+ const dy = dirs(y);
2048
+ if (!shareFile && ![...dirs(x)].some((d) => dy.has(d))) continue;
2049
+ const key = `${x.agent.id}|${y.agent.id}`;
2050
+ const h = hash(JSON.stringify([Object.keys(x.changes.files), Object.keys(y.changes.files)]));
2051
+ const prev = this.clashVerdicts.get(key);
2052
+ if (prev && (prev.hash === h || prev.pending || Date.now() - prev.at < 30 * 60_000)) continue;
2053
+ this.clashVerdicts.set(key, { ...prev, at: Date.now(), hash: h, a: x.agent.id, b: y.agent.id, pending: true });
2054
+ const side = (e) => ({ name: e.agent.name, intent: e.agent.intent, changes: e.changes, brief: fs.existsSync(briefPath(e.agent.id)) ? fs.readFileSync(briefPath(e.agent.id), 'utf8') : '' });
2055
+ this.judge
2056
+ .ask(`clash:${key}:${h}`, x.agent, clashPrompt(side(x), side(y), this.judge.examples('clash')), (d) => typeof d.conflict === 'boolean')
2057
+ .then((data) => {
2058
+ const cur = this.clashVerdicts.get(key);
2059
+ this.clashVerdicts.set(key, { ...cur, data: data ?? cur?.data ?? null, pending: false });
2060
+ for (const id of [x.agent.id, y.agent.id]) {
2061
+ const a = this.store.get(id);
2062
+ if (a) this.changed(a);
2063
+ }
2064
+ });
2065
+ }
2066
+ }
2067
+ }
2068
+ }
2069
+
2070
+ /**
2071
+ * Overlaps as the person sees them: the rule's file overlaps, with the judge's reason, advice
2072
+ * and merge order; an overlap only in different places is dropped when the judge says the work
2073
+ * doesn't collide; a collision the rule can't see (same folder, different files) is added.
2074
+ */
2075
+ conflictGroups(agent) {
2076
+ const groups = summarizeConflicts(this.conflicts.get(agent.id));
2077
+ if (!this.judge.enabled) return groups;
2078
+ const verdictWith = (otherId) => this.clashVerdicts.get([agent.id, otherId].sort().join('|'));
2079
+ const ai = (v) => {
2080
+ const d = v.data;
2081
+ const self = v.a === agent.id ? 'A' : 'B';
2082
+ const first = d.mergeFirst === 'A' ? v.a : d.mergeFirst === 'B' ? v.b : null;
2083
+ return { first, info: { conflict: d.conflict, confidence: d.confidence, reason: d.reason, orderReason: d.orderReason, advice: self === 'A' ? d.adviceA : d.adviceB } };
2084
+ };
2085
+ const out = [];
2086
+ for (const g of groups) {
2087
+ const v = verdictWith(g.agent.id);
2088
+ if (!v?.data) {
2089
+ out.push(v?.pending ? { ...g, ai: { checking: true } } : g);
2090
+ continue;
2091
+ }
2092
+ const { first, info } = ai(v);
2093
+ if (!info.conflict && info.confidence >= 0.6 && !g.lines) continue;
2094
+ out.push({ ...g, mergeFirst: first ?? g.mergeFirst, ai: info });
2095
+ }
2096
+ for (const v of this.clashVerdicts.values()) {
2097
+ if (!v.data?.conflict || v.data.confidence < 0.6 || (v.a !== agent.id && v.b !== agent.id)) continue;
2098
+ const otherId = v.a === agent.id ? v.b : v.a;
2099
+ const other = this.store.get(otherId);
2100
+ if (!other || out.some((g) => g.agent.id === otherId)) continue;
2101
+ const { first, info } = ai(v);
2102
+ out.push({ agent: { id: other.id, name: other.name }, files: [], lines: 0, mergeFirst: first ?? agent.id, ai: info });
2103
+ }
2104
+ return out;
2105
+ }
2106
+
2107
+ clashFeedback(agent, group, outcome) {
2108
+ const what = group.files.length ? group.files.map((f) => f.file).slice(0, 4).join(', ') : group.ai?.reason ?? 'related code';
2109
+ this.judge.feedback('clash', { summary: `${agent.name} and ${group.agent.name}: ${what}`, verdict: group.ai?.reason ? `${group.ai.conflict ? 'collide' : 'no collision'} (${group.ai.confidence})` : 'not asked', outcome });
2110
+ }
2111
+
2112
+ /** The person says these two don't collide: hide the pair until their changes move. */
2113
+ dismissConflict(ref, otherId) {
2114
+ const agent = this.mustGet(ref);
2115
+ const group = this.conflictGroups(agent).find((g) => g.agent.id === otherId);
2116
+ if (!group) throw Object.assign(new Error('No overlap with that agent right now'), { status: 404 });
2117
+ this.clashFeedback(agent, group, 'said they do not collide');
2118
+ const key = [agent.id, otherId].sort().join('|');
2119
+ const [a, b] = key.split('|');
2120
+ const cur = this.clashVerdicts.get(key);
2121
+ this.clashVerdicts.set(key, { at: Date.now(), hash: cur?.hash ?? null, a, b, pending: false, data: { conflict: false, confidence: 1, reason: 'You said these do not collide', byPerson: true } });
2122
+ for (const id of [agent.id, otherId]) {
2123
+ const x = this.store.get(id);
2124
+ if (x) this.changed(x);
2125
+ }
2126
+ return this.view(this.store.get(agent.id));
2127
+ }
2128
+
2129
+ /** Tell an agent (or both) about an overlap with another agent. */
2130
+ warnConflict(ref, otherId) {
2131
+ const agent = this.mustGet(ref);
2132
+ const group = this.conflictGroups(agent).find((g) => g.agent.id === otherId);
2133
+ if (!group) throw Object.assign(new Error('No overlap with that agent right now'), { status: 404 });
2134
+ this.clashFeedback(agent, group, 'told the agent about it');
2135
+ return this.tell(agent.id, conflictMessage(agent, group), { source: 'conflict' });
2136
+ }
2137
+
2138
+ // ------------------------------------------------------- stuck detection
2139
+
2140
+ updateStuck(agent, sessionDir) {
2141
+ if (!sessionDir) return;
2142
+ const key = `${agent.sessionId}:${sessionDir}`;
2143
+ const state = this.activity.get(key) ?? {};
2144
+ const engine = engineOf(agent);
2145
+ this.activity.set(key, engine.activity(engine.sessionFile(sessionDir, agent.sessionId), state));
2146
+ const running = Boolean(this.runtimes.get(agent.id)?.pty);
2147
+ const opts = { ...STUCK_DEFAULTS, ...this.config.stuck };
2148
+ const strict = running ? detectStuck(state.events, { opts }) : [];
2149
+ // With the judge on, looser thresholds only pick candidates; the model decides which are real.
2150
+ const loose = running && this.judge.enabled ? detectStuck(state.events, { opts: loosen(opts) }) : [];
2151
+ const found = [...strict.map((f) => ({ ...f, rule: true })), ...loose.filter((f) => !strict.some((x) => x.key === f.key))];
2152
+ const before = JSON.stringify(this.stuck.get(agent.id) ?? []);
2153
+ this.stuck.set(agent.id, found);
2154
+ for (const f of found) this.judgeStuck(agent, f, state.events);
2155
+ if (before !== JSON.stringify(found)) this.changed(agent);
2156
+ }
2157
+
2158
+ /** Ask the judge about a finding, at most once per finding every 15 minutes. */
2159
+ judgeStuck(agent, f, events) {
2160
+ if (!this.judge.enabled) return;
2161
+ const seen = this.stuckVerdicts.get(agent.id) ?? new Map();
2162
+ this.stuckVerdicts.set(agent.id, seen);
2163
+ const prev = seen.get(f.key);
2164
+ if (prev && (prev.since === f.since || Date.now() - prev.at < 15 * 60_000)) return;
2165
+ seen.set(f.key, { at: Date.now(), since: f.since, data: prev?.data ?? null, pending: true });
2166
+ this.explainContext(agent)
2167
+ .then((ctx) => this.judge.ask(`stuck:${agent.id}:${f.key}:${f.since}`, agent, stuckPrompt(ctx, f, events, this.judge.examples('stuck')), (d) => typeof d.stuck === 'boolean'))
2168
+ .then((data) => {
2169
+ seen.set(f.key, { at: Date.now(), since: f.since, data: data ?? prev?.data ?? null, pending: false });
2170
+ const a = this.store.get(agent.id);
2171
+ if (a) this.changed(a);
2172
+ })
2173
+ .catch(() => seen.set(f.key, { ...seen.get(f.key), pending: false }));
2174
+ }
2175
+
2176
+ /**
2177
+ * Findings as the person sees them: a rule's finding shows until the judge clears it, and the
2178
+ * judge's diagnosis and nudge replace the canned ones; a looser candidate shows only when the
2179
+ * judge confirms it.
2180
+ */
2181
+ resolvedStuck(agent) {
2182
+ const verdicts = this.stuckVerdicts.get(agent.id);
2183
+ const out = [];
2184
+ for (const f of this.stuck.get(agent.id) ?? []) {
2185
+ const { rule, ...finding } = f;
2186
+ const v = verdicts?.get(f.key);
2187
+ const d = v?.data;
2188
+ if (d && !d.stuck && d.confidence >= 0.5) continue;
2189
+ if (d?.stuck) {
2190
+ out.push({
2191
+ ...finding,
2192
+ title: d.title || f.title,
2193
+ detail: d.diagnosis || f.detail,
2194
+ nudge: d.nudge || f.nudge,
2195
+ ai: { verdict: 'stuck', confidence: d.confidence, rule: f.title },
2196
+ });
2197
+ } else if (rule) out.push(v?.pending ? { ...finding, ai: { verdict: 'checking' } } : finding);
2198
+ }
2199
+ return out;
2200
+ }
2201
+
2202
+ /** Findings the user hasn't dismissed. A dismissal holds until that finding clears. */
2203
+ activeStuck(agent) {
2204
+ const dismissed = agent.stuckDismissed ?? {};
2205
+ return this.resolvedStuck(agent).filter((f) => dismissed[f.key] !== f.since);
2206
+ }
2207
+
2208
+ dismissStuck(ref, key, { feedback = 'dismissed it' } = {}) {
2209
+ const agent = this.mustGet(ref);
2210
+ const f = this.resolvedStuck(agent).find((x) => x.key === key);
2211
+ if (!f) return this.view(agent);
2212
+ if (feedback) this.judge.feedback('stuck', { summary: `${f.ai?.rule ?? f.title}: ${f.detail}`, verdict: f.ai?.verdict === 'stuck' ? `stuck (${f.ai.confidence})` : 'not asked', outcome: feedback });
2213
+ return this.view(this.patch(agent.id, { stuckDismissed: { ...agent.stuckDismissed, [key]: f.since } }));
2214
+ }
2215
+
2216
+ nudge(ref, key, text) {
2217
+ const agent = this.mustGet(ref);
2218
+ const f = this.resolvedStuck(agent).find((x) => x.key === key);
2219
+ const message = text?.trim() || f?.nudge;
2220
+ if (!message) throw Object.assign(new Error('Nothing to send'), { status: 400 });
2221
+ this.tell(agent.id, message, { source: 'nudge' });
2222
+ return f ? this.dismissStuck(agent.id, key, { feedback: message === f.nudge ? 'sent the nudge as written' : 'sent an edited nudge' }) : this.view(agent);
2223
+ }
2224
+
2225
+ // ------------------------------------------------------------- the AI judge
2226
+
2227
+ /** Engine and model for judge calls: config `judge.engine`/`judge.model`, else Claude's fast model, else the summary writer. */
2228
+ judgeModel(agent) {
2229
+ const s = this.judge.settings;
2230
+ const usable = (e) => e?.supports.oneShot && installed(e, this.config);
2231
+ if (s.engine && usable(ENGINES[s.engine])) return { engine: ENGINES[s.engine], model: s.model ?? undefined };
2232
+ if (usable(ENGINES[DEFAULT_ENGINE])) return { engine: ENGINES[DEFAULT_ENGINE], model: s.model ?? 'haiku' };
2233
+ return this.writerFor(agent);
2234
+ }
2235
+
2236
+ /** The end of the terminal screen as text: cursor moves become spaces or line breaks. */
2237
+ screenText(rt) {
2238
+ return rt.tail
2239
+ .replace(/\x1b\[\d*(;\d*)?[Hf]/g, '\n')
2240
+ .replace(/\x1b\[\d*[CG]/g, ' ')
2241
+ .replace(ANSI, '')
2242
+ .replace(/\r\n?/g, '\n')
2243
+ .replace(/[^\S\n]+/g, ' ')
2244
+ .replace(/\n\s*\n+/g, '\n')
2245
+ .slice(-2500)
2246
+ .trim();
2247
+ }
2248
+
2249
+ /**
2250
+ * An idle agent whose screen matched no known prompt: ask the judge whether it is asking
2251
+ * something, finished, or broken. Once per screen.
2252
+ */
2253
+ async judgeScreen(id, rt) {
2254
+ const agent = this.store.get(id);
2255
+ if (!agent) return;
2256
+ const screen = this.screenText(rt);
2257
+ if (!screen) return;
2258
+ const h = hash(screen);
2259
+ if (rt.screenVerdict?.hash === h) return this.applyScreen(id, rt, rt.screenVerdict.data);
2260
+ const ctx = await this.explainContext(agent);
2261
+ const recent = ctx.digest ? `${screen}\n\n(last part of the conversation:)\n${ctx.digest.slice(-1500)}` : screen;
2262
+ const data = await this.judge.ask(`screen:${id}:${h}`, agent, screenPrompt(ctx, recent, this.judge.examples('screen')), (d) => ['question', 'done', 'error', 'idle'].includes(d.state));
2263
+ if (!data || !this.runtimes.has(id)) return;
2264
+ rt.screenVerdict = { hash: h, data };
2265
+ this.applyScreen(id, rt, data);
2266
+ }
2267
+
2268
+ applyScreen(id, rt, data) {
2269
+ if (!data || rt.busy || !rt.pty) return;
2270
+ const sure = data.confidence >= 0.6;
2271
+ rt.waiting = sure && (data.state === 'question' || data.state === 'error') ? { ...data, at: now() } : null;
2272
+ const a = this.store.get(id);
2273
+ if (!a) return;
2274
+ this.changed(a);
2275
+ if (sure && data.state === 'done' && a.kind !== 'general') this.requestReview(id, { trigger: 'screen' }).catch(() => {});
2276
+ }
2277
+
2278
+ /** The person says the agent is not actually waiting on them. */
2279
+ dismissWaiting(ref) {
2280
+ const agent = this.mustGet(ref);
2281
+ const rt = this.runtimes.get(agent.id);
2282
+ if (rt?.waiting) {
2283
+ this.judge.feedback('screen', { summary: rt.waiting.summary, verdict: `${rt.waiting.state} (${rt.waiting.confidence})`, outcome: 'said it was not waiting on them' });
2284
+ rt.waiting = null;
2285
+ this.changed(agent);
2286
+ }
2287
+ return this.view(agent);
2288
+ }
2289
+
2290
+ /** Answer what the judge saw the agent ask: typed into the session like any message. */
2291
+ answerWaiting(ref, text) {
2292
+ const agent = this.mustGet(ref);
2293
+ const rt = this.runtimes.get(agent.id);
2294
+ if (rt?.waiting) {
2295
+ this.judge.feedback('screen', { summary: rt.waiting.summary, verdict: `${rt.waiting.state} (${rt.waiting.confidence})`, outcome: 'answered it' });
2296
+ rt.waiting = null;
2297
+ }
2298
+ return this.tell(agent.id, text, { source: 'answer' });
2299
+ }
2300
+
2301
+ /**
2302
+ * Review the work against the intent and brief. Triggered when the brief says done or the
2303
+ * screen judge sees the agent say it finished; also on request. Skipped when nothing changed
2304
+ * since the last review.
2305
+ */
2306
+ async requestReview(ref, { trigger = 'manual', force = false } = {}) {
2307
+ const agent = this.mustGet(ref);
2308
+ if (!this.judge.enabled) throw Object.assign(new Error('The AI judge is off (config.json "judge": { "enabled": false })'), { status: 409 });
2309
+ const ctx = await this.explainContext(agent);
2310
+ const h = hash(`${ctx.repo}\n${ctx.briefMarkdown}\n${ctx.digest.slice(-2000)}`);
2311
+ if (!force && agent.aiReview?.hash === h) return this.view(agent);
2312
+ this.patch(agent.id, { aiReview: { ...agent.aiReview, pending: true } });
2313
+ const data = await this.judge.ask(`review:${agent.id}:${h}`, agent, reviewPrompt(ctx, this.judge.examples('review')), (d) => ['complete', 'partial', 'not_done'].includes(d.verdict));
2314
+ const cur = this.store.get(agent.id);
2315
+ if (!cur) return null;
2316
+ if (!data) return this.view(this.patch(agent.id, { aiReview: cur.aiReview?.verdict ? { ...cur.aiReview, pending: false } : null }));
2317
+ const list = (x) => (Array.isArray(x) ? x.map(String).slice(0, 8) : []);
2318
+ const m = this.judgeModel(agent);
2319
+ const review = {
2320
+ verdict: data.verdict,
2321
+ confidence: data.confidence,
2322
+ summary: String(data.summary ?? ''),
2323
+ met: list(data.met),
2324
+ missing: list(data.missing),
2325
+ risks: list(data.risks),
2326
+ trigger,
2327
+ hash: h,
2328
+ by: `${m.engine.label}${m.model ? ` (${m.model})` : ''}`,
2329
+ at: now(),
2330
+ seen: false,
2331
+ pending: false,
2332
+ };
2333
+ return this.view(this.patch(agent.id, { aiReview: review }));
2334
+ }
2335
+
2336
+ /** "finish": send the agent back with what is missing; "accept": the person is satisfied. */
2337
+ ackReview(ref, action) {
2338
+ const agent = this.mustGet(ref);
2339
+ const r = agent.aiReview;
2340
+ if (!r?.verdict) throw Object.assign(new Error('There is no AI review for this agent'), { status: 404 });
2341
+ if (action === 'finish') {
2342
+ if (!r.missing.length) throw Object.assign(new Error('The review found nothing missing'), { status: 400 });
2343
+ this.tell(agent.id, finishMessage(r), { source: 'review' });
2344
+ } else if (action !== 'accept') throw Object.assign(new Error('action must be "finish" or "accept"'), { status: 400 });
2345
+ this.judge.feedback('review', {
2346
+ summary: `${agent.intent?.slice(0, 120) ?? agent.name}: ${r.summary.slice(0, 80)}`,
2347
+ verdict: `${r.verdict} (${r.confidence})`,
2348
+ outcome: action === 'finish' ? 'sent it back to finish the missing items' : 'accepted the work',
2349
+ });
2350
+ return this.view(this.patch(agent.id, { aiReview: { ...r, seen: true, outcome: action } }));
2351
+ }
2352
+
2353
+ // ------------------------------------------------------- decision inbox
2354
+
2355
+ questionsView(agent) {
2356
+ if (agent.kind === 'general') return [];
2357
+ const answers = agent.answers ?? {};
2358
+ return loadQuestions(agent.id).map((q) => ({ ...q, answer: answers[q.id] ?? null }));
2359
+ }
2360
+
2361
+ answerQuestion(ref, qid, text) {
2362
+ const agent = this.mustGet(ref);
2363
+ const q = loadQuestions(agent.id).find((x) => x.id === qid);
2364
+ if (!q) throw Object.assign(new Error('No such question'), { status: 404 });
2365
+ text = String(text ?? '').trim();
2366
+ if (!text) throw Object.assign(new Error('Answer is empty'), { status: 400 });
2367
+ this.patch(agent.id, { answers: { ...agent.answers, [qid]: { text, at: now() } } });
2368
+ return this.tell(agent.id, answerMessage(q, text), { source: 'answer' });
2369
+ }
2370
+
2371
+ /** Everything waiting on the user, across agents: prompts, questions, stuck agents, overlaps. */
2372
+ inbox() {
2373
+ const items = [];
2374
+ for (const agent of this.store.list()) {
2375
+ const v = this.view(agent);
2376
+ const base = { agentId: agent.id, agentName: agent.name, project: v.projectInfo?.name ?? null, priority: v.priority };
2377
+ if (v.runtime.attention) {
2378
+ items.push({ ...base, kind: 'prompt', key: `prompt:${agent.id}`, title: v.runtime.attention, prompt: v.runtime.prompt, at: v.runtime.lastOutputAt });
2379
+ }
2380
+ if (v.runtime.waiting) {
2381
+ items.push({ ...base, kind: 'waiting', key: `waiting:${agent.id}`, title: v.runtime.waiting.question || v.runtime.waiting.summary, waiting: v.runtime.waiting, at: v.runtime.waiting.at });
2382
+ }
2383
+ for (const q of v.questions) if (!q.answer) items.push({ ...base, kind: 'question', key: `q:${agent.id}:${q.id}`, title: q.question, question: q });
2384
+ if (agent.aiReview?.verdict && !agent.aiReview.seen) {
2385
+ items.push({ ...base, kind: 'review', key: `review:${agent.id}`, title: agent.aiReview.summary, review: agent.aiReview, at: agent.aiReview.at });
2386
+ }
2387
+ for (const f of v.stuck) items.push({ ...base, kind: 'stuck', key: `stuck:${agent.id}:${f.key}`, title: f.title, finding: f, at: f.since });
2388
+ for (const g of v.conflicts) {
2389
+ // One entry per pair, on the agent that should rebase.
2390
+ if (g.mergeFirst === agent.id) continue;
2391
+ items.push({ ...base, kind: 'conflict', key: `conflict:${agent.id}:${g.agent.id}`, title: `Overlaps with ${g.agent.name}`, conflict: g });
2392
+ }
2393
+ }
2394
+ const order = { prompt: 0, waiting: 1, question: 1, review: 2, stuck: 3, conflict: 4 };
2395
+ return items.sort((a, b) => order[a.kind] - order[b.kind] || a.priority - b.priority);
2396
+ }
2397
+
2398
+ /** Send keys to a live prompt (e.g. "1" to pick the first option). */
2399
+ answerPrompt(ref, key) {
2400
+ const agent = this.mustGet(ref);
2401
+ const keys = { esc: '\x1b', enter: '\r', up: '\x1b[A', down: '\x1b[B' };
2402
+ const data = keys[key] ?? (/^\d$/.test(key) ? key : null);
2403
+ if (!data) throw Object.assign(new Error('Unsupported key'), { status: 400 });
2404
+ this.write(agent.id, data);
2405
+ return { ok: true };
2406
+ }
2407
+
2408
+ // ------------------------------------------------------- checkpoints and forks
2409
+
2410
+ /**
2411
+ * At the end of a turn, snapshot the working tree (as a commit under refs/agentmgr/<id>/)
2412
+ * together with how far the transcript had got, so the agent can be forked from here later.
2413
+ */
2414
+ async checkpoint(id) {
2415
+ const agent = this.store.get(id);
2416
+ if (!agent?.workdir || agent.kind === 'general' || !agent.branch || this.checkpointing?.has(id)) return null;
2417
+ // Output pauses mid-turn too (a slow command); one snapshot per half minute is plenty.
2418
+ this.lastCheckpointTry ??= new Map();
2419
+ if (Date.now() - (this.lastCheckpointTry.get(id) ?? 0) < 30_000) return null;
2420
+ this.lastCheckpointTry.set(id, Date.now());
2421
+ (this.checkpointing ??= new Set()).add(id);
2422
+ try {
2423
+ const snap = await git.snapshot(agent.workdir).catch(() => null);
2424
+ const cur = this.store.get(id);
2425
+ if (!snap || !cur) return null;
2426
+ const list = cur.checkpoints ?? [];
2427
+ let bytes = 0;
2428
+ try {
2429
+ bytes = fs.statSync(engineOf(cur).sessionFile(cur.workdir, cur.sessionId)).size;
2430
+ } catch {}
2431
+ const last = list.at(-1);
2432
+ if (last && last.tree === snap.tree && last.sessionId === cur.sessionId && last.bytes === bytes) return null;
2433
+ const n = (last?.n ?? 0) + 1;
2434
+ await git.setRef(cur.workdir, `refs/agentmgr/${id}/${n}`, snap.sha);
2435
+ const session = cur.sessions.find((s) => s.id === cur.sessionId);
2436
+ list.push({ n, at: now(), sha: snap.sha, tree: snap.tree, head: snap.head, sessionId: cur.sessionId, bytes, prompt: session?.lastPrompt?.slice(0, 200) ?? null });
2437
+ const max = this.config.maxCheckpoints ?? 40;
2438
+ while (list.length > max) {
2439
+ const old = list.shift();
2440
+ await git.run('git', ['update-ref', '-d', `refs/agentmgr/${id}/${old.n}`], { cwd: cur.workdir }).catch(() => {});
2441
+ }
2442
+ this.patch(id, { checkpoints: list });
2443
+ return list.at(-1);
2444
+ } finally {
2445
+ this.checkpointing.delete(id);
2446
+ }
2447
+ }
2448
+
2449
+ /**
2450
+ * A new agent that starts where this one is now (or at checkpoint `n`): its own worktree
2451
+ * holding the same code (commits and uncommitted work), and a copy of the conversation
2452
+ * under a new session ID. The original keeps running untouched.
2453
+ */
2454
+ async fork(ref, { checkpoint: n, name, instructions } = {}) {
2455
+ const src = this.mustGet(ref);
2456
+ if (!engineOf(src).supports.fork) throw Object.assign(new Error(`Forking isn't available for ${engineOf(src).label} agents yet`), { status: 409 });
2457
+ if (!src.workdir || !src.branch || !(await git.isGitRepo(src.workdir))) {
2458
+ throw Object.assign(new Error('Only agents with their own git worktree can be forked'), { status: 409 });
2459
+ }
2460
+ let point;
2461
+ if (n) {
2462
+ point = (src.checkpoints ?? []).find((c) => c.n === Number(n));
2463
+ if (!point) throw Object.assign(new Error(`No checkpoint ${n}`), { status: 404 });
2464
+ } else {
2465
+ const snap = await git.snapshot(src.workdir, 'agentmgr fork');
2466
+ if (!snap) throw Object.assign(new Error('Nothing to fork yet (no commits)'), { status: 409 });
2467
+ let bytes = 0;
2468
+ try {
2469
+ bytes = fs.statSync(engineOf(src).sessionFile(src.workdir, src.sessionId)).size;
2470
+ } catch {}
2471
+ point = { sha: snap.sha, head: snap.head, sessionId: src.sessionId, bytes };
2472
+ }
2473
+ const forks = this.store.list().filter((a) => a.forkOf?.agentId === src.id).length;
2474
+ const agent = this.create({
2475
+ intent: src.intent,
2476
+ name: name || `${src.name}-fork${forks + 1}`,
2477
+ repo: src.repo ?? undefined,
2478
+ permissionMode: src.permissionMode,
2479
+ model: src.model ?? undefined,
2480
+ project: src.project ?? undefined,
2481
+ priority: src.priority,
2482
+ start: true,
2483
+ workspace: (a, opts) => this.forkWorkspace(a, src, point, opts),
2484
+ });
2485
+ this.patch(agent.id, { forkOf: { agentId: src.id, name: src.name, checkpoint: n ? Number(n) : null, at: now() }, baseRef: src.baseRef });
2486
+ if (instructions?.trim()) this.tell(agent.id, instructions.trim(), { source: 'fork' });
2487
+ return this.view(this.store.get(agent.id));
2488
+ }
2489
+
2490
+ async forkWorkspace(agent, src, point, { signal, progress }) {
2491
+ const root = src.sourceDir || (await git.run('git', ['rev-parse', '--show-toplevel'], { cwd: src.workdir }));
2492
+ const workdir = path.join(paths.workspaces, `${path.basename(src.workdir).replace(/-[0-9a-f]{6}$/, '')}-fork-${agent.id}`);
2493
+ const branch = `agent/${agent.slug}-${agent.id}`;
2494
+ progress({ phase: 'Checking out' });
2495
+ await this.withLock(root, () => git.addWorktree(root, workdir, branch, point.head, { signal, onProgress: (p) => progress({ phase: 'Checking out', ...p }) }));
2496
+ // Same uncommitted work as the source had at that point.
2497
+ await git.restoreSnapshot(workdir, point.sha);
2498
+ // Same conversation, under the fork's own session ID.
2499
+ engineOf(src).copySession({ fromCwd: src.workdir, toCwd: workdir, fromId: point.sessionId, toId: agent.sessionId, bytes: point.bytes });
2500
+ return { workdir, sourceDir: root, branch, worktree: true, repo: src.repo, baseRef: src.baseRef };
2501
+ }
2502
+
2503
+ tick() {
2504
+ this.tickCount++;
2505
+ const t = Date.now();
2506
+ for (const [id, rt] of this.runtimes) {
2507
+ if (rt.busy && t - rt.lastOutputAt > BUSY_IDLE_MS) {
2508
+ rt.busy = false;
2509
+ const screen = rt.tail.slice(-1500).replace(ANSI, '').replace(/\s+/g, '');
2510
+ const a0 = this.store.get(id);
2511
+ rt.attention = (a0 ? engineOf(a0).attention : []).find(([re]) => re.test(screen))?.[1] ?? null;
2512
+ const a = this.store.get(id);
2513
+ if (a) this.changed(a);
2514
+ // A turn just ended: remember the code and conversation at this point.
2515
+ if (a && !rt.planning && !rt.attention) this.checkpoint(id).catch(() => {});
2516
+ }
2517
+ }
2518
+ this.deliverOutbox(t);
2519
+ this.scanSignIns();
2520
+ if (this.judge.enabled) {
2521
+ const idleMs = this.judge.settings.idleSec * 1000;
2522
+ for (const [id, rt] of this.runtimes) {
2523
+ if (!rt.pty || rt.busy || rt.attention || rt.planning || rt.screenChecked || this.outbox.get(id)?.length) continue;
2524
+ if (!rt.lastOutputAt || t - rt.lastOutputAt < idleMs) continue;
2525
+ // Output only right after launch (a resume repainting its screen) is not a turn worth reading.
2526
+ if (rt.lastOutputAt - rt.startedAt < this.judge.settings.warmupSec * 1000) continue;
2527
+ rt.screenChecked = true;
2528
+ this.judgeScreen(id, rt).catch(() => {});
2529
+ }
2530
+ }
2531
+ for (const [id, rt] of this.runtimes) {
2532
+ if (rt.pty) this.reloadBrief(id);
2533
+ }
2534
+ for (const [id, rt] of this.runtimes) {
2535
+ if (!rt.pty || !rt.planning) continue;
2536
+ const a = this.store.get(id);
2537
+ if (a?.workdir && a.status !== 'preparing') this.maybeHandoff(id).catch(() => {});
2538
+ }
2539
+ if (this.config.flushSec && this.tickCount % this.config.flushSec === 0) this.flush().catch(() => {});
2540
+ if (this.tickCount % this.config.gitRefreshSec !== 0) return;
2541
+ for (const [id, rt] of this.runtimes) {
2542
+ if (!rt.pty || !this.store.get(id)) continue;
2543
+ const withPrs = t - (this.lastPrCheck.get(id) ?? 0) > this.config.prRefreshSec * 1000;
2544
+ this.refresh(id, { withPrs }).catch(() => {});
2545
+ }
2546
+ }
2547
+
2548
+ /** One-off refresh of every agent (on daemon start), staggered to avoid a burst of gh calls. */
2549
+ async refreshAll({ withPrs = true } = {}) {
2550
+ for (const agent of this.store.list()) {
2551
+ if (agent.workdir) await this.refresh(agent.id, { withPrs }).catch(() => {});
2552
+ }
2553
+ }
2554
+ }