ai-agentmanager 1.57.3 → 1.58.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 +12 -0
- package/README.md +33 -4
- package/docs/architecture.md +3 -1
- package/package.json +1 -1
- package/public/app.js +76 -6
- package/public/files.js +105 -0
- package/public/index.html +44 -3
- package/public/keys.js +1 -0
- package/public/palette.js +122 -0
- package/public/screen.js +231 -13
- package/public/setup.js +1 -1
- package/public/style.css +37 -0
- package/src/awake.js +75 -0
- package/src/cli.js +33 -2
- package/src/files.js +80 -0
- package/src/notify.js +77 -7
- package/src/screen.js +60 -3
- package/src/server.js +62 -11
package/src/cli.js
CHANGED
|
@@ -1783,6 +1783,21 @@ export async function main(argv) {
|
|
|
1783
1783
|
for (const w of v.viewers) console.log(` viewed from ${w.who} since ${new Date(w.since).toLocaleTimeString()}`);
|
|
1784
1784
|
});
|
|
1785
1785
|
|
|
1786
|
+
program
|
|
1787
|
+
.command('awake')
|
|
1788
|
+
.description('Keep this computer from going to sleep by itself, so agents keep working and the phone can reach it: always, or only while an agent works')
|
|
1789
|
+
.argument('[mode]', 'off, working (while an agent works, and five minutes after) or always')
|
|
1790
|
+
.option('--json', 'print JSON')
|
|
1791
|
+
.action(async (mode, opts) => {
|
|
1792
|
+
await daemon();
|
|
1793
|
+
const v = mode ? await api('PUT', '/awake', { mode }) : await api('GET', '/awake');
|
|
1794
|
+
if (opts.json) return console.log(JSON.stringify(v, null, 2));
|
|
1795
|
+
console.log(`Keep awake: ${v.mode === 'off' ? dim('off') : green(v.mode === 'always' ? 'always' : 'while an agent works')}${v.holding ? ' (held awake now)' : ''}`);
|
|
1796
|
+
if (!v.supported) console.log(yellow('This computer has nothing here to keep it awake with (macOS: caffeinate; Linux: systemd-inhibit).'));
|
|
1797
|
+
else if (v.mode === 'off') console.log(dim('agentmgr awake always, or: agentmgr awake working'));
|
|
1798
|
+
else console.log(dim('The display may still sleep and lock, and closing the lid still puts a laptop to sleep.'));
|
|
1799
|
+
});
|
|
1800
|
+
|
|
1786
1801
|
program
|
|
1787
1802
|
.command('rounds')
|
|
1788
1803
|
.description("Review rounds before a pull request: critics on other models read an agent's changes when it says it is done, the agent fixes what they find, and the pull request is opened when they approve")
|
|
@@ -2411,9 +2426,10 @@ export async function main(argv) {
|
|
|
2411
2426
|
printBacklog(await api('POST', '/backlog/settings', { autoRun: true }));
|
|
2412
2427
|
});
|
|
2413
2428
|
|
|
2414
|
-
const notifyCmd = program.command('notify').description('
|
|
2429
|
+
const notifyCmd = program.command('notify').description('Alerts when an agent needs you: in Slack, and on the phone');
|
|
2415
2430
|
const printNotify = (n) => {
|
|
2416
|
-
|
|
2431
|
+
const to = [n.slackConfigured ? (n.slack.channel ? `Slack bot → ${n.slack.channel}` : `Slack webhook ${n.slack.webhookUrl}`) : null, n.phone?.topic ? `phone → ${n.phone.server}/${n.phone.topic}` : null].filter(Boolean);
|
|
2432
|
+
console.log(`alerts ${n.enabled && n.configured ? green('on') : dim('off')} ${to.length ? to.join(', ') : dim('neither Slack nor the phone is set up')}`);
|
|
2417
2433
|
console.log(` events: ${Object.entries(n.events).map(([k, v]) => `${k} ${v ? green('on') : dim('off')}`).join(', ')}`);
|
|
2418
2434
|
console.log(dim(` needs input after ${n.needsInputDelaySec}s, waiting after ${n.waitingDelaySec}s, skip while you watch: ${n.skipWhenWatching}`));
|
|
2419
2435
|
for (const r of n.recent ?? []) console.log(dim(` ${r.at} ${r.kind} ${r.agent} ${r.error ? red(r.error) : 'sent'}`));
|
|
@@ -2430,6 +2446,21 @@ export async function main(argv) {
|
|
|
2430
2446
|
printNotify(await api('POST', '/notify', { webhookUrl: opts.webhook, botToken: opts.token, channel: opts.channel }));
|
|
2431
2447
|
console.log(dim('Send a test: agentmgr notify test'));
|
|
2432
2448
|
});
|
|
2449
|
+
notifyCmd
|
|
2450
|
+
.command('phone')
|
|
2451
|
+
.description('Send alerts to the phone as notifications, through the ntfy app (ntfy.sh, or a server of your own)')
|
|
2452
|
+
.option('--topic <topic>', 'the ntfy topic to publish to (default: a new one nobody can guess)')
|
|
2453
|
+
.option('--server <url>', 'your own ntfy server instead of https://ntfy.sh')
|
|
2454
|
+
.option('--token <token>', 'access token, for a server or topic that needs one')
|
|
2455
|
+
.option('--off', 'stop sending alerts to the phone')
|
|
2456
|
+
.action(async (opts) => {
|
|
2457
|
+
await daemon();
|
|
2458
|
+
if (opts.off) return printNotify(await api('POST', '/notify', { phone: { topic: null, token: null } }));
|
|
2459
|
+
const n = await api('POST', '/notify', { phone: { create: true, topic: opts.topic, server: opts.server, token: opts.token } });
|
|
2460
|
+
printNotify(n);
|
|
2461
|
+
console.log(`\nOn the phone:\n 1. Install the ${bold('ntfy')} app (App Store or Google Play).\n 2. In it: + → Subscribe to topic → ${bold(n.phone.topic)}${n.phone.server === 'https://ntfy.sh' ? '' : ` (Use another server: ${n.phone.server})`}\n 3. Here: agentmgr notify test`);
|
|
2462
|
+
console.log(dim(`\nA tap on a notification opens the agent${n.phone.server === 'https://ntfy.sh' ? '. Alerts pass through ntfy.sh, a public service: whoever knows the topic can read them, so keep it to yourself (--server for your own).' : '.'}`));
|
|
2463
|
+
});
|
|
2433
2464
|
notifyCmd.command('test').description('Send a test message').action(async () => {
|
|
2434
2465
|
await daemon();
|
|
2435
2466
|
await api('POST', '/notify/test');
|
package/src/files.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Files: this computer's folders from a signed-in device, to send it a file (a photo from the
|
|
2
|
+
// phone, a document) and to fetch one from it (a log, a build, a screenshot). It reaches what a
|
|
3
|
+
// terminal on this computer reaches (Open Terminal), and is allowed where that is.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const MAX_LISTED = 2000;
|
|
9
|
+
|
|
10
|
+
const fail = (status, message) => Object.assign(new Error(message), { status });
|
|
11
|
+
|
|
12
|
+
export class Files {
|
|
13
|
+
/** `home` is where it starts; what is sent goes to `inbox` (the Downloads folder). */
|
|
14
|
+
constructor({ home = os.homedir(), inbox = null } = {}) {
|
|
15
|
+
this.home = home;
|
|
16
|
+
this.inbox = inbox ?? path.join(home, 'Downloads');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A path as typed or sent: `~` is the home folder, nothing is the home folder, anything else must be absolute. */
|
|
20
|
+
resolve(p) {
|
|
21
|
+
const text = String(p ?? '').trim();
|
|
22
|
+
if (!text || text === '~') return this.home;
|
|
23
|
+
if (text.startsWith('~/')) return path.join(this.home, text.slice(2));
|
|
24
|
+
if (!path.isAbsolute(text)) throw fail(400, 'Give the whole path, or one that starts with ~/');
|
|
25
|
+
return path.resolve(text);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A folder's files and folders, folders first. Hidden ones (a leading dot) only when asked for. */
|
|
29
|
+
async list(dir, { hidden = false } = {}) {
|
|
30
|
+
const at = this.resolve(dir);
|
|
31
|
+
let names;
|
|
32
|
+
try {
|
|
33
|
+
names = await fs.promises.readdir(at, { withFileTypes: true });
|
|
34
|
+
} catch (err) {
|
|
35
|
+
throw fail(err.code === 'ENOENT' ? 404 : err.code === 'ENOTDIR' ? 400 : 403, err.code === 'ENOENT' ? `No folder ${at}` : err.code === 'ENOTDIR' ? `${at} is a file` : `${at} cannot be read (${err.code})`);
|
|
36
|
+
}
|
|
37
|
+
const shown = names.filter((d) => hidden || !d.name.startsWith('.'));
|
|
38
|
+
const entries = (
|
|
39
|
+
await Promise.all(
|
|
40
|
+
shown.slice(0, MAX_LISTED).map(async (d) => {
|
|
41
|
+
// Through a link too: what it points at is what gets opened.
|
|
42
|
+
const st = await fs.promises.stat(path.join(at, d.name)).catch(() => null);
|
|
43
|
+
if (!st || (!st.isDirectory() && !st.isFile())) return null;
|
|
44
|
+
return { name: d.name, dir: st.isDirectory(), size: st.isDirectory() ? null : st.size, at: st.mtime.toISOString() };
|
|
45
|
+
}),
|
|
46
|
+
)
|
|
47
|
+
).filter(Boolean);
|
|
48
|
+
entries.sort((a, b) => b.dir - a.dir || a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }));
|
|
49
|
+
const parent = path.dirname(at);
|
|
50
|
+
return { dir: at, parent: parent === at ? null : parent, home: this.home, inbox: this.inbox, entries, more: Math.max(0, shown.length - MAX_LISTED) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A file to send to the device: its path, name and size. */
|
|
54
|
+
async file(p) {
|
|
55
|
+
const at = this.resolve(p);
|
|
56
|
+
const st = await fs.promises.stat(at).catch(() => null);
|
|
57
|
+
if (!st) throw fail(404, `No file ${at}`);
|
|
58
|
+
if (!st.isFile()) throw fail(400, `${at} is not a file`);
|
|
59
|
+
return { path: at, name: path.basename(at), size: st.size };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Keep what a device sent: in `dir` (the inbox when none), under its own name, numbered if that is taken. */
|
|
63
|
+
async save(name, data, dir = null) {
|
|
64
|
+
const base = String(name ?? '').split(/[\\/]/).pop().replace(/[:\0]/g, '_').replace(/^\.+/, '') || 'file';
|
|
65
|
+
const into = dir ? this.resolve(dir) : this.inbox;
|
|
66
|
+
await fs.promises.mkdir(into, { recursive: true }).catch(() => {});
|
|
67
|
+
const { name: stem, ext } = path.parse(base);
|
|
68
|
+
for (let n = 1; n < 1000; n++) {
|
|
69
|
+
const file = path.join(into, n === 1 ? base : `${stem} (${n})${ext}`);
|
|
70
|
+
try {
|
|
71
|
+
// wx: never over a file that is there.
|
|
72
|
+
await fs.promises.writeFile(file, data, { flag: 'wx' });
|
|
73
|
+
return { path: file, name: path.basename(file), dir: into, size: data.length };
|
|
74
|
+
} catch (err) {
|
|
75
|
+
if (err.code !== 'EEXIST') throw fail(err.code === 'ENOENT' ? 404 : 403, `${into} cannot be written to (${err.code})`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
throw fail(409, `Too many files named ${base} in ${into}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
package/src/notify.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// Alerts when an agent needs you: an unanswered prompt, a backlog item ready for
|
|
2
|
+
// review, an error, or (optionally) an agent sitting idle. To Slack, and to the
|
|
3
|
+
// phone as a notification through ntfy (ntfy.sh, or a server of your own).
|
|
3
4
|
import fs from 'node:fs';
|
|
4
5
|
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
5
7
|
import { paths } from './config.js';
|
|
6
8
|
import { alertPrompt, hash } from './judge.js';
|
|
7
9
|
|
|
@@ -35,21 +37,30 @@ export function loadNotify() {
|
|
|
35
37
|
} catch {}
|
|
36
38
|
return {
|
|
37
39
|
slack: { webhookUrl: s.slack?.webhookUrl ?? null, botToken: s.slack?.botToken ?? null, channel: s.slack?.channel ?? null },
|
|
40
|
+
phone: { server: s.phone?.server ?? NTFY, topic: s.phone?.topic ?? null, token: s.phone?.token ?? null },
|
|
38
41
|
events: { ...EVENT_DEFAULTS, ...s.events },
|
|
39
42
|
needsInputDelaySec: s.needsInputDelaySec ?? 60,
|
|
40
43
|
waitingDelaySec: s.waitingDelaySec ?? 120,
|
|
41
44
|
skipWhenWatching: s.skipWhenWatching ?? true,
|
|
42
45
|
includeIntent: s.includeIntent ?? true,
|
|
43
|
-
enabled: s.enabled ?? Boolean(s.slack?.webhookUrl || (s.slack?.botToken && s.slack?.channel)),
|
|
46
|
+
enabled: s.enabled ?? Boolean(s.slack?.webhookUrl || (s.slack?.botToken && s.slack?.channel) || s.phone?.topic),
|
|
44
47
|
};
|
|
45
48
|
}
|
|
46
49
|
|
|
50
|
+
const NTFY = 'https://ntfy.sh';
|
|
51
|
+
const hasSlack = (n) => Boolean(n.slack.webhookUrl || (n.slack.botToken && n.slack.channel));
|
|
52
|
+
const hasPhone = (n) => Boolean(n.phone.topic);
|
|
53
|
+
|
|
54
|
+
/** A topic nobody can guess: on a public ntfy server, whoever knows the name can read the alerts. */
|
|
55
|
+
export const newTopic = () => `agentmgr-${crypto.randomBytes(12).toString('base64url')}`;
|
|
56
|
+
|
|
47
57
|
export function saveNotify(patch) {
|
|
48
58
|
const cur = loadNotify();
|
|
49
59
|
const next = {
|
|
50
60
|
...cur,
|
|
51
61
|
...patch,
|
|
52
62
|
slack: { ...cur.slack, ...patch.slack },
|
|
63
|
+
phone: { ...cur.phone, ...patch.phone },
|
|
53
64
|
events: { ...cur.events, ...patch.events },
|
|
54
65
|
};
|
|
55
66
|
fs.mkdirSync(paths.home, { recursive: true });
|
|
@@ -66,7 +77,10 @@ export function publicNotify() {
|
|
|
66
77
|
return {
|
|
67
78
|
...n,
|
|
68
79
|
slack: { webhookUrl: mask(n.slack.webhookUrl), botToken: mask(n.slack.botToken), channel: n.slack.channel },
|
|
69
|
-
|
|
80
|
+
// The topic is shown: it is what you subscribe to on the phone, and these settings are local only.
|
|
81
|
+
phone: { ...n.phone, token: mask(n.phone.token) },
|
|
82
|
+
configured: hasSlack(n) || hasPhone(n),
|
|
83
|
+
slackConfigured: hasSlack(n),
|
|
70
84
|
};
|
|
71
85
|
}
|
|
72
86
|
|
|
@@ -105,6 +119,55 @@ export async function sendSlack(text, n = loadNotify(), plain = text) {
|
|
|
105
119
|
}
|
|
106
120
|
}
|
|
107
121
|
|
|
122
|
+
// Slack's names for the icons that lead a message, where ntfy calls them something else.
|
|
123
|
+
const TAGS = { robot_face: 'robot' };
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A plain message as a phone notification: the icon as a tag, the first line as the title, and
|
|
127
|
+
* the link (a last "Open: https://…" line) as what a tap opens.
|
|
128
|
+
*/
|
|
129
|
+
export function phoneMessage(plain, { title = null, message = null, link = null, priority = 3 } = {}) {
|
|
130
|
+
const tags = [];
|
|
131
|
+
let lines = String(plain ?? '')
|
|
132
|
+
.replace(/^\s*:([\w+-]+):\s*/, (_m, code) => (tags.push(TAGS[code] ?? code), ''))
|
|
133
|
+
.split('\n')
|
|
134
|
+
.map((l) => l.replace(/^>\s*/, '').trimEnd());
|
|
135
|
+
lines = lines.filter((l) => {
|
|
136
|
+
const m = /^[^:\n]{0,24}:\s*(https?:\/\/\S+)$/.exec(l);
|
|
137
|
+
if (m) link ??= m[1];
|
|
138
|
+
return !m && l.trim();
|
|
139
|
+
});
|
|
140
|
+
const clip = (t, n) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);
|
|
141
|
+
const head = title ?? (lines.length > 1 ? lines.shift() : 'AI Agent Manager');
|
|
142
|
+
const text = message ?? lines.join('\n');
|
|
143
|
+
return { title: clip(head, 120), message: clip(text || head, 1500), tags, priority, ...(link ? { click: link } : {}) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** One notification to the phone, through ntfy: the ntfy app on it is subscribed to the topic. */
|
|
147
|
+
export async function sendPhone(msg, n = loadNotify()) {
|
|
148
|
+
const { server, topic, token } = n.phone;
|
|
149
|
+
if (!topic) throw new Error('Phone alerts are not set up (agentmgr notify phone)');
|
|
150
|
+
const res = await fetch(`${server.replace(/\/+$/, '')}/`, {
|
|
151
|
+
method: 'POST',
|
|
152
|
+
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
|
|
153
|
+
body: JSON.stringify({ topic, ...msg }),
|
|
154
|
+
});
|
|
155
|
+
if (!res.ok) throw new Error(`ntfy: HTTP ${res.status} ${(await res.text().catch(() => '')).slice(0, 160)}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Send one alert everywhere it is set up to go: Slack, the phone, or both. `phone` may give the
|
|
160
|
+
* notification's own title, message, link and priority; otherwise they are read from `plain`.
|
|
161
|
+
*/
|
|
162
|
+
export async function sendAlert(text, n = loadNotify(), plain = text, phone = {}) {
|
|
163
|
+
const sends = [];
|
|
164
|
+
if (hasSlack(n)) sends.push(sendSlack(text, n, plain));
|
|
165
|
+
if (hasPhone(n)) sends.push(sendPhone(phoneMessage(plain, phone), n));
|
|
166
|
+
if (!sends.length) throw new Error('Alerts have nowhere to go: set up Slack (a webhook URL, or a bot token and channel) or the phone');
|
|
167
|
+
const failed = (await Promise.allSettled(sends)).filter((r) => r.status === 'rejected');
|
|
168
|
+
if (failed.length) throw new Error(failed.map((r) => r.reason.message).join('; '));
|
|
169
|
+
}
|
|
170
|
+
|
|
108
171
|
/**
|
|
109
172
|
* Watches agents and the backlog and sends each alert once per episode (an
|
|
110
173
|
* episode ends when the condition clears, e.g. the prompt is answered).
|
|
@@ -264,7 +327,7 @@ export class Notifier {
|
|
|
264
327
|
const text = `:memo: *Agent digest* (${items.length})\n${items.map((x) => `• *${line(x).replace(/^([^:]+):/, '$1*:')}`).join('\n')}`;
|
|
265
328
|
const plain = `:memo: Agent digest (${items.length})\n${items.map((x) => `- ${line(x)}`).join('\n')}`;
|
|
266
329
|
const who = { name: `${items.length} alerts` };
|
|
267
|
-
return
|
|
330
|
+
return sendAlert(text, n, plain, { title: `Agent digest (${items.length})`, message: items.map((x) => `• ${line(x)}`).join('\n') })
|
|
268
331
|
.then(() => this.record('digest', who, null))
|
|
269
332
|
.catch((err) => this.record('digest', who, err.message));
|
|
270
333
|
}
|
|
@@ -278,7 +341,14 @@ export class Notifier {
|
|
|
278
341
|
const prio = agent.priority <= 1 ? `[P${agent.priority}] ` : '';
|
|
279
342
|
const text = `${icon} ${prio ? `*${prio.trim()}* ` : ''}*${agent.name}*${project} ${what}${intent}${link ? `\n<${link}|Open in AI Agent Manager>` : ''}`;
|
|
280
343
|
const plain = `${icon} ${prio}${agent.name}${project} ${what.replace(/\*/g, '')}${intent}${link ? `\nOpen: ${link}` : ''}`;
|
|
281
|
-
|
|
344
|
+
// On the phone: the agent as the title, and a tap opens it. What waits for an answer is urgent.
|
|
345
|
+
const phone = {
|
|
346
|
+
title: `${prio}${agent.name}${project}`,
|
|
347
|
+
message: `${what.replace(/\*/g, '')}${intent.replace('\n> ', '\n')}`,
|
|
348
|
+
link,
|
|
349
|
+
priority: ['needsInput', 'question', 'error', 'blocked'].includes(kind) ? 4 : 3,
|
|
350
|
+
};
|
|
351
|
+
sendAlert(text, n, plain, phone)
|
|
282
352
|
.then(() => this.record(kind, agent, null, urgency))
|
|
283
353
|
.catch((err) => this.record(kind, agent, err.message, urgency));
|
|
284
354
|
}
|
|
@@ -286,6 +356,6 @@ export class Notifier {
|
|
|
286
356
|
record(kind, agent, error, urgency = null) {
|
|
287
357
|
this.log.unshift({ at: new Date().toISOString(), kind, agent: agent.name, error, ...(urgency ? { urgency } : {}) });
|
|
288
358
|
this.log.length = Math.min(this.log.length, 20);
|
|
289
|
-
if (error) console.error(`[agentmgr]
|
|
359
|
+
if (error) console.error(`[agentmgr] Alert failed: ${error}`);
|
|
290
360
|
}
|
|
291
361
|
}
|
package/src/screen.js
CHANGED
|
@@ -10,13 +10,15 @@ import net from 'node:net';
|
|
|
10
10
|
import fs from 'node:fs';
|
|
11
11
|
import os from 'node:os';
|
|
12
12
|
import crypto from 'node:crypto';
|
|
13
|
-
import { execFile } from 'node:child_process';
|
|
13
|
+
import { execFile, spawn } from 'node:child_process';
|
|
14
14
|
|
|
15
15
|
export const SCREEN_DEFAULTS = { enabled: false, port: 5900 };
|
|
16
16
|
const HOST = '127.0.0.1'; // never another computer: this is not a way into the network
|
|
17
17
|
const MAX_VIEWERS = 4;
|
|
18
18
|
const QUIET_MS = 60_000; // a stream whose page went away without closing it
|
|
19
19
|
|
|
20
|
+
const CLIP_MAX = 200_000; // characters of text to and from the clipboard
|
|
21
|
+
|
|
20
22
|
const fail = (status, message) => Object.assign(new Error(message), { status });
|
|
21
23
|
|
|
22
24
|
export function screenSettings(config) {
|
|
@@ -55,10 +57,47 @@ export async function macAccess() {
|
|
|
55
57
|
return { user, allowed: everyone || listed, fix: `sudo ${KICKSTART} -configure -users ${user} -access -on -privs -ControlObserve` };
|
|
56
58
|
}
|
|
57
59
|
|
|
60
|
+
/** Run a program with `input` on its standard input; what it prints. */
|
|
61
|
+
const pipe = (cmd, args, input = null) =>
|
|
62
|
+
new Promise((resolve, reject) => {
|
|
63
|
+
// UTF-8 whatever the daemon was started with: pbcopy and pbpaste go by the locale.
|
|
64
|
+
const child = spawn(cmd, args, { env: { ...process.env, LC_CTYPE: 'UTF-8' }, stdio: [input === null ? 'ignore' : 'pipe', 'pipe', 'ignore'] });
|
|
65
|
+
const chunks = [];
|
|
66
|
+
const timer = setTimeout(() => child.kill(), 4000);
|
|
67
|
+
child.stdout.on('data', (d) => chunks.push(d));
|
|
68
|
+
child.on('error', (err) => reject(fail(501, err.code === 'ENOENT' ? `${cmd} is not on this computer` : err.message)));
|
|
69
|
+
child.on('close', (code) => {
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
if (code === 0) resolve(Buffer.concat(chunks).toString('utf8'));
|
|
72
|
+
else reject(fail(500, `${cmd} failed`));
|
|
73
|
+
});
|
|
74
|
+
if (input !== null) {
|
|
75
|
+
child.stdin.on('error', () => {});
|
|
76
|
+
child.stdin.end(input);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* This computer's clipboard, as text: `read()` and `write(text)`. Asked of the computer itself and
|
|
82
|
+
* not of its screen sharing, which on a Mac shares the clipboard only with Apple's own viewer.
|
|
83
|
+
*/
|
|
84
|
+
export function systemClipboard(platform = process.platform) {
|
|
85
|
+
// A file in its place, for the tests: they must not take over the clipboard of whoever runs them.
|
|
86
|
+
const file = process.env.AGENTMGR_CLIPBOARD_FILE;
|
|
87
|
+
if (file) return { read: async () => fs.promises.readFile(file, 'utf8').catch(() => ''), write: (text) => fs.promises.writeFile(file, text) };
|
|
88
|
+
if (platform === 'darwin') return { read: () => pipe('/usr/bin/pbpaste', []), write: (text) => pipe('/usr/bin/pbcopy', [], text) };
|
|
89
|
+
const wayland = Boolean(process.env.WAYLAND_DISPLAY);
|
|
90
|
+
return {
|
|
91
|
+
read: () => (wayland ? pipe('wl-paste', ['--no-newline']) : pipe('xclip', ['-selection', 'clipboard', '-o'])),
|
|
92
|
+
write: (text) => (wayland ? pipe('wl-copy', [], text) : pipe('xclip', ['-selection', 'clipboard', '-i'], text)),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
58
96
|
export class Screen {
|
|
59
|
-
/** `onChange(viewers)` is called when someone connects or leaves. `mac`
|
|
60
|
-
constructor({ config, onChange = () => {}, log = () => {}, mac = macAccess }) {
|
|
97
|
+
/** `onChange(viewers)` is called when someone connects or leaves. `mac` and `clip` stand in for macAccess and the clipboard in tests. */
|
|
98
|
+
constructor({ config, onChange = () => {}, log = () => {}, mac = macAccess, clip = systemClipboard() }) {
|
|
61
99
|
this.mac = mac;
|
|
100
|
+
this.clip = clip;
|
|
62
101
|
this.config = config;
|
|
63
102
|
this.onChange = onChange;
|
|
64
103
|
this.log = log;
|
|
@@ -93,6 +132,24 @@ export class Screen {
|
|
|
93
132
|
return next;
|
|
94
133
|
}
|
|
95
134
|
|
|
135
|
+
/**
|
|
136
|
+
* The computer's clipboard goes with its screen: whoever may use the one may read and set the
|
|
137
|
+
* other, and nobody may while screen access is off.
|
|
138
|
+
*/
|
|
139
|
+
async clipboard() {
|
|
140
|
+
if (!this.settings.enabled) throw fail(403, 'Screen access is off. Turn it on on the computer itself: the Screen button.');
|
|
141
|
+
const text = await this.clip.read();
|
|
142
|
+
return { text: text.slice(0, CLIP_MAX), cut: text.length > CLIP_MAX };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async setClipboard(text) {
|
|
146
|
+
if (!this.settings.enabled) throw fail(403, 'Screen access is off. Turn it on on the computer itself: the Screen button.');
|
|
147
|
+
if (typeof text !== 'string') throw fail(400, 'text is required');
|
|
148
|
+
if (text.length > CLIP_MAX) throw fail(413, `That is more than the ${CLIP_MAX / 1000}k characters the clipboard takes from here`);
|
|
149
|
+
await this.clip.write(text);
|
|
150
|
+
return { ok: true, length: text.length };
|
|
151
|
+
}
|
|
152
|
+
|
|
96
153
|
/**
|
|
97
154
|
* A connection to the screen sharing service for one page. `sink.data(buffer)` gets what it
|
|
98
155
|
* sends, `sink.end(reason)` is called once when it is over. Returns the link's id.
|
package/src/server.js
CHANGED
|
@@ -19,6 +19,8 @@ import { Cleanup } from './cleanup.js';
|
|
|
19
19
|
import { Landing } from './landing.js';
|
|
20
20
|
import { PreReview } from './prereview.js';
|
|
21
21
|
import { Screen } from './screen.js';
|
|
22
|
+
import { Awake } from './awake.js';
|
|
23
|
+
import { Files } from './files.js';
|
|
22
24
|
import { Autopilot } from './autopilot.js';
|
|
23
25
|
import { Goals, goalMarkdown } from './goals.js';
|
|
24
26
|
import { Budgets } from './budgets.js';
|
|
@@ -37,7 +39,7 @@ import { installed, listEngines, localEngineId, registerAcpEngines, registerEngi
|
|
|
37
39
|
import { LOCAL_ENGINES } from './engines/local.js';
|
|
38
40
|
import { Plugins, pluginSpecs } from './plugins.js';
|
|
39
41
|
import { HubLink, linkUrls } from './hublink.js';
|
|
40
|
-
import { Notifier, isWorkflowUrl, loadNotify, publicNotify, saveNotify,
|
|
42
|
+
import { Notifier, isWorkflowUrl, loadNotify, newTopic, publicNotify, saveNotify, sendAlert } from './notify.js';
|
|
41
43
|
import { Previews, parseUrl } from './preview.js';
|
|
42
44
|
import { LiveBrowser } from './livebrowser.js';
|
|
43
45
|
import * as remote from './remote.js';
|
|
@@ -262,6 +264,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
262
264
|
return `${kind ? (/^[AEIOU]/i.test(kind) ? `an ${kind}` : `a ${kind}`) : 'a signed-in device'}${req.device?.ip ? ` (${String(req.device.ip).replace(/^::ffff:/, '')})` : ''}`;
|
|
263
265
|
};
|
|
264
266
|
const screen = new Screen({ config, onChange: (viewers) => pushScreen(viewers), log: (m) => console.log(`[agentmgr] ${m}`) });
|
|
267
|
+
// Awake (awake.js): the computer kept from sleeping, always or while an agent works.
|
|
268
|
+
const awake = new Awake({ config, working: () => manager.list().some((a) => a.runtime?.busy), log: (m) => console.log(`[agentmgr] ${m}`) });
|
|
265
269
|
const standup = new Standup({
|
|
266
270
|
manager,
|
|
267
271
|
store,
|
|
@@ -274,7 +278,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
274
278
|
const link = `${phone ? phone.url : `http://127.0.0.1:${port}/`}#standup`;
|
|
275
279
|
const need = latest.items.filter((i) => i.needs).length;
|
|
276
280
|
const what = `${latest.items.length} agent${latest.items.length === 1 ? '' : 's'} with news${need ? `, ${need} need you` : ''}`;
|
|
277
|
-
|
|
281
|
+
sendAlert(`:sunrise: *Standup ready*: ${what}\n<${link}|Play it>`, n, `Standup ready: ${what}\nPlay it: ${link}`).catch(() => {});
|
|
278
282
|
},
|
|
279
283
|
});
|
|
280
284
|
// Value: what delivered work is worth, by day, week, month and quarter, with scheduled reports (value.js).
|
|
@@ -287,11 +291,11 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
287
291
|
onChange: () => pushValue(),
|
|
288
292
|
notify: async (period, s) => {
|
|
289
293
|
const n = loadNotify();
|
|
290
|
-
if (!n.enabled || !n.events.value) throw new Error('
|
|
294
|
+
if (!n.enabled || !n.events.value) throw new Error('Alerts are off');
|
|
291
295
|
const phone = remoteServer ? remote.remoteUrls(remotePort).find((u) => !u.vpn) : null;
|
|
292
296
|
const link = `${phone ? phone.url : `http://127.0.0.1:${port}/`}#value`;
|
|
293
297
|
const msg = valueSlack(period, s, link);
|
|
294
|
-
await
|
|
298
|
+
await sendAlert(msg.text, n, msg.plain);
|
|
295
299
|
},
|
|
296
300
|
publishDrive: async (title, markdown) => {
|
|
297
301
|
const st = store.data.value;
|
|
@@ -335,7 +339,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
335
339
|
notify: async (text, plain) => {
|
|
336
340
|
const n = loadNotify();
|
|
337
341
|
if (!n.enabled || !n.events.milestone) return;
|
|
338
|
-
await
|
|
342
|
+
await sendAlert(text, n, plain);
|
|
339
343
|
},
|
|
340
344
|
});
|
|
341
345
|
const decisions = new Decisions({
|
|
@@ -363,7 +367,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
363
367
|
notify: async (text, plain) => {
|
|
364
368
|
const n = loadNotify();
|
|
365
369
|
if (!n.enabled || !n.events.decided) return;
|
|
366
|
-
await
|
|
370
|
+
await sendAlert(text, n, plain);
|
|
367
371
|
},
|
|
368
372
|
});
|
|
369
373
|
// Usage: each engine's plan limits, used and left (usage.js).
|
|
@@ -378,7 +382,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
378
382
|
notify: async (text, plain) => {
|
|
379
383
|
const n = loadNotify();
|
|
380
384
|
if (!n.enabled || !n.events.usage) return;
|
|
381
|
-
await
|
|
385
|
+
await sendAlert(text, n, plain);
|
|
382
386
|
},
|
|
383
387
|
});
|
|
384
388
|
manager.on('usage', ({ engine, limits, at }) => engine === 'codex' && usage.record('codex', codexWindows(limits, Date.parse(at) || Date.now()), { at: at ?? undefined, source: 'Codex session log' }));
|
|
@@ -624,6 +628,29 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
624
628
|
// Opening VS Code or Cursor happens on this computer, so only from it.
|
|
625
629
|
api.get('/editors', wrap(() => studio.editors()));
|
|
626
630
|
api.post('/agents/:id/open-in', wrap((req) => studio.openIn(req.params.id, req.body?.editor, req.body?.path ?? null)));
|
|
631
|
+
// Files (files.js): this computer's folders, to send it a file and fetch one. As far as its
|
|
632
|
+
// terminal reaches, and allowed where that is.
|
|
633
|
+
const files = new Files();
|
|
634
|
+
const filesAllowed = () => manager.plugins.check('terminal.open', { agent: null, kind: 'machine' });
|
|
635
|
+
api.get('/machine/files', wrap((req) => (filesAllowed(), files.list(req.query.dir, { hidden: req.query.hidden === '1' }))));
|
|
636
|
+
api.post(
|
|
637
|
+
'/machine/files',
|
|
638
|
+
express.raw({ type: () => true, limit: '250mb' }),
|
|
639
|
+
wrap((req) => {
|
|
640
|
+
filesAllowed();
|
|
641
|
+
if (!Buffer.isBuffer(req.body) || !req.body.length) throw fail(400, 'Empty file');
|
|
642
|
+
return files.save(req.query.name, req.body, req.query.dir || null);
|
|
643
|
+
}),
|
|
644
|
+
);
|
|
645
|
+
api.get('/machine/file', async (req, res) => {
|
|
646
|
+
try {
|
|
647
|
+
filesAllowed();
|
|
648
|
+
const f = await files.file(req.query.path);
|
|
649
|
+
res.download(f.path, f.name, { dotfiles: 'allow' });
|
|
650
|
+
} catch (err) {
|
|
651
|
+
res.status(err.status || 500).json({ error: err.message });
|
|
652
|
+
}
|
|
653
|
+
});
|
|
627
654
|
// The machine terminal: shells in the home folder, not tied to an agent (Open Terminal).
|
|
628
655
|
api.get('/machine/shells', wrap(() => ({ shells: manager.shellNumbers(MACHINE), home: os.homedir() })));
|
|
629
656
|
api.post('/machine/shell/new', wrap(() => ({ n: manager.nextShellNumber(MACHINE) })));
|
|
@@ -754,7 +781,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
754
781
|
api.delete('/agents/:id/links', wrap((req) => manager.removeLink(req.params.id, req.query)));
|
|
755
782
|
api.post('/flush', wrap(() => manager.flush()));
|
|
756
783
|
|
|
757
|
-
// ---------------------------------------------------------- Slack
|
|
784
|
+
// ---------------------------------------------------------- alerts: Slack, and the phone through ntfy (local only)
|
|
758
785
|
const okUrl = (u) => /^https:\/\/[\w.-]+\//.test(u) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(u);
|
|
759
786
|
api.get('/notify', wrap(() => ({ ...publicNotify(), workflow: isWorkflowUrl(loadNotify().slack.webhookUrl), recent: notifier.log, judge: judgeAlerts() })));
|
|
760
787
|
const judgeAlerts = () => (manager.judge.enabled ? { digestMin: manager.judge.settings.digestMin, pending: notifier.digest.length } : null);
|
|
@@ -770,19 +797,35 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
770
797
|
if (b.botToken !== undefined) slack.botToken = b.botToken || null;
|
|
771
798
|
if (b.channel !== undefined) slack.channel = b.channel || null;
|
|
772
799
|
const patch = { slack };
|
|
800
|
+
// The phone, through ntfy: `create` makes a topic nobody can guess; an empty topic turns it off.
|
|
801
|
+
const p = b.phone && typeof b.phone === 'object' ? b.phone : null;
|
|
802
|
+
if (p) {
|
|
803
|
+
patch.phone = {};
|
|
804
|
+
if (p.server !== undefined) {
|
|
805
|
+
const server = String(p.server || 'https://ntfy.sh').replace(/\/+$/, '');
|
|
806
|
+
if (!/^https:\/\/[\w.-]+(:\d+)?(\/|$)/.test(server) && !okUrl(`${server}/`)) throw fail(400, 'The ntfy server must be https://…');
|
|
807
|
+
patch.phone.server = server;
|
|
808
|
+
}
|
|
809
|
+
if (p.topic !== undefined) {
|
|
810
|
+
if (p.topic && !/^[\w-]{1,64}$/.test(p.topic)) throw fail(400, 'A topic is up to 64 letters, digits, - and _');
|
|
811
|
+
patch.phone.topic = p.topic || null;
|
|
812
|
+
}
|
|
813
|
+
if (p.token !== undefined) patch.phone.token = p.token || null;
|
|
814
|
+
if (p.create && !patch.phone.topic) patch.phone.topic = loadNotify().phone.topic ?? newTopic();
|
|
815
|
+
}
|
|
773
816
|
for (const k of ['enabled', 'skipWhenWatching', 'includeIntent']) if (typeof b[k] === 'boolean') patch[k] = b[k];
|
|
774
817
|
for (const k of ['needsInputDelaySec', 'waitingDelaySec']) if (Number(b[k]) >= 0) patch[k] = Number(b[k]);
|
|
775
818
|
if (b.events && typeof b.events === 'object') patch.events = b.events;
|
|
776
819
|
const next = saveNotify(patch);
|
|
777
|
-
// Configuring Slack for the first time turns alerts on.
|
|
778
|
-
if (b.enabled === undefined && (slack.webhookUrl || (slack.botToken && (b.channel ?? next.slack.channel)))) saveNotify({ enabled: true });
|
|
820
|
+
// Configuring Slack or the phone for the first time turns alerts on.
|
|
821
|
+
if (b.enabled === undefined && (slack.webhookUrl || (slack.botToken && (b.channel ?? next.slack.channel)) || patch.phone?.topic)) saveNotify({ enabled: true });
|
|
779
822
|
return { ...publicNotify(), recent: notifier.log };
|
|
780
823
|
}),
|
|
781
824
|
);
|
|
782
825
|
api.post(
|
|
783
826
|
'/notify/test',
|
|
784
827
|
wrap(async () => {
|
|
785
|
-
await
|
|
828
|
+
await sendAlert(':wave: Test from AI Agent Manager: alerts will arrive here when an agent needs you.', loadNotify());
|
|
786
829
|
return { ok: true };
|
|
787
830
|
}),
|
|
788
831
|
);
|
|
@@ -1681,6 +1724,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
1681
1724
|
screen.close(id, 'The page closed it');
|
|
1682
1725
|
});
|
|
1683
1726
|
});
|
|
1727
|
+
api.get('/screen/clipboard', wrap(() => screen.clipboard()));
|
|
1728
|
+
api.put('/screen/clipboard', wrap((req) => screen.setClipboard(req.body?.text)));
|
|
1729
|
+
api.get('/awake', wrap(() => awake.status()));
|
|
1730
|
+
api.put('/awake', wrap((req) => {
|
|
1731
|
+
saveConfig({ awake: awake.change(req.body ?? {}) });
|
|
1732
|
+
return awake.status();
|
|
1733
|
+
}));
|
|
1684
1734
|
api.post('/screen/input', wrap((req) => {
|
|
1685
1735
|
if (typeof req.body?.id !== 'string' || typeof req.body?.d !== 'string') throw fail(400, 'id and d (base64) are required');
|
|
1686
1736
|
screen.write(req.body.id, Buffer.from(req.body.d, 'base64'));
|
|
@@ -1895,6 +1945,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
|
|
|
1895
1945
|
mcp.close();
|
|
1896
1946
|
assistant.close();
|
|
1897
1947
|
screen.closeAll('AI Agent Manager is shutting down');
|
|
1948
|
+
awake.stop();
|
|
1898
1949
|
console.log(`[agentmgr] shutting down (${reason}); closing agents so their sessions are saved`);
|
|
1899
1950
|
builder.stopAll();
|
|
1900
1951
|
await manager.stopAll({ final: true });
|