ai-agentmanager 1.16.0 → 1.18.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.
- package/CHANGELOG.md +14 -0
- package/README.md +50 -6
- package/package.json +1 -1
- package/public/app.js +105 -9
- package/public/goals.js +153 -0
- package/public/index.html +40 -1
- package/public/style.css +28 -0
- package/public/worklog.js +67 -0
- package/src/autopilot.js +27 -18
- package/src/backlog.js +14 -2
- package/src/brief.js +4 -2
- package/src/cli.js +112 -5
- package/src/goals.js +359 -0
- package/src/manager.js +82 -6
- package/src/reminders.js +58 -0
- package/src/server.js +48 -2
- package/src/sessions.js +54 -6
- package/src/worklog.js +265 -0
package/src/manager.js
CHANGED
|
@@ -101,6 +101,7 @@ import { spawn } from 'node:child_process';
|
|
|
101
101
|
import * as git from './git.js';
|
|
102
102
|
import { parseDiff } from '../public/review.js';
|
|
103
103
|
import { issueSummary, leadingIssue, wordsAfterLink } from './jira.js';
|
|
104
|
+
import { reminderFor, reminderSettings } from './reminders.js';
|
|
104
105
|
import { combine, facts as scoreFacts, improveMessage, scorecardMarkdown, scorecardPrompt } from './scorecard.js';
|
|
105
106
|
import { CONTAINER_ENGINES, claudeToken, containerName, containerRunning, engineMounts, gitCommonDir, removeContainer, runArgs, stopContainer } from './container.js';
|
|
106
107
|
import { conflictMessage, findConflicts, related, repoKey, summarize as summarizeConflicts } from './conflicts.js';
|
|
@@ -349,7 +350,7 @@ export class AgentManager extends EventEmitter {
|
|
|
349
350
|
usage.io = usage.input + usage.output;
|
|
350
351
|
const costs = (agent.sessions ?? []).map((s) => s.cost?.usd).filter((c) => c != null);
|
|
351
352
|
const prs = Object.values(agent.prs ?? {});
|
|
352
|
-
|
|
353
|
+
const v = {
|
|
353
354
|
...agent,
|
|
354
355
|
// Intent, spec and plan files that exist, with when each changed (task agents).
|
|
355
356
|
...(NO_REPO.has(agent.kind) ? {} : { specDocs: specDocsInfo(agent.id) }),
|
|
@@ -381,6 +382,9 @@ export class AgentManager extends EventEmitter {
|
|
|
381
382
|
prompt: rt?.pty && !rt.busy && rt.attention ? this.promptView(agent, rt) : null,
|
|
382
383
|
},
|
|
383
384
|
};
|
|
385
|
+
// A recent agent gone quiet: follow up on it, or close its finished session (reminders.js).
|
|
386
|
+
v.followUp = reminderFor(v, reminderSettings(this.config));
|
|
387
|
+
return v;
|
|
384
388
|
}
|
|
385
389
|
|
|
386
390
|
/**
|
|
@@ -955,6 +959,7 @@ export class AgentManager extends EventEmitter {
|
|
|
955
959
|
if (!agent.workdir || !fs.existsSync(agent.workdir)) {
|
|
956
960
|
throw Object.assign(new Error(`Working folder ${agent.workdir} no longer exists`), { status: 409 });
|
|
957
961
|
}
|
|
962
|
+
if (agent.desktop) this.patch(agent.id, { desktop: null }); // continued here again
|
|
958
963
|
|
|
959
964
|
if (sessionId) {
|
|
960
965
|
if (!agent.sessions.some((s) => s.id === sessionId)) {
|
|
@@ -1303,6 +1308,32 @@ export class AgentManager extends EventEmitter {
|
|
|
1303
1308
|
});
|
|
1304
1309
|
}
|
|
1305
1310
|
|
|
1311
|
+
/**
|
|
1312
|
+
* Close every open agent session (not the assistant's), from one button. Agents working right
|
|
1313
|
+
* now are left open unless `working`; they're returned so the person can decide.
|
|
1314
|
+
*/
|
|
1315
|
+
async closeAll({ working = false } = {}) {
|
|
1316
|
+
const open = this.store.list().filter((a) => a.kind !== 'assistant' && this.runtimes.get(a.id)?.pty);
|
|
1317
|
+
const busy = (a) => this.runtimes.get(a.id)?.busy;
|
|
1318
|
+
const close = open.filter((a) => working || !busy(a));
|
|
1319
|
+
const results = await Promise.allSettled(close.map((a) => this.stop(a.id)));
|
|
1320
|
+
const failed = close.filter((a, i) => results[i].status === 'rejected').map((a) => ({ id: a.id, name: a.name }));
|
|
1321
|
+
return {
|
|
1322
|
+
closed: close.filter((a, i) => results[i].status === 'fulfilled').map((a) => ({ id: a.id, name: a.name })),
|
|
1323
|
+
failed,
|
|
1324
|
+
working: open.filter((a) => !working && busy(a)).map((a) => ({ id: a.id, name: a.name })),
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/** A reminder's "Later" (hidden for a few hours) or "Not needed" (hidden until the agent is used again). */
|
|
1329
|
+
remind(ref, action) {
|
|
1330
|
+
const agent = this.mustGet(ref);
|
|
1331
|
+
const v = this.view(agent);
|
|
1332
|
+
if (action === 'later') return this.view(this.patch(agent.id, { reminder: { ...agent.reminder, laterUntil: new Date(Date.now() + reminderSettings(this.config).laterHours * 3_600_000).toISOString() } }));
|
|
1333
|
+
if (action === 'dismiss') return this.view(this.patch(agent.id, { reminder: { ...agent.reminder, dismissedAt: v.activeAt ?? now() } }));
|
|
1334
|
+
throw Object.assign(new Error('action must be later or dismiss'), { status: 400 });
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1306
1337
|
/** Daemon shutdown: close everything but remember which agents should come back. */
|
|
1307
1338
|
async stopAll({ final = false } = {}) {
|
|
1308
1339
|
// On a real shutdown, a workspace that finishes preparing afterwards must not launch its agent.
|
|
@@ -1763,9 +1794,52 @@ export class AgentManager extends EventEmitter {
|
|
|
1763
1794
|
return this.view(this.store.get(agent.id));
|
|
1764
1795
|
}
|
|
1765
1796
|
|
|
1797
|
+
/**
|
|
1798
|
+
* Continue a Claude agent's conversation in the Claude desktop app (`claude --desktop --resume`):
|
|
1799
|
+
* its session here is closed first, and it waits until you resume it here, where it picks up
|
|
1800
|
+
* what was said in the desktop app (the same session).
|
|
1801
|
+
*/
|
|
1802
|
+
async openInDesktop(ref) {
|
|
1803
|
+
const agent = this.mustGet(ref);
|
|
1804
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
1805
|
+
if ((agent.engine ?? DEFAULT_ENGINE) !== 'claude') throw err(409, 'Only Claude Code sessions open in the Claude desktop app');
|
|
1806
|
+
if (agent.isolation === 'container') throw err(409, 'Its session runs in a container; the desktop app cannot reach it');
|
|
1807
|
+
if (agent.movedTo) throw err(409, `${agent.name} moved to ${agent.movedTo.machine}; open it in the desktop app there`);
|
|
1808
|
+
if (!agent.sessionId) throw err(409, 'It has no session yet: start it first');
|
|
1809
|
+
if (!agent.workdir || !fs.existsSync(agent.workdir)) throw err(409, `Working folder ${agent.workdir} no longer exists`);
|
|
1810
|
+
if (this.runtimes.get(agent.id)?.pty) await this.stop(agent.id);
|
|
1811
|
+
const args = [...(this.config.claudeArgs ?? []), '--desktop', '--resume', agent.sessionId];
|
|
1812
|
+
// In a terminal of its own: Claude Code refuses --desktop when its output isn't one.
|
|
1813
|
+
const out = await new Promise((resolve) => {
|
|
1814
|
+
let child;
|
|
1815
|
+
try {
|
|
1816
|
+
child = pty.spawn(this.config.claudeBin, args, { name: 'xterm-256color', cols: 120, rows: 30, cwd: agent.workdir, env: { ...process.env, FORCE_COLOR: '0' } });
|
|
1817
|
+
} catch (e) {
|
|
1818
|
+
return resolve({ code: -1, text: e.message });
|
|
1819
|
+
}
|
|
1820
|
+
let text = '';
|
|
1821
|
+
child.onData((d) => (text = (text + d).slice(-4000)));
|
|
1822
|
+
const timer = setTimeout(() => {
|
|
1823
|
+
child.kill();
|
|
1824
|
+
resolve({ code: null, text });
|
|
1825
|
+
}, 30_000);
|
|
1826
|
+
child.onExit(({ exitCode }) => {
|
|
1827
|
+
clearTimeout(timer);
|
|
1828
|
+
resolve({ code: exitCode, text });
|
|
1829
|
+
});
|
|
1830
|
+
});
|
|
1831
|
+
if (out.code !== 0) {
|
|
1832
|
+
const why = out.text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r/g, '').trim().split('\n').filter(Boolean).slice(-3).join(' ') || (out.code === null ? 'it did not finish in 30 seconds' : `exit code ${out.code}`);
|
|
1833
|
+
throw err(502, `Couldn't open it in the Claude desktop app: ${why}`);
|
|
1834
|
+
}
|
|
1835
|
+
this.patch(agent.id, { desktop: { at: now(), sessionId: agent.sessionId } });
|
|
1836
|
+
this.changed(this.store.get(agent.id));
|
|
1837
|
+
return this.view(this.store.get(agent.id));
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1766
1840
|
// ------------------------------------------------- sessions started elsewhere
|
|
1767
1841
|
|
|
1768
|
-
/** Claude Code sessions started outside AI Agent Manager (in a terminal), to continue here. */
|
|
1842
|
+
/** Claude Code sessions started outside AI Agent Manager (in a terminal or the Claude desktop app), to continue here. */
|
|
1769
1843
|
scanSessions({ days = 30 } = {}) {
|
|
1770
1844
|
const known = new Set(this.store.list().flatMap((a) => a.sessions.map((x) => x.id)));
|
|
1771
1845
|
return scanClaudeSessions({ days: Math.max(1, Math.min(365, Number(days) || 30)), known, excludeDir: paths.home });
|
|
@@ -1787,7 +1861,7 @@ export class AgentManager extends EventEmitter {
|
|
|
1787
1861
|
continue;
|
|
1788
1862
|
}
|
|
1789
1863
|
if (s.inUse && !copy) {
|
|
1790
|
-
out.push({ sessionId: s.sessionId, error:
|
|
1864
|
+
out.push({ sessionId: s.sessionId, error: `Still open in ${s.source === 'desktop' ? 'the Claude desktop app' : 'a terminal'}: close it there first, or continue a copy` });
|
|
1791
1865
|
continue;
|
|
1792
1866
|
}
|
|
1793
1867
|
let sessionId = s.sessionId;
|
|
@@ -1803,7 +1877,7 @@ export class AgentManager extends EventEmitter {
|
|
|
1803
1877
|
engine: 'claude',
|
|
1804
1878
|
start,
|
|
1805
1879
|
sessionId,
|
|
1806
|
-
imported: { from: 'terminal', sessionId: s.sessionId, copy: sessionId !== s.sessionId, at: now() },
|
|
1880
|
+
imported: { from: s.source === 'desktop' ? 'desktop' : 'terminal', sessionId: s.sessionId, copy: sessionId !== s.sessionId, at: now() },
|
|
1807
1881
|
});
|
|
1808
1882
|
out.push({ sessionId: s.sessionId, agentId: agent.id, name: agent.name });
|
|
1809
1883
|
}
|
|
@@ -2474,7 +2548,8 @@ export class AgentManager extends EventEmitter {
|
|
|
2474
2548
|
this.plugins.emit('agent.message', { agent: this.auditView(agent), text, source });
|
|
2475
2549
|
if (!this.outbox.has(agent.id)) this.outbox.set(agent.id, []);
|
|
2476
2550
|
this.outbox.get(agent.id).push({ text, source, at: now() });
|
|
2477
|
-
|
|
2551
|
+
// In the Claude desktop app: it waits for Resume here (two places writing one conversation mix it up).
|
|
2552
|
+
if (!this.runtimes.get(agent.id)?.pty && agent.workdir && agent.status !== 'preparing' && !agent.desktop) this.start(agent.id);
|
|
2478
2553
|
this.changed(agent);
|
|
2479
2554
|
return this.view(this.store.get(agent.id));
|
|
2480
2555
|
}
|
|
@@ -2889,6 +2964,7 @@ export class AgentManager extends EventEmitter {
|
|
|
2889
2964
|
if (agent.aiReview?.verdict && !agent.aiReview.seen) {
|
|
2890
2965
|
items.push({ ...base, kind: 'review', key: `review:${agent.id}`, title: agent.aiReview.summary, review: agent.aiReview, at: agent.aiReview.at });
|
|
2891
2966
|
}
|
|
2967
|
+
if (v.followUp) items.push({ ...base, kind: 'reminder', key: `reminder:${agent.id}`, title: v.followUp.title, reminder: v.followUp, at: v.followUp.since });
|
|
2892
2968
|
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 });
|
|
2893
2969
|
for (const g of v.conflicts) {
|
|
2894
2970
|
// One entry per pair, on the agent that should rebase.
|
|
@@ -2900,7 +2976,7 @@ export class AgentManager extends EventEmitter {
|
|
|
2900
2976
|
for (const r of this.rules.view().suggestions) items.push({ kind: 'rule', key: `rule:${r.repo}:${r.rule}`, title: `Always allow ${r.label}?`, priority: 2, ...r });
|
|
2901
2977
|
// Others' items (autopilot's held backlog work).
|
|
2902
2978
|
for (const source of this.inboxSources) items.push(...source());
|
|
2903
|
-
const order = { prompt: 0, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, repeat: 5 };
|
|
2979
|
+
const order = { prompt: 0, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
|
|
2904
2980
|
return items.sort((a, b) => order[a.kind] - order[b.kind] || a.priority - b.priority);
|
|
2905
2981
|
}
|
|
2906
2982
|
|
package/src/reminders.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Reminders about recent agents that went quiet: work that needs a follow-up, or a finished
|
|
2
|
+
// agent whose session is still open. They show in the inbox once an agent used in the last few
|
|
3
|
+
// days has been quiet for a couple of hours (and isn't already waiting on you for something else):
|
|
4
|
+
// follow-up - open, not finished: nudge it, open it, or close it
|
|
5
|
+
// - closed before it finished, by itself or by the session cap / clean up: resume it
|
|
6
|
+
// close - finished (brief done, or its pull requests merged) with its session still open
|
|
7
|
+
// Agents you closed yourself are left alone. "Later" hides a reminder for a few hours; "Not
|
|
8
|
+
// needed" hides it until the agent is used again.
|
|
9
|
+
export const REMINDER_DEFAULTS = { enabled: true, quietHours: 2, recentDays: 3, laterHours: 4 };
|
|
10
|
+
const HOUR = 3_600_000;
|
|
11
|
+
|
|
12
|
+
/** Settings from config.json's "reminders", with defaults. */
|
|
13
|
+
export function reminderSettings(config = {}) {
|
|
14
|
+
const r = { ...REMINDER_DEFAULTS, ...config.reminders };
|
|
15
|
+
const n = (v, d) => (Number(v) > 0 ? Number(v) : d);
|
|
16
|
+
return { enabled: r.enabled !== false, quietHours: n(r.quietHours, 2), recentDays: n(r.recentDays, 3), laterHours: n(r.laterHours, 4) };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const hours = (ms) => {
|
|
20
|
+
const h = Math.floor(ms / HOUR);
|
|
21
|
+
if (h < 1) return `${Math.max(1, Math.floor(ms / 60_000))} minutes`;
|
|
22
|
+
return h >= 48 ? `${Math.floor(h / 24)} days` : `${h} hour${h === 1 ? '' : 's'}`;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The reminder for an agent's view now, or null: { kind: 'followup' | 'close', title, detail, since }.
|
|
27
|
+
* `v` is the agent's view (runtime, results, prs, activeAt).
|
|
28
|
+
*/
|
|
29
|
+
export function reminderFor(v, settings, t = Date.now()) {
|
|
30
|
+
if (!settings.enabled || v.kind === 'assistant' || v.status === 'preparing' || v.builds) return null;
|
|
31
|
+
const rt = v.runtime ?? {};
|
|
32
|
+
if (rt.busy || rt.attention || rt.waiting || rt.planning) return null;
|
|
33
|
+
const active = Date.parse(v.activeAt ?? v.createdAt ?? '') || 0;
|
|
34
|
+
const quiet = t - active;
|
|
35
|
+
if (quiet < settings.quietHours * HOUR || quiet > settings.recentDays * 24 * HOUR) return null;
|
|
36
|
+
const r = v.reminder ?? {};
|
|
37
|
+
if (r.dismissedAt && Date.parse(r.dismissedAt) >= active) return null;
|
|
38
|
+
if (r.laterUntil && Date.parse(r.laterUntil) > t) return null;
|
|
39
|
+
const outcome = v.results?.outcome ?? null;
|
|
40
|
+
const prs = v.prs ?? [];
|
|
41
|
+
const merged = prs.length > 0 && prs.every((p) => p.state === 'MERGED' || p.state === 'CLOSED') && prs.some((p) => p.state === 'MERGED');
|
|
42
|
+
const done = outcome === 'done' || merged;
|
|
43
|
+
const since = new Date(active).toISOString();
|
|
44
|
+
if (rt.running) {
|
|
45
|
+
if (done) return { kind: 'close', title: `${merged ? 'Its pull request merged' : 'Done'} and quiet for ${hours(quiet)}, but its session is still open`, detail: null, since };
|
|
46
|
+
const open = prs.find((p) => p.state === 'OPEN');
|
|
47
|
+
const detail =
|
|
48
|
+
(outcome === 'blocked' && v.results?.blockers?.[0]?.text ? `Blocked: ${v.results.blockers[0].text}` : null) ??
|
|
49
|
+
(open ? `Pull request #${String(open.url ?? '').split('/').pop()} is open${open.land === 'fix' ? ' and needs fixes' : ''}` : null) ??
|
|
50
|
+
(v.git?.dirtyFiles ? `${v.git.dirtyFiles} file${v.git.dirtyFiles === 1 ? '' : 's'} changed, not committed` : null);
|
|
51
|
+
return { kind: 'followup', title: `Quiet for ${hours(quiet)} and not finished`, detail, since };
|
|
52
|
+
}
|
|
53
|
+
// Closed: only when it closed by itself or was closed for you (session cap, clean up).
|
|
54
|
+
const byItself = v.status === 'exited' || v.closedBy === 'cap' || v.closedBy === 'cleanup';
|
|
55
|
+
if (done || !byItself || !v.sessionId) return null;
|
|
56
|
+
const how = v.closedBy === 'cap' ? 'closed by the session cap' : v.closedBy === 'cleanup' ? 'closed by clean up' : 'its session ended';
|
|
57
|
+
return { kind: 'followup', title: `Not finished, and ${how}`, detail: outcome === 'blocked' && v.results?.blockers?.[0]?.text ? `Blocked: ${v.results.blockers[0].text}` : null, since, closed: true };
|
|
58
|
+
}
|
package/src/server.js
CHANGED
|
@@ -18,12 +18,14 @@ import { Assistant } from './assistant.js';
|
|
|
18
18
|
import { Cleanup } from './cleanup.js';
|
|
19
19
|
import { Landing } from './landing.js';
|
|
20
20
|
import { Autopilot } from './autopilot.js';
|
|
21
|
+
import { Goals, goalMarkdown } from './goals.js';
|
|
21
22
|
import { Budgets } from './budgets.js';
|
|
22
23
|
import { stats } from './stats.js';
|
|
23
24
|
import { Playbooks } from './playbooks.js';
|
|
24
25
|
import { Repeats } from './repeats.js';
|
|
25
26
|
import { Updates } from './update.js';
|
|
26
27
|
import { identity } from './identity.js';
|
|
28
|
+
import { WorkLog, summaryMarkdown } from './worklog.js';
|
|
27
29
|
import { Studio } from './studio.js';
|
|
28
30
|
import { Memory } from './memory.js';
|
|
29
31
|
import { doctor } from './doctor.js';
|
|
@@ -95,6 +97,11 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
95
97
|
// Backlog work the scorecard calls ready goes on to a pull request (and merged) by itself.
|
|
96
98
|
const autopilot = new Autopilot({ manager, store, backlog, review, landing, config });
|
|
97
99
|
manager.inboxSources.push(() => autopilot.inbox());
|
|
100
|
+
// Daily or weekly goals across projects, planned into backlog tasks and seen through (goals.js).
|
|
101
|
+
const goals = new Goals({ manager, store, backlog, config });
|
|
102
|
+
// What agents got done, appended to a CSV for reviews (worklog.js).
|
|
103
|
+
const me = identity().then((i) => i.display, () => '');
|
|
104
|
+
const worklog = new WorkLog({ manager, store, config, who: me });
|
|
98
105
|
const assistant = new Assistant({ manager, store, config });
|
|
99
106
|
// Alerts link to the phone address when remote access is on, else the local UI.
|
|
100
107
|
const notifier = new Notifier({
|
|
@@ -416,6 +423,9 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
416
423
|
);
|
|
417
424
|
api.post('/agents/:id/start', wrap((req) => manager.start(req.params.id, req.body ?? {})));
|
|
418
425
|
api.post('/agents/:id/stop', wrap((req) => manager.stop(req.params.id)));
|
|
426
|
+
api.post('/agents/close-all', wrap((req) => manager.closeAll({ working: Boolean(req.body?.working) })));
|
|
427
|
+
api.post('/agents/:id/reminder', wrap((req) => manager.remind(req.params.id, req.body?.action)));
|
|
428
|
+
api.post('/agents/:id/desktop', wrap((req) => manager.openInDesktop(req.params.id)));
|
|
419
429
|
api.post('/agents/:id/refresh', wrap((req) => manager.refresh(req.params.id, { withPrs: true })));
|
|
420
430
|
api.post('/agents/:id/links', wrap((req) => manager.addLink(req.params.id, req.body ?? {})));
|
|
421
431
|
api.delete('/agents/:id/links', wrap((req) => manager.removeLink(req.params.id, req.query)));
|
|
@@ -695,6 +705,19 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
695
705
|
api.get('/repeats', wrap(() => repeats.view()));
|
|
696
706
|
api.post('/repeats/dismiss', wrap((req) => repeats.dismiss(String(req.body?.key ?? ''))));
|
|
697
707
|
api.post('/playbooks/:id/run', wrap((req) => playbooks.run(req.params.id, { vars: req.body?.vars ?? {} })));
|
|
708
|
+
api.get('/worklog', wrap(async (req) => (await worklog.record(), worklog.view({ days: Number(req.query.days ?? 30) || 0 }))));
|
|
709
|
+
api.get('/worklog/summary', wrap(async (req) => {
|
|
710
|
+
await worklog.record();
|
|
711
|
+
return { markdown: summaryMarkdown(worklog.view({ days: Number(req.query.days ?? 30) || 0 }), { who: await me }) };
|
|
712
|
+
}));
|
|
713
|
+
for (const [name, which] of [['worklog.csv', 'events'], ['worklog-weekly.csv', 'weekly']]) {
|
|
714
|
+
api.get(`/worklog/${name}`, async (req, res) => {
|
|
715
|
+
await worklog.record().catch(() => {});
|
|
716
|
+
const file = worklog.files[which];
|
|
717
|
+
if (!fs.existsSync(file)) return res.status(404).json({ error: 'Nothing recorded yet' });
|
|
718
|
+
res.download(file, name);
|
|
719
|
+
});
|
|
720
|
+
}
|
|
698
721
|
api.get('/stats', wrap((req) => {
|
|
699
722
|
const days = req.query.days === undefined ? 30 : Math.max(0, Math.min(3650, Math.floor(Number(req.query.days)) || 0));
|
|
700
723
|
return stats(store.list(), { days, projectOf: (a) => manager.projectInfo(a)?.name ?? null });
|
|
@@ -746,6 +769,14 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
746
769
|
api.post('/backlog/:id/move', wrap((req) => backlog.move(req.params.id, req.body?.where)));
|
|
747
770
|
api.post('/backlog/:id/split', wrap((req) => backlog.split(req.params.id, req.body?.parts)));
|
|
748
771
|
api.post('/backlog/:id/keep-whole', wrap((req) => backlog.keepWhole(req.params.id)));
|
|
772
|
+
api.get('/goals', wrap(() => goals.list()));
|
|
773
|
+
api.post('/goals', wrap((req) => goals.create(req.body ?? {})));
|
|
774
|
+
api.post('/goals/:id/approve', wrap((req) => goals.approve(req.params.id, req.body ?? {})));
|
|
775
|
+
api.post('/goals/:id/replan', wrap((req) => goals.replan(req.params.id)));
|
|
776
|
+
api.post('/goals/:id/extend', wrap((req) => goals.extend(req.params.id)));
|
|
777
|
+
api.post('/goals/:id/stop', wrap((req) => goals.stop(req.params.id)));
|
|
778
|
+
api.delete('/goals/:id', wrap((req) => goals.remove(req.params.id)));
|
|
779
|
+
api.get('/goals/:id/summary', wrap((req) => ({ markdown: goalMarkdown(goals.view(goals.get(req.params.id))) })));
|
|
749
780
|
api.post('/backlog/:id/ship', wrap((req) => autopilot.shipNow(req.params.id)));
|
|
750
781
|
api.post(
|
|
751
782
|
'/shutdown',
|
|
@@ -862,7 +893,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
862
893
|
const eventSinks = new Set();
|
|
863
894
|
api.get('/events/stream', (req, res) => {
|
|
864
895
|
const send = sse(req, res);
|
|
865
|
-
send({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list() });
|
|
896
|
+
send({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), goals: goals.list(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list() });
|
|
866
897
|
eventSinks.add(send);
|
|
867
898
|
req.on('close', () => eventSinks.delete(send));
|
|
868
899
|
});
|
|
@@ -963,6 +994,19 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
963
994
|
live.closeAgent(id).catch(() => {});
|
|
964
995
|
});
|
|
965
996
|
backlog.on('change', (view) => broadcast({ t: 'backlog', backlog: view }));
|
|
997
|
+
// Goals' summaries follow their tasks and agents: sent at most every couple of seconds.
|
|
998
|
+
let goalsSoon = null;
|
|
999
|
+
const sendGoals = () => {
|
|
1000
|
+
if (goalsSoon) return;
|
|
1001
|
+
goalsSoon = setTimeout(() => {
|
|
1002
|
+
goalsSoon = null;
|
|
1003
|
+
broadcast({ t: 'goals', goals: goals.list() });
|
|
1004
|
+
}, 2000);
|
|
1005
|
+
goalsSoon.unref?.();
|
|
1006
|
+
};
|
|
1007
|
+
goals.on('change', sendGoals);
|
|
1008
|
+
backlog.on('change', sendGoals);
|
|
1009
|
+
manager.on('change', () => Object.values(goals.data).some((g) => g.status === 'running') && sendGoals());
|
|
966
1010
|
const raceTimers = new Map();
|
|
967
1011
|
races.on('change', (id) => {
|
|
968
1012
|
if (raceTimers.has(id)) return;
|
|
@@ -994,7 +1038,7 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
994
1038
|
const url = new URL(req.url, 'http://x');
|
|
995
1039
|
if (url.pathname === '/ws/events') {
|
|
996
1040
|
eventClients.add(ws);
|
|
997
|
-
ws.send(JSON.stringify({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list(), rules: manager.rules.view(), repeats: repeats.view() }));
|
|
1041
|
+
ws.send(JSON.stringify({ t: 'snapshot', agents: manager.list(), backlog: backlog.view(), goals: goals.list(), projects: manager.listProjects(), races: races.list(), teams: teams.list(), built: reports.list(), rules: manager.rules.view(), repeats: repeats.view() }));
|
|
998
1042
|
ws.on('close', () => eventClients.delete(ws));
|
|
999
1043
|
return;
|
|
1000
1044
|
}
|
|
@@ -1076,6 +1120,8 @@ export async function startServer({ port = PORT, host = HOST } = {}) {
|
|
|
1076
1120
|
cleanup.close();
|
|
1077
1121
|
landing.close();
|
|
1078
1122
|
autopilot.close();
|
|
1123
|
+
goals.close();
|
|
1124
|
+
worklog.close();
|
|
1079
1125
|
triggers.close();
|
|
1080
1126
|
budgets.close();
|
|
1081
1127
|
playbooks.close();
|
package/src/sessions.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Claude Code sessions started outside AI Agent Manager (a plain `claude` in a terminal
|
|
2
|
-
// can be continued here. Claude Code keeps each session as ~/.claude/projects/<cwd>/<id>.jsonl;
|
|
1
|
+
// Claude Code sessions started outside AI Agent Manager (a plain `claude` in a terminal, or the
|
|
2
|
+
// Claude desktop app's Code tab), so they can be continued here. Claude Code keeps each session as ~/.claude/projects/<cwd>/<id>.jsonl;
|
|
3
3
|
// the start and end of each file say where it ran, its title, branch and first ask.
|
|
4
4
|
import { execFileSync } from 'node:child_process';
|
|
5
5
|
import fs from 'node:fs';
|
|
@@ -15,6 +15,46 @@ const encode = (p) => {
|
|
|
15
15
|
return real.replace(/[^a-zA-Z0-9]/g, '-');
|
|
16
16
|
};
|
|
17
17
|
|
|
18
|
+
/** Where the Claude desktop app keeps its data (its list of Code sessions is under it). */
|
|
19
|
+
const desktopDir = () =>
|
|
20
|
+
process.env.AGENTMGR_CLAUDE_DESKTOP_DIR ||
|
|
21
|
+
(process.platform === 'darwin'
|
|
22
|
+
? path.join(os.homedir(), 'Library', 'Application Support', 'Claude')
|
|
23
|
+
: process.platform === 'win32'
|
|
24
|
+
? path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'Claude')
|
|
25
|
+
: path.join(os.homedir(), '.config', 'Claude'));
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The Claude desktop app's Code sessions on this computer, by Claude Code session ID: its title
|
|
29
|
+
* and whether it's archived. Read from the app's own records (claude-code-sessions/<account>/<org>/
|
|
30
|
+
* local_*.json, each naming its `cliSessionId`); an app that keeps them elsewhere gives none, and
|
|
31
|
+
* its sessions are still found by their transcripts.
|
|
32
|
+
*/
|
|
33
|
+
export function desktopSessions() {
|
|
34
|
+
const out = new Map();
|
|
35
|
+
const root = path.join(desktopDir(), 'claude-code-sessions');
|
|
36
|
+
const walk = (dir, depth) => {
|
|
37
|
+
let entries = [];
|
|
38
|
+
try {
|
|
39
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
40
|
+
} catch {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
for (const e of entries) {
|
|
44
|
+
const p = path.join(dir, e.name);
|
|
45
|
+
if (e.isDirectory() && depth < 3) walk(p, depth + 1);
|
|
46
|
+
else if (e.isFile() && /^local_.*\.json$/.test(e.name)) {
|
|
47
|
+
try {
|
|
48
|
+
const r = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
49
|
+
if (typeof r.cliSessionId === 'string') out.set(r.cliSessionId, { title: typeof r.title === 'string' ? r.title : null, archived: Boolean(r.isArchived) });
|
|
50
|
+
} catch {}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
walk(root, 0);
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
18
58
|
/** The first and last `bytes` of a file as JSON records (partial lines dropped). */
|
|
19
59
|
function edges(file, size, bytes = 96 * 1024) {
|
|
20
60
|
const fd = fs.openSync(file, 'r');
|
|
@@ -84,7 +124,7 @@ export function runningClaude() {
|
|
|
84
124
|
}
|
|
85
125
|
|
|
86
126
|
/**
|
|
87
|
-
* Interactive Claude Code sessions from the last `days
|
|
127
|
+
* Interactive Claude Code sessions from the last `days` (terminal and Claude desktop app), newest first, leaving out `known`
|
|
88
128
|
* session IDs (AI Agent Manager's own) and anything run under `excludeDir` (its one-off calls and
|
|
89
129
|
* workspaces). inUse: "open" when a running claude names the session, "maybe" when one runs in
|
|
90
130
|
* its folder and the session was active in the last 10 minutes.
|
|
@@ -121,6 +161,7 @@ export function scanClaudeSessions({ days = 30, known = new Set(), excludeDir, l
|
|
|
121
161
|
}
|
|
122
162
|
files.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
123
163
|
const running = runningClaude();
|
|
164
|
+
const desktop = desktopSessions();
|
|
124
165
|
const out = [];
|
|
125
166
|
for (const f of files.slice(0, limit)) {
|
|
126
167
|
let recs;
|
|
@@ -132,10 +173,15 @@ export function scanClaudeSessions({ days = 30, known = new Set(), excludeDir, l
|
|
|
132
173
|
const all = [...recs.head, ...recs.tail];
|
|
133
174
|
const withCwd = all.find((r) => r.cwd);
|
|
134
175
|
if (!withCwd) continue;
|
|
135
|
-
// Headless runs (claude -p, the SDK) aren't conversations to continue.
|
|
136
|
-
if (all.some((r) => r.entrypoint && r.entrypoint !== 'cli')) continue;
|
|
137
176
|
const firstAsk = recs.head.map(typed).find(Boolean);
|
|
138
177
|
if (!firstAsk) continue;
|
|
178
|
+
// Where it was started: a terminal (`cli`), the Claude desktop app (in its list of sessions, or
|
|
179
|
+
// saying so), an editor, or a program (claude -p, the SDK, built agents), whose runs aren't
|
|
180
|
+
// conversations to continue.
|
|
181
|
+
const app = desktop.get(f.id);
|
|
182
|
+
const entry = all.find((r) => r.entrypoint)?.entrypoint ?? 'cli';
|
|
183
|
+
const source = app || /desktop/i.test(entry) ? 'desktop' : entry === 'cli' ? 'terminal' : /vscode|jetbrains|ide/i.test(entry) ? 'editor' : null;
|
|
184
|
+
if (!source) continue;
|
|
139
185
|
const cwd = withCwd.cwd;
|
|
140
186
|
if (excludeDir && (cwd === excludeDir || cwd.startsWith(`${excludeDir}/`))) continue;
|
|
141
187
|
const last = (type, key) => [...all].reverse().find((r) => r.type === type && r[key])?.[key];
|
|
@@ -147,7 +193,9 @@ export function scanClaudeSessions({ days = 30, known = new Set(), excludeDir, l
|
|
|
147
193
|
sessionId: f.id,
|
|
148
194
|
cwd,
|
|
149
195
|
exists: fs.existsSync(cwd),
|
|
150
|
-
|
|
196
|
+
source,
|
|
197
|
+
archived: app?.archived || undefined,
|
|
198
|
+
title: app?.title || last('custom-title', 'customTitle') || last('agent-name', 'agentName') || last('ai-title', 'aiTitle') || last('summary', 'summary') || null,
|
|
151
199
|
firstAsk: firstAsk.slice(0, 300),
|
|
152
200
|
lastAsk: lastAsk && lastAsk !== firstAsk ? lastAsk.slice(0, 300) : null,
|
|
153
201
|
branch: branch === 'HEAD' ? null : branch,
|