ai-agentmanager 1.57.3 → 1.59.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/src/cli.js CHANGED
@@ -504,6 +504,50 @@ export async function main(argv) {
504
504
  process.stdout.write(`${d.markdown}\n`);
505
505
  });
506
506
 
507
+ program
508
+ .command('announce')
509
+ .description('What to tell the people who asked: a short Slack message, a short email and the details, written from the agent work for you to send. Without an agent: the settings')
510
+ .argument('[agent]')
511
+ .option('--cached', 'print the last one instead of writing a new one')
512
+ .option('--slack', 'print only the Slack message')
513
+ .option('--email', 'print only the email')
514
+ .option('--details', 'print only the details (Markdown)')
515
+ .option('--link <url>', 'where the details can be read; it goes under both messages')
516
+ .option('--post', 'post the Slack message (to the webhook for updates, or where the Slack alerts go)')
517
+ .option('--auto <on|off>', 'settings: write one when an agent finishes or opens a pull request (on)')
518
+ .option('--webhook <url>', "settings: a Slack webhook for these (the stakeholders' channel); \"none\" goes back to where the alerts go")
519
+ .action(async (ref, opts) => {
520
+ await daemon();
521
+ if (!ref) {
522
+ if (opts.auto !== undefined) {
523
+ if (!['on', 'off'].includes(opts.auto)) throw new Error('--auto is on or off');
524
+ await api('PUT', '/announce/settings', { auto: opts.auto === 'on' });
525
+ }
526
+ if (opts.webhook !== undefined) await api('PUT', '/announce/slack', { webhookUrl: opts.webhook === 'none' ? '' : opts.webhook });
527
+ const v = await api('GET', '/announce/settings');
528
+ console.log(`Updates for the people who asked, written by themselves: ${v.auto ? green('on') : dim('off')} ${dim('(when an agent finishes or opens a pull request)')}`);
529
+ console.log(`Posted to Slack: ${v.slack ? v.slack : dim('nowhere yet: agentmgr announce --webhook <url>, or set up Slack alerts')}`);
530
+ return console.log(dim('They are drafts: nothing is sent to anyone until you send it (Update on an agent, or agentmgr announce <agent> --post).'));
531
+ }
532
+ let a = await resolveAgent(ref);
533
+ if (!opts.cached || !a.docs?.update?.markdown) {
534
+ process.stderr.write(dim('Writing the update… (a separate Claude call; the agent is not interrupted)\n'));
535
+ a = await api('POST', `/agents/${a.id}/docs/update`);
536
+ }
537
+ if (opts.link !== undefined) a = await api('PUT', `/agents/${a.id}/announce`, { link: opts.link });
538
+ const d = a.docs.update;
539
+ const link = a.announce?.link ? `\n\nDetails: ${a.announce.link}` : '';
540
+ const slack = `${d.parts.slack}${link}`;
541
+ const email = `${d.parts.to ? `To: ${d.parts.to}\n` : ''}Subject: ${d.parts.subject}\n\n${d.parts.email}${link}`;
542
+ if (opts.post) {
543
+ const r = await api('POST', `/agents/${a.id}/announce/slack`, {});
544
+ return console.log(`${green('✓')} posted to ${r.postedTo}`);
545
+ }
546
+ const only = opts.slack ? slack : opts.email ? email : opts.details ? d.markdown : null;
547
+ if (only !== null) return process.stdout.write(`${only}\n`);
548
+ process.stdout.write(`${bold('Slack')}\n${slack}\n\n${bold('Email')}\n${email}\n\n${bold('Details')}\n${d.markdown}\n`);
549
+ });
550
+
507
551
  program
508
552
  .command('insights')
509
553
  .description('Why / What / How / Now for an agent, three tidy points each (one-off Claude call)')
@@ -1783,6 +1827,21 @@ export async function main(argv) {
1783
1827
  for (const w of v.viewers) console.log(` viewed from ${w.who} since ${new Date(w.since).toLocaleTimeString()}`);
1784
1828
  });
1785
1829
 
1830
+ program
1831
+ .command('awake')
1832
+ .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')
1833
+ .argument('[mode]', 'off, working (while an agent works, and five minutes after) or always')
1834
+ .option('--json', 'print JSON')
1835
+ .action(async (mode, opts) => {
1836
+ await daemon();
1837
+ const v = mode ? await api('PUT', '/awake', { mode }) : await api('GET', '/awake');
1838
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
1839
+ console.log(`Keep awake: ${v.mode === 'off' ? dim('off') : green(v.mode === 'always' ? 'always' : 'while an agent works')}${v.holding ? ' (held awake now)' : ''}`);
1840
+ if (!v.supported) console.log(yellow('This computer has nothing here to keep it awake with (macOS: caffeinate; Linux: systemd-inhibit).'));
1841
+ else if (v.mode === 'off') console.log(dim('agentmgr awake always, or: agentmgr awake working'));
1842
+ else console.log(dim('The display may still sleep and lock, and closing the lid still puts a laptop to sleep.'));
1843
+ });
1844
+
1786
1845
  program
1787
1846
  .command('rounds')
1788
1847
  .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 +2470,10 @@ export async function main(argv) {
2411
2470
  printBacklog(await api('POST', '/backlog/settings', { autoRun: true }));
2412
2471
  });
2413
2472
 
2414
- const notifyCmd = program.command('notify').description('Slack alerts when an agent needs you');
2473
+ const notifyCmd = program.command('notify').description('Alerts when an agent needs you: in Slack, and on the phone');
2415
2474
  const printNotify = (n) => {
2416
- console.log(`alerts ${n.enabled && n.configured ? green('on') : dim('off')} ${n.configured ? (n.slack.channel ? `bot → ${n.slack.channel}` : `webhook ${n.slack.webhookUrl}`) : dim('Slack not configured')}`);
2475
+ 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);
2476
+ 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
2477
  console.log(` events: ${Object.entries(n.events).map(([k, v]) => `${k} ${v ? green('on') : dim('off')}`).join(', ')}`);
2418
2478
  console.log(dim(` needs input after ${n.needsInputDelaySec}s, waiting after ${n.waitingDelaySec}s, skip while you watch: ${n.skipWhenWatching}`));
2419
2479
  for (const r of n.recent ?? []) console.log(dim(` ${r.at} ${r.kind} ${r.agent} ${r.error ? red(r.error) : 'sent'}`));
@@ -2430,6 +2490,21 @@ export async function main(argv) {
2430
2490
  printNotify(await api('POST', '/notify', { webhookUrl: opts.webhook, botToken: opts.token, channel: opts.channel }));
2431
2491
  console.log(dim('Send a test: agentmgr notify test'));
2432
2492
  });
2493
+ notifyCmd
2494
+ .command('phone')
2495
+ .description('Send alerts to the phone as notifications, through the ntfy app (ntfy.sh, or a server of your own)')
2496
+ .option('--topic <topic>', 'the ntfy topic to publish to (default: a new one nobody can guess)')
2497
+ .option('--server <url>', 'your own ntfy server instead of https://ntfy.sh')
2498
+ .option('--token <token>', 'access token, for a server or topic that needs one')
2499
+ .option('--off', 'stop sending alerts to the phone')
2500
+ .action(async (opts) => {
2501
+ await daemon();
2502
+ if (opts.off) return printNotify(await api('POST', '/notify', { phone: { topic: null, token: null } }));
2503
+ const n = await api('POST', '/notify', { phone: { create: true, topic: opts.topic, server: opts.server, token: opts.token } });
2504
+ printNotify(n);
2505
+ 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`);
2506
+ 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).' : '.'}`));
2507
+ });
2433
2508
  notifyCmd.command('test').description('Send a test message').action(async () => {
2434
2509
  await daemon();
2435
2510
  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/manager.js CHANGED
@@ -67,6 +67,7 @@ const SUMMARIES = {
67
67
  diagrams: { doc: 'diagrams', run: 'runDiagrams' },
68
68
  walkthrough: { doc: 'walkthrough', run: 'runWalkthrough' },
69
69
  scorecard: { doc: 'scorecard', run: 'runScorecard' },
70
+ update: { doc: 'update', run: 'runUpdate' },
70
71
  };
71
72
  /** Read / write where a summary of `kind` is kept on the agent record. */
72
73
  const getSummary = (agent, kind) => (SUMMARIES[kind].doc ? agent.docs?.[kind] : agent[SUMMARIES[kind].field]);
@@ -143,6 +144,7 @@ import { Rules, describeTool } from './rules.js';
143
144
  import { continuePrompt, findLimit } from './limits.js';
144
145
  import { runningClaude, scanClaudeSessions } from './sessions.js';
145
146
  import { builderAllowedTools, builderPrompt } from './builder.js';
147
+ import { parseUpdate, stageOf, updatePrompt, withLink } from './announce.js';
146
148
  import { DRIVE_DOCS, DRIVE_TOOLS, docUrl, driveHtml, drivePrompt, folderUrl, parseDrive } from './drive.js';
147
149
  import {
148
150
  bugFromRef,
@@ -2902,6 +2904,76 @@ export class AgentManager extends EventEmitter {
2902
2904
  return { folderId: r.folderId, id: r.files.doc, url: docUrl(r.files.doc) };
2903
2905
  }
2904
2906
 
2907
+ /**
2908
+ * An update for the people who asked (announce.js): a Slack message and an email to send, kept as
2909
+ * `parts`, and the details they point to, kept as the document itself so it reads, prints and
2910
+ * publishes like the others.
2911
+ */
2912
+ async runUpdate(agent, ctx) {
2913
+ const writer = this.writerFor(agent);
2914
+ const stage = stageOf(this.view(agent));
2915
+ const u = parseUpdate(await this.oneShot(agent, updatePrompt({ ...ctx, stage }), writer));
2916
+ const cur = this.store.get(agent.id);
2917
+ if (!cur) return null;
2918
+ return this.view(
2919
+ this.patch(
2920
+ agent.id,
2921
+ summaryPatch(cur, 'update', {
2922
+ markdown: `# Update: ${agent.name}\n\n${u.details || 'To be confirmed.'}`,
2923
+ parts: { slack: u.slack, to: u.to, subject: u.subject, email: u.email },
2924
+ stage,
2925
+ writer: `${writer.engine.label}${writer.model ? ` (${writer.model})` : ''}`,
2926
+ at: now(),
2927
+ briefUpdatedAt: cur.brief?.updatedAt ?? null,
2928
+ pending: false,
2929
+ error: null,
2930
+ }),
2931
+ ),
2932
+ );
2933
+ }
2934
+
2935
+ /** What goes with an update besides its text: the link to its details, who it is for, what was sent, set aside. */
2936
+ updateState(ref, b = {}) {
2937
+ const agent = this.mustGet(ref);
2938
+ const next = { ...agent.announce };
2939
+ if (b.link !== undefined) {
2940
+ const link = String(b.link ?? '').trim();
2941
+ if (link && !/^https?:\/\/\S+$/.test(link)) throw Object.assign(new Error('The link starts with https://'), { status: 400 });
2942
+ next.link = link || null;
2943
+ }
2944
+ if (b.to !== undefined) next.to = String(b.to ?? '').trim().slice(0, 500) || null;
2945
+ if (['slack', 'email'].includes(b.sent)) next.sent = { ...next.sent, [b.sent]: now() };
2946
+ if (b.dismissed !== undefined) next.dismissedAt = b.dismissed ? now() : null;
2947
+ return this.view(this.patch(agent.id, { announce: next }));
2948
+ }
2949
+
2950
+ /** The update's Slack message as it goes out: the text given (yours, edited) or the written one, with the link. */
2951
+ updateSlackText(ref, text = null) {
2952
+ const agent = this.mustGet(ref);
2953
+ const body = String(text ?? agent.docs?.update?.parts?.slack ?? '').trim();
2954
+ if (!body) throw Object.assign(new Error('There is no message to post: write the update first'), { status: 409 });
2955
+ return withLink(body.slice(0, 3000), agent.announce?.link);
2956
+ }
2957
+
2958
+ /** The update's details as one Google Doc, through the Drive connector; its link then goes under both messages. */
2959
+ publishUpdate(ref) {
2960
+ const agent = this.mustGet(ref);
2961
+ const markdown = agent.docs?.update?.markdown;
2962
+ if (!markdown) throw Object.assign(new Error('Write the update first'), { status: 409 });
2963
+ if (agent.announce?.publishing) return this.view(agent);
2964
+ this.patch(agent.id, { announce: { ...agent.announce, publishing: true, publishError: null } });
2965
+ this.publishDriveDoc({ folderTitle: `${agent.name} (AI Agent Manager)`, folderId: agent.drive?.folderId ?? null, title: `Update: ${agent.name}`, markdown })
2966
+ .then((r) => {
2967
+ const cur = this.store.get(agent.id);
2968
+ if (cur) this.patch(agent.id, { announce: { ...cur.announce, publishing: false, link: r.url, published: { id: r.id, at: now() } } });
2969
+ })
2970
+ .catch((e) => {
2971
+ const cur = this.store.get(agent.id);
2972
+ if (cur) this.patch(agent.id, { announce: { ...cur.announce, publishing: false, publishError: e.message } });
2973
+ });
2974
+ return this.view(this.store.get(agent.id));
2975
+ }
2976
+
2905
2977
  /** Diagrams only: the problem and its solution drawn from the documents already written and the live context. */
2906
2978
  async runDiagrams(agent, ctx) {
2907
2979
  const cur0 = this.store.get(agent.id) ?? agent;
package/src/notify.js CHANGED
@@ -1,7 +1,9 @@
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.
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
 
@@ -23,6 +25,7 @@ export const EVENT_DEFAULTS = {
23
25
  milestone: true, // a project's date (code complete, RC, GA) is coming up, at risk or late
24
26
  usage: true, // an engine's plan limit is nearly used up (Usage)
25
27
  decided: true, // something was decided for you (a standing decision, or within the autonomy you set)
28
+ announce: true, // an update for the people who asked is written and ready for you to send
26
29
  };
27
30
 
28
31
  // Alerts the AI judge may hold for the digest or drop; the rest are always sent at once.
@@ -35,21 +38,40 @@ export function loadNotify() {
35
38
  } catch {}
36
39
  return {
37
40
  slack: { webhookUrl: s.slack?.webhookUrl ?? null, botToken: s.slack?.botToken ?? null, channel: s.slack?.channel ?? null },
41
+ phone: { server: s.phone?.server ?? NTFY, topic: s.phone?.topic ?? null, token: s.phone?.token ?? null },
42
+ // Where updates for stakeholders are posted (their channel), when not where the alerts go.
43
+ announce: { webhookUrl: s.announce?.webhookUrl ?? null },
38
44
  events: { ...EVENT_DEFAULTS, ...s.events },
39
45
  needsInputDelaySec: s.needsInputDelaySec ?? 60,
40
46
  waitingDelaySec: s.waitingDelaySec ?? 120,
41
47
  skipWhenWatching: s.skipWhenWatching ?? true,
42
48
  includeIntent: s.includeIntent ?? true,
43
- enabled: s.enabled ?? Boolean(s.slack?.webhookUrl || (s.slack?.botToken && s.slack?.channel)),
49
+ enabled: s.enabled ?? Boolean(s.slack?.webhookUrl || (s.slack?.botToken && s.slack?.channel) || s.phone?.topic),
44
50
  };
45
51
  }
46
52
 
53
+ const NTFY = 'https://ntfy.sh';
54
+ const hasSlack = (n) => Boolean(n.slack.webhookUrl || (n.slack.botToken && n.slack.channel));
55
+ const hasPhone = (n) => Boolean(n.phone.topic);
56
+
57
+ /** Where an update for stakeholders is posted: its own webhook, else the Slack the alerts use; null when neither. */
58
+ export function announceSlack(n = loadNotify()) {
59
+ if (n.announce.webhookUrl) return { slack: { webhookUrl: n.announce.webhookUrl, botToken: null, channel: null }, where: 'the updates webhook' };
60
+ if (hasSlack(n)) return { slack: n.slack, where: n.slack.botToken && n.slack.channel ? n.slack.channel : 'the alerts webhook' };
61
+ return null;
62
+ }
63
+
64
+ /** A topic nobody can guess: on a public ntfy server, whoever knows the name can read the alerts. */
65
+ export const newTopic = () => `agentmgr-${crypto.randomBytes(12).toString('base64url')}`;
66
+
47
67
  export function saveNotify(patch) {
48
68
  const cur = loadNotify();
49
69
  const next = {
50
70
  ...cur,
51
71
  ...patch,
52
72
  slack: { ...cur.slack, ...patch.slack },
73
+ phone: { ...cur.phone, ...patch.phone },
74
+ announce: { ...cur.announce, ...patch.announce },
53
75
  events: { ...cur.events, ...patch.events },
54
76
  };
55
77
  fs.mkdirSync(paths.home, { recursive: true });
@@ -66,7 +88,11 @@ export function publicNotify() {
66
88
  return {
67
89
  ...n,
68
90
  slack: { webhookUrl: mask(n.slack.webhookUrl), botToken: mask(n.slack.botToken), channel: n.slack.channel },
69
- configured: Boolean(n.slack.webhookUrl || (n.slack.botToken && n.slack.channel)),
91
+ // The topic is shown: it is what you subscribe to on the phone, and these settings are local only.
92
+ phone: { ...n.phone, token: mask(n.phone.token) },
93
+ announce: { webhookUrl: mask(n.announce.webhookUrl) },
94
+ configured: hasSlack(n) || hasPhone(n),
95
+ slackConfigured: hasSlack(n),
70
96
  };
71
97
  }
72
98
 
@@ -105,6 +131,55 @@ export async function sendSlack(text, n = loadNotify(), plain = text) {
105
131
  }
106
132
  }
107
133
 
134
+ // Slack's names for the icons that lead a message, where ntfy calls them something else.
135
+ const TAGS = { robot_face: 'robot' };
136
+
137
+ /**
138
+ * A plain message as a phone notification: the icon as a tag, the first line as the title, and
139
+ * the link (a last "Open: https://…" line) as what a tap opens.
140
+ */
141
+ export function phoneMessage(plain, { title = null, message = null, link = null, priority = 3 } = {}) {
142
+ const tags = [];
143
+ let lines = String(plain ?? '')
144
+ .replace(/^\s*:([\w+-]+):\s*/, (_m, code) => (tags.push(TAGS[code] ?? code), ''))
145
+ .split('\n')
146
+ .map((l) => l.replace(/^>\s*/, '').trimEnd());
147
+ lines = lines.filter((l) => {
148
+ const m = /^[^:\n]{0,24}:\s*(https?:\/\/\S+)$/.exec(l);
149
+ if (m) link ??= m[1];
150
+ return !m && l.trim();
151
+ });
152
+ const clip = (t, n) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);
153
+ const head = title ?? (lines.length > 1 ? lines.shift() : 'AI Agent Manager');
154
+ const text = message ?? lines.join('\n');
155
+ return { title: clip(head, 120), message: clip(text || head, 1500), tags, priority, ...(link ? { click: link } : {}) };
156
+ }
157
+
158
+ /** One notification to the phone, through ntfy: the ntfy app on it is subscribed to the topic. */
159
+ export async function sendPhone(msg, n = loadNotify()) {
160
+ const { server, topic, token } = n.phone;
161
+ if (!topic) throw new Error('Phone alerts are not set up (agentmgr notify phone)');
162
+ const res = await fetch(`${server.replace(/\/+$/, '')}/`, {
163
+ method: 'POST',
164
+ headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
165
+ body: JSON.stringify({ topic, ...msg }),
166
+ });
167
+ if (!res.ok) throw new Error(`ntfy: HTTP ${res.status} ${(await res.text().catch(() => '')).slice(0, 160)}`);
168
+ }
169
+
170
+ /**
171
+ * Send one alert everywhere it is set up to go: Slack, the phone, or both. `phone` may give the
172
+ * notification's own title, message, link and priority; otherwise they are read from `plain`.
173
+ */
174
+ export async function sendAlert(text, n = loadNotify(), plain = text, phone = {}) {
175
+ const sends = [];
176
+ if (hasSlack(n)) sends.push(sendSlack(text, n, plain));
177
+ if (hasPhone(n)) sends.push(sendPhone(phoneMessage(plain, phone), n));
178
+ 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');
179
+ const failed = (await Promise.allSettled(sends)).filter((r) => r.status === 'rejected');
180
+ if (failed.length) throw new Error(failed.map((r) => r.reason.message).join('; '));
181
+ }
182
+
108
183
  /**
109
184
  * Watches agents and the backlog and sends each alert once per episode (an
110
185
  * episode ends when the condition clears, e.g. the prompt is answered).
@@ -264,21 +339,28 @@ export class Notifier {
264
339
  const text = `:memo: *Agent digest* (${items.length})\n${items.map((x) => `• *${line(x).replace(/^([^:]+):/, '$1*:')}`).join('\n')}`;
265
340
  const plain = `:memo: Agent digest (${items.length})\n${items.map((x) => `- ${line(x)}`).join('\n')}`;
266
341
  const who = { name: `${items.length} alerts` };
267
- return sendSlack(text, n, plain)
342
+ return sendAlert(text, n, plain, { title: `Agent digest (${items.length})`, message: items.map((x) => `• ${line(x)}`).join('\n') })
268
343
  .then(() => this.record('digest', who, null))
269
344
  .catch((err) => this.record('digest', who, err.message));
270
345
  }
271
346
 
272
347
  deliver(kind, agent, what, n, urgency = null) {
273
348
  if (!n.enabled || !n.events[kind]) return;
274
- 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:', assistant: ':robot_face:', budget: ':moneybag:' }[kind];
349
+ 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:', assistant: ':robot_face:', budget: ':moneybag:', announce: ':mega:' }[kind];
275
350
  const project = agent.projectInfo?.name ? ` (${agent.projectInfo.name})` : '';
276
351
  const link = this.linkFor(agent.id);
277
352
  const intent = n.includeIntent && agent.intent ? `\n> ${agent.intent.replace(/\s+/g, ' ').slice(0, 200)}` : '';
278
353
  const prio = agent.priority <= 1 ? `[P${agent.priority}] ` : '';
279
354
  const text = `${icon} ${prio ? `*${prio.trim()}* ` : ''}*${agent.name}*${project} ${what}${intent}${link ? `\n<${link}|Open in AI Agent Manager>` : ''}`;
280
355
  const plain = `${icon} ${prio}${agent.name}${project} ${what.replace(/\*/g, '')}${intent}${link ? `\nOpen: ${link}` : ''}`;
281
- sendSlack(text, n, plain)
356
+ // On the phone: the agent as the title, and a tap opens it. What waits for an answer is urgent.
357
+ const phone = {
358
+ title: `${prio}${agent.name}${project}`,
359
+ message: `${what.replace(/\*/g, '')}${intent.replace('\n> ', '\n')}`,
360
+ link,
361
+ priority: ['needsInput', 'question', 'error', 'blocked'].includes(kind) ? 4 : 3,
362
+ };
363
+ sendAlert(text, n, plain, phone)
282
364
  .then(() => this.record(kind, agent, null, urgency))
283
365
  .catch((err) => this.record(kind, agent, err.message, urgency));
284
366
  }
@@ -286,6 +368,6 @@ export class Notifier {
286
368
  record(kind, agent, error, urgency = null) {
287
369
  this.log.unshift({ at: new Date().toISOString(), kind, agent: agent.name, error, ...(urgency ? { urgency } : {}) });
288
370
  this.log.length = Math.min(this.log.length, 20);
289
- if (error) console.error(`[agentmgr] Slack alert failed: ${error}`);
371
+ if (error) console.error(`[agentmgr] Alert failed: ${error}`);
290
372
  }
291
373
  }
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` stands in for macAccess in tests. */
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.