ai-agentmanager 1.37.0 → 1.39.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 +18 -0
- package/README.md +5 -1
- package/package.json +1 -1
- package/public/app.js +65 -12
- package/public/groups.js +83 -17
- package/public/index.html +11 -3
- package/public/keys.js +6 -0
- package/public/menu.js +6 -3
- package/public/style.css +20 -2
- package/public/topnav.js +75 -0
- package/src/cleanup.js +26 -11
- package/src/cli.js +18 -3
- package/src/engines/codex.js +12 -0
- package/src/limits.js +115 -0
- package/src/manager.js +82 -5
- package/src/reminders.js +2 -2
- package/src/rules.js +52 -7
- package/src/server.js +1 -0
package/public/topnav.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The top bar's view buttons fit the window: the ones that don't fit move, in order, into a
|
|
2
|
+
// "More" menu at the end of the row (as VS Code does with tabs). The buttons themselves move, so
|
|
3
|
+
// their handlers, counts and shortcuts keep working; a count on a moved one shows as a dot on More.
|
|
4
|
+
|
|
5
|
+
export function initTopNav({ $ }) {
|
|
6
|
+
const nav = $('#top-nav');
|
|
7
|
+
const wrap = $('#top-more');
|
|
8
|
+
const btn = $('#top-more-btn');
|
|
9
|
+
const menu = $('#top-more-menu');
|
|
10
|
+
const order = [...nav.querySelectorAll(':scope > button')];
|
|
11
|
+
let fitting = false;
|
|
12
|
+
|
|
13
|
+
const counted = (b) => [...b.querySelectorAll('.badge')].some((x) => x.textContent.trim()) || Boolean(b.querySelector('.assistant-dot:not([hidden])'));
|
|
14
|
+
|
|
15
|
+
function fit() {
|
|
16
|
+
if (fitting) return;
|
|
17
|
+
fitting = true;
|
|
18
|
+
observer.disconnect();
|
|
19
|
+
// Everything back in the row, in order; then move the last ones out until the row fits.
|
|
20
|
+
for (const b of order) nav.insertBefore(b, wrap);
|
|
21
|
+
wrap.hidden = false;
|
|
22
|
+
const moved = [];
|
|
23
|
+
while (nav.scrollWidth > nav.clientWidth + 1) {
|
|
24
|
+
const last = order.filter((b) => b.parentElement === nav && !b.hidden).pop();
|
|
25
|
+
if (!last) break;
|
|
26
|
+
moved.unshift(last);
|
|
27
|
+
menu.prepend(last);
|
|
28
|
+
}
|
|
29
|
+
wrap.hidden = moved.length === 0;
|
|
30
|
+
if (!moved.length) close();
|
|
31
|
+
btn.classList.toggle('has-news', moved.some(counted));
|
|
32
|
+
btn.title = moved.length ? `More: ${moved.map((b) => b.firstChild?.textContent?.trim()).filter(Boolean).join(', ')}` : '';
|
|
33
|
+
observe();
|
|
34
|
+
fitting = false;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let queued = false;
|
|
38
|
+
const later = () => {
|
|
39
|
+
if (queued) return;
|
|
40
|
+
queued = true;
|
|
41
|
+
requestAnimationFrame(() => {
|
|
42
|
+
queued = false;
|
|
43
|
+
fit();
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
// Counts change the buttons' widths; the window and the rest of the bar change the room.
|
|
47
|
+
const observer = new MutationObserver(later);
|
|
48
|
+
const observe = () => {
|
|
49
|
+
for (const b of order) observer.observe(b, { childList: true, characterData: true, subtree: true, attributes: true, attributeFilter: ['hidden', 'class'] });
|
|
50
|
+
};
|
|
51
|
+
new ResizeObserver(later).observe(nav.parentElement);
|
|
52
|
+
addEventListener('resize', later);
|
|
53
|
+
|
|
54
|
+
function close() {
|
|
55
|
+
menu.hidden = true;
|
|
56
|
+
btn.setAttribute('aria-expanded', 'false');
|
|
57
|
+
}
|
|
58
|
+
btn.addEventListener('click', (e) => {
|
|
59
|
+
e.stopPropagation();
|
|
60
|
+
menu.hidden = !menu.hidden;
|
|
61
|
+
btn.setAttribute('aria-expanded', String(!menu.hidden));
|
|
62
|
+
});
|
|
63
|
+
// A button in the menu does its own thing (its handler is unchanged); then the menu closes.
|
|
64
|
+
menu.addEventListener('click', () => setTimeout(close));
|
|
65
|
+
document.addEventListener('click', (e) => {
|
|
66
|
+
if (!menu.hidden && !wrap.contains(e.target)) close();
|
|
67
|
+
});
|
|
68
|
+
document.addEventListener('keydown', (e) => {
|
|
69
|
+
if (e.key === 'Escape' && !menu.hidden) close();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
fit();
|
|
73
|
+
document.fonts?.ready.then(later);
|
|
74
|
+
return { fit };
|
|
75
|
+
}
|
package/src/cleanup.js
CHANGED
|
@@ -7,14 +7,16 @@
|
|
|
7
7
|
// that exists only in their worktree (uncommitted changes or commits on no other branch).
|
|
8
8
|
// Optionally, a cap on open sessions ("maxRunning"): above it, the agents idle longest are closed
|
|
9
9
|
// (they resume when opened), so the machine stays responsive. The same agents are left alone,
|
|
10
|
-
// plus ones waiting for an answer and ones active in the last few minutes.
|
|
10
|
+
// plus ones waiting for an answer and ones active in the last few minutes. And optionally an
|
|
11
|
+
// idle time in hours ("idleHours"): open sessions quiet that long are closed the same way.
|
|
11
12
|
import fs from 'node:fs';
|
|
12
13
|
import * as git from './git.js';
|
|
13
14
|
|
|
14
15
|
export const STRATEGIES = ['close-delete', 'close', 'manual', 'off'];
|
|
15
|
-
export const CLEANUP_DEFAULTS = { strategy: 'close', closeAfterDays: 14, deleteAfterDays: 14, maxRunning: null };
|
|
16
|
+
export const CLEANUP_DEFAULTS = { strategy: 'close', closeAfterDays: 14, deleteAfterDays: 14, maxRunning: null, idleHours: null };
|
|
16
17
|
const CAP_GRACE_MS = 5 * 60_000;
|
|
17
|
-
const
|
|
18
|
+
const HOUR = 3_600_000;
|
|
19
|
+
const DAY = 24 * HOUR;
|
|
18
20
|
const TEAM_DONE = new Set(['done', 'stopped']);
|
|
19
21
|
|
|
20
22
|
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
@@ -29,6 +31,7 @@ export function cleanupSettings(config = {}) {
|
|
|
29
31
|
closeAfterDays: n(c.closeAfterDays, CLEANUP_DEFAULTS.closeAfterDays),
|
|
30
32
|
deleteAfterDays: n(c.deleteAfterDays, CLEANUP_DEFAULTS.deleteAfterDays),
|
|
31
33
|
maxRunning: Number(c.maxRunning) >= 1 ? Math.min(500, Math.floor(Number(c.maxRunning))) : null,
|
|
34
|
+
idleHours: Number(c.idleHours) >= 1 ? Math.min(720, Math.floor(Number(c.idleHours))) : null,
|
|
32
35
|
};
|
|
33
36
|
}
|
|
34
37
|
|
|
@@ -63,7 +66,7 @@ export class Cleanup {
|
|
|
63
66
|
this.timer.unref?.();
|
|
64
67
|
// The cap: checked soon after agents change (one starts) and every minute.
|
|
65
68
|
this.onChange = () => {
|
|
66
|
-
if (!this.settings.maxRunning || this.capSoon) return;
|
|
69
|
+
if ((!this.settings.maxRunning && !this.settings.idleHours) || this.capSoon) return;
|
|
67
70
|
this.capSoon = setTimeout(() => {
|
|
68
71
|
this.capSoon = null;
|
|
69
72
|
this.enforceCap().catch((e) => this.log(`cap: ${e.message}`));
|
|
@@ -88,16 +91,24 @@ export class Cleanup {
|
|
|
88
91
|
return this.store.list().filter((a) => a.kind !== 'assistant' && this.manager.runtimes.get(a.id)?.pty);
|
|
89
92
|
}
|
|
90
93
|
|
|
91
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Which open agents to close: those idle `idleHours` or more, and, above the cap, the ones idle
|
|
96
|
+
* longest until back under it. Protected and recently active agents are skipped.
|
|
97
|
+
*/
|
|
92
98
|
capPlan(now = Date.now()) {
|
|
93
|
-
const max = this.settings
|
|
99
|
+
const { maxRunning: max, idleHours } = this.settings;
|
|
94
100
|
const running = this.runningAgents();
|
|
95
|
-
|
|
101
|
+
const over = max ? running.length - max : 0;
|
|
102
|
+
if (over <= 0 && !idleHours) return { max, idleHours, running: running.length, close: [] };
|
|
96
103
|
const activeAt = (a) => Date.parse(this.manager.activeAt(a, this.manager.runtimes.get(a.id)) ?? a.createdAt) || now;
|
|
97
104
|
const closable = running
|
|
98
105
|
.filter((a) => !this.protectedBy(a) && !this.manager.runtimes.get(a.id)?.attention && now - activeAt(a) >= (this.config.capGraceMs ?? CAP_GRACE_MS))
|
|
99
106
|
.sort((x, y) => activeAt(x) - activeAt(y));
|
|
100
|
-
|
|
107
|
+
const close = closable
|
|
108
|
+
.map((a, i) => ({ a, why: idleHours && now - activeAt(a) >= idleHours * HOUR ? 'idle' : i < over ? 'cap' : null }))
|
|
109
|
+
.filter((x) => x.why)
|
|
110
|
+
.map(({ a, why }) => ({ id: a.id, name: a.name, idleMin: Math.floor((now - activeAt(a)) / 60_000), why }));
|
|
111
|
+
return { max, idleHours, running: running.length, close };
|
|
101
112
|
}
|
|
102
113
|
|
|
103
114
|
async enforceCap() {
|
|
@@ -110,7 +121,7 @@ export class Cleanup {
|
|
|
110
121
|
for (const row of plan.close) {
|
|
111
122
|
try {
|
|
112
123
|
await this.manager.stop(row.id);
|
|
113
|
-
this.manager.patch(row.id, { closedBy:
|
|
124
|
+
this.manager.patch(row.id, { closedBy: row.why });
|
|
114
125
|
closed.push(row);
|
|
115
126
|
} catch (e) {
|
|
116
127
|
this.log(`cap: couldn't close ${row.name}: ${e.message}`);
|
|
@@ -120,7 +131,7 @@ export class Cleanup {
|
|
|
120
131
|
this.capping = false;
|
|
121
132
|
}
|
|
122
133
|
if (closed.length) {
|
|
123
|
-
this.log(`cap: ${plan.running} open
|
|
134
|
+
this.log(`cap: ${plan.running} open${plan.max ? `, limit ${plan.max}` : ''}${plan.idleHours ? `, close after ${plan.idleHours} h idle` : ''}; closed ${closed.map((r) => `${r.name} (idle ${r.idleMin} min)`).join(', ')}`);
|
|
124
135
|
this.store.data.cleanup.lastCap = { at: new Date().toISOString(), closed };
|
|
125
136
|
this.store.save();
|
|
126
137
|
}
|
|
@@ -141,9 +152,13 @@ export class Cleanup {
|
|
|
141
152
|
if (patch.maxRunning !== undefined && patch.maxRunning !== null && patch.maxRunning !== '' && Number(patch.maxRunning) !== 0 && !(Number(patch.maxRunning) >= 1)) {
|
|
142
153
|
throw err(400, 'maxRunning must be 1 or more, or empty for no cap');
|
|
143
154
|
}
|
|
155
|
+
// idleHours: close open sessions idle this many hours, or empty/null/0 for never.
|
|
156
|
+
if (patch.idleHours !== undefined && patch.idleHours !== null && patch.idleHours !== '' && Number(patch.idleHours) !== 0 && !(Number(patch.idleHours) >= 1)) {
|
|
157
|
+
throw err(400, 'idleHours must be 1 or more, or empty to keep idle sessions open');
|
|
158
|
+
}
|
|
144
159
|
const next = cleanupSettings({ cleanup: { ...this.config.cleanup, ...patch } });
|
|
145
160
|
this.config.cleanup = next;
|
|
146
|
-
if (next.maxRunning) this.onChange?.();
|
|
161
|
+
if (next.maxRunning || next.idleHours) this.onChange?.();
|
|
147
162
|
return next;
|
|
148
163
|
}
|
|
149
164
|
|
package/src/cli.js
CHANGED
|
@@ -1299,11 +1299,12 @@ export async function main(argv) {
|
|
|
1299
1299
|
else if (action) throw new Error('Use: agentmgr rules [allow <n> | no <n> | rm <n>]');
|
|
1300
1300
|
if (r.suggestions.length) {
|
|
1301
1301
|
console.log(bold('Suggested') + dim(` (you allowed these ${r.suggestAfter}+ times; agentmgr rules allow <n> | no <n>)`));
|
|
1302
|
-
r.suggestions.forEach((x, i) => console.log(` ${i + 1}. ${x.label} ${dim(`in ${repoLabel(x.repo)}, allowed ${x.n} times`)}`));
|
|
1302
|
+
r.suggestions.forEach((x, i) => console.log(` ${i + 1}. ${x.label} ${dim(x.everywhere ? `in every repo (allowed in ${x.n} repos)` : `in ${repoLabel(x.repo)}, allowed ${x.n} times`)}`));
|
|
1303
1303
|
}
|
|
1304
1304
|
console.log(bold('Allowed') + dim(' (agents in the repo run these without asking; agentmgr rules rm <n>)'));
|
|
1305
1305
|
if (!r.allowed.length) console.log(dim(' none yet'));
|
|
1306
|
-
r.allowed.forEach((x, i) => console.log(` ${i + 1}. ${x.label} ${dim(`in ${repoLabel(x.repo)}${x.uses ? `, answered ${x.uses} prompts` : ''}`)}`));
|
|
1306
|
+
r.allowed.forEach((x, i) => console.log(` ${i + 1}. ${x.label} ${dim(`in ${x.repo === '*' ? 'every repo' : repoLabel(x.repo)}${x.uses ? `, answered ${x.uses} prompts` : ''}`)}`));
|
|
1307
|
+
if (r.readOnly?.length) console.log(dim(`Never asked anywhere (they only look): ${r.readOnly.join(', ')}`));
|
|
1307
1308
|
});
|
|
1308
1309
|
|
|
1309
1310
|
program
|
|
@@ -1366,6 +1367,18 @@ export async function main(argv) {
|
|
|
1366
1367
|
console.log(`${green('+')} ${bold(f.name)} ${f.id} forked from ${a.name}${opts.checkpoint ? ` at checkpoint ${opts.checkpoint}` : ''} session ${cyan(f.sessionId)}`);
|
|
1367
1368
|
});
|
|
1368
1369
|
|
|
1370
|
+
program
|
|
1371
|
+
.command('continue-on')
|
|
1372
|
+
.description("Carry an agent's work on with another engine (when it hits a limit): a new agent in the same folder and branch")
|
|
1373
|
+
.argument('<agent>')
|
|
1374
|
+
.argument('<engine>', 'codex, antigravity, muse, claude, or an ACP engine (acp-<name>)')
|
|
1375
|
+
.action(async (ref, engine) => {
|
|
1376
|
+
await daemon();
|
|
1377
|
+
const a = await resolveAgent(ref);
|
|
1378
|
+
const n = await api('POST', `/agents/${a.id}/continue-on`, { engine });
|
|
1379
|
+
console.log(`${green('+')} ${bold(n.name)} ${n.id} continues ${a.name} on ${engine}, in ${a.workdir}`);
|
|
1380
|
+
});
|
|
1381
|
+
|
|
1369
1382
|
program
|
|
1370
1383
|
.command('checkpoints')
|
|
1371
1384
|
.description('Checkpoints saved at the end of each turn (fork from one with agentmgr fork -c)')
|
|
@@ -1908,10 +1921,12 @@ export async function main(argv) {
|
|
|
1908
1921
|
.option('--close-after <days>', 'close sessions idle this many days')
|
|
1909
1922
|
.option('--delete-after <days>', 'delete agents closed this many days')
|
|
1910
1923
|
.option('--max-open <n>', 'keep at most this many agents open; the ones idle longest are closed above it ("off": no limit)')
|
|
1924
|
+
.option('--idle-hours <h>', 'close open sessions idle this many hours; they resume when opened ("off": never)')
|
|
1911
1925
|
.action(async (opts) => {
|
|
1912
1926
|
await daemon();
|
|
1913
1927
|
const patch = {
|
|
1914
1928
|
...(opts.maxOpen ? { maxRunning: /^(off|none|0)$/i.test(opts.maxOpen) ? null : Number(opts.maxOpen) } : {}),
|
|
1929
|
+
...(opts.idleHours ? { idleHours: /^(off|none|0)$/i.test(opts.idleHours) ? null : Number(opts.idleHours) } : {}),
|
|
1915
1930
|
...(opts.strategy ? { strategy: opts.strategy } : {}),
|
|
1916
1931
|
...(opts.closeAfter ? { closeAfterDays: Number(opts.closeAfter) } : {}),
|
|
1917
1932
|
...(opts.deleteAfter ? { deleteAfterDays: Number(opts.deleteAfter) } : {}),
|
|
@@ -1928,7 +1943,7 @@ export async function main(argv) {
|
|
|
1928
1943
|
const c = await api('GET', '/cleanup');
|
|
1929
1944
|
const what = { 'close-delete': 'closes and deletes automatically', close: 'closes automatically; delete with --run', manual: 'nothing automatic; use --run', off: 'off' }[c.strategy];
|
|
1930
1945
|
console.log(`${bold('Clean up')}: ${c.strategy} (${what}) · close after ${c.closeAfterDays} days idle · delete ${c.deleteAfterDays} days after closing`);
|
|
1931
|
-
console.log(`${bold('Open agents')}: ${c.running} open · ${c.maxRunning ? `at most ${c.maxRunning} (the ones idle longest close above it)` : 'no limit (set one: --max-open <n>)'}`);
|
|
1946
|
+
console.log(`${bold('Open agents')}: ${c.running} open · ${c.maxRunning ? `at most ${c.maxRunning} (the ones idle longest close above it)` : 'no limit (set one: --max-open <n>)'}${c.idleHours ? ` · close after ${c.idleHours} h idle` : ''}`);
|
|
1932
1947
|
if (c.lastCap) console.log(dim(` last closed for the limit ${new Date(c.lastCap.at).toLocaleString()}: ${c.lastCap.closed.map((x) => x.name).join(', ')}`));
|
|
1933
1948
|
const rows = [
|
|
1934
1949
|
...c.close.map((x) => [yellow('close'), x.name, `idle ${x.idleDays}d`, '']),
|
package/src/engines/codex.js
CHANGED
|
@@ -286,6 +286,18 @@ export default {
|
|
|
286
286
|
[/Wouldyouliketo(run|make|apply|allow|grant)/i, 'Permission prompt'],
|
|
287
287
|
],
|
|
288
288
|
|
|
289
|
+
/** The command a "Would you like to run the following command?" prompt is about, as a Bash call. */
|
|
290
|
+
screenCall(screen) {
|
|
291
|
+
const text = String(screen ?? '')
|
|
292
|
+
.replace(/\x1b\[(\d*)C/g, ' ')
|
|
293
|
+
.replace(ANSI, ' ')
|
|
294
|
+
.replace(/\s+/g, ' ');
|
|
295
|
+
const at = text.lastIndexOf('Would you like to run the following command?');
|
|
296
|
+
if (at < 0) return null;
|
|
297
|
+
const m = /^Would you like to run the following command\?.*?\$ (.+?)\s+(?:›\s*)?1\. /.exec(text.slice(at));
|
|
298
|
+
return m ? { name: 'Bash', input: { command: m[1].trim() } } : null;
|
|
299
|
+
},
|
|
300
|
+
|
|
289
301
|
/** Codex's menus: "› 1. Yes, proceed (y)" ... "3. No, and tell Codex what to do differently (esc)". */
|
|
290
302
|
promptChoices(screen) {
|
|
291
303
|
const text = String(screen ?? '')
|
package/src/limits.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// When an engine stops for a limit: a usage limit or exhausted quota ("Claude usage limit
|
|
2
|
+
// reached… resets 3pm", Codex's "You've hit your usage limit… try again at 3:05 PM"), or a busy or
|
|
3
|
+
// failing service (429, 529 overloaded, 5xx). Read from the end of the agent's screen once a turn
|
|
4
|
+
// ends. The manager shows it, types "continue" when the limit resets (a few minutes later for a
|
|
5
|
+
// busy service), and offers to carry the work on with another engine.
|
|
6
|
+
|
|
7
|
+
// Engines' own words, not an agent talking about rate limits in its code: a limit names your
|
|
8
|
+
// usage, quota or credits; a 429 or an overload has to read as an error.
|
|
9
|
+
const LIMIT = [
|
|
10
|
+
/usage limit (?:reached|hit)|(?:hit|reached) (?:your|the) (?:usage |session |weekly |5-hour |daily )?limit\b/i,
|
|
11
|
+
/\b(?:5-hour|weekly|daily|session|opus|sonnet) limit reached/i,
|
|
12
|
+
/quota (?:exceeded|exhausted)|exceeded your (?:current )?quota|RESOURCE_EXHAUSTED/i,
|
|
13
|
+
/out of (?:credits|extra usage)|credit balance is too low/i,
|
|
14
|
+
];
|
|
15
|
+
const BUSY = [/(?:api error|error|■)[^\n]{0,80}(?:\b429\b|rate limit|\b529\b|overloaded|\b50[0234]\b)/i, /overloaded_error/i];
|
|
16
|
+
// A busy service says nothing about when: try again after this long.
|
|
17
|
+
export const BUSY_RETRY_MS = 5 * 60_000;
|
|
18
|
+
|
|
19
|
+
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
|
|
20
|
+
|
|
21
|
+
/** Minutes a time zone is ahead of UTC at `t`, or null for a zone this Node doesn't know. */
|
|
22
|
+
function zoneOffset(zone, t) {
|
|
23
|
+
try {
|
|
24
|
+
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }).formatToParts(t).map((p) => [p.type, p.value]));
|
|
25
|
+
return (Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute) - Math.floor(t / 60_000) * 60_000) / 60_000;
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Wall-clock fields in a zone (or this machine's, without one) as epoch ms. */
|
|
32
|
+
function wallTime(y, mo, d, h, min, zone, near) {
|
|
33
|
+
if (!zone) return new Date(y, mo, d, h, min).getTime();
|
|
34
|
+
const guess = Date.UTC(y, mo, d, h, min);
|
|
35
|
+
const off = zoneOffset(zone, near);
|
|
36
|
+
return off === null ? new Date(y, mo, d, h, min).getTime() : guess - off * 60_000;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Today's date in a zone (or here), as [year, month, day]. */
|
|
40
|
+
function today(zone, now) {
|
|
41
|
+
const off = zone ? zoneOffset(zone, now) : null;
|
|
42
|
+
const d = off === null ? new Date(now) : new Date(now + off * 60_000);
|
|
43
|
+
return off === null ? [d.getFullYear(), d.getMonth(), d.getDate()] : [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** "3pm", "3:05 PM", "15:00", with an optional "Nov 12" before it and "(Area/City)" after: the next such time. */
|
|
47
|
+
function clockTime(s, now) {
|
|
48
|
+
const m = /(?:\b([a-z]{3})[a-z]*\.? (\d{1,2}),? (?:at )?)?\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i.exec(s);
|
|
49
|
+
if (!m) return null;
|
|
50
|
+
let h = Number(m[3]);
|
|
51
|
+
const min = Number(m[4] ?? 0);
|
|
52
|
+
const ampm = m[5]?.toLowerCase();
|
|
53
|
+
if (!ampm && m[4] === undefined) return null; // a bare number isn't a time
|
|
54
|
+
if (h > 23 || min > 59 || (ampm && (h < 1 || h > 12))) return null;
|
|
55
|
+
if (ampm === 'pm' && h < 12) h += 12;
|
|
56
|
+
if (ampm === 'am' && h === 12) h = 0;
|
|
57
|
+
const zone = /\(([A-Za-z_]+\/[A-Za-z_/+-]+|UTC)\)/.exec(s)?.[1] ?? null;
|
|
58
|
+
const [y, mo, d] = today(zone, now);
|
|
59
|
+
const month = m[1] ? MONTHS.indexOf(m[1].toLowerCase()) : -1;
|
|
60
|
+
if (month >= 0) {
|
|
61
|
+
let t = wallTime(y, month, Number(m[2]), h, min, zone, now);
|
|
62
|
+
if (t < now - 86_400_000) t = wallTime(y + 1, month, Number(m[2]), h, min, zone, now);
|
|
63
|
+
return t;
|
|
64
|
+
}
|
|
65
|
+
const t = wallTime(y, mo, d, h, min, zone, now);
|
|
66
|
+
return t > now ? t : wallTime(y, mo, d + 1, h, min, zone, now);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** "in 2h 15m", "in 45 minutes", "in 3 hours": from `now`. */
|
|
70
|
+
function inTime(s, now) {
|
|
71
|
+
const m = /\bin (?:(\d+)\s*(?:h|hr|hrs|hours?))?\s*(?:(\d+)\s*(?:m|min|mins|minutes?))?\b/i.exec(s);
|
|
72
|
+
if (!m || (!m[1] && !m[2])) return null;
|
|
73
|
+
return now + (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60_000;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** When a limit message says it resets, as epoch ms, or null. */
|
|
77
|
+
export function resetTime(text, now = Date.now()) {
|
|
78
|
+
const m = /(?:resets?|reset at|resets at|try again|available again|retry)\b([^\n]{0,60})/i.exec(text);
|
|
79
|
+
if (!m) return null;
|
|
80
|
+
return inTime(m[1], now) ?? clockTime(m[1], now);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A limit at the end of a screen: { kind: 'limit' | 'busy', text, resetAt } (resetAt an ISO time,
|
|
85
|
+
* or null when a usage limit doesn't say), or null. Only the last lines count.
|
|
86
|
+
*/
|
|
87
|
+
export function findLimit(screen, now = Date.now()) {
|
|
88
|
+
const lines = String(screen ?? '')
|
|
89
|
+
.split('\n')
|
|
90
|
+
.map((l) => l.trim())
|
|
91
|
+
.filter(Boolean)
|
|
92
|
+
.slice(-8);
|
|
93
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
94
|
+
const line = lines[i];
|
|
95
|
+
const kind = LIMIT.some((re) => re.test(line)) ? 'limit' : BUSY.some((re) => re.test(line)) ? 'busy' : null;
|
|
96
|
+
if (!kind) continue;
|
|
97
|
+
// The reset time is often on the same line, sometimes on the next.
|
|
98
|
+
const at = kind === 'limit' ? resetTime(lines.slice(i, i + 2).join(' '), now) : now + BUSY_RETRY_MS;
|
|
99
|
+
return { kind, text: line.slice(0, 200), resetAt: at ? new Date(at).toISOString() : null };
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The first message for an agent that carries on another's work with a different engine. */
|
|
105
|
+
export function continuePrompt({ from, engineLabel, limit, intent, branch, brief, digest }) {
|
|
106
|
+
return [
|
|
107
|
+
`Continue this work. ${from} (${engineLabel}) was doing it in this folder${branch ? `, on branch ${branch}` : ''}, and stopped${limit ? ` at a limit ("${limit}")` : ''}.`,
|
|
108
|
+
`The original request:\n${intent}`,
|
|
109
|
+
brief ? `Its brief (what it planned and where it got to):\n${brief.slice(-6000)}` : null,
|
|
110
|
+
digest ? `The end of its conversation:\n${digest.slice(-4000)}` : null,
|
|
111
|
+
"Check `git status` and `git log` to see what is already done, then carry on from there. Don't redo finished work.",
|
|
112
|
+
]
|
|
113
|
+
.filter(Boolean)
|
|
114
|
+
.join('\n\n');
|
|
115
|
+
}
|
package/src/manager.js
CHANGED
|
@@ -126,6 +126,7 @@ import { leadPrompt, subagents, teamDir, teamPrompt } from './teams.js';
|
|
|
126
126
|
import { assistantDir, currentPrompt } from './assistant.js';
|
|
127
127
|
import { learnCommand, memoryKey, memoryPrompt, memoryText } from './memory.js';
|
|
128
128
|
import { Rules, describeTool } from './rules.js';
|
|
129
|
+
import { continuePrompt, findLimit } from './limits.js';
|
|
129
130
|
import { runningClaude, scanClaudeSessions } from './sessions.js';
|
|
130
131
|
import { builderAllowedTools, builderPrompt } from './builder.js';
|
|
131
132
|
import { DRIVE_DOCS, DRIVE_TOOLS, docUrl, driveHtml, drivePrompt, folderUrl, parseDrive } from './drive.js';
|
|
@@ -301,7 +302,7 @@ export class AgentManager extends EventEmitter {
|
|
|
301
302
|
this.stuck = new Map(); // agent id -> [finding]
|
|
302
303
|
this.outbox = new Map(); // agent id -> [message] waiting to be typed into its session
|
|
303
304
|
// The AI judge: rules decide when to look, a model decides what is going on (see judge.js).
|
|
304
|
-
this.rules = new Rules({ suggestAfter: config.rules?.suggestAfter });
|
|
305
|
+
this.rules = new Rules({ suggestAfter: config.rules?.suggestAfter, readOnly: config.rules?.readOnly });
|
|
305
306
|
this.inboxSources = [];
|
|
306
307
|
this.judge = new Judge({ config, call: (agent, prompt, { timeoutMs }) => this.oneShot(agent, prompt, { ...this.judgeModel(agent), timeoutMs }) });
|
|
307
308
|
this.stuckVerdicts = new Map(); // agent id -> Map(finding key -> { at, since, data })
|
|
@@ -390,6 +391,8 @@ export class AgentManager extends EventEmitter {
|
|
|
390
391
|
attention: (rt?.pty && !rt.busy && rt.attention) || null,
|
|
391
392
|
// What the AI judge read on an idle screen no rule matched: a question or an error.
|
|
392
393
|
waiting: (rt?.pty && !rt.busy && !rt.attention && rt.waiting) || null,
|
|
394
|
+
// Stopped at a usage limit or a busy service (limits.js): { kind, text, resetAt, resumedAt }.
|
|
395
|
+
limited: (rt?.pty && !rt.busy && !rt.attention && rt.limited) || null,
|
|
393
396
|
clients: rt?.clients.size ?? 0,
|
|
394
397
|
shell: this.shellNumbers(agent.id).length > 0,
|
|
395
398
|
shells: this.shellNumbers(agent.id),
|
|
@@ -1452,6 +1455,7 @@ export class AgentManager extends EventEmitter {
|
|
|
1452
1455
|
if (!rt.busy) {
|
|
1453
1456
|
rt.busy = true;
|
|
1454
1457
|
rt.waiting = null;
|
|
1458
|
+
rt.limited = null;
|
|
1455
1459
|
rt.screenChecked = false;
|
|
1456
1460
|
const a = this.store.get(agent.id);
|
|
1457
1461
|
if (a) this.changed(a);
|
|
@@ -3293,6 +3297,10 @@ export class AgentManager extends EventEmitter {
|
|
|
3293
3297
|
if (v.runtime.attention) {
|
|
3294
3298
|
items.push({ ...base, kind: 'prompt', key: `prompt:${agent.id}`, title: v.runtime.attention, prompt: v.runtime.prompt, at: v.runtime.lastOutputAt });
|
|
3295
3299
|
}
|
|
3300
|
+
if (v.runtime.limited) {
|
|
3301
|
+
const l = v.runtime.limited;
|
|
3302
|
+
items.push({ ...base, kind: 'limit', key: `limit:${agent.id}`, title: `${engineOf(agent).label} ${l.kind === 'busy' ? 'is busy or failing' : 'hit a limit'}: ${l.text}`, limited: l, at: l.at });
|
|
3303
|
+
}
|
|
3296
3304
|
if (v.runtime.waiting) {
|
|
3297
3305
|
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 });
|
|
3298
3306
|
}
|
|
@@ -3309,10 +3317,10 @@ export class AgentManager extends EventEmitter {
|
|
|
3309
3317
|
}
|
|
3310
3318
|
}
|
|
3311
3319
|
// Commands you keep allowing in a repo: offer to always allow them there.
|
|
3312
|
-
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 });
|
|
3320
|
+
for (const r of this.rules.view().suggestions) items.push({ kind: 'rule', key: `rule:${r.repo}:${r.rule}`, title: `Always allow ${r.label}${r.everywhere ? ' in every repo' : ''}?`, priority: 2, ...r });
|
|
3313
3321
|
// Others' items (autopilot's held backlog work).
|
|
3314
3322
|
for (const source of this.inboxSources) items.push(...source());
|
|
3315
|
-
const order = { prompt: 0, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
|
|
3323
|
+
const order = { prompt: 0, limit: 1, waiting: 1, question: 1, rule: 2, review: 2, autopilot: 2, stuck: 3, conflict: 4, reminder: 5, repeat: 5 };
|
|
3316
3324
|
return items.sort((a, b) => order[a.kind] - order[b.kind] || a.priority - b.priority);
|
|
3317
3325
|
}
|
|
3318
3326
|
|
|
@@ -3323,9 +3331,13 @@ export class AgentManager extends EventEmitter {
|
|
|
3323
3331
|
return call ? { ...p, tool: describeTool(call) } : p;
|
|
3324
3332
|
}
|
|
3325
3333
|
|
|
3326
|
-
/**
|
|
3334
|
+
/**
|
|
3335
|
+
* The one tool call a live prompt is waiting on: from the transcript (Claude Code), or from the
|
|
3336
|
+
* prompt on screen for engines that show it there (Codex); null when unsure.
|
|
3337
|
+
*/
|
|
3327
3338
|
pendingCall(agent) {
|
|
3328
3339
|
const engine = engineOf(agent);
|
|
3340
|
+
if (engine.screenCall) return engine.screenCall(this.runtimes.get(agent.id)?.tail ?? '');
|
|
3329
3341
|
if (engine.id !== 'claude' || !agent.workdir || !agent.sessionId) return null;
|
|
3330
3342
|
const key = `${agent.sessionId}:${agent.workdir}`;
|
|
3331
3343
|
const state = this.activity.get(key) ?? {};
|
|
@@ -3470,6 +3482,68 @@ export class AgentManager extends EventEmitter {
|
|
|
3470
3482
|
return { workdir, sourceDir: root, branch, worktree: true, repo: src.repo, baseRef: src.baseRef };
|
|
3471
3483
|
}
|
|
3472
3484
|
|
|
3485
|
+
// ------------------------------------------------------- limits
|
|
3486
|
+
|
|
3487
|
+
/** The limit at the end of an idle agent's screen, keeping when it was first seen and resumed. */
|
|
3488
|
+
limitOf(id, rt, t = Date.now()) {
|
|
3489
|
+
const found = findLimit(this.screenText(rt), t);
|
|
3490
|
+
if (!found) return null;
|
|
3491
|
+
const prev = rt.limited ?? rt.lastLimit;
|
|
3492
|
+
// The same limit seen again before it was resumed (a repaint): keep its times.
|
|
3493
|
+
if (prev && !prev.resumedAt && prev.text === found.text) return (rt.lastLimit = prev);
|
|
3494
|
+
const agent = this.store.get(id);
|
|
3495
|
+
if (agent) console.log(`[agentmgr] ${agent.name}: ${engineOf(agent).label} stopped at a limit (${found.text})${found.resetAt ? `; resets ${found.resetAt}` : ''}`);
|
|
3496
|
+
return (rt.lastLimit = { ...found, at: new Date(t).toISOString(), resumedAt: null });
|
|
3497
|
+
}
|
|
3498
|
+
|
|
3499
|
+
/**
|
|
3500
|
+
* Agents stopped at a limit get "continue" once it resets (a busy service: a few minutes on),
|
|
3501
|
+
* at most three times an hour each. config.json "limits": { "autoResume": false } turns it off.
|
|
3502
|
+
*/
|
|
3503
|
+
resumeLimited(t = Date.now()) {
|
|
3504
|
+
if (this.config.limits?.autoResume === false) return;
|
|
3505
|
+
for (const [id, rt] of this.runtimes) {
|
|
3506
|
+
const l = rt.limited;
|
|
3507
|
+
if (!rt.pty || rt.busy || !l?.resetAt || l.resumedAt || t < Date.parse(l.resetAt) + (l.kind === 'limit' ? 60_000 : 0)) continue;
|
|
3508
|
+
rt.limitResumes = (rt.limitResumes ?? []).filter((x) => t - x < 3_600_000);
|
|
3509
|
+
if (rt.limitResumes.length >= 3) continue;
|
|
3510
|
+
rt.limitResumes.push(t);
|
|
3511
|
+
l.resumedAt = new Date(t).toISOString();
|
|
3512
|
+
try {
|
|
3513
|
+
this.tell(id, 'Continue where you left off.', { source: 'limit' });
|
|
3514
|
+
} catch {}
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
|
|
3518
|
+
/**
|
|
3519
|
+
* Carry an agent's work on with another engine: a new agent in the same folder and branch,
|
|
3520
|
+
* started with the request, the brief and the end of the conversation (a conversation can't
|
|
3521
|
+
* move between engines). The new agent owns the folder from then on; the old one is closed.
|
|
3522
|
+
*/
|
|
3523
|
+
async continueOn(ref, { engine } = {}) {
|
|
3524
|
+
const src = this.mustGet(ref);
|
|
3525
|
+
const target = engineOf(engine);
|
|
3526
|
+
if (target.id === (src.engine ?? DEFAULT_ENGINE)) throw Object.assign(new Error(`${src.name} already runs on ${target.label}`), { status: 400 });
|
|
3527
|
+
if (!installed(target, this.config)) throw Object.assign(new Error(notInstalled(target, this.config)), { status: 409 });
|
|
3528
|
+
if (!src.workdir || src.sharedWith || NO_REPO.has(src.kind)) throw Object.assign(new Error('Only an agent with its own folder can continue on another engine'), { status: 409 });
|
|
3529
|
+
if (this.store.list().some((a) => a.continuesFrom?.agentId === src.id)) {
|
|
3530
|
+
throw Object.assign(new Error(`${src.name} already continues as another agent`), { status: 409 });
|
|
3531
|
+
}
|
|
3532
|
+
const ctx = await this.explainContext(src);
|
|
3533
|
+
const limit = this.runtimes.get(src.id)?.limited?.text ?? null;
|
|
3534
|
+
const intent = continuePrompt({ from: src.name, engineLabel: engineOf(src).label, limit, intent: src.intent, branch: src.branch ?? src.git?.branch, brief: ctx.briefMarkdown, digest: ctx.digest });
|
|
3535
|
+
if (this.runtimes.get(src.id)?.pty) await this.stop(src.id);
|
|
3536
|
+
const ws = { workdir: src.workdir, sourceDir: src.sourceDir, branch: src.branch, worktree: src.worktree, repo: src.repo, baseRef: src.baseRef };
|
|
3537
|
+
const permissionMode = target.permissionModes.includes(src.permissionMode) ? src.permissionMode : undefined;
|
|
3538
|
+
const name = `${src.name.replace(/-(claude|codex|antigravity|muse|acp-[\w-]+)$/, '')}-${target.id}`;
|
|
3539
|
+
const agent = this.create({ intent, name, engine: target.id, permissionMode, project: src.project ?? undefined, priority: src.priority, start: true, workspace: async () => ws });
|
|
3540
|
+
// The folder is the new agent's now: deleting the old one must not take it.
|
|
3541
|
+
this.patch(src.id, { sharedWith: agent.id, worktree: false, continuedOn: { agentId: agent.id, name: agent.name, engine: target.id, label: target.label, at: now() } });
|
|
3542
|
+
this.patch(agent.id, { continuesFrom: { agentId: src.id, name: src.name, engine: engineOf(src).id, label: engineOf(src).label, at: now() } });
|
|
3543
|
+
this.plugins.emit('agent.continued', { from: this.auditView(this.store.get(src.id)), to: this.auditView(this.store.get(agent.id)) });
|
|
3544
|
+
return this.view(this.store.get(agent.id));
|
|
3545
|
+
}
|
|
3546
|
+
|
|
3473
3547
|
tick() {
|
|
3474
3548
|
this.tickCount++;
|
|
3475
3549
|
const t = Date.now();
|
|
@@ -3480,18 +3554,21 @@ export class AgentManager extends EventEmitter {
|
|
|
3480
3554
|
const a0 = this.store.get(id);
|
|
3481
3555
|
rt.attention = (a0 ? engineOf(a0).attention : []).find(([re]) => re.test(screen))?.[1] ?? null;
|
|
3482
3556
|
if (a0 && rt.attention === PERMISSION) this.autoAllow(a0, rt);
|
|
3557
|
+
// Stopped at a usage limit or a busy service: shown, and resumed when it resets.
|
|
3558
|
+
rt.limited = a0 && !rt.attention ? this.limitOf(id, rt, t) : null;
|
|
3483
3559
|
const a = this.store.get(id);
|
|
3484
3560
|
if (a) this.changed(a);
|
|
3485
3561
|
// A turn just ended: remember the code and conversation at this point.
|
|
3486
3562
|
if (a && !rt.planning && !rt.attention) this.checkpoint(id).catch(() => {});
|
|
3487
3563
|
}
|
|
3488
3564
|
}
|
|
3565
|
+
this.resumeLimited(t);
|
|
3489
3566
|
this.deliverOutbox(t);
|
|
3490
3567
|
this.scanSignIns();
|
|
3491
3568
|
if (this.judge.enabled) {
|
|
3492
3569
|
const idleMs = this.judge.settings.idleSec * 1000;
|
|
3493
3570
|
for (const [id, rt] of this.runtimes) {
|
|
3494
|
-
if (!rt.pty || rt.busy || rt.attention || rt.planning || rt.screenChecked || this.outbox.get(id)?.length) continue;
|
|
3571
|
+
if (!rt.pty || rt.busy || rt.attention || rt.limited || rt.planning || rt.screenChecked || this.outbox.get(id)?.length) continue;
|
|
3495
3572
|
// A team member that finished its step is meant to sit idle until its next turn.
|
|
3496
3573
|
if (this.idleExpected?.(id)) continue;
|
|
3497
3574
|
if (!rt.lastOutputAt || t - rt.lastOutputAt < idleMs) continue;
|
package/src/reminders.js
CHANGED
|
@@ -51,8 +51,8 @@ export function reminderFor(v, settings, t = Date.now()) {
|
|
|
51
51
|
return { kind: 'followup', title: `Quiet for ${hours(quiet)} and not finished`, detail, since };
|
|
52
52
|
}
|
|
53
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';
|
|
54
|
+
const byItself = v.status === 'exited' || v.closedBy === 'cap' || v.closedBy === 'idle' || v.closedBy === 'cleanup';
|
|
55
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';
|
|
56
|
+
const how = v.closedBy === 'cap' ? 'closed by the session cap' : v.closedBy === 'idle' ? 'closed after being idle' : v.closedBy === 'cleanup' ? 'closed by clean up' : 'its session ended';
|
|
57
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
58
|
}
|