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/service.js ADDED
@@ -0,0 +1,150 @@
1
+ // Registers the daemon to start at login so agents come back after a reboot.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { paths } from './config.js';
7
+ import { run } from './git.js';
8
+
9
+ const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'agentmgr.js');
10
+ const LABEL = process.env.AGENTMGR_SERVICE_LABEL || 'com.agentmgr.daemon';
11
+ const PLIST = path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
12
+ const UNIT_NAME = `${LABEL.replace(/^com\./, '').replace(/\./g, '-')}.service`;
13
+ const UNIT = path.join(os.homedir(), '.config', 'systemd', 'user', UNIT_NAME);
14
+
15
+ /** First `node` on PATH (e.g. /opt/homebrew/bin/node), which survives node upgrades unlike the Cellar path. */
16
+ function nodePath() {
17
+ for (const dir of (process.env.PATH || '').split(':')) {
18
+ const candidate = path.join(dir, 'node');
19
+ try {
20
+ fs.accessSync(candidate, fs.constants.X_OK);
21
+ return candidate;
22
+ } catch {}
23
+ }
24
+ return process.execPath;
25
+ }
26
+
27
+ /**
28
+ * The daemon runs through your login + interactive shell so agents get the same
29
+ * environment as your terminal (PATH, tokens exported in ~/.zshrc, ...). `exec`
30
+ * replaces the shell so the service manager supervises node directly.
31
+ */
32
+ function command() {
33
+ const shell = process.env.SHELL || '/bin/zsh';
34
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
35
+ return [shell, '-l', '-i', '-c', `exec ${q(nodePath())} ${q(BIN)} serve`];
36
+ }
37
+
38
+ // Settings that change which daemon runs, or what it loads (plugins from a wrapper such as an
39
+ // enterprise package), carry over to the service.
40
+ export function passEnv(source = process.env) {
41
+ const env = {};
42
+ for (const key of ['AGENTMGR_HOME', 'AGENTMGR_PORT', 'AGENTMGR_PLUGINS', 'AGENTMGR_HUB_PLUGINS']) if (source[key]) env[key] = source[key];
43
+ return env;
44
+ }
45
+
46
+ const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
47
+
48
+ export function plist() {
49
+ const env = passEnv();
50
+ return `<?xml version="1.0" encoding="UTF-8"?>
51
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
52
+ <plist version="1.0">
53
+ <dict>
54
+ <key>Label</key><string>${xml(LABEL)}</string>
55
+ <key>ProgramArguments</key>
56
+ <array>
57
+ ${command().map((a) => ` <string>${xml(a)}</string>`).join('\n')}
58
+ </array>
59
+ <key>RunAtLoad</key><true/>
60
+ <!-- Restart after a crash, but not after "agentmgr shutdown" (clean exit). -->
61
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
62
+ <key>WorkingDirectory</key><string>${xml(os.homedir())}</string>
63
+ <key>EnvironmentVariables</key>
64
+ <dict>
65
+ ${Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`).join('\n')}
66
+ </dict>
67
+ <key>StandardOutPath</key><string>${xml(paths.log)}</string>
68
+ <key>StandardErrorPath</key><string>${xml(paths.log)}</string>
69
+ </dict>
70
+ </plist>
71
+ `;
72
+ }
73
+
74
+ export function unit() {
75
+ const env = Object.entries(passEnv()).map(([k, v]) => `Environment=${k}=${v}\n`).join('');
76
+ const cmd = command().map((a) => `"${a.replace(/(["\\])/g, '\\$1')}"`).join(' ');
77
+ return `[Unit]
78
+ Description=Agent Manager daemon (background Claude Code agents)
79
+
80
+ [Service]
81
+ ExecStart=${cmd}
82
+ Restart=on-failure
83
+ ${env}StandardOutput=append:${paths.log}
84
+ StandardError=append:${paths.log}
85
+
86
+ [Install]
87
+ WantedBy=default.target
88
+ `;
89
+ }
90
+
91
+ const uid = () => process.getuid();
92
+
93
+ export async function install() {
94
+ fs.mkdirSync(paths.home, { recursive: true });
95
+ if (process.platform === 'darwin') {
96
+ fs.mkdirSync(path.dirname(PLIST), { recursive: true });
97
+ await run('launchctl', ['bootout', `gui/${uid()}/${LABEL}`]).catch(() => {});
98
+ fs.writeFileSync(PLIST, plist());
99
+ await run('launchctl', ['bootstrap', `gui/${uid()}`, PLIST]);
100
+ return { file: PLIST, manager: 'launchd' };
101
+ }
102
+ if (process.platform === 'linux') {
103
+ fs.mkdirSync(path.dirname(UNIT), { recursive: true });
104
+ fs.writeFileSync(UNIT, unit());
105
+ await run('systemctl', ['--user', 'daemon-reload']);
106
+ await run('systemctl', ['--user', 'enable', '--now', UNIT_NAME]);
107
+ return {
108
+ file: UNIT,
109
+ manager: 'systemd',
110
+ note: 'To start it at boot without logging in, run: loginctl enable-linger $USER',
111
+ };
112
+ }
113
+ throw new Error(`Login service is not supported on ${process.platform}`);
114
+ }
115
+
116
+ export async function uninstall() {
117
+ if (process.platform === 'darwin') {
118
+ await run('launchctl', ['bootout', `gui/${uid()}/${LABEL}`]).catch(() => {});
119
+ fs.rmSync(PLIST, { force: true });
120
+ return { file: PLIST };
121
+ }
122
+ if (process.platform === 'linux') {
123
+ await run('systemctl', ['--user', 'disable', '--now', UNIT_NAME]).catch(() => {});
124
+ fs.rmSync(UNIT, { force: true });
125
+ await run('systemctl', ['--user', 'daemon-reload']).catch(() => {});
126
+ return { file: UNIT };
127
+ }
128
+ throw new Error(`Login service is not supported on ${process.platform}`);
129
+ }
130
+
131
+ export async function status() {
132
+ if (process.platform === 'darwin') {
133
+ const installed = fs.existsSync(PLIST);
134
+ const loaded = await run('launchctl', ['print', `gui/${uid()}/${LABEL}`]).then(() => true, () => false);
135
+ return { installed, loaded, file: PLIST };
136
+ }
137
+ if (process.platform === 'linux') {
138
+ const installed = fs.existsSync(UNIT);
139
+ const loaded = await run('systemctl', ['--user', 'is-active', UNIT_NAME]).then(() => true, () => false);
140
+ return { installed, loaded, file: UNIT };
141
+ }
142
+ return { installed: false, loaded: false, file: null };
143
+ }
144
+
145
+ /** Start the service-managed daemon now (after "agentmgr shutdown", launchd won't on its own). */
146
+ export async function kickstart() {
147
+ if (process.platform === 'darwin') return run('launchctl', ['kickstart', `gui/${uid()}/${LABEL}`]);
148
+ if (process.platform === 'linux') return run('systemctl', ['--user', 'start', UNIT_NAME]);
149
+ throw new Error(`Login service is not supported on ${process.platform}`);
150
+ }
@@ -0,0 +1,160 @@
1
+ // Claude Code sessions started outside Agent Manager (a plain `claude` in a terminal), so they
2
+ // can be continued here. Claude Code keeps each session as ~/.claude/projects/<cwd>/<id>.jsonl;
3
+ // the start and end of each file say where it ran, its title, branch and first ask.
4
+ import { execFileSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+
9
+ const projectsDir = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
10
+ const encode = (p) => {
11
+ let real = p;
12
+ try {
13
+ real = fs.realpathSync(p);
14
+ } catch {}
15
+ return real.replace(/[^a-zA-Z0-9]/g, '-');
16
+ };
17
+
18
+ /** The first and last `bytes` of a file as JSON records (partial lines dropped). */
19
+ function edges(file, size, bytes = 96 * 1024) {
20
+ const fd = fs.openSync(file, 'r');
21
+ try {
22
+ const read = (start, len) => {
23
+ const buf = Buffer.alloc(len);
24
+ fs.readSync(fd, buf, 0, len, start);
25
+ return buf.toString('utf8');
26
+ };
27
+ const head = read(0, Math.min(size, bytes));
28
+ const tail = size > bytes ? read(size - bytes, bytes) : '';
29
+ const parse = (text, dropFirst) =>
30
+ text
31
+ .split('\n')
32
+ .slice(dropFirst ? 1 : 0)
33
+ .map((l) => {
34
+ try {
35
+ return JSON.parse(l);
36
+ } catch {
37
+ return null;
38
+ }
39
+ })
40
+ .filter(Boolean);
41
+ return { head: parse(head, false), tail: parse(tail, true) };
42
+ } finally {
43
+ fs.closeSync(fd);
44
+ }
45
+ }
46
+
47
+ const textOf = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.filter((b) => b.type === 'text').map((b) => b.text).join('\n') : '');
48
+ /** A message the person typed (not a tool result, a slash command's output or a system note). */
49
+ const typed = (r) => {
50
+ if (r.type !== 'user' || r.isMeta || r.isSidechain) return null;
51
+ const t = textOf(r.message?.content).trim();
52
+ if (!t || /^<(command-|local-command|bash-|system-reminder)|^Caveat:/.test(t)) return null;
53
+ return t;
54
+ };
55
+
56
+ /** Running `claude` processes: session IDs they named, and the folders they run in. */
57
+ export function runningClaude() {
58
+ const ids = new Set();
59
+ const cwds = new Set();
60
+ let ps = '';
61
+ try {
62
+ ps = execFileSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 });
63
+ } catch {
64
+ return { ids, cwds };
65
+ }
66
+ const pids = [];
67
+ for (const line of ps.split('\n')) {
68
+ const m = line.trim().match(/^(\d+)\s+(.*)$/);
69
+ if (!m) continue;
70
+ const cmd = m[2];
71
+ // The claude CLI itself (native binary or node script), not this daemon or a one-off -p call.
72
+ if (!/(^|\/)claude(\s|$)|@anthropic-ai\/claude-code/.test(cmd) || /\s(-p|--print)(\s|$)/.test(cmd)) continue;
73
+ const id = cmd.match(/--(?:resume|session-id)[ =]([0-9a-f-]{36})/)?.[1];
74
+ if (id) ids.add(id);
75
+ else pids.push(m[1]);
76
+ }
77
+ if (pids.length) {
78
+ try {
79
+ const out = execFileSync('lsof', ['-a', '-d', 'cwd', '-Fn', '-p', pids.join(',')], { encoding: 'utf8' });
80
+ for (const l of out.split('\n')) if (l.startsWith('n')) cwds.add(l.slice(1));
81
+ } catch {}
82
+ }
83
+ return { ids, cwds };
84
+ }
85
+
86
+ /**
87
+ * Interactive Claude Code sessions from the last `days`, newest first, leaving out `known`
88
+ * session IDs (Agent Manager's own) and anything run under `excludeDir` (its one-off calls and
89
+ * workspaces). inUse: "open" when a running claude names the session, "maybe" when one runs in
90
+ * its folder and the session was active in the last 10 minutes.
91
+ */
92
+ export function scanClaudeSessions({ days = 30, known = new Set(), excludeDir, limit = 400 } = {}) {
93
+ const root = projectsDir();
94
+ const since = Date.now() - days * 86_400_000;
95
+ const skip = excludeDir ? encode(excludeDir) : null;
96
+ const files = [];
97
+ let dirs = [];
98
+ try {
99
+ dirs = fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory());
100
+ } catch {
101
+ return [];
102
+ }
103
+ for (const d of dirs) {
104
+ if (skip && d.name.startsWith(skip)) continue;
105
+ let names = [];
106
+ try {
107
+ names = fs.readdirSync(path.join(root, d.name));
108
+ } catch {
109
+ continue;
110
+ }
111
+ for (const n of names) {
112
+ if (!n.endsWith('.jsonl')) continue;
113
+ const id = n.slice(0, -6);
114
+ if (known.has(id)) continue;
115
+ const file = path.join(root, d.name, n);
116
+ try {
117
+ const st = fs.statSync(file);
118
+ if (st.mtimeMs >= since) files.push({ id, file, size: st.size, mtimeMs: st.mtimeMs });
119
+ } catch {}
120
+ }
121
+ }
122
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs);
123
+ const running = runningClaude();
124
+ const out = [];
125
+ for (const f of files.slice(0, limit)) {
126
+ let recs;
127
+ try {
128
+ recs = edges(f.file, f.size);
129
+ } catch {
130
+ continue;
131
+ }
132
+ const all = [...recs.head, ...recs.tail];
133
+ const withCwd = all.find((r) => r.cwd);
134
+ 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
+ const firstAsk = recs.head.map(typed).find(Boolean);
138
+ if (!firstAsk) continue;
139
+ const cwd = withCwd.cwd;
140
+ if (excludeDir && (cwd === excludeDir || cwd.startsWith(`${excludeDir}/`))) continue;
141
+ const last = (type, key) => [...all].reverse().find((r) => r.type === type && r[key])?.[key];
142
+ const lastAsk = [...recs.tail, ...recs.head].reverse().map(typed).find(Boolean);
143
+ const branch = [...all].reverse().find((r) => r.gitBranch)?.gitBranch ?? null;
144
+ const recent = Date.now() - f.mtimeMs < 10 * 60_000;
145
+ out.push({
146
+ engine: 'claude',
147
+ sessionId: f.id,
148
+ cwd,
149
+ exists: fs.existsSync(cwd),
150
+ title: last('custom-title', 'customTitle') || last('agent-name', 'agentName') || last('ai-title', 'aiTitle') || last('summary', 'summary') || null,
151
+ firstAsk: firstAsk.slice(0, 300),
152
+ lastAsk: lastAsk && lastAsk !== firstAsk ? lastAsk.slice(0, 300) : null,
153
+ branch: branch === 'HEAD' ? null : branch,
154
+ lastActivity: new Date(f.mtimeMs).toISOString(),
155
+ bytes: f.size,
156
+ inUse: running.ids.has(f.id) ? 'open' : recent && running.cwds.has(cwd) ? 'maybe' : null,
157
+ });
158
+ }
159
+ return out;
160
+ }
package/src/store.js ADDED
@@ -0,0 +1,104 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** The state file's format. Bump it with a migration below whenever saved fields change shape. */
5
+ export const STATE_VERSION = 1;
6
+
7
+ /** MIGRATIONS[n] turns version n data into version n + 1. */
8
+ const MIGRATIONS = {};
9
+
10
+ /**
11
+ * JSON-file persistence for agent records. Writes are atomic (tmp + rename)
12
+ * so a crash mid-write never loses the session IDs.
13
+ *
14
+ * Upgrades: older files are copied to `<file>.v<N>.bak` and migrated one version at a time.
15
+ * A file from a newer Agent Manager is refused rather than overwritten (downgrades would lose
16
+ * fields). The file as it was at startup is kept as `<file>.bak`.
17
+ */
18
+ export class Store {
19
+ constructor(file) {
20
+ this.file = file;
21
+ this.data = { version: STATE_VERSION, agents: {} };
22
+ this.load();
23
+ }
24
+
25
+ load() {
26
+ let raw;
27
+ try {
28
+ raw = fs.readFileSync(this.file, 'utf8');
29
+ } catch (err) {
30
+ if (err.code === 'ENOENT') return;
31
+ throw new Error(`Cannot read ${this.file}: ${err.message}`);
32
+ }
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(raw);
36
+ } catch (err) {
37
+ throw new Error(`Cannot read ${this.file}: ${err.message}. The copy from the last start is ${this.file}.bak`);
38
+ }
39
+ const version = Number(parsed.version ?? 1);
40
+ if (version > STATE_VERSION) {
41
+ throw new Error(`${this.file} was written by a newer Agent Manager (state version ${version}; this one reads up to ${STATE_VERSION}). Upgrade Agent Manager, or restore a backup.`);
42
+ }
43
+ if (version < STATE_VERSION) {
44
+ fs.copyFileSync(this.file, `${this.file}.v${version}.bak`);
45
+ for (let v = version; v < STATE_VERSION; v++) parsed = { ...MIGRATIONS[v](parsed), version: v + 1 };
46
+ }
47
+ try {
48
+ fs.writeFileSync(`${this.file}.bak`, raw);
49
+ } catch {}
50
+ this.data = { agents: {}, ...parsed, version: STATE_VERSION };
51
+ }
52
+
53
+ save() {
54
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
55
+ const tmp = `${this.file}.${process.pid}.tmp`;
56
+ // fsync before the rename so a crash or power loss can't leave an empty or partial file.
57
+ const fd = fs.openSync(tmp, 'w');
58
+ try {
59
+ fs.writeSync(fd, JSON.stringify(this.data, null, 2));
60
+ fs.fsyncSync(fd);
61
+ } finally {
62
+ fs.closeSync(fd);
63
+ }
64
+ fs.renameSync(tmp, this.file);
65
+ }
66
+
67
+ list() {
68
+ return Object.values(this.data.agents).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
69
+ }
70
+
71
+ get(id) {
72
+ return this.data.agents[id];
73
+ }
74
+
75
+ /** Find by exact id, then unique id prefix, then unique name. */
76
+ resolve(ref) {
77
+ if (this.data.agents[ref]) return this.data.agents[ref];
78
+ const all = this.list();
79
+ const byPrefix = all.filter((a) => a.id.startsWith(ref));
80
+ if (byPrefix.length === 1) return byPrefix[0];
81
+ const byName = all.filter((a) => a.name === ref);
82
+ if (byName.length === 1) return byName[0];
83
+ return undefined;
84
+ }
85
+
86
+ put(agent) {
87
+ this.data.agents[agent.id] = agent;
88
+ this.save();
89
+ return agent;
90
+ }
91
+
92
+ patch(id, fields) {
93
+ const agent = this.data.agents[id];
94
+ if (!agent) return undefined;
95
+ Object.assign(agent, fields, { updatedAt: new Date().toISOString() });
96
+ this.save();
97
+ return agent;
98
+ }
99
+
100
+ remove(id) {
101
+ delete this.data.agents[id];
102
+ this.save();
103
+ }
104
+ }
package/src/stuck.js ADDED
@@ -0,0 +1,160 @@
1
+ // Stuck detection: spot an agent going in circles from its transcript.
2
+ // repeat - the same command failing the same way again and again
3
+ // thrash - edits that undo earlier edits, or one file rewritten over and over
4
+ // drift - lots of activity for a long time without changing any file
5
+ // Each finding carries a suggested nudge the user can send with one click.
6
+ import fs from 'node:fs';
7
+
8
+ const WINDOW_MS = 45 * 60_000;
9
+ export const STUCK_DEFAULTS = { repeatFailures: 3, thrashReverts: 2, thrashEdits: 10, driftMinutes: 20, driftActions: 25 };
10
+
11
+ export const norm = (s) =>
12
+ String(s ?? '')
13
+ .replace(/\x1b\[[0-9;]*m/g, '')
14
+ .replace(/\d+(\.\d+)?\s*(ms|s|sec|seconds)\b/g, 'N')
15
+ .replace(/0x[0-9a-f]+|\b\d{3,}\b/gi, 'N')
16
+ .replace(/\s+/g, ' ')
17
+ .trim();
18
+ export const tailOf = (s, n = 300) => norm(s).slice(-n);
19
+ const textOf = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((b) => (b.type === 'text' ? b.text : '')).join('\n') : '');
20
+
21
+ /**
22
+ * Incrementally read new transcript lines into `state.events` (tool calls with their results).
23
+ * state: { offset, events: [{ t, kind: 'cmd'|'edit'|'other', ... }], pending: Map(id -> event) }.
24
+ */
25
+ export function scanActivity(file, state) {
26
+ state.offset ??= 0;
27
+ state.events ??= [];
28
+ state.pending ??= new Map();
29
+ let fd;
30
+ try {
31
+ fd = fs.openSync(file, 'r');
32
+ } catch {
33
+ return state;
34
+ }
35
+ try {
36
+ const { size } = fs.fstatSync(fd);
37
+ if (size < state.offset) Object.assign(state, { offset: 0, events: [], pending: new Map() });
38
+ if (size === state.offset) return state;
39
+ const buf = Buffer.alloc(size - state.offset);
40
+ fs.readSync(fd, buf, 0, buf.length, state.offset);
41
+ const lastNl = buf.lastIndexOf(0x0a);
42
+ if (lastNl < 0) return state;
43
+ state.offset += lastNl + 1;
44
+ for (const line of buf.subarray(0, lastNl).toString('utf8').split('\n')) {
45
+ let rec;
46
+ try {
47
+ rec = JSON.parse(line);
48
+ } catch {
49
+ continue;
50
+ }
51
+ if (rec.isSidechain) continue;
52
+ const t = Date.parse(rec.timestamp ?? '') || Date.now();
53
+ const blocks = Array.isArray(rec.message?.content) ? rec.message.content : [];
54
+ for (const b of blocks) {
55
+ if (rec.type === 'assistant' && b.type === 'tool_use') {
56
+ const ev = eventFor(b, t);
57
+ state.events.push(ev);
58
+ state.pending.set(b.id, ev);
59
+ } else if (rec.type === 'user' && b.type === 'tool_result') {
60
+ const ev = state.pending.get(b.tool_use_id);
61
+ if (!ev) continue;
62
+ state.pending.delete(b.tool_use_id);
63
+ const out = textOf(b.content);
64
+ ev.failed = Boolean(b.is_error) || /^Exit code [1-9]/m.test(out);
65
+ ev.result = tailOf(out); // normalized, for matching repeats
66
+ ev.shown = out.replace(/\s+/g, ' ').trim().slice(-160); // as it was, for people
67
+ }
68
+ }
69
+ }
70
+ // Only recent history matters.
71
+ const cutoff = Date.now() - 2 * WINDOW_MS;
72
+ if (state.events.length > 400 || state.events[0]?.t < cutoff) state.events = state.events.filter((e) => e.t >= cutoff).slice(-400);
73
+ } finally {
74
+ fs.closeSync(fd);
75
+ }
76
+ return state;
77
+ }
78
+
79
+ function eventFor(b, t) {
80
+ const input = b.input ?? {};
81
+ if (b.name === 'Bash') return { t, kind: 'cmd', cmd: norm(input.command).slice(0, 300) };
82
+ if (['Edit', 'MultiEdit', 'Write'].includes(b.name)) {
83
+ const edits = b.name === 'MultiEdit' ? input.edits ?? [] : b.name === 'Edit' ? [{ old_string: input.old_string, new_string: input.new_string }] : [];
84
+ return { t, kind: 'edit', file: input.file_path ?? '', edits: edits.map((e) => [norm(e.old_string), norm(e.new_string)]) };
85
+ }
86
+ return { t, kind: 'other', name: b.name };
87
+ }
88
+
89
+ /** Findings for an agent's recent activity, most important first. */
90
+ export function detectStuck(events, { now = Date.now(), opts = STUCK_DEFAULTS } = {}) {
91
+ const recent = events.filter((e) => now - e.t <= WINDOW_MS);
92
+ const found = [];
93
+
94
+ // repeat: one command failing with the same output N times in a row (among its own runs).
95
+ const runs = new Map();
96
+ for (const e of recent) if (e.kind === 'cmd' && e.cmd && e.result !== undefined) (runs.get(e.cmd) ?? runs.set(e.cmd, []).get(e.cmd)).push(e);
97
+ for (const [cmd, list] of runs) {
98
+ let streak = 0;
99
+ for (let i = list.length - 1; i >= 0 && list[i].failed && list[i].result === list.at(-1).result; i--) streak++;
100
+ if (streak >= opts.repeatFailures) {
101
+ found.push({
102
+ kind: 'repeat',
103
+ key: `repeat:${cmd}`,
104
+ title: `Same failure ${streak}× in a row`,
105
+ detail: `\`${cmd.slice(0, 120)}\` keeps failing with the same output: ${list.at(-1).shown ?? list.at(-1).result.slice(-160)}`,
106
+ since: new Date(list[list.length - streak].t).toISOString(),
107
+ nudge:
108
+ `You've run \`${cmd.slice(0, 120)}\` ${streak} times and it fails the same way each time. Stop retrying. ` +
109
+ 'Write down what you have tried and why each attempt failed, list two or three different hypotheses for the root cause, ' +
110
+ 'then test the most likely one with a small experiment before changing more code. If you need something from me, ask.',
111
+ });
112
+ }
113
+ }
114
+
115
+ // thrash: edits that put back what an earlier edit removed, or one file edited over and over.
116
+ const byFile = new Map();
117
+ for (const e of recent) if (e.kind === 'edit' && e.file) (byFile.get(e.file) ?? byFile.set(e.file, []).get(e.file)).push(e);
118
+ for (const [file, list] of byFile) {
119
+ let reverts = 0;
120
+ const seen = [];
121
+ for (const e of list) {
122
+ for (const [oldS, newS] of e.edits) {
123
+ if (oldS && newS && seen.some(([o, n]) => o === newS && n === oldS)) reverts++;
124
+ seen.push([oldS, newS]);
125
+ }
126
+ }
127
+ const short = file.split('/').slice(-2).join('/');
128
+ if (reverts >= opts.thrashReverts || list.length >= opts.thrashEdits) {
129
+ found.push({
130
+ kind: 'thrash',
131
+ key: `thrash:${file}`,
132
+ title: reverts >= opts.thrashReverts ? `Undoing its own edits in ${short}` : `${list.length} edits to ${short}`,
133
+ detail: reverts >= opts.thrashReverts ? `${reverts} edits put back code an earlier edit removed.` : `The same file was edited ${list.length} times in the last ${Math.round(WINDOW_MS / 60_000)} minutes.`,
134
+ since: new Date(list[0].t).toISOString(),
135
+ nudge:
136
+ `You're going back and forth on ${short}. Pause editing it. Explain in a few sentences what the code there must do, ` +
137
+ 'what constraint keeps pulling it in two directions, and which version you will commit to and why. Then make one deliberate change.',
138
+ });
139
+ }
140
+ }
141
+
142
+ // drift: busy for a long time, many actions, no file changed.
143
+ const lastEdit = [...recent].reverse().find((e) => e.kind === 'edit');
144
+ const sinceEdit = recent.filter((e) => !lastEdit || e.t > lastEdit.t);
145
+ const span = sinceEdit.length ? now - sinceEdit[0].t : 0;
146
+ const active = recent.length && now - recent.at(-1).t < 5 * 60_000; // still at it, not idle for hours
147
+ if (active && sinceEdit.length >= opts.driftActions && span >= opts.driftMinutes * 60_000) {
148
+ found.push({
149
+ kind: 'drift',
150
+ key: 'drift',
151
+ title: `${Math.round(span / 60_000)} min without changing a file`,
152
+ detail: `${sinceEdit.length} actions (searches, reads, commands) since the last edit.`,
153
+ since: new Date(sinceEdit[0].t).toISOString(),
154
+ nudge:
155
+ 'Quick check-in: you have spent a while exploring without changing anything. Summarize what you have learned so far, ' +
156
+ 'state the next concrete change you will make, and make it. If you are blocked or unsure what I want, ask me now.',
157
+ });
158
+ }
159
+ return found;
160
+ }