ai-agentmanager 1.43.0 → 1.46.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/server.js CHANGED
@@ -49,6 +49,7 @@ 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';
52
53
  import { Store } from './store.js';
53
54
  import { about, latestRelease } from './about.js';
54
55
  import { Support } from './support.js';
@@ -247,6 +248,14 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
247
248
  return r;
248
249
  },
249
250
  });
251
+ // AI News: the frontier labs' latest releases, summarized (news.js).
252
+ let pushNews = () => {};
253
+ const news = new News({
254
+ store,
255
+ config,
256
+ onChange: () => pushNews(),
257
+ oneShot: (prompt, { web, timeoutMs } = {}) => manager.oneShot(null, prompt, { ...manager.writerFor({}), web, timeoutMs }),
258
+ });
250
259
  const triggers = new Triggers({ manager, store, config, notifier });
251
260
  const budgets = new Budgets({ manager, store, config, notifier });
252
261
  const playbooks = new Playbooks({ manager, store });
@@ -642,6 +651,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
642
651
  api.post('/rules/dismiss', wrap((req) => (manager.rules.dismiss(...ruleArgs(req)), manager.rules.view())));
643
652
  api.post('/rules/remove', wrap((req) => (manager.rules.remove(...ruleArgs(req)), manager.rules.view())));
644
653
  api.post('/agents/:id/tell', wrap((req) => manager.tell(req.params.id, req.body?.text)));
654
+ // Debug: what to debug (or a follow-up), or `fix` to apply the report's fixes; the report is /specs/debug.
655
+ api.post('/agents/:id/debug', wrap((req) => manager.debug(req.params.id, { question: req.body?.question, fix: req.body?.fix ?? null })));
645
656
  api.post('/agents/:id/answer', wrap((req) => manager.answerQuestion(req.params.id, req.body?.question, req.body?.text)));
646
657
  api.post('/agents/:id/prompt-key', wrap((req) => manager.answerPrompt(req.params.id, String(req.body?.key ?? ''))));
647
658
  api.post('/agents/:id/stuck/dismiss', wrap((req) => manager.dismissStuck(req.params.id, req.body?.key)));
@@ -1000,6 +1011,13 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1000
1011
  api.patch('/value/items/:id', wrap((req) => value.edit(req.params.id, req.body ?? {})));
1001
1012
  api.post('/value/items/:id/estimate', wrap((req) => value.estimate(req.params.id).then((it) => value.itemView(it))));
1002
1013
  api.post('/value/items/:id/exclude', wrap((req) => value.exclude(req.params.id, req.body?.excluded !== false)));
1014
+ // AI News: the entries, a refresh now (answers at once; the page hears when it's done), and "seen".
1015
+ api.get('/news', wrap(() => news.view()));
1016
+ api.post('/news/refresh', wrap((req) => {
1017
+ news.refresh({ search: req.body?.search === true ? true : null }).catch(() => {});
1018
+ return news.view();
1019
+ }));
1020
+ api.post('/news/seen', wrap(() => news.seen()));
1003
1021
  api.get('/value/report', wrap((req) => value.report(String(req.query.kind ?? 'week'), { current: req.query.current === '1' })));
1004
1022
  api.post('/value/report', wrap((req) => value.sendReport(String(req.body?.kind ?? 'week'), { current: req.body?.current === true })));
1005
1023
  api.get('/value/value.csv', (req, res) => {
@@ -1347,6 +1365,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1347
1365
  manager.on('change', (agent) => broadcast({ t: 'agent', agent }));
1348
1366
  pushStandup = (latest) => broadcast({ t: 'standup', latest });
1349
1367
  pushValue = () => broadcast({ t: 'value' });
1368
+ pushNews = () => broadcast({ t: 'news' });
1350
1369
  reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
1351
1370
  manager.rules.on('change', (rules) => broadcast({ t: 'rules', rules }));
1352
1371
  repeats.on('change', (view) => broadcast({ t: 'repeats', repeats: view }));
@@ -1484,6 +1503,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1484
1503
  landing.close();
1485
1504
  standup.close();
1486
1505
  value.close();
1506
+ news.close();
1487
1507
  reviews.close();
1488
1508
  hunts.close();
1489
1509
  benches.close();
package/src/today.js CHANGED
@@ -32,6 +32,15 @@ export function dueAt(due, now = new Date()) {
32
32
  return null;
33
33
  }
34
34
 
35
+ /**
36
+ * When an action is due: its words read from when it was asked, so "by Friday" said last week is
37
+ * that Friday (overdue now), not the next one. From `now` when it isn't known when it was asked.
38
+ */
39
+ export function actionDue(a, now = new Date()) {
40
+ const asked = a?.when ? new Date(a.when) : null;
41
+ return dueAt(a?.due, asked && Number.isFinite(asked.getTime()) ? asked : now);
42
+ }
43
+
35
44
  /** "overdue 2 days", "due today", "due tomorrow", "due Friday", or null. */
36
45
  export function dueWords(at, now = new Date()) {
37
46
  if (!at) return null;
@@ -87,12 +96,12 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
87
96
  if (a.group !== 'open') continue;
88
97
  // A question put to you: asked directly is pressing; copied or mentioned can wait a little.
89
98
  if (a.kind === 'question') {
90
- const at = dueAt(a.due, now);
99
+ const at = actionDue(a, now);
91
100
  const why = [a.cc ? `you're copied${a.from ? `; ${a.from} asked` : ''}` : a.from ? `${a.from} asked you` : 'asked of you', a.sourceLabel && `in ${a.sourceLabel}`, dueWords(at, now), a.answer ? 'answer drafted' : 'no answer drafted yet'].filter(Boolean).join(' · ');
92
101
  items.push({ id: `action:${a.id}`, kind: 'ask', label: a.cc ? "CC'd" : 'Asked you', title: a.question || a.text, why, score: a.cc ? 44 : at && at.getTime() < now.getTime() + DAY ? 16 : 22, at: a.when ?? null, url: a.link ?? null, actionId: a.id, draft: a.answer ?? null });
93
102
  continue;
94
103
  }
95
- const at = dueAt(a.due, now);
104
+ const at = actionDue(a, now);
96
105
  const words = dueWords(at, now);
97
106
  const late = at && at.getTime() < now.getTime();
98
107
  const soon = at && !late && at.getTime() - now.getTime() < DAY;