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
package/src/notify.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// Slack alerts when an agent needs you: an unanswered prompt, a backlog item
|
|
2
|
+
// ready for review, an error, or (optionally) an agent sitting idle.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { paths } from './config.js';
|
|
6
|
+
import { alertPrompt, hash } from './judge.js';
|
|
7
|
+
|
|
8
|
+
const FILE = path.join(paths.home, 'notify.json');
|
|
9
|
+
|
|
10
|
+
export const EVENT_DEFAULTS = {
|
|
11
|
+
needsInput: true, // trust / permission prompt or a question menu, unanswered
|
|
12
|
+
review: true, // backlog item moved to review
|
|
13
|
+
error: true, // workspace setup or launch failed
|
|
14
|
+
blocked: true, // the agent reports it is blocked (brief status / results outcome)
|
|
15
|
+
waiting: false, // finished its turn and idle (can be noisy)
|
|
16
|
+
stuck: true, // going in circles: same failure, undoing its edits, or long stretches without changes
|
|
17
|
+
conflict: true, // changing the same files as another agent in the same repo
|
|
18
|
+
question: true, // asked a question in the decision inbox
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// Alerts the AI judge may hold for the digest or drop; the rest are always sent at once.
|
|
22
|
+
const TRIAGE = new Set(['stuck', 'conflict', 'waiting', 'blocked', 'review']);
|
|
23
|
+
|
|
24
|
+
export function loadNotify() {
|
|
25
|
+
let s = {};
|
|
26
|
+
try {
|
|
27
|
+
s = JSON.parse(fs.readFileSync(FILE, 'utf8'));
|
|
28
|
+
} catch {}
|
|
29
|
+
return {
|
|
30
|
+
slack: { webhookUrl: s.slack?.webhookUrl ?? null, botToken: s.slack?.botToken ?? null, channel: s.slack?.channel ?? null },
|
|
31
|
+
events: { ...EVENT_DEFAULTS, ...s.events },
|
|
32
|
+
needsInputDelaySec: s.needsInputDelaySec ?? 60,
|
|
33
|
+
waitingDelaySec: s.waitingDelaySec ?? 120,
|
|
34
|
+
skipWhenWatching: s.skipWhenWatching ?? true,
|
|
35
|
+
includeIntent: s.includeIntent ?? true,
|
|
36
|
+
enabled: s.enabled ?? Boolean(s.slack?.webhookUrl || (s.slack?.botToken && s.slack?.channel)),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function saveNotify(patch) {
|
|
41
|
+
const cur = loadNotify();
|
|
42
|
+
const next = {
|
|
43
|
+
...cur,
|
|
44
|
+
...patch,
|
|
45
|
+
slack: { ...cur.slack, ...patch.slack },
|
|
46
|
+
events: { ...cur.events, ...patch.events },
|
|
47
|
+
};
|
|
48
|
+
fs.mkdirSync(paths.home, { recursive: true });
|
|
49
|
+
const tmp = `${FILE}.${process.pid}.tmp`;
|
|
50
|
+
fs.writeFileSync(tmp, JSON.stringify(next, null, 2), { mode: 0o600 }); // holds a webhook / token
|
|
51
|
+
fs.renameSync(tmp, FILE);
|
|
52
|
+
return next;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Settings safe to show in a UI: secrets masked. */
|
|
56
|
+
export function publicNotify() {
|
|
57
|
+
const n = loadNotify();
|
|
58
|
+
const mask = (v) => (v ? `${v.slice(0, 24)}…${v.slice(-4)}` : null);
|
|
59
|
+
return {
|
|
60
|
+
...n,
|
|
61
|
+
slack: { webhookUrl: mask(n.slack.webhookUrl), botToken: mask(n.slack.botToken), channel: n.slack.channel },
|
|
62
|
+
configured: Boolean(n.slack.webhookUrl || (n.slack.botToken && n.slack.channel)),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Workflow Builder webhook ("From a webhook" trigger) rather than an app's incoming webhook. */
|
|
67
|
+
export const isWorkflowUrl = (url) => /^https:\/\/hooks\.slack\.com\/triggers\//.test(url ?? '') || /\/triggers\//.test(url ?? '');
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Post one message: via a bot token (chat.postMessage), an incoming webhook, or a
|
|
71
|
+
* Workflow Builder webhook. `text` may use Slack link markup (<url|label>);
|
|
72
|
+
* `plain` is the same message without it, for workflows, which insert the
|
|
73
|
+
* "text" variable verbatim and only accept the variables they define.
|
|
74
|
+
*/
|
|
75
|
+
export async function sendSlack(text, n = loadNotify(), plain = text) {
|
|
76
|
+
const { webhookUrl, botToken, channel } = n.slack;
|
|
77
|
+
if (botToken && channel) {
|
|
78
|
+
const res = await fetch('https://slack.com/api/chat.postMessage', {
|
|
79
|
+
method: 'POST',
|
|
80
|
+
headers: { 'content-type': 'application/json; charset=utf-8', authorization: `Bearer ${botToken}` },
|
|
81
|
+
body: JSON.stringify({ channel, text, unfurl_links: false }),
|
|
82
|
+
});
|
|
83
|
+
const body = await res.json().catch(() => ({}));
|
|
84
|
+
if (!body.ok) throw new Error(`Slack: ${body.error || `HTTP ${res.status}`}`);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (!webhookUrl) throw new Error('Slack is not configured (set a webhook URL, or a bot token and channel)');
|
|
88
|
+
const workflow = isWorkflowUrl(webhookUrl);
|
|
89
|
+
const res = await fetch(webhookUrl, {
|
|
90
|
+
method: 'POST',
|
|
91
|
+
headers: { 'content-type': 'application/json' },
|
|
92
|
+
body: JSON.stringify(workflow ? { text: plain } : { text, unfurl_links: false }),
|
|
93
|
+
});
|
|
94
|
+
if (!res.ok) {
|
|
95
|
+
const detail = (await res.text().catch(() => '')).slice(0, 160);
|
|
96
|
+
const hint = workflow && res.status === 400 ? ' (does the workflow define exactly one variable named "text"?)' : '';
|
|
97
|
+
throw new Error(`Slack ${workflow ? 'workflow' : 'webhook'}: HTTP ${res.status} ${detail}${hint}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Watches agents and the backlog and sends each alert once per episode (an
|
|
103
|
+
* episode ends when the condition clears, e.g. the prompt is answered).
|
|
104
|
+
*/
|
|
105
|
+
export class Notifier {
|
|
106
|
+
constructor({ manager, backlog, linkFor }) {
|
|
107
|
+
this.manager = manager;
|
|
108
|
+
this.backlog = backlog;
|
|
109
|
+
this.linkFor = linkFor; // (agentId) => URL to open it
|
|
110
|
+
this.state = new Map(); // agentId -> { attentionSince, idleSince, worked, sent: Set }
|
|
111
|
+
this.reviewed = new Set(); // backlog item ids already announced
|
|
112
|
+
this.log = []; // recent sends, for the settings view
|
|
113
|
+
this.digest = []; // alerts the AI judge said can wait: { at, kind, agent, line }
|
|
114
|
+
manager.on('change', (a) => this.observe(a));
|
|
115
|
+
backlog?.on('change', (v) => this.observeBacklog(v));
|
|
116
|
+
this.timer = setInterval(() => this.tick().catch(() => {}), 5000);
|
|
117
|
+
this.timer.unref();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
st(id) {
|
|
121
|
+
if (!this.state.has(id)) this.state.set(id, { attentionSince: null, idleSince: null, worked: false, sent: new Set() });
|
|
122
|
+
return this.state.get(id);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
observe(a) {
|
|
126
|
+
const s = this.st(a.id);
|
|
127
|
+
const rt = a.runtime ?? {};
|
|
128
|
+
// A known prompt, or a question / error the AI judge read on an idle screen.
|
|
129
|
+
if (rt.attention || rt.waiting) s.attentionSince ??= Date.now();
|
|
130
|
+
else {
|
|
131
|
+
s.attentionSince = null;
|
|
132
|
+
s.sent.delete('needsInput');
|
|
133
|
+
}
|
|
134
|
+
if (rt.busy) {
|
|
135
|
+
s.worked = true;
|
|
136
|
+
s.idleSince = null;
|
|
137
|
+
s.sent.delete('waiting');
|
|
138
|
+
} else if (rt.running && !rt.attention && !rt.waiting) {
|
|
139
|
+
s.idleSince ??= Date.now();
|
|
140
|
+
} else {
|
|
141
|
+
s.idleSince = null;
|
|
142
|
+
}
|
|
143
|
+
const blocked = a.brief?.status === 'blocked' || a.brief?.results?.outcome === 'blocked';
|
|
144
|
+
if (blocked) {
|
|
145
|
+
if (!s.sent.has('blocked')) {
|
|
146
|
+
s.sent.add('blocked');
|
|
147
|
+
const why = a.brief?.results?.blockers?.[0];
|
|
148
|
+
this.send('blocked', a, `is blocked${why ? `: ${why}` : ''}`);
|
|
149
|
+
}
|
|
150
|
+
} else s.sent.delete('blocked');
|
|
151
|
+
for (const f of a.stuck ?? []) {
|
|
152
|
+
const k = `stuck:${f.key}:${f.since}`;
|
|
153
|
+
if (!s.sent.has(k)) {
|
|
154
|
+
s.sent.add(k);
|
|
155
|
+
this.send('stuck', a, `may be stuck: ${f.title}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
for (const g of a.conflicts ?? []) {
|
|
159
|
+
const k = `conflict:${g.agent.id}:${g.files.map((f) => f.file).join(',')}`;
|
|
160
|
+
// Announce each pair once, from the agent that should rebase.
|
|
161
|
+
if (g.mergeFirst !== a.id && !s.sent.has(k)) {
|
|
162
|
+
s.sent.add(k);
|
|
163
|
+
this.send('conflict', a, `changes the same files as *${g.agent.name}*: ${g.files.slice(0, 3).map((f) => f.file).join(', ')}${g.files.length > 3 ? '…' : ''}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const q of a.questions ?? []) {
|
|
167
|
+
const k = `question:${q.id}`;
|
|
168
|
+
if (!q.answer && !s.sent.has(k)) {
|
|
169
|
+
s.sent.add(k);
|
|
170
|
+
this.send('question', a, `asks: ${q.question}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// A plan waiting for review is an inbox decision too (same switch as questions).
|
|
174
|
+
if (a.planReview?.status === 'review') {
|
|
175
|
+
const k = `plan:${a.planReview.updatedAt}`;
|
|
176
|
+
if (!s.sent.has(k)) {
|
|
177
|
+
s.sent.add(k);
|
|
178
|
+
this.send('question', a, 'wrote its implementation plan; review it before it starts');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
// The AI judge reviewed finished work (backlog items already alert when they reach review).
|
|
182
|
+
if (a.aiReview?.verdict && !a.aiReview.seen && !a.backlogItem) {
|
|
183
|
+
const k = `review:${a.aiReview.at}`;
|
|
184
|
+
if (!s.sent.has(k)) {
|
|
185
|
+
s.sent.add(k);
|
|
186
|
+
const r = a.aiReview;
|
|
187
|
+
this.send('review', a, `finished; AI review: *${r.verdict.replace('_', ' ')}*${r.missing.length ? `, ${r.missing.length} item${r.missing.length > 1 ? 's' : ''} missing` : ''}`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (a.status === 'error') {
|
|
191
|
+
if (!s.sent.has('error')) {
|
|
192
|
+
s.sent.add('error');
|
|
193
|
+
this.send('error', a, `failed: ${a.error ?? 'unknown error'}`);
|
|
194
|
+
}
|
|
195
|
+
} else s.sent.delete('error');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
observeBacklog(view) {
|
|
199
|
+
for (const it of view.items) {
|
|
200
|
+
if (it.status === 'review' && !this.reviewed.has(it.id)) {
|
|
201
|
+
this.reviewed.add(it.id);
|
|
202
|
+
const agent = it.agentId && this.manager.get(it.agentId);
|
|
203
|
+
this.send('review', agent ?? { id: it.agentId, name: it.title, intent: it.title }, `finished backlog item *${it.title}*; ready for your review`);
|
|
204
|
+
} else if (it.status !== 'review') this.reviewed.delete(it.id);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async tick() {
|
|
209
|
+
this.flushDigest();
|
|
210
|
+
const n = loadNotify();
|
|
211
|
+
for (const [id, s] of this.state) {
|
|
212
|
+
const a = this.manager.get(id);
|
|
213
|
+
if (!a) {
|
|
214
|
+
this.state.delete(id);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const watching = n.skipWhenWatching && a.runtime.clients > 0;
|
|
218
|
+
if (s.attentionSince && !s.sent.has('needsInput') && Date.now() - s.attentionSince >= n.needsInputDelaySec * 1000 && !watching) {
|
|
219
|
+
s.sent.add('needsInput');
|
|
220
|
+
this.send('needsInput', a, `needs input: ${a.runtime.attention ?? a.runtime.waiting?.question ?? a.runtime.waiting?.summary}`);
|
|
221
|
+
}
|
|
222
|
+
if (s.idleSince && s.worked && !s.sent.has('waiting') && Date.now() - s.idleSince >= n.waitingDelaySec * 1000 && !watching) {
|
|
223
|
+
s.sent.add('waiting');
|
|
224
|
+
this.send('waiting', a, 'is waiting for your next instruction');
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Prompts, questions and errors always go out at once. Other alerts go through the AI judge
|
|
231
|
+
* (when on): now, in the next digest, or not at all. Without an answer they go out at once.
|
|
232
|
+
*/
|
|
233
|
+
send(kind, agent, what) {
|
|
234
|
+
const n = loadNotify();
|
|
235
|
+
if (!n.enabled || !n.events[kind]) return;
|
|
236
|
+
const judge = this.manager.judge;
|
|
237
|
+
if (!judge?.enabled || !TRIAGE.has(kind)) return this.deliver(kind, agent, what, n);
|
|
238
|
+
const recent = this.log.slice(0, 8).map((r) => ({ at: r.at, kind: r.kind, agent: r.agent, urgency: r.urgency }));
|
|
239
|
+
judge
|
|
240
|
+
.ask(`alert:${kind}:${agent.id}:${hash(what)}`, agent, alertPrompt({ kind, what, agent, recent }, judge.examples('alert')), (d) => ['now', 'digest', 'skip'].includes(d.urgency))
|
|
241
|
+
.then((d) => {
|
|
242
|
+
if (!d || d.urgency === 'now' || d.confidence < 0.5) return this.deliver(kind, agent, what, loadNotify(), d ? 'now' : null);
|
|
243
|
+
if (d.urgency === 'digest') this.digest.push({ at: new Date().toISOString(), kind, agent: agent.name, agentId: agent.id, line: d.line || what });
|
|
244
|
+
this.record(kind, agent, null, d.urgency);
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Send what the judge held back as one message, every `judge.digestMin` minutes. */
|
|
249
|
+
flushDigest(force = false) {
|
|
250
|
+
if (!this.digest.length) return null;
|
|
251
|
+
const every = (this.manager.judge?.settings.digestMin ?? 60) * 60_000;
|
|
252
|
+
if (!force && Date.now() - Date.parse(this.digest[0].at) < every) return null;
|
|
253
|
+
const n = loadNotify();
|
|
254
|
+
const items = this.digest.splice(0);
|
|
255
|
+
if (!n.enabled) return null;
|
|
256
|
+
const line = (x) => `${x.agent}: ${x.line.replace(/\s+/g, ' ').slice(0, 200)}`;
|
|
257
|
+
const text = `:memo: *Agent digest* (${items.length})\n${items.map((x) => `• *${line(x).replace(/^([^:]+):/, '$1*:')}`).join('\n')}`;
|
|
258
|
+
const plain = `:memo: Agent digest (${items.length})\n${items.map((x) => `- ${line(x)}`).join('\n')}`;
|
|
259
|
+
const who = { name: `${items.length} alerts` };
|
|
260
|
+
return sendSlack(text, n, plain)
|
|
261
|
+
.then(() => this.record('digest', who, null))
|
|
262
|
+
.catch((err) => this.record('digest', who, err.message));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
deliver(kind, agent, what, n, urgency = null) {
|
|
266
|
+
if (!n.enabled || !n.events[kind]) return;
|
|
267
|
+
const icon = { needsInput: ':raised_hand:', review: ':white_check_mark:', error: ':x:', waiting: ':hourglass_flowing_sand:', blocked: ':no_entry:', stuck: ':repeat:', conflict: ':crossed_swords:', question: ':question:' }[kind];
|
|
268
|
+
const project = agent.projectInfo?.name ? ` (${agent.projectInfo.name})` : '';
|
|
269
|
+
const link = this.linkFor(agent.id);
|
|
270
|
+
const intent = n.includeIntent && agent.intent ? `\n> ${agent.intent.replace(/\s+/g, ' ').slice(0, 200)}` : '';
|
|
271
|
+
const prio = agent.priority <= 1 ? `[P${agent.priority}] ` : '';
|
|
272
|
+
const text = `${icon} ${prio ? `*${prio.trim()}* ` : ''}*${agent.name}*${project} ${what}${intent}${link ? `\n<${link}|Open in Agent Manager>` : ''}`;
|
|
273
|
+
const plain = `${icon} ${prio}${agent.name}${project} ${what.replace(/\*/g, '')}${intent}${link ? `\nOpen: ${link}` : ''}`;
|
|
274
|
+
sendSlack(text, n, plain)
|
|
275
|
+
.then(() => this.record(kind, agent, null, urgency))
|
|
276
|
+
.catch((err) => this.record(kind, agent, err.message, urgency));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
record(kind, agent, error, urgency = null) {
|
|
280
|
+
this.log.unshift({ at: new Date().toISOString(), kind, agent: agent.name, error, ...(urgency ? { urgency } : {}) });
|
|
281
|
+
this.log.length = Math.min(this.log.length, 20);
|
|
282
|
+
if (error) console.error(`[agentmgr] Slack alert failed: ${error}`);
|
|
283
|
+
}
|
|
284
|
+
}
|
package/src/plugins.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Plugins: how a separate package extends Agent Manager without changing it. A plugin is an
|
|
2
|
+
// ES module listed in config.json "plugins" (the daemon) or AGENTMGR_HUB_PLUGINS (the hub),
|
|
3
|
+
// whose default export (or `register`) receives the API below:
|
|
4
|
+
//
|
|
5
|
+
// export default function register(api) {
|
|
6
|
+
// api.policy((action, details) => details.input?.permissionMode === 'bypassPermissions'
|
|
7
|
+
// ? { allow: false, reason: 'Not allowed here' } : undefined);
|
|
8
|
+
// api.on((event, payload) => appendAuditLog(event, payload));
|
|
9
|
+
// api.routes((router) => router.get('/status', (req, res) => res.json({ ok: true })));
|
|
10
|
+
// }
|
|
11
|
+
//
|
|
12
|
+
// Policies run before an action and may refuse it; listeners hear what happened; routes are
|
|
13
|
+
// served under /api/ext/<plugin name> behind the same sign-in and request checks as the rest
|
|
14
|
+
// of the API. A plugin that fails to load stops startup: a policy that silently isn't there
|
|
15
|
+
// is worse than no start.
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { pathToFileURL } from 'node:url';
|
|
19
|
+
|
|
20
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
21
|
+
|
|
22
|
+
export class Plugins {
|
|
23
|
+
constructor({ log = (m) => console.log(m) } = {}) {
|
|
24
|
+
this.log = log;
|
|
25
|
+
this.loaded = []; // { name, spec }
|
|
26
|
+
this.policies = []; // { name, fn }
|
|
27
|
+
this.listeners = []; // { name, fn }
|
|
28
|
+
this.routers = []; // { name, fn }
|
|
29
|
+
this.authenticators = []; // { name, fn }
|
|
30
|
+
this.engines = []; // { name, def }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Imports each plugin and lets it register. `base` resolves relative paths. */
|
|
34
|
+
async load(specs = [], { config = {}, base = process.cwd() } = {}) {
|
|
35
|
+
for (const spec of specs.filter(Boolean)) {
|
|
36
|
+
const target = /^(\.|\/|~)/.test(spec) ? pathToFileURL(path.resolve(base, spec.replace(/^~(?=\/|$)/, os.homedir()))).href : spec;
|
|
37
|
+
let mod;
|
|
38
|
+
try {
|
|
39
|
+
mod = await import(target);
|
|
40
|
+
} catch (e) {
|
|
41
|
+
throw new Error(`Plugin "${spec}" could not be loaded: ${e.message}`);
|
|
42
|
+
}
|
|
43
|
+
const register = typeof mod.default === 'function' ? mod.default : mod.register;
|
|
44
|
+
if (typeof register !== 'function') throw new Error(`Plugin "${spec}" has no default export or register() function`);
|
|
45
|
+
const name = String(mod.name ?? path.basename(spec).replace(/\.m?js$/, '')).replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 40) || 'plugin';
|
|
46
|
+
await register(this.api(name, config));
|
|
47
|
+
this.loaded.push({ name, spec });
|
|
48
|
+
this.log(`plugin ${name} loaded`);
|
|
49
|
+
}
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
api(name, config) {
|
|
54
|
+
return {
|
|
55
|
+
name,
|
|
56
|
+
config,
|
|
57
|
+
log: (m) => this.log(`[${name}] ${m}`),
|
|
58
|
+
/** fn(action, details) -> { allow: false, reason } to refuse; anything else allows. */
|
|
59
|
+
policy: (fn) => this.policies.push({ name, fn }),
|
|
60
|
+
/** fn(event, payload); errors are logged, never thrown into the caller. */
|
|
61
|
+
on: (fn) => this.listeners.push({ name, fn }),
|
|
62
|
+
/** fn(expressRouter): mounted at /api/ext/<name>. */
|
|
63
|
+
routes: (fn) => this.routers.push({ name, fn }),
|
|
64
|
+
/** Hub only. fn(req) -> { user, email?, roles? } for a request this plugin signs in, else null. */
|
|
65
|
+
authenticate: (fn) => this.authenticators.push({ name, fn }),
|
|
66
|
+
/** Daemon only. An agent engine adapter (see src/engines/). */
|
|
67
|
+
engine: (def) => this.engines.push({ name, def }),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Throws a 403 when a policy refuses `action`. Policies are synchronous so every caller can use them. */
|
|
72
|
+
check(action, details = {}) {
|
|
73
|
+
for (const { name, fn } of this.policies) {
|
|
74
|
+
let verdict;
|
|
75
|
+
try {
|
|
76
|
+
verdict = fn(action, details);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
throw err(403, `Refused by ${name}: its policy failed (${e.message})`);
|
|
79
|
+
}
|
|
80
|
+
if (verdict && verdict.allow === false) throw err(403, verdict.reason ? `${verdict.reason} (${name})` : `Refused by ${name}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Tells listeners what happened; never throws and never waits. */
|
|
85
|
+
emit(event, payload = {}) {
|
|
86
|
+
for (const { name, fn } of this.listeners) {
|
|
87
|
+
Promise.resolve()
|
|
88
|
+
.then(() => fn(event, { ...payload, at: new Date().toISOString() }))
|
|
89
|
+
.catch((e) => this.log(`[${name}] listener failed on ${event}: ${e.message}`));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Mounts each plugin's routes on `router` under /ext/<name>. */
|
|
94
|
+
mount(router, express) {
|
|
95
|
+
for (const { name, fn } of this.routers) {
|
|
96
|
+
const r = express.Router();
|
|
97
|
+
fn(r);
|
|
98
|
+
router.use(`/ext/${name}`, r);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The first plugin sign-in that accepts the request, as { plugin, ...identity }, or null. */
|
|
103
|
+
authenticate(req) {
|
|
104
|
+
for (const { name, fn } of this.authenticators) {
|
|
105
|
+
try {
|
|
106
|
+
const who = fn(req);
|
|
107
|
+
if (who) return { plugin: name, ...who };
|
|
108
|
+
} catch (e) {
|
|
109
|
+
this.log(`[${name}] authenticate failed: ${e.message}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Plugins named in config.json "plugins" plus $AGENTMGR_PLUGINS (comma separated). */
|
|
117
|
+
export function pluginSpecs(config = {}, env = process.env.AGENTMGR_PLUGINS) {
|
|
118
|
+
return [...(Array.isArray(config.plugins) ? config.plugins : []), ...String(env ?? '').split(',').map((s) => s.trim())].filter(Boolean);
|
|
119
|
+
}
|