@newses/plugin-digest-summary 0.1.1 → 0.3.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/dist/digest.js CHANGED
@@ -1,33 +1,62 @@
1
- import Anthropic from '@anthropic-ai/sdk';
2
1
  import { DIGEST_LIMITS, } from '@newses/plugin-api';
3
- import { FALLBACK_BETA, finalText } from './claude.js';
4
- import { MERGE_SYSTEM, mergePrompt, OVERVIEW_FORMAT, OVERVIEW_SYSTEM, overviewPrompt, PART_FORMAT, PART_SYSTEM, partPrompt, readOverview, readPart, } from './prompts.js';
2
+ import { PART_TOKENS } from './providers/anthropic.js';
3
+ import { MERGE_SYSTEM, mergePrompt, OVERVIEW_SYSTEM, overviewPrompt, PART_SYSTEM, partFormat, partPrompt, partThemes, preferencesText, readPart, readSections, sectionsFormat, sectionsOf, } from './prompts.js';
5
4
  import { costOf, dollars, tokensIn } from './prices.js';
6
- import { count, remaining, tokensOf } from './usage.js';
7
- /** Input tokens one request reads at most; a larger digest is read in parts. */
8
- export const PART_TOKENS = 50_000;
9
- /** Parts read at once, at most; a digest larger than this many parts has larger parts. */
5
+ import { DEFAULT_SECTIONS, INSTRUCTIONS_LENGTH, } from './settings.js';
6
+ import { estimateTokens } from './tokens.js';
7
+ import { count, remaining } from './usage.js';
8
+ export { estimateTokens, PART_TOKENS };
9
+ /** Parts a digest is read in, at most; a larger one has larger parts, or reads the newest. */
10
10
  export const MAX_PARTS = 6;
11
11
  /** Of the time left, the share the parts may take, leaving the rest to the merge. */
12
12
  const PARTS_SHARE = 0.6;
13
- /** A request's `max_tokens`, thinking included. */
14
- const MAX_TOKENS = 16_000;
15
- /** Output tokens a request is expected to use, thinking included, for the budget check. */
16
- const OUTPUT_ESTIMATE = 3_000;
13
+ /**
14
+ * Output tokens Claude is expected to use, thinking included, for the budget check: a part's,
15
+ * and the overview's by length.
16
+ */
17
+ const PART_OUTPUT_ESTIMATE = 3_000;
18
+ export const OUTPUT_ESTIMATE = { brief: 3_000, standard: 5_000, detailed: 8_000 };
19
+ /**
20
+ * Output tokens a self-hosted model may write, without thinking: a part's, and the overview's
21
+ * by length; thinking adds `THINKING_TOKENS` to the overview's, as parts never think. They are its `num_predict`/`max_tokens`,
22
+ * and are kept free of its context.
23
+ */
24
+ const LOCAL_PART_OUTPUT = 3_000;
25
+ export const LOCAL_OUTPUT = { brief: 2_000, standard: 4_000, detailed: 7_000 };
26
+ const THINKING_TOKENS = 4_000;
27
+ /** Of a self-hosted model's context, the share planned for, as token counts are estimated. */
28
+ const CONTEXT_SHARE = 0.85;
17
29
  /** Input tokens the parts' themes are expected to take in the request that merges them. */
18
- const THEMES_ESTIMATE = 400;
19
- /** The requests reading articles of `whole` tokens are expected to take: one, or parts and a merge. */
20
- export function plannedRequests(partTokens, whole) {
21
- const request = (input) => ({
22
- input,
30
+ const THEMES_ESTIMATE = 800;
31
+ /**
32
+ * Output tokens the requests are given (and expected to use): a part's, and the overview's; a
33
+ * self-hosted model's at most half its context, leaving the rest to the prompt.
34
+ */
35
+ export function outputTokens(capacity, length) {
36
+ if (capacity.kind === 'grow')
37
+ return { part: PART_OUTPUT_ESTIMATE, overview: OUTPUT_ESTIMATE[length] };
38
+ const thinking = capacity.thinking ? THINKING_TOKENS : 0;
39
+ const half = Math.floor(capacity.contextTokens / 2);
40
+ return {
41
+ part: Math.min(half, LOCAL_PART_OUTPUT),
42
+ overview: Math.min(half, LOCAL_OUTPUT[length] + thinking),
43
+ };
44
+ }
45
+ /**
46
+ * The requests reading articles of `whole` tokens are expected to take: one, or parts and a
47
+ * merge; `preferences` is the tokens of the reader's preferences each request carries.
48
+ */
49
+ export function plannedRequests(partTokens, whole, options) {
50
+ const request = (input, output = options.output.overview) => ({
51
+ input: input + options.preferences,
23
52
  cacheWrite: 0,
24
53
  cacheRead: 0,
25
- output: OUTPUT_ESTIMATE,
54
+ output,
26
55
  });
27
56
  if (!partTokens)
28
57
  return [request(whole)];
29
58
  return [
30
- ...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens)),
59
+ ...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens, options.output.part)),
31
60
  request(estimateTokens(MERGE_SYSTEM) + THEMES_ESTIMATE * partTokens.length),
32
61
  ];
33
62
  }
@@ -47,9 +76,13 @@ export function chosen(entries, settings) {
47
76
  return true;
48
77
  });
49
78
  }
50
- /** Entries grouped by feed, feeds in the order their newest entry comes. */
79
+ /**
80
+ * Entries grouped by feed, feeds in the order their newest entry comes, each entry with a ref
81
+ * (`a1`, `a2`, … in the order given), and the entry id each ref names.
82
+ */
51
83
  export function byFeed(entries) {
52
84
  const feeds = new Map();
85
+ const ids = new Map();
53
86
  for (const entry of entries) {
54
87
  if (!entry.feed)
55
88
  continue;
@@ -58,18 +91,28 @@ export function byFeed(entries) {
58
91
  feed = { feed: entry.feed.title, articles: [] };
59
92
  feeds.set(entry.feed.id, feed);
60
93
  }
61
- feed.articles.push({ title: entry.title, excerpt: entry.excerpt });
94
+ const ref = `a${String(ids.size + 1)}`;
95
+ ids.set(ref, entry.id);
96
+ feed.articles.push({ ref, title: entry.title, excerpt: entry.excerpt });
62
97
  }
63
- return [...feeds.values()];
98
+ return { feeds: [...feeds.values()], ids };
64
99
  }
65
- /** Tokens a text is about, rounded up: some 3 characters each. */
66
- export const estimateTokens = (text) => Math.ceil(text.length / 3);
67
- const articleTokens = (article) => estimateTokens(`<article><title>${article.title}</title><start>${article.excerpt ?? ''}</start>`);
100
+ const articleTokens = (article) => estimateTokens(`<article ref="${article.ref}"><title>${article.title}</title><start>${article.excerpt ?? ''}</start>`);
101
+ /** Of the share a part aims at, how far over it a feed may go to stay whole in the part. */
102
+ const PART_STRETCH = 1.1;
68
103
  /**
69
- * Feeds packed into parts of about `limit` tokens, each feed's articles together where they fit;
70
- * a feed larger than a part is split across parts.
104
+ * Feeds packed, in order, into as few parts of at most `limit` tokens as they take, each part
105
+ * about the same size: the articles' tokens shared evenly between them. A feed joins a part whole
106
+ * when that keeps it within `PART_STRETCH` of its share; otherwise its articles fill the part to
107
+ * its share and go on in the next. Every part but the last reaches its share, so there are never
108
+ * more parts than the fewest the articles take.
71
109
  */
72
110
  export function partsOf(feeds, limit) {
111
+ const tokensOf = (articles) => articles.reduce((sum, article) => sum + articleTokens(article), 0);
112
+ const total = feeds.reduce((sum, feed) => sum + tokensOf(feed.articles), 0);
113
+ const count = Math.max(1, Math.ceil(total / limit));
114
+ const share = Math.ceil(total / count);
115
+ const stretch = Math.min(limit, Math.floor(share * PART_STRETCH));
73
116
  const parts = [];
74
117
  let part = [];
75
118
  let size = 0;
@@ -80,12 +123,18 @@ export function partsOf(feeds, limit) {
80
123
  size = 0;
81
124
  };
82
125
  for (const feed of feeds) {
83
- const tokens = feed.articles.reduce((sum, article) => sum + articleTokens(article), 0);
84
- if (size > 0 && size + tokens > limit)
85
- close();
126
+ const tokens = tokensOf(feed.articles);
127
+ if (size + tokens <= stretch) {
128
+ part.push(feed);
129
+ size += tokens;
130
+ if (size >= share)
131
+ close();
132
+ continue;
133
+ }
86
134
  let piece = { feed: feed.feed, articles: [] };
87
135
  for (const article of feed.articles) {
88
136
  const cost = articleTokens(article);
137
+ // One article larger than a part's room still goes in a part of its own.
89
138
  if (size > 0 && size + cost > limit) {
90
139
  if (piece.articles.length > 0)
91
140
  part.push(piece);
@@ -94,6 +143,11 @@ export function partsOf(feeds, limit) {
94
143
  }
95
144
  piece.articles.push(article);
96
145
  size += cost;
146
+ if (size >= share) {
147
+ part.push(piece);
148
+ close();
149
+ piece = { feed: feed.feed, articles: [] };
150
+ }
97
151
  }
98
152
  if (piece.articles.length > 0)
99
153
  part.push(piece);
@@ -102,29 +156,177 @@ export function partsOf(feeds, limit) {
102
156
  return parts;
103
157
  }
104
158
  /**
105
- * How a digest's overview would be read: the user's chosen entries of those listed and unlisted,
106
- * by feed, in one request or in parts, and the requests' expected tokens; null with none chosen.
159
+ * The reader's preferences as the requests give them: the sections, and the second system block
160
+ * of the overview's requests and of the parts'. Their instructions only when the server allows.
161
+ */
162
+ export function preferencesOf(settings, userSettings) {
163
+ const sections = sectionsOf(userSettings, DEFAULT_SECTIONS);
164
+ const instructions = settings.allowInstructions
165
+ ? userSettings.instructions.trim().slice(0, INSTRUCTIONS_LENGTH) || null
166
+ : null;
167
+ const options = {
168
+ sections,
169
+ length: userSettings.length,
170
+ lead: userSettings.lead,
171
+ instructions,
172
+ };
173
+ return {
174
+ sections,
175
+ names: sections.map((section) => section.name),
176
+ overview: preferencesText(options),
177
+ parts: preferencesText({ ...options, forParts: true }),
178
+ };
179
+ }
180
+ /**
181
+ * Article tokens one request to a self-hosted model may carry: its context, less the output it
182
+ * may write, the longer system prompt, and the reader's preferences, of which `CONTEXT_SHARE`;
183
+ * at least one article's worth.
107
184
  */
108
- export function planOf(input, userSettings) {
109
- const entries = chosen([...input.entries, ...input.unlisted], userSettings);
110
- if (entries.length === 0)
185
+ export function contextLimit(capacity, output, preferences) {
186
+ const prompt = Math.max(estimateTokens(OVERVIEW_SYSTEM), estimateTokens(PART_SYSTEM));
187
+ const room = Math.floor((capacity.contextTokens - Math.max(output.part, output.overview)) * CONTEXT_SHARE) -
188
+ prompt -
189
+ estimateTokens(preferences) -
190
+ // The user turn's lines before the articles.
191
+ 100;
192
+ return Math.max(room, 200);
193
+ }
194
+ /**
195
+ * Parts a self-hosted model may read a digest in: at most `MAX_PARTS`, and no more than the
196
+ * request merging their themes holds in its context; one when it holds none.
197
+ */
198
+ export function contextParts(capacity, output, preferences) {
199
+ const room = Math.floor((capacity.contextTokens - output.overview) * CONTEXT_SHARE) -
200
+ estimateTokens(MERGE_SYSTEM) -
201
+ estimateTokens(preferences) -
202
+ 100;
203
+ return Math.max(1, Math.min(MAX_PARTS, Math.floor(room / THEMES_ESTIMATE)));
204
+ }
205
+ /** The newest entries whose articles take at most `limit` tokens, in their order; one at least. */
206
+ function newestWithin(entries, limit) {
207
+ let size = 0;
208
+ const kept = [];
209
+ for (const entry of entries) {
210
+ size += articleTokens({ ref: `a${String(kept.length + 1)}`, ...entry });
211
+ if (kept.length > 0 && size > limit)
212
+ break;
213
+ kept.push(entry);
214
+ }
215
+ return kept;
216
+ }
217
+ /**
218
+ * How a digest's overview would be read: the user's chosen entries of those listed and unlisted
219
+ * (a self-hosted model's, the newest its parts hold), by feed with their refs, the reader's
220
+ * preferences, in one request or in parts, the requests' output tokens and expected tokens;
221
+ * null with none chosen. `total` is every unread article the digest counts.
222
+ */
223
+ export function planOf(input, settings, userSettings, capacity = { kind: 'grow', partTokens: PART_TOKENS }) {
224
+ const chosenEntries = chosen([...input.entries, ...input.unlisted], userSettings);
225
+ if (chosenEntries.length === 0)
111
226
  return null;
112
- const feeds = byFeed(entries);
113
- const total = entries.length + Math.max(0, input.more - input.unlisted.length);
227
+ const preferences = preferencesOf(settings, userSettings);
228
+ const total = chosenEntries.length + Math.max(0, input.more - input.unlisted.length);
229
+ const output = outputTokens(capacity, userSettings.length);
230
+ let entries = chosenEntries;
231
+ let parts;
232
+ let byRef;
233
+ let maxParts = MAX_PARTS;
234
+ if (capacity.kind === 'grow') {
235
+ byRef = byFeed(entries);
236
+ const whole = estimateTokens(OVERVIEW_SYSTEM) + articlesTokens(byRef.feeds);
237
+ parts =
238
+ whole <= capacity.partTokens
239
+ ? null
240
+ : partsOf(byRef.feeds, Math.max(capacity.partTokens, Math.ceil(whole / MAX_PARTS)));
241
+ }
242
+ else {
243
+ const limit = contextLimit(capacity, output, preferences.overview);
244
+ maxParts = contextParts(capacity, output, preferences.overview);
245
+ // Feeds packed into parts leave some room unused, so a little more than the parts hold is
246
+ // taken, and what does not fit in `maxParts` is left out.
247
+ entries = newestWithin(chosenEntries, Math.floor(limit * maxParts * 0.95));
248
+ byRef = byFeed(entries);
249
+ parts = articlesTokens(byRef.feeds) <= limit ? null : partsOf(byRef.feeds, limit);
250
+ // One part is one request: what it holds is all that is read.
251
+ if (maxParts === 1)
252
+ parts = null;
253
+ if (parts && parts.length > maxParts) {
254
+ parts = parts.slice(0, maxParts);
255
+ const read = new Set(parts.flat().flatMap((feed) => feed.articles.map((a) => a.ref)));
256
+ entries = entries.filter((_, index) => read.has(`a${String(index + 1)}`));
257
+ byRef = {
258
+ feeds: byRef.feeds,
259
+ ids: new Map([...byRef.ids].filter(([ref]) => read.has(ref))),
260
+ };
261
+ }
262
+ }
263
+ const { feeds, ids } = byRef;
114
264
  const whole = estimateTokens(OVERVIEW_SYSTEM) + articlesTokens(feeds);
115
- const parts = whole <= PART_TOKENS
116
- ? null
117
- : partsOf(feeds, Math.max(PART_TOKENS, Math.ceil(whole / MAX_PARTS)));
118
- const planned = plannedRequests(parts?.map(articlesTokens) ?? null, whole);
119
- return { entries, feeds, total, parts, planned };
265
+ const planned = plannedRequests(parts?.map(articlesTokens) ?? null, whole, {
266
+ preferences: estimateTokens(preferences.overview),
267
+ output,
268
+ });
269
+ return {
270
+ entries,
271
+ chosen: chosenEntries.length,
272
+ feeds,
273
+ ids,
274
+ preferences,
275
+ total,
276
+ parts,
277
+ maxParts,
278
+ planned,
279
+ output,
280
+ };
281
+ }
282
+ /** The overview as the digest takes it: the lead as its overview, then its sections. */
283
+ export function additionsOf(overview, userSettings) {
284
+ return {
285
+ overview: userSettings.lead && overview.lead ? overview.lead : null,
286
+ sections: overview.sections.map((section) => ({
287
+ heading: section.heading,
288
+ list: userSettings.style === 'bullets',
289
+ items: section.points.map((point) => ({ text: point.text, entries: point.entries })),
290
+ })),
291
+ };
292
+ }
293
+ /** Where the speed a self-hosted model last read and wrote at is kept, in the instance's store. */
294
+ const SPEED_KEY = 'speed';
295
+ async function speedOf(storage) {
296
+ const value = (await storage.get(SPEED_KEY));
297
+ return typeof value?.prompt === 'number' && typeof value.output === 'number'
298
+ ? { prompt: value.prompt, output: value.output }
299
+ : null;
300
+ }
301
+ /** Keeps the speed of an answer that read and wrote enough to measure it. */
302
+ async function keepSpeed(storage, timing) {
303
+ if (timing.promptMs <= 0 || timing.outputMs <= 0 || timing.outputTokens < 50)
304
+ return;
305
+ await storage.set(SPEED_KEY, {
306
+ prompt: (timing.promptTokens * 1000) / timing.promptMs,
307
+ output: (timing.outputTokens * 1000) / timing.outputMs,
308
+ });
309
+ }
310
+ /**
311
+ * Seconds the planned requests would take at a speed, at most: the parts `parallel` at a time,
312
+ * then the overview, each writing all the output it may.
313
+ */
314
+ function secondsAt(speed, planned, parallel) {
315
+ const seconds = planned.map((r) => r.input / speed.prompt + r.output / speed.output);
316
+ if (seconds.length === 1)
317
+ return seconds[0] ?? 0;
318
+ const parts = seconds.slice(0, -1);
319
+ return (parts.reduce((sum, s) => sum + s, 0) / Math.min(parallel, parts.length) + (seconds.at(-1) ?? 0));
120
320
  }
121
321
  /**
122
322
  * What the overview of a digest is expected to cost, making no request, as plain text: how it
123
- * would be read, its tokens, and US dollars at list prices, or why it would add nothing.
323
+ * would be read, its tokens, and US dollars at list prices, or why it would add nothing. A
324
+ * self-hosted model's has no price, but how many articles its context holds, and how long it
325
+ * would take at the speed it last answered at.
124
326
  */
125
327
  export async function estimate(options) {
126
- const { settings } = options;
127
- const plan = planOf(options.input, options.userSettings);
328
+ const { settings, provider } = options;
329
+ const plan = planOf(options.input, settings, options.userSettings, provider.capacity);
128
330
  if (!plan)
129
331
  return "None of the test digest's articles are from feeds it reads, so it would add nothing.";
130
332
  const tokens = tokensIn(plan.planned);
@@ -135,23 +337,41 @@ export async function estimate(options) {
135
337
  const requests = `${String(plan.planned.length)} ${plan.planned.length === 1 ? 'request' : 'requests'}`;
136
338
  if (left < tokens)
137
339
  return `A test digest now: ${articles}, about ${formatted(tokens)} tokens, more than the ${formatted(left)} left of this month's budget, so it would add nothing.`;
138
- return `A test digest now: ${articles} in ${requests} to ${settings.model} at ${settings.effort} effort, about ${formatted(tokens)} tokens, ${dollars(costOf(settings.model, plan.planned))}. The output is estimated.`;
340
+ const { capacity } = provider;
341
+ if (capacity.kind === 'grow')
342
+ return `A test digest now: ${articles} in ${requests} to ${provider.label}, about ${formatted(tokens)} tokens, ${dollars(costOf(settings.model, plan.planned))}. The output is estimated.`;
343
+ const held = count < plan.chosen
344
+ ? `: the newest ${formatted(count)} of ${formatted(plan.chosen)}, as many as ${formatted(capacity.contextTokens)} tokens of context hold in ${String(plan.maxParts)} ${plan.maxParts === 1 ? 'request' : 'parts'}`
345
+ : '';
346
+ const speed = await speedOf(options.storage);
347
+ const minutes = speed
348
+ ? Math.max(1, Math.round(secondsAt(speed, plan.planned, provider.parallel) / 60))
349
+ : null;
350
+ const time = minutes === null
351
+ ? ''
352
+ : ` At the speed it last answered at, it would take up to about ${String(minutes)} ${minutes === 1 ? 'minute' : 'minutes'}${minutes * 60 > DIGEST_LIMITS.timeoutSeconds
353
+ ? `, longer than the ${String(DIGEST_LIMITS.timeoutSeconds / 60)} minutes a digest waits, so parts would be left out`
354
+ : ''}.`;
355
+ return `A test digest now: ${articles} in ${requests} to ${provider.label}, about ${formatted(tokens)} tokens${held}. It runs on your own server, at no charge per token.${time}`;
139
356
  }
357
+ const nothing = (outcome) => ({ overview: null, sections: null, outcome });
140
358
  /**
141
359
  * One digest's overview: the user's chosen entries of those listed and unlisted, read in one
142
- * request, or in parts whose themes a last request turns into the overview, within the budgets.
143
- * Whatever a request ends as (refused, unreadable, out of time), the digest goes out without it.
360
+ * request, or in parts whose themes a last request turns into the overview, within the budgets,
361
+ * as a lead and sections whose points cite entries. Whatever a request ends as (refused,
362
+ * unreadable, out of time), the digest goes out without it.
144
363
  */
145
364
  export async function compose(options) {
146
- const { client, settings, input, storage, userStorage, logger, signal } = options;
147
- const plan = planOf(input, options.userSettings);
365
+ const { provider, settings, userSettings, input, storage, userStorage, logger, signal } = options;
366
+ const plan = planOf(input, settings, userSettings, provider.capacity);
148
367
  if (!plan)
149
- return { overview: null, outcome: 'none' };
150
- const { entries, feeds, total, parts, planned } = plan;
368
+ return nothing('none');
369
+ const { entries, feeds, ids, preferences, total, parts, planned, output } = plan;
370
+ const { names } = preferences;
151
371
  const budgets = { instance: settings.monthlyTokens, user: settings.userMonthlyTokens };
152
372
  if ((await remaining(budgets, { instance: storage, user: userStorage }, options.now())) <
153
373
  tokensIn(planned))
154
- return { overview: null, outcome: 'over budget' };
374
+ return nothing('over budget');
155
375
  // Counts are read and written back, so parts answering together count one after another.
156
376
  let counting = Promise.resolve();
157
377
  const counted = (tokens) => {
@@ -162,86 +382,106 @@ export async function compose(options) {
162
382
  });
163
383
  return counting;
164
384
  };
165
- const ask = async (system, prompt, format, by) => {
166
- let response;
385
+ const ask = async (system, prompt, format, maxTokens, by, thinking) => {
167
386
  // Whole milliseconds: AbortSignal.timeout refuses fractions.
168
387
  const left = Math.max(1, Math.floor(by - Date.now()));
169
388
  const ownTime = AbortSignal.timeout(left);
170
- try {
171
- response = await client.beta.messages.create({
172
- model: settings.model,
173
- max_tokens: MAX_TOKENS,
174
- betas: [FALLBACK_BETA],
175
- fallbacks: 'default',
176
- output_config: { effort: settings.effort, format },
177
- system: [{ type: 'text', text: system, cache_control: { type: 'ephemeral' } }],
178
- messages: [{ role: 'user', content: prompt }],
179
- }, {
180
- signal: AbortSignal.any([signal, ownTime]),
181
- timeout: left,
182
- maxRetries: 0,
183
- });
184
- }
185
- catch (error) {
186
- // Out of its own time, rather than the digest's (which ends the digest too).
187
- const timedOut = !signal.aborted &&
188
- (ownTime.aborted || error instanceof Anthropic.APIConnectionTimeoutError);
189
- logger.warn(timedOut ? 'digest request ran out of time' : 'digest request failed', {
190
- error: String(error),
191
- });
192
- return { ok: false, outcome: timedOut ? 'timed out' : 'failed' };
389
+ const asked = await provider.ask({
390
+ system,
391
+ prompt,
392
+ format,
393
+ maxTokens,
394
+ thinking,
395
+ signal: AbortSignal.any([signal, ownTime]),
396
+ timeoutMs: left,
397
+ });
398
+ if (asked.tokens > 0)
399
+ await counted(asked.tokens);
400
+ if (asked.ok) {
401
+ if (asked.timing)
402
+ await keepSpeed(storage, asked.timing);
403
+ return { ok: true, text: asked.text };
193
404
  }
194
- await counted(tokensOf(response.usage));
195
- if (response.stop_reason === 'refusal')
196
- return { ok: false, outcome: 'refused' };
197
- if (response.stop_reason !== 'end_turn')
198
- return { ok: false, outcome: 'invalid' };
199
- return { ok: true, text: finalText(response.content) };
405
+ if (asked.outcome !== 'failed' && asked.outcome !== 'timed out')
406
+ return { ok: false, outcome: asked.outcome };
407
+ // Out of its own time, rather than the digest's (which ends the digest too).
408
+ const timedOut = !signal.aborted && (ownTime.aborted || asked.outcome === 'timed out');
409
+ logger.warn(timedOut ? 'digest request ran out of time' : 'digest request failed', {
410
+ provider: provider.name,
411
+ error: String(asked.error),
412
+ });
413
+ return { ok: false, outcome: timedOut ? 'timed out' : 'failed' };
200
414
  };
201
415
  const language = input.language;
202
416
  const frequency = input.frequency;
417
+ const read = (text) => readSections(text, { names, length: userSettings.length, ids });
203
418
  if (!parts) {
204
- const asked = await ask(OVERVIEW_SYSTEM, overviewPrompt({ language, frequency, total, feeds }), OVERVIEW_FORMAT, options.deadline);
419
+ const asked = await ask([OVERVIEW_SYSTEM, preferences.overview], overviewPrompt({ language, frequency, total, feeds }), sectionsFormat(names), output.overview, options.deadline, true);
205
420
  if (!asked.ok)
206
- return { overview: null, outcome: asked.outcome };
207
- const overview = readOverview(asked.text);
208
- return overview ? { overview, outcome: 'written' } : { overview: null, outcome: 'invalid' };
421
+ return nothing(asked.outcome);
422
+ const overview = read(asked.text);
423
+ return overview
424
+ ? { ...additionsOf(overview, userSettings), outcome: 'written' }
425
+ : nothing('invalid');
209
426
  }
210
427
  const partsBy = Date.now() + Math.floor((options.deadline - Date.now()) * PARTS_SHARE);
211
- const found = await Promise.all(parts.map(async (part) => {
212
- const asked = await ask(PART_SYSTEM, partPrompt({ language, feeds: part }), PART_FORMAT, partsBy);
428
+ // A part not started by then runs out of time without a request.
429
+ const found = await pooled(parts, provider.parallel, async (part) => {
430
+ if (Date.now() >= partsBy)
431
+ return 'timed out';
432
+ const asked = await ask([PART_SYSTEM, preferences.parts], partPrompt({ language, feeds: part }), partFormat(names), output.part, partsBy,
433
+ // Sorting articles into themes needs no thinking; writing the overview may.
434
+ false);
213
435
  if (!asked.ok)
214
436
  return asked.outcome;
215
- return readPart(asked.text) ?? 'invalid';
216
- }));
437
+ return (readPart(asked.text, { names, ids, themes: partThemes(userSettings.length) }) ?? 'invalid');
438
+ });
217
439
  // A part that failed or ran out of time leaves the overview to the parts that answered.
218
- const read = parts.filter((_, index) => typeof found[index] !== 'string');
219
- if (read.length === 0)
220
- return { overview: null, outcome: found[0] };
221
- const asked = await ask(MERGE_SYSTEM, mergePrompt({
440
+ const answered = parts.filter((_, index) => typeof found[index] !== 'string');
441
+ if (answered.length === 0)
442
+ return nothing(found[0]);
443
+ const asked = await ask([MERGE_SYSTEM, preferences.overview], mergePrompt({
222
444
  language,
223
445
  frequency,
224
446
  given: entries.length,
225
- read: read.length < parts.length ? articleCount(read.flat()) : entries.length,
447
+ read: answered.length < parts.length ? articleCount(answered.flat()) : entries.length,
226
448
  total,
227
449
  parts: found.filter((part) => typeof part !== 'string'),
228
- }), OVERVIEW_FORMAT, options.deadline);
450
+ }), sectionsFormat(names), output.overview, options.deadline, true);
229
451
  if (!asked.ok)
230
- return { overview: null, outcome: asked.outcome };
231
- const overview = readOverview(asked.text);
452
+ return nothing(asked.outcome);
453
+ const overview = read(asked.text);
232
454
  if (!overview)
233
- return { overview: null, outcome: 'invalid' };
234
- if (read.length === parts.length)
235
- return { overview, outcome: 'written' };
455
+ return nothing('invalid');
456
+ const additions = additionsOf(overview, userSettings);
457
+ if (answered.length === parts.length)
458
+ return { ...additions, outcome: 'written' };
236
459
  const missed = found.filter((part) => typeof part === 'string');
237
460
  const note = missingNote({
238
- read: articleCount(read.flat()),
461
+ read: articleCount(answered.flat()),
239
462
  given: entries.length,
240
463
  parts: parts.length,
241
464
  timedOut: missed.filter((outcome) => outcome === 'timed out').length,
242
465
  failed: missed.filter((outcome) => outcome !== 'timed out').length,
243
466
  });
244
- return { overview: withNote(overview, note), outcome: 'partial' };
467
+ return {
468
+ overview: additions.overview ? withNote(additions.overview, note) : note,
469
+ sections: additions.sections,
470
+ outcome: 'partial',
471
+ };
472
+ }
473
+ /** Each item run, at most `size` at once, the results in the items' order. */
474
+ async function pooled(items, size, run) {
475
+ const results = [];
476
+ let next = 0;
477
+ const worker = async () => {
478
+ while (next < items.length) {
479
+ const index = next++;
480
+ results[index] = await run(items[index]);
481
+ }
482
+ };
483
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(size, items.length)) }, worker));
484
+ return results;
245
485
  }
246
486
  /** What an overview written from only some parts says of the rest. */
247
487
  export function missingNote(counts) {
package/dist/index.d.ts CHANGED
@@ -1,10 +1,17 @@
1
1
  /**
2
- * Opens each user's email digest with an overview of what their unread articles are about,
3
- * written by Claude through the Anthropic API from the titles and excerpts of every unread
4
- * article the digest counts, of the feeds the user chooses.
2
+ * Opens each user's email digest with an overview of what their unread articles are about, in
3
+ * topic sections whose points link the articles they draw on, written by Claude through the
4
+ * Anthropic API or by a self-hosted model (Ollama, or a server with the OpenAI chat completions
5
+ * API) from the titles and excerpts of the unread articles the digest counts, of the feeds the
6
+ * user chooses, with the sections, length, style, and instructions the user chooses.
5
7
  */
6
8
  declare const _default: import("@newses/plugin-api").PluginDefinition<import("zod").ZodObject<{
7
- apiKey: import("zod").ZodString;
9
+ provider: import("zod").ZodDefault<import("zod").ZodEnum<{
10
+ anthropic: "anthropic";
11
+ ollama: "ollama";
12
+ openai: "openai";
13
+ }>>;
14
+ apiKey: import("zod").ZodOptional<import("zod").ZodString>;
8
15
  model: import("zod").ZodDefault<import("zod").ZodEnum<{
9
16
  "claude-opus-5-5": "claude-opus-5-5";
10
17
  "claude-sonnet-5-5": "claude-sonnet-5-5";
@@ -15,8 +22,15 @@ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zo
15
22
  medium: "medium";
16
23
  high: "high";
17
24
  }>>;
25
+ baseUrl: import("zod").ZodOptional<import("zod").ZodURL>;
26
+ localApiKey: import("zod").ZodOptional<import("zod").ZodString>;
27
+ localModel: import("zod").ZodDefault<import("zod").ZodString>;
28
+ contextTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
29
+ parallelRequests: import("zod").ZodDefault<import("zod").ZodNumber>;
30
+ thinking: import("zod").ZodDefault<import("zod").ZodBoolean>;
18
31
  monthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
19
32
  userMonthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
33
+ allowInstructions: import("zod").ZodDefault<import("zod").ZodBoolean>;
20
34
  }, import("zod/v4/core").$strip>, import("zod").ZodObject<{
21
35
  feedChoice: import("zod").ZodDefault<import("zod").ZodEnum<{
22
36
  all: "all";
@@ -24,5 +38,20 @@ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zo
24
38
  except: "except";
25
39
  }>>;
26
40
  feeds: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodInt>>;
41
+ sections: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
42
+ name: import("zod").ZodString;
43
+ about: import("zod").ZodDefault<import("zod").ZodString>;
44
+ }, import("zod/v4/core").$strip>>>;
45
+ length: import("zod").ZodDefault<import("zod").ZodEnum<{
46
+ brief: "brief";
47
+ standard: "standard";
48
+ detailed: "detailed";
49
+ }>>;
50
+ style: import("zod").ZodDefault<import("zod").ZodEnum<{
51
+ paragraphs: "paragraphs";
52
+ bullets: "bullets";
53
+ }>>;
54
+ lead: import("zod").ZodDefault<import("zod").ZodBoolean>;
55
+ instructions: import("zod").ZodDefault<import("zod").ZodString>;
27
56
  }, import("zod/v4/core").$strip>>;
28
57
  export default _default;