@newses/plugin-digest-summary 0.1.1 → 0.2.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Newses digest summary plugin
2
2
 
3
- A [Newses](https://newses.app) server plugin that opens each user's email digest with an overview of what their unread articles are about: their common themes, then other notable stories. Claude writes it through the Anthropic API.
3
+ A [Newses](https://newses.app) server plugin that opens each user's email digest with an overview of what their unread articles are about: a lead on their common themes, then topic sections (world, politics, technology, sports…) whose points link the articles they draw on. Claude writes it through the Anthropic API, with the sections, length, style, and instructions each user chooses.
4
4
 
5
5
  ## What is sent, and to whom
6
6
 
@@ -8,16 +8,18 @@ A [Newses](https://newses.app) server plugin that opens each user's email digest
8
8
  - What is sent, for each digest:
9
9
  - the digest's language;
10
10
  - how many unread articles it has;
11
- - for each unread article of the feeds the user chose: its title, the feed's name, and the start of its text as the digest shows it.
11
+ - for each unread article of the feeds the user chose: its title, the feed's name, the start of its text as the digest shows it, and a ref (`a12`) the answer cites it by;
12
+ - the user's sections (names and what goes in each), length, and whether there is a lead;
13
+ - the user's own instructions, when they wrote some and an admin allows them.
12
14
 
13
15
  That covers the up to 100 articles the digest lists and up to 2,000 more that it counts.
14
16
 
15
- - Never sent: articles from feeds with a login, pages a user published from outside any feed, links, authors, and anything about the user.
17
+ - Never sent: articles from feeds with a login, pages a user published from outside any feed, links, authors, and anything else about the user.
16
18
  - Only for users who turn the plugin on for themselves.
17
19
 
18
20
  ## Install
19
21
 
20
- The server's operator installs it at an exact version, `@newses/plugin-digest-summary@0.1.0`. It needs a server with plugin API 0.1.1 or later.
22
+ The server's operator installs it at an exact version, `@newses/plugin-digest-summary@0.2.0`. It needs a server with plugin API 0.1.2 or later, which links the articles sections cite.
21
23
 
22
24
  - **Docker:** add it to `PLUGINS` in `.env` and start with the plugins override ([Self-hosting](https://newses.app/guide/self-hosting#plugins)).
23
25
  - **AWS:** add it to the stage's `plugins` in the deployment config, then `scripts/store-deploy-config.sh --apply --release STAGE` ([Plugins](https://newses.app/guide/plugins)).
@@ -25,50 +27,61 @@ The server's operator installs it at an exact version, `@newses/plugin-digest-su
25
27
  Then, in Settings > Plugins:
26
28
 
27
29
  1. An admin creates an API key in the [Claude Console](https://platform.claude.com) (API keys), enters it, approves the host `api.anthropic.com`, and turns the plugin on for the server.
28
- 2. Each user who wants an overview turns it on for themselves under "For me", and chooses which feeds it reads. "Send test" checks the key and says how many tokens this month used.
30
+ 2. Each user who wants an overview turns it on for themselves under "For me", and chooses which feeds it reads, its sections, length, and style. "Send test" checks the key, says how many tokens this month used, and sends a test digest.
29
31
 
30
32
  ## Settings
31
33
 
32
- | Setting | Who | What it does |
33
- | ------------------------------ | ----- | --------------------------------------------------------------------------------------------------------------------- |
34
- | Anthropic API key | Admin | Every request is billed to it; a secret |
35
- | Model | Admin | Claude Opus 5.5 (default), Sonnet 5.5, or Haiku 5.5 |
36
- | Effort | Admin | How much the model thinks before it writes: low (default), medium, or high; higher costs more tokens and takes longer |
37
- | Tokens a month, for the server | Admin | 10,000,000 by default; once used, no overviews are written until the month ends (UTC) |
38
- | Tokens a month, for each user | Admin | 1,000,000 by default; counts the user's overviews |
39
- | Feeds to read | User | All my feeds (default), only the feeds chosen, or all but the feeds chosen |
40
- | Feeds | User | Picked from the user's subscriptions |
34
+ | Setting | Who | What it does |
35
+ | ------------------------------------ | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | Anthropic API key | Admin | Every request is billed to it; a secret |
37
+ | Model | Admin | Claude Opus 5.5 (default), Sonnet 5.5, or Haiku 5.5 |
38
+ | Effort | Admin | How much the model thinks before it writes: low (default), medium, or high; higher costs more tokens and takes longer |
39
+ | Tokens a month, for the server | Admin | 10,000,000 by default; once used, no overviews are written until the month ends (UTC) |
40
+ | Tokens a month, for each user | Admin | 1,000,000 by default; counts the user's overviews |
41
+ | Users may add their own instructions | Admin | On by default; when off, users' instructions are kept but not sent |
42
+ | Feeds to read | User | All my feeds (default), only the feeds chosen, or all but the feeds chosen |
43
+ | Feeds | User | Picked from the user's subscriptions |
44
+ | Sections | User | Up to 12, in order, each a name and what goes in it; by default World, Politics, Business, Technology, Science, Health, Sports, Culture, and Other. Sections nothing fits are left out |
45
+ | Length | User | Brief (up to 2 short points a section), standard (default, 3), or detailed (5 longer ones) |
46
+ | Points shown as | User | Paragraphs (default) or bullets |
47
+ | Open with a lead | User | On by default: a paragraph on what ties stories together across sections |
48
+ | Your instructions | User | Up to 1,000 characters on what to focus on, leave out, or how to write |
41
49
 
42
50
  ## How it works
43
51
 
44
- | Digest size | What happens |
45
- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
46
- | Up to about 50,000 tokens (some 400 articles) | One request reads every chosen article, grouped by feed, and writes the overview |
47
- | Larger | The articles are split into up to 6 parts, feeds kept together where they fit, read at once. Each part gives its themes, with how many articles each covers, and notable stories. A last request writes the overview from them |
52
+ | Digest size | What happens |
53
+ | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
54
+ | Up to about 100,000 tokens (some 800 articles) | One request reads every chosen article, grouped by feed, and writes the overview |
55
+ | Larger | The articles are split into up to 6 parts, feeds kept together where they fit, read at once. Each part sorts its stories into the user's sections and gives each section's themes, with how many articles each covers and the refs of those it draws on. A last request writes the overview from them |
56
+
57
+ - **Sections and citations:** the answer is a lead and sections of points, each section one of the user's (an enum in the output format, so none is made up), its heading the name in the digest's language. Each point cites the refs of up to 5 articles; the plugin turns them into entry ids, leaving out refs it never gave, and the server links each cited article by its title and feed name to the article in Newses, whether the digest lists it or only counts it. Neither the model nor the plugin writes a link.
58
+ - **Limits:** points beyond the length's count, and then, from the end, points beyond the digest's 8,000 characters of sections, are left out.
48
59
 
49
60
  - **Time limit:** a digest waits at most 5 minutes for its plugins. The parts have about 60% of that, and the last request the rest.
50
- - **When an answer is missing:** if a request fails, runs out of time, is declined, is cut off, or is not the format asked for, the digest goes out without an overview. When only some parts answer, the overview is written from them and ends by saying how many articles it covers and how many parts ran out of time or failed.
61
+ - **When an answer is missing:** if a request fails, runs out of time, is declined, is cut off, or is not the format asked for, the digest goes out without an overview. When only some parts answer, the overview is written from them and its lead (or, without one, a note of its own) says how many articles it covers and how many parts ran out of time or failed.
51
62
  - **Untrusted feed text:** it sits in the user turn, escaped inside tags. The system prompt says to summarise only, and to take no instructions from articles. The answer must be JSON of the overview, or of a part's themes, alone (structured outputs).
63
+ - **The user's preferences:** a second system block, after the fixed one that is cached, gives the sections, length, lead, and the user's instructions, escaped. The model follows the instructions on what to cover and how to write; they cannot change the format, make articles anything but material, or ask for anything but a summary. Each user's instructions reach only their own digest, within their monthly budget.
52
64
  - **Declined requests:** when the model declines a request, the server's default fallback model answers instead (server-side fallback).
53
65
 
54
66
  ## Costs
55
67
 
56
68
  Every request is billed to the API key at [Anthropic's prices](https://platform.claude.com/docs/en/about-claude/pricing), per million tokens of input and output; thinking counts as output.
57
69
 
58
- - **Size:** an article takes about 100 input tokens, so a digest of 1,000 unread articles reads about 100,000. The overview takes 500 to 3,000 output tokens, depending on effort.
70
+ - **Size:** an article takes about 100 input tokens, so a digest of 1,000 unread articles reads about 100,000. The overview takes 1,000 to 8,000 output tokens, depending on length and effort.
59
71
  - **Budget check:** before a digest, the plugin estimates its tokens. When the server's or the user's budget left is smaller than that, it makes no request.
60
72
  - **What is counted:** every token, input and output, of every attempt, fallbacks included, against both budgets. "Send test" shows the counts.
61
- - **Estimate:** "Estimate cost" under "For me" shows what the overview of a test digest now would cost, making no request: the tokens it expects, priced at Anthropic's list prices for the three models as of November 2026 (5-minute cache writes at 1.25 times input; Haiku's higher price for prompts over 100,000 tokens), with 3,000 output tokens a request. It counts neither discounts nor answers from a fallback model, and says when the budget left would stop it.
73
+ - **Estimate:** "Estimate cost" under "For me" shows what the overview of a test digest now would cost, making no request: the tokens it expects, priced at Anthropic's list prices for the three models as of November 2026 (5-minute cache writes at 1.25 times input; Haiku's higher price for prompts over 100,000 tokens), with 3,000 output tokens a part, and 3,000, 5,000, or 8,000 for the overview by length. It counts neither discounts nor answers from a fallback model, and says when the budget left would stop it.
62
74
 
63
75
  To choose the effort, measure it on digests like yours, billed to your key:
64
76
 
65
77
  ```sh
66
78
  npm install && npm run build
67
- ANTHROPIC_API_KEY=sk-ant-... node scripts/measure-effort.mjs [DIGEST.json ...] --efforts low,medium,high [--copies 100]
79
+ ANTHROPIC_API_KEY=sk-ant-... node scripts/measure-effort.mjs [DIGEST.json ...] --efforts low,medium,high [--copies 100] [--length brief|standard|detailed] [--instructions TEXT]
68
80
  ```
69
81
 
70
82
  - **Digest files:** a digest file is what the plugin's `digest.compose` hook is given. [scripts/sample-digest.json](scripts/sample-digest.json) is the default, and includes an article that tries to give the model instructions.
71
83
  - **Larger digests:** `--copies N` adds N copies of its articles as unlisted ones, to measure a digest read in parts.
84
+ - **Reader settings:** `--length` and `--instructions` measure those settings, with the default sections. The script prints each section's points with the titles of the articles they cite.
72
85
 
73
86
  ## Failures
74
87
 
package/dist/digest.d.ts CHANGED
@@ -1,14 +1,25 @@
1
1
  import Anthropic from '@anthropic-ai/sdk';
2
- import { type DigestComposeInput, type DigestEntry, type PluginLogger, type PluginStore } from '@newses/plugin-api';
3
- import { type FeedArticles } from './prompts.js';
2
+ import { type DigestComposeInput, type DigestEntry, type DigestSection, type PluginLogger, type PluginStore } from '@newses/plugin-api';
3
+ import { type FeedArticles, type Overview } from './prompts.js';
4
4
  import { type RequestTokens } from './prices.js';
5
- import type { InstanceSettings, UserSettings } from './settings.js';
5
+ import { type InstanceSettings, type UserSettings } from './settings.js';
6
6
  /** Input tokens one request reads at most; a larger digest is read in parts. */
7
- export declare const PART_TOKENS = 50000;
7
+ export declare const PART_TOKENS = 100000;
8
8
  /** Parts read at once, at most; a digest larger than this many parts has larger parts. */
9
9
  export declare const MAX_PARTS = 6;
10
- /** The requests reading articles of `whole` tokens are expected to take: one, or parts and a merge. */
11
- export declare function plannedRequests(partTokens: readonly number[] | null, whole: number): RequestTokens[];
10
+ export declare const OUTPUT_ESTIMATE: {
11
+ readonly brief: 3000;
12
+ readonly standard: 5000;
13
+ readonly detailed: 8000;
14
+ };
15
+ /**
16
+ * The requests reading articles of `whole` tokens are expected to take: one, or parts and a
17
+ * merge; `preferences` is the tokens of the reader's preferences each request carries.
18
+ */
19
+ export declare function plannedRequests(partTokens: readonly number[] | null, whole: number, options: {
20
+ preferences: number;
21
+ length: UserSettings['length'];
22
+ }): RequestTokens[];
12
23
  /** What a digest's overview ended as, for the log. */
13
24
  export type DigestOutcome = 'written'
14
25
  /** Written from the parts that answered, saying how many did not. */
@@ -17,8 +28,14 @@ export type DigestOutcome = 'written'
17
28
  export declare const sendable: (entry: DigestEntry) => boolean;
18
29
  /** The digest's entries the user's feed choice takes, of those that may be sent. */
19
30
  export declare function chosen(entries: readonly DigestEntry[], settings: UserSettings): DigestEntry[];
20
- /** Entries grouped by feed, feeds in the order their newest entry comes. */
21
- export declare function byFeed(entries: readonly DigestEntry[]): FeedArticles[];
31
+ /**
32
+ * Entries grouped by feed, feeds in the order their newest entry comes, each entry with a ref
33
+ * (`a1`, `a2`, … in the order given), and the entry id each ref names.
34
+ */
35
+ export declare function byFeed(entries: readonly DigestEntry[]): {
36
+ feeds: FeedArticles[];
37
+ ids: Map<string, number>;
38
+ };
22
39
  /** Tokens a text is about, rounded up: some 3 characters each. */
23
40
  export declare const estimateTokens: (text: string) => number;
24
41
  /**
@@ -26,17 +43,46 @@ export declare const estimateTokens: (text: string) => number;
26
43
  * a feed larger than a part is split across parts.
27
44
  */
28
45
  export declare function partsOf(feeds: readonly FeedArticles[], limit: number): FeedArticles[][];
46
+ /**
47
+ * The reader's preferences as the requests give them: the sections, and the second system block
48
+ * of the overview's requests and of the parts'. Their instructions only when the server allows.
49
+ */
50
+ export declare function preferencesOf(settings: InstanceSettings, userSettings: UserSettings): {
51
+ sections: {
52
+ name: string;
53
+ about: string;
54
+ }[];
55
+ names: string[];
56
+ overview: string;
57
+ parts: string;
58
+ };
29
59
  /**
30
60
  * How a digest's overview would be read: the user's chosen entries of those listed and unlisted,
31
- * by feed, in one request or in parts, and the requests' expected tokens; null with none chosen.
61
+ * by feed with their refs, the reader's preferences, in one request or in parts, and the
62
+ * requests' expected tokens; null with none chosen.
32
63
  */
33
- export declare function planOf(input: DigestComposeInput, userSettings: UserSettings): {
64
+ export declare function planOf(input: DigestComposeInput, settings: InstanceSettings, userSettings: UserSettings): {
34
65
  entries: DigestEntry[];
35
66
  feeds: FeedArticles[];
67
+ ids: Map<string, number>;
68
+ preferences: {
69
+ sections: {
70
+ name: string;
71
+ about: string;
72
+ }[];
73
+ names: string[];
74
+ overview: string;
75
+ parts: string;
76
+ };
36
77
  total: number;
37
78
  parts: FeedArticles[][] | null;
38
79
  planned: RequestTokens[];
39
80
  } | null;
81
+ /** The overview as the digest takes it: the lead as its overview, then its sections. */
82
+ export declare function additionsOf(overview: Overview, userSettings: Pick<UserSettings, 'lead' | 'style'>): {
83
+ overview: string | null;
84
+ sections: DigestSection[];
85
+ };
40
86
  /**
41
87
  * What the overview of a digest is expected to cost, making no request, as plain text: how it
42
88
  * would be read, its tokens, and US dollars at list prices, or why it would add nothing.
@@ -49,10 +95,17 @@ export declare function estimate(options: {
49
95
  userStorage: PluginStore | null;
50
96
  now: () => Date;
51
97
  }): Promise<string>;
98
+ /** What a digest's overview ended as, and what it adds to the digest. */
99
+ export interface Composed {
100
+ overview: string | null;
101
+ sections: DigestSection[] | null;
102
+ outcome: DigestOutcome;
103
+ }
52
104
  /**
53
105
  * One digest's overview: the user's chosen entries of those listed and unlisted, read in one
54
- * request, or in parts whose themes a last request turns into the overview, within the budgets.
55
- * Whatever a request ends as (refused, unreadable, out of time), the digest goes out without it.
106
+ * request, or in parts whose themes a last request turns into the overview, within the budgets,
107
+ * as a lead and sections whose points cite entries. Whatever a request ends as (refused,
108
+ * unreadable, out of time), the digest goes out without it.
56
109
  */
57
110
  export declare function compose(options: {
58
111
  client: Anthropic;
@@ -66,10 +119,7 @@ export declare function compose(options: {
66
119
  /** When the overview must be written by, in ms since the epoch. */
67
120
  deadline: number;
68
121
  now: () => Date;
69
- }): Promise<{
70
- overview: string | null;
71
- outcome: DigestOutcome;
72
- }>;
122
+ }): Promise<Composed>;
73
123
  /** What an overview written from only some parts says of the rest. */
74
124
  export declare function missingNote(counts: {
75
125
  read: number;
package/dist/digest.js CHANGED
@@ -1,33 +1,41 @@
1
1
  import Anthropic from '@anthropic-ai/sdk';
2
2
  import { DIGEST_LIMITS, } from '@newses/plugin-api';
3
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';
4
+ import { MERGE_SYSTEM, mergePrompt, OVERVIEW_SYSTEM, overviewPrompt, PART_SYSTEM, partFormat, partPrompt, preferencesText, readPart, readSections, sectionsFormat, sectionsOf, } from './prompts.js';
5
5
  import { costOf, dollars, tokensIn } from './prices.js';
6
+ import { DEFAULT_SECTIONS, INSTRUCTIONS_LENGTH, } from './settings.js';
6
7
  import { count, remaining, tokensOf } from './usage.js';
7
8
  /** Input tokens one request reads at most; a larger digest is read in parts. */
8
- export const PART_TOKENS = 50_000;
9
+ export const PART_TOKENS = 100_000;
9
10
  /** Parts read at once, at most; a digest larger than this many parts has larger parts. */
10
11
  export const MAX_PARTS = 6;
11
12
  /** Of the time left, the share the parts may take, leaving the rest to the merge. */
12
13
  const PARTS_SHARE = 0.6;
13
14
  /** A request's `max_tokens`, thinking included. */
14
15
  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;
16
+ /**
17
+ * Output tokens a request is expected to use, thinking included, for the budget check: a part's,
18
+ * and the overview's by length.
19
+ */
20
+ const PART_OUTPUT_ESTIMATE = 3_000;
21
+ export const OUTPUT_ESTIMATE = { brief: 3_000, standard: 5_000, detailed: 8_000 };
17
22
  /** 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,
23
+ const THEMES_ESTIMATE = 800;
24
+ /**
25
+ * The requests reading articles of `whole` tokens are expected to take: one, or parts and a
26
+ * merge; `preferences` is the tokens of the reader's preferences each request carries.
27
+ */
28
+ export function plannedRequests(partTokens, whole, options) {
29
+ const request = (input, output = OUTPUT_ESTIMATE[options.length]) => ({
30
+ input: input + options.preferences,
23
31
  cacheWrite: 0,
24
32
  cacheRead: 0,
25
- output: OUTPUT_ESTIMATE,
33
+ output,
26
34
  });
27
35
  if (!partTokens)
28
36
  return [request(whole)];
29
37
  return [
30
- ...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens)),
38
+ ...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens, PART_OUTPUT_ESTIMATE)),
31
39
  request(estimateTokens(MERGE_SYSTEM) + THEMES_ESTIMATE * partTokens.length),
32
40
  ];
33
41
  }
@@ -47,9 +55,13 @@ export function chosen(entries, settings) {
47
55
  return true;
48
56
  });
49
57
  }
50
- /** Entries grouped by feed, feeds in the order their newest entry comes. */
58
+ /**
59
+ * Entries grouped by feed, feeds in the order their newest entry comes, each entry with a ref
60
+ * (`a1`, `a2`, … in the order given), and the entry id each ref names.
61
+ */
51
62
  export function byFeed(entries) {
52
63
  const feeds = new Map();
64
+ const ids = new Map();
53
65
  for (const entry of entries) {
54
66
  if (!entry.feed)
55
67
  continue;
@@ -58,13 +70,15 @@ export function byFeed(entries) {
58
70
  feed = { feed: entry.feed.title, articles: [] };
59
71
  feeds.set(entry.feed.id, feed);
60
72
  }
61
- feed.articles.push({ title: entry.title, excerpt: entry.excerpt });
73
+ const ref = `a${String(ids.size + 1)}`;
74
+ ids.set(ref, entry.id);
75
+ feed.articles.push({ ref, title: entry.title, excerpt: entry.excerpt });
62
76
  }
63
- return [...feeds.values()];
77
+ return { feeds: [...feeds.values()], ids };
64
78
  }
65
79
  /** Tokens a text is about, rounded up: some 3 characters each. */
66
80
  export const estimateTokens = (text) => Math.ceil(text.length / 3);
67
- const articleTokens = (article) => estimateTokens(`<article><title>${article.title}</title><start>${article.excerpt ?? ''}</start>`);
81
+ const articleTokens = (article) => estimateTokens(`<article ref="${article.ref}"><title>${article.title}</title><start>${article.excerpt ?? ''}</start>`);
68
82
  /**
69
83
  * Feeds packed into parts of about `limit` tokens, each feed's articles together where they fit;
70
84
  * a feed larger than a part is split across parts.
@@ -101,22 +115,60 @@ export function partsOf(feeds, limit) {
101
115
  close();
102
116
  return parts;
103
117
  }
118
+ /**
119
+ * The reader's preferences as the requests give them: the sections, and the second system block
120
+ * of the overview's requests and of the parts'. Their instructions only when the server allows.
121
+ */
122
+ export function preferencesOf(settings, userSettings) {
123
+ const sections = sectionsOf(userSettings, DEFAULT_SECTIONS);
124
+ const instructions = settings.allowInstructions
125
+ ? userSettings.instructions.trim().slice(0, INSTRUCTIONS_LENGTH) || null
126
+ : null;
127
+ const options = {
128
+ sections,
129
+ length: userSettings.length,
130
+ lead: userSettings.lead,
131
+ instructions,
132
+ };
133
+ return {
134
+ sections,
135
+ names: sections.map((section) => section.name),
136
+ overview: preferencesText(options),
137
+ parts: preferencesText({ ...options, forParts: true }),
138
+ };
139
+ }
104
140
  /**
105
141
  * 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.
142
+ * by feed with their refs, the reader's preferences, in one request or in parts, and the
143
+ * requests' expected tokens; null with none chosen.
107
144
  */
108
- export function planOf(input, userSettings) {
145
+ export function planOf(input, settings, userSettings) {
109
146
  const entries = chosen([...input.entries, ...input.unlisted], userSettings);
110
147
  if (entries.length === 0)
111
148
  return null;
112
- const feeds = byFeed(entries);
149
+ const { feeds, ids } = byFeed(entries);
150
+ const preferences = preferencesOf(settings, userSettings);
113
151
  const total = entries.length + Math.max(0, input.more - input.unlisted.length);
114
152
  const whole = estimateTokens(OVERVIEW_SYSTEM) + articlesTokens(feeds);
115
153
  const parts = whole <= PART_TOKENS
116
154
  ? null
117
155
  : 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 };
156
+ const planned = plannedRequests(parts?.map(articlesTokens) ?? null, whole, {
157
+ preferences: estimateTokens(preferences.overview),
158
+ length: userSettings.length,
159
+ });
160
+ return { entries, feeds, ids, preferences, total, parts, planned };
161
+ }
162
+ /** The overview as the digest takes it: the lead as its overview, then its sections. */
163
+ export function additionsOf(overview, userSettings) {
164
+ return {
165
+ overview: userSettings.lead && overview.lead ? overview.lead : null,
166
+ sections: overview.sections.map((section) => ({
167
+ heading: section.heading,
168
+ list: userSettings.style === 'bullets',
169
+ items: section.points.map((point) => ({ text: point.text, entries: point.entries })),
170
+ })),
171
+ };
120
172
  }
121
173
  /**
122
174
  * What the overview of a digest is expected to cost, making no request, as plain text: how it
@@ -124,7 +176,7 @@ export function planOf(input, userSettings) {
124
176
  */
125
177
  export async function estimate(options) {
126
178
  const { settings } = options;
127
- const plan = planOf(options.input, options.userSettings);
179
+ const plan = planOf(options.input, settings, options.userSettings);
128
180
  if (!plan)
129
181
  return "None of the test digest's articles are from feeds it reads, so it would add nothing.";
130
182
  const tokens = tokensIn(plan.planned);
@@ -137,21 +189,24 @@ export async function estimate(options) {
137
189
  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
190
  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.`;
139
191
  }
192
+ const nothing = (outcome) => ({ overview: null, sections: null, outcome });
140
193
  /**
141
194
  * 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.
195
+ * request, or in parts whose themes a last request turns into the overview, within the budgets,
196
+ * as a lead and sections whose points cite entries. Whatever a request ends as (refused,
197
+ * unreadable, out of time), the digest goes out without it.
144
198
  */
145
199
  export async function compose(options) {
146
- const { client, settings, input, storage, userStorage, logger, signal } = options;
147
- const plan = planOf(input, options.userSettings);
200
+ const { client, settings, userSettings, input, storage, userStorage, logger, signal } = options;
201
+ const plan = planOf(input, settings, userSettings);
148
202
  if (!plan)
149
- return { overview: null, outcome: 'none' };
150
- const { entries, feeds, total, parts, planned } = plan;
203
+ return nothing('none');
204
+ const { entries, feeds, ids, preferences, total, parts, planned } = plan;
205
+ const { names } = preferences;
151
206
  const budgets = { instance: settings.monthlyTokens, user: settings.userMonthlyTokens };
152
207
  if ((await remaining(budgets, { instance: storage, user: userStorage }, options.now())) <
153
208
  tokensIn(planned))
154
- return { overview: null, outcome: 'over budget' };
209
+ return nothing('over budget');
155
210
  // Counts are read and written back, so parts answering together count one after another.
156
211
  let counting = Promise.resolve();
157
212
  const counted = (tokens) => {
@@ -174,7 +229,11 @@ export async function compose(options) {
174
229
  betas: [FALLBACK_BETA],
175
230
  fallbacks: 'default',
176
231
  output_config: { effort: settings.effort, format },
177
- system: [{ type: 'text', text: system, cache_control: { type: 'ephemeral' } }],
232
+ // The fixed prompt first, cached for every reader's digests; then the reader's own.
233
+ system: [
234
+ { type: 'text', text: system[0], cache_control: { type: 'ephemeral' } },
235
+ { type: 'text', text: system[1] },
236
+ ],
178
237
  messages: [{ role: 'user', content: prompt }],
179
238
  }, {
180
239
  signal: AbortSignal.any([signal, ownTime]),
@@ -200,48 +259,56 @@ export async function compose(options) {
200
259
  };
201
260
  const language = input.language;
202
261
  const frequency = input.frequency;
262
+ const read = (text) => readSections(text, { names, length: userSettings.length, ids });
203
263
  if (!parts) {
204
- const asked = await ask(OVERVIEW_SYSTEM, overviewPrompt({ language, frequency, total, feeds }), OVERVIEW_FORMAT, options.deadline);
264
+ const asked = await ask([OVERVIEW_SYSTEM, preferences.overview], overviewPrompt({ language, frequency, total, feeds }), sectionsFormat(names), options.deadline);
205
265
  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' };
266
+ return nothing(asked.outcome);
267
+ const overview = read(asked.text);
268
+ return overview
269
+ ? { ...additionsOf(overview, userSettings), outcome: 'written' }
270
+ : nothing('invalid');
209
271
  }
210
272
  const partsBy = Date.now() + Math.floor((options.deadline - Date.now()) * PARTS_SHARE);
211
273
  const found = await Promise.all(parts.map(async (part) => {
212
- const asked = await ask(PART_SYSTEM, partPrompt({ language, feeds: part }), PART_FORMAT, partsBy);
274
+ const asked = await ask([PART_SYSTEM, preferences.parts], partPrompt({ language, feeds: part }), partFormat(names), partsBy);
213
275
  if (!asked.ok)
214
276
  return asked.outcome;
215
- return readPart(asked.text) ?? 'invalid';
277
+ return readPart(asked.text, { names, ids }) ?? 'invalid';
216
278
  }));
217
279
  // 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({
280
+ const answered = parts.filter((_, index) => typeof found[index] !== 'string');
281
+ if (answered.length === 0)
282
+ return nothing(found[0]);
283
+ const asked = await ask([MERGE_SYSTEM, preferences.overview], mergePrompt({
222
284
  language,
223
285
  frequency,
224
286
  given: entries.length,
225
- read: read.length < parts.length ? articleCount(read.flat()) : entries.length,
287
+ read: answered.length < parts.length ? articleCount(answered.flat()) : entries.length,
226
288
  total,
227
289
  parts: found.filter((part) => typeof part !== 'string'),
228
- }), OVERVIEW_FORMAT, options.deadline);
290
+ }), sectionsFormat(names), options.deadline);
229
291
  if (!asked.ok)
230
- return { overview: null, outcome: asked.outcome };
231
- const overview = readOverview(asked.text);
292
+ return nothing(asked.outcome);
293
+ const overview = read(asked.text);
232
294
  if (!overview)
233
- return { overview: null, outcome: 'invalid' };
234
- if (read.length === parts.length)
235
- return { overview, outcome: 'written' };
295
+ return nothing('invalid');
296
+ const additions = additionsOf(overview, userSettings);
297
+ if (answered.length === parts.length)
298
+ return { ...additions, outcome: 'written' };
236
299
  const missed = found.filter((part) => typeof part === 'string');
237
300
  const note = missingNote({
238
- read: articleCount(read.flat()),
301
+ read: articleCount(answered.flat()),
239
302
  given: entries.length,
240
303
  parts: parts.length,
241
304
  timedOut: missed.filter((outcome) => outcome === 'timed out').length,
242
305
  failed: missed.filter((outcome) => outcome !== 'timed out').length,
243
306
  });
244
- return { overview: withNote(overview, note), outcome: 'partial' };
307
+ return {
308
+ overview: additions.overview ? withNote(additions.overview, note) : note,
309
+ sections: additions.sections,
310
+ outcome: 'partial',
311
+ };
245
312
  }
246
313
  /** What an overview written from only some parts says of the rest. */
247
314
  export function missingNote(counts) {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
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 from the titles and excerpts of every unread article the digest counts, of the
5
+ * feeds the user chooses, with the sections, length, style, and instructions the user chooses.
5
6
  */
6
7
  declare const _default: import("@newses/plugin-api").PluginDefinition<import("zod").ZodObject<{
7
8
  apiKey: import("zod").ZodString;
@@ -17,6 +18,7 @@ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zo
17
18
  }>>;
18
19
  monthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
19
20
  userMonthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
21
+ allowInstructions: import("zod").ZodDefault<import("zod").ZodBoolean>;
20
22
  }, import("zod/v4/core").$strip>, import("zod").ZodObject<{
21
23
  feedChoice: import("zod").ZodDefault<import("zod").ZodEnum<{
22
24
  all: "all";
@@ -24,5 +26,20 @@ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zo
24
26
  except: "except";
25
27
  }>>;
26
28
  feeds: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodInt>>;
29
+ sections: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
30
+ name: import("zod").ZodString;
31
+ about: import("zod").ZodDefault<import("zod").ZodString>;
32
+ }, import("zod/v4/core").$strip>>>;
33
+ length: import("zod").ZodDefault<import("zod").ZodEnum<{
34
+ brief: "brief";
35
+ standard: "standard";
36
+ detailed: "detailed";
37
+ }>>;
38
+ style: import("zod").ZodDefault<import("zod").ZodEnum<{
39
+ paragraphs: "paragraphs";
40
+ bullets: "bullets";
41
+ }>>;
42
+ lead: import("zod").ZodDefault<import("zod").ZodBoolean>;
43
+ instructions: import("zod").ZodDefault<import("zod").ZodString>;
27
44
  }, import("zod/v4/core").$strip>>;
28
45
  export default _default;