ai-agentmanager 1.44.0 → 1.47.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/news.js ADDED
@@ -0,0 +1,454 @@
1
+ // AI News: what the frontier labs released lately, in one list. It reads their release notes
2
+ // (Claude Platform, Claude Code, OpenAI API, Gemini API, and any you add in config.json), keeps
3
+ // the last few weeks, and has each entry summarized in a sentence or two by one batched,
4
+ // tool-less model call per refresh (each entry once). Once a day a Claude Code call allowed only
5
+ // web search and web fetch looks for the latest releases of the top 10 AI labs, for those without
6
+ // release notes read here. Nothing is sent anywhere; it only reads public pages.
7
+
8
+ import crypto from 'node:crypto';
9
+ import { parseJsonReply } from './brief.js';
10
+
11
+ const HOUR = 3_600_000;
12
+ const DAY = 24 * HOUR;
13
+ const MAX_ITEMS = 400;
14
+ const SUMMARY_BATCH = 25;
15
+ const FETCH_TIMEOUT_MS = 30_000;
16
+ const SEARCH_TIMEOUT_MS = 10 * 60_000;
17
+ export const NEWS_DEFAULTS = { enabled: true, sources: ['claude-platform', 'claude-code', 'openai', 'gemini'], custom: [], search: true, summaries: true, refreshHours: 6, searchHours: 24, days: 30 };
18
+
19
+ const err = (status, message) => Object.assign(new Error(message), { status });
20
+ const clip = (s, n) => {
21
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim();
22
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
23
+ };
24
+ const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
25
+ const ymd = (y, m, d) => `${y}-${String(m + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
26
+
27
+ /** "November 12, 2026" (or "Nov 12, 2026") as "2026-11-12", or null. */
28
+ export function dateOf(words) {
29
+ const m = String(words ?? '').match(/\b([A-Za-z]{3,9})\.?\s+(\d{1,2}),?\s+(\d{4})\b/);
30
+ const mi = m ? MONTHS.findIndex((x) => x.startsWith(m[1].toLowerCase().slice(0, 3))) : -1;
31
+ return mi < 0 ? null : ymd(Number(m[3]), mi, Number(m[2]));
32
+ }
33
+
34
+ /** An address on the page, made absolute; null for anything but http(s). */
35
+ const absolute = (href, base) => {
36
+ try {
37
+ const u = new URL(href, base);
38
+ return /^https?:$/.test(u.protocol) ? u.href : null;
39
+ } catch {
40
+ return null;
41
+ }
42
+ };
43
+
44
+ /** Markdown to plain text, with its links kept apart: { text, links: [{ text, url }] }. */
45
+ export function plainText(md, base) {
46
+ const links = [];
47
+ const text = String(md ?? '')
48
+ .replace(/^#{1,6}\s.*$/gm, '')
49
+ .replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_, t, href) => {
50
+ const url = absolute(href, base);
51
+ if (url && !links.some((l) => l.url === url)) links.push({ text: t.replace(/[*`_]/g, ''), url });
52
+ return t;
53
+ })
54
+ .replace(/<[^>]+>/g, '')
55
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
56
+ .replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g, '$1')
57
+ .replace(/\s+/g, ' ')
58
+ .trim();
59
+ return { text, links };
60
+ }
61
+
62
+ /** A headline for an entry: its bold lead ("**Gemini 4 GA**: …") or its first sentence. */
63
+ function headline(md, text) {
64
+ const bold = String(md).match(/^\s*\*\*([^*]{3,160})\*\*/);
65
+ if (bold) return plainText(bold[1]).text.replace(/[:.]$/, '');
66
+ return clip(text.split(/(?<=[.!?])\s/)[0], 140);
67
+ }
68
+
69
+ /**
70
+ * Release notes in Markdown, one "## <date>" (or "###") heading per day and a bullet per change,
71
+ * as the Claude Platform and the Gemini API publish them: [{ date, title, text, links }].
72
+ */
73
+ export function parseDatedMarkdown(md, { base, since = null } = {}) {
74
+ const out = [];
75
+ let date = null;
76
+ let cur = null;
77
+ const flush = () => {
78
+ if (!cur) return;
79
+ const { text, links } = plainText(cur, base);
80
+ if (text.length > 3) out.push({ date, title: headline(cur, text), text: clip(text, 2400), links });
81
+ cur = null;
82
+ };
83
+ let gap = false; // a blank line since the bullet's last line
84
+ for (const line of String(md ?? '').split('\n')) {
85
+ const h = line.match(/^#{1,4}\s+(.*)$/);
86
+ if (h) {
87
+ flush();
88
+ date = dateOf(h[1]);
89
+ continue;
90
+ }
91
+ if (!date || (since && date < since)) continue;
92
+ if (!line.trim()) {
93
+ gap = true;
94
+ continue;
95
+ }
96
+ // A bullet at the margin starts an entry; an indented one is a sub-point of the entry above.
97
+ if (/^\s?[*-]\s+/.test(line)) {
98
+ flush();
99
+ cur = line.replace(/^\s*[*-]\s+/, '');
100
+ } else if (cur !== null && (!gap || /^\s/.test(line)) && !/^\s*</.test(line)) cur += ` ${line.trim().replace(/^[*-]\s+/, '')}`;
101
+ else flush();
102
+ gap = false;
103
+ }
104
+ flush();
105
+ return out;
106
+ }
107
+
108
+ const unescapeHtml = (s) => String(s).replace(/&(amp|lt|gt|quot|#39|#x27|nbsp);/g, (_, e) => ({ amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", '#x27': "'", nbsp: ' ' })[e]);
109
+ const htmlText = (h) => unescapeHtml(String(h).replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim();
110
+
111
+ /**
112
+ * OpenAI's changelog page: "<Month>, <Year>" headings, then entries with a date badge ("Nov 5"),
113
+ * a type and tags (models, endpoints), and the text. Read from the page's HTML.
114
+ */
115
+ export function parseOpenAiChangelog(html, { base, since = null } = {}) {
116
+ const out = [];
117
+ const sections = String(html ?? '').split(/<h3\b/).slice(1);
118
+ for (const sec of sections) {
119
+ const head = htmlText(sec.slice(sec.indexOf('>') + 1, sec.indexOf('</h3>')));
120
+ const year = Number(head.match(/\b(\d{4})\b/)?.[1]);
121
+ if (!year) continue;
122
+ for (const chunk of sec.split(/grid-cols-\[3rem_1fr\]/).slice(1)) {
123
+ const day = chunk.match(/data-variant="outline"[^>]*>\s*([A-Z][a-z]{2})\s+(\d{1,2})\s*</);
124
+ const mi = day ? MONTHS.findIndex((x) => x.startsWith(day[1].toLowerCase())) : -1;
125
+ if (mi < 0) continue;
126
+ const date = ymd(year, mi, Number(day[2]));
127
+ if (since && date < since) continue;
128
+ const type = chunk.match(/<span class="capitalize">([^<]+)<\/span>/)?.[1] ?? null;
129
+ const bodyAt = chunk.search(/MarkdownContent/);
130
+ if (bodyAt < 0) continue;
131
+ const body = chunk.slice(chunk.indexOf('>', bodyAt) + 1);
132
+ const tags = [...chunk.slice(0, bodyAt).matchAll(/data-variant="soft"[^>]*>([^<]+)</g)].map((m) => htmlText(m[1])).filter(Boolean);
133
+ const links = [];
134
+ for (const m of body.matchAll(/<a\s[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g)) {
135
+ const url = absolute(unescapeHtml(m[1]), base);
136
+ if (url && !links.some((l) => l.url === url)) links.push({ text: htmlText(m[2]), url });
137
+ }
138
+ const text = clip(htmlText(body), 2400);
139
+ if (text.length < 4) continue;
140
+ out.push({ date, title: tags.length ? `${type ? `${type}: ` : ''}${tags.slice(0, 3).join(', ')}` : headline('', text), text, links, tags });
141
+ }
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** GitHub releases (Claude Code's): one entry per version, with its date and notes. */
147
+ export function parseGithubReleases(json, { label, since = null } = {}) {
148
+ const list = typeof json === 'string' ? JSON.parse(json) : json;
149
+ if (!Array.isArray(list)) throw new Error(list?.message ?? 'Not a list of releases');
150
+ return list
151
+ .filter((r) => !r.draft && !r.prerelease && r.published_at)
152
+ .map((r) => {
153
+ const { text, links } = plainText(r.body ?? '', r.html_url);
154
+ return { date: r.published_at.slice(0, 10), title: `${label} ${String(r.tag_name).replace(/^v/, '')}`, text: clip(text || r.name || r.tag_name, 6000), links: links.slice(0, 6), url: r.html_url };
155
+ })
156
+ .filter((e) => !since || e.date >= since);
157
+ }
158
+
159
+ /** The release notes read here. `page` is where a person reads them. */
160
+ export const SOURCES = {
161
+ 'claude-platform': {
162
+ lab: 'Anthropic',
163
+ label: 'Claude Platform',
164
+ url: 'https://platform.claude.com/docs/en/release-notes/overview.md',
165
+ page: 'https://platform.claude.com/docs/en/release-notes/overview',
166
+ parse: (body, o) => parseDatedMarkdown(body, { ...o, base: 'https://platform.claude.com/docs/en/release-notes/overview' }),
167
+ },
168
+ 'claude-code': {
169
+ lab: 'Anthropic',
170
+ label: 'Claude Code',
171
+ url: 'https://api.github.com/repos/anthropics/claude-code/releases?per_page=15',
172
+ page: 'https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md',
173
+ parse: (body, o) => parseGithubReleases(body, { ...o, label: 'Claude Code' }),
174
+ },
175
+ openai: {
176
+ lab: 'OpenAI',
177
+ label: 'OpenAI API',
178
+ url: 'https://developers.openai.com/changelog',
179
+ page: 'https://developers.openai.com/changelog',
180
+ parse: (body, o) => parseOpenAiChangelog(body, { ...o, base: 'https://developers.openai.com/changelog' }),
181
+ },
182
+ gemini: {
183
+ lab: 'Google',
184
+ label: 'Gemini API',
185
+ url: 'https://ai.google.dev/gemini-api/docs/changelog.md.txt',
186
+ page: 'https://ai.google.dev/gemini-api/docs/changelog',
187
+ // Its Markdown links "/docs/…" for what the site serves at "/gemini-api/docs/…".
188
+ parse: (body, o) =>
189
+ parseDatedMarkdown(body, { ...o, base: 'https://ai.google.dev/gemini-api/docs/changelog' }).map((e) => ({
190
+ ...e,
191
+ links: e.links.map((l) => ({ ...l, url: l.url.replace(/^https:\/\/ai\.google\.dev\/docs\//, 'https://ai.google.dev/gemini-api/docs/') })),
192
+ })),
193
+ },
194
+ };
195
+
196
+ /** Settings from config.json's "news", with defaults; custom sources are dated Markdown. */
197
+ export function newsSettings(config = {}) {
198
+ const s = { ...NEWS_DEFAULTS, ...config.news };
199
+ const num = (v, d, min) => (Number.isFinite(Number(v)) && Number(v) >= min ? Number(v) : d);
200
+ const custom = (Array.isArray(s.custom) ? s.custom : [])
201
+ .filter((c) => c && /^[\w-]{1,40}$/.test(c.id ?? '') && /^https?:\/\//.test(c.url ?? '') && !SOURCES[c.id])
202
+ .map((c) => ({ id: c.id, lab: clip(c.lab || c.label || c.id, 40), label: clip(c.label || c.id, 60), url: c.url, page: /^https?:\/\//.test(c.page ?? '') ? c.page : c.url }));
203
+ return {
204
+ enabled: s.enabled !== false,
205
+ sources: (Array.isArray(s.sources) ? s.sources : NEWS_DEFAULTS.sources).filter((id) => SOURCES[id]),
206
+ custom,
207
+ search: s.search !== false,
208
+ summaries: s.summaries !== false,
209
+ refreshHours: num(s.refreshHours, NEWS_DEFAULTS.refreshHours, 0.25),
210
+ searchHours: num(s.searchHours, NEWS_DEFAULTS.searchHours, 1),
211
+ days: num(s.days, NEWS_DEFAULTS.days, 1),
212
+ };
213
+ }
214
+
215
+ const idOf = (source, e) => crypto.createHash('sha1').update(`${source}\n${e.date}\n${e.url ?? ''}\n${e.title}\n${e.text.slice(0, 200)}`).digest('hex').slice(0, 12);
216
+
217
+ /** The prompt that summarizes entries; the reply is { summaries: { id: text } }. */
218
+ export function summaryPrompt(entries) {
219
+ return [
220
+ 'Summarize these AI release notes for a developer who builds with AI models and coding agents, one entry at a time.',
221
+ 'For each entry write one or two plain sentences (at most 240 characters): what was released or changed, and why it matters or who it is for.',
222
+ 'Keep model names, IDs and API names exactly as written. No hype, no marketing words, no "This update…" opener. Do not invent anything not in the entry.',
223
+ 'Reply with JSON only: {"summaries": {"<id>": "<summary>", …}}, one for every id.',
224
+ '',
225
+ '<entries>',
226
+ JSON.stringify(entries.map((e) => ({ id: e.id, source: e.label, date: e.date, title: e.title, text: clip(e.text, 3000) }))),
227
+ '</entries>',
228
+ ].join('\n');
229
+ }
230
+
231
+ /** The prompt for the web search over the top AI labs; the reply is { items: [...] }. */
232
+ export function searchPrompt({ today, days = 14, known = [] }) {
233
+ return [
234
+ `Find the latest frontier AI releases from the top 10 AI labs, from the last ${days} days (today is ${today}).`,
235
+ 'The labs: Anthropic, OpenAI, Google DeepMind, Meta, xAI, Mistral AI, DeepSeek, Alibaba (Qwen), Microsoft AI and Amazon, or whichever ten lead now.',
236
+ 'Look for new models, model updates, major API or developer platform features, and agent or coding tools. Use web search, and open the announcement to check the date and details. Leave out rumors, opinion pieces and anything older.',
237
+ known.length ? `Already known (skip these): ${known.slice(0, 40).join('; ')}.` : '',
238
+ 'Reply with JSON only: {"items": [{"lab": "<lab>", "date": "YYYY-MM-DD", "title": "<the release, short>", "summary": "<one or two plain sentences: what it is and why it matters, at most 240 characters>", "url": "<the official announcement or docs>"}]}, newest first, at most 20.',
239
+ ]
240
+ .filter(Boolean)
241
+ .join('\n');
242
+ }
243
+
244
+ export class News {
245
+ /**
246
+ * `fetchText(url)` reads a page; `oneShot(prompt, { web })` makes the model call (web: the
247
+ * tools a search may use) and resolves to its text.
248
+ */
249
+ constructor({ store, config = {}, fetchText = defaultFetch, oneShot = null, onChange = () => {}, log = (m) => console.log(`[agentmgr] ${m}`), now = () => Date.now() }) {
250
+ this.store = store;
251
+ this.config = config;
252
+ this.fetchText = fetchText;
253
+ this.oneShot = oneShot;
254
+ this.onChange = onChange;
255
+ this.log = log;
256
+ this.now = now;
257
+ this.running = null;
258
+ this.timer = null;
259
+ if (this.settings.enabled) {
260
+ // A first look shortly after start, then whenever a refresh is due.
261
+ this.first = setTimeout(() => this.tick(), 20_000);
262
+ this.timer = setInterval(() => this.tick(), 15 * 60_000);
263
+ this.first.unref?.();
264
+ this.timer.unref?.();
265
+ }
266
+ }
267
+
268
+ get settings() {
269
+ return newsSettings(this.config);
270
+ }
271
+
272
+ get state() {
273
+ return (this.store.data.news ??= { items: {}, sources: {}, search: {}, seenAt: null });
274
+ }
275
+
276
+ close() {
277
+ clearTimeout(this.first);
278
+ clearInterval(this.timer);
279
+ }
280
+
281
+ /** The sources in use, built in and custom. */
282
+ sources() {
283
+ const s = this.settings;
284
+ return [
285
+ ...s.sources.map((id) => ({ id, ...SOURCES[id] })),
286
+ ...s.custom.map((c) => ({ ...c, parse: (body, o) => parseDatedMarkdown(body, { ...o, base: c.page }) })),
287
+ ];
288
+ }
289
+
290
+ tick() {
291
+ const s = this.settings;
292
+ if (!s.enabled || this.running) return;
293
+ const last = Date.parse(this.state.refreshedAt ?? '') || 0;
294
+ if (this.now() - last >= s.refreshHours * HOUR) this.refresh().catch((e) => this.log(`news: ${e.message}`));
295
+ }
296
+
297
+ /** Read every source, search when due (or `search`: now), then summarize what's new. One at a time. */
298
+ refresh({ search = null } = {}) {
299
+ if (!this.settings.enabled) return Promise.reject(err(409, 'AI News is off: "news": { "enabled": true } in config.json'));
300
+ this.running ??= this.run({ search }).finally(() => {
301
+ this.running = null;
302
+ this.onChange();
303
+ });
304
+ this.onChange();
305
+ return this.running;
306
+ }
307
+
308
+ async run({ search }) {
309
+ const s = this.settings;
310
+ const st = this.state;
311
+ const since = new Date(this.now() - s.days * DAY).toISOString().slice(0, 10);
312
+ await Promise.all(
313
+ this.sources().map(async (src) => {
314
+ const at = new Date(this.now()).toISOString();
315
+ try {
316
+ // Read whole, so a page with nothing recent isn't taken for one that can't be read.
317
+ const all = src.parse(await this.fetchText(src.url), {});
318
+ if (!all.length) throw new Error('No dated entries found on the page (its layout may have changed)');
319
+ const entries = all.filter((e) => e.date >= since);
320
+ let added = 0;
321
+ for (const e of entries) added += this.add(src, e);
322
+ st.sources[src.id] = { at, error: null, count: entries.length, added };
323
+ } catch (e) {
324
+ st.sources[src.id] = { ...st.sources[src.id], at, error: clip(e.message, 200) };
325
+ this.log(`news: ${src.label}: ${e.message}`);
326
+ }
327
+ }),
328
+ );
329
+ const searchDue = search ?? (s.search && this.now() - (Date.parse(st.search.at ?? '') || 0) >= s.searchHours * HOUR);
330
+ if (searchDue && s.search && this.oneShot) await this.search(since);
331
+ st.refreshedAt = new Date(this.now()).toISOString();
332
+ this.prune(since);
333
+ this.store.save();
334
+ this.onChange();
335
+ if (s.summaries && this.oneShot) await this.summarize();
336
+ this.store.save();
337
+ }
338
+
339
+ /** Keep one entry; 1 when it's new. */
340
+ add(src, e) {
341
+ const st = this.state;
342
+ const id = idOf(src.id, e);
343
+ if (st.items[id]) return 0;
344
+ st.items[id] = {
345
+ id,
346
+ source: src.id,
347
+ lab: src.lab,
348
+ label: src.label,
349
+ date: e.date,
350
+ title: clip(String(e.title).replace(/`/g, ''), 200),
351
+ text: e.text,
352
+ links: (e.links ?? []).slice(0, 8),
353
+ tags: e.tags ?? [],
354
+ url: e.url ?? src.page,
355
+ summary: e.summary ? clip(e.summary, 300) : null,
356
+ summaryBy: e.summary ? 'search' : null,
357
+ seenAt: new Date(this.now()).toISOString(),
358
+ };
359
+ return 1;
360
+ }
361
+
362
+ /** The top labs' latest releases, from the web: one Claude Code call with only web search and fetch. */
363
+ async search(since) {
364
+ const st = this.state;
365
+ const at = new Date(this.now()).toISOString();
366
+ const known = Object.values(st.items).filter((i) => i.date >= since).map((i) => `${i.lab}: ${i.title}`);
367
+ try {
368
+ const reply = parseJsonReply(await this.oneShot(searchPrompt({ today: at.slice(0, 10), days: 14, known }), { web: ['WebSearch', 'WebFetch'], timeoutMs: SEARCH_TIMEOUT_MS }));
369
+ const items = (Array.isArray(reply?.items) ? reply.items : []).filter((x) => x && /^\d{4}-\d{2}-\d{2}$/.test(x.date ?? '') && x.date >= since && /^https?:\/\//.test(x.url ?? '') && x.title);
370
+ // One the release notes already have (same address) isn't added twice.
371
+ const urls = new Set(Object.values(st.items).flatMap((i) => [i.url, ...i.links.map((l) => l.url)]));
372
+ let added = 0;
373
+ for (const x of items) {
374
+ if (urls.has(x.url)) continue;
375
+ added += this.add({ id: 'search', lab: clip(x.lab || 'AI lab', 40), label: 'Web search', page: x.url }, { date: x.date, title: x.title, text: clip(x.summary ?? '', 600), links: [{ text: 'Announcement', url: x.url }], url: x.url, summary: x.summary });
376
+ }
377
+ st.search = { at, error: null, count: items.length, added };
378
+ } catch (e) {
379
+ st.search = { ...st.search, at, error: clip(e.message, 200) };
380
+ this.log(`news: search: ${e.message}`);
381
+ }
382
+ }
383
+
384
+ /** Summaries for the entries that have none, newest first, a batch per call; tried twice at most. */
385
+ async summarize() {
386
+ const todo = Object.values(this.state.items)
387
+ .filter((i) => !i.summary && (i.summaryTries ?? 0) < 2)
388
+ .sort((x, y) => y.date.localeCompare(x.date));
389
+ for (let i = 0; i < todo.length; i += SUMMARY_BATCH) {
390
+ const batch = todo.slice(i, i + SUMMARY_BATCH);
391
+ try {
392
+ const got = parseJsonReply(await this.oneShot(summaryPrompt(batch), {}))?.summaries ?? {};
393
+ for (const it of batch) {
394
+ if (typeof got[it.id] === 'string' && got[it.id].trim()) Object.assign(it, { summary: clip(got[it.id], 300), summaryBy: 'ai' });
395
+ else it.summaryTries = (it.summaryTries ?? 0) + 1;
396
+ }
397
+ } catch (e) {
398
+ for (const it of batch) it.summaryTries = (it.summaryTries ?? 0) + 1;
399
+ this.log(`news: summaries: ${e.message}`);
400
+ }
401
+ this.store.save();
402
+ this.onChange();
403
+ }
404
+ }
405
+
406
+ /** Older than the window goes; past MAX_ITEMS, the oldest. */
407
+ prune(since) {
408
+ const st = this.state;
409
+ const keep = Object.values(st.items)
410
+ .filter((i) => i.date >= since)
411
+ .sort((x, y) => y.date.localeCompare(x.date) || y.seenAt.localeCompare(x.seenAt))
412
+ .slice(0, MAX_ITEMS);
413
+ st.items = Object.fromEntries(keep.map((i) => [i.id, i]));
414
+ }
415
+
416
+ /** What the page shows: entries newest first, with which are new since you last looked. */
417
+ view() {
418
+ const s = this.settings;
419
+ const st = this.state;
420
+ const seen = st.seenAt ?? '';
421
+ const items = Object.values(st.items)
422
+ .sort((x, y) => y.date.localeCompare(x.date) || x.lab.localeCompare(y.lab) || y.seenAt.localeCompare(x.seenAt))
423
+ .map((i) => ({ id: i.id, source: i.source, lab: i.lab, label: i.label, date: i.date, title: i.title, summary: i.summary, summaryBy: i.summaryBy, lead: i.summary ? null : clip(i.text, 280), links: i.links, tags: i.tags, url: i.url, isNew: Boolean(seen) && i.seenAt > seen }));
424
+ return {
425
+ enabled: s.enabled,
426
+ settings: { search: s.search, summaries: s.summaries, refreshHours: s.refreshHours, searchHours: s.searchHours, days: s.days },
427
+ sources: [
428
+ ...this.sources().map((x) => ({ id: x.id, lab: x.lab, label: x.label, page: x.page, ...pick(st.sources[x.id]) })),
429
+ ...(s.search ? [{ id: 'search', lab: 'Top 10 labs', label: 'Web search', page: null, ...pick(st.search) }] : []),
430
+ ],
431
+ items,
432
+ newCount: seen ? items.filter((i) => i.isNew).length : 0,
433
+ seenAt: st.seenAt ?? null,
434
+ refreshing: Boolean(this.running),
435
+ refreshedAt: st.refreshedAt ?? null,
436
+ };
437
+ }
438
+
439
+ /** You've looked: the "new" marks clear. */
440
+ seen() {
441
+ this.state.seenAt = new Date(this.now()).toISOString();
442
+ this.store.save();
443
+ this.onChange();
444
+ return { ok: true };
445
+ }
446
+ }
447
+
448
+ const pick = (x = {}) => ({ at: x.at ?? null, error: x.error ?? null, count: x.count ?? 0 });
449
+
450
+ async function defaultFetch(url) {
451
+ const res = await fetch(url, { headers: { 'user-agent': 'Mozilla/5.0 (AI Agent Manager news)', accept: 'text/markdown, text/html, application/json;q=0.9, */*;q=0.8' }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), redirect: 'follow' });
452
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText} from ${new URL(url).host}`);
453
+ return res.text();
454
+ }
package/src/notify.js CHANGED
@@ -20,6 +20,7 @@ export const EVENT_DEFAULTS = {
20
20
  budget: true, // an agent neared or reached its budget, or today's spend reached the daily limit
21
21
  standup: true, // the daily standup is ready to play
22
22
  value: true, // a scheduled value report (week, month, quarter)
23
+ milestone: true, // a project's date (code complete, RC, GA) is coming up, at risk or late
23
24
  };
24
25
 
25
26
  // Alerts the AI judge may hold for the digest or drop; the rest are always sent at once.
package/src/server.js CHANGED
@@ -9,7 +9,7 @@ import { spawn } from 'node:child_process';
9
9
  import express from 'express';
10
10
  import { WebSocketServer } from 'ws';
11
11
  import { ensureHome, HOST, loadConfig, paths, PORT, saveConfig } from './config.js';
12
- import { AgentManager, MACHINE, projectOf, shellNumber } from './manager.js';
12
+ import { AgentManager, MACHINE, NO_REPO, projectOf, repoCacheDir, shellNumber } from './manager.js';
13
13
  import { Backlog } from './backlog.js';
14
14
  import { Races } from './races.js';
15
15
  import { Review } from './review.js';
@@ -49,6 +49,13 @@ import { AgentkitReports } from './agentkit-reports.js';
49
49
  import { Builder } from './builder.js';
50
50
  import { Standup } from './standup.js';
51
51
  import { Value, valueSlack } from './value.js';
52
+ import { News } from './news.js';
53
+ import { Milestones } from './milestones.js';
54
+ import { Decisions } from './decisions.js';
55
+ import { Debt } from './debt.js';
56
+ import { Calendar } from './calendar.js';
57
+ import { loadQuestions } from './inbox.js';
58
+ import { readSpecDoc } from './brief.js';
52
59
  import { Store } from './store.js';
53
60
  import { about, latestRelease } from './about.js';
54
61
  import { Support } from './support.js';
@@ -247,6 +254,62 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
247
254
  return r;
248
255
  },
249
256
  });
257
+ // AI News: the frontier labs' latest releases, summarized (news.js).
258
+ let pushNews = () => {};
259
+ const news = new News({
260
+ store,
261
+ config,
262
+ onChange: () => pushNews(),
263
+ oneShot: (prompt, { web, timeoutMs } = {}) => manager.oneShot(null, prompt, { ...manager.writerFor({}), web, timeoutMs }),
264
+ });
265
+ // Plan: a project's dates with their reminders and checklists, the decision log, the tech debt
266
+ // radar, and the calendar Today is planned around (milestones.js, decisions.js, debt.js, calendar.js).
267
+ let pushPlan = () => {};
268
+ const openFindings = (p) => hunts.list().findings.filter((f) => ['open', 'fixing', 'pr'].includes(f.status) && manager.resolveProject(f.project)?.key === p.key);
269
+ const queueTask = (p, title) => backlog.add([title], { project: p.shortcut })[0];
270
+ const milestones = new Milestones({
271
+ store,
272
+ projects: () => manager.listProjects(),
273
+ onChange: () => pushPlan(),
274
+ queue: queueTask,
275
+ facts: (p) => {
276
+ const mine = store.list().filter((a) => projectOf(a).key === p.key && !NO_REPO.has(a.kind) && !a.hunting && !a.reviewing);
277
+ const views = mine.map((a) => manager.view(a));
278
+ const prs = mine.flatMap((a) => Object.values(a.prs ?? {}).filter((x) => x.state === 'OPEN' && x.source !== 'mentioned'));
279
+ return {
280
+ working: views.filter((v) => ['planning', 'working', 'blocked'].includes(v.brief?.status) || (v.runtime.running && v.brief?.status !== 'done')),
281
+ backlog: backlog.view().items.filter((it) => it.projectKey === p.key && ['queued', 'active', 'review', 'blocked'].includes(it.status)),
282
+ waiting: views.filter((v) => v.runtime.attention || v.runtime.waiting || v.planReview?.status === 'review' || (v.questions ?? []).some((q) => !q.answer)),
283
+ prs,
284
+ failing: prs.filter((x) => x.checks?.state === 'failed'),
285
+ bugs: openFindings(p).filter((f) => ['critical', 'high'].includes(f.severity)),
286
+ };
287
+ },
288
+ notify: async (text, plain) => {
289
+ const n = loadNotify();
290
+ if (!n.enabled || !n.events.milestone) return;
291
+ await sendSlack(text, n, plain);
292
+ },
293
+ });
294
+ const decisions = new Decisions({
295
+ store,
296
+ agents: () => store.list(),
297
+ projectOf,
298
+ questions: (a) => (NO_REPO.has(a.kind) ? [] : loadQuestions(a.id)),
299
+ designDoc: (id) => readSpecDoc(id, 'designdoc'),
300
+ onChange: () => pushPlan(),
301
+ });
302
+ const debt = new Debt({
303
+ store,
304
+ config,
305
+ projects: () => manager.listProjects(),
306
+ // The project's folder, or the shared clone its agents' worktrees come from.
307
+ dirOf: (p) => p.dir ?? (p.repo && git.isRemoteUrl(p.repo) ? repoCacheDir(p.repo) : p.repo ?? null),
308
+ bugs: (p) => openFindings(p).map((f) => f.file),
309
+ queue: queueTask,
310
+ onChange: () => pushPlan(),
311
+ });
312
+ const calendar = new Calendar({ config });
250
313
  const triggers = new Triggers({ manager, store, config, notifier });
251
314
  const budgets = new Budgets({ manager, store, config, notifier });
252
315
  const playbooks = new Playbooks({ manager, store });
@@ -642,6 +705,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
642
705
  api.post('/rules/dismiss', wrap((req) => (manager.rules.dismiss(...ruleArgs(req)), manager.rules.view())));
643
706
  api.post('/rules/remove', wrap((req) => (manager.rules.remove(...ruleArgs(req)), manager.rules.view())));
644
707
  api.post('/agents/:id/tell', wrap((req) => manager.tell(req.params.id, req.body?.text)));
708
+ // Debug: what to debug (or a follow-up), or `fix` to apply the report's fixes; the report is /specs/debug.
709
+ api.post('/agents/:id/debug', wrap((req) => manager.debug(req.params.id, { question: req.body?.question, fix: req.body?.fix ?? null })));
645
710
  api.post('/agents/:id/answer', wrap((req) => manager.answerQuestion(req.params.id, req.body?.question, req.body?.text)));
646
711
  api.post('/agents/:id/prompt-key', wrap((req) => manager.answerPrompt(req.params.id, String(req.body?.key ?? ''))));
647
712
  api.post('/agents/:id/stuck/dismiss', wrap((req) => manager.dismissStuck(req.params.id, req.body?.key)));
@@ -1000,6 +1065,46 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1000
1065
  api.patch('/value/items/:id', wrap((req) => value.edit(req.params.id, req.body ?? {})));
1001
1066
  api.post('/value/items/:id/estimate', wrap((req) => value.estimate(req.params.id).then((it) => value.itemView(it))));
1002
1067
  api.post('/value/items/:id/exclude', wrap((req) => value.exclude(req.params.id, req.body?.excluded !== false)));
1068
+ // Plan → Dates: a project's code complete, RC and GA dates, their checklists and reminders.
1069
+ api.get('/milestones', wrap(() => milestones.view()));
1070
+ api.put('/milestones/:project', wrap((req) => milestones.set(req.params.project, req.body ?? {})));
1071
+ api.post('/milestones/:project/check', wrap((req) => milestones.check(req.params.project, req.body?.stage, req.body?.item, req.body?.done !== false)));
1072
+ api.post('/milestones/:project/reach', wrap((req) => milestones.reach(req.params.project, req.body?.stage, req.body?.reached !== false)));
1073
+ api.post('/milestones/:project/task', wrap((req) => milestones.task(req.params.project, req.body?.stage, req.body?.item)));
1074
+ // Plan → Decisions: the log (?project=<key>&q=<words>; ?format=markdown), one of your own, and removal.
1075
+ api.get('/decisions', (req, res) => {
1076
+ try {
1077
+ const project = req.query.project ? String(req.query.project) : null;
1078
+ if (req.query.format === 'markdown') return res.type('text/markdown').send(decisions.markdown({ project }));
1079
+ res.json(decisions.view({ project, q: String(req.query.q ?? '') }));
1080
+ } catch (e) {
1081
+ res.status(e.status ?? 500).json({ error: e.message });
1082
+ }
1083
+ });
1084
+ api.post('/decisions', wrap((req) => {
1085
+ const p = manager.resolveProject(req.body?.project) ?? manager.listProjects().find((x) => x.key === req.body?.project);
1086
+ return decisions.add({ ...req.body, project: p ? { key: p.key, name: p.name } : null });
1087
+ }));
1088
+ api.delete('/decisions/:id', wrap((req) => decisions.remove(req.params.id)));
1089
+ // Plan → Debt: each project's hot spots; a scan answers at once and the page hears when it's done.
1090
+ api.get('/debt', wrap(() => debt.view()));
1091
+ api.post('/debt/:project/scan', wrap((req) => {
1092
+ debt.project(req.params.project);
1093
+ debt.scan(req.params.project).catch(() => {});
1094
+ return debt.view();
1095
+ }));
1096
+ api.post('/debt/:project/queue', wrap((req) => debt.queueSpot(req.params.project, String(req.body?.file ?? ''))));
1097
+ api.post('/debt/:project/dismiss', wrap((req) => debt.dismiss(req.params.project, String(req.body?.file ?? ''), req.body?.dismissed !== false)));
1098
+ // The calendar Today is planned around: its private iCal addresses (never sent back) and working hours.
1099
+ api.get('/calendar', wrap(() => calendar.status()));
1100
+ api.put('/calendar', wrap((req) => calendar.set(req.body ?? {}, saveConfig)));
1101
+ // AI News: the entries, a refresh now (answers at once; the page hears when it's done), and "seen".
1102
+ api.get('/news', wrap(() => news.view()));
1103
+ api.post('/news/refresh', wrap((req) => {
1104
+ news.refresh({ search: req.body?.search === true ? true : null }).catch(() => {});
1105
+ return news.view();
1106
+ }));
1107
+ api.post('/news/seen', wrap(() => news.seen()));
1003
1108
  api.get('/value/report', wrap((req) => value.report(String(req.query.kind ?? 'week'), { current: req.query.current === '1' })));
1004
1109
  api.post('/value/report', wrap((req) => value.sendReport(String(req.body?.kind ?? 'week'), { current: req.body?.current === true })));
1005
1110
  api.get('/value/value.csv', (req, res) => {
@@ -1041,8 +1146,12 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1041
1146
  got('reviews', () => reviews.rows()),
1042
1147
  ]);
1043
1148
  const findings = hunts.list().findings.filter((x) => x.status === 'open' || x.status === 'pr');
1044
- const items = todayItems({ inbox, issues, actions, reviews: prs, findings, slower: benches.slower(), unsure: evals.unsure().map((a) => ({ id: a.id, name: a.name, issue: manager.issueKey(a), confidence: a.eval.confidence, pending: a.eval.pending, at: a.eval.at })) });
1045
- return { items, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
1149
+ const items = todayItems({ inbox, issues, actions, reviews: prs, findings, slower: benches.slower(), milestones: milestones.todayItems(), unsure: evals.unsure().map((a) => ({ id: a.id, name: a.name, issue: manager.issueKey(a), confidence: a.eval.confidence, pending: a.eval.pending, at: a.eval.at })) });
1150
+ // The day around your meetings: what needs you, placed in the free time (calendar.js).
1151
+ const day = await calendar
1152
+ .day({ items, agents: store.list().filter((a) => !NO_REPO.has(a.kind)).map((a) => ({ id: a.id, name: a.name, status: a.status, issue: manager.issueKey(a), prs: Object.values(a.prs ?? {}), project: projectOf(a).name })) })
1153
+ .catch((e) => ({ connected: true, error: e.message }));
1154
+ return { items, day, aside: todayAside({ issues, actions }), speech: todaySpeech(items), features: f, errors };
1046
1155
  }));
1047
1156
  // Support tickets: kept on this computer, each with a filled-in link to a new GitHub issue.
1048
1157
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
@@ -1347,6 +1456,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1347
1456
  manager.on('change', (agent) => broadcast({ t: 'agent', agent }));
1348
1457
  pushStandup = (latest) => broadcast({ t: 'standup', latest });
1349
1458
  pushValue = () => broadcast({ t: 'value' });
1459
+ pushNews = () => broadcast({ t: 'news' });
1460
+ pushPlan = () => broadcast({ t: 'plan' });
1350
1461
  reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
1351
1462
  manager.rules.on('change', (rules) => broadcast({ t: 'rules', rules }));
1352
1463
  repeats.on('change', (view) => broadcast({ t: 'repeats', repeats: view }));
@@ -1484,6 +1595,10 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1484
1595
  landing.close();
1485
1596
  standup.close();
1486
1597
  value.close();
1598
+ news.close();
1599
+ milestones.close();
1600
+ decisions.close();
1601
+ debt.close();
1487
1602
  reviews.close();
1488
1603
  hunts.close();
1489
1604
  benches.close();
package/src/today.js CHANGED
@@ -68,7 +68,7 @@ const INBOX = {
68
68
  * The list: [{ id, kind, label, title, why, score, at, agentId?, url?, actionId?, issueKey?, reviewUrl? }],
69
69
  * most pressing first. Each source may be missing (turned off, or it couldn't be had).
70
70
  */
71
- export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], slower = [], unsure = [], now = new Date() } = {}) {
71
+ export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], slower = [], unsure = [], milestones = [], now = new Date() } = {}) {
72
72
  const items = [];
73
73
  // The issue each agent works on: named on its questions, and not listed twice.
74
74
  const issueOfAgent = new Map(issues.filter((r) => r.agent?.id).map((r) => [r.agent.id, r]));
@@ -141,6 +141,8 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
141
141
  const why = `Micro benchmarks${r.agent && r.agent !== r.issue ? ` by ${r.agent}` : ''}${worst ? `: ${worst.name} ${worst.before} → ${worst.after}${worst.unit ? ` ${worst.unit}` : ''}` : ''}${worst?.note ? ` · its note: ${worst.note}` : ''}`;
142
142
  items.push({ id: `bench:${r.id}`, kind: 'bench', label: 'Slower', title, why, score: r.worst > 20 ? 27 : 36, at: r.at ?? null, agentId: r.agentId, runId: r.id, issueKey: r.issue ?? null });
143
143
  }
144
+ // A project's dates coming up, at risk or late (milestones.js), already scored.
145
+ items.push(...milestones);
144
146
  return items.sort((x, y) => x.score - y.score || String(y.at ?? '').localeCompare(String(x.at ?? '')));
145
147
  }
146
148