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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +767 -2
- package/SECURITY.md +44 -0
- package/bin/agentmgr-hub.js +16 -0
- package/bin/agentmgr.js +4 -0
- package/docs/architecture.md +67 -0
- package/docs/distributed.md +147 -0
- package/docs/engines.md +177 -0
- package/docs/images/agents.jpg +0 -0
- package/docs/images/conflict-radar.jpg +0 -0
- package/docs/plugins.md +81 -0
- package/package.json +56 -4
- package/public/app.js +3083 -0
- package/public/hub/hub.css +230 -0
- package/public/hub/hub.js +766 -0
- package/public/hub/index.html +146 -0
- package/public/hub/term.js +147 -0
- package/public/index.html +342 -0
- package/public/share.html +34 -0
- package/public/share.js +41 -0
- package/public/style.css +541 -0
- package/public/touchscroll.js +73 -0
- package/public/transport.js +78 -0
- package/scripts/build-release.sh +58 -0
- package/scripts/fix-pty.js +15 -0
- package/src/backlog.js +413 -0
- package/src/brief.js +512 -0
- package/src/cli.js +1447 -0
- package/src/client.js +49 -0
- package/src/config.js +109 -0
- package/src/conflicts.js +105 -0
- package/src/engines/antigravity.js +296 -0
- package/src/engines/claude.js +98 -0
- package/src/engines/codex.js +331 -0
- package/src/engines/index.js +37 -0
- package/src/fleet.js +176 -0
- package/src/git.js +340 -0
- package/src/hub.js +857 -0
- package/src/hubactions.js +107 -0
- package/src/hubbacklog.js +373 -0
- package/src/hublink.js +437 -0
- package/src/inbox.js +94 -0
- package/src/judge.js +278 -0
- package/src/livebrowser.js +637 -0
- package/src/manager.js +2554 -0
- package/src/notify.js +284 -0
- package/src/plugins.js +119 -0
- package/src/preview.js +334 -0
- package/src/races.js +192 -0
- package/src/remote.js +284 -0
- package/src/server.js +759 -0
- package/src/service.js +150 -0
- package/src/sessions.js +160 -0
- package/src/store.js +104 -0
- package/src/stuck.js +160 -0
- package/src/tracker.js +311 -0
- package/src/trust.js +44 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// What a hub may ask this machine to do, and the permission each needs. The list is fixed
|
|
2
|
+
// here (no generic API proxy), every call is checked against this machine's own policy,
|
|
3
|
+
// and agents are matched by exact ID only, within the projects the policy shares.
|
|
4
|
+
//
|
|
5
|
+
// Permissions (config.json "hub.allow"):
|
|
6
|
+
// view see agents and the inbox (phase 1)
|
|
7
|
+
// inbox answer questions, pick prompt choices, send stuck nudges, warn about overlaps
|
|
8
|
+
// control message, start, stop, checkpoint, change priority
|
|
9
|
+
// create start new agents in registered projects
|
|
10
|
+
// terminal live Claude terminals
|
|
11
|
+
// shell shells in an agent's folder (runs any command: grant with care)
|
|
12
|
+
// signin one-time sign-in links to this machine's own page (full access there: grant with care)
|
|
13
|
+
import { engineOf, installed } from './engines/index.js';
|
|
14
|
+
import { allowedProject } from './fleet.js';
|
|
15
|
+
import { createTicket } from './remote.js';
|
|
16
|
+
|
|
17
|
+
export const PERMISSIONS = ['view', 'inbox', 'control', 'create', 'terminal', 'shell', 'signin'];
|
|
18
|
+
// The hub may not start agents that skip permission prompts.
|
|
19
|
+
const HUB_PERMISSION_MODES = new Set(['default', 'acceptEdits', 'plan']);
|
|
20
|
+
|
|
21
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
22
|
+
const text = (v, n = 20_000) => {
|
|
23
|
+
const s = String(v ?? '').trim();
|
|
24
|
+
if (!s) throw err(400, 'Text is required');
|
|
25
|
+
return s.slice(0, n);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** The agent an action targets: exact ID, and in a project this machine shares. */
|
|
29
|
+
function agentFor(manager, policy, id) {
|
|
30
|
+
const agent = manager.store.get(String(id ?? ''));
|
|
31
|
+
if (!agent) throw err(404, 'No such agent on this machine');
|
|
32
|
+
const info = manager.projectInfo(agent);
|
|
33
|
+
if (!allowedProject(policy.projects, info.key === 'other' ? null : info.name, info.shortcut)) throw err(403, 'This machine does not share that project with the hub');
|
|
34
|
+
return agent;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const ACTIONS = {
|
|
38
|
+
answer: { perm: 'inbox', run: (m, a, args) => m.answerQuestion(a.id, String(args.question ?? ''), text(args.text)) },
|
|
39
|
+
'prompt-key': {
|
|
40
|
+
perm: 'inbox',
|
|
41
|
+
run: (m, a, args) => {
|
|
42
|
+
const key = String(args.key ?? '');
|
|
43
|
+
if (!/^(\d|esc)$/.test(key)) throw err(400, 'Key must be a digit or esc');
|
|
44
|
+
return m.answerPrompt(a.id, key);
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
nudge: { perm: 'inbox', run: (m, a, args) => m.nudge(a.id, String(args.key ?? ''), args.text ? text(args.text) : undefined) },
|
|
48
|
+
'dismiss-stuck': { perm: 'inbox', run: (m, a, args) => m.dismissStuck(a.id, String(args.key ?? '')) },
|
|
49
|
+
'dismiss-conflict': { perm: 'inbox', run: (m, a, args) => m.dismissConflict(a.id, String(args.with ?? '')) },
|
|
50
|
+
'answer-waiting': { perm: 'inbox', run: (m, a, args) => m.answerWaiting(a.id, text(args.text)) },
|
|
51
|
+
'dismiss-waiting': { perm: 'inbox', run: (m, a) => m.dismissWaiting(a.id) },
|
|
52
|
+
'ack-review': { perm: 'inbox', run: (m, a, args) => m.ackReview(a.id, String(args.action ?? '')) },
|
|
53
|
+
'warn-conflict': { perm: 'inbox', run: (m, a, args) => m.warnConflict(a.id, String(args.with ?? '')) },
|
|
54
|
+
tell: { perm: 'control', run: (m, a, args) => m.tell(a.id, text(args.text)) },
|
|
55
|
+
start: { perm: 'control', run: (m, a) => m.start(a.id) },
|
|
56
|
+
stop: { perm: 'control', run: (m, a) => m.stop(a.id) },
|
|
57
|
+
checkpoint: { perm: 'control', run: async (m, a) => (m.lastCheckpointTry?.delete(a.id), await m.checkpoint(a.id), m.get(a.id)) },
|
|
58
|
+
priority: { perm: 'control', run: (m, a, args) => m.update(a.id, { priority: args.priority }) },
|
|
59
|
+
create: { perm: 'create', agentless: true, run: (m, _a, args, policy) => createAgent(m, args, policy) },
|
|
60
|
+
signin: { perm: 'signin', agentless: true, run: () => ({ ticket: createTicket() }) },
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
function createAgent(manager, args, policy) {
|
|
64
|
+
const entry = manager.resolveProject(String(args.project ?? ''));
|
|
65
|
+
if (!entry) throw err(400, 'Pick one of the projects this machine shares');
|
|
66
|
+
if (!allowedProject(policy.projects, entry.name, entry.shortcut)) throw err(403, 'This machine does not share that project with the hub');
|
|
67
|
+
let engine;
|
|
68
|
+
if (args.engine) {
|
|
69
|
+
engine = engineOf(String(args.engine)).id;
|
|
70
|
+
if (!installed(engineOf(engine), manager.config)) throw err(400, `${engineOf(engine).label} isn't installed on this machine`);
|
|
71
|
+
}
|
|
72
|
+
const mode = args.permissionMode ?? undefined;
|
|
73
|
+
if (mode !== undefined && !HUB_PERMISSION_MODES.has(mode)) throw err(400, `Permission mode must be one of ${[...HUB_PERMISSION_MODES].join(', ')} from the hub`);
|
|
74
|
+
return manager.createMany([text(args.intent, 10_000)], {
|
|
75
|
+
project: entry.shortcut,
|
|
76
|
+
priority: args.priority,
|
|
77
|
+
model: args.model ? String(args.model).slice(0, 60) : undefined,
|
|
78
|
+
permissionMode: mode,
|
|
79
|
+
engine,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Run one hub action. Throws {status, message} on refusal; returns a small result. */
|
|
84
|
+
export async function runAction(manager, policy, action, args = {}) {
|
|
85
|
+
const def = Object.hasOwn(ACTIONS, action) ? ACTIONS[action] : null;
|
|
86
|
+
if (!def) throw err(400, `Unknown action "${String(action).slice(0, 40)}"`);
|
|
87
|
+
if (!policy.allow.includes(def.perm)) throw err(403, `This machine doesn't allow "${def.perm}" from the hub`);
|
|
88
|
+
const agent = def.agentless ? null : agentFor(manager, policy, args.agent);
|
|
89
|
+
manager.plugins?.check('hub.action', { action, agent: agent ? manager.auditView(agent) : null });
|
|
90
|
+
manager.plugins?.emit('hub.action', { action, agent: agent ? manager.auditView(agent) : null });
|
|
91
|
+
const out = await def.run(manager, agent, args, policy);
|
|
92
|
+
// Enough for the hub to confirm; the next state frame carries the rest.
|
|
93
|
+
if (out?.ticket) return { ok: true, ticket: out.ticket };
|
|
94
|
+
if (Array.isArray(out)) return { ok: true, agents: out.map((a) => ({ id: a.id, name: a.name })) };
|
|
95
|
+
return { ok: true, agent: out?.id ? { id: out.id, name: out.name, status: out.status } : undefined };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Terminal kinds the hub may open: the Claude session, or shell N. */
|
|
99
|
+
export function terminalPermission(kind) {
|
|
100
|
+
const k = String(kind ?? 'claude');
|
|
101
|
+
if (k === 'claude') return { kind: 'claude', perm: 'terminal' };
|
|
102
|
+
const m = k.match(/^shell(?::(\d{1,3}))?$/);
|
|
103
|
+
if (m && Number(m[1] ?? 1) >= 1) return { kind: `shell:${Number(m[1] ?? 1)}`, perm: 'shell' };
|
|
104
|
+
throw err(400, 'Unknown terminal');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export { agentFor };
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
// The hub's shared backlog: work queued once and started on whichever machine has room.
|
|
2
|
+
// Each item becomes one agent on one machine, created through that machine's own "create"
|
|
3
|
+
// action (so its policy and audit log apply), and then followed through the machine's
|
|
4
|
+
// state frames like the local backlog follows its agents.
|
|
5
|
+
//
|
|
6
|
+
// Placement, in order: hard constraints (online, allows "create", shares the project, has
|
|
7
|
+
// every required label), capacity (the machine's limits in total and per project), warm
|
|
8
|
+
// start (the repo is already cloned there), then spread (fewest running agents).
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import { label } from './fleet.js';
|
|
11
|
+
|
|
12
|
+
const now = () => new Date().toISOString();
|
|
13
|
+
const fail = (status, message) => Object.assign(new Error(message), { status });
|
|
14
|
+
const OPEN = new Set(['queued', 'active', 'review', 'blocked']);
|
|
15
|
+
const MODES = new Set(['default', 'acceptEdits', 'plan']);
|
|
16
|
+
// An agent the machine hasn't reported this long after creating it is treated as removed.
|
|
17
|
+
const MISSING_GRACE_MS = 30_000;
|
|
18
|
+
// After a machine refuses an item, try it elsewhere first.
|
|
19
|
+
const REFUSED_COOLDOWN_MS = 60_000;
|
|
20
|
+
|
|
21
|
+
const priorityOf = (v, d = 2) => {
|
|
22
|
+
const n = Number(String(v ?? '').replace(/^p/i, ''));
|
|
23
|
+
return Number.isInteger(n) && n >= 0 && n <= 4 ? n : d;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Scheduling labels a machine has: what it reports, plus machine:<name>. */
|
|
27
|
+
export const runnerLabels = (r) => new Set([...(r.state?.labels ?? []), `machine:${r.name}`]);
|
|
28
|
+
|
|
29
|
+
/** Items the hub has started on a machine and that still hold one of its slots. */
|
|
30
|
+
const holding = (items, runnerId) => items.filter((x) => x.runnerId === runnerId && (x.status === 'active' || x.starting));
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Pick the machine for one item, or explain why none fits. runners: [{ id, name, online,
|
|
34
|
+
* policy, state }], items: every hub backlog item (for capacity), cooldown(runnerId).
|
|
35
|
+
*/
|
|
36
|
+
export function pickRunner(item, runners, items, { cooldown = () => false, ignoreCapacity = false } = {}) {
|
|
37
|
+
const reasons = [];
|
|
38
|
+
const fits = [];
|
|
39
|
+
for (const r of runners) {
|
|
40
|
+
if (!r.online) continue;
|
|
41
|
+
if (!r.policy?.allow?.includes('create')) {
|
|
42
|
+
reasons.push(`${r.name} doesn't allow "create"`);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const project = (r.state?.projects ?? []).find((p) => p.ref === item.project);
|
|
46
|
+
if (!project) continue;
|
|
47
|
+
const labels = runnerLabels(r);
|
|
48
|
+
const missing = item.labels.filter((l) => !labels.has(l));
|
|
49
|
+
if (missing.length) {
|
|
50
|
+
reasons.push(`${r.name} lacks ${missing.join(', ')}`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (item.avoid?.includes(r.id)) {
|
|
54
|
+
reasons.push(`${r.name} is skipped for this item`);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (cooldown(r.id)) {
|
|
58
|
+
reasons.push(`${r.name} refused it a moment ago`);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const cap = r.state?.capacity ?? { max: 4, perProject: 2, busy: 0, busyBy: {} };
|
|
62
|
+
const mine = holding(items, r.id);
|
|
63
|
+
const total = cap.busy + mine.length;
|
|
64
|
+
const inProject = (cap.busyBy?.[item.project] ?? 0) + mine.filter((x) => x.project === item.project).length;
|
|
65
|
+
if (!ignoreCapacity && (total >= cap.max || inProject >= cap.perProject)) {
|
|
66
|
+
reasons.push(`${r.name} is full (${total >= cap.max ? `${total}/${cap.max} in total` : `${inProject}/${cap.perProject} in this project`})`);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const running = (r.state?.agents ?? []).filter((a) => a.status === 'running').length;
|
|
70
|
+
fits.push({ runner: r, project, warm: project.warm !== false, load: total + running / 100 });
|
|
71
|
+
}
|
|
72
|
+
fits.sort((a, b) => b.warm - a.warm || a.load - b.load || a.runner.name.localeCompare(b.runner.name));
|
|
73
|
+
if (fits.length) return { runner: fits[0].runner, shortcut: fits[0].project.shortcut, warm: fits[0].warm };
|
|
74
|
+
return { runner: null, why: reasons.length ? reasons.join('; ') : 'No online machine shares this project' };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class HubBacklog {
|
|
78
|
+
/** runners(): live runner views; rpc(runnerId, action, args); changed(): push the fleet. */
|
|
79
|
+
constructor({ store, runners, rpc, changed, audit = () => {}, log = () => {} }) {
|
|
80
|
+
this.store = store;
|
|
81
|
+
this.runners = runners;
|
|
82
|
+
this.rpc = rpc;
|
|
83
|
+
this.notify = changed;
|
|
84
|
+
this.audit = audit;
|
|
85
|
+
this.log = log;
|
|
86
|
+
store.data.backlog ??= { items: {}, autoRun: true };
|
|
87
|
+
this.data = store.data.backlog;
|
|
88
|
+
for (const it of Object.values(this.data.items)) delete it.starting; // a start cut short by a restart
|
|
89
|
+
this.refused = new Map(); // `${itemId}:${runnerId}` -> time
|
|
90
|
+
this.waiting = new Map(); // itemId -> why it can't start yet (memory only)
|
|
91
|
+
this.dispatching = false;
|
|
92
|
+
this.timer = setInterval(() => this.dispatch().catch(() => {}), 3000);
|
|
93
|
+
this.timer.unref();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
stop() {
|
|
97
|
+
clearInterval(this.timer);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
changed() {
|
|
101
|
+
this.store.save();
|
|
102
|
+
this.notify();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
items() {
|
|
106
|
+
return Object.values(this.data.items).sort((a, b) => a.priority - b.priority || a.order - b.order || a.createdAt.localeCompare(b.createdAt));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
get(id) {
|
|
110
|
+
const it = this.data.items[id];
|
|
111
|
+
if (!it) throw fail(404, `No backlog item "${id}"`);
|
|
112
|
+
return it;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Projects any online machine can start agents in, grouped across machines. */
|
|
116
|
+
projects() {
|
|
117
|
+
const out = new Map();
|
|
118
|
+
for (const r of this.runners()) {
|
|
119
|
+
if (!r.online || !r.policy?.allow?.includes('create')) continue;
|
|
120
|
+
for (const p of r.state?.projects ?? []) {
|
|
121
|
+
const e = out.get(p.ref) ?? { ref: p.ref, name: p.name, machines: [] };
|
|
122
|
+
e.machines.push({ runnerId: r.id, name: r.name, shortcut: p.shortcut, warm: p.warm !== false });
|
|
123
|
+
out.set(p.ref, e);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return [...out.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The project an item names: a ref, or a name or shortcut on any online machine. */
|
|
130
|
+
resolveProject(ref) {
|
|
131
|
+
const r = String(ref ?? '').trim().replace(/^@/, '').toLowerCase();
|
|
132
|
+
if (!r) throw fail(400, 'Pick a project');
|
|
133
|
+
const all = this.projects();
|
|
134
|
+
const hit =
|
|
135
|
+
all.find((p) => p.ref === r) ??
|
|
136
|
+
all.find((p) => p.name.toLowerCase() === r) ??
|
|
137
|
+
all.find((p) => p.machines.some((m) => m.shortcut === r));
|
|
138
|
+
if (!hit) throw fail(400, `No online machine that allows "create" shares a project called "${ref}"`);
|
|
139
|
+
return hit;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
view() {
|
|
143
|
+
const runners = new Map(this.runners().map((r) => [r.id, r]));
|
|
144
|
+
const items = this.items().map((it) => {
|
|
145
|
+
const r = it.runnerId ? runners.get(it.runnerId) : null;
|
|
146
|
+
const a = r?.state?.agents?.find((x) => x.id === it.agentId);
|
|
147
|
+
return {
|
|
148
|
+
...it,
|
|
149
|
+
runnerName: r?.name ?? it.runnerName ?? null,
|
|
150
|
+
// Its machine went away mid-item. Not re-run elsewhere on its own: the work in that
|
|
151
|
+
// machine's worktree would be lost or duplicated. You choose: wait, or requeue.
|
|
152
|
+
stalled: (it.status === 'active' || it.status === 'blocked') && !r?.online,
|
|
153
|
+
waiting: it.status === 'queued' ? this.waiting.get(it.id) ?? null : null,
|
|
154
|
+
agent: a ? { id: a.id, name: a.name, status: a.status, working: a.working, attention: a.attention, briefStatus: a.briefStatus } : null,
|
|
155
|
+
};
|
|
156
|
+
});
|
|
157
|
+
return { autoRun: this.data.autoRun, projects: this.projects(), items };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ------------------------------------------------------------ editing
|
|
161
|
+
|
|
162
|
+
add(titles, { project, labels = [], priority = 2, permissionMode, model, engine } = {}) {
|
|
163
|
+
const list = (Array.isArray(titles) ? titles : [titles]).map((t) => String(t ?? '').trim().slice(0, 10_000)).filter(Boolean).slice(0, 50);
|
|
164
|
+
if (!list.length) throw fail(400, 'At least one item is required');
|
|
165
|
+
const p = this.resolveProject(project);
|
|
166
|
+
if (permissionMode && !MODES.has(permissionMode)) throw fail(400, `Permission mode must be one of ${[...MODES].join(', ')}`);
|
|
167
|
+
const want = (Array.isArray(labels) ? labels : String(labels).split(',')).map(label).filter(Boolean).slice(0, 10);
|
|
168
|
+
const eng = engine ? label(engine) : null;
|
|
169
|
+
// An engine is a label like any other: only machines that have it installed qualify.
|
|
170
|
+
if (eng) want.push(`engine:${eng}`);
|
|
171
|
+
const order = Math.max(0, ...Object.values(this.data.items).map((i) => i.order ?? 0)) + 1;
|
|
172
|
+
const added = list.map((title, i) => {
|
|
173
|
+
const it = {
|
|
174
|
+
id: crypto.randomBytes(3).toString('hex'),
|
|
175
|
+
title,
|
|
176
|
+
project: p.ref,
|
|
177
|
+
projectName: p.name,
|
|
178
|
+
labels: [...new Set(want)],
|
|
179
|
+
priority: priorityOf(priority),
|
|
180
|
+
permissionMode: permissionMode || null,
|
|
181
|
+
model: model ? String(model).slice(0, 60) : null,
|
|
182
|
+
engine: eng,
|
|
183
|
+
status: 'queued',
|
|
184
|
+
order: order + i,
|
|
185
|
+
runnerId: null,
|
|
186
|
+
runnerName: null,
|
|
187
|
+
agentId: null,
|
|
188
|
+
avoid: [],
|
|
189
|
+
error: null,
|
|
190
|
+
createdAt: now(),
|
|
191
|
+
startedAt: null,
|
|
192
|
+
activeSince: null,
|
|
193
|
+
reviewAt: null,
|
|
194
|
+
doneAt: null,
|
|
195
|
+
};
|
|
196
|
+
this.data.items[it.id] = it;
|
|
197
|
+
return it;
|
|
198
|
+
});
|
|
199
|
+
this.changed();
|
|
200
|
+
this.dispatch().catch(() => {});
|
|
201
|
+
return added;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
remove(id) {
|
|
205
|
+
const it = this.get(id);
|
|
206
|
+
if (it.status === 'active' && !this.view().items.find((x) => x.id === id)?.stalled) throw fail(409, 'Cancel the item first (its agent is working on it)');
|
|
207
|
+
delete this.data.items[id];
|
|
208
|
+
this.changed();
|
|
209
|
+
return { id };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
settings({ autoRun } = {}) {
|
|
213
|
+
if (typeof autoRun === 'boolean') this.data.autoRun = autoRun;
|
|
214
|
+
this.changed();
|
|
215
|
+
this.dispatch().catch(() => {});
|
|
216
|
+
return { autoRun: this.data.autoRun };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ------------------------------------------------------------ lifecycle
|
|
220
|
+
|
|
221
|
+
/** Start now: skips the queue and the capacity limits, not the machine's own rules. */
|
|
222
|
+
async start(id) {
|
|
223
|
+
const it = this.get(id);
|
|
224
|
+
if (it.status !== 'queued') throw fail(409, `Item is ${it.status}`);
|
|
225
|
+
const pick = pickRunner(it, this.runners(), this.items(), { ignoreCapacity: true });
|
|
226
|
+
if (!pick.runner) throw fail(409, pick.why);
|
|
227
|
+
await this.launch(it, pick);
|
|
228
|
+
return it;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async launch(it, { runner, shortcut, warm }) {
|
|
232
|
+
it.starting = true;
|
|
233
|
+
try {
|
|
234
|
+
const out = await this.rpc(runner.id, 'create', {
|
|
235
|
+
project: shortcut,
|
|
236
|
+
intent: it.title,
|
|
237
|
+
priority: it.priority,
|
|
238
|
+
permissionMode: it.permissionMode ?? undefined,
|
|
239
|
+
model: it.model ?? undefined,
|
|
240
|
+
engine: it.engine ?? undefined,
|
|
241
|
+
});
|
|
242
|
+
const agent = out?.agents?.[0];
|
|
243
|
+
if (!agent?.id) throw fail(502, `${runner.name} did not report the new agent`);
|
|
244
|
+
Object.assign(it, { status: 'active', runnerId: runner.id, runnerName: runner.name, agentId: agent.id, error: null, startedAt: now(), activeSince: now(), briefSeen: null });
|
|
245
|
+
this.waiting.delete(it.id);
|
|
246
|
+
this.audit(`backlog started ${it.id} on ${runner.name}/${agent.id}${warm ? '' : ' (cold: needs a clone)'}`);
|
|
247
|
+
this.log(`backlog item ${it.id} started on ${runner.name} as ${agent.id}`);
|
|
248
|
+
} catch (e) {
|
|
249
|
+
if (e.status === 504) {
|
|
250
|
+
// It may have started anyway; don't risk a second copy.
|
|
251
|
+
Object.assign(it, { status: 'blocked', runnerId: runner.id, runnerName: runner.name, error: `${runner.name} did not answer in time; check it before requeueing` });
|
|
252
|
+
} else {
|
|
253
|
+
this.refused.set(`${it.id}:${runner.id}`, Date.now());
|
|
254
|
+
it.error = `${runner.name}: ${e.message}`;
|
|
255
|
+
}
|
|
256
|
+
this.audit(`backlog could not start ${it.id} on ${runner.name}: ${e.message}`);
|
|
257
|
+
throw e;
|
|
258
|
+
} finally {
|
|
259
|
+
delete it.starting;
|
|
260
|
+
this.changed();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
accept(id) {
|
|
265
|
+
const it = this.get(id);
|
|
266
|
+
if (!['review', 'active', 'blocked'].includes(it.status)) throw fail(409, `Item is ${it.status}`);
|
|
267
|
+
Object.assign(it, { status: 'done', doneAt: now() });
|
|
268
|
+
this.changed();
|
|
269
|
+
return it;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
cancel(id) {
|
|
273
|
+
const it = this.get(id);
|
|
274
|
+
if (!OPEN.has(it.status)) throw fail(409, `Item is ${it.status}`);
|
|
275
|
+
it.status = 'cancelled';
|
|
276
|
+
this.changed();
|
|
277
|
+
return it;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Back to the queue, for a stalled or blocked item. Its old machine is skipped next time. */
|
|
281
|
+
requeue(id) {
|
|
282
|
+
const it = this.get(id);
|
|
283
|
+
if (!['active', 'blocked', 'review', 'cancelled'].includes(it.status)) throw fail(409, `Item is ${it.status}`);
|
|
284
|
+
if (it.runnerId && !it.avoid.includes(it.runnerId)) it.avoid.push(it.runnerId);
|
|
285
|
+
Object.assign(it, { status: 'queued', runnerId: null, agentId: null, briefSeen: null, error: null, startedAt: null, activeSince: null, reviewAt: null, doneAt: null });
|
|
286
|
+
this.changed();
|
|
287
|
+
this.dispatch().catch(() => {});
|
|
288
|
+
return it;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Send it back to the same agent with a note (needs "control" on its machine). */
|
|
292
|
+
async reopen(id, { note } = {}) {
|
|
293
|
+
const it = this.get(id);
|
|
294
|
+
if (!['review', 'done', 'blocked'].includes(it.status)) throw fail(409, `Item is ${it.status}`);
|
|
295
|
+
if (!it.agentId || !it.runnerId) return this.requeue(id);
|
|
296
|
+
const message = `Reopened from review${note ? `: ${String(note).slice(0, 4000)}` : '.'} Please continue until the task is complete, and set the brief's Status back to done when it is.`;
|
|
297
|
+
// "tell" resumes a closed agent and types the note in once it is idle.
|
|
298
|
+
await this.rpc(it.runnerId, 'tell', { agent: it.agentId, text: message });
|
|
299
|
+
const a = this.runners().find((r) => r.id === it.runnerId)?.state?.agents?.find((x) => x.id === it.agentId);
|
|
300
|
+
Object.assign(it, { status: 'active', reviewAt: null, doneAt: null, activeSince: now(), briefSeen: a?.briefAt ?? null });
|
|
301
|
+
this.changed();
|
|
302
|
+
return it;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ------------------------------------------------------------ automation
|
|
306
|
+
|
|
307
|
+
/** A machine sent new state: move its items along, like the local backlog does. */
|
|
308
|
+
onState(runnerId) {
|
|
309
|
+
const r = this.runners().find((x) => x.id === runnerId);
|
|
310
|
+
if (!r?.online) return;
|
|
311
|
+
let dirty = false;
|
|
312
|
+
for (const it of Object.values(this.data.items)) {
|
|
313
|
+
if (it.runnerId !== runnerId || !it.agentId || !['active', 'blocked'].includes(it.status)) continue;
|
|
314
|
+
const a = r.state?.agents?.find((x) => x.id === it.agentId);
|
|
315
|
+
let next = it.status;
|
|
316
|
+
if (!a) {
|
|
317
|
+
if (Date.now() - Date.parse(it.startedAt ?? it.activeSince ?? 0) > MISSING_GRACE_MS) {
|
|
318
|
+
next = 'cancelled';
|
|
319
|
+
it.error = `The agent is gone from ${r.name} (removed, or no longer shared)`;
|
|
320
|
+
}
|
|
321
|
+
} else if (it.status === 'active') {
|
|
322
|
+
if (a.status === 'error') next = 'blocked';
|
|
323
|
+
// A brief marked done since the item (re)started. Compared with the brief time seen
|
|
324
|
+
// then, not the hub's clock, so clock skew between machines doesn't matter.
|
|
325
|
+
else if (a.briefStatus === 'done' && a.briefAt && a.briefAt !== (it.briefSeen ?? null)) next = 'review';
|
|
326
|
+
else if (a.status === 'exited') next = 'review';
|
|
327
|
+
} else if (a.status === 'running') {
|
|
328
|
+
next = 'active';
|
|
329
|
+
it.activeSince = now();
|
|
330
|
+
it.briefSeen = a.briefAt ?? null;
|
|
331
|
+
it.error = null;
|
|
332
|
+
}
|
|
333
|
+
if (next !== it.status) {
|
|
334
|
+
it.status = next;
|
|
335
|
+
if (next === 'review') it.reviewAt = now();
|
|
336
|
+
dirty = true;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (dirty) this.changed();
|
|
340
|
+
this.dispatch().catch(() => {});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Start queued items on machines with room. */
|
|
344
|
+
async dispatch() {
|
|
345
|
+
if (!this.data.autoRun || this.dispatching) return [];
|
|
346
|
+
this.dispatching = true;
|
|
347
|
+
const started = [];
|
|
348
|
+
try {
|
|
349
|
+
const runners = this.runners();
|
|
350
|
+
let explained = false;
|
|
351
|
+
for (const it of this.items()) {
|
|
352
|
+
if (it.status !== 'queued' || it.starting) continue;
|
|
353
|
+
const cooldown = (rid) => Date.now() - (this.refused.get(`${it.id}:${rid}`) ?? 0) < REFUSED_COOLDOWN_MS;
|
|
354
|
+
const pick = pickRunner(it, runners, this.items(), { cooldown });
|
|
355
|
+
if (!pick.runner) {
|
|
356
|
+
if (this.waiting.get(it.id) !== pick.why) {
|
|
357
|
+
this.waiting.set(it.id, pick.why);
|
|
358
|
+
explained = true;
|
|
359
|
+
}
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
try {
|
|
363
|
+
await this.launch(it, pick);
|
|
364
|
+
started.push(it.id);
|
|
365
|
+
} catch {}
|
|
366
|
+
}
|
|
367
|
+
if (explained) this.notify();
|
|
368
|
+
return started;
|
|
369
|
+
} finally {
|
|
370
|
+
this.dispatching = false;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|